);\nfunction Lc(e7) {\n let t2 = \"[0-5]\\\\d\";\n e7.precision ? t2 = `${t2}\\\\.\\\\d{${e7.precision}}` : e7.precision == null \u0026\u0026 (t2 = `${t2}(\\\\.\\\\d+)?`);\n return `([01]\\\\d|2[0-3]):[0-5]\\\\d(:${t2})${e7.precision ? \"+\" : \"?\"}`;\n}\nfunction zc(e7) {\n return new RegExp(`^${Lc(e7)} dist/index.js - ShiboSoftwareDev/cc2340r5-reference-design - tscircuit );\n}\nfunction Bc(e7) {\n let t2 = `${kc}T${Lc(e7)}`;\n const n2 = [];\n return n2.push(e7.local ? \"Z?\" : \"Z\"), e7.offset \u0026\u0026 n2.push(\"([+-]\\\\d{2}:?\\\\d{2})\"), t2 = `${t2}(${n2.join(\"|\")})`, new RegExp(`^${t2} dist/index.js - ShiboSoftwareDev/cc2340r5-reference-design - tscircuit );\n}\nfunction Fc(e7, t2) {\n return !(t2 !== \"v4\" \u0026\u0026 t2 || !Nc.test(e7)) || !(t2 !== \"v6\" \u0026\u0026 t2 || !Tc.test(e7));\n}\nfunction jc(e7, t2) {\n if (!Pc.test(e7))\n return false;\n try {\n const [n2] = e7.split(\".\");\n if (!n2)\n return false;\n const o3 = n2.replace(/-/g, \"+\").replace(/_/g, \"/\").padEnd(n2.length + (4 - n2.length % 4) % 4, \"=\"), i3 = JSON.parse(atob(o3));\n return typeof i3 == \"object\" \u0026\u0026 i3 !== null \u0026\u0026 ((!(\"typ\" in i3) || i3?.typ === \"JWT\") \u0026\u0026 (!!i3.alg \u0026\u0026 (!t2 || i3.alg === t2)));\n } catch {\n return false;\n }\n}\nfunction $c(e7, t2) {\n return !(t2 !== \"v4\" \u0026\u0026 t2 || !Rc.test(e7)) || !(t2 !== \"v6\" \u0026\u0026 t2 || !Ec.test(e7));\n}\nvar Yc = class e7 extends bc {\n _parse(e8) {\n this._def.coerce \u0026\u0026 (e8.data = String(e8.data));\n if (this._getType(e8) !== Ga.string) {\n const t3 = this._getOrReturnCtx(e8);\n return ic(t3, { code: Za.invalid_type, expected: Ga.string, received: t3.parsedType }), cc;\n }\n const t2 = new ac;\n let n2;\n for (const o3 of this._def.checks)\n if (o3.kind === \"min\")\n e8.data.length \u003c o3.value \u0026\u0026 (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { code: Za.too_small, minimum: o3.value, type: \"string\", inclusive: true, exact: false, message: o3.message }), t2.dirty());\n else if (o3.kind === \"max\")\n e8.data.length \u003e o3.value \u0026\u0026 (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { code: Za.too_big, maximum: o3.value, type: \"string\", inclusive: true, exact: false, message: o3.message }), t2.dirty());\n else if (o3.kind === \"length\") {\n const i3 = e8.data.length \u003e o3.value, r3 = e8.data.length \u003c o3.value;\n (i3 || r3) \u0026\u0026 (n2 = this._getOrReturnCtx(e8, n2), i3 ? ic(n2, { code: Za.too_big, maximum: o3.value, type: \"string\", inclusive: true, exact: true, message: o3.message }) : r3 \u0026\u0026 ic(n2, { code: Za.too_small, minimum: o3.value, type: \"string\", inclusive: true, exact: true, message: o3.message }), t2.dirty());\n } else if (o3.kind === \"email\")\n wc.test(e8.data) || (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { validation: \"email\", code: Za.invalid_string, message: o3.message }), t2.dirty());\n else if (o3.kind === \"emoji\")\n yc || (yc = new RegExp(\"^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$\", \"u\")), yc.test(e8.data) || (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { validation: \"emoji\", code: Za.invalid_string, message: o3.message }), t2.dirty());\n else if (o3.kind === \"uuid\")\n Sc.test(e8.data) || (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { validation: \"uuid\", code: Za.invalid_string, message: o3.message }), t2.dirty());\n else if (o3.kind === \"nanoid\")\n Cc.test(e8.data) || (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { validation: \"nanoid\", code: Za.invalid_string, message: o3.message }), t2.dirty());\n else if (o3.kind === \"cuid\")\n xc.test(e8.data) || (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { validation: \"cuid\", code: Za.invalid_string, message: o3.message }), t2.dirty());\n else if (o3.kind === \"cuid2\")\n vc.test(e8.data) || (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { validation: \"cuid2\", code: Za.invalid_string, message: o3.message }), t2.dirty());\n else if (o3.kind === \"ulid\")\n Ic.test(e8.data) || (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { validation: \"ulid\", code: Za.invalid_string, message: o3.message }), t2.dirty());\n else if (o3.kind === \"url\")\n try {\n new URL(e8.data);\n } catch {\n n2 = this._getOrReturnCtx(e8, n2), ic(n2, { validation: \"url\", code: Za.invalid_string, message: o3.message }), t2.dirty();\n }\n else if (o3.kind === \"regex\") {\n o3.regex.lastIndex = 0;\n o3.regex.test(e8.data) || (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { validation: \"regex\", code: Za.invalid_string, message: o3.message }), t2.dirty());\n } else if (o3.kind === \"trim\")\n e8.data = e8.data.trim();\n else if (o3.kind === \"includes\")\n e8.data.includes(o3.value, o3.position) || (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { code: Za.invalid_string, validation: { includes: o3.value, position: o3.position }, message: o3.message }), t2.dirty());\n else if (o3.kind === \"toLowerCase\")\n e8.data = e8.data.toLowerCase();\n else if (o3.kind === \"toUpperCase\")\n e8.data = e8.data.toUpperCase();\n else if (o3.kind === \"startsWith\")\n e8.data.startsWith(o3.value) || (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { code: Za.invalid_string, validation: { startsWith: o3.value }, message: o3.message }), t2.dirty());\n else if (o3.kind === \"endsWith\")\n e8.data.endsWith(o3.value) || (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { code: Za.invalid_string, validation: { endsWith: o3.value }, message: o3.message }), t2.dirty());\n else if (o3.kind === \"datetime\") {\n Bc(o3).test(e8.data) || (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { code: Za.invalid_string, validation: \"datetime\", message: o3.message }), t2.dirty());\n } else if (o3.kind === \"date\") {\n Dc.test(e8.data) || (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { code: Za.invalid_string, validation: \"date\", message: o3.message }), t2.dirty());\n } else if (o3.kind === \"time\") {\n zc(o3).test(e8.data) || (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { code: Za.invalid_string, validation: \"time\", message: o3.message }), t2.dirty());\n } else\n o3.kind === \"duration\" ? Mc.test(e8.data) || (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { validation: \"duration\", code: Za.invalid_string, message: o3.message }), t2.dirty()) : o3.kind === \"ip\" ? Fc(e8.data, o3.version) || (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { validation: \"ip\", code: Za.invalid_string, message: o3.message }), t2.dirty()) : o3.kind === \"jwt\" ? jc(e8.data, o3.alg) || (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { validation: \"jwt\", code: Za.invalid_string, message: o3.message }), t2.dirty()) : o3.kind === \"cidr\" ? $c(e8.data, o3.version) || (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { validation: \"cidr\", code: Za.invalid_string, message: o3.message }), t2.dirty()) : o3.kind === \"base64\" ? Ac.test(e8.data) || (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { validation: \"base64\", code: Za.invalid_string, message: o3.message }), t2.dirty()) : o3.kind === \"base64url\" ? Oc.test(e8.data) || (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { validation: \"base64url\", code: Za.invalid_string, message: o3.message }), t2.dirty()) : Xa.assertNever(o3);\n return { status: t2.value, value: e8.data };\n }\n _regex(e8, t2, n2) {\n return this.refinement((t3) =\u003e e8.test(t3), { validation: t2, code: Za.invalid_string, ...rc.errToObj(n2) });\n }\n _addCheck(t2) {\n return new e7({ ...this._def, checks: [...this._def.checks, t2] });\n }\n email(e8) {\n return this._addCheck({ kind: \"email\", ...rc.errToObj(e8) });\n }\n url(e8) {\n return this._addCheck({ kind: \"url\", ...rc.errToObj(e8) });\n }\n emoji(e8) {\n return this._addCheck({ kind: \"emoji\", ...rc.errToObj(e8) });\n }\n uuid(e8) {\n return this._addCheck({ kind: \"uuid\", ...rc.errToObj(e8) });\n }\n nanoid(e8) {\n return this._addCheck({ kind: \"nanoid\", ...rc.errToObj(e8) });\n }\n cuid(e8) {\n return this._addCheck({ kind: \"cuid\", ...rc.errToObj(e8) });\n }\n cuid2(e8) {\n return this._addCheck({ kind: \"cuid2\", ...rc.errToObj(e8) });\n }\n ulid(e8) {\n return this._addCheck({ kind: \"ulid\", ...rc.errToObj(e8) });\n }\n base64(e8) {\n return this._addCheck({ kind: \"base64\", ...rc.errToObj(e8) });\n }\n base64url(e8) {\n return this._addCheck({ kind: \"base64url\", ...rc.errToObj(e8) });\n }\n jwt(e8) {\n return this._addCheck({ kind: \"jwt\", ...rc.errToObj(e8) });\n }\n ip(e8) {\n return this._addCheck({ kind: \"ip\", ...rc.errToObj(e8) });\n }\n cidr(e8) {\n return this._addCheck({ kind: \"cidr\", ...rc.errToObj(e8) });\n }\n datetime(e8) {\n return typeof e8 == \"string\" ? this._addCheck({ kind: \"datetime\", precision: null, offset: false, local: false, message: e8 }) : this._addCheck({ kind: \"datetime\", precision: e8?.precision === undefined ? null : e8?.precision, offset: e8?.offset ?? false, local: e8?.local ?? false, ...rc.errToObj(e8?.message) });\n }\n date(e8) {\n return this._addCheck({ kind: \"date\", message: e8 });\n }\n time(e8) {\n return typeof e8 == \"string\" ? this._addCheck({ kind: \"time\", precision: null, message: e8 }) : this._addCheck({ kind: \"time\", precision: e8?.precision === undefined ? null : e8?.precision, ...rc.errToObj(e8?.message) });\n }\n duration(e8) {\n return this._addCheck({ kind: \"duration\", ...rc.errToObj(e8) });\n }\n regex(e8, t2) {\n return this._addCheck({ kind: \"regex\", regex: e8, ...rc.errToObj(t2) });\n }\n includes(e8, t2) {\n return this._addCheck({ kind: \"includes\", value: e8, position: t2?.position, ...rc.errToObj(t2?.message) });\n }\n startsWith(e8, t2) {\n return this._addCheck({ kind: \"startsWith\", value: e8, ...rc.errToObj(t2) });\n }\n endsWith(e8, t2) {\n return this._addCheck({ kind: \"endsWith\", value: e8, ...rc.errToObj(t2) });\n }\n min(e8, t2) {\n return this._addCheck({ kind: \"min\", value: e8, ...rc.errToObj(t2) });\n }\n max(e8, t2) {\n return this._addCheck({ kind: \"max\", value: e8, ...rc.errToObj(t2) });\n }\n length(e8, t2) {\n return this._addCheck({ kind: \"length\", value: e8, ...rc.errToObj(t2) });\n }\n nonempty(e8) {\n return this.min(1, rc.errToObj(e8));\n }\n trim() {\n return new e7({ ...this._def, checks: [...this._def.checks, { kind: \"trim\" }] });\n }\n toLowerCase() {\n return new e7({ ...this._def, checks: [...this._def.checks, { kind: \"toLowerCase\" }] });\n }\n toUpperCase() {\n return new e7({ ...this._def, checks: [...this._def.checks, { kind: \"toUpperCase\" }] });\n }\n get isDatetime() {\n return !!this._def.checks.find((e8) =\u003e e8.kind === \"datetime\");\n }\n get isDate() {\n return !!this._def.checks.find((e8) =\u003e e8.kind === \"date\");\n }\n get isTime() {\n return !!this._def.checks.find((e8) =\u003e e8.kind === \"time\");\n }\n get isDuration() {\n return !!this._def.checks.find((e8) =\u003e e8.kind === \"duration\");\n }\n get isEmail() {\n return !!this._def.checks.find((e8) =\u003e e8.kind === \"email\");\n }\n get isURL() {\n return !!this._def.checks.find((e8) =\u003e e8.kind === \"url\");\n }\n get isEmoji() {\n return !!this._def.checks.find((e8) =\u003e e8.kind === \"emoji\");\n }\n get isUUID() {\n return !!this._def.checks.find((e8) =\u003e e8.kind === \"uuid\");\n }\n get isNANOID() {\n return !!this._def.checks.find((e8) =\u003e e8.kind === \"nanoid\");\n }\n get isCUID() {\n return !!this._def.checks.find((e8) =\u003e e8.kind === \"cuid\");\n }\n get isCUID2() {\n return !!this._def.checks.find((e8) =\u003e e8.kind === \"cuid2\");\n }\n get isULID() {\n return !!this._def.checks.find((e8) =\u003e e8.kind === \"ulid\");\n }\n get isIP() {\n return !!this._def.checks.find((e8) =\u003e e8.kind === \"ip\");\n }\n get isCIDR() {\n return !!this._def.checks.find((e8) =\u003e e8.kind === \"cidr\");\n }\n get isBase64() {\n return !!this._def.checks.find((e8) =\u003e e8.kind === \"base64\");\n }\n get isBase64url() {\n return !!this._def.checks.find((e8) =\u003e e8.kind === \"base64url\");\n }\n get minLength() {\n let e8 = null;\n for (const t2 of this._def.checks)\n t2.kind === \"min\" \u0026\u0026 (e8 === null || t2.value \u003e e8) \u0026\u0026 (e8 = t2.value);\n return e8;\n }\n get maxLength() {\n let e8 = null;\n for (const t2 of this._def.checks)\n t2.kind === \"max\" \u0026\u0026 (e8 === null || t2.value \u003c e8) \u0026\u0026 (e8 = t2.value);\n return e8;\n }\n};\nfunction Xc(e8, t2) {\n const n2 = (e8.toString().split(\".\")[1] || \"\").length, o3 = (t2.toString().split(\".\")[1] || \"\").length, i3 = n2 \u003e o3 ? n2 : o3;\n return Number.parseInt(e8.toFixed(i3).replace(\".\", \"\")) % Number.parseInt(t2.toFixed(i3).replace(\".\", \"\")) / 10 ** i3;\n}\nYc.create = (e8) =\u003e new Yc({ checks: [], typeName: Al.ZodString, coerce: e8?.coerce ?? false, ..._c(e8) });\nvar Hc = class e8 extends bc {\n constructor() {\n super(...arguments), this.min = this.gte, this.max = this.lte, this.step = this.multipleOf;\n }\n _parse(e9) {\n this._def.coerce \u0026\u0026 (e9.data = Number(e9.data));\n if (this._getType(e9) !== Ga.number) {\n const t3 = this._getOrReturnCtx(e9);\n return ic(t3, { code: Za.invalid_type, expected: Ga.number, received: t3.parsedType }), cc;\n }\n let t2;\n const n2 = new ac;\n for (const o3 of this._def.checks)\n if (o3.kind === \"int\")\n Xa.isInteger(e9.data) || (t2 = this._getOrReturnCtx(e9, t2), ic(t2, { code: Za.invalid_type, expected: \"integer\", received: \"float\", message: o3.message }), n2.dirty());\n else if (o3.kind === \"min\") {\n (o3.inclusive ? e9.data \u003c o3.value : e9.data \u003c= o3.value) \u0026\u0026 (t2 = this._getOrReturnCtx(e9, t2), ic(t2, { code: Za.too_small, minimum: o3.value, type: \"number\", inclusive: o3.inclusive, exact: false, message: o3.message }), n2.dirty());\n } else if (o3.kind === \"max\") {\n (o3.inclusive ? e9.data \u003e o3.value : e9.data \u003e= o3.value) \u0026\u0026 (t2 = this._getOrReturnCtx(e9, t2), ic(t2, { code: Za.too_big, maximum: o3.value, type: \"number\", inclusive: o3.inclusive, exact: false, message: o3.message }), n2.dirty());\n } else\n o3.kind === \"multipleOf\" ? Xc(e9.data, o3.value) !== 0 \u0026\u0026 (t2 = this._getOrReturnCtx(e9, t2), ic(t2, { code: Za.not_multiple_of, multipleOf: o3.value, message: o3.message }), n2.dirty()) : o3.kind === \"finite\" ? Number.isFinite(e9.data) || (t2 = this._getOrReturnCtx(e9, t2), ic(t2, { code: Za.not_finite, message: o3.message }), n2.dirty()) : Xa.assertNever(o3);\n return { status: n2.value, value: e9.data };\n }\n gte(e9, t2) {\n return this.setLimit(\"min\", e9, true, rc.toString(t2));\n }\n gt(e9, t2) {\n return this.setLimit(\"min\", e9, false, rc.toString(t2));\n }\n lte(e9, t2) {\n return this.setLimit(\"max\", e9, true, rc.toString(t2));\n }\n lt(e9, t2) {\n return this.setLimit(\"max\", e9, false, rc.toString(t2));\n }\n setLimit(t2, n2, o3, i3) {\n return new e8({ ...this._def, checks: [...this._def.checks, { kind: t2, value: n2, inclusive: o3, message: rc.toString(i3) }] });\n }\n _addCheck(t2) {\n return new e8({ ...this._def, checks: [...this._def.checks, t2] });\n }\n int(e9) {\n return this._addCheck({ kind: \"int\", message: rc.toString(e9) });\n }\n positive(e9) {\n return this._addCheck({ kind: \"min\", value: 0, inclusive: false, message: rc.toString(e9) });\n }\n negative(e9) {\n return this._addCheck({ kind: \"max\", value: 0, inclusive: false, message: rc.toString(e9) });\n }\n nonpositive(e9) {\n return this._addCheck({ kind: \"max\", value: 0, inclusive: true, message: rc.toString(e9) });\n }\n nonnegative(e9) {\n return this._addCheck({ kind: \"min\", value: 0, inclusive: true, message: rc.toString(e9) });\n }\n multipleOf(e9, t2) {\n return this._addCheck({ kind: \"multipleOf\", value: e9, message: rc.toString(t2) });\n }\n finite(e9) {\n return this._addCheck({ kind: \"finite\", message: rc.toString(e9) });\n }\n safe(e9) {\n return this._addCheck({ kind: \"min\", inclusive: true, value: Number.MIN_SAFE_INTEGER, message: rc.toString(e9) })._addCheck({ kind: \"max\", inclusive: true, value: Number.MAX_SAFE_INTEGER, message: rc.toString(e9) });\n }\n get minValue() {\n let e9 = null;\n for (const t2 of this._def.checks)\n t2.kind === \"min\" \u0026\u0026 (e9 === null || t2.value \u003e e9) \u0026\u0026 (e9 = t2.value);\n return e9;\n }\n get maxValue() {\n let e9 = null;\n for (const t2 of this._def.checks)\n t2.kind === \"max\" \u0026\u0026 (e9 === null || t2.value \u003c e9) \u0026\u0026 (e9 = t2.value);\n return e9;\n }\n get isInt() {\n return !!this._def.checks.find((e9) =\u003e e9.kind === \"int\" || e9.kind === \"multipleOf\" \u0026\u0026 Xa.isInteger(e9.value));\n }\n get isFinite() {\n let e9 = null, t2 = null;\n for (const n2 of this._def.checks) {\n if (n2.kind === \"finite\" || n2.kind === \"int\" || n2.kind === \"multipleOf\")\n return true;\n n2.kind === \"min\" ? (t2 === null || n2.value \u003e t2) \u0026\u0026 (t2 = n2.value) : n2.kind === \"max\" \u0026\u0026 (e9 === null || n2.value \u003c e9) \u0026\u0026 (e9 = n2.value);\n }\n return Number.isFinite(t2) \u0026\u0026 Number.isFinite(e9);\n }\n};\nHc.create = (e9) =\u003e new Hc({ checks: [], typeName: Al.ZodNumber, coerce: e9?.coerce || false, ..._c(e9) });\nvar Vc = class e9 extends bc {\n constructor() {\n super(...arguments), this.min = this.gte, this.max = this.lte;\n }\n _parse(e10) {\n if (this._def.coerce)\n try {\n e10.data = BigInt(e10.data);\n } catch {\n return this._getInvalidInput(e10);\n }\n if (this._getType(e10) !== Ga.bigint)\n return this._getInvalidInput(e10);\n let t2;\n const n2 = new ac;\n for (const o3 of this._def.checks)\n if (o3.kind === \"min\") {\n (o3.inclusive ? e10.data \u003c o3.value : e10.data \u003c= o3.value) \u0026\u0026 (t2 = this._getOrReturnCtx(e10, t2), ic(t2, { code: Za.too_small, type: \"bigint\", minimum: o3.value, inclusive: o3.inclusive, message: o3.message }), n2.dirty());\n } else if (o3.kind === \"max\") {\n (o3.inclusive ? e10.data \u003e o3.value : e10.data \u003e= o3.value) \u0026\u0026 (t2 = this._getOrReturnCtx(e10, t2), ic(t2, { code: Za.too_big, type: \"bigint\", maximum: o3.value, inclusive: o3.inclusive, message: o3.message }), n2.dirty());\n } else\n o3.kind === \"multipleOf\" ? e10.data % o3.value !== BigInt(0) \u0026\u0026 (t2 = this._getOrReturnCtx(e10, t2), ic(t2, { code: Za.not_multiple_of, multipleOf: o3.value, message: o3.message }), n2.dirty()) : Xa.assertNever(o3);\n return { status: n2.value, value: e10.data };\n }\n _getInvalidInput(e10) {\n const t2 = this._getOrReturnCtx(e10);\n return ic(t2, { code: Za.invalid_type, expected: Ga.bigint, received: t2.parsedType }), cc;\n }\n gte(e10, t2) {\n return this.setLimit(\"min\", e10, true, rc.toString(t2));\n }\n gt(e10, t2) {\n return this.setLimit(\"min\", e10, false, rc.toString(t2));\n }\n lte(e10, t2) {\n return this.setLimit(\"max\", e10, true, rc.toString(t2));\n }\n lt(e10, t2) {\n return this.setLimit(\"max\", e10, false, rc.toString(t2));\n }\n setLimit(t2, n2, o3, i3) {\n return new e9({ ...this._def, checks: [...this._def.checks, { kind: t2, value: n2, inclusive: o3, message: rc.toString(i3) }] });\n }\n _addCheck(t2) {\n return new e9({ ...this._def, checks: [...this._def.checks, t2] });\n }\n positive(e10) {\n return this._addCheck({ kind: \"min\", value: BigInt(0), inclusive: false, message: rc.toString(e10) });\n }\n negative(e10) {\n return this._addCheck({ kind: \"max\", value: BigInt(0), inclusive: false, message: rc.toString(e10) });\n }\n nonpositive(e10) {\n return this._addCheck({ kind: \"max\", value: BigInt(0), inclusive: true, message: rc.toString(e10) });\n }\n nonnegative(e10) {\n return this._addCheck({ kind: \"min\", value: BigInt(0), inclusive: true, message: rc.toString(e10) });\n }\n multipleOf(e10, t2) {\n return this._addCheck({ kind: \"multipleOf\", value: e10, message: rc.toString(t2) });\n }\n get minValue() {\n let e10 = null;\n for (const t2 of this._def.checks)\n t2.kind === \"min\" \u0026\u0026 (e10 === null || t2.value \u003e e10) \u0026\u0026 (e10 = t2.value);\n return e10;\n }\n get maxValue() {\n let e10 = null;\n for (const t2 of this._def.checks)\n t2.kind === \"max\" \u0026\u0026 (e10 === null || t2.value \u003c e10) \u0026\u0026 (e10 = t2.value);\n return e10;\n }\n};\nVc.create = (e10) =\u003e new Vc({ checks: [], typeName: Al.ZodBigInt, coerce: e10?.coerce ?? false, ..._c(e10) });\nvar Wc = class extends bc {\n _parse(e10) {\n this._def.coerce \u0026\u0026 (e10.data = Boolean(e10.data));\n if (this._getType(e10) !== Ga.boolean) {\n const t2 = this._getOrReturnCtx(e10);\n return ic(t2, { code: Za.invalid_type, expected: Ga.boolean, received: t2.parsedType }), cc;\n }\n return hc(e10.data);\n }\n};\nWc.create = (e10) =\u003e new Wc({ typeName: Al.ZodBoolean, coerce: e10?.coerce || false, ..._c(e10) });\nvar Gc = class e10 extends bc {\n _parse(e11) {\n this._def.coerce \u0026\u0026 (e11.data = new Date(e11.data));\n if (this._getType(e11) !== Ga.date) {\n const t3 = this._getOrReturnCtx(e11);\n return ic(t3, { code: Za.invalid_type, expected: Ga.date, received: t3.parsedType }), cc;\n }\n if (Number.isNaN(e11.data.getTime())) {\n return ic(this._getOrReturnCtx(e11), { code: Za.invalid_date }), cc;\n }\n const t2 = new ac;\n let n2;\n for (const o3 of this._def.checks)\n o3.kind === \"min\" ? e11.data.getTime() \u003c o3.value \u0026\u0026 (n2 = this._getOrReturnCtx(e11, n2), ic(n2, { code: Za.too_small, message: o3.message, inclusive: true, exact: false, minimum: o3.value, type: \"date\" }), t2.dirty()) : o3.kind === \"max\" ? e11.data.getTime() \u003e o3.value \u0026\u0026 (n2 = this._getOrReturnCtx(e11, n2), ic(n2, { code: Za.too_big, message: o3.message, inclusive: true, exact: false, maximum: o3.value, type: \"date\" }), t2.dirty()) : Xa.assertNever(o3);\n return { status: t2.value, value: new Date(e11.data.getTime()) };\n }\n _addCheck(t2) {\n return new e10({ ...this._def, checks: [...this._def.checks, t2] });\n }\n min(e11, t2) {\n return this._addCheck({ kind: \"min\", value: e11.getTime(), message: rc.toString(t2) });\n }\n max(e11, t2) {\n return this._addCheck({ kind: \"max\", value: e11.getTime(), message: rc.toString(t2) });\n }\n get minDate() {\n let e11 = null;\n for (const t2 of this._def.checks)\n t2.kind === \"min\" \u0026\u0026 (e11 === null || t2.value \u003e e11) \u0026\u0026 (e11 = t2.value);\n return e11 != null ? new Date(e11) : null;\n }\n get maxDate() {\n let e11 = null;\n for (const t2 of this._def.checks)\n t2.kind === \"max\" \u0026\u0026 (e11 === null || t2.value \u003c e11) \u0026\u0026 (e11 = t2.value);\n return e11 != null ? new Date(e11) : null;\n }\n};\nGc.create = (e11) =\u003e new Gc({ checks: [], coerce: e11?.coerce || false, typeName: Al.ZodDate, ..._c(e11) });\nvar Uc = class extends bc {\n _parse(e11) {\n if (this._getType(e11) !== Ga.symbol) {\n const t2 = this._getOrReturnCtx(e11);\n return ic(t2, { code: Za.invalid_type, expected: Ga.symbol, received: t2.parsedType }), cc;\n }\n return hc(e11.data);\n }\n};\nUc.create = (e11) =\u003e new Uc({ typeName: Al.ZodSymbol, ..._c(e11) });\nvar Zc = class extends bc {\n _parse(e11) {\n if (this._getType(e11) !== Ga.undefined) {\n const t2 = this._getOrReturnCtx(e11);\n return ic(t2, { code: Za.invalid_type, expected: Ga.undefined, received: t2.parsedType }), cc;\n }\n return hc(e11.data);\n }\n};\nZc.create = (e11) =\u003e new Zc({ typeName: Al.ZodUndefined, ..._c(e11) });\nvar qc = class extends bc {\n _parse(e11) {\n if (this._getType(e11) !== Ga.null) {\n const t2 = this._getOrReturnCtx(e11);\n return ic(t2, { code: Za.invalid_type, expected: Ga.null, received: t2.parsedType }), cc;\n }\n return hc(e11.data);\n }\n};\nqc.create = (e11) =\u003e new qc({ typeName: Al.ZodNull, ..._c(e11) });\nvar Jc = class extends bc {\n constructor() {\n super(...arguments), this._any = true;\n }\n _parse(e11) {\n return hc(e11.data);\n }\n};\nJc.create = (e11) =\u003e new Jc({ typeName: Al.ZodAny, ..._c(e11) });\nvar Qc = class extends bc {\n constructor() {\n super(...arguments), this._unknown = true;\n }\n _parse(e11) {\n return hc(e11.data);\n }\n};\nQc.create = (e11) =\u003e new Qc({ typeName: Al.ZodUnknown, ..._c(e11) });\nvar Kc = class extends bc {\n _parse(e11) {\n const t2 = this._getOrReturnCtx(e11);\n return ic(t2, { code: Za.invalid_type, expected: Ga.never, received: t2.parsedType }), cc;\n }\n};\nKc.create = (e11) =\u003e new Kc({ typeName: Al.ZodNever, ..._c(e11) });\nvar el = class extends bc {\n _parse(e11) {\n if (this._getType(e11) !== Ga.undefined) {\n const t2 = this._getOrReturnCtx(e11);\n return ic(t2, { code: Za.invalid_type, expected: Ga.void, received: t2.parsedType }), cc;\n }\n return hc(e11.data);\n }\n};\nel.create = (e11) =\u003e new el({ typeName: Al.ZodVoid, ..._c(e11) });\nvar tl = class e11 extends bc {\n _parse(e12) {\n const { ctx: t2, status: n2 } = this._processInputParams(e12), o3 = this._def;\n if (t2.parsedType !== Ga.array)\n return ic(t2, { code: Za.invalid_type, expected: Ga.array, received: t2.parsedType }), cc;\n if (o3.exactLength !== null) {\n const e13 = t2.data.length \u003e o3.exactLength.value, i4 = t2.data.length \u003c o3.exactLength.value;\n (e13 || i4) \u0026\u0026 (ic(t2, { code: e13 ? Za.too_big : Za.too_small, minimum: i4 ? o3.exactLength.value : undefined, maximum: e13 ? o3.exactLength.value : undefined, type: \"array\", inclusive: true, exact: true, message: o3.exactLength.message }), n2.dirty());\n }\n if (o3.minLength !== null \u0026\u0026 t2.data.length \u003c o3.minLength.value \u0026\u0026 (ic(t2, { code: Za.too_small, minimum: o3.minLength.value, type: \"array\", inclusive: true, exact: false, message: o3.minLength.message }), n2.dirty()), o3.maxLength !== null \u0026\u0026 t2.data.length \u003e o3.maxLength.value \u0026\u0026 (ic(t2, { code: Za.too_big, maximum: o3.maxLength.value, type: \"array\", inclusive: true, exact: false, message: o3.maxLength.message }), n2.dirty()), t2.common.async)\n return Promise.all([...t2.data].map((e13, n3) =\u003e o3.type._parseAsync(new gc(t2, e13, t2.path, n3)))).then((e13) =\u003e ac.mergeArray(n2, e13));\n const i3 = [...t2.data].map((e13, n3) =\u003e o3.type._parseSync(new gc(t2, e13, t2.path, n3)));\n return ac.mergeArray(n2, i3);\n }\n get element() {\n return this._def.type;\n }\n min(t2, n2) {\n return new e11({ ...this._def, minLength: { value: t2, message: rc.toString(n2) } });\n }\n max(t2, n2) {\n return new e11({ ...this._def, maxLength: { value: t2, message: rc.toString(n2) } });\n }\n length(t2, n2) {\n return new e11({ ...this._def, exactLength: { value: t2, message: rc.toString(n2) } });\n }\n nonempty(e12) {\n return this.min(1, e12);\n }\n};\nfunction nl(e12) {\n if (e12 instanceof ol) {\n const t2 = {};\n for (const n2 in e12.shape) {\n const o3 = e12.shape[n2];\n t2[n2] = vl.create(nl(o3));\n }\n return new ol({ ...e12._def, shape: () =\u003e t2 });\n }\n return e12 instanceof tl ? new tl({ ...e12._def, type: nl(e12.element) }) : e12 instanceof vl ? vl.create(nl(e12.unwrap())) : e12 instanceof Il ? Il.create(nl(e12.unwrap())) : e12 instanceof ll ? ll.create(e12.items.map((e13) =\u003e nl(e13))) : e12;\n}\ntl.create = (e12, t2) =\u003e new tl({ type: e12, minLength: null, maxLength: null, exactLength: null, typeName: Al.ZodArray, ..._c(t2) });\nvar ol = class e12 extends bc {\n constructor() {\n super(...arguments), this._cached = null, this.nonstrict = this.passthrough, this.augment = this.extend;\n }\n _getCached() {\n if (this._cached !== null)\n return this._cached;\n const e13 = this._def.shape(), t2 = Xa.objectKeys(e13);\n return this._cached = { shape: e13, keys: t2 }, this._cached;\n }\n _parse(e13) {\n if (this._getType(e13) !== Ga.object) {\n const t3 = this._getOrReturnCtx(e13);\n return ic(t3, { code: Za.invalid_type, expected: Ga.object, received: t3.parsedType }), cc;\n }\n const { status: t2, ctx: n2 } = this._processInputParams(e13), { shape: o3, keys: i3 } = this._getCached(), r3 = [];\n if (!(this._def.catchall instanceof Kc \u0026\u0026 this._def.unknownKeys === \"strip\"))\n for (const e14 in n2.data)\n i3.includes(e14) || r3.push(e14);\n const s2 = [];\n for (const e14 of i3) {\n const t3 = o3[e14], i4 = n2.data[e14];\n s2.push({ key: { status: \"valid\", value: e14 }, value: t3._parse(new gc(n2, i4, n2.path, e14)), alwaysSet: e14 in n2.data });\n }\n if (this._def.catchall instanceof Kc) {\n const e14 = this._def.unknownKeys;\n if (e14 === \"passthrough\")\n for (const e15 of r3)\n s2.push({ key: { status: \"valid\", value: e15 }, value: { status: \"valid\", value: n2.data[e15] } });\n else if (e14 === \"strict\")\n r3.length \u003e 0 \u0026\u0026 (ic(n2, { code: Za.unrecognized_keys, keys: r3 }), t2.dirty());\n else if (e14 !== \"strip\")\n throw new Error(\"Internal ZodObject error: invalid unknownKeys value.\");\n } else {\n const e14 = this._def.catchall;\n for (const t3 of r3) {\n const o4 = n2.data[t3];\n s2.push({ key: { status: \"valid\", value: t3 }, value: e14._parse(new gc(n2, o4, n2.path, t3)), alwaysSet: t3 in n2.data });\n }\n }\n return n2.common.async ? Promise.resolve().then(async () =\u003e {\n const e14 = [];\n for (const t3 of s2) {\n const n3 = await t3.key, o4 = await t3.value;\n e14.push({ key: n3, value: o4, alwaysSet: t3.alwaysSet });\n }\n return e14;\n }).then((e14) =\u003e ac.mergeObjectSync(t2, e14)) : ac.mergeObjectSync(t2, s2);\n }\n get shape() {\n return this._def.shape();\n }\n strict(t2) {\n return rc.errToObj, new e12({ ...this._def, unknownKeys: \"strict\", ...t2 !== undefined ? { errorMap: (e13, n2) =\u003e {\n const o3 = this._def.errorMap?.(e13, n2).message ?? n2.defaultError;\n return e13.code === \"unrecognized_keys\" ? { message: rc.errToObj(t2).message ?? o3 } : { message: o3 };\n } } : {} });\n }\n strip() {\n return new e12({ ...this._def, unknownKeys: \"strip\" });\n }\n passthrough() {\n return new e12({ ...this._def, unknownKeys: \"passthrough\" });\n }\n extend(t2) {\n return new e12({ ...this._def, shape: () =\u003e ({ ...this._def.shape(), ...t2 }) });\n }\n merge(t2) {\n return new e12({ unknownKeys: t2._def.unknownKeys, catchall: t2._def.catchall, shape: () =\u003e ({ ...this._def.shape(), ...t2._def.shape() }), typeName: Al.ZodObject });\n }\n setKey(e13, t2) {\n return this.augment({ [e13]: t2 });\n }\n catchall(t2) {\n return new e12({ ...this._def, catchall: t2 });\n }\n pick(t2) {\n const n2 = {};\n for (const e13 of Xa.objectKeys(t2))\n t2[e13] \u0026\u0026 this.shape[e13] \u0026\u0026 (n2[e13] = this.shape[e13]);\n return new e12({ ...this._def, shape: () =\u003e n2 });\n }\n omit(t2) {\n const n2 = {};\n for (const e13 of Xa.objectKeys(this.shape))\n t2[e13] || (n2[e13] = this.shape[e13]);\n return new e12({ ...this._def, shape: () =\u003e n2 });\n }\n deepPartial() {\n return nl(this);\n }\n partial(t2) {\n const n2 = {};\n for (const e13 of Xa.objectKeys(this.shape)) {\n const o3 = this.shape[e13];\n t2 \u0026\u0026 !t2[e13] ? n2[e13] = o3 : n2[e13] = o3.optional();\n }\n return new e12({ ...this._def, shape: () =\u003e n2 });\n }\n required(t2) {\n const n2 = {};\n for (const e13 of Xa.objectKeys(this.shape))\n if (t2 \u0026\u0026 !t2[e13])\n n2[e13] = this.shape[e13];\n else {\n let t3 = this.shape[e13];\n for (;t3 instanceof vl; )\n t3 = t3._def.innerType;\n n2[e13] = t3;\n }\n return new e12({ ...this._def, shape: () =\u003e n2 });\n }\n keyof() {\n return fl(Xa.objectKeys(this.shape));\n }\n};\nol.create = (e13, t2) =\u003e new ol({ shape: () =\u003e e13, unknownKeys: \"strip\", catchall: Kc.create(), typeName: Al.ZodObject, ..._c(t2) }), ol.strictCreate = (e13, t2) =\u003e new ol({ shape: () =\u003e e13, unknownKeys: \"strict\", catchall: Kc.create(), typeName: Al.ZodObject, ..._c(t2) }), ol.lazycreate = (e13, t2) =\u003e new ol({ shape: e13, unknownKeys: \"strip\", catchall: Kc.create(), typeName: Al.ZodObject, ..._c(t2) });\nvar il = class extends bc {\n _parse(e13) {\n const { ctx: t2 } = this._processInputParams(e13), n2 = this._def.options;\n if (t2.common.async)\n return Promise.all(n2.map(async (e14) =\u003e {\n const n3 = { ...t2, common: { ...t2.common, issues: [] }, parent: null };\n return { result: await e14._parseAsync({ data: t2.data, path: t2.path, parent: n3 }), ctx: n3 };\n })).then(function(e14) {\n for (const t3 of e14)\n if (t3.result.status === \"valid\")\n return t3.result;\n for (const n4 of e14)\n if (n4.result.status === \"dirty\")\n return t2.common.issues.push(...n4.ctx.common.issues), n4.result;\n const n3 = e14.map((e15) =\u003e new Ja(e15.ctx.common.issues));\n return ic(t2, { code: Za.invalid_union, unionErrors: n3 }), cc;\n });\n {\n let e14;\n const o3 = [];\n for (const i4 of n2) {\n const n3 = { ...t2, common: { ...t2.common, issues: [] }, parent: null }, r3 = i4._parseSync({ data: t2.data, path: t2.path, parent: n3 });\n if (r3.status === \"valid\")\n return r3;\n r3.status !== \"dirty\" || e14 || (e14 = { result: r3, ctx: n3 }), n3.common.issues.length \u0026\u0026 o3.push(n3.common.issues);\n }\n if (e14)\n return t2.common.issues.push(...e14.ctx.common.issues), e14.result;\n const i3 = o3.map((e15) =\u003e new Ja(e15));\n return ic(t2, { code: Za.invalid_union, unionErrors: i3 }), cc;\n }\n }\n get options() {\n return this._def.options;\n }\n};\nil.create = (e13, t2) =\u003e new il({ options: e13, typeName: Al.ZodUnion, ..._c(t2) });\nvar rl = (e13) =\u003e e13 instanceof ml ? rl(e13.schema) : e13 instanceof xl ? rl(e13.innerType()) : e13 instanceof gl ? [e13.value] : e13 instanceof _l ? e13.options : e13 instanceof yl ? Xa.objectValues(e13.enum) : e13 instanceof Sl ? rl(e13._def.innerType) : e13 instanceof Zc ? [undefined] : e13 instanceof qc ? [null] : e13 instanceof vl ? [undefined, ...rl(e13.unwrap())] : e13 instanceof Il ? [null, ...rl(e13.unwrap())] : e13 instanceof wl || e13 instanceof Rl ? rl(e13.unwrap()) : e13 instanceof Cl ? rl(e13._def.innerType) : [];\nvar sl = class e13 extends bc {\n _parse(e14) {\n const { ctx: t2 } = this._processInputParams(e14);\n if (t2.parsedType !== Ga.object)\n return ic(t2, { code: Za.invalid_type, expected: Ga.object, received: t2.parsedType }), cc;\n const n2 = this.discriminator, o3 = t2.data[n2], i3 = this.optionsMap.get(o3);\n return i3 ? t2.common.async ? i3._parseAsync({ data: t2.data, path: t2.path, parent: t2 }) : i3._parseSync({ data: t2.data, path: t2.path, parent: t2 }) : (ic(t2, { code: Za.invalid_union_discriminator, options: Array.from(this.optionsMap.keys()), path: [n2] }), cc);\n }\n get discriminator() {\n return this._def.discriminator;\n }\n get options() {\n return this._def.options;\n }\n get optionsMap() {\n return this._def.optionsMap;\n }\n static create(t2, n2, o3) {\n const i3 = new Map;\n for (const e14 of n2) {\n const n3 = rl(e14.shape[t2]);\n if (!n3.length)\n throw new Error(`A discriminator value for key \\`${t2}\\` could not be extracted from all schema options`);\n for (const o4 of n3) {\n if (i3.has(o4))\n throw new Error(`Discriminator property ${String(t2)} has duplicate value ${String(o4)}`);\n i3.set(o4, e14);\n }\n }\n return new e13({ typeName: Al.ZodDiscriminatedUnion, discriminator: t2, options: n2, optionsMap: i3, ..._c(o3) });\n }\n};\nfunction al(e14, t2) {\n const n2 = Ua(e14), o3 = Ua(t2);\n if (e14 === t2)\n return { valid: true, data: e14 };\n if (n2 === Ga.object \u0026\u0026 o3 === Ga.object) {\n const n3 = Xa.objectKeys(t2), o4 = Xa.objectKeys(e14).filter((e15) =\u003e n3.indexOf(e15) !== -1), i3 = { ...e14, ...t2 };\n for (const n4 of o4) {\n const o5 = al(e14[n4], t2[n4]);\n if (!o5.valid)\n return { valid: false };\n i3[n4] = o5.data;\n }\n return { valid: true, data: i3 };\n }\n if (n2 === Ga.array \u0026\u0026 o3 === Ga.array) {\n if (e14.length !== t2.length)\n return { valid: false };\n const n3 = [];\n for (let o4 = 0;o4 \u003c e14.length; o4++) {\n const i3 = al(e14[o4], t2[o4]);\n if (!i3.valid)\n return { valid: false };\n n3.push(i3.data);\n }\n return { valid: true, data: n3 };\n }\n return n2 === Ga.date \u0026\u0026 o3 === Ga.date \u0026\u0026 +e14 === +t2 ? { valid: true, data: e14 } : { valid: false };\n}\nvar cl = class extends bc {\n _parse(e14) {\n const { status: t2, ctx: n2 } = this._processInputParams(e14), o3 = (e15, o4) =\u003e {\n if (dc(e15) || dc(o4))\n return cc;\n const i3 = al(e15.value, o4.value);\n return i3.valid ? ((uc(e15) || uc(o4)) \u0026\u0026 t2.dirty(), { status: t2.value, value: i3.data }) : (ic(n2, { code: Za.invalid_intersection_types }), cc);\n };\n return n2.common.async ? Promise.all([this._def.left._parseAsync({ data: n2.data, path: n2.path, parent: n2 }), this._def.right._parseAsync({ data: n2.data, path: n2.path, parent: n2 })]).then(([e15, t3]) =\u003e o3(e15, t3)) : o3(this._def.left._parseSync({ data: n2.data, path: n2.path, parent: n2 }), this._def.right._parseSync({ data: n2.data, path: n2.path, parent: n2 }));\n }\n};\ncl.create = (e14, t2, n2) =\u003e new cl({ left: e14, right: t2, typeName: Al.ZodIntersection, ..._c(n2) });\nvar ll = class e14 extends bc {\n _parse(e15) {\n const { status: t2, ctx: n2 } = this._processInputParams(e15);\n if (n2.parsedType !== Ga.array)\n return ic(n2, { code: Za.invalid_type, expected: Ga.array, received: n2.parsedType }), cc;\n if (n2.data.length \u003c this._def.items.length)\n return ic(n2, { code: Za.too_small, minimum: this._def.items.length, inclusive: true, exact: false, type: \"array\" }), cc;\n !this._def.rest \u0026\u0026 n2.data.length \u003e this._def.items.length \u0026\u0026 (ic(n2, { code: Za.too_big, maximum: this._def.items.length, inclusive: true, exact: false, type: \"array\" }), t2.dirty());\n const o3 = [...n2.data].map((e16, t3) =\u003e {\n const o4 = this._def.items[t3] || this._def.rest;\n return o4 ? o4._parse(new gc(n2, e16, n2.path, t3)) : null;\n }).filter((e16) =\u003e !!e16);\n return n2.common.async ? Promise.all(o3).then((e16) =\u003e ac.mergeArray(t2, e16)) : ac.mergeArray(t2, o3);\n }\n get items() {\n return this._def.items;\n }\n rest(t2) {\n return new e14({ ...this._def, rest: t2 });\n }\n};\nll.create = (e15, t2) =\u003e {\n if (!Array.isArray(e15))\n throw new Error(\"You must pass an array of schemas to z.tuple([ ... ])\");\n return new ll({ items: e15, typeName: Al.ZodTuple, rest: null, ..._c(t2) });\n};\nvar hl = class e15 extends bc {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(e16) {\n const { status: t2, ctx: n2 } = this._processInputParams(e16);\n if (n2.parsedType !== Ga.object)\n return ic(n2, { code: Za.invalid_type, expected: Ga.object, received: n2.parsedType }), cc;\n const o3 = [], i3 = this._def.keyType, r3 = this._def.valueType;\n for (const e17 in n2.data)\n o3.push({ key: i3._parse(new gc(n2, e17, n2.path, e17)), value: r3._parse(new gc(n2, n2.data[e17], n2.path, e17)), alwaysSet: e17 in n2.data });\n return n2.common.async ? ac.mergeObjectAsync(t2, o3) : ac.mergeObjectSync(t2, o3);\n }\n get element() {\n return this._def.valueType;\n }\n static create(t2, n2, o3) {\n return new e15(n2 instanceof bc ? { keyType: t2, valueType: n2, typeName: Al.ZodRecord, ..._c(o3) } : { keyType: Yc.create(), valueType: t2, typeName: Al.ZodRecord, ..._c(n2) });\n }\n};\nvar dl = class extends bc {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(e16) {\n const { status: t2, ctx: n2 } = this._processInputParams(e16);\n if (n2.parsedType !== Ga.map)\n return ic(n2, { code: Za.invalid_type, expected: Ga.map, received: n2.parsedType }), cc;\n const o3 = this._def.keyType, i3 = this._def.valueType, r3 = [...n2.data.entries()].map(([e17, t3], r4) =\u003e ({ key: o3._parse(new gc(n2, e17, n2.path, [r4, \"key\"])), value: i3._parse(new gc(n2, t3, n2.path, [r4, \"value\"])) }));\n if (n2.common.async) {\n const e17 = new Map;\n return Promise.resolve().then(async () =\u003e {\n for (const n3 of r3) {\n const o4 = await n3.key, i4 = await n3.value;\n if (o4.status === \"aborted\" || i4.status === \"aborted\")\n return cc;\n o4.status !== \"dirty\" \u0026\u0026 i4.status !== \"dirty\" || t2.dirty(), e17.set(o4.value, i4.value);\n }\n return { status: t2.value, value: e17 };\n });\n }\n {\n const e17 = new Map;\n for (const n3 of r3) {\n const { key: o4, value: i4 } = n3;\n if (o4.status === \"aborted\" || i4.status === \"aborted\")\n return cc;\n o4.status !== \"dirty\" \u0026\u0026 i4.status !== \"dirty\" || t2.dirty(), e17.set(o4.value, i4.value);\n }\n return { status: t2.value, value: e17 };\n }\n }\n};\ndl.create = (e16, t2, n2) =\u003e new dl({ valueType: t2, keyType: e16, typeName: Al.ZodMap, ..._c(n2) });\nvar ul = class e16 extends bc {\n _parse(e17) {\n const { status: t2, ctx: n2 } = this._processInputParams(e17);\n if (n2.parsedType !== Ga.set)\n return ic(n2, { code: Za.invalid_type, expected: Ga.set, received: n2.parsedType }), cc;\n const o3 = this._def;\n o3.minSize !== null \u0026\u0026 n2.data.size \u003c o3.minSize.value \u0026\u0026 (ic(n2, { code: Za.too_small, minimum: o3.minSize.value, type: \"set\", inclusive: true, exact: false, message: o3.minSize.message }), t2.dirty()), o3.maxSize !== null \u0026\u0026 n2.data.size \u003e o3.maxSize.value \u0026\u0026 (ic(n2, { code: Za.too_big, maximum: o3.maxSize.value, type: \"set\", inclusive: true, exact: false, message: o3.maxSize.message }), t2.dirty());\n const i3 = this._def.valueType;\n function r3(e18) {\n const n3 = new Set;\n for (const o4 of e18) {\n if (o4.status === \"aborted\")\n return cc;\n o4.status === \"dirty\" \u0026\u0026 t2.dirty(), n3.add(o4.value);\n }\n return { status: t2.value, value: n3 };\n }\n const s2 = [...n2.data.values()].map((e18, t3) =\u003e i3._parse(new gc(n2, e18, n2.path, t3)));\n return n2.common.async ? Promise.all(s2).then((e18) =\u003e r3(e18)) : r3(s2);\n }\n min(t2, n2) {\n return new e16({ ...this._def, minSize: { value: t2, message: rc.toString(n2) } });\n }\n max(t2, n2) {\n return new e16({ ...this._def, maxSize: { value: t2, message: rc.toString(n2) } });\n }\n size(e17, t2) {\n return this.min(e17, t2).max(e17, t2);\n }\n nonempty(e17) {\n return this.min(1, e17);\n }\n};\nul.create = (e17, t2) =\u003e new ul({ valueType: e17, minSize: null, maxSize: null, typeName: Al.ZodSet, ..._c(t2) });\nvar pl = class e17 extends bc {\n constructor() {\n super(...arguments), this.validate = this.implement;\n }\n _parse(e18) {\n const { ctx: t2 } = this._processInputParams(e18);\n if (t2.parsedType !== Ga.function)\n return ic(t2, { code: Za.invalid_type, expected: Ga.function, received: t2.parsedType }), cc;\n function n2(e19, n3) {\n return nc({ data: e19, path: t2.path, errorMaps: [t2.common.contextualErrorMap, t2.schemaErrorMap, tc(), Qa].filter((e20) =\u003e !!e20), issueData: { code: Za.invalid_arguments, argumentsError: n3 } });\n }\n function o3(e19, n3) {\n return nc({ data: e19, path: t2.path, errorMaps: [t2.common.contextualErrorMap, t2.schemaErrorMap, tc(), Qa].filter((e20) =\u003e !!e20), issueData: { code: Za.invalid_return_type, returnTypeError: n3 } });\n }\n const i3 = { errorMap: t2.common.contextualErrorMap }, r3 = t2.data;\n if (this._def.returns instanceof bl) {\n const e19 = this;\n return hc(async function(...t3) {\n const s2 = new Ja([]), a3 = await e19._def.args.parseAsync(t3, i3).catch((e20) =\u003e {\n throw s2.addIssue(n2(t3, e20)), s2;\n }), c3 = await Reflect.apply(r3, this, a3);\n return await e19._def.returns._def.type.parseAsync(c3, i3).catch((e20) =\u003e {\n throw s2.addIssue(o3(c3, e20)), s2;\n });\n });\n }\n {\n const e19 = this;\n return hc(function(...t3) {\n const s2 = e19._def.args.safeParse(t3, i3);\n if (!s2.success)\n throw new Ja([n2(t3, s2.error)]);\n const a3 = Reflect.apply(r3, this, s2.data), c3 = e19._def.returns.safeParse(a3, i3);\n if (!c3.success)\n throw new Ja([o3(a3, c3.error)]);\n return c3.data;\n });\n }\n }\n parameters() {\n return this._def.args;\n }\n returnType() {\n return this._def.returns;\n }\n args(...t2) {\n return new e17({ ...this._def, args: ll.create(t2).rest(Qc.create()) });\n }\n returns(t2) {\n return new e17({ ...this._def, returns: t2 });\n }\n implement(e18) {\n return this.parse(e18);\n }\n strictImplement(e18) {\n return this.parse(e18);\n }\n static create(t2, n2, o3) {\n return new e17({ args: t2 || ll.create([]).rest(Qc.create()), returns: n2 || Qc.create(), typeName: Al.ZodFunction, ..._c(o3) });\n }\n};\nvar ml = class extends bc {\n get schema() {\n return this._def.getter();\n }\n _parse(e18) {\n const { ctx: t2 } = this._processInputParams(e18);\n return this._def.getter()._parse({ data: t2.data, path: t2.path, parent: t2 });\n }\n};\nml.create = (e18, t2) =\u003e new ml({ getter: e18, typeName: Al.ZodLazy, ..._c(t2) });\nvar gl = class extends bc {\n _parse(e18) {\n if (e18.data !== this._def.value) {\n const t2 = this._getOrReturnCtx(e18);\n return ic(t2, { received: t2.data, code: Za.invalid_literal, expected: this._def.value }), cc;\n }\n return { status: \"valid\", value: e18.data };\n }\n get value() {\n return this._def.value;\n }\n};\nfunction fl(e18, t2) {\n return new _l({ values: e18, typeName: Al.ZodEnum, ..._c(t2) });\n}\ngl.create = (e18, t2) =\u003e new gl({ value: e18, typeName: Al.ZodLiteral, ..._c(t2) });\nvar _l = class e18 extends bc {\n _parse(e19) {\n if (typeof e19.data != \"string\") {\n const t2 = this._getOrReturnCtx(e19), n2 = this._def.values;\n return ic(t2, { expected: Xa.joinValues(n2), received: t2.parsedType, code: Za.invalid_type }), cc;\n }\n if (this._cache || (this._cache = new Set(this._def.values)), !this._cache.has(e19.data)) {\n const t2 = this._getOrReturnCtx(e19), n2 = this._def.values;\n return ic(t2, { received: t2.data, code: Za.invalid_enum_value, options: n2 }), cc;\n }\n return hc(e19.data);\n }\n get options() {\n return this._def.values;\n }\n get enum() {\n const e19 = {};\n for (const t2 of this._def.values)\n e19[t2] = t2;\n return e19;\n }\n get Values() {\n const e19 = {};\n for (const t2 of this._def.values)\n e19[t2] = t2;\n return e19;\n }\n get Enum() {\n const e19 = {};\n for (const t2 of this._def.values)\n e19[t2] = t2;\n return e19;\n }\n extract(t2, n2 = this._def) {\n return e18.create(t2, { ...this._def, ...n2 });\n }\n exclude(t2, n2 = this._def) {\n return e18.create(this.options.filter((e19) =\u003e !t2.includes(e19)), { ...this._def, ...n2 });\n }\n};\n_l.create = fl;\nvar yl = class extends bc {\n _parse(e19) {\n const t2 = Xa.getValidEnumValues(this._def.values), n2 = this._getOrReturnCtx(e19);\n if (n2.parsedType !== Ga.string \u0026\u0026 n2.parsedType !== Ga.number) {\n const e20 = Xa.objectValues(t2);\n return ic(n2, { expected: Xa.joinValues(e20), received: n2.parsedType, code: Za.invalid_type }), cc;\n }\n if (this._cache || (this._cache = new Set(Xa.getValidEnumValues(this._def.values))), !this._cache.has(e19.data)) {\n const e20 = Xa.objectValues(t2);\n return ic(n2, { received: n2.data, code: Za.invalid_enum_value, options: e20 }), cc;\n }\n return hc(e19.data);\n }\n get enum() {\n return this._def.values;\n }\n};\nyl.create = (e19, t2) =\u003e new yl({ values: e19, typeName: Al.ZodNativeEnum, ..._c(t2) });\nvar bl = class extends bc {\n unwrap() {\n return this._def.type;\n }\n _parse(e19) {\n const { ctx: t2 } = this._processInputParams(e19);\n if (t2.parsedType !== Ga.promise \u0026\u0026 t2.common.async === false)\n return ic(t2, { code: Za.invalid_type, expected: Ga.promise, received: t2.parsedType }), cc;\n const n2 = t2.parsedType === Ga.promise ? t2.data : Promise.resolve(t2.data);\n return hc(n2.then((e20) =\u003e this._def.type.parseAsync(e20, { path: t2.path, errorMap: t2.common.contextualErrorMap })));\n }\n};\nbl.create = (e19, t2) =\u003e new bl({ type: e19, typeName: Al.ZodPromise, ..._c(t2) });\nvar xl = class extends bc {\n innerType() {\n return this._def.schema;\n }\n sourceType() {\n return this._def.schema._def.typeName === Al.ZodEffects ? this._def.schema.sourceType() : this._def.schema;\n }\n _parse(e19) {\n const { status: t2, ctx: n2 } = this._processInputParams(e19), o3 = this._def.effect || null, i3 = { addIssue: (e20) =\u003e {\n ic(n2, e20), e20.fatal ? t2.abort() : t2.dirty();\n }, get path() {\n return n2.path;\n } };\n if (i3.addIssue = i3.addIssue.bind(i3), o3.type === \"preprocess\") {\n const e20 = o3.transform(n2.data, i3);\n if (n2.common.async)\n return Promise.resolve(e20).then(async (e21) =\u003e {\n if (t2.value === \"aborted\")\n return cc;\n const o4 = await this._def.schema._parseAsync({ data: e21, path: n2.path, parent: n2 });\n return o4.status === \"aborted\" ? cc : o4.status === \"dirty\" || t2.value === \"dirty\" ? lc(o4.value) : o4;\n });\n {\n if (t2.value === \"aborted\")\n return cc;\n const o4 = this._def.schema._parseSync({ data: e20, path: n2.path, parent: n2 });\n return o4.status === \"aborted\" ? cc : o4.status === \"dirty\" || t2.value === \"dirty\" ? lc(o4.value) : o4;\n }\n }\n if (o3.type === \"refinement\") {\n const e20 = (e21) =\u003e {\n const t3 = o3.refinement(e21, i3);\n if (n2.common.async)\n return Promise.resolve(t3);\n if (t3 instanceof Promise)\n throw new Error(\"Async refinement encountered during synchronous parse operation. Use .parseAsync instead.\");\n return e21;\n };\n if (n2.common.async === false) {\n const o4 = this._def.schema._parseSync({ data: n2.data, path: n2.path, parent: n2 });\n return o4.status === \"aborted\" ? cc : (o4.status === \"dirty\" \u0026\u0026 t2.dirty(), e20(o4.value), { status: t2.value, value: o4.value });\n }\n return this._def.schema._parseAsync({ data: n2.data, path: n2.path, parent: n2 }).then((n3) =\u003e n3.status === \"aborted\" ? cc : (n3.status === \"dirty\" \u0026\u0026 t2.dirty(), e20(n3.value).then(() =\u003e ({ status: t2.value, value: n3.value }))));\n }\n if (o3.type === \"transform\") {\n if (n2.common.async === false) {\n const e20 = this._def.schema._parseSync({ data: n2.data, path: n2.path, parent: n2 });\n if (!pc(e20))\n return cc;\n const r3 = o3.transform(e20.value, i3);\n if (r3 instanceof Promise)\n throw new Error(\"Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.\");\n return { status: t2.value, value: r3 };\n }\n return this._def.schema._parseAsync({ data: n2.data, path: n2.path, parent: n2 }).then((e20) =\u003e pc(e20) ? Promise.resolve(o3.transform(e20.value, i3)).then((e21) =\u003e ({ status: t2.value, value: e21 })) : cc);\n }\n Xa.assertNever(o3);\n }\n};\nxl.create = (e19, t2, n2) =\u003e new xl({ schema: e19, typeName: Al.ZodEffects, effect: t2, ..._c(n2) }), xl.createWithPreprocess = (e19, t2, n2) =\u003e new xl({ schema: t2, effect: { type: \"preprocess\", transform: e19 }, typeName: Al.ZodEffects, ..._c(n2) });\nvar vl = class extends bc {\n _parse(e19) {\n return this._getType(e19) === Ga.undefined ? hc(undefined) : this._def.innerType._parse(e19);\n }\n unwrap() {\n return this._def.innerType;\n }\n};\nvl.create = (e19, t2) =\u003e new vl({ innerType: e19, typeName: Al.ZodOptional, ..._c(t2) });\nvar Il = class extends bc {\n _parse(e19) {\n return this._getType(e19) === Ga.null ? hc(null) : this._def.innerType._parse(e19);\n }\n unwrap() {\n return this._def.innerType;\n }\n};\nIl.create = (e19, t2) =\u003e new Il({ innerType: e19, typeName: Al.ZodNullable, ..._c(t2) });\nvar Sl = class extends bc {\n _parse(e19) {\n const { ctx: t2 } = this._processInputParams(e19);\n let n2 = t2.data;\n return t2.parsedType === Ga.undefined \u0026\u0026 (n2 = this._def.defaultValue()), this._def.innerType._parse({ data: n2, path: t2.path, parent: t2 });\n }\n removeDefault() {\n return this._def.innerType;\n }\n};\nSl.create = (e19, t2) =\u003e new Sl({ innerType: e19, typeName: Al.ZodDefault, defaultValue: typeof t2.default == \"function\" ? t2.default : () =\u003e t2.default, ..._c(t2) });\nvar Cl = class extends bc {\n _parse(e19) {\n const { ctx: t2 } = this._processInputParams(e19), n2 = { ...t2, common: { ...t2.common, issues: [] } }, o3 = this._def.innerType._parse({ data: n2.data, path: n2.path, parent: { ...n2 } });\n return mc(o3) ? o3.then((e20) =\u003e ({ status: \"valid\", value: e20.status === \"valid\" ? e20.value : this._def.catchValue({ get error() {\n return new Ja(n2.common.issues);\n }, input: n2.data }) })) : { status: \"valid\", value: o3.status === \"valid\" ? o3.value : this._def.catchValue({ get error() {\n return new Ja(n2.common.issues);\n }, input: n2.data }) };\n }\n removeCatch() {\n return this._def.innerType;\n }\n};\nCl.create = (e19, t2) =\u003e new Cl({ innerType: e19, typeName: Al.ZodCatch, catchValue: typeof t2.catch == \"function\" ? t2.catch : () =\u003e t2.catch, ..._c(t2) });\nvar Pl = class extends bc {\n _parse(e19) {\n if (this._getType(e19) !== Ga.nan) {\n const t2 = this._getOrReturnCtx(e19);\n return ic(t2, { code: Za.invalid_type, expected: Ga.nan, received: t2.parsedType }), cc;\n }\n return { status: \"valid\", value: e19.data };\n }\n};\nPl.create = (e19) =\u003e new Pl({ typeName: Al.ZodNaN, ..._c(e19) });\nvar Ml = Symbol(\"zod_brand\");\nvar wl = class extends bc {\n _parse(e19) {\n const { ctx: t2 } = this._processInputParams(e19), n2 = t2.data;\n return this._def.type._parse({ data: n2, path: t2.path, parent: t2 });\n }\n unwrap() {\n return this._def.type;\n }\n};\nvar Nl = class e19 extends bc {\n _parse(e20) {\n const { status: t2, ctx: n2 } = this._processInputParams(e20);\n if (n2.common.async) {\n return (async () =\u003e {\n const e21 = await this._def.in._parseAsync({ data: n2.data, path: n2.path, parent: n2 });\n return e21.status === \"aborted\" ? cc : e21.status === \"dirty\" ? (t2.dirty(), lc(e21.value)) : this._def.out._parseAsync({ data: e21.value, path: n2.path, parent: n2 });\n })();\n }\n {\n const e21 = this._def.in._parseSync({ data: n2.data, path: n2.path, parent: n2 });\n return e21.status === \"aborted\" ? cc : e21.status === \"dirty\" ? (t2.dirty(), { status: \"dirty\", value: e21.value }) : this._def.out._parseSync({ data: e21.value, path: n2.path, parent: n2 });\n }\n }\n static create(t2, n2) {\n return new e19({ in: t2, out: n2, typeName: Al.ZodPipeline });\n }\n};\nvar Rl = class extends bc {\n _parse(e20) {\n const t2 = this._def.innerType._parse(e20), n2 = (e21) =\u003e (pc(e21) \u0026\u0026 (e21.value = Object.freeze(e21.value)), e21);\n return mc(t2) ? t2.then((e21) =\u003e n2(e21)) : n2(t2);\n }\n unwrap() {\n return this._def.innerType;\n }\n};\nfunction Tl(e20, t2) {\n const n2 = typeof e20 == \"function\" ? e20(t2) : typeof e20 == \"string\" ? { message: e20 } : e20;\n return typeof n2 == \"string\" ? { message: n2 } : n2;\n}\nfunction El(e20, t2 = {}, n2) {\n return e20 ? Jc.create().superRefine((o3, i3) =\u003e {\n const r3 = e20(o3);\n if (r3 instanceof Promise)\n return r3.then((e21) =\u003e {\n if (!e21) {\n const e22 = Tl(t2, o3), r4 = e22.fatal ?? n2 ?? true;\n i3.addIssue({ code: \"custom\", ...e22, fatal: r4 });\n }\n });\n if (!r3) {\n const e21 = Tl(t2, o3), r4 = e21.fatal ?? n2 ?? true;\n i3.addIssue({ code: \"custom\", ...e21, fatal: r4 });\n }\n }) : Jc.create();\n}\nRl.create = (e20, t2) =\u003e new Rl({ innerType: e20, typeName: Al.ZodReadonly, ..._c(t2) });\nvar Al;\nvar Ol;\nvar kl = { object: ol.lazycreate };\n(Ol = Al || (Al = {})).ZodString = \"ZodString\", Ol.ZodNumber = \"ZodNumber\", Ol.ZodNaN = \"ZodNaN\", Ol.ZodBigInt = \"ZodBigInt\", Ol.ZodBoolean = \"ZodBoolean\", Ol.ZodDate = \"ZodDate\", Ol.ZodSymbol = \"ZodSymbol\", Ol.ZodUndefined = \"ZodUndefined\", Ol.ZodNull = \"ZodNull\", Ol.ZodAny = \"ZodAny\", Ol.ZodUnknown = \"ZodUnknown\", Ol.ZodNever = \"ZodNever\", Ol.ZodVoid = \"ZodVoid\", Ol.ZodArray = \"ZodArray\", Ol.ZodObject = \"ZodObject\", Ol.ZodUnion = \"ZodUnion\", Ol.ZodDiscriminatedUnion = \"ZodDiscriminatedUnion\", Ol.ZodIntersection = \"ZodIntersection\", Ol.ZodTuple = \"ZodTuple\", Ol.ZodRecord = \"ZodRecord\", Ol.ZodMap = \"ZodMap\", Ol.ZodSet = \"ZodSet\", Ol.ZodFunction = \"ZodFunction\", Ol.ZodLazy = \"ZodLazy\", Ol.ZodLiteral = \"ZodLiteral\", Ol.ZodEnum = \"ZodEnum\", Ol.ZodEffects = \"ZodEffects\", Ol.ZodNativeEnum = \"ZodNativeEnum\", Ol.ZodOptional = \"ZodOptional\", Ol.ZodNullable = \"ZodNullable\", Ol.ZodDefault = \"ZodDefault\", Ol.ZodCatch = \"ZodCatch\", Ol.ZodPromise = \"ZodPromise\", Ol.ZodBranded = \"ZodBranded\", Ol.ZodPipeline = \"ZodPipeline\", Ol.ZodReadonly = \"ZodReadonly\";\nvar Dl = (e20, t2 = { message: `Input not instance of ${e20.name}` }) =\u003e El((t3) =\u003e t3 instanceof e20, t2);\nvar Ll = Yc.create;\nvar zl = Hc.create;\nvar Bl = Pl.create;\nvar Fl = Vc.create;\nvar jl = Wc.create;\nvar $l = Gc.create;\nvar Yl = Uc.create;\nvar Xl = Zc.create;\nvar Hl = qc.create;\nvar Vl = Jc.create;\nvar Wl = Qc.create;\nvar Gl = Kc.create;\nvar Ul = el.create;\nvar Zl = tl.create;\nvar ql = ol.create;\nvar Jl = ol.strictCreate;\nvar Ql = il.create;\nvar Kl = sl.create;\nvar eh = cl.create;\nvar th = ll.create;\nvar nh = hl.create;\nvar oh = dl.create;\nvar ih = ul.create;\nvar rh = pl.create;\nvar sh = ml.create;\nvar ah = gl.create;\nvar ch = _l.create;\nvar lh = yl.create;\nvar hh = bl.create;\nvar dh = xl.create;\nvar uh = vl.create;\nvar ph = Il.create;\nvar mh = xl.createWithPreprocess;\nvar gh = Nl.create;\nvar fh = () =\u003e Ll().optional();\nvar _h = () =\u003e zl().optional();\nvar yh = () =\u003e jl().optional();\nvar bh = { string: (e20) =\u003e Yc.create({ ...e20, coerce: true }), number: (e20) =\u003e Hc.create({ ...e20, coerce: true }), boolean: (e20) =\u003e Wc.create({ ...e20, coerce: true }), bigint: (e20) =\u003e Vc.create({ ...e20, coerce: true }), date: (e20) =\u003e Gc.create({ ...e20, coerce: true }) };\nvar xh = cc;\nvar vh = { Hz: { baseUnit: \"Hz\", variants: { MHz: 1e6, kHz: 1000, Hz: 1 } }, g: { baseUnit: \"g\", variants: { kg: 1000, g: 1 } }, \"Ω\": { baseUnit: \"Ω\", variants: { \"mΩ\": 0.001, \"Ω\": 1, \"kΩ\": 1000, \"KΩ\": 1000, kohm: 1000, \"MΩ\": 1e6, \"GΩ\": 1e9, \"TΩ\": 1000000000000 } }, V: { baseUnit: \"V\", variants: { mV: 0.001, V: 1, kV: 1000, KV: 1000, MV: 1e6, GV: 1e9, TV: 1000000000000 } }, A: { baseUnit: \"A\", variants: { \"µA\": 0.000001, mA: 0.001, ma: 0.001, A: 1, kA: 1000, MA: 1e6 } }, F: { baseUnit: \"F\", variants: { pF: 0.000000000001, nF: 0.000000001, \"µF\": 0.000001, uF: 0.000001, mF: 0.001, F: 1 } }, ml: { baseUnit: \"ml\", variants: { ml: 1, mL: 1, l: 1000, L: 1000 } }, deg: { baseUnit: \"deg\", variants: { rad: 180 / Math.PI } }, ms: { baseUnit: \"ms\", variants: { fs: 0.000000000001, ps: 0.000000001, ns: 0.000001, us: 0.001, \"µs\": 0.001, ms: 1, s: 1000 } }, mm: { baseUnit: \"mm\", variants: { nm: 0.000001, \"µm\": 0.001, um: 0.001, mm: 1, cm: 10, dm: 100, m: 1000, km: 1e6, in: 25.4, ft: 304.8, IN: 25.4, FT: 304.8, yd: 914.4, mi: 1609344, mil: 0.0254 } } };\nvar Ih = new Set;\nfor (const [e20, t2] of Object.entries(vh)) {\n Ih.add(e20);\n for (const e21 of Object.keys(t2.variants))\n Ih.add(e21);\n}\nvar Sh = { tera: 1000000000000, T: 1000000000000, giga: 1e9, G: 1e9, mega: 1e6, M: 1e6, kilo: 1000, k: 1000, deci: 0.1, d: 0.1, centi: 0.01, c: 0.01, milli: 0.001, m: 0.001, micro: 0.000001, u: 0.000001, \"µ\": 0.000001, nano: 0.000000001, n: 0.000000001, pico: 0.000000000001, p: 0.000000000001 };\nfunction Ch(e20) {\n if (e20 == null)\n return { parsedUnit: null, unitOfValue: null, value: null };\n if (typeof e20 == \"string\" \u0026\u0026 e20.match(/^-?[\\d\\.]+$/))\n return { value: Number.parseFloat(e20), parsedUnit: null, unitOfValue: null };\n if (typeof e20 == \"number\")\n return { value: e20, parsedUnit: null, unitOfValue: null };\n if (typeof e20 == \"object\" \u0026\u0026 \"x\" in e20 \u0026\u0026 \"y\" in e20) {\n const { parsedUnit: t3, unitOfValue: n3 } = Ch(e20.x), o4 = Ch(e20.x), i4 = Ch(e20.y);\n return o4.value === null || i4.value === null ? { parsedUnit: null, unitOfValue: null, value: null } : { parsedUnit: t3, unitOfValue: n3, value: { x: o4.value, y: i4.value } };\n }\n const t2 = e20.toString().split(\"\").reverse().join(\"\"), n2 = t2.match(/[^\\d\\s]+/)?.[0];\n if (!n2)\n throw new Error(`Could not determine unit: \"${e20}\"`);\n const o3 = n2.split(\"\").reverse().join(\"\"), i3 = e20.slice(0, -o3.length);\n if (o3 in Sh \u0026\u0026 !Ih.has(o3)) {\n const e21 = Sh[o3];\n return { parsedUnit: null, unitOfValue: null, value: Number.parseFloat(i3) * e21 };\n }\n const { baseUnit: r3, conversionFactor: s2 } = function(e21) {\n for (const [t3, n3] of Object.entries(vh))\n if (e21 in n3.variants)\n return { baseUnit: n3.baseUnit, conversionFactor: n3.variants[e21] };\n return { baseUnit: e21, conversionFactor: 1 };\n }(o3);\n return { parsedUnit: o3, unitOfValue: r3, value: s2 * Number.parseFloat(i3) };\n}\nvar Ph = Wa.string().or(Wa.number()).transform((e20) =\u003e Ch(e20).value);\nvar Mh = Wa.string().or(Wa.number()).transform((e20) =\u003e Ch(e20).value).transform((e20) =\u003e Number.parseFloat(e20.toPrecision(12)));\nvar wh = Wa.string().or(Wa.number()).transform((e20) =\u003e Ch(e20).value);\nvar Nh = Wa.string().or(Wa.number()).transform((e20) =\u003e Ch(e20).value);\nvar Rh = Wa.string().or(Wa.number()).transform((e20) =\u003e Ch(e20).value);\nvar Th = Wa.string().or(Wa.number()).transform((e20) =\u003e Ch(e20).value);\nvar Eh = Rh;\nvar Ah = Wa.string().or(Wa.number()).transform((e20) =\u003e Ch(e20).value);\nvar Oh = Wa.string().or(Wa.number()).transform((e20) =\u003e Ch(e20).value);\nvar kh = Oh;\nvar Dh = Oh;\nvar Lh = Wa.string().datetime();\nvar zh = Wa.string().or(Wa.number()).transform((e20) =\u003e typeof e20 == \"number\" ? e20 : e20.endsWith(\"deg\") ? Number.parseFloat(e20.split(\"deg\")[0]) : e20.endsWith(\"rad\") ? 180 * Number.parseFloat(e20.split(\"rad\")[0]) / Math.PI : Number.parseFloat(e20));\nvar Bh = Wa.number().or(Wa.string().endsWith(\"mAh\")).transform((e20) =\u003e {\n if (typeof e20 == \"string\") {\n const t2 = e20.replace(\"mAh\", \"\"), n2 = Number.parseFloat(t2);\n if (Number.isNaN(n2))\n throw new Error(\"Invalid capacity\");\n return n2;\n }\n return e20;\n}).describe(\"Battery capacity in mAh\");\nvar Fh = Wa.object({ x: Eh, y: Eh });\nvar jh = Fh;\nvar $h = Wa.object({ x: Eh, y: Eh, z: Eh });\nvar Yh = $h;\nvar Xh = Wa.object({ width: Wa.number(), height: Wa.number() });\nvar Hh = (e20) =\u003e Wa.string().optional().default(() =\u003e `${e20}_${((e21) =\u003e {\n const t2 = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\";\n return Array.from({ length: e21 }, () =\u003e t2[Math.floor(62 * Math.random())]).join(\"\");\n})(10)}`);\nvar Vh = Wa.enum([\"top_left\", \"top_center\", \"top_right\", \"center_left\", \"center\", \"center_right\", \"bottom_left\", \"bottom_center\", \"bottom_right\"]);\nvar Wh = Wa.enum([\"top_silkscreen\", \"bottom_silkscreen\", \"top_copper\", \"bottom_copper\", \"top_soldermask\", \"bottom_soldermask\", \"top_fabrication_note\", \"bottom_fabrication_note\", \"top_user_note\", \"bottom_user_note\", \"top_courtyard\", \"bottom_courtyard\", \"inner1_copper\", \"inner2_copper\", \"inner3_copper\", \"inner4_copper\", \"inner5_copper\", \"inner6_copper\", \"edge_cuts\", \"drill\"]);\nvar Gh = Wa.object({ project_relative_path: Wa.string(), url: Wa.string(), mimetype: Wa.string() });\nvar Uh = Fh.extend({ rotation: zh.optional() });\nvar Zh = Wa.object({ size: Fh.optional(), thickness: Eh.optional() });\nvar qh = Wa.object({ font: Zh.optional() });\nvar Jh = Wa.object({ value: Wa.string(), at: Uh.optional(), layer: Wa.string().optional(), uuid: Wa.string().optional(), hide: Wa.boolean().optional(), effects: qh.optional() });\nvar Qh = Wa.object({ Reference: Jh.optional(), Value: Jh.optional(), Datasheet: Jh.optional(), Description: Jh.optional() });\nvar Kh = Wa.object({ through_hole: Wa.boolean().optional(), smd: Wa.boolean().optional(), exclude_from_pos_files: Wa.boolean().optional(), exclude_from_bom: Wa.boolean().optional() });\nvar ed = Wa.object({ name: Wa.string(), type: Wa.string(), shape: Wa.string().optional(), at: Uh.optional(), size: Fh.optional(), drill: Eh.optional(), layers: Wa.array(Wa.string()).optional(), removeUnusedLayers: Wa.boolean().optional(), uuid: Wa.string().optional() });\nvar td = Wa.object({ path: Wa.string(), offset: $h.optional(), scale: $h.optional(), rotate: $h.optional() });\nvar nd = Wa.object({ footprintName: Wa.string().optional(), version: Wa.union([Wa.number(), Wa.string()]).optional(), generator: Wa.string().optional(), generatorVersion: Wa.union([Wa.number(), Wa.string()]).optional(), layer: Wa.string().optional(), properties: Qh.optional(), attributes: Kh.optional(), pads: Wa.array(ed).optional(), embeddedFonts: Wa.boolean().optional(), model: td.optional() });\nvar od = Wa.object({ hide: Wa.boolean().optional() });\nvar id = Wa.object({ offset: Eh.optional(), hide: Wa.boolean().optional() });\nvar rd = Wa.object({ font: Zh.optional(), justify: Wa.union([Wa.string(), Wa.array(Wa.string())]).optional(), hide: Wa.boolean().optional() });\nvar sd = Wa.object({ value: Wa.string(), id: Wa.union([Wa.number(), Wa.string()]).optional(), at: Uh.optional(), effects: rd.optional() });\nvar ad = Wa.object({ Reference: sd.optional(), Value: sd.optional(), Footprint: sd.optional(), Datasheet: sd.optional(), Description: sd.optional(), ki_keywords: sd.optional(), ki_fp_filters: sd.optional() });\nvar cd = Wa.object({ symbolName: Wa.string().optional(), extends: Wa.string().optional(), pinNumbers: od.optional(), pinNames: id.optional(), excludeFromSim: Wa.boolean().optional(), inBom: Wa.boolean().optional(), onBoard: Wa.boolean().optional(), properties: ad.optional(), embeddedFonts: Wa.boolean().optional() });\nvar ld = Wa.object({ error_type: Wa.string(), message: Wa.string(), is_fatal: Wa.boolean().optional() });\nvar hd = Wa.enum([\"jlcpcb\", \"macrofab\", \"pcbway\", \"digikey\", \"mouser\", \"lcsc\"]);\nvar dd = Wa.object({ type: Wa.literal(\"source_component\"), ftype: Wa.string().optional(), source_component_id: Wa.string(), name: Wa.string(), manufacturer_part_number: Wa.string().optional(), supplier_part_numbers: Wa.record(hd, Wa.array(Wa.string())).optional(), display_value: Wa.string().optional(), display_name: Wa.string().optional(), are_pins_interchangeable: Wa.boolean().optional(), internally_connected_source_port_ids: Wa.array(Wa.array(Wa.string())).optional(), source_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() });\nvar ud = dd.extend({ ftype: Wa.literal(\"simple_capacitor\"), capacitance: Mh, max_voltage_rating: Nh.optional(), display_capacitance: Wa.string().optional(), max_decoupling_trace_length: Eh.optional() });\nvar pd = dd.extend({ ftype: Wa.literal(\"simple_resistor\"), resistance: Ph, display_resistance: Wa.string().optional() });\nvar md = dd.extend({ ftype: Wa.literal(\"simple_diode\") });\nvar gd = dd.extend({ ftype: Wa.literal(\"simple_fiducial\") });\nvar fd = md.extend({ ftype: Wa.literal(\"simple_led\"), color: Wa.string().optional(), wavelength: Wa.string().optional() });\nvar _d = dd.extend({ ftype: Wa.literal(\"simple_ground\") });\nvar yd = dd.extend({ ftype: Wa.literal(\"simple_chip\") });\nvar bd = dd.extend({ ftype: Wa.literal(\"simple_power_source\"), voltage: Nh });\nvar xd = dd.extend({ ftype: Wa.literal(\"simple_current_source\"), current: Ah, frequency: Th.optional(), peak_to_peak_current: Ah.optional(), wave_shape: Wa.enum([\"sine\", \"square\", \"triangle\", \"sawtooth\", \"dc\"]).optional().default(\"dc\"), phase: Wa.number().optional(), duty_cycle: Wa.number().min(0).max(1).optional() });\nvar vd = Wa.object({ must_be_connected: Wa.boolean().optional(), provides_power: Wa.boolean().optional(), requires_power: Wa.boolean().optional(), provides_ground: Wa.boolean().optional(), requires_ground: Wa.boolean().optional(), provides_voltage: Wa.union([Wa.string(), Wa.number()]).optional(), requires_voltage: Wa.union([Wa.string(), Wa.number()]).optional(), do_not_connect: Wa.boolean().optional(), include_in_board_pinout: Wa.boolean().optional(), can_use_internal_pullup: Wa.boolean().optional(), is_using_internal_pullup: Wa.boolean().optional(), needs_external_pullup: Wa.boolean().optional(), can_use_internal_pulldown: Wa.boolean().optional(), is_using_internal_pulldown: Wa.boolean().optional(), needs_external_pulldown: Wa.boolean().optional(), can_use_open_drain: Wa.boolean().optional(), is_using_open_drain: Wa.boolean().optional(), can_use_push_pull: Wa.boolean().optional(), is_using_push_pull: Wa.boolean().optional(), should_have_decoupling_capacitor: Wa.boolean().optional(), recommended_decoupling_capacitor_capacitance: Wa.union([Wa.string(), Wa.number()]).optional(), is_configured_for_i2c_sda: Wa.boolean().optional(), is_configured_for_i2c_scl: Wa.boolean().optional(), is_configured_for_spi_mosi: Wa.boolean().optional(), is_configured_for_spi_miso: Wa.boolean().optional(), is_configured_for_spi_sck: Wa.boolean().optional(), is_configured_for_spi_cs: Wa.boolean().optional(), is_configured_for_uart_tx: Wa.boolean().optional(), is_configured_for_uart_rx: Wa.boolean().optional(), supports_i2c_sda: Wa.boolean().optional(), supports_i2c_scl: Wa.boolean().optional(), supports_spi_mosi: Wa.boolean().optional(), supports_spi_miso: Wa.boolean().optional(), supports_spi_sck: Wa.boolean().optional(), supports_spi_cs: Wa.boolean().optional(), supports_uart_tx: Wa.boolean().optional(), supports_uart_rx: Wa.boolean().optional() });\nvar Id = dd.extend({ ftype: Wa.literal(\"simple_fuse\"), current_rating_amps: Wa.number().describe(\"Nominal current in amps the fuse is rated for\"), voltage_rating_volts: Wa.number().describe(\"Voltage rating in volts, e.g. ±5V would be 5\") });\nvar Sd = dd.extend({ ftype: Wa.literal(\"simple_battery\"), capacity: Bh });\nvar Cd = dd.extend({ ftype: Wa.literal(\"simple_inductor\"), inductance: wh, display_inductance: Wa.string().optional(), max_current_rating: Wa.number().optional() });\nvar Pd = dd.extend({ ftype: Wa.literal(\"simple_push_button\") });\nvar Md = dd.extend({ ftype: Wa.literal(\"simple_potentiometer\"), max_resistance: Ph, display_max_resistance: Wa.string().optional() });\nvar wd = dd.extend({ ftype: Wa.literal(\"simple_crystal\"), frequency: Wa.number().describe(\"Frequency in Hz\"), load_capacitance: Wa.number().optional().describe(\"Load capacitance in pF\"), pin_variant: Wa.enum([\"two_pin\", \"four_pin\"]).optional() });\nvar Nd = dd.extend({ ftype: Wa.literal(\"simple_pin_header\"), pin_count: Wa.number(), gender: Wa.enum([\"male\", \"female\"]).optional().default(\"male\") });\nvar Rd = dd.extend({ ftype: Wa.literal(\"simple_connector\"), standard: Wa.enum([\"usb_c\", \"m2\"]).optional() });\nvar Td = dd.extend({ ftype: Wa.literal(\"simple_pinout\") });\nvar Ed = dd.extend({ ftype: Wa.literal(\"simple_resonator\"), load_capacitance: Mh, equivalent_series_resistance: Ph.optional(), frequency: Th });\nvar Ad = dd.extend({ ftype: Wa.literal(\"simple_transistor\"), transistor_type: Wa.enum([\"npn\", \"pnp\"]) });\nvar Od = dd.extend({ ftype: Wa.literal(\"simple_test_point\"), footprint_variant: Wa.enum([\"pad\", \"through_hole\"]).optional(), pad_shape: Wa.enum([\"rect\", \"circle\"]).optional(), pad_diameter: Wa.union([Wa.number(), Wa.string()]).optional(), hole_diameter: Wa.union([Wa.number(), Wa.string()]).optional(), width: Wa.union([Wa.number(), Wa.string()]).optional(), height: Wa.union([Wa.number(), Wa.string()]).optional() });\nvar kd = dd.extend({ ftype: Wa.literal(\"simple_mosfet\"), channel_type: Wa.enum([\"n\", \"p\"]), mosfet_mode: Wa.enum([\"enhancement\", \"depletion\"]) });\nvar Dd = dd.extend({ ftype: Wa.literal(\"simple_op_amp\") });\nvar Ld = dd.extend({ ftype: Wa.literal(\"simple_switch\") });\nvar zd = Wa.object({ type: Wa.literal(\"source_project_metadata\"), name: Wa.string().optional(), software_used_string: Wa.string().optional(), project_url: Wa.string().optional(), created_at: Lh.optional() });\nvar Bd = ld.extend({ type: Wa.literal(\"source_missing_property_error\"), source_missing_property_error_id: Hh(\"source_missing_property_error\"), source_component_id: Wa.string(), property_name: Wa.string(), subcircuit_id: Wa.string().optional(), error_type: Wa.literal(\"source_missing_property_error\").default(\"source_missing_property_error\") }).describe(\"The source code is missing a property\");\nvar Fd = ld.extend({ type: Wa.literal(\"source_failed_to_create_component_error\"), source_failed_to_create_component_error_id: Hh(\"source_failed_to_create_component_error\"), error_type: Wa.literal(\"source_failed_to_create_component_error\").default(\"source_failed_to_create_component_error\"), component_name: Wa.string().optional(), subcircuit_id: Wa.string().optional(), parent_source_component_id: Wa.string().optional(), pcb_center: Wa.object({ x: Wa.number().optional(), y: Wa.number().optional() }).optional(), schematic_center: Wa.object({ x: Wa.number().optional(), y: Wa.number().optional() }).optional() }).describe(\"Error emitted when a component fails to be constructed\");\nvar jd = ld.extend({ type: Wa.literal(\"source_invalid_component_property_error\"), source_invalid_component_property_error_id: Hh(\"source_invalid_component_property_error\"), source_component_id: Wa.string(), property_name: Wa.string(), property_value: Wa.unknown().optional(), expected_format: Wa.string().optional(), subcircuit_id: Wa.string().optional(), error_type: Wa.literal(\"source_invalid_component_property_error\").default(\"source_invalid_component_property_error\") }).describe(\"The source component property is invalid\");\nvar $d = ld.extend({ type: Wa.literal(\"source_trace_not_connected_error\"), source_trace_not_connected_error_id: Hh(\"source_trace_not_connected_error\"), error_type: Wa.literal(\"source_trace_not_connected_error\").default(\"source_trace_not_connected_error\"), subcircuit_id: Wa.string().optional(), source_group_id: Wa.string().optional(), source_trace_id: Wa.string().optional(), connected_source_port_ids: Wa.array(Wa.string()).optional(), selectors_not_found: Wa.array(Wa.string()).optional() }).describe(\"Occurs when a source trace selector does not match any ports\");\nvar Yd = Wa.object({ type: Wa.literal(\"source_property_ignored_warning\"), source_property_ignored_warning_id: Hh(\"source_property_ignored_warning\"), source_component_id: Wa.string(), property_name: Wa.string(), subcircuit_id: Wa.string().optional(), error_type: Wa.literal(\"source_property_ignored_warning\").default(\"source_property_ignored_warning\"), message: Wa.string() }).describe(\"The source property was ignored\");\nvar Xd = Wa.object({ type: Wa.literal(\"source_pin_missing_trace_warning\"), source_pin_missing_trace_warning_id: Hh(\"source_pin_missing_trace_warning\"), warning_type: Wa.literal(\"source_pin_missing_trace_warning\").default(\"source_pin_missing_trace_warning\"), message: Wa.string(), source_component_id: Wa.string(), source_port_id: Wa.string(), subcircuit_id: Wa.string().optional() }).describe(\"Warning emitted when a source component pin is missing a trace connection\");\nvar Hd = Wa.object({ type: Wa.literal(\"source_missing_manufacturer_part_number_warning\"), source_missing_manufacturer_part_number_warning_id: Hh(\"source_missing_manufacturer_part_number_warning\"), warning_type: Wa.literal(\"source_missing_manufacturer_part_number_warning\").default(\"source_missing_manufacturer_part_number_warning\"), message: Wa.string(), source_component_id: Wa.string(), standard: Wa.string(), subcircuit_id: Wa.string().optional() }).describe(\"Warning emitted when a standard connector is missing manufacturer part number\");\nvar Vd = dd.extend({ ftype: Wa.literal(\"simple_voltage_probe\") });\nvar Wd = dd.extend({ ftype: Wa.literal(\"interconnect\") });\nvar Gd = ld.extend({ type: Wa.literal(\"source_i2c_misconfigured_error\"), source_i2c_misconfigured_error_id: Hh(\"source_i2c_misconfigured_error\"), error_type: Wa.literal(\"source_i2c_misconfigured_error\").default(\"source_i2c_misconfigured_error\"), source_port_ids: Wa.array(Wa.string()) }).describe(\"Error emitted when incompatible I2C pins (e.g. SDA and SCL) are connected to the same net\");\nvar Ud = dd.extend({ ftype: Wa.literal(\"simple_voltage_source\"), voltage: Nh, frequency: Th.optional(), peak_to_peak_voltage: Nh.optional(), wave_shape: Wa.enum([\"sinewave\", \"square\", \"triangle\", \"sawtooth\"]).optional(), phase: zh.optional(), duty_cycle: Wa.number().optional().describe(\"Duty cycle as a fraction (0 to 1)\") });\nvar Zd = Wa.union([pd, ud, md, gd, fd, _d, yd, bd, xd, Sd, Cd, Pd, Md, wd, Nd, Rd, Td, Ed, Ld, Ad, Od, kd, Dd, Id, Vd, Wd, Ud, zd, Bd, jd, Fd, $d, Yd, Xd, Hd, Gd]);\nvar qd = Wa.object({ type: Wa.literal(\"source_port\"), pin_number: Wa.number().optional(), port_hints: Wa.array(Wa.string()).optional(), name: Wa.string(), source_port_id: Wa.string(), source_component_id: Wa.string().optional(), source_group_id: Wa.string().optional(), most_frequently_referenced_by_name: Wa.string().optional(), subcircuit_id: Wa.string().optional(), subcircuit_connectivity_map_key: Wa.string().optional() }).merge(vd);\nvar Jd = Wa.object({ type: Wa.literal(\"source_component_internal_connection\"), source_component_internal_connection_id: Wa.string(), source_component_id: Wa.string(), source_port_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() });\nvar Qd = Wa.object({ type: Wa.literal(\"source_trace\"), source_trace_id: Wa.string(), connected_source_port_ids: Wa.array(Wa.string()), connected_source_net_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional(), subcircuit_connectivity_map_key: Wa.string().optional(), max_length: Wa.number().optional(), min_trace_thickness: Wa.number().optional(), display_name: Wa.string().optional() });\nvar Kd = Wa.object({ type: Wa.literal(\"source_group\"), source_group_id: Wa.string(), subcircuit_id: Wa.string().optional(), parent_subcircuit_id: Wa.string().optional(), parent_source_group_id: Wa.string().optional(), is_subcircuit: Wa.boolean().optional(), show_as_schematic_box: Wa.boolean().optional(), name: Wa.string().optional(), was_automatically_named: Wa.boolean().optional() });\nvar eu = Wa.object({ type: Wa.literal(\"source_net\"), source_net_id: Wa.string(), name: Wa.string(), member_source_group_ids: Wa.array(Wa.string()), is_power: Wa.boolean().optional(), is_ground: Wa.boolean().optional(), is_digital_signal: Wa.boolean().optional(), is_analog_signal: Wa.boolean().optional(), is_positive_voltage_source: Wa.boolean().optional(), trace_width: Wa.number().optional(), subcircuit_id: Wa.string().optional(), subcircuit_connectivity_map_key: Wa.string().optional() });\nvar tu = Wa.object({ type: Wa.literal(\"source_board\"), source_board_id: Wa.string(), source_group_id: Wa.string(), title: Wa.string().optional() }).describe(\"Defines a board in the source domain\");\nvar nu = ld.extend({ type: Wa.literal(\"source_ambiguous_port_reference\"), source_ambiguous_port_reference_id: Hh(\"source_ambiguous_port_reference\"), error_type: Wa.literal(\"source_ambiguous_port_reference\").default(\"source_ambiguous_port_reference\"), source_port_id: Wa.string().optional(), source_component_id: Wa.string().optional() }).describe(\"Error emitted when a port hint matches multiple non-overlapping pads, making the port reference ambiguous\");\nvar ou = Wa.object({ type: Wa.literal(\"source_pcb_ground_plane\"), source_pcb_ground_plane_id: Wa.string(), source_group_id: Wa.string(), source_net_id: Wa.string(), subcircuit_id: Wa.string().optional() }).describe(\"Defines a ground plane in the source domain\");\nvar iu = [\"top\", \"bottom\", \"inner1\", \"inner2\", \"inner3\", \"inner4\", \"inner5\", \"inner6\"];\nvar ru = Wa.enum(iu);\nvar su = ru.or(Wa.object({ name: ru })).transform((e20) =\u003e typeof e20 == \"string\" ? e20 : e20.name);\nvar au = Wa.enum([\"top\", \"bottom\"]);\nvar cu = Wa.object({ type: Wa.literal(\"source_manually_placed_via\"), source_manually_placed_via_id: Wa.string(), source_group_id: Wa.string(), source_net_id: Wa.string(), subcircuit_id: Wa.string().optional(), source_trace_id: Wa.string().optional() }).describe(\"Defines a via that is manually placed in the source domain\");\nvar lu = Wa.object({ type: Wa.literal(\"source_no_power_pin_defined_warning\"), source_no_power_pin_defined_warning_id: Hh(\"source_no_power_pin_defined_warning\"), warning_type: Wa.literal(\"source_no_power_pin_defined_warning\").default(\"source_no_power_pin_defined_warning\"), message: Wa.string(), source_component_id: Wa.string(), source_port_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe(\"Warning emitted when a chip has no source ports with requires_power=true\");\nvar hu = Wa.object({ type: Wa.literal(\"source_no_ground_pin_defined_warning\"), source_no_ground_pin_defined_warning_id: Hh(\"source_no_ground_pin_defined_warning\"), warning_type: Wa.literal(\"source_no_ground_pin_defined_warning\").default(\"source_no_ground_pin_defined_warning\"), message: Wa.string(), source_component_id: Wa.string(), source_port_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe(\"Warning emitted when a chip has no source ports marked as ground pins\");\nvar du = Wa.object({ type: Wa.literal(\"source_component_pins_underspecified_warning\"), source_component_pins_underspecified_warning_id: Hh(\"source_component_pins_underspecified_warning\"), warning_type: Wa.literal(\"source_component_pins_underspecified_warning\").default(\"source_component_pins_underspecified_warning\"), message: Wa.string(), source_component_id: Wa.string(), source_port_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe(\"Warning emitted when all ports on a source component are underspecified\");\nvar uu = ld.extend({ type: Wa.literal(\"source_pin_must_be_connected_error\"), source_pin_must_be_connected_error_id: Hh(\"source_pin_must_be_connected_error\"), error_type: Wa.literal(\"source_pin_must_be_connected_error\").default(\"source_pin_must_be_connected_error\"), source_component_id: Wa.string(), source_port_id: Wa.string(), subcircuit_id: Wa.string().optional() }).describe(\"Error emitted when a pin with mustBeConnected attribute is not connected to any trace\");\nvar pu = ld.extend({ type: Wa.literal(\"unknown_error_finding_part\"), unknown_error_finding_part_id: Hh(\"unknown_error_finding_part\"), error_type: Wa.literal(\"unknown_error_finding_part\").default(\"unknown_error_finding_part\"), source_component_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe(\"Error emitted when an unexpected error occurs while finding a part\");\nvar mu = Wa.object({ type: Wa.literal(\"schematic_box\"), schematic_component_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), width: Eh, height: Eh, is_dashed: Wa.boolean().default(false), x: Eh, y: Eh, subcircuit_id: Wa.string().optional() }).describe(\"Draws a box on the schematic\");\nvar gu = Wa.object({ type: Wa.literal(\"schematic_path\"), schematic_path_id: Hh(\"schematic_path\"), schematic_component_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), fill_color: Wa.string().optional(), is_filled: Wa.boolean().optional(), stroke_width: Eh.nullable().optional(), stroke_color: Wa.string().optional(), points: Wa.array(Fh), subcircuit_id: Wa.string().optional() });\nvar fu = Wa.record(Wa.object({ left_margin: Rh.optional(), right_margin: Rh.optional(), top_margin: Rh.optional(), bottom_margin: Rh.optional() }));\nvar _u = Wa.object({ left_size: Wa.number(), right_size: Wa.number(), top_size: Wa.number().optional(), bottom_size: Wa.number().optional() });\nvar yu = Wa.object({ left_side: Wa.object({ pins: Wa.array(Wa.number()), direction: Wa.enum([\"top-to-bottom\", \"bottom-to-top\"]).optional() }).optional(), right_side: Wa.object({ pins: Wa.array(Wa.number()), direction: Wa.enum([\"top-to-bottom\", \"bottom-to-top\"]).optional() }).optional(), top_side: Wa.object({ pins: Wa.array(Wa.number()), direction: Wa.enum([\"left-to-right\", \"right-to-left\"]).optional() }).optional(), bottom_side: Wa.object({ pins: Wa.array(Wa.number()), direction: Wa.enum([\"left-to-right\", \"right-to-left\"]).optional() }).optional() });\nvar bu = Wa.union([_u, yu]);\nvar xu = Wa.object({ type: Wa.literal(\"schematic_component\"), size: Xh, center: Fh, source_component_id: Wa.string().optional(), schematic_component_id: Wa.string(), schematic_symbol_id: Wa.string().optional(), pin_spacing: Rh.optional(), pin_styles: fu.optional(), box_width: Rh.optional(), symbol_name: Wa.string().optional(), port_arrangement: bu.optional(), port_labels: Wa.record(Wa.string()).optional(), symbol_display_value: Wa.string().optional(), subcircuit_id: Wa.string().optional(), schematic_group_id: Wa.string().optional(), is_schematic_group: Wa.boolean().optional(), source_group_id: Wa.string().optional(), is_box_with_pins: Wa.boolean().optional().default(true) });\nvar vu = Wa.object({ kicad_symbol: cd.optional() }).catchall(Wa.unknown());\nvar Iu = Wa.object({ type: Wa.literal(\"schematic_symbol\"), schematic_symbol_id: Wa.string(), name: Wa.string().optional(), metadata: vu.optional() }).describe(\"Defines a named schematic symbol that can be referenced by components.\");\nvar Su = Wa.object({ type: Wa.literal(\"schematic_line\"), schematic_line_id: Hh(\"schematic_line\"), schematic_component_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), x1: Eh, y1: Eh, x2: Eh, y2: Eh, stroke_width: Eh.nullable().optional(), color: Wa.string().default(\"#000000\"), is_dashed: Wa.boolean().default(false), subcircuit_id: Wa.string().optional() }).describe(\"Draws a styled line on the schematic\");\nvar Cu = Wa.object({ type: Wa.literal(\"schematic_rect\"), schematic_rect_id: Hh(\"schematic_rect\"), schematic_component_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), center: Fh, width: Eh, height: Eh, rotation: zh.default(0), stroke_width: Eh.nullable().optional(), color: Wa.string().default(\"#000000\"), is_filled: Wa.boolean().default(false), fill_color: Wa.string().optional(), is_dashed: Wa.boolean().default(false), subcircuit_id: Wa.string().optional() }).describe(\"Draws a styled rectangle on the schematic\");\nvar Pu = Wa.object({ type: Wa.literal(\"schematic_circle\"), schematic_circle_id: Hh(\"schematic_circle\"), schematic_component_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), center: Fh, radius: Eh, stroke_width: Eh.nullable().optional(), color: Wa.string().default(\"#000000\"), is_filled: Wa.boolean().default(false), fill_color: Wa.string().optional(), is_dashed: Wa.boolean().default(false), subcircuit_id: Wa.string().optional() }).describe(\"Draws a styled circle on the schematic\");\nvar Mu = Wa.object({ type: Wa.literal(\"schematic_arc\"), schematic_arc_id: Hh(\"schematic_arc\"), schematic_component_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), center: Fh, radius: Eh, start_angle_degrees: zh, end_angle_degrees: zh, direction: Wa.enum([\"clockwise\", \"counterclockwise\"]).default(\"counterclockwise\"), stroke_width: Eh.nullable().optional(), color: Wa.string().default(\"#000000\"), is_dashed: Wa.boolean().default(false), subcircuit_id: Wa.string().optional() }).describe(\"Draws a styled arc on the schematic\");\nvar wu = Wa.object({ type: Wa.literal(\"schematic_trace\"), schematic_trace_id: Wa.string(), source_trace_id: Wa.string().optional(), junctions: Wa.array(Wa.object({ x: Wa.number(), y: Wa.number() })), edges: Wa.array(Wa.object({ from: Wa.object({ x: Wa.number(), y: Wa.number() }), to: Wa.object({ x: Wa.number(), y: Wa.number() }), is_crossing: Wa.boolean().optional(), from_schematic_port_id: Wa.string().optional(), to_schematic_port_id: Wa.string().optional() })), subcircuit_id: Wa.string().optional(), subcircuit_connectivity_map_key: Wa.string().optional() });\nvar Nu = Wa.enum([\"center\", \"left\", \"right\", \"top\", \"bottom\"]);\nvar Ru = Wa.object({ type: Wa.literal(\"schematic_text\"), schematic_component_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), schematic_text_id: Wa.string(), text: Wa.string(), font_size: Wa.number().default(0.18), position: Wa.object({ x: Eh, y: Eh }), rotation: Wa.number().default(0), anchor: Wa.union([Nu.describe(\"legacy\"), Vh]).default(\"center\"), color: Wa.string().default(\"#000000\"), subcircuit_id: Wa.string().optional() });\nvar Tu = Wa.object({ type: Wa.literal(\"schematic_port\"), schematic_port_id: Wa.string(), source_port_id: Wa.string(), schematic_component_id: Wa.string().optional(), center: Fh, facing_direction: Wa.enum([\"up\", \"down\", \"left\", \"right\"]).optional(), distance_from_component_edge: Wa.number().optional(), side_of_component: Wa.enum([\"top\", \"bottom\", \"left\", \"right\"]).optional(), true_ccw_index: Wa.number().optional(), pin_number: Wa.number().optional(), display_pin_label: Wa.string().optional(), subcircuit_id: Wa.string().optional(), is_connected: Wa.boolean().optional(), has_input_arrow: Wa.boolean().optional(), has_output_arrow: Wa.boolean().optional(), is_drawn_with_inversion_circle: Wa.boolean().optional() }).describe(\"Defines a port on a schematic component\");\nvar Eu = Wa.object({ type: Wa.literal(\"schematic_net_label\"), schematic_net_label_id: Hh(\"schematic_net_label\"), schematic_trace_id: Wa.string().optional(), source_trace_id: Wa.string().optional(), source_net_id: Wa.string(), center: Fh, anchor_position: Fh.optional(), anchor_side: Wa.enum([\"top\", \"bottom\", \"left\", \"right\"]), text: Wa.string(), symbol_name: Wa.string().optional(), is_movable: Wa.boolean().optional(), subcircuit_id: Wa.string().optional() });\nvar Au = ld.extend({ type: Wa.literal(\"schematic_error\"), schematic_error_id: Wa.string(), error_type: Wa.literal(\"schematic_port_not_found\").default(\"schematic_port_not_found\"), subcircuit_id: Wa.string().optional() }).describe(\"Defines a schematic error on the schematic\");\nvar Ou = ld.extend({ type: Wa.literal(\"schematic_layout_error\"), schematic_layout_error_id: Hh(\"schematic_layout_error\"), error_type: Wa.literal(\"schematic_layout_error\").default(\"schematic_layout_error\"), source_group_id: Wa.string(), schematic_group_id: Wa.string(), subcircuit_id: Wa.string().optional() }).describe(\"Error emitted when schematic layout fails for a group\");\nvar ku = Wa.object({ type: Wa.literal(\"schematic_debug_object\"), label: Wa.string().optional(), subcircuit_id: Wa.string().optional() });\nvar Du = ku.extend({ shape: Wa.literal(\"rect\"), center: Fh, size: Xh });\nvar Lu = ku.extend({ shape: Wa.literal(\"line\"), start: Fh, end: Fh });\nvar zu = ku.extend({ shape: Wa.literal(\"point\"), center: Fh });\nvar Bu = Wa.discriminatedUnion(\"shape\", [Du, Lu, zu]);\nvar Fu = Wa.object({ type: Wa.literal(\"schematic_voltage_probe\"), schematic_voltage_probe_id: Wa.string(), source_component_id: Wa.string().optional(), name: Wa.string().optional(), position: Fh, schematic_trace_id: Wa.string(), voltage: Nh.optional(), subcircuit_id: Wa.string().optional(), color: Wa.string().optional(), label_alignment: Vh.optional() }).describe(\"Defines a voltage probe measurement point on a schematic trace\");\nvar ju = Wa.object({ type: Wa.literal(\"schematic_manual_edit_conflict_warning\"), schematic_manual_edit_conflict_warning_id: Hh(\"schematic_manual_edit_conflict_warning\"), warning_type: Wa.literal(\"schematic_manual_edit_conflict_warning\").default(\"schematic_manual_edit_conflict_warning\"), message: Wa.string(), schematic_component_id: Wa.string(), schematic_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), source_component_id: Wa.string() }).describe(\"Warning emitted when a component has both manual placement and explicit schX/schY coordinates\");\nvar $u = Wa.object({ type: Wa.literal(\"schematic_group\"), schematic_group_id: Hh(\"schematic_group\"), source_group_id: Wa.string(), is_subcircuit: Wa.boolean().optional(), subcircuit_id: Wa.string().optional(), width: Rh, height: Rh, center: Fh, schematic_component_ids: Wa.array(Wa.string()), show_as_schematic_box: Wa.boolean().optional(), name: Wa.string().optional(), description: Wa.string().optional() }).describe(\"Defines a group of components on the schematic\");\nvar Yu = Wa.object({ type: Wa.literal(\"schematic_table\"), schematic_table_id: Hh(\"schematic_table\"), anchor_position: Fh, column_widths: Wa.array(Eh), row_heights: Wa.array(Eh), cell_padding: Eh.optional(), border_width: Eh.optional(), subcircuit_id: Wa.string().optional(), schematic_component_id: Wa.string().optional(), anchor: Vh.optional() }).describe(\"Defines a table on the schematic\");\nvar Xu = Wa.object({ type: Wa.literal(\"schematic_table_cell\"), schematic_table_cell_id: Hh(\"schematic_table_cell\"), schematic_table_id: Wa.string(), start_row_index: Wa.number(), end_row_index: Wa.number(), start_column_index: Wa.number(), end_column_index: Wa.number(), text: Wa.string().optional(), center: Fh, width: Eh, height: Eh, horizontal_align: Wa.enum([\"left\", \"center\", \"right\"]).optional(), vertical_align: Wa.enum([\"top\", \"middle\", \"bottom\"]).optional(), font_size: Eh.optional(), subcircuit_id: Wa.string().optional() }).describe(\"Defines a cell within a schematic_table\");\nvar Hu = Wa.object({ type: Wa.literal(\"schematic_sheet\"), schematic_sheet_id: Hh(\"schematic_sheet\"), name: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe(\"Defines a schematic sheet or page that components can be placed on\");\nvar Vu = Wa.object({ x: Eh, y: Eh, bulge: Wa.number().optional() });\nvar Wu = Wa.object({ vertices: Wa.array(Vu) });\nvar Gu = Wa.object({ outer_ring: Wu, inner_rings: Wa.array(Wu).default([]) });\nvar Uu = Wa.object({ x: Eh, y: Eh, via: Wa.boolean().optional(), via_to_layer: su.optional() });\nvar Zu = Wa.array(Uu);\nvar qu = Wa.object({ x: Eh, y: Eh, via: Wa.boolean().optional(), to_layer: su.optional(), trace_width: Eh.optional() });\nvar Ju = Wa.object({ min_trace_width: Rh.optional(), min_board_edge_clearance: Rh.optional(), min_via_hole_edge_to_via_hole_edge_clearance: Rh.optional(), min_plated_hole_drill_edge_to_drill_edge_clearance: Rh.optional(), min_trace_to_pad_edge_clearance: Rh.optional(), min_pad_edge_to_pad_edge_clearance: Rh.optional(), min_same_net_trace_edge_to_trace_edge_clearance: Rh.optional(), min_different_net_trace_edge_to_trace_edge_clearance: Rh.optional(), min_via_hole_diameter: Rh.optional(), min_via_pad_diameter: Rh.optional() });\nvar Qu = Wa.object({ type: Wa.literal(\"pcb_component\"), pcb_component_id: Hh(\"pcb_component\"), source_component_id: Wa.string(), center: Fh, layer: su, rotation: zh, display_offset_x: Wa.string().optional().describe(\"How to display the x offset for this part, usually corresponding with how the user specified it\"), display_offset_y: Wa.string().optional().describe(\"How to display the y offset for this part, usually corresponding with how the user specified it\"), width: Rh, height: Rh, do_not_place: Wa.boolean().optional(), is_allowed_to_be_off_board: Wa.boolean().optional(), subcircuit_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), position_mode: Wa.enum([\"packed\", \"relative_to_group_anchor\", \"relative_to_another_component\", \"none\"]).optional(), anchor_position: Fh.optional(), anchor_alignment: Vh.optional(), positioned_relative_to_pcb_group_id: Wa.string().optional(), positioned_relative_to_pcb_board_id: Wa.string().optional(), cable_insertion_center: Fh.optional(), insertion_direction: Wa.enum([\"from_above\", \"from_left\", \"from_right\", \"from_front\", \"from_back\"]).optional(), metadata: Wa.object({ kicad_footprint: nd.optional() }).optional(), obstructs_within_bounds: Wa.boolean().default(true).describe(\"Does this component take up all the space within its bounds on a layer. This is generally true except for when separated pin headers are being represented by a single component (in which case, chips can be placed between the pin headers) or for tall modules where chips fit underneath\") }).describe(\"Defines a component on the PCB\");\nvar Ku = Wa.object({ type: Wa.literal(\"pcb_hole\"), pcb_hole_id: Hh(\"pcb_hole\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), pcb_component_id: Wa.string().optional(), hole_shape: Wa.literal(\"circle\"), hole_diameter: Wa.number(), x: Eh, y: Eh, is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });\nvar ep = Ku.describe(\"Defines a circular hole on the PCB\");\nvar tp = Wa.object({ type: Wa.literal(\"pcb_hole\"), pcb_hole_id: Hh(\"pcb_hole\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), pcb_component_id: Wa.string().optional(), hole_shape: Wa.literal(\"rect\"), hole_width: Wa.number(), hole_height: Wa.number(), x: Eh, y: Eh, is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });\nvar np = tp.describe(\"Defines a rectangular (square-capable) hole on the PCB. Use equal width/height for square.\");\nvar op = Wa.object({ type: Wa.literal(\"pcb_hole\"), pcb_hole_id: Hh(\"pcb_hole\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), pcb_component_id: Wa.string().optional(), hole_shape: Wa.enum([\"circle\", \"square\"]), hole_diameter: Wa.number(), x: Eh, y: Eh, is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });\nvar ip = op.describe(\"Defines a circular or square hole on the PCB\");\nvar rp = Wa.object({ type: Wa.literal(\"pcb_hole\"), pcb_hole_id: Hh(\"pcb_hole\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), pcb_component_id: Wa.string().optional(), hole_shape: Wa.literal(\"oval\"), hole_width: Wa.number(), hole_height: Wa.number(), x: Eh, y: Eh, is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });\nvar sp = rp.describe(\"Defines an oval hole on the PCB\");\nvar ap = Wa.object({ type: Wa.literal(\"pcb_hole\"), pcb_hole_id: Hh(\"pcb_hole\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), pcb_component_id: Wa.string().optional(), hole_shape: Wa.literal(\"pill\"), hole_width: Wa.number(), hole_height: Wa.number(), x: Eh, y: Eh, is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });\nvar cp = ap.describe(\"Defines a pill-shaped hole on the PCB\");\nvar lp = Wa.object({ type: Wa.literal(\"pcb_hole\"), pcb_hole_id: Hh(\"pcb_hole\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), pcb_component_id: Wa.string().optional(), hole_shape: Wa.literal(\"rotated_pill\"), hole_width: Wa.number(), hole_height: Wa.number(), x: Eh, y: Eh, ccw_rotation: zh, is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });\nvar hp = lp.describe(\"Defines a rotated pill-shaped hole on the PCB\");\nvar dp = op.or(rp).or(ap).or(lp).or(Ku).or(tp);\nvar up = Wa.object({ type: Wa.literal(\"pcb_plated_hole\"), shape: Wa.literal(\"circle\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), outer_diameter: Wa.number(), hole_diameter: Wa.number(), is_covered_with_solder_mask: Wa.boolean().optional(), x: Eh, y: Eh, layers: Wa.array(su), port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), pcb_plated_hole_id: Hh(\"pcb_plated_hole\"), soldermask_margin: Wa.number().optional() });\nvar pp = Wa.object({ type: Wa.literal(\"pcb_plated_hole\"), shape: Wa.enum([\"oval\", \"pill\"]), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), outer_width: Wa.number(), outer_height: Wa.number(), hole_width: Wa.number(), hole_height: Wa.number(), is_covered_with_solder_mask: Wa.boolean().optional(), x: Eh, y: Eh, ccw_rotation: zh, layers: Wa.array(su), port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), pcb_plated_hole_id: Hh(\"pcb_plated_hole\"), soldermask_margin: Wa.number().optional() });\nvar mp = Wa.object({ type: Wa.literal(\"pcb_plated_hole\"), shape: Wa.literal(\"circular_hole_with_rect_pad\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), hole_shape: Wa.literal(\"circle\"), pad_shape: Wa.literal(\"rect\"), hole_diameter: Wa.number(), rect_pad_width: Wa.number(), rect_pad_height: Wa.number(), rect_border_radius: Wa.number().optional(), hole_offset_x: Eh.default(0), hole_offset_y: Eh.default(0), is_covered_with_solder_mask: Wa.boolean().optional(), x: Eh, y: Eh, layers: Wa.array(su), port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), pcb_plated_hole_id: Hh(\"pcb_plated_hole\"), soldermask_margin: Wa.number().optional(), rect_ccw_rotation: zh.optional() });\nvar gp = Wa.object({ type: Wa.literal(\"pcb_plated_hole\"), shape: Wa.literal(\"pill_hole_with_rect_pad\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), hole_shape: Wa.literal(\"pill\"), pad_shape: Wa.literal(\"rect\"), hole_width: Wa.number(), hole_height: Wa.number(), rect_pad_width: Wa.number(), rect_pad_height: Wa.number(), rect_border_radius: Wa.number().optional(), hole_offset_x: Eh.default(0), hole_offset_y: Eh.default(0), is_covered_with_solder_mask: Wa.boolean().optional(), x: Eh, y: Eh, layers: Wa.array(su), port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), pcb_plated_hole_id: Hh(\"pcb_plated_hole\"), soldermask_margin: Wa.number().optional() });\nvar fp = Wa.object({ type: Wa.literal(\"pcb_plated_hole\"), shape: Wa.literal(\"rotated_pill_hole_with_rect_pad\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), hole_shape: Wa.literal(\"rotated_pill\"), pad_shape: Wa.literal(\"rect\"), hole_width: Wa.number(), hole_height: Wa.number(), hole_ccw_rotation: zh, rect_pad_width: Wa.number(), rect_pad_height: Wa.number(), rect_border_radius: Wa.number().optional(), rect_ccw_rotation: zh, hole_offset_x: Eh.default(0), hole_offset_y: Eh.default(0), is_covered_with_solder_mask: Wa.boolean().optional(), x: Eh, y: Eh, layers: Wa.array(su), port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), pcb_plated_hole_id: Hh(\"pcb_plated_hole\"), soldermask_margin: Wa.number().optional() });\nvar _p = Wa.object({ type: Wa.literal(\"pcb_plated_hole\"), shape: Wa.literal(\"hole_with_polygon_pad\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), hole_shape: Wa.enum([\"circle\", \"oval\", \"pill\", \"rotated_pill\"]), hole_diameter: Wa.number().optional(), hole_width: Wa.number().optional(), hole_height: Wa.number().optional(), pad_outline: Wa.array(Wa.object({ x: Eh, y: Eh })).min(3), hole_offset_x: Eh.default(0), hole_offset_y: Eh.default(0), is_covered_with_solder_mask: Wa.boolean().optional(), x: Eh, y: Eh, layers: Wa.array(su), port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), pcb_plated_hole_id: Hh(\"pcb_plated_hole\"), soldermask_margin: Wa.number().optional(), ccw_rotation: zh.optional() });\nvar yp = Wa.union([up, pp, mp, gp, fp, _p]);\nvar bp = Wa.object({ type: Wa.literal(\"pcb_port\"), pcb_port_id: Hh(\"pcb_port\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), source_port_id: Wa.string(), pcb_component_id: Wa.string().optional(), x: Eh, y: Eh, layers: Wa.array(su), is_board_pinout: Wa.boolean().optional() }).describe(\"Defines a port on the PCB\");\nvar xp = Wa.object({ type: Wa.literal(\"pcb_smtpad\"), shape: Wa.literal(\"circle\"), pcb_smtpad_id: Hh(\"pcb_smtpad\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: Eh, y: Eh, radius: Wa.number(), layer: su, port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });\nvar vp = Wa.object({ type: Wa.literal(\"pcb_smtpad\"), shape: Wa.literal(\"rect\"), pcb_smtpad_id: Hh(\"pcb_smtpad\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: Eh, y: Eh, width: Wa.number(), height: Wa.number(), rect_border_radius: Wa.number().optional(), corner_radius: Wa.number().optional(), layer: su, port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional(), soldermask_margin_left: Wa.number().optional(), soldermask_margin_top: Wa.number().optional(), soldermask_margin_right: Wa.number().optional(), soldermask_margin_bottom: Wa.number().optional() });\nvar Ip = Wa.object({ type: Wa.literal(\"pcb_smtpad\"), shape: Wa.literal(\"rotated_rect\"), pcb_smtpad_id: Hh(\"pcb_smtpad\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: Eh, y: Eh, width: Wa.number(), height: Wa.number(), rect_border_radius: Wa.number().optional(), corner_radius: Wa.number().optional(), ccw_rotation: zh, layer: su, port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional(), soldermask_margin_left: Wa.number().optional(), soldermask_margin_top: Wa.number().optional(), soldermask_margin_right: Wa.number().optional(), soldermask_margin_bottom: Wa.number().optional() });\nvar Sp = Wa.object({ type: Wa.literal(\"pcb_smtpad\"), shape: Wa.literal(\"pill\"), pcb_smtpad_id: Hh(\"pcb_smtpad\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: Eh, y: Eh, width: Wa.number(), height: Wa.number(), radius: Wa.number(), layer: su, port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });\nvar Cp = Wa.object({ type: Wa.literal(\"pcb_smtpad\"), shape: Wa.literal(\"rotated_pill\"), pcb_smtpad_id: Hh(\"pcb_smtpad\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: Eh, y: Eh, width: Wa.number(), height: Wa.number(), radius: Wa.number(), ccw_rotation: zh, layer: su, port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });\nvar Pp = Wa.object({ type: Wa.literal(\"pcb_smtpad\"), shape: Wa.literal(\"polygon\"), pcb_smtpad_id: Hh(\"pcb_smtpad\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), points: Wa.array(Fh), layer: su, port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });\nvar Mp = Wa.discriminatedUnion(\"shape\", [xp, vp, Ip, Cp, Sp, Pp]).describe(\"Defines an SMT pad on the PCB\");\nvar wp = Wa.object({ type: Wa.literal(\"pcb_solder_paste\"), shape: Wa.literal(\"circle\"), pcb_solder_paste_id: Hh(\"pcb_solder_paste\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: Eh, y: Eh, radius: Wa.number(), layer: su, pcb_component_id: Wa.string().optional(), pcb_smtpad_id: Wa.string().optional() });\nvar Np = Wa.object({ type: Wa.literal(\"pcb_solder_paste\"), shape: Wa.literal(\"rect\"), pcb_solder_paste_id: Hh(\"pcb_solder_paste\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: Eh, y: Eh, width: Wa.number(), height: Wa.number(), layer: su, pcb_component_id: Wa.string().optional(), pcb_smtpad_id: Wa.string().optional() });\nvar Rp = Wa.object({ type: Wa.literal(\"pcb_solder_paste\"), shape: Wa.literal(\"pill\"), pcb_solder_paste_id: Hh(\"pcb_solder_paste\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: Eh, y: Eh, width: Wa.number(), height: Wa.number(), radius: Wa.number(), layer: su, pcb_component_id: Wa.string().optional(), pcb_smtpad_id: Wa.string().optional() });\nvar Tp = Wa.object({ type: Wa.literal(\"pcb_solder_paste\"), shape: Wa.literal(\"rotated_rect\"), pcb_solder_paste_id: Hh(\"pcb_solder_paste\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: Eh, y: Eh, width: Wa.number(), height: Wa.number(), ccw_rotation: Eh, layer: su, pcb_component_id: Wa.string().optional(), pcb_smtpad_id: Wa.string().optional() });\nvar Ep = Wa.object({ type: Wa.literal(\"pcb_solder_paste\"), shape: Wa.literal(\"oval\"), pcb_solder_paste_id: Hh(\"pcb_solder_paste\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: Eh, y: Eh, width: Wa.number(), height: Wa.number(), layer: su, pcb_component_id: Wa.string().optional(), pcb_smtpad_id: Wa.string().optional() });\nvar Ap = Wa.union([wp, Np, Rp, Tp, Ep]).describe(\"Defines solderpaste on the PCB\");\nvar Op = Wa.object({ type: Wa.literal(\"pcb_text\"), pcb_text_id: Hh(\"pcb_text\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), text: Wa.string(), center: Fh, layer: su, width: Rh, height: Rh, lines: Wa.number(), align: Wa.enum([\"bottom-left\"]) }).describe(\"Defines text on the PCB\");\nvar kp = Wa.object({ route_type: Wa.literal(\"wire\"), x: Eh, y: Eh, width: Eh, copper_pour_id: Wa.string().optional(), is_inside_copper_pour: Wa.boolean().optional(), start_pcb_port_id: Wa.string().optional(), end_pcb_port_id: Wa.string().optional(), layer: su });\nvar Dp = Wa.object({ route_type: Wa.literal(\"via\"), x: Eh, y: Eh, copper_pour_id: Wa.string().optional(), is_inside_copper_pour: Wa.boolean().optional(), hole_diameter: Eh.optional(), outer_diameter: Eh.optional(), from_layer: su, to_layer: su });\nvar Lp = Wa.union([kp, Dp]);\nvar zp = Wa.object({ type: Wa.literal(\"pcb_trace\"), source_trace_id: Wa.string().optional(), pcb_component_id: Wa.string().optional(), pcb_trace_id: Hh(\"pcb_trace\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), route_thickness_mode: Wa.enum([\"constant\", \"interpolated\"]).default(\"constant\").optional(), route_order_index: Wa.number().optional(), should_round_corners: Wa.boolean().optional(), trace_length: Wa.number().optional(), highlight_color: Wa.string().optional(), route: Wa.array(Lp) }).describe(\"Defines a trace on the PCB\");\nvar Bp = Wa.object({ type: Wa.literal(\"pcb_trace_warning\"), pcb_trace_warning_id: Hh(\"pcb_trace_warning\"), warning_type: Wa.literal(\"pcb_trace_warning\").default(\"pcb_trace_warning\"), message: Wa.string(), center: Fh.optional(), pcb_trace_id: Wa.string(), source_trace_id: Wa.string(), pcb_component_ids: Wa.array(Wa.string()), pcb_port_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe(\"Defines a trace warning on the PCB\");\nvar Fp = ld.extend({ type: Wa.literal(\"pcb_trace_error\"), pcb_trace_error_id: Hh(\"pcb_trace_error\"), error_type: Wa.literal(\"pcb_trace_error\").default(\"pcb_trace_error\"), center: Fh.optional(), pcb_trace_id: Wa.string(), source_trace_id: Wa.string(), pcb_component_ids: Wa.array(Wa.string()), pcb_port_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe(\"Defines a trace error on the PCB\");\nvar jp = ld.extend({ type: Wa.literal(\"pcb_trace_missing_error\"), pcb_trace_missing_error_id: Hh(\"pcb_trace_missing_error\"), error_type: Wa.literal(\"pcb_trace_missing_error\").default(\"pcb_trace_missing_error\"), center: Fh.optional(), source_trace_id: Wa.string(), pcb_component_ids: Wa.array(Wa.string()), pcb_port_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe(\"Defines an error when a source trace has no corresponding PCB trace\");\nvar $p = ld.extend({ type: Wa.literal(\"pcb_port_not_matched_error\"), pcb_error_id: Hh(\"pcb_error\"), error_type: Wa.literal(\"pcb_port_not_matched_error\").default(\"pcb_port_not_matched_error\"), pcb_component_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe(\"Defines a trace error on the PCB where a port is not matched\");\nvar Yp = ld.extend({ type: Wa.literal(\"pcb_port_not_connected_error\"), pcb_port_not_connected_error_id: Hh(\"pcb_port_not_connected_error\"), error_type: Wa.literal(\"pcb_port_not_connected_error\").default(\"pcb_port_not_connected_error\"), pcb_port_ids: Wa.array(Wa.string()), pcb_component_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe(\"Defines an error when a pcb port is not connected to any trace\");\nvar Xp = Wa.object({ type: Wa.literal(\"pcb_net\"), pcb_net_id: Hh(\"pcb_net\"), source_net_id: Wa.string().optional(), highlight_color: Wa.string().optional() }).describe(\"Defines a net on the PCB\");\nvar Hp = Wa.object({ type: Wa.literal(\"pcb_via\"), pcb_via_id: Hh(\"pcb_via\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), subcircuit_connectivity_map_key: Wa.string().optional(), x: Eh, y: Eh, outer_diameter: Eh.default(\"0.6mm\"), hole_diameter: Eh.default(\"0.25mm\"), from_layer: su.optional(), to_layer: su.optional(), layers: Wa.array(su), pcb_trace_id: Wa.string().optional(), net_is_assignable: Wa.boolean().optional(), net_assigned: Wa.boolean().optional(), is_tented: Wa.boolean().optional() }).describe(\"Defines a via on the PCB\");\nvar Vp = Wa.object({ type: Wa.literal(\"pcb_board\"), pcb_board_id: Hh(\"pcb_board\"), pcb_panel_id: Wa.string().optional(), carrier_pcb_board_id: Wa.string().optional(), is_subcircuit: Wa.boolean().optional(), subcircuit_id: Wa.string().optional(), is_mounted_to_carrier_board: Wa.boolean().optional(), width: Rh.optional(), height: Rh.optional(), center: Fh, display_offset_x: Wa.string().optional().describe(\"How to display the x offset for this board, usually corresponding with how the user specified it\"), display_offset_y: Wa.string().optional().describe(\"How to display the y offset for this board, usually corresponding with how the user specified it\"), thickness: Rh.optional().default(1.4), num_layers: Wa.number().optional().default(4), outline: Wa.array(Fh).optional(), shape: Wa.enum([\"rect\", \"polygon\"]).optional(), material: Wa.enum([\"fr4\", \"fr1\"]).default(\"fr4\"), anchor_position: Fh.optional(), anchor_alignment: Vh.optional(), position_mode: Wa.enum([\"relative_to_panel_anchor\", \"none\"]).optional() }).merge(Ju).describe(\"Defines the board outline of the PCB\");\nvar Wp = Wa.object({ type: Wa.literal(\"pcb_panel\"), pcb_panel_id: Hh(\"pcb_panel\"), width: Rh, height: Rh, center: Fh, thickness: Rh.optional().default(1.4), covered_with_solder_mask: Wa.boolean().optional().default(true) }).describe(\"Defines a PCB panel that can contain multiple boards\");\nvar Gp = ld.extend({ type: Wa.literal(\"pcb_placement_error\"), pcb_placement_error_id: Hh(\"pcb_placement_error\"), error_type: Wa.literal(\"pcb_placement_error\").default(\"pcb_placement_error\"), subcircuit_id: Wa.string().optional() }).describe(\"Defines a placement error on the PCB\");\nvar Up = ld.extend({ type: Wa.literal(\"pcb_panelization_placement_error\"), pcb_panelization_placement_error_id: Hh(\"pcb_panelization_placement_error\"), error_type: Wa.literal(\"pcb_panelization_placement_error\").default(\"pcb_panelization_placement_error\"), pcb_panel_id: Wa.string().optional(), pcb_board_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe(\"Defines a panelization placement error on the PCB\");\nvar Zp = Wa.object({ type: Wa.literal(\"pcb_trace_hint\"), pcb_trace_hint_id: Hh(\"pcb_trace_hint\"), pcb_port_id: Wa.string(), pcb_component_id: Wa.string(), route: Wa.array(qu), subcircuit_id: Wa.string().optional() }).describe(\"A hint that can be used during generation of a PCB trace\");\nvar qp = Wa.object({ type: Wa.literal(\"pcb_silkscreen_line\"), pcb_silkscreen_line_id: Hh(\"pcb_silkscreen_line\"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), stroke_width: Eh.default(\"0.1mm\"), x1: Eh, y1: Eh, x2: Eh, y2: Eh, layer: au }).describe(\"Defines a silkscreen line on the PCB\");\nvar Jp = Wa.object({ type: Wa.literal(\"pcb_silkscreen_path\"), pcb_silkscreen_path_id: Hh(\"pcb_silkscreen_path\"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), layer: au, route: Wa.array(Fh), stroke_width: Rh }).describe(\"Defines a silkscreen path on the PCB\");\nvar Qp = Wa.object({ type: Wa.literal(\"pcb_silkscreen_text\"), pcb_silkscreen_text_id: Hh(\"pcb_silkscreen_text\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), font: Wa.literal(\"tscircuit2024\").default(\"tscircuit2024\"), font_size: Eh.default(\"0.2mm\"), pcb_component_id: Wa.string(), text: Wa.string(), is_knockout: Wa.boolean().default(false).optional(), knockout_padding: Wa.object({ left: Rh, top: Rh, bottom: Rh, right: Rh }).default({ left: \"0.2mm\", top: \"0.2mm\", bottom: \"0.2mm\", right: \"0.2mm\" }).optional(), ccw_rotation: Wa.number().optional(), layer: su, is_mirrored: Wa.boolean().default(false).optional(), anchor_position: Fh.default({ x: 0, y: 0 }), anchor_alignment: Vh.default(\"center\") }).describe(\"Defines silkscreen text on the PCB\");\nvar Kp = Wa.object({ type: Wa.literal(\"pcb_copper_text\"), pcb_copper_text_id: Hh(\"pcb_copper_text\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), font: Wa.literal(\"tscircuit2024\").default(\"tscircuit2024\"), font_size: Eh.default(\"0.2mm\"), pcb_component_id: Wa.string(), text: Wa.string(), is_knockout: Wa.boolean().default(false).optional(), knockout_padding: Wa.object({ left: Rh, top: Rh, bottom: Rh, right: Rh }).default({ left: \"0.2mm\", top: \"0.2mm\", bottom: \"0.2mm\", right: \"0.2mm\" }).optional(), ccw_rotation: Wa.number().optional(), layer: su, is_mirrored: Wa.boolean().default(false).optional(), anchor_position: Fh.default({ x: 0, y: 0 }), anchor_alignment: Vh.default(\"center\") }).describe(\"Defines copper text on the PCB\");\nvar em = Wa.object({ type: Wa.literal(\"pcb_silkscreen_rect\"), pcb_silkscreen_rect_id: Hh(\"pcb_silkscreen_rect\"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: Fh, width: Rh, height: Rh, layer: su, stroke_width: Rh.default(\"1mm\"), corner_radius: Rh.optional(), is_filled: Wa.boolean().default(true).optional(), has_stroke: Wa.boolean().optional(), is_stroke_dashed: Wa.boolean().optional(), ccw_rotation: Wa.number().optional() }).describe(\"Defines a silkscreen rect on the PCB\");\nvar tm = Wa.object({ type: Wa.literal(\"pcb_silkscreen_circle\"), pcb_silkscreen_circle_id: Hh(\"pcb_silkscreen_circle\"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: Fh, radius: Rh, layer: au, stroke_width: Rh.default(\"1mm\"), is_filled: Wa.boolean().optional() }).describe(\"Defines a silkscreen circle on the PCB\");\nvar nm = Wa.object({ type: Wa.literal(\"pcb_silkscreen_oval\"), pcb_silkscreen_oval_id: Hh(\"pcb_silkscreen_oval\"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: Fh, radius_x: Eh, radius_y: Eh, layer: au, ccw_rotation: zh.optional() }).describe(\"Defines a silkscreen oval on the PCB\");\nvar om = Wa.object({ type: Wa.literal(\"pcb_silkscreen_pill\"), pcb_silkscreen_pill_id: Hh(\"pcb_silkscreen_pill\"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: Fh, width: Rh, height: Rh, layer: su, ccw_rotation: Wa.number().optional() }).describe(\"Defines a silkscreen pill on the PCB\");\nvar im = Wa.object({ type: Wa.literal(\"pcb_fabrication_note_text\"), pcb_fabrication_note_text_id: Hh(\"pcb_fabrication_note_text\"), subcircuit_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), font: Wa.literal(\"tscircuit2024\").default(\"tscircuit2024\"), font_size: Eh.default(\"1mm\"), pcb_component_id: Wa.string(), text: Wa.string(), layer: au, anchor_position: Fh.default({ x: 0, y: 0 }), anchor_alignment: Wa.enum([\"center\", \"top_left\", \"top_right\", \"bottom_left\", \"bottom_right\"]).default(\"center\"), color: Wa.string().optional() }).describe(\"Defines a fabrication note in text on the PCB, useful for leaving notes for assemblers or fabricators\");\nvar rm = Wa.object({ type: Wa.literal(\"pcb_fabrication_note_path\"), pcb_fabrication_note_path_id: Hh(\"pcb_fabrication_note_path\"), pcb_component_id: Wa.string(), subcircuit_id: Wa.string().optional(), layer: su, route: Wa.array(Fh), stroke_width: Rh, color: Wa.string().optional() }).describe(\"Defines a fabrication path on the PCB for fabricators or assemblers\");\nvar sm = Wa.object({ type: Wa.literal(\"pcb_fabrication_note_rect\"), pcb_fabrication_note_rect_id: Hh(\"pcb_fabrication_note_rect\"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: Fh, width: Rh, height: Rh, layer: au, stroke_width: Rh.default(\"0.1mm\"), corner_radius: Rh.optional(), is_filled: Wa.boolean().optional(), has_stroke: Wa.boolean().optional(), is_stroke_dashed: Wa.boolean().optional(), color: Wa.string().optional() }).describe(\"Defines a fabrication note rectangle on the PCB\");\nvar am = Wa.object({ type: Wa.literal(\"pcb_fabrication_note_dimension\"), pcb_fabrication_note_dimension_id: Hh(\"pcb_fabrication_note_dimension\"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), layer: au, from: Fh, to: Fh, text: Wa.string().optional(), text_ccw_rotation: Wa.number().optional(), offset: Rh.optional(), offset_distance: Rh.optional(), offset_direction: Wa.object({ x: Wa.number(), y: Wa.number() }).optional(), font: Wa.literal(\"tscircuit2024\").default(\"tscircuit2024\"), font_size: Rh.default(\"1mm\"), color: Wa.string().optional(), arrow_size: Rh.default(\"1mm\") }).describe(\"Defines a measurement annotation within PCB fabrication notes\");\nvar cm = Wa.object({ type: Wa.literal(\"pcb_note_text\"), pcb_note_text_id: Hh(\"pcb_note_text\"), pcb_component_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), name: Wa.string().optional(), font: Wa.literal(\"tscircuit2024\").default(\"tscircuit2024\"), font_size: Eh.default(\"1mm\"), text: Wa.string().optional(), anchor_position: Fh.default({ x: 0, y: 0 }), anchor_alignment: Wa.enum([\"center\", \"top_left\", \"top_right\", \"bottom_left\", \"bottom_right\"]).default(\"center\"), layer: au.default(\"top\"), is_mirrored_from_top_view: Wa.boolean().optional(), color: Wa.string().optional() }).describe(\"Defines a documentation note in text on the PCB\");\nvar lm = Wa.object({ type: Wa.literal(\"pcb_note_rect\"), pcb_note_rect_id: Hh(\"pcb_note_rect\"), pcb_component_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), name: Wa.string().optional(), text: Wa.string().optional(), center: Fh, width: Rh, height: Rh, layer: au.default(\"top\"), stroke_width: Rh.default(\"0.1mm\"), corner_radius: Rh.optional(), is_filled: Wa.boolean().optional(), has_stroke: Wa.boolean().optional(), is_stroke_dashed: Wa.boolean().optional(), color: Wa.string().optional() }).describe(\"Defines a rectangular documentation note on the PCB\");\nvar hm = Wa.object({ type: Wa.literal(\"pcb_note_path\"), pcb_note_path_id: Hh(\"pcb_note_path\"), pcb_component_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), name: Wa.string().optional(), text: Wa.string().optional(), route: Wa.array(Fh), layer: au.default(\"top\"), stroke_width: Rh.default(\"0.1mm\"), color: Wa.string().optional() }).describe(\"Defines a polyline documentation note on the PCB\");\nvar dm = Wa.object({ type: Wa.literal(\"pcb_note_line\"), pcb_note_line_id: Hh(\"pcb_note_line\"), pcb_component_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), name: Wa.string().optional(), text: Wa.string().optional(), x1: Eh, y1: Eh, x2: Eh, y2: Eh, layer: au.default(\"top\"), stroke_width: Eh.default(\"0.1mm\"), color: Wa.string().optional(), is_dashed: Wa.boolean().optional() }).describe(\"Defines a straight documentation note line on the PCB\");\nvar um = Wa.object({ type: Wa.literal(\"pcb_note_dimension\"), pcb_note_dimension_id: Hh(\"pcb_note_dimension\"), pcb_component_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), name: Wa.string().optional(), from: Fh, to: Fh, text: Wa.string().optional(), text_ccw_rotation: Wa.number().optional(), offset_distance: Rh.optional(), offset_direction: Wa.object({ x: Wa.number(), y: Wa.number() }).optional(), font: Wa.literal(\"tscircuit2024\").default(\"tscircuit2024\"), font_size: Rh.default(\"1mm\"), layer: au.default(\"top\"), color: Wa.string().optional(), arrow_size: Rh.default(\"1mm\") }).describe(\"Defines a measurement annotation within PCB documentation notes\");\nvar pm = ld.extend({ type: Wa.literal(\"pcb_footprint_overlap_error\"), pcb_error_id: Hh(\"pcb_error\"), error_type: Wa.literal(\"pcb_footprint_overlap_error\").default(\"pcb_footprint_overlap_error\"), pcb_smtpad_ids: Wa.array(Wa.string()).optional(), pcb_plated_hole_ids: Wa.array(Wa.string()).optional(), pcb_hole_ids: Wa.array(Wa.string()).optional(), pcb_keepout_ids: Wa.array(Wa.string()).optional() }).describe(\"Error emitted when a pcb footprint overlaps with another element\");\nvar mm = ld.extend({ type: Wa.literal(\"pcb_courtyard_overlap_error\"), pcb_error_id: Hh(\"pcb_error\"), error_type: Wa.literal(\"pcb_courtyard_overlap_error\").default(\"pcb_courtyard_overlap_error\"), pcb_component_ids: Wa.tuple([Wa.string(), Wa.string()]) }).describe(\"Error emitted when the courtyard (CrtYd) of one PCB component overlaps with the courtyard of another\");\nvar gm = Wa.object({ type: Wa.literal(\"pcb_keepout\"), shape: Wa.literal(\"rect\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: Fh, width: Eh, height: Eh, pcb_keepout_id: Wa.string(), layers: Wa.array(Wa.string()), description: Wa.string().optional() }).or(Wa.object({ type: Wa.literal(\"pcb_keepout\"), shape: Wa.literal(\"circle\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: Fh, radius: Eh, pcb_keepout_id: Wa.string(), layers: Wa.array(Wa.string()), description: Wa.string().optional() }));\nvar fm = Wa.object({ type: Wa.literal(\"pcb_cutout\"), pcb_cutout_id: Hh(\"pcb_cutout\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), pcb_board_id: Wa.string().optional(), pcb_panel_id: Wa.string().optional() });\nvar _m = fm.extend({ shape: Wa.literal(\"rect\"), center: Fh, width: Rh, height: Rh, rotation: zh.optional(), corner_radius: Rh.optional() });\nvar ym = fm.extend({ shape: Wa.literal(\"circle\"), center: Fh, radius: Rh });\nvar bm = fm.extend({ shape: Wa.literal(\"polygon\"), points: Wa.array(Fh) });\nvar xm = fm.extend({ shape: Wa.literal(\"path\"), route: Wa.array(Fh), slot_width: Rh, slot_length: Rh.optional(), space_between_slots: Rh.optional(), slot_corner_radius: Rh.optional() });\nvar vm = Wa.discriminatedUnion(\"shape\", [_m, ym, bm, xm]).describe(\"Defines a cutout on the PCB, removing board material.\");\nvar Im = ld.extend({ type: Wa.literal(\"pcb_missing_footprint_error\"), pcb_missing_footprint_error_id: Hh(\"pcb_missing_footprint_error\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), error_type: Wa.literal(\"pcb_missing_footprint_error\").default(\"pcb_missing_footprint_error\"), source_component_id: Wa.string() }).describe(\"Defines a missing footprint error on the PCB\");\nvar Sm = ld.extend({ type: Wa.literal(\"external_footprint_load_error\"), external_footprint_load_error_id: Hh(\"external_footprint_load_error\"), pcb_component_id: Wa.string(), source_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), footprinter_string: Wa.string().optional(), error_type: Wa.literal(\"external_footprint_load_error\").default(\"external_footprint_load_error\") }).describe(\"Defines an error when an external footprint fails to load\");\nvar Cm = ld.extend({ type: Wa.literal(\"circuit_json_footprint_load_error\"), circuit_json_footprint_load_error_id: Hh(\"circuit_json_footprint_load_error\"), pcb_component_id: Wa.string(), source_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), error_type: Wa.literal(\"circuit_json_footprint_load_error\").default(\"circuit_json_footprint_load_error\"), circuit_json: Wa.array(Wa.any()).optional() }).describe(\"Defines an error when a circuit JSON footprint fails to load\");\nvar Pm = Wa.object({ type: Wa.literal(\"pcb_group\"), pcb_group_id: Hh(\"pcb_group\"), source_group_id: Wa.string(), is_subcircuit: Wa.boolean().optional(), subcircuit_id: Wa.string().optional(), width: Rh.optional(), height: Rh.optional(), center: Fh, display_offset_x: Wa.string().optional().describe(\"How to display the x offset for this group, usually corresponding with how the user specified it\"), display_offset_y: Wa.string().optional().describe(\"How to display the y offset for this group, usually corresponding with how the user specified it\"), outline: Wa.array(Fh).optional(), anchor_position: Fh.optional(), anchor_alignment: Vh.default(\"center\"), position_mode: Wa.enum([\"packed\", \"relative_to_group_anchor\", \"none\"]).optional(), positioned_relative_to_pcb_group_id: Wa.string().optional(), positioned_relative_to_pcb_board_id: Wa.string().optional(), pcb_component_ids: Wa.array(Wa.string()), child_layout_mode: Wa.enum([\"packed\", \"none\"]).optional(), name: Wa.string().optional(), description: Wa.string().optional(), layout_mode: Wa.string().optional(), autorouter_configuration: Wa.object({ trace_clearance: Rh }).optional(), autorouter_used_string: Wa.string().optional() }).describe(\"Defines a group of components on the PCB\");\nvar Mm = ld.extend({ type: Wa.literal(\"pcb_autorouting_error\"), pcb_error_id: Hh(\"pcb_autorouting_error\"), error_type: Wa.literal(\"pcb_autorouting_error\").default(\"pcb_autorouting_error\"), subcircuit_id: Wa.string().optional() }).describe(\"The autorouting has failed to route a portion of the board\");\nvar wm = Wa.object({ type: Wa.literal(\"pcb_manual_edit_conflict_warning\"), pcb_manual_edit_conflict_warning_id: Hh(\"pcb_manual_edit_conflict_warning\"), warning_type: Wa.literal(\"pcb_manual_edit_conflict_warning\").default(\"pcb_manual_edit_conflict_warning\"), message: Wa.string(), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), source_component_id: Wa.string() }).describe(\"Warning emitted when a component has both manual placement and explicit pcbX/pcbY coordinates\");\nvar Nm = Wa.enum([\"x-\", \"x+\", \"y+\", \"y-\"]);\nvar Rm = Wa.object({ type: Wa.literal(\"pcb_connector_not_in_accessible_orientation_warning\"), pcb_connector_not_in_accessible_orientation_warning_id: Hh(\"pcb_connector_not_in_accessible_orientation_warning\"), warning_type: Wa.literal(\"pcb_connector_not_in_accessible_orientation_warning\").default(\"pcb_connector_not_in_accessible_orientation_warning\"), message: Wa.string(), pcb_component_id: Wa.string(), source_component_id: Wa.string().optional(), pcb_board_id: Wa.string().optional(), facing_direction: Nm, recommended_facing_direction: Nm, subcircuit_id: Wa.string().optional() }).describe(\"Warning emitted when a connector PCB component is facing inward toward the board and should be reoriented to an outward-facing direction\");\nvar Tm = Wa.object({ type: Wa.literal(\"supplier_footprint_mismatch_warning\"), supplier_footprint_mismatch_warning_id: Hh(\"supplier_footprint_mismatch_warning\"), warning_type: Wa.literal(\"supplier_footprint_mismatch_warning\").default(\"supplier_footprint_mismatch_warning\"), message: Wa.string(), source_component_id: Wa.string(), pcb_component_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), supplier_name: hd.optional(), supplier_part_number: Wa.string().optional(), supplier_footprint_url: Wa.string().optional(), footprint_copper_intersection_over_union: Wa.number() }).describe(\"Warning emitted when a supplier part footprint does not match the expected footprint\");\nvar Em = Wa.object({ type: Wa.literal(\"pcb_breakout_point\"), pcb_breakout_point_id: Hh(\"pcb_breakout_point\"), pcb_group_id: Wa.string(), subcircuit_id: Wa.string().optional(), source_trace_id: Wa.string().optional(), source_port_id: Wa.string().optional(), source_net_id: Wa.string().optional(), x: Eh, y: Eh }).describe(\"Defines a routing target within a pcb_group for a source_trace or source_net\");\nvar Am = Wa.object({ type: Wa.literal(\"pcb_ground_plane\"), pcb_ground_plane_id: Hh(\"pcb_ground_plane\"), source_pcb_ground_plane_id: Wa.string(), source_net_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe(\"Defines a ground plane on the PCB\");\nvar Om = Wa.object({ type: Wa.literal(\"pcb_ground_plane_region\"), pcb_ground_plane_region_id: Hh(\"pcb_ground_plane_region\"), pcb_ground_plane_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), layer: su, points: Wa.array(Fh) }).describe(\"Defines a polygon region of a ground plane\");\nvar km = Wa.object({ type: Wa.literal(\"pcb_thermal_spoke\"), pcb_thermal_spoke_id: Hh(\"pcb_thermal_spoke\"), pcb_ground_plane_id: Wa.string(), shape: Wa.string(), spoke_count: Wa.number(), spoke_thickness: Eh, spoke_inner_diameter: Eh, spoke_outer_diameter: Eh, pcb_plated_hole_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe(\"Pattern for connecting a ground plane to a plated hole\");\nvar Dm = Wa.object({ type: Wa.literal(\"pcb_copper_pour\"), pcb_copper_pour_id: Hh(\"pcb_copper_pour\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), layer: su, source_net_id: Wa.string().optional(), covered_with_solder_mask: Wa.boolean().optional().default(true) });\nvar Lm = Dm.extend({ shape: Wa.literal(\"rect\"), center: Fh, width: Rh, height: Rh, rotation: zh.optional() });\nvar zm = Dm.extend({ shape: Wa.literal(\"brep\"), brep_shape: Gu });\nvar Bm = Dm.extend({ shape: Wa.literal(\"polygon\"), points: Wa.array(Fh) });\nvar Fm = Wa.discriminatedUnion(\"shape\", [Lm, zm, Bm]).describe(\"Defines a copper pour on the PCB.\");\nvar jm = ld.extend({ type: Wa.literal(\"pcb_component_outside_board_error\"), pcb_component_outside_board_error_id: Hh(\"pcb_component_outside_board_error\"), error_type: Wa.literal(\"pcb_component_outside_board_error\").default(\"pcb_component_outside_board_error\"), pcb_component_id: Wa.string(), pcb_board_id: Wa.string(), component_center: Fh, component_bounds: Wa.object({ min_x: Wa.number(), max_x: Wa.number(), min_y: Wa.number(), max_y: Wa.number() }), subcircuit_id: Wa.string().optional(), source_component_id: Wa.string().optional() }).describe(\"Error emitted when a PCB component is placed outside the board boundaries\");\nvar $m = ld.extend({ type: Wa.literal(\"pcb_component_not_on_board_edge_error\"), pcb_component_not_on_board_edge_error_id: Hh(\"pcb_component_not_on_board_edge_error\"), error_type: Wa.literal(\"pcb_component_not_on_board_edge_error\").default(\"pcb_component_not_on_board_edge_error\"), pcb_component_id: Wa.string(), pcb_board_id: Wa.string(), component_center: Fh, pad_to_nearest_board_edge_distance: Wa.number(), source_component_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe(\"Error emitted when a component that must be placed on the board edge is centered away from the edge\");\nvar Ym = ld.extend({ type: Wa.literal(\"pcb_component_invalid_layer_error\"), pcb_component_invalid_layer_error_id: Hh(\"pcb_component_invalid_layer_error\"), error_type: Wa.literal(\"pcb_component_invalid_layer_error\").default(\"pcb_component_invalid_layer_error\"), pcb_component_id: Wa.string().optional(), source_component_id: Wa.string(), layer: su, subcircuit_id: Wa.string().optional() }).describe(\"Error emitted when a component is placed on an invalid layer (components can only be on 'top' or 'bottom' layers)\");\nvar Xm = ld.extend({ type: Wa.literal(\"pcb_via_clearance_error\"), pcb_error_id: Hh(\"pcb_error\"), error_type: Wa.literal(\"pcb_via_clearance_error\").default(\"pcb_via_clearance_error\"), pcb_via_ids: Wa.array(Wa.string()).min(2), minimum_clearance: Eh.optional(), actual_clearance: Eh.optional(), pcb_center: Wa.object({ x: Wa.number().optional(), y: Wa.number().optional() }).optional(), subcircuit_id: Wa.string().optional() }).describe(\"Error emitted when vias are closer than the allowed clearance\");\nvar Hm = ld.extend({ type: Wa.literal(\"pcb_via_trace_clearance_error\"), pcb_via_trace_clearance_error_id: Hh(\"pcb_via_trace_clearance_error\"), error_type: Wa.literal(\"pcb_via_trace_clearance_error\").default(\"pcb_via_trace_clearance_error\"), pcb_via_id: Wa.string(), pcb_trace_id: Wa.string(), minimum_clearance: Eh.optional(), actual_clearance: Eh.optional(), center: Wa.object({ x: Wa.number().optional(), y: Wa.number().optional() }).optional(), subcircuit_id: Wa.string().optional() }).describe(\"Error emitted when a via and trace are closer than the allowed clearance\");\nvar Vm = ld.extend({ type: Wa.literal(\"pcb_pad_pad_clearance_error\"), pcb_pad_pad_clearance_error_id: Hh(\"pcb_pad_pad_clearance_error\"), error_type: Wa.literal(\"pcb_pad_pad_clearance_error\").default(\"pcb_pad_pad_clearance_error\"), pcb_pad_ids: Wa.array(Wa.string()).min(2), minimum_clearance: Eh.optional(), actual_clearance: Eh.optional(), center: Wa.object({ x: Wa.number().optional(), y: Wa.number().optional() }).optional(), subcircuit_id: Wa.string().optional() }).describe(\"Error emitted when pads are closer than the allowed clearance\");\nvar Wm = ld.extend({ type: Wa.literal(\"pcb_pad_trace_clearance_error\"), pcb_pad_trace_clearance_error_id: Hh(\"pcb_pad_trace_clearance_error\"), error_type: Wa.literal(\"pcb_pad_trace_clearance_error\").default(\"pcb_pad_trace_clearance_error\"), pcb_pad_id: Wa.string(), pcb_trace_id: Wa.string(), minimum_clearance: Eh.optional(), actual_clearance: Eh.optional(), center: Wa.object({ x: Wa.number().optional(), y: Wa.number().optional() }).optional(), subcircuit_id: Wa.string().optional() }).describe(\"Error emitted when a pad and trace are closer than allowed clearance\");\nvar Gm = Wa.object({ type: Wa.literal(\"pcb_courtyard_rect\"), pcb_courtyard_rect_id: Hh(\"pcb_courtyard_rect\"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: Fh, width: Rh, height: Rh, layer: au, ccw_rotation: zh.optional(), color: Wa.string().optional() }).describe(\"Defines a courtyard rectangle on the PCB\");\nvar Um = Wa.object({ type: Wa.literal(\"pcb_courtyard_outline\"), pcb_courtyard_outline_id: Hh(\"pcb_courtyard_outline\"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), layer: au, outline: Wa.array(Fh).min(2) }).describe(\"Defines a courtyard outline on the PCB\");\nvar Zm = Wa.object({ type: Wa.literal(\"pcb_courtyard_polygon\"), pcb_courtyard_polygon_id: Hh(\"pcb_courtyard_polygon\"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), layer: au, points: Wa.array(Fh).min(3), color: Wa.string().optional() }).describe(\"Defines a courtyard polygon on the PCB\");\nvar qm = Wa.object({ type: Wa.literal(\"pcb_courtyard_circle\"), pcb_courtyard_circle_id: Hh(\"pcb_courtyard_circle\"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: Fh, radius: Rh, layer: au, color: Wa.string().optional() }).describe(\"Defines a courtyard circle on the PCB\");\nvar Jm = [\"obj\", \"stl\", \"3mf\", \"gltf\", \"glb\", \"step\", \"wrl\"];\nvar Qm = [\"x+\", \"x-\", \"y+\", \"y-\", \"z+\", \"z-\"];\nvar Km = { obj: \"z+\", stl: \"z+\", \"3mf\": \"z+\", gltf: \"y+\", glb: \"y+\", step: \"z+\", wrl: \"y+\" };\nvar eg = Wa.object({ type: Wa.literal(\"cad_component\"), cad_component_id: Wa.string(), pcb_component_id: Wa.string(), source_component_id: Wa.string(), position: $h, rotation: $h.optional(), size: $h.optional(), layer: su.optional(), subcircuit_id: Wa.string().optional(), footprinter_string: Wa.string().optional(), model_obj_url: Wa.string().optional(), model_stl_url: Wa.string().optional(), model_3mf_url: Wa.string().optional(), model_gltf_url: Wa.string().optional(), model_glb_url: Wa.string().optional(), model_step_url: Wa.string().optional(), model_wrl_url: Wa.string().optional(), model_asset: Gh.optional(), model_unit_to_mm_scale_factor: Wa.number().optional(), model_board_normal_direction: Wa.enum(Qm).optional().describe(`The direction in the model's coordinate space that is considered \"up\" or \"coming out of the board surface\"`), model_origin_position: $h.optional(), model_origin_alignment: Wa.enum([\"unknown\", \"center\", \"center_of_component_on_board_surface\", \"bottom_center_of_component\"]).optional(), model_object_fit: Wa.enum([\"contain_within_bounds\", \"fill_bounds\"]).optional().default(\"contain_within_bounds\"), model_jscad: Wa.any().optional(), show_as_translucent_model: Wa.boolean().optional(), anchor_alignment: Wa.enum([\"center\", \"center_of_component_on_board_surface\"]).optional().default(\"center\") }).describe(\"Defines a component on the PCB\");\nvar tg = Wa.enum([\"sinewave\", \"square\", \"triangle\", \"sawtooth\"]);\nvar ng = Wa.union([Wa.string(), Wa.number()]).transform((e20) =\u003e typeof e20 == \"string\" ? e20.endsWith(\"%\") ? parseFloat(e20.slice(0, -1)) / 100 : parseFloat(e20) : e20).pipe(Wa.number().min(0, \"Duty cycle must be non-negative\").max(1, \"Duty cycle cannot be greater than 100%\"));\nvar og = Wa.object({ type: Wa.literal(\"simulation_voltage_source\"), simulation_voltage_source_id: Hh(\"simulation_voltage_source\"), is_dc_source: Wa.literal(true).optional().default(true), positive_source_port_id: Wa.string().optional(), negative_source_port_id: Wa.string().optional(), positive_source_net_id: Wa.string().optional(), negative_source_net_id: Wa.string().optional(), voltage: Nh }).describe(\"Defines a DC voltage source for simulation\");\nvar ig = Wa.object({ type: Wa.literal(\"simulation_voltage_source\"), simulation_voltage_source_id: Hh(\"simulation_voltage_source\"), is_dc_source: Wa.literal(false), terminal1_source_port_id: Wa.string().optional(), terminal2_source_port_id: Wa.string().optional(), terminal1_source_net_id: Wa.string().optional(), terminal2_source_net_id: Wa.string().optional(), voltage: Nh.optional(), frequency: Th.optional(), peak_to_peak_voltage: Nh.optional(), wave_shape: tg.optional(), phase: zh.optional(), duty_cycle: ng.optional() }).describe(\"Defines an AC voltage source for simulation\");\nvar rg = Wa.union([og, ig]).describe(\"Defines a voltage source for simulation\");\nvar sg = Wa.union([Wa.string(), Wa.number()]).transform((e20) =\u003e typeof e20 == \"string\" ? e20.endsWith(\"%\") ? parseFloat(e20.slice(0, -1)) / 100 : parseFloat(e20) : e20).pipe(Wa.number().min(0, \"Duty cycle must be non-negative\").max(1, \"Duty cycle cannot be greater than 100%\"));\nvar ag = Wa.object({ type: Wa.literal(\"simulation_current_source\"), simulation_current_source_id: Hh(\"simulation_current_source\"), is_dc_source: Wa.literal(true).optional().default(true), positive_source_port_id: Wa.string().optional(), negative_source_port_id: Wa.string().optional(), positive_source_net_id: Wa.string().optional(), negative_source_net_id: Wa.string().optional(), current: Ah }).describe(\"Defines a DC current source for simulation\");\nvar cg = Wa.object({ type: Wa.literal(\"simulation_current_source\"), simulation_current_source_id: Hh(\"simulation_current_source\"), is_dc_source: Wa.literal(false), terminal1_source_port_id: Wa.string().optional(), terminal2_source_port_id: Wa.string().optional(), terminal1_source_net_id: Wa.string().optional(), terminal2_source_net_id: Wa.string().optional(), current: Ah.optional(), frequency: Th.optional(), peak_to_peak_current: Ah.optional(), wave_shape: tg.optional(), phase: zh.optional(), duty_cycle: sg.optional() }).describe(\"Defines an AC current source for simulation\");\nvar lg = Wa.union([ag, cg]).describe(\"Defines a current source for simulation\");\nvar hg = Wa.union([Wa.literal(\"spice_dc_sweep\"), Wa.literal(\"spice_dc_operating_point\"), Wa.literal(\"spice_transient_analysis\"), Wa.literal(\"spice_ac_analysis\")]);\nvar dg = Wa.object({ type: Wa.literal(\"simulation_experiment\"), simulation_experiment_id: Hh(\"simulation_experiment\"), name: Wa.string(), experiment_type: hg, time_per_step: Oh.optional(), start_time_ms: Dh.optional(), end_time_ms: Dh.optional() }).describe(\"Defines a simulation experiment configuration\");\nvar ug = Wa.object({ type: Wa.literal(\"simulation_transient_voltage_graph\"), simulation_transient_voltage_graph_id: Hh(\"simulation_transient_voltage_graph\"), simulation_experiment_id: Wa.string(), timestamps_ms: Wa.array(Wa.number()).optional(), voltage_levels: Wa.array(Wa.number()), source_component_id: Wa.string().optional(), subcircuit_connectivity_map_key: Wa.string().optional(), time_per_step: Oh, start_time_ms: Dh, end_time_ms: Dh, name: Wa.string().optional(), color: Wa.string().optional() }).describe(\"Stores voltage measurements over time for a simulation\");\nvar pg = Wa.object({ type: Wa.literal(\"simulation_switch\"), simulation_switch_id: Hh(\"simulation_switch\"), source_component_id: Wa.string().optional(), closes_at: Dh.optional(), opens_at: Dh.optional(), starts_closed: Wa.boolean().optional(), switching_frequency: Th.optional() }).describe(\"Defines a switch for simulation timing control\");\nvar mg = Wa.object({ type: Wa.literal(\"simulation_voltage_probe\"), simulation_voltage_probe_id: Hh(\"simulation_voltage_probe\"), source_component_id: Wa.string().optional(), name: Wa.string().optional(), signal_input_source_port_id: Wa.string().optional(), signal_input_source_net_id: Wa.string().optional(), reference_input_source_port_id: Wa.string().optional(), reference_input_source_net_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), color: Wa.string().optional() }).describe(\"Defines a voltage probe for simulation. If a reference input is not provided, it measures against ground. If a reference input is provided, it measures the differential voltage between two points.\").superRefine((e20, t2) =\u003e {\n if (e20.reference_input_source_port_id || e20.reference_input_source_net_id) {\n const n2 = !!e20.signal_input_source_port_id || !!e20.reference_input_source_port_id, o3 = !!e20.signal_input_source_net_id || !!e20.reference_input_source_net_id;\n n2 \u0026\u0026 o3 ? t2.addIssue({ code: Wa.ZodIssueCode.custom, message: \"Cannot mix port and net connections in a differential probe.\" }) : n2 ? e20.signal_input_source_port_id \u0026\u0026 e20.reference_input_source_port_id || t2.addIssue({ code: Wa.ZodIssueCode.custom, message: \"Differential port probe requires both signal_input_source_port_id and reference_input_source_port_id.\" }) : o3 \u0026\u0026 (e20.signal_input_source_net_id \u0026\u0026 e20.reference_input_source_net_id || t2.addIssue({ code: Wa.ZodIssueCode.custom, message: \"Differential net probe requires both signal_input_source_net_id and reference_input_source_net_id.\" }));\n } else\n !!e20.signal_input_source_port_id == !!e20.signal_input_source_net_id \u0026\u0026 t2.addIssue({ code: Wa.ZodIssueCode.custom, message: \"A voltage probe must have exactly one of signal_input_source_port_id or signal_input_source_net_id.\" });\n});\nvar gg = ld.extend({ type: Wa.literal(\"simulation_unknown_experiment_error\"), simulation_unknown_experiment_error_id: Hh(\"simulation_unknown_experiment_error\"), error_type: Wa.literal(\"simulation_unknown_experiment_error\").default(\"simulation_unknown_experiment_error\"), simulation_experiment_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe(\"An unknown error occurred during the simulation experiment.\");\nvar fg = Wa.object({ type: Wa.literal(\"simulation_op_amp\"), simulation_op_amp_id: Hh(\"simulation_op_amp\"), source_component_id: Wa.string().optional(), inverting_input_source_port_id: Wa.string(), non_inverting_input_source_port_id: Wa.string(), output_source_port_id: Wa.string(), positive_supply_source_port_id: Wa.string(), negative_supply_source_port_id: Wa.string() }).describe(\"Defines a simple ideal operational amplifier for simulation\");\nvar _g = Wa.union([Qd, qd, Jd, Zd, eu, Kd, yd, ud, md, fd, pd, bd, Sd, Cd, Nd, Td, Ed, Ld, Ad, Od, kd, Dd, Md, Pd, ou, cu, tu, zd, jd, $d, Xd, Hd, lu, hu, du, uu, pu, Gd, nu, Qu, dp, Im, Sm, Cm, wm, Rm, Tm, yp, gm, bp, Xp, Op, zp, Bp, Hp, Mp, Ap, Vp, Wp, Pm, Zp, qp, Jp, Qp, om, Kp, em, tm, nm, Fp, jp, Gp, Up, $p, Yp, Xm, Hm, Vm, Wm, rm, im, sm, am, cm, lm, hm, dm, um, Mm, pm, mm, Em, vm, Am, Om, km, Fm, jm, $m, Ym, Gm, Um, Zm, qm, mu, Ru, Su, Cu, Pu, Mu, xu, Iu, Tu, wu, gu, Au, Ou, Eu, Bu, Fu, ju, $u, Hu, Yu, Xu, eg, rg, lg, dg, ug, pg, mg, gg, fg]);\nvar yg = _g;\nfunction bg(e20, t2, n2) {\n if (!t2 || !n2)\n return;\n let o3 = e20.get(t2);\n o3 || (o3 = new Set, e20.set(t2, o3)), o3.add(n2);\n let i3 = e20.get(n2);\n i3 || (i3 = new Set, e20.set(n2, i3)), i3.add(t2);\n}\nvar xg = (e20, t2 = {}) =\u003e {\n const n2 = e20;\n let o3 = n2._internal_store;\n if (!o3) {\n o3 = { counts: {}, editCount: 0 }, n2._internal_store = o3;\n for (const e21 of n2) {\n const t3 = e21.type, n3 = e21[`${t3}_id`];\n if (!n3)\n continue;\n const i4 = Number.parseInt(n3.split(\"_\").pop());\n Number.isNaN(i4) || (o3.counts[t3] = Math.max(o3.counts[t3] ?? 0, i4));\n }\n }\n const i3 = new Proxy({}, { get: (e21, r3) =\u003e {\n if (r3 === \"toArray\")\n return () =\u003e (n2.editCount = o3.editCount, n2);\n if (r3 === \"editCount\")\n return o3.editCount;\n if (r3 === \"subtree\")\n return (e22) =\u003e xg(function(e23, t3) {\n if (!t3.subcircuit_id \u0026\u0026 !t3.source_group_id)\n return [...e23];\n let n3 = t3;\n if (t3.subcircuit_id) {\n const o5 = new Set([t3.subcircuit_id]), i5 = new Map, r5 = new Map;\n for (const t4 of e23)\n if (t4.type === \"source_group\") {\n const { source_group_id: e24, subcircuit_id: n4 } = t4;\n n4 \u0026\u0026 r5.set(e24, n4);\n const o6 = t4.parent_source_group_id;\n o6 \u0026\u0026 (i5.has(o6) || i5.set(o6, []), i5.get(o6).push(e24));\n }\n let s4;\n for (const [e24, n4] of r5)\n if (n4 === t3.subcircuit_id) {\n s4 = e24;\n break;\n }\n if (s4) {\n const e24 = (t4) =\u003e {\n const n4 = i5.get(t4) || [];\n for (const t5 of n4) {\n const n5 = r5.get(t5);\n n5 \u0026\u0026 o5.add(n5), e24(t5);\n }\n };\n e24(s4), n3 = { ...t3, subcircuit_ids: Array.from(o5) };\n }\n }\n const o4 = new Map;\n for (const t4 of e23) {\n const e24 = t4[`${t4.type}_id`];\n typeof e24 == \"string\" \u0026\u0026 o4.set(e24, t4);\n }\n const i4 = new Map;\n for (const t4 of e23) {\n const e24 = Object.entries(t4);\n for (const [n4, r5] of e24)\n if (n4 !== \"parent_source_group_id\") {\n if (n4.endsWith(\"_id\") \u0026\u0026 typeof r5 == \"string\")\n bg(i4, t4, o4.get(r5));\n else if (n4.endsWith(\"_ids\") \u0026\u0026 Array.isArray(r5))\n for (const e25 of r5)\n typeof e25 == \"string\" \u0026\u0026 bg(i4, t4, o4.get(e25));\n }\n }\n const r4 = [], s3 = new Set;\n for (const t4 of e23) {\n let e24 = false;\n (n3.subcircuit_id \u0026\u0026 (\"subcircuit_id\" in t4) \u0026\u0026 t4.subcircuit_id === n3.subcircuit_id || n3.subcircuit_ids \u0026\u0026 (\"subcircuit_id\" in t4) \u0026\u0026 t4.subcircuit_id \u0026\u0026 n3.subcircuit_ids.includes(t4.subcircuit_id) || n3.source_group_id \u0026\u0026 (\"source_group_id\" in t4) \u0026\u0026 t4.source_group_id === n3.source_group_id || n3.source_group_id \u0026\u0026 (\"member_source_group_ids\" in t4) \u0026\u0026 Array.isArray(t4.member_source_group_ids) \u0026\u0026 t4.member_source_group_ids.includes(n3.source_group_id)) \u0026\u0026 (e24 = true), e24 \u0026\u0026 (r4.push(t4), s3.add(t4));\n }\n for (;r4.length \u003e 0; ) {\n const e24 = r4.shift(), t4 = i4.get(e24);\n if (t4)\n for (const e25 of t4)\n s3.has(e25) || (s3.add(e25), r4.push(e25));\n }\n return e23.filter((e24) =\u003e s3.has(e24));\n }(n2, e22), t2);\n if (r3 === \"insert\")\n return (e22) =\u003e {\n const i4 = e22.type;\n if (!i4)\n throw new Error(\"insert requires an element with a type\");\n o3.counts[i4] ??= -1, o3.counts[i4]++;\n const r4 = o3.counts[i4], s3 = { ...e22, type: i4, [`${i4}_id`]: `${i4}_${r4}` };\n if (t2.validateInserts) {\n (Ya[i4] ?? yg).parse(s3);\n }\n return n2.push(s3), o3.editCount++, s3;\n };\n if (r3 === \"insertAll\")\n return (e22) =\u003e e22.map((e23) =\u003e i3.insert(e23));\n const s2 = r3;\n return { get: (e22) =\u003e n2.find((t3) =\u003e t3.type === s2 \u0026\u0026 t3[`${s2}_id`] === e22), getUsing: (e22) =\u003e {\n const t3 = Object.keys(e22);\n if (t3.length !== 1)\n throw new Error(\"getUsing requires exactly one key, e.g. { pcb_component_id }\");\n const o4 = t3[0], i4 = o4.replace(\"_id\", \"\"), r4 = n2.find((t4) =\u003e t4.type === i4 \u0026\u0026 t4[o4] === e22[o4]);\n return r4 ? n2.find((e23) =\u003e e23.type === s2 \u0026\u0026 e23[`${s2}_id`] === r4[`${s2}_id`]) : null;\n }, getWhere: (e22) =\u003e {\n const t3 = Object.keys(e22);\n return n2.find((n3) =\u003e n3.type === s2 \u0026\u0026 t3.every((t4) =\u003e n3[t4] === e22[t4]));\n }, list: (e22) =\u003e {\n const t3 = e22 ? Object.keys(e22) : [];\n return n2.filter((n3) =\u003e n3.type === s2 \u0026\u0026 t3.every((t4) =\u003e n3[t4] === e22[t4]));\n }, insert: (e22) =\u003e {\n o3.counts[s2] ??= -1, o3.counts[s2]++;\n const i4 = o3.counts[s2], r4 = { type: s2, [`${s2}_id`]: `${s2}_${i4}`, ...e22 };\n if (t2.validateInserts) {\n (Ya[s2] ?? yg).parse(r4);\n }\n return n2.push(r4), o3.editCount++, r4;\n }, delete: (e22) =\u003e {\n const t3 = n2.find((t4) =\u003e t4[`${s2}_id`] === e22);\n t3 \u0026\u0026 (n2.splice(n2.indexOf(t3), 1), o3.editCount++);\n }, update: (e22, t3) =\u003e {\n const i4 = n2.find((t4) =\u003e t4.type === s2 \u0026\u0026 t4[`${s2}_id`] === e22);\n return i4 ? (Object.assign(i4, t3), o3.editCount++, i4) : null;\n }, select: (e22) =\u003e {\n if (s2 === \"source_component\")\n return n2.find((t3) =\u003e t3.type === \"source_component\" \u0026\u0026 t3.name === e22.replace(/\\./g, \"\"));\n if (s2 === \"pcb_port\" || s2 === \"source_port\" || s2 === \"schematic_port\") {\n const [t3, o4] = e22.replace(/\\./g, \"\").split(/[\\s\\\u003e]+/), i4 = n2.find((e23) =\u003e e23.type === \"source_component\" \u0026\u0026 e23.name === t3);\n if (!i4)\n return null;\n const r4 = n2.find((e23) =\u003e e23.type === \"source_port\" \u0026\u0026 e23.source_component_id === i4.source_component_id \u0026\u0026 (e23.name === o4 || (e23.port_hints ?? []).includes(o4)));\n if (!r4)\n return null;\n if (s2 === \"source_port\")\n return r4;\n if (s2 === \"pcb_port\")\n return n2.find((e23) =\u003e e23.type === \"pcb_port\" \u0026\u0026 e23.source_port_id === r4.source_port_id);\n if (s2 === \"schematic_port\")\n return n2.find((e23) =\u003e e23.type === \"schematic_port\" \u0026\u0026 e23.source_port_id === r4.source_port_id);\n }\n } };\n } });\n return i3;\n};\nfunction vg(e20) {\n const t2 = e20.type;\n return `${t2}:${e20[`${t2}_id`]}`;\n}\nxg.unparsed = xg;\nvar Ig = (e20, t2 = {}) =\u003e {\n let n2 = e20._internal_store_indexed;\n if (!n2) {\n n2 = { counts: {}, editCount: 0, indexes: {} };\n for (const t3 of e20) {\n const e21 = t3.type, o4 = t3[`${e21}_id`];\n if (!o4)\n continue;\n const i4 = Number.parseInt(o4.split(\"_\").pop() || \"\");\n Number.isNaN(i4) || (n2.counts[e21] = Math.max(n2.counts[e21] ?? 0, i4));\n }\n const o3 = t2.indexConfig || {}, i3 = n2.indexes;\n if (o3.byId \u0026\u0026 (i3.byId = new Map), o3.byType \u0026\u0026 (i3.byType = new Map), o3.byRelation \u0026\u0026 (i3.byRelation = new Map), o3.bySubcircuit \u0026\u0026 (i3.bySubcircuit = new Map), o3.byCustomField \u0026\u0026 o3.byCustomField.length \u003e 0) {\n i3.byCustomField = new Map;\n for (const e21 of o3.byCustomField)\n i3.byCustomField.set(e21, new Map);\n }\n for (const t3 of e20) {\n if (o3.byId) {\n const e21 = vg(t3);\n i3.byId.set(e21, t3);\n }\n if (o3.byType) {\n const e21 = i3.byType.get(t3.type) || [];\n e21.push(t3), i3.byType.set(t3.type, e21);\n }\n if (o3.byRelation) {\n const e21 = Object.entries(t3);\n for (const [n3, o4] of e21)\n if (n3.endsWith(\"_id\") \u0026\u0026 n3 !== `${t3.type}_id` \u0026\u0026 typeof o4 == \"string\") {\n const e22 = i3.byRelation.get(n3) || new Map, r3 = e22.get(o4) || [];\n r3.push(t3), e22.set(o4, r3), i3.byRelation.set(n3, e22);\n }\n }\n if (o3.bySubcircuit \u0026\u0026 \"subcircuit_id\" in t3) {\n const e21 = t3.subcircuit_id;\n if (e21 \u0026\u0026 typeof e21 == \"string\") {\n const n3 = i3.bySubcircuit.get(e21) || [];\n n3.push(t3), i3.bySubcircuit.set(e21, n3);\n }\n }\n if (o3.byCustomField \u0026\u0026 i3.byCustomField) {\n for (const e21 of o3.byCustomField)\n if (e21 in t3) {\n const n3 = t3[e21];\n if (n3 !== undefined \u0026\u0026 (typeof n3 == \"string\" || typeof n3 == \"number\")) {\n const o4 = String(n3), r3 = i3.byCustomField.get(e21), s2 = r3.get(o4) || [];\n s2.push(t3), r3.set(o4, s2);\n }\n }\n }\n }\n e20._internal_store_indexed = n2;\n }\n return new Proxy({}, { get: (o3, i3) =\u003e {\n if (i3 === \"toArray\")\n return () =\u003e (e20.editCount = n2.editCount, e20);\n if (i3 === \"editCount\")\n return n2.editCount;\n const r3 = i3;\n return { get: (o4) =\u003e {\n const i4 = t2.indexConfig || {};\n if (i4.byId \u0026\u0026 n2.indexes.byId)\n return n2.indexes.byId.get(`${r3}:${o4}`) || null;\n if (i4.byType \u0026\u0026 n2.indexes.byType) {\n return (n2.indexes.byType.get(r3) || []).find((e21) =\u003e e21[`${r3}_id`] === o4) || null;\n }\n return e20.find((e21) =\u003e e21.type === r3 \u0026\u0026 e21[`${r3}_id`] === o4) || null;\n }, getUsing: (o4) =\u003e {\n const i4 = t2.indexConfig || {}, s2 = Object.keys(o4);\n if (s2.length !== 1)\n throw new Error(\"getUsing requires exactly one key, e.g. { pcb_component_id }\");\n const a3 = s2[0], c3 = a3.replace(\"_id\", \"\");\n if (i4.byRelation \u0026\u0026 n2.indexes.byRelation) {\n const t3 = n2.indexes.byRelation.get(a3);\n if (t3) {\n const s3 = (t3.get(o4[a3]) || []).find((e21) =\u003e e21.type === c3);\n if (!s3)\n return null;\n const l4 = s3[`${r3}_id`];\n if (i4.byId \u0026\u0026 n2.indexes.byId)\n return n2.indexes.byId.get(`${r3}:${l4}`) || null;\n if (i4.byType \u0026\u0026 n2.indexes.byType) {\n return (n2.indexes.byType.get(r3) || []).find((e21) =\u003e e21[`${r3}_id`] === l4) || null;\n }\n return e20.find((e21) =\u003e e21.type === r3 \u0026\u0026 e21[`${r3}_id`] === l4) || null;\n }\n }\n const l3 = e20.find((e21) =\u003e e21.type === c3 \u0026\u0026 e21[a3] === o4[a3]);\n return l3 \u0026\u0026 e20.find((e21) =\u003e e21.type === r3 \u0026\u0026 e21[`${r3}_id`] === l3[`${r3}_id`]) || null;\n }, getWhere: (o4) =\u003e {\n const i4 = t2.indexConfig || {}, s2 = Object.keys(o4);\n if (s2.length === 1 \u0026\u0026 i4.byCustomField \u0026\u0026 n2.indexes.byCustomField) {\n const e21 = s2[0], t3 = n2.indexes.byCustomField.get(e21);\n if (t3) {\n const n3 = String(o4[e21]);\n return (t3.get(n3) || []).find((e22) =\u003e e22.type === r3) || null;\n }\n }\n if (\"subcircuit_id\" in o4 \u0026\u0026 i4.bySubcircuit \u0026\u0026 n2.indexes.bySubcircuit) {\n const e21 = o4.subcircuit_id;\n return (n2.indexes.bySubcircuit.get(e21) || []).find((e22) =\u003e e22.type === r3 \u0026\u0026 s2.every((t3) =\u003e e22[t3] === o4[t3])) || null;\n }\n if (i4.byType \u0026\u0026 n2.indexes.byType) {\n return (n2.indexes.byType.get(r3) || []).find((e21) =\u003e s2.every((t3) =\u003e e21[t3] === o4[t3])) || null;\n }\n return e20.find((e21) =\u003e e21.type === r3 \u0026\u0026 s2.every((t3) =\u003e e21[t3] === o4[t3])) || null;\n }, list: (o4) =\u003e {\n const i4 = t2.indexConfig || {}, s2 = o4 ? Object.keys(o4) : [];\n if (s2.length === 0 \u0026\u0026 i4.byType \u0026\u0026 n2.indexes.byType)\n return n2.indexes.byType.get(r3) || [];\n if (s2.length === 1 \u0026\u0026 s2[0] === \"subcircuit_id\" \u0026\u0026 i4.bySubcircuit \u0026\u0026 n2.indexes.bySubcircuit) {\n const e21 = o4.subcircuit_id;\n return (n2.indexes.bySubcircuit.get(e21) || []).filter((e22) =\u003e e22.type === r3);\n }\n let a3;\n return a3 = i4.byType \u0026\u0026 n2.indexes.byType ? n2.indexes.byType.get(r3) || [] : e20.filter((e21) =\u003e e21.type === r3), s2.length \u003e 0 ? a3.filter((e21) =\u003e s2.every((t3) =\u003e e21[t3] === o4[t3])) : a3;\n }, insert: (o4) =\u003e {\n n2.counts[r3] ??= -1, n2.counts[r3]++;\n const i4 = n2.counts[r3], s2 = { type: r3, [`${r3}_id`]: `${r3}_${i4}`, ...o4 };\n if (t2.validateInserts) {\n (Ya[r3] ?? yg).parse(s2);\n }\n e20.push(s2), n2.editCount++;\n const a3 = t2.indexConfig || {};\n if (a3.byId \u0026\u0026 n2.indexes.byId) {\n const e21 = vg(s2);\n n2.indexes.byId.set(e21, s2);\n }\n if (a3.byType \u0026\u0026 n2.indexes.byType) {\n const e21 = n2.indexes.byType.get(r3) || [];\n e21.push(s2), n2.indexes.byType.set(r3, e21);\n }\n if (a3.byRelation \u0026\u0026 n2.indexes.byRelation) {\n const e21 = Object.entries(s2);\n for (const [t3, o5] of e21)\n if (t3.endsWith(\"_id\") \u0026\u0026 t3 !== `${s2.type}_id` \u0026\u0026 typeof o5 == \"string\") {\n const e22 = n2.indexes.byRelation.get(t3) || new Map, i5 = e22.get(o5) || [];\n i5.push(s2), e22.set(o5, i5), n2.indexes.byRelation.set(t3, e22);\n }\n }\n if (a3.bySubcircuit \u0026\u0026 n2.indexes.bySubcircuit \u0026\u0026 \"subcircuit_id\" in s2) {\n const e21 = s2.subcircuit_id;\n if (e21 \u0026\u0026 typeof e21 == \"string\") {\n const t3 = n2.indexes.bySubcircuit.get(e21) || [];\n t3.push(s2), n2.indexes.bySubcircuit.set(e21, t3);\n }\n }\n if (a3.byCustomField \u0026\u0026 n2.indexes.byCustomField) {\n for (const e21 of a3.byCustomField)\n if (e21 in s2) {\n const t3 = s2[e21];\n if (t3 !== undefined \u0026\u0026 (typeof t3 == \"string\" || typeof t3 == \"number\")) {\n const o5 = String(t3), i5 = n2.indexes.byCustomField.get(e21), r4 = i5.get(o5) || [];\n r4.push(s2), i5.set(o5, r4);\n }\n }\n }\n return s2;\n }, delete: (o4) =\u003e {\n const i4 = t2.indexConfig || {};\n let s2;\n if (i4.byId \u0026\u0026 n2.indexes.byId)\n s2 = n2.indexes.byId.get(`${r3}:${o4}`);\n else if (i4.byType \u0026\u0026 n2.indexes.byType) {\n const e21 = n2.indexes.byType.get(r3) || [];\n s2 = e21.find((e22) =\u003e e22[`${r3}_id`] === o4);\n } else\n s2 = e20.find((e21) =\u003e e21[`${r3}_id`] === o4);\n if (!s2)\n return;\n const a3 = e20.indexOf(s2);\n if (a3 \u003e= 0 \u0026\u0026 (e20.splice(a3, 1), n2.editCount++), i4.byId \u0026\u0026 n2.indexes.byId) {\n const e21 = vg(s2);\n n2.indexes.byId.delete(e21);\n }\n if (i4.byType \u0026\u0026 n2.indexes.byType) {\n const e21 = (n2.indexes.byType.get(r3) || []).filter((e22) =\u003e e22[`${r3}_id`] !== o4);\n n2.indexes.byType.set(r3, e21);\n }\n if (i4.byRelation \u0026\u0026 n2.indexes.byRelation)\n for (const [e21, t3] of n2.indexes.byRelation.entries())\n for (const [e22, n3] of t3.entries()) {\n const o5 = n3.filter((e23) =\u003e e23 !== s2);\n o5.length === 0 ? t3.delete(e22) : t3.set(e22, o5);\n }\n if (i4.bySubcircuit \u0026\u0026 n2.indexes.bySubcircuit \u0026\u0026 \"subcircuit_id\" in s2) {\n const e21 = s2.subcircuit_id;\n if (e21) {\n const t3 = (n2.indexes.bySubcircuit.get(e21) || []).filter((e22) =\u003e e22 !== s2);\n t3.length === 0 ? n2.indexes.bySubcircuit.delete(e21) : n2.indexes.bySubcircuit.set(e21, t3);\n }\n }\n if (i4.byCustomField \u0026\u0026 n2.indexes.byCustomField)\n for (const e21 of n2.indexes.byCustomField.values())\n for (const [t3, n3] of e21.entries()) {\n const o5 = n3.filter((e22) =\u003e e22 !== s2);\n o5.length === 0 ? e21.delete(t3) : e21.set(t3, o5);\n }\n }, update: (o4, i4) =\u003e {\n const s2 = t2.indexConfig || {};\n let a3;\n if (s2.byId \u0026\u0026 n2.indexes.byId)\n a3 = n2.indexes.byId.get(`${r3}:${o4}`);\n else if (s2.byType \u0026\u0026 n2.indexes.byType) {\n const e21 = n2.indexes.byType.get(r3) || [];\n a3 = e21.find((e22) =\u003e e22[`${r3}_id`] === o4);\n } else\n a3 = e20.find((e21) =\u003e e21.type === r3 \u0026\u0026 e21[`${r3}_id`] === o4);\n if (!a3)\n return null;\n if (s2.byRelation \u0026\u0026 n2.indexes.byRelation) {\n const e21 = Object.entries(a3);\n for (const [t3, o5] of e21)\n if (t3.endsWith(\"_id\") \u0026\u0026 t3 !== `${a3.type}_id` \u0026\u0026 typeof o5 == \"string\" \u0026\u0026 t3 in i4 \u0026\u0026 i4[t3] !== o5) {\n const e22 = n2.indexes.byRelation.get(t3);\n if (e22) {\n const t4 = (e22.get(o5) || []).filter((e23) =\u003e e23 !== a3);\n t4.length === 0 ? e22.delete(o5) : e22.set(o5, t4);\n }\n }\n }\n if (s2.bySubcircuit \u0026\u0026 n2.indexes.bySubcircuit \u0026\u0026 \"subcircuit_id\" in a3 \u0026\u0026 \"subcircuit_id\" in i4) {\n const e21 = a3.subcircuit_id;\n if (e21 !== i4.subcircuit_id) {\n const t3 = (n2.indexes.bySubcircuit.get(e21) || []).filter((e22) =\u003e e22 !== a3);\n t3.length === 0 ? n2.indexes.bySubcircuit.delete(e21) : n2.indexes.bySubcircuit.set(e21, t3);\n }\n }\n if (s2.byCustomField \u0026\u0026 n2.indexes.byCustomField) {\n for (const e21 of s2.byCustomField)\n if (e21 in a3 \u0026\u0026 e21 in i4 \u0026\u0026 a3[e21] !== i4[e21]) {\n const t3 = n2.indexes.byCustomField.get(e21);\n if (t3) {\n const n3 = String(a3[e21]), o5 = (t3.get(n3) || []).filter((e22) =\u003e e22 !== a3);\n o5.length === 0 ? t3.delete(n3) : t3.set(n3, o5);\n }\n }\n }\n if (Object.assign(a3, i4), n2.editCount++, s2.byRelation \u0026\u0026 n2.indexes.byRelation) {\n const e21 = Object.entries(a3);\n for (const [t3, o5] of e21)\n if (t3.endsWith(\"_id\") \u0026\u0026 t3 !== `${a3.type}_id` \u0026\u0026 typeof o5 == \"string\" \u0026\u0026 t3 in i4) {\n const e22 = n2.indexes.byRelation.get(t3) || new Map, i5 = e22.get(o5) || [];\n i5.includes(a3) || (i5.push(a3), e22.set(o5, i5), n2.indexes.byRelation.set(t3, e22));\n }\n }\n if (s2.bySubcircuit \u0026\u0026 n2.indexes.bySubcircuit \u0026\u0026 \"subcircuit_id\" in a3 \u0026\u0026 \"subcircuit_id\" in i4) {\n const e21 = a3.subcircuit_id;\n if (e21 \u0026\u0026 typeof e21 == \"string\") {\n const t3 = n2.indexes.bySubcircuit.get(e21) || [];\n t3.includes(a3) || (t3.push(a3), n2.indexes.bySubcircuit.set(e21, t3));\n }\n }\n if (s2.byCustomField \u0026\u0026 n2.indexes.byCustomField) {\n for (const e21 of s2.byCustomField)\n if (e21 in a3 \u0026\u0026 e21 in i4) {\n const t3 = a3[e21];\n if (t3 !== undefined \u0026\u0026 (typeof t3 == \"string\" || typeof t3 == \"number\")) {\n const o5 = String(t3), i5 = n2.indexes.byCustomField.get(e21), r4 = i5.get(o5) || [];\n r4.includes(a3) || (r4.push(a3), i5.set(o5, r4));\n }\n }\n }\n return a3;\n }, select: (t3) =\u003e {\n if (r3 === \"source_component\")\n return e20.find((e21) =\u003e e21.type === \"source_component\" \u0026\u0026 e21.name === t3.replace(/\\./g, \"\")) || null;\n if (r3 === \"pcb_port\" || r3 === \"source_port\" || r3 === \"schematic_port\") {\n const [n3, o4] = t3.replace(/\\./g, \"\").split(/[\\s\\\u003e]+/), i4 = e20.find((e21) =\u003e e21.type === \"source_component\" \u0026\u0026 e21.name === n3);\n if (!i4)\n return null;\n const s2 = e20.find((e21) =\u003e e21.type === \"source_port\" \u0026\u0026 e21.source_component_id === i4.source_component_id \u0026\u0026 (e21.name === o4 || (e21.port_hints ?? []).includes(o4)));\n if (!s2)\n return null;\n if (r3 === \"source_port\")\n return s2;\n if (r3 === \"pcb_port\")\n return e20.find((e21) =\u003e e21.type === \"pcb_port\" \u0026\u0026 e21.source_port_id === s2.source_port_id) || null;\n if (r3 === \"schematic_port\")\n return e20.find((e21) =\u003e e21.type === \"schematic_port\" \u0026\u0026 e21.source_port_id === s2.source_port_id) || null;\n }\n return null;\n } };\n } });\n};\nIg.unparsed = Ig;\nvar Sg = true;\nvar Cg = { CCW: -1, CW: 1, NOT_ORIENTABLE: 0 };\nvar Pg = 2 * Math.PI;\nvar Mg = Object.freeze({ __proto__: null, BOUNDARY: 2, CCW: Sg, CONTAINS: 3, CW: false, END_VERTEX: 2, INSIDE: 1, INTERLACE: 4, NOT_VERTEX: 0, ORIENTATION: Cg, OUTSIDE: 0, OVERLAP_OPPOSITE: 2, OVERLAP_SAME: 1, PIx2: Pg, START_VERTEX: 1 });\nvar wg = 0.000001;\nfunction Ng(e20) {\n wg = e20;\n}\nfunction Rg() {\n return wg;\n}\nfunction Tg(e20) {\n return e20 \u003c wg \u0026\u0026 e20 \u003e -wg;\n}\nfunction Eg(e20, t2) {\n return e20 - t2 \u003c wg \u0026\u0026 e20 - t2 \u003e -wg;\n}\nfunction Ag(e20, t2) {\n return e20 - t2 \u003e wg;\n}\nfunction Og(e20, t2) {\n return e20 - t2 \u003c -wg;\n}\nvar kg = { Utils: Object.freeze({ __proto__: null, DECIMALS: 3, EQ: Eg, EQ_0: Tg, GE: function(e20, t2) {\n return e20 - t2 \u003e -wg;\n}, GT: Ag, LE: function(e20, t2) {\n return e20 - t2 \u003c wg;\n}, LT: Og, getTolerance: Rg, setTolerance: Ng }), Errors: undefined, Matrix: undefined, Planar_set: undefined, Point: undefined, Vector: undefined, Line: undefined, Circle: undefined, Segment: undefined, Arc: undefined, Box: undefined, Edge: undefined, Face: undefined, Ray: undefined, Ray_shooting: undefined, Multiline: undefined, Polygon: undefined, Distance: undefined, Inversion: undefined };\nfor (let e20 in Mg)\n kg[e20] = Mg[e20];\nObject.defineProperty(kg, \"DP_TOL\", { get: function() {\n return Rg();\n}, set: function(e20) {\n Ng(e20);\n} });\nvar Dg = class {\n static get ILLEGAL_PARAMETERS() {\n return new ReferenceError(\"Illegal Parameters\");\n }\n static get ZERO_DIVISION() {\n return new Error(\"Zero division\");\n }\n static get UNRESOLVED_BOUNDARY_CONFLICT() {\n return new Error(\"Unresolved boundary conflict in boolean operation\");\n }\n static get INFINITE_LOOP() {\n return new Error(\"Infinite loop\");\n }\n static get CANNOT_COMPLETE_BOOLEAN_OPERATION() {\n return new Error(\"Cannot complete boolean operation\");\n }\n static get CANNOT_INVOKE_ABSTRACT_METHOD() {\n return new Error(\"Abstract method cannot be invoked\");\n }\n static get OPERATION_IS_NOT_SUPPORTED() {\n return new Error(\"Operation is not supported\");\n }\n static get UNSUPPORTED_SHAPE_TYPE() {\n return new Error(\"Unsupported shape type\");\n }\n};\nkg.Errors = Dg;\nvar Lg = class {\n constructor(e20, t2) {\n this.first = e20, this.last = t2 || this.first;\n }\n [Symbol.iterator]() {\n let e20;\n return { next: () =\u003e (e20 = e20 ? e20.next : this.first, { value: e20, done: e20 === undefined }) };\n }\n get size() {\n let e20 = 0;\n for (let t2 of this)\n e20++;\n return e20;\n }\n toArray(e20 = undefined, t2 = undefined) {\n let n2 = [], o3 = e20 || this.first, i3 = t2 || this.last, r3 = o3;\n if (r3 === undefined)\n return n2;\n do {\n n2.push(r3), r3 = r3.next;\n } while (r3 !== i3.next);\n return n2;\n }\n append(e20) {\n return this.isEmpty() ? this.first = e20 : (e20.prev = this.last, this.last.next = e20), this.last = e20, this.last.next = undefined, this.first.prev = undefined, this;\n }\n insert(e20, t2) {\n if (this.isEmpty())\n this.first = e20, this.last = e20;\n else if (t2 == null)\n e20.next = this.first, this.first.prev = e20, this.first = e20;\n else {\n let n2 = t2.next;\n t2.next = e20, n2 \u0026\u0026 (n2.prev = e20), e20.prev = t2, e20.next = n2, this.last === t2 \u0026\u0026 (this.last = e20);\n }\n return this.last.next = undefined, this.first.prev = undefined, this;\n }\n remove(e20) {\n return e20 === this.first \u0026\u0026 e20 === this.last ? (this.first = undefined, this.last = undefined) : (e20.prev \u0026\u0026 (e20.prev.next = e20.next), e20.next \u0026\u0026 (e20.next.prev = e20.prev), e20 === this.first \u0026\u0026 (this.first = e20.next), e20 === this.last \u0026\u0026 (this.last = e20.prev)), this;\n }\n isEmpty() {\n return this.first === undefined;\n }\n static testInfiniteLoop(e20) {\n let t2 = e20, n2 = e20;\n do {\n if (t2 != e20 \u0026\u0026 t2 === n2)\n throw Dg.INFINITE_LOOP;\n t2 = t2.next, n2 = n2.next.next;\n } while (t2 != e20);\n }\n};\nvar zg = { stroke: \"black\" };\nvar Bg = class {\n constructor(e20 = zg) {\n for (const t2 in e20)\n this[t2] = e20[t2];\n this.stroke = e20.stroke ?? zg.stroke;\n }\n toAttributesString() {\n return Object.keys(this).reduce((e20, t2) =\u003e e20 + (this[t2] !== undefined ? this.toAttrString(t2, this[t2]) : \"\"), \"\");\n }\n toAttrString(e20, t2) {\n const n2 = e20 === \"className\" ? \"class\" : this.convertCamelToKebabCase(e20);\n return t2 === null ? `${n2} ` : `${n2}=\"${t2.toString()}\" `;\n }\n convertCamelToKebabCase(e20) {\n return e20.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g).join(\"-\").toLowerCase();\n }\n};\nfunction Fg(e20) {\n return new Bg(e20).toAttributesString();\n}\nfunction jg(e20, t2) {\n let n2 = [], [o3, i3, r3] = e20.standard, [s2, a3, c3] = t2.standard, l3 = o3 * a3 - i3 * s2, h2 = r3 * a3 - i3 * c3, d2 = o3 * c3 - r3 * s2;\n if (!kg.Utils.EQ_0(l3)) {\n let e21, t3;\n i3 === 0 ? (e21 = r3 / o3, t3 = d2 / l3) : a3 === 0 ? (e21 = c3 / s2, t3 = d2 / l3) : o3 === 0 ? (e21 = h2 / l3, t3 = r3 / i3) : s2 === 0 ? (e21 = h2 / l3, t3 = c3 / a3) : (e21 = h2 / l3, t3 = d2 / l3), n2.push(new kg.Point(e21, t3));\n }\n return n2;\n}\nfunction $g(e20, t2) {\n let n2 = [], o3 = t2.pc.projectionOn(e20), i3 = t2.pc.distanceTo(o3)[0];\n if (kg.Utils.EQ(i3, t2.r))\n n2.push(o3);\n else if (kg.Utils.LT(i3, t2.r)) {\n let r3, s2, a3 = Math.sqrt(t2.r * t2.r - i3 * i3);\n r3 = e20.norm.rotate90CCW().multiply(a3), s2 = o3.translate(r3), n2.push(s2), r3 = e20.norm.rotate90CW().multiply(a3), s2 = o3.translate(r3), n2.push(s2);\n }\n return n2;\n}\nfunction Yg(e20, t2) {\n let n2 = [];\n for (let o3 of t2.toSegments()) {\n let t3 = Hg(o3, e20);\n for (let e21 of t3)\n hf(e21, n2) || n2.push(e21);\n }\n return n2;\n}\nfunction Xg(e20, t2) {\n let n2 = [];\n if (Yg(e20, t2.box).length === 0)\n return n2;\n let o3 = $g(e20, new kg.Circle(t2.pc, t2.r));\n for (let e21 of o3)\n e21.on(t2) \u0026\u0026 n2.push(e21);\n return n2;\n}\nfunction Hg(e20, t2) {\n let n2 = [];\n return e20.ps.on(t2) \u0026\u0026 n2.push(e20.ps), e20.pe.on(t2) \u0026\u0026 !e20.isZeroLength() \u0026\u0026 n2.push(e20.pe), n2.length \u003e 0 || e20.isZeroLength() || e20.ps.leftTo(t2) \u0026\u0026 e20.pe.leftTo(t2) || !e20.ps.leftTo(t2) \u0026\u0026 !e20.pe.leftTo(t2) ? n2 : jg(new kg.Line(e20.ps, e20.pe), t2);\n}\nfunction Vg(e20, t2) {\n let n2 = [];\n if (e20.isZeroLength())\n return e20.ps.on(t2) \u0026\u0026 n2.push(e20.ps), n2;\n if (t2.isZeroLength())\n return t2.ps.on(e20) \u0026\u0026 n2.push(t2.ps), n2;\n let o3 = new kg.Line(e20.ps, e20.pe), i3 = new kg.Line(t2.ps, t2.pe);\n if (o3.incidentTo(i3))\n e20.ps.on(t2) \u0026\u0026 n2.push(e20.ps), e20.pe.on(t2) \u0026\u0026 n2.push(e20.pe), !t2.ps.on(e20) || t2.ps.equalTo(e20.ps) || t2.ps.equalTo(e20.pe) || n2.push(t2.ps), !t2.pe.on(e20) || t2.pe.equalTo(e20.ps) || t2.pe.equalTo(e20.pe) || n2.push(t2.pe);\n else if (o3.parallelTo(i3)) {\n const o4 = new kg.Vector(e20.ps, e20.pe), i4 = new kg.Vector(t2.ps, t2.pe), r3 = new kg.Vector(e20.ps, t2.ps), s2 = o4.cross(i4);\n if (!kg.Utils.EQ_0(s2)) {\n const a3 = r3.cross(i4) / s2, c3 = r3.cross(o4) / s2;\n kg.Utils.GE(a3, 0) \u0026\u0026 kg.Utils.LE(a3, 1) \u0026\u0026 kg.Utils.GE(c3, 0) \u0026\u0026 kg.Utils.LE(c3, 1) \u0026\u0026 n2.push(Wg(e20.ps.translate(o4.multiply(a3)), e20, t2));\n }\n } else {\n let r3 = jg(o3, i3);\n r3.length \u003e 0 \u0026\u0026 Gg(r3[0], e20) \u0026\u0026 Gg(r3[0], t2) \u0026\u0026 n2.push(Wg(r3[0], e20, t2));\n }\n return n2;\n}\nfunction Wg(e20, t2, n2) {\n for (const o3 of [t2.ps, t2.pe, n2.ps, n2.pe])\n if (e20.equalTo(o3))\n return o3;\n return e20;\n}\nfunction Gg(e20, t2) {\n const n2 = t2.box;\n return kg.Utils.LE(e20.x, n2.xmax) \u0026\u0026 kg.Utils.GE(e20.x, n2.xmin) \u0026\u0026 kg.Utils.LE(e20.y, n2.ymax) \u0026\u0026 kg.Utils.GE(e20.y, n2.ymin);\n}\nfunction Ug(e20, t2) {\n let n2 = [];\n if (e20.isZeroLength()) {\n let [o4, i3] = e20.ps.distanceTo(t2.pc);\n return kg.Utils.EQ(o4, t2.r) \u0026\u0026 n2.push(e20.ps), n2;\n }\n let o3 = $g(new kg.Line(e20.ps, e20.pe), t2);\n for (let t3 of o3)\n t3.on(e20) \u0026\u0026 n2.push(t3);\n return n2;\n}\nfunction Zg(e20, t2) {\n let n2 = [];\n if (e20.isZeroLength())\n return e20.ps.on(t2) \u0026\u0026 n2.push(e20.ps), n2;\n let o3 = $g(new kg.Line(e20.ps, e20.pe), new kg.Circle(t2.pc, t2.r));\n for (let i3 of o3)\n i3.on(e20) \u0026\u0026 i3.on(t2) \u0026\u0026 n2.push(i3);\n return n2;\n}\nfunction qg(e20, t2) {\n let n2 = [], o3 = new kg.Vector(e20.pc, t2.pc), i3 = e20.r, r3 = t2.r;\n if (kg.Utils.EQ_0(i3) || kg.Utils.EQ_0(r3))\n return n2;\n if (kg.Utils.EQ_0(o3.x) \u0026\u0026 kg.Utils.EQ_0(o3.y) \u0026\u0026 kg.Utils.EQ(i3, r3))\n return n2.push(e20.pc.translate(-i3, 0)), n2;\n let s2, a3 = e20.pc.distanceTo(t2.pc)[0];\n if (kg.Utils.GT(a3, i3 + r3))\n return n2;\n if (kg.Utils.LT(a3, Math.abs(i3 - r3)))\n return n2;\n if (o3.x /= a3, o3.y /= a3, kg.Utils.EQ(a3, i3 + r3) || kg.Utils.EQ(a3, Math.abs(i3 - r3)))\n return s2 = e20.pc.translate(i3 * o3.x, i3 * o3.y), n2.push(s2), n2;\n let c3 = i3 * i3 / (2 * a3) - r3 * r3 / (2 * a3) + a3 / 2, l3 = e20.pc.translate(c3 * o3.x, c3 * o3.y), h2 = Math.sqrt(i3 * i3 - c3 * c3);\n return s2 = l3.translate(o3.rotate90CCW().multiply(h2)), n2.push(s2), s2 = l3.translate(o3.rotate90CW().multiply(h2)), n2.push(s2), n2;\n}\nfunction Jg(e20, t2) {\n let n2 = [];\n if (e20.pc.equalTo(t2.pc) \u0026\u0026 kg.Utils.EQ(e20.r, t2.r)) {\n let o4;\n return o4 = e20.start, o4.on(t2) \u0026\u0026 n2.push(o4), o4 = e20.end, o4.on(t2) \u0026\u0026 n2.push(o4), o4 = t2.start, o4.on(e20) \u0026\u0026 n2.push(o4), o4 = t2.end, o4.on(e20) \u0026\u0026 n2.push(o4), n2;\n }\n let o3 = new kg.Circle(e20.pc, e20.r), i3 = new kg.Circle(t2.pc, t2.r), r3 = o3.intersect(i3);\n for (let o4 of r3)\n o4.on(e20) \u0026\u0026 o4.on(t2) \u0026\u0026 n2.push(o4);\n return n2;\n}\nfunction Qg(e20, t2) {\n let n2 = [];\n if (t2.pc.equalTo(e20.pc) \u0026\u0026 kg.Utils.EQ(t2.r, e20.r))\n return n2.push(e20.start), n2.push(e20.end), n2;\n let o3 = qg(t2, new kg.Circle(e20.pc, e20.r));\n for (let t3 of o3)\n t3.on(e20) \u0026\u0026 n2.push(t3);\n return n2;\n}\nfunction Kg(e20, t2) {\n return e20.isSegment ? Vg(e20.shape, t2) : Zg(t2, e20.shape);\n}\nfunction ef(e20, t2) {\n return e20.isSegment ? Zg(e20.shape, t2) : Jg(e20.shape, t2);\n}\nfunction tf(e20, t2) {\n return e20.isSegment ? Hg(e20.shape, t2) : Xg(t2, e20.shape);\n}\nfunction nf(e20, t2) {\n return e20.isSegment ? Ug(e20.shape, t2) : Qg(e20.shape, t2);\n}\nfunction of(e20, t2) {\n let n2 = [];\n for (let o3 of t2.edges)\n for (let t3 of Kg(o3, e20))\n n2.push(t3);\n return n2;\n}\nfunction rf(e20, t2) {\n let n2 = [];\n for (let o3 of t2.edges)\n for (let t3 of ef(o3, e20))\n n2.push(t3);\n return n2;\n}\nfunction sf(e20, t2) {\n let n2 = [];\n if (t2.isEmpty())\n return n2;\n for (let o3 of t2.edges)\n for (let t3 of tf(o3, e20))\n hf(t3, n2) || n2.push(t3);\n return e20.sortPoints(n2);\n}\nfunction af(e20, t2) {\n let n2 = [];\n if (t2.isEmpty())\n return n2;\n for (let o3 of t2.edges)\n for (let t3 of nf(o3, e20))\n n2.push(t3);\n return n2;\n}\nfunction cf(e20, t2) {\n return e20.isSegment ? Kg(t2, e20.shape) : e20.isArc ? ef(t2, e20.shape) : e20.isLine ? tf(t2, e20.shape) : e20.isRay ? (n2 = t2, o3 = e20.shape, n2.isSegment ? uf(o3, n2.shape) : pf(o3, n2.shape)) : [];\n var n2, o3;\n}\nfunction lf(e20, t2) {\n let n2 = [];\n if (t2.isEmpty() || e20.shape.box.not_intersect(t2.box))\n return n2;\n let o3 = t2.edges.search(e20.shape.box);\n for (let t3 of o3)\n n2 = [...n2, ...cf(e20, t3)];\n return n2;\n}\nfunction hf(e20, t2) {\n return t2.some((t3) =\u003e t3.equalTo(e20));\n}\nfunction df(e20) {\n return new kg.Line(e20.start, e20.norm);\n}\nfunction uf(e20, t2) {\n return Hg(t2, df(e20)).filter((t3) =\u003e e20.contains(t3));\n}\nfunction pf(e20, t2) {\n return Xg(df(e20), t2).filter((t3) =\u003e e20.contains(t3));\n}\nfunction mf(e20, t2) {\n return $g(df(e20), t2).filter((t3) =\u003e e20.contains(t3));\n}\nfunction gf(e20, t2) {\n return jg(df(e20), t2).filter((t3) =\u003e e20.contains(t3));\n}\nfunction ff(e20, t2) {\n return sf(df(e20), t2).filter((t3) =\u003e e20.contains(t3));\n}\nfunction _f(e20, t2) {\n if (e20.intersect \u0026\u0026 e20.intersect instanceof Function)\n return e20.intersect(t2);\n throw Dg.UNSUPPORTED_SHAPE_TYPE;\n}\nfunction yf(e20, t2) {\n let n2 = [];\n for (let o3 of t2)\n n2 = [...n2, ..._f(e20, o3.shape)];\n return n2;\n}\nvar bf = class e20 extends Lg {\n constructor(...e21) {\n if (super(), this.isInfinite = false, e21.length === 1 \u0026\u0026 e21[0] instanceof Array \u0026\u0026 e21[0].length \u003e 0) {\n const t2 = e21[0], n2 = t2.length, o3 = (e22) =\u003e e22 instanceof kg.Segment || e22 instanceof kg.Arc || e22 instanceof kg.Ray, i3 = (e22) =\u003e e22 instanceof kg.Segment || e22 instanceof kg.Arc;\n if (!(n2 === 1 \u0026\u0026 ((e22) =\u003e e22 instanceof kg.Segment || e22 instanceof kg.Arc || e22 instanceof kg.Ray || e22 instanceof kg.Line)(t2[0]) || n2 \u003e 1 \u0026\u0026 o3(t2[0]) \u0026\u0026 o3(t2[n2 - 1]) \u0026\u0026 t2.slice(1, n2 - 1).every(i3)))\n throw kg.Errors.ILLEGAL_PARAMETERS;\n this.isInfinite = t2.some((e22) =\u003e e22 instanceof kg.Ray || e22 instanceof kg.Line);\n for (let e22 of t2) {\n let t3 = new kg.Edge(e22);\n this.append(t3);\n }\n this.setArcLength();\n }\n }\n get edges() {\n return [...this];\n }\n get box() {\n return this.edges.reduce((e21, t2) =\u003e e21.merge(t2.box), new kg.Box);\n }\n get vertices() {\n let e21 = this.edges.map((e22) =\u003e e22.start);\n return e21.push(this.last.end), e21;\n }\n get length() {\n if (this.isEmpty())\n return 0;\n if (this.isInfinite)\n return Number.POSITIVE_INFINITY;\n let e21 = 0;\n for (let t2 of this)\n e21 += t2.length;\n return e21;\n }\n clone() {\n return new e20(this.toShapes());\n }\n setArcLength() {\n for (let e21 of this)\n this.setOneEdgeArcLength(e21);\n }\n setOneEdgeArcLength(e21) {\n e21 === this.first ? e21.arc_length = 0 : e21.arc_length = e21.prev.arc_length + e21.prev.length;\n }\n pointAtLength(e21) {\n if (e21 \u003e this.length || e21 \u003c 0)\n return null;\n if (this.isInfinite)\n return null;\n let t2 = null;\n for (let n2 of this)\n if (e21 \u003e= n2.arc_length \u0026\u0026 (n2 === this.last || e21 \u003c n2.next.arc_length)) {\n t2 = n2.pointAtLength(e21 - n2.arc_length);\n break;\n }\n return t2;\n }\n addVertex(e21, t2) {\n let n2 = t2.shape.split(e21);\n if (n2[0] === null)\n return t2.prev;\n if (n2[1] === null)\n return t2;\n let o3 = new kg.Edge(n2[0]), i3 = t2.prev;\n return this.insert(o3, i3), t2.shape = n2[1], o3;\n }\n getChain(e21, t2) {\n let n2 = [];\n for (let o3 = e21;o3 !== t2.next; o3 = o3.next)\n n2.push(o3);\n return n2;\n }\n split(e21) {\n for (let t2 of e21) {\n let e22 = this.findEdgeByPoint(t2);\n this.addVertex(t2, e22);\n }\n return this;\n }\n findEdgeByPoint(e21) {\n let t2;\n for (let n2 of this)\n if (n2.shape.contains(e21)) {\n t2 = n2;\n break;\n }\n return t2;\n }\n distanceTo(e21) {\n if (e21 instanceof kg.Point) {\n const [t2, n2] = kg.Distance.shape2multiline(e21, this);\n return [t2, n2.reverse()];\n }\n if (e21 instanceof kg.Line) {\n const [t2, n2] = kg.Distance.shape2multiline(e21, this);\n return [t2, n2.reverse()];\n }\n if (e21 instanceof kg.Circle) {\n const [t2, n2] = kg.Distance.shape2multiline(e21, this);\n return [t2, n2.reverse()];\n }\n if (e21 instanceof kg.Segment) {\n const [t2, n2] = kg.Distance.shape2multiline(e21, this);\n return [t2, n2.reverse()];\n }\n if (e21 instanceof kg.Arc) {\n const [t2, n2] = kg.Distance.shape2multiline(e21, this);\n return [t2, n2.reverse()];\n }\n if (e21 instanceof kg.Box) {\n const [t2, n2] = kg.Distance.shape2multiline(new kg.Polygon(e21), this);\n return [t2, n2.reverse()];\n }\n if (e21 instanceof kg.Multiline)\n return kg.Distance.multiline2multiline(this, e21);\n throw kg.Errors.UNSUPPORTED_SHAPE_TYPE;\n }\n intersect(e21) {\n return e21 instanceof kg.Multiline ? function(e22, t2) {\n let n2 = [];\n for (let o3 of e22)\n for (let e23 of t2)\n n2 = [...n2, ..._f(o3.shape, e23.shape)];\n return n2;\n }(this, e21) : yf(e21, this);\n }\n contains(e21) {\n if (e21 instanceof kg.Point)\n return this.edges.some((t2) =\u003e t2.shape.contains(e21));\n throw kg.Errors.UNSUPPORTED_SHAPE_TYPE;\n }\n translate(t2) {\n return new e20(this.edges.map((e21) =\u003e e21.shape.translate(t2)));\n }\n rotate(t2 = 0, n2 = new kg.Point) {\n return new e20(this.edges.map((e21) =\u003e e21.shape.rotate(t2, n2)));\n }\n transform(t2 = new kg.Matrix) {\n return new e20(this.edges.map((e21) =\u003e e21.shape.transform(t2)));\n }\n toShapes() {\n return this.edges.map((e21) =\u003e e21.shape.clone());\n }\n toJSON() {\n return this.edges.map((e21) =\u003e e21.toJSON());\n }\n svgPoints() {\n return this.vertices.map((e21) =\u003e `${e21.x},${e21.y}`).join(\" \");\n }\n dpath() {\n let e21 = `M${this.first.start.x},${this.first.start.y}`;\n for (let t2 of this)\n e21 += t2.svg();\n return e21;\n }\n svg(e21 = {}) {\n let t2 = `\n\u003cpath ${Fg({ fill: \"none\", ...e21 })} d=\"`;\n t2 += `\nM${this.first.start.x},${this.first.start.y}`;\n for (let e22 of this)\n t2 += e22.svg();\n return t2 += `\" \u003e\n\u003c/path\u003e`, t2;\n }\n};\nkg.Multiline = bf;\nfunction xf(e21, t2, n2) {\n let o3 = n2.length, i3 = e21.shape.split(t2);\n if (i3.length === 0)\n return;\n let r3 = 0;\n r3 = i3[0] === null ? 0 : i3[1] === null ? e21.shape.length : i3[0].length;\n let s2, a3 = 0;\n Eg(r3, 0) \u0026\u0026 (a3 |= 1), Eg(r3, e21.shape.length) \u0026\u0026 (a3 |= 2), s2 = r3 === 1 / 0 ? i3[0].coord(t2) : 2 \u0026 a3 \u0026\u0026 e21.next \u0026\u0026 e21.next.arc_length === 0 ? 0 : e21.arc_length + r3, n2.push({ id: o3, pt: t2, arc_length: s2, edge_before: e21, edge_after: undefined, face: e21.face, is_vertex: a3 });\n}\nfunction vf(e21) {\n e21.int_points1_sorted = If(e21.int_points1), e21.int_points2_sorted = If(e21.int_points2);\n}\nfunction If(e21) {\n let t2 = new Map, n2 = 0;\n for (let o3 of e21)\n t2.has(o3.face) || (t2.set(o3.face, n2), n2++);\n for (let n3 of e21)\n n3.faceId = t2.get(n3.face);\n return e21.slice().sort(Sf);\n}\nfunction Sf(e21, t2) {\n return e21.faceId \u003c t2.faceId ? -1 : e21.faceId \u003e t2.faceId ? 1 : e21.arc_length \u003c t2.arc_length ? -1 : e21.arc_length \u003e t2.arc_length ? 1 : 0;\n}\nfunction Cf(e21) {\n if (e21.int_points1.length \u003c 2)\n return;\n let t2, n2, o3, i3, r3 = false;\n for (let s2 = 0;s2 \u003c e21.int_points1_sorted.length; s2++)\n if (e21.int_points1_sorted[s2].id !== -1) {\n t2 = e21.int_points1_sorted[s2], n2 = e21.int_points2[t2.id];\n for (let a3 = s2 + 1;a3 \u003c e21.int_points1_sorted.length \u0026\u0026 (o3 = e21.int_points1_sorted[a3], Eg(o3.arc_length, t2.arc_length)); a3++)\n o3.id !== -1 \u0026\u0026 (i3 = e21.int_points2[o3.id], i3.id !== -1 \u0026\u0026 o3.edge_before === t2.edge_before \u0026\u0026 o3.edge_after === t2.edge_after \u0026\u0026 i3.edge_before === n2.edge_before \u0026\u0026 i3.edge_after === n2.edge_after \u0026\u0026 (o3.id = -1, i3.id = -1, r3 = true));\n }\n n2 = e21.int_points2_sorted[0], t2 = e21.int_points1[n2.id];\n for (let o4 = 1;o4 \u003c e21.int_points2_sorted.length; o4++) {\n let i4 = e21.int_points2_sorted[o4];\n if (i4.id === -1)\n continue;\n if (n2.id === -1 || !Eg(i4.arc_length, n2.arc_length)) {\n n2 = i4, t2 = e21.int_points1[n2.id];\n continue;\n }\n let s2 = e21.int_points1[i4.id];\n s2.edge_before === t2.edge_before \u0026\u0026 s2.edge_after === t2.edge_after \u0026\u0026 i4.edge_before === n2.edge_before \u0026\u0026 i4.edge_after === n2.edge_after \u0026\u0026 (s2.id = -1, i4.id = -1, r3 = true);\n }\n r3 \u0026\u0026 (e21.int_points1 = e21.int_points1.filter((e22) =\u003e e22.id \u003e= 0), e21.int_points2 = e21.int_points2.filter((e22) =\u003e e22.id \u003e= 0), e21.int_points1.forEach((e22, t3) =\u003e e22.id = t3), e21.int_points2.forEach((e22, t3) =\u003e e22.id = t3));\n}\nfunction Pf(e21) {\n for (let t2 of e21)\n t2.edge_before \u0026\u0026 (t2.edge_before.bvStart = undefined, t2.edge_before.bvEnd = undefined, t2.edge_before.bv = undefined, t2.edge_before.overlap = undefined), t2.edge_after \u0026\u0026 (t2.edge_after.bvStart = undefined, t2.edge_after.bvEnd = undefined, t2.edge_after.bv = undefined, t2.edge_after.overlap = undefined);\n for (let t2 of e21)\n t2.edge_before \u0026\u0026 (t2.edge_before.bvEnd = 2), t2.edge_after \u0026\u0026 (t2.edge_after.bvStart = 2);\n}\nfunction Mf(e21, t2) {\n for (let n2 of e21)\n n2.edge_before \u0026\u0026 n2.edge_before.setInclusion(t2), n2.edge_after \u0026\u0026 n2.edge_after.setInclusion(t2);\n}\nfunction wf(e21, t2, n2) {\n let o3, i3, r3 = 1;\n if (e21.length === 1)\n return 1;\n o3 = e21[t2];\n for (let s2 = t2 + 1;s2 \u003c e21.length \u0026\u0026 o3.face === n2 \u0026\u0026 (i3 = e21[s2], i3.pt.equalTo(o3.pt) \u0026\u0026 i3.edge_before === o3.edge_before \u0026\u0026 i3.edge_after === o3.edge_after); s2++)\n r3++;\n return r3;\n}\nfunction Nf(e21, t2) {\n if (t2) {\n for (let n2 of t2) {\n let t3 = n2.edge_before;\n if (n2.is_vertex = 0, t3.shape.start \u0026\u0026 t3.shape.start.equalTo(n2.pt) \u0026\u0026 (n2.is_vertex |= 1), t3.shape.end \u0026\u0026 t3.shape.end.equalTo(n2.pt) \u0026\u0026 (n2.is_vertex |= 2), 1 \u0026 n2.is_vertex) {\n n2.edge_before = t3.prev, t3.prev \u0026\u0026 (n2.is_vertex = 2);\n continue;\n }\n if (2 \u0026 n2.is_vertex)\n continue;\n let o3 = e21.addVertex(n2.pt, t3);\n n2.edge_before = o3;\n }\n for (let n2 of t2)\n n2.edge_before ? n2.edge_after = n2.edge_before.next : e21 instanceof bf \u0026\u0026 1 \u0026 n2.is_vertex \u0026\u0026 (n2.edge_after = e21.first);\n }\n}\nfunction Rf(e21, t2, n2) {\n const o3 = e21.edge_before, i3 = t2.edge_after, r3 = n2.length;\n o3.next = n2[0], n2[0].prev = o3, n2[r3 - 1].next = i3, i3.prev = n2[r3 - 1];\n}\nkg.multiline = (...e21) =\u003e new kg.Multiline(...e21);\nvar { INSIDE: Tf, OUTSIDE: Ef, BOUNDARY: Af, OVERLAP_SAME: Of, OVERLAP_OPPOSITE: kf } = Mg;\nvar { NOT_VERTEX: Df, START_VERTEX: Lf, END_VERTEX: zf } = Mg;\nfunction Bf(e21, t2) {\n let n2 = t2.clone().reverse(), [o3, i3] = Hf(e21, n2, 3, true);\n return o3;\n}\nfunction Ff(e21, t2) {\n let [n2, o3] = Hf(e21, t2, 2, true);\n return n2;\n}\nfunction jf(e21, t2) {\n let [n2, o3] = Hf(e21, t2, 2, false), i3 = [];\n for (let e22 of n2.faces)\n i3 = [...i3, ...[...e22.edges].map((e23) =\u003e e23.shape)];\n let r3 = [];\n for (let e22 of o3.faces)\n r3 = [...r3, ...[...e22.edges].map((e23) =\u003e e23.shape)];\n return [i3, r3];\n}\nfunction $f(e21, t2) {\n let [n2, o3] = Hf(e21, t2, 3, false), i3 = [];\n for (let e22 of n2.faces)\n i3 = [...i3, ...[...e22.edges].map((e23) =\u003e e23.shape)];\n return i3;\n}\nfunction Yf(e21, t2) {\n let n2 = e21.clone(), o3 = t2.clone(), i3 = Vf(n2, o3);\n return vf(i3), Nf(n2, i3.int_points1_sorted), Nf(o3, i3.int_points2_sorted), Cf(i3), vf(i3), [i3.int_points1_sorted.map((e22) =\u003e e22.pt), i3.int_points2_sorted.map((e22) =\u003e e22.pt)];\n}\nfunction Xf(e21, t2, n2, o3) {\n let i3 = Wf(e21, n2.int_points1), r3 = Wf(t2, n2.int_points2);\n for (Gf(i3, t2), Gf(r3, e21), Pf(n2.int_points1), Pf(n2.int_points2), Mf(n2.int_points1, t2), Mf(n2.int_points2, e21);Uf(e21, t2, n2.int_points1, n2.int_points1_sorted, n2.int_points2, n2); )\n ;\n (function(e22) {\n let t3, n3, o4, i4 = e22.int_points1.length;\n for (let r4 = 0;r4 \u003c i4; r4++) {\n let s2 = e22.int_points1_sorted[r4];\n s2.face !== t3 \u0026\u0026 (n3 = r4, t3 = s2.face);\n let a3, c3 = r4, l3 = wf(e22.int_points1_sorted, r4, t3);\n a3 = c3 + l3 \u003c i4 \u0026\u0026 e22.int_points1_sorted[c3 + l3].face === t3 ? c3 + l3 : n3;\n let h2 = wf(e22.int_points1_sorted, a3, t3);\n o4 = null;\n for (let n4 = a3;n4 \u003c a3 + h2; n4++) {\n let i5 = e22.int_points1_sorted[n4];\n if (i5.face === t3 \u0026\u0026 e22.int_points2[i5.id].face === e22.int_points2[s2.id].face) {\n o4 = i5;\n break;\n }\n }\n if (o4 === null)\n continue;\n let d2 = s2.edge_after, u2 = o4.edge_before;\n if (d2.bv !== 2 || u2.bv !== 2)\n continue;\n if (d2 !== u2)\n continue;\n let p3 = e22.int_points2[s2.id], m2 = e22.int_points2[o4.id], g2 = p3.edge_after, f2 = m2.edge_before;\n g2.bv === 2 \u0026\u0026 f2.bv === 2 \u0026\u0026 g2 === f2 || (p3 = e22.int_points2[o4.id], m2 = e22.int_points2[s2.id], g2 = p3.edge_after, f2 = m2.edge_before), g2.bv === 2 \u0026\u0026 f2.bv === 2 \u0026\u0026 g2 === f2 \u0026\u0026 d2.setOverlap(g2);\n }\n })(n2), Zf(e21, o3, n2.int_points1_sorted, true), Zf(t2, o3, n2.int_points2_sorted, false), Qf(e21, i3, o3, true), Qf(t2, r3, o3, false);\n}\nfunction Hf(e21, t2, n2, o3) {\n let i3 = e21.clone(), r3 = t2.clone(), s2 = Vf(i3, r3);\n return vf(s2), Nf(i3, s2.int_points1_sorted), Nf(r3, s2.int_points2_sorted), Cf(s2), vf(s2), Xf(i3, r3, s2, n2), o3 \u0026\u0026 function(e22, t3, n3) {\n (function(e23, t4, n4, o4) {\n for (let n5 of t4.faces) {\n for (let t5 of n5)\n e23.edges.add(t5);\n o4.find((e24) =\u003e e24.face === n5) === undefined \u0026\u0026 e23.addFace(n5.first, n5.last);\n }\n })(e22, t3, 0, n3.int_points2), function(e23, t4, n4) {\n if (n4.int_points1.length !== 0)\n for (let e24 = 0;e24 \u003c n4.int_points1.length; e24++) {\n let t5 = n4.int_points1[e24], o4 = n4.int_points2[e24];\n if (t5.edge_before !== undefined \u0026\u0026 t5.edge_after === undefined \u0026\u0026 o4.edge_before === undefined \u0026\u0026 o4.edge_after !== undefined \u0026\u0026 (t5.edge_before.next = o4.edge_after, o4.edge_after.prev = t5.edge_before, t5.edge_after = o4.edge_after, o4.edge_before = t5.edge_before), o4.edge_before !== undefined \u0026\u0026 o4.edge_after === undefined \u0026\u0026 t5.edge_before === undefined \u0026\u0026 t5.edge_after !== undefined \u0026\u0026 (o4.edge_before.next = t5.edge_after, t5.edge_after.prev = o4.edge_before, o4.edge_after = t5.edge_after, t5.edge_before = o4.edge_before), t5.edge_before !== undefined \u0026\u0026 t5.edge_after === undefined)\n for (let e25 of n4.int_points1_sorted)\n e25 !== t5 \u0026\u0026 e25.edge_before === undefined \u0026\u0026 e25.edge_after !== undefined \u0026\u0026 e25.pt.equalTo(t5.pt) \u0026\u0026 (t5.edge_before.next = e25.edge_after, e25.edge_after.prev = t5.edge_before, t5.edge_after = e25.edge_after, e25.edge_before = t5.edge_before);\n if (o4.edge_before !== undefined \u0026\u0026 o4.edge_after === undefined)\n for (let e25 of n4.int_points2_sorted)\n e25 !== o4 \u0026\u0026 e25.edge_before === undefined \u0026\u0026 e25.edge_after !== undefined \u0026\u0026 e25.pt.equalTo(o4.pt) \u0026\u0026 (o4.edge_before.next = e25.edge_after, e25.edge_after.prev = o4.edge_before, o4.edge_after = e25.edge_after, e25.edge_before = o4.edge_before);\n }\n }(0, 0, n3), qf(e22, n3.int_points1), qf(t3, n3.int_points2), Jf(e22, n3.int_points1, n3.int_points2), Jf(e22, n3.int_points2, n3.int_points1), Kf(e22), Kf(t3);\n }(i3, r3, s2), [i3, r3];\n}\nfunction Vf(e21, t2) {\n let n2 = { int_points1: [], int_points2: [] };\n for (let o3 of e21.edges) {\n let e22 = t2.edges.search(o3.box);\n for (let t3 of e22) {\n let e23 = o3.shape.intersect(t3.shape);\n for (let i3 of e23)\n xf(o3, i3, n2.int_points1), xf(t3, i3, n2.int_points2);\n }\n }\n return n2;\n}\nfunction Wf(e21, t2) {\n let n2 = [];\n for (let o3 of e21.faces)\n t2.find((e22) =\u003e e22.face === o3) || n2.push(o3);\n return n2;\n}\nfunction Gf(e21, t2) {\n for (let n2 of e21)\n n2.first.bv = n2.first.bvStart = n2.first.bvEnd = undefined, n2.first.setInclusion(t2);\n}\nfunction Uf(e21, t2, n2, o3, i3, r3) {\n let s2, a3, c3, l3 = o3.length, h2 = false;\n for (let d2 = 0;d2 \u003c l3; d2++) {\n let u2 = o3[d2];\n u2.face !== s2 \u0026\u0026 (a3 = d2, s2 = u2.face);\n let p3, m2 = d2, g2 = wf(o3, d2, s2);\n p3 = m2 + g2 \u003c l3 \u0026\u0026 o3[m2 + g2].face === s2 ? m2 + g2 : a3;\n let f2 = wf(o3, p3, s2);\n c3 = null;\n for (let e22 = p3;e22 \u003c p3 + f2; e22++) {\n let t3 = o3[e22];\n if (t3.face === s2 \u0026\u0026 i3[t3.id].face === i3[u2.id].face) {\n c3 = t3;\n break;\n }\n }\n if (c3 === null)\n continue;\n let _2 = u2.edge_after, y2 = c3.edge_before;\n if (_2.bv !== Af || y2.bv == Af)\n if (_2.bv == Af || y2.bv !== Af) {\n if (_2.bv === Af \u0026\u0026 y2.bv === Af \u0026\u0026 _2 != y2 || _2.bv === Tf \u0026\u0026 y2.bv === Ef || _2.bv === Ef \u0026\u0026 y2.bv === Tf) {\n let e22 = _2.next;\n for (;e22 != y2; )\n e22.bvStart = undefined, e22.bvEnd = undefined, e22.bv = undefined, e22.setInclusion(t2), e22 = e22.next;\n }\n if (_2.bv === Af \u0026\u0026 y2.bv === Af \u0026\u0026 _2 != y2) {\n let e22, t3 = _2.next;\n for (;t3 != y2; ) {\n if (t3.bv != Af) {\n if (e22 === undefined)\n e22 = t3.bv;\n else if (t3.bv != e22)\n throw Dg.UNRESOLVED_BOUNDARY_CONFLICT;\n }\n t3 = t3.next;\n }\n e22 != null \u0026\u0026 (_2.bv = e22, y2.bv = e22);\n continue;\n }\n if (_2.bv === Tf \u0026\u0026 y2.bv === Ef || _2.bv === Ef \u0026\u0026 y2.bv === Tf) {\n let o4 = _2;\n for (;o4 != y2; ) {\n if (o4.bvStart === _2.bv \u0026\u0026 o4.bvEnd === y2.bv) {\n let [s3, a4] = o4.shape.distanceTo(t2);\n if (s3 \u003c 10 * kg.DP_TOL) {\n xf(o4, a4.ps, n2);\n let s4 = n2[n2.length - 1];\n if (s4.is_vertex \u0026 Lf)\n s4.edge_after = o4, s4.edge_before = o4.prev, o4.bvStart = Af, o4.bv = undefined, o4.setInclusion(t2);\n else if (s4.is_vertex \u0026 zf)\n s4.edge_after = o4.next, o4.bvEnd = Af, o4.bv = undefined, o4.setInclusion(t2);\n else {\n let e22 = t2.addVertex(s4.pt, o4);\n s4.edge_before = e22, s4.edge_after = e22.next, e22.setInclusion(t2), e22.next.bvStart = Af, e22.next.bvEnd = undefined, e22.next.bv = undefined, e22.next.setInclusion(t2);\n }\n let c4 = t2.findEdgeByPoint(a4.pe);\n xf(c4, a4.pe, i3);\n let l4 = i3[i3.length - 1];\n if (l4.is_vertex \u0026 Lf)\n l4.edge_after = c4, l4.edge_before = c4.prev;\n else if (l4.is_vertex \u0026 zf)\n l4.edge_after = c4.next;\n else {\n let n3 = i3.find((e22) =\u003e e22.edge_after === c4), o5 = t2.addVertex(l4.pt, c4);\n l4.edge_before = o5, l4.edge_after = o5.next, n3 \u0026\u0026 (n3.edge_after = o5), o5.bvStart = undefined, o5.bvEnd = Af, o5.bv = undefined, o5.setInclusion(e21), o5.next.bvStart = Af, o5.next.bvEnd = undefined, o5.next.bv = undefined, o5.next.setInclusion(e21);\n }\n vf(r3), h2 = true;\n break;\n }\n }\n o4 = o4.next;\n }\n if (h2)\n break;\n throw Dg.UNRESOLVED_BOUNDARY_CONFLICT;\n }\n } else\n y2.bv = _2.bv;\n else\n _2.bv = y2.bv;\n }\n return h2;\n}\nfunction Zf(e21, t2, n2, o3) {\n if (!n2)\n return;\n let i3, r3, s2, a3;\n for (let c3 = 0;c3 \u003c n2.length; c3++) {\n if (s2 = n2[c3], s2.face !== i3 \u0026\u0026 (r3 = c3, i3 = s2.face), i3.isEmpty())\n continue;\n let l3, h2 = c3, d2 = wf(n2, c3, i3);\n l3 = h2 + d2 \u003c n2.length \u0026\u0026 n2[h2 + d2].face === s2.face ? h2 + d2 : r3, a3 = n2[l3];\n let u2 = l3, p3 = wf(n2, u2, i3), m2 = s2.edge_after, g2 = a3.edge_before;\n if (m2.bv === Tf \u0026\u0026 g2.bv === Tf \u0026\u0026 t2 === 1 || m2.bv === Ef \u0026\u0026 g2.bv === Ef \u0026\u0026 t2 === 2 || (m2.bv === Ef || g2.bv === Ef) \u0026\u0026 t2 === 3 \u0026\u0026 !o3 || (m2.bv === Tf || g2.bv === Tf) \u0026\u0026 t2 === 3 \u0026\u0026 o3 || m2.bv === Af \u0026\u0026 g2.bv === Af \u0026\u0026 m2.overlap \u0026 Of \u0026\u0026 o3 || m2.bv === Af \u0026\u0026 g2.bv === Af \u0026\u0026 m2.overlap \u0026 kf) {\n e21.removeChain(i3, m2, g2);\n for (let e22 = h2;e22 \u003c h2 + d2; e22++)\n n2[e22].edge_after = undefined;\n for (let e22 = u2;e22 \u003c u2 + p3; e22++)\n n2[e22].edge_before = undefined;\n }\n c3 += d2 - 1;\n }\n}\nfunction qf(e21, t2) {\n for (let n2 of t2)\n e21.faces.delete(n2.face), n2.face = undefined, n2.edge_before \u0026\u0026 (n2.edge_before.face = undefined), n2.edge_after \u0026\u0026 (n2.edge_after.face = undefined);\n}\nfunction Jf(e21, t2, n2) {\n for (let o3 of t2) {\n if (o3.edge_before === undefined || o3.edge_after === undefined)\n continue;\n if (o3.face)\n continue;\n if (o3.edge_after.face || o3.edge_before.face)\n continue;\n let { edge_after: i3, edge_before: r3 } = o3;\n try {\n Lg.testInfiniteLoop(i3);\n } catch (e22) {\n throw Dg.CANNOT_COMPLETE_BOOLEAN_OPERATION;\n }\n let s2 = e21.addFace(i3, r3);\n for (let e22 of t2)\n e22.edge_before \u0026\u0026 e22.edge_after \u0026\u0026 e22.edge_before.face === s2 \u0026\u0026 e22.edge_after.face === s2 \u0026\u0026 (e22.face = s2);\n for (let e22 of n2)\n e22.edge_before \u0026\u0026 e22.edge_after \u0026\u0026 e22.edge_before.face === s2 \u0026\u0026 e22.edge_after.face === s2 \u0026\u0026 (e22.face = s2);\n }\n}\nfunction Qf(e21, t2, n2, o3) {\n for (let i3 of t2) {\n let t3 = i3.first.bv;\n (n2 === 1 \u0026\u0026 t3 === Tf || n2 === 3 \u0026\u0026 t3 === Tf \u0026\u0026 o3 || n2 === 3 \u0026\u0026 t3 === Ef \u0026\u0026 !o3 || n2 === 2 \u0026\u0026 t3 === Ef) \u0026\u0026 e21.deleteFace(i3);\n }\n}\nfunction Kf(e21) {\n const t2 = [];\n for (const n2 of e21.edges)\n n2.face \u0026\u0026 e21.faces.has(n2.face) || t2.push(n2);\n for (const n2 of t2)\n e21.edges.delete(n2);\n}\nvar e_ = Object.freeze({ __proto__: null, BOOLEAN_INTERSECT: 2, BOOLEAN_SUBTRACT: 3, BOOLEAN_UNION: 1, calculateIntersections: Yf, innerClip: jf, intersect: Ff, outerClip: $f, removeNotRelevantChains: Zf, removeOldFaces: qf, restoreFaces: Jf, subtract: Bf, unify: function(e21, t2) {\n let [n2, o3] = Hf(e21, t2, 1, true);\n return n2;\n} });\nvar t_ = RegExp(\"T.F..FFF.|T.F...F..\");\nvar n_ = RegExp(\"T........|.T.......|...T.....|....T....\");\nvar o_ = RegExp(\"FT.......|F..T.....|F...T....\");\nvar i_ = RegExp(\"T.F..F...\");\nvar r_ = RegExp(\"T.F..F...|.TF..F...|..FT.F...|..F.TF...\");\nvar s_ = class {\n constructor() {\n this.m = new Array(9).fill(undefined);\n }\n get I2I() {\n return this.m[0];\n }\n set I2I(e21) {\n this.m[0] = e21;\n }\n get I2B() {\n return this.m[1];\n }\n set I2B(e21) {\n this.m[1] = e21;\n }\n get I2E() {\n return this.m[2];\n }\n set I2E(e21) {\n this.m[2] = e21;\n }\n get B2I() {\n return this.m[3];\n }\n set B2I(e21) {\n this.m[3] = e21;\n }\n get B2B() {\n return this.m[4];\n }\n set B2B(e21) {\n this.m[4] = e21;\n }\n get B2E() {\n return this.m[5];\n }\n set B2E(e21) {\n this.m[5] = e21;\n }\n get E2I() {\n return this.m[6];\n }\n set E2I(e21) {\n this.m[6] = e21;\n }\n get E2B() {\n return this.m[7];\n }\n set E2B(e21) {\n this.m[7] = e21;\n }\n get E2E() {\n return this.m[8];\n }\n set E2E(e21) {\n this.m[8] = e21;\n }\n toString() {\n return this.m.map((e21) =\u003e e21 instanceof Array \u0026\u0026 e21.length \u003e 0 ? \"T\" : e21 instanceof Array \u0026\u0026 e21.length === 0 ? \"F\" : \"*\").join(\"\");\n }\n equal() {\n return t_.test(this.toString());\n }\n intersect() {\n return n_.test(this.toString());\n }\n touch() {\n return o_.test(this.toString());\n }\n inside() {\n return i_.test(this.toString());\n }\n covered() {\n return r_.test(this.toString());\n }\n};\nfunction a_(e21, t2) {\n let n2, o3 = new kg.Ray(t2), i3 = new kg.Line(o3.pt, o3.norm);\n const r3 = new kg.Box(o3.box.xmin - kg.DP_TOL, o3.box.ymin - kg.DP_TOL, o3.box.xmax + kg.DP_TOL, o3.box.ymax + kg.DP_TOL);\n if (e21.box.not_intersect(r3))\n return kg.OUTSIDE;\n let s2 = e21.edges.search(r3);\n if (s2.length === 0)\n return kg.OUTSIDE;\n for (let e22 of s2)\n if (e22.shape.contains(t2))\n return kg.BOUNDARY;\n let a3 = [...e21.faces], c3 = [];\n for (let e22 of s2)\n for (let n3 of o3.intersect(e22.shape)) {\n if (n3.equalTo(t2))\n return kg.BOUNDARY;\n c3.push({ pt: n3, edge: e22, face_index: a3.indexOf(e22.face) });\n }\n c3.sort((e22, t3) =\u003e Og(e22.pt.x, t3.pt.x) ? -1 : Ag(e22.pt.x, t3.pt.x) ? 1 : e22.face_index \u003c t3.face_index ? -1 : e22.face_index \u003e t3.face_index ? 1 : e22.edge.arc_length \u003c t3.edge.arc_length ? -1 : e22.edge.arc_length \u003e t3.edge.arc_length ? 1 : 0);\n let l3 = 0;\n for (let e22 = 0;e22 \u003c c3.length; e22++) {\n let t3 = c3[e22];\n if (t3.pt.equalTo(t3.edge.shape.start)) {\n if (e22 \u003e 0 \u0026\u0026 t3.pt.equalTo(c3[e22 - 1].pt) \u0026\u0026 t3.face_index === c3[e22 - 1].face_index \u0026\u0026 t3.edge.prev === c3[e22 - 1].edge)\n continue;\n let n3 = t3.edge.prev;\n for (;Tg(n3.length); )\n n3 = n3.prev;\n let o4 = n3.shape.tangentInEnd(), r4 = t3.pt.translate(o4), s3 = t3.edge.shape.tangentInStart(), a4 = t3.pt.translate(s3), h2 = r4.leftTo(i3), d2 = a4.leftTo(i3);\n (h2 \u0026\u0026 !d2 || !h2 \u0026\u0026 d2) \u0026\u0026 l3++;\n } else if (t3.pt.equalTo(t3.edge.shape.end)) {\n if (e22 \u003e 0 \u0026\u0026 t3.pt.equalTo(c3[e22 - 1].pt) \u0026\u0026 t3.face_index === c3[e22 - 1].face_index \u0026\u0026 t3.edge.next === c3[e22 - 1].edge)\n continue;\n let n3 = t3.edge.next;\n for (;Tg(n3.length); )\n n3 = n3.next;\n let o4 = n3.shape.tangentInStart(), r4 = t3.pt.translate(o4), s3 = t3.edge.shape.tangentInEnd(), a4 = t3.pt.translate(s3), h2 = r4.leftTo(i3), d2 = a4.leftTo(i3);\n (h2 \u0026\u0026 !d2 || !h2 \u0026\u0026 d2) \u0026\u0026 l3++;\n } else if (t3.edge.shape instanceof kg.Segment)\n l3++;\n else {\n let e23 = t3.edge.shape.box;\n Eg(t3.pt.y, e23.ymin) || Eg(t3.pt.y, e23.ymax) || l3++;\n }\n }\n return n2 = l3 % 2 == 1 ? 1 : 0, n2;\n}\nfunction c_(e21, t2) {\n return u_(e21, t2).intersect();\n}\nfunction l_(e21, t2) {\n return u_(e21, t2).inside();\n}\nfunction h_(e21, t2) {\n return u_(e21, t2).covered();\n}\nfunction d_(e21, t2) {\n return h_(t2, e21);\n}\nfunction u_(e21, t2) {\n return e21 instanceof kg.Line \u0026\u0026 t2 instanceof kg.Line ? function(e22, t3) {\n let n2 = new s_, o3 = jg(e22, t3);\n o3.length === 0 ? e22.contains(t3.pt) \u0026\u0026 t3.contains(e22.pt) ? (n2.I2I = [e22], n2.I2E = [], n2.E2I = []) : (n2.I2I = [], n2.I2E = [e22], n2.E2I = [t3]) : (n2.I2I = o3, n2.I2E = e22.split(o3), n2.E2I = t3.split(o3));\n return n2;\n }(e21, t2) : e21 instanceof kg.Line \u0026\u0026 t2 instanceof kg.Circle ? function(e22, t3) {\n let n2 = new s_, o3 = $g(e22, t3);\n if (o3.length === 0)\n n2.I2I = [], n2.I2B = [], n2.I2E = [e22], n2.E2I = [t3];\n else if (o3.length === 1)\n n2.I2I = [], n2.I2B = o3, n2.I2E = e22.split(o3), n2.E2I = [t3];\n else {\n let i3 = new bf([e22]), r3 = e22.sortPoints(o3);\n i3.split(r3);\n let s2 = i3.toShapes();\n n2.I2I = [s2[1]], n2.I2B = r3, n2.I2E = [s2[0], s2[2]], n2.E2I = new kg.Polygon([t3.toArc()]).cutWithLine(e22);\n }\n return n2;\n }(e21, t2) : e21 instanceof kg.Line \u0026\u0026 t2 instanceof kg.Box ? function(e22, t3) {\n let n2 = new s_, o3 = Yg(e22, t3);\n if (o3.length === 0)\n n2.I2I = [], n2.I2B = [], n2.I2E = [e22], n2.E2I = [t3];\n else if (o3.length === 1)\n n2.I2I = [], n2.I2B = o3, n2.I2E = e22.split(o3), n2.E2I = [t3];\n else {\n let i3 = new bf([e22]), r3 = e22.sortPoints(o3);\n i3.split(r3);\n let s2 = i3.toShapes();\n t3.toSegments().some((e23) =\u003e e23.contains(o3[0]) \u0026\u0026 e23.contains(o3[1])) ? (n2.I2I = [], n2.I2B = [s2[1]], n2.I2E = [s2[0], s2[2]], n2.E2I = [t3]) : (n2.I2I = [s2[1]], n2.I2B = r3, n2.I2E = [s2[0], s2[2]], n2.E2I = new kg.Polygon(t3.toSegments()).cutWithLine(e22));\n }\n return n2;\n }(e21, t2) : e21 instanceof kg.Line \u0026\u0026 t2 instanceof kg.Polygon ? function(e22, t3) {\n let n2 = new s_, o3 = sf(e22, t3), i3 = new bf([e22]), r3 = o3.length \u003e 0 ? o3.slice() : e22.sortPoints(o3);\n return i3.split(r3), [...i3].forEach((e23) =\u003e e23.setInclusion(t3)), n2.I2I = [...i3].filter((e23) =\u003e e23.bv === kg.INSIDE).map((e23) =\u003e e23.shape), n2.I2B = [...i3].slice(1).map((e23) =\u003e e23.bv === kg.BOUNDARY ? e23.shape : e23.shape.start), n2.I2E = [...i3].filter((e23) =\u003e e23.bv === kg.OUTSIDE).map((e23) =\u003e e23.shape), n2.E2I = t3.cutWithLine(e22), n2;\n }(e21, t2) : (e21 instanceof kg.Segment || e21 instanceof kg.Arc) \u0026\u0026 t2 instanceof kg.Polygon ? p_(e21, t2) : (e21 instanceof kg.Segment || e21 instanceof kg.Arc) \u0026\u0026 (t2 instanceof kg.Circle || t2 instanceof kg.Box) ? p_(e21, new kg.Polygon(t2)) : e21 instanceof kg.Polygon \u0026\u0026 t2 instanceof kg.Polygon ? m_(e21, t2) : (e21 instanceof kg.Circle || e21 instanceof kg.Box) \u0026\u0026 (t2 instanceof kg.Circle || t2 instanceof kg.Box) ? m_(new kg.Polygon(e21), new kg.Polygon(t2)) : (e21 instanceof kg.Circle || e21 instanceof kg.Box) \u0026\u0026 t2 instanceof kg.Polygon ? m_(new kg.Polygon(e21), t2) : e21 instanceof kg.Polygon \u0026\u0026 (t2 instanceof kg.Circle || t2 instanceof kg.Box) ? m_(e21, new kg.Polygon(t2)) : undefined;\n}\nfunction p_(e21, t2) {\n let n2 = new s_, o3 = function(e22, t3) {\n return e22 instanceof kg.Line ? sf(e22, t3) : e22 instanceof kg.Segment ? of(e22, t3) : e22 instanceof kg.Arc ? rf(e22, t3) : [];\n }(e21, t2), i3 = o3.length \u003e 0 ? o3.slice() : e21.sortPoints(o3), r3 = new bf([e21]);\n r3.split(i3), [...r3].forEach((e22) =\u003e e22.setInclusion(t2)), n2.I2I = [...r3].filter((e22) =\u003e e22.bv === kg.INSIDE).map((e22) =\u003e e22.shape), n2.I2B = [...r3].slice(1).map((e22) =\u003e e22.bv === kg.BOUNDARY ? e22.shape : e22.shape.start), n2.I2E = [...r3].filter((e22) =\u003e e22.bv === kg.OUTSIDE).map((e22) =\u003e e22.shape), n2.B2I = [], n2.B2B = [], n2.B2E = [];\n for (let o4 of [e21.start, e21.end])\n switch (a_(t2, o4)) {\n case kg.INSIDE:\n n2.B2I.push(o4);\n break;\n case kg.BOUNDARY:\n n2.B2B.push(o4);\n break;\n case kg.OUTSIDE:\n n2.B2E.push(o4);\n }\n return n2;\n}\nfunction m_(e21, t2) {\n let n2 = new s_, [o3, i3] = Yf(e21, t2), r3 = Ff(e21, t2), s2 = Bf(e21, t2), a3 = Bf(t2, e21), [c3, l3] = jf(e21, t2), h2 = $f(e21, t2), d2 = $f(t2, e21);\n return n2.I2I = r3.isEmpty() ? [] : [r3], n2.I2B = l3, n2.I2E = s2.isEmpty() ? [] : [s2], n2.B2I = c3, n2.B2B = o3, n2.B2E = h2, n2.E2I = a3.isEmpty() ? [] : [a3], n2.E2B = d2, n2;\n}\nvar g_ = Object.freeze({ __proto__: null, contain: function(e21, t2) {\n return l_(t2, e21);\n}, cover: d_, covered: h_, disjoint: function(e21, t2) {\n return !c_(e21, t2);\n}, equal: function(e21, t2) {\n return u_(e21, t2).equal();\n}, inside: l_, intersect: c_, relate: u_, touch: function(e21, t2) {\n return u_(e21, t2).touch();\n} });\nvar f_ = class e21 {\n constructor(e22 = 1, t2 = 0, n2 = 0, o3 = 1, i3 = 0, r3 = 0) {\n this.a = e22, this.b = t2, this.c = n2, this.d = o3, this.tx = i3, this.ty = r3;\n }\n fromMatrix3x3(t2) {\n const [n2, o3, i3] = t2[0], [r3, s2, a3] = t2[1];\n return new e21(n2, r3, o3, s2, i3, a3);\n }\n toMatrix3x3() {\n return [[this.a, this.c, this.tx], [this.b, this.d, this.ty], [0, 0, 1]];\n }\n clone() {\n return new e21(this.a, this.b, this.c, this.d, this.tx, this.ty);\n }\n transform(e22) {\n return [e22[0] * this.a + e22[1] * this.c + this.tx, e22[0] * this.b + e22[1] * this.d + this.ty];\n }\n multiply(t2) {\n return new e21(this.a * t2.a + this.c * t2.b, this.b * t2.a + this.d * t2.b, this.a * t2.c + this.c * t2.d, this.b * t2.c + this.d * t2.d, this.a * t2.tx + this.c * t2.ty + this.tx, this.b * t2.tx + this.d * t2.ty + this.ty);\n }\n translate(...t2) {\n let n2, o3;\n if (t2.length != 1 || isNaN(t2[0].x) || isNaN(t2[0].y)) {\n if (t2.length !== 2 || typeof t2[0] != \"number\" || typeof t2[1] != \"number\")\n throw Dg.ILLEGAL_PARAMETERS;\n n2 = t2[0], o3 = t2[1];\n } else\n n2 = t2[0].x, o3 = t2[0].y;\n return this.multiply(new e21(1, 0, 0, 1, n2, o3));\n }\n rotate(t2, n2 = 0, o3 = 0) {\n let i3 = Math.cos(t2), r3 = Math.sin(t2);\n return this.translate(n2, o3).multiply(new e21(i3, r3, -r3, i3, 0, 0)).translate(-n2, -o3);\n }\n scale(t2, n2) {\n return this.multiply(new e21(t2, 0, 0, n2, 0, 0));\n }\n equalTo(e22) {\n return !!kg.Utils.EQ(this.tx, e22.tx) \u0026\u0026 (!!kg.Utils.EQ(this.ty, e22.ty) \u0026\u0026 (!!kg.Utils.EQ(this.a, e22.a) \u0026\u0026 (!!kg.Utils.EQ(this.b, e22.b) \u0026\u0026 (!!kg.Utils.EQ(this.c, e22.c) \u0026\u0026 !!kg.Utils.EQ(this.d, e22.d)))));\n }\n};\nkg.Matrix = f_;\nkg.matrix = (...e22) =\u003e new kg.Matrix(...e22);\nvar __ = class {\n constructor(e22, t2) {\n this.low = e22, this.high = t2;\n }\n get max() {\n return this.clone();\n }\n less_than(e22) {\n return this.low \u003c e22.low || this.low === e22.low \u0026\u0026 this.high \u003c e22.high;\n }\n equal_to(e22) {\n return this.low === e22.low \u0026\u0026 this.high === e22.high;\n }\n intersect(e22) {\n return !this.not_intersect(e22);\n }\n not_intersect(e22) {\n return this.high \u003c e22.low || e22.high \u003c this.low;\n }\n merge(e22) {\n const t2 = this.low === undefined ? e22.low : this.low \u003c e22.low ? this.low : e22.low, n2 = this.high === undefined ? e22.high : this.high \u003e e22.high ? this.high : e22.high, o3 = this.clone();\n return o3.low = t2, o3.high = n2, o3;\n }\n output() {\n return [this.low, this.high];\n }\n comparable_less_than(e22, t2) {\n return e22 \u003c t2;\n }\n};\nvar y_ = class e22 extends __ {\n clone() {\n return new e22(this.low, this.high);\n }\n};\nvar b_ = class {\n constructor(e23, t2, n2 = null, o3 = null, i3 = null, r3 = 0) {\n if (this.left = n2, this.right = o3, this.parent = i3, this.color = r3, this.item = { key: undefined, values: [] }, t2 !== undefined \u0026\u0026 this.item.values.push(t2), e23 !== undefined)\n if (Array.isArray(e23)) {\n const [t3, n3] = e23;\n if (!Number.isNaN(t3) \u0026\u0026 !Number.isNaN(n3)) {\n let e24 = t3, o4 = n3;\n e24 \u003e o4 \u0026\u0026 ([e24, o4] = [o4, e24]), this.item.key = new y_(e24, o4);\n }\n } else\n this.item.key = e23;\n this.max = this.item.key ? this.item.key.max : undefined;\n }\n isNil() {\n return this.item.key === undefined \u0026\u0026 this.item.values.length === 0 \u0026\u0026 this.left === null \u0026\u0026 this.right === null \u0026\u0026 this.color === 0;\n }\n requireKey() {\n if (!this.item.key)\n throw new Error(\"Node key is undefined (nil/sentinel). Operation is not applicable.\");\n return this.item.key;\n }\n less_than(e23) {\n const t2 = this.requireKey(), n2 = e23.requireKey();\n return t2.less_than(n2);\n }\n _value_equal(e23) {\n const t2 = this.item.values[0], n2 = e23.item.values[0];\n return t2 \u0026\u0026 n2 \u0026\u0026 t2.equal_to ? t2.equal_to(n2) : t2 === n2;\n }\n equal_to(e23) {\n const t2 = this.requireKey(), n2 = e23.requireKey();\n return t2.equal_to(n2);\n }\n intersect(e23) {\n const t2 = this.requireKey(), n2 = e23.requireKey();\n return t2.intersect(n2);\n }\n copy_data(e23) {\n this.item.key = e23.item.key, this.item.values = e23.item.values.slice();\n }\n update_max() {\n this.max = this.item.key ? this.item.key.max : undefined, this.right \u0026\u0026 this.right.max \u0026\u0026 (this.max = this.max ? this.max.merge(this.right.max) : this.right.max), this.left \u0026\u0026 this.left.max \u0026\u0026 (this.max = this.max ? this.max.merge(this.left.max) : this.left.max);\n }\n not_intersect_left_subtree(e23) {\n if (!this.left)\n return true;\n const t2 = this.left.max ? this.left.max.high : this.left.item.key.high, n2 = this.requireKey(), o3 = e23.requireKey();\n return n2.comparable_less_than(t2, o3.low);\n }\n not_intersect_right_subtree(e23) {\n if (!this.right)\n return true;\n const t2 = this.right.max ? this.right.max.low : this.right.item.key.low, n2 = this.requireKey(), o3 = e23.requireKey();\n return n2.comparable_less_than(o3.high, t2);\n }\n};\nvar x_ = class e23 {\n constructor() {\n this.root = null, this.nil_node = new b_;\n }\n get size() {\n let e24 = 0;\n return this.tree_walk(this.root, (t2) =\u003e e24 += t2.item.values.length), e24;\n }\n get keys() {\n const e24 = [];\n return this.tree_walk(this.root, (t2) =\u003e e24.push(t2.item.key.output())), e24;\n }\n get values() {\n const e24 = [];\n return this.tree_walk(this.root, (t2) =\u003e {\n for (const n2 of t2.item.values)\n e24.push(n2);\n }), e24;\n }\n get items() {\n const e24 = [];\n return this.tree_walk(this.root, (t2) =\u003e {\n const n2 = t2.item.key.output();\n for (const o3 of t2.item.values)\n e24.push({ key: n2, value: o3 });\n }), e24;\n }\n isEmpty() {\n return this.root == null || this.root === this.nil_node;\n }\n clear() {\n this.root = null;\n }\n insert(e24, t2 = e24) {\n if (e24 === undefined)\n return;\n const n2 = this.tree_search(this.root, new b_(e24));\n if (n2)\n return n2.item.values.push(t2), n2;\n const o3 = new b_(e24, t2, this.nil_node, this.nil_node, null, 1);\n return this.tree_insert(o3), this.recalc_max(o3), o3;\n }\n exist(e24, t2 = e24) {\n const n2 = this.tree_search(this.root, new b_(e24));\n return !!n2 \u0026\u0026 (arguments.length \u003c 2 || t2 === e24 || n2.item.values.some((e25) =\u003e e25 \u0026\u0026 e25.equal_to ? e25.equal_to(t2) : e25 === t2));\n }\n remove(e24, t2 = e24) {\n const n2 = this.tree_search(this.root, new b_(e24));\n if (!n2)\n return;\n if (arguments.length \u003c 2)\n return this.tree_delete(n2), n2;\n const o3 = n2.item.values.findIndex((e25) =\u003e e25 \u0026\u0026 e25.equal_to ? e25.equal_to(t2) : e25 === t2);\n return o3 \u003e= 0 ? (n2.item.values.splice(o3, 1), n2.item.values.length === 0 \u0026\u0026 this.tree_delete(n2), n2) : undefined;\n }\n search(e24, t2 = (e25, t3) =\u003e e25 === t3 ? t3.output() : e25) {\n const n2 = new b_(e24), o3 = [];\n this.tree_search_interval(this.root, n2, o3);\n const i3 = [];\n for (const e25 of o3)\n for (const n3 of e25.item.values)\n i3.push(t2(n3, e25.item.key));\n return i3;\n }\n intersect_any(e24) {\n const t2 = new b_(e24);\n return this.tree_find_any_interval(this.root, t2);\n }\n forEach(e24) {\n this.tree_walk(this.root, (t2) =\u003e {\n for (const n2 of t2.item.values)\n e24(t2.item.key, n2);\n });\n }\n map(t2) {\n const n2 = new e23;\n return this.tree_walk(this.root, (e24) =\u003e {\n for (const o3 of e24.item.values)\n n2.insert(e24.item.key, t2(o3, e24.item.key));\n }), n2;\n }\n *iterate(e24, t2 = (e25, t3) =\u003e e25 === t3 ? t3.output() : e25) {\n let n2 = null;\n for (e24 ? n2 = this.tree_search_nearest_forward(this.root, new b_(e24)) : this.root \u0026\u0026 (n2 = this.local_minimum(this.root));n2; ) {\n for (const e25 of n2.item.values)\n yield t2(e25, n2.item.key);\n n2 = this.tree_successor(n2);\n }\n }\n recalc_max(e24) {\n let t2 = e24;\n for (;t2.parent != null; )\n t2.parent.update_max(), t2 = t2.parent;\n }\n tree_insert(e24) {\n let t2 = this.root, n2 = null;\n if (this.root == null || this.root === this.nil_node)\n this.root = e24;\n else {\n for (;t2 !== this.nil_node; )\n n2 = t2, t2 = e24.less_than(t2) ? t2.left : t2.right;\n e24.parent = n2, e24.less_than(n2) ? n2.left = e24 : n2.right = e24;\n }\n this.insert_fixup(e24);\n }\n insert_fixup(e24) {\n let t2, n2;\n for (t2 = e24;t2 !== this.root \u0026\u0026 t2.parent.color === 1; )\n t2.parent === t2.parent.parent.left ? (n2 = t2.parent.parent.right, n2.color === 1 ? (t2.parent.color = 0, n2.color = 0, t2.parent.parent.color = 1, t2 = t2.parent.parent) : (t2 === t2.parent.right \u0026\u0026 (t2 = t2.parent, this.rotate_left(t2)), t2.parent.color = 0, t2.parent.parent.color = 1, this.rotate_right(t2.parent.parent))) : (n2 = t2.parent.parent.left, n2.color === 1 ? (t2.parent.color = 0, n2.color = 0, t2.parent.parent.color = 1, t2 = t2.parent.parent) : (t2 === t2.parent.left \u0026\u0026 (t2 = t2.parent, this.rotate_right(t2)), t2.parent.color = 0, t2.parent.parent.color = 1, this.rotate_left(t2.parent.parent)));\n this.root.color = 0;\n }\n tree_delete(e24) {\n let t2, n2;\n t2 = e24.left === this.nil_node || e24.right === this.nil_node ? e24 : this.tree_successor(e24), n2 = t2.left !== this.nil_node ? t2.left : t2.right, n2.parent = t2.parent, t2 === this.root ? this.root = n2 : (t2 === t2.parent.left ? t2.parent.left = n2 : t2.parent.right = n2, t2.parent.update_max()), this.recalc_max(n2), t2 !== e24 \u0026\u0026 (e24.copy_data(t2), e24.update_max(), this.recalc_max(e24)), t2.color === 0 \u0026\u0026 this.delete_fixup(n2);\n }\n delete_fixup(e24) {\n let t2, n2 = e24;\n for (;n2 !== this.root \u0026\u0026 n2.parent != null \u0026\u0026 n2.color === 0; )\n n2 === n2.parent.left ? (t2 = n2.parent.right, t2.color === 1 \u0026\u0026 (t2.color = 0, n2.parent.color = 1, this.rotate_left(n2.parent), t2 = n2.parent.right), t2.left.color === 0 \u0026\u0026 t2.right.color === 0 ? (t2.color = 1, n2 = n2.parent) : (t2.right.color === 0 \u0026\u0026 (t2.color = 1, t2.left.color = 0, this.rotate_right(t2), t2 = n2.parent.right), t2.color = n2.parent.color, n2.parent.color = 0, t2.right.color = 0, this.rotate_left(n2.parent), n2 = this.root)) : (t2 = n2.parent.left, t2.color === 1 \u0026\u0026 (t2.color = 0, n2.parent.color = 1, this.rotate_right(n2.parent), t2 = n2.parent.left), t2.left.color === 0 \u0026\u0026 t2.right.color === 0 ? (t2.color = 1, n2 = n2.parent) : (t2.left.color === 0 \u0026\u0026 (t2.color = 1, t2.right.color = 0, this.rotate_left(t2), t2 = n2.parent.left), t2.color = n2.parent.color, n2.parent.color = 0, t2.left.color = 0, this.rotate_right(n2.parent), n2 = this.root));\n n2.color = 0;\n }\n tree_search(e24, t2) {\n if (e24 != null \u0026\u0026 e24 !== this.nil_node)\n return t2.equal_to(e24) ? e24 : t2.less_than(e24) ? this.tree_search(e24.left, t2) : this.tree_search(e24.right, t2);\n }\n tree_search_nearest_forward(e24, t2) {\n let n2 = null, o3 = e24;\n for (;o3 \u0026\u0026 o3 !== this.nil_node; )\n o3.less_than(t2) ? o3.intersect(t2) ? (n2 = o3, o3 = o3.left) : o3 = o3.right : (n2 \u0026\u0026 !o3.less_than(n2) || (n2 = o3), o3 = o3.left);\n return n2 || null;\n }\n tree_search_interval(e24, t2, n2) {\n e24 != null \u0026\u0026 e24 !== this.nil_node \u0026\u0026 (e24.left === this.nil_node || e24.not_intersect_left_subtree(t2) || this.tree_search_interval(e24.left, t2, n2), e24.intersect(t2) \u0026\u0026 n2.push(e24), e24.right === this.nil_node || e24.not_intersect_right_subtree(t2) || this.tree_search_interval(e24.right, t2, n2));\n }\n tree_find_any_interval(e24, t2) {\n let n2 = false;\n return e24 != null \u0026\u0026 e24 !== this.nil_node \u0026\u0026 (e24.left === this.nil_node || e24.not_intersect_left_subtree(t2) || (n2 = this.tree_find_any_interval(e24.left, t2)), n2 || (n2 = e24.intersect(t2)), n2 || e24.right === this.nil_node || e24.not_intersect_right_subtree(t2) || (n2 = this.tree_find_any_interval(e24.right, t2))), n2;\n }\n local_minimum(e24) {\n let t2 = e24;\n for (;t2.left != null \u0026\u0026 t2.left !== this.nil_node; )\n t2 = t2.left;\n return t2;\n }\n local_maximum(e24) {\n let t2 = e24;\n for (;t2.right != null \u0026\u0026 t2.right !== this.nil_node; )\n t2 = t2.right;\n return t2;\n }\n tree_successor(e24) {\n let t2, n2, o3;\n if (e24.right !== this.nil_node)\n t2 = this.local_minimum(e24.right);\n else {\n for (n2 = e24, o3 = e24.parent;o3 != null \u0026\u0026 o3.right === n2; )\n n2 = o3, o3 = o3.parent;\n t2 = o3;\n }\n return t2;\n }\n rotate_left(e24) {\n const t2 = e24.right;\n e24.right = t2.left, t2.left !== this.nil_node \u0026\u0026 (t2.left.parent = e24), t2.parent = e24.parent, e24 === this.root ? this.root = t2 : e24 === e24.parent.left ? e24.parent.left = t2 : e24.parent.right = t2, t2.left = e24, e24.parent = t2, e24 !== null \u0026\u0026 e24 !== this.nil_node \u0026\u0026 e24.update_max(), t2 != null \u0026\u0026 t2 !== this.nil_node \u0026\u0026 t2.update_max();\n }\n rotate_right(e24) {\n const t2 = e24.left;\n e24.left = t2.right, t2.right !== this.nil_node \u0026\u0026 (t2.right.parent = e24), t2.parent = e24.parent, e24 === this.root ? this.root = t2 : e24 === e24.parent.left ? e24.parent.left = t2 : e24.parent.right = t2, t2.right = e24, e24.parent = t2, e24 !== null \u0026\u0026 e24 !== this.nil_node \u0026\u0026 e24.update_max(), t2 != null \u0026\u0026 t2 !== this.nil_node \u0026\u0026 t2.update_max();\n }\n tree_walk(e24, t2) {\n e24 != null \u0026\u0026 e24 !== this.nil_node \u0026\u0026 (this.tree_walk(e24.left, t2), t2(e24), this.tree_walk(e24.right, t2));\n }\n testRedBlackProperty() {\n let e24 = true;\n return this.tree_walk(this.root, function(t2) {\n t2.color === 1 \u0026\u0026 (t2.left.color === 0 \u0026\u0026 t2.right.color === 0 || (e24 = false));\n }), e24;\n }\n testBlackHeightProperty(e24) {\n let t2 = 0, n2 = 0, o3 = 0;\n if (e24.color === 0 \u0026\u0026 t2++, n2 = e24.left !== this.nil_node ? this.testBlackHeightProperty(e24.left) : 1, o3 = e24.right !== this.nil_node ? this.testBlackHeightProperty(e24.right) : 1, n2 !== o3)\n throw new Error(\"Red-black height property violated\");\n return t2 += n2, t2;\n }\n};\nvar v_ = class extends Set {\n constructor(e24) {\n super(e24), this.index = new x_, this.forEach((e25) =\u003e this.index.insert(e25));\n }\n add(e24) {\n let t2 = this.size;\n const { key: n2, value: o3 } = e24, i3 = n2 || e24.box, r3 = o3 || e24;\n return super.add(r3), this.size \u003e t2 \u0026\u0026 this.index.insert(i3, r3), this;\n }\n delete(e24) {\n const { key: t2, value: n2 } = e24, o3 = t2 || e24.box, i3 = n2 || e24;\n let r3 = super.delete(i3);\n return r3 \u0026\u0026 this.index.remove(o3, i3), r3;\n }\n clear() {\n super.clear(), this.index = new x_;\n }\n search(e24) {\n return this.index.search(e24);\n }\n hit(e24) {\n let t2 = new kg.Box(e24.x - 1, e24.y - 1, e24.x + 1, e24.y + 1);\n return this.index.search(t2).filter((t3) =\u003e e24.on(t3));\n }\n svg() {\n return [...this].reduce((e24, t2) =\u003e e24 + t2.svg(), \"\");\n }\n};\nkg.PlanarSet = v_;\nvar I_ = class {\n get name() {\n throw Dg.CANNOT_INVOKE_ABSTRACT_METHOD;\n }\n get box() {\n throw Dg.CANNOT_INVOKE_ABSTRACT_METHOD;\n }\n clone() {\n throw Dg.CANNOT_INVOKE_ABSTRACT_METHOD;\n }\n translate(...e24) {\n return this.transform(new f_().translate(...e24));\n }\n rotate(e24, t2 = new kg.Point) {\n return this.transform(new f_().rotate(e24, t2.x, t2.y));\n }\n scale(e24, t2) {\n return this.transform(new f_().scale(e24, t2));\n }\n transform(...e24) {\n throw Dg.CANNOT_INVOKE_ABSTRACT_METHOD;\n }\n toJSON() {\n return Object.assign({}, this, { name: this.name });\n }\n svg(e24 = {}) {\n throw Dg.CANNOT_INVOKE_ABSTRACT_METHOD;\n }\n};\nvar S_ = class e24 extends I_ {\n constructor(...e25) {\n if (super(), this.x = 0, this.y = 0, e25.length !== 0) {\n if (e25.length === 1 \u0026\u0026 e25[0] instanceof Array \u0026\u0026 e25[0].length === 2) {\n let t2 = e25[0];\n if (typeof t2[0] == \"number\" \u0026\u0026 typeof t2[1] == \"number\")\n return this.x = t2[0], void (this.y = t2[1]);\n }\n if (e25.length === 1 \u0026\u0026 e25[0] instanceof Object \u0026\u0026 e25[0].name === \"point\") {\n let { x: t2, y: n2 } = e25[0];\n return this.x = t2, void (this.y = n2);\n }\n if (e25.length === 2 \u0026\u0026 typeof e25[0] == \"number\" \u0026\u0026 typeof e25[1] == \"number\")\n return this.x = e25[0], void (this.y = e25[1]);\n throw Dg.ILLEGAL_PARAMETERS;\n }\n }\n get box() {\n return new kg.Box(this.x, this.y, this.x, this.y);\n }\n clone() {\n return new kg.Point(this.x, this.y);\n }\n get vertices() {\n return [this.clone()];\n }\n equalTo(e25) {\n return kg.Utils.EQ(this.x, e25.x) \u0026\u0026 kg.Utils.EQ(this.y, e25.y);\n }\n lessThan(e25) {\n return !!kg.Utils.LT(this.y, e25.y) || !(!kg.Utils.EQ(this.y, e25.y) || !kg.Utils.LT(this.x, e25.x));\n }\n transform(e25) {\n return new kg.Point(e25.transform([this.x, this.y]));\n }\n projectionOn(e25) {\n if (this.equalTo(e25.pt))\n return this.clone();\n let t2 = new kg.Vector(this, e25.pt);\n if (kg.Utils.EQ_0(t2.cross(e25.norm)))\n return e25.pt.clone();\n let n2 = t2.dot(e25.norm), o3 = e25.norm.multiply(n2);\n return this.translate(o3);\n }\n leftTo(e25) {\n let t2 = new kg.Vector(e25.pt, this);\n return kg.Utils.GT(t2.dot(e25.norm), 0);\n }\n distanceTo(t2) {\n if (t2 instanceof e24) {\n let e25 = t2.x - this.x, n2 = t2.y - this.y;\n return [Math.sqrt(e25 * e25 + n2 * n2), new kg.Segment(this, t2)];\n }\n return t2 instanceof kg.Line ? kg.Distance.point2line(this, t2) : t2 instanceof kg.Circle ? kg.Distance.point2circle(this, t2) : t2 instanceof kg.Segment ? kg.Distance.point2segment(this, t2) : t2 instanceof kg.Arc ? kg.Distance.point2arc(this, t2) : t2 instanceof kg.Box ? kg.Distance.point2polygon(this, new kg.Polygon(t2)) : t2 instanceof kg.Polygon ? kg.Distance.point2polygon(this, t2) : t2 instanceof kg.PlanarSet ? kg.Distance.shape2planarSet(this, t2) : t2 instanceof kg.Multiline ? kg.Distance.shape2multiline(this, t2) : undefined;\n }\n on(e25) {\n if (e25 instanceof kg.Point)\n return this.equalTo(e25);\n if (e25.contains \u0026\u0026 e25.contains instanceof Function)\n return e25.contains(this);\n throw kg.Errors.UNSUPPORTED_SHAPE_TYPE;\n }\n get name() {\n return \"point\";\n }\n svg(e25 = {}) {\n const t2 = e25.r ?? 3;\n return `\n\u003ccircle cx=\"${this.x}\" cy=\"${this.y}\" r=\"${t2}\"\n ${Fg({ fill: \"red\", ...e25 })} /\u003e`;\n }\n};\nkg.Point = S_;\nvar C_ = (...e25) =\u003e new kg.Point(...e25);\nkg.point = C_;\nvar P_ = class extends I_ {\n constructor(...e25) {\n if (super(), this.x = 0, this.y = 0, e25.length !== 0) {\n if (e25.length === 1 \u0026\u0026 e25[0] instanceof Array \u0026\u0026 e25[0].length === 2) {\n let t2 = e25[0];\n if (typeof t2[0] == \"number\" \u0026\u0026 typeof t2[1] == \"number\")\n return this.x = t2[0], void (this.y = t2[1]);\n }\n if (e25.length === 1 \u0026\u0026 e25[0] instanceof Object \u0026\u0026 e25[0].name === \"vector\") {\n let { x: t2, y: n2 } = e25[0];\n return this.x = t2, void (this.y = n2);\n }\n if (e25.length === 1 \u0026\u0026 e25[0] instanceof Object \u0026\u0026 e25[0].name === \"segment\") {\n let { start: t2, end: n2 } = e25[0];\n return this.x = n2.x - t2.x, void (this.y = n2.y - t2.y);\n }\n if (e25.length === 2) {\n let t2 = e25[0], n2 = e25[1];\n if (typeof t2 == \"number\" \u0026\u0026 typeof n2 == \"number\")\n return this.x = t2, void (this.y = n2);\n if (t2 instanceof kg.Point \u0026\u0026 n2 instanceof kg.Point)\n return this.x = n2.x - t2.x, void (this.y = n2.y - t2.y);\n }\n throw Dg.ILLEGAL_PARAMETERS;\n }\n }\n clone() {\n return new kg.Vector(this.x, this.y);\n }\n get slope() {\n let e25 = Math.atan2(this.y, this.x);\n return e25 \u003c 0 \u0026\u0026 (e25 = 2 * Math.PI + e25), e25;\n }\n get length() {\n return Math.sqrt(this.dot(this));\n }\n isZeroLength() {\n return kg.Utils.EQ_0(this.length);\n }\n equalTo(e25) {\n return kg.Utils.EQ(this.x, e25.x) \u0026\u0026 kg.Utils.EQ(this.y, e25.y);\n }\n multiply(e25) {\n return new kg.Vector(e25 * this.x, e25 * this.y);\n }\n dot(e25) {\n return this.x * e25.x + this.y * e25.y;\n }\n cross(e25) {\n return this.x * e25.y - this.y * e25.x;\n }\n normalize() {\n if (this.isZeroLength())\n throw Dg.ZERO_DIVISION;\n return new kg.Vector(this.x / this.length, this.y / this.length);\n }\n rotate(e25, t2 = new kg.Point) {\n if (t2.x === 0 \u0026\u0026 t2.y === 0)\n return this.transform(new f_().rotate(e25));\n throw Dg.OPERATION_IS_NOT_SUPPORTED;\n }\n transform(e25) {\n return new kg.Vector(e25.transform([this.x, this.y]));\n }\n rotate90CCW() {\n return new kg.Vector(-this.y, this.x);\n }\n rotate90CW() {\n return new kg.Vector(this.y, -this.x);\n }\n invert() {\n return new kg.Vector(-this.x, -this.y);\n }\n add(e25) {\n return new kg.Vector(this.x + e25.x, this.y + e25.y);\n }\n subtract(e25) {\n return new kg.Vector(this.x - e25.x, this.y - e25.y);\n }\n angleTo(e25) {\n let t2 = this.normalize(), n2 = e25.normalize(), o3 = Math.atan2(t2.cross(n2), t2.dot(n2));\n return o3 \u003c 0 \u0026\u0026 (o3 += 2 * Math.PI), o3;\n }\n projectionOn(e25) {\n let t2 = e25.normalize(), n2 = this.dot(t2);\n return t2.multiply(n2);\n }\n get name() {\n return \"vector\";\n }\n};\nkg.Vector = P_;\nvar M_ = (...e25) =\u003e new kg.Vector(...e25);\nkg.vector = M_;\nvar w_ = class e25 extends I_ {\n constructor(...e26) {\n if (super(), this.ps = new kg.Point, this.pe = new kg.Point, e26.length !== 0) {\n if (e26.length === 1 \u0026\u0026 e26[0] instanceof Array \u0026\u0026 e26[0].length === 4) {\n let t2 = e26[0];\n return this.ps = new kg.Point(t2[0], t2[1]), void (this.pe = new kg.Point(t2[2], t2[3]));\n }\n if (e26.length === 1 \u0026\u0026 e26[0] instanceof Object \u0026\u0026 e26[0].name === \"segment\") {\n let { ps: t2, pe: n2 } = e26[0];\n return this.ps = new kg.Point(t2.x, t2.y), void (this.pe = new kg.Point(n2.x, n2.y));\n }\n if (!(e26.length === 1 \u0026\u0026 e26[0] instanceof kg.Point)) {\n if (e26.length === 2 \u0026\u0026 e26[0] instanceof kg.Point \u0026\u0026 e26[1] instanceof kg.Point)\n return this.ps = e26[0].clone(), void (this.pe = e26[1].clone());\n if (e26.length === 4)\n return this.ps = new kg.Point(e26[0], e26[1]), void (this.pe = new kg.Point(e26[2], e26[3]));\n throw Dg.ILLEGAL_PARAMETERS;\n }\n this.ps = e26[0].clone();\n }\n }\n clone() {\n return new kg.Segment(this.start, this.end);\n }\n get start() {\n return this.ps;\n }\n get end() {\n return this.pe;\n }\n get vertices() {\n return [this.ps.clone(), this.pe.clone()];\n }\n get length() {\n return this.start.distanceTo(this.end)[0];\n }\n get slope() {\n return new kg.Vector(this.start, this.end).slope;\n }\n get box() {\n return new kg.Box(Math.min(this.start.x, this.end.x), Math.min(this.start.y, this.end.y), Math.max(this.start.x, this.end.x), Math.max(this.start.y, this.end.y));\n }\n equalTo(e26) {\n return this.ps.equalTo(e26.ps) \u0026\u0026 this.pe.equalTo(e26.pe);\n }\n contains(e26) {\n return kg.Utils.EQ_0(this.distanceToPoint(e26));\n }\n intersect(e26) {\n return e26 instanceof kg.Point ? this.contains(e26) ? [e26] : [] : e26 instanceof kg.Line ? Hg(this, e26) : e26 instanceof kg.Ray ? uf(e26, this) : e26 instanceof kg.Segment ? Vg(this, e26) : e26 instanceof kg.Circle ? Ug(this, e26) : e26 instanceof kg.Box ? function(e27, t2) {\n let n2 = [];\n for (let o3 of t2.toSegments()) {\n let t3 = Vg(o3, e27);\n for (let e28 of t3)\n n2.push(e28);\n }\n return n2;\n }(this, e26) : e26 instanceof kg.Arc ? Zg(this, e26) : e26 instanceof kg.Polygon ? of(this, e26) : e26 instanceof kg.Multiline ? yf(this, e26) : undefined;\n }\n distanceTo(e26) {\n if (e26 instanceof kg.Point) {\n let [t2, n2] = kg.Distance.point2segment(e26, this);\n return n2 = n2.reverse(), [t2, n2];\n }\n if (e26 instanceof kg.Circle) {\n let [t2, n2] = kg.Distance.segment2circle(this, e26);\n return [t2, n2];\n }\n if (e26 instanceof kg.Line) {\n let [t2, n2] = kg.Distance.segment2line(this, e26);\n return [t2, n2];\n }\n if (e26 instanceof kg.Segment) {\n let [t2, n2] = kg.Distance.segment2segment(this, e26);\n return [t2, n2];\n }\n if (e26 instanceof kg.Arc) {\n let [t2, n2] = kg.Distance.segment2arc(this, e26);\n return [t2, n2];\n }\n if (e26 instanceof kg.Box) {\n let [t2, n2] = kg.Distance.shape2polygon(this, new kg.Polygon(e26));\n return [t2, n2];\n }\n if (e26 instanceof kg.Polygon) {\n let [t2, n2] = kg.Distance.shape2polygon(this, e26);\n return [t2, n2];\n }\n if (e26 instanceof kg.PlanarSet) {\n let [t2, n2] = kg.Distance.shape2planarSet(this, e26);\n return [t2, n2];\n }\n if (e26 instanceof kg.Multiline)\n return kg.Distance.shape2multiline(this, e26);\n }\n tangentInStart() {\n return new kg.Vector(this.start, this.end).normalize();\n }\n tangentInEnd() {\n return new kg.Vector(this.end, this.start).normalize();\n }\n reverse() {\n return new e25(this.end, this.start);\n }\n split(e26) {\n return this.start.equalTo(e26) ? [null, this.clone()] : this.end.equalTo(e26) ? [this.clone(), null] : [new kg.Segment(this.start, e26), new kg.Segment(e26, this.end)];\n }\n middle() {\n return new kg.Point((this.start.x + this.end.x) / 2, (this.start.y + this.end.y) / 2);\n }\n pointAtLength(e26) {\n if (e26 \u003e this.length || e26 \u003c 0)\n return null;\n if (e26 == 0)\n return this.start;\n if (e26 == this.length)\n return this.end;\n let t2 = e26 / this.length;\n return new kg.Point((this.end.x - this.start.x) * t2 + this.start.x, (this.end.y - this.start.y) * t2 + this.start.y);\n }\n distanceToPoint(e26) {\n let [t2, ...n2] = kg.Distance.point2segment(e26, this);\n return t2;\n }\n definiteIntegral(e26 = 0) {\n return (this.end.x - this.start.x) * (this.start.y - e26 + (this.end.y - e26)) / 2;\n }\n transform(t2 = new kg.Matrix) {\n return new e25(this.ps.transform(t2), this.pe.transform(t2));\n }\n isZeroLength() {\n return this.ps.equalTo(this.pe);\n }\n sortPoints(e26) {\n return new kg.Line(this.start, this.end).sortPoints(e26);\n }\n get name() {\n return \"segment\";\n }\n svg(e26 = {}) {\n return `\n\u003cline x1=\"${this.start.x}\" y1=\"${this.start.y}\" x2=\"${this.end.x}\" y2=\"${this.end.y}\" ${Fg(e26)} /\u003e`;\n }\n};\nkg.Segment = w_;\nvar N_ = (...e26) =\u003e new kg.Segment(...e26);\nkg.segment = N_;\nvar { vector: R_ } = kg;\nkg.Line = class e26 extends I_ {\n constructor(...t2) {\n if (super(), this.pt = new kg.Point, this.norm = new kg.Vector(0, 1), t2.length !== 0) {\n if (t2.length === 1 \u0026\u0026 t2[0] instanceof Object \u0026\u0026 t2[0].name === \"line\") {\n let { pt: e27, norm: n2 } = t2[0];\n return this.pt = new kg.Point(e27), void (this.norm = new kg.Vector(n2));\n }\n if (t2.length === 2) {\n let n2 = t2[0], o3 = t2[1];\n if (n2 instanceof kg.Point \u0026\u0026 o3 instanceof kg.Point)\n return this.pt = n2, this.norm = e26.points2norm(n2, o3), void (this.norm.dot(R_(this.pt.x, this.pt.y)) \u003e= 0 \u0026\u0026 this.norm.invert());\n if (n2 instanceof kg.Point \u0026\u0026 o3 instanceof kg.Vector) {\n if (kg.Utils.EQ_0(o3.x) \u0026\u0026 kg.Utils.EQ_0(o3.y))\n throw Dg.ILLEGAL_PARAMETERS;\n return this.pt = n2.clone(), this.norm = o3.clone(), this.norm = this.norm.normalize(), void (this.norm.dot(R_(this.pt.x, this.pt.y)) \u003e= 0 \u0026\u0026 this.norm.invert());\n }\n if (n2 instanceof kg.Vector \u0026\u0026 o3 instanceof kg.Point) {\n if (kg.Utils.EQ_0(n2.x) \u0026\u0026 kg.Utils.EQ_0(n2.y))\n throw Dg.ILLEGAL_PARAMETERS;\n return this.pt = o3.clone(), this.norm = n2.clone(), this.norm = this.norm.normalize(), void (this.norm.dot(R_(this.pt.x, this.pt.y)) \u003e= 0 \u0026\u0026 this.norm.invert());\n }\n }\n throw Dg.ILLEGAL_PARAMETERS;\n }\n }\n clone() {\n return new kg.Line(this.pt, this.norm);\n }\n get start() {}\n get end() {}\n get length() {\n return Number.POSITIVE_INFINITY;\n }\n get box() {\n return new kg.Box(Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY);\n }\n get middle() {}\n get slope() {\n return new kg.Vector(this.norm.y, -this.norm.x).slope;\n }\n get standard() {\n return [this.norm.x, this.norm.y, this.norm.dot(R_(this.pt.x, this.pt.y))];\n }\n parallelTo(e27) {\n return kg.Utils.EQ_0(this.norm.cross(e27.norm));\n }\n incidentTo(e27) {\n return this.parallelTo(e27) \u0026\u0026 this.pt.on(e27);\n }\n contains(e27) {\n if (this.pt.equalTo(e27))\n return true;\n let t2 = new kg.Vector(this.pt, e27);\n return kg.Utils.EQ_0(this.norm.dot(t2));\n }\n coord(e27) {\n return R_(e27.x, e27.y).cross(this.norm);\n }\n intersect(e27) {\n return e27 instanceof kg.Point ? this.contains(e27) ? [e27] : [] : e27 instanceof kg.Line ? jg(this, e27) : e27 instanceof kg.Ray ? gf(e27, this) : e27 instanceof kg.Circle ? $g(this, e27) : e27 instanceof kg.Box ? Yg(this, e27) : e27 instanceof kg.Segment ? Hg(e27, this) : e27 instanceof kg.Arc ? Xg(this, e27) : e27 instanceof kg.Polygon ? sf(this, e27) : e27 instanceof kg.Multiline ? yf(this, e27) : undefined;\n }\n distanceTo(e27) {\n if (e27 instanceof kg.Point) {\n let [t2, n2] = kg.Distance.point2line(e27, this);\n return n2 = n2.reverse(), [t2, n2];\n }\n if (e27 instanceof kg.Circle) {\n let [t2, n2] = kg.Distance.circle2line(e27, this);\n return n2 = n2.reverse(), [t2, n2];\n }\n if (e27 instanceof kg.Segment) {\n let [t2, n2] = kg.Distance.segment2line(e27, this);\n return [t2, n2.reverse()];\n }\n if (e27 instanceof kg.Arc) {\n let [t2, n2] = kg.Distance.arc2line(e27, this);\n return [t2, n2.reverse()];\n }\n if (e27 instanceof kg.Box) {\n let [t2, n2] = kg.Distance.shape2polygon(this, new kg.Polygon(e27));\n return [t2, n2];\n }\n if (e27 instanceof kg.Polygon) {\n let [t2, n2] = kg.Distance.shape2polygon(this, e27);\n return [t2, n2];\n }\n }\n split(e27) {\n if (e27 instanceof kg.Point)\n return [new kg.Ray(e27, this.norm), new kg.Ray(e27, this.norm)];\n {\n let t2 = new kg.Multiline([this]), n2 = this.sortPoints(e27);\n return t2.split(n2), t2.toShapes();\n }\n }\n rotate(e27, t2 = new kg.Point) {\n return new kg.Line(this.pt.rotate(e27, t2), this.norm.rotate(e27));\n }\n transform(e27) {\n return new kg.Line(this.pt.transform(e27), this.norm.clone());\n }\n sortPoints(e27) {\n return e27.slice().sort((e28, t2) =\u003e this.coord(e28) \u003c this.coord(t2) ? -1 : this.coord(e28) \u003e this.coord(t2) ? 1 : 0);\n }\n get name() {\n return \"line\";\n }\n svg(e27, t2 = {}) {\n let n2 = Yg(this, e27);\n if (n2.length === 0)\n return \"\";\n let o3 = n2[0], i3 = n2.length === 2 ? n2[1] : n2.find((e28) =\u003e !e28.equalTo(o3));\n return i3 === undefined \u0026\u0026 (i3 = o3), new kg.Segment(o3, i3).svg(t2);\n }\n static points2norm(e27, t2) {\n if (e27.equalTo(t2))\n throw Dg.ILLEGAL_PARAMETERS;\n return new kg.Vector(e27, t2).normalize().rotate90CCW();\n }\n};\nvar T_ = (...e27) =\u003e new kg.Line(...e27);\nkg.line = T_;\nvar E_ = class extends I_ {\n constructor(...e27) {\n if (super(), this.pc = new kg.Point, this.r = 1, e27.length === 1 \u0026\u0026 e27[0] instanceof Object \u0026\u0026 e27[0].name === \"circle\") {\n let { pc: t2, r: n2 } = e27[0];\n this.pc = new kg.Point(t2), this.r = n2;\n } else {\n let [t2, n2] = [...e27];\n t2 \u0026\u0026 t2 instanceof kg.Point \u0026\u0026 (this.pc = t2.clone()), n2 !== undefined \u0026\u0026 (this.r = n2);\n }\n }\n clone() {\n return new kg.Circle(this.pc.clone(), this.r);\n }\n get center() {\n return this.pc;\n }\n get box() {\n return new kg.Box(this.pc.x - this.r, this.pc.y - this.r, this.pc.x + this.r, this.pc.y + this.r);\n }\n contains(e27) {\n return e27 instanceof kg.Point ? kg.Utils.LE(e27.distanceTo(this.center)[0], this.r) : e27 instanceof kg.Segment ? kg.Utils.LE(e27.start.distanceTo(this.center)[0], this.r) \u0026\u0026 kg.Utils.LE(e27.end.distanceTo(this.center)[0], this.r) : e27 instanceof kg.Arc ? this.intersect(e27).length === 0 \u0026\u0026 kg.Utils.LE(e27.start.distanceTo(this.center)[0], this.r) \u0026\u0026 kg.Utils.LE(e27.end.distanceTo(this.center)[0], this.r) : e27 instanceof kg.Circle ? this.intersect(e27).length === 0 \u0026\u0026 kg.Utils.LE(e27.r, this.r) \u0026\u0026 kg.Utils.LE(e27.center.distanceTo(this.center)[0], this.r) : undefined;\n }\n toArc(e27 = true) {\n return new kg.Arc(this.center, this.r, Math.PI, -Math.PI, e27);\n }\n scale(e27, t2) {\n if (e27 !== t2)\n throw Dg.OPERATION_IS_NOT_SUPPORTED;\n if (this.pc.x !== 0 || this.pc.y !== 0)\n throw Dg.OPERATION_IS_NOT_SUPPORTED;\n return new kg.Circle(this.pc, this.r * e27);\n }\n transform(e27 = new kg.Matrix) {\n return new kg.Circle(this.pc.transform(e27), this.r);\n }\n intersect(e27) {\n return e27 instanceof kg.Point ? this.contains(e27) ? [e27] : [] : e27 instanceof kg.Line ? $g(e27, this) : e27 instanceof kg.Ray ? mf(e27, this) : e27 instanceof kg.Segment ? Ug(e27, this) : e27 instanceof kg.Circle ? qg(e27, this) : e27 instanceof kg.Box ? function(e28, t2) {\n let n2 = [];\n for (let o3 of t2.toSegments()) {\n let t3 = Ug(o3, e28);\n for (let e29 of t3)\n n2.push(e29);\n }\n return n2;\n }(this, e27) : e27 instanceof kg.Arc ? Qg(e27, this) : e27 instanceof kg.Polygon ? af(this, e27) : e27 instanceof kg.Multiline ? yf(this, e27) : undefined;\n }\n distanceTo(e27) {\n if (e27 instanceof kg.Point) {\n let [t2, n2] = kg.Distance.point2circle(e27, this);\n return n2 = n2.reverse(), [t2, n2];\n }\n if (e27 instanceof kg.Circle) {\n let [t2, n2] = kg.Distance.circle2circle(this, e27);\n return [t2, n2];\n }\n if (e27 instanceof kg.Line) {\n let [t2, n2] = kg.Distance.circle2line(this, e27);\n return [t2, n2];\n }\n if (e27 instanceof kg.Segment) {\n let [t2, n2] = kg.Distance.segment2circle(e27, this);\n return n2 = n2.reverse(), [t2, n2];\n }\n if (e27 instanceof kg.Arc) {\n let [t2, n2] = kg.Distance.arc2circle(e27, this);\n return n2 = n2.reverse(), [t2, n2];\n }\n if (e27 instanceof kg.Box) {\n let [t2, n2] = kg.Distance.shape2polygon(this, new kg.Polygon(e27));\n return [t2, n2];\n }\n if (e27 instanceof kg.Polygon) {\n let [t2, n2] = kg.Distance.shape2polygon(this, e27);\n return [t2, n2];\n }\n if (e27 instanceof kg.PlanarSet) {\n let [t2, n2] = kg.Distance.shape2planarSet(this, e27);\n return [t2, n2];\n }\n if (e27 instanceof kg.Multiline) {\n let [t2, n2] = kg.Distance.shape2multiline(this, e27);\n return [t2, n2];\n }\n }\n get name() {\n return \"circle\";\n }\n svg(e27 = {}) {\n return `\n\u003ccircle cx=\"${this.pc.x}\" cy=\"${this.pc.y}\" r=\"${this.r}\"\n ${Fg({ fill: \"none\", ...e27 })} /\u003e`;\n }\n};\nkg.Circle = E_;\nkg.circle = (...e27) =\u003e new kg.Circle(...e27);\nvar A_ = class extends I_ {\n constructor(...e27) {\n if (super(), this.pc = new kg.Point, this.r = 1, this.startAngle = 0, this.endAngle = 2 * Math.PI, this.counterClockwise = true, e27.length !== 0)\n if (e27.length === 1 \u0026\u0026 e27[0] instanceof Object \u0026\u0026 e27[0].name === \"arc\") {\n let { pc: t2, r: n2, startAngle: o3, endAngle: i3, counterClockwise: r3 } = e27[0];\n this.pc = new kg.Point(t2.x, t2.y), this.r = n2, this.startAngle = o3, this.endAngle = i3, this.counterClockwise = r3;\n } else {\n let [t2, n2, o3, i3, r3] = [...e27];\n t2 \u0026\u0026 t2 instanceof kg.Point \u0026\u0026 (this.pc = t2.clone()), n2 !== undefined \u0026\u0026 (this.r = n2), o3 !== undefined \u0026\u0026 (this.startAngle = o3), i3 !== undefined \u0026\u0026 (this.endAngle = i3), r3 !== undefined \u0026\u0026 (this.counterClockwise = r3);\n }\n }\n clone() {\n return new kg.Arc(this.pc.clone(), this.r, this.startAngle, this.endAngle, this.counterClockwise);\n }\n get sweep() {\n let e27 = this.startAngle, t2 = this.endAngle;\n if (kg.Utils.EQ(Math.abs(e27 - t2), kg.PIx2))\n return kg.PIx2;\n Math.abs(e27) \u003e kg.PIx2 \u0026\u0026 (e27 -= Math.trunc(e27 / kg.PIx2) * kg.PIx2), e27 \u003c 0 \u0026\u0026 (e27 += kg.PIx2), Math.abs(t2) \u003e kg.PIx2 \u0026\u0026 (t2 -= Math.trunc(t2 / kg.PIx2) * kg.PIx2), t2 \u003c 0 \u0026\u0026 (t2 += kg.PIx2);\n let n2 = this.counterClockwise ? t2 - e27 : e27 - t2;\n return n2 \u003c 0 \u0026\u0026 (n2 += kg.PIx2), n2;\n }\n get start() {\n return new kg.Point(this.pc.x + this.r, this.pc.y).rotate(this.startAngle, this.pc);\n }\n get end() {\n return new kg.Point(this.pc.x + this.r, this.pc.y).rotate(this.endAngle, this.pc);\n }\n get center() {\n return this.pc.clone();\n }\n get vertices() {\n return [this.start.clone(), this.end.clone()];\n }\n get length() {\n return Math.abs(this.sweep * this.r);\n }\n get box() {\n let e27 = this.breakToFunctional().reduce((e28, t2) =\u003e e28.merge(t2.start.box), new kg.Box);\n return e27 = e27.merge(this.end.box), e27;\n }\n contains(e27) {\n if (!kg.Utils.EQ(this.pc.distanceTo(e27)[0], this.r))\n return false;\n if (e27.equalTo(this.start))\n return true;\n let t2 = new kg.Vector(this.pc, e27).slope, n2 = new kg.Arc(this.pc, this.r, this.startAngle, t2, this.counterClockwise);\n return kg.Utils.LE(n2.length, this.length);\n }\n split(e27) {\n if (this.start.equalTo(e27))\n return [null, this.clone()];\n if (this.end.equalTo(e27))\n return [this.clone(), null];\n let t2 = new kg.Vector(this.pc, e27).slope;\n return [new kg.Arc(this.pc, this.r, this.startAngle, t2, this.counterClockwise), new kg.Arc(this.pc, this.r, t2, this.endAngle, this.counterClockwise)];\n }\n middle() {\n let e27 = this.counterClockwise ? this.startAngle + this.sweep / 2 : this.startAngle - this.sweep / 2;\n return new kg.Arc(this.pc, this.r, this.startAngle, e27, this.counterClockwise).end;\n }\n pointAtLength(e27) {\n if (e27 \u003e this.length || e27 \u003c 0)\n return null;\n if (e27 === 0)\n return this.start;\n if (e27 === this.length)\n return this.end;\n let t2 = e27 / this.length, n2 = this.counterClockwise ? this.startAngle + this.sweep * t2 : this.startAngle - this.sweep * t2;\n return new kg.Arc(this.pc, this.r, this.startAngle, n2, this.counterClockwise).end;\n }\n chordHeight() {\n return (1 - Math.cos(Math.abs(this.sweep / 2))) * this.r;\n }\n intersect(e27) {\n return e27 instanceof kg.Point ? this.contains(e27) ? [e27] : [] : e27 instanceof kg.Line ? Xg(e27, this) : e27 instanceof kg.Ray ? pf(e27, this) : e27 instanceof kg.Circle ? Qg(this, e27) : e27 instanceof kg.Segment ? Zg(e27, this) : e27 instanceof kg.Box ? function(e28, t2) {\n let n2 = [];\n for (let o3 of t2.toSegments()) {\n let t3 = Zg(o3, e28);\n for (let e29 of t3)\n n2.push(e29);\n }\n return n2;\n }(this, e27) : e27 instanceof kg.Arc ? Jg(this, e27) : e27 instanceof kg.Polygon ? rf(this, e27) : e27 instanceof kg.Multiline ? yf(this, e27) : undefined;\n }\n distanceTo(e27) {\n if (e27 instanceof kg.Point) {\n let [t2, n2] = kg.Distance.point2arc(e27, this);\n return n2 = n2.reverse(), [t2, n2];\n }\n if (e27 instanceof kg.Circle) {\n let [t2, n2] = kg.Distance.arc2circle(this, e27);\n return [t2, n2];\n }\n if (e27 instanceof kg.Line) {\n let [t2, n2] = kg.Distance.arc2line(this, e27);\n return [t2, n2];\n }\n if (e27 instanceof kg.Segment) {\n let [t2, n2] = kg.Distance.segment2arc(e27, this);\n return n2 = n2.reverse(), [t2, n2];\n }\n if (e27 instanceof kg.Arc) {\n let [t2, n2] = kg.Distance.arc2arc(this, e27);\n return [t2, n2];\n }\n if (e27 instanceof kg.Box) {\n let [t2, n2] = kg.Distance.shape2polygon(this, new kg.Polygon(e27));\n return [t2, n2];\n }\n if (e27 instanceof kg.Polygon) {\n let [t2, n2] = kg.Distance.shape2polygon(this, e27);\n return [t2, n2];\n }\n if (e27 instanceof kg.PlanarSet) {\n let [t2, n2] = kg.Distance.shape2planarSet(this, e27);\n return [t2, n2];\n }\n if (e27 instanceof kg.Multiline)\n return kg.Distance.shape2multiline(this, e27);\n }\n breakToFunctional() {\n let e27 = [], t2 = [0, Math.PI / 2, Math.PI, 3 * Math.PI / 2], n2 = this.startAngle, o3 = this.endAngle;\n kg.Utils.EQ(Math.abs(n2 - o3), kg.PIx2) \u0026\u0026 (o3 = n2), Math.abs(n2) \u003e kg.PIx2 \u0026\u0026 (n2 -= Math.trunc(n2 / kg.PIx2) * kg.PIx2), n2 \u003c 0 \u0026\u0026 (n2 += kg.PIx2), Math.abs(o3) \u003e kg.PIx2 \u0026\u0026 (o3 -= Math.trunc(o3 / kg.PIx2) * kg.PIx2), o3 \u003c 0 \u0026\u0026 (o3 += kg.PIx2);\n let i3, r3, s2, a3 = n2;\n this.counterClockwise ? (r3 = Math.ceil(n2 / (Math.PI / 2)) % 4, s2 = 1) : (r3 = Math.floor(n2 / (Math.PI / 2)) % 4, s2 = -1);\n for (let o4 = 0, c3 = r3;o4 \u003c 4; o4++, c3 = (c3 + s2 + 4) % 4) {\n if (i3 = t2[c3], i3 === a3)\n continue;\n let o5 = this.counterClockwise ? i3 - n2 : n2 - i3;\n if (o5 \u003c 0 \u0026\u0026 (o5 += kg.PIx2), o5 \u003e this.sweep)\n break;\n e27.push(new kg.Arc(this.pc, this.r, a3, i3, this.counterClockwise)), a3 = i3;\n }\n return e27.length === 0 ? (e27.push(this), e27) : (i3 = o3, a3 !== i3 \u0026\u0026 e27.push(new kg.Arc(this.pc, this.r, a3, i3, this.counterClockwise)), e27);\n }\n tangentInStart() {\n let e27 = new kg.Vector(this.pc, this.start), t2 = this.counterClockwise ? Math.PI / 2 : -Math.PI / 2;\n return e27.rotate(t2).normalize();\n }\n tangentInEnd() {\n let e27 = new kg.Vector(this.pc, this.end), t2 = this.counterClockwise ? -Math.PI / 2 : Math.PI / 2;\n return e27.rotate(t2).normalize();\n }\n reverse() {\n return new kg.Arc(this.pc, this.r, this.endAngle, this.startAngle, !this.counterClockwise);\n }\n transform(e27 = new kg.Matrix) {\n let t2 = this.start.transform(e27), n2 = this.end.transform(e27), o3 = this.pc.transform(e27), i3 = this.counterClockwise;\n return e27.a * e27.d \u003c 0 \u0026\u0026 (i3 = !i3), kg.Arc.arcSE(o3, t2, n2, i3);\n }\n static arcSE(e27, t2, n2, o3) {\n let { vector: i3 } = kg, r3 = i3(e27, t2).slope, s2 = i3(e27, n2).slope;\n kg.Utils.EQ(r3, s2) \u0026\u0026 (s2 += 2 * Math.PI, o3 = true);\n let a3 = i3(e27, t2).length;\n return new kg.Arc(e27, a3, r3, s2, o3);\n }\n definiteIntegral(e27 = 0) {\n return this.breakToFunctional().reduce((t2, n2) =\u003e t2 + n2.circularSegmentDefiniteIntegral(e27), 0);\n }\n circularSegmentDefiniteIntegral(e27) {\n let t2 = new kg.Segment(this.start, this.end).definiteIntegral(e27), n2 = kg.Utils.EQ(this.sweep, kg.PIx2) ? 0 : this.circularSegmentArea();\n return this.counterClockwise ? t2 - n2 : t2 + n2;\n }\n circularSegmentArea() {\n return 0.5 * this.r * this.r * (this.sweep - Math.sin(this.sweep));\n }\n sortPoints(e27) {\n let { vector: t2 } = kg;\n return e27.slice().sort((e28, n2) =\u003e {\n let o3 = t2(this.pc, e28).slope, i3 = t2(this.pc, n2).slope;\n return o3 \u003c i3 ? -1 : o3 \u003e i3 ? 1 : 0;\n });\n }\n get name() {\n return \"arc\";\n }\n svg(e27 = {}) {\n let t2 = this.sweep \u003c= Math.PI ? \"0\" : \"1\", n2 = this.counterClockwise ? \"1\" : \"0\";\n if (kg.Utils.EQ(this.sweep, 2 * Math.PI)) {\n return new kg.Circle(this.pc, this.r).svg(e27);\n }\n return `\n\u003cpath d=\"M${this.start.x},${this.start.y}\n A${this.r},${this.r} 0 ${t2},${n2} ${this.end.x},${this.end.y}\"\n ${Fg({ fill: \"none\", ...e27 })} /\u003e`;\n }\n};\nkg.Arc = A_;\nkg.arc = (...e27) =\u003e new kg.Arc(...e27);\nvar O_ = class e27 extends I_ {\n constructor(e28 = undefined, t2 = undefined, n2 = undefined, o3 = undefined) {\n super(), this.xmin = e28, this.ymin = t2, this.xmax = n2, this.ymax = o3;\n }\n clone() {\n return new e27(this.xmin, this.ymin, this.xmax, this.ymax);\n }\n get low() {\n return new kg.Point(this.xmin, this.ymin);\n }\n get high() {\n return new kg.Point(this.xmax, this.ymax);\n }\n get max() {\n return this.clone();\n }\n get center() {\n return new kg.Point((this.xmin + this.xmax) / 2, (this.ymin + this.ymax) / 2);\n }\n get width() {\n return Math.abs(this.xmax - this.xmin);\n }\n get height() {\n return Math.abs(this.ymax - this.ymin);\n }\n get box() {\n return this.clone();\n }\n not_intersect(e28) {\n return this.xmax \u003c e28.xmin || this.xmin \u003e e28.xmax || this.ymax \u003c e28.ymin || this.ymin \u003e e28.ymax;\n }\n intersect(e28) {\n return !this.not_intersect(e28);\n }\n merge(t2) {\n return new e27(this.xmin === undefined ? t2.xmin : Math.min(this.xmin, t2.xmin), this.ymin === undefined ? t2.ymin : Math.min(this.ymin, t2.ymin), this.xmax === undefined ? t2.xmax : Math.max(this.xmax, t2.xmax), this.ymax === undefined ? t2.ymax : Math.max(this.ymax, t2.ymax));\n }\n less_than(e28) {\n return !!this.low.lessThan(e28.low) || !(!this.low.equalTo(e28.low) || !this.high.lessThan(e28.high));\n }\n equal_to(e28) {\n return this.low.equalTo(e28.low) \u0026\u0026 this.high.equalTo(e28.high);\n }\n output() {\n return this.clone();\n }\n comparable_less_than(e28, t2) {\n return e28.lessThan(t2);\n }\n set(e28, t2, n2, o3) {\n this.xmin = e28, this.ymin = t2, this.xmax = n2, this.ymax = o3;\n }\n extend(t2) {\n return t2 \u003c= 0 ? this.clone() : new e27(this.xmin - t2, this.ymin - t2, this.xmax + t2, this.ymax + t2);\n }\n toPoints() {\n return [new kg.Point(this.xmin, this.ymin), new kg.Point(this.xmax, this.ymin), new kg.Point(this.xmax, this.ymax), new kg.Point(this.xmin, this.ymax)];\n }\n toSegments() {\n let e28 = this.toPoints();\n return [new kg.Segment(e28[0], e28[1]), new kg.Segment(e28[1], e28[2]), new kg.Segment(e28[2], e28[3]), new kg.Segment(e28[3], e28[0])];\n }\n rotate(e28, t2 = new kg.Point) {\n throw Dg.OPERATION_IS_NOT_SUPPORTED;\n }\n transform(t2 = new kg.Matrix) {\n return this.toPoints().map((e28) =\u003e e28.transform(t2)).reduce((e28, t3) =\u003e e28.merge(t3.box), new e27);\n }\n contains(e28) {\n return e28 instanceof kg.Point ? e28.x \u003e= this.xmin \u0026\u0026 e28.x \u003c= this.xmax \u0026\u0026 e28.y \u003e= this.ymin \u0026\u0026 e28.y \u003c= this.ymax : e28 instanceof kg.Segment ? e28.vertices.every((e29) =\u003e this.contains(e29)) : e28 instanceof kg.Box ? e28.toSegments().every((e29) =\u003e this.contains(e29)) : e28 instanceof kg.Circle ? this.contains(e28.box) : e28 instanceof kg.Arc ? e28.vertices.every((e29) =\u003e this.contains(e29)) \u0026\u0026 this.toSegments().every((t2) =\u003e Zg(t2, e28).length === 0) : !(e28 instanceof kg.Line || e28 instanceof kg.Ray) \u0026\u0026 (e28 instanceof kg.Multiline ? e28.toShapes().every((e29) =\u003e this.contains(e29)) : e28 instanceof kg.Polygon ? this.contains(e28.box) : undefined);\n }\n distanceTo(e28) {\n const t2 = this.toSegments().map((t3) =\u003e t3.distanceTo(e28));\n let n2 = [Number.MAX_SAFE_INTEGER, null];\n return t2.forEach((e29) =\u003e {\n e29[0] \u003c n2[0] \u0026\u0026 (n2 = e29);\n }), n2;\n }\n get name() {\n return \"box\";\n }\n svg(e28 = {}) {\n const t2 = this.xmax - this.xmin, n2 = this.ymax - this.ymin;\n return `\n\u003crect x=\"${this.xmin}\" y=\"${this.ymin}\" width=\"${t2}\" height=\"${n2}\"\n ${Fg({ fill: \"none\", ...e28 })} /\u003e`;\n }\n};\nkg.Box = O_;\nkg.box = (...e28) =\u003e new kg.Box(...e28);\nkg.Edge = class {\n constructor(e28) {\n this.shape = e28, this.next = undefined, this.prev = undefined, this.face = undefined, this.arc_length = 0, this.bvStart = undefined, this.bvEnd = undefined, this.bv = undefined, this.overlap = undefined;\n }\n get start() {\n return this.shape.start;\n }\n get end() {\n return this.shape.end;\n }\n get length() {\n return this.shape.length;\n }\n get box() {\n return this.shape.box;\n }\n get isSegment() {\n return this.shape instanceof kg.Segment;\n }\n get isArc() {\n return this.shape instanceof kg.Arc;\n }\n get isLine() {\n return this.shape instanceof kg.Line;\n }\n get isRay() {\n return this.shape instanceof kg.Ray;\n }\n middle() {\n return this.shape.middle();\n }\n pointAtLength(e28) {\n return this.shape.pointAtLength(e28);\n }\n contains(e28) {\n return this.shape.contains(e28);\n }\n setInclusion(e28) {\n if (this.bv !== undefined)\n return this.bv;\n if (this.shape instanceof kg.Line || this.shape instanceof kg.Ray)\n return this.bv = kg.OUTSIDE, this.bv;\n if (this.bvStart === undefined \u0026\u0026 (this.bvStart = a_(e28, this.start)), this.bvEnd === undefined \u0026\u0026 (this.bvEnd = a_(e28, this.end)), this.bvStart === kg.OUTSIDE || this.bvEnd == kg.OUTSIDE)\n this.bv = kg.OUTSIDE;\n else if (this.bvStart === kg.INSIDE || this.bvEnd == kg.INSIDE)\n this.bv = kg.INSIDE;\n else {\n let t2 = a_(e28, this.middle());\n this.bv = t2;\n }\n return this.bv;\n }\n setOverlap(e28) {\n let t2, n2 = this.shape, o3 = e28.shape;\n n2 instanceof kg.Segment \u0026\u0026 o3 instanceof kg.Segment ? n2.start.equalTo(o3.start) \u0026\u0026 n2.end.equalTo(o3.end) ? t2 = kg.OVERLAP_SAME : n2.start.equalTo(o3.end) \u0026\u0026 n2.end.equalTo(o3.start) \u0026\u0026 (t2 = kg.OVERLAP_OPPOSITE) : (n2 instanceof kg.Arc \u0026\u0026 o3 instanceof kg.Arc || n2 instanceof kg.Segment \u0026\u0026 o3 instanceof kg.Arc || n2 instanceof kg.Arc \u0026\u0026 o3 instanceof kg.Segment) \u0026\u0026 (n2.start.equalTo(o3.start) \u0026\u0026 n2.end.equalTo(o3.end) \u0026\u0026 n2.middle().equalTo(o3.middle()) ? t2 = kg.OVERLAP_SAME : n2.start.equalTo(o3.end) \u0026\u0026 n2.end.equalTo(o3.start) \u0026\u0026 n2.middle().equalTo(o3.middle()) \u0026\u0026 (t2 = kg.OVERLAP_OPPOSITE)), this.overlap === undefined \u0026\u0026 (this.overlap = t2), e28.overlap === undefined \u0026\u0026 (e28.overlap = t2);\n }\n svg() {\n if (this.shape instanceof kg.Segment)\n return ` L${this.shape.end.x},${this.shape.end.y}`;\n if (this.shape instanceof kg.Arc) {\n let e28, t2 = this.shape, n2 = t2.counterClockwise ? \"1\" : \"0\";\n if (kg.Utils.EQ(t2.sweep, 2 * Math.PI)) {\n let o3 = t2.counterClockwise ? 1 : -1, i3 = new kg.Arc(t2.pc, t2.r, t2.startAngle, t2.startAngle + o3 * Math.PI, t2.counterClockwise), r3 = new kg.Arc(t2.pc, t2.r, t2.startAngle + o3 * Math.PI, t2.endAngle, t2.counterClockwise);\n return e28 = \"0\", ` A${i3.r},${i3.r} 0 ${e28},${n2} ${i3.end.x},${i3.end.y}\n A${r3.r},${r3.r} 0 ${e28},${n2} ${r3.end.x},${r3.end.y}`;\n }\n return e28 = t2.sweep \u003c= Math.PI ? \"0\" : \"1\", ` A${t2.r},${t2.r} 0 ${e28},${n2} ${t2.end.x},${t2.end.y}`;\n }\n }\n toJSON() {\n return this.shape.toJSON();\n }\n};\nvar k_ = class extends Lg {\n constructor(e28, t2) {\n super(e28, t2), this.setCircularLinks();\n }\n setCircularLinks() {\n this.isEmpty() || (this.last.next = this.first, this.first.prev = this.last);\n }\n [Symbol.iterator]() {\n let e28;\n return { next: () =\u003e {\n let t2 = e28 || this.first, n2 = !this.first || !!e28 \u0026\u0026 e28 === this.first;\n return e28 = t2 ? t2.next : undefined, { value: t2, done: n2 };\n } };\n }\n append(e28) {\n return super.append(e28), this.setCircularLinks(), this;\n }\n insert(e28, t2) {\n return super.insert(e28, t2), this.setCircularLinks(), this;\n }\n remove(e28) {\n return super.remove(e28), this;\n }\n};\nkg.Face = class e28 extends k_ {\n constructor(t2, ...n2) {\n if (super(), this._box = undefined, this._orientation = undefined, n2.length !== 0) {\n if (n2.length === 1) {\n if (n2[0] instanceof Array) {\n let o3 = n2[0];\n if (o3.length === 0)\n return;\n if (o3.every((e29) =\u003e e29 instanceof kg.Point)) {\n let n3 = e28.points2segments(o3);\n this.shapes2face(t2.edges, n3);\n } else if (o3.every((e29) =\u003e e29 instanceof Array \u0026\u0026 e29.length === 2)) {\n let n3 = o3.map((e29) =\u003e new kg.Point(e29[0], e29[1])), i3 = e28.points2segments(n3);\n this.shapes2face(t2.edges, i3);\n } else if (o3.every((e29) =\u003e e29 instanceof kg.Segment || e29 instanceof kg.Arc))\n this.shapes2face(t2.edges, o3);\n else if (o3.every((e29) =\u003e e29.name === \"segment\" || e29.name === \"arc\")) {\n let e29 = [];\n for (let t3 of o3) {\n let n3;\n n3 = t3.name === \"segment\" ? new kg.Segment(t3) : new kg.Arc(t3), e29.push(n3);\n }\n this.shapes2face(t2.edges, e29);\n }\n } else if (n2[0] instanceof e28) {\n let e29 = n2[0];\n this.first = e29.first, this.last = e29.last;\n for (let n3 of e29)\n t2.edges.add(n3);\n } else if (n2[0] instanceof kg.Circle)\n this.shapes2face(t2.edges, [n2[0].toArc(Sg)]);\n else if (n2[0] instanceof kg.Box) {\n let e29 = n2[0];\n this.shapes2face(t2.edges, [new kg.Segment(new kg.Point(e29.xmin, e29.ymin), new kg.Point(e29.xmax, e29.ymin)), new kg.Segment(new kg.Point(e29.xmax, e29.ymin), new kg.Point(e29.xmax, e29.ymax)), new kg.Segment(new kg.Point(e29.xmax, e29.ymax), new kg.Point(e29.xmin, e29.ymax)), new kg.Segment(new kg.Point(e29.xmin, e29.ymax), new kg.Point(e29.xmin, e29.ymin))]);\n }\n }\n n2.length === 2 \u0026\u0026 n2[0] instanceof kg.Edge \u0026\u0026 n2[1] instanceof kg.Edge \u0026\u0026 (this.first = n2[0], this.last = n2[1], this.last.next = this.first, this.first.prev = this.last, this.setArcLength());\n }\n }\n get edges() {\n return this.toArray();\n }\n get vertices() {\n return this.edges.map((e29) =\u003e e29.shape.start.clone());\n }\n get shapes() {\n return this.edges.map((e29) =\u003e e29.shape.clone());\n }\n get box() {\n if (this._box === undefined) {\n let e29 = new kg.Box;\n for (let t2 of this)\n e29 = e29.merge(t2.box);\n this._box = e29;\n }\n return this._box;\n }\n get perimeter() {\n return this.last.arc_length + this.last.length;\n }\n pointAtLength(e29) {\n if (e29 \u003e this.perimeter || e29 \u003c 0)\n return null;\n let t2 = null;\n for (let n2 of this)\n if (e29 \u003e= n2.arc_length \u0026\u0026 (n2 === this.last || e29 \u003c n2.next.arc_length)) {\n t2 = n2.pointAtLength(e29 - n2.arc_length);\n break;\n }\n return t2;\n }\n static points2segments(e29) {\n let t2 = [];\n for (let n2 = 0;n2 \u003c e29.length; n2++)\n e29[n2].equalTo(e29[(n2 + 1) % e29.length]) || t2.push(new kg.Segment(e29[n2], e29[(n2 + 1) % e29.length]));\n return t2;\n }\n shapes2face(e29, t2) {\n for (let n2 of t2) {\n let t3 = new kg.Edge(n2);\n this.append(t3), e29.add(t3);\n }\n }\n append(e29) {\n return super.append(e29), this.setOneEdgeArcLength(e29), e29.face = this, this;\n }\n insert(e29, t2) {\n return super.insert(e29, t2), this.setOneEdgeArcLength(e29), e29.face = this, this;\n }\n remove(e29) {\n return super.remove(e29), this.setArcLength(), this;\n }\n merge_with_next_edge(e29) {\n return e29.shape.end.x = e29.next.shape.end.x, e29.shape.end.y = e29.next.shape.end.y, this.remove(e29.next), this;\n }\n reverse() {\n let e29 = [], t2 = this.last;\n do {\n t2.shape = t2.shape.reverse(), e29.push(t2), t2 = t2.prev;\n } while (t2 !== this.last);\n this.first = undefined, this.last = undefined;\n for (let t3 of e29)\n this.first === undefined ? (t3.prev = t3, t3.next = t3, this.first = t3, this.last = t3) : (t3.prev = this.last, this.last.next = t3, this.last = t3, this.last.next = this.first, this.first.prev = this.last), this.setOneEdgeArcLength(t3);\n this._orientation !== undefined \u0026\u0026 (this._orientation = undefined, this._orientation = this.orientation());\n }\n setArcLength() {\n for (let e29 of this)\n this.setOneEdgeArcLength(e29), e29.face = this;\n }\n setOneEdgeArcLength(e29) {\n e29 === this.first ? e29.arc_length = 0 : e29.arc_length = e29.prev.arc_length + e29.prev.length;\n }\n area() {\n return Math.abs(this.signedArea());\n }\n signedArea() {\n let e29 = 0, t2 = this.box.ymin;\n for (let n2 of this)\n e29 += n2.shape.definiteIntegral(t2);\n return e29;\n }\n orientation() {\n if (this._orientation === undefined) {\n let e29 = this.signedArea();\n kg.Utils.EQ_0(e29) ? this._orientation = Cg.NOT_ORIENTABLE : kg.Utils.LT(e29, 0) ? this._orientation = Cg.CCW : this._orientation = Cg.CW;\n }\n return this._orientation;\n }\n isSimple(t2) {\n return e28.getSelfIntersections(this, t2, true).length === 0;\n }\n static getSelfIntersections(e29, t2, n2 = false) {\n let o3 = [];\n for (let i3 of e29) {\n let r3 = t2.search(i3.box);\n for (let t3 of r3) {\n if (i3 === t3)\n continue;\n if (t3.face !== e29)\n continue;\n if (i3.shape instanceof kg.Segment \u0026\u0026 t3.shape instanceof kg.Segment \u0026\u0026 (i3.next === t3 || i3.prev === t3))\n continue;\n let r4 = i3.shape.intersect(t3.shape);\n for (let e30 of r4)\n if ((!e30.equalTo(i3.start) || !e30.equalTo(t3.end) || t3 !== i3.prev) \u0026\u0026 (!e30.equalTo(i3.end) || !e30.equalTo(t3.start) || t3 !== i3.next) \u0026\u0026 (o3.push(e30), n2))\n break;\n if (o3.length \u003e 0 \u0026\u0026 n2)\n break;\n }\n if (o3.length \u003e 0 \u0026\u0026 n2)\n break;\n }\n return o3;\n }\n findEdgeByPoint(e29) {\n let t2;\n for (let n2 of this)\n if (!e29.equalTo(n2.shape.start) \u0026\u0026 (e29.equalTo(n2.shape.end) || n2.shape.contains(e29))) {\n t2 = n2;\n break;\n }\n return t2;\n }\n toPolygon() {\n return new kg.Polygon(this.shapes);\n }\n toJSON() {\n return this.edges.map((e29) =\u003e e29.toJSON());\n }\n svg() {\n let e29 = `M${this.first.start.x},${this.first.start.y}`;\n for (let t2 of this)\n e29 += t2.svg();\n return e29 += \" z\", e29;\n }\n};\nkg.Ray = class e29 extends I_ {\n constructor(...e30) {\n if (super(), this.pt = new kg.Point, this.norm = new kg.Vector(0, 1), e30.length !== 0 \u0026\u0026 (e30.length \u003e= 1 \u0026\u0026 e30[0] instanceof kg.Point \u0026\u0026 (this.pt = e30[0].clone()), e30.length !== 1)) {\n if (!(e30.length === 2 \u0026\u0026 e30[1] instanceof kg.Vector))\n throw Dg.ILLEGAL_PARAMETERS;\n this.norm = e30[1].clone();\n }\n }\n clone() {\n return new e29(this.pt, this.norm);\n }\n get slope() {\n return new kg.Vector(this.norm.y, -this.norm.x).slope;\n }\n get box() {\n let e30 = this.slope;\n return new kg.Box(e30 \u003e Math.PI / 2 \u0026\u0026 e30 \u003c 3 * Math.PI / 2 ? Number.NEGATIVE_INFINITY : this.pt.x, e30 \u003e= 0 \u0026\u0026 e30 \u003c= Math.PI ? this.pt.y : Number.NEGATIVE_INFINITY, e30 \u003e= Math.PI / 2 \u0026\u0026 e30 \u003c= 3 * Math.PI / 2 ? this.pt.x : Number.POSITIVE_INFINITY, e30 \u003e= Math.PI \u0026\u0026 e30 \u003c= 2 * Math.PI || e30 === 0 ? this.pt.y : Number.POSITIVE_INFINITY);\n }\n get start() {\n return this.pt;\n }\n get end() {}\n get length() {\n return Number.POSITIVE_INFINITY;\n }\n contains(e30) {\n if (this.pt.equalTo(e30))\n return true;\n let t2 = new kg.Vector(this.pt, e30);\n return kg.Utils.EQ_0(this.norm.dot(t2)) \u0026\u0026 kg.Utils.GE(t2.cross(this.norm), 0);\n }\n coord(e30) {\n return M_(e30.x, e30.y).cross(this.norm);\n }\n split(e30) {\n return this.contains(e30) ? this.pt.equalTo(e30) ? [this] : [new kg.Segment(this.pt, e30), new kg.Ray(e30, this.norm)] : [];\n }\n intersect(e30) {\n return e30 instanceof kg.Point ? this.contains(e30) ? [e30] : [] : e30 instanceof kg.Segment ? uf(this, e30) : e30 instanceof kg.Arc ? pf(this, e30) : e30 instanceof kg.Line ? gf(this, e30) : e30 instanceof kg.Ray ? (n2 = e30, jg(df(t2 = this), df(n2)).filter((e31) =\u003e t2.contains(e31)).filter((e31) =\u003e n2.contains(e31))) : e30 instanceof kg.Circle ? mf(this, e30) : e30 instanceof kg.Box ? (i3 = e30, Yg(df(o3 = this), i3).filter((e31) =\u003e o3.contains(e31))) : e30 instanceof kg.Polygon ? ff(this, e30) : e30 instanceof kg.Multiline ? yf(this, e30) : undefined;\n var t2, n2, o3, i3;\n }\n rotate(e30, t2 = new kg.Point) {\n return new kg.Ray(this.pt.rotate(e30, t2), this.norm.rotate(e30));\n }\n transform(e30) {\n return new kg.Ray(this.pt.transform(e30), this.norm.clone());\n }\n get name() {\n return \"ray\";\n }\n svg(e30, t2 = {}) {\n let n2 = Yg(new kg.Line(this.pt, this.norm), e30);\n return n2 = n2.filter((e31) =\u003e this.contains(e31)), n2.length === 0 || n2.length === 2 ? \"\" : new kg.Segment(this.pt, n2[0]).svg(t2);\n }\n};\nkg.ray = (...e30) =\u003e new kg.Ray(...e30);\nvar D_ = class e30 {\n constructor() {\n this.faces = new kg.PlanarSet, this.edges = new kg.PlanarSet;\n let e31 = [...arguments];\n if (e31.length === 1 \u0026\u0026 (e31[0] instanceof Array \u0026\u0026 e31[0].length \u003e 0 || e31[0] instanceof kg.Circle || e31[0] instanceof kg.Box)) {\n let t2 = e31[0];\n if (e31[0] instanceof Array \u0026\u0026 e31[0].every((e32) =\u003e e32 instanceof Array))\n if (t2.every((e32) =\u003e e32 instanceof Array \u0026\u0026 e32.length === 2 \u0026\u0026 typeof e32[0] == \"number\" \u0026\u0026 typeof e32[1] == \"number\"))\n this.faces.add(new kg.Face(this, t2));\n else\n for (let e32 of t2)\n if (e32 instanceof Array \u0026\u0026 e32[0] instanceof Array \u0026\u0026 e32[0].every((e33) =\u003e e33 instanceof Array \u0026\u0026 e33.length === 2 \u0026\u0026 typeof e33[0] == \"number\" \u0026\u0026 typeof e33[1] == \"number\"))\n for (let t3 of e32)\n this.faces.add(new kg.Face(this, t3));\n else\n this.faces.add(new kg.Face(this, e32));\n else\n this.faces.add(new kg.Face(this, t2));\n }\n }\n get box() {\n return [...this.faces].reduce((e31, t2) =\u003e e31.merge(t2.box), new kg.Box);\n }\n get vertices() {\n return [...this.faces].flatMap((e31) =\u003e e31.vertices);\n }\n clone() {\n let t2 = new e30;\n for (let e31 of this.faces)\n t2.addFace(e31.shapes);\n return t2;\n }\n createFromArray(t2) {\n const n2 = new e30;\n return t2.forEach((e31) =\u003e [...e31.faces].forEach((e32) =\u003e n2.addFace(e32.shapes))), n2;\n }\n isEmpty() {\n return this.edges.size === 0 || this.faces.size === 0;\n }\n isValid() {\n let e31 = true;\n for (let t2 of this.faces)\n if (!t2.isSimple(this.edges)) {\n e31 = false;\n break;\n }\n return e31;\n }\n area() {\n let e31 = [...this.faces].reduce((e32, t2) =\u003e e32 + t2.signedArea(), 0);\n return Math.abs(e31);\n }\n addFace(...e31) {\n let t2 = new kg.Face(this, ...e31);\n return this.faces.add(t2), t2;\n }\n deleteFace(e31) {\n for (let t2 of e31)\n this.edges.delete(t2);\n return this.faces.delete(e31);\n }\n recreateFaces() {\n this.faces.clear();\n for (let e32 of this.edges)\n e32.face = null;\n let e31, t2 = true;\n for (;t2; ) {\n t2 = false;\n for (let n2 of this.edges)\n if (n2.face === null) {\n e31 = n2, t2 = true;\n break;\n }\n if (t2) {\n let t3 = e31;\n do {\n t3 = t3.next;\n } while (t3.next !== e31);\n this.addFace(e31, t3);\n }\n }\n }\n removeChain(e31, t2, n2) {\n if (n2.next !== t2) {\n for (let o3 = t2;o3 !== n2.next; o3 = o3.next)\n if (e31.remove(o3), this.edges.delete(o3), e31.isEmpty()) {\n this.deleteFace(e31);\n break;\n }\n } else\n this.deleteFace(e31);\n }\n addVertex(e31, t2) {\n let n2 = t2.shape.split(e31);\n if (n2[0] === null)\n return t2.prev;\n if (n2[1] === null)\n return t2;\n let o3 = new kg.Edge(n2[0]), i3 = t2.prev;\n return t2.face.insert(o3, i3), this.edges.delete(t2), this.edges.add(o3), t2.shape = n2[1], this.edges.add(t2), o3;\n }\n removeEndVertex(e31) {\n const t2 = e31.next;\n t2 !== e31 \u0026\u0026 (e31.face.merge_with_next_edge(e31), this.edges.delete(t2));\n }\n cut(e31) {\n const t2 = this.splitToIslands().flatMap((t3) =\u003e t3._cutSingleIsland(e31)).filter((e32) =\u003e e32.isValid() \u0026\u0026 e32.isEmpty() === false);\n return this.createFromArray(t2);\n }\n _cutSingleIsland(e31) {\n let t2 = this.clone();\n const n2 = e31.clone();\n let o3, i3, r3 = { int_points1: [], int_points2: [], int_points1_sorted: [], int_points2_sorted: [] };\n for (let e32 of n2.edges)\n for (let n3 of t2.edges) {\n let t3 = cf(e32, n3);\n for (let o4 of t3)\n xf(e32, o4, r3.int_points1), xf(n3, o4, r3.int_points2);\n }\n if (r3.int_points1.length === 0)\n return t2;\n r3.int_points1_sorted = If(r3.int_points1), r3.int_points2_sorted = If(r3.int_points2), Nf(n2, r3.int_points1_sorted), Nf(t2, r3.int_points2_sorted), Cf(r3), r3.int_points1_sorted = If(r3.int_points1), r3.int_points2_sorted = If(r3.int_points2), Pf(r3.int_points1), Mf(r3.int_points1, t2);\n for (let e32 of r3.int_points1_sorted)\n e32.edge_before \u0026\u0026 e32.edge_after \u0026\u0026 e32.edge_before.bv === e32.edge_after.bv \u0026\u0026 (r3.int_points2[e32.id] = -1, e32.id = -1);\n if (r3.int_points1 = r3.int_points1.filter((e32) =\u003e e32.id \u003e= 0), r3.int_points2 = r3.int_points2.filter((e32) =\u003e e32.id \u003e= 0), r3.int_points1.forEach((e32, t3) =\u003e {\n e32.id = t3;\n }), r3.int_points2.forEach((e32, t3) =\u003e {\n e32.id = t3;\n }), r3.int_points1.length === 0)\n return t2;\n r3.int_points1_sorted = If(r3.int_points1), r3.int_points2_sorted = If(r3.int_points2);\n for (let e32 = 1;e32 \u003c r3.int_points1_sorted.length; e32++)\n if (i3 = r3.int_points1_sorted[e32], o3 = r3.int_points1_sorted[e32 - 1], i3.edge_before \u0026\u0026 i3.edge_before.bv === 1) {\n let e33 = o3.edge_after, s2 = i3.edge_before, a3 = n2.getChain(e33, s2);\n Rf(r3.int_points2[o3.id], r3.int_points2[i3.id], a3), a3.forEach((e34) =\u003e t2.edges.add(e34)), a3 = a3.reverse().map((e34) =\u003e new kg.Edge(e34.shape.reverse()));\n for (let e34 = 0;e34 \u003c a3.length - 1; e34++)\n a3[e34].next = a3[e34 + 1], a3[e34 + 1].prev = a3[e34];\n Rf(r3.int_points2[i3.id], r3.int_points2[o3.id], a3), a3.forEach((e34) =\u003e t2.edges.add(e34));\n }\n return t2.recreateFaces(), t2;\n }\n cutWithLine(e31) {\n let t2 = new bf([e31]);\n return this.cut(t2);\n }\n findEdgeByPoint(e31) {\n let t2;\n for (let n2 of this.faces)\n if (t2 = n2.findEdgeByPoint(e31), t2 !== undefined)\n break;\n return t2;\n }\n splitToIslands() {\n if (this.isEmpty())\n return [];\n let e31 = this.toArray();\n e31.sort((e32, t3) =\u003e t3.area() - e32.area());\n let t2 = [...e31[0].faces][0].orientation(), n2 = e31.filter((e32) =\u003e [...e32.faces][0].orientation() === t2);\n for (let o3 of e31) {\n let e32 = [...o3.faces][0];\n if (e32.orientation() !== t2) {\n for (let t3 of n2)\n if (e32.shapes.every((e33) =\u003e t3.contains(e33))) {\n t3.addFace(e32.shapes);\n break;\n }\n }\n }\n return n2;\n }\n rearrange() {\n if (this.faces.size \u003c= 1)\n return this.clone();\n const t2 = this.splitToIslands(), n2 = new e30;\n return t2.forEach((e31) =\u003e {\n e31.faces.forEach((e32) =\u003e n2.addFace(e32.shapes));\n }), n2;\n }\n orientation() {\n return this.isEmpty() ? Cg.NOT_ORIENTABLE : [...this.faces][0].orientation();\n }\n isOuter(e31) {\n return e31.orientation() === this.orientation();\n }\n isMultiPolygon() {\n let e31 = 0;\n return this.faces.forEach((t2) =\u003e {\n this.isOuter(t2) \u0026\u0026 e31++;\n }), e31 \u003e 1;\n }\n reverse() {\n for (let e31 of this.faces)\n e31.reverse();\n return this;\n }\n contains(e31) {\n if (e31 instanceof kg.Point) {\n let t2 = a_(this, e31);\n return t2 === 1 || t2 === 2;\n }\n return d_(this, e31);\n }\n distanceTo(e31) {\n if (e31 instanceof kg.Point) {\n let [t2, n2] = kg.Distance.point2polygon(e31, this);\n return n2 = n2.reverse(), [t2, n2];\n }\n if (e31 instanceof kg.Circle || e31 instanceof kg.Line || e31 instanceof kg.Segment || e31 instanceof kg.Arc) {\n let [t2, n2] = kg.Distance.shape2polygon(e31, this);\n return n2 = n2.reverse(), [t2, n2];\n }\n if (e31 instanceof kg.Box)\n return this.distanceTo(new kg.Polygon(e31));\n if (e31 instanceof kg.Polygon) {\n let t2, n2, o3 = [Number.POSITIVE_INFINITY, new kg.Segment];\n for (let i3 of this.edges) {\n let r3 = o3[0];\n [t2, n2] = kg.Distance.shape2planarSet(i3.shape, e31.edges, r3), kg.Utils.LT(t2, r3) \u0026\u0026 (o3 = [t2, n2]);\n }\n return o3;\n }\n }\n intersect(e31) {\n return e31 instanceof kg.Point ? this.contains(e31) ? [e31] : [] : e31 instanceof kg.Line ? sf(e31, this) : e31 instanceof kg.Ray ? ff(e31, this) : e31 instanceof kg.Circle ? af(e31, this) : e31 instanceof kg.Segment ? of(e31, this) : e31 instanceof kg.Arc ? rf(e31, this) : e31 instanceof kg.Polygon ? function(e32, t2) {\n let n2 = [];\n if (e32.isEmpty() || t2.isEmpty())\n return n2;\n if (e32.box.not_intersect(t2.box))\n return n2;\n for (let o3 of e32.edges)\n n2 = [...n2, ...lf(o3, t2)];\n return n2;\n }(e31, this) : e31 instanceof kg.Multiline ? function(e32, t2) {\n let n2 = [];\n if (t2.isEmpty() || e32.size === 0)\n return n2;\n for (let o3 of e32)\n n2 = [...n2, ...lf(o3, t2)];\n return n2;\n }(e31, this) : undefined;\n }\n translate(t2) {\n let n2 = new e30;\n for (let e31 of this.faces)\n n2.addFace(e31.shapes.map((e32) =\u003e e32.translate(t2)));\n return n2;\n }\n rotate(t2 = 0, n2 = new kg.Point) {\n let o3 = new e30;\n for (let e31 of this.faces)\n o3.addFace(e31.shapes.map((e32) =\u003e e32.rotate(t2, n2)));\n return o3;\n }\n scale(t2, n2) {\n let o3 = new e30;\n for (let e31 of this.faces)\n o3.addFace(e31.shapes.map((e32) =\u003e e32.scale(t2, n2)));\n return o3;\n }\n transform(t2 = new kg.Matrix) {\n let n2 = new e30;\n for (let e31 of this.faces)\n n2.addFace(e31.shapes.map((e32) =\u003e e32.transform(t2)));\n return n2;\n }\n toJSON() {\n return [...this.faces].map((e31) =\u003e e31.toJSON());\n }\n toArray() {\n return [...this.faces].map((e31) =\u003e e31.toPolygon());\n }\n dpath() {\n return [...this.faces].reduce((e31, t2) =\u003e e31 + t2.svg(), \"\");\n }\n svg(e31 = {}) {\n let t2 = `\n\u003cpath ${Fg({ fillRule: \"evenodd\", fill: \"lightcyan\", ...e31 })} d=\"`;\n for (let e32 of this.faces)\n t2 += `\n${e32.svg()}`;\n return t2 += `\" \u003e\n\u003c/path\u003e`, t2;\n }\n};\nkg.Polygon = D_;\nkg.polygon = (...e31) =\u003e new kg.Polygon(...e31);\nvar { Circle: L_, Line: z_, Point: B_, Vector: F_, Utils: j_ } = kg;\nkg.Inversion = class e31 {\n constructor(e32) {\n this.circle = e32;\n }\n get inversion_circle() {\n return this.circle;\n }\n static inversePoint(e32, t2) {\n const n2 = new F_(e32.pc, t2), o3 = e32.r * e32.r, i3 = n2.dot(n2);\n return j_.EQ_0(i3) ? new B_(Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY) : e32.pc.translate(n2.multiply(o3 / i3));\n }\n static inverseCircle(e32, t2) {\n const n2 = e32.pc.distanceTo(t2.pc)[0];\n if (j_.EQ(n2, t2.r)) {\n let n3 = e32.r * e32.r / (2 * t2.r), o3 = new F_(e32.pc, t2.pc);\n o3 = o3.normalize();\n let i3 = e32.pc.translate(o3.multiply(n3));\n return new z_(i3, o3);\n }\n {\n let n3 = new F_(e32.pc, t2.pc), o3 = e32.r * e32.r / (n3.dot(n3) - t2.r * t2.r), i3 = e32.pc.translate(n3.multiply(o3)), r3 = Math.abs(o3) * t2.r;\n return new L_(i3, r3);\n }\n }\n static inverseLine(e32, t2) {\n const [n2, o3] = e32.pc.distanceTo(t2);\n if (j_.EQ_0(n2))\n return t2.clone();\n {\n let t3 = e32.r * e32.r / (2 * n2), i3 = new F_(e32.pc, o3.end);\n return i3 = i3.multiply(t3 / n2), new L_(e32.pc.translate(i3), t3);\n }\n }\n inverse(t2) {\n return t2 instanceof B_ ? e31.inversePoint(this.circle, t2) : t2 instanceof L_ ? e31.inverseCircle(this.circle, t2) : t2 instanceof z_ ? e31.inverseLine(this.circle, t2) : undefined;\n }\n};\nkg.inversion = (e32) =\u003e new kg.Inversion(e32);\nkg.Distance = class e32 {\n static point2point(e33, t2) {\n return e33.distanceTo(t2);\n }\n static point2line(e33, t2) {\n let n2 = e33.projectionOn(t2);\n return [new kg.Vector(e33, n2).length, new kg.Segment(e33, n2)];\n }\n static point2circle(e33, t2) {\n let [n2, o3] = e33.distanceTo(t2.center);\n if (kg.Utils.EQ_0(n2))\n return [t2.r, new kg.Segment(e33, t2.toArc().start)];\n {\n let o4 = Math.abs(n2 - t2.r), i3 = new kg.Vector(t2.pc, e33).normalize().multiply(t2.r), r3 = t2.pc.translate(i3);\n return [o4, new kg.Segment(e33, r3)];\n }\n }\n static point2segment(t2, n2) {\n if (n2.start.equalTo(n2.end))\n return e32.point2point(t2, n2.start);\n let o3, i3, r3 = new kg.Vector(n2.start, n2.end), s2 = new kg.Vector(n2.start, t2), a3 = new kg.Vector(n2.end, t2), c3 = r3.dot(s2), l3 = -r3.dot(a3);\n if (kg.Utils.GE(c3, 0) \u0026\u0026 kg.Utils.GE(l3, 0)) {\n let e33 = n2.tangentInStart();\n return o3 = Math.abs(e33.cross(s2)), i3 = n2.start.translate(e33.multiply(e33.dot(s2))), [o3, new kg.Segment(t2, i3)];\n }\n return c3 \u003c 0 ? t2.distanceTo(n2.start) : t2.distanceTo(n2.end);\n }\n static point2arc(t2, n2) {\n let o3, i3, r3 = new kg.Circle(n2.pc, n2.r), s2 = [];\n return [o3, i3] = e32.point2circle(t2, r3), i3.end.on(n2) \u0026\u0026 s2.push(e32.point2circle(t2, r3)), s2.push(e32.point2point(t2, n2.start)), s2.push(e32.point2point(t2, n2.end)), e32.sort(s2), s2[0];\n }\n static point2edge(t2, n2) {\n return n2.shape instanceof kg.Segment ? e32.point2segment(t2, n2.shape) : e32.point2arc(t2, n2.shape);\n }\n static segment2line(t2, n2) {\n let o3 = t2.intersect(n2);\n if (o3.length \u003e 0)\n return [0, new kg.Segment(o3[0], o3[0])];\n let i3 = [];\n return i3.push(e32.point2line(t2.start, n2)), i3.push(e32.point2line(t2.end, n2)), e32.sort(i3), i3[0];\n }\n static segment2segment(t2, n2) {\n let o3 = Vg(t2, n2);\n if (o3.length \u003e 0)\n return [0, new kg.Segment(o3[0], o3[0])];\n let i3, r3, s2 = [];\n return [i3, r3] = e32.point2segment(n2.start, t2), s2.push([i3, r3.reverse()]), [i3, r3] = e32.point2segment(n2.end, t2), s2.push([i3, r3.reverse()]), s2.push(e32.point2segment(t2.start, n2)), s2.push(e32.point2segment(t2.end, n2)), e32.sort(s2), s2[0];\n }\n static segment2circle(t2, n2) {\n let o3 = t2.intersect(n2);\n if (o3.length \u003e 0)\n return [0, new kg.Segment(o3[0], o3[0])];\n let i3 = new kg.Line(t2.ps, t2.pe), [r3, s2] = e32.point2line(n2.center, i3);\n if (kg.Utils.GE(r3, n2.r) \u0026\u0026 s2.end.on(t2))\n return e32.point2circle(s2.end, n2);\n {\n let [o4, i4] = e32.point2circle(t2.start, n2), [r4, s3] = e32.point2circle(t2.end, n2);\n return kg.Utils.LT(o4, r4) ? [o4, i4] : [r4, s3];\n }\n }\n static segment2arc(t2, n2) {\n let o3 = t2.intersect(n2);\n if (o3.length \u003e 0)\n return [0, new kg.Segment(o3[0], o3[0])];\n let i3 = new kg.Line(t2.ps, t2.pe), r3 = new kg.Circle(n2.pc, n2.r), [s2, a3] = e32.point2line(r3.center, i3);\n if (kg.Utils.GE(s2, r3.r) \u0026\u0026 a3.end.on(t2)) {\n let [t3, o4] = e32.point2circle(a3.end, r3);\n if (o4.end.on(n2))\n return [t3, o4];\n }\n let c3, l3, h2 = [];\n return h2.push(e32.point2arc(t2.start, n2)), h2.push(e32.point2arc(t2.end, n2)), [c3, l3] = e32.point2segment(n2.start, t2), h2.push([c3, l3.reverse()]), [c3, l3] = e32.point2segment(n2.end, t2), h2.push([c3, l3.reverse()]), e32.sort(h2), h2[0];\n }\n static circle2circle(t2, n2) {\n let o3 = t2.intersect(n2);\n if (o3.length \u003e 0)\n return [0, new kg.Segment(o3[0], o3[0])];\n if (t2.center.equalTo(n2.center)) {\n let o4 = t2.toArc(), i3 = n2.toArc();\n return e32.point2point(o4.start, i3.start);\n }\n {\n let o4 = new kg.Line(t2.center, n2.center), i3 = o4.intersect(t2), r3 = o4.intersect(n2), s2 = [];\n return s2.push(e32.point2point(i3[0], r3[0])), s2.push(e32.point2point(i3[0], r3[1])), s2.push(e32.point2point(i3[1], r3[0])), s2.push(e32.point2point(i3[1], r3[1])), e32.sort(s2), s2[0];\n }\n }\n static circle2line(t2, n2) {\n let o3 = t2.intersect(n2);\n if (o3.length \u003e 0)\n return [0, new kg.Segment(o3[0], o3[0])];\n let [i3, r3] = e32.point2line(t2.center, n2), [s2, a3] = e32.point2circle(r3.end, t2);\n return a3 = a3.reverse(), [s2, a3];\n }\n static arc2line(t2, n2) {\n let o3 = n2.intersect(t2);\n if (o3.length \u003e 0)\n return [0, new kg.Segment(o3[0], o3[0])];\n let i3 = new kg.Circle(t2.center, t2.r), [r3, s2] = e32.point2line(i3.center, n2);\n if (!kg.Utils.GE(r3, i3.r)) {\n let o4 = [];\n return o4.push(e32.point2line(t2.start, n2)), o4.push(e32.point2line(t2.end, n2)), e32.sort(o4), o4[0];\n }\n {\n let [n3, o4] = e32.point2circle(s2.end, i3);\n if (o4.end.on(t2))\n return [n3, o4];\n }\n }\n static arc2circle(t2, n2) {\n let o3 = t2.intersect(n2);\n if (o3.length \u003e 0)\n return [0, new kg.Segment(o3[0], o3[0])];\n let i3 = new kg.Circle(t2.center, t2.r), [r3, s2] = e32.circle2circle(i3, n2);\n if (s2.start.on(t2))\n return [r3, s2];\n {\n let o4 = [];\n return o4.push(e32.point2circle(t2.start, n2)), o4.push(e32.point2circle(t2.end, n2)), e32.sort(o4), o4[0];\n }\n }\n static arc2arc(t2, n2) {\n let o3 = t2.intersect(n2);\n if (o3.length \u003e 0)\n return [0, new kg.Segment(o3[0], o3[0])];\n let i3 = new kg.Circle(t2.center, t2.r), r3 = new kg.Circle(n2.center, n2.r), [s2, a3] = e32.circle2circle(i3, r3);\n if (a3.start.on(t2) \u0026\u0026 a3.end.on(n2))\n return [s2, a3];\n {\n let o4, i4, r4 = [];\n return [o4, i4] = e32.point2arc(t2.start, n2), i4.end.on(n2) \u0026\u0026 r4.push([o4, i4]), [o4, i4] = e32.point2arc(t2.end, n2), i4.end.on(n2) \u0026\u0026 r4.push([o4, i4]), [o4, i4] = e32.point2arc(n2.start, t2), i4.end.on(t2) \u0026\u0026 r4.push([o4, i4.reverse()]), [o4, i4] = e32.point2arc(n2.end, t2), i4.end.on(t2) \u0026\u0026 r4.push([o4, i4.reverse()]), [o4, i4] = e32.point2point(t2.start, n2.start), r4.push([o4, i4]), [o4, i4] = e32.point2point(t2.start, n2.end), r4.push([o4, i4]), [o4, i4] = e32.point2point(t2.end, n2.start), r4.push([o4, i4]), [o4, i4] = e32.point2point(t2.end, n2.end), r4.push([o4, i4]), e32.sort(r4), r4[0];\n }\n }\n static point2polygon(t2, n2) {\n let o3 = [Number.POSITIVE_INFINITY, new kg.Segment];\n for (let i3 of n2.edges) {\n let [n3, r3] = e32.point2edge(t2, i3);\n kg.Utils.LT(n3, o3[0]) \u0026\u0026 (o3 = [n3, r3]);\n }\n return o3;\n }\n static shape2polygon(e33, t2) {\n let n2 = [Number.POSITIVE_INFINITY, new kg.Segment];\n for (let o3 of t2.edges) {\n let [t3, i3] = e33.distanceTo(o3.shape);\n kg.Utils.LT(t3, n2[0]) \u0026\u0026 (n2 = [t3, i3]);\n }\n return n2;\n }\n static polygon2polygon(e33, t2) {\n let n2 = [Number.POSITIVE_INFINITY, new kg.Segment];\n for (let o3 of e33.edges)\n for (let e34 of t2.edges) {\n let [t3, i3] = o3.shape.distanceTo(e34.shape);\n kg.Utils.LT(t3, n2[0]) \u0026\u0026 (n2 = [t3, i3]);\n }\n return n2;\n }\n static box2box_minmax(e33, t2) {\n let n2 = Math.max(Math.max(e33.xmin - t2.xmax, 0), Math.max(t2.xmin - e33.xmax, 0)), o3 = Math.max(Math.max(e33.ymin - t2.ymax, 0), Math.max(t2.ymin - e33.ymax, 0)), i3 = n2 * n2 + o3 * o3, r3 = e33.merge(t2), s2 = r3.xmax - r3.xmin, a3 = r3.ymax - r3.ymin;\n return [i3, s2 * s2 + a3 * a3];\n }\n static minmax_tree_process_level(t2, n2, o3, i3) {\n let r3, s2;\n for (let a4 of n2) {\n [r3, s2] = e32.box2box_minmax(t2.box, a4.item.key);\n for (let e33 of a4.item.values)\n e33 instanceof kg.Edge ? i3.insert([r3, s2], e33.shape) : i3.insert([r3, s2], e33);\n kg.Utils.LT(s2, o3) \u0026\u0026 (o3 = s2);\n }\n if (n2.length === 0)\n return o3;\n let a3 = [...n2.map((e33) =\u003e e33.left.isNil() ? undefined : e33.left).filter((e33) =\u003e e33 !== undefined), ...n2.map((e33) =\u003e e33.right.isNil() ? undefined : e33.right).filter((e33) =\u003e e33 !== undefined)].filter((n3) =\u003e {\n let [i4, r4] = e32.box2box_minmax(t2.box, n3.max);\n return kg.Utils.LE(i4, o3);\n });\n return o3 = e32.minmax_tree_process_level(t2, a3, o3, i3);\n }\n static minmax_tree(t2, n2, o3) {\n let i3 = new x_, r3 = [n2.index.root], s2 = o3 \u003c Number.POSITIVE_INFINITY ? o3 * o3 : Number.POSITIVE_INFINITY;\n return s2 = e32.minmax_tree_process_level(t2, r3, s2, i3), i3;\n }\n static minmax_tree_calc_distance(t2, n2, o3) {\n let i3, r3;\n if (n2 != null \u0026\u0026 !n2.isNil()) {\n if ([i3, r3] = e32.minmax_tree_calc_distance(t2, n2.left, o3), r3)\n return [i3, r3];\n if (kg.Utils.LT(i3[0], Math.sqrt(n2.item.key.low)))\n return [i3, true];\n let [s2, a3] = e32.distanceToArray(t2, n2.item.values);\n return kg.Utils.LT(s2, i3[0]) \u0026\u0026 (i3 = [s2, a3]), [i3, r3] = e32.minmax_tree_calc_distance(t2, n2.right, i3), [i3, r3];\n }\n return [o3, false];\n }\n static shape2planarSet(t2, n2, o3 = Number.POSITIVE_INFINITY) {\n let i3 = [o3, new kg.Segment], r3 = false;\n if (n2 instanceof kg.PlanarSet) {\n let s2 = e32.minmax_tree(t2, n2, o3);\n [i3, r3] = e32.minmax_tree_calc_distance(t2, s2.root, i3);\n }\n return i3;\n }\n static sort(e33) {\n e33.sort((e34, t2) =\u003e kg.Utils.LT(e34[0], t2[0]) ? -1 : kg.Utils.GT(e34[0], t2[0]) ? 1 : 0);\n }\n static distance(e33, t2) {\n return e33.distanceTo(t2);\n }\n static distanceToArray(e33, t2) {\n let n2 = [Number.POSITIVE_INFINITY, new kg.Segment];\n for (let o3 of t2) {\n let [t3, i3] = e33.distanceTo(o3);\n kg.Utils.LT(t3, n2[0]) \u0026\u0026 (n2 = [t3, i3]);\n }\n return n2;\n }\n static shape2multiline(t2, n2) {\n let o3 = [Number.POSITIVE_INFINITY, new kg.Segment];\n for (let i3 of n2) {\n let [n3, r3] = e32.distance(t2, i3.shape);\n kg.Utils.LT(n3, o3[0]) \u0026\u0026 (o3 = [n3, r3]);\n }\n return o3;\n }\n static multiline2multiline(t2, n2) {\n let o3 = [Number.POSITIVE_INFINITY, new kg.Segment];\n for (let i3 of t2)\n for (let t3 of n2) {\n let [n3, r3] = e32.distance(i3.shape, t3.shape);\n kg.Utils.LT(n3, o3[0]) \u0026\u0026 (o3 = [n3, r3]);\n }\n return o3;\n }\n};\nvar { Multiline: $_, Point: Y_, Segment: X_, Polygon: H_ } = kg;\nfunction V_(e33) {\n const t2 = [];\n let n2 = 0, o3 = 0;\n for (let i3 = 0;i3 \u003c e33.length; i3++) {\n if (e33[i3] === \"(\" \u0026\u0026 n2++, e33[i3] === \")\" \u0026\u0026 n2--, n2 \u003c 0)\n throw kg.Errors.ILLEGAL_PARAMETERS;\n e33[i3] === \",\" \u0026\u0026 n2 === 0 \u0026\u0026 (t2.push(e33.slice(o3, i3).trim()), o3 = i3 + 1);\n }\n if (n2 !== 0)\n throw kg.Errors.ILLEGAL_PARAMETERS;\n return t2.push(e33.slice(o3).trim()), t2;\n}\nfunction W_(e33) {\n if ((e33 = e33.trim()) === \"EMPTY\")\n throw new Error(\"Empty geometry not supported\");\n if (!e33.startsWith(\"(\") || !e33.endsWith(\")\"))\n throw kg.Errors.ILLEGAL_PARAMETERS;\n return e33.slice(1, -1).trim();\n}\nfunction G_(e33) {\n if ((e33 = e33.trim()) === \"EMPTY\")\n throw new Error(\"Empty geometry not supported\");\n return new Y_(e33.split(/\\s+/).map(Number));\n}\nfunction U_(e33) {\n const t2 = V_(e33).map(G_);\n let n2 = [];\n for (let e34 = 0;e34 \u003c t2.length - 1; e34++)\n n2.push(new X_(t2[e34], t2[e34 + 1]));\n return new $_(n2);\n}\nfunction Z_(e33) {\n const t2 = new H_;\n if (e33.trim() === \"EMPTY\")\n return t2;\n let n2;\n return V_(W_(e33)).forEach((e34, o3) =\u003e {\n const i3 = V_(W_(e34)).map(G_), r3 = t2.addFace(i3);\n o3 === 0 ? n2 = r3.orientation() : r3.orientation() === n2 \u0026\u0026 r3.reverse();\n }), t2;\n}\nfunction q_(e33) {\n return e33.split(`\n`).map((e34) =\u003e e34.match(/\\(([^)]+)\\)/)[1]).map(G_);\n}\nfunction J_(e33) {\n return e33.split(`\n`).map((e34) =\u003e e34.match(/\\(([^)]+)\\)/)[1]).map(U_).reduce((e34, t2) =\u003e [...e34, ...t2], []);\n}\nfunction Q_(e33) {\n return e33.split(`\n`)?.every((e34) =\u003e e34.includes(\"POINT\"));\n}\nfunction K_(e33) {\n return e33.split(`\n`)?.every((e34) =\u003e e34.includes(\"LINESTRING\"));\n}\nkg.isWktString = function(e34) {\n return e34.startsWith(\"POINT\") || Q_(e34) || e34.startsWith(\"LINESTRING\") || K_(e34) || e34.startsWith(\"MULTILINESTRING\") || e34.startsWith(\"POLYGON\") || e34.startsWith(\"MULTIPOINT\") || e34.startsWith(\"MULTIPOLYGON\") || e34.startsWith(\"GEOMETRYCOLLECTION\");\n}, kg.parseWKT = function e33(t2) {\n const n2 = t2.trim().split(`\n`);\n if (n2.length \u003e 1) {\n if (n2.every((e34) =\u003e /^\\s*POINT\\s*\\([^()]*\\)\\s*$/.test(e34)))\n return q_(t2.trim());\n if (n2.every((e34) =\u003e /^\\s*LINESTRING\\s*\\([^()]*\\)\\s*$/.test(e34)))\n return J_(t2.trim());\n }\n const o3 = t2.trim().match(/^(POINT|MULTIPOINT|LINESTRING|MULTILINESTRING|POLYGON|MULTIPOLYGON|GEOMETRYCOLLECTION)\\s*(EMPTY|\\([\\s\\S]*\\))$/);\n if (o3) {\n const [, t3, n3] = o3;\n if (n3 === \"EMPTY\") {\n if (t3 === \"POLYGON\")\n return new H_;\n throw new Error(\"Empty geometry not supported\");\n }\n const i3 = W_(n3);\n switch (t3) {\n case \"POINT\":\n return G_(i3);\n case \"MULTIPOINT\":\n return V_(i3).map((e34) =\u003e G_(e34.startsWith(\"(\") ? W_(e34) : e34));\n case \"LINESTRING\":\n return U_(i3);\n case \"MULTILINESTRING\":\n return V_(i3).map((e34) =\u003e U_(W_(e34)));\n case \"POLYGON\":\n return Z_(n3);\n case \"MULTIPOLYGON\":\n return function(e34) {\n const t4 = new H_;\n return V_(e34).map(Z_).forEach((e35) =\u003e {\n e35.faces.forEach((e36) =\u003e t4.addFace([...e36.shapes]));\n }), t4;\n }(i3);\n case \"GEOMETRYCOLLECTION\":\n return V_(i3).map(e33).reduce((e34, t4) =\u003e e34.concat(t4), []);\n }\n } else {\n if (Q_(t2))\n return q_(t2);\n if (K_(t2))\n return J_(t2);\n }\n return [];\n}, kg.BooleanOperations = e_, kg.Relations = g_;\nvar ey = [0, 1, -1, 2, -2, 3, -3, 4];\nvar ty = (ey.flatMap((e34) =\u003e ey.map((t2) =\u003e [e34, t2])).sort(([e34, t2], [n2, o3]) =\u003e Math.abs(e34) + Math.abs(t2) - Math.abs(n2) - Math.abs(o3)).length, [0.2, 0.4, 0.8, 1.2].flatMap((e34) =\u003e [0.2, 0.3, 0.45, 0.6].flatMap((t2) =\u003e [-1, 1].map((n2) =\u003e ({ halfSpan: e34, offset: t2, directionSign: n2 })))).flatMap((e34) =\u003e [0, 1].map((t2) =\u003e ({ kind: \"segment\", routeSide: t2, ...e34 }))));\n[1, -1].flatMap((e34) =\u003e [1, -1].flatMap((t2) =\u003e [false, true].flatMap((n2) =\u003e [0, 1].map((o3) =\u003e ({ routeSide: o3, normalDirectionSign: e34, tangentDirectionSign: t2, reverseEndpointOffsets: n2 }))))), [0, 1].map((e34) =\u003e ({ kind: \"displacementChain\", routeSide: e34 })), [-1, 1].flatMap((e34) =\u003e [0, 1].map((t2) =\u003e ({ kind: \"segment\", routeSide: t2, halfSpan: 0.4, offset: 1.2, directionSign: e34 }))), [-1, 1].flatMap((e34) =\u003e [0, 1].map((t2) =\u003e ({ kind: \"span\", routeSide: t2, spanExpansion: 3, offset: 1.8, directionSign: e34 }))), [{ dx: -2.4, dy: -0.4 }, { dx: -2.4, dy: 0.4 }, { dx: 2.4, dy: -0.4 }, { dx: 2.4, dy: 0.4 }, { dx: -0.4, dy: -2.4 }, { dx: -0.4, dy: 2.4 }, { dx: 0.4, dy: -2.4 }, { dx: 0.4, dy: 2.4 }].flatMap((e34) =\u003e [0, 1].map((t2) =\u003e ({ kind: \"waypoint\", routeSide: t2, spanExpansion: 2, ...e34 }))), [{ dx: -0.17, dy: 0 }, { dx: 0.17, dy: 0 }, { dx: 0, dy: -0.17 }, { dx: 0, dy: 0.17 }].flatMap((e34) =\u003e [0, 1].map((t2) =\u003e ({ kind: \"waypoint\", routeSide: t2, spanExpansion: 0, ...e34 })));\nfunction ny(e34) {\n if (e34.isNonPlatedHole \u0026\u0026 e34.shape === \"circle\")\n return { type: \"oval\", a: { x: 0, y: 0 }, b: { x: 0, y: 0 }, radius: e34.width / 2 };\n if (e34.type === \"rect\")\n return { type: \"rect\", bounds: { minX: -e34.width / 2, maxX: e34.width / 2, minY: -e34.height / 2, maxY: e34.height / 2 } };\n if (e34.type !== \"oval\")\n throw new Error(\"repair04 found an unsupported obstacle shape\");\n const t2 = Math.abs(e34.width - e34.height) / 2, n2 = e34.width \u003e= e34.height ? t2 : 0, o3 = e34.height \u003e e34.width ? t2 : 0;\n return { type: \"oval\", a: { x: -n2, y: -o3 }, b: { x: n2, y: o3 }, radius: Math.min(e34.width, e34.height) / 2 };\n}\nfunction oy(e34, t2, n2) {\n return n2.type === \"rect\" ? Ne(e34, t2, n2.bounds) : Math.max(0, we(e34, t2, n2.a, n2.b) - n2.radius);\n}\nvar iy = (e34, t2) =\u003e {\n const n2 = new Map, o3 = (e35) =\u003e {\n const t3 = n2.get(e35);\n if (t3 === undefined)\n return n2.set(e35, e35), e35;\n if (t3 === e35)\n return e35;\n const i4 = o3(t3);\n return n2.set(e35, i4), i4;\n }, i3 = (e35) =\u003e {\n const t3 = e35.filter((e36) =\u003e typeof e36 == \"string\" \u0026\u0026 e36.length \u003e 0);\n if (t3.length === 0)\n return;\n const i4 = o3(t3[0]);\n for (const e36 of t3)\n n2.set(o3(e36), i4);\n };\n for (const t3 of e34.connections) {\n const e35 = t3;\n i3([e35.name, e35.rootConnectionName, e35.netConnectionName, e35.__netConnectionName, ...e35.mergedConnectionNames ?? [], ...e35.__rootConnectionNames ?? [], ...e35.pointsToConnect.flatMap((e36) =\u003e [e36.pointId, e36.pcb_port_id])]);\n }\n for (const t3 of e34.obstacles)\n i3(t3.connectedTo);\n for (const e35 of t2)\n i3([e35.connectionName, e35.rootConnectionName]);\n for (const e35 of n2.keys())\n n2.set(e35, o3(e35));\n return n2;\n};\nvar ry = (e34, t2) =\u003e {\n const n2 = e34.__zLayers;\n if (n2)\n return new Set(n2);\n if (e34.zLayers)\n return new Set(e34.zLayers);\n const o3 = new Set;\n for (const n3 of e34.layers) {\n const e35 = n3 === \"top\" ? 0 : n3 === \"bottom\" ? t2 - 1 : /^inner\\d+$/.test(n3) ? Number(n3.slice(5)) : -1;\n if (e35 \u003c 0 || e35 \u003e= t2)\n throw new Error(`repair04 obstacle has an unknown layer: ${n3}`);\n o3.add(e35);\n }\n return o3;\n};\nvar sy = ({ srj: e34, routes: t2, traceClearance: n2 = 0.1, viaClearance: o3 = 0.1 }) =\u003e {\n let i3;\n const r3 = new Map, s2 = [];\n let a3 = false;\n return (c3) =\u003e {\n const l3 = i3 ??= iy(e34, t2), h2 = new Map, d2 = a3 ? s2 : function* (t3) {\n for (let i4 = 0;i4 \u003c e34.obstacles.length; i4++) {\n if (r3.has(i4)) {\n const e35 = r3.get(i4);\n e35 \u0026\u0026 (yield e35);\n continue;\n }\n const a4 = e34.obstacles[i4], c4 = a4.connectedTo.some((e35) =\u003e /^(pcb_smtpad_|pcb_plated_hole_|pcb_port_)/.test(e35)), l4 = Math.abs((a4.ccwRotationDegrees ?? 0) % 180) \u003e 0.00000001, h3 = a4.type === \"rect\" \u0026\u0026 a4.layers.length \u003e 1 \u0026\u0026 Math.abs(a4.width - a4.height) \u003c 0.001;\n if (c4 \u0026\u0026 !l4 \u0026\u0026 !h3) {\n r3.set(i4, null);\n continue;\n }\n if (![a4.center.x, a4.center.y, a4.width, a4.height, a4.ccwRotationDegrees ?? 0].every(Number.isFinite) || a4.width \u003c 0 || a4.height \u003c 0)\n throw new Error(\"repair04 fixed obstacle geometry must be finite and nonnegative\");\n const d3 = ry(a4, e34.layerCount), u2 = new Set(a4.connectedTo.map((e35) =\u003e t3.get(e35) ?? e35)), p3 = ny(a4), m2 = (a4.ccwRotationDegrees ?? 0) * Math.PI / 180, g2 = Math.cos(m2), f2 = Math.sin(m2), _2 = Math.hypot(a4.width, a4.height) / 2, y2 = (e35) =\u003e {\n const t4 = e35.x - a4.center.x, n3 = e35.y - a4.center.y;\n return { x: t4 * g2 + n3 * f2, y: -t4 * f2 + n3 * g2 };\n }, b2 = (e35, t4, n3) =\u003e Math.max(e35.x, t4.x) + n3 \u003c a4.center.x - _2 || Math.min(e35.x, t4.x) - n3 \u003e a4.center.x + _2 || Math.max(e35.y, t4.y) + n3 \u003c a4.center.y - _2 || Math.min(e35.y, t4.y) - n3 \u003e a4.center.y + _2, x2 = a4.obstacleId?.startsWith(\"repair04_board_edge_\") === true, v2 = x2 ? 0 : a4.isNonPlatedHole \u0026\u0026 e34.minTraceToHoleEdgeClearance !== undefined ? e34.minTraceToHoleEdgeClearance : Math.max(n2, e34.defaultObstacleMargin ?? 0, e34.minTraceToPadEdgeClearance ?? 0), I2 = x2 ? 0 : Math.max(o3, e34.defaultObstacleMargin ?? 0, e34.minViaEdgeToPadEdgeClearance ?? 0), S2 = { obstacleIndex: i4, obstacle: a4, zLayers: d3, obstacleNets: u2, shape: p3, toLocal: y2, separated: b2, wireGap: v2, viaGap: I2 };\n r3.set(i4, S2), s2.push(S2), yield S2;\n }\n a3 = true;\n }(l3);\n for (const { obstacleIndex: t3, obstacle: n3, zLayers: o4, obstacleNets: i4, shape: r4, toLocal: s3, separated: a4, wireGap: u2, viaGap: p3 } of d2)\n for (let d3 = 0;d3 \u003c c3.length; d3 += 1) {\n const m2 = c3[d3];\n if (!(m2.route.length \u003c 2) \u0026\u0026 ![m2.connectionName, m2.rootConnectionName].some((e35) =\u003e e35 !== undefined \u0026\u0026 i4.has(l3.get(e35) ?? e35)))\n for (let i5 = 1;i5 \u003c m2.route.length; i5 += 1) {\n const c4 = m2.route[i5 - 1], l4 = m2.route[i5];\n if (c4.toNextSegmentType === \"through_obstacle\")\n continue;\n if (c4.z !== l4.z) {\n const n4 = Na(e34, c4, l4);\n if (!Array.from(o4).some((e35) =\u003e e35 \u003e= n4.minZ \u0026\u0026 e35 \u003c= n4.maxZ))\n continue;\n if (Math.abs(c4.x - l4.x) \u003e 0.00000001 || Math.abs(c4.y - l4.y) \u003e 0.00000001)\n throw new Error(\"repair04 found a non-colocated via transition\");\n if (a4(c4, c4, m2.viaDiameter / 2 + p3 + 0.00000001))\n continue;\n const i6 = s3(c4), u3 = oy(i6, i6, r4), g3 = m2.viaDiameter / 2 + p3 - u3;\n if (g3 \u003c= 0.00000001)\n continue;\n const f3 = `fixed-obstacle:${d3}:${t3}:via`;\n (h2.get(f3)?.severity ?? -1 / 0) \u003c g3 \u0026\u0026 h2.set(f3, { key: f3, center: { x: c4.x, y: c4.y }, routeIndex: d3, obstacleIndex: t3, kind: \"via\", severity: g3 });\n continue;\n }\n if (!o4.has(c4.z))\n continue;\n const g2 = Math.max(c4.traceThickness ?? m2.traceThickness, l4.traceThickness ?? m2.traceThickness) / 2;\n if (a4(c4, l4, g2 + u2 + 0.00000001))\n continue;\n const f2 = g2 + u2 - oy(s3(c4), s3(l4), r4);\n if (f2 \u003c= 0.00000001)\n continue;\n const _2 = `fixed-obstacle:${d3}:${t3}:wire`;\n (h2.get(_2)?.severity ?? -1 / 0) \u003c f2 \u0026\u0026 h2.set(_2, { key: _2, center: Ee(n3.center, c4, l4), routeIndex: d3, obstacleIndex: t3, kind: \"wire\", severity: f2 });\n }\n }\n return Array.from(h2.values());\n };\n};\nvar ay = (e34) =\u003e sy(e34)(e34.routes);\nvar cy = (e34, t2) =\u003e {\n const n2 = [];\n for (let o3 = 1;o3 \u003c e34.route.length; o3++) {\n const i3 = e34.route[o3 - 1], r3 = e34.route[o3];\n if (i3.z === r3.z || i3.toNextSegmentType === \"through_obstacle\")\n continue;\n if (i3.x !== r3.x || i3.y !== r3.y || ![i3.x, i3.y, i3.z, r3.z, e34.viaDiameter].every(Number.isFinite) || !Number.isInteger(i3.z) || !Number.isInteger(r3.z) || Math.min(i3.z, r3.z) \u003c 0 || Math.max(i3.z, r3.z) \u003e= t2 || e34.viaDiameter \u003c= 0)\n throw new Error(\"repair04 new-via guard requires valid colocated vias\");\n const s2 = o3 - 1, a3 = [i3.z, r3.z];\n let c3 = Math.min(i3.z, r3.z), l3 = Math.max(i3.z, r3.z);\n for (;o3 + 1 \u003c e34.route.length \u0026\u0026 e34.route[o3].toNextSegmentType !== \"through_obstacle\"; ) {\n const n3 = e34.route[o3 + 1];\n if (n3.x !== r3.x || n3.y !== r3.y)\n break;\n if (!Number.isInteger(n3.z) || n3.z \u003c 0 || n3.z \u003e= t2)\n throw new Error(\"repair04 new-via guard found an invalid layer span\");\n n3.z !== a3.at(-1) \u0026\u0026 a3.push(n3.z), c3 = Math.min(c3, n3.z), l3 = Math.max(l3, n3.z), o3++;\n }\n n2.push({ pointIndices: Array.from({ length: o3 - s2 + 1 }, (e35, t3) =\u003e s2 + t3), layerSequence: a3, x: r3.x, y: r3.y, minZ: c3, maxZ: l3, diameter: e34.viaDiameter, identity: JSON.stringify([r3.x, r3.y, c3, l3, e34.viaDiameter]) });\n }\n return n2;\n};\nvar ly = (e34) =\u003e (({ srj: e35, viaClearance: t2 = 0.1 }) =\u003e {\n const n2 = new Map, o3 = new Map, i3 = [t2, e35.defaultObstacleMargin ?? 0, e35.minViaEdgeToPadEdgeClearance ?? 0], r3 = Math.max(...i3), s2 = Ea(e35, t2, true);\n let a3, c3 = [];\n const l3 = (t3) =\u003e {\n const i4 = o3.get(t3.identity);\n if (i4)\n return i4;\n const s3 = [], a4 = Na(e35, { z: t3.minZ }, { z: t3.maxZ });\n for (let o4 = 0;o4 \u003c e35.obstacles.length; o4++) {\n const i5 = e35.obstacles[o4];\n let c4 = n2.get(o4);\n if (!c4) {\n const t4 = i5.__zLayers ?? i5.zLayers ?? i5.layers.map((t5) =\u003e t5 === \"top\" ? 0 : t5 === \"bottom\" ? e35.layerCount - 1 : /^inner\\d+$/.test(t5) ? Number(t5.slice(5)) : -1);\n if (t4.some((t5) =\u003e !Number.isInteger(t5) || t5 \u003c 0 || t5 \u003e= e35.layerCount))\n throw new Error(\"repair04 new-via guard found an unknown obstacle layer\");\n c4 = { zs: t4 }, n2.set(o4, c4);\n }\n if (!c4.zs.some((e36) =\u003e e36 \u003e= a4.minZ \u0026\u0026 e36 \u003c= a4.maxZ))\n continue;\n if (!c4.geometry) {\n if (![i5.center.x, i5.center.y, i5.width, i5.height, i5.ccwRotationDegrees ?? 0].every(Number.isFinite) || i5.width \u003c 0 || i5.height \u003c 0)\n throw new Error(\"repair04 new-via guard found invalid obstacle geometry\");\n const e36 = (i5.ccwRotationDegrees ?? 0) * Math.PI / 180;\n c4.geometry = { x: i5.center.x, y: i5.center.y, cosine: Math.cos(e36), sine: Math.sin(e36), extent: Math.hypot(i5.width, i5.height) / 2, shape: ny(i5) };\n }\n const l4 = c4.geometry, h2 = l4.extent + t3.diameter / 2 + r3 + 0.00000001;\n if (Math.abs(t3.x - l4.x) \u003e h2 || Math.abs(t3.y - l4.y) \u003e h2)\n continue;\n const d2 = t3.x - l4.x, u2 = t3.y - l4.y, p3 = { x: d2 * l4.cosine + u2 * l4.sine, y: -d2 * l4.sine + u2 * l4.cosine }, m2 = oy(p3, p3, l4.shape), g2 = t3.diameter / 2 + r3 - m2;\n g2 \u003c= 0.00000001 || s3.push({ obstacleIndex: o4, severity: g2 });\n }\n return o3.set(t3.identity, s3), s3;\n };\n return ({ previousRoutes: t3, routes: n3, includeExistingVias: o4 = [] }) =\u003e {\n if (t3.length !== n3.length)\n throw new Error(\"repair04 new-via guard requires matching route ordering\");\n if (i3.some((e36) =\u003e !Number.isFinite(e36) || e36 \u003c 0))\n throw new Error(\"repair04 new-via guard requires nonnegative finite margins\");\n const h2 = [];\n a3 \u0026\u0026 c3.length === n3.length \u0026\u0026 !c3.some((e36, t4) =\u003e e36.connectionName !== n3[t4].connectionName || e36.rootConnectionName !== n3[t4].rootConnectionName) || (a3 = iy(e35, n3), c3 = n3.map((e36) =\u003e ({ connectionName: e36.connectionName, rootConnectionName: e36.rootConnectionName })));\n for (let i4 = 0;i4 \u003c n3.length; i4++) {\n const c4 = n3[i4], d2 = t3[i4], u2 = a3.get(c4.connectionName) ?? c4.connectionName, p3 = (t4) =\u003e l3(t4).flatMap((t5) =\u003e {\n const n4 = e35.obstacles[t5.obstacleIndex].connectedTo.some((e36) =\u003e (a3.get(e36) ?? e36) === u2), o5 = t5.severity - (n4 ? r3 - s2 : 0);\n return o5 \u003e 0.00000001 ? [{ obstacleIndex: t5.obstacleIndex, severity: o5 }] : [];\n }), m2 = cy(d2, e35.layerCount), g2 = c4.connectionName === d2.connectionName \u0026\u0026 c4.rootConnectionName === d2.rootConnectionName, f2 = new Set(g2 ? m2.map((e36) =\u003e e36.identity) : []), _2 = cy(c4, e35.layerCount), y2 = g2 \u0026\u0026 c4.route.length === d2.route.length \u0026\u0026 c4.route.every((e36, t4) =\u003e {\n const n4 = d2.route[t4];\n return (!(t4 === 0 || t4 === c4.route.length - 1 || e36.pcb_port_id || e36.insideJumperPad || e36.toNextSegmentType) || e36.x === n4.x \u0026\u0026 e36.y === n4.y) \u0026\u0026 e36.z === n4.z \u0026\u0026 e36.pcb_port_id === n4.pcb_port_id \u0026\u0026 e36.toNextSegmentType === n4.toNextSegmentType \u0026\u0026 e36.insideJumperPad === n4.insideJumperPad;\n }) \u0026\u0026 _2.length === m2.length \u0026\u0026 new Set(_2.map((e36) =\u003e e36.identity)).size === _2.length \u0026\u0026 _2.every((e36, t4) =\u003e {\n const n4 = m2[t4];\n return e36.diameter === n4.diameter \u0026\u0026 e36.pointIndices.length === n4.pointIndices.length \u0026\u0026 e36.pointIndices.every((e37, t5) =\u003e e37 === n4.pointIndices[t5]) \u0026\u0026 e36.layerSequence.length === n4.layerSequence.length \u0026\u0026 e36.layerSequence.every((e37, t5) =\u003e e37 === n4.layerSequence[t5]) \u0026\u0026 !m2.some((n5, o5) =\u003e o5 !== t4 \u0026\u0026 n5.identity === e36.identity);\n });\n for (let e36 = 0;e36 \u003c _2.length; e36++) {\n const t4 = _2[e36];\n if (f2.has(t4.identity) \u0026\u0026 !o4.some((t5) =\u003e t5.routeIndex === i4 \u0026\u0026 t5.viaIndex === e36))\n continue;\n const n4 = y2 \u0026\u0026 !o4.some((t5) =\u003e t5.routeIndex === i4 \u0026\u0026 t5.viaIndex === e36) ? new Map(p3(m2[e36]).map((e37) =\u003e [e37.obstacleIndex, e37.severity])) : undefined;\n for (const o5 of p3(t4)) {\n const r4 = n4?.get(o5.obstacleIndex);\n r4 !== undefined \u0026\u0026 o5.severity \u003c= r4 + 0.00000001 || h2.push({ key: `new-via-pad:${i4}:${o5.obstacleIndex}:${e36}`, routeIndex: i4, obstacleIndex: o5.obstacleIndex, center: { x: t4.x, y: t4.y }, kind: \"via\", severity: o5.severity });\n }\n }\n }\n return h2;\n };\n})(e34)(e34);\nvar hy = (e34, t2, n2) =\u003e {\n if (n2 \u003c= Aa)\n return structuredClone(e34);\n if (n2 \u003e= 0.99999999)\n return structuredClone(t2);\n const o3 = { ...structuredClone(e34), x: e34.x + (t2.x - e34.x) * n2, y: e34.y + (t2.y - e34.y) * n2 };\n return delete o3.start_pcb_port_id, delete o3.end_pcb_port_id, o3;\n};\nvar dy = [Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array];\nvar uy = class e34 {\n static from(t2, n2 = 0) {\n if (n2 % 8 != 0)\n throw new Error(\"byteOffset must be 8-byte aligned.\");\n if (!t2 || t2.byteLength === undefined || \"buffer\" in t2)\n throw new Error(\"Data must be an instance of ArrayBuffer or SharedArrayBuffer.\");\n const [o3, i3] = new Uint8Array(t2, n2 + 0, 2);\n if (o3 !== 251)\n throw new Error(\"Data does not appear to be in a Flatbush format.\");\n const r3 = i3 \u003e\u003e 4;\n if (r3 !== 3)\n throw new Error(`Got v${r3} data when expected v3.`);\n const s2 = dy[15 \u0026 i3];\n if (!s2)\n throw new Error(\"Unrecognized array type.\");\n const [a3] = new Uint16Array(t2, n2 + 2, 1), [c3] = new Uint32Array(t2, n2 + 4, 1);\n return new e34(c3, a3, s2, undefined, t2, n2);\n }\n constructor(e35, t2 = 16, n2 = Float64Array, o3 = ArrayBuffer, i3, r3 = 0) {\n if (e35 === undefined)\n throw new Error(\"Missing required argument: numItems.\");\n if (isNaN(e35) || e35 \u003c= 0)\n throw new Error(`Unexpected numItems value: ${e35}.`);\n this.numItems = +e35, this.nodeSize = Math.min(Math.max(+t2, 2), 65535), this.byteOffset = r3;\n let s2 = e35, a3 = s2;\n this._levelBounds = [4 * s2];\n do {\n s2 = Math.ceil(s2 / this.nodeSize), a3 += s2, this._levelBounds.push(4 * a3);\n } while (s2 !== 1);\n this.ArrayType = n2, this.IndexArrayType = a3 \u003c 16384 ? Uint16Array : Uint32Array;\n const c3 = dy.indexOf(n2), l3 = 4 * a3 * n2.BYTES_PER_ELEMENT;\n if (c3 \u003c 0)\n throw new Error(`Unexpected typed array class: ${n2}.`);\n const h2 = n2, d2 = this.IndexArrayType;\n if (i3)\n this.data = i3, this._boxes = new h2(i3, r3 + 8, 4 * a3), this._indices = new d2(i3, r3 + 8 + l3, a3), this._pos = 4 * a3, 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];\n else {\n const n3 = this.data = new o3(8 + l3 + a3 * this.IndexArrayType.BYTES_PER_ELEMENT);\n this._boxes = new h2(n3, 8, 4 * a3), this._indices = new d2(n3, 8 + l3, a3), this._pos = 0, this.minX = 1 / 0, this.minY = 1 / 0, this.maxX = -1 / 0, this.maxY = -1 / 0, new Uint8Array(n3, 0, 2).set([251, 48 + c3]), new Uint16Array(n3, 2, 1)[0] = t2, new Uint32Array(n3, 4, 1)[0] = e35;\n }\n this._queue = new R;\n }\n add(e35, t2, n2 = e35, o3 = t2) {\n const i3 = this._pos, r3 = i3 \u003e\u003e 2, s2 = this._boxes;\n return this._indices[r3] = r3, s2[i3] = e35, s2[i3 + 1] = t2, s2[i3 + 2] = n2, s2[i3 + 3] = o3, this._pos = i3 + 4, e35 \u003c this.minX \u0026\u0026 (this.minX = e35), t2 \u003c this.minY \u0026\u0026 (this.minY = t2), n2 \u003e this.maxX \u0026\u0026 (this.maxX = n2), o3 \u003e this.maxY \u0026\u0026 (this.maxY = o3), r3;\n }\n finish() {\n if (this._pos \u003e\u003e 2 !== this.numItems)\n throw new Error(`Added ${this._pos \u003e\u003e 2} items when expected ${this.numItems}.`);\n const e35 = this._boxes;\n if (this.numItems \u003c= this.nodeSize)\n return e35[this._pos++] = this.minX, e35[this._pos++] = this.minY, e35[this._pos++] = this.maxX, void (e35[this._pos++] = this.maxY);\n const { numItems: t2, minX: n2, minY: o3, nodeSize: i3, _indices: r3, _levelBounds: s2 } = this, a3 = this.maxX - n2 || 1, c3 = this.maxY - o3 || 1, l3 = new Int32Array(t2), h2 = 65535 / a3, d2 = 65535 / c3;\n for (let i4 = 0, r4 = 0;i4 \u003c t2; i4++) {\n const t3 = e35[r4++], s3 = e35[r4++], a4 = h2 * ((t3 + e35[r4++]) / 2 - n2) | 0, c4 = d2 * ((s3 + e35[r4++]) / 2 - o3) | 0;\n l3[i4] = gy(a4, c4);\n }\n (function(e36, t3, n3, o4, i4, r4) {\n const s3 = [o4, i4];\n for (;s3.length; ) {\n const o5 = s3.pop() || 0, i5 = s3.pop() || 0;\n if (o5 - i5 \u003c= r4 \u0026\u0026 Math.floor(i5 / r4) \u003e= Math.floor(o5 / r4))\n continue;\n const a4 = e36[i5], c4 = e36[i5 + o5 \u003e\u003e 1], l4 = e36[o5], h3 = a4 \u003e c4 != a4 \u003e l4 ? a4 : c4 \u003c a4 != c4 \u003c l4 ? c4 : l4;\n let d3 = i5 - 1, u3 = o5 + 1;\n for (;; ) {\n do {\n d3++;\n } while (e36[d3] \u003c h3);\n do {\n u3--;\n } while (e36[u3] \u003e h3);\n if (d3 \u003e= u3)\n break;\n my(e36, t3, n3, d3, u3);\n }\n s3.push(i5, u3, u3 + 1, o5);\n }\n })(l3, e35, r3, 0, t2 - 1, i3);\n let u2 = 4 * t2;\n for (let t3 = 0, n3 = 0;t3 \u003c s2.length - 1; t3++) {\n const o4 = s2[t3];\n for (;n3 \u003c o4; ) {\n const t4 = n3;\n let s3 = e35[n3++], a4 = e35[n3++], c4 = e35[n3++], l4 = e35[n3++];\n for (let t5 = 1;t5 \u003c i3 \u0026\u0026 n3 \u003c o4; t5++)\n s3 = Math.min(s3, e35[n3++]), a4 = Math.min(a4, e35[n3++]), c4 = Math.max(c4, e35[n3++]), l4 = Math.max(l4, e35[n3++]);\n r3[u2 \u003e\u003e 2] = t4, e35[u2++] = s3, e35[u2++] = a4, e35[u2++] = c4, e35[u2++] = l4;\n }\n }\n this._pos = u2;\n }\n search(e35, t2, n2, o3, i3) {\n if (this._pos !== this._boxes.length)\n throw new Error(\"Data not yet indexed - call index.finish().\");\n const { _boxes: r3, _levelBounds: s2, _indices: a3, nodeSize: c3 } = this, l3 = 4 * this.numItems;\n let h2 = r3.length - 4, d2 = s2.length - 1;\n const u2 = [], p3 = [];\n let m2 = false;\n for (;h2 !== undefined; ) {\n const g2 = Math.min(h2 + 4 * c3, s2[d2]), f2 = h2 \u003e= l3;\n if (m2)\n this._collectContained(h2, g2, d2, l3, p3, i3);\n else\n for (let s3 = h2;s3 \u003c g2; s3 += 4) {\n const c4 = r3[s3];\n if (n2 \u003c c4)\n continue;\n const l4 = r3[s3 + 1];\n if (o3 \u003c l4)\n continue;\n const h3 = r3[s3 + 2];\n if (e35 \u003e h3)\n continue;\n const m3 = r3[s3 + 3];\n if (t2 \u003e m3)\n continue;\n const g3 = 0 | a3[s3 \u003e\u003e 2];\n if (f2) {\n const i4 = +(e35 \u003c= c4 \u0026\u0026 t2 \u003c= l4 \u0026\u0026 n2 \u003e= h3 \u0026\u0026 o3 \u003e= m3);\n u2.push(g3 | i4, d2 - 1);\n } else\n (i3 === undefined || i3(g3, c4, l4, h3, m3)) \u0026\u0026 p3.push(g3);\n }\n d2 = u2.pop(), h2 = u2.pop(), h2 !== undefined \u0026\u0026 (m2 = !(1 \u0026 ~h2), h2 \u0026= -2);\n }\n return p3;\n }\n _collectContained(e35, t2, n2, o3, i3, r3) {\n const s2 = this._boxes, a3 = this._indices;\n let c3 = e35;\n for (let e36 = n2;e36 \u003e 0; e36--)\n c3 = a3[c3 \u003e\u003e 2];\n const l3 = Math.min(c3 + (t2 - e35) * this.nodeSize ** n2, o3);\n if (r3 === undefined)\n for (;c3 \u003c l3; c3 += 4)\n i3.push(0 | a3[c3 \u003e\u003e 2]);\n else\n for (;c3 \u003c l3; c3 += 4) {\n const e36 = 0 | a3[c3 \u003e\u003e 2];\n r3(e36, s2[c3], s2[c3 + 1], s2[c3 + 2], s2[c3 + 3]) \u0026\u0026 i3.push(e36);\n }\n }\n neighbors(e35, t2, n2 = 1 / 0, o3 = 1 / 0, i3) {\n if (this._pos !== this._boxes.length)\n throw new Error(\"Data not yet indexed - call index.finish().\");\n const { _boxes: r3, _levelBounds: s2, _indices: a3, _queue: c3, nodeSize: l3 } = this, h2 = 4 * this.numItems, d2 = 4 * l3, u2 = [], p3 = n2 === 1;\n let m2 = o3 * o3;\n for (c3.push(r3.length - 4 \u003c\u003c 1, 0);c3.length; ) {\n const o4 = c3.ids[0];\n if (1 \u0026 o4) {\n if (c3.pop(), u2.push(o4 \u003e\u003e 1), u2.length === n2)\n break;\n continue;\n }\n c3.pop();\n const l4 = o4 \u003e\u003e 1, g2 = l4 \u003c h2, f2 = Math.min(l4 + d2, py(l4, s2));\n for (let n3 = l4;n3 \u003c f2; n3 += 4) {\n const o5 = r3[n3], s3 = r3[n3 + 1], l5 = r3[n3 + 2], h3 = r3[n3 + 3], d3 = Math.max(Math.max(o5 - e35, e35 - l5), 0), u3 = Math.max(Math.max(s3 - t2, t2 - h3), 0), f3 = d3 * d3 + u3 * u3;\n if (f3 \u003e m2)\n continue;\n const _2 = 0 | a3[n3 \u003e\u003e 2];\n g2 ? (i3 === undefined || i3(_2)) \u0026\u0026 (c3.push(_2 \u003c\u003c 1 | 1, f3), p3 \u0026\u0026 f3 \u003c m2 \u0026\u0026 (m2 = f3)) : c3.push(_2 \u003c\u003c 1, f3);\n }\n }\n return c3.clear(), u2;\n }\n};\nfunction py(e35, t2) {\n let n2 = 0, o3 = t2.length - 1;\n for (;n2 \u003c o3; ) {\n const i3 = n2 + o3 \u003e\u003e 1;\n t2[i3] \u003e e35 ? o3 = i3 : n2 = i3 + 1;\n }\n return t2[n2];\n}\nfunction my(e35, t2, n2, o3, i3) {\n const r3 = e35[o3];\n e35[o3] = e35[i3], e35[i3] = r3;\n const s2 = 4 * o3, a3 = 4 * i3, c3 = t2[s2], l3 = t2[s2 + 1], h2 = t2[s2 + 2], d2 = t2[s2 + 3];\n t2[s2] = t2[a3], t2[s2 + 1] = t2[a3 + 1], t2[s2 + 2] = t2[a3 + 2], t2[s2 + 3] = t2[a3 + 3], t2[a3] = c3, t2[a3 + 1] = l3, t2[a3 + 2] = h2, t2[a3 + 3] = d2;\n const u2 = n2[o3];\n n2[o3] = n2[i3], n2[i3] = u2;\n}\nfunction gy(e35, t2) {\n let n2 = e35 ^ t2, o3 = 65535 ^ n2, i3 = 65535 ^ (e35 | t2), r3 = e35 \u0026 (65535 ^ t2), s2 = n2 | o3 \u003e\u003e 1, a3 = n2 \u003e\u003e 1 ^ n2, c3 = i3 ^ i3 \u003e\u003e 1 ^ o3 \u0026 r3 \u003e\u003e 1, l3 = r3 ^ n2 \u0026 i3 \u003e\u003e 1 ^ r3 \u003e\u003e 1;\n return n2 = s2 \u0026 s2 \u003e\u003e 2 ^ a3 \u0026 a3 \u003e\u003e 2, o3 = s2 \u0026 a3 \u003e\u003e 2 ^ a3 \u0026 (s2 ^ a3) \u003e\u003e 2, i3 = c3 ^ s2 \u0026 c3 \u003e\u003e 2 ^ a3 \u0026 l3 \u003e\u003e 2, r3 = l3 ^ a3 \u0026 c3 \u003e\u003e 2 ^ (s2 ^ a3) \u0026 l3 \u003e\u003e 2, s2 = n2 \u0026 n2 \u003e\u003e 4 ^ o3 \u0026 o3 \u003e\u003e 4, a3 = n2 \u0026 o3 \u003e\u003e 4 ^ o3 \u0026 (n2 ^ o3) \u003e\u003e 4, c3 = i3 ^ n2 \u0026 i3 \u003e\u003e 4 ^ o3 \u0026 r3 \u003e\u003e 4, l3 = r3 ^ o3 \u0026 i3 \u003e\u003e 4 ^ (n2 ^ o3) \u0026 r3 \u003e\u003e 4, i3 = c3 ^ s2 \u0026 c3 \u003e\u003e 8 ^ a3 \u0026 l3 \u003e\u003e 8, r3 = l3 ^ a3 \u0026 c3 \u003e\u003e 8 ^ (s2 ^ a3) \u0026 l3 \u003e\u003e 8, i3 ^= i3 \u003e\u003e 1, r3 ^= r3 \u003e\u003e 1, n2 = e35 ^ t2, o3 = r3 | 65535 ^ (n2 | i3), n2 = 16711935 \u0026 (n2 | n2 \u003c\u003c 8), n2 = 252645135 \u0026 (n2 | n2 \u003c\u003c 4), n2 = 858993459 \u0026 (n2 | n2 \u003c\u003c 2), n2 = 1431655765 \u0026 (n2 | n2 \u003c\u003c 1), o3 = 16711935 \u0026 (o3 | o3 \u003c\u003c 8), o3 = 252645135 \u0026 (o3 | o3 \u003c\u003c 4), o3 = 858993459 \u0026 (o3 | o3 \u003c\u003c 2), o3 = 1431655765 \u0026 (o3 | o3 \u003c\u003c 1), ((o3 \u003c\u003c 1 | n2) \u003e\u003e\u003e 0) - 2147483648;\n}\nvar fy = (e35, t2) =\u003e {\n const n2 = e35.end.x - e35.start.x, o3 = e35.end.y - e35.start.y, i3 = t2.end.x - t2.start.x, r3 = t2.end.y - t2.start.y, s2 = t2.start.x - e35.start.x, a3 = t2.start.y - e35.start.y, c3 = n2 * r3 - o3 * i3, l3 = (e36, t3) =\u003e ({ x: e36.start.x + (e36.end.x - e36.start.x) * t3, y: e36.start.y + (e36.end.y - e36.start.y) * t3 }), h2 = (e36, t3) =\u003e {\n const n3 = t3.end.x - t3.start.x, o4 = t3.end.y - t3.start.y, i4 = n3 * n3 + o4 * o4, r4 = i4 \u003e 0.00000000000000010000000000000001 ? Math.max(0, Math.min(1, ((e36.x - t3.start.x) * n3 + (e36.y - t3.start.y) * o4) / i4)) : 0;\n return l3(t3, r4);\n };\n if (Math.abs(c3) \u003e Aa) {\n const t3 = (s2 * r3 - a3 * i3) / c3, h3 = (s2 * o3 - a3 * n2) / c3;\n if (t3 \u003e= 0 \u0026\u0026 t3 \u003c= 1 \u0026\u0026 h3 \u003e= 0 \u0026\u0026 h3 \u003c= 1) {\n const n3 = l3(e35, t3);\n return [n3, n3];\n }\n } else {\n const i4 = n2 * n2 + o3 * o3;\n if (i4 \u003e 0.00000000000000010000000000000001) {\n const r4 = (s2 * n2 + a3 * o3) / i4, c4 = ((t2.end.x - e35.start.x) * n2 + (t2.end.y - e35.start.y) * o3) / i4, d3 = Math.max(0, Math.min(r4, c4)), u2 = Math.min(1, Math.max(r4, c4));\n if (d3 \u003c= u2) {\n const n3 = l3(e35, (d3 + u2) / 2);\n return [n3, h2(n3, t2)];\n }\n }\n }\n const d2 = [[e35.start, h2(e35.start, t2)], [e35.end, h2(e35.end, t2)], [h2(t2.start, e35), t2.start], [h2(t2.end, e35), t2.end]];\n return d2.sort((e36, t3) =\u003e Math.hypot(e36[0].x - e36[1].x, e36[0].y - e36[1].y) - Math.hypot(t3[0].x - t3[1].x, t3[0].y - t3[1].y)), d2[0];\n};\nvar _y = (e35, t2) =\u003e {\n const n2 = e35 === \"top\" ? 0 : e35 === \"bottom\" ? t2 - 1 : /^inner\\d+$/.test(e35) ? Number(e35.slice(5)) : -1;\n if (!Number.isInteger(n2) || n2 \u003c 0 || n2 \u003e= t2)\n throw new Error(`repair04 preload has an unknown layer: ${e35}`);\n return n2;\n};\nvar yy = (e35, t2, n2) =\u003e {\n const o3 = ((e36, t3) =\u003e {\n const n3 = new Map, o4 = (e37) =\u003e {\n const t4 = n3.get(e37);\n if (t4 === undefined || t4 === e37)\n return e37;\n const i5 = o4(t4);\n return n3.set(e37, i5), i5;\n }, i4 = (e37) =\u003e {\n const t4 = e37.filter((e38) =\u003e typeof e38 == \"string\" \u0026\u0026 e38.length \u003e 0);\n if (t4.length === 0)\n return;\n const i5 = o4(t4[0]);\n for (const e38 of t4)\n n3.set(o4(e38), i5);\n };\n for (const t4 of e36.connections) {\n const e37 = t4;\n i4([e37.name, e37.rootConnectionName, e37.netConnectionName, e37.__netConnectionName, ...e37.mergedConnectionNames ?? [], ...e37.__rootConnectionNames ?? []]);\n }\n for (const e37 of t3)\n i4([e37.connectionName, e37.rootConnectionName]);\n for (const t4 of e36.traces ?? [])\n i4([t4.connection_name, ...t4.connectsTo ?? []]);\n return o4;\n })(e35, t2), i3 = t2.map((e36, t3) =\u003e t3), r3 = (e36) =\u003e {\n const t3 = i3[e36];\n if (t3 === e36)\n return e36;\n const n3 = r3(t3);\n return i3[e36] = n3, n3;\n }, s2 = new Map, a3 = new Map;\n for (let t3 = 0;t3 \u003c e35.obstacles.length; t3 += 1)\n for (const n3 of e35.obstacles[t3].connectedTo) {\n const e36 = a3.get(n3) ?? [];\n e36.push(t3), a3.set(n3, e36);\n }\n for (let n3 = 0;n3 \u003c t2.length; n3 += 1) {\n const c4 = t2[n3];\n for (const t3 of [c4.route[0], c4.route.at(-1)]) {\n if (!t3)\n continue;\n const l4 = o3(c4.connectionName), h3 = [JSON.stringify([l4, \"point\", t3.x, t3.y, t3.z])], d3 = t3.pcb_port_id ? a3.get(t3.pcb_port_id) ?? [] : [];\n for (const n4 of d3) {\n const o4 = e35.obstacles[n4];\n if (!(o4.zLayers ?? o4.layers.map((t4) =\u003e _y(t4, e35.layerCount))).includes(t3.z))\n continue;\n const i4 = (o4.ccwRotationDegrees ?? 0) * Math.PI / 180, r4 = t3.x - o4.center.x, s3 = t3.y - o4.center.y, a4 = { x: r4 * Math.cos(i4) + s3 * Math.sin(i4), y: -r4 * Math.sin(i4) + s3 * Math.cos(i4) };\n oy(a4, a4, ny(o4)) \u003e Aa || h3.push(JSON.stringify([l4, \"pad\", n4]));\n }\n for (const e36 of h3) {\n const t4 = s2.get(e36);\n t4 === undefined ? s2.set(e36, n3) : i3[r3(n3)] = r3(t4);\n }\n }\n }\n const c3 = (e36, t3) =\u003e !(!e36.startsWith(\"route:\") || !t3.startsWith(\"route:\")) \u0026\u0026 r3(Number(e36.slice(6))) === r3(Number(t3.slice(6))), l3 = [], h2 = [], d2 = [], u2 = t2.map(() =\u003e ({ segmentTimes: new Map, viaPositions: [] })), p3 = (e36) =\u003e {\n if (Oa(e36, n2)) {\n d2.push(e36);\n for (let t3 = e36.minZ;t3 \u003c= e36.maxZ; t3 += 1)\n l3.push({ x: e36.x, y: e36.y, z: t3, radius: e36.radius, net: e36.net, source: e36.source, ...e36.routeIndex !== undefined ? { viaOwner: e36.routeIndex } : {} });\n }\n };\n for (let e36 = 0;e36 \u003c t2.length; e36 += 1) {\n const i4 = t2[e36], r4 = o3(i4.connectionName), s3 = `route:${e36}`;\n for (let t3 = 0;t3 \u003c i4.route.length; t3 += 1) {\n const o4 = i4.route[t3];\n if ((t3 === 0 || t3 === i4.route.length - 1 || o4.pcb_port_id) \u0026\u0026 Oa(o4, n2) \u0026\u0026 l3.push({ x: o4.x, y: o4.y, z: o4.z, radius: (o4.traceThickness ?? i4.traceThickness) / 2, net: r4, source: s3 }), t3 === 0)\n continue;\n const a4 = i4.route[t3 - 1];\n a4.toNextSegmentType !== \"through_obstacle\" \u0026\u0026 (a4.z === o4.z ? h2.push({ start: a4, end: o4, z: o4.z, radius: Math.max(a4.traceThickness ?? i4.traceThickness, o4.traceThickness ?? i4.traceThickness) / 2, net: r4, source: s3, routeIndex: e36, segmentIndex: t3 - 1 }) : p3({ x: o4.x, y: o4.y, minZ: Math.min(a4.z, o4.z), maxZ: Math.max(a4.z, o4.z), radius: i4.viaDiameter / 2, net: r4, source: s3, routeIndex: e36 }));\n }\n }\n for (let t3 = 0;t3 \u003c (e35.traces ?? []).length; t3 += 1) {\n const i4 = Ta(e35.traces[t3], e35.minTraceWidth), r4 = o3(i4.connection_name), s3 = `fixed:${t3}`;\n for (let t4 = 0;t4 \u003c i4.route.length; t4 += 1) {\n const o4 = i4.route[t4], a4 = i4.route[t4 - 1];\n if (o4.route_type === \"wire\") {\n const c4 = _y(o4.layer, e35.layerCount);\n (t4 === 0 || t4 === i4.route.length - 1 || o4.start_pcb_port_id || o4.end_pcb_port_id) \u0026\u0026 Oa(o4, n2) \u0026\u0026 l3.push({ x: o4.x, y: o4.y, z: c4, radius: o4.width / 2, net: r4, source: s3 }), a4?.route_type === \"wire\" \u0026\u0026 a4.layer === o4.layer \u0026\u0026 h2.push({ start: a4, end: o4, z: c4, radius: Math.max(a4.width, o4.width) / 2, net: r4, source: s3 });\n } else if (o4.route_type === \"via\") {\n const t5 = _y(o4.from_layer, e35.layerCount), n3 = _y(o4.to_layer, e35.layerCount);\n p3({ x: o4.x, y: o4.y, minZ: Math.min(t5, n3), maxZ: Math.max(t5, n3), radius: (o4.via_diameter ?? e35.minViaDiameter ?? 0.3) / 2, net: r4, source: s3 });\n }\n }\n }\n const m2 = new Map;\n for (const e36 of l3) {\n const t3 = JSON.stringify([e36.net, e36.z]), n3 = m2.get(t3) ?? [];\n n3.push(e36), m2.set(t3, n3);\n }\n const g2 = new Map;\n for (const [e36, t3] of m2) {\n const n3 = new uy(t3.length);\n for (const e37 of t3) {\n const t4 = e37.radius + Aa;\n n3.add(e37.x - t4, e37.y - t4, e37.x + t4, e37.y + t4);\n }\n n3.finish(), g2.set(e36, n3);\n }\n const f2 = (e36, t3, n3) =\u003e {\n const o4 = JSON.stringify([e36, t3]), i4 = m2.get(o4);\n return i4 ? g2.get(o4).search(n3.minX, n3.minY, n3.maxX, n3.maxY).sort((e37, t4) =\u003e e37 - t4).map((e37) =\u003e i4[e37]) : [];\n }, _2 = (e36, t3) =\u003e {\n if (e36 === undefined)\n return;\n const n3 = u2[e36].viaPositions;\n n3.some((e37) =\u003e Math.hypot(e37.x - t3.x, e37.y - t3.y) \u003c= Aa) || n3.push({ x: t3.x, y: t3.y });\n };\n for (const e36 of h2) {\n if (!ka(e36.start, e36.end, n2))\n continue;\n const t3 = e36.end.x - e36.start.x, o4 = e36.end.y - e36.start.y, i4 = t3 * t3 + o4 * o4;\n if (i4 \u003c= 0.00000000000000010000000000000001)\n continue;\n const r4 = e36.radius + Aa;\n for (const s3 of f2(e36.net, e36.z, { minX: Math.min(e36.start.x, e36.end.x) - r4, minY: Math.min(e36.start.y, e36.end.y) - r4, maxX: Math.max(e36.start.x, e36.end.x) + r4, maxY: Math.max(e36.start.y, e36.end.y) + r4 })) {\n if (s3.source === e36.source || c3(s3.source, e36.source))\n continue;\n const r5 = Math.max(0, Math.min(1, ((s3.x - e36.start.x) * t3 + (s3.y - e36.start.y) * o4) / i4)), a4 = { x: e36.start.x + t3 * r5, y: e36.start.y + o4 * r5 };\n if (Oa(a4, n2) \u0026\u0026 !(Math.hypot(a4.x - s3.x, a4.y - s3.y) \u003e e36.radius + s3.radius + Aa)) {\n if (e36.routeIndex !== undefined \u0026\u0026 e36.segmentIndex !== undefined) {\n const t4 = u2[e36.routeIndex].segmentTimes.get(e36.segmentIndex) ?? [];\n t4.some((e37) =\u003e Math.abs(e37 - r5) \u003c= Aa) || t4.push(r5), u2[e36.routeIndex].segmentTimes.set(e36.segmentIndex, t4);\n }\n _2(s3.viaOwner, s3);\n }\n }\n }\n for (const e36 of d2) {\n const t3 = e36.radius + Aa;\n for (let n3 = e36.minZ;n3 \u003c= e36.maxZ; n3 += 1)\n for (const o4 of f2(e36.net, n3, { minX: e36.x - t3, minY: e36.y - t3, maxX: e36.x + t3, maxY: e36.y + t3 }))\n o4.source === e36.source || c3(o4.source, e36.source) || Math.hypot(e36.x - o4.x, e36.y - o4.y) \u003e e36.radius + o4.radius + Aa || (_2(e36.routeIndex, e36), _2(o4.viaOwner, o4));\n }\n return ((e36, t3, n3, o4) =\u003e {\n const i4 = new Map, r4 = new Set, s3 = [], a4 = (e37, t4) =\u003e {\n if (e37.routeIndex === undefined || e37.segmentIndex === undefined)\n return;\n const o5 = e37.end.x - e37.start.x, i5 = e37.end.y - e37.start.y, r5 = o5 * o5 + i5 * i5;\n if (r5 \u003c= 0.00000000000000010000000000000001)\n return;\n const s4 = Math.max(0, Math.min(1, ((t4.x - e37.start.x) * o5 + (t4.y - e37.start.y) * i5) / r5)), a5 = n3[e37.routeIndex].segmentTimes.get(e37.segmentIndex) ?? [];\n a5.some((e38) =\u003e Math.abs(e38 - s4) \u003c= Aa) || a5.push(s4), n3[e37.routeIndex].segmentTimes.set(e37.segmentIndex, a5);\n };\n for (const n4 of e36) {\n const e37 = ka(n4.start, n4.end, t3);\n if (!e37 || e37[1] - e37[0] \u003c= Aa)\n continue;\n const c4 = (e38) =\u003e ({ x: n4.start.x + (n4.end.x - n4.start.x) * e38, y: n4.start.y + (n4.end.y - n4.start.y) * e38 }), l4 = { ...n4, start: c4(e37[0]), end: c4(e37[1]) }, h3 = s3.length;\n s3.push({ original: n4, clipped: l4 });\n const d3 = Math.floor((Math.min(l4.start.x, l4.end.x) - l4.radius) / 2), u3 = Math.floor((Math.max(l4.start.x, l4.end.x) + l4.radius) / 2), p4 = Math.floor((Math.min(l4.start.y, l4.end.y) - l4.radius) / 2), m3 = Math.floor((Math.max(l4.start.y, l4.end.y) + l4.radius) / 2);\n for (let e38 = d3;e38 \u003c= u3; e38 += 1)\n for (let t4 = p4;t4 \u003c= m3; t4 += 1) {\n const c5 = JSON.stringify([l4.net, l4.z, e38, t4]), d4 = i4.get(c5) ?? [];\n for (const e39 of d4) {\n const t5 = s3[e39];\n if (t5.original.source === n4.source || o4(t5.original.source, n4.source) || t5.original.routeIndex === undefined \u0026\u0026 n4.routeIndex === undefined)\n continue;\n const i5 = `${e39}:${h3}`;\n if (r4.has(i5))\n continue;\n r4.add(i5);\n const [c6, d5] = fy(l4, t5.clipped);\n Math.hypot(c6.x - d5.x, c6.y - d5.y) \u003e l4.radius + t5.clipped.radius + Aa || (a4(n4, c6), a4(t5.original, d5));\n }\n d4.push(h3), i4.set(c5, d4);\n }\n }\n })(h2, n2, u2, c3), u2;\n};\nvar by = (e35, t2) =\u003e ({ minX: e35.minX - t2, maxX: e35.maxX + t2, minY: e35.minY - t2, maxY: e35.maxY + t2 });\nvar xy = (e35, t2, n2, o3) =\u003e {\n const i3 = [];\n let r3;\n const s2 = e35.route, a3 = (e36) =\u003e e36 === 0 || e36 === s2.length - 1 || s2[e36]?.pcb_port_id !== undefined, c3 = () =\u003e {\n r3 !== undefined \u0026\u0026 r3.points.length \u003e 0 \u0026\u0026 (r3.locks[0] = true, r3.locks[r3.points.length - 1] = true, i3.push(r3)), r3 = undefined;\n };\n if (s2.length === 1 \u0026\u0026 s2[0] \u0026\u0026 Oa(s2[0], t2))\n return [{ points: structuredClone(s2), locks: [true], start: { segmentIndex: 0, t: 0 }, end: { segmentIndex: 0, t: 0 } }];\n for (let i4 = 0;i4 \u003c s2.length - 1; i4 += 1) {\n const l3 = s2[i4], h2 = s2[i4 + 1];\n if (!l3 || !h2)\n throw new Error(\"repair04 found a missing route point\");\n if (![l3.x, l3.y, l3.z, h2.x, h2.y, h2.z].every(Number.isFinite))\n throw new Error(\"repair04 route coordinates must be finite\");\n if (l3.z !== h2.z \u0026\u0026 !La({ x: l3.x, y: l3.y }, { x: h2.x, y: h2.y }) \u0026\u0026 l3.toNextSegmentType !== \"through_obstacle\")\n throw new Error(\"repair04 requires colocated points at a via transition\");\n const d2 = ka(l3, h2, t2);\n if (!d2) {\n c3();\n continue;\n }\n const [u2, p3] = d2;\n if (p3 - u2 \u003c= Aa \u0026\u0026 !La(l3, h2)) {\n c3();\n continue;\n }\n const m2 = ka(l3, h2, n2), g2 = [u2, p3], f2 = o3.segmentTimes.get(i4) ?? [];\n for (const e36 of f2)\n e36 \u003e= u2 - Aa \u0026\u0026 e36 \u003c= p3 + Aa \u0026\u0026 g2.push(Math.max(u2, Math.min(p3, e36)));\n if (m2 \u0026\u0026 l3.z === h2.z)\n for (const e36 of m2)\n e36 \u003e u2 + Aa \u0026\u0026 e36 \u003c p3 - Aa \u0026\u0026 g2.push(e36);\n g2.sort((e36, t3) =\u003e e36 - t3);\n const _2 = g2.filter((e36, t3) =\u003e t3 === 0 || Math.abs(e36 - g2[t3 - 1]) \u003e Aa), y2 = Da(l3, h2, u2);\n r3 \u0026\u0026 !La(r3.points[r3.points.length - 1], y2) \u0026\u0026 c3(), r3 || (r3 = { points: [], locks: [], start: { segmentIndex: i4, t: u2 }, end: { segmentIndex: i4, t: p3 } });\n for (const t3 of _2) {\n const s3 = Da(l3, h2, t3), c4 = t3 \u003c= Aa ? i4 : t3 \u003e= 0.99999999 ? i4 + 1 : undefined, d3 = !Oa(s3, n2, 0.00000004) || f2.some((e36) =\u003e Math.abs(e36 - t3) \u003c= Aa) || o3.viaPositions.some((e36) =\u003e Math.hypot(e36.x - s3.x, e36.y - s3.y) \u003c= Aa) || c4 !== undefined \u0026\u0026 a3(c4) || l3.toNextSegmentType === \"through_obstacle\" || s3.toNextSegmentType === \"through_obstacle\" || l3.insideJumperPad === true || h2.insideJumperPad === true || (e35.jumpers ?? []).some((e36) =\u003e La(s3, { ...e36.start, z: s3.z }) || La(s3, { ...e36.end, z: s3.z })), u3 = r3.points[r3.points.length - 1];\n u3 \u0026\u0026 u3.x === s3.x \u0026\u0026 u3.y === s3.y \u0026\u0026 u3.z === s3.z ? r3.locks[r3.locks.length - 1] = r3.locks[r3.locks.length - 1] || d3 : (r3.points.push(s3), r3.locks.push(d3));\n }\n r3.end = { segmentIndex: i4, t: p3 }, p3 \u003c 0.99999999 \u0026\u0026 c3();\n }\n c3();\n for (const e36 of i3)\n for (let t3 = 1;t3 \u003c e36.points.length; t3 += 1) {\n const n3 = e36.points[t3 - 1], o4 = e36.points[t3];\n if (n3.z !== o4.z \u0026\u0026 (e36.locks[t3 - 1] || e36.locks[t3])) {\n let n4 = t3 - 1, i4 = t3;\n for (;n4 \u003e 0 \u0026\u0026 La({ x: e36.points[n4 - 1].x, y: e36.points[n4 - 1].y }, { x: o4.x, y: o4.y }); )\n n4 -= 1;\n for (;i4 + 1 \u003c e36.points.length \u0026\u0026 La({ x: e36.points[i4 + 1].x, y: e36.points[i4 + 1].y }, { x: o4.x, y: o4.y }); )\n i4 += 1;\n for (let t4 = n4;t4 \u003c= i4; t4 += 1)\n e36.locks[t4] = true;\n }\n }\n return i3;\n};\nvar vy = (e35, t2) =\u003e {\n const n2 = e35.bounds, o3 = e35.outline \u0026\u0026 e35.outline.length \u003e= 3 ? e35.outline : [{ x: n2.minX, y: n2.minY }, { x: n2.maxX, y: n2.minY }, { x: n2.maxX, y: n2.maxY }, { x: n2.minX, y: n2.maxY }], i3 = [];\n for (let n3 = 0;n3 \u003c o3.length; n3 += 1) {\n const r3 = o3[n3], s2 = o3[(n3 + 1) % o3.length], a3 = ka(r3, s2, t2);\n if (!a3)\n continue;\n const c3 = s2.x - r3.x, l3 = s2.y - r3.y, h2 = Math.hypot(c3, l3);\n if (h2 \u003c= Aa)\n continue;\n const d2 = (a3[0] + a3[1]) / 2;\n i3.push({ obstacleId: `repair04_board_edge_${n3}`, type: \"rect\", center: { x: r3.x + c3 * d2, y: r3.y + l3 * d2 }, width: h2 * (a3[1] - a3[0]), height: Math.max(2 * (e35.minBoardEdgeClearance ?? 0), Aa), ccwRotationDegrees: 180 * Math.atan2(l3, c3) / Math.PI, layers: Array.from({ length: e35.layerCount }, (t3, n4) =\u003e n4 === 0 ? \"top\" : n4 === e35.layerCount - 1 ? \"bottom\" : `inner${n4}`), zLayers: Array.from({ length: e35.layerCount }, (e36, t3) =\u003e t3), connectedTo: [] });\n }\n return i3;\n};\nvar Iy = ({ srj: e35, routes: t2, bounds: n2, boundaryMargin: o3 = 0.5, clearanceHalo: i3 }) =\u003e {\n if (((e36) =\u003e {\n if (!Object.values(e36).every(Number.isFinite))\n throw new Error(\"repair04 bounds must contain finite coordinates\");\n if (e36.maxX - e36.minX \u003c 9.99999999 || e36.maxY - e36.minY \u003c 9.99999999)\n throw new Error(\"repair04 requires bounds at least 10 mm by 10 mm\");\n })(n2), !Number.isFinite(o3) || o3 \u003c 0 || i3 !== undefined \u0026\u0026 (!Number.isFinite(i3) || i3 \u003c 0))\n throw new Error(\"repair04 collar and halo must be finite and nonnegative\");\n const r3 = Math.max(e35.defaultObstacleMargin ?? 0.2, e35.minTraceToPadEdgeClearance ?? 0, e35.minTraceToHoleEdgeClearance ?? 0, e35.minViaEdgeToPadEdgeClearance ?? 0);\n let s2 = Math.max(e35.minTraceWidth, e35.minViaDiameter ?? 0);\n for (const e36 of t2) {\n s2 = Math.max(s2, e36.traceThickness, e36.viaDiameter);\n for (const t3 of e36.route)\n s2 = Math.max(s2, t3.traceThickness ?? 0);\n }\n for (const t3 of e35.traces ?? [])\n for (const n3 of t3.route)\n n3.route_type === \"wire\" \u0026\u0026 (s2 = Math.max(s2, n3.width)), n3.route_type === \"via\" \u0026\u0026 (s2 = Math.max(s2, n3.via_diameter ?? e35.minViaDiameter ?? 0.3));\n if (!Number.isFinite(s2) || s2 \u003c= 0)\n throw new Error(\"repair04 requires finite positive copper widths\");\n const a3 = Math.max(o3, s2 + r3);\n if (2 * a3 \u003e= Math.min(n2.maxX - n2.minX, n2.maxY - n2.minY))\n throw new Error(\"repair04 bounds are too small for their required copper safety collar\");\n const c3 = by(n2, Math.max(i3 ?? a3, r3 + s2)), l3 = by(n2, -a3), h2 = yy(e35, t2, c3), d2 = ((e36, t3, n3) =\u003e {\n const o4 = [];\n for (const i4 of e36) {\n const e37 = Ta(i4, n3), r4 = [];\n let s3 = [];\n const a4 = () =\u003e {\n s3.length \u003e 0 \u0026\u0026 r4.push(s3), s3 = [];\n }, c4 = (e38) =\u003e {\n za(s3[s3.length - 1]) !== za(e38) \u0026\u0026 s3.push(structuredClone(e38));\n };\n for (let n4 = 0;n4 \u003c e37.route.length; n4 += 1) {\n const o5 = e37.route[n4], i5 = e37.route[n4 - 1];\n if (o5.route_type === \"wire\" \u0026\u0026 i5?.route_type === \"wire\" \u0026\u0026 o5.layer === i5.layer) {\n const e38 = ka(i5, o5, t3);\n if (!e38) {\n a4();\n continue;\n }\n const n5 = hy(i5, o5, e38[0]), r5 = hy(i5, o5, e38[1]), l4 = s3[s3.length - 1];\n l4?.route_type === \"wire\" \u0026\u0026 (l4.layer !== n5.layer || Math.hypot(l4.x - n5.x, l4.y - n5.y) \u003e Aa) \u0026\u0026 a4(), c4(n5), c4(r5), e38[1] \u003c 0.99999999 \u0026\u0026 a4();\n } else if (o5.route_type === \"via\") {\n if (!Oa(o5, t3)) {\n a4();\n continue;\n }\n if (i5?.route_type !== \"wire\")\n throw new Error(\"repair04 normalized preload via has no incoming wire\");\n c4(i5), c4(o5);\n const r5 = e37.route[n4 + 1];\n if (r5?.route_type !== \"wire\")\n throw new Error(\"repair04 normalized preload via has no outgoing wire\");\n c4(r5);\n } else if (o5.route_type === \"wire\")\n Oa(o5, t3) \u0026\u0026 c4(o5);\n else if (\"start\" in o5 \u0026\u0026 \"end\" in o5) {\n const e38 = ka(o5.start, o5.end, t3);\n if (!e38) {\n a4();\n continue;\n }\n const n5 = (e39) =\u003e ({ x: o5.start.x + (o5.end.x - o5.start.x) * e39, y: o5.start.y + (o5.end.y - o5.start.y) * e39 });\n c4({ ...structuredClone(o5), start: n5(e38[0]), end: n5(e38[1]) }), e38[1] \u003c 0.99999999 \u0026\u0026 a4();\n }\n }\n a4();\n for (let e38 = 0;e38 \u003c r4.length; e38 += 1)\n o4.push({ ...structuredClone(i4), pcb_trace_id: r4.length === 1 ? i4.pcb_trace_id : `${i4.pcb_trace_id}__repair04_fixed_${e38}`, route: r4[e38] });\n }\n return o4;\n })(e35.traces ?? [], c3, e35.minTraceWidth), u2 = [], p3 = [], m2 = [];\n for (let e36 = 0;e36 \u003c t2.length; e36 += 1) {\n const n3 = t2[e36];\n for (const t3 of xy(n3, c3, l3, h2[e36])) {\n const o4 = { ...structuredClone(Object.fromEntries(Object.entries(n3).filter(([e37]) =\u003e e37 !== \"route\" \u0026\u0026 e37 !== \"vias\" \u0026\u0026 e37 !== \"jumpers\"))), connectionName: n3.connectionName, traceThickness: n3.traceThickness, viaDiameter: n3.viaDiameter, route: t3.points, vias: n3.vias.filter((e37) =\u003e t3.points.some((t4) =\u003e Math.abs(t4.x - e37.x) \u003c= Aa \u0026\u0026 Math.abs(t4.y - e37.y) \u003c= Aa)).map((e37) =\u003e structuredClone(e37)), ...n3.jumpers !== undefined ? { jumpers: n3.jumpers.filter((e37) =\u003e ka(e37.start, e37.end, c3) !== undefined).map((e37) =\u003e structuredClone(e37)) } : {} };\n u2.push(o4), p3.push(t3.locks), m2.push({ sourceRouteIndex: e36, start: t3.start, end: t3.end, sourceGeometryKey: Fa(n3, t3.start.segmentIndex + t3.start.t, t3.end.segmentIndex + t3.end.t), originalFragment: structuredClone(o4) });\n }\n }\n const g2 = new Set([...u2.flatMap((e36) =\u003e [e36.connectionName, ...e36.rootConnectionName ? [e36.rootConnectionName] : []]), ...d2.map((e36) =\u003e e36.connection_name)]), f2 = e35.connections.filter((e36) =\u003e g2.has(e36.name) || e36.pointsToConnect.some((e37) =\u003e Oa(e37, c3))).map((e36) =\u003e ({ ...structuredClone(Object.fromEntries(Object.entries(e36).filter(([e37]) =\u003e e37 !== \"pointsToConnect\"))), name: e36.name, pointsToConnect: e36.pointsToConnect.filter((e37) =\u003e Oa(e37, c3)).map((e37) =\u003e structuredClone(e37)) }));\n for (let t3 = 0;t3 \u003c u2.length; t3 += 1) {\n const n3 = u2[t3];\n let o4 = f2.find((e36) =\u003e e36.name === n3.connectionName);\n o4 || (o4 = { name: n3.connectionName, ...n3.rootConnectionName ? { rootConnectionName: n3.rootConnectionName } : {}, pointsToConnect: [] }, f2.push(o4));\n for (const [i4, r4] of [[\"start\", n3.route[0]], [\"end\", n3.route[n3.route.length - 1]]]) {\n if (!r4)\n continue;\n const n4 = r4.z === 0 ? \"top\" : r4.z === e35.layerCount - 1 ? \"bottom\" : `inner${r4.z}`;\n o4.pointsToConnect.some((e36) =\u003e Math.abs(e36.x - r4.x) \u003c= Aa \u0026\u0026 Math.abs(e36.y - r4.y) \u003c= Aa \u0026\u0026 (\"layer\" in e36 ? e36.layer === n4 : e36.layers.includes(n4))) || o4.pointsToConnect.push({ x: r4.x, y: r4.y, layer: n4, pointId: `repair04_${t3}_${i4}`, ...r4.pcb_port_id ? { pcb_port_id: r4.pcb_port_id } : {} });\n }\n }\n const _2 = { ...Object.fromEntries(Object.entries(e35).filter(([e36, t3]) =\u003e e36 !== \"sourceCircuitJson\" \u0026\u0026 e36 !== \"sourceKicadPcb\" \u0026\u0026 (typeof t3 == \"number\" || typeof t3 == \"boolean\" || typeof t3 == \"string\"))), layerCount: e35.layerCount, minTraceWidth: e35.minTraceWidth, bounds: structuredClone(c3), obstacles: [...e35.obstacles.filter((e36) =\u003e ((e37, t3) =\u003e {\n const n3 = (e37.ccwRotationDegrees ?? 0) * Math.PI / 180, o4 = (Math.abs(e37.width * Math.cos(n3)) + Math.abs(e37.height * Math.sin(n3))) / 2, i4 = (Math.abs(e37.width * Math.sin(n3)) + Math.abs(e37.height * Math.cos(n3))) / 2;\n return e37.center.x + o4 \u003e= t3.minX \u0026\u0026 e37.center.x - o4 \u003c= t3.maxX \u0026\u0026 e37.center.y + i4 \u003e= t3.minY \u0026\u0026 e37.center.y - i4 \u003c= t3.maxY;\n })(e36, c3)).map((e36) =\u003e structuredClone(e36)), ...vy(e35, c3)], connections: f2, ...e35.traces !== undefined ? { traces: d2 } : {}, ...e35.allowJumpers !== undefined ? { allowJumpers: e35.allowJumpers } : {}, ...e35.availableJumperTypes ? { availableJumperTypes: structuredClone(e35.availableJumperTypes) } : {} };\n return { srj: _2, routes: u2, bounds: structuredClone(n2), contextBounds: c3, mutableBounds: l3, boundaryMargin: a3, lockedPointIndices: p3, routeMappings: m2 };\n};\nvar Sy = (e35) =\u003e za(Object.fromEntries(Object.entries(e35).filter(([e36]) =\u003e e36 !== \"route\" \u0026\u0026 e36 !== \"vias\")));\nvar Cy = (e35, t2) =\u003e {\n const n2 = [];\n for (let o3 = 1;o3 \u003c e35.route.length; o3 += 1) {\n const i3 = e35.route[o3 - 1], r3 = e35.route[o3], s2 = ka(i3, r3, t2), a3 = s2 ? [...s2[0] \u003e Aa ? [[0, s2[0]]] : [], ...s2[1] \u003c 0.99999999 ? [[s2[1], 1]] : []] : [[0, 1]];\n s2 \u0026\u0026 !Oa(Da(i3, r3, 0.5), t2, 0.00000004) \u0026\u0026 a3.length === 0 \u0026\u0026 a3.push([0, 1]);\n for (const [e36, t3] of a3)\n n2.push(za([Da(i3, r3, e36), Da(i3, r3, t3)]));\n }\n return n2;\n};\nvar Py = (e35, t2, n2, o3, i3, r3) =\u003e {\n if (Sy(e35) !== Sy(t2))\n throw new Error(\"repair04 merge rejected changed net, width, jumper, or route metadata\");\n if (n2.length !== e35.route.length)\n throw new Error(\"repair04 merge received an invalid lock mask\");\n if (t2.route.length === 0)\n throw new Error(\"repair04 merge rejected an empty replacement route\");\n if (za(e35.route[0]) !== za(t2.route[0]) || za(e35.route[e35.route.length - 1]) !== za(t2.route[t2.route.length - 1]))\n throw new Error(\"repair04 merge rejected a moved fragment endpoint\");\n let s2 = 0;\n for (let o4 = 0;o4 \u003c e35.route.length; o4 += 1) {\n if (!n2[o4])\n continue;\n const i4 = za(e35.route[o4]);\n for (;s2 \u003c t2.route.length \u0026\u0026 za(t2.route[s2]) !== i4; )\n s2 += 1;\n if (s2 === t2.route.length)\n throw new Error(\"repair04 merge rejected a moved or removed locked point\");\n s2 += 1;\n }\n if (za(Cy(e35, o3)) !== za(Cy(t2, o3)))\n throw new Error(\"repair04 merge rejected modified geometry in the fixed boundary collar\");\n for (let n3 = 1;n3 \u003c e35.route.length; n3 += 1) {\n const o4 = e35.route[n3 - 1], i4 = e35.route[n3];\n if (!(o4.toNextSegmentType === \"through_obstacle\" || o4.insideJumperPad === true || i4.insideJumperPad === true || (e35.jumpers ?? []).some((e36) =\u003e La(o4, { ...e36.start, z: o4.z }) \u0026\u0026 La(i4, { ...e36.end, z: i4.z }) || La(o4, { ...e36.end, z: o4.z }) \u0026\u0026 La(i4, { ...e36.start, z: i4.z }))))\n continue;\n const r4 = za([o4, i4]);\n if (!t2.route.some((e36, n4) =\u003e n4 + 1 \u003c t2.route.length \u0026\u0026 za([e36, t2.route[n4 + 1]]) === r4))\n throw new Error(\"repair04 merge rejected a changed atomic jumper or through-obstacle span\");\n }\n for (const n3 of t2.route) {\n if (![n3.x, n3.y, n3.z].every(Number.isFinite) || !Number.isInteger(n3.z) || n3.z \u003c 0 || n3.z \u003e= r3 || !Oa(n3, i3))\n throw new Error(\"repair04 merge rejected invalid or out-of-region geometry\");\n if ((n3.pcb_port_id !== undefined || n3.insideJumperPad === true || n3.toNextSegmentCircuitJsonMetadata !== undefined) \u0026\u0026 !e35.route.some((e36) =\u003e za(e36) === za(n3)))\n throw new Error(\"repair04 merge rejected invented or moved terminal/circuit metadata\");\n if (n3.traceThickness !== undefined \u0026\u0026 (!Number.isFinite(n3.traceThickness) || n3.traceThickness \u003c= 0 || n3.traceThickness \u003e Math.max(e35.traceThickness, ...e35.route.map((e36) =\u003e e36.traceThickness ?? 0)) + Aa))\n throw new Error(\"repair04 merge rejected increased per-point copper width\");\n }\n for (let n3 = 1;n3 \u003c t2.route.length; n3 += 1) {\n const o4 = t2.route[n3 - 1], i4 = t2.route[n3];\n if (o4.toNextSegmentType === \"through_obstacle\" \u0026\u0026 !e35.route.some((t3, n4) =\u003e n4 + 1 \u003c e35.route.length \u0026\u0026 za([t3, e35.route[n4 + 1]]) === za([o4, i4])))\n throw new Error(\"repair04 merge rejected an invented through-obstacle span\");\n if (o4.z !== i4.z \u0026\u0026 o4.toNextSegmentType !== \"through_obstacle\" \u0026\u0026 (Math.abs(o4.x - i4.x) \u003e Aa || Math.abs(o4.y - i4.y) \u003e Aa || !t2.vias.some((e36) =\u003e Math.abs(e36.x - o4.x) \u003c= Aa \u0026\u0026 Math.abs(e36.y - o4.y) \u003c= Aa)))\n throw new Error(\"repair04 merge rejected a disconnected or missing via\");\n }\n for (const n3 of t2.vias) {\n if (!(Number.isFinite(n3.x) \u0026\u0026 Number.isFinite(n3.y) \u0026\u0026 Oa(n3, i3) \u0026\u0026 t2.route.some((e36) =\u003e Math.abs(e36.x - n3.x) \u003c= Aa \u0026\u0026 Math.abs(e36.y - n3.y) \u003c= Aa)))\n throw new Error(\"repair04 merge rejected an invalid via position\");\n if (!Oa(n3, o3, 0.00000004) \u0026\u0026 !e35.vias.some((e36) =\u003e za(e36) === za(n3)))\n throw new Error(\"repair04 merge rejected a new via in the boundary collar\");\n }\n for (const n3 of e35.vias)\n if (!Oa(n3, o3, 0.00000004) \u0026\u0026 !t2.vias.some((e36) =\u003e za(e36) === za(n3)))\n throw new Error(\"repair04 merge rejected a changed via in the boundary collar\");\n};\nvar My = (e35, t2) =\u003e {\n for (const n2 of t2) {\n const t3 = e35[e35.length - 1];\n t3 \u0026\u0026 La(t3, n2) \u0026\u0026 za(t3) === za(n2) || e35.push(structuredClone(n2));\n }\n};\nvar wy = (e35, t2, n2) =\u003e {\n const o3 = new Set(t2.route.map(za)), i3 = new Set(n2.flatMap((e36) =\u003e e36.originalFragment.route.map(za)).filter((e36) =\u003e !o3.has(e36))), r3 = [];\n for (const t3 of e35)\n for (r3.push(t3);r3.length \u003e= 3; ) {\n const e36 = r3[r3.length - 3], t4 = r3[r3.length - 2], n3 = r3[r3.length - 1];\n if (!i3.has(za(t4)))\n break;\n if (e36.z !== t4.z || t4.z !== n3.z \u0026\u0026 e36.toNextSegmentType !== \"through_obstacle\")\n break;\n if (e36.toNextSegmentType !== t4.toNextSegmentType || e36.insideJumperPad !== t4.insideJumperPad || e36.traceThickness !== t4.traceThickness || za(e36.toNextSegmentCircuitJsonMetadata) !== za(t4.toNextSegmentCircuitJsonMetadata))\n break;\n const o4 = n3.x - e36.x, s2 = n3.y - e36.y, a3 = o4 * o4 + s2 * s2;\n if (a3 \u003c= 0.00000000000000010000000000000001)\n break;\n const c3 = (t4.x - e36.x) * s2 - (t4.y - e36.y) * o4, l3 = ((t4.x - e36.x) * o4 + (t4.y - e36.y) * s2) / a3;\n if (Math.abs(c3) \u003e Aa * Math.sqrt(a3) || l3 \u003c 0 || l3 \u003e 1)\n break;\n r3.splice(r3.length - 2, 1);\n }\n return r3;\n};\nvar Ny = (e35) =\u003e {\n if (!Number.isInteger(e35.segmentIndex) || e35.segmentIndex \u003c 0 || !Number.isFinite(e35.t) || e35.t \u003c 0 || e35.t \u003e 1)\n throw new Error(\"repair04 merge received invalid fragment provenance\");\n return e35.segmentIndex + e35.t;\n};\nvar Ry = (e35, t2) =\u003e {\n const n2 = Math.max(Math.abs(e35), Math.abs(t2));\n if (n2 === 0 || n2 === Number.POSITIVE_INFINITY)\n return n2;\n const o3 = e35 / n2, i3 = t2 / n2;\n return n2 * Math.sqrt(o3 * o3 + i3 * i3);\n};\nfunction Ty(e35, t2, n2) {\n return e35.minX - n2 - Aa \u003e t2.maxX || e35.maxX + n2 + Aa \u003c t2.minX || e35.minY - n2 - Aa \u003e t2.maxY || e35.maxY + n2 + Aa \u003c t2.minY;\n}\nfunction Ey({ route: e35, mutableBounds: t2 }) {\n const n2 = e35.vias.filter((n3) =\u003e !Oa(n3, t2, 0.00000004) \u0026\u0026 e35.route.some((e36) =\u003e Math.abs(e36.x - n3.x) \u003c= Aa \u0026\u0026 Math.abs(e36.y - n3.y) \u003c= Aa)).map((e36) =\u003e structuredClone(e36));\n for (let t3 = 1;t3 \u003c e35.route.length; t3++) {\n const o3 = e35.route[t3 - 1], i3 = e35.route[t3];\n if (o3.z !== i3.z \u0026\u0026 o3.toNextSegmentType !== \"through_obstacle\") {\n if (o3.x !== i3.x || o3.y !== i3.y)\n throw new Error(\"repair04: a layer transition must have coincident endpoints\");\n n2.some((e36) =\u003e e36.x === i3.x \u0026\u0026 e36.y === i3.y) || n2.push({ x: i3.x, y: i3.y });\n }\n }\n return n2;\n}\nvar Ay = class {\n constructor(e35) {\n this.srj = e35;\n }\n boardParents;\n createNetResolver(e35) {\n const t2 = new Map(this.boardParents), n2 = (e36) =\u003e {\n const o4 = t2.get(e36);\n if (o4 === undefined || o4 === e36)\n return e36;\n const i3 = n2(o4);\n return t2.set(e36, i3), i3;\n }, o3 = (e36) =\u003e {\n const o4 = e36.filter((e37) =\u003e Boolean(e37));\n if (!o4.length)\n return;\n const i3 = n2(o4[0]);\n for (const e37 of o4)\n t2.set(n2(e37), i3);\n };\n if (!this.boardParents) {\n for (const e36 of this.srj.connections) {\n const t3 = e36;\n o3([t3.name, t3.rootConnectionName, t3.netConnectionName, t3.__netConnectionName, ...t3.mergedConnectionNames ?? [], ...t3.__rootConnectionNames ?? [], ...t3.pointsToConnect.flatMap((e37) =\u003e [e37.pcb_port_id, e37.pointId])]);\n }\n for (const e36 of this.srj.obstacles)\n o3(e36.connectedTo);\n this.boardParents = new Map(t2);\n }\n for (const t3 of e35)\n o3([t3.connectionName, t3.rootConnectionName]);\n return n2;\n }\n};\nvar Dy = (e35, t2, n2) =\u003e {\n const o3 = n2.x - t2.x, i3 = n2.y - t2.y, r3 = o3 ** 2 + i3 ** 2;\n if (r3 === 0) {\n const n3 = e35.x - t2.x, o4 = e35.y - t2.y;\n return n3 * n3 + o4 * o4;\n }\n const s2 = Math.max(0, Math.min(1, ((e35.x - t2.x) * o3 + (e35.y - t2.y) * i3) / r3)), a3 = e35.x - (t2.x + s2 * o3), c3 = e35.y - (t2.y + s2 * i3);\n return a3 * a3 + c3 * c3;\n};\nvar Ly = (e35, t2, n2, o3) =\u003e e35.x === t2.x \u0026\u0026 e35.y === t2.y ? Math.sqrt(Dy(e35, n2, o3)) : n2.x === o3.x \u0026\u0026 n2.y === o3.y ? Math.sqrt(Dy(n2, e35, t2)) : he(e35, t2, n2, o3) ? 0 : Math.sqrt(Math.min(Dy(e35, n2, o3), Dy(t2, n2, o3), Dy(n2, e35, t2), Dy(o3, e35, t2)));\nvar zy = class extends BaseSolver {\n constructor(e35, t2) {\n super(), this.connectivity = t2, this.input = e35, this.stats = e35.stats ?? { nodesPopped: 0, completionReason: \"no-path\" }, this.MAX_ITERATIONS = Math.ceil((e35.maxNodes ?? 30000) / 128) + Math.ceil(e35.srj.obstacles.length / 128) + Math.ceil(e35.routes.length / 32) + Math.ceil((e35.srj.traces?.length ?? 0) / 32) + e35.srj.obstacles.length * e35.srj.layerCount + e35.routes.reduce((e36, t3) =\u003e e36 + t3.route.length, 0) + (e35.srj.traces ?? []).reduce((e36, t3) =\u003e e36 + t3.route.length, 0) + 32;\n }\n input;\n stats;\n phase = \"initialize\";\n cursor = 0;\n barrierCount = 0;\n output;\n prepareObstacle;\n prepareRoute;\n prepareTrace;\n indexBarrier;\n seedSearch;\n searchBatch;\n finish(e35) {\n this.output = e35, this.phase = \"finished\", this.solved = true, this.progress = 1, this.prepareObstacle = undefined, this.prepareRoute = undefined, this.prepareTrace = undefined, this.indexBarrier = undefined, this.seedSearch = undefined, this.searchBatch = undefined;\n }\n _step() {\n if (this.phase === \"initialize\")\n return void this.initialize();\n if (this.phase === \"seed\")\n return void this.seedSearch();\n if (this.phase === \"search\")\n return this.searchBatch(), void (this.solved || (this.progress = Math.min(0.99, this.stats.nodesPopped / (this.input.maxNodes ?? 30000))));\n const e35 = this.cursor;\n if (this.phase === \"obstacles\") {\n const t2 = this.input.srj.obstacles;\n for (;this.cursor \u003c Math.min(e35 + 128, t2.length); this.cursor++)\n this.prepareObstacle(t2[this.cursor]);\n return void (this.cursor === t2.length \u0026\u0026 (this.phase = \"routes\", this.cursor = 0));\n }\n if (this.phase !== \"routes\") {\n if (this.phase === \"traces\") {\n const t2 = this.input.srj.traces ?? [];\n for (;this.cursor \u003c Math.min(e35 + 32, t2.length); this.cursor++)\n this.prepareTrace(t2[this.cursor]);\n return void (this.cursor === t2.length \u0026\u0026 (this.phase = \"index\", this.cursor = 0));\n }\n if (this.phase !== \"index\")\n throw new Error(\"repair04: clearance path stepped after completion\");\n for (;this.cursor \u003c Math.min(e35 + 128, this.barrierCount); this.cursor++)\n this.indexBarrier(this.cursor);\n this.cursor === this.barrierCount \u0026\u0026 (this.phase = \"seed\");\n } else {\n for (;this.cursor \u003c Math.min(e35 + 32, this.input.routes.length); this.cursor++)\n this.prepareRoute(this.input.routes[this.cursor]);\n this.cursor === this.input.routes.length \u0026\u0026 (this.phase = \"traces\", this.cursor = 0);\n }\n }\n initialize() {\n const e35 = this.input, { srj: t2, routes: n2, routeIndex: o3, start: i3, end: r3, bounds: s2, traceThickness: a3 } = e35, c3 = e35.heuristicWeight ?? 1;\n if (!Number.isFinite(c3) || c3 \u003c 1)\n throw new Error(\"repair04: heuristic weight must be finite and at least one\");\n const l3 = (t3, n3) =\u003e {\n const o4 = e35.getAdditionalEdgeCost?.(t3, n3) ?? 0;\n if (Number.isNaN(o4) || o4 \u003c 0)\n throw new Error(\"repair04: additional edge costs must be nonnegative\");\n return o4;\n };\n if (e35.maxNodes !== undefined \u0026\u0026 (!Number.isSafeInteger(e35.maxNodes) || e35.maxNodes \u003c 1))\n throw new Error(\"repair04: maxNodes must be a positive safe integer\");\n if (this.stats \u0026\u0026 (this.stats.nodesPopped = 0, this.stats.completionReason = \"no-path\"), e35.allowLayerChanges === false \u0026\u0026 i3.z !== r3.z)\n return void this.finish(null);\n const h2 = n2[o3], d2 = e35.viaHoleDiameter ?? h2.viaDiameter;\n if (!Number.isFinite(d2) || d2 \u003c= 0 || d2 \u003e h2.viaDiameter)\n throw new Error(\"repair04: via hole diameter must be positive and fit the copper\");\n const u2 = d2 + e35.viaClearance, p3 = (e36, t3) =\u003e {\n for (let n3 = t3;n3; n3 = n3.previous)\n if ((e36.x !== n3.x || e36.y !== n3.y) \u0026\u0026 Math.hypot(e36.x - n3.x, e36.y - n3.y) + Aa \u003c u2)\n return false;\n return true;\n }, m2 = (e36) =\u003e {\n let t3;\n for (let n3 = 1;n3 \u003c e36.length; n3++) {\n const o4 = e36[n3 - 1], i4 = e36[n3];\n if (o4.z !== i4.z \u0026\u0026 o4.toNextSegmentType !== \"through_obstacle\") {\n if (!p3(o4, t3))\n return false;\n o4.x === t3?.x \u0026\u0026 o4.y === t3?.y || (t3 = { x: o4.x, y: o4.y, previous: t3 });\n }\n }\n return true;\n }, g2 = (this.connectivity ?? new Ay(t2)).createNetResolver(n2), f2 = g2(h2.connectionName), _2 = (e36) =\u003e e36 === \"top\" ? 0 : e36 === \"bottom\" ? t2.layerCount - 1 : Number(e36.slice(5)), y2 = [s2.minX, s2.maxX, s2.minY, s2.maxY, i3.x, i3.y, r3.x, r3.y, a3, h2.viaDiameter, e35.traceClearance, e35.viaClearance, t2.defaultObstacleMargin ?? 0, t2.minTraceToPadEdgeClearance ?? 0, t2.minTraceToHoleEdgeClearance ?? 0, t2.minViaEdgeToPadEdgeClearance ?? 0].every((e36) =\u003e Number.isFinite(e36) \u0026\u0026 Math.abs(e36) \u003c= 1e4), b2 = [], x2 = (e36, n3, o4, i4, r4 = false, s3 = false, a4 = false) =\u003e {\n const c4 = i4 ? Math.hypot(i4.width, i4.height) / 2 : o4, l4 = i4 ? Math.cos(i4.rotation) : 1, h3 = i4 ? Math.sin(i4.rotation) : 0, d3 = { minX: Math.min(e36.x, n3.x) - c4, maxX: Math.max(e36.x, n3.x) + c4, minY: Math.min(e36.y, n3.y) - c4, maxY: Math.max(e36.y, n3.y) + c4 }, u3 = i4 \u0026\u0026 y2 ? ((e37, t3, n4, o5, i5, r5) =\u003e {\n if (e37.x !== t3.x || e37.y !== t3.y || !Number.isFinite(n4.rotation) || n4.width \u003c= 0 || n4.height \u003c= 0 || ![e37.x, e37.y, n4.width, n4.height, r5.minX, r5.maxX, r5.minY, r5.maxY].every((e38) =\u003e Number.isFinite(e38) \u0026\u0026 Math.abs(e38) \u003c= 1e4))\n return r5;\n const s4 = o5 * o5 + i5 * i5;\n if (!Number.isFinite(s4) || Math.abs(s4 - 1) \u003e 0.000000000001)\n return r5;\n const a5 = n4.width / 2, c5 = n4.height / 2, l5 = (Math.abs(o5) * a5 + Math.abs(i5) * c5) / s4 + 0.00000001, h4 = (Math.abs(i5) * a5 + Math.abs(o5) * c5) / s4 + 0.00000001, d4 = { minX: e37.x - l5, maxX: e37.x + l5, minY: e37.y - h4, maxY: e37.y + h4 };\n return d4.minX \u003c r5.minX || d4.maxX \u003e r5.maxX || d4.minY \u003c r5.minY || d4.maxY \u003e r5.maxY ? r5 : d4;\n })(e36, n3, i4, l4, h3, d3) : d3;\n b2.push({ a: e36, b: n3, radius: o4, rect: i4, viaOnly: r4, pad: s3, isNonPlatedHole: a4, rectCos: l4, rectSin: h3, rectBounds: i4 ? { minX: -i4.width / 2, maxX: i4.width / 2, minY: -i4.height / 2, maxY: i4.height / 2 } : undefined, visitedQuery: 0, ...u3, ...Na(t2, e36, n3) });\n };\n this.prepareObstacle = (e36) =\u003e {\n const t3 = e36.connectedTo.some((e37) =\u003e g2(e37) === f2), n3 = e36.__zLayers ?? e36.zLayers ?? e36.layers.map(_2), o4 = e36.isNonPlatedHole \u0026\u0026 e36.shape === \"circle\" || e36.type === \"oval\" \u0026\u0026 e36.width === e36.height \u0026\u0026 e36.ccwRotationDegrees === undefined \u0026\u0026 n3.length \u003e 1;\n for (const i4 of n3) {\n const n4 = { ...e36.center, z: i4 };\n x2(n4, n4, o4 ? e36.width / 2 : 0, o4 ? undefined : { width: e36.width, height: e36.height, rotation: (e36.ccwRotationDegrees ?? 0) * Math.PI / 180 }, t3, o4, e36.isNonPlatedHole);\n }\n this.barrierCount = b2.length;\n }, this.prepareRoute = (e36) =\u003e {\n if (g2(e36.connectionName) !== f2) {\n for (let t3 = 1;t3 \u003c e36.route.length; t3++) {\n const n3 = e36.route[t3 - 1], o4 = e36.route[t3];\n n3.toNextSegmentType !== \"through_obstacle\" \u0026\u0026 x2(n3, o4, n3.z !== o4.z ? e36.viaDiameter / 2 : Math.max(n3.traceThickness ?? e36.traceThickness, o4.traceThickness ?? e36.traceThickness) / 2);\n }\n this.barrierCount = b2.length;\n }\n }, this.prepareTrace = (e36) =\u003e {\n if (g2(e36.connection_name) === f2)\n return;\n const n3 = Ta(e36, t2.minTraceWidth);\n for (let e37 = 1;e37 \u003c n3.route.length; e37++) {\n const t3 = n3.route[e37 - 1], o4 = n3.route[e37];\n t3.route_type === \"wire\" \u0026\u0026 o4.route_type === \"wire\" \u0026\u0026 t3.layer === o4.layer \u0026\u0026 x2({ x: t3.x, y: t3.y, z: _2(t3.layer) }, { x: o4.x, y: o4.y, z: _2(o4.layer) }, Math.max(t3.width, o4.width) / 2), o4.route_type === \"via\" \u0026\u0026 x2({ x: o4.x, y: o4.y, z: _2(o4.from_layer) }, { x: o4.x, y: o4.y, z: _2(o4.to_layer) }, (o4.via_diameter ?? h2.viaDiameter) / 2);\n }\n this.barrierCount = b2.length;\n };\n const v2 = new Map, I2 = Math.max(h2.viaDiameter, a3) / 2 + Math.max(e35.traceClearance, e35.viaClearance, t2.defaultObstacleMargin ?? 0, t2.minTraceToPadEdgeClearance ?? 0, t2.minTraceToHoleEdgeClearance ?? 0, t2.minViaEdgeToPadEdgeClearance ?? 0) + 0.00001;\n this.indexBarrier = (e36) =\u003e {\n const t3 = b2[e36];\n for (let e37 = Math.floor(Math.max(t3.minX, s2.minX - I2));e37 \u003c= Math.floor(Math.min(t3.maxX, s2.maxX + I2)); e37++) {\n let n3 = v2.get(e37);\n for (let o4 = Math.floor(Math.max(t3.minY, s2.minY - I2));o4 \u003c= Math.floor(Math.min(t3.maxY, s2.maxY + I2)); o4++) {\n n3 || (n3 = new Map, v2.set(e37, n3));\n const i4 = n3.get(o4);\n i4 ? i4.push(t3) : n3.set(o4, [t3]);\n }\n }\n };\n let S2 = 0;\n const C = { x: 0, y: 0 }, P = { x: 0, y: 0 }, M = (n3, o4) =\u003e {\n const i4 = n3.z !== o4.z, r4 = i4 ? h2.viaDiameter / 2 : a3 / 2, s3 = Math.max(i4 ? e35.viaClearance : e35.traceClearance, t2.defaultObstacleMargin ?? 0, i4 ? t2.minViaEdgeToPadEdgeClearance ?? 0 : t2.minTraceToPadEdgeClearance ?? 0), c4 = r4 + Math.max(s3, t2.minTraceToHoleEdgeClearance ?? 0) + 0.00001, l4 = ++S2, d3 = Math.min(n3.x, o4.x), u3 = Math.max(n3.x, o4.x), p4 = Math.min(n3.y, o4.y), m3 = Math.max(n3.y, o4.y), { minZ: g3, maxZ: f3 } = Na(t2, n3, o4);\n for (let a4 = Math.floor(d3 - c4);a4 \u003c= Math.floor(u3 + c4); a4++) {\n const h3 = v2.get(a4);\n if (h3)\n for (let a5 = Math.floor(p4 - c4);a5 \u003c= Math.floor(m3 + c4); a5++) {\n const c5 = h3.get(a5);\n if (c5)\n for (const a6 of c5) {\n if (a6.viaOnly \u0026\u0026 !i4)\n continue;\n if (a6.visitedQuery === l4)\n continue;\n if (a6.visitedQuery = l4, a6.maxZ \u003c g3 || a6.minZ \u003e f3)\n continue;\n const c6 = r4 + (a6.isNonPlatedHole \u0026\u0026 !i4 \u0026\u0026 t2.minTraceToHoleEdgeClearance !== undefined ? t2.minTraceToHoleEdgeClearance : a6.viaOnly ? Ea(t2, e35.viaClearance, true) : a6.rect || a6.pad ? s3 : i4 \u0026\u0026 a6.minZ !== a6.maxZ ? e35.viaClearance : e35.traceClearance);\n if (u3 + c6 \u003c a6.minX || d3 - c6 \u003e a6.maxX || m3 + c6 \u003c a6.minY || p4 - c6 \u003e a6.maxY)\n continue;\n let h4;\n if (a6.rect ? (C.x = (n3.x - a6.a.x) * a6.rectCos + (n3.y - a6.a.y) * a6.rectSin, C.y = -(n3.x - a6.a.x) * a6.rectSin + (n3.y - a6.a.y) * a6.rectCos, P.x = (o4.x - a6.a.x) * a6.rectCos + (o4.y - a6.a.y) * a6.rectSin, P.y = -(o4.x - a6.a.x) * a6.rectSin + (o4.y - a6.a.y) * a6.rectCos, h4 = Ne(C, P, a6.rectBounds)) : h4 = Ly(n3, o4, a6.a, a6.b) - a6.radius, h4 + Aa \u003c c6)\n return false;\n }\n }\n }\n return true;\n };\n this.seedSearch = () =\u003e {\n if (!M(i3, i3) || !M(r3, r3))\n return void this.finish(null);\n if (e35.existingPath) {\n const t3 = e35.existingPath, n4 = t3[0], o5 = t3.at(-1);\n if (!n4 || !o5 || n4.x !== i3.x || n4.y !== i3.y || n4.z !== i3.z || o5.x !== r3.x || o5.y !== r3.y || o5.z !== r3.z)\n throw new Error(\"repair04: existing clearance path must match its anchors\");\n if (t3.some((e36, n5) =\u003e {\n const o6 = t3[n5 - 1];\n return Boolean(o6 \u0026\u0026 o6.z !== e36.z \u0026\u0026 (o6.x !== e36.x || o6.y !== e36.y));\n }))\n throw new Error(\"repair04: existing clearance path has a non-colocated layer transition\");\n if (m2(t3) \u0026\u0026 (e35.allowLayerChanges !== false || t3.every((e36) =\u003e e36.z === i3.z)) \u0026\u0026 t3.slice(1).every((e36, n5) =\u003e M(t3[n5], e36) \u0026\u0026 l3(t3[n5], e36) === 0))\n return this.stats \u0026\u0026 (this.stats.completionReason = \"found\"), void this.finish(t3.map((e36) =\u003e ({ ...e36 })));\n }\n const n3 = e35.gridSize ?? 0.1;\n if (!Number.isFinite(n3) || n3 \u003c= 0)\n throw new Error(\"repair04: clearance grid size must be positive and finite\");\n const o4 = Math.floor((s2.maxX - s2.minX) / n3), h3 = Math.floor((s2.maxY - s2.minY) / n3), d3 = (e36) =\u003e ({ x: s2.minX + (e36 % o4 + 0.5) * n3, y: s2.minY + (Math.floor(e36 / o4) % h3 + 0.5) * n3, z: Math.floor(e36 / (o4 * h3)), traceThickness: a3 }), u3 = (e36, t3, n4) =\u003e (n4 * h3 + t3) * o4 + e36, g3 = (e36) =\u003e Math.hypot(e36.x - r3.x, e36.y - r3.y) + (e36.z === r3.z ? 0 : 1), f3 = o4 * h3 * t2.layerCount, _3 = o4 \u003e 0 \u0026\u0026 h3 \u003e 0 \u0026\u0026 Number.isSafeInteger(t2.layerCount) \u0026\u0026 Number.isSafeInteger(f3) \u0026\u0026 f3 \u003e 0 \u0026\u0026 f3 \u003c= 1e6 \u0026\u0026 Number.isInteger(i3.z) \u0026\u0026 i3.z \u003e= 0 \u0026\u0026 i3.z \u003c t2.layerCount, y3 = new Ra(_3 ? f3 : undefined), b3 = _3 ? new Float64Array(f3).fill(1 / 0) : undefined, x3 = _3 ? new Int32Array(f3) : undefined, v3 = new Map, I3 = new Map, S3 = new Map, C2 = (N = i3, u3(Math.max(0, Math.min(o4 - 1, Math.floor((N.x - s2.minX) / n3))), Math.max(0, Math.min(h3 - 1, Math.floor((N.y - s2.minY) / n3))), N.z)), P2 = C2 % o4, w = Math.floor(C2 / o4) % h3;\n var N;\n for (let e36 = -2;e36 \u003c= 2; e36++)\n for (let t3 = -2;t3 \u003c= 2; t3++) {\n const n4 = P2 + e36, r4 = w + t3;\n if (n4 \u003c 0 || n4 \u003e= o4 || r4 \u003c 0 || r4 \u003e= h3)\n continue;\n const s3 = u3(n4, r4, i3.z), a4 = d3(s3);\n if (!M(i3, a4))\n continue;\n const p4 = Math.hypot(a4.x - i3.x, a4.y - i3.y) + l3(i3, a4);\n Number.isFinite(p4) \u0026\u0026 (b3 ? b3[s3] = p4 : v3.set(s3, p4), x3 ? x3[s3] = -1 : I3.set(s3, -1), y3.pushValues(s3, p4, p4 + c3 * g3(a4)));\n }\n const R2 = o4 * h3 * t2.layerCount, T2 = o4 \u003e 0 \u0026\u0026 h3 \u003e 0 \u0026\u0026 Number.isSafeInteger(t2.layerCount) \u0026\u0026 Number.isSafeInteger(R2) \u0026\u0026 R2 \u003e 0 \u0026\u0026 Number.isSafeInteger(R2 * R2 - 1) \u0026\u0026 Number.isInteger(i3.z) \u0026\u0026 i3.z \u003e= 0 \u0026\u0026 i3.z \u003c t2.layerCount, E3 = _3 \u0026\u0026 c3 \u003e 1 ? new Uint8Array(f3) : undefined, A2 = !_3 \u0026\u0026 c3 \u003e 1 ? new Set : undefined, O2 = new Map, k2 = _3 \u0026\u0026 o4 \u003e= 3 ? new Uint8Array(f3) : undefined, D2 = new Map, L2 = _3 ? new Uint8Array(o4 * h3) : undefined;\n let z2 = 0;\n this.searchBatch = () =\u003e {\n const s3 = Math.min(z2 + 128, e35.maxNodes ?? 30000);\n for (;y3.length \u0026\u0026 z2 \u003c s3; ) {\n const s4 = y3.pop();\n if (z2++, this.stats \u0026\u0026 (this.stats.nodesPopped = z2), s4.cost !== (b3 ? b3[s4.id] : v3.get(s4.id)))\n continue;\n E3 ? E3[s4.id] = 1 : A2?.add(s4.id);\n const a4 = d3(s4.id), f4 = S3.get(s4.id);\n if (a4.z === r3.z \u0026\u0026 Math.hypot(a4.x - r3.x, a4.y - r3.y) \u003c 3 * n3 \u0026\u0026 M(a4, r3) \u0026\u0026 Number.isFinite(l3(a4, r3))) {\n const t3 = [r3];\n for (let e36 = s4.id;e36 !== -1; e36 = x3 ? x3[e36] : I3.get(e36))\n t3.push(d3(e36));\n t3.push(i3);\n const n4 = t3.reverse(), o5 = [i3], a5 = [0];\n for (let t4 = 1;e35.getAdditionalEdgeCost \u0026\u0026 t4 \u003c n4.length; t4++) {\n const e36 = n4[t4 - 1], o6 = n4[t4];\n a5.push(a5[t4 - 1] + (e36.z === o6.z ? Math.hypot(e36.x - o6.x, e36.y - o6.y) : 1) + l3(e36, o6));\n }\n let c4 = 0;\n for (let t4 = 1;t4 \u003c n4.length; ) {\n let i4 = t4;\n if (n4[t4].z === o5.at(-1).z)\n for (let r4 = t4 + 1;r4 \u003c n4.length \u0026\u0026 n4[r4].z === n4[t4].z; r4++)\n M(o5.at(-1), n4[r4]) \u0026\u0026 (!e35.getAdditionalEdgeCost || Math.hypot(n4[r4].x - n4[c4].x, n4[r4].y - n4[c4].y) + l3(n4[c4], n4[r4]) \u003c= a5[r4] - a5[c4] + Aa) \u0026\u0026 (i4 = r4);\n o5.push(n4[i4]), c4 = i4, t4 = i4 + 1;\n }\n if (!m2(o5))\n throw new Error(\"repair04: search generated conflicting drill sites\");\n return this.stats \u0026\u0026 (this.stats.completionReason = \"found\"), void this.finish(o5);\n }\n const _4 = s4.id % o4, C3 = Math.floor(s4.id / o4) % h3, P3 = [];\n for (let e36 = -1;e36 \u003c= 1; e36++)\n for (let t3 = -1;t3 \u003c= 1; t3++)\n e36 === 0 \u0026\u0026 t3 === 0 || _4 + e36 \u003c 0 || _4 + e36 \u003e= o4 || C3 + t3 \u003c 0 || C3 + t3 \u003e= h3 || P3.push(u3(_4 + e36, C3 + t3, a4.z));\n if (e35.allowLayerChanges !== false \u0026\u0026 p3(a4, f4))\n for (let e36 = 0;e36 \u003c t2.layerCount; e36++)\n e36 !== a4.z \u0026\u0026 P3.push(u3(_4, C3, e36));\n for (const e36 of P3) {\n if (E3 ? E3[e36] === 1 : A2?.has(e36))\n continue;\n const n4 = d3(e36), i4 = s4.cost + (a4.z === n4.z ? Math.hypot(a4.x - n4.x, a4.y - n4.y) : 1), r4 = b3 ? b3[e36] : v3.get(e36) ?? 1 / 0;\n if (i4 \u003e= r4)\n continue;\n const u4 = Math.min(s4.id, e36), p4 = Math.max(s4.id, e36), m3 = T2 \u0026\u0026 a4.z !== n4.z \u0026\u0026 t2.allowBlindAndBuriedVias !== true ? s4.id % (o4 * h3) : undefined;\n let _5;\n if (k2 \u0026\u0026 a4.z === n4.z) {\n const e37 = p4 - u4, t3 = e37 === 1 ? 0 : e37 === o4 - 1 ? 2 : e37 === o4 ? 4 : 6, i5 = k2[u4] \u003e\u003e t3 \u0026 3;\n i5 === 0 ? (_5 = M(a4, n4), k2[u4] = k2[u4] | (_5 ? 2 : 1) \u003c\u003c t3) : _5 = i5 === 2;\n } else if (L2 \u0026\u0026 m3 !== undefined) {\n const e37 = L2[m3];\n e37 === 0 ? (_5 = M(a4, n4), L2[m3] = _5 ? 2 : 1) : _5 = e37 === 2;\n } else {\n const e37 = T2 ? u4 * R2 + p4 : `${u4},${p4}`;\n _5 = m3 === undefined ? O2.get(e37) : D2.get(m3), _5 === undefined \u0026\u0026 (_5 = M(a4, n4), m3 === undefined ? O2.set(e37, _5) : D2.set(m3, _5));\n }\n if (!_5)\n continue;\n const C4 = i4 + l3(a4, n4);\n C4 \u003e= r4 || (a4.z === n4.z || a4.x === f4?.x \u0026\u0026 a4.y === f4?.y ? f4 ? S3.set(e36, f4) : S3.delete(e36) : S3.set(e36, { x: a4.x, y: a4.y, previous: f4 }), b3 ? b3[e36] = C4 : v3.set(e36, C4), x3 ? x3[e36] = s4.id : I3.set(e36, s4.id), y3.pushValues(e36, C4, C4 + c3 * g3(n4)));\n }\n }\n y3.length \u0026\u0026 z2 \u003c (e35.maxNodes ?? 30000) || (this.stats.completionReason = y3.length ? \"node-limit\" : \"no-path\", this.finish(null));\n }, this.phase = \"search\";\n }, this.phase = \"obstacles\";\n }\n getOutput() {\n if (!this.solved || this.failed || this.output === undefined)\n throw new Error(\"repair04: clearance path output requested before completion\");\n return this.output;\n }\n isSearchPrepared() {\n return this.phase === \"search\";\n }\n getResult() {\n return this.getOutput();\n }\n};\nfunction Fy(e35) {\n let t2;\n return { ...e35.pathInput, stats: { nodesPopped: 0, completionReason: \"no-path\" }, getAdditionalEdgeCost: (n2, o3) =\u003e (t2 ??= function(e36) {\n const { pathInput: t3, coppers: n3, selectedOwner: o4, weights: i3 } = e36, r3 = t3.routes[t3.routeIndex], s2 = (e37) =\u003e {\n if (!e37.length)\n return;\n const t4 = new uy(e37.length);\n for (const n4 of e37)\n t4.add(n4.minX - n4.radius - Aa, n4.minY - n4.radius - Aa, n4.maxX + n4.radius + Aa, n4.maxY + n4.radius + Aa);\n return t4.finish(), { index: t4, copper: e37, cellCandidates: new Map, queryStamps: new Uint32Array(e37.length) };\n }, a3 = s2(n3), c3 = new Map;\n for (let e37 = 0;e37 \u003c t3.srj.layerCount; e37++)\n c3.set(e37, s2(n3.filter((t4) =\u003e t4.minZ \u003c= e37 \u0026\u0026 t4.maxZ \u003e= e37)));\n const l3 = [];\n let h2 = 0;\n const d2 = (e37, n4) =\u003e {\n const i4 = e37.z !== n4.z, s3 = Math.min(e37.x, n4.x), d3 = Math.max(e37.x, n4.x), u3 = Math.min(e37.y, n4.y), p4 = Math.max(e37.y, n4.y), m2 = (i4 ? r3.viaDiameter : r3.traceThickness) / 2 + Math.max(t3.traceClearance, t3.viaClearance), g2 = [], f2 = Na(t3.srj, e37, n4), _2 = i4 ? a3 : c3.get(e37.z), y2 = s3 - m2 - Aa, b2 = u3 - m2 - Aa, x2 = d3 + m2 + Aa, v2 = p4 + m2 + Aa, I2 = Math.floor(y2), S2 = Math.floor(x2), C = Math.floor(b2), P = Math.floor(v2);\n if (h2 === 4294967295) {\n a3?.queryStamps.fill(0);\n for (const e38 of c3.values())\n e38?.queryStamps.fill(0);\n h2 = 0;\n }\n const M = ++h2;\n let w;\n if (_2 \u0026\u0026 (S2 - I2 + 1) * (P - C + 1) \u003c= 16 \u0026\u0026 Number.isSafeInteger(I2) \u0026\u0026 Number.isSafeInteger(S2) \u0026\u0026 Number.isSafeInteger(C) \u0026\u0026 Number.isSafeInteger(P)) {\n l3.length = 0;\n for (let e38 = I2;e38 \u003c= S2; e38++) {\n let t4 = _2.cellCandidates.get(e38);\n t4 || (t4 = new Map, _2.cellCandidates.set(e38, t4));\n for (let n5 = C;n5 \u003c= P; n5++) {\n let o5 = t4.get(n5);\n o5 || (o5 = _2.index.search(e38, n5, e38 + 1, n5 + 1), t4.set(n5, o5));\n for (const e39 of o5) {\n const t5 = _2.copper[e39];\n _2.queryStamps[e39] !== M \u0026\u0026 (_2.queryStamps[e39] = M, x2 \u003c t5.minX - t5.radius - Aa || v2 \u003c t5.minY - t5.radius - Aa || y2 \u003e t5.maxX + t5.radius + Aa || b2 \u003e t5.maxY + t5.radius + Aa || l3.push(e39));\n }\n }\n }\n w = l3;\n } else\n w = _2?.index.search(y2, b2, x2, v2) ?? [];\n for (const a4 of w) {\n const c4 = _2.copper[a4], l4 = i4 \u0026\u0026 c4.minZ !== c4.maxZ, h3 = c4.minZ \u003c= f2.maxZ \u0026\u0026 c4.maxZ \u003e= f2.minZ;\n if (!h3 \u0026\u0026 !l4)\n continue;\n if (c4.immutable \u0026\u0026 !l4)\n continue;\n if (c4.owner === o4 \u0026\u0026 (!l4 || e37.x === c4.a.x \u0026\u0026 e37.y === c4.a.y))\n continue;\n const m3 = (i4 ? r3.viaDiameter : r3.traceThickness) / 2 + (l4 ? t3.viaClearance : t3.traceClearance) + c4.radius, y3 = (t3.viaHoleDiameter ?? r3.viaDiameter) / 2 + (t3.viaHoleDiameter ?? 2 * c4.radius) / 2 + t3.viaClearance, b3 = l4 ? h3 \u0026\u0026 c4.owner !== o4 ? Math.max(m3, y3) : y3 : m3;\n if (s3 - b3 - Aa \u003e c4.maxX || d3 + b3 + Aa \u003c c4.minX || u3 - b3 - Aa \u003e c4.maxY || p4 + b3 + Aa \u003c c4.minY)\n continue;\n const x3 = Ly(e37, n4, c4.a, c4.b);\n x3 \u003c b3 - Aa \u0026\u0026 g2.push({ copper: c4, ratio: (b3 - x3) / (b3 * b3) });\n }\n const N = Math.floor(s3 - m2), R2 = Math.floor(u3 - m2);\n return g2.sort((e38, t4) =\u003e {\n const n5 = Math.max(N, e38.copper.cellX) - Math.max(N, t4.copper.cellX);\n return n5 !== 0 ? n5 : Math.max(R2, e38.copper.cellY) - Math.max(R2, t4.copper.cellY) || e38.copper.index - t4.copper.index;\n }), g2;\n }, u2 = (e37, n4) =\u003e {\n const r4 = (e37.x + n4.x) / 2, s3 = (e37.y + n4.y) / 2;\n if (r4 \u003c= t3.bounds.minX + 0.00000004 || r4 \u003e= t3.bounds.maxX - 0.00000004 || s3 \u003c= t3.bounds.minY + 0.00000004 || s3 \u003e= t3.bounds.maxY - 0.00000004)\n return 1 / 0;\n const a4 = new Map;\n for (const { copper: t4, ratio: r5 } of d2(e37, n4)) {\n if (t4.owner === o4 || t4.immutable)\n return 1 / 0;\n a4.set(t4.owner, Math.max(a4.get(t4.owner) ?? 0, r5 * i3[t4.spanIndex]));\n }\n let c4 = 0;\n for (const e38 of a4.values())\n c4 += e38;\n return (e37.z === n4.z ? Math.hypot(e37.x - n4.x, e37.y - n4.y) : 1) * c4;\n }, p3 = new Map;\n return { getAdditionalEdgeCost: (e37, n4) =\u003e {\n if (e37.z === n4.z || t3.srj.allowBlindAndBuriedVias === true || e37.x !== n4.x || e37.y !== n4.y)\n return u2(e37, n4);\n let o5 = p3.get(e37.x);\n const i4 = o5?.get(e37.y);\n if (i4 !== undefined)\n return i4;\n const r4 = u2(e37, n4);\n return o5 || (o5 = new Map, p3.set(e37.x, o5)), o5.set(e37.y, r4), r4;\n }, query: d2 };\n }(e35), t2.getAdditionalEdgeCost(n2, o3)) };\n}\nfunction jy(e35, t2) {\n return new zy(Fy(e35), t2);\n}\nvar $y = class extends BaseSolver {\n input;\n forward;\n reverse;\n stats = { nodesPopped: 0, completionReason: \"no-path\" };\n phase = \"prepare-forward\";\n output;\n laneErrors = [];\n originalErrors = [];\n constructor(e35) {\n if (super(), e35.reverseMaxNodes !== undefined \u0026\u0026 (!Number.isSafeInteger(e35.reverseMaxNodes) || e35.reverseMaxNodes \u003c 1))\n throw new Error(\"repair04: reverse node budget must be positive\");\n this.input = e35, this.forward = jy(e35.task, e35.connectivity), this.activeSubSolver = this.forward;\n const t2 = e35.task.pathInput.maxNodes ?? 30000, n2 = this.forward.MAX_ITERATIONS + Math.ceil((e35.reverseMaxNodes ?? t2) / 128) - Math.ceil(t2 / 128);\n this.MAX_ITERATIONS = this.forward.MAX_ITERATIONS + n2 + 8;\n }\n getLaneStats() {\n return [this.forward, ...this.reverse ? [this.reverse] : []].map((e35) =\u003e ({ ...e35.stats }));\n }\n getLastLaneErrors() {\n return this.laneErrors.map((e35) =\u003e e35 ? { ...e35 } : undefined);\n }\n stepLane(e35, t2) {\n try {\n e35.step();\n } catch (e36) {\n this.originalErrors[t2] = { error: e36 }, this.laneErrors[t2] = e36 instanceof Error ? { name: e36.name, message: e36.message } : { name: \"Error\", message: String(e36) };\n }\n }\n throwLaneError() {\n const e35 = this.originalErrors.find((e36) =\u003e e36 !== undefined);\n if (e35)\n throw e35.error;\n }\n updateStats() {\n this.stats.nodesPopped = this.forward.stats.nodesPopped + (this.reverse?.stats.nodesPopped ?? 0), this.solved || (this.progress = Math.min(0.99, this.stats.nodesPopped / ((this.input.task.pathInput.maxNodes ?? 30000) + (this.reverse ? this.input.reverseMaxNodes : 0))));\n }\n finish(e35, t2 = false) {\n this.output = t2 \u0026\u0026 e35 ? e35.slice().reverse() : e35, this.stats.completionReason = e35 ? \"found\" : this.getLaneStats().some((e36) =\u003e e36.completionReason === \"node-limit\") ? \"node-limit\" : \"no-path\", this.solved = true, this.progress = 1, this.activeSubSolver = null;\n }\n checkFailure() {\n const e35 = [this.forward, this.reverse].find((e36) =\u003e Boolean(e36?.failed));\n return !!e35 \u0026\u0026 (this.failed = true, this.error = e35.error, true);\n }\n _step() {\n if (this.laneErrors = [], this.originalErrors = [], this.phase === \"prepare-forward\") {\n if (this.stepLane(this.forward, 0), this.updateStats(), this.throwLaneError(), this.checkFailure())\n return;\n if (this.forward.solved)\n return void this.finish(this.forward.getOutput());\n if (!this.forward.isSearchPrepared())\n return;\n return this.input.reverseMaxNodes === undefined ? void (this.phase = \"search\") : void (this.phase = \"search-forward\");\n }\n if (this.phase === \"search-forward\") {\n if (this.stepLane(this.forward, 0), this.updateStats(), this.throwLaneError(), this.checkFailure())\n return;\n if (this.forward.solved)\n return void this.finish(this.forward.getOutput());\n if (this.forward.stats.nodesPopped \u003c 1024)\n return;\n const { task: e35 } = this.input;\n return this.reverse = jy({ ...e35, pathInput: { ...e35.pathInput, start: e35.pathInput.end, end: e35.pathInput.start, existingPath: e35.pathInput.existingPath?.slice().reverse(), maxNodes: this.input.reverseMaxNodes } }, this.input.connectivity), this.activeSubSolver = this.reverse, void (this.phase = \"prepare-reverse\");\n }\n if (this.phase === \"prepare-reverse\") {\n if (this.stepLane(this.reverse, 1), this.updateStats(), this.throwLaneError(), this.checkFailure())\n return;\n return this.reverse.solved \u0026\u0026 this.reverse.getOutput() ? void this.finish(this.reverse.getOutput(), true) : void ((this.reverse.solved || this.reverse.isSearchPrepared()) \u0026\u0026 (this.phase = \"search\", this.activeSubSolver = this.forward));\n }\n this.forward.solved || this.forward.failed || this.stepLane(this.forward, 0), !this.reverse || this.reverse.solved || this.reverse.failed || this.stepLane(this.reverse, 1), this.updateStats(), this.throwLaneError(), this.checkFailure() || (this.forward.solved \u0026\u0026 this.forward.getOutput() ? this.finish(this.forward.getOutput()) : this.reverse?.solved \u0026\u0026 this.reverse.getOutput() ? this.finish(this.reverse.getOutput(), true) : !this.forward.solved || this.reverse \u0026\u0026 !this.reverse.solved || this.finish(null));\n }\n getOutput() {\n if (!this.solved || this.failed || this.output === undefined)\n throw new Error(\"repair04: paired clearance output requested too early\");\n return this.output;\n }\n};\nfunction Yy({ route: e35, points: t2, mutableBounds: n2 }) {\n const o3 = { ...e35, route: t2 };\n return { ...o3, vias: Ey({ route: o3, mutableBounds: n2 }) };\n}\nvar Xy = class extends BaseSolver {\n input;\n phase = \"initialize\";\n routeCursor = 0;\n copperCursor = 0;\n spanCount = 0;\n output;\n pathSolver;\n prepareRoute;\n finishSetup;\n selectSpan;\n prepareCopper;\n startPath;\n applyPath;\n updateWorkStats;\n constructor(e35) {\n super(), this.input = e35, this.stats = { pathSearchNodes: 0, pathSearchCalls: 0, unresolvedSpanCount: 0 }, this.MAX_ITERATIONS = Math.ceil(e35.maxPathSearchNodes / 128) + e35.maxPathSearchCalls * (e35.routes.reduce((e36, t2) =\u003e e36 + t2.route.length, 0) + e35.srj.obstacles.length * e35.srj.layerCount + 128) + e35.routes.length + 32;\n }\n _step() {\n if (this.phase !== \"initialize\") {\n if (this.phase === \"spans\") {\n const e35 = Math.min(this.routeCursor + 32, this.input.routes.length);\n for (;this.routeCursor \u003c e35; this.routeCursor++)\n this.prepareRoute(this.routeCursor);\n return void (this.routeCursor === this.input.routes.length \u0026\u0026 (this.phase = \"setup\"));\n }\n if (this.phase !== \"setup\") {\n if (this.phase === \"select\")\n return this.selectSpan(), void this.updateWorkStats();\n if (this.phase === \"coppers\") {\n const e35 = Math.min(this.copperCursor + 32, this.spanCount);\n for (;this.copperCursor \u003c e35; this.copperCursor++)\n this.prepareCopper(this.copperCursor);\n return void (this.copperCursor === this.spanCount \u0026\u0026 (this.phase = \"start-path\"));\n }\n if (this.phase !== \"start-path\") {\n if (this.phase === \"path\") {\n const e35 = this.pathSolver;\n if (!e35)\n throw new Error(\"repair04: negotiated search child is missing\");\n return e35.step(), e35.failed ? (this.failed = true, this.error = e35.error) : e35.solved \u0026\u0026 (this.activeSubSolver = null, this.phase = \"apply-path\"), void this.updateWorkStats();\n }\n if (this.phase === \"apply-path\") {\n const e35 = this.pathSolver;\n if (!e35)\n throw new Error(\"repair04: completed negotiated search child is missing\");\n return this.applyPath(e35.getOutput()), this.applyPath = undefined, void this.updateWorkStats();\n }\n throw new Error(\"repair04: negotiated clearance stepped after completion\");\n }\n this.startPath();\n } else\n this.finishSetup();\n } else\n this.initialize();\n }\n initialize() {\n const e35 = this.input, t2 = new Ay(e35.srj);\n if (e35.searchDirectionCount !== undefined \u0026\u0026 e35.searchDirectionCount !== 1 \u0026\u0026 e35.searchDirectionCount !== 2)\n throw new Error(\"repair04: search direction count must be one or two\");\n for (const t3 of [e35.maxPathSearchNodes, e35.maxPathSearchCalls])\n if (!Number.isSafeInteger(t3) || t3 \u003c 0)\n throw new Error(\"repair04: negotiated work budgets must be nonnegative integers\");\n if (e35.maxPathSearchNodesPerCall !== undefined \u0026\u0026 (!Number.isSafeInteger(e35.maxPathSearchNodesPerCall) || e35.maxPathSearchNodesPerCall \u003c 1))\n throw new Error(\"repair04: per-path work budget must be a positive integer\");\n if (e35.pathHeuristicWeight !== undefined \u0026\u0026 (!Number.isFinite(e35.pathHeuristicWeight) || e35.pathHeuristicWeight \u003c 1))\n throw new Error(\"repair04: heuristic weight must be finite and at least one\");\n if (e35.pathGridSizeScale !== undefined \u0026\u0026 (!Number.isFinite(e35.pathGridSizeScale) || e35.pathGridSizeScale \u003c= 0))\n throw new Error(\"repair04: path grid scale must be positive and finite\");\n if (e35.viaHoleDiameter !== undefined \u0026\u0026 (!Number.isFinite(e35.viaHoleDiameter) || e35.viaHoleDiameter \u003c= 0 || e35.routes.some((t3) =\u003e e35.viaHoleDiameter \u003e t3.viaDiameter)))\n throw new Error(\"repair04: via hole diameter must be positive and fit the copper\");\n const n2 = (t3) =\u003e t3.x \u003e= e35.bounds.minX - Aa \u0026\u0026 t3.x \u003c= e35.bounds.maxX + Aa \u0026\u0026 t3.y \u003e= e35.bounds.minY - Aa \u0026\u0026 t3.y \u003c= e35.bounds.maxY + Aa, o3 = [], i3 = e35.routes.map(() =\u003e []);\n this.prepareRoute = (t3) =\u003e {\n const r3 = e35.routes[t3], s2 = r3.route, a3 = s2.flatMap((n3, o4) =\u003e {\n const i4 = s2[o4 - 1], a4 = s2[o4 + 1], c3 = n3.traceThickness ?? r3.traceThickness, l3 = i4 \u0026\u0026 (i4.traceThickness ?? r3.traceThickness) !== c3 || a4 \u0026\u0026 (a4.traceThickness ?? r3.traceThickness) !== c3, h2 = i4 \u0026\u0026 i4.z !== n3.z \u0026\u0026 (!e35.allowLayerChanges || e35.isLocked(t3, o4) || e35.isLocked(t3, o4 - 1)) || a4 \u0026\u0026 a4.z !== n3.z \u0026\u0026 (!e35.allowLayerChanges || e35.isLocked(t3, o4) || e35.isLocked(t3, o4 + 1));\n return o4 === 0 || o4 === s2.length - 1 || e35.isLocked(t3, o4) || n3.pcb_port_id || n3.toNextSegmentType || n3.insideJumperPad || l3 || h2 ? [o4] : [];\n });\n for (let c3 = 1;c3 \u003c a3.length; c3++) {\n const l3 = s2.slice(a3[c3 - 1], a3[c3] + 1), h2 = l3[0].traceThickness ?? r3.traceThickness, d2 = l3.slice(1).every((t4, n3) =\u003e {\n const o4 = l3[n3], i4 = (o4.x + t4.x) / 2, r4 = (o4.y + t4.y) / 2;\n return i4 \u003e e35.bounds.minX + 0.00000004 \u0026\u0026 i4 \u003c e35.bounds.maxX - 0.00000004 \u0026\u0026 r4 \u003e e35.bounds.minY + 0.00000004 \u0026\u0026 r4 \u003c e35.bounds.maxY - 0.00000004;\n }), u2 = l3.slice(1).every((n3, o4) =\u003e {\n const i4 = l3[o4], r4 = a3[c3 - 1] + o4;\n return i4.z === n3.z || !e35.isLocked(t3, r4) \u0026\u0026 !e35.isLocked(t3, r4 + 1);\n }), p3 = l3.every(n2) \u0026\u0026 d2 \u0026\u0026 u2 \u0026\u0026 !r3.jumpers?.length \u0026\u0026 l3.every((e36) =\u003e !e36.toNextSegmentType \u0026\u0026 !e36.insideJumperPad \u0026\u0026 (e36.traceThickness ?? r3.traceThickness) === h2) \u0026\u0026 (e35.allowLayerChanges || l3.every((e36) =\u003e e36.z === l3[0].z));\n i3[t3].push(o3.length), o3.push({ routeIndex: t3, mutable: Boolean(p3), route: Yy({ route: { ...r3, traceThickness: h2 }, points: l3, mutableBounds: e35.bounds }) });\n }\n }, this.finishSetup = () =\u003e {\n const n3 = o3.map((e36) =\u003e e36.route), r3 = o3.filter((e36) =\u003e !e36.mutable).map((e36) =\u003e e36.route), s2 = iy(e35.srj, e35.routes), a3 = (e36) =\u003e s2.get(e36.connectionName) ?? e36.connectionName, c3 = new Set;\n for (const e36 of o3)\n for (const t3 of [e36.route.route[0], e36.route.route.at(-1)]) {\n const n4 = t3.traceThickness ?? e36.route.traceThickness, o4 = `${a3(e36.route)}|${t3.x}|${t3.y}|${t3.z}|${n4}`;\n if (c3.has(o4))\n continue;\n c3.add(o4);\n const i4 = { x: t3.x, y: t3.y, z: t3.z };\n r3.push({ ...e36.route, traceThickness: n4, route: [i4, i4], vias: [] });\n }\n const l3 = o3.map(({ route: e36 }) =\u003e {\n let t3 = 0;\n for (let n4 = 1;n4 \u003c e36.route.length; n4++) {\n const o4 = e36.route[n4 - 1], i4 = e36.route[n4];\n t3 += o4.z === i4.z ? Math.hypot(o4.x - i4.x, o4.y - i4.y) : 1;\n }\n return t3;\n }), h2 = new Set, d2 = new Set(e35.dirtyRouteIndices), u2 = [], p3 = new Set, m2 = (e36) =\u003e {\n p3.has(e36) || h2.has(e36) || !o3[e36].mutable || (p3.add(e36), u2.push(e36));\n };\n o3.forEach((e36, t3) =\u003e {\n d2.has(e36.routeIndex) \u0026\u0026 m2(t3);\n });\n let g2 = 0, f2 = 0, _2 = 0;\n this.spanCount = o3.length, this.updateWorkStats = () =\u003e {\n this.stats = { pathSearchNodes: g2 + (this.pathSolver?.stats.nodesPopped ?? 0), pathSearchCalls: f2, unresolvedSpanCount: p3.size + h2.size }, this.progress = this.solved ? 1 : Math.min(0.99, Math.max(this.stats.pathSearchNodes / Math.max(1, e35.maxPathSearchNodes), f2 / Math.max(1, e35.maxPathSearchCalls)));\n }, this.selectSpan = () =\u003e {\n if (!(_2 \u003c u2.length \u0026\u0026 g2 \u003c e35.maxPathSearchNodes \u0026\u0026 f2 \u003c e35.maxPathSearchCalls))\n return this.output = { routes: e35.routes.map((t3, o4) =\u003e {\n if (!i3[o4].length)\n return t3;\n return Yy({ route: t3, points: i3[o4].flatMap((e36, t4) =\u003e t4 === 0 ? n3[e36].route : n3[e36].route.slice(1)), mutableBounds: e35.bounds });\n }), pathSearchNodes: g2, pathSearchCalls: f2, unresolvedSpanCount: p3.size + h2.size }, this.solved = true, void (this.phase = \"finished\");\n const s3 = u2[_2++];\n p3.delete(s3);\n const c4 = n3[s3], d3 = a3(c4), y2 = [];\n this.copperCursor = 0, this.prepareCopper = (t3) =\u003e {\n if (t3 === s3)\n return;\n const i4 = n3[t3], r4 = a3(i4);\n for (let n4 = 1;n4 \u003c i4.route.length; n4++) {\n const s4 = i4.route[n4 - 1], a4 = i4.route[n4];\n if (s4.toNextSegmentType === \"through_obstacle\")\n continue;\n const c5 = !o3[t3].mutable || h2.has(t3);\n if (s4.z === a4.z \u0026\u0026 (r4 === d3 || c5))\n continue;\n const l4 = (s4.z !== a4.z ? i4.viaDiameter : Math.max(s4.traceThickness ?? i4.traceThickness, a4.traceThickness ?? i4.traceThickness)) / 2, u3 = { a: s4, b: a4, radius: l4, minX: Math.min(s4.x, a4.x), maxX: Math.max(s4.x, a4.x), minY: Math.min(s4.y, a4.y), maxY: Math.max(s4.y, a4.y), ...Na(e35.srj, s4, a4), spanIndex: t3, owner: r4, index: y2.length, cellX: Math.floor(Math.min(s4.x, a4.x) - l4), cellY: Math.floor(Math.min(s4.y, a4.y) - l4), immutable: c5, visitedQuery: 0 };\n y2.push(u3);\n }\n }, this.startPath = () =\u003e {\n const o4 = (e36) =\u003e {\n if (!e36.length)\n return;\n const t3 = new uy(e36.length);\n for (const n4 of e36)\n t3.add(n4.minX - n4.radius - Aa, n4.minY - n4.radius - Aa, n4.maxX + n4.radius + Aa, n4.maxY + n4.radius + Aa);\n return t3.finish(), { index: t3, copper: e36, cellCandidates: new Map };\n }, i4 = o4(y2), a4 = new Map;\n for (let t3 = 0;t3 \u003c e35.srj.layerCount; t3++)\n a4.set(t3, o4(y2.filter((e36) =\u003e e36.minZ \u003c= t3 \u0026\u0026 e36.maxZ \u003e= t3)));\n const u3 = [];\n let p4 = 0;\n const _3 = (t3, n4) =\u003e {\n const o5 = t3.z !== n4.z, r4 = Math.min(t3.x, n4.x), s4 = Math.max(t3.x, n4.x), l4 = Math.min(t3.y, n4.y), h3 = Math.max(t3.y, n4.y), m3 = (o5 ? c4.viaDiameter : c4.traceThickness) / 2 + Math.max(e35.traceClearance, e35.viaClearance), g3 = [], f3 = Na(e35.srj, t3, n4), _4 = o5 ? i4 : a4.get(t3.z), y3 = r4 - m3 - Aa, b3 = l4 - m3 - Aa, x3 = s4 + m3 + Aa, v3 = h3 + m3 + Aa, I3 = Math.floor(y3), S3 = Math.floor(x3), C2 = Math.floor(b3), P = Math.floor(v3), M = ++p4;\n let w;\n if (_4 \u0026\u0026 (S3 - I3 + 1) * (P - C2 + 1) \u003c= 16 \u0026\u0026 Number.isSafeInteger(I3) \u0026\u0026 Number.isSafeInteger(S3) \u0026\u0026 Number.isSafeInteger(C2) \u0026\u0026 Number.isSafeInteger(P)) {\n u3.length = 0;\n for (let e36 = I3;e36 \u003c= S3; e36++) {\n let t4 = _4.cellCandidates.get(e36);\n t4 || (t4 = new Map, _4.cellCandidates.set(e36, t4));\n for (let n5 = C2;n5 \u003c= P; n5++) {\n let o6 = t4.get(n5);\n o6 || (o6 = _4.index.search(e36, n5, e36 + 1, n5 + 1), t4.set(n5, o6));\n for (const e37 of o6) {\n const t5 = _4.copper[e37];\n t5.visitedQuery !== M \u0026\u0026 (t5.visitedQuery = M, x3 \u003c t5.minX - t5.radius - Aa || v3 \u003c t5.minY - t5.radius - Aa || y3 \u003e t5.maxX + t5.radius + Aa || b3 \u003e t5.maxY + t5.radius + Aa || u3.push(e37));\n }\n }\n }\n w = u3;\n } else\n w = _4?.index.search(y3, b3, x3, v3) ?? [];\n for (const i5 of w) {\n const a5 = _4.copper[i5], u4 = o5 \u0026\u0026 a5.minZ !== a5.maxZ, p5 = a5.minZ \u003c= f3.maxZ \u0026\u0026 a5.maxZ \u003e= f3.minZ;\n if (!p5 \u0026\u0026 !u4)\n continue;\n if (a5.immutable \u0026\u0026 !u4)\n continue;\n if (a5.owner === d3 \u0026\u0026 (!u4 || t3.x === a5.a.x \u0026\u0026 t3.y === a5.a.y))\n continue;\n const m4 = (o5 ? c4.viaDiameter : c4.traceThickness) / 2 + (u4 ? e35.viaClearance : e35.traceClearance) + a5.radius, y4 = (e35.viaHoleDiameter ?? c4.viaDiameter) / 2 + (e35.viaHoleDiameter ?? 2 * a5.radius) / 2 + e35.viaClearance, b4 = u4 ? p5 \u0026\u0026 a5.owner !== d3 ? Math.max(m4, y4) : y4 : m4;\n if (r4 - b4 - Aa \u003e a5.maxX || s4 + b4 + Aa \u003c a5.minX || l4 - b4 - Aa \u003e a5.maxY || h3 + b4 + Aa \u003c a5.minY)\n continue;\n const x4 = Ly(t3, n4, a5.a, a5.b);\n x4 \u003c b4 - Aa \u0026\u0026 g3.push({ copper: a5, ratio: (b4 - x4) / (b4 * b4) });\n }\n const N = Math.floor(r4 - m3), R2 = Math.floor(l4 - m3);\n return g3.sort((e36, t4) =\u003e {\n const n5 = Math.max(N, e36.copper.cellX) - Math.max(N, t4.copper.cellX);\n if (n5 !== 0)\n return n5;\n return Math.max(R2, e36.copper.cellY) - Math.max(R2, t4.copper.cellY) || e36.copper.index - t4.copper.index;\n }), g3;\n }, b2 = (t3, n4) =\u003e {\n const o5 = (t3.x + n4.x) / 2, i5 = (t3.y + n4.y) / 2;\n if (o5 \u003c= e35.bounds.minX + 0.00000004 || o5 \u003e= e35.bounds.maxX - 0.00000004 || i5 \u003c= e35.bounds.minY + 0.00000004 || i5 \u003e= e35.bounds.maxY - 0.00000004)\n return 1 / 0;\n const r4 = new Map;\n for (const { copper: e36, ratio: o6 } of _3(t3, n4)) {\n if (e36.owner === d3 || e36.immutable)\n return 1 / 0;\n r4.set(e36.owner, Math.max(r4.get(e36.owner) ?? 0, o6 * l3[e36.spanIndex]));\n }\n let s4 = 0;\n for (const e36 of r4.values())\n s4 += e36;\n return (t3.z === n4.z ? Math.hypot(t3.x - n4.x, t3.y - n4.y) : 1) * s4;\n }, x2 = new Map, v2 = { nodesPopped: 0, completionReason: \"no-path\" }, I2 = { srj: e35.srj, routes: [...r3, c4], routeIndex: r3.length, start: c4.route[0], end: c4.route.at(-1), bounds: e35.bounds, traceThickness: c4.traceThickness, traceClearance: e35.traceClearance, viaClearance: e35.viaClearance, gridSize: Math.min(0.1, c4.traceThickness * (e35.pathGridSizeScale ?? 1) / 2), allowLayerChanges: e35.allowLayerChanges, maxNodes: Math.min(e35.maxPathSearchNodesPerCall ?? e35.maxPathSearchNodes, e35.maxPathSearchNodes - g2), heuristicWeight: e35.pathHeuristicWeight, existingPath: c4.route, viaHoleDiameter: e35.viaHoleDiameter }, S2 = Math.min(e35.maxPathSearchNodesPerCall ?? e35.maxPathSearchNodes, e35.maxPathSearchNodes - g2 - I2.maxNodes), C = e35.searchDirectionCount === 2 ? new $y({ task: { pathInput: I2, coppers: y2, selectedOwner: d3, weights: l3 }, connectivity: t2, reverseMaxNodes: e35.maxPathSearchCalls - f2 \u003e= 2 \u0026\u0026 S2 \u003e 0 ? S2 : undefined }) : new zy({ ...I2, stats: v2, getAdditionalEdgeCost: (t3, n4) =\u003e {\n if (t3.z === n4.z || e35.srj.allowBlindAndBuriedVias === true || t3.x !== n4.x || t3.y !== n4.y)\n return b2(t3, n4);\n let o5 = x2.get(t3.x);\n const i5 = o5?.get(t3.y);\n if (i5 !== undefined)\n return i5;\n const r4 = b2(t3, n4);\n return o5 || (o5 = new Map, x2.set(t3.x, o5)), o5.set(t3.y, r4), r4;\n } }, t2);\n this.pathSolver = C, this.activeSubSolver = C, this.MAX_ITERATIONS = Math.max(this.MAX_ITERATIONS, this.iterations + C.MAX_ITERATIONS + 3), this.phase = \"path\", this.applyPath = (t3) =\u003e {\n const o5 = C instanceof $y ? C.getLaneStats() : [v2];\n f2 += o5.length;\n for (const t4 of o5)\n g2 += t4.nodesPopped, e35.onSearch?.(t4);\n if (!t3)\n return h2.add(s3), r3.push(c4), this.phase = \"select\", void (this.pathSolver = undefined);\n n3[s3] = Yy({ route: c4, points: t3, mutableBounds: e35.bounds });\n const i5 = new Set;\n for (let e36 = 1;e36 \u003c t3.length; e36++)\n for (const { copper: n4 } of _3(t3[e36 - 1], t3[e36]))\n i5.add(n4.spanIndex);\n for (const e36 of [...i5].sort((e37, t4) =\u003e e37 - t4))\n l3[e36]++, m2(e36);\n i5.size \u0026\u0026 (l3[s3]++, m2(s3)), this.phase = \"select\", this.pathSolver = undefined;\n };\n }, this.phase = \"coppers\";\n }, this.phase = \"select\", this.updateWorkStats();\n }, this.phase = \"spans\";\n }\n getOutput() {\n if (!this.solved || this.failed || !this.output)\n throw new Error(\"repair04: negotiated clearance output requested before completion\");\n return this.output;\n }\n getResult() {\n return this.getOutput();\n }\n};\nvar Vy = 256;\nvar Wy = 0.25;\nfunction Gy(e35, t2, n2, o3) {\n const i3 = t2.x - e35.x, r3 = t2.y - e35.y, s2 = o3.x - n2.x, a3 = o3.y - n2.y, c3 = e35.x - n2.x, l3 = e35.y - n2.y, h2 = i3 * i3 + r3 * r3, d2 = i3 * s2 + r3 * a3, u2 = s2 * s2 + a3 * a3, p3 = i3 * c3 + r3 * l3, m2 = s2 * c3 + a3 * l3, g2 = h2 * u2 - d2 * d2;\n let f2 = g2 \u003e 0.000000000000001 ? Math.max(0, Math.min(1, (d2 * m2 - u2 * p3) / g2)) : 0;\n u2 \u003c 0.000000000000001 \u0026\u0026 (f2 = h2 \u003e 0.000000000000001 ? Math.max(0, Math.min(1, -p3 / h2)) : 0);\n let _2 = u2 \u003e 0.000000000000001 ? (d2 * f2 + m2) / u2 : 0;\n _2 \u003c 0 ? (_2 = 0, f2 = h2 \u003e 0.000000000000001 ? Math.max(0, Math.min(1, -p3 / h2)) : 0) : _2 \u003e 1 \u0026\u0026 (_2 = 1, f2 = h2 \u003e 0.000000000000001 ? Math.max(0, Math.min(1, (d2 - p3) / h2)) : 0);\n const y2 = e35.x + f2 * i3 - n2.x - _2 * s2, b2 = e35.y + f2 * r3 - n2.y - _2 * a3;\n return { s: f2, t: _2, x: y2, y: b2, distance: Ry(y2, b2) };\n}\nfunction Uy(e35, t2) {\n let n2 = { x: 0, y: 0, depth: 1 / 0 };\n for (let o3 = 0;o3 \u003c t2.length; o3++) {\n const i3 = t2[o3], r3 = t2[(o3 + 1) % t2.length], s2 = r3.x - i3.x, a3 = r3.y - i3.y, c3 = Ry(s2, a3), l3 = a3 / c3, h2 = -s2 / c3, d2 = -((e35.x - i3.x) * l3 + (e35.y - i3.y) * h2);\n if (d2 \u003c 0)\n return null;\n d2 \u003c n2.depth \u0026\u0026 (n2 = { x: l3, y: h2, depth: d2 });\n }\n return n2;\n}\nvar Zy = class extends BaseSolver {\n input;\n phase = \"geometry\";\n routes = [];\n nets = new Map;\n vertices = new Map;\n segments = [];\n pairs = [];\n padContacts = [];\n viaPadConstraints = new Map;\n traceClearance = 0.1;\n viaClearance = 0.1;\n pairOuterIndex = 0;\n pairInnerIndex = 1;\n obstacleIndex = 0;\n sweepIndex = 0;\n sweepPairIndex = 0;\n sweepPadIndex = 0;\n preparedPairCount = 0;\n projectedConstraintCount = 0;\n constructor(e35) {\n super(), this.input = e35, this.MAX_ITERATIONS = 1024;\n }\n prepareGeometry() {\n const e35 = this.input, t2 = structuredClone(e35.routes), n2 = iy(e35.srj, t2), o3 = e35.traceClearance ?? 0.1, i3 = e35.viaClearance ?? 0.1, r3 = { minX: e35.bounds.minX + e35.boundaryMargin, maxX: e35.bounds.maxX - e35.boundaryMargin, minY: e35.bounds.minY + e35.boundaryMargin, maxY: e35.bounds.maxY - e35.boundaryMargin }, s2 = yy(e35.srj, t2, e35.bounds), a3 = new Map, c3 = t2.map((t3, o4) =\u003e t3.route.map((i4, c4) =\u003e {\n const l4 = `${n2.get(t3.connectionName)}:${i4.x}:${i4.y}`;\n let h3 = a3.get(l4);\n return h3 || (h3 = { x: i4.x, y: i4.y, original: { x: i4.x, y: i4.y }, locked: false, radius: 0, revision: 0, bounds: r3, points: [] }, a3.set(l4, h3)), h3.points.push(i4), h3.locked ||= Boolean(e35.lockedPointIndices[o4][c4] || s2[o4].segmentTimes.has(c4) || s2[o4].segmentTimes.has(c4 - 1) || s2[o4].viaPositions.some((e36) =\u003e Math.hypot(e36.x - i4.x, e36.y - i4.y) \u003c= Aa) || c4 === 0 || c4 === t3.route.length - 1 || i4.pcb_port_id || i4.insideJumperPad || i4.toNextSegmentType || i4.x \u003c= r3.minX || i4.x \u003e= r3.maxX || i4.y \u003c= r3.minY || i4.y \u003e= r3.maxY), h3;\n })), l3 = [];\n for (let o4 = 0;o4 \u003c t2.length; o4++) {\n const i4 = t2[o4];\n for (let t3 = 1;t3 \u003c i4.route.length; t3++) {\n const r4 = i4.route[t3 - 1], s3 = i4.route[t3];\n if (r4.toNextSegmentType || r4.insideJumperPad || s3.insideJumperPad)\n continue;\n const a4 = c3[o4][t3 - 1], h3 = c3[o4][t3], d3 = r4.z !== s3.z;\n d3 \u0026\u0026 e35.allowViaMovement !== true \u0026\u0026 (a4.locked = h3.locked = true), l3.push({ a: a4, b: h3, initialBounds: { minX: Math.min(a4.x, h3.x), maxX: Math.max(a4.x, h3.x), minY: Math.min(a4.y, h3.y), maxY: Math.max(a4.y, h3.y) }, ...Na(e35.srj, r4, s3), radius: d3 ? i4.viaDiameter / 2 : Math.max(r4.traceThickness ?? i4.traceThickness, s3.traceThickness ?? i4.traceThickness) / 2, net: n2.get(i4.connectionName), routeIndex: o4, via: d3 });\n }\n }\n for (const e36 of l3)\n e36.a.radius = Math.max(e36.a.radius, e36.radius), e36.b.radius = Math.max(e36.b.radius, e36.radius);\n if (e35.boardEdgeClearance !== undefined) {\n const t3 = e35.srj.bounds;\n for (const n3 of a3.values()) {\n const o4 = n3.radius + e35.boardEdgeClearance;\n n3.bounds = { minX: Math.max(r3.minX, Math.min(n3.original.x, t3.minX + o4)), maxX: Math.min(r3.maxX, Math.max(n3.original.x, t3.maxX - o4)), minY: Math.max(r3.minY, Math.min(n3.original.y, t3.minY + o4)), maxY: Math.min(r3.maxY, Math.max(n3.original.y, t3.maxY - o4)) };\n }\n }\n this.routes = t2, this.nets = n2, this.vertices = a3, this.segments = l3, this.traceClearance = o3, this.viaClearance = i3;\n const h2 = l3.length * (l3.length - 1) / 2, d2 = l3.length * e35.srj.obstacles.length;\n this.MAX_ITERATIONS = this.iterations + Math.ceil(h2 / 4096) + Math.ceil(e35.srj.obstacles.length / 16) + Vy * Math.max(1, Math.ceil((h2 + d2) / 4096)) + 4, this.phase = \"pairs\";\n }\n preparePairs() {\n let e35 = 0;\n for (;e35 \u003c 4096 \u0026\u0026 this.pairOuterIndex \u003c this.segments.length; ) {\n if (this.pairInnerIndex \u003e= this.segments.length) {\n this.pairOuterIndex++, this.pairInnerIndex = this.pairOuterIndex + 1;\n continue;\n }\n const t2 = this.segments[this.pairOuterIndex], n2 = this.segments[this.pairInnerIndex++];\n if (e35++, this.preparedPairCount++, t2.net === n2.net || t2.maxZ \u003c n2.minZ || n2.maxZ \u003c t2.minZ)\n continue;\n const o3 = t2.radius + n2.radius + Math.max(this.traceClearance, this.viaClearance) + 2 * Math.SQRT2 * Wy;\n Ty(t2.initialBounds, n2.initialBounds, o3) || Ly(t2.a, t2.b, n2.a, n2.b) \u003c= o3 \u0026\u0026 this.pairs.push({ a: t2, b: n2, revisions: [-1, -1, -1, -1], contact: null });\n }\n this.pairOuterIndex \u003e= this.segments.length \u0026\u0026 (this.phase = \"obstacles\"), this.stats = { ...this.stats, preparedPairCount: this.preparedPairCount, pairCount: this.pairs.length, lastPreparedPairBatchCount: e35 };\n }\n prepareObstacles() {\n const { input: e35, nets: t2, segments: n2, traceClearance: o3, viaClearance: i3, padContacts: r3, viaPadConstraints: s2 } = this;\n let a3 = 0;\n for (;a3 \u003c 16 \u0026\u0026 this.obstacleIndex \u003c e35.srj.obstacles.length; ) {\n const c3 = e35.srj.obstacles[this.obstacleIndex++];\n a3++;\n const l3 = (c3.ccwRotationDegrees ?? 0) * Math.PI / 180, h2 = Math.cos(l3), d2 = Math.sin(l3), u2 = new Set(c3.connectedTo.map((e36) =\u003e t2.get(e36) ?? e36)), p3 = c3.__zLayers ?? c3.zLayers ?? c3.layers.map((t3) =\u003e t3 === \"top\" ? 0 : t3 === \"bottom\" ? e35.srj.layerCount - 1 : Number(t3.slice(5))), m2 = [[-1, -1], [1, -1], [1, 1], [-1, 1]].map(([e36, t3]) =\u003e ({ x: c3.center.x + h2 * e36 * c3.width / 2 - d2 * t3 * c3.height / 2, y: c3.center.y + d2 * e36 * c3.width / 2 + h2 * t3 * c3.height / 2 })), g2 = { minX: Math.min(...m2.map((e36) =\u003e e36.x)), maxX: Math.max(...m2.map((e36) =\u003e e36.x)), minY: Math.min(...m2.map((e36) =\u003e e36.y)), maxY: Math.max(...m2.map((e36) =\u003e e36.y)) };\n for (const t3 of n2) {\n if (!t3.via \u0026\u0026 u2.has(t3.net) || !p3.some((e36) =\u003e e36 \u003e= t3.minZ \u0026\u0026 e36 \u003c= t3.maxZ))\n continue;\n const n3 = t3.radius + Math.max(o3, i3, e35.srj.defaultObstacleMargin ?? 0, e35.srj.minTraceToPadEdgeClearance ?? 0, e35.srj.minTraceToHoleEdgeClearance ?? 0, e35.srj.minViaEdgeToPadEdgeClearance ?? 0) + Math.SQRT2 * Wy;\n if (Ty(t3.initialBounds, g2, n3))\n continue;\n if (Math.min(...m2.map((e36, n4) =\u003e Ly(t3.a, t3.b, e36, m2[(n4 + 1) % 4]))) \u003e n3)\n continue;\n const a4 = t3.radius + (t3.via ? Ea(e35.srj, i3, u2.has(t3.net)) : c3.isNonPlatedHole \u0026\u0026 e35.srj.minTraceToHoleEdgeClearance !== undefined ? e35.srj.minTraceToHoleEdgeClearance : Math.max(o3, e35.srj.defaultObstacleMargin ?? 0, e35.srj.minTraceToPadEdgeClearance ?? 0));\n if (r3.push({ segment: t3, corners: m2, bounds: g2, required: a4, revisions: [-1, -1], projectionRevisions: [-1, -1], contact: null }), t3.via) {\n const e36 = { center: c3.center, cosine: h2, sine: d2, shape: ny(c3), clearance: a4 }, n4 = t3.a.original.x - c3.center.x, o4 = t3.a.original.y - c3.center.y, i4 = { x: n4 * h2 + o4 * d2, y: -n4 * d2 + o4 * h2 };\n e36.clearance = Math.min(e36.clearance, oy(i4, i4, e36.shape));\n for (const n5 of new Set([t3.a, t3.b])) {\n const t4 = s2.get(n5);\n t4 ? t4.push(e36) : s2.set(n5, [e36]);\n }\n }\n }\n }\n this.stats = { ...this.stats, preparedObstacleCount: this.obstacleIndex, padContactCount: this.padContacts.length, lastPreparedObstacleBatchCount: a3 }, this.obstacleIndex === e35.srj.obstacles.length \u0026\u0026 (this.MAX_ITERATIONS = this.iterations + Vy * Math.max(1, Math.ceil((this.pairs.length + this.padContacts.length) / 4096)) + 2, this.phase = \"sweeps\");\n }\n project(e35, t2, n2, o3, i3) {\n const r3 = this.viaPadConstraints, s2 = [], a3 = [];\n for (const [t3, n3] of e35) {\n if (t3.locked)\n continue;\n const e36 = s2.indexOf(t3);\n e36 === -1 ? (s2.push(t3), a3.push(0 + n3)) : a3[e36] = a3[e36] + n3;\n }\n let c3 = 0;\n for (const e36 of a3)\n c3 += e36 * e36;\n if (c3 \u003c 0.000000000000001)\n return;\n const l3 = Math.min(0.05, 0.7 * o3) / c3;\n for (let e36 = 0;e36 \u003c s2.length; e36++) {\n const o4 = s2[e36], c4 = a3[e36];\n let h2 = Math.max(o4.bounds.minX, o4.original.x - Wy, Math.min(o4.bounds.maxX, o4.original.x + Wy, o4.x + t2 * l3 * c4)), d2 = Math.max(o4.bounds.minY, o4.original.y - Wy, Math.min(o4.bounds.maxY, o4.original.y + Wy, o4.y + n2 * l3 * c4));\n const u2 = r3.get(o4);\n if (u2?.some((e37) =\u003e this.getViaPadDistance({ x: h2, y: d2 }, e37) \u003c e37.clearance)) {\n if (!i3)\n continue;\n const e37 = this.constrainViaDisplacement(o4, { x: h2, y: d2 }, u2);\n h2 = e37.x, d2 = e37.y;\n }\n u2?.some((e37) =\u003e this.getViaPadDistance({ x: h2, y: d2 }, e37) \u003c e37.clearance) || (o4.x === h2 \u0026\u0026 o4.y === d2 || o4.revision++, o4.x = h2, o4.y = d2);\n }\n }\n getViaPadDistance(e35, t2) {\n const n2 = e35.x - t2.center.x, o3 = e35.y - t2.center.y, i3 = { x: n2 * t2.cosine + o3 * t2.sine, y: -n2 * t2.sine + o3 * t2.cosine };\n return oy(i3, i3, t2.shape);\n }\n constrainViaDisplacement(e35, t2, n2) {\n const o3 = t2.x - e35.x, i3 = t2.y - e35.y, r3 = [];\n for (const o4 of n2) {\n if (this.getViaPadDistance(t2, o4) \u003e= o4.clearance)\n continue;\n const n3 = e35.x - o4.center.x, i4 = e35.y - o4.center.y, s3 = { x: n3 * o4.cosine + i4 * o4.sine, y: -n3 * o4.sine + i4 * o4.cosine };\n let a4;\n if (o4.shape.type === \"rect\") {\n const e36 = o4.shape.bounds;\n a4 = { x: Math.max(e36.minX, Math.min(e36.maxX, s3.x)), y: Math.max(e36.minY, Math.min(e36.maxY, s3.y)) };\n } else {\n const { a: e36, b: t3 } = o4.shape, n4 = t3.x - e36.x, i5 = t3.y - e36.y, r4 = n4 * n4 + i5 * i5, c4 = r4 \u003e 0 ? Math.max(0, Math.min(1, ((s3.x - e36.x) * n4 + (s3.y - e36.y) * i5) / r4)) : 0;\n a4 = { x: e36.x + c4 * n4, y: e36.y + c4 * i5 };\n }\n const c3 = s3.x - a4.x, l3 = s3.y - a4.y, h2 = { x: c3 * o4.cosine - l3 * o4.sine, y: c3 * o4.sine + l3 * o4.cosine };\n h2.x * h2.x + h2.y * h2.y \u003e 0.00000000000000000001 \u0026\u0026 r3.push(h2);\n }\n let s2 = { x: 0, y: 0 }, a3 = o3 * o3 + i3 * i3;\n for (const t3 of r3) {\n const n3 = o3 * t3.x + i3 * t3.y, c3 = t3.x * t3.x + t3.y * t3.y, l3 = this.shortenDisplacement(e35, { x: o3 - t3.x * n3 / c3, y: i3 - t3.y * n3 / c3 });\n if (r3.some((e36) =\u003e l3.x * e36.x + l3.y * e36.y \u003c -0.000000000000001))\n continue;\n const h2 = (l3.x - o3) ** 2 + (l3.y - i3) ** 2;\n h2 \u003c a3 \u0026\u0026 (s2 = l3, a3 = h2);\n }\n return this.compensateTangentRounding(e35, s2, n2, r3);\n }\n shortenDisplacement(e35, t2) {\n const n2 = Math.max(e35.bounds.minX, e35.original.x - Wy), o3 = Math.min(e35.bounds.maxX, e35.original.x + Wy), i3 = Math.max(e35.bounds.minY, e35.original.y - Wy), r3 = Math.min(e35.bounds.maxY, e35.original.y + Wy);\n let s2 = 1;\n return t2.x \u003e 0 \u0026\u0026 (s2 = Math.min(s2, (o3 - e35.x) / t2.x)), t2.x \u003c 0 \u0026\u0026 (s2 = Math.min(s2, (n2 - e35.x) / t2.x)), t2.y \u003e 0 \u0026\u0026 (s2 = Math.min(s2, (r3 - e35.y) / t2.y)), t2.y \u003c 0 \u0026\u0026 (s2 = Math.min(s2, (i3 - e35.y) / t2.y)), { x: Math.max(n2, Math.min(o3, e35.x + t2.x * s2)) - e35.x, y: Math.max(i3, Math.min(r3, e35.y + t2.y * s2)) - e35.y };\n }\n compensateTangentRounding(e35, t2, n2, o3) {\n const i3 = { x: e35.x + t2.x, y: e35.y + t2.y }, r3 = n2.reduce((e36, t3) =\u003e Math.max(e36, Math.abs(t3.center.x), Math.abs(t3.center.y), t3.clearance), Math.max(1, Math.abs(e35.x), Math.abs(e35.y), Math.abs(i3.x), Math.abs(i3.y))), s2 = 32 * Number.EPSILON * r3, a3 = n2.map((e36) =\u003e this.getViaPadDistance(i3, e36));\n if (a3.every((e36, t3) =\u003e e36 \u003e= n2[t3].clearance) || a3.some((e36, t3) =\u003e e36 \u003c n2[t3].clearance - s2))\n return i3;\n const c3 = o3.map((e36) =\u003e {\n const t3 = Math.hypot(e36.x, e36.y);\n return { x: e36.x / t3, y: e36.y / t3 };\n }), l3 = { x: 0, y: 0 };\n for (const e36 of c3)\n for (const t3 of [e36, { x: -e36.y, y: e36.x }, { x: e36.y, y: -e36.x }])\n c3.some((e37) =\u003e t3.x * e37.x + t3.y * e37.y \u003c -0.000000000000001) || (l3.x += t3.x, l3.y += t3.y);\n const h2 = Math.hypot(l3.x, l3.y);\n if (h2 \u003c 0.000000000000001)\n return i3;\n const d2 = this.shortenDisplacement(e35, { x: t2.x + l3.x * s2 / h2, y: t2.y + l3.y * s2 / h2 }), u2 = { x: e35.x + d2.x, y: e35.y + d2.y };\n return n2.every((e36) =\u003e this.getViaPadDistance(u2, e36) \u003e= e36.clearance) ? u2 : i3;\n }\n projectPair(e35) {\n const { a: t2, b: n2, revisions: o3 } = e35;\n if (t2.a.locked \u0026\u0026 t2.b.locked \u0026\u0026 n2.a.locked \u0026\u0026 n2.b.locked)\n return;\n if (t2.a.revision === o3[0] \u0026\u0026 t2.b.revision === o3[1] \u0026\u0026 n2.a.revision === o3[2] \u0026\u0026 n2.b.revision === o3[3])\n return;\n o3[0] = t2.a.revision, o3[1] = t2.b.revision, o3[2] = n2.a.revision, o3[3] = n2.b.revision;\n const i3 = t2.radius + n2.radius + (t2.via \u0026\u0026 n2.via ? this.viaClearance : this.traceClearance);\n if (Ty({ minX: Math.min(t2.a.x, t2.b.x), maxX: Math.max(t2.a.x, t2.b.x), minY: Math.min(t2.a.y, t2.b.y), maxY: Math.max(t2.a.y, t2.b.y) }, { minX: Math.min(n2.a.x, n2.b.x), maxX: Math.max(n2.a.x, n2.b.x), minY: Math.min(n2.a.y, n2.b.y), maxY: Math.max(n2.a.y, n2.b.y) }, i3))\n return void (e35.contact = null);\n const r3 = e35.contact = Gy(t2.a, t2.b, n2.a, n2.b);\n r3.distance \u003e= i3 || r3.distance \u003c 0.0000000001 || this.project([[t2.a, 1 - r3.s], [t2.b, r3.s], [n2.a, r3.t - 1], [n2.b, -r3.t]], r3.x / r3.distance, r3.y / r3.distance, i3 - r3.distance, t2.via \u0026\u0026 n2.via);\n }\n projectPad(e35) {\n const { segment: t2, corners: n2, required: o3 } = e35;\n if (t2.a.locked \u0026\u0026 t2.b.locked)\n return;\n if (t2.a.revision === e35.projectionRevisions[0] \u0026\u0026 t2.b.revision === e35.projectionRevisions[1])\n return;\n e35.projectionRevisions[0] = t2.a.revision, e35.projectionRevisions[1] = t2.b.revision;\n if (Ty({ minX: Math.min(t2.a.x, t2.b.x), maxX: Math.max(t2.a.x, t2.b.x), minY: Math.min(t2.a.y, t2.b.y), maxY: Math.max(t2.a.y, t2.b.y) }, e35.bounds, o3))\n return;\n const i3 = t2.a === t2.b ? 1 : 2;\n for (let e36 = 0;e36 \u003c i3; e36++) {\n const i4 = e36 === 0 ? t2.a : t2.b, r4 = Uy(i4, n2);\n r4 \u0026\u0026 this.project([[i4, 1]], r4.x, r4.y, o3 + r4.depth, false);\n }\n if (t2.a.revision !== e35.revisions[0] || t2.b.revision !== e35.revisions[1]) {\n let o4 = Gy(t2.a, t2.b, n2[0], n2[1]);\n for (let e36 = 1;e36 \u003c n2.length; e36++) {\n const i4 = Gy(t2.a, t2.b, n2[e36], n2[(e36 + 1) % n2.length]);\n o4 = o4.distance \u003c i4.distance ? o4 : i4;\n }\n e35.contact = o4, e35.revisions[0] = t2.a.revision, e35.revisions[1] = t2.b.revision;\n }\n const r3 = e35.contact;\n r3.distance \u003c 0.0000000001 || r3.distance \u003e= o3 || this.project([[t2.a, 1 - r3.s], [t2.b, r3.s]], r3.x / r3.distance, r3.y / r3.distance, o3 - r3.distance, false);\n }\n stepSweep() {\n let e35 = 0;\n for (;e35 \u003c 4096 \u0026\u0026 this.sweepPairIndex \u003c this.pairs.length; )\n this.projectPair(this.pairs[this.sweepPairIndex++]), e35++;\n for (;e35 \u003c 4096 \u0026\u0026 this.sweepPairIndex === this.pairs.length \u0026\u0026 this.sweepPadIndex \u003c this.padContacts.length; )\n this.projectPad(this.padContacts[this.sweepPadIndex++]), e35++;\n this.projectedConstraintCount += e35, this.sweepPairIndex === this.pairs.length \u0026\u0026 this.sweepPadIndex === this.padContacts.length \u0026\u0026 (this.sweepIndex++, this.sweepPairIndex = 0, this.sweepPadIndex = 0, this.sweepIndex === Vy \u0026\u0026 (this.phase = \"finalize\")), this.progress = this.sweepIndex / 257, this.stats = { ...this.stats, sweepCount: this.sweepIndex, projectedConstraintCount: this.projectedConstraintCount, lastProjectedConstraintBatchCount: e35 };\n }\n finalizeRoutes() {\n const { vertices: e35, routes: t2 } = this;\n for (const t3 of e35.values())\n for (const e36 of t3.points)\n e36.x = t3.x, e36.y = t3.y;\n for (const e36 of t2) {\n e36.vias = [];\n for (let t3 = 1;t3 \u003c e36.route.length; t3++) {\n const n2 = e36.route[t3 - 1], o3 = e36.route[t3];\n n2.z === o3.z || n2.toNextSegmentType === \"through_obstacle\" || e36.vias.some((e37) =\u003e e37.x === o3.x \u0026\u0026 e37.y === o3.y) || e36.vias.push({ x: o3.x, y: o3.y });\n }\n }\n this.solved = true, this.progress = 1;\n }\n _step() {\n switch (this.phase) {\n case \"geometry\":\n return this.prepareGeometry();\n case \"pairs\":\n return this.preparePairs();\n case \"obstacles\":\n return this.prepareObstacles();\n case \"sweeps\":\n return this.stepSweep();\n case \"finalize\":\n return this.finalizeRoutes();\n }\n }\n getOutput() {\n if (!this.solved || this.failed)\n throw new Error(\"Trace clearance projection is not complete\");\n return this.routes;\n }\n getResult() {\n return this.getOutput();\n }\n};\nvar qy = (e35) =\u003e {\n const t2 = Qo(e35), n2 = e35.filter((e36) =\u003e e36.type === \"pcb_via\" \u0026\u0026 typeof e36.pcb_trace_id == \"string\").map((e36) =\u003e [e36.pcb_via_id, e36.pcb_trace_id]);\n return t2.addConnections(n2), t2;\n};\nvar Qy = (e35, t2) =\u003e e35 === 0 ? \"top\" : e35 === t2 - 1 ? \"bottom\" : `inner${e35}`;\nvar Ky = (e35, t2) =\u003e {\n if (e35.layers !== undefined)\n return e35.layers;\n if (!Number.isInteger(t2) || t2 \u003c 1)\n throw new Error(`Invalid board layer count: ${t2}`);\n const n2 = Array.from({ length: t2 }, (e36, n3) =\u003e Qy(n3, t2)), o3 = n2.findIndex((t3) =\u003e t3 === e35.from_layer), i3 = n2.findIndex((t3) =\u003e t3 === e35.to_layer);\n if (o3 \u003c 0 || i3 \u003c 0)\n throw new Error(`Via span ${e35.from_layer} -\u003e ${e35.to_layer} is outside the board`);\n return n2.slice(Math.min(o3, i3), Math.max(o3, i3) + 1);\n};\nvar eb = ({ via: e35, layerCount: t2, allowBlindAndBuriedVias: n2 = false }) =\u003e {\n const o3 = n2 ? e35 : { from_layer: \"top\", to_layer: Qy(t2 - 1, t2) };\n return Ky(o3, t2);\n};\nvar tb = 0.005;\nvar nb = 0.000001;\nvar ob = (e35, t2) =\u003e ({ minX: e35.minX - t2, minY: e35.minY - t2, maxX: e35.maxX + t2, maxY: e35.maxY + t2 });\nvar ib = (e35) =\u003e ob({ minX: Math.min(e35.start.x, e35.end.x), minY: Math.min(e35.start.y, e35.end.y), maxX: Math.max(e35.start.x, e35.end.x), maxY: Math.max(e35.start.y, e35.end.y) }, e35.width / 2);\nvar rb = (e35) =\u003e {\n const t2 = e35.diameter / 2;\n return { minX: e35.x - t2, minY: e35.y - t2, maxX: e35.x + t2, maxY: e35.y + t2 };\n};\nvar sb = (e35) =\u003e {\n return ((e36) =\u003e {\n if (e36.length === 0)\n return null;\n let t3 = e36[0].x, n2 = e36[0].y, o3 = e36[0].x, i3 = e36[0].y;\n for (let r3 = 1;r3 \u003c e36.length; r3++) {\n const s2 = e36[r3];\n s2.x \u003c t3 \u0026\u0026 (t3 = s2.x), s2.y \u003c n2 \u0026\u0026 (n2 = s2.y), s2.x \u003e o3 \u0026\u0026 (o3 = s2.x), s2.y \u003e i3 \u0026\u0026 (i3 = s2.y);\n }\n return { minX: t3, minY: n2, maxX: o3, maxY: i3 };\n })((t2 = e35.localToWorld, [{ x: -e35.width / 2, y: -e35.height / 2 }, { x: e35.width / 2, y: -e35.height / 2 }, { x: e35.width / 2, y: e35.height / 2 }, { x: -e35.width / 2, y: e35.height / 2 }].map((e36) =\u003e Ht(t2, e36))));\n var t2;\n};\nvar ab = (e35) =\u003e ({ minX: -e35.width / 2, minY: -e35.height / 2, maxX: e35.width / 2, maxY: e35.height / 2 });\nvar cb = class {\n constructor(e35) {\n this.cellSize = e35;\n }\n cells = new Map;\n itemIds = new Map;\n rowItems = [];\n visitedGenerations = new Uint32Array(0);\n queryGeneration = 0;\n registerItem(e35) {\n const t2 = this.itemIds.get(e35);\n if (t2 !== undefined)\n return t2;\n const n2 = this.rowItems.length;\n if (n2 \u003e= this.visitedGenerations.length) {\n const e36 = new Uint32Array(this.visitedGenerations.length === 0 ? 16 : 2 * this.visitedGenerations.length);\n e36.set(this.visitedGenerations), this.visitedGenerations = e36;\n }\n return this.itemIds.set(e35, n2), this.rowItems.push(e35 === 0 ? 0 : e35), n2;\n }\n insert(e35, t2) {\n const n2 = Math.floor(t2.minX / this.cellSize), o3 = Math.floor(t2.maxX / this.cellSize), i3 = Math.floor(t2.minY / this.cellSize), r3 = Math.floor(t2.maxY / this.cellSize);\n let s2;\n for (let t3 = n2;t3 \u003c= o3; t3 += 1) {\n let n3 = this.cells.get(t3);\n !n3 \u0026\u0026 i3 \u003c= r3 \u0026\u0026 (n3 = new Map, this.cells.set(t3, n3));\n for (let t4 = i3;t4 \u003c= r3; t4 += 1) {\n const o4 = n3.get(t4);\n s2 === undefined \u0026\u0026 (s2 = this.registerItem(e35)), o4 ? o4.push(s2) : n3.set(t4, [s2]);\n }\n }\n }\n query(e35) {\n const t2 = Math.floor(e35.minX / this.cellSize), n2 = Math.floor(e35.maxX / this.cellSize), o3 = Math.floor(e35.minY / this.cellSize), i3 = Math.floor(e35.maxY / this.cellSize);\n let r3 = this.queryGeneration + 1;\n r3 \u003e 4294967295 \u0026\u0026 (this.visitedGenerations.fill(0), r3 = 1), this.queryGeneration = r3;\n const s2 = [];\n for (let e36 = t2;e36 \u003c= n2; e36 += 1) {\n const t3 = this.cells.get(e36);\n if (!(!t3 \u0026\u0026 o3 \u003e= -9007199254740991 \u0026\u0026 i3 \u003c= 9007199254740991))\n for (let e37 = o3;e37 \u003c= i3; e37 += 1) {\n const n3 = t3?.get(e37);\n if (n3)\n for (const e38 of n3)\n this.visitedGenerations[e38] !== r3 \u0026\u0026 (this.visitedGenerations[e38] = r3, s2.push(this.rowItems[e38]));\n }\n }\n return s2;\n }\n};\nvar lb = (e35, t2) =\u003e {\n const n2 = ge(e35.start, e35.end, t2.start, t2.end);\n if (n2)\n return n2;\n const o3 = [{ left: e35.start, right: Ee(e35.start, t2.start, t2.end) }, { left: e35.end, right: Ee(e35.end, t2.start, t2.end) }, { left: Ee(t2.start, e35.start, e35.end), right: t2.start }, { left: Ee(t2.end, e35.start, e35.end), right: t2.end }];\n let i3 = { left: e35.start, right: t2.start }, r3 = Number.POSITIVE_INFINITY;\n for (const e36 of o3) {\n const t3 = Math.hypot(e36.left.x - e36.right.x, e36.left.y - e36.right.y);\n t3 \u003c r3 \u0026\u0026 (i3 = e36, r3 = t3);\n }\n return { x: (i3.left.x + i3.right.x) / 2, y: (i3.left.y + i3.right.y) / 2 };\n};\nvar hb = (e35, t2) =\u003e {\n const n2 = Ee(t2, e35.start, e35.end);\n return { x: (n2.x + t2.x) / 2, y: (n2.y + t2.y) / 2 };\n};\nvar db = (e35, t2) =\u003e {\n const n2 = Ee({ x: (t2.minX + t2.maxX) / 2, y: (t2.minY + t2.maxY) / 2 }, e35.start, e35.end), o3 = Math.max(t2.minX, Math.min(t2.maxX, n2.x)), i3 = Math.max(t2.minY, Math.min(t2.maxY, n2.y));\n return { x: (n2.x + o3) / 2, y: (n2.y + i3) / 2 };\n};\nvar ub = (e35) =\u003e {\n const t2 = new Set;\n for (const n2 of e35.route)\n n2.route_type === \"wire\" \u0026\u0026 (n2.start_pcb_port_id \u0026\u0026 t2.add(n2.start_pcb_port_id), n2.end_pcb_port_id \u0026\u0026 t2.add(n2.end_pcb_port_id));\n return [...t2];\n};\nvar pb = (e35, t2, n2) =\u003e n2 \u003c 0 ? `PCB trace ${e35} overlaps with ${t2} (accidental contact)` : `PCB trace ${e35} is too close to ${t2} (gap: ${n2.toFixed(3)}mm)`;\nvar mb = class {\n constructor(e35, t2 = {}) {\n this.srj = e35;\n const n2 = t2.queryResultCacheBudget ?? 8000000;\n if (!Number.isSafeInteger(n2) || n2 \u003c 0)\n throw new Error(\"queryResultCacheBudget must be a nonnegative safe integer\");\n if (this.primitiveKeyBudget = Math.floor(n2 / 4), this.queryResultBudget = n2 - this.primitiveKeyBudget, this.traceClearance = t2.traceClearance ?? 0.1, this.viaClearance = Math.max(t2.viaClearance ?? 0.1, 0.1), this.viaToPadClearance = t2.viaToPadClearance ?? this.srj.minViaEdgeToPadEdgeClearance ?? 0.1, this.connMap = t2.connMap, this.includeTraceViaOwnerMetadata = t2.includeTraceViaOwnerMetadata ?? false, this.cellSize = t2.spatialCellSize ?? this.getDefaultSpatialCellSize(), !Number.isFinite(this.traceClearance) || this.traceClearance \u003c 0)\n throw new Error(\"traceClearance must be a non-negative finite number\");\n if (!Number.isFinite(this.viaClearance))\n throw new Error(\"viaClearance must be a finite number\");\n if (!Number.isFinite(this.viaToPadClearance) || this.viaToPadClearance \u003c 0)\n throw new Error(\"viaToPadClearance must be a non-negative finite number\");\n if (!Number.isFinite(this.cellSize) || this.cellSize \u003c= 0)\n throw new Error(\"spatialCellSize must be a positive finite number\");\n this.compileConnectionAliases(), this.obstacles = this.compileStaticObstacles(), this.obstacles.forEach((e36, t3) =\u003e this.staticObstacleIds.set(e36, t3)), this.indexStaticObstacles();\n }\n traceClearance;\n viaClearance;\n viaToPadClearance;\n cellSize;\n connMap;\n includeTraceViaOwnerMetadata;\n canonicalNetByAlias = new Map;\n connMapNetByCanonicalNet = new Map;\n obstacles;\n queryResultBudget;\n primitiveKeyBudget;\n primitiveIdsByKey = new Map;\n primitiveEvictionCursor = this.primitiveIdsByKey.entries();\n primitiveKeyUnits = 0;\n nextPrimitiveId = 0;\n staticObstacleIds = new WeakMap;\n queryResultCache = new Map;\n queryEvictionCursor = this.queryResultCache.entries();\n queryResultUnits = 0;\n cachedConnectivityKey;\n obstacleIndexesByLayer = new Map;\n lastRunStats = { traceCount: 0, segmentCount: 0, viaCount: 0, obstacleCount: 0, broadPhaseCandidateCount: 0, exactCheckCount: 0 };\n getDefaultSpatialCellSize() {\n const e35 = Math.max(0, this.srj.bounds.maxX - this.srj.bounds.minX), t2 = Math.max(0, this.srj.bounds.maxY - this.srj.bounds.minY);\n return Math.max(0.25, Math.max(e35, t2) / 64, (this.srj.minViaDiameter ?? 0.3) + Math.max(this.traceClearance, this.viaToPadClearance));\n }\n compileConnectionAliases() {\n const e35 = new Map;\n for (const t2 of this.srj.connections) {\n const n2 = t2.netConnectionName ?? t2.rootConnectionName ?? t2.name, o3 = [t2.name, t2.rootConnectionName, t2.netConnectionName, ...t2.mergedConnectionNames ?? [], ...t2.pointsToConnect.flatMap((e36) =\u003e [e36.pointId, e36.pcb_port_id])];\n for (const t3 of o3) {\n if (!t3)\n continue;\n this.canonicalNetByAlias.set(t3, n2);\n const o4 = this.connMap?.getNetConnectedToId(t3);\n if (!o4)\n continue;\n let i3 = e35.get(n2);\n i3 || (i3 = new Set, e35.set(n2, i3)), i3.add(o4);\n }\n this.canonicalNetByAlias.set(n2, n2);\n }\n for (const [t2, n2] of e35)\n n2.size === 1 \u0026\u0026 this.connMapNetByCanonicalNet.set(t2, n2.values().next().value);\n }\n resolveNetId(e35) {\n const t2 = this.connMap?.getNetConnectedToId(e35);\n if (t2)\n return t2;\n const n2 = this.canonicalNetByAlias.get(e35);\n return n2 ? this.connMapNetByCanonicalNet.get(n2) ?? n2 : e35;\n }\n areConnected(e35, t2) {\n return e35 === t2 || (!!this.connMap?.areIdsConnected(e35, t2) || this.resolveNetId(e35) === this.resolveNetId(t2));\n }\n compileStaticObstacles() {\n const e35 = [], t2 = new Set, n2 = new Set;\n for (const o3 of this.srj.obstacles) {\n if (o3.layers.length === 0)\n continue;\n const i3 = o3.connectedTo.find((e36) =\u003e e36.startsWith(\"pcb_smtpad_\")), r3 = o3.connectedTo.find((e36) =\u003e e36.startsWith(\"pcb_plated_hole_\")), s2 = o3.connectedTo.find((e36) =\u003e e36.startsWith(\"pcb_port_\"));\n if (!i3 \u0026\u0026 !r3 \u0026\u0026 !s2)\n continue;\n const a3 = o3.layers.length \u003e 1, c3 = a3 ? \"pcb_plated_hole\" : \"pcb_smtpad\", l3 = a3 ? r3 ?? `pcb_plated_hole_${o3.center.x.toFixed(3)}_${o3.center.y.toFixed(3)}` : i3 ?? `pcb_smtpad_${o3.center.x.toFixed(3)}_${o3.center.y.toFixed(3)}`, h2 = a3 ? n2 : t2;\n if (h2.has(l3))\n continue;\n h2.add(l3);\n const d2 = typeof o3.ccwRotationDegrees == \"number\" \u0026\u0026 Number.isFinite(o3.ccwRotationDegrees), u2 = Zt(Gt(o3.center.x, o3.center.y), en(d2 ? o3.ccwRotationDegrees : 0)), p3 = o3.shape === \"circle\" || !d2 \u0026\u0026 a3 \u0026\u0026 Math.abs(o3.width - o3.height) \u003c 0.001;\n e35.push({ kind: \"obstacle\", obstacleType: c3, obstacleId: l3, shape: o3.shape, connectedTo: o3.connectedTo, x: o3.center.x, y: o3.center.y, width: o3.width, height: o3.height, localToWorld: u2, worldToLocal: Vt(u2), ...p3 ? { radius: Math.max(o3.width, o3.height) / 2 } : {}, layers: o3.layers, ...s2 ? { pcbPortId: s2 } : {} });\n }\n return e35;\n }\n indexStaticObstacles() {\n for (const e35 of this.obstacles) {\n const t2 = ob(sb(e35), Math.max(this.traceClearance, this.viaToPadClearance));\n for (const n2 of e35.layers) {\n let o3 = this.obstacleIndexesByLayer.get(n2);\n o3 || (o3 = new cb(this.cellSize), this.obstacleIndexesByLayer.set(n2, o3)), o3.insert(e35, t2);\n }\n }\n }\n collectDynamicGeometry(e35) {\n const t2 = [], n2 = [], o3 = new Set;\n for (const i3 of e35) {\n const e36 = this.resolveNetId(i3.connection_name), r3 = ub(i3), s2 = this.queryResultBudget ? JSON.stringify([i3.pcb_trace_id, e36, r3]) : undefined;\n for (let n3 = 0;n3 \u003c i3.route.length - 1; n3 += 1) {\n const o4 = i3.route[n3], a3 = i3.route[n3 + 1];\n o4?.route_type === \"wire\" \u0026\u0026 a3?.route_type === \"wire\" \u0026\u0026 o4.layer === a3.layer \u0026\u0026 (Math.abs(o4.x - a3.x) \u003c= nb \u0026\u0026 Math.abs(o4.y - a3.y) \u003c= nb || t2.push({ kind: \"trace_segment\", order: t2.length, traceId: i3.pcb_trace_id, netId: e36, start: { x: o4.x, y: o4.y }, end: { x: a3.x, y: a3.y }, width: gb(o4, a3), layer: o4.layer, pcbPortIds: r3, primitiveId: s2 === undefined ? undefined : this.getPrimitiveId([\"trace\", s2, o4.x, o4.y, a3.x, a3.y, gb(o4, a3), o4.layer]) }));\n }\n for (const t3 of i3.route) {\n if (t3.route_type !== \"via\")\n continue;\n const r4 = `${t3.x},${t3.y},${t3.from_layer},${t3.to_layer}`;\n if (o3.has(r4))\n continue;\n o3.add(r4);\n const s3 = `via_${n2.length}`, a3 = t3.via_diameter ?? this.srj.minViaDiameter ?? 0.3, c3 = t3.via_hole_diameter ?? this.srj.min_via_hole_diameter ?? this.srj.minViaHoleDiameter ?? a3 / 2, l3 = eb({ via: t3, layerCount: this.srj.layerCount, allowBlindAndBuriedVias: this.srj.allowBlindAndBuriedVias });\n n2.push({ kind: \"via\", order: n2.length, viaId: s3, traceId: i3.pcb_trace_id, netId: e36, x: t3.x, y: t3.y, diameter: a3, holeDiameter: c3, layers: l3, primitiveId: this.queryResultBudget ? this.getPrimitiveId([\"via\", s3, i3.pcb_trace_id, e36, t3.x, t3.y, a3, c3, l3]) : undefined });\n }\n }\n return { segments: t2, vias: n2 };\n }\n buildDynamicIndexes(e35, t2) {\n const n2 = new Map, o3 = (e36, t3, o4) =\u003e {\n let i3 = n2.get(e36);\n i3 || (i3 = new cb(this.cellSize), n2.set(e36, i3)), i3.insert(t3, ob(o4, this.traceClearance));\n };\n for (const t3 of e35)\n o3(t3.layer, t3, ib(t3));\n for (const e36 of t2)\n for (const t3 of e36.layers)\n o3(t3, e36, rb(e36));\n return n2;\n }\n obstacleSharesNet(e35, t2) {\n return t2.connectedTo.some((t3) =\u003e this.areConnected(e35, t3));\n }\n getPrimitiveId(e35) {\n if (!this.primitiveKeyBudget)\n return;\n const t2 = JSON.stringify(e35.map((e36) =\u003e typeof e36 != \"number\" ? e36 : Object.is(e36, -0) ? \"-0\" : Number.isNaN(e36) ? \"NaN\" : e36 === 1 / 0 ? \"+Infinity\" : e36 === -1 / 0 ? \"-Infinity\" : e36)), n2 = this.primitiveIdsByKey.get(t2);\n if (n2)\n return n2.id;\n const o3 = t2.length + 64;\n if (o3 \u003e this.primitiveKeyBudget || this.nextPrimitiveId \u003e= Number.MAX_SAFE_INTEGER)\n return;\n for (;this.primitiveKeyUnits + o3 \u003e this.primitiveKeyBudget; ) {\n const [e36, t3] = this.primitiveEvictionCursor.next().value;\n this.primitiveKeyUnits -= t3.units, this.primitiveIdsByKey.delete(e36);\n }\n const i3 = this.nextPrimitiveId++;\n return this.primitiveIdsByKey.set(t2, { id: i3, units: o3 }), this.primitiveKeyUnits += o3, i3;\n }\n getQueryCacheKey(e35, t2) {\n if (this.queryResultBudget \u0026\u0026 !t2.some((e36) =\u003e e36 === undefined))\n return `${e35}:${t2.join(\",\")}`;\n }\n runCachedQuery(e35, t2) {\n const n2 = e35 === undefined ? undefined : this.queryResultCache.get(e35);\n if (n2)\n return this.lastRunStats.exactCheckCount += n2.exactCheckCount, this.lastRunStats.broadPhaseCandidateCount += n2.broadPhaseCandidateCount, n2.errors.length ? structuredClone(n2.errors) : [];\n const o3 = this.lastRunStats.exactCheckCount, i3 = this.lastRunStats.broadPhaseCandidateCount, r3 = t2();\n if (e35 === undefined)\n return r3;\n const s2 = e35.length + (r3.length ? JSON.stringify(r3).length : 0) + 64 * r3.length + 64;\n if (s2 \u003e this.queryResultBudget)\n return r3;\n for (;this.queryResultUnits + s2 \u003e this.queryResultBudget; ) {\n const [e36, t3] = this.queryEvictionCursor.next().value;\n this.queryResultUnits -= t3.units, this.queryResultCache.delete(e36);\n }\n return this.queryResultCache.set(e35, { errors: r3.length ? structuredClone(r3) : [], exactCheckCount: this.lastRunStats.exactCheckCount - o3, broadPhaseCandidateCount: this.lastRunStats.broadPhaseCandidateCount - i3, units: s2 }), this.queryResultUnits += s2, r3;\n }\n checkTraceQuery(e35, t2, n2) {\n let o3;\n if (this.lastRunStats.broadPhaseCandidateCount += t2.length + n2.length, this.queryResultBudget) {\n const i3 = [e35.primitiveId];\n for (const n3 of t2)\n n3.kind === \"trace_segment\" \u0026\u0026 n3.order \u003c= e35.order || i3.push(n3.primitiveId);\n i3.push(-1);\n for (const e36 of n2)\n i3.push(this.staticObstacleIds.get(e36));\n o3 = this.getQueryCacheKey(\"trace\", i3);\n }\n return this.runCachedQuery(o3, () =\u003e {\n const o4 = [];\n for (const n3 of t2) {\n if (n3.kind === \"trace_segment\" \u0026\u0026 n3.order \u003c= e35.order)\n continue;\n const t3 = n3.kind === \"trace_segment\" ? this.checkTracePair(e35, n3) : this.checkTraceVia(e35, n3);\n t3 \u0026\u0026 o4.push(t3);\n }\n for (const t3 of n2) {\n const n3 = this.checkTraceObstacle(e35, t3);\n n3 \u0026\u0026 o4.push(n3);\n }\n return o4;\n });\n }\n checkTracePair(e35, t2) {\n if (this.areConnected(e35.netId, t2.netId))\n return;\n this.lastRunStats.exactCheckCount += 1;\n const n2 = we(e35.start, e35.end, t2.start, t2.end) - e35.width / 2 - t2.width / 2;\n if (n2 \u003e this.traceClearance - tb)\n return;\n const o3 = `overlap_${e35.traceId}_${t2.traceId}`;\n return { type: \"pcb_trace_error\", error_type: \"pcb_trace_error\", message: pb(e35.traceId, `PCB trace ${t2.traceId}`, n2), pcb_trace_id: e35.traceId, source_trace_id: \"\", pcb_trace_error_id: o3, minimum_clearance: this.traceClearance, actual_clearance: n2, pcb_component_ids: [], pcb_port_ids: [...new Set([...e35.pcbPortIds, ...t2.pcbPortIds])], center: lb(e35, t2) };\n }\n checkTraceVia(e35, t2) {\n if (this.areConnected(e35.netId, t2.netId))\n return;\n this.lastRunStats.exactCheckCount += 1;\n const n2 = Te(e35.start, e35.end, { x: t2.x, y: t2.y, radius: t2.diameter / 2 }) - e35.width / 2;\n if (n2 \u003e this.traceClearance - tb)\n return;\n const o3 = `overlap_${e35.traceId}_${t2.viaId}`;\n return { type: \"pcb_trace_error\", error_type: \"pcb_trace_error\", message: pb(e35.traceId, `pcb_via \"${t2.viaId}\"`, n2), pcb_trace_id: e35.traceId, ...this.includeTraceViaOwnerMetadata ? { pcb_trace_ids: [e35.traceId, t2.traceId], pcb_via_id: t2.viaId, pcb_via_ids: [t2.viaId] } : {}, source_trace_id: \"\", pcb_trace_error_id: o3, minimum_clearance: this.traceClearance, actual_clearance: n2, pcb_component_ids: [], pcb_port_ids: e35.pcbPortIds, center: hb(e35, t2) };\n }\n checkTraceObstacle(e35, t2) {\n if (this.obstacleSharesNet(e35.netId, t2))\n return;\n this.lastRunStats.exactCheckCount += 1;\n const n2 = ab(t2), o3 = { ...e35, start: Ht(t2.worldToLocal, e35.start), end: Ht(t2.worldToLocal, e35.end) }, i3 = (t2.radius === undefined ? Ne(o3.start, o3.end, n2) : Te(e35.start, e35.end, { x: t2.x, y: t2.y, radius: t2.radius })) - e35.width / 2;\n if (i3 + tb \u003e= this.traceClearance)\n return;\n const r3 = `overlap_${e35.traceId}_${t2.obstacleId}`;\n return { type: \"pcb_trace_error\", error_type: \"pcb_trace_error\", message: pb(e35.traceId, `${t2.obstacleType} \"${t2.obstacleId}\"`, i3), pcb_trace_id: e35.traceId, source_trace_id: \"\", pcb_trace_error_id: r3, minimum_clearance: this.traceClearance, actual_clearance: i3, pcb_component_ids: [], pcb_port_ids: [...new Set([...e35.pcbPortIds, ...t2.pcbPortId ? [t2.pcbPortId] : []])], center: t2.radius === undefined ? Ht(t2.localToWorld, db(o3, n2)) : hb(e35, t2) };\n }\n checkViaObstacle(e35, t2) {\n const n2 = this.obstacleSharesNet(e35.netId, t2);\n if (n2 \u0026\u0026 this.srj.allowViaInPad !== false)\n return;\n this.lastRunStats.exactCheckCount += 1;\n const o3 = ab(t2), i3 = Ht(t2.worldToLocal, e35), r3 = n2 \u0026\u0026 t2.shape === \"circle\" ? Math.min(t2.width, t2.height) / 2 : t2.radius, s2 = r3 === undefined ? Math.hypot(Math.max(o3.minX - i3.x, 0, i3.x - o3.maxX), Math.max(o3.minY - i3.y, 0, i3.y - o3.maxY)) : Math.hypot(e35.x - t2.x, e35.y - t2.y) - r3, a3 = n2 ? e35.holeDiameter : e35.diameter, c3 = n2 ? 0 : this.viaToPadClearance, l3 = s2 - a3 / 2;\n if (l3 + (n2 ? nb : tb) \u003e= c3)\n return;\n const h2 = n2 ? \"pcb_placement_error\" : \"pcb_pad_pad_clearance_error\", d2 = `via_pad_clearance_${e35.viaId}_${t2.obstacleId}`, u2 = { x: (e35.x + t2.x) / 2, y: (e35.y + t2.y) / 2 };\n return { type: h2, error_type: h2, [`${h2}_id`]: d2, message: `pcb_via \"${e35.viaId}\" and ${t2.obstacleType} \"${t2.obstacleId}\" are too close (gap: ${l3.toFixed(3)}mm)`, pcb_trace_id: e35.traceId, pcb_pad_ids: [e35.viaId, t2.obstacleId], pcb_via_ids: [e35.viaId], minimum_clearance: c3, actual_clearance: l3, center: u2 };\n }\n checkViaPairs(e35) {\n const t2 = this.queryResultBudget ? this.getQueryCacheKey(\"via-pairs\", e35.map((e36) =\u003e e36.primitiveId)) : undefined;\n return this.runCachedQuery(t2, () =\u003e this.computeViaPairs(e35));\n }\n computeViaPairs(e35) {\n if (e35.length \u003c 2)\n return [];\n const t2 = [], n2 = new cb(this.cellSize);\n for (const t3 of e35)\n n2.insert(t3, ob(rb(t3), this.viaClearance));\n for (const o3 of e35)\n for (const e36 of n2.query(rb(o3))) {\n if (this.lastRunStats.broadPhaseCandidateCount += 1, e36.order \u003c= o3.order)\n continue;\n this.lastRunStats.exactCheckCount += 1;\n const n3 = Math.hypot(o3.x - e36.x, o3.y - e36.y);\n if (n3 \u003c= nb)\n continue;\n const i3 = n3 - o3.diameter / 2 - e36.diameter / 2;\n if (i3 + tb \u003e= this.viaClearance)\n continue;\n const r3 = this.areConnected(o3.netId, e36.netId), s2 = [o3.viaId, e36.viaId].sort().join(\"_\"), a3 = { x: (o3.x + e36.x) / 2, y: (o3.y + e36.y) / 2 };\n t2.push({ type: \"pcb_via_clearance_error\", error_type: \"pcb_via_clearance_error\", pcb_error_id: `${r3 ? \"same_net\" : \"different_net\"}_vias_close_${s2}`, message: `Vias ${o3.viaId} and ${e36.viaId}${r3 ? \"\" : \" from different nets\"} are too close together (gap: ${i3.toFixed(3)}mm)`, pcb_via_ids: [o3.viaId, e36.viaId], ...this.includeTraceViaOwnerMetadata ? { pcb_trace_ids: [o3.traceId, e36.traceId] } : {}, pcb_via_pair_net_relation: r3 ? \"same_net\" : \"different_net\", minimum_clearance: this.viaClearance, actual_clearance: i3, pcb_center: a3, center: a3 });\n }\n return t2;\n }\n checkViaPadQuery(e35) {\n const t2 = this.getQueryCacheKey(\"via-pad\", [e35.primitiveId]);\n return this.runCachedQuery(t2, () =\u003e {\n const t3 = [], n2 = new Set;\n for (const o3 of e35.layers) {\n const i3 = this.obstacleIndexesByLayer.get(o3)?.query(rb(e35)) ?? [];\n for (const o4 of i3) {\n if (n2.has(o4))\n continue;\n n2.add(o4), this.lastRunStats.broadPhaseCandidateCount += 1;\n const i4 = this.checkViaObstacle(e35, o4);\n i4 \u0026\u0026 t3.push(i4);\n }\n }\n return t3;\n });\n }\n evaluate(e35) {\n return this.evaluateInternal(e35, true);\n }\n evaluateLegacy(e35) {\n return this.evaluateInternal(e35, false);\n }\n evaluateInternal(e35, t2) {\n if (this.queryResultBudget) {\n const e36 = JSON.stringify([this.connMap?.idToNetMap, this.obstacles.map((e37) =\u003e e37.connectedTo)]);\n e36 !== this.cachedConnectivityKey \u0026\u0026 (this.queryResultCache.clear(), this.queryEvictionCursor = this.queryResultCache.entries(), this.queryResultUnits = 0, this.cachedConnectivityKey = e36);\n }\n const { segments: n2, vias: o3 } = this.collectDynamicGeometry(e35), i3 = this.buildDynamicIndexes(n2, o3), r3 = [], s2 = [];\n this.lastRunStats = { traceCount: e35.length, segmentCount: n2.length, viaCount: o3.length, obstacleCount: this.obstacles.length, broadPhaseCandidateCount: 0, exactCheckCount: 0 };\n for (const e36 of n2) {\n const t3 = ib(e36), n3 = i3.get(e36.layer)?.query(t3) ?? [], o4 = this.obstacleIndexesByLayer.get(e36.layer)?.query(t3) ?? [];\n r3.push(...this.checkTraceQuery(e36, n3, o4));\n }\n const a3 = this.checkViaPairs(o3);\n if (t2)\n for (const e36 of o3)\n s2.push(...this.checkViaPadQuery(e36));\n const c3 = new Map;\n for (const e36 of r3) {\n const t3 = String(e36.pcb_trace_error_id), n3 = c3.get(t3), o4 = Number(e36.actual_clearance);\n if (!n3) {\n c3.set(t3, { ...e36, first_contact_center: e36.center, first_contact_message: e36.message, first_actual_clearance: o4, worst_contact_center: e36.center, worst_contact_message: e36.message, worst_actual_clearance: o4 });\n continue;\n }\n const i4 = Number(n3.worst_actual_clearance);\n (o4 \u003c i4 || !Number.isFinite(i4)) \u0026\u0026 (n3.worst_contact_center = e36.center, n3.worst_contact_message = e36.message, n3.worst_actual_clearance = o4);\n }\n const l3 = [...c3.values()].map((e36) =\u003e ({ ...e36, center: typeof e36.worst_contact_center == \"object\" ? e36.worst_contact_center : e36.center, message: typeof e36.worst_contact_message == \"string\" ? e36.worst_contact_message : e36.message, actual_clearance: typeof e36.worst_actual_clearance == \"number\" ? e36.worst_actual_clearance : e36.actual_clearance }));\n l3.push(...s2), l3.push(...a3);\n const h2 = l3.filter((e36) =\u003e e36.center);\n return { errors: l3, errorsWithCenters: h2, locationAwareErrors: h2 };\n }\n};\nvar gb = (e35, t2) =\u003e e35.width ?? t2.width ?? 0.1;\nvar fb = [1, 1.75, -1];\nvar _b = [1, 1.75, -1];\nvar yb = 8 / 3;\nvar bb = 0.000001;\nvar xb = 0.001;\nvar vb = 0.14;\nvar Ib = 0.035;\nvar Sb = 0.015;\nvar Cb = (e35) =\u003e e35.minTraceToPadEdgeClearance ?? 0.16;\nvar Pb = (e35) =\u003e e35.minViaEdgeToPadEdgeClearance ?? 0.1;\nvar Mb = (e35) =\u003e Math.max(48, Math.round(48 * Math.max(1, e35)));\nvar wb = (e35) =\u003e e35 \u003e= 2 ? fb : _b;\nvar Nb = class {\n netMap;\n idToNetMap;\n constructor(e35) {\n this.netMap = e35, this.idToNetMap = {};\n for (const [t2, n2] of Object.entries(e35))\n for (const e36 of n2)\n this.idToNetMap[e36] = t2;\n }\n addConnections(e35) {\n for (const t2 of e35) {\n const e36 = new Set;\n for (const n3 of t2) {\n const t3 = this.idToNetMap[n3];\n t3 \u0026\u0026 e36.add(t3);\n }\n let n2;\n if (e36.size === 0)\n n2 = `connectivity_net${Object.keys(this.netMap).length}`, this.netMap[n2] = [];\n else if (e36.size === 1)\n n2 = e36.values().next().value ?? `connectivity_net${Object.keys(this.netMap).length}`;\n else {\n n2 = e36.values().next().value ?? `connectivity_net${Object.keys(this.netMap).length}`;\n for (const t3 of e36)\n if (t3 !== n2) {\n this.netMap[n2].push(...this.netMap[t3]), this.netMap[t3] = this.netMap[n2];\n for (const e37 of this.netMap[n2])\n this.idToNetMap[e37] = n2;\n }\n }\n for (const e37 of t2)\n this.netMap[n2].includes(e37) || this.netMap[n2].push(e37), this.idToNetMap[e37] = n2;\n }\n }\n getIdsConnectedToNet(e35) {\n return this.netMap[e35] || [];\n }\n getNetConnectedToId(e35) {\n return this.idToNetMap[e35];\n }\n areIdsConnected(e35, t2) {\n if (e35 === t2)\n return true;\n const n2 = this.getNetConnectedToId(e35);\n if (!n2)\n return false;\n const o3 = this.getNetConnectedToId(t2);\n return !!o3 \u0026\u0026 (n2 === o3 || o3 === e35 || o3 === e35);\n }\n areAllIdsConnected(e35) {\n const t2 = this.getNetConnectedToId(e35[0]);\n for (const n2 of e35) {\n const e36 = this.getNetConnectedToId(n2);\n if (e36 === undefined)\n return false;\n if (e36 !== t2)\n return false;\n }\n return true;\n }\n};\nvar Rb = (e35) =\u003e {\n const t2 = [];\n for (const n3 of e35)\n if (n3.type === \"source_trace\")\n t2.push([n3.source_trace_id, ...n3.connected_source_port_ids ?? [], ...n3.connected_source_net_ids ?? []].filter(Boolean));\n else if (n3.type === \"pcb_port\") {\n const { pcb_port_id: e36, source_port_id: o3 } = n3;\n o3 \u0026\u0026 e36 \u0026\u0026 t2.push([o3, e36]);\n } else if (n3.type === \"pcb_smtpad\") {\n const { pcb_smtpad_id: e36, pcb_port_id: o3 } = n3;\n o3 \u0026\u0026 e36 \u0026\u0026 t2.push([e36, o3]);\n } else if (n3.type === \"pcb_plated_hole\") {\n const { pcb_plated_hole_id: e36, pcb_port_id: o3 } = n3;\n o3 \u0026\u0026 e36 \u0026\u0026 t2.push([e36, o3]);\n } else if (n3.type === \"pcb_trace\") {\n const { pcb_trace_id: e36, source_trace_id: o3 } = n3, i3 = Array.isArray(n3.route) ? n3.route.filter((e37) =\u003e e37 \u0026\u0026 e37.route_type === \"wire\") : [];\n if (o3 \u0026\u0026 e36 \u0026\u0026 t2.push([e36, o3]), Array.isArray(i3)) {\n const n4 = i3.find((e37) =\u003e e37?.start_pcb_port_id)?.start_pcb_port_id, o4 = i3.find((e37) =\u003e e37?.end_pcb_port_id)?.end_pcb_port_id;\n n4 \u0026\u0026 e36 \u0026\u0026 o4 \u0026\u0026 t2.push([n4, e36, o4]);\n }\n } else if (n3.type === \"pcb_via\") {\n const { pcb_via_id: e36, pcb_trace_id: o3 } = n3;\n o3 \u0026\u0026 e36 \u0026\u0026 t2.push([e36, o3]);\n } else if (n3.type === \"source_component\" \u0026\u0026 n3.internally_connected_source_port_ids)\n for (const e36 of n3.internally_connected_source_port_ids)\n t2.push(e36);\n const n2 = function(e36) {\n const t3 = new Map;\n let n3 = 0;\n function o3(e37) {\n for (const [, n4] of t3)\n if (n4.has(e37))\n return n4;\n const o4 = new Set;\n return t3.set(\"connectivity_net\" + n3++, o4), o4;\n }\n for (const n4 of e36) {\n let e37 = null;\n for (const i3 of n4) {\n if (e37) {\n if (!e37.has(i3)) {\n const n5 = o3(i3);\n if (n5 !== e37) {\n for (const t4 of n5)\n e37.add(t4);\n t3.delete(Array.from(t3.entries()).find(([, e38]) =\u003e e38 === n5)[0]);\n }\n }\n } else\n e37 = o3(i3);\n e37.add(i3);\n }\n }\n return Object.fromEntries(Array.from(t3.entries()).map(([e37, t4]) =\u003e [e37, Array.from(t4)]));\n }(t2);\n return new Nb(n2);\n};\nvar Tb = {};\nc(Tb, { all_layers: () =\u003e mv, any_circuit_element: () =\u003e wC, any_soup_element: () =\u003e NC, any_source_component: () =\u003e rv, asset: () =\u003e ox, base_circuit_json_error: () =\u003e bx, battery_capacity: () =\u003e Ub, brep_shape: () =\u003e oI, cadModelDefaultDirectionMap: () =\u003e lC, cad_component: () =\u003e hC, cad_model_axis_directions: () =\u003e cC, cad_model_formats: () =\u003e aC, capacitance: () =\u003e Lb, circuit_json_footprint_load_error: () =\u003e kS, current: () =\u003e Yb, distance: () =\u003e $b, duration_ms: () =\u003e Xb, experiment_type: () =\u003e xC, external_footprint_load_error: () =\u003e OS, frequency: () =\u003e jb, getZodPrefixedIdWithDefault: () =\u003e ex, inductance: () =\u003e zb, kicadAt: () =\u003e ix, kicadEffects: () =\u003e sx, kicadFont: () =\u003e rx, kicadFootprintAttributes: () =\u003e lx, kicadFootprintMetadata: () =\u003e ux, kicadFootprintModel: () =\u003e dx, kicadFootprintPad: () =\u003e hx, kicadFootprintProperties: () =\u003e cx, kicadProperty: () =\u003e ax, kicadSymbolEffects: () =\u003e gx, kicadSymbolMetadata: () =\u003e yx, kicadSymbolPinNames: () =\u003e mx, kicadSymbolPinNumbers: () =\u003e px, kicadSymbolProperties: () =\u003e _x, kicadSymbolProperty: () =\u003e fx, layer_ref: () =\u003e fv, layer_string: () =\u003e gv, length: () =\u003e Fb, manufacturing_drc_properties: () =\u003e aI, ms: () =\u003e Vb, ninePointAnchor: () =\u003e tx, pcbRenderLayer: () =\u003e nx, pcb_autorouting_error: () =\u003e LS, pcb_board: () =\u003e tS, pcb_breakout_point: () =\u003e $S, pcb_component: () =\u003e cI, pcb_component_invalid_layer_error: () =\u003e QS, pcb_component_not_on_board_edge_error: () =\u003e JS, pcb_component_outside_board_error: () =\u003e qS, pcb_connector_not_in_accessible_orientation_warning: () =\u003e FS, pcb_copper_pour: () =\u003e ZS, pcb_copper_pour_brep: () =\u003e GS, pcb_copper_pour_polygon: () =\u003e US, pcb_copper_pour_rect: () =\u003e WS, pcb_copper_text: () =\u003e lS, pcb_courtyard_circle: () =\u003e sC, pcb_courtyard_outline: () =\u003e iC, pcb_courtyard_overlap_error: () =\u003e CS, pcb_courtyard_polygon: () =\u003e rC, pcb_courtyard_rect: () =\u003e oC, pcb_cutout: () =\u003e ES, pcb_cutout_circle: () =\u003e NS, pcb_cutout_path: () =\u003e TS, pcb_cutout_polygon: () =\u003e RS, pcb_cutout_rect: () =\u003e wS, pcb_fabrication_note_dimension: () =\u003e _S, pcb_fabrication_note_path: () =\u003e gS, pcb_fabrication_note_rect: () =\u003e fS, pcb_fabrication_note_text: () =\u003e mS, pcb_footprint_overlap_error: () =\u003e SS, pcb_ground_plane: () =\u003e YS, pcb_ground_plane_region: () =\u003e XS, pcb_group: () =\u003e DS, pcb_hole: () =\u003e vI, pcb_hole_circle_or_square_shape: () =\u003e mI, pcb_hole_circle_shape: () =\u003e hI, pcb_hole_oval_shape: () =\u003e fI, pcb_hole_pill_shape: () =\u003e yI, pcb_hole_rect_shape: () =\u003e uI, pcb_hole_rotated_pill_shape: () =\u003e xI, pcb_keepout: () =\u003e PS, pcb_manual_edit_conflict_warning: () =\u003e zS, pcb_missing_footprint_error: () =\u003e AS, pcb_net: () =\u003e KI, pcb_note_dimension: () =\u003e IS, pcb_note_line: () =\u003e vS, pcb_note_path: () =\u003e xS, pcb_note_rect: () =\u003e bS, pcb_note_text: () =\u003e yS, pcb_pad_pad_clearance_error: () =\u003e tC, pcb_pad_trace_clearance_error: () =\u003e nC, pcb_panel: () =\u003e nS, pcb_panelization_placement_error: () =\u003e iS, pcb_placement_error: () =\u003e oS, pcb_plated_hole: () =\u003e NI, pcb_port: () =\u003e RI, pcb_port_not_connected_error: () =\u003e QI, pcb_port_not_matched_error: () =\u003e JI, pcb_route_hint: () =\u003e iI, pcb_route_hints: () =\u003e rI, pcb_silkscreen_circle: () =\u003e dS, pcb_silkscreen_line: () =\u003e sS, pcb_silkscreen_oval: () =\u003e uS, pcb_silkscreen_path: () =\u003e aS, pcb_silkscreen_pill: () =\u003e pS, pcb_silkscreen_rect: () =\u003e hS, pcb_silkscreen_text: () =\u003e cS, pcb_smtpad: () =\u003e LI, pcb_smtpad_pill: () =\u003e OI, pcb_solder_paste: () =\u003e YI, pcb_text: () =\u003e XI, pcb_thermal_spoke: () =\u003e HS, pcb_trace: () =\u003e GI, pcb_trace_error: () =\u003e ZI, pcb_trace_hint: () =\u003e rS, pcb_trace_missing_error: () =\u003e qI, pcb_trace_route_point: () =\u003e WI, pcb_trace_route_point_via: () =\u003e VI, pcb_trace_route_point_wire: () =\u003e HI, pcb_trace_warning: () =\u003e UI, pcb_via: () =\u003e eS, pcb_via_clearance_error: () =\u003e KS, pcb_via_trace_clearance_error: () =\u003e eC, point: () =\u003e Zb, point3: () =\u003e Jb, point_with_bulge: () =\u003e tI, port_arrangement: () =\u003e Rv, position: () =\u003e qb, position3: () =\u003e Qb, resistance: () =\u003e Db, ring: () =\u003e nI, rotation: () =\u003e Gb, route_hint_point: () =\u003e sI, schematic_arc: () =\u003e Lv, schematic_box: () =\u003e Cv, schematic_circle: () =\u003e Dv, schematic_component: () =\u003e Tv, schematic_component_port_arrangement_by_sides: () =\u003e Nv, schematic_component_port_arrangement_by_size: () =\u003e wv, schematic_debug_line: () =\u003e Wv, schematic_debug_object: () =\u003e Uv, schematic_debug_object_base: () =\u003e Hv, schematic_debug_point: () =\u003e Gv, schematic_debug_rect: () =\u003e Vv, schematic_error: () =\u003e Yv, schematic_group: () =\u003e Jv, schematic_layout_error: () =\u003e Xv, schematic_line: () =\u003e Ov, schematic_manual_edit_conflict_warning: () =\u003e qv, schematic_net_label: () =\u003e $v, schematic_path: () =\u003e Pv, schematic_pin_styles: () =\u003e Mv, schematic_port: () =\u003e jv, schematic_rect: () =\u003e kv, schematic_sheet: () =\u003e eI, schematic_symbol: () =\u003e Av, schematic_table: () =\u003e Qv, schematic_table_cell: () =\u003e Kv, schematic_text: () =\u003e Fv, schematic_trace: () =\u003e zv, schematic_voltage_probe: () =\u003e Zv, simulation_ac_current_source: () =\u003e yC, simulation_ac_voltage_source: () =\u003e mC, simulation_current_source: () =\u003e bC, simulation_dc_current_source: () =\u003e _C, simulation_dc_voltage_source: () =\u003e pC, simulation_experiment: () =\u003e vC, simulation_op_amp: () =\u003e MC, simulation_switch: () =\u003e SC, simulation_transient_voltage_graph: () =\u003e IC, simulation_unknown_experiment_error: () =\u003e PC, simulation_voltage_probe: () =\u003e CC, simulation_voltage_source: () =\u003e gC, size: () =\u003e Kb, source_ambiguous_port_reference: () =\u003e uv, source_board: () =\u003e dv, source_component_base: () =\u003e vx, source_component_internal_connection: () =\u003e av, source_component_pins_underspecified_warning: () =\u003e vv, source_failed_to_create_component_error: () =\u003e Zx, source_group: () =\u003e lv, source_i2c_misconfigured_error: () =\u003e ov, source_interconnect: () =\u003e nv, source_invalid_component_property_error: () =\u003e qx, source_manually_placed_via: () =\u003e yv, source_missing_manufacturer_part_number_warning: () =\u003e ev, source_missing_property_error: () =\u003e Ux, source_net: () =\u003e hv, source_no_ground_pin_defined_warning: () =\u003e xv, source_no_power_pin_defined_warning: () =\u003e bv, source_pcb_ground_plane: () =\u003e pv, source_pin_attributes: () =\u003e Ex, source_pin_missing_trace_warning: () =\u003e Kx, source_pin_must_be_connected_error: () =\u003e Iv, source_port: () =\u003e sv, source_project_metadata: () =\u003e Gx, source_property_ignored_warning: () =\u003e Qx, source_simple_battery: () =\u003e Ox, source_simple_capacitor: () =\u003e Ix, source_simple_chip: () =\u003e Nx, source_simple_connector: () =\u003e Fx, source_simple_crystal: () =\u003e zx, source_simple_current_source: () =\u003e Tx, source_simple_diode: () =\u003e Cx, source_simple_fiducial: () =\u003e Px, source_simple_ground: () =\u003e wx, source_simple_inductor: () =\u003e kx, source_simple_led: () =\u003e Mx, source_simple_mosfet: () =\u003e Hx, source_simple_op_amp: () =\u003e Vx, source_simple_pin_header: () =\u003e Bx, source_simple_pinout: () =\u003e jx, source_simple_potentiometer: () =\u003e Lx, source_simple_power_source: () =\u003e Rx, source_simple_push_button: () =\u003e Dx, source_simple_resistor: () =\u003e Sx, source_simple_resonator: () =\u003e $x, source_simple_switch: () =\u003e Wx, source_simple_test_point: () =\u003e Xx, source_simple_transistor: () =\u003e Yx, source_simple_voltage_probe: () =\u003e tv, source_simple_voltage_source: () =\u003e iv, source_trace: () =\u003e cv, source_trace_not_connected_error: () =\u003e Jx, supplier_footprint_mismatch_warning: () =\u003e jS, supplier_name: () =\u003e xx, time: () =\u003e Hb, timestamp: () =\u003e Wb, unknown_error_finding_part: () =\u003e Sv, visible_layer: () =\u003e _v, voltage: () =\u003e Bb, wave_shape: () =\u003e dC });\nvar Eb = { Hz: { baseUnit: \"Hz\", variants: { MHz: 1e6, kHz: 1000, Hz: 1 } }, g: { baseUnit: \"g\", variants: { kg: 1000, g: 1 } }, \"Ω\": { baseUnit: \"Ω\", variants: { \"mΩ\": 0.001, \"Ω\": 1, \"kΩ\": 1000, \"KΩ\": 1000, kohm: 1000, \"MΩ\": 1e6, \"GΩ\": 1e9, \"TΩ\": 1000000000000 } }, V: { baseUnit: \"V\", variants: { mV: 0.001, V: 1, kV: 1000, KV: 1000, MV: 1e6, GV: 1e9, TV: 1000000000000 } }, A: { baseUnit: \"A\", variants: { \"µA\": 0.000001, mA: 0.001, ma: 0.001, A: 1, kA: 1000, MA: 1e6 } }, F: { baseUnit: \"F\", variants: { pF: 0.000000000001, nF: 0.000000001, \"µF\": 0.000001, uF: 0.000001, mF: 0.001, F: 1 } }, ml: { baseUnit: \"ml\", variants: { ml: 1, mL: 1, l: 1000, L: 1000 } }, deg: { baseUnit: \"deg\", variants: { rad: 180 / Math.PI } }, ms: { baseUnit: \"ms\", variants: { fs: 0.000000000001, ps: 0.000000001, ns: 0.000001, us: 0.001, \"µs\": 0.001, ms: 1, s: 1000 } }, mm: { baseUnit: \"mm\", variants: { nm: 0.000001, \"µm\": 0.001, um: 0.001, mm: 1, cm: 10, dm: 100, m: 1000, km: 1e6, in: 25.4, ft: 304.8, IN: 25.4, FT: 304.8, yd: 914.4, mi: 1609344, mil: 0.0254 } } };\nvar Ab = new Set;\nfor (const [e35, t2] of Object.entries(Eb)) {\n Ab.add(e35);\n for (const e36 of Object.keys(t2.variants))\n Ab.add(e36);\n}\nvar Ob = { tera: 1000000000000, T: 1000000000000, giga: 1e9, G: 1e9, mega: 1e6, M: 1e6, kilo: 1000, k: 1000, deci: 0.1, d: 0.1, centi: 0.01, c: 0.01, milli: 0.001, m: 0.001, micro: 0.000001, u: 0.000001, \"µ\": 0.000001, nano: 0.000000001, n: 0.000000001, pico: 0.000000000001, p: 0.000000000001 };\nfunction kb(e35) {\n if (e35 == null)\n return { parsedUnit: null, unitOfValue: null, value: null };\n if (typeof e35 == \"string\" \u0026\u0026 e35.match(/^-?[\\d\\.]+$/))\n return { value: Number.parseFloat(e35), parsedUnit: null, unitOfValue: null };\n if (typeof e35 == \"number\")\n return { value: e35, parsedUnit: null, unitOfValue: null };\n if (typeof e35 == \"object\" \u0026\u0026 \"x\" in e35 \u0026\u0026 \"y\" in e35) {\n const { parsedUnit: t3, unitOfValue: n3 } = kb(e35.x), o4 = kb(e35.x), i4 = kb(e35.y);\n return o4.value === null || i4.value === null ? { parsedUnit: null, unitOfValue: null, value: null } : { parsedUnit: t3, unitOfValue: n3, value: { x: o4.value, y: i4.value } };\n }\n const t2 = e35.toString().split(\"\").reverse().join(\"\"), n2 = t2.match(/[^\\d\\s]+/)?.[0];\n if (!n2)\n throw new Error(`Could not determine unit: \"${e35}\"`);\n const o3 = n2.split(\"\").reverse().join(\"\"), i3 = e35.slice(0, -o3.length);\n if (o3 in Ob \u0026\u0026 !Ab.has(o3)) {\n const e36 = Ob[o3];\n return { parsedUnit: null, unitOfValue: null, value: Number.parseFloat(i3) * e36 };\n }\n const { baseUnit: r3, conversionFactor: s2 } = function(e36) {\n for (const [t3, n3] of Object.entries(Eb))\n if (e36 in n3.variants)\n return { baseUnit: n3.baseUnit, conversionFactor: n3.variants[e36] };\n return { baseUnit: e36, conversionFactor: 1 };\n }(o3);\n return { parsedUnit: o3, unitOfValue: r3, value: s2 * Number.parseFloat(i3) };\n}\nvar Db = Wa.string().or(Wa.number()).transform((e35) =\u003e kb(e35).value);\nvar Lb = Wa.string().or(Wa.number()).transform((e35) =\u003e kb(e35).value).transform((e35) =\u003e Number.parseFloat(e35.toPrecision(12)));\nvar zb = Wa.string().or(Wa.number()).transform((e35) =\u003e kb(e35).value);\nvar Bb = Wa.string().or(Wa.number()).transform((e35) =\u003e kb(e35).value);\nvar Fb = Wa.string().or(Wa.number()).transform((e35) =\u003e kb(e35).value);\nvar jb = Wa.string().or(Wa.number()).transform((e35) =\u003e kb(e35).value);\nvar $b = Fb;\nvar Yb = Wa.string().or(Wa.number()).transform((e35) =\u003e kb(e35).value);\nvar Xb = Wa.string().or(Wa.number()).transform((e35) =\u003e kb(e35).value);\nvar Hb = Xb;\nvar Vb = Xb;\nvar Wb = Wa.string().datetime();\nvar Gb = Wa.string().or(Wa.number()).transform((e35) =\u003e typeof e35 == \"number\" ? e35 : e35.endsWith(\"deg\") ? Number.parseFloat(e35.split(\"deg\")[0]) : e35.endsWith(\"rad\") ? 180 * Number.parseFloat(e35.split(\"rad\")[0]) / Math.PI : Number.parseFloat(e35));\nvar Ub = Wa.number().or(Wa.string().endsWith(\"mAh\")).transform((e35) =\u003e {\n if (typeof e35 == \"string\") {\n const t2 = e35.replace(\"mAh\", \"\"), n2 = Number.parseFloat(t2);\n if (Number.isNaN(n2))\n throw new Error(\"Invalid capacity\");\n return n2;\n }\n return e35;\n}).describe(\"Battery capacity in mAh\");\nvar Zb = Wa.object({ x: $b, y: $b });\nvar qb = Zb;\nvar Jb = Wa.object({ x: $b, y: $b, z: $b });\nvar Qb = Jb;\nvar Kb = Wa.object({ width: Wa.number(), height: Wa.number() });\nvar ex = (e35) =\u003e Wa.string().optional().default(() =\u003e `${e35}_${((e36) =\u003e {\n const t2 = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\";\n return Array.from({ length: e36 }, () =\u003e t2[Math.floor(62 * Math.random())]).join(\"\");\n})(10)}`);\nvar tx = Wa.enum([\"top_left\", \"top_center\", \"top_right\", \"center_left\", \"center\", \"center_right\", \"bottom_left\", \"bottom_center\", \"bottom_right\"]);\nvar nx = Wa.enum([\"top_silkscreen\", \"bottom_silkscreen\", \"top_copper\", \"bottom_copper\", \"top_soldermask\", \"bottom_soldermask\", \"top_fabrication_note\", \"bottom_fabrication_note\", \"top_user_note\", \"bottom_user_note\", \"top_courtyard\", \"bottom_courtyard\", \"inner1_copper\", \"inner2_copper\", \"inner3_copper\", \"inner4_copper\", \"inner5_copper\", \"inner6_copper\", \"edge_cuts\", \"drill\"]);\nvar ox = Wa.object({ project_relative_path: Wa.string(), url: Wa.string(), mimetype: Wa.string() });\nvar ix = Zb.extend({ rotation: Gb.optional() });\nvar rx = Wa.object({ size: Zb.optional(), thickness: $b.optional() });\nvar sx = Wa.object({ font: rx.optional() });\nvar ax = Wa.object({ value: Wa.string(), at: ix.optional(), layer: Wa.string().optional(), uuid: Wa.string().optional(), hide: Wa.boolean().optional(), effects: sx.optional() });\nvar cx = Wa.object({ Reference: ax.optional(), Value: ax.optional(), Datasheet: ax.optional(), Description: ax.optional() });\nvar lx = Wa.object({ through_hole: Wa.boolean().optional(), smd: Wa.boolean().optional(), exclude_from_pos_files: Wa.boolean().optional(), exclude_from_bom: Wa.boolean().optional() });\nvar hx = Wa.object({ name: Wa.string(), type: Wa.string(), shape: Wa.string().optional(), at: ix.optional(), size: Zb.optional(), drill: $b.optional(), layers: Wa.array(Wa.string()).optional(), removeUnusedLayers: Wa.boolean().optional(), uuid: Wa.string().optional() });\nvar dx = Wa.object({ path: Wa.string(), offset: Jb.optional(), scale: Jb.optional(), rotate: Jb.optional() });\nvar ux = Wa.object({ footprintName: Wa.string().optional(), version: Wa.union([Wa.number(), Wa.string()]).optional(), generator: Wa.string().optional(), generatorVersion: Wa.union([Wa.number(), Wa.string()]).optional(), layer: Wa.string().optional(), properties: cx.optional(), attributes: lx.optional(), pads: Wa.array(hx).optional(), embeddedFonts: Wa.boolean().optional(), model: dx.optional() });\nvar px = Wa.object({ hide: Wa.boolean().optional() });\nvar mx = Wa.object({ offset: $b.optional(), hide: Wa.boolean().optional() });\nvar gx = Wa.object({ font: rx.optional(), justify: Wa.union([Wa.string(), Wa.array(Wa.string())]).optional(), hide: Wa.boolean().optional() });\nvar fx = Wa.object({ value: Wa.string(), id: Wa.union([Wa.number(), Wa.string()]).optional(), at: ix.optional(), effects: gx.optional() });\nvar _x = Wa.object({ Reference: fx.optional(), Value: fx.optional(), Footprint: fx.optional(), Datasheet: fx.optional(), Description: fx.optional(), ki_keywords: fx.optional(), ki_fp_filters: fx.optional() });\nvar yx = Wa.object({ symbolName: Wa.string().optional(), extends: Wa.string().optional(), pinNumbers: px.optional(), pinNames: mx.optional(), excludeFromSim: Wa.boolean().optional(), inBom: Wa.boolean().optional(), onBoard: Wa.boolean().optional(), properties: _x.optional(), embeddedFonts: Wa.boolean().optional() });\nvar bx = Wa.object({ error_type: Wa.string(), message: Wa.string(), is_fatal: Wa.boolean().optional() });\nvar xx = Wa.enum([\"jlcpcb\", \"macrofab\", \"pcbway\", \"digikey\", \"mouser\", \"lcsc\"]);\nvar vx = Wa.object({ type: Wa.literal(\"source_component\"), ftype: Wa.string().optional(), source_component_id: Wa.string(), name: Wa.string(), manufacturer_part_number: Wa.string().optional(), supplier_part_numbers: Wa.record(xx, Wa.array(Wa.string())).optional(), display_value: Wa.string().optional(), display_name: Wa.string().optional(), are_pins_interchangeable: Wa.boolean().optional(), internally_connected_source_port_ids: Wa.array(Wa.array(Wa.string())).optional(), source_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() });\nvar Ix = vx.extend({ ftype: Wa.literal(\"simple_capacitor\"), capacitance: Lb, max_voltage_rating: Bb.optional(), display_capacitance: Wa.string().optional(), max_decoupling_trace_length: $b.optional() });\nvar Sx = vx.extend({ ftype: Wa.literal(\"simple_resistor\"), resistance: Db, display_resistance: Wa.string().optional() });\nvar Cx = vx.extend({ ftype: Wa.literal(\"simple_diode\") });\nvar Px = vx.extend({ ftype: Wa.literal(\"simple_fiducial\") });\nvar Mx = Cx.extend({ ftype: Wa.literal(\"simple_led\"), color: Wa.string().optional(), wavelength: Wa.string().optional() });\nvar wx = vx.extend({ ftype: Wa.literal(\"simple_ground\") });\nvar Nx = vx.extend({ ftype: Wa.literal(\"simple_chip\") });\nvar Rx = vx.extend({ ftype: Wa.literal(\"simple_power_source\"), voltage: Bb });\nvar Tx = vx.extend({ ftype: Wa.literal(\"simple_current_source\"), current: Yb, frequency: jb.optional(), peak_to_peak_current: Yb.optional(), wave_shape: Wa.enum([\"sine\", \"square\", \"triangle\", \"sawtooth\", \"dc\"]).optional().default(\"dc\"), phase: Wa.number().optional(), duty_cycle: Wa.number().min(0).max(1).optional() });\nvar Ex = Wa.object({ must_be_connected: Wa.boolean().optional(), provides_power: Wa.boolean().optional(), requires_power: Wa.boolean().optional(), provides_ground: Wa.boolean().optional(), requires_ground: Wa.boolean().optional(), provides_voltage: Wa.union([Wa.string(), Wa.number()]).optional(), requires_voltage: Wa.union([Wa.string(), Wa.number()]).optional(), do_not_connect: Wa.boolean().optional(), include_in_board_pinout: Wa.boolean().optional(), can_use_internal_pullup: Wa.boolean().optional(), is_using_internal_pullup: Wa.boolean().optional(), needs_external_pullup: Wa.boolean().optional(), can_use_internal_pulldown: Wa.boolean().optional(), is_using_internal_pulldown: Wa.boolean().optional(), needs_external_pulldown: Wa.boolean().optional(), can_use_open_drain: Wa.boolean().optional(), is_using_open_drain: Wa.boolean().optional(), can_use_push_pull: Wa.boolean().optional(), is_using_push_pull: Wa.boolean().optional(), should_have_decoupling_capacitor: Wa.boolean().optional(), recommended_decoupling_capacitor_capacitance: Wa.union([Wa.string(), Wa.number()]).optional(), is_configured_for_i2c_sda: Wa.boolean().optional(), is_configured_for_i2c_scl: Wa.boolean().optional(), is_configured_for_spi_mosi: Wa.boolean().optional(), is_configured_for_spi_miso: Wa.boolean().optional(), is_configured_for_spi_sck: Wa.boolean().optional(), is_configured_for_spi_cs: Wa.boolean().optional(), is_configured_for_uart_tx: Wa.boolean().optional(), is_configured_for_uart_rx: Wa.boolean().optional(), supports_i2c_sda: Wa.boolean().optional(), supports_i2c_scl: Wa.boolean().optional(), supports_spi_mosi: Wa.boolean().optional(), supports_spi_miso: Wa.boolean().optional(), supports_spi_sck: Wa.boolean().optional(), supports_spi_cs: Wa.boolean().optional(), supports_uart_tx: Wa.boolean().optional(), supports_uart_rx: Wa.boolean().optional() });\nvar Ax = vx.extend({ ftype: Wa.literal(\"simple_fuse\"), current_rating_amps: Wa.number().describe(\"Nominal current in amps the fuse is rated for\"), voltage_rating_volts: Wa.number().describe(\"Voltage rating in volts, e.g. ±5V would be 5\") });\nvar Ox = vx.extend({ ftype: Wa.literal(\"simple_battery\"), capacity: Ub });\nvar kx = vx.extend({ ftype: Wa.literal(\"simple_inductor\"), inductance: zb, display_inductance: Wa.string().optional(), max_current_rating: Wa.number().optional() });\nvar Dx = vx.extend({ ftype: Wa.literal(\"simple_push_button\") });\nvar Lx = vx.extend({ ftype: Wa.literal(\"simple_potentiometer\"), max_resistance: Db, display_max_resistance: Wa.string().optional() });\nvar zx = vx.extend({ ftype: Wa.literal(\"simple_crystal\"), frequency: Wa.number().describe(\"Frequency in Hz\"), load_capacitance: Wa.number().optional().describe(\"Load capacitance in pF\"), pin_variant: Wa.enum([\"two_pin\", \"four_pin\"]).optional() });\nvar Bx = vx.extend({ ftype: Wa.literal(\"simple_pin_header\"), pin_count: Wa.number(), gender: Wa.enum([\"male\", \"female\"]).optional().default(\"male\") });\nvar Fx = vx.extend({ ftype: Wa.literal(\"simple_connector\"), standard: Wa.enum([\"usb_c\", \"m2\"]).optional() });\nvar jx = vx.extend({ ftype: Wa.literal(\"simple_pinout\") });\nvar $x = vx.extend({ ftype: Wa.literal(\"simple_resonator\"), load_capacitance: Lb, equivalent_series_resistance: Db.optional(), frequency: jb });\nvar Yx = vx.extend({ ftype: Wa.literal(\"simple_transistor\"), transistor_type: Wa.enum([\"npn\", \"pnp\"]) });\nvar Xx = vx.extend({ ftype: Wa.literal(\"simple_test_point\"), footprint_variant: Wa.enum([\"pad\", \"through_hole\"]).optional(), pad_shape: Wa.enum([\"rect\", \"circle\"]).optional(), pad_diameter: Wa.union([Wa.number(), Wa.string()]).optional(), hole_diameter: Wa.union([Wa.number(), Wa.string()]).optional(), width: Wa.union([Wa.number(), Wa.string()]).optional(), height: Wa.union([Wa.number(), Wa.string()]).optional() });\nvar Hx = vx.extend({ ftype: Wa.literal(\"simple_mosfet\"), channel_type: Wa.enum([\"n\", \"p\"]), mosfet_mode: Wa.enum([\"enhancement\", \"depletion\"]) });\nvar Vx = vx.extend({ ftype: Wa.literal(\"simple_op_amp\") });\nvar Wx = vx.extend({ ftype: Wa.literal(\"simple_switch\") });\nvar Gx = Wa.object({ type: Wa.literal(\"source_project_metadata\"), name: Wa.string().optional(), software_used_string: Wa.string().optional(), project_url: Wa.string().optional(), created_at: Wb.optional() });\nvar Ux = bx.extend({ type: Wa.literal(\"source_missing_property_error\"), source_missing_property_error_id: ex(\"source_missing_property_error\"), source_component_id: Wa.string(), property_name: Wa.string(), subcircuit_id: Wa.string().optional(), error_type: Wa.literal(\"source_missing_property_error\").default(\"source_missing_property_error\") }).describe(\"The source code is missing a property\");\nvar Zx = bx.extend({ type: Wa.literal(\"source_failed_to_create_component_error\"), source_failed_to_create_component_error_id: ex(\"source_failed_to_create_component_error\"), error_type: Wa.literal(\"source_failed_to_create_component_error\").default(\"source_failed_to_create_component_error\"), component_name: Wa.string().optional(), subcircuit_id: Wa.string().optional(), parent_source_component_id: Wa.string().optional(), pcb_center: Wa.object({ x: Wa.number().optional(), y: Wa.number().optional() }).optional(), schematic_center: Wa.object({ x: Wa.number().optional(), y: Wa.number().optional() }).optional() }).describe(\"Error emitted when a component fails to be constructed\");\nvar qx = bx.extend({ type: Wa.literal(\"source_invalid_component_property_error\"), source_invalid_component_property_error_id: ex(\"source_invalid_component_property_error\"), source_component_id: Wa.string(), property_name: Wa.string(), property_value: Wa.unknown().optional(), expected_format: Wa.string().optional(), subcircuit_id: Wa.string().optional(), error_type: Wa.literal(\"source_invalid_component_property_error\").default(\"source_invalid_component_property_error\") }).describe(\"The source component property is invalid\");\nvar Jx = bx.extend({ type: Wa.literal(\"source_trace_not_connected_error\"), source_trace_not_connected_error_id: ex(\"source_trace_not_connected_error\"), error_type: Wa.literal(\"source_trace_not_connected_error\").default(\"source_trace_not_connected_error\"), subcircuit_id: Wa.string().optional(), source_group_id: Wa.string().optional(), source_trace_id: Wa.string().optional(), connected_source_port_ids: Wa.array(Wa.string()).optional(), selectors_not_found: Wa.array(Wa.string()).optional() }).describe(\"Occurs when a source trace selector does not match any ports\");\nvar Qx = Wa.object({ type: Wa.literal(\"source_property_ignored_warning\"), source_property_ignored_warning_id: ex(\"source_property_ignored_warning\"), source_component_id: Wa.string(), property_name: Wa.string(), subcircuit_id: Wa.string().optional(), error_type: Wa.literal(\"source_property_ignored_warning\").default(\"source_property_ignored_warning\"), message: Wa.string() }).describe(\"The source property was ignored\");\nvar Kx = Wa.object({ type: Wa.literal(\"source_pin_missing_trace_warning\"), source_pin_missing_trace_warning_id: ex(\"source_pin_missing_trace_warning\"), warning_type: Wa.literal(\"source_pin_missing_trace_warning\").default(\"source_pin_missing_trace_warning\"), message: Wa.string(), source_component_id: Wa.string(), source_port_id: Wa.string(), subcircuit_id: Wa.string().optional() }).describe(\"Warning emitted when a source component pin is missing a trace connection\");\nvar ev = Wa.object({ type: Wa.literal(\"source_missing_manufacturer_part_number_warning\"), source_missing_manufacturer_part_number_warning_id: ex(\"source_missing_manufacturer_part_number_warning\"), warning_type: Wa.literal(\"source_missing_manufacturer_part_number_warning\").default(\"source_missing_manufacturer_part_number_warning\"), message: Wa.string(), source_component_id: Wa.string(), standard: Wa.string(), subcircuit_id: Wa.string().optional() }).describe(\"Warning emitted when a standard connector is missing manufacturer part number\");\nvar tv = vx.extend({ ftype: Wa.literal(\"simple_voltage_probe\") });\nvar nv = vx.extend({ ftype: Wa.literal(\"interconnect\") });\nvar ov = bx.extend({ type: Wa.literal(\"source_i2c_misconfigured_error\"), source_i2c_misconfigured_error_id: ex(\"source_i2c_misconfigured_error\"), error_type: Wa.literal(\"source_i2c_misconfigured_error\").default(\"source_i2c_misconfigured_error\"), source_port_ids: Wa.array(Wa.string()) }).describe(\"Error emitted when incompatible I2C pins (e.g. SDA and SCL) are connected to the same net\");\nvar iv = vx.extend({ ftype: Wa.literal(\"simple_voltage_source\"), voltage: Bb, frequency: jb.optional(), peak_to_peak_voltage: Bb.optional(), wave_shape: Wa.enum([\"sinewave\", \"square\", \"triangle\", \"sawtooth\"]).optional(), phase: Gb.optional(), duty_cycle: Wa.number().optional().describe(\"Duty cycle as a fraction (0 to 1)\") });\nvar rv = Wa.union([Sx, Ix, Cx, Px, Mx, wx, Nx, Rx, Tx, Ox, kx, Dx, Lx, zx, Bx, Fx, jx, $x, Wx, Yx, Xx, Hx, Vx, Ax, tv, nv, iv, Gx, Ux, qx, Zx, Jx, Qx, Kx, ev, ov]);\nvar sv = Wa.object({ type: Wa.literal(\"source_port\"), pin_number: Wa.number().optional(), port_hints: Wa.array(Wa.string()).optional(), name: Wa.string(), source_port_id: Wa.string(), source_component_id: Wa.string().optional(), source_group_id: Wa.string().optional(), most_frequently_referenced_by_name: Wa.string().optional(), subcircuit_id: Wa.string().optional(), subcircuit_connectivity_map_key: Wa.string().optional() }).merge(Ex);\nvar av = Wa.object({ type: Wa.literal(\"source_component_internal_connection\"), source_component_internal_connection_id: Wa.string(), source_component_id: Wa.string(), source_port_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() });\nvar cv = Wa.object({ type: Wa.literal(\"source_trace\"), source_trace_id: Wa.string(), connected_source_port_ids: Wa.array(Wa.string()), connected_source_net_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional(), subcircuit_connectivity_map_key: Wa.string().optional(), max_length: Wa.number().optional(), min_trace_thickness: Wa.number().optional(), display_name: Wa.string().optional() });\nvar lv = Wa.object({ type: Wa.literal(\"source_group\"), source_group_id: Wa.string(), subcircuit_id: Wa.string().optional(), parent_subcircuit_id: Wa.string().optional(), parent_source_group_id: Wa.string().optional(), is_subcircuit: Wa.boolean().optional(), show_as_schematic_box: Wa.boolean().optional(), name: Wa.string().optional(), was_automatically_named: Wa.boolean().optional() });\nvar hv = Wa.object({ type: Wa.literal(\"source_net\"), source_net_id: Wa.string(), name: Wa.string(), member_source_group_ids: Wa.array(Wa.string()), is_power: Wa.boolean().optional(), is_ground: Wa.boolean().optional(), is_digital_signal: Wa.boolean().optional(), is_analog_signal: Wa.boolean().optional(), is_positive_voltage_source: Wa.boolean().optional(), trace_width: Wa.number().optional(), subcircuit_id: Wa.string().optional(), subcircuit_connectivity_map_key: Wa.string().optional() });\nvar dv = Wa.object({ type: Wa.literal(\"source_board\"), source_board_id: Wa.string(), source_group_id: Wa.string(), title: Wa.string().optional() }).describe(\"Defines a board in the source domain\");\nvar uv = bx.extend({ type: Wa.literal(\"source_ambiguous_port_reference\"), source_ambiguous_port_reference_id: ex(\"source_ambiguous_port_reference\"), error_type: Wa.literal(\"source_ambiguous_port_reference\").default(\"source_ambiguous_port_reference\"), source_port_id: Wa.string().optional(), source_component_id: Wa.string().optional() }).describe(\"Error emitted when a port hint matches multiple non-overlapping pads, making the port reference ambiguous\");\nvar pv = Wa.object({ type: Wa.literal(\"source_pcb_ground_plane\"), source_pcb_ground_plane_id: Wa.string(), source_group_id: Wa.string(), source_net_id: Wa.string(), subcircuit_id: Wa.string().optional() }).describe(\"Defines a ground plane in the source domain\");\nvar mv = [\"top\", \"bottom\", \"inner1\", \"inner2\", \"inner3\", \"inner4\", \"inner5\", \"inner6\"];\nvar gv = Wa.enum(mv);\nvar fv = gv.or(Wa.object({ name: gv })).transform((e35) =\u003e typeof e35 == \"string\" ? e35 : e35.name);\nvar _v = Wa.enum([\"top\", \"bottom\"]);\nvar yv = Wa.object({ type: Wa.literal(\"source_manually_placed_via\"), source_manually_placed_via_id: Wa.string(), source_group_id: Wa.string(), source_net_id: Wa.string(), subcircuit_id: Wa.string().optional(), source_trace_id: Wa.string().optional() }).describe(\"Defines a via that is manually placed in the source domain\");\nvar bv = Wa.object({ type: Wa.literal(\"source_no_power_pin_defined_warning\"), source_no_power_pin_defined_warning_id: ex(\"source_no_power_pin_defined_warning\"), warning_type: Wa.literal(\"source_no_power_pin_defined_warning\").default(\"source_no_power_pin_defined_warning\"), message: Wa.string(), source_component_id: Wa.string(), source_port_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe(\"Warning emitted when a chip has no source ports with requires_power=true\");\nvar xv = Wa.object({ type: Wa.literal(\"source_no_ground_pin_defined_warning\"), source_no_ground_pin_defined_warning_id: ex(\"source_no_ground_pin_defined_warning\"), warning_type: Wa.literal(\"source_no_ground_pin_defined_warning\").default(\"source_no_ground_pin_defined_warning\"), message: Wa.string(), source_component_id: Wa.string(), source_port_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe(\"Warning emitted when a chip has no source ports marked as ground pins\");\nvar vv = Wa.object({ type: Wa.literal(\"source_component_pins_underspecified_warning\"), source_component_pins_underspecified_warning_id: ex(\"source_component_pins_underspecified_warning\"), warning_type: Wa.literal(\"source_component_pins_underspecified_warning\").default(\"source_component_pins_underspecified_warning\"), message: Wa.string(), source_component_id: Wa.string(), source_port_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe(\"Warning emitted when all ports on a source component are underspecified\");\nvar Iv = bx.extend({ type: Wa.literal(\"source_pin_must_be_connected_error\"), source_pin_must_be_connected_error_id: ex(\"source_pin_must_be_connected_error\"), error_type: Wa.literal(\"source_pin_must_be_connected_error\").default(\"source_pin_must_be_connected_error\"), source_component_id: Wa.string(), source_port_id: Wa.string(), subcircuit_id: Wa.string().optional() }).describe(\"Error emitted when a pin with mustBeConnected attribute is not connected to any trace\");\nvar Sv = bx.extend({ type: Wa.literal(\"unknown_error_finding_part\"), unknown_error_finding_part_id: ex(\"unknown_error_finding_part\"), error_type: Wa.literal(\"unknown_error_finding_part\").default(\"unknown_error_finding_part\"), source_component_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe(\"Error emitted when an unexpected error occurs while finding a part\");\nvar Cv = Wa.object({ type: Wa.literal(\"schematic_box\"), schematic_component_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), width: $b, height: $b, is_dashed: Wa.boolean().default(false), x: $b, y: $b, subcircuit_id: Wa.string().optional() }).describe(\"Draws a box on the schematic\");\nvar Pv = Wa.object({ type: Wa.literal(\"schematic_path\"), schematic_path_id: ex(\"schematic_path\"), schematic_component_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), fill_color: Wa.string().optional(), is_filled: Wa.boolean().optional(), stroke_width: $b.nullable().optional(), stroke_color: Wa.string().optional(), points: Wa.array(Zb), subcircuit_id: Wa.string().optional() });\nvar Mv = Wa.record(Wa.object({ left_margin: Fb.optional(), right_margin: Fb.optional(), top_margin: Fb.optional(), bottom_margin: Fb.optional() }));\nvar wv = Wa.object({ left_size: Wa.number(), right_size: Wa.number(), top_size: Wa.number().optional(), bottom_size: Wa.number().optional() });\nvar Nv = Wa.object({ left_side: Wa.object({ pins: Wa.array(Wa.number()), direction: Wa.enum([\"top-to-bottom\", \"bottom-to-top\"]).optional() }).optional(), right_side: Wa.object({ pins: Wa.array(Wa.number()), direction: Wa.enum([\"top-to-bottom\", \"bottom-to-top\"]).optional() }).optional(), top_side: Wa.object({ pins: Wa.array(Wa.number()), direction: Wa.enum([\"left-to-right\", \"right-to-left\"]).optional() }).optional(), bottom_side: Wa.object({ pins: Wa.array(Wa.number()), direction: Wa.enum([\"left-to-right\", \"right-to-left\"]).optional() }).optional() });\nvar Rv = Wa.union([wv, Nv]);\nvar Tv = Wa.object({ type: Wa.literal(\"schematic_component\"), size: Kb, center: Zb, source_component_id: Wa.string().optional(), schematic_component_id: Wa.string(), schematic_symbol_id: Wa.string().optional(), pin_spacing: Fb.optional(), pin_styles: Mv.optional(), box_width: Fb.optional(), symbol_name: Wa.string().optional(), port_arrangement: Rv.optional(), port_labels: Wa.record(Wa.string()).optional(), symbol_display_value: Wa.string().optional(), subcircuit_id: Wa.string().optional(), schematic_group_id: Wa.string().optional(), is_schematic_group: Wa.boolean().optional(), source_group_id: Wa.string().optional(), is_box_with_pins: Wa.boolean().optional().default(true) });\nvar Ev = Wa.object({ kicad_symbol: yx.optional() }).catchall(Wa.unknown());\nvar Av = Wa.object({ type: Wa.literal(\"schematic_symbol\"), schematic_symbol_id: Wa.string(), name: Wa.string().optional(), metadata: Ev.optional() }).describe(\"Defines a named schematic symbol that can be referenced by components.\");\nvar Ov = Wa.object({ type: Wa.literal(\"schematic_line\"), schematic_line_id: ex(\"schematic_line\"), schematic_component_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), x1: $b, y1: $b, x2: $b, y2: $b, stroke_width: $b.nullable().optional(), color: Wa.string().default(\"#000000\"), is_dashed: Wa.boolean().default(false), subcircuit_id: Wa.string().optional() }).describe(\"Draws a styled line on the schematic\");\nvar kv = Wa.object({ type: Wa.literal(\"schematic_rect\"), schematic_rect_id: ex(\"schematic_rect\"), schematic_component_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), center: Zb, width: $b, height: $b, rotation: Gb.default(0), stroke_width: $b.nullable().optional(), color: Wa.string().default(\"#000000\"), is_filled: Wa.boolean().default(false), fill_color: Wa.string().optional(), is_dashed: Wa.boolean().default(false), subcircuit_id: Wa.string().optional() }).describe(\"Draws a styled rectangle on the schematic\");\nvar Dv = Wa.object({ type: Wa.literal(\"schematic_circle\"), schematic_circle_id: ex(\"schematic_circle\"), schematic_component_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), center: Zb, radius: $b, stroke_width: $b.nullable().optional(), color: Wa.string().default(\"#000000\"), is_filled: Wa.boolean().default(false), fill_color: Wa.string().optional(), is_dashed: Wa.boolean().default(false), subcircuit_id: Wa.string().optional() }).describe(\"Draws a styled circle on the schematic\");\nvar Lv = Wa.object({ type: Wa.literal(\"schematic_arc\"), schematic_arc_id: ex(\"schematic_arc\"), schematic_component_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), center: Zb, radius: $b, start_angle_degrees: Gb, end_angle_degrees: Gb, direction: Wa.enum([\"clockwise\", \"counterclockwise\"]).default(\"counterclockwise\"), stroke_width: $b.nullable().optional(), color: Wa.string().default(\"#000000\"), is_dashed: Wa.boolean().default(false), subcircuit_id: Wa.string().optional() }).describe(\"Draws a styled arc on the schematic\");\nvar zv = Wa.object({ type: Wa.literal(\"schematic_trace\"), schematic_trace_id: Wa.string(), source_trace_id: Wa.string().optional(), junctions: Wa.array(Wa.object({ x: Wa.number(), y: Wa.number() })), edges: Wa.array(Wa.object({ from: Wa.object({ x: Wa.number(), y: Wa.number() }), to: Wa.object({ x: Wa.number(), y: Wa.number() }), is_crossing: Wa.boolean().optional(), from_schematic_port_id: Wa.string().optional(), to_schematic_port_id: Wa.string().optional() })), subcircuit_id: Wa.string().optional(), subcircuit_connectivity_map_key: Wa.string().optional() });\nvar Bv = Wa.enum([\"center\", \"left\", \"right\", \"top\", \"bottom\"]);\nvar Fv = Wa.object({ type: Wa.literal(\"schematic_text\"), schematic_component_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), schematic_text_id: Wa.string(), text: Wa.string(), font_size: Wa.number().default(0.18), position: Wa.object({ x: $b, y: $b }), rotation: Wa.number().default(0), anchor: Wa.union([Bv.describe(\"legacy\"), tx]).default(\"center\"), color: Wa.string().default(\"#000000\"), subcircuit_id: Wa.string().optional() });\nvar jv = Wa.object({ type: Wa.literal(\"schematic_port\"), schematic_port_id: Wa.string(), source_port_id: Wa.string(), schematic_component_id: Wa.string().optional(), center: Zb, facing_direction: Wa.enum([\"up\", \"down\", \"left\", \"right\"]).optional(), distance_from_component_edge: Wa.number().optional(), side_of_component: Wa.enum([\"top\", \"bottom\", \"left\", \"right\"]).optional(), true_ccw_index: Wa.number().optional(), pin_number: Wa.number().optional(), display_pin_label: Wa.string().optional(), subcircuit_id: Wa.string().optional(), is_connected: Wa.boolean().optional(), has_input_arrow: Wa.boolean().optional(), has_output_arrow: Wa.boolean().optional(), is_drawn_with_inversion_circle: Wa.boolean().optional() }).describe(\"Defines a port on a schematic component\");\nvar $v = Wa.object({ type: Wa.literal(\"schematic_net_label\"), schematic_net_label_id: ex(\"schematic_net_label\"), schematic_trace_id: Wa.string().optional(), source_trace_id: Wa.string().optional(), source_net_id: Wa.string(), center: Zb, anchor_position: Zb.optional(), anchor_side: Wa.enum([\"top\", \"bottom\", \"left\", \"right\"]), text: Wa.string(), symbol_name: Wa.string().optional(), is_movable: Wa.boolean().optional(), subcircuit_id: Wa.string().optional() });\nvar Yv = bx.extend({ type: Wa.literal(\"schematic_error\"), schematic_error_id: Wa.string(), error_type: Wa.literal(\"schematic_port_not_found\").default(\"schematic_port_not_found\"), subcircuit_id: Wa.string().optional() }).describe(\"Defines a schematic error on the schematic\");\nvar Xv = bx.extend({ type: Wa.literal(\"schematic_layout_error\"), schematic_layout_error_id: ex(\"schematic_layout_error\"), error_type: Wa.literal(\"schematic_layout_error\").default(\"schematic_layout_error\"), source_group_id: Wa.string(), schematic_group_id: Wa.string(), subcircuit_id: Wa.string().optional() }).describe(\"Error emitted when schematic layout fails for a group\");\nvar Hv = Wa.object({ type: Wa.literal(\"schematic_debug_object\"), label: Wa.string().optional(), subcircuit_id: Wa.string().optional() });\nvar Vv = Hv.extend({ shape: Wa.literal(\"rect\"), center: Zb, size: Kb });\nvar Wv = Hv.extend({ shape: Wa.literal(\"line\"), start: Zb, end: Zb });\nvar Gv = Hv.extend({ shape: Wa.literal(\"point\"), center: Zb });\nvar Uv = Wa.discriminatedUnion(\"shape\", [Vv, Wv, Gv]);\nvar Zv = Wa.object({ type: Wa.literal(\"schematic_voltage_probe\"), schematic_voltage_probe_id: Wa.string(), source_component_id: Wa.string().optional(), name: Wa.string().optional(), position: Zb, schematic_trace_id: Wa.string(), voltage: Bb.optional(), subcircuit_id: Wa.string().optional(), color: Wa.string().optional(), label_alignment: tx.optional() }).describe(\"Defines a voltage probe measurement point on a schematic trace\");\nvar qv = Wa.object({ type: Wa.literal(\"schematic_manual_edit_conflict_warning\"), schematic_manual_edit_conflict_warning_id: ex(\"schematic_manual_edit_conflict_warning\"), warning_type: Wa.literal(\"schematic_manual_edit_conflict_warning\").default(\"schematic_manual_edit_conflict_warning\"), message: Wa.string(), schematic_component_id: Wa.string(), schematic_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), source_component_id: Wa.string() }).describe(\"Warning emitted when a component has both manual placement and explicit schX/schY coordinates\");\nvar Jv = Wa.object({ type: Wa.literal(\"schematic_group\"), schematic_group_id: ex(\"schematic_group\"), source_group_id: Wa.string(), is_subcircuit: Wa.boolean().optional(), subcircuit_id: Wa.string().optional(), width: Fb, height: Fb, center: Zb, schematic_component_ids: Wa.array(Wa.string()), show_as_schematic_box: Wa.boolean().optional(), name: Wa.string().optional(), description: Wa.string().optional() }).describe(\"Defines a group of components on the schematic\");\nvar Qv = Wa.object({ type: Wa.literal(\"schematic_table\"), schematic_table_id: ex(\"schematic_table\"), anchor_position: Zb, column_widths: Wa.array($b), row_heights: Wa.array($b), cell_padding: $b.optional(), border_width: $b.optional(), subcircuit_id: Wa.string().optional(), schematic_component_id: Wa.string().optional(), anchor: tx.optional() }).describe(\"Defines a table on the schematic\");\nvar Kv = Wa.object({ type: Wa.literal(\"schematic_table_cell\"), schematic_table_cell_id: ex(\"schematic_table_cell\"), schematic_table_id: Wa.string(), start_row_index: Wa.number(), end_row_index: Wa.number(), start_column_index: Wa.number(), end_column_index: Wa.number(), text: Wa.string().optional(), center: Zb, width: $b, height: $b, horizontal_align: Wa.enum([\"left\", \"center\", \"right\"]).optional(), vertical_align: Wa.enum([\"top\", \"middle\", \"bottom\"]).optional(), font_size: $b.optional(), subcircuit_id: Wa.string().optional() }).describe(\"Defines a cell within a schematic_table\");\nvar eI = Wa.object({ type: Wa.literal(\"schematic_sheet\"), schematic_sheet_id: ex(\"schematic_sheet\"), name: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe(\"Defines a schematic sheet or page that components can be placed on\");\nvar tI = Wa.object({ x: $b, y: $b, bulge: Wa.number().optional() });\nvar nI = Wa.object({ vertices: Wa.array(tI) });\nvar oI = Wa.object({ outer_ring: nI, inner_rings: Wa.array(nI).default([]) });\nvar iI = Wa.object({ x: $b, y: $b, via: Wa.boolean().optional(), via_to_layer: fv.optional() });\nvar rI = Wa.array(iI);\nvar sI = Wa.object({ x: $b, y: $b, via: Wa.boolean().optional(), to_layer: fv.optional(), trace_width: $b.optional() });\nvar aI = Wa.object({ min_trace_width: Fb.optional(), min_board_edge_clearance: Fb.optional(), min_via_hole_edge_to_via_hole_edge_clearance: Fb.optional(), min_plated_hole_drill_edge_to_drill_edge_clearance: Fb.optional(), min_trace_to_pad_edge_clearance: Fb.optional(), min_pad_edge_to_pad_edge_clearance: Fb.optional(), min_same_net_trace_edge_to_trace_edge_clearance: Fb.optional(), min_different_net_trace_edge_to_trace_edge_clearance: Fb.optional(), min_via_hole_diameter: Fb.optional(), min_via_pad_diameter: Fb.optional() });\nvar cI = Wa.object({ type: Wa.literal(\"pcb_component\"), pcb_component_id: ex(\"pcb_component\"), source_component_id: Wa.string(), center: Zb, layer: fv, rotation: Gb, display_offset_x: Wa.string().optional().describe(\"How to display the x offset for this part, usually corresponding with how the user specified it\"), display_offset_y: Wa.string().optional().describe(\"How to display the y offset for this part, usually corresponding with how the user specified it\"), width: Fb, height: Fb, do_not_place: Wa.boolean().optional(), is_allowed_to_be_off_board: Wa.boolean().optional(), subcircuit_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), position_mode: Wa.enum([\"packed\", \"relative_to_group_anchor\", \"relative_to_another_component\", \"none\"]).optional(), anchor_position: Zb.optional(), anchor_alignment: tx.optional(), positioned_relative_to_pcb_group_id: Wa.string().optional(), positioned_relative_to_pcb_board_id: Wa.string().optional(), cable_insertion_center: Zb.optional(), insertion_direction: Wa.enum([\"from_above\", \"from_left\", \"from_right\", \"from_front\", \"from_back\"]).optional(), metadata: Wa.object({ kicad_footprint: ux.optional() }).optional(), obstructs_within_bounds: Wa.boolean().default(true).describe(\"Does this component take up all the space within its bounds on a layer. This is generally true except for when separated pin headers are being represented by a single component (in which case, chips can be placed between the pin headers) or for tall modules where chips fit underneath\") }).describe(\"Defines a component on the PCB\");\nvar lI = Wa.object({ type: Wa.literal(\"pcb_hole\"), pcb_hole_id: ex(\"pcb_hole\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), pcb_component_id: Wa.string().optional(), hole_shape: Wa.literal(\"circle\"), hole_diameter: Wa.number(), x: $b, y: $b, is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });\nvar hI = lI.describe(\"Defines a circular hole on the PCB\");\nvar dI = Wa.object({ type: Wa.literal(\"pcb_hole\"), pcb_hole_id: ex(\"pcb_hole\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), pcb_component_id: Wa.string().optional(), hole_shape: Wa.literal(\"rect\"), hole_width: Wa.number(), hole_height: Wa.number(), x: $b, y: $b, is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });\nvar uI = dI.describe(\"Defines a rectangular (square-capable) hole on the PCB. Use equal width/height for square.\");\nvar pI = Wa.object({ type: Wa.literal(\"pcb_hole\"), pcb_hole_id: ex(\"pcb_hole\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), pcb_component_id: Wa.string().optional(), hole_shape: Wa.enum([\"circle\", \"square\"]), hole_diameter: Wa.number(), x: $b, y: $b, is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });\nvar mI = pI.describe(\"Defines a circular or square hole on the PCB\");\nvar gI = Wa.object({ type: Wa.literal(\"pcb_hole\"), pcb_hole_id: ex(\"pcb_hole\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), pcb_component_id: Wa.string().optional(), hole_shape: Wa.literal(\"oval\"), hole_width: Wa.number(), hole_height: Wa.number(), x: $b, y: $b, is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });\nvar fI = gI.describe(\"Defines an oval hole on the PCB\");\nvar _I = Wa.object({ type: Wa.literal(\"pcb_hole\"), pcb_hole_id: ex(\"pcb_hole\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), pcb_component_id: Wa.string().optional(), hole_shape: Wa.literal(\"pill\"), hole_width: Wa.number(), hole_height: Wa.number(), x: $b, y: $b, is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });\nvar yI = _I.describe(\"Defines a pill-shaped hole on the PCB\");\nvar bI = Wa.object({ type: Wa.literal(\"pcb_hole\"), pcb_hole_id: ex(\"pcb_hole\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), pcb_component_id: Wa.string().optional(), hole_shape: Wa.literal(\"rotated_pill\"), hole_width: Wa.number(), hole_height: Wa.number(), x: $b, y: $b, ccw_rotation: Gb, is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });\nvar xI = bI.describe(\"Defines a rotated pill-shaped hole on the PCB\");\nvar vI = pI.or(gI).or(_I).or(bI).or(lI).or(dI);\nvar II = Wa.object({ type: Wa.literal(\"pcb_plated_hole\"), shape: Wa.literal(\"circle\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), outer_diameter: Wa.number(), hole_diameter: Wa.number(), is_covered_with_solder_mask: Wa.boolean().optional(), x: $b, y: $b, layers: Wa.array(fv), port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), pcb_plated_hole_id: ex(\"pcb_plated_hole\"), soldermask_margin: Wa.number().optional() });\nvar SI = Wa.object({ type: Wa.literal(\"pcb_plated_hole\"), shape: Wa.enum([\"oval\", \"pill\"]), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), outer_width: Wa.number(), outer_height: Wa.number(), hole_width: Wa.number(), hole_height: Wa.number(), is_covered_with_solder_mask: Wa.boolean().optional(), x: $b, y: $b, ccw_rotation: Gb, layers: Wa.array(fv), port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), pcb_plated_hole_id: ex(\"pcb_plated_hole\"), soldermask_margin: Wa.number().optional() });\nvar CI = Wa.object({ type: Wa.literal(\"pcb_plated_hole\"), shape: Wa.literal(\"circular_hole_with_rect_pad\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), hole_shape: Wa.literal(\"circle\"), pad_shape: Wa.literal(\"rect\"), hole_diameter: Wa.number(), rect_pad_width: Wa.number(), rect_pad_height: Wa.number(), rect_border_radius: Wa.number().optional(), hole_offset_x: $b.default(0), hole_offset_y: $b.default(0), is_covered_with_solder_mask: Wa.boolean().optional(), x: $b, y: $b, layers: Wa.array(fv), port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), pcb_plated_hole_id: ex(\"pcb_plated_hole\"), soldermask_margin: Wa.number().optional(), rect_ccw_rotation: Gb.optional() });\nvar PI = Wa.object({ type: Wa.literal(\"pcb_plated_hole\"), shape: Wa.literal(\"pill_hole_with_rect_pad\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), hole_shape: Wa.literal(\"pill\"), pad_shape: Wa.literal(\"rect\"), hole_width: Wa.number(), hole_height: Wa.number(), rect_pad_width: Wa.number(), rect_pad_height: Wa.number(), rect_border_radius: Wa.number().optional(), hole_offset_x: $b.default(0), hole_offset_y: $b.default(0), is_covered_with_solder_mask: Wa.boolean().optional(), x: $b, y: $b, layers: Wa.array(fv), port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), pcb_plated_hole_id: ex(\"pcb_plated_hole\"), soldermask_margin: Wa.number().optional() });\nvar MI = Wa.object({ type: Wa.literal(\"pcb_plated_hole\"), shape: Wa.literal(\"rotated_pill_hole_with_rect_pad\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), hole_shape: Wa.literal(\"rotated_pill\"), pad_shape: Wa.literal(\"rect\"), hole_width: Wa.number(), hole_height: Wa.number(), hole_ccw_rotation: Gb, rect_pad_width: Wa.number(), rect_pad_height: Wa.number(), rect_border_radius: Wa.number().optional(), rect_ccw_rotation: Gb, hole_offset_x: $b.default(0), hole_offset_y: $b.default(0), is_covered_with_solder_mask: Wa.boolean().optional(), x: $b, y: $b, layers: Wa.array(fv), port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), pcb_plated_hole_id: ex(\"pcb_plated_hole\"), soldermask_margin: Wa.number().optional() });\nvar wI = Wa.object({ type: Wa.literal(\"pcb_plated_hole\"), shape: Wa.literal(\"hole_with_polygon_pad\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), hole_shape: Wa.enum([\"circle\", \"oval\", \"pill\", \"rotated_pill\"]), hole_diameter: Wa.number().optional(), hole_width: Wa.number().optional(), hole_height: Wa.number().optional(), pad_outline: Wa.array(Wa.object({ x: $b, y: $b })).min(3), hole_offset_x: $b.default(0), hole_offset_y: $b.default(0), is_covered_with_solder_mask: Wa.boolean().optional(), x: $b, y: $b, layers: Wa.array(fv), port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), pcb_plated_hole_id: ex(\"pcb_plated_hole\"), soldermask_margin: Wa.number().optional(), ccw_rotation: Gb.optional() });\nvar NI = Wa.union([II, SI, CI, PI, MI, wI]);\nvar RI = Wa.object({ type: Wa.literal(\"pcb_port\"), pcb_port_id: ex(\"pcb_port\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), source_port_id: Wa.string(), pcb_component_id: Wa.string().optional(), x: $b, y: $b, layers: Wa.array(fv), is_board_pinout: Wa.boolean().optional() }).describe(\"Defines a port on the PCB\");\nvar TI = Wa.object({ type: Wa.literal(\"pcb_smtpad\"), shape: Wa.literal(\"circle\"), pcb_smtpad_id: ex(\"pcb_smtpad\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: $b, y: $b, radius: Wa.number(), layer: fv, port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });\nvar EI = Wa.object({ type: Wa.literal(\"pcb_smtpad\"), shape: Wa.literal(\"rect\"), pcb_smtpad_id: ex(\"pcb_smtpad\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: $b, y: $b, width: Wa.number(), height: Wa.number(), rect_border_radius: Wa.number().optional(), corner_radius: Wa.number().optional(), layer: fv, port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional(), soldermask_margin_left: Wa.number().optional(), soldermask_margin_top: Wa.number().optional(), soldermask_margin_right: Wa.number().optional(), soldermask_margin_bottom: Wa.number().optional() });\nvar AI = Wa.object({ type: Wa.literal(\"pcb_smtpad\"), shape: Wa.literal(\"rotated_rect\"), pcb_smtpad_id: ex(\"pcb_smtpad\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: $b, y: $b, width: Wa.number(), height: Wa.number(), rect_border_radius: Wa.number().optional(), corner_radius: Wa.number().optional(), ccw_rotation: Gb, layer: fv, port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional(), soldermask_margin_left: Wa.number().optional(), soldermask_margin_top: Wa.number().optional(), soldermask_margin_right: Wa.number().optional(), soldermask_margin_bottom: Wa.number().optional() });\nvar OI = Wa.object({ type: Wa.literal(\"pcb_smtpad\"), shape: Wa.literal(\"pill\"), pcb_smtpad_id: ex(\"pcb_smtpad\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: $b, y: $b, width: Wa.number(), height: Wa.number(), radius: Wa.number(), layer: fv, port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });\nvar kI = Wa.object({ type: Wa.literal(\"pcb_smtpad\"), shape: Wa.literal(\"rotated_pill\"), pcb_smtpad_id: ex(\"pcb_smtpad\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: $b, y: $b, width: Wa.number(), height: Wa.number(), radius: Wa.number(), ccw_rotation: Gb, layer: fv, port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });\nvar DI = Wa.object({ type: Wa.literal(\"pcb_smtpad\"), shape: Wa.literal(\"polygon\"), pcb_smtpad_id: ex(\"pcb_smtpad\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), points: Wa.array(Zb), layer: fv, port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });\nvar LI = Wa.discriminatedUnion(\"shape\", [TI, EI, AI, kI, OI, DI]).describe(\"Defines an SMT pad on the PCB\");\nvar zI = Wa.object({ type: Wa.literal(\"pcb_solder_paste\"), shape: Wa.literal(\"circle\"), pcb_solder_paste_id: ex(\"pcb_solder_paste\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: $b, y: $b, radius: Wa.number(), layer: fv, pcb_component_id: Wa.string().optional(), pcb_smtpad_id: Wa.string().optional() });\nvar BI = Wa.object({ type: Wa.literal(\"pcb_solder_paste\"), shape: Wa.literal(\"rect\"), pcb_solder_paste_id: ex(\"pcb_solder_paste\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: $b, y: $b, width: Wa.number(), height: Wa.number(), layer: fv, pcb_component_id: Wa.string().optional(), pcb_smtpad_id: Wa.string().optional() });\nvar FI = Wa.object({ type: Wa.literal(\"pcb_solder_paste\"), shape: Wa.literal(\"pill\"), pcb_solder_paste_id: ex(\"pcb_solder_paste\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: $b, y: $b, width: Wa.number(), height: Wa.number(), radius: Wa.number(), layer: fv, pcb_component_id: Wa.string().optional(), pcb_smtpad_id: Wa.string().optional() });\nvar jI = Wa.object({ type: Wa.literal(\"pcb_solder_paste\"), shape: Wa.literal(\"rotated_rect\"), pcb_solder_paste_id: ex(\"pcb_solder_paste\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: $b, y: $b, width: Wa.number(), height: Wa.number(), ccw_rotation: $b, layer: fv, pcb_component_id: Wa.string().optional(), pcb_smtpad_id: Wa.string().optional() });\nvar $I = Wa.object({ type: Wa.literal(\"pcb_solder_paste\"), shape: Wa.literal(\"oval\"), pcb_solder_paste_id: ex(\"pcb_solder_paste\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: $b, y: $b, width: Wa.number(), height: Wa.number(), layer: fv, pcb_component_id: Wa.string().optional(), pcb_smtpad_id: Wa.string().optional() });\nvar YI = Wa.union([zI, BI, FI, jI, $I]).describe(\"Defines solderpaste on the PCB\");\nvar XI = Wa.object({ type: Wa.literal(\"pcb_text\"), pcb_text_id: ex(\"pcb_text\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), text: Wa.string(), center: Zb, layer: fv, width: Fb, height: Fb, lines: Wa.number(), align: Wa.enum([\"bottom-left\"]) }).describe(\"Defines text on the PCB\");\nvar HI = Wa.object({ route_type: Wa.literal(\"wire\"), x: $b, y: $b, width: $b, copper_pour_id: Wa.string().optional(), is_inside_copper_pour: Wa.boolean().optional(), start_pcb_port_id: Wa.string().optional(), end_pcb_port_id: Wa.string().optional(), layer: fv });\nvar VI = Wa.object({ route_type: Wa.literal(\"via\"), x: $b, y: $b, copper_pour_id: Wa.string().optional(), is_inside_copper_pour: Wa.boolean().optional(), hole_diameter: $b.optional(), outer_diameter: $b.optional(), from_layer: fv, to_layer: fv });\nvar WI = Wa.union([HI, VI]);\nvar GI = Wa.object({ type: Wa.literal(\"pcb_trace\"), source_trace_id: Wa.string().optional(), pcb_component_id: Wa.string().optional(), pcb_trace_id: ex(\"pcb_trace\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), route_thickness_mode: Wa.enum([\"constant\", \"interpolated\"]).default(\"constant\").optional(), route_order_index: Wa.number().optional(), should_round_corners: Wa.boolean().optional(), trace_length: Wa.number().optional(), highlight_color: Wa.string().optional(), route: Wa.array(WI) }).describe(\"Defines a trace on the PCB\");\nvar UI = Wa.object({ type: Wa.literal(\"pcb_trace_warning\"), pcb_trace_warning_id: ex(\"pcb_trace_warning\"), warning_type: Wa.literal(\"pcb_trace_warning\").default(\"pcb_trace_warning\"), message: Wa.string(), center: Zb.optional(), pcb_trace_id: Wa.string(), source_trace_id: Wa.string(), pcb_component_ids: Wa.array(Wa.string()), pcb_port_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe(\"Defines a trace warning on the PCB\");\nvar ZI = bx.extend({ type: Wa.literal(\"pcb_trace_error\"), pcb_trace_error_id: ex(\"pcb_trace_error\"), error_type: Wa.literal(\"pcb_trace_error\").default(\"pcb_trace_error\"), center: Zb.optional(), pcb_trace_id: Wa.string(), source_trace_id: Wa.string(), pcb_component_ids: Wa.array(Wa.string()), pcb_port_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe(\"Defines a trace error on the PCB\");\nvar qI = bx.extend({ type: Wa.literal(\"pcb_trace_missing_error\"), pcb_trace_missing_error_id: ex(\"pcb_trace_missing_error\"), error_type: Wa.literal(\"pcb_trace_missing_error\").default(\"pcb_trace_missing_error\"), center: Zb.optional(), source_trace_id: Wa.string(), pcb_component_ids: Wa.array(Wa.string()), pcb_port_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe(\"Defines an error when a source trace has no corresponding PCB trace\");\nvar JI = bx.extend({ type: Wa.literal(\"pcb_port_not_matched_error\"), pcb_error_id: ex(\"pcb_error\"), error_type: Wa.literal(\"pcb_port_not_matched_error\").default(\"pcb_port_not_matched_error\"), pcb_component_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe(\"Defines a trace error on the PCB where a port is not matched\");\nvar QI = bx.extend({ type: Wa.literal(\"pcb_port_not_connected_error\"), pcb_port_not_connected_error_id: ex(\"pcb_port_not_connected_error\"), error_type: Wa.literal(\"pcb_port_not_connected_error\").default(\"pcb_port_not_connected_error\"), pcb_port_ids: Wa.array(Wa.string()), pcb_component_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe(\"Defines an error when a pcb port is not connected to any trace\");\nvar KI = Wa.object({ type: Wa.literal(\"pcb_net\"), pcb_net_id: ex(\"pcb_net\"), source_net_id: Wa.string().optional(), highlight_color: Wa.string().optional() }).describe(\"Defines a net on the PCB\");\nvar eS = Wa.object({ type: Wa.literal(\"pcb_via\"), pcb_via_id: ex(\"pcb_via\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), subcircuit_connectivity_map_key: Wa.string().optional(), x: $b, y: $b, outer_diameter: $b.default(\"0.6mm\"), hole_diameter: $b.default(\"0.25mm\"), from_layer: fv.optional(), to_layer: fv.optional(), layers: Wa.array(fv), pcb_trace_id: Wa.string().optional(), net_is_assignable: Wa.boolean().optional(), net_assigned: Wa.boolean().optional(), is_tented: Wa.boolean().optional() }).describe(\"Defines a via on the PCB\");\nvar tS = Wa.object({ type: Wa.literal(\"pcb_board\"), pcb_board_id: ex(\"pcb_board\"), pcb_panel_id: Wa.string().optional(), carrier_pcb_board_id: Wa.string().optional(), is_subcircuit: Wa.boolean().optional(), subcircuit_id: Wa.string().optional(), is_mounted_to_carrier_board: Wa.boolean().optional(), width: Fb.optional(), height: Fb.optional(), center: Zb, display_offset_x: Wa.string().optional().describe(\"How to display the x offset for this board, usually corresponding with how the user specified it\"), display_offset_y: Wa.string().optional().describe(\"How to display the y offset for this board, usually corresponding with how the user specified it\"), thickness: Fb.optional().default(1.4), num_layers: Wa.number().optional().default(4), outline: Wa.array(Zb).optional(), shape: Wa.enum([\"rect\", \"polygon\"]).optional(), material: Wa.enum([\"fr4\", \"fr1\"]).default(\"fr4\"), anchor_position: Zb.optional(), anchor_alignment: tx.optional(), position_mode: Wa.enum([\"relative_to_panel_anchor\", \"none\"]).optional() }).merge(aI).describe(\"Defines the board outline of the PCB\");\nvar nS = Wa.object({ type: Wa.literal(\"pcb_panel\"), pcb_panel_id: ex(\"pcb_panel\"), width: Fb, height: Fb, center: Zb, thickness: Fb.optional().default(1.4), covered_with_solder_mask: Wa.boolean().optional().default(true) }).describe(\"Defines a PCB panel that can contain multiple boards\");\nvar oS = bx.extend({ type: Wa.literal(\"pcb_placement_error\"), pcb_placement_error_id: ex(\"pcb_placement_error\"), error_type: Wa.literal(\"pcb_placement_error\").default(\"pcb_placement_error\"), subcircuit_id: Wa.string().optional() }).describe(\"Defines a placement error on the PCB\");\nvar iS = bx.extend({ type: Wa.literal(\"pcb_panelization_placement_error\"), pcb_panelization_placement_error_id: ex(\"pcb_panelization_placement_error\"), error_type: Wa.literal(\"pcb_panelization_placement_error\").default(\"pcb_panelization_placement_error\"), pcb_panel_id: Wa.string().optional(), pcb_board_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe(\"Defines a panelization placement error on the PCB\");\nvar rS = Wa.object({ type: Wa.literal(\"pcb_trace_hint\"), pcb_trace_hint_id: ex(\"pcb_trace_hint\"), pcb_port_id: Wa.string(), pcb_component_id: Wa.string(), route: Wa.array(sI), subcircuit_id: Wa.string().optional() }).describe(\"A hint that can be used during generation of a PCB trace\");\nvar sS = Wa.object({ type: Wa.literal(\"pcb_silkscreen_line\"), pcb_silkscreen_line_id: ex(\"pcb_silkscreen_line\"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), stroke_width: $b.default(\"0.1mm\"), x1: $b, y1: $b, x2: $b, y2: $b, layer: _v }).describe(\"Defines a silkscreen line on the PCB\");\nvar aS = Wa.object({ type: Wa.literal(\"pcb_silkscreen_path\"), pcb_silkscreen_path_id: ex(\"pcb_silkscreen_path\"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), layer: _v, route: Wa.array(Zb), stroke_width: Fb }).describe(\"Defines a silkscreen path on the PCB\");\nvar cS = Wa.object({ type: Wa.literal(\"pcb_silkscreen_text\"), pcb_silkscreen_text_id: ex(\"pcb_silkscreen_text\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), font: Wa.literal(\"tscircuit2024\").default(\"tscircuit2024\"), font_size: $b.default(\"0.2mm\"), pcb_component_id: Wa.string(), text: Wa.string(), is_knockout: Wa.boolean().default(false).optional(), knockout_padding: Wa.object({ left: Fb, top: Fb, bottom: Fb, right: Fb }).default({ left: \"0.2mm\", top: \"0.2mm\", bottom: \"0.2mm\", right: \"0.2mm\" }).optional(), ccw_rotation: Wa.number().optional(), layer: fv, is_mirrored: Wa.boolean().default(false).optional(), anchor_position: Zb.default({ x: 0, y: 0 }), anchor_alignment: tx.default(\"center\") }).describe(\"Defines silkscreen text on the PCB\");\nvar lS = Wa.object({ type: Wa.literal(\"pcb_copper_text\"), pcb_copper_text_id: ex(\"pcb_copper_text\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), font: Wa.literal(\"tscircuit2024\").default(\"tscircuit2024\"), font_size: $b.default(\"0.2mm\"), pcb_component_id: Wa.string(), text: Wa.string(), is_knockout: Wa.boolean().default(false).optional(), knockout_padding: Wa.object({ left: Fb, top: Fb, bottom: Fb, right: Fb }).default({ left: \"0.2mm\", top: \"0.2mm\", bottom: \"0.2mm\", right: \"0.2mm\" }).optional(), ccw_rotation: Wa.number().optional(), layer: fv, is_mirrored: Wa.boolean().default(false).optional(), anchor_position: Zb.default({ x: 0, y: 0 }), anchor_alignment: tx.default(\"center\") }).describe(\"Defines copper text on the PCB\");\nvar hS = Wa.object({ type: Wa.literal(\"pcb_silkscreen_rect\"), pcb_silkscreen_rect_id: ex(\"pcb_silkscreen_rect\"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: Zb, width: Fb, height: Fb, layer: fv, stroke_width: Fb.default(\"1mm\"), corner_radius: Fb.optional(), is_filled: Wa.boolean().default(true).optional(), has_stroke: Wa.boolean().optional(), is_stroke_dashed: Wa.boolean().optional(), ccw_rotation: Wa.number().optional() }).describe(\"Defines a silkscreen rect on the PCB\");\nvar dS = Wa.object({ type: Wa.literal(\"pcb_silkscreen_circle\"), pcb_silkscreen_circle_id: ex(\"pcb_silkscreen_circle\"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: Zb, radius: Fb, layer: _v, stroke_width: Fb.default(\"1mm\"), is_filled: Wa.boolean().optional() }).describe(\"Defines a silkscreen circle on the PCB\");\nvar uS = Wa.object({ type: Wa.literal(\"pcb_silkscreen_oval\"), pcb_silkscreen_oval_id: ex(\"pcb_silkscreen_oval\"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: Zb, radius_x: $b, radius_y: $b, layer: _v, ccw_rotation: Gb.optional() }).describe(\"Defines a silkscreen oval on the PCB\");\nvar pS = Wa.object({ type: Wa.literal(\"pcb_silkscreen_pill\"), pcb_silkscreen_pill_id: ex(\"pcb_silkscreen_pill\"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: Zb, width: Fb, height: Fb, layer: fv, ccw_rotation: Wa.number().optional() }).describe(\"Defines a silkscreen pill on the PCB\");\nvar mS = Wa.object({ type: Wa.literal(\"pcb_fabrication_note_text\"), pcb_fabrication_note_text_id: ex(\"pcb_fabrication_note_text\"), subcircuit_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), font: Wa.literal(\"tscircuit2024\").default(\"tscircuit2024\"), font_size: $b.default(\"1mm\"), pcb_component_id: Wa.string(), text: Wa.string(), layer: _v, anchor_position: Zb.default({ x: 0, y: 0 }), anchor_alignment: Wa.enum([\"center\", \"top_left\", \"top_right\", \"bottom_left\", \"bottom_right\"]).default(\"center\"), color: Wa.string().optional() }).describe(\"Defines a fabrication note in text on the PCB, useful for leaving notes for assemblers or fabricators\");\nvar gS = Wa.object({ type: Wa.literal(\"pcb_fabrication_note_path\"), pcb_fabrication_note_path_id: ex(\"pcb_fabrication_note_path\"), pcb_component_id: Wa.string(), subcircuit_id: Wa.string().optional(), layer: fv, route: Wa.array(Zb), stroke_width: Fb, color: Wa.string().optional() }).describe(\"Defines a fabrication path on the PCB for fabricators or assemblers\");\nvar fS = Wa.object({ type: Wa.literal(\"pcb_fabrication_note_rect\"), pcb_fabrication_note_rect_id: ex(\"pcb_fabrication_note_rect\"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: Zb, width: Fb, height: Fb, layer: _v, stroke_width: Fb.default(\"0.1mm\"), corner_radius: Fb.optional(), is_filled: Wa.boolean().optional(), has_stroke: Wa.boolean().optional(), is_stroke_dashed: Wa.boolean().optional(), color: Wa.string().optional() }).describe(\"Defines a fabrication note rectangle on the PCB\");\nvar _S = Wa.object({ type: Wa.literal(\"pcb_fabrication_note_dimension\"), pcb_fabrication_note_dimension_id: ex(\"pcb_fabrication_note_dimension\"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), layer: _v, from: Zb, to: Zb, text: Wa.string().optional(), text_ccw_rotation: Wa.number().optional(), offset: Fb.optional(), offset_distance: Fb.optional(), offset_direction: Wa.object({ x: Wa.number(), y: Wa.number() }).optional(), font: Wa.literal(\"tscircuit2024\").default(\"tscircuit2024\"), font_size: Fb.default(\"1mm\"), color: Wa.string().optional(), arrow_size: Fb.default(\"1mm\") }).describe(\"Defines a measurement annotation within PCB fabrication notes\");\nvar yS = Wa.object({ type: Wa.literal(\"pcb_note_text\"), pcb_note_text_id: ex(\"pcb_note_text\"), pcb_component_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), name: Wa.string().optional(), font: Wa.literal(\"tscircuit2024\").default(\"tscircuit2024\"), font_size: $b.default(\"1mm\"), text: Wa.string().optional(), anchor_position: Zb.default({ x: 0, y: 0 }), anchor_alignment: Wa.enum([\"center\", \"top_left\", \"top_right\", \"bottom_left\", \"bottom_right\"]).default(\"center\"), layer: _v.default(\"top\"), is_mirrored_from_top_view: Wa.boolean().optional(), color: Wa.string().optional() }).describe(\"Defines a documentation note in text on the PCB\");\nvar bS = Wa.object({ type: Wa.literal(\"pcb_note_rect\"), pcb_note_rect_id: ex(\"pcb_note_rect\"), pcb_component_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), name: Wa.string().optional(), text: Wa.string().optional(), center: Zb, width: Fb, height: Fb, layer: _v.default(\"top\"), stroke_width: Fb.default(\"0.1mm\"), corner_radius: Fb.optional(), is_filled: Wa.boolean().optional(), has_stroke: Wa.boolean().optional(), is_stroke_dashed: Wa.boolean().optional(), color: Wa.string().optional() }).describe(\"Defines a rectangular documentation note on the PCB\");\nvar xS = Wa.object({ type: Wa.literal(\"pcb_note_path\"), pcb_note_path_id: ex(\"pcb_note_path\"), pcb_component_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), name: Wa.string().optional(), text: Wa.string().optional(), route: Wa.array(Zb), layer: _v.default(\"top\"), stroke_width: Fb.default(\"0.1mm\"), color: Wa.string().optional() }).describe(\"Defines a polyline documentation note on the PCB\");\nvar vS = Wa.object({ type: Wa.literal(\"pcb_note_line\"), pcb_note_line_id: ex(\"pcb_note_line\"), pcb_component_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), name: Wa.string().optional(), text: Wa.string().optional(), x1: $b, y1: $b, x2: $b, y2: $b, layer: _v.default(\"top\"), stroke_width: $b.default(\"0.1mm\"), color: Wa.string().optional(), is_dashed: Wa.boolean().optional() }).describe(\"Defines a straight documentation note line on the PCB\");\nvar IS = Wa.object({ type: Wa.literal(\"pcb_note_dimension\"), pcb_note_dimension_id: ex(\"pcb_note_dimension\"), pcb_component_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), name: Wa.string().optional(), from: Zb, to: Zb, text: Wa.string().optional(), text_ccw_rotation: Wa.number().optional(), offset_distance: Fb.optional(), offset_direction: Wa.object({ x: Wa.number(), y: Wa.number() }).optional(), font: Wa.literal(\"tscircuit2024\").default(\"tscircuit2024\"), font_size: Fb.default(\"1mm\"), layer: _v.default(\"top\"), color: Wa.string().optional(), arrow_size: Fb.default(\"1mm\") }).describe(\"Defines a measurement annotation within PCB documentation notes\");\nvar SS = bx.extend({ type: Wa.literal(\"pcb_footprint_overlap_error\"), pcb_error_id: ex(\"pcb_error\"), error_type: Wa.literal(\"pcb_footprint_overlap_error\").default(\"pcb_footprint_overlap_error\"), pcb_smtpad_ids: Wa.array(Wa.string()).optional(), pcb_plated_hole_ids: Wa.array(Wa.string()).optional(), pcb_hole_ids: Wa.array(Wa.string()).optional(), pcb_keepout_ids: Wa.array(Wa.string()).optional() }).describe(\"Error emitted when a pcb footprint overlaps with another element\");\nvar CS = bx.extend({ type: Wa.literal(\"pcb_courtyard_overlap_error\"), pcb_error_id: ex(\"pcb_error\"), error_type: Wa.literal(\"pcb_courtyard_overlap_error\").default(\"pcb_courtyard_overlap_error\"), pcb_component_ids: Wa.tuple([Wa.string(), Wa.string()]) }).describe(\"Error emitted when the courtyard (CrtYd) of one PCB component overlaps with the courtyard of another\");\nvar PS = Wa.object({ type: Wa.literal(\"pcb_keepout\"), shape: Wa.literal(\"rect\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: Zb, width: $b, height: $b, pcb_keepout_id: Wa.string(), layers: Wa.array(Wa.string()), description: Wa.string().optional() }).or(Wa.object({ type: Wa.literal(\"pcb_keepout\"), shape: Wa.literal(\"circle\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: Zb, radius: $b, pcb_keepout_id: Wa.string(), layers: Wa.array(Wa.string()), description: Wa.string().optional() }));\nvar MS = Wa.object({ type: Wa.literal(\"pcb_cutout\"), pcb_cutout_id: ex(\"pcb_cutout\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), pcb_board_id: Wa.string().optional(), pcb_panel_id: Wa.string().optional() });\nvar wS = MS.extend({ shape: Wa.literal(\"rect\"), center: Zb, width: Fb, height: Fb, rotation: Gb.optional(), corner_radius: Fb.optional() });\nvar NS = MS.extend({ shape: Wa.literal(\"circle\"), center: Zb, radius: Fb });\nvar RS = MS.extend({ shape: Wa.literal(\"polygon\"), points: Wa.array(Zb) });\nvar TS = MS.extend({ shape: Wa.literal(\"path\"), route: Wa.array(Zb), slot_width: Fb, slot_length: Fb.optional(), space_between_slots: Fb.optional(), slot_corner_radius: Fb.optional() });\nvar ES = Wa.discriminatedUnion(\"shape\", [wS, NS, RS, TS]).describe(\"Defines a cutout on the PCB, removing board material.\");\nvar AS = bx.extend({ type: Wa.literal(\"pcb_missing_footprint_error\"), pcb_missing_footprint_error_id: ex(\"pcb_missing_footprint_error\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), error_type: Wa.literal(\"pcb_missing_footprint_error\").default(\"pcb_missing_footprint_error\"), source_component_id: Wa.string() }).describe(\"Defines a missing footprint error on the PCB\");\nvar OS = bx.extend({ type: Wa.literal(\"external_footprint_load_error\"), external_footprint_load_error_id: ex(\"external_footprint_load_error\"), pcb_component_id: Wa.string(), source_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), footprinter_string: Wa.string().optional(), error_type: Wa.literal(\"external_footprint_load_error\").default(\"external_footprint_load_error\") }).describe(\"Defines an error when an external footprint fails to load\");\nvar kS = bx.extend({ type: Wa.literal(\"circuit_json_footprint_load_error\"), circuit_json_footprint_load_error_id: ex(\"circuit_json_footprint_load_error\"), pcb_component_id: Wa.string(), source_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), error_type: Wa.literal(\"circuit_json_footprint_load_error\").default(\"circuit_json_footprint_load_error\"), circuit_json: Wa.array(Wa.any()).optional() }).describe(\"Defines an error when a circuit JSON footprint fails to load\");\nvar DS = Wa.object({ type: Wa.literal(\"pcb_group\"), pcb_group_id: ex(\"pcb_group\"), source_group_id: Wa.string(), is_subcircuit: Wa.boolean().optional(), subcircuit_id: Wa.string().optional(), width: Fb.optional(), height: Fb.optional(), center: Zb, display_offset_x: Wa.string().optional().describe(\"How to display the x offset for this group, usually corresponding with how the user specified it\"), display_offset_y: Wa.string().optional().describe(\"How to display the y offset for this group, usually corresponding with how the user specified it\"), outline: Wa.array(Zb).optional(), anchor_position: Zb.optional(), anchor_alignment: tx.default(\"center\"), position_mode: Wa.enum([\"packed\", \"relative_to_group_anchor\", \"none\"]).optional(), positioned_relative_to_pcb_group_id: Wa.string().optional(), positioned_relative_to_pcb_board_id: Wa.string().optional(), pcb_component_ids: Wa.array(Wa.string()), child_layout_mode: Wa.enum([\"packed\", \"none\"]).optional(), name: Wa.string().optional(), description: Wa.string().optional(), layout_mode: Wa.string().optional(), autorouter_configuration: Wa.object({ trace_clearance: Fb }).optional(), autorouter_used_string: Wa.string().optional() }).describe(\"Defines a group of components on the PCB\");\nvar LS = bx.extend({ type: Wa.literal(\"pcb_autorouting_error\"), pcb_error_id: ex(\"pcb_autorouting_error\"), error_type: Wa.literal(\"pcb_autorouting_error\").default(\"pcb_autorouting_error\"), subcircuit_id: Wa.string().optional() }).describe(\"The autorouting has failed to route a portion of the board\");\nvar zS = Wa.object({ type: Wa.literal(\"pcb_manual_edit_conflict_warning\"), pcb_manual_edit_conflict_warning_id: ex(\"pcb_manual_edit_conflict_warning\"), warning_type: Wa.literal(\"pcb_manual_edit_conflict_warning\").default(\"pcb_manual_edit_conflict_warning\"), message: Wa.string(), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), source_component_id: Wa.string() }).describe(\"Warning emitted when a component has both manual placement and explicit pcbX/pcbY coordinates\");\nvar BS = Wa.enum([\"x-\", \"x+\", \"y+\", \"y-\"]);\nvar FS = Wa.object({ type: Wa.literal(\"pcb_connector_not_in_accessible_orientation_warning\"), pcb_connector_not_in_accessible_orientation_warning_id: ex(\"pcb_connector_not_in_accessible_orientation_warning\"), warning_type: Wa.literal(\"pcb_connector_not_in_accessible_orientation_warning\").default(\"pcb_connector_not_in_accessible_orientation_warning\"), message: Wa.string(), pcb_component_id: Wa.string(), source_component_id: Wa.string().optional(), pcb_board_id: Wa.string().optional(), facing_direction: BS, recommended_facing_direction: BS, subcircuit_id: Wa.string().optional() }).describe(\"Warning emitted when a connector PCB component is facing inward toward the board and should be reoriented to an outward-facing direction\");\nvar jS = Wa.object({ type: Wa.literal(\"supplier_footprint_mismatch_warning\"), supplier_footprint_mismatch_warning_id: ex(\"supplier_footprint_mismatch_warning\"), warning_type: Wa.literal(\"supplier_footprint_mismatch_warning\").default(\"supplier_footprint_mismatch_warning\"), message: Wa.string(), source_component_id: Wa.string(), pcb_component_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), supplier_name: xx.optional(), supplier_part_number: Wa.string().optional(), supplier_footprint_url: Wa.string().optional(), footprint_copper_intersection_over_union: Wa.number() }).describe(\"Warning emitted when a supplier part footprint does not match the expected footprint\");\nvar $S = Wa.object({ type: Wa.literal(\"pcb_breakout_point\"), pcb_breakout_point_id: ex(\"pcb_breakout_point\"), pcb_group_id: Wa.string(), subcircuit_id: Wa.string().optional(), source_trace_id: Wa.string().optional(), source_port_id: Wa.string().optional(), source_net_id: Wa.string().optional(), x: $b, y: $b }).describe(\"Defines a routing target within a pcb_group for a source_trace or source_net\");\nvar YS = Wa.object({ type: Wa.literal(\"pcb_ground_plane\"), pcb_ground_plane_id: ex(\"pcb_ground_plane\"), source_pcb_ground_plane_id: Wa.string(), source_net_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe(\"Defines a ground plane on the PCB\");\nvar XS = Wa.object({ type: Wa.literal(\"pcb_ground_plane_region\"), pcb_ground_plane_region_id: ex(\"pcb_ground_plane_region\"), pcb_ground_plane_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), layer: fv, points: Wa.array(Zb) }).describe(\"Defines a polygon region of a ground plane\");\nvar HS = Wa.object({ type: Wa.literal(\"pcb_thermal_spoke\"), pcb_thermal_spoke_id: ex(\"pcb_thermal_spoke\"), pcb_ground_plane_id: Wa.string(), shape: Wa.string(), spoke_count: Wa.number(), spoke_thickness: $b, spoke_inner_diameter: $b, spoke_outer_diameter: $b, pcb_plated_hole_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe(\"Pattern for connecting a ground plane to a plated hole\");\nvar VS = Wa.object({ type: Wa.literal(\"pcb_copper_pour\"), pcb_copper_pour_id: ex(\"pcb_copper_pour\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), layer: fv, source_net_id: Wa.string().optional(), covered_with_solder_mask: Wa.boolean().optional().default(true) });\nvar WS = VS.extend({ shape: Wa.literal(\"rect\"), center: Zb, width: Fb, height: Fb, rotation: Gb.optional() });\nvar GS = VS.extend({ shape: Wa.literal(\"brep\"), brep_shape: oI });\nvar US = VS.extend({ shape: Wa.literal(\"polygon\"), points: Wa.array(Zb) });\nvar ZS = Wa.discriminatedUnion(\"shape\", [WS, GS, US]).describe(\"Defines a copper pour on the PCB.\");\nvar qS = bx.extend({ type: Wa.literal(\"pcb_component_outside_board_error\"), pcb_component_outside_board_error_id: ex(\"pcb_component_outside_board_error\"), error_type: Wa.literal(\"pcb_component_outside_board_error\").default(\"pcb_component_outside_board_error\"), pcb_component_id: Wa.string(), pcb_board_id: Wa.string(), component_center: Zb, component_bounds: Wa.object({ min_x: Wa.number(), max_x: Wa.number(), min_y: Wa.number(), max_y: Wa.number() }), subcircuit_id: Wa.string().optional(), source_component_id: Wa.string().optional() }).describe(\"Error emitted when a PCB component is placed outside the board boundaries\");\nvar JS = bx.extend({ type: Wa.literal(\"pcb_component_not_on_board_edge_error\"), pcb_component_not_on_board_edge_error_id: ex(\"pcb_component_not_on_board_edge_error\"), error_type: Wa.literal(\"pcb_component_not_on_board_edge_error\").default(\"pcb_component_not_on_board_edge_error\"), pcb_component_id: Wa.string(), pcb_board_id: Wa.string(), component_center: Zb, pad_to_nearest_board_edge_distance: Wa.number(), source_component_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe(\"Error emitted when a component that must be placed on the board edge is centered away from the edge\");\nvar QS = bx.extend({ type: Wa.literal(\"pcb_component_invalid_layer_error\"), pcb_component_invalid_layer_error_id: ex(\"pcb_component_invalid_layer_error\"), error_type: Wa.literal(\"pcb_component_invalid_layer_error\").default(\"pcb_component_invalid_layer_error\"), pcb_component_id: Wa.string().optional(), source_component_id: Wa.string(), layer: fv, subcircuit_id: Wa.string().optional() }).describe(\"Error emitted when a component is placed on an invalid layer (components can only be on 'top' or 'bottom' layers)\");\nvar KS = bx.extend({ type: Wa.literal(\"pcb_via_clearance_error\"), pcb_error_id: ex(\"pcb_error\"), error_type: Wa.literal(\"pcb_via_clearance_error\").default(\"pcb_via_clearance_error\"), pcb_via_ids: Wa.array(Wa.string()).min(2), minimum_clearance: $b.optional(), actual_clearance: $b.optional(), pcb_center: Wa.object({ x: Wa.number().optional(), y: Wa.number().optional() }).optional(), subcircuit_id: Wa.string().optional() }).describe(\"Error emitted when vias are closer than the allowed clearance\");\nvar eC = bx.extend({ type: Wa.literal(\"pcb_via_trace_clearance_error\"), pcb_via_trace_clearance_error_id: ex(\"pcb_via_trace_clearance_error\"), error_type: Wa.literal(\"pcb_via_trace_clearance_error\").default(\"pcb_via_trace_clearance_error\"), pcb_via_id: Wa.string(), pcb_trace_id: Wa.string(), minimum_clearance: $b.optional(), actual_clearance: $b.optional(), center: Wa.object({ x: Wa.number().optional(), y: Wa.number().optional() }).optional(), subcircuit_id: Wa.string().optional() }).describe(\"Error emitted when a via and trace are closer than the allowed clearance\");\nvar tC = bx.extend({ type: Wa.literal(\"pcb_pad_pad_clearance_error\"), pcb_pad_pad_clearance_error_id: ex(\"pcb_pad_pad_clearance_error\"), error_type: Wa.literal(\"pcb_pad_pad_clearance_error\").default(\"pcb_pad_pad_clearance_error\"), pcb_pad_ids: Wa.array(Wa.string()).min(2), minimum_clearance: $b.optional(), actual_clearance: $b.optional(), center: Wa.object({ x: Wa.number().optional(), y: Wa.number().optional() }).optional(), subcircuit_id: Wa.string().optional() }).describe(\"Error emitted when pads are closer than the allowed clearance\");\nvar nC = bx.extend({ type: Wa.literal(\"pcb_pad_trace_clearance_error\"), pcb_pad_trace_clearance_error_id: ex(\"pcb_pad_trace_clearance_error\"), error_type: Wa.literal(\"pcb_pad_trace_clearance_error\").default(\"pcb_pad_trace_clearance_error\"), pcb_pad_id: Wa.string(), pcb_trace_id: Wa.string(), minimum_clearance: $b.optional(), actual_clearance: $b.optional(), center: Wa.object({ x: Wa.number().optional(), y: Wa.number().optional() }).optional(), subcircuit_id: Wa.string().optional() }).describe(\"Error emitted when a pad and trace are closer than allowed clearance\");\nvar oC = Wa.object({ type: Wa.literal(\"pcb_courtyard_rect\"), pcb_courtyard_rect_id: ex(\"pcb_courtyard_rect\"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: Zb, width: Fb, height: Fb, layer: _v, ccw_rotation: Gb.optional(), color: Wa.string().optional() }).describe(\"Defines a courtyard rectangle on the PCB\");\nvar iC = Wa.object({ type: Wa.literal(\"pcb_courtyard_outline\"), pcb_courtyard_outline_id: ex(\"pcb_courtyard_outline\"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), layer: _v, outline: Wa.array(Zb).min(2) }).describe(\"Defines a courtyard outline on the PCB\");\nvar rC = Wa.object({ type: Wa.literal(\"pcb_courtyard_polygon\"), pcb_courtyard_polygon_id: ex(\"pcb_courtyard_polygon\"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), layer: _v, points: Wa.array(Zb).min(3), color: Wa.string().optional() }).describe(\"Defines a courtyard polygon on the PCB\");\nvar sC = Wa.object({ type: Wa.literal(\"pcb_courtyard_circle\"), pcb_courtyard_circle_id: ex(\"pcb_courtyard_circle\"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: Zb, radius: Fb, layer: _v, color: Wa.string().optional() }).describe(\"Defines a courtyard circle on the PCB\");\nvar aC = [\"obj\", \"stl\", \"3mf\", \"gltf\", \"glb\", \"step\", \"wrl\"];\nvar cC = [\"x+\", \"x-\", \"y+\", \"y-\", \"z+\", \"z-\"];\nvar lC = { obj: \"z+\", stl: \"z+\", \"3mf\": \"z+\", gltf: \"y+\", glb: \"y+\", step: \"z+\", wrl: \"y+\" };\nvar hC = Wa.object({ type: Wa.literal(\"cad_component\"), cad_component_id: Wa.string(), pcb_component_id: Wa.string(), source_component_id: Wa.string(), position: Jb, rotation: Jb.optional(), size: Jb.optional(), layer: fv.optional(), subcircuit_id: Wa.string().optional(), footprinter_string: Wa.string().optional(), model_obj_url: Wa.string().optional(), model_stl_url: Wa.string().optional(), model_3mf_url: Wa.string().optional(), model_gltf_url: Wa.string().optional(), model_glb_url: Wa.string().optional(), model_step_url: Wa.string().optional(), model_wrl_url: Wa.string().optional(), model_asset: ox.optional(), model_unit_to_mm_scale_factor: Wa.number().optional(), model_board_normal_direction: Wa.enum(cC).optional().describe(`The direction in the model's coordinate space that is considered \"up\" or \"coming out of the board surface\"`), model_origin_position: Jb.optional(), model_origin_alignment: Wa.enum([\"unknown\", \"center\", \"center_of_component_on_board_surface\", \"bottom_center_of_component\"]).optional(), model_object_fit: Wa.enum([\"contain_within_bounds\", \"fill_bounds\"]).optional().default(\"contain_within_bounds\"), model_jscad: Wa.any().optional(), show_as_translucent_model: Wa.boolean().optional(), anchor_alignment: Wa.enum([\"center\", \"center_of_component_on_board_surface\"]).optional().default(\"center\") }).describe(\"Defines a component on the PCB\");\nvar dC = Wa.enum([\"sinewave\", \"square\", \"triangle\", \"sawtooth\"]);\nvar uC = Wa.union([Wa.string(), Wa.number()]).transform((e35) =\u003e typeof e35 == \"string\" ? e35.endsWith(\"%\") ? parseFloat(e35.slice(0, -1)) / 100 : parseFloat(e35) : e35).pipe(Wa.number().min(0, \"Duty cycle must be non-negative\").max(1, \"Duty cycle cannot be greater than 100%\"));\nvar pC = Wa.object({ type: Wa.literal(\"simulation_voltage_source\"), simulation_voltage_source_id: ex(\"simulation_voltage_source\"), is_dc_source: Wa.literal(true).optional().default(true), positive_source_port_id: Wa.string().optional(), negative_source_port_id: Wa.string().optional(), positive_source_net_id: Wa.string().optional(), negative_source_net_id: Wa.string().optional(), voltage: Bb }).describe(\"Defines a DC voltage source for simulation\");\nvar mC = Wa.object({ type: Wa.literal(\"simulation_voltage_source\"), simulation_voltage_source_id: ex(\"simulation_voltage_source\"), is_dc_source: Wa.literal(false), terminal1_source_port_id: Wa.string().optional(), terminal2_source_port_id: Wa.string().optional(), terminal1_source_net_id: Wa.string().optional(), terminal2_source_net_id: Wa.string().optional(), voltage: Bb.optional(), frequency: jb.optional(), peak_to_peak_voltage: Bb.optional(), wave_shape: dC.optional(), phase: Gb.optional(), duty_cycle: uC.optional() }).describe(\"Defines an AC voltage source for simulation\");\nvar gC = Wa.union([pC, mC]).describe(\"Defines a voltage source for simulation\");\nvar fC = Wa.union([Wa.string(), Wa.number()]).transform((e35) =\u003e typeof e35 == \"string\" ? e35.endsWith(\"%\") ? parseFloat(e35.slice(0, -1)) / 100 : parseFloat(e35) : e35).pipe(Wa.number().min(0, \"Duty cycle must be non-negative\").max(1, \"Duty cycle cannot be greater than 100%\"));\nvar _C = Wa.object({ type: Wa.literal(\"simulation_current_source\"), simulation_current_source_id: ex(\"simulation_current_source\"), is_dc_source: Wa.literal(true).optional().default(true), positive_source_port_id: Wa.string().optional(), negative_source_port_id: Wa.string().optional(), positive_source_net_id: Wa.string().optional(), negative_source_net_id: Wa.string().optional(), current: Yb }).describe(\"Defines a DC current source for simulation\");\nvar yC = Wa.object({ type: Wa.literal(\"simulation_current_source\"), simulation_current_source_id: ex(\"simulation_current_source\"), is_dc_source: Wa.literal(false), terminal1_source_port_id: Wa.string().optional(), terminal2_source_port_id: Wa.string().optional(), terminal1_source_net_id: Wa.string().optional(), terminal2_source_net_id: Wa.string().optional(), current: Yb.optional(), frequency: jb.optional(), peak_to_peak_current: Yb.optional(), wave_shape: dC.optional(), phase: Gb.optional(), duty_cycle: fC.optional() }).describe(\"Defines an AC current source for simulation\");\nvar bC = Wa.union([_C, yC]).describe(\"Defines a current source for simulation\");\nvar xC = Wa.union([Wa.literal(\"spice_dc_sweep\"), Wa.literal(\"spice_dc_operating_point\"), Wa.literal(\"spice_transient_analysis\"), Wa.literal(\"spice_ac_analysis\")]);\nvar vC = Wa.object({ type: Wa.literal(\"simulation_experiment\"), simulation_experiment_id: ex(\"simulation_experiment\"), name: Wa.string(), experiment_type: xC, time_per_step: Xb.optional(), start_time_ms: Vb.optional(), end_time_ms: Vb.optional() }).describe(\"Defines a simulation experiment configuration\");\nvar IC = Wa.object({ type: Wa.literal(\"simulation_transient_voltage_graph\"), simulation_transient_voltage_graph_id: ex(\"simulation_transient_voltage_graph\"), simulation_experiment_id: Wa.string(), timestamps_ms: Wa.array(Wa.number()).optional(), voltage_levels: Wa.array(Wa.number()), source_component_id: Wa.string().optional(), subcircuit_connectivity_map_key: Wa.string().optional(), time_per_step: Xb, start_time_ms: Vb, end_time_ms: Vb, name: Wa.string().optional(), color: Wa.string().optional() }).describe(\"Stores voltage measurements over time for a simulation\");\nvar SC = Wa.object({ type: Wa.literal(\"simulation_switch\"), simulation_switch_id: ex(\"simulation_switch\"), source_component_id: Wa.string().optional(), closes_at: Vb.optional(), opens_at: Vb.optional(), starts_closed: Wa.boolean().optional(), switching_frequency: jb.optional() }).describe(\"Defines a switch for simulation timing control\");\nvar CC = Wa.object({ type: Wa.literal(\"simulation_voltage_probe\"), simulation_voltage_probe_id: ex(\"simulation_voltage_probe\"), source_component_id: Wa.string().optional(), name: Wa.string().optional(), signal_input_source_port_id: Wa.string().optional(), signal_input_source_net_id: Wa.string().optional(), reference_input_source_port_id: Wa.string().optional(), reference_input_source_net_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), color: Wa.string().optional() }).describe(\"Defines a voltage probe for simulation. If a reference input is not provided, it measures against ground. If a reference input is provided, it measures the differential voltage between two points.\").superRefine((e35, t2) =\u003e {\n if (e35.reference_input_source_port_id || e35.reference_input_source_net_id) {\n const n2 = !!e35.signal_input_source_port_id || !!e35.reference_input_source_port_id, o3 = !!e35.signal_input_source_net_id || !!e35.reference_input_source_net_id;\n n2 \u0026\u0026 o3 ? t2.addIssue({ code: Wa.ZodIssueCode.custom, message: \"Cannot mix port and net connections in a differential probe.\" }) : n2 ? e35.signal_input_source_port_id \u0026\u0026 e35.reference_input_source_port_id || t2.addIssue({ code: Wa.ZodIssueCode.custom, message: \"Differential port probe requires both signal_input_source_port_id and reference_input_source_port_id.\" }) : o3 \u0026\u0026 (e35.signal_input_source_net_id \u0026\u0026 e35.reference_input_source_net_id || t2.addIssue({ code: Wa.ZodIssueCode.custom, message: \"Differential net probe requires both signal_input_source_net_id and reference_input_source_net_id.\" }));\n } else\n !!e35.signal_input_source_port_id == !!e35.signal_input_source_net_id \u0026\u0026 t2.addIssue({ code: Wa.ZodIssueCode.custom, message: \"A voltage probe must have exactly one of signal_input_source_port_id or signal_input_source_net_id.\" });\n});\nvar PC = bx.extend({ type: Wa.literal(\"simulation_unknown_experiment_error\"), simulation_unknown_experiment_error_id: ex(\"simulation_unknown_experiment_error\"), error_type: Wa.literal(\"simulation_unknown_experiment_error\").default(\"simulation_unknown_experiment_error\"), simulation_experiment_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe(\"An unknown error occurred during the simulation experiment.\");\nvar MC = Wa.object({ type: Wa.literal(\"simulation_op_amp\"), simulation_op_amp_id: ex(\"simulation_op_amp\"), source_component_id: Wa.string().optional(), inverting_input_source_port_id: Wa.string(), non_inverting_input_source_port_id: Wa.string(), output_source_port_id: Wa.string(), positive_supply_source_port_id: Wa.string(), negative_supply_source_port_id: Wa.string() }).describe(\"Defines a simple ideal operational amplifier for simulation\");\nvar wC = Wa.union([cv, sv, av, rv, hv, lv, Nx, Ix, Cx, Mx, Sx, Rx, Ox, kx, Bx, jx, $x, Wx, Yx, Xx, Hx, Vx, Lx, Dx, pv, yv, dv, Gx, qx, Jx, Kx, ev, bv, xv, vv, Iv, Sv, ov, uv, cI, vI, AS, OS, kS, zS, FS, jS, NI, PS, RI, KI, XI, GI, UI, eS, LI, YI, tS, nS, DS, rS, sS, aS, cS, pS, lS, hS, dS, uS, ZI, qI, oS, iS, JI, QI, KS, eC, tC, nC, gS, mS, fS, _S, yS, bS, xS, vS, IS, LS, SS, CS, $S, ES, YS, XS, HS, ZS, qS, JS, QS, oC, iC, rC, sC, Cv, Fv, Ov, kv, Dv, Lv, Tv, Av, jv, zv, Pv, Yv, Xv, $v, Uv, Zv, qv, Jv, eI, Qv, Kv, hC, gC, bC, vC, IC, SC, CC, PC, MC]);\nvar NC = wC;\nfunction RC(e35, t2, n2) {\n if (!t2 || !n2)\n return;\n let o3 = e35.get(t2);\n o3 || (o3 = new Set, e35.set(t2, o3)), o3.add(n2);\n let i3 = e35.get(n2);\n i3 || (i3 = new Set, e35.set(n2, i3)), i3.add(t2);\n}\nvar TC = (e35, t2 = {}) =\u003e {\n const n2 = e35;\n let o3 = n2._internal_store;\n if (!o3) {\n o3 = { counts: {}, editCount: 0 }, n2._internal_store = o3;\n for (const e36 of n2) {\n const t3 = e36.type, n3 = e36[`${t3}_id`];\n if (!n3)\n continue;\n const i4 = Number.parseInt(n3.split(\"_\").pop());\n Number.isNaN(i4) || (o3.counts[t3] = Math.max(o3.counts[t3] ?? 0, i4));\n }\n }\n const i3 = new Proxy({}, { get: (e36, r3) =\u003e {\n if (r3 === \"toArray\")\n return () =\u003e (n2.editCount = o3.editCount, n2);\n if (r3 === \"editCount\")\n return o3.editCount;\n if (r3 === \"subtree\")\n return (e37) =\u003e TC(function(e38, t3) {\n if (!t3.subcircuit_id \u0026\u0026 !t3.source_group_id)\n return [...e38];\n let n3 = t3;\n if (t3.subcircuit_id) {\n const o5 = new Set([t3.subcircuit_id]), i5 = new Map, r5 = new Map;\n for (const t4 of e38)\n if (t4.type === \"source_group\") {\n const { source_group_id: e39, subcircuit_id: n4 } = t4;\n n4 \u0026\u0026 r5.set(e39, n4);\n const o6 = t4.parent_source_group_id;\n o6 \u0026\u0026 (i5.has(o6) || i5.set(o6, []), i5.get(o6).push(e39));\n }\n let s4;\n for (const [e39, n4] of r5)\n if (n4 === t3.subcircuit_id) {\n s4 = e39;\n break;\n }\n if (s4) {\n const e39 = (t4) =\u003e {\n const n4 = i5.get(t4) || [];\n for (const t5 of n4) {\n const n5 = r5.get(t5);\n n5 \u0026\u0026 o5.add(n5), e39(t5);\n }\n };\n e39(s4), n3 = { ...t3, subcircuit_ids: Array.from(o5) };\n }\n }\n const o4 = new Map;\n for (const t4 of e38) {\n const e39 = t4[`${t4.type}_id`];\n typeof e39 == \"string\" \u0026\u0026 o4.set(e39, t4);\n }\n const i4 = new Map;\n for (const t4 of e38) {\n const e39 = Object.entries(t4);\n for (const [n4, r5] of e39)\n if (n4 !== \"parent_source_group_id\") {\n if (n4.endsWith(\"_id\") \u0026\u0026 typeof r5 == \"string\")\n RC(i4, t4, o4.get(r5));\n else if (n4.endsWith(\"_ids\") \u0026\u0026 Array.isArray(r5))\n for (const e40 of r5)\n typeof e40 == \"string\" \u0026\u0026 RC(i4, t4, o4.get(e40));\n }\n }\n const r4 = [], s3 = new Set;\n for (const t4 of e38) {\n let e39 = false;\n (n3.subcircuit_id \u0026\u0026 (\"subcircuit_id\" in t4) \u0026\u0026 t4.subcircuit_id === n3.subcircuit_id || n3.subcircuit_ids \u0026\u0026 (\"subcircuit_id\" in t4) \u0026\u0026 t4.subcircuit_id \u0026\u0026 n3.subcircuit_ids.includes(t4.subcircuit_id) || n3.source_group_id \u0026\u0026 (\"source_group_id\" in t4) \u0026\u0026 t4.source_group_id === n3.source_group_id || n3.source_group_id \u0026\u0026 (\"member_source_group_ids\" in t4) \u0026\u0026 Array.isArray(t4.member_source_group_ids) \u0026\u0026 t4.member_source_group_ids.includes(n3.source_group_id)) \u0026\u0026 (e39 = true), e39 \u0026\u0026 (r4.push(t4), s3.add(t4));\n }\n for (;r4.length \u003e 0; ) {\n const e39 = r4.shift(), t4 = i4.get(e39);\n if (t4)\n for (const e40 of t4)\n s3.has(e40) || (s3.add(e40), r4.push(e40));\n }\n return e38.filter((e39) =\u003e s3.has(e39));\n }(n2, e37), t2);\n if (r3 === \"insert\")\n return (e37) =\u003e {\n const i4 = e37.type;\n if (!i4)\n throw new Error(\"insert requires an element with a type\");\n o3.counts[i4] ??= -1, o3.counts[i4]++;\n const r4 = o3.counts[i4], s3 = { ...e37, type: i4, [`${i4}_id`]: `${i4}_${r4}` };\n if (t2.validateInserts) {\n (Tb[i4] ?? NC).parse(s3);\n }\n return n2.push(s3), o3.editCount++, s3;\n };\n if (r3 === \"insertAll\")\n return (e37) =\u003e e37.map((e38) =\u003e i3.insert(e38));\n const s2 = r3;\n return { get: (e37) =\u003e n2.find((t3) =\u003e t3.type === s2 \u0026\u0026 t3[`${s2}_id`] === e37), getUsing: (e37) =\u003e {\n const t3 = Object.keys(e37);\n if (t3.length !== 1)\n throw new Error(\"getUsing requires exactly one key, e.g. { pcb_component_id }\");\n const o4 = t3[0], i4 = o4.replace(\"_id\", \"\"), r4 = n2.find((t4) =\u003e t4.type === i4 \u0026\u0026 t4[o4] === e37[o4]);\n return r4 ? n2.find((e38) =\u003e e38.type === s2 \u0026\u0026 e38[`${s2}_id`] === r4[`${s2}_id`]) : null;\n }, getWhere: (e37) =\u003e {\n const t3 = Object.keys(e37);\n return n2.find((n3) =\u003e n3.type === s2 \u0026\u0026 t3.every((t4) =\u003e n3[t4] === e37[t4]));\n }, list: (e37) =\u003e {\n const t3 = e37 ? Object.keys(e37) : [];\n return n2.filter((n3) =\u003e n3.type === s2 \u0026\u0026 t3.every((t4) =\u003e n3[t4] === e37[t4]));\n }, insert: (e37) =\u003e {\n o3.counts[s2] ??= -1, o3.counts[s2]++;\n const i4 = o3.counts[s2], r4 = { type: s2, [`${s2}_id`]: `${s2}_${i4}`, ...e37 };\n if (t2.validateInserts) {\n (Tb[s2] ?? NC).parse(r4);\n }\n return n2.push(r4), o3.editCount++, r4;\n }, delete: (e37) =\u003e {\n const t3 = n2.find((t4) =\u003e t4[`${s2}_id`] === e37);\n t3 \u0026\u0026 (n2.splice(n2.indexOf(t3), 1), o3.editCount++);\n }, update: (e37, t3) =\u003e {\n const i4 = n2.find((t4) =\u003e t4.type === s2 \u0026\u0026 t4[`${s2}_id`] === e37);\n return i4 ? (Object.assign(i4, t3), o3.editCount++, i4) : null;\n }, select: (e37) =\u003e {\n if (s2 === \"source_component\")\n return n2.find((t3) =\u003e t3.type === \"source_component\" \u0026\u0026 t3.name === e37.replace(/\\./g, \"\"));\n if (s2 === \"pcb_port\" || s2 === \"source_port\" || s2 === \"schematic_port\") {\n const [t3, o4] = e37.replace(/\\./g, \"\").split(/[\\s\\\u003e]+/), i4 = n2.find((e38) =\u003e e38.type === \"source_component\" \u0026\u0026 e38.name === t3);\n if (!i4)\n return null;\n const r4 = n2.find((e38) =\u003e e38.type === \"source_port\" \u0026\u0026 e38.source_component_id === i4.source_component_id \u0026\u0026 (e38.name === o4 || (e38.port_hints ?? []).includes(o4)));\n if (!r4)\n return null;\n if (s2 === \"source_port\")\n return r4;\n if (s2 === \"pcb_port\")\n return n2.find((e38) =\u003e e38.type === \"pcb_port\" \u0026\u0026 e38.source_port_id === r4.source_port_id);\n if (s2 === \"schematic_port\")\n return n2.find((e38) =\u003e e38.type === \"schematic_port\" \u0026\u0026 e38.source_port_id === r4.source_port_id);\n }\n } };\n } });\n return i3;\n};\nTC.unparsed = TC;\nvar EC = TC;\nfunction AC(e35) {\n const t2 = e35.type;\n return `${t2}:${e35[`${t2}_id`]}`;\n}\nvar OC = (e35, t2 = {}) =\u003e {\n let n2 = e35._internal_store_indexed;\n if (!n2) {\n n2 = { counts: {}, editCount: 0, indexes: {} };\n for (const t3 of e35) {\n const e36 = t3.type, o4 = t3[`${e36}_id`];\n if (!o4)\n continue;\n const i4 = Number.parseInt(o4.split(\"_\").pop() || \"\");\n Number.isNaN(i4) || (n2.counts[e36] = Math.max(n2.counts[e36] ?? 0, i4));\n }\n const o3 = t2.indexConfig || {}, i3 = n2.indexes;\n if (o3.byId \u0026\u0026 (i3.byId = new Map), o3.byType \u0026\u0026 (i3.byType = new Map), o3.byRelation \u0026\u0026 (i3.byRelation = new Map), o3.bySubcircuit \u0026\u0026 (i3.bySubcircuit = new Map), o3.byCustomField \u0026\u0026 o3.byCustomField.length \u003e 0) {\n i3.byCustomField = new Map;\n for (const e36 of o3.byCustomField)\n i3.byCustomField.set(e36, new Map);\n }\n for (const t3 of e35) {\n if (o3.byId) {\n const e36 = AC(t3);\n i3.byId.set(e36, t3);\n }\n if (o3.byType) {\n const e36 = i3.byType.get(t3.type) || [];\n e36.push(t3), i3.byType.set(t3.type, e36);\n }\n if (o3.byRelation) {\n const e36 = Object.entries(t3);\n for (const [n3, o4] of e36)\n if (n3.endsWith(\"_id\") \u0026\u0026 n3 !== `${t3.type}_id` \u0026\u0026 typeof o4 == \"string\") {\n const e37 = i3.byRelation.get(n3) || new Map, r3 = e37.get(o4) || [];\n r3.push(t3), e37.set(o4, r3), i3.byRelation.set(n3, e37);\n }\n }\n if (o3.bySubcircuit \u0026\u0026 \"subcircuit_id\" in t3) {\n const e36 = t3.subcircuit_id;\n if (e36 \u0026\u0026 typeof e36 == \"string\") {\n const n3 = i3.bySubcircuit.get(e36) || [];\n n3.push(t3), i3.bySubcircuit.set(e36, n3);\n }\n }\n if (o3.byCustomField \u0026\u0026 i3.byCustomField) {\n for (const e36 of o3.byCustomField)\n if (e36 in t3) {\n const n3 = t3[e36];\n if (n3 !== undefined \u0026\u0026 (typeof n3 == \"string\" || typeof n3 == \"number\")) {\n const o4 = String(n3), r3 = i3.byCustomField.get(e36), s2 = r3.get(o4) || [];\n s2.push(t3), r3.set(o4, s2);\n }\n }\n }\n }\n e35._internal_store_indexed = n2;\n }\n return new Proxy({}, { get: (o3, i3) =\u003e {\n if (i3 === \"toArray\")\n return () =\u003e (e35.editCount = n2.editCount, e35);\n if (i3 === \"editCount\")\n return n2.editCount;\n const r3 = i3;\n return { get: (o4) =\u003e {\n const i4 = t2.indexConfig || {};\n if (i4.byId \u0026\u0026 n2.indexes.byId)\n return n2.indexes.byId.get(`${r3}:${o4}`) || null;\n if (i4.byType \u0026\u0026 n2.indexes.byType) {\n return (n2.indexes.byType.get(r3) || []).find((e36) =\u003e e36[`${r3}_id`] === o4) || null;\n }\n return e35.find((e36) =\u003e e36.type === r3 \u0026\u0026 e36[`${r3}_id`] === o4) || null;\n }, getUsing: (o4) =\u003e {\n const i4 = t2.indexConfig || {}, s2 = Object.keys(o4);\n if (s2.length !== 1)\n throw new Error(\"getUsing requires exactly one key, e.g. { pcb_component_id }\");\n const a3 = s2[0], c3 = a3.replace(\"_id\", \"\");\n if (i4.byRelation \u0026\u0026 n2.indexes.byRelation) {\n const t3 = n2.indexes.byRelation.get(a3);\n if (t3) {\n const s3 = (t3.get(o4[a3]) || []).find((e36) =\u003e e36.type === c3);\n if (!s3)\n return null;\n const l4 = s3[`${r3}_id`];\n if (i4.byId \u0026\u0026 n2.indexes.byId)\n return n2.indexes.byId.get(`${r3}:${l4}`) || null;\n if (i4.byType \u0026\u0026 n2.indexes.byType) {\n return (n2.indexes.byType.get(r3) || []).find((e36) =\u003e e36[`${r3}_id`] === l4) || null;\n }\n return e35.find((e36) =\u003e e36.type === r3 \u0026\u0026 e36[`${r3}_id`] === l4) || null;\n }\n }\n const l3 = e35.find((e36) =\u003e e36.type === c3 \u0026\u0026 e36[a3] === o4[a3]);\n return l3 \u0026\u0026 e35.find((e36) =\u003e e36.type === r3 \u0026\u0026 e36[`${r3}_id`] === l3[`${r3}_id`]) || null;\n }, getWhere: (o4) =\u003e {\n const i4 = t2.indexConfig || {}, s2 = Object.keys(o4);\n if (s2.length === 1 \u0026\u0026 i4.byCustomField \u0026\u0026 n2.indexes.byCustomField) {\n const e36 = s2[0], t3 = n2.indexes.byCustomField.get(e36);\n if (t3) {\n const n3 = String(o4[e36]);\n return (t3.get(n3) || []).find((e37) =\u003e e37.type === r3) || null;\n }\n }\n if (\"subcircuit_id\" in o4 \u0026\u0026 i4.bySubcircuit \u0026\u0026 n2.indexes.bySubcircuit) {\n const e36 = o4.subcircuit_id;\n return (n2.indexes.bySubcircuit.get(e36) || []).find((e37) =\u003e e37.type === r3 \u0026\u0026 s2.every((t3) =\u003e e37[t3] === o4[t3])) || null;\n }\n if (i4.byType \u0026\u0026 n2.indexes.byType) {\n return (n2.indexes.byType.get(r3) || []).find((e36) =\u003e s2.every((t3) =\u003e e36[t3] === o4[t3])) || null;\n }\n return e35.find((e36) =\u003e e36.type === r3 \u0026\u0026 s2.every((t3) =\u003e e36[t3] === o4[t3])) || null;\n }, list: (o4) =\u003e {\n const i4 = t2.indexConfig || {}, s2 = o4 ? Object.keys(o4) : [];\n if (s2.length === 0 \u0026\u0026 i4.byType \u0026\u0026 n2.indexes.byType)\n return n2.indexes.byType.get(r3) || [];\n if (s2.length === 1 \u0026\u0026 s2[0] === \"subcircuit_id\" \u0026\u0026 i4.bySubcircuit \u0026\u0026 n2.indexes.bySubcircuit) {\n const e36 = o4.subcircuit_id;\n return (n2.indexes.bySubcircuit.get(e36) || []).filter((e37) =\u003e e37.type === r3);\n }\n let a3;\n return a3 = i4.byType \u0026\u0026 n2.indexes.byType ? n2.indexes.byType.get(r3) || [] : e35.filter((e36) =\u003e e36.type === r3), s2.length \u003e 0 ? a3.filter((e36) =\u003e s2.every((t3) =\u003e e36[t3] === o4[t3])) : a3;\n }, insert: (o4) =\u003e {\n n2.counts[r3] ??= -1, n2.counts[r3]++;\n const i4 = n2.counts[r3], s2 = { type: r3, [`${r3}_id`]: `${r3}_${i4}`, ...o4 };\n if (t2.validateInserts) {\n (Tb[r3] ?? NC).parse(s2);\n }\n e35.push(s2), n2.editCount++;\n const a3 = t2.indexConfig || {};\n if (a3.byId \u0026\u0026 n2.indexes.byId) {\n const e36 = AC(s2);\n n2.indexes.byId.set(e36, s2);\n }\n if (a3.byType \u0026\u0026 n2.indexes.byType) {\n const e36 = n2.indexes.byType.get(r3) || [];\n e36.push(s2), n2.indexes.byType.set(r3, e36);\n }\n if (a3.byRelation \u0026\u0026 n2.indexes.byRelation) {\n const e36 = Object.entries(s2);\n for (const [t3, o5] of e36)\n if (t3.endsWith(\"_id\") \u0026\u0026 t3 !== `${s2.type}_id` \u0026\u0026 typeof o5 == \"string\") {\n const e37 = n2.indexes.byRelation.get(t3) || new Map, i5 = e37.get(o5) || [];\n i5.push(s2), e37.set(o5, i5), n2.indexes.byRelation.set(t3, e37);\n }\n }\n if (a3.bySubcircuit \u0026\u0026 n2.indexes.bySubcircuit \u0026\u0026 \"subcircuit_id\" in s2) {\n const e36 = s2.subcircuit_id;\n if (e36 \u0026\u0026 typeof e36 == \"string\") {\n const t3 = n2.indexes.bySubcircuit.get(e36) || [];\n t3.push(s2), n2.indexes.bySubcircuit.set(e36, t3);\n }\n }\n if (a3.byCustomField \u0026\u0026 n2.indexes.byCustomField) {\n for (const e36 of a3.byCustomField)\n if (e36 in s2) {\n const t3 = s2[e36];\n if (t3 !== undefined \u0026\u0026 (typeof t3 == \"string\" || typeof t3 == \"number\")) {\n const o5 = String(t3), i5 = n2.indexes.byCustomField.get(e36), r4 = i5.get(o5) || [];\n r4.push(s2), i5.set(o5, r4);\n }\n }\n }\n return s2;\n }, delete: (o4) =\u003e {\n const i4 = t2.indexConfig || {};\n let s2;\n if (i4.byId \u0026\u0026 n2.indexes.byId)\n s2 = n2.indexes.byId.get(`${r3}:${o4}`);\n else if (i4.byType \u0026\u0026 n2.indexes.byType) {\n const e36 = n2.indexes.byType.get(r3) || [];\n s2 = e36.find((e37) =\u003e e37[`${r3}_id`] === o4);\n } else\n s2 = e35.find((e36) =\u003e e36[`${r3}_id`] === o4);\n if (!s2)\n return;\n const a3 = e35.indexOf(s2);\n if (a3 \u003e= 0 \u0026\u0026 (e35.splice(a3, 1), n2.editCount++), i4.byId \u0026\u0026 n2.indexes.byId) {\n const e36 = AC(s2);\n n2.indexes.byId.delete(e36);\n }\n if (i4.byType \u0026\u0026 n2.indexes.byType) {\n const e36 = (n2.indexes.byType.get(r3) || []).filter((e37) =\u003e e37[`${r3}_id`] !== o4);\n n2.indexes.byType.set(r3, e36);\n }\n if (i4.byRelation \u0026\u0026 n2.indexes.byRelation)\n for (const [e36, t3] of n2.indexes.byRelation.entries())\n for (const [e37, n3] of t3.entries()) {\n const o5 = n3.filter((e38) =\u003e e38 !== s2);\n o5.length === 0 ? t3.delete(e37) : t3.set(e37, o5);\n }\n if (i4.bySubcircuit \u0026\u0026 n2.indexes.bySubcircuit \u0026\u0026 \"subcircuit_id\" in s2) {\n const e36 = s2.subcircuit_id;\n if (e36) {\n const t3 = (n2.indexes.bySubcircuit.get(e36) || []).filter((e37) =\u003e e37 !== s2);\n t3.length === 0 ? n2.indexes.bySubcircuit.delete(e36) : n2.indexes.bySubcircuit.set(e36, t3);\n }\n }\n if (i4.byCustomField \u0026\u0026 n2.indexes.byCustomField)\n for (const e36 of n2.indexes.byCustomField.values())\n for (const [t3, n3] of e36.entries()) {\n const o5 = n3.filter((e37) =\u003e e37 !== s2);\n o5.length === 0 ? e36.delete(t3) : e36.set(t3, o5);\n }\n }, update: (o4, i4) =\u003e {\n const s2 = t2.indexConfig || {};\n let a3;\n if (s2.byId \u0026\u0026 n2.indexes.byId)\n a3 = n2.indexes.byId.get(`${r3}:${o4}`);\n else if (s2.byType \u0026\u0026 n2.indexes.byType) {\n const e36 = n2.indexes.byType.get(r3) || [];\n a3 = e36.find((e37) =\u003e e37[`${r3}_id`] === o4);\n } else\n a3 = e35.find((e36) =\u003e e36.type === r3 \u0026\u0026 e36[`${r3}_id`] === o4);\n if (!a3)\n return null;\n if (s2.byRelation \u0026\u0026 n2.indexes.byRelation) {\n const e36 = Object.entries(a3);\n for (const [t3, o5] of e36)\n if (t3.endsWith(\"_id\") \u0026\u0026 t3 !== `${a3.type}_id` \u0026\u0026 typeof o5 == \"string\" \u0026\u0026 t3 in i4 \u0026\u0026 i4[t3] !== o5) {\n const e37 = n2.indexes.byRelation.get(t3);\n if (e37) {\n const t4 = (e37.get(o5) || []).filter((e38) =\u003e e38 !== a3);\n t4.length === 0 ? e37.delete(o5) : e37.set(o5, t4);\n }\n }\n }\n if (s2.bySubcircuit \u0026\u0026 n2.indexes.bySubcircuit \u0026\u0026 \"subcircuit_id\" in a3 \u0026\u0026 \"subcircuit_id\" in i4) {\n const e36 = a3.subcircuit_id;\n if (e36 !== i4.subcircuit_id) {\n const t3 = (n2.indexes.bySubcircuit.get(e36) || []).filter((e37) =\u003e e37 !== a3);\n t3.length === 0 ? n2.indexes.bySubcircuit.delete(e36) : n2.indexes.bySubcircuit.set(e36, t3);\n }\n }\n if (s2.byCustomField \u0026\u0026 n2.indexes.byCustomField) {\n for (const e36 of s2.byCustomField)\n if (e36 in a3 \u0026\u0026 e36 in i4 \u0026\u0026 a3[e36] !== i4[e36]) {\n const t3 = n2.indexes.byCustomField.get(e36);\n if (t3) {\n const n3 = String(a3[e36]), o5 = (t3.get(n3) || []).filter((e37) =\u003e e37 !== a3);\n o5.length === 0 ? t3.delete(n3) : t3.set(n3, o5);\n }\n }\n }\n if (Object.assign(a3, i4), n2.editCount++, s2.byRelation \u0026\u0026 n2.indexes.byRelation) {\n const e36 = Object.entries(a3);\n for (const [t3, o5] of e36)\n if (t3.endsWith(\"_id\") \u0026\u0026 t3 !== `${a3.type}_id` \u0026\u0026 typeof o5 == \"string\" \u0026\u0026 t3 in i4) {\n const e37 = n2.indexes.byRelation.get(t3) || new Map, i5 = e37.get(o5) || [];\n i5.includes(a3) || (i5.push(a3), e37.set(o5, i5), n2.indexes.byRelation.set(t3, e37));\n }\n }\n if (s2.bySubcircuit \u0026\u0026 n2.indexes.bySubcircuit \u0026\u0026 \"subcircuit_id\" in a3 \u0026\u0026 \"subcircuit_id\" in i4) {\n const e36 = a3.subcircuit_id;\n if (e36 \u0026\u0026 typeof e36 == \"string\") {\n const t3 = n2.indexes.bySubcircuit.get(e36) || [];\n t3.includes(a3) || (t3.push(a3), n2.indexes.bySubcircuit.set(e36, t3));\n }\n }\n if (s2.byCustomField \u0026\u0026 n2.indexes.byCustomField) {\n for (const e36 of s2.byCustomField)\n if (e36 in a3 \u0026\u0026 e36 in i4) {\n const t3 = a3[e36];\n if (t3 !== undefined \u0026\u0026 (typeof t3 == \"string\" || typeof t3 == \"number\")) {\n const o5 = String(t3), i5 = n2.indexes.byCustomField.get(e36), r4 = i5.get(o5) || [];\n r4.includes(a3) || (r4.push(a3), i5.set(o5, r4));\n }\n }\n }\n return a3;\n }, select: (t3) =\u003e {\n if (r3 === \"source_component\")\n return e35.find((e36) =\u003e e36.type === \"source_component\" \u0026\u0026 e36.name === t3.replace(/\\./g, \"\")) || null;\n if (r3 === \"pcb_port\" || r3 === \"source_port\" || r3 === \"schematic_port\") {\n const [n3, o4] = t3.replace(/\\./g, \"\").split(/[\\s\\\u003e]+/), i4 = e35.find((e36) =\u003e e36.type === \"source_component\" \u0026\u0026 e36.name === n3);\n if (!i4)\n return null;\n const s2 = e35.find((e36) =\u003e e36.type === \"source_port\" \u0026\u0026 e36.source_component_id === i4.source_component_id \u0026\u0026 (e36.name === o4 || (e36.port_hints ?? []).includes(o4)));\n if (!s2)\n return null;\n if (r3 === \"source_port\")\n return s2;\n if (r3 === \"pcb_port\")\n return e35.find((e36) =\u003e e36.type === \"pcb_port\" \u0026\u0026 e36.source_port_id === s2.source_port_id) || null;\n if (r3 === \"schematic_port\")\n return e35.find((e36) =\u003e e36.type === \"schematic_port\" \u0026\u0026 e36.source_port_id === s2.source_port_id) || null;\n }\n return null;\n } };\n } });\n};\nOC.unparsed = OC;\nvar kC = (e35) =\u003e e35[`${e35.type}_id`];\nfunction DC(e35, t2) {\n const n2 = TC(e35).pcb_trace.get(t2);\n if (!n2)\n return `trace[${t2}]`;\n const o3 = n2.route.flatMap((e36) =\u003e [e36.start_pcb_port_id, e36.end_pcb_port_id]).filter(Boolean);\n if (o3.length === 0)\n return `trace[${t2}]`;\n return `trace[${o3.map((t3) =\u003e {\n const n3 = function(t4) {\n const n4 = TC(e35).pcb_port.get(t4);\n if (!n4)\n return null;\n const o4 = n4.pcb_component_id ? TC(e35).pcb_component.get(n4.pcb_component_id) : undefined;\n if (!o4)\n return null;\n const i3 = TC(e35).source_component.get(o4.source_component_id);\n if (!i3)\n return null;\n const r3 = TC(e35).source_port.get(n4.source_port_id), s2 = r3?.port_hints ? r3.port_hints[1] : \"\";\n return { componentName: i3.name, portHint: s2 };\n }(t3);\n return n3 ? `.${n3.componentName} \u003e port.${n3.portHint}` : `port[${t3}]`;\n }).join(\", \")}]`;\n}\nvar LC = (e35, t2) =\u003e {\n const n2 = TC(e35).pcb_port.get(t2);\n if (!n2)\n return `pcb_port[#${t2}]`;\n const o3 = n2.pcb_component_id ? TC(e35).pcb_component.get(n2.pcb_component_id) : undefined;\n if (!o3)\n return `pcb_port[#${t2}]`;\n const i3 = TC(e35).source_component.get(o3.source_component_id);\n if (!i3)\n return `pcb_port[#${t2}]`;\n const r3 = TC(e35).source_port.get(n2.source_port_id);\n if (!r3)\n return `pcb_port[#${t2}]`;\n let s2;\n return s2 = r3?.port_hints \u0026\u0026 r3.port_hints.length \u003e 0 || r3.port_hints \u0026\u0026 r3.port_hints.length \u003e 0 ? r3.port_hints[0] : t2, `pcb_port[.${i3.name} \u003e .${s2}]`;\n};\nvar zC = (e35, t2) =\u003e {\n if (typeof t2 == \"string\") {\n const n2 = ((e36, t3) =\u003e e36.find((e37) =\u003e kC(e37) === t3) ?? null)(e35, t2);\n return zC(e35, n2);\n }\n switch (t2.type) {\n case \"pcb_port\":\n return LC(e35, t2.pcb_port_id);\n case \"pcb_smtpad\":\n return function(e36, t3) {\n const n2 = TC(e36).pcb_smtpad.get(t3);\n return n2 \u0026\u0026 n2.pcb_port_id ? LC(e36, n2.pcb_port_id) : `smtpad[${t3}]`;\n }(e35, t2.pcb_smtpad_id);\n case \"pcb_trace\":\n return DC(e35, t2.pcb_trace_id);\n case \"source_component\":\n return `source_component[${t2.name}]`;\n default:\n return `${t2.type}[#${kC(t2)}]`;\n }\n};\nvar BC = (e35, t2) =\u003e ({ minX: Math.min(e35.minX, t2.minX), minY: Math.min(e35.minY, t2.minY), maxX: Math.max(e35.maxX, t2.maxX), maxY: Math.max(e35.maxY, t2.maxY) });\nvar FC = (e35, t2, n2) =\u003e {\n const o3 = n2 / 2;\n return { minX: e35 - o3, minY: t2 - o3, maxX: e35 + o3, maxY: t2 + o3 };\n};\nvar jC = (e35, t2, n2, o3, i3) =\u003e {\n const r3 = n2 / 2, s2 = o3 / 2, a3 = i3 * Math.PI / 180, c3 = Math.cos(a3), l3 = Math.sin(a3), h2 = [{ x: -r3, y: -s2 }, { x: r3, y: -s2 }, { x: r3, y: s2 }, { x: -r3, y: s2 }].map((n3) =\u003e ({ x: e35 + n3.x * c3 - n3.y * l3, y: t2 + n3.x * l3 + n3.y * c3 }));\n return { minX: Math.min(...h2.map((e36) =\u003e e36.x)), minY: Math.min(...h2.map((e36) =\u003e e36.y)), maxX: Math.max(...h2.map((e36) =\u003e e36.x)), maxY: Math.max(...h2.map((e36) =\u003e e36.y)) };\n};\nvar $C = (e35) =\u003e e35[`${e35.type}_id`];\nfunction YC(e35, t2, n2, o3) {\n return Math.sqrt((n2 - e35) ** 2 + (o3 - t2) ** 2);\n}\nvar XC = class {\n buckets;\n objectsById;\n getBounds;\n getId;\n CELL_SIZE = 0.4;\n constructor({ objects: e35, getBounds: t2, getId: n2, CELL_SIZE: o3 }) {\n this.buckets = new Map, this.objectsById = new Map, this.getBounds = t2, this.getId = n2 ?? (() =\u003e this._getNextId()), this.CELL_SIZE = o3 ?? this.CELL_SIZE;\n for (const t3 of e35)\n this.addObject(t3);\n }\n _idCounter = 0;\n _getNextId() {\n return \"\" + this._idCounter++;\n }\n addObject(e35) {\n const t2 = this.getBounds(e35), n2 = this.getId(e35), o3 = { ...e35, spatialIndexId: n2 };\n this.objectsById.set(n2, o3);\n const i3 = Math.floor(t2.minX / this.CELL_SIZE), r3 = Math.floor(t2.minY / this.CELL_SIZE), s2 = Math.floor(t2.maxX / this.CELL_SIZE), a3 = Math.floor(t2.maxY / this.CELL_SIZE);\n for (let e36 = i3;e36 \u003c= s2; e36++)\n for (let t3 = r3;t3 \u003c= a3; t3++) {\n const n3 = `${e36}x${t3}`, i4 = this.buckets.get(n3);\n i4 ? i4.push(o3) : this.buckets.set(n3, [o3]);\n }\n }\n removeObject(e35) {\n const t2 = this.objectsById.get(e35);\n if (!t2)\n return false;\n this.objectsById.delete(e35);\n const n2 = this.getBounds(t2), o3 = Math.floor(n2.minX / this.CELL_SIZE), i3 = Math.floor(n2.minY / this.CELL_SIZE), r3 = Math.floor(n2.maxX / this.CELL_SIZE), s2 = Math.floor(n2.maxY / this.CELL_SIZE);\n for (let t3 = o3;t3 \u003c= r3; t3++)\n for (let n3 = i3;n3 \u003c= s2; n3++) {\n const o4 = `${t3}x${n3}`, i4 = this.buckets.get(o4);\n if (i4) {\n const t4 = i4.findIndex((t5) =\u003e t5.spatialIndexId === e35);\n t4 !== -1 \u0026\u0026 (i4.splice(t4, 1), i4.length === 0 \u0026\u0026 this.buckets.delete(o4));\n }\n }\n return true;\n }\n getBucketKey(e35, t2) {\n return `${Math.floor(e35 / this.CELL_SIZE)}x${Math.floor(t2 / this.CELL_SIZE)}`;\n }\n getObjectsInBounds(e35, t2 = 0) {\n const n2 = [], o3 = new Set, i3 = Math.floor((e35.minX - t2) / this.CELL_SIZE), r3 = Math.floor((e35.minY - t2) / this.CELL_SIZE), s2 = Math.floor((e35.maxX + t2) / this.CELL_SIZE), a3 = Math.floor((e35.maxY + t2) / this.CELL_SIZE);\n for (let e36 = i3;e36 \u003c= s2; e36++)\n for (let t3 = r3;t3 \u003c= a3; t3++) {\n const i4 = `${e36}x${t3}`, r4 = this.buckets.get(i4) || [];\n for (const e37 of r4) {\n const t4 = e37.spatialIndexId;\n o3.has(t4) || (o3.add(t4), n2.push(e37));\n }\n }\n return n2;\n }\n};\nvar HC = 0.1;\nvar VC = 0.1;\nvar WC = HC;\nvar GC = HC;\nvar UC = 0.005;\nfunction ZC(e35) {\n return e35.type === \"pcb_trace_segment\" || e35.type === \"pcb_smtpad\" ? [e35.layer] : e35.type === \"pcb_plated_hole\" ? Array.isArray(e35.layers) ? e35.layers : [...mv] : e35.type === \"pcb_hole\" ? [...mv] : e35.type === \"pcb_via\" ? Array.isArray(e35.layers) ? e35.layers : [...mv] : e35.type === \"pcb_keepout\" \u0026\u0026 Array.isArray(e35.layers) ? e35.layers : [];\n}\nvar qC = (e35, t2) =\u003e {\n const n2 = { x: e35.x1, y: e35.y1 }, o3 = { x: e35.x2, y: e35.y2 }, i3 = t2.minX, r3 = t2.minY, s2 = t2.maxX, a3 = t2.maxY;\n if (n2.x === o3.x \u0026\u0026 n2.y === o3.y) {\n const e36 = Math.max(i3, Math.min(s2, n2.x)), t3 = Math.max(r3, Math.min(a3, n2.y));\n return e36 === n2.x \u0026\u0026 t3 === n2.y ? { x: n2.x, y: n2.y } : { x: e36, y: t3 };\n }\n const c3 = o3.x - n2.x, l3 = o3.y - n2.y, h2 = c3 !== 0 ? (i3 - n2.x) / c3 : Number.NEGATIVE_INFINITY, d2 = c3 !== 0 ? (s2 - n2.x) / c3 : Number.POSITIVE_INFINITY, u2 = l3 !== 0 ? (r3 - n2.y) / l3 : Number.NEGATIVE_INFINITY, p3 = l3 !== 0 ? (a3 - n2.y) / l3 : Number.POSITIVE_INFINITY, m2 = Math.max(Math.min(h2, d2), Math.min(u2, p3)), g2 = Math.min(Math.max(h2, d2), Math.max(u2, p3));\n if (m2 \u003c= g2 \u0026\u0026 g2 \u003e= 0 \u0026\u0026 m2 \u003c= 1) {\n const e36 = Math.max(0, Math.min(1, m2));\n return { x: n2.x + e36 * c3, y: n2.y + e36 * l3 };\n }\n const f2 = { x: Math.max(i3, Math.min(s2, n2.x)), y: Math.max(r3, Math.min(a3, n2.y)) }, _2 = { x: Math.max(i3, Math.min(s2, o3.x)), y: Math.max(r3, Math.min(a3, o3.y)) }, y2 = (f2.x - n2.x) ** 2 + (f2.y - n2.y) ** 2, b2 = (_2.x - o3.x) ** 2 + (_2.y - o3.y) ** 2, x2 = [{ start: { x: i3, y: r3 }, end: { x: s2, y: r3 } }, { start: { x: s2, y: r3 }, end: { x: s2, y: a3 } }, { start: { x: s2, y: a3 }, end: { x: i3, y: a3 } }, { start: { x: i3, y: a3 }, end: { x: i3, y: r3 } }];\n let v2 = Math.min(y2, b2), I2 = y2 \u003c= b2 ? f2 : _2;\n const S2 = (e36, t3, n3) =\u003e Math.max(t3, Math.min(n3, e36));\n for (const e36 of x2) {\n const t3 = { x: o3.x - n2.x, y: o3.y - n2.y }, i4 = { x: e36.end.x - e36.start.x, y: e36.end.y - e36.start.y }, r4 = { x: n2.x - e36.start.x, y: n2.y - e36.start.y }, s3 = t3.x * t3.x + t3.y * t3.y, a4 = t3.x * i4.x + t3.y * i4.y, c4 = t3.x * r4.x + t3.y * r4.y, l4 = i4.x * i4.x + i4.y * i4.y, h3 = i4.x * r4.x + i4.y * r4.y, d3 = s3 * l4 - a4 * a4;\n if (Math.abs(d3) \u003c 0.0000000001)\n continue;\n let u3 = (a4 * h3 - l4 * c4) / d3, p4 = (s3 * h3 - a4 * c4) / d3;\n u3 = S2(u3, 0, 1), p4 = S2(p4, 0, 1);\n const m3 = { x: n2.x + u3 * t3.x, y: n2.y + u3 * t3.y }, g3 = { x: e36.start.x + p4 * i4.x, y: e36.start.y + p4 * i4.y }, f3 = m3.x - g3.x, _3 = m3.y - g3.y, y3 = f3 * f3 + _3 * _3;\n y3 \u003c v2 \u0026\u0026 (v2 = y3, I2 = { x: (m3.x + g3.x) / 2, y: (m3.y + g3.y) / 2 });\n }\n return I2;\n};\nvar JC = (e35, t2) =\u003e {\n const n2 = { x: e35.x1, y: e35.y1 }, o3 = { x: e35.x2, y: e35.y2 }, i3 = { x: t2.x1, y: t2.y1 }, r3 = { x: t2.x2, y: t2.y2 }, s2 = { x: o3.x - n2.x, y: o3.y - n2.y }, a3 = { x: r3.x - i3.x, y: r3.y - i3.y }, c3 = s2.x * s2.x + s2.y * s2.y, l3 = a3.x * a3.x + a3.y * a3.y;\n if (c3 === 0 || l3 === 0) {\n if (c3 === 0 \u0026\u0026 l3 === 0)\n return { x: (n2.x + i3.x) / 2, y: (n2.y + i3.y) / 2 };\n if (c3 === 0) {\n const e37 = KC(((n2.x - i3.x) * a3.x + (n2.y - i3.y) * a3.y) / l3, 0, 1), t4 = { x: i3.x + e37 * a3.x, y: i3.y + e37 * a3.y };\n return { x: (n2.x + t4.x) / 2, y: (n2.y + t4.y) / 2 };\n }\n const e36 = KC(((i3.x - n2.x) * s2.x + (i3.y - n2.y) * s2.y) / c3, 0, 1), t3 = { x: n2.x + e36 * s2.x, y: n2.y + e36 * s2.y };\n return { x: (t3.x + i3.x) / 2, y: (t3.y + i3.y) / 2 };\n }\n const h2 = n2.x - i3.x, d2 = n2.y - i3.y, u2 = s2.x * s2.x + s2.y * s2.y, p3 = s2.x * a3.x + s2.y * a3.y, m2 = s2.x * h2 + s2.y * d2, g2 = a3.x * a3.x + a3.y * a3.y, f2 = a3.x * h2 + a3.y * d2, _2 = u2 * g2 - p3 * p3;\n if (_2 \u003c 0.0000000001)\n return QC(n2, o3, i3, r3, s2, a3, c3, l3);\n let y2 = (p3 * f2 - g2 * m2) / _2, b2 = (u2 * f2 - p3 * m2) / _2;\n y2 = KC(y2, 0, 1), b2 = KC(b2, 0, 1), b2 = (y2 * p3 + f2) / g2, b2 = KC(b2, 0, 1), y2 = (b2 * p3 - m2) / u2, y2 = KC(y2, 0, 1);\n const x2 = n2.x + y2 * s2.x, v2 = n2.y + y2 * s2.y, I2 = i3.x + b2 * a3.x, S2 = i3.y + b2 * a3.y, C = x2 - I2, P = v2 - S2;\n Math.sqrt(C * C + P * P);\n return { x: (x2 + I2) / 2, y: (v2 + S2) / 2 };\n};\nvar QC = (e35, t2, n2, o3, i3, r3, s2, a3) =\u003e {\n let c3 = ((n2.x - e35.x) * i3.x + (n2.y - e35.y) * i3.y) / s2;\n c3 = KC(c3, 0, 1);\n const l3 = { x: e35.x + c3 * i3.x, y: e35.y + c3 * i3.y };\n let h2 = ((o3.x - e35.x) * i3.x + (o3.y - e35.y) * i3.y) / s2;\n h2 = KC(h2, 0, 1);\n const d2 = { x: e35.x + h2 * i3.x, y: e35.y + h2 * i3.y };\n let u2 = ((e35.x - n2.x) * r3.x + (e35.y - n2.y) * r3.y) / a3;\n u2 = KC(u2, 0, 1);\n const p3 = { x: n2.x + u2 * r3.x, y: n2.y + u2 * r3.y };\n let m2 = ((t2.x - n2.x) * r3.x + (t2.y - n2.y) * r3.y) / a3;\n m2 = KC(m2, 0, 1);\n const g2 = { x: n2.x + m2 * r3.x, y: n2.y + m2 * r3.y }, f2 = [{ pointA: l3, pointB: n2, distance: Math.sqrt((l3.x - n2.x) ** 2 + (l3.y - n2.y) ** 2) }, { pointA: d2, pointB: o3, distance: Math.sqrt((d2.x - o3.x) ** 2 + (d2.y - o3.y) ** 2) }, { pointA: e35, pointB: p3, distance: Math.sqrt((e35.x - p3.x) ** 2 + (e35.y - p3.y) ** 2) }, { pointA: t2, pointB: g2, distance: Math.sqrt((t2.x - g2.x) ** 2 + (t2.y - g2.y) ** 2) }].reduce((e36, t3) =\u003e t3.distance \u003c e36.distance ? t3 : e36);\n return { x: (f2.pointA.x + f2.pointB.x) / 2, y: (f2.pointA.y + f2.pointB.y) / 2 };\n};\nvar KC = (e35, t2, n2) =\u003e Math.max(t2, Math.min(n2, e35));\nvar eP = (e35) =\u003e e35.type === \"pcb_trace_segment\" ? { minX: Math.min(e35.x1, e35.x2), minY: Math.min(e35.y1, e35.y2), maxX: Math.max(e35.x1, e35.x2), maxY: Math.max(e35.y1, e35.y2) } : ((e36) =\u003e {\n let { POSITIVE_INFINITY: t2, POSITIVE_INFINITY: n2, NEGATIVE_INFINITY: o3, NEGATIVE_INFINITY: i3 } = Number;\n for (const r3 of e36) {\n if (!r3.type.startsWith(\"pcb_\"))\n continue;\n if (r3.type === \"pcb_smtpad\" \u0026\u0026 r3.shape === \"polygon\" \u0026\u0026 Array.isArray(r3.points)) {\n for (const e38 of r3.points)\n t2 = Math.min(t2, e38.x), n2 = Math.min(n2, e38.y), o3 = Math.max(o3, e38.x), i3 = Math.max(i3, e38.y);\n continue;\n }\n if (r3.type === \"pcb_hole\" \u0026\u0026 r3.hole_shape === \"circle\") {\n const e38 = FC(r3.x, r3.y, r3.hole_diameter);\n t2 = Math.min(t2, e38.minX), n2 = Math.min(n2, e38.minY), o3 = Math.max(o3, e38.maxX), i3 = Math.max(i3, e38.maxY);\n continue;\n }\n if (r3.type === \"pcb_plated_hole\") {\n let e38;\n if (\"outer_diameter\" in r3 \u0026\u0026 typeof r3.outer_diameter == \"number\" ? e38 = FC(r3.x, r3.y, r3.outer_diameter) : (\"hole_diameter\" in r3) \u0026\u0026 typeof r3.hole_diameter == \"number\" \u0026\u0026 (e38 = FC(r3.x, r3.y, r3.hole_diameter)), \"rect_pad_width\" in r3 \u0026\u0026 typeof r3.rect_pad_width == \"number\" \u0026\u0026 \"rect_pad_height\" in r3 \u0026\u0026 typeof r3.rect_pad_height == \"number\") {\n const t3 = jC(r3.x, r3.y, r3.rect_pad_width, r3.rect_pad_height, \"rect_ccw_rotation\" in r3 ? r3.rect_ccw_rotation ?? 0 : 0);\n e38 = e38 ? BC(e38, t3) : t3;\n }\n if (\"hole_diameter\" in r3 \u0026\u0026 typeof r3.hole_diameter == \"number\") {\n const t3 = FC(r3.x + (\"hole_offset_x\" in r3 ? r3.hole_offset_x ?? 0 : 0), r3.y + (\"hole_offset_y\" in r3 ? r3.hole_offset_y ?? 0 : 0), r3.hole_diameter);\n e38 = e38 ? BC(e38, t3) : t3;\n }\n if (e38) {\n t2 = Math.min(t2, e38.minX), n2 = Math.min(n2, e38.minY), o3 = Math.max(o3, e38.maxX), i3 = Math.max(i3, e38.maxY);\n continue;\n }\n }\n let e37, s2, a3, c3;\n if (\"x\" in r3 \u0026\u0026 \"y\" in r3 \u0026\u0026 (e37 = Number(r3.x), s2 = Number(r3.y)), \"outer_diameter\" in r3 \u0026\u0026 (a3 = Number(r3.outer_diameter), c3 = Number(r3.outer_diameter)), \"width\" in r3 \u0026\u0026 (a3 = Number(r3.width)), \"height\" in r3 \u0026\u0026 (c3 = Number(r3.height)), \"center\" in r3 \u0026\u0026 (e37 = r3.center.x, s2 = r3.center.y), e37 !== undefined \u0026\u0026 s2 !== undefined)\n t2 = Math.min(t2, e37), n2 = Math.min(n2, s2), o3 = Math.max(o3, e37), i3 = Math.max(i3, s2), a3 !== undefined \u0026\u0026 c3 !== undefined \u0026\u0026 (t2 = Math.min(t2, e37 - a3 / 2), n2 = Math.min(n2, s2 - c3 / 2), o3 = Math.max(o3, e37 + a3 / 2), i3 = Math.max(i3, s2 + c3 / 2)), \"radius\" in r3 \u0026\u0026 (t2 = Math.min(t2, e37 - r3.radius), n2 = Math.min(n2, s2 - r3.radius), o3 = Math.max(o3, e37 + r3.radius), i3 = Math.max(i3, s2 + r3.radius));\n else if (r3.type === \"pcb_trace\")\n for (const e38 of r3.route)\n t2 = Math.min(t2, e38.x), n2 = Math.min(n2, e38.y), o3 = Math.max(o3, e38.x), i3 = Math.max(i3, e38.y);\n else if (r3.type === \"pcb_courtyard_outline\")\n for (const e38 of r3.outline)\n t2 = Math.min(t2, e38.x), n2 = Math.min(n2, e38.y), o3 = Math.max(o3, e38.x), i3 = Math.max(i3, e38.y);\n else if (r3.type === \"pcb_courtyard_polygon\")\n for (const e38 of r3.points)\n t2 = Math.min(t2, e38.x), n2 = Math.min(n2, e38.y), o3 = Math.max(o3, e38.x), i3 = Math.max(i3, e38.y);\n }\n return { minX: t2, minY: n2, maxX: o3, maxY: i3 };\n})([e35]);\nfunction tP(e35) {\n const t2 = new Set;\n for (const n2 of e35.route)\n n2.route_type === \"wire\" \u0026\u0026 (n2.start_pcb_port_id \u0026\u0026 t2.add(n2.start_pcb_port_id), n2.end_pcb_port_id \u0026\u0026 t2.add(n2.end_pcb_port_id));\n return Array.from(t2);\n}\nfunction nP(e35) {\n const t2 = new Set;\n for (const n2 of e35)\n for (const e36 of tP(n2))\n t2.add(e36);\n return Array.from(t2);\n}\nvar oP = (e35) =\u003e {\n if (e35.type === \"pcb_via\")\n return e35.outer_diameter / 2;\n if (e35.type === \"pcb_plated_hole\" \u0026\u0026 e35.shape === \"circle\")\n return e35.outer_diameter / 2;\n if (e35.type === \"pcb_hole\" \u0026\u0026 e35.hole_shape === \"circle\")\n return e35.hole_diameter / 2;\n if (e35.type === \"pcb_smtpad\" \u0026\u0026 e35.shape === \"circle\")\n return e35.radius;\n throw new Error(`Could not determine radius of element: ${JSON.stringify(e35)}`);\n};\nfunction iP(e35, { connMap: t2, minClearance: n2 = 0.1 } = {}) {\n const o3 = [];\n ((e36) =\u003e {\n const t3 = e36.filter((e37) =\u003e e37.type === \"pcb_port\"), n3 = e36.filter((e37) =\u003e e37.type === \"pcb_smtpad\"), o4 = e36.filter((e37) =\u003e e37.type === \"pcb_trace\");\n function i4(e37, o5 = {}) {\n const i5 = o5.traceWidth || 0, r4 = t3.find((t4) =\u003e YC(t4.x, t4.y, e37.x, e37.y) \u003c 0.01);\n if (r4)\n return r4.pcb_port_id;\n if (o5.isFirstOrLastPoint) {\n const t4 = n3.find((t5) =\u003e t5.shape === \"rect\" ? Math.abs(e37.x - t5.x) \u003c t5.width / 2 + i5 / 2 \u0026\u0026 Math.abs(e37.y - t5.y) \u003c t5.height / 2 + i5 / 2 : t5.shape === \"circle\" ? YC(e37.x, e37.y, t5.x, t5.y) \u003c t5.radius : undefined);\n if (t4)\n return t4.pcb_port_id ?? null;\n }\n return null;\n }\n for (const e37 of o4)\n for (let t4 = 0;t4 \u003c e37.route.length; t4++) {\n const n4 = e37.route[t4], o5 = t4 === 0 || t4 === e37.route.length - 1;\n if (n4.route_type === \"wire\") {\n if (!n4.start_pcb_port_id \u0026\u0026 t4 === 0) {\n const e38 = i4(n4, { isFirstOrLastPoint: o5, traceWidth: n4.width });\n e38 \u0026\u0026 (n4.start_pcb_port_id = e38);\n }\n if (!n4.end_pcb_port_id \u0026\u0026 t4 === e37.route.length - 1) {\n const e38 = i4(n4, { isFirstOrLastPoint: o5, traceWidth: n4.width });\n e38 \u0026\u0026 (n4.end_pcb_port_id = e38);\n }\n }\n }\n })(e35), t2 ??= Rb(e35);\n const i3 = EC(e35).pcb_trace.list().flatMap((e36) =\u003e {\n const t3 = [];\n for (let n3 = 0;n3 \u003c e36.route.length - 1; n3++) {\n const o4 = e36.route[n3], i4 = e36.route[n3 + 1];\n o4.route_type === \"wire\" \u0026\u0026 (i4.route_type === \"wire\" \u0026\u0026 o4.layer === i4.layer \u0026\u0026 t3.push({ type: \"pcb_trace_segment\", pcb_trace_id: e36.pcb_trace_id, _pcbTrace: e36, thickness: \"width\" in o4 ? o4.width : (\"width\" in i4) ? i4.width : VC, layer: o4.layer, x1: o4.x, y1: o4.y, x2: i4.x, y2: i4.y }));\n }\n return t3;\n }), r3 = EC(e35).pcb_smtpad.list(), s2 = EC(e35).pcb_plated_hole.list(), a3 = EC(e35).pcb_hole.list(), c3 = EC(e35).pcb_via.list(), l3 = EC(e35).pcb_keepout.list(), h2 = [...i3, ...r3, ...s2, ...a3, ...c3, ...l3], d2 = new XC({ objects: h2, getBounds: eP }), u2 = (t3) =\u003e zC(e35, t3), p3 = (e36, t3, n3) =\u003e n3 \u003c 0 ? `PCB trace ${e36} overlaps with ${t3} (accidental contact)` : `PCB trace ${e36} is too close to ${t3} (gap: ${n3.toFixed(3)}mm)`, m2 = new Set;\n for (const e36 of i3) {\n const i4 = n2, r4 = eP(e36), s3 = d2.getObjectsInBounds(r4, i4 + e36.thickness / 2);\n if (e36.x1 !== e36.x2 || e36.y1 !== e36.y2)\n for (const r5 of s3) {\n if (!ZC(r5).includes(e36.layer))\n continue;\n if (r5.type === \"pcb_trace_segment\") {\n const i5 = r5;\n if (e36.layer !== i5.layer)\n continue;\n if (t2.areIdsConnected(e36.pcb_trace_id, i5.pcb_trace_id))\n continue;\n const s5 = we({ x: e36.x1, y: e36.y1 }, { x: e36.x2, y: e36.y2 }, { x: i5.x1, y: i5.y1 }, { x: i5.x2, y: i5.y2 }) - e36.thickness / 2 - i5.thickness / 2;\n if (s5 \u003e n2 - UC)\n continue;\n const a5 = `overlap_${e36.pcb_trace_id}_${i5.pcb_trace_id}`, c4 = `overlap_${i5.pcb_trace_id}_${e36.pcb_trace_id}`;\n if (m2.has(a5))\n continue;\n if (m2.has(c4))\n continue;\n m2.add(a5), o3.push({ type: \"pcb_trace_error\", error_type: \"pcb_trace_error\", message: p3(u2(e36.pcb_trace_id), u2(i5.pcb_trace_id), s5), pcb_trace_id: e36.pcb_trace_id, source_trace_id: \"\", pcb_trace_error_id: a5, pcb_component_ids: [], center: JC(e36, i5), pcb_port_ids: nP([e36._pcbTrace, i5._pcbTrace]) });\n continue;\n }\n const s4 = $C(r5);\n if (t2.areIdsConnected(e36.pcb_trace_id, \"pcb_trace_id\" in r5 ? r5.pcb_trace_id : s4))\n continue;\n if (r5.type === \"pcb_via\" || r5.type === \"pcb_plated_hole\" \u0026\u0026 r5.shape === \"circle\" || r5.type === \"pcb_hole\" || r5.type === \"pcb_smtpad\" \u0026\u0026 r5.shape === \"circle\") {\n const t3 = oP(r5), i5 = Te({ x: e36.x1, y: e36.y1 }, { x: e36.x2, y: e36.y2 }, { x: r5.x, y: r5.y, radius: t3 }) - e36.thickness / 2;\n if (i5 \u003e n2 - UC)\n continue;\n const a5 = `overlap_${e36.pcb_trace_id}_${s4}`;\n if (m2.has(a5))\n continue;\n m2.add(a5), o3.push({ type: \"pcb_trace_error\", error_type: \"pcb_trace_error\", message: p3(u2(e36.pcb_trace_id), `${r5.type} \"${u2($C(r5))}\"`, i5), pcb_trace_id: e36.pcb_trace_id, center: qC(e36, eP(r5)), source_trace_id: \"\", pcb_trace_error_id: a5, pcb_component_ids: [\"pcb_component_id\" in r5 ? r5.pcb_component_id : undefined].filter(Boolean), pcb_port_ids: [...nP([e36._pcbTrace]), \"pcb_port_id\" in r5 ? r5.pcb_port_id : undefined].filter(Boolean) });\n }\n const a4 = Ne({ x: e36.x1, y: e36.y1 }, { x: e36.x2, y: e36.y2 }, eP(r5)) - e36.thickness / 2;\n if (a4 + UC \u003c i4) {\n const t3 = `overlap_${e36.pcb_trace_id}_${s4}`;\n if (m2.has(t3))\n continue;\n m2.add(t3), o3.push({ type: \"pcb_trace_error\", error_type: \"pcb_trace_error\", message: p3(u2(e36.pcb_trace_id), `${r5.type} \"${u2($C(r5))}\"`, a4), pcb_trace_id: e36.pcb_trace_id, source_trace_id: \"\", pcb_trace_error_id: t3, pcb_component_ids: [\"pcb_component_id\" in r5 ? r5.pcb_component_id : undefined].filter(Boolean), center: qC(e36, eP(r5)), pcb_port_ids: [...nP([e36._pcbTrace]), \"pcb_port_id\" in r5 ? r5.pcb_port_id : undefined].filter(Boolean) });\n }\n }\n }\n return o3;\n}\nfunction rP(e35, t2) {\n return Math.hypot(e35.x - t2.x, e35.y - t2.y);\n}\nfunction sP(e35, t2) {\n return rP(e35, t2) \u003c= UC;\n}\nfunction aP(e35, { connMap: t2, minClearance: n2 = WC } = {}) {\n const o3 = e35.filter((e36) =\u003e e36.type === \"pcb_via\");\n if (o3.length \u003c 2)\n return [];\n t2 ??= Rb(e35);\n const i3 = [], r3 = new Set;\n for (let s2 = 0;s2 \u003c o3.length; s2++)\n for (let a3 = s2 + 1;a3 \u003c o3.length; a3++) {\n const c3 = o3[s2], l3 = o3[a3];\n if (sP(c3, l3))\n continue;\n if (!t2.areIdsConnected(c3.pcb_via_id, l3.pcb_via_id))\n continue;\n const h2 = rP(c3, l3) - c3.outer_diameter / 2 - l3.outer_diameter / 2;\n if (h2 + UC \u003e= n2)\n continue;\n const d2 = [c3.pcb_via_id, l3.pcb_via_id].sort().join(\"_\");\n r3.has(d2) || (r3.add(d2), i3.push({ type: \"pcb_via_clearance_error\", pcb_error_id: `same_net_vias_close_${d2}`, message: `Vias ${zC(e35, c3.pcb_via_id)} and ${zC(e35, l3.pcb_via_id)} are too close together (gap: ${h2.toFixed(3)}mm)`, error_type: \"pcb_via_clearance_error\", pcb_via_ids: [c3.pcb_via_id, l3.pcb_via_id], minimum_clearance: n2, actual_clearance: h2, pcb_center: { x: (c3.x + l3.x) / 2, y: (c3.y + l3.y) / 2 } }));\n }\n return i3;\n}\nfunction cP(e35, { connMap: t2, minClearance: n2 = GC } = {}) {\n const o3 = e35.filter((e36) =\u003e e36.type === \"pcb_via\");\n if (o3.length \u003c 2)\n return [];\n t2 ??= Rb(e35);\n const i3 = [], r3 = new Set;\n for (let s2 = 0;s2 \u003c o3.length; s2++)\n for (let a3 = s2 + 1;a3 \u003c o3.length; a3++) {\n const c3 = o3[s2], l3 = o3[a3];\n if (sP(c3, l3))\n continue;\n if (t2.areIdsConnected(c3.pcb_via_id, l3.pcb_via_id))\n continue;\n const h2 = rP(c3, l3) - c3.outer_diameter / 2 - l3.outer_diameter / 2;\n if (h2 + UC \u003e= n2)\n continue;\n const d2 = [c3.pcb_via_id, l3.pcb_via_id].sort().join(\"_\");\n r3.has(d2) || (r3.add(d2), i3.push({ type: \"pcb_via_clearance_error\", pcb_error_id: `different_net_vias_close_${d2}`, message: `Vias ${zC(e35, c3.pcb_via_id)} and ${zC(e35, l3.pcb_via_id)} from different nets are too close together (gap: ${h2.toFixed(3)}mm)`, error_type: \"pcb_via_clearance_error\", pcb_via_ids: [c3.pcb_via_id, l3.pcb_via_id], minimum_clearance: n2, actual_clearance: h2, pcb_center: { x: (c3.x + l3.x) / 2, y: (c3.y + l3.y) / 2 } }));\n }\n return i3;\n}\nvar lP = (e35) =\u003e ({ minSpacing: e35, minClearance: e35 });\nvar hP = { traceClearance: 0.1, viaClearance: 0.1 };\nvar dP = (e35) =\u003e ((e36) =\u003e (\"layer\" in e36))(e35) ? [e35.layer] : e35.layers;\nfunction uP(e35, t2, n2) {\n let o3, i3 = Number.POSITIVE_INFINITY;\n for (const r3 of t2) {\n const t3 = n2.get(r3);\n if (!t3)\n continue;\n const s2 = Math.hypot(t3.x - e35.x, t3.y - e35.y);\n s2 \u003c i3 \u0026\u0026 (i3 = s2, o3 = r3);\n }\n return o3 ?? t2[0];\n}\nfunction pP(e35) {\n const t2 = [], n2 = new Set, o3 = new Set, i3 = function(e36) {\n const t3 = new Map;\n for (const n3 of e36.connections)\n for (const e37 of n3.pointsToConnect)\n e37.pcb_port_id \u0026\u0026 t3.set(e37.pcb_port_id, { x: e37.x, y: e37.y });\n return t3;\n }(e35);\n for (const r3 of e35.obstacles) {\n const e36 = r3.connectedTo, s2 = e36.find((e37) =\u003e e37.startsWith(\"pcb_smtpad_\")), a3 = e36.find((e37) =\u003e e37.startsWith(\"pcb_plated_hole_\")), c3 = e36.filter((e37) =\u003e e37.startsWith(\"pcb_port_\")), l3 = uP(r3.center, c3, i3);\n if (!s2 \u0026\u0026 !a3 \u0026\u0026 !l3)\n continue;\n const h2 = r3.layers;\n if (h2.length === 0)\n continue;\n const { width: d2, height: u2 } = r3, p3 = r3.center.x, m2 = r3.center.y, g2 = r3.ccwRotationDegrees, f2 = typeof g2 == \"number\" \u0026\u0026 Number.isFinite(g2);\n if (h2.length \u003e 1) {\n const e37 = a3 ?? `pcb_plated_hole_${p3.toFixed(3)}_${m2.toFixed(3)}`;\n if (o3.has(e37))\n continue;\n if (o3.add(e37), f2) {\n const n3 = Math.max(0.5 * Math.min(d2, u2), 0.1);\n t2.push({ type: \"pcb_plated_hole\", pcb_plated_hole_id: e37, shape: \"rotated_pill_hole_with_rect_pad\", hole_shape: \"rotated_pill\", pad_shape: \"rect\", hole_width: n3, hole_height: n3, hole_ccw_rotation: g2, rect_pad_width: d2, rect_pad_height: u2, rect_ccw_rotation: g2, hole_offset_x: 0, hole_offset_y: 0, x: p3, y: m2, layers: h2, ...l3 ? { pcb_port_id: l3 } : {} });\n continue;\n }\n if (Math.abs(d2 - u2) \u003c 0.001) {\n t2.push({ type: \"pcb_plated_hole\", pcb_plated_hole_id: e37, shape: \"circle\", outer_diameter: Math.max(d2, u2), hole_diameter: Math.max(0.5 * Math.min(d2, u2), 0.1), x: p3, y: m2, layers: h2, ...l3 ? { pcb_port_id: l3 } : {} });\n continue;\n }\n t2.push({ type: \"pcb_plated_hole\", pcb_plated_hole_id: e37, shape: \"circular_hole_with_rect_pad\", hole_shape: \"circle\", hole_diameter: Math.max(0.5 * Math.min(d2, u2), 0.1), rect_pad_width: d2, rect_pad_height: u2, hole_offset_x: 0, hole_offset_y: 0, x: p3, y: m2, layers: h2, ...l3 ? { pcb_port_id: l3 } : {} });\n continue;\n }\n const _2 = s2 ?? `pcb_smtpad_${p3.toFixed(3)}_${m2.toFixed(3)}`;\n n2.has(_2) || (n2.add(_2), f2 ? t2.push({ type: \"pcb_smtpad\", pcb_smtpad_id: _2, layer: h2[0], shape: \"rotated_rect\", x: p3, y: m2, width: d2, height: u2, ccw_rotation: g2, ...l3 ? { pcb_port_id: l3 } : {} }) : t2.push({ type: \"pcb_smtpad\", pcb_smtpad_id: _2, layer: h2[0], shape: \"rect\", width: d2, height: u2, x: p3, y: m2, ...l3 ? { pcb_port_id: l3 } : {} }));\n }\n return t2;\n}\nfunction mP(e35, t2, n2 = 0.1, o3 = e35.minViaDiameter ?? 0.3) {\n const i3 = [];\n i3.push(...function(e36, t3) {\n const n3 = [];\n return e36.connections.forEach((o4) =\u003e {\n const i4 = o4.pointsToConnect.filter((e37) =\u003e e37.pcb_port_id).map((e37) =\u003e e37.pcb_port_id).filter(Boolean), r4 = o4.netConnectionName || o4.rootConnectionName || o4.name, s2 = [], a3 = t3.find((e37) =\u003e (e37.connection_name ?? e37.connectionName) === o4.name);\n if (a3) {\n const t4 = (e37) =\u003e (\"route_type\" in e37) \u0026\u0026 e37.route_type === \"jumper\" ? e37.start : (\"x\" in e37) \u0026\u0026 (\"y\" in e37) ? { x: e37.x, y: e37.y } : { x: 0, y: 0 }, n4 = [t4(a3.route[0]), t4(a3.route[a3.route.length - 1])];\n for (const t5 of n4)\n for (const n5 of e36.obstacles)\n Oe(t5, n5) \u003c= 0 \u0026\u0026 s2.push(n5);\n }\n const c3 = n3.find((e37) =\u003e e37.type === \"source_trace\" \u0026\u0026 e37.source_trace_id === r4);\n if (c3) {\n const e37 = c3;\n e37.connected_source_port_ids = [...new Set([...e37.connected_source_port_ids, ...i4])];\n } else\n n3.push({ type: \"source_trace\", source_trace_id: r4, connected_source_port_ids: i4.concat(s2.flatMap((e37) =\u003e [`obstacle_${e37.center.x.toFixed(3)}_${e37.center.y.toFixed(3)}_${e37.layers.join(\".\")}`, ...e37.connectedTo])), connected_source_net_ids: [] });\n }), n3;\n }(e35, t2)), i3.push(...function(e36) {\n const t3 = new Map;\n return e36.connections.forEach((e37) =\u003e {\n e37.pointsToConnect.forEach((e38) =\u003e {\n e38.pcb_port_id \u0026\u0026 t3.set(e38.pcb_port_id, { type: \"pcb_port\", pcb_port_id: e38.pcb_port_id, source_port_id: e38.pcb_port_id, x: e38.x, y: e38.y, layers: dP(e38) });\n });\n }), Array.from(t3.values());\n }(e35)), i3.push(...pP(e35)), i3.push(...function({ routes: e36, layerCount: t3, minViaDiameter: n3 = 0.3, allowBlindAndBuriedVias: o4 = false }) {\n const i4 = [], r4 = new Set;\n return e36.length \u003e 0 \u0026\u0026 (\"type\" in e36[0] \u0026\u0026 e36[0].type === \"pcb_trace\" ? e36.forEach((e37) =\u003e {\n e37.route.forEach((s2) =\u003e {\n if (s2.route_type === \"via\") {\n const a3 = s2.via_diameter ?? n3, c3 = `${s2.x},${s2.y},${s2.from_layer},${s2.to_layer}`;\n r4.has(c3) || (i4.push({ type: \"pcb_via\", pcb_via_id: `via_${i4.length}`, pcb_trace_id: e37.pcb_trace_id, x: s2.x, y: s2.y, outer_diameter: a3, hole_diameter: 0.5 * a3, layers: eb({ via: s2, layerCount: t3, allowBlindAndBuriedVias: o4 }) }), r4.add(c3));\n }\n });\n }) : e36.forEach((e37, s2) =\u003e {\n const a3 = `trace_${s2}`, c3 = e37.viaDiameter ?? n3;\n for (let n4 = 1;n4 \u003c e37.route.length; n4++) {\n const s3 = e37.route[n4 - 1], l3 = e37.route[n4];\n if (s3.z !== l3.z \u0026\u0026 Math.abs(s3.x - l3.x) \u003c 0.01 \u0026\u0026 Math.abs(s3.y - l3.y) \u003c 0.01) {\n const e38 = Qy(s3.z, t3), n5 = Qy(l3.z, t3), h2 = `${l3.x},${l3.y},${e38},${n5}`;\n r4.has(h2) || (i4.push({ type: \"pcb_via\", pcb_via_id: `via_${i4.length}`, pcb_trace_id: a3, x: l3.x, y: l3.y, outer_diameter: c3, hole_diameter: 0.5 * c3, layers: eb({ via: { from_layer: e38, to_layer: n5 }, layerCount: t3, allowBlindAndBuriedVias: o4 }) }), r4.add(h2));\n }\n }\n })), i4;\n }({ routes: t2, layerCount: e35.layerCount, minViaDiameter: o3, allowBlindAndBuriedVias: e35.allowBlindAndBuriedVias }));\n const r3 = new Map;\n return e35.connections.forEach((e36) =\u003e {\n r3.set(e36.name, e36.netConnectionName || e36.rootConnectionName || e36.name);\n }), t2.length \u003e 0 \u0026\u0026 (\"type\" in t2[0] \u0026\u0026 t2[0].type === \"pcb_trace\" ? t2.forEach((e36) =\u003e {\n const t3 = e36.connection_name;\n i3.push(function(e37, t4) {\n return { type: \"pcb_trace\", pcb_trace_id: e37.pcb_trace_id, source_trace_id: t4, route: e37.route.map((e38) =\u003e e38.route_type === \"wire\" ? { route_type: \"wire\", x: e38.x, y: e38.y, width: e38.width, layer: e38.layer, start_pcb_port_id: e38.start_pcb_port_id, end_pcb_port_id: e38.end_pcb_port_id } : e38.route_type === \"via\" ? { route_type: \"via\", x: e38.x, y: e38.y, from_layer: e38.from_layer, to_layer: e38.to_layer } : null).filter((e38) =\u003e e38 !== null) };\n }(e36, r3.get(t3) || t3));\n }) : t2.forEach((t3, o4) =\u003e {\n const s2 = t3.connectionName, a3 = function(e36, t4, n3, o5 = 0.1, i4) {\n const r4 = [];\n if (!e36.jumpers || e36.jumpers.length === 0)\n return [{ type: \"pcb_trace\", pcb_trace_id: t4, source_trace_id: n3, route: e36.route.map((t5, n4) =\u003e {\n const r5 = n4 === 0, s4 = n4 === e36.route.length - 1;\n return { route_type: \"wire\", x: t5.x, y: t5.y, width: o5, layer: Qy(t5.z, i4), ...r5 \u0026\u0026 t5.pcb_port_id ? { start_pcb_port_id: t5.pcb_port_id } : {}, ...s4 \u0026\u0026 t5.pcb_port_id ? { end_pcb_port_id: t5.pcb_port_id } : {} };\n }) }];\n const s3 = [];\n for (const t5 of e36.jumpers) {\n let n4 = -1, o6 = -1;\n for (let i5 = 0;i5 \u003c e36.route.length; i5++) {\n const r5 = e36.route[i5];\n Math.abs(r5.x - t5.start.x) \u003c 0.01 \u0026\u0026 Math.abs(r5.y - t5.start.y) \u003c 0.01 \u0026\u0026 (n4 = i5), Math.abs(r5.x - t5.end.x) \u003c 0.01 \u0026\u0026 Math.abs(r5.y - t5.end.y) \u003c 0.01 \u0026\u0026 (o6 = i5);\n }\n n4 !== -1 \u0026\u0026 o6 !== -1 \u0026\u0026 (n4 \u003e o6 \u0026\u0026 ([n4, o6] = [o6, n4]), s3.push({ startIdx: n4, endIdx: o6 }));\n }\n s3.sort((e37, t5) =\u003e e37.startIdx - t5.startIdx);\n let a4 = 0, c3 = 0;\n for (const { startIdx: l3, endIdx: h2 } of s3) {\n if (l3 \u003e= a4) {\n const s4 = e36.route.slice(a4, l3 + 1);\n s4.length \u003e 0 \u0026\u0026 (r4.push({ type: \"pcb_trace\", pcb_trace_id: `${t4}_${c3}`, source_trace_id: n3, route: s4.map((e37, t5) =\u003e {\n const n4 = t5 === 0 \u0026\u0026 a4 === 0;\n return { route_type: \"wire\", x: e37.x, y: e37.y, width: o5, layer: Qy(e37.z, i4), ...n4 \u0026\u0026 e37.pcb_port_id ? { start_pcb_port_id: e37.pcb_port_id } : {} };\n }) }), c3++);\n }\n a4 = h2;\n }\n if (a4 \u003c e36.route.length) {\n const s4 = e36.route.slice(a4);\n if (s4.length \u003e 0) {\n const e37 = true;\n r4.push({ type: \"pcb_trace\", pcb_trace_id: `${t4}_${c3}`, source_trace_id: n3, route: s4.map((t5, n4) =\u003e {\n const r5 = e37 \u0026\u0026 n4 === s4.length - 1;\n return { route_type: \"wire\", x: t5.x, y: t5.y, width: o5, layer: Qy(t5.z, i4), ...r5 \u0026\u0026 t5.pcb_port_id ? { end_pcb_port_id: t5.pcb_port_id } : {} };\n }) });\n }\n }\n return r4;\n }(t3, `trace_${o4}`, r3.get(s2) || s2, n2, e35.layerCount);\n i3.push(...a3);\n })), i3;\n}\nvar gP = (e35) =\u003e e35.rootConnectionName ?? e35.connectionName;\nvar fP = (e35, t2) =\u003e {\n if (e35 \u0026\u0026 t2)\n return e35.getNetConnectedToId(t2);\n};\nvar _P = (e35, t2) =\u003e t2 ? { ...e35, connections: e35.connections.map((e36) =\u003e {\n const n2 = fP(t2, e36.name) ?? fP(t2, e36.rootConnectionName) ?? e36.netConnectionName;\n return n2 ? { ...e36, netConnectionName: n2 } : e36;\n}), obstacles: e35.obstacles.map((e36) =\u003e {\n const n2 = new Set(e36.connectedTo);\n for (const o3 of e36.connectedTo) {\n const e37 = fP(t2, o3);\n e37 \u0026\u0026 n2.add(e37);\n }\n return { ...e36, connectedTo: [...n2] };\n}) } : e35;\nvar yP = (e35, t2, n2) =\u003e {\n if (!t2)\n return false;\n if (e35 === t2)\n return true;\n const o3 = n2?.getNetConnectedToId(e35), i3 = n2?.getNetConnectedToId(t2);\n return !(!o3 || !(o3 === i3 || e35 \u0026\u0026 o3 === t2)) || !(!i3 || i3 !== e35);\n};\nvar bP = (e35, t2, n2) =\u003e t2.connectedTo?.some((t3) =\u003e yP(e35, t3, n2)) ?? false;\nvar xP = (e35, t2, n2) =\u003e Math.max(t2, Math.min(e35, n2));\nvar vP = (e35, t2) =\u003e {\n e35.x = xP(e35.x, t2.minX, t2.maxX), e35.y = xP(e35.y, t2.minY, t2.maxY);\n};\nvar IP = (e35, t2) =\u003e ({ minX: e35.minX - t2, minY: e35.minY - t2, maxX: e35.maxX + t2, maxY: e35.maxY + t2 });\nvar SP = (e35, t2) =\u003e ({ minCellX: Math.floor(e35.minX / t2), maxCellX: Math.floor(e35.maxX / t2), minCellY: Math.floor(e35.minY / t2), maxCellY: Math.floor(e35.maxY / t2) });\nvar CP = (e35, t2) =\u003e `${e35}:${t2}`;\nvar PP = new WeakMap;\nvar MP = (e35, t2, n2) =\u003e {\n const o3 = new Map, i3 = Math.ceil(e35.length / 32);\n PP.set(o3, { bits: new Uint32Array(i3), wordGenerations: new Uint32Array(i3), generation: 0 });\n for (let i4 = 0;i4 \u003c e35.length; i4 += 1) {\n const r3 = e35[i4];\n if (!r3)\n continue;\n const s2 = SP(t2(r3), n2);\n for (let e36 = s2.minCellX;e36 \u003c= s2.maxCellX; e36 += 1)\n for (let t3 = s2.minCellY;t3 \u003c= s2.maxCellY; t3 += 1) {\n const n3 = CP(e36, t3), r4 = o3.get(n3);\n r4 ? r4.push(i4) : o3.set(n3, [i4]);\n }\n }\n return o3;\n};\nvar wP = (e35, t2, n2) =\u003e {\n let o3 = PP.get(e35);\n o3 || (o3 = { bits: new Uint32Array(0), wordGenerations: new Uint32Array(0), generation: 0 }, PP.set(e35, o3)), o3.generation += 1, o3.generation \u003e 4294967295 \u0026\u0026 (o3.wordGenerations.fill(0), o3.generation = 1);\n const i3 = o3.generation, r3 = SP(t2, n2);\n let s2 = 1 / 0, a3 = -1;\n for (let t3 = r3.minCellX;t3 \u003c= r3.maxCellX; t3 += 1)\n for (let n3 = r3.minCellY;n3 \u003c= r3.maxCellY; n3 += 1) {\n const r4 = e35.get(CP(t3, n3));\n if (r4)\n for (const e36 of r4) {\n const t4 = e36 \u003e\u003e\u003e 5;\n if (t4 \u003e= o3.bits.length) {\n const e37 = Math.max(t4 + 1, 2 * o3.bits.length), n4 = new Uint32Array(e37);\n n4.set(o3.bits);\n const i4 = new Uint32Array(e37);\n i4.set(o3.wordGenerations), o3.bits = n4, o3.wordGenerations = i4;\n }\n o3.wordGenerations[t4] !== i3 \u0026\u0026 (o3.wordGenerations[t4] = i3, o3.bits[t4] = 0), o3.bits[t4] = o3.bits[t4] | 1 \u003c\u003c (31 \u0026 e36), t4 \u003c s2 \u0026\u0026 (s2 = t4), t4 \u003e a3 \u0026\u0026 (a3 = t4);\n }\n }\n const c3 = [];\n for (let e36 = s2;e36 \u003c= a3; e36 += 1) {\n if (o3.wordGenerations[e36] !== i3)\n continue;\n let t3 = o3.bits[e36];\n for (;t3 !== 0; ) {\n const n3 = 31 - Math.clz32(t3 \u0026 -t3);\n c3.push(32 * e36 + n3), t3 \u0026= t3 - 1;\n }\n }\n return c3;\n};\nvar NP = 0.000001;\nvar RP = (e35, t2, n2) =\u003e {\n if (e35.length === 0)\n return [];\n const o3 = n2?.traceThickness ?? 0.1, i3 = e35[0], r3 = e35.at(-1), s2 = (e36) =\u003e {\n if (e36.pcb_port_id)\n return e36.pcb_port_id;\n const o4 = Qy(e36.z, t2);\n return n2?.connectionPoints?.find((t3) =\u003e {\n return t3.pcb_port_id \u0026\u0026 (n3 = t3, i4 = e36, Math.abs(n3.x - i4.x) \u003c= NP \u0026\u0026 Math.abs(n3.y - i4.y) \u003c= NP) \u0026\u0026 dP(t3).includes(o4);\n var n3, i4;\n })?.pcb_port_id;\n }, a3 = s2(i3), c3 = s2(r3), l3 = [{ route_type: \"wire\", x: i3.x, y: i3.y, width: o3, layer: Qy(i3.z, t2), ...a3 ? { start_pcb_port_id: a3 } : {}, ...e35.length === 1 \u0026\u0026 c3 ? { end_pcb_port_id: c3 } : {} }];\n for (let i4 = 1;i4 \u003c e35.length; i4 += 1) {\n const r4 = e35[i4 - 1], s3 = e35[i4];\n r4 \u0026\u0026 s3 \u0026\u0026 (r4.toNextSegmentType === \"through_obstacle\" || r4.z === s3.z || r4.x !== s3.x || r4.y !== s3.y ? l3.push({ route_type: \"wire\", x: s3.x, y: s3.y, width: o3, layer: Qy(s3.z, t2), ...i4 === e35.length - 1 \u0026\u0026 c3 ? { end_pcb_port_id: c3 } : {} }) : l3.push({ route_type: \"via\", x: s3.x, y: s3.y, from_layer: Qy(r4.z, t2), to_layer: Qy(s3.z, t2), ...n2?.viaDiameter ? { via_diameter: n2.viaDiameter } : {} }));\n }\n return l3;\n};\nvar TP = 1048576;\nvar EP = (e35) =\u003e ({ ...e35, route: e35.route.map((e36) =\u003e ({ ...e36 })), vias: e35.vias.map((e36) =\u003e ({ ...e36 })) });\nvar AP = (e35) =\u003e e35.map(EP);\nvar OP = (e35, t2) =\u003e {\n const n2 = new Set(t2);\n return e35.map((e36, t3) =\u003e n2.has(t3) ? EP(e36) : e36);\n};\nvar kP = (e35, t2) =\u003e Math.abs(e35.x - t2.x) \u003c= xb \u0026\u0026 Math.abs(e35.y - t2.y) \u003c= xb;\nvar DP = [\"pcb_smtpad\", \"pcb_plated_hole\", \"pcb_hole\", \"pcb_keepout\"];\nvar LP = (e35) =\u003e typeof e35.type == \"string\" ? e35.type : typeof e35.error_type == \"string\" ? e35.error_type : undefined;\nvar zP = (e35) =\u003e {\n if (LP(e35) === \"pcb_pad_trace_clearance_error\")\n return true;\n const t2 = typeof e35.message == \"string\" ? e35.message.toLowerCase() : \"\";\n return (t2.includes(\"pcb_trace\") || t2.includes(\"pcb trace\")) \u0026\u0026 DP.some((e36) =\u003e t2.includes(e36));\n};\nvar BP = (e35, t2, n2 = true) =\u003e {\n const o3 = [], i3 = new Map, r3 = new Map, s2 = new Map;\n for (let e36 = 0;e36 \u003c t2.length; e36 += 1) {\n const n3 = t2[e36];\n if (!n3)\n continue;\n const o4 = s2.get(n3.connectionName);\n o4 ? o4.push({ route: n3, routeIndex: e36 }) : s2.set(n3.connectionName, [{ route: n3, routeIndex: e36 }]);\n }\n for (const t3 of e35.connections) {\n const a3 = s2.get(t3.name) ?? [];\n for (let s3 = 0;s3 \u003c a3.length; s3 += 1) {\n const c3 = a3[s3];\n if (!c3)\n continue;\n const l3 = `${t3.name}_${s3}`;\n n2 \u0026\u0026 o3.push({ type: \"pcb_trace\", pcb_trace_id: l3, connection_name: t3.netConnectionName ?? t3.rootConnectionName ?? t3.name, route: RP(c3.route.route, e35.layerCount, { traceThickness: c3.route.traceThickness ?? t3.nominalTraceWidth ?? e35.nominalTraceWidth ?? e35.minTraceWidth, viaDiameter: c3.route.viaDiameter ?? e35.minViaDiameter, connectionPoints: t3.pointsToConnect }) }), i3.set(l3, c3.routeIndex), r3.set(l3, t3.name);\n }\n }\n return { traces: o3, traceRouteIndexById: i3, traceConnectionNameById: r3 };\n};\nvar FP = (e35) =\u003e {\n const t2 = typeof e35.message == \"string\" ? e35.message : \"\", n2 = t2.match(/gap: (-?\\d+(?:\\.\\d+)?)mm/), o3 = t2.match(/required: (-?\\d+(?:\\.\\d+)?)mm/);\n if (n2 \u0026\u0026 o3) {\n const e36 = Number.parseFloat(n2[1]), t3 = Number.parseFloat(o3[1]);\n if (Number.isFinite(e36) \u0026\u0026 Number.isFinite(t3))\n return Math.max(0, t3 - e36);\n }\n if (n2) {\n const e36 = Number.parseFloat(n2[1]), t3 = hP.traceClearance ?? 0.1;\n if (Number.isFinite(e36))\n return Math.max(0, t3 - e36);\n }\n return 1;\n};\nvar jP = { projectEngineError: (e35) =\u003e ({ ...e35, center: typeof e35.first_contact_center == \"object\" ? e35.first_contact_center : e35.center, message: typeof e35.first_contact_message == \"string\" ? e35.first_contact_message : e35.message, actual_clearance: typeof e35.first_actual_clearance == \"number\" ? e35.first_actual_clearance : e35.actual_clearance }), getErrorSeverity: FP };\nvar $P = { projectEngineError: (e35) =\u003e e35, getErrorSeverity: (e35) =\u003e {\n const t2 = Number(e35.minimum_clearance), n2 = Number(e35.worst_actual_clearance);\n return Number.isFinite(t2) \u0026\u0026 Number.isFinite(n2) ? Math.max(0, t2 - n2) : FP(e35);\n} };\nvar YP = (e35, t2 = FP) =\u003e e35.reduce((e36, n2) =\u003e e36 + t2(n2), 0);\nvar XP = (e35, t2, n2, o3, i3, r3 = jP) =\u003e {\n const s2 = n2?.inputMode === \"routes-only\";\n let a3 = i3 \u0026\u0026 !n2 || s2 ? e35 : _P(e35, o3), { traces: c3, traceRouteIndexById: l3, traceConnectionNameById: h2 } = BP(a3, t2, !s2);\n const d2 = n2?.({ srj: a3, routes: t2, traces: c3 });\n if (d2) {\n const e36 = Array.isArray(d2) ? d2 : d2.errors, t3 = Array.isArray(d2) ? d2 : d2.errorsWithCenters ?? d2.errors;\n return { rawErrors: e36, errors: t3, count: e36.length, issueScore: YP(t3, r3.getErrorSeverity), legacyIssueScore: YP(t3.filter((e37) =\u003e !uw(e37)), r3.getErrorSeverity), traceRouteIndexById: l3, traceConnectionNameById: h2 };\n }\n if (s2) {\n a3 = _P(e35, o3);\n const n3 = BP(a3, t2);\n c3 = n3.traces, l3 = n3.traceRouteIndexById, h2 = n3.traceConnectionNameById;\n }\n const u2 = i3?.evaluate(c3) ?? ((e36, t3 = {}) =\u003e {\n const n3 = Math.max(t3.viaClearance ?? 0.1, 0.1), o4 = [...iP(e36, lP(t3.traceClearance)), ...aP(e36, lP(n3)), ...cP(e36, lP(n3))], i4 = e36.filter((e37) =\u003e e37.type === \"pcb_via\"), r4 = new Map(i4.map((e37) =\u003e [e37.pcb_via_id, e37])), s3 = o4.map((e37) =\u003e {\n if (\"center\" in e37 \u0026\u0026 e37.center)\n return e37;\n if (\"pcb_center\" in e37 \u0026\u0026 e37.pcb_center)\n return { ...e37, center: e37.pcb_center };\n if (\"pcb_via_ids\" in e37 \u0026\u0026 Array.isArray(e37.pcb_via_ids)) {\n const [t4, n4] = e37.pcb_via_ids;\n if (typeof t4 != \"string\" || typeof n4 != \"string\")\n return e37;\n const o5 = r4.get(t4), i5 = r4.get(n4);\n if (o5 \u0026\u0026 i5)\n return { ...e37, center: { x: (o5.x + i5.x) / 2, y: (o5.y + i5.y) / 2 } };\n }\n if (\"pcb_error_id\" in e37 \u0026\u0026 typeof e37.pcb_error_id == \"string\" \u0026\u0026 (e37.pcb_error_id.startsWith(\"same_net_vias_close_\") || e37.pcb_error_id.startsWith(\"different_net_vias_close_\"))) {\n const t4 = e37.pcb_error_id.replace(\"same_net_vias_close_\", \"\").replace(\"different_net_vias_close_\", \"\").split(\"_\").filter(Boolean);\n if (t4.length === 2) {\n const n4 = t4[0], o5 = t4[1];\n if (!n4 || !o5)\n return e37;\n const i5 = r4.get(n4), s4 = r4.get(o5);\n if (i5 \u0026\u0026 s4)\n return { ...e37, center: { x: (i5.x + s4.x) / 2, y: (i5.y + s4.y) / 2 } };\n }\n }\n return e37;\n }), a4 = s3.filter((e37) =\u003e Boolean(e37.center));\n return { errors: o4, errorsWithCenters: s3, locationAwareErrors: a4 };\n })(mP(a3, c3, a3.minTraceWidth, a3.minViaDiameter), { ...hP, traceClearance: a3.minTraceToPadEdgeClearance ?? hP.traceClearance, viaClearance: a3.minTraceToPadEdgeClearance ?? hP.viaClearance }), p3 = u2.errors, m2 = (u2.errorsWithCenters.length \u003e 0 ? u2.errorsWithCenters : u2.errors).map((e36) =\u003e r3.projectEngineError(e36));\n return { rawErrors: p3, errors: m2, count: p3.length, issueScore: YP(m2, r3.getErrorSeverity), legacyIssueScore: YP(m2.filter((e36) =\u003e !uw(e36)), r3.getErrorSeverity), traceRouteIndexById: l3, traceConnectionNameById: h2 };\n};\nvar HP = (e35, t2, n2, o3, i3) =\u003e XP(e35, t2, n2, o3, i3, jP);\nvar VP = (e35, t2, n2, o3, i3) =\u003e XP(e35, t2, n2, o3, i3, $P);\nvar WP = (e35, t2) =\u003e {\n const n2 = [];\n for (let o3 = 0;o3 \u003c e35.length; o3 += 1) {\n const i3 = e35[o3];\n if (!i3)\n continue;\n let r3;\n for (let e36 = 0;e36 \u003c i3.route.length - 1; e36 += 1) {\n const s2 = i3.route[e36], a3 = i3.route[e36 + 1];\n if (!s2 || !a3)\n continue;\n if (s2.z === a3.z || !kP(s2, a3))\n continue;\n const c3 = r3 ??= new Set, l3 = [e36, e36 + 1];\n for (let t3 = e36 - 1;t3 \u003e= 0; t3 -= 1) {\n const e37 = i3.route[t3];\n if (!e37 || !kP(e37, s2))\n break;\n l3.push(t3);\n }\n for (let t3 = e36 + 2;t3 \u003c i3.route.length; t3 += 1) {\n const e37 = i3.route[t3];\n if (!e37 || !kP(e37, s2))\n break;\n l3.push(t3);\n }\n const h2 = l3;\n if (h2.some((e37) =\u003e c3.has(e37)))\n continue;\n for (const e37 of h2)\n c3.add(e37);\n const d2 = h2.filter((e37) =\u003e e37 === 0 || e37 === i3.route.length - 1), u2 = d2.some((e37) =\u003e Boolean(i3.route[e37]?.pcb_port_id));\n let p3 = 0, m2 = t2.layerCount - 1;\n if (t2.allowBlindAndBuriedVias) {\n const e37 = h2.map((e38) =\u003e i3.route[e38].z);\n p3 = Math.min(...e37), m2 = Math.max(...e37);\n }\n n2.push({ routeIndex: o3, rootConnectionName: gP(i3), pointIndexes: h2, zLayers: Array.from({ length: m2 - p3 + 1 }, (e37, t3) =\u003e p3 + t3), x: s2.x, y: s2.y, radius: (i3.viaDiameter ?? t2.minViaDiameter ?? 0.3) / 2, movable: d2.length === 0, canCanonicalize: d2.length === 0 || !u2 });\n }\n }\n return n2;\n};\nvar GP = (e35, t2) =\u003e {\n const n2 = [];\n for (let o3 = 0;o3 \u003c e35.route.length - 1; o3 += 1) {\n const i3 = e35.route[o3], r3 = e35.route[o3 + 1];\n i3 \u0026\u0026 r3 \u0026\u0026 (i3.z !== r3.z || kP(i3, r3) || n2.push({ routeIndex: t2, rootConnectionName: gP(e35), startIndex: o3, endIndex: o3 + 1, start: i3, end: r3, z: i3.z, radius: (e35.traceThickness ?? 0.1) / 2 }));\n }\n return n2;\n};\nvar UP = (e35) =\u003e e35.flatMap((e36, t2) =\u003e GP(e36, t2));\nvar ZP = (e35) =\u003e ({ minX: e35.x, minY: e35.y, maxX: e35.x, maxY: e35.y });\nvar qP = (e35) =\u003e ({ minX: Math.min(e35.start.x, e35.end.x), minY: Math.min(e35.start.y, e35.end.y), maxX: Math.max(e35.start.x, e35.end.x), maxY: Math.max(e35.start.y, e35.end.y) });\nvar JP = (e35) =\u003e ({ minX: e35.center.x - e35.width / 2, minY: e35.center.y - e35.height / 2, maxX: e35.center.x + e35.width / 2, maxY: e35.center.y + e35.height / 2 });\nvar QP = (e35, t2) =\u003e {\n if (e35.zLayers \u0026\u0026 e35.zLayers.length \u003e 0)\n return e35.zLayers;\n const n2 = Array.from({ length: t2 }, (e36, t3) =\u003e t3).filter((n3) =\u003e e35.layers.includes(Qy(n3, t2)));\n return n2.length \u003e 0 ? n2 : Array.from({ length: t2 }, (e36, t3) =\u003e t3);\n};\nvar KP = (e35, t2, n2) =\u003e {\n const o3 = t2.reduce((e36, t3) =\u003e Math.max(e36, t3.radius), (e35.minViaDiameter ?? 0.3) / 2), i3 = n2.reduce((e36, t3) =\u003e Math.max(e36, t3.radius), e35.minTraceWidth / 2), r3 = (hP.traceClearance ?? 0.1) + Sb;\n return Math.max(2 * o3 + 0.2 + Sb, o3 + i3 + r3, 2 * i3 + r3, i3 + Cb(e35) + Sb, o3 + Pb(e35) + Sb);\n};\nvar eM = (e35, t2, n2) =\u003e {\n const o3 = n2.x - t2.x, i3 = n2.y - t2.y, r3 = o3 * o3 + i3 * i3;\n if (r3 \u003c= bb)\n return { x: t2.x, y: t2.y, t: 0 };\n const s2 = xP(((e35.x - t2.x) * o3 + (e35.y - t2.y) * i3) / r3, 0, 1);\n return { x: t2.x + o3 * s2, y: t2.y + i3 * s2, t: s2 };\n};\nvar tM = (e35, t2) =\u003e eM(e35, t2.start, t2.end);\nvar nM = (e35, t2) =\u003e {\n if (t2.shape === \"circle\") {\n const n3 = Math.hypot(e35.x - t2.center.x, e35.y - t2.center.y);\n return Math.max(0, n3 - t2.width / 2);\n }\n const n2 = t2.width / 2, o3 = t2.height / 2, i3 = Math.max(Math.abs(e35.x - t2.center.x) - n2, 0), r3 = Math.max(Math.abs(e35.y - t2.center.y) - o3, 0);\n return Math.hypot(i3, r3);\n};\nvar oM = (e35, t2) =\u003e e35.x \u003e= t2.center.x - t2.width / 2 - xb \u0026\u0026 e35.x \u003c= t2.center.x + t2.width / 2 + xb \u0026\u0026 e35.y \u003e= t2.center.y - t2.height / 2 - xb \u0026\u0026 e35.y \u003c= t2.center.y + t2.height / 2 + xb;\nvar iM = (e35, t2, n2, o3) =\u003e e35.obstacles.find((i3) =\u003e bP(gP(t2), i3, o3) \u0026\u0026 QP(i3, e35.layerCount).includes(n2.z) \u0026\u0026 oM(n2, i3));\nvar rM = (e35, t2, n2 = 0.6, o3) =\u003e {\n let i3;\n for (const r3 of e35.obstacles) {\n const e36 = nM(t2, r3);\n e36 \u003e n2 || (o3 \u0026\u0026 !o3(r3) || (!i3 || e36 \u003c i3.distance) \u0026\u0026 (i3 = { obstacle: r3, distance: e36 }));\n }\n return i3?.obstacle;\n};\nvar sM = (e35, t2, n2) =\u003e {\n if (t2.shape === \"circle\") {\n const o4 = e35.x - t2.center.x, i4 = e35.y - t2.center.y, r4 = Math.hypot(o4, i4), s3 = n2 + t2.width / 2 - r4;\n if (s3 \u003c= 0)\n return;\n let a4 = { x: 1, y: 0 };\n return r4 \u003e bb \u0026\u0026 (a4 = { x: o4 / r4, y: i4 / r4 }), { direction: a4, penetration: s3 };\n }\n const o3 = t2.width / 2, i3 = t2.height / 2, r3 = xP(e35.x, t2.center.x - o3, t2.center.x + o3), s2 = xP(e35.y, t2.center.y - i3, t2.center.y + i3);\n let a3 = e35.x - r3, c3 = e35.y - s2, l3 = Math.hypot(a3, c3);\n if (l3 \u003c= bb) {\n o3 - Math.abs(e35.x - t2.center.x) \u003c i3 - Math.abs(e35.y - t2.center.y) ? (a3 = e35.x \u003e= t2.center.x ? 1 : -1, c3 = 0, l3 = 0) : (a3 = 0, c3 = e35.y \u003e= t2.center.y ? 1 : -1, l3 = 0);\n }\n const h2 = n2 - l3;\n if (h2 \u003c= 0)\n return;\n const d2 = Math.hypot(a3, c3);\n return { direction: { x: d2 \u003e bb ? a3 / d2 : 1, y: d2 \u003e bb ? c3 / d2 : 0 }, penetration: h2 };\n};\nvar aM = (e35, t2, n2, o3) =\u003e {\n const i3 = t2.message;\n if (typeof i3 != \"string\" || !i3.includes(\"pcb_\"))\n return n2;\n const r3 = Array.isArray(t2.pcb_pad_ids) ? t2.pcb_pad_ids.filter((e36) =\u003e typeof e36 == \"string\") : [], s2 = e35.obstacles.find((e36) =\u003e r3.some((t3) =\u003e e36.connectedTo.includes(t3)) \u0026\u0026 (o3?.(e36) ?? true));\n return s2 ? s2.center : rM(e35, n2, 0.6, o3)?.center ?? n2;\n};\nvar cM = (e35, t2) =\u003e {\n const n2 = e35.route[t2];\n if (!n2)\n return [];\n const o3 = [t2];\n for (let i3 = t2 - 1;i3 \u003e= 0; i3 -= 1) {\n const t3 = e35.route[i3];\n if (!t3 || !kP(t3, n2))\n break;\n o3.push(i3);\n }\n for (let i3 = t2 + 1;i3 \u003c e35.route.length; i3 += 1) {\n const t3 = e35.route[i3];\n if (!t3 || !kP(t3, n2))\n break;\n o3.push(i3);\n }\n return [...new Set(o3)];\n};\nvar lM = (e35, t2) =\u003e {\n if (t2 \u003c= 0 || t2 \u003e= e35.route.length - 1)\n return;\n const n2 = cM(e35, t2);\n return n2.includes(0) || n2.includes(e35.route.length - 1) ? undefined : n2;\n};\nvar hM = (e35, t2) =\u003e e35.x \u003e= t2.minX - xb \u0026\u0026 e35.x \u003c= t2.maxX + xb \u0026\u0026 e35.y \u003e= t2.minY - xb \u0026\u0026 e35.y \u003c= t2.maxY + xb;\nvar dM = (e35, t2) =\u003e Math.min(e35.x - t2.minX, t2.maxX - e35.x, e35.y - t2.minY, t2.maxY - e35.y);\nvar uM = (e35, t2, n2) =\u003e {\n const o3 = n2.x - t2.x, i3 = n2.y - t2.y, r3 = e35.x - t2.x, s2 = o3 * (e35.y - t2.y) - i3 * r3;\n if (Math.abs(s2) \u003e xb)\n return false;\n const a3 = Math.min(t2.x, n2.x) - xb, c3 = Math.max(t2.x, n2.x) + xb, l3 = Math.min(t2.y, n2.y) - xb, h2 = Math.max(t2.y, n2.y) + xb;\n return e35.x \u003e= a3 \u0026\u0026 e35.x \u003c= c3 \u0026\u0026 e35.y \u003e= l3 \u0026\u0026 e35.y \u003c= h2;\n};\nvar pM = (e35, t2) =\u003e {\n if (t2.length \u003c 3)\n return true;\n for (let n3 = 0;n3 \u003c t2.length; n3 += 1) {\n const o3 = t2[n3], i3 = t2[(n3 + 1) % t2.length];\n if (o3 \u0026\u0026 i3 \u0026\u0026 uM(e35, o3, i3))\n return true;\n }\n let n2 = false;\n for (let o3 = 0, i3 = t2.length - 1;o3 \u003c t2.length; i3 = o3, o3 += 1) {\n const r3 = t2[o3], s2 = t2[i3];\n if (!r3 || !s2)\n continue;\n r3.y \u003e e35.y != s2.y \u003e e35.y \u0026\u0026 e35.x \u003c (s2.x - r3.x) * (e35.y - r3.y) / (s2.y - r3.y) + r3.x \u0026\u0026 (n2 = !n2);\n }\n return n2;\n};\nvar mM = (e35, t2) =\u003e {\n const n2 = Math.hypot(e35, t2);\n if (!(n2 \u003c= bb))\n return { x: e35 / n2, y: t2 / n2 };\n};\nvar gM = (e35, t2) =\u003e e35.outline \u0026\u0026 e35.outline.length \u003e= 3 ? ((e36, t3) =\u003e {\n const n2 = pM(e36, t3);\n let o3;\n for (let n3 = 0;n3 \u003c t3.length; n3 += 1) {\n const i4 = t3[n3], r4 = t3[(n3 + 1) % t3.length];\n if (!i4 || !r4)\n continue;\n const s3 = eM(e36, i4, r4), a4 = Math.hypot(e36.x - s3.x, e36.y - s3.y);\n (!o3 || a4 \u003c o3.distance) \u0026\u0026 (o3 = { projection: s3, start: i4, end: r4, distance: a4 });\n }\n if (!o3)\n return;\n const i3 = mM(n2 ? e36.x - o3.projection.x : o3.projection.x - e36.x, n2 ? e36.y - o3.projection.y : o3.projection.y - e36.y);\n if (i3)\n return i3;\n const r3 = o3.end.x - o3.start.x, s2 = o3.end.y - o3.start.y, a3 = Math.hypot(r3, s2);\n if (a3 \u003c= bb)\n return;\n const c3 = ((e37) =\u003e {\n let t4 = 0;\n for (let n3 = 0;n3 \u003c e37.length; n3 += 1) {\n const o4 = e37[n3], i4 = e37[(n3 + 1) % e37.length];\n o4 \u0026\u0026 i4 \u0026\u0026 (t4 += o4.x * i4.y - i4.x * o4.y);\n }\n return t4 / 2;\n })(t3) \u003e= 0;\n return { x: c3 ? -s2 / a3 : s2 / a3, y: c3 ? r3 / a3 : -r3 / a3 };\n})(t2, e35.outline) : ((e36, t3) =\u003e {\n const n2 = e36.x - t3.minX, o3 = t3.maxX - e36.x, i3 = e36.y - t3.minY, r3 = t3.maxY - e36.y, s2 = Math.min(n2, o3, i3, r3);\n let a3 = 0, c3 = 0;\n return n2 \u003c= s2 + xb \u0026\u0026 (a3 += 1), o3 \u003c= s2 + xb \u0026\u0026 (a3 -= 1), i3 \u003c= s2 + xb \u0026\u0026 (c3 += 1), r3 \u003c= s2 + xb \u0026\u0026 (c3 -= 1), mM(a3, c3);\n})(t2, e35.bounds);\nvar fM = (e35, t2) =\u003e e35.outline \u0026\u0026 e35.outline.length \u003e= 3 ? pM(t2, e35.outline) : hM(t2, e35.bounds);\nvar _M = (e35, t2) =\u003e {\n if (e35.outline \u0026\u0026 e35.outline.length \u003e= 3) {\n const n2 = ((e36, t3) =\u003e {\n let n3 = Number.POSITIVE_INFINITY;\n for (let o3 = 0;o3 \u003c t3.length; o3 += 1) {\n const i3 = t3[o3], r3 = t3[(o3 + 1) % t3.length];\n i3 \u0026\u0026 r3 \u0026\u0026 (n3 = Math.min(n3, pe(e36, i3, r3)));\n }\n return n3;\n })(t2, e35.outline);\n return pM(t2, e35.outline) ? n2 : -n2;\n }\n return dM(t2, e35.bounds);\n};\nvar yM = (e35, t2, n2) =\u003e {\n if (Math.abs(t2.x - n2.x) \u003c= xb \u0026\u0026 Math.abs(t2.y - n2.y) \u003c= xb)\n return Math.min(_M(e35, t2), _M(e35, n2));\n if (e35.outline \u0026\u0026 e35.outline.length \u003e= 3) {\n if (!pM(t2, e35.outline) || !pM(n2, e35.outline))\n return Math.min(_M(e35, t2), _M(e35, n2));\n let o3 = Number.POSITIVE_INFINITY;\n for (let i3 = 0;i3 \u003c e35.outline.length; i3 += 1) {\n const r3 = e35.outline[i3], s2 = e35.outline[(i3 + 1) % e35.outline.length];\n r3 \u0026\u0026 s2 \u0026\u0026 (o3 = Math.min(o3, we(t2, n2, r3, s2)));\n }\n return o3;\n }\n return hM(t2, e35.bounds) \u0026\u0026 hM(n2, e35.bounds) ? Math.min(dM(t2, e35.bounds), dM(n2, e35.bounds)) : Math.min(_M(e35, t2), _M(e35, n2));\n};\nvar bM = (e35, t2) =\u003e t2 + Math.max(0.16, e35.defaultObstacleMargin ?? 0, hP.traceClearance ?? 0.1);\nvar xM = (e35, t2, n2) =\u003e t2 \u003c e35 - xb \u0026\u0026 Math.min(e35, t2) \u003c= n2 + xb;\nvar vM = (e35, t2, n2, o3, i3) =\u003e {\n const r3 = e35 * n2.x + t2 * n2.y, s2 = -Math.max(0, o3 - i3);\n if (r3 \u003e= s2 - xb)\n return { x: e35, y: t2 };\n const a3 = s2 - r3;\n return { x: e35 + n2.x * a3, y: t2 + n2.y * a3 };\n};\nvar IM = (e35, t2, n2, o3, i3) =\u003e {\n const r3 = gM(e35, t2);\n return r3 ? vM(n2, o3, r3, _M(e35, t2), bM(e35, i3)) : { x: n2, y: o3 };\n};\nvar SM = (e35, t2, n2, o3) =\u003e {\n const i3 = [...new Set(n2)].sort((e36, t3) =\u003e e36 - t3);\n if (i3.length === 0)\n return Number.POSITIVE_INFINITY;\n const r3 = new Set(i3), s2 = (e36) =\u003e o3?.get(e36) ?? t2.route[e36];\n let a3 = Number.POSITIVE_INFINITY;\n for (const t3 of i3) {\n const n3 = s2(t3);\n n3 \u0026\u0026 (a3 = Math.min(a3, _M(e35, n3)));\n }\n for (let n3 = 0;n3 \u003c t2.route.length - 1; n3 += 1) {\n if (!r3.has(n3) \u0026\u0026 !r3.has(n3 + 1))\n continue;\n const t3 = s2(n3), o4 = s2(n3 + 1);\n t3 \u0026\u0026 o4 \u0026\u0026 (a3 = Math.min(a3, yM(e35, t3, o4)));\n }\n return a3;\n};\nvar CM = (e35, t2, n2, o3, i3, r3) =\u003e {\n const s2 = [...new Set(n2)].sort((e36, t3) =\u003e e36 - t3);\n if (s2.length === 0)\n return;\n const a3 = ((e36, t3, n3, o4, i4, r4) =\u003e {\n const s3 = [...new Set(n3)].sort((e37, t4) =\u003e e37 - t4);\n let a4 = { x: o4, y: i4 };\n const c4 = bM(e36, r4);\n for (let n4 = 0;n4 \u003c Math.max(1, s3.length); n4 += 1) {\n let n5 = false;\n for (const o5 of s3) {\n const i5 = t3.route[o5];\n if (!i5)\n continue;\n const r5 = gM(e36, i5);\n if (!r5)\n continue;\n const s4 = vM(a4.x, a4.y, r5, _M(e36, i5), c4);\n (Math.abs(s4.x - a4.x) \u003e bb || Math.abs(s4.y - a4.y) \u003e bb) \u0026\u0026 (a4 = s4, n5 = true);\n }\n if (!n5)\n break;\n }\n return a4;\n })(e35, t2, s2, o3, i3, r3);\n if (Math.abs(a3.x) \u003c= bb \u0026\u0026 Math.abs(a3.y) \u003c= bb)\n return;\n const c3 = new Map;\n for (const e36 of s2) {\n const n3 = t2.route[e36];\n if (!n3)\n continue;\n const o4 = { x: n3.x + a3.x, y: n3.y + a3.y };\n c3.set(e36, o4);\n }\n const l3 = SM(e35, t2, s2), h2 = SM(e35, t2, s2, c3);\n if (h2 \u003c r3 - xb)\n return;\n const d2 = bM(e35, r3);\n return xM(l3, h2, d2) ? undefined : a3;\n};\nvar PM = (e35, t2, n2, o3, i3, r3, s2) =\u003e {\n const a3 = e35[t2];\n if (!a3)\n return false;\n const c3 = lM(a3, n2);\n if (!c3)\n return false;\n const l3 = CM(r3, a3, c3, o3, i3, s2);\n if (!l3)\n return false;\n let h2 = false;\n for (const e36 of c3) {\n const t3 = a3.route[e36];\n t3 \u0026\u0026 (t3.x += l3.x, t3.y += l3.y, vP(t3, r3.bounds), h2 = true);\n }\n return h2;\n};\nvar MM = (e35, t2, n2, o3, i3, r3) =\u003e lM(t2, n2) ?? ((e36, t3, n3, o4, i4, r4) =\u003e {\n const s2 = t3.route[n3];\n if (!s2 || s2.pcb_port_id || n3 !== 0 \u0026\u0026 n3 !== t3.route.length - 1)\n return;\n const a3 = iM(e36, t3, s2, r4);\n if (!a3)\n return;\n const c3 = { ...s2, x: s2.x + o4, y: s2.y + i4 };\n return fM(e36, c3) \u0026\u0026 oM(c3, a3) ? cM(t3, n3) : undefined;\n})(e35, t2, n2, o3, i3, r3);\nvar wM = (e35, t2, n2, o3, i3, r3) =\u003e {\n const s2 = CM(i3, e35, t2, n2, o3, r3);\n if (!s2)\n return false;\n let a3 = false;\n for (const n3 of t2) {\n const t3 = e35.route[n3];\n t3 \u0026\u0026 (t3.x += s2.x, t3.y += s2.y, vP(t3, i3.bounds), a3 = true);\n }\n return a3;\n};\nvar NM = (e35, t2, n2, o3, i3, r3) =\u003e {\n const s2 = t2.route[n2];\n if (!s2)\n return false;\n if (s2.pcb_port_id)\n return false;\n const a3 = iM(e35, t2, s2, r3);\n return !!a3 \u0026\u0026 oM({ ...s2, x: s2.x + o3, y: s2.y + i3 }, a3);\n};\nvar RM = (e35, t2, n2, o3) =\u003e {\n const i3 = t2.route[n2];\n if (i3 \u0026\u0026 !i3.pcb_port_id)\n return iM(e35, t2, i3, o3);\n};\nvar TM = (e35, t2, n2, o3, i3, r3, s2) =\u003e {\n const a3 = e35[t2];\n if (!a3 || a3.route.length === 0)\n return false;\n const c3 = ((e36, t3, n3, o4, i4) =\u003e {\n let { NEGATIVE_INFINITY: r4, POSITIVE_INFINITY: s3, NEGATIVE_INFINITY: a4, POSITIVE_INFINITY: c4 } = Number;\n for (const n4 of [0, t3.route.length - 1]) {\n const o5 = t3.route[n4], l4 = RM(e36, t3, n4, i4);\n if (!o5 || !l4)\n return;\n r4 = Math.max(r4, l4.center.x - l4.width / 2 - o5.x), s3 = Math.min(s3, l4.center.x + l4.width / 2 - o5.x), a4 = Math.max(a4, l4.center.y - l4.height / 2 - o5.y), c4 = Math.min(c4, l4.center.y + l4.height / 2 - o5.y);\n }\n if (!(r4 \u003e s3 || a4 \u003e c4))\n return { x: xP(n3, r4, s3), y: xP(o4, a4, c4) };\n })(i3, a3, n2, o3, s2);\n if (!c3)\n return false;\n const l3 = a3.route.map((e36, t3) =\u003e t3), h2 = CM(i3, a3, l3, c3.x, c3.y, r3);\n if (!h2)\n return false;\n const d2 = a3.route.length - 1;\n if (!NM(i3, a3, 0, h2.x, h2.y, s2) || !NM(i3, a3, d2, h2.x, h2.y, s2))\n return false;\n let u2 = false;\n for (const e36 of a3.route)\n e36.x += h2.x, e36.y += h2.y, vP(e36, i3.bounds), u2 = true;\n return u2;\n};\nvar EM = (e35, t2, n2) =\u003e {\n const o3 = t2.x - e35.x, i3 = t2.y - e35.y, r3 = n2.x - t2.x, s2 = n2.y - t2.y;\n return Math.abs(o3 * s2 - i3 * r3) \u003c= xb;\n};\nvar AM = (e35, t2) =\u003e {\n if (e35.z !== t2.z)\n return false;\n const n2 = t2.end.x - t2.start.x, o3 = t2.end.y - t2.start.y, i3 = e35.x - t2.start.x, r3 = e35.y - t2.start.y;\n return Math.abs(n2 * r3 - o3 * i3) \u003c= xb;\n};\nvar OM = (e35, t2) =\u003e {\n const n2 = ((e36, t3) =\u003e {\n const n3 = t3.end.x - t3.start.x, o4 = t3.end.y - t3.start.y, i3 = Math.max(xb, 0.12 * (e36.traceThickness ?? 0.1)), r3 = Math.abs(o4) \u003c= i3, s2 = Math.abs(n3) \u003c= i3;\n let { startIndex: a3, endIndex: c3 } = t3;\n if (r3 || s2) {\n const n4 = r3 ? (t3.start.y + t3.end.y) / 2 : (t3.start.x + t3.end.x) / 2;\n for (;a3 \u003e 0; ) {\n const o5 = e36.route[a3 - 1];\n if (!o5 || o5.z !== t3.z || Math.abs((r3 ? o5.y : o5.x) - n4) \u003e i3)\n break;\n a3 -= 1;\n }\n for (;c3 \u003c e36.route.length - 1; ) {\n const o5 = e36.route[c3 + 1];\n if (!o5 || o5.z !== t3.z || Math.abs((r3 ? o5.y : o5.x) - n4) \u003e i3)\n break;\n c3 += 1;\n }\n return Array.from({ length: c3 - a3 + 1 }, (e37, t4) =\u003e a3 + t4);\n }\n for (;a3 \u003e 0; ) {\n const n4 = e36.route[a3 - 1], o5 = e36.route[a3], i4 = e36.route[a3 + 1];\n if (!(n4 \u0026\u0026 o5 \u0026\u0026 i4 \u0026\u0026 n4.z === t3.z \u0026\u0026 AM(n4, t3) \u0026\u0026 EM(n4, o5, i4)))\n break;\n a3 -= 1;\n }\n for (;c3 \u003c e36.route.length - 1; ) {\n const n4 = e36.route[c3 - 1], o5 = e36.route[c3], i4 = e36.route[c3 + 1];\n if (!(n4 \u0026\u0026 o5 \u0026\u0026 i4 \u0026\u0026 i4.z === t3.z \u0026\u0026 AM(i4, t3) \u0026\u0026 EM(n4, o5, i4)))\n break;\n c3 += 1;\n }\n return Array.from({ length: c3 - a3 + 1 }, (e37, t4) =\u003e a3 + t4);\n })(e35, t2);\n if (n2.length \u003c= 2)\n return;\n const o3 = [];\n for (const t3 of n2) {\n const n3 = lM(e35, t3);\n if (!n3)\n return;\n o3.push(...n3);\n }\n return [...new Set(o3)];\n};\nvar kM = (e35, t2) =\u003e t2 \u003e 0 \u0026\u0026 t2 \u003c e35.route.length - 1 \u0026\u0026 !((e36, t3) =\u003e {\n const n2 = e36.route[t3];\n if (!n2)\n return false;\n const o3 = e36.route[t3 - 1], i3 = e36.route[t3 + 1];\n return o3 \u0026\u0026 o3.z !== n2.z \u0026\u0026 kP(o3, n2) || i3 \u0026\u0026 i3.z !== n2.z \u0026\u0026 kP(i3, n2);\n})(e35, t2);\nvar DM = (e35, t2, n2) =\u003e {\n const o3 = e35.route[t2.startIndex], i3 = e35.route[t2.endIndex];\n return !(!o3 || !i3) \u0026\u0026 (o3.z === t2.z \u0026\u0026 i3.z === t2.z \u0026\u0026 (!!((e36, t3) =\u003e qP(e36).maxX \u003e= t3.minX - xb \u0026\u0026 qP(e36).minX \u003c= t3.maxX + xb \u0026\u0026 qP(e36).maxY \u003e= t3.minY - xb \u0026\u0026 qP(e36).minY \u003c= t3.maxY + xb)(t2, n2) \u0026\u0026 (kM(e35, t2.startIndex) || kM(e35, t2.endIndex))));\n};\nvar LM = (e35, t2, n2, o3, i3, r3, s2) =\u003e {\n const a3 = e35[t2.routeIndex];\n if (!a3)\n return false;\n const c3 = ((e36, t3, n3, o4) =\u003e {\n const i4 = IP(JP(n3), o4);\n let { startIndex: r4, startIndex: s3 } = t3;\n for (;r4 \u003e 0; ) {\n const n4 = { ...t3, startIndex: r4 - 1, endIndex: r4, start: e36.route[r4 - 1], end: e36.route[r4] };\n if (!e36.route[r4 - 1] || !DM(e36, n4, i4))\n break;\n r4 -= 1;\n }\n for (;s3 \u003c e36.route.length - 2; ) {\n const n4 = { ...t3, startIndex: s3 + 1, endIndex: s3 + 2, start: e36.route[s3 + 1], end: e36.route[s3 + 2] };\n if (!e36.route[s3 + 2] || !DM(e36, n4, i4))\n break;\n s3 += 1;\n }\n const a4 = [];\n for (let t4 = r4;t4 \u003c= s3 + 1; t4 += 1)\n kM(e36, t4) \u0026\u0026 a4.push(t4);\n return [...new Set(a4)];\n })(a3, t2, n2, o3);\n return !(c3.length \u003c= 2) \u0026\u0026 wM(a3, c3, i3, r3, s2, t2.radius);\n};\nvar zM = (e35, t2) =\u003e {\n const n2 = tM(t2, e35), o3 = n2.x - t2.x, i3 = n2.y - t2.y, r3 = Math.hypot(o3, i3), s2 = e35.end.x - e35.start.x, a3 = e35.end.y - e35.start.y, c3 = Math.hypot(s2, a3), l3 = e35.routeIndex % 2 == 0 ? 1 : -1;\n return { projection: n2, direction: r3 \u003e bb ? { x: o3 / r3, y: i3 / r3 } : c3 \u003e bb ? { x: -a3 / c3 * l3, y: s2 / c3 * l3 } : { x: 1, y: 0 } };\n};\nvar BM = (e35, t2, n2, o3, i3) =\u003e {\n const r3 = e35[t2.routeIndex];\n if (!r3)\n return false;\n const s2 = IM(i3, t2, n2, o3, t2.radius);\n if (Math.abs(s2.x) \u003c= bb \u0026\u0026 Math.abs(s2.y) \u003c= bb)\n return false;\n const a3 = { x: t2.x + s2.x, y: t2.y + s2.y }, c3 = _M(i3, t2), l3 = _M(i3, a3);\n if (l3 \u003c t2.radius - xb)\n return false;\n const h2 = bM(i3, t2.radius);\n if (xM(c3, l3, h2))\n return false;\n t2.x += s2.x, t2.y += s2.y, vP(t2, i3.bounds);\n for (const e36 of t2.pointIndexes) {\n const n3 = r3.route[e36];\n n3 \u0026\u0026 (n3.x = t2.x, n3.y = t2.y);\n }\n return true;\n};\nvar FM = ({ routes: e35, via: t2, srj: n2 }) =\u003e {\n if (!Number.isInteger(t2.routeIndex))\n return [];\n const o3 = e35[t2.routeIndex];\n if (!o3 || t2.routeIndex \u003c 0 || t2.routeIndex \u003e= e35.length)\n return [];\n const i3 = WP([o3], n2), r3 = i3.find((e36) =\u003e e36.pointIndexes.some((e37) =\u003e t2.pointIndexes.includes(e37)));\n if (!r3)\n return [];\n const s2 = [];\n for (let o4 = 0;o4 \u003c e35.length; o4 += 1) {\n const a3 = e35[o4];\n if (!a3 || gP(a3) !== r3.rootConnectionName)\n continue;\n const c3 = o4 === t2.routeIndex ? i3 : WP([a3], n2);\n for (const e36 of c3)\n e36.routeIndex = o4, e36.rootConnectionName === r3.rootConnectionName \u0026\u0026 Math.hypot(e36.x - r3.x, e36.y - r3.y) \u003c= xb \u0026\u0026 s2.push(e36);\n }\n return s2;\n};\nvar jM = (e35, t2, n2, o3, i3) =\u003e t2.movable \u0026\u0026 FM({ routes: e35, via: t2, srj: i3 }).length \u003c= 1 \u0026\u0026 BM(e35, t2, n2, o3, i3);\nvar $M = (e35, t2, n2, o3, i3 = 1) =\u003e {\n const { projection: r3, direction: s2 } = zM(t2, n2), a3 = vb * i3, c3 = 1 - r3.t, l3 = r3.t, h2 = PM(e35, t2.routeIndex, t2.startIndex, s2.x * a3 * c3, s2.y * a3 * c3, o3, t2.radius), d2 = PM(e35, t2.routeIndex, t2.endIndex, s2.x * a3 * l3, s2.y * a3 * l3, o3, t2.radius);\n return !(!h2 \u0026\u0026 !d2) || ((e36, t3, n3, o4, i4) =\u003e {\n const r4 = e36[t3.routeIndex];\n if (!r4)\n return false;\n const { projection: s3, direction: a4 } = zM(t3, n3), c4 = IM(o4, s3, a4.x * vb * i4, a4.y * vb * i4, t3.radius);\n if (Math.abs(c4.x) \u003c= bb \u0026\u0026 Math.abs(c4.y) \u003c= bb)\n return false;\n const l4 = { ...r4.route[t3.startIndex], x: s3.x + c4.x, y: s3.y + c4.y };\n if (vP(l4, o4.bounds), pe(l4, t3.start, t3.end) \u003c= xb)\n return false;\n const h3 = r4.route[t3.startIndex], d3 = r4.route[t3.endIndex];\n if (!h3 || !d3)\n return false;\n const u2 = yM(o4, h3, d3), p3 = Math.min(_M(o4, l4), yM(o4, h3, l4), yM(o4, l4, d3));\n if (p3 \u003c t3.radius - xb)\n return false;\n const m2 = bM(o4, t3.radius);\n return !xM(u2, p3, m2) \u0026\u0026 (r4.route.splice(t3.endIndex, 0, l4), true);\n })(e35, t2, n2, o3, i3);\n};\nvar YM = (e35, t2, n2, o3, i3, r3 = 1) =\u003e {\n const s2 = t2.radius + Cb(o3) + Sb, a3 = tw(t2, n2, s2);\n if (!a3)\n return false;\n const c3 = Math.min(0.3 * Math.abs(r3), a3.penetration + Sb), l3 = a3.direction.x * c3, h2 = a3.direction.y * c3, d2 = e35[t2.routeIndex];\n if (!d2)\n return false;\n const u2 = !((e36) =\u003e {\n for (let t3 = 0;t3 \u003c e36.route.length - 1; t3 += 1) {\n const n3 = e36.route[t3], o4 = e36.route[t3 + 1];\n if (n3 \u0026\u0026 o4 \u0026\u0026 n3.z !== o4.z \u0026\u0026 kP(n3, o4))\n return true;\n }\n return false;\n })(d2);\n if (u2 \u0026\u0026 TM(e35, t2.routeIndex, l3, h2, o3, t2.radius, i3))\n return true;\n const p3 = LM(e35, t2, n2, s2, l3, h2, o3) || ((e36, t3, n3, o4, i4) =\u003e {\n const r4 = e36[t3.routeIndex];\n if (!r4)\n return false;\n const s3 = OM(r4, t3);\n return !!s3 \u0026\u0026 wM(r4, s3, n3, o4, i4, t3.radius);\n })(e35, t2, l3, h2, o3) || ((e36, t3, n3, o4, i4, r4) =\u003e {\n const s3 = e36[t3.routeIndex];\n if (!s3)\n return false;\n const a4 = MM(i4, s3, t3.startIndex, n3, o4, r4), c4 = MM(i4, s3, t3.endIndex, n3, o4, r4);\n if (!a4 || !c4)\n return false;\n const l4 = [...new Set([...a4, ...c4])], h3 = CM(i4, s3, l4, n3, o4, t3.radius);\n if (!h3)\n return false;\n let d3 = false;\n for (const e37 of l4) {\n const t4 = s3.route[e37];\n t4 \u0026\u0026 (t4.x += h3.x, t4.y += h3.y, vP(t4, i4.bounds), d3 = true);\n }\n return d3;\n })(e35, t2, l3, h2, o3, i3);\n if (p3)\n return true;\n if (!u2 \u0026\u0026 TM(e35, t2.routeIndex, l3, h2, o3, t2.radius, i3))\n return true;\n const m2 = n2.width / 2, g2 = n2.height / 2, f2 = (Math.abs(a3.direction.y) \u003e= Math.abs(a3.direction.x) ? [{ ...d2.route[t2.startIndex], x: n2.center.x - m2 - s2, y: n2.center.y + a3.direction.y * (g2 + s2) }, { ...d2.route[t2.startIndex], x: n2.center.x + m2 + s2, y: n2.center.y + a3.direction.y * (g2 + s2) }] : [{ ...d2.route[t2.startIndex], x: n2.center.x + a3.direction.x * (m2 + s2), y: n2.center.y - g2 - s2 }, { ...d2.route[t2.startIndex], x: n2.center.x + a3.direction.x * (m2 + s2), y: n2.center.y + g2 + s2 }]).map((e36) =\u003e {\n const { t: n3 } = tM(e36, t2), i4 = { x: t2.start.x + (t2.end.x - t2.start.x) * n3, y: t2.start.y + (t2.end.y - t2.start.y) * n3 }, r4 = IM(o3, i4, e36.x - i4.x, e36.y - i4.y, t2.radius);\n return e36.x = i4.x + r4.x, e36.y = i4.y + r4.y, vP(e36, o3.bounds), { point: e36, t: n3, moved: Math.abs(r4.x) \u003e bb || Math.abs(r4.y) \u003e bb, awayFromObstacleMotion: r4.x * a3.direction.x + r4.y * a3.direction.y };\n }).sort((e36, t3) =\u003e e36.t - t3.t);\n if (!f2.some(({ moved: e36 }) =\u003e e36))\n return false;\n if (!f2.some(({ awayFromObstacleMotion: e36 }) =\u003e e36 \u003e xb))\n return false;\n const _2 = f2.map(({ point: e36 }) =\u003e e36);\n if (_2.every((e36) =\u003e pe(e36, t2.start, t2.end) \u003c= xb))\n return false;\n if (_2.some((e36) =\u003e !fM(o3, e36)))\n return false;\n const y2 = d2.route[t2.startIndex], b2 = d2.route[t2.endIndex], x2 = _2[0], v2 = _2[1];\n if (!(y2 \u0026\u0026 b2 \u0026\u0026 x2 \u0026\u0026 v2))\n return false;\n const I2 = yM(o3, y2, b2), S2 = Math.min(_M(o3, x2), _M(o3, v2), yM(o3, y2, x2), yM(o3, x2, v2), yM(o3, v2, b2));\n if (S2 \u003c t2.radius - xb)\n return false;\n const C = bM(o3, t2.radius);\n return !xM(I2, S2, C) \u0026\u0026 (d2.route.splice(t2.endIndex, 0, ..._2), true);\n};\nvar XM = (e35, t2, n2) =\u003e {\n let o3;\n for (const i3 of e35) {\n if (n2 !== undefined \u0026\u0026 i3.routeIndex !== n2)\n continue;\n const e36 = tM(t2, i3), r3 = Math.hypot(e36.x - t2.x, e36.y - t2.y);\n (!o3 || r3 \u003c o3.distance) \u0026\u0026 (o3 = { segment: i3, distance: r3 });\n }\n return o3?.segment;\n};\nvar HM = (e35, t2, n2) =\u003e {\n let o3;\n for (const i3 of e35) {\n if (n2 !== undefined \u0026\u0026 i3.routeIndex !== n2)\n continue;\n const e36 = Math.hypot(i3.x - t2.x, i3.y - t2.y);\n (!o3 || e36 \u003c o3.distance) \u0026\u0026 (o3 = { via: i3, distance: e36 });\n }\n return o3?.via;\n};\nvar VM = (e35, t2) =\u003e {\n const n2 = e35.map((e36) =\u003e ({ via: e36, distance: Math.hypot(e36.x - t2.x, e36.y - t2.y) })).sort((e36, t3) =\u003e e36.distance - t3.distance).slice(0, 2).map(({ via: e36 }) =\u003e e36);\n return n2.length === 2 ? n2 : undefined;\n};\nvar WM = (e35, t2, n2, o3) =\u003e {\n const i3 = t2.x - n2.x, r3 = t2.y - n2.y, s2 = Math.hypot(i3, r3);\n return jM(e35, t2, (s2 \u003e bb ? i3 / s2 : 1) * vb, (s2 \u003e bb ? r3 / s2 : 0) * vb, o3);\n};\nvar GM = (e35, t2) =\u003e {\n const n2 = tM(e35.start, t2), o3 = tM(e35.end, t2), i3 = tM(t2.start, e35), r3 = tM(t2.end, e35), s2 = [{ leftT: 0, rightT: n2.t, leftPoint: e35.start, rightPoint: n2 }, { leftT: 1, rightT: o3.t, leftPoint: e35.end, rightPoint: o3 }, { leftT: i3.t, rightT: 0, leftPoint: i3, rightPoint: t2.start }, { leftT: r3.t, rightT: 1, leftPoint: r3, rightPoint: t2.end }];\n let a3 = s2[0], c3 = Math.hypot(a3.leftPoint.x - a3.rightPoint.x, a3.leftPoint.y - a3.rightPoint.y);\n for (let e36 = 1;e36 \u003c s2.length; e36 += 1) {\n const t3 = s2[e36], n3 = Math.hypot(t3.leftPoint.x - t3.rightPoint.x, t3.leftPoint.y - t3.rightPoint.y);\n n3 \u003c c3 \u0026\u0026 (a3 = t3, c3 = n3);\n }\n return a3;\n};\nvar UM = (e35, t2, n2, o3, i3, r3) =\u003e {\n const s2 = xP(r3, 0, 1), a3 = 1 - s2, c3 = s2, l3 = PM(e35, t2.routeIndex, t2.startIndex, n2 * a3, o3 * a3, i3, t2.radius), h2 = PM(e35, t2.routeIndex, t2.endIndex, n2 * c3, o3 * c3, i3, t2.radius);\n return l3 || h2;\n};\nvar ZM = (e35, t2, n2, o3, i3, r3 = 0.035, s2 = false, a3) =\u003e {\n if (!s2 \u0026\u0026 (a3 ? a3.routesShareNet(t2, n2) : yP(t2.rootConnectionName, n2.rootConnectionName, i3)))\n return false;\n const c3 = t2.radius + n2.radius + 0.2 + Sb, l3 = t2.x - n2.x, h2 = t2.y - n2.y, d2 = Math.hypot(l3, h2), u2 = c3 - d2;\n if (u2 \u003c= 0)\n return false;\n const p3 = 1.618 * (97 * t2.routeIndex + 13 * n2.routeIndex), m2 = d2 \u003e bb ? l3 / d2 : Math.cos(p3), g2 = d2 \u003e bb ? h2 / d2 : Math.sin(p3), f2 = Number(t2.movable) + Number(n2.movable);\n if (f2 === 0)\n return false;\n const _2 = Math.min(r3, u2 / f2), y2 = jM(e35, t2, m2 * _2, g2 * _2, o3), b2 = jM(e35, n2, -m2 * _2, -g2 * _2, o3);\n return y2 || b2;\n};\nvar qM = (e35, t2, n2, o3, i3) =\u003e {\n if (!yP(t2.rootConnectionName, n2.rootConnectionName, i3))\n return false;\n const [r3, s2] = t2.canCanonicalize ? n2.canCanonicalize \u0026\u0026 t2.routeIndex \u003c= n2.routeIndex ? [t2, n2] : [n2, t2] : [t2, n2];\n return ((e36, t3, n3, o4) =\u003e {\n if (!n3.canCanonicalize)\n return false;\n const i4 = t3.x - n3.x, r4 = t3.y - n3.y;\n if (!n3.movable \u0026\u0026 Math.hypot(i4, r4) \u003e n3.radius + xb)\n return false;\n const s3 = e36[n3.routeIndex];\n if (!s3)\n return false;\n const a3 = { x: n3.x, y: n3.y }, c3 = n3.pointIndexes.map((e37) =\u003e {\n const t4 = s3.route[e37];\n return t4 ? { pointIndex: e37, x: t4.x, y: t4.y } : undefined;\n });\n if (BM(e36, n3, i4, r4, o4) \u0026\u0026 kP(n3, t3))\n return true;\n n3.x = a3.x, n3.y = a3.y;\n for (const e37 of c3) {\n if (!e37)\n continue;\n const t4 = s3.route[e37.pointIndex];\n t4 \u0026\u0026 (t4.x = e37.x, t4.y = e37.y);\n }\n return false;\n })(e35, r3, s2, o3);\n};\nvar JM = (e35, t2, n2, o3, i3, r3 = 0.035, s2 = 2, a3 = false, c3) =\u003e {\n if (c3 ? c3.routesShareNet(t2, n2) : yP(t2.rootConnectionName, n2.rootConnectionName, i3))\n return false;\n const l3 = tM(t2, n2), h2 = t2.x - l3.x, d2 = t2.y - l3.y, u2 = Math.hypot(h2, d2), p3 = t2.radius + n2.radius + (hP.traceClearance ?? 0.1) + Sb - u2;\n if (p3 \u003c= 0)\n return false;\n const m2 = n2.end.x - n2.start.x, g2 = n2.end.y - n2.start.y, f2 = Math.hypot(m2, g2), _2 = t2.routeIndex % 2 == 0 ? 1 : -1, y2 = u2 \u003e bb ? h2 / u2 : f2 \u003e bb ? -g2 / f2 * _2 : 1, b2 = u2 \u003e bb ? d2 / u2 : f2 \u003e bb ? m2 / f2 * _2 : 0, x2 = Math.min(r3, p3 / s2), v2 = a3 ? ((e36, t3, n3, o4, i4) =\u003e {\n const r4 = FM({ routes: e36, via: t3, srj: i4 });\n if (r4.length === 0 || r4.some((t4) =\u003e !t4.movable || e36[t4.routeIndex] === undefined))\n return false;\n const s3 = r4.reduce((e37, t4) =\u003e t4.radius \u003e e37.radius ? t4 : e37);\n if (!BM(e36, s3, n3, o4, i4))\n return false;\n for (const t4 of r4) {\n if (t4 === s3)\n continue;\n t4.x = s3.x, t4.y = s3.y;\n const n4 = e36[t4.routeIndex];\n for (const e37 of t4.pointIndexes) {\n const t5 = n4.route[e37];\n t5 \u0026\u0026 (t5.x = s3.x, t5.y = s3.y);\n }\n }\n return true;\n })(e35, t2, y2 * x2, b2 * x2, o3) : jM(e35, t2, y2 * x2, b2 * x2, o3), I2 = UM(e35, n2, -y2 * x2, -b2 * x2, o3, l3.t);\n return v2 || I2;\n};\nvar QM = (e35, t2, n2, o3, i3, r3) =\u003e {\n if (t2.z !== n2.z || (r3 ? r3.routesShareNet(t2, n2) : yP(t2.rootConnectionName, n2.rootConnectionName, i3)))\n return false;\n const s2 = GM(t2, n2), a3 = s2.leftPoint.x - s2.rightPoint.x, c3 = s2.leftPoint.y - s2.rightPoint.y, l3 = Math.hypot(a3, c3), h2 = t2.radius + n2.radius + (hP.traceClearance ?? 0.1) + Sb - l3;\n if (h2 \u003c= 0)\n return false;\n const d2 = t2.end.x - t2.start.x, u2 = t2.end.y - t2.start.y, p3 = Math.hypot(d2, u2), m2 = (t2.routeIndex + n2.routeIndex) % 2 == 0 ? 1 : -1, g2 = l3 \u003e bb ? a3 / l3 : p3 \u003e bb ? -u2 / p3 * m2 : 1, f2 = l3 \u003e bb ? c3 / l3 : p3 \u003e bb ? d2 / p3 * m2 : 0, _2 = Math.min(Ib, h2 / 2), y2 = UM(e35, t2, g2 * _2, f2 * _2, o3, s2.leftT), b2 = UM(e35, n2, -g2 * _2, -f2 * _2, o3, s2.rightT);\n return y2 || b2;\n};\nvar KM = (e35, t2, n2) =\u003e QP(e35, n2).includes(t2.z);\nvar ew = (e35, t2, n2, o3, i3) =\u003e {\n const r3 = t2[n2];\n if (!r3)\n return;\n const s2 = GP(r3, n2);\n if (s2.length === 0)\n return;\n const a3 = gP(r3), c3 = XM(s2, o3);\n if (!c3)\n return;\n const l3 = rM(e35, o3, 0.6, (t3) =\u003e !bP(a3, t3, i3) \u0026\u0026 KM(t3, c3, e35.layerCount));\n if (l3)\n return { obstacle: l3, segment: c3 };\n const h2 = rM(e35, o3, 0.6, (t3) =\u003e !bP(a3, t3, i3) \u0026\u0026 s2.some((n3) =\u003e KM(t3, n3, e35.layerCount)));\n if (!h2)\n return;\n const d2 = XM(s2.filter((t3) =\u003e KM(h2, t3, e35.layerCount)), o3);\n return d2 ? { obstacle: h2, segment: d2 } : undefined;\n};\nvar tw = (e35, t2, n2) =\u003e {\n const o3 = t2.width / 2, i3 = t2.height / 2, r3 = [{ x: t2.center.x - o3, y: t2.center.y - i3 }, { x: t2.center.x + o3, y: t2.center.y - i3 }, { x: t2.center.x + o3, y: t2.center.y + i3 }, { x: t2.center.x - o3, y: t2.center.y + i3 }], s2 = [t2.center, ...r3].map((t3) =\u003e tM(t3, e35)), a3 = [{ point: e35.start, t: 0 }, { point: e35.end, t: 1 }, { point: { x: (e35.start.x + e35.end.x) / 2, y: (e35.start.y + e35.end.y) / 2 }, t: 0.5 }, ...s2.map((e36) =\u003e ({ point: { x: e36.x, y: e36.y }, t: e36.t }))];\n let c3;\n const l3 = Math.hypot(e35.end.x - e35.start.x, e35.end.y - e35.start.y);\n for (const o4 of a3) {\n const i4 = sM(o4.point, t2, n2);\n if (!i4)\n continue;\n const r4 = l3 \u003e bb ? Math.abs(((e35.end.x - e35.start.x) * i4.direction.y - (e35.end.y - e35.start.y) * i4.direction.x) / l3) : 0;\n (!c3 || i4.penetration \u003e c3.penetration + bb || Math.abs(i4.penetration - c3.penetration) \u003c= bb \u0026\u0026 r4 \u003e c3.normality) \u0026\u0026 (c3 = { ...i4, normality: r4, t: o4.t });\n }\n return c3;\n};\nvar nw = (e35, t2, n2, o3 = false, i3) =\u003e {\n let r3 = false;\n const s2 = WP(t2, e35), a3 = UP(t2), c3 = KP(e35, s2, a3), l3 = Math.max(1, 2 * c3), h2 = MP(s2, ZP, l3), d2 = MP(a3, qP, l3);\n for (let a4 = 0;a4 \u003c s2.length; a4 += 1) {\n const d3 = s2[a4];\n if (!d3)\n continue;\n const u2 = wP(h2, IP(ZP(d3), c3), l3);\n for (const c4 of u2) {\n if (c4 \u003c= a4)\n continue;\n const l4 = s2[c4];\n l4 \u0026\u0026 (r3 = ZM(t2, d3, l4, e35, n2, Ib, o3, i3) || r3);\n }\n }\n for (let o4 = 0;o4 \u003c s2.length; o4 += 1) {\n const h3 = s2[o4];\n if (!h3)\n continue;\n const u2 = wP(d2, IP(ZP(h3), c3), l3);\n for (const o5 of u2) {\n const s3 = a3[o5];\n s3 \u0026\u0026 (r3 = JM(t2, h3, s3, e35, n2, Ib, 2, false, i3) || r3);\n }\n }\n for (let o4 = 0;o4 \u003c a3.length; o4 += 1) {\n const s3 = a3[o4];\n if (!s3)\n continue;\n const h3 = wP(d2, IP(qP(s3), c3), l3);\n for (const c4 of h3) {\n if (c4 \u003c= o4)\n continue;\n const l4 = a3[c4];\n l4 \u0026\u0026 (r3 = QM(t2, s3, l4, e35, n2, i3) || r3);\n }\n }\n return ((e36, t3, n3, o4, i4, r4, s3, a4, c4) =\u003e {\n let l4 = false;\n const h3 = Cb(e36), d3 = o4.reduce((e37, t4) =\u003e Math.max(e37, t4.radius), 0) + h3 + Sb, u2 = Pb(e36), p3 = n3.reduce((e37, t4) =\u003e Math.max(e37, t4.radius), 0) + u2 + Sb;\n for (const m2 of e36.obstacles) {\n if (m2.isCopperPour)\n continue;\n const g2 = JP(m2), f2 = c4?.forObstacle(m2), _2 = wP(i4, IP(g2, p3), s3);\n for (const o5 of _2) {\n const i5 = n3[o5];\n if (!i5)\n continue;\n if (f2 ? f2(i5) : bP(i5.rootConnectionName, m2, a4))\n continue;\n const r5 = sM(i5, m2, i5.radius + u2 + Sb);\n if (!r5)\n continue;\n const s4 = Math.min(Ib, r5.penetration);\n l4 = jM(t3, i5, r5.direction.x * s4, r5.direction.y * s4, e36) || l4;\n }\n const y2 = wP(r4, IP(g2, d3), s3);\n for (const n4 of y2) {\n const i5 = o4[n4];\n if (!i5)\n continue;\n if ((f2 ? f2(i5) : bP(i5.rootConnectionName, m2, a4)) || !KM(m2, i5, e36.layerCount))\n continue;\n const r5 = tw(i5, m2, i5.radius + h3 + Sb);\n if (!r5)\n continue;\n const s4 = Math.min(Ib, r5.penetration);\n l4 = UM(t3, i5, r5.direction.x * s4, r5.direction.y * s4, e36, r5.t) || l4;\n }\n }\n return l4;\n })(e35, t2, s2, a3, h2, d2, l3, n2, i3) || r3;\n};\nvar ow = (e35, t2, n2, o3 = 1, i3, r3 = false, s2 = true) =\u003e {\n const a3 = AP(t2), c3 = ((e36, t3, n3) =\u003e {\n const o4 = e36 * e36 \u003c= TP ? new Uint8Array(e36 * e36) : undefined, i4 = e36 * t3 \u003c= TP, r4 = new WeakMap;\n return { routesShareNet: (t4, i5) =\u003e {\n const r5 = t4.routeIndex * e36 + i5.routeIndex, s3 = o4?.[r5];\n if (s3)\n return s3 === 2;\n const a4 = yP(t4.rootConnectionName, i5.rootConnectionName, n3);\n return o4 \u0026\u0026 (o4[r5] = a4 ? 2 : 1), a4;\n }, forObstacle: (t4) =\u003e {\n let o5 = r4.get(t4);\n if (o5)\n return o5;\n const s3 = i4 ? new Uint8Array(e36) : undefined;\n return o5 = (e37) =\u003e {\n const o6 = s3?.[e37.routeIndex];\n if (o6)\n return o6 === 2;\n const i5 = bP(e37.rootConnectionName, t4, n3);\n return s3 \u0026\u0026 (s3[e37.routeIndex] = i5 ? 2 : 1), i5;\n }, r4.set(t4, o5), o5;\n } };\n })(a3.length, e35.obstacles.length, i3), l3 = Math.max(2, Math.round(12 * Math.max(1, n2) * o3));\n let h2 = false;\n for (let t3 = 0;t3 \u003c l3; t3 += 1) {\n if (!nw(e35, a3, i3, r3, c3))\n break;\n h2 = true;\n }\n return h2 \u0026\u0026 s2 \u0026\u0026 ((e36, t3, n3, o4) =\u003e {\n let i4 = false;\n const r4 = WP(t3, e36), s3 = UP(t3), a4 = KP(e36, r4, s3), c4 = Math.max(1, 2 * a4), l4 = MP(s3, qP, c4);\n for (const h3 of r4) {\n const r5 = wP(l4, IP(ZP(h3), a4), c4);\n for (const a5 of r5) {\n const r6 = s3[a5];\n r6 \u0026\u0026 (i4 = JM(t3, h3, r6, e36, n3, Ib, 1.75, false, o4) || i4);\n }\n }\n })(e35, a3, i3, c3), h2 ? sw(a3) : t2;\n};\nvar iw = (e35) =\u003e {\n const t2 = [];\n for (let n2 = 0;n2 \u003c e35.route.length - 1; n2 += 1) {\n const o3 = e35.route[n2], i3 = e35.route[n2 + 1];\n if (!o3 || !i3)\n continue;\n if (o3.toNextSegmentType === \"through_obstacle\")\n continue;\n if (o3.z === i3.z || !kP(o3, i3))\n continue;\n const r3 = { x: o3.x, y: o3.y }, s2 = t2.at(-1);\n s2 \u0026\u0026 kP(s2, r3) || t2.push(r3);\n }\n return t2;\n};\nvar rw = (e35) =\u003e ({ ...e35, vias: iw(e35) });\nvar sw = (e35) =\u003e e35.map(rw);\nvar aw = (e35, t2) =\u003e {\n const n2 = new Set(t2);\n return e35.map((e36, t3) =\u003e n2.has(t3) ? rw(e36) : e36);\n};\nvar cw = (e35) =\u003e {\n const t2 = e35.pcb_trace_id;\n if (typeof t2 != \"string\")\n return;\n const n2 = t2.match(/^trace_(\\d+)/);\n return n2 ? Number.parseInt(n2[1], 10) : undefined;\n};\nvar lw = (e35) =\u003e {\n const t2 = e35.center ?? e35.pcb_center;\n if (!t2 || typeof t2 != \"object\")\n return;\n const n2 = t2;\n return typeof n2.x == \"number\" \u0026\u0026 typeof n2.y == \"number\" ? { x: n2.x, y: n2.y } : undefined;\n};\nvar hw = (e35, t2 = true) =\u003e e35.errors.filter((e36) =\u003e ((e37) =\u003e LP(e37) === \"pcb_via_clearance_error\" || Array.isArray(e37.pcb_via_ids))(e36) \u0026\u0026 (t2 || !uw(e36))).length;\nvar dw = (e35) =\u003e LP(e35) === \"pcb_placement_error\" \u0026\u0026 Array.isArray(e35.pcb_via_ids) \u0026\u0026 e35.pcb_via_ids.length === 1 \u0026\u0026 Array.isArray(e35.pcb_pad_ids);\nvar uw = (e35) =\u003e LP(e35) === \"pcb_pad_pad_clearance_error\" \u0026\u0026 Array.isArray(e35.pcb_via_ids) \u0026\u0026 e35.pcb_via_ids.length === 1;\nvar pw = (e35) =\u003e {\n const t2 = Object.entries(e35).filter(([e36, t3]) =\u003e e36 !== \"source_trace_id\" \u0026\u0026 (e36.endsWith(\"_id\") || e36.endsWith(\"_ids\")) \u0026\u0026 t3 !== undefined \u0026\u0026 t3 !== \"\").sort(([e36], [t3]) =\u003e e36.localeCompare(t3)), n2 = typeof e35.message == \"string\" ? e35.message.replace(/-?\\d+\\.\\d+/g, \"#\") : \"\";\n return JSON.stringify([LP(e35), t2, n2]);\n};\nvar mw = (e35) =\u003e Math.max(e35.errors.filter((e36) =\u003e !uw(e36)).length, e35.count - e35.errors.filter(uw).length);\nvar gw = (e35) =\u003e {\n const t2 = mw(e35);\n return t2 \u003e 0 ? t2 : e35.count;\n};\nvar fw = (e35) =\u003e {\n if (mw(e35) === 0)\n return e35.issueScore;\n const t2 = e35.errors.filter((e36) =\u003e !uw(e36));\n return e35.errors.some(uw) ? YP(t2) : e35.legacyIssueScore ?? YP(t2);\n};\nvar _w = (e35, t2) =\u003e {\n const n2 = e35.pcb_trace_id;\n if (typeof n2 != \"string\" || n2.length === 0)\n return;\n const o3 = [e35.pcb_pad_id, e35.pcb_smtpad_id, e35.pcb_plated_hole_id, e35.pcb_hole_id, e35.pcb_keepout_id, e35.pcb_obstacle_id].find((e36) =\u003e typeof e36 == \"string\" \u0026\u0026 e36.length \u003e 0), i3 = e35.worst_contact_message ?? e35.message, r3 = typeof i3 == \"string\" ? i3.match(/\\b(?:pcb_smtpad|pcb_plated_hole|pcb_hole|pcb_keepout)\\s+\"([^\"]+)\"/)?.[1] : undefined, s2 = o3 ?? r3?.match(/\\[#([^\\]]+)\\]/)?.[1] ?? r3;\n if (!s2)\n return;\n const a3 = t2.traceConnectionNameById?.get(n2);\n return JSON.stringify([a3 === undefined ? \"trace\" : \"connection\", a3 ?? n2, s2]);\n};\nvar yw = (e35) =\u003e {\n const t2 = [], n2 = e35.rawErrors ? e35.rawErrors.concat(e35.errors) : e35.errors;\n for (const o3 of n2) {\n if (!_w(o3, e35) \u0026\u0026 !zP(o3))\n continue;\n const n3 = o3.worst_actual_clearance ?? o3.actual_clearance, i3 = o3.worst_contact_message ?? o3.message;\n (typeof n3 == \"number\" \u0026\u0026 Number.isFinite(n3) ? n3 \u003c -0.001 : typeof i3 == \"string\" \u0026\u0026 i3.includes(\"(accidental contact)\")) \u0026\u0026 t2.push(o3);\n }\n return t2;\n};\nvar bw = (e35) =\u003e new Set(yw(e35).map((t2) =\u003e _w(t2, e35) ?? Symbol(\"unidentified trace-obstacle contact\")));\nvar xw = (e35, t2) =\u003e {\n const n2 = bw(e35);\n if (n2.size === 0)\n return false;\n const o3 = bw(t2);\n return [...n2].some((e36) =\u003e !o3.has(e36));\n};\nvar vw = (e35, t2) =\u003e {\n if (e35.errors.filter(dw).length \u003e t2.errors.filter(dw).length)\n return false;\n const n2 = mw(e35), o3 = mw(t2);\n return n2 !== o3 ? n2 \u003c o3 : !(n2 \u003e 0) \u0026\u0026 e35.count \u003c t2.count;\n};\nvar Iw = (e35) =\u003e {\n const t2 = e35.filter(dw);\n if (t2.length \u003e 0)\n return t2;\n const n2 = e35.filter((e36) =\u003e !uw(e36));\n return n2.length \u003e 0 ? n2 : e35;\n};\nvar Sw = (e35, t2) =\u003e {\n const n2 = e35.pcb_trace_id;\n return typeof n2 == \"string\" ? t2.get(n2) ?? cw(e35) : cw(e35);\n};\nvar Cw = (e35, t2, n2, o3, i3) =\u003e {\n const r3 = n2.pcb_port_id;\n if (!r3)\n return false;\n const s2 = (i3 ?? t2.viaDiameter) / 2;\n return e35.obstacles.some((i4) =\u003e {\n const a3 = QP(i4, e35.layerCount);\n return !(a3.length !== 1 || a3[0] !== n2.z || !i4.connectedTo.includes(r3) || n2.x - s2 \u003c i4.center.x - i4.width / 2 - bb || n2.x + s2 \u003e i4.center.x + i4.width / 2 + bb || n2.y - s2 \u003c i4.center.y - i4.height / 2 - bb || n2.y + s2 \u003e i4.center.y + i4.height / 2 + bb) \u0026\u0026 (bP(gP(t2), i4, o3) || bP(t2.connectionName, i4, o3));\n });\n};\nvar Pw = [0, 1, -1, 2, -2, 3, -3, 4];\nvar Mw = Pw.flatMap((e35) =\u003e Pw.map((t2) =\u003e [e35, t2])).sort(([e35, t2], [n2, o3]) =\u003e Math.abs(e35) + Math.abs(t2) - Math.abs(n2) - Math.abs(o3));\nvar ww = Mw.length;\nvar Nw = (e35, t2) =\u003e {\n const n2 = t2 * Math.PI / 4, o3 = Math.cos(n2), i3 = Math.sin(n2);\n return { x: e35.x * o3 - e35.y * i3, y: e35.x * i3 + e35.y * o3 };\n};\nvar Rw = (e35, t2, n2) =\u003e e35.x - t2 \u003e= n2.minX - bb \u0026\u0026 e35.x + t2 \u003c= n2.maxX + bb \u0026\u0026 e35.y - t2 \u003e= n2.minY - bb \u0026\u0026 e35.y + t2 \u003c= n2.maxY + bb;\nvar Tw = (e35, t2) =\u003e {\n const n2 = e35.at(-1);\n n2 \u0026\u0026 n2.x === t2.x \u0026\u0026 n2.y === t2.y \u0026\u0026 n2.z === t2.z \u0026\u0026 n2.pcb_port_id === t2.pcb_port_id || e35.push(t2);\n};\nvar Ew = (e35, t2, n2, o3, i3, r3, s2, a3 = 0) =\u003e {\n const c3 = LP(n2);\n if (c3 !== \"pcb_pad_trace_clearance_error\" \u0026\u0026 c3 !== \"pcb_trace_error\")\n return false;\n if (i3 \u003c 0 || i3 \u003e= e35.layerCount)\n return false;\n const l3 = t2[o3];\n if (!l3 || l3.route.length \u003c 2)\n return false;\n const h2 = l3.route.map((e36) =\u003e ({ ...e36 })), d2 = h2[0], u2 = h2.at(-1);\n if (!d2 || !u2)\n return false;\n const p3 = lw(n2);\n if (!p3)\n return false;\n const m2 = zP(n2), g2 = m2 ? ew(e35, t2, o3, p3, s2) : undefined, f2 = m2 ? g2?.segment : XM(GP(l3, o3), p3);\n if (!f2 || f2.z === i3)\n return false;\n let { startIndex: _2, endIndex: y2 } = f2;\n const b2 = r3 === \"full\" ? h2.length : r3;\n for (let e36 = 0;e36 \u003c b2; e36 += 1) {\n let e37 = false;\n const t3 = h2[_2 - 1];\n t3?.z === f2.z \u0026\u0026 (_2 -= 1, e37 = true);\n const n3 = h2[y2 + 1];\n if (n3?.z === f2.z \u0026\u0026 (y2 += 1, e37 = true), !e37)\n break;\n }\n const x2 = _2 === 0 \u0026\u0026 d2.pcb_port_id, v2 = y2 === h2.length - 1 \u0026\u0026 u2.pcb_port_id, I2 = l3.viaDiameter / 2, S2 = Mw[a3 % ww], C = (t3) =\u003e {\n const n3 = t3 === \"start\" ? d2 : u2, o4 = ((e36, t4, n4, o5) =\u003e {\n const i5 = n4.pcb_port_id;\n if (i5)\n return e36.obstacles.find((r5) =\u003e {\n const s3 = QP(r5, e36.layerCount);\n return !(s3.length !== 1 || s3[0] !== n4.z || !r5.connectedTo.includes(i5) || !oM(n4, r5)) \u0026\u0026 (bP(gP(t4), r5, o5) || bP(t4.connectionName, r5, o5));\n });\n })(e35, l3, n3, s2), i4 = ((e36, t4) =\u003e {\n const n4 = t4 === \"start\" ? e36[0] : e36.at(-1);\n if (!n4)\n return;\n const o5 = t4 === \"start\" ? Array.from({ length: e36.length - 1 }, (e37, t5) =\u003e t5 + 1) : Array.from({ length: e36.length - 1 }, (t5, n5) =\u003e e36.length - n5 - 2);\n for (const t5 of o5) {\n const o6 = e36[t5];\n if (!o6)\n continue;\n const i5 = o6.x - n4.x, r5 = o6.y - n4.y, s3 = Math.hypot(i5, r5);\n if (!(s3 \u003c= bb))\n return { x: i5 / s3, y: r5 / s3 };\n }\n })(h2, t3);\n if (!o4 || !i4)\n return;\n const r4 = t3 === \"start\" ? S2[0] : S2[1], a4 = I2 + Pb(e35) + bb, c4 = (({ endpoint: e36, pad: t4, direction: n4, requiredDistance: o5 }) =\u003e {\n let i5 = 0, r5 = Math.hypot(t4.width, t4.height) + 2 * o5;\n const s3 = (t5) =\u003e ({ x: e36.x + n4.x * t5, y: e36.y + n4.y * t5 });\n if (!(nM(s3(r5), t4) \u003c o5)) {\n for (;r5 - i5 \u003e bb; ) {\n const e37 = (i5 + r5) / 2;\n nM(s3(e37), t4) \u003e= o5 ? r5 = e37 : i5 = e37;\n }\n return s3(r5);\n }\n })({ endpoint: n3, pad: o4, direction: Nw(i4, r4), requiredDistance: a4 });\n return !c4 || !Rw(c4, I2, e35.bounds) || nM(c4, o4) + bb \u003c a4 ? undefined : c4;\n }, P = x2 ? C(\"start\") : undefined, M = v2 ? C(\"end\") : undefined;\n if (x2 \u0026\u0026 !P || v2 \u0026\u0026 !M)\n return false;\n const w = [];\n for (let e36 = 0;e36 \u003c _2; e36 += 1)\n Tw(w, h2[e36]);\n const N = h2[_2], R2 = h2[_2 - 1], T2 = R2?.x === N.x \u0026\u0026 R2.y === N.y, E3 = h2[y2], A2 = h2[y2 + 1], O2 = A2?.x === E3.x \u0026\u0026 A2.y === E3.y;\n x2 ? (Tw(w, d2), Tw(w, { ...d2, ...P, pcb_port_id: undefined }), Tw(w, { ...d2, ...P, z: i3, pcb_port_id: undefined })) : (T2 || Tw(w, { ...N, pcb_port_id: undefined }), Tw(w, { ...N, z: i3, pcb_port_id: undefined }));\n const k2 = v2 ? y2 - 1 : y2;\n for (let e36 = _2 + 1;e36 \u003c= k2; e36 += 1)\n Tw(w, { ...h2[e36], z: i3, pcb_port_id: undefined });\n v2 ? (Tw(w, { ...u2, ...M, z: i3, pcb_port_id: undefined }), Tw(w, { ...u2, ...M, pcb_port_id: undefined }), Tw(w, u2)) : O2 || Tw(w, { ...E3, pcb_port_id: undefined });\n for (let e36 = y2 + 1;e36 \u003c h2.length; e36 += 1)\n Tw(w, h2[e36]);\n for (let e36 = 1;e36 \u003c w.length - 1; e36 += 1)\n w[e36].pcb_port_id = undefined;\n return l3.route = w, true;\n};\nvar Aw = (e35, t2, n2, o3, i3, r3, s2) =\u003e {\n const a3 = LP(n2);\n if (a3 !== \"pcb_pad_trace_clearance_error\" \u0026\u0026 a3 !== \"pcb_trace_error\")\n return false;\n if (i3 \u003c 0 || i3 \u003e= e35.layerCount)\n return false;\n const c3 = Sw(n2, o3);\n if (c3 === undefined)\n return false;\n const l3 = t2[c3];\n if (!l3 || l3.route.length \u003c 2)\n return false;\n const h2 = l3.route[0], d2 = l3.route.at(-1);\n if (!h2 || !d2 || h2.z !== d2.z || i3 === h2.z)\n return false;\n if (l3.route.some((e36) =\u003e e36.z !== h2.z))\n return false;\n if (!h2.pcb_port_id || !d2.pcb_port_id)\n return false;\n if (!Cw(e35, l3, h2, r3, s2) || !Cw(e35, l3, d2, r3, s2))\n return false;\n const u2 = l3.route.map((e36) =\u003e ({ ...e36 }));\n return l3.route = [u2[0], { ...u2[0], z: i3, pcb_port_id: undefined }, ...u2.slice(1, -1).map((e36) =\u003e ({ ...e36, z: i3 })), { ...u2.at(-1), z: i3, pcb_port_id: undefined }, u2.at(-1)], true;\n};\nvar Ow = (e35, t2, n2, o3, i3, r3, s2) =\u003e {\n if (LP(n2) !== \"pcb_pad_trace_clearance_error\")\n return false;\n const a3 = Sw(n2, o3);\n if (a3 === undefined)\n return false;\n const c3 = t2[a3];\n if (!c3 || c3.route.length \u003c 4)\n return false;\n const l3 = c3.route.map((e36) =\u003e ({ ...e36 }));\n if (i3 === \"start\") {\n const t3 = l3[0];\n if (!Cw(e35, c3, t3, r3, s2))\n return false;\n let n3 = -1;\n for (let e36 = 1;e36 \u003c l3.length; e36 += 1)\n if (l3[e36].z !== t3.z) {\n n3 = e36;\n break;\n }\n if (n3 \u003c= 0)\n return false;\n const o4 = n3 - 1;\n if (!kP(l3[o4], l3[n3]))\n return false;\n let i4 = n3;\n for (;i4 + 1 \u003c l3.length \u0026\u0026 kP(l3[n3], l3[i4 + 1]); )\n i4 += 1;\n const a4 = l3[i4].z, h3 = l3.slice(o4, i4 + 1).map((e36) =\u003e e36.z);\n return c3.route = [t3, ...h3.slice(1).map((e36) =\u003e ({ ...t3, z: e36, pcb_port_id: undefined })), ...l3.slice(1, o4 + 1).map((e36) =\u003e ({ ...e36, z: a4 })), ...l3.slice(i4 + 1)], true;\n }\n const h2 = l3.at(-1);\n if (!Cw(e35, c3, h2, r3, s2))\n return false;\n let d2 = -1;\n for (let e36 = l3.length - 2;e36 \u003e= 0; e36 -= 1)\n if (l3[e36].z !== h2.z) {\n d2 = e36;\n break;\n }\n if (d2 \u003c 0 || d2 \u003e= l3.length - 1)\n return false;\n const u2 = d2 + 1;\n if (!kP(l3[d2], l3[u2]))\n return false;\n let p3 = d2;\n for (;p3 - 1 \u003e= 0 \u0026\u0026 kP(l3[d2], l3[p3 - 1]); )\n p3 -= 1;\n const m2 = l3[p3].z, g2 = l3.slice(p3, u2 + 1).map((e36) =\u003e e36.z);\n return c3.route = [...l3.slice(0, p3 + 1), ...l3.slice(u2 + 1, -1).map((e36) =\u003e ({ ...e36, z: m2 })), { ...h2, z: m2, pcb_port_id: undefined }, ...g2.slice(1, -1).map((e36) =\u003e ({ ...h2, z: e36, pcb_port_id: undefined })), h2], true;\n};\nvar kw = (e35, t2) =\u003e {\n const n2 = e35.pcb_trace_id;\n if (typeof n2 != \"string\")\n return;\n if (Array.isArray(e35.pcb_via_ids) \u0026\u0026 e35.pcb_via_ids.length \u003e 0)\n return;\n const o3 = Array.isArray(e35.pcb_trace_ids) ? e35.pcb_trace_ids.filter((e36) =\u003e typeof e36 == \"string\") : [], i3 = e35.pcb_trace_error_id, r3 = `overlap_${n2}_`, s2 = typeof i3 == \"string\" \u0026\u0026 i3.startsWith(r3) ? i3.slice(r3.length) : undefined, a3 = [n2, ...o3, ...s2 ? [s2] : []], c3 = [...new Set(a3.map((e36) =\u003e t2.get(e36)).filter((e36) =\u003e e36 !== undefined))];\n return c3.length \u003e= 2 ? [c3[0], c3[1]] : undefined;\n};\nvar Dw = (e35, t2, n2, o3, i3) =\u003e {\n if (LP(n2) !== \"pcb_trace_error\")\n return;\n const r3 = kw(n2, o3);\n if (!r3)\n return;\n const s2 = n2.worst_contact_center ?? n2.center;\n if (!s2 || typeof s2 != \"object\")\n return;\n const a3 = s2;\n if (typeof a3.x != \"number\" || typeof a3.y != \"number\")\n return;\n const c3 = { x: a3.x, y: a3.y }, l3 = UP(t2), h2 = XM(l3, c3, r3[0]), d2 = XM(l3, c3, r3[1]);\n if (!h2 || !d2 || h2.z !== d2.z)\n return;\n const u2 = GM(h2, d2), p3 = u2.leftPoint.x - u2.rightPoint.x, m2 = u2.leftPoint.y - u2.rightPoint.y, g2 = Math.hypot(p3, m2), f2 = Number(n2.minimum_clearance), _2 = Number.isFinite(f2) ? f2 : hP.traceClearance ?? 0.1, y2 = h2.radius + d2.radius + _2 - g2;\n if (y2 \u003c= bb)\n return;\n const b2 = i3 === 0 ? h2 : d2, x2 = i3 === 0 ? u2.leftT : u2.rightT, v2 = (1 - x2) ** 2 + x2 ** 2;\n if (v2 \u003c= bb)\n return;\n const I2 = y2 / v2, S2 = i3 === 0 ? u2.leftPoint : u2.rightPoint, C = i3 === 0 ? u2.rightPoint : u2.leftPoint, P = i3 === 0 ? 1 : -1, M = b2.end.x - b2.start.x, w = b2.end.y - b2.start.y, N = Math.hypot(M, w), R2 = (b2.routeIndex + (i3 === 0 ? d2.routeIndex : h2.routeIndex)) % 2 == 0 ? 1 : -1, T2 = g2 \u003e bb ? (S2.x - C.x) / g2 : N \u003e bb ? -w / N * R2 * P : P, E3 = g2 \u003e bb ? (S2.y - C.y) / g2 : N \u003e bb ? M / N * R2 * P : 0;\n return UM(t2, b2, T2 * I2, E3 * I2, e35, x2) ? { movedRouteIndex: b2.routeIndex } : undefined;\n};\nvar Lw = (e35) =\u003e {\n const { srj: t2, via: n2, segment: o3, initialTarget: i3, requiredTraceDistance: r3, requiredObstacleDistance: s2, connMap: a3 } = e35, c3 = t2.obstacles.filter((e36) =\u003e !e36.isCopperPour \u0026\u0026 !bP(n2.rootConnectionName, e36, a3) \u0026\u0026 QP(e36, t2.layerCount).some((e37) =\u003e n2.zLayers.includes(e37))), l3 = c3.filter((e36) =\u003e Boolean(sM(i3, e36, s2))), h2 = [i3, ...l3.flatMap((e36) =\u003e ((e37) =\u003e {\n const { point: t3, obstacle: n3, requiredDistance: o4 } = e37, i4 = n3.center.x - n3.width / 2, r4 = n3.center.x + n3.width / 2, s3 = n3.center.y - n3.height / 2, a4 = n3.center.y + n3.height / 2, c4 = Math.max(i4 - t3.x, t3.x - r4, 0), l4 = Math.max(s3 - t3.y, t3.y - a4, 0), h3 = [];\n if (c4 \u003c o4) {\n const e38 = Math.sqrt(o4 * o4 - c4 * c4);\n h3.push({ x: t3.x, y: s3 - e38 - bb }, { x: t3.x, y: a4 + e38 + bb });\n }\n if (l4 \u003c o4) {\n const e38 = Math.sqrt(o4 * o4 - l4 * l4);\n h3.push({ x: i4 - e38 - bb, y: t3.y }, { x: r4 + e38 + bb, y: t3.y });\n }\n return h3;\n })({ point: i3, obstacle: e36, requiredDistance: s2 }))];\n return h2.filter((e36) =\u003e {\n if (!Rw(e36, n2.radius, t2.bounds))\n return false;\n const i4 = tM(e36, o3);\n return !(Math.hypot(e36.x - i4.x, e36.y - i4.y) \u003c r3 - bb) \u0026\u0026 c3.every((t3) =\u003e nM(e36, t3) \u003e= s2 - bb);\n }).sort((e36, t3) =\u003e Math.hypot(e36.x - n2.x, e36.y - n2.y) - Math.hypot(t3.x - n2.x, t3.y - n2.y))[0];\n};\nvar zw = (e35, t2, n2, o3, i3, r3) =\u003e {\n if (LP(n2) !== \"pcb_trace_error\")\n return false;\n const s2 = typeof n2.pcb_trace_error_id == \"string\" ? n2.pcb_trace_error_id.toLowerCase() : \"\", a3 = typeof n2.message == \"string\" ? n2.message.toLowerCase() : \"\";\n if (!(typeof n2.pcb_via_id == \"string\" || Array.isArray(n2.pcb_via_ids) || s2.includes(\"_via_\") || a3.includes(\"via\")))\n return false;\n if (Sw(n2, o3) !== i3)\n return false;\n if (kw(n2, o3))\n return false;\n const c3 = n2.worst_contact_center ?? n2.center;\n if (!c3 || typeof c3 != \"object\")\n return false;\n const l3 = c3;\n if (typeof l3.x != \"number\" || typeof l3.y != \"number\")\n return false;\n const h2 = { x: l3.x, y: l3.y }, d2 = XM(UP(t2), h2, i3), u2 = HM(WP(t2, e35), h2);\n if (!d2 || !u2 || !u2.movable || yP(u2.rootConnectionName, d2.rootConnectionName, r3))\n return false;\n const p3 = tM(u2, d2), m2 = u2.x - p3.x, g2 = u2.y - p3.y, f2 = Math.hypot(m2, g2), _2 = Number(n2.minimum_clearance), y2 = Number.isFinite(_2) ? _2 : hP.traceClearance ?? 0.1, b2 = u2.radius + d2.radius + y2 - f2;\n if (b2 \u003c= bb)\n return false;\n const x2 = d2.end.x - d2.start.x, v2 = d2.end.y - d2.start.y, I2 = Math.hypot(x2, v2), S2 = u2.routeIndex % 2 == 0 ? 1 : -1, C = f2 \u003e bb ? m2 / f2 : I2 \u003e bb ? -v2 / I2 * S2 : 1, P = f2 \u003e bb ? g2 / f2 : I2 \u003e bb ? x2 / I2 * S2 : 0, M = u2.radius + d2.radius + y2 + Sb, w = u2.radius + Pb(e35) + Sb, N = { x: u2.x + C * (b2 + Sb), y: u2.y + P * (b2 + Sb) }, R2 = Lw({ srj: e35, via: u2, segment: d2, initialTarget: N, requiredTraceDistance: M, requiredObstacleDistance: w, connMap: r3 });\n return !!R2 \u0026\u0026 jM(t2, u2, R2.x - u2.x, R2.y - u2.y, e35);\n};\nvar Bw = (e35, t2, n2) =\u003e {\n if (LP(t2) !== \"pcb_trace_error\")\n return;\n const o3 = lw(t2), i3 = e35[n2];\n if (!o3 || !i3)\n return;\n const r3 = XM(GP(i3, n2), o3);\n return r3 ? { center: o3, route: i3, segment: r3 } : undefined;\n};\nvar Fw = (e35, t2, n2, o3) =\u003e {\n const i3 = Bw(e35, t2, n2);\n if (!i3)\n return;\n const { route: r3, segment: s2 } = i3, a3 = Math.max(0, s2.startIndex - o3), c3 = Math.min(r3.route.length - 1, s2.endIndex + o3), l3 = r3.route.slice(a3, c3 + 1), h2 = l3[0], d2 = l3.at(-1);\n return h2 \u0026\u0026 d2 \u0026\u0026 !l3.some((e36) =\u003e e36.z !== h2.z) \u0026\u0026 h2.z === d2.z ? { route: r3, spanStartIndex: a3, spanEndIndex: c3, start: h2, end: d2 } : undefined;\n};\nvar jw = (e35, t2, n2, o3, i3, r3, s2 = 0, a3, c3) =\u003e {\n if (r3 \u003c 0 || r3 \u003e= e35.layerCount)\n return false;\n const l3 = kw(n2, o3);\n if (!l3)\n return false;\n const h2 = l3[i3], d2 = Bw(t2, n2, h2);\n if (!d2 || d2.segment.z === r3)\n return false;\n const { route: u2, segment: p3 } = d2;\n let { startIndex: m2, endIndex: g2 } = p3;\n for (let e36 = 0;e36 \u003c s2; e36 += 1) {\n const e37 = u2.route[m2 - 1];\n e37?.z === p3.z \u0026\u0026 (m2 -= 1);\n const t3 = u2.route[g2 + 1];\n t3?.z === p3.z \u0026\u0026 (g2 += 1);\n }\n if (m2 === 0 \u0026\u0026 u2.route[0]?.pcb_port_id \u0026\u0026 !Cw(e35, u2, u2.route[0], a3, c3) || g2 === u2.route.length - 1 \u0026\u0026 u2.route.at(-1)?.pcb_port_id \u0026\u0026 !Cw(e35, u2, u2.route.at(-1), a3, c3))\n return false;\n const f2 = u2.route[m2], _2 = u2.route[g2];\n if (!f2 || !_2 || f2.z !== _2.z)\n return false;\n const y2 = u2.route.slice(m2, g2 + 1).map((e36) =\u003e ({ ...e36, z: r3, pcb_port_id: undefined }));\n return u2.route.splice(m2, g2 - m2 + 1, { ...f2 }, ...y2, { ..._2 }), true;\n};\nvar $w = (e35, t2, n2, o3, i3, r3) =\u003e {\n if (o3 \u003c= 0 || i3 \u003c= 0)\n return false;\n const s2 = Bw(e35, t2, n2);\n if (!s2)\n return false;\n const { center: a3, route: c3, segment: l3 } = s2, h2 = l3.end.x - l3.start.x, d2 = l3.end.y - l3.start.y, u2 = Math.hypot(h2, d2);\n if (u2 \u003c= bb)\n return false;\n const p3 = tM(a3, l3), m2 = xP(p3.t - o3 / u2, 0.02, 0.98), g2 = xP(p3.t + o3 / u2, 0.02, 0.98);\n if (m2 \u003e= g2)\n return false;\n const f2 = (e36) =\u003e ({ x: l3.start.x + h2 * e36, y: l3.start.y + d2 * e36, z: l3.z }), _2 = f2(m2), y2 = f2(g2), b2 = -d2 / u2 * r3, x2 = h2 / u2 * r3, v2 = c3.route[l3.startIndex], I2 = c3.route[l3.endIndex];\n return c3.route.splice(l3.startIndex, 2, { ...v2 }, _2, { ..._2, x: _2.x + b2 * i3, y: _2.y + x2 * i3 }, { ...y2, x: y2.x + b2 * i3, y: y2.y + x2 * i3 }, y2, { ...I2 }), true;\n};\nvar Yw = (e35, t2, n2, o3, i3, r3, s2, a3 = false) =\u003e {\n if (!Number.isInteger(i3) || i3 \u003c 0 || i3 \u003e= e35.layerCount)\n return false;\n const c3 = lw(n2), l3 = t2[o3], h2 = l3?.route[0], d2 = l3?.route.at(-1);\n if (!l3 || !c3 || !h2 || !d2 || h2.z !== d2.z || h2.z === i3 || l3.jumpers?.length || l3.route.some((e36) =\u003e e36.z !== h2.z || e36.toNextSegmentType === \"through_obstacle\"))\n return false;\n const u2 = d2.x - h2.x, p3 = d2.y - h2.y, m2 = Math.hypot(u2, p3);\n if (m2 \u003c= bb || m2 \u003e 8)\n return false;\n const g2 = u2 / m2, f2 = p3 / m2, _2 = f2 * r3, y2 = -g2 * r3, b2 = (e36) =\u003e (e36.x - c3.x) * g2 + (e36.y - c3.y) * f2, x2 = (e36, t3, n3) =\u003e ({ x: c3.x + g2 * e36 + _2 * t3, y: c3.y + f2 * e36 + y2 * t3, z: n3 }), v2 = (l3.viaDiameter ?? e35.minViaDiameter ?? 0.3) + (e35.minTraceToPadEdgeClearance ?? hP.traceClearance ?? 0.1), I2 = (a3 ? 1.25 : -0.75) * v2, S2 = (a3 ? -0.75 : 1.25) * v2, C = b2(h2) + 0.5 * v2 * s2, P = b2(d2) + v2 * s2, M = x2(C, I2, h2.z), w = x2(P, S2, h2.z), N = x2(C, 2 * v2, i3), R2 = x2(P, 2 * v2, i3), T2 = [{ ...h2 }, M, { ...M, z: i3 }, N, R2, { ...w, z: i3 }, w, { ...d2 }], E3 = e35.minBoardEdgeClearance ?? 0, A2 = (l3.viaDiameter ?? e35.minViaDiameter ?? 0.3) / 2, O2 = l3.traceThickness / 2;\n if ([M, w].some((t3) =\u003e _M(e35, t3) + xb \u003c A2 + E3))\n return false;\n for (let t3 = 0;t3 \u003c T2.length - 1; t3 += 1) {\n const n3 = T2[t3], o4 = T2[t3 + 1];\n if (n3.z === o4.z \u0026\u0026 yM(e35, n3, o4) + xb \u003c O2 + E3)\n return false;\n }\n return l3.route.splice(0, l3.route.length, ...T2), true;\n};\nvar Xw = (e35, t2, n2, o3, i3, r3, s2) =\u003e {\n if (!Number.isInteger(i3) || i3 \u003c 1 || r3 \u003c= 0)\n return false;\n const a3 = Fw(t2, n2, o3, i3);\n if (!a3)\n return false;\n const { route: c3, spanStartIndex: l3, spanEndIndex: h2, start: d2, end: u2 } = a3, p3 = u2.x - d2.x, m2 = u2.y - d2.y, g2 = Math.hypot(p3, m2);\n if (g2 \u003c= bb)\n return false;\n const f2 = -m2 / g2 * s2 * r3, _2 = p3 / g2 * s2 * r3, y2 = { ...d2, x: d2.x + f2, y: d2.y + _2, pcb_port_id: undefined }, b2 = { ...u2, x: u2.x + f2, y: u2.y + _2, pcb_port_id: undefined };\n return !(!hM(y2, e35.bounds) || !hM(b2, e35.bounds)) \u0026\u0026 (c3.route.splice(l3, h2 - l3 + 1, { ...d2 }, y2, b2, { ...u2 }), true);\n};\nvar Hw = (e35, t2, n2, o3, i3, r3) =\u003e {\n if (!Number.isInteger(i3) || i3 \u003c 0)\n return false;\n const s2 = Fw(t2, n2, o3, i3);\n if (!s2)\n return false;\n const { route: a3, spanStartIndex: c3, spanEndIndex: l3, start: h2, end: d2 } = s2;\n return !(Math.hypot(r3.x - h2.x, r3.y - h2.y) \u003c= bb || Math.hypot(r3.x - d2.x, r3.y - d2.y) \u003c= bb || !hM(r3, e35.bounds)) \u0026\u0026 (a3.route.splice(c3, l3 - c3 + 1, { ...h2 }, { x: r3.x, y: r3.y, z: h2.z }, { ...d2 }), true);\n};\nvar Vw = (e35, t2, n2, o3, i3, r3) =\u003e {\n if (r3) {\n if (e35.errors.filter(dw).length \u003e r3.errors.filter(dw).length)\n return false;\n const t3 = mw(e35), n3 = mw(r3);\n if (t3 !== n3)\n return t3 \u003c n3;\n }\n const s2 = gw(e35), a3 = fw(e35);\n return s2 \u003c n2 || s2 === n2 \u0026\u0026 a3 \u003c o3 || s2 === n2 \u0026\u0026 t2 \u003c i3;\n};\nvar Ww = (e35, t2, n2, o3, i3, r3, s2 = true, a3 = false, c3 = true, l3 = false) =\u003e {\n let h2 = false, d2 = WP(t2, e35), u2 = UP(t2);\n for (const p3 of n2) {\n const n3 = lw(p3);\n if (!n3)\n continue;\n let m2 = n3;\n const g2 = p3.pcb_via_ids, f2 = LP(p3) === \"pcb_via_clearance_error\", _2 = uw(p3), y2 = Array.isArray(g2) \u0026\u0026 g2.length \u003e 0, b2 = !f2 \u0026\u0026 !_2 \u0026\u0026 !Array.isArray(p3.pcb_pad_ids) \u0026\u0026 y2 \u0026\u0026 (typeof p3.pcb_trace_id == \"string\" || Array.isArray(p3.pcb_trace_ids)), x2 = l3 \u0026\u0026 b2;\n if (y2 \u0026\u0026 !b2) {\n m2 = aM(e35, p3, n3);\n const c4 = Sw(p3, o3), l4 = g2.length \u003e 1 ? VM(d2, n3) : undefined;\n if (l4) {\n const n4 = a3 \u0026\u0026 LP(p3) === \"pcb_via_clearance_error\" \u0026\u0026 p3.pcb_via_pair_net_relation === \"same_net\", o4 = s2 \u0026\u0026 LP(p3) === \"pcb_via_clearance_error\";\n h2 = (n4 ? qM(t2, l4[0], l4[1], e35, r3) : ZM(t2, l4[0], l4[1], e35, r3, 0.16 * Math.abs(i3), o4)) || h2;\n } else {\n const o4 = HM(d2, n3, c4);\n if (o4)\n if (dw(p3) \u0026\u0026 typeof p3.minimum_clearance == \"number\" \u0026\u0026 typeof p3.actual_clearance == \"number\") {\n const n4 = o4.x - m2.x, r4 = o4.y - m2.y, s3 = Math.hypot(n4, r4), a4 = Math.min(vb, p3.minimum_clearance - p3.actual_clearance + bb) * i3;\n h2 = jM(t2, o4, (s3 \u003e bb ? n4 / s3 : 1) * a4, (s3 \u003e bb ? r4 / s3 : 0) * a4, e35) || h2;\n } else\n h2 = WM(t2, o4, m2, e35) || h2;\n }\n continue;\n }\n const v2 = p3.pcb_trace_id, I2 = Sw(p3, o3);\n if (x2 \u0026\u0026 I2 === undefined)\n continue;\n const S2 = Array.isArray(p3.pcb_trace_ids) ? p3.pcb_trace_ids.filter((e36) =\u003e typeof e36 == \"string\") : [];\n if (x2 \u0026\u0026 typeof v2 == \"string\" \u0026\u0026 I2 !== undefined \u0026\u0026 S2.includes(v2) \u0026\u0026 S2.some((e36) =\u003e e36 !== v2 \u0026\u0026 !o3.has(e36))) {\n const o4 = HM(d2, n3, I2);\n if (o4) {\n h2 = WM(t2, o4, n3, e35) || h2;\n continue;\n }\n }\n const C = s2 \u0026\u0026 !b2 ? kw(p3, o3) : undefined;\n if (C) {\n const o4 = XM(u2, n3, C[0]), i4 = XM(u2, n3, C[1]);\n if (o4 \u0026\u0026 i4 \u0026\u0026 QM(t2, o4, i4, e35, r3)) {\n h2 = true;\n continue;\n }\n }\n const P = zP(p3), M = P \u0026\u0026 I2 !== undefined ? ew(e35, t2, I2, n3, r3) : undefined, w = P ? M?.segment : XM(u2, n3, I2);\n if (w) {\n const o4 = P ? M?.obstacle : rM(e35, n3);\n if (P \u0026\u0026 !o4)\n continue;\n m2 = P ? o4?.center ?? n3 : aM(e35, p3, n3);\n const s3 = x2 ? undefined : HM(d2, n3), a4 = LP(p3) === \"pcb_via_trace_clearance_error\", l4 = typeof p3.pcb_trace_error_id == \"string\" ? p3.pcb_trace_error_id.toLowerCase() : \"\", g3 = typeof p3.message == \"string\" ? p3.message.toLowerCase() : \"\", f3 = a4 || typeof p3.pcb_via_id == \"string\" || Array.isArray(p3.pcb_via_ids) || l4.includes(\"_via_\") || g3.includes(\"via\"), _3 = Array.isArray(p3.pcb_port_ids) \u0026\u0026 p3.pcb_port_ids.length \u003e 0;\n if (s3 \u0026\u0026 !yP(s3.rootConnectionName, w.rootConnectionName, r3) \u0026\u0026 (a4 || Math.hypot(s3.x - n3.x, s3.y - n3.y) \u003c 0.45)) {\n if (JM(t2, s3, w, e35, r3, 0.3 * Math.abs(i3), 1, c3) \u0026\u0026 (h2 = true, f3 \u0026\u0026 !_3))\n continue;\n }\n const y3 = o4 !== undefined \u0026\u0026 (P || !bP(w.rootConnectionName, o4, r3) \u0026\u0026 KM(o4, w, e35.layerCount)), b3 = t2[w.routeIndex].route.length, v3 = y3 ? YM(t2, w, o4, e35, r3, i3) : $M(t2, w, m2, e35, i3);\n t2[w.routeIndex].route.length !== b3 \u0026\u0026 (d2 = WP(t2, e35), u2 = UP(t2)), h2 = v3 || h2;\n }\n const N = x2 ? undefined : HM(d2, n3);\n N \u0026\u0026 Math.hypot(N.x - n3.x, N.y - n3.y) \u003c 0.35 \u0026\u0026 (h2 = WM(t2, N, m2, e35) || h2);\n }\n return h2;\n};\nvar Gw = 0.000001;\nvar Uw = 0.006;\nvar Zw = [1, 0.5, 0.25, 0.1, 0.05, 0.025];\nvar qw = (e35, t2) =\u003e (t2.traceThickness ?? e35.minTraceWidth) / 2;\nvar Jw = (e35) =\u003e e35.minTraceToPadEdgeClearance ?? 0.1;\nvar Qw = (e35, t2) =\u003e t2.viaDiameter ?? e35.minViaDiameter ?? 0.3;\nvar Kw = (e35, t2) =\u003e me(e35, t2) \u003c Gw;\nvar eN = (e35) =\u003e {\n const t2 = [], n2 = (e36) =\u003e {\n t2.some((t3) =\u003e Kw(t3, e36)) || t2.push({ x: e36.x, y: e36.y });\n };\n for (const t3 of e35.vias)\n n2(t3);\n for (let t3 = 0;t3 \u003c e35.route.length - 1; t3 += 1) {\n const o3 = e35.route[t3], i3 = e35.route[t3 + 1];\n o3 \u0026\u0026 i3 \u0026\u0026 o3.z !== i3.z \u0026\u0026 (Kw(o3, i3) \u0026\u0026 n2(o3));\n }\n return t2;\n};\nvar tN = (e35) =\u003e me({ x: 0, y: 0 }, e35) \u003c Gw ? { x: 0, y: 0 } : Ae({ x: 0, y: 0 }, e35);\nvar nN = (e35, t2) =\u003e {\n if (e35.zLayers \u0026\u0026 e35.zLayers.length \u003e 0)\n return e35.zLayers;\n const n2 = Array.from({ length: t2 }, (e36, t3) =\u003e t3).filter((n3) =\u003e e35.layers.includes(Qy(n3, t2)));\n return n2.length \u003e 0 ? n2 : Array.from({ length: t2 }, (e36, t3) =\u003e t3);\n};\nvar oN = (e35, t2, n2) =\u003e yP(gP(e35), gP(t2), n2) || yP(gP(e35), t2.connectionName, n2) || yP(e35.connectionName, gP(t2), n2) || yP(e35.connectionName, t2.connectionName, n2);\nvar iN = (e35, t2, n2) =\u003e bP(gP(e35), t2, n2) || bP(e35.connectionName, t2, n2);\nvar rN = (e35, t2, n2, o3) =\u003e !n2.pcb_port_id \u0026\u0026 e35.obstacles.some((i3) =\u003e iN(t2, i3, o3) \u0026\u0026 nN(i3, e35.layerCount).includes(n2.z) \u0026\u0026 ((e36, t3) =\u003e e36.x \u003e= t3.center.x - t3.width / 2 - Gw \u0026\u0026 e36.x \u003c= t3.center.x + t3.width / 2 + Gw \u0026\u0026 e36.y \u003e= t3.center.y - t3.height / 2 - Gw \u0026\u0026 e36.y \u003c= t3.center.y + t3.height / 2 + Gw)(n2, i3));\nvar sN = (e35, t2, n2, o3, i3) =\u003e {\n if (!((e36, t3) =\u003e e36.zLayers.includes(t3))(i3, n2.z))\n return Number.POSITIVE_INFINITY;\n const r3 = qw(e35, t2);\n return i3.kind === \"pad\" ? Re(n2, o3, i3.obstacle) - (Jw(e35) + r3 + Uw) : pe(i3.center, n2, o3) - (Jw(e35) + r3 + i3.diameter / 2 + Uw);\n};\nvar aN = (e35, t2, n2) =\u003e {\n const o3 = n2.kind === \"pad\" ? n2.obstacle.center : n2.center, i3 = Ee(o3, e35, t2);\n let r3 = tN({ x: i3.x - o3.x, y: i3.y - o3.y });\n if (Math.abs(r3.x) \u003c Gw \u0026\u0026 Math.abs(r3.y) \u003c Gw) {\n const n3 = t2.x - e35.x, i4 = t2.y - e35.y, s2 = ke(e35, t2), a3 = tN({ x: -i4, y: n3 }), c3 = { x: -a3.x, y: -a3.y };\n r3 = me({ x: s2.x + a3.x, y: s2.y + a3.y }, o3) \u003e= me({ x: s2.x + c3.x, y: s2.y + c3.y }, o3) ? a3 : c3;\n }\n return r3;\n};\nvar cN = (e35, t2, n2, o3) =\u003e {\n if (n2 \u003c= 0 || n2 \u003e= t2.route.length - 1) {\n const i4 = t2.route[n2];\n return !i4 || !rN(e35, t2, i4, o3);\n }\n const i3 = t2.route[n2];\n if (!i3 || i3.insideJumperPad)\n return true;\n const r3 = t2.route[n2 - 1], s2 = t2.route[n2 + 1];\n return !(!r3 || r3.z === i3.z) || (!(!s2 || s2.z === i3.z) || t2.vias.some((e36) =\u003e Kw(e36, i3)));\n};\nvar lN = (e35, t2, n2) =\u003e {\n let o3 = 0;\n for (let i3 = 0;i3 \u003c t2.route.length - 1; i3 += 1) {\n const r3 = t2.route[i3], s2 = t2.route[i3 + 1];\n if (r3 \u0026\u0026 s2 \u0026\u0026 r3.z === s2.z \u0026\u0026 !Kw(r3, s2))\n for (const i4 of n2) {\n const n3 = sN(e35, t2, r3, s2, i4);\n if (!(n3 \u003e= 0) \u0026\u0026 (o3 += n3 * n3, i4.kind === \"pad\")) {\n if (Re(r3, s2, i4.obstacle) \u003c Gw) {\n o3 += 0.01 / (pe(i4.obstacle.center, r3, s2) + 0.01);\n }\n }\n }\n }\n return o3;\n};\nvar hN = (e35, t2, n2, o3) =\u003e {\n let i3 = 0;\n for (let r3 = 0;r3 \u003c t2.route.length - 1; r3 += 1) {\n const s2 = t2.route[r3], a3 = t2.route[r3 + 1];\n if (s2 \u0026\u0026 a3 \u0026\u0026 s2.z === a3.z \u0026\u0026 !Kw(s2, a3)) {\n for (const r4 of n2)\n if (!oN(t2, r4, o3)) {\n for (let n3 = 0;n3 \u003c r4.route.length - 1; n3 += 1) {\n const o4 = r4.route[n3], c3 = r4.route[n3 + 1];\n if (!o4 || !c3 || o4.z !== s2.z || c3.z !== s2.z || Kw(o4, c3))\n continue;\n const l3 = we(s2, a3, o4, c3) - qw(e35, t2) - qw(e35, r4), h2 = Jw(e35) + Uw - l3;\n h2 \u003e 0 \u0026\u0026 (i3 += h2 * h2);\n }\n for (const n3 of eN(r4)) {\n const o4 = pe(n3, s2, a3) - qw(e35, t2) - Qw(e35, r4) / 2, c3 = Jw(e35) + Uw - o4;\n c3 \u003e 0 \u0026\u0026 (i3 += c3 * c3);\n }\n }\n }\n }\n return i3;\n};\nvar dN = (e35, t2, n2, o3, i3) =\u003e {\n const r3 = t2.route.map(() =\u003e ({ x: 0, y: 0 }));\n for (let s2 = 0;s2 \u003c t2.route.length - 1; s2 += 1) {\n const a3 = t2.route[s2], c3 = t2.route[s2 + 1];\n if (a3 \u0026\u0026 c3 \u0026\u0026 a3.z === c3.z \u0026\u0026 !Kw(a3, c3)) {\n for (const o4 of n2) {\n const n3 = sN(e35, t2, a3, c3, o4);\n if (n3 \u003e= 0)\n continue;\n const l3 = aN(a3, c3, o4);\n if (Math.abs(l3.x) \u003c Gw \u0026\u0026 Math.abs(l3.y) \u003c Gw)\n continue;\n const h2 = !cN(e35, t2, s2, i3), d2 = !cN(e35, t2, s2 + 1, i3);\n if (!h2 \u0026\u0026 !d2)\n continue;\n const u2 = -n3, p3 = h2 \u0026\u0026 d2 ? 0.5 : h2 ? 1 : 0, m2 = h2 \u0026\u0026 d2 ? 0.5 : d2 ? 1 : 0;\n r3[s2].x += l3.x * u2 * p3, r3[s2].y += l3.y * u2 * p3, r3[s2 + 1].x += l3.x * u2 * m2, r3[s2 + 1].y += l3.y * u2 * m2;\n }\n for (const n3 of o3)\n if (!oN(t2, n3, i3))\n for (let o4 = 0;o4 \u003c n3.route.length - 1; o4 += 1) {\n const l3 = n3.route[o4], h2 = n3.route[o4 + 1];\n if (!l3 || !h2 || l3.z !== a3.z || h2.z !== a3.z || Kw(l3, h2))\n continue;\n const d2 = we(a3, c3, l3, h2) - qw(e35, t2) - qw(e35, n3), u2 = e35.minTraceToPadEdgeClearance + Uw - d2;\n if (u2 \u003c= 0)\n continue;\n const p3 = ke(a3, c3), m2 = Ee(p3, l3, h2);\n let g2 = tN({ x: p3.x - m2.x, y: p3.y - m2.y });\n if (Math.abs(g2.x) \u003c Gw \u0026\u0026 Math.abs(g2.y) \u003c Gw) {\n const e36 = c3.x - a3.x, t3 = c3.y - a3.y;\n g2 = tN({ x: -t3, y: e36 });\n }\n const f2 = !cN(e35, t2, s2, i3), _2 = !cN(e35, t2, s2 + 1, i3);\n if (!f2 \u0026\u0026 !_2)\n continue;\n const y2 = f2 \u0026\u0026 _2 ? 0.5 : f2 ? 1 : 0, b2 = f2 \u0026\u0026 _2 ? 0.5 : _2 ? 1 : 0;\n r3[s2].x += g2.x * u2 * y2, r3[s2].y += g2.y * u2 * y2, r3[s2 + 1].x += g2.x * u2 * b2, r3[s2 + 1].y += g2.y * u2 * b2;\n }\n }\n }\n return r3;\n};\nvar uN = (e35, t2, n2, o3, i3) =\u003e ({ ...t2, route: t2.route.map((r3, s2) =\u003e {\n if (cN(e35, t2, s2, i3))\n return { ...r3 };\n const a3 = ((e36, t3) =\u003e {\n const n3 = me({ x: 0, y: 0 }, e36);\n if (n3 \u003c= t3 || n3 \u003c Gw)\n return e36;\n const o4 = t3 / n3;\n return { x: e36.x * o4, y: e36.y * o4 };\n })(n2[s2] ?? { x: 0, y: 0 }, 0.5);\n return { ...r3, x: r3.x + a3.x * o3, y: r3.y + a3.y * o3 };\n}), vias: t2.vias.map((e36) =\u003e ({ ...e36 })), jumpers: t2.jumpers ? [...t2.jumpers] : undefined });\nvar pN = (e35, t2) =\u003e t2.route.every((t3) =\u003e t3.x \u003e= e35.bounds.minX - Gw \u0026\u0026 t3.x \u003c= e35.bounds.maxX + Gw \u0026\u0026 t3.y \u003e= e35.bounds.minY - Gw \u0026\u0026 t3.y \u003c= e35.bounds.maxY + Gw);\nvar mN = (e35, t2, n2, o3, i3) =\u003e {\n const r3 = ((e36, t3, n3, o4) =\u003e {\n const i4 = [];\n for (const t4 of e36.obstacles)\n t4.isCopperPour || iN(n3, t4, o4) || i4.push({ kind: \"pad\", obstacle: t4, zLayers: nN(t4, e36.layerCount) });\n const r4 = Array.from({ length: e36.layerCount }, (e37, t4) =\u003e t4);\n for (const s3 of t3)\n if (s3 !== n3 \u0026\u0026 !oN(n3, s3, o4))\n for (const t4 of eN(s3))\n i4.push({ kind: \"via\", center: { x: t4.x, y: t4.y }, diameter: Qw(e36, s3), zLayers: r4, connectionName: s3.connectionName, rootConnectionName: s3.rootConnectionName });\n return i4;\n })(e35, t2, n2, i3), s2 = t2.filter((e36, t3) =\u003e t3 !== o3 \u0026\u0026 e36 !== n2);\n let a3 = n2, c3 = lN(e35, a3, r3) + hN(e35, a3, s2, i3);\n for (let t3 = 0;t3 \u003c 160 \u0026\u0026 !(c3 \u003c= Gw); t3 += 1) {\n const t4 = dN(e35, a3, r3, s2, i3);\n if (t4.every((e36) =\u003e me(e36, { x: 0, y: 0 }) \u003c 0.000000001))\n break;\n let n3 = null, o4 = c3;\n for (const l3 of Zw) {\n const h2 = uN(e35, a3, t4, l3, i3), d2 = lN(e35, h2, r3) + hN(e35, h2, s2, i3);\n if (d2 \u003c c3 - 0.000001 \u0026\u0026 pN(e35, h2)) {\n n3 = h2, o4 = d2;\n break;\n }\n }\n if (!n3)\n break;\n a3 = n3, c3 = o4;\n }\n return a3;\n};\nvar gN = 0.000001;\nvar fN = [1, 0.5, 0.25, 0.1, 0.05, 0.025];\nvar _N = (e35, t2) =\u003e e35.some((e36) =\u003e t2.includes(e36));\nvar yN = (e35, t2, n2, o3) =\u003e (bP(e35.rootConnectionName, n2, o3) || bP(t2.connectionName, n2, o3)) \u0026\u0026 nM(e35, n2) \u003c= gN;\nvar bN = (e35, t2, n2, o3) =\u003e {\n const i3 = [], r3 = t2[n2.routeIndex];\n if (!r3)\n return i3;\n for (const t3 of e35.obstacles) {\n if (t3.isCopperPour || yN(n2, r3, t3, o3))\n continue;\n const s2 = QP(t3, e35.layerCount);\n _N(n2.zLayers, s2) \u0026\u0026 i3.push({ obstacle: t3 });\n }\n return i3;\n};\nvar xN = (e35, t2, n2) =\u003e nM(t2, n2.obstacle) - (t2.radius + e35.minViaEdgeToPadEdgeClearance + 0.006);\nvar vN = (e35, t2, n2, o3) =\u003e WP(t2, e35).filter((e36) =\u003e e36.routeIndex === n2).reduce((n3, i3) =\u003e n3 + ((e36, t3, n4, o4) =\u003e {\n let i4 = 0;\n for (const r3 of bN(e36, t3, n4, o4)) {\n const t4 = xN(e36, n4, r3);\n !(t4 \u003e= 0) \u0026\u0026 (i4 += t4 * t4, nM(n4, r3.obstacle) \u003c gN) \u0026\u0026 (i4 += 0.01 / (me(n4, r3.obstacle.center) + 0.01));\n }\n return i4;\n})(e35, t2, i3, o3), 0);\nvar IN = (e35, t2, n2, o3) =\u003e {\n const i3 = t2[n2];\n if (!i3)\n return [];\n const r3 = i3.route.map(() =\u003e ({ x: 0, y: 0 })), s2 = WP(t2, e35).filter((e36) =\u003e e36.routeIndex === n2);\n for (const n3 of s2)\n if (n3.movable)\n for (const i4 of bN(e35, t2, n3, o3)) {\n const t3 = n3.radius + e35.minViaEdgeToPadEdgeClearance + 0.006, o4 = sM(n3, i4.obstacle, t3);\n if (o4)\n for (const e36 of n3.pointIndexes)\n r3[e36].x += o4.direction.x * o4.penetration, r3[e36].y += o4.direction.y * o4.penetration;\n }\n return r3;\n};\nvar SN = (e35, t2, n2, o3) =\u003e {\n const i3 = new Set(WP([t2], e35).flatMap((e36) =\u003e e36.movable ? e36.pointIndexes : []));\n return { ...t2, route: t2.route.map((e36, t3) =\u003e {\n if (!i3.has(t3))\n return { ...e36 };\n const r3 = ((e37, t4) =\u003e {\n const n3 = me({ x: 0, y: 0 }, e37);\n if (n3 \u003c= t4 || n3 \u003c gN)\n return e37;\n const o4 = t4 / n3;\n return { x: e37.x * o4, y: e37.y * o4 };\n })(n2[t3] ?? { x: 0, y: 0 }, 0.5);\n return { ...e36, x: e36.x + r3.x * o3, y: e36.y + r3.y * o3 };\n }), vias: t2.vias.map((e36) =\u003e ({ ...e36 })), jumpers: t2.jumpers ? [...t2.jumpers] : undefined };\n};\nvar CN = (e35, t2) =\u003e t2.route.every((t3) =\u003e t3.x \u003e= e35.bounds.minX - gN \u0026\u0026 t3.x \u003c= e35.bounds.maxX + gN \u0026\u0026 t3.y \u003e= e35.bounds.minY - gN \u0026\u0026 t3.y \u003c= e35.bounds.maxY + gN);\nvar PN = (e35, t2, n2, o3, i3) =\u003e {\n let r3 = n2, s2 = vN(e35, t2, o3, i3);\n for (let n3 = 0;n3 \u003c 160 \u0026\u0026 !(s2 \u003c= gN); n3 += 1) {\n const n4 = IN(e35, t2, o3, i3);\n if (n4.every((e36) =\u003e me(e36, { x: 0, y: 0 }) \u003c 0.000000001))\n break;\n let a3 = null, c3 = s2;\n for (const l3 of fN) {\n const h2 = SN(e35, r3, n4, l3), d2 = [...t2];\n d2[o3] = h2;\n const u2 = vN(e35, d2, o3, i3);\n if (u2 \u003c s2 - 0.000001 \u0026\u0026 CN(e35, h2)) {\n a3 = h2, c3 = u2;\n break;\n }\n }\n if (!a3)\n break;\n t2[o3] = a3, r3 = a3, s2 = c3;\n }\n return r3;\n};\nvar MN = ({ routes: e35, snapshot: t2, inputSnapshot: n2, checkpointRoutes: o3, peerConnectionNames: i3 }) =\u003e {\n const r3 = ((e36, t3) =\u003e {\n const n3 = bw(t3), o4 = new Set;\n for (const t4 of yw(e36)) {\n const i4 = _w(t4, e36);\n if (!i4)\n return;\n if (n3.has(i4))\n continue;\n const r4 = t4.pcb_trace_id, s3 = typeof r4 == \"string\" ? e36.traceConnectionNameById?.get(r4) : undefined;\n if (s3 === undefined)\n return;\n o4.add(s3);\n }\n return o4;\n })(t2, n2);\n if (!r3)\n return;\n if (r3.size === 0)\n for (const e36 of i3 ?? [])\n r3.add(e36);\n if (!r3?.size)\n return;\n const s2 = new Map;\n for (const e36 of o3) {\n if (!r3.has(e36.connectionName))\n continue;\n const t3 = s2.get(e36.connectionName);\n t3 ? t3.push(e36) : s2.set(e36.connectionName, [e36]);\n }\n if (s2.size !== r3.size)\n return;\n const a3 = new Set, c3 = [];\n for (const t3 of e35)\n r3.has(t3.connectionName) ? a3.has(t3.connectionName) || (a3.add(t3.connectionName), c3.push(...s2.get(t3.connectionName))) : c3.push(t3);\n return a3.size === r3.size ? { routes: c3, restoredConnectionCount: a3.size, restoredConnectionNames: a3 } : undefined;\n};\nvar wN = (e35, t2) =\u003e e35.connectionName === t2.connectionName \u0026\u0026 e35.rootConnectionName === t2.rootConnectionName \u0026\u0026 e35.traceThickness === t2.traceThickness \u0026\u0026 e35.route.length === t2.route.length \u0026\u0026 e35.route.every((e36, n2) =\u003e {\n const o3 = t2.route[n2];\n return e36.x === o3.x \u0026\u0026 e36.y === o3.y \u0026\u0026 e36.z === o3.z \u0026\u0026 e36.toNextSegmentType === o3.toNextSegmentType;\n});\nvar NN = (e35, t2, n2) =\u003e {\n if (t2.start.z !== n2.start.z || t2.net === n2.net || t2.bounds.maxX \u003c= n2.bounds.minX || n2.bounds.maxX \u003c= t2.bounds.minX || t2.bounds.maxY \u003c= n2.bounds.minY || n2.bounds.maxY \u003c= t2.bounds.minY)\n return;\n const o3 = t2.connectionName \u003c n2.connectionName ? [t2.connectionName, n2.connectionName] : [n2.connectionName, t2.connectionName], i3 = JSON.stringify(o3);\n if (e35.has(i3))\n return;\n we(t2.start, t2.end, n2.start, n2.end) - t2.radius - n2.radius \u003c -0.000000001 \u0026\u0026 e35.set(i3, o3);\n};\nvar RN = class {\n connectivity;\n inputContacts;\n cellSize;\n constructor({ srj: e35, inputRoutes: t2, connMap: n2 }) {\n this.cellSize = Math.max(1, (e35.bounds.maxX - e35.bounds.minX) / 64, (e35.bounds.maxY - e35.bounds.minY) / 64), this.connectivity = new Nb({}), this.connectivity.addConnections([...Object.entries(n2?.netMap ?? {}).map(([e36, t3]) =\u003e [e36, ...t3]), ...e35.connections.map((e36) =\u003e [e36.name, e36.rootConnectionName, e36.netConnectionName, ...e36.mergedConnectionNames ?? [], ...e36.pointsToConnect.flatMap((e37) =\u003e [e37.pointId, e37.pcb_port_id])].filter((e37) =\u003e typeof e37 == \"string\" \u0026\u0026 e37.length \u003e 0)), ...t2.map((e36) =\u003e [e36.connectionName, e36.rootConnectionName ?? e36.connectionName])]), this.inputContacts = this.collectContacts(t2);\n }\n getNewContactConnectionNames(e35) {\n const t2 = new Set;\n for (const n2 of this.getNewContactPairs(e35))\n t2.add(n2[0]), t2.add(n2[1]);\n return t2;\n }\n getNewContactPairs(e35) {\n return [...this.collectContacts(e35)].filter(([e36]) =\u003e !this.inputContacts.has(e36)).map(([, e36]) =\u003e e36);\n }\n hasContactPair(e35, t2) {\n const n2 = e35.filter((e36) =\u003e e36.connectionName === t2[0] || e36.connectionName === t2[1]);\n return this.collectContacts(n2).has(JSON.stringify(t2));\n }\n preserveClearedContacts(e35) {\n const t2 = this.collectContacts(e35);\n for (const e36 of this.inputContacts.keys())\n t2.has(e36) || this.inputContacts.delete(e36);\n }\n prepareCandidateCheck(e35) {\n const t2 = structuredClone(e35), n2 = this.collectContacts(t2), o3 = [...this.collectSegments(t2).values()].flat(), i3 = MP(o3, (e36) =\u003e e36.bounds, this.cellSize);\n return (e36) =\u003e {\n if (e36.length !== t2.length)\n return this.getNewContactPairs(e36);\n const r3 = new Set;\n for (let n3 = 0;n3 \u003c e36.length; n3++) {\n const o4 = t2[n3], i4 = e36[n3];\n wN(o4, i4) || (r3.add(o4.connectionName), r3.add(i4.connectionName));\n }\n if (r3.size \u003e e36.length / 4)\n return this.getNewContactPairs(e36);\n const s2 = new Map([...n2].filter(([, e37]) =\u003e !r3.has(e37[0]) \u0026\u0026 !r3.has(e37[1]))), a3 = [...this.collectSegments(e36.filter((e37) =\u003e r3.has(e37.connectionName))).values()].flat();\n for (let e37 = 0;e37 \u003c a3.length; e37++) {\n const t3 = a3[e37];\n for (const e38 of wP(i3, t3.bounds, this.cellSize)) {\n const n3 = o3[e38];\n r3.has(n3.connectionName) || NN(s2, t3, n3);\n }\n for (let n3 = e37 + 1;n3 \u003c a3.length; n3++)\n NN(s2, t3, a3[n3]);\n }\n return [...s2].filter(([e37]) =\u003e !this.inputContacts.has(e37)).map(([, e37]) =\u003e e37);\n };\n }\n collectSegments(e35) {\n const t2 = new Map;\n for (const n2 of e35) {\n const e36 = this.connectivity.getNetConnectedToId(n2.connectionName) ?? n2.rootConnectionName ?? n2.connectionName, o3 = n2.traceThickness / 2;\n for (let i3 = 1;i3 \u003c n2.route.length; i3++) {\n const r3 = n2.route[i3 - 1], s2 = n2.route[i3];\n if (r3.z !== s2.z || r3.toNextSegmentType === \"through_obstacle\")\n continue;\n let a3 = t2.get(r3.z);\n a3 || (a3 = [], t2.set(r3.z, a3)), a3.push({ connectionName: n2.connectionName, net: e36, start: r3, end: s2, radius: o3, bounds: { minX: Math.min(r3.x, s2.x) - o3, minY: Math.min(r3.y, s2.y) - o3, maxX: Math.max(r3.x, s2.x) + o3, maxY: Math.max(r3.y, s2.y) + o3 } });\n }\n }\n return t2;\n }\n collectContacts(e35) {\n const t2 = new Map;\n for (const n2 of this.collectSegments(e35).values()) {\n const e36 = MP(n2, (e37) =\u003e e37.bounds, this.cellSize);\n for (let o3 = 0;o3 \u003c n2.length; o3++) {\n const i3 = n2[o3];\n for (const r3 of wP(e36, i3.bounds, this.cellSize))\n r3 \u003c= o3 || NN(t2, i3, n2[r3]);\n }\n }\n return t2;\n }\n};\nvar TN = [0.2, 0.4, 0.8, 1.2].flatMap((e35) =\u003e [0.2, 0.3, 0.45, 0.6].flatMap((t2) =\u003e [-1, 1].map((n2) =\u003e ({ halfSpan: e35, offset: t2, directionSign: n2 })))).flatMap((e35) =\u003e [0, 1].map((t2) =\u003e ({ kind: \"segment\", routeSide: t2, ...e35 })));\nvar EN = [1, -1].flatMap((e35) =\u003e [1, -1].flatMap((t2) =\u003e [false, true].flatMap((n2) =\u003e [0, 1].map((o3) =\u003e ({ routeSide: o3, normalDirectionSign: e35, tangentDirectionSign: t2, reverseEndpointOffsets: n2 })))));\nvar AN = [...[0, 1].map((e35) =\u003e ({ kind: \"displacementChain\", routeSide: e35 })), ...[-1, 1].flatMap((e35) =\u003e [0, 1].map((t2) =\u003e ({ kind: \"segment\", routeSide: t2, halfSpan: 0.4, offset: 1.2, directionSign: e35 }))), ...[-1, 1].flatMap((e35) =\u003e [0, 1].map((t2) =\u003e ({ kind: \"span\", routeSide: t2, spanExpansion: 3, offset: 1.8, directionSign: e35 }))), ...[{ dx: -2.4, dy: -0.4 }, { dx: -2.4, dy: 0.4 }, { dx: 2.4, dy: -0.4 }, { dx: 2.4, dy: 0.4 }, { dx: -0.4, dy: -2.4 }, { dx: -0.4, dy: 2.4 }, { dx: 0.4, dy: -2.4 }, { dx: 0.4, dy: 2.4 }].flatMap((e35) =\u003e [0, 1].map((t2) =\u003e ({ kind: \"waypoint\", routeSide: t2, spanExpansion: 2, ...e35 }))), ...[{ dx: -0.17, dy: 0 }, { dx: 0.17, dy: 0 }, { dx: 0, dy: -0.17 }, { dx: 0, dy: 0.17 }].flatMap((e35) =\u003e [0, 1].map((t2) =\u003e ({ kind: \"waypoint\", routeSide: t2, spanExpansion: 0, ...e35 }))), ...TN];\nvar ON = [0, 1, 2];\nvar kN = class extends BaseSolver {\n srj;\n inputHdRoutes;\n guardedInputHdRoutes;\n connMap;\n effort;\n drcEvaluator;\n referenceDrcEvaluator;\n autoroutingDrcEngine;\n viaHoleDiameter;\n configuredMaxIterations;\n enableBroadFallback;\n enableLargeBoardBroadFallback;\n enableTargetedErrorSweep;\n enablePostSolveClearanceRelaxation;\n enableSafeTraceLayerMoves;\n enableViaInPadLayerMoves;\n enableTraceViaOwnerTargeting;\n deferTraceContactGuard;\n outputHdRoutes;\n deferTraceObstacleOverlapGuard = false;\n initialDrcIssueCount;\n initialRepairDrcIssueCount;\n initialLowCountErrorsHaveMovableTraces = false;\n broadForceAccepted = false;\n targetedForceAccepted = false;\n candidateAttempts = 0;\n viaInPadCandidateAttempts = 0;\n viaInPadCandidatesAccepted = 0;\n padTopologyErrorCursor = 0;\n safeTraceLayerCursorByErrorId = new Map;\n traceLayerCorridorCursorByErrorId = new Map;\n tracePairDetourCursorByErrorId = new Map;\n errorCursor = 0;\n stalledIterations = 0;\n bestDrcIssueCountSeen;\n bestDrcIssueScoreSeen;\n lastDrcCountImprovementCheckIteration = 0;\n drcCountPlateauChecks = 0;\n largeBoardBroadFallbackMisses = 0;\n outputSnapshot;\n overlapSafeCheckpoint;\n traceObstacleRepairRolledBack = false;\n traceObstacleConnectionsRestored = 0;\n traceContactGuard;\n peerTraceRepairRolledBack = false;\n overlapRestorationChecks = 0;\n legacyCleanCheckpoint;\n viaPadRepairRolledBack = false;\n referenceInputDrcIssueCount;\n referenceCandidateDrcIssueCount;\n referenceCandidateRolledBack = false;\n referenceInputSnapshot;\n inputSnapshot;\n constructor(e35) {\n if (super(), this.srj = e35.srj, this.inputHdRoutes = e35.hdRoutes, this.guardedInputHdRoutes = sw(AP(e35.hdRoutes)), this.connMap = e35.connMap, this.effort = e35.effort ?? 1, this.drcEvaluator = e35.drcEvaluator, this.referenceDrcEvaluator = e35.referenceDrcEvaluator, this.autoroutingDrcEngine = e35.autoroutingDrcEngine ?? (e35.drcEvaluator ? undefined : new mb(e35.srj, { connMap: e35.connMap, traceClearance: e35.srj.minTraceToPadEdgeClearance ?? hP.traceClearance, viaClearance: e35.srj.minTraceToPadEdgeClearance ?? hP.viaClearance, includeTraceViaOwnerMetadata: e35.enableTraceViaOwnerTargeting ?? false })), e35.viaHoleDiameter !== undefined \u0026\u0026 (!Number.isFinite(e35.viaHoleDiameter) || e35.viaHoleDiameter \u003c= 0))\n throw new Error(\"viaHoleDiameter must be a positive finite number\");\n this.viaHoleDiameter = e35.viaHoleDiameter, this.configuredMaxIterations = e35.maxIterations, this.enableBroadFallback = e35.enableBroadFallback ?? true, this.enableLargeBoardBroadFallback = e35.enableLargeBoardBroadFallback ?? true, this.enableTargetedErrorSweep = e35.enableTargetedErrorSweep ?? false, this.enablePostSolveClearanceRelaxation = e35.enablePostSolveClearanceRelaxation ?? true, this.enableSafeTraceLayerMoves = e35.enableSafeTraceLayerMoves ?? false, this.enableViaInPadLayerMoves = e35.enableViaInPadLayerMoves ?? false, this.enableTraceViaOwnerTargeting = e35.enableTraceViaOwnerTargeting ?? false, this.deferTraceContactGuard = e35.deferTraceContactGuard ?? false, this.outputHdRoutes = e35.hdRoutes, this.referenceDrcEvaluator \u0026\u0026 (this.referenceInputSnapshot = this.getReferenceDrcSnapshot(this.inputHdRoutes)), this.MAX_ITERATIONS = this.configuredMaxIterations ?? Mb(this.effort);\n }\n getConstructorParams() {\n return [{ srj: this.srj, hdRoutes: this.inputHdRoutes, connMap: this.connMap, effort: this.effort, drcEvaluator: this.drcEvaluator, referenceDrcEvaluator: this.referenceDrcEvaluator, autoroutingDrcEngine: this.autoroutingDrcEngine, viaHoleDiameter: this.viaHoleDiameter, maxIterations: this.configuredMaxIterations, enableBroadFallback: this.enableBroadFallback, enableLargeBoardBroadFallback: this.enableLargeBoardBroadFallback, enableTargetedErrorSweep: this.enableTargetedErrorSweep, enablePostSolveClearanceRelaxation: this.enablePostSolveClearanceRelaxation, enableSafeTraceLayerMoves: this.enableSafeTraceLayerMoves, enableViaInPadLayerMoves: this.enableViaInPadLayerMoves, enableTraceViaOwnerTargeting: this.enableTraceViaOwnerTargeting, deferTraceContactGuard: this.deferTraceContactGuard }];\n }\n updateStats(e35) {\n this.stats = { initialDrcIssueCount: this.initialDrcIssueCount ?? e35.count, finalDrcIssueCount: e35.count, globalDrcForceImproveMaxIterations: this.MAX_ITERATIONS, globalDrcForceImproveBroadForceAccepted: this.broadForceAccepted, globalDrcForceImproveTargetedForceAccepted: this.targetedForceAccepted, globalDrcForceImproveCandidateAttempts: this.candidateAttempts, globalDrcForceImproveViaInPadCandidateAttempts: this.viaInPadCandidateAttempts, globalDrcForceImproveViaInPadCandidatesAccepted: this.viaInPadCandidatesAccepted, globalDrcForceImproveStalledIterations: this.stalledIterations, globalDrcForceImproveBestDrcIssueCountSeen: this.bestDrcIssueCountSeen ?? e35.count, globalDrcForceImproveBestDrcIssueScoreSeen: this.bestDrcIssueScoreSeen ?? e35.issueScore, globalDrcForceImproveDrcCountPlateauChecks: this.drcCountPlateauChecks, globalDrcForceImproveLargeBoardBroadFallbackMisses: this.largeBoardBroadFallbackMisses, globalDrcForceImproveViaPadRepairRolledBack: this.viaPadRepairRolledBack, globalDrcForceImproveTraceObstacleRepairRolledBack: this.traceObstacleRepairRolledBack, globalDrcForceImproveTraceObstacleConnectionsRestored: this.traceObstacleConnectionsRestored, globalDrcForceImprovePeerTraceRepairRolledBack: this.peerTraceRepairRolledBack, globalDrcForceImproveOverlapRestorationChecks: this.overlapRestorationChecks, globalDrcForceImproveReferenceInputDrcIssueCount: this.referenceInputDrcIssueCount, globalDrcForceImproveReferenceCandidateDrcIssueCount: this.referenceCandidateDrcIssueCount, globalDrcForceImproveReferenceCandidateRolledBack: this.referenceCandidateRolledBack };\n }\n finishAtLegacyCleanCheckpoint() {\n const e35 = this.legacyCleanCheckpoint;\n return !!e35 \u0026\u0026 (this.outputHdRoutes = e35.routes, this.outputSnapshot = e35.snapshot, this.viaPadRepairRolledBack = true, this.updateStats(e35.snapshot), this.solved = true, true);\n }\n increaseMaxIterationsForDrcIssueCount(e35) {\n this.configuredMaxIterations === undefined ? this.MAX_ITERATIONS = Math.max(this.MAX_ITERATIONS, ((e36, t2) =\u003e Math.max(Mb(t2), Math.ceil(e36 * yb * Math.max(1, t2))))(e35, this.effort), ((e36, t2) =\u003e e36 \u003e 120 \u0026\u0026 t2 \u003e 0 ? 192 : 48)(this.inputHdRoutes.length, e35)) : this.MAX_ITERATIONS = this.configuredMaxIterations;\n }\n getSnapshot(e35) {\n return (this.initialLowCountErrorsHaveMovableTraces ? VP : HP)(this.srj, e35, this.drcEvaluator, this.connMap, this.autoroutingDrcEngine);\n }\n getReferenceDrcSnapshot(e35) {\n const t2 = { traces: [], srj: this.srj, routes: e35, hdRoutes: e35 }, n2 = this.referenceDrcEvaluator?.getCachedResult?.(t2);\n if (n2) {\n const e36 = Array.isArray(n2) ? n2 : n2.errors;\n return { errors: e36, count: e36.length };\n }\n return HP(this.srj, e35, this.referenceDrcEvaluator, this.connMap, this.autoroutingDrcEngine);\n }\n getViaIssueCount(e35) {\n return hw(e35, false);\n }\n getRepairIssueCount(e35) {\n return gw(e35);\n }\n getRepairIssueScore(e35) {\n return fw(e35);\n }\n getNewPeerContactConnectionNames(e35) {\n return this.deferTraceContactGuard ? new Set : (this.traceContactGuard ??= new RN({ srj: this.srj, inputRoutes: this.guardedInputHdRoutes, connMap: this.connMap }), this.traceContactGuard.getNewContactConnectionNames(e35));\n }\n rememberOverlapSafeRoutes(e35, t2) {\n if (this.deferTraceObstacleOverlapGuard)\n return;\n const n2 = this.overlapSafeCheckpoint;\n n2 \u0026\u0026 !Vw(t2, this.getViaIssueCount(t2), this.getRepairIssueCount(n2.snapshot), this.getRepairIssueScore(n2.snapshot), this.getViaIssueCount(n2.snapshot), n2.snapshot) || this.inputSnapshot \u0026\u0026 xw(t2, this.inputSnapshot) || this.getNewPeerContactConnectionNames(e35).size \u003e 0 || (this.overlapSafeCheckpoint = { routes: sw(AP(e35)), snapshot: t2 });\n }\n acceptSolvedRoutes(e35, t2) {\n this.rememberOverlapSafeRoutes(e35, t2);\n const n2 = this.enablePostSolveClearanceRelaxation ? ((e36, t3, n3) =\u003e {\n if (e36.minTraceToPadEdgeClearance === undefined || e36.minTraceToPadEdgeClearance \u003c= 0)\n return t3;\n let o4 = false;\n const i4 = AP(t3);\n for (let t4 = 0;t4 \u003c 4; t4 += 1)\n for (let t5 = 0;t5 \u003c i4.length; t5 += 1) {\n const r4 = i4[t5];\n if (!r4)\n continue;\n const s3 = mN(e36, i4, r4, t5, n3);\n s3 !== r4 \u0026\u0026 (i4[t5] = s3, o4 = true);\n }\n return o4 ? i4 : t3;\n })(this.srj, e35, this.connMap) : e35, o3 = this.enablePostSolveClearanceRelaxation ? ((e36, t3, n3) =\u003e {\n if (e36.minViaEdgeToPadEdgeClearance === undefined || e36.minViaEdgeToPadEdgeClearance \u003c= 0)\n return t3;\n let o4 = false;\n const i4 = AP(t3);\n for (let t4 = 0;t4 \u003c 4; t4 += 1)\n for (let t5 = 0;t5 \u003c i4.length; t5 += 1) {\n const r4 = i4[t5];\n if (!r4)\n continue;\n const s3 = PN(e36, i4, r4, t5, n3);\n s3 !== r4 \u0026\u0026 (i4[t5] = s3, o4 = true);\n }\n return o4 ? sw(i4) : t3;\n })(this.srj, n2, this.connMap) : e35, i3 = o3 === e35 ? t2 : this.getSnapshot(o3), r3 = i3.count \u003c t2.count || i3.count === t2.count \u0026\u0026 i3.issueScore \u003c= t2.issueScore;\n let s2 = r3 ? o3 : e35, a3 = r3 ? i3 : t2;\n const c3 = this.inputSnapshot ?? this.getSnapshot(this.guardedInputHdRoutes);\n let l3 = this.deferTraceObstacleOverlapGuard ? new Set : this.getNewPeerContactConnectionNames(s2);\n if (!this.deferTraceObstacleOverlapGuard \u0026\u0026 (xw(a3, c3) || l3.size \u003e 0)) {\n this.peerTraceRepairRolledBack = l3.size \u003e 0;\n const e36 = new Set, t3 = l3.size \u003e 0 ? 2 : 1;\n for (let n3 = 0;n3 \u003c t3; n3++) {\n const t4 = MN({ routes: s2, snapshot: a3, inputSnapshot: c3, checkpointRoutes: this.overlapSafeCheckpoint?.routes ?? this.guardedInputHdRoutes, peerConnectionNames: l3 });\n if (!t4)\n break;\n for (const n5 of t4.restoredConnectionNames)\n e36.add(n5);\n const n4 = this.getSnapshot(t4.routes);\n if (this.overlapRestorationChecks++, this.rememberOverlapSafeRoutes(t4.routes, n4), this.overlapSafeCheckpoint?.snapshot === n4) {\n this.traceObstacleConnectionsRestored = e36.size;\n break;\n }\n if (s2 = t4.routes, a3 = n4, l3 = this.getNewPeerContactConnectionNames(s2), !xw(a3, c3) \u0026\u0026 l3.size === 0)\n break;\n }\n s2 = this.overlapSafeCheckpoint?.routes ?? this.guardedInputHdRoutes, a3 = this.overlapSafeCheckpoint?.snapshot ?? c3, this.traceObstacleRepairRolledBack = true;\n }\n if (this.referenceDrcEvaluator) {\n const e36 = this.referenceInputSnapshot, t3 = this.getReferenceDrcSnapshot(s2);\n this.referenceInputDrcIssueCount = e36.count, this.referenceCandidateDrcIssueCount = t3.count, t3.count \u003e e36.count \u0026\u0026 (s2 = this.guardedInputHdRoutes, a3 = c3, this.referenceCandidateRolledBack = true, this.traceObstacleConnectionsRestored = 0);\n }\n this.outputHdRoutes = s2, this.outputSnapshot = a3, this.stalledIterations = 0, this.updateStats(a3), this.solved = true;\n }\n updateDrcCountPlateauState(e35) {\n const t2 = this.getRepairIssueCount(e35), n2 = this.getRepairIssueScore(e35);\n this.bestDrcIssueCountSeen ??= t2, this.bestDrcIssueScoreSeen ??= n2;\n const o3 = this.initialRepairDrcIssueCount ?? t2, i3 = this.inputHdRoutes.length \u003e 120 \u0026\u0026 o3 \u003e 0;\n if ((o3 \u003e= 20 || i3) \u0026\u0026 this.iterations \u003c 192)\n return (t2 \u003c this.bestDrcIssueCountSeen || t2 === this.bestDrcIssueCountSeen \u0026\u0026 n2 \u003c this.bestDrcIssueScoreSeen) \u0026\u0026 (this.bestDrcIssueCountSeen = t2, this.bestDrcIssueScoreSeen = n2), void (i3 \u0026\u0026 this.largeBoardBroadFallbackMisses \u003e= 2 \u0026\u0026 (this.solved = true));\n const r3 = ((e36) =\u003e e36 \u003e= 20 ? 8 : e36 \u003c= 2 ? 1 : 2)(o3);\n if (!(this.iterations - this.lastDrcCountImprovementCheckIteration \u003c r3)) {\n if (this.lastDrcCountImprovementCheckIteration = this.iterations, t2 \u003c this.bestDrcIssueCountSeen || t2 === this.bestDrcIssueCountSeen \u0026\u0026 n2 \u003c this.bestDrcIssueScoreSeen)\n return this.bestDrcIssueCountSeen = t2, this.bestDrcIssueScoreSeen = n2, void (this.drcCountPlateauChecks = 0);\n this.drcCountPlateauChecks += 1, this.drcCountPlateauChecks \u003e= 2 \u0026\u0026 (this.solved = true);\n }\n }\n _step() {\n let e35 = this.outputHdRoutes, t2 = this.outputSnapshot ?? this.getSnapshot(e35);\n const n2 = mw(t2);\n if (this.legacyCleanCheckpoint \u0026\u0026 n2 \u003e 0)\n return void this.finishAtLegacyCleanCheckpoint();\n if (this.legacyCleanCheckpoint || n2 !== 0 || !t2.errors.some(uw) || !this.deferTraceObstacleOverlapGuard \u0026\u0026 (this.getNewPeerContactConnectionNames(e35).size !== 0 || this.inputSnapshot \u0026\u0026 xw(t2, this.inputSnapshot)) || (this.legacyCleanCheckpoint = { routes: sw(AP(e35)), snapshot: t2 }), this.initialDrcIssueCount === undefined) {\n this.inputSnapshot = t2, this.initialDrcIssueCount = t2.count, this.initialRepairDrcIssueCount = this.getRepairIssueCount(t2);\n const n3 = Iw(t2.errors);\n this.initialLowCountErrorsHaveMovableTraces = this.initialRepairDrcIssueCount \u003e 0 \u0026\u0026 this.initialRepairDrcIssueCount \u003c= 3 \u0026\u0026 n3.every((e36) =\u003e Sw(e36, t2.traceRouteIndexById) !== undefined), this.initialLowCountErrorsHaveMovableTraces \u0026\u0026 (t2 = this.getSnapshot(e35)), this.bestDrcIssueCountSeen = this.getRepairIssueCount(t2), this.bestDrcIssueScoreSeen = this.getRepairIssueScore(t2), this.increaseMaxIterationsForDrcIssueCount(this.getRepairIssueCount(t2));\n }\n if (this.rememberOverlapSafeRoutes(e35, t2), t2.count === 0)\n return void this.acceptSolvedRoutes(e35, t2);\n let o3 = this.getRepairIssueCount(t2), i3 = this.getRepairIssueScore(t2), r3 = this.getViaIssueCount(t2);\n const s2 = t2.errors.filter((e36) =\u003e Boolean(lw(e36)));\n if (s2.length === 0)\n return void this.acceptSolvedRoutes(e35, t2);\n const a3 = (c3 = this.effort, Math.max(1, Math.round(3 * Math.max(1, c3))));\n var c3;\n let l3 = 0, h2 = 0, d2 = false, u2 = false, p3 = false;\n const m2 = Iw(s2), g2 = this.enableTargetedErrorSweep ? m2.find((e36) =\u003e e36.type === \"pcb_via_clearance_error\" \u0026\u0026 e36.pcb_via_pair_net_relation === \"same_net\") : undefined, f2 = this.enableTargetedErrorSweep \u0026\u0026 (this.iterations - 1) % 8 == 0, _2 = g2 ?? (f2 ? m2.find((e36) =\u003e e36.type === \"pcb_via_clearance_error\") : undefined), y2 = _2 ? [_2, ...m2.filter((e36) =\u003e e36 !== _2)] : m2, b2 = Math.min(y2.length, Math.max(1, Math.ceil(this.effort))), x2 = _2 ? 0 : this.errorCursor % y2.length, v2 = this.enableTargetedErrorSweep ? ((e36, t3) =\u003e {\n const n3 = Math.max(2, Math.round(12 * Math.max(1, t3)));\n return e36.filter((e37) =\u003e LP(e37) === \"pcb_trace_error\").slice(0, n3);\n })(s2, this.effort) : [], I2 = o3 \u003c= 1 || this.initialLowCountErrorsHaveMovableTraces, S2 = !this.initialLowCountErrorsHaveMovableTraces \u0026\u0026 o3 \u003c= 8 \u0026\u0026 this.srj.layerCount \u003e 1, C = _2 ? [] : s2.filter((e36) =\u003e e36.type === \"pcb_pad_trace_clearance_error\" || (this.enableSafeTraceLayerMoves || I2 || S2) \u0026\u0026 e36.type === \"pcb_trace_error\"), P = C.map((e36, t3) =\u003e C[(this.padTopologyErrorCursor + t3) % C.length]);\n for (const n3 of this.enableSafeTraceLayerMoves || this.enableViaInPadLayerMoves ? P : []) {\n const s3 = !this.enableSafeTraceLayerMoves || h2 \u003e= a3, c4 = !this.enableViaInPadLayerMoves || l3 \u003e= a3;\n if (u2 || s3 \u0026\u0026 c4)\n break;\n let p4;\n this.padTopologyErrorCursor = (C.indexOf(n3) + 1) % C.length;\n const m3 = typeof n3.pcb_trace_error_id == \"string\" ? n3.pcb_trace_error_id : typeof n3.pcb_trace_id == \"string\" ? n3.pcb_trace_id : undefined, g3 = Sw(n3, t2.traceRouteIndexById), f3 = kw(n3, t2.traceRouteIndexById);\n if (this.enableSafeTraceLayerMoves \u0026\u0026 g3 !== undefined) {\n const o4 = f3 ?? [g3], i4 = o4.length * this.srj.layerCount * ON.length, s4 = o4.length * this.srj.layerCount * ww, c5 = i4 + s4, l4 = zP(n3), d3 = l4 ? 0 : i4, u3 = l4 ? s4 : 0;\n let _4 = m3 ? this.safeTraceLayerCursorByErrorId.get(m3) ?? 0 : 0, y3 = 0;\n for (;h2 \u003c a3 \u0026\u0026 y3 \u003c c5; ) {\n const i5 = _4;\n _4 = (_4 + 1) % c5, y3 += 1;\n const a4 = i5 \u003e= d3 \u0026\u0026 i5 \u003c d3 + s4, l5 = i5 - (a4 ? d3 : u3), m4 = l5 % o4.length, g4 = Math.floor(l5 / o4.length), f4 = g4 % this.srj.layerCount, b3 = a4 ? \"full\" : ON[Math.floor(g4 / this.srj.layerCount) % ON.length], x3 = a4 ? Math.floor(g4 / this.srj.layerCount) : 0, v3 = o4[m4], I3 = OP(e35, [v3]);\n if (!Ew(this.srj, I3, n3, v3, f4, b3, this.connMap, x3))\n continue;\n const S3 = aw(I3, [v3]);\n h2 += 1, this.candidateAttempts += 1;\n const C2 = this.getSnapshot(S3), P2 = this.getViaIssueCount(C2), M2 = p4?.snapshot ?? t2;\n P2 \u003c= (p4?.viaIssueCount ?? r3) \u0026\u0026 vw(C2, M2) \u0026\u0026 (p4 = { routes: S3, snapshot: C2, viaIssueCount: P2, usesViaInPad: false });\n }\n m3 \u0026\u0026 this.safeTraceLayerCursorByErrorId.set(m3, _4);\n }\n if (this.enableSafeTraceLayerMoves \u0026\u0026 S2 \u0026\u0026 m3 \u0026\u0026 f3) {\n let o4 = this.traceLayerCorridorCursorByErrorId.get(m3) ?? 0, i4 = 0;\n for (;l3 \u003c a3 \u0026\u0026 i4 \u003c EN.length; ) {\n const s4 = EN[o4 % EN.length];\n o4 += 1, i4 += 1;\n const a4 = f3[s4.routeSide], c5 = e35[a4]?.route[0]?.z;\n if (c5 === undefined)\n continue;\n const h3 = (c5 + 1) % this.srj.layerCount, d3 = OP(e35, [a4]);\n if (!Yw(this.srj, d3, n3, a4, h3, s4.normalDirectionSign, s4.tangentDirectionSign, s4.reverseEndpointOffsets))\n continue;\n const u3 = aw(d3, [a4]);\n l3 += 1, this.candidateAttempts += 1;\n const m4 = this.getSnapshot(u3), g4 = this.getViaIssueCount(m4), _4 = p4?.snapshot ?? t2;\n g4 \u003c= (p4?.viaIssueCount ?? r3) \u0026\u0026 vw(m4, _4) \u0026\u0026 (p4 = { routes: u3, snapshot: m4, viaIssueCount: g4, usesViaInPad: false });\n }\n this.traceLayerCorridorCursorByErrorId.set(m3, o4);\n }\n if (this.enableSafeTraceLayerMoves \u0026\u0026 I2 \u0026\u0026 m3 \u0026\u0026 (this.initialLowCountErrorsHaveMovableTraces \u0026\u0026 (f3 || g3 !== undefined) || !this.initialLowCountErrorsHaveMovableTraces \u0026\u0026 f3)) {\n const s4 = this.initialLowCountErrorsHaveMovableTraces ? AN : TN, c5 = f3 ?? [g3];\n let h3 = this.tracePairDetourCursorByErrorId.get(m3) ?? 0, u3 = 0;\n for (;l3 \u003c a3 \u0026\u0026 u3 \u003c s4.length; ) {\n const m4 = s4[h3 % s4.length];\n h3 += 1, u3 += 1;\n const g4 = c5[m4.routeSide];\n if (g4 === undefined)\n continue;\n const f4 = this.initialLowCountErrorsHaveMovableTraces \u0026\u0026 n3.worst_contact_center ? { ...n3, center: n3.worst_contact_center, message: n3.worst_contact_message ?? n3.message, actual_clearance: n3.worst_actual_clearance ?? n3.actual_clearance } : n3;\n if (m4.kind === \"displacementChain\") {\n const n4 = AP(e35), s5 = Dw(this.srj, n4, f4, t2.traceRouteIndexById, m4.routeSide);\n if (!s5)\n continue;\n d2 = true, l3 += 1, this.candidateAttempts += 1;\n let c6 = sw(n4), h4 = this.getSnapshot(c6), u4 = this.getViaIssueCount(h4), g5 = this.getRepairIssueCount(h4);\n if (g5 \u003e 0 \u0026\u0026 g5 \u003c= 3 \u0026\u0026 l3 \u003c a3) {\n const e36 = AP(c6);\n let t3 = false;\n for (const n5 of h4.errors)\n t3 = zw(this.srj, e36, n5, h4.traceRouteIndexById, s5.movedRouteIndex, this.connMap) || t3;\n if (t3) {\n l3 += 1, this.candidateAttempts += 1;\n const t4 = sw(e36), n5 = this.getSnapshot(t4), o4 = this.getViaIssueCount(n5);\n Vw(n5, o4, g5, this.getRepairIssueScore(h4), u4, h4) \u0026\u0026 (c6 = t4, h4 = n5, u4 = o4, g5 = this.getRepairIssueCount(h4));\n }\n }\n const _5 = p4 ? this.getRepairIssueCount(p4.snapshot) : o3, y4 = p4 ? this.getRepairIssueScore(p4.snapshot) : i3;\n if (Vw(h4, u4, _5, y4, p4?.viaIssueCount ?? r3, p4?.snapshot ?? t2) \u0026\u0026 (p4 = { routes: c6, snapshot: h4, viaIssueCount: u4, usesViaInPad: false }), g5 === 0)\n break;\n continue;\n }\n const _4 = OP(e35, [g4]);\n if (!(m4.kind === \"segment\" ? $w(_4, f4, g4, m4.halfSpan, m4.offset, m4.directionSign) : m4.kind === \"span\" ? Xw(this.srj, _4, f4, g4, m4.spanExpansion, m4.offset, m4.directionSign) : Hw(this.srj, _4, f4, g4, m4.spanExpansion, { x: f4.center.x + m4.dx, y: f4.center.y + m4.dy })))\n continue;\n const y3 = aw(_4, [g4]);\n d2 = true, l3 += 1, this.candidateAttempts += 1;\n const b3 = this.getSnapshot(y3), x3 = this.getViaIssueCount(b3), v3 = p4 ? this.getRepairIssueCount(p4.snapshot) : o3, I3 = p4 ? this.getRepairIssueScore(p4.snapshot) : i3, S3 = p4?.viaIssueCount ?? r3;\n (this.initialLowCountErrorsHaveMovableTraces ? Vw(b3, x3, v3, I3, S3, p4?.snapshot ?? t2) : x3 \u003c= S3 \u0026\u0026 vw(b3, p4?.snapshot ?? t2)) \u0026\u0026 (p4 = { routes: y3, snapshot: b3, viaIssueCount: x3, usesViaInPad: false });\n }\n this.tracePairDetourCursorByErrorId.set(m3, h3);\n }\n for (const s4 of this.enableViaInPadLayerMoves ? [\"start\", \"end\"] : []) {\n if (l3 \u003e= a3)\n break;\n if (g3 === undefined)\n break;\n const c5 = OP(e35, [g3]);\n if (!Ow(this.srj, c5, n3, t2.traceRouteIndexById, s4, this.connMap, this.viaHoleDiameter))\n continue;\n const h3 = aw(c5, [g3]);\n this.viaInPadCandidateAttempts += 1, l3 += 1, this.candidateAttempts += 1;\n const d3 = this.getSnapshot(h3), u3 = this.getViaIssueCount(d3), m4 = p4 ? this.getRepairIssueCount(p4.snapshot) : o3, f4 = p4 ? this.getRepairIssueScore(p4.snapshot) : i3;\n Vw(d3, u3, m4, f4, p4?.viaIssueCount ?? r3, p4?.snapshot ?? t2) \u0026\u0026 (p4 = { routes: h3, snapshot: d3, viaIssueCount: u3, usesViaInPad: true });\n }\n const _3 = this.enableViaInPadLayerMoves ? this.srj.layerCount : 0;\n for (let s4 = 0;s4 \u003c _3 \u0026\u0026 !(l3 \u003e= a3) \u0026\u0026 g3 !== undefined; s4 += 1) {\n const a4 = OP(e35, [g3]);\n if (!Aw(this.srj, a4, n3, t2.traceRouteIndexById, s4, this.connMap, this.viaHoleDiameter))\n continue;\n const c5 = aw(a4, [g3]);\n this.viaInPadCandidateAttempts += 1, l3 += 1, this.candidateAttempts += 1;\n const h3 = this.getSnapshot(c5), d3 = this.getViaIssueCount(h3), u3 = p4 ? this.getRepairIssueCount(p4.snapshot) : o3, m4 = p4 ? this.getRepairIssueScore(p4.snapshot) : i3;\n Vw(h3, d3, u3, m4, p4?.viaIssueCount ?? r3, p4?.snapshot ?? t2) \u0026\u0026 (p4 = { routes: c5, snapshot: h3, viaIssueCount: d3, usesViaInPad: true });\n }\n if (this.enableViaInPadLayerMoves \u0026\u0026 I2 \u0026\u0026 f3) {\n const s4 = this.iterations % 2 == 0 ? [0, 1] : [1, 0], c5 = this.iterations % 3;\n for (const h3 of s4)\n for (let s5 = 0;s5 \u003c this.srj.layerCount \u0026\u0026 !(l3 \u003e= a3); s5 += 1) {\n const a4 = f3[h3], d3 = OP(e35, [a4]);\n if (!jw(this.srj, d3, n3, t2.traceRouteIndexById, h3, s5, c5, this.connMap, this.viaHoleDiameter))\n continue;\n const u3 = aw(d3, [a4]);\n this.viaInPadCandidateAttempts += 1, l3 += 1, this.candidateAttempts += 1;\n const m4 = this.getSnapshot(u3), g4 = this.getViaIssueCount(m4), _4 = p4 ? this.getRepairIssueCount(p4.snapshot) : o3, y3 = p4 ? this.getRepairIssueScore(p4.snapshot) : i3;\n Vw(m4, g4, _4, y3, p4?.viaIssueCount ?? r3, p4?.snapshot ?? t2) \u0026\u0026 (p4 = { routes: u3, snapshot: m4, viaIssueCount: g4, usesViaInPad: true });\n }\n }\n p4 \u0026\u0026 (e35 = p4.routes, t2 = p4.snapshot, o3 = this.getRepairIssueCount(t2), i3 = this.getRepairIssueScore(t2), r3 = p4.viaIssueCount, this.targetedForceAccepted = true, p4.usesViaInPad \u0026\u0026 (this.viaInPadCandidatesAccepted += 1), u2 = true);\n }\n if (!u2 \u0026\u0026 v2.length \u003e= 2) {\n const n3 = AP(e35);\n let s3 = false;\n for (const e36 of v2)\n s3 = Ww(this.srj, n3, [e36], t2.traceRouteIndexById, 1, this.connMap, true, this.enableTargetedErrorSweep, false, this.enableTraceViaOwnerTargeting) || s3;\n if (s3) {\n const s4 = sw(n3);\n l3 += 1, this.candidateAttempts += 1;\n const a4 = this.getSnapshot(s4), c4 = this.getViaIssueCount(a4);\n if (Vw(a4, c4, o3, i3, r3, t2) \u0026\u0026 (e35 = s4, t2 = a4, o3 = this.getRepairIssueCount(a4), i3 = this.getRepairIssueScore(a4), r3 = c4, this.targetedForceAccepted = true, u2 = true, a4.count === 0))\n return void this.acceptSolvedRoutes(e35, t2);\n }\n }\n for (let n3 = 0;n3 \u003c b2 \u0026\u0026 l3 \u003c a3 \u0026\u0026 !u2; n3 += 1) {\n const s3 = (x2 + n3) % y2.length, c4 = y2[s3];\n if (!c4)\n continue;\n this.errorCursor = (s3 + 1) % y2.length;\n const h3 = o3 === 1;\n for (const n4 of wb(this.effort)) {\n if (l3 \u003e= a3)\n break;\n const s4 = AP(e35);\n if (!Ww(this.srj, s4, [c4], t2.traceRouteIndexById, n4, this.connMap, true, this.enableTargetedErrorSweep, h3, this.enableTraceViaOwnerTargeting))\n continue;\n const d3 = sw(s4);\n l3 += 1, this.candidateAttempts += 1;\n const p4 = this.getSnapshot(d3), m3 = this.getViaIssueCount(p4);\n if (Vw(p4, m3, o3, i3, r3, t2)) {\n if (e35 = d3, t2 = p4, o3 = this.getRepairIssueCount(p4), i3 = this.getRepairIssueScore(p4), r3 = m3, this.targetedForceAccepted = true, u2 = true, p4.count === 0)\n return void this.acceptSolvedRoutes(e35, t2);\n break;\n }\n }\n if (u2)\n break;\n }\n const M = e35.length \u003c= 120, w = (N = s2.length, Math.max(16, Math.min(64, 2 * N)));\n var N;\n const R2 = this.enableLargeBoardBroadFallback \u0026\u0026 this.MAX_ITERATIONS \u003e= 192 \u0026\u0026 !M \u0026\u0026 this.stalledIterations \u003e 0 \u0026\u0026 this.stalledIterations % w === 0;\n if (this.enableBroadFallback \u0026\u0026 !u2 \u0026\u0026 (M || this.effort \u003e= 2 \u0026\u0026 this.stalledIterations \u003e= 2 || R2)) {\n p3 = R2;\n for (const n3 of [1, 2]) {\n const s3 = ow(this.srj, e35, this.effort, n3, this.connMap, this.drcEvaluator === undefined, false);\n if (s3 === e35)\n continue;\n const a4 = this.getSnapshot(s3), c4 = this.getViaIssueCount(a4);\n if (Vw(a4, c4, o3, i3, r3, t2) \u0026\u0026 (e35 = s3, t2 = a4, o3 = this.getRepairIssueCount(a4), i3 = this.getRepairIssueScore(a4), r3 = c4, this.broadForceAccepted = true, u2 = true, a4.count === 0))\n return void this.acceptSolvedRoutes(e35, t2);\n }\n }\n u2 ? this.largeBoardBroadFallbackMisses = 0 : p3 \u0026\u0026 (this.largeBoardBroadFallbackMisses += 1), this.outputHdRoutes = e35, this.outputSnapshot = t2, this.stalledIterations = u2 ? 0 : this.stalledIterations + 1, d2 || this.updateDrcCountPlateauState(t2), this.updateStats(t2), (this.solved || o3 === 0) \u0026\u0026 this.acceptSolvedRoutes(e35, t2);\n }\n tryFinalAcceptance() {\n const e35 = this.outputSnapshot ?? this.getSnapshot(this.outputHdRoutes);\n this.legacyCleanCheckpoint \u0026\u0026 mw(e35) \u003e 0 \u0026\u0026 this.finishAtLegacyCleanCheckpoint() || this.acceptSolvedRoutes(this.outputHdRoutes, e35);\n }\n getOutput() {\n return this.outputHdRoutes;\n }\n visualize() {\n return super.visualize();\n }\n preview() {\n return this.visualize();\n }\n};\nvar DN = class extends kN {\n deferTraceObstacleOverlapGuard = true;\n};\nvar LN = class extends BaseSolver {\n params;\n inputHdRoutes;\n guardedInputHdRoutes;\n broadMaxIterations;\n broadPassMultiplier;\n autoroutingDrcEngine;\n legacyDrcEvaluator;\n outputHdRoutes;\n phase = \"start\";\n inputSnapshot;\n baselineSolver;\n baselineSnapshot;\n broadInputSnapshot;\n broadSnapshot;\n broadSolver;\n preBroadCandidate;\n safeTraceLayerInputRoutes;\n safeTraceLayerInputSnapshot;\n safeTraceLayerSolver;\n safeTraceLayerPhaseAccepted = false;\n mixedSafeTraceLayerSolver;\n mixedSafeTraceLayerPhaseAccepted = false;\n legacySafeTraceLayerRoutes;\n legacySafeTraceLayerSnapshot;\n legacySafeTraceLayerSelectedSolver;\n viaInPadSolver;\n portfolioSelectedSolver;\n outputVisualizationSolver;\n overlapSafeCheckpoint;\n traceObstacleRepairRolledBack = false;\n traceObstacleConnectionsRestored = 0;\n traceContactGuard;\n peerTraceRepairRolledBack = false;\n overlapRestorationChecks = 0;\n stoppedForTraceContacts = false;\n referenceInputDrcIssueCount;\n referenceCandidateDrcIssueCount;\n referenceCandidateRolledBack = false;\n mixedReferenceInputDrcIssueCount;\n mixedReferenceCandidateDrcIssueCount;\n referenceInputSnapshot;\n constructor(e35) {\n if (super(), !Number.isFinite(e35.broadPassMultiplier))\n throw new Error(\"broadPassMultiplier must be a finite number\");\n if (e35.broadPassMultiplier \u003c= 0)\n throw new Error(\"broadPassMultiplier must be greater than zero\");\n if (!Number.isInteger(e35.broadMaxIterations))\n throw new Error(\"broadMaxIterations must be an integer\");\n if (e35.broadMaxIterations \u003c= 0)\n throw new Error(\"broadMaxIterations must be greater than zero\");\n if (e35.viaInPadMaxIterations !== undefined \u0026\u0026 !Number.isInteger(e35.viaInPadMaxIterations))\n throw new Error(\"viaInPadMaxIterations must be an integer\");\n if (e35.viaInPadMaxIterations !== undefined \u0026\u0026 e35.viaInPadMaxIterations \u003c= 0)\n throw new Error(\"viaInPadMaxIterations must be greater than zero\");\n this.autoroutingDrcEngine = e35.autoroutingDrcEngine ?? (e35.drcEvaluator ? undefined : new mb(e35.srj, { connMap: e35.connMap, traceClearance: e35.srj.minTraceToPadEdgeClearance ?? hP.traceClearance, viaClearance: e35.srj.minTraceToPadEdgeClearance ?? hP.viaClearance, includeTraceViaOwnerMetadata: e35.enableTraceViaOwnerTargeting ?? false })), this.legacyDrcEvaluator = (t2) =\u003e {\n const n2 = e35.drcEvaluator?.evaluateLegacy ?? e35.drcEvaluator, o3 = n2 ? n2(t2) : this.autoroutingDrcEngine.evaluateLegacy(t2.traces), i3 = Array.isArray(o3) ? o3 : o3.errors, r3 = Array.isArray(o3) ? o3 : o3.errorsWithCenters ?? o3.errors;\n return { errors: i3.filter((e36) =\u003e !uw(e36)), errorsWithCenters: r3.filter((e36) =\u003e !uw(e36)) };\n }, Object.defineProperty(this.legacyDrcEvaluator, \"inputMode\", { get: () =\u003e (e35.drcEvaluator?.evaluateLegacy ?? e35.drcEvaluator)?.inputMode }), this.params = { ...e35, autoroutingDrcEngine: this.autoroutingDrcEngine }, this.inputHdRoutes = e35.hdRoutes, this.guardedInputHdRoutes = sw(AP(e35.hdRoutes)), this.broadMaxIterations = e35.broadMaxIterations, this.broadPassMultiplier = e35.broadPassMultiplier, this.outputHdRoutes = e35.hdRoutes, this.params.referenceDrcEvaluator \u0026\u0026 (this.referenceInputSnapshot = this.getReferenceDrcSnapshot(this.inputHdRoutes));\n }\n getConstructorParams() {\n return [{ ...this.params, hdRoutes: this.inputHdRoutes }];\n }\n stepBranch(e35, t2) {\n if (this.activeSubSolver = e35, e35.step(), e35.failed)\n throw new Error(`${t2} DRC repair branch failed: ${e35.error}`);\n }\n getReferenceDrcSnapshot(e35) {\n const t2 = { traces: [], srj: this.params.srj, routes: e35, hdRoutes: e35 }, n2 = this.params.referenceDrcEvaluator?.getCachedResult?.(t2);\n if (n2) {\n const e36 = Array.isArray(n2) ? n2 : n2.errors;\n return { errors: e36, count: e36.length };\n }\n return HP(this.params.srj, e35, this.params.referenceDrcEvaluator, this.params.connMap, this.autoroutingDrcEngine);\n }\n getNewPeerContactConnectionNames(e35) {\n return this.params.deferTraceContactGuard ? new Set : (this.traceContactGuard ??= new RN({ srj: this.params.srj, inputRoutes: this.guardedInputHdRoutes, connMap: this.params.connMap }), this.traceContactGuard.getNewContactConnectionNames(e35));\n }\n rememberOverlapSafeCandidate({ routes: e35, snapshot: t2, solver: n2, safeTraceLayerPhaseAccepted: o3 }) {\n this.overlapSafeCheckpoint \u0026\u0026 !vw(t2, this.overlapSafeCheckpoint.snapshot) || xw(t2, this.inputSnapshot) || this.getNewPeerContactConnectionNames(e35).size \u003e 0 || (this.overlapSafeCheckpoint = { routes: sw(AP(e35)), snapshot: t2, solver: n2, safeTraceLayerPhaseAccepted: o3 });\n }\n finishWithOutput(e35, t2, n2) {\n let o3 = e35, i3 = t2;\n this.rememberOverlapSafeCandidate({ routes: e35, snapshot: t2, solver: n2, safeTraceLayerPhaseAccepted: this.safeTraceLayerPhaseAccepted });\n let r3 = this.getNewPeerContactConnectionNames(e35);\n if (xw(t2, this.inputSnapshot) || r3.size \u003e 0) {\n this.peerTraceRepairRolledBack = r3.size \u003e 0;\n const e36 = new Set, t3 = r3.size \u003e 0 ? 2 : 1;\n for (let s3 = 0;s3 \u003c t3; s3++) {\n const t4 = MN({ routes: o3, snapshot: i3, inputSnapshot: this.inputSnapshot, checkpointRoutes: this.overlapSafeCheckpoint.routes, peerConnectionNames: r3 });\n if (!t4)\n break;\n for (const n3 of t4.restoredConnectionNames)\n e36.add(n3);\n const s4 = HP(this.params.srj, t4.routes, this.phase === \"viaInPad\" ? this.params.viaInPadDrcEvaluator ?? this.params.drcEvaluator : this.params.drcEvaluator, this.params.connMap, this.autoroutingDrcEngine);\n if (this.overlapRestorationChecks++, this.rememberOverlapSafeCandidate({ routes: t4.routes, snapshot: s4, solver: n2, safeTraceLayerPhaseAccepted: this.safeTraceLayerPhaseAccepted }), this.overlapSafeCheckpoint.snapshot === s4) {\n this.traceObstacleConnectionsRestored = e36.size;\n break;\n }\n if (o3 = t4.routes, i3 = s4, r3 = this.getNewPeerContactConnectionNames(o3), !xw(i3, this.inputSnapshot) \u0026\u0026 r3.size === 0)\n break;\n }\n const s2 = this.overlapSafeCheckpoint;\n o3 = s2.routes, i3 = s2.snapshot, n2 = s2.solver, this.portfolioSelectedSolver = s2.solver, this.safeTraceLayerPhaseAccepted = s2.safeTraceLayerPhaseAccepted, this.mixedSafeTraceLayerPhaseAccepted = s2.solver !== undefined \u0026\u0026 s2.solver === this.mixedSafeTraceLayerSolver, this.traceObstacleRepairRolledBack = true;\n }\n if (this.params.referenceDrcEvaluator) {\n const e36 = this.referenceInputSnapshot, t3 = this.getReferenceDrcSnapshot(o3);\n this.referenceInputDrcIssueCount = e36.count, this.referenceCandidateDrcIssueCount = t3.count, (t3.count \u003e e36.count || t3.count === e36.count \u0026\u0026 ((e37, t4) =\u003e {\n const n3 = new Set(t4.map(pw));\n return e37.some((e38) =\u003e !n3.has(pw(e38)));\n })(t3.errors, e36.errors)) \u0026\u0026 (o3 = this.guardedInputHdRoutes, i3 = this.inputSnapshot, this.referenceCandidateRolledBack = true, this.traceObstacleConnectionsRestored = 0);\n }\n this.outputHdRoutes = o3, this.activeSubSolver = null, this.phase = \"done\", this.progress = 1, this.stats = { ...this.portfolioSelectedSolver?.stats ?? {}, ...n2?.stats ?? {}, finalDrcIssueCount: i3.count, drcBranchPortfolioInitialDrcIssueCount: this.inputSnapshot?.count ?? t2.count, drcBranchPortfolioBaselineDrcIssueCount: this.baselineSnapshot?.count ?? t2.count, drcBranchPortfolioBroadInitialDrcIssueCount: this.broadInputSnapshot?.count, drcBranchPortfolioBroadFinalDrcIssueCount: this.broadSnapshot?.count, drcBranchPortfolioBroadMaxIterations: this.broadMaxIterations, drcBranchPortfolioBroadBranchAttempted: Boolean(this.broadSolver), drcBranchPortfolioBroadBranchAccepted: this.portfolioSelectedSolver !== undefined \u0026\u0026 this.portfolioSelectedSolver === this.broadSolver, drcBranchPortfolioSafeTraceLayerPhaseAttempted: Boolean(this.safeTraceLayerSolver), drcBranchPortfolioSafeTraceLayerPhaseAccepted: this.safeTraceLayerPhaseAccepted, drcBranchPortfolioMixedSafeTraceLayerPhaseAttempted: Boolean(this.mixedSafeTraceLayerSolver), drcBranchPortfolioMixedSafeTraceLayerPhaseAccepted: this.mixedSafeTraceLayerPhaseAccepted, drcBranchPortfolioViaInPadPhaseAttempted: Boolean(this.viaInPadSolver), drcBranchPortfolioViaInPadMaxIterations: this.params.viaInPadMaxIterations, drcBranchPortfolioFinalNonViaPadDrcIssueCount: mw(i3), drcBranchPortfolioReferenceInputDrcIssueCount: this.referenceInputDrcIssueCount, drcBranchPortfolioReferenceCandidateDrcIssueCount: this.referenceCandidateDrcIssueCount, drcBranchPortfolioReferenceCandidateRolledBack: this.referenceCandidateRolledBack, drcBranchPortfolioTraceObstacleRepairRolledBack: this.traceObstacleRepairRolledBack, drcBranchPortfolioTraceObstacleConnectionsRestored: this.traceObstacleConnectionsRestored, drcBranchPortfolioPeerTraceRepairRolledBack: this.peerTraceRepairRolledBack, drcBranchPortfolioOverlapRestorationChecks: this.overlapRestorationChecks, drcBranchPortfolioStoppedForTraceContacts: this.stoppedForTraceContacts, drcBranchPortfolioMixedReferenceInputDrcIssueCount: this.mixedReferenceInputDrcIssueCount, drcBranchPortfolioMixedReferenceCandidateDrcIssueCount: this.mixedReferenceCandidateDrcIssueCount }, this.solved = true;\n }\n startBaselineBranch() {\n this.baselineSolver = new DN({ ...this.params, hdRoutes: this.inputHdRoutes, drcEvaluator: this.legacyDrcEvaluator, referenceDrcEvaluator: undefined, enableSafeTraceLayerMoves: false, enableViaInPadLayerMoves: false }), this.activeSubSolver = this.baselineSolver, this.phase = \"baseline\";\n }\n startSafeTraceLayerPhase(e35, t2, n2) {\n this.portfolioSelectedSolver = n2, this.rememberOverlapSafeCandidate({ routes: e35, snapshot: t2, solver: n2, safeTraceLayerPhaseAccepted: false }), this.params.enableSafeTraceLayerMoves ? (this.safeTraceLayerInputRoutes = e35, this.safeTraceLayerInputSnapshot = t2, this.safeTraceLayerSolver = new DN({ ...this.params, hdRoutes: e35, drcEvaluator: this.legacyDrcEvaluator, referenceDrcEvaluator: undefined, maxIterations: this.params.viaInPadMaxIterations ?? this.params.maxIterations, enableLargeBoardBroadFallback: false, enableTargetedErrorSweep: false, enablePostSolveClearanceRelaxation: false, enableSafeTraceLayerMoves: true, enableViaInPadLayerMoves: false }), this.activeSubSolver = this.safeTraceLayerSolver, this.phase = \"safeTraceLayer\") : this.startViaInPadPhase(e35, t2, n2);\n }\n startViaInPadPhase(e35, t2, n2) {\n this.portfolioSelectedSolver = n2, this.rememberOverlapSafeCandidate({ routes: e35, snapshot: t2, solver: n2, safeTraceLayerPhaseAccepted: this.safeTraceLayerPhaseAccepted });\n const o3 = this.params.enableViaInPadLayerMoves \u0026\u0026 this.params.viaInPadDrcEvaluator !== undefined;\n t2.errors.some(uw) || o3 ? (this.viaInPadSolver = new DN({ ...this.params, hdRoutes: e35, drcEvaluator: this.params.viaInPadDrcEvaluator ?? this.params.drcEvaluator, maxIterations: this.params.viaInPadMaxIterations ?? this.params.maxIterations, enableLargeBoardBroadFallback: false, enableTargetedErrorSweep: false, enablePostSolveClearanceRelaxation: false, enableSafeTraceLayerMoves: false, enableViaInPadLayerMoves: this.params.enableViaInPadLayerMoves }), this.activeSubSolver = this.viaInPadSolver, this.phase = \"viaInPad\") : this.finishWithOutput(e35, t2, n2);\n }\n startMixedSafeTraceLayerPhase(e35, t2, n2) {\n if (this.params.prioritizeMultipleTraceContactRepair \u0026\u0026 this.params.deferTraceContactGuard \u0026\u0026 (this.traceContactGuard ??= new RN({ srj: this.params.srj, inputRoutes: this.guardedInputHdRoutes, connMap: this.params.connMap }), this.traceContactGuard.getNewContactPairs(e35).length \u003e 1))\n return this.stoppedForTraceContacts = true, void this.finishWithOutput(e35, t2, n2);\n this.legacySafeTraceLayerRoutes = e35, this.legacySafeTraceLayerSnapshot = t2, this.legacySafeTraceLayerSelectedSolver = n2, this.mixedSafeTraceLayerSolver = new DN({ ...this.params, hdRoutes: this.safeTraceLayerInputRoutes, drcEvaluator: this.params.drcEvaluator, referenceDrcEvaluator: undefined, maxIterations: this.params.viaInPadMaxIterations ?? this.params.maxIterations, enableLargeBoardBroadFallback: false, enableTargetedErrorSweep: false, enablePostSolveClearanceRelaxation: false, enableSafeTraceLayerMoves: true, enableViaInPadLayerMoves: false }), this.activeSubSolver = this.mixedSafeTraceLayerSolver, this.phase = \"mixedSafeTraceLayer\";\n }\n startBroadBranch() {\n const e35 = ow(this.params.srj, this.inputHdRoutes, this.params.effort ?? 1, this.broadPassMultiplier, this.params.connMap);\n this.broadInputSnapshot = HP(this.params.srj, e35, this.params.drcEvaluator, this.params.connMap, this.autoroutingDrcEngine), vw(this.broadInputSnapshot, this.baselineSnapshot) ? (this.broadSolver = new DN({ ...this.params, hdRoutes: e35, drcEvaluator: this.legacyDrcEvaluator, referenceDrcEvaluator: undefined, maxIterations: this.broadMaxIterations, enableSafeTraceLayerMoves: false, enableViaInPadLayerMoves: false }), this.activeSubSolver = this.broadSolver, this.phase = \"broad\") : this.startSafeTraceLayerPhase(this.baselineSolver.getOutput(), this.baselineSnapshot, this.baselineSolver);\n }\n _step() {\n if (this.phase === \"start\")\n return this.inputSnapshot = HP(this.params.srj, this.inputHdRoutes, this.params.drcEvaluator, this.params.connMap, this.autoroutingDrcEngine), this.overlapSafeCheckpoint = { routes: this.guardedInputHdRoutes, snapshot: this.inputSnapshot, safeTraceLayerPhaseAccepted: false }, mw(this.inputSnapshot) === 0 ? void this.startViaInPadPhase(this.inputHdRoutes, this.inputSnapshot) : void this.startBaselineBranch();\n if (this.phase === \"baseline\") {\n if (this.stepBranch(this.baselineSolver, \"baseline\"), !this.baselineSolver.solved)\n return;\n const e35 = this.baselineSolver.getOutput();\n return this.baselineSnapshot = HP(this.params.srj, e35, this.params.drcEvaluator, this.params.connMap, this.autoroutingDrcEngine), this.rememberOverlapSafeCandidate({ routes: e35, snapshot: this.baselineSnapshot, solver: this.baselineSolver, safeTraceLayerPhaseAccepted: false }), mw(this.baselineSnapshot) === 0 ? void this.startViaInPadPhase(e35, this.baselineSnapshot, this.baselineSolver) : void (this.params.enableSafeTraceLayerMoves \u0026\u0026 this.baselineSnapshot.count \u003c= 3 ? this.startSafeTraceLayerPhase(e35, this.baselineSnapshot, this.baselineSolver) : this.startBroadBranch());\n }\n if (this.phase === \"broad\") {\n if (this.stepBranch(this.broadSolver, \"broad\"), !this.broadSolver.solved)\n return;\n const e35 = this.broadSolver.getOutput();\n return this.broadSnapshot = HP(this.params.srj, e35, this.params.drcEvaluator, this.params.connMap, this.autoroutingDrcEngine), vw(this.broadSnapshot, this.baselineSnapshot) ? void this.startSafeTraceLayerPhase(e35, this.broadSnapshot, this.broadSolver) : void this.startSafeTraceLayerPhase(this.baselineSolver.getOutput(), this.baselineSnapshot, this.baselineSolver);\n }\n if (this.phase === \"safeTraceLayer\") {\n if (this.stepBranch(this.safeTraceLayerSolver, \"safe trace-layer\"), !this.safeTraceLayerSolver.solved)\n return;\n const e35 = this.safeTraceLayerSolver.getOutput(), t2 = HP(this.params.srj, e35, this.params.drcEvaluator, this.params.connMap, this.autoroutingDrcEngine), n2 = hw(this.safeTraceLayerInputSnapshot), o3 = hw(t2);\n this.safeTraceLayerPhaseAccepted = o3 \u003c= n2 \u0026\u0026 Vw(t2, o3, this.safeTraceLayerInputSnapshot.count, this.safeTraceLayerInputSnapshot.issueScore, n2);\n let i3 = this.safeTraceLayerPhaseAccepted ? e35 : this.safeTraceLayerInputRoutes, r3 = this.safeTraceLayerPhaseAccepted ? t2 : this.safeTraceLayerInputSnapshot, s2 = this.safeTraceLayerPhaseAccepted ? this.safeTraceLayerSolver : this.portfolioSelectedSolver;\n return this.rememberOverlapSafeCandidate({ routes: i3, snapshot: r3, solver: s2, safeTraceLayerPhaseAccepted: this.safeTraceLayerPhaseAccepted }), this.preBroadCandidate \u0026\u0026 !vw(r3, this.preBroadCandidate.snapshot) \u0026\u0026 (i3 = this.preBroadCandidate.routes, r3 = this.preBroadCandidate.snapshot, s2 = this.preBroadCandidate.solver, this.safeTraceLayerPhaseAccepted = this.preBroadCandidate.safeTraceLayerPhaseAccepted), r3.count \u003e 0 \u0026\u0026 !this.broadInputSnapshot ? (this.preBroadCandidate = { routes: i3, snapshot: r3, solver: s2, safeTraceLayerPhaseAccepted: this.safeTraceLayerPhaseAccepted }, void this.startBroadBranch()) : mw(r3) \u003e 0 \u0026\u0026 this.safeTraceLayerInputSnapshot.errors.some(uw) ? void this.startMixedSafeTraceLayerPhase(i3, r3, s2) : void this.startViaInPadPhase(i3, r3, s2);\n }\n if (this.phase === \"mixedSafeTraceLayer\") {\n if (this.stepBranch(this.mixedSafeTraceLayerSolver, \"mixed safe trace-layer\"), !this.mixedSafeTraceLayerSolver.solved)\n return;\n const e35 = this.mixedSafeTraceLayerSolver.getOutput(), t2 = HP(this.params.srj, e35, this.params.drcEvaluator, this.params.connMap, this.autoroutingDrcEngine), n2 = mw(t2) \u003c= mw(this.legacySafeTraceLayerSnapshot);\n let o3 = true;\n if (this.params.referenceDrcEvaluator) {\n const t3 = this.getReferenceDrcSnapshot(this.legacySafeTraceLayerRoutes), n3 = this.getReferenceDrcSnapshot(e35);\n this.mixedReferenceInputDrcIssueCount = t3.count, this.mixedReferenceCandidateDrcIssueCount = n3.count, o3 = n3.count \u003c= t3.count;\n }\n return this.mixedSafeTraceLayerPhaseAccepted = n2 \u0026\u0026 o3, void this.startViaInPadPhase(this.mixedSafeTraceLayerPhaseAccepted ? e35 : this.legacySafeTraceLayerRoutes, this.mixedSafeTraceLayerPhaseAccepted ? t2 : this.legacySafeTraceLayerSnapshot, this.mixedSafeTraceLayerPhaseAccepted ? this.mixedSafeTraceLayerSolver : this.legacySafeTraceLayerSelectedSolver);\n }\n if (this.phase === \"viaInPad\") {\n if (this.stepBranch(this.viaInPadSolver, \"via-in-pad\"), !this.viaInPadSolver.solved)\n return;\n const e35 = this.viaInPadSolver.getOutput(), t2 = HP(this.params.srj, e35, this.params.viaInPadDrcEvaluator ?? this.params.drcEvaluator, this.params.connMap, this.autoroutingDrcEngine);\n this.finishWithOutput(e35, t2, this.viaInPadSolver);\n }\n }\n getOutput() {\n return this.outputHdRoutes;\n }\n visualize() {\n return this.activeSubSolver ? this.activeSubSolver.visualize() : this.solved ? (this.outputVisualizationSolver || (this.outputVisualizationSolver = new kN({ ...this.params, hdRoutes: this.inputHdRoutes, referenceDrcEvaluator: undefined }), this.outputVisualizationSolver.outputHdRoutes = this.outputHdRoutes, this.outputVisualizationSolver.stats = this.stats, this.outputVisualizationSolver.solved = true, this.outputVisualizationSolver.progress = 1), this.outputVisualizationSolver.visualize()) : super.visualize();\n }\n preview() {\n return this.activeSubSolver?.preview() ?? this.visualize();\n }\n};\nvar zN = (e35, t2, n2) =\u003e {\n const o3 = n2.x - t2.x, i3 = n2.y - t2.y, r3 = o3 * o3 + i3 * i3;\n return r3 === 0 ? 0 : Math.max(0, Math.min(1, ((e35.x - t2.x) * o3 + (e35.y - t2.y) * i3) / r3));\n};\nvar BN = (e35, t2, n2) =\u003e ({ x: e35.x + (t2.x - e35.x) * n2, y: e35.y + (t2.y - e35.y) * n2, z: e35.z });\nvar FN = (e35, t2, n2, o3) =\u003e {\n const i3 = t2.x - e35.x, r3 = t2.y - e35.y, s2 = o3.x - n2.x, a3 = o3.y - n2.y, c3 = i3 * a3 - r3 * s2;\n if (Math.abs(c3) \u003e 0.000000000001) {\n const t3 = ((n2.x - e35.x) * a3 - (n2.y - e35.y) * s2) / c3, o4 = ((n2.x - e35.x) * r3 - (n2.y - e35.y) * i3) / c3;\n if (t3 \u003e= 0 \u0026\u0026 t3 \u003c= 1 \u0026\u0026 o4 \u003e= 0 \u0026\u0026 o4 \u003c= 1)\n return [t3, o4];\n }\n const l3 = [[0, zN(e35, n2, o3)], [1, zN(t2, n2, o3)], [zN(n2, e35, t2), 0], [zN(o3, e35, t2), 1]];\n let h2 = l3[0], d2 = 1 / 0;\n for (const i4 of l3) {\n const r4 = BN(e35, t2, i4[0]), s3 = BN(n2, o3, i4[1]), a4 = Math.hypot(r4.x - s3.x, r4.y - s3.y);\n a4 \u003c d2 \u0026\u0026 (h2 = i4, d2 = a4);\n }\n return h2;\n};\nvar jN = (e35, t2) =\u003e {\n const n2 = [];\n for (let o3 = 1;o3 \u003c e35.route.length; o3++) {\n const i3 = e35.route[o3 - 1], r3 = e35.route[o3];\n if (i3.z === r3.z \u0026\u0026 i3.toNextSegmentType !== \"through_obstacle\")\n for (let s2 = 1;s2 \u003c t2.route.length; s2++) {\n const a3 = t2.route[s2 - 1], c3 = t2.route[s2];\n if (a3.z !== c3.z || i3.z !== a3.z || a3.toNextSegmentType === \"through_obstacle\")\n continue;\n if (we(i3, r3, a3, c3) \u003e= (e35.traceThickness + t2.traceThickness) / 2 - 0.000000001)\n continue;\n const [l3, h2] = FN(i3, r3, a3, c3);\n n2.push({ indexes: [o3, s2], positions: [o3 - 1 + l3, s2 - 1 + h2] });\n }\n }\n return n2;\n};\nvar $N = (e35, t2, n2, o3) =\u003e {\n const i3 = Math.min(Math.floor(t2), e35.route.length - 2);\n let r3 = BN(e35.route[i3], e35.route[i3 + 1], t2 - i3), s2 = n2 \u003c 0 ? i3 : i3 + 1;\n for (;s2 \u003e= 0 \u0026\u0026 s2 \u003c e35.route.length; ) {\n const t3 = e35.route[s2], i4 = n2 \u003c 0 ? t3 : e35.route[s2 - 1];\n if (r3.z !== t3.z || i4.toNextSegmentType === \"through_obstacle\")\n return;\n const a3 = Math.hypot(t3.x - r3.x, t3.y - r3.y);\n if (a3 \u003e= o3 \u0026\u0026 a3 \u003e 0) {\n if (Math.abs(a3 - o3) \u003c= 0.000000001 \u0026\u0026 t3.pcb_port_id)\n return;\n return { index: n2 \u003c 0 ? s2 : s2 - 1, point: BN(r3, t3, o3 / a3) };\n }\n o3 -= a3, r3 = t3, s2 += n2;\n }\n};\nvar YN = (e35) =\u003e e35.reduce((e36, t2) =\u003e e36 + t2.vias.length, 0);\nvar XN = (e35, t2) =\u003e e35.snapshot.count \u003c t2.snapshot.count || e35.snapshot.count === t2.snapshot.count \u0026\u0026 e35.snapshot.issueScore \u003c t2.snapshot.issueScore - 0.00000001;\nvar HN = class extends BaseSolver {\n params;\n guard;\n phase = \"start\";\n inputSnapshot;\n targetDrcCount = 1 / 0;\n current;\n best;\n proposals;\n candidateContactCheck;\n pairs = [];\n affectedConnections = new Set;\n refineSolver;\n candidateChecks = 0;\n geometryChecks = 0;\n contactRounds = 0;\n viaRounds = 0;\n simplificationRounds = 0;\n outputHdRoutes;\n constructor(e35) {\n super(), this.params = e35, this.guard = new RN({ srj: e35.srj, inputRoutes: e35.inputHdRoutes, connMap: e35.connMap }), this.outputHdRoutes = e35.inputHdRoutes, this.MAX_ITERATIONS = 20000;\n }\n snapshot(e35) {\n return HP(this.params.srj, e35, this.params.drcEvaluator, this.params.connMap, this.params.autoroutingDrcEngine);\n }\n startContactRound() {\n this.guard.preserveClearedContacts(this.current.routes), this.pairs = this.guard.getNewContactPairs(this.current.routes), this.pairs.length !== 0 ? this.contactRounds++ \u003e= 4 || this.geometryChecks \u003e= 2048 || this.candidateChecks \u003e= 256 ? this.finish() : (this.best = undefined, this.candidateContactCheck = this.guard.prepareCandidateCheck(this.current.routes), this.proposals = function* ({ srj: e35, routes: t2, pair: n2, connMap: o3, viaHoleDiameter: i3 }) {\n const r3 = t2.flatMap((e36, t3) =\u003e e36.connectionName === n2[0] ? [t3] : []), s2 = t2.flatMap((e36, t3) =\u003e e36.connectionName === n2[1] ? [t3] : []);\n for (const n3 of r3)\n for (const r4 of s2) {\n const s3 = [n3, r4], a3 = t2[n3], c3 = t2[r4], l3 = jN(a3, c3);\n if (l3.length === 0)\n continue;\n for (const n4 of [0, 1]) {\n const o4 = s3[n4], i4 = t2[o4], r5 = t2[s3[1 - n4]];\n for (const s4 of [-1, 1])\n for (const h4 of [0.001, 0.1])\n for (const d2 of [0, 1]) {\n const u2 = OP(t2, [o4]);\n for (const e36 of l3) {\n const t3 = e36.indexes[n4], l4 = e36.indexes[1 - n4], p3 = r5.route[l4 - 1], m2 = r5.route[l4], g2 = m2.x - p3.x, f2 = m2.y - p3.y, _2 = Math.hypot(g2, f2);\n if (_2 \u003c= 0.000000001)\n continue;\n const y2 = -f2 / _2 * s4, b2 = g2 / _2 * s4, x2 = (a3.traceThickness + c3.traceThickness) / 2 + h4;\n for (let e37 = Math.max(1, t3 - 1 - d2);e37 \u003c= Math.min(i4.route.length - 2, t3 + d2); e37++) {\n const t4 = u2[o4].route[e37], n5 = i4.route[e37 - 1], r6 = i4.route[e37 + 1];\n if (t4.z !== p3.z || t4.pcb_port_id || n5.z !== t4.z || r6.z !== t4.z || n5.toNextSegmentType === \"through_obstacle\" || t4.toNextSegmentType === \"through_obstacle\")\n continue;\n const s5 = x2 - ((t4.x - p3.x) * y2 + (t4.y - p3.y) * b2);\n s5 \u003e 0 \u0026\u0026 (t4.x += s5 * y2, t4.y += s5 * b2);\n }\n }\n u2[o4].route.every((t3) =\u003e t3.x \u003e= e35.bounds.minX \u0026\u0026 t3.x \u003c= e35.bounds.maxX \u0026\u0026 t3.y \u003e= e35.bounds.minY \u0026\u0026 t3.y \u003c= e35.bounds.maxY) \u0026\u0026 (yield aw(u2, [o4]));\n }\n const h3 = [[Math.min(...l3.map((e36) =\u003e e36.positions[n4])), Math.max(...l3.map((e36) =\u003e e36.positions[n4]))], [Math.min(...l3.map((e36) =\u003e e36.indexes[n4])) - 1, Math.max(...l3.map((e36) =\u003e e36.indexes[n4]))]];\n for (const [n5, r6] of h3) {\n const s4 = i4.route[Math.floor(n5)].z, a4 = [0.15, 0.3, 0.6, 1, 2];\n for (const c4 of a4)\n for (const l4 of a4)\n for (let a5 = 0;a5 \u003c e35.layerCount; a5++) {\n if (a5 === s4)\n continue;\n const e36 = $N(i4, n5, -1, c4), h4 = $N(i4, r6, 1, l4);\n if (!e36 || !h4 || e36.index \u003e h4.index)\n continue;\n const d2 = i4.route.slice(e36.index + 1, h4.index + 1);\n if (d2.some((e37) =\u003e e37.z !== s4 || e37.pcb_port_id || e37.toNextSegmentType === \"through_obstacle\"))\n continue;\n const u2 = OP(t2, [o4]);\n u2[o4].route = [...i4.route.slice(0, e36.index + 1), e36.point, { ...e36.point, z: a5 }, ...d2.map((e37) =\u003e ({ ...e37, z: a5 })), { ...h4.point, z: a5 }, h4.point, ...i4.route.slice(h4.index + 1)], yield aw(u2, [o4]);\n }\n }\n }\n const h2 = new Map([[\"peer_left\", n3], [\"peer_right\", r4]]);\n for (const n4 of l3) {\n const r5 = { type: \"pcb_trace_error\", pcb_trace_id: \"peer_left\", pcb_trace_ids: [\"peer_left\", \"peer_right\"], center: BN(a3.route[n4.indexes[0] - 1], a3.route[n4.indexes[0]], n4.positions[0] - n4.indexes[0] + 1), minimum_clearance: 0.1 };\n for (const n5 of [0, 1])\n for (let a4 = 0;a4 \u003c e35.layerCount; a4++)\n for (const c4 of [0, 1, 2, 4]) {\n const l4 = OP(t2, [s3[n5]]);\n jw(e35, l4, r5, h2, n5, a4, c4, o3, i3) \u0026\u0026 (yield aw(l4, [s3[n5]]));\n }\n }\n }\n }({ ...this.params, routes: this.current.routes, pair: this.pairs[0] }), this.phase = \"contacts\") : this.startRefinement();\n }\n startRefinement() {\n this.current.snapshot.count \u003c= this.targetDrcCount || xw(this.current.snapshot, this.inputSnapshot) ? this.finish() : (this.refineSolver = new LN({ ...this.params, hdRoutes: this.current.routes, maxIterations: 1, viaInPadMaxIterations: Math.min(24, this.params.viaInPadMaxIterations ?? 8), broadMaxIterations: 4, enableSafeTraceLayerMoves: false, prioritizeMultipleTraceContactRepair: false, enableBroadFallback: false, enableLargeBoardBroadFallback: false, enablePostSolveClearanceRelaxation: false, deferTraceContactGuard: false, referenceDrcEvaluator: undefined }), this.activeSubSolver = this.refineSolver, this.phase = \"refine\");\n }\n startViaRound() {\n this.guard.preserveClearedContacts(this.current.routes), this.current.snapshot.count \u003c= this.targetDrcCount || this.viaRounds++ \u003e= 4 || this.candidateChecks \u003e= 768 ? this.finish() : (this.best = this.current, this.candidateContactCheck = this.guard.prepareCandidateCheck(this.current.routes), this.proposals = function* ({ srj: e35, routes: t2, previousRoutes: n2, affectedConnections: o3 }) {\n const i3 = new Set(n2.flatMap((e36) =\u003e e36.vias.map((t3) =\u003e `${e36.connectionName}:${t3.x},${t3.y}`)));\n let r3 = 0;\n for (const [n3, s2] of t2.entries())\n if (o3.has(s2.connectionName))\n for (let o4 = 1;o4 \u003c s2.route.length; o4++) {\n const a3 = s2.route[o4 - 1], c3 = s2.route[o4];\n if (a3.z === c3.z || a3.x !== c3.x || a3.y !== c3.y || i3.has(`${s2.connectionName}:${c3.x},${c3.y}`))\n continue;\n let l3 = o4 - 1, h2 = o4;\n for (;l3 \u003e 0 \u0026\u0026 s2.route[l3 - 1].x === c3.x \u0026\u0026 s2.route[l3 - 1].y === c3.y; )\n l3--;\n for (;h2 + 1 \u003c s2.route.length \u0026\u0026 s2.route[h2 + 1].x === c3.x \u0026\u0026 s2.route[h2 + 1].y === c3.y; )\n h2++;\n if (o4 = h2, l3 !== 0 \u0026\u0026 h2 !== s2.route.length - 1 \u0026\u0026 s2.route[l3 - 1].toNextSegmentType !== \"through_obstacle\" \u0026\u0026 !s2.route.slice(l3, h2 + 1).some((e36) =\u003e e36.pcb_port_id || e36.toNextSegmentType === \"through_obstacle\")) {\n if (++r3 \u003e 8)\n return;\n for (const o5 of [0.05, 0.1, 0.4])\n for (let i4 = 0;i4 \u003c 8; i4++) {\n const r4 = c3.x + Math.cos(i4 * Math.PI / 4) * o5, a4 = c3.y + Math.sin(i4 * Math.PI / 4) * o5, d2 = s2.viaDiameter / 2, u2 = e35.bounds;\n if (r4 - d2 \u003c u2.minX || r4 + d2 \u003e u2.maxX || a4 - d2 \u003c u2.minY || a4 + d2 \u003e u2.maxY)\n continue;\n const p3 = OP(t2, [n3]);\n for (let e36 = l3;e36 \u003c= h2; e36++)\n p3[n3].route[e36].x = r4, p3[n3].route[e36].y = a4;\n yield aw(p3, [n3]);\n }\n }\n }\n }({ srj: this.params.srj, routes: this.current.routes, previousRoutes: this.params.hdRoutes, affectedConnections: this.affectedConnections }), this.phase = \"vias\");\n }\n finish() {\n const e35 = this.current;\n if (e35 \u0026\u0026 e35.snapshot.count \u003c= this.inputSnapshot.count \u0026\u0026 this.guard.getNewContactPairs(e35.routes).length === 0 \u0026\u0026 !xw(e35.snapshot, this.inputSnapshot)) {\n if (this.phase !== \"simplify\" \u0026\u0026 YN(e35.routes) \u003e YN(this.params.hdRoutes))\n return void this.startSimplificationRound();\n this.outputHdRoutes = e35.routes;\n }\n this.stats = { traceContactRepairCandidateChecks: this.candidateChecks, traceContactRepairGeometryChecks: this.geometryChecks, traceContactRepairContactRounds: this.contactRounds, traceContactRepairViaRounds: this.viaRounds, traceContactRepairSimplificationRounds: this.simplificationRounds, traceContactRepairAccepted: this.outputHdRoutes !== this.params.inputHdRoutes }, this.activeSubSolver = null, this.phase = \"done\", this.progress = 1, this.solved = true;\n }\n startSimplificationRound() {\n this.phase = \"simplify\", this.guard.preserveClearedContacts(this.current.routes), YN(this.current.routes) \u003c= YN(this.params.hdRoutes) || this.simplificationRounds++ \u003e= 4 ? this.finish() : (this.proposals = function* (e35) {\n for (let t2 = 0;t2 \u003c e35.length; t2++) {\n const n2 = e35[t2], o3 = n2.route.flatMap((e36, t3) =\u003e t3 \u003e 0 \u0026\u0026 e36.z !== n2.route[t3 - 1].z ? [t3] : []);\n for (let i3 = 0;i3 + 1 \u003c o3.length; i3++) {\n const r3 = o3[i3], s2 = o3[i3 + 1], a3 = n2.route[r3 - 1].z;\n if (n2.route[s2].z === a3 \u0026\u0026 !n2.route.slice(r3 - 1, s2 + 1).some((e36) =\u003e e36.toNextSegmentType === \"through_obstacle\") \u0026\u0026 !n2.route.slice(r3, s2).some((e36) =\u003e e36.pcb_port_id))\n for (const n3 of [\"chord\", \"flatten\"]) {\n const o4 = OP(e35, [t2]), i4 = o4[t2];\n if (n3 === \"chord\")\n i4.route.splice(r3, s2 - r3);\n else\n for (let e36 = r3;e36 \u003c s2; e36++)\n i4.route[e36].z = a3;\n i4.route = i4.route.filter((e36, t3, n4) =\u003e {\n const o5 = n4[t3 - 1];\n return !o5 || e36.pcb_port_id || e36.toNextSegmentType || o5.toNextSegmentType || e36.insideJumperPad !== o5.insideJumperPad || e36.x !== o5.x || e36.y !== o5.y || e36.z !== o5.z;\n }), yield aw(o4, [t2]);\n }\n }\n }\n }(this.current.routes), this.candidateContactCheck = this.guard.prepareCandidateCheck(this.current.routes));\n }\n _step() {\n if (this.phase === \"start\")\n return this.inputSnapshot = this.snapshot(this.params.inputHdRoutes), this.current = { routes: this.params.hdRoutes, snapshot: this.snapshot(this.params.hdRoutes) }, this.targetDrcCount = this.current.snapshot.count, this.affectedConnections = this.guard.getNewContactConnectionNames(this.current.routes), void this.startContactRound();\n if (this.phase === \"refine\") {\n const e36 = this.refineSolver;\n if (e36.step(), e36.failed)\n throw new Error(`Peer contact refinement failed: ${e36.error}`);\n if (!e36.solved)\n return;\n const t3 = e36.getOutput(), n3 = { routes: t3, snapshot: this.snapshot(t3) };\n return XN(n3, this.current) \u0026\u0026 this.guard.getNewContactPairs(t3).length === 0 \u0026\u0026 !xw(n3.snapshot, this.inputSnapshot) \u0026\u0026 (this.current = n3), this.activeSubSolver = null, void this.startViaRound();\n }\n if (this.phase === \"simplify\") {\n const e36 = this.proposals.next();\n if (e36.done || this.geometryChecks \u003e= 4096 || this.candidateChecks \u003e= 768)\n return void this.finish();\n const t3 = e36.value;\n if (this.geometryChecks++, this.candidateContactCheck(t3).length \u003e 0)\n return;\n this.candidateChecks++;\n const n3 = this.snapshot(t3);\n if (n3.count \u003e this.current.snapshot.count || xw(n3, this.inputSnapshot) || YN(t3) \u003e= YN(this.current.routes))\n return;\n return this.current = { routes: t3, snapshot: n3 }, void this.startSimplificationRound();\n }\n if (this.phase !== \"contacts\" \u0026\u0026 this.phase !== \"vias\")\n return;\n const e35 = this.proposals.next();\n if (e35.done || this.geometryChecks \u003e= 4096 || this.candidateChecks \u003e= 768) {\n if (this.phase === \"contacts\") {\n if (!this.best)\n return void this.finish();\n this.current = this.best, this.startContactRound();\n } else\n this.best !== this.current ? (this.current = this.best, this.startViaRound()) : this.finish();\n return;\n }\n const t2 = e35.value;\n if (this.geometryChecks++, this.phase === \"contacts\" \u0026\u0026 this.guard.hasContactPair(t2, this.pairs[0]))\n return;\n const n2 = this.candidateContactCheck(t2);\n if (this.phase === \"contacts\") {\n if (n2.length \u003e= this.pairs.length || n2.some((e36) =\u003e e36[0] === this.pairs[0][0] \u0026\u0026 e36[1] === this.pairs[0][1] || !this.pairs.some((t3) =\u003e t3[0] === e36[0] \u0026\u0026 t3[1] === e36[1])))\n return;\n } else if (n2.length \u003e 0)\n return;\n this.candidateChecks++;\n const o3 = { routes: t2, snapshot: this.snapshot(t2) };\n xw(o3.snapshot, this.inputSnapshot) || (this.best \u0026\u0026 !XN(o3, this.best) || (this.best = o3), this.phase === \"contacts\" \u0026\u0026 this.best.snapshot.count \u003c= this.current.snapshot.count \u0026\u0026 YN(this.best.routes) \u003c= YN(this.current.routes) \u0026\u0026 (this.current = this.best, this.startContactRound()));\n }\n getOutput() {\n return this.outputHdRoutes;\n }\n};\nfunction VN(e35) {\n if (!e35.connections.some((e36) =\u003e e36.pointsToConnect.some((e37) =\u003e !e37.pcb_port_id \u0026\u0026 e37.pointId)))\n return e35;\n const t2 = new Map;\n for (const n3 of e35.obstacles) {\n const e36 = n3.circuitJsonMetadata;\n if (!e36?.source_component_name || !e36.source_port_name || e36.pcb_via_id || n3.isNonPlatedHole)\n continue;\n const o4 = new Set([n3.obstacleId, `${e36.source_component_name}.${e36.source_port_name}`, ...n3.connectedTo]);\n for (const e37 of o4) {\n if (!e37)\n continue;\n const o5 = t2.get(e37);\n o5 ? o5.push(n3) : t2.set(e37, [n3]);\n }\n }\n if (t2.size === 0)\n return e35;\n let n2 = false;\n const o3 = { ...e35, connections: e35.connections.map((e36) =\u003e ({ ...e36, pointsToConnect: e36.pointsToConnect.map((o4) =\u003e {\n if (o4.pcb_port_id || !o4.pointId)\n return o4;\n const i3 = So(o4);\n return [o4.pointId, o4.port_selector, e36.name, e36.__netConnectionName, ...e36.__rootConnectionNames ?? []].some((e37) =\u003e e37 \u0026\u0026 t2.get(e37)?.some((e38) =\u003e Math.hypot(o4.x - e38.center.x, o4.y - e38.center.y) \u003c 0.000001 \u0026\u0026 i3.some((t3) =\u003e e38.layers.includes(t3)))) ? (n2 = true, { ...o4, pcb_port_id: o4.pointId }) : o4;\n }) })) };\n return n2 ? o3 : e35;\n}\nvar WN = (e35) =\u003e e35.circuitJsonMetadata ?? {};\nvar GN = ({ connections: e35, obstacles: t2 }) =\u003e new Set([...e35.flatMap((e36) =\u003e e36.pointsToConnect.flatMap((e37) =\u003e e37.pcb_port_id ? [e37.pcb_port_id] : [])), ...t2.flatMap((e36) =\u003e {\n const t3 = WN(e36).pcb_port_id;\n return t3 ? [t3] : [];\n})]);\nvar UN = (e35) =\u003e e35.__netConnectionName ?? e35.__rootConnectionNames?.[0] ?? e35.name;\nvar ZN = (e35) =\u003e Array.from(new Set([e35.name, e35.__netConnectionName, ...e35.__rootConnectionNames ?? [], ...e35.pointsToConnect.flatMap((e36) =\u003e [e36.pointId, e36.pcb_port_id])])).filter((e36) =\u003e Boolean(e36));\nvar qN = (e35, t2) =\u003e {\n const n2 = new Map, o3 = new Set, i3 = new Map;\n for (const r3 of e35) {\n const e36 = UN(r3);\n for (const t3 of ZN(r3)) {\n const i4 = n2.get(t3);\n i4 \u0026\u0026 i4 !== e36 ? (n2.delete(t3), o3.add(t3)) : o3.has(t3) || n2.set(t3, e36);\n }\n const s2 = t2.getNetConnectedToId(r3.name);\n if (!s2)\n continue;\n const a3 = s2, c3 = i3.get(a3) ?? new Set;\n c3.add(e36), i3.set(a3, c3);\n }\n return { connMap: t2, circuitJsonSourceTraceIdBySrjDeclaredConnectionReference: n2, circuitJsonSourceTraceIdsByConnectivityNetId: i3 };\n};\nvar JN = (e35, t2) =\u003e {\n const n2 = e35.circuitJsonSourceTraceIdBySrjDeclaredConnectionReference.get(t2);\n if (n2)\n return n2;\n const o3 = e35.connMap.getNetConnectedToId(t2);\n if (!o3)\n return;\n const i3 = e35.circuitJsonSourceTraceIdsByConnectivityNetId.get(o3);\n return i3?.size === 1 ? i3.values().next().value : undefined;\n};\nfunction QN(e35, t2, n2 = e35, o3) {\n const i3 = [], r3 = n2 === e35 ? e35.connections : [...e35.connections, ...n2.connections], s2 = n2 === e35 ? e35.obstacles : n2.obstacles, a3 = qN(r3, o3 ?? ei(n2 === e35 ? e35 : { ...n2, connections: r3 })), c3 = GN({ connections: r3, obstacles: s2 });\n if (r3.forEach((e36) =\u003e {\n const n3 = e36.pointsToConnect.map((e37) =\u003e e37.pcb_port_id).filter((e37) =\u003e Boolean(e37)), o4 = new Set(n3), r4 = (e37) =\u003e ((e38) =\u003e Array.from(new Set(e38.flatMap((e39) =\u003e e39.connectedTo))))(e37).filter((e38) =\u003e !o4.has(e38)), c4 = e36.pointsToConnect.map((e37) =\u003e e37.pointId).filter((e37) =\u003e Boolean(e37)), l3 = JN(a3, e36.name) ?? UN(e36), h2 = new Set(ZN(e36)), d2 = [], u2 = t2.find((t3) =\u003e (t3.connection_name ?? t3.connectionName) === e36.name);\n if (u2) {\n const e37 = (e38) =\u003e (\"route_type\" in e38) \u0026\u0026 e38.route_type === \"jumper\" ? e38.start : (\"x\" in e38) \u0026\u0026 (\"y\" in e38) ? { x: e38.x, y: e38.y } : { x: 0, y: 0 }, t3 = [e37(u2.route[0]), e37(u2.route[u2.route.length - 1])];\n for (const e38 of t3)\n for (const t4 of s2)\n Oe(e38, t4) \u003c= 0 \u0026\u0026 (n3.length === 0 || t4.netIsAssignable || t4.connectedTo.some((e39) =\u003e h2.has(e39))) \u0026\u0026 d2.push(t4);\n }\n const p3 = i3.find((e37) =\u003e e37.type === \"source_trace\" \u0026\u0026 e37.source_trace_id === l3);\n if (p3) {\n const e37 = p3;\n e37.connected_source_port_ids = [...new Set([...e37.connected_source_port_ids, ...n3])], e37.connected_source_net_ids = [...new Set([...e37.connected_source_net_ids ?? [], ...c4, ...r4(d2)])];\n } else\n i3.push({ type: \"source_trace\", source_trace_id: l3, connected_source_port_ids: n3, connected_source_net_ids: r4(d2).concat(c4) });\n }), t2[0] \u0026\u0026 \"type\" in t2[0]) {\n const e36 = new Map(r3.map((e37) =\u003e [e37.name, e37]));\n for (const n3 of t2) {\n const t3 = [...new Set((n3.connectsTo ?? []).filter((e37) =\u003e c3.has(e37)))], o4 = new Set(t3), r4 = [...new Set((n3.connectsTo ?? []).filter((e37) =\u003e !o4.has(e37)))];\n if (t3.length === 0 \u0026\u0026 r4.length === 0)\n continue;\n const s3 = e36.get(n3.connection_name), l3 = JN(a3, n3.connection_name) ?? n3.connectsTo?.map((e37) =\u003e JN(a3, e37)).find((e37) =\u003e e37 !== undefined) ?? (s3 ? UN(s3) : n3.connection_name), h2 = i3.find((e37) =\u003e e37.type === \"source_trace\" \u0026\u0026 e37.source_trace_id === l3);\n h2?.type !== \"source_trace\" ? i3.push({ type: \"source_trace\", source_trace_id: l3, connected_source_port_ids: t3, connected_source_net_ids: r4 }) : (h2.connected_source_port_ids = [...new Set([...h2.connected_source_port_ids, ...t3])], h2.connected_source_net_ids = [...new Set([...h2.connected_source_net_ids ?? [], ...r4])]);\n }\n }\n return i3;\n}\nfunction KN(e35, t2, n2) {\n let o3, i3 = Number.POSITIVE_INFINITY;\n for (const r3 of t2) {\n const t3 = n2.get(r3);\n if (!t3)\n continue;\n const s2 = Math.hypot(t3.x - e35.x, t3.y - e35.y);\n s2 \u003c i3 \u0026\u0026 (i3 = s2, o3 = r3);\n }\n return o3 ?? t2[0];\n}\nvar eR = new Set([\"top\", \"bottom\", \"inner1\", \"inner2\", \"inner3\", \"inner4\", \"inner5\", \"inner6\", \"inner7\", \"inner8\"]);\nvar tR = (e35) =\u003e eR.has(e35);\nfunction nR(e35, t2, n2, o3) {\n const i3 = JSON.stringify([t2.center.x, t2.center.y, t2.width, t2.height, t2.ccwRotationDegrees ?? 0, [...t2.layers].sort()]), r3 = o3.get(e35) ?? new Set;\n if (r3.has(i3))\n return;\n const s2 = r3.size === 0 ? e35 : `${e35}_fragment_${n2}`;\n return r3.add(i3), o3.set(e35, r3), s2;\n}\nfunction oR(e35) {\n const t2 = [], n2 = new Map, o3 = new Map, i3 = function(e36) {\n const t3 = new Map;\n for (const n3 of e36.connections)\n for (const e37 of n3.pointsToConnect)\n e37.pcb_port_id \u0026\u0026 t3.set(e37.pcb_port_id, { x: e37.x, y: e37.y });\n return t3;\n }(e35), r3 = GN(e35);\n for (const [s2, a3] of e35.obstacles.entries()) {\n if (a3.isNonPlatedHole) {\n const e36 = { type: \"pcb_hole\", pcb_hole_id: a3.obstacleId ?? `pcb_hole_${s2}`, x: a3.center.x, y: a3.center.y };\n if (a3.shape === \"circle\")\n t2.push({ ...e36, hole_shape: \"circle\", hole_diameter: a3.width });\n else {\n const n3 = a3.ccwRotationDegrees ?? 0;\n if (n3 % 90 != 0)\n throw new Error(`Cannot represent rotated rectangular hole ${e36.pcb_hole_id} in Circuit JSON`);\n const o4 = n3 % 180 != 0;\n t2.push({ ...e36, hole_shape: \"rect\", hole_width: o4 ? a3.height : a3.width, hole_height: o4 ? a3.width : a3.height });\n }\n continue;\n }\n const c3 = a3.connectedTo, l3 = WN(a3);\n if (l3.pcb_via_id || a3.isCopperPour)\n continue;\n const { source_component_name: h2, source_port_name: d2 } = l3, u2 = h2 \u0026\u0026 d2 ? a3.obstacleId ?? `${h2}.${d2}` : undefined, p3 = l3.pcb_smtpad_id ?? u2, m2 = l3.pcb_plated_hole_id, g2 = [...new Set([...l3.pcb_port_id ? [l3.pcb_port_id] : [], ...c3.filter((e36) =\u003e r3.has(e36))])];\n if (g2.length === 0) {\n for (const t3 of e35.connections)\n if (a3.netIsAssignable || ZN(t3).some((e36) =\u003e c3.includes(e36)))\n for (const e36 of t3.pointsToConnect)\n e36.pcb_port_id \u0026\u0026 Math.hypot(e36.x - a3.center.x, e36.y - a3.center.y) \u003c 0.000001 \u0026\u0026 g2.push(e36.pcb_port_id);\n }\n const f2 = l3.pcb_port_id \u0026\u0026 i3.has(l3.pcb_port_id) ? l3.pcb_port_id : KN(a3.center, g2, i3);\n if (!p3 \u0026\u0026 !m2 \u0026\u0026 !f2)\n continue;\n const _2 = a3.layers.filter(tR);\n if (_2.length === 0)\n continue;\n const { width: y2, height: b2 } = a3, x2 = a3.center.x, v2 = a3.center.y, I2 = a3.ccwRotationDegrees;\n if (Boolean(m2) || _2.length \u003e 1) {\n const e36 = nR(m2 ?? `pcb_plated_hole_${x2.toFixed(3)}_${v2.toFixed(3)}`, a3, s2, o3);\n if (e36 === undefined)\n continue;\n if (typeof I2 == \"number\" \u0026\u0026 Number.isFinite(I2)) {\n const n3 = Math.max(0.5 * Math.min(y2, b2), 0.1);\n t2.push({ type: \"pcb_plated_hole\", pcb_plated_hole_id: e36, shape: \"rotated_pill_hole_with_rect_pad\", hole_shape: \"rotated_pill\", pad_shape: \"rect\", hole_width: n3, hole_height: n3, hole_ccw_rotation: I2, rect_pad_width: y2, rect_pad_height: b2, rect_ccw_rotation: I2, hole_offset_x: 0, hole_offset_y: 0, x: x2, y: v2, layers: _2, ...f2 ? { pcb_port_id: f2 } : {} });\n continue;\n }\n if (Math.abs(y2 - b2) \u003c 0.001) {\n t2.push({ type: \"pcb_plated_hole\", pcb_plated_hole_id: e36, shape: \"circle\", outer_diameter: Math.max(y2, b2), hole_diameter: Math.max(0.5 * Math.min(y2, b2), 0.1), x: x2, y: v2, layers: _2, ...f2 ? { pcb_port_id: f2 } : {} });\n continue;\n }\n t2.push({ type: \"pcb_plated_hole\", pcb_plated_hole_id: e36, shape: \"circular_hole_with_rect_pad\", hole_shape: \"circle\", hole_diameter: Math.max(0.5 * Math.min(y2, b2), 0.1), rect_pad_width: y2, rect_pad_height: b2, hole_offset_x: 0, hole_offset_y: 0, x: x2, y: v2, layers: _2, ...f2 ? { pcb_port_id: f2 } : {} });\n continue;\n }\n const S2 = nR(p3 ?? `pcb_smtpad_${x2.toFixed(3)}_${v2.toFixed(3)}`, a3, s2, n2);\n S2 !== undefined \u0026\u0026 (a3.shape !== \"circle\" ? typeof I2 == \"number\" \u0026\u0026 Number.isFinite(I2) ? t2.push({ type: \"pcb_smtpad\", pcb_smtpad_id: S2, layer: _2[0], shape: \"rotated_rect\", x: x2, y: v2, width: y2, height: b2, ccw_rotation: I2, ...f2 ? { pcb_port_id: f2 } : {} }) : t2.push({ type: \"pcb_smtpad\", pcb_smtpad_id: S2, layer: _2[0], shape: \"rect\", width: y2, height: b2, x: x2, y: v2, ...f2 ? { pcb_port_id: f2 } : {} }) : t2.push({ type: \"pcb_smtpad\", pcb_smtpad_id: S2, layer: _2[0], shape: \"circle\", radius: y2 / 2, x: x2, y: v2, ...f2 ? { pcb_port_id: f2 } : {} }));\n }\n return t2;\n}\nfunction iR(e35, t2, n2) {\n if (n2 \u0026\u0026 e35.layers !== undefined)\n return e35.layers;\n const o3 = n2 ? e35 : { from_layer: \"top\", to_layer: Co(t2 - 1, t2) };\n return Ky(o3, t2);\n}\nfunction rR(e35) {\n const { minX: t2, maxX: n2, minY: o3, maxY: i3 } = e35.bounds;\n return { type: \"pcb_board\", pcb_board_id: \"__autorouting_board__\", thickness: 1.6, num_layers: e35.layerCount, center: { x: (t2 + n2) / 2, y: (o3 + i3) / 2 }, width: n2 - t2, height: i3 - o3, ...e35.outline ? { outline: e35.outline, shape: \"polygon\" } : { shape: \"rect\" }, material: \"fr4\", min_trace_to_hole_edge_clearance: e35.minTraceToHoleEdgeClearance, min_pad_edge_to_pad_edge_clearance: e35.minPadEdgeToPadEdgeClearance, ...e35.minBoardEdgeClearance !== undefined ? { min_board_edge_clearance: e35.minBoardEdgeClearance } : {} };\n}\nfunction sR(e35, t2, n2 = {}) {\n const { minTraceWidth: o3 = 0.1, minViaDiameter: i3, minViaHoleDiameter: r3, originalSrj: s2, includeOriginalConnections: a3 = false } = n2, c3 = VN(e35), l3 = s2 ? VN(s2) : undefined, h2 = Yo(c3), d2 = i3 ?? h2.padDiameter, u2 = c3.min_via_hole_diameter ?? c3.minViaHoleDiameter, p3 = r3 ?? u2 ?? (i3 !== undefined ? 0.5 * d2 : h2.holeDiameter), m2 = [];\n m2.push(...QN(c3, t2, a3 \u0026\u0026 l3 ? l3 : c3, n2.connectivityMaps?.source)), m2.push(...function(e36) {\n const t3 = new Map;\n return e36.connections.forEach((e37) =\u003e {\n e37.pointsToConnect.forEach((e38) =\u003e {\n e38.pcb_port_id \u0026\u0026 t3.set(e38.pcb_port_id, { type: \"pcb_port\", pcb_port_id: e38.pcb_port_id, source_port_id: e38.pcb_port_id, x: e38.x, y: e38.y, layers: So(e38) });\n });\n }), Array.from(t3.values());\n }(a3 \u0026\u0026 l3 ? l3 : c3)), m2.push(...oR(l3 ?? c3)), m2.push(...function(e36, t3, n3 = 0.3, o4 = 0.5 * n3, i4 = false) {\n const r4 = [], s3 = new Set;\n return e36.length \u003e 0 \u0026\u0026 (\"type\" in e36[0] \u0026\u0026 e36[0].type === \"pcb_trace\" ? e36.forEach((e37) =\u003e {\n e37.route.forEach((a4) =\u003e {\n if (a4.route_type === \"via\") {\n if (!tR(a4.from_layer) || !tR(a4.to_layer))\n return;\n const c4 = a4.via_diameter ?? n3, l4 = a4.via_hole_diameter ?? o4, h3 = `${a4.x},${a4.y},${a4.from_layer},${a4.to_layer}`;\n s3.has(h3) || (r4.push({ type: \"pcb_via\", pcb_via_id: `via_${r4.length}`, pcb_trace_id: e37.pcb_trace_id, x: a4.x, y: a4.y, outer_diameter: c4, hole_diameter: l4, layers: iR(a4, t3, i4) }), s3.add(h3));\n }\n });\n }) : e36.forEach((e37, a4) =\u003e {\n const c4 = `trace_${a4}`, l4 = e37.viaDiameter ?? n3, h3 = o4;\n for (let n4 = 1;n4 \u003c e37.route.length; n4++) {\n const o5 = e37.route[n4 - 1], a5 = e37.route[n4];\n if (o5.z !== a5.z \u0026\u0026 Math.abs(o5.x - a5.x) \u003c 0.01 \u0026\u0026 Math.abs(o5.y - a5.y) \u003c 0.01) {\n const e38 = Co(o5.z, t3), n5 = Co(a5.z, t3), d3 = `${a5.x},${a5.y},${e38},${n5}`;\n s3.has(d3) || (r4.push({ type: \"pcb_via\", pcb_via_id: `via_${r4.length}`, pcb_trace_id: c4, x: a5.x, y: a5.y, outer_diameter: l4, hole_diameter: h3, layers: iR({ from_layer: e38, to_layer: n5 }, t3, i4) }), s3.add(d3));\n }\n }\n })), r4;\n }(t2, c3.layerCount, d2, p3, (l3 ?? c3).allowBlindAndBuriedVias === true));\n const g2 = new Set(c3.connections.flatMap(ZN)), f2 = qN(a3 \u0026\u0026 l3 ? [...c3.connections, ...l3.connections.filter((e36) =\u003e !g2.has(e36.name))] : c3.connections, n2.connectivityMaps?.route ?? ei(c3));\n return t2.length \u003e 0 \u0026\u0026 (\"type\" in t2[0] \u0026\u0026 t2[0].type === \"pcb_trace\" ? t2.forEach((e36) =\u003e {\n const t3 = JN(f2, e36.connection_name) ?? e36.connectsTo?.map((e37) =\u003e JN(f2, e37)).find((e37) =\u003e Boolean(e37)) ?? e36.connection_name;\n m2.push(function(e37, t4) {\n return { type: \"pcb_trace\", pcb_trace_id: e37.pcb_trace_id, source_trace_id: t4, route: e37.route.map((e38) =\u003e {\n if (e38.route_type === \"wire\") {\n if (!tR(e38.layer))\n return null;\n const t5 = \"start_pcb_port_id\" in e38 \u0026\u0026 typeof e38.start_pcb_port_id == \"string\" ? e38.start_pcb_port_id : undefined, n3 = \"end_pcb_port_id\" in e38 \u0026\u0026 typeof e38.end_pcb_port_id == \"string\" ? e38.end_pcb_port_id : undefined;\n return { route_type: \"wire\", x: e38.x, y: e38.y, width: e38.width, layer: e38.layer, ...t5 ? { start_pcb_port_id: t5 } : {}, ...n3 ? { end_pcb_port_id: n3 } : {} };\n }\n return e38.route_type === \"via\" \u0026\u0026 tR(e38.from_layer) \u0026\u0026 tR(e38.to_layer) ? { route_type: \"via\", x: e38.x, y: e38.y, from_layer: e38.from_layer, to_layer: e38.to_layer } : null;\n }).filter((e38) =\u003e e38 !== null) };\n }(e36, t3));\n }) : t2.forEach((e36, t3) =\u003e {\n const n3 = function(e37, t4, n4, o4, i4 = 0.1) {\n const r4 = [];\n if (!e37.jumpers || e37.jumpers.length === 0)\n return [{ type: \"pcb_trace\", pcb_trace_id: t4, source_trace_id: n4, route: e37.route.map((t5, n5) =\u003e {\n const r5 = n5 === 0, s4 = n5 === e37.route.length - 1;\n return { route_type: \"wire\", x: t5.x, y: t5.y, width: t5.traceThickness ?? i4, layer: Co(t5.z, o4), ...r5 \u0026\u0026 t5.pcb_port_id ? { start_pcb_port_id: t5.pcb_port_id } : {}, ...s4 \u0026\u0026 t5.pcb_port_id ? { end_pcb_port_id: t5.pcb_port_id } : {} };\n }) }];\n const s3 = [];\n for (const t5 of e37.jumpers) {\n let n5 = -1, o5 = -1;\n for (let i5 = 0;i5 \u003c e37.route.length; i5++) {\n const r5 = e37.route[i5];\n Math.abs(r5.x - t5.start.x) \u003c 0.01 \u0026\u0026 Math.abs(r5.y - t5.start.y) \u003c 0.01 \u0026\u0026 (n5 = i5), Math.abs(r5.x - t5.end.x) \u003c 0.01 \u0026\u0026 Math.abs(r5.y - t5.end.y) \u003c 0.01 \u0026\u0026 (o5 = i5);\n }\n n5 !== -1 \u0026\u0026 o5 !== -1 \u0026\u0026 (n5 \u003e o5 \u0026\u0026 ([n5, o5] = [o5, n5]), s3.push({ startIdx: n5, endIdx: o5 }));\n }\n s3.sort((e38, t5) =\u003e e38.startIdx - t5.startIdx);\n let a4 = 0, c4 = 0;\n for (const { startIdx: l4, endIdx: h3 } of s3) {\n if (l4 \u003e= a4) {\n const s4 = e37.route.slice(a4, l4 + 1);\n s4.length \u003e 0 \u0026\u0026 (r4.push({ type: \"pcb_trace\", pcb_trace_id: `${t4}_${c4}`, source_trace_id: n4, route: s4.map((e38, t5) =\u003e {\n const n5 = t5 === 0 \u0026\u0026 a4 === 0;\n return { route_type: \"wire\", x: e38.x, y: e38.y, width: e38.traceThickness ?? i4, layer: Co(e38.z, o4), ...n5 \u0026\u0026 e38.pcb_port_id ? { start_pcb_port_id: e38.pcb_port_id } : {} };\n }) }), c4++);\n }\n a4 = h3;\n }\n if (a4 \u003c e37.route.length) {\n const s4 = e37.route.slice(a4);\n if (s4.length \u003e 0) {\n const e38 = true;\n r4.push({ type: \"pcb_trace\", pcb_trace_id: `${t4}_${c4}`, source_trace_id: n4, route: s4.map((t5, n5) =\u003e {\n const r5 = e38 \u0026\u0026 n5 === s4.length - 1;\n return { route_type: \"wire\", x: t5.x, y: t5.y, width: t5.traceThickness ?? i4, layer: Co(t5.z, o4), ...r5 \u0026\u0026 t5.pcb_port_id ? { end_pcb_port_id: t5.pcb_port_id } : {} };\n }) });\n }\n }\n return r4;\n }(e36, `trace_${t3}`, JN(f2, e36.connectionName) ?? e36.connectionName, c3.layerCount, o3);\n m2.push(...n3);\n })), m2;\n}\nvar aR = (e35) =\u003e {\n const t2 = e35.filter((e36) =\u003e e36.type === \"pcb_port\"), n2 = e35.filter((e36) =\u003e e36.type === \"pcb_smtpad\"), o3 = e35.filter((e36) =\u003e e36.type === \"pcb_trace\");\n for (const e36 of o3)\n for (const [o4, i3] of e36.route.entries()) {\n if (i3.route_type !== \"wire\")\n continue;\n const r3 = o4 === 0 \u0026\u0026 !i3.start_pcb_port_id, s2 = o4 === e36.route.length - 1 \u0026\u0026 !i3.end_pcb_port_id;\n if (!r3 \u0026\u0026 !s2)\n continue;\n const a3 = t2.find((e37) =\u003e e37.layers.includes(i3.layer) \u0026\u0026 Math.hypot(e37.x - i3.x, e37.y - i3.y) \u003c 0.01);\n let c3 = a3?.pcb_port_id;\n if (!c3) {\n const e37 = n2.find((e38) =\u003e {\n if (e38.layer !== i3.layer)\n return false;\n if (e38.shape === \"rect\") {\n const t3 = (i3.width || 0) / 2;\n return Math.abs(i3.x - e38.x) \u003c e38.width / 2 + t3 \u0026\u0026 Math.abs(i3.y - e38.y) \u003c e38.height / 2 + t3;\n }\n return e38.shape === \"circle\" \u0026\u0026 Math.hypot(i3.x - e38.x, i3.y - e38.y) \u003c e38.radius;\n });\n c3 = e37?.pcb_port_id;\n }\n c3 \u0026\u0026 (r3 \u0026\u0026 (i3.start_pcb_port_id = c3), s2 \u0026\u0026 (i3.end_pcb_port_id = c3));\n }\n};\nvar cR = new WeakMap;\nvar lR = (e35, t2 = {}) =\u003e {\n const n2 = t2.board ?? e35.find((e36) =\u003e e36.type === \"pcb_board\");\n if (!n2)\n return [];\n let o3 = cR.get(n2);\n if (!o3) {\n let e36;\n if (n2.outline?.length)\n e36 = n2.outline;\n else {\n if (!n2.center || typeof n2.width != \"number\" || typeof n2.height != \"number\")\n return [];\n e36 = [{ x: n2.center.x - n2.width / 2, y: n2.center.y - n2.height / 2 }, { x: n2.center.x + n2.width / 2, y: n2.center.y - n2.height / 2 }, { x: n2.center.x + n2.width / 2, y: n2.center.y + n2.height / 2 }, { x: n2.center.x - n2.width / 2, y: n2.center.y + n2.height / 2 }];\n }\n o3 = e36.map((t3, n3) =\u003e ({ start: t3, end: e36[(n3 + 1) % e36.length] })), cR.set(n2, o3);\n }\n const i3 = t2.margin ?? n2.min_board_edge_clearance ?? 0.2, r3 = [];\n for (const t3 of e35)\n if (t3.type === \"pcb_trace\")\n for (let e36 = 0;e36 \u003c t3.route.length - 1; e36++) {\n const n3 = t3.route[e36], s2 = t3.route[e36 + 1];\n if (n3.route_type !== \"wire\" || s2.route_type !== \"wire\")\n continue;\n const a3 = n3.width ?? s2.width ?? 0.1;\n let c3 = Number.POSITIVE_INFINITY;\n for (const e37 of o3)\n c3 = Math.min(c3, we(n3, s2, e37.start, e37.end));\n const l3 = a3 / 2 + i3;\n c3 \u003c l3 \u0026\u0026 r3.push({ type: \"pcb_trace_error\", error_type: \"pcb_trace_error\", pcb_trace_error_id: `trace_too_close_to_board_${t3.pcb_trace_id}_segment_${e36}`, message: `Trace too close to board edge (${c3.toFixed(3)}mm \u003c ${l3.toFixed(3)}mm required, margin: ${i3}mm)`, pcb_trace_id: t3.pcb_trace_id, source_trace_id: t3.source_trace_id || \"\", center: { x: (n3.x + s2.x) / 2, y: (n3.y + s2.y) / 2 }, pcb_component_ids: [], pcb_port_ids: [] });\n }\n return r3;\n};\nvar hR = 0.1;\nvar dR = 0.1;\nvar uR = {};\nc(uR, { all_layers: () =\u003e fE, any_circuit_element: () =\u003e vL, any_soup_element: () =\u003e IL, any_source_component: () =\u003e aE, asset: () =\u003e qR, base_circuit_json_error: () =\u003e uT, battery_capacity: () =\u003e kR, brep_shape: () =\u003e vA, cadModelDefaultDirectionMap: () =\u003e fD, cad_cable: () =\u003e xD, cad_collision_error: () =\u003e yD, cad_component: () =\u003e _D, cad_model_axis_directions: () =\u003e gD, cad_model_formats: () =\u003e mD, cad_reference_surface: () =\u003e CD, capacitance: () =\u003e IR, circle_shape: () =\u003e YR, circuit_json_footprint_load_error: () =\u003e zk, current: () =\u003e NR, distance: () =\u003e wR, duration_ms: () =\u003e RR, experiment_type: () =\u003e LD, external_footprint_load_error: () =\u003e Lk, frequency: () =\u003e MR, getRotationBetweenPcbPin1Locations: () =\u003e wA, getSimulationReturnCurrentGridJsonSchema: () =\u003e _L, getZodPrefixedIdWithDefault: () =\u003e GR, inductance: () =\u003e SR, insertionDirectionToCanonical: () =\u003e IA, insertionDirectionToVector: () =\u003e SA, insertion_direction: () =\u003e CA, kicadAt: () =\u003e JR, kicadEffects: () =\u003e KR, kicadFont: () =\u003e QR, kicadFootprintAttributes: () =\u003e nT, kicadFootprintMetadata: () =\u003e rT, kicadFootprintModel: () =\u003e iT, kicadFootprintPad: () =\u003e oT, kicadFootprintProperties: () =\u003e tT, kicadProperty: () =\u003e eT, kicadSymbolEffects: () =\u003e cT, kicadSymbolMetadata: () =\u003e dT, kicadSymbolPinNames: () =\u003e aT, kicadSymbolPinNumbers: () =\u003e sT, kicadSymbolProperties: () =\u003e hT, kicadSymbolProperty: () =\u003e lT, layer_ref: () =\u003e yE, layer_string: () =\u003e _E, length: () =\u003e PR, manufacturing_drc_properties: () =\u003e EA, ms: () =\u003e ER, ninePointAnchor: () =\u003e UR, parseAndConvertSiUnit: () =\u003e bR, pcbRenderLayer: () =\u003e ZR, pcb_autorouting_error: () =\u003e Fk, pcb_bend: () =\u003e GO, pcb_board: () =\u003e VO, pcb_breakout_point: () =\u003e Gk, pcb_bus_length_skew_error: () =\u003e AO, pcb_bus_routing_constraint_error: () =\u003e LO, pcb_bus_routing_constraint_warning: () =\u003e BO, pcb_component: () =\u003e AA, pcb_component_invalid_layer_error: () =\u003e iD, pcb_component_missing_courtyard_warning: () =\u003e Hk, pcb_component_not_on_board_edge_error: () =\u003e oD, pcb_component_outside_board_error: () =\u003e nD, pcb_connector_not_in_accessible_orientation_warning: () =\u003e Xk, pcb_copper_pour: () =\u003e tD, pcb_copper_pour_brep: () =\u003e Kk, pcb_copper_pour_polygon: () =\u003e eD, pcb_copper_pour_rect: () =\u003e Qk, pcb_copper_text: () =\u003e ck, pcb_courtyard_circle: () =\u003e uD, pcb_courtyard_outline: () =\u003e hD, pcb_courtyard_overlap_error: () =\u003e Pk, pcb_courtyard_pill: () =\u003e pD, pcb_courtyard_polygon: () =\u003e dD, pcb_courtyard_rect: () =\u003e lD, pcb_cutout: () =\u003e kk, pcb_cutout_circle: () =\u003e Ek, pcb_cutout_path: () =\u003e Ok, pcb_cutout_polygon: () =\u003e Ak, pcb_cutout_rect: () =\u003e Tk, pcb_debug_line: () =\u003e DA, pcb_debug_object: () =\u003e zA, pcb_debug_object_base: () =\u003e OA, pcb_debug_point: () =\u003e LA, pcb_debug_rect: () =\u003e kA, pcb_fabrication_note_dimension: () =\u003e yk, pcb_fabrication_note_path: () =\u003e fk, pcb_fabrication_note_rect: () =\u003e _k, pcb_fabrication_note_text: () =\u003e gk, pcb_fabricator_extra_charge_warning: () =\u003e Wk, pcb_footprint_overlap_error: () =\u003e Ck, pcb_ground_plane: () =\u003e Uk, pcb_ground_plane_region: () =\u003e Zk, pcb_group: () =\u003e Bk, pcb_hole: () =\u003e qA, pcb_hole_circle_or_square_shape: () =\u003e XA, pcb_hole_circle_shape: () =\u003e FA, pcb_hole_oval_shape: () =\u003e VA, pcb_hole_pill_shape: () =\u003e GA, pcb_hole_rect_shape: () =\u003e $A, pcb_hole_rotated_pill_shape: () =\u003e ZA, pcb_keepout: () =\u003e wk, pcb_keepout_outline: () =\u003e Mk, pcb_keepout_overlap_warning: () =\u003e Nk, pcb_manual_edit_conflict_warning: () =\u003e $k, pcb_missing_footprint_error: () =\u003e Dk, pcb_net: () =\u003e XO, pcb_note_dimension: () =\u003e Sk, pcb_note_line: () =\u003e Ik, pcb_note_path: () =\u003e vk, pcb_note_rect: () =\u003e xk, pcb_note_text: () =\u003e bk, pcb_packing_error: () =\u003e nk, pcb_pad_pad_clearance_error: () =\u003e aD, pcb_pad_trace_clearance_error: () =\u003e cD, pcb_panel: () =\u003e ek, pcb_panelization_placement_error: () =\u003e ok, pcb_pin1_location: () =\u003e PA, pcb_placement_error: () =\u003e tk, pcb_plated_hole: () =\u003e oO, pcb_port: () =\u003e iO, pcb_port_not_connected_error: () =\u003e YO, pcb_port_not_matched_error: () =\u003e $O, pcb_preflight_routing_error: () =\u003e jk, pcb_route_hint: () =\u003e NA, pcb_route_hints: () =\u003e RA, pcb_silkscreen_circle: () =\u003e hk, pcb_silkscreen_graphic: () =\u003e pk, pcb_silkscreen_graphic_brep: () =\u003e uk, pcb_silkscreen_line: () =\u003e rk, pcb_silkscreen_oval: () =\u003e dk, pcb_silkscreen_path: () =\u003e sk, pcb_silkscreen_pill: () =\u003e mk, pcb_silkscreen_rect: () =\u003e lk, pcb_silkscreen_text: () =\u003e ak, pcb_smtpad: () =\u003e dO, pcb_smtpad_pill: () =\u003e cO, pcb_solder_paste: () =\u003e bO, pcb_soldermask_opening: () =\u003e vO, pcb_stiffener: () =\u003e KO, pcb_stiffener_polygon: () =\u003e QO, pcb_stiffener_rect: () =\u003e JO, pcb_text: () =\u003e IO, pcb_thermal_spoke: () =\u003e qk, pcb_trace: () =\u003e NO, pcb_trace_error: () =\u003e FO, pcb_trace_hint: () =\u003e ik, pcb_trace_missing_error: () =\u003e jO, pcb_trace_route_point: () =\u003e wO, pcb_trace_route_point_through_pad: () =\u003e MO, pcb_trace_route_point_via: () =\u003e PO, pcb_trace_route_point_wire: () =\u003e CO, pcb_trace_style_warning: () =\u003e TO, pcb_trace_too_long_error: () =\u003e EO, pcb_trace_too_long_warning: () =\u003e OO, pcb_trace_too_many_vias_warning: () =\u003e kO, pcb_trace_warning: () =\u003e RO, pcb_via: () =\u003e HO, pcb_via_clearance_error: () =\u003e rD, pcb_via_trace_clearance_error: () =\u003e sD, point: () =\u003e DR, point3: () =\u003e zR, point_with_bulge: () =\u003e bA, polygon_shape: () =\u003e VR, port_arrangement: () =\u003e BE, position: () =\u003e LR, position3: () =\u003e BR, rect_shape: () =\u003e XR, resistance: () =\u003e vR, ring: () =\u003e xA, rotated_rect_shape: () =\u003e HR, rotation: () =\u003e OR, route_hint_point: () =\u003e TA, schematic_arc: () =\u003e VE, schematic_box: () =\u003e OE, schematic_circle: () =\u003e HE, schematic_component: () =\u003e FE, schematic_component_overlap_warning: () =\u003e aA, schematic_component_port_arrangement_by_sides: () =\u003e zE, schematic_component_port_arrangement_by_size: () =\u003e LE, schematic_component_styling_warning: () =\u003e cA, schematic_debug_line: () =\u003e nA, schematic_debug_object: () =\u003e iA, schematic_debug_object_base: () =\u003e eA, schematic_debug_point: () =\u003e oA, schematic_debug_rect: () =\u003e tA, schematic_element_outside_sheet_warning: () =\u003e hA, schematic_error: () =\u003e QE, schematic_graphic: () =\u003e uA, schematic_group: () =\u003e pA, schematic_layout_error: () =\u003e KE, schematic_line: () =\u003e YE, schematic_manual_edit_conflict_warning: () =\u003e sA, schematic_missing_sheet_warning: () =\u003e yA, schematic_net_label: () =\u003e JE, schematic_path: () =\u003e kE, schematic_pin_styles: () =\u003e DE, schematic_port: () =\u003e qE, schematic_rect: () =\u003e XE, schematic_sheet: () =\u003e _A, schematic_sheet_size: () =\u003e fA, schematic_sheet_styling_warning: () =\u003e lA, schematic_symbol: () =\u003e $E, schematic_table: () =\u003e mA, schematic_table_cell: () =\u003e gA, schematic_text: () =\u003e ZE, schematic_text_part: () =\u003e UE, schematic_trace: () =\u003e WE, schematic_voltage_probe: () =\u003e rA, simulation_ac_current_source: () =\u003e AD, simulation_ac_sweep_current_graph: () =\u003e tL, simulation_ac_sweep_voltage_graph: () =\u003e eL, simulation_ac_voltage_source: () =\u003e ND, simulation_complex_sample: () =\u003e KD, simulation_current_probe: () =\u003e HD, simulation_current_source: () =\u003e OD, simulation_dc_current_source: () =\u003e ED, simulation_dc_operating_point_current: () =\u003e qD, simulation_dc_operating_point_voltage: () =\u003e ZD, simulation_dc_sweep_current_graph: () =\u003e QD, simulation_dc_sweep_unit: () =\u003e kD, simulation_dc_sweep_voltage_graph: () =\u003e JD, simulation_dc_voltage_source: () =\u003e wD, simulation_experiment: () =\u003e BD, simulation_op_amp: () =\u003e nL, simulation_oscilloscope_trace: () =\u003e rL, simulation_parameter_sweep: () =\u003e UD, simulation_parameter_sweep_coordinate: () =\u003e FD, simulation_parameter_type: () =\u003e WD, simulation_parameter_unit: () =\u003e DD, simulation_pcb_return_current_field: () =\u003e mL, simulation_pcb_return_current_heatmap: () =\u003e yL, simulation_pcb_return_current_marker: () =\u003e xL, simulation_pcb_return_current_result: () =\u003e hL, simulation_return_current_contact: () =\u003e aL, simulation_return_current_excitation: () =\u003e lL, simulation_return_current_field_asset: () =\u003e uL, simulation_return_current_grid_json: () =\u003e fL, simulation_return_current_image_asset: () =\u003e pL, simulation_spice_subcircuit: () =\u003e oL, simulation_switch: () =\u003e YD, simulation_terminal_port: () =\u003e cL, simulation_transient_current_graph: () =\u003e $D, simulation_transient_voltage_graph: () =\u003e jD, simulation_unknown_experiment_error: () =\u003e VD, simulation_voltage_probe: () =\u003e XD, simulation_voltage_source: () =\u003e RD, size: () =\u003e FR, source_ambiguous_port_reference: () =\u003e mE, source_board: () =\u003e pE, source_bus: () =\u003e EE, source_component_availability_warning: () =\u003e tE, source_component_base: () =\u003e mT, source_component_internal_connection: () =\u003e lE, source_component_misconfigured_error: () =\u003e rE, source_component_pins_underspecified_warning: () =\u003e CE, source_confusing_net_name_warning: () =\u003e NE, source_failed_to_create_component_error: () =\u003e UT, source_group: () =\u003e dE, source_i2c_misconfigured_error: () =\u003e iE, source_interconnect: () =\u003e oE, source_invalid_component_property_error: () =\u003e ZT, source_manually_placed_via: () =\u003e xE, source_missing_manufacturer_part_number_warning: () =\u003e KT, source_missing_property_error: () =\u003e GT, source_motor: () =\u003e CT, source_net: () =\u003e uE, source_no_ground_pin_defined_warning: () =\u003e SE, source_no_power_pin_defined_warning: () =\u003e IE, source_part_not_found_warning: () =\u003e wE, source_pcb_ground_plane: () =\u003e gE, source_pin_attributes: () =\u003e TT, source_pin_missing_trace_warning: () =\u003e QT, source_pin_must_be_connected_error: () =\u003e PE, source_port: () =\u003e cE, source_printed_part: () =\u003e IT, source_project_metadata: () =\u003e WT, source_property_ignored_warning: () =\u003e JT, source_refdes_convention_warning: () =\u003e eE, source_runtime_error: () =\u003e AE, source_simple_ammeter: () =\u003e NT, source_simple_battery: () =\u003e ET, source_simple_capacitor: () =\u003e gT, source_simple_chip: () =\u003e vT, source_simple_connector: () =\u003e BT, source_simple_connector_standards: () =\u003e zT, source_simple_crystal: () =\u003e DT, source_simple_current_source: () =\u003e MT, source_simple_diode: () =\u003e _T, source_simple_fiducial: () =\u003e yT, source_simple_fuse: () =\u003e wT, source_simple_ground: () =\u003e xT, source_simple_inductor: () =\u003e AT, source_simple_led: () =\u003e bT, source_simple_mosfet: () =\u003e XT, source_simple_op_amp: () =\u003e HT, source_simple_pin_header: () =\u003e LT, source_simple_pinout: () =\u003e FT, source_simple_potentiometer: () =\u003e kT, source_simple_power_source: () =\u003e PT, source_simple_push_button: () =\u003e OT, source_simple_resistor: () =\u003e fT, source_simple_resonator: () =\u003e jT, source_simple_switch: () =\u003e VT, source_simple_test_point: () =\u003e YT, source_simple_transistor: () =\u003e $T, source_simple_voltage_probe: () =\u003e nE, source_simple_voltage_source: () =\u003e sE, source_subassembly: () =\u003e ST, source_trace: () =\u003e hE, source_trace_not_connected_error: () =\u003e qT, source_unnamed_trace_warning: () =\u003e vE, spice_simulation_options: () =\u003e zD, standard_shape: () =\u003e WR, supplier_footprint_mismatch_warning: () =\u003e Vk, supplier_name: () =\u003e pT, time: () =\u003e TR, timestamp: () =\u003e AR, unknown_error_finding_part: () =\u003e ME, visible_layer: () =\u003e bE, voltage: () =\u003e CR, wave_shape: () =\u003e PD });\nvar pR = (e35) =\u003e {\n const t2 = Math.round(1000 * e35) / 1000;\n return `${Number(t2.toFixed(3))}mm`;\n};\nvar mR = new Map([[\"T\", 1000000000000], [\"G\", 1e9], [\"M\", 1e6], [\"K\", 1000], [\"k\", 1000], [\"\", 1], [\"m\", 0.001], [\"µ\", 0.000001], [\"μ\", 0.000001], [\"u\", 0.000001], [\"n\", 0.000000001], [\"p\", 0.000000000001], [\"f\", 0.000000000000001]]);\nvar gR = [...mR.keys()];\nfunction fR(e35) {\n return mR.get(e35);\n}\nvar _R = { Hz: { baseUnit: \"Hz\", variants: { MHz: 1e6, kHz: 1000, Hz: 1 } }, g: { baseUnit: \"g\", variants: { kg: 1000, g: 1 } }, \"Ω\": { baseUnit: \"Ω\", variants: { \"mΩ\": 0.001, mohm: 0.001, mOhm: 0.001, milliohm: 0.001, \"Ω\": 1, ohm: 1, Ohm: 1, \"kΩ\": 1000, \"KΩ\": 1000, kohm: 1000, kOhm: 1000, KOhm: 1000, Kohm: 1000, \"MΩ\": 1e6, Mohm: 1e6, MOhm: 1e6, megohm: 1e6, Megohm: 1e6, \"GΩ\": 1e9, Gohm: 1e9, GOhm: 1e9, \"TΩ\": 1000000000000, Tohm: 1000000000000, TOhm: 1000000000000 } }, V: { baseUnit: \"V\", variants: { mV: 0.001, V: 1, kV: 1000, KV: 1000, MV: 1e6, GV: 1e9, TV: 1000000000000 } }, A: { baseUnit: \"A\", variants: { \"µA\": 0.000001, \"μA\": 0.000001, mA: 0.001, ma: 0.001, A: 1, kA: 1000, MA: 1e6 } }, F: { baseUnit: \"F\", variants: { pF: 0.000000000001, nF: 0.000000001, \"µF\": 0.000001, \"μF\": 0.000001, uF: 0.000001, mF: 0.001, F: 1, kF: 1000, KF: 1000, MF: 1e6 } }, H: { baseUnit: \"H\", variants: { pH: 0.000000000001, nH: 0.000000001, \"µH\": 0.000001, \"μH\": 0.000001, uH: 0.000001, mH: 0.001, H: 1, kH: 1000, KH: 1000, MH: 1e6 } }, ml: { baseUnit: \"ml\", variants: { ml: 1, mL: 1, l: 1000, L: 1000 } }, deg: { baseUnit: \"deg\", variants: { rad: 180 / Math.PI } }, ms: { baseUnit: \"ms\", variants: { fs: 0.000000000001, ps: 0.000000001, ns: 0.000001, us: 0.001, \"µs\": 0.001, \"μs\": 0.001, ms: 1, s: 1000 } }, mm: { baseUnit: \"mm\", variants: { nm: 0.000001, \"µm\": 0.001, \"μm\": 0.001, um: 0.001, mm: 1, cm: 10, dm: 100, m: 1000, km: 1e6, in: 25.4, ft: 304.8, IN: 25.4, FT: 304.8, yd: 914.4, mi: 1609344, mil: 0.0254 } } };\nvar yR = new Set;\nfor (const [e35, t2] of Object.entries(_R)) {\n yR.add(e35);\n for (const e36 of Object.keys(t2.variants))\n yR.add(e36);\n}\nfunction bR(e35, t2) {\n if (e35 == null)\n return { parsedUnit: null, unitOfValue: null, value: null };\n if (typeof e35 == \"string\" \u0026\u0026 e35.match(/^-?[\\d.]+$/))\n return { value: Number.parseFloat(e35), parsedUnit: null, unitOfValue: null };\n if (typeof e35 == \"number\")\n return { value: e35, parsedUnit: null, unitOfValue: null };\n if (typeof e35 == \"object\" \u0026\u0026 \"x\" in e35 \u0026\u0026 \"y\" in e35) {\n const n3 = bR(e35.x, t2), o4 = bR(e35.x, t2), i4 = bR(e35.y, t2);\n return o4.value === null || i4.value === null ? { parsedUnit: null, unitOfValue: null, value: null } : { parsedUnit: n3.parsedUnit, unitOfValue: n3.unitOfValue, value: { x: o4.value, y: i4.value } };\n }\n const n2 = e35.toString().split(\"\").reverse().join(\"\"), o3 = n2.match(/[^\\d\\s]+/)?.[0];\n if (!o3)\n throw new Error(`Could not determine unit: \"${e35}\"`);\n const i3 = o3.split(\"\").reverse().join(\"\"), r3 = e35.slice(0, -i3.length), s2 = fR(i3);\n if (t2 \u0026\u0026 s2 != null)\n return { parsedUnit: null, unitOfValue: t2, value: Number.parseFloat(r3) * s2 };\n if (s2 != null \u0026\u0026 !yR.has(i3))\n return { parsedUnit: null, unitOfValue: null, value: Number.parseFloat(r3) * s2 };\n const { baseUnit: a3, conversionFactor: c3 } = function(e36) {\n for (const t3 of Object.values(_R)) {\n if (e36 in t3.variants)\n return { baseUnit: t3.baseUnit, conversionFactor: t3.variants[e36] };\n for (const [n3, o4] of Object.entries(t3.variants)) {\n if (!e36.endsWith(n3))\n continue;\n const i4 = fR(e36.slice(0, -n3.length));\n if (i4 != null)\n return { baseUnit: t3.baseUnit, conversionFactor: i4 * o4 };\n }\n }\n return { baseUnit: e36, conversionFactor: 1 };\n }(i3);\n return { parsedUnit: i3, unitOfValue: a3, value: c3 * Number.parseFloat(r3) };\n}\nvar xR = gR.filter((e35) =\u003e e35 !== \"\").sort((e35, t2) =\u003e t2.length - e35.length).map((e35) =\u003e e35.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$\u0026\")).join(\"|\");\nvar vR = (new RegExp(`^([+-]?(?:\\\\d+(?:\\\\.\\\\d*)?|\\\\.\\\\d+)(?:[eE][+-]?\\\\d+)?)(?:(${xR}))? dist/index.js - ShiboSoftwareDev/cc2340r5-reference-design - tscircuit ), Wa.string().or(Wa.number()).transform((e35) =\u003e bR(e35, \"Ω\").value));\nvar IR = Wa.string().or(Wa.number()).transform((e35) =\u003e bR(e35, \"F\").value).transform((e35) =\u003e Number.parseFloat(e35.toPrecision(12)));\nvar SR = Wa.string().or(Wa.number()).transform((e35) =\u003e bR(e35, \"H\").value);\nvar CR = Wa.string().or(Wa.number()).transform((e35) =\u003e bR(e35, \"V\").value);\nvar PR = Wa.string().or(Wa.number()).transform((e35) =\u003e bR(e35).value);\nvar MR = Wa.string().or(Wa.number()).transform((e35) =\u003e bR(e35, \"Hz\").value);\nvar wR = PR;\nvar NR = Wa.string().or(Wa.number()).transform((e35) =\u003e bR(e35, \"A\").value);\nvar RR = Wa.string().or(Wa.number()).transform((e35) =\u003e bR(e35).value);\nvar TR = RR;\nvar ER = RR;\nvar AR = Wa.string().datetime();\nvar OR = Wa.string().or(Wa.number()).transform((e35) =\u003e typeof e35 == \"number\" ? e35 : e35.endsWith(\"deg\") ? Number.parseFloat(e35.split(\"deg\")[0]) : e35.endsWith(\"rad\") ? 180 * Number.parseFloat(e35.split(\"rad\")[0]) / Math.PI : Number.parseFloat(e35));\nvar kR = Wa.number().or(Wa.string().endsWith(\"mAh\")).transform((e35) =\u003e {\n if (typeof e35 == \"string\") {\n const t2 = e35.replace(\"mAh\", \"\"), n2 = Number.parseFloat(t2);\n if (Number.isNaN(n2))\n throw new Error(\"Invalid capacity\");\n return n2;\n }\n return e35;\n}).describe(\"Battery capacity in mAh\");\nvar DR = Wa.object({ x: wR, y: wR });\nvar LR = DR;\nvar zR = Wa.object({ x: wR, y: wR, z: wR });\nvar BR = zR;\nvar FR = Wa.object({ width: Wa.number(), height: Wa.number() });\nvar jR = wR.pipe(Wa.number().finite());\nvar $R = wR.pipe(Wa.number().finite().positive());\nvar YR = Wa.object({ shape: Wa.literal(\"circle\"), x: jR, y: jR, radius: $R }).strict();\nvar XR = Wa.object({ shape: Wa.literal(\"rect\"), x: jR, y: jR, width: $R, height: $R }).strict();\nvar HR = XR.extend({ shape: Wa.literal(\"rotated_rect\"), ccw_rotation: OR.pipe(Wa.number().finite()) });\nvar VR = Wa.object({ shape: Wa.literal(\"polygon\"), points: Wa.array(DR.extend({ x: jR, y: jR })).min(3).refine((e35) =\u003e {\n const t2 = e35.reduce((t3, n2, o3) =\u003e {\n const i3 = e35[(o3 + 1) % e35.length];\n return t3 + n2.x * i3.y - i3.x * n2.y;\n }, 0);\n return Number.isFinite(t2) \u0026\u0026 t2 !== 0;\n}, \"Polygon boundary must enclose a nonzero area\") }).strict();\nvar WR = Wa.discriminatedUnion(\"shape\", [YR, XR, HR, VR]);\nvar GR = (e35) =\u003e Wa.string().optional().default(() =\u003e `${e35}_${((e36) =\u003e {\n const t2 = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\";\n return Array.from({ length: e36 }, () =\u003e t2[Math.floor(62 * Math.random())]).join(\"\");\n})(10)}`);\nvar UR = Wa.enum([\"top_left\", \"top_center\", \"top_right\", \"center_left\", \"center\", \"center_right\", \"bottom_left\", \"bottom_center\", \"bottom_right\"]);\nvar ZR = Wa.enum([\"top_silkscreen\", \"bottom_silkscreen\", \"top_copper\", \"bottom_copper\", \"top_soldermask\", \"bottom_soldermask\", \"top_fabrication_note\", \"bottom_fabrication_note\", \"top_user_note\", \"bottom_user_note\", \"top_courtyard\", \"bottom_courtyard\", \"inner1_copper\", \"inner2_copper\", \"inner3_copper\", \"inner4_copper\", \"inner5_copper\", \"inner6_copper\", \"inner7_copper\", \"inner8_copper\", \"edge_cuts\", \"drill\"]);\nvar qR = Wa.object({ project_relative_path: Wa.string(), url: Wa.string(), mimetype: Wa.string() });\nvar JR = DR.extend({ rotation: OR.optional() });\nvar QR = Wa.object({ size: DR.optional(), thickness: wR.optional() });\nvar KR = Wa.object({ font: QR.optional() });\nvar eT = Wa.object({ value: Wa.string(), at: JR.optional(), layer: Wa.string().optional(), uuid: Wa.string().optional(), hide: Wa.boolean().optional(), effects: KR.optional() });\nvar tT = Wa.object({ Reference: eT.optional(), Value: eT.optional(), Datasheet: eT.optional(), Description: eT.optional() });\nvar nT = Wa.object({ through_hole: Wa.boolean().optional(), smd: Wa.boolean().optional(), exclude_from_pos_files: Wa.boolean().optional(), exclude_from_bom: Wa.boolean().optional() });\nvar oT = Wa.object({ name: Wa.string(), type: Wa.string(), shape: Wa.string().optional(), at: JR.optional(), size: DR.optional(), drill: wR.optional(), layers: Wa.array(Wa.string()).optional(), removeUnusedLayers: Wa.boolean().optional(), uuid: Wa.string().optional() });\nvar iT = Wa.object({ path: Wa.string(), offset: zR.optional(), scale: zR.optional(), rotate: zR.optional() });\nvar rT = Wa.object({ footprintName: Wa.string().optional(), version: Wa.union([Wa.number(), Wa.string()]).optional(), generator: Wa.string().optional(), generatorVersion: Wa.union([Wa.number(), Wa.string()]).optional(), layer: Wa.string().optional(), properties: tT.optional(), attributes: nT.optional(), pads: Wa.array(oT).optional(), embeddedFonts: Wa.boolean().optional(), model: iT.optional() });\nvar sT = Wa.object({ hide: Wa.boolean().optional() });\nvar aT = Wa.object({ offset: wR.optional(), hide: Wa.boolean().optional() });\nvar cT = Wa.object({ font: QR.optional(), justify: Wa.union([Wa.string(), Wa.array(Wa.string())]).optional(), hide: Wa.boolean().optional() });\nvar lT = Wa.object({ value: Wa.string(), id: Wa.union([Wa.number(), Wa.string()]).optional(), at: JR.optional(), effects: cT.optional() });\nvar hT = Wa.object({ Reference: lT.optional(), Value: lT.optional(), Footprint: lT.optional(), Datasheet: lT.optional(), Description: lT.optional(), ki_keywords: lT.optional(), ki_fp_filters: lT.optional() });\nvar dT = Wa.object({ symbolName: Wa.string().optional(), extends: Wa.string().optional(), pinNumbers: sT.optional(), pinNames: aT.optional(), excludeFromSim: Wa.boolean().optional(), inBom: Wa.boolean().optional(), onBoard: Wa.boolean().optional(), properties: hT.optional(), embeddedFonts: Wa.boolean().optional() });\nvar uT = Wa.object({ error_type: Wa.string(), message: Wa.string(), is_fatal: Wa.boolean().optional() });\nvar pT = Wa.enum([\"jlcpcb\", \"macrofab\", \"pcbway\", \"digikey\", \"mouser\", \"lcsc\"]);\nvar mT = Wa.object({ type: Wa.literal(\"source_component\"), ftype: Wa.string().optional(), source_component_id: Wa.string(), name: Wa.string(), manufacturer_part_number: Wa.string().optional(), supplier_part_numbers: Wa.record(pT, Wa.array(Wa.string())).optional(), display_value: Wa.string().optional(), display_name: Wa.string().optional(), are_pins_interchangeable: Wa.boolean().optional(), internally_connected_source_port_ids: Wa.array(Wa.array(Wa.string())).optional(), source_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() });\nvar gT = mT.extend({ ftype: Wa.literal(\"simple_capacitor\"), capacitance: IR, max_voltage_rating: CR.optional(), display_capacitance: Wa.string().optional(), max_decoupling_trace_length: wR.optional() });\nvar fT = mT.extend({ ftype: Wa.literal(\"simple_resistor\"), resistance: vR, display_resistance: Wa.string().optional() });\nvar _T = mT.extend({ ftype: Wa.literal(\"simple_diode\") });\nvar yT = mT.extend({ ftype: Wa.literal(\"simple_fiducial\") });\nvar bT = _T.extend({ ftype: Wa.literal(\"simple_led\"), color: Wa.string().optional(), wavelength: Wa.string().optional() });\nvar xT = mT.extend({ ftype: Wa.literal(\"simple_ground\") });\nvar vT = mT.extend({ ftype: Wa.literal(\"simple_chip\") });\nvar IT = mT.extend({ ftype: Wa.literal(\"printedpart\"), material: Wa.enum([\"pla\", \"petg\", \"nylon\"]).optional(), color: Wa.string().trim().min(1).optional() });\nvar ST = mT.extend({ ftype: Wa.literal(\"subassembly\") });\nvar CT = mT.extend({ ftype: Wa.literal(\"motor\") });\nvar PT = mT.extend({ ftype: Wa.literal(\"simple_power_source\"), voltage: CR });\nvar MT = mT.extend({ ftype: Wa.literal(\"simple_current_source\"), current: NR, frequency: MR.optional(), peak_to_peak_current: NR.optional(), wave_shape: Wa.enum([\"sine\", \"square\", \"triangle\", \"sawtooth\", \"dc\"]).optional().default(\"dc\"), phase: Wa.number().optional(), duty_cycle: Wa.number().min(0).max(1).optional() });\nvar wT = mT.extend({ ftype: Wa.literal(\"simple_fuse\"), current_rating_amps: Wa.number().describe(\"Nominal current in amps the fuse is rated for\"), voltage_rating_volts: Wa.number().describe(\"Voltage rating in volts, e.g. ±5V would be 5\") });\nvar NT = mT.extend({ ftype: Wa.literal(\"simple_ammeter\") });\nvar RT = Wa.union([Wa.number(), Wa.string().trim().regex(/^[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?\\s*(?:[fpnumkKMGTµμ]?V?|V)?$/, \"Expected a scalar voltage, optionally with SI units\")]).pipe(CR).pipe(Wa.number().finite());\nvar TT = Wa.object({ is_input: Wa.boolean().optional(), is_output: Wa.boolean().optional(), is_bidirectional: Wa.boolean().optional(), is_passive: Wa.boolean().optional(), can_use_tri_state: Wa.boolean().optional(), is_using_tri_state: Wa.boolean().optional(), can_use_open_collector: Wa.boolean().optional(), is_using_open_collector: Wa.boolean().optional(), can_use_open_emitter: Wa.boolean().optional(), is_using_open_emitter: Wa.boolean().optional(), is_gpio: Wa.boolean().optional(), highlight_color: Wa.string().optional(), must_be_connected: Wa.boolean().optional(), provides_power: Wa.boolean().optional(), requires_power: Wa.boolean().optional(), provides_ground: Wa.boolean().optional(), requires_ground: Wa.boolean().optional(), provides_voltage: RT.optional(), requires_voltage: RT.optional(), required_voltage_tolerance: Wa.number().finite().min(0).max(1).optional(), do_not_connect: Wa.boolean().optional(), include_in_board_pinout: Wa.boolean().optional(), can_use_internal_pullup: Wa.boolean().optional(), is_using_internal_pullup: Wa.boolean().optional(), needs_external_pullup: Wa.boolean().optional(), can_use_internal_pulldown: Wa.boolean().optional(), is_using_internal_pulldown: Wa.boolean().optional(), needs_external_pulldown: Wa.boolean().optional(), can_use_open_drain: Wa.boolean().optional(), is_using_open_drain: Wa.boolean().optional(), can_use_push_pull: Wa.boolean().optional(), is_using_push_pull: Wa.boolean().optional(), should_have_decoupling_capacitor: Wa.boolean().optional(), recommended_decoupling_capacitor_capacitance: Wa.union([Wa.string(), Wa.number()]).optional(), is_configured_for_i2c_sda: Wa.boolean().optional(), is_configured_for_i2c_scl: Wa.boolean().optional(), is_configured_for_spi_mosi: Wa.boolean().optional(), is_configured_for_spi_miso: Wa.boolean().optional(), is_configured_for_spi_sck: Wa.boolean().optional(), is_configured_for_spi_cs: Wa.boolean().optional(), is_configured_for_uart_tx: Wa.boolean().optional(), is_configured_for_uart_rx: Wa.boolean().optional(), supports_i2c_sda: Wa.boolean().optional(), supports_i2c_scl: Wa.boolean().optional(), supports_spi_mosi: Wa.boolean().optional(), supports_spi_miso: Wa.boolean().optional(), supports_spi_sck: Wa.boolean().optional(), supports_spi_cs: Wa.boolean().optional(), supports_uart_tx: Wa.boolean().optional(), supports_uart_rx: Wa.boolean().optional() });\nvar ET = mT.extend({ ftype: Wa.literal(\"simple_battery\"), capacity: kR });\nvar AT = mT.extend({ ftype: Wa.literal(\"simple_inductor\"), inductance: SR, display_inductance: Wa.string().optional(), max_current_rating: Wa.number().optional() });\nvar OT = mT.extend({ ftype: Wa.literal(\"simple_push_button\") });\nvar kT = mT.extend({ ftype: Wa.literal(\"simple_potentiometer\"), max_resistance: vR, display_max_resistance: Wa.string().optional() });\nvar DT = mT.extend({ ftype: Wa.literal(\"simple_crystal\"), frequency: Wa.number().describe(\"Frequency in Hz\"), load_capacitance: Wa.number().optional().describe(\"Load capacitance in pF\"), pin_variant: Wa.enum([\"two_pin\", \"four_pin\"]).optional() });\nvar LT = mT.extend({ ftype: Wa.literal(\"simple_pin_header\"), pin_count: Wa.number(), gender: Wa.enum([\"male\", \"female\"]).optional().default(\"male\") });\nvar zT = [\"usb_c\", \"m2\", \"jst_sh\", \"jst_gh\", \"jst_zh\", \"jst_ph\", \"jst_xh\", \"jst_vh\"];\nvar BT = mT.extend({ ftype: Wa.literal(\"simple_connector\"), standard: Wa.enum(zT).optional(), pin_count: Wa.number().int().positive().optional() });\nvar FT = mT.extend({ ftype: Wa.literal(\"simple_pinout\") });\nvar jT = mT.extend({ ftype: Wa.literal(\"simple_resonator\"), load_capacitance: IR, equivalent_series_resistance: vR.optional(), frequency: MR });\nvar $T = mT.extend({ ftype: Wa.literal(\"simple_transistor\"), transistor_type: Wa.enum([\"npn\", \"pnp\"]) });\nvar YT = mT.extend({ ftype: Wa.literal(\"simple_test_point\"), footprint_variant: Wa.enum([\"pad\", \"through_hole\"]).optional(), pad_shape: Wa.enum([\"rect\", \"circle\"]).optional(), pad_diameter: Wa.union([Wa.number(), Wa.string()]).optional(), hole_diameter: Wa.union([Wa.number(), Wa.string()]).optional(), width: Wa.union([Wa.number(), Wa.string()]).optional(), height: Wa.union([Wa.number(), Wa.string()]).optional() });\nvar XT = mT.extend({ ftype: Wa.literal(\"simple_mosfet\"), channel_type: Wa.enum([\"n\", \"p\"]), mosfet_mode: Wa.enum([\"enhancement\", \"depletion\"]) });\nvar HT = mT.extend({ ftype: Wa.literal(\"simple_op_amp\") });\nvar VT = mT.extend({ ftype: Wa.literal(\"simple_switch\") });\nvar WT = Wa.object({ type: Wa.literal(\"source_project_metadata\"), name: Wa.string().optional(), software_used_string: Wa.string().optional(), project_url: Wa.string().optional(), source_filesystem_md5_hash: Wa.string().optional(), created_at: AR.optional() });\nvar GT = uT.extend({ type: Wa.literal(\"source_missing_property_error\"), source_missing_property_error_id: GR(\"source_missing_property_error\"), source_component_id: Wa.string(), property_name: Wa.string(), subcircuit_id: Wa.string().optional(), error_type: Wa.literal(\"source_missing_property_error\").default(\"source_missing_property_error\") }).describe(\"The source code is missing a property\");\nvar UT = uT.extend({ type: Wa.literal(\"source_failed_to_create_component_error\"), source_failed_to_create_component_error_id: GR(\"source_failed_to_create_component_error\"), error_type: Wa.literal(\"source_failed_to_create_component_error\").default(\"source_failed_to_create_component_error\"), component_name: Wa.string().optional(), subcircuit_id: Wa.string().optional(), parent_source_component_id: Wa.string().optional(), pcb_center: Wa.object({ x: Wa.number().optional(), y: Wa.number().optional() }).optional(), schematic_center: Wa.object({ x: Wa.number().optional(), y: Wa.number().optional() }).optional() }).describe(\"Error emitted when a component fails to be constructed\");\nvar ZT = uT.extend({ type: Wa.literal(\"source_invalid_component_property_error\"), source_invalid_component_property_error_id: GR(\"source_invalid_component_property_error\"), source_component_id: Wa.string(), property_name: Wa.string(), property_value: Wa.unknown().optional(), expected_format: Wa.string().optional(), subcircuit_id: Wa.string().optional(), error_type: Wa.literal(\"source_invalid_component_property_error\").default(\"source_invalid_component_property_error\") }).describe(\"The source component property is invalid\");\nvar qT = uT.extend({ type: Wa.literal(\"source_trace_not_connected_error\"), source_trace_not_connected_error_id: GR(\"source_trace_not_connected_error\"), error_type: Wa.literal(\"source_trace_not_connected_error\").default(\"source_trace_not_connected_error\"), subcircuit_id: Wa.string().optional(), source_group_id: Wa.string().optional(), source_trace_id: Wa.string().optional(), connected_source_port_ids: Wa.array(Wa.string()).optional(), selectors_not_found: Wa.array(Wa.string()).optional() }).describe(\"Occurs when a source trace selector does not match any ports\");\nvar JT = Wa.object({ type: Wa.literal(\"source_property_ignored_warning\"), source_property_ignored_warning_id: GR(\"source_property_ignored_warning\"), source_component_id: Wa.string(), property_name: Wa.string(), subcircuit_id: Wa.string().optional(), error_type: Wa.literal(\"source_property_ignored_warning\").default(\"source_property_ignored_warning\"), message: Wa.string() }).describe(\"The source property was ignored\");\nvar QT = Wa.object({ type: Wa.literal(\"source_pin_missing_trace_warning\"), source_pin_missing_trace_warning_id: GR(\"source_pin_missing_trace_warning\"), warning_type: Wa.literal(\"source_pin_missing_trace_warning\").default(\"source_pin_missing_trace_warning\"), message: Wa.string(), source_component_id: Wa.string(), source_port_id: Wa.string(), subcircuit_id: Wa.string().optional() }).describe(\"Warning emitted when a source component pin is missing a trace connection\");\nvar KT = Wa.object({ type: Wa.literal(\"source_missing_manufacturer_part_number_warning\"), source_missing_manufacturer_part_number_warning_id: GR(\"source_missing_manufacturer_part_number_warning\"), warning_type: Wa.literal(\"source_missing_manufacturer_part_number_warning\").default(\"source_missing_manufacturer_part_number_warning\"), message: Wa.string(), source_component_id: Wa.string(), standard: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe(\"Warning emitted when a source component is missing its manufacturer part number\");\nvar eE = Wa.object({ type: Wa.literal(\"source_refdes_convention_warning\"), source_refdes_convention_warning_id: GR(\"source_refdes_convention_warning\"), warning_type: Wa.literal(\"source_refdes_convention_warning\").default(\"source_refdes_convention_warning\"), message: Wa.string(), source_component_id: Wa.string(), refdes: Wa.string(), source_component_ftype: Wa.string(), expected_prefixes: Wa.array(Wa.string()), actual_prefix: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe(\"Warning emitted when a source component reference designator does not match the component type convention\");\nvar tE = Wa.object({ type: Wa.literal(\"source_component_availability_warning\"), source_component_availability_warning_id: GR(\"source_component_availability_warning\"), warning_type: Wa.literal(\"source_component_availability_warning\").default(\"source_component_availability_warning\"), message: Wa.string(), source_component_id: Wa.string(), subcircuit_id: Wa.string().optional(), supplier_name: pT, supplier_part_numbers: Wa.array(Wa.string()).nonempty() }).describe(\"Warning emitted when no supplier alternative can be confirmed in stock. Availability may be unknown or change over time.\");\nvar nE = mT.extend({ ftype: Wa.literal(\"simple_voltage_probe\") });\nvar oE = mT.extend({ ftype: Wa.literal(\"interconnect\") });\nvar iE = uT.extend({ type: Wa.literal(\"source_i2c_misconfigured_error\"), source_i2c_misconfigured_error_id: GR(\"source_i2c_misconfigured_error\"), error_type: Wa.literal(\"source_i2c_misconfigured_error\").default(\"source_i2c_misconfigured_error\"), source_port_ids: Wa.array(Wa.string()) }).describe(\"Error emitted when incompatible I2C pins (e.g. SDA and SCL) are connected to the same net\");\nvar rE = uT.extend({ type: Wa.literal(\"source_component_misconfigured_error\"), source_component_misconfigured_error_id: GR(\"source_component_misconfigured_error\"), error_type: Wa.literal(\"source_component_misconfigured_error\").default(\"source_component_misconfigured_error\"), source_component_ids: Wa.array(Wa.string()), source_port_ids: Wa.array(Wa.string()).optional() }).describe(\"Error emitted when one or more source components have an invalid or conflicting configuration\");\nvar sE = mT.extend({ ftype: Wa.literal(\"simple_voltage_source\"), voltage: CR, frequency: MR.optional(), peak_to_peak_voltage: CR.optional(), wave_shape: Wa.enum([\"sinewave\", \"square\", \"triangle\", \"sawtooth\"]).optional(), phase: OR.optional(), duty_cycle: Wa.number().optional().describe(\"Duty cycle as a fraction (0 to 1)\"), pulse_delay: ER.optional(), rise_time: ER.optional(), fall_time: ER.optional(), pulse_width: ER.optional(), period: ER.optional() });\nvar aE = Wa.union([fT, gT, _T, yT, bT, xT, vT, IT, ST, CT, PT, MT, NT, ET, AT, OT, kT, DT, LT, BT, FT, jT, VT, $T, YT, XT, HT, wT, nE, oE, sE, WT, GT, ZT, UT, qT, JT, QT, KT, eE, tE, iE, rE]);\nvar cE = Wa.object({ type: Wa.literal(\"source_port\"), pin_number: Wa.number().optional(), port_hints: Wa.array(Wa.string()).optional(), name: Wa.string(), source_port_id: Wa.string(), source_component_id: Wa.string().optional(), source_group_id: Wa.string().optional(), most_frequently_referenced_by_name: Wa.string().optional(), subcircuit_id: Wa.string().optional(), subcircuit_connectivity_map_key: Wa.string().optional() }).merge(TT);\nvar lE = Wa.object({ type: Wa.literal(\"source_component_internal_connection\"), source_component_internal_connection_id: Wa.string(), source_component_id: Wa.string(), source_port_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() });\nvar hE = Wa.object({ type: Wa.literal(\"source_trace\"), source_trace_id: Wa.string(), connected_source_port_ids: Wa.array(Wa.string()), connected_source_net_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional(), subcircuit_connectivity_map_key: Wa.string().optional(), max_length: Wa.number().optional(), max_via_count: Wa.number().int().nonnegative().optional(), name: Wa.string().optional(), min_trace_thickness: Wa.number().optional(), display_name: Wa.string().optional() });\nvar dE = Wa.object({ type: Wa.literal(\"source_group\"), source_group_id: Wa.string(), subcircuit_id: Wa.string().optional(), parent_subcircuit_id: Wa.string().optional(), parent_source_group_id: Wa.string().optional(), is_subcircuit: Wa.boolean().optional(), show_as_schematic_box: Wa.boolean().optional(), name: Wa.string().optional(), was_automatically_named: Wa.boolean().optional() });\nvar uE = Wa.object({ type: Wa.literal(\"source_net\"), source_net_id: Wa.string(), name: Wa.string(), member_source_group_ids: Wa.array(Wa.string()), is_power: Wa.boolean().optional(), is_ground: Wa.boolean().optional(), is_digital_signal: Wa.boolean().optional(), is_analog_signal: Wa.boolean().optional(), is_positive_voltage_source: Wa.boolean().optional(), trace_width: Wa.number().optional(), subcircuit_id: Wa.string().optional(), subcircuit_connectivity_map_key: Wa.string().optional() });\nvar pE = Wa.object({ type: Wa.literal(\"source_board\"), source_board_id: Wa.string(), source_group_id: Wa.string(), title: Wa.string().optional() }).describe(\"Defines a board in the source domain\");\nvar mE = uT.extend({ type: Wa.literal(\"source_ambiguous_port_reference\"), source_ambiguous_port_reference_id: GR(\"source_ambiguous_port_reference\"), error_type: Wa.literal(\"source_ambiguous_port_reference\").default(\"source_ambiguous_port_reference\"), source_port_id: Wa.string().optional(), source_component_id: Wa.string().optional() }).describe(\"Error emitted when a port hint matches multiple non-overlapping pads, making the port reference ambiguous\");\nvar gE = Wa.object({ type: Wa.literal(\"source_pcb_ground_plane\"), source_pcb_ground_plane_id: Wa.string(), source_group_id: Wa.string(), source_net_id: Wa.string(), subcircuit_id: Wa.string().optional() }).describe(\"Defines a ground plane in the source domain\");\nvar fE = [\"top\", \"bottom\", \"inner1\", \"inner2\", \"inner3\", \"inner4\", \"inner5\", \"inner6\", \"inner7\", \"inner8\"];\nvar _E = Wa.enum(fE);\nvar yE = _E.or(Wa.object({ name: _E })).transform((e35) =\u003e typeof e35 == \"string\" ? e35 : e35.name);\nvar bE = Wa.enum([\"top\", \"bottom\"]);\nvar xE = Wa.object({ type: Wa.literal(\"source_manually_placed_via\"), source_manually_placed_via_id: Wa.string(), source_group_id: Wa.string(), source_net_id: Wa.string().min(1).optional(), subcircuit_id: Wa.string().optional(), source_trace_id: Wa.string().optional() }).describe(\"Defines a via that is manually placed in the source domain\");\nvar vE = Wa.object({ type: Wa.literal(\"source_unnamed_trace_warning\"), source_unnamed_trace_warning_id: GR(\"source_unnamed_trace_warning\"), warning_type: Wa.literal(\"source_unnamed_trace_warning\").default(\"source_unnamed_trace_warning\"), message: Wa.string(), source_trace_id: Wa.string(), subcircuit_id: Wa.string().optional() }).describe(\"Warning emitted when a source trace is missing a name\");\nvar IE = Wa.object({ type: Wa.literal(\"source_no_power_pin_defined_warning\"), source_no_power_pin_defined_warning_id: GR(\"source_no_power_pin_defined_warning\"), warning_type: Wa.literal(\"source_no_power_pin_defined_warning\").default(\"source_no_power_pin_defined_warning\"), message: Wa.string(), source_component_id: Wa.string(), source_port_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe(\"Warning emitted when a chip has no source ports with requires_power=true\");\nvar SE = Wa.object({ type: Wa.literal(\"source_no_ground_pin_defined_warning\"), source_no_ground_pin_defined_warning_id: GR(\"source_no_ground_pin_defined_warning\"), warning_type: Wa.literal(\"source_no_ground_pin_defined_warning\").default(\"source_no_ground_pin_defined_warning\"), message: Wa.string(), source_component_id: Wa.string(), source_port_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe(\"Warning emitted when a chip has no source ports marked as ground pins\");\nvar CE = Wa.object({ type: Wa.literal(\"source_component_pins_underspecified_warning\"), source_component_pins_underspecified_warning_id: GR(\"source_component_pins_underspecified_warning\"), warning_type: Wa.literal(\"source_component_pins_underspecified_warning\").default(\"source_component_pins_underspecified_warning\"), message: Wa.string(), source_component_id: Wa.string(), source_port_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe(\"Warning emitted when all ports on a source component are underspecified\");\nvar PE = uT.extend({ type: Wa.literal(\"source_pin_must_be_connected_error\"), source_pin_must_be_connected_error_id: GR(\"source_pin_must_be_connected_error\"), error_type: Wa.literal(\"source_pin_must_be_connected_error\").default(\"source_pin_must_be_connected_error\"), source_component_id: Wa.string(), source_port_id: Wa.string(), subcircuit_id: Wa.string().optional() }).describe(\"Error emitted when a pin with mustBeConnected attribute is not connected to any trace\");\nvar ME = uT.extend({ type: Wa.literal(\"unknown_error_finding_part\"), unknown_error_finding_part_id: GR(\"unknown_error_finding_part\"), error_type: Wa.literal(\"unknown_error_finding_part\").default(\"unknown_error_finding_part\"), source_component_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe(\"Error emitted when an unexpected error occurs while finding a part\");\nvar wE = Wa.object({ type: Wa.literal(\"source_part_not_found_warning\"), source_part_not_found_warning_id: GR(\"source_part_not_found_warning\"), warning_type: Wa.literal(\"source_part_not_found_warning\").default(\"source_part_not_found_warning\"), message: Wa.string(), source_component_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), supplier_name: pT.optional(), manufacturer_part_number: Wa.string().optional(), supplier_part_number: Wa.string().optional(), part_name: Wa.string().optional() }).describe(\"Warning emitted when a requested part can not be found\");\nvar NE = Wa.object({ type: Wa.literal(\"source_confusing_net_name_warning\"), source_confusing_net_name_warning_id: GR(\"source_confusing_net_name_warning\"), warning_type: Wa.literal(\"source_confusing_net_name_warning\").default(\"source_confusing_net_name_warning\"), message: Wa.string(), source_net_ids: Wa.array(Wa.string()).min(2), net_name: Wa.string(), subcircuit_id: Wa.string().optional() }).describe(\"Warning emitted when electrically disconnected source nets share a name\");\nvar RE = Wa.union([Wa.number().nonnegative().finite(), Wa.object({ reference: Wa.literal(\"longest_manhattan\"), source_trace_ids: Wa.array(Wa.string()).min(1).optional(), offset: Wa.number().finite().optional() })]);\nvar TE = Wa.union([Wa.number().positive().finite(), Wa.object({ width_multiplier: Wa.number().positive().finite() })]);\nvar EE = Wa.object({ type: Wa.literal(\"source_bus\"), source_bus_id: Wa.string(), name: Wa.string().optional(), source_trace_ids: Wa.array(Wa.string()).min(1), max_length_skew: Wa.number().nonnegative().finite().optional(), target_impedance: Wa.number().positive().finite().optional(), target_differential_impedance: Wa.number().positive().finite().optional(), differential_pair: Wa.object({ positive_source_trace_id: Wa.string(), negative_source_trace_id: Wa.string(), trace_gap: Wa.number().positive().finite().optional(), max_uncoupled_length: Wa.number().nonnegative().finite().optional() }).optional(), length_match_source_trace_ids: Wa.array(Wa.string()).min(1).optional(), min_length: RE.optional(), max_length: RE.optional(), target_length: RE.optional(), length_tolerance: Wa.number().nonnegative().finite().optional(), pcb_trace_spacing: TE.optional(), pcb_spacing_to_other_signals: TE.optional(), target_impedance_min: Wa.number().positive().finite().optional(), target_impedance_max: Wa.number().positive().finite().optional(), target_differential_impedance_min: Wa.number().positive().finite().optional(), target_differential_impedance_max: Wa.number().positive().finite().optional(), subcircuit_id: Wa.string().optional() });\nvar AE = uT.pick({ message: true, error_type: true }).extend({ type: Wa.literal(\"source_runtime_error\"), source_runtime_error_id: GR(\"source_runtime_error\"), error_type: Wa.literal(\"source_runtime_error\").default(\"source_runtime_error\"), phase_name: Wa.string().optional() }).describe(\"An unexpected runtime failure while generating or validating a circuit\");\nvar OE = Wa.object({ type: Wa.literal(\"schematic_box\"), schematic_sheet_id: Wa.string().optional(), schematic_component_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), width: wR, height: wR, is_dashed: Wa.boolean().default(false), x: wR, y: wR, subcircuit_id: Wa.string().optional() }).describe(\"Draws a box on the schematic\");\nvar kE = Wa.object({ type: Wa.literal(\"schematic_path\"), schematic_path_id: GR(\"schematic_path\"), schematic_sheet_id: Wa.string().optional(), schematic_component_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), fill_color: Wa.string().optional(), is_filled: Wa.boolean().optional(), is_dashed: Wa.boolean().default(false), stroke_width: wR.nullable().optional(), stroke_color: Wa.string().optional(), dash_length: wR.optional(), dash_gap: wR.optional(), points: Wa.array(DR), subcircuit_id: Wa.string().optional() });\nvar DE = Wa.record(Wa.object({ left_margin: PR.optional(), right_margin: PR.optional(), top_margin: PR.optional(), bottom_margin: PR.optional() }));\nvar LE = Wa.object({ left_size: Wa.number(), right_size: Wa.number(), top_size: Wa.number().optional(), bottom_size: Wa.number().optional() });\nvar zE = Wa.object({ left_side: Wa.object({ pins: Wa.array(Wa.number()), direction: Wa.enum([\"top-to-bottom\", \"bottom-to-top\"]).optional() }).optional(), right_side: Wa.object({ pins: Wa.array(Wa.number()), direction: Wa.enum([\"top-to-bottom\", \"bottom-to-top\"]).optional() }).optional(), top_side: Wa.object({ pins: Wa.array(Wa.number()), direction: Wa.enum([\"left-to-right\", \"right-to-left\"]).optional() }).optional(), bottom_side: Wa.object({ pins: Wa.array(Wa.number()), direction: Wa.enum([\"left-to-right\", \"right-to-left\"]).optional() }).optional() });\nvar BE = Wa.union([LE, zE]);\nvar FE = Wa.object({ type: Wa.literal(\"schematic_component\"), size: FR, center: DR, source_component_id: Wa.string().optional(), schematic_component_id: Wa.string(), schematic_sheet_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), pin_spacing: PR.optional(), pin_styles: DE.optional(), box_width: PR.optional(), symbol_name: Wa.string().optional(), port_arrangement: BE.optional(), port_labels: Wa.record(Wa.string()).optional(), symbol_display_value: Wa.string().optional(), subcircuit_id: Wa.string().optional(), schematic_group_id: Wa.string().optional(), is_schematic_group: Wa.boolean().optional(), source_group_id: Wa.string().optional(), is_box_with_pins: Wa.boolean().optional().default(true) });\nvar jE = Wa.object({ kicad_symbol: dT.optional() }).catchall(Wa.unknown());\nvar $E = Wa.object({ type: Wa.literal(\"schematic_symbol\"), schematic_symbol_id: Wa.string(), name: Wa.string().optional(), metadata: jE.optional() }).describe(\"Defines a named schematic symbol that can be referenced by components.\");\nvar YE = Wa.object({ type: Wa.literal(\"schematic_line\"), schematic_line_id: GR(\"schematic_line\"), schematic_sheet_id: Wa.string().optional(), schematic_component_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), x1: wR, y1: wR, x2: wR, y2: wR, stroke_width: wR.nullable().optional(), color: Wa.string().default(\"#000000\"), is_dashed: Wa.boolean().default(false), dash_length: wR.optional(), dash_gap: wR.optional(), subcircuit_id: Wa.string().optional() }).describe(\"Draws a styled line on the schematic\");\nvar XE = Wa.object({ type: Wa.literal(\"schematic_rect\"), schematic_rect_id: GR(\"schematic_rect\"), schematic_sheet_id: Wa.string().optional(), schematic_component_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), center: DR, width: wR, height: wR, rotation: OR.default(0), stroke_width: wR.nullable().optional(), color: Wa.string().default(\"#000000\"), is_filled: Wa.boolean().default(false), fill_color: Wa.string().optional(), is_dashed: Wa.boolean().default(false), subcircuit_id: Wa.string().optional() }).describe(\"Draws a styled rectangle on the schematic\");\nvar HE = Wa.object({ type: Wa.literal(\"schematic_circle\"), schematic_circle_id: GR(\"schematic_circle\"), schematic_sheet_id: Wa.string().optional(), schematic_component_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), center: DR, radius: wR, stroke_width: wR.nullable().optional(), color: Wa.string().default(\"#000000\"), is_filled: Wa.boolean().default(false), fill_color: Wa.string().optional(), is_dashed: Wa.boolean().default(false), subcircuit_id: Wa.string().optional() }).describe(\"Draws a styled circle on the schematic\");\nvar VE = Wa.object({ type: Wa.literal(\"schematic_arc\"), schematic_arc_id: GR(\"schematic_arc\"), schematic_sheet_id: Wa.string().optional(), schematic_component_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), center: DR, radius: wR, start_angle_degrees: OR, end_angle_degrees: OR, direction: Wa.enum([\"clockwise\", \"counterclockwise\"]).default(\"counterclockwise\"), stroke_width: wR.nullable().optional(), color: Wa.string().default(\"#000000\"), is_dashed: Wa.boolean().default(false), subcircuit_id: Wa.string().optional() }).describe(\"Draws a styled arc on the schematic\");\nvar WE = Wa.object({ type: Wa.literal(\"schematic_trace\"), schematic_trace_id: Wa.string(), schematic_sheet_id: Wa.string().optional(), source_trace_id: Wa.string().optional(), junctions: Wa.array(Wa.object({ x: Wa.number(), y: Wa.number() })), edges: Wa.array(Wa.object({ from: Wa.object({ x: Wa.number(), y: Wa.number() }), to: Wa.object({ x: Wa.number(), y: Wa.number() }), is_crossing: Wa.boolean().optional(), from_schematic_port_id: Wa.string().optional(), to_schematic_port_id: Wa.string().optional() })), subcircuit_id: Wa.string().optional(), subcircuit_connectivity_map_key: Wa.string().optional() });\nvar GE = Wa.enum([\"center\", \"left\", \"right\", \"top\", \"bottom\"]);\nvar UE = Wa.object({ text: Wa.string(), is_overlined: Wa.boolean().optional() });\nvar ZE = Wa.object({ type: Wa.literal(\"schematic_text\"), schematic_sheet_id: Wa.string().optional(), schematic_component_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), schematic_text_id: Wa.string(), source_trace_id: Wa.string().optional(), text: Wa.string(), text_parts: Wa.array(UE).min(1).optional(), display_superscript: Wa.string().optional(), font_size: Wa.number().default(0.18), position: Wa.object({ x: wR, y: wR }), rotation: Wa.number().default(0), anchor: Wa.union([GE.describe(\"legacy\"), UR]).default(\"center\"), color: Wa.string().default(\"#000000\"), subcircuit_id: Wa.string().optional() });\nvar qE = Wa.object({ type: Wa.literal(\"schematic_port\"), schematic_port_id: Wa.string(), source_port_id: Wa.string(), schematic_sheet_id: Wa.string().optional(), schematic_component_id: Wa.string().optional(), center: DR, facing_direction: Wa.enum([\"up\", \"down\", \"left\", \"right\"]).optional(), distance_from_component_edge: Wa.number().optional(), side_of_component: Wa.enum([\"top\", \"bottom\", \"left\", \"right\"]).optional(), true_ccw_index: Wa.number().optional(), pin_number: Wa.number().optional(), display_pin_label: Wa.string().optional(), display_pin_label_text_parts: Wa.array(UE).min(1).optional(), display_pin_label_font_size: Wa.number().positive().finite().optional(), subcircuit_id: Wa.string().optional(), is_connected: Wa.boolean().optional(), is_internal_circuit_port: Wa.boolean().optional(), is_overlapping_internal_circuit_port: Wa.boolean().optional(), has_input_arrow: Wa.boolean().optional(), has_output_arrow: Wa.boolean().optional(), is_drawn_with_inversion_circle: Wa.boolean().optional() }).describe(\"Defines a port on a schematic component\");\nvar JE = Wa.object({ type: Wa.literal(\"schematic_net_label\"), schematic_net_label_id: GR(\"schematic_net_label\"), schematic_sheet_id: Wa.string().optional(), schematic_trace_id: Wa.string().optional(), source_trace_id: Wa.string().optional(), source_net_id: Wa.string(), center: DR, anchor_position: DR.optional(), anchor_side: Wa.enum([\"top\", \"bottom\", \"left\", \"right\"]), text: Wa.string(), display_superscript: Wa.string().optional(), symbol_name: Wa.string().optional(), is_movable: Wa.boolean().optional(), subcircuit_id: Wa.string().optional() });\nvar QE = uT.extend({ type: Wa.literal(\"schematic_error\"), schematic_error_id: Wa.string(), error_type: Wa.literal(\"schematic_port_not_found\").default(\"schematic_port_not_found\"), subcircuit_id: Wa.string().optional() }).describe(\"Defines a schematic error on the schematic\");\nvar KE = uT.extend({ type: Wa.literal(\"schematic_layout_error\"), schematic_layout_error_id: GR(\"schematic_layout_error\"), error_type: Wa.literal(\"schematic_layout_error\").default(\"schematic_layout_error\"), source_group_id: Wa.string(), schematic_group_id: Wa.string(), subcircuit_id: Wa.string().optional() }).describe(\"Error emitted when schematic layout fails for a group\");\nvar eA = Wa.object({ type: Wa.literal(\"schematic_debug_object\"), label: Wa.string().optional(), subcircuit_id: Wa.string().optional() });\nvar tA = eA.extend({ shape: Wa.literal(\"rect\"), center: DR, size: FR });\nvar nA = eA.extend({ shape: Wa.literal(\"line\"), start: DR, end: DR });\nvar oA = eA.extend({ shape: Wa.literal(\"point\"), center: DR });\nvar iA = Wa.discriminatedUnion(\"shape\", [tA, nA, oA]);\nvar rA = Wa.object({ type: Wa.literal(\"schematic_voltage_probe\"), schematic_voltage_probe_id: Wa.string(), schematic_sheet_id: Wa.string().optional(), source_component_id: Wa.string().optional(), name: Wa.string().optional(), position: DR, schematic_trace_id: Wa.string(), voltage: CR.optional(), subcircuit_id: Wa.string().optional(), color: Wa.string().optional(), label_alignment: UR.optional() }).describe(\"Defines a voltage probe measurement point on a schematic trace\");\nvar sA = Wa.object({ type: Wa.literal(\"schematic_manual_edit_conflict_warning\"), schematic_manual_edit_conflict_warning_id: GR(\"schematic_manual_edit_conflict_warning\"), warning_type: Wa.literal(\"schematic_manual_edit_conflict_warning\").default(\"schematic_manual_edit_conflict_warning\"), message: Wa.string(), schematic_component_id: Wa.string(), schematic_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), source_component_id: Wa.string() }).describe(\"Warning emitted when a component has both manual placement and explicit schX/schY coordinates\");\nvar aA = Wa.object({ type: Wa.literal(\"schematic_component_overlap_warning\"), schematic_component_overlap_warning_id: GR(\"schematic_component_overlap_warning\"), warning_type: Wa.literal(\"schematic_component_overlap_warning\").default(\"schematic_component_overlap_warning\"), message: Wa.string(), schematic_component_ids: Wa.tuple([Wa.string(), Wa.string()]), schematic_sheet_id: Wa.string().optional() }).describe(\"Warning emitted when the rendered bounds of two schematic components overlap\");\nvar cA = Wa.object({ type: Wa.literal(\"schematic_component_styling_warning\"), schematic_component_styling_warning_id: GR(\"schematic_component_styling_warning\"), warning_type: Wa.literal(\"schematic_component_styling_warning\").default(\"schematic_component_styling_warning\"), message: Wa.string(), schematic_component_id: Wa.string(), styling_issue_type: Wa.string(), schematic_port_ids: Wa.array(Wa.string()).optional(), source_component_id: Wa.string().optional(), schematic_sheet_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe(\"Warning emitted when a schematic component has a visual styling issue\");\nvar lA = Wa.object({ type: Wa.literal(\"schematic_sheet_styling_warning\"), schematic_sheet_styling_warning_id: GR(\"schematic_sheet_styling_warning\"), warning_type: Wa.literal(\"schematic_sheet_styling_warning\").default(\"schematic_sheet_styling_warning\"), message: Wa.string(), schematic_sheet_id: Wa.string(), styling_issue_type: Wa.literal(\"non_default_sheet_size\"), subcircuit_id: Wa.string().optional() }).describe(\"Style warning emitted when a schematic sheet uses a non-default size\");\nvar hA = Wa.object({ type: Wa.literal(\"schematic_element_outside_sheet_warning\"), schematic_element_outside_sheet_warning_id: GR(\"schematic_element_outside_sheet_warning\"), warning_type: Wa.literal(\"schematic_element_outside_sheet_warning\").default(\"schematic_element_outside_sheet_warning\"), message: Wa.string(), schematic_sheet_id: Wa.string(), schematic_element_type: Wa.enum([\"schematic_component\", \"schematic_net_label\", \"schematic_trace\"]), schematic_element_id: Wa.string() }).describe(\"Warning emitted when a schematic component, net label, or trace extends outside its schematic sheet\");\nvar dA = wR.pipe(Wa.number().positive().finite());\nvar uA = Wa.object({ type: Wa.literal(\"schematic_graphic\"), schematic_graphic_id: GR(\"schematic_graphic\"), schematic_sheet_id: Wa.string().optional(), asset: qR.optional(), svg_content: Wa.string().optional(), width: dA.optional(), height: dA.optional() }).describe(\"References a graphic asset or inline SVG content with optional centered layout bounds on a schematic sheet\").superRefine(({ asset: e35, svg_content: t2 }, n2) =\u003e {\n e35 === undefined \u0026\u0026 t2 === undefined \u0026\u0026 n2.addIssue({ code: Wa.ZodIssueCode.custom, message: \"At least one of asset or svg_content is required\" });\n});\nvar pA = Wa.object({ type: Wa.literal(\"schematic_group\"), schematic_group_id: GR(\"schematic_group\"), schematic_sheet_id: Wa.string().optional(), source_group_id: Wa.string(), is_subcircuit: Wa.boolean().optional(), subcircuit_id: Wa.string().optional(), width: PR, height: PR, center: DR, schematic_component_ids: Wa.array(Wa.string()), show_as_schematic_box: Wa.boolean().optional(), name: Wa.string().optional(), description: Wa.string().optional() }).describe(\"Defines a group of components on the schematic\");\nvar mA = Wa.object({ type: Wa.literal(\"schematic_table\"), schematic_table_id: GR(\"schematic_table\"), schematic_sheet_id: Wa.string().optional(), anchor_position: DR, column_widths: Wa.array(wR), row_heights: Wa.array(wR), cell_padding: wR.optional(), border_width: wR.optional(), subcircuit_id: Wa.string().optional(), schematic_component_id: Wa.string().optional(), anchor: UR.optional() }).describe(\"Defines a table on the schematic\");\nvar gA = Wa.object({ type: Wa.literal(\"schematic_table_cell\"), schematic_table_cell_id: GR(\"schematic_table_cell\"), schematic_sheet_id: Wa.string().optional(), schematic_table_id: Wa.string(), start_row_index: Wa.number(), end_row_index: Wa.number(), start_column_index: Wa.number(), end_column_index: Wa.number(), text: Wa.string().optional(), center: DR, width: wR, height: wR, horizontal_align: Wa.enum([\"left\", \"center\", \"right\"]).optional(), vertical_align: Wa.enum([\"top\", \"middle\", \"bottom\"]).optional(), font_size: wR.optional(), subcircuit_id: Wa.string().optional() }).describe(\"Defines a cell within a schematic_table\");\nvar fA = Wa.enum([\"a4\", \"ansi_b\"]);\nvar _A = Wa.object({ type: Wa.literal(\"schematic_sheet\"), schematic_sheet_id: GR(\"schematic_sheet\"), name: Wa.string().optional(), sheet_index: Wa.number().optional(), sheet_size: fA.optional(), sheet_width: Wa.number().positive().optional(), sheet_height: Wa.number().positive().optional(), subcircuit_id: Wa.string().optional(), outline_color: Wa.string().optional() }).describe(\"Defines a schematic sheet or page that components can be placed on\");\nvar yA = Wa.object({ type: Wa.literal(\"schematic_missing_sheet_warning\"), schematic_missing_sheet_warning_id: GR(\"schematic_missing_sheet_warning\"), warning_type: Wa.literal(\"schematic_missing_sheet_warning\").default(\"schematic_missing_sheet_warning\"), message: Wa.string() }).describe(\"Circuit-wide warning emitted when a schematic has no schematic sheet. Display as a banner without attaching it to a component or drawing a target outline or leader line.\");\nvar bA = Wa.object({ x: wR, y: wR, bulge: Wa.number().optional() });\nvar xA = Wa.object({ vertices: Wa.array(bA) });\nvar vA = Wa.object({ outer_ring: xA, inner_rings: Wa.array(xA).default([]) });\nvar IA = { from_left: \"from_left\", from_right: \"from_right\", from_top: \"from_top\", from_bottom: \"from_bottom\", from_above: \"from_above\", from_below: \"from_below\", from_x_neg: \"from_left\", from_x_pos: \"from_right\", from_y_pos: \"from_top\", from_y_neg: \"from_bottom\", from_z_pos: \"from_above\", from_z_neg: \"from_below\", from_front: \"from_top\", from_back: \"from_bottom\" };\nvar SA = { from_left: { x: -1, y: 0, z: 0 }, from_right: { x: 1, y: 0, z: 0 }, from_top: { x: 0, y: 1, z: 0 }, from_bottom: { x: 0, y: -1, z: 0 }, from_above: { x: 0, y: 0, z: 1 }, from_below: { x: 0, y: 0, z: -1 } };\nvar CA = Wa.enum([\"from_left\", \"from_right\", \"from_top\", \"from_bottom\", \"from_above\", \"from_below\", \"from_x_neg\", \"from_x_pos\", \"from_y_pos\", \"from_y_neg\", \"from_z_pos\", \"from_z_neg\", \"from_front\", \"from_back\"]).transform((e35) =\u003e IA[e35]).describe('The side exposing the receptacle where the cable or mating part is attached, following the 2D PCB diagram convention, not a 3D viewport frame. In project coordinate space, \"from_top\" is +Y, \"from_bottom\" -Y, \"from_left\" -X, \"from_right\" +X, \"from_above\" +Z and \"from_below\" -Z. A receptacle on the +Y edge is \"from_top\" even though the plug moves in -Y as it seats. Cartesian spellings such as \"from_y_pos\" are accepted and normalized to the named values, as are the deprecated \"from_front\" (now \"from_top\") and \"from_back\" (now \"from_bottom\").');\nvar PA = Wa.enum([\"leftside_top\", \"leftside_bottom\", \"rightside_top\", \"rightside_bottom\", \"topside_left\", \"topside_right\", \"bottomside_left\", \"bottomside_right\"]);\nvar MA = [[\"leftside_top\", \"bottomside_left\", \"rightside_bottom\", \"topside_right\"], [\"leftside_bottom\", \"bottomside_right\", \"rightside_top\", \"topside_left\"]];\nvar wA = (e35, t2) =\u003e {\n for (const n2 of MA) {\n const o3 = n2.indexOf(e35), i3 = n2.indexOf(t2);\n if (o3 !== -1 \u0026\u0026 i3 !== -1)\n return (i3 - o3 + n2.length) % n2.length * 90;\n }\n return null;\n};\nvar NA = Wa.object({ x: wR, y: wR, via: Wa.boolean().optional(), via_to_layer: yE.optional() });\nvar RA = Wa.array(NA);\nvar TA = Wa.object({ x: wR, y: wR, via: Wa.boolean().optional(), to_layer: yE.optional(), trace_width: wR.optional() });\nvar EA = Wa.object({ min_trace_width: PR.optional(), min_board_edge_clearance: PR.optional(), min_via_hole_edge_to_via_hole_edge_clearance: PR.optional(), min_plated_hole_drill_edge_to_drill_edge_clearance: PR.optional(), min_trace_to_pad_edge_clearance: PR.optional(), min_trace_to_hole_edge_clearance: PR.optional().describe(\"Minimum distance from a trace copper edge to a non-plated hole edge, in mm. No default is applied when omitted.\"), min_pad_edge_to_pad_edge_clearance: PR.optional(), min_same_net_trace_edge_to_trace_edge_clearance: PR.optional(), min_different_net_trace_edge_to_trace_edge_clearance: PR.optional(), min_via_edge_to_pad_edge_clearance: PR.optional(), min_via_hole_diameter: PR.optional(), min_via_pad_diameter: PR.optional() });\nvar AA = Wa.object({ type: Wa.literal(\"pcb_component\"), pcb_component_id: GR(\"pcb_component\"), source_component_id: Wa.string(), center: DR, layer: yE, rotation: OR, display_offset_x: Wa.string().optional().describe(\"How to display the x offset for this part, usually corresponding with how the user specified it\"), display_offset_y: Wa.string().optional().describe(\"How to display the y offset for this part, usually corresponding with how the user specified it\"), width: PR, height: PR, do_not_place: Wa.boolean().optional(), is_allowed_to_be_off_board: Wa.boolean().optional(), subcircuit_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), position_mode: Wa.enum([\"packed\", \"relative_to_group_anchor\", \"relative_to_another_component\", \"none\"]).optional(), anchor_position: DR.optional(), anchor_alignment: UR.optional(), positioned_relative_to_pcb_group_id: Wa.string().optional(), positioned_relative_to_pcb_board_id: Wa.string().optional(), cable_insertion_center: DR.optional(), insertion_direction: CA.optional(), pin1_location: PA.optional().describe(\"Location of pin 1 on the unrotated, top-view component footprint\"), supplier_pin1_location_map: Wa.record(pT, PA).optional().describe(\"Pin 1 location for each supplier's unrotated, top-view footprint\"), metadata: Wa.object({ kicad_footprint: rT.optional() }).optional(), obstructs_within_bounds: Wa.boolean().default(true).describe(\"Does this component take up all the space within its bounds on a layer. This is generally true except for when separated pin headers are being represented by a single component (in which case, chips can be placed between the pin headers) or for tall modules where chips fit underneath\") }).describe(\"Defines a component on the PCB\");\nvar OA = Wa.object({ type: Wa.literal(\"pcb_debug_object\"), pcb_debug_object_id: GR(\"pcb_debug_object\"), label: Wa.string().optional(), subcircuit_id: Wa.string().optional() });\nvar kA = OA.extend({ shape: Wa.literal(\"rect\"), center: DR, size: FR });\nvar DA = OA.extend({ shape: Wa.literal(\"line\"), start: DR, end: DR });\nvar LA = OA.extend({ shape: Wa.literal(\"point\"), center: DR });\nvar zA = Wa.discriminatedUnion(\"shape\", [kA, DA, LA]);\nvar BA = Wa.object({ type: Wa.literal(\"pcb_hole\"), pcb_hole_id: GR(\"pcb_hole\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), pcb_component_id: Wa.string().optional(), hole_shape: Wa.literal(\"circle\"), hole_diameter: Wa.number(), x: wR, y: wR, is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });\nvar FA = BA.describe(\"Defines a circular hole on the PCB\");\nvar jA = Wa.object({ type: Wa.literal(\"pcb_hole\"), pcb_hole_id: GR(\"pcb_hole\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), pcb_component_id: Wa.string().optional(), hole_shape: Wa.literal(\"rect\"), hole_width: Wa.number(), hole_height: Wa.number(), x: wR, y: wR, is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });\nvar $A = jA.describe(\"Defines a rectangular (square-capable) hole on the PCB. Use equal width/height for square.\");\nvar YA = Wa.object({ type: Wa.literal(\"pcb_hole\"), pcb_hole_id: GR(\"pcb_hole\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), pcb_component_id: Wa.string().optional(), hole_shape: Wa.enum([\"circle\", \"square\"]), hole_diameter: Wa.number(), x: wR, y: wR, is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });\nvar XA = YA.describe(\"Defines a circular or square hole on the PCB\");\nvar HA = Wa.object({ type: Wa.literal(\"pcb_hole\"), pcb_hole_id: GR(\"pcb_hole\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), pcb_component_id: Wa.string().optional(), hole_shape: Wa.literal(\"oval\"), hole_width: Wa.number(), hole_height: Wa.number(), x: wR, y: wR, is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });\nvar VA = HA.describe(\"Defines an oval hole on the PCB\");\nvar WA = Wa.object({ type: Wa.literal(\"pcb_hole\"), pcb_hole_id: GR(\"pcb_hole\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), pcb_component_id: Wa.string().optional(), hole_shape: Wa.literal(\"pill\"), hole_width: Wa.number(), hole_height: Wa.number(), x: wR, y: wR, is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });\nvar GA = WA.describe(\"Defines a pill-shaped hole on the PCB\");\nvar UA = Wa.object({ type: Wa.literal(\"pcb_hole\"), pcb_hole_id: GR(\"pcb_hole\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), pcb_component_id: Wa.string().optional(), hole_shape: Wa.literal(\"rotated_pill\"), hole_width: Wa.number(), hole_height: Wa.number(), x: wR, y: wR, ccw_rotation: OR, is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });\nvar ZA = UA.describe(\"Defines a rotated pill-shaped hole on the PCB\");\nvar qA = YA.or(HA).or(WA).or(UA).or(BA).or(jA);\nvar JA = Wa.object({ type: Wa.literal(\"pcb_plated_hole\"), shape: Wa.literal(\"circle\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), outer_diameter: Wa.number(), hole_diameter: Wa.number(), is_covered_with_solder_mask: Wa.boolean().optional(), x: wR, y: wR, layers: Wa.array(yE), port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), pcb_plated_hole_id: GR(\"pcb_plated_hole\"), soldermask_margin: Wa.number().optional() });\nvar QA = Wa.object({ type: Wa.literal(\"pcb_plated_hole\"), shape: Wa.enum([\"oval\", \"pill\"]), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), outer_width: Wa.number(), outer_height: Wa.number(), hole_width: Wa.number(), hole_height: Wa.number(), is_covered_with_solder_mask: Wa.boolean().optional(), x: wR, y: wR, ccw_rotation: OR, layers: Wa.array(yE), port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), pcb_plated_hole_id: GR(\"pcb_plated_hole\"), soldermask_margin: Wa.number().optional() });\nvar KA = Wa.object({ type: Wa.literal(\"pcb_plated_hole\"), shape: Wa.literal(\"circular_hole_with_rect_pad\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), hole_shape: Wa.literal(\"circle\"), pad_shape: Wa.literal(\"rect\"), hole_diameter: Wa.number(), rect_pad_width: Wa.number(), rect_pad_height: Wa.number(), rect_border_radius: Wa.number().optional(), hole_offset_x: wR.default(0), hole_offset_y: wR.default(0), is_covered_with_solder_mask: Wa.boolean().optional(), x: wR, y: wR, layers: Wa.array(yE), port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), pcb_plated_hole_id: GR(\"pcb_plated_hole\"), soldermask_margin: Wa.number().optional(), rect_ccw_rotation: OR.optional() });\nvar eO = Wa.object({ type: Wa.literal(\"pcb_plated_hole\"), shape: Wa.literal(\"pill_hole_with_rect_pad\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), hole_shape: Wa.literal(\"pill\"), pad_shape: Wa.literal(\"rect\"), hole_width: Wa.number(), hole_height: Wa.number(), rect_pad_width: Wa.number(), rect_pad_height: Wa.number(), rect_border_radius: Wa.number().optional(), hole_offset_x: wR.default(0), hole_offset_y: wR.default(0), is_covered_with_solder_mask: Wa.boolean().optional(), x: wR, y: wR, layers: Wa.array(yE), port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), pcb_plated_hole_id: GR(\"pcb_plated_hole\"), soldermask_margin: Wa.number().optional() });\nvar tO = Wa.object({ type: Wa.literal(\"pcb_plated_hole\"), shape: Wa.literal(\"rotated_pill_hole_with_rect_pad\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), hole_shape: Wa.literal(\"rotated_pill\"), pad_shape: Wa.literal(\"rect\"), hole_width: Wa.number(), hole_height: Wa.number(), hole_ccw_rotation: OR, rect_pad_width: Wa.number(), rect_pad_height: Wa.number(), rect_border_radius: Wa.number().optional(), rect_ccw_rotation: OR, hole_offset_x: wR.default(0), hole_offset_y: wR.default(0), is_covered_with_solder_mask: Wa.boolean().optional(), x: wR, y: wR, layers: Wa.array(yE), port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), pcb_plated_hole_id: GR(\"pcb_plated_hole\"), soldermask_margin: Wa.number().optional() });\nvar nO = Wa.object({ type: Wa.literal(\"pcb_plated_hole\"), shape: Wa.literal(\"hole_with_polygon_pad\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), hole_shape: Wa.enum([\"circle\", \"oval\", \"pill\", \"rotated_pill\"]), hole_diameter: Wa.number().optional(), hole_width: Wa.number().optional(), hole_height: Wa.number().optional(), pad_outline: Wa.array(Wa.object({ x: wR, y: wR })).min(3), hole_offset_x: wR.default(0), hole_offset_y: wR.default(0), is_covered_with_solder_mask: Wa.boolean().optional(), x: wR, y: wR, layers: Wa.array(yE), port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), pcb_plated_hole_id: GR(\"pcb_plated_hole\"), soldermask_margin: Wa.number().optional(), ccw_rotation: OR.optional() });\nvar oO = Wa.union([JA, QA, KA, eO, tO, nO]);\nvar iO = Wa.object({ type: Wa.literal(\"pcb_port\"), pcb_port_id: GR(\"pcb_port\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), source_port_id: Wa.string(), pcb_component_id: Wa.string().optional(), x: wR, y: wR, layers: Wa.array(yE), is_board_pinout: Wa.boolean().optional() }).describe(\"Defines a port on the PCB\");\nvar rO = Wa.object({ type: Wa.literal(\"pcb_smtpad\"), shape: Wa.literal(\"circle\"), pcb_smtpad_id: GR(\"pcb_smtpad\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: wR, y: wR, radius: Wa.number(), layer: yE, port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional(), solderpaste_margin: Wa.number().optional() });\nvar sO = Wa.object({ type: Wa.literal(\"pcb_smtpad\"), shape: Wa.literal(\"rect\"), pcb_smtpad_id: GR(\"pcb_smtpad\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: wR, y: wR, width: Wa.number(), height: Wa.number(), rect_border_radius: Wa.number().optional(), corner_radius: Wa.number().optional(), layer: yE, port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional(), soldermask_margin_left: Wa.number().optional(), soldermask_margin_top: Wa.number().optional(), soldermask_margin_right: Wa.number().optional(), soldermask_margin_bottom: Wa.number().optional(), solderpaste_margin: Wa.number().optional() });\nvar aO = Wa.object({ type: Wa.literal(\"pcb_smtpad\"), shape: Wa.literal(\"rotated_rect\"), pcb_smtpad_id: GR(\"pcb_smtpad\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: wR, y: wR, width: Wa.number(), height: Wa.number(), rect_border_radius: Wa.number().optional(), corner_radius: Wa.number().optional(), ccw_rotation: OR, layer: yE, port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional(), soldermask_margin_left: Wa.number().optional(), soldermask_margin_top: Wa.number().optional(), soldermask_margin_right: Wa.number().optional(), soldermask_margin_bottom: Wa.number().optional(), solderpaste_margin: Wa.number().optional() });\nvar cO = Wa.object({ type: Wa.literal(\"pcb_smtpad\"), shape: Wa.literal(\"pill\"), pcb_smtpad_id: GR(\"pcb_smtpad\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: wR, y: wR, width: Wa.number(), height: Wa.number(), radius: Wa.number(), layer: yE, port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional(), solderpaste_margin: Wa.number().optional() });\nvar lO = Wa.object({ type: Wa.literal(\"pcb_smtpad\"), shape: Wa.literal(\"rotated_pill\"), pcb_smtpad_id: GR(\"pcb_smtpad\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: wR, y: wR, width: Wa.number(), height: Wa.number(), radius: Wa.number(), ccw_rotation: OR, layer: yE, port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional(), solderpaste_margin: Wa.number().optional() });\nvar hO = Wa.object({ type: Wa.literal(\"pcb_smtpad\"), shape: Wa.literal(\"polygon\"), pcb_smtpad_id: GR(\"pcb_smtpad\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), points: Wa.array(DR), layer: yE, port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional(), solderpaste_margin: Wa.number().optional() });\nvar dO = Wa.discriminatedUnion(\"shape\", [rO, sO, aO, lO, cO, hO]).describe(\"Defines an SMT pad on the PCB\");\nvar uO = Wa.object({ type: Wa.literal(\"pcb_solder_paste\"), shape: Wa.literal(\"circle\"), pcb_solder_paste_id: GR(\"pcb_solder_paste\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: wR, y: wR, radius: Wa.number(), layer: yE, pcb_component_id: Wa.string().optional(), pcb_smtpad_id: Wa.string().optional() });\nvar pO = Wa.object({ type: Wa.literal(\"pcb_solder_paste\"), shape: Wa.literal(\"rect\"), pcb_solder_paste_id: GR(\"pcb_solder_paste\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: wR, y: wR, width: Wa.number(), height: Wa.number(), layer: yE, pcb_component_id: Wa.string().optional(), pcb_smtpad_id: Wa.string().optional() });\nvar mO = Wa.object({ type: Wa.literal(\"pcb_solder_paste\"), shape: Wa.literal(\"pill\"), pcb_solder_paste_id: GR(\"pcb_solder_paste\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: wR, y: wR, width: Wa.number(), height: Wa.number(), radius: Wa.number(), layer: yE, pcb_component_id: Wa.string().optional(), pcb_smtpad_id: Wa.string().optional() });\nvar gO = Wa.object({ type: Wa.literal(\"pcb_solder_paste\"), shape: Wa.literal(\"rotated_rect\"), pcb_solder_paste_id: GR(\"pcb_solder_paste\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: wR, y: wR, width: Wa.number(), height: Wa.number(), ccw_rotation: wR, layer: yE, pcb_component_id: Wa.string().optional(), pcb_smtpad_id: Wa.string().optional() });\nvar fO = Wa.object({ type: Wa.literal(\"pcb_solder_paste\"), shape: Wa.literal(\"rotated_pill\"), pcb_solder_paste_id: GR(\"pcb_solder_paste\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: wR, y: wR, width: Wa.number(), height: Wa.number(), radius: Wa.number(), ccw_rotation: OR, layer: yE, pcb_component_id: Wa.string().optional(), pcb_smtpad_id: Wa.string().optional() });\nvar _O = Wa.object({ type: Wa.literal(\"pcb_solder_paste\"), shape: Wa.literal(\"oval\"), pcb_solder_paste_id: GR(\"pcb_solder_paste\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: wR, y: wR, width: Wa.number(), height: Wa.number(), layer: yE, pcb_component_id: Wa.string().optional(), pcb_smtpad_id: Wa.string().optional() });\nvar yO = VR.extend({ type: Wa.literal(\"pcb_solder_paste\"), pcb_solder_paste_id: GR(\"pcb_solder_paste\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), holes: Wa.array(VR.shape.points).optional(), layer: yE, pcb_component_id: Wa.string().optional(), pcb_smtpad_id: Wa.string().optional() });\nvar bO = Wa.union([uO, pO, mO, gO, fO, _O, yO]).describe(\"Defines solderpaste on the PCB\");\nvar xO = Wa.object({ type: Wa.literal(\"pcb_soldermask_opening\"), pcb_soldermask_opening_id: GR(\"pcb_soldermask_opening\"), layer: yE.pipe(bE), pcb_component_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() });\nvar vO = Wa.discriminatedUnion(\"shape\", [YR.extend(xO.shape), XR.extend(xO.shape), HR.extend(xO.shape), VR.extend(xO.shape)]).describe(\"An explicit opening in top or bottom solder mask or flex coverlay, independent of pads. Removes mask without adding copper or solder paste.\");\nvar IO = Wa.object({ type: Wa.literal(\"pcb_text\"), pcb_text_id: GR(\"pcb_text\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), text: Wa.string(), center: DR, layer: yE, width: PR, height: PR, lines: Wa.number(), align: Wa.enum([\"bottom-left\"]) }).describe(\"Defines text on the PCB\");\nvar SO = wR.pipe(Wa.number().finite().positive());\nvar CO = Wa.object({ route_type: Wa.literal(\"wire\"), x: wR, y: wR, width: wR, start_width: SO.optional(), end_width: SO.optional(), width_interpolation_mode: Wa.enum([\"linear\", \"quadratic\"]).optional(), copper_pour_id: Wa.string().optional(), is_inside_copper_pour: Wa.boolean().optional(), start_pcb_port_id: Wa.string().optional(), end_pcb_port_id: Wa.string().optional(), layer: yE }).superRefine((e35, t2) =\u003e {\n const n2 = [e35.start_width, e35.end_width, e35.width_interpolation_mode].filter((e36) =\u003e e36 !== undefined).length;\n n2 !== 0 \u0026\u0026 (n2 !== 3 \u0026\u0026 t2.addIssue({ code: Wa.ZodIssueCode.custom, message: \"Wire taper requires start_width, end_width and width_interpolation_mode together\" }), e35.width !== e35.start_width \u0026\u0026 t2.addIssue({ code: Wa.ZodIssueCode.custom, path: [\"start_width\"], message: \"start_width must equal width\" }), Number.isFinite(e35.x) \u0026\u0026 Number.isFinite(e35.y) || t2.addIssue({ code: Wa.ZodIssueCode.custom, message: \"Tapered wire coordinates must be finite\" }));\n});\nvar PO = Wa.object({ route_type: Wa.literal(\"via\"), x: wR, y: wR, copper_pour_id: Wa.string().optional(), is_inside_copper_pour: Wa.boolean().optional(), hole_diameter: wR.optional(), outer_diameter: wR.optional(), tented_on_top: Wa.boolean().optional(), tented_on_bottom: Wa.boolean().optional(), from_layer: yE, to_layer: yE });\nvar MO = Wa.object({ route_type: Wa.literal(\"through_pad\"), start: DR, end: DR, width: wR, start_layer: yE, end_layer: yE, pcb_smtpad_id: Wa.string().optional(), pcb_plated_hole_id: Wa.string().optional() });\nvar wO = Wa.union([CO, PO, MO]);\nvar NO = Wa.object({ type: Wa.literal(\"pcb_trace\"), source_trace_id: Wa.string().optional(), pcb_component_id: Wa.string().optional(), pcb_trace_id: GR(\"pcb_trace\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), route_thickness_mode: Wa.enum([\"constant\", \"interpolated\"]).default(\"constant\").optional(), route_order_index: Wa.number().optional(), should_round_corners: Wa.boolean().optional(), trace_length: Wa.number().optional(), is_antenna_trace: Wa.boolean().optional(), highlight_color: Wa.string().optional(), route: Wa.array(wO).superRefine((e35, t2) =\u003e {\n for (const [n2, o3] of e35.entries()) {\n if (o3.route_type !== \"wire\" || o3.width_interpolation_mode === undefined)\n continue;\n const i3 = e35[n2 + 1], r3 = i3?.route_type === \"through_pad\" ? i3.start : i3, s2 = i3?.route_type === \"wire\" ? i3.layer : i3?.route_type === \"via\" ? i3.from_layer : i3?.start_layer, a3 = r3 ? Math.hypot(r3.x - o3.x, r3.y - o3.y) : NaN;\n (!Number.isFinite(a3) || a3 \u003c= 0 || s2 !== o3.layer) \u0026\u0026 t2.addIssue({ code: Wa.ZodIssueCode.custom, path: [n2], message: \"Tapered wire must lead to a distinct finite next point on the same layer\" });\n }\n}) }).describe(\"Defines a trace on the PCB\");\nvar RO = Wa.object({ type: Wa.literal(\"pcb_trace_warning\"), pcb_trace_warning_id: GR(\"pcb_trace_warning\"), warning_type: Wa.literal(\"pcb_trace_warning\").default(\"pcb_trace_warning\"), message: Wa.string(), center: DR.optional(), pcb_trace_id: Wa.string(), source_trace_id: Wa.string(), pcb_component_ids: Wa.array(Wa.string()), pcb_port_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe(\"Defines a trace warning on the PCB\");\nvar TO = Wa.object({ type: Wa.literal(\"pcb_trace_style_warning\"), pcb_trace_style_warning_id: GR(\"pcb_trace_style_warning\"), warning_type: Wa.literal(\"pcb_trace_style_warning\").default(\"pcb_trace_style_warning\"), message: Wa.string(), styling_issue_type: Wa.literal(\"long_segment_at_odd_angle\"), pcb_trace_id: Wa.string(), source_trace_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), layer: yE, start_route_index: Wa.number().int().nonnegative(), end_route_index: Wa.number().int().nonnegative(), segment_start: DR, segment_end: DR, center: DR, segment_length: wR, minimum_segment_length: wR, angle_degrees: Wa.number().min(0).lt(360), nearest_allowed_angle_degrees: Wa.number().min(0).lt(360).multipleOf(45), angle_deviation_degrees: Wa.number().min(0).max(22.5), angle_tolerance_degrees: Wa.number().min(0).lt(22.5) }).describe(\"Warning for a long PCB trace segment whose direction deviates from a multiple of 45 degrees\");\nvar EO = Wa.object({ type: Wa.literal(\"pcb_trace_too_long_error\"), pcb_trace_too_long_error_id: GR(\"pcb_trace_too_long_error\"), error_type: Wa.literal(\"pcb_trace_too_long_error\").default(\"pcb_trace_too_long_error\"), message: Wa.string(), pcb_trace_id: Wa.string(), source_net_id: Wa.string().optional(), source_trace_id: Wa.string().optional(), actual_trace_length: wR, maximum_trace_length: wR, subcircuit_id: Wa.string().optional() }).describe(\"Error emitted when a PCB trace is longer than its maximum allowed length\");\nvar AO = uT.extend({ type: Wa.literal(\"pcb_bus_length_skew_error\"), pcb_bus_length_skew_error_id: GR(\"pcb_bus_length_skew_error\"), error_type: Wa.literal(\"pcb_bus_length_skew_error\").default(\"pcb_bus_length_skew_error\"), source_bus_id: Wa.string(), source_trace_ids: Wa.array(Wa.string()), pcb_trace_ids: Wa.array(Wa.string()), actual_length_skew: Wa.number().nonnegative().finite(), maximum_length_skew: Wa.number().nonnegative().finite(), subcircuit_id: Wa.string().optional() });\nvar OO = Wa.object({ type: Wa.literal(\"pcb_trace_too_long_warning\"), pcb_trace_too_long_warning_id: GR(\"pcb_trace_too_long_warning\"), warning_type: Wa.literal(\"pcb_trace_too_long_warning\").default(\"pcb_trace_too_long_warning\"), message: Wa.string(), pcb_trace_id: Wa.string(), source_net_id: Wa.string().optional(), source_trace_id: Wa.string().optional(), actual_trace_length: wR, maximum_trace_length: wR, subcircuit_id: Wa.string().optional() }).describe(\"Warning emitted when a PCB trace is longer than its maximum allowed length\");\nvar kO = Wa.object({ type: Wa.literal(\"pcb_trace_too_many_vias_warning\"), pcb_trace_too_many_vias_warning_id: GR(\"pcb_trace_too_many_vias_warning\"), warning_type: Wa.literal(\"pcb_trace_too_many_vias_warning\").default(\"pcb_trace_too_many_vias_warning\"), message: Wa.string(), pcb_trace_id: Wa.string(), source_net_id: Wa.string().optional(), source_trace_id: Wa.string().optional(), actual_via_count: Wa.number().int().nonnegative(), maximum_via_count: Wa.number().int().nonnegative(), subcircuit_id: Wa.string().optional() }).describe(\"Warning emitted when a PCB trace has more vias than its maximum allowed count\");\nvar DO = uT.extend({ type: Wa.literal(\"pcb_bus_routing_constraint_error\"), pcb_bus_routing_constraint_error_id: GR(\"pcb_bus_routing_constraint_error\"), error_type: Wa.literal(\"pcb_bus_routing_constraint_error\").default(\"pcb_bus_routing_constraint_error\"), source_bus_id: Wa.string(), source_trace_ids: Wa.array(Wa.string()).min(1), pcb_trace_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() });\nvar LO = Wa.discriminatedUnion(\"routing_rule\", [DO.extend({ routing_rule: Wa.literal(\"length_skew\"), actual_length_skew: Wa.number().nonnegative().finite(), maximum_length_skew: Wa.number().nonnegative().finite() }), DO.extend({ routing_rule: Wa.literal(\"min_length\"), actual_trace_length: Wa.number().nonnegative().finite(), minimum_trace_length: Wa.number().finite() }), DO.extend({ routing_rule: Wa.literal(\"max_length\"), actual_trace_length: Wa.number().nonnegative().finite(), maximum_trace_length: Wa.number().finite() }), DO.extend({ routing_rule: Wa.literal(\"target_length\"), actual_trace_length: Wa.number().nonnegative().finite(), target_trace_length: Wa.number().finite(), length_tolerance: Wa.number().nonnegative().finite() }), DO.extend({ routing_rule: Wa.literal(\"pcb_trace_spacing\"), other_pcb_trace_id: Wa.string(), other_source_trace_id: Wa.string().optional(), actual_centerline_spacing: Wa.number().nonnegative().finite(), minimum_centerline_spacing: Wa.number().positive().finite() }), DO.extend({ routing_rule: Wa.literal(\"pcb_spacing_to_other_signals\"), other_pcb_trace_id: Wa.string(), other_source_trace_id: Wa.string().optional(), actual_centerline_spacing: Wa.number().nonnegative().finite(), minimum_centerline_spacing: Wa.number().positive().finite() }), DO.extend({ routing_rule: Wa.literal(\"impedance_target\"), target_impedance: Wa.number().positive().finite(), minimum_impedance: Wa.number().positive().finite().optional(), maximum_impedance: Wa.number().positive().finite().optional() })]).superRefine((e35, t2) =\u003e {\n e35.routing_rule === \"impedance_target\" \u0026\u0026 (e35.minimum_impedance === undefined \u0026\u0026 e35.maximum_impedance === undefined \u0026\u0026 t2.addIssue({ code: Wa.ZodIssueCode.custom, path: [\"minimum_impedance\"], message: \"Provide an impedance bound\" }), e35.minimum_impedance !== undefined \u0026\u0026 e35.maximum_impedance !== undefined \u0026\u0026 e35.minimum_impedance \u003e e35.maximum_impedance \u0026\u0026 t2.addIssue({ code: Wa.ZodIssueCode.custom, path: [\"maximum_impedance\"], message: \"Impedance bounds must be ordered\" }));\n}).describe(\"A declared bus or differential-pair routing constraint is violated.\");\nvar zO = Wa.object({ type: Wa.literal(\"pcb_bus_routing_constraint_warning\"), pcb_bus_routing_constraint_warning_id: GR(\"pcb_bus_routing_constraint_warning\"), warning_type: Wa.literal(\"pcb_bus_routing_constraint_warning\").default(\"pcb_bus_routing_constraint_warning\"), source_bus_id: Wa.string(), source_trace_ids: Wa.array(Wa.string()).min(1), pcb_trace_ids: Wa.array(Wa.string()), message: Wa.string(), subcircuit_id: Wa.string().optional() }).describe(\"A declared bus or pair constraint could not be verified; this is not a pass.\");\nvar BO = Wa.discriminatedUnion(\"routing_rule\", [zO.extend({ routing_rule: Wa.literal(\"route_geometry\") }), zO.extend({ routing_rule: Wa.literal(\"reference_geometry\") }), zO.extend({ routing_rule: Wa.literal(\"spacing_geometry\") }), zO.extend({ routing_rule: Wa.literal(\"target_length\") }), zO.extend({ routing_rule: Wa.literal(\"physical_impedance\") })]);\nvar FO = uT.extend({ type: Wa.literal(\"pcb_trace_error\"), pcb_trace_error_id: GR(\"pcb_trace_error\"), error_type: Wa.literal(\"pcb_trace_error\").default(\"pcb_trace_error\"), center: DR.optional(), pcb_trace_id: Wa.string(), source_trace_id: Wa.string(), pcb_component_ids: Wa.array(Wa.string()), pcb_port_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe(\"Defines a trace error on the PCB\");\nvar jO = uT.extend({ type: Wa.literal(\"pcb_trace_missing_error\"), pcb_trace_missing_error_id: GR(\"pcb_trace_missing_error\"), error_type: Wa.literal(\"pcb_trace_missing_error\").default(\"pcb_trace_missing_error\"), center: DR.optional(), source_trace_id: Wa.string(), pcb_component_ids: Wa.array(Wa.string()), pcb_port_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe(\"Defines an error when a source trace has no corresponding PCB trace\");\nvar $O = uT.extend({ type: Wa.literal(\"pcb_port_not_matched_error\"), pcb_error_id: GR(\"pcb_error\"), error_type: Wa.literal(\"pcb_port_not_matched_error\").default(\"pcb_port_not_matched_error\"), pcb_component_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe(\"Defines a trace error on the PCB where a port is not matched\");\nvar YO = uT.extend({ type: Wa.literal(\"pcb_port_not_connected_error\"), pcb_port_not_connected_error_id: GR(\"pcb_port_not_connected_error\"), error_type: Wa.literal(\"pcb_port_not_connected_error\").default(\"pcb_port_not_connected_error\"), pcb_port_ids: Wa.array(Wa.string()), pcb_component_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe(\"Defines an error when a pcb port is not connected to any trace\");\nvar XO = Wa.object({ type: Wa.literal(\"pcb_net\"), pcb_net_id: GR(\"pcb_net\"), source_net_id: Wa.string().optional(), highlight_color: Wa.string().optional() }).describe(\"Defines a net on the PCB\");\nvar HO = Wa.object({ type: Wa.literal(\"pcb_via\"), pcb_via_id: GR(\"pcb_via\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), subcircuit_connectivity_map_key: Wa.string().optional(), x: wR, y: wR, outer_diameter: wR.default(\"0.6mm\"), hole_diameter: wR.default(\"0.25mm\"), topmost_drill_layer: yE.optional(), bottommost_drill_layer: yE.optional(), through_hole: Wa.boolean().optional(), from_layer: yE.optional(), to_layer: yE.optional(), layers: Wa.array(yE), pcb_port_ids: Wa.array(Wa.string()).optional(), pcb_trace_id: Wa.string().optional(), source_trace_id: Wa.string().optional(), source_net_id: Wa.string().min(1).optional(), net_is_assignable: Wa.boolean().optional(), net_assigned: Wa.boolean().optional(), is_tented: Wa.boolean().optional(), tented_on_top: Wa.boolean().optional(), tented_on_bottom: Wa.boolean().optional() }).transform(({ is_tented: e35, ...t2 }) =\u003e (e35 !== undefined \u0026\u0026 (t2.tented_on_top ??= e35, t2.tented_on_bottom ??= e35), t2)).describe(\"Defines a via on the PCB\");\nvar VO = Wa.object({ type: Wa.literal(\"pcb_board\"), pcb_board_id: GR(\"pcb_board\"), pcb_panel_id: Wa.string().optional(), carrier_pcb_board_id: Wa.string().optional(), is_subcircuit: Wa.boolean().optional(), subcircuit_id: Wa.string().optional(), is_mounted_to_carrier_board: Wa.boolean().optional(), is_via_in_pad_allowed: Wa.boolean().optional(), default_via_tented_on_top: Wa.boolean().optional(), default_via_tented_on_bottom: Wa.boolean().optional(), default_via_plugged: Wa.boolean().optional(), width: PR.optional(), height: PR.optional(), center: DR, display_offset_x: Wa.string().optional().describe(\"How to display the x offset for this board, usually corresponding with how the user specified it\"), display_offset_y: Wa.string().optional().describe(\"How to display the y offset for this board, usually corresponding with how the user specified it\"), thickness: PR.optional().default(1.4), num_layers: Wa.number().optional().default(4), allow_blind_and_buried_vias: Wa.boolean().optional().describe(\"Whether autorouters may generate blind and buried vias. False restricts newly generated vias to the full board stack.\"), outline: Wa.array(DR).optional(), shape: Wa.enum([\"rect\", \"polygon\"]).optional(), material: Wa.enum([\"fr4\", \"fr1\", \"flex\"]).default(\"fr4\"), solder_mask_color: Wa.string().optional(), silkscreen_color: Wa.string().optional(), anchor_position: DR.optional(), anchor_alignment: UR.optional(), position_mode: Wa.enum([\"relative_to_panel_anchor\", \"none\"]).optional() }).merge(EA).describe(\"Defines the board outline of the PCB\");\nvar WO = DR.extend({ x: PR.pipe(Wa.number().finite()), y: PR.pipe(Wa.number().finite()) });\nvar GO = Wa.object({ type: Wa.literal(\"pcb_bend\"), pcb_bend_id: GR(\"pcb_bend\"), pcb_board_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), name: Wa.string().optional(), start: WO, end: WO, bend_angle: OR.pipe(Wa.number().finite()), bend_radius: PR.pipe(Wa.number().finite().positive()), bend_side: Wa.enum([\"left\", \"right\"]) }).refine(({ start: e35, end: t2 }) =\u003e e35.x !== t2.x || e35.y !== t2.y, { message: \"Bend centerline endpoints must be distinct\", path: [\"end\"] }).describe(\"Defines a finite-radius bend on a flat PCB for runtime CAD folding\");\nvar UO = PR.pipe(Wa.number().finite().positive());\nvar ZO = DR.extend({ x: PR.pipe(Wa.number().finite()), y: PR.pipe(Wa.number().finite()) });\nvar qO = Wa.object({ type: Wa.literal(\"pcb_stiffener\"), pcb_stiffener_id: GR(\"pcb_stiffener\"), pcb_board_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), name: Wa.string().optional(), layer: Wa.enum([\"top\", \"bottom\"]), material: Wa.enum([\"fr4\", \"polyimide\", \"stainless_steel\", \"aluminum\"]), thickness: UO, adhesive_thickness: PR.pipe(Wa.number().finite().nonnegative()).optional() });\nvar JO = qO.extend({ shape: Wa.literal(\"rect\"), center: ZO, rotation: OR.pipe(Wa.number().finite()).optional(), width: UO, height: UO, outline: Wa.never().optional() });\nvar QO = qO.extend({ shape: Wa.literal(\"polygon\"), outline: Wa.array(ZO).min(3).refine((e35) =\u003e {\n const t2 = e35.reduce((t3, n2, o3) =\u003e {\n const i3 = e35[(o3 + 1) % e35.length];\n return t3 + n2.x * i3.y - i3.x * n2.y;\n }, 0);\n return Number.isFinite(t2) \u0026\u0026 t2 !== 0;\n}, \"Stiffener outline must enclose a nonzero area\"), center: Wa.never().optional(), rotation: Wa.never().optional(), width: Wa.never().optional(), height: Wa.never().optional() });\nvar KO = Wa.discriminatedUnion(\"shape\", [JO, QO]).describe(\"Defines bonded mechanical PCB reinforcement without adding copper layers\");\nvar ek = Wa.object({ type: Wa.literal(\"pcb_panel\"), pcb_panel_id: GR(\"pcb_panel\"), width: PR, height: PR, center: DR, thickness: PR.optional().default(1.4), covered_with_solder_mask: Wa.boolean().optional().default(true) }).describe(\"Defines a PCB panel that can contain multiple boards\");\nvar tk = uT.extend({ type: Wa.literal(\"pcb_placement_error\"), pcb_placement_error_id: GR(\"pcb_placement_error\"), error_type: Wa.literal(\"pcb_placement_error\").default(\"pcb_placement_error\"), subcircuit_id: Wa.string().optional() }).describe(\"Defines a placement error on the PCB\");\nvar nk = uT.extend({ type: Wa.literal(\"pcb_packing_error\"), pcb_packing_error_id: GR(\"pcb_packing_error\"), error_type: Wa.literal(\"pcb_packing_error\").default(\"pcb_packing_error\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe(\"Defines a failure to pack PCB components within layout bounds\");\nvar ok = uT.extend({ type: Wa.literal(\"pcb_panelization_placement_error\"), pcb_panelization_placement_error_id: GR(\"pcb_panelization_placement_error\"), error_type: Wa.literal(\"pcb_panelization_placement_error\").default(\"pcb_panelization_placement_error\"), pcb_panel_id: Wa.string().optional(), pcb_board_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe(\"Defines a panelization placement error on the PCB\");\nvar ik = Wa.object({ type: Wa.literal(\"pcb_trace_hint\"), pcb_trace_hint_id: GR(\"pcb_trace_hint\"), pcb_port_id: Wa.string(), pcb_component_id: Wa.string(), route: Wa.array(TA), subcircuit_id: Wa.string().optional() }).describe(\"A hint that can be used during generation of a PCB trace\");\nvar rk = Wa.object({ type: Wa.literal(\"pcb_silkscreen_line\"), pcb_silkscreen_line_id: GR(\"pcb_silkscreen_line\"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), stroke_width: wR.default(\"0.1mm\"), x1: wR, y1: wR, x2: wR, y2: wR, layer: bE }).describe(\"Defines a silkscreen line on the PCB\");\nvar sk = Wa.object({ type: Wa.literal(\"pcb_silkscreen_path\"), pcb_silkscreen_path_id: GR(\"pcb_silkscreen_path\"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), layer: bE, route: Wa.array(DR), stroke_width: PR }).describe(\"Defines a silkscreen path on the PCB\");\nvar ak = Wa.object({ type: Wa.literal(\"pcb_silkscreen_text\"), pcb_silkscreen_text_id: GR(\"pcb_silkscreen_text\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), font: Wa.literal(\"tscircuit2024\").default(\"tscircuit2024\"), font_size: wR.default(\"0.2mm\"), pcb_component_id: Wa.string(), text: Wa.string(), is_knockout: Wa.boolean().default(false).optional(), knockout_padding: Wa.object({ left: PR, top: PR, bottom: PR, right: PR }).default({ left: \"0.2mm\", top: \"0.2mm\", bottom: \"0.2mm\", right: \"0.2mm\" }).optional(), ccw_rotation: Wa.number().optional(), layer: yE, is_mirrored: Wa.boolean().default(false).optional(), anchor_position: DR.default({ x: 0, y: 0 }), anchor_alignment: UR.default(\"center\") }).describe(\"Defines silkscreen text on the PCB\");\nvar ck = Wa.object({ type: Wa.literal(\"pcb_copper_text\"), pcb_copper_text_id: GR(\"pcb_copper_text\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), font: Wa.literal(\"tscircuit2024\").default(\"tscircuit2024\"), font_size: wR.default(\"0.2mm\"), pcb_component_id: Wa.string(), text: Wa.string(), is_knockout: Wa.boolean().default(false).optional(), knockout_padding: Wa.object({ left: PR, top: PR, bottom: PR, right: PR }).default({ left: \"0.2mm\", top: \"0.2mm\", bottom: \"0.2mm\", right: \"0.2mm\" }).optional(), ccw_rotation: Wa.number().optional(), layer: yE, is_mirrored: Wa.boolean().default(false).optional(), anchor_position: DR.default({ x: 0, y: 0 }), anchor_alignment: UR.default(\"center\") }).describe(\"Defines copper text on the PCB\");\nvar lk = Wa.object({ type: Wa.literal(\"pcb_silkscreen_rect\"), pcb_silkscreen_rect_id: GR(\"pcb_silkscreen_rect\"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: DR, width: PR, height: PR, layer: yE, stroke_width: PR.default(\"1mm\"), corner_radius: PR.optional(), is_filled: Wa.boolean().default(true).optional(), has_stroke: Wa.boolean().optional(), is_stroke_dashed: Wa.boolean().optional(), ccw_rotation: Wa.number().optional() }).describe(\"Defines a silkscreen rect on the PCB\");\nvar hk = Wa.object({ type: Wa.literal(\"pcb_silkscreen_circle\"), pcb_silkscreen_circle_id: GR(\"pcb_silkscreen_circle\"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: DR, radius: PR, layer: bE, stroke_width: PR.default(\"1mm\"), is_filled: Wa.boolean().optional() }).describe(\"Defines a silkscreen circle on the PCB\");\nvar dk = Wa.object({ type: Wa.literal(\"pcb_silkscreen_oval\"), pcb_silkscreen_oval_id: GR(\"pcb_silkscreen_oval\"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: DR, radius_x: wR, radius_y: wR, layer: bE, ccw_rotation: OR.optional() }).describe(\"Defines a silkscreen oval on the PCB\");\nvar uk = Wa.object({ type: Wa.literal(\"pcb_silkscreen_graphic\"), pcb_silkscreen_graphic_id: GR(\"pcb_silkscreen_graphic\"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), layer: bE, image_asset: qR.optional() }).extend({ shape: Wa.literal(\"brep\"), brep_shape: vA }).describe(\"Defines a BRep silkscreen graphic on the PCB\");\nvar pk = Wa.discriminatedUnion(\"shape\", [uk]).describe(\"Defines a silkscreen graphic on the PCB\");\nvar mk = Wa.object({ type: Wa.literal(\"pcb_silkscreen_pill\"), pcb_silkscreen_pill_id: GR(\"pcb_silkscreen_pill\"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: DR, width: PR, height: PR, layer: yE, ccw_rotation: Wa.number().optional() }).describe(\"Defines a silkscreen pill on the PCB\");\nvar gk = Wa.object({ type: Wa.literal(\"pcb_fabrication_note_text\"), pcb_fabrication_note_text_id: GR(\"pcb_fabrication_note_text\"), subcircuit_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), font: Wa.literal(\"tscircuit2024\").default(\"tscircuit2024\"), font_size: wR.default(\"1mm\"), pcb_component_id: Wa.string(), text: Wa.string(), ccw_rotation: Wa.number().optional(), layer: bE, anchor_position: DR.default({ x: 0, y: 0 }), anchor_alignment: Wa.enum([\"center\", \"top_left\", \"top_right\", \"bottom_left\", \"bottom_right\"]).default(\"center\"), color: Wa.string().optional() }).describe(\"Defines a fabrication note in text on the PCB, useful for leaving notes for assemblers or fabricators\");\nvar fk = Wa.object({ type: Wa.literal(\"pcb_fabrication_note_path\"), pcb_fabrication_note_path_id: GR(\"pcb_fabrication_note_path\"), pcb_component_id: Wa.string(), subcircuit_id: Wa.string().optional(), layer: yE, route: Wa.array(DR), stroke_width: PR, color: Wa.string().optional(), is_filled: Wa.boolean().optional(), has_stroke: Wa.boolean().optional() }).describe(\"Defines a fabrication path on the PCB for fabricators or assemblers\");\nvar _k = Wa.object({ type: Wa.literal(\"pcb_fabrication_note_rect\"), pcb_fabrication_note_rect_id: GR(\"pcb_fabrication_note_rect\"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: DR, width: PR, height: PR, layer: bE, stroke_width: PR.default(\"0.1mm\"), corner_radius: PR.optional(), is_filled: Wa.boolean().optional(), has_stroke: Wa.boolean().optional(), is_stroke_dashed: Wa.boolean().optional(), color: Wa.string().optional() }).describe(\"Defines a fabrication note rectangle on the PCB\");\nvar yk = Wa.object({ type: Wa.literal(\"pcb_fabrication_note_dimension\"), pcb_fabrication_note_dimension_id: GR(\"pcb_fabrication_note_dimension\"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), layer: bE, from: DR, to: DR, text: Wa.string().optional(), text_ccw_rotation: Wa.number().optional(), offset: PR.optional(), offset_distance: PR.optional(), offset_direction: Wa.object({ x: Wa.number(), y: Wa.number() }).optional(), font: Wa.literal(\"tscircuit2024\").default(\"tscircuit2024\"), font_size: PR.default(\"1mm\"), color: Wa.string().optional(), arrow_size: PR.default(\"1mm\") }).describe(\"Defines a measurement annotation within PCB fabrication notes\");\nvar bk = Wa.object({ type: Wa.literal(\"pcb_note_text\"), pcb_note_text_id: GR(\"pcb_note_text\"), pcb_component_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), name: Wa.string().optional(), font: Wa.literal(\"tscircuit2024\").default(\"tscircuit2024\"), font_size: wR.default(\"1mm\"), text: Wa.string().optional(), anchor_position: DR.default({ x: 0, y: 0 }), anchor_alignment: Wa.enum([\"center\", \"top_left\", \"top_right\", \"bottom_left\", \"bottom_right\"]).default(\"center\"), layer: bE.default(\"top\"), is_mirrored_from_top_view: Wa.boolean().optional(), color: Wa.string().optional() }).describe(\"Defines a documentation note in text on the PCB\");\nvar xk = Wa.object({ type: Wa.literal(\"pcb_note_rect\"), pcb_note_rect_id: GR(\"pcb_note_rect\"), pcb_component_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), name: Wa.string().optional(), text: Wa.string().optional(), center: DR, width: PR, height: PR, layer: bE.default(\"top\"), stroke_width: PR.default(\"0.1mm\"), corner_radius: PR.optional(), is_filled: Wa.boolean().optional(), has_stroke: Wa.boolean().optional(), is_stroke_dashed: Wa.boolean().optional(), color: Wa.string().optional() }).describe(\"Defines a rectangular documentation note on the PCB\");\nvar vk = Wa.object({ type: Wa.literal(\"pcb_note_path\"), pcb_note_path_id: GR(\"pcb_note_path\"), pcb_component_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), name: Wa.string().optional(), text: Wa.string().optional(), route: Wa.array(DR), layer: bE.default(\"top\"), stroke_width: PR.default(\"0.1mm\"), color: Wa.string().optional() }).describe(\"Defines a polyline documentation note on the PCB\");\nvar Ik = Wa.object({ type: Wa.literal(\"pcb_note_line\"), pcb_note_line_id: GR(\"pcb_note_line\"), pcb_component_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), name: Wa.string().optional(), text: Wa.string().optional(), x1: wR, y1: wR, x2: wR, y2: wR, layer: bE.default(\"top\"), stroke_width: wR.default(\"0.1mm\"), color: Wa.string().optional(), is_dashed: Wa.boolean().optional() }).describe(\"Defines a straight documentation note line on the PCB\");\nvar Sk = Wa.object({ type: Wa.literal(\"pcb_note_dimension\"), pcb_note_dimension_id: GR(\"pcb_note_dimension\"), pcb_component_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), name: Wa.string().optional(), from: DR, to: DR, text: Wa.string().optional(), text_ccw_rotation: Wa.number().optional(), offset_distance: PR.optional(), offset_direction: Wa.object({ x: Wa.number(), y: Wa.number() }).optional(), font: Wa.literal(\"tscircuit2024\").default(\"tscircuit2024\"), font_size: PR.default(\"1mm\"), layer: bE.default(\"top\"), color: Wa.string().optional(), arrow_size: PR.default(\"1mm\") }).describe(\"Defines a measurement annotation within PCB documentation notes\");\nvar Ck = uT.extend({ type: Wa.literal(\"pcb_footprint_overlap_error\"), pcb_error_id: GR(\"pcb_error\"), error_type: Wa.literal(\"pcb_footprint_overlap_error\").default(\"pcb_footprint_overlap_error\"), pcb_smtpad_ids: Wa.array(Wa.string()).optional(), pcb_plated_hole_ids: Wa.array(Wa.string()).optional(), pcb_hole_ids: Wa.array(Wa.string()).optional(), pcb_keepout_ids: Wa.array(Wa.string()).optional() }).describe(\"Error emitted when a pcb footprint overlaps with another element\");\nvar Pk = uT.extend({ type: Wa.literal(\"pcb_courtyard_overlap_error\"), pcb_error_id: GR(\"pcb_error\"), error_type: Wa.literal(\"pcb_courtyard_overlap_error\").default(\"pcb_courtyard_overlap_error\"), pcb_component_ids: Wa.tuple([Wa.string(), Wa.string()]) }).describe(\"Error emitted when the courtyard (CrtYd) of one PCB component overlaps with the courtyard of another\");\nvar Mk = Wa.object({ type: Wa.literal(\"pcb_keepout\"), shape: Wa.literal(\"outline\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), outline: Wa.array(DR).min(2), stroke_width: PR, pcb_keepout_id: Wa.string(), layers: Wa.array(Wa.string()), description: Wa.string().optional(), excluded_pcb_component_ids: Wa.array(Wa.string()).optional(), warning_only: Wa.boolean().optional(), allow_traces: Wa.boolean().optional(), allow_placements: Wa.boolean().optional() });\nvar wk = Wa.object({ type: Wa.literal(\"pcb_keepout\"), shape: Wa.literal(\"rect\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: DR, width: wR, height: wR, pcb_keepout_id: Wa.string(), layers: Wa.array(Wa.string()), description: Wa.string().optional(), excluded_pcb_component_ids: Wa.array(Wa.string()).optional(), warning_only: Wa.boolean().optional(), allow_traces: Wa.boolean().optional(), allow_placements: Wa.boolean().optional() }).or(Wa.object({ type: Wa.literal(\"pcb_keepout\"), shape: Wa.literal(\"circle\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: DR, radius: wR, pcb_keepout_id: Wa.string(), layers: Wa.array(Wa.string()), description: Wa.string().optional(), excluded_pcb_component_ids: Wa.array(Wa.string()).optional(), warning_only: Wa.boolean().optional(), allow_traces: Wa.boolean().optional(), allow_placements: Wa.boolean().optional() })).or(Mk);\nvar Nk = Wa.object({ type: Wa.literal(\"pcb_keepout_overlap_warning\"), pcb_keepout_overlap_warning_id: GR(\"pcb_keepout_overlap_warning\"), warning_type: Wa.literal(\"pcb_keepout_overlap_warning\").default(\"pcb_keepout_overlap_warning\"), message: Wa.string(), pcb_keepout_id: Wa.string(), pcb_component_ids: Wa.array(Wa.string()).optional(), pcb_trace_ids: Wa.array(Wa.string()).optional(), pcb_smtpad_ids: Wa.array(Wa.string()).optional(), pcb_plated_hole_ids: Wa.array(Wa.string()).optional(), pcb_via_ids: Wa.array(Wa.string()).optional(), center: DR.optional(), subcircuit_id: Wa.string().optional() }).describe(\"Warning emitted when copper overlaps a PCB keepout with warning_only enabled\");\nvar Rk = Wa.object({ type: Wa.literal(\"pcb_cutout\"), pcb_cutout_id: GR(\"pcb_cutout\"), pcb_component_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), pcb_board_id: Wa.string().optional(), pcb_panel_id: Wa.string().optional() });\nvar Tk = Rk.extend({ shape: Wa.literal(\"rect\"), center: DR, width: PR, height: PR, rotation: OR.optional(), corner_radius: PR.optional() });\nvar Ek = Rk.extend({ shape: Wa.literal(\"circle\"), center: DR, radius: PR });\nvar Ak = Rk.extend({ shape: Wa.literal(\"polygon\"), points: Wa.array(DR) });\nvar Ok = Rk.extend({ shape: Wa.literal(\"path\"), route: Wa.array(DR), slot_width: PR, slot_length: PR.optional(), space_between_slots: PR.optional(), slot_corner_radius: PR.optional() });\nvar kk = Wa.discriminatedUnion(\"shape\", [Tk, Ek, Ak, Ok]).describe(\"Defines a cutout on the PCB, removing board material.\");\nvar Dk = uT.extend({ type: Wa.literal(\"pcb_missing_footprint_error\"), pcb_missing_footprint_error_id: GR(\"pcb_missing_footprint_error\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), error_type: Wa.literal(\"pcb_missing_footprint_error\").default(\"pcb_missing_footprint_error\"), source_component_id: Wa.string() }).describe(\"Defines a missing footprint error on the PCB\");\nvar Lk = uT.extend({ type: Wa.literal(\"external_footprint_load_error\"), external_footprint_load_error_id: GR(\"external_footprint_load_error\"), pcb_component_id: Wa.string(), source_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), footprinter_string: Wa.string().optional(), error_type: Wa.literal(\"external_footprint_load_error\").default(\"external_footprint_load_error\") }).describe(\"Defines an error when an external footprint fails to load\");\nvar zk = uT.extend({ type: Wa.literal(\"circuit_json_footprint_load_error\"), circuit_json_footprint_load_error_id: GR(\"circuit_json_footprint_load_error\"), pcb_component_id: Wa.string(), source_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), error_type: Wa.literal(\"circuit_json_footprint_load_error\").default(\"circuit_json_footprint_load_error\"), circuit_json: Wa.array(Wa.any()).optional() }).describe(\"Defines an error when a circuit JSON footprint fails to load\");\nvar Bk = Wa.object({ type: Wa.literal(\"pcb_group\"), pcb_group_id: GR(\"pcb_group\"), source_group_id: Wa.string(), is_subcircuit: Wa.boolean().optional(), subcircuit_id: Wa.string().optional(), width: PR.optional(), height: PR.optional(), center: DR, display_offset_x: Wa.string().optional().describe(\"How to display the x offset for this group, usually corresponding with how the user specified it\"), display_offset_y: Wa.string().optional().describe(\"How to display the y offset for this group, usually corresponding with how the user specified it\"), outline: Wa.array(DR).optional(), anchor_position: DR.optional(), anchor_alignment: UR.default(\"center\"), position_mode: Wa.enum([\"packed\", \"relative_to_group_anchor\", \"none\"]).optional(), positioned_relative_to_pcb_group_id: Wa.string().optional(), positioned_relative_to_pcb_board_id: Wa.string().optional(), pcb_component_ids: Wa.array(Wa.string()), child_layout_mode: Wa.enum([\"packed\", \"none\"]).optional(), name: Wa.string().optional(), description: Wa.string().optional(), layout_mode: Wa.string().optional(), autorouter_configuration: Wa.object({ trace_clearance: PR }).optional(), autorouter_used_string: Wa.string().optional() }).describe(\"Defines a group of components on the PCB\");\nvar Fk = uT.extend({ type: Wa.literal(\"pcb_autorouting_error\"), pcb_error_id: GR(\"pcb_autorouting_error\"), error_type: Wa.literal(\"pcb_autorouting_error\").default(\"pcb_autorouting_error\"), subcircuit_id: Wa.string().optional() }).describe(\"The autorouting has failed to route a portion of the board\");\nvar jk = uT.extend({ type: Wa.literal(\"pcb_preflight_routing_error\"), pcb_preflight_routing_error_id: GR(\"pcb_preflight_routing_error\"), error_type: Wa.literal(\"pcb_preflight_routing_error\").default(\"pcb_preflight_routing_error\"), error_code: Wa.string(), subcircuit_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), routing_phase_index: Wa.number().int().optional(), phase_name: Wa.string().optional(), source_trace_ids: Wa.array(Wa.string()).optional(), pcb_component_ids: Wa.array(Wa.string()).optional(), pcb_port_ids: Wa.array(Wa.string()).optional(), related_error_ids: Wa.array(Wa.string()).optional(), measurements: Wa.record(Wa.number().finite()).optional() });\nvar $k = Wa.object({ type: Wa.literal(\"pcb_manual_edit_conflict_warning\"), pcb_manual_edit_conflict_warning_id: GR(\"pcb_manual_edit_conflict_warning\"), warning_type: Wa.literal(\"pcb_manual_edit_conflict_warning\").default(\"pcb_manual_edit_conflict_warning\"), message: Wa.string(), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), source_component_id: Wa.string() }).describe(\"Warning emitted when a component has both manual placement and explicit pcbX/pcbY coordinates\");\nvar Yk = Wa.enum([\"x-\", \"x+\", \"y+\", \"y-\"]);\nvar Xk = Wa.object({ type: Wa.literal(\"pcb_connector_not_in_accessible_orientation_warning\"), pcb_connector_not_in_accessible_orientation_warning_id: GR(\"pcb_connector_not_in_accessible_orientation_warning\"), warning_type: Wa.literal(\"pcb_connector_not_in_accessible_orientation_warning\").default(\"pcb_connector_not_in_accessible_orientation_warning\"), message: Wa.string(), pcb_component_id: Wa.string(), source_component_id: Wa.string().optional(), pcb_board_id: Wa.string().optional(), facing_direction: Yk, recommended_facing_direction: Yk, subcircuit_id: Wa.string().optional() }).describe(\"Warning emitted when a connector PCB component is facing inward toward the board and should be reoriented to an outward-facing direction\");\nvar Hk = Wa.object({ type: Wa.literal(\"pcb_component_missing_courtyard_warning\"), pcb_component_missing_courtyard_warning_id: GR(\"pcb_component_missing_courtyard_warning\"), warning_type: Wa.literal(\"pcb_component_missing_courtyard_warning\").default(\"pcb_component_missing_courtyard_warning\"), message: Wa.string(), pcb_component_id: Wa.string(), source_component_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe(\"Warning emitted when a PCB component has no courtyard geometry\");\nvar Vk = Wa.object({ type: Wa.literal(\"supplier_footprint_mismatch_warning\"), supplier_footprint_mismatch_warning_id: GR(\"supplier_footprint_mismatch_warning\"), warning_type: Wa.literal(\"supplier_footprint_mismatch_warning\").default(\"supplier_footprint_mismatch_warning\"), message: Wa.string(), source_component_id: Wa.string(), pcb_component_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), supplier_name: pT.optional(), supplier_part_number: Wa.string().optional(), supplier_footprint_url: Wa.string().optional(), footprint_copper_intersection_over_union: Wa.number() }).describe(\"Warning emitted when a supplier part footprint does not match the expected footprint\");\nvar Wk = Wa.object({ type: Wa.literal(\"pcb_fabricator_extra_charge_warning\"), pcb_fabricator_extra_charge_warning_id: GR(\"pcb_fabricator_extra_charge_warning\"), warning_type: Wa.literal(\"pcb_fabricator_extra_charge_warning\").default(\"pcb_fabricator_extra_charge_warning\"), message: Wa.string(), fabricator_preset: Wa.string(), pcb_board_id: Wa.string().optional(), pcb_via_ids: Wa.array(Wa.string()).optional(), subcircuit_id: Wa.string().optional() }).describe(\"Warning that a design feature incurs an extra charge for the selected fabricator preset, such as via hole diameters below 0.3 mm with JLCPCB economy or standard presets.\");\nvar Gk = Wa.object({ type: Wa.literal(\"pcb_breakout_point\"), pcb_breakout_point_id: GR(\"pcb_breakout_point\"), pcb_group_id: Wa.string(), subcircuit_id: Wa.string().optional(), source_trace_id: Wa.string().optional(), source_port_id: Wa.string().optional(), source_net_id: Wa.string().optional(), layer: yE.optional(), x: wR, y: wR }).describe(\"Defines a routing target within a pcb_group for a source_trace or source_net\");\nvar Uk = Wa.object({ type: Wa.literal(\"pcb_ground_plane\"), pcb_ground_plane_id: GR(\"pcb_ground_plane\"), source_pcb_ground_plane_id: Wa.string(), source_net_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe(\"Defines a ground plane on the PCB\");\nvar Zk = Wa.object({ type: Wa.literal(\"pcb_ground_plane_region\"), pcb_ground_plane_region_id: GR(\"pcb_ground_plane_region\"), pcb_ground_plane_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), layer: yE, points: Wa.array(DR) }).describe(\"Defines a polygon region of a ground plane\");\nvar qk = Wa.object({ type: Wa.literal(\"pcb_thermal_spoke\"), pcb_thermal_spoke_id: GR(\"pcb_thermal_spoke\"), pcb_ground_plane_id: Wa.string(), shape: Wa.string(), spoke_count: Wa.number(), spoke_thickness: wR, spoke_inner_diameter: wR, spoke_outer_diameter: wR, pcb_plated_hole_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe(\"Pattern for connecting a ground plane to a plated hole\");\nvar Jk = Wa.object({ type: Wa.literal(\"pcb_copper_pour\"), pcb_copper_pour_id: GR(\"pcb_copper_pour\"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), layer: yE, source_net_id: Wa.string().optional(), covered_with_solder_mask: Wa.boolean().optional().default(true) });\nvar Qk = Jk.extend({ shape: Wa.literal(\"rect\"), center: DR, width: PR, height: PR, rotation: OR.optional() });\nvar Kk = Jk.extend({ shape: Wa.literal(\"brep\"), brep_shape: vA });\nvar eD = Jk.extend({ shape: Wa.literal(\"polygon\"), points: Wa.array(DR) });\nvar tD = Wa.discriminatedUnion(\"shape\", [Qk, Kk, eD]).describe(\"Defines a copper pour on the PCB.\");\nvar nD = uT.extend({ type: Wa.literal(\"pcb_component_outside_board_error\"), pcb_component_outside_board_error_id: GR(\"pcb_component_outside_board_error\"), error_type: Wa.literal(\"pcb_component_outside_board_error\").default(\"pcb_component_outside_board_error\"), pcb_component_id: Wa.string(), pcb_board_id: Wa.string(), component_center: DR, component_bounds: Wa.object({ min_x: Wa.number(), max_x: Wa.number(), min_y: Wa.number(), max_y: Wa.number() }), subcircuit_id: Wa.string().optional(), source_component_id: Wa.string().optional() }).describe(\"Error emitted when a PCB component is placed outside the board boundaries\");\nvar oD = uT.extend({ type: Wa.literal(\"pcb_component_not_on_board_edge_error\"), pcb_component_not_on_board_edge_error_id: GR(\"pcb_component_not_on_board_edge_error\"), error_type: Wa.literal(\"pcb_component_not_on_board_edge_error\").default(\"pcb_component_not_on_board_edge_error\"), pcb_component_id: Wa.string(), pcb_board_id: Wa.string(), component_center: DR, pad_to_nearest_board_edge_distance: Wa.number(), source_component_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe(\"Error emitted when a component that must be placed on the board edge is centered away from the edge\");\nvar iD = uT.extend({ type: Wa.literal(\"pcb_component_invalid_layer_error\"), pcb_component_invalid_layer_error_id: GR(\"pcb_component_invalid_layer_error\"), error_type: Wa.literal(\"pcb_component_invalid_layer_error\").default(\"pcb_component_invalid_layer_error\"), pcb_component_id: Wa.string().optional(), source_component_id: Wa.string(), layer: yE, subcircuit_id: Wa.string().optional() }).describe(\"Error emitted when a component is placed on an invalid layer (components can only be on 'top' or 'bottom' layers)\");\nvar rD = uT.extend({ type: Wa.literal(\"pcb_via_clearance_error\"), pcb_error_id: GR(\"pcb_error\"), error_type: Wa.literal(\"pcb_via_clearance_error\").default(\"pcb_via_clearance_error\"), pcb_via_ids: Wa.array(Wa.string()).min(2), minimum_clearance: wR.optional(), actual_clearance: wR.optional(), pcb_center: Wa.object({ x: Wa.number().optional(), y: Wa.number().optional() }).optional(), subcircuit_id: Wa.string().optional() }).describe(\"Error emitted when vias are closer than the allowed clearance\");\nvar sD = uT.extend({ type: Wa.literal(\"pcb_via_trace_clearance_error\"), pcb_via_trace_clearance_error_id: GR(\"pcb_via_trace_clearance_error\"), error_type: Wa.literal(\"pcb_via_trace_clearance_error\").default(\"pcb_via_trace_clearance_error\"), pcb_via_id: Wa.string(), pcb_trace_id: Wa.string(), minimum_clearance: wR.optional(), actual_clearance: wR.optional(), center: Wa.object({ x: Wa.number().optional(), y: Wa.number().optional() }).optional(), subcircuit_id: Wa.string().optional() }).describe(\"Error emitted when a via and trace are closer than the allowed clearance\");\nvar aD = uT.extend({ type: Wa.literal(\"pcb_pad_pad_clearance_error\"), pcb_pad_pad_clearance_error_id: GR(\"pcb_pad_pad_clearance_error\"), error_type: Wa.literal(\"pcb_pad_pad_clearance_error\").default(\"pcb_pad_pad_clearance_error\"), pcb_pad_ids: Wa.array(Wa.string()).min(2), minimum_clearance: wR.optional(), actual_clearance: wR.optional(), center: Wa.object({ x: Wa.number().optional(), y: Wa.number().optional() }).optional(), subcircuit_id: Wa.string().optional() }).describe(\"Error emitted when pads are closer than the allowed clearance\");\nvar cD = uT.extend({ type: Wa.literal(\"pcb_pad_trace_clearance_error\"), pcb_pad_trace_clearance_error_id: GR(\"pcb_pad_trace_clearance_error\"), error_type: Wa.literal(\"pcb_pad_trace_clearance_error\").default(\"pcb_pad_trace_clearance_error\"), pcb_pad_id: Wa.string(), pcb_trace_id: Wa.string(), minimum_clearance: wR.optional(), actual_clearance: wR.optional(), center: Wa.object({ x: Wa.number().optional(), y: Wa.number().optional() }).optional(), subcircuit_id: Wa.string().optional() }).describe(\"Error emitted when a pad and trace are closer than allowed clearance\");\nvar lD = Wa.object({ type: Wa.literal(\"pcb_courtyard_rect\"), pcb_courtyard_rect_id: GR(\"pcb_courtyard_rect\"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: DR, width: PR, height: PR, layer: bE, ccw_rotation: OR.optional(), color: Wa.string().optional() }).describe(\"Defines a courtyard rectangle on the PCB\");\nvar hD = Wa.object({ type: Wa.literal(\"pcb_courtyard_outline\"), pcb_courtyard_outline_id: GR(\"pcb_courtyard_outline\"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), layer: bE, outline: Wa.array(DR).min(2) }).describe(\"Defines a courtyard outline on the PCB\");\nvar dD = Wa.object({ type: Wa.literal(\"pcb_courtyard_polygon\"), pcb_courtyard_polygon_id: GR(\"pcb_courtyard_polygon\"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), layer: bE, points: Wa.array(DR).min(3), color: Wa.string().optional() }).describe(\"Defines a courtyard polygon on the PCB\");\nvar uD = Wa.object({ type: Wa.literal(\"pcb_courtyard_circle\"), pcb_courtyard_circle_id: GR(\"pcb_courtyard_circle\"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: DR, radius: PR, layer: bE, color: Wa.string().optional() }).describe(\"Defines a courtyard circle on the PCB\");\nvar pD = Wa.object({ type: Wa.literal(\"pcb_courtyard_pill\"), pcb_courtyard_pill_id: GR(\"pcb_courtyard_pill\"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: DR, width: PR, height: PR, radius: PR, layer: bE, color: Wa.string().optional() }).describe(\"Defines a courtyard pill on the PCB\");\nvar mD = [\"obj\", \"stl\", \"3mf\", \"gltf\", \"glb\", \"step\", \"wrl\"];\nvar gD = [\"x+\", \"x-\", \"y+\", \"y-\", \"z+\", \"z-\"];\nvar fD = { obj: \"z+\", stl: \"z+\", \"3mf\": \"z+\", gltf: \"y+\", glb: \"y+\", step: \"z+\", wrl: \"y+\" };\nvar _D = Wa.object({ type: Wa.literal(\"cad_component\"), cad_component_id: Wa.string(), pcb_component_id: Wa.string().optional().describe(\"Optional PCB component reference; omit for CAD geometry without a PCB component\"), source_component_id: Wa.string(), position: zR, rotation: zR.optional(), is_on_folded_board: Wa.boolean().optional().describe(\"True when position and rotation describe the assembled folded board pose. False or omitted means the flat board pose. PCB records remain flat; pcb_component_id identifies the flat mount and owning board for reversible transforms.\"), size: zR.optional(), layer: yE.optional(), subcircuit_id: Wa.string().optional(), footprinter_string: Wa.string().optional(), model_obj_url: Wa.string().optional(), model_stl_url: Wa.string().optional(), model_3mf_url: Wa.string().optional(), model_gltf_url: Wa.string().optional(), model_glb_url: Wa.string().optional(), model_step_url: Wa.string().optional(), model_wrl_url: Wa.string().optional(), model_asset: qR.optional(), model_unit_to_mm_scale_factor: Wa.number().optional(), model_board_normal_direction: Wa.enum(gD).optional().describe(`The direction in the model's coordinate space that is considered \"up\" or \"coming out of the board surface\"`), model_origin_position: zR.optional(), model_origin_alignment: Wa.enum([\"unknown\", \"center\", \"center_of_component_on_board_surface\", \"bottom_center_of_component\"]).optional(), model_object_fit: Wa.enum([\"contain_within_bounds\", \"fill_bounds\"]).optional().default(\"contain_within_bounds\"), model_jscad: Wa.any().optional(), color: Wa.string().trim().min(1).optional().describe(\"Explicit color override for CAD geometry, including authored JSCAD material colors. Omit to preserve model materials.\"), show_as_translucent_model: Wa.boolean().optional(), show_as_bounding_box: Wa.boolean().optional(), show_hidden_edges: Wa.boolean().optional(), anchor_alignment: Wa.enum([\"center\", \"center_of_component_on_board_surface\"]).optional().default(\"center\") }).describe(\"Defines CAD geometry, optionally associated with a PCB component\");\nvar yD = uT.extend({ type: Wa.literal(\"cad_collision_error\"), cad_collision_error_id: GR(\"cad_collision_error\"), error_type: Wa.literal(\"cad_collision_error\").default(\"cad_collision_error\"), cad_component_ids: Wa.array(Wa.string()).min(1), pcb_component_ids: Wa.array(Wa.string()).optional(), source_component_ids: Wa.array(Wa.string()).min(1), intersection_area_mm2: Wa.number().finite().nonnegative(), threshold_area_mm2: Wa.number().finite().nonnegative() }).describe(\"An aperture-bearing part intersects the finished enclosure. The intersection_area_mm2 is the union silhouette area of the solid intersection projected along the aperture face normal, in the right-handed Circuit JSON world frame (+X right, +Y top, +Z above). It is an area in square millimetres, not intersection volume or surface area. This indicates possible aperture misplacement, insufficient size/depth, or body clearance problems; it does not prove which cause applies.\");\nvar bD = zR.refine((e35) =\u003e [e35.x, e35.y, e35.z].every(Number.isFinite), \"Connector pin 1 positions must be finite\").describe(\"Resolved pin 1 position at the connector mating face, in right-handed circuit world, millimeters: +X right, +Y top, +Z above. An absolute point, not a direction. Computed by the circuit producer from endpoint geometry. Together with the endpoint path tangent, fixes connector roll and identifies its pin 1 side; renderers must not infer it from footprints.\");\nvar xD = Wa.object({ type: Wa.literal(\"cad_cable\"), cad_cable_id: Wa.string(), name: Wa.string().min(1), from_source_component_id: Wa.string(), to_source_component_id: Wa.string(), from_connector_pin1_position: bD.optional(), to_connector_pin1_position: bD.optional(), cableprinter_string: Wa.string().min(1).describe('Physical cable definition, e.g. \"usb_c\" or \"jst_ph_pins6\". Independent of the route.'), path: Wa.array(zR).min(2).refine((e35) =\u003e e35.every((t2, n2) =\u003e [t2.x, t2.y, t2.z].every(Number.isFinite) \u0026\u0026 (n2 === 0 || Math.hypot(t2.x - e35[n2 - 1].x, t2.y - e35[n2 - 1].y, t2.z - e35[n2 - 1].z) \u003e 0.00000001)), \"Cable paths require finite, distinct consecutive points\").describe(\"Resolved cable centerline points in right-handed circuit world, millimeters: +X right, +Y top, +Z above. First/last samples are connector wire exits; their tangents point into/out of the cable. Includes routing/slack; renderers must not recompute the path.\") }).describe(\"A physical assembly cable with a resolved 3D route. Several cables are independent cad_cable records, each with its own endpoints, definition and path. Does not imply electrical pin mapping.\");\nvar vD = 0.000001;\nvar ID = Wa.object({ x: Wa.number().finite(), y: Wa.number().finite(), z: Wa.number().finite() }).refine((e35) =\u003e Math.abs(Math.hypot(e35.x, e35.y, e35.z) - 1) \u003c= vD, \"Reference surface directions must be unit vectors\");\nvar SD = wR.pipe(Wa.number().finite().positive());\nvar CD = Wa.object({ type: Wa.literal(\"cad_reference_surface\"), cad_reference_surface_id: Wa.string().min(1), source_component_id: Wa.string().min(1).describe(\"Owning assembly part's source component ID. The part may have no CAD geometry.\"), name: Wa.string().trim().min(1).describe(\"Reference name, unique within the owning part, e.g. shade in STEM.shade.\"), shape: Wa.literal(\"rect\"), center: zR.refine((e35) =\u003e [e35.x, e35.y, e35.z].every(Number.isFinite), \"Reference surface centers must be finite\").describe(\"Resolved surface center in right-handed circuit-world XYZ, millimeters: +X right, +Y top, +Z above. An absolute point after assembly placement.\"), normal: ID.describe(\"Outward unit normal in circuit-world XYZ. Dimensionless direction; transform with the part's rotation, without translation.\"), x_axis: ID.describe(\"In-plane unit X direction in circuit-world XYZ, perpendicular to normal. The second tangent is normal cross x_axis, giving a right-handed frame.\"), width: SD.optional().describe(\"Rectangular extent along x_axis in millimeters. Supply together with height. Omission leaves the surface's display size unspecified.\"), height: SD.optional().describe(\"Rectangular extent along normal cross x_axis in millimeters. Supply together with width.\"), subcircuit_id: Wa.string().optional() }).superRefine((e35, t2) =\u003e {\n e35.width === undefined != (e35.height === undefined) \u0026\u0026 t2.addIssue({ code: Wa.ZodIssueCode.custom, path: [\"width\"], message: \"Provide width and height together\" });\n const { normal: n2, x_axis: o3 } = e35;\n Math.abs(n2.x * o3.x + n2.y * o3.y + n2.z * o3.z) \u003e vD \u0026\u0026 t2.addIssue({ code: Wa.ZodIssueCode.custom, path: [\"x_axis\"], message: \"x_axis must be perpendicular to normal\" });\n}).describe(\"A named assembly mounting surface with a resolved world-space frame. Reference geometry for optional visualization; does not add solid material or electrical connectivity. The producer resolves part placement independently of CAD-model offsets; renderers consume the world frame without reapplying the owning model's transform.\");\nvar PD = Wa.enum([\"sinewave\", \"square\", \"triangle\", \"sawtooth\"]);\nvar MD = Wa.union([Wa.string(), Wa.number()]).transform((e35) =\u003e typeof e35 == \"string\" ? e35.endsWith(\"%\") ? parseFloat(e35.slice(0, -1)) / 100 : parseFloat(e35) : e35).pipe(Wa.number().min(0, \"Duty cycle must be non-negative\").max(1, \"Duty cycle cannot be greater than 100%\"));\nvar wD = Wa.object({ type: Wa.literal(\"simulation_voltage_source\"), simulation_voltage_source_id: GR(\"simulation_voltage_source\"), is_dc_source: Wa.literal(true).optional().default(true), positive_source_port_id: Wa.string().optional(), negative_source_port_id: Wa.string().optional(), positive_source_net_id: Wa.string().optional(), negative_source_net_id: Wa.string().optional(), voltage: CR, ac_magnitude: CR.optional(), ac_phase: OR.optional() }).describe(\"Defines a DC voltage source for simulation\");\nvar ND = Wa.object({ type: Wa.literal(\"simulation_voltage_source\"), simulation_voltage_source_id: GR(\"simulation_voltage_source\"), is_dc_source: Wa.literal(false), terminal1_source_port_id: Wa.string().optional(), terminal2_source_port_id: Wa.string().optional(), terminal1_source_net_id: Wa.string().optional(), terminal2_source_net_id: Wa.string().optional(), voltage: CR.optional(), frequency: MR.optional(), peak_to_peak_voltage: CR.optional(), wave_shape: PD.optional(), phase: OR.optional(), duty_cycle: MD.optional(), pulse_delay: ER.optional(), rise_time: ER.optional(), fall_time: ER.optional(), pulse_width: ER.optional(), period: ER.optional(), ac_magnitude: CR.optional(), ac_phase: OR.optional() }).describe(\"Defines an AC voltage source for simulation\");\nvar RD = Wa.union([wD, ND]).describe(\"Defines a voltage source for simulation\");\nvar TD = Wa.union([Wa.string(), Wa.number()]).transform((e35) =\u003e typeof e35 == \"string\" ? e35.endsWith(\"%\") ? parseFloat(e35.slice(0, -1)) / 100 : parseFloat(e35) : e35).pipe(Wa.number().min(0, \"Duty cycle must be non-negative\").max(1, \"Duty cycle cannot be greater than 100%\"));\nvar ED = Wa.object({ type: Wa.literal(\"simulation_current_source\"), simulation_current_source_id: GR(\"simulation_current_source\"), is_dc_source: Wa.literal(true).optional().default(true), positive_source_port_id: Wa.string().optional(), negative_source_port_id: Wa.string().optional(), positive_source_net_id: Wa.string().optional(), negative_source_net_id: Wa.string().optional(), current: NR, ac_magnitude: NR.optional(), ac_phase: OR.optional() }).describe(\"Defines a DC current source for simulation\");\nvar AD = Wa.object({ type: Wa.literal(\"simulation_current_source\"), simulation_current_source_id: GR(\"simulation_current_source\"), is_dc_source: Wa.literal(false), terminal1_source_port_id: Wa.string().optional(), terminal2_source_port_id: Wa.string().optional(), terminal1_source_net_id: Wa.string().optional(), terminal2_source_net_id: Wa.string().optional(), current: NR.optional(), frequency: MR.optional(), peak_to_peak_current: NR.optional(), wave_shape: PD.optional(), phase: OR.optional(), duty_cycle: TD.optional(), ac_magnitude: NR.optional(), ac_phase: OR.optional() }).describe(\"Defines an AC current source for simulation\");\nvar OD = Wa.union([ED, AD]).describe(\"Defines a current source for simulation\");\nvar kD = Wa.custom((e35) =\u003e e35 === \"V\" || e35 === \"A\");\nvar DD = Wa.custom((e35) =\u003e e35 === \"Ω\" || e35 === \"F\" || e35 === \"H\" || e35 === \"V\" || e35 === \"A\");\nvar LD = Wa.union([Wa.literal(\"spice_dc_sweep\"), Wa.literal(\"spice_dc_operating_point\"), Wa.literal(\"spice_transient_analysis\"), Wa.literal(\"spice_ac_analysis\"), Wa.literal(\"pcb_return_current\")]);\nvar zD = Wa.object({ method: Wa.enum([\"trap\", \"gear\"]).optional(), reltol: Wa.union([Wa.number(), Wa.string()]).optional(), abstol: Wa.union([Wa.number(), Wa.string()]).optional(), vntol: Wa.union([Wa.number(), Wa.string()]).optional() }).describe(\"SPICE solver options for a simulation experiment\");\nvar BD = Wa.object({ type: Wa.literal(\"simulation_experiment\"), simulation_experiment_id: GR(\"simulation_experiment\"), name: Wa.string(), experiment_type: LD, time_per_step: RR.optional(), start_time_ms: ER.optional(), end_time_ms: ER.optional(), spice_options: zD.optional(), dc_sweep_voltage_source_id: Wa.string().optional(), dc_sweep_current_source_id: Wa.string().optional(), dc_sweep_start: Wa.number().optional(), dc_sweep_stop: Wa.number().optional(), dc_sweep_step: Wa.number().refine((e35) =\u003e e35 !== 0).optional(), dc_sweep_unit: kD.optional(), ac_sweep_type: Wa.enum([\"linear\", \"decade\", \"octave\"]).optional(), ac_samples_per_interval: Wa.number().int().positive().optional(), ac_sample_count: Wa.number().int().positive().optional(), ac_start_frequency_hz: Wa.number().positive().optional(), ac_stop_frequency_hz: Wa.number().positive().optional() }).superRefine((e35, t2) =\u003e {\n if (e35.experiment_type === \"spice_dc_sweep\") {\n const n2 = [\"dc_sweep_start\", \"dc_sweep_stop\", \"dc_sweep_step\", \"dc_sweep_unit\"];\n for (const o3 of n2)\n e35[o3] === undefined \u0026\u0026 t2.addIssue({ code: Wa.ZodIssueCode.custom, path: [o3], message: `${o3} is required for a DC sweep` });\n e35.dc_sweep_voltage_source_id !== undefined === (e35.dc_sweep_current_source_id !== undefined) \u0026\u0026 t2.addIssue({ code: Wa.ZodIssueCode.custom, path: [\"dc_sweep_voltage_source_id\"], message: \"Exactly one DC sweep voltage or current source ID is required\" });\n }\n e35.experiment_type === \"spice_ac_analysis\" \u0026\u0026 (e35.ac_sweep_type === undefined \u0026\u0026 t2.addIssue({ code: Wa.ZodIssueCode.custom, path: [\"ac_sweep_type\"], message: \"ac_sweep_type is required for an AC analysis\" }), e35.ac_start_frequency_hz === undefined \u0026\u0026 t2.addIssue({ code: Wa.ZodIssueCode.custom, path: [\"ac_start_frequency_hz\"], message: \"ac_start_frequency_hz is required for an AC analysis\" }), e35.ac_stop_frequency_hz === undefined \u0026\u0026 t2.addIssue({ code: Wa.ZodIssueCode.custom, path: [\"ac_stop_frequency_hz\"], message: \"ac_stop_frequency_hz is required for an AC analysis\" }), e35.ac_sweep_type === \"linear\" \u0026\u0026 e35.ac_sample_count === undefined \u0026\u0026 t2.addIssue({ code: Wa.ZodIssueCode.custom, path: [\"ac_sample_count\"], message: \"ac_sample_count is required for a linear AC analysis\" }), e35.ac_sweep_type !== \"decade\" \u0026\u0026 e35.ac_sweep_type !== \"octave\" || e35.ac_samples_per_interval !== undefined || t2.addIssue({ code: Wa.ZodIssueCode.custom, path: [\"ac_samples_per_interval\"], message: \"ac_samples_per_interval is required for decade and octave AC analyses\" }));\n}).describe(\"Defines a simulation experiment configuration\");\nvar FD = Wa.object({ simulation_parameter_sweep_id: Wa.string(), sweep_index: Wa.number().int().nonnegative(), parameter_value: Wa.number(), parameter_unit: DD });\nvar jD = Wa.object({ type: Wa.literal(\"simulation_transient_voltage_graph\"), simulation_transient_voltage_graph_id: GR(\"simulation_transient_voltage_graph\"), simulation_experiment_id: Wa.string(), simulation_parameter_sweep_coordinate: FD.optional(), timestamps_ms: Wa.array(Wa.number()).optional(), voltage_levels: Wa.array(Wa.number()), source_component_id: Wa.string().optional(), subcircuit_connectivity_map_key: Wa.string().optional(), time_per_step: RR, start_time_ms: ER, end_time_ms: ER, name: Wa.string().optional(), color: Wa.string().optional() }).describe(\"Stores voltage measurements over time for a simulation\");\nvar $D = Wa.object({ type: Wa.literal(\"simulation_transient_current_graph\"), simulation_transient_current_graph_id: GR(\"simulation_transient_current_graph\"), simulation_experiment_id: Wa.string(), simulation_parameter_sweep_coordinate: FD.optional(), timestamps_ms: Wa.array(Wa.number()).optional(), current_levels: Wa.array(Wa.number()), source_component_id: Wa.string().optional(), subcircuit_connectivity_map_key: Wa.string().optional(), time_per_step: RR, start_time_ms: ER, end_time_ms: ER, name: Wa.string().optional(), color: Wa.string().optional() }).describe(\"Stores current measurements over time for a simulation\");\nvar YD = Wa.object({ type: Wa.literal(\"simulation_switch\"), simulation_switch_id: GR(\"simulation_switch\"), source_component_id: Wa.string().optional(), closes_at: ER.optional(), opens_at: ER.optional(), starts_closed: Wa.boolean().optional(), switching_frequency: MR.optional() }).describe(\"Defines a switch for simulation timing control\");\nvar XD = Wa.object({ type: Wa.literal(\"simulation_voltage_probe\"), simulation_voltage_probe_id: GR(\"simulation_voltage_probe\"), source_component_id: Wa.string().optional(), name: Wa.string().optional(), signal_input_source_port_id: Wa.string().optional(), signal_input_source_net_id: Wa.string().optional(), reference_input_source_port_id: Wa.string().optional(), reference_input_source_net_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), color: Wa.string().optional() }).describe(\"Defines a voltage probe for simulation. If a reference input is not provided, it measures against ground. If a reference input is provided, it measures the differential voltage between two points.\").superRefine((e35, t2) =\u003e {\n if (e35.reference_input_source_port_id || e35.reference_input_source_net_id) {\n const n2 = !!e35.signal_input_source_port_id || !!e35.reference_input_source_port_id, o3 = !!e35.signal_input_source_net_id || !!e35.reference_input_source_net_id;\n n2 \u0026\u0026 o3 ? t2.addIssue({ code: Wa.ZodIssueCode.custom, message: \"Cannot mix port and net connections in a differential probe.\" }) : n2 ? e35.signal_input_source_port_id \u0026\u0026 e35.reference_input_source_port_id || t2.addIssue({ code: Wa.ZodIssueCode.custom, message: \"Differential port probe requires both signal_input_source_port_id and reference_input_source_port_id.\" }) : o3 \u0026\u0026 (e35.signal_input_source_net_id \u0026\u0026 e35.reference_input_source_net_id || t2.addIssue({ code: Wa.ZodIssueCode.custom, message: \"Differential net probe requires both signal_input_source_net_id and reference_input_source_net_id.\" }));\n } else\n !!e35.signal_input_source_port_id == !!e35.signal_input_source_net_id \u0026\u0026 t2.addIssue({ code: Wa.ZodIssueCode.custom, message: \"A voltage probe must have exactly one of signal_input_source_port_id or signal_input_source_net_id.\" });\n});\nvar HD = Wa.object({ type: Wa.literal(\"simulation_current_probe\"), simulation_current_probe_id: GR(\"simulation_current_probe\"), source_component_id: Wa.string().optional(), name: Wa.string().optional(), positive_source_port_id: Wa.string().optional(), negative_source_port_id: Wa.string().optional(), positive_source_net_id: Wa.string().optional(), negative_source_net_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), color: Wa.string().optional() }).describe(\"Defines a current probe for simulation. It measures current flowing from the positive endpoint to the negative endpoint.\").superRefine((e35, t2) =\u003e {\n const n2 = !!e35.positive_source_port_id, o3 = !!e35.negative_source_port_id, i3 = !!e35.positive_source_net_id, r3 = !!e35.negative_source_net_id, s2 = n2 || o3, a3 = i3 || r3;\n s2 \u0026\u0026 a3 ? t2.addIssue({ code: Wa.ZodIssueCode.custom, message: \"Cannot mix port and net connections in a current probe.\" }) : s2 ? n2 \u0026\u0026 o3 || t2.addIssue({ code: Wa.ZodIssueCode.custom, message: \"Current probe using source ports requires both positive_source_port_id and negative_source_port_id.\" }) : a3 ? i3 \u0026\u0026 r3 || t2.addIssue({ code: Wa.ZodIssueCode.custom, message: \"Current probe using source nets requires both positive_source_net_id and negative_source_net_id.\" }) : t2.addIssue({ code: Wa.ZodIssueCode.custom, message: \"A current probe must have either positive/negative source port ids or positive/negative source net ids.\" });\n});\nvar VD = uT.extend({ type: Wa.literal(\"simulation_unknown_experiment_error\"), simulation_unknown_experiment_error_id: GR(\"simulation_unknown_experiment_error\"), error_type: Wa.literal(\"simulation_unknown_experiment_error\").default(\"simulation_unknown_experiment_error\"), simulation_experiment_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe(\"An unknown error occurred during the simulation experiment.\");\nvar WD = Wa.enum([\"resistance\", \"capacitance\", \"inductance\", \"voltage\", \"current\"]);\nvar GD = Wa.object({ type: Wa.literal(\"simulation_parameter_sweep\"), simulation_parameter_sweep_id: GR(\"simulation_parameter_sweep\"), simulation_experiment_id: Wa.string(), name: Wa.string().optional(), parameter_values: Wa.array(Wa.number()).min(1), parameter_unit: DD });\nvar UD = Wa.discriminatedUnion(\"parameter_type\", [GD.extend({ parameter_type: Wa.literal(\"resistance\"), resistor_source_component_id: Wa.string() }), GD.extend({ parameter_type: Wa.literal(\"capacitance\"), capacitor_source_component_id: Wa.string() }), GD.extend({ parameter_type: Wa.literal(\"inductance\"), inductor_source_component_id: Wa.string() }), GD.extend({ parameter_type: Wa.literal(\"voltage\"), source_net_id: Wa.string() }), GD.extend({ parameter_type: Wa.literal(\"current\"), current_source_component_id: Wa.string() })]).describe(\"Repeats a simulation experiment over component parameter values\");\nvar ZD = Wa.object({ type: Wa.literal(\"simulation_dc_operating_point_voltage\"), simulation_dc_operating_point_voltage_id: GR(\"simulation_dc_operating_point_voltage\"), simulation_experiment_id: Wa.string(), simulation_parameter_sweep_coordinate: FD.optional(), simulation_voltage_probe_id: Wa.string(), voltage: Wa.number(), name: Wa.string().optional(), color: Wa.string().optional() });\nvar qD = Wa.object({ type: Wa.literal(\"simulation_dc_operating_point_current\"), simulation_dc_operating_point_current_id: GR(\"simulation_dc_operating_point_current\"), simulation_experiment_id: Wa.string(), simulation_parameter_sweep_coordinate: FD.optional(), simulation_current_probe_id: Wa.string(), current: Wa.number(), name: Wa.string().optional(), color: Wa.string().optional() });\nvar JD = Wa.object({ type: Wa.literal(\"simulation_dc_sweep_voltage_graph\"), simulation_dc_sweep_voltage_graph_id: GR(\"simulation_dc_sweep_voltage_graph\"), simulation_experiment_id: Wa.string(), simulation_parameter_sweep_coordinate: FD.optional(), simulation_voltage_probe_id: Wa.string(), sweep_values: Wa.array(Wa.number()), sweep_unit: kD, voltage_levels: Wa.array(Wa.number()), name: Wa.string().optional(), color: Wa.string().optional() }).refine((e35) =\u003e e35.sweep_values.length === e35.voltage_levels.length, { message: \"sweep_values and voltage_levels must have the same length\" });\nvar QD = Wa.object({ type: Wa.literal(\"simulation_dc_sweep_current_graph\"), simulation_dc_sweep_current_graph_id: GR(\"simulation_dc_sweep_current_graph\"), simulation_experiment_id: Wa.string(), simulation_parameter_sweep_coordinate: FD.optional(), simulation_current_probe_id: Wa.string(), sweep_values: Wa.array(Wa.number()), sweep_unit: kD, current_levels: Wa.array(Wa.number()), name: Wa.string().optional(), color: Wa.string().optional() }).refine((e35) =\u003e e35.sweep_values.length === e35.current_levels.length, { message: \"sweep_values and current_levels must have the same length\" });\nvar KD = Wa.object({ re: Wa.number(), im: Wa.number() });\nvar eL = Wa.object({ type: Wa.literal(\"simulation_ac_sweep_voltage_graph\"), simulation_ac_sweep_voltage_graph_id: GR(\"simulation_ac_sweep_voltage_graph\"), simulation_experiment_id: Wa.string(), simulation_parameter_sweep_coordinate: FD.optional(), simulation_voltage_probe_id: Wa.string(), frequencies_hz: Wa.array(Wa.number()), complex_voltages: Wa.array(KD), name: Wa.string().optional(), color: Wa.string().optional() }).refine((e35) =\u003e e35.frequencies_hz.length === e35.complex_voltages.length, { message: \"frequencies_hz and complex_voltages must have the same length\" });\nvar tL = Wa.object({ type: Wa.literal(\"simulation_ac_sweep_current_graph\"), simulation_ac_sweep_current_graph_id: GR(\"simulation_ac_sweep_current_graph\"), simulation_experiment_id: Wa.string(), simulation_parameter_sweep_coordinate: FD.optional(), simulation_current_probe_id: Wa.string(), frequencies_hz: Wa.array(Wa.number()), complex_currents: Wa.array(KD), name: Wa.string().optional(), color: Wa.string().optional() }).refine((e35) =\u003e e35.frequencies_hz.length === e35.complex_currents.length, { message: \"frequencies_hz and complex_currents must have the same length\" });\nvar nL = Wa.object({ type: Wa.literal(\"simulation_op_amp\"), simulation_op_amp_id: GR(\"simulation_op_amp\"), source_component_id: Wa.string().optional(), inverting_input_source_port_id: Wa.string(), non_inverting_input_source_port_id: Wa.string(), output_source_port_id: Wa.string(), positive_supply_source_port_id: Wa.string(), negative_supply_source_port_id: Wa.string() }).describe(\"Defines a simple ideal operational amplifier for simulation\");\nvar oL = Wa.object({ type: Wa.literal(\"simulation_spice_subcircuit\"), simulation_spice_subcircuit_id: GR(\"simulation_spice_subcircuit\"), source_component_id: Wa.string(), spice_pin_to_source_port_map: Wa.record(Wa.string(), Wa.string()), subcircuit_source: Wa.string() }).describe(\"Defines a custom SPICE subcircuit model for simulation\");\nvar iL = (e35) =\u003e e35 !== undefined;\nvar rL = Wa.object({ type: Wa.literal(\"simulation_oscilloscope_trace\"), simulation_oscilloscope_trace_id: GR(\"simulation_oscilloscope_trace\"), simulation_transient_voltage_graph_id: Wa.string().optional(), simulation_transient_current_graph_id: Wa.string().optional(), simulation_voltage_probe_id: Wa.string().optional(), simulation_current_probe_id: Wa.string().optional(), display_name: Wa.string().optional(), color: Wa.string().optional(), display_center_value: Wa.number().optional(), display_center_offset_divs: Wa.number().optional(), volts_per_div: Wa.number().positive().optional(), amps_per_div: Wa.number().positive().optional() }).describe(\"Defines how a simulation measurement is rendered as an oscilloscope-style trace.\").superRefine((e35, t2) =\u003e {\n const n2 = [e35.simulation_transient_voltage_graph_id, e35.simulation_voltage_probe_id].filter(iL).length, o3 = [e35.simulation_transient_current_graph_id, e35.simulation_current_probe_id].filter(iL).length;\n n2 + o3 !== 1 \u0026\u0026 t2.addIssue({ code: Wa.ZodIssueCode.custom, message: \"An oscilloscope trace must reference exactly one voltage graph, current graph, voltage probe, or current probe.\" }), n2 \u003e 0 \u0026\u0026 e35.amps_per_div !== undefined \u0026\u0026 t2.addIssue({ code: Wa.ZodIssueCode.custom, message: \"Voltage oscilloscope traces must use volts_per_div, not amps_per_div.\" }), o3 \u003e 0 \u0026\u0026 e35.volts_per_div !== undefined \u0026\u0026 t2.addIssue({ code: Wa.ZodIssueCode.custom, message: \"Current oscilloscope traces must use amps_per_div, not volts_per_div.\" });\n});\nvar sL = Wa.object({ x: Wa.number().finite(), y: Wa.number().finite(), layer: yE });\nvar aL = Wa.discriminatedUnion(\"contact_type\", [sL.extend({ contact_type: Wa.literal(\"pcb_port\"), pcb_port_id: Wa.string().min(1) }), sL.extend({ contact_type: Wa.literal(\"pcb_via\"), pcb_via_id: Wa.string().min(1) }), sL.extend({ contact_type: Wa.literal(\"pcb_copper_pour\"), pcb_copper_pour_id: Wa.string().min(1) })]).describe(\"Identifies the reference conductor at a return-current contact\");\nvar cL = Wa.object({ signal_pcb_port_id: Wa.string().min(1), reference_pcb_port_id: Wa.string().min(1).optional(), reference_layer: yE, resistance: Wa.number().finite().positive() }).describe(\"A two-terminal return-current excitation port with resistance in ohms\");\nvar lL = Wa.object({ type: Wa.literal(\"simulation_return_current_excitation\"), simulation_return_current_excitation_id: GR(\"simulation_return_current_excitation\"), simulation_experiment_id: Wa.string().min(1), pcb_trace_id: Wa.string().min(1), ground_source_net_id: Wa.string().min(1), current: Wa.number().finite(), return_source: aL, return_sink: aL, source_port: cL.optional(), load_port: cL.optional() }).describe(\"Excites a signal trace with signed current in amperes, peak for AC; return_source is near the load and return_sink near the driver for positive current\");\nvar hL = Wa.object({ type: Wa.literal(\"simulation_pcb_return_current_result\"), simulation_pcb_return_current_result_id: GR(\"simulation_pcb_return_current_result\"), simulation_experiment_id: Wa.string().min(1), pcb_board_id: Wa.string().min(1), simulation_return_current_excitation_ids: Wa.array(Wa.string().min(1)).min(1).refine((e35) =\u003e new Set(e35).size === e35.length, \"Excitation IDs must be unique\"), frequency_hz: Wa.number().finite().positive().optional() }).describe(\"A PCB return-current result at one frequency, or a frequency-independent result when frequency_hz is absent\");\nfunction dL(e35) {\n return qR.extend({ project_relative_path: Wa.string().min(1), url: Wa.string().url() }).superRefine((t2, n2) =\u003e {\n if (e35.includes(t2.mimetype) || n2.addIssue({ code: Wa.ZodIssueCode.custom, path: [\"mimetype\"], message: `Expected one of: ${e35.join(\", \")}` }), t2.url.startsWith(\"data:\")) {\n const e36 = /^data:([^;,]*)(?:;[^,]*)?,/i.exec(t2.url)?.[1];\n e36?.toLowerCase() !== t2.mimetype \u0026\u0026 n2.addIssue({ code: Wa.ZodIssueCode.custom, path: [\"url\"], message: \"Data URL media type must match asset.mimetype\" });\n }\n });\n}\nvar uL = dL([\"application/json\", \"application/gzip\"]);\nvar pL = dL([\"image/png\", \"image/webp\"]);\nvar mL = Wa.object({ type: Wa.literal(\"simulation_pcb_return_current_field\"), simulation_pcb_return_current_field_id: GR(\"simulation_pcb_return_current_field\"), simulation_pcb_return_current_result_id: Wa.string().min(1), layer: yE, source_net_id: Wa.string().min(1), field_type: Wa.enum([\"real\", \"complex_phasor\"]), min_x: Wa.number().finite(), min_y: Wa.number().finite(), columns: Wa.number().int().positive().safe(), rows: Wa.number().int().positive().safe(), cell_width: Wa.number().finite().positive(), cell_height: Wa.number().finite().positive(), copper_thickness: Wa.number().finite().positive(), data_format: Wa.literal(\"simulation_return_current_grid_json_v1\"), field_asset: uL }).superRefine((e35, t2) =\u003e {\n Number.isSafeInteger(e35.columns * e35.rows) || t2.addIssue({ code: Wa.ZodIssueCode.custom, path: [\"columns\"], message: \"The grid cell count must be a safe integer\" });\n}).describe(\"A sampled sheet-current field in A/mm, using plain or gzipped JSON Asset URLs; dimensions are PCB millimeters\");\nvar gL = Wa.array(Wa.number().finite().nullable()).min(1);\nvar fL = Wa.discriminatedUnion(\"field_type\", [Wa.object({ field_type: Wa.literal(\"real\"), sheet_current_x: gL, sheet_current_y: gL }), Wa.object({ field_type: Wa.literal(\"complex_phasor\"), sheet_current_x_real: gL, sheet_current_x_imag: gL, sheet_current_y_real: gL, sheet_current_y_imag: gL })]).superRefine((e35, t2) =\u003e {\n const n2 = e35.field_type === \"real\" ? [e35.sheet_current_x, e35.sheet_current_y] : [e35.sheet_current_x_real, e35.sheet_current_x_imag, e35.sheet_current_y_real, e35.sheet_current_y_imag], o3 = n2[0];\n if (n2.some((e36) =\u003e e36.length !== o3.length))\n t2.addIssue({ code: Wa.ZodIssueCode.custom, message: \"Current channels must have equal lengths\" });\n else\n for (let e36 = 0;e36 \u003c o3.length; e36++) {\n const i3 = o3[e36] === null;\n if (n2.some((t3) =\u003e t3[e36] === null !== i3))\n return void t2.addIssue({ code: Wa.ZodIssueCode.custom, message: `Cell ${e36} must be null in every channel or finite in every channel` });\n }\n}).describe(\"Decoded real or complex sheet-current arrays with a shared conductor mask\");\nfunction _L(e35) {\n const t2 = e35.columns * e35.rows;\n if (!Number.isSafeInteger(e35.columns) || e35.columns \u003c= 0 || !Number.isSafeInteger(e35.rows) || e35.rows \u003c= 0 || !Number.isSafeInteger(t2))\n throw new Error(\"Grid dimensions must be positive safe integers\");\n return fL.superRefine((n2, o3) =\u003e {\n n2.field_type !== e35.field_type \u0026\u0026 o3.addIssue({ code: Wa.ZodIssueCode.custom, path: [\"field_type\"], message: \"Decoded field_type must match the parent field\" });\n (n2.field_type === \"real\" ? n2.sheet_current_x : n2.sheet_current_x_real).length !== t2 \u0026\u0026 o3.addIssue({ code: Wa.ZodIssueCode.custom, message: `Each current channel must have ${t2} entries (columns * rows)` });\n });\n}\nvar yL = Wa.object({ type: Wa.literal(\"simulation_pcb_return_current_heatmap\"), simulation_pcb_return_current_heatmap_id: GR(\"simulation_pcb_return_current_heatmap\"), simulation_pcb_return_current_result_id: Wa.string().min(1), layer: yE, source_net_id: Wa.string().min(1), min_x: Wa.number().finite(), min_y: Wa.number().finite(), max_x: Wa.number().finite(), max_y: Wa.number().finite(), image_asset: pL }).superRefine((e35, t2) =\u003e {\n for (const n2 of [\"x\", \"y\"])\n e35[`max_${n2}`] \u003c= e35[`min_${n2}`] \u0026\u0026 t2.addIssue({ code: Wa.ZodIssueCode.custom, path: [`max_${n2}`], message: \"Heatmap bounds must have positive width and height\" });\n}).describe(\"A transparent PNG/WebP current-density overlay in A/mm²; the top-left pixel maps to (min_x, max_y)\");\nvar bL = Wa.object({ type: Wa.literal(\"simulation_pcb_return_current_marker\"), simulation_pcb_return_current_marker_id: GR(\"simulation_pcb_return_current_marker\"), simulation_pcb_return_current_result_id: Wa.string().min(1), role: Wa.enum([\"signal_source\", \"signal_load\", \"return_source\", \"return_sink\", \"signal_transition\", \"return_transition\"]), label: Wa.string().optional(), label_x: Wa.number().finite().optional(), label_y: Wa.number().finite().optional() });\nvar xL = Wa.discriminatedUnion(\"target_type\", [bL.extend({ target_type: Wa.literal(\"pcb_port\"), pcb_port_id: Wa.string().min(1), layer: yE }), bL.extend({ target_type: Wa.literal(\"pcb_via\"), pcb_via_id: Wa.string().min(1), from_layer: yE, to_layer: yE })]).superRefine((e35, t2) =\u003e {\n e35.label_x === undefined != (e35.label_y === undefined) \u0026\u0026 t2.addIssue({ code: Wa.ZodIssueCode.custom, path: [\"label_x\"], message: \"label_x and label_y must be provided together\" }), e35.target_type === \"pcb_via\" \u0026\u0026 e35.from_layer === e35.to_layer \u0026\u0026 t2.addIssue({ code: Wa.ZodIssueCode.custom, path: [\"to_layer\"], message: \"A via transition must connect distinct layers\" });\n}).describe(\"A signal/return port or via highlight; markers do not assert measured via-transfer currents\");\nvar vL = Wa.union([AE, hE, EE, cE, lE, aE, uE, dE, vT, gT, _T, bT, fT, PT, ET, AT, LT, FT, jT, VT, $T, YT, XT, HT, kT, OT, gE, xE, pE, WT, ZT, qT, QT, vE, NE, KT, tE, eE, IE, SE, CE, PE, ME, wE, iE, rE, mE, AA, zA, qA, Dk, Lk, zk, $k, Xk, Hk, Vk, Wk, oO, wk, Nk, iO, XO, IO, NO, RO, TO, OO, EO, AO, kO, HO, dO, bO, vO, VO, GO, KO, ek, Bk, ik, rk, sk, ak, mk, ck, lk, hk, dk, pk, LO, BO, FO, jO, tk, nk, ok, $O, YO, rD, sD, aD, cD, fk, gk, _k, yk, bk, xk, vk, Ik, Sk, Fk, jk, Ck, Pk, Gk, kk, Uk, Zk, qk, tD, nD, oD, iD, lD, hD, dD, uD, pD, OE, ZE, YE, XE, HE, VE, FE, $E, qE, WE, kE, QE, KE, JE, iA, rA, sA, aA, cA, lA, yA, hA, uA, pA, _A, mA, gA, _D, xD, CD, yD, RD, OD, BD, lL, hL, mL, yL, xL, jD, $D, ZD, qD, JD, QD, eL, tL, UD, YD, XD, HD, rL, VD, nL, oL]);\nvar IL = vL;\nfunction SL(e35, t2, n2) {\n if (!t2 || !n2)\n return;\n let o3 = e35.get(t2);\n o3 || (o3 = new Set, e35.set(t2, o3)), o3.add(n2);\n let i3 = e35.get(n2);\n i3 || (i3 = new Set, e35.set(n2, i3)), i3.add(t2);\n}\nvar CL = (e35, t2 = {}) =\u003e {\n const n2 = e35;\n let o3 = n2._internal_store;\n if (!o3) {\n o3 = { counts: {}, editCount: 0 }, n2._internal_store = o3;\n for (const e36 of n2) {\n const t3 = e36.type, n3 = e36[`${t3}_id`];\n if (!n3)\n continue;\n const i4 = Number.parseInt(n3.split(\"_\").pop());\n Number.isNaN(i4) || (o3.counts[t3] = Math.max(o3.counts[t3] ?? 0, i4));\n }\n }\n const i3 = new Proxy({}, { get: (e36, r3) =\u003e {\n if (r3 === \"toArray\")\n return () =\u003e (n2.editCount = o3.editCount, n2);\n if (r3 === \"editCount\")\n return o3.editCount;\n if (r3 === \"subtree\")\n return (e37) =\u003e CL(function(e38, t3) {\n if (!t3.subcircuit_id \u0026\u0026 !t3.source_group_id)\n return [...e38];\n let n3 = t3;\n if (t3.subcircuit_id) {\n const o5 = new Set([t3.subcircuit_id]), i5 = new Map, r5 = new Map;\n for (const t4 of e38)\n if (t4.type === \"source_group\") {\n const { source_group_id: e39, subcircuit_id: n4 } = t4;\n n4 \u0026\u0026 r5.set(e39, n4);\n const o6 = t4.parent_source_group_id;\n o6 \u0026\u0026 (i5.has(o6) || i5.set(o6, []), i5.get(o6).push(e39));\n }\n let s4;\n for (const [e39, n4] of r5)\n if (n4 === t3.subcircuit_id) {\n s4 = e39;\n break;\n }\n if (s4) {\n const e39 = (t4) =\u003e {\n const n4 = i5.get(t4) || [];\n for (const t5 of n4) {\n const n5 = r5.get(t5);\n n5 \u0026\u0026 o5.add(n5), e39(t5);\n }\n };\n e39(s4), n3 = { ...t3, subcircuit_ids: Array.from(o5) };\n }\n }\n const o4 = new Map;\n for (const t4 of e38) {\n const e39 = t4[`${t4.type}_id`];\n typeof e39 == \"string\" \u0026\u0026 o4.set(e39, t4);\n }\n const i4 = new Map;\n for (const t4 of e38) {\n const e39 = Object.entries(t4);\n for (const [n4, r5] of e39)\n if (n4 !== \"parent_source_group_id\") {\n if (n4.endsWith(\"_id\") \u0026\u0026 typeof r5 == \"string\")\n SL(i4, t4, o4.get(r5));\n else if (n4.endsWith(\"_ids\") \u0026\u0026 Array.isArray(r5))\n for (const e40 of r5)\n typeof e40 == \"string\" \u0026\u0026 SL(i4, t4, o4.get(e40));\n }\n }\n const r4 = [], s3 = new Set;\n for (const t4 of e38) {\n let e39 = false;\n (n3.subcircuit_id \u0026\u0026 (\"subcircuit_id\" in t4) \u0026\u0026 t4.subcircuit_id === n3.subcircuit_id || n3.subcircuit_ids \u0026\u0026 (\"subcircuit_id\" in t4) \u0026\u0026 t4.subcircuit_id \u0026\u0026 n3.subcircuit_ids.includes(t4.subcircuit_id) || n3.source_group_id \u0026\u0026 (\"source_group_id\" in t4) \u0026\u0026 t4.source_group_id === n3.source_group_id || n3.source_group_id \u0026\u0026 (\"member_source_group_ids\" in t4) \u0026\u0026 Array.isArray(t4.member_source_group_ids) \u0026\u0026 t4.member_source_group_ids.includes(n3.source_group_id)) \u0026\u0026 (e39 = true), e39 \u0026\u0026 (r4.push(t4), s3.add(t4));\n }\n for (;r4.length \u003e 0; ) {\n const e39 = r4.shift(), t4 = i4.get(e39);\n if (t4)\n for (const e40 of t4)\n s3.has(e40) || (s3.add(e40), r4.push(e40));\n }\n return e38.filter((e39) =\u003e s3.has(e39));\n }(n2, e37), t2);\n if (r3 === \"insert\")\n return (e37) =\u003e {\n const i4 = e37.type;\n if (!i4)\n throw new Error(\"insert requires an element with a type\");\n o3.counts[i4] ??= -1, o3.counts[i4]++;\n const r4 = o3.counts[i4], s3 = { ...e37, type: i4, [`${i4}_id`]: `${i4}_${r4}` };\n if (t2.validateInserts) {\n (uR[i4] ?? IL).parse(s3);\n }\n return n2.push(s3), o3.editCount++, s3;\n };\n if (r3 === \"insertAll\")\n return (e37) =\u003e e37.map((e38) =\u003e i3.insert(e38));\n const s2 = r3;\n return { get: (e37) =\u003e n2.find((t3) =\u003e t3.type === s2 \u0026\u0026 t3[`${s2}_id`] === e37), getUsing: (e37) =\u003e {\n const t3 = Object.keys(e37);\n if (t3.length !== 1)\n throw new Error(\"getUsing requires exactly one key, e.g. { pcb_component_id }\");\n const o4 = t3[0], i4 = o4.replace(\"_id\", \"\"), r4 = n2.find((t4) =\u003e t4.type === i4 \u0026\u0026 t4[o4] === e37[o4]);\n return r4 ? n2.find((e38) =\u003e e38.type === s2 \u0026\u0026 e38[`${s2}_id`] === r4[`${s2}_id`]) : null;\n }, getWhere: (e37) =\u003e {\n const t3 = Object.keys(e37);\n return n2.find((n3) =\u003e n3.type === s2 \u0026\u0026 t3.every((t4) =\u003e n3[t4] === e37[t4]));\n }, list: (e37) =\u003e {\n const t3 = e37 ? Object.keys(e37) : [];\n return n2.filter((n3) =\u003e n3.type === s2 \u0026\u0026 t3.every((t4) =\u003e n3[t4] === e37[t4]));\n }, insert: (e37) =\u003e {\n o3.counts[s2] ??= -1, o3.counts[s2]++;\n const i4 = o3.counts[s2], r4 = { type: s2, [`${s2}_id`]: `${s2}_${i4}`, ...e37 };\n if (t2.validateInserts) {\n (uR[s2] ?? IL).parse(r4);\n }\n return n2.push(r4), o3.editCount++, r4;\n }, delete: (e37) =\u003e {\n const t3 = n2.find((t4) =\u003e t4[`${s2}_id`] === e37);\n t3 \u0026\u0026 (n2.splice(n2.indexOf(t3), 1), o3.editCount++);\n }, update: (e37, t3) =\u003e {\n const i4 = n2.find((t4) =\u003e t4.type === s2 \u0026\u0026 t4[`${s2}_id`] === e37);\n return i4 ? (Object.assign(i4, t3), o3.editCount++, i4) : null;\n }, select: (e37) =\u003e {\n if (s2 === \"source_component\")\n return n2.find((t3) =\u003e t3.type === \"source_component\" \u0026\u0026 t3.name === e37.replace(/\\./g, \"\"));\n if (s2 === \"pcb_port\" || s2 === \"source_port\" || s2 === \"schematic_port\") {\n const [t3, o4] = e37.replace(/\\./g, \"\").split(/[\\s\\\u003e]+/), i4 = n2.find((e38) =\u003e e38.type === \"source_component\" \u0026\u0026 e38.name === t3);\n if (!i4)\n return null;\n const r4 = n2.find((e38) =\u003e e38.type === \"source_port\" \u0026\u0026 e38.source_component_id === i4.source_component_id \u0026\u0026 (e38.name === o4 || (e38.port_hints ?? []).includes(o4)));\n if (!r4)\n return null;\n if (s2 === \"source_port\")\n return r4;\n if (s2 === \"pcb_port\")\n return n2.find((e38) =\u003e e38.type === \"pcb_port\" \u0026\u0026 e38.source_port_id === r4.source_port_id);\n if (s2 === \"schematic_port\")\n return n2.find((e38) =\u003e e38.type === \"schematic_port\" \u0026\u0026 e38.source_port_id === r4.source_port_id);\n }\n } };\n } });\n return i3;\n};\nfunction PL(e35) {\n const t2 = e35.type;\n return `${t2}:${e35[`${t2}_id`]}`;\n}\nCL.unparsed = CL;\nvar ML = (e35, t2 = {}) =\u003e {\n let n2 = e35._internal_store_indexed;\n if (!n2) {\n n2 = { counts: {}, editCount: 0, indexes: {} };\n for (const t3 of e35) {\n const e36 = t3.type, o4 = t3[`${e36}_id`];\n if (!o4)\n continue;\n const i4 = Number.parseInt(o4.split(\"_\").pop() || \"\");\n Number.isNaN(i4) || (n2.counts[e36] = Math.max(n2.counts[e36] ?? 0, i4));\n }\n const o3 = t2.indexConfig || {}, i3 = n2.indexes;\n if (o3.byId \u0026\u0026 (i3.byId = new Map), o3.byType \u0026\u0026 (i3.byType = new Map), o3.byRelation \u0026\u0026 (i3.byRelation = new Map), o3.bySubcircuit \u0026\u0026 (i3.bySubcircuit = new Map), o3.byCustomField \u0026\u0026 o3.byCustomField.length \u003e 0) {\n i3.byCustomField = new Map;\n for (const e36 of o3.byCustomField)\n i3.byCustomField.set(e36, new Map);\n }\n for (const t3 of e35) {\n if (o3.byId) {\n const e36 = PL(t3);\n i3.byId.set(e36, t3);\n }\n if (o3.byType) {\n const e36 = i3.byType.get(t3.type) || [];\n e36.push(t3), i3.byType.set(t3.type, e36);\n }\n if (o3.byRelation) {\n const e36 = Object.entries(t3);\n for (const [n3, o4] of e36)\n if (n3.endsWith(\"_id\") \u0026\u0026 n3 !== `${t3.type}_id` \u0026\u0026 typeof o4 == \"string\") {\n const e37 = i3.byRelation.get(n3) || new Map, r3 = e37.get(o4) || [];\n r3.push(t3), e37.set(o4, r3), i3.byRelation.set(n3, e37);\n }\n }\n if (o3.bySubcircuit \u0026\u0026 \"subcircuit_id\" in t3) {\n const e36 = t3.subcircuit_id;\n if (e36 \u0026\u0026 typeof e36 == \"string\") {\n const n3 = i3.bySubcircuit.get(e36) || [];\n n3.push(t3), i3.bySubcircuit.set(e36, n3);\n }\n }\n if (o3.byCustomField \u0026\u0026 i3.byCustomField) {\n for (const e36 of o3.byCustomField)\n if (e36 in t3) {\n const n3 = t3[e36];\n if (n3 !== undefined \u0026\u0026 (typeof n3 == \"string\" || typeof n3 == \"number\")) {\n const o4 = String(n3), r3 = i3.byCustomField.get(e36), s2 = r3.get(o4) || [];\n s2.push(t3), r3.set(o4, s2);\n }\n }\n }\n }\n e35._internal_store_indexed = n2;\n }\n return new Proxy({}, { get: (o3, i3) =\u003e {\n if (i3 === \"toArray\")\n return () =\u003e (e35.editCount = n2.editCount, e35);\n if (i3 === \"editCount\")\n return n2.editCount;\n const r3 = i3;\n return { get: (o4) =\u003e {\n const i4 = t2.indexConfig || {};\n if (i4.byId \u0026\u0026 n2.indexes.byId)\n return n2.indexes.byId.get(`${r3}:${o4}`) || null;\n if (i4.byType \u0026\u0026 n2.indexes.byType) {\n return (n2.indexes.byType.get(r3) || []).find((e36) =\u003e e36[`${r3}_id`] === o4) || null;\n }\n return e35.find((e36) =\u003e e36.type === r3 \u0026\u0026 e36[`${r3}_id`] === o4) || null;\n }, getUsing: (o4) =\u003e {\n const i4 = t2.indexConfig || {}, s2 = Object.keys(o4);\n if (s2.length !== 1)\n throw new Error(\"getUsing requires exactly one key, e.g. { pcb_component_id }\");\n const a3 = s2[0], c3 = a3.replace(\"_id\", \"\");\n if (i4.byRelation \u0026\u0026 n2.indexes.byRelation) {\n const t3 = n2.indexes.byRelation.get(a3);\n if (t3) {\n const s3 = (t3.get(o4[a3]) || []).find((e36) =\u003e e36.type === c3);\n if (!s3)\n return null;\n const l4 = s3[`${r3}_id`];\n if (i4.byId \u0026\u0026 n2.indexes.byId)\n return n2.indexes.byId.get(`${r3}:${l4}`) || null;\n if (i4.byType \u0026\u0026 n2.indexes.byType) {\n return (n2.indexes.byType.get(r3) || []).find((e36) =\u003e e36[`${r3}_id`] === l4) || null;\n }\n return e35.find((e36) =\u003e e36.type === r3 \u0026\u0026 e36[`${r3}_id`] === l4) || null;\n }\n }\n const l3 = e35.find((e36) =\u003e e36.type === c3 \u0026\u0026 e36[a3] === o4[a3]);\n return l3 \u0026\u0026 e35.find((e36) =\u003e e36.type === r3 \u0026\u0026 e36[`${r3}_id`] === l3[`${r3}_id`]) || null;\n }, getWhere: (o4) =\u003e {\n const i4 = t2.indexConfig || {}, s2 = Object.keys(o4);\n if (s2.length === 1 \u0026\u0026 i4.byCustomField \u0026\u0026 n2.indexes.byCustomField) {\n const e36 = s2[0], t3 = n2.indexes.byCustomField.get(e36);\n if (t3) {\n const n3 = String(o4[e36]);\n return (t3.get(n3) || []).find((e37) =\u003e e37.type === r3) || null;\n }\n }\n if (\"subcircuit_id\" in o4 \u0026\u0026 i4.bySubcircuit \u0026\u0026 n2.indexes.bySubcircuit) {\n const e36 = o4.subcircuit_id;\n return (n2.indexes.bySubcircuit.get(e36) || []).find((e37) =\u003e e37.type === r3 \u0026\u0026 s2.every((t3) =\u003e e37[t3] === o4[t3])) || null;\n }\n if (i4.byType \u0026\u0026 n2.indexes.byType) {\n return (n2.indexes.byType.get(r3) || []).find((e36) =\u003e s2.every((t3) =\u003e e36[t3] === o4[t3])) || null;\n }\n return e35.find((e36) =\u003e e36.type === r3 \u0026\u0026 s2.every((t3) =\u003e e36[t3] === o4[t3])) || null;\n }, list: (o4) =\u003e {\n const i4 = t2.indexConfig || {}, s2 = o4 ? Object.keys(o4) : [];\n if (s2.length === 0 \u0026\u0026 i4.byType \u0026\u0026 n2.indexes.byType)\n return n2.indexes.byType.get(r3) || [];\n if (s2.length === 1 \u0026\u0026 s2[0] === \"subcircuit_id\" \u0026\u0026 i4.bySubcircuit \u0026\u0026 n2.indexes.bySubcircuit) {\n const e36 = o4.subcircuit_id;\n return (n2.indexes.bySubcircuit.get(e36) || []).filter((e37) =\u003e e37.type === r3);\n }\n let a3;\n return a3 = i4.byType \u0026\u0026 n2.indexes.byType ? n2.indexes.byType.get(r3) || [] : e35.filter((e36) =\u003e e36.type === r3), s2.length \u003e 0 ? a3.filter((e36) =\u003e s2.every((t3) =\u003e e36[t3] === o4[t3])) : a3;\n }, insert: (o4) =\u003e {\n n2.counts[r3] ??= -1, n2.counts[r3]++;\n const i4 = n2.counts[r3], s2 = { type: r3, [`${r3}_id`]: `${r3}_${i4}`, ...o4 };\n if (t2.validateInserts) {\n (uR[r3] ?? IL).parse(s2);\n }\n e35.push(s2), n2.editCount++;\n const a3 = t2.indexConfig || {};\n if (a3.byId \u0026\u0026 n2.indexes.byId) {\n const e36 = PL(s2);\n n2.indexes.byId.set(e36, s2);\n }\n if (a3.byType \u0026\u0026 n2.indexes.byType) {\n const e36 = n2.indexes.byType.get(r3) || [];\n e36.push(s2), n2.indexes.byType.set(r3, e36);\n }\n if (a3.byRelation \u0026\u0026 n2.indexes.byRelation) {\n const e36 = Object.entries(s2);\n for (const [t3, o5] of e36)\n if (t3.endsWith(\"_id\") \u0026\u0026 t3 !== `${s2.type}_id` \u0026\u0026 typeof o5 == \"string\") {\n const e37 = n2.indexes.byRelation.get(t3) || new Map, i5 = e37.get(o5) || [];\n i5.push(s2), e37.set(o5, i5), n2.indexes.byRelation.set(t3, e37);\n }\n }\n if (a3.bySubcircuit \u0026\u0026 n2.indexes.bySubcircuit \u0026\u0026 \"subcircuit_id\" in s2) {\n const e36 = s2.subcircuit_id;\n if (e36 \u0026\u0026 typeof e36 == \"string\") {\n const t3 = n2.indexes.bySubcircuit.get(e36) || [];\n t3.push(s2), n2.indexes.bySubcircuit.set(e36, t3);\n }\n }\n if (a3.byCustomField \u0026\u0026 n2.indexes.byCustomField) {\n for (const e36 of a3.byCustomField)\n if (e36 in s2) {\n const t3 = s2[e36];\n if (t3 !== undefined \u0026\u0026 (typeof t3 == \"string\" || typeof t3 == \"number\")) {\n const o5 = String(t3), i5 = n2.indexes.byCustomField.get(e36), r4 = i5.get(o5) || [];\n r4.push(s2), i5.set(o5, r4);\n }\n }\n }\n return s2;\n }, delete: (o4) =\u003e {\n const i4 = t2.indexConfig || {};\n let s2;\n if (i4.byId \u0026\u0026 n2.indexes.byId)\n s2 = n2.indexes.byId.get(`${r3}:${o4}`);\n else if (i4.byType \u0026\u0026 n2.indexes.byType) {\n const e36 = n2.indexes.byType.get(r3) || [];\n s2 = e36.find((e37) =\u003e e37[`${r3}_id`] === o4);\n } else\n s2 = e35.find((e36) =\u003e e36[`${r3}_id`] === o4);\n if (!s2)\n return;\n const a3 = e35.indexOf(s2);\n if (a3 \u003e= 0 \u0026\u0026 (e35.splice(a3, 1), n2.editCount++), i4.byId \u0026\u0026 n2.indexes.byId) {\n const e36 = PL(s2);\n n2.indexes.byId.delete(e36);\n }\n if (i4.byType \u0026\u0026 n2.indexes.byType) {\n const e36 = (n2.indexes.byType.get(r3) || []).filter((e37) =\u003e e37[`${r3}_id`] !== o4);\n n2.indexes.byType.set(r3, e36);\n }\n if (i4.byRelation \u0026\u0026 n2.indexes.byRelation)\n for (const [e36, t3] of n2.indexes.byRelation.entries())\n for (const [e37, n3] of t3.entries()) {\n const o5 = n3.filter((e38) =\u003e e38 !== s2);\n o5.length === 0 ? t3.delete(e37) : t3.set(e37, o5);\n }\n if (i4.bySubcircuit \u0026\u0026 n2.indexes.bySubcircuit \u0026\u0026 \"subcircuit_id\" in s2) {\n const e36 = s2.subcircuit_id;\n if (e36) {\n const t3 = (n2.indexes.bySubcircuit.get(e36) || []).filter((e37) =\u003e e37 !== s2);\n t3.length === 0 ? n2.indexes.bySubcircuit.delete(e36) : n2.indexes.bySubcircuit.set(e36, t3);\n }\n }\n if (i4.byCustomField \u0026\u0026 n2.indexes.byCustomField)\n for (const e36 of n2.indexes.byCustomField.values())\n for (const [t3, n3] of e36.entries()) {\n const o5 = n3.filter((e37) =\u003e e37 !== s2);\n o5.length === 0 ? e36.delete(t3) : e36.set(t3, o5);\n }\n }, update: (o4, i4) =\u003e {\n const s2 = t2.indexConfig || {};\n let a3;\n if (s2.byId \u0026\u0026 n2.indexes.byId)\n a3 = n2.indexes.byId.get(`${r3}:${o4}`);\n else if (s2.byType \u0026\u0026 n2.indexes.byType) {\n const e36 = n2.indexes.byType.get(r3) || [];\n a3 = e36.find((e37) =\u003e e37[`${r3}_id`] === o4);\n } else\n a3 = e35.find((e36) =\u003e e36.type === r3 \u0026\u0026 e36[`${r3}_id`] === o4);\n if (!a3)\n return null;\n if (s2.byRelation \u0026\u0026 n2.indexes.byRelation) {\n const e36 = Object.entries(a3);\n for (const [t3, o5] of e36)\n if (t3.endsWith(\"_id\") \u0026\u0026 t3 !== `${a3.type}_id` \u0026\u0026 typeof o5 == \"string\" \u0026\u0026 t3 in i4 \u0026\u0026 i4[t3] !== o5) {\n const e37 = n2.indexes.byRelation.get(t3);\n if (e37) {\n const t4 = (e37.get(o5) || []).filter((e38) =\u003e e38 !== a3);\n t4.length === 0 ? e37.delete(o5) : e37.set(o5, t4);\n }\n }\n }\n if (s2.bySubcircuit \u0026\u0026 n2.indexes.bySubcircuit \u0026\u0026 \"subcircuit_id\" in a3 \u0026\u0026 \"subcircuit_id\" in i4) {\n const e36 = a3.subcircuit_id;\n if (e36 !== i4.subcircuit_id) {\n const t3 = (n2.indexes.bySubcircuit.get(e36) || []).filter((e37) =\u003e e37 !== a3);\n t3.length === 0 ? n2.indexes.bySubcircuit.delete(e36) : n2.indexes.bySubcircuit.set(e36, t3);\n }\n }\n if (s2.byCustomField \u0026\u0026 n2.indexes.byCustomField) {\n for (const e36 of s2.byCustomField)\n if (e36 in a3 \u0026\u0026 e36 in i4 \u0026\u0026 a3[e36] !== i4[e36]) {\n const t3 = n2.indexes.byCustomField.get(e36);\n if (t3) {\n const n3 = String(a3[e36]), o5 = (t3.get(n3) || []).filter((e37) =\u003e e37 !== a3);\n o5.length === 0 ? t3.delete(n3) : t3.set(n3, o5);\n }\n }\n }\n if (Object.assign(a3, i4), n2.editCount++, s2.byRelation \u0026\u0026 n2.indexes.byRelation) {\n const e36 = Object.entries(a3);\n for (const [t3, o5] of e36)\n if (t3.endsWith(\"_id\") \u0026\u0026 t3 !== `${a3.type}_id` \u0026\u0026 typeof o5 == \"string\" \u0026\u0026 t3 in i4) {\n const e37 = n2.indexes.byRelation.get(t3) || new Map, i5 = e37.get(o5) || [];\n i5.includes(a3) || (i5.push(a3), e37.set(o5, i5), n2.indexes.byRelation.set(t3, e37));\n }\n }\n if (s2.bySubcircuit \u0026\u0026 n2.indexes.bySubcircuit \u0026\u0026 \"subcircuit_id\" in a3 \u0026\u0026 \"subcircuit_id\" in i4) {\n const e36 = a3.subcircuit_id;\n if (e36 \u0026\u0026 typeof e36 == \"string\") {\n const t3 = n2.indexes.bySubcircuit.get(e36) || [];\n t3.includes(a3) || (t3.push(a3), n2.indexes.bySubcircuit.set(e36, t3));\n }\n }\n if (s2.byCustomField \u0026\u0026 n2.indexes.byCustomField) {\n for (const e36 of s2.byCustomField)\n if (e36 in a3 \u0026\u0026 e36 in i4) {\n const t3 = a3[e36];\n if (t3 !== undefined \u0026\u0026 (typeof t3 == \"string\" || typeof t3 == \"number\")) {\n const o5 = String(t3), i5 = n2.indexes.byCustomField.get(e36), r4 = i5.get(o5) || [];\n r4.includes(a3) || (r4.push(a3), i5.set(o5, r4));\n }\n }\n }\n return a3;\n }, select: (t3) =\u003e {\n if (r3 === \"source_component\")\n return e35.find((e36) =\u003e e36.type === \"source_component\" \u0026\u0026 e36.name === t3.replace(/\\./g, \"\")) || null;\n if (r3 === \"pcb_port\" || r3 === \"source_port\" || r3 === \"schematic_port\") {\n const [n3, o4] = t3.replace(/\\./g, \"\").split(/[\\s\\\u003e]+/), i4 = e35.find((e36) =\u003e e36.type === \"source_component\" \u0026\u0026 e36.name === n3);\n if (!i4)\n return null;\n const s2 = e35.find((e36) =\u003e e36.type === \"source_port\" \u0026\u0026 e36.source_component_id === i4.source_component_id \u0026\u0026 (e36.name === o4 || (e36.port_hints ?? []).includes(o4)));\n if (!s2)\n return null;\n if (r3 === \"source_port\")\n return s2;\n if (r3 === \"pcb_port\")\n return e35.find((e36) =\u003e e36.type === \"pcb_port\" \u0026\u0026 e36.source_port_id === s2.source_port_id) || null;\n if (r3 === \"schematic_port\")\n return e35.find((e36) =\u003e e36.type === \"schematic_port\" \u0026\u0026 e36.source_port_id === s2.source_port_id) || null;\n }\n return null;\n } };\n } });\n};\nML.unparsed = ML;\nvar wL = (e35) =\u003e e35[`${e35.type}_id`];\nvar NL = (e35, t2) =\u003e {\n const n2 = CL(e35).pcb_port.get(t2);\n if (!n2)\n return `pcb_port[#${t2}]`;\n const o3 = n2.pcb_component_id ? CL(e35).pcb_component.get(n2.pcb_component_id) : undefined;\n if (!o3)\n return `pcb_port[#${t2}]`;\n const i3 = CL(e35).source_component.get(o3.source_component_id);\n if (!i3)\n return `pcb_port[#${t2}]`;\n const r3 = CL(e35).source_port.get(n2.source_port_id);\n if (!r3)\n return `pcb_port[#${t2}]`;\n let s2;\n return s2 = r3?.port_hints \u0026\u0026 r3.port_hints.length \u003e 0 || r3.port_hints \u0026\u0026 r3.port_hints.length \u003e 0 ? r3.port_hints[0] : t2, `pcb_port[.${i3.name} \u003e .${s2}]`;\n};\nfunction RL(e35, t2) {\n const n2 = CL(e35).pcb_trace.get(t2);\n if (!n2)\n return `trace[${t2}]`;\n const o3 = n2.route.flatMap((e36) =\u003e [e36.start_pcb_port_id, e36.end_pcb_port_id]).filter(Boolean);\n if (o3.length === 0)\n return `trace[${t2}]`;\n return `trace[${o3.map((t3) =\u003e {\n const n3 = function(t4) {\n const n4 = CL(e35).pcb_port.get(t4);\n if (!n4)\n return null;\n const o4 = n4.pcb_component_id ? CL(e35).pcb_component.get(n4.pcb_component_id) : undefined;\n if (!o4)\n return null;\n const i3 = CL(e35).source_component.get(o4.source_component_id);\n if (!i3)\n return null;\n const r3 = CL(e35).source_port.get(n4.source_port_id), s2 = r3?.port_hints ? r3.port_hints[1] : \"\";\n return { componentName: i3.name, portHint: s2 };\n }(t3);\n return n3 ? `.${n3.componentName} \u003e port.${n3.portHint}` : `port[${t3}]`;\n }).join(\", \")}]`;\n}\nvar TL = (e35, t2) =\u003e {\n if (typeof t2 == \"string\") {\n const n2 = ((e36, t3) =\u003e e36.find((e37) =\u003e wL(e37) === t3) ?? null)(e35, t2);\n return TL(e35, n2);\n }\n switch (t2.type) {\n case \"pcb_port\":\n return NL(e35, t2.pcb_port_id);\n case \"pcb_smtpad\":\n return function(e36, t3) {\n const n2 = CL(e36).pcb_smtpad.get(t3);\n return n2 \u0026\u0026 n2.pcb_port_id ? NL(e36, n2.pcb_port_id) : `smtpad[${t3}]`;\n }(e35, t2.pcb_smtpad_id);\n case \"pcb_trace\":\n return RL(e35, t2.pcb_trace_id);\n case \"source_component\":\n return `source_component[${t2.name}]`;\n default:\n return `${t2.type}[#${wL(t2)}]`;\n }\n};\nvar EL = (e35, t2) =\u003e ({ minX: Math.min(e35.minX, t2.minX), minY: Math.min(e35.minY, t2.minY), maxX: Math.max(e35.maxX, t2.maxX), maxY: Math.max(e35.maxY, t2.maxY) });\nvar AL = (e35, t2, n2) =\u003e {\n const o3 = n2 / 2;\n return { minX: e35 - o3, minY: t2 - o3, maxX: e35 + o3, maxY: t2 + o3 };\n};\nvar OL = (e35, t2, n2, o3, i3) =\u003e {\n const r3 = n2 / 2, s2 = o3 / 2, a3 = i3 * Math.PI / 180, c3 = Math.cos(a3), l3 = Math.sin(a3), h2 = [{ x: -r3, y: -s2 }, { x: r3, y: -s2 }, { x: r3, y: s2 }, { x: -r3, y: s2 }].map((n3) =\u003e ({ x: e35 + n3.x * c3 - n3.y * l3, y: t2 + n3.x * l3 + n3.y * c3 }));\n return { minX: Math.min(...h2.map((e36) =\u003e e36.x)), minY: Math.min(...h2.map((e36) =\u003e e36.y)), maxX: Math.max(...h2.map((e36) =\u003e e36.x)), maxY: Math.max(...h2.map((e36) =\u003e e36.y)) };\n};\nvar kL = (e35, t2, n2, o3, i3) =\u003e {\n const r3 = n2 / 2, s2 = o3 / 2, a3 = i3 * Math.PI / 180, c3 = Math.cos(a3), l3 = Math.sin(a3), h2 = Math.hypot(r3 * c3, s2 * l3), d2 = Math.hypot(r3 * l3, s2 * c3);\n return { minX: e35 - h2, minY: t2 - d2, maxX: e35 + h2, maxY: t2 + d2 };\n};\nvar DL = (e35, t2, n2, o3, i3) =\u003e {\n const r3 = Math.min(n2, o3) / 2, s2 = Math.max(n2, o3) / 2 - r3, a3 = i3 * Math.PI / 180, c3 = n2 \u003e= o3 ? { x: s2, y: 0 } : { x: 0, y: s2 }, l3 = { x: c3.x * Math.cos(a3) - c3.y * Math.sin(a3), y: c3.x * Math.sin(a3) + c3.y * Math.cos(a3) }, h2 = Math.abs(l3.x) + r3, d2 = Math.abs(l3.y) + r3;\n return { minX: e35 - h2, minY: t2 - d2, maxX: e35 + h2, maxY: t2 + d2 };\n};\nvar LL = (e35) =\u003e e35.length === 0 ? null : { minX: Math.min(...e35.map((e36) =\u003e e36.x)), minY: Math.min(...e35.map((e36) =\u003e e36.y)), maxX: Math.max(...e35.map((e36) =\u003e e36.x)), maxY: Math.max(...e35.map((e36) =\u003e e36.y)) };\nvar zL = (e35) =\u003e Array.isArray(e35) ? e35.flatMap((e36) =\u003e {\n if (!e36 || typeof e36 != \"object\")\n return [];\n if (\"x\" in e36 \u0026\u0026 \"y\" in e36 \u0026\u0026 typeof e36.x == \"number\" \u0026\u0026 typeof e36.y == \"number\")\n return [{ x: e36.x, y: e36.y }];\n if (\"start\" in e36 \u0026\u0026 \"end\" in e36) {\n return [e36.start, e36.end].filter((e37) =\u003e Boolean(e37 \u0026\u0026 typeof e37 == \"object\" \u0026\u0026 \"x\" in e37 \u0026\u0026 \"y\" in e37 \u0026\u0026 typeof e37.x == \"number\" \u0026\u0026 typeof e37.y == \"number\"));\n }\n return [];\n}) : [];\nvar BL = (e35) =\u003e {\n if (!e35.type.startsWith(\"pcb_\"))\n return null;\n if (e35.type === \"pcb_smtpad\" \u0026\u0026 e35.shape === \"polygon\" \u0026\u0026 Array.isArray(e35.points))\n return LL(e35.points);\n if (e35.type === \"pcb_hole\" \u0026\u0026 e35.hole_shape === \"circle\")\n return AL(e35.x, e35.y, e35.hole_diameter);\n if (e35.type === \"pcb_plated_hole\") {\n let t3;\n if (\"outer_diameter\" in e35 \u0026\u0026 typeof e35.outer_diameter == \"number\" ? t3 = AL(e35.x, e35.y, e35.outer_diameter) : (\"hole_diameter\" in e35) \u0026\u0026 typeof e35.hole_diameter == \"number\" \u0026\u0026 (t3 = AL(e35.x, e35.y, e35.hole_diameter)), (e35.shape === \"oval\" || e35.shape === \"pill\") \u0026\u0026 typeof e35.outer_width == \"number\" \u0026\u0026 typeof e35.outer_height == \"number\") {\n t3 = (e35.shape === \"pill\" ? DL : kL)(e35.x, e35.y, e35.outer_width, e35.outer_height, e35.ccw_rotation ?? 0);\n }\n if (\"rect_pad_width\" in e35 \u0026\u0026 typeof e35.rect_pad_width == \"number\" \u0026\u0026 \"rect_pad_height\" in e35 \u0026\u0026 typeof e35.rect_pad_height == \"number\") {\n const n3 = OL(e35.x, e35.y, e35.rect_pad_width, e35.rect_pad_height, \"rect_ccw_rotation\" in e35 ? e35.rect_ccw_rotation ?? 0 : 0);\n t3 = t3 ? EL(t3, n3) : n3;\n }\n if (\"hole_diameter\" in e35 \u0026\u0026 typeof e35.hole_diameter == \"number\") {\n const n3 = AL(e35.x + (\"hole_offset_x\" in e35 ? e35.hole_offset_x ?? 0 : 0), e35.y + (\"hole_offset_y\" in e35 ? e35.hole_offset_y ?? 0 : 0), e35.hole_diameter);\n t3 = t3 ? EL(t3, n3) : n3;\n }\n if (t3)\n return t3;\n }\n const t2 = e35, n2 = LL(zL(t2.route));\n if (n2)\n return n2;\n const o3 = LL(zL(t2.outline));\n if (o3)\n return o3;\n const i3 = LL(zL(t2.points));\n if (i3)\n return i3;\n let r3, s2, a3, c3;\n \"x\" in e35 \u0026\u0026 \"y\" in e35 \u0026\u0026 (r3 = Number(e35.x), s2 = Number(e35.y)), \"outer_diameter\" in e35 \u0026\u0026 (a3 = Number(e35.outer_diameter), c3 = Number(e35.outer_diameter)), \"width\" in e35 \u0026\u0026 (a3 = Number(e35.width)), \"height\" in e35 \u0026\u0026 (c3 = Number(e35.height)), \"center\" in e35 \u0026\u0026 e35.center \u0026\u0026 typeof e35.center == \"object\" \u0026\u0026 \"x\" in e35.center \u0026\u0026 \"y\" in e35.center \u0026\u0026 (r3 = Number(e35.center.x), s2 = Number(e35.center.y));\n let l3 = 0;\n if (\"rotation\" in e35 \u0026\u0026 typeof e35.rotation == \"number\" \u0026\u0026 (l3 = e35.rotation), \"ccw_rotation\" in e35 \u0026\u0026 typeof e35.ccw_rotation == \"number\" \u0026\u0026 (l3 = e35.ccw_rotation), r3 !== undefined \u0026\u0026 s2 !== undefined)\n return a3 !== undefined \u0026\u0026 c3 !== undefined ? l3 ? OL(r3, s2, a3, c3, l3) : { minX: r3 - a3 / 2, minY: s2 - c3 / 2, maxX: r3 + a3 / 2, maxY: s2 + c3 / 2 } : (\"radius\" in e35) \u0026\u0026 typeof e35.radius == \"number\" ? AL(r3, s2, 2 * e35.radius) : { minX: r3, minY: s2, maxX: r3, maxY: s2 };\n const h2 = [t2.anchor_position, t2.position].filter((e36) =\u003e Boolean(e36 \u0026\u0026 typeof e36 == \"object\" \u0026\u0026 \"x\" in e36 \u0026\u0026 \"y\" in e36 \u0026\u0026 typeof e36.x == \"number\" \u0026\u0026 typeof e36.y == \"number\")).at(0);\n return h2 ? { minX: h2.x, minY: h2.y, maxX: h2.x, maxY: h2.y } : null;\n};\nvar FL = (e35) =\u003e {\n let t2 = { minX: Number.POSITIVE_INFINITY, minY: Number.POSITIVE_INFINITY, maxX: Number.NEGATIVE_INFINITY, maxY: Number.NEGATIVE_INFINITY };\n for (const n2 of e35) {\n const e36 = BL(n2);\n e36 \u0026\u0026 (t2 = EL(t2, e36));\n }\n return t2;\n};\nvar jL = (e35) =\u003e e35[`${e35.type}_id`];\nvar $L = 0.000000001;\nvar YL = (e35, t2, n2) =\u003e {\n const o3 = n2.x - t2.x, i3 = n2.y - t2.y, r3 = o3 * o3 + i3 * i3;\n if (r3 \u003c= $L)\n return ((e36, t3) =\u003e Math.hypot(e36.x - t3.x, e36.y - t3.y))(e35, t2);\n const s2 = (a3 = ((e35.x - t2.x) * o3 + (e35.y - t2.y) * i3) / r3, c3 = 0, l3 = 1, Math.max(c3, Math.min(l3, a3)));\n var a3, c3, l3;\n return Math.hypot(e35.x - (t2.x + s2 * o3), e35.y - (t2.y + s2 * i3));\n};\nvar XL = (e35, t2, n2) =\u003e !(Math.abs(((e36, t3, n3) =\u003e (t3.x - e36.x) * (n3.y - e36.y) - (t3.y - e36.y) * (n3.x - e36.x))(t2, n2, e35)) \u003e $L) \u0026\u0026 (e35.x \u003e= Math.min(t2.x, n2.x) - $L \u0026\u0026 e35.x \u003c= Math.max(t2.x, n2.x) + $L \u0026\u0026 e35.y \u003e= Math.min(t2.y, n2.y) - $L \u0026\u0026 e35.y \u003c= Math.max(t2.y, n2.y) + $L);\nvar HL = (e35) =\u003e {\n const t2 = [];\n if (e35.points.length \u003c 2)\n return t2;\n for (let n2 = 0;n2 \u003c e35.points.length; n2 += 1) {\n const o3 = e35.points[n2], i3 = e35.points[(n2 + 1) % e35.points.length];\n o3 \u0026\u0026 i3 \u0026\u0026 t2.push([o3, i3]);\n }\n return t2;\n};\nvar VL = (e35, t2) =\u003e Math.max(0, Math.hypot(e35.x - t2.x, e35.y - t2.y) - e35.radius - t2.radius);\nvar WL = (e35, t2) =\u003e {\n if (t2.points.length \u003c 3)\n return Number.POSITIVE_INFINITY;\n if (((e36, t3) =\u003e {\n for (const [n4, o3] of HL(t3))\n if (XL(e36, n4, o3))\n return true;\n let n3 = false;\n for (let o3 = 0, i3 = t3.points.length - 1;o3 \u003c t3.points.length; i3 = o3++) {\n const r3 = t3.points[o3], s2 = t3.points[i3];\n r3 \u0026\u0026 s2 \u0026\u0026 (r3.y \u003e e36.y != s2.y \u003e e36.y \u0026\u0026 e36.x \u003c (s2.x - r3.x) * (e36.y - r3.y) / (s2.y - r3.y) + r3.x \u0026\u0026 (n3 = !n3));\n }\n return n3;\n })({ x: e35.x, y: e35.y }, t2))\n return 0;\n let n2 = Number.POSITIVE_INFINITY;\n for (const [o3, i3] of HL(t2))\n n2 = Math.min(n2, YL({ x: e35.x, y: e35.y }, o3, i3));\n return Math.max(0, n2 - e35.radius);\n};\nvar GL = (Object.keys({ leftside_top: { side: \"leftside\", alignment: \"top\" }, leftside_bottom: { side: \"leftside\", alignment: \"bottom\" }, rightside_top: { side: \"rightside\", alignment: \"top\" }, rightside_bottom: { side: \"rightside\", alignment: \"bottom\" }, topside_left: { side: \"topside\", alignment: \"left\" }, topside_right: { side: \"topside\", alignment: \"right\" }, bottomside_left: { side: \"bottomside\", alignment: \"left\" }, bottomside_right: { side: \"bottomside\", alignment: \"right\" } }), (e35, t2, n2 = 0) =\u003e {\n const { a: o3, b: i3, c: r3, d: s2, e: a3, f: c3 } = Zt(Gt(t2.x, t2.y), Kt(n2 * Math.PI / 180));\n return e35.transform(new f_(o3, i3, r3, s2, a3, c3));\n});\nvar UL = (e35) =\u003e e35.orientation() === Cg.CCW ? e35 : e35.reverse();\nvar ZL = (e35, t2) =\u003e UL(new D_(new E_(new S_(e35.x, e35.y), t2)));\nvar qL = (e35, t2, n2, o3 = 0, i3 = 0) =\u003e {\n const r3 = t2 / 2, s2 = n2 / 2, a3 = Math.max(0, Math.min(o3, r3, s2));\n if (a3 === 0)\n return GL(UL(new D_(new O_(-r3, -s2, r3, s2))), e35, i3);\n const c3 = [new A_(new S_(r3 - a3, -s2 + a3), a3, -Math.PI / 2, 0, true), new A_(new S_(r3 - a3, s2 - a3), a3, 0, Math.PI / 2, true), new A_(new S_(-r3 + a3, s2 - a3), a3, Math.PI / 2, Math.PI, true), new A_(new S_(-r3 + a3, -s2 + a3), a3, Math.PI, 1.5 * Math.PI, true)], l3 = [];\n for (let e36 = 0;e36 \u003c c3.length; e36++) {\n const t3 = c3[e36], n3 = c3[(e36 + 1) % c3.length];\n l3.push(t3), t3.end.distanceTo(n3.start)[0] \u003e 0.000000000001 \u0026\u0026 l3.push(new w_(t3.end, n3.start));\n }\n return GL(UL(new D_(l3)), e35, i3);\n};\nvar JL = (e35, t2) =\u003e {\n for (const n2 of t2.reverse().faces)\n e35.addFace(n2.shapes);\n return e35;\n};\nvar QL = (e35, t2 = 0) =\u003e {\n if (e35.shape === \"circle\")\n return ((e36, t3, n3) =\u003e JL(ZL(e36, t3 / 2), ZL(e36, n3 / 2)))(e35, e35.outer_diameter, e35.hole_diameter);\n if (\"outer_width\" in e35)\n return JL(qL(e35, e35.outer_width, e35.outer_height, Math.min(e35.outer_width, e35.outer_height) / 2, e35.ccw_rotation), qL(e35, e35.hole_width, e35.hole_height, Math.min(e35.hole_width, e35.hole_height) / 2, e35.ccw_rotation));\n const n2 = { x: e35.x + e35.hole_offset_x, y: e35.y + e35.hole_offset_y }, o3 = e35.shape === \"hole_with_polygon_pad\" ? GL(UL(new D_(e35.pad_outline.map((e36) =\u003e new S_(e36.x, e36.y)))), e35, e35.ccw_rotation ?? t2) : qL(e35, e35.rect_pad_width, e35.rect_pad_height, e35.rect_border_radius, \"rect_ccw_rotation\" in e35 ? e35.rect_ccw_rotation : 0);\n if (e35.shape === \"circular_hole_with_rect_pad\" || e35.shape === \"hole_with_polygon_pad\" \u0026\u0026 e35.hole_shape === \"circle\") {\n if (e35.hole_diameter === undefined)\n throw new Error(\"Circular plated hole requires hole_diameter\");\n return JL(o3, ZL(n2, e35.hole_diameter / 2));\n }\n if (!(\"hole_width\" in e35) || e35.hole_width === undefined || e35.hole_height === undefined)\n throw new Error(\"Slotted plated hole requires hole_width and hole_height\");\n return JL(o3, qL(n2, e35.hole_width, e35.hole_height, Math.min(e35.hole_width, e35.hole_height) / 2, \"hole_ccw_rotation\" in e35 ? e35.hole_ccw_rotation : e35.shape === \"hole_with_polygon_pad\" ? e35.ccw_rotation ?? t2 : 0));\n};\nvar KL = (e35, t2, n2, o3 = n2) =\u003e {\n const i3 = Math.hypot(t2.x - e35.x, t2.y - e35.y), r3 = n2 / 2, s2 = o3 / 2;\n if (i3 \u003c= Math.abs(s2 - r3))\n return ZL(r3 \u003e= s2 ? e35 : t2, Math.max(r3, s2));\n const a3 = Math.atan2(t2.y - e35.y, t2.x - e35.x), c3 = Math.acos((r3 - s2) / i3), l3 = new A_(new S_(e35.x, e35.y), r3, a3 + c3, a3 - c3, true), h2 = new A_(new S_(t2.x, t2.y), s2, a3 - c3, a3 + c3, true);\n return UL(new D_([l3, new w_(l3.end, h2.start), h2, new w_(h2.end, l3.start)]));\n};\nvar ez = (e35, t2, n2 = 0.0000001) =\u003e e35.vertices.some((e36) =\u003e t2.contains(e36)) || t2.vertices.some((t3) =\u003e e35.contains(t3)) || e35.distanceTo(t2)[0] \u003c= n2;\nvar tz = (e35, t2) =\u003e {\n for (const n2 of e35)\n if (n2 \u0026\u0026 n2 !== t2 \u0026\u0026 !(t2.length \u003e 0 \u0026\u0026 n2.includes(t2)) \u0026\u0026 !/\\b(?:pcb|source|schematic|subcircuit)_[a-z0-9_]+\\b/i.test(n2))\n return n2;\n return \"\";\n};\nvar nz = (e35, t2) =\u003e {\n const n2 = e35.find((e36) =\u003e e36.type === \"pcb_port\" \u0026\u0026 e36.pcb_port_id === t2);\n if (n2?.type !== \"pcb_port\")\n return \"unnamed port\";\n const o3 = e35.find((e36) =\u003e e36.type === \"source_port\" \u0026\u0026 e36.source_port_id === n2.source_port_id);\n if (o3?.type !== \"source_port\")\n return \"unnamed port\";\n const i3 = e35.find((e36) =\u003e e36.type === \"source_component\" \u0026\u0026 e36.source_component_id === o3.source_component_id), r3 = i3?.type === \"source_component\" ? tz([i3.name], i3.source_component_id) : \"\", s2 = tz([o3.name, o3.pin_number?.toString(), o3.port_hints?.[0]], o3.source_port_id);\n return r3 \u0026\u0026 s2 ? `${r3}.${s2}` : s2 || \"unnamed port\";\n};\nvar oz = (e35, t2) =\u003e {\n const n2 = e35.find((e36) =\u003e e36.type === \"pcb_trace\" \u0026\u0026 e36.pcb_trace_id === t2);\n if (n2?.type !== \"pcb_trace\")\n return \"unnamed trace\";\n const o3 = e35.find((e36) =\u003e e36.type === \"source_trace\" \u0026\u0026 e36.source_trace_id === n2.source_trace_id);\n if (o3?.type === \"source_trace\")\n return ((e36, t3) =\u003e {\n const n3 = tz([t3.display_name], t3.source_trace_id);\n if (n3)\n return n3;\n const o4 = [];\n for (const n4 of t3.connected_source_port_ids ?? []) {\n const t4 = e36.find((e37) =\u003e e37.type === \"pcb_port\" \u0026\u0026 e37.source_port_id === n4);\n if (t4?.type === \"pcb_port\") {\n const n5 = nz(e36, t4.pcb_port_id);\n n5 !== \"unnamed port\" \u0026\u0026 o4.push(n5);\n } else {\n const t5 = e36.find((e37) =\u003e e37.type === \"source_port\" \u0026\u0026 e37.source_port_id === n4);\n if (t5?.type !== \"source_port\")\n continue;\n const i4 = e36.find((e37) =\u003e e37.type === \"source_component\" \u0026\u0026 e37.source_component_id === t5.source_component_id), r3 = i4?.type === \"source_component\" ? tz([i4.name], i4.source_component_id) : \"\", s2 = tz([t5.name, t5.pin_number?.toString(), t5.port_hints?.[0]], t5.source_port_id);\n r3 \u0026\u0026 s2 ? o4.push(`${r3}.${s2}`) : s2 \u0026\u0026 o4.push(s2);\n }\n if (o4.length === 2)\n return `${o4[0]} to ${o4[1]}`;\n }\n return o4.length === 1 ? `trace connected to ${o4[0]}` : \"unnamed trace\";\n })(e35, o3);\n const i3 = Array.from(new Set(n2.route.flatMap((e36) =\u003e e36.route_type === \"wire\" ? [e36.start_pcb_port_id, e36.end_pcb_port_id].filter((e37) =\u003e Boolean(e37)) : []))).map((t3) =\u003e nz(e35, t3)).filter((e36) =\u003e e36 !== \"unnamed port\");\n return i3.length \u003e= 2 ? `${i3[0]} to ${i3[1]}` : i3.length === 1 ? `trace connected to ${i3[0]}` : \"unnamed trace\";\n};\nvar iz = (e35, t2) =\u003e {\n const n2 = e35.find((e36) =\u003e jL(e36) === t2);\n if (!n2)\n return \"unnamed element\";\n if (n2.type === \"pcb_component\" || n2.type === \"schematic_component\") {\n const t3 = e35.find((e36) =\u003e e36.type === \"source_component\" \u0026\u0026 e36.source_component_id === n2.source_component_id);\n if (t3?.type === \"source_component\")\n return tz([t3.name], t3.source_component_id) || \"unnamed component\";\n }\n if ((n2.type === \"pcb_smtpad\" || n2.type === \"pcb_plated_hole\") \u0026\u0026 n2.pcb_port_id) {\n const t3 = nz(e35, n2.pcb_port_id);\n if (t3 !== \"unnamed port\")\n return t3;\n }\n if (n2.type === \"pcb_trace\")\n return oz(e35, t2);\n const o3 = { pcb_smtpad: \"SMD pad\", pcb_plated_hole: \"through-hole pad\", pcb_via: \"via\", pcb_hole: \"hole\", pcb_bend: \"bend\", pcb_stiffener: \"stiffener\", pcb_keepout: \"keepout\", pcb_cutout: \"cutout\", pcb_copper_pour: \"copper pour\" }[n2.type] ?? n2.type.replace(/^(pcb|source|schematic)_/, \"\").replaceAll(\"_\", \" \");\n return tz([\"name\" in n2 ? n2.name : undefined, \"description\" in n2 ? n2.description : undefined, TL(e35, t2)], t2) || `unnamed ${o3}`;\n};\nvar rz = (e35, t2, n2 = {}) =\u003e {\n const o3 = e35.find((e36) =\u003e e36.type === \"pcb_board\"), i3 = Math.max(n2.viaClearance ?? 0.1, 0.1), r3 = o3?.min_pad_edge_to_pad_edge_clearance ?? 0.1, s2 = e35.filter((e36) =\u003e e36.type === \"pcb_via\").map((e36, t3) =\u003e ({ minX: e36.x - Math.max(e36.hole_diameter, e36.outer_diameter) / 2, minY: e36.y - Math.max(e36.hole_diameter, e36.outer_diameter) / 2, maxX: e36.x + Math.max(e36.hole_diameter, e36.outer_diameter) / 2, maxY: e36.y + Math.max(e36.hole_diameter, e36.outer_diameter) / 2, via: e36, order: t3 })), a3 = new G;\n a3.load(s2);\n const c3 = [], l3 = [], h2 = new Set, d2 = Math.max(i3, r3);\n for (const n3 of s2) {\n const o4 = a3.search({ minX: n3.minX - d2, minY: n3.minY - d2, maxX: n3.maxX + d2, maxY: n3.maxY + d2 }).sort((e36, t3) =\u003e e36.order - t3.order);\n for (const s3 of o4) {\n if (s3.order \u003c= n3.order)\n continue;\n const o5 = n3.via, a4 = s3.via, d3 = Math.hypot(o5.x - a4.x, o5.y - a4.y), u2 = t2.areIdsConnected(o5.pcb_via_id, a4.pcb_via_id);\n if (u2 \u0026\u0026 d3 \u003c= 0.005)\n continue;\n let p3 = d3 - o5.hole_diameter / 2 - a4.hole_diameter / 2, m2 = i3;\n if (p3 + 0.005 \u003e= m2) {\n if (u2 || !o5.layers.some((e36) =\u003e a4.layers.includes(e36)))\n continue;\n if (p3 = d3 - o5.outer_diameter / 2 - a4.outer_diameter / 2, m2 = r3, p3 \u003e= 0 \u0026\u0026 p3 + 0.005 \u003e= m2)\n continue;\n }\n const g2 = [o5.pcb_via_id, a4.pcb_via_id].sort().join(\"_\");\n if (h2.has(g2))\n continue;\n h2.add(g2);\n const f2 = { x: (o5.x + a4.x) / 2, y: (o5.y + a4.y) / 2 }, _2 = { type: \"pcb_via_clearance_error\", error_type: \"pcb_via_clearance_error\", pcb_error_id: `${u2 ? \"same_net\" : \"different_net\"}_vias_close_${g2}`, message: `Vias ${iz(e35, o5.pcb_via_id)} and ${iz(e35, a4.pcb_via_id)}${u2 ? \"\" : \" from different nets\"} are too close together (gap: ${p3.toFixed(3)}mm)`, pcb_via_ids: [o5.pcb_via_id, a4.pcb_via_id], minimum_clearance: m2, actual_clearance: p3, pcb_center: f2 };\n u2 ? c3.push(_2) : l3.push(_2);\n }\n }\n return [...c3, ...l3];\n};\nvar sz = 0.005;\nvar az = (e35, t2) =\u003e {\n const n2 = e35.type === \"pcb_via\" ? e35.pcb_via_id : e35.type === \"pcb_smtpad\" ? e35.pcb_smtpad_id : e35.type === \"pcb_hole\" ? e35.pcb_hole_id : e35.pcb_plated_hole_id, o3 = e35.type === \"pcb_smtpad\" ? [e35.layer] : e35.type === \"pcb_hole\" ? [...fE] : e35.layers, i3 = FL([e35]);\n if (e35.type === \"pcb_smtpad\" \u0026\u0026 e35.shape === \"polygon\")\n return { id: n2, order: t2, layers: o3, element: e35, clearanceBounds: i3, minX: Math.min(...e35.points.map((e36) =\u003e e36.x)), minY: Math.min(...e35.points.map((e36) =\u003e e36.y)), maxX: Math.max(...e35.points.map((e36) =\u003e e36.x)), maxY: Math.max(...e35.points.map((e36) =\u003e e36.y)), shape: { kind: \"polygon\", points: e35.points } };\n if (e35.type === \"pcb_via\" || (e35.type === \"pcb_hole\" ? e35.hole_shape === \"circle\" : e35.shape === \"circle\")) {\n const r4 = e35.type === \"pcb_via\" ? e35.outer_diameter / 2 : e35.type === \"pcb_hole\" \u0026\u0026 e35.hole_shape === \"circle\" ? e35.hole_diameter / 2 : e35.type === \"pcb_smtpad\" \u0026\u0026 e35.shape === \"circle\" ? e35.radius : e35.outer_diameter / 2;\n return { id: n2, order: t2, layers: o3, element: e35, clearanceBounds: i3, minX: e35.x - r4, minY: e35.y - r4, maxX: e35.x + r4, maxY: e35.y + r4, shape: { kind: \"circle\", center: { x: e35.x, y: e35.y }, radius: r4 } };\n }\n let r3, s2, a3, c3 = 0, l3 = false;\n if (e35.type !== \"pcb_smtpad\" || e35.shape !== \"rect\" \u0026\u0026 e35.shape !== \"rotated_rect\")\n if (e35.type !== \"pcb_smtpad\" || e35.shape !== \"pill\" \u0026\u0026 e35.shape !== \"rotated_pill\")\n if (e35.type !== \"pcb_plated_hole\" || e35.shape !== \"oval\" \u0026\u0026 e35.shape !== \"pill\")\n if (e35.type === \"pcb_hole\")\n r3 = \"hole_width\" in e35 ? e35.hole_width : e35.hole_diameter, s2 = \"hole_height\" in e35 ? e35.hole_height : e35.hole_diameter, a3 = e35.hole_shape === \"rotated_pill\" ? e35.ccw_rotation : 0, l3 = e35.hole_shape === \"pill\" || e35.hole_shape === \"rotated_pill\", c3 = l3 ? Math.min(r3, s2) / 2 : 0;\n else {\n if (e35.type !== \"pcb_plated_hole\" || !(\"rect_pad_width\" in e35) || !(\"rect_pad_height\" in e35))\n throw new Error(`Unsupported autorouting DRC obstacle shape: ${e35.type}`);\n r3 = e35.rect_pad_width, s2 = e35.rect_pad_height, a3 = \"rect_ccw_rotation\" in e35 \u0026\u0026 typeof e35.rect_ccw_rotation == \"number\" ? e35.rect_ccw_rotation : 0;\n }\n else\n r3 = e35.outer_width, s2 = e35.outer_height, c3 = Math.min(r3, s2) / 2, a3 = e35.ccw_rotation, l3 = true;\n else\n r3 = e35.width, s2 = e35.height, c3 = e35.radius, a3 = e35.shape === \"rotated_pill\" ? e35.ccw_rotation : 0, l3 = true;\n else\n r3 = e35.width, s2 = e35.height, a3 = e35.shape === \"rotated_rect\" ? e35.ccw_rotation : 0, c3 = Math.max(0, Math.min(e35.corner_radius ?? 0, r3 / 2, s2 / 2)), l3 = c3 \u003e 0 \u0026\u0026 c3 === Math.min(r3, s2) / 2;\n const h2 = a3 * Math.PI / 180, d2 = Math.cos(h2), u2 = Math.sin(h2), p3 = [{ x: -r3 / 2, y: -s2 / 2 }, { x: r3 / 2, y: -s2 / 2 }, { x: r3 / 2, y: s2 / 2 }, { x: -r3 / 2, y: s2 / 2 }].map((t3) =\u003e ({ x: e35.x + (t3.x * d2 - t3.y * u2), y: e35.y + (t3.x * u2 + t3.y * d2) }));\n let m2, g2;\n if (l3) {\n const t3 = Math.max(Math.max(r3, s2) / 2 - c3, 0), n3 = r3 \u003e= s2 ? t3 * d2 : -t3 * u2, o4 = r3 \u003e= s2 ? t3 * u2 : t3 * d2;\n m2 = { kind: \"capsule\", start: { x: e35.x - n3, y: e35.y - o4 }, end: { x: e35.x + n3, y: e35.y + o4 }, radius: c3 };\n } else {\n m2 = { kind: \"polygon\", points: c3 === 0 ? p3 : [{ x: -r3 / 2 + c3, y: -s2 / 2 + c3 }, { x: r3 / 2 - c3, y: -s2 / 2 + c3 }, { x: r3 / 2 - c3, y: s2 / 2 - c3 }, { x: -r3 / 2 + c3, y: s2 / 2 - c3 }].map((t3) =\u003e ({ x: e35.x + t3.x * d2 - t3.y * u2, y: e35.y + t3.x * u2 + t3.y * d2 })), radius: c3 };\n }\n if (e35.type === \"pcb_hole\") {\n if (e35.hole_shape === \"oval\")\n if (Math.abs(r3 - s2) \u003c 0.000000001)\n g2 = new D_(new E_(new S_(0, 0), r3 / 2));\n else {\n const e36 = Math.max(16, Math.ceil(Math.PI / Math.acos(Math.max(-1, 1 - 0.000001 / (Math.max(r3, s2) / 2)))));\n g2 = new D_(Array.from({ length: e36 }, (t3, n3) =\u003e new S_(r3 / 2 * Math.cos(2 * n3 * Math.PI / e36), s2 / 2 * Math.sin(2 * n3 * Math.PI / e36))));\n }\n else if (l3) {\n const e36 = [new S_(r3 / 2 - c3, -s2 / 2 + c3), new S_(r3 / 2 - c3, s2 / 2 - c3), new S_(-r3 / 2 + c3, s2 / 2 - c3), new S_(-r3 / 2 + c3, -s2 / 2 + c3)], t3 = [];\n for (let n3 = 0;n3 \u003c 4; n3++) {\n const o4 = -Math.PI / 2 + n3 * Math.PI / 2, i4 = new A_(e36[n3], c3, o4, o4 + Math.PI / 2, true), r4 = e36[(n3 + 1) % 4], s3 = new S_(r4.x + c3 * Math.cos(o4 + Math.PI / 2), r4.y + c3 * Math.sin(o4 + Math.PI / 2));\n t3.push(i4), i4.end.distanceTo(s3)[0] \u003e 0.000000001 \u0026\u0026 t3.push(new w_(i4.end, s3));\n }\n g2 = new D_, g2.addFace(t3);\n } else\n g2 = new D_([new S_(-r3 / 2, -s2 / 2), new S_(r3 / 2, -s2 / 2), new S_(r3 / 2, s2 / 2), new S_(-r3 / 2, s2 / 2)]);\n g2 = g2.rotate(a3 * Math.PI / 180).translate(new P_(e35.x, e35.y));\n }\n const f2 = p3, _2 = g2 ? { minX: g2.box.xmin, minY: g2.box.ymin, maxX: g2.box.xmax, maxY: g2.box.ymax } : m2.kind === \"capsule\" ? { minX: Math.min(m2.start.x, m2.end.x) - m2.radius, minY: Math.min(m2.start.y, m2.end.y) - m2.radius, maxX: Math.max(m2.start.x, m2.end.x) + m2.radius, maxY: Math.max(m2.start.y, m2.end.y) + m2.radius } : { minX: Math.min(...f2.map((e36) =\u003e e36.x)), minY: Math.min(...f2.map((e36) =\u003e e36.y)), maxX: Math.max(...f2.map((e36) =\u003e e36.x)), maxY: Math.max(...f2.map((e36) =\u003e e36.y)) };\n return { id: n2, order: t2, layers: o3, element: e35, clearanceBounds: i3, holePolygon: g2, ..._2, shape: m2 };\n};\nvar cz = (e35, t2, n2, o3) =\u003e {\n const i3 = ge(e35, t2, n2, o3);\n if (i3)\n return { distance: 0, tracePoint: i3, obstaclePoint: i3 };\n const r3 = [{ tracePoint: e35, obstaclePoint: Ee(e35, n2, o3) }, { tracePoint: t2, obstaclePoint: Ee(t2, n2, o3) }, { tracePoint: Ee(n2, e35, t2), obstaclePoint: n2 }, { tracePoint: Ee(o3, e35, t2), obstaclePoint: o3 }];\n let s2 = r3[0], a3 = Number.POSITIVE_INFINITY;\n for (const e36 of r3) {\n const t3 = (e36.tracePoint.x - e36.obstaclePoint.x) ** 2 + (e36.tracePoint.y - e36.obstaclePoint.y) ** 2;\n t3 \u003c a3 \u0026\u0026 (s2 = e36, a3 = t3);\n }\n return { ...s2, distance: we(e35, t2, n2, o3) };\n};\nvar lz = (e35, t2, n2, o3) =\u003e {\n const i3 = n2 / 2;\n if (o3.element.type === \"pcb_hole\") {\n const n3 = o3.element;\n if (n3.hole_shape === \"circle\")\n return { gap: pe(n3, e35, t2) - n3.hole_diameter / 2 - i3, center: Ee(n3, e35, t2) };\n if (!o3.holePolygon)\n throw new Error(`Missing compiled hole geometry for ${o3.id}`);\n const r4 = new S_(e35.x, e35.y), s3 = new S_(t2.x, t2.y), [a4, c4] = o3.holePolygon.distanceTo(new w_(r4, s3));\n return { gap: (o3.holePolygon.contains(r4) || o3.holePolygon.contains(s3) ? 0 : a4) - i3, center: { x: c4.end.x, y: c4.end.y } };\n }\n let r3, s2, a3, c3 = 0;\n if (o3.shape.kind === \"circle\")\n c3 = o3.shape.radius, s2 = o3.shape.center, r3 = Ee(s2, e35, t2), a3 = Te(e35, t2, { ...s2, radius: c3 });\n else if (o3.shape.kind === \"capsule\") {\n const n3 = cz(e35, t2, o3.shape.start, o3.shape.end);\n r3 = n3.tracePoint, s2 = n3.obstaclePoint, c3 = o3.shape.radius, a3 = n3.distance - c3;\n } else {\n const n3 = o3.shape.points;\n if (c3 = o3.shape.radius ?? 0, n3.length \u003c 3)\n return { gap: 1 / 0, center: e35 };\n const i4 = n3.flatMap((o4, i5) =\u003e {\n const r4 = ge(e35, t2, o4, n3[(i5 + 1) % n3.length]);\n return r4 ? [r4] : [];\n });\n if (i4.length \u003e 0) {\n const n4 = t2.x - e35.x, o4 = t2.y - e35.y;\n i4.sort((t3, i5) =\u003e (t3.x - e35.x) * n4 + (t3.y - e35.y) * o4 - ((i5.x - e35.x) * n4 + (i5.y - e35.y) * o4)), r3 = s2 = i4[0], a3 = 0;\n } else if (ve(e35, n3) || ve(t2, n3))\n r3 = s2 = { x: (e35.x + t2.x) / 2, y: (e35.y + t2.y) / 2 }, a3 = 0;\n else {\n let o4 = cz(e35, t2, n3[0], n3[1]);\n for (let i5 = 1;i5 \u003c n3.length; i5++) {\n const r4 = cz(e35, t2, n3[i5], n3[(i5 + 1) % n3.length]);\n r4.distance \u003c o4.distance \u0026\u0026 (o4 = r4);\n }\n r3 = o4.tracePoint, s2 = o4.obstaclePoint, a3 = o4.distance;\n }\n a3 -= c3;\n }\n const l3 = s2.x - r3.x, h2 = s2.y - r3.y, d2 = Math.hypot(l3, h2), u2 = d2 === 0 ? 0 : l3 / d2, p3 = d2 === 0 ? 0 : h2 / d2;\n if (d2 \u003e 0 \u0026\u0026 d2 \u003c= i3 + c3) {\n const e36 = (Math.max(-i3, d2 - c3) + Math.min(i3, d2 + c3)) / 2;\n return { gap: a3 - i3, center: { x: r3.x + u2 * e36, y: r3.y + p3 * e36 } };\n }\n return { gap: a3 - i3, center: { x: (r3.x + u2 * i3 + (s2.x - u2 * c3)) / 2, y: (r3.y + p3 * i3 + (s2.y - p3 * c3)) / 2 } };\n};\nvar hz = (e35, t2) =\u003e {\n const n2 = e35.start, o3 = t2.start, i3 = e35.end.x - n2.x, r3 = e35.end.y - n2.y, s2 = t2.end.x - o3.x, a3 = t2.end.y - o3.y, c3 = i3 * i3 + r3 * r3, l3 = s2 * s2 + a3 * a3;\n if (c3 === 0 || l3 === 0) {\n const i4 = c3 === 0 ? n2 : Ee(o3, n2, e35.end), r4 = l3 === 0 ? o3 : Ee(n2, o3, t2.end);\n return { x: (i4.x + r4.x) / 2, y: (i4.y + r4.y) / 2 };\n }\n const h2 = n2.x - o3.x, d2 = n2.y - o3.y, u2 = i3 * s2 + r3 * a3, p3 = i3 * h2 + r3 * d2, m2 = s2 * h2 + a3 * d2, g2 = c3 * l3 - u2 * u2;\n if (g2 \u003c 0.0000000001) {\n const i4 = [{ pointA: Ee(o3, n2, e35.end), pointB: o3 }, { pointA: Ee(t2.end, n2, e35.end), pointB: t2.end }, { pointA: n2, pointB: Ee(n2, o3, t2.end) }, { pointA: e35.end, pointB: Ee(e35.end, o3, t2.end) }];\n let r4 = i4[0], s3 = Number.POSITIVE_INFINITY;\n for (const e36 of i4) {\n const t3 = Math.sqrt((e36.pointA.x - e36.pointB.x) ** 2 + (e36.pointA.y - e36.pointB.y) ** 2);\n t3 \u003c s3 \u0026\u0026 (r4 = e36, s3 = t3);\n }\n return { x: (r4.pointA.x + r4.pointB.x) / 2, y: (r4.pointA.y + r4.pointB.y) / 2 };\n }\n let f2 = Math.max(0, Math.min(1, (u2 * m2 - l3 * p3) / g2)), _2 = Math.max(0, Math.min(1, (f2 * u2 + m2) / l3));\n return f2 = Math.max(0, Math.min(1, (_2 * u2 - p3) / c3)), { x: (n2.x + f2 * i3 + (o3.x + _2 * s2)) / 2, y: (n2.y + f2 * r3 + (o3.y + _2 * a3)) / 2 };\n};\nvar dz = (e35, t2 = {}) =\u003e {\n const n2 = e35.filter((e36) =\u003e e36.type === \"pcb_smtpad\" || e36.type === \"pcb_plated_hole\" || e36.type === \"pcb_hole\").sort((e36, t3) =\u003e {\n const n3 = { pcb_smtpad: 0, pcb_plated_hole: 1, pcb_hole: 2 };\n return n3[e36.type] - n3[t3.type];\n }).map(az), o3 = new G;\n o3.load(n2);\n const i3 = new G;\n i3.load(n2.filter((e36) =\u003e e36.element.type !== \"pcb_hole\").map((e36) =\u003e ({ ...e36, ...e36.clearanceBounds })));\n const r3 = new G;\n return r3.load(n2.filter((e36) =\u003e e36.element.type === \"pcb_hole\")), (e36, s2) =\u003e {\n const a3 = e36.find((e37) =\u003e e37.type === \"pcb_board\"), c3 = t2.traceClearance ?? a3?.min_trace_to_pad_edge_clearance ?? 0.1, l3 = t2.holeClearance ?? a3?.min_trace_to_hole_edge_clearance ?? 0.2;\n if (!Number.isFinite(l3) || l3 \u003c 0)\n throw new Error(\"Trace-to-hole clearance must be finite and non-negative\");\n const h2 = e36.filter((e37) =\u003e e37.type === \"pcb_trace\"), d2 = [];\n for (const [e37, t3] of h2.entries()) {\n const n3 = Array.from(new Set(t3.route.flatMap((e38) =\u003e e38.route_type === \"wire\" ? [e38.start_pcb_port_id, e38.end_pcb_port_id].filter((e39) =\u003e Boolean(e39)) : [])));\n for (let o4 = 0;o4 \u003c t3.route.length - 1; o4++) {\n const i4 = t3.route[o4], r4 = t3.route[o4 + 1];\n if (i4.route_type !== \"wire\" \u0026\u0026 i4.route_type !== \"via\" || r4.route_type !== \"wire\" \u0026\u0026 r4.route_type !== \"via\")\n continue;\n const s3 = i4.route_type === \"wire\" ? i4 : r4;\n s3.route_type === \"wire\" \u0026\u0026 (i4.route_type === \"wire\" \u0026\u0026 r4.route_type === \"wire\" \u0026\u0026 i4.layer !== r4.layer || d2.push({ start: i4, end: r4, trace: t3, traceOrder: e37, portIds: n3, width: Math.max(i4.route_type === \"wire\" ? i4.width ?? 0.1 : 0, r4.route_type === \"wire\" ? r4.width ?? 0.1 : 0), typedWidth: i4.route_type === \"wire\" \u0026\u0026 r4.route_type === \"wire\" ? i4.width ?? r4.width ?? 0.1 : undefined, layer: s3.layer, order: d2.length, minX: Math.min(i4.x, r4.x), minY: Math.min(i4.y, r4.y), maxX: Math.max(i4.x, r4.x), maxY: Math.max(i4.y, r4.y) }));\n }\n }\n const u2 = e36.filter((e37) =\u003e e37.type === \"pcb_via\").map((e37, t3) =\u003e az(e37, n2.length + t3)), p3 = new G;\n p3.load([...d2, ...u2]);\n const m2 = d2.filter((e37) =\u003e e37.typedWidth !== undefined), g2 = new G;\n g2.load(m2);\n const f2 = m2.reduce((e37, t3) =\u003e Math.max(e37, t3.typedWidth / 2), 0), _2 = new Map, y2 = (e37, t3, n3) =\u003e {\n const o4 = Math.floor((e37.minX - t3) / 0.4), i4 = Math.floor((e37.minY - t3) / 0.4), r4 = Math.floor((e37.maxX + t3) / 0.4), s3 = Math.floor((e37.maxY + t3) / 0.4), a4 = { minX: 0.4 * o4, minY: 0.4 * i4, maxX: 0.4 * (r4 + 1), maxY: 0.4 * (s3 + 1) };\n return n3.flatMap((e38) =\u003e e38.search(a4)).filter((e38) =\u003e Math.floor(e38.minX / 0.4) \u003c= r4 \u0026\u0026 Math.floor(e38.maxX / 0.4) \u003e= o4 \u0026\u0026 Math.floor(e38.minY / 0.4) \u003c= s3 \u0026\u0026 Math.floor(e38.maxY / 0.4) \u003e= i4).sort((e38, t4) =\u003e Math.max(o4, Math.floor(e38.minX / 0.4)) - Math.max(o4, Math.floor(t4.minX / 0.4)) || Math.max(i4, Math.floor(e38.minY / 0.4)) - Math.max(i4, Math.floor(t4.minY / 0.4)) || e38.order + (\"trace\" in e38 ? 0 : d2.length) - (t4.order + (\"trace\" in t4 ? 0 : d2.length)));\n };\n for (const t3 of d2) {\n const { start: n3, end: i4, trace: r4, width: a4, portIds: l4 } = t3;\n if (n3.x !== i4.x || n3.y !== i4.y)\n for (const h3 of y2(t3, c3 + a4 / 2, [p3, o3])) {\n const o4 = \"trace\" in h3 ? h3.trace.pcb_trace_id : h3.id;\n if (!(\"trace\" in h3 ? [h3.layer] : h3.layers).includes(t3.layer))\n continue;\n const d3 = \"trace\" in h3 ? o4 : (\"pcb_trace_id\" in h3.element) ? h3.element.pcb_trace_id : o4;\n if (s2.areIdsConnected(r4.pcb_trace_id, d3))\n continue;\n const u3 = `${r4.pcb_trace_id}_${o4}`;\n if (_2.has(u3) || \"trace\" in h3 \u0026\u0026 _2.has(`${o4}_${r4.pcb_trace_id}`))\n continue;\n const p4 = \"trace\" in h3 ? { gap: we(n3, i4, h3.start, h3.end) - a4 / 2 - h3.width / 2, center: hz(t3, h3) } : lz(n3, i4, a4, h3);\n if (\"trace\" in h3 ? p4.gap \u003e c3 - sz : p4.gap \u003e 0)\n continue;\n const m3 = iz(e36, r4.pcb_trace_id), g3 = \"trace\" in h3 ? iz(e36, o4) : `${h3.element.type} \"${iz(e36, o4)}\"`, f3 = !(\"trace\" in h3) \u0026\u0026 h3.element.type === \"pcb_hole\";\n _2.set(u3, { type: \"pcb_trace_error\", error_type: \"pcb_trace_error\", message: p4.gap \u003c= 0 ? `PCB trace ${m3} overlaps with ${g3} (accidental contact)` : `PCB trace ${m3} is too close to ${g3} (gap: ${p4.gap.toFixed(3)}mm)`, pcb_trace_id: r4.pcb_trace_id, source_trace_id: f3 ? r4.source_trace_id ?? \"\" : \"\", pcb_trace_error_id: `overlap_${u3}`, pcb_component_ids: !(\"trace\" in h3) \u0026\u0026 \"pcb_component_id\" in h3.element \u0026\u0026 h3.element.pcb_component_id ? [h3.element.pcb_component_id] : [], pcb_port_ids: \"trace\" in h3 ? Array.from(new Set([...l4, ...h3.portIds])) : [...l4, ...\"pcb_port_id\" in h3.element \u0026\u0026 h3.element.pcb_port_id ? [h3.element.pcb_port_id] : []], center: p4.center });\n }\n }\n const b2 = new Map, x2 = new Set, v2 = (t3, n3) =\u003e {\n if (!n3.layers.includes(t3.layer) || s2.areIdsConnected(t3.trace.pcb_trace_id, n3.id))\n return;\n const o4 = `${n3.id}_${t3.trace.pcb_trace_id}`, { gap: i4, center: r4 } = lz(t3.start, t3.end, t3.typedWidth, n3);\n if (i4 \u003c= 0)\n return b2.delete(o4), void x2.add(o4);\n if (x2.has(o4) || i4 + sz \u003e= c3 || (b2.get(o4)?.gap ?? 1 / 0) \u003c= i4)\n return;\n const a4 = n3.element.type === \"pcb_via\", l4 = a4 ? \"pcb_via_trace_clearance_error\" : \"pcb_pad_trace_clearance_error\";\n b2.set(o4, { gap: i4, error: { type: l4, error_type: l4, [a4 ? \"pcb_via_trace_clearance_error_id\" : \"pcb_pad_trace_clearance_error_id\"]: `${a4 ? \"via\" : \"pad\"}_trace_clearance_${o4}`, [a4 ? \"pcb_via_id\" : \"pcb_pad_id\"]: n3.id, pcb_trace_id: t3.trace.pcb_trace_id, minimum_clearance: c3, actual_clearance: i4, message: `${a4 ? \"Via\" : \"Pad\"} ${iz(e36, n3.id)} and trace ${iz(e36, t3.trace.pcb_trace_id)} are too close (clearance: ${pR(i4)}, minimum: ${pR(c3)})`, center: r4 } });\n };\n for (const e37 of u2) {\n const t3 = c3 + f2 + sz, n3 = g2.search({ minX: e37.minX - t3, minY: e37.minY - t3, maxX: e37.maxX + t3, maxY: e37.maxY + t3 }).sort((e38, t4) =\u003e e38.order - t4.order);\n for (const t4 of n3)\n v2(t4, e37);\n }\n for (const e37 of m2)\n for (const t3 of y2(e37, c3 + e37.typedWidth / 2, [i3])) {\n if (\"trace\" in t3)\n throw new Error(\"Unexpected trace in pad index\");\n v2(e37, t3);\n }\n const I2 = new Map, S2 = new Set;\n for (const t3 of d2)\n for (const n3 of y2(t3, l3 + t3.width / 2, [r3])) {\n if (\"trace\" in n3 || n3.element.type !== \"pcb_hole\")\n throw new Error(\"Unexpected geometry in hole index\");\n const { gap: o4, center: i4 } = lz(t3.start, t3.end, t3.width, n3), r4 = `${t3.trace.pcb_trace_id}_${n3.id}`;\n o4 \u003c= 0 ? (I2.delete(r4), S2.add(r4)) : S2.has(r4) || o4 + 0.000001 \u003e= l3 || (I2.get(r4)?.gap ?? 1 / 0) \u003c= o4 || I2.set(r4, { gap: o4, error: { type: \"pcb_trace_error\", error_type: \"pcb_trace_error\", pcb_trace_error_id: `overlap_${r4}`, pcb_trace_id: t3.trace.pcb_trace_id, source_trace_id: t3.trace.source_trace_id ?? \"\", pcb_component_ids: n3.element.pcb_component_id ? [n3.element.pcb_component_id] : [], pcb_port_ids: [], center: i4, message: `Trace ${oz(e36, t3.trace.pcb_trace_id)} is too close to non-plated hole ${iz(e36, n3.id)} (gap: ${o4.toFixed(6)}mm, required: ${l3}mm)` } });\n }\n const C = Array.from(b2.values(), ({ error: e37 }) =\u003e e37);\n return { traceErrors: [..._2.values()], viaErrors: C.filter((e37) =\u003e e37.type === \"pcb_via_trace_clearance_error\"), padErrors: C.filter((e37) =\u003e e37.type === \"pcb_pad_trace_clearance_error\"), holeErrors: Array.from(I2.values(), ({ error: e37 }) =\u003e e37) };\n };\n};\nvar uz = (e35, t2 = {}) =\u003e {\n const n2 = e35.find((e36) =\u003e e36.type === \"pcb_board\"), o3 = t2.minClearance ?? n2?.min_pad_edge_to_pad_edge_clearance ?? 0.1, i3 = e35.filter((e36) =\u003e e36.type === \"pcb_smtpad\" || e36.type === \"pcb_plated_hole\").sort((e36, t3) =\u003e Number(e36.type === \"pcb_plated_hole\") - Number(t3.type === \"pcb_plated_hole\")), r3 = new G;\n return r3.load(i3.map((e36, t3) =\u003e {\n const n3 = az(e36, t3);\n return { ...n3, ...n3.clearanceBounds };\n })), (e36, n3) =\u003e {\n const i4 = [];\n for (const s2 of e36) {\n if (s2.type !== \"pcb_via\")\n continue;\n const a3 = FL([s2]), c3 = Math.floor((a3.minX - o3) / 0.4), l3 = Math.floor((a3.minY - o3) / 0.4), h2 = Math.floor((a3.maxX + o3) / 0.4), d2 = Math.floor((a3.maxY + o3) / 0.4), u2 = r3.search({ minX: 0.4 * c3, minY: 0.4 * l3, maxX: 0.4 * (h2 + 1), maxY: 0.4 * (d2 + 1) }).filter((e37) =\u003e Math.floor(e37.minX / 0.4) \u003c= h2 \u0026\u0026 Math.floor(e37.maxX / 0.4) \u003e= c3 \u0026\u0026 Math.floor(e37.minY / 0.4) \u003c= d2 \u0026\u0026 Math.floor(e37.maxY / 0.4) \u003e= l3).sort((e37, t3) =\u003e Math.max(c3, Math.floor(e37.minX / 0.4)) - Math.max(c3, Math.floor(t3.minX / 0.4)) || Math.max(l3, Math.floor(e37.minY / 0.4)) - Math.max(l3, Math.floor(t3.minY / 0.4)) || e37.order - t3.order);\n for (const r4 of u2) {\n if (!s2.layers.some((e37) =\u003e r4.layers.includes(e37)))\n continue;\n const c4 = n3.areIdsConnected(s2.pcb_via_id, r4.id);\n if (c4 \u0026\u0026 t2.allowViaInPad !== false)\n continue;\n let l4 = o3, h3 = 0.005, d3 = s2.outer_diameter, u3 = \"pcb_pad_pad_clearance_error\";\n c4 \u0026\u0026 (l4 = 0, h3 = 0.000001, d3 = s2.hole_diameter, u3 = \"pcb_placement_error\");\n const p3 = { kind: \"circle\", x: (a3.minX + a3.maxX) / 2, y: (a3.minY + a3.maxY) / 2, radius: Math.min(a3.maxX - a3.minX, a3.maxY - a3.minY) / 2 };\n let m2 = r4.shape.kind === \"circle\" ? VL(p3, { kind: \"circle\", x: (r4.clearanceBounds.minX + r4.clearanceBounds.maxX) / 2, y: (r4.clearanceBounds.minY + r4.clearanceBounds.maxY) / 2, radius: Math.min(r4.clearanceBounds.maxX - r4.clearanceBounds.minX, r4.clearanceBounds.maxY - r4.clearanceBounds.minY) / 2 }) : r4.shape.kind === \"capsule\" ? Te(r4.shape.start, r4.shape.end, p3) - r4.shape.radius : WL(p3, { kind: \"polygon\", points: r4.shape.points }) - (r4.shape.radius ?? 0);\n if (c4 \u0026\u0026 (m2 = lz(s2, s2, d3, r4).gap), m2 + h3 \u003e= l4)\n continue;\n let g2 = lz(s2, s2, d3, r4).center;\n c4 \u0026\u0026 (g2 = { x: (r4.minX + r4.maxX) / 2, y: (r4.minY + r4.maxY) / 2 }), i4.push({ type: u3, error_type: u3, [`${u3}_id`]: `via_pad_clearance_${s2.pcb_via_id}_${r4.id}`, message: `Via ${iz(e36, s2.pcb_via_id)} and pad ${iz(e36, r4.id)} are too close (clearance: ${pR(m2)}, minimum: ${pR(l4)})`, pcb_pad_ids: [s2.pcb_via_id, r4.id], minimum_clearance: l4, actual_clearance: m2, center: g2, pcb_via_ids: [s2.pcb_via_id], ...typeof s2.pcb_trace_id == \"string\" ? { pcb_trace_id: s2.pcb_trace_id } : {} });\n }\n }\n return i4;\n };\n};\nvar pz = Symbol(\"originalPortPoint\");\nvar mz = class extends mr {\n constructor(e35) {\n const t2 = e35.nodeWithPortPoints, n2 = (e35.traceThickness ?? 0.1) / 2 + (e35.traceMargin ?? 0.1), o3 = t2.width \u003e 2 * n2 \u0026\u0026 t2.height \u003e 2 * n2, i3 = t2.center.x - t2.width / 2 + n2, r3 = t2.center.x + t2.width / 2 - n2, s2 = t2.center.y - t2.height / 2 + n2, a3 = t2.center.y + t2.height / 2 - n2, c3 = t2.portPoints.map((e36) =\u003e ({ ...e36, x: Math.max(i3, Math.min(r3, e36.x)), y: Math.max(s2, Math.min(a3, e36.y)), [pz]: e36 })), l3 = new Map;\n let h2 = false;\n for (const e36 of c3) {\n const t3 = `${e36.x},${e36.y},${e36.z}`, n3 = l3.get(t3), o4 = e36[pz];\n !n3 || n3.x === o4.x \u0026\u0026 n3.y === o4.y || (h2 = true), l3.set(t3, o4);\n }\n super({ ...e35, nodeWithPortPoints: o3 ? { ...t2, width: t2.width - 2 * n2, height: t2.height - 2 * n2, portPoints: c3 } : t2 }), h2 \u0026\u0026 (this.failed = true, this.error = \"Boundary clearance collapses distinct terminals\"), o3 || (this.failed = true, this.error = \"Node has no interior after copper boundary clearance\");\n }\n getOutput() {\n return super.getOutput().map((e35) =\u003e {\n const t2 = e35.route[0], n2 = e35.route[e35.route.length - 1];\n if (!t2[pz] || !n2[pz])\n throw new Error(\"A13 route lost its original terminal metadata\");\n return { ...e35, route: [{ ...t2[pz] }, ...e35.route, { ...n2[pz] }] };\n });\n }\n};\nvar gz = class extends mz {\n constructor(e35) {\n super(e35), this.validationParams = e35;\n }\n _step() {\n if (super._step(), !this.solved)\n return;\n const e35 = this.getOutput(), { connMap: t2, layerCount: n2 } = this.validationParams, o3 = this.nodeWithPortPoints, i3 = e35.flatMap((e36) =\u003e e36.route), r3 = Math.max(this.traceThickness, this.viaDiameter) / 2 + Math.max(this.traceMargin, 0.1) + 0.000001, s2 = Math.min(...i3.map((e36) =\u003e e36.x)) - r3, a3 = Math.max(...i3.map((e36) =\u003e e36.x)) + r3, c3 = Math.min(...i3.map((e36) =\u003e e36.y)) - r3, l3 = Math.max(...i3.map((e36) =\u003e e36.y)) + r3, h2 = this.validationParams.obstacles.filter((e36) =\u003e {\n const t3 = Math.hypot(e36.width, e36.height) / 2;\n return e36.center.x + t3 \u003e= s2 \u0026\u0026 e36.center.x - t3 \u003c= a3 \u0026\u0026 e36.center.y + t3 \u003e= c3 \u0026\u0026 e36.center.y - t3 \u003c= l3;\n });\n this.stats.boardObstaclesChecked = h2.length;\n const { connectedRouteNamesByObstacle: d2, connectedObstaclesByRoute: u2 } = (({ obstacles: e36, routes: t3, connMap: n3 }) =\u003e {\n const o4 = e36.map(() =\u003e []), i4 = t3.map(() =\u003e []);\n for (let r4 = 0;r4 \u003c e36.length; r4++) {\n const s3 = e36[r4], a4 = { ...s3, connectedTo: [...new Set(s3.connectedTo)] };\n for (let e37 = 0;e37 \u003c t3.length; e37++) {\n const c4 = t3[e37];\n xo(a4, c4, n3) \u0026\u0026 (o4[r4].push(c4.connectionName), i4[e37].push(s3));\n }\n }\n return { connectedRouteNamesByObstacle: o4, connectedObstaclesByRoute: i4 };\n })({ obstacles: h2, routes: e35, connMap: t2 }), p3 = { layerCount: n2, minTraceWidth: this.traceThickness, minViaDiameter: this.viaDiameter, bounds: { minX: o3.center.x - o3.width / 2, maxX: o3.center.x + o3.width / 2, minY: o3.center.y - o3.height / 2, maxY: o3.center.y + o3.height / 2 }, ...this.validationParams.boardGeometry, obstacles: h2.map((e36, t3) =\u003e ({ ...e36, connectedTo: [...e36.connectedTo, ...d2[t3]] })), connections: e35.map((e36, t3) =\u003e ({ name: e36.connectionName, rootConnectionName: e36.rootConnectionName, __netConnectionName: e36.rootConnectionName ?? e36.connectionName, pointsToConnect: [...[e36.route[0], e36.route.at(-1)].map((e37) =\u003e ({ x: e37.x, y: e37.y, layer: Co(e37.z, n2) })), ...u2[t3].flatMap((e37) =\u003e {\n const t4 = e37.circuitJsonMetadata?.pcb_port_id;\n return t4 ? [{ ...e37.center, layer: Co(0, n2), pcb_port_id: t4 }] : [];\n })] })) }, m2 = sR(p3, e35.map((e36, t3) =\u003e ({ type: \"pcb_trace\", pcb_trace_id: `${e36.connectionName}_${t3}`, connection_name: e36.connectionName, route: Ro(e36, n2) })));\n this.validationParams.boardGeometry \u0026\u0026 m2.push(rR(p3));\n const g2 = qy(m2);\n aR(m2);\n const f2 = dz(m2, { traceClearance: this.traceMargin })(m2, g2), _2 = [...f2.traceErrors, ...lR(m2), ...f2.viaErrors, ...f2.padErrors, ...f2.holeErrors, ...uz(m2)(m2, g2), ...rz(m2, g2, { viaClearance: this.traceMargin })], y2 = ay({ srj: { ...p3, traces: undefined }, routes: e35 });\n this.stats.boardDrcIssueCount = _2.length + y2.length, (_2.length \u003e 0 || y2.length \u003e 0) \u0026\u0026 (this.solved = false, this.failed = true, this.error = `A13 candidate fails board copper validation: ${_2[0]?.message ?? \"fixed obstacle clearance violation\"}`);\n }\n};\nvar fz = (e35) =\u003e `${e35.x.toFixed(6)},${e35.y.toFixed(6)},${e35.z}`;\nvar _z = (e35) =\u003e [e35.route[0], e35.route[e35.route.length - 1]];\nvar yz = (e35, t2, n2) =\u003e {\n const o3 = new Map, i3 = (e36, t3) =\u003e {\n o3.has(e36) || o3.set(e36, new Set), o3.has(t3) || o3.set(t3, new Set), o3.get(e36).add(t3), o3.get(t3).add(e36);\n };\n for (const n3 of e35)\n if (n3.connectionName === t2 \u0026\u0026 n3.route.length !== 0) {\n if (n3.route.length === 1) {\n const e36 = fz(n3.route[0]);\n o3.has(e36) || o3.set(e36, new Set);\n continue;\n }\n for (let e36 = 0;e36 \u003c n3.route.length - 1; e36++)\n i3(fz(n3.route[e36]), fz(n3.route[e36 + 1]));\n }\n const r3 = new Set([n2]), s2 = [n2];\n for (;s2.length \u003e 0; ) {\n const e36 = s2.pop();\n for (const t3 of o3.get(e36) ?? [])\n r3.has(t3) || (r3.add(t3), s2.push(t3));\n }\n return r3;\n};\nvar bz = Array.from({ length: 6 }, (e35, t2) =\u003e t2);\nvar xz = class extends wa {\n getSolverName() {\n return \"PortfolioSingleIntraNodeSolver\";\n }\n constructorParams;\n solvedRoutes = [];\n nodeWithPortPoints;\n connMap;\n effort;\n adaptiveSearchExpanded = false;\n negotiatedSearchStarted = false;\n enableNegotiatedSearch;\n gridSearchSegmentWork;\n gridSearchWorkScale;\n rejectOverlappingTerminals;\n precomputedIntraNodeRouteParams;\n nodeSegmentCount;\n totalCandidateWork = 0;\n dynamicExpansionWorkBudget = 1;\n candidateWorkBySolver = new WeakMap;\n getSolvedSegmentCount(e35) {\n const t2 = e35.solvedConnectionsMap;\n if (!(t2 instanceof Map))\n return null;\n let n2 = 0;\n for (const e36 of t2.values())\n Array.isArray(e36) \u0026\u0026 (n2 += e36.length);\n return n2;\n }\n getNodeSegmentCount() {\n return this.nodeSegmentCount ??= Math.max(1, this.nodeWithPortPoints.portPointsInPairs?.length ?? new Set(this.nodeWithPortPoints.portPoints.map((e35) =\u003e e35.connectionName)).size), this.nodeSegmentCount;\n }\n getCandidateProgress(e35) {\n if (e35 instanceof mr) {\n if (e35.solved)\n return 1;\n const t3 = e35.connections.length;\n if (t3 === 0)\n return 0;\n const n2 = e35.routedCount / t3, o3 = Math.max(0, (e35.routedCount - e35.conflictCount) / t3);\n return Math.min(0.99, (n2 + o3) / 2);\n }\n const t2 = this.getSolvedSegmentCount(e35);\n return t2 !== null ? Math.min(1, t2 / this.getNodeSegmentCount()) : Math.max(0, Math.min(1, e35.progress || 0));\n }\n constructor(e35) {\n if (super(), this.nodeWithPortPoints = e35.nodeWithPortPoints, this.connMap = e35.connMap, this.constructorParams = e35, this.effort = e35.effort ?? 1, this.gridSearchSegmentWork = e35.gridSearchSegmentWork ?? 1e4, this.gridSearchWorkScale = e35.gridSearchWorkScale ?? 1, this.rejectOverlappingTerminals = e35.rejectOverlappingTerminals ?? false, this.enableNegotiatedSearch = e35.enableNegotiatedSearch ?? false, this.MAX_ITERATIONS = 20000000 * this.effort, this.GREEDY_MULTIPLIER = 5, this.MIN_SUBSTEPS = 100, this.rejectOverlappingTerminals) {\n const t2 = this.nodeWithPortPoints.portPoints, n2 = e35.traceWidth ?? 0.15;\n for (let e36 = 0;e36 \u003c t2.length; e36++)\n for (let o3 = e36 + 1;o3 \u003c t2.length; o3++) {\n const i3 = t2[e36], r3 = t2[o3];\n if (i3.z === r3.z \u0026\u0026 (i3.rootConnectionName ?? i3.connectionName) !== (r3.rootConnectionName ?? r3.connectionName) \u0026\u0026 !this.connMap?.areIdsConnected(i3.connectionName, r3.connectionName) \u0026\u0026 Math.hypot(i3.x - r3.x, i3.y - r3.y) \u003c n2 - 0.000001)\n return this.failed = true, void (this.error = \"Unrelated route terminals overlap at the requested trace width\");\n }\n }\n }\n getGridSearchIterationBudget() {\n const e35 = this.nodeWithPortPoints, t2 = e35.availableZ?.length ?? new Set(e35.portPoints.map((e36) =\u003e e36.z)).size, n2 = Math.floor(e35.width / 0.1) * Math.floor(e35.height / 0.1) * t2, o3 = t2 \u003e 2 ? this.gridSearchWorkScale : 1;\n return Math.round(o3 * Math.max(150000, (t2 \u003c= 2 ? 1e4 : this.gridSearchSegmentWork) * this.getNodeSegmentCount() ** 2, Math.round(n2 * (8 + 1.2 * Math.sqrt(this.getNodeSegmentCount())) * this.effort)));\n }\n getCombinationDefs() {\n return [[\"throughObstacle\"], [\"singleLayerNoDifferentRootIntersections\"], [\"multiHeadPolyLine\"], [\"majorCombinations\", \"orderings6\", \"cellSizeFactor\"], [\"noVias\"], [\"orderings50\"], [\"flipTraceAlignmentDirection\", \"orderings6\"], [\"closedFormSingleTrace\"], [\"highDensityA01\"], [\"highDensityA03\"], ...this.enableNegotiatedSearch ? [[\"highDensityA13\"]] : []];\n }\n getHyperParameterDefs() {\n let e35 = false;\n if (this.constructorParams.priorityDagSearch) {\n this.precomputedIntraNodeRouteParams ??= Or(this.nodeWithPortPoints);\n const t2 = [...this.precomputedIntraNodeRouteParams.connectionPointsByName.entries()].map(([e36, t3]) =\u003e ({ connectionName: e36, rootConnectionName: this.precomputedIntraNodeRouteParams.rootConnectionNameByConnectionName.get(e36), points: t3 }));\n let n2 = 0;\n const o3 = ds.detailedWorkDiagnostics;\n e35 = $r(t2, (e36, t3 = 1) =\u003e {\n o3 \u0026\u0026 (n2 += t3);\n }) !== null;\n const i3 = this.constructorParams.priorityDiagnostics;\n o3 \u0026\u0026 i3 \u0026\u0026 (i3.priorityEligibilityCalls = (i3.priorityEligibilityCalls ?? 0) + 1, i3.priorityEligibilityObservedWork = (i3.priorityEligibilityObservedWork ?? 0) + n2, e35 || (i3.priorityIneligiblePreflightWork = (i3.priorityIneligiblePreflightWork ?? 0) + n2));\n }\n return [{ name: \"singleLayerNoDifferentRootIntersections\", possibleValues: [{ SINGLE_LAYER_NO_DIFFERENT_ROOT_INTERSECTIONS: true }] }, { name: \"majorCombinations\", possibleValues: [{ FUTURE_CONNECTION_PROX_TRACE_PENALTY_FACTOR: 2, FUTURE_CONNECTION_PROX_VIA_PENALTY_FACTOR: 1, FUTURE_CONNECTION_PROXIMITY_VD: 10, MISALIGNED_DIST_PENALTY_FACTOR: 5 }, { FUTURE_CONNECTION_PROX_TRACE_PENALTY_FACTOR: 1, FUTURE_CONNECTION_PROX_VIA_PENALTY_FACTOR: 0.5, FUTURE_CONNECTION_PROXIMITY_VD: 5, MISALIGNED_DIST_PENALTY_FACTOR: 2 }, { FUTURE_CONNECTION_PROX_TRACE_PENALTY_FACTOR: 10, FUTURE_CONNECTION_PROX_VIA_PENALTY_FACTOR: 1, FUTURE_CONNECTION_PROXIMITY_VD: 5, MISALIGNED_DIST_PENALTY_FACTOR: 10, VIA_PENALTY_FACTOR_2: 1 }] }, { name: \"orderings6\", possibleValues: e35 ? [{ SHUFFLE_SEED: 0, PRIORITY_DAG_FAMILY_SIZE: 6 }] : bz.map((e36) =\u003e ({ SHUFFLE_SEED: e36 })) }, { name: \"cellSizeFactor\", possibleValues: [{ CELL_SIZE_FACTOR: 0.5 }, { CELL_SIZE_FACTOR: 1 }] }, { name: \"flipTraceAlignmentDirection\", possibleValues: [{ FLIP_TRACE_ALIGNMENT_DIRECTION: true }] }, { name: \"noVias\", possibleValues: [{ CELL_SIZE_FACTOR: 2, VIA_PENALTY_FACTOR_2: 10 }] }, { name: \"orderings50\", possibleValues: e35 ? [{ SHUFFLE_SEED: 0, PRIORITY_DAG_FAMILY_SIZE: 20 }] : Array.from({ length: 20 }, (e36, t2) =\u003e ({ SHUFFLE_SEED: 100 + t2 })) }, { name: \"throughObstacle\", possibleValues: [{ THROUGH_OBSTACLE: true }] }, { name: \"closedFormSingleTrace\", possibleValues: [{ CLOSED_FORM_SINGLE_TRANSITION: true }] }, { name: \"multiHeadPolyLine\", possibleValues: [{ MULTI_HEAD_POLYLINE_SOLVER: true, SEGMENTS_PER_POLYLINE: 6, BOUNDARY_PADDING: 0.05 }, { MULTI_HEAD_POLYLINE_SOLVER: true, SEGMENTS_PER_POLYLINE: 6, BOUNDARY_PADDING: -0.05, ITERATION_PENALTY: 1e4, MINIMUM_FINAL_ACCEPTANCE_GAP: 0.001 }] }, { name: \"highDensityA01\", possibleValues: [{ HIGH_DENSITY_A01: true, SHUFFLE_SEED: bz[0] }] }, { name: \"highDensityA03\", possibleValues: [{ HIGH_DENSITY_A03: true }] }, { name: \"highDensityA13\", possibleValues: [{ HIGH_DENSITY_A13: true, SHUFFLE_SEED: 0 }] }];\n }\n initializeCandidateBudget(e35) {\n if (e35 instanceof mr)\n return;\n const t2 = e35.setup;\n typeof t2 == \"function\" \u0026\u0026 t2.call(e35), (e35 instanceof Mi || e35 instanceof zi) \u0026\u0026 (e35.MAX_ITERATIONS = Math.min(e35.MAX_ITERATIONS, this.getGridSearchIterationBudget()));\n }\n refreshDynamicIterationLimit() {\n this.totalCandidateWork = 0, this.dynamicExpansionWorkBudget = 1;\n const e35 = (this.supervisedSolvers ?? []).reduce((e36, { solver: t2 }) =\u003e {\n if (t2 instanceof mr || (this.totalCandidateWork += t2.iterations, this.dynamicExpansionWorkBudget = Math.max(this.dynamicExpansionWorkBudget, t2 instanceof ds ? t2.nativeCandidateIterationLimit : t2.MAX_ITERATIONS), this.candidateWorkBySolver.set(t2, { iterations: t2.iterations, maxIterations: t2.MAX_ITERATIONS })), t2.solved || t2.failed)\n return e36;\n const n2 = Math.max(0, t2.MAX_ITERATIONS - t2.iterations + 1);\n return e36 + Math.ceil(n2 / this.MIN_SUBSTEPS);\n }, 0);\n this.MAX_ITERATIONS = Math.max(this.iterations + 1, this.iterations + e35), this.stats.dynamicSupervisorIterationLimit = this.MAX_ITERATIONS;\n }\n initialA01Orderings = new Set;\n initializeSolvers() {\n super.initializeSolvers();\n for (const { solver: e35, hyperParameters: t2 } of this.supervisedSolvers ?? [])\n this.initializeCandidateBudget(e35), t2.HIGH_DENSITY_A01 \u0026\u0026 this.initialA01Orderings.add(JSON.stringify(e35.unsolvedConnections));\n this.refreshDynamicIterationLimit(), this.stats.dynamicExpansionWorkBudget = this.dynamicExpansionWorkBudget;\n }\n addSupervisedCandidate(e35) {\n const t2 = this.generateSolver(e35);\n if (this.initializeCandidateBudget(t2), e35.HIGH_DENSITY_A01) {\n const e36 = JSON.stringify(t2.unsolvedConnections);\n if (this.initialA01Orderings.has(e36))\n return;\n this.initialA01Orderings.add(e36);\n }\n const n2 = this.computeG(t2);\n this.supervisedSolvers.push({ hyperParameters: e35, solver: t2, h: 0, g: n2, f: n2 });\n }\n expandAdaptiveSearch() {\n if (!this.adaptiveSearchExpanded) {\n this.adaptiveSearchExpanded = true;\n for (const e35 of bz.slice(1))\n this.addSupervisedCandidate({ HIGH_DENSITY_A01: true, SHUFFLE_SEED: e35 });\n this.refreshDynamicIterationLimit(), this.stats.adaptiveSearchExpanded = true, this.stats.adaptiveSearchExpandedAtIteration = this.iterations, this.stats.candidateWorkAtExpansion = this.totalCandidateWork, this.stats.bestProgressAtExpansion = Math.max(0, ...(this.supervisedSolvers ?? []).map(({ solver: e35 }) =\u003e this.getCandidateProgress(e35)));\n }\n }\n shouldExpandPortfolio() {\n if (this.adaptiveSearchExpanded)\n return false;\n const e35 = this.dynamicExpansionWorkBudget;\n return this.stats.dynamicExpansionWorkBudget = e35, this.totalCandidateWork \u003e= e35;\n }\n _step() {\n this.supervisedSolvers || this.initializeSolvers(), this.adaptiveSearchExpanded || this.getSupervisedSolverWithBestFitness() || this.expandAdaptiveSearch(), super._step(), !this.negotiatedSearchStarted \u0026\u0026 this.activeSubSolver instanceof mr \u0026\u0026 (this.negotiatedSearchStarted = true, this.stats.negotiatedSearchStartedAtIteration = this.iterations), this.solved || this.failed || !this.shouldExpandPortfolio() || this.expandAdaptiveSearch();\n }\n computeG(e35) {\n if (e35 instanceof mr)\n return e35.routingIterations / 1e6;\n const t2 = this.candidateWorkBySolver.get(e35);\n if (t2 \u0026\u0026 (this.totalCandidateWork += e35.iterations - t2.iterations, t2.iterations = e35.iterations, t2.maxIterations !== e35.MAX_ITERATIONS)) {\n t2.maxIterations = e35.MAX_ITERATIONS, this.dynamicExpansionWorkBudget = 1;\n for (const { solver: e36 } of this.supervisedSolvers ?? [])\n e36 instanceof mr || (this.dynamicExpansionWorkBudget = Math.max(this.dynamicExpansionWorkBudget, e36 instanceof ds ? e36.nativeCandidateIterationLimit : e36.MAX_ITERATIONS));\n }\n return e35 instanceof Mi || e35 instanceof zi || e35 instanceof mr ? e35.iterations / 1e6 : e35?.hyperParameters?.MULTI_HEAD_POLYLINE_SOLVER ? 1000 + ((e35.hyperParameters?.ITERATION_PENALTY ?? 0) + e35.iterations) / 1e4 + 1e4 * (e35.hyperParameters.SEGMENTS_PER_POLYLINE - 3) : e35.iterations / 1e4;\n }\n computeH(e35) {\n return e35 instanceof mr || this.adaptiveSearchExpanded ? 1 - this.getCandidateProgress(e35) : 1 - (e35.progress || 0);\n }\n generateSolver(e35) {\n if (this.precomputedIntraNodeRouteParams ??= Or(this.nodeWithPortPoints), e35.SINGLE_LAYER_NO_DIFFERENT_ROOT_INTERSECTIONS) {\n if (!ra.isApplicable(this.nodeWithPortPoints)) {\n const e36 = new Lr({ nodeWithPortPoints: this.nodeWithPortPoints, connMap: this.connMap, traceWidth: this.constructorParams.traceWidth, viaDiameter: this.constructorParams.viaDiameter, obstacleMargin: this.constructorParams.obstacleMargin, precomputedIntraNodeRouteParams: this.precomputedIntraNodeRouteParams });\n return e36.failed = true, e36.error = \"Single-layer no-different-root-intersection solver not applicable\", e36;\n }\n return new ra({ nodeWithPortPoints: this.nodeWithPortPoints, traceWidth: this.constructorParams.traceWidth, viaDiameter: this.constructorParams.viaDiameter });\n }\n if (e35.HIGH_DENSITY_A13) {\n const t2 = Math.max(1, Math.round(50000000 * this.effort)), n2 = new gz({ obstacles: this.constructorParams.obstacles ?? [], boardGeometry: this.constructorParams.boardGeometry, connMap: this.connMap, layerCount: this.constructorParams.layerCount ?? 2, nodeWithPortPoints: this.nodeWithPortPoints, cellSizeMm: 0.1, viaDiameter: this.constructorParams.viaDiameter ?? 0.3, viaMinDistFromBorder: (this.constructorParams.viaDiameter ?? 0.3) / 2, traceThickness: this.constructorParams.traceWidth ?? 0.15, traceMargin: 0.1, stepMultiplier: 1000, maxSearchIterations: t2, maxRounds: Math.max(1, Math.round(200 * this.effort)), hyperParameters: { shuffleSeed: e35.SHUFFLE_SEED ?? 0 } });\n return n2.MAX_ITERATIONS = 2 * t2, n2;\n }\n if (e35.HIGH_DENSITY_A01) {\n return new Mi({ nodeWithPortPoints: this.nodeWithPortPoints, cellSizeMm: 0.1, viaDiameter: this.constructorParams.viaDiameter ?? 0.3, viaMinDistFromBorder: (this.constructorParams.viaDiameter ?? 0.3) / 2, traceMargin: 0.1, traceThickness: this.constructorParams.traceWidth ?? 0.15, effort: this.effort, hyperParameters: { shuffleSeed: e35.SHUFFLE_SEED ?? 0 } });\n }\n if (e35.HIGH_DENSITY_A03) {\n return new zi({ nodeWithPortPoints: this.nodeWithPortPoints, highResolutionCellSize: 0.1, highResolutionCellThickness: 8, lowResolutionCellSize: 0.4, viaDiameter: this.constructorParams.viaDiameter ?? 0.3, viaMinDistFromBorder: (this.constructorParams.viaDiameter ?? 0.3) / 2, traceMargin: 0.1, traceThickness: 0.1, effort: this.effort, hyperParameters: e35 });\n }\n return e35.CLOSED_FORM_TWO_TRACE_SAME_LAYER ? new Ma({ nodeWithPortPoints: this.nodeWithPortPoints, viaDiameter: this.constructorParams.viaDiameter }) : e35.CLOSED_FORM_TWO_TRACE_TRANSITION_CROSSING ? new Ca({ nodeWithPortPoints: this.nodeWithPortPoints, viaDiameter: this.constructorParams.viaDiameter }) : e35.CLOSED_FORM_SINGLE_TRANSITION ? new aa({ nodeWithPortPoints: this.nodeWithPortPoints, viaDiameter: this.constructorParams.viaDiameter }) : e35.THROUGH_OBSTACLE ? new da({ nodeWithPortPoints: this.nodeWithPortPoints, obstacles: this.constructorParams.obstacles, connMap: this.connMap, layerCount: this.constructorParams.layerCount, viaDiameter: this.constructorParams.viaDiameter, traceThickness: this.constructorParams.traceWidth }) : e35.MULTI_HEAD_POLYLINE_SOLVER ? new Bs({ nodeWithPortPoints: this.nodeWithPortPoints, connMap: this.connMap, hyperParameters: e35, viaDiameter: this.constructorParams.viaDiameter }) : e35.PRIORITY_DAG_FAMILY_SIZE ? new ds({ ...this.constructorParams, hyperParameters: e35, priorityFamilySize: e35.PRIORITY_DAG_FAMILY_SIZE, precomputedIntraNodeRouteParams: this.precomputedIntraNodeRouteParams }) : new jr({ ...this.constructorParams, hyperParameters: e35, precomputedIntraNodeRouteParams: this.precomputedIntraNodeRouteParams });\n }\n onSolve(e35) {\n let t2;\n t2 = e35.solver instanceof Mi || e35.solver instanceof zi || e35.solver instanceof mr ? e35.solver.getOutput() : e35.solver.solvedRoutes;\n const n2 = t2.map((e36) =\u003e {\n const t3 = this.nodeWithPortPoints.portPoints.find((t4) =\u003e t4.connectionName === e36.connectionName);\n return t3?.rootConnectionName ? { ...e36, rootConnectionName: t3.rootConnectionName } : e36;\n });\n this.solvedRoutes = ((e36, t3) =\u003e {\n const n3 = [...e36], o3 = new Map;\n for (const e37 of t3.portPoints) {\n const t4 = o3.get(e37.connectionName) ?? [];\n t4.push(e37), o3.set(e37.connectionName, t4);\n }\n for (const [e37, t4] of o3) {\n if (t4.length \u003c= 1)\n continue;\n const o4 = t4[0]?.rootConnectionName ?? e37, i3 = new Set(t4.map(fz));\n let r3 = yz(n3, e37, fz(t4[0]));\n for (const s2 of t4.slice(1)) {\n const a3 = fz(s2);\n if (r3.has(a3))\n continue;\n const c3 = n3.find((t5) =\u003e {\n if ((t5.rootConnectionName ?? t5.connectionName) !== o4)\n return false;\n if (t5.connectionName === e37)\n return false;\n const [n4, s3] = _z(t5);\n if (!n4 || !s3)\n return false;\n const c4 = fz(n4), l3 = fz(s3);\n return r3.has(c4) \u0026\u0026 l3 === a3 || r3.has(l3) \u0026\u0026 c4 === a3 || i3.has(c4) \u0026\u0026 i3.has(l3) \u0026\u0026 (c4 === a3 || l3 === a3);\n });\n c3 \u0026\u0026 (n3.push({ ...c3, connectionName: e37, rootConnectionName: o4, route: c3.route.map((t5) =\u003e ({ ...t5, connectionName: e37, rootConnectionName: o4 })), vias: c3.vias.map((e38) =\u003e ({ ...e38 })), jumpers: c3.jumpers?.map((e38) =\u003e ({ ...e38, start: { ...e38.start }, end: { ...e38.end } })) }), r3 = yz(n3, e37, fz(t4[0])));\n }\n }\n return n3;\n })(n2, this.nodeWithPortPoints);\n }\n};\nfunction vz(e35, t2, n2, o3, i3) {\n const r3 = n2 - t2, s2 = i3 - o3, a3 = 0.000001;\n if (Math.abs(e35.y - i3) \u003c a3)\n return e35.x - t2;\n if (Math.abs(e35.x - n2) \u003c a3)\n return r3 + (i3 - e35.y);\n if (Math.abs(e35.y - o3) \u003c a3)\n return r3 + s2 + (n2 - e35.x);\n if (Math.abs(e35.x - t2) \u003c a3)\n return 2 * r3 + s2 + (e35.y - o3);\n const c3 = Math.abs(e35.y - i3), l3 = Math.abs(e35.x - n2), h2 = Math.abs(e35.y - o3), d2 = Math.abs(e35.x - t2), u2 = Math.min(c3, l3, h2, d2);\n return u2 === c3 ? Math.max(0, Math.min(r3, e35.x - t2)) : u2 === l3 ? r3 + Math.max(0, Math.min(s2, i3 - e35.y)) : u2 === h2 ? r3 + s2 + Math.max(0, Math.min(r3, n2 - e35.x)) : 2 * r3 + s2 + Math.max(0, Math.min(s2, e35.y - o3));\n}\nfunction Iz(e35, t2, n2 = 0.000001) {\n return Math.abs(e35 - t2) \u003c n2;\n}\nfunction Sz(e35) {\n if (e35.length \u003c 2)\n return 0;\n const t2 = e35.map(([e36, t3]) =\u003e e36 \u003c t3 ? [e36, t3] : [t3, e36]);\n let n2 = 0;\n for (let e36 = 0;e36 \u003c t2.length; e36++) {\n const [o3, i3] = t2[e36];\n for (let r3 = e36 + 1;r3 \u003c t2.length; r3++) {\n const [e37, s2] = t2[r3];\n Iz(o3, e37) || Iz(o3, s2) || Iz(i3, e37) || Iz(i3, s2) || (o3 \u003c e37 \u0026\u0026 e37 \u003c i3 \u0026\u0026 i3 \u003c s2 || e37 \u003c o3 \u0026\u0026 o3 \u003c s2 \u0026\u0026 s2 \u003c i3) \u0026\u0026 n2++;\n }\n }\n return n2;\n}\nvar Cz = (e35) =\u003e {\n const t2 = e35.center.x - e35.width / 2, n2 = e35.center.x + e35.width / 2, o3 = e35.center.y - e35.height / 2, i3 = e35.center.y + e35.height / 2, r3 = new Map;\n for (const t3 of e35.portPoints) {\n const e36 = r3.get(t3.connectionName) ?? [];\n e36.some((e37) =\u003e e37.x === t3.x \u0026\u0026 e37.y === t3.y \u0026\u0026 e37.z === t3.z) || e36.push({ x: t3.x, y: t3.y, z: t3.z }), r3.set(t3.connectionName, e36);\n }\n const s2 = new Map, a3 = [];\n let c3 = 0;\n for (const [e36, l4] of r3) {\n if (l4.length \u003c 2)\n continue;\n const e37 = l4[0], r4 = l4[1], h2 = vz(e37, t2, n2, o3, i3), d2 = vz(r4, t2, n2, o3, i3);\n if (e37.z === r4.z) {\n const t3 = e37.z, n3 = s2.get(t3) ?? [];\n n3.push([h2, d2]), s2.set(t3, n3);\n } else\n c3++, a3.push([h2, d2]);\n }\n let l3 = 0;\n for (const [e36, t3] of s2)\n l3 += Sz(t3);\n return { numSameLayerCrossings: l3, numEntryExitLayerChanges: c3, numTransitionPairCrossings: Sz(a3) };\n};\nvar Pz = (e35) =\u003e e35.availableZ?.length ? [...new Set(e35.availableZ)].sort((e36, t2) =\u003e e36 - t2) : [...new Set(e35.portPoints.map((e36) =\u003e e36.z ?? 0))].sort((e36, t2) =\u003e e36 - t2);\nvar Mz = (e35) =\u003e Pz(e35).length === 1 \u0026\u0026 Cz(e35).numSameLayerCrossings \u003e 0;\nvar wz = (e35, t2, n2) =\u003e {\n const o3 = new Map, [i3] = Pz(e35);\n for (const t3 of e35.portPoints)\n o3.set(t3.connectionName, [...o3.get(t3.connectionName) ?? [], t3]);\n return Array.from(o3.entries()).flatMap(([o4, r3]) =\u003e {\n if (r3.length \u003c 2)\n return [];\n const s2 = r3[0], a3 = r3[r3.length - 1];\n return [{ connectionName: o4, rootConnectionName: s2.rootConnectionName, regionId: e35.capacityMeshNodeId, traceThickness: t2, viaDiameter: n2, route: [{ x: s2.x, y: s2.y, z: i3 ?? s2.z ?? 0 }, { x: a3.x, y: a3.y, z: i3 ?? a3.z ?? 0 }], vias: [] }];\n });\n};\nvar Nz = wz;\nvar Rz = (e35, t2, n2) =\u003e ({ ...e35, x: t2.x + (e35.x - t2.x) * n2, y: t2.y + (e35.y - t2.y) * n2 });\nvar Tz = (e35, t2, n2) =\u003e Rz(e35, t2, n2);\nvar Ez = [\"#dc2626\", \"#2563eb\", \"#16a34a\", \"#ca8a04\", \"#9333ea\", \"#0891b2\"];\nvar Az = (e35, t2, n2 = []) =\u003e [e35, t2 ? `rootConnectionName: ${t2}` : undefined, ...n2].filter(Boolean).join(`\n`);\nvar Oz = class extends ni {\n getSolverName() {\n return \"GrowShrinkHighDensityIntraNodeSolver\";\n }\n constructorParams;\n nodeWithPortPoints;\n solvedRoutes = [];\n failedSolvers = [];\n activeSubSolver = null;\n winningSolver;\n scaleFactor = 1;\n growthAttempts = 0;\n maxGrowthAttempts;\n minimumGrowthAttempts;\n constructor(e35) {\n super(), this.constructorParams = e35, this.nodeWithPortPoints = e35.nodeWithPortPoints;\n const t2 = Math.min(this.nodeWithPortPoints.width, this.nodeWithPortPoints.height), n2 = t2 \u003e 0 ? Math.max(0, Math.ceil(Math.log2((e35.viaDiameter ?? 0.3) / t2))) : 0;\n let o3 = Number.POSITIVE_INFINITY;\n const i3 = this.nodeWithPortPoints.portPoints;\n for (let e36 = 0;e36 \u003c i3.length; e36++)\n for (let t3 = e36 + 1;t3 \u003c i3.length; t3++) {\n const n3 = i3[e36], r4 = i3[t3];\n if (n3.z !== r4.z || (n3.rootConnectionName ?? n3.connectionName) === (r4.rootConnectionName ?? r4.connectionName))\n continue;\n const s3 = Math.hypot(n3.x - r4.x, n3.y - r4.y);\n s3 \u003e 0.000000001 \u0026\u0026 (o3 = Math.min(o3, s3));\n }\n const r3 = Math.max(0, Math.ceil(Math.log2((e35.traceWidth ?? 0.15) / o3))), s2 = Math.max(n2, r3);\n if (this.maxGrowthAttempts = e35.maxGrowthAttempts ?? 3 + s2, this.minimumGrowthAttempts = Math.min(e35.maxGrowthAttempts ?? 3 + n2, Math.max(n2, 0, r3 - 1)), this.MAX_ITERATIONS = 20000000 * (e35.effort ?? 1) * (this.maxGrowthAttempts + 1), Mz(this.nodeWithPortPoints)) {\n if (!e35.fallbackToInvalidGeometryOnFailure)\n return this.failed = true, this.progress = 1, void (this.error = \"GrowShrinkHighDensityIntraNodeSolver cannot route an impossible single-layer crossing\");\n this.solvedRoutes = Nz(this.nodeWithPortPoints, e35.traceWidth ?? 0.15, e35.viaDiameter ?? 0.3), this.solved = true, this.progress = 1, this.stats = { invalidGeometryFallback: true, reason: \"single-layer node has same-layer crossings\" };\n }\n }\n getConstructorParams() {\n return this.constructorParams;\n }\n createActiveSubSolver() {\n const { growShrinkSolutionValidator: e35, ...t2 } = this.constructorParams;\n var n2, o3;\n this.activeSubSolver = new xz({ ...t2, priorityCoordinateScale: (t2.priorityCoordinateScale ?? 1) * this.scaleFactor, enableNegotiatedSearch: this.scaleFactor === 1 \u0026\u0026 (t2.enableNegotiatedSearch ?? true), nodeWithPortPoints: (n2 = this.nodeWithPortPoints, o3 = this.scaleFactor, { ...n2, width: n2.width * o3, height: n2.height * o3, portPoints: n2.portPoints.map((e36) =\u003e Tz(e36, n2.center, o3)), portPointsInPairs: n2.portPointsInPairs?.map(([e36, t3]) =\u003e [Tz(e36, n2.center, o3), Tz(t3, n2.center, o3)]) }) }), this.constructorParams.maxInnerIterationsPerGrowthAttempt \u0026\u0026 (this.activeSubSolver.MAX_ITERATIONS = this.constructorParams.maxInnerIterationsPerGrowthAttempt);\n }\n acceptSolution(e35) {\n const t2 = this.scaleFactor === 1 ? e35.solvedRoutes : e35.solvedRoutes.map((e36) =\u003e ((e37, t3, n2) =\u003e ({ ...e37, route: e37.route.map((e38) =\u003e Rz(e38, t3, n2)), vias: e37.vias.map((e38) =\u003e Rz(e38, t3, n2)), jumpers: e37.jumpers?.map((e38) =\u003e ({ ...e38, start: Rz(e38.start, t3, n2), end: Rz(e38.end, t3, n2) })) }))(e36, this.nodeWithPortPoints.center, 1 / this.scaleFactor));\n return this.constructorParams.growShrinkSolutionValidator \u0026\u0026 !this.constructorParams.growShrinkSolutionValidator(t2) ? (e35.solved = false, e35.failed = true, e35.error = \"High-density scale solution rejected by validator\", false) : (this.winningSolver = e35, this.error = null, this.solvedRoutes = t2, this.solved = true, this.failed = false, true);\n }\n computeProgress() {\n return Math.min(0.99, (this.growthAttempts + (this.activeSubSolver?.progress ?? 0)) / (this.maxGrowthAttempts + 1));\n }\n _step() {\n if (this.activeSubSolver || this.createActiveSubSolver(), this.activeSubSolver.step(), this.activeSubSolver.solved \u0026\u0026 this.acceptSolution(this.activeSubSolver))\n this.activeSubSolver = null;\n else if (this.activeSubSolver.failed) {\n if (this.failedSolvers.push(this.activeSubSolver), this.error = this.activeSubSolver.error, this.activeSubSolver = null, this.growthAttempts \u003e= this.maxGrowthAttempts)\n return this.constructorParams.fallbackToInvalidGeometryOnFailure ? (this.solvedRoutes = wz(this.nodeWithPortPoints, this.constructorParams.traceWidth ?? 0.15, this.constructorParams.viaDiameter ?? 0.3), this.solved = true, this.failed = false, this.progress = 1, this.stats = { ...this.stats, invalidGeometryFallback: true, reason: \"growth attempts exhausted\", lastError: this.error }, void (this.error = null)) : (this.failed = true, void (this.error = `GrowShrinkHighDensityIntraNodeSolver failed after resizing to ${this.scaleFactor}x. Last error: ${this.error}`));\n this.growthAttempts = Math.max(this.growthAttempts + 1, this.minimumGrowthAttempts), this.scaleFactor = 2 ** this.growthAttempts;\n }\n }\n visualize() {\n const e35 = this.activeSubSolver?.visualize() ?? this.winningSolver?.visualize();\n return e35 || (this.solvedRoutes.length \u003e 0 ? { title: this.stats.invalidGeometryFallback ? \"Invalid same-layer crossing geometry\" : \"Grow/shrink high density routes\", lines: this.solvedRoutes.flatMap((e36, t2) =\u003e e36.route.slice(0, -1).map((n2, o3) =\u003e ({ points: [n2, e36.route[o3 + 1]], strokeColor: Ez[t2 % Ez.length], strokeWidth: e36.traceThickness, layer: `z${n2.z}`, label: Az(e36.connectionName, e36.rootConnectionName, [`z${n2.z}`, this.stats.invalidGeometryFallback ? \"invalid fallback route\" : undefined].filter(Boolean)) }))), points: this.nodeWithPortPoints.portPoints.map((e36) =\u003e ({ x: e36.x, y: e36.y, color: Ez[Math.max(0, this.solvedRoutes.findIndex((t2) =\u003e t2.connectionName === e36.connectionName)) % Ez.length], label: Az(e36.connectionName, e36.rootConnectionName, [`z${e36.z}`]) })), rects: [{ center: this.nodeWithPortPoints.center, width: this.nodeWithPortPoints.width, height: this.nodeWithPortPoints.height, fill: this.stats.invalidGeometryFallback ? \"rgba(245, 158, 11, 0.12)\" : \"rgba(14, 165, 233, 0.08)\", stroke: this.stats.invalidGeometryFallback ? \"rgba(217, 119, 6, 0.8)\" : \"rgba(14, 165, 233, 0.55)\", label: [this.nodeWithPortPoints.capacityMeshNodeId, this.stats.reason].filter(Boolean).join(`\n`) }], circles: [] } : e35 ?? { lines: [], points: [], rects: [], circles: [] });\n }\n};\nvar kz = (e35, t2, n2 = []) =\u003e [e35, t2 ? `rootConnectionName: ${t2}` : undefined, ...n2].filter(Boolean).join(`\n`);\nvar Dz = class extends ni {\n getSolverName() {\n return \"HighDensitySolver\";\n }\n unsolvedNodePortPoints;\n routes;\n colorMap;\n defaultViaDiameter = 0.3;\n defaultTraceThickness = 0.15;\n viaDiameter;\n traceWidth;\n obstacleMargin;\n effort;\n obstacles;\n layerCount;\n useGrowShrinkHighDensityIntraNodeSolver;\n enableNegotiatedSearch;\n gridSearchSegmentWork;\n gridSearchWorkScale;\n rejectOverlappingTerminals;\n boardGeometry;\n preserveTerminalPcbPortIds;\n growShrinkMaxInnerIterationsPerGrowthAttempt;\n growShrinkFallbackToInvalidGeometryOnFailure;\n growShrinkSolutionValidator;\n captureSearchDebug;\n benchmarkDiagnosticCounters;\n priorityDagOptions;\n failedSolvers;\n activeSubSolver = null;\n connMap;\n nodePfById;\n nodeSolveMetadataById;\n constructor({ nodePortPoints: e35, colorMap: t2, connMap: n2, viaDiameter: o3, traceWidth: i3, obstacleMargin: r3, effort: s2, nodePfById: a3, obstacles: c3, layerCount: l3, useGrowShrinkHighDensityIntraNodeSolver: h2, enableNegotiatedSearch: d2 = false, gridSearchSegmentWork: u2 = 1e4, gridSearchWorkScale: p3 = 1, rejectOverlappingTerminals: m2 = false, boardGeometry: g2, preserveTerminalPcbPortIds: f2, growShrinkMaxInnerIterationsPerGrowthAttempt: _2, growShrinkFallbackToInvalidGeometryOnFailure: y2, growShrinkSolutionValidator: b2, captureSearchDebug: x2, priorityDagSearch: v2 = false, priorityDiagnostics: I2, viaHoleDiameter: S2, minViaHoleEdgeToViaHoleEdgeClearance: C, allowBlindAndBuriedVias: P }) {\n super(), this.unsolvedNodePortPoints = e35, this.colorMap = t2 ?? {}, this.connMap = n2, this.routes = [], this.failedSolvers = [], this.effort = s2 ?? 1, this.viaDiameter = o3 ?? this.defaultViaDiameter, this.traceWidth = i3 ?? this.defaultTraceThickness, this.obstacleMargin = r3 ?? 0.15, this.obstacles = c3 ?? [], this.layerCount = l3 ?? 2, this.enableNegotiatedSearch = d2, this.gridSearchSegmentWork = u2, this.gridSearchWorkScale = p3, this.rejectOverlappingTerminals = m2, this.boardGeometry = g2, this.useGrowShrinkHighDensityIntraNodeSolver = h2 ?? false, this.preserveTerminalPcbPortIds = f2 ?? false, this.growShrinkMaxInnerIterationsPerGrowthAttempt = _2, this.growShrinkFallbackToInvalidGeometryOnFailure = y2 ?? false, this.growShrinkSolutionValidator = b2, this.captureSearchDebug = x2 ?? true, this.benchmarkDiagnosticCounters = I2 ?? {}, this.priorityDagOptions = { priorityDagSearch: v2, viaHoleDiameter: S2, minViaHoleEdgeToViaHoleEdgeClearance: C, allowBlindAndBuriedVias: P }, this.MAX_ITERATIONS = 1e7 * this.effort * (this.useGrowShrinkHighDensityIntraNodeSolver ? 4 : 1), this.nodePfById = a3 instanceof Map ? new Map(a3) : new Map(Object.entries(a3 ?? {})), this.nodeSolveMetadataById = new Map, this.stats = { solverNodeCount: {}, difficultNodePfs: {}, highDensityResizeCount: 0 };\n }\n getSolvedNodeSolverType(e35) {\n return e35 instanceof Oz \u0026\u0026 e35.winningSolver ? this.getSolvedNodeSolverType(e35.winningSolver) : e35 instanceof xz \u0026\u0026 e35.winningSolver ? this.getConcreteSolverTypeName(e35.winningSolver) : this.getConcreteSolverTypeName(e35);\n }\n recordNodeSolveMetadata(e35, t2) {\n const n2 = e35.nodeWithPortPoints, o3 = this.nodePfById.get(n2.capacityMeshNodeId) ?? null;\n this.nodeSolveMetadataById.set(n2.capacityMeshNodeId, { node: n2, status: t2, solverType: this.getSolvedNodeSolverType(e35), iterations: e35.iterations, routeCount: e35.solvedRoutes.length, nodePf: o3, error: e35.error ?? undefined });\n }\n createNodeMarkerLabel(e35, t2) {\n return [\"hd_node_marker\", `node: ${e35}`, `status: ${t2.status}`, `solver: ${t2.solverType}`, `iterations: ${t2.iterations}`, `routes: ${t2.routeCount}`, `nodePf: ${t2.nodePf ?? \"n/a\"}`, `portPoints: ${t2.node.portPoints.length}`, ...t2.error ? [`error: ${t2.error}`] : []].join(`\n`);\n }\n getConcreteSolverTypeName(e35) {\n if (e35 instanceof jr) {\n const t2 = this.getIntraNodeStrategyName(e35.hyperParameters);\n return e35.cacheHit ? `${t2} [cached]` : t2;\n }\n return e35 instanceof Lr ? this.getIntraNodeStrategyName(e35.hyperParameters) : e35.getSolverName();\n }\n getIntraNodeStrategyName(e35) {\n return e35?.PRIORITY_DAG_FAMILY_SIZE ? \"PriorityDagIntraNodeSolver\" : e35?.MULTI_HEAD_POLYLINE_SOLVER ? \"MultiHeadPolyLineIntraNodeSolver3\" : e35?.SINGLE_LAYER_NO_DIFFERENT_ROOT_INTERSECTIONS ? \"SingleLayerNoDifferentRootIntersectionsIntraNodeSolver\" : e35?.CLOSED_FORM_SINGLE_TRANSITION ? \"SingleTransitionIntraNodeSolver\" : e35?.CLOSED_FORM_TWO_TRACE_SAME_LAYER ? \"TwoCrossingRoutesHighDensitySolver\" : e35?.CLOSED_FORM_TWO_TRACE_TRANSITION_CROSSING ? \"SingleTransitionCrossingRouteSolver\" : e35?.HIGH_DENSITY_A01 ? \"HighDensitySolverA01\" : e35?.HIGH_DENSITY_A03 ? \"HighDensitySolverA03\" : \"SingleHighDensityRouteSolver6_VertHorzLayer_FutureCost\";\n }\n recordSolvedNodeStats(e35, t2) {\n const n2 = this.getSolvedNodeSolverType(e35), o3 = this.stats.solverNodeCount, i3 = this.stats.difficultNodePfs;\n o3[n2] = (o3[n2] ?? 0) + 1;\n const r3 = this.nodePfById.get(t2.capacityMeshNodeId) ?? null;\n r3 !== null \u0026\u0026 r3 \u003e 0.05 \u0026\u0026 (i3[n2] || (i3[n2] = []), i3[n2].push(r3));\n }\n recordResizeStats(e35) {\n e35 instanceof Oz \u0026\u0026 (this.stats.highDensityResizeCount = (this.stats.highDensityResizeCount ?? 0) + e35.growthAttempts);\n }\n getSolvedRoutesWithTerminalPcbPortIds(e35) {\n const t2 = e35.nodeWithPortPoints.portPoints.filter((e36) =\u003e e36.pcb_port_id !== undefined);\n if (t2.length === 0)\n return e35.solvedRoutes;\n const n2 = (e36, n3) =\u003e {\n const o3 = t2.filter((t3) =\u003e t3.connectionName === e36.connectionName \u0026\u0026 t3.x === n3.x \u0026\u0026 t3.y === n3.y \u0026\u0026 t3.z === n3.z);\n if (o3.length \u003e 1)\n throw new Error(`HighDensitySolver found multiple PCB terminals at an endpoint of \"${e36.connectionName}\"`);\n const i3 = o3[0];\n if (i3?.pcb_port_id)\n return i3.pcb_port_id;\n };\n return e35.solvedRoutes.map((e36) =\u003e ({ ...e36, startPcbPortId: e36.route[0] ? n2(e36, e36.route[0]) : undefined, endPcbPortId: e36.route.length \u003e 1 ? n2(e36, e36.route[e36.route.length - 1]) : undefined }));\n }\n _step() {\n if (this.updateCacheStats(), this.activeSubSolver)\n return this.activeSubSolver.step(), this.activeSubSolver.solved ? (this.routes.push(...this.preserveTerminalPcbPortIds ? this.getSolvedRoutesWithTerminalPcbPortIds(this.activeSubSolver) : this.activeSubSolver.solvedRoutes), this.recordNodeSolveMetadata(this.activeSubSolver, \"solved\"), this.recordSolvedNodeStats(this.activeSubSolver, this.activeSubSolver.nodeWithPortPoints), this.recordResizeStats(this.activeSubSolver), this.activeSubSolver = null) : this.activeSubSolver.failed \u0026\u0026 (this.recordNodeSolveMetadata(this.activeSubSolver, \"failed\"), this.recordResizeStats(this.activeSubSolver), this.failedSolvers.push(this.activeSubSolver), this.activeSubSolver = null), void this.updateCacheStats();\n if (this.unsolvedNodePortPoints.length === 0)\n return this.failedSolvers.length \u003e 0 ? (this.solved = false, this.failed = true, this.error = `Failed to solve ${this.failedSolvers.length} nodes, ${this.failedSolvers.slice(0, 5).map((e36) =\u003e e36.nodeWithPortPoints.capacityMeshNodeId)}. err0: ${this.failedSolvers[0].error}.`, void this.updateCacheStats()) : (this.solved = true, void this.updateCacheStats());\n const e35 = { nodeWithPortPoints: this.unsolvedNodePortPoints.pop(), ...this.priorityDagOptions, priorityDiagnostics: this.benchmarkDiagnosticCounters, enableNegotiatedSearch: this.enableNegotiatedSearch, gridSearchSegmentWork: this.gridSearchSegmentWork, gridSearchWorkScale: this.gridSearchWorkScale, rejectOverlappingTerminals: this.rejectOverlappingTerminals, boardGeometry: this.boardGeometry, colorMap: this.colorMap, connMap: this.connMap, viaDiameter: this.viaDiameter, traceWidth: this.traceWidth, obstacleMargin: this.obstacleMargin, effort: this.effort, obstacles: this.obstacles, layerCount: this.layerCount, maxInnerIterationsPerGrowthAttempt: this.growShrinkMaxInnerIterationsPerGrowthAttempt, fallbackToInvalidGeometryOnFailure: this.growShrinkFallbackToInvalidGeometryOnFailure, growShrinkSolutionValidator: this.growShrinkSolutionValidator, captureSearchDebug: this.captureSearchDebug };\n this.activeSubSolver = this.useGrowShrinkHighDensityIntraNodeSolver ? new Oz(e35) : new xz(e35), this.updateCacheStats();\n }\n updateCacheStats() {\n const e35 = no();\n this.stats.intraNodeCacheHits = e35.cacheHits, this.stats.intraNodeCacheMisses = e35.cacheMisses;\n }\n visualize() {\n let e35 = { lines: [], points: [], rects: [], circles: [] };\n for (const t2 of this.routes) {\n const n2 = mi(t2.route, t2.connectionName, this.colorMap[t2.connectionName]);\n for (const o3 of n2)\n e35.lines.push({ points: o3.points, label: kz(t2.connectionName, t2.rootConnectionName), strokeColor: o3.z === 0 ? o3.color : Ao(o3.color, 0.5), layer: `z${o3.z}`, strokeWidth: t2.traceThickness, strokeDash: o3.z !== 0 ? [0.1, 0.3] : undefined });\n for (const n3 of t2.vias)\n e35.circles.push({ center: n3, layer: \"z0,1\", radius: t2.viaDiameter / 2, fill: this.colorMap[t2.connectionName], label: kz(t2.connectionName, t2.rootConnectionName, [\"via\"]) });\n }\n if (this.solved || this.failed)\n for (const [t2, n2] of this.nodeSolveMetadataById) {\n const o3 = n2.node.center.x - n2.node.width / 2, i3 = n2.node.center.x + n2.node.width / 2, r3 = n2.node.center.y - n2.node.height / 2, s2 = n2.node.center.y + n2.node.height / 2, a3 = this.createNodeMarkerLabel(t2, n2), c3 = n2.status === \"solved\" ? \"blue\" : \"red\";\n if (e35.lines.push({ points: [{ x: o3, y: r3 }, { x: i3, y: r3 }], layer: \"hd_node_boundaries\", strokeColor: c3, strokeDash: \"6, 4\", strokeWidth: 0.03, label: a3 }, { points: [{ x: i3, y: r3 }, { x: i3, y: s2 }], layer: \"hd_node_boundaries\", strokeColor: c3, strokeDash: \"6, 4\", strokeWidth: 0.03, label: a3 }, { points: [{ x: i3, y: s2 }, { x: o3, y: s2 }], layer: \"hd_node_boundaries\", strokeColor: c3, strokeDash: \"6, 4\", strokeWidth: 0.03, label: a3 }, { points: [{ x: o3, y: s2 }, { x: o3, y: r3 }], layer: \"hd_node_boundaries\", strokeColor: c3, strokeDash: \"6, 4\", strokeWidth: 0.03, label: a3 }), n2.status === \"solved\")\n e35.points.push({ x: n2.node.center.x, y: n2.node.center.y, color: c3, layer: \"hd_node_markers\", label: a3 });\n else {\n e35.lines.push({ points: [{ x: 0, y: 0 }, { x: n2.node.center.x, y: n2.node.center.y }], layer: \"hd_failed_node_guides\", strokeColor: \"red\", strokeDash: \"8, 6\", strokeWidth: 0.05, label: a3 });\n const t3 = Math.max(0.1 * n2.node.width, 0.12), o4 = Math.max(0.1 * n2.node.height, 0.12);\n e35.rects.push({ center: n2.node.center, layer: \"hd_node_markers\", width: t3, height: o4, fill: \"red\", label: a3 });\n }\n }\n return this.activeSubSolver \u0026\u0026 (e35 = pi(e35, this.activeSubSolver.visualize())), e35;\n }\n};\nfunction Lz(e35, t2) {\n const n2 = [], o3 = t2.filter((e36) =\u003e e36._containsTarget), i3 = new Map;\n for (const r3 of e35.connections) {\n const e36 = [];\n for (const n3 of r3.pointsToConnect) {\n let i4 = t2[0], r4 = Number.MAX_VALUE;\n for (const e37 of o3) {\n const t3 = Math.sqrt((e37.center.x - n3.x) ** 2 + (e37.center.y - n3.y) ** 2);\n t3 \u003c r4 \u0026\u0026 (r4 = t3, i4 = e37);\n }\n e36.push(i4);\n }\n if (e36.length \u003c 2)\n throw new Error(`Not enough nodes for connection \"${r3.name}\", only ${e36.length} found`);\n i3.set(r3.name, e36.map((e37) =\u003e e37.capacityMeshNodeId)), n2.push({ connection: r3, nodeIds: [e36[0].capacityMeshNodeId, e36[e36.length - 1].capacityMeshNodeId], straightLineDistance: me(e36[0].center, e36[e36.length - 1].center) });\n }\n return { unshuffledConnectionsWithResults: n2, connectionNameToGoalNodeIds: i3 };\n}\nfunction zz(e35, t2) {\n const n2 = new Map(t2.map((e36) =\u003e [e36.capacityMeshNodeId, e36])), o3 = t2.map((e36) =\u003e (e36.width + e36.height) / 2).filter((e36) =\u003e Number.isFinite(e36) \u0026\u0026 e36 \u003e 0), i3 = o3.length \u003e 0 ? o3.reduce((e36, t3) =\u003e e36 + t3, 0) / o3.length : 1, r3 = t2.filter((e36) =\u003e e36._offBoardConnectionId), s2 = new Map, a3 = new Map, c3 = new Map;\n for (const e36 of t2)\n a3.set(e36.capacityMeshNodeId, []), c3.set(e36.capacityMeshNodeId, []);\n for (const e36 of t2)\n for (const t3 of e36.portPoints) {\n s2.set(t3.portPointId, t3);\n for (const e37 of t3.connectionNodeIds) {\n const n3 = a3.get(e37);\n n3 \u0026\u0026 !n3.some((e38) =\u003e e38.portPointId === t3.portPointId) \u0026\u0026 n3.push(t3);\n }\n }\n const { unshuffledConnectionsWithResults: l3, connectionNameToGoalNodeIds: h2 } = Lz(e35, t2);\n return { nodeMap: n2, avgNodePitch: i3, offBoardNodes: r3, portPointMap: s2, nodePortPointsMap: a3, nodeAssignedPortPoints: c3, unshuffledConnectionsWithResults: l3, connectionNameToGoalNodeIds: h2 };\n}\nvar Bz = (e35, t2 = 1, n2 = {}) =\u003e {\n const o3 = n2.viaDiameter ?? 0.3, i3 = \"width\" in e35 ? e35.width : e35, r3 = n2.obstacleMargin ?? 0.2, s2 = \"height\" in e35 \u0026\u0026 typeof e35.height == \"number\" ? e35.height : i3;\n if (!Number.isFinite(i3) || !Number.isFinite(s2))\n return 0;\n if (i3 \u003c= 0 || s2 \u003c= 0)\n return 0;\n const a3 = Math.min(i3, s2) / (o3 + r3), c3 = (Math.sqrt(i3 * s2) * Math.min(1.2, Math.max(0.85, a3 ** 0.05)) / (o3 / 2 + r3) / 2) ** 1.1 * t2;\n return Number.isFinite(c3) ? e35.availableZ?.length === 1 \u0026\u0026 c3 \u003e 1 ? 1 : c3 : 0;\n};\nvar Fz = (e35, t2 = 0.5, n2 = 16) =\u003e {\n let o3 = 0, i3 = e35;\n for (;o3 \u003c n2; ) {\n if (Bz({ width: i3 }) \u003c= t2)\n break;\n i3 /= 2, o3++;\n }\n return Math.max(1, o3);\n};\nvar jz = (e35, t2, n2, o3) =\u003e {\n if (e35?._containsTarget)\n return 0;\n if ((e35.availableZ?.length ?? 2) === 1 \u0026\u0026 (t2 \u003e 0 || n2 \u003e 0 || o3 \u003e 0))\n return 1;\n const i3 = ((0.82 * t2 + 0.41 * n2 + 0.2 * o3) / 2) ** 1.1;\n if (!Number.isFinite(i3))\n return 1;\n const r3 = Bz(e35);\n if (!Number.isFinite(r3) || r3 \u003c= 0)\n return i3 \u003e 0 ? 1 : 0;\n const s2 = i3 / r3;\n if (Number.isNaN(s2))\n throw new Error(\"calculateNodeProbabilityOfFailure returned NaN\");\n return Number.isFinite(s2) ? s2 : i3 \u003e 0 ? 1 : 0;\n};\nfunction $z(e35, t2, n2) {\n let o3 = 0;\n const i3 = n2?.NODE_MAX_PF ?? 0.99999;\n for (const n3 of e35) {\n const e36 = t2.get(n3.capacityMeshNodeId);\n if (!e36)\n continue;\n if (e36._containsTarget)\n continue;\n const r3 = Cz(n3), s2 = Math.min(jz(e36, r3.numSameLayerCrossings, r3.numEntryExitLayerChanges, r3.numTransitionPairCrossings), i3);\n o3 += Math.log(1 - s2);\n }\n return o3;\n}\nfunction Yz(e35, t2) {\n if (t2._containsTarget)\n return 0;\n const n2 = Cz(e35);\n return jz(t2, n2.numSameLayerCrossings, n2.numEntryExitLayerChanges, n2.numTransitionPairCrossings);\n}\nfunction Xz(e35, t2, n2, o3, i3) {\n const r3 = n2 - t2, s2 = i3 - o3, a3 = 0.000001;\n if (Math.abs(e35.y - i3) \u003c a3)\n return e35.x - t2;\n if (Math.abs(e35.x - n2) \u003c a3)\n return r3 + (i3 - e35.y);\n if (Math.abs(e35.y - o3) \u003c a3)\n return r3 + s2 + (n2 - e35.x);\n if (Math.abs(e35.x - t2) \u003c a3)\n return 2 * r3 + s2 + (e35.y - o3);\n const c3 = Math.abs(e35.y - i3), l3 = Math.abs(e35.x - n2), h2 = Math.abs(e35.y - o3), d2 = Math.abs(e35.x - t2), u2 = Math.min(c3, l3, h2, d2);\n return u2 === c3 ? Math.max(0, Math.min(r3, e35.x - t2)) : u2 === l3 ? r3 + Math.max(0, Math.min(s2, i3 - e35.y)) : u2 === h2 ? r3 + s2 + Math.max(0, Math.min(r3, n2 - e35.x)) : 2 * r3 + s2 + Math.max(0, Math.min(s2, e35.y - o3));\n}\nvar Hz = 1.6 * 3.2;\nvar Vz = (e35, t2) =\u003e {\n const n2 = Math.ceil(t2 / 2), o3 = Math.min(e35.width, e35.height), i3 = Math.max(e35.width, e35.height), r3 = (Math.floor(o3 / 1.6) + 0.1) * (Math.floor(i3 / 3.2) + 0.1) / Hz;\n return Math.min(1, n2 / r3);\n};\nfunction Wz(e35, t2, n2, o3) {\n const i3 = t2.x - n2 / 2, r3 = t2.x + n2 / 2, s2 = t2.y - o3 / 2, a3 = t2.y + o3 / 2, c3 = Math.abs(e35.y - a3), l3 = Math.abs(e35.x - r3), h2 = Math.abs(e35.y - s2), d2 = Math.abs(e35.x - i3), u2 = Math.min(c3, l3, h2, d2);\n return u2 \u003e 0.001 ? \"interior\" : u2 === c3 ? \"top\" : u2 === l3 ? \"right\" : u2 === h2 ? \"bottom\" : \"left\";\n}\nfunction Gz(e35, t2, n2, o3, i3) {\n const r3 = Wz(e35, n2, o3, i3), s2 = Wz(t2, n2, o3, i3);\n return r3 !== \"interior\" \u0026\u0026 r3 === s2;\n}\nfunction Uz(e35, t2, n2, o3, i3) {\n const r3 = Wz(e35, n2, o3, i3);\n let s2;\n if (r3 === \"top\" || r3 === \"bottom\") {\n const n3 = o3;\n s2 = Math.abs(t2.x - e35.x) / n3;\n } else {\n const n3 = i3;\n s2 = Math.abs(t2.y - e35.y) / n3;\n }\n s2 = Math.min(1, Math.max(0, s2));\n const a3 = (e35.x + t2.x) / 2, c3 = (e35.y + t2.y) / 2;\n return { x: a3 + (n2.x - a3) * s2, y: c3 + (n2.y - c3) * s2 };\n}\nfunction Zz(e35) {\n return \"computeNodePf\" in e35 \u0026\u0026 typeof e35.computeNodePf == \"function\";\n}\nfunction qz(e35) {\n const t2 = { lines: [], points: [], rects: [], circles: [] };\n for (const n3 of e35.inputNodes) {\n let o3 = 0, i3 = 0, r3 = { numSameLayerCrossings: 0, numEntryExitLayerChanges: 0, numTransitionPairCrossings: 0 }, s2 = 0;\n if (Zz(e35)) {\n o3 = e35.computeNodePf(n3), i3 = e35.nodeMemoryPfMap.get(n3.capacityMeshNodeId) ?? 0;\n const t3 = e35.buildNodeWithPortPointsForCrossing(n3);\n r3 = Cz(t3);\n const a4 = new Set, c4 = e35.nodeAssignedPortPoints.get(n3.capacityMeshNodeId) ?? [];\n for (const e36 of c4)\n e36.connectionName \u0026\u0026 a4.add(e36.connectionName);\n s2 = a4.size;\n } else {\n o3 = e35.nodePfMap.get(n3.capacityMeshNodeId) ?? 0;\n const t3 = e35.nodeAssignedPortPoints.get(n3.capacityMeshNodeId) ?? [], i4 = { capacityMeshNodeId: n3.capacityMeshNodeId, center: n3.center, width: n3.width, height: n3.height, portPoints: t3, availableZ: n3.availableZ };\n r3 = Cz(i4);\n const a4 = new Set;\n for (const e36 of t3)\n e36.connectionName \u0026\u0026 a4.add(e36.connectionName);\n s2 = a4.size;\n }\n const a3 = Math.min(255, Math.floor(512 * o3)), c3 = Math.max(0, 255 - Math.floor(512 * o3));\n let l3 = `rgba(${a3}, ${c3}, ${c3}, ${o3 \u003c 0.001 ? \"0.1\" : \"0.3\"})`;\n n3._containsObstacle \u0026\u0026 (l3 = \"rgba(255, 0, 0, 0.3)\"), n3._offBoardConnectedCapacityMeshNodeIds?.length \u0026\u0026 (l3 = \"rgba(255, 165, 0, 0.3)\"), t2.rects.push({ center: n3.center, width: n3.width - 0.2, height: n3.height - 0.2, layer: `z${n3.availableZ.join(\",\")}`, fill: l3, label: `${n3.capacityMeshNodeId}\npf: ${o3.toFixed(3)}, memPf: ${i3.toFixed(3)}\nC#: ${s2}\nxSame: ${r3.numSameLayerCrossings}, xLC: ${r3.numEntryExitLayerChanges}, xTransition: ${r3.numTransitionPairCrossings}\nobCmid: ${n3._offBoardConnectedCapacityMeshNodeIds?.join(\",\")}\nobs: ${n3._containsObstacle ? \"yes\" : \"no\"}` });\n }\n if (Zz(e35))\n for (const [n3, o3] of e35.portPointMap) {\n const i3 = e35.assignedPortPoints.get(n3), r3 = i3 ? e35.colorMap[i3.connectionName] ?? \"blue\" : \"rgba(150, 150, 150, 0.5)\";\n t2.circles.push({ center: { x: o3.x, y: o3.y }, radius: 0.05, fill: r3, layer: `z${o3.z}`, label: [n3, `conn: ${i3?.connectionName}`, `cd: ${o3.distToCentermostPortOnZ}`, `connects: ${o3.connectionNodeIds.join(\",\")}`, `rootConn: ${i3?.rootConnectionName}`].filter(Boolean).join(`\n`) });\n }\n const n2 = Zz(e35) ? e35.connectionsWithResults : e35.connectionResults;\n for (const o3 of n2) {\n if (!o3.path)\n continue;\n const n3 = o3.connection, i3 = e35.colorMap[n3.name] ?? \"blue\", r3 = [];\n for (const e36 of o3.path)\n r3.push({ x: e36.point.x, y: e36.point.y, z: e36.z, nodeId: e36.currentNodeId });\n for (let n4 = 0;n4 \u003c r3.length - 1; n4++) {\n const o4 = r3[n4], s2 = r3[n4 + 1], a3 = o4.z === s2.z, c3 = o4.z;\n let l3;\n l3 = a3 ? c3 === 0 ? undefined : \"10 5\" : \"3 3 10\";\n const h2 = o4.nodeId ? e35.nodeMap.get(o4.nodeId) : null;\n if (h2 \u0026\u0026 Gz(o4, s2, h2.center, h2.width, h2.height)) {\n const e36 = Uz(o4, s2, h2.center, h2.width, h2.height);\n t2.lines.push({ points: [{ x: o4.x, y: o4.y }, { x: e36.x, y: e36.y }], strokeColor: i3, strokeDash: l3 }), t2.lines.push({ points: [{ x: e36.x, y: e36.y }, { x: s2.x, y: s2.y }], strokeColor: i3, strokeDash: l3 });\n } else\n t2.lines.push({ points: [{ x: o4.x, y: o4.y }, { x: s2.x, y: s2.y }], strokeColor: i3, strokeDash: l3 });\n }\n }\n if (Zz(e35) \u0026\u0026 !e35.solved \u0026\u0026 e35.candidates \u0026\u0026 e35.candidates.length \u003e 0) {\n const n3 = e35.currentConnection, o3 = n3 ? e35.colorMap[n3.connection.name] ?? \"blue\" : \"blue\";\n if (n3) {\n const [i4, r3] = n3.nodeIds, s2 = e35.nodeMap.get(i4), a3 = e35.nodeMap.get(r3), c3 = n3.connection.pointsToConnect[0], l3 = n3.connection.pointsToConnect[n3.connection.pointsToConnect.length - 1];\n if (s2 \u0026\u0026 a3) {\n const e36 = c3 ? { x: c3.x, y: c3.y } : s2.center, i5 = l3 ? { x: l3.x, y: l3.y } : a3.center;\n t2.lines.push({ points: [e36, i5], strokeColor: Ao(o3, 0.5), strokeDash: \"5 5\" }), t2.points.push({ x: e36.x, y: e36.y, color: o3, label: [`Start: ${n3.connection.name}`, `${n3.connection.__rootConnectionNames?.[0]}`].join(`\n`) }), t2.points.push({ x: i5.x, y: i5.y, color: o3, label: [`End: ${n3.connection.name}`, `${n3.connection.__rootConnectionNames?.[0]}`].join(`\n`) }), t2.circles.push({ center: i5, radius: 0.08, stroke: o3, label: `Goal: ${n3.connection.name}` });\n }\n }\n const i3 = [...e35.candidates].sort((e36, t3) =\u003e e36.f - t3.f).slice(0, 1);\n for (const r3 of i3) {\n const i4 = [];\n let s2 = r3;\n for (;s2; )\n i4.unshift({ x: s2.point.x, y: s2.point.y, z: s2.z, lastMoveWasOffBoard: s2.lastMoveWasOffBoard, nodeId: s2.currentNodeId }), s2 = s2.prevCandidate;\n for (let n4 = 0;n4 \u003c i4.length - 1; n4++) {\n const r4 = i4[n4], s3 = i4[n4 + 1], a3 = r4.z === s3.z, c3 = r4.z;\n let l3;\n l3 = s3.lastMoveWasOffBoard ? \"2 2\" : a3 ? c3 === 0 ? undefined : \"10 5\" : \"3 3 10\";\n const h2 = r4.nodeId ? e35.nodeMap.get(r4.nodeId) : null, d2 = 0.02 * r4.z;\n if (h2 \u0026\u0026 Gz(r4, s3, h2.center, h2.width, h2.height)) {\n const e36 = Uz(r4, s3, h2.center, h2.width, h2.height);\n t2.lines.push({ points: [{ x: r4.x + d2, y: r4.y + d2 }, { x: e36.x + d2, y: e36.y + d2 }], strokeColor: Ao(o3, 0.25), strokeDash: l3 }), t2.lines.push({ points: [{ x: e36.x + d2, y: e36.y + d2 }, { x: s3.x + d2, y: s3.y + d2 }], strokeColor: Ao(o3, 0.25), strokeDash: l3 });\n } else\n t2.lines.push({ points: [{ x: r4.x + d2, y: r4.y + d2 }, { x: s3.x + d2, y: s3.y + d2 }], strokeColor: Ao(o3, 0.25), strokeDash: l3 });\n }\n if (i4.length \u003e= 1) {\n const s3 = i4[i4.length - 1];\n let a3 = 0, c3 = 0, l3 = 0, h2 = 0, d2 = 0, u2 = 0;\n const p3 = e35.nodeMap.get(r3.prevCandidate?.currentNodeId);\n if (p3 \u0026\u0026 r3.prevCandidate \u0026\u0026 r3.portPoint \u0026\u0026 n3) {\n const t3 = n3.connection.name, o4 = { x: r3.prevCandidate.point.x, y: r3.prevCandidate.point.y, z: r3.prevCandidate.z, connectionName: t3 }, i5 = { x: r3.portPoint.x, y: r3.portPoint.y, z: r3.portPoint.z, connectionName: t3 }, s4 = e35.buildNodeWithPortPointsForCrossing(p3, [o4, i5]), m3 = gs(s4);\n l3 = m3.numSameLayerCrossings, h2 = m3.numTransitionPairCrossings, d2 = m3.numEntryExitLayerChanges;\n const g3 = e35.capacityMeshNodeMap.get(p3.capacityMeshNodeId);\n g3 \u0026\u0026 (c3 = e35.JUMPER_PF_FN_ENABLED \u0026\u0026 p3.availableZ.length === 1 ? Vz(g3, l3) : jz(g3, l3, d2, h2), a3 = c3 ** 2 * e35.NODE_PF_FACTOR), u2 = r3.prevCandidate.g \u003e 0 ? r3.g - r3.prevCandidate.g : r3.g;\n }\n if (!n3)\n continue;\n const [m2, g2] = n3.nodeIds, f2 = e35.nodeMap.get(g2), _2 = f2 ? Math.sqrt((s3.x - f2.center.x) ** 2 + (s3.y - f2.center.y) ** 2) : 0, y2 = e35.avgNodePitch \u003e 0 ? _2 / e35.avgNodePitch : 0, b2 = y2 * e35.BASE_CANDIDATE_COST, x2 = e35.nodeMemoryPfMap.get(r3.currentNodeId) ?? 0, v2 = -Math.log(1 - x2) * e35.MEMORY_PF_FACTOR;\n t2.circles.push({ center: s3, radius: 0.03, fill: Ao(o3, 0.25), layer: `z${r3.z}`, label: [`f: ${r3.f.toFixed(2)}`, `g: ${r3.g.toFixed(2)} (nodeDelta: ${u2.toFixed(2)})`, `h: ${r3.h.toFixed(2)}`, ` dist: ${_2.toFixed(2)}`, ` estHops: ${y2.toFixed(1)}`, ` estStepCost: ${b2.toFixed(2)}`, ` memRiskCost: ${v2.toFixed(2)}`, `z: ${r3.z}`, `node: ${r3.currentNodeId}`, `Cost(Pf): ${a3.toFixed(3)}`, `Pf: ${c3.toFixed(3)}`, `xSame: ${l3}, xTrans: ${h2}, xLC: ${d2}`, `routeOffBoard=${e35.currentConnectionShouldRouteOffBoard}`, `offBoardTouched=${r3.hasTouchedOffBoardNode ?? false}`, `lastMoveWasOffBoard=${r3.lastMoveWasOffBoard ?? false}`].join(`\n`) });\n }\n }\n }\n return t2;\n}\nfunction Jz(e35, t2, n2) {\n let o3 = 0;\n const i3 = n2?.NODE_MAX_PF ?? 0.99999;\n for (const n3 of e35) {\n const e36 = t2.get(n3.capacityMeshNodeId);\n if (!e36)\n continue;\n if (e36._containsTarget)\n continue;\n const r3 = Cz(n3), s2 = Math.min(Vz(e36, r3.numSameLayerCrossings), i3);\n o3 += Math.log(1 - s2);\n }\n return o3;\n}\nvar Qz = class extends ni {\n constructor(e35) {\n super(), this.input = e35;\n const { simpleRouteJson: t2, capacityMeshNodes: n2, inputNodes: o3, colorMap: i3, nodeMemoryPfMap: r3, hyperParameters: s2, precomputedInitialParams: a3, fixedRoutes: c3 } = e35;\n if (this.input = structuredClone(e35), this.MAX_ITERATIONS = 1e8, this.simpleRouteJson = t2, this.inputNodes = o3, this.colorMap = i3 ?? {}, this.capacityMeshNodeMap = new Map(n2.map((e36) =\u003e [e36.capacityMeshNodeId, e36])), this.nodeMemoryPfMap = r3 ?? new Map, this.hyperParameters = s2 ?? {}, a3) {\n this.nodeMap = a3.nodeMap, this.avgNodePitch = a3.avgNodePitch, this.offBoardNodes = a3.offBoardNodes, this.portPointMap = a3.portPointMap, this.nodePortPointsMap = a3.nodePortPointsMap, this.connectionNameToGoalNodeIds = a3.connectionNameToGoalNodeIds;\n const { nodeAssignedPortPoints: e36 } = function(e37) {\n const t3 = new Map;\n for (const [n3, o4] of e37.nodeAssignedPortPoints)\n t3.set(n3, [...o4]);\n return { nodeAssignedPortPoints: t3 };\n }(a3);\n this.nodeAssignedPortPoints = e36, this.connectionsWithResults = Sr(structuredClone(a3.unshuffledConnectionsWithResults), this.hyperParameters.SHUFFLE_SEED ?? 0);\n } else {\n this.nodeMap = new Map(o3.map((e37) =\u003e [e37.capacityMeshNodeId, e37]));\n const e36 = o3.map((e37) =\u003e (e37.width + e37.height) / 2).filter((e37) =\u003e Number.isFinite(e37) \u0026\u0026 e37 \u003e 0);\n this.avgNodePitch = e36.length \u003e 0 ? e36.reduce((e37, t4) =\u003e e37 + t4, 0) / e36.length : 1, this.offBoardNodes = o3.filter((e37) =\u003e e37._offBoardConnectionId), this.portPointMap = new Map, this.nodePortPointsMap = new Map;\n for (const e37 of o3)\n this.nodePortPointsMap.set(e37.capacityMeshNodeId, []), this.nodeAssignedPortPoints.set(e37.capacityMeshNodeId, []);\n for (const e37 of o3)\n for (const t4 of e37.portPoints) {\n this.portPointMap.set(t4.portPointId, t4);\n for (const e38 of t4.connectionNodeIds) {\n const n4 = this.nodePortPointsMap.get(e38);\n n4 \u0026\u0026 !n4.some((e39) =\u003e e39.portPointId === t4.portPointId) \u0026\u0026 n4.push(t4);\n }\n }\n const { connectionsWithResults: t3, connectionNameToGoalNodeIds: n3 } = this.getConnectionsWithNodes();\n this.connectionsWithResults = t3, this.connectionNameToGoalNodeIds = n3;\n }\n if (c3 \u0026\u0026 c3.length \u003e 0) {\n for (const e36 of c3)\n if (this.connectionsWithResults.push(e36), e36.portPoints)\n for (const t3 of e36.portPoints)\n t3.portPointId \u0026\u0026 this.assignedPortPoints.set(t3.portPointId, { connectionName: t3.connectionName, rootConnectionName: t3.rootConnectionName });\n }\n for (const e36 of this.connectionsWithResults)\n e36.path ? this.processedConnectionQueue.push(e36) : this.unprocessedConnectionQueue.push(e36);\n this.totalConnectionCount = this.connectionsWithResults.length;\n }\n getSolverName() {\n return \"PortPointPathingSolver\";\n }\n hyperParameters;\n simpleRouteJson;\n inputNodes;\n nodeMap;\n nodePortPointsMap;\n portPointMap;\n connectionsWithResults = [];\n failedConnection = null;\n assignedPortPoints = new Map;\n nodeAssignedPortPoints = new Map;\n PORT_POINT_REUSE_FACTOR = 1000;\n BASE_COST_FOR_NOT_GOING_OFF_BOARD = 100;\n get NODE_PF_FACTOR() {\n return this.hyperParameters.NODE_PF_FACTOR ?? 50;\n }\n get RANDOM_WALK_DISTANCE() {\n return this.hyperParameters.RANDOM_WALK_DISTANCE ?? 0;\n }\n get MEMORY_PF_FACTOR() {\n return this.hyperParameters.MEMORY_PF_FACTOR ?? 0;\n }\n get CENTER_OFFSET_FOCUS_SHIFT() {\n return this.hyperParameters.CENTER_OFFSET_FOCUS_SHIFT ?? 0;\n }\n get RANDOM_COST_MAGNITUDE() {\n return this.hyperParameters.RANDOM_COST_MAGNITUDE ?? 0;\n }\n get BASE_CANDIDATE_COST() {\n return this.hyperParameters.BASE_CANDIDATE_COST ?? 0;\n }\n get NODE_PF_MAX_PENALTY() {\n return this.hyperParameters.NODE_PF_MAX_PENALTY ?? 1e4;\n }\n get FORCE_CENTER_FIRST() {\n return this.hyperParameters.FORCE_CENTER_FIRST ?? true;\n }\n get FORCE_OFF_BOARD_FREQUENCY() {\n return this.offBoardNodes.length === 0 ? 0 : this.hyperParameters.FORCE_OFF_BOARD_FREQUENCY ?? 0;\n }\n get FORCE_OFF_BOARD_SEED() {\n return this.hyperParameters.FORCE_OFF_BOARD_SEED ?? 0;\n }\n get NODE_MAX_PF() {\n return Math.min(0.99999, 1 - Math.exp(-this.NODE_PF_MAX_PENALTY));\n }\n get CENTER_OFFSET_DIST_PENALTY_FACTOR() {\n return this.hyperParameters.CENTER_OFFSET_DIST_PENALTY_FACTOR ?? 0;\n }\n get STRAIGHT_LINE_DEVIATION_PENALTY_FACTOR() {\n return this.hyperParameters.STRAIGHT_LINE_DEVIATION_PENALTY_FACTOR ?? 0;\n }\n colorMap;\n get GREEDY_MULTIPLIER() {\n return this.hyperParameters.GREEDY_MULTIPLIER ?? 1.3;\n }\n MAX_CANDIDATES_IN_MEMORY = 5000;\n get MAX_ITERATIONS_PER_PATH() {\n return this.hyperParameters.MAX_ITERATIONS_PER_PATH ?? 1e4;\n }\n ITERATIONS_PER_MM_FOR_PATH = 30;\n BASE_ITERATIONS_PER_PATH = 1e4;\n get RIPPING_ENABLED() {\n return this.hyperParameters.RIPPING_ENABLED ?? false;\n }\n get RIPPING_PF_THRESHOLD() {\n const e35 = this.hyperParameters.START_RIPPING_PF_THRESHOLD, t2 = this.hyperParameters.END_RIPPING_PF_THRESHOLD;\n if (e35 !== undefined \u0026\u0026 t2 !== undefined) {\n const n2 = this.MAX_RIPS;\n return e35 + (n2 \u003e 0 ? this.totalRipCount / n2 : 0) * (t2 - e35);\n }\n return this.hyperParameters.RIPPING_PF_THRESHOLD ?? 0.3;\n }\n get MAX_RIPS() {\n return this.hyperParameters.MAX_RIPS ?? 100;\n }\n get RANDOM_RIP_FRACTION() {\n return this.hyperParameters.RANDOM_RIP_FRACTION ?? 0;\n }\n get JUMPER_PF_FN_ENABLED() {\n return this.hyperParameters.JUMPER_PF_FN_ENABLED ?? false;\n }\n jumpersPerMmSquared = 0.1;\n testedRipConnections = new Map;\n totalRipCount = 0;\n get MIN_ALLOWED_BOARD_SCORE() {\n return this.hyperParameters.MIN_ALLOWED_BOARD_SCORE ?? -1e4;\n }\n nodeMemoryPfMap;\n unprocessedConnectionQueue = [];\n processedConnectionQueue = [];\n currentConnection = null;\n totalConnectionCount = 0;\n currentPathIterations = 0;\n candidates;\n visitedPortPoints;\n connectionNameToGoalNodeIds;\n capacityMeshNodeMap;\n avgNodePitch;\n currentConnectionShouldRouteOffBoard = false;\n activeCandidateStraightLineDistance;\n offBoardNodes = [];\n baseNodeCostCache = new Map;\n getConstructorParams() {\n return this.input;\n }\n clearCostCaches() {\n this.baseNodeCostCache.clear();\n }\n clampPf(e35) {\n return Number.isFinite(e35) ? Math.min(Math.max(e35, 0), 0.999999) : 0.999999;\n }\n pfToFailureCost(e35) {\n const t2 = this.clampPf(e35);\n return t2 \u003e= this.NODE_MAX_PF ? this.NODE_PF_MAX_PENALTY : -Math.log(1 - t2);\n }\n getBaseNodeFailureCost(e35) {\n const t2 = this.baseNodeCostCache.get(e35);\n if (t2 != null)\n return t2;\n const n2 = this.nodeMap.get(e35);\n if (!n2)\n return 0;\n const o3 = this.computeNodePf(n2), i3 = this.pfToFailureCost(o3);\n return this.baseNodeCostCache.set(e35, i3), i3;\n }\n computeBoardScore() {\n const e35 = this.getNodesWithPortPoints();\n return this.JUMPER_PF_FN_ENABLED ? Jz(e35, this.capacityMeshNodeMap) : $z(e35, this.capacityMeshNodeMap);\n }\n getMaxIterationsForCurrentPath() {\n const e35 = this.activeCandidateStraightLineDistance ?? 0;\n return Math.min(this.BASE_ITERATIONS_PER_PATH + this.ITERATIONS_PER_MM_FOR_PATH * e35, this.MAX_ITERATIONS_PER_PATH);\n }\n getNodeDeltaFailureCostForSegment(e35, t2, n2) {\n const o3 = this.nodeMap.get(e35);\n if (!o3)\n return 0;\n const i3 = this.getBaseNodeFailureCost(e35), r3 = this.computeNodePf(o3, [t2, n2]), s2 = this.pfToFailureCost(r3), a3 = Math.max(0, s2 - i3);\n return r3 \u003e= this.NODE_MAX_PF ? this.NODE_PF_MAX_PENALTY : a3 * this.NODE_PF_FACTOR;\n }\n getConnectionsWithNodes() {\n const { unshuffledConnectionsWithResults: e35, connectionNameToGoalNodeIds: t2 } = Lz(this.simpleRouteJson, this.inputNodes);\n return { connectionsWithResults: Sr(e35, this.hyperParameters.SHUFFLE_SEED ?? 0), connectionNameToGoalNodeIds: t2 };\n }\n buildNodeWithPortPointsForCrossing(e35, t2) {\n const n2 = this.nodeAssignedPortPoints.get(e35.capacityMeshNodeId) ?? [], o3 = t2 ? [...n2, ...t2] : n2;\n return { capacityMeshNodeId: e35.capacityMeshNodeId, center: e35.center, width: e35.width, height: e35.height, portPoints: o3, availableZ: e35.availableZ };\n }\n computeNodePf(e35, t2) {\n if (e35._containsTarget)\n return 0;\n const n2 = this.buildNodeWithPortPointsForCrossing(e35, t2), o3 = Cz(n2);\n return this.JUMPER_PF_FN_ENABLED \u0026\u0026 e35.availableZ.length === 1 ? Vz(this.capacityMeshNodeMap.get(e35.capacityMeshNodeId), o3.numSameLayerCrossings) : jz(this.capacityMeshNodeMap.get(e35.capacityMeshNodeId), o3.numSameLayerCrossings, o3.numEntryExitLayerChanges, o3.numTransitionPairCrossings);\n }\n getPortPointReusePenalty(e35, t2) {\n const n2 = this.assignedPortPoints.get(e35);\n return n2 ? t2 === n2.rootConnectionName ? 0 : this.PORT_POINT_REUSE_FACTOR : 0;\n }\n getOtherNodeId(e35, t2) {\n const [n2, o3] = e35.connectionNodeIds;\n return n2 === t2 ? o3 : o3 === t2 ? n2 : null;\n }\n computeG(e35, t2, n2, o3, i3) {\n const { currentNodeId: r3, point: s2 } = e35, a3 = { x: s2.x, y: s2.y, z: e35.z, connectionName: o3, rootConnectionName: i3 }, c3 = { x: t2.x, y: t2.y, z: t2.z, connectionName: o3, rootConnectionName: i3 }, l3 = this.getNodeDeltaFailureCostForSegment(r3, a3, c3);\n return e35.g + l3;\n }\n computeGToEndTarget(e35, t2, n2, o3) {\n const i3 = e35.currentNodeId, r3 = { x: e35.point.x, y: e35.point.y, z: e35.z, connectionName: n2, rootConnectionName: o3 }, s2 = { x: t2.x, y: t2.y, z: e35.z, connectionName: n2, rootConnectionName: o3 }, a3 = this.getNodeDeltaFailureCostForSegment(i3, r3, s2);\n return e35.g + a3;\n }\n computeDistanceToNearestOffBoardNode(e35) {\n if (this.offBoardNodes.length === 0)\n return 1 / 0;\n let t2 = 1 / 0;\n for (const n2 of this.offBoardNodes) {\n const o3 = me(e35, n2.center);\n o3 \u003c t2 \u0026\u0026 (t2 = o3);\n }\n return t2;\n }\n computeH(e35, t2, n2, o3, i3, r3) {\n if (this.RANDOM_WALK_DISTANCE \u003e 0 \u0026\u0026 i3 \u003c this.RANDOM_WALK_DISTANCE)\n return 0;\n if (this.currentConnectionShouldRouteOffBoard \u0026\u0026 !r3)\n return this.BASE_COST_FOR_NOT_GOING_OFF_BOARD + this.computeDistanceToNearestOffBoardNode(e35);\n const s2 = this.nodeMap.get(n2);\n if (!s2)\n return 0;\n const a3 = me(e35, s2.center), c3 = this.avgNodePitch \u003e 0 ? a3 / this.avgNodePitch : 0, l3 = this.clampPf(this.nodeMemoryPfMap.get(t2) ?? 0), h2 = this.pfToFailureCost(l3) * this.MEMORY_PF_FACTOR, d2 = c3 * this.BASE_CANDIDATE_COST, u2 = this.CENTER_OFFSET_DIST_PENALTY_FACTOR * e35.distToCentermostPortOnZ ** 2;\n let p3 = 0;\n if (this.STRAIGHT_LINE_DEVIATION_PENALTY_FACTOR \u003e 0 \u0026\u0026 this.currentConnection) {\n const t3 = pe(e35, this.currentConnection.connection.pointsToConnect[0], this.currentConnection.connection.pointsToConnect[1]);\n p3 = this.STRAIGHT_LINE_DEVIATION_PENALTY_FACTOR * t3;\n }\n return a3 + d2 + h2 + u2 + p3;\n }\n getVisitedPortPointKey(e35, t2) {\n return this.currentConnectionShouldRouteOffBoard \u0026\u0026 t2 ? `${e35}:touched_off_board` : e35;\n }\n getAvailableExitPortPoints(e35, t2) {\n const n2 = this.currentConnection?.connection.__rootConnectionNames?.[0], o3 = this.nodePortPointsMap.get(e35) ?? [], i3 = [];\n for (const e36 of o3) {\n const o4 = this.getVisitedPortPointKey(e36.portPointId, t2);\n if (this.visitedPortPoints?.has(o4))\n continue;\n const r3 = this.assignedPortPoints.get(e36.portPointId);\n r3 \u0026\u0026 r3?.rootConnectionName !== n2 || i3.push(e36);\n }\n return i3;\n }\n getAvailableExitPortPointsWithOmissions(e35, t2, n2) {\n const o3 = this.nodePortPointsMap.get(e35) ?? [], i3 = this.currentConnection?.connection.__rootConnectionNames?.[0], r3 = new Map;\n for (const t3 of o3) {\n const o4 = this.getVisitedPortPointKey(t3.portPointId, n2);\n if (this.visitedPortPoints?.has(o4))\n continue;\n const i4 = this.getOtherNodeId(t3, e35);\n if (!i4)\n continue;\n this.nodeMap.get(i4);\n const s3 = `${i4}|${t3.z}`, a3 = r3.get(s3) ?? [];\n a3.push(t3), r3.set(s3, a3);\n }\n const s2 = [];\n for (const [, e36] of r3) {\n e36.sort((e37, t4) =\u003e e37.distToCentermostPortOnZ - t4.distToCentermostPortOnZ);\n const t3 = e36[0];\n if (!t3)\n continue;\n const n3 = this.assignedPortPoints.get(t3.portPointId), o4 = n3 \u0026\u0026 n3.rootConnectionName === i3;\n if (!n3 || o4) {\n s2.push(t3);\n continue;\n }\n const r4 = [...e36].sort((e37, t4) =\u003e e37.x !== t4.x ? e37.x - t4.x : e37.y - t4.y), a3 = [];\n let c3 = [];\n for (const e37 of r4) {\n const t4 = this.assignedPortPoints.get(e37.portPointId);\n !t4 || t4.rootConnectionName === i3 ? c3.push(e37) : c3.length \u003e 0 \u0026\u0026 (a3.push(c3), c3 = []);\n }\n c3.length \u003e 0 \u0026\u0026 a3.push(c3);\n for (const e37 of a3) {\n const t4 = Math.floor(e37.length / 2);\n s2.push(e37[t4]);\n }\n }\n return s2;\n }\n getAvailableExitPortPointsForOffboardConnection(e35, t2) {\n const n2 = this.nodeMap.get(e35);\n if (!n2)\n return [];\n const o3 = this.currentConnection?.connection.__rootConnectionNames?.[0], i3 = [];\n for (const r3 of n2?._offBoardConnectedCapacityMeshNodeIds ?? []) {\n if (r3 === e35)\n continue;\n if (!this.nodeMap.get(r3))\n continue;\n const n3 = this.nodePortPointsMap.get(r3) ?? [];\n for (const e36 of n3) {\n const n4 = this.getVisitedPortPointKey(e36.portPointId, t2);\n if (this.visitedPortPoints?.has(n4))\n continue;\n const s2 = this.assignedPortPoints.get(e36.portPointId);\n s2 \u0026\u0026 s2.rootConnectionName !== o3 || i3.push({ ...e36, throughNodeId: r3 });\n }\n }\n return i3;\n }\n canTravelThroughObstacle(e35, t2, n2) {\n const o3 = this.connectionNameToGoalNodeIds.get(t2);\n return o3?.includes(e35.capacityMeshNodeId) || Boolean(e35._offBoardConnectionId);\n }\n isAtEndGoal(e35, t2) {\n return e35 === t2;\n }\n getBacktrackedPath(e35) {\n const t2 = [];\n let n2 = e35;\n for (;n2; ) {\n if (n2.lastMoveWasOffBoard \u0026\u0026 n2.throughNodeId) {\n const e36 = this.nodeMap.get(n2.throughNodeId), o3 = n2.prevCandidate ? this.nodeMap.get(n2.prevCandidate.currentNodeId) : null;\n t2.push(n2), e36 \u0026\u0026 t2.push({ prevCandidate: null, portPoint: null, currentNodeId: n2.throughNodeId, point: e36.center, z: n2.z, f: 0, g: 0, h: 0, distanceTraveled: 0 }), o3 \u0026\u0026 o3._offBoardConnectionId \u0026\u0026 t2.push({ prevCandidate: null, portPoint: null, currentNodeId: n2.prevCandidate.currentNodeId, point: o3.center, z: n2.z, f: 0, g: 0, h: 0, distanceTraveled: 0 });\n } else\n t2.push(n2);\n n2 = n2.prevCandidate;\n }\n return t2.reverse();\n }\n assignPortPointsForPath(e35, t2, n2) {\n const o3 = [];\n for (let i4 = 0;i4 \u003c e35.length; i4++) {\n const r4 = e35[i4];\n if (!r4.portPoint) {\n const s4 = i4 === 0, a4 = i4 === e35.length - 1;\n if (!s4 \u0026\u0026 !a4) {\n const e36 = { x: r4.point.x, y: r4.point.y, z: r4.z, connectionName: t2, rootConnectionName: n2 };\n o3.push(e36);\n const i5 = this.nodeAssignedPortPoints.get(r4.currentNodeId) ?? [];\n i5.push(e36), this.nodeAssignedPortPoints.set(r4.currentNodeId, i5);\n }\n continue;\n }\n const s3 = r4.portPoint;\n this.assignedPortPoints.set(s3.portPointId, { connectionName: t2, rootConnectionName: n2 });\n const a3 = { portPointId: s3.portPointId, x: s3.x, y: s3.y, z: s3.z, connectionName: t2, rootConnectionName: n2, prevPortPointId: s3.prevPortPointId, nextPortPointId: s3.nextPortPointId };\n o3.push(a3);\n for (const e36 of s3.connectionNodeIds) {\n const t3 = this.nodeAssignedPortPoints.get(e36) ?? [];\n t3.push(a3), this.nodeAssignedPortPoints.set(e36, t3);\n }\n }\n const i3 = o3.map((e36) =\u003e e36.portPointId).filter((e36) =\u003e Boolean(e36));\n let r3 = 0;\n for (const e36 of o3)\n e36.portPointId \u0026\u0026 (e36.prevPortPointId = i3[r3 - 1], e36.nextPortPointId = i3[r3 + 1], r3 += 1);\n const s2 = Array.from(new Set(e35.map((e36) =\u003e e36.currentNodeId)));\n for (const e36 of s2) {\n const o4 = this.nodeMap.get(e36);\n if (o4 \u0026\u0026 o4._offBoardConnectionId)\n for (const e37 of o4?._offBoardConnectedCapacityMeshNodeIds ?? []) {\n const o5 = this.nodePortPointsMap.get(e37) ?? [];\n for (const e38 of o5)\n this.assignedPortPoints.set(e38.portPointId, { connectionName: t2, rootConnectionName: n2 });\n }\n }\n return o3;\n }\n addTargetPointsToNodes(e35, t2) {\n const n2 = e35[0], o3 = e35[e35.length - 1], i3 = t2.pointsToConnect[0], r3 = t2.pointsToConnect[t2.pointsToConnect.length - 1];\n if (n2 \u0026\u0026 i3) {\n const e36 = this.nodeAssignedPortPoints.get(n2.currentNodeId) ?? [];\n e36.push({ x: i3.x, y: i3.y, z: n2.z, connectionName: t2.name, rootConnectionName: t2.__rootConnectionNames?.[0] }), this.nodeAssignedPortPoints.set(n2.currentNodeId, e36);\n }\n if (o3 \u0026\u0026 r3) {\n const e36 = this.nodeAssignedPortPoints.get(o3.currentNodeId) ?? [];\n e36.push({ x: r3.x, y: r3.y, z: o3.z, connectionName: t2.name, rootConnectionName: t2.__rootConnectionNames?.[0] }), this.nodeAssignedPortPoints.set(o3.currentNodeId, e36);\n }\n }\n isPortPointInPathChain(e35, t2) {\n let n2 = e35;\n for (;n2; ) {\n if (n2.portPoint?.portPointId === t2)\n return true;\n n2 = n2.prevCandidate;\n }\n return false;\n }\n isNodeInPathChain(e35, t2) {\n let n2 = e35;\n for (;n2; ) {\n if (n2.currentNodeId === t2)\n return true;\n n2 = n2.prevCandidate;\n }\n return false;\n }\n _step() {\n if (this.currentConnection || (this.currentConnection = this.unprocessedConnectionQueue.shift() ?? null), !this.currentConnection) {\n const e36 = this.computeBoardScore();\n return this.stats = { boardScore: e36, totalRipCount: this.totalRipCount }, e36 \u003c this.MIN_ALLOWED_BOARD_SCORE ? (this.failedConnection = null, this.failed = true, void (this.error = `Board score ${e36.toFixed(2)} is less than MIN_ALLOWED_BOARD_SCORE ${this.MIN_ALLOWED_BOARD_SCORE.toFixed(2)}`)) : void (this.solved = true);\n }\n const e35 = this.currentConnection;\n this.activeCandidateStraightLineDistance = e35.straightLineDistance, this.currentPathIterations++;\n const t2 = this.getMaxIterationsForCurrentPath();\n if (this.currentPathIterations \u003e t2)\n return this.failedConnection = e35, this.processedConnectionQueue.push(e35), this.currentConnection = null, this.candidates = null, this.visitedPortPoints = null, this.currentPathIterations = 0, this.failed = true, void (this.error = `Exceeded max iterations for path (${t2}) on connection ${e35.connection.name}`);\n const [n2, o3] = e35.nodeIds, i3 = this.nodeMap.get(n2), r3 = this.nodeMap.get(o3);\n if (!i3 || !r3)\n return this.processedConnectionQueue.push(e35), this.currentConnection = null, void (this.currentPathIterations = 0);\n const s2 = e35.connection.name, a3 = e35.connection.__rootConnectionNames?.[0], c3 = e35.connection.pointsToConnect[0];\n if (!this.candidates) {\n if (this.clearCostCaches(), this.FORCE_OFF_BOARD_FREQUENCY \u003e 0) {\n const e36 = vr(17 * (this.hyperParameters.SHUFFLE_SEED ?? 0) + this.FORCE_OFF_BOARD_SEED + this.processedConnectionQueue.length);\n this.currentConnectionShouldRouteOffBoard = e36() \u003c this.FORCE_OFF_BOARD_FREQUENCY;\n } else\n this.currentConnectionShouldRouteOffBoard = false;\n this.candidates = [], this.visitedPortPoints = new Set;\n for (const e36 of i3.availableZ) {\n const t3 = c3 ? { x: c3.x, y: c3.y } : i3.center, r4 = { portPointId: `start:${n2}:${e36}`, x: t3.x, y: t3.y, z: e36, connectionNodeIds: [n2, n2], distToCentermostPortOnZ: 0 }, s3 = this.computeH(r4, n2, o3, e36, 0, false), a4 = 0 + s3 * this.GREEDY_MULTIPLIER;\n this.candidates.push({ prevCandidate: null, portPoint: null, currentNodeId: n2, point: t3, z: e36, f: a4, g: 0, h: s3, distanceTraveled: 0, hasTouchedOffBoardNode: false });\n }\n }\n this.candidates.sort((e36, t3) =\u003e e36.f - t3.f);\n let l3, h2 = this.candidates.shift();\n for (;h2?.portPoint \u0026\u0026 this.visitedPortPoints; ) {\n const e36 = this.getVisitedPortPointKey(h2.portPoint.portPointId, h2.hasTouchedOffBoardNode);\n if (!this.visitedPortPoints.has(e36))\n break;\n h2 = this.candidates.shift();\n }\n if (this.candidates.length \u003e this.MAX_CANDIDATES_IN_MEMORY \u0026\u0026 this.candidates.splice(this.MAX_CANDIDATES_IN_MEMORY, this.candidates.length - this.MAX_CANDIDATES_IN_MEMORY), !h2)\n return this.error = `Ran out of candidates on connection ${s2}`, this.failedConnection = e35, this.processedConnectionQueue.push(e35), this.currentConnection = null, this.candidates = null, this.visitedPortPoints = null, this.currentPathIterations = 0, void (this.failed = true);\n if (h2.portPoint \u0026\u0026 this.visitedPortPoints) {\n const e36 = this.getVisitedPortPointKey(h2.portPoint.portPointId, h2.hasTouchedOffBoardNode);\n this.visitedPortPoints.add(e36);\n }\n if (this.isAtEndGoal(h2.currentNodeId, o3)) {\n const t3 = e35.connection.pointsToConnect[e35.connection.pointsToConnect.length - 1], n3 = t3 ? { x: t3.x, y: t3.y } : r3.center, i4 = this.computeGToEndTarget(h2, n3, s2, a3), c4 = { prevCandidate: h2, portPoint: null, currentNodeId: o3, point: n3, z: h2.z, g: i4, h: 0, f: i4, distanceTraveled: h2.distanceTraveled + me(h2.point, n3) }, l4 = this.getBacktrackedPath(c4);\n return e35.path = l4, e35.portPoints = this.assignPortPointsForPath(l4, s2, a3), this.addTargetPointsToNodes(l4, e35.connection), this.clearCostCaches(), this.RIPPING_ENABLED \u0026\u0026 this.processRippingForPath(l4, s2), this.processedConnectionQueue.push(e35), this.currentConnection = null, this.progress = this.processedConnectionQueue.length / this.totalConnectionCount, this.candidates = null, this.visitedPortPoints = null, void (this.currentPathIterations = 0);\n }\n const d2 = this.nodeMap.get(h2.currentNodeId);\n l3 = d2?._offBoardConnectionId ? this.getAvailableExitPortPointsForOffboardConnection(h2.currentNodeId, h2.hasTouchedOffBoardNode) : this.FORCE_CENTER_FIRST ? this.getAvailableExitPortPointsWithOmissions(h2.currentNodeId, o3, h2.hasTouchedOffBoardNode) : this.getAvailableExitPortPoints(h2.currentNodeId, h2.hasTouchedOffBoardNode);\n for (const e36 of l3) {\n if (this.isPortPointInPathChain(h2, e36.portPointId))\n continue;\n if (this.visitedPortPoints?.has(e36.portPointId))\n continue;\n const t3 = this.getOtherNodeId(e36, e36.throughNodeId ?? h2.currentNodeId);\n if (!t3)\n continue;\n if (this.isNodeInPathChain(h2, t3))\n continue;\n const n3 = \"throughNodeId\" in e36 ? e36.throughNodeId : undefined, i4 = n3 ? this.nodeMap.get(n3) : null, r4 = this.nodeMap.get(t3);\n if (!r4)\n continue;\n if (r4._containsObstacle \u0026\u0026 !this.canTravelThroughObstacle(r4, s2, a3))\n continue;\n const c4 = this.computeG(h2, e36, t3, s2, a3);\n if (!this.RIPPING_ENABLED \u0026\u0026 c4 \u003e -this.MIN_ALLOWED_BOARD_SCORE)\n continue;\n const l4 = h2.distanceTraveled + me(h2.point, e36), u2 = h2.hasTouchedOffBoardNode || Boolean(r4._offBoardConnectionId), p3 = this.computeH(e36, t3, o3, e36.z, l4, u2), m2 = c4 + p3 * this.GREEDY_MULTIPLIER, g2 = Boolean(d2?._offBoardConnectionId) \u0026\u0026 Boolean(i4?._offBoardConnectionId);\n this.candidates.push({ prevCandidate: h2, portPoint: e36, currentNodeId: t3, point: { x: e36.x, y: e36.y }, z: e36.z, f: m2, g: c4, h: p3, distanceTraveled: l4, lastMoveWasOffBoard: g2, throughNodeId: g2 ? n3 : undefined, hasTouchedOffBoardNode: u2 || Boolean(r4._offBoardConnectionId) || Boolean(d2?._offBoardConnectionId) });\n }\n }\n getNodesWithPortPoints() {\n const e35 = [];\n for (const t2 of this.inputNodes) {\n const n2 = this.nodeAssignedPortPoints.get(t2.capacityMeshNodeId) ?? [];\n n2.length \u003e 0 \u0026\u0026 e35.push({ capacityMeshNodeId: t2.capacityMeshNodeId, center: t2.center, width: t2.width, height: t2.height, portPoints: n2, availableZ: t2.availableZ });\n }\n return e35;\n }\n getConnectionsInNode(e35, t2) {\n const n2 = [], o3 = new Set;\n for (const i3 of this.connectionsWithResults)\n if (i3.path \u0026\u0026 i3.connection.name !== t2 \u0026\u0026 !o3.has(i3.connection.name)) {\n for (const t3 of i3.path)\n if (t3.currentNodeId === e35) {\n n2.push(i3), o3.add(i3.connection.name);\n break;\n }\n }\n return n2;\n }\n computeNodePfWithoutConnection(e35, t2) {\n if (e35._containsTarget)\n return { pf: 0, totalCrossings: 0 };\n const n2 = (this.nodeAssignedPortPoints.get(e35.capacityMeshNodeId) ?? []).filter((e36) =\u003e e36.connectionName !== t2), o3 = { capacityMeshNodeId: e35.capacityMeshNodeId, center: e35.center, width: e35.width, height: e35.height, portPoints: n2, availableZ: e35.availableZ }, i3 = Cz(o3), r3 = i3.numSameLayerCrossings + i3.numEntryExitLayerChanges + i3.numTransitionPairCrossings;\n return { pf: jz(this.capacityMeshNodeMap.get(e35.capacityMeshNodeId), i3.numSameLayerCrossings, i3.numEntryExitLayerChanges, i3.numTransitionPairCrossings), totalCrossings: r3 };\n }\n computeNodeCrossings(e35) {\n if (e35._containsTarget)\n return 0;\n const t2 = this.buildNodeWithPortPointsForCrossing(e35), n2 = Cz(t2);\n return n2.numSameLayerCrossings + n2.numEntryExitLayerChanges + n2.numTransitionPairCrossings;\n }\n ripConnection(e35) {\n const t2 = e35.connection.name;\n for (const [e36, n2] of this.assignedPortPoints.entries())\n n2.connectionName === t2 \u0026\u0026 this.assignedPortPoints.delete(e36);\n for (const [e36, n2] of this.nodeAssignedPortPoints.entries()) {\n const o3 = n2.filter((e37) =\u003e e37.connectionName !== t2);\n this.nodeAssignedPortPoints.set(e36, o3);\n }\n e35.path = undefined, e35.portPoints = undefined;\n }\n requeueConnection(e35) {\n this.totalRipCount++;\n const t2 = this.processedConnectionQueue.indexOf(e35);\n if (t2 !== -1)\n return this.processedConnectionQueue.splice(t2, 1), this.unprocessedConnectionQueue.push(e35), true;\n const n2 = this.unprocessedConnectionQueue.indexOf(e35);\n return n2 !== -1 \u0026\u0026 (this.unprocessedConnectionQueue.splice(n2, 1), this.unprocessedConnectionQueue.unshift(e35)), true;\n }\n processRippingForPath(e35, t2) {\n const n2 = Array.from(new Set(e35.map((e36) =\u003e e36.currentNodeId)));\n let o3 = false;\n for (const e36 of n2) {\n if (this.totalRipCount \u003e this.MAX_RIPS)\n break;\n const n3 = this.nodeMap.get(e36);\n if (!n3)\n continue;\n let i3 = this.computeNodePf(n3);\n if (i3 \u003c= this.RIPPING_PF_THRESHOLD)\n continue;\n this.testedRipConnections.has(e36) || this.testedRipConnections.set(e36, new Set);\n const r3 = this.testedRipConnections.get(e36), s2 = Sr(this.getConnectionsInNode(e36, t2), (this.hyperParameters.SHUFFLE_SEED ?? 0) + this.processedConnectionQueue.length);\n for (const e37 of s2) {\n if (i3 \u003c= this.RIPPING_PF_THRESHOLD)\n break;\n const t3 = e37.connection.name;\n r3.add(t3);\n const { pf: s3 } = this.computeNodePfWithoutConnection(n3, t3);\n this.ripConnection(e37);\n if (!this.requeueConnection(e37))\n return;\n i3 = s3, o3 = true, this.clearCostCaches();\n }\n }\n o3 \u0026\u0026 this.RANDOM_RIP_FRACTION \u003e 0 \u0026\u0026 this.processRandomRipping(t2);\n }\n processRandomRipping(e35) {\n const t2 = this.processedConnectionQueue.filter((t3) =\u003e t3.path !== undefined \u0026\u0026 t3.connection.name !== e35);\n if (t2.length === 0)\n return;\n const n2 = Math.max(1, Math.floor(this.RANDOM_RIP_FRACTION * t2.length)), o3 = Sr(t2, (this.hyperParameters.SHUFFLE_SEED ?? 0) + this.totalRipCount + this.processedConnectionQueue.length);\n for (let e36 = 0;e36 \u003c n2 \u0026\u0026 e36 \u003c o3.length \u0026\u0026 !(this.totalRipCount \u003e this.MAX_RIPS); e36++) {\n const t3 = o3[e36];\n this.ripConnection(t3);\n if (!this.requeueConnection(t3))\n return;\n this.clearCostCaches();\n }\n }\n visualize() {\n let e35 = {};\n if (this.failed) {\n const t2 = this.failedConnection?.connection.pointsToConnect[0], n2 = this.failedConnection?.connection.pointsToConnect[1];\n t2 \u0026\u0026 n2 \u0026\u0026 (e35 = { lines: [{ points: [t2, n2], label: `Failed Connection ${this.failedConnection?.connection.name}`, strokeWidth: 1, strokeColor: \"red\", strokeDash: [2, 2] }] });\n }\n return Gn(qz(this), e35);\n }\n};\nvar Kz = class extends wa {\n getSolverName() {\n return \"HyperPortPointPathingSolver\";\n }\n params;\n precomputedInitialParams;\n constructor(e35) {\n super(), this.params = e35, this.MAX_ITERATIONS = 1e8, this.GREEDY_MULTIPLIER = 1.2, this.MIN_SUBSTEPS = 50, this.precomputedInitialParams = e35.precomputedInitialParams ?? zz(e35.simpleRouteJson, e35.inputNodes);\n }\n getHyperParameterDefs() {\n const e35 = this.params.numShuffleSeeds ?? 50;\n return [{ name: \"SHUFFLE_SEED\", possibleValues: Array.from({ length: e35 }, (e36, t2) =\u003e ({ SHUFFLE_SEED: t2 + 1700 * (this.params.hyperParameters?.SHUFFLE_SEED ?? 0) })) }];\n }\n getCombinationDefs() {\n return [[\"SHUFFLE_SEED\"]];\n }\n generateSolver(e35) {\n return new Qz({ simpleRouteJson: this.params.simpleRouteJson, capacityMeshNodes: this.params.capacityMeshNodes, inputNodes: this.params.inputNodes, colorMap: this.params.colorMap, nodeMemoryPfMap: this.params.nodeMemoryPfMap, hyperParameters: { ...this.params.hyperParameters, ...e35, MIN_ALLOWED_BOARD_SCORE: this.params.minAllowedBoardScore ?? e35.MIN_ALLOWED_BOARD_SCORE ?? this.params.hyperParameters?.MIN_ALLOWED_BOARD_SCORE }, precomputedInitialParams: this.precomputedInitialParams, fixedRoutes: this.params.fixedRoutes });\n }\n computeG(e35) {\n return -e35.computeBoardScore();\n }\n computeH(e35) {\n const t2 = e35.progress || 0;\n if (t2 \u003c 0.1)\n return 0;\n return -(e35.computeBoardScore() / t2) * (1 - t2);\n }\n getNodesWithPortPoints() {\n if (this.winningSolver)\n return this.winningSolver.getNodesWithPortPoints();\n const e35 = this.getSupervisedSolverWithBestFitness();\n return e35 ? e35.solver.getNodesWithPortPoints() : [];\n }\n get connectionsWithResults() {\n if (this.winningSolver)\n return this.winningSolver.connectionsWithResults;\n const e35 = this.getSupervisedSolverWithBestFitness();\n return e35 ? e35.solver.connectionsWithResults : [];\n }\n get inputNodes() {\n if (this.winningSolver)\n return this.winningSolver.inputNodes;\n const e35 = this.getSupervisedSolverWithBestFitness();\n return e35 ? e35.solver.inputNodes : this.params.inputNodes;\n }\n get nodeMap() {\n if (this.winningSolver)\n return this.winningSolver.nodeMap;\n const e35 = this.getSupervisedSolverWithBestFitness();\n return e35 ? e35.solver.nodeMap : new Map(this.params.inputNodes.map((e36) =\u003e [e36.capacityMeshNodeId, e36]));\n }\n get assignedPortPoints() {\n if (this.winningSolver)\n return this.winningSolver.assignedPortPoints;\n const e35 = this.getSupervisedSolverWithBestFitness();\n return e35 ? e35.solver.assignedPortPoints : new Map;\n }\n get nodeAssignedPortPoints() {\n if (this.winningSolver)\n return this.winningSolver.nodeAssignedPortPoints;\n const e35 = this.getSupervisedSolverWithBestFitness();\n return e35 ? e35.solver.nodeAssignedPortPoints : new Map;\n }\n computeNodePf(e35) {\n if (this.winningSolver)\n return this.winningSolver.computeNodePf(e35);\n const t2 = this.getSupervisedSolverWithBestFitness();\n return t2 ? t2.solver.computeNodePf(e35) : null;\n }\n computeBoardScore() {\n if (this.winningSolver)\n return this.winningSolver.computeBoardScore();\n const e35 = this.getSupervisedSolverWithBestFitness();\n return e35 ? e35.solver.computeBoardScore() : 0;\n }\n onSolve(e35) {\n this.stats = { ...e35.solver.stats, winningHyperParameters: this.winningSolver?.hyperParameters };\n }\n visualize() {\n return this.winningSolver ? this.winningSolver.visualize() : super.visualize();\n }\n};\nfunction eB(e35) {\n let t2 = e35;\n return () =\u003e {\n t2 += 1831565813;\n let e36 = t2;\n return e36 = Math.imul(e36 ^ e36 \u003e\u003e\u003e 15, 1 | e36), e36 ^= e36 + Math.imul(e36 ^ e36 \u003e\u003e\u003e 7, 61 | e36), ((e36 ^ e36 \u003e\u003e\u003e 14) \u003e\u003e\u003e 0) / 4294967296;\n };\n}\nvar tB = [{ SHUFFLE_SEED: 100, NODE_PF_FACTOR: 100, NODE_PF_MAX_PENALTY: 100, MEMORY_PF_FACTOR: 0, EXPANSION_DEGREES: 10, FORCE_CENTER_FIRST: true, FORCE_OFF_BOARD_FREQUENCY: 0, CENTER_OFFSET_DIST_PENALTY_FACTOR: 0 }];\nvar nB = class extends ni {\n getSolverName() {\n return \"MultiSectionPortPointOptimizer\";\n }\n simpleRouteJson;\n inputNodes;\n capacityMeshNodes;\n capacityMeshEdges;\n colorMap;\n nodeMap;\n capacityMeshNodeMap;\n connectionResults;\n assignedPortPoints;\n nodeAssignedPortPoints;\n sections = [];\n activeSubSolver = null;\n currentSection = null;\n sectionScoreBeforeOptimization = 0;\n currentSectionCenterNodeId = null;\n currentScheduleIndex = 0;\n nodePfMap = new Map;\n attemptsToFixNode = new Map;\n sectionAttempts = 0;\n MAX_ATTEMPTS_PER_NODE = 100;\n MAX_SECTION_ATTEMPTS = 15;\n ACCEPTABLE_PF = 0.05;\n FRACTION_TO_REPLACE = 0.2;\n JUMPER_PF_FN_ENABLED = false;\n SHUFFLE_SEEDS_PER_SECTION = null;\n ALWAYS_RIP_INTERSECTIONS = true;\n effort = 1;\n HYPERPARAMETER_SCHEDULE = tB;\n constructor(e35) {\n super(), this.MAX_ITERATIONS = 1e6, this.simpleRouteJson = e35.simpleRouteJson, this.inputNodes = e35.inputNodes, this.capacityMeshNodes = e35.capacityMeshNodes, this.capacityMeshEdges = e35.capacityMeshEdges, this.colorMap = e35.colorMap ?? {}, this.effort = e35.effort ?? 1, e35.FRACTION_TO_REPLACE !== undefined \u0026\u0026 (this.FRACTION_TO_REPLACE = e35.FRACTION_TO_REPLACE), e35.ALWAYS_RIP_INTERSECTIONS !== undefined \u0026\u0026 (this.ALWAYS_RIP_INTERSECTIONS = e35.ALWAYS_RIP_INTERSECTIONS), e35.MAX_ATTEMPTS_PER_NODE !== undefined \u0026\u0026 (this.MAX_ATTEMPTS_PER_NODE = e35.MAX_ATTEMPTS_PER_NODE), e35.MAX_SECTION_ATTEMPTS !== undefined \u0026\u0026 (this.MAX_SECTION_ATTEMPTS = e35.MAX_SECTION_ATTEMPTS), e35.HYPERPARAMETER_SCHEDULE !== undefined \u0026\u0026 (this.HYPERPARAMETER_SCHEDULE = e35.HYPERPARAMETER_SCHEDULE), this.JUMPER_PF_FN_ENABLED = e35.JUMPER_PF_FN_ENABLED ?? this.JUMPER_PF_FN_ENABLED, this.SHUFFLE_SEEDS_PER_SECTION = e35.SHUFFLE_SEEDS_PER_SECTION, this.nodeMap = new Map(e35.inputNodes.map((e36) =\u003e [e36.capacityMeshNodeId, e36])), this.capacityMeshNodeMap = new Map(e35.capacityMeshNodes.map((e36) =\u003e [e36.capacityMeshNodeId, e36])), this.connectionResults = [...e35.initialConnectionResults], this.assignedPortPoints = new Map(e35.initialAssignedPortPoints), this.nodeAssignedPortPoints = new Map(e35.initialNodeAssignedPortPoints), this.nodePfMap = this.computeInitialPfMap();\n const t2 = this.computeBoardScore();\n this.stats.successfulOptimizations = 0, this.stats.failedOptimizations = 0, this.stats.nodesExamined = 0, this.stats.sectionAttempts = 0, this.stats.sectionScores = {}, this.stats.initialBoardScore = t2, this.stats.currentBoardScore = t2, this.stats.errors = 0;\n }\n computeInitialPfMap() {\n const e35 = new Map;\n for (const t2 of this.capacityMeshNodes) {\n const n2 = this.nodeAssignedPortPoints.get(t2.capacityMeshNodeId) ?? [];\n if (n2.length === 0)\n continue;\n const o3 = { capacityMeshNodeId: t2.capacityMeshNodeId, center: t2.center, width: t2.width, height: t2.height, portPoints: n2, availableZ: t2.availableZ }, i3 = this.JUMPER_PF_FN_ENABLED \u0026\u0026 t2.availableZ.length === 1 ? Vz(t2, Cz(o3).numSameLayerCrossings) : Yz(o3, t2);\n e35.set(t2.capacityMeshNodeId, i3);\n }\n return e35;\n }\n computeBoardScore() {\n const e35 = this.getNodesWithPortPoints();\n return this.computeScoreForNodes(e35);\n }\n computeScoreForNodes(e35) {\n return this.JUMPER_PF_FN_ENABLED ? Jz(e35, this.capacityMeshNodeMap) : $z(e35, this.capacityMeshNodeMap);\n }\n recomputePfForNodes(e35) {\n for (const t2 of e35) {\n const e36 = this.capacityMeshNodeMap.get(t2);\n if (!e36)\n continue;\n const n2 = this.nodeAssignedPortPoints.get(t2) ?? [];\n if (n2.length === 0) {\n this.nodePfMap.set(t2, 0);\n continue;\n }\n const o3 = { capacityMeshNodeId: t2, center: e36.center, width: e36.width, height: e36.height, portPoints: n2, availableZ: e36.availableZ }, i3 = this.JUMPER_PF_FN_ENABLED \u0026\u0026 e36.availableZ.length === 1 ? Vz(e36, Cz(o3).numSameLayerCrossings) : Yz(o3, e36);\n this.nodePfMap.set(t2, i3);\n }\n }\n getCreatePortPointSectionInput() {\n return { inputNodes: this.inputNodes, capacityMeshNodes: this.capacityMeshNodes, capacityMeshEdges: this.capacityMeshEdges, nodeMap: this.nodeMap, connectionResults: this.connectionResults };\n }\n createSection(e35) {\n return function(e36, t2) {\n const { inputNodes: n2, capacityMeshNodes: o3, capacityMeshEdges: i3, connectionResults: r3 } = e36, { centerOfSectionCapacityNodeId: s2, expansionDegrees: a3 } = t2, c3 = new Map;\n for (const e37 of i3) {\n const [t3, n3] = e37.nodeIds;\n c3.has(t3) || c3.set(t3, new Set), c3.has(n3) || c3.set(n3, new Set), c3.get(t3).add(n3), c3.get(n3).add(t3);\n }\n const l3 = new Set, h2 = new Set, d2 = [];\n for (d2.push({ nodeId: s2, depth: 0 }), h2.add(s2);d2.length \u003e 0; ) {\n const { nodeId: e37, depth: t3 } = d2.shift();\n if (l3.add(e37), t3 \u003c a3) {\n const n3 = c3.get(e37) ?? new Set;\n for (const e38 of n3)\n h2.has(e38) || (h2.add(e38), d2.push({ nodeId: e38, depth: t3 + 1 }));\n }\n }\n const u2 = n2.filter((e37) =\u003e l3.has(e37.capacityMeshNodeId)), p3 = o3.filter((e37) =\u003e l3.has(e37.capacityMeshNodeId)), m2 = [], g2 = [];\n for (const e37 of i3) {\n const [t3, n3] = e37.nodeIds, o4 = l3.has(t3), i4 = l3.has(n3);\n o4 \u0026\u0026 i4 ? m2.push(e37) : (o4 || i4) \u0026\u0026 g2.push(e37);\n }\n const f2 = u2.map((e37) =\u003e {\n const t3 = e37.portPoints.filter((e38) =\u003e {\n const [t4, n3] = e38.connectionNodeIds, o4 = l3.has(t4), i4 = l3.has(n3);\n return o4 || i4;\n });\n return { ...e37, portPoints: t3 };\n }), _2 = function(e37, t3) {\n const n3 = [];\n for (const o4 of e37) {\n if (!o4.path || o4.path.length === 0)\n continue;\n const e38 = o4.connection.name, i4 = o4.connection.__rootConnectionNames?.[0], r4 = [];\n for (let e39 = 0;e39 \u003c o4.path.length; e39++) {\n const n4 = o4.path[e39];\n t3.has(n4.currentNodeId) \u0026\u0026 r4.push(e39);\n }\n if (r4.length === 0)\n continue;\n const s3 = r4[0], a4 = r4[r4.length - 1];\n let c4 = s3, l4 = a4;\n if (s3 \u003e 0) {\n const e39 = o4.path[0].currentNodeId;\n (o4.nodeIds[0] === e39 || o4.nodeIds[1] === e39) \u0026\u0026 (c4 = 0);\n }\n if (a4 \u003c o4.path.length - 1) {\n const e39 = o4.path.length - 1, t4 = o4.path[e39].currentNodeId;\n (o4.nodeIds[0] === t4 || o4.nodeIds[1] === t4) \u0026\u0026 (l4 = e39);\n }\n const h3 = o4.path.slice(c4, l4 + 1), d3 = c4 \u003e 0, u3 = l4 \u003c o4.path.length - 1;\n n3.push({ connectionName: e38, rootConnectionName: i4, points: h3.map((e39) =\u003e ({ x: e39.point.x, y: e39.point.y, z: e39.z, nodeId: e39.currentNodeId, portPointId: e39.portPoint?.portPointId })), originalStartIndex: c4, originalEndIndex: l4, hasEntryFromOutside: d3, hasExitToOutside: u3 });\n }\n return n3;\n }(r3 ?? [], l3);\n return { centerNodeId: s2, expansionDegrees: a3, nodeIds: l3, inputNodes: f2, capacityMeshNodes: p3, internalEdges: m2, boundaryEdges: g2, sectionPaths: _2 };\n }(this.getCreatePortPointSectionInput(), e35);\n }\n getSectionNodesWithPortPoints(e35) {\n const t2 = [];\n for (const n2 of e35.nodeIds) {\n const e36 = this.nodeMap.get(n2), o3 = this.capacityMeshNodeMap.get(n2);\n if (!e36 || !o3)\n continue;\n const i3 = this.nodeAssignedPortPoints.get(n2) ?? [];\n i3.length \u003e 0 \u0026\u0026 t2.push({ capacityMeshNodeId: n2, center: e36.center, width: e36.width, height: e36.height, portPoints: i3, availableZ: e36.availableZ });\n }\n return t2;\n }\n getNodesWithPortPoints() {\n const e35 = [];\n for (const t2 of this.inputNodes) {\n const n2 = this.nodeAssignedPortPoints.get(t2.capacityMeshNodeId) ?? [];\n n2.length \u003e 0 \u0026\u0026 e35.push({ capacityMeshNodeId: t2.capacityMeshNodeId, center: t2.center, width: t2.width, height: t2.height, portPoints: n2, availableZ: t2.availableZ });\n }\n return e35;\n }\n findHighestPfNode() {\n let e35 = null, t2 = 0;\n for (const [n2, o3] of this.nodePfMap.entries()) {\n o3 * (1 - (this.attemptsToFixNode.get(n2) ?? 0) / this.MAX_ATTEMPTS_PER_NODE) ** 2 \u003e t2 \u0026\u0026 (t2 = o3, e35 = n2);\n }\n return !e35 || t2 \u003c this.ACCEPTABLE_PF ? null : e35;\n }\n currentSectionCutPathInfo = new Map;\n currentSectionKeptPortPoints = new Map;\n currentSectionFixedRoutes = [];\n determineConnectionsToRip(e35, t2) {\n const n2 = 31337 * this.sectionAttempts, o3 = eB(n2);\n if (this.FRACTION_TO_REPLACE \u003e= 1)\n return new Set(t2);\n const i3 = function(e36, t3) {\n const n3 = eB(t3), o4 = [...e36];\n for (let e37 = o4.length - 1;e37 \u003e 0; e37--) {\n const t4 = Math.floor(n3() * (e37 + 1));\n [o4[e37], o4[t4]] = [o4[t4], o4[e37]];\n }\n return o4;\n }(t2, n2), r3 = Math.max(1, Math.ceil(i3.length * this.FRACTION_TO_REPLACE)), s2 = new Set(i3.slice(0, r3));\n if (this.ALWAYS_RIP_INTERSECTIONS) {\n const n3 = function(e36) {\n const { section: t3, nodePfMap: n4, capacityMeshNodeMap: o4, nodeAssignedPortPoints: i4, acceptablePf: r4 } = e36, s3 = [];\n for (const e37 of t3.nodeIds) {\n if ((n4.get(e37) ?? 0) \u003c= r4)\n continue;\n const t4 = o4.get(e37);\n if (!t4)\n continue;\n const a3 = i4.get(e37) ?? [];\n if (a3.length \u003c 2)\n continue;\n const c3 = t4.center.x - t4.width / 2, l3 = t4.center.x + t4.width / 2, h2 = t4.center.y - t4.height / 2, d2 = t4.center.y + t4.height / 2, u2 = new Map;\n for (const e38 of a3) {\n const t5 = u2.get(e38.connectionName) ?? [];\n t5.some((t6) =\u003e t6.x === e38.x \u0026\u0026 t6.y === e38.y \u0026\u0026 t6.z === e38.z) || t5.push({ x: e38.x, y: e38.y, z: e38.z }), u2.set(e38.connectionName, t5);\n }\n const p3 = new Map;\n for (const [e38, t5] of u2) {\n if (t5.length \u003c 2)\n continue;\n const n5 = t5[0], o5 = t5[1];\n if (n5.z !== o5.z)\n continue;\n const i5 = Xz(n5, c3, l3, h2, d2), r5 = Xz(o5, c3, l3, h2, d2), s4 = n5.z, a4 = p3.get(s4) ?? [];\n a4.push({ connectionName: e38, t1: i5, t2: r5 }), p3.set(s4, a4);\n }\n const m2 = 0.000001;\n for (const [, e38] of p3) {\n const t5 = e38.map((e39) =\u003e ({ connectionName: e39.connectionName, a: Math.min(e39.t1, e39.t2), b: Math.max(e39.t1, e39.t2) }));\n for (let e39 = 0;e39 \u003c t5.length; e39++) {\n const { connectionName: n5, a: o5, b: i5 } = t5[e39];\n for (let r5 = e39 + 1;r5 \u003c t5.length; r5++) {\n const { connectionName: e40, a: a4, b: c4 } = t5[r5];\n Math.abs(o5 - a4) \u003c m2 || Math.abs(o5 - c4) \u003c m2 || Math.abs(i5 - a4) \u003c m2 || Math.abs(i5 - c4) \u003c m2 || (o5 \u003c a4 \u0026\u0026 a4 \u003c i5 \u0026\u0026 i5 \u003c c4 || a4 \u003c o5 \u0026\u0026 o5 \u003c c4 \u0026\u0026 c4 \u003c i5) \u0026\u0026 s3.push([n5, e40]);\n }\n }\n }\n }\n return s3;\n }({ section: e35, nodePfMap: this.nodePfMap, capacityMeshNodeMap: this.capacityMeshNodeMap, nodeAssignedPortPoints: this.nodeAssignedPortPoints, acceptablePf: this.ACCEPTABLE_PF });\n for (const [e36, i4] of n3) {\n if (s2.has(e36) || s2.has(i4))\n continue;\n const n4 = t2.includes(e36), r4 = t2.includes(i4);\n if (n4 \u0026\u0026 r4) {\n const t3 = o3() \u003c 0.5;\n s2.add(t3 ? e36 : i4);\n } else\n n4 ? s2.add(e36) : r4 \u0026\u0026 s2.add(i4);\n }\n }\n return this.stats.lastRipCount = s2.size, s2;\n }\n createSectionSimpleRouteJson(e35) {\n const t2 = [];\n this.currentSectionCutPathInfo.clear(), this.currentSectionKeptPortPoints.clear(), this.currentSectionFixedRoutes = [];\n const n2 = [], o3 = [];\n for (const t3 of this.connectionResults) {\n if (!t3.path || t3.path.length === 0)\n continue;\n const [i4, r4] = t3.nodeIds, s3 = e35.nodeIds.has(i4), a3 = e35.nodeIds.has(r4);\n s3 \u0026\u0026 a3 \u0026\u0026 (o3.push(t3), n2.push(t3.connection.name));\n }\n const i3 = [];\n for (const t3 of e35.sectionPaths) {\n if (!t3.hasEntryFromOutside \u0026\u0026 !t3.hasExitToOutside)\n continue;\n if (t3.points.length \u003c 2)\n continue;\n const e36 = this.connectionResults.find((e37) =\u003e e37.connection.name === t3.connectionName);\n e36 \u0026\u0026 (i3.push({ sectionPath: t3, originalResult: e36 }), n2.includes(t3.connectionName) || n2.push(t3.connectionName));\n }\n const r3 = this.determineConnectionsToRip(e35, n2);\n for (const e36 of o3)\n r3.has(e36.connection.name) \u0026\u0026 t2.push(e36.connection);\n for (const { sectionPath: e36, originalResult: n3 } of i3) {\n if (!r3.has(e36.connectionName))\n continue;\n const o4 = `__cut__${e36.connectionName}__${e36.originalStartIndex}`;\n this.colorMap[o4] = this.colorMap[e36.connectionName];\n const i4 = e36.points[0], s3 = e36.points[e36.points.length - 1], a3 = { name: o4, __rootConnectionNames: [e36.rootConnectionName ?? e36.connectionName], pointsToConnect: [{ x: i4.x, y: i4.y, layers: [`layer${i4.z + 1}`] }, { x: s3.x, y: s3.y, layers: [`layer${s3.z + 1}`] }] };\n t2.push(a3), this.currentSectionCutPathInfo.set(o4, { sectionPath: e36, originalConnectionResult: n3 });\n }\n const s2 = new Set(n2.filter((e36) =\u003e !r3.has(e36)));\n if (s2.size \u003e 0) {\n for (const t3 of e35.nodeIds) {\n const e36 = (this.nodeAssignedPortPoints.get(t3) ?? []).filter((e37) =\u003e s2.has(e37.connectionName));\n e36.length \u003e 0 \u0026\u0026 this.currentSectionKeptPortPoints.set(t3, e36);\n }\n for (const e36 of o3)\n s2.has(e36.connection.name) \u0026\u0026 this.currentSectionFixedRoutes.push(e36);\n for (const { sectionPath: e36, originalResult: t3 } of i3)\n if (s2.has(e36.connectionName)) {\n const n3 = { connection: { name: e36.connectionName, __rootConnectionNames: e36.rootConnectionName ? [e36.rootConnectionName] : undefined, pointsToConnect: t3.connection.pointsToConnect }, path: e36.points.map((e37) =\u003e ({ prevCandidate: null, portPoint: null, currentNodeId: e37.nodeId, point: { x: e37.x, y: e37.y }, z: e37.z, f: 0, g: 0, h: 0, distanceTraveled: 0 })), portPoints: e36.points.map((t4) =\u003e ({ portPointId: t4.portPointId, x: t4.x, y: t4.y, z: t4.z, connectionName: e36.connectionName, rootConnectionName: e36.rootConnectionName })), nodeIds: t3.nodeIds, straightLineDistance: t3.straightLineDistance };\n this.currentSectionFixedRoutes.push(n3);\n }\n }\n return { ...this.simpleRouteJson, connections: t2 };\n }\n prepareSectionInputNodesForCutPaths(e35) {\n const t2 = new Set;\n for (const [, e36] of this.currentSectionCutPathInfo.entries()) {\n const { sectionPath: n2 } = e36;\n if (n2.points.length === 0)\n continue;\n const o3 = n2.points[0].nodeId;\n t2.add(o3);\n const i3 = n2.points[n2.points.length - 1].nodeId;\n t2.add(i3);\n }\n return e35.inputNodes.map((e36) =\u003e t2.has(e36.capacityMeshNodeId) ? { ...e36, _containsTarget: true } : e36);\n }\n getHyperParametersForScheduleIndex(e35, t2) {\n const n2 = this.HYPERPARAMETER_SCHEDULE[e35];\n return { ...n2, SHUFFLE_SEED: (n2.SHUFFLE_SEED ?? 0) + 17 * t2 };\n }\n createSectionSolver(e35) {\n const t2 = this.createSectionSimpleRouteJson(e35), n2 = this.prepareSectionInputNodesForCutPaths(e35), o3 = zz(t2, n2);\n for (const [e36, t3] of this.currentSectionKeptPortPoints) {\n const n3 = o3.nodeAssignedPortPoints.get(e36) ?? [];\n o3.nodeAssignedPortPoints.set(e36, [...n3, ...t3]);\n }\n return new Kz({ simpleRouteJson: t2, inputNodes: n2, capacityMeshNodes: e35.capacityMeshNodes, colorMap: this.colorMap, nodeMemoryPfMap: this.nodePfMap, numShuffleSeeds: this.SHUFFLE_SEEDS_PER_SECTION ?? 2 * t2.connections.length * this.effort, hyperParameters: { ...this.getHyperParametersForScheduleIndex(this.currentScheduleIndex, this.sectionAttempts) }, precomputedInitialParams: o3, fixedRoutes: this.currentSectionFixedRoutes });\n }\n reattachSection(e35, t2, n2, o3) {\n const i3 = [], r3 = [];\n for (const e36 of t2)\n e36.connection.name.startsWith(\"__cut__\") ? r3.push(e36) : i3.push(e36);\n const s2 = new Set(i3.map((e36) =\u003e e36.connection.name));\n this.connectionResults = this.connectionResults.filter((e36) =\u003e !s2.has(e36.connection.name)), this.connectionResults.push(...i3);\n for (const [t3, n3] of this.nodeAssignedPortPoints.entries()) {\n if (!e35.nodeIds.has(t3))\n continue;\n const o4 = n3.filter((e36) =\u003e !s2.has(e36.connectionName));\n this.nodeAssignedPortPoints.set(t3, o4);\n }\n for (const [e36, t3] of this.assignedPortPoints.entries())\n s2.has(t3.connectionName) \u0026\u0026 this.assignedPortPoints.delete(e36);\n for (const t3 of r3) {\n const n3 = this.currentSectionCutPathInfo.get(t3.connection.name);\n if (!n3 || !t3.path)\n continue;\n const { sectionPath: o4, originalConnectionResult: i4 } = n3, r4 = i4.path;\n if (!r4)\n continue;\n const s3 = o4.connectionName;\n for (const [t4, n4] of this.nodeAssignedPortPoints.entries()) {\n const o5 = n4.filter((n5) =\u003e n5.connectionName !== s3 || !e35.nodeIds.has(t4));\n this.nodeAssignedPortPoints.set(t4, o5);\n }\n const a3 = r4.slice(0, o4.originalStartIndex), c3 = r4.slice(o4.originalEndIndex + 1), l3 = [];\n let h2 = a3.length \u003e 0 ? a3[a3.length - 1] : null;\n for (const e36 of t3.path) {\n const t4 = { ...e36, prevCandidate: h2 };\n l3.push(t4), h2 = t4;\n }\n if (c3.length \u003e 0 \u0026\u0026 l3.length \u003e 0 \u0026\u0026 (c3[0] = { ...c3[0], prevCandidate: l3[l3.length - 1] }), i4.path = [...a3, ...l3, ...c3], t3.portPoints)\n for (const n4 of t3.portPoints) {\n const t4 = { ...n4, connectionName: s3, rootConnectionName: o4.rootConnectionName ?? s3 };\n for (const o5 of e35.inputNodes)\n for (const e36 of o5.portPoints)\n if (Math.abs(e36.x - n4.x) \u003c 0.001 \u0026\u0026 Math.abs(e36.y - n4.y) \u003c 0.001 \u0026\u0026 e36.z === n4.z) {\n for (const n5 of e36.connectionNodeIds) {\n const e37 = this.nodeAssignedPortPoints.get(n5) ?? [];\n e37.push(t4), this.nodeAssignedPortPoints.set(n5, e37);\n }\n break;\n }\n }\n }\n for (const [e36, t3] of n2.entries())\n t3.connectionName.startsWith(\"__cut__\") || this.assignedPortPoints.set(e36, t3);\n for (const [e36, t3] of o3.entries()) {\n const n3 = t3.filter((e37) =\u003e !e37.connectionName.startsWith(\"__cut__\"));\n if (n3.length \u003e 0) {\n const t4 = this.nodeAssignedPortPoints.get(e36) ?? [];\n this.nodeAssignedPortPoints.set(e36, [...t4, ...n3]);\n }\n }\n }\n _step() {\n if (this.activeSubSolver) {\n if (this.activeSubSolver.step(), this.activeSubSolver.solved || this.activeSubSolver.failed) {\n if (this.activeSubSolver.failed) {\n if (this.currentScheduleIndex++, this.activeSubSolver.error \u0026\u0026 this.stats.errors++, this.currentScheduleIndex \u003c this.HYPERPARAMETER_SCHEDULE.length \u0026\u0026 this.currentSectionCenterNodeId) {\n const e37 = this.HYPERPARAMETER_SCHEDULE[this.currentScheduleIndex];\n this.currentSection = this.createSection({ centerOfSectionCapacityNodeId: this.currentSectionCenterNodeId, expansionDegrees: e37.EXPANSION_DEGREES }), this.activeSubSolver = this.createSectionSolver(this.currentSection);\n } else\n this.stats.failedOptimizations++, this.activeSubSolver = null, this.currentSection = null, this.currentSectionCenterNodeId = null, this.currentScheduleIndex = 0;\n return;\n }\n const e36 = this.activeSubSolver.getNodesWithPortPoints().map((e37) =\u003e ({ ...e37, portPoints: e37.portPoints.map((e38) =\u003e {\n if (e38.connectionName.startsWith(\"__cut__\")) {\n const t4 = e38.connectionName.slice(7), n4 = t4.lastIndexOf(\"__\"), o4 = n4 \u003e= 0 ? t4.slice(0, n4) : t4;\n return { ...e38, connectionName: o4 };\n }\n return e38;\n }) })), t3 = new Set;\n for (const n4 of e36)\n for (const e37 of n4.portPoints)\n t3.add(e37.connectionName);\n const n3 = this.getSectionNodesWithPortPoints(this.currentSection).map((e37) =\u003e ({ ...e37, portPoints: e37.portPoints.filter((e38) =\u003e t3.has(e38.connectionName)) })).filter((e37) =\u003e e37.portPoints.length \u003e 0), o3 = this.computeScoreForNodes(n3), i3 = this.computeScoreForNodes(e36), r3 = `attempt${this.sectionAttempts}`;\n if (this.stats.lastSectionScore = i3, i3 \u003e o3) {\n const e37 = this.stats.currentBoardScore;\n this.stats.lastBoardScore = e37;\n const t4 = [...this.connectionResults], n4 = new Map(this.assignedPortPoints), o4 = new Map(Array.from(this.nodeAssignedPortPoints.entries()).map(([e38, t5]) =\u003e [e38, [...t5]]));\n this.reattachSection(this.currentSection, this.activeSubSolver.connectionsWithResults, this.activeSubSolver.assignedPortPoints, this.activeSubSolver.nodeAssignedPortPoints), this.recomputePfForNodes(this.currentSection.nodeIds);\n const i4 = this.computeBoardScore();\n this.stats.sectionScores[r3] = i4, i4 \u003e e37 ? (this.stats.successfulOptimizations++, this.stats.currentBoardScore = i4) : (this.connectionResults = t4, this.assignedPortPoints = n4, this.nodeAssignedPortPoints = o4, this.recomputePfForNodes(this.currentSection.nodeIds), this.stats.failedOptimizations++), this.activeSubSolver = null, this.currentSection = null, this.currentSectionCenterNodeId = null, this.currentScheduleIndex = 0;\n } else if (this.currentScheduleIndex++, this.currentScheduleIndex \u003c this.HYPERPARAMETER_SCHEDULE.length \u0026\u0026 this.currentSectionCenterNodeId) {\n const e37 = this.HYPERPARAMETER_SCHEDULE[this.currentScheduleIndex];\n this.currentSection = this.createSection({ centerOfSectionCapacityNodeId: this.currentSectionCenterNodeId, expansionDegrees: e37.EXPANSION_DEGREES }), this.activeSubSolver = this.createSectionSolver(this.currentSection);\n } else\n this.stats.failedOptimizations++, this.activeSubSolver = null, this.currentSection = null, this.currentSectionCenterNodeId = null, this.currentScheduleIndex = 0;\n }\n return;\n }\n if (this.sectionAttempts \u003e= this.MAX_SECTION_ATTEMPTS)\n return void (this.solved = true);\n const e35 = this.findHighestPfNode();\n if (!e35)\n return void (this.solved = true);\n this.sectionAttempts++, this.stats.sectionAttempts = this.sectionAttempts, this.stats.nodesExamined++, this.attemptsToFixNode.set(e35, (this.attemptsToFixNode.get(e35) ?? 0) + 1), this.currentSectionCenterNodeId = e35, this.currentScheduleIndex = 0;\n const t2 = this.HYPERPARAMETER_SCHEDULE[this.currentScheduleIndex];\n this.currentSection = this.createSection({ centerOfSectionCapacityNodeId: e35, expansionDegrees: t2.EXPANSION_DEGREES });\n const n2 = this.getSectionNodesWithPortPoints(this.currentSection);\n this.sectionScoreBeforeOptimization = this.computeScoreForNodes(n2);\n if (this.createSectionSimpleRouteJson(this.currentSection).connections.length === 0)\n return this.currentSection = null, void (this.currentSectionCenterNodeId = null);\n this.activeSubSolver = this.createSectionSolver(this.currentSection);\n }\n computeProgress() {\n return this.sectionAttempts / this.MAX_SECTION_ATTEMPTS;\n }\n visualize() {\n return this.solved ? qz(this) : this.activeSubSolver ? this.activeSubSolver.visualize() : this.currentSection ? function(e35, t2) {\n const n2 = { lines: [], points: [], rects: [], circles: [] };\n for (const t3 of e35.inputNodes) {\n const o3 = t3.capacityMeshNodeId === e35.centerNodeId, i3 = o3 ? \"rgba(0, 200, 0, 0.3)\" : \"rgba(200, 200, 200, 0.3)\";\n n2.rects.push({ center: t3.center, width: 0.9 * t3.width, height: 0.9 * t3.height, layer: `z${t3.availableZ.join(\",\")}`, fill: i3, label: `${t3.capacityMeshNodeId}${o3 ? \" (CENTER)\" : \"\"}` });\n }\n for (const t3 of e35.inputNodes)\n for (const e36 of t3.portPoints) {\n const t4 = \"rgba(150, 150, 150, 0.5)\";\n n2.circles.push({ center: { x: e36.x, y: e36.y }, radius: 0.05, fill: t4, layer: `z${e36.z}`, label: [e36.portPointId, `cd: ${e36.distToCentermostPortOnZ}`, `connects: ${e36.connectionNodeIds.join(\",\")}`].filter(Boolean).join(`\n`) });\n }\n for (const o3 of e35.sectionPaths) {\n const e36 = t2?.[o3.connectionName] ?? \"blue\";\n for (let t3 = 0;t3 \u003c o3.points.length - 1; t3++) {\n const i3 = o3.points[t3], r3 = o3.points[t3 + 1], s2 = i3.z === r3.z, a3 = i3.z;\n let c3;\n c3 = s2 ? a3 === 0 ? \"5 5\" : \"10 5\" : \"3 3 10\", n2.lines.push({ points: [{ x: i3.x, y: i3.y }, { x: r3.x, y: r3.y }], strokeColor: e36, strokeDash: c3 });\n }\n }\n return n2;\n }(this.currentSection, this.colorMap) : qz(this);\n }\n};\nvar oB = class {\n parent = {};\n constructor(e35) {\n for (const t2 of e35)\n this.parent[t2] = t2;\n }\n find(e35) {\n return this.parent[e35] === e35 ? e35 : this.parent[e35] = this.find(this.parent[e35]);\n }\n union(e35, t2) {\n const n2 = this.find(e35), o3 = this.find(t2);\n n2 !== o3 \u0026\u0026 (this.parent[o3] = n2);\n }\n getGroup(e35) {\n const t2 = this.find(e35), n2 = [];\n for (const e36 in this.parent)\n this.find(e36) === t2 \u0026\u0026 n2.push(e36);\n return n2;\n }\n};\nvar iB = class {\n point;\n left = null;\n right = null;\n constructor(e35) {\n this.point = e35;\n }\n};\nvar rB = class {\n root = null;\n constructor(e35) {\n e35.length \u003e 0 \u0026\u0026 (this.root = this.buildTree(e35, 0));\n }\n buildTree(e35, t2) {\n const n2 = t2 % 2 == 0 ? \"x\" : \"y\";\n e35.sort((e36, t3) =\u003e e36[n2] - t3[n2]);\n const o3 = Math.floor(e35.length / 2), i3 = new iB(e35[o3]);\n return o3 \u003e 0 \u0026\u0026 (i3.left = this.buildTree(e35.slice(0, o3), t2 + 1)), o3 \u003c e35.length - 1 \u0026\u0026 (i3.right = this.buildTree(e35.slice(o3 + 1), t2 + 1)), i3;\n }\n findNearestNeighbor(e35) {\n if (!this.root)\n throw new Error(\"Tree is empty\");\n const t2 = this.root.point, n2 = this.distance(e35, t2);\n return this.nearestNeighborSearch(this.root, e35, 0, t2, n2), t2;\n }\n nearestNeighborSearch(e35, t2, n2, o3, i3) {\n if (!e35)\n return o3;\n const r3 = n2 % 2 ? \"x\" : \"y\", s2 = this.distance(t2, e35.point);\n s2 \u003c i3 \u0026\u0026 (o3 = e35.point, i3 = s2);\n const a3 = t2[r3] - e35.point[r3], c3 = a3 \u003c= 0 ? e35.left : e35.right, l3 = a3 \u003c= 0 ? e35.right : e35.left;\n return o3 = this.nearestNeighborSearch(c3, t2, n2 + 1, o3, i3), i3 = this.distance(t2, o3), Math.abs(a3) \u003c i3 \u0026\u0026 (o3 = this.nearestNeighborSearch(l3, t2, n2 + 1, o3, i3)), o3;\n }\n findKNearestNeighbors(e35, t2) {\n if (!this.root)\n return [];\n const n2 = [];\n return this.kNearestNeighborSearch(this.root, e35, 0, n2, t2), n2.sort((e36, t3) =\u003e e36.distance - t3.distance).slice(0, t2).map((e36) =\u003e e36.point);\n }\n kNearestNeighborSearch(e35, t2, n2, o3, i3) {\n if (!e35)\n return;\n const r3 = n2 % 2 ? \"x\" : \"y\", s2 = this.distance(t2, e35.point);\n o3.push({ point: e35.point, distance: s2 });\n const a3 = t2[r3] - e35.point[r3], c3 = a3 \u003c= 0 ? e35.left : e35.right, l3 = a3 \u003c= 0 ? e35.right : e35.left;\n this.kNearestNeighborSearch(c3, t2, n2 + 1, o3, i3);\n let h2 = 1 / 0;\n o3.length \u003e= i3 \u0026\u0026 (o3.sort((e36, t3) =\u003e e36.distance - t3.distance), h2 = o3[i3 - 1]?.distance || 1 / 0), (Math.abs(a3) \u003c h2 || o3.length \u003c i3) \u0026\u0026 this.kNearestNeighborSearch(l3, t2, n2 + 1, o3, i3);\n }\n distance(e35, t2) {\n return Math.sqrt((e35.x - t2.x) ** 2 + (e35.y - t2.y) ** 2);\n }\n};\nvar sB = class {\n parent = new Map;\n rank = new Map;\n componentCount;\n constructor(e35) {\n for (const t2 of e35) {\n const e36 = this.pointToKey(t2);\n this.parent.set(e36, e36), this.rank.set(e36, 0);\n }\n this.componentCount = this.parent.size;\n }\n pointToKey(e35) {\n return `${e35.x},${e35.y}`;\n }\n find(e35) {\n const t2 = this.pointToKey(e35);\n if (!this.parent.has(t2))\n throw new Error(`Point ${t2} not found in DisjointSet`);\n let n2 = t2;\n for (;n2 !== this.parent.get(n2); )\n n2 = this.parent.get(n2);\n let o3 = t2;\n for (;o3 !== n2; ) {\n const e36 = this.parent.get(o3);\n this.parent.set(o3, n2), o3 = e36;\n }\n return n2;\n }\n union(e35, t2) {\n const n2 = this.find(e35), o3 = this.find(t2);\n if (n2 === o3)\n return false;\n const i3 = this.rank.get(n2) || 0, r3 = this.rank.get(o3) || 0;\n return i3 \u003c r3 ? this.parent.set(n2, o3) : i3 \u003e r3 ? this.parent.set(o3, n2) : (this.parent.set(o3, n2), this.rank.set(n2, i3 + 1)), this.componentCount -= 1, true;\n }\n};\nfunction aB(e35, t2 = {}) {\n if (e35.length \u003c= 1)\n return [];\n const n2 = [...e35], o3 = new rB(n2);\n let i3 = Math.min(10, e35.length - 1);\n for (;; ) {\n const r3 = [];\n for (const e36 of n2) {\n const t3 = o3.findKNearestNeighbors(e36, i3 + 1);\n for (const n3 of t3) {\n if (e36.x === n3.x \u0026\u0026 e36.y === n3.y)\n continue;\n const t4 = Math.sqrt((e36.x - n3.x) ** 2 + (e36.y - n3.y) ** 2);\n r3.push({ from: e36, to: n3, weight: t4 });\n }\n }\n t2.extraEdges \u0026\u0026 r3.push(...t2.extraEdges), r3.sort((e36, t3) =\u003e e36.weight - t3.weight);\n const s2 = new sB(n2), a3 = [];\n for (const e36 of r3)\n if (s2.union(e36.from, e36.to) \u0026\u0026 (a3.push(e36), a3.length === n2.length - 1))\n break;\n if (s2.componentCount === 1)\n return a3;\n i3 = Math.min(2 * i3, e35.length - 1);\n }\n}\nvar cB = (e35, t2) =\u003e {\n const n2 = new Map;\n for (const o4 of e35.pointsToConnect) {\n if (!o4.pointId)\n continue;\n const e36 = t2.getNetConnectedToId(o4.pointId);\n if (!e36)\n continue;\n const i3 = n2.get(e36) ?? [];\n i3.push(o4), n2.set(e36, i3);\n }\n const o3 = [];\n for (const e36 of n2.values()) {\n const t3 = e36[0];\n if (t3)\n for (const n3 of e36.slice(1))\n o3.push({ from: t3, to: n3, weight: 0 });\n }\n return o3;\n};\nvar lB = (e35, t2) =\u003e ({ zeroWeightEdges: cB(e35, t2), arePointsConnected: (e36, n2) =\u003e Boolean(e36.pointId \u0026\u0026 n2.pointId \u0026\u0026 ((e37, t3, n3) =\u003e {\n const o3 = e37.getNetConnectedToId(t3);\n return !!o3 \u0026\u0026 o3 === e37.getNetConnectedToId(n3);\n})(t2, e36.pointId, n2.pointId)) });\nfunction hB(e35) {\n if (e35.pointId)\n return e35.pointId;\n const t2 = [...So(e35)].sort().join(\"-\");\n return `${e35.x.toFixed(4)},${e35.y.toFixed(4)},${t2}`;\n}\nfunction dB(e35) {\n if (e35.length === 0)\n return [];\n const t2 = e35.map((e36, t3) =\u003e `conn_${t3}`), n2 = new oB(t2), o3 = new Map;\n e35.forEach((e36, t3) =\u003e {\n const n3 = `conn_${t3}`;\n e36.pointsToConnect.forEach((e37) =\u003e {\n const t4 = hB(e37);\n o3.has(t4) || o3.set(t4, []), o3.get(t4).push(n3);\n });\n });\n for (const e36 of o3.values())\n if (e36.length \u003e 1) {\n const t3 = e36[0];\n for (let o4 = 1;o4 \u003c e36.length; o4++)\n n2.union(t3, e36[o4]);\n }\n const i3 = new Map;\n e35.forEach((e36, t3) =\u003e {\n const o4 = `conn_${t3}`, r4 = n2.find(o4);\n i3.has(r4) || i3.set(r4, []), i3.get(r4).push(e36);\n });\n const r3 = [];\n for (const e36 of i3.values()) {\n if (e36.length === 1) {\n r3.push(e36[0]);\n continue;\n }\n const t3 = new Map, n3 = new Set;\n let o4 = false;\n const i4 = [], s2 = new Set;\n let a3;\n e36.forEach((e37) =\u003e {\n e37.pointsToConnect.forEach((e38) =\u003e t3.set(hB(e38), e38));\n const r4 = e37.__rootConnectionNames;\n if (r4 \u0026\u0026 r4.length \u003e 0)\n for (const e38 of r4)\n n3.add(e38);\n else\n n3.add(e37.name);\n e37.isOffBoard \u0026\u0026 (o4 = true), e37.externallyConnectedPointIds \u0026\u0026 i4.push(...e37.externallyConnectedPointIds), e37.__netConnectionName \u0026\u0026 s2.add(e37.__netConnectionName), a3 === undefined \u0026\u0026 e37.nominalTraceWidth !== undefined \u0026\u0026 (a3 = e37.nominalTraceWidth);\n });\n const c3 = { name: e36.map((e37) =\u003e e37.name).join(\"__\"), pointsToConnect: Array.from(t3.values()), isOffBoard: o4, externallyConnectedPointIds: i4.length \u003e 0 ? i4 : undefined, __netConnectionName: s2.size \u003e 0 ? Array.from(s2).join(\"__\") : undefined, __rootConnectionNames: Array.from(n3), nominalTraceWidth: a3 };\n r3.push(c3);\n }\n return r3;\n}\nvar uB = class extends ni {\n constructor(e35, t2 = {}, n2) {\n super(), this.ogSrj = e35, this.colorMap = t2;\n const o3 = new Map;\n for (const t3 of e35.buses ?? [])\n if (t3.traceWidth !== undefined)\n for (const e36 of t3.connectionNames)\n o3.set(e36, Math.max(o3.get(e36) ?? 0, t3.traceWidth));\n const i3 = e35.connections.map((e36) =\u003e {\n const t3 = o3.get(e36.name);\n return t3 === undefined ? e36 : { ...e36, nominalTraceWidth: Math.max(e36.nominalTraceWidth ?? 0, t3) };\n });\n this.unprocessedConnections = dB(i3), this.newConnections = [], this.initiallyConnectedMap = n2;\n }\n getSolverName() {\n return \"NetToPointPairsSolver\";\n }\n unprocessedConnections;\n newConnections;\n initiallyConnectedMap;\n _step() {\n if (this.unprocessedConnections.length === 0)\n return void (this.solved = true);\n const e35 = this.unprocessedConnections.pop(), { zeroWeightEdges: t2, arePointsConnected: n2 } = lB(e35, this.initiallyConnectedMap);\n if (e35.pointsToConnect.length === 2) {\n const [t3, o4] = e35.pointsToConnect;\n if (t3 \u0026\u0026 o4 \u0026\u0026 n2(t3, o4))\n return;\n return void this.newConnections.push({ ...e35, __rootConnectionNames: e35.__rootConnectionNames ?? [e35.name] });\n }\n const o3 = aB(e35.pointsToConnect, { extraEdges: t2 });\n let i3 = 0;\n for (const t3 of o3)\n n2(t3.from, t3.to) || this.newConnections.push({ ...e35, pointsToConnect: [t3.from, t3.to], name: `${e35.name}_mst${i3++}`, __rootConnectionNames: e35.__rootConnectionNames ?? [e35.name], __netConnectionName: e35.__netConnectionName });\n }\n getNewSimpleRouteJson() {\n return { ...structuredClone(this.ogSrj), connections: structuredClone(this.newConnections) };\n }\n visualize() {\n const e35 = { lines: [], points: [], rects: [], circles: [], coordinateSystem: \"cartesian\", title: \"Net To Point Pairs Visualization\" };\n return this.unprocessedConnections.forEach((t2) =\u003e {\n t2.pointsToConnect.forEach((t3) =\u003e {\n e35.points.push({ x: t3.x, y: t3.y, color: \"red\", label: t3.pcb_port_id ?? t3.pointId });\n });\n const n2 = t2.pointsToConnect.length ** 2, o3 = vr(0), i3 = new Set;\n for (let r3 = 0;r3 \u003c Math.max(n2, 2 * t2.pointsToConnect.length); r3++) {\n const n3 = Math.floor(o3() * t2.pointsToConnect.length), r4 = Math.floor(o3() * t2.pointsToConnect.length);\n i3.has(`${n3}-${r4}`) || (i3.add(`${n3}-${r4}`), e35.lines.push({ points: [t2.pointsToConnect[n3], t2.pointsToConnect[r4]], strokeColor: \"rgba(255,0,0,0.25)\", label: t2.name }));\n }\n }), this.newConnections.forEach((t2) =\u003e {\n const n2 = this.colorMap?.[t2.name] || \"blue\";\n t2.pointsToConnect.forEach((t3) =\u003e {\n e35.points.push({ x: t3.x, y: t3.y, color: n2, label: t3.pcb_port_id ?? t3.pointId });\n });\n for (let o3 = 0;o3 \u003c t2.pointsToConnect.length - 1; o3++)\n for (let i3 = o3 + 1;i3 \u003c t2.pointsToConnect.length; i3++)\n e35.lines.push({ points: [t2.pointsToConnect[o3], t2.pointsToConnect[i3]], strokeColor: n2, label: t2.name });\n }), e35;\n }\n};\nvar pB = class extends uB {\n constructor(e35, t2 = {}, n2) {\n const o3 = e35.connections.flatMap((e36) =\u003e e36.pointsToConnect), i3 = new Map;\n for (const e36 of o3)\n e36.pointId \u0026\u0026 i3.set(e36.pointId, e36);\n const r3 = o3.map((e36) =\u003e e36.pointId).filter((e36) =\u003e !!e36), s2 = new oB(r3), a3 = [];\n for (const t3 of e35.connections)\n t3.isOffBoard ? t3.pointsToConnect.length \u003e= 2 \u0026\u0026 t3.pointsToConnect[0].pointId \u0026\u0026 t3.pointsToConnect[1].pointId \u0026\u0026 s2.union(t3.pointsToConnect[0].pointId, t3.pointsToConnect[1].pointId) : a3.push(t3);\n super({ ...e35, connections: a3 }, t2, n2), this.ogSrj = e35, this.colorMap = t2, this.connectionPointDsu = s2, this.connectionPointMap = i3, this.ogSrj = e35;\n }\n getSolverName() {\n return \"NetToPointPairsSolver2_OffBoardConnection\";\n }\n connectionPointDsu;\n connectionPointMap;\n _findBestConnectionPointsFromDisjointSets(e35, t2) {\n if (!e35.pointId || !t2.pointId)\n return { pointsToConnect: [e35, t2] };\n const n2 = this.connectionPointDsu.getGroup(e35.pointId).map((e36) =\u003e this.connectionPointMap.get(e36)), o3 = this.connectionPointDsu.getGroup(t2.pointId).map((e36) =\u003e this.connectionPointMap.get(e36));\n let i3 = e35, r3 = t2, s2 = 1 / 0;\n for (const e36 of n2)\n for (const t3 of o3) {\n const n3 = Math.sqrt(Math.pow(e36.x - t3.x, 2) + Math.pow(e36.y - t3.y, 2));\n n3 \u003c s2 \u0026\u0026 (s2 = n3, i3 = e36, r3 = t3);\n }\n return { pointsToConnect: [i3, r3] };\n }\n _step() {\n if (this.unprocessedConnections.length === 0)\n return void (this.solved = true);\n const e35 = this.unprocessedConnections.pop(), { zeroWeightEdges: t2, arePointsConnected: n2 } = lB(e35, this.initiallyConnectedMap);\n if (e35.pointsToConnect.length === 2) {\n const [t3, o4] = e35.pointsToConnect;\n if (t3 \u0026\u0026 o4 \u0026\u0026 n2(t3, o4))\n return;\n const i4 = this._findBestConnectionPointsFromDisjointSets(e35.pointsToConnect[0], e35.pointsToConnect[1]);\n return void this.newConnections.push({ ...e35, pointsToConnect: i4.pointsToConnect, __rootConnectionNames: e35.__rootConnectionNames ?? [e35.name] });\n }\n const o3 = aB(e35.pointsToConnect, { extraEdges: t2 });\n let i3 = 0;\n for (const t3 of o3) {\n if (n2(t3.from, t3.to))\n continue;\n const o4 = this._findBestConnectionPointsFromDisjointSets(t3.from, t3.to);\n this.newConnections.push({ ...e35, pointsToConnect: o4.pointsToConnect, name: `${e35.name}_mst${i3++}`, __rootConnectionNames: e35.__rootConnectionNames ?? [e35.name], __netConnectionName: e35.__netConnectionName });\n }\n }\n};\nvar mB = class {\n netMap;\n idToNetMap;\n constructor(e35) {\n this.netMap = e35, this.idToNetMap = {};\n for (const [t2, n2] of Object.entries(e35))\n for (const e36 of n2)\n this.idToNetMap[e36] = t2;\n }\n addConnections(e35) {\n for (const t2 of e35) {\n const e36 = new Set;\n for (const n3 of t2) {\n const t3 = this.idToNetMap[n3];\n t3 \u0026\u0026 e36.add(t3);\n }\n let n2;\n if (e36.size === 0)\n n2 = `connectivity_net${Object.keys(this.netMap).length}`, this.netMap[n2] = [];\n else if (e36.size === 1)\n n2 = e36.values().next().value ?? `connectivity_net${Object.keys(this.netMap).length}`;\n else {\n n2 = e36.values().next().value ?? `connectivity_net${Object.keys(this.netMap).length}`;\n for (const t3 of e36)\n if (t3 !== n2) {\n const e37 = this.netMap[n2], o3 = this.netMap[t3];\n if (e37 \u0026\u0026 o3) {\n e37.push(...o3), this.netMap[t3] = e37;\n for (const t4 of e37)\n this.idToNetMap[t4] = n2;\n }\n }\n }\n for (const e37 of t2) {\n const t3 = this.netMap[n2];\n t3 \u0026\u0026 !t3.includes(e37) \u0026\u0026 t3.push(e37), this.idToNetMap[e37] = n2;\n }\n }\n }\n getIdsConnectedToNet(e35) {\n return this.netMap[e35] || [];\n }\n getNetConnectedToId(e35) {\n return this.idToNetMap[e35];\n }\n areIdsConnected(e35, t2) {\n if (e35 === t2)\n return true;\n const n2 = this.getNetConnectedToId(e35);\n if (!n2)\n return false;\n const o3 = this.getNetConnectedToId(t2);\n return !!o3 \u0026\u0026 (n2 === o3 || o3 === e35 || o3 === e35);\n }\n areAllIdsConnected(e35) {\n if (e35.length === 0)\n return true;\n const t2 = this.getNetConnectedToId(e35[0]);\n if (!t2)\n return false;\n for (const n2 of e35) {\n const e36 = this.getNetConnectedToId(n2);\n if (e36 === undefined)\n return false;\n if (e36 !== t2)\n return false;\n }\n return true;\n }\n};\nfunction gB(e35, t2 = {}) {\n const n2 = [], o3 = [], i3 = t2.color ?? \"gray\", r3 = t2.label, s2 = Xo[e35.footprint] ?? Xo[\"0603\"], a3 = e35.end.x - e35.start.x, c3 = e35.end.y - e35.start.y, l3 = Math.abs(a3) \u003e Math.abs(c3), h2 = l3 ? s2.padLength : s2.padWidth, d2 = l3 ? s2.padWidth : s2.padLength;\n return n2.push({ center: e35.start, width: h2, height: d2, fill: Ao(i3, 0.5), stroke: \"rgba(0, 0, 0, 0.5)\", layer: \"jumper\", label: r3 ? `${r3} (start)` : undefined }), n2.push({ center: e35.end, width: h2, height: d2, fill: Ao(i3, 0.5), stroke: \"rgba(0, 0, 0, 0.5)\", layer: \"jumper\", label: r3 ? `${r3} (end)` : undefined }), o3.push({ points: [e35.start, e35.end], strokeColor: \"rgba(100, 100, 100, 0.8)\", strokeWidth: 0.3 * s2.padWidth, layer: \"jumper-body\" }), { rects: n2, lines: o3 };\n}\nfunction fB(e35, t2 = {}) {\n const n2 = { rects: [], lines: [] };\n for (const o3 of e35) {\n const { rects: e36, lines: i3 } = gB(o3, t2);\n n2.rects.push(...e36), n2.lines.push(...i3);\n }\n return n2;\n}\nvar _B = 1e5;\nvar yB = 0.001;\nvar bB = class extends ni {\n getSolverName() {\n return \"SingleHighDensityRouteStitchSolver\";\n }\n mergedHdRoute;\n remainingHdRoutes;\n start;\n end;\n colorMap;\n constructor(e35) {\n if (super(), this.remainingHdRoutes = [...e35.hdRoutes], this.colorMap = e35.colorMap ?? {}, e35.hdRoutes.length === 0) {\n this.start = e35.start, this.end = e35.end;\n const t3 = [{ x: e35.start.x, y: e35.start.y, z: e35.start.z }], n3 = [];\n return e35.start.z !== e35.end.z \u0026\u0026 (t3.push({ x: e35.start.x, y: e35.start.y, z: e35.end.z }), n3.push({ x: e35.start.x, y: e35.start.y })), t3.push({ x: e35.end.x, y: e35.end.y, z: e35.end.z }), this.mergedHdRoute = { connectionName: e35.connectionName, rootConnectionName: e35.hdRoutes[0]?.rootConnectionName, route: t3, vias: n3, jumpers: [], viaDiameter: e35.defaultViaDiameter ?? 0.3, traceThickness: e35.defaultTraceThickness ?? 0.15 }, void (this.solved = true);\n }\n let t2 = 1 / 0, n2 = e35.hdRoutes[0], o3 = \"start-to-end\";\n for (const i4 of e35.hdRoutes) {\n const r4 = i4.route[0], s3 = i4.route[i4.route.length - 1], a3 = me(e35.start, r4), c3 = me(e35.start, s3), l3 = me(e35.end, r4), h2 = me(e35.end, s3), d2 = Math.min(a3, c3, l3, h2);\n d2 \u003c t2 \u0026\u0026 (t2 = d2, n2 = i4, o3 = Math.min(l3, h2) \u003c Math.min(a3, c3) ? \"end-to-start\" : \"start-to-end\");\n }\n o3 === \"start-to-end\" ? (this.start = e35.start, this.end = e35.end) : (this.start = e35.end, this.end = e35.start);\n const i3 = n2.route[0], r3 = n2.route[n2.route.length - 1], s2 = me(this.start, i3) \u003c= me(this.start, r3) ? i3 : r3;\n this.mergedHdRoute = { connectionName: e35.connectionName, rootConnectionName: n2.rootConnectionName, route: [{ x: this.start.x, y: this.start.y, z: s2.z }], vias: [], jumpers: [], viaDiameter: n2.viaDiameter, traceThickness: n2.traceThickness };\n }\n getDisjointedRoute() {\n for (const e35 of this.remainingHdRoutes) {\n if ([e35.route[0], e35.route[e35.route.length - 1]].some((t2) =\u003e !this.remainingHdRoutes.some((n2) =\u003e {\n if (n2 === e35)\n return false;\n return [n2.route[0], n2.route[n2.route.length - 1]].some((e36) =\u003e e36.z === t2.z \u0026\u0026 me(t2, e36) \u003c 0.001);\n })))\n return { firstRoute: e35 };\n }\n return { firstRoute: this.remainingHdRoutes[0] };\n }\n _step() {\n if (this.remainingHdRoutes.length === 0) {\n const e36 = this.mergedHdRoute.route[this.mergedHdRoute.route.length - 1];\n return this.mergedHdRoute.route.push({ x: this.end.x, y: this.end.y, z: e36.z }), void (this.solved = true);\n }\n const e35 = this.mergedHdRoute.route[this.mergedHdRoute.route.length - 1];\n let t2 = -1, n2 = \"first\", o3 = 1 / 0;\n for (let i4 = 0;i4 \u003c this.remainingHdRoutes.length; i4++) {\n const r4 = this.remainingHdRoutes[i4], s2 = r4.route[0], a3 = r4.route[r4.route.length - 1], c3 = me(e35, s2), l3 = me(e35, a3);\n let h2 = 1 / 0;\n h2 = e35.z === s2.z ? c3 \u003c yB ? c3 : _B + c3 : c3 \u003c yB ? 1000 + c3 : _B + c3, h2 \u003c o3 \u0026\u0026 (o3 = h2, t2 = i4, n2 = \"first\");\n let d2 = 1 / 0;\n d2 = e35.z === a3.z ? l3 \u003c yB ? l3 : _B + l3 : l3 \u003c yB ? 1000 + l3 : _B + l3, d2 \u003c o3 \u0026\u0026 (o3 = d2, t2 = i4, n2 = \"last\");\n }\n if (t2 === -1)\n return void (this.remainingHdRoutes = []);\n const i3 = this.remainingHdRoutes[t2];\n let r3;\n this.remainingHdRoutes.splice(t2, 1), r3 = n2 === \"first\" ? i3.route : [...i3.route].reverse(), me(e35, r3[0]) \u003c yB \u0026\u0026 e35.z === r3[0].z ? this.mergedHdRoute.route.push(...r3.slice(1)) : this.mergedHdRoute.route.push(...r3), this.mergedHdRoute.vias.push(...i3.vias), i3.jumpers \u0026\u0026 this.mergedHdRoute.jumpers.push(...i3.jumpers);\n }\n visualize() {\n const e35 = { points: [], lines: [], circles: [], rects: [], title: \"Single High Density Route Stitch Solver\" };\n if (e35.points?.push({ x: this.start.x, y: this.start.y, color: \"green\", label: \"Start\" }, { x: this.end.x, y: this.end.y, color: \"red\", label: \"End\" }), this.mergedHdRoute \u0026\u0026 this.mergedHdRoute.route.length \u003e 1) {\n e35.lines?.push({ points: this.mergedHdRoute.route.map((e36) =\u003e ({ x: e36.x, y: e36.y })), strokeColor: \"green\" });\n for (const t2 of this.mergedHdRoute.route)\n e35.points?.push({ x: t2.x, y: t2.y, color: \"green\" });\n for (const t2 of this.mergedHdRoute.vias)\n e35.circles?.push({ center: { x: t2.x, y: t2.y }, radius: this.mergedHdRoute.viaDiameter / 2, fill: \"green\" });\n if (this.mergedHdRoute.jumpers \u0026\u0026 this.mergedHdRoute.jumpers.length \u003e 0) {\n const t2 = fB(this.mergedHdRoute.jumpers, { color: \"green\", label: this.mergedHdRoute.connectionName });\n e35.rects.push(...t2.rects ?? []), e35.lines.push(...t2.lines ?? []);\n }\n }\n for (const [t2, n2] of this.remainingHdRoutes.entries()) {\n const o3 = this.colorMap[n2.connectionName] ?? \"gray\";\n e35.lines?.push({ points: n2.route.map((e36) =\u003e ({ x: e36.x, y: e36.y })), strokeColor: o3 });\n for (let i3 = 0;i3 \u003c n2.route.length; i3++) {\n const r3 = n2.route[i3];\n e35.points?.push({ x: r3.x + (t2 % 2 - 0.5) / 500 + (i3 % 8 - 4) / 1000, y: r3.y + (t2 % 2 - 0.5) / 500 + (i3 % 8 - 4) / 1000, color: o3, label: `Route ${n2.connectionName} ${r3 === n2.route[0] ? \"First\" : r3 === n2.route[n2.route.length - 1] ? \"Last\" : \"\"}` });\n }\n for (const t3 of n2.vias)\n e35.circles?.push({ center: { x: t3.x, y: t3.y }, radius: n2.viaDiameter / 2, fill: o3 });\n if (n2.jumpers \u0026\u0026 n2.jumpers.length \u003e 0) {\n const t3 = fB(n2.jumpers, { color: o3, label: n2.connectionName });\n e35.rects.push(...t3.rects ?? []), e35.lines.push(...t3.lines ?? []);\n }\n }\n return e35;\n }\n};\nvar xB = (e35) =\u003e `${Math.round(100 * e35.x)},${Math.round(100 * e35.y)},${Math.round(100 * e35.z)}`;\nvar vB = (e35) =\u003e ({ startHash: xB(e35.route[0]), endHash: xB(e35.route[e35.route.length - 1]) });\nvar IB = class extends ni {\n getSolverName() {\n return \"MultipleHighDensityRouteStitchSolver\";\n }\n unsolvedRoutes;\n activeSolver = null;\n mergedHdRoutes = [];\n colorMap = {};\n defaultTraceThickness;\n defaultViaDiameter;\n getClosestEndpointHash(e35, t2) {\n let n2 = null, o3 = 1 / 0;\n for (const i3 of e35) {\n const e36 = [i3.route[0], i3.route[i3.route.length - 1]];\n for (const i4 of e36) {\n const e37 = me(t2, i4);\n e37 \u003c o3 \u0026\u0026 (o3 = e37, n2 = xB(i4));\n }\n }\n return n2;\n }\n selectRoutesAlongEndpointPath(e35, t2, n2) {\n if (e35.length \u003c= 2)\n return e35;\n const o3 = this.getClosestEndpointHash(e35, t2), i3 = this.getClosestEndpointHash(e35, n2);\n if (!o3 || !i3 || o3 === i3)\n return e35;\n const r3 = new Map;\n for (let t3 = 0;t3 \u003c e35.length; t3++) {\n const { startHash: n3, endHash: o4 } = vB(e35[t3]), i4 = r3.get(n3) ?? [];\n i4.push({ nextHash: o4, routeIndex: t3 }), r3.set(n3, i4);\n const s3 = r3.get(o4) ?? [];\n s3.push({ nextHash: n3, routeIndex: t3 }), r3.set(o4, s3);\n }\n const s2 = [o3], a3 = new Set([o3]), c3 = new Map;\n for (;s2.length \u003e 0; ) {\n const e36 = s2.shift();\n if (e36 === i3)\n break;\n for (const t3 of r3.get(e36) ?? [])\n a3.has(t3.nextHash) || (a3.add(t3.nextHash), c3.set(t3.nextHash, { prevHash: e36, routeIndex: t3.routeIndex }), s2.push(t3.nextHash));\n }\n if (!a3.has(i3))\n return e35;\n const l3 = new Set;\n let h2 = i3;\n for (;h2 !== o3; ) {\n const t3 = c3.get(h2);\n if (!t3)\n return e35;\n l3.add(t3.routeIndex), h2 = t3.prevHash;\n }\n if (l3.size === 0)\n return e35;\n return e35.filter((e36, t3) =\u003e l3.has(t3));\n }\n constructor(e35) {\n super(), this.colorMap = e35.colorMap ?? {};\n const t2 = e35.hdRoutes[0];\n this.defaultTraceThickness = t2?.traceThickness ?? 0.15, this.defaultViaDiameter = t2?.viaDiameter ?? e35.defaultViaDiameter ?? 0.3;\n const n2 = new mB({}), o3 = [], i3 = new Map;\n for (let t3 = 0;t3 \u003c e35.hdRoutes.length; t3++) {\n const n3 = e35.hdRoutes[t3], i4 = n3.route[0], r4 = n3.route[n3.route.length - 1];\n o3.push([`route_island_${t3}`, `${n3.connectionName}:${xB(i4)}`, `${n3.connectionName}:${xB(r4)}`]);\n }\n n2.addConnections(o3);\n for (const e36 of o3)\n for (const t3 of e36.slice(1))\n i3.set(t3, (i3.get(t3) ?? 0) + 1);\n this.unsolvedRoutes = [];\n const r3 = Array.from(new Set(Object.values(n2.idToNetMap)));\n for (const t3 of r3) {\n const o4 = n2.getIdsConnectedToNet(t3), r4 = e35.hdRoutes.filter((e36, t4) =\u003e o4.includes(`route_island_${t4}`));\n if (r4.length === 0)\n continue;\n const s3 = e35.connections.find((e36) =\u003e e36.name === r4[0].connectionName), a3 = r4.flatMap((e36) =\u003e [e36.route[0], e36.route[e36.route.length - 1]]), c3 = [];\n for (const e36 of a3) {\n const t4 = `${r4[0].connectionName}:${xB(e36)}`;\n i3.get(t4) === 1 \u0026\u0026 c3.push(e36);\n }\n if (c3.length === 0) {\n console.log(\"no possible endpoints, can't stitch\");\n continue;\n }\n let l3, h2;\n c3.length !== 2 ? (l3 = { ...s3.pointsToConnect[0], z: mo(Io(s3.pointsToConnect[0]), e35.layerCount) }, h2 = { ...s3.pointsToConnect[1], z: mo(Io(s3.pointsToConnect[1]), e35.layerCount) }) : (l3 = c3[0], h2 = c3[1], me(l3, s3.pointsToConnect[1]) \u003c me(h2, s3.pointsToConnect[0]) \u0026\u0026 ([l3, h2] = [h2, l3]));\n const d2 = this.selectRoutesAlongEndpointPath(r4, l3, h2);\n this.unsolvedRoutes.push({ connectionName: r4[0].connectionName, hdRoutes: d2, start: l3, end: h2 });\n }\n const s2 = new Map;\n for (const e36 of this.unsolvedRoutes) {\n const t3 = s2.get(e36.connectionName);\n t3 ? t3.push(e36) : s2.set(e36.connectionName, [e36]);\n }\n this.unsolvedRoutes = Array.from(s2.entries()).flatMap(([t3, n3]) =\u003e {\n if (!n3.some((e36) =\u003e e36.hdRoutes.some((e37) =\u003e e37.route.length \u003c 2)))\n return n3;\n const o4 = e35.connections.find((e36) =\u003e e36.name === t3);\n if (!o4)\n return n3;\n const i4 = { ...o4.pointsToConnect[0], z: mo(Io(o4.pointsToConnect[0]), e35.layerCount) }, r4 = { ...o4.pointsToConnect[1], z: mo(Io(o4.pointsToConnect[1]), e35.layerCount) }, s3 = n3.flatMap((e36) =\u003e e36.hdRoutes);\n return [{ connectionName: t3, hdRoutes: this.selectRoutesAlongEndpointPath(s3, i4, r4), start: i4, end: r4 }];\n }), this.MAX_ITERATIONS = 1e5;\n }\n _step() {\n if (this.activeSolver)\n return this.activeSolver.step(), void (this.activeSolver.solved ? (this.activeSolver instanceof bB \u0026\u0026 this.mergedHdRoutes.push(this.activeSolver.mergedHdRoute), this.activeSolver = null) : this.activeSolver.failed \u0026\u0026 (this.failed = true, this.error = this.activeSolver.error));\n const e35 = this.unsolvedRoutes.pop();\n e35 ? this.activeSolver = new bB({ connectionName: e35.connectionName, hdRoutes: e35.hdRoutes, start: e35.start, end: e35.end, colorMap: this.colorMap, defaultTraceThickness: this.defaultTraceThickness, defaultViaDiameter: this.defaultViaDiameter }) : this.solved = true;\n }\n visualize() {\n const e35 = { points: [], lines: [], circles: [], rects: [], title: \"Multiple High Density Route Stitch Solver\" };\n if (this.activeSolver) {\n const t2 = this.activeSolver.visualize();\n t2.points?.length \u0026\u0026 e35.points?.push(...t2.points), t2.lines?.length \u0026\u0026 e35.lines?.push(...t2.lines), t2.circles?.length \u0026\u0026 e35.circles?.push(...t2.circles), t2.rects?.length \u0026\u0026 (e35.rects || (e35.rects = []), e35.rects.push(...t2.rects));\n }\n for (const [t2, n2] of this.mergedHdRoutes.entries()) {\n const o3 = this.colorMap[n2.connectionName] ?? `hsl(120, 100%, ${40 + 10 * t2 % 40}%)`;\n for (let t3 = 0;t3 \u003c n2.route.length - 1; t3++) {\n const i3 = n2.route[t3], r3 = n2.route[t3 + 1], s2 = i3.z !== 0 ? Ao(o3, 0.5) : o3;\n e35.lines?.push({ points: [{ x: i3.x, y: i3.y }, { x: r3.x, y: r3.y }], strokeColor: s2, strokeWidth: n2.traceThickness });\n }\n for (const t3 of n2.route) {\n const n3 = t3.z !== 0 ? Ao(o3, 0.5) : o3;\n e35.points?.push({ x: t3.x, y: t3.y, color: n3 });\n }\n for (const t3 of n2.vias)\n e35.circles?.push({ center: { x: t3.x, y: t3.y }, radius: n2.viaDiameter / 2, fill: o3 });\n if (n2.jumpers \u0026\u0026 n2.jumpers.length \u003e 0) {\n const t3 = fB(n2.jumpers, { color: o3, label: n2.connectionName });\n e35.rects.push(...t3.rects ?? []), e35.lines.push(...t3.lines ?? []);\n }\n }\n for (const t2 of this.unsolvedRoutes) {\n const n2 = this.colorMap[t2.connectionName] ?? \"gray\";\n e35.points?.push({ x: t2.start.x, y: t2.start.y, color: n2, label: `${t2.connectionName} Start (z=${t2.start.z})` }, { x: t2.end.x, y: t2.end.y, color: n2, label: `${t2.connectionName} End (z=${t2.end.z})` }), e35.lines?.push({ points: [{ x: t2.start.x, y: t2.start.y }, { x: t2.end.x, y: t2.end.y }], strokeColor: n2, strokeDash: \"2 2\" });\n for (const o3 of t2.hdRoutes) {\n o3.route.length \u003e 1 \u0026\u0026 e35.lines?.push({ points: o3.route.map((e36) =\u003e ({ x: e36.x, y: e36.y })), strokeColor: Ao(n2, 0.5), strokeDash: \"10 5\" });\n for (const t3 of o3.vias)\n e35.circles?.push({ center: { x: t3.x, y: t3.y }, radius: o3.viaDiameter / 2, fill: n2 });\n if (o3.jumpers \u0026\u0026 o3.jumpers.length \u003e 0) {\n const t3 = fB(o3.jumpers, { color: n2, label: o3.connectionName });\n e35.rects.push(...t3.rects ?? []), e35.lines.push(...t3.lines ?? []);\n }\n }\n }\n return e35;\n }\n};\nvar SB = class {\n MAX_ITERATIONS = 1000;\n solved = false;\n failed = false;\n iterations = 0;\n progress = 0;\n error = null;\n activeSubSolver;\n failedSubSolvers;\n timeToSolve;\n stats = {};\n pendingEffects;\n cacheHit;\n cacheKey;\n cacheToSolveSpaceTransform;\n getSolverName() {\n return this.constructor.name;\n }\n step() {\n if (!this.solved \u0026\u0026 !this.failed) {\n this.iterations++;\n try {\n this._step();\n } catch (e35) {\n throw this.error = `${this.getSolverName()} error: ${e35}`, console.error(this.error), this.failed = true, e35;\n }\n !this.solved \u0026\u0026 this.iterations \u003e this.MAX_ITERATIONS \u0026\u0026 this.tryFinalAcceptance(), !this.solved \u0026\u0026 this.iterations \u003e this.MAX_ITERATIONS \u0026\u0026 (this.error = `${this.getSolverName()} ran out of iterations (MAX_ITERATIONS=${this.MAX_ITERATIONS})`, this.failed = true), \"computeProgress\" in this \u0026\u0026 (this.progress = this.computeProgress());\n }\n }\n _step() {}\n getConstructorParams() {\n throw new Error(\"getConstructorParams not implemented\");\n }\n solve() {\n const e35 = Date.now();\n for (;!this.solved \u0026\u0026 !this.failed; )\n this.step();\n const t2 = Date.now();\n this.timeToSolve = t2 - e35;\n }\n visualize() {\n return { lines: [], points: [], rects: [], circles: [] };\n }\n tryFinalAcceptance() {}\n preview() {\n return { lines: [], points: [], rects: [], circles: [] };\n }\n};\nvar CB = class {\n tree;\n constructor(e35 = 9) {\n this.tree = new G(e35);\n }\n insert(e35, t2, n2, o3, i3) {\n this.tree.insert({ minX: t2, minY: n2, maxX: o3, maxY: i3, data: e35 });\n }\n bulkLoad(e35) {\n const t2 = e35.map(({ item: e36, minX: t3, minY: n2, maxX: o3, maxY: i3 }) =\u003e ({ minX: t3, minY: n2, maxX: o3, maxY: i3, data: e36 }));\n this.tree.load(t2);\n }\n search(e35, t2, n2, o3) {\n return this.tree.search({ minX: e35, minY: t2, maxX: n2, maxY: o3 }).map((e36) =\u003e e36.data);\n }\n clear() {\n this.tree.clear();\n }\n};\nvar PB = [Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array];\nvar MB = class e35 {\n static from(t2, n2 = 0) {\n if (n2 % 8 != 0)\n throw new Error(\"byteOffset must be 8-byte aligned.\");\n if (!t2 || t2.byteLength === undefined || \"buffer\" in t2)\n throw new Error(\"Data must be an instance of ArrayBuffer or SharedArrayBuffer.\");\n const [o3, i3] = new Uint8Array(t2, n2 + 0, 2);\n if (o3 !== 251)\n throw new Error(\"Data does not appear to be in a Flatbush format.\");\n const r3 = i3 \u003e\u003e 4;\n if (r3 !== 3)\n throw new Error(`Got v${r3} data when expected v3.`);\n const s2 = PB[15 \u0026 i3];\n if (!s2)\n throw new Error(\"Unrecognized array type.\");\n const [a3] = new Uint16Array(t2, n2 + 2, 1), [c3] = new Uint32Array(t2, n2 + 4, 1);\n return new e35(c3, a3, s2, undefined, t2, n2);\n }\n constructor(e36, t2 = 16, n2 = Float64Array, o3 = ArrayBuffer, i3, r3 = 0) {\n if (e36 === undefined)\n throw new Error(\"Missing required argument: numItems.\");\n if (isNaN(e36) || e36 \u003c= 0)\n throw new Error(`Unexpected numItems value: ${e36}.`);\n this.numItems = +e36, this.nodeSize = Math.min(Math.max(+t2, 2), 65535), this.byteOffset = r3;\n let s2 = e36, a3 = s2;\n this._levelBounds = [4 * s2];\n do {\n s2 = Math.ceil(s2 / this.nodeSize), a3 += s2, this._levelBounds.push(4 * a3);\n } while (s2 !== 1);\n this.ArrayType = n2, this.IndexArrayType = a3 \u003c 16384 ? Uint16Array : Uint32Array;\n const c3 = PB.indexOf(n2), l3 = 4 * a3 * n2.BYTES_PER_ELEMENT;\n if (c3 \u003c 0)\n throw new Error(`Unexpected typed array class: ${n2}.`);\n const h2 = n2, d2 = this.IndexArrayType;\n if (i3)\n this.data = i3, this._boxes = new h2(i3, r3 + 8, 4 * a3), this._indices = new d2(i3, r3 + 8 + l3, a3), this._pos = 4 * a3, 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];\n else {\n const n3 = this.data = new o3(8 + l3 + a3 * this.IndexArrayType.BYTES_PER_ELEMENT);\n this._boxes = new h2(n3, 8, 4 * a3), this._indices = new d2(n3, 8 + l3, a3), this._pos = 0, this.minX = 1 / 0, this.minY = 1 / 0, this.maxX = -1 / 0, this.maxY = -1 / 0, new Uint8Array(n3, 0, 2).set([251, 48 + c3]), new Uint16Array(n3, 2, 1)[0] = t2, new Uint32Array(n3, 4, 1)[0] = e36;\n }\n this._queue = new R;\n }\n add(e36, t2, n2 = e36, o3 = t2) {\n const i3 = this._pos, r3 = i3 \u003e\u003e 2, s2 = this._boxes;\n return this._indices[r3] = r3, s2[i3] = e36, s2[i3 + 1] = t2, s2[i3 + 2] = n2, s2[i3 + 3] = o3, this._pos = i3 + 4, e36 \u003c this.minX \u0026\u0026 (this.minX = e36), t2 \u003c this.minY \u0026\u0026 (this.minY = t2), n2 \u003e this.maxX \u0026\u0026 (this.maxX = n2), o3 \u003e this.maxY \u0026\u0026 (this.maxY = o3), r3;\n }\n finish() {\n if (this._pos \u003e\u003e 2 !== this.numItems)\n throw new Error(`Added ${this._pos \u003e\u003e 2} items when expected ${this.numItems}.`);\n const e36 = this._boxes;\n if (this.numItems \u003c= this.nodeSize)\n return e36[this._pos++] = this.minX, e36[this._pos++] = this.minY, e36[this._pos++] = this.maxX, void (e36[this._pos++] = this.maxY);\n const { numItems: t2, minX: n2, minY: o3, nodeSize: i3, _indices: r3, _levelBounds: s2 } = this, a3 = this.maxX - n2 || 1, c3 = this.maxY - o3 || 1, l3 = new Int32Array(t2), h2 = 65535 / a3, d2 = 65535 / c3;\n for (let i4 = 0, r4 = 0;i4 \u003c t2; i4++) {\n const t3 = e36[r4++], s3 = e36[r4++], a4 = h2 * ((t3 + e36[r4++]) / 2 - n2) | 0, c4 = d2 * ((s3 + e36[r4++]) / 2 - o3) | 0;\n l3[i4] = RB(a4, c4);\n }\n (function(e37, t3, n3, o4, i4, r4) {\n const s3 = [o4, i4];\n for (;s3.length; ) {\n const o5 = s3.pop() || 0, i5 = s3.pop() || 0;\n if (o5 - i5 \u003c= r4 \u0026\u0026 Math.floor(i5 / r4) \u003e= Math.floor(o5 / r4))\n continue;\n const a4 = e37[i5], c4 = e37[i5 + o5 \u003e\u003e 1], l4 = e37[o5], h3 = a4 \u003e c4 != a4 \u003e l4 ? a4 : c4 \u003c a4 != c4 \u003c l4 ? c4 : l4;\n let d3 = i5 - 1, u3 = o5 + 1;\n for (;; ) {\n do {\n d3++;\n } while (e37[d3] \u003c h3);\n do {\n u3--;\n } while (e37[u3] \u003e h3);\n if (d3 \u003e= u3)\n break;\n NB(e37, t3, n3, d3, u3);\n }\n s3.push(i5, u3, u3 + 1, o5);\n }\n })(l3, e36, r3, 0, t2 - 1, i3);\n let u2 = 4 * t2;\n for (let t3 = 0, n3 = 0;t3 \u003c s2.length - 1; t3++) {\n const o4 = s2[t3];\n for (;n3 \u003c o4; ) {\n const t4 = n3;\n let s3 = e36[n3++], a4 = e36[n3++], c4 = e36[n3++], l4 = e36[n3++];\n for (let t5 = 1;t5 \u003c i3 \u0026\u0026 n3 \u003c o4; t5++)\n s3 = Math.min(s3, e36[n3++]), a4 = Math.min(a4, e36[n3++]), c4 = Math.max(c4, e36[n3++]), l4 = Math.max(l4, e36[n3++]);\n r3[u2 \u003e\u003e 2] = t4, e36[u2++] = s3, e36[u2++] = a4, e36[u2++] = c4, e36[u2++] = l4;\n }\n }\n this._pos = u2;\n }\n search(e36, t2, n2, o3, i3) {\n if (this._pos !== this._boxes.length)\n throw new Error(\"Data not yet indexed - call index.finish().\");\n const { _boxes: r3, _levelBounds: s2, _indices: a3, nodeSize: c3 } = this, l3 = 4 * this.numItems;\n let h2 = r3.length - 4, d2 = s2.length - 1;\n const u2 = [], p3 = [];\n let m2 = false;\n for (;h2 !== undefined; ) {\n const g2 = Math.min(h2 + 4 * c3, s2[d2]), f2 = h2 \u003e= l3;\n if (m2)\n this._collectContained(h2, g2, d2, l3, p3, i3);\n else\n for (let s3 = h2;s3 \u003c g2; s3 += 4) {\n const c4 = r3[s3];\n if (n2 \u003c c4)\n continue;\n const l4 = r3[s3 + 1];\n if (o3 \u003c l4)\n continue;\n const h3 = r3[s3 + 2];\n if (e36 \u003e h3)\n continue;\n const m3 = r3[s3 + 3];\n if (t2 \u003e m3)\n continue;\n const g3 = 0 | a3[s3 \u003e\u003e 2];\n if (f2) {\n const i4 = +(e36 \u003c= c4 \u0026\u0026 t2 \u003c= l4 \u0026\u0026 n2 \u003e= h3 \u0026\u0026 o3 \u003e= m3);\n u2.push(g3 | i4, d2 - 1);\n } else\n (i3 === undefined || i3(g3, c4, l4, h3, m3)) \u0026\u0026 p3.push(g3);\n }\n d2 = u2.pop(), h2 = u2.pop(), h2 !== undefined \u0026\u0026 (m2 = !(1 \u0026 ~h2), h2 \u0026= -2);\n }\n return p3;\n }\n _collectContained(e36, t2, n2, o3, i3, r3) {\n const s2 = this._boxes, a3 = this._indices;\n let c3 = e36;\n for (let e37 = n2;e37 \u003e 0; e37--)\n c3 = a3[c3 \u003e\u003e 2];\n const l3 = Math.min(c3 + (t2 - e36) * this.nodeSize ** n2, o3);\n if (r3 === undefined)\n for (;c3 \u003c l3; c3 += 4)\n i3.push(0 | a3[c3 \u003e\u003e 2]);\n else\n for (;c3 \u003c l3; c3 += 4) {\n const e37 = 0 | a3[c3 \u003e\u003e 2];\n r3(e37, s2[c3], s2[c3 + 1], s2[c3 + 2], s2[c3 + 3]) \u0026\u0026 i3.push(e37);\n }\n }\n neighbors(e36, t2, n2 = 1 / 0, o3 = 1 / 0, i3) {\n if (this._pos !== this._boxes.length)\n throw new Error(\"Data not yet indexed - call index.finish().\");\n const { _boxes: r3, _levelBounds: s2, _indices: a3, _queue: c3, nodeSize: l3 } = this, h2 = 4 * this.numItems, d2 = 4 * l3, u2 = [], p3 = n2 === 1;\n let m2 = o3 * o3;\n for (c3.push(r3.length - 4 \u003c\u003c 1, 0);c3.length; ) {\n const o4 = c3.ids[0];\n if (1 \u0026 o4) {\n if (c3.pop(), u2.push(o4 \u003e\u003e 1), u2.length === n2)\n break;\n continue;\n }\n c3.pop();\n const l4 = o4 \u003e\u003e 1, g2 = l4 \u003c h2, f2 = Math.min(l4 + d2, wB(l4, s2));\n for (let n3 = l4;n3 \u003c f2; n3 += 4) {\n const o5 = r3[n3], s3 = r3[n3 + 1], l5 = r3[n3 + 2], h3 = r3[n3 + 3], d3 = Math.max(Math.max(o5 - e36, e36 - l5), 0), u3 = Math.max(Math.max(s3 - t2, t2 - h3), 0), f3 = d3 * d3 + u3 * u3;\n if (f3 \u003e m2)\n continue;\n const _2 = 0 | a3[n3 \u003e\u003e 2];\n g2 ? (i3 === undefined || i3(_2)) \u0026\u0026 (c3.push(_2 \u003c\u003c 1 | 1, f3), p3 \u0026\u0026 f3 \u003c m2 \u0026\u0026 (m2 = f3)) : c3.push(_2 \u003c\u003c 1, f3);\n }\n }\n return c3.clear(), u2;\n }\n};\nfunction wB(e36, t2) {\n let n2 = 0, o3 = t2.length - 1;\n for (;n2 \u003c o3; ) {\n const i3 = n2 + o3 \u003e\u003e 1;\n t2[i3] \u003e e36 ? o3 = i3 : n2 = i3 + 1;\n }\n return t2[n2];\n}\nfunction NB(e36, t2, n2, o3, i3) {\n const r3 = e36[o3];\n e36[o3] = e36[i3], e36[i3] = r3;\n const s2 = 4 * o3, a3 = 4 * i3, c3 = t2[s2], l3 = t2[s2 + 1], h2 = t2[s2 + 2], d2 = t2[s2 + 3];\n t2[s2] = t2[a3], t2[s2 + 1] = t2[a3 + 1], t2[s2 + 2] = t2[a3 + 2], t2[s2 + 3] = t2[a3 + 3], t2[a3] = c3, t2[a3 + 1] = l3, t2[a3 + 2] = h2, t2[a3 + 3] = d2;\n const u2 = n2[o3];\n n2[o3] = n2[i3], n2[i3] = u2;\n}\nfunction RB(e36, t2) {\n let n2 = e36 ^ t2, o3 = 65535 ^ n2, i3 = 65535 ^ (e36 | t2), r3 = e36 \u0026 (65535 ^ t2), s2 = n2 | o3 \u003e\u003e 1, a3 = n2 \u003e\u003e 1 ^ n2, c3 = i3 ^ i3 \u003e\u003e 1 ^ o3 \u0026 r3 \u003e\u003e 1, l3 = r3 ^ n2 \u0026 i3 \u003e\u003e 1 ^ r3 \u003e\u003e 1;\n return n2 = s2 \u0026 s2 \u003e\u003e 2 ^ a3 \u0026 a3 \u003e\u003e 2, o3 = s2 \u0026 a3 \u003e\u003e 2 ^ a3 \u0026 (s2 ^ a3) \u003e\u003e 2, i3 = c3 ^ s2 \u0026 c3 \u003e\u003e 2 ^ a3 \u0026 l3 \u003e\u003e 2, r3 = l3 ^ a3 \u0026 c3 \u003e\u003e 2 ^ (s2 ^ a3) \u0026 l3 \u003e\u003e 2, s2 = n2 \u0026 n2 \u003e\u003e 4 ^ o3 \u0026 o3 \u003e\u003e 4, a3 = n2 \u0026 o3 \u003e\u003e 4 ^ o3 \u0026 (n2 ^ o3) \u003e\u003e 4, c3 = i3 ^ n2 \u0026 i3 \u003e\u003e 4 ^ o3 \u0026 r3 \u003e\u003e 4, l3 = r3 ^ o3 \u0026 i3 \u003e\u003e 4 ^ (n2 ^ o3) \u0026 r3 \u003e\u003e 4, i3 = c3 ^ s2 \u0026 c3 \u003e\u003e 8 ^ a3 \u0026 l3 \u003e\u003e 8, r3 = l3 ^ a3 \u0026 c3 \u003e\u003e 8 ^ (s2 ^ a3) \u0026 l3 \u003e\u003e 8, i3 ^= i3 \u003e\u003e 1, r3 ^= r3 \u003e\u003e 1, n2 = e36 ^ t2, o3 = r3 | 65535 ^ (n2 | i3), n2 = 16711935 \u0026 (n2 | n2 \u003c\u003c 8), n2 = 252645135 \u0026 (n2 | n2 \u003c\u003c 4), n2 = 858993459 \u0026 (n2 | n2 \u003c\u003c 2), n2 = 1431655765 \u0026 (n2 | n2 \u003c\u003c 1), o3 = 16711935 \u0026 (o3 | o3 \u003c\u003c 8), o3 = 252645135 \u0026 (o3 | o3 \u003c\u003c 4), o3 = 858993459 \u0026 (o3 | o3 \u003c\u003c 2), o3 = 1431655765 \u0026 (o3 | o3 \u003c\u003c 1), ((o3 \u003c\u003c 1 | n2) \u003e\u003e\u003e 0) - 2147483648;\n}\nvar TB = class {\n index;\n items = [];\n currentIndex = 0;\n capacity;\n constructor(e36) {\n this.capacity = Math.max(1, e36), this.index = new MB(this.capacity);\n }\n insert(e36, t2, n2, o3, i3) {\n if (this.currentIndex \u003e= this.index.numItems)\n throw new Error(\"Exceeded initial capacity\");\n this.items[this.currentIndex] = e36, this.index.add(t2, n2, o3, i3), this.currentIndex++;\n }\n finish() {\n this.index.finish();\n }\n search(e36, t2, n2, o3) {\n return this.index.search(e36, t2, n2, o3).map((e37) =\u003e this.items[e37] || null).filter(Boolean);\n }\n clear() {\n this.items = [], this.currentIndex = 0, this.index = new MB(this.capacity);\n }\n};\nvar EB = class {\n idx;\n storage = [];\n constructor(e36 = \"native\", t2 = []) {\n e36 === \"flatbush\" ? t2.length === 0 ? (this.idx = new CB, e36 = \"rbush\") : this.idx = new TB(t2.length) : this.idx = e36 === \"rbush\" ? new CB : new class {\n shi = new AB(t2);\n insert(e37) {}\n search(e37, t3, n2, o3) {\n const i3 = (e37 + n2) / 2, r3 = (t3 + o3) / 2, s2 = n2 - e37, a3 = o3 - t3;\n return this.shi.getNodesInArea(i3, r3, s2, a3);\n }\n clear() {}\n }, t2.forEach((e37) =\u003e this.insert(e37)), e36 === \"flatbush\" \u0026\u0026 t2.length \u003e 0 \u0026\u0026 this.idx.finish?.();\n }\n insert(e36) {\n this.storage.push(e36), this.idx.insert(e36, e36.center.x - e36.width / 2, e36.center.y - e36.height / 2, e36.center.x + e36.width / 2, e36.center.y + e36.height / 2);\n }\n search(e36) {\n return this.idx.search(e36.minX, e36.minY, e36.maxX, e36.maxY);\n }\n searchArea(e36, t2, n2, o3) {\n return this.search({ minX: e36 - n2 / 2, minY: t2 - o3 / 2, maxX: e36 + n2 / 2, maxY: t2 + o3 / 2 });\n }\n};\nvar AB = class {\n constructor(e36) {\n this.obstacles = e36, this.buckets = new Map;\n for (let t2 = 0;t2 \u003c e36.length; t2++) {\n const n2 = e36[t2], o3 = n2.center.x - n2.width / 2, i3 = n2.center.y - n2.height / 2, r3 = n2.center.x + n2.width / 2, s2 = n2.center.y + n2.height / 2;\n for (let e37 = o3;e37 \u003c= r3; e37 += this.CELL_SIZE)\n for (let o4 = i3;o4 \u003c= s2; o4 += this.CELL_SIZE) {\n const i4 = this.getBucketKey(e37, o4), r4 = this.buckets.get(i4);\n r4 ? r4.push([n2, t2]) : this.buckets.set(i4, [[n2, t2]]);\n }\n }\n }\n buckets;\n CELL_SIZE = 0.4;\n getBucketKey(e36, t2) {\n return `${Math.floor(e36 / this.CELL_SIZE)}x${Math.floor(t2 / this.CELL_SIZE)}`;\n }\n getNodesInArea(e36, t2, n2, o3) {\n const i3 = [], r3 = new Set, s2 = t2 - o3 / 2, a3 = e36 + n2 / 2, c3 = t2 + o3 / 2;\n for (let t3 = e36 - n2 / 2;t3 \u003c= a3; t3 += this.CELL_SIZE)\n for (let e37 = s2;e37 \u003c= c3; e37 += this.CELL_SIZE) {\n const n3 = this.getBucketKey(t3, e37), o4 = this.buckets.get(n3) || [];\n for (const e38 of o4)\n r3.has(e38[1]) || (r3.add(e38[1]), i3.push(e38[0]));\n }\n return i3;\n }\n};\nvar OB = (e36) =\u003e ({ minX: Math.min(e36[0].x, e36[1].x), maxX: Math.max(e36[0].x, e36[1].x), minY: Math.min(e36[0].y, e36[1].y), maxY: Math.max(e36[0].y, e36[1].y) });\nfunction kB(e36, t2) {\n const n2 = e36.x - t2.x, o3 = e36.y - t2.y;\n return n2 * n2 + o3 * o3;\n}\nfunction DB(e36, t2, n2) {\n const o3 = kB(t2, n2);\n if (o3 === 0)\n return kB(e36, t2);\n let i3 = ((e36.x - t2.x) * (n2.x - t2.x) + (e36.y - t2.y) * (n2.y - t2.y)) / o3;\n i3 = Math.max(0, Math.min(1, i3));\n return kB(e36, { x: t2.x + i3 * (n2.x - t2.x), y: t2.y + i3 * (n2.y - t2.y) });\n}\nfunction LB(e36, t2, n2, o3) {\n if (he(e36, t2, n2, o3))\n return 0;\n const i3 = { x: e36.x, y: e36.y }, r3 = { x: t2.x, y: t2.y }, s2 = { x: n2.x, y: n2.y }, a3 = { x: o3.x, y: o3.y };\n return Math.min(DB(i3, s2, a3), DB(r3, s2, a3), DB(s2, i3, r3), DB(a3, i3, r3));\n}\nvar zB = class {\n segmentBuckets;\n viaBuckets;\n CELL_SIZE;\n maximumCopperRadius = 0;\n constructor(e36, t2 = 1) {\n this.segmentBuckets = new Map, this.viaBuckets = new Map, this.CELL_SIZE = t2;\n for (const t3 of e36)\n if (t3 \u0026\u0026 t3.connectionName) {\n if (this.maximumCopperRadius = Math.max(this.maximumCopperRadius, t3.traceThickness / 2, t3.viaDiameter / 2), t3.route \u0026\u0026 t3.route.length \u003e= 2)\n for (let e37 = 0;e37 \u003c t3.route.length - 1; e37++) {\n const n2 = t3.route[e37], o3 = t3.route[e37 + 1];\n if (n2.x === o3.x \u0026\u0026 n2.y === o3.y)\n continue;\n if (n2.insideJumperPad \u0026\u0026 o3.insideJumperPad)\n continue;\n const i3 = [n2, o3], r3 = OB(i3), s2 = { segmentId: `${t3.connectionName}-seg-${e37}`, segment: i3, parentRoute: t3 }, a3 = Math.floor(r3.minX / this.CELL_SIZE), c3 = Math.floor((r3.maxX + 0.000000001) / this.CELL_SIZE), l3 = Math.floor(r3.minY / this.CELL_SIZE), h2 = Math.floor((r3.maxY + 0.000000001) / this.CELL_SIZE);\n for (let e38 = a3;e38 \u003c= c3; e38++)\n for (let t4 = l3;t4 \u003c= h2; t4++) {\n const n3 = `${e38}x${t4}`;\n let o4 = this.segmentBuckets.get(n3);\n o4 || (o4 = [], this.segmentBuckets.set(n3, o4)), o4.push(s2);\n }\n }\n if (t3.vias \u0026\u0026 t3.vias.length \u003e 0)\n for (let e37 = 0;e37 \u003c t3.vias.length; e37++) {\n const n2 = t3.vias[e37];\n if (n2 == null)\n continue;\n const o3 = { viaId: `${t3.connectionName}-via-${e37}`, x: n2.x, y: n2.y, parentRoute: t3 }, i3 = `${Math.floor(n2.x / this.CELL_SIZE)}x${Math.floor(n2.y / this.CELL_SIZE)}`;\n let r3 = this.viaBuckets.get(i3);\n r3 || (r3 = [], this.viaBuckets.set(i3, r3)), r3.push(o3);\n }\n } else\n console.warn(\"Skipping route with missing data:\", t3);\n }\n hasConflictingRoutesForSegment(e36, t2, n2, o3, i3) {\n const r3 = OB([e36, t2]), s2 = n2 + this.maximumCopperRadius, a3 = Math.floor((r3.minX - s2) / this.CELL_SIZE), c3 = Math.floor((r3.maxX + s2 + 0.000000001) / this.CELL_SIZE), l3 = Math.floor((r3.minY - s2) / this.CELL_SIZE), h2 = Math.floor((r3.maxY + s2 + 0.000000001) / this.CELL_SIZE), d2 = new Set, u2 = new Set;\n for (let r4 = a3;r4 \u003c= c3; r4++)\n for (let s3 = l3;s3 \u003c= h2; s3++) {\n const a4 = `${r4}x${s3}`, c4 = this.segmentBuckets.get(a4);\n if (c4)\n for (const r5 of c4) {\n const s4 = r5.parentRoute, [a5, c5] = r5.segment;\n if (e36.z !== t2.z || a5.z !== c5.z || a5.z !== e36.z || o3(s4) || d2.has(r5.segmentId))\n continue;\n d2.add(r5.segmentId);\n const l5 = n2 + s4.traceThickness / 2, h3 = LB(e36, t2, a5, c5);\n if (h3 \u003c l5 * l5 \u0026\u0026 (!i3 || Math.sqrt(h3) \u003c i3(s4)))\n return true;\n }\n const l4 = this.viaBuckets.get(a4);\n if (l4)\n for (const r5 of l4) {\n const s4 = r5.parentRoute;\n if (o3(s4) || u2.has(r5.viaId))\n continue;\n u2.add(r5.viaId);\n const a5 = n2 + s4.viaDiameter / 2, c5 = DB(r5, e36, t2);\n if (c5 \u003c a5 * a5 \u0026\u0026 (!i3 || Math.sqrt(c5) \u003c i3(s4)))\n return true;\n }\n }\n return false;\n }\n getConflictingRoutesForSegment(e36, t2, n2, o3) {\n const i3 = OB([e36, t2]), r3 = n2 + this.maximumCopperRadius, s2 = i3.minX - r3, a3 = i3.minY - r3, c3 = i3.maxX + r3, l3 = i3.maxY + r3, h2 = Math.floor(s2 / this.CELL_SIZE), d2 = Math.floor((c3 + 0.000000001) / this.CELL_SIZE), u2 = Math.floor(a3 / this.CELL_SIZE), p3 = Math.floor((l3 + 0.000000001) / this.CELL_SIZE), m2 = new Map, g2 = new Set, f2 = new Set, _2 = { x: e36.x, y: e36.y }, y2 = { x: t2.x, y: t2.y };\n for (let i4 = h2;i4 \u003c= d2; i4++)\n for (let r4 = u2;r4 \u003c= p3; r4++) {\n const s3 = `${i4}x${r4}`, a4 = this.segmentBuckets.get(s3);\n if (a4)\n for (const i5 of a4) {\n if (g2.has(i5.segmentId))\n continue;\n g2.add(i5.segmentId);\n const r5 = i5.parentRoute, [s4, a5] = i5.segment;\n if (e36.z !== t2.z || s4.z !== a5.z || s4.z !== e36.z)\n continue;\n if (o3?.(r5))\n continue;\n const c5 = n2 + r5.traceThickness / 2, l4 = c5 * c5, h3 = LB(e36, t2, s4, a5);\n if (h3 \u003c l4) {\n const e37 = r5.connectionName, t3 = m2.get(e37);\n (!t3 || h3 \u003c t3.minDistSq) \u0026\u0026 m2.set(e37, { route: r5, minDistSq: h3 });\n }\n }\n const c4 = this.viaBuckets.get(s3);\n if (c4)\n for (const e37 of c4) {\n if (f2.has(e37.viaId))\n continue;\n f2.add(e37.viaId);\n const t3 = e37.parentRoute;\n if (o3?.(t3))\n continue;\n const i5 = { x: e37.x, y: e37.y }, r5 = n2 + t3.viaDiameter / 2, s4 = r5 * r5, a5 = DB(i5, _2, y2);\n if (a5 \u003c s4) {\n const e38 = t3.connectionName, n3 = m2.get(e38);\n (!n3 || a5 \u003c n3.minDistSq) \u0026\u0026 m2.set(e38, { route: t3, minDistSq: a5 });\n }\n }\n }\n const b2 = [];\n for (const e37 of m2.values())\n b2.push({ conflictingRoute: e37.route, distance: Math.sqrt(e37.minDistSq) });\n return b2;\n }\n removeRoute(e36) {\n for (const [t2, n2] of this.segmentBuckets) {\n const o3 = n2.filter((t3) =\u003e t3.parentRoute.connectionName !== e36);\n o3.length === 0 ? this.segmentBuckets.delete(t2) : o3.length !== n2.length \u0026\u0026 this.segmentBuckets.set(t2, o3);\n }\n for (const [t2, n2] of this.viaBuckets) {\n const o3 = n2.filter((t3) =\u003e t3.parentRoute.connectionName !== e36);\n o3.length === 0 ? this.viaBuckets.delete(t2) : o3.length !== n2.length \u0026\u0026 this.viaBuckets.set(t2, o3);\n }\n }\n addRoute(e36) {\n if (!e36 || !e36.connectionName)\n return void console.warn(\"Skipping route with missing data:\", e36);\n this.maximumCopperRadius = Math.max(this.maximumCopperRadius, e36.traceThickness / 2, e36.viaDiameter / 2);\n if (e36.route \u0026\u0026 e36.route.length \u003e= 2)\n for (let t2 = 0;t2 \u003c e36.route.length - 1; t2++) {\n const n2 = e36.route[t2], o3 = e36.route[t2 + 1];\n if (n2.x === o3.x \u0026\u0026 n2.y === o3.y)\n continue;\n if (n2.insideJumperPad \u0026\u0026 o3.insideJumperPad)\n continue;\n const i3 = [n2, o3], r3 = OB(i3), s2 = { segmentId: `${e36.connectionName}-seg-${t2}`, segment: i3, parentRoute: e36 }, a3 = Math.floor(r3.minX / this.CELL_SIZE), c3 = Math.floor((r3.maxX + 0.000000001) / this.CELL_SIZE), l3 = Math.floor(r3.minY / this.CELL_SIZE), h2 = Math.floor((r3.maxY + 0.000000001) / this.CELL_SIZE);\n for (let e37 = a3;e37 \u003c= c3; e37++)\n for (let t3 = l3;t3 \u003c= h2; t3++) {\n const n3 = `${e37}x${t3}`;\n let o4 = this.segmentBuckets.get(n3);\n o4 || (o4 = [], this.segmentBuckets.set(n3, o4)), o4.push(s2);\n }\n }\n if (e36.vias \u0026\u0026 e36.vias.length \u003e 0)\n for (let t2 = 0;t2 \u003c e36.vias.length; t2++) {\n const n2 = e36.vias[t2];\n if (n2 == null)\n continue;\n const o3 = { viaId: `${e36.connectionName}-via-${t2}`, x: n2.x, y: n2.y, parentRoute: e36 }, i3 = `${Math.floor(n2.x / this.CELL_SIZE)}x${Math.floor(n2.y / this.CELL_SIZE)}`;\n let r3 = this.viaBuckets.get(i3);\n r3 || (r3 = [], this.viaBuckets.set(i3, r3)), r3.push(o3);\n }\n }\n getConflictingRoutesNearPoint(e36, t2, n2) {\n const o3 = t2 + this.maximumCopperRadius, i3 = e36.x - o3, r3 = e36.y - o3, s2 = e36.x + o3, a3 = e36.y + o3, c3 = Math.floor(i3 / this.CELL_SIZE), l3 = Math.floor((s2 + 0.000000001) / this.CELL_SIZE), h2 = Math.floor(r3 / this.CELL_SIZE), d2 = Math.floor((a3 + 0.000000001) / this.CELL_SIZE), u2 = new Map, p3 = new Set, m2 = new Set;\n for (let n3 = c3;n3 \u003c= l3; n3++)\n for (let o4 = h2;o4 \u003c= d2; o4++) {\n const i4 = `${n3}x${o4}`, r4 = this.segmentBuckets.get(i4);\n if (r4)\n for (const n4 of r4) {\n if (p3.has(n4.segmentId))\n continue;\n p3.add(n4.segmentId);\n const o5 = n4.segment[0], i5 = n4.segment[1];\n if (o5.z !== i5.z || o5.z !== e36.z)\n continue;\n const r5 = n4.parentRoute, s4 = { x: n4.segment[0].x, y: n4.segment[0].y }, a4 = { x: n4.segment[1].x, y: n4.segment[1].y }, c4 = t2 + r5.traceThickness / 2, l4 = c4 * c4, h3 = DB(e36, s4, a4);\n if (h3 \u003c l4) {\n const e37 = r5.connectionName, t3 = u2.get(e37);\n (!t3 || h3 \u003c t3.minDistSq) \u0026\u0026 u2.set(e37, { route: r5, minDistSq: h3 });\n }\n }\n const s3 = this.viaBuckets.get(i4);\n if (s3)\n for (const n4 of s3) {\n if (m2.has(n4.viaId))\n continue;\n m2.add(n4.viaId);\n const o5 = n4.parentRoute, i5 = { x: n4.x, y: n4.y }, r5 = t2 + o5.viaDiameter / 2, s4 = r5 * r5, a4 = kB(e36, i5);\n if (a4 \u003c s4) {\n const e37 = o5.connectionName, t3 = u2.get(e37);\n (!t3 || a4 \u003c t3.minDistSq) \u0026\u0026 u2.set(e37, { route: o5, minDistSq: a4 });\n }\n }\n }\n const g2 = [];\n for (const e37 of u2.values())\n g2.push({ conflictingRoute: e37.route, distance: Math.sqrt(e37.minDistSq) });\n return g2;\n }\n};\nvar BB = (e36, t2) =\u003e {\n const n2 = [], o3 = Math.abs(t2.x - e36.x), i3 = Math.abs(t2.y - e36.y), r3 = t2.x \u003e e36.x ? 1 : -1, s2 = t2.y \u003e e36.y ? 1 : -1, a3 = { x: t2.x - r3 * Math.abs(t2.y - e36.y), y: e36.y };\n (a3.x - e36.x) * r3 \u003e= 0 \u0026\u0026 (a3.x - t2.x) * r3 \u003c= 0 \u0026\u0026 n2.push([e36, a3, t2]);\n const c3 = { x: e36.x, y: t2.y - s2 * Math.abs(t2.x - e36.x) };\n (c3.y - e36.y) * s2 \u003e= 0 \u0026\u0026 (c3.y - t2.y) * s2 \u003c= 0 \u0026\u0026 n2.push([e36, c3, t2]);\n const l3 = Math.min(o3, i3), h2 = { x: e36.x + r3 * l3, y: e36.y + s2 * l3 };\n return (h2.x - e36.x) * r3 \u003e= 0 \u0026\u0026 (h2.x - t2.x) * r3 \u003c= 0 \u0026\u0026 (h2.y - e36.y) * s2 \u003e= 0 \u0026\u0026 (h2.y - t2.y) * s2 \u003c= 0 \u0026\u0026 n2.push([e36, h2, t2]), n2;\n};\nvar FB = (e36, t2) =\u003e {\n const n2 = Math.max(Math.abs(e36), Math.abs(t2));\n if (n2 === 0 || n2 === Number.POSITIVE_INFINITY)\n return n2;\n const o3 = e36 / n2, i3 = t2 / n2;\n return n2 * Math.sqrt(o3 * o3 + i3 * i3);\n};\nfunction jB(e36, t2, n2, o3) {\n if (he(e36, t2, n2, o3))\n return 0;\n const i3 = $B(e36, n2, o3), r3 = $B(t2, n2, o3), s2 = $B(n2, e36, t2), a3 = $B(o3, e36, t2);\n return Math.min(i3, r3, s2, a3);\n}\nfunction $B(e36, t2, n2) {\n const o3 = { x: n2.x - t2.x, y: n2.y - t2.y }, i3 = YB({ x: e36.x - t2.x, y: e36.y - t2.y }, o3);\n if (i3 \u003c= 0)\n return XB(e36, t2);\n const r3 = YB(o3, o3);\n if (r3 \u003c= i3)\n return XB(e36, n2);\n const s2 = i3 / r3;\n return XB(e36, { x: t2.x + s2 * o3.x, y: t2.y + s2 * o3.y });\n}\nfunction YB(e36, t2) {\n return e36.x * t2.x + e36.y * t2.y;\n}\nfunction XB(e36, t2) {\n const n2 = t2.x - e36.x, o3 = t2.y - e36.y;\n return Math.sqrt(n2 * n2 + o3 * o3);\n}\nvar HB = 0.000001;\nvar VB = (e36, t2, n2) =\u003e pe(e36, t2, n2) \u003c= HB;\nvar WB = (e36, t2) =\u003e Math.abs(e36.x - t2.x) \u003c= HB \u0026\u0026 Math.abs(e36.y - t2.y) \u003c= HB;\nvar GB = (e36, t2) =\u003e {\n if (!t2 || t2.length \u003c 3)\n return false;\n for (let n3 = 0;n3 \u003c t2.length; n3++) {\n const o3 = t2[n3], i3 = t2[(n3 + 1) % t2.length];\n if (VB(e36, o3, i3))\n return true;\n }\n let n2 = false;\n for (let o3 = 0, i3 = t2.length - 1;o3 \u003c t2.length; i3 = o3++) {\n const r3 = t2[o3], s2 = t2[i3];\n r3.y \u003e e36.y != s2.y \u003e e36.y \u0026\u0026 e36.x \u003c (s2.x - r3.x) * (e36.y - r3.y) / (s2.y - r3.y) + r3.x \u0026\u0026 (n2 = !n2);\n }\n return n2;\n};\nvar UB = ({ start: e36, end: t2, polygon: n2, margin: o3 = 0.2 }) =\u003e {\n if (!n2 || n2.length \u003c 3)\n return false;\n const i3 = GB(e36, n2), r3 = GB(t2, n2);\n if (!i3 || !r3)\n return true;\n for (let i4 = 0;i4 \u003c n2.length; i4++) {\n const r4 = n2[i4], s2 = n2[(i4 + 1) % n2.length], a3 = VB(e36, r4, s2), c3 = VB(t2, r4, s2);\n if (a3 \u0026\u0026 c3)\n continue;\n if (!he(e36, t2, r4, s2)) {\n if (!a3 \u0026\u0026 !c3) {\n if (jB(e36, t2, r4, s2) \u003c o3 - HB)\n return true;\n }\n continue;\n }\n const l3 = ge(e36, t2, r4, s2);\n if ((!l3 || !(a3 \u0026\u0026 WB(l3, e36) || c3 \u0026\u0026 WB(l3, t2))) \u0026\u0026 (!l3 || !WB(l3, e36) \u0026\u0026 !WB(l3, t2)))\n return true;\n }\n return false;\n};\nvar ZB = (e36) =\u003e {\n const t2 = [], n2 = e36.route;\n if (n2.length === 0)\n return [];\n let o3 = { startIndex: 0, endIndex: -1, z: n2[0].z, points: [n2[0]] };\n for (let e37 = 1;e37 \u003c n2.length; e37++)\n n2[e37].z === o3.z ? o3.points.push(n2[e37]) : (o3.endIndex = e37 - 1, t2.push(o3), o3 = { startIndex: e37, endIndex: -1, z: n2[e37].z, points: [n2[e37]] });\n return o3.endIndex = n2.length - 1, t2.push(o3), t2;\n};\nvar qB = ({ endpointX: e36, endpointY: t2, targetZ: n2, endpointPcbPortId: o3, terminalLayerIndicesByPcbPortId: i3, obstacleSHI: r3, route: s2, connMap: a3 }) =\u003e {\n const c3 = o3 ? i3?.get(o3) : undefined;\n if (c3 \u0026\u0026 !c3.has(n2))\n return false;\n const l3 = [s2.connectionName, s2.rootConnectionName].filter((e37) =\u003e e37 !== undefined), h2 = r3.searchArea(e36, t2, 2, 2).filter((n3) =\u003e {\n if (!l3.some((e37) =\u003e n3.connectedTo.some((t3) =\u003e t3 === e37 || a3.areIdsConnected(e37, t3))))\n return false;\n const o4 = n3.width / 2 + 0.05, i4 = n3.height / 2 + 0.05, r4 = Math.abs(e36 - n3.center.x) \u003c= o4, s3 = Math.abs(t2 - n3.center.y) \u003c= i4;\n return r4 \u0026\u0026 s3;\n });\n return h2.length \u003e 0 \u0026\u0026 h2.some((e37) =\u003e e37.__zLayers?.includes(n2));\n};\nvar JB = ({ currentSection: e36, targetZ: t2, route: n2, hdRouteSHI: o3, obstacleSHI: i3, connMap: r3, defaultTraceThickness: s2, obstacleMargin: a3, traceMargin: c3, shouldCheckStaticGeometryForSegment: l3 }) =\u003e {\n const h2 = n2.traceThickness ?? s2, d2 = c3 ?? 0, u2 = [n2.connectionName, n2.rootConnectionName].filter((e37) =\u003e e37 !== undefined);\n for (let n3 = 0;n3 \u003c e36.points.length - 1; n3++) {\n const c4 = { ...e36.points[n3], z: t2 }, p3 = { ...e36.points[n3 + 1], z: t2 }, m2 = o3.getConflictingRoutesForSegment(c4, p3, h2 / 2 + d2);\n for (const { conflictingRoute: e37, distance: t3 } of m2) {\n const n4 = [e37.connectionName, e37.rootConnectionName].filter((e38) =\u003e e38 !== undefined);\n if (u2.some((e38) =\u003e n4.some((t4) =\u003e t4 === e38 || r3.areIdsConnected(t4, e38))))\n continue;\n const o4 = e37.traceThickness ?? s2;\n if (t3 \u003c h2 / 2 + (d2 \u003e 0 ? Math.max(o4 / 2, e37.viaDiameter / 2) : o4 / 2) + d2)\n return false;\n }\n if (l3?.(c4, p3) === false)\n continue;\n const g2 = { centerX: (c4.x + p3.x) / 2, centerY: (c4.y + p3.y) / 2, width: Math.abs(c4.x - p3.x), height: Math.abs(c4.y - p3.y) }, f2 = h2 / 2 + a3, _2 = i3.searchArea(g2.centerX, g2.centerY, g2.width + 2 * f2, g2.height + 2 * f2);\n for (const e37 of _2) {\n if (u2.some((t3) =\u003e e37.connectedTo.some((e38) =\u003e e38 === t3 || r3.areIdsConnected(e38, t3))))\n continue;\n if (e37.__zLayers?.includes(t2)) {\n if (Math.abs(c4.x - e37.center.x) \u003c 0.01 \u0026\u0026 Math.abs(c4.y - e37.center.y) \u003c 0.01 || Math.abs(p3.x - e37.center.x) \u003c 0.01 \u0026\u0026 Math.abs(p3.y - e37.center.y) \u003c 0.01)\n continue;\n }\n if (Re(c4, p3, e37) \u003c f2)\n return false;\n }\n }\n return true;\n};\nvar QB = ({ targetZ: e36, route: t2, hdRouteSHI: n2, obstacleSHI: o3, connMap: i3, defaultTraceThickness: r3, obstacleMargin: s2, traceMargin: a3, useNumericSegmentKeys: c3 }) =\u003e {\n const l3 = t2.traceThickness ?? r3, h2 = l3 / 2 + a3, d2 = l3 / 2 + s2, u2 = t2.connectionName, p3 = t2.rootConnectionName, m2 = new Map, g2 = new WeakMap, f2 = new WeakMap, _2 = c3 ? new Map : undefined;\n let y2 = 0;\n const b2 = (e37) =\u003e {\n let t3 = _2.get(e37.x);\n t3 || (t3 = new Map, _2.set(e37.x, t3));\n let n3 = t3.get(e37.y);\n return n3 === undefined \u0026\u0026 (n3 = y2++, t3.set(e37.y, n3)), n3;\n }, x2 = (e37, t3) =\u003e {\n if (c3) {\n const n3 = b2(e37), o4 = b2(t3), i4 = Math.max(n3, o4);\n return i4 * (i4 + 1) / 2 + Math.min(n3, o4);\n }\n return e37.x \u003c t3.x || e37.x === t3.x \u0026\u0026 e37.y \u003c= t3.y ? `${e37.x}:${e37.y}|${t3.x}:${t3.y}` : `${t3.x}:${t3.y}|${e37.x}:${e37.y}`;\n }, v2 = (e37) =\u003e e37 === u2 || i3.areIdsConnected(e37, u2) || p3 !== undefined \u0026\u0026 (e37 === p3 || i3.areIdsConnected(e37, p3)), I2 = (e37) =\u003e {\n let t3 = f2.get(e37);\n return t3 === undefined \u0026\u0026 (t3 = v2(e37.connectionName) || e37.rootConnectionName !== undefined \u0026\u0026 v2(e37.rootConnectionName), f2.set(e37, t3)), t3;\n }, S2 = (e37) =\u003e l3 / 2 + Math.max((e37.traceThickness ?? r3) / 2, e37.viaDiameter / 2) + a3;\n return (t3, i4) =\u003e {\n const r4 = t3.length - 1;\n for (let s3 = 0;s3 \u003c r4; s3++) {\n const r5 = s3 - 1, a4 = i4 === 0 ? s3 : s3 === 0 ? i4 : r5 \u003e= i4 ? r5 + 1 : r5, c4 = t3[a4], l4 = t3[a4 + 1], u3 = x2(c4, l4), p4 = m2.get(u3);\n if (p4 !== undefined) {\n if (!p4)\n return false;\n continue;\n }\n const f3 = c4.z === e36 ? c4 : { ...c4, z: e36 }, _3 = l4.z === e36 ? l4 : { ...l4, z: e36 }, y3 = { centerX: (f3.x + _3.x) / 2, centerY: (f3.y + _3.y) / 2, width: Math.abs(f3.x - _3.x), height: Math.abs(f3.y - _3.y) }, b3 = o3.searchArea(y3.centerX, y3.centerY, y3.width + 2 * d2, y3.height + 2 * d2);\n for (const t4 of b3) {\n let n3 = g2.get(t4);\n if (n3 === undefined \u0026\u0026 (n3 = t4.connectedTo.some(v2), g2.set(t4, n3)), n3)\n continue;\n if (t4.__zLayers?.includes(e36)) {\n if (Math.abs(f3.x - t4.center.x) \u003c 0.01 \u0026\u0026 Math.abs(f3.y - t4.center.y) \u003c 0.01 || Math.abs(_3.x - t4.center.x) \u003c 0.01 \u0026\u0026 Math.abs(_3.y - t4.center.y) \u003c 0.01)\n continue;\n }\n if (Re(f3, _3, t4) \u003c d2)\n return m2.set(u3, false), false;\n }\n if (n2.hasConflictingRoutesForSegment(f3, _3, h2, I2, S2))\n return m2.set(u3, false), false;\n m2.set(u3, true);\n }\n return true;\n };\n};\nvar KB = class extends SB {\n getSolverName() {\n return \"SingleRouteUselessViaRemovalSolver\";\n }\n obstacleSHI;\n hdRouteSHI;\n unsimplifiedRoute;\n connMap;\n outline;\n terminalLayerIndicesByPcbPortId;\n routeSections;\n currentSectionIndex;\n sameNetRouteCache = new WeakMap;\n detourContexts = new WeakMap;\n TRACE_THICKNESS = 0.15;\n OBSTACLE_MARGIN = 0.1;\n GEOMETRY_SHORTCUT_TRACE_MARGIN = 0.1;\n GEOMETRY_SHORTCUT_OBSTACLE_MARGIN = 0.15;\n MAX_GEOMETRY_SHORTCUT_ADDED_LENGTH = 4;\n ENABLE_GEOMETRY_SHORTCUTS = true;\n ENABLE_OBSTACLE_DETOUR_SHORTCUTS = false;\n ENABLE_ROUTED_TRACE_DETOURS = false;\n PRESERVE_ROUTE_ENDPOINTS = false;\n geometryShortcutsApplied = 0;\n multilayerSectionsCollapsed = 0;\n obstacleDetourCandidatesValidated = 0;\n constructor(e36) {\n super(), this.currentSectionIndex = 0, this.obstacleSHI = e36.obstacleSHI, this.hdRouteSHI = e36.hdRouteSHI, this.unsimplifiedRoute = e36.unsimplifiedRoute, this.connMap = e36.connMap, this.outline = e36.outline, this.terminalLayerIndicesByPcbPortId = e36.terminalLayerIndicesByPcbPortId, this.GEOMETRY_SHORTCUT_TRACE_MARGIN = e36.geometryShortcutTraceMargin ?? this.GEOMETRY_SHORTCUT_TRACE_MARGIN, this.GEOMETRY_SHORTCUT_OBSTACLE_MARGIN = e36.geometryShortcutObstacleMargin ?? this.GEOMETRY_SHORTCUT_OBSTACLE_MARGIN, this.ENABLE_GEOMETRY_SHORTCUTS = e36.enableGeometryShortcuts ?? true, this.ENABLE_OBSTACLE_DETOUR_SHORTCUTS = e36.enableObstacleDetourShortcuts ?? false, this.ENABLE_ROUTED_TRACE_DETOURS = e36.enableRoutedTraceDetours ?? false, this.PRESERVE_ROUTE_ENDPOINTS = e36.preserveRouteEndpoints ?? false, this.routeSections = ZB(this.unsimplifiedRoute);\n }\n getPathLength(e36) {\n let t2 = 0;\n for (let n2 = 1;n2 \u003c e36.length; n2++)\n t2 += FB(e36[n2].x - e36[n2 - 1].x, e36[n2].y - e36[n2 - 1].y);\n return t2;\n }\n normalizeShortcutPath(e36, t2, n2) {\n const o3 = e36.filter((t3, n3) =\u003e {\n const o4 = e36[n3 - 1];\n return !o4 || t3.x !== o4.x || t3.y !== o4.y;\n });\n return o3.map((e37, i3) =\u003e i3 === 0 ? { ...t2 } : i3 === o3.length - 1 ? { ...n2 } : { x: e37.x, y: e37.y, z: t2.z });\n }\n shortcutCrossesOutline(e36) {\n if (!this.outline || this.outline.length \u003c 3)\n return false;\n for (let t2 = 1;t2 \u003c e36.length; t2++)\n if (UB({ start: e36[t2 - 1], end: e36[t2], polygon: this.outline }))\n return true;\n return false;\n }\n isRouteOnSameNet(e36) {\n const t2 = this.sameNetRouteCache.get(e36);\n if (t2 !== undefined)\n return t2;\n const n2 = [this.unsimplifiedRoute.connectionName, this.unsimplifiedRoute.rootConnectionName].filter((e37) =\u003e e37 !== undefined), o3 = [e36.connectionName, e36.rootConnectionName].filter((e37) =\u003e e37 !== undefined), i3 = n2.some((e37) =\u003e o3.some((t3) =\u003e e37 === t3 || this.connMap.areIdsConnected(e37, t3)));\n return this.sameNetRouteCache.set(e36, i3), i3;\n }\n getObstacleDetourContext(e36, t2, n2) {\n const o3 = this.ENABLE_ROUTED_TRACE_DETOURS ? this.detourContexts.get(e36)?.get(t2) : undefined;\n if (o3?.targetZ === n2)\n return o3;\n const i3 = this.unsimplifiedRoute.traceThickness ?? this.TRACE_THICKNESS, r3 = i3 / 2 + this.GEOMETRY_SHORTCUT_OBSTACLE_MARGIN + 0.000001, s2 = this.MAX_GEOMETRY_SHORTCUT_ADDED_LENGTH / 2 + r3, a3 = Math.min(e36.x, t2.x) - s2, c3 = Math.max(e36.x, t2.x) + s2, l3 = Math.min(e36.y, t2.y) - s2, h2 = Math.max(e36.y, t2.y) + s2, d2 = this.obstacleSHI.search({ minX: a3, minY: l3, maxX: c3, maxY: h2 }).filter((e37) =\u003e e37.__zLayers?.includes(n2)), u2 = this.ENABLE_ROUTED_TRACE_DETOURS ? this.hdRouteSHI.getConflictingRoutesForSegment({ ...e36, z: n2 }, { ...t2, z: n2 }, i3 / 2 + this.GEOMETRY_SHORTCUT_TRACE_MARGIN, (e37) =\u003e this.isRouteOnSameNet(e37)) : [], p3 = [], m2 = new Set, g2 = new Set;\n for (const e37 of d2)\n m2.add(e37.center.x - e37.width / 2 - r3), m2.add(e37.center.x + e37.width / 2 + r3), g2.add(e37.center.y - e37.height / 2 - r3), g2.add(e37.center.y + e37.height / 2 + r3);\n for (const { conflictingRoute: e37 } of u2) {\n const t3 = e37.route.filter((e38) =\u003e e38.z === n2 \u0026\u0026 e38.x \u003e= a3 \u0026\u0026 e38.x \u003c= c3 \u0026\u0026 e38.y \u003e= l3 \u0026\u0026 e38.y \u003c= h2);\n if (t3.length === 0)\n continue;\n const o4 = i3 / 2 + Math.max(e37.traceThickness / 2, e37.viaDiameter / 2) + this.GEOMETRY_SHORTCUT_TRACE_MARGIN + 0.000001;\n m2.add(Math.min(...t3.map((e38) =\u003e e38.x)) - o4), m2.add(Math.max(...t3.map((e38) =\u003e e38.x)) + o4), g2.add(Math.min(...t3.map((e38) =\u003e e38.y)) - o4), g2.add(Math.max(...t3.map((e38) =\u003e e38.y)) + o4);\n {\n const e38 = Math.min(...t3.map((e39) =\u003e e39.x)) - o4, n3 = Math.max(...t3.map((e39) =\u003e e39.x)) + o4, i4 = Math.min(...t3.map((e39) =\u003e e39.y)) - o4, r4 = Math.max(...t3.map((e39) =\u003e e39.y)) + o4;\n p3.push({ x: e38, y: i4 }, { x: e38, y: r4 }, { x: n3, y: i4 }, { x: n3, y: r4 });\n }\n }\n const f2 = { targetZ: n2, traceCorners: p3, corridorXs: m2, corridorYs: g2 };\n if (this.ENABLE_ROUTED_TRACE_DETOURS) {\n const n3 = this.detourContexts.get(e36) ?? new WeakMap;\n n3.set(t2, f2), this.detourContexts.set(e36, n3);\n }\n return f2;\n }\n getObstacleDetourPaths(e36, t2, n2, o3, i3 = false, r3) {\n const { traceCorners: s2, corridorXs: a3, corridorYs: c3 } = this.getObstacleDetourContext(e36, t2, n2), l3 = [], h2 = new Set, d2 = (n3) =\u003e {\n let i4 = 0;\n for (let e37 = 1;e37 \u003c n3.length; e37++)\n i4 += FB(n3[e37].x - n3[e37 - 1].x, n3[e37].y - n3[e37 - 1].y);\n if (i4 \u003e o3)\n return;\n if (r3) {\n let t3 = 0, o4 = -1;\n for (let e37 = 0;e37 \u003c n3.length - 1; e37++) {\n const i5 = n3[e37 + 1].x - n3[e37].x, r4 = n3[e37 + 1].y - n3[e37].y, s4 = i5 * i5 + r4 * r4;\n s4 \u003e o4 \u0026\u0026 (t3 = e37, o4 = s4);\n }\n if (!r3([{ ...n3[t3], z: e36.z }, { ...n3[t3 + 1], z: e36.z }], 0))\n return;\n }\n const s3 = this.normalizeShortcutPath(n3, e36, t2);\n let a4 = 0, c4 = -1;\n for (let e37 = 0;e37 \u003c s3.length - 1; e37++) {\n const t3 = s3[e37 + 1].x - s3[e37].x, n4 = s3[e37 + 1].y - s3[e37].y, o4 = t3 * t3 + n4 * n4;\n o4 \u003e c4 \u0026\u0026 (a4 = e37, c4 = o4);\n }\n const d3 = s3.map((e37) =\u003e `${e37.x}:${e37.y}`).join(\"|\");\n h2.has(d3) || (h2.add(d3), l3.push({ path: s3, length: i4, longestSegmentIndex: a4 }));\n };\n if (i3) {\n for (const n3 of s2)\n for (const o4 of BB(e36, n3))\n for (const e37 of BB(n3, t2))\n d2([...o4, ...e37.slice(1)]);\n return l3;\n }\n for (const n3 of c3)\n d2([e36, { x: e36.x, y: n3 }, { x: t2.x, y: n3 }, t2]);\n for (const n3 of a3)\n d2([e36, { x: n3, y: e36.y }, { x: n3, y: t2.y }, t2]);\n return l3;\n }\n getDirectGeometryShortcut(e36, t2, n2) {\n let o3 = null;\n const i3 = QB({ targetZ: e36.z, route: this.unsimplifiedRoute, hdRouteSHI: this.hdRouteSHI, obstacleSHI: this.obstacleSHI, connMap: this.connMap, defaultTraceThickness: this.TRACE_THICKNESS, obstacleMargin: this.GEOMETRY_SHORTCUT_OBSTACLE_MARGIN, traceMargin: this.GEOMETRY_SHORTCUT_TRACE_MARGIN, useNumericSegmentKeys: true });\n for (let r3 = 0;r3 \u003c e36.points.length; r3++) {\n const s2 = e36.points[r3];\n for (let a3 = 0;a3 \u003c n2.points.length; a3++) {\n const c3 = n2.points[a3], l3 = [...e36.points.slice(r3), ...t2.points, ...n2.points.slice(0, a3 + 1)];\n if (!l3.some((e37) =\u003e e37.insideJumperPad || e37.toNextSegmentType))\n for (const e37 of BB(s2, c3)) {\n const t3 = this.normalizeShortcutPath(e37, s2, c3), n3 = this.getPathLength(l3) - this.getPathLength(t3);\n if (n3 \u003c -0.000001)\n continue;\n i3(t3, 0) \u0026\u0026 !this.shortcutCrossesOutline(t3) \u0026\u0026 ((!o3 || n3 \u003e o3.savedLength) \u0026\u0026 (o3 = { path: t3, previousPointIndex: r3, nextPointIndex: a3, savedLength: n3 }));\n }\n }\n }\n return o3;\n }\n getObstacleDetourShortcut(e36, t2, n2, o3 = false) {\n const i3 = e36.points.length - 1, r3 = [];\n for (let e37 = 0;e37 \u003c= i3; e37++)\n r3.push([e37, 0]);\n for (let e37 = 1;e37 \u003c n2.points.length; e37++)\n r3.push([i3, e37]);\n const s2 = this.ENABLE_ROUTED_TRACE_DETOURS ? QB({ targetZ: e36.z, route: this.unsimplifiedRoute, hdRouteSHI: this.hdRouteSHI, obstacleSHI: this.obstacleSHI, connMap: this.connMap, defaultTraceThickness: this.TRACE_THICKNESS, obstacleMargin: this.GEOMETRY_SHORTCUT_OBSTACLE_MARGIN, traceMargin: this.GEOMETRY_SHORTCUT_TRACE_MARGIN, useNumericSegmentKeys: true }) : undefined, a3 = [];\n for (const [i4, c4] of r3) {\n const r4 = e36.points[i4], l4 = n2.points[c4], h3 = [...e36.points.slice(i4), ...t2.points, ...n2.points.slice(0, c4 + 1)];\n if (h3.some((e37) =\u003e e37.insideJumperPad || e37.toNextSegmentType))\n continue;\n const d2 = this.getPathLength(h3);\n for (const { path: t3, length: n3, longestSegmentIndex: h4 } of this.getObstacleDetourPaths(r4, l4, e36.z, d2 + this.MAX_GEOMETRY_SHORTCUT_ADDED_LENGTH + 0.000001, o3, s2)) {\n const e37 = d2 - n3;\n e37 \u003c -this.MAX_GEOMETRY_SHORTCUT_ADDED_LENGTH - 0.000001 || a3.push({ path: t3, previousPointIndex: i4, nextPointIndex: c4, savedLength: e37, validationFirstSegmentIndex: h4 });\n }\n }\n a3.sort((e37, t3) =\u003e t3.savedLength - e37.savedLength);\n let c3 = 0;\n const l3 = a3.length \u003e= 256, h2 = s2 ?? QB({ targetZ: e36.z, route: this.unsimplifiedRoute, hdRouteSHI: this.hdRouteSHI, obstacleSHI: this.obstacleSHI, connMap: this.connMap, defaultTraceThickness: this.TRACE_THICKNESS, obstacleMargin: this.GEOMETRY_SHORTCUT_OBSTACLE_MARGIN, traceMargin: this.GEOMETRY_SHORTCUT_TRACE_MARGIN, useNumericSegmentKeys: l3 });\n for (const e37 of a3) {\n c3++;\n const { path: t3 } = e37;\n if (h2(t3, e37.validationFirstSegmentIndex ?? 0) \u0026\u0026 !this.shortcutCrossesOutline(t3))\n return this.obstacleDetourCandidatesValidated += c3, this.stats.obstacleDetourCandidatesValidated = this.obstacleDetourCandidatesValidated, e37;\n }\n return this.obstacleDetourCandidatesValidated += c3, this.stats.obstacleDetourCandidatesValidated = this.obstacleDetourCandidatesValidated, null;\n }\n findGeometryShortcut(e36, t2, n2) {\n if (this.detourContexts = new WeakMap, this.unsimplifiedRoute.jumpers?.length)\n return null;\n if (this.ENABLE_GEOMETRY_SHORTCUTS) {\n const o4 = this.getDirectGeometryShortcut(e36, t2, n2);\n if (o4)\n return o4;\n }\n if (!this.ENABLE_OBSTACLE_DETOUR_SHORTCUTS)\n return null;\n const o3 = this.getObstacleDetourShortcut(e36, t2, n2);\n return o3 || !this.ENABLE_ROUTED_TRACE_DETOURS ? o3 : this.getObstacleDetourShortcut(e36, t2, n2, true);\n }\n applyGeometryShortcut(e36) {\n const t2 = this.routeSections[this.currentSectionIndex - 1], n2 = this.routeSections[this.currentSectionIndex + 1], o3 = [...t2.points.slice(0, e36.previousPointIndex), ...e36.path, ...n2.points.slice(e36.nextPointIndex + 1)].filter((e37, t3, n3) =\u003e {\n const o4 = n3[t3 - 1];\n return !o4 || e37.x !== o4.x || e37.y !== o4.y || e37.z !== o4.z;\n });\n this.routeSections.splice(this.currentSectionIndex - 1, 3, { startIndex: t2.startIndex, endIndex: n2.endIndex, z: t2.z, points: o3 }), this.geometryShortcutsApplied++, this.stats.geometryShortcutsApplied = this.geometryShortcutsApplied, this.stats.viasRemovedByGeometryShortcuts = 2 * this.geometryShortcutsApplied, this.currentSectionIndex = Math.max(0, this.currentSectionIndex - 1);\n }\n findMultilayerSectionCollapse(e36, t2, n2) {\n if (e36.z === n2.z || this.unsimplifiedRoute.jumpers?.length)\n return null;\n const o3 = e36.points[e36.points.length - 1];\n if (o3?.insideJumperPad || o3?.toNextSegmentType || t2.points.some((e37) =\u003e e37.insideJumperPad || e37.toNextSegmentType))\n return null;\n const i3 = [{ targetZ: e36.z, mergeWith: \"previous\" }, { targetZ: n2.z, mergeWith: \"next\" }];\n for (const e37 of i3)\n if (e37.targetZ !== t2.z \u0026\u0026 JB({ currentSection: t2, targetZ: e37.targetZ, route: this.unsimplifiedRoute, hdRouteSHI: this.hdRouteSHI, obstacleSHI: this.obstacleSHI, connMap: this.connMap, defaultTraceThickness: this.TRACE_THICKNESS, obstacleMargin: this.GEOMETRY_SHORTCUT_OBSTACLE_MARGIN, traceMargin: this.GEOMETRY_SHORTCUT_TRACE_MARGIN }))\n return e37;\n return null;\n }\n applyMultilayerSectionCollapse(e36) {\n const t2 = this.routeSections[this.currentSectionIndex - 1], n2 = this.routeSections[this.currentSectionIndex], o3 = this.routeSections[this.currentSectionIndex + 1], i3 = n2.points.map((t3) =\u003e ({ ...t3, z: e36.targetZ })), r3 = (e37) =\u003e e37.filter((t3, n3) =\u003e {\n const o4 = e37[n3 - 1];\n return !o4 || t3.x !== o4.x || t3.y !== o4.y || t3.z !== o4.z;\n });\n e36.mergeWith === \"previous\" ? this.routeSections.splice(this.currentSectionIndex - 1, 2, { startIndex: t2.startIndex, endIndex: n2.endIndex, z: e36.targetZ, points: r3([...t2.points, ...i3]) }) : this.routeSections.splice(this.currentSectionIndex, 2, { startIndex: n2.startIndex, endIndex: o3.endIndex, z: e36.targetZ, points: r3([...i3, ...o3.points]) }), this.multilayerSectionsCollapsed++, this.stats.multilayerSectionsCollapsed = this.multilayerSectionsCollapsed, this.stats.viasRemovedByMultilayerSectionCollapses = this.multilayerSectionsCollapsed, this.currentSectionIndex = Math.max(0, this.currentSectionIndex - 1);\n }\n _step() {\n if (this.currentSectionIndex \u003e= this.routeSections.length)\n return void (this.solved = true);\n if (this.currentSectionIndex === 0 \u0026\u0026 this.routeSections.length \u003e 1) {\n const e37 = this.routeSections[0], t3 = this.routeSections[1];\n if (!this.PRESERVE_ROUTE_ENDPOINTS \u0026\u0026 e37.z !== t3.z) {\n const n3 = t3.z, o4 = e37.points[0];\n if (qB({ endpointX: o4.x, endpointY: o4.y, targetZ: n3, endpointPcbPortId: this.unsimplifiedRoute.startPcbPortId, terminalLayerIndicesByPcbPortId: this.terminalLayerIndicesByPcbPortId, obstacleSHI: this.obstacleSHI, route: this.unsimplifiedRoute, connMap: this.connMap }) \u0026\u0026 JB({ currentSection: e37, targetZ: n3, route: this.unsimplifiedRoute, hdRouteSHI: this.hdRouteSHI, obstacleSHI: this.obstacleSHI, connMap: this.connMap, defaultTraceThickness: this.TRACE_THICKNESS, obstacleMargin: this.OBSTACLE_MARGIN }))\n return e37.z = n3, e37.points = e37.points.map((e38) =\u003e ({ ...e38, z: n3 })), void (this.currentSectionIndex = 2);\n }\n return void this.currentSectionIndex++;\n }\n if (this.currentSectionIndex === this.routeSections.length - 1) {\n if (!this.PRESERVE_ROUTE_ENDPOINTS \u0026\u0026 this.routeSections.length \u003e= 2) {\n const e37 = this.routeSections[this.routeSections.length - 1], t3 = this.routeSections[this.routeSections.length - 2];\n if (e37.z !== t3.z) {\n const n3 = t3.z, o4 = e37.points[e37.points.length - 1];\n qB({ endpointX: o4.x, endpointY: o4.y, targetZ: n3, endpointPcbPortId: this.unsimplifiedRoute.endPcbPortId, terminalLayerIndicesByPcbPortId: this.terminalLayerIndicesByPcbPortId, obstacleSHI: this.obstacleSHI, route: this.unsimplifiedRoute, connMap: this.connMap }) \u0026\u0026 JB({ currentSection: e37, targetZ: n3, route: this.unsimplifiedRoute, hdRouteSHI: this.hdRouteSHI, obstacleSHI: this.obstacleSHI, connMap: this.connMap, defaultTraceThickness: this.TRACE_THICKNESS, obstacleMargin: this.OBSTACLE_MARGIN }) \u0026\u0026 (e37.z = n3, e37.points = e37.points.map((e38) =\u003e ({ ...e38, z: n3 })));\n }\n }\n return void (this.solved = true);\n }\n const e36 = this.routeSections[this.currentSectionIndex - 1], t2 = this.routeSections[this.currentSectionIndex], n2 = this.routeSections[this.currentSectionIndex + 1];\n if (e36.z !== n2.z) {\n const o4 = this.findMultilayerSectionCollapse(e36, t2, n2);\n return o4 ? void this.applyMultilayerSectionCollapse(o4) : void this.currentSectionIndex++;\n }\n const o3 = e36.z;\n if (JB({ currentSection: t2, targetZ: o3, route: this.unsimplifiedRoute, hdRouteSHI: this.hdRouteSHI, obstacleSHI: this.obstacleSHI, connMap: this.connMap, defaultTraceThickness: this.TRACE_THICKNESS, obstacleMargin: this.OBSTACLE_MARGIN }))\n return t2.z = o3, t2.points = t2.points.map((e37) =\u003e ({ ...e37, z: o3 })), void (this.currentSectionIndex += 2);\n const i3 = this.findGeometryShortcut(e36, t2, n2);\n i3 ? this.applyGeometryShortcut(i3) : this.currentSectionIndex++;\n }\n getConstructorParams() {\n return { obstacleSHI: this.obstacleSHI, hdRouteSHI: this.hdRouteSHI, unsimplifiedRoute: this.unsimplifiedRoute, connMap: this.connMap, outline: this.outline, geometryShortcutTraceMargin: this.GEOMETRY_SHORTCUT_TRACE_MARGIN, geometryShortcutObstacleMargin: this.GEOMETRY_SHORTCUT_OBSTACLE_MARGIN, enableGeometryShortcuts: this.ENABLE_GEOMETRY_SHORTCUTS, enableObstacleDetourShortcuts: this.ENABLE_OBSTACLE_DETOUR_SHORTCUTS, enableRoutedTraceDetours: this.ENABLE_ROUTED_TRACE_DETOURS, preserveRouteEndpoints: this.PRESERVE_ROUTE_ENDPOINTS, terminalLayerIndicesByPcbPortId: this.terminalLayerIndicesByPcbPortId };\n }\n getOptimizedHdRoute() {\n const e36 = this.routeSections.flatMap((e37) =\u003e e37.points), t2 = [];\n for (let n2 = 0;n2 \u003c e36.length - 1; n2++)\n e36[n2].z !== e36[n2 + 1].z \u0026\u0026 t2.push({ x: e36[n2].x, y: e36[n2].y });\n return { connectionName: this.unsimplifiedRoute.connectionName, rootConnectionName: this.unsimplifiedRoute.rootConnectionName, startPcbPortId: this.unsimplifiedRoute.startPcbPortId, endPcbPortId: this.unsimplifiedRoute.endPcbPortId, route: e36, traceThickness: this.unsimplifiedRoute.traceThickness, vias: t2, viaDiameter: this.unsimplifiedRoute.viaDiameter, jumpers: this.unsimplifiedRoute.jumpers };\n }\n visualize() {\n const e36 = { circles: [], lines: [], points: [], rects: [], coordinateSystem: \"cartesian\", title: \"Single Route Useless Via Removal Solver\" };\n for (let t2 = 0;t2 \u003c this.routeSections.length; t2++) {\n const n2 = this.routeSections[t2];\n e36.lines.push({ points: n2.points, strokeWidth: this.TRACE_THICKNESS, strokeColor: t2 === this.currentSectionIndex ? \"orange\" : n2.z === 0 ? \"red\" : \"blue\" });\n }\n return e36;\n }\n};\nvar eF = (e36, t2) =\u003e {\n try {\n return Hn(t2, e36);\n } catch (t3) {\n return console.error(t3), e36;\n }\n};\nvar tF = { \"0603\": { length: 1.65, width: 0.95, padLength: 0.8, padWidth: 0.95 }, 1206: { length: 3.2, width: 1.6, padLength: 0.6, padWidth: 1.6 }, \"1206x4_pair\": { length: 2.7, width: 0.5, padLength: 0.8, padWidth: 0.5 } };\nfunction nF(e36, t2 = {}) {\n const n2 = [], o3 = [], i3 = t2.color ?? \"gray\", r3 = t2.label, s2 = tF[e36.footprint] ?? tF[\"0603\"], a3 = e36.end.x - e36.start.x, c3 = e36.end.y - e36.start.y, l3 = Math.abs(a3) \u003e Math.abs(c3), h2 = l3 ? s2.padLength : s2.padWidth, d2 = l3 ? s2.padWidth : s2.padLength;\n return n2.push({ center: e36.start, width: h2, height: d2, fill: eF(i3, 0.5), stroke: \"rgba(0, 0, 0, 0.5)\", layer: \"jumper\", label: r3 ? `${r3} (start)` : undefined }), n2.push({ center: e36.end, width: h2, height: d2, fill: eF(i3, 0.5), stroke: \"rgba(0, 0, 0, 0.5)\", layer: \"jumper\", label: r3 ? `${r3} (end)` : undefined }), o3.push({ points: [e36.start, e36.end], strokeColor: \"rgba(100, 100, 100, 0.8)\", strokeWidth: 0.3 * s2.padWidth, layer: \"jumper-body\" }), { rects: n2, lines: o3 };\n}\nfunction oF(e36, t2 = {}) {\n const n2 = { rects: [], lines: [] };\n for (const o3 of e36) {\n const { rects: e37, lines: i3 } = nF(o3, t2);\n n2.rects.push(...e37), n2.lines.push(...i3);\n }\n return n2;\n}\nfunction iF(e36, t2) {\n return [...new Set(e36)].filter((e37) =\u003e Number.isInteger(e37) \u0026\u0026 e37 \u003e= 0 \u0026\u0026 e37 \u003c t2).sort((e37, t3) =\u003e e37 - t3);\n}\nfunction rF(e36, t2) {\n return iF(e36.map((e37) =\u003e ((e38, t3) =\u003e e38 === \"top\" ? 0 : e38 === \"bottom\" ? t3 - 1 : parseInt(e38.slice(5)))(e37, t2)), t2);\n}\nvar sF = (e36, t2 = 2) =\u003e {\n const n2 = Array.from({ length: t2 }, (e37, t3) =\u003e t3);\n return e36.map((e37) =\u003e {\n const o3 = iF(e37.__zLayers ?? (e37.layers ? rF(e37.layers, t2) : undefined) ?? n2, t2);\n return { ...e37, __zLayers: o3.length \u003e 0 ? o3 : n2 };\n });\n};\nvar aF = class extends SB {\n constructor(e36) {\n super(), this.input = e36, this.input = { ...e36, obstacles: sF(e36.obstacles, e36.layerCount) }, this.MAX_ITERATIONS = 1e6, this.unsimplifiedHdRoutes = e36.unsimplifiedHdRoutes, this.optimizedHdRoutes = [], this.unprocessedRoutes = [...e36.unsimplifiedHdRoutes], this.obstacleSHI = new EB(\"flatbush\", this.input.obstacles), this.hdRouteSHI = new zB([...this.unsimplifiedHdRoutes, ...e36.otherHdRoutes ?? []]);\n }\n getSolverName() {\n return \"UselessViaRemovalSolver\";\n }\n unsimplifiedHdRoutes;\n optimizedHdRoutes;\n unprocessedRoutes;\n activeSubSolver = null;\n obstacleSHI = null;\n hdRouteSHI = null;\n _step() {\n if (this.activeSubSolver) {\n if (this.activeSubSolver.step(), this.activeSubSolver.solved) {\n const e37 = this.activeSubSolver.getOptimizedHdRoute();\n this.hdRouteSHI.removeRoute(e37.connectionName), this.hdRouteSHI.addRoute(e37), this.optimizedHdRoutes.push(e37), this.activeSubSolver = null;\n } else\n (this.activeSubSolver.failed || this.activeSubSolver.error) \u0026\u0026 (this.error = this.activeSubSolver.error, this.failed = true);\n return;\n }\n const e36 = this.unprocessedRoutes.shift();\n e36 ? this.activeSubSolver = new KB({ hdRouteSHI: this.hdRouteSHI, obstacleSHI: this.obstacleSHI, unsimplifiedRoute: e36, connMap: this.input.connMap, outline: this.input.outline, geometryShortcutTraceMargin: this.input.geometryShortcutTraceMargin, geometryShortcutObstacleMargin: this.input.geometryShortcutObstacleMargin, enableGeometryShortcuts: this.input.enableGeometryShortcuts, enableObstacleDetourShortcuts: this.input.enableObstacleDetourShortcuts, enableRoutedTraceDetours: this.input.enableRoutedTraceDetours, preserveRouteEndpoints: this.input.preserveRouteEndpoints, terminalLayerIndicesByPcbPortId: this.input.terminalLayerIndicesByPcbPortId }) : this.solved = true;\n }\n getOptimizedHdRoutes() {\n return this.optimizedHdRoutes;\n }\n visualize() {\n const e36 = { lines: [], points: [], rects: [], circles: [], coordinateSystem: \"cartesian\", title: \"Useless Via Removal Solver\" };\n for (const t2 of this.input.obstacles) {\n let n2 = \"rgba(128, 128, 128, 0.2)\";\n const o3 = t2.__zLayers?.includes(0), i3 = t2.__zLayers?.includes(1);\n o3 \u0026\u0026 i3 ? n2 = \"rgba(128, 0, 128, 0.2)\" : o3 ? n2 = \"rgba(255, 0, 0, 0.2)\" : i3 \u0026\u0026 (n2 = \"rgba(0, 0, 255, 0.2)\"), e36.rects.push({ center: t2.center, width: t2.width, height: t2.height, fill: n2, label: `Obstacle (Z: ${t2.__zLayers?.join(\", \")})` });\n }\n for (const t2 of this.optimizedHdRoutes) {\n if (t2.route.length === 0)\n continue;\n const n2 = this.input.colorMap[t2.connectionName] || \"#888888\";\n for (let n3 = 0;n3 \u003c t2.route.length - 1; n3++) {\n const o3 = t2.route[n3], i3 = t2.route[n3 + 1];\n o3.z === i3.z \u0026\u0026 e36.lines.push({ points: [{ x: o3.x, y: o3.y }, { x: i3.x, y: i3.y }], strokeColor: o3.z === 0 ? \"red\" : \"blue\", strokeWidth: t2.traceThickness, label: `${t2.connectionName} (z=${o3.z})` });\n }\n for (const n3 of t2.vias)\n e36.circles.push({ center: { x: n3.x, y: n3.y }, radius: t2.viaDiameter / 2, fill: \"rgba(255, 0, 255, 0.5)\", label: `${t2.connectionName} via` });\n if (t2.jumpers \u0026\u0026 t2.jumpers.length \u003e 0) {\n const o3 = oF(t2.jumpers, { color: n2, label: t2.connectionName });\n e36.rects.push(...o3.rects ?? []), e36.lines.push(...o3.lines ?? []);\n }\n }\n return this.activeSubSolver \u0026\u0026 e36.lines.push(...this.activeSubSolver.visualize().lines ?? []), e36;\n }\n};\nvar cF = class {\n netMap;\n idToNetMap;\n constructor(e36) {\n this.netMap = e36, this.idToNetMap = {};\n for (const [t2, n2] of Object.entries(e36))\n for (const e37 of n2)\n this.idToNetMap[e37] = t2;\n }\n addConnections(e36) {\n for (const t2 of e36) {\n const e37 = new Set;\n for (const n3 of t2) {\n const t3 = this.idToNetMap[n3];\n t3 \u0026\u0026 e37.add(t3);\n }\n let n2;\n if (e37.size === 0)\n n2 = `connectivity_net${Object.keys(this.netMap).length}`, this.netMap[n2] = [];\n else if (e37.size === 1)\n n2 = e37.values().next().value ?? `connectivity_net${Object.keys(this.netMap).length}`;\n else {\n n2 = e37.values().next().value ?? `connectivity_net${Object.keys(this.netMap).length}`;\n for (const t3 of e37)\n if (t3 !== n2) {\n this.netMap[n2].push(...this.netMap[t3]), this.netMap[t3] = this.netMap[n2];\n for (const e38 of this.netMap[n2])\n this.idToNetMap[e38] = n2;\n }\n }\n for (const e38 of t2)\n this.netMap[n2].includes(e38) || this.netMap[n2].push(e38), this.idToNetMap[e38] = n2;\n }\n }\n getIdsConnectedToNet(e36) {\n return this.netMap[e36] || [];\n }\n getNetConnectedToId(e36) {\n return this.idToNetMap[e36];\n }\n areIdsConnected(e36, t2) {\n if (e36 === t2)\n return true;\n const n2 = this.getNetConnectedToId(e36);\n if (!n2)\n return false;\n const o3 = this.getNetConnectedToId(t2);\n return !!o3 \u0026\u0026 (n2 === o3 || o3 === e36 || o3 === e36);\n }\n areAllIdsConnected(e36) {\n const t2 = this.getNetConnectedToId(e36[0]);\n for (const n2 of e36) {\n const e37 = this.getNetConnectedToId(n2);\n if (e37 === undefined)\n return false;\n if (e37 !== t2)\n return false;\n }\n return true;\n }\n};\nvar lF = class extends SB {\n getSolverName() {\n return \"SingleSimplifiedPathSolver\";\n }\n newRoute;\n newVias;\n headIndex = 0;\n tailIndex = 0;\n inputRoute;\n otherHdRoutes;\n obstacles;\n connMap;\n colorMap;\n outline;\n minBoardEdgeClearance;\n constructor(e36) {\n super(), this.inputRoute = e36.inputRoute, this.otherHdRoutes = e36.otherHdRoutes, this.obstacles = e36.obstacles, this.connMap = e36.connMap, this.colorMap = e36.colorMap, this.outline = e36.outline, this.minBoardEdgeClearance = e36.minBoardEdgeClearance ?? 0.2, this.newRoute = [this.inputRoute.route[0]], this.newVias = [];\n }\n getConstructorParams() {\n return { inputRoute: this.inputRoute, otherHdRoutes: this.otherHdRoutes, obstacles: this.obstacles, connMap: this.connMap.netMap, colorMap: this.colorMap, outline: this.outline, minBoardEdgeClearance: this.minBoardEdgeClearance };\n }\n get simplifiedRoute() {\n return { connectionName: this.inputRoute.connectionName, rootConnectionName: this.inputRoute.rootConnectionName, startPcbPortId: this.inputRoute.startPcbPortId, endPcbPortId: this.inputRoute.endPcbPortId, traceThickness: this.inputRoute.traceThickness, viaDiameter: this.inputRoute.viaDiameter, route: this.newRoute, vias: this.newVias, jumpers: this.inputRoute.jumpers };\n }\n isValidPath(e36) {\n throw new Error(\"Not implemented\");\n }\n _step() {\n throw new Error(\"Not implemented\");\n }\n getVisualsForNewRouteAndObstacles() {\n const e36 = { lines: [], points: [], circles: [], rects: [], coordinateSystem: \"cartesian\", title: \"Simplified Path Solver\" };\n for (let t2 = 0;t2 \u003c this.inputRoute.route.length - 1; t2++)\n e36.lines.push({ points: [{ x: this.inputRoute.route[t2].x, y: this.inputRoute.route[t2].y }, { x: this.inputRoute.route[t2 + 1].x, y: this.inputRoute.route[t2 + 1].y }], strokeColor: \"rgba(255, 0, 0, 0.8)\", strokeDash: this.inputRoute.route[t2].z === 1 ? \"5, 5\" : undefined, layer: `z${this.inputRoute.route[t2].z.toString()}` });\n for (let t2 = 0;t2 \u003c this.newRoute.length; t2++)\n t2 \u003c this.newRoute.length - 1 \u0026\u0026 e36.lines.push({ points: [{ x: this.newRoute[t2].x, y: this.newRoute[t2].y }, { x: this.newRoute[t2 + 1].x, y: this.newRoute[t2 + 1].y }], strokeWidth: 0.15, strokeColor: \"rgba(0, 255, 0, 0.8)\", strokeDash: this.newRoute[t2].z === 1 ? [0.4, 0.4] : undefined, layer: `z${this.newRoute[t2].z.toString()}` }), e36.points.push({ x: this.newRoute[t2].x, y: this.newRoute[t2].y, color: \"rgba(0, 255, 0, 0.8)\", label: `z: ${this.newRoute[t2].z}`, layer: `z${this.newRoute[t2].z.toString()}` });\n for (const t2 of this.newVias)\n e36.circles.push({ center: t2, radius: this.inputRoute.viaDiameter / 2, fill: \"rgba(0, 0, 255, 0.5)\" });\n for (const t2 of this.obstacles)\n e36.rects.push({ center: t2.center, width: t2.width, height: t2.height, fill: t2.layers?.includes(\"top\") ? \"rgba(255, 0, 0, 0.3)\" : t2.layers?.includes(\"bottom\") ? \"rgba(0, 0, 255, 0.3)\" : \"rgba(128, 128, 128, 0.3)\" });\n for (const t2 of this.otherHdRoutes)\n for (let n2 = 0;n2 \u003c t2.route.length - 1; n2++)\n e36.lines.push({ points: [{ x: t2.route[n2].x, y: t2.route[n2].y }, { x: t2.route[n2 + 1].x, y: t2.route[n2 + 1].y }], strokeWidth: 0.15, strokeColor: t2.route[n2].z === 0 ? \"rgba(255, 0, 255, 0.5)\" : t2.route[n2].z === 1 ? \"rgba(128, 0, 128, 0.5)\" : \"rgba(0, 0, 255, 0.5)\", layer: `z${t2.route[n2].z.toString()}` });\n if (\"filteredObstaclePathSegments\" in this) {\n const t2 = this.filteredObstaclePathSegments;\n for (const [n2, o3] of t2)\n e36.lines.push({ points: [n2, o3] });\n }\n return e36;\n }\n};\nvar hF = (e36) =\u003e ({ minX: Math.min(e36[0].x, e36[1].x), maxX: Math.max(e36[0].x, e36[1].x), minY: Math.min(e36[0].y, e36[1].y), maxY: Math.max(e36[0].y, e36[1].y) });\nvar dF = class {\n constructor(e36, t2 = 0.4) {\n this.segments = e36, this.buckets = new Map, this.SEGMENT_MARGIN = t2;\n const n2 = new Map;\n for (const t3 of e36) {\n const e37 = this.getSegmentKey(t3);\n if (n2.has(e37))\n continue;\n n2.set(e37, t3);\n const o3 = hF(t3), i3 = Math.floor(o3.minX / this.CELL_SIZE), r3 = Math.floor(o3.maxX / this.CELL_SIZE), s2 = Math.floor(o3.minY / this.CELL_SIZE), a3 = Math.floor(o3.maxY / this.CELL_SIZE);\n for (let n3 = i3;n3 \u003c= r3; n3++)\n for (let o4 = s2;o4 \u003c= a3; o4++) {\n const i4 = `${n3}x${o4}`, r4 = this.buckets.get(i4), s3 = [t3[0], t3[1], e37];\n r4 ? r4.push(s3) : this.buckets.set(i4, [s3]);\n }\n }\n }\n buckets;\n CELL_SIZE = 0.4;\n SEGMENT_MARGIN;\n getBucketKey(e36, t2) {\n return `${Math.floor(e36 / this.CELL_SIZE)}x${Math.floor(t2 / this.CELL_SIZE)}`;\n }\n getSegmentKey(e36) {\n return `${e36[0].x}-${e36[0].y}-${e36[0].z}-${e36[1].x}-${e36[1].y}-${e36[1].z}`;\n }\n getSegmentsThatCouldIntersect(e36, t2) {\n const n2 = [], o3 = new Set, i3 = Math.min(e36.x, t2.x) - this.SEGMENT_MARGIN, r3 = Math.min(e36.y, t2.y) - this.SEGMENT_MARGIN, s2 = Math.max(e36.x, t2.x) + this.SEGMENT_MARGIN, a3 = Math.max(e36.y, t2.y) + this.SEGMENT_MARGIN, c3 = Math.floor(i3 / this.CELL_SIZE), l3 = Math.floor(s2 / this.CELL_SIZE), h2 = Math.floor(r3 / this.CELL_SIZE), d2 = Math.floor(a3 / this.CELL_SIZE);\n for (let e37 = c3;e37 \u003c= l3; e37++)\n for (let t3 = h2;t3 \u003c= d2; t3++) {\n const i4 = `${e37}x${t3}`, r4 = this.buckets.get(i4);\n if (r4)\n for (const e38 of r4) {\n const t4 = e38[2];\n o3.has(t4) || (o3.add(t4), n2.push(e38));\n }\n }\n return n2;\n }\n};\nvar uF = class extends lF {\n pathSegments = [];\n totalPathLength = 0;\n headDistanceAlongPath = 0;\n tailDistanceAlongPath = 0;\n minStepSize = 0.25;\n lastValidPath = null;\n lastValidPathHeadDistance = 0;\n STEP_SIZE_REDUCTION_FACTOR = 0.25;\n maxStepSize = 4;\n currentStepSize = this.maxStepSize;\n lastHeadMoveDistance = 0;\n cachedValidPathSegments;\n filteredObstacles = [];\n filteredObstaclePathSegments = [];\n traceThicknessByObstacleSegmentId = new Map;\n filteredVias = [];\n filteredJumperPads = [];\n jumperPadPointIndices = new Set;\n segmentTree;\n OBSTACLE_MARGIN = 0.1;\n TRACE_THICKNESS = 0.15;\n useTraceWidthAwareClearance = false;\n clearanceTraceThickness = this.TRACE_THICKNESS;\n TAIL_JUMP_RATIO = 0.8;\n isSameNetRoute(e36) {\n const t2 = [this.inputRoute.connectionName, this.inputRoute.rootConnectionName].filter((e37) =\u003e e37 !== undefined), n2 = [e36.connectionName, e36.rootConnectionName].filter((e37) =\u003e e37 !== undefined);\n return t2.some((e37) =\u003e n2.some((t3) =\u003e e37 === t3 || this.connMap.areIdsConnected(e37, t3)));\n }\n constructor(e36) {\n if (super(e36), this.cachedValidPathSegments = new Set, this.useTraceWidthAwareClearance = e36.useTraceWidthAwareClearance ?? false, this.clearanceTraceThickness = this.useTraceWidthAwareClearance ? this.inputRoute.traceThickness : this.TRACE_THICKNESS, this.inputRoute.route.length \u003c= 1)\n return this.newRoute = [...this.inputRoute.route], void (this.solved = true);\n const t2 = this.inputRoute.route.reduce((e37, t3) =\u003e (e37.minX = Math.min(e37.minX, t3.x), e37.maxX = Math.max(e37.maxX, t3.x), e37.minY = Math.min(e37.minY, t3.y), e37.maxY = Math.max(e37.maxY, t3.y), e37), { minX: 1 / 0, maxX: -1 / 0, minY: 1 / 0, maxY: -1 / 0 }), n2 = this.useTraceWidthAwareClearance ? Math.max(0, ...this.otherHdRoutes.flatMap((e37) =\u003e [e37.traceThickness, ...e37.route.map((t3) =\u003e t3.traceThickness ?? e37.traceThickness)])) : this.TRACE_THICKNESS, o3 = this.useTraceWidthAwareClearance ? this.OBSTACLE_MARGIN + this.clearanceTraceThickness / 2 + n2 / 2 : this.OBSTACLE_MARGIN + this.TRACE_THICKNESS, i3 = { center: { x: (t2.minX + t2.maxX) / 2, y: (t2.minY + t2.maxY) / 2 }, width: t2.maxX - t2.minX, height: t2.maxY - t2.minY }, r3 = this.OBSTACLE_MARGIN + this.clearanceTraceThickness / 2, s2 = e36.geometryQuery ? e36.geometryQuery.index.getCandidateObstacles({ minX: i3.center.x - i3.width / 2, minY: i3.center.y - i3.height / 2, maxX: i3.center.x + i3.width / 2, maxY: i3.center.y + i3.height / 2 }, r3) : this.obstacles, a3 = e36.geometryQuery ? e36.geometryQuery.index.getCandidateRoutes(t2, Math.max(o3, r3), e36.geometryQuery.routeIndex) : this.otherHdRoutes;\n this.filteredObstacles = s2.filter((e37) =\u003e !e37.connectedTo.some((e38) =\u003e this.connMap.areIdsConnected(this.inputRoute.connectionName, e38))).filter((e37) =\u003e {\n if (e37.connectedTo.some((e38) =\u003e this.connMap.areIdsConnected(this.inputRoute.connectionName, e38)))\n return false;\n return function(e38, t3) {\n const n3 = Pe(e38), o4 = Pe(t3), i4 = Math.max(n3.minX - o4.maxX, o4.minX - n3.maxX, 0), r4 = Math.max(n3.minY - o4.maxY, o4.minY - n3.maxY, 0);\n return Math.hypot(i4, r4);\n }(i3, e37) \u003c this.OBSTACLE_MARGIN + this.clearanceTraceThickness / 2;\n }), this.filteredObstaclePathSegments = a3.flatMap((e37) =\u003e {\n if (this.isSameNetRoute(e37))\n return [];\n const n3 = e37.route, i4 = [];\n for (let r4 = 0;r4 \u003c n3.length - 1; r4++) {\n const s3 = n3[r4], a4 = n3[r4 + 1];\n if (Ne(s3, a4, t2) \u003c= o3) {\n i4.push([s3, a4]);\n const t3 = `${s3.x}-${s3.y}-${s3.z}-${a4.x}-${a4.y}-${a4.z}`;\n if (this.useTraceWidthAwareClearance) {\n const n4 = Math.max(s3.traceThickness ?? e37.traceThickness, a4.traceThickness ?? e37.traceThickness);\n this.traceThicknessByObstacleSegmentId.set(t3, Math.max(this.traceThicknessByObstacleSegmentId.get(t3) ?? 0, n4));\n }\n }\n }\n return i4;\n }), this.segmentTree = this.useTraceWidthAwareClearance ? new dF(this.filteredObstaclePathSegments, o3) : new dF(this.filteredObstaclePathSegments), this.filteredVias = a3.flatMap((e37) =\u003e {\n if (this.isSameNetRoute(e37))\n return [];\n const n3 = e37.vias, o4 = [];\n for (const i4 of n3) {\n const n4 = this.OBSTACLE_MARGIN + this.clearanceTraceThickness / 2 + e37.viaDiameter / 2, r4 = i4.x - n4, s3 = i4.x + n4, a4 = i4.y - n4, c4 = i4.y + n4;\n r4 \u003c= t2.maxX \u0026\u0026 s3 \u003e= t2.minX \u0026\u0026 a4 \u003c= t2.maxY \u0026\u0026 c4 \u003e= t2.minY \u0026\u0026 o4.push({ ...i4, diameter: e37.viaDiameter });\n }\n return o4;\n });\n const c3 = (e37, n3) =\u003e {\n const o4 = [];\n for (const i4 of e37) {\n const e38 = tF[i4.footprint] ?? tF[\"0603\"], r4 = i4.end.x - i4.start.x, s3 = i4.end.y - i4.start.y, a4 = Math.abs(r4) \u003e Math.abs(s3), c4 = a4 ? e38.padLength : e38.padWidth, l3 = a4 ? e38.padWidth : e38.padLength, h2 = this.OBSTACLE_MARGIN + this.clearanceTraceThickness / 2;\n i4.start.x - c4 / 2 - h2 \u003c= t2.maxX \u0026\u0026 i4.start.x + c4 / 2 + h2 \u003e= t2.minX \u0026\u0026 i4.start.y - l3 / 2 - h2 \u003c= t2.maxY \u0026\u0026 i4.start.y + l3 / 2 + h2 \u003e= t2.minY \u0026\u0026 o4.push({ center: i4.start, width: c4, height: l3, connectionName: n3 }), i4.end.x - c4 / 2 - h2 \u003c= t2.maxX \u0026\u0026 i4.end.x + c4 / 2 + h2 \u003e= t2.minX \u0026\u0026 i4.end.y - l3 / 2 - h2 \u003c= t2.maxY \u0026\u0026 i4.end.y + l3 / 2 + h2 \u003e= t2.minY \u0026\u0026 o4.push({ center: i4.end, width: c4, height: l3, connectionName: n3 });\n }\n return o4;\n };\n if (this.filteredJumperPads = a3.flatMap((e37) =\u003e this.isSameNetRoute(e37) ? [] : c3(e37.jumpers ?? [], e37.connectionName)), this.inputRoute.jumpers \u0026\u0026 this.inputRoute.jumpers.length \u003e 0) {\n this.filteredJumperPads.push(...c3(this.inputRoute.jumpers, this.inputRoute.connectionName));\n for (const e37 of this.inputRoute.jumpers)\n for (let t3 = 0;t3 \u003c this.inputRoute.route.length; t3++) {\n const n3 = this.inputRoute.route[t3];\n (Math.abs(n3.x - e37.start.x) \u003c 0.01 \u0026\u0026 Math.abs(n3.y - e37.start.y) \u003c 0.01 || Math.abs(n3.x - e37.end.x) \u003c 0.01 \u0026\u0026 Math.abs(n3.y - e37.end.y) \u003c 0.01) \u0026\u0026 this.jumperPadPointIndices.add(t3);\n }\n }\n this.computePathSegments(), this.MAX_ITERATIONS = Math.max(this.MAX_ITERATIONS, 6 * (Math.ceil(this.totalPathLength / this.minStepSize) + this.pathSegments.length));\n }\n computePathSegments() {\n let e36 = 0;\n for (let t2 = 0;t2 \u003c this.inputRoute.route.length - 1; t2++) {\n const n2 = this.inputRoute.route[t2], o3 = this.inputRoute.route[t2 + 1], i3 = Math.sqrt((o3.x - n2.x) ** 2 + (o3.y - n2.y) ** 2) + t2 / 1e4;\n this.pathSegments.push({ start: n2, end: o3, length: i3, startDistance: e36, endDistance: e36 + i3 }), e36 += i3;\n }\n this.totalPathLength = e36;\n }\n arePointsEqual(e36, t2) {\n return e36.x === t2.x \u0026\u0026 e36.y === t2.y \u0026\u0026 e36.z === t2.z;\n }\n getPointAtDistance(e36) {\n e36 = Math.max(0, Math.min(e36, this.totalPathLength));\n const t2 = this.pathSegments.find((t3) =\u003e e36 \u003e= t3.startDistance \u0026\u0026 e36 \u003c= t3.endDistance);\n if (!t2)\n return this.inputRoute.route[this.inputRoute.route.length - 1];\n const n2 = (e36 - t2.startDistance) / t2.length;\n return { x: t2.start.x + n2 * (t2.end.x - t2.start.x), y: t2.start.y + n2 * (t2.end.y - t2.start.y), z: n2 \u003c 0.5 ? t2.start.z : t2.end.z };\n }\n getNearestIndexForDistance(e36) {\n if (e36 \u003c= 0)\n return 0;\n if (e36 \u003e= this.totalPathLength)\n return this.inputRoute.route.length - 1;\n const t2 = this.pathSegments.findIndex((t3) =\u003e e36 \u003e= t3.startDistance \u0026\u0026 e36 \u003c= t3.endDistance);\n if (t2 === -1)\n return 0;\n const n2 = this.pathSegments[t2], o3 = (n2.startDistance + n2.endDistance) / 2;\n return e36 \u003e o3 ? t2 + 1 : t2;\n }\n isValidPathSegment(e36, t2) {\n for (const n3 of this.filteredObstacles) {\n if (!n3.__zLayers?.includes(e36.z))\n continue;\n if (Re(e36, t2, n3) \u003c this.OBSTACLE_MARGIN + this.clearanceTraceThickness / 2)\n return false;\n }\n const n2 = this.segmentTree.getSegmentsThatCouldIntersect(e36, t2);\n for (const [o3, i3, r3] of n2)\n if (o3.z === e36.z \u0026\u0026 i3.z === e36.z) {\n const n3 = jB({ x: e36.x, y: e36.y }, { x: t2.x, y: t2.y }, { x: o3.x, y: o3.y }, { x: i3.x, y: i3.y });\n if (!this.useTraceWidthAwareClearance) {\n if (n3 \u003c this.OBSTACLE_MARGIN + this.TRACE_THICKNESS)\n return false;\n continue;\n }\n const s2 = this.traceThicknessByObstacleSegmentId.get(r3);\n if (s2 === undefined)\n throw new Error(`Missing trace thickness for segment \"${r3}\"`);\n if (n3 \u003c this.OBSTACLE_MARGIN + this.clearanceTraceThickness / 2 + s2 / 2)\n return false;\n }\n for (const n3 of this.filteredVias)\n if (pe(n3, e36, t2) \u003c this.OBSTACLE_MARGIN + n3.diameter / 2 + this.clearanceTraceThickness / 2)\n return false;\n for (const n3 of this.filteredJumperPads) {\n if (Re(e36, t2, n3) \u003c this.OBSTACLE_MARGIN + this.clearanceTraceThickness / 2)\n return false;\n }\n if (this.outline \u0026\u0026 this.outline.length \u003e= 3) {\n if (UB({ start: { x: e36.x, y: e36.y }, end: { x: t2.x, y: t2.y }, polygon: this.outline, margin: this.minBoardEdgeClearance + this.inputRoute.traceThickness / 2 }))\n return false;\n }\n return true;\n }\n isValidPath(e36) {\n if (e36.length \u003c 2)\n return true;\n for (let t2 = 0;t2 \u003c e36.length - 1; t2++)\n if (e36[t2].z !== e36[t2 + 1].z)\n return false;\n for (let t2 = 0;t2 \u003c e36.length - 1; t2++)\n if (!this.isValidPathSegment(e36[t2], e36[t2 + 1]))\n return false;\n return true;\n }\n find45DegreePath(e36, t2) {\n if (this.arePointsEqual(e36, t2))\n return [e36];\n if (e36.z !== t2.z)\n return null;\n const n2 = BB({ x: e36.x, y: e36.y }, { x: t2.x, y: t2.y });\n for (const t3 of n2) {\n const n3 = t3.map((t4) =\u003e ({ x: t4.x, y: t4.y, z: e36.z }));\n if (this.isValidPath(n3))\n return n3;\n }\n return null;\n }\n addPathToResult(e36) {\n if (e36.length !== 0) {\n for (let t2 = 0;t2 \u003c e36.length; t2++)\n t2 === 0 \u0026\u0026 this.newRoute.length \u003e 0 \u0026\u0026 this.arePointsEqual(this.newRoute[this.newRoute.length - 1], e36[t2]) || this.newRoute.push(e36[t2]);\n this.currentStepSize = this.maxStepSize;\n }\n }\n appendOriginalRouteSlice(e36, t2) {\n const n2 = this.pathSegments.findIndex((t3) =\u003e e36 \u003e= t3.startDistance \u0026\u0026 e36 \u003c= t3.endDistance);\n if (n2 === -1)\n throw new Error(`Could not find path segment containing distance ${e36}`);\n for (let e37 = n2 + 1;e37 \u003c= t2 \u0026\u0026 e37 \u003c this.inputRoute.route.length; e37++) {\n const t3 = this.inputRoute.route[e37], n3 = this.newRoute[this.newRoute.length - 1];\n n3 \u0026\u0026 this.arePointsEqual(n3, t3) || this.newRoute.push({ ...t3 });\n }\n }\n moveHead(e36) {\n this.lastHeadMoveDistance = e36, this.headDistanceAlongPath = Math.min(this.headDistanceAlongPath + e36, this.totalPathLength);\n }\n stepBackAndReduceStepSize() {\n this.headDistanceAlongPath = Math.max(this.tailDistanceAlongPath, this.headDistanceAlongPath - this.lastHeadMoveDistance), this.currentStepSize = Math.max(this.minStepSize, this.currentStepSize * this.STEP_SIZE_REDUCTION_FACTOR);\n }\n _step() {\n const e36 = this.tailDistanceAlongPath \u003e= this.totalPathLength, t2 = this.headDistanceAlongPath \u003e= this.totalPathLength;\n if (e36) {\n const e37 = this.inputRoute.route[this.inputRoute.route.length - 1];\n return this.newRoute.length !== 0 \u0026\u0026 this.arePointsEqual(this.newRoute[this.newRoute.length - 1], e37) || this.newRoute.push(e37), void (this.solved = true);\n }\n if (t2) {\n const e37 = this.getPointAtDistance(this.tailDistanceAlongPath), t3 = this.inputRoute.route[this.inputRoute.route.length - 1], n3 = this.find45DegreePath(e37, t3);\n if (n3)\n return this.addPathToResult(n3), void (this.solved = true);\n const o4 = this.lastValidPath ? this.lastValidPathHeadDistance : this.tailDistanceAlongPath;\n this.lastValidPath \u0026\u0026 (this.addPathToResult(this.lastValidPath), this.lastValidPath = null);\n this.getNearestIndexForDistance(o4);\n return this.appendOriginalRouteSlice(o4, this.inputRoute.route.length - 1), this.tailDistanceAlongPath = this.totalPathLength, this.headDistanceAlongPath = this.totalPathLength, void (this.solved = true);\n }\n this.moveHead(this.currentStepSize);\n const n2 = this.getPointAtDistance(this.tailDistanceAlongPath), o3 = this.getPointAtDistance(this.headDistanceAlongPath), i3 = this.getNearestIndexForDistance(this.tailDistanceAlongPath), r3 = this.getNearestIndexForDistance(this.headDistanceAlongPath);\n let s2 = false, a3 = -1;\n for (let e37 = i3;e37 \u003c r3; e37++)\n if (e37 + 1 \u003c this.inputRoute.route.length \u0026\u0026 this.inputRoute.route[e37].z !== this.inputRoute.route[e37 + 1].z) {\n s2 = true;\n const t3 = e37;\n a3 = this.pathSegments[t3].startDistance;\n break;\n }\n if (s2 \u0026\u0026 this.lastHeadMoveDistance \u003e this.minStepSize)\n return void this.stepBackAndReduceStepSize();\n let c3 = false, l3 = -1, h2 = -1;\n for (let e37 = i3 + 1;e37 \u003c= r3; e37++)\n if (this.jumperPadPointIndices.has(e37)) {\n c3 = true, l3 = e37, h2 = e37 \u003e 0 \u0026\u0026 e37 - 1 \u003c this.pathSegments.length ? this.pathSegments[e37 - 1].endDistance : this.pathSegments[0]?.startDistance ?? 0;\n break;\n }\n if (c3 \u0026\u0026 this.lastHeadMoveDistance \u003e this.minStepSize)\n return void this.stepBackAndReduceStepSize();\n if (c3 \u0026\u0026 l3 \u003e= 0) {\n const e37 = this.inputRoute.route[l3];\n this.lastValidPath \u0026\u0026 (this.addPathToResult(this.lastValidPath), this.lastValidPath = null);\n const t3 = this.newRoute[this.newRoute.length - 1];\n return t3 \u0026\u0026 t3.x === e37.x \u0026\u0026 t3.y === e37.y || this.newRoute.push({ x: e37.x, y: e37.y, z: e37.z }), this.currentStepSize = this.maxStepSize, this.tailDistanceAlongPath = h2, this.headDistanceAlongPath = this.tailDistanceAlongPath, this.lastValidPath = null, void (this.lastValidPathHeadDistance = this.tailDistanceAlongPath);\n }\n if (s2 \u0026\u0026 a3 \u003e 0) {\n const e37 = this.lastValidPath ? this.lastValidPathHeadDistance : this.tailDistanceAlongPath, t3 = this.getNearestIndexForDistance(a3) + 1, n3 = this.inputRoute.route[t3], o4 = { x: n3.x, y: n3.y };\n this.lastValidPath \u0026\u0026 (this.addPathToResult(this.lastValidPath), this.lastValidPath = null);\n const i4 = this.newRoute[this.newRoute.length - 1], r4 = { x: o4.x, y: o4.y, z: i4.z };\n if (!this.arePointsEqual(i4, r4)) {\n const n4 = this.find45DegreePath(i4, r4);\n n4 ? this.addPathToResult(n4) : this.appendOriginalRouteSlice(e37, t3 - 1);\n }\n this.newVias.push(o4), this.newRoute.push({ x: o4.x, y: o4.y, z: n3.z }), this.currentStepSize = this.maxStepSize;\n const s3 = this.pathSegments.findIndex((e38) =\u003e e38.start === n3);\n if (s3 !== -1)\n this.tailDistanceAlongPath = this.pathSegments[s3].startDistance, this.headDistanceAlongPath = this.tailDistanceAlongPath, this.lastValidPath = null, this.lastValidPathHeadDistance = this.tailDistanceAlongPath;\n else if (t3 \u003c this.inputRoute.route.length) {\n if (t3 === this.inputRoute.route.length - 1)\n return void (this.solved = true);\n console.warn(\"Fallback used for tailDistanceAlongPath after layer change\");\n const e38 = this.pathSegments.find((e39) =\u003e e39.start === this.inputRoute.route[t3]);\n e38 ? (this.tailDistanceAlongPath = e38.startDistance, this.headDistanceAlongPath = this.tailDistanceAlongPath, this.lastValidPath = null, this.lastValidPathHeadDistance = this.tailDistanceAlongPath) : (console.error(`[${this.inputRoute.connectionName}] Could not find segment start after layer change. Path might be incomplete.\n Index sought: ${t3}, Point: (${this.inputRoute.route[t3].x.toFixed(3)}, ${this.inputRoute.route[t3].y.toFixed(3)}, z=${this.inputRoute.route[t3].z})\n Route Length: ${this.inputRoute.route.length}, Path Segments: ${this.pathSegments.length}`), this.solved = true);\n } else\n console.warn(\"Layer change occurred at the end of the path.\"), this.solved = true;\n return;\n }\n const d2 = this.find45DegreePath(n2, o3);\n if (!d2 \u0026\u0026 this.lastHeadMoveDistance \u003e this.minStepSize)\n this.stepBackAndReduceStepSize();\n else {\n if (!d2 \u0026\u0026 !this.lastValidPath) {\n const e37 = this.getPointAtDistance(this.tailDistanceAlongPath);\n this.tailDistanceAlongPath += this.minStepSize, this.moveHead(this.minStepSize);\n let t3 = this.getNearestIndexForDistance(this.tailDistanceAlongPath);\n for (let e38 = i3;e38 \u003c t3; e38++)\n if (this.inputRoute.route[e38].z !== this.inputRoute.route[e38 + 1].z) {\n t3 = e38;\n break;\n }\n const n3 = this.inputRoute.route[t3], o4 = this.inputRoute.route[this.inputRoute.route.length - 1];\n return void (this.arePointsEqual(e37, n3) || this.arePointsEqual(n3, o4) || (this.newRoute.push(n3), this.tailDistanceAlongPath = t3 === 0 ? 0 : this.pathSegments[t3 - 1].endDistance));\n }\n if (d2)\n return this.lastValidPath = d2, void (this.lastValidPathHeadDistance = this.headDistanceAlongPath);\n this.lastValidPath \u0026\u0026 (this.addPathToResult(this.lastValidPath), this.lastValidPath = null, this.tailDistanceAlongPath = this.lastValidPathHeadDistance, this.moveHead(this.minStepSize));\n }\n }\n visualize() {\n const e36 = this.getVisualsForNewRouteAndObstacles(), t2 = this.getPointAtDistance(this.tailDistanceAlongPath), n2 = this.getPointAtDistance(this.headDistanceAlongPath);\n e36.points.push({ x: t2.x, y: t2.y, color: \"yellow\", label: [\"Tail\", `z: ${t2.z}`].join(`\n`) }), e36.points.push({ x: n2.x, y: n2.y, color: \"orange\", label: [\"Head\", `z: ${n2.z}`].join(`\n`) });\n const o3 = this.getPointAtDistance(this.headDistanceAlongPath + this.currentStepSize);\n e36.points.push({ x: o3.x, y: o3.y, color: \"red\", label: [\"Tentative Head\", `z: ${o3.z}`].join(`\n`) });\n let i3 = 0;\n for (;i3 \u003c this.totalPathLength; ) {\n const t3 = this.getPointAtDistance(i3);\n e36.circles.push({ center: { x: t3.x, y: t3.y }, radius: 0.05, fill: \"rgba(100, 100, 100, 0.5)\" }), i3 += this.totalPathLength / 20;\n }\n if (this.lastValidPath \u0026\u0026 this.lastValidPath.length \u003e 1)\n for (let t3 = 0;t3 \u003c this.lastValidPath.length - 1; t3++)\n e36.lines.push({ points: [{ x: this.lastValidPath[t3].x, y: this.lastValidPath[t3].y }, { x: this.lastValidPath[t3 + 1].x, y: this.lastValidPath[t3 + 1].y }], strokeColor: \"rgba(0, 255, 255, 0.9)\", strokeDash: \"3, 3\" });\n return e36;\n }\n};\nvar pF = class extends uF {\n vertexIndex = 0;\n constructor(e36) {\n super(e36), this.newRoute = this.inputRoute.route.slice(0, 1).map((e37) =\u003e ({ ...e37 })), this.newVias = this.inputRoute.vias.map((e37) =\u003e ({ ...e37 }));\n }\n getSolverName() {\n return \"VertexShortcutPathSolver\";\n }\n _step() {\n const e36 = this.inputRoute.route, t2 = e36[this.vertexIndex];\n if (this.vertexIndex \u003e= e36.length - 1)\n return void (this.solved = true);\n let n2 = this.vertexIndex + 1;\n const o3 = [0];\n for (let t3 = this.vertexIndex;t3 \u003c e36.length - 1; t3++) {\n const i3 = e36[t3], r3 = e36[t3 + 1];\n if (i3.z !== r3.z || i3.toNextSegmentType || i3.traceThickness !== r3.traceThickness || i3.traceThickness !== undefined \u0026\u0026 i3.traceThickness !== this.inputRoute.traceThickness || i3.insideJumperPad || r3.insideJumperPad)\n break;\n if (o3.push(o3.at(-1) + Math.hypot(r3.x - i3.x, r3.y - i3.y)), n2 = t3 + 1, r3.pcb_port_id || this.jumperPadPointIndices.has(n2))\n break;\n }\n for (let i3 = n2;i3 \u003e this.vertexIndex + 1; i3--) {\n const n3 = e36[i3], r3 = o3[i3 - this.vertexIndex];\n for (const e37 of BB(t2, n3)) {\n const o4 = e37.filter((t3, n4) =\u003e n4 === 0 || t3.x !== e37[n4 - 1].x || t3.y !== e37[n4 - 1].y).map((e38) =\u003e ({ ...e38, z: t2.z, traceThickness: t2.traceThickness })), s2 = o4.reduce((e38, t3, n4) =\u003e n4 === 0 ? e38 : e38 + Math.hypot(t3.x - o4[n4 - 1].x, t3.y - o4[n4 - 1].y), 0);\n if (!(o4.length \u003c 2 || s2 \u003e r3 + 0.000000001 || s2 \u003e= r3 - 0.000000001 \u0026\u0026 o4.length \u003e= i3 - this.vertexIndex + 1) \u0026\u0026 this.isValidPath(o4))\n return o4[o4.length - 1] = { ...n3 }, this.newRoute.push(...o4.slice(1)), void (this.vertexIndex = i3);\n }\n }\n this.vertexIndex++, this.newRoute.push({ ...e36[this.vertexIndex] });\n }\n};\nvar mF = new Float64Array(1);\nvar gF = new BigUint64Array(mF.buffer);\nfunction fF(e36, t2) {\n return Number.isFinite(e36) ? e36 === 0 ? t2 ? Number.MIN_VALUE : -Number.MIN_VALUE : (mF[0] = e36, gF[0] += e36 \u003e 0 === t2 ? 1n : -1n, mF[0]) : e36;\n}\nfunction _F(e36, t2, n2 = t2) {\n const o3 = fF(t2, true), i3 = fF(n2, true);\n return { minX: fF(fF(e36.minX, false) - o3, false), minY: fF(fF(e36.minY, false) - i3, false), maxX: fF(fF(e36.maxX, true) + o3, true), maxY: fF(fF(e36.maxY, true) + i3, true) };\n}\nfunction yF(e36, t2, n2) {\n const o3 = { minX: 1 / 0, minY: 1 / 0, maxX: -1 / 0, maxY: -1 / 0 };\n for (const t3 of e36.route)\n o3.minX = Math.min(o3.minX, t3.x), o3.minY = Math.min(o3.minY, t3.y), o3.maxX = Math.max(o3.maxX, t3.x), o3.maxY = Math.max(o3.maxY, t3.y);\n for (const t3 of e36.vias) {\n const n3 = _F({ minX: t3.x, minY: t3.y, maxX: t3.x, maxY: t3.y }, Math.abs(e36.viaDiameter / 2));\n o3.minX = Math.min(o3.minX, n3.minX), o3.minY = Math.min(o3.minY, n3.minY), o3.maxX = Math.max(o3.maxX, n3.maxX), o3.maxY = Math.max(o3.maxY, n3.maxY);\n }\n for (const t3 of e36.jumpers ?? []) {\n const e37 = tF[t3.footprint] ?? tF[\"0603\"], n3 = Math.abs(t3.end.x - t3.start.x) \u003e Math.abs(t3.end.y - t3.start.y), i3 = (n3 ? e37.padLength : e37.padWidth) / 2, r3 = (n3 ? e37.padWidth : e37.padLength) / 2;\n for (const e38 of [t3.start, t3.end]) {\n const t4 = _F({ minX: e38.x, minY: e38.y, maxX: e38.x, maxY: e38.y }, i3, r3);\n o3.minX = Math.min(o3.minX, t4.minX), o3.minY = Math.min(o3.minY, t4.minY), o3.maxX = Math.max(o3.maxX, t4.maxX), o3.maxY = Math.max(o3.maxY, t4.maxY);\n }\n }\n if (e36.route.length !== 0 || e36.vias.length !== 0 || e36.jumpers?.length)\n return [o3.minX, o3.minY, o3.maxX, o3.maxY].every(Number.isFinite) ? { ..._F(o3, 0), route: e36, routeIndex: t2, immutable: n2 } : { minX: -1 / 0, minY: -1 / 0, maxX: 1 / 0, maxY: 1 / 0, route: e36, routeIndex: t2, immutable: n2 };\n}\nvar bF = class {\n constructor(e36, t2, n2) {\n this.obstacles = n2, this.mutableRoutes = e36.map((e37, t3) =\u003e yF(e37, t3, false));\n const o3 = t2.map((e37, t3) =\u003e yF(e37, t3, true)).concat(this.mutableRoutes).filter((e37) =\u003e e37 !== undefined);\n this.routeIndex.load(o3);\n const i3 = n2.map((e37, t3) =\u003e {\n const n3 = { minX: e37.center.x - e37.width / 2, minY: e37.center.y - e37.height / 2, maxX: e37.center.x + e37.width / 2, maxY: e37.center.y + e37.height / 2 };\n return Object.values(n3).every(Number.isFinite) ? this.indexedObstacleIds.push(t3) : this.unindexedObstacleIds.push(t3), n3;\n });\n if (this.indexedObstacleIds.length \u003e 0) {\n this.obstacleIndex = new MB(this.indexedObstacleIds.length);\n for (const e37 of this.indexedObstacleIds) {\n const t3 = i3[e37];\n this.obstacleIndex.add(t3.minX, t3.minY, t3.maxX, t3.maxY);\n }\n this.obstacleIndex.finish();\n }\n }\n routeIndex = new G;\n mutableRoutes;\n obstacleIndex;\n indexedObstacleIds = [];\n unindexedObstacleIds = [];\n getCandidateObstacles(e36, t2) {\n if (!Number.isFinite(t2) || !Object.values(e36).every(Number.isFinite))\n return [...this.obstacles];\n const n2 = _F(e36, Math.max(0, t2));\n return (this.obstacleIndex ? this.obstacleIndex.search(n2.minX, n2.minY, n2.maxX, n2.maxY).map((e37) =\u003e this.indexedObstacleIds[e37]) : []).concat(this.unindexedObstacleIds).sort((e37, t3) =\u003e e37 - t3).map((e37) =\u003e this.obstacles[e37]);\n }\n getCandidateRoutes(e36, t2, n2) {\n return (Number.isFinite(t2) \u0026\u0026 Object.values(e36).every(Number.isFinite) ? this.routeIndex.search(_F(e36, Math.max(0, t2))) : this.routeIndex.all()).filter((e37) =\u003e e37.immutable || e37.routeIndex !== n2).sort((e37, t3) =\u003e (e37.immutable ? 0 : e37.routeIndex \u003e n2 ? 1 : 2) - (t3.immutable ? 0 : t3.routeIndex \u003e n2 ? 1 : 2) || e37.routeIndex - t3.routeIndex).map((e37) =\u003e e37.route);\n }\n replaceRoute(e36, t2) {\n if (!Number.isInteger(e36) || e36 \u003c 0 || e36 \u003e= this.mutableRoutes.length)\n throw new Error(`Cannot replace path simplification route ${e36}`);\n const n2 = this.mutableRoutes[e36];\n n2 \u0026\u0026 this.routeIndex.remove(n2);\n const o3 = yF(t2, e36, false);\n this.mutableRoutes[e36] = o3, o3 \u0026\u0026 this.routeIndex.insert(o3);\n }\n};\nvar xF = class extends SB {\n getSolverName() {\n return \"MultiSimplifiedPathSolver\";\n }\n simplifiedHdRoutes;\n currentUnsimplifiedHdRouteIndex = 0;\n activeSubSolver = null;\n unsimplifiedHdRoutes;\n otherHdRoutes;\n obstacles;\n connMap;\n colorMap;\n outline;\n minBoardEdgeClearance;\n defaultViaDiameter;\n useTraceWidthAwareClearance;\n enableVertexShortcuts;\n geometryIndex;\n constructor(e36) {\n super(), this.MAX_ITERATIONS = 1e8, this.unsimplifiedHdRoutes = e36.unsimplifiedHdRoutes, this.otherHdRoutes = e36.otherHdRoutes ?? [];\n const t2 = Math.max(2, ...[...e36.unsimplifiedHdRoutes, ...this.otherHdRoutes].flatMap((e37) =\u003e e37.route.map((e38) =\u003e e38.z + 1))) || 2;\n this.obstacles = sF(e36.obstacles, t2), this.connMap = e36.connMap || new cF({}), this.colorMap = e36.colorMap || {}, this.outline = e36.outline, this.minBoardEdgeClearance = e36.minBoardEdgeClearance ?? 0.2, this.defaultViaDiameter = e36.defaultViaDiameter ?? 0.3, this.useTraceWidthAwareClearance = e36.useTraceWidthAwareClearance ?? false, this.enableVertexShortcuts = e36.enableVertexShortcuts ?? false, this.geometryIndex = new bF(this.unsimplifiedHdRoutes, this.otherHdRoutes, this.obstacles), this.simplifiedHdRoutes = [];\n }\n _step() {\n const e36 = this.unsimplifiedHdRoutes[this.currentUnsimplifiedHdRouteIndex];\n if (!this.activeSubSolver)\n return e36 ? (this.activeSubSolver = new uF({ inputRoute: e36, otherHdRoutes: this.otherHdRoutes.concat(this.unsimplifiedHdRoutes.slice(this.currentUnsimplifiedHdRouteIndex + 1).concat(this.simplifiedHdRoutes)), obstacles: this.obstacles, connMap: this.connMap, colorMap: this.colorMap, outline: this.outline, minBoardEdgeClearance: this.minBoardEdgeClearance, useTraceWidthAwareClearance: this.useTraceWidthAwareClearance, geometryQuery: { index: this.geometryIndex, routeIndex: this.currentUnsimplifiedHdRouteIndex } }), void this.currentUnsimplifiedHdRouteIndex++) : void (this.solved = true);\n if (this.activeSubSolver.step(), this.activeSubSolver.failed)\n return this.failed = true, void (this.error = this.activeSubSolver.error);\n if (this.activeSubSolver.solved) {\n if (this.enableVertexShortcuts \u0026\u0026 !(this.activeSubSolver instanceof pF))\n return void (this.activeSubSolver = new pF({ inputRoute: this.activeSubSolver.simplifiedRoute, otherHdRoutes: this.activeSubSolver.otherHdRoutes, obstacles: this.obstacles, connMap: this.connMap, colorMap: this.colorMap, outline: this.outline, minBoardEdgeClearance: this.minBoardEdgeClearance, useTraceWidthAwareClearance: this.useTraceWidthAwareClearance, geometryQuery: { index: this.geometryIndex, routeIndex: this.currentUnsimplifiedHdRouteIndex - 1 } }));\n const e37 = this.activeSubSolver.simplifiedRoute;\n this.geometryIndex.replaceRoute(this.currentUnsimplifiedHdRouteIndex - 1, e37), this.simplifiedHdRoutes.push(e37), this.activeSubSolver = null;\n }\n }\n visualize() {\n if (this.activeSubSolver)\n return this.activeSubSolver.visualize();\n const e36 = { lines: [], points: [], circles: [], rects: [], coordinateSystem: \"cartesian\", title: \"Multi Simplified Path Solver\" };\n for (const t2 of this.unsimplifiedHdRoutes)\n if (!this.simplifiedHdRoutes.some((e37) =\u003e e37.connectionName === t2.connectionName)) {\n for (let n2 = 0;n2 \u003c t2.route.length - 1; n2++)\n e36.lines.push({ points: [{ x: t2.route[n2].x, y: t2.route[n2].y }, { x: t2.route[n2 + 1].x, y: t2.route[n2 + 1].y }], strokeColor: t2.route[n2].z === 1 ? \"rgba(0, 0, 255, 0.4)\" : \"rgba(255, 0, 0, 0.4)\", strokeWidth: 0.15, strokeDash: t2.route[n2].z === 1 ? [0.5, 0.5] : undefined });\n for (const n2 of t2.vias || [])\n e36.circles.push({ center: n2, radius: (t2.viaDiameter ?? this.defaultViaDiameter) / 2, fill: \"rgba(0, 0, 255, 0.4)\" });\n }\n for (const t2 of this.simplifiedHdRoutes) {\n const n2 = this.colorMap?.[t2.connectionName] || \"rgba(128, 128, 128, 0.8)\";\n for (let o3 = 0;o3 \u003c t2.route.length - 1; o3++)\n e36.lines.push({ points: [{ x: t2.route[o3].x, y: t2.route[o3].y }, { x: t2.route[o3 + 1].x, y: t2.route[o3 + 1].y }], strokeWidth: 0.15, strokeColor: n2, strokeDash: t2.route[o3].z === 1 ? [0.5, 0.5] : undefined, step: 1 });\n for (const n3 of t2.vias || [])\n e36.circles.push({ center: n3, radius: t2.viaDiameter / 2, fill: \"rgba(0, 0, 255, 0.5)\", step: 1 });\n }\n for (const t2 of this.unsimplifiedHdRoutes) {\n for (let n2 = 0;n2 \u003c t2.route.length - 1; n2++)\n e36.lines.push({ points: [{ x: t2.route[n2].x, y: t2.route[n2].y }, { x: t2.route[n2 + 1].x, y: t2.route[n2 + 1].y }], strokeWidth: 0.15, strokeColor: \"rgba(255, 0, 0, 0.2)\", strokeDash: [0.5, 0.5], step: 0, layer: `z${t2.route[n2].z.toString()}` });\n for (const n2 of t2.vias)\n e36.circles.push({ center: { x: n2.x, y: n2.y }, radius: t2.viaDiameter / 2, fill: \"rgba(255, 0, 0, 0.2)\", step: 0 });\n }\n for (const t2 of this.obstacles)\n e36.rects.push({ center: t2.center, width: t2.width, height: t2.height, fill: t2.layers?.includes(\"top\") ? \"rgba(255, 0, 0, 0.3)\" : t2.layers?.includes(\"bottom\") ? \"rgba(0, 0, 255, 0.3)\" : \"rgba(128, 128, 128, 0.3)\" });\n if (this.currentUnsimplifiedHdRouteIndex \u003c this.unsimplifiedHdRoutes.length) {\n const t2 = this.unsimplifiedHdRoutes[this.currentUnsimplifiedHdRouteIndex];\n t2.route.length \u003e 0 \u0026\u0026 e36.circles.push({ center: { x: t2.route[0].x, y: t2.route[0].y }, radius: 0.2, fill: \"yellow\", label: \"Current\" });\n }\n return e36;\n }\n};\nvar vF = (e36, t2) =\u003e {\n for (let n2 = 0;n2 \u003c e36.route.length - 1; n2++) {\n const o3 = e36.route[n2], i3 = e36.route[n2 + 1];\n if (o3.z === i3.z || o3.x !== t2.x || o3.y !== t2.y || i3.x !== t2.x || i3.y !== t2.y)\n continue;\n let r3 = n2;\n for (;r3 \u003e 0 \u0026\u0026 e36.route[r3 - 1].x === t2.x \u0026\u0026 e36.route[r3 - 1].y === t2.y; )\n r3--;\n let s2 = n2 + 1;\n for (;s2 \u003c e36.route.length - 1 \u0026\u0026 e36.route[s2 + 1].x === t2.x \u0026\u0026 e36.route[s2 + 1].y === t2.y; )\n s2++;\n if (r3 === 0 || s2 === e36.route.length - 1)\n return true;\n }\n return false;\n};\nvar IF = (e36, t2, n2) =\u003e n2?.get(t2.connectionName) ?? e36.idToNetMap[t2.connectionName] ?? (t2.rootConnectionName ? e36.idToNetMap[t2.rootConnectionName] : undefined);\nvar SF = (e36, t2, n2) =\u003e {\n for (const o3 of t2.connectedTo) {\n if (o3 === n2.net)\n return true;\n if (e36.idToNetMap[o3] === n2.net)\n return true;\n if (e36.areIdsConnected(o3, n2.net))\n return true;\n }\n return false;\n};\nvar CF = (e36, t2, n2) =\u003e {\n const o3 = n2.mergedViaHdRoutes[e36.routeIndex];\n if (!o3)\n throw new Error(`SameNetViaMergerSolver could not find route for via at index ${e36.routeIndex}`);\n const i3 = new Set;\n for (let t3 = 1;t3 \u003c o3.route.length; t3++) {\n const n3 = o3.route[t3 - 1], r3 = o3.route[t3];\n n3.z !== r3.z \u0026\u0026 (n3.x === e36.x \u0026\u0026 n3.y === e36.y \u0026\u0026 r3.x === e36.x \u0026\u0026 r3.y === e36.y \u0026\u0026 (i3.add(n3.z), i3.add(r3.z)));\n }\n if (i3.size === 0)\n throw new Error(`SameNetViaMergerSolver could not find transition layers for via at (${e36.x}, ${e36.y})`);\n for (const r3 of i3) {\n const i4 = o3.traceThickness, s2 = { x: e36.x, y: e36.y, z: r3 }, a3 = { x: t2.x, y: t2.y, z: r3 };\n if (s2.x === a3.x \u0026\u0026 s2.y === a3.y)\n continue;\n const c3 = n2.hdRouteSHI.getConflictingRoutesForSegment(s2, a3, i4 / 2);\n for (const { conflictingRoute: t3, distance: r4 } of c3) {\n if (t3.connectionName === o3.connectionName)\n continue;\n if (IF(n2.connMap, t3, n2.netByConnectionName) === e36.net)\n continue;\n if (r4 \u003c i4 / 2 + t3.traceThickness / 2)\n return false;\n }\n const l3 = { centerX: (s2.x + a3.x) / 2, centerY: (s2.y + a3.y) / 2, width: Math.abs(s2.x - a3.x), height: Math.abs(s2.y - a3.y) }, h2 = i4 / 2 + 0.1, d2 = n2.obstacleSHI.searchArea(l3.centerX, l3.centerY, l3.width + 2 * h2, l3.height + 2 * h2);\n for (const t3 of d2) {\n if (!t3.__zLayers)\n throw new Error(`SameNetViaMergerSolver found obstacle without zLayers near via at (${e36.x}, ${e36.y})`);\n if (t3.__zLayers.includes(r3) \u0026\u0026 (!SF(n2.connMap, t3, e36) \u0026\u0026 Re(s2, a3, t3) \u003c h2))\n return false;\n }\n }\n return true;\n};\nvar PF = class extends SB {\n constructor(e36) {\n if (super(), this.input = e36, !e36.connMap)\n throw new Error(\"SameNetViaMergerSolver requires connMap\");\n this.input = { ...e36, obstacles: sF(e36.obstacles, e36.layerCount) }, this.MAX_ITERATIONS = 1e6, this.inputHdRoutes = this.input.inputHdRoutes, this.mergedViaHdRoutes = structuredClone(this.inputHdRoutes);\n for (const e37 of this.mergedViaHdRoutes)\n this.dedupeRouteVias(e37);\n this.unprocessedRoutes = [...this.input.inputHdRoutes], this.colorMap = this.input.colorMap, this.outline = this.input.outline, this.obstacles = this.input.obstacles, this.obstacleSHI = new EB(\"flatbush\", this.input.obstacles), this.hdRouteSHI = this.createHdRouteSpatialIndex(), this.vias = [], this.offendingVias = [], this.connMap = e36.connMap, this.netByConnectionName = e36.netByConnectionName, this.viasByNet = new Map, this.rebuildVias();\n }\n getSolverName() {\n return \"SameNetViaMergerSolver\";\n }\n inputHdRoutes;\n mergedViaHdRoutes;\n unprocessedRoutes;\n vias;\n offendingVias;\n currentViaRoutes = [];\n connMap;\n colorMap;\n outline;\n obstacles;\n viasByNet;\n netByConnectionName;\n obstacleSHI;\n hdRouteSHI;\n createHdRouteSpatialIndex() {\n return new zB([...this.mergedViaHdRoutes, ...this.input.otherHdRoutes ?? []]);\n }\n rebuildVias() {\n this.vias = [], this.viasByNet = new Map;\n const e36 = (e37, t2, n2) =\u003e {\n if (e37.vias.length === 0)\n return;\n const o3 = n2 ? ((e38, t3, n3) =\u003e {\n const o4 = IF(e38, t3, n3);\n if (!o4)\n throw new Error(`SameNetViaMergerSolver could not find net for route \"${t3.connectionName}\"`);\n return o4;\n })(this.connMap, e37, this.netByConnectionName) : IF(this.connMap, e37, this.netByConnectionName);\n if (o3)\n for (let i3 = 0;i3 \u003c e37.vias.length; i3++) {\n const r3 = e37.vias[i3], s2 = [...new Set(e37.route.map((e38) =\u003e e38.z))];\n if (s2.length === 0)\n throw new Error(`SameNetViaMergerSolver found via on route \"${e37.connectionName}\" with no route points`);\n const a3 = { x: r3.x, y: r3.y, diameter: e37.viaDiameter, net: o3, layers: s2, routeIndex: t2, mutable: n2 \u0026\u0026 !(this.input.preserveRouteEndpoints \u0026\u0026 vF(e37, r3)) };\n this.vias.push(a3);\n const c3 = this.viasByNet.get(a3.net);\n c3 ? c3.push(a3) : this.viasByNet.set(a3.net, [a3]);\n }\n };\n for (let t2 = 0;t2 \u003c this.mergedViaHdRoutes.length; t2++)\n e36(this.mergedViaHdRoutes[t2], t2, true);\n for (let t2 = 0;t2 \u003c (this.input.otherHdRoutes?.length ?? 0); t2++)\n e36(this.input.otherHdRoutes[t2], this.mergedViaHdRoutes.length + t2, false);\n }\n getViaLocationKey(e36) {\n return [e36.net, e36.x, e36.y].join(\":\");\n }\n dedupeRouteVias(e36) {\n const t2 = new Set;\n e36.vias = e36.vias.filter((e37) =\u003e {\n const n2 = `${e37.x}:${e37.y}`;\n return !t2.has(n2) \u0026\u0026 (t2.add(n2), true);\n });\n }\n getOffendingViaGroupsBatch() {\n const e36 = [], t2 = new Set, n2 = [];\n for (const e37 of this.viasByNet.values()) {\n if (e37.length \u003c 2)\n continue;\n const t3 = Math.max(0.000001, ...e37.map((e38) =\u003e e38.diameter)), o3 = new Map, i3 = new Map;\n for (let n3 = 0;n3 \u003c e37.length; n3++) {\n const r3 = e37[n3], s2 = this.getViaLocationKey(r3), a3 = i3.get(s2);\n a3 ? a3.push(r3) : i3.set(s2, [r3]);\n const c3 = `${Math.floor(r3.x / t3)}:${Math.floor(r3.y / t3)}`, l3 = o3.get(c3);\n l3 ? l3.push(n3) : o3.set(c3, [n3]);\n }\n for (let r3 = 0;r3 \u003c e37.length; r3++) {\n const s2 = e37[r3], a3 = Math.floor(s2.x / t3), c3 = Math.floor(s2.y / t3), l3 = Math.ceil(2.5), h2 = [];\n for (let t4 = -l3;t4 \u003c= l3; t4++)\n for (let n3 = -l3;n3 \u003c= l3; n3++) {\n const i4 = o3.get(`${a3 + t4}:${c3 + n3}`);\n if (i4)\n for (const t5 of i4) {\n if (t5 === r3)\n continue;\n const n4 = e37[t5];\n if (!n4.mutable)\n continue;\n const o4 = s2.x - n4.x, i5 = s2.y - n4.y, a4 = o4 * o4 + i5 * i5, c4 = s2.diameter / 2 + n4.diameter / 2, l4 = 2.5 * c4;\n a4 !== 0 \u0026\u0026 ((a4 \u003c= c4 * c4 || a4 \u003c= l4 * l4 \u0026\u0026 CF(n4, s2, { connMap: this.connMap, mergedViaHdRoutes: this.mergedViaHdRoutes, hdRouteSHI: this.hdRouteSHI, obstacleSHI: this.obstacleSHI, netByConnectionName: this.netByConnectionName })) \u0026\u0026 h2.push(n4));\n }\n }\n const d2 = new Set(h2), u2 = h2.filter((e38) =\u003e e38.x === s2.x \u0026\u0026 e38.y === s2.y || i3.get(this.getViaLocationKey(e38)).every((e39) =\u003e e39.mutable \u0026\u0026 d2.has(e39)));\n u2.length \u003e 0 \u0026\u0026 n2.push({ keep: s2, remove: u2 });\n }\n }\n n2.sort((e37, t3) =\u003e t3.remove.length !== e37.remove.length ? t3.remove.length - e37.remove.length : e37.keep.mutable !== t3.keep.mutable ? e37.keep.mutable ? 1 : -1 : t3.keep.layers.length !== e37.keep.layers.length ? t3.keep.layers.length - e37.keep.layers.length : e37.keep.routeIndex - t3.keep.routeIndex);\n for (const o3 of n2) {\n const n3 = this.getViaLocationKey(o3.keep);\n if (t2.has(n3))\n continue;\n const i3 = o3.remove.filter((e37) =\u003e !t2.has(this.getViaLocationKey(e37)));\n if (i3.length !== 0) {\n e36.push({ keep: o3.keep, remove: i3 }), t2.add(n3);\n for (const e37 of i3)\n t2.add(this.getViaLocationKey(e37));\n }\n }\n return e36;\n }\n moveViaTo(e36, t2, n2 = true) {\n if (!e36.mutable)\n throw new Error(\"SameNetViaMergerSolver cannot mutate an immutable via anchor\");\n const o3 = this.mergedViaHdRoutes[e36.routeIndex];\n if (!o3)\n throw new Error(`SameNetViaMergerSolver could not find route for via at index ${e36.routeIndex}`);\n const i3 = o3.route, r3 = new Set;\n let s2 = false;\n for (let t3 = i3.length - 1;t3 \u003e= 1; t3--) {\n const n3 = i3[t3 - 1], o4 = i3[t3];\n if (n3.z === o4.z)\n continue;\n if (n3.x !== e36.x || n3.y !== e36.y)\n continue;\n if (o4.x !== e36.x || o4.y !== e36.y)\n continue;\n let s3 = t3 - 1;\n for (;s3 \u003e 0 \u0026\u0026 i3[s3 - 1].x === e36.x \u0026\u0026 i3[s3 - 1].y === e36.y; )\n s3--;\n let a3 = t3;\n for (;a3 \u003c i3.length - 1 \u0026\u0026 i3[a3 + 1].x === e36.x \u0026\u0026 i3[a3 + 1].y === e36.y; )\n a3++;\n for (let e37 = s3;e37 \u003c= a3; e37++)\n r3.add(e37);\n }\n if (r3.size === 0)\n throw new Error(`SameNetViaMergerSolver could not find route transition for via at (${e36.x}, ${e36.y}) on route \"${o3.connectionName}\"`);\n for (const e37 of r3) {\n const n3 = i3[e37];\n i3[e37] = { ...n3, x: t2.x, y: t2.y };\n }\n if (o3.vias = o3.vias.map((n3) =\u003e n3.x !== e36.x || n3.y !== e36.y ? n3 : (s2 = true, { x: t2.x, y: t2.y })), !s2)\n throw new Error(`SameNetViaMergerSolver could not find via at (${e36.x}, ${e36.y}) on route \"${o3.connectionName}\"`);\n this.dedupeRouteVias(o3), n2 \u0026\u0026 this.rebuildVias();\n }\n _step() {\n const e36 = this.getOffendingViaGroupsBatch();\n if (e36.length === 0)\n return void (this.solved = true);\n let t2 = 0;\n for (const n2 of e36)\n for (const e37 of n2.remove)\n this.moveViaTo(e37, n2.keep, false), t2++;\n this.rebuildVias(), this.hdRouteSHI = this.createHdRouteSpatialIndex(), this.stats.mergedViaGroups = e36.length, this.stats.mergedViaCount = t2;\n }\n getMergedViaHdRoutes() {\n return this.mergedViaHdRoutes;\n }\n visualize() {\n const e36 = { lines: [], points: [], rects: [], circles: [], coordinateSystem: \"cartesian\", title: \"Same Net Via Merger Solver\" };\n for (const t2 of this.input.obstacles) {\n if (!t2.__zLayers)\n throw new Error(\"SameNetViaMergerSolver found obstacle without zLayers while visualizing\");\n let n2 = \"rgba(128, 128, 128, 0.2)\";\n const o3 = t2.__zLayers.includes(0), i3 = t2.__zLayers.includes(1);\n o3 \u0026\u0026 i3 ? n2 = \"rgba(128, 0, 128, 0.2)\" : o3 ? n2 = \"rgba(255, 0, 0, 0.2)\" : i3 \u0026\u0026 (n2 = \"rgba(0, 0, 255, 0.2)\"), e36.rects.push({ center: t2.center, width: t2.width, height: t2.height, fill: n2, label: `Obstacle (Z: ${t2.__zLayers?.join(\", \")})` });\n }\n for (const t2 of this.mergedViaHdRoutes) {\n if (t2.route.length === 0)\n continue;\n const n2 = this.input.colorMap[t2.connectionName];\n if (!n2)\n throw new Error(`SameNetViaMergerSolver could not find color for route \"${t2.connectionName}\"`);\n for (let n3 = 0;n3 \u003c t2.route.length - 1; n3++) {\n const o3 = t2.route[n3], i3 = t2.route[n3 + 1];\n o3.z === i3.z \u0026\u0026 e36.lines.push({ points: [{ x: o3.x, y: o3.y }, { x: i3.x, y: i3.y }], strokeColor: o3.z === 0 ? \"rgba(255, 0, 0, 0.5)\" : \"rgba(0, 0, 255, 0.5)\", strokeWidth: t2.traceThickness, label: `${t2.connectionName} (z=${o3.z})` });\n }\n for (const n3 of t2.vias)\n e36.circles.push({ center: { x: n3.x, y: n3.y }, radius: t2.viaDiameter / 2, fill: \"rgba(255, 0, 255, 0.5)\", label: `${t2.connectionName} via` });\n if (t2.jumpers \u0026\u0026 t2.jumpers.length \u003e 0) {\n const o3 = oF(t2.jumpers, { color: n2, label: t2.connectionName });\n if (!o3.rects || !o3.lines)\n throw new Error(`SameNetViaMergerSolver expected jumper graphics for route \"${t2.connectionName}\"`);\n e36.rects.push(...o3.rects), e36.lines.push(...o3.lines);\n }\n }\n return e36;\n }\n};\nvar MF = { getConflictingRoutesForSegment: () =\u003e [], getConflictingRoutesNearPoint: () =\u003e [] };\nvar wF = 0.000001;\nvar NF = (e36, t2) =\u003e {\n const n2 = `${e36.x}:${e36.y}:${e36.z}`, o3 = `${t2.x}:${t2.y}:${t2.z}`;\n return n2 \u003c o3 ? `${n2}|${o3}` : `${o3}|${n2}`;\n};\nvar RF = (e36) =\u003e {\n const t2 = new Set;\n for (let n2 = 1;n2 \u003c e36.route.length; n2++) {\n const o3 = e36.route[n2 - 1], i3 = e36.route[n2];\n o3.z === i3.z \u0026\u0026 t2.add(NF(o3, i3));\n }\n return t2;\n};\nvar TF = (e36) =\u003e e36.filter((t2, n2) =\u003e {\n const o3 = e36[n2 - 1];\n return !o3 || t2.x !== o3.x || t2.y !== o3.y || t2.z !== o3.z;\n});\nvar EF = (e36) =\u003e {\n const t2 = [], n2 = new Set;\n for (let o3 = 1;o3 \u003c e36.length; o3++) {\n const i3 = e36[o3 - 1], r3 = e36[o3];\n if (i3.z === r3.z)\n continue;\n if (i3.toNextSegmentType === \"through_obstacle\")\n continue;\n if (i3.x !== r3.x || i3.y !== r3.y)\n throw new Error(`CrossingViaReductionSolver found a layer transition without a via at route point ${o3}`);\n const s2 = `${r3.x}:${r3.y}`;\n n2.has(s2) || (n2.add(s2), t2.push({ x: r3.x, y: r3.y }));\n }\n return t2;\n};\nvar AF = (e36) =\u003e {\n const t2 = [e36.connectionName];\n return e36.rootConnectionName \u0026\u0026 t2.push(e36.rootConnectionName), t2;\n};\nvar OF = (e36, t2, n2) =\u003e {\n const o3 = AF(e36), i3 = AF(t2);\n return o3.some((e37) =\u003e i3.some((t3) =\u003e e37 === t3 || n2.areIdsConnected(e37, t3)));\n};\nvar kF = (e36, t2, n2) =\u003e {\n const o3 = AF(t2);\n return e36.connectedTo.some((e37) =\u003e o3.some((t3) =\u003e e37 === t3 || n2.areIdsConnected(e37, t3)));\n};\nvar DF = (e36) =\u003e {\n let t2 = 0;\n for (let n2 = 1;n2 \u003c e36.length; n2++)\n t2 += Math.hypot(e36[n2].x - e36[n2 - 1].x, e36[n2].y - e36[n2 - 1].y);\n return t2;\n};\nvar LF = (e36, t2) =\u003e {\n const n2 = DF(e36);\n if (t2 \u003c= wF || t2 \u003e= n2 - wF)\n return null;\n let o3 = 0;\n for (let n3 = 1;n3 \u003c e36.length; n3++) {\n const i3 = e36[n3 - 1], r3 = e36[n3], s2 = Math.hypot(r3.x - i3.x, r3.y - i3.y);\n if (o3 + s2 \u003c t2 - wF) {\n o3 += s2;\n continue;\n }\n const a3 = t2 - o3;\n if (a3 \u003c= wF)\n return { prefix: e36.slice(0, n3).map((e37) =\u003e ({ ...e37 })), suffix: e36.slice(n3 - 1).map((e37) =\u003e ({ ...e37 })), point: { ...i3 } };\n if (s2 - a3 \u003c= wF)\n return { prefix: e36.slice(0, n3 + 1).map((e37) =\u003e ({ ...e37 })), suffix: e36.slice(n3).map((e37) =\u003e ({ ...e37 })), point: { ...r3 } };\n const c3 = a3 / s2, l3 = { x: i3.x + (r3.x - i3.x) * c3, y: i3.y + (r3.y - i3.y) * c3, z: i3.z };\n return { prefix: [...e36.slice(0, n3), l3].map((e37) =\u003e ({ ...e37 })), suffix: [l3, ...e36.slice(n3)].map((e37) =\u003e ({ ...e37 })), point: l3 };\n }\n return null;\n};\nvar zF = (e36, t2, n2, o3) =\u003e {\n const i3 = ge(e36, t2, n2, o3);\n if (!i3)\n return null;\n const r3 = Math.hypot(i3.x - e36.x, i3.y - e36.y), s2 = Math.hypot(i3.x - t2.x, i3.y - t2.y), a3 = Math.hypot(i3.x - n2.x, i3.y - n2.y), c3 = Math.hypot(i3.x - o3.x, i3.y - o3.y);\n return Math.min(r3, s2, a3, c3) \u003c= wF ? null : r3;\n};\nvar BF = (e36) =\u003e e36.points.some((e37) =\u003e e37.insideJumperPad || e37.toNextSegmentType);\nvar FF = ({ sections: e36, sectionIndex: t2, side: n2 }) =\u003e {\n const o3 = e36[t2], i3 = n2 === \"start\" ? e36[t2 - 1] : e36[t2 + 1];\n if (!i3)\n return null;\n const r3 = n2 === \"start\" ? o3.points[0] : o3.points.at(-1), s2 = n2 === \"start\" ? i3.points.at(-1) : i3.points[0];\n return r3.x !== s2.x || r3.y !== s2.y ? null : i3.z;\n};\nvar jF = ({ sections: e36, sectionIndex: t2, targetZ: n2, side: o3 }) =\u003e FF({ sections: e36, sectionIndex: t2, side: o3 }) === n2;\nvar $F = ({ baseIndexes: e36, otherCandidateRoutes: t2, ignoredConnectionNames: n2, originalRouteSegmentKeys: o3 }) =\u003e {\n const i3 = new zB([...t2]);\n return { getConflictingRoutesForSegment: (t3, r3, s2) =\u003e {\n const a3 = o3.has(NF(t3, r3));\n return [...a3 ? [] : e36.mutableRoutes.getConflictingRoutesForSegment(t3, r3, s2).filter(({ conflictingRoute: e37 }) =\u003e !n2.has(e37.connectionName)), ...a3 ? [] : e36.immutableRoutes?.getConflictingRoutesForSegment(t3, r3, s2) ?? [], ...i3.getConflictingRoutesForSegment(t3, r3, s2)];\n }, getConflictingRoutesNearPoint: (t3, o4) =\u003e [...e36.mutableRoutes.getConflictingRoutesNearPoint(t3, o4).filter(({ conflictingRoute: e37 }) =\u003e !n2.has(e37.connectionName)), ...e36.immutableRoutes?.getConflictingRoutesNearPoint(t3, o4) ?? [], ...i3.getConflictingRoutesNearPoint(t3, o4)] };\n};\nvar YF = class extends SB {\n input;\n obstacleSHI;\n traceMargin;\n obstacleMargin;\n reducedHdRoutes;\n getSolverName() {\n return \"CrossingViaReductionSolver\";\n }\n constructor(e36) {\n super(), this.input = { ...e36, obstacles: sF(e36.obstacles, e36.layerCount) }, this.traceMargin = e36.traceMargin ?? 0.1, this.obstacleMargin = e36.obstacleMargin ?? 0.15, this.reducedHdRoutes = structuredClone([...e36.inputHdRoutes]), this.obstacleSHI = new EB(\"flatbush\", [...this.input.obstacles]), this.MAX_ITERATIONS = 1e6;\n }\n collapseDetourSection({ route: e36, section: t2, targetZ: n2 }) {\n const o3 = t2.points.map((e37) =\u003e ({ ...e37, z: n2 })), i3 = TF([...e36.route.slice(0, t2.startIndex).map((e37) =\u003e ({ ...e37 })), ...o3, ...e36.route.slice(t2.endIndex + 1).map((e37) =\u003e ({ ...e37 }))]);\n return { ...e36, route: i3, vias: EF(i3) };\n }\n relocateTransitionVia({ route: e36, section: t2, targetZ: n2, side: o3, newViaDistance: i3 }) {\n const r3 = LF(t2.points, i3);\n if (!r3)\n return null;\n const s2 = o3 === \"start\" ? n2 : t2.z, a3 = o3 === \"start\" ? t2.z : n2, c3 = [...r3.prefix.map((e37) =\u003e ({ ...e37, z: s2 })), ...r3.suffix.map((e37) =\u003e ({ ...e37, z: a3 }))], l3 = TF([...e36.route.slice(0, t2.startIndex).map((e37) =\u003e ({ ...e37 })), ...c3, ...e36.route.slice(t2.endIndex + 1).map((e37) =\u003e ({ ...e37 }))]);\n return { route: { ...e36, route: l3, vias: EF(l3) }, relocatedVia: { x: r3.point.x, y: r3.point.y } };\n }\n relocateTransitionVias({ route: e36, sections: t2, crossingGroups: n2, detourZ: o3, detourTraceThickness: i3 }) {\n const r3 = new Map;\n for (const e37 of n2) {\n const t3 = r3.get(e37.transitionSectionIndex) ?? [];\n t3.push(e37), r3.set(e37.transitionSectionIndex, t3);\n }\n const s2 = [], a3 = [], c3 = e36.viaDiameter / 2 + i3 / 2 + this.traceMargin + wF;\n for (const [e37, n3] of r3) {\n if (n3.length !== 1)\n return null;\n const i4 = t2[e37], r4 = n3[0];\n if (!jF({ sections: t2, sectionIndex: e37, targetZ: o3, side: r4.side }))\n return null;\n const l4 = r4.side === \"start\" ? Math.max(...r4.crossingDistances) + c3 : Math.min(...r4.crossingDistances) - c3, h2 = LF(i4.points, l4);\n if (!h2)\n return null;\n const d2 = r4.side === \"start\" ? o3 : i4.z, u2 = r4.side === \"start\" ? i4.z : o3;\n s2.push({ section: i4, points: [...h2.prefix.map((e38) =\u003e ({ ...e38, z: d2 })), ...h2.suffix.map((e38) =\u003e ({ ...e38, z: u2 }))] }), a3.push({ x: h2.point.x, y: h2.point.y });\n }\n let l3 = e36.route.map((e37) =\u003e ({ ...e37 }));\n for (const e37 of s2.sort((e38, t3) =\u003e t3.section.startIndex - e38.section.startIndex))\n l3 = [...l3.slice(0, e37.section.startIndex), ...e37.points, ...l3.slice(e37.section.endIndex + 1)];\n return l3 = TF(l3), { route: { ...e36, route: l3, vias: EF(l3) }, relocatedVias: a3 };\n }\n routeIsClear(e36, t2, n2) {\n for (const o3 of ZB(e36)) {\n for (let t3 = 1;t3 \u003c o3.points.length; t3++) {\n const i3 = o3.points[t3 - 1], r3 = o3.points[t3];\n if (!n2.has(NF(i3, r3)) \u0026\u0026 this.input.outline \u0026\u0026 UB({ start: i3, end: r3, polygon: [...this.input.outline], margin: e36.traceThickness / 2 }))\n return false;\n }\n if (!JB({ currentSection: o3, targetZ: o3.z, route: e36, hdRouteSHI: t2, obstacleSHI: this.obstacleSHI, connMap: this.input.connMap, defaultTraceThickness: e36.traceThickness, obstacleMargin: this.obstacleMargin, traceMargin: this.traceMargin, shouldCheckStaticGeometryForSegment: (e37, t3) =\u003e !n2.has(NF(e37, t3)) }))\n return false;\n }\n return true;\n }\n relocatedViaIsClear(e36, t2, n2) {\n const o3 = e36.viaDiameter / 2;\n for (let i4 = 0;i4 \u003c this.input.layerCount; i4++) {\n if (n2.getConflictingRoutesNearPoint({ ...t2, z: i4 }, o3 + this.traceMargin).some(({ conflictingRoute: t3 }) =\u003e !OF(e36, t3, this.input.connMap)))\n return false;\n }\n const i3 = o3 + this.obstacleMargin, r3 = this.obstacleSHI.searchArea(t2.x, t2.y, 2 * i3, 2 * i3);\n for (const n3 of r3)\n if (!kF(n3, e36, this.input.connMap) \u0026\u0026 Re(t2, t2, n3) \u003c i3)\n return false;\n if (this.input.outline)\n for (let e37 = 0;e37 \u003c this.input.outline.length; e37++) {\n if (pe(t2, this.input.outline[e37], this.input.outline[(e37 + 1) % this.input.outline.length]) \u003c o3 + this.traceMargin)\n return false;\n }\n return true;\n }\n changedSectionsAreStaticallyClear(e36, t2) {\n for (const n2 of ZB(e36)) {\n if (n2.points.some((e37, o3) =\u003e {\n const i3 = n2.points[o3 - 1];\n return i3 !== undefined \u0026\u0026 !t2.has(NF(i3, e37));\n })) {\n if (this.input.outline) {\n for (let t3 = 1;t3 \u003c n2.points.length; t3++)\n if (UB({ start: n2.points[t3 - 1], end: n2.points[t3], polygon: [...this.input.outline], margin: e36.traceThickness / 2 }))\n return false;\n }\n if (!JB({ currentSection: n2, targetZ: n2.z, route: e36, hdRouteSHI: MF, obstacleSHI: this.obstacleSHI, connMap: this.input.connMap, defaultTraceThickness: e36.traceThickness, obstacleMargin: Math.min(this.obstacleMargin, 0.1), traceMargin: this.traceMargin }))\n return false;\n }\n }\n return true;\n }\n candidateIsClear(e36, t2) {\n const n2 = [{ routeIndex: e36.detourRouteIndex, route: e36.detourRoute }, ...e36.transitionUpdates], o3 = new Set(n2.map(({ routeIndex: e37 }) =\u003e this.reducedHdRoutes[e37].connectionName)), i3 = RF(this.reducedHdRoutes[e36.detourRouteIndex]), r3 = $F({ baseIndexes: t2, otherCandidateRoutes: e36.transitionUpdates.map(({ route: e37 }) =\u003e e37), ignoredConnectionNames: o3, originalRouteSegmentKeys: i3 });\n if (this.stats.candidateClearanceChecks = (this.stats.candidateClearanceChecks ?? 0) + 1, !this.routeIsClear(e36.detourRoute, r3, i3))\n return false;\n for (const i4 of e36.transitionUpdates) {\n const e37 = RF(this.reducedHdRoutes[i4.routeIndex]), r4 = $F({ baseIndexes: t2, otherCandidateRoutes: n2.filter(({ routeIndex: e38 }) =\u003e e38 !== i4.routeIndex).map(({ route: e38 }) =\u003e e38), ignoredConnectionNames: o3, originalRouteSegmentKeys: e37 });\n if (!this.routeIsClear(i4.route, r4, e37) || i4.relocatedVias.some((e38) =\u003e !this.relocatedViaIsClear(i4.route, e38, r4)))\n return false;\n }\n return this.changedSectionsAreStaticallyClear(e36.detourRoute, i3);\n }\n candidateRoutesHaveNoExternalCopperConflicts(e36, t2) {\n const n2 = [e36.detourRoute, ...e36.transitionUpdates.map(({ route: e37 }) =\u003e e37)], o3 = new Set(n2.map(({ connectionName: e37 }) =\u003e e37)), i3 = [t2.mutableRoutes, ...t2.immutableRoutes ? [t2.immutableRoutes] : []];\n for (const e37 of n2)\n for (const t3 of ZB(e37))\n for (let n3 = 1;n3 \u003c t3.points.length; n3++) {\n const r3 = t3.points[n3 - 1], s2 = t3.points[n3];\n for (const t4 of i3) {\n if (t4.getConflictingRoutesForSegment(r3, s2, e37.traceThickness / 2 + this.traceMargin).some(({ conflictingRoute: t5 }) =\u003e !o3.has(t5.connectionName) \u0026\u0026 !OF(e37, t5, this.input.connMap)))\n return false;\n }\n }\n return true;\n }\n buildTransitionSegmentIndex(e36, t2) {\n const n2 = [];\n for (let o4 = 0;o4 \u003c this.reducedHdRoutes.length; o4++) {\n if (this.reducedHdRoutes[o4].jumpers?.length)\n continue;\n const i3 = e36[o4];\n for (let e37 = 0;e37 \u003c i3.length; e37++) {\n const r3 = i3[e37];\n if (!BF(r3))\n for (const s2 of [\"start\", \"end\"]) {\n const a3 = FF({ sections: i3, sectionIndex: e37, side: s2 });\n if (a3 === null || a3 === r3.z)\n continue;\n if (!t2.has(`${r3.z}:${a3}`))\n continue;\n let c3 = 0;\n for (let t3 = 1;t3 \u003c r3.points.length; t3++) {\n const i4 = r3.points[t3 - 1], l3 = r3.points[t3], h2 = Math.hypot(l3.x - i4.x, l3.y - i4.y);\n h2 \u003e wF \u0026\u0026 n2.push({ routeIndex: o4, sectionIndex: e37, side: s2, adjacentZ: a3, start: i4, end: l3, distanceFromSectionStart: c3 }), c3 += h2;\n }\n }\n }\n }\n if (this.stats.transitionSegmentsIndexed = (this.stats.transitionSegmentsIndexed ?? 0) + n2.length, n2.length === 0)\n return null;\n const o3 = new TB(n2.length);\n for (const e37 of n2)\n o3.insert(e37, Math.min(e37.start.x, e37.end.x), Math.min(e37.start.y, e37.end.y), Math.max(e37.start.x, e37.end.x), Math.max(e37.start.y, e37.end.y));\n return o3.finish(), o3;\n }\n getIndexedCrossingGroups({ detourRouteIndex: e36, detourSection: t2, targetZ: n2, transitionSegmentIndex: o3 }) {\n const i3 = new Map;\n for (let r3 = 1;r3 \u003c t2.points.length; r3++) {\n const s2 = t2.points[r3 - 1], a3 = t2.points[r3];\n if (Math.hypot(a3.x - s2.x, a3.y - s2.y) \u003c= wF)\n continue;\n this.stats.indexedDetourSegmentQueries = (this.stats.indexedDetourSegmentQueries ?? 0) + 1;\n const c3 = o3.search(Math.min(s2.x, a3.x) - wF, Math.min(s2.y, a3.y) - wF, Math.max(s2.x, a3.x) + wF, Math.max(s2.y, a3.y) + wF);\n for (const o4 of c3) {\n if (o4.routeIndex === e36 || o4.start.z !== n2 || o4.adjacentZ !== t2.z)\n continue;\n this.stats.exactSegmentIntersectionChecks = (this.stats.exactSegmentIntersectionChecks ?? 0) + 1;\n const r4 = zF(o4.start, o4.end, s2, a3);\n if (r4 === null)\n continue;\n const c4 = `${o4.routeIndex}:${o4.sectionIndex}:${o4.side}`;\n let l3 = i3.get(c4);\n l3 || (l3 = { transitionRouteIndex: o4.routeIndex, transitionSectionIndex: o4.sectionIndex, side: o4.side, crossingDistances: [] }, i3.set(c4, l3)), l3.crossingDistances.push(o4.distanceFromSectionStart + r4);\n }\n }\n return [...i3.values()].sort((e37, t3) =\u003e e37.transitionRouteIndex !== t3.transitionRouteIndex ? e37.transitionRouteIndex - t3.transitionRouteIndex : e37.transitionSectionIndex !== t3.transitionSectionIndex ? e37.transitionSectionIndex - t3.transitionSectionIndex : e37.side === t3.side ? 0 : e37.side === \"start\" ? -1 : 1);\n }\n tryCreateCandidate({ detourRouteIndex: e36, detourSection: t2, targetZ: n2, transitionRouteIndex: o3, transitionSection: i3, transitionSections: r3, transitionSectionIndex: s2, side: a3, crossingDistances: c3, baseClearanceIndexes: l3 }) {\n if (!jF({ sections: r3, sectionIndex: s2, targetZ: t2.z, side: a3 }))\n return null;\n const h2 = this.reducedHdRoutes[e36], d2 = this.reducedHdRoutes[o3];\n if (c3.length === 0)\n return null;\n const u2 = d2.viaDiameter / 2 + h2.traceThickness / 2 + this.traceMargin + wF, p3 = a3 === \"start\" ? Math.max(...c3) + u2 : Math.min(...c3) - u2, m2 = this.relocateTransitionVia({ route: d2, section: i3, targetZ: t2.z, side: a3, newViaDistance: p3 });\n if (!m2)\n return null;\n const g2 = this.collapseDetourSection({ route: h2, section: t2, targetZ: n2 });\n if (h2.vias.length + d2.vias.length - g2.vias.length - m2.route.vias.length !== 2)\n return null;\n const f2 = { detourRouteIndex: e36, detourRoute: g2, transitionUpdates: [{ routeIndex: o3, route: m2.route, relocatedVias: [m2.relocatedVia] }] };\n return this.candidateIsClear(f2, l3) ? f2 : null;\n }\n tryCreateMultiCrossingCandidate({ detourRouteIndex: e36, detourSection: t2, targetZ: n2, crossingGroups: o3, sectionsByRoute: i3, baseClearanceIndexes: r3 }) {\n if (o3.length \u003c 2)\n return null;\n const s2 = this.reducedHdRoutes[e36], a3 = [], c3 = new Map;\n for (const e37 of o3) {\n const t3 = c3.get(e37.transitionRouteIndex) ?? [];\n t3.push(e37), c3.set(e37.transitionRouteIndex, t3);\n }\n for (const [e37, n3] of c3) {\n const o4 = this.reducedHdRoutes[e37], r4 = this.relocateTransitionVias({ route: o4, sections: i3[e37], crossingGroups: n3, detourZ: t2.z, detourTraceThickness: s2.traceThickness });\n if (!r4)\n return null;\n a3.push({ routeIndex: e37, route: r4.route, relocatedVias: r4.relocatedVias });\n }\n const l3 = this.collapseDetourSection({ route: s2, section: t2, targetZ: n2 });\n if (s2.vias.length + [...c3.keys()].reduce((e37, t3) =\u003e e37 + this.reducedHdRoutes[t3].vias.length, 0) - (l3.vias.length + a3.reduce((e37, { route: t3 }) =\u003e e37 + t3.vias.length, 0)) !== 2)\n return null;\n this.stats.multiCrossingCandidates = (this.stats.multiCrossingCandidates ?? 0) + 1;\n const h2 = { detourRouteIndex: e36, detourRoute: l3, transitionUpdates: a3 };\n return this.candidateIsClear(h2, r3) ? this.candidateRoutesHaveNoExternalCopperConflicts(h2, r3) ? (this.stats.multiCrossingReductions = (this.stats.multiCrossingReductions ?? 0) + 1, this.stats.transitionRoutesMovedByMultiCrossingReductions = (this.stats.transitionRoutesMovedByMultiCrossingReductions ?? 0) + a3.length, h2) : (this.stats.multiCrossingPreexistingConflictRejections = (this.stats.multiCrossingPreexistingConflictRejections ?? 0) + 1, null) : null;\n }\n findCrossingReduction() {\n const e36 = this.reducedHdRoutes.map((e37) =\u003e ZB(e37)), t2 = [], n2 = new Set;\n for (let o4 = 0;o4 \u003c this.reducedHdRoutes.length; o4++) {\n if (this.reducedHdRoutes[o4].jumpers?.length)\n continue;\n const i4 = e36[o4];\n for (let e37 = 1;e37 \u003c i4.length - 1; e37++) {\n const r3 = i4[e37 - 1], s2 = i4[e37], a3 = i4[e37 + 1];\n r3.z !== a3.z || r3.z === s2.z || BF(s2) || (t2.push({ routeIndex: o4, section: s2, targetZ: r3.z }), n2.add(`${r3.z}:${s2.z}`));\n }\n }\n if (t2.length === 0)\n return null;\n const o3 = this.buildTransitionSegmentIndex(e36, n2);\n if (!o3)\n return null;\n let i3 = null;\n for (const n3 of t2) {\n const { routeIndex: t3, section: r3 } = n3, s2 = this.reducedHdRoutes[t3], a3 = this.getIndexedCrossingGroups({ detourRouteIndex: t3, detourSection: r3, targetZ: n3.targetZ, transitionSegmentIndex: o3 }).filter(({ transitionRouteIndex: e37 }) =\u003e {\n const t4 = this.reducedHdRoutes[e37];\n return !t4.jumpers?.length \u0026\u0026 !OF(s2, t4, this.input.connMap);\n }), c3 = new Map;\n for (const e37 of a3) {\n const t4 = `${e37.transitionRouteIndex}:${e37.transitionSectionIndex}`, n4 = c3.get(t4) ?? [];\n n4.push(e37), c3.set(t4, n4);\n }\n if (c3.size \u003e 1) {\n i3 ??= { mutableRoutes: new zB(this.reducedHdRoutes), immutableRoutes: this.input.otherHdRoutes?.length ? new zB([...this.input.otherHdRoutes]) : null };\n let o4 = [{ groups: [], movement: 0 }];\n const a4 = (t4) =\u003e {\n const n4 = this.reducedHdRoutes[t4.transitionRouteIndex], o5 = e36[t4.transitionRouteIndex][t4.transitionSectionIndex], i4 = n4.viaDiameter / 2 + s2.traceThickness / 2 + this.traceMargin + wF, r4 = t4.side === \"start\" ? Math.max(...t4.crossingDistances) + i4 : Math.min(...t4.crossingDistances) - i4;\n return t4.side === \"start\" ? r4 : DF(o5.points) - r4;\n };\n for (const e37 of c3.values()) {\n const t4 = e37.map((e38) =\u003e ({ group: e38, movement: a4(e38) })).sort((e38, t5) =\u003e e38.movement - t5.movement);\n o4 = o4.flatMap((e38) =\u003e t4.map((t5) =\u003e ({ groups: [...e38.groups, t5.group], movement: e38.movement + t5.movement }))).sort((e38, t5) =\u003e e38.movement - t5.movement).slice(0, 4);\n }\n for (const s3 of o4) {\n const o5 = this.tryCreateMultiCrossingCandidate({ detourRouteIndex: t3, detourSection: r3, targetZ: n3.targetZ, crossingGroups: s3.groups, sectionsByRoute: e36, baseClearanceIndexes: i3 });\n if (o5)\n return o5;\n }\n continue;\n }\n const l3 = c3.values().next().value ?? [];\n for (const o4 of l3) {\n const s3 = o4.transitionRouteIndex, a4 = e36[s3], c4 = a4[o4.transitionSectionIndex];\n i3 ??= { mutableRoutes: new zB(this.reducedHdRoutes), immutableRoutes: this.input.otherHdRoutes?.length ? new zB([...this.input.otherHdRoutes]) : null };\n const l4 = this.tryCreateCandidate({ detourRouteIndex: t3, detourSection: r3, targetZ: n3.targetZ, transitionRouteIndex: s3, transitionSection: c4, transitionSections: a4, transitionSectionIndex: o4.transitionSectionIndex, side: o4.side, crossingDistances: o4.crossingDistances, baseClearanceIndexes: i3 });\n if (l4)\n return l4;\n }\n }\n return null;\n }\n _step() {\n const e36 = this.findCrossingReduction();\n if (e36) {\n this.reducedHdRoutes[e36.detourRouteIndex] = e36.detourRoute;\n for (const t2 of e36.transitionUpdates)\n this.reducedHdRoutes[t2.routeIndex] = t2.route;\n this.stats.crossingViaReductions = (this.stats.crossingViaReductions ?? 0) + 1, this.stats.viasRemovedByCrossingReductions = (this.stats.viasRemovedByCrossingReductions ?? 0) + 2;\n } else\n this.solved = true;\n }\n getReducedHdRoutes() {\n return this.reducedHdRoutes;\n }\n visualize() {\n const e36 = { lines: [], circles: [], rects: [], coordinateSystem: \"cartesian\", title: \"Crossing Via Reduction Solver\" };\n for (const t2 of this.input.obstacles)\n e36.rects.push({ center: t2.center, width: t2.width, height: t2.height, fill: \"rgba(128, 128, 128, 0.2)\" });\n for (const t2 of this.reducedHdRoutes) {\n for (let n2 = 1;n2 \u003c t2.route.length; n2++) {\n const o3 = t2.route[n2 - 1], i3 = t2.route[n2];\n o3.z === i3.z \u0026\u0026 e36.lines.push({ points: [o3, i3], strokeColor: o3.z === 0 ? \"#d32f2f\" : \"#3367a8\", strokeWidth: t2.traceThickness, label: `${t2.connectionName} (z=${o3.z})` });\n }\n for (const n2 of t2.vias)\n e36.circles.push({ center: n2, radius: t2.viaDiameter / 2, fill: \"#ff20d6\", label: `${t2.connectionName} via` });\n }\n return e36;\n }\n};\nvar XF = 0.000001;\nvar HF = (e36, t2) =\u003e Math.abs(e36.x - t2.center.x) \u003c= t2.width / 2 + XF \u0026\u0026 Math.abs(e36.y - t2.center.y) \u003c= t2.height / 2 + XF;\nvar VF = (e36) =\u003e (e36.__zLayers?.length ?? e36.layers?.length ?? 0) \u003e 1;\nvar WF = class extends SB {\n constructor(e36) {\n if (super(), this.simplificationConfig = e36, this.simplificationConfig = { ...e36, obstacles: sF(e36.obstacles, e36.layerCount) }, this.hdRoutes = this.markThroughObstacleSegments(e36.hdRoutes), e36.preserveRouteEndpoints) {\n const t2 = new Map;\n for (const n2 of e36.hdRoutes) {\n const e37 = n2.route[0], o3 = n2.route.at(-1);\n if (!e37 || !o3)\n throw new Error(`TraceSimplificationSolver cannot preserve endpoints for empty route \"${n2.connectionName}\"`);\n if (t2.has(n2.connectionName))\n throw new Error(`TraceSimplificationSolver cannot preserve endpoints for duplicate route \"${n2.connectionName}\"`);\n t2.set(n2.connectionName, { start: { ...e37 }, end: { ...o3 } });\n }\n this.preservedRouteEndpoints = t2;\n }\n this.MAX_ITERATIONS = 1e8;\n }\n getSolverName() {\n return \"TraceSimplificationSolver\";\n }\n hdRoutes = [];\n preservedRouteEndpoints;\n simplificationPipelineLoops = 0;\n MAX_SIMPLIFICATION_PIPELINE_LOOPS = 2;\n PHASE_ORDER = [\"via_removal\", \"crossing_via_reduction\", \"via_merging\", \"path_simplification\"];\n currentPhase = \"via_removal\";\n extractResult = null;\n get simplifiedHdRoutes() {\n return this.hdRoutes;\n }\n validatePreservedRouteEndpoints(e36) {\n if (!this.preservedRouteEndpoints)\n return;\n if (e36.length !== this.preservedRouteEndpoints.size)\n throw new Error(`TraceSimplificationSolver changed the preserved route set (expected ${this.preservedRouteEndpoints.size}, got ${e36.length})`);\n const t2 = new Set, n2 = (e37, t3) =\u003e Math.abs(e37.x - t3.x) \u003c= XF \u0026\u0026 Math.abs(e37.y - t3.y) \u003c= XF \u0026\u0026 e37.z === t3.z;\n for (const o3 of e36) {\n if (t2.has(o3.connectionName))\n throw new Error(`TraceSimplificationSolver produced duplicate preserved route \"${o3.connectionName}\"`);\n t2.add(o3.connectionName);\n const e37 = this.preservedRouteEndpoints.get(o3.connectionName), i3 = o3.route[0], r3 = o3.route.at(-1);\n if (!(e37 \u0026\u0026 i3 \u0026\u0026 r3 \u0026\u0026 n2(i3, e37.start) \u0026\u0026 n2(r3, e37.end)))\n throw new Error(`TraceSimplificationSolver changed a preserved endpoint for route \"${o3.connectionName}\"`);\n }\n }\n isSameNetObstacle(e36, t2) {\n return t2.connectedTo.some((t3) =\u003e t3 === e36.connectionName || t3 === e36.rootConnectionName || this.simplificationConfig.connMap.areIdsConnected(e36.connectionName, t3) || e36.rootConnectionName !== undefined \u0026\u0026 this.simplificationConfig.connMap.areIdsConnected(e36.rootConnectionName, t3));\n }\n getSameNetObstacleForSegment(e36, t2, n2) {\n return this.simplificationConfig.obstacles.find((o3) =\u003e VF(o3) \u0026\u0026 HF(t2, o3) \u0026\u0026 HF(n2, o3) \u0026\u0026 this.isSameNetObstacle(e36, o3));\n }\n isViaInsideSameNetObstacle(e36, t2) {\n return this.simplificationConfig.obstacles.some((n2) =\u003e VF(n2) \u0026\u0026 HF(t2, n2) \u0026\u0026 this.isSameNetObstacle(e36, n2));\n }\n markThroughObstacleSegments(e36) {\n return e36.map((e37) =\u003e ({ ...e37, route: e37.route.map((t2, n2, o3) =\u003e {\n const i3 = o3[n2 + 1], r3 = i3 \u0026\u0026 t2.z !== i3.z \u0026\u0026 this.getSameNetObstacleForSegment(e37, t2, i3);\n if (r3)\n return { ...t2, toNextSegmentType: \"through_obstacle\", ...r3.circuitJsonMetadata ? { toNextSegmentCircuitJsonMetadata: r3.circuitJsonMetadata } : {} };\n const s2 = { ...t2 };\n return delete s2.toNextSegmentType, delete s2.toNextSegmentCircuitJsonMetadata, s2;\n }), vias: e37.vias.filter((t2) =\u003e !this.isViaInsideSameNetObstacle(e37, t2)) }));\n }\n _step() {\n if (this.simplificationPipelineLoops \u003e= this.MAX_SIMPLIFICATION_PIPELINE_LOOPS)\n this.solved = true;\n else {\n if (this.activeSubSolver) {\n if (this.activeSubSolver.step(), !this.activeSubSolver.failed \u0026\u0026 !this.activeSubSolver.solved)\n return;\n if (this.activeSubSolver.solved) {\n if (this.extractResult) {\n const e36 = this.extractResult(this.activeSubSolver);\n this.validatePreservedRouteEndpoints(e36), this.hdRoutes = this.markThroughObstacleSegments(e36);\n }\n if (this.activeSubSolver = null, this.extractResult = null, this.currentPhase === \"via_removal\" ? this.currentPhase = this.simplificationConfig.enableCrossingViaReduction ? \"crossing_via_reduction\" : \"via_merging\" : this.currentPhase === \"crossing_via_reduction\" ? this.currentPhase = \"via_merging\" : this.currentPhase === \"via_merging\" ? this.currentPhase = \"path_simplification\" : (this.currentPhase = \"via_removal\", this.simplificationPipelineLoops++), this.simplificationPipelineLoops \u003e= this.MAX_SIMPLIFICATION_PIPELINE_LOOPS)\n return void (this.solved = true);\n } else if (this.activeSubSolver.failed)\n return this.failed = true, void (this.error = this.activeSubSolver.error ?? \"Sub-solver failed without error message\");\n }\n if (!this.activeSubSolver \u0026\u0026 !this.solved)\n switch (this.currentPhase) {\n case \"via_removal\":\n this.activeSubSolver = new aF({ enableRoutedTraceDetours: this.simplificationConfig.enableRoutedTraceDetours, unsimplifiedHdRoutes: this.hdRoutes, otherHdRoutes: [...this.simplificationConfig.otherHdRoutes ?? []], obstacles: [...this.simplificationConfig.obstacles], colorMap: { ...this.simplificationConfig.colorMap }, layerCount: this.simplificationConfig.layerCount, connMap: this.simplificationConfig.connMap, outline: this.simplificationConfig.outline ? [...this.simplificationConfig.outline] : undefined, geometryShortcutTraceMargin: 0.1, geometryShortcutObstacleMargin: this.simplificationConfig.minTraceToPadEdgeClearance ?? 0.15, enableGeometryShortcuts: this.simplificationPipelineLoops \u003e 0, enableObstacleDetourShortcuts: this.simplificationConfig.enableCrossingViaReduction === true \u0026\u0026 this.simplificationPipelineLoops \u003e 0, preserveRouteEndpoints: this.simplificationConfig.preserveRouteEndpoints, terminalLayerIndicesByPcbPortId: this.simplificationConfig.terminalLayerIndicesByPcbPortId }), this.extractResult = (e36) =\u003e e36.getOptimizedHdRoutes() ?? [];\n break;\n case \"crossing_via_reduction\":\n this.activeSubSolver = new YF({ inputHdRoutes: this.hdRoutes, otherHdRoutes: [...this.simplificationConfig.otherHdRoutes ?? []], obstacles: [...this.simplificationConfig.obstacles], connMap: this.simplificationConfig.connMap, layerCount: this.simplificationConfig.layerCount, outline: this.simplificationConfig.outline ? [...this.simplificationConfig.outline] : undefined, traceMargin: 0.1, obstacleMargin: this.simplificationConfig.minTraceToPadEdgeClearance ?? 0.15 }), this.extractResult = (e36) =\u003e e36.getReducedHdRoutes();\n break;\n case \"via_merging\":\n this.activeSubSolver = new PF({ inputHdRoutes: this.hdRoutes, otherHdRoutes: [...this.simplificationConfig.otherHdRoutes ?? []], netByConnectionName: this.simplificationConfig.netByConnectionName, obstacles: [...this.simplificationConfig.obstacles], colorMap: { ...this.simplificationConfig.colorMap }, layerCount: this.simplificationConfig.layerCount, connMap: this.simplificationConfig.connMap, outline: this.simplificationConfig.outline ? [...this.simplificationConfig.outline] : undefined, preserveRouteEndpoints: this.simplificationConfig.preserveRouteEndpoints }), this.extractResult = (e36) =\u003e e36.getMergedViaHdRoutes() ?? [];\n break;\n case \"path_simplification\":\n this.activeSubSolver = new xF({ unsimplifiedHdRoutes: this.hdRoutes, otherHdRoutes: [...this.simplificationConfig.otherHdRoutes ?? []], obstacles: [...this.simplificationConfig.obstacles], connMap: this.simplificationConfig.connMap, colorMap: { ...this.simplificationConfig.colorMap }, outline: this.simplificationConfig.outline ? [...this.simplificationConfig.outline] : undefined, minBoardEdgeClearance: this.simplificationConfig.minBoardEdgeClearance, defaultViaDiameter: this.simplificationConfig.defaultViaDiameter, useTraceWidthAwareClearance: this.simplificationConfig.useTraceWidthAwareClearance, enableVertexShortcuts: this.simplificationConfig.enableVertexShortcuts }), this.extractResult = (e36) =\u003e e36.simplifiedHdRoutes;\n break;\n default:\n this.failed = true, this.error = `Unknown phase: ${this.currentPhase}`;\n }\n }\n }\n visualize() {\n if (this.activeSubSolver)\n return this.activeSubSolver.visualize();\n const e36 = { lines: [], points: [], rects: [], circles: [], coordinateSystem: \"cartesian\", title: \"Trace Simplification Solver\" };\n for (const t2 of this.simplificationConfig.obstacles) {\n let n2 = \"rgba(128, 128, 128, 0.2)\";\n const o3 = t2.__zLayers?.includes(0), i3 = t2.__zLayers?.includes(1);\n o3 \u0026\u0026 i3 ? n2 = \"rgba(128, 0, 128, 0.2)\" : o3 ? n2 = \"rgba(255, 0, 0, 0.2)\" : i3 \u0026\u0026 (n2 = \"rgba(0, 0, 255, 0.2)\"), e36.rects.push({ center: t2.center, width: t2.width, height: t2.height, fill: n2, label: `Obstacle (Z: ${t2.__zLayers?.join(\", \")})` });\n }\n for (const t2 of this.simplificationConfig.otherHdRoutes ?? []) {\n for (let n2 = 0;n2 \u003c t2.route.length - 1; n2++) {\n const o3 = t2.route[n2], i3 = t2.route[n2 + 1];\n o3.z === i3.z \u0026\u0026 e36.lines.push({ points: [{ x: o3.x, y: o3.y }, { x: i3.x, y: i3.y }], strokeColor: o3.z === 0 ? \"rgba(160, 32, 32, 0.55)\" : \"rgba(32, 32, 160, 0.55)\", strokeWidth: t2.traceThickness, strokeDash: [0.08, 0.08], label: `${t2.connectionName} immutable (z=${o3.z})` });\n }\n for (const n2 of t2.vias)\n e36.circles.push({ center: { x: n2.x, y: n2.y }, radius: t2.viaDiameter / 2, fill: \"rgba(96, 96, 96, 0.45)\", label: `${t2.connectionName} immutable via` });\n }\n for (const t2 of this.hdRoutes)\n if (t2.route.length !== 0) {\n for (let n2 = 0;n2 \u003c t2.route.length - 1; n2++) {\n const o3 = t2.route[n2], i3 = t2.route[n2 + 1];\n o3.z === i3.z \u0026\u0026 e36.lines.push({ points: [{ x: o3.x, y: o3.y }, { x: i3.x, y: i3.y }], strokeColor: o3.z === 0 ? \"red\" : \"blue\", strokeWidth: t2.traceThickness, label: `${t2.connectionName} (z=${o3.z})` });\n }\n for (const n2 of t2.vias)\n e36.circles.push({ center: { x: n2.x, y: n2.y }, radius: t2.viaDiameter / 2, fill: \"rgba(255, 0, 255, 0.5)\", label: `${t2.connectionName} via` });\n if (t2.jumpers \u0026\u0026 t2.jumpers.length \u003e 0) {\n const n2 = oF(t2.jumpers, { color: \"orange\", label: t2.connectionName });\n e36.rects.push(...n2.rects ?? []), e36.lines.push(...n2.lines ?? []);\n }\n }\n return e36;\n }\n};\nvar GF = class {\n tree;\n constructor(e36 = 9) {\n this.tree = new G(e36);\n }\n insert(e36, t2, n2, o3, i3) {\n this.tree.insert({ minX: t2, minY: n2, maxX: o3, maxY: i3, data: e36 });\n }\n bulkLoad(e36) {\n const t2 = e36.map(({ item: e37, minX: t3, minY: n2, maxX: o3, maxY: i3 }) =\u003e ({ minX: t3, minY: n2, maxX: o3, maxY: i3, data: e37 }));\n this.tree.load(t2);\n }\n search(e36, t2, n2, o3) {\n return this.tree.search({ minX: e36, minY: t2, maxX: n2, maxY: o3 }).map((e37) =\u003e e37.data);\n }\n clear() {\n this.tree.clear();\n }\n};\nvar UF = class {\n index;\n items = [];\n currentIndex = 0;\n capacity;\n constructor(e36) {\n this.capacity = Math.max(1, e36), this.index = new E2(this.capacity);\n }\n insert(e36, t2, n2, o3, i3) {\n if (this.currentIndex \u003e= this.index.numItems)\n throw new Error(\"Exceeded initial capacity\");\n this.items[this.currentIndex] = e36, this.index.add(t2, n2, o3, i3), this.currentIndex++;\n }\n finish() {\n this.index.finish();\n }\n search(e36, t2, n2, o3) {\n return this.index.search(e36, t2, n2, o3).map((e37) =\u003e this.items[e37] || null).filter(Boolean);\n }\n clear() {\n this.items = [], this.currentIndex = 0, this.index = new E2(this.capacity);\n }\n};\nvar ZF = class {\n idx;\n storage = [];\n constructor(e36 = \"native\", t2 = []) {\n e36 === \"flatbush\" ? t2.length === 0 ? (this.idx = new GF, e36 = \"rbush\") : this.idx = new UF(t2.length) : this.idx = e36 === \"rbush\" ? new GF : new class {\n shi = new qF(t2);\n insert(e37) {}\n search(e37, t3, n2, o3) {\n const i3 = (e37 + n2) / 2, r3 = (t3 + o3) / 2, s2 = n2 - e37, a3 = o3 - t3;\n return this.shi.getNodesInArea(i3, r3, s2, a3);\n }\n clear() {}\n }, t2.forEach((e37) =\u003e this.insert(e37)), e36 === \"flatbush\" \u0026\u0026 t2.length \u003e 0 \u0026\u0026 this.idx.finish?.();\n }\n insert(e36) {\n this.storage.push(e36), this.idx.insert(e36, e36.center.x - e36.width / 2, e36.center.y - e36.height / 2, e36.center.x + e36.width / 2, e36.center.y + e36.height / 2);\n }\n search(e36) {\n return this.idx.search(e36.minX, e36.minY, e36.maxX, e36.maxY);\n }\n searchArea(e36, t2, n2, o3) {\n return this.search({ minX: e36 - n2 / 2, minY: t2 - o3 / 2, maxX: e36 + n2 / 2, maxY: t2 + o3 / 2 });\n }\n};\nvar qF = class {\n constructor(e36) {\n this.obstacles = e36, this.buckets = new Map;\n for (let t2 = 0;t2 \u003c e36.length; t2++) {\n const n2 = e36[t2], o3 = n2.center.x - n2.width / 2, i3 = n2.center.y - n2.height / 2, r3 = n2.center.x + n2.width / 2, s2 = n2.center.y + n2.height / 2;\n for (let e37 = o3;e37 \u003c= r3; e37 += this.CELL_SIZE)\n for (let o4 = i3;o4 \u003c= s2; o4 += this.CELL_SIZE) {\n const i4 = this.getBucketKey(e37, o4), r4 = this.buckets.get(i4);\n r4 ? r4.push([n2, t2]) : this.buckets.set(i4, [[n2, t2]]);\n }\n }\n }\n buckets;\n CELL_SIZE = 0.4;\n getBucketKey(e36, t2) {\n return `${Math.floor(e36 / this.CELL_SIZE)}x${Math.floor(t2 / this.CELL_SIZE)}`;\n }\n getNodesInArea(e36, t2, n2, o3) {\n const i3 = [], r3 = new Set, s2 = t2 - o3 / 2, a3 = e36 + n2 / 2, c3 = t2 + o3 / 2;\n for (let t3 = e36 - n2 / 2;t3 \u003c= a3; t3 += this.CELL_SIZE)\n for (let e37 = s2;e37 \u003c= c3; e37 += this.CELL_SIZE) {\n const n3 = this.getBucketKey(t3, e37), o4 = this.buckets.get(n3) || [];\n for (const e38 of o4)\n r3.has(e38[1]) || (r3.add(e38[1]), i3.push(e38[0]));\n }\n return i3;\n }\n};\nvar JF = 0.000000001;\nvar QF = class extends ni {\n getSolverName() {\n return \"TraceWidthSolver\";\n }\n hdRoutes;\n hdRoutesWithWidths = [];\n nominalTraceWidth;\n minTraceWidth;\n obstacleMargin;\n minTraceToHoleEdgeClearance;\n TRACE_WIDTH_SCHEDULE;\n connectionNominalTraceWidthMap;\n unprocessedRoutes = [];\n processedRoutes = [];\n currentTrace = null;\n cursorPosition = null;\n currentTraceSegmentIndex = 0;\n currentTraceSegmentT = 0;\n currentScheduleIndex = 0;\n currentTargetWidth = 0;\n hasInsufficientClearance = false;\n lastCollidingObstacles = [];\n lastCollidingRoutes = [];\n lastClearance = 1 / 0;\n obstacles = [];\n obstacleSHI;\n hdRouteSHI;\n connMap;\n colorMap;\n constructor(e36) {\n super(), this.MAX_ITERATIONS = 1e6, this.hdRoutes = [...e36.hdRoutes], this.minTraceWidth = e36.minTraceWidth, this.obstacleMargin = e36.obstacleMargin ?? 0.15, this.minTraceToHoleEdgeClearance = e36.minTraceToHoleEdgeClearance, this.nominalTraceWidth = 0, this.TRACE_WIDTH_SCHEDULE = [], this.unprocessedRoutes = [...this.hdRoutes], this.connMap = e36.connMap, this.colorMap = e36.colorMap;\n const t2 = e36.layerCount;\n this.obstacles = ca(e36.obstacles ?? [], t2), this.connectionNominalTraceWidthMap = new Map;\n for (const t3 of e36.connection)\n t3.nominalTraceWidth !== undefined \u0026\u0026 this.connectionNominalTraceWidthMap.set(t3.name, t3.nominalTraceWidth);\n this.obstacles.length \u003e 0 \u0026\u0026 (this.obstacleSHI = new ZF(\"flatbush\", this.obstacles)), this.hdRouteSHI = new xr(this.hdRoutes);\n }\n getNominalTraceWidthForRoute(e36) {\n const t2 = this.connectionNominalTraceWidthMap.get(e36.connectionName);\n return t2 !== undefined ? t2 : e36.rootConnectionName ? this.connectionNominalTraceWidthMap.get(e36.rootConnectionName) : undefined;\n }\n _step() {\n if (!this.currentTrace) {\n const e37 = this.unprocessedRoutes.shift();\n if (!e37)\n return this.hdRoutesWithWidths = this.processedRoutes, void (this.solved = true);\n const t2 = this.getNominalTraceWidthForRoute(e37);\n if (t2 === undefined) {\n const t3 = e37.traceThickness ?? this.minTraceWidth;\n return this.processedRoutes.push(this.createRouteWithWidth(e37, t3)), void (this.currentTrace = null);\n }\n this.currentTrace = e37, this.nominalTraceWidth = t2;\n const n2 = (this.nominalTraceWidth + this.minTraceWidth) / 2;\n return this.TRACE_WIDTH_SCHEDULE = [this.nominalTraceWidth, n2], this.currentTrace.route.length \u003c 2 ? (this.processedRoutes.push(this.createRouteWithWidth(this.currentTrace, this.minTraceWidth)), void (this.currentTrace = null)) : (this.currentScheduleIndex = 0, this.currentTargetWidth = this.TRACE_WIDTH_SCHEDULE[0], void this.initializeCursor());\n }\n const e36 = this.stepCursorForward();\n (e36 ? this.getClearanceForSegment(this.cursorPosition, this.cursorPosition) : this.getMinimumRouteClearance()) \u003c this.currentTargetWidth / 2 + this.obstacleMargin ? (this.hasInsufficientClearance = true, this.currentScheduleIndex++, this.currentScheduleIndex \u003c this.TRACE_WIDTH_SCHEDULE.length ? (this.currentTargetWidth = this.TRACE_WIDTH_SCHEDULE[this.currentScheduleIndex], this.initializeCursor()) : this.finalizeCurrentTrace(this.minTraceWidth)) : e36 || this.finalizeCurrentTrace(this.currentTargetWidth);\n }\n initializeCursor() {\n if (!this.currentTrace)\n return;\n const e36 = this.currentTrace.route[0];\n this.cursorPosition = { ...e36 }, this.currentTraceSegmentIndex = 0, this.currentTraceSegmentT = 0, this.hasInsufficientClearance = false;\n }\n stepCursorForward() {\n if (!this.currentTrace || !this.cursorPosition)\n return false;\n const e36 = this.currentTrace.route;\n let t2 = 0.1;\n for (;t2 \u003e 0; ) {\n if (this.currentTraceSegmentIndex \u003e= e36.length - 1)\n return false;\n const n2 = e36[this.currentTraceSegmentIndex], o3 = e36[this.currentTraceSegmentIndex + 1];\n if (n2.insideJumperPad \u0026\u0026 o3.insideJumperPad) {\n this.currentTraceSegmentIndex++, this.currentTraceSegmentT = 0;\n continue;\n }\n const i3 = o3.x - n2.x, r3 = o3.y - n2.y, s2 = Math.sqrt(i3 * i3 + r3 * r3);\n if (s2 === 0) {\n this.currentTraceSegmentIndex++, this.currentTraceSegmentT = 0;\n continue;\n }\n const a3 = this.currentTraceSegmentT * s2, c3 = s2 - a3;\n if (t2 \u003c= c3) {\n const e37 = a3 + t2;\n return this.currentTraceSegmentT = e37 / s2, this.cursorPosition = { x: n2.x + i3 * this.currentTraceSegmentT, y: n2.y + r3 * this.currentTraceSegmentT, z: n2.z }, true;\n }\n if (t2 -= c3, this.currentTraceSegmentIndex++, this.currentTraceSegmentT = 0, this.currentTraceSegmentIndex \u003e= e36.length - 1) {\n const t3 = e36[e36.length - 1];\n return this.cursorPosition = { ...t3 }, false;\n }\n }\n return true;\n }\n isObstacleOwnJumperPad(e36) {\n if (!this.currentTrace?.jumpers)\n return false;\n for (const t2 of this.currentTrace.jumpers) {\n const n2 = Math.sqrt((e36.center.x - t2.start.x) ** 2 + (e36.center.y - t2.start.y) ** 2), o3 = Math.sqrt((e36.center.x - t2.end.x) ** 2 + (e36.center.y - t2.end.y) ** 2), i3 = Math.max(e36.width, e36.height) / 2 + 0.01;\n if (n2 \u003c i3 || o3 \u003c i3)\n return true;\n }\n return false;\n }\n getMinimumRouteClearance() {\n if (!this.currentTrace)\n return 1 / 0;\n let e36 = 1 / 0;\n const t2 = this.currentTrace.route;\n for (let n2 = 0;n2 \u003c t2.length - 1; n2++) {\n const o3 = t2[n2], i3 = t2[n2 + 1];\n o3.z === i3.z \u0026\u0026 (o3.insideJumperPad \u0026\u0026 i3.insideJumperPad || o3.toNextSegmentType !== \"through_obstacle\" \u0026\u0026 (e36 = Math.min(e36, this.getClearanceForSegment(o3, i3))));\n }\n return e36;\n }\n getClearanceForSegment(e36, t2) {\n if (!this.currentTrace)\n return 1 / 0;\n const n2 = this.currentTrace.rootConnectionName ?? this.currentTrace.connectionName, o3 = this.currentTargetWidth / 2 + this.obstacleMargin;\n let i3 = 1 / 0;\n this.lastCollidingObstacles = [], this.lastCollidingRoutes = [];\n const r3 = this.currentTargetWidth / 2 + Math.max(this.obstacleMargin, this.minTraceToHoleEdgeClearance ?? 0), s2 = new Set(this.obstacleSHI?.search({ minX: Math.min(e36.x, t2.x) - r3, minY: Math.min(e36.y, t2.y) - r3, maxX: Math.max(e36.x, t2.x) + r3, maxY: Math.max(e36.y, t2.y) + r3 }));\n for (const e37 of this.obstacles)\n e37.ccwRotationDegrees \u0026\u0026 s2.add(e37);\n for (const r4 of s2) {\n if (!this.isObstacleOnPointLayer(r4, e36))\n continue;\n if (xo(r4, this.currentTrace, this.connMap))\n continue;\n if (r4.obstacleId \u0026\u0026 this.connMap?.areIdsConnected(n2, r4.obstacleId))\n continue;\n if (this.isObstacleOwnJumperPad(r4))\n continue;\n const s3 = -(r4.ccwRotationDegrees ?? 0) * Math.PI / 180, a4 = Math.cos(s3), c3 = Math.sin(s3), l3 = { x: (e36.x - r4.center.x) * a4 - (e36.y - r4.center.y) * c3, y: (e36.x - r4.center.x) * c3 + (e36.y - r4.center.y) * a4 }, h2 = { x: (t2.x - r4.center.x) * a4 - (t2.y - r4.center.y) * c3, y: (t2.x - r4.center.x) * c3 + (t2.y - r4.center.y) * a4 }, d2 = (r4.isNonPlatedHole \u0026\u0026 r4.shape === \"circle\" ? Te(e36, t2, { ...r4.center, radius: r4.width / 2 }) : Re(l3, h2, { center: { x: 0, y: 0 }, width: r4.width, height: r4.height })) - ((r4.isNonPlatedHole ? this.minTraceToHoleEdgeClearance ?? this.obstacleMargin : this.obstacleMargin) - this.obstacleMargin);\n i3 = Math.min(i3, d2), d2 \u003c o3 \u0026\u0026 this.lastCollidingObstacles.push(r4);\n }\n const a3 = this.hdRouteSHI.getConflictingRoutesForSegment(e36, t2, o3);\n for (const { conflictingRoute: r4 } of a3) {\n const s3 = r4, a4 = s3.rootConnectionName ?? s3.connectionName;\n if (a4 === n2)\n continue;\n if (this.connMap?.areIdsConnected(n2, a4))\n continue;\n let c3 = 1 / 0;\n for (let n3 = 0;n3 \u003c s3.route.length - 1; n3++) {\n const o4 = s3.route[n3], i4 = s3.route[n3 + 1];\n o4.z === i4.z \u0026\u0026 o4.z === e36.z \u0026\u0026 (o4.insideJumperPad \u0026\u0026 i4.insideJumperPad || o4.toNextSegmentType !== \"through_obstacle\" \u0026\u0026 (c3 = Math.min(c3, we(e36, t2, o4, i4) - (o4.traceThickness ?? s3.traceThickness) / 2)));\n }\n for (const n3 of s3.vias)\n c3 = Math.min(c3, Te(e36, t2, { ...n3, radius: s3.viaDiameter / 2 }));\n i3 = Math.min(i3, c3), c3 \u003c o3 \u0026\u0026 this.lastCollidingRoutes.push(s3);\n }\n return this.lastClearance = i3, i3;\n }\n isObstacleOnPointLayer(e36, t2) {\n return !e36.__zLayers || e36.__zLayers.includes(t2.z);\n }\n getAdjacentNonCoincidentRoutePoint(e36, t2) {\n const n2 = e36.route[t2];\n if (!n2)\n return;\n const o3 = t2 === 0 ? 1 : -1;\n for (let i3 = t2 + o3;i3 \u003e= 0 \u0026\u0026 i3 \u003c e36.route.length; i3 += o3) {\n const t3 = e36.route[i3];\n if (me(t3, n2) \u003e JF)\n return t3;\n }\n }\n getObstacleWidthAlongVector(e36, t2) {\n const n2 = (e36.ccwRotationDegrees ?? 0) * Math.PI / 180, o3 = Math.cos(n2), i3 = Math.sin(n2), r3 = o3, s2 = i3, a3 = -i3, c3 = o3;\n return Math.abs(t2.x * r3 + t2.y * s2) * e36.width + Math.abs(t2.x * a3 + t2.y * c3) * e36.height;\n }\n getTerminalPadWidthLimit(e36, t2, n2) {\n const o3 = e36.route[t2];\n if (!o3)\n return;\n const i3 = this.getAdjacentNonCoincidentRoutePoint(e36, t2);\n if (!i3)\n return;\n const r3 = t2 === 0 ? Ae(o3, i3) : Ae(i3, o3);\n if (me(r3, { x: 0, y: 0 }) \u003c= JF)\n return;\n const s2 = { x: -r3.y, y: r3.x };\n let a3;\n for (const t3 of this.obstacles) {\n if (!this.isObstacleOnPointLayer(t3, o3))\n continue;\n if (Oe(o3, t3) \u003e JF)\n continue;\n if (!xo(t3, e36, this.connMap))\n continue;\n const n3 = this.getObstacleWidthAlongVector(t3, s2);\n if (n3 \u003c= JF)\n continue;\n const i4 = this.getObstacleWidthAlongVector(t3, r3) / 2;\n (!a3 || n3 \u003c a3.width || Math.abs(n3 - a3.width) \u003c= JF \u0026\u0026 i4 \u003e a3.neckDistance) \u0026\u0026 (a3 = { width: n3, neckDistance: i4 });\n }\n return !a3 || a3.width \u003e= n2 - JF ? undefined : a3;\n }\n getRouteDistanceInfo(e36) {\n const t2 = [0];\n let n2 = 0;\n for (let o3 = 1;o3 \u003c e36.length; o3++) {\n const i3 = e36[o3 - 1];\n n2 += me(e36[o3], i3), t2.push(n2);\n }\n return { distances: t2, totalDistance: n2 };\n }\n interpolateRoutePointAtDistance(e36, t2, n2) {\n for (let o3 = 1;o3 \u003c e36.length; o3++) {\n const i3 = t2[o3 - 1], r3 = t2[o3], s2 = r3 - i3;\n if (n2 \u003e r3 + JF)\n continue;\n const a3 = e36[o3 - 1], c3 = e36[o3];\n if (s2 \u003c= JF)\n return { ...c3 };\n const l3 = Math.max(0, Math.min(1, (n2 - i3) / s2));\n return { x: a3.x + (c3.x - a3.x) * l3, y: a3.y + (c3.y - a3.y) * l3, z: a3.z };\n }\n return { ...e36[e36.length - 1] };\n }\n getTaperWidthAtDistance({ distanceFromStart: e36, totalDistance: t2, startLimit: n2, endLimit: o3, taperDistance: i3, traceWidth: r3 }) {\n let s2 = r3;\n if (n2 !== undefined \u0026\u0026 e36 \u003c= i3) {\n const t3 = Math.min(n2.neckDistance, i3);\n if (e36 \u003c= t3)\n s2 = Math.min(s2, n2.width);\n else {\n const o4 = (e36 - t3) / Math.max(i3 - t3, JF);\n s2 = Math.min(s2, n2.width + (r3 - n2.width) * o4);\n }\n }\n if (o3 !== undefined) {\n const n3 = t2 - e36;\n if (n3 \u003c= i3) {\n const e37 = Math.min(o3.neckDistance, i3);\n if (n3 \u003c= e37)\n s2 = Math.min(s2, o3.width);\n else {\n const t3 = (n3 - e37) / Math.max(i3 - e37, JF);\n s2 = Math.min(s2, o3.width + (r3 - o3.width) * t3);\n }\n }\n }\n return s2;\n }\n createTerminalTaperedRoute(e36, t2) {\n if (e36.route.length \u003c 2)\n return e36.route.map((e37) =\u003e ({ ...e37, traceThickness: e37.traceThickness ?? t2 }));\n const n2 = this.getTerminalPadWidthLimit(e36, 0, t2), o3 = this.getTerminalPadWidthLimit(e36, e36.route.length - 1, t2), { distances: i3, totalDistance: r3 } = this.getRouteDistanceInfo(e36.route);\n if (r3 \u003c= JF) {\n const i4 = Math.min(n2?.width ?? t2, o3?.width ?? t2);\n return e36.route.map((e37) =\u003e ({ ...e37, traceThickness: i4 }));\n }\n const s2 = Math.min(Math.max(2 * t2, 0.75), r3 / 2), a3 = i3.map((e37, t3) =\u003e ({ distanceFromStart: e37, originalPointIndex: t3 })), c3 = [];\n if (n2 !== undefined) {\n c3.push(n2.neckDistance);\n for (let e37 = 0;e37 \u003c= 8; e37++)\n c3.push(s2 * e37 / 8);\n }\n if (o3 !== undefined) {\n c3.push(r3 - o3.neckDistance);\n for (let e37 = 0;e37 \u003c= 8; e37++)\n c3.push(r3 - s2 + s2 * e37 / 8);\n }\n for (const e37 of c3) {\n const t3 = Math.max(0, Math.min(r3, e37));\n a3.some((e38) =\u003e Math.abs(e38.distanceFromStart - t3) \u003c= JF) || a3.push({ distanceFromStart: t3 });\n }\n return a3.sort((e37, t3) =\u003e {\n const n3 = e37.distanceFromStart - t3.distanceFromStart;\n return Math.abs(n3) \u003e JF ? n3 : (e37.originalPointIndex ?? 1 / 0) - (t3.originalPointIndex ?? 1 / 0);\n }), a3.map((a4) =\u003e {\n const { distanceFromStart: c4 } = a4, l3 = a4.originalPointIndex !== undefined ? { ...e36.route[a4.originalPointIndex] } : this.interpolateRoutePointAtDistance(e36.route, i3, c4);\n return l3.traceThickness = this.getTaperWidthAtDistance({ distanceFromStart: c4, totalDistance: r3, startLimit: n2, endLimit: o3, taperDistance: s2, traceWidth: t2 }), l3;\n });\n }\n createRouteWithWidth(e36, t2) {\n return { connectionName: e36.connectionName, rootConnectionName: e36.rootConnectionName, startPcbPortId: e36.startPcbPortId, endPcbPortId: e36.endPcbPortId, traceThickness: t2, viaDiameter: e36.viaDiameter, route: this.createTerminalTaperedRoute(e36, t2), vias: [...e36.vias], jumpers: e36.jumpers };\n }\n finalizeCurrentTrace(e36) {\n if (!this.currentTrace)\n return;\n const t2 = this.createRouteWithWidth(this.currentTrace, e36);\n this.processedRoutes.push(t2), this.hdRouteSHI.removeRoute(t2.connectionName), this.hdRouteSHI.addRoute(t2), this.currentTrace = null, this.cursorPosition = null, this.hasInsufficientClearance = false;\n }\n visualize() {\n const e36 = { lines: [], points: [], circles: [], rects: [], coordinateSystem: \"cartesian\", title: `Trace Width Solver (schedule: [${this.TRACE_WIDTH_SCHEDULE.map((e37) =\u003e e37.toFixed(2)).join(\", \")}]mm, fallback: ${this.minTraceWidth.toFixed(2)}mm, margin: ${this.obstacleMargin.toFixed(2)}mm)` }, t2 = new Set(this.lastCollidingObstacles.map((e37) =\u003e e37.obstacleId)), n2 = new Set(this.lastCollidingRoutes.map((e37) =\u003e e37.connectionName));\n for (const n3 of this.obstacles) {\n const o3 = t2.has(n3.obstacleId), i3 = n3.__zLayers?.includes(0), r3 = n3.__zLayers?.includes(1);\n let s2;\n s2 = o3 ? \"rgba(255, 0, 0, 0.6)\" : i3 \u0026\u0026 r3 ? \"rgba(128, 0, 128, 0.15)\" : i3 ? \"rgba(255, 0, 0, 0.15)\" : r3 ? \"rgba(0, 0, 255, 0.15)\" : \"rgba(128, 128, 128, 0.15)\", e36.rects.push({ center: n3.center, width: n3.width, height: n3.height, fill: s2, stroke: o3 ? \"red\" : undefined, label: o3 ? `COLLIDING: ${n3.obstacleId ?? \"obstacle\"}` : `${n3.obstacleId ?? \"obstacle\"} (Z: ${n3.__zLayers?.join(\", \")})` });\n }\n for (const t3 of this.processedRoutes) {\n if (t3.route.length === 0)\n continue;\n const n3 = t3.traceThickness === this.nominalTraceWidth, o3 = t3.traceThickness === this.TRACE_WIDTH_SCHEDULE[1], i3 = n3 ? \"green\" : o3 ? \"yellow\" : \"orange\";\n for (let n4 = 0;n4 \u003c t3.route.length - 1; n4++) {\n const o4 = t3.route[n4], r3 = t3.route[n4 + 1];\n o4.insideJumperPad \u0026\u0026 r3.insideJumperPad || o4.z === r3.z \u0026\u0026 e36.lines.push({ points: [{ x: o4.x, y: o4.y }, { x: r3.x, y: r3.y }], strokeColor: i3, strokeWidth: o4.traceThickness ?? t3.traceThickness, label: `${t3.connectionName} (w=${(o4.traceThickness ?? t3.traceThickness).toFixed(2)})` });\n }\n for (const n4 of t3.vias)\n e36.circles.push({ center: { x: n4.x, y: n4.y }, radius: t3.viaDiameter / 2, fill: \"rgba(255, 0, 255, 0.5)\", label: `${t3.connectionName} via` });\n if (t3.jumpers \u0026\u0026 t3.jumpers.length \u003e 0) {\n const n4 = fB(t3.jumpers, { color: i3, label: t3.connectionName });\n e36.rects.push(...n4.rects ?? []), e36.lines.push(...n4.lines ?? []);\n }\n }\n if (this.currentTrace) {\n for (let t3 = 0;t3 \u003c this.currentTrace.route.length - 1; t3++) {\n const n3 = this.currentTrace.route[t3], o3 = this.currentTrace.route[t3 + 1];\n n3.insideJumperPad \u0026\u0026 o3.insideJumperPad || n3.z === o3.z \u0026\u0026 e36.lines.push({ points: [{ x: n3.x, y: n3.y }, { x: o3.x, y: o3.y }], strokeColor: \"cyan\", strokeWidth: this.currentTrace.traceThickness ?? this.minTraceWidth, label: `Processing: ${this.currentTrace.connectionName}` });\n }\n this.cursorPosition \u0026\u0026 (e36.circles.push({ center: { x: this.cursorPosition.x, y: this.cursorPosition.y }, radius: this.currentTargetWidth / 2, stroke: this.hasInsufficientClearance ? \"red\" : \"green\", fill: \"none\", label: `Testing width: ${this.currentTargetWidth.toFixed(2)}mm (clearance: ${this.lastClearance.toFixed(2)}mm)` }), e36.points.push({ x: this.cursorPosition.x, y: this.cursorPosition.y, color: \"orange\", label: \"Cursor\" }));\n }\n for (const t3 of this.unprocessedRoutes) {\n if (t3.route.length === 0)\n continue;\n const o3 = n2.has(t3.connectionName);\n for (let n3 = 0;n3 \u003c t3.route.length - 1; n3++) {\n const i3 = t3.route[n3], r3 = t3.route[n3 + 1];\n i3.z === r3.z \u0026\u0026 e36.lines.push({ points: [{ x: i3.x, y: i3.y }, { x: r3.x, y: r3.y }], strokeColor: o3 ? \"rgba(255, 0, 0, 0.8)\" : \"rgba(128, 128, 128, 0.3)\", strokeWidth: t3.traceThickness ?? this.minTraceWidth, label: o3 ? `COLLIDING: ${t3.connectionName}` : t3.connectionName });\n }\n }\n return e36;\n }\n getHdRoutesWithWidths() {\n return this.hdRoutesWithWidths;\n }\n};\nfunction KF(e36, t2, n2, o3 = {}) {\n return { solverName: e36, solverClass: t2, getConstructorParams: n2, onSolved: o3.onSolved };\n}\nvar ej = class extends ni {\n constructor(e36, t2 = {}) {\n super(), this.srj = e36, this.opts = t2, this.srj = e36, this.opts = { ...t2 }, this.viaDiameter = Yo(e36).padDiameter, this.minTraceWidth = e36.minTraceWidth;\n const n2 = this.opts;\n if (this.effort = n2.effort ?? 1, this.MAX_ITERATIONS = 1e8 * this.effort, n2.capacityDepth === undefined) {\n const t3 = e36.bounds.maxX - e36.bounds.minX, o3 = e36.bounds.maxY - e36.bounds.minY, i3 = Math.max(t3, o3), r3 = n2.targetMinCapacity ?? 0.5;\n n2.capacityDepth = Fz(i3, r3);\n }\n this.connMap = ei(e36), this.colorMap = Eo(e36, this.connMap), this.cacheProvider = n2.cacheProvider === undefined ? no() : n2.cacheProvider === null ? null : n2.cacheProvider, this.startTimeOfPhase = {}, this.endTimeOfPhase = {}, this.timeSpentOnPhase = {};\n }\n getSolverName() {\n return \"AutoroutingPipelineSolver2_PortPointPathing\";\n }\n netToPointPairsSolver;\n nodeSolver;\n nodeTargetMerger;\n edgeSolver;\n colorMap;\n highDensityRouteSolver;\n highDensityStitchSolver;\n singleLayerNodeMerger;\n strawSolver;\n deadEndSolver;\n traceSimplificationSolver;\n availableSegmentPointSolver;\n portPointPathingSolver;\n multiSectionPortPointOptimizer;\n uniformPortDistributionSolver;\n traceWidthSolver;\n viaDiameter;\n minTraceWidth;\n effort;\n startTimeOfPhase;\n endTimeOfPhase;\n timeSpentOnPhase;\n activeSubSolver = null;\n connMap;\n srjWithPointPairs;\n capacityNodes = null;\n capacityEdges = null;\n inputNodeWithPortPoints = [];\n cacheProvider = null;\n pipelineDef = [KF(\"netToPointPairsSolver\", pB, (e36) =\u003e [e36.srj, e36.colorMap, ti(e36.srj)], { onSolved: (e36) =\u003e {\n e36.srjWithPointPairs = e36.netToPointPairsSolver?.getNewSimpleRouteJson(), e36.colorMap = Eo(e36.srjWithPointPairs, this.connMap), e36.connMap = ei(e36.srjWithPointPairs);\n } }), KF(\"nodeSolver\", Jn, (e36) =\u003e [{ simpleRouteJson: e36.srjWithPointPairs, maxGapFillPasses: 4 }], { onSolved: (e36) =\u003e {\n e36.capacityNodes = e36.nodeSolver?.getOutput().meshNodes ?? [];\n } }), KF(\"edgeSolver\", ui, (e36) =\u003e [e36.capacityNodes], { onSolved: (e36) =\u003e {\n e36.capacityEdges = e36.edgeSolver?.edges;\n } }), KF(\"availableSegmentPointSolver\", ii, (e36) =\u003e [{ nodes: e36.capacityNodes, edges: e36.capacityEdges || [], traceWidth: e36.minTraceWidth, colorMap: e36.colorMap, shouldReturnCrampedPortPoints: false }]), KF(\"portPointPathingSolver\", Kz, (e36) =\u003e {\n this.inputNodeWithPortPoints = e36.capacityNodes.map((e37) =\u003e ({ capacityMeshNodeId: e37.capacityMeshNodeId, center: e37.center, width: e37.width, height: e37.height, portPoints: [], availableZ: e37.availableZ, _containsTarget: e37._containsTarget, _containsObstacle: e37._containsObstacle }));\n const t2 = new Map(this.inputNodeWithPortPoints.map((e37) =\u003e [e37.capacityMeshNodeId, e37])), n2 = e36.availableSegmentPointSolver;\n for (const e37 of n2.sharedEdgeSegments)\n for (const n3 of e37.portPoints) {\n const [e38, o3] = n3.nodeIds, i3 = { portPointId: n3.segmentPortPointId, x: n3.x, y: n3.y, z: n3.availableZ[0] ?? 0, connectionNodeIds: [e38, o3], distToCentermostPortOnZ: n3.distToCentermostPortOnZ }, r3 = t2.get(e38);\n r3 \u0026\u0026 r3.portPoints.push(i3);\n }\n return [{ simpleRouteJson: e36.srjWithPointPairs, inputNodes: this.inputNodeWithPortPoints, capacityMeshNodes: e36.capacityNodes, colorMap: e36.colorMap, numShuffleSeeds: 200, hyperParameters: { NODE_PF_MAX_PENALTY: 100, FORCE_OFF_BOARD_FREQUENCY: 0, STRAIGHT_LINE_DEVIATION_PENALTY_FACTOR: 4 } }];\n }), KF(\"multiSectionPortPointOptimizer\", nB, (e36) =\u003e {\n const t2 = e36.portPointPathingSolver;\n return [{ simpleRouteJson: e36.srjWithPointPairs, inputNodes: t2.inputNodes, capacityMeshNodes: e36.capacityNodes, capacityMeshEdges: e36.capacityEdges, colorMap: e36.colorMap, initialConnectionResults: t2.connectionsWithResults, initialAssignedPortPoints: t2.assignedPortPoints, initialNodeAssignedPortPoints: t2.nodeAssignedPortPoints, effort: Math.min(1, e36.effort) }];\n }), KF(\"uniformPortDistributionSolver\", bo, (e36) =\u003e [{ nodeWithPortPoints: e36.multiSectionPortPointOptimizer?.getNodesWithPortPoints() ?? e36.portPointPathingSolver?.getNodesWithPortPoints() ?? [], inputNodesWithPortPoints: this.inputNodeWithPortPoints, minTraceWidth: e36.minTraceWidth, obstacles: e36.srj.obstacles, layerCount: e36.srj.layerCount }]), KF(\"highDensityRouteSolver\", Dz, (e36) =\u003e [{ nodePortPoints: e36.uniformPortDistributionSolver?.getOutput() ?? e36.multiSectionPortPointOptimizer?.getNodesWithPortPoints() ?? e36.portPointPathingSolver?.getNodesWithPortPoints() ?? [], nodePfById: e36.multiSectionPortPointOptimizer?.nodePfMap ?? new Map((e36.portPointPathingSolver?.inputNodes ?? []).map((t2) =\u003e [t2.capacityMeshNodeId, e36.portPointPathingSolver?.computeNodePf(t2) ?? null])), colorMap: e36.colorMap, connMap: e36.connMap, viaDiameter: e36.viaDiameter, traceWidth: e36.minTraceWidth, effort: Math.min(1, e36.effort) }]), KF(\"highDensityStitchSolver\", IB, (e36) =\u003e [{ connections: e36.srjWithPointPairs.connections, hdRoutes: e36.highDensityRouteSolver.routes, colorMap: e36.colorMap, layerCount: e36.srj.layerCount, defaultViaDiameter: e36.viaDiameter }]), KF(\"traceSimplificationSolver\", WF, (e36) =\u003e [{ hdRoutes: e36.highDensityStitchSolver.mergedHdRoutes, obstacles: e36.srj.obstacles, connMap: e36.connMap, colorMap: e36.colorMap, outline: e36.srj.outline, defaultViaDiameter: e36.viaDiameter, layerCount: e36.srj.layerCount, iterations: 2 }]), KF(\"traceWidthSolver\", QF, (e36) =\u003e [{ hdRoutes: e36.traceSimplificationSolver.simplifiedHdRoutes, obstacles: e36.srj.obstacles, connMap: e36.connMap, colorMap: e36.colorMap, minTraceWidth: e36.minTraceWidth, connection: e36.srj.connections, layerCount: e36.srj.layerCount }])];\n getConstructorParams() {\n return [this.srj, this.opts];\n }\n currentPipelineStepIndex = 0;\n _step() {\n const e36 = this.pipelineDef[this.currentPipelineStepIndex];\n if (!e36)\n return void (this.solved = true);\n if (this.activeSubSolver)\n return this.activeSubSolver.step(), void (this.activeSubSolver.solved ? (this.endTimeOfPhase[e36.solverName] = performance.now(), this.timeSpentOnPhase[e36.solverName] = this.endTimeOfPhase[e36.solverName] - this.startTimeOfPhase[e36.solverName], e36.onSolved?.(this), this.activeSubSolver = null, this.currentPipelineStepIndex++) : this.activeSubSolver.failed \u0026\u0026 (this.error = this.activeSubSolver?.error, this.failed = true, this.activeSubSolver = null));\n const t2 = e36.getConstructorParams(this);\n this.activeSubSolver = new e36.solverClass(...t2), this[e36.solverName] = this.activeSubSolver, this.timeSpentOnPhase[e36.solverName] = 0, this.startTimeOfPhase[e36.solverName] = performance.now();\n }\n solveUntilPhase(e36) {\n for (;this.getCurrentPhase() !== e36; )\n this.step();\n }\n getCurrentPhase() {\n return this.pipelineDef[this.currentPipelineStepIndex]?.solverName ?? \"none\";\n }\n visualize() {\n if (!this.solved \u0026\u0026 this.activeSubSolver)\n return this.activeSubSolver.visualize();\n const e36 = this.netToPointPairsSolver?.visualize(), t2 = this.nodeSolver?.visualize(), n2 = this.nodeTargetMerger?.visualize(), o3 = this.singleLayerNodeMerger?.visualize(), i3 = this.strawSolver?.visualize(), r3 = this.edgeSolver?.visualize(), s2 = this.deadEndSolver?.visualize(), a3 = this.availableSegmentPointSolver?.visualize(), c3 = this.portPointPathingSolver?.visualize(), l3 = this.multiSectionPortPointOptimizer?.visualize(), h2 = this.uniformPortDistributionSolver?.visualize(), d2 = this.highDensityRouteSolver?.visualize(), u2 = this.highDensityStitchSolver?.visualize(), p3 = this.traceSimplificationSolver?.visualize(), m2 = this.srj.outline, g2 = [];\n if (g2.push({ points: [{ x: this.srj.bounds?.minX ?? -50, y: this.srj.bounds?.minY ?? -50 }, { x: this.srj.bounds?.maxX ?? 50, y: this.srj.bounds?.minY ?? -50 }, { x: this.srj.bounds?.maxX ?? 50, y: this.srj.bounds?.maxY ?? 50 }, { x: this.srj.bounds?.minX ?? -50, y: this.srj.bounds?.maxY ?? 50 }, { x: this.srj.bounds?.minX ?? -50, y: this.srj.bounds?.minY ?? -50 }], strokeColor: \"rgba(255,0,0,0.25)\" }), m2 \u0026\u0026 m2.length \u003e= 2) {\n const e37 = m2.map((e38) =\u003e ({ x: e38.x, y: e38.y }));\n e37.push({ ...e37[0] }), g2.push({ points: e37, strokeColor: \"rgba(0, 136, 255, 0.95)\" });\n }\n const f2 = Lo(this.srj), _2 = { points: [...this.srj.connections.flatMap((e37) =\u003e e37.pointsToConnect.map((t3) =\u003e ({ ...t3, layer: Bo(t3, this.srj.layerCount), label: `${e37.name} ${t3.pcb_port_id ?? \"\"}` })))], rects: [...(this.srj.obstacles ?? []).filter((e37) =\u003e !e37.isCopperPour).map((e37) =\u003e ({ ...e37, fill: e37.layers?.includes(\"top\") ? \"rgba(255,0,0,0.25)\" : e37.layers?.includes(\"bottom\") ? \"rgba(0,0,255,0.25)\" : \"rgba(255,0,0,0.25)\", layer: jo(e37, this.srj.layerCount), label: f2(e37) }))], lines: g2 }, y2 = [_2, e36, t2, n2, o3, i3, r3, s2, a3, c3, l3, h2, d2 ? pi(_2, d2) : null, u2, p3, this.solved ? pi({ lines: g2 }, Wo(this.getOutputSimpleRouteJson())) : null].filter(Boolean);\n return pi(...y2);\n }\n preview() {\n if (this.highDensityRouteSolver) {\n const e36 = [];\n for (let t2 = this.highDensityRouteSolver.routes.length - 1;t2 \u003e= 0; t2--) {\n const n2 = this.highDensityRouteSolver.routes[t2];\n if (e36.push({ points: n2.route.map((e37) =\u003e ({ x: e37.x, y: e37.y })), strokeColor: this.colorMap[n2.connectionName] }), e36.length \u003e 200)\n break;\n }\n return { lines: e36 };\n }\n if (this.portPointPathingSolver) {\n const e36 = [];\n for (const t2 of this.portPointPathingSolver.connectionsWithResults)\n t2.path \u0026\u0026 e36.push({ points: t2.path.map((e37) =\u003e ({ x: e37.point.x, y: e37.point.y })), strokeColor: this.colorMap[t2.connection.name] });\n return { lines: e36 };\n }\n return this.netToPointPairsSolver ? this.netToPointPairsSolver?.visualize() : {};\n }\n _getOutputHdRoutes() {\n return this.traceWidthSolver?.getHdRoutesWithWidths() ?? this.traceSimplificationSolver?.simplifiedHdRoutes ?? this.highDensityStitchSolver.mergedHdRoutes;\n }\n getOutputSimplifiedPcbTraces() {\n if (!this.solved || !this.highDensityRouteSolver)\n throw new Error(\"Cannot get output before solving is complete\");\n const e36 = [], t2 = this._getOutputHdRoutes();\n for (const n2 of this.netToPointPairsSolver?.newConnections ?? []) {\n const o3 = n2.__netConnectionName ?? this.srj.connections.find((e37) =\u003e e37.name === n2.name)?.__netConnectionName, i3 = t2.filter((e37) =\u003e e37.connectionName === n2.name);\n for (let t3 = 0;t3 \u003c i3.length; t3++) {\n const r3 = i3[t3], s2 = { type: \"pcb_trace\", pcb_trace_id: `${n2.name}_${t3}`, connection_name: o3 ?? n2.__rootConnectionNames?.[0] ?? n2.name, route: Ro(r3, this.srj.layerCount) };\n e36.push(s2);\n }\n }\n return e36;\n }\n getOutputSimpleRouteJson() {\n return { ...this.srj, traces: this.getOutputSimplifiedPcbTraces() };\n }\n};\nvar nj = class extends ni {\n getSolverName() {\n return \"CapacityEdgeToPortSegmentSolver\";\n }\n nodes;\n edges;\n capacityPaths;\n nodeMap;\n nodeEdgeMap;\n unprocessedNodeIds;\n nodePortSegments;\n colorMap;\n constructor({ nodes: e36, edges: t2, capacityPaths: n2, colorMap: o3 }) {\n super(), this.nodes = e36, this.edges = t2, this.nodeMap = new Map(e36.map((e37) =\u003e [e37.capacityMeshNodeId, e37])), this.nodeEdgeMap = oi(t2), this.capacityPaths = n2, this.colorMap = o3 ?? {}, this.unprocessedNodeIds = [...new Set(n2.flatMap((e37) =\u003e e37.nodeIds))], this.nodePortSegments = new Map;\n }\n step() {\n const e36 = this.unprocessedNodeIds.pop();\n if (!e36)\n return void (this.solved = true);\n const t2 = [];\n for (const n3 of this.capacityPaths) {\n const o4 = n3.nodeIds.indexOf(e36);\n o4 !== -1 \u0026\u0026 t2.push({ path: n3, indexOfNodeInPath: o4 });\n }\n const n2 = this.nodeMap.get(e36), o3 = [];\n for (const { path: i4, indexOfNodeInPath: r3 } of t2) {\n const t3 = i4.nodeIds[r3 - 1], s2 = i4.nodeIds[r3 + 1];\n for (const r4 of [t3, s2]) {\n const t4 = this.nodeMap.get(r4);\n if (!t4)\n continue;\n const s3 = oj(n2, t4), a3 = t4.availableZ.filter((e37) =\u003e n2.availableZ.includes(e37));\n if (a3.length === 0)\n continue;\n const c3 = { capacityMeshNodeId: e36, start: s3.start, end: s3.end, connectionNames: [i4.connectionName], rootConnectionNames: i4.rootConnectionName ? [i4.rootConnectionName] : undefined, availableZ: a3 };\n o3.push(c3);\n }\n }\n const i3 = function(e37) {\n const t3 = [], n3 = e37.map((e38) =\u003e ({ ...e38, connectionNames: [...e38.connectionNames], rootConnectionNames: e38.rootConnectionNames ? [...e38.rootConnectionNames] : [], availableZ: [...e38.availableZ].sort((e39, t4) =\u003e e39 - t4) }));\n for (;n3.length \u003e 0; ) {\n const e38 = n3.pop();\n let o4 = false;\n for (let n4 = 0;n4 \u003c t3.length; n4++) {\n const i4 = t3[n4], r3 = rj(i4.start, e38.start) \u0026\u0026 rj(i4.end, e38.end) || rj(i4.start, e38.end) \u0026\u0026 rj(i4.end, e38.start), s2 = sj(i4.availableZ, e38.availableZ);\n if (r3 \u0026\u0026 s2) {\n const t4 = new Set(i4.connectionNames);\n e38.connectionNames.forEach((e39) =\u003e t4.add(e39)), i4.connectionNames = Array.from(t4);\n const n5 = new Set(i4.rootConnectionNames || []);\n e38.rootConnectionNames?.forEach((e39) =\u003e n5.add(e39)), i4.rootConnectionNames = Array.from(n5), o4 = true;\n break;\n }\n }\n o4 || t3.push(e38);\n }\n return t3;\n }(o3);\n this.nodePortSegments.set(e36, i3);\n }\n visualize() {\n const e36 = { lines: [], points: [], rects: [], circles: [] };\n return this.nodePortSegments.forEach((t2, n2) =\u003e {\n this.nodeMap.get(n2);\n t2.forEach((t3) =\u003e {\n t3.start.x, t3.end.x;\n for (let o3 = 0;o3 \u003c t3.connectionNames.length; o3++) {\n const i3 = { x: 0.05 * Math.max(...t3.availableZ), y: 0.05 * Math.max(...t3.availableZ) }, r3 = { x: (t3.start.x + t3.end.x) / 2, y: (t3.start.y + t3.end.y) / 2 }, s2 = { x: r3.x + i3.x, y: r3.y + i3.y };\n i3.x \u003e 0 \u0026\u0026 e36.lines.push({ points: [r3, s2], strokeColor: \"rgba(0, 0, 0, 0.25)\", strokeDash: \"5 5\" }), e36.points.push({ x: s2.x, y: s2.y, label: `${n2}: ${t3.connectionNames.join(\", \")}\navailableZ: ${t3.availableZ.join(\",\")}\nnodePortSegmentId: ${t3.nodePortSegmentId}` }), e36.lines.push({ points: [t3.start, t3.end], strokeColor: Ao(this.colorMap[t3.connectionNames[o3]], 0.6) });\n }\n });\n }), e36;\n }\n};\nfunction oj(e36, t2) {\n const n2 = { start: Math.max(e36.center.x - e36.width / 2, t2.center.x - t2.width / 2), end: Math.min(e36.center.x + e36.width / 2, t2.center.x + t2.width / 2) }, o3 = { start: Math.max(e36.center.y - e36.height / 2, t2.center.y - t2.height / 2), end: Math.min(e36.center.y + e36.height / 2, t2.center.y + t2.height / 2) };\n if (n2.end - n2.start \u003c o3.end - o3.start) {\n const e37 = (n2.start + n2.end) / 2;\n return { start: { x: e37, y: o3.start }, end: { x: e37, y: o3.end } };\n }\n {\n const e37 = (o3.start + o3.end) / 2;\n return { start: { x: n2.start, y: e37 }, end: { x: n2.end, y: e37 } };\n }\n}\nvar ij = 0.000000001;\nfunction rj(e36, t2) {\n return Math.abs(e36.x - t2.x) \u003c ij \u0026\u0026 Math.abs(e36.y - t2.y) \u003c ij;\n}\nfunction sj(e36, t2) {\n if (e36.length !== t2.length)\n return false;\n for (let n2 = 0;n2 \u003c e36.length; n2++)\n if (e36[n2] !== t2[n2])\n return false;\n return true;\n}\nvar aj = class {\n constructor(e36) {\n this.targets = e36, this.buckets = new Map;\n for (let t2 = 0;t2 \u003c e36.length; t2++) {\n const n2 = e36[t2], o3 = Math.floor(n2.bounds.minX / this.CELL_SIZE) * this.CELL_SIZE, i3 = Math.floor(n2.bounds.minY / this.CELL_SIZE) * this.CELL_SIZE, r3 = n2.bounds.maxX, s2 = n2.bounds.maxY;\n for (let e37 = o3;e37 \u003c= r3; e37 += this.CELL_SIZE)\n for (let o4 = i3;o4 \u003c= s2; o4 += this.CELL_SIZE) {\n const i4 = this.getBucketKey(e37, o4), r4 = this.buckets.get(i4);\n r4 ? r4.push([n2, t2]) : this.buckets.set(i4, [[n2, t2]]);\n }\n }\n }\n buckets;\n CELL_SIZE = 5;\n getBucketKey(e36, t2) {\n return `${Math.floor(e36 / this.CELL_SIZE)}x${Math.floor(t2 / this.CELL_SIZE)}`;\n }\n getTargetsInArea(e36, t2, n2, o3) {\n const i3 = [], r3 = new Set, s2 = Math.floor((e36 - n2 / 2) / this.CELL_SIZE) * this.CELL_SIZE, a3 = Math.floor((t2 - o3 / 2) / this.CELL_SIZE) * this.CELL_SIZE, c3 = e36 + n2 / 2, l3 = t2 + o3 / 2;\n for (let e37 = s2;e37 \u003c= c3; e37 += this.CELL_SIZE)\n for (let t3 = a3;t3 \u003c= l3; t3 += this.CELL_SIZE) {\n const n3 = this.getBucketKey(e37, t3), o4 = this.buckets.get(n3) || [];\n for (const e38 of o4)\n r3.has(e38[1]) || (r3.add(e38[1]), i3.push(e38[0]));\n }\n return i3;\n }\n};\nvar cj = class extends ni {\n constructor(e36, t2 = {}) {\n super(), this.srj = e36, this.opts = t2, this.MAX_DEPTH = t2?.capacityDepth ?? this.MAX_DEPTH, this.MAX_ITERATIONS = 1e5, this.layerCount = e36.layerCount ?? 2, this.outlinePolygon = e36.outline \u0026\u0026 e36.outline.length \u003e= 3 ? e36.outline : undefined;\n const n2 = { x: (e36.bounds.minX + e36.bounds.maxX) / 2, y: (e36.bounds.minY + e36.bounds.maxY) / 2 }, o3 = { width: e36.bounds.maxX - e36.bounds.minX, height: e36.bounds.maxY - e36.bounds.minY }, i3 = Math.max(o3.width, o3.height);\n this.unfinishedNodes = [{ capacityMeshNodeId: this.getNextNodeId(), center: n2, width: i3, height: i3, layer: \"top\", availableZ: Array.from({ length: this.layerCount }, (e37, t3) =\u003e t3), _depth: 0, _containsTarget: true, _containsObstacle: true, _completelyInsideObstacle: false }], this.finishedNodes = [], this.nodeToXYOverlappingObstaclesMap = new Map, this.obstacleZLayersByObstacle = new WeakMap;\n const r3 = ca(this.srj.obstacles, this.layerCount);\n for (const [e37, t3] of this.srj.obstacles.entries())\n this.obstacleZLayersByObstacle.set(t3, r3[e37].__zLayers);\n this.obstacleTree = new ZF(\"flatbush\", this.srj.obstacles), this.targets = this.computeTargets(), this.targetTree = new aj(this.targets);\n }\n getSolverName() {\n return \"CapacityMeshNodeSolver\";\n }\n unfinishedNodes;\n finishedNodes;\n nodeToXYOverlappingObstaclesMap;\n layerCount;\n outlinePolygon;\n MAX_DEPTH = 4;\n targets;\n targetTree;\n obstacleTree;\n obstacleZLayersByObstacle;\n computeTargets() {\n const e36 = [];\n for (const t2 of this.srj.connections)\n for (const n2 of t2.pointsToConnect) {\n const o3 = So(n2), i3 = this.obstacleTree.searchArea(n2.x, n2.y, 0.01, 0.01).filter((e37) =\u003e {\n const t3 = this.getObstacleZLayers(e37);\n return !(!t3 || t3.length === 0) \u0026\u0026 t3.some((e38) =\u003e o3.some((t4) =\u003e e38 === mo(t4, this.layerCount)));\n });\n let r3 = { minX: n2.x - 0.005, minY: n2.y - 0.005, maxX: n2.x + 0.005, maxY: n2.y + 0.005 };\n i3.length \u003e 0 \u0026\u0026 (r3 = { minX: Math.min(...i3.map((e37) =\u003e e37.center.x - e37.width / 2)), minY: Math.min(...i3.map((e37) =\u003e e37.center.y - e37.height / 2)), maxX: Math.max(...i3.map((e37) =\u003e e37.center.x + e37.width / 2)), maxY: Math.max(...i3.map((e37) =\u003e e37.center.y + e37.height / 2)) });\n const s2 = { ...n2, connectionName: t2.name, availableZ: o3.map((e37) =\u003e mo(e37, this.layerCount)), bounds: r3 };\n e36.push(s2);\n }\n return e36;\n }\n getNodeBounds(e36) {\n const t2 = e36.width / 2, n2 = e36.height / 2;\n return { minX: e36.center.x - t2, maxX: e36.center.x + t2, minY: e36.center.y - n2, maxY: e36.center.y + n2 };\n }\n getNodeRect(e36) {\n return { center: { x: e36.center.x, y: e36.center.y }, width: e36.width, height: e36.height };\n }\n _nextNodeCounter = 0;\n getNextNodeId() {\n return \"cn\" + this._nextNodeCounter++;\n }\n getCapacityFromDepth(e36) {\n return (this.MAX_DEPTH - e36 + 1) ** 2;\n }\n getTargetIfNodeContainsTarget(e36) {\n const t2 = e36.width \u003e 4 * this.targetTree.CELL_SIZE ? this.targets : this.targetTree.getTargetsInArea(e36.center.x, e36.center.y, e36.width, e36.height);\n for (const n2 of t2)\n if (n2.bounds.minX \u003c= e36.center.x + e36.width / 2 \u0026\u0026 n2.bounds.maxX \u003e= e36.center.x - e36.width / 2 \u0026\u0026 n2.bounds.minY \u003c= e36.center.y + e36.height / 2 \u0026\u0026 n2.bounds.maxY \u003e= e36.center.y - e36.height / 2 \u0026\u0026 n2.availableZ.some((t3) =\u003e e36.availableZ.includes(t3)))\n return n2;\n return null;\n }\n getXYOverlappingObstacles(e36) {\n const t2 = this.nodeToXYOverlappingObstaclesMap.get(e36.capacityMeshNodeId);\n if (t2)\n return t2;\n const n2 = [], o3 = this.getNodeBounds(e36), i3 = o3.minX, r3 = o3.maxX, s2 = o3.minY, a3 = o3.maxY, c3 = e36._parent ? this.getXYOverlappingObstacles(e36._parent) : this.srj.obstacles;\n for (const e37 of c3) {\n const t3 = e37.center.x - e37.width / 2, o4 = e37.center.x + e37.width / 2, c4 = e37.center.y - e37.height / 2, l3 = e37.center.y + e37.height / 2;\n r3 \u003e= t3 \u0026\u0026 i3 \u003c= o4 \u0026\u0026 a3 \u003e= c4 \u0026\u0026 s2 \u003c= l3 ? n2.push(e37) : (i3 \u003e= t3 \u0026\u0026 r3 \u003c= o4 \u0026\u0026 s2 \u003e= c4 \u0026\u0026 a3 \u003c= l3 || t3 \u003e= i3 \u0026\u0026 o4 \u003c= r3 \u0026\u0026 c4 \u003e= s2 \u0026\u0026 l3 \u003c= a3) \u0026\u0026 n2.push(e37);\n }\n return this.nodeToXYOverlappingObstaclesMap.set(e36.capacityMeshNodeId, n2), n2;\n }\n getXYZOverlappingObstacles(e36) {\n const t2 = this.getXYOverlappingObstacles(e36), n2 = [];\n for (const o3 of t2)\n e36.availableZ.some((e37) =\u003e this.getObstacleZLayers(o3).includes(e37)) \u0026\u0026 n2.push(o3);\n return n2;\n }\n doesNodeOverlapObstacle(e36) {\n if (this.getXYZOverlappingObstacles(e36).length \u003e 0)\n return true;\n const t2 = this.getNodeBounds(e36);\n if (this.outlinePolygon) {\n const t3 = this.getNodeRect(e36);\n if (!Ce(t3, this.outlinePolygon))\n return true;\n }\n return t2.minX \u003c this.srj.bounds.minX || t2.maxX \u003e this.srj.bounds.maxX || t2.minY \u003c this.srj.bounds.minY || t2.maxY \u003e this.srj.bounds.maxY;\n }\n isNodeCompletelyInsideObstacle(e36) {\n const t2 = this.getXYZOverlappingObstacles(e36), n2 = this.getNodeBounds(e36);\n if (this.outlinePolygon) {\n const t3 = this.getNodeRect(e36);\n if (!Se(t3, this.outlinePolygon))\n return true;\n }\n for (const e37 of t2) {\n const t3 = e37.center.x - e37.width / 2, o3 = e37.center.x + e37.width / 2, i3 = e37.center.y - e37.height / 2, r3 = e37.center.y + e37.height / 2;\n if (n2.minX \u003e= t3 \u0026\u0026 n2.maxX \u003c= o3 \u0026\u0026 n2.minY \u003e= i3 \u0026\u0026 n2.maxY \u003c= r3)\n return true;\n }\n return false;\n }\n getChildNodes(e36) {\n if (e36._depth === this.MAX_DEPTH)\n return [];\n const t2 = [], n2 = { width: e36.width / 2, height: e36.height / 2 }, o3 = [{ x: e36.center.x - n2.width / 2, y: e36.center.y - n2.height / 2 }, { x: e36.center.x + n2.width / 2, y: e36.center.y - n2.height / 2 }, { x: e36.center.x - n2.width / 2, y: e36.center.y + n2.height / 2 }, { x: e36.center.x + n2.width / 2, y: e36.center.y + n2.height / 2 }];\n for (const i3 of o3) {\n const o4 = { capacityMeshNodeId: this.getNextNodeId(), center: i3, width: n2.width, height: n2.height, layer: e36.layer, availableZ: e36.availableZ, _depth: (e36._depth ?? 0) + 1, _parent: e36 };\n o4._containsObstacle = this.doesNodeOverlapObstacle(o4);\n const r3 = this.getTargetIfNodeContainsTarget(o4);\n r3 \u0026\u0026 (o4._targetConnectionName = r3.connectionName, o4.availableZ = r3.availableZ, o4._containsTarget = true), o4._containsObstacle \u0026\u0026 (o4._completelyInsideObstacle = this.isNodeCompletelyInsideObstacle(o4)), o4._completelyInsideObstacle \u0026\u0026 !o4._containsTarget || t2.push(o4);\n }\n return t2;\n }\n shouldNodeBeXYSubdivided(e36) {\n return !(e36._depth \u003e= this.MAX_DEPTH) \u0026\u0026 (!!e36._containsTarget || !(!e36._containsObstacle || e36._completelyInsideObstacle));\n }\n _step() {\n const e36 = this.unfinishedNodes.pop();\n if (!e36)\n return void (this.solved = true);\n const t2 = this.getChildNodes(e36), n2 = [], o3 = [];\n for (const e37 of t2) {\n const t3 = this.shouldNodeBeXYSubdivided(e37);\n t3 ? o3.push(e37) : t3 || e37._containsObstacle ? !t3 \u0026\u0026 e37._containsTarget \u0026\u0026 n2.push(e37) : n2.push(e37);\n }\n this.unfinishedNodes.push(...o3), this.finishedNodes.push(...n2);\n }\n visualize() {\n const e36 = { lines: [], points: [], rects: [], circles: [], coordinateSystem: \"cartesian\", title: \"Capacity Mesh Visualization\" };\n if (this.outlinePolygon \u0026\u0026 this.outlinePolygon.length \u003e= 2) {\n const t3 = this.outlinePolygon.map((e37) =\u003e ({ x: e37.x, y: e37.y }));\n t3.push({ ...t3[0] }), e36.lines.push({ points: t3, strokeColor: \"rgba(0, 136, 255, 0.95)\", label: \"outline\" });\n for (const t4 of this.outlinePolygon)\n e36.points.push({ x: t4.x, y: t4.y, color: \"rgba(0, 136, 255, 0.95)\" });\n }\n for (const t3 of this.srj.obstacles) {\n if (t3.isCopperPour)\n continue;\n const n2 = this.getObstacleZLayers(t3);\n e36.rects.push({ center: t3.center, width: t3.width, height: t3.height, fill: n2.length === 1 \u0026\u0026 n2.includes(1) ? \"rgba(0,0,255,0.3)\" : \"rgba(255,0,0,0.3)\", stroke: \"red\", label: [\"obstacle\", `z: ${n2.join(\",\")}`].join(`\n`) });\n }\n const t2 = [...this.finishedNodes, ...this.unfinishedNodes];\n for (const n2 of t2) {\n const t3 = Math.min(...n2.availableZ), o3 = this.unfinishedNodes.length \u003e 0 \u0026\u0026 n2 === this.unfinishedNodes[this.unfinishedNodes.length - 1];\n e36.rects.push({ center: { x: n2.center.x + t3 * n2.width * 0.05, y: n2.center.y - t3 * n2.width * 0.05 }, width: Math.max(n2.width - 2, 0.8 * n2.width), height: Math.max(n2.height - 2, 0.8 * n2.height), fill: n2._containsObstacle ? \"rgba(255,0,0,0.1)\" : { \"0,1\": \"rgba(0,0,0,0.1)\", 0: \"rgba(0,200,200, 0.1)\", 1: \"rgba(0,0,200, 0.1)\" }[n2.availableZ.join(\",\")] ?? \"rgba(0,200,200,0.1)\", stroke: o3 ? \"rgba(255,165,0,0.5)\" : undefined, label: [n2.capacityMeshNodeId, `availableZ: ${n2.availableZ.join(\",\")}`, `target? ${n2._containsTarget ?? false}`, `obs? ${n2._containsObstacle ?? false}`, `${n2.width.toFixed(2)}x${n2.height.toFixed(2)}`, `capacity: ${Bz(n2).toFixed(2)}`].join(`\n`) });\n }\n return e36.rects.sort((e37, t3) =\u003e e37.center.y - t3.center.y), this.srj.connections.forEach((t3, n2) =\u003e {\n const o3 = To[n2 % To.length];\n for (const i3 of t3.pointsToConnect) {\n const t4 = So(i3);\n e36.points.push({ x: i3.x, y: i3.y, label: `conn-${n2} (${t4.join(\",\")})`, color: o3 });\n }\n }), e36;\n }\n getObstacleZLayers(e36) {\n return this.obstacleZLayersByObstacle.get(e36) ?? [];\n }\n};\nvar lj = class extends cj {\n constructor(e36, t2 = {}) {\n super(e36, t2), this.srj = e36, this.opts = t2, this.VIA_DIAMETER = Yo(e36).padDiameter;\n }\n getSolverName() {\n return \"CapacityMeshNodeSolver2_NodeUnderObstacle\";\n }\n VIA_DIAMETER = 0.6;\n OBSTACLE_MARGIN = 0.1;\n OVERLAP_THRESHOLD_FOR_SINGLE_LAYER_NODES = 0.2;\n isNodeCompletelyOutsideBounds(e36) {\n if (this.outlinePolygon) {\n const t2 = this.getNodeRect(e36);\n if (!Se(t2, this.outlinePolygon))\n return true;\n }\n return e36.center.x + e36.width / 2 \u003c this.srj.bounds.minX || e36.center.x - e36.width / 2 \u003e this.srj.bounds.maxX || e36.center.y + e36.height / 2 \u003c this.srj.bounds.minY || e36.center.y - e36.height / 2 \u003e this.srj.bounds.maxY;\n }\n isNodePartiallyOutsideBounds(e36) {\n if (this.outlinePolygon) {\n const t2 = this.getNodeRect(e36);\n return !!Se(t2, this.outlinePolygon) \u0026\u0026 !Ce(t2, this.outlinePolygon);\n }\n return e36.center.x - e36.width / 2 \u003c this.srj.bounds.minX || e36.center.x + e36.width / 2 \u003e this.srj.bounds.maxX || e36.center.y - e36.height / 2 \u003c this.srj.bounds.minY || e36.center.y + e36.height / 2 \u003e this.srj.bounds.maxY;\n }\n getObstacleCoveragePercentage(e36) {\n const t2 = this.getXYZOverlappingObstacles(e36);\n if (t2.length === 0)\n return 0;\n const n2 = e36.center.x - e36.width / 2, o3 = e36.center.x + e36.width / 2, i3 = e36.center.y - e36.height / 2, r3 = e36.center.y + e36.height / 2, s2 = e36.width * e36.height;\n let a3 = 0;\n for (const e37 of t2) {\n const t3 = Math.max(n2, e37.center.x - e37.width / 2), s3 = Math.min(o3, e37.center.x + e37.width / 2), c3 = Math.max(i3, e37.center.y - e37.height / 2), l3 = Math.min(r3, e37.center.y + e37.height / 2);\n if (t3 \u003c s3 \u0026\u0026 c3 \u003c l3) {\n a3 += (s3 - t3) * (l3 - c3);\n }\n }\n return a3 / s2;\n }\n shouldFilterSingleLayerNodeForObstacle(e36) {\n if (e36.availableZ.length !== 1)\n return false;\n if (!e36._containsObstacle)\n return false;\n return this.getObstacleCoveragePercentage(e36) \u003e this.OVERLAP_THRESHOLD_FOR_SINGLE_LAYER_NODES;\n }\n shouldFilterNodeForObstacle(e36) {\n return !!e36._containsObstacle \u0026\u0026 (e36.availableZ.length !== 1 || this.shouldFilterSingleLayerNodeForObstacle(e36));\n }\n createChildNodeAtPosition(e36, t2) {\n const n2 = { capacityMeshNodeId: this.getNextNodeId(), center: t2.center, width: t2.width, height: t2.height, layer: e36.layer, availableZ: t2.availableZ, _depth: t2._depth ?? (e36._depth ?? 0) + 1, _parent: e36 }, o3 = this.getXYZOverlappingObstacles(n2);\n n2._containsObstacle = o3.length \u003e 0 || this.isNodePartiallyOutsideBounds(n2);\n const i3 = this.getTargetIfNodeContainsTarget(n2);\n return i3 \u0026\u0026 (n2._targetConnectionName = i3.connectionName, n2._containsTarget = true), n2._containsObstacle \u0026\u0026 (n2._completelyInsideObstacle = this.isNodeCompletelyInsideObstacle(n2)), n2;\n }\n getZSubdivisionChildNodes(e36) {\n if (e36.availableZ.length === 1)\n return [];\n const t2 = [], n2 = e36.availableZ.map((e37) =\u003e [e37]);\n for (const o3 of n2) {\n const n3 = this.createChildNodeAtPosition(e36, { center: { ...e36.center }, width: e36.width, height: e36.height, availableZ: o3, _depth: e36._depth });\n this.isNodeCompletelyOutsideBounds(n3) || t2.push(n3);\n }\n return t2;\n }\n getChildNodes(e36) {\n if (e36._depth \u003e= this.MAX_DEPTH)\n return [];\n const t2 = [], n2 = { width: e36.width / 2, height: e36.height / 2 }, o3 = [{ x: e36.center.x - n2.width / 2, y: e36.center.y - n2.height / 2 }, { x: e36.center.x + n2.width / 2, y: e36.center.y - n2.height / 2 }, { x: e36.center.x - n2.width / 2, y: e36.center.y + n2.height / 2 }, { x: e36.center.x + n2.width / 2, y: e36.center.y + n2.height / 2 }];\n for (const i3 of o3) {\n const o4 = this.createChildNodeAtPosition(e36, { center: i3, width: n2.width, height: n2.height, availableZ: e36.availableZ });\n this.isNodeCompletelyOutsideBounds(o4) || t2.push(o4);\n }\n return t2;\n }\n shouldNodeBeXYSubdivided(e36) {\n return !(e36._depth \u003e= this.MAX_DEPTH) \u0026\u0026 (!!e36._containsTarget || (e36.availableZ.length === 1 \u0026\u0026 e36._depth \u003c= this.MAX_DEPTH || !(!e36._containsObstacle || e36._completelyInsideObstacle)));\n }\n _step() {\n const e36 = this.unfinishedNodes.pop();\n if (!e36)\n return void (this.solved = true);\n const t2 = this.getChildNodes(e36), n2 = [], o3 = [];\n for (const e37 of t2) {\n const t3 = this.shouldNodeBeXYSubdivided(e37), i3 = e37.availableZ.length \u003e 1 \u0026\u0026 !t3 \u0026\u0026 (e37._containsObstacle || e37.width \u003c this.VIA_DIAMETER + this.OBSTACLE_MARGIN);\n if (t3)\n o3.push(e37);\n else if (t3 || this.shouldFilterNodeForObstacle(e37) || i3)\n if (!t3 \u0026\u0026 e37._containsTarget)\n if (i3) {\n const t4 = this.getZSubdivisionChildNodes(e37);\n n2.push(...t4.filter((e38) =\u003e e38._containsTarget || !this.shouldFilterNodeForObstacle(e38)));\n } else\n n2.push(e37);\n else\n i3 \u0026\u0026 n2.push(...this.getZSubdivisionChildNodes(e37).filter((e38) =\u003e !this.shouldFilterNodeForObstacle(e38)));\n else\n n2.push(e37);\n }\n this.unfinishedNodes.push(...o3), this.finishedNodes.push(...n2);\n }\n};\nvar hj = class extends ni {\n getSolverName() {\n return \"CapacitySegmentToPointSolver\";\n }\n unsolvedSegments;\n solvedSegments;\n nodeMap;\n colorMap;\n constructor({ segments: e36, colorMap: t2, nodes: n2 }) {\n super(), this.MAX_ITERATIONS = 1e5, this.unsolvedSegments = e36, this.solvedSegments = [], this.colorMap = t2 ?? {}, this.nodeMap = Object.fromEntries(n2.map((e37) =\u003e [e37.capacityMeshNodeId, e37]));\n }\n _step() {\n let e36 = false;\n const t2 = [...this.unsolvedSegments];\n for (const n2 of t2) {\n const t3 = n2.connectionNames.length;\n if ((!(\"assignedPoints\" in n2) || n2.assignedPoints?.length !== t3) \u0026\u0026 t3 === 1) {\n const t4 = { x: (n2.start.x + n2.end.x) / 2, y: (n2.start.y + n2.end.y) / 2, z: n2.availableZ[0] };\n n2.assignedPoints = [{ connectionName: n2.connectionNames[0], rootConnectionName: n2.rootConnectionNames?.[0], point: t4 }], this.unsolvedSegments.splice(this.unsolvedSegments.indexOf(n2), 1), this.solvedSegments.push(n2), e36 = true;\n }\n }\n if (!e36 \u0026\u0026 t2.length \u003e 0) {\n let n2 = t2[0];\n for (const e37 of t2)\n e37.connectionNames.length \u003c n2.connectionNames.length \u0026\u0026 (n2 = e37);\n const o3 = [...n2.connectionNames].sort(), i3 = n2.end.x - n2.start.x, r3 = n2.end.y - n2.start.y, s2 = o3.length, a3 = [];\n for (let e37 = 1;e37 \u003c= s2; e37++) {\n const t3 = e37 / (s2 + 1);\n a3.push({ x: n2.start.x + i3 * t3, y: n2.start.y + r3 * t3, z: n2.availableZ[0] });\n }\n n2.assignedPoints = o3.map((e37, t3) =\u003e ({ connectionName: e37, rootConnectionName: n2.rootConnectionNames?.[n2.connectionNames.indexOf(e37)], point: a3[t3] })), this.unsolvedSegments.splice(this.unsolvedSegments.indexOf(n2), 1), this.solvedSegments.push(n2), e36 = true;\n }\n this.unsolvedSegments.length === 0 \u0026\u0026 (this.solved = true);\n }\n getNodesWithPortPoints() {\n if (!this.solved)\n throw new Error(\"CapacitySegmentToPointSolver not solved, can't give port points yet\");\n const e36 = new Map;\n for (const t2 of this.solvedSegments) {\n const n2 = t2.capacityMeshNodeId, o3 = this.nodeMap[n2];\n e36.has(n2) || e36.set(n2, { capacityMeshNodeId: n2, portPoints: [], center: o3.center, width: o3.width, height: o3.height }), e36.get(n2).portPoints.push(...t2.assignedPoints.map((e37) =\u003e ({ ...e37.point, connectionName: e37.connectionName })));\n }\n return Array.from(e36.values());\n }\n visualize() {\n const e36 = { points: [], lines: this.solvedSegments.map((e37) =\u003e ({ points: [e37.start, e37.end], step: 4 })), rects: [], circles: [], coordinateSystem: \"cartesian\", title: \"Capacity Segment to Point Solver\" };\n for (let t3 = 0;t3 \u003c this.solvedSegments.length; t3++) {\n const n3 = this.solvedSegments[t3];\n for (let t4 = 0;t4 \u003c n3.assignedPoints.length; t4++) {\n const o3 = n3.assignedPoints[t4], i3 = { x: o3.point.x, y: o3.point.y }, r3 = { x: o3.point.x + 0.05 * o3.point.z, y: o3.point.y + 0.05 * o3.point.z };\n o3.point.z !== 0 \u0026\u0026 e36.lines.push({ points: [i3, r3], strokeColor: \"rgba(0, 0, 0, 0.25)\", strokeDash: \"5 5\", step: 4 }), e36.points.push({ x: r3.x, y: r3.y, label: [`${n3.capacityMeshNodeId}-${o3.connectionName}`, `z: ${n3.availableZ.join(\",\")}`, `nodePortSegmentId: ${n3.nodePortSegmentId}`].join(`\n`), color: this.colorMap[o3.connectionName], step: 4 });\n }\n }\n const t2 = [], n2 = {};\n for (const e37 of this.solvedSegments) {\n const t3 = e37.capacityMeshNodeId;\n n2[t3] || (n2[t3] = {});\n for (const o3 of e37.assignedPoints)\n n2[t3][o3.connectionName] || (n2[t3][o3.connectionName] = []), n2[t3][o3.connectionName].push({ x: o3.point.x, y: o3.point.y });\n }\n for (const e37 in n2)\n for (const o3 in n2[e37]) {\n const i3 = n2[e37][o3];\n i3.length \u003e 1 \u0026\u0026 t2.push({ points: i3, step: 4, strokeDash: \"5 5\", strokeColor: this.colorMap[o3] || \"#000\" });\n }\n return e36.lines.push(...t2), e36;\n }\n};\nvar dj = (e36, t2 = {}) =\u003e {\n const n2 = Math.min(...e36.availableZ);\n return { center: !t2.rectMargin || t2.zOffset ? { x: e36.center.x + n2 * e36.width * (t2.zOffset ?? 0.05), y: e36.center.y - n2 * e36.width * (t2.zOffset ?? 0.05) } : e36.center, width: t2.rectMargin ? e36.width - 2 * t2.rectMargin : Math.max(e36.width - 0.5, 0.8 * e36.width), height: t2.rectMargin ? e36.height - 2 * t2.rectMargin : Math.max(e36.height - 0.5, 0.8 * e36.height), fill: e36._containsObstacle ? \"rgba(255,0,0,0.1)\" : { \"0,1\": \"rgba(0,0,0,0.1)\", 0: \"rgba(0,200,200, 0.1)\", 1: \"rgba(0,0,200, 0.1)\" }[e36.availableZ.join(\",\")] ?? \"rgba(0,200,200,0.1)\", layer: `z${e36.availableZ.join(\",\")}`, label: [e36.capacityMeshNodeId, `availableZ: ${e36.availableZ.join(\",\")}`, \"\" + (e36._containsTarget ? \"containsTarget\" : \"\"), \"\" + (e36._containsObstacle ? \"containsObstacle\" : \"\")].filter(Boolean).join(`\n`) };\n};\nvar uj = class extends ni {\n getSolverName() {\n return \"CapacityPathingSolver\";\n }\n connectionsWithNodes;\n usedNodeCapacityMap;\n simpleRouteJson;\n nodes;\n edges;\n GREEDY_MULTIPLIER = 1.1;\n MAX_CANDIDATES_IN_MEMORY = 1e5;\n nodeMap;\n nodeEdgeMap;\n connectionNameToGoalNodeIds;\n colorMap;\n maxDepthOfNodes;\n activeCandidateStraightLineDistance;\n debug_lastNodeCostMap;\n hyperParameters;\n constructor({ simpleRouteJson: e36, nodes: t2, edges: n2, colorMap: o3, MAX_ITERATIONS: i3 = 1e6, hyperParameters: r3 = {} }) {\n super(), this.MAX_ITERATIONS = i3, this.simpleRouteJson = e36, this.nodes = t2, this.edges = n2, this.colorMap = o3 ?? {};\n const { connectionsWithNodes: s2, connectionNameToGoalNodeIds: a3 } = this.getConnectionsWithNodes();\n this.connectionsWithNodes = s2, this.connectionNameToGoalNodeIds = a3, this.hyperParameters = r3, this.usedNodeCapacityMap = new Map(this.nodes.map((e37) =\u003e [e37.capacityMeshNodeId, 0])), this.nodeMap = new Map(this.nodes.map((e37) =\u003e [e37.capacityMeshNodeId, e37])), this.nodeEdgeMap = oi(this.edges), this.maxDepthOfNodes = Math.max(...this.nodes.map((e37) =\u003e e37._depth ?? 0)), this.debug_lastNodeCostMap = new Map;\n }\n getTotalCapacity(e36) {\n const t2 = e36._depth ?? 0;\n return (this.maxDepthOfNodes - t2 + 1) ** 2;\n }\n getConnectionsWithNodes() {\n const e36 = [], t2 = this.nodes.filter((e37) =\u003e e37._containsTarget), n2 = new Map;\n for (const o3 of this.simpleRouteJson.connections) {\n const i3 = [];\n for (const e37 of o3.pointsToConnect) {\n let n3 = this.nodes[0], o4 = Number.MAX_VALUE;\n for (const i4 of t2) {\n const t3 = Math.sqrt((i4.center.x - e37.x) ** 2 + (i4.center.y - e37.y) ** 2);\n t3 \u003c o4 \u0026\u0026 (o4 = t3, n3 = i4);\n }\n i3.push(n3);\n }\n if (i3.length \u003c 2)\n throw new Error(`Not enough nodes for connection \"${o3.name}\", only ${i3.length} found`);\n n2.set(o3.name, i3.map((e37) =\u003e e37.capacityMeshNodeId)), e36.push({ connection: o3, nodes: i3, pathFound: false, straightLineDistance: me(i3[0].center, i3[i3.length - 1].center) });\n }\n return e36.sort((e37, t3) =\u003e e37.straightLineDistance - t3.straightLineDistance), { connectionsWithNodes: e36, connectionNameToGoalNodeIds: n2 };\n }\n currentConnectionIndex = 0;\n candidates;\n visitedNodes;\n computeG(e36, t2, n2) {\n return e36.g + this.getDistanceBetweenNodes(e36.node, t2);\n }\n computeH(e36, t2, n2) {\n return this.getDistanceBetweenNodes(t2, n2);\n }\n getBacktrackedPath(e36) {\n const t2 = [];\n let n2 = e36;\n for (;n2; )\n t2.push(n2.node), n2 = n2.prevCandidate;\n return t2;\n }\n getNeighboringNodes(e36) {\n return this.nodeEdgeMap.get(e36.capacityMeshNodeId).flatMap((t2) =\u003e t2.nodeIds.filter((t3) =\u003e t3 !== e36.capacityMeshNodeId)).map((e37) =\u003e this.nodeMap.get(e37));\n }\n getCapacityPaths() {\n const e36 = [];\n for (const t2 of this.connectionsWithNodes) {\n const n2 = t2.path;\n n2 \u0026\u0026 e36.push({ capacityPathId: t2.connection.name, connectionName: t2.connection.name, rootConnectionName: t2.connection.__rootConnectionNames?.[0], nodeIds: n2.map((e37) =\u003e e37.capacityMeshNodeId) });\n }\n return e36;\n }\n doesNodeHaveCapacityForTrace(e36, t2) {\n const n2 = this.usedNodeCapacityMap.get(e36.capacityMeshNodeId) ?? 0, o3 = this.getTotalCapacity(e36);\n if (e36.availableZ.length === 1 \u0026\u0026 !e36._containsTarget \u0026\u0026 n2 \u003e 0)\n return false;\n let i3 = 0;\n return e36.availableZ.length \u003e 1 \u0026\u0026 t2.availableZ.length === 1 \u0026\u0026 (i3 += 0.5), n2 + i3 \u003c o3;\n }\n canTravelThroughObstacle(e36, t2) {\n const n2 = this.connectionNameToGoalNodeIds.get(t2);\n return n2?.includes(e36.capacityMeshNodeId) ?? false;\n }\n getDistanceBetweenNodes(e36, t2) {\n return Math.sqrt((e36.center.x - t2.center.x) ** 2 + (e36.center.y - t2.center.y) ** 2);\n }\n reduceCapacityAlongPath(e36) {\n for (const t2 of e36.path ?? [])\n this.usedNodeCapacityMap.set(t2.capacityMeshNodeId, this.usedNodeCapacityMap.get(t2.capacityMeshNodeId) + 1);\n }\n isConnectedToEndGoal(e36, t2) {\n return this.nodeEdgeMap.get(e36.capacityMeshNodeId).some((e37) =\u003e e37.nodeIds.includes(t2.capacityMeshNodeId));\n }\n _step() {\n const e36 = this.connectionsWithNodes[this.currentConnectionIndex];\n if (!e36)\n return void (this.solved = true);\n const [t2, n2] = e36.nodes;\n this.candidates || (this.candidates = [{ prevCandidate: null, node: t2, f: 0, g: 0, h: 0 }], this.debug_lastNodeCostMap = new Map, this.visitedNodes = new Set([t2.capacityMeshNodeId]), this.activeCandidateStraightLineDistance = me(t2.center, n2.center)), this.candidates.sort((e37, t3) =\u003e e37.f - t3.f);\n const o3 = this.candidates.shift();\n if (this.candidates.length \u003e this.MAX_CANDIDATES_IN_MEMORY \u0026\u0026 this.candidates.splice(this.MAX_CANDIDATES_IN_MEMORY, this.candidates.length - this.MAX_CANDIDATES_IN_MEMORY), !o3)\n return console.error(`Ran out of candidates on connection ${e36.connection.name}`), this.currentConnectionIndex++, this.candidates = null, this.visitedNodes = null, void (this.failed = true);\n if (this.isConnectedToEndGoal(o3.node, n2))\n return e36.path = this.getBacktrackedPath({ prevCandidate: o3, node: n2, f: 0, g: 0, h: 0 }), this.reduceCapacityAlongPath(e36), this.currentConnectionIndex++, this.candidates = null, void (this.visitedNodes = null);\n const i3 = this.getNeighboringNodes(o3.node);\n for (const e37 of i3) {\n if (this.visitedNodes?.has(e37.capacityMeshNodeId))\n continue;\n if (!this.doesNodeHaveCapacityForTrace(e37, o3.node))\n continue;\n const t3 = this.connectionsWithNodes[this.currentConnectionIndex].connection.name;\n if (e37._containsObstacle \u0026\u0026 !this.canTravelThroughObstacle(e37, t3))\n continue;\n const i4 = this.computeG(o3, e37, n2), r3 = this.computeH(o3, e37, n2), s2 = i4 + r3 * this.GREEDY_MULTIPLIER;\n this.debug_lastNodeCostMap.set(e37.capacityMeshNodeId, { f: s2, g: i4, h: r3 });\n const a3 = { prevCandidate: o3, node: e37, f: s2, g: i4, h: r3 };\n this.candidates.push(a3);\n }\n this.visitedNodes.add(o3.node.capacityMeshNodeId);\n }\n visualize() {\n const e36 = { lines: [], points: [], rects: [], circles: [] };\n if (this.connectionsWithNodes)\n for (let t3 = 0;t3 \u003c this.connectionsWithNodes.length; t3++) {\n const n2 = this.connectionsWithNodes[t3];\n if (n2.path \u0026\u0026 n2.path.length \u003e 0) {\n const o3 = n2.path.map(({ center: { x: e37, y: n3 }, width: o4, availableZ: i3 }) =\u003e ({ x: e37 + 0.005 * o4 * (t3 % 10 + t3 % 19), y: n3 + 0.005 * o4 * (t3 % 10 + t3 % 19), availableZ: i3 }));\n e36.lines.push({ points: o3, strokeColor: this.colorMap[n2.connection.name] });\n for (let t4 = 0;t4 \u003c o3.length; t4++) {\n const i3 = o3[t4];\n e36.points.push({ x: i3.x, y: i3.y, label: [`conn: ${n2.connection.name}`, `node: ${n2.path[t4].capacityMeshNodeId}`, `z: ${i3.availableZ.join(\",\")}`].join(`\n`) });\n }\n }\n }\n for (const t3 of this.nodes) {\n const n2 = this.usedNodeCapacityMap.get(t3.capacityMeshNodeId) ?? 0, o3 = this.getTotalCapacity(t3), i3 = this.debug_lastNodeCostMap.get(t3.capacityMeshNodeId);\n e36.rects.push({ ...dj(t3, { rectMargin: 0.025, zOffset: 0.01 }), label: [`${t3.capacityMeshNodeId}`, `${n2}/${o3}`, `${t3.width.toFixed(2)}x${t3.height.toFixed(2)}`, `g: ${i3?.g !== undefined ? i3.g.toFixed(2) : \"?\"}`, `h: ${i3?.h !== undefined ? i3.h.toFixed(2) : \"?\"}`, `f: ${i3?.f !== undefined ? i3.f.toFixed(2) : \"?\"}`, `z: ${t3.availableZ.join(\", \")}`].join(`\n`), stroke: n2 \u003e o3 + 0.5 ? \"red\" : undefined });\n }\n if (this.connectionsWithNodes) {\n for (const t3 of this.connectionsWithNodes)\n if (t3.connection?.pointsToConnect)\n for (const n2 of t3.connection.pointsToConnect)\n e36.points.push({ x: n2.x, y: n2.y, label: [`pointsToConnect ${t3.connection.name}`].join(`\n`) });\n }\n let t2 = this.connectionsWithNodes[this.currentConnectionIndex];\n if (!this.candidates \u0026\u0026 this.currentConnectionIndex \u003e 0 \u0026\u0026 !this.connectionsWithNodes[this.currentConnectionIndex - 1].path \u0026\u0026 (t2 = this.connectionsWithNodes[this.currentConnectionIndex - 1]), t2) {\n const [n2, o3] = t2.connection.pointsToConnect;\n e36.lines.push({ points: [{ x: n2.x, y: n2.y }, { x: o3.x, y: o3.y }], strokeColor: \"red\", strokeDash: \"10 5\" });\n }\n if (this.candidates) {\n const t3 = this.candidates.slice(0, 5), n2 = this.connectionsWithNodes[this.currentConnectionIndex].connection.name;\n t3.forEach((t4, o3) =\u003e {\n const i3 = 0.5 * (1 - o3 / 5), r3 = this.getBacktrackedPath(t4);\n e36.lines.push({ points: r3.map(({ center: { x: e37, y: t5 } }) =\u003e ({ x: e37, y: t5 })), strokeColor: Ao(this.colorMap[n2] ?? \"red\", 1 - i3) });\n });\n }\n return e36;\n }\n};\nvar pj = class extends uj {\n getSolverName() {\n return \"CapacityPathingSolver5\";\n }\n NEGATIVE_CAPACITY_PENALTY_FACTOR = 1;\n REDUCED_CAPACITY_PENALTY_FACTOR = 1;\n constructor(...e36) {\n super(...e36), this.GREEDY_MULTIPLIER = 2.5;\n }\n get maxCapacityFactor() {\n return this.hyperParameters.MAX_CAPACITY_FACTOR ?? 1;\n }\n getTotalCapacity(e36) {\n return Bz(e36, this.maxCapacityFactor);\n }\n getNodeCapacityPenalty(e36) {\n const t2 = e36.width + e36.height, n2 = 0.05, o3 = this.getTotalCapacity(e36) - (this.usedNodeCapacityMap.get(e36.capacityMeshNodeId) ?? 0);\n if (o3 \u003e 2)\n return n2;\n return (t2 - n2) * Math.max(1, (2 - o3) / (t2 - n2)) + n2;\n }\n getDistanceBetweenNodes(e36, t2) {\n const n2 = e36.center.x - t2.center.x, o3 = e36.center.y - t2.center.y;\n return Math.sqrt(n2 ** 2 + o3 ** 2);\n }\n computeG(e36, t2, n2) {\n return e36.g + this.getDistanceBetweenNodes(e36.node, t2) + this.getNodeCapacityPenalty(t2);\n }\n computeH(e36, t2, n2) {\n return this.getDistanceBetweenNodes(t2, n2) + this.getNodeCapacityPenalty(t2);\n }\n};\nvar mj = class extends pj {\n getSolverName() {\n return \"CapacityPathingGreedySolver\";\n }\n doesNodeHaveCapacityForTrace(e36, t2) {\n return true;\n }\n getNodeCapacityPenalty(e36) {\n const t2 = this.getTotalCapacity(e36) - (this.usedNodeCapacityMap.get(e36.capacityMeshNodeId) ?? 0) - 1;\n if (t2 \u003e 0)\n return 0;\n let n2 = 1;\n return e36.availableZ.length === 1 \u0026\u0026 (n2 = 10), (0.05 + 2 * Math.abs(t2)) * n2;\n }\n};\nfunction gj(e36, t2, n2) {\n const o3 = t2.x - e36.x, i3 = t2.y - e36.y;\n if (Math.abs(o3) \u003c 0.000000001 \u0026\u0026 Math.abs(i3) \u003c 0.000000001)\n return e36;\n const r3 = n2.width / 2, s2 = n2.height / 2, a3 = n2.center.x - r3, c3 = n2.center.x + r3, l3 = n2.center.y - s2, h2 = n2.center.y + s2;\n let d2 = 0, u2 = 1 / 0;\n if (Math.abs(o3) \u003e 0.000000001) {\n const t3 = (a3 - e36.x) / o3, n3 = (c3 - e36.x) / o3;\n d2 = Math.max(d2, Math.min(t3, n3)), u2 = Math.min(u2, Math.max(t3, n3));\n } else if (e36.x \u003c a3 || e36.x \u003e c3)\n return e36;\n if (Math.abs(i3) \u003e 0.000000001) {\n const t3 = (l3 - e36.y) / i3, n3 = (h2 - e36.y) / i3;\n d2 = Math.max(d2, Math.min(t3, n3)), u2 = Math.min(u2, Math.max(t3, n3));\n } else if (e36.y \u003c l3 || e36.y \u003e h2)\n return e36;\n if (u2 \u003c d2 || d2 === 1 / 0 || d2 \u003c -1e9)\n return e36;\n return { x: e36.x + o3 * d2, y: e36.y + i3 * d2 };\n}\nfunction fj(e36, t2) {\n const n2 = e36.center, o3 = t2.center, i3 = gj(n2, o3, e36), r3 = gj(o3, n2, t2), s2 = o3.x - n2.x, a3 = o3.y - n2.y, c3 = Math.sqrt(s2 * s2 + a3 * a3);\n let l3 = i3, h2 = r3;\n if (c3 \u003e 0.000000001) {\n const n3 = { x: s2 / c3, y: a3 / c3 }, o4 = 0.3 * e36.width, d2 = 0.3 * t2.width;\n o4 + d2 \u003c Math.sqrt((r3.x - i3.x) ** 2 + (r3.y - i3.y) ** 2) ? (l3 = { x: i3.x + n3.x * o4, y: i3.y + n3.y * o4 }, h2 = { x: r3.x - n3.x * d2, y: r3.y - n3.y * d2 }) : (l3 = i3, h2 = r3);\n }\n return { lineStart: l3, lineEnd: h2 };\n}\nvar _j = (e36) =\u003e {\n const { usedCapacity: t2, totalCapacity: n2, layerCount: o3 } = e36;\n if (t2 \u003c n2)\n return 0;\n if (n2 \u003c 1 \u0026\u0026 t2 \u003c= 1)\n return 0;\n if (o3 === 1 \u0026\u0026 t2 \u003e 1)\n return 1 - 0.01 ** t2;\n const i3 = t2 / n2 - 1;\n return 1 - Math.exp(-2 * i3);\n};\nvar yj = (e36, t2, n2) =\u003e {\n if (n2._containsTarget)\n return 0;\n if (e36 \u003c= t2)\n return 0;\n const o3 = 1 - _j({ usedCapacity: e36, totalCapacity: t2, layerCount: n2.availableZ.length });\n return o3 \u003c= 0 ? -1e9 : Math.log(o3);\n};\nvar bj = ({ totalNodeCapacityMap: e36, usedNodeCapacityMap: t2, nodeMap: n2, sectionNodeIds: o3 }) =\u003e {\n let i3 = 0;\n const r3 = o3 ?? new Set(t2.keys());\n for (const o4 of r3) {\n if (!e36.has(o4))\n continue;\n const r4 = n2.get(o4);\n if (!r4)\n continue;\n const s2 = e36.get(o4), a3 = t2.get(o4) ?? 0;\n i3 += yj(a3, s2, r4);\n }\n return i3;\n};\nfunction xj({ sectionNodes: e36, sectionEdges: t2, sectionConnectionTerminals: n2, completedPaths: o3, nodeMap: i3, colorMap: r3, centerNodeId: s2, title: a3, nodeOpacity: c3 = 0.1, usedNodeCapacityMap: l3, totalCapacityMap: h2 }) {\n const d2 = { points: [], lines: [], rects: [], circles: [], title: a3 }, u2 = new Set(e36.map((e37) =\u003e e37.capacityMeshNodeId));\n for (const t3 of e36) {\n let e37 = `rgba(128, 128, 128, ${c3})`, n3 = `rgba(128, 128, 128, ${c3})`;\n const o4 = t3.availableZ ?? [], i4 = o4.includes(0), r4 = o4.includes(1);\n i4 \u0026\u0026 r4 ? (e37 = `rgba(128, 0, 128, ${c3})`, n3 = `rgba(128, 0, 128, ${c3})`) : i4 ? (e37 = `rgba(0, 0, 255, ${c3})`, n3 = `rgba(0, 0, 255, ${c3})`) : r4 \u0026\u0026 (e37 = `rgba(255, 0, 0, ${c3})`, n3 = `rgba(255, 0, 0, ${c3})`), s2 \u0026\u0026 t3.capacityMeshNodeId === s2 \u0026\u0026 (e37 = `rgba(0, 255, 0, ${c3})`, n3 = `rgba(0, 128, 0, ${c3})`), d2.rects.push({ ...dj(t3), fill: e37, stroke: n3, label: `${t3.capacityMeshNodeId}\n(Section Node)\nZ: ${o4.join(\",\")}` });\n const a4 = d2.rects.length - 1;\n if (l3 \u0026\u0026 h2) {\n const e38 = l3.get(t3.capacityMeshNodeId) ?? 0, n4 = h2.get(t3.capacityMeshNodeId) ?? 0, o5 = n4 \u003e 0 ? (e38 / n4 * 100).toFixed(1) : \"N/A\", i5 = _j({ usedCapacity: e38, totalCapacity: n4, layerCount: t3.availableZ.length });\n d2.rects[a4].label += `\n${e38.toFixed(1)} / ${n4.toFixed(1)}\n${o5}% (Pf: ${(100 * i5).toFixed(1)}%)`, i5 \u003e 0.2 \u0026\u0026 (d2.rects[a4].stroke = Ao(\"red\", 0.7 * (0.8 + c3)));\n }\n }\n for (const e37 of t2) {\n const [t3, n3] = e37.nodeIds, o4 = i3.get(t3), r4 = i3.get(n3);\n if (o4 \u0026\u0026 r4) {\n const { lineStart: e38, lineEnd: t4 } = fj(o4, r4);\n d2.lines.push({ points: [e38, t4], strokeColor: `rgba(0, 0, 0, ${0.2 * Math.min(1, c3 / 0.1)})` });\n }\n }\n return n2.forEach((e37, t3) =\u003e {\n const n3 = i3.get(e37.startNodeId), o4 = i3.get(e37.endNodeId), s3 = r3[e37.connectionName] ?? \"black\", a4 = n3 \u0026\u0026 u2.has(n3.capacityMeshNodeId), c4 = o4 \u0026\u0026 u2.has(o4.capacityMeshNodeId), l4 = (t3 + t3 / 50) % 5;\n let h3 = 0, p3 = 0, m2 = 0, g2 = 0;\n if (a4 \u0026\u0026 n3) {\n const t4 = 0.02 * Math.min(n3.width, n3.height);\n h3 = t4 * l4, p3 = t4 * l4, d2.points.push({ x: n3.center.x + h3, y: n3.center.y + p3, color: s3, label: `Start: ${e37.connectionName}\n(${e37.startNodeId})` }), d2.lines.push({ points: [{ x: n3.center.x, y: n3.center.y }, { x: n3.center.x + h3, y: n3.center.y + p3 }], strokeColor: \"gray\", strokeDash: \"2 2\" });\n }\n if (c4 \u0026\u0026 o4) {\n const t4 = 0.02 * Math.min(o4.width, o4.height);\n m2 = t4 * l4, g2 = t4 * l4, d2.points.push({ x: o4.center.x + m2, y: o4.center.y + g2, color: s3, label: `End: ${e37.connectionName}\n(${e37.endNodeId})` }), d2.lines.push({ points: [{ x: o4.center.x, y: o4.center.y }, { x: o4.center.x + m2, y: o4.center.y + g2 }], strokeColor: \"gray\", strokeDash: \"2 2\" });\n }\n a4 \u0026\u0026 c4 \u0026\u0026 n3 \u0026\u0026 o4 \u0026\u0026 d2.lines.push({ points: [{ x: n3.center.x + h3, y: n3.center.y + p3 }, { x: o4.center.x + m2, y: o4.center.y + g2 }], strokeColor: s3, strokeDash: \"5 5\" });\n }), o3 \u0026\u0026 o3.forEach((e37, t3) =\u003e {\n if (e37.path \u0026\u0026 e37.path.length \u003e 0) {\n const n3 = r3[e37.connectionName] ?? \"gray\", o4 = { x: (t3 + t3 / 50) % 5 * 0.03, y: (t3 + t3 / 50) % 5 * 0.03 };\n d2.lines.push({ points: e37.path.map(({ center: { x: e38, y: t4 } }) =\u003e ({ x: e38 + o4.x, y: t4 + o4.y })), strokeColor: Ao(n3, 0.2) });\n }\n }), d2;\n}\nvar vj = class extends ni {\n getSolverName() {\n return \"CapacityPathingSingleSectionSolver\";\n }\n GREEDY_MULTIPLIER = 1.5;\n sectionNodes;\n sectionEdges;\n sectionConnectionTerminals;\n nodeMap;\n nodeEdgeMap;\n colorMap;\n usedNodeCapacityMap;\n totalNodeCapacityMap;\n centerNodeId;\n currentSectionScore = 0;\n MAX_CANDIDATES_IN_MEMORY = 1e4;\n currentConnectionIndex = 0;\n candidates = null;\n visitedNodes = null;\n queuedNodes = null;\n activeCandidateStraightLineDistance;\n debug_lastNodeCostMap = new Map;\n maxCapacityFactor = 1;\n constructor(e36) {\n super(), this.MAX_ITERATIONS = 1e4, this.centerNodeId = e36.centerNodeId, this.sectionNodes = e36.sectionNodes, this.sectionEdges = e36.sectionEdges, this.sectionConnectionTerminals = e36.sectionConnectionTerminals.map((e37) =\u003e ({ ...e37, path: undefined })), this.nodeMap = e36.nodeMap ?? new Map(this.sectionNodes.map((e37) =\u003e [e37.capacityMeshNodeId, e37])), this.nodeEdgeMap = e36.nodeEdgeMap ?? oi(this.sectionEdges), this.colorMap = e36.colorMap ?? {}, this.usedNodeCapacityMap = new Map(this.sectionNodes.map((e37) =\u003e [e37.capacityMeshNodeId, 0])), this.totalNodeCapacityMap = new Map(this.sectionNodes.map((e37) =\u003e [e37.capacityMeshNodeId, this.getTotalCapacity(e37)]));\n const t2 = new Set(this.sectionNodes.map((e37) =\u003e e37.capacityMeshNodeId));\n this.currentSectionScore = bj({ totalNodeCapacityMap: this.totalNodeCapacityMap, usedNodeCapacityMap: this.usedNodeCapacityMap, nodeMap: this.nodeMap, sectionNodeIds: t2 }), e36.hyperParameters?.SHUFFLE_SEED \u0026\u0026 (this.sectionConnectionTerminals = Sr(this.sectionConnectionTerminals, e36.hyperParameters?.SHUFFLE_SEED));\n }\n getTotalCapacity(e36) {\n return Bz(e36, this.maxCapacityFactor);\n }\n getNodeCapacityPenalty(e36) {\n if (!this.nodeMap.has(e36.capacityMeshNodeId))\n return 1 / 0;\n const t2 = this.getTotalCapacity(e36) - (this.usedNodeCapacityMap.get(e36.capacityMeshNodeId) ?? 0) - 1;\n if (t2 \u003e 0)\n return 0;\n let n2 = 1;\n return e36.availableZ.length === 1 \u0026\u0026 (n2 = 10), (0.05 + t2 ** 2 * 4) * n2;\n }\n getDistanceBetweenNodes(e36, t2) {\n const n2 = e36.center.x - t2.center.x, o3 = e36.center.y - t2.center.y;\n return Math.sqrt(n2 ** 2 + o3 ** 2);\n }\n computeG(e36, t2, n2) {\n return e36.g + this.getDistanceBetweenNodes(e36.node, t2) + this.getNodeCapacityPenalty(t2);\n }\n computeH(e36, t2, n2) {\n return this.getDistanceBetweenNodes(t2, n2) + this.getNodeCapacityPenalty(t2);\n }\n getBacktrackedPath(e36) {\n const t2 = [];\n let n2 = e36;\n for (;n2; ) {\n if (t2.push(n2.node), !this.nodeMap.has(n2.node.capacityMeshNodeId)) {\n console.warn(\"Backtracked path went outside section bounds\");\n break;\n }\n n2 = n2.prevCandidate;\n }\n return t2.reverse();\n }\n getNeighboringNodes(e36) {\n return this.nodeMap.has(e36.capacityMeshNodeId) ? this.nodeEdgeMap.get(e36.capacityMeshNodeId)?.flatMap((t2) =\u003e t2.nodeIds.filter((t3) =\u003e t3 !== e36.capacityMeshNodeId)).map((e37) =\u003e this.nodeMap.get(e37)).filter(Boolean) ?? [] : [];\n }\n isConnectedToEndGoal(e36, t2) {\n return !(!this.nodeMap.has(e36.capacityMeshNodeId) || !this.nodeMap.has(t2.capacityMeshNodeId)) \u0026\u0026 (this.nodeEdgeMap.get(e36.capacityMeshNodeId) ?? []).some((e37) =\u003e e37.nodeIds.includes(t2.capacityMeshNodeId));\n }\n doesNodeHaveCapacityForTrace(e36, t2) {\n return true;\n }\n reduceCapacityAlongPath(e36) {\n for (const t2 of e36)\n if (this.usedNodeCapacityMap.has(t2.capacityMeshNodeId)) {\n const e37 = t2.capacityMeshNodeId, n2 = this.nodeMap.get(e37);\n if (!n2) {\n console.warn(`Node ${e37} from path not found in section's nodeMap during score update.`);\n continue;\n }\n const o3 = this.totalNodeCapacityMap.get(e37), i3 = this.usedNodeCapacityMap.get(e37) ?? 0, r3 = yj(i3, o3, n2);\n this.currentSectionScore -= r3;\n const s2 = i3 + 1;\n this.usedNodeCapacityMap.set(e37, s2);\n const a3 = yj(s2, o3, n2);\n this.currentSectionScore += a3;\n }\n }\n getSolvedSectionScore() {\n return this.currentSectionScore;\n }\n _step() {\n const e36 = this.sectionConnectionTerminals[this.currentConnectionIndex];\n if (!e36)\n return void (this.solved = true);\n const t2 = this.nodeMap.get(e36.startNodeId), n2 = this.nodeMap.get(e36.endNodeId);\n if (!t2 || !n2)\n return console.error(`Start or end node not found in section for connection ${e36.connectionName}`), this.currentConnectionIndex++, this.candidates = null, void (this.visitedNodes = null);\n this.candidates || this._setupAStar(t2, n2);\n const o3 = this.candidates;\n if (o3.length === 0)\n return void this._handleCandidatesExhausted(e36);\n o3.sort((e37, t3) =\u003e e37.f - t3.f);\n const i3 = o3.shift();\n if (o3.length \u003e this.MAX_CANDIDATES_IN_MEMORY \u0026\u0026 o3.splice(this.MAX_CANDIDATES_IN_MEMORY, o3.length - this.MAX_CANDIDATES_IN_MEMORY), this.visitedNodes.add(i3.node.capacityMeshNodeId), i3.node.capacityMeshNodeId === n2.capacityMeshNodeId)\n return void this._handleGoalReached(i3, e36, n2);\n const r3 = this.getNeighboringNodes(i3.node);\n for (const t3 of r3) {\n if (this.queuedNodes?.has(t3.capacityMeshNodeId))\n continue;\n if (!this.doesNodeHaveCapacityForTrace(t3, i3.node))\n continue;\n if (t3._containsObstacle) {\n const n3 = t3.capacityMeshNodeId === e36.startNodeId, o4 = t3.capacityMeshNodeId === e36.endNodeId;\n if (!n3 \u0026\u0026 !o4)\n continue;\n }\n const r4 = this.computeG(i3, t3, n2), s2 = this.computeH(i3, t3, n2), a3 = r4 + s2 * this.GREEDY_MULTIPLIER;\n this.debug_lastNodeCostMap.set(t3.capacityMeshNodeId, { f: a3, g: r4, h: s2 });\n const c3 = { prevCandidate: i3, node: t3, f: a3, g: r4, h: s2 };\n this.queuedNodes?.add(t3.capacityMeshNodeId), o3.push(c3);\n }\n }\n computeProgress() {\n const e36 = this.sectionConnectionTerminals.length;\n if (e36 === 0)\n return 1;\n let t2 = this.currentConnectionIndex / e36;\n if (this.currentConnectionIndex \u003c e36 \u0026\u0026 this.candidates \u0026\u0026 this.candidates.length \u003e 0 \u0026\u0026 this.activeCandidateStraightLineDistance \u0026\u0026 this.activeCandidateStraightLineDistance \u003e 0) {\n const n2 = this.candidates.reduce((e37, t3) =\u003e t3.f \u003c e37.f ? t3 : e37);\n t2 += Math.max(0, Math.min(1, 1 - n2.h / this.activeCandidateStraightLineDistance)) / e36;\n } else\n this.solved \u0026\u0026 (t2 = 1);\n return Math.min(1, t2);\n }\n _setupAStar(e36, t2) {\n this.candidates = [{ prevCandidate: null, node: e36, f: 0, g: 0, h: 0 }], this.visitedNodes = new Set([e36.capacityMeshNodeId]), this.debug_lastNodeCostMap = new Map, this.activeCandidateStraightLineDistance = me(e36.center, t2.center);\n const n2 = this.computeH(null, e36, t2);\n this.candidates[0].h = n2, this.candidates[0].f = n2 * this.GREEDY_MULTIPLIER, this.debug_lastNodeCostMap.set(e36.capacityMeshNodeId, { f: this.candidates[0].f, g: 0, h: n2 }), this.queuedNodes = new Set([e36.capacityMeshNodeId]);\n }\n _handleCandidatesExhausted(e36) {\n console.error(`Ran out of candidates for section connection ${e36.connectionName}`), this.currentConnectionIndex++, this.candidates = null, this.visitedNodes = null, this.queuedNodes = null;\n }\n _handleGoalReached(e36, t2, n2) {\n const o3 = this.getBacktrackedPath(e36);\n t2.path = o3, this.reduceCapacityAlongPath(o3), this.currentConnectionIndex++, this.candidates = null, this.visitedNodes = null, this.queuedNodes = null;\n }\n visualize() {\n const e36 = this.sectionConnectionTerminals.filter((e37) =\u003e e37.path \u0026\u0026 e37.path.length \u003e 0).map((e37) =\u003e ({ connectionName: e37.connectionName, path: e37.path })), t2 = xj({ sectionNodes: this.sectionNodes, sectionEdges: this.sectionEdges, sectionConnectionTerminals: this.sectionConnectionTerminals, completedPaths: e36, nodeMap: this.nodeMap, colorMap: this.colorMap, centerNodeId: null, title: `Section Pathing: Conn ${this.currentConnectionIndex + 1}/${this.sectionConnectionTerminals.length} (${this.sectionNodes.length} nodes)`, nodeOpacity: 0.1 });\n for (const e37 of this.sectionNodes) {\n const n2 = t2.rects.findIndex((t3) =\u003e t3.label?.includes(e37.capacityMeshNodeId));\n if (n2 !== -1) {\n const o3 = this.debug_lastNodeCostMap.get(e37.capacityMeshNodeId), i3 = this.usedNodeCapacityMap.get(e37.capacityMeshNodeId) ?? 0, r3 = this.getTotalCapacity(e37), s2 = `${i3.toFixed(1)}/${r3.toFixed(1)}`, a3 = o3 ? `f:${o3.f.toFixed(1)} g:${o3.g.toFixed(1)} h:${o3.h.toFixed(1)}` : \"cost:?\";\n t2.rects[n2].label = [e37.capacityMeshNodeId, `Cap: ${s2}`, a3, `Z: ${e37.availableZ.join(\",\")}`].join(`\n`), i3 \u003e r3 \u0026\u0026 (t2.rects[n2].stroke = Ao(\"red\", 0.7));\n }\n }\n if (this.candidates \u0026\u0026 this.candidates.length \u003e 0) {\n const e37 = this.candidates.slice().sort((e38, t3) =\u003e e38.f - t3.f).slice(0, 5), n2 = this.sectionConnectionTerminals[this.currentConnectionIndex], o3 = n2?.connectionName ?? \"unknown\", i3 = this.colorMap[o3] ?? \"purple\";\n e37.forEach((e38, n3) =\u003e {\n const o4 = 0.8 * (1 - n3 / 5), r3 = this.getBacktrackedPath(e38);\n r3.length \u003e 0 \u0026\u0026 t2.lines.push({ points: r3.map(({ center: { x: e39, y: t3 } }) =\u003e ({ x: e39, y: t3 })), strokeColor: Ao(i3, 1 - o4), strokeWidth: 0.05 });\n });\n }\n return t2;\n }\n};\nvar Ij = (e36) =\u003e Array.from({ length: e36 }, (e37, t2) =\u003e t2);\nvar Sj = class extends wa {\n getSolverName() {\n return \"HyperCapacityPathingSingleSectionSolver\";\n }\n constructorParams;\n constructor(e36) {\n super(), this.MAX_ITERATIONS = 1e5, this.constructorParams = e36;\n }\n computeG(e36) {\n return -e36.getSolvedSectionScore();\n }\n computeH(e36) {\n return 0;\n }\n getCombinationDefs() {\n const e36 = this.constructorParams.sectionConnectionTerminals.length;\n return e36 === 2 ? [[\"orderings2_for2\"]] : e36 === 3 ? [[\"orderings6_for3\"]] : e36 === 4 ? [[\"orderings24_for4\"]] : [[\"orderings30\"]];\n }\n getFailureMessage() {\n return `All CapacityPathingSingleSection solvers failed for \"${this.centerNodeId}\"`;\n }\n getHyperParameterDefs() {\n return [{ name: \"orderings2_for2\", possibleValues: Ij(2).map((e36) =\u003e ({ SHUFFLE_SEED: e36 })) }, { name: \"orderings6_for3\", possibleValues: Ij(6).map((e36) =\u003e ({ SHUFFLE_SEED: e36 })) }, { name: \"orderings24_for4\", possibleValues: Ij(24).map((e36) =\u003e ({ SHUFFLE_SEED: e36 })) }, { name: \"orderings30\", possibleValues: Ij(30).map((e36) =\u003e ({ SHUFFLE_SEED: e36 })) }];\n }\n generateSolver(e36) {\n return new vj({ ...this.constructorParams, hyperParameters: { ...this.constructorParams.hyperParameters, ...e36 } });\n }\n onSolve({ solver: e36 }) {\n this.winningSolver = e36;\n }\n get centerNodeId() {\n return this.constructorParams.centerNodeId;\n }\n get sectionNodes() {\n return this.constructorParams.sectionNodes;\n }\n get sectionConnectionTerminals() {\n return this.winningSolver?.sectionConnectionTerminals;\n }\n};\nvar Pj = (e36) =\u003e Math.floor(10 * e36) / 10;\nvar Mj = class extends Sj {\n cacheHit = false;\n cacheProvider;\n hasAttemptedToUseCache = false;\n sectionNodeIdSet;\n cachedSectionConnectionTerminals = null;\n sectionScore = 0;\n constructor(e36) {\n e36.nodeMap = e36.nodeMap ?? new Map(e36.sectionNodes.map((e37) =\u003e [e37.capacityMeshNodeId, e37])), super(e36), this.sectionNodeIdSet = new Set(e36.sectionNodes.map((e37) =\u003e e37.capacityMeshNodeId)), this.cacheProvider = e36.cacheProvider === undefined ? no() : e36.cacheProvider;\n }\n _step() {\n !this.hasAttemptedToUseCache \u0026\u0026 this.cacheProvider \u0026\u0026 this.attemptToUseCacheSync() || (super._step(), (this.solved || this.failed) \u0026\u0026 this.cacheProvider \u0026\u0026 this.saveToCacheSync());\n }\n _computeBfsOrderingOfNodesInSection() {\n const e36 = new Set(this.constructorParams.centerNodeId), t2 = [], n2 = [{ ancestorCapacitySum: 0, capacity: 0, g: 0, capacityMeshNodeId: this.constructorParams.centerNodeId }];\n for (;n2.length \u003e 0; ) {\n n2.sort((e37, t3) =\u003e t3.g - e37.g);\n const o3 = n2.pop();\n if (!o3)\n break;\n t2.push(o3.capacityMeshNodeId);\n const i3 = this.constructorParams.nodeEdgeMap.get(o3.capacityMeshNodeId).flatMap((e37) =\u003e e37.nodeIds).filter((t3) =\u003e !e36.has(t3)).filter((e37) =\u003e this.sectionNodeIdSet.has(e37));\n for (const t3 of i3) {\n e36.add(t3);\n const i4 = this.constructorParams.nodeMap.get(t3), r3 = Bz(i4);\n n2.push({ ancestorCapacitySum: o3.g, capacity: r3, g: o3.g + r3, capacityMeshNodeId: t3 });\n }\n }\n return t2;\n }\n computeCacheKeyAndTransform() {\n const e36 = this._computeBfsOrderingOfNodesInSection(), t2 = new Map, n2 = new Map;\n e36.forEach((e37, o4) =\u003e {\n const i4 = `node${o4}`;\n t2.set(e37, i4), n2.set(i4, e37);\n });\n const o3 = {};\n for (const n3 of e36) {\n const e37 = t2.get(n3), i4 = this.constructorParams.nodeMap.get(n3), r4 = Bz(i4);\n o3[e37] = Pj(r4).toFixed(1);\n }\n const i3 = new Set, r3 = [];\n for (const n3 of e36) {\n const e37 = t2.get(n3), o4 = this.constructorParams.nodeEdgeMap.get(n3) ?? [];\n for (const s3 of o4) {\n const o5 = s3.nodeIds.find((e38) =\u003e e38 !== n3);\n if (this.sectionNodeIdSet.has(o5)) {\n const n4 = [e37, t2.get(o5)].sort(), s4 = `${n4[0]}-${n4[1]}`;\n i3.has(s4) || (r3.push(n4), i3.add(s4));\n }\n }\n }\n r3.sort((e37, t3) =\u003e e37[0] !== t3[0] ? e37[0].localeCompare(t3[0]) : e37[1].localeCompare(t3[1]));\n const s2 = {}, a3 = new Map, c3 = new Map;\n for (const e37 of this.constructorParams.sectionConnectionTerminals) {\n const n3 = t2.get(e37.startNodeId), o4 = t2.get(e37.endNodeId), [i4, r4] = [n3, o4].sort(), l4 = `${i4}-\u003e${r4}`, h3 = c3.get(l4) ?? 0;\n c3.set(l4, h3 + 1);\n const d2 = `${i4}-\u003e${r4}::${h3}`;\n s2[d2] = { start: i4, end: r4 }, a3.set(d2, e37.connectionName);\n }\n const l3 = `capacitypathing:${import_object_hash2.default({ node_capacity_map: o3, node_edge_map: r3, terminals: s2 })}`, h2 = { cacheSpaceToRealConnectionId: a3, cacheSpaceToRealNodeId: n2 };\n return this.cacheKey = l3, this.cacheToSolveSpaceTransform = h2, { cacheKey: l3, cacheToSolveSpaceTransform: h2 };\n }\n applyCachedSolution(e36) {\n if (!this.cacheToSolveSpaceTransform)\n return console.error(\"Cache transform not available, cannot apply cached solution.\"), void (this.failed = true);\n if (!e36.success)\n return this.failed = true, void (this.cacheHit = true);\n this.cachedSectionConnectionTerminals = [];\n const { cacheSpaceToRealNodeId: t2, cacheSpaceToRealConnectionId: n2 } = this.cacheToSolveSpaceTransform;\n for (const [o3, i3] of Object.entries(e36.solutionPaths)) {\n const e37 = n2.get(o3);\n if (!e37) {\n console.warn(`Could not find real connection name for ${o3}`);\n continue;\n }\n const r3 = this.constructorParams.sectionConnectionTerminals.find((t3) =\u003e t3.connectionName === e37);\n if (!r3) {\n console.warn(`Could not find original terminal for connection name ${e37}`);\n continue;\n }\n const s2 = i3.map((n3) =\u003e {\n const o4 = t2.get(n3);\n if (!o4)\n throw new Error(`Could not map cache node ID ${n3} to real node ID for connection ${e37}`);\n const i4 = this.constructorParams.nodeMap.get(o4);\n if (!i4)\n throw new Error(`Could not find node with ID ${o4} in nodeMap for connection ${e37}`);\n return i4;\n });\n this.cachedSectionConnectionTerminals.push({ ...r3, path: s2 });\n }\n this.sectionScore = e36.sectionScore, this.solved = true, this.cacheHit = true;\n }\n attemptToUseCacheSync() {\n if (this.hasAttemptedToUseCache = true, !this.cacheProvider?.isSyncCache)\n return console.log(\"Cache provider is not synchronous, skipping sync cache check.\"), false;\n if (this.cacheKey || this.computeCacheKeyAndTransform(), !this.cacheKey)\n return console.error(\"Failed to compute cache key.\"), false;\n try {\n const e36 = this.cacheProvider.getCachedSolutionSync(this.cacheKey);\n if (e36)\n return this.applyCachedSolution(e36), true;\n } catch (e36) {\n console.error(\"Error attempting to use cache:\", e36);\n }\n return false;\n }\n saveToCacheSync() {\n if (!this.cacheKey)\n return void console.error(\"Cannot save to cache without cache key.\");\n if (!this.cacheToSolveSpaceTransform)\n return void console.error(\"Cache transform not available, cannot save solution to cache.\");\n let e36;\n if (this.failed)\n e36 = { success: false };\n else {\n if (!this.solved)\n return;\n {\n const t2 = {}, { cacheSpaceToRealNodeId: n2, cacheSpaceToRealConnectionId: o3 } = this.cacheToSolveSpaceTransform, i3 = new Map;\n for (const [e37, t3] of n2)\n i3.set(t3, e37);\n const r3 = new Map;\n for (const [e37, t3] of o3)\n r3.set(t3, e37);\n const s2 = [];\n if (super.sectionConnectionTerminals) {\n for (const e37 of super.sectionConnectionTerminals)\n if (e37.path \u0026\u0026 e37.path.length \u003e 0) {\n const t3 = e37.path.map((e38) =\u003e e38.capacityMeshNodeId);\n s2.push([e37.connectionName, t3]);\n }\n }\n for (const [e37, n3] of s2) {\n const o4 = r3.get(e37);\n if (!o4) {\n console.warn(`Could not find cache space connection ID for ${e37} when saving to cache.`);\n continue;\n }\n const s3 = n3.map((t3) =\u003e {\n const n4 = i3.get(t3);\n if (!n4)\n throw new Error(`Could not map real node ID ${t3} to cache node ID for connection ${e37} when saving to cache.`);\n return n4;\n });\n t2[o4] = s3;\n }\n e36 = { success: true, sectionScore: this.sectionScore, solutionPaths: t2 };\n }\n }\n try {\n this.cacheProvider?.setCachedSolutionSync(this.cacheKey, e36);\n } catch (e37) {\n console.error(\"Error saving solution to cache:\", e37);\n }\n }\n get sectionConnectionTerminals() {\n return this.cacheHit \u0026\u0026 this.solved \u0026\u0026 this.cachedSectionConnectionTerminals ? (console.log(\"returning the cached section connection terminals\"), this.cachedSectionConnectionTerminals) : super.sectionConnectionTerminals;\n }\n visualize() {\n if (!this.cacheHit)\n return super.visualize();\n return xj({ sectionNodes: this.constructorParams.sectionNodes, sectionEdges: this.constructorParams.sectionEdges, sectionConnectionTerminals: this.cachedSectionConnectionTerminals, completedPaths: this.cachedSectionConnectionTerminals.map((e36) =\u003e ({ connectionName: e36.connectionName, path: e36.path })), nodeMap: this.constructorParams.nodeMap, colorMap: this.constructorParams.colorMap, title: \"CachedHyperCapacityPathingSingleSectionSolver\" });\n }\n};\nvar wj = class extends ni {\n getSolverName() {\n return \"CapacityPathingMultiSectionSolver\";\n }\n simpleRouteJson;\n nodes;\n edges;\n nodeEdgeMap;\n connectionsWithNodes = [];\n colorMap;\n initialSolver;\n cacheProvider;\n stage = \"initialization\";\n nodeMap = new Map;\n allNodeIdsSet;\n usedNodeCapacityMap = new Map;\n totalNodeCapacityMap = new Map;\n nodeCapacityPercentMap = new Map;\n nodeOptimizationAttemptCountMap = new Map;\n currentSection = null;\n sectionSolver = null;\n currentScheduleIndex = 0;\n stats;\n OPTIMIZATION_SCHEDULE = [{ MAX_ATTEMPTS_PER_NODE: 1, MAX_EXPANSION_DEGREES: 3, MINIMUM_PROBABILITY_OF_FAILURE_TO_OPTIMIZE: 0.05 }, { MAX_ATTEMPTS_PER_NODE: 2, MAX_EXPANSION_DEGREES: 5, MINIMUM_PROBABILITY_OF_FAILURE_TO_OPTIMIZE: 0.2 }, { MAX_ATTEMPTS_PER_NODE: 3, MAX_EXPANSION_DEGREES: 7, MINIMUM_PROBABILITY_OF_FAILURE_TO_OPTIMIZE: 0.9 }];\n get currentSchedule() {\n return this.OPTIMIZATION_SCHEDULE[this.currentScheduleIndex] ?? null;\n }\n constructor(e36) {\n super(), this.stats = { successfulOptimizations: 0, failedOptimizations: 0, failedSectionSolvers: 0, startingScore: 0, scheduleScores: this.OPTIMIZATION_SCHEDULE.map(({ MAX_EXPANSION_DEGREES: e37 }) =\u003e ({ maxExpansionDegrees: e37, endingScore: 0, endingHighestNodePf: 0, sectionAttempts: 0 })), cacheHits: 0, cacheMisses: 0 }, this.MAX_ITERATIONS = e36.MAX_ITERATIONS ?? 1e7, this.cacheProvider = e36.cacheProvider, this.simpleRouteJson = e36.simpleRouteJson, this.nodes = e36.nodes, this.edges = e36.edges, this.nodeEdgeMap = oi(this.edges), this.colorMap = e36.colorMap ?? {}, this.nodeMap = new Map(this.nodes.map((e37) =\u003e [e37.capacityMeshNodeId, e37])), this.nodeEdgeMap = oi(this.edges), this.initialSolver = e36.initialPathingSolver || new mj({ simpleRouteJson: this.simpleRouteJson, nodes: this.nodes, edges: this.edges, colorMap: this.colorMap }), this.activeSubSolver = this.initialSolver;\n for (const e37 of this.nodes) {\n const t2 = this.initialSolver.getTotalCapacity(e37);\n this.totalNodeCapacityMap.set(e37.capacityMeshNodeId, t2);\n }\n this.allNodeIdsSet = new Set(this.nodes.map((e37) =\u003e e37.capacityMeshNodeId));\n }\n _stepInitialization() {\n if (this.initialSolver?.step(), this.initialSolver?.failed)\n return this.failed = true, void (this.error = this.initialSolver.error);\n if (this.initialSolver?.solved) {\n this.usedNodeCapacityMap = new Map(this.initialSolver.usedNodeCapacityMap);\n for (const e36 of this.nodes) {\n const t2 = this.totalNodeCapacityMap.get(e36.capacityMeshNodeId) ?? 0, n2 = this.usedNodeCapacityMap.get(e36.capacityMeshNodeId) ?? 0, o3 = t2 \u003e 0 ? n2 / t2 : 0;\n this.nodeCapacityPercentMap.set(e36.capacityMeshNodeId, o3), this.nodeOptimizationAttemptCountMap.set(e36.capacityMeshNodeId, 0);\n }\n this.connectionsWithNodes = this.initialSolver.connectionsWithNodes, this.stats.startingScore = bj({ totalNodeCapacityMap: this.totalNodeCapacityMap, usedNodeCapacityMap: this.usedNodeCapacityMap, nodeMap: this.nodeMap, sectionNodeIds: this.allNodeIdsSet }), this.stage = \"section-optimization\";\n }\n }\n _getNextNodeToOptimize() {\n let e36 = 0, t2 = 0, n2 = null;\n for (const o3 of this.nodes) {\n if (o3._containsTarget)\n continue;\n const i3 = this.nodeOptimizationAttemptCountMap.get(o3.capacityMeshNodeId), r3 = this.totalNodeCapacityMap.get(o3.capacityMeshNodeId), s2 = _j({ usedCapacity: this.usedNodeCapacityMap.get(o3.capacityMeshNodeId) ?? 0, totalCapacity: r3, layerCount: o3.availableZ.length }), a3 = s2 / (i3 + 1);\n i3 \u003c this.currentSchedule.MAX_ATTEMPTS_PER_NODE \u0026\u0026 a3 \u003e e36 \u0026\u0026 s2 \u003e this.currentSchedule.MINIMUM_PROBABILITY_OF_FAILURE_TO_OPTIMIZE \u0026\u0026 (e36 = a3, t2 = s2, n2 = o3.capacityMeshNodeId);\n }\n return n2;\n }\n getOverallScore() {\n let e36 = 0;\n for (const t2 of this.nodes) {\n if (t2._containsTarget)\n continue;\n const n2 = this.totalNodeCapacityMap.get(t2.capacityMeshNodeId), o3 = _j({ usedCapacity: this.usedNodeCapacityMap.get(t2.capacityMeshNodeId) ?? 0, totalCapacity: n2, layerCount: t2.availableZ.length });\n o3 \u003e e36 \u0026\u0026 (e36 = o3);\n }\n return { highestNodePf: e36, score: bj({ totalNodeCapacityMap: this.totalNodeCapacityMap, usedNodeCapacityMap: this.usedNodeCapacityMap, nodeMap: this.nodeMap, sectionNodeIds: this.allNodeIdsSet }) };\n }\n _stepSectionOptimization() {\n if (!this.sectionSolver) {\n const e36 = this._getNextNodeToOptimize();\n if (!e36) {\n const { highestNodePf: e37, score: t3 } = this.getOverallScore();\n return this.stats.scheduleScores[this.currentScheduleIndex].endingHighestNodePf = e37, this.stats.scheduleScores[this.currentScheduleIndex].endingScore = t3, this.currentScheduleIndex++, void (this.currentSchedule || (this.solved = true));\n }\n const t2 = ((e37) =\u003e {\n const { centerNodeId: t3, connectionsWithNodes: n2, nodeMap: o3, edges: i3, nodeEdgeMap: r3, expansionDegrees: s2 } = e37, a3 = new Set, c3 = [{ nodeId: t3, depth: 0 }];\n a3.add(t3);\n let l3 = 0;\n for (;l3 \u003c c3.length; ) {\n const { nodeId: e38, depth: t4 } = c3[l3++];\n if (t4 \u003e= s2)\n continue;\n const n3 = r3.get(e38)?.flatMap((t5) =\u003e t5.nodeIds.filter((t6) =\u003e t6 !== e38)) ?? [];\n for (const e39 of n3)\n a3.has(e39) || (a3.add(e39), c3.push({ nodeId: e39, depth: t4 + 1 }));\n }\n const h2 = Array.from(a3).map((e38) =\u003e o3.get(e38)), d2 = i3.filter((e38) =\u003e {\n const [t4, n3] = e38.nodeIds;\n return a3.has(t4) \u0026\u0026 a3.has(n3);\n }), u2 = [];\n for (const e38 of n2) {\n if (!e38.path)\n continue;\n let t4 = null, n3 = null;\n for (const n4 of e38.path)\n if (a3.has(n4.capacityMeshNodeId)) {\n t4 = n4.capacityMeshNodeId;\n break;\n }\n for (let t5 = e38.path.length - 1;t5 \u003e= 0; t5--) {\n const o4 = e38.path[t5];\n if (a3.has(o4.capacityMeshNodeId)) {\n n3 = o4.capacityMeshNodeId;\n break;\n }\n }\n t4 \u0026\u0026 n3 \u0026\u0026 u2.push({ connectionName: e38.connection.name, startNodeId: t4, endNodeId: n3 });\n }\n return { sectionConnectionTerminals: u2, sectionNodes: h2, sectionEdges: d2, centerNodeId: t3 };\n })({ centerNodeId: e36, connectionsWithNodes: this.connectionsWithNodes, nodeMap: this.nodeMap, edges: this.edges, expansionDegrees: this.currentSchedule.MAX_EXPANSION_DEGREES, nodeEdgeMap: this.nodeEdgeMap });\n this.stats.scheduleScores[this.currentScheduleIndex].sectionAttempts++, this.currentSection = t2, this.sectionSolver = new Mj({ sectionNodes: this.currentSection.sectionNodes, sectionEdges: this.currentSection.sectionEdges, sectionConnectionTerminals: this.currentSection.sectionConnectionTerminals, colorMap: this.colorMap, centerNodeId: this.currentSection.centerNodeId, nodeEdgeMap: this.nodeEdgeMap, hyperParameters: { EXPANSION_DEGREES: this.currentSchedule.MAX_EXPANSION_DEGREES }, cacheProvider: this.cacheProvider }), this.activeSubSolver = this.sectionSolver, this.nodeOptimizationAttemptCountMap.set(e36, (this.nodeOptimizationAttemptCountMap.get(e36) ?? 0) + 1);\n }\n if (this.sectionSolver.step(), (this.sectionSolver.failed || this.sectionSolver.solved) \u0026\u0026 (this.sectionSolver.cacheHit ? this.stats.cacheHits++ : this.stats.cacheMisses++), this.sectionSolver.failed)\n return console.warn(`Section solver failed for node ${this.currentSection.centerNodeId}. Error: ${this.sectionSolver.error}`), this.stats.failedSectionSolvers++, this.stats.failedOptimizations++, this.sectionSolver = null, void (this.activeSubSolver = null);\n if (this.sectionSolver.solved) {\n const e36 = this.sectionSolver.sectionConnectionTerminals, t2 = this.sectionSolver.sectionNodes, n2 = this.sectionSolver.centerNodeId;\n if (this.sectionSolver = null, this.activeSubSolver = null, !e36)\n return void console.warn(`Pathing sub-solver for section ${this.currentSection.centerNodeId} did not complete successfully. Discarding results.`);\n const o3 = new Set(t2.map((e37) =\u003e e37.capacityMeshNodeId)), i3 = bj({ totalNodeCapacityMap: this.totalNodeCapacityMap, usedNodeCapacityMap: this.usedNodeCapacityMap, nodeMap: this.nodeMap, sectionNodeIds: o3 }), r3 = new Map(this.usedNodeCapacityMap), s2 = e36;\n for (const e37 of s2) {\n const t3 = this.connectionsWithNodes.find((t4) =\u003e t4.connection.name === e37.connectionName);\n if (t3?.path) {\n for (const e38 of t3.path)\n if (o3.has(e38.capacityMeshNodeId)) {\n const t4 = r3.get(e38.capacityMeshNodeId) ?? 0;\n r3.set(e38.capacityMeshNodeId, Math.max(0, t4 - 1));\n }\n }\n }\n for (const e37 of s2)\n if (e37.path)\n for (const t3 of e37.path)\n o3.has(t3.capacityMeshNodeId) \u0026\u0026 r3.set(t3.capacityMeshNodeId, (r3.get(t3.capacityMeshNodeId) ?? 0) + 1);\n bj({ totalNodeCapacityMap: this.totalNodeCapacityMap, usedNodeCapacityMap: r3, nodeMap: this.nodeMap, sectionNodeIds: o3 }) \u003e i3 ? (this.stats.successfulOptimizations++, this._mergeSolvedSectionPaths({ centerNodeId: n2, sectionConnectionTerminals: e36 }), this._recalculateNodeCapacityUsage()) : this.stats.failedOptimizations++;\n }\n }\n _mergeSolvedSectionPaths({ centerNodeId: e36, sectionConnectionTerminals: t2 }) {\n for (const n2 of t2) {\n if (!n2.path) {\n console.warn(`No path found for connection ${n2.connectionName} in section ${e36}`);\n continue;\n }\n const t3 = this.connectionsWithNodes.find((e37) =\u003e e37.connection.name === n2.connectionName);\n if (!t3 || !t3.path) {\n console.warn(`Original connection or path not found for ${n2.connectionName} while merging section ${e36}`);\n continue;\n }\n const o3 = t3.path, i3 = n2.path, r3 = o3.findIndex((e37) =\u003e e37.capacityMeshNodeId === n2.startNodeId), s2 = o3.findIndex((e37) =\u003e e37.capacityMeshNodeId === n2.endNodeId);\n if (r3 === -1 || s2 === -1) {\n console.warn(`Could not find start/end nodes (${n2.startNodeId}/${n2.endNodeId}) in original path for ${n2.connectionName}`);\n continue;\n }\n const [a3, c3] = r3 \u003c= s2 ? [r3, s2] : [s2, r3], l3 = o3.slice(0, a3), h2 = o3.slice(c3 + 1);\n let d2 = i3;\n if (i3.length \u003e 0 \u0026\u0026 o3[a3] \u0026\u0026 i3[0].capacityMeshNodeId !== o3[a3].capacityMeshNodeId) {\n if (i3[i3.length - 1].capacityMeshNodeId !== o3[a3].capacityMeshNodeId) {\n console.warn(`New section path for ${n2.connectionName} doesn't align with original path boundaries. Skipping merge for this connection.`);\n continue;\n }\n d2 = [...i3].reverse();\n }\n t3.path = [...l3, ...d2, ...h2];\n }\n }\n _recalculateNodeCapacityUsage() {\n this.usedNodeCapacityMap.clear();\n for (const e36 of this.connectionsWithNodes)\n if (e36.path)\n for (const t2 of e36.path)\n this.usedNodeCapacityMap.set(t2.capacityMeshNodeId, (this.usedNodeCapacityMap.get(t2.capacityMeshNodeId) ?? 0) + 1);\n for (const e36 of this.nodes) {\n const t2 = this.totalNodeCapacityMap.get(e36.capacityMeshNodeId) ?? 0, n2 = this.usedNodeCapacityMap.get(e36.capacityMeshNodeId) ?? 0, o3 = t2 \u003e 0 ? n2 / t2 : 0;\n this.nodeCapacityPercentMap.set(e36.capacityMeshNodeId, o3);\n }\n }\n getCapacityPaths() {\n const e36 = [];\n for (const t2 of this.connectionsWithNodes) {\n const n2 = t2.path;\n n2 \u0026\u0026 e36.push({ capacityPathId: t2.connection.name, connectionName: t2.connection.name, nodeIds: n2.map((e37) =\u003e e37.capacityMeshNodeId) });\n }\n return e36;\n }\n _step() {\n this.iterations \u003e= this.MAX_ITERATIONS - 1 ? this.solved = true : this.stage === \"initialization\" ? this._stepInitialization() : this.stage === \"section-optimization\" \u0026\u0026 this._stepSectionOptimization();\n }\n visualize() {\n const e36 = this.connectionsWithNodes.filter((e37) =\u003e e37.path \u0026\u0026 e37.path.length \u003e 0).map((e37) =\u003e ({ connectionName: e37.connection.name, path: e37.path }));\n return xj({ nodeMap: this.nodeMap, sectionConnectionTerminals: this.connectionsWithNodes.map((e37) =\u003e ({ connectionName: e37.connection.name, startNodeId: e37.path?.[0]?.capacityMeshNodeId, endNodeId: e37.path?.[e37.path.length - 1]?.capacityMeshNodeId })), completedPaths: e36, sectionNodes: this.nodes, sectionEdges: this.edges, colorMap: this.colorMap, totalCapacityMap: this.totalNodeCapacityMap, usedNodeCapacityMap: this.usedNodeCapacityMap, nodeOpacity: 0.05, title: \"Capacity Pathing Multi-Section Solver (Solved)\" });\n }\n};\nvar Nj = class extends ni {\n getSolverName() {\n return \"DeadEndSolver\";\n }\n removedNodeIds;\n targetNodeIds;\n leaves;\n leavesIndex;\n adjacencyList;\n nodeMap;\n nodes;\n edges;\n constructor({ nodes: e36, edges: t2 }) {\n super(), this.MAX_ITERATIONS = e36.length, this.nodes = e36, this.edges = t2, this.removedNodeIds = new Set, this.targetNodeIds = new Set(e36.filter((e37) =\u003e e37._containsTarget).map((e37) =\u003e e37.capacityMeshNodeId)), this.adjacencyList = new Map(e36.map(({ capacityMeshNodeId: e37 }) =\u003e [e37, new Set]));\n for (const { nodeIds: [e37, n2] } of t2)\n this.adjacencyList.get(e37).add(n2), this.adjacencyList.get(n2).add(e37);\n this.leavesIndex = 0, this.leaves = [...this.adjacencyList.entries()].filter(([e37, t3]) =\u003e t3.size === 1).filter(([e37, t3]) =\u003e !this.targetNodeIds.has(e37)).map(([e37, t3]) =\u003e e37);\n }\n _step() {\n if (this.leavesIndex === this.leaves.length)\n return void (this.solved = true);\n const e36 = this.leaves[this.leavesIndex], t2 = this.adjacencyList.get(e36);\n if (!t2 || t2.size === 0)\n return this.removedNodeIds.add(e36), this.adjacencyList.delete(e36), this.leavesIndex += 1, void (this.leavesIndex === this.leaves.length \u0026\u0026 (this.solved = true));\n const [n2] = t2, o3 = n2 ? this.adjacencyList.get(n2) : undefined;\n if (!n2 || !o3)\n return this.removedNodeIds.add(e36), this.adjacencyList.delete(e36), this.leavesIndex += 1, void (this.leavesIndex === this.leaves.length \u0026\u0026 (this.solved = true));\n o3.delete(e36), this.removedNodeIds.add(e36), this.adjacencyList.delete(e36), o3.size !== 1 || this.targetNodeIds.has(n2) || this.leaves.push(n2), this.leavesIndex += 1, this.leavesIndex === this.leaves.length \u0026\u0026 (this.solved = true);\n }\n visualize() {\n if (!this.nodeMap) {\n this.nodeMap = new Map;\n for (const e37 of this.nodes)\n this.nodeMap.set(e37.capacityMeshNodeId, e37);\n }\n const e36 = new Map;\n for (const t3 of this.edges)\n for (const n2 of t3.nodeIds)\n e36.set(n2, 1 + (e36.get(n2) ?? 0));\n const t2 = { lines: [], points: [], rects: this.nodes.map((t3) =\u003e {\n const n2 = Math.min(...t3.availableZ);\n return { width: Math.max(t3.width - 2, 0.8 * t3.width), height: Math.max(t3.height - 2, 0.8 * t3.height), center: { x: t3.center.x + n2 * t3.width * 0.05, y: t3.center.y - n2 * t3.width * 0.05 }, fill: t3._containsObstacle ? \"rgba(255,0,0,0.1)\" : { \"0,1\": \"rgba(0,0,0,0.1)\", 0: \"rgba(0,200,200, 0.1)\", 1: \"rgba(0,0,200, 0.1)\" }[t3.availableZ.join(\",\")] ?? \"rgba(0,200,200,0.1)\", label: [t3.capacityMeshNodeId, `availableZ: ${t3.availableZ.join(\",\")}`, `target? ${t3._containsTarget ?? false}`, `obs? ${t3._containsObstacle ?? false}`, `conn: ${e36.get(t3.capacityMeshNodeId) ?? 0}`].join(`\n`), layer: `z${t3.availableZ.join(\",\")}` };\n }), circles: [] };\n for (const e37 of this.edges) {\n const n2 = this.nodeMap.get(e37.nodeIds[0]), o3 = this.nodeMap.get(e37.nodeIds[1]);\n if (n2?.center \u0026\u0026 o3?.center) {\n const i3 = Math.min(...n2.availableZ), r3 = Math.min(...o3.availableZ), s2 = { x: n2.center.x + i3 * n2.width * 0.05, y: n2.center.y - i3 * n2.width * 0.05 }, a3 = { x: o3.center.x + r3 * o3.width * 0.05, y: o3.center.y - r3 * o3.width * 0.05 }, c3 = Array.from(new Set([...n2.availableZ, ...o3.availableZ])).sort();\n t2.lines.push({ layer: `z${c3.join(\",\")}`, points: [s2, a3], strokeDash: n2.availableZ.join(\",\") === o3.availableZ.join(\",\") ? undefined : \"10 5\", strokeColor: e37.nodeIds.some((e38) =\u003e this.removedNodeIds.has(e38)) ? Ao(\"black\", 0.9) : undefined });\n }\n }\n return t2;\n }\n};\nvar Rj = class extends IB {\n getSolverName() {\n return \"NoOffBoardMultipleHighDensityRouteStitchSolver\";\n }\n constructor(e36) {\n super(e36), this.unsolvedRoutes = [];\n const t2 = new Map;\n for (const n2 of e36.hdRoutes) {\n const e37 = t2.get(n2.connectionName) || [];\n e37.push(n2), t2.set(n2.connectionName, e37);\n }\n for (const [n2, o3] of t2.entries()) {\n const t3 = e36.connections.find((e37) =\u003e e37.name === n2);\n if (!t3)\n continue;\n const i3 = { ...t3.pointsToConnect[0], z: mo(Io(t3.pointsToConnect[0]), e36.layerCount) }, r3 = { ...t3.pointsToConnect[1], z: mo(Io(t3.pointsToConnect[1]), e36.layerCount) };\n this.unsolvedRoutes.push({ connectionName: n2, hdRoutes: o3, start: i3, end: r3 });\n }\n for (const n2 of e36.connections)\n t2.has(n2.name) || this.unsolvedRoutes.push({ connectionName: n2.name, hdRoutes: [], start: { ...n2.pointsToConnect[0], z: mo(Io(n2.pointsToConnect[0]), e36.layerCount) }, end: { ...n2.pointsToConnect[1], z: mo(Io(n2.pointsToConnect[1]), e36.layerCount) } });\n }\n};\nvar Tj = 0.005;\nvar Ej = class extends ni {\n getSolverName() {\n return \"SingleLayerNodeMergerSolver\";\n }\n nodeMap;\n currentBatchNodeIds;\n absorbedNodeIds;\n nextBatchNodeIds;\n batchHadModifications;\n hasComputedAdjacentNodeIds = false;\n newNodes;\n constructor(e36) {\n super(), this.nodeMap = new Map, this.MAX_ITERATIONS = 1e5;\n for (const t3 of e36)\n this.nodeMap.set(t3.capacityMeshNodeId, t3);\n this.newNodes = [], this.absorbedNodeIds = new Set;\n const t2 = [];\n for (const n2 of e36)\n n2.availableZ.length \u003e 1 ? (this.newNodes.push(n2), this.absorbedNodeIds.add(n2.capacityMeshNodeId)) : t2.push([n2, n2.width * n2.height]);\n t2.sort((e37, t3) =\u003e e37[1] - t3[1]);\n for (const [e37, n2] of t2) {\n const t3 = { ...e37, center: { ...e37.center } };\n this.nodeMap.set(e37.capacityMeshNodeId, t3);\n }\n this.currentBatchNodeIds = t2.map(([e37]) =\u003e e37.capacityMeshNodeId), this.nextBatchNodeIds = [], this.batchHadModifications = false;\n }\n computeAdjacentNodeIdsForFirstBatch(e36) {\n const t2 = Math.max(...e36.map((e37) =\u003e Math.max(...e37.availableZ))), n2 = [];\n for (let o3 = 0;o3 \u003c= t2; o3++)\n n2.push(new di(e36.filter((e37) =\u003e e37.availableZ[0] === o3)));\n for (const t3 of e36) {\n const e37 = [], o3 = n2[t3.availableZ[0]].getNodesInArea(t3.center.x, t3.center.y, 4 * t3.width, 4 * t3.height);\n for (const n3 of o3)\n n3._containsTarget \u0026\u0026 n3._targetConnectionName !== t3._targetConnectionName || t3._containsTarget \u0026\u0026 (!n3._containsTarget || n3._targetConnectionName !== t3._targetConnectionName) || n3.capacityMeshNodeId !== t3.capacityMeshNodeId \u0026\u0026 ri(t3, n3) \u0026\u0026 e37.push(n3);\n t3._adjacentNodeIds = e37.map((e38) =\u003e e38.capacityMeshNodeId);\n }\n }\n getAdjacentSameLayerUnprocessedNodes(e36) {\n return this.getAdjacentSameLayerUnprocessedNodes2(e36);\n }\n getAdjacentSameLayerUnprocessedNodes2(e36) {\n const t2 = [], n2 = Array.from(new Set((e36._adjacentNodeIds ?? []).map((e37) =\u003e this.nodeMap.get(e37)))).filter((t3) =\u003e t3 \u0026\u0026 t3.capacityMeshNodeId !== e36.capacityMeshNodeId);\n n2.sort((e37, t3) =\u003e e37.width * e37.height - t3.width * t3.height);\n for (const e37 of n2)\n this.absorbedNodeIds.has(e37.capacityMeshNodeId) || t2.push(e37);\n return t2;\n }\n _step() {\n this.hasComputedAdjacentNodeIds || (this.computeAdjacentNodeIdsForFirstBatch(this.currentBatchNodeIds.map((e37) =\u003e this.nodeMap.get(e37))), this.hasComputedAdjacentNodeIds = true);\n let e36 = this.currentBatchNodeIds.pop();\n for (;e36 \u0026\u0026 this.absorbedNodeIds.has(e36); )\n e36 = this.currentBatchNodeIds.pop();\n if (!e36)\n return this.batchHadModifications ? (this.currentBatchNodeIds = this.nextBatchNodeIds.sort((e37, t3) =\u003e {\n const n3 = this.nodeMap.get(e37), o4 = this.nodeMap.get(t3);\n return n3.width * n3.height - o4.width * o4.height;\n }), this.nextBatchNodeIds = [], void (this.batchHadModifications = false)) : (this.solved = true, void this.newNodes.push(...this.nextBatchNodeIds.map((e37) =\u003e this.nodeMap.get(e37))));\n const t2 = this.nodeMap.get(e36);\n let n2 = false;\n const o3 = this.getAdjacentSameLayerUnprocessedNodes(t2);\n if (o3.length === 0)\n return void this.nextBatchNodeIds.push(e36);\n const i3 = (e37) =\u003e {\n for (const t3 of e37)\n this.absorbedNodeIds.add(t3.capacityMeshNodeId);\n t2._adjacentNodeIds = Array.from(new Set([...t2._adjacentNodeIds ?? [], ...e37.flatMap((e38) =\u003e e38._adjacentNodeIds ?? [])].filter((e38) =\u003e e38 !== t2.capacityMeshNodeId \u0026\u0026 !this.absorbedNodeIds.has(e38))));\n }, r3 = o3.filter((e37) =\u003e e37.center.x \u003c t2.center.x \u0026\u0026 Math.abs(e37.center.y - t2.center.y) \u003c t2.height / 2);\n if (r3.length \u003e 0) {\n const { width: e37, height: o4 } = r3[0], s3 = r3.every((t3) =\u003e t3.width === e37 \u0026\u0026 t3.height === o4);\n Math.abs(r3.reduce((e38, t3) =\u003e e38 + t3.height, 0) - t2.height) \u003c Tj \u0026\u0026 s3 \u0026\u0026 (t2.width += e37, t2.center.x = t2.center.x - e37 / 2, i3(r3), n2 = true);\n }\n const s2 = o3.filter((e37) =\u003e e37.center.x \u003e t2.center.x \u0026\u0026 Math.abs(e37.center.y - t2.center.y) \u003c t2.height / 2);\n if (s2.length \u003e 0 \u0026\u0026 !n2) {\n const { width: e37, height: o4 } = s2[0], r4 = s2.every((t3) =\u003e t3.width === e37 \u0026\u0026 t3.height === o4);\n Math.abs(s2.reduce((e38, t3) =\u003e e38 + t3.height, 0) - t2.height) \u003c Tj \u0026\u0026 r4 \u0026\u0026 (t2.width += e37, t2.center.x = t2.center.x + e37 / 2, i3(s2), n2 = true);\n }\n const a3 = o3.filter((e37) =\u003e e37.center.y \u003e t2.center.y \u0026\u0026 Math.abs(e37.center.x - t2.center.x) \u003c t2.width / 2);\n if (a3.length \u003e 0 \u0026\u0026 !n2) {\n const { width: e37, height: o4 } = a3[0], r4 = a3.every((t3) =\u003e t3.width === e37 \u0026\u0026 t3.height === o4);\n Math.abs(a3.reduce((e38, t3) =\u003e e38 + t3.width, 0) - t2.width) \u003c Tj \u0026\u0026 r4 \u0026\u0026 (t2.height += o4, t2.center.y = t2.center.y + o4 / 2, i3(a3), n2 = true);\n }\n const c3 = o3.filter((e37) =\u003e e37.center.y \u003c t2.center.y \u0026\u0026 Math.abs(e37.center.x - t2.center.x) \u003c t2.width / 2);\n if (c3.length \u003e 0 \u0026\u0026 !n2) {\n const { width: e37, height: o4 } = c3[0], r4 = c3.every((t3) =\u003e t3.width === e37 \u0026\u0026 t3.height === o4);\n Math.abs(c3.reduce((e38, t3) =\u003e e38 + t3.width, 0) - t2.width) \u003c Tj \u0026\u0026 r4 \u0026\u0026 (t2.height += o4, t2.center.y = t2.center.y - o4 / 2, i3(c3), n2 = true);\n }\n n2 ? (this.batchHadModifications = true, this.currentBatchNodeIds.push(e36)) : this.nextBatchNodeIds.unshift(e36);\n }\n visualize() {\n const e36 = { circles: [], lines: [], points: [], rects: [], coordinateSystem: \"cartesian\", title: \"Same Layer Node Merger\" };\n for (const t3 of this.newNodes)\n e36.rects.push(dj(t3));\n const t2 = this.currentBatchNodeIds[this.currentBatchNodeIds.length - 1];\n let n2;\n t2 \u0026\u0026 (n2 = this.getAdjacentSameLayerUnprocessedNodes(this.nodeMap.get(t2)));\n for (const o3 of this.currentBatchNodeIds) {\n const i3 = this.nodeMap.get(o3);\n if (!this.absorbedNodeIds.has(o3) \u0026\u0026 i3) {\n const r3 = dj(i3, { rectMargin: 0.01 });\n o3 === t2 ? r3.stroke = \"rgba(0, 255, 0, 0.8)\" : n2?.some((e37) =\u003e e37.capacityMeshNodeId === o3) ? r3.stroke = \"rgba(128, 0, 128, 0.8)\" : r3.stroke = \"rgba(255, 165, 0, 0.8)\", r3.layer = `z${i3.availableZ.join(\",\")}`, r3.label = `${r3.label}\n(unprocessed)`, e36.rects.push(r3);\n }\n }\n for (const t3 of this.nextBatchNodeIds) {\n const n3 = this.nodeMap.get(t3);\n if (!this.absorbedNodeIds.has(t3) \u0026\u0026 n3) {\n const t4 = dj(n3, { rectMargin: 0.01 });\n t4.layer = `z${n3.availableZ.join(\",\")}`, t4.stroke = \"rgba(0, 217, 255, 0.8)\", t4.label = `${t4.label}\nx: ${n3.center.x}, y: ${n3.center.y}\n${n3.width}x${n3.height}\n(next batch)`, e36.rects.push(t4);\n }\n }\n return e36;\n }\n};\nvar Aj = class extends ni {\n getSolverName() {\n return \"StrawSolver\";\n }\n multiLayerNodes;\n strawNodes;\n skippedNodes;\n unprocessedNodes;\n strawSize;\n nodeIdCounter;\n constructor(e36) {\n super(), this.MAX_ITERATIONS = 1e5, this.strawSize = e36.strawSize ?? 0.5, this.multiLayerNodes = [], this.strawNodes = [], this.skippedNodes = [], this.nodeIdCounter = 0, this.unprocessedNodes = [];\n for (const t2 of e36.nodes)\n t2.availableZ.length === 1 ? this.unprocessedNodes.push(t2) : this.multiLayerNodes.push(t2);\n }\n getCapacityOfMultiLayerNodesWithinBounds(e36) {\n let t2 = 0;\n for (const n2 of this.multiLayerNodes) {\n const o3 = n2.center.x - n2.width / 2, i3 = n2.center.x + n2.width / 2, r3 = n2.center.y - n2.height / 2, s2 = n2.center.y + n2.height / 2, a3 = Math.max(e36.minX, o3), c3 = Math.min(e36.maxX, i3), l3 = Math.max(e36.minY, r3), h2 = Math.min(e36.maxY, s2);\n if (a3 \u003c c3 \u0026\u0026 l3 \u003c h2) {\n const e37 = (c3 - a3) * (h2 - l3) / (n2.width * n2.height);\n t2 += Bz(n2) * e37;\n }\n }\n return t2;\n }\n getSurroundingCapacities(e36) {\n const t2 = Math.min(e36.width, e36.height);\n return { leftSurroundingCapacity: this.getCapacityOfMultiLayerNodesWithinBounds({ minX: e36.center.x - e36.width / 2 - t2, maxX: e36.center.x - e36.width / 2, minY: e36.center.y - e36.height / 2, maxY: e36.center.y + e36.height / 2 }), rightSurroundingCapacity: this.getCapacityOfMultiLayerNodesWithinBounds({ minX: e36.center.x + e36.width / 2, maxX: e36.center.x + e36.width / 2 + t2, minY: e36.center.y - e36.height / 2, maxY: e36.center.y + e36.height / 2 }), topSurroundingCapacity: this.getCapacityOfMultiLayerNodesWithinBounds({ minX: e36.center.x - e36.width / 2, maxX: e36.center.x + e36.width / 2, minY: e36.center.y - e36.height / 2 - t2, maxY: e36.center.y - e36.height / 2 }), bottomSurroundingCapacity: this.getCapacityOfMultiLayerNodesWithinBounds({ minX: e36.center.x - e36.width / 2, maxX: e36.center.x + e36.width / 2, minY: e36.center.y + e36.height / 2, maxY: e36.center.y + e36.height / 2 + t2 }) };\n }\n createStrawsForNode(e36) {\n const t2 = [], { leftSurroundingCapacity: n2, rightSurroundingCapacity: o3, topSurroundingCapacity: i3, bottomSurroundingCapacity: r3 } = this.getSurroundingCapacities(e36);\n if (1 * (n2 + o3) \u003e i3 + r3) {\n const n3 = Math.floor(e36.height / this.strawSize), o4 = e36.height / n3;\n for (let i4 = 0;i4 \u003c n3; i4++) {\n const n4 = e36.center.y - e36.height / 2 + i4 * o4 + o4 / 2;\n t2.push({ capacityMeshNodeId: `${e36.capacityMeshNodeId}_straw${i4}`, center: { x: e36.center.x, y: n4 }, width: e36.width, height: o4, layer: e36.layer, availableZ: [...e36.availableZ], _depth: e36._depth, _strawNode: true, _strawParentCapacityMeshNodeId: e36.capacityMeshNodeId });\n }\n } else {\n const n3 = Math.floor(e36.width / this.strawSize), o4 = e36.width / n3;\n for (let i4 = 0;i4 \u003c n3; i4++) {\n const n4 = e36.center.x - e36.width / 2 + i4 * o4 + o4 / 2;\n t2.push({ capacityMeshNodeId: `${e36.capacityMeshNodeId}_straw${i4}`, center: { x: n4, y: e36.center.y }, width: o4, height: e36.height, layer: e36.layer, availableZ: [...e36.availableZ], _depth: e36._depth, _strawNode: true, _strawParentCapacityMeshNodeId: e36.capacityMeshNodeId });\n }\n }\n return t2;\n }\n getResultNodes() {\n return [...this.multiLayerNodes, ...this.strawNodes, ...this.skippedNodes];\n }\n _step() {\n const e36 = this.unprocessedNodes.pop();\n if (!e36)\n return void (this.solved = true);\n if (e36.width \u003c this.strawSize \u0026\u0026 e36.height \u003c this.strawSize)\n return void this.skippedNodes.push(e36);\n if (e36._containsTarget)\n return void this.skippedNodes.push(e36);\n const t2 = this.createStrawsForNode(e36);\n this.strawNodes.push(...t2), t2.length === 0 \u0026\u0026 this.strawNodes.push(e36);\n }\n visualize() {\n const e36 = { rects: [], lines: [], points: [], circles: [], title: \"Straw Solver\" };\n for (const t2 of this.unprocessedNodes)\n e36.rects.push({ center: t2.center, width: t2.width, height: t2.height, fill: \"rgba(200, 200, 200, 0.5)\", stroke: \"rgba(0, 0, 0, 0.5)\", label: `${t2.capacityMeshNodeId}\nUnprocessed\n${t2.width}x${t2.height}` });\n for (const t2 of this.strawNodes) {\n const n2 = t2.availableZ[0] === 0 ? \"rgba(0, 150, 255, 0.5)\" : \"rgba(255, 100, 0, 0.5)\";\n e36.rects.push({ center: t2.center, width: t2.width, height: t2.height, fill: n2, stroke: \"rgba(0, 0, 0, 0.5)\", label: `${t2.capacityMeshNodeId}\nLayer: ${t2.availableZ[0]}\n${t2.width}x${t2.height}`, layer: `z${t2.availableZ.join(\",\")}` });\n }\n for (const t2 of this.multiLayerNodes)\n e36.rects.push({ center: t2.center, width: 0.9 * t2.width, height: 0.9 * t2.height, fill: \"rgba(100, 255, 100, 0.5)\", stroke: \"rgba(0, 0, 0, 0.5)\", layer: `z${t2.availableZ.join(\",\")}`, label: `${t2.capacityMeshNodeId}\nLayers: ${t2.availableZ.join(\",\")}\n${t2.width}x${t2.height}` });\n return e36;\n }\n};\nfunction Oj(e36) {\n const { nodeId: t2, nodeIdToSegmentIds: n2, segmentIdToNodeIds: o3, hops: i3 } = e36;\n if (i3 === 0)\n return [t2];\n const r3 = new Set([t2]), s2 = [{ nodeId: t2, remainingHops: i3 }];\n for (;s2.length \u003e 0; ) {\n const { nodeId: e37, remainingHops: t3 } = s2.shift();\n if (t3 === 0)\n continue;\n const i4 = n2.get(e37) || [];\n for (const e38 of i4) {\n const n3 = o3.get(e38) || [];\n for (const e39 of n3)\n r3.has(e39) || (r3.add(e39), s2.push({ nodeId: e39, remainingHops: t3 - 1 }));\n }\n }\n return Array.from(r3);\n}\nvar kj = (e36) =\u003e Array.from(e36.entries()).map(([e37, { x: t2, y: n2, z: o3 }]) =\u003e `${e37}(${t2?.toFixed(3) ?? \"\"},${n2?.toFixed(3) ?? \"\"},${o3 ?? \"\"})`).sort().join(\"\u0026\");\nvar Dj = (e36, t2, n2, o3) =\u003e {\n const i3 = Math.min(e36, t2), r3 = Math.max(e36, t2), s2 = Math.min(n2, o3);\n return i3 \u003c= Math.max(n2, o3) \u0026\u0026 r3 \u003e= s2;\n};\nvar Lj = (e36, t2, n2, o3) =\u003e {\n const i3 = [], r3 = new Map(e36.originalPointMap);\n for (const [e37, t3] of n2.entries()) {\n const n3 = r3.get(e37);\n r3.set(e37, { x: t3.x ?? n3.x, y: t3.y ?? n3.y, z: t3.z ?? n3.z });\n }\n for (const n3 of e36.allNodeIds) {\n if (!t2.get(n3))\n continue;\n const s2 = e36.segmentPairsInNode.get(n3);\n for (const e37 of s2) {\n const t3 = r3.get(e37[0]), o4 = r3.get(e37[1]);\n t3.z !== o4.z \u0026\u0026 i3.push({ type: \"transition_via\", segmentPoints: e37, capacityMeshNodeId: n3, probabilityOfFailure: 0 });\n }\n for (let e37 = 0;e37 \u003c s2.length; e37++)\n for (let t3 = e37 + 1;t3 \u003c s2.length; t3++) {\n if (o3?.areIdsConnected(s2[e37][0], s2[e37][1]))\n continue;\n const a3 = s2[e37], c3 = s2[t3], l3 = r3.get(a3[0]), h2 = r3.get(a3[1]), d2 = r3.get(c3[0]), u2 = r3.get(c3[1]);\n if (!Dj(l3.z, h2.z, d2.z, u2.z))\n continue;\n const p3 = he(l3, h2, d2, u2), m2 = l3.z === h2.z \u0026\u0026 d2.z === u2.z \u0026\u0026 l3.z === d2.z;\n p3 \u0026\u0026 (m2 ? i3.push({ type: \"same_layer_crossing\", segmentPoints: [a3, c3], capacityMeshNodeId: n3, crossingLine1: a3, crossingLine2: c3, probabilityOfFailure: 0 }) : l3.z === h2.z \u0026\u0026 d2.z !== u2.z ? i3.push({ type: \"single_transition_crossing\", segmentPoints: [a3, c3], capacityMeshNodeId: n3, sameLayerCrossingLine: a3, transitionCrossingLine: c3, probabilityOfFailure: 0 }) : l3.z !== h2.z \u0026\u0026 d2.z === u2.z ? i3.push({ type: \"single_transition_crossing\", segmentPoints: [a3, c3], capacityMeshNodeId: n3, sameLayerCrossingLine: c3, transitionCrossingLine: a3, probabilityOfFailure: 0 }) : l3.z !== h2.z \u0026\u0026 d2.z !== u2.z \u0026\u0026 i3.push({ type: \"double_transition_crossing\", segmentPoints: [a3, c3], capacityMeshNodeId: n3, crossingLine1: a3, crossingLine2: c3, probabilityOfFailure: 0 }));\n }\n }\n return i3;\n};\nvar zj = (e36, t2, n2) =\u003e {\n if (t2.type === \"change_layer\")\n for (const n3 of t2.segmentPointIds) {\n const o3 = e36.get(n3) || {};\n e36.set(n3, { ...o3, z: t2.newZ });\n }\n else if (t2.type === \"swap_position_on_segment\") {\n const [o3, i3] = t2.segmentPointIds, r3 = n2(o3), s2 = n2(i3), a3 = e36.get(o3) || {}, c3 = e36.get(i3) || {};\n e36.set(o3, { ...a3, x: s2.x, y: s2.y }), e36.set(i3, { ...c3, x: r3.x, y: r3.y });\n } else if (t2.type === \"combined\")\n for (const o3 of t2.operations)\n zj(e36, o3, n2);\n};\nvar Bj = (e36, t2) =\u003e {\n const n2 = new Map, o3 = new Map, i3 = new Map, r3 = [];\n let s2 = 0;\n for (const a3 of e36)\n for (const e37 of a3.assignedPoints) {\n const c3 = { segmentPointId: \"SP\" + s2++, segmentId: a3.nodePortSegmentId, capacityMeshNodeIds: t2.get(a3.nodePortSegmentId), connectionName: e37.connectionName, rootConnectionName: e37.rootConnectionName, x: e37.point.x, y: e37.point.y, z: e37.point.z, directlyConnectedSegmentPointIds: [] };\n n2.set(c3.segmentPointId, c3);\n for (const e38 of c3.capacityMeshNodeIds)\n o3.set(e38, [...o3.get(e38) ?? [], c3.segmentPointId]);\n i3.set(a3.nodePortSegmentId, [...i3.get(a3.nodePortSegmentId) ?? [], c3.segmentPointId]), r3.push(c3);\n }\n return { segmentPointMap: n2, nodeToSegmentPointMap: o3, segmentToSegmentPointMap: i3 };\n};\nvar Fj = class extends ni {\n getSolverName() {\n return \"UnravelSectionSolver\";\n }\n nodeMap;\n dedupedSegments;\n dedupedSegmentMap;\n MUTABLE_HOPS = 1;\n unravelSection;\n candidates = [];\n lastProcessedCandidate = null;\n bestCandidate = null;\n originalCandidate;\n rootNodeId;\n nodeIdToSegmentIds;\n segmentIdToNodeIds;\n colorMap;\n tunedNodeCapacityMap;\n MAX_CANDIDATES = 500;\n iterationsSinceImprovement = 0;\n hyperParameters;\n selectedCandidateIndex = null;\n queuedOrExploredCandidatePointModificationHashes = new Set;\n constructorParams;\n constructor(e36) {\n if (super(), this.constructorParams = e36, this.MUTABLE_HOPS = e36.MUTABLE_HOPS ?? this.MUTABLE_HOPS, this.MAX_ITERATIONS = 50000, this.hyperParameters = { ...e36.hyperParameters, MAX_ITERATIONS_WITHOUT_IMPROVEMENT: 200 }, this.nodeMap = e36.nodeMap, this.dedupedSegments = e36.dedupedSegments, e36.dedupedSegmentMap)\n this.dedupedSegmentMap = e36.dedupedSegmentMap;\n else {\n this.dedupedSegmentMap = new Map;\n for (const e37 of this.dedupedSegments)\n this.dedupedSegmentMap.set(e37.nodePortSegmentId, e37);\n }\n this.nodeIdToSegmentIds = e36.nodeIdToSegmentIds, this.segmentIdToNodeIds = e36.segmentIdToNodeIds, this.rootNodeId = e36.rootNodeId, this.colorMap = e36.colorMap ?? {}, this.unravelSection = this.createUnravelSection({ segmentPointMap: e36.segmentPointMap, nodeToSegmentPointMap: e36.nodeToSegmentPointMap, segmentToSegmentPointMap: e36.segmentToSegmentPointMap }), this.tunedNodeCapacityMap = new Map;\n for (const e37 of this.unravelSection.allNodeIds)\n this.tunedNodeCapacityMap.set(e37, Bz(this.nodeMap.get(e37)));\n this.originalCandidate = this.createInitialCandidate(), this.candidates = [this.originalCandidate];\n }\n getConstructorParams() {\n return { ...this.constructorParams, segmentPointMap: this.unravelSection.segmentPointMap, nodeToSegmentPointMap: this.unravelSection.segmentPointsInNode, segmentToSegmentPointMap: this.unravelSection.segmentPointsInSegment };\n }\n createUnravelSection(e36) {\n const t2 = Oj({ nodeId: this.rootNodeId, nodeIdToSegmentIds: this.nodeIdToSegmentIds, segmentIdToNodeIds: this.segmentIdToNodeIds, hops: this.MUTABLE_HOPS }), n2 = Oj({ nodeId: this.rootNodeId, nodeIdToSegmentIds: this.nodeIdToSegmentIds, segmentIdToNodeIds: this.segmentIdToNodeIds, hops: this.MUTABLE_HOPS + 1 }), o3 = Array.from(new Set(n2).difference(new Set(t2)));\n e36?.segmentPointMap || (e36 = Bj(this.dedupedSegments, this.segmentIdToNodeIds));\n const i3 = new Map;\n for (const t3 of n2)\n i3.set(t3, e36.nodeToSegmentPointMap.get(t3));\n const r3 = new Map;\n for (const t3 of n2)\n for (const n3 of i3.get(t3)) {\n const t4 = e36.segmentPointMap.get(n3);\n r3.set(n3, t4);\n }\n const s2 = Array.from(r3.values()), a3 = new Map;\n for (const e37 of s2)\n a3.set(e37.segmentId, [...a3.get(e37.segmentId) ?? [], e37.segmentPointId]);\n for (const [t3, n3] of i3.entries())\n for (let t4 = 0;t4 \u003c n3.length; t4++) {\n const o4 = e36.segmentPointMap.get(n3[t4]);\n for (let i4 = t4 + 1;i4 \u003c n3.length; i4++) {\n const t5 = e36.segmentPointMap.get(n3[i4]);\n t5.segmentPointId !== o4.segmentPointId \u0026\u0026 (t5.segmentId !== o4.segmentId \u0026\u0026 t5.connectionName === o4.connectionName \u0026\u0026 (t5.directlyConnectedSegmentPointIds.includes(o4.segmentPointId) || (o4.directlyConnectedSegmentPointIds.push(t5.segmentPointId), t5.directlyConnectedSegmentPointIds.push(o4.segmentPointId))));\n }\n }\n const c3 = new Map;\n for (const e37 of n2)\n c3.set(e37, []);\n for (const t3 of s2)\n for (const n3 of t3.capacityMeshNodeIds) {\n const o4 = c3.get(n3);\n if (o4)\n for (const i4 of t3.directlyConnectedSegmentPointIds) {\n const r4 = e36.segmentPointMap.get(i4);\n r4.segmentPointId !== t3.segmentPointId \u0026\u0026 (r4.capacityMeshNodeIds.some((e37) =\u003e e37 === n3) \u0026\u0026 (o4.some(([e37, n4]) =\u003e e37 === t3.segmentPointId \u0026\u0026 n4 === r4.segmentPointId || e37 === r4.segmentPointId \u0026\u0026 n4 === t3.segmentPointId) || o4.push([t3.segmentPointId, r4.segmentPointId])));\n }\n }\n const l3 = new Set;\n for (const e37 of t2)\n for (const t3 of this.nodeIdToSegmentIds.get(e37)) {\n this.segmentIdToNodeIds.get(t3).every((e38) =\u003e !this.nodeMap.get(e38)._containsTarget) \u0026\u0026 l3.add(t3);\n }\n const h2 = new Set;\n for (const e37 of s2) {\n const n3 = e37.capacityMeshNodeIds.some((e38) =\u003e t2.includes(e38)), o4 = this.dedupedSegmentMap.get(e37.segmentId), i4 = o4 \u0026\u0026 o4.availableZ.length \u003e 1;\n (n3 || i4) \u0026\u0026 h2.add(e37.segmentPointId);\n }\n const d2 = new Set;\n for (const e37 of s2) {\n if (e37.capacityMeshNodeIds.some((e38) =\u003e this.nodeMap.get(e38)?._containsTarget)) {\n const t3 = this.dedupedSegmentMap.get(e37.segmentId);\n t3 \u0026\u0026 t3.availableZ.length === 1 \u0026\u0026 d2.add(e37.segmentPointId);\n }\n }\n return { allNodeIds: n2, mutableNodeIds: t2, immutableNodeIds: o3, mutableSegmentIds: l3, segmentPairsInNode: c3, segmentPointMap: r3, segmentPointsInNode: i3, segmentPointsInSegment: a3, originalPointMap: r3, mutableSegmentPointIds: h2, zLockedSegmentPointIds: d2 };\n }\n createInitialCandidate() {\n const e36 = new Map, t2 = Lj(this.unravelSection, this.nodeMap, e36), n2 = this.computeG({ issues: t2, originalCandidate: {}, operationsPerformed: 0, operation: {} });\n return { pointModifications: e36, g: n2, h: 0, f: n2, operationsPerformed: 0, candidateHash: kj(e36), issues: Lj(this.unravelSection, this.nodeMap, e36) };\n }\n get nextCandidate() {\n return this.candidates[0] ?? null;\n }\n getPointInCandidate(e36, t2) {\n const n2 = this.unravelSection.segmentPointMap.get(t2), o3 = e36.pointModifications.get(t2);\n return { x: o3?.x ?? n2.x, y: o3?.y ?? n2.y, z: o3?.z ?? n2.z, segmentId: n2.segmentId };\n }\n getConnectionSegmentPointIds(e36) {\n const t2 = [];\n for (const [n2, o3] of this.unravelSection.segmentPointMap.entries())\n o3.connectionName === e36 \u0026\u0026 t2.push(n2);\n return t2;\n }\n canConnectionUseLayer(e36, t2) {\n for (const n2 of e36) {\n const e37 = this.unravelSection.segmentPointMap.get(n2), o3 = this.dedupedSegmentMap.get(e37.segmentId);\n if (!o3 || !o3.availableZ.includes(t2))\n return false;\n }\n return true;\n }\n getOperationsForIssue(e36, t2) {\n const n2 = [];\n if (t2.type === \"transition_via\") {\n const [o3, i3] = t2.segmentPoints, r3 = this.getPointInCandidate(e36, o3), s2 = this.getPointInCandidate(e36, i3), a3 = this.unravelSection.segmentPointMap.get(o3), c3 = (this.unravelSection.segmentPointMap.get(i3), this.dedupedSegmentMap.get(r3.segmentId).availableZ), l3 = this.dedupedSegmentMap.get(s2.segmentId).availableZ, h2 = this.unravelSection.zLockedSegmentPointIds.has(o3), d2 = this.unravelSection.zLockedSegmentPointIds.has(i3), u2 = this.getConnectionSegmentPointIds(a3.connectionName);\n if (this.canConnectionUseLayer(u2, s2.z)) {\n const e37 = u2.filter((e38) =\u003e this.unravelSection.mutableSegmentPointIds.has(e38) \u0026\u0026 !this.unravelSection.zLockedSegmentPointIds.has(e38));\n e37.length \u003e 0 \u0026\u0026 n2.push({ type: \"change_layer\", newZ: s2.z, segmentPointIds: e37 });\n }\n if (this.canConnectionUseLayer(u2, r3.z)) {\n const e37 = u2.filter((e38) =\u003e this.unravelSection.mutableSegmentPointIds.has(e38) \u0026\u0026 !this.unravelSection.zLockedSegmentPointIds.has(e38));\n e37.length \u003e 0 \u0026\u0026 n2.push({ type: \"change_layer\", newZ: r3.z, segmentPointIds: e37 });\n }\n this.unravelSection.mutableSegmentPointIds.has(o3) \u0026\u0026 !h2 \u0026\u0026 c3.includes(s2.z) \u0026\u0026 n2.push({ type: \"change_layer\", newZ: s2.z, segmentPointIds: [o3] }), this.unravelSection.mutableSegmentPointIds.has(i3) \u0026\u0026 !d2 \u0026\u0026 l3.includes(r3.z) \u0026\u0026 n2.push({ type: \"change_layer\", newZ: r3.z, segmentPointIds: [i3] });\n }\n if (t2.type === \"same_layer_crossing\") {\n const [e37, o3] = t2.crossingLine1, [i3, r3] = t2.crossingLine2, s2 = [], a3 = this.unravelSection.segmentPointMap.get(e37), c3 = this.unravelSection.segmentPointMap.get(o3), l3 = this.unravelSection.segmentPointMap.get(i3), h2 = this.unravelSection.segmentPointMap.get(r3), d2 = this.unravelSection.mutableSegmentPointIds.has(e37), u2 = this.unravelSection.mutableSegmentPointIds.has(o3), p3 = this.unravelSection.mutableSegmentPointIds.has(i3), m2 = this.unravelSection.mutableSegmentPointIds.has(r3), g2 = this.unravelSection.zLockedSegmentPointIds.has(e37), f2 = this.unravelSection.zLockedSegmentPointIds.has(o3), _2 = this.unravelSection.zLockedSegmentPointIds.has(i3), y2 = this.unravelSection.zLockedSegmentPointIds.has(r3);\n d2 \u0026\u0026 p3 \u0026\u0026 a3.segmentId === l3.segmentId \u0026\u0026 s2.push([e37, i3]), d2 \u0026\u0026 m2 \u0026\u0026 a3.segmentId === h2.segmentId \u0026\u0026 s2.push([e37, r3]), u2 \u0026\u0026 p3 \u0026\u0026 c3.segmentId === l3.segmentId \u0026\u0026 s2.push([o3, i3]), u2 \u0026\u0026 m2 \u0026\u0026 c3.segmentId === h2.segmentId \u0026\u0026 s2.push([o3, r3]);\n for (const [e38, t3] of s2)\n n2.push({ type: \"swap_position_on_segment\", segmentPointIds: [e38, t3] });\n const b2 = this.getConnectionSegmentPointIds(a3.connectionName), x2 = this.getConnectionSegmentPointIds(l3.connectionName), v2 = new Set;\n for (const e38 of this.unravelSection.segmentPointMap.values()) {\n const t3 = this.dedupedSegmentMap.get(e38.segmentId);\n if (t3)\n for (const e39 of t3.availableZ)\n v2.add(e39);\n }\n for (const e38 of v2)\n if (e38 !== a3.z \u0026\u0026 this.canConnectionUseLayer(b2, e38)) {\n const t3 = b2.filter((e39) =\u003e this.unravelSection.mutableSegmentPointIds.has(e39) \u0026\u0026 !this.unravelSection.zLockedSegmentPointIds.has(e39));\n t3.length \u003e 0 \u0026\u0026 n2.push({ type: \"change_layer\", newZ: e38, segmentPointIds: t3 });\n }\n for (const e38 of v2)\n if (e38 !== l3.z \u0026\u0026 this.canConnectionUseLayer(x2, e38)) {\n const t3 = x2.filter((e39) =\u003e this.unravelSection.mutableSegmentPointIds.has(e39) \u0026\u0026 !this.unravelSection.zLockedSegmentPointIds.has(e39));\n t3.length \u003e 0 \u0026\u0026 n2.push({ type: \"change_layer\", newZ: e38, segmentPointIds: t3 });\n }\n const I2 = this.dedupedSegmentMap.get(a3.segmentId), S2 = this.dedupedSegmentMap.get(c3.segmentId), C = this.dedupedSegmentMap.get(l3.segmentId), P = this.dedupedSegmentMap.get(h2.segmentId), M = (e38, t3) =\u003e e38.every((e39) =\u003e e39.availableZ.includes(t3));\n if (d2 \u0026\u0026 u2 \u0026\u0026 !g2 \u0026\u0026 !f2) {\n const t3 = a3.z === 0 ? 1 : 0;\n M([I2, S2], t3) \u0026\u0026 n2.push({ type: \"change_layer\", newZ: t3, segmentPointIds: [e37, o3] });\n }\n if (p3 \u0026\u0026 m2 \u0026\u0026 !_2 \u0026\u0026 !y2) {\n const e38 = l3.z === 0 ? 1 : 0;\n M([C, P], e38) \u0026\u0026 n2.push({ type: \"change_layer\", newZ: e38, segmentPointIds: [i3, r3] });\n }\n if (d2 \u0026\u0026 !g2) {\n const t3 = a3.z === 0 ? 1 : 0;\n I2.availableZ.includes(t3) \u0026\u0026 n2.push({ type: \"change_layer\", newZ: t3, segmentPointIds: [e37] });\n }\n if (u2 \u0026\u0026 !f2) {\n const e38 = c3.z === 0 ? 1 : 0;\n S2.availableZ.includes(e38) \u0026\u0026 n2.push({ type: \"change_layer\", newZ: e38, segmentPointIds: [o3] });\n }\n if (p3 \u0026\u0026 !_2) {\n const e38 = l3.z === 0 ? 1 : 0;\n C.availableZ.includes(e38) \u0026\u0026 n2.push({ type: \"change_layer\", newZ: e38, segmentPointIds: [i3] });\n }\n if (m2 \u0026\u0026 !y2) {\n const e38 = h2.z === 0 ? 1 : 0;\n P.availableZ.includes(e38) \u0026\u0026 n2.push({ type: \"change_layer\", newZ: e38, segmentPointIds: [r3] });\n }\n }\n return n2;\n }\n computeG(e36) {\n const { issues: t2, originalCandidate: n2, operationsPerformed: o3, operation: i3 } = e36, r3 = new Map;\n for (const e37 of t2) {\n r3.has(e37.capacityMeshNodeId) || r3.set(e37.capacityMeshNodeId, { numTransitionCrossings: 0, numSameLayerCrossings: 0, numEntryExitLayerChanges: 0 });\n const t3 = r3.get(e37.capacityMeshNodeId);\n e37.type === \"transition_via\" ? t3.numTransitionCrossings++ : e37.type === \"same_layer_crossing\" ? t3.numSameLayerCrossings++ : e37.type === \"double_transition_crossing\" || e37.type === \"single_transition_crossing\" ? t3.numEntryExitLayerChanges++ : e37.type;\n }\n let s2 = 0;\n for (const [e37, { numEntryExitLayerChanges: t3, numSameLayerCrossings: n3, numTransitionCrossings: o4 }] of r3) {\n const i4 = this.nodeMap.get(e37), r4 = Math.min(jz(i4, n3, t3, o4), 0.999999);\n s2 += Math.log(1 - r4);\n }\n var a3;\n return (a3 = s2) \u003c -Math.LN2 ? Math.log(1 - Math.exp(a3)) : Math.log(-Math.expm1(a3));\n }\n getUnexploredNeighborByApplyingOperation(e36, t2) {\n const n2 = new Map(e36.pointModifications);\n zj(n2, t2, (t3) =\u003e this.getPointInCandidate(e36, t3));\n const o3 = kj(n2);\n if (this.queuedOrExploredCandidatePointModificationHashes.has(o3))\n return null;\n const i3 = Lj(this.unravelSection, this.nodeMap, n2), r3 = e36.operationsPerformed + 1, s2 = this.computeG({ issues: i3, originalCandidate: e36, operationsPerformed: r3, operation: t2 });\n return { issues: i3, g: s2, h: 0, f: s2, pointModifications: n2, candidateHash: o3, operationsPerformed: r3 };\n }\n getNeighborOperationsForCandidate(e36) {\n return e36.issues.flatMap((t2) =\u003e this.getOperationsForIssue(e36, t2));\n }\n getNeighbors(e36) {\n const t2 = [], n2 = this.getNeighborOperationsForCandidate(e36);\n for (const o3 of n2) {\n const n3 = this.getUnexploredNeighborByApplyingOperation(e36, o3);\n n3 \u0026\u0026 t2.push(n3);\n }\n return t2;\n }\n _step() {\n const e36 = this.candidates.shift();\n this.iterationsSinceImprovement++, this.iterationsSinceImprovement \u003e this.hyperParameters.MAX_ITERATIONS_WITHOUT_IMPROVEMENT ? this.solved = true : e36 ? (this.lastProcessedCandidate = e36, e36.f \u003c (this.bestCandidate?.f ?? 1 / 0) \u0026\u0026 (this.bestCandidate = e36, this.iterationsSinceImprovement = 0), this.getNeighbors(e36).forEach((e37) =\u003e {\n this.queuedOrExploredCandidatePointModificationHashes.has(e37.candidateHash) || (this.queuedOrExploredCandidatePointModificationHashes.add(e37.candidateHash), this.candidates.push(e37));\n }), this.candidates.sort((e37, t2) =\u003e e37.f - t2.f), this.candidates.length = Math.min(this.candidates.length, this.MAX_CANDIDATES)) : this.solved = true;\n }\n visualize() {\n const e36 = { points: [], lines: [], rects: [], circles: [], coordinateSystem: \"cartesian\", title: \"Unravel Section Solver\" };\n let t2 = null;\n if (t2 = this.selectedCandidateIndex !== null ? this.selectedCandidateIndex === \"best\" ? this.bestCandidate : this.selectedCandidateIndex === \"original\" ? this.originalCandidate : this.candidates[this.selectedCandidateIndex] : this.solved ? this.bestCandidate : this.lastProcessedCandidate || this.candidates[0], !t2)\n return e36;\n const n2 = new Map;\n for (const [e37, o4] of this.unravelSection.segmentPointMap) {\n const i3 = { ...o4 }, r3 = t2.pointModifications.get(e37);\n r3 \u0026\u0026 (r3.x !== undefined \u0026\u0026 (i3.x = r3.x), r3.y !== undefined \u0026\u0026 (i3.y = r3.y), r3.z !== undefined \u0026\u0026 (i3.z = r3.z)), n2.set(e37, i3);\n }\n for (const [t3, o4] of n2)\n e36.points.push({ x: o4.x, y: o4.y, label: `${t3}\nSegment: ${o4.segmentId} ${this.unravelSection.mutableSegmentIds.has(o4.segmentId) ? \"MUTABLE\" : \"IMMUTABLE\"}\nLayer: ${o4.z}`, color: this.colorMap[o4.connectionName] || \"#000\" });\n const o3 = new Map;\n for (const e37 of this.unravelSection.allNodeIds)\n o3.set(e37, { numTransitionCrossings: 0, numSameLayerCrossings: 0, numEntryExitLayerChanges: 0, estPf: 0 });\n for (const e37 of t2.issues) {\n const t3 = o3.get(e37.capacityMeshNodeId);\n e37.type === \"transition_via\" ? t3.numTransitionCrossings++ : e37.type === \"same_layer_crossing\" ? t3.numSameLayerCrossings++ : e37.type !== \"double_transition_crossing\" \u0026\u0026 e37.type !== \"single_transition_crossing\" || t3.numEntryExitLayerChanges++;\n }\n for (const [e37, t3] of o3.entries()) {\n const n3 = this.nodeMap.get(e37);\n t3.estPf = jz(n3, t3.numSameLayerCrossings, t3.numEntryExitLayerChanges, t3.numTransitionCrossings);\n }\n for (const t3 of this.unravelSection.allNodeIds) {\n const n3 = this.nodeMap.get(t3), i3 = this.unravelSection.mutableNodeIds.includes(t3), r3 = o3.get(t3), s2 = [`${t3} (${i3 ? \"MUT\" : \"IMM\"})`, `${n3.width.toFixed(2)}x${n3.height.toFixed(2)}`, `Pf: ${r3.estPf.toFixed(3)}`, `TC: ${r3.numTransitionCrossings}`, `SLC: ${r3.numSameLayerCrossings}`, `EELC: ${r3.numEntryExitLayerChanges}`].join(`\n`);\n e36.rects.push({ center: n3.center, label: s2, color: i3 ? \"green\" : \"red\", width: n3.width / 8, height: n3.height / 8 });\n }\n for (const [t3, o4] of this.unravelSection.segmentPointsInSegment) {\n if (o4.length \u003c= 1)\n continue;\n const i3 = o4.map((e37) =\u003e n2.get(e37));\n for (let n3 = 0;n3 \u003c i3.length - 1; n3++)\n e36.lines.push({ points: [{ x: i3[n3].x, y: i3[n3].y }, { x: i3[n3 + 1].x, y: i3[n3 + 1].y }], strokeColor: this.colorMap[t3] || \"#000\" });\n }\n for (const [t3, o4] of n2)\n for (const i3 of o4.directlyConnectedSegmentPointIds)\n if (t3 \u003c i3) {\n const t4 = n2.get(i3);\n if (!t4)\n continue;\n const r3 = o4.z === t4.z, s2 = o4.z;\n let a3;\n a3 = r3 ? s2 === 0 ? undefined : \"10 5\" : \"3 3 10\", e36.lines.push({ points: [{ x: o4.x, y: o4.y }, { x: t4.x, y: t4.y }], strokeDash: a3, strokeColor: this.colorMap[o4.connectionName] || \"#000\" });\n }\n for (const o4 of t2.issues) {\n const t3 = this.nodeMap.get(o4.capacityMeshNodeId);\n if (o4.type === \"transition_via\")\n for (const i3 of o4.segmentPoints) {\n const o5 = n2.get(i3);\n e36.circles.push({ center: { x: o5.x, y: o5.y }, radius: t3.width / 16, stroke: \"#ff0000\", fill: \"rgba(255, 0, 0, 0.2)\", label: `Via Issue\n${i3}\nLayer: ${o5.z}` });\n }\n else if (o4.type === \"same_layer_crossing\")\n for (const [i3, r3] of [o4.crossingLine1, o4.crossingLine2]) {\n const o5 = n2.get(i3), s2 = n2.get(r3);\n e36.lines.push({ points: [{ x: o5.x, y: o5.y }, { x: s2.x, y: s2.y }], strokeColor: \"rgba(255,0,0,0.2)\", strokeWidth: t3.width / 32 });\n }\n }\n for (const [o4, i3] of t2.pointModifications) {\n const t3 = n2.get(o4), i4 = this.unravelSection.segmentPointMap.get(o4);\n e36.circles.push({ center: { x: t3.x, y: t3.y }, radius: 0.05, stroke: \"#0000ff\", fill: \"rgba(0, 0, 255, 0.2)\", label: `${o4}\nOriginal: (${i4.x.toFixed(2)}, ${i4.y.toFixed(2)}, ${i4.z})\nNew: (${t3.x.toFixed(2)}, ${t3.y.toFixed(2)}, ${t3.z})` });\n }\n return e36;\n }\n};\nvar $j = (e36) =\u003e (Math.round(20 * e36) / 20).toFixed(2);\nvar Yj = (e36) =\u003e (Math.round(1000 * e36) / 1000).toFixed(3);\noo();\nvar Xj = class extends Fj {\n cacheHit = false;\n cacheProvider;\n hasAttemptedToUseCache = false;\n constructor(e36) {\n super(e36), this.cacheProvider = e36.cacheProvider === undefined ? to() : e36.cacheProvider;\n }\n _step() {\n !this.hasAttemptedToUseCache \u0026\u0026 this.cacheProvider \u0026\u0026 this.attemptToUseCacheSync() || (super._step(), (this.solved || this.failed) \u0026\u0026 this.cacheProvider \u0026\u0026 this.saveToCacheSync());\n }\n computeCacheKeyAndTransform() {\n const e36 = this.nodeMap.get(this.rootNodeId), t2 = Gt(-e36.center.x, -e36.center.y), n2 = new Map, o3 = new Map, i3 = new Map, r3 = new Map, s2 = new Map, a3 = new Map;\n let c3 = 0, l3 = 0, h2 = 0;\n const d2 = [...this.unravelSection.allNodeIds].sort((e37, t3) =\u003e {\n const n3 = this.nodeMap.get(e37), o4 = this.nodeMap.get(t3);\n return n3.center.x !== o4.center.x ? n3.center.x - o4.center.x : n3.center.y - o4.center.y;\n });\n for (const e37 of d2) {\n const t3 = \"node_\" + c3++;\n n2.set(e37, t3), o3.set(t3, e37);\n }\n const u2 = [...Array.from(this.unravelSection.segmentPointMap.entries()).sort(([, e37], [, t3]) =\u003e e37.x !== t3.x ? e37.x - t3.x : e37.y - t3.y).map(([e37]) =\u003e e37)].sort();\n for (const e37 of u2) {\n const t3 = \"sp_\" + h2++;\n s2.set(e37, t3), a3.set(t3, e37);\n const n3 = this.unravelSection.segmentPointMap.get(e37).segmentId;\n if (!i3.has(n3)) {\n const e38 = \"seg_\" + l3++;\n i3.set(n3, e38), r3.set(e38, n3);\n }\n }\n const p3 = {};\n for (const [e37, o4] of n2.entries()) {\n const n3 = this.nodeMap.get(e37), i4 = Ht(t2, n3.center);\n p3[o4] = { width: n3.width, height: n3.height, availableZ: n3.availableZ, center: { x: $j(i4.x), y: $j(i4.y) } };\n }\n const m2 = {};\n for (const [e37, n3] of s2.entries()) {\n const o4 = this.unravelSection.segmentPointMap.get(e37), i4 = Ht(t2, { x: o4.x, y: o4.y });\n m2[n3] = { x: $j(i4.x), y: $j(i4.y), z: o4.z };\n }\n const g2 = { hyperParameters: this.hyperParameters, normalizedNodes: p3, normalizedSegmentPoints: m2, mutableHops: this.MUTABLE_HOPS }, f2 = `unravelsec:${import_object_hash3.default(g2)}`, _2 = { realToCacheTransform: t2, nodeIdMap: n2, segmentIdMap: i3, segmentPointIdMap: s2, reverseNodeIdMap: o3, reverseSegmentIdMap: r3, reverseSegmentPointIdMap: a3 };\n return this.cacheKey = f2, this.cacheToSolveSpaceTransform = _2, { cacheKey: f2, cacheToSolveSpaceTransform: _2 };\n }\n applyCachedSolution(e36) {\n if (e36.success === false)\n return void (this.failed = true);\n if (!this.cacheToSolveSpaceTransform)\n return void console.error(\"Cache transform not available to apply cached solution.\");\n const { reverseSegmentPointIdMap: t2, reverseNodeIdMap: n2 } = this.cacheToSolveSpaceTransform, o3 = new Map;\n for (const [n3, i4] of e36.bestCandidatePointModificationsDelta) {\n const e37 = t2.get(n3);\n if (!e37) {\n console.warn(`Could not find original ID for normalized SP ID: ${n3} when applying cache.`);\n continue;\n }\n const r3 = this.unravelSection.segmentPointMap.get(e37);\n if (!r3) {\n console.warn(`Could not find original segment point for ID: ${e37} when applying cache.`);\n continue;\n }\n const s2 = {};\n if (i4.dx !== undefined) {\n const e38 = parseFloat(i4.dx);\n Number.isNaN(e38) ? console.warn(`Failed to parse cached dx coordinate: ${i4.dx}`) : s2.x = r3.x + e38;\n }\n if (i4.dy !== undefined) {\n const e38 = parseFloat(i4.dy);\n Number.isNaN(e38) ? console.warn(`Failed to parse cached dy coordinate: ${i4.dy}`) : s2.y = r3.y + e38;\n }\n i4.dz !== undefined \u0026\u0026 (s2.z = r3.z + i4.dz), Object.keys(s2).length \u003e 0 \u0026\u0026 o3.set(e37, s2);\n }\n const i3 = Lj(this.unravelSection, this.nodeMap, o3);\n this.bestCandidate = { pointModifications: o3, issues: i3, f: e36.bestCandidateF, g: e36.bestCandidateF, h: 0, operationsPerformed: -1, candidateHash: kj(o3) }, this.cacheHit = true, this.solved = true;\n }\n attemptToUseCacheSync() {\n if (this.hasAttemptedToUseCache = true, !this.cacheProvider?.isSyncCache)\n return console.log(\"Cache provider is not synchronous, skipping sync cache check.\"), false;\n if (this.cacheKey || this.computeCacheKeyAndTransform(), !this.cacheKey)\n return console.error(\"Failed to compute cache key.\"), false;\n try {\n const e36 = this.cacheProvider.getCachedSolutionSync(this.cacheKey);\n if (e36)\n return this.applyCachedSolution(e36), true;\n } catch (e36) {\n console.error(\"Error attempting to use cache:\", e36);\n }\n return false;\n }\n saveToCacheSync() {\n if (this.failed)\n return void this.cacheProvider?.setCachedSolutionSync(this.cacheKey, { success: false });\n if (!this.bestCandidate)\n return;\n const { segmentPointIdMap: e36 } = this.cacheToSolveSpaceTransform, t2 = [];\n for (const [n3, o3] of this.bestCandidate.pointModifications.entries()) {\n const i3 = e36.get(n3);\n if (!i3) {\n console.warn(`Could not find normalized ID for original SP ID: ${n3} when saving to cache.`);\n continue;\n }\n const r3 = this.unravelSection.segmentPointMap.get(n3);\n if (!r3) {\n console.warn(`Could not find original segment point for ID: ${n3} when saving cache.`);\n continue;\n }\n const s2 = {};\n let a3 = false;\n if (o3.x !== undefined) {\n const e37 = o3.x - r3.x, t3 = Yj(e37);\n parseFloat(t3) !== 0 \u0026\u0026 (s2.dx = t3, a3 = true);\n }\n if (o3.y !== undefined) {\n const e37 = o3.y - r3.y, t3 = Yj(e37);\n parseFloat(t3) !== 0 \u0026\u0026 (s2.dy = t3, a3 = true);\n }\n if (o3.z !== undefined) {\n const e37 = o3.z - r3.z;\n e37 !== 0 \u0026\u0026 (s2.dz = e37, a3 = true);\n }\n a3 \u0026\u0026 t2.push([i3, s2]);\n }\n const n2 = { success: true, bestCandidatePointModificationsDelta: t2, bestCandidateF: this.bestCandidate.f };\n this.cacheProvider?.setCachedSolutionSync(this.cacheKey, n2);\n }\n};\nvar Hj = class extends ni {\n getSolverName() {\n return \"UnravelMultiSectionSolver\";\n }\n nodeMap;\n dedupedSegmentMap;\n dedupedSegments;\n nodeIdToSegmentIds;\n segmentIdToNodeIds;\n nodeToSegmentPointMap;\n segmentToSegmentPointMap;\n colorMap;\n tunedNodeCapacityMap;\n MAX_NODE_ATTEMPTS = 2;\n MUTABLE_HOPS = 1;\n ACCEPTABLE_PF = 0.05;\n MAX_ITERATIONS_WITHOUT_IMPROVEMENT = 200;\n nodePfMap;\n attemptsToFixNode;\n activeSubSolver = null;\n segmentPointMap;\n cacheProvider = null;\n constructor({ assignedSegments: e36, colorMap: t2, nodes: n2, cacheProvider: o3 }) {\n super(), this.stats.successfulOptimizations = 0, this.stats.failedOptimizations = 0, this.stats.cacheHits = 0, this.stats.cacheMisses = 0, this.cacheProvider = o3 ?? null, this.MAX_ITERATIONS = 1e6, this.dedupedSegments = ((e37) =\u003e {\n const t3 = [], n3 = new Map;\n let o4 = -1;\n for (const i4 of e37) {\n const e38 = `${i4.start.x}-${i4.start.y}-${i4.end.x}-${i4.end.y}-${i4.availableZ.join(\",\")}`, r4 = n3.get(e38);\n r4 ? i4.nodePortSegmentId = r4.nodePortSegmentId : (o4++, i4.nodePortSegmentId = `SEG${o4}`, n3.set(e38, i4), t3.push(i4));\n }\n return t3;\n })(e36), this.dedupedSegmentMap = new Map;\n for (const e37 of this.dedupedSegments)\n this.dedupedSegmentMap.set(e37.nodePortSegmentId, e37);\n this.nodeMap = new Map;\n for (const e37 of n2)\n this.nodeMap.set(e37.capacityMeshNodeId, e37);\n this.nodeIdToSegmentIds = new Map, this.segmentIdToNodeIds = new Map, this.attemptsToFixNode = new Map;\n for (const t3 of e36)\n this.segmentIdToNodeIds.set(t3.nodePortSegmentId, [...this.segmentIdToNodeIds.get(t3.nodePortSegmentId) ?? [], t3.capacityMeshNodeId]), this.nodeIdToSegmentIds.set(t3.capacityMeshNodeId, [...this.nodeIdToSegmentIds.get(t3.capacityMeshNodeId) ?? [], t3.nodePortSegmentId]);\n this.colorMap = t2 ?? {}, this.tunedNodeCapacityMap = new Map;\n for (const [e37, t3] of this.nodeMap)\n this.tunedNodeCapacityMap.set(e37, Bz(t3));\n const { segmentPointMap: i3, nodeToSegmentPointMap: r3, segmentToSegmentPointMap: s2 } = Bj(this.dedupedSegments, this.segmentIdToNodeIds);\n this.segmentPointMap = i3, this.nodeToSegmentPointMap = r3, this.segmentToSegmentPointMap = s2, this.nodePfMap = this.computeInitialPfMap();\n }\n computeInitialPfMap() {\n const e36 = new Map;\n for (const [t2, n2] of this.nodeMap.entries())\n e36.set(t2, this.computeNodePf(n2));\n return e36;\n }\n computeNodePf(e36) {\n const { numSameLayerCrossings: t2, numEntryExitLayerChanges: n2, numTransitionCrossings: o3 } = ((e37) =\u003e {\n let t3 = 0, n3 = 0, o4 = 0;\n const i3 = new Map;\n for (const t4 of e37)\n i3.has(t4.connectionName) || i3.set(t4.connectionName, []), i3.get(t4.connectionName).push(t4);\n const r3 = [], s2 = [];\n for (const [e38, t4] of i3.entries()) {\n if (t4.length \u003c 2)\n continue;\n const o5 = t4[0];\n for (let i4 = 1;i4 \u003c t4.length; i4++) {\n const a3 = t4[i4], c3 = { connectionName: e38, z: o5.z, points: [o5, a3] };\n o5.z !== a3.z ? (n3++, s2.push({ connectionName: e38, points: [o5, a3] })) : r3.push(c3);\n }\n }\n for (let e38 = 0;e38 \u003c r3.length; e38++)\n for (let n4 = e38 + 1;n4 \u003c r3.length; n4++) {\n const o5 = r3[e38], i4 = r3[n4];\n o5.z === i4.z \u0026\u0026 he(o5.points[0], o5.points[1], i4.points[0], i4.points[1]) \u0026\u0026 t3++;\n }\n for (let e38 = 0;e38 \u003c s2.length; e38++)\n for (let t4 = e38 + 1;t4 \u003c s2.length; t4++) {\n const n4 = s2[e38], i4 = s2[t4];\n he(n4.points[0], n4.points[1], i4.points[0], i4.points[1]) \u0026\u0026 o4++;\n }\n for (let e38 = 0;e38 \u003c s2.length; e38++)\n for (let t4 = 0;t4 \u003c r3.length; t4++) {\n const n4 = s2[e38], i4 = r3[t4];\n he(n4.points[0], n4.points[1], i4.points[0], i4.points[1]) \u0026\u0026 o4++;\n }\n return { numSameLayerCrossings: t3, numEntryExitLayerChanges: n3, numTransitionCrossings: o4 };\n })((this.nodeToSegmentPointMap.get(e36.capacityMeshNodeId) ?? []).map((e37) =\u003e this.segmentPointMap.get(e37)));\n return jz(e36, t2, n2, o3);\n }\n _step() {\n if (this.iterations \u003e= this.MAX_ITERATIONS - 1)\n return void (this.solved = true);\n if (!this.activeSubSolver) {\n let e37 = null, t3 = 0;\n for (const [n3, o3] of this.nodePfMap.entries()) {\n o3 * (1 - (this.attemptsToFixNode.get(n3) ?? 0) / this.MAX_NODE_ATTEMPTS) \u003e t3 \u0026\u0026 (t3 = o3, e37 = n3);\n }\n if (!e37 || t3 \u003c this.ACCEPTABLE_PF)\n return void (this.solved = true);\n this.attemptsToFixNode.set(e37, (this.attemptsToFixNode.get(e37) ?? 0) + 1), this.activeSubSolver = new Xj({ dedupedSegments: this.dedupedSegments, dedupedSegmentMap: this.dedupedSegmentMap, nodeMap: this.nodeMap, nodeIdToSegmentIds: this.nodeIdToSegmentIds, segmentIdToNodeIds: this.segmentIdToNodeIds, colorMap: this.colorMap, rootNodeId: e37, MUTABLE_HOPS: this.MUTABLE_HOPS, segmentPointMap: this.segmentPointMap, nodeToSegmentPointMap: this.nodeToSegmentPointMap, segmentToSegmentPointMap: this.segmentToSegmentPointMap, cacheProvider: this.cacheProvider });\n }\n this.activeSubSolver.step();\n const { bestCandidate: e36, originalCandidate: t2, lastProcessedCandidate: n2 } = this.activeSubSolver;\n if (this.activeSubSolver.failed)\n return this.stats.failedOptimizations += 1, void (this.activeSubSolver = null);\n if (this.activeSubSolver.solved) {\n this.activeSubSolver.cacheHit ? this.stats.cacheHits += 1 : this.stats.cacheMisses += 1;\n if (e36 \u0026\u0026 e36.g \u003c t2.g) {\n this.stats.successfulOptimizations += 1;\n for (const [t3, n3] of e36.pointModifications.entries()) {\n const e37 = this.segmentPointMap.get(t3);\n e37.x = n3.x ?? e37.x, e37.y = n3.y ?? e37.y, e37.z = n3.z ?? e37.z;\n }\n for (const e37 of this.activeSubSolver.unravelSection.allNodeIds)\n this.nodePfMap.set(e37, this.computeNodePf(this.nodeMap.get(e37)));\n } else\n this.stats.failedOptimizations += 1;\n this.activeSubSolver = null;\n }\n }\n visualize() {\n if (this.activeSubSolver)\n return this.activeSubSolver.visualize();\n const e36 = { lines: [], points: [], rects: [], circles: [], coordinateSystem: \"cartesian\", title: \"Unravel Multi Section Solver\" };\n for (const [t3, n3] of this.nodeMap.entries()) {\n const o4 = this.nodePfMap.get(t3) || 0, i3 = Math.min(o4, 1), r3 = `rgb(${Math.floor(255 * i3)}, ${Math.floor(255 * (1 - i3))}, 0)`;\n (this.attemptsToFixNode.get(t3) ?? 0) === 0 \u0026\u0026 i3 === 0 || e36.rects.push({ center: n3.center, label: [t3, `${n3.width.toFixed(2)}x${n3.height.toFixed(2)}`, `Pf: ${o4.toFixed(3)}`].join(`\n`), color: r3, width: n3.width / 8, height: n3.height / 8 });\n }\n for (const t3 of this.segmentPointMap.values()) {\n const n3 = this.dedupedSegmentMap.get(t3.segmentId);\n e36.points.push({ x: t3.x, y: t3.y, label: [t3.segmentPointId, t3.segmentId, `z: ${t3.z}`, `segment.availableZ: ${n3?.availableZ.join(\",\")}`].join(`\n`), color: this.colorMap[t3.connectionName] || \"#000\" });\n }\n const t2 = new Map;\n for (const e37 of this.segmentPointMap.values())\n t2.has(e37.segmentId) || t2.set(e37.segmentId, []), t2.get(e37.segmentId).push(e37);\n for (const [n3, o4] of t2.entries()) {\n if (o4.length \u003c 2)\n continue;\n const t3 = [...o4].sort((e37, t4) =\u003e e37.x !== t4.x ? e37.x - t4.x : e37.y - t4.y);\n for (let o5 = 0;o5 \u003c t3.length - 1; o5++)\n e36.lines.push({ points: [{ x: t3[o5].x, y: t3[o5].y }, { x: t3[o5 + 1].x, y: t3[o5 + 1].y }], strokeColor: this.colorMap[n3] || \"#000\" });\n }\n const n2 = new Set, o3 = Array.from(this.segmentPointMap.values());\n for (let t3 = 0;t3 \u003c o3.length; t3++) {\n const i3 = o3[t3];\n for (let r3 = t3 + 1;r3 \u003c o3.length; r3++) {\n const t4 = o3[r3];\n if (i3.connectionName !== t4.connectionName || i3.segmentId === t4.segmentId)\n continue;\n if (i3.capacityMeshNodeIds.some((e37) =\u003e t4.capacityMeshNodeIds.includes(e37))) {\n const o4 = `${i3.segmentPointId}-${t4.segmentPointId}`;\n if (n2.has(o4))\n continue;\n n2.add(o4);\n const r4 = i3.z === t4.z, s2 = i3.z;\n let a3;\n a3 = r4 ? s2 === 0 ? undefined : \"10 5\" : \"3 3 10\", e36.lines.push({ points: [{ x: i3.x, y: i3.y }, { x: t4.x, y: t4.y }], strokeDash: a3, strokeColor: this.colorMap[i3.connectionName] || \"#666\" });\n }\n }\n }\n return e36;\n }\n getNodesWithPortPoints() {\n if (!this.solved)\n throw new Error(\"CapacitySegmentToPointSolver not solved, can't give port points yet\");\n const e36 = new Map;\n for (const t2 of this.dedupedSegments) {\n const n2 = t2.nodePortSegmentId;\n for (const t3 of this.segmentIdToNodeIds.get(n2)) {\n const n3 = this.nodeMap.get(t3);\n e36.has(t3) || e36.set(t3, { capacityMeshNodeId: t3, portPoints: [], center: n3.center, width: n3.width, height: n3.height });\n }\n }\n for (const t2 of this.segmentPointMap.values())\n for (const n2 of t2.capacityMeshNodeIds) {\n const o3 = e36.get(n2);\n o3 \u0026\u0026 o3.portPoints.push({ x: t2.x, y: t2.y, z: t2.z, connectionName: t2.connectionName, rootConnectionName: t2.rootConnectionName });\n }\n return Array.from(e36.values());\n }\n};\nfunction Vj(e36, t2, n2, o3 = {}) {\n return { solverName: e36, solverClass: t2, getConstructorParams: n2, onSolved: o3.onSolved };\n}\nvar Wj = class extends ni {\n constructor(e36, t2 = {}) {\n super(), this.srj = e36, this.opts = t2, this.srj = e36, this.opts = { ...t2 }, this.MAX_ITERATIONS = 1e8, this.viaDiameter = Yo(e36).padDiameter, this.minTraceWidth = e36.minTraceWidth;\n const n2 = this.opts;\n if (n2.capacityDepth === undefined) {\n const t3 = e36.bounds.maxX - e36.bounds.minX, o3 = e36.bounds.maxY - e36.bounds.minY, i3 = Math.max(t3, o3), r3 = n2.targetMinCapacity ?? 0.5;\n n2.capacityDepth = Fz(i3, r3);\n }\n this.connMap = ei(e36), this.colorMap = Eo(e36, this.connMap), this.cacheProvider = n2.cacheProvider === undefined ? no() : n2.cacheProvider === null ? null : n2.cacheProvider, this.startTimeOfPhase = {}, this.endTimeOfPhase = {}, this.timeSpentOnPhase = {};\n }\n getSolverName() {\n return \"AutoroutingPipeline1_OriginalUnravel\";\n }\n netToPointPairsSolver;\n nodeSolver;\n nodeTargetMerger;\n edgeSolver;\n initialPathingSolver;\n pathingOptimizer;\n edgeToPortSegmentSolver;\n colorMap;\n segmentToPointSolver;\n unravelMultiSectionSolver;\n segmentToPointOptimizer;\n highDensityRouteSolver;\n highDensityStitchSolver;\n singleLayerNodeMerger;\n strawSolver;\n deadEndSolver;\n traceSimplificationSolver;\n viaDiameter;\n minTraceWidth;\n startTimeOfPhase;\n endTimeOfPhase;\n timeSpentOnPhase;\n activeSubSolver = null;\n connMap;\n srjWithPointPairs;\n capacityNodes = null;\n capacityEdges = null;\n cacheProvider = null;\n pipelineDef = [Vj(\"netToPointPairsSolver\", pB, (e36) =\u003e [e36.srj, e36.colorMap, ti(e36.srj)], { onSolved: (e36) =\u003e {\n e36.srjWithPointPairs = e36.netToPointPairsSolver?.getNewSimpleRouteJson(), e36.colorMap = Eo(e36.srjWithPointPairs, this.connMap), e36.connMap = ei(e36.srjWithPointPairs);\n } }), Vj(\"nodeSolver\", lj, (e36) =\u003e [e36.netToPointPairsSolver?.getNewSimpleRouteJson() || e36.srj, e36.opts], { onSolved: (e36) =\u003e {\n e36.capacityNodes = e36.nodeSolver?.finishedNodes;\n } }), Vj(\"singleLayerNodeMerger\", Ej, (e36) =\u003e [e36.nodeSolver?.finishedNodes], { onSolved: (e36) =\u003e {\n e36.capacityNodes = e36.singleLayerNodeMerger?.newNodes;\n } }), Vj(\"strawSolver\", Aj, (e36) =\u003e [{ nodes: e36.singleLayerNodeMerger?.newNodes }], { onSolved: (e36) =\u003e {\n e36.capacityNodes = e36.strawSolver?.getResultNodes();\n } }), Vj(\"edgeSolver\", ui, (e36) =\u003e [e36.capacityNodes], { onSolved: (e36) =\u003e {\n e36.capacityEdges = e36.edgeSolver?.edges;\n } }), Vj(\"deadEndSolver\", Nj, (e36) =\u003e [{ nodes: e36.capacityNodes, edges: e36.capacityEdges }], { onSolved: (e36) =\u003e {\n const t2 = e36.deadEndSolver?.removedNodeIds;\n e36.capacityNodes = e36.capacityNodes.filter((e37) =\u003e !t2.has(e37.capacityMeshNodeId)), e36.capacityEdges = e36.capacityEdges.filter((e37) =\u003e e37.nodeIds.every((e38) =\u003e !t2.has(e38)));\n } }), Vj(\"initialPathingSolver\", mj, (e36) =\u003e [{ simpleRouteJson: e36.srjWithPointPairs, nodes: e36.capacityNodes, edges: e36.capacityEdges || [], colorMap: e36.colorMap, hyperParameters: { MAX_CAPACITY_FACTOR: 1 } }]), Vj(\"pathingOptimizer\", wj, (e36) =\u003e [{ initialPathingSolver: e36.initialPathingSolver, simpleRouteJson: e36.srjWithPointPairs, nodes: e36.capacityNodes, edges: e36.capacityEdges || [], colorMap: e36.colorMap, cacheProvider: e36.cacheProvider, hyperParameters: { MAX_CAPACITY_FACTOR: 1 } }]), Vj(\"edgeToPortSegmentSolver\", nj, (e36) =\u003e [{ nodes: e36.capacityNodes, edges: e36.capacityEdges || [], capacityPaths: e36.pathingOptimizer?.getCapacityPaths() || [], colorMap: e36.colorMap }]), Vj(\"segmentToPointSolver\", hj, (e36) =\u003e {\n const t2 = [];\n return e36.edgeToPortSegmentSolver?.nodePortSegments \u0026\u0026 e36.edgeToPortSegmentSolver.nodePortSegments.forEach((e37) =\u003e {\n t2.push(...e37);\n }), [{ segments: t2, colorMap: e36.colorMap, nodes: e36.capacityNodes }];\n }), Vj(\"unravelMultiSectionSolver\", Hj, (e36) =\u003e [{ assignedSegments: e36.segmentToPointSolver?.solvedSegments || [], colorMap: e36.colorMap, nodes: e36.capacityNodes, cacheProvider: this.cacheProvider }]), Vj(\"highDensityRouteSolver\", Dz, (e36) =\u003e [{ nodePortPoints: e36.unravelMultiSectionSolver?.getNodesWithPortPoints() ?? e36.segmentToPointOptimizer?.getNodesWithPortPoints() ?? [], colorMap: e36.colorMap, connMap: e36.connMap, viaDiameter: e36.viaDiameter, traceWidth: e36.minTraceWidth }]), Vj(\"highDensityStitchSolver\", Rj, (e36) =\u003e [{ connections: e36.srjWithPointPairs.connections, hdRoutes: e36.highDensityRouteSolver.routes, colorMap: e36.colorMap, layerCount: e36.srj.layerCount, defaultViaDiameter: e36.viaDiameter }]), Vj(\"traceSimplificationSolver\", WF, (e36) =\u003e [{ hdRoutes: e36.highDensityStitchSolver.mergedHdRoutes, obstacles: e36.srj.obstacles, connMap: e36.connMap, colorMap: e36.colorMap, outline: e36.srj.outline, defaultViaDiameter: e36.viaDiameter, layerCount: e36.srj.layerCount }])];\n getConstructorParams() {\n return [this.srj, this.opts];\n }\n currentPipelineStepIndex = 0;\n _step() {\n const e36 = this.pipelineDef[this.currentPipelineStepIndex];\n if (!e36)\n return void (this.solved = true);\n if (this.activeSubSolver)\n return this.activeSubSolver.step(), void (this.activeSubSolver.solved ? (this.endTimeOfPhase[e36.solverName] = performance.now(), this.timeSpentOnPhase[e36.solverName] = this.endTimeOfPhase[e36.solverName] - this.startTimeOfPhase[e36.solverName], e36.onSolved?.(this), this.activeSubSolver = null, this.currentPipelineStepIndex++) : this.activeSubSolver.failed \u0026\u0026 (this.error = this.activeSubSolver?.error, this.failed = true, this.activeSubSolver = null));\n const t2 = e36.getConstructorParams(this);\n this.activeSubSolver = new e36.solverClass(...t2), this[e36.solverName] = this.activeSubSolver, this.timeSpentOnPhase[e36.solverName] = 0, this.startTimeOfPhase[e36.solverName] = performance.now();\n }\n solveUntilPhase(e36) {\n for (;this.getCurrentPhase() !== e36; )\n this.step();\n }\n getCurrentPhase() {\n return this.pipelineDef[this.currentPipelineStepIndex]?.solverName ?? \"none\";\n }\n visualize() {\n if (!this.solved \u0026\u0026 this.activeSubSolver)\n return this.activeSubSolver.visualize();\n const e36 = this.netToPointPairsSolver?.visualize(), t2 = this.nodeSolver?.visualize(), n2 = this.nodeTargetMerger?.visualize(), o3 = this.singleLayerNodeMerger?.visualize(), i3 = this.strawSolver?.visualize(), r3 = this.edgeSolver?.visualize(), s2 = this.deadEndSolver?.visualize(), a3 = this.initialPathingSolver?.visualize(), c3 = this.pathingOptimizer?.visualize(), l3 = this.edgeToPortSegmentSolver?.visualize(), h2 = this.segmentToPointSolver?.visualize(), d2 = this.unravelMultiSectionSolver?.visualize() ?? this.segmentToPointOptimizer?.visualize(), u2 = this.highDensityRouteSolver?.visualize(), p3 = this.highDensityStitchSolver?.visualize(), m2 = this.traceSimplificationSolver?.visualize(), g2 = this.srj.outline, f2 = [];\n if (f2.push({ points: [{ x: this.srj.bounds?.minX ?? -50, y: this.srj.bounds?.minY ?? -50 }, { x: this.srj.bounds?.maxX ?? 50, y: this.srj.bounds?.minY ?? -50 }, { x: this.srj.bounds?.maxX ?? 50, y: this.srj.bounds?.maxY ?? 50 }, { x: this.srj.bounds?.minX ?? -50, y: this.srj.bounds?.maxY ?? 50 }, { x: this.srj.bounds?.minX ?? -50, y: this.srj.bounds?.minY ?? -50 }], strokeColor: \"rgba(255,0,0,0.25)\" }), g2 \u0026\u0026 g2.length \u003e= 2) {\n const e37 = g2.map((e38) =\u003e ({ x: e38.x, y: e38.y }));\n e37.push({ ...e37[0] }), f2.push({ points: e37, strokeColor: \"rgba(0, 136, 255, 0.95)\" });\n }\n const _2 = Lo(this.srj), y2 = { points: [...this.srj.connections.flatMap((e37) =\u003e e37.pointsToConnect.map((t3) =\u003e ({ ...t3, layer: Bo(t3, this.srj.layerCount), label: `${e37.name} ${t3.pcb_port_id ?? \"\"}` })))], rects: [...(this.srj.obstacles ?? []).filter((e37) =\u003e !e37.isCopperPour).map((e37) =\u003e ({ ...e37, fill: e37.layers?.includes(\"top\") ? \"rgba(255,0,0,0.25)\" : e37.layers?.includes(\"bottom\") ? \"rgba(0,0,255,0.25)\" : \"rgba(255,0,0,0.25)\", layer: jo(e37, this.srj.layerCount), label: _2(e37) }))], lines: f2 }, b2 = [y2, e36, t2, n2, o3, i3, r3, s2, a3, c3, l3, h2, d2, u2 ? pi(y2, u2) : null, p3, m2, this.solved ? pi({ lines: f2 }, Wo(this.getOutputSimpleRouteJson())) : null].filter(Boolean);\n return pi(...b2);\n }\n preview() {\n if (this.highDensityRouteSolver) {\n const e36 = [];\n for (let t2 = this.highDensityRouteSolver.routes.length - 1;t2 \u003e= 0; t2--) {\n const n2 = this.highDensityRouteSolver.routes[t2];\n if (e36.push({ points: n2.route.map((e37) =\u003e ({ x: e37.x, y: e37.y })), strokeColor: this.colorMap[n2.connectionName] }), e36.length \u003e 200)\n break;\n }\n return { lines: e36 };\n }\n if (this.pathingOptimizer) {\n const e36 = [];\n for (const t2 of this.pathingOptimizer.connectionsWithNodes)\n t2.path \u0026\u0026 e36.push({ points: t2.path.map((e37) =\u003e ({ x: e37.center.x, y: e37.center.y })), strokeColor: this.colorMap[t2.connection.name] });\n return { lines: e36 };\n }\n return this.netToPointPairsSolver ? this.netToPointPairsSolver?.visualize() : {};\n }\n _getOutputHdRoutes() {\n return this.traceSimplificationSolver?.simplifiedHdRoutes ?? this.highDensityStitchSolver.mergedHdRoutes;\n }\n getOutputSimplifiedPcbTraces() {\n if (!this.solved || !this.highDensityRouteSolver)\n throw new Error(\"Cannot get output before solving is complete\");\n const e36 = [], t2 = this._getOutputHdRoutes();\n for (const n2 of this.netToPointPairsSolver?.newConnections ?? []) {\n const o3 = n2.__netConnectionName ?? this.srj.connections.find((e37) =\u003e e37.name === n2.name)?.__netConnectionName, i3 = t2.filter((e37) =\u003e e37.connectionName === n2.name);\n for (let t3 = 0;t3 \u003c i3.length; t3++) {\n const r3 = i3[t3], s2 = { type: \"pcb_trace\", pcb_trace_id: `${n2.name}_${t3}`, connection_name: o3 ?? n2.__rootConnectionNames?.[0] ?? n2.name, route: Ro(r3, this.srj.layerCount) };\n e36.push(s2);\n }\n }\n return e36;\n }\n getOutputSimpleRouteJson() {\n return { ...this.srj, traces: this.getOutputSimplifiedPcbTraces() };\n }\n};\nfunction Gj(e36) {\n const { pos: t2, segments: n2, dir: o3, keepoutRadius: i3 } = e36;\n let r3 = 1 / 0;\n const s2 = i3 / 4, a3 = { x: t2.x - o3.x * s2, y: t2.y - o3.y * s2 }, c3 = { x: t2.x + o3.x * s2, y: t2.y + o3.y * s2 };\n for (const e37 of n2) {\n const t3 = we(a3, c3, e37.start, e37.end);\n r3 = Math.min(r3, t3);\n }\n return r3;\n}\nfunction Uj(e36, t2, n2, o3) {\n const i3 = Zj(n2, o3, e36), r3 = Zj(n2, o3, t2), s2 = Zj(e36, t2, n2), a3 = Zj(e36, t2, o3);\n if ((i3 \u003e 0 \u0026\u0026 r3 \u003c 0 || i3 \u003c 0 \u0026\u0026 r3 \u003e 0) \u0026\u0026 (s2 \u003e 0 \u0026\u0026 a3 \u003c 0 || s2 \u003c 0 \u0026\u0026 a3 \u003e 0))\n return true;\n const c3 = 0.0001;\n return !!(Math.abs(i3) \u003c c3 \u0026\u0026 qj(n2, o3, e36)) || (!!(Math.abs(r3) \u003c c3 \u0026\u0026 qj(n2, o3, t2)) || (!!(Math.abs(s2) \u003c c3 \u0026\u0026 qj(e36, t2, n2)) || !!(Math.abs(a3) \u003c c3 \u0026\u0026 qj(e36, t2, o3))));\n}\nfunction Zj(e36, t2, n2) {\n return (n2.x - e36.x) * (t2.y - e36.y) - (t2.x - e36.x) * (n2.y - e36.y);\n}\nfunction qj(e36, t2, n2) {\n return n2.x \u003e= Math.min(e36.x, t2.x) - 0.0001 \u0026\u0026 n2.x \u003c= Math.max(e36.x, t2.x) + 0.0001 \u0026\u0026 n2.y \u003e= Math.min(e36.y, t2.y) - 0.0001 \u0026\u0026 n2.y \u003c= Math.max(e36.y, t2.y) + 0.0001;\n}\nfunction Jj(e36, t2, n2) {\n for (const o3 of n2)\n if (Uj(e36, t2, o3.start, o3.end))\n return false;\n return true;\n}\nvar Qj = 0.0001;\nfunction Kj(e36) {\n const t2 = e36.width / 2, n2 = e36.height / 2, o3 = e36.center.x, i3 = e36.center.y, r3 = { x: o3 - t2, y: i3 + n2 }, s2 = { x: o3 + t2, y: i3 + n2 }, a3 = { x: o3 - t2, y: i3 - n2 }, c3 = { x: o3 + t2, y: i3 - n2 };\n return [{ start: r3, end: s2 }, { start: s2, end: c3 }, { start: c3, end: a3 }, { start: a3, end: r3 }];\n}\nfunction e$(e36, t2, n2 = 0.1) {\n const o3 = t2.x - e36.x, i3 = t2.y - e36.y, r3 = Math.sqrt(o3 * o3 + i3 * i3);\n if (r3 === 0)\n return [];\n const s2 = -(i3 / r3), a3 = o3 / r3, c3 = n2 / 2;\n return [{ start: { x: e36.x + s2 * c3, y: e36.y + a3 * c3 }, end: { x: t2.x + s2 * c3, y: t2.y + a3 * c3 } }, { start: { x: e36.x - s2 * c3, y: e36.y - a3 * c3 }, end: { x: t2.x - s2 * c3, y: t2.y - a3 * c3 } }];\n}\nfunction t$(e36, t2, n2) {\n const o3 = Math.hypot(e36.start.x - t2.x, e36.start.y - t2.y), i3 = Math.hypot(e36.end.x - t2.x, e36.end.y - t2.y);\n if (o3 \u003c= n2 || i3 \u003c= n2)\n return true;\n const r3 = e36.end.x - e36.start.x, s2 = e36.end.y - e36.start.y, a3 = r3 * r3 + s2 * s2;\n if (a3 === 0)\n return false;\n const c3 = Math.max(0, Math.min(1, ((t2.x - e36.start.x) * r3 + (t2.y - e36.start.y) * s2) / a3)), l3 = e36.start.x + c3 * r3, h2 = e36.start.y + c3 * s2;\n return Math.hypot(l3 - t2.x, h2 - t2.y) \u003c= n2;\n}\nfunction n$(e36, t2, n2) {\n if (!n2 || n2.length === 0)\n return false;\n for (const o3 of n2) {\n const n3 = Math.abs(e36.x - o3.start.x) \u003c Qj \u0026\u0026 Math.abs(e36.y - o3.start.y) \u003c Qj \u0026\u0026 Math.abs(t2.x - o3.end.x) \u003c Qj \u0026\u0026 Math.abs(t2.y - o3.end.y) \u003c Qj, i3 = Math.abs(e36.x - o3.end.x) \u003c Qj \u0026\u0026 Math.abs(e36.y - o3.end.y) \u003c Qj \u0026\u0026 Math.abs(t2.x - o3.start.x) \u003c Qj \u0026\u0026 Math.abs(t2.y - o3.start.y) \u003c Qj;\n if (n3 || i3)\n return true;\n }\n return false;\n}\nfunction o$(e36, t2, n2, o3, i3) {\n const r3 = [];\n for (let s2 = 0;s2 \u003c e36.length - 1; s2++) {\n const a3 = e36[s2], c3 = e36[s2 + 1];\n n$(a3, c3, i3) || t$({ start: a3, end: c3 }, n2, o3 + t2) \u0026\u0026 r3.push(...e$(a3, c3, t2));\n }\n return r3;\n}\nvar i$ = 0.0001;\nfunction r$(e36, t2, n2, o3) {\n const i3 = t2.x - e36.x, r3 = t2.y - e36.y, s2 = o3.x - n2.x, a3 = o3.y - n2.y, c3 = i3 * a3 - r3 * s2;\n if (Math.abs(c3) \u003c 0.0000000001)\n return null;\n const l3 = n2.x - e36.x, h2 = n2.y - e36.y, d2 = (l3 * a3 - h2 * s2) / c3, u2 = (l3 * r3 - h2 * i3) / c3, p3 = 0.000001;\n return d2 \u003e p3 \u0026\u0026 d2 \u003c 0.999999 \u0026\u0026 u2 \u003e p3 \u0026\u0026 u2 \u003c 0.999999 ? { x: e36.x + d2 * i3, y: e36.y + d2 * r3 } : null;\n}\nfunction s$(e36, t2) {\n if (!t2 || t2.length === 0)\n return false;\n for (const n2 of t2)\n if (Math.abs(e36.x - n2.start.x) \u003c i$ \u0026\u0026 Math.abs(e36.y - n2.start.y) \u003c i$ || Math.abs(e36.x - n2.end.x) \u003c i$ \u0026\u0026 Math.abs(e36.y - n2.end.y) \u003c i$)\n return true;\n return false;\n}\nfunction a$(e36, t2, n2, o3) {\n if (!o3 || o3.length === 0)\n return false;\n for (let i3 = t2;i3 \u003c= n2; i3++)\n if (i3 \u003e= 0 \u0026\u0026 i3 \u003c e36.length \u0026\u0026 s$(e36[i3], o3))\n return true;\n return false;\n}\nvar c$ = 0.0001;\nvar l$ = class extends ni {\n constructor(e36) {\n super(), this.input = e36;\n const t2 = e36.srj?.layerCount ?? 2;\n this.input = { ...e36, obstacles: ca(e36.obstacles, t2) }, this.MAX_ITERATIONS = 1e6, this.originalHdRoutes = [...this.input.hdRoutes], this.hdRoutes = this.input.hdRoutes, this.KEEPOUT_RADIUS_SCHEDULE = e36.keepoutRadiusSchedule ?? [0.3, 0.5, 0.5], this.currentKeepoutRadius = this.KEEPOUT_RADIUS_SCHEDULE[0] ?? 0.15, this.unprocessedRoutes = [...this.hdRoutes], this.smoothedCursorRoutes = [...this.unprocessedRoutes];\n const n2 = [...this.input.obstacles, ...this.getJumperPadObstacles()];\n this.obstacleSHI = new ZF(\"flatbush\", n2), this.boardOutlineRoutes = this.createBoardOutlineRoutes(), this.hdRouteSHI = new xr([...this.hdRoutes, ...this.boardOutlineRoutes]);\n for (const [e37, t3, n3] of this.hdRoutes.flatMap((e38) =\u003e [[e38.route[0], e38.connectionName, e38.rootConnectionName], [e38.route[e38.route.length - 1], e38.connectionName, e38.rootConnectionName]])) {\n const o3 = this.obstacleSHI.searchArea(e37.x, e37.y, 0.01, 0.01).filter((t4) =\u003e t4.__zLayers?.includes(e37.z));\n if (o3.length === 0)\n continue;\n const i3 = o3[0];\n this.input.connMap.addConnections([[t3, n3, ...i3.offBoardConnectsTo ?? [], i3.obstacleId, ...i3.connectedTo].filter(Boolean)]);\n }\n }\n getSolverName() {\n return \"TraceKeepoutSolver\";\n }\n originalHdRoutes;\n hdRoutes;\n redrawnHdRoutes = [];\n KEEPOUT_RADIUS_SCHEDULE;\n currentScheduleIndex = 0;\n currentKeepoutRadius;\n unprocessedRoutes = [];\n smoothedCursorRoutes = [];\n processedRoutes = [];\n currentTrace = null;\n cursorPosition = null;\n lastCursorPosition = null;\n drawPosition = null;\n currentTraceSegmentIndex = 0;\n currentTraceSegmentT = 0;\n recordedDrawPositions = [];\n lastCollidingSegments = [];\n currentTraceJumperSegments = new Map;\n obstacleSHI;\n hdRouteSHI;\n boardOutlineRoutes = [];\n getSmoothDistance() {\n return this.currentKeepoutRadius;\n }\n getJumperPadObstacles() {\n const e36 = [];\n if (!this.input.jumpers)\n return e36;\n for (const t2 of this.input.jumpers)\n for (const n2 of t2.pads)\n e36.push({ ...n2, __zLayers: [0] });\n return e36;\n }\n buildJumperSegmentMap(e36) {\n const t2 = new Map;\n if (!e36.jumpers || e36.jumpers.length === 0)\n return t2;\n const n2 = e36.route;\n for (const o3 of e36.jumpers) {\n let e37 = -1, i3 = 1 / 0;\n for (let t3 = 0;t3 \u003c n2.length - 1; t3++) {\n const r3 = n2[t3], s2 = n2[t3 + 1], a3 = Math.sqrt((r3.x - o3.start.x) ** 2 + (r3.y - o3.start.y) ** 2), c3 = Math.sqrt((s2.x - o3.end.x) ** 2 + (s2.y - o3.end.y) ** 2), l3 = a3 + c3, h2 = Math.sqrt((r3.x - o3.end.x) ** 2 + (r3.y - o3.end.y) ** 2), d2 = Math.sqrt((s2.x - o3.start.x) ** 2 + (s2.y - o3.start.y) ** 2), u2 = h2 + d2, p3 = Math.min(l3, u2);\n (l3 \u003c= u2 ? a3 : h2) \u003c 1 \u0026\u0026 (l3 \u003c= u2 ? c3 : d2) \u003c 1 \u0026\u0026 p3 \u003c i3 \u0026\u0026 (i3 = p3, e37 = t3);\n }\n e37 \u003e= 0 \u0026\u0026 t2.set(e37, o3);\n }\n return t2;\n }\n _step() {\n if (!this.currentTrace) {\n const e37 = this.unprocessedRoutes.shift();\n if (!e37)\n return this.currentScheduleIndex++, this.currentScheduleIndex \u003c this.KEEPOUT_RADIUS_SCHEDULE.length ? (this.currentKeepoutRadius = this.KEEPOUT_RADIUS_SCHEDULE[this.currentScheduleIndex], this.unprocessedRoutes = Sr([...this.processedRoutes], this.currentScheduleIndex), this.smoothedCursorRoutes = [...this.unprocessedRoutes], this.processedRoutes = [], void (this.hdRouteSHI = new xr([...this.unprocessedRoutes, ...this.boardOutlineRoutes]))) : (this.redrawnHdRoutes = this.processedRoutes, void (this.solved = true));\n if (this.currentTrace = e37, this.currentTrace.route.length \u003c 2)\n return this.processedRoutes.push(this.currentTrace), void (this.currentTrace = null);\n this.currentTraceJumperSegments = this.buildJumperSegmentMap(this.currentTrace);\n const t3 = this.currentTrace.route[0];\n return this.cursorPosition = { ...t3 }, this.lastCursorPosition = { ...t3 }, this.drawPosition = { x: t3.x, y: t3.y }, this.currentTraceSegmentIndex = 0, this.currentTraceSegmentT = 0, void (this.recordedDrawPositions = [{ ...t3 }]);\n }\n this.lastCursorPosition = { ...this.cursorPosition };\n const e36 = this.stepCursorForward();\n if (e36 === \"end\")\n return void this.finalizeCurrentTrace();\n if (e36 === \"jumper\")\n return void (this.drawPosition = { x: this.cursorPosition.x, y: this.cursorPosition.y });\n const t2 = this.getCollidingSegments(this.cursorPosition);\n this.lastCollidingSegments = t2;\n const n2 = function(e37) {\n const { cursorPosition: t3, lastCursorPosition: n3, collidingSegments: o4, keepoutRadius: i3 } = e37;\n if (o4.length === 0)\n return null;\n const r3 = 0.0001, s2 = t3.x - n3.x, a3 = t3.y - n3.y, c3 = Math.sqrt(s2 * s2 + a3 * a3), l3 = c3 \u003e r3 ? { x: s2 / c3, y: a3 / c3 } : { x: 1, y: 0 }, h2 = -l3.y, d2 = l3.x, u2 = Gj({ pos: t3, segments: o4, dir: l3, keepoutRadius: i3 });\n if (u2 \u003e= i3)\n return null;\n for (let e38 = 1;e38 \u003c= 20; e38++) {\n const n4 = e38 / 20 * i3, r4 = { x: t3.x + h2 * n4, y: t3.y + d2 * n4 }, s3 = Gj({ pos: r4, segments: o4, dir: l3, keepoutRadius: i3 }), a4 = { x: t3.x - h2 * n4, y: t3.y - d2 * n4 }, c4 = Gj({ pos: a4, segments: o4, dir: l3, keepoutRadius: i3 }), u3 = s3 \u003e= i3 \u0026\u0026 Jj(t3, r4, o4), p4 = c4 \u003e= i3 \u0026\u0026 Jj(t3, a4, o4);\n if (u3 \u0026\u0026 p4)\n return s3 \u003e= c4 ? r4 : a4;\n if (u3)\n return r4;\n if (p4)\n return a4;\n }\n const p3 = i3, m2 = [];\n for (let e38 = -60;e38 \u003c= 60; e38++) {\n const n4 = e38 / 60 * p3, r4 = { x: t3.x + h2 * n4, y: t3.y + d2 * n4 }, s3 = Gj({ pos: r4, segments: o4, dir: l3, keepoutRadius: i3 }), a4 = Jj(t3, r4, o4);\n m2.push({ pos: r4, clearance: s3, dist: Math.abs(n4), pathClear: a4, index: e38 });\n }\n const g2 = m2.filter((e38) =\u003e e38.pathClear), f2 = m2.findIndex((e38) =\u003e e38.index === 0), _2 = f2 \u003e= 0 ? f2 : Math.floor(m2.length / 2);\n let y2 = null;\n for (let e38 = _2 + 1;e38 \u003c m2.length - 1; e38++) {\n const t4 = m2[e38 - 1], n4 = m2[e38], o5 = m2[e38 + 1];\n if (n4.clearance \u003e= t4.clearance \u0026\u0026 n4.clearance \u003e= o5.clearance) {\n y2 = n4;\n break;\n }\n }\n let b2 = null;\n for (let e38 = _2 - 1;e38 \u003e 0; e38--) {\n const t4 = m2[e38 - 1], n4 = m2[e38], o5 = m2[e38 + 1];\n if (n4.clearance \u003e= t4.clearance \u0026\u0026 n4.clearance \u003e= o5.clearance) {\n b2 = n4;\n break;\n }\n }\n let x2 = null, v2 = null;\n if (g2.length \u003e 0) {\n const e38 = g2.findIndex((e39) =\u003e e39.index === 0), t4 = e38 \u003e= 0 ? e38 : Math.floor(g2.length / 2);\n for (let e39 = t4 + 1;e39 \u003c g2.length - 1; e39++) {\n const t5 = g2[e39 - 1], n4 = g2[e39], o5 = g2[e39 + 1];\n if (n4.clearance \u003e= t5.clearance \u0026\u0026 n4.clearance \u003e= o5.clearance) {\n x2 = n4;\n break;\n }\n }\n for (let e39 = t4 - 1;e39 \u003e 0; e39--) {\n const t5 = g2[e39 - 1], n4 = g2[e39], o5 = g2[e39 + 1];\n if (n4.clearance \u003e= t5.clearance \u0026\u0026 n4.clearance \u003e= o5.clearance) {\n v2 = n4;\n break;\n }\n }\n }\n const I2 = [y2, b2, x2, v2, m2.find((e38) =\u003e e38.index === 0)].filter((e38) =\u003e e38 != null), S2 = new Set, C = I2.filter((e38) =\u003e {\n const t4 = `${e38.pos.x.toFixed(6)},${e38.pos.y.toFixed(6)}`;\n return !S2.has(t4) \u0026\u0026 (S2.add(t4), true);\n });\n if (C.length === 0) {\n let e38 = m2[0];\n if (!e38)\n return null;\n for (const t4 of m2)\n t4.clearance \u003e e38.clearance \u0026\u0026 (e38 = t4);\n return Math.sqrt((e38.pos.x - t3.x) ** 2 + (e38.pos.y - t3.y) ** 2) \u003e r3 ? e38.pos : null;\n }\n let P;\n if (u2 \u003c 0.15 * i3) {\n P = C[0];\n for (const e38 of C)\n e38.clearance \u003e P.clearance \u0026\u0026 (P = e38);\n } else {\n const e38 = C.filter((e39) =\u003e e39.pathClear), t4 = e38.length \u003e 0 ? e38 : C;\n P = t4[0];\n for (const e39 of t4)\n e39.clearance \u003e P.clearance \u0026\u0026 (P = e39);\n }\n return Math.sqrt((P.pos.x - t3.x) ** 2 + (P.pos.y - t3.y) ** 2) \u003e r3 ? P.pos : null;\n }({ cursorPosition: this.cursorPosition, lastCursorPosition: this.lastCursorPosition, collidingSegments: t2, keepoutRadius: this.currentKeepoutRadius });\n this.drawPosition = n2 ?? { ...this.cursorPosition };\n const o3 = this.recordedDrawPositions[this.recordedDrawPositions.length - 1];\n if (o3 \u0026\u0026 this.drawPosition) {\n const e37 = { x: o3.x, y: o3.y, z: o3.z }, t3 = { x: this.drawPosition.x, y: this.drawPosition.y, z: this.cursorPosition.z };\n this.segmentIntersectsOtherRoutes(e37, t3) \u0026\u0026 (this.drawPosition = { ...this.cursorPosition });\n }\n this.recordedDrawPositions.push({ x: this.drawPosition.x, y: this.drawPosition.y, z: this.cursorPosition.z });\n }\n getStepDistance() {\n return this.currentKeepoutRadius / 2;\n }\n getJumperAtCurrentSegmentStart() {\n return this.currentTraceSegmentT \u003e c$ ? null : this.currentTraceJumperSegments.get(this.currentTraceSegmentIndex) ?? null;\n }\n stepCursorForward() {\n if (!this.currentTrace || !this.cursorPosition)\n return \"end\";\n const e36 = this.currentTrace.route;\n let t2 = this.getStepDistance();\n for (;t2 \u003e 0; ) {\n if (this.currentTraceSegmentIndex \u003e= e36.length - 1)\n return \"end\";\n const n2 = this.getJumperAtCurrentSegmentStart();\n if (n2) {\n const t3 = e36[this.currentTraceSegmentIndex], o4 = e36[this.currentTraceSegmentIndex + 1], i4 = Math.sqrt((t3.x - n2.start.x) ** 2 + (t3.y - n2.start.y) ** 2), r4 = Math.sqrt((t3.x - n2.end.x) ** 2 + (t3.y - n2.end.y) ** 2), s3 = i4 \u003c= r4 ? n2.start : n2.end, a4 = i4 \u003c= r4 ? n2.end : n2.start;\n return this.recordedDrawPositions.push({ x: s3.x, y: s3.y, z: t3.z, insideJumperPad: true }), this.recordedDrawPositions.push({ x: a4.x, y: a4.y, z: o4.z, insideJumperPad: true }), this.cursorPosition = { x: a4.x, y: a4.y, z: o4.z }, this.currentTraceSegmentIndex++, this.currentTraceSegmentT = 0, \"jumper\";\n }\n const o3 = e36[this.currentTraceSegmentIndex], i3 = e36[this.currentTraceSegmentIndex + 1], r3 = i3.x - o3.x, s2 = i3.y - o3.y, a3 = Math.sqrt(r3 * r3 + s2 * s2);\n if (a3 === 0) {\n this.currentTraceSegmentIndex++, this.currentTraceSegmentT = 0;\n continue;\n }\n const c3 = this.currentTraceSegmentT * a3, l3 = a3 - c3;\n if (t2 \u003c= l3) {\n const e37 = c3 + t2;\n return this.currentTraceSegmentT = e37 / a3, this.cursorPosition = { x: o3.x + r3 * this.currentTraceSegmentT, y: o3.y + s2 * this.currentTraceSegmentT, z: o3.z }, \"stepped\";\n }\n if (t2 -= l3, this.currentTraceSegmentIndex++, this.currentTraceSegmentT = 0, this.currentTraceSegmentIndex \u003e= e36.length - 1) {\n const t3 = e36[e36.length - 1];\n return this.cursorPosition = { ...t3 }, \"end\";\n }\n }\n return \"stepped\";\n }\n getCollidingSegments(e36) {\n if (!this.currentTrace)\n return [];\n const t2 = this.currentTrace.rootConnectionName ?? this.currentTrace.connectionName, n2 = 2 * this.currentKeepoutRadius, o3 = [], i3 = this.obstacleSHI.searchArea(e36.x, e36.y, n2, n2).filter((t3) =\u003e t3.__zLayers?.includes(e36.z));\n for (const n3 of i3) {\n if (n3.__zLayers \u0026\u0026 !n3.__zLayers.includes(e36.z))\n continue;\n if (n3.connectedTo.includes(t2))\n continue;\n if (n3.obstacleId \u0026\u0026 this.input.connMap.areIdsConnected(t2, n3.obstacleId))\n continue;\n let i4 = false;\n for (const e37 of n3.connectedTo)\n if (this.input.connMap.areIdsConnected(t2, e37)) {\n i4 = true;\n break;\n }\n i4 || o3.push(...Kj(n3));\n }\n const r3 = this.hdRouteSHI.getConflictingRoutesNearPoint({ x: e36.x, y: e36.y, z: e36.z }, n2);\n for (const { conflictingRoute: i4 } of r3) {\n const r4 = i4.rootConnectionName ?? i4.connectionName;\n if (r4 === t2)\n continue;\n if (this.input.connMap.areIdsConnected(t2, r4))\n continue;\n const s2 = i4.traceThickness ?? 0.15;\n o3.push(...o$(i4.route, s2, { x: e36.x, y: e36.y }, n2, i4.jumpers));\n }\n return o3;\n }\n positionHasCollision(e36, t2 = 0) {\n const n2 = this.getCollidingSegments(e36);\n for (const o3 of n2)\n if (pe(e36, o3.start, o3.end) \u003c= this.currentKeepoutRadius + t2)\n return true;\n return false;\n }\n segmentIntersectsOtherRoutes(e36, t2) {\n if (!this.currentTrace)\n return false;\n const n2 = this.currentTrace.rootConnectionName ?? this.currentTrace.connectionName, o3 = [...this.unprocessedRoutes, ...this.smoothedCursorRoutes, ...this.processedRoutes];\n for (const i3 of o3) {\n if ((i3.rootConnectionName ?? i3.connectionName) !== n2)\n for (let n3 = 0;n3 \u003c i3.route.length - 1; n3++) {\n const o4 = i3.route[n3], r3 = i3.route[n3 + 1];\n if ((o4.z === e36.z || r3.z === e36.z) \u0026\u0026 ((!o4.insideJumperPad || !r3.insideJumperPad) \u0026\u0026 he({ x: e36.x, y: e36.y }, { x: t2.x, y: t2.y }, { x: o4.x, y: o4.y }, { x: r3.x, y: r3.y })))\n return true;\n }\n }\n return false;\n }\n finalizeCurrentTrace() {\n if (!this.currentTrace)\n return;\n const e36 = this.currentTrace.route[this.currentTrace.route.length - 1], t2 = this.recordedDrawPositions[this.recordedDrawPositions.length - 1];\n t2 \u0026\u0026 t2.x === e36.x \u0026\u0026 t2.y === e36.y || this.recordedDrawPositions.push({ ...e36 });\n const n2 = function(e37, t3) {\n if (e37.length \u003c 4)\n return e37;\n let n3 = [...e37], o4 = true;\n for (;o4; ) {\n o4 = false;\n for (let e38 = 0;e38 \u003c n3.length - 1 \u0026\u0026 !o4; e38++) {\n const i3 = n3[e38], r3 = n3[e38 + 1];\n if (i3.z === r3.z)\n for (let s2 = e38 + 2;s2 \u003c n3.length - 1 \u0026\u0026 !o4; s2++) {\n if (s2 === e38 + 1)\n continue;\n const a3 = n3[s2], c3 = n3[s2 + 1];\n if (a3.z !== c3.z || i3.z !== a3.z)\n continue;\n const l3 = r$(i3, r3, a3, c3);\n if (l3) {\n if (a$(n3, e38 + 1, s2, t3))\n continue;\n const r4 = [];\n for (let t4 = 0;t4 \u003c= e38; t4++)\n r4.push(n3[t4]);\n r4.push({ x: l3.x, y: l3.y, z: i3.z });\n for (let e39 = s2 + 1;e39 \u003c n3.length; e39++)\n r4.push(n3[e39]);\n n3 = r4, o4 = true;\n }\n }\n }\n }\n return n3;\n }(this.simplifyRoute(this.recordedDrawPositions, this.currentTrace.jumpers), this.currentTrace.jumpers), o3 = { connectionName: this.currentTrace.connectionName, rootConnectionName: this.currentTrace.rootConnectionName, traceThickness: this.currentTrace.traceThickness, viaDiameter: this.currentTrace.viaDiameter, route: n2, vias: [...this.currentTrace.vias], jumpers: this.currentTrace.jumpers };\n this.processedRoutes.push(o3), this.hdRouteSHI.removeRoute(this.currentTrace.connectionName), this.hdRouteSHI.addRoute(o3), this.currentTrace = null, this.cursorPosition = null, this.lastCursorPosition = null, this.drawPosition = null, this.recordedDrawPositions = [];\n }\n isJumperEndpoint(e36, t2) {\n if (!t2 || t2.length === 0)\n return false;\n for (const n2 of t2)\n if (Math.abs(e36.x - n2.start.x) \u003c c$ \u0026\u0026 Math.abs(e36.y - n2.start.y) \u003c c$ || Math.abs(e36.x - n2.end.x) \u003c c$ \u0026\u0026 Math.abs(e36.y - n2.end.y) \u003c c$)\n return true;\n return false;\n }\n simplifyRoute(e36, t2) {\n if (e36.length \u003c= 2)\n return e36;\n const n2 = [e36[0]];\n for (let o3 = 1;o3 \u003c e36.length - 1; o3++) {\n const i3 = n2[n2.length - 1], r3 = e36[o3], s2 = e36[o3 + 1];\n if (this.isJumperEndpoint(r3, t2)) {\n n2.push(r3);\n continue;\n }\n if (r3.z !== i3.z || r3.z !== s2.z) {\n n2.push(r3);\n continue;\n }\n const a3 = r3.x - i3.x, c3 = r3.y - i3.y, l3 = s2.x - r3.x, h2 = a3 * (s2.y - r3.y) - c3 * l3, d2 = 0.000001;\n Math.abs(h2) \u003e d2 \u0026\u0026 n2.push(r3);\n }\n return n2.push(e36[e36.length - 1]), n2;\n }\n createBoardOutlineRoutes() {\n const e36 = [];\n if (!this.input.srj)\n return e36;\n const { outline: t2, bounds: n2 } = this.input.srj;\n let o3;\n o3 = t2 \u0026\u0026 t2.length \u003e= 3 ? t2 : [{ x: n2.minX, y: n2.minY }, { x: n2.maxX, y: n2.minY }, { x: n2.maxX, y: n2.maxY }, { x: n2.minX, y: n2.maxY }];\n const i3 = this.input.srj.layerCount ?? 2;\n for (let t3 = 0;t3 \u003c o3.length; t3++) {\n const n3 = o3[t3], r3 = o3[(t3 + 1) % o3.length];\n for (let o4 = 0;o4 \u003c i3; o4++)\n e36.push({ connectionName: `__board_outline___${t3}_z${o4}`, traceThickness: 0.01, viaDiameter: 0, route: [{ x: n3.x, y: n3.y, z: o4 }, { x: r3.x, y: r3.y, z: o4 }], vias: [] });\n }\n return e36;\n }\n visualize() {\n const e36 = { lines: [], points: [], rects: [], circles: [], coordinateSystem: \"cartesian\", title: `Trace Keepout Solver (radius: ${this.currentKeepoutRadius.toFixed(2)})` };\n for (const t2 of this.originalHdRoutes)\n if (t2.route.length !== 0)\n for (let n2 = 0;n2 \u003c t2.route.length - 1; n2++) {\n const o3 = t2.route[n2], i3 = t2.route[n2 + 1];\n o3.z === i3.z \u0026\u0026 e36.lines.push({ points: [{ x: o3.x, y: o3.y }, { x: i3.x, y: i3.y }], strokeColor: \"rgba(0,0,0,0.25)\", strokeWidth: 1.5 * (t2.traceThickness ?? 0.15) });\n }\n if (this.input.jumpers)\n for (const t2 of this.input.jumpers) {\n for (const n2 of t2.pads) {\n const t3 = n2.connectedTo.length \u003e 0 ? n2.connectedTo.join(\", \") : \"unused\", o3 = n2.connectedTo.length \u003e 0 ? this.input.colorMap[n2.connectedTo[0]] || \"#888888\" : \"rgba(128, 128, 128, 0.5)\";\n e36.rects.push({ center: n2.center, width: n2.width, height: n2.height, fill: o3, stroke: \"rgba(0, 0, 0, 0.5)\", label: `Jumper pad (${t3})` });\n }\n t2.pads.length \u003e= 2 \u0026\u0026 e36.lines.push({ points: [t2.pads[0].center, t2.pads[1].center], strokeColor: \"rgba(100, 100, 100, 0.8)\", strokeWidth: 0.2, label: \"Jumper body\" });\n }\n for (const t2 of this.input.obstacles) {\n let n2 = \"rgba(128, 128, 128, 0.2)\";\n const o3 = t2.__zLayers?.includes(0), i3 = t2.__zLayers?.includes(1);\n o3 \u0026\u0026 i3 ? n2 = \"rgba(128, 0, 128, 0.2)\" : o3 ? n2 = \"rgba(255, 0, 0, 0.2)\" : i3 \u0026\u0026 (n2 = \"rgba(0, 0, 255, 0.2)\"), e36.rects.push({ center: t2.center, width: t2.width, height: t2.height, fill: n2, label: `Obstacle (Z: ${t2.__zLayers?.join(\", \")})` });\n }\n if (this.input.srj) {\n const { outline: t2, bounds: n2 } = this.input.srj;\n let o3;\n o3 = t2 \u0026\u0026 t2.length \u003e= 3 ? t2 : [{ x: n2.minX, y: n2.minY }, { x: n2.maxX, y: n2.minY }, { x: n2.maxX, y: n2.maxY }, { x: n2.minX, y: n2.maxY }];\n for (let t3 = 0;t3 \u003c o3.length; t3++) {\n const n3 = o3[t3], i3 = o3[(t3 + 1) % o3.length];\n e36.lines.push({ points: [{ x: n3.x, y: n3.y }, { x: i3.x, y: i3.y }], strokeColor: \"rgba(0, 128, 0, 0.6)\", strokeWidth: 0.1, label: \"Board outline\" });\n }\n }\n for (const t2 of this.processedRoutes) {\n if (t2.route.length === 0)\n continue;\n const n2 = this.input.colorMap[t2.connectionName] || \"#888888\", o3 = new Set;\n if (t2.jumpers \u0026\u0026 t2.jumpers.length \u003e 0)\n for (const e37 of t2.jumpers)\n for (let n3 = 0;n3 \u003c t2.route.length - 1; n3++) {\n const i3 = t2.route[n3], r3 = t2.route[n3 + 1], s2 = Math.abs(i3.x - e37.start.x) \u003c c$ \u0026\u0026 Math.abs(i3.y - e37.start.y) \u003c c$ \u0026\u0026 Math.abs(r3.x - e37.end.x) \u003c c$ \u0026\u0026 Math.abs(r3.y - e37.end.y) \u003c c$, a3 = Math.abs(i3.x - e37.end.x) \u003c c$ \u0026\u0026 Math.abs(i3.y - e37.end.y) \u003c c$ \u0026\u0026 Math.abs(r3.x - e37.start.x) \u003c c$ \u0026\u0026 Math.abs(r3.y - e37.start.y) \u003c c$;\n if (s2 || a3) {\n o3.add(n3);\n break;\n }\n }\n for (let n3 = 0;n3 \u003c t2.route.length - 1; n3++) {\n const i3 = t2.route[n3], r3 = t2.route[n3 + 1];\n o3.has(n3) ? e36.lines.push({ points: [{ x: i3.x, y: i3.y }, { x: r3.x, y: r3.y }], strokeColor: \"rgba(128, 128, 128, 0.6)\", strokeDash: \"2 2\", label: `${t2.connectionName} (jumper segment - fixed)` }) : i3.z === r3.z \u0026\u0026 e36.lines.push({ points: [{ x: i3.x, y: i3.y }, { x: r3.x, y: r3.y }], strokeColor: i3.z === 0 ? \"red\" : \"blue\", strokeWidth: t2.traceThickness, label: `${t2.connectionName} (z=${i3.z})` });\n }\n for (const n3 of t2.vias)\n e36.circles.push({ center: { x: n3.x, y: n3.y }, radius: t2.viaDiameter / 2, fill: \"rgba(255, 0, 255, 0.5)\", label: `${t2.connectionName} via` });\n if (t2.jumpers \u0026\u0026 t2.jumpers.length \u003e 0) {\n const o4 = fB(t2.jumpers, { color: n2, label: t2.connectionName });\n e36.rects.push(...o4.rects ?? []), e36.lines.push(...o4.lines ?? []);\n }\n }\n if (this.currentTrace \u0026\u0026 this.recordedDrawPositions.length \u003e 0) {\n this.input.colorMap[this.currentTrace.connectionName];\n for (let t2 = 0;t2 \u003c this.recordedDrawPositions.length - 1; t2++) {\n const n2 = this.recordedDrawPositions[t2], o3 = this.recordedDrawPositions[t2 + 1];\n e36.lines.push({ points: [{ x: n2.x, y: n2.y }, { x: o3.x, y: o3.y }], strokeColor: \"green\", strokeWidth: this.currentTrace.traceThickness });\n }\n if (this.cursorPosition \u0026\u0026 (e36.circles.push({ center: { x: this.cursorPosition.x, y: this.cursorPosition.y }, radius: this.currentKeepoutRadius, stroke: \"orange\", fill: \"none\" }), e36.points.push({ x: this.cursorPosition.x, y: this.cursorPosition.y, color: \"orange\", label: \"Cursor\" }), this.lastCursorPosition)) {\n const t2 = this.cursorPosition.x - this.lastCursorPosition.x, n2 = this.cursorPosition.y - this.lastCursorPosition.y, o3 = Math.sqrt(t2 * t2 + n2 * n2), i3 = o3 \u003e 0.0001 ? { x: t2 / o3, y: n2 / o3 } : { x: 1, y: 0 }, r3 = this.currentKeepoutRadius / 4, s2 = { x: this.cursorPosition.x - i3.x * r3, y: this.cursorPosition.y - i3.y * r3 }, a3 = { x: this.cursorPosition.x + i3.x * r3, y: this.cursorPosition.y + i3.y * r3 };\n e36.lines.push({ points: [s2, a3], strokeColor: \"cyan\", strokeWidth: 0.05, label: \"Projected segment\" });\n }\n this.drawPosition \u0026\u0026 e36.points.push({ x: this.drawPosition.x, y: this.drawPosition.y, color: \"lime\", label: \"Draw\" });\n for (const t2 of this.lastCollidingSegments)\n e36.lines.push({ points: [{ x: t2.start.x, y: t2.start.y }, { x: t2.end.x, y: t2.end.y }], strokeColor: \"rgba(255, 0, 255, 0.8)\", strokeWidth: 0.02, label: \"Colliding segment\" });\n }\n if (!this.solved) {\n for (const t2 of this.smoothedCursorRoutes)\n if (t2.route.length !== 0)\n for (let n2 = 0;n2 \u003c t2.route.length - 1; n2++) {\n const o3 = t2.route[n2], i3 = t2.route[n2 + 1];\n o3.z === i3.z \u0026\u0026 e36.lines.push({ points: [{ x: o3.x, y: o3.y }, { x: i3.x, y: i3.y }], strokeColor: \"gray\" });\n }\n }\n return e36;\n }\n getRedrawnHdRoutes() {\n return this.redrawnHdRoutes;\n }\n};\nvar h$ = class extends ni {\n constructor(e36) {\n super(), this.input = e36, this.unprocessedObstacles = ca(this.input.srj.obstacles, this.input.srj.layerCount).filter((e37) =\u003e e37.offBoardConnectsTo \u0026\u0026 e37.offBoardConnectsTo.length \u003e 0), this.unprocessedObstacles.forEach((e37, t2) =\u003e {\n e37.obstacleId = e37.obstacleId ?? `__obs${t2}`;\n }), this.offBoardConnMap = new mB({}), this.offBoardConnMap.addConnections(this.unprocessedObstacles.filter((e37) =\u003e e37.offBoardConnectsTo?.length).map((e37) =\u003e [e37.obstacleId, ...e37.offBoardConnectsTo ?? []])), this.nodeTree = new di(this.input.capacityMeshNodes);\n }\n getSolverName() {\n return \"RelateNodesToOffBoardConnectionsSolver\";\n }\n unprocessedObstacles;\n nodeTree;\n offBoardConnMap;\n nodesInNet = new Map;\n lastProcessedObstacle;\n _step() {\n const e36 = this.unprocessedObstacles.pop();\n if (this.lastProcessedObstacle = e36, !e36)\n return void (this.solved = true);\n const t2 = this.offBoardConnMap.getNetConnectedToId(e36.obstacleId), n2 = this.nodeTree.getNodesInArea(e36.center.x, e36.center.y, 0.01, 0.01).filter((t3) =\u003e t3.availableZ.some((t4) =\u003e e36.__zLayers?.includes(t4))).filter((t3) =\u003e Math.abs(t3.center.x - e36.center.x) \u003c 0.01 \u0026\u0026 Math.abs(t3.center.y - e36.center.y) \u003c 0.01), o3 = n2.map((e37) =\u003e e37.capacityMeshNodeId), i3 = this.nodesInNet.get(t2) ?? [], r3 = [...i3.map((e37) =\u003e e37.capacityMeshNodeId), ...o3];\n for (const e37 of i3)\n e37._offBoardConnectedCapacityMeshNodeIds = r3;\n for (const e37 of n2)\n e37._offBoardConnectedCapacityMeshNodeIds = r3, e37._offBoardConnectionId = t2;\n this.nodesInNet.set(t2, [...i3, ...n2]);\n }\n getOutput() {\n return { capacityNodes: this.input.capacityMeshNodes };\n }\n visualize() {\n const e36 = { rects: [], lines: [], points: [], circles: [] }, t2 = new Set;\n for (const [e37, n2] of this.nodesInNet)\n for (const e38 of n2)\n t2.add(e38.capacityMeshNodeId);\n for (const n2 of this.input.capacityMeshNodes)\n t2.has(n2.capacityMeshNodeId) || e36.rects.push({ center: n2.center, width: n2.width - 0.1, height: n2.height - 0.1, fill: \"rgba(0, 0, 0, 0.2)\" });\n this.lastProcessedObstacle \u0026\u0026 e36.rects.push({ center: this.lastProcessedObstacle.center, width: this.lastProcessedObstacle.width, height: this.lastProcessedObstacle.height, fill: \"rgba(255, 0, 0, 0.5)\" });\n for (const [t3, n2] of this.nodesInNet.entries()) {\n for (const o3 of n2)\n e36.rects.push({ center: o3.center, width: o3.width, height: o3.height, fill: Oo(t3, 0.2), label: `OffBoardConn: ${t3}` });\n for (const o3 of n2)\n for (const i3 of n2)\n o3.capacityMeshNodeId !== i3.capacityMeshNodeId \u0026\u0026 e36.lines.push({ points: [o3.center, i3.center], strokeColor: Oo(t3, 1) });\n }\n return e36;\n }\n};\nvar d$ = 0.1;\nvar u$ = 0.1;\nfunction p$(e36, t2, n2, o3, i3, r3) {\n return (i3 - e36) * (o3 - t2) - (r3 - t2) * (n2 - e36);\n}\nfunction m$(e36, t2, n2, o3, i3, r3) {\n return Math.min(e36, n2) \u003c= i3 \u0026\u0026 i3 \u003c= Math.max(e36, n2) \u0026\u0026 Math.min(t2, o3) \u003c= r3 \u0026\u0026 r3 \u003c= Math.max(t2, o3);\n}\nfunction g$(e36, t2, n2, o3, i3, r3, s2, a3) {\n const c3 = p$(i3, r3, s2, a3, e36, t2), l3 = p$(i3, r3, s2, a3, n2, o3), h2 = p$(e36, t2, n2, o3, i3, r3), d2 = p$(e36, t2, n2, o3, s2, a3);\n return (c3 \u003e 0 \u0026\u0026 l3 \u003c 0 || c3 \u003c 0 \u0026\u0026 l3 \u003e 0) \u0026\u0026 (h2 \u003e 0 \u0026\u0026 d2 \u003c 0 || h2 \u003c 0 \u0026\u0026 d2 \u003e 0) || (!(c3 !== 0 || !m$(i3, r3, s2, a3, e36, t2)) || (!(l3 !== 0 || !m$(i3, r3, s2, a3, n2, o3)) || (!(h2 !== 0 || !m$(e36, t2, n2, o3, i3, r3)) || !(d2 !== 0 || !m$(e36, t2, n2, o3, s2, a3)))));\n}\nfunction f$(e36, t2, n2, o3, i3, r3) {\n const s2 = i3 - n2, a3 = r3 - o3, c3 = e36 - n2, l3 = t2 - o3, h2 = s2 * s2 + a3 * a3;\n if (h2 === 0) {\n return { x: n2, y: o3, distSq: c3 * c3 + l3 * l3 };\n }\n let d2 = (c3 * s2 + l3 * a3) / h2;\n d2 = Math.max(0, Math.min(1, d2));\n const u2 = n2 + d2 * s2, p3 = o3 + d2 * a3, m2 = e36 - u2, g2 = t2 - p3;\n return { x: u2, y: p3, distSq: m2 * m2 + g2 * g2 };\n}\nvar _$ = class extends ni {\n getSolverName() {\n return \"SimpleHighDensitySolver\";\n }\n unsolvedNodes;\n allNodes;\n routes;\n colorMap;\n traceWidth;\n viaDiameter;\n numMovablePoints;\n currentNode = null;\n lastNode = null;\n currentNodeStep = 0;\n routesInProgress = [];\n pushMargin;\n currentNodeBounds = null;\n constructor({ nodePortPoints: e36, colorMap: t2, traceWidth: n2 = 0.1, viaDiameter: o3 = 0.3, pushMargin: i3 = 0.3, numMovablePoints: r3 = 2 }) {\n if (super(), r3 \u003c 1 || r3 \u003e 3)\n throw new Error(`numMovablePoints must be 1, 2, or 3, got ${r3}`);\n this.allNodes = [...e36], this.unsolvedNodes = [...e36], this.colorMap = t2 ?? {}, this.routes = [], this.traceWidth = n2, this.viaDiameter = o3, this.numMovablePoints = r3, this.pushMargin = i3, this.MAX_ITERATIONS = 10 * e36.length + 1;\n }\n _step() {\n if (this.currentNode === null) {\n if (this.unsolvedNodes.length === 0)\n return void (this.solved = true);\n this.lastNode = this.currentNode, this.currentNode = this.unsolvedNodes.pop(), this.currentNodeStep = 0, this.routesInProgress = [], this._initializeRoutesForCurrentNode();\n }\n this.currentNodeStep \u003e 0 \u0026\u0026 this._runForceDirectedStep(), this.currentNodeStep++, this.currentNodeStep \u003e= 10 \u0026\u0026 (this._finalizeRoutesForCurrentNode(), this.lastNode = this.currentNode, this.currentNode = null);\n }\n _initializeRoutesForCurrentNode() {\n const e36 = this.currentNode, t2 = e36.center.x - e36.width / 2, n2 = e36.center.x + e36.width / 2, o3 = e36.center.y - e36.height / 2, i3 = e36.center.y + e36.height / 2;\n this.currentNodeBounds = { minX: t2, maxX: n2, minY: o3, maxY: i3 };\n const r3 = new Map;\n for (const t3 of e36.portPoints)\n r3.has(t3.connectionName) || r3.set(t3.connectionName, []), r3.get(t3.connectionName).push({ x: t3.x, y: t3.y, z: t3.z, rootConnectionName: t3.rootConnectionName });\n for (const [e37, t3] of r3) {\n if (t3.length \u003c 2)\n continue;\n const n3 = t3[0], o4 = t3[t3.length - 1], i4 = n3.z, r4 = o4.x - n3.x, s2 = o4.y - n3.y, a3 = Math.sqrt(r4 * r4 + s2 * s2), c3 = a3 \u003e 0 ? r4 / a3 : 0, l3 = a3 \u003e 0 ? s2 / a3 : 0, h2 = [];\n this.numMovablePoints \u003e= 1 \u0026\u0026 h2.push({ x: n3.x + c3 * u$, y: n3.y + l3 * u$, z: i4, rootConnectionName: n3.rootConnectionName, connectionName: e37 }), this.numMovablePoints \u003e= 2 \u0026\u0026 h2.push({ x: o4.x - c3 * u$, y: o4.y - l3 * u$, z: i4, rootConnectionName: n3.rootConnectionName, connectionName: e37 }), this.numMovablePoints \u003e= 3 \u0026\u0026 h2.push({ x: n3.x + r4 / 2, y: n3.y + s2 / 2, z: i4, rootConnectionName: n3.rootConnectionName, connectionName: e37 }), this.routesInProgress.push({ connectionName: e37, rootConnectionName: n3.rootConnectionName, startPoint: { x: n3.x, y: n3.y, z: i4 }, endPoint: { x: o4.x, y: o4.y, z: i4 }, movablePoints: h2 });\n }\n }\n _runForceDirectedStep() {\n const e36 = this.currentNodeBounds, t2 = [];\n for (const e37 of this.routesInProgress)\n t2.push(...e37.movablePoints);\n const n2 = new Map;\n for (const e37 of t2)\n n2.set(e37, { fx: 0, fy: 0 });\n const o3 = 0.3 + this.pushMargin, i3 = new Map;\n for (const e37 of this.routesInProgress) {\n const t3 = [{ x: e37.startPoint.x, y: e37.startPoint.y, movablePoint: null }];\n e37.movablePoints.length === 1 ? t3.push({ x: e37.movablePoints[0].x, y: e37.movablePoints[0].y, movablePoint: e37.movablePoints[0] }) : e37.movablePoints.length === 2 ? (t3.push({ x: e37.movablePoints[0].x, y: e37.movablePoints[0].y, movablePoint: e37.movablePoints[0] }), t3.push({ x: e37.movablePoints[1].x, y: e37.movablePoints[1].y, movablePoint: e37.movablePoints[1] })) : e37.movablePoints.length === 3 \u0026\u0026 (t3.push({ x: e37.movablePoints[0].x, y: e37.movablePoints[0].y, movablePoint: e37.movablePoints[0] }), t3.push({ x: e37.movablePoints[2].x, y: e37.movablePoints[2].y, movablePoint: e37.movablePoints[2] }), t3.push({ x: e37.movablePoints[1].x, y: e37.movablePoints[1].y, movablePoint: e37.movablePoints[1] })), t3.push({ x: e37.endPoint.x, y: e37.endPoint.y, movablePoint: null }), i3.set(e37, t3);\n }\n for (const r4 of t2) {\n const t3 = n2.get(r4), s3 = r4.x - e36.minX, a3 = e36.maxX - r4.x, c3 = e36.maxY - r4.y, l3 = r4.y - e36.minY;\n s3 \u003c o3 \u0026\u0026 (t3.fx += d$ * (o3 - s3)), a3 \u003c o3 \u0026\u0026 (t3.fx -= d$ * (o3 - a3)), l3 \u003c o3 \u0026\u0026 (t3.fy += d$ * (o3 - l3)), c3 \u003c o3 \u0026\u0026 (t3.fy -= d$ * (o3 - c3));\n for (const e37 of this.routesInProgress) {\n if (e37.rootConnectionName === r4.rootConnectionName)\n continue;\n const s4 = i3.get(e37);\n for (let e38 = 0;e38 \u003c s4.length - 1; e38++) {\n const i4 = s4[e38], a4 = s4[e38 + 1], c4 = f$(r4.x, r4.y, i4.x, i4.y, a4.x, a4.y), l4 = Math.sqrt(c4.distSq);\n if (l4 \u003e 0 \u0026\u0026 l4 \u003c 2 * o3) {\n const e39 = r4.x - c4.x, o4 = r4.y - c4.y, s5 = 0.002 / c4.distSq, l5 = s5 * e39, h2 = s5 * o4;\n t3.fx += l5, t3.fy += h2;\n const d2 = i4.movablePoint, u2 = a4.movablePoint;\n if (d2 \u0026\u0026 u2) {\n const e40 = n2.get(d2), t4 = n2.get(u2);\n e40.fx -= l5 / 2, e40.fy -= h2 / 2, t4.fx -= l5 / 2, t4.fy -= h2 / 2;\n } else if (d2) {\n const e40 = n2.get(d2);\n e40.fx -= l5, e40.fy -= h2;\n } else if (u2) {\n const e40 = n2.get(u2);\n e40.fx -= l5, e40.fy -= h2;\n }\n }\n }\n }\n }\n const r3 = (e37) =\u003e e37.movablePoint ? { x: e37.movablePoint.x, y: e37.movablePoint.y } : { x: e37.x, y: e37.y }, s2 = (e37) =\u003e {\n let t3 = null;\n for (const n4 of this.routesInProgress)\n if (n4.movablePoints.includes(e37)) {\n t3 = n4;\n break;\n }\n if (!t3)\n return false;\n const n3 = i3.get(t3);\n let o4 = -1;\n for (let t4 = 0;t4 \u003c n3.length; t4++)\n if (n3[t4].movablePoint === e37) {\n o4 = t4;\n break;\n }\n if (o4 === -1)\n return false;\n const s3 = [];\n if (o4 \u003e 0) {\n const t4 = r3(n3[o4 - 1]);\n s3.push({ ax: t4.x, ay: t4.y, bx: e37.x, by: e37.y });\n }\n if (o4 \u003c n3.length - 1) {\n const t4 = r3(n3[o4 + 1]);\n s3.push({ ax: e37.x, ay: e37.y, bx: t4.x, by: t4.y });\n }\n for (const e38 of this.routesInProgress) {\n if (e38.rootConnectionName === t3.rootConnectionName)\n continue;\n const n4 = i3.get(e38);\n for (let e39 = 0;e39 \u003c n4.length - 1; e39++) {\n const t4 = r3(n4[e39]), o5 = r3(n4[e39 + 1]);\n for (const e40 of s3)\n if (g$(e40.ax, e40.ay, e40.bx, e40.by, t4.x, t4.y, o5.x, o5.y))\n return true;\n }\n }\n return false;\n };\n for (const o4 of t2) {\n const t3 = n2.get(o4);\n o4.forceX = t3.fx, o4.forceY = t3.fy;\n const { x: i4, y: r4 } = o4;\n o4.x += t3.fx, o4.y += t3.fy, o4.x = Math.max(e36.minX, Math.min(e36.maxX, o4.x)), o4.y = Math.max(e36.minY, Math.min(e36.maxY, o4.y)), s2(o4) \u0026\u0026 (o4.x = i4, o4.y = r4);\n }\n }\n _finalizeRoutesForCurrentNode() {\n for (const e36 of this.routesInProgress) {\n const { connectionName: t2, rootConnectionName: n2, startPoint: o3, endPoint: i3, movablePoints: r3 } = e36, s2 = [{ x: o3.x, y: o3.y, z: o3.z }];\n r3.length === 1 ? s2.push({ x: r3[0].x, y: r3[0].y, z: r3[0].z }) : r3.length === 2 ? (s2.push({ x: r3[0].x, y: r3[0].y, z: r3[0].z }), s2.push({ x: r3[1].x, y: r3[1].y, z: r3[1].z })) : r3.length === 3 \u0026\u0026 (s2.push({ x: r3[0].x, y: r3[0].y, z: r3[0].z }), s2.push({ x: r3[2].x, y: r3[2].y, z: r3[2].z }), s2.push({ x: r3[1].x, y: r3[1].y, z: r3[1].z })), s2.push({ x: i3.x, y: i3.y, z: i3.z });\n const a3 = { connectionName: t2, rootConnectionName: n2, traceThickness: this.traceWidth, viaDiameter: this.viaDiameter, route: s2, vias: [] };\n this.routes.push(a3);\n }\n this.routesInProgress = [];\n }\n _getNodeBounds(e36) {\n return { minX: e36.center.x - e36.width / 2, maxX: e36.center.x + e36.width / 2, minY: e36.center.y - e36.height / 2, maxY: e36.center.y + e36.height / 2 };\n }\n visualize() {\n const e36 = { lines: [], points: [], rects: [], circles: [] };\n for (const t2 of this.unsolvedNodes) {\n if (t2 === this.currentNode)\n continue;\n const n2 = this._getNodeBounds(t2);\n e36.rects.push({ center: { x: (n2.minX + n2.maxX) / 2, y: (n2.minY + n2.maxY) / 2 }, width: n2.maxX - n2.minX, height: n2.maxY - n2.minY, fill: \"rgba(0, 0, 0, 0.08)\", stroke: \"rgba(0, 0, 0, 0.2)\", label: t2.capacityMeshNodeId });\n }\n if (this.lastNode) {\n const t2 = this._getNodeBounds(this.lastNode);\n e36.rects.push({ center: { x: (t2.minX + t2.maxX) / 2, y: (t2.minY + t2.maxY) / 2 }, width: t2.maxX - t2.minX, height: t2.maxY - t2.minY, fill: \"rgba(0, 200, 0, 0.15)\", stroke: \"rgba(0, 0, 255, 0.6)\" });\n }\n if (this.currentNode) {\n const t2 = this._getNodeBounds(this.currentNode);\n e36.rects.push({ center: { x: (t2.minX + t2.maxX) / 2, y: (t2.minY + t2.maxY) / 2 }, width: t2.maxX - t2.minX, height: t2.maxY - t2.minY, fill: \"rgba(0, 200, 0, 0.15)\", stroke: \"rgba(0, 200, 0, 0.6)\" });\n }\n for (const t2 of this.unsolvedNodes) {\n const n2 = new Map;\n for (const e37 of t2.portPoints)\n n2.has(e37.connectionName) || n2.set(e37.connectionName, []), n2.get(e37.connectionName).push({ x: e37.x, y: e37.y });\n for (const [t3, o3] of n2)\n o3.length \u003c 2 || e36.lines.push({ points: o3.map((e37) =\u003e ({ x: e37.x, y: e37.y })), label: t3, strokeColor: \"gray\", strokeWidth: this.traceWidth });\n }\n for (const t2 of this.routes) {\n const n2 = mi(t2.route, t2.connectionName, this.colorMap[t2.connectionName]);\n for (const o4 of n2)\n e36.lines.push({ points: o4.points, label: o4.connectionName, strokeColor: o4.z === 0 ? o4.color : Ao(o4.color, 0.75), layer: `z${o4.z}`, strokeWidth: t2.traceThickness, strokeDash: o4.z !== 0 ? \"10, 5\" : undefined });\n const o3 = t2.route;\n for (let t3 = 0;t3 \u003c o3.length; t3++) {\n const n3 = o3[t3], i3 = t3 === 0, r3 = t3 === o3.length - 1, s2 = !i3 \u0026\u0026 !r3;\n let a3;\n a3 = i3 ? \"start\" : r3 ? \"end\" : `M${t3}`, e36.points.push({ x: n3.x, y: n3.y, label: a3, color: s2 ? \"orange\" : \"blue\" });\n }\n }\n for (const t2 of this.routesInProgress) {\n const { startPoint: n2, endPoint: o3, movablePoints: i3, connectionName: r3 } = t2, s2 = this.colorMap[r3] ?? \"gray\", a3 = [{ x: n2.x, y: n2.y }];\n i3.length === 1 ? a3.push({ x: i3[0].x, y: i3[0].y }) : i3.length === 2 ? (a3.push({ x: i3[0].x, y: i3[0].y }), a3.push({ x: i3[1].x, y: i3[1].y })) : i3.length === 3 \u0026\u0026 (a3.push({ x: i3[0].x, y: i3[0].y }), a3.push({ x: i3[2].x, y: i3[2].y }), a3.push({ x: i3[1].x, y: i3[1].y })), a3.push({ x: o3.x, y: o3.y }), e36.lines.push({ points: a3, label: r3, strokeColor: s2, strokeWidth: this.traceWidth }), e36.points.push({ x: n2.x, y: n2.y, label: \"start\", color: \"blue\" });\n for (let t3 = 0;t3 \u003c i3.length; t3++) {\n const n3 = i3[t3];\n if (e36.points.push({ x: n3.x, y: n3.y, label: `M${t3 + 1}`, color: \"orange\" }), n3.forceX !== undefined \u0026\u0026 n3.forceY !== undefined) {\n if (Math.sqrt(n3.forceX * n3.forceX + n3.forceY * n3.forceY) \u003e 0.001) {\n const o4 = 5;\n e36.lines.push({ points: [{ x: n3.x, y: n3.y }, { x: n3.x + n3.forceX * o4, y: n3.y + n3.forceY * o4 }], strokeColor: \"red\", strokeWidth: 0.02, label: `F${t3 + 1}` });\n const i4 = 0.05, r4 = n3.x + n3.forceX * o4, s3 = n3.y + n3.forceY * o4, a4 = Math.atan2(n3.forceY, n3.forceX);\n e36.lines.push({ points: [{ x: r4, y: s3 }, { x: r4 - i4 * Math.cos(a4 - Math.PI / 6), y: s3 - i4 * Math.sin(a4 - Math.PI / 6) }], strokeColor: \"red\", strokeWidth: 0.02 }), e36.lines.push({ points: [{ x: r4, y: s3 }, { x: r4 - i4 * Math.cos(a4 + Math.PI / 6), y: s3 - i4 * Math.sin(a4 + Math.PI / 6) }], strokeColor: \"purple\", strokeWidth: 0.02 });\n }\n }\n }\n e36.points.push({ x: o3.x, y: o3.y, label: \"end\", color: \"blue\" });\n }\n return e36;\n }\n};\nvar y$ = ({ connMap: e36, connectionsWithResults: t2, inputNodes: n2, obstacles: o3 }) =\u003e {\n const i3 = o3.filter((e37) =\u003e e37.offBoardConnectsTo?.length);\n if (i3.length === 0)\n return;\n const r3 = new Jo({});\n r3.addConnections(i3.map((e37, t3) =\u003e [e37.obstacleId ?? `__obs${t3}`, ...e37.offBoardConnectsTo ?? []]));\n const s2 = new Map(n2.map((e37) =\u003e [e37.capacityMeshNodeId, e37]));\n for (const n3 of t2) {\n if (!n3.path)\n continue;\n const t3 = n3.connection.rootConnectionName ?? n3.connection.name, o4 = new Set;\n for (const e37 of n3.path) {\n const t4 = s2.get(e37.currentNodeId);\n if (t4?._offBoardConnectionId \u0026\u0026 o4.add(t4._offBoardConnectionId), e37.throughNodeId) {\n const t5 = s2.get(e37.throughNodeId);\n t5?._offBoardConnectionId \u0026\u0026 o4.add(t5._offBoardConnectionId);\n }\n }\n for (const n4 of o4) {\n const o5 = r3.getIdsConnectedToNet(n4);\n o5?.length \u0026\u0026 e36.addConnections([[t3, ...o5]]);\n }\n }\n};\nfunction b$(e36, t2, n2, o3 = {}) {\n return { solverName: e36, solverClass: t2, getConstructorParams: n2, onSolved: o3.onSolved };\n}\nvar x$ = class extends ni {\n constructor(e36, t2 = {}) {\n super(), this.srj = e36, this.opts = t2, this.srj = e36, this.opts = { ...t2 }, this.viaDiameter = Yo(e36).padDiameter, this.minTraceWidth = e36.minTraceWidth;\n const n2 = this.opts;\n if (this.effort = n2.effort ?? 1, this.MAX_ITERATIONS = 1e8 * this.effort, n2.capacityDepth === undefined) {\n const t3 = e36.bounds.maxX - e36.bounds.minX, o3 = e36.bounds.maxY - e36.bounds.minY, i3 = Math.max(t3, o3), r3 = n2.targetMinCapacity ?? 0.5;\n n2.capacityDepth = Fz(i3, r3);\n }\n this.connMap = ei(e36), this.colorMap = Eo(e36, this.connMap), this.cacheProvider = n2.cacheProvider === undefined ? no() : n2.cacheProvider === null ? null : n2.cacheProvider, this.startTimeOfPhase = {}, this.endTimeOfPhase = {}, this.timeSpentOnPhase = {};\n }\n getSolverName() {\n return \"AssignableAutoroutingPipeline2\";\n }\n netToPointPairsSolver;\n nodeSolver;\n nodeTargetMerger;\n edgeSolver;\n relateNodesToOffBoardConnections;\n colorMap;\n highDensityRouteSolver;\n simpleHighDensityRouteSolver;\n highDensitySolver;\n highDensityStitchSolver;\n singleLayerNodeMerger;\n offboardPathFragmentSolver;\n strawSolver;\n deadEndSolver;\n traceSimplificationSolver;\n traceKeepoutSolver;\n traceWidthSolver;\n availableSegmentPointSolver;\n portPointPathingSolver;\n multiSectionPortPointOptimizer;\n viaDiameter;\n minTraceWidth;\n effort;\n startTimeOfPhase;\n endTimeOfPhase;\n timeSpentOnPhase;\n activeSubSolver = null;\n connMap;\n srjWithPointPairs;\n capacityNodes = null;\n capacityEdges = null;\n cacheProvider = null;\n pipelineDef = [b$(\"netToPointPairsSolver\", uB, (e36) =\u003e [e36.srj, e36.colorMap, ti(e36.srj)], { onSolved: (e36) =\u003e {\n e36.srjWithPointPairs = e36.netToPointPairsSolver?.getNewSimpleRouteJson(), e36.colorMap = Eo(e36.srjWithPointPairs, this.connMap), e36.connMap = ei(e36.srjWithPointPairs);\n } }), b$(\"nodeSolver\", Jn, (e36) =\u003e [{ simpleRouteJson: e36.srjWithPointPairs, maxGapFillPasses: 4 }], { onSolved: (e36) =\u003e {\n e36.capacityNodes = e36.nodeSolver?.getOutput().meshNodes ?? [];\n } }), b$(\"relateNodesToOffBoardConnections\", h$, (e36) =\u003e [{ capacityMeshNodes: e36.capacityNodes, srj: e36.srj }], { onSolved: (e36) =\u003e {\n e36.capacityNodes = e36.relateNodesToOffBoardConnections?.getOutput().capacityNodes;\n } }), b$(\"edgeSolver\", ui, (e36) =\u003e [e36.capacityNodes], { onSolved: (e36) =\u003e {\n e36.capacityEdges = e36.edgeSolver?.edges;\n } }), b$(\"availableSegmentPointSolver\", ii, (e36) =\u003e [{ nodes: e36.capacityNodes, edges: e36.capacityEdges || [], traceWidth: e36.minTraceWidth, colorMap: e36.colorMap, shouldReturnCrampedPortPoints: false }]), b$(\"portPointPathingSolver\", Kz, (e36) =\u003e {\n const t2 = e36.capacityNodes.map((e37) =\u003e ({ capacityMeshNodeId: e37.capacityMeshNodeId, center: e37.center, width: e37.width, height: e37.height, portPoints: [], availableZ: e37.availableZ, _containsTarget: e37._containsTarget, _containsObstacle: e37._containsObstacle, _offBoardConnectionId: e37._offBoardConnectionId, _offBoardConnectedCapacityMeshNodeIds: e37._offBoardConnectedCapacityMeshNodeIds })), n2 = new Map(t2.map((e37) =\u003e [e37.capacityMeshNodeId, e37])), o3 = e36.availableSegmentPointSolver;\n for (const e37 of o3.sharedEdgeSegments)\n for (const t3 of e37.portPoints) {\n const [o4, i3] = t3.nodeIds, r3 = { portPointId: t3.segmentPortPointId, x: t3.x, y: t3.y, z: t3.availableZ[0] ?? 0, connectionNodeIds: [o4, i3], distToCentermostPortOnZ: t3.distToCentermostPortOnZ, connectsToOffBoardNode: e37.nodeIds.some((e38) =\u003e n2.get(e38)?._offBoardConnectionId) }, s2 = n2.get(o4);\n s2 \u0026\u0026 s2.portPoints.push(r3);\n }\n return [{ simpleRouteJson: e36.srjWithPointPairs, inputNodes: t2, capacityMeshNodes: e36.capacityNodes, colorMap: e36.colorMap, numShuffleSeeds: 100 * Math.min(1, e36.effort), hyperParameters: { JUMPER_PF_FN_ENABLED: false, NODE_PF_FACTOR: 100, NODE_PF_MAX_PENALTY: 100, CENTER_OFFSET_DIST_PENALTY_FACTOR: 0, FORCE_CENTER_FIRST: true } }];\n }, { onSolved: (e36) =\u003e {\n const t2 = e36.portPointPathingSolver;\n t2 \u0026\u0026 y$({ connMap: e36.connMap, connectionsWithResults: t2.connectionsWithResults, inputNodes: t2.inputNodes, obstacles: e36.srj.obstacles });\n } }), b$(\"multiSectionPortPointOptimizer\", nB, (e36) =\u003e {\n const t2 = e36.portPointPathingSolver;\n return [{ simpleRouteJson: e36.srjWithPointPairs, inputNodes: t2.inputNodes, capacityMeshNodes: e36.capacityNodes, capacityMeshEdges: e36.capacityEdges, colorMap: e36.colorMap, initialConnectionResults: t2.connectionsWithResults, initialAssignedPortPoints: t2.assignedPortPoints, initialNodeAssignedPortPoints: t2.nodeAssignedPortPoints }];\n }), b$(\"highDensitySolver\", _$, (e36) =\u003e [{ nodePortPoints: e36.multiSectionPortPointOptimizer?.getNodesWithPortPoints() ?? e36.portPointPathingSolver?.getNodesWithPortPoints() ?? [], colorMap: e36.colorMap, viaDiameter: e36.viaDiameter, traceWidth: e36.minTraceWidth, connMap: e36.connMap }]), b$(\"highDensityStitchSolver\", IB, (e36) =\u003e [{ connections: e36.srjWithPointPairs.connections, hdRoutes: e36.highDensitySolver.routes, colorMap: e36.colorMap, layerCount: e36.srj.layerCount, defaultViaDiameter: e36.viaDiameter }]), b$(\"traceSimplificationSolver\", WF, (e36) =\u003e [{ hdRoutes: e36.highDensityStitchSolver?.mergedHdRoutes ?? e36.highDensitySolver?.routes ?? e36.highDensityRouteSolver?.routes, obstacles: e36.srj.obstacles, connMap: e36.connMap, colorMap: e36.colorMap, outline: e36.srj.outline, defaultViaDiameter: e36.viaDiameter, layerCount: e36.srj.layerCount, iterations: 2 }]), b$(\"traceKeepoutSolver\", l$, (e36) =\u003e [{ hdRoutes: e36.traceSimplificationSolver?.simplifiedHdRoutes ?? [], obstacles: e36.srj.obstacles, connMap: e36.connMap, colorMap: e36.colorMap, srj: e36.srj }]), b$(\"traceWidthSolver\", QF, (e36) =\u003e [{ hdRoutes: e36.traceKeepoutSolver?.redrawnHdRoutes ?? [], connection: e36.srj.connections, obstacles: e36.srj.obstacles, connMap: e36.connMap, colorMap: e36.colorMap, minTraceWidth: e36.minTraceWidth, obstacleMargin: e36.srj.defaultObstacleMargin ?? 0.15, layerCount: e36.srj.layerCount }])];\n getConstructorParams() {\n return [this.srj, this.opts];\n }\n currentPipelineStepIndex = 0;\n _step() {\n const e36 = this.pipelineDef[this.currentPipelineStepIndex];\n if (!e36)\n return void (this.solved = true);\n if (this.activeSubSolver)\n return this.activeSubSolver.step(), void (this.activeSubSolver.solved ? (this.endTimeOfPhase[e36.solverName] = performance.now(), this.timeSpentOnPhase[e36.solverName] = this.endTimeOfPhase[e36.solverName] - this.startTimeOfPhase[e36.solverName], e36.onSolved?.(this), this.activeSubSolver = null, this.currentPipelineStepIndex++) : this.activeSubSolver.failed \u0026\u0026 (this.error = this.activeSubSolver?.error, this.failed = true, this.activeSubSolver = null));\n const t2 = e36.getConstructorParams(this);\n this.activeSubSolver = new e36.solverClass(...t2), this[e36.solverName] = this.activeSubSolver, this.timeSpentOnPhase[e36.solverName] = 0, this.startTimeOfPhase[e36.solverName] = performance.now();\n }\n solveUntilPhase(e36) {\n for (;this.getCurrentPhase() !== e36; )\n this.step();\n }\n getCurrentPhase() {\n return this.pipelineDef[this.currentPipelineStepIndex]?.solverName ?? \"none\";\n }\n visualize() {\n if (!this.solved \u0026\u0026 this.activeSubSolver)\n return this.activeSubSolver.visualize();\n const e36 = this.netToPointPairsSolver?.visualize(), t2 = this.nodeSolver?.visualize(), n2 = this.nodeTargetMerger?.visualize(), o3 = this.singleLayerNodeMerger?.visualize(), i3 = this.strawSolver?.visualize(), r3 = this.edgeSolver?.visualize(), s2 = this.deadEndSolver?.visualize(), a3 = this.availableSegmentPointSolver?.visualize(), c3 = this.offboardPathFragmentSolver?.visualize(), l3 = this.portPointPathingSolver?.visualize(), h2 = this.multiSectionPortPointOptimizer?.visualize(), d2 = this.highDensityRouteSolver?.visualize(), u2 = this.highDensitySolver?.visualize(), p3 = this.simpleHighDensityRouteSolver?.visualize(), m2 = this.highDensityStitchSolver?.visualize(), g2 = this.traceSimplificationSolver?.visualize(), f2 = this.traceKeepoutSolver?.visualize(), _2 = this.traceWidthSolver?.visualize(), y2 = this.srj.outline, b2 = [];\n if (b2.push({ points: [{ x: this.srj.bounds?.minX ?? -50, y: this.srj.bounds?.minY ?? -50 }, { x: this.srj.bounds?.maxX ?? 50, y: this.srj.bounds?.minY ?? -50 }, { x: this.srj.bounds?.maxX ?? 50, y: this.srj.bounds?.maxY ?? 50 }, { x: this.srj.bounds?.minX ?? -50, y: this.srj.bounds?.maxY ?? 50 }, { x: this.srj.bounds?.minX ?? -50, y: this.srj.bounds?.minY ?? -50 }], strokeColor: \"rgba(255,0,0,0.25)\" }), y2 \u0026\u0026 y2.length \u003e= 2) {\n const e37 = y2.map((e38) =\u003e ({ x: e38.x, y: e38.y }));\n e37.push({ ...e37[0] }), b2.push({ points: e37, strokeColor: \"rgba(0, 136, 255, 0.95)\" });\n }\n const x2 = Lo(this.srj), v2 = { points: [...this.srj.connections.flatMap((e37) =\u003e e37.pointsToConnect.map((t3) =\u003e ({ ...t3, layer: Bo(t3, this.srj.layerCount), label: `${e37.name} ${t3.pcb_port_id ?? \"\"}` })))], rects: [...(this.srj.obstacles ?? []).filter((e37) =\u003e !e37.isCopperPour).map((e37) =\u003e ({ ...e37, fill: e37.layers?.includes(\"top\") ? \"rgba(255,0,0,0.25)\" : e37.layers?.includes(\"bottom\") ? \"rgba(0,0,255,0.25)\" : \"rgba(255,0,0,0.25)\", layer: jo(e37, this.srj.layerCount), label: x2(e37) }))], lines: b2 }, I2 = [v2, e36, t2, n2, o3, i3, r3, s2, a3, c3, l3, h2, d2 ? pi(v2, d2) : null, u2 ? pi(v2, u2) : null, p3 ? pi(v2, p3) : null, m2, g2, f2, _2, this.solved ? pi({ lines: b2 }, Wo(this.getOutputSimpleRouteJson())) : null].filter(Boolean);\n return pi(...I2);\n }\n preview() {\n const e36 = this.highDensitySolver?.routes ?? this.simpleHighDensityRouteSolver?.routes ?? this.highDensityRouteSolver?.routes;\n if (e36) {\n const t2 = [];\n for (let n2 = e36.length - 1;n2 \u003e= 0; n2--) {\n const o3 = e36[n2];\n if (t2.push({ points: o3.route.map((e37) =\u003e ({ x: e37.x, y: e37.y })), strokeColor: this.colorMap[o3.connectionName] }), t2.length \u003e 200)\n break;\n }\n return { lines: t2 };\n }\n if (this.portPointPathingSolver) {\n const e37 = [];\n for (const t2 of this.portPointPathingSolver.connectionsWithResults)\n t2.path \u0026\u0026 e37.push({ points: t2.path.map((e38) =\u003e ({ x: e38.point.x, y: e38.point.y })), strokeColor: this.colorMap[t2.connection.name] });\n return { lines: e37 };\n }\n return this.netToPointPairsSolver ? this.netToPointPairsSolver?.visualize() : {};\n }\n _getOutputHdRoutes() {\n return this.traceWidthSolver?.hdRoutesWithWidths ?? this.traceKeepoutSolver?.redrawnHdRoutes ?? this.traceSimplificationSolver?.simplifiedHdRoutes ?? this.highDensityStitchSolver?.mergedHdRoutes ?? this.highDensitySolver?.routes ?? this.simpleHighDensityRouteSolver?.routes ?? this.highDensityRouteSolver?.routes;\n }\n getConnectedOffboardObstacles() {\n const e36 = {}, t2 = new Set(this.srj.connections.flatMap((e37) =\u003e e37.__rootConnectionNames ?? [e37.name]));\n for (const [n2, o3] of this.srj.obstacles.entries()) {\n if (!o3.offBoardConnectsTo?.length)\n continue;\n const i3 = o3.obstacleId ?? `__obs${n2}`, r3 = this.connMap.getNetConnectedToId(i3);\n if (!r3)\n continue;\n const s2 = this.connMap.getIdsConnectedToNet(r3).find((e37) =\u003e t2.has(e37));\n s2 \u0026\u0026 (e36[i3] = s2);\n }\n return e36;\n }\n getOutputSimplifiedPcbTraces() {\n if (!this.solved || !this.highDensityRouteSolver \u0026\u0026 !this.simpleHighDensityRouteSolver \u0026\u0026 !this.highDensitySolver)\n throw new Error(\"Cannot get output before solving is complete\");\n const e36 = [], t2 = this._getOutputHdRoutes();\n for (const n2 of this.netToPointPairsSolver?.newConnections ?? []) {\n const o3 = n2.__netConnectionName ?? this.srj.connections.find((e37) =\u003e e37.name === n2.name)?.__netConnectionName, i3 = t2.filter((e37) =\u003e e37.connectionName === n2.name);\n for (let t3 = 0;t3 \u003c i3.length; t3++) {\n const r3 = i3[t3], s2 = { type: \"pcb_trace\", pcb_trace_id: `${n2.name}_${t3}`, connection_name: o3 ?? n2.__rootConnectionNames?.[0] ?? n2.name, route: Ro(r3, this.srj.layerCount) };\n e36.push(s2);\n }\n }\n return e36;\n }\n getOutputSimpleRouteJson() {\n return { ...this.srj, traces: this.getOutputSimplifiedPcbTraces() };\n }\n};\nvar v$ = class extends ni {\n getSolverName() {\n return \"MultipleHighDensityRouteStitchSolver2\";\n }\n unsolvedRoutes;\n mergedHdRoutes = [];\n colorMap = {};\n defaultTraceThickness;\n defaultViaDiameter;\n constructor(e36) {\n super(), this.colorMap = e36.colorMap ?? {};\n const t2 = e36.hdRoutes[0];\n this.defaultTraceThickness = t2?.traceThickness ?? 0.15, this.defaultViaDiameter = t2?.viaDiameter ?? e36.defaultViaDiameter ?? 0.3;\n const n2 = new Map;\n for (const t3 of e36.connectionPathResults)\n n2.set(t3.connection.name, t3);\n const o3 = new Map;\n for (const t3 of e36.hdRoutes) {\n const e37 = o3.get(t3.connectionName);\n e37 ? e37.push(t3) : o3.set(t3.connectionName, [t3]);\n }\n this.unsolvedRoutes = [];\n for (const [t3, i3] of o3.entries()) {\n const o4 = e36.connections.find((e37) =\u003e e37.name === t3);\n if (!o4)\n continue;\n const r3 = n2.get(t3);\n let s2 = [];\n r3?.path \u0026\u0026 (s2 = r3.path.map((e37) =\u003e e37.currentNodeId));\n const a3 = { ...o4.pointsToConnect[0], z: mo(Io(o4.pointsToConnect[0]), e36.layerCount) }, c3 = { ...o4.pointsToConnect[1], z: mo(Io(o4.pointsToConnect[1]), e36.layerCount) };\n this.unsolvedRoutes.push({ connectionName: t3, hdRoutes: i3, nodeOrder: s2, start: a3, end: c3 });\n }\n this.MAX_ITERATIONS = 1e5;\n }\n _step() {\n const e36 = this.unsolvedRoutes.pop();\n if (!e36)\n return void (this.solved = true);\n const t2 = this.stitchOrderedRoutes(e36);\n this.mergedHdRoutes.push(t2);\n }\n stitchOrderedRoutes(e36) {\n const { connectionName: t2, hdRoutes: n2, nodeOrder: o3, start: i3, end: r3 } = e36;\n if (n2.length === 0)\n return { connectionName: t2, traceThickness: this.defaultTraceThickness, viaDiameter: this.defaultViaDiameter, route: [i3, r3], vias: [], jumpers: [] };\n let s2;\n s2 = o3.length \u003e 0 ? this.orderRoutesByNodePath(n2, o3, i3, t2) : this.orderRoutesByProximity(n2, i3);\n const a3 = [], c3 = [], l3 = [];\n a3.push({ x: i3.x, y: i3.y, z: i3.z });\n for (let e37 = 0;e37 \u003c s2.length; e37++) {\n const t3 = s2[e37], n3 = a3[a3.length - 1], o4 = t3.route[0], i4 = t3.route[t3.route.length - 1], r4 = me(n3, o4), h3 = me(n3, i4), d2 = Math.min(r4, h3);\n if (e37 \u003e 0 \u0026\u0026 d2 \u003e 1)\n continue;\n let u2;\n u2 = r4 \u003c= h3 ? [...t3.route] : [...t3.route].reverse();\n const p3 = 0.001;\n u2.length \u003e 0 \u0026\u0026 me(n3, u2[0]) \u003c p3 \u0026\u0026 (u2 = u2.slice(1)), a3.push(...u2), c3.push(...t3.vias), t3.jumpers \u0026\u0026 l3.push(...t3.jumpers);\n }\n const h2 = me(a3[a3.length - 1], r3);\n return h2 \u003e 0.001 \u0026\u0026 h2 \u003c 1 \u0026\u0026 a3.push({ x: r3.x, y: r3.y, z: r3.z }), { connectionName: t2, rootConnectionName: n2[0]?.rootConnectionName, traceThickness: n2[0]?.traceThickness ?? this.defaultTraceThickness, viaDiameter: n2[0]?.viaDiameter ?? this.defaultViaDiameter, route: a3, vias: c3, jumpers: l3 };\n }\n orderRoutesByNodePath(e36, t2, n2, o3) {\n if (e36.length === 0)\n return [];\n const i3 = new Set(e36);\n let r3 = null, s2 = 1 / 0;\n for (const e37 of i3) {\n const t3 = e37.route[0], o4 = e37.route[e37.route.length - 1], i4 = Math.min(me(n2, t3), me(n2, o4));\n i4 \u003c s2 \u0026\u0026 (s2 = i4, r3 = e37);\n }\n if (!r3)\n return [];\n i3.delete(r3);\n const a3 = r3.route[0], c3 = r3.route[r3.route.length - 1];\n let l3, h2;\n me(n2, a3) \u003c= me(n2, c3) ? (l3 = a3, h2 = c3) : (l3 = c3, h2 = a3);\n const d2 = (e37, t3) =\u003e {\n let n3 = 0;\n for (const o4 of i3) {\n if (o4 === t3)\n continue;\n const i4 = o4.route[0], r4 = o4.route[o4.route.length - 1];\n (me(e37, i4) \u003c 10 || me(e37, r4) \u003c 10) \u0026\u0026 n3++;\n }\n return n3;\n }, u2 = [r3];\n let p3 = h2;\n for (;i3.size \u003e 0; ) {\n let e37 = null, t3 = 1 / 0, n3 = -1;\n for (const o4 of i3) {\n const i4 = o4.route[0], r4 = o4.route[o4.route.length - 1], s3 = me(p3, i4), a4 = me(p3, r4), c4 = Math.min(s3, a4);\n if (c4 \u003e= 10)\n continue;\n const l4 = d2(s3 \u003c= a4 ? r4 : i4, o4), h3 = l4 === 0, u3 = n3 === 0, m3 = c4 - t3;\n let g3 = false;\n g3 = e37 === null || (!!(!h3 \u0026\u0026 u3 \u0026\u0026 m3 \u003c 5) || !(h3 \u0026\u0026 !u3 \u0026\u0026 m3 \u003e -5) \u0026\u0026 c4 \u003c t3), g3 \u0026\u0026 (t3 = c4, e37 = o4, n3 = l4);\n }\n if (!e37)\n break;\n {\n u2.push(e37), i3.delete(e37);\n const t4 = e37.route[0], n4 = e37.route[e37.route.length - 1];\n p3 = me(p3, t4) \u003c= me(p3, n4) ? n4 : t4;\n }\n }\n const m2 = [];\n for (p3 = l3;i3.size \u003e 0; ) {\n let e37 = null, t3 = 1 / 0, o4 = -1;\n const r4 = me(p3, n2);\n for (const s3 of i3) {\n const i4 = s3.route[0], a4 = s3.route[s3.route.length - 1], c4 = me(p3, i4), l4 = me(p3, a4), h3 = Math.min(c4, l4);\n if (h3 \u003e= 10)\n continue;\n const u3 = c4 \u003c= l4 ? a4 : i4;\n if (me(u3, n2) \u003e r4 + 2)\n continue;\n const m3 = d2(u3, s3), g3 = m3 === 0, f2 = o4 === 0, _2 = h3 - t3;\n let y2 = false;\n y2 = e37 === null || (!!(!g3 \u0026\u0026 f2 \u0026\u0026 _2 \u003c 5) || !(g3 \u0026\u0026 !f2 \u0026\u0026 _2 \u003e -5) \u0026\u0026 h3 \u003c t3), y2 \u0026\u0026 (t3 = h3, e37 = s3, o4 = m3);\n }\n if (!e37)\n break;\n {\n m2.unshift(e37), i3.delete(e37);\n const t4 = e37.route[0], n3 = e37.route[e37.route.length - 1];\n p3 = me(p3, t4) \u003c= me(p3, n3) ? n3 : t4;\n }\n }\n const g2 = [...m2, ...u2];\n if (i3.size \u003e 0) {\n const t3 = [...i3].map((e37) =\u003e {\n const t4 = e37.route[0], n3 = e37.route[e37.route.length - 1];\n return `start=(${t4.x.toFixed(2)},${t4.y.toFixed(2)}) end=(${n3.x.toFixed(2)},${n3.y.toFixed(2)})`;\n });\n console.warn(`[StitchSolver] Skipped ${i3.size} routes for connection ${e36[0]?.connectionName ?? \"?\"}, skipped routes: ${t3.join(\"; \")}`);\n }\n return g2;\n }\n orderRoutesByProximity(e36, t2) {\n const n2 = new Set(e36), o3 = [];\n let i3 = t2;\n for (;n2.size \u003e 0; ) {\n let e37 = null, t3 = 1 / 0, r3 = false;\n for (const o4 of n2) {\n const n3 = o4.route[0], s2 = o4.route[o4.route.length - 1], a3 = me(i3, n3), c3 = me(i3, s2);\n a3 \u003c t3 \u0026\u0026 (t3 = a3, e37 = o4, r3 = false), c3 \u003c t3 \u0026\u0026 (t3 = c3, e37 = o4, r3 = true);\n }\n if (!e37)\n break;\n {\n o3.push(e37), n2.delete(e37);\n const t4 = e37.route[0], s2 = e37.route[e37.route.length - 1];\n i3 = r3 ? t4 : s2;\n }\n }\n return o3;\n }\n visualize() {\n const e36 = { points: [], lines: [], circles: [], rects: [], title: \"Multiple High Density Route Stitch Solver 2\" };\n for (const [t2, n2] of this.mergedHdRoutes.entries()) {\n const o3 = this.colorMap[n2.connectionName] ?? `hsl(120, 100%, ${40 + 10 * t2 % 40}%)`;\n for (let t3 = 0;t3 \u003c n2.route.length - 1; t3++) {\n const i3 = n2.route[t3], r3 = n2.route[t3 + 1], s2 = i3.z !== 0 ? Ao(o3, 0.5) : o3;\n e36.lines?.push({ points: [{ x: i3.x, y: i3.y }, { x: r3.x, y: r3.y }], strokeColor: s2, strokeWidth: n2.traceThickness });\n }\n for (const t3 of n2.route) {\n const n3 = t3.z !== 0 ? Ao(o3, 0.5) : o3;\n e36.points?.push({ x: t3.x, y: t3.y, color: n3 });\n }\n for (const t3 of n2.vias)\n e36.circles?.push({ center: { x: t3.x, y: t3.y }, radius: n2.viaDiameter / 2, fill: o3 });\n if (n2.jumpers \u0026\u0026 n2.jumpers.length \u003e 0) {\n const t3 = fB(n2.jumpers, { color: o3, label: n2.connectionName });\n e36.rects.push(...t3.rects ?? []), e36.lines.push(...t3.lines ?? []);\n }\n }\n for (const t2 of this.unsolvedRoutes) {\n const n2 = this.colorMap[t2.connectionName] ?? \"gray\";\n e36.points?.push({ x: t2.start.x, y: t2.start.y, color: n2, label: `${t2.connectionName} Start` }, { x: t2.end.x, y: t2.end.y, color: n2, label: `${t2.connectionName} End` });\n for (let o3 = 0;o3 \u003c t2.hdRoutes.length; o3++) {\n const i3 = t2.hdRoutes[o3];\n if (i3.route.length \u003e 1 \u0026\u0026 e36.lines?.push({ points: i3.route.map((e37) =\u003e ({ x: e37.x, y: e37.y })), strokeColor: Ao(n2, 0.5), strokeDash: \"10 5\", label: `segment ${o3}` }), i3.jumpers \u0026\u0026 i3.jumpers.length \u003e 0) {\n const t3 = fB(i3.jumpers, { color: n2, label: i3.connectionName });\n e36.rects.push(...t3.rects ?? []), e36.lines.push(...t3.lines ?? []);\n }\n }\n }\n return e36;\n }\n};\nvar I$ = Object.create;\nvar S$ = Object.defineProperty;\nvar C$ = Object.getOwnPropertyDescriptor;\nvar P$ = Object.getOwnPropertyNames;\nvar M$ = Object.getPrototypeOf;\nvar w$ = Object.prototype.hasOwnProperty;\nvar N$ = (e36, t2) =\u003e function() {\n return t2 || (0, e36[P$(e36)[0]])((t2 = { exports: {} }).exports, t2), t2.exports;\n};\nvar R$ = (e36, t2, n2) =\u003e (n2 = e36 != null ? I$(M$(e36)) : {}, ((e37, t3, n3, o3) =\u003e {\n if (t3 \u0026\u0026 typeof t3 == \"object\" || typeof t3 == \"function\")\n for (let i3 of P$(t3))\n w$.call(e37, i3) || i3 === n3 || S$(e37, i3, { get: () =\u003e t3[i3], enumerable: !(o3 = C$(t3, i3)) || o3.enumerable });\n return e37;\n})(!t2 \u0026\u0026 e36 \u0026\u0026 e36.__esModule ? n2 : S$(n2, \"default\", { value: e36, enumerable: true }), e36));\nvar T$ = N$({ \"node_modules/is-buffer/index.js\"(e36, t2) {\n function n2(e37) {\n return !!e37.constructor \u0026\u0026 typeof e37.constructor.isBuffer == \"function\" \u0026\u0026 e37.constructor.isBuffer(e37);\n }\n t2.exports = function(e37) {\n return e37 != null \u0026\u0026 (n2(e37) || function(e38) {\n return typeof e38.readFloatLE == \"function\" \u0026\u0026 typeof e38.slice == \"function\" \u0026\u0026 n2(e38.slice(0, 0));\n }(e37) || !!e37._isBuffer);\n };\n} });\nvar E$ = N$({ \"node_modules/kind-of/index.js\"(e36, t2) {\n var n2 = T$(), o3 = Object.prototype.toString;\n t2.exports = function(e37) {\n if (e37 === undefined)\n return \"undefined\";\n if (e37 === null)\n return \"null\";\n if (e37 === true || e37 === false || e37 instanceof Boolean)\n return \"boolean\";\n if (typeof e37 == \"string\" || e37 instanceof String)\n return \"string\";\n if (typeof e37 == \"number\" || e37 instanceof Number)\n return \"number\";\n if (typeof e37 == \"function\" || e37 instanceof Function)\n return \"function\";\n if (Array.isArray !== undefined \u0026\u0026 Array.isArray(e37))\n return \"array\";\n if (e37 instanceof RegExp)\n return \"regexp\";\n if (e37 instanceof Date)\n return \"date\";\n var t3 = o3.call(e37);\n return t3 === \"[object RegExp]\" ? \"regexp\" : t3 === \"[object Date]\" ? \"date\" : t3 === \"[object Arguments]\" ? \"arguments\" : t3 === \"[object Error]\" ? \"error\" : n2(e37) ? \"buffer\" : t3 === \"[object Set]\" ? \"set\" : t3 === \"[object WeakSet]\" ? \"weakset\" : t3 === \"[object Map]\" ? \"map\" : t3 === \"[object WeakMap]\" ? \"weakmap\" : t3 === \"[object Symbol]\" ? \"symbol\" : t3 === \"[object Int8Array]\" ? \"int8array\" : t3 === \"[object Uint8Array]\" ? \"uint8array\" : t3 === \"[object Uint8ClampedArray]\" ? \"uint8clampedarray\" : t3 === \"[object Int16Array]\" ? \"int16array\" : t3 === \"[object Uint16Array]\" ? \"uint16array\" : t3 === \"[object Int32Array]\" ? \"int32array\" : t3 === \"[object Uint32Array]\" ? \"uint32array\" : t3 === \"[object Float32Array]\" ? \"float32array\" : t3 === \"[object Float64Array]\" ? \"float64array\" : \"object\";\n };\n} });\nvar A$ = N$({ \"node_modules/rename-keys/index.js\"(e36, t2) {\n (function() {\n function e37(e38, t3) {\n if (typeof t3 != \"function\")\n return e38;\n var n2 = {};\n for (var o3 in e38)\n Object.prototype.hasOwnProperty.call(e38, o3) \u0026\u0026 (n2[t3(o3, e38[o3]) || o3] = e38[o3]);\n return n2;\n }\n t2 !== undefined \u0026\u0026 t2.exports ? t2.exports = e37 : typeof define == \"function\" \u0026\u0026 define.amd ? define([], function() {\n return e37;\n }) : window.rename = e37;\n })();\n} });\nvar O$ = N$({ \"node_modules/deep-rename-keys/index.js\"(e36, t2) {\n var n2 = E$(), o3 = A$();\n t2.exports = function e37(t3, i3) {\n var r3 = n2(t3);\n if (r3 !== \"object\" \u0026\u0026 r3 !== \"array\")\n throw new Error(\"expected an object\");\n var s2 = [];\n for (var a3 in r3 === \"object\" \u0026\u0026 (t3 = o3(t3, i3), s2 = {}), t3)\n if (t3.hasOwnProperty(a3)) {\n var c3 = t3[a3];\n n2(c3) === \"object\" || n2(c3) === \"array\" ? s2[a3] = e37(c3, i3) : s2[a3] = c3;\n }\n return s2;\n };\n} });\nvar k$ = N$({ \"node_modules/eventemitter3/index.js\"(e36, t2) {\n var n2 = Object.prototype.hasOwnProperty, o3 = \"~\";\n function i3() {}\n function r3(e37, t3, n3) {\n this.fn = e37, this.context = t3, this.once = n3 || false;\n }\n function s2() {\n this._events = new i3, this._eventsCount = 0;\n }\n Object.create \u0026\u0026 (i3.prototype = Object.create(null), new i3().__proto__ || (o3 = false)), s2.prototype.eventNames = function() {\n var e37, t3, i4 = [];\n if (this._eventsCount === 0)\n return i4;\n for (t3 in e37 = this._events)\n n2.call(e37, t3) \u0026\u0026 i4.push(o3 ? t3.slice(1) : t3);\n return Object.getOwnPropertySymbols ? i4.concat(Object.getOwnPropertySymbols(e37)) : i4;\n }, s2.prototype.listeners = function(e37, t3) {\n var n3 = o3 ? o3 + e37 : e37, i4 = this._events[n3];\n if (t3)\n return !!i4;\n if (!i4)\n return [];\n if (i4.fn)\n return [i4.fn];\n for (var r4 = 0, s3 = i4.length, a3 = new Array(s3);r4 \u003c s3; r4++)\n a3[r4] = i4[r4].fn;\n return a3;\n }, s2.prototype.emit = function(e37, t3, n3, i4, r4, s3) {\n var a3 = o3 ? o3 + e37 : e37;\n if (!this._events[a3])\n return false;\n var c3, l3, h2 = this._events[a3], d2 = arguments.length;\n if (h2.fn) {\n switch (h2.once \u0026\u0026 this.removeListener(e37, h2.fn, undefined, true), d2) {\n case 1:\n return h2.fn.call(h2.context), true;\n case 2:\n return h2.fn.call(h2.context, t3), true;\n case 3:\n return h2.fn.call(h2.context, t3, n3), true;\n case 4:\n return h2.fn.call(h2.context, t3, n3, i4), true;\n case 5:\n return h2.fn.call(h2.context, t3, n3, i4, r4), true;\n case 6:\n return h2.fn.call(h2.context, t3, n3, i4, r4, s3), true;\n }\n for (l3 = 1, c3 = new Array(d2 - 1);l3 \u003c d2; l3++)\n c3[l3 - 1] = arguments[l3];\n h2.fn.apply(h2.context, c3);\n } else {\n var u2, p3 = h2.length;\n for (l3 = 0;l3 \u003c p3; l3++)\n switch (h2[l3].once \u0026\u0026 this.removeListener(e37, h2[l3].fn, undefined, true), d2) {\n case 1:\n h2[l3].fn.call(h2[l3].context);\n break;\n case 2:\n h2[l3].fn.call(h2[l3].context, t3);\n break;\n case 3:\n h2[l3].fn.call(h2[l3].context, t3, n3);\n break;\n case 4:\n h2[l3].fn.call(h2[l3].context, t3, n3, i4);\n break;\n default:\n if (!c3)\n for (u2 = 1, c3 = new Array(d2 - 1);u2 \u003c d2; u2++)\n c3[u2 - 1] = arguments[u2];\n h2[l3].fn.apply(h2[l3].context, c3);\n }\n }\n return true;\n }, s2.prototype.on = function(e37, t3, n3) {\n var i4 = new r3(t3, n3 || this), s3 = o3 ? o3 + e37 : e37;\n return this._events[s3] ? this._events[s3].fn ? this._events[s3] = [this._events[s3], i4] : this._events[s3].push(i4) : (this._events[s3] = i4, this._eventsCount++), this;\n }, s2.prototype.once = function(e37, t3, n3) {\n var i4 = new r3(t3, n3 || this, true), s3 = o3 ? o3 + e37 : e37;\n return this._events[s3] ? this._events[s3].fn ? this._events[s3] = [this._events[s3], i4] : this._events[s3].push(i4) : (this._events[s3] = i4, this._eventsCount++), this;\n }, s2.prototype.removeListener = function(e37, t3, n3, r4) {\n var s3 = o3 ? o3 + e37 : e37;\n if (!this._events[s3])\n return this;\n if (!t3)\n return --this._eventsCount === 0 ? this._events = new i3 : delete this._events[s3], this;\n var a3 = this._events[s3];\n if (a3.fn)\n a3.fn !== t3 || r4 \u0026\u0026 !a3.once || n3 \u0026\u0026 a3.context !== n3 || (--this._eventsCount === 0 ? this._events = new i3 : delete this._events[s3]);\n else {\n for (var c3 = 0, l3 = [], h2 = a3.length;c3 \u003c h2; c3++)\n (a3[c3].fn !== t3 || r4 \u0026\u0026 !a3[c3].once || n3 \u0026\u0026 a3[c3].context !== n3) \u0026\u0026 l3.push(a3[c3]);\n l3.length ? this._events[s3] = l3.length === 1 ? l3[0] : l3 : --this._eventsCount === 0 ? this._events = new i3 : delete this._events[s3];\n }\n return this;\n }, s2.prototype.removeAllListeners = function(e37) {\n var t3;\n return e37 ? (t3 = o3 ? o3 + e37 : e37, this._events[t3] \u0026\u0026 (--this._eventsCount === 0 ? this._events = new i3 : delete this._events[t3])) : (this._events = new i3, this._eventsCount = 0), this;\n }, s2.prototype.off = s2.prototype.removeListener, s2.prototype.addListener = s2.prototype.on, s2.prototype.setMaxListeners = function() {\n return this;\n }, s2.prefixed = o3, s2.EventEmitter = s2, t2 !== undefined \u0026\u0026 (t2.exports = s2);\n} });\nvar D$ = N$({ \"node_modules/xml-lexer/dist/lexer.js\"(e36, t2) {\n function n2(e37, t3, n3) {\n return t3 in e37 ? Object.defineProperty(e37, t3, { value: n3, enumerable: true, configurable: true, writable: true }) : e37[t3] = n3, e37;\n }\n var o3 = k$(), i3 = function() {}, r3 = { 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\" }, s2 = { 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\" }, c3 = { \" \": s2.space, \"\\t\": s2.space, \"\\n\": s2.space, \"\\r\": s2.space, \"\u003c\": s2.lt, \"\u003e\": s2.gt, '\"': s2.quote, \"'\": s2.quote, \"=\": s2.equal, \"/\": s2.slash };\n t2.exports = { State: r3, Action: s2, Type: a3, create: function(e37) {\n var t3, l3, h2, d2, u2, p3, m2, g2, f2, _2;\n e37 = Object.assign({ debug: false }, e37);\n var y2 = new o3, b2 = r3.data, x2 = \"\", v2 = \"\", I2 = \"\", S2 = \"\", C = \"\", P = \"\", M = function(t4, n3) {\n if (v2[0] !== \"?\" \u0026\u0026 v2[0] !== \"!\") {\n var o4 = { type: t4, value: n3 };\n e37.debug \u0026\u0026 console.log(\"emit:\", o4), y2.emit(\"data\", o4);\n }\n };\n y2.stateMachine = (n2(_2 = {}, r3.data, (n2(t3 = {}, s2.lt, function() {\n x2.trim() \u0026\u0026 M(a3.text, x2), v2 = \"\", C = false, b2 = r3.tagBegin;\n }), n2(t3, s2.char, function(e38) {\n x2 += e38;\n }), t3)), n2(_2, r3.cdata, n2({}, s2.char, function(e38) {\n (x2 += e38).substr(-3) === \"]]\u003e\" \u0026\u0026 (M(a3.text, x2.slice(0, -3)), x2 = \"\", b2 = r3.data);\n })), n2(_2, r3.tagBegin, (n2(l3 = {}, s2.space, i3), n2(l3, s2.char, function(e38) {\n v2 = e38, b2 = r3.tagName;\n }), n2(l3, s2.slash, function() {\n v2 = \"\", C = true;\n }), l3)), n2(_2, r3.tagName, (n2(h2 = {}, s2.space, function() {\n C ? b2 = r3.tagEnd : (b2 = r3.attributeNameStart, M(a3.openTag, v2));\n }), n2(h2, s2.gt, function() {\n M(C ? a3.closeTag : a3.openTag, v2), x2 = \"\", b2 = r3.data;\n }), n2(h2, s2.slash, function() {\n b2 = r3.tagEnd, M(a3.openTag, v2);\n }), n2(h2, s2.char, function(e38) {\n (v2 += e38) === \"![CDATA[\" \u0026\u0026 (b2 = r3.cdata, x2 = \"\", v2 = \"\");\n }), h2)), n2(_2, r3.tagEnd, (n2(d2 = {}, s2.gt, function() {\n M(a3.closeTag, v2), x2 = \"\", b2 = r3.data;\n }), n2(d2, s2.char, i3), d2)), n2(_2, r3.attributeNameStart, (n2(u2 = {}, s2.char, function(e38) {\n I2 = e38, b2 = r3.attributeName;\n }), n2(u2, s2.gt, function() {\n x2 = \"\", b2 = r3.data;\n }), n2(u2, s2.space, i3), n2(u2, s2.slash, function() {\n C = true, b2 = r3.tagEnd;\n }), u2)), n2(_2, r3.attributeName, (n2(p3 = {}, s2.space, function() {\n b2 = r3.attributeNameEnd;\n }), n2(p3, s2.equal, function() {\n M(a3.attributeName, I2), b2 = r3.attributeValueBegin;\n }), n2(p3, s2.gt, function() {\n S2 = \"\", M(a3.attributeName, I2), M(a3.attributeValue, S2), x2 = \"\", b2 = r3.data;\n }), n2(p3, s2.slash, function() {\n C = true, S2 = \"\", M(a3.attributeName, I2), M(a3.attributeValue, S2), b2 = r3.tagEnd;\n }), n2(p3, s2.char, function(e38) {\n I2 += e38;\n }), p3)), n2(_2, r3.attributeNameEnd, (n2(m2 = {}, s2.space, i3), n2(m2, s2.equal, function() {\n M(a3.attributeName, I2), b2 = r3.attributeValueBegin;\n }), n2(m2, s2.gt, function() {\n S2 = \"\", M(a3.attributeName, I2), M(a3.attributeValue, S2), x2 = \"\", b2 = r3.data;\n }), n2(m2, s2.char, function(e38) {\n S2 = \"\", M(a3.attributeName, I2), M(a3.attributeValue, S2), I2 = e38, b2 = r3.attributeName;\n }), m2)), n2(_2, r3.attributeValueBegin, (n2(g2 = {}, s2.space, i3), n2(g2, s2.quote, function(e38) {\n P = e38, S2 = \"\", b2 = r3.attributeValue;\n }), n2(g2, s2.gt, function() {\n M(a3.attributeValue, S2 = \"\"), x2 = \"\", b2 = r3.data;\n }), n2(g2, s2.char, function(e38) {\n P = \"\", S2 = e38, b2 = r3.attributeValue;\n }), g2)), n2(_2, r3.attributeValue, (n2(f2 = {}, s2.space, function(e38) {\n P ? S2 += e38 : (M(a3.attributeValue, S2), b2 = r3.attributeNameStart);\n }), n2(f2, s2.quote, function(e38) {\n P === e38 ? (M(a3.attributeValue, S2), b2 = r3.attributeNameStart) : S2 += e38;\n }), n2(f2, s2.gt, function(e38) {\n P ? S2 += e38 : (M(a3.attributeValue, S2), x2 = \"\", b2 = r3.data);\n }), n2(f2, s2.slash, function(e38) {\n P ? S2 += e38 : (M(a3.attributeValue, S2), C = true, b2 = r3.tagEnd);\n }), n2(f2, s2.char, function(e38) {\n S2 += e38;\n }), f2)), _2);\n var w = function(t4) {\n e37.debug \u0026\u0026 console.log(b2, t4);\n var n3 = y2.stateMachine[b2], o4 = n3[function(e38) {\n return c3[e38] || s2.char;\n }(t4)] || n3[s2.error] || n3[s2.char];\n o4(t4);\n };\n return y2.write = function(e38) {\n for (var t4 = e38.length, n3 = 0;n3 \u003c t4; n3++)\n w(e38[n3]);\n }, y2;\n } };\n} });\nvar L$ = N$({ \"node_modules/xml-reader/dist/reader.js\"(e36, t2) {\n var n2 = k$(), o3 = D$(), i3 = o3.Type, r3 = { element: \"element\", text: \"text\" }, s2 = function(e37) {\n return Object.assign({ name: \"\", type: r3.element, value: \"\", parent: null, attributes: {}, children: [] }, e37);\n }, a3 = function(e37) {\n e37 = Object.assign({ stream: false, parentNodes: true, doneEvent: \"done\", tagPrefix: \"tag:\", emitTopLevelOnly: false, debug: false }, e37);\n var t3 = undefined, a4 = undefined, c3 = undefined, l3 = undefined, h2 = new n2, d2 = function(n3) {\n switch (n3.type) {\n case i3.openTag:\n if (c3 === null)\n (c3 = a4).name = n3.value;\n else {\n var o4 = s2({ name: n3.value, parent: c3 });\n c3.children.push(o4), c3 = o4;\n }\n break;\n case i3.closeTag:\n var d3 = c3.parent;\n if (e37.parentNodes || (c3.parent = null), c3.name !== n3.value)\n break;\n e37.stream \u0026\u0026 d3 === a4 \u0026\u0026 (a4.children = [], c3.parent = null), e37.emitTopLevelOnly \u0026\u0026 d3 !== a4 || (h2.emit(e37.tagPrefix + c3.name, c3), h2.emit(\"tag\", c3.name, c3)), c3 === a4 \u0026\u0026 (t3.removeAllListeners(\"data\"), h2.emit(e37.doneEvent, c3), a4 = null), c3 = d3;\n break;\n case i3.text:\n c3 \u0026\u0026 c3.children.push(s2({ type: r3.text, value: n3.value, parent: e37.parentNodes ? c3 : null }));\n break;\n case i3.attributeName:\n l3 = n3.value, c3.attributes[l3] = \"\";\n break;\n case i3.attributeValue:\n c3.attributes[l3] = n3.value;\n }\n };\n return h2.reset = function() {\n (t3 = o3.create({ debug: e37.debug })).on(\"data\", d2), a4 = s2(), c3 = null, l3 = \"\", h2.parse = t3.write;\n }, h2.reset(), h2;\n };\n t2.exports = { parseSync: function(e37, t3) {\n t3 = Object.assign({}, t3, { stream: false, tagPrefix: \":\" });\n var n3 = a3(t3), o4 = undefined;\n return n3.on(\"done\", function(e38) {\n o4 = e38;\n }), n3.parse(e37), o4;\n }, create: a3, NodeType: r3 };\n} });\nvar $ = (R$(O$()), R$(L$()), class {\n MAX_ITERATIONS = 1e5;\n solved = false;\n failed = false;\n iterations = 0;\n progress = 0;\n error = null;\n activeSubSolver;\n failedSubSolvers;\n timeToSolve;\n stats = {};\n _setupDone = false;\n setup() {\n this._setupDone || (this._setup(), this._setupDone = true);\n }\n _setup() {}\n step() {\n if (this._setupDone || this.setup(), !this.solved \u0026\u0026 !this.failed) {\n this.iterations++;\n try {\n this._step();\n } catch (e36) {\n throw this.error = `${this.constructor.name} error: ${e36}`, this.failed = true, e36;\n }\n !this.solved \u0026\u0026 this.iterations \u003e= this.MAX_ITERATIONS \u0026\u0026 this.tryFinalAcceptance(), !this.solved \u0026\u0026 this.iterations \u003e= this.MAX_ITERATIONS \u0026\u0026 (this.error = `${this.constructor.name} ran out of iterations`, this.failed = true), \"computeProgress\" in this \u0026\u0026 (this.progress = this.computeProgress());\n }\n }\n _step() {}\n getConstructorParams() {\n throw new Error(\"getConstructorParams not implemented\");\n }\n getOutput() {\n return null;\n }\n solve() {\n const e36 = Date.now();\n for (;!this.solved \u0026\u0026 !this.failed; )\n this.step();\n const t2 = Date.now();\n this.timeToSolve = t2 - e36;\n }\n visualize() {\n return { lines: [], points: [], rects: [], circles: [] };\n }\n tryFinalAcceptance() {}\n preview() {\n return { lines: [], points: [], rects: [], circles: [] };\n }\n});\nvar Y$ = (e36) =\u003e e36 ? `hsl(${((e37) =\u003e {\n let t2 = 0;\n for (let n2 = 0;n2 \u003c e37.length; n2++)\n t2 = 779 * e37.charCodeAt(n2) + ((t2 \u003c\u003c 5) - t2);\n return t2;\n})(e36) % 360}, 100%, 50%)` : \"rgba(0, 0, 0, 0.5)\";\nvar X$ = (e36) =\u003e [[{ x: e36.minX, y: e36.minY }, { x: e36.maxX, y: e36.minY }], [{ x: e36.maxX, y: e36.minY }, { x: e36.maxX, y: e36.maxY }], [{ x: e36.maxX, y: e36.maxY }, { x: e36.minX, y: e36.maxY }], [{ x: e36.minX, y: e36.maxY }, { x: e36.minX, y: e36.minY }]];\nfunction H$(e36, t2) {\n const { minX: n2, maxX: o3, minY: i3, maxY: r3 } = t2, s2 = o3 - n2, a3 = r3 - i3, c3 = 0.000001;\n return Math.abs(e36.y - r3) \u003c c3 ? e36.x - n2 : Math.abs(e36.x - o3) \u003c c3 ? s2 + (r3 - e36.y) : Math.abs(e36.y - i3) \u003c c3 ? s2 + a3 + (o3 - e36.x) : Math.abs(e36.x - n2) \u003c c3 ? 2 * s2 + a3 + (e36.y - i3) : 0;\n}\nfunction V$(e36, t2) {\n const { minX: n2, maxX: o3, minY: i3, maxY: r3 } = t2, s2 = 0.000001, a3 = Math.abs(e36.y - r3) \u003c s2, c3 = Math.abs(e36.y - i3) \u003c s2, l3 = Math.abs(e36.x - o3) \u003c s2, h2 = Math.abs(e36.x - n2) \u003c s2;\n if (a3 \u0026\u0026 l3)\n return { x: -Math.SQRT1_2, y: -Math.SQRT1_2 };\n if (a3 \u0026\u0026 h2)\n return { x: Math.SQRT1_2, y: -Math.SQRT1_2 };\n if (c3 \u0026\u0026 l3)\n return { x: -Math.SQRT1_2, y: Math.SQRT1_2 };\n if (c3 \u0026\u0026 h2)\n return { x: Math.SQRT1_2, y: Math.SQRT1_2 };\n if (a3)\n return { x: 0, y: -1 };\n if (c3)\n return { x: 0, y: 1 };\n if (l3)\n return { x: -1, y: 0 };\n if (h2)\n return { x: 1, y: 0 };\n const d2 = (i3 + r3) / 2, u2 = (n2 + o3) / 2 - e36.x, p3 = d2 - e36.y, m2 = Math.hypot(u2, p3);\n return m2 \u003e 0 ? { x: u2 / m2, y: p3 / m2 } : { x: 0, y: -1 };\n}\nfunction W$(e36, t2, n2, o3, i3, r3, s2, a3, c3, l3) {\n for (let h2 = 0;h2 \u003c= l3; h2++) {\n const d2 = h2 / l3, u2 = 1 - d2, p3 = u2 * u2, m2 = p3 * u2, g2 = d2 * d2, f2 = g2 * d2, _2 = 2 * h2;\n c3[_2] = m2 * e36 + 3 * p3 * d2 * n2 + 3 * u2 * g2 * i3 + f2 * s2, c3[_2 + 1] = m2 * t2 + 3 * p3 * d2 * o3 + 3 * u2 * g2 * r3 + f2 * a3;\n }\n}\nfunction G$(e36, t2, n2, o3, i3) {\n const r3 = [];\n for (let s2 = 0;s2 \u003c= i3; s2++) {\n const a3 = s2 / i3, c3 = 1 - a3, l3 = c3 * c3, h2 = l3 * c3, d2 = a3 * a3, u2 = d2 * a3;\n r3.push({ x: h2 * e36.x + 3 * l3 * a3 * t2.x + 3 * c3 * d2 * n2.x + u2 * o3.x, y: h2 * e36.y + 3 * l3 * a3 * t2.y + 3 * c3 * d2 * n2.y + u2 * o3.y });\n }\n return r3;\n}\nfunction U$(e36, t2, n2, o3, i3, r3) {\n const s2 = i3 - n2, a3 = r3 - o3, c3 = s2 * s2 + a3 * a3;\n if (c3 === 0) {\n const i4 = e36 - n2, r4 = t2 - o3;\n return i4 * i4 + r4 * r4;\n }\n const l3 = Math.max(0, Math.min(1, ((e36 - n2) * s2 + (t2 - o3) * a3) / c3)), h2 = e36 - (n2 + l3 * s2), d2 = t2 - (o3 + l3 * a3);\n return h2 * h2 + d2 * d2;\n}\nfunction Z$(e36, t2, n2, o3, i3, r3, s2, a3) {\n const c3 = (s2 - i3) * (t2 - r3) - (a3 - r3) * (e36 - i3), l3 = (s2 - i3) * (o3 - r3) - (a3 - r3) * (n2 - i3), h2 = (n2 - e36) * (r3 - t2) - (o3 - t2) * (i3 - e36), d2 = (n2 - e36) * (a3 - t2) - (o3 - t2) * (s2 - e36);\n return (c3 \u003e 0 \u0026\u0026 l3 \u003c 0 || c3 \u003c 0 \u0026\u0026 l3 \u003e 0) \u0026\u0026 (h2 \u003e 0 \u0026\u0026 d2 \u003c 0 || h2 \u003c 0 \u0026\u0026 d2 \u003e 0) ? 0 : Math.min(U$(e36, t2, i3, r3, s2, a3), U$(n2, o3, i3, r3, s2, a3), U$(i3, r3, e36, t2, n2, o3), U$(s2, a3, e36, t2, n2, o3));\n}\nfunction q$(e36, t2, n2, o3, i3, r3, s2, a3) {\n const c3 = (s2 - i3) * (t2 - r3) - (a3 - r3) * (e36 - i3), l3 = (s2 - i3) * (o3 - r3) - (a3 - r3) * (n2 - i3), h2 = (n2 - e36) * (r3 - t2) - (o3 - t2) * (i3 - e36), d2 = (n2 - e36) * (a3 - t2) - (o3 - t2) * (s2 - e36);\n return (c3 \u003e 0 \u0026\u0026 l3 \u003c 0 || c3 \u003c 0 \u0026\u0026 l3 \u003e 0) \u0026\u0026 (h2 \u003e 0 \u0026\u0026 d2 \u003c 0 || h2 \u003c 0 \u0026\u0026 d2 \u003e 0);\n}\nfunction J$(e36, t2, n2, o3, i3) {\n const r3 = (e37) =\u003e (e37 % i3 + i3) % i3, s2 = r3(e36), a3 = r3(t2), c3 = r3(n2), l3 = r3(o3), [h2, d2] = s2 \u003c a3 ? [s2, a3] : [a3, s2];\n return c3 \u003e h2 \u0026\u0026 c3 \u003c d2 \u0026\u0026 l3 \u003e h2 \u0026\u0026 l3 \u003c d2;\n}\nfunction Q$(e36, t2) {\n let n2 = 1 / 0, o3 = -1 / 0, i3 = 1 / 0, r3 = -1 / 0;\n for (let s2 = 0;s2 \u003c t2; s2++) {\n const t3 = e36[2 * s2], a3 = e36[2 * s2 + 1];\n t3 \u003c n2 \u0026\u0026 (n2 = t3), t3 \u003e o3 \u0026\u0026 (o3 = t3), a3 \u003c i3 \u0026\u0026 (i3 = a3), a3 \u003e r3 \u0026\u0026 (r3 = a3);\n }\n return { minX: n2, maxX: o3, minY: i3, maxY: r3 };\n}\nvar K$ = class extends $ {\n constructor(e36) {\n super(), this.problem = e36;\n for (const e37 of this.problem.obstacles)\n e37.outerSegments = X$(e37);\n this.precomputeObstacles();\n }\n outputTraces = [];\n traces = [];\n optimizationStep = 0;\n maxOptimizationSteps = 100;\n sampledPoints = [];\n traceBounds = [];\n obstacleSegments = new Float64Array(0);\n obstacleNetworkIds = [];\n numObstacleSegments = 0;\n collisionPairs = [];\n lastCost = 1 / 0;\n stagnantSteps = 0;\n effectiveTraceToTraceSpacing = 0;\n getConstructorParams() {\n return this.problem;\n }\n precomputeObstacles() {\n const { obstacles: e36 } = this.problem;\n let t2 = 0;\n for (const n3 of e36)\n n3.outerSegments \u0026\u0026 (t2 += n3.outerSegments.length);\n this.obstacleSegments = new Float64Array(4 * t2), this.obstacleNetworkIds = [], this.numObstacleSegments = t2;\n let n2 = 0;\n for (const t3 of e36)\n if (t3.outerSegments)\n for (const e37 of t3.outerSegments)\n this.obstacleSegments[n2++] = e37[0].x, this.obstacleSegments[n2++] = e37[0].y, this.obstacleSegments[n2++] = e37[1].x, this.obstacleSegments[n2++] = e37[1].y, this.obstacleNetworkIds.push(t3.networkId);\n }\n initializeTraces() {\n const { bounds: e36, waypointPairs: t2 } = this.problem, { minX: n2, maxX: o3, minY: i3, maxY: r3 } = e36, s2 = o3 - n2, a3 = r3 - i3, c3 = 2 * s2 + 2 * a3, l3 = function(e37) {\n return { x: (e37.minX + e37.maxX) / 2, y: (e37.minY + e37.maxY) / 2 };\n }(e36), h2 = t2.map((t3, n3) =\u003e ({ pair: t3, t1: H$(t3.start, e36), t2: H$(t3.end, e36), idx: n3 })), d2 = h2.map(() =\u003e []), u2 = h2.map(() =\u003e []);\n for (const e37 of h2)\n for (const t3 of h2)\n if (e37.idx !== t3.idx) {\n if (e37.pair.networkId \u0026\u0026 t3.pair.networkId \u0026\u0026 e37.pair.networkId === t3.pair.networkId)\n continue;\n J$(t3.t1, t3.t2, e37.t1, e37.t2, c3) \u0026\u0026 (d2[e37.idx].push(t3.idx), u2[t3.idx].push(e37.idx));\n }\n const p3 = d2.map((e37) =\u003e e37.length), m2 = Math.max(...p3, 1);\n this.traces = h2.map(({ pair: t3, t1: n3, t2: o4, idx: i4 }) =\u003e {\n const r4 = V$(t3.start, e36), c4 = V$(t3.end, e36), h3 = Math.hypot(t3.end.x - t3.start.x, t3.end.y - t3.start.y), g2 = p3[i4] / m2, f2 = (t3.start.x + t3.end.x) / 2, _2 = (t3.start.y + t3.end.y) / 2, y2 = h3 * (0.25 + 0.15 * (1 - Math.hypot(f2 - l3.x, _2 - l3.y) / Math.hypot(s2 / 2, a3 / 2))) * (1 - 0.3 * g2), b2 = 0.05 * Math.min(s2, a3), x2 = Math.max(b2, y2), v2 = Math.max(b2, y2);\n return { waypointPair: t3, ctrl1: { x: t3.start.x + x2 * r4.x, y: t3.start.y + x2 * r4.y }, ctrl2: { x: t3.end.x + v2 * c4.x, y: t3.end.y + v2 * c4.y }, networkId: t3.networkId, t1: n3, t2: o4, perpDir1: r4, perpDir2: c4, d1: x2, d2: v2, containedBy: d2[i4], contains: u2[i4] };\n }), this.sampledPoints = this.traces.map(() =\u003e new Float64Array(12)), this.traceBounds = this.traces.map(() =\u003e ({ minX: 0, maxX: 0, minY: 0, maxY: 0 })), this.updateSampledTraces(), this.updateCollisionPairs();\n }\n updateSampledTraces() {\n for (let e36 = 0;e36 \u003c this.traces.length; e36++) {\n const t2 = this.traces[e36];\n W$(t2.waypointPair.start.x, t2.waypointPair.start.y, t2.ctrl1.x, t2.ctrl1.y, t2.ctrl2.x, t2.ctrl2.y, t2.waypointPair.end.x, t2.waypointPair.end.y, this.sampledPoints[e36], 5), this.traceBounds[e36] = Q$(this.sampledPoints[e36], 6);\n }\n }\n updateSingleTraceSample(e36) {\n const t2 = this.traces[e36];\n W$(t2.waypointPair.start.x, t2.waypointPair.start.y, t2.ctrl1.x, t2.ctrl1.y, t2.ctrl2.x, t2.ctrl2.y, t2.waypointPair.end.x, t2.waypointPair.end.y, this.sampledPoints[e36], 5), this.traceBounds[e36] = Q$(this.sampledPoints[e36], 6);\n }\n updateControlPointsFromDistances(e36) {\n const t2 = this.traces[e36], { minX: n2, maxX: o3, minY: i3, maxY: r3 } = this.problem.bounds, s2 = 0.000001;\n let a3 = t2.waypointPair.start.x + t2.d1 * t2.perpDir1.x, c3 = t2.waypointPair.start.y + t2.d1 * t2.perpDir1.y, l3 = t2.waypointPair.end.x + t2.d2 * t2.perpDir2.x, h2 = t2.waypointPair.end.y + t2.d2 * t2.perpDir2.y;\n const d2 = t2.waypointPair.start;\n Math.abs(d2.x - n2) \u003c s2 \u0026\u0026 (a3 = Math.max(a3, n2)), Math.abs(d2.x - o3) \u003c s2 \u0026\u0026 (a3 = Math.min(a3, o3)), Math.abs(d2.y - i3) \u003c s2 \u0026\u0026 (c3 = Math.max(c3, i3)), Math.abs(d2.y - r3) \u003c s2 \u0026\u0026 (c3 = Math.min(c3, r3));\n const u2 = t2.waypointPair.end;\n Math.abs(u2.x - n2) \u003c s2 \u0026\u0026 (l3 = Math.max(l3, n2)), Math.abs(u2.x - o3) \u003c s2 \u0026\u0026 (l3 = Math.min(l3, o3)), Math.abs(u2.y - i3) \u003c s2 \u0026\u0026 (h2 = Math.max(h2, i3)), Math.abs(u2.y - r3) \u003c s2 \u0026\u0026 (h2 = Math.min(h2, r3)), a3 = Math.max(n2, Math.min(o3, a3)), c3 = Math.max(i3, Math.min(r3, c3)), l3 = Math.max(n2, Math.min(o3, l3)), h2 = Math.max(i3, Math.min(r3, h2)), t2.ctrl1.x = a3, t2.ctrl1.y = c3, t2.ctrl2.x = l3, t2.ctrl2.y = h2;\n }\n updateCollisionPairs() {\n const e36 = this.effectiveTraceToTraceSpacing;\n this.collisionPairs = [];\n for (let t2 = 0;t2 \u003c this.traces.length; t2++)\n for (let n2 = t2 + 1;n2 \u003c this.traces.length; n2++) {\n const o3 = this.traces[t2], i3 = this.traces[n2];\n if (o3.networkId \u0026\u0026 i3.networkId \u0026\u0026 o3.networkId === i3.networkId)\n continue;\n const r3 = this.traceBounds[t2], s2 = this.traceBounds[n2];\n r3.maxX + e36 \u003e= s2.minX \u0026\u0026 s2.maxX + e36 \u003e= r3.minX \u0026\u0026 r3.maxY + e36 \u003e= s2.minY \u0026\u0026 s2.maxY + e36 \u003e= r3.minY \u0026\u0026 this.collisionPairs.push([t2, n2]);\n }\n }\n computeTotalCost() {\n const { preferredObstacleToTraceSpacing: e36 } = this.problem, t2 = this.effectiveTraceToTraceSpacing, n2 = t2 ** 2, o3 = e36 ** 2;\n let i3 = 0;\n for (const [e37, o4] of this.collisionPairs) {\n const r3 = this.sampledPoints[e37], s2 = this.sampledPoints[o4];\n for (let e38 = 0;e38 \u003c 5; e38++) {\n const o5 = r3[2 * e38], a3 = r3[2 * e38 + 1], c3 = r3[2 * (e38 + 1)], l3 = r3[2 * (e38 + 1) + 1];\n for (let e39 = 0;e39 \u003c 5; e39++) {\n const r4 = Z$(o5, a3, c3, l3, s2[2 * e39], s2[2 * e39 + 1], s2[2 * (e39 + 1)], s2[2 * (e39 + 1) + 1]);\n if (r4 \u003c n2) {\n i3 += (t2 - Math.sqrt(r4)) ** 2, r4 \u003c 0.000000000000000001 \u0026\u0026 (i3 += 20 * n2);\n }\n }\n }\n }\n for (let t3 = 0;t3 \u003c this.traces.length; t3++) {\n const n3 = this.traces[t3], r3 = this.sampledPoints[t3], s2 = this.traceBounds[t3];\n for (let t4 = 0;t4 \u003c this.numObstacleSegments; t4++) {\n if (n3.networkId \u0026\u0026 this.obstacleNetworkIds[t4] \u0026\u0026 n3.networkId === this.obstacleNetworkIds[t4])\n continue;\n const a3 = 4 * t4, c3 = this.obstacleSegments[a3], l3 = this.obstacleSegments[a3 + 1], h2 = this.obstacleSegments[a3 + 2], d2 = this.obstacleSegments[a3 + 3], u2 = Math.min(c3, h2), p3 = Math.max(c3, h2), m2 = Math.min(l3, d2), g2 = Math.max(l3, d2);\n if (!(s2.maxX + e36 \u003c u2 || p3 + e36 \u003c s2.minX || s2.maxY + e36 \u003c m2 || g2 + e36 \u003c s2.minY))\n for (let t5 = 0;t5 \u003c 5; t5++) {\n const n4 = Z$(r3[2 * t5], r3[2 * t5 + 1], r3[2 * (t5 + 1)], r3[2 * (t5 + 1) + 1], c3, l3, h2, d2);\n if (n4 \u003c o3) {\n i3 += (e36 - Math.sqrt(n4)) ** 2, n4 \u003c 0.000000000000000001 \u0026\u0026 (i3 += 20 * o3);\n }\n }\n }\n }\n return i3;\n }\n computeCostForTrace(e36) {\n const { preferredObstacleToTraceSpacing: t2 } = this.problem, n2 = this.effectiveTraceToTraceSpacing, o3 = n2 ** 2, i3 = t2 ** 2, r3 = this.traces[e36], s2 = this.sampledPoints[e36], a3 = this.traceBounds[e36];\n let c3 = 0;\n for (let t3 = 0;t3 \u003c this.traces.length; t3++) {\n if (t3 === e36)\n continue;\n const i4 = this.traces[t3];\n if (r3.networkId \u0026\u0026 i4.networkId \u0026\u0026 r3.networkId === i4.networkId)\n continue;\n const l3 = this.traceBounds[t3];\n if (a3.maxX + n2 \u003c l3.minX || l3.maxX + n2 \u003c a3.minX || a3.maxY + n2 \u003c l3.minY || l3.maxY + n2 \u003c a3.minY)\n continue;\n const h2 = this.sampledPoints[t3];\n for (let e37 = 0;e37 \u003c 5; e37++) {\n const t4 = s2[2 * e37], i5 = s2[2 * e37 + 1], r4 = s2[2 * (e37 + 1)], a4 = s2[2 * (e37 + 1) + 1];\n for (let e38 = 0;e38 \u003c 5; e38++) {\n const s3 = Z$(t4, i5, r4, a4, h2[2 * e38], h2[2 * e38 + 1], h2[2 * (e38 + 1)], h2[2 * (e38 + 1) + 1]);\n if (s3 \u003c o3) {\n c3 += (n2 - Math.sqrt(s3)) ** 2, s3 \u003c 0.000000000000000001 \u0026\u0026 (c3 += 20 * o3);\n }\n }\n }\n }\n for (let e37 = 0;e37 \u003c this.numObstacleSegments; e37++) {\n if (r3.networkId \u0026\u0026 this.obstacleNetworkIds[e37] \u0026\u0026 r3.networkId === this.obstacleNetworkIds[e37])\n continue;\n const n3 = 4 * e37, o4 = this.obstacleSegments[n3], l3 = this.obstacleSegments[n3 + 1], h2 = this.obstacleSegments[n3 + 2], d2 = this.obstacleSegments[n3 + 3], u2 = Math.min(o4, h2), p3 = Math.max(o4, h2), m2 = Math.min(l3, d2), g2 = Math.max(l3, d2);\n if (!(a3.maxX + t2 \u003c u2 || p3 + t2 \u003c a3.minX || a3.maxY + t2 \u003c m2 || g2 + t2 \u003c a3.minY))\n for (let e38 = 0;e38 \u003c 5; e38++) {\n const n4 = Z$(s2[2 * e38], s2[2 * e38 + 1], s2[2 * (e38 + 1)], s2[2 * (e38 + 1) + 1], o4, l3, h2, d2);\n if (n4 \u003c i3) {\n c3 += (t2 - Math.sqrt(n4)) ** 2, n4 \u003c 0.000000000000000001 \u0026\u0026 (c3 += 20 * i3);\n }\n }\n }\n return c3;\n }\n tracesIntersect(e36, t2) {\n const n2 = this.traces[e36], o3 = this.traces[t2], i3 = 15, r3 = new Float64Array(32), s2 = new Float64Array(32);\n W$(n2.waypointPair.start.x, n2.waypointPair.start.y, n2.ctrl1.x, n2.ctrl1.y, n2.ctrl2.x, n2.ctrl2.y, n2.waypointPair.end.x, n2.waypointPair.end.y, r3, i3), W$(o3.waypointPair.start.x, o3.waypointPair.start.y, o3.ctrl1.x, o3.ctrl1.y, o3.ctrl2.x, o3.ctrl2.y, o3.waypointPair.end.x, o3.waypointPair.end.y, s2, i3);\n for (let e37 = 0;e37 \u003c i3; e37++) {\n const t3 = r3[2 * e37], n3 = r3[2 * e37 + 1], o4 = r3[2 * (e37 + 1)], a3 = r3[2 * (e37 + 1) + 1];\n for (let e38 = 0;e38 \u003c i3; e38++) {\n if (q$(t3, n3, o4, a3, s2[2 * e38], s2[2 * e38 + 1], s2[2 * (e38 + 1)], s2[2 * (e38 + 1) + 1]))\n return true;\n }\n }\n return false;\n }\n findIntersectingPairs() {\n const e36 = [];\n for (let t2 = 0;t2 \u003c this.traces.length; t2++)\n for (let n2 = t2 + 1;n2 \u003c this.traces.length; n2++) {\n const o3 = this.traces[t2], i3 = this.traces[n2];\n if (o3.networkId \u0026\u0026 i3.networkId \u0026\u0026 o3.networkId === i3.networkId)\n continue;\n const r3 = this.traceBounds[t2], s2 = this.traceBounds[n2];\n r3.maxX \u003c s2.minX || s2.maxX \u003c r3.minX || r3.maxY \u003c s2.minY || s2.maxY \u003c r3.minY || this.tracesIntersect(t2, n2) \u0026\u0026 e36.push([t2, n2]);\n }\n return e36;\n }\n resolveIntersections() {\n const { bounds: e36, preferredTraceToTraceSpacing: t2 } = this.problem, { minX: n2, maxX: o3, minY: i3, maxY: r3 } = e36, s2 = Math.min(o3 - n2, r3 - i3), a3 = 0.02 * s2, c3 = 1.5 * s2, l3 = this.findIntersectingPairs();\n if (l3.length === 0)\n return 0;\n let h2 = 0;\n for (const [e37, n3] of l3) {\n const o4 = this.traces[e37], i4 = this.traces[n3];\n if (!this.tracesIntersect(e37, n3))\n continue;\n let r4, s3;\n if (o4.containedBy.includes(n3))\n r4 = n3, s3 = e37;\n else if (i4.containedBy.includes(e37))\n r4 = e37, s3 = n3;\n else {\n (o4.d1 + o4.d2) / 2 \u003c (i4.d1 + i4.d2) / 2 ? (r4 = e37, s3 = n3) : (r4 = n3, s3 = e37);\n }\n const l4 = this.traces[r4], d2 = this.traces[s3], u2 = l4.d1, p3 = l4.d2, m2 = d2.d1, g2 = d2.d2, f2 = 2 * t2, _2 = [{ innerMult: 1, outerMult: 0 }, { innerMult: 0, outerMult: 1 }, { innerMult: 0.5, outerMult: 0.5 }, { innerMult: 2, outerMult: 0 }, { innerMult: 1, outerMult: 1 }, { innerMult: 3, outerMult: 0 }, { innerMult: 2, outerMult: 1 }, { innerMult: 4, outerMult: 0 }];\n let y2 = this.computeTotalCost(), b2 = null;\n for (const e38 of _2)\n if (l4.d1 = u2, l4.d2 = p3, d2.d1 = m2, d2.d2 = g2, d2.d1 = Math.min(c3, m2 + f2 * e38.innerMult), d2.d2 = Math.min(c3, g2 + f2 * e38.innerMult), l4.d1 = Math.max(a3, u2 - f2 * e38.outerMult), l4.d2 = Math.max(a3, p3 - f2 * e38.outerMult), this.updateControlPointsFromDistances(s3), this.updateControlPointsFromDistances(r4), this.updateSingleTraceSample(s3), this.updateSingleTraceSample(r4), !this.tracesIntersect(r4, s3)) {\n const t3 = this.computeTotalCost();\n (b2 === null || t3 \u003c y2) \u0026\u0026 (y2 = t3, b2 = e38);\n }\n b2 ? (d2.d1 = Math.min(c3, m2 + f2 * b2.innerMult), d2.d2 = Math.min(c3, g2 + f2 * b2.innerMult), l4.d1 = Math.max(a3, u2 - f2 * b2.outerMult), l4.d2 = Math.max(a3, p3 - f2 * b2.outerMult), this.updateControlPointsFromDistances(s3), this.updateControlPointsFromDistances(r4), this.updateSingleTraceSample(s3), this.updateSingleTraceSample(r4), h2++) : (l4.d1 = u2, l4.d2 = p3, d2.d1 = m2, d2.d2 = g2, this.updateControlPointsFromDistances(r4), this.updateControlPointsFromDistances(s3), this.updateSingleTraceSample(r4), this.updateSingleTraceSample(s3));\n }\n return h2;\n }\n optimizeStep() {\n const { bounds: e36 } = this.problem, { minX: t2, maxX: n2, minY: o3, maxY: i3 } = e36, r3 = Math.min(n2 - t2, i3 - o3), s2 = this.effectiveTraceToTraceSpacing, a3 = 4 * (1 - this.optimizationStep / this.maxOptimizationSteps) + 0.5, c3 = 0.02 * r3, l3 = 1.5 * r3, h2 = [];\n for (let e37 = 0;e37 \u003c this.traces.length; e37++)\n h2.push({ idx: e37, cost: this.computeCostForTrace(e37) });\n h2.sort((e37, t3) =\u003e t3.cost - e37.cost);\n for (const { idx: e37, cost: t3 } of h2) {\n if (t3 === 0)\n continue;\n const n3 = this.traces[e37], o4 = t3 \u003e 100 ? 2 : 1, i4 = [a3 * o4, 1.5 * a3 * o4, 0.5 * a3];\n for (const o5 of i4) {\n const i5 = t3 \u003e 100 ? [o5, -o5, 2 * o5, 2 * -o5, 3 * o5, 3 * -o5, 2 * s2, 2 * -s2] : [o5, -o5, 2 * o5, 2 * -o5];\n let r4 = this.computeCostForTrace(e37), a4 = n3.d1, h3 = n3.d2;\n const { d1: d2, d2: u2 } = n3;\n for (const t4 of i5) {\n n3.d1 = Math.max(c3, Math.min(l3, d2 + t4)), this.updateControlPointsFromDistances(e37), this.updateSingleTraceSample(e37);\n const o6 = this.computeCostForTrace(e37);\n o6 \u003c r4 \u0026\u0026 (r4 = o6, a4 = n3.d1, h3 = u2), n3.d1 = d2, this.updateControlPointsFromDistances(e37), n3.d2 = Math.max(c3, Math.min(l3, u2 + t4)), this.updateControlPointsFromDistances(e37), this.updateSingleTraceSample(e37);\n const i6 = this.computeCostForTrace(e37);\n i6 \u003c r4 \u0026\u0026 (r4 = i6, a4 = d2, h3 = n3.d2), n3.d2 = u2, this.updateControlPointsFromDistances(e37), n3.d1 = Math.max(c3, Math.min(l3, d2 + t4)), n3.d2 = Math.max(c3, Math.min(l3, u2 + t4)), this.updateControlPointsFromDistances(e37), this.updateSingleTraceSample(e37);\n const s3 = this.computeCostForTrace(e37);\n s3 \u003c r4 \u0026\u0026 (r4 = s3, a4 = n3.d1, h3 = n3.d2), n3.d1 = d2, n3.d2 = u2, this.updateControlPointsFromDistances(e37), n3.d1 = Math.max(c3, Math.min(l3, d2 + t4)), n3.d2 = Math.max(c3, Math.min(l3, u2 - t4)), this.updateControlPointsFromDistances(e37), this.updateSingleTraceSample(e37);\n const p3 = this.computeCostForTrace(e37);\n p3 \u003c r4 \u0026\u0026 (r4 = p3, a4 = n3.d1, h3 = n3.d2), n3.d1 = d2, n3.d2 = u2, this.updateControlPointsFromDistances(e37);\n }\n if (n3.d1 = a4, n3.d2 = h3, this.updateControlPointsFromDistances(e37), this.updateSingleTraceSample(e37), r4 \u003c 0.9 * t3)\n break;\n }\n }\n this.optimizationStep % 10 == 0 \u0026\u0026 this.updateCollisionPairs();\n }\n buildOutputTraces() {\n this.outputTraces = this.traces.map((e36) =\u003e ({ waypointPair: e36.waypointPair, points: G$(e36.waypointPair.start, e36.ctrl1, e36.ctrl2, e36.waypointPair.end, 20), networkId: e36.networkId }));\n }\n _step() {\n if (this.traces.length === 0 \u0026\u0026 (this.effectiveTraceToTraceSpacing = 3 * this.problem.preferredTraceToTraceSpacing, this.initializeTraces(), this.lastCost = this.computeTotalCost(), this.stagnantSteps = 0), this.optimizationStep \u003c this.maxOptimizationSteps) {\n const e36 = 3, t2 = e36 + (1 - e36) * (this.optimizationStep / this.maxOptimizationSteps);\n if (this.effectiveTraceToTraceSpacing = this.problem.preferredTraceToTraceSpacing * t2, this.optimizeStep(), this.optimizationStep++, this.optimizationStep % 10 == 0) {\n this.resolveIntersections() \u003e 0 \u0026\u0026 this.updateCollisionPairs();\n }\n const n2 = this.computeTotalCost();\n if (n2 === 0)\n this.optimizationStep = this.maxOptimizationSteps;\n else if (n2 \u003e= 0.99 * this.lastCost) {\n if (this.stagnantSteps++, this.stagnantSteps \u003e 10) {\n this.resolveIntersections() \u003e 0 ? (this.updateCollisionPairs(), this.stagnantSteps = 0) : this.stagnantSteps \u003e 15 \u0026\u0026 (this.optimizationStep = this.maxOptimizationSteps);\n }\n } else\n this.stagnantSteps = 0;\n this.lastCost = n2;\n }\n this.optimizationStep \u003e= this.maxOptimizationSteps \u0026\u0026 (this.resolveIntersections(), this.buildOutputTraces(), this.solved = true);\n }\n visualize() {\n return this.traces.length \u003e 0 \u0026\u0026 this.buildOutputTraces(), ((e36, t2 = []) =\u003e {\n const n2 = { arrows: [], circles: [], lines: [], rects: [], coordinateSystem: \"cartesian\", points: [], texts: [], title: \"Curvy Trace Problem\" };\n n2.lines.push({ points: [{ x: e36.bounds.minX, y: e36.bounds.minY }, { x: e36.bounds.maxX, y: e36.bounds.minY }, { x: e36.bounds.maxX, y: e36.bounds.maxY }, { x: e36.bounds.minX, y: e36.bounds.maxY }, { x: e36.bounds.minX, y: e36.bounds.minY }], strokeColor: \"rgba(0, 0, 0, 0.1)\" });\n for (const t3 of e36.waypointPairs)\n n2.points.push({ ...t3.start, label: `start ${t3.networkId ?? \"\"}`, color: Y$(t3.networkId) }), n2.points.push({ ...t3.end, label: `end ${t3.networkId ?? \"\"}`, color: Y$(t3.networkId) });\n for (const t3 of e36.obstacles)\n n2.rects.push({ center: t3.center, width: t3.maxX - t3.minX, height: t3.maxY - t3.minY, fill: \"rgba(128, 128, 128, 0.3)\", stroke: \"rgba(128, 128, 128, 0.8)\", label: `netId: ${t3.networkId}` });\n for (const e37 of t2)\n n2.lines.push({ points: e37.points, strokeColor: Y$(e37.networkId) });\n return n2;\n })(this.problem, this.outputTraces);\n }\n};\nvar eY = class extends ni {\n getSolverName() {\n return \"CurvyIntraNodeSolver\";\n }\n nodeWithPortPoints;\n colorMap;\n traceWidth;\n viaDiameter;\n adjacentObstacles;\n routes = [];\n curvyTraceSolver;\n phase = \"initializing\";\n constructor(e36) {\n super(), this.nodeWithPortPoints = e36.nodeWithPortPoints, this.colorMap = e36.colorMap ?? {}, this.traceWidth = e36.traceWidth ?? 0.15, this.viaDiameter = e36.viaDiameter ?? 0.3, this.adjacentObstacles = e36.adjacentObstacles ?? [], this.MAX_ITERATIONS = 1000;\n }\n _step() {\n switch (this.phase) {\n case \"initializing\":\n this._initializeCurvySolver();\n break;\n case \"solving\":\n this._stepCurvySolver();\n break;\n case \"done\":\n this.solved = true;\n }\n }\n _initializeCurvySolver() {\n const e36 = this.nodeWithPortPoints, t2 = { minX: e36.center.x - e36.width / 2, minY: e36.center.y - e36.height / 2, maxX: e36.center.x + e36.width / 2, maxY: e36.center.y + e36.height / 2 }, n2 = new Map;\n for (const t3 of e36.portPoints)\n n2.has(t3.connectionName) || n2.set(t3.connectionName, []), n2.get(t3.connectionName).push(t3);\n const o3 = [];\n for (const [e37, t3] of n2) {\n if (t3.length \u003c 2)\n continue;\n const n3 = t3[0], i4 = t3[t3.length - 1];\n o3.push({ start: { x: n3.x, y: n3.y }, end: { x: i4.x, y: i4.y }, networkId: e37 });\n }\n if (o3.length === 0)\n return void (this.phase = \"done\");\n const i3 = { bounds: t2, waypointPairs: o3, obstacles: this.adjacentObstacles.map((e37) =\u003e ({ minX: e37.minX, minY: e37.minY, maxX: e37.maxX, maxY: e37.maxY, center: { x: (e37.minX + e37.maxX) / 2, y: (e37.minY + e37.maxY) / 2 }, networkId: e37.networkId })), preferredTraceToTraceSpacing: 2 * this.traceWidth, preferredObstacleToTraceSpacing: 2 * this.traceWidth };\n this.curvyTraceSolver = new K$(i3), this.phase = \"solving\";\n }\n _stepCurvySolver() {\n this.curvyTraceSolver ? (this.activeSubSolver = this.curvyTraceSolver, this.curvyTraceSolver.step(), this.curvyTraceSolver.solved ? (this._convertOutputTraces(), this.phase = \"done\") : this.curvyTraceSolver.failed \u0026\u0026 (this.error = this.curvyTraceSolver.error, this.failed = true)) : this.phase = \"done\";\n }\n _convertOutputTraces() {\n if (!this.curvyTraceSolver)\n return;\n const e36 = this.nodeWithPortPoints, t2 = new Map;\n for (const n2 of e36.portPoints) {\n const e37 = n2.connectionName;\n t2.has(e37) || t2.set(e37, { connectionName: n2.connectionName, rootConnectionName: n2.rootConnectionName, z: n2.z });\n }\n for (const e37 of this.curvyTraceSolver.outputTraces) {\n const n2 = e37.networkId ?? \"\", o3 = t2.get(n2);\n if (!o3)\n continue;\n const i3 = { connectionName: o3.connectionName, rootConnectionName: o3.rootConnectionName, traceThickness: this.traceWidth, viaDiameter: this.viaDiameter, route: e37.points.map((e38) =\u003e ({ x: e38.x, y: e38.y, z: o3.z })), vias: [] };\n this.routes.push(i3);\n }\n }\n getConstructorParams() {\n return { nodeWithPortPoints: this.nodeWithPortPoints, colorMap: this.colorMap, traceWidth: this.traceWidth, viaDiameter: this.viaDiameter, adjacentObstacles: this.adjacentObstacles };\n }\n visualize() {\n const e36 = { lines: [], points: [], rects: [], circles: [] }, t2 = this.nodeWithPortPoints;\n e36.rects.push({ center: t2.center, width: t2.width, height: t2.height, fill: \"rgba(0, 200, 0, 0.1)\", stroke: \"rgba(0, 200, 0, 0.5)\", label: t2.capacityMeshNodeId });\n for (const t3 of this.adjacentObstacles)\n e36.rects.push({ center: { x: (t3.minX + t3.maxX) / 2, y: (t3.minY + t3.maxY) / 2 }, width: t3.maxX - t3.minX, height: t3.maxY - t3.minY, fill: \"rgba(255, 0, 0, 0.1)\", stroke: \"rgba(255, 0, 0, 0.3)\", label: `obstacle: ${t3.networkId ?? \"\"}` });\n if (this.curvyTraceSolver) {\n const t3 = this.curvyTraceSolver.visualize();\n t3.lines \u0026\u0026 e36.lines.push(...t3.lines), t3.points \u0026\u0026 e36.points.push(...t3.points), t3.rects \u0026\u0026 e36.rects.push(...t3.rects), t3.circles \u0026\u0026 e36.circles.push(...t3.circles);\n }\n for (const t3 of this.routes) {\n const n2 = this.colorMap[t3.connectionName] ?? \"gray\";\n e36.lines.push({ points: t3.route.map((e37) =\u003e ({ x: e37.x, y: e37.y })), strokeColor: n2, strokeWidth: this.traceWidth, label: t3.connectionName });\n }\n for (const n2 of t2.portPoints) {\n const t3 = this.colorMap[n2.connectionName] ?? \"gray\";\n e36.points.push({ x: n2.x, y: n2.y, color: t3, label: n2.connectionName });\n }\n return e36;\n }\n};\nvar iY = Object.create;\nvar rY = Object.defineProperty;\nvar sY = Object.getOwnPropertyDescriptor;\nvar aY = Object.getOwnPropertyNames;\nvar cY = Object.getPrototypeOf;\nvar lY = Object.prototype.hasOwnProperty;\nvar hY = (e36, t2) =\u003e function() {\n return t2 || (0, e36[aY(e36)[0]])((t2 = { exports: {} }).exports, t2), t2.exports;\n};\nvar dY = hY({ \"node_modules/binary-search-bounds/search-bounds.js\"(e36, t2) {\n function n2(e37, t3, n3, o4, i4) {\n for (var r4 = i4 + 1;o4 \u003c= i4; ) {\n var s3 = o4 + i4 \u003e\u003e\u003e 1, a4 = e37[s3];\n (n3 !== undefined ? n3(a4, t3) : a4 - t3) \u003e= 0 ? (r4 = s3, i4 = s3 - 1) : o4 = s3 + 1;\n }\n return r4;\n }\n function o3(e37, t3, n3, o4, i4) {\n for (var r4 = i4 + 1;o4 \u003c= i4; ) {\n var s3 = o4 + i4 \u003e\u003e\u003e 1, a4 = e37[s3];\n (n3 !== undefined ? n3(a4, t3) : a4 - t3) \u003e 0 ? (r4 = s3, i4 = s3 - 1) : o4 = s3 + 1;\n }\n return r4;\n }\n function i3(e37, t3, n3, o4, i4) {\n for (var r4 = o4 - 1;o4 \u003c= i4; ) {\n var s3 = o4 + i4 \u003e\u003e\u003e 1, a4 = e37[s3];\n (n3 !== undefined ? n3(a4, t3) : a4 - t3) \u003c 0 ? (r4 = s3, o4 = s3 + 1) : i4 = s3 - 1;\n }\n return r4;\n }\n function r3(e37, t3, n3, o4, i4) {\n for (var r4 = o4 - 1;o4 \u003c= i4; ) {\n var s3 = o4 + i4 \u003e\u003e\u003e 1, a4 = e37[s3];\n (n3 !== undefined ? n3(a4, t3) : a4 - t3) \u003c= 0 ? (r4 = s3, o4 = s3 + 1) : i4 = s3 - 1;\n }\n return r4;\n }\n function s2(e37, t3, n3, o4, i4) {\n for (;o4 \u003c= i4; ) {\n var r4 = o4 + i4 \u003e\u003e\u003e 1, s3 = e37[r4], a4 = n3 !== undefined ? n3(s3, t3) : s3 - t3;\n if (a4 === 0)\n return r4;\n a4 \u003c= 0 ? o4 = r4 + 1 : i4 = r4 - 1;\n }\n return -1;\n }\n function a3(e37, t3, n3, o4, i4, r4) {\n return typeof n3 == \"function\" ? r4(e37, t3, n3, o4 === undefined ? 0 : 0 | o4, i4 === undefined ? e37.length - 1 : 0 | i4) : r4(e37, t3, undefined, n3 === undefined ? 0 : 0 | n3, o4 === undefined ? e37.length - 1 : 0 | o4);\n }\n t2.exports = { ge: function(e37, t3, o4, i4, r4) {\n return a3(e37, t3, o4, i4, r4, n2);\n }, gt: function(e37, t3, n3, i4, r4) {\n return a3(e37, t3, n3, i4, r4, o3);\n }, lt: function(e37, t3, n3, o4, r4) {\n return a3(e37, t3, n3, o4, r4, i3);\n }, le: function(e37, t3, n3, o4, i4) {\n return a3(e37, t3, n3, o4, i4, r3);\n }, eq: function(e37, t3, n3, o4, i4) {\n return a3(e37, t3, n3, o4, i4, s2);\n } };\n} });\nvar uY = hY({ \"node_modules/two-product/two-product.js\"(e36, t2) {\n t2.exports = function(e37, t3, o3) {\n var i3 = e37 * t3, r3 = n2 * e37, s2 = r3 - (r3 - e37), a3 = e37 - s2, c3 = n2 * t3, l3 = c3 - (c3 - t3), h2 = t3 - l3, d2 = a3 * h2 - (i3 - s2 * l3 - a3 * l3 - s2 * h2);\n if (o3)\n return o3[0] = d2, o3[1] = i3, o3;\n return [d2, i3];\n };\n var n2 = +(Math.pow(2, 27) + 1);\n} });\nvar pY = hY({ \"node_modules/robust-sum/robust-sum.js\"(e36, t2) {\n t2.exports = function(e37, t3) {\n var n2 = 0 | e37.length, o3 = 0 | t3.length;\n if (n2 === 1 \u0026\u0026 o3 === 1)\n return function(e38, t4) {\n var n3 = e38 + t4, o4 = n3 - e38, i4 = n3 - o4, r4 = t4 - o4, s3 = e38 - i4, a4 = s3 + r4;\n if (a4)\n return [a4, n3];\n return [n3];\n }(e37[0], t3[0]);\n var i3, r3, s2 = new Array(n2 + o3), a3 = 0, c3 = 0, l3 = 0, h2 = Math.abs, d2 = e37[c3], u2 = h2(d2), p3 = t3[l3], m2 = h2(p3);\n u2 \u003c m2 ? (r3 = d2, (c3 += 1) \u003c n2 \u0026\u0026 (u2 = h2(d2 = e37[c3]))) : (r3 = p3, (l3 += 1) \u003c o3 \u0026\u0026 (m2 = h2(p3 = t3[l3])));\n c3 \u003c n2 \u0026\u0026 u2 \u003c m2 || l3 \u003e= o3 ? (i3 = d2, (c3 += 1) \u003c n2 \u0026\u0026 (u2 = h2(d2 = e37[c3]))) : (i3 = p3, (l3 += 1) \u003c o3 \u0026\u0026 (m2 = h2(p3 = t3[l3])));\n var g2, f2, _2 = i3 + r3, y2 = _2 - i3, b2 = r3 - y2, x2 = b2, v2 = _2;\n for (;c3 \u003c n2 \u0026\u0026 l3 \u003c o3; )\n u2 \u003c m2 ? (i3 = d2, (c3 += 1) \u003c n2 \u0026\u0026 (u2 = h2(d2 = e37[c3]))) : (i3 = p3, (l3 += 1) \u003c o3 \u0026\u0026 (m2 = h2(p3 = t3[l3]))), (b2 = (r3 = x2) - (y2 = (_2 = i3 + r3) - i3)) \u0026\u0026 (s2[a3++] = b2), x2 = v2 - ((g2 = v2 + _2) - (f2 = g2 - v2)) + (_2 - f2), v2 = g2;\n for (;c3 \u003c n2; )\n (b2 = (r3 = x2) - (y2 = (_2 = (i3 = d2) + r3) - i3)) \u0026\u0026 (s2[a3++] = b2), x2 = v2 - ((g2 = v2 + _2) - (f2 = g2 - v2)) + (_2 - f2), v2 = g2, (c3 += 1) \u003c n2 \u0026\u0026 (d2 = e37[c3]);\n for (;l3 \u003c o3; )\n (b2 = (r3 = x2) - (y2 = (_2 = (i3 = p3) + r3) - i3)) \u0026\u0026 (s2[a3++] = b2), x2 = v2 - ((g2 = v2 + _2) - (f2 = g2 - v2)) + (_2 - f2), v2 = g2, (l3 += 1) \u003c o3 \u0026\u0026 (p3 = t3[l3]);\n x2 \u0026\u0026 (s2[a3++] = x2);\n v2 \u0026\u0026 (s2[a3++] = v2);\n a3 || (s2[a3++] = 0);\n return s2.length = a3, s2;\n };\n} });\nvar mY = hY({ \"node_modules/two-sum/two-sum.js\"(e36, t2) {\n t2.exports = function(e37, t3, n2) {\n var o3 = e37 + t3, i3 = o3 - e37, r3 = t3 - i3, s2 = e37 - (o3 - i3);\n if (n2)\n return n2[0] = s2 + r3, n2[1] = o3, n2;\n return [s2 + r3, o3];\n };\n} });\nvar gY = hY({ \"node_modules/robust-scale/robust-scale.js\"(e36, t2) {\n var n2 = uY(), o3 = mY();\n t2.exports = function(e37, t3) {\n var i3 = e37.length;\n if (i3 === 1) {\n var r3 = n2(e37[0], t3);\n return r3[0] ? r3 : [r3[1]];\n }\n var s2 = new Array(2 * i3), a3 = [0.1, 0.1], c3 = [0.1, 0.1], l3 = 0;\n n2(e37[0], t3, a3), a3[0] \u0026\u0026 (s2[l3++] = a3[0]);\n for (var h2 = 1;h2 \u003c i3; ++h2) {\n n2(e37[h2], t3, c3);\n var d2 = a3[1];\n o3(d2, c3[0], a3), a3[0] \u0026\u0026 (s2[l3++] = a3[0]);\n var u2 = c3[1], p3 = a3[1], m2 = u2 + p3, g2 = p3 - (m2 - u2);\n a3[1] = m2, g2 \u0026\u0026 (s2[l3++] = g2);\n }\n a3[1] \u0026\u0026 (s2[l3++] = a3[1]);\n l3 === 0 \u0026\u0026 (s2[l3++] = 0);\n return s2.length = l3, s2;\n };\n} });\nvar fY = hY({ \"node_modules/robust-subtract/robust-diff.js\"(e36, t2) {\n t2.exports = function(e37, t3) {\n var n2 = 0 | e37.length, o3 = 0 | t3.length;\n if (n2 === 1 \u0026\u0026 o3 === 1)\n return function(e38, t4) {\n var n3 = e38 + t4, o4 = n3 - e38, i4 = n3 - o4, r4 = t4 - o4, s3 = e38 - i4, a4 = s3 + r4;\n if (a4)\n return [a4, n3];\n return [n3];\n }(e37[0], -t3[0]);\n var i3, r3, s2 = new Array(n2 + o3), a3 = 0, c3 = 0, l3 = 0, h2 = Math.abs, d2 = e37[c3], u2 = h2(d2), p3 = -t3[l3], m2 = h2(p3);\n u2 \u003c m2 ? (r3 = d2, (c3 += 1) \u003c n2 \u0026\u0026 (u2 = h2(d2 = e37[c3]))) : (r3 = p3, (l3 += 1) \u003c o3 \u0026\u0026 (m2 = h2(p3 = -t3[l3])));\n c3 \u003c n2 \u0026\u0026 u2 \u003c m2 || l3 \u003e= o3 ? (i3 = d2, (c3 += 1) \u003c n2 \u0026\u0026 (u2 = h2(d2 = e37[c3]))) : (i3 = p3, (l3 += 1) \u003c o3 \u0026\u0026 (m2 = h2(p3 = -t3[l3])));\n var g2, f2, _2 = i3 + r3, y2 = _2 - i3, b2 = r3 - y2, x2 = b2, v2 = _2;\n for (;c3 \u003c n2 \u0026\u0026 l3 \u003c o3; )\n u2 \u003c m2 ? (i3 = d2, (c3 += 1) \u003c n2 \u0026\u0026 (u2 = h2(d2 = e37[c3]))) : (i3 = p3, (l3 += 1) \u003c o3 \u0026\u0026 (m2 = h2(p3 = -t3[l3]))), (b2 = (r3 = x2) - (y2 = (_2 = i3 + r3) - i3)) \u0026\u0026 (s2[a3++] = b2), x2 = v2 - ((g2 = v2 + _2) - (f2 = g2 - v2)) + (_2 - f2), v2 = g2;\n for (;c3 \u003c n2; )\n (b2 = (r3 = x2) - (y2 = (_2 = (i3 = d2) + r3) - i3)) \u0026\u0026 (s2[a3++] = b2), x2 = v2 - ((g2 = v2 + _2) - (f2 = g2 - v2)) + (_2 - f2), v2 = g2, (c3 += 1) \u003c n2 \u0026\u0026 (d2 = e37[c3]);\n for (;l3 \u003c o3; )\n (b2 = (r3 = x2) - (y2 = (_2 = (i3 = p3) + r3) - i3)) \u0026\u0026 (s2[a3++] = b2), x2 = v2 - ((g2 = v2 + _2) - (f2 = g2 - v2)) + (_2 - f2), v2 = g2, (l3 += 1) \u003c o3 \u0026\u0026 (p3 = -t3[l3]);\n x2 \u0026\u0026 (s2[a3++] = x2);\n v2 \u0026\u0026 (s2[a3++] = v2);\n a3 || (s2[a3++] = 0);\n return s2.length = a3, s2;\n };\n} });\nvar _Y = hY({ \"node_modules/robust-orientation/orientation.js\"(e36, t2) {\n var n2 = uY(), o3 = pY(), i3 = gY(), r3 = fY();\n function s2(e37, t3, n3, o4) {\n return function(n4, i4, r4) {\n var s3 = e37(e37(t3(i4[1], r4[0]), t3(-r4[1], i4[0])), e37(t3(n4[1], i4[0]), t3(-i4[1], n4[0]))), a4 = e37(t3(n4[1], r4[0]), t3(-r4[1], n4[0])), c4 = o4(s3, a4);\n return c4[c4.length - 1];\n };\n }\n function a3(e37, t3, n3, o4) {\n return function(i4, r4, s3, a4) {\n var c4 = e37(e37(n3(e37(t3(s3[1], a4[0]), t3(-a4[1], s3[0])), r4[2]), e37(n3(e37(t3(r4[1], a4[0]), t3(-a4[1], r4[0])), -s3[2]), n3(e37(t3(r4[1], s3[0]), t3(-s3[1], r4[0])), a4[2]))), e37(n3(e37(t3(r4[1], a4[0]), t3(-a4[1], r4[0])), i4[2]), e37(n3(e37(t3(i4[1], a4[0]), t3(-a4[1], i4[0])), -r4[2]), n3(e37(t3(i4[1], r4[0]), t3(-r4[1], i4[0])), a4[2])))), l4 = e37(e37(n3(e37(t3(s3[1], a4[0]), t3(-a4[1], s3[0])), i4[2]), e37(n3(e37(t3(i4[1], a4[0]), t3(-a4[1], i4[0])), -s3[2]), n3(e37(t3(i4[1], s3[0]), t3(-s3[1], i4[0])), a4[2]))), e37(n3(e37(t3(r4[1], s3[0]), t3(-s3[1], r4[0])), i4[2]), e37(n3(e37(t3(i4[1], s3[0]), t3(-s3[1], i4[0])), -r4[2]), n3(e37(t3(i4[1], r4[0]), t3(-r4[1], i4[0])), s3[2])))), h3 = o4(c4, l4);\n return h3[h3.length - 1];\n };\n }\n function c3(e37, t3, n3, o4) {\n return function(i4, r4, s3, a4, c4) {\n var l4 = e37(e37(e37(n3(e37(n3(e37(t3(a4[1], c4[0]), t3(-c4[1], a4[0])), s3[2]), e37(n3(e37(t3(s3[1], c4[0]), t3(-c4[1], s3[0])), -a4[2]), n3(e37(t3(s3[1], a4[0]), t3(-a4[1], s3[0])), c4[2]))), r4[3]), e37(n3(e37(n3(e37(t3(a4[1], c4[0]), t3(-c4[1], a4[0])), r4[2]), e37(n3(e37(t3(r4[1], c4[0]), t3(-c4[1], r4[0])), -a4[2]), n3(e37(t3(r4[1], a4[0]), t3(-a4[1], r4[0])), c4[2]))), -s3[3]), n3(e37(n3(e37(t3(s3[1], c4[0]), t3(-c4[1], s3[0])), r4[2]), e37(n3(e37(t3(r4[1], c4[0]), t3(-c4[1], r4[0])), -s3[2]), n3(e37(t3(r4[1], s3[0]), t3(-s3[1], r4[0])), c4[2]))), a4[3]))), e37(n3(e37(n3(e37(t3(s3[1], a4[0]), t3(-a4[1], s3[0])), r4[2]), e37(n3(e37(t3(r4[1], a4[0]), t3(-a4[1], r4[0])), -s3[2]), n3(e37(t3(r4[1], s3[0]), t3(-s3[1], r4[0])), a4[2]))), -c4[3]), e37(n3(e37(n3(e37(t3(a4[1], c4[0]), t3(-c4[1], a4[0])), r4[2]), e37(n3(e37(t3(r4[1], c4[0]), t3(-c4[1], r4[0])), -a4[2]), n3(e37(t3(r4[1], a4[0]), t3(-a4[1], r4[0])), c4[2]))), i4[3]), n3(e37(n3(e37(t3(a4[1], c4[0]), t3(-c4[1], a4[0])), i4[2]), e37(n3(e37(t3(i4[1], c4[0]), t3(-c4[1], i4[0])), -a4[2]), n3(e37(t3(i4[1], a4[0]), t3(-a4[1], i4[0])), c4[2]))), -r4[3])))), e37(e37(n3(e37(n3(e37(t3(r4[1], c4[0]), t3(-c4[1], r4[0])), i4[2]), e37(n3(e37(t3(i4[1], c4[0]), t3(-c4[1], i4[0])), -r4[2]), n3(e37(t3(i4[1], r4[0]), t3(-r4[1], i4[0])), c4[2]))), a4[3]), e37(n3(e37(n3(e37(t3(r4[1], a4[0]), t3(-a4[1], r4[0])), i4[2]), e37(n3(e37(t3(i4[1], a4[0]), t3(-a4[1], i4[0])), -r4[2]), n3(e37(t3(i4[1], r4[0]), t3(-r4[1], i4[0])), a4[2]))), -c4[3]), n3(e37(n3(e37(t3(s3[1], a4[0]), t3(-a4[1], s3[0])), r4[2]), e37(n3(e37(t3(r4[1], a4[0]), t3(-a4[1], r4[0])), -s3[2]), n3(e37(t3(r4[1], s3[0]), t3(-s3[1], r4[0])), a4[2]))), i4[3]))), e37(n3(e37(n3(e37(t3(s3[1], a4[0]), t3(-a4[1], s3[0])), i4[2]), e37(n3(e37(t3(i4[1], a4[0]), t3(-a4[1], i4[0])), -s3[2]), n3(e37(t3(i4[1], s3[0]), t3(-s3[1], i4[0])), a4[2]))), -r4[3]), e37(n3(e37(n3(e37(t3(r4[1], a4[0]), t3(-a4[1], r4[0])), i4[2]), e37(n3(e37(t3(i4[1], a4[0]), t3(-a4[1], i4[0])), -r4[2]), n3(e37(t3(i4[1], r4[0]), t3(-r4[1], i4[0])), a4[2]))), s3[3]), n3(e37(n3(e37(t3(r4[1], s3[0]), t3(-s3[1], r4[0])), i4[2]), e37(n3(e37(t3(i4[1], s3[0]), t3(-s3[1], i4[0])), -r4[2]), n3(e37(t3(i4[1], r4[0]), t3(-r4[1], i4[0])), s3[2]))), -a4[3]))))), h3 = e37(e37(e37(n3(e37(n3(e37(t3(a4[1], c4[0]), t3(-c4[1], a4[0])), s3[2]), e37(n3(e37(t3(s3[1], c4[0]), t3(-c4[1], s3[0])), -a4[2]), n3(e37(t3(s3[1], a4[0]), t3(-a4[1], s3[0])), c4[2]))), i4[3]), n3(e37(n3(e37(t3(a4[1], c4[0]), t3(-c4[1], a4[0])), i4[2]), e37(n3(e37(t3(i4[1], c4[0]), t3(-c4[1], i4[0])), -a4[2]), n3(e37(t3(i4[1], a4[0]), t3(-a4[1], i4[0])), c4[2]))), -s3[3])), e37(n3(e37(n3(e37(t3(s3[1], c4[0]), t3(-c4[1], s3[0])), i4[2]), e37(n3(e37(t3(i4[1], c4[0]), t3(-c4[1], i4[0])), -s3[2]), n3(e37(t3(i4[1], s3[0]), t3(-s3[1], i4[0])), c4[2]))), a4[3]), n3(e37(n3(e37(t3(s3[1], a4[0]), t3(-a4[1], s3[0])), i4[2]), e37(n3(e37(t3(i4[1], a4[0]), t3(-a4[1], i4[0])), -s3[2]), n3(e37(t3(i4[1], s3[0]), t3(-s3[1], i4[0])), a4[2]))), -c4[3]))), e37(e37(n3(e37(n3(e37(t3(s3[1], c4[0]), t3(-c4[1], s3[0])), r4[2]), e37(n3(e37(t3(r4[1], c4[0]), t3(-c4[1], r4[0])), -s3[2]), n3(e37(t3(r4[1], s3[0]), t3(-s3[1], r4[0])), c4[2]))), i4[3]), n3(e37(n3(e37(t3(s3[1], c4[0]), t3(-c4[1], s3[0])), i4[2]), e37(n3(e37(t3(i4[1], c4[0]), t3(-c4[1], i4[0])), -s3[2]), n3(e37(t3(i4[1], s3[0]), t3(-s3[1], i4[0])), c4[2]))), -r4[3])), e37(n3(e37(n3(e37(t3(r4[1], c4[0]), t3(-c4[1], r4[0])), i4[2]), e37(n3(e37(t3(i4[1], c4[0]), t3(-c4[1], i4[0])), -r4[2]), n3(e37(t3(i4[1], r4[0]), t3(-r4[1], i4[0])), c4[2]))), s3[3]), n3(e37(n3(e37(t3(r4[1], s3[0]), t3(-s3[1], r4[0])), i4[2]), e37(n3(e37(t3(i4[1], s3[0]), t3(-s3[1], i4[0])), -r4[2]), n3(e37(t3(i4[1], r4[0]), t3(-r4[1], i4[0])), s3[2]))), -c4[3])))), d3 = o4(l4, h3);\n return d3[d3.length - 1];\n };\n }\n function l3(e37) {\n return (e37 === 3 ? s2 : e37 === 4 ? a3 : c3)(o3, n2, i3, r3);\n }\n var h2 = l3(3), d2 = l3(4), u2 = [function() {\n return 0;\n }, function() {\n return 0;\n }, function(e37, t3) {\n return t3[0] - e37[0];\n }, function(e37, t3, n3) {\n var o4, i4 = (e37[1] - n3[1]) * (t3[0] - n3[0]), r4 = (e37[0] - n3[0]) * (t3[1] - n3[1]), s3 = i4 - r4;\n if (i4 \u003e 0) {\n if (r4 \u003c= 0)\n return s3;\n o4 = i4 + r4;\n } else {\n if (!(i4 \u003c 0))\n return s3;\n if (r4 \u003e= 0)\n return s3;\n o4 = -(i4 + r4);\n }\n var a4 = 0.00000000000000033306690738754716 * o4;\n return s3 \u003e= a4 || s3 \u003c= -a4 ? s3 : h2(e37, t3, n3);\n }, function(e37, t3, n3, o4) {\n var i4 = e37[0] - o4[0], r4 = t3[0] - o4[0], s3 = n3[0] - o4[0], a4 = e37[1] - o4[1], c4 = t3[1] - o4[1], l4 = n3[1] - o4[1], h3 = e37[2] - o4[2], u3 = t3[2] - o4[2], p4 = n3[2] - o4[2], m3 = r4 * l4, g2 = s3 * c4, f2 = s3 * a4, _2 = i4 * l4, y2 = i4 * c4, b2 = r4 * a4, x2 = h3 * (m3 - g2) + u3 * (f2 - _2) + p4 * (y2 - b2), v2 = 0.0000000000000007771561172376103 * ((Math.abs(m3) + Math.abs(g2)) * Math.abs(h3) + (Math.abs(f2) + Math.abs(_2)) * Math.abs(u3) + (Math.abs(y2) + Math.abs(b2)) * Math.abs(p4));\n return x2 \u003e v2 || -x2 \u003e v2 ? x2 : d2(e37, t3, n3, o4);\n }];\n function p3(e37) {\n var t3 = u2[e37.length];\n return t3 || (t3 = u2[e37.length] = l3(e37.length)), t3.apply(undefined, e37);\n }\n function m2(e37, t3, n3, o4, i4, r4, s3) {\n return function(t4, n4, a4, c4, l4) {\n switch (arguments.length) {\n case 0:\n case 1:\n return 0;\n case 2:\n return o4(t4, n4);\n case 3:\n return i4(t4, n4, a4);\n case 4:\n return r4(t4, n4, a4, c4);\n case 5:\n return s3(t4, n4, a4, c4, l4);\n }\n for (var h3 = new Array(arguments.length), d3 = 0;d3 \u003c arguments.length; ++d3)\n h3[d3] = arguments[d3];\n return e37(h3);\n };\n }\n (function() {\n for (;u2.length \u003c= 5; )\n u2.push(l3(u2.length));\n t2.exports = m2.apply(undefined, [p3].concat(u2));\n for (var e37 = 0;e37 \u003c= 5; ++e37)\n t2.exports[e37] = u2[e37];\n })();\n} });\nvar yY = hY({ \"node_modules/cdt2d/lib/monotone.js\"(e36, t2) {\n var n2 = dY(), o3 = _Y()[3];\n function i3(e37, t3, n3, o4, i4) {\n this.a = e37, this.b = t3, this.idx = n3, this.lowerIds = o4, this.upperIds = i4;\n }\n function r3(e37, t3, n3, o4) {\n this.a = e37, this.b = t3, this.type = n3, this.idx = o4;\n }\n function s2(e37, t3) {\n var n3 = e37.a[0] - t3.a[0] || e37.a[1] - t3.a[1] || e37.type - t3.type;\n return n3 || (e37.type !== 0 \u0026\u0026 (n3 = o3(e37.a, e37.b, t3.b)) ? n3 : e37.idx - t3.idx);\n }\n function a3(e37, t3) {\n return o3(e37.a, e37.b, t3);\n }\n function c3(e37, t3, i4, r4, s3) {\n for (var c4 = n2.lt(t3, r4, a3), l4 = n2.gt(t3, r4, a3), h3 = c4;h3 \u003c l4; ++h3) {\n for (var d3 = t3[h3], u2 = d3.lowerIds, p3 = u2.length;p3 \u003e 1 \u0026\u0026 o3(i4[u2[p3 - 2]], i4[u2[p3 - 1]], r4) \u003e 0; )\n e37.push([u2[p3 - 1], u2[p3 - 2], s3]), p3 -= 1;\n u2.length = p3, u2.push(s3);\n var m2 = d3.upperIds;\n for (p3 = m2.length;p3 \u003e 1 \u0026\u0026 o3(i4[m2[p3 - 2]], i4[m2[p3 - 1]], r4) \u003c 0; )\n e37.push([m2[p3 - 2], m2[p3 - 1], s3]), p3 -= 1;\n m2.length = p3, m2.push(s3);\n }\n }\n function l3(e37, t3) {\n var n3;\n return (n3 = e37.a[0] \u003c t3.a[0] ? o3(e37.a, e37.b, t3.a) : o3(t3.b, t3.a, e37.a)) ? n3 : (n3 = t3.b[0] \u003c e37.b[0] ? o3(e37.a, e37.b, t3.b) : o3(t3.b, t3.a, e37.b)) || e37.idx - t3.idx;\n }\n function h2(e37, t3, o4) {\n var r4 = n2.le(e37, o4, l3), s3 = e37[r4], a4 = s3.upperIds, c4 = a4[a4.length - 1];\n s3.upperIds = [c4], e37.splice(r4 + 1, 0, new i3(o4.a, o4.b, o4.idx, [c4], a4));\n }\n function d2(e37, t3, o4) {\n var i4 = o4.a;\n o4.a = o4.b, o4.b = i4;\n var r4 = n2.eq(e37, o4, l3), s3 = e37[r4];\n e37[r4 - 1].upperIds = s3.upperIds, e37.splice(r4, 1);\n }\n t2.exports = function(e37, t3) {\n for (var n3 = e37.length, o4 = t3.length, a4 = [], l4 = 0;l4 \u003c n3; ++l4)\n a4.push(new r3(e37[l4], null, 0, l4));\n for (l4 = 0;l4 \u003c o4; ++l4) {\n var u2 = t3[l4], p3 = e37[u2[0]], m2 = e37[u2[1]];\n p3[0] \u003c m2[0] ? a4.push(new r3(p3, m2, 2, l4), new r3(m2, p3, 1, l4)) : p3[0] \u003e m2[0] \u0026\u0026 a4.push(new r3(m2, p3, 2, l4), new r3(p3, m2, 1, l4));\n }\n a4.sort(s2);\n for (var g2 = a4[0].a[0] - (1 + Math.abs(a4[0].a[0])) * Math.pow(2, -52), f2 = [new i3([g2, 1], [g2, 0], -1, [], [], [], [])], _2 = [], y2 = (l4 = 0, a4.length);l4 \u003c y2; ++l4) {\n var b2 = a4[l4], x2 = b2.type;\n x2 === 0 ? c3(_2, f2, e37, b2.a, b2.idx) : x2 === 2 ? h2(f2, e37, b2) : d2(f2, e37, b2);\n }\n return _2;\n };\n} });\nvar bY = hY({ \"node_modules/cdt2d/lib/triangulation.js\"(e36, t2) {\n var n2 = dY();\n function o3(e37, t3) {\n this.stars = e37, this.edges = t3;\n }\n t2.exports = function(e37, t3) {\n for (var n3 = new Array(e37), i4 = 0;i4 \u003c e37; ++i4)\n n3[i4] = [];\n return new o3(n3, t3);\n };\n var i3 = o3.prototype;\n function r3(e37, t3, n3) {\n for (var o4 = 1, i4 = e37.length;o4 \u003c i4; o4 += 2)\n if (e37[o4 - 1] === t3 \u0026\u0026 e37[o4] === n3)\n return e37[o4 - 1] = e37[i4 - 2], e37[o4] = e37[i4 - 1], void (e37.length = i4 - 2);\n }\n i3.isConstraint = function() {\n var e37 = [0, 0];\n function t3(e38, t4) {\n return e38[0] - t4[0] || e38[1] - t4[1];\n }\n return function(o4, i4) {\n return e37[0] = Math.min(o4, i4), e37[1] = Math.max(o4, i4), n2.eq(this.edges, e37, t3) \u003e= 0;\n };\n }(), i3.removeTriangle = function(e37, t3, n3) {\n var o4 = this.stars;\n r3(o4[e37], t3, n3), r3(o4[t3], n3, e37), r3(o4[n3], e37, t3);\n }, i3.addTriangle = function(e37, t3, n3) {\n var o4 = this.stars;\n o4[e37].push(t3, n3), o4[t3].push(n3, e37), o4[n3].push(e37, t3);\n }, i3.opposite = function(e37, t3) {\n for (var n3 = this.stars[t3], o4 = 1, i4 = n3.length;o4 \u003c i4; o4 += 2)\n if (n3[o4] === e37)\n return n3[o4 - 1];\n return -1;\n }, i3.flip = function(e37, t3) {\n var n3 = this.opposite(e37, t3), o4 = this.opposite(t3, e37);\n this.removeTriangle(e37, t3, n3), this.removeTriangle(t3, e37, o4), this.addTriangle(e37, o4, n3), this.addTriangle(t3, n3, o4);\n }, i3.edges = function() {\n for (var e37 = this.stars, t3 = [], n3 = 0, o4 = e37.length;n3 \u003c o4; ++n3)\n for (var i4 = e37[n3], r4 = 0, s2 = i4.length;r4 \u003c s2; r4 += 2)\n t3.push([i4[r4], i4[r4 + 1]]);\n return t3;\n }, i3.cells = function() {\n for (var e37 = this.stars, t3 = [], n3 = 0, o4 = e37.length;n3 \u003c o4; ++n3)\n for (var i4 = e37[n3], r4 = 0, s2 = i4.length;r4 \u003c s2; r4 += 2) {\n var a3 = i4[r4], c3 = i4[r4 + 1];\n n3 \u003c Math.min(a3, c3) \u0026\u0026 t3.push([n3, a3, c3]);\n }\n return t3;\n };\n} });\nvar xY = hY({ \"node_modules/robust-in-sphere/in-sphere.js\"(e36, t2) {\n var n2 = uY(), o3 = pY(), i3 = fY(), r3 = gY();\n function s2(e37) {\n return (e37 === 3 ? a3 : e37 === 4 ? c3 : e37 === 5 ? l3 : h2)(o3, i3, n2, r3);\n }\n function a3(e37, t3, n3, o4) {\n return function(i4, r4, s3) {\n var a4 = n3(i4[0], i4[0]), c4 = o4(a4, r4[0]), l4 = o4(a4, s3[0]), h3 = n3(r4[0], r4[0]), d3 = o4(h3, i4[0]), u3 = o4(h3, s3[0]), p4 = n3(s3[0], s3[0]), m2 = o4(p4, i4[0]), g2 = o4(p4, r4[0]), f2 = e37(t3(g2, u3), t3(d3, c4)), _2 = t3(m2, l4), y2 = t3(f2, _2);\n return y2[y2.length - 1];\n };\n }\n function c3(e37, t3, n3, o4) {\n return function(i4, r4, s3, a4) {\n var c4 = e37(n3(i4[0], i4[0]), n3(i4[1], i4[1])), l4 = o4(c4, r4[0]), h3 = o4(c4, s3[0]), d3 = o4(c4, a4[0]), u3 = e37(n3(r4[0], r4[0]), n3(r4[1], r4[1])), p4 = o4(u3, i4[0]), m2 = o4(u3, s3[0]), g2 = o4(u3, a4[0]), f2 = e37(n3(s3[0], s3[0]), n3(s3[1], s3[1])), _2 = o4(f2, i4[0]), y2 = o4(f2, r4[0]), b2 = o4(f2, a4[0]), x2 = e37(n3(a4[0], a4[0]), n3(a4[1], a4[1])), v2 = o4(x2, i4[0]), I2 = o4(x2, r4[0]), S2 = o4(x2, s3[0]), C = e37(e37(o4(t3(S2, b2), r4[1]), e37(o4(t3(I2, g2), -s3[1]), o4(t3(y2, m2), a4[1]))), e37(o4(t3(I2, g2), i4[1]), e37(o4(t3(v2, d3), -r4[1]), o4(t3(p4, l4), a4[1])))), P = e37(e37(o4(t3(S2, b2), i4[1]), e37(o4(t3(v2, d3), -s3[1]), o4(t3(_2, h3), a4[1]))), e37(o4(t3(y2, m2), i4[1]), e37(o4(t3(_2, h3), -r4[1]), o4(t3(p4, l4), s3[1])))), M = t3(C, P);\n return M[M.length - 1];\n };\n }\n function l3(e37, t3, n3, o4) {\n return function(i4, r4, s3, a4, c4) {\n var l4 = e37(n3(i4[0], i4[0]), e37(n3(i4[1], i4[1]), n3(i4[2], i4[2]))), h3 = o4(l4, r4[0]), d3 = o4(l4, s3[0]), u3 = o4(l4, a4[0]), p4 = o4(l4, c4[0]), m2 = e37(n3(r4[0], r4[0]), e37(n3(r4[1], r4[1]), n3(r4[2], r4[2]))), g2 = o4(m2, i4[0]), f2 = o4(m2, s3[0]), _2 = o4(m2, a4[0]), y2 = o4(m2, c4[0]), b2 = e37(n3(s3[0], s3[0]), e37(n3(s3[1], s3[1]), n3(s3[2], s3[2]))), x2 = o4(b2, i4[0]), v2 = o4(b2, r4[0]), I2 = o4(b2, a4[0]), S2 = o4(b2, c4[0]), C = e37(n3(a4[0], a4[0]), e37(n3(a4[1], a4[1]), n3(a4[2], a4[2]))), P = o4(C, i4[0]), M = o4(C, r4[0]), w = o4(C, s3[0]), N = o4(C, c4[0]), R2 = e37(n3(c4[0], c4[0]), e37(n3(c4[1], c4[1]), n3(c4[2], c4[2]))), T2 = o4(R2, i4[0]), E3 = o4(R2, r4[0]), A2 = o4(R2, s3[0]), O2 = o4(R2, a4[0]), k2 = e37(e37(e37(o4(e37(o4(t3(O2, N), s3[1]), e37(o4(t3(A2, S2), -a4[1]), o4(t3(w, I2), c4[1]))), r4[2]), e37(o4(e37(o4(t3(O2, N), r4[1]), e37(o4(t3(E3, y2), -a4[1]), o4(t3(M, _2), c4[1]))), -s3[2]), o4(e37(o4(t3(A2, S2), r4[1]), e37(o4(t3(E3, y2), -s3[1]), o4(t3(v2, f2), c4[1]))), a4[2]))), e37(o4(e37(o4(t3(w, I2), r4[1]), e37(o4(t3(M, _2), -s3[1]), o4(t3(v2, f2), a4[1]))), -c4[2]), e37(o4(e37(o4(t3(O2, N), r4[1]), e37(o4(t3(E3, y2), -a4[1]), o4(t3(M, _2), c4[1]))), i4[2]), o4(e37(o4(t3(O2, N), i4[1]), e37(o4(t3(T2, p4), -a4[1]), o4(t3(P, u3), c4[1]))), -r4[2])))), e37(e37(o4(e37(o4(t3(E3, y2), i4[1]), e37(o4(t3(T2, p4), -r4[1]), o4(t3(g2, h3), c4[1]))), a4[2]), e37(o4(e37(o4(t3(M, _2), i4[1]), e37(o4(t3(P, u3), -r4[1]), o4(t3(g2, h3), a4[1]))), -c4[2]), o4(e37(o4(t3(w, I2), r4[1]), e37(o4(t3(M, _2), -s3[1]), o4(t3(v2, f2), a4[1]))), i4[2]))), e37(o4(e37(o4(t3(w, I2), i4[1]), e37(o4(t3(P, u3), -s3[1]), o4(t3(x2, d3), a4[1]))), -r4[2]), e37(o4(e37(o4(t3(M, _2), i4[1]), e37(o4(t3(P, u3), -r4[1]), o4(t3(g2, h3), a4[1]))), s3[2]), o4(e37(o4(t3(v2, f2), i4[1]), e37(o4(t3(x2, d3), -r4[1]), o4(t3(g2, h3), s3[1]))), -a4[2]))))), D2 = e37(e37(e37(o4(e37(o4(t3(O2, N), s3[1]), e37(o4(t3(A2, S2), -a4[1]), o4(t3(w, I2), c4[1]))), i4[2]), o4(e37(o4(t3(O2, N), i4[1]), e37(o4(t3(T2, p4), -a4[1]), o4(t3(P, u3), c4[1]))), -s3[2])), e37(o4(e37(o4(t3(A2, S2), i4[1]), e37(o4(t3(T2, p4), -s3[1]), o4(t3(x2, d3), c4[1]))), a4[2]), o4(e37(o4(t3(w, I2), i4[1]), e37(o4(t3(P, u3), -s3[1]), o4(t3(x2, d3), a4[1]))), -c4[2]))), e37(e37(o4(e37(o4(t3(A2, S2), r4[1]), e37(o4(t3(E3, y2), -s3[1]), o4(t3(v2, f2), c4[1]))), i4[2]), o4(e37(o4(t3(A2, S2), i4[1]), e37(o4(t3(T2, p4), -s3[1]), o4(t3(x2, d3), c4[1]))), -r4[2])), e37(o4(e37(o4(t3(E3, y2), i4[1]), e37(o4(t3(T2, p4), -r4[1]), o4(t3(g2, h3), c4[1]))), s3[2]), o4(e37(o4(t3(v2, f2), i4[1]), e37(o4(t3(x2, d3), -r4[1]), o4(t3(g2, h3), s3[1]))), -c4[2])))), L2 = t3(k2, D2);\n return L2[L2.length - 1];\n };\n }\n function h2(e37, t3, n3, o4) {\n return function(i4, r4, s3, a4, c4, l4) {\n var h3 = e37(e37(n3(i4[0], i4[0]), n3(i4[1], i4[1])), e37(n3(i4[2], i4[2]), n3(i4[3], i4[3]))), d3 = o4(h3, r4[0]), u3 = o4(h3, s3[0]), p4 = o4(h3, a4[0]), m2 = o4(h3, c4[0]), g2 = o4(h3, l4[0]), f2 = e37(e37(n3(r4[0], r4[0]), n3(r4[1], r4[1])), e37(n3(r4[2], r4[2]), n3(r4[3], r4[3]))), _2 = o4(f2, i4[0]), y2 = o4(f2, s3[0]), b2 = o4(f2, a4[0]), x2 = o4(f2, c4[0]), v2 = o4(f2, l4[0]), I2 = e37(e37(n3(s3[0], s3[0]), n3(s3[1], s3[1])), e37(n3(s3[2], s3[2]), n3(s3[3], s3[3]))), S2 = o4(I2, i4[0]), C = o4(I2, r4[0]), P = o4(I2, a4[0]), M = o4(I2, c4[0]), w = o4(I2, l4[0]), N = e37(e37(n3(a4[0], a4[0]), n3(a4[1], a4[1])), e37(n3(a4[2], a4[2]), n3(a4[3], a4[3]))), R2 = o4(N, i4[0]), T2 = o4(N, r4[0]), E3 = o4(N, s3[0]), A2 = o4(N, c4[0]), O2 = o4(N, l4[0]), k2 = e37(e37(n3(c4[0], c4[0]), n3(c4[1], c4[1])), e37(n3(c4[2], c4[2]), n3(c4[3], c4[3]))), D2 = o4(k2, i4[0]), L2 = o4(k2, r4[0]), z2 = o4(k2, s3[0]), B2 = o4(k2, a4[0]), F2 = o4(k2, l4[0]), j2 = e37(e37(n3(l4[0], l4[0]), n3(l4[1], l4[1])), e37(n3(l4[2], l4[2]), n3(l4[3], l4[3]))), $2 = o4(j2, i4[0]), Y2 = o4(j2, r4[0]), X = o4(j2, s3[0]), H2 = o4(j2, a4[0]), V2 = o4(j2, c4[0]), W2 = e37(e37(e37(o4(e37(e37(o4(e37(o4(t3(V2, F2), a4[1]), e37(o4(t3(H2, O2), -c4[1]), o4(t3(B2, A2), l4[1]))), s3[2]), o4(e37(o4(t3(V2, F2), s3[1]), e37(o4(t3(X, w), -c4[1]), o4(t3(z2, M), l4[1]))), -a4[2])), e37(o4(e37(o4(t3(H2, O2), s3[1]), e37(o4(t3(X, w), -a4[1]), o4(t3(E3, P), l4[1]))), c4[2]), o4(e37(o4(t3(B2, A2), s3[1]), e37(o4(t3(z2, M), -a4[1]), o4(t3(E3, P), c4[1]))), -l4[2]))), r4[3]), e37(o4(e37(e37(o4(e37(o4(t3(V2, F2), a4[1]), e37(o4(t3(H2, O2), -c4[1]), o4(t3(B2, A2), l4[1]))), r4[2]), o4(e37(o4(t3(V2, F2), r4[1]), e37(o4(t3(Y2, v2), -c4[1]), o4(t3(L2, x2), l4[1]))), -a4[2])), e37(o4(e37(o4(t3(H2, O2), r4[1]), e37(o4(t3(Y2, v2), -a4[1]), o4(t3(T2, b2), l4[1]))), c4[2]), o4(e37(o4(t3(B2, A2), r4[1]), e37(o4(t3(L2, x2), -a4[1]), o4(t3(T2, b2), c4[1]))), -l4[2]))), -s3[3]), o4(e37(e37(o4(e37(o4(t3(V2, F2), s3[1]), e37(o4(t3(X, w), -c4[1]), o4(t3(z2, M), l4[1]))), r4[2]), o4(e37(o4(t3(V2, F2), r4[1]), e37(o4(t3(Y2, v2), -c4[1]), o4(t3(L2, x2), l4[1]))), -s3[2])), e37(o4(e37(o4(t3(X, w), r4[1]), e37(o4(t3(Y2, v2), -s3[1]), o4(t3(C, y2), l4[1]))), c4[2]), o4(e37(o4(t3(z2, M), r4[1]), e37(o4(t3(L2, x2), -s3[1]), o4(t3(C, y2), c4[1]))), -l4[2]))), a4[3]))), e37(e37(o4(e37(e37(o4(e37(o4(t3(H2, O2), s3[1]), e37(o4(t3(X, w), -a4[1]), o4(t3(E3, P), l4[1]))), r4[2]), o4(e37(o4(t3(H2, O2), r4[1]), e37(o4(t3(Y2, v2), -a4[1]), o4(t3(T2, b2), l4[1]))), -s3[2])), e37(o4(e37(o4(t3(X, w), r4[1]), e37(o4(t3(Y2, v2), -s3[1]), o4(t3(C, y2), l4[1]))), a4[2]), o4(e37(o4(t3(E3, P), r4[1]), e37(o4(t3(T2, b2), -s3[1]), o4(t3(C, y2), a4[1]))), -l4[2]))), -c4[3]), o4(e37(e37(o4(e37(o4(t3(B2, A2), s3[1]), e37(o4(t3(z2, M), -a4[1]), o4(t3(E3, P), c4[1]))), r4[2]), o4(e37(o4(t3(B2, A2), r4[1]), e37(o4(t3(L2, x2), -a4[1]), o4(t3(T2, b2), c4[1]))), -s3[2])), e37(o4(e37(o4(t3(z2, M), r4[1]), e37(o4(t3(L2, x2), -s3[1]), o4(t3(C, y2), c4[1]))), a4[2]), o4(e37(o4(t3(E3, P), r4[1]), e37(o4(t3(T2, b2), -s3[1]), o4(t3(C, y2), a4[1]))), -c4[2]))), l4[3])), e37(o4(e37(e37(o4(e37(o4(t3(V2, F2), a4[1]), e37(o4(t3(H2, O2), -c4[1]), o4(t3(B2, A2), l4[1]))), r4[2]), o4(e37(o4(t3(V2, F2), r4[1]), e37(o4(t3(Y2, v2), -c4[1]), o4(t3(L2, x2), l4[1]))), -a4[2])), e37(o4(e37(o4(t3(H2, O2), r4[1]), e37(o4(t3(Y2, v2), -a4[1]), o4(t3(T2, b2), l4[1]))), c4[2]), o4(e37(o4(t3(B2, A2), r4[1]), e37(o4(t3(L2, x2), -a4[1]), o4(t3(T2, b2), c4[1]))), -l4[2]))), i4[3]), o4(e37(e37(o4(e37(o4(t3(V2, F2), a4[1]), e37(o4(t3(H2, O2), -c4[1]), o4(t3(B2, A2), l4[1]))), i4[2]), o4(e37(o4(t3(V2, F2), i4[1]), e37(o4(t3($2, g2), -c4[1]), o4(t3(D2, m2), l4[1]))), -a4[2])), e37(o4(e37(o4(t3(H2, O2), i4[1]), e37(o4(t3($2, g2), -a4[1]), o4(t3(R2, p4), l4[1]))), c4[2]), o4(e37(o4(t3(B2, A2), i4[1]), e37(o4(t3(D2, m2), -a4[1]), o4(t3(R2, p4), c4[1]))), -l4[2]))), -r4[3])))), e37(e37(e37(o4(e37(e37(o4(e37(o4(t3(V2, F2), r4[1]), e37(o4(t3(Y2, v2), -c4[1]), o4(t3(L2, x2), l4[1]))), i4[2]), o4(e37(o4(t3(V2, F2), i4[1]), e37(o4(t3($2, g2), -c4[1]), o4(t3(D2, m2), l4[1]))), -r4[2])), e37(o4(e37(o4(t3(Y2, v2), i4[1]), e37(o4(t3($2, g2), -r4[1]), o4(t3(_2, d3), l4[1]))), c4[2]), o4(e37(o4(t3(L2, x2), i4[1]), e37(o4(t3(D2, m2), -r4[1]), o4(t3(_2, d3), c4[1]))), -l4[2]))), a4[3]), o4(e37(e37(o4(e37(o4(t3(H2, O2), r4[1]), e37(o4(t3(Y2, v2), -a4[1]), o4(t3(T2, b2), l4[1]))), i4[2]), o4(e37(o4(t3(H2, O2), i4[1]), e37(o4(t3($2, g2), -a4[1]), o4(t3(R2, p4), l4[1]))), -r4[2])), e37(o4(e37(o4(t3(Y2, v2), i4[1]), e37(o4(t3($2, g2), -r4[1]), o4(t3(_2, d3), l4[1]))), a4[2]), o4(e37(o4(t3(T2, b2), i4[1]), e37(o4(t3(R2, p4), -r4[1]), o4(t3(_2, d3), a4[1]))), -l4[2]))), -c4[3])), e37(o4(e37(e37(o4(e37(o4(t3(B2, A2), r4[1]), e37(o4(t3(L2, x2), -a4[1]), o4(t3(T2, b2), c4[1]))), i4[2]), o4(e37(o4(t3(B2, A2), i4[1]), e37(o4(t3(D2, m2), -a4[1]), o4(t3(R2, p4), c4[1]))), -r4[2])), e37(o4(e37(o4(t3(L2, x2), i4[1]), e37(o4(t3(D2, m2), -r4[1]), o4(t3(_2, d3), c4[1]))), a4[2]), o4(e37(o4(t3(T2, b2), i4[1]), e37(o4(t3(R2, p4), -r4[1]), o4(t3(_2, d3), a4[1]))), -c4[2]))), l4[3]), o4(e37(e37(o4(e37(o4(t3(H2, O2), s3[1]), e37(o4(t3(X, w), -a4[1]), o4(t3(E3, P), l4[1]))), r4[2]), o4(e37(o4(t3(H2, O2), r4[1]), e37(o4(t3(Y2, v2), -a4[1]), o4(t3(T2, b2), l4[1]))), -s3[2])), e37(o4(e37(o4(t3(X, w), r4[1]), e37(o4(t3(Y2, v2), -s3[1]), o4(t3(C, y2), l4[1]))), a4[2]), o4(e37(o4(t3(E3, P), r4[1]), e37(o4(t3(T2, b2), -s3[1]), o4(t3(C, y2), a4[1]))), -l4[2]))), i4[3]))), e37(e37(o4(e37(e37(o4(e37(o4(t3(H2, O2), s3[1]), e37(o4(t3(X, w), -a4[1]), o4(t3(E3, P), l4[1]))), i4[2]), o4(e37(o4(t3(H2, O2), i4[1]), e37(o4(t3($2, g2), -a4[1]), o4(t3(R2, p4), l4[1]))), -s3[2])), e37(o4(e37(o4(t3(X, w), i4[1]), e37(o4(t3($2, g2), -s3[1]), o4(t3(S2, u3), l4[1]))), a4[2]), o4(e37(o4(t3(E3, P), i4[1]), e37(o4(t3(R2, p4), -s3[1]), o4(t3(S2, u3), a4[1]))), -l4[2]))), -r4[3]), o4(e37(e37(o4(e37(o4(t3(H2, O2), r4[1]), e37(o4(t3(Y2, v2), -a4[1]), o4(t3(T2, b2), l4[1]))), i4[2]), o4(e37(o4(t3(H2, O2), i4[1]), e37(o4(t3($2, g2), -a4[1]), o4(t3(R2, p4), l4[1]))), -r4[2])), e37(o4(e37(o4(t3(Y2, v2), i4[1]), e37(o4(t3($2, g2), -r4[1]), o4(t3(_2, d3), l4[1]))), a4[2]), o4(e37(o4(t3(T2, b2), i4[1]), e37(o4(t3(R2, p4), -r4[1]), o4(t3(_2, d3), a4[1]))), -l4[2]))), s3[3])), e37(o4(e37(e37(o4(e37(o4(t3(X, w), r4[1]), e37(o4(t3(Y2, v2), -s3[1]), o4(t3(C, y2), l4[1]))), i4[2]), o4(e37(o4(t3(X, w), i4[1]), e37(o4(t3($2, g2), -s3[1]), o4(t3(S2, u3), l4[1]))), -r4[2])), e37(o4(e37(o4(t3(Y2, v2), i4[1]), e37(o4(t3($2, g2), -r4[1]), o4(t3(_2, d3), l4[1]))), s3[2]), o4(e37(o4(t3(C, y2), i4[1]), e37(o4(t3(S2, u3), -r4[1]), o4(t3(_2, d3), s3[1]))), -l4[2]))), -a4[3]), o4(e37(e37(o4(e37(o4(t3(E3, P), r4[1]), e37(o4(t3(T2, b2), -s3[1]), o4(t3(C, y2), a4[1]))), i4[2]), o4(e37(o4(t3(E3, P), i4[1]), e37(o4(t3(R2, p4), -s3[1]), o4(t3(S2, u3), a4[1]))), -r4[2])), e37(o4(e37(o4(t3(T2, b2), i4[1]), e37(o4(t3(R2, p4), -r4[1]), o4(t3(_2, d3), a4[1]))), s3[2]), o4(e37(o4(t3(C, y2), i4[1]), e37(o4(t3(S2, u3), -r4[1]), o4(t3(_2, d3), s3[1]))), -a4[2]))), l4[3]))))), G2 = e37(e37(e37(o4(e37(e37(o4(e37(o4(t3(V2, F2), a4[1]), e37(o4(t3(H2, O2), -c4[1]), o4(t3(B2, A2), l4[1]))), s3[2]), o4(e37(o4(t3(V2, F2), s3[1]), e37(o4(t3(X, w), -c4[1]), o4(t3(z2, M), l4[1]))), -a4[2])), e37(o4(e37(o4(t3(H2, O2), s3[1]), e37(o4(t3(X, w), -a4[1]), o4(t3(E3, P), l4[1]))), c4[2]), o4(e37(o4(t3(B2, A2), s3[1]), e37(o4(t3(z2, M), -a4[1]), o4(t3(E3, P), c4[1]))), -l4[2]))), i4[3]), e37(o4(e37(e37(o4(e37(o4(t3(V2, F2), a4[1]), e37(o4(t3(H2, O2), -c4[1]), o4(t3(B2, A2), l4[1]))), i4[2]), o4(e37(o4(t3(V2, F2), i4[1]), e37(o4(t3($2, g2), -c4[1]), o4(t3(D2, m2), l4[1]))), -a4[2])), e37(o4(e37(o4(t3(H2, O2), i4[1]), e37(o4(t3($2, g2), -a4[1]), o4(t3(R2, p4), l4[1]))), c4[2]), o4(e37(o4(t3(B2, A2), i4[1]), e37(o4(t3(D2, m2), -a4[1]), o4(t3(R2, p4), c4[1]))), -l4[2]))), -s3[3]), o4(e37(e37(o4(e37(o4(t3(V2, F2), s3[1]), e37(o4(t3(X, w), -c4[1]), o4(t3(z2, M), l4[1]))), i4[2]), o4(e37(o4(t3(V2, F2), i4[1]), e37(o4(t3($2, g2), -c4[1]), o4(t3(D2, m2), l4[1]))), -s3[2])), e37(o4(e37(o4(t3(X, w), i4[1]), e37(o4(t3($2, g2), -s3[1]), o4(t3(S2, u3), l4[1]))), c4[2]), o4(e37(o4(t3(z2, M), i4[1]), e37(o4(t3(D2, m2), -s3[1]), o4(t3(S2, u3), c4[1]))), -l4[2]))), a4[3]))), e37(e37(o4(e37(e37(o4(e37(o4(t3(H2, O2), s3[1]), e37(o4(t3(X, w), -a4[1]), o4(t3(E3, P), l4[1]))), i4[2]), o4(e37(o4(t3(H2, O2), i4[1]), e37(o4(t3($2, g2), -a4[1]), o4(t3(R2, p4), l4[1]))), -s3[2])), e37(o4(e37(o4(t3(X, w), i4[1]), e37(o4(t3($2, g2), -s3[1]), o4(t3(S2, u3), l4[1]))), a4[2]), o4(e37(o4(t3(E3, P), i4[1]), e37(o4(t3(R2, p4), -s3[1]), o4(t3(S2, u3), a4[1]))), -l4[2]))), -c4[3]), o4(e37(e37(o4(e37(o4(t3(B2, A2), s3[1]), e37(o4(t3(z2, M), -a4[1]), o4(t3(E3, P), c4[1]))), i4[2]), o4(e37(o4(t3(B2, A2), i4[1]), e37(o4(t3(D2, m2), -a4[1]), o4(t3(R2, p4), c4[1]))), -s3[2])), e37(o4(e37(o4(t3(z2, M), i4[1]), e37(o4(t3(D2, m2), -s3[1]), o4(t3(S2, u3), c4[1]))), a4[2]), o4(e37(o4(t3(E3, P), i4[1]), e37(o4(t3(R2, p4), -s3[1]), o4(t3(S2, u3), a4[1]))), -c4[2]))), l4[3])), e37(o4(e37(e37(o4(e37(o4(t3(V2, F2), s3[1]), e37(o4(t3(X, w), -c4[1]), o4(t3(z2, M), l4[1]))), r4[2]), o4(e37(o4(t3(V2, F2), r4[1]), e37(o4(t3(Y2, v2), -c4[1]), o4(t3(L2, x2), l4[1]))), -s3[2])), e37(o4(e37(o4(t3(X, w), r4[1]), e37(o4(t3(Y2, v2), -s3[1]), o4(t3(C, y2), l4[1]))), c4[2]), o4(e37(o4(t3(z2, M), r4[1]), e37(o4(t3(L2, x2), -s3[1]), o4(t3(C, y2), c4[1]))), -l4[2]))), i4[3]), o4(e37(e37(o4(e37(o4(t3(V2, F2), s3[1]), e37(o4(t3(X, w), -c4[1]), o4(t3(z2, M), l4[1]))), i4[2]), o4(e37(o4(t3(V2, F2), i4[1]), e37(o4(t3($2, g2), -c4[1]), o4(t3(D2, m2), l4[1]))), -s3[2])), e37(o4(e37(o4(t3(X, w), i4[1]), e37(o4(t3($2, g2), -s3[1]), o4(t3(S2, u3), l4[1]))), c4[2]), o4(e37(o4(t3(z2, M), i4[1]), e37(o4(t3(D2, m2), -s3[1]), o4(t3(S2, u3), c4[1]))), -l4[2]))), -r4[3])))), e37(e37(e37(o4(e37(e37(o4(e37(o4(t3(V2, F2), r4[1]), e37(o4(t3(Y2, v2), -c4[1]), o4(t3(L2, x2), l4[1]))), i4[2]), o4(e37(o4(t3(V2, F2), i4[1]), e37(o4(t3($2, g2), -c4[1]), o4(t3(D2, m2), l4[1]))), -r4[2])), e37(o4(e37(o4(t3(Y2, v2), i4[1]), e37(o4(t3($2, g2), -r4[1]), o4(t3(_2, d3), l4[1]))), c4[2]), o4(e37(o4(t3(L2, x2), i4[1]), e37(o4(t3(D2, m2), -r4[1]), o4(t3(_2, d3), c4[1]))), -l4[2]))), s3[3]), o4(e37(e37(o4(e37(o4(t3(X, w), r4[1]), e37(o4(t3(Y2, v2), -s3[1]), o4(t3(C, y2), l4[1]))), i4[2]), o4(e37(o4(t3(X, w), i4[1]), e37(o4(t3($2, g2), -s3[1]), o4(t3(S2, u3), l4[1]))), -r4[2])), e37(o4(e37(o4(t3(Y2, v2), i4[1]), e37(o4(t3($2, g2), -r4[1]), o4(t3(_2, d3), l4[1]))), s3[2]), o4(e37(o4(t3(C, y2), i4[1]), e37(o4(t3(S2, u3), -r4[1]), o4(t3(_2, d3), s3[1]))), -l4[2]))), -c4[3])), e37(o4(e37(e37(o4(e37(o4(t3(z2, M), r4[1]), e37(o4(t3(L2, x2), -s3[1]), o4(t3(C, y2), c4[1]))), i4[2]), o4(e37(o4(t3(z2, M), i4[1]), e37(o4(t3(D2, m2), -s3[1]), o4(t3(S2, u3), c4[1]))), -r4[2])), e37(o4(e37(o4(t3(L2, x2), i4[1]), e37(o4(t3(D2, m2), -r4[1]), o4(t3(_2, d3), c4[1]))), s3[2]), o4(e37(o4(t3(C, y2), i4[1]), e37(o4(t3(S2, u3), -r4[1]), o4(t3(_2, d3), s3[1]))), -c4[2]))), l4[3]), o4(e37(e37(o4(e37(o4(t3(B2, A2), s3[1]), e37(o4(t3(z2, M), -a4[1]), o4(t3(E3, P), c4[1]))), r4[2]), o4(e37(o4(t3(B2, A2), r4[1]), e37(o4(t3(L2, x2), -a4[1]), o4(t3(T2, b2), c4[1]))), -s3[2])), e37(o4(e37(o4(t3(z2, M), r4[1]), e37(o4(t3(L2, x2), -s3[1]), o4(t3(C, y2), c4[1]))), a4[2]), o4(e37(o4(t3(E3, P), r4[1]), e37(o4(t3(T2, b2), -s3[1]), o4(t3(C, y2), a4[1]))), -c4[2]))), i4[3]))), e37(e37(o4(e37(e37(o4(e37(o4(t3(B2, A2), s3[1]), e37(o4(t3(z2, M), -a4[1]), o4(t3(E3, P), c4[1]))), i4[2]), o4(e37(o4(t3(B2, A2), i4[1]), e37(o4(t3(D2, m2), -a4[1]), o4(t3(R2, p4), c4[1]))), -s3[2])), e37(o4(e37(o4(t3(z2, M), i4[1]), e37(o4(t3(D2, m2), -s3[1]), o4(t3(S2, u3), c4[1]))), a4[2]), o4(e37(o4(t3(E3, P), i4[1]), e37(o4(t3(R2, p4), -s3[1]), o4(t3(S2, u3), a4[1]))), -c4[2]))), -r4[3]), o4(e37(e37(o4(e37(o4(t3(B2, A2), r4[1]), e37(o4(t3(L2, x2), -a4[1]), o4(t3(T2, b2), c4[1]))), i4[2]), o4(e37(o4(t3(B2, A2), i4[1]), e37(o4(t3(D2, m2), -a4[1]), o4(t3(R2, p4), c4[1]))), -r4[2])), e37(o4(e37(o4(t3(L2, x2), i4[1]), e37(o4(t3(D2, m2), -r4[1]), o4(t3(_2, d3), c4[1]))), a4[2]), o4(e37(o4(t3(T2, b2), i4[1]), e37(o4(t3(R2, p4), -r4[1]), o4(t3(_2, d3), a4[1]))), -c4[2]))), s3[3])), e37(o4(e37(e37(o4(e37(o4(t3(z2, M), r4[1]), e37(o4(t3(L2, x2), -s3[1]), o4(t3(C, y2), c4[1]))), i4[2]), o4(e37(o4(t3(z2, M), i4[1]), e37(o4(t3(D2, m2), -s3[1]), o4(t3(S2, u3), c4[1]))), -r4[2])), e37(o4(e37(o4(t3(L2, x2), i4[1]), e37(o4(t3(D2, m2), -r4[1]), o4(t3(_2, d3), c4[1]))), s3[2]), o4(e37(o4(t3(C, y2), i4[1]), e37(o4(t3(S2, u3), -r4[1]), o4(t3(_2, d3), s3[1]))), -c4[2]))), -a4[3]), o4(e37(e37(o4(e37(o4(t3(E3, P), r4[1]), e37(o4(t3(T2, b2), -s3[1]), o4(t3(C, y2), a4[1]))), i4[2]), o4(e37(o4(t3(E3, P), i4[1]), e37(o4(t3(R2, p4), -s3[1]), o4(t3(S2, u3), a4[1]))), -r4[2])), e37(o4(e37(o4(t3(T2, b2), i4[1]), e37(o4(t3(R2, p4), -r4[1]), o4(t3(_2, d3), a4[1]))), s3[2]), o4(e37(o4(t3(C, y2), i4[1]), e37(o4(t3(S2, u3), -r4[1]), o4(t3(_2, d3), s3[1]))), -a4[2]))), c4[3]))))), U2 = t3(W2, G2);\n return U2[U2.length - 1];\n };\n }\n var d2 = [function() {\n return 0;\n }, function() {\n return 0;\n }, function() {\n return 0;\n }];\n function u2(e37) {\n var t3 = d2[e37.length];\n return t3 || (t3 = d2[e37.length] = s2(e37.length)), t3.apply(undefined, e37);\n }\n function p3(e37, t3, n3, o4, i4, r4, s3, a4) {\n return function(t4, n4, c4, l4, h3, d3) {\n switch (arguments.length) {\n case 0:\n case 1:\n return 0;\n case 2:\n return o4(t4, n4);\n case 3:\n return i4(t4, n4, c4);\n case 4:\n return r4(t4, n4, c4, l4);\n case 5:\n return s3(t4, n4, c4, l4, h3);\n case 6:\n return a4(t4, n4, c4, l4, h3, d3);\n }\n for (var u3 = new Array(arguments.length), p4 = 0;p4 \u003c arguments.length; ++p4)\n u3[p4] = arguments[p4];\n return e37(u3);\n };\n }\n (function() {\n for (;d2.length \u003c= 6; )\n d2.push(s2(d2.length));\n t2.exports = p3.apply(undefined, [u2].concat(d2));\n for (var e37 = 0;e37 \u003c= 6; ++e37)\n t2.exports[e37] = d2[e37];\n })();\n} });\nvar vY = hY({ \"node_modules/cdt2d/lib/delaunay.js\"(e36, t2) {\n var n2 = xY()[4];\n dY();\n function o3(e37, t3, o4, i3, r3, s2) {\n var a3 = t3.opposite(i3, r3);\n if (!(a3 \u003c 0)) {\n if (r3 \u003c i3) {\n var c3 = i3;\n i3 = r3, r3 = c3, c3 = s2, s2 = a3, a3 = c3;\n }\n t3.isConstraint(i3, r3) || n2(e37[i3], e37[r3], e37[s2], e37[a3]) \u003c 0 \u0026\u0026 o4.push(i3, r3);\n }\n }\n t2.exports = function(e37, t3) {\n for (var i3 = [], r3 = e37.length, s2 = t3.stars, a3 = 0;a3 \u003c r3; ++a3)\n for (var c3 = s2[a3], l3 = 1;l3 \u003c c3.length; l3 += 2) {\n if (!((p3 = c3[l3]) \u003c a3) \u0026\u0026 !t3.isConstraint(a3, p3)) {\n for (var h2 = c3[l3 - 1], d2 = -1, u2 = 1;u2 \u003c c3.length; u2 += 2)\n if (c3[u2 - 1] === p3) {\n d2 = c3[u2];\n break;\n }\n d2 \u003c 0 || n2(e37[a3], e37[p3], e37[h2], e37[d2]) \u003c 0 \u0026\u0026 i3.push(a3, p3);\n }\n }\n for (;i3.length \u003e 0; ) {\n for (var p3 = i3.pop(), m2 = (h2 = -1, d2 = -1, c3 = s2[a3 = i3.pop()], 1);m2 \u003c c3.length; m2 += 2) {\n var g2 = c3[m2 - 1], f2 = c3[m2];\n g2 === p3 ? d2 = f2 : f2 === p3 \u0026\u0026 (h2 = g2);\n }\n h2 \u003c 0 || d2 \u003c 0 || (n2(e37[a3], e37[p3], e37[h2], e37[d2]) \u003e= 0 || (t3.flip(a3, p3), o3(e37, t3, i3, h2, a3, d2), o3(e37, t3, i3, a3, d2, h2), o3(e37, t3, i3, d2, p3, h2), o3(e37, t3, i3, p3, h2, d2)));\n }\n };\n} });\nvar IY = hY({ \"node_modules/cdt2d/lib/filter.js\"(e36, t2) {\n var n2 = dY();\n function o3(e37, t3, n3, o4, i4, r3, s2) {\n this.cells = e37, this.neighbor = t3, this.flags = o4, this.constraint = n3, this.active = i4, this.next = r3, this.boundary = s2;\n }\n function i3(e37, t3) {\n return e37[0] - t3[0] || e37[1] - t3[1] || e37[2] - t3[2];\n }\n t2.exports = function(e37, t3, n3) {\n var r3 = function(e38, t4) {\n for (var n4 = e38.cells(), r4 = n4.length, s3 = 0;s3 \u003c r4; ++s3) {\n var a4 = (_3 = n4[s3])[0], c4 = _3[1], l4 = _3[2];\n c4 \u003c l4 ? c4 \u003c a4 \u0026\u0026 (_3[0] = c4, _3[1] = l4, _3[2] = a4) : l4 \u003c a4 \u0026\u0026 (_3[0] = l4, _3[1] = a4, _3[2] = c4);\n }\n n4.sort(i3);\n var h3 = new Array(r4);\n for (s3 = 0;s3 \u003c h3.length; ++s3)\n h3[s3] = 0;\n var d3 = [], u3 = [], p4 = new Array(3 * r4), m3 = new Array(3 * r4), g3 = null;\n t4 \u0026\u0026 (g3 = []);\n var f3 = new o3(n4, p4, m3, h3, d3, u3, g3);\n for (s3 = 0;s3 \u003c r4; ++s3)\n for (var _3 = n4[s3], y2 = 0;y2 \u003c 3; ++y2) {\n a4 = _3[y2], c4 = _3[(y2 + 1) % 3];\n var b2 = p4[3 * s3 + y2] = f3.locate(c4, a4, e38.opposite(c4, a4)), x2 = m3[3 * s3 + y2] = e38.isConstraint(a4, c4);\n b2 \u003c 0 \u0026\u0026 (x2 ? u3.push(s3) : (d3.push(s3), h3[s3] = 1), t4 \u0026\u0026 g3.push([c4, a4, -1]));\n }\n return f3;\n }(e37, n3);\n if (t3 === 0)\n return n3 ? r3.cells.concat(r3.boundary) : r3.cells;\n var s2 = 1, a3 = r3.active, c3 = r3.next, l3 = r3.flags, h2 = r3.cells, d2 = r3.constraint, u2 = r3.neighbor;\n for (;a3.length \u003e 0 || c3.length \u003e 0; ) {\n for (;a3.length \u003e 0; ) {\n var p3 = a3.pop();\n if (l3[p3] !== -s2) {\n l3[p3] = s2;\n h2[p3];\n for (var m2 = 0;m2 \u003c 3; ++m2) {\n var g2 = u2[3 * p3 + m2];\n g2 \u003e= 0 \u0026\u0026 l3[g2] === 0 \u0026\u0026 (d2[3 * p3 + m2] ? c3.push(g2) : (a3.push(g2), l3[g2] = s2));\n }\n }\n }\n var f2 = c3;\n c3 = a3, a3 = f2, c3.length = 0, s2 = -s2;\n }\n var _2 = function(e38, t4, n4) {\n for (var o4 = 0, i4 = 0;i4 \u003c e38.length; ++i4)\n t4[i4] === n4 \u0026\u0026 (e38[o4++] = e38[i4]);\n return e38.length = o4, e38;\n }(h2, l3, t3);\n if (n3)\n return _2.concat(r3.boundary);\n return _2;\n }, o3.prototype.locate = function() {\n var e37 = [0, 0, 0];\n return function(t3, o4, r3) {\n var s2 = t3, a3 = o4, c3 = r3;\n return o4 \u003c r3 ? o4 \u003c t3 \u0026\u0026 (s2 = o4, a3 = r3, c3 = t3) : r3 \u003c t3 \u0026\u0026 (s2 = r3, a3 = t3, c3 = o4), s2 \u003c 0 ? -1 : (e37[0] = s2, e37[1] = a3, e37[2] = c3, n2.eq(this.cells, e37, i3));\n };\n }();\n} });\nvar SY = hY({ \"node_modules/cdt2d/cdt2d.js\"(e36, t2) {\n var n2 = yY(), o3 = bY(), i3 = vY(), r3 = IY();\n function s2(e37) {\n return [Math.min(e37[0], e37[1]), Math.max(e37[0], e37[1])];\n }\n function a3(e37, t3) {\n return e37[0] - t3[0] || e37[1] - t3[1];\n }\n function c3(e37, t3, n3) {\n return t3 in e37 ? e37[t3] : n3;\n }\n t2.exports = function(e37, t3, l3) {\n Array.isArray(t3) ? (l3 = l3 || {}, t3 = t3 || []) : (l3 = t3 || {}, t3 = []);\n var h2 = !!c3(l3, \"delaunay\", true), d2 = !!c3(l3, \"interior\", true), u2 = !!c3(l3, \"exterior\", true), p3 = !!c3(l3, \"infinity\", false);\n if (!d2 \u0026\u0026 !u2 || e37.length === 0)\n return [];\n var m2 = n2(e37, t3);\n if (h2 || d2 !== u2 || p3) {\n for (var g2 = o3(e37.length, function(e38) {\n return e38.map(s2).sort(a3);\n }(t3)), f2 = 0;f2 \u003c m2.length; ++f2) {\n var _2 = m2[f2];\n g2.addTriangle(_2[0], _2[1], _2[2]);\n }\n return h2 \u0026\u0026 i3(e37, g2), u2 ? d2 ? p3 ? r3(g2, 0, p3) : g2.cells() : r3(g2, 1, p3) : r3(g2, -1);\n }\n return m2;\n };\n} });\nvar CY = (e36) =\u003e e36.map((e37) =\u003e ({ connectionId: e37.connectionId, startRegionId: e37.startRegion.regionId, endRegionId: e37.endRegion.regionId, mutuallyConnectedNetworkId: e37.mutuallyConnectedNetworkId }));\nvar PY = (e36) =\u003e ({ ports: e36.ports.map((e37) =\u003e ({ portId: e37.portId, region1Id: e37.region1.regionId, region2Id: e37.region2.regionId, d: e37.d })), regions: e36.regions.map((e37) =\u003e ({ regionId: e37.regionId, pointIds: e37.ports.map((e38) =\u003e e38.portId), d: e37.d })) });\nvar MY = ({ port: e36, boundaryRegionMap: t2 }) =\u003e {\n let n2 = t2.get(e36.portId);\n if (!n2) {\n const o3 = typeof e36.d?.x == \"number\" ? e36.d.x : 0, i3 = typeof e36.d?.y == \"number\" ? e36.d.y : 0;\n n2 = { regionId: `__section_boundary__${e36.portId}`, ports: [], d: { isBoundaryRegion: true, boundaryPortId: e36.portId, ...e36.d, center: { x: o3, y: i3 }, bounds: { minX: o3 - 0.05, maxX: o3 + 0.05, minY: i3 - 0.05, maxY: i3 + 0.05 } }, assignments: [] }, t2.set(e36.portId, n2);\n }\n return n2;\n};\nvar wY = (e36) =\u003e {\n const { sectionRoute: t2, graph: n2 } = e36, o3 = new Set(n2.ports.map((e37) =\u003e e37.portId)), i3 = t2.globalRoute.path.slice(t2.sectionStartIndex, t2.sectionEndIndex + 1).filter((e37) =\u003e o3.has(e37.port.portId)), r3 = [];\n let s2 = t2.sectionConnection.startRegion;\n for (let e37 = 0;e37 \u003c i3.length; e37++) {\n const t3 = i3[e37], o4 = n2.ports.find((e38) =\u003e e38.portId === t3.port.portId), a3 = o4.region1 === s2 ? o4.region2 : o4.region1;\n r3.push({ port: o4, g: 0, h: 0, f: 0, hops: e37, ripRequired: t3.ripRequired, parent: e37 \u003e 0 ? r3[e37 - 1] : undefined, lastPort: e37 \u003e 0 ? r3[e37 - 1].port : undefined, lastRegion: e37 \u003e 0 ? s2 : undefined, nextRegion: a3 }), s2 = a3;\n }\n return { connection: t2.sectionConnection, path: r3, requiredRip: t2.globalRoute.requiredRip };\n};\nvar NY = (e36, t2) =\u003e {\n let n2 = -1, o3 = -1;\n for (let i3 = 0;i3 \u003c e36.path.length; i3++) {\n const r3 = e36.path[i3];\n (r3.lastRegion \u0026\u0026 t2.has(r3.lastRegion.regionId) || r3.nextRegion \u0026\u0026 t2.has(r3.nextRegion.regionId)) \u0026\u0026 (n2 === -1 \u0026\u0026 (n2 = i3), o3 = i3);\n }\n return n2 === -1 ? null : { startIndex: n2, endIndex: o3 };\n};\nvar RY = (e36) =\u003e {\n const { graph: t2, solvedRoutes: n2, centralRegion: o3, expansionHopsFromCentralRegion: i3 } = e36, r3 = (({ centralRegion: e37, expansionHopsFromCentralRegion: t3 }) =\u003e {\n const n3 = new Set([e37.regionId]), o4 = [{ region: e37, hops: 0 }];\n for (;o4.length \u003e 0; ) {\n const { region: e38, hops: i4 } = o4.shift();\n if (!(i4 \u003e= t3 + 1))\n for (const t4 of e38.ports) {\n const r4 = t4.region1 === e38 ? t4.region2 : t4.region1;\n n3.has(r4.regionId) || (n3.add(r4.regionId), o4.push({ region: r4, hops: i4 + 1 }));\n }\n }\n return n3;\n })({ graph: t2, centralRegion: o3, expansionHopsFromCentralRegion: i3 }), s2 = new Map, a3 = new Map, c3 = [];\n for (const e37 of t2.regions)\n r3.has(e37.regionId) \u0026\u0026 s2.set(e37.regionId, { regionId: e37.regionId, ports: [], d: e37.d ? structuredClone(e37.d) : e37.d, assignments: [] });\n for (const e37 of t2.ports) {\n const t3 = r3.has(e37.region1.regionId), n3 = r3.has(e37.region2.regionId);\n if (!t3 \u0026\u0026 !n3)\n continue;\n if (t3 \u0026\u0026 n3) {\n const t4 = { portId: e37.portId, region1: s2.get(e37.region1.regionId), region2: s2.get(e37.region2.regionId), d: e37.d };\n t4.region1.ports.push(t4), t4.region2.ports.push(t4), c3.push(t4);\n continue;\n }\n const o4 = t3 ? e37.region1 : e37.region2, i4 = MY({ port: e37, boundaryRegionMap: a3 }), l4 = { portId: e37.portId, region1: s2.get(o4.regionId), region2: i4, d: e37.d };\n l4.region1.ports.push(l4), l4.region2.ports.push(l4), c3.push(l4);\n }\n const l3 = { regions: [...s2.values(), ...a3.values()], ports: c3 }, h2 = [], d2 = [], u2 = [];\n for (const e37 of n2) {\n const t3 = NY(e37, r3);\n if (!t3)\n continue;\n const n3 = e37.path[t3.startIndex], o4 = e37.path[t3.endIndex];\n u2.push({ solvedRoute: e37, solvedPathStartIndex: t3.startIndex, solvedPathEndIndex: t3.endIndex, startCandidate: n3, endCandidate: o4 });\n }\n const p3 = new Map(l3.regions.map((e37) =\u003e [e37.regionId, e37]));\n for (const { solvedRoute: e37, solvedPathStartIndex: t3, solvedPathEndIndex: n3, startCandidate: o4, endCandidate: i4 } of u2) {\n let s3, c4, u3, m2;\n if (r3.has(e37.connection.startRegion.regionId))\n s3 = e37.connection.startRegion.regionId, c4 = p3.get(s3);\n else {\n const e38 = MY({ port: o4.port, boundaryRegionMap: a3 });\n s3 = e38.regionId, c4 = e38, p3.has(s3) || p3.set(s3, e38);\n }\n if (r3.has(e37.connection.endRegion.regionId))\n u3 = e37.connection.endRegion.regionId, m2 = p3.get(u3);\n else {\n const e38 = MY({ port: i4.port, boundaryRegionMap: a3 });\n u3 = e38.regionId, m2 = e38, p3.has(u3) || p3.set(u3, e38);\n }\n if (!c4)\n throw console.error(\"[getSectionOfHyperGraphAsHyperGraph] CRITICAL ERROR: startRegion not found!\"), console.error(` Looking for: ${s3}`), console.error(` Route connection: ${e37.connection.connectionId}`), console.error(` Original startRegion: ${e37.connection.startRegion.regionId}`), console.error(` startCandidate port: ${o4.port.portId}`), console.error(\" Available regions in sectionRegionMap:\", Array.from(p3.keys())), new Error(`startRegion ${s3} not found in sectionRegionMap`);\n if (!m2)\n throw console.error(\"[getSectionOfHyperGraphAsHyperGraph] CRITICAL ERROR: endRegion not found!\"), console.error(` Looking for: ${u3}`), console.error(` Route connection: ${e37.connection.connectionId}`), console.error(` Original endRegion: ${e37.connection.endRegion.regionId}`), console.error(` endCandidate port: ${i4.port.portId}`), console.error(\" Available regions in sectionRegionMap:\", Array.from(p3.keys())), new Error(`endRegion ${u3} not found in sectionRegionMap`);\n const g2 = { connectionId: e37.connection.connectionId, mutuallyConnectedNetworkId: e37.connection.mutuallyConnectedNetworkId, startRegion: c4, endRegion: m2 }, f2 = e37.path.slice(t3, n3 + 1), _2 = { globalRoute: e37, globalConnection: e37.connection, sectionConnection: g2, sectionStartIndex: t3, sectionEndIndex: n3 };\n h2.push({ ..._2, canRemainFixedInSectionSolve: f2.every((e38) =\u003e l3.ports.some((t4) =\u003e t4.portId === e38.port.portId)), sectionRoute: wY({ sectionRoute: _2, graph: l3 }) }), d2.push(g2);\n }\n return { centralRegionId: o3.regionId, sectionRegionIds: r3, graph: l3, connections: d2, sectionRoutes: h2 };\n};\nvar TY = class {\n heap = [];\n maxSize;\n constructor(e36 = [], t2 = 1e4) {\n if (this.maxSize = t2, e36.length \u003e 0) {\n this.heap = [...e36].sort((e37, t3) =\u003e e37.f - t3.f).slice(0, this.maxSize);\n for (let e37 = Math.floor(this.heap.length / 2) - 1;e37 \u003e= 0; e37--)\n this._siftDown(e37);\n }\n }\n get size() {\n return this.heap.length;\n }\n isEmpty() {\n return this.heap.length === 0;\n }\n peek() {\n return this.isEmpty() ? null : this.heap[0] ?? null;\n }\n peekMany(e36) {\n return [...this.heap].sort((e37, t2) =\u003e e37.f - t2.f).slice(0, e36);\n }\n dequeue() {\n if (this.isEmpty())\n return null;\n const e36 = this.heap[0], t2 = this.heap.pop();\n return this.heap.length === 0 \u0026\u0026 t2 !== undefined || t2 !== undefined \u0026\u0026 (this.heap[0] = t2, this._siftDown(0)), e36;\n }\n enqueue(e36) {\n this.heap.length \u003e= this.maxSize || (this.heap.push(e36), this._siftUp(this.heap.length - 1));\n }\n _siftUp(e36) {\n let t2 = e36;\n for (;t2 \u003e 0; ) {\n const e37 = this._parentIndex(t2);\n if (this.heap[e37].f \u003c= this.heap[t2].f)\n break;\n this._swap(t2, e37), t2 = e37;\n }\n }\n _siftDown(e36) {\n let t2 = e36;\n const n2 = this.heap.length;\n for (;; ) {\n const e37 = this._leftChildIndex(t2), o3 = this._rightChildIndex(t2);\n let i3 = t2;\n if (e37 \u003c n2 \u0026\u0026 this.heap[e37].f \u003c this.heap[i3].f \u0026\u0026 (i3 = e37), o3 \u003c n2 \u0026\u0026 this.heap[o3].f \u003c this.heap[i3].f \u0026\u0026 (i3 = o3), i3 === t2)\n break;\n this._swap(t2, i3), t2 = i3;\n }\n }\n _swap(e36, t2) {\n [this.heap[e36], this.heap[t2]] = [this.heap[t2], this.heap[e36]];\n }\n _parentIndex(e36) {\n return Math.floor((e36 - 1) / 2);\n }\n _leftChildIndex(e36) {\n return 2 * e36 + 1;\n }\n _rightChildIndex(e36) {\n return 2 * e36 + 2;\n }\n};\nvar EY = (e36) =\u003e {\n for (const t2 of e36.regions)\n t2.assignments = [];\n for (const t2 of e36.ports)\n t2.assignment = undefined;\n};\nvar AY = ({ graph: e36, connections: t2, solvedRoutes: n2 }) =\u003e {\n const o3 = new Map(e36.ports.map((e37) =\u003e [e37.portId, e37])), i3 = new Map(e36.regions.map((e37) =\u003e [e37.regionId, e37])), r3 = new Map(t2.map((e37) =\u003e [e37.connectionId, e37])), s2 = n2.map((e37) =\u003e {\n const t3 = [];\n for (const n3 of e37.path) {\n const e38 = { port: o3.get(n3.port.portId), g: n3.g, h: n3.h, f: n3.f, hops: n3.hops, ripRequired: n3.ripRequired };\n n3.lastPort \u0026\u0026 (e38.lastPort = o3.get(n3.lastPort.portId)), n3.lastRegion \u0026\u0026 (e38.lastRegion = i3.get(n3.lastRegion.regionId)), n3.nextRegion \u0026\u0026 (e38.nextRegion = i3.get(n3.nextRegion.regionId));\n const r4 = t3[t3.length - 1];\n r4 \u0026\u0026 (e38.parent = r4), t3.push(e38);\n }\n return { path: t3, connection: r3.get(e37.connection.connectionId), requiredRip: e37.requiredRip };\n });\n EY(e36), e36.solvedRoutes = s2;\n for (const e37 of s2)\n for (const t3 of e37.path) {\n if (t3.port.assignment = { solvedRoute: e37, connection: e37.connection }, !t3.lastPort || !t3.lastRegion)\n continue;\n const n3 = { regionPort1: t3.lastPort, regionPort2: t3.port, region: t3.lastRegion, connection: e37.connection, solvedRoute: e37 };\n t3.lastRegion.assignments ??= [], t3.lastRegion.assignments.push(n3);\n }\n return s2;\n};\nvar OY = class extends BaseSolver {\n constructor(e36) {\n super(), this.input = e36, this.graph = ((e37) =\u003e {\n if (e37.ports.length \u003e 0 \u0026\u0026 \"region1\" in e37.ports[0] \u0026\u0026 typeof e37.ports[0].region1 == \"object\")\n return e37;\n const t3 = new Map, n2 = new Map;\n for (const t4 of e37.regions) {\n const { assignments: e38, ...o3 } = t4;\n n2.set(t4.regionId, { ...o3, d: o3.d ? structuredClone(o3.d) : o3.d, ports: [], assignments: undefined });\n }\n for (const o3 of e37.ports) {\n const e38 = n2.get(o3.region1Id ?? o3.region1?.regionId), i3 = n2.get(o3.region2Id ?? o3.region2?.regionId), r3 = { portId: o3.portId, region1: e38, region2: i3, d: o3.d };\n t3.set(o3.portId, r3), e38.ports.push(r3), i3.ports.push(r3);\n }\n return { ports: Array.from(t3.values()), regions: Array.from(n2.values()) };\n })(e36.inputGraph), EY(this.graph), this.connections = ((e37, t3) =\u003e {\n const n2 = [];\n for (const o3 of e37)\n \"startRegionId\" in o3 ? n2.push({ connectionId: o3.connectionId, mutuallyConnectedNetworkId: o3.mutuallyConnectedNetworkId ?? o3.connectionId, startRegion: t3.regions.find((e38) =\u003e e38.regionId === o3.startRegionId), endRegion: t3.regions.find((e38) =\u003e e38.regionId === o3.endRegionId) }) : n2.push(o3);\n return n2;\n })(e36.inputConnections, this.graph), e36.inputSolvedRoutes ? this.solvedRoutes = AY({ graph: this.graph, connections: this.connections, solvedRoutes: e36.inputSolvedRoutes }) : this.graph.solvedRoutes = this.solvedRoutes, e36.greedyMultiplier !== undefined \u0026\u0026 (this.greedyMultiplier = e36.greedyMultiplier), e36.rippingEnabled !== undefined \u0026\u0026 (this.rippingEnabled = e36.rippingEnabled), e36.ripCost !== undefined \u0026\u0026 (this.ripCost = e36.ripCost);\n const t2 = new Set(this.solvedRoutes.map((e37) =\u003e e37.connection.connectionId));\n this.unprocessedConnections = this.connections.filter((e37) =\u003e !t2.has(e37.connectionId)), this.candidateQueue = new TY, this.unprocessedConnections.length === 0 ? this.solved = true : this.beginNewConnection();\n }\n getSolverName() {\n return \"HyperGraphSolver\";\n }\n graph;\n connections;\n candidateQueue;\n unprocessedConnections;\n solvedRoutes = [];\n currentConnection = null;\n currentEndRegion = null;\n greedyMultiplier = 1;\n rippingEnabled = false;\n ripCost = 0;\n lastCandidate = null;\n visitedPointsForCurrentConnection = new Map;\n getConstructorParams() {\n return { inputGraph: PY(this.graph), inputConnections: CY(this.connections), greedyMultiplier: this.greedyMultiplier, rippingEnabled: this.rippingEnabled, ripCost: this.ripCost, inputSolvedRoutes: this.solvedRoutes };\n }\n computeH(e36) {\n return this.estimateCostToEnd(e36.port);\n }\n estimateCostToEnd(e36) {\n return 0;\n }\n getPortUsagePenalty(e36) {\n return 0;\n }\n computeIncreasedRegionCostIfPortsAreUsed(e36, t2, n2) {\n return 0;\n }\n getRipsRequiredForPortUsage(e36, t2, n2) {\n return [];\n }\n isRipRequiredForPortUsage(e36, t2, n2) {\n return false;\n }\n isTransitionAllowed(e36, t2, n2) {\n return true;\n }\n computeG(e36) {\n return e36.parent.g + this.computeIncreasedRegionCostIfPortsAreUsed(e36.lastRegion, e36.lastPort, e36.port) + (e36.ripRequired ? this.ripCost : 0) + this.getPortUsagePenalty(e36.port);\n }\n selectCandidatesForEnteringRegion(e36) {\n return e36;\n }\n computeRoutesToRip(e36) {\n const t2 = this.computeCrossingRoutes(e36), n2 = this.computePortOverlapRoutes(e36);\n return new Set([...t2, ...n2]);\n }\n computePortOverlapRoutes(e36) {\n const t2 = new Set;\n for (const n2 of e36.path)\n n2.port.assignment \u0026\u0026 n2.port.assignment.connection.mutuallyConnectedNetworkId !== e36.connection.mutuallyConnectedNetworkId \u0026\u0026 t2.add(n2.port.assignment.solvedRoute);\n return t2;\n }\n computeCrossingRoutes(e36) {\n const t2 = new Set;\n for (const n2 of e36.path) {\n if (!n2.lastPort || !n2.lastRegion)\n continue;\n const e37 = this.getRipsRequiredForPortUsage(n2.lastRegion, n2.lastPort, n2.port);\n for (const n3 of e37)\n t2.add(n3.solvedRoute);\n }\n return t2;\n }\n getNextCandidates(e36) {\n const { nextRegion: t2, port: n2 } = e36, o3 = {};\n for (const i4 of t2.ports) {\n if (i4 === e36.port)\n continue;\n if (!this.isTransitionAllowed(t2, n2, i4))\n continue;\n const r3 = i4.assignment \u0026\u0026 i4.assignment.connection.mutuallyConnectedNetworkId !== this.currentConnection.mutuallyConnectedNetworkId || this.isRipRequiredForPortUsage(t2, n2, i4), s2 = { port: i4, hops: e36.hops + 1, parent: e36, lastRegion: t2, nextRegion: i4.region1 === t2 ? i4.region2 : i4.region1, lastPort: n2, ripRequired: r3 };\n !this.rippingEnabled \u0026\u0026 s2.ripRequired || (o3[s2.nextRegion.regionId] ??= [], o3[s2.nextRegion.regionId].push(s2));\n }\n const i3 = [];\n for (const e37 in o3) {\n const t3 = o3[e37];\n i3.push(...this.selectCandidatesForEnteringRegion(t3));\n }\n for (const e37 of i3)\n e37.g = this.computeG(e37), e37.h = this.computeH(e37), e37.f = e37.g + e37.h * this.greedyMultiplier;\n return i3;\n }\n processSolvedRoute(e36) {\n const t2 = { path: [], connection: this.currentConnection, requiredRip: false };\n let n2 = e36, o3 = false;\n for (;n2; )\n o3 ||= !!n2.ripRequired, t2.path.unshift(n2), n2 = n2.parent;\n o3 \u0026\u0026 (t2.requiredRip = true);\n const i3 = this.computeRoutesToRip(t2);\n if (i3.size \u003e 0) {\n t2.requiredRip = true;\n for (const e37 of i3)\n this.ripSolvedRoute(e37);\n }\n for (const e37 of t2.path) {\n if (e37.port.assignment = { solvedRoute: t2, connection: this.currentConnection }, !e37.lastPort)\n continue;\n const n3 = { regionPort1: e37.lastPort, regionPort2: e37.port, region: e37.lastRegion, connection: this.currentConnection, solvedRoute: t2 };\n e37.lastRegion.assignments?.push(n3);\n }\n this.solvedRoutes.push(t2), this.routeSolvedHook(t2);\n }\n routeSolvedHook(e36) {}\n routeStartedHook(e36) {}\n ripSolvedRoute(e36) {\n for (const t2 of e36.path.map((e37) =\u003e e37.port))\n t2.ripCount = (t2.ripCount ?? 0) + 1, t2.region1.assignments = t2.region1.assignments?.filter((e37) =\u003e e37.regionPort1 !== t2 \u0026\u0026 e37.regionPort2 !== t2), t2.region2.assignments = t2.region2.assignments?.filter((e37) =\u003e e37.regionPort1 !== t2 \u0026\u0026 e37.regionPort2 !== t2), t2.assignment = undefined;\n this.solvedRoutes = this.solvedRoutes.filter((t2) =\u003e t2 !== e36), this.unprocessedConnections.push(e36.connection);\n }\n beginNewConnection() {\n this.currentConnection = this.unprocessedConnections.shift(), this.currentEndRegion = this.currentConnection.endRegion, this.candidateQueue = new TY, this.visitedPointsForCurrentConnection.clear(), this.routeStartedHook(this.currentConnection);\n for (const e36 of this.currentConnection.startRegion.ports)\n this.candidateQueue.enqueue({ port: e36, g: 0, h: 0, f: 0, hops: 0, ripRequired: false, nextRegion: e36.region1 === this.currentConnection.startRegion ? e36.region2 : e36.region1 });\n }\n _step() {\n let e36 = this.candidateQueue.dequeue();\n if (!e36)\n return this.failed = true, void (this.error = \"Ran out of candidates\");\n let t2 = this.visitedPointsForCurrentConnection.get(e36.port.portId);\n for (;e36 \u0026\u0026 t2 !== undefined \u0026\u0026 !(e36.g \u003c t2) \u0026\u0026 (e36 = this.candidateQueue.dequeue(), e36); )\n t2 = this.visitedPointsForCurrentConnection.get(e36.port.portId);\n if (!e36)\n return this.failed = true, void (this.error = \"Ran out of candidates\");\n if (this.lastCandidate = e36, this.visitedPointsForCurrentConnection.set(e36.port.portId, e36.g), e36.nextRegion === this.currentEndRegion)\n return this.processSolvedRoute(e36), this.unprocessedConnections.length === 0 ? void (this.solved = true) : void this.beginNewConnection();\n const n2 = this.getNextCandidates(e36);\n for (const e37 of n2)\n this.candidateQueue.enqueue(e37);\n }\n};\nfunction kY(e36, t2) {\n const n2 = e36.x - t2.x, o3 = e36.y - t2.y;\n return n2 * n2 + o3 * o3;\n}\nfunction DY(e36, t2, n2, o3, i3) {\n const r3 = n2 - t2, s2 = i3 - o3, a3 = 0.000001;\n if (Math.abs(e36.y - i3) \u003c a3)\n return e36.x - t2;\n if (Math.abs(e36.x - n2) \u003c a3)\n return r3 + (i3 - e36.y);\n if (Math.abs(e36.y - o3) \u003c a3)\n return r3 + s2 + (n2 - e36.x);\n if (Math.abs(e36.x - t2) \u003c a3)\n return 2 * r3 + s2 + (e36.y - o3);\n const c3 = Math.abs(e36.y - i3), l3 = Math.abs(e36.x - n2), h2 = Math.abs(e36.y - o3), d2 = Math.abs(e36.x - t2), u2 = Math.min(c3, l3, h2, d2);\n return u2 === c3 ? Math.max(0, Math.min(r3, e36.x - t2)) : u2 === l3 ? r3 + Math.max(0, Math.min(s2, i3 - e36.y)) : u2 === h2 ? r3 + s2 + Math.max(0, Math.min(r3, n2 - e36.x)) : 2 * r3 + s2 + Math.max(0, Math.min(s2, e36.y - o3));\n}\nfunction LY(e36, t2, n2) {\n const o3 = n2.x - t2.x, i3 = n2.y - t2.y, r3 = e36.x - t2.x, s2 = e36.y - t2.y, a3 = o3 * o3 + i3 * i3, c3 = a3 \u003e 0 ? (l3 = (r3 * o3 + s2 * i3) / a3, h2 = 0, d2 = 1, Math.max(h2, Math.min(d2, l3))) : 0;\n var l3, h2, d2;\n return { u: c3, d2: kY(e36, { x: t2.x + c3 * o3, y: t2.y + c3 * i3 }) };\n}\nfunction zY(e36) {\n const t2 = e36.d.polygon;\n if (!t2 || t2.length \u003c 3)\n return null;\n const n2 = e36.d.polygonPerimeterCache;\n if (n2)\n return n2;\n const o3 = function(e37) {\n const t3 = e37.length, n3 = new Array(t3), o4 = new Array(t3 + 1);\n o4[0] = 0;\n for (let i3 = 0;i3 \u003c t3; i3++) {\n const r3 = e37[i3], s2 = e37[(i3 + 1) % t3], a3 = Math.hypot(s2.x - r3.x, s2.y - r3.y);\n n3[i3] = a3, o4[i3 + 1] = o4[i3] + a3;\n }\n return { edgeLengths: n3, cumulative: o4, perimeter: o4[t3] };\n }(t2);\n return e36.d.polygonPerimeterCache = o3, o3;\n}\nfunction BY(e36) {\n const t2 = zY(e36);\n if (t2)\n return t2.perimeter;\n const { minX: n2, maxX: o3, minY: i3, maxY: r3 } = e36.d.bounds;\n return 2 * (o3 - n2) + 2 * (r3 - i3);\n}\nfunction FY(e36, t2) {\n if (e36.region1 === t2) {\n if (typeof e36.region1T == \"number\")\n return e36.region1T;\n const n2 = jY(e36.d, t2);\n return e36.region1T = n2, n2;\n }\n if (e36.region2 === t2) {\n if (typeof e36.region2T == \"number\")\n return e36.region2T;\n const n2 = jY(e36.d, t2);\n return e36.region2T = n2, n2;\n }\n return jY(e36.d, t2);\n}\nfunction jY(e36, t2) {\n const n2 = t2.d.polygon;\n if (n2 \u0026\u0026 n2.length \u003e= 3) {\n const o4 = zY(t2);\n if (o4)\n return function(e37, t3, n3, o5 = 0.000001) {\n let i4 = 0, r4 = 0, s3 = Number.POSITIVE_INFINITY;\n const a3 = o5 * o5;\n for (let n4 = 0;n4 \u003c t3.length; n4++) {\n const o6 = LY(e37, t3[n4], t3[(n4 + 1) % t3.length]);\n if (o6.d2 \u003c= a3) {\n i4 = n4, r4 = o6.u, s3 = o6.d2;\n break;\n }\n o6.d2 \u003c s3 \u0026\u0026 (i4 = n4, r4 = o6.u, s3 = o6.d2);\n }\n return n3.cumulative[i4] + r4 * n3.edgeLengths[i4];\n }(e36, n2, o4);\n }\n const { minX: o3, maxX: i3, minY: r3, maxY: s2 } = t2.d.bounds;\n return DY(e36, o3, i3, r3, s2);\n}\nfunction $Y(e36, t2, n2 = 0.000001) {\n return Math.abs(e36 - t2) \u003c n2;\n}\nfunction YY(e36, t2) {\n return (e36 % t2 + t2) % t2;\n}\nfunction XY(e36, t2, n2, o3) {\n const i3 = Math.abs(YY(e36 - t2, n2));\n return i3 \u003c o3 || n2 - i3 \u003c o3;\n}\nfunction HY(e36, t2, n2, o3, i3) {\n const r3 = YY(e36, o3), s2 = YY(t2, o3), a3 = YY(n2, o3);\n return !(Math.abs(s2 - a3) \u003c i3) \u0026\u0026 (s2 \u003c a3 ? s2 \u003c r3 \u0026\u0026 r3 \u003c a3 : r3 \u003e s2 || r3 \u003c a3);\n}\nfunction VY(e36, t2, n2) {\n if (typeof n2 == \"number\" \u0026\u0026 n2 \u003e 0) {\n let [o4, i4] = e36, [r4, s3] = t2;\n if (o4 = YY(o4, n2), i4 = YY(i4, n2), r4 = YY(r4, n2), s3 = YY(s3, n2), XY(o4, r4, n2, 0.000001) || XY(o4, s3, n2, 0.000001) || XY(i4, r4, n2, 0.000001) || XY(i4, s3, n2, 0.000001))\n return false;\n return HY(r4, o4, i4, n2, 0.000000000001) !== HY(s3, o4, i4, n2, 0.000000000001);\n }\n const [o3, i3] = e36[0] \u003c e36[1] ? e36 : [e36[1], e36[0]], [r3, s2] = t2[0] \u003c t2[1] ? t2 : [t2[1], t2[0]];\n return !($Y(o3, r3) || $Y(o3, s2) || $Y(i3, r3) || $Y(i3, s2)) \u0026\u0026 (o3 \u003c r3 \u0026\u0026 r3 \u003c i3 \u0026\u0026 i3 \u003c s2 || r3 \u003c o3 \u0026\u0026 o3 \u003c s2 \u0026\u0026 s2 \u003c i3);\n}\nvar WY = (e36) =\u003e {\n let { POSITIVE_INFINITY: t2, NEGATIVE_INFINITY: n2, POSITIVE_INFINITY: o3, NEGATIVE_INFINITY: i3 } = Number;\n for (const r3 of e36) {\n const { bounds: e37 } = r3.d;\n t2 = Math.min(t2, e37.minX), n2 = Math.max(n2, e37.maxX), o3 = Math.min(o3, e37.minY), i3 = Math.max(i3, e37.maxY);\n }\n return { minX: t2, maxX: n2, minY: o3, maxY: i3 };\n};\nvar GY = (e36, t2, n2, o3) =\u003e {\n const i3 = { portId: e36, region1: t2, region2: n2, d: { x: o3.x, y: o3.y } };\n return t2.ports.push(i3), n2.ports.push(i3), i3;\n};\nvar UY = (e36, t2, n2) =\u003e {\n const o3 = 0.2;\n return { regionId: e36, ports: [], d: { bounds: { minX: t2 - o3, maxX: t2 + o3, minY: n2 - o3, maxY: n2 + o3 }, center: { x: t2, y: n2 }, isPad: false, isConnectionRegion: true } };\n};\nvar ZY = 0.01;\nvar qY = (e36, t2, n2) =\u003e Math.max(t2, Math.min(n2, e36));\nvar JY = (e36, t2, n2) =\u003e t2 === \"left\" ? Math.abs(e36.x - n2.minX) \u003c ZY : t2 === \"right\" ? Math.abs(e36.x - n2.maxX) \u003c ZY : t2 === \"top\" ? Math.abs(e36.y - n2.maxY) \u003c ZY : Math.abs(e36.y - n2.minY) \u003c ZY;\nvar QY = (e36, t2, n2, o3) =\u003e {\n const i3 = o3.x - n2.x, r3 = o3.y - n2.y, s2 = e36 - n2.x, a3 = t2 - n2.y, c3 = i3 * i3 + r3 * r3, l3 = c3 \u003e 0 ? qY((s2 * i3 + a3 * r3) / c3, 0, 1) : 0, h2 = n2.x + l3 * i3, d2 = n2.y + l3 * r3, u2 = e36 - h2, p3 = t2 - d2;\n return { x: h2, y: d2, d2: u2 * u2 + p3 * p3 };\n};\nvar KY = (e36, t2, n2, o3, i3) =\u003e {\n const r3 = n2.d.polygon;\n if (r3 \u0026\u0026 r3.length \u003e= 3) {\n const n3 = new Set(i3);\n let s3 = null;\n for (let a4 = 0;a4 \u003c r3.length; a4++) {\n const c4 = r3[a4], l3 = r3[(a4 + 1) % r3.length];\n if (i3.length \u003e 0) {\n if (!i3.some((e37) =\u003e JY(c4, e37, o3) \u0026\u0026 JY(l3, e37, o3) \u0026\u0026 n3.has(e37)))\n continue;\n }\n const h2 = QY(e36, t2, c4, l3);\n (!s3 || h2.d2 \u003c s3.d2) \u0026\u0026 (s3 = h2);\n }\n if (s3)\n return s3;\n }\n const s2 = n2.d.bounds, a3 = [];\n if (i3.length \u003e 0)\n for (const n3 of i3)\n n3 === \"left\" ? a3.push({ side: n3, x: s2.minX, y: qY(t2, s2.minY, s2.maxY) }) : n3 === \"right\" ? a3.push({ side: n3, x: s2.maxX, y: qY(t2, s2.minY, s2.maxY) }) : n3 === \"top\" ? a3.push({ side: n3, x: qY(e36, s2.minX, s2.maxX), y: s2.maxY }) : a3.push({ side: n3, x: qY(e36, s2.minX, s2.maxX), y: s2.minY });\n a3.length === 0 \u0026\u0026 a3.push({ side: \"left\", x: s2.minX, y: qY(t2, s2.minY, s2.maxY) }, { side: \"right\", x: s2.maxX, y: qY(t2, s2.minY, s2.maxY) }, { side: \"top\", x: qY(e36, s2.minX, s2.maxX), y: s2.maxY }, { side: \"bottom\", x: qY(e36, s2.minX, s2.maxX), y: s2.minY });\n let c3 = null;\n for (const n3 of a3) {\n if (i3.length \u003e 0 \u0026\u0026 !i3.includes(n3.side))\n continue;\n const o4 = e36 - n3.x, r4 = t2 - n3.y, s3 = o4 * o4 + r4 * r4;\n (!c3 || s3 \u003c c3.d2) \u0026\u0026 (c3 = { x: n3.x, y: n3.y, d2: s3 });\n }\n return c3;\n};\nvar eX = (e36, t2, n2, o3) =\u003e {\n const i3 = ((e37, t3, n3) =\u003e {\n const o4 = [];\n return Math.abs(e37 - n3.minX) \u003c ZY \u0026\u0026 o4.push(\"left\"), Math.abs(e37 - n3.maxX) \u003c ZY \u0026\u0026 o4.push(\"right\"), Math.abs(t3 - n3.maxY) \u003c ZY \u0026\u0026 o4.push(\"top\"), Math.abs(t3 - n3.minY) \u003c ZY \u0026\u0026 o4.push(\"bottom\"), o4;\n })(e36, t2, o3);\n let r3 = null, s2 = Number.POSITIVE_INFINITY, a3 = { x: e36, y: t2 };\n for (const c3 of n2) {\n if (c3.d.isPad || c3.d.isThroughJumper)\n continue;\n const n3 = c3.d.bounds;\n if (!(Math.abs(n3.minX - o3.minX) \u003c 0.01 || Math.abs(n3.maxX - o3.maxX) \u003c 0.01 || Math.abs(n3.minY - o3.minY) \u003c 0.01 || Math.abs(n3.maxY - o3.maxY) \u003c 0.01))\n continue;\n const l3 = KY(e36, t2, c3, o3, i3);\n if (!l3)\n continue;\n const h2 = Math.sqrt(l3.d2);\n h2 \u003c s2 \u0026\u0026 (s2 = h2, r3 = c3, a3 = { x: l3.x, y: l3.y });\n }\n return r3 ? { region: r3, portPosition: a3 } : null;\n};\nvar tX = class extends BaseSolver {\n constructor(e36) {\n super(), this.input = e36, this.graph = e36.hyperGraphSolver.graph;\n const t2 = e36.inputSolvedRoutes, n2 = e36.hyperGraphSolver.connections;\n this.connections = n2, this.solvedRoutes = AY({ graph: this.graph, connections: this.connections, solvedRoutes: t2 }), this.maxAttemptsPerRegion = e36.MAX_ATTEMPTS_PER_REGION, this.maxSectionAttempts = e36.MAX_ATTEMPTS_PER_SECTION ?? 500, this.iterations += this.iterations * (e36.effort ?? 1), this.fractionToReplace = e36.FRACTION_TO_REPLACE ?? 0.2, this.alwaysRipConflicts = e36.alwaysRipConflicts ?? true;\n }\n graph;\n connections;\n solvedRoutes;\n activeSection = null;\n baselineSectionCost = 1 / 0;\n baselineGlobalCost = 1 / 0;\n regionAttemptCounts = new Map;\n sectionAttempts = 0;\n maxAttemptsPerRegion;\n maxSectionAttempts;\n fractionToReplace;\n alwaysRipConflicts;\n random = ((e36) =\u003e {\n let t2 = e36;\n return () =\u003e (t2 = 1664525 * t2 + 1013904223 \u003e\u003e\u003e 0, t2 / 4294967295);\n })(31337);\n getSolverName() {\n return \"HyperGraphSectionOptimizer\";\n }\n getConstructorParams() {\n return { inputGraph: PY(this.graph), inputConnections: CY(this.connections), inputSolvedRoutes: this.solvedRoutes, expansionHopsFromCentralRegion: this.input.expansionHopsFromCentralRegion, maxAttemptsPerRegion: this.maxAttemptsPerRegion, maxSectionAttempts: this.maxSectionAttempts, effort: this.input.effort, fractionToReplace: this.fractionToReplace, alwaysRipConflicts: this.alwaysRipConflicts, ACCEPTABLE_COST: this.input.ACCEPTABLE_REGION_COST };\n }\n getOutput() {\n return this.solvedRoutes;\n }\n _setup() {\n this.beginSectionSolve();\n }\n visualize() {\n return this.activeSubSolver ? this.activeSubSolver.visualize() : { title: \"HyperGraphSectionOptimizer\", points: [], lines: [], rects: [], circles: [], texts: [], polygons: [], arrows: [] };\n }\n getCostOfRegionWithAttempts(e36) {\n const t2 = this.regionAttemptCounts.get(e36.regionId) ?? 0;\n return this.input.regionCost(e36) + 1e4 * t2;\n }\n computeCostOfSection({ section: e36, solvedRoutes: t2 }) {\n if (this.input.computeSolvedGraphCost)\n return this.input.computeSolvedGraphCost(t2);\n const n2 = this.input.createHyperGraphSolver({ inputGraph: e36.graph, inputConnections: e36.connections, inputSolvedRoutes: t2 });\n let o3 = 0;\n for (const e37 of n2.graph.regions)\n o3 += this.input.regionCost(e37);\n return o3;\n }\n computeSolvedGraphCost(e36) {\n if (this.input.computeSolvedGraphCost)\n return this.input.computeSolvedGraphCost(e36);\n const t2 = this.input.createHyperGraphSolver({ inputGraph: this.graph, inputConnections: this.connections, inputSolvedRoutes: e36 });\n let n2 = 0;\n for (const e37 of t2.graph.regions)\n n2 += this.input.regionCost(e37);\n return n2;\n }\n determineConnectionsToRip(e36, t2) {\n const n2 = e36.sectionRoutes.map((e37) =\u003e e37.globalConnection.connectionId);\n if (this.fractionToReplace \u003e= 1)\n return new Set(n2);\n const o3 = [...n2];\n for (let e37 = o3.length - 1;e37 \u003e 0; e37--) {\n const t3 = Math.floor(this.random() * (e37 + 1));\n [o3[e37], o3[t3]] = [o3[t3], o3[e37]];\n }\n const i3 = Math.max(1, Math.ceil(o3.length * this.fractionToReplace)), r3 = new Set(o3.slice(0, i3));\n if (!this.alwaysRipConflicts)\n return r3;\n const s2 = new Map(e36.graph.regions.map((e37) =\u003e [e37.regionId, e37]));\n for (const n3 of e36.sectionRoutes)\n for (const e37 of n3.sectionRoute.path) {\n if (!e37.lastPort || !e37.lastRegion)\n continue;\n const o4 = s2.get(e37.lastRegion.regionId);\n if (!o4)\n continue;\n t2.currentConnection = n3.globalConnection;\n const i4 = t2.getRipsRequiredForPortUsage(o4, e37.lastPort, e37.port);\n for (const e38 of i4) {\n const t3 = n3.globalConnection.connectionId, o5 = e38.connection.connectionId;\n r3.has(t3) || r3.has(o5) || r3.add(this.random() \u003c 0.5 ? t3 : o5);\n }\n }\n return r3;\n }\n getNextCentralRegion() {\n let e36 = null, t2 = 1 / 0;\n for (const n2 of this.graph.regions) {\n if ((n2.assignments?.length ?? 0) === 0)\n continue;\n if ((this.regionAttemptCounts.get(n2.regionId) ?? 0) \u003e= this.maxAttemptsPerRegion)\n continue;\n if (this.input.regionCost(n2) \u003c this.input.ACCEPTABLE_REGION_COST)\n continue;\n const o3 = this.getCostOfRegionWithAttempts(n2);\n o3 \u003e= t2 || (t2 = o3, e36 = n2);\n }\n return e36;\n }\n beginSectionSolve() {\n if (this.sectionAttempts \u003e= this.maxSectionAttempts)\n return console.log(`Reached max section attempts (${this.maxSectionAttempts}), stopping optimization`), void (this.solved = true);\n const e36 = this.getNextCentralRegion();\n if (!e36)\n return void (this.solved = true);\n if (this.sectionAttempts++, this.activeSection = RY({ graph: this.graph, solvedRoutes: this.solvedRoutes, centralRegion: e36, expansionHopsFromCentralRegion: this.input.expansionHopsFromCentralRegion }), !this.activeSection)\n return;\n if (this.activeSection.connections.length === 0)\n return this.regionAttemptCounts.set(e36.regionId, (this.regionAttemptCounts.get(e36.regionId) ?? 0) + 1), void (this.activeSection = null);\n const t2 = this.activeSection.sectionRoutes.filter((e37) =\u003e e37.canRemainFixedInSectionSolve), n2 = this.input.createHyperGraphSolver({ inputGraph: this.activeSection.graph, inputConnections: this.activeSection.connections, inputSolvedRoutes: t2.map((e37) =\u003e e37.sectionRoute) }), o3 = this.determineConnectionsToRip(this.activeSection, n2);\n for (const e37 of this.activeSection.sectionRoutes)\n e37.canRemainFixedInSectionSolve || o3.add(e37.globalConnection.connectionId);\n const i3 = this.activeSection.sectionRoutes.filter((e37) =\u003e e37.canRemainFixedInSectionSolve \u0026\u0026 !o3.has(e37.globalConnection.connectionId)).map((e37) =\u003e e37.sectionRoute), r3 = [...i3, ...this.activeSection.sectionRoutes.filter((e37) =\u003e o3.has(e37.globalConnection.connectionId)).map((e37) =\u003e e37.sectionRoute)];\n this.baselineSectionCost = this.computeCostOfSection({ section: this.activeSection, solvedRoutes: r3 }), this.baselineGlobalCost = this.computeSolvedGraphCost(this.solvedRoutes), this.activeSubSolver = this.input.createHyperGraphSolver({ inputGraph: this.activeSection.graph, inputConnections: this.activeSection.connections, inputSolvedRoutes: i3 });\n for (const e37 of this.activeSubSolver.connections)\n e37.startRegion \u0026\u0026 e37.endRegion || console.error({ startRegion: e37.startRegion?.regionId, endRegion: e37.endRegion?.regionId });\n }\n _step() {\n if (!this.activeSubSolver)\n return void this.beginSectionSolve();\n if (this.activeSubSolver.step(), !this.activeSection)\n return;\n if (this.activeSubSolver.failed) {\n this.failedSubSolvers ??= [], this.failedSubSolvers.push(this.activeSubSolver);\n const e37 = this.regionAttemptCounts.get(this.activeSection.centralRegionId) ?? 0;\n return this.regionAttemptCounts.set(this.activeSection.centralRegionId, e37 + 1), this.activeSubSolver = null, this.activeSection = null, this.baselineSectionCost = 1 / 0, void (this.baselineGlobalCost = 1 / 0);\n }\n if (!this.activeSubSolver.solved)\n return;\n const e36 = this.activeSubSolver.solvedRoutes, t2 = this.computeCostOfSection({ section: this.activeSection, solvedRoutes: e36 }), n2 = ((e37) =\u003e {\n const { solvedRoutes: t3, section: n3, replacementSolvedRoutes: o4 } = e37, i4 = new Map(o4.map((e38) =\u003e [e38.connection.connectionId, e38]));\n return t3.map((e38) =\u003e {\n const t4 = n3.sectionRoutes.find((t5) =\u003e t5.globalConnection.connectionId === e38.connection.connectionId);\n if (!t4)\n return e38;\n const o5 = i4.get(e38.connection.connectionId);\n if (!o5)\n return e38;\n const r4 = [...e38.path.slice(0, t4.sectionStartIndex), ...o5.path, ...e38.path.slice(t4.sectionEndIndex + 1)].map((e39) =\u003e ({ port: e39.port, g: e39.g, h: e39.h, f: e39.f, hops: e39.hops, ripRequired: e39.ripRequired, lastPort: e39.lastPort, lastRegion: e39.lastRegion, nextRegion: e39.nextRegion }));\n for (let e39 = 0;e39 \u003c r4.length; e39++)\n r4[e39].parent = e39 \u003e 0 ? r4[e39 - 1] : undefined;\n return { connection: e38.connection, path: r4, requiredRip: e38.requiredRip || o5.requiredRip };\n });\n })({ solvedRoutes: this.solvedRoutes, section: this.activeSection, replacementSolvedRoutes: e36 }), o3 = this.computeSolvedGraphCost(n2), i3 = t2 \u003c= this.baselineSectionCost, r3 = o3 \u003c this.baselineGlobalCost;\n if (i3 \u0026\u0026 r3) {\n this.solvedRoutes = n2;\n const e37 = this.input.hyperGraphSolver;\n if (!e37)\n return;\n e37.solvedRoutes = AY({ graph: e37.graph, connections: e37.connections, solvedRoutes: this.solvedRoutes });\n for (const e38 of this.activeSection.sectionRegionIds)\n this.regionAttemptCounts.set(e38, 0);\n this.baselineSectionCost = t2, this.baselineGlobalCost = o3;\n } else {\n const e37 = this.regionAttemptCounts.get(this.activeSection.centralRegionId) ?? 0;\n this.regionAttemptCounts.set(this.activeSection.centralRegionId, e37 + 1);\n }\n this.activeSubSolver = null, this.activeSection = null, this.baselineSectionCost = 1 / 0, this.baselineGlobalCost = 1 / 0;\n }\n};\nfunction nX(e36, t2) {\n return Array.isArray(t2) ? [e36.a * t2[0] + e36.c * t2[1] + e36.e, e36.b * t2[0] + e36.d * t2[1] + e36.f] : { x: e36.a * t2.x + e36.c * t2.y + e36.e, y: e36.b * t2.x + e36.d * t2.y + e36.f };\n}\nfunction oX(e36) {\n return e36 === undefined;\n}\nfunction iX(e36, t2 = 0) {\n return { a: 1, c: 0, e: e36, b: 0, d: 1, f: t2 };\n}\nfunction rX(...e36) {\n const t2 = (e37, t3) =\u003e ({ a: e37.a * t3.a + e37.c * t3.b, c: e37.a * t3.c + e37.c * t3.d, e: e37.a * t3.e + e37.c * t3.f + e37.e, b: e37.b * t3.a + e37.d * t3.b, d: e37.b * t3.c + e37.d * t3.d, f: e37.b * t3.e + e37.d * t3.f + e37.f });\n switch ((e36 = Array.isArray(e36[0]) ? e36[0] : e36).length) {\n case 0:\n throw new Error(\"no matrices provided\");\n case 1:\n return e36[0];\n case 2:\n return t2(e36[0], e36[1]);\n default: {\n const [n2, o3, ...i3] = e36;\n return rX(t2(n2, o3), ...i3);\n }\n }\n}\nvar { cos: sX, sin: aX, PI: cX } = Math;\nvar hX = (e36) =\u003e ({ x: (e36.minX + e36.maxX) / 2, y: (e36.minY + e36.maxY) / 2 });\nvar dX = (e36, t2) =\u003e {\n const n2 = e36.regions.map((e37) =\u003e {\n const { bounds: n3, center: o4, ...i4 } = e37.d, r4 = [{ x: n3.minX, y: n3.minY }, { x: n3.maxX, y: n3.minY }, { x: n3.minX, y: n3.maxY }, { x: n3.maxX, y: n3.maxY }].map((e38) =\u003e nX(t2, e38)), s2 = { minX: Math.min(...r4.map((e38) =\u003e e38.x)), maxX: Math.max(...r4.map((e38) =\u003e e38.x)), minY: Math.min(...r4.map((e38) =\u003e e38.y)), maxY: Math.max(...r4.map((e38) =\u003e e38.y)) }, a3 = nX(t2, o4);\n return { ...e37, ports: [], d: { ...i4, bounds: s2, center: a3 } };\n }), o3 = new Map;\n for (let t3 = 0;t3 \u003c e36.regions.length; t3++)\n o3.set(e36.regions[t3], n2[t3]);\n const i3 = e36.ports.map((e37) =\u003e {\n const n3 = nX(t2, e37.d), i4 = o3.get(e37.region1), r4 = o3.get(e37.region2), s2 = { ...e37, region1: i4, region2: r4, d: n3 };\n return i4.ports.push(s2), r4.ports.push(s2), s2;\n }), r3 = e36.jumperLocations?.map((e37) =\u003e {\n const n3 = nX(t2, e37.center), i4 = e37.padRegions.map((e38) =\u003e o3.get(e38)), r4 = nX(t2, { x: 1, y: 0 }), s2 = nX(t2, { x: 0, y: 0 }), a3 = r4.x - s2.x, c3 = r4.y - s2.y;\n return { center: n3, orientation: Math.abs(c3) \u003e Math.abs(a3) ? e37.orientation === \"horizontal\" ? \"vertical\" : \"horizontal\" : e37.orientation, padRegions: i4 };\n });\n return { regions: n2, ports: i3, ...r3 \u0026\u0026 { jumperLocations: r3 } };\n};\nvar uX = (e36, t2 = 0.8) =\u003e {\n let n2 = 0;\n for (let t3 = 0;t3 \u003c e36.length; t3++)\n n2 = 17777 * e36.charCodeAt(t3) + ((n2 \u003c\u003c 5) - n2);\n return `hsla(${Math.abs(n2) % 360}, 70%, 50%, ${t2})`;\n};\nvar pX = (e36) =\u003e {\n const t2 = ((e37) =\u003e {\n const t3 = ((e38, t4) =\u003e {\n const n3 = { arrows: [], circles: [], title: \"Jumper Graph\", lines: [], points: [], rects: [], texts: [], polygons: [], coordinateSystem: \"cartesian\" };\n for (const t5 of e38.regions) {\n const { bounds: e39, isPad: o4, isThroughJumper: i3, isConnectionRegion: r3, polygon: s2 } = t5.d, a3 = (e39.minX + e39.maxX) / 2, c3 = (e39.minY + e39.maxY) / 2, l3 = e39.maxX - e39.minX, h2 = e39.maxY - e39.minY;\n let d2;\n if (d2 = r3 ? \"rgba(255, 100, 255, 0.6)\" : i3 ? \"rgba(100, 200, 100, 0.5)\" : o4 ? \"rgba(255, 200, 100, 0.5)\" : \"rgba(200, 200, 255, 0.1)\", s2 \u0026\u0026 s2.length \u003e= 3) {\n const e40 = s2;\n n3.polygons.push({ points: e40, fill: d2 });\n } else\n n3.rects.push({ center: { x: a3, y: c3 }, width: l3 - 0.1, height: h2 - 0.1, fill: d2 });\n }\n if (!t4?.hidePortPoints)\n for (const t5 of e38.ports) {\n const e39 = t5.region1.regionId.split(\":\").pop() ?? t5.region1.regionId, o4 = t5.region2.regionId.split(\":\").pop() ?? t5.region2.regionId;\n n3.circles.push({ center: { x: t5.d.x, y: t5.d.y }, radius: 0.05, fill: \"rgba(128, 128, 128, 0.5)\", label: `${e39}-${o4}` });\n }\n if (!t4?.hideRegionPortLines)\n for (const t5 of e38.ports) {\n const e39 = { x: (t5.region1.d.bounds.minX + t5.region1.d.bounds.maxX) / 2, y: (t5.region1.d.bounds.minY + t5.region1.d.bounds.maxY) / 2 }, o4 = { x: (t5.region2.d.bounds.minX + t5.region2.d.bounds.maxX) / 2, y: (t5.region2.d.bounds.minY + t5.region2.d.bounds.maxY) / 2 };\n n3.lines.push({ points: [e39, { x: t5.d.x, y: t5.d.y }, o4], strokeColor: \"rgba(100, 100, 100, 0.3)\" });\n }\n if (t4?.connections \u0026\u0026 !t4?.hideConnectionLines)\n for (const e39 of t4.connections) {\n const { startRegion: t5, endRegion: o4 } = e39, i3 = { x: (t5.d.bounds.minX + t5.d.bounds.maxX) / 2, y: (t5.d.bounds.minY + t5.d.bounds.maxY) / 2 }, r3 = { x: (o4.d.bounds.minX + o4.d.bounds.maxX) / 2, y: (o4.d.bounds.minY + o4.d.bounds.maxY) / 2 }, s2 = (i3.x + r3.x) / 2, a3 = (i3.y + r3.y) / 2;\n n3.lines.push({ points: [i3, r3], strokeColor: \"rgba(255, 50, 150, 0.8)\", strokeDash: \"3 3\" }), n3.points.push({ x: s2, y: a3, color: \"rgba(200, 0, 100, 1)\", label: e39.connectionId });\n }\n return n3;\n })(e37.graph, { connections: e37.connections, ...e37.hideInitialGeometry ? { hideRegionPortLines: true, hideConnectionLines: true, hidePortPoints: true } : {} });\n if (!e37.hideInitialGeometry)\n for (const e38 of t3.polygons)\n e38.stroke = \"rgba(128, 128, 128, 0.5)\", e38.strokeWidth = 0.03;\n e37.title \u0026\u0026 (t3.title = e37.title);\n for (const n3 of e37.priorSolvedRoutes ?? []) {\n const e38 = n3.path.map((e39) =\u003e {\n const t4 = e39.port;\n return { x: t4.d.x, y: t4.d.y };\n });\n e38.length !== 0 \u0026\u0026 t3.lines.push({ points: e38, strokeColor: \"rgba(80, 80, 80, 0.45)\", strokeDash: \"4 4\" });\n }\n for (const n3 of e37.solvedRoutes) {\n const e38 = uX(n3.connection.connectionId), o4 = [];\n for (const e39 of n3.path) {\n const t4 = e39.port;\n o4.push({ x: t4.d.x, y: t4.d.y });\n }\n o4.length \u003e 0 \u0026\u0026 t3.lines.push({ points: o4, strokeColor: e38 });\n }\n return t3;\n })({ graph: { regions: e36.graph.regions, ports: e36.graph.ports }, connections: e36.connections, solvedRoutes: e36.solvedRoutes, hideInitialGeometry: e36.iterations \u003e 0 });\n if (e36.currentConnection \u0026\u0026 !e36.solved) {\n const n3 = uX(e36.currentConnection.connectionId), o4 = e36.currentConnection.startRegion, i3 = e36.currentConnection.endRegion;\n if (!o4?.d || !i3?.d)\n return t2;\n const r3 = { x: (o4.d.bounds.minX + o4.d.bounds.maxX) / 2, y: (o4.d.bounds.minY + o4.d.bounds.maxY) / 2 }, s2 = { x: (i3.d.bounds.minX + i3.d.bounds.maxX) / 2, y: (i3.d.bounds.minY + i3.d.bounds.maxY) / 2 };\n t2.lines.push({ points: [r3, s2], strokeColor: n3, strokeDash: \"10 5\" }), t2.points.push({ x: r3.x - 0.1, y: r3.y + 0.1, color: n3, label: [e36.currentConnection.connectionId, \"start\"].join(`\n`) }), t2.points.push({ x: s2.x - 0.1, y: s2.y + 0.1, color: n3, label: [e36.currentConnection.connectionId, \"end\"].join(`\n`) });\n }\n const n2 = e36.candidateQueue.peekMany(10);\n for (let e37 = 0;e37 \u003c n2.length; e37++) {\n const o4 = n2[e37], i3 = o4.port, r3 = e37 === 0;\n t2.points.push({ x: i3.d.x, y: i3.d.y, color: r3 ? \"green\" : \"rgba(128, 128, 128, 0.25)\", label: [o4.port.portId, `g: ${o4.g.toFixed(2)}`, `h: ${o4.h.toFixed(2)}`, `f: ${o4.f.toFixed(2)}`].join(`\n`) });\n }\n const o3 = n2[0];\n if (!e36.solved \u0026\u0026 o3 \u0026\u0026 e36.currentConnection) {\n const n3 = uX(e36.currentConnection.connectionId), i3 = [];\n let r3 = o3;\n for (;r3; ) {\n const e37 = r3.port;\n i3.unshift({ x: e37.d.x, y: e37.d.y }), r3 = r3.parent;\n }\n i3.length \u003e 1 \u0026\u0026 t2.lines.push({ points: i3, strokeColor: n3 });\n }\n return t2;\n};\nvar mX = 0.034685181009478865;\nvar gX = 0;\nvar fX = 4.072520483177124;\nvar _X = 0;\nvar yX = 35.38577539020022;\nvar bX = 0.5518001238069296;\nvar xX = class extends OY {\n getSolverName() {\n return \"JumperGraphSolver\";\n }\n UNIT_OF_COST = \"hops\";\n portUsagePenalty = mX;\n portUsagePenaltySq = gX;\n crossingPenalty = fX;\n crossingPenaltySq = _X;\n ripCost = yX;\n baseMaxIterations = 4000;\n additionalMaxIterationsPerConnection = 2000;\n additionalMaxIterationsPerCrossing = 2000;\n constructor(e36) {\n super({ greedyMultiplier: bX, rippingEnabled: true, ...e36 }), this.ripCost = e36.ripCost ?? this.ripCost, this.portUsagePenalty = e36.portUsagePenalty ?? this.portUsagePenalty, this.crossingPenalty = e36.crossingPenalty ?? this.crossingPenalty, this.baseMaxIterations = e36.baseMaxIterations ?? this.baseMaxIterations, this.additionalMaxIterationsPerConnection = e36.additionalMaxIterationsPerConnection ?? this.additionalMaxIterationsPerConnection;\n const t2 = function(e37, t3) {\n if (t3.length \u003c 2)\n return 0;\n let n2 = 1 / 0, o3 = -1 / 0, i3 = 1 / 0, r3 = -1 / 0;\n for (const t4 of e37.regions) {\n const e38 = t4;\n e38.d?.bounds ? (n2 = Math.min(n2, e38.d.bounds.minX), o3 = Math.max(o3, e38.d.bounds.maxX), i3 = Math.min(i3, e38.d.bounds.minY), r3 = Math.max(r3, e38.d.bounds.maxY)) : e38.d?.center \u0026\u0026 (n2 = Math.min(n2, e38.d.center.x), o3 = Math.max(o3, e38.d.center.x), i3 = Math.min(i3, e38.d.center.y), r3 = Math.max(r3, e38.d.center.y));\n }\n const s2 = new Map;\n for (const t4 of e37.regions) {\n const e38 = t4;\n e38.d?.center \u0026\u0026 s2.set(t4.regionId, e38.d.center);\n }\n const a3 = [], c3 = 2 * (o3 - n2) + 2 * (r3 - i3);\n for (const e38 of t3) {\n let t4, c4;\n if (\"startRegion\" in e38 \u0026\u0026 e38.startRegion) {\n const { startRegion: n3, endRegion: o4 } = e38;\n t4 = n3.d?.center, c4 = o4.d?.center;\n } else\n \"startRegionId\" in e38 \u0026\u0026 (t4 = s2.get(e38.startRegionId), c4 = s2.get(e38.endRegionId));\n if (!t4 || !c4)\n continue;\n const l4 = DY(t4, n2, o3, i3, r3), h2 = DY(c4, n2, o3, i3, r3);\n a3.push([l4, h2]);\n }\n let l3 = 0;\n for (let e38 = 0;e38 \u003c a3.length; e38++)\n for (let t4 = e38 + 1;t4 \u003c a3.length; t4++)\n VY(a3[e38], a3[t4], c3) \u0026\u0026 l3++;\n return l3;\n }(this.graph, e36.inputConnections);\n this.MAX_ITERATIONS = this.baseMaxIterations + e36.inputConnections.length * this.additionalMaxIterationsPerConnection + t2 * this.additionalMaxIterationsPerCrossing, this.populateDistanceToEndMaps();\n }\n populateDistanceToEndMaps() {\n const e36 = new Set(this.connections.map((e37) =\u003e e37.endRegion));\n for (const t2 of e36) {\n const e37 = new Map, n2 = [];\n for (e37.set(t2.regionId, 0), n2.push({ region: t2, distance: 0 });n2.length \u003e 0; ) {\n const { region: t3, distance: o3 } = n2.shift();\n for (const i3 of t3.ports) {\n const r3 = i3.region1 === t3 ? i3.region2 : i3.region1;\n e37.has(r3.regionId) || (e37.set(r3.regionId, o3 + 1), n2.push({ region: r3, distance: o3 + 1 }));\n }\n }\n for (const n3 of this.graph.ports) {\n n3.distanceToEndMap || (n3.distanceToEndMap = {});\n const o3 = e37.get(n3.region1.regionId) ?? 1 / 0, i3 = e37.get(n3.region2.regionId) ?? 1 / 0;\n n3.distanceToEndMap[t2.regionId] = Math.min(o3, i3);\n }\n }\n }\n estimateCostToEnd(e36) {\n const t2 = this.currentEndRegion.regionId;\n return e36.distanceToEndMap[t2];\n }\n getPortUsagePenalty(e36) {\n const t2 = e36.ripCount ?? 0;\n return t2 * this.portUsagePenalty + t2 * this.portUsagePenaltySq;\n }\n isTransitionAllowed(e36, t2, n2) {\n if (!e36.d.isPad)\n return true;\n const o3 = (t3) =\u003e {\n const n3 = t3.region1 === e36 ? t3.region2 : t3.region1;\n return Boolean(n3.d.isThroughJumper);\n };\n return o3(t2) || o3(n2);\n }\n computeIncreasedRegionCostIfPortsAreUsed(e36, t2, n2) {\n if (e36.d.isPad) {\n const t3 = (e36.assignments ?? []).filter((e37) =\u003e e37.connection.mutuallyConnectedNetworkId !== this.currentConnection.mutuallyConnectedNetworkId).length;\n return t3 \u003e 0 ? t3 * this.crossingPenalty + t3 * this.crossingPenaltySq : 0;\n }\n const o3 = function(e37, t3, n3) {\n const o4 = BY(e37), i3 = [FY(t3, e37), FY(n3, e37)];\n let r3 = 0;\n const s2 = e37.assignments ?? [];\n for (const t4 of s2)\n VY(i3, [FY(t4.regionPort1, e37), FY(t4.regionPort2, e37)], o4) \u0026\u0026 r3++;\n return r3;\n }(e36, t2, n2);\n return o3 * this.crossingPenalty + o3 * this.crossingPenaltySq;\n }\n getRipsRequiredForPortUsage(e36, t2, n2) {\n if (e36.d.isPad) {\n return (e36.assignments ?? []).filter((e37) =\u003e e37.connection.mutuallyConnectedNetworkId !== this.currentConnection.mutuallyConnectedNetworkId);\n }\n const o3 = function(e37, t3, n3) {\n const o4 = BY(e37), i4 = [FY(t3, e37), FY(n3, e37)], r3 = [], s2 = e37.assignments ?? [];\n for (const t4 of s2)\n VY(i4, [FY(t4.regionPort1, e37), FY(t4.regionPort2, e37)], o4) \u0026\u0026 r3.push(t4);\n return r3;\n }(e36, t2, n2), i3 = o3.filter((e37) =\u003e e37.connection.mutuallyConnectedNetworkId !== this.currentConnection.mutuallyConnectedNetworkId);\n if (!e36.d.isThroughJumper)\n return i3;\n for (const t3 of e36.assignments ?? [])\n t3.connection.mutuallyConnectedNetworkId !== this.currentConnection.mutuallyConnectedNetworkId \u0026\u0026 i3.push(t3);\n return i3;\n }\n isRipRequiredForPortUsage(e36, t2, n2) {\n if (!e36.d.isThroughJumper \u0026\u0026 !e36.d.isPad)\n return false;\n for (const t3 of e36.assignments ?? [])\n if (t3.connection.mutuallyConnectedNetworkId !== this.currentConnection.mutuallyConnectedNetworkId)\n return true;\n return false;\n }\n routeSolvedHook(e36) {}\n routeStartedHook(e36) {}\n visualize() {\n return pX(this);\n }\n};\nvar vX = { padWidth: 0.8, outerPadHeight: 0.5, innerPadHeight: 0.4, leftPadCenterX: -0.9, rightPadCenterX: 0.9, row1CenterY: -1.2, row2CenterY: -0.4, row3CenterY: 0.4, row4CenterY: 1.2 };\nvar IX = ({ cols: e36, rows: t2, marginX: n2, marginY: o3, innerColChannelPointCount: i3 = 1, innerRowChannelPointCount: r3 = 1, regionsBetweenPads: s2 = false, outerPaddingX: a3 = 0.5, outerPaddingY: c3 = 0.5, outerChannelXPointCount: l3, outerChannelYPointCount: h2, orientation: d2 = \"vertical\", center: u2, bounds: p3, parallelTracesUnderJumperCount: m2 = 2 }) =\u003e {\n const g2 = [], f2 = [], { padWidth: _2, outerPadHeight: y2, innerPadHeight: b2, leftPadCenterX: x2, rightPadCenterX: v2, row1CenterY: I2, row2CenterY: S2, row3CenterY: C, row4CenterY: P } = vX, M = _2 / 2, w = y2 / 2, N = b2 / 2, R2 = v2 - x2 + _2, T2 = R2 + n2, E3 = P - I2 + y2, A2 = E3 + o3;\n let O2 = a3, k2 = c3;\n if (p3) {\n const i4 = e36 * R2 + (e36 - 1) * n2, r4 = t2 * E3 + (t2 - 1) * o3;\n O2 = ((d2 === \"horizontal\" ? p3.maxY - p3.minY : p3.maxX - p3.minX) - i4) / 2, k2 = ((d2 === \"horizontal\" ? p3.maxX - p3.minX : p3.maxY - p3.minY) - r4) / 2;\n }\n const D2 = l3 ?? Math.max(1, Math.floor(O2 / 0.4)), L2 = h2 ?? Math.max(1, Math.floor(k2 / 0.4)), z2 = [], B2 = [], F2 = (e37, t3, n3, o4) =\u003e ({ regionId: e37, ports: [], d: { bounds: t3, center: hX(t3), isPad: n3, isThroughJumper: o4 } }), j2 = (e37, t3, n3) =\u003e {\n const o4 = t3.d.bounds, i4 = n3.d.bounds;\n let r4, s3;\n Math.abs(o4.maxX - i4.minX) \u003c 0.001 ? (r4 = o4.maxX, s3 = (Math.max(o4.minY, i4.minY) + Math.min(o4.maxY, i4.maxY)) / 2) : Math.abs(o4.minX - i4.maxX) \u003c 0.001 ? (r4 = o4.minX, s3 = (Math.max(o4.minY, i4.minY) + Math.min(o4.maxY, i4.maxY)) / 2) : Math.abs(o4.maxY - i4.minY) \u003c 0.001 ? (r4 = (Math.max(o4.minX, i4.minX) + Math.min(o4.maxX, i4.maxX)) / 2, s3 = o4.maxY) : (r4 = (Math.max(o4.minX, i4.minX) + Math.min(o4.maxX, i4.maxX)) / 2, s3 = o4.minY);\n const a4 = { portId: e37, region1: t3, region2: n3, d: { x: r4, y: s3 } };\n return t3.ports.push(a4), n3.ports.push(a4), a4;\n }, $2 = (e37, t3, n3, o4) =\u003e {\n if (o4 \u003c= 0)\n return [];\n if (o4 === 1)\n return [j2(e37, t3, n3)];\n const i4 = t3.d.bounds, r4 = n3.d.bounds, s3 = [];\n let a4, c4, l4, h3;\n Math.abs(i4.maxX - r4.minX) \u003c 0.001 ? (a4 = true, c4 = i4.maxX, l4 = Math.max(i4.minY, r4.minY), h3 = Math.min(i4.maxY, r4.maxY)) : Math.abs(i4.minX - r4.maxX) \u003c 0.001 ? (a4 = true, c4 = i4.minX, l4 = Math.max(i4.minY, r4.minY), h3 = Math.min(i4.maxY, r4.maxY)) : Math.abs(i4.maxY - r4.minY) \u003c 0.001 ? (a4 = false, c4 = i4.maxY, l4 = Math.max(i4.minX, r4.minX), h3 = Math.min(i4.maxX, r4.maxX)) : (a4 = false, c4 = i4.minY, l4 = Math.max(i4.minX, r4.minX), h3 = Math.min(i4.maxX, r4.maxX));\n for (let i5 = 0;i5 \u003c o4; i5++) {\n const r5 = l4 + (i5 + 0.5) / o4 * (h3 - l4), d3 = { portId: `${e37}:${i5}`, region1: t3, region2: n3, d: { x: a4 ? c4 : r5, y: a4 ? r5 : c4 } };\n t3.ports.push(d3), n3.ports.push(d3), s3.push(d3);\n }\n return s3;\n };\n for (let n3 = 0;n3 \u003c t2; n3++) {\n z2[n3] = [];\n for (let a4 = 0;a4 \u003c e36; a4++) {\n const c4 = `cell_${n3}_${a4}`, l4 = a4 * T2, h3 = -n3 * A2, d3 = l4 + x2, u3 = h3 + I2, p4 = l4 + x2, _3 = h3 + S2, y3 = l4 + x2, b3 = h3 + C, R3 = l4 + x2, E4 = h3 + P, Y3 = l4 + v2, X2 = h3 + P, H2 = l4 + v2, V2 = h3 + C, W2 = l4 + v2, G2 = h3 + S2, U2 = l4 + v2, Z2 = h3 + I2, q2 = (e37, t3, n4) =\u003e ({ minX: e37 - M, maxX: e37 + M, minY: t3 - n4, maxY: t3 + n4 }), J2 = q2(d3, u3, w), Q2 = q2(p4, _3, N), K2 = q2(y3, b3, N), ee2 = q2(R3, E4, w), te2 = q2(Y3, X2, w), ne2 = q2(H2, V2, N), oe2 = q2(W2, G2, N), ie2 = q2(U2, Z2, w), re2 = { minX: J2.maxX, maxX: ie2.minX, minY: J2.minY, maxY: ee2.maxY }, se2 = 0.3, ae2 = { minX: d3, maxX: U2, minY: u3 - se2 / 2, maxY: u3 + se2 / 2 }, ce2 = { minX: p4, maxX: W2, minY: _3 - se2 / 2, maxY: _3 + se2 / 2 }, le2 = { minX: y3, maxX: H2, minY: b3 - se2 / 2, maxY: b3 + se2 / 2 }, he2 = { minX: R3, maxX: Y3, minY: E4 - se2 / 2, maxY: E4 + se2 / 2 }, de2 = J2.minX, ue2 = ie2.maxX, pe2 = J2.minY, me2 = ee2.maxY, ge2 = F2(`${c4}:pad1`, J2, true), fe2 = F2(`${c4}:pad2`, Q2, true), _e2 = F2(`${c4}:pad3`, K2, true), ye2 = F2(`${c4}:pad4`, ee2, true), be2 = F2(`${c4}:pad5`, te2, true), xe2 = F2(`${c4}:pad6`, ne2, true), ve2 = F2(`${c4}:pad7`, oe2, true), Ie2 = F2(`${c4}:pad8`, ie2, true), Se2 = F2(`${c4}:underjumper`, re2, false), Ce2 = F2(`${c4}:throughjumper1`, ae2, false, true), Pe2 = F2(`${c4}:throughjumper2`, ce2, false, true), Me2 = F2(`${c4}:throughjumper3`, le2, false, true), we2 = F2(`${c4}:throughjumper4`, he2, false, true);\n g2.push(ge2, fe2, _e2, ye2, be2, xe2, ve2, Ie2, Se2, Ce2, Pe2, Me2, we2);\n const Ne2 = (d3 + U2) / 2, Re2 = (u3 + E4) / 2;\n B2.push({ center: { x: Ne2, y: Re2 }, orientation: \"vertical\", padRegions: [ge2, fe2, _e2, ye2, be2, xe2, ve2, Ie2] });\n let Te2 = null, Ee2 = null, Ae2 = null, Oe2 = null, ke2 = null, De2 = null;\n s2 \u0026\u0026 (Te2 = F2(`${c4}:L-BP12`, { minX: J2.minX, maxX: J2.maxX, minY: J2.maxY, maxY: Q2.minY }, false), Ee2 = F2(`${c4}:L-BP23`, { minX: Q2.minX, maxX: Q2.maxX, minY: Q2.maxY, maxY: K2.minY }, false), Ae2 = F2(`${c4}:L-BP34`, { minX: K2.minX, maxX: K2.maxX, minY: K2.maxY, maxY: ee2.minY }, false), Oe2 = F2(`${c4}:R-BP87`, { minX: ie2.minX, maxX: ie2.maxX, minY: ie2.maxY, maxY: oe2.minY }, false), ke2 = F2(`${c4}:R-BP76`, { minX: oe2.minX, maxX: oe2.maxX, minY: oe2.maxY, maxY: ne2.minY }, false), De2 = F2(`${c4}:R-BP65`, { minX: ne2.minX, maxX: ne2.maxX, minY: ne2.maxY, maxY: te2.minY }, false), g2.push(Te2, Ee2, Ae2, Oe2, ke2, De2));\n const Le2 = a4 === 0, ze2 = n3 === t2 - 1, Be2 = a4 === e36 - 1;\n let Fe2;\n if (Be2)\n Fe2 = ue2 + O2;\n else {\n Fe2 = (a4 + 1) * T2 + x2 - M;\n }\n let je = null;\n n3 === 0 \u0026\u0026 (je = F2(`${c4}:T`, { minX: Le2 ? de2 - O2 : de2, maxX: Fe2, minY: me2, maxY: me2 + k2 }, false), g2.push(je));\n let $e2 = null;\n $e2 = F2(`${c4}:B`, { minX: Le2 ? de2 - O2 : de2, maxX: Fe2, minY: pe2 - (ze2 ? k2 : o3), maxY: pe2 }, false), g2.push($e2);\n let Ye2 = null;\n Le2 \u0026\u0026 (Ye2 = F2(`${c4}:L`, { minX: de2 - O2, maxX: de2, minY: pe2, maxY: me2 }, false), g2.push(Ye2));\n const Xe2 = F2(`${c4}:R`, { minX: ue2, maxX: Fe2, minY: pe2, maxY: me2 }, false);\n if (g2.push(Xe2), z2[n3][a4] = { pad1: ge2, pad2: fe2, pad3: _e2, pad4: ye2, pad5: be2, pad6: xe2, pad7: ve2, pad8: Ie2, underjumper: Se2, throughjumper1: Ce2, throughjumper2: Pe2, throughjumper3: Me2, throughjumper4: we2, top: je, bottom: $e2, left: Ye2, right: Xe2, leftBP12: Te2, leftBP23: Ee2, leftBP34: Ae2, rightBP87: Oe2, rightBP76: ke2, rightBP65: De2 }, je)\n if (Ye2 \u0026\u0026 f2.push(...$2(`${c4}:T-L`, je, Ye2, D2)), f2.push(...$2(`${c4}:T-R`, je, Xe2, Be2 ? D2 : i3)), f2.push(j2(`${c4}:T-P4`, je, ye2)), f2.push(j2(`${c4}:T-P5`, je, be2)), s2) {\n const e37 = Se2.d.bounds, t3 = (e37.maxX - e37.minX) / (m2 + 1);\n for (let n4 = 1;n4 \u003c= m2; n4++) {\n const o4 = { portId: `${c4}:T-UJ${n4}`, region1: je, region2: Se2, d: { x: e37.minX + t3 * n4, y: e37.maxY } };\n je.ports.push(o4), Se2.ports.push(o4), f2.push(o4);\n }\n } else\n f2.push(j2(`${c4}:T-UJ`, je, Se2));\n if ($e2)\n if (Ye2 \u0026\u0026 f2.push(...$2(`${c4}:B-L`, $e2, Ye2, D2)), f2.push(...$2(`${c4}:B-R`, $e2, Xe2, Be2 ? D2 : i3)), f2.push(j2(`${c4}:B-P1`, $e2, ge2)), f2.push(j2(`${c4}:B-P8`, $e2, Ie2)), s2) {\n const e37 = Se2.d.bounds, t3 = (e37.maxX - e37.minX) / (m2 + 1);\n for (let n4 = 1;n4 \u003c= m2; n4++) {\n const o4 = { portId: `${c4}:B-UJ${n4}`, region1: $e2, region2: Se2, d: { x: e37.minX + t3 * n4, y: e37.minY } };\n $e2.ports.push(o4), Se2.ports.push(o4), f2.push(o4);\n }\n } else\n f2.push(j2(`${c4}:B-UJ`, $e2, Se2));\n Ye2 \u0026\u0026 (f2.push(j2(`${c4}:L-P1`, Ye2, ge2)), f2.push(j2(`${c4}:L-P2`, Ye2, fe2)), f2.push(j2(`${c4}:L-P3`, Ye2, _e2)), f2.push(j2(`${c4}:L-P4`, Ye2, ye2))), f2.push(j2(`${c4}:R-P5`, Xe2, be2)), f2.push(j2(`${c4}:R-P6`, Xe2, xe2)), f2.push(j2(`${c4}:R-P7`, Xe2, ve2)), f2.push(j2(`${c4}:R-P8`, Xe2, Ie2)), s2 \u0026\u0026 (Ye2 \u0026\u0026 (f2.push(j2(`${c4}:L-BP12`, Ye2, Te2)), f2.push(j2(`${c4}:L-BP23`, Ye2, Ee2)), f2.push(j2(`${c4}:L-BP34`, Ye2, Ae2))), f2.push(j2(`${c4}:UJ-LBP12`, Te2, Se2)), f2.push(j2(`${c4}:UJ-LBP23`, Ee2, Se2)), f2.push(j2(`${c4}:UJ-LBP34`, Ae2, Se2)), f2.push(j2(`${c4}:R-BP87`, Xe2, Oe2)), f2.push(j2(`${c4}:R-BP76`, Xe2, ke2)), f2.push(j2(`${c4}:R-BP65`, Xe2, De2)), f2.push(j2(`${c4}:UJ-RBP87`, Oe2, Se2)), f2.push(j2(`${c4}:UJ-RBP76`, ke2, Se2)), f2.push(j2(`${c4}:UJ-RBP65`, De2, Se2)));\n const He2 = { portId: `${c4}:TJ1-P1`, region1: Ce2, region2: ge2, d: { x: d3, y: u3 } };\n Ce2.ports.push(He2), ge2.ports.push(He2), f2.push(He2);\n const Ve2 = { portId: `${c4}:TJ1-P8`, region1: Ce2, region2: Ie2, d: { x: U2, y: Z2 } };\n Ce2.ports.push(Ve2), Ie2.ports.push(Ve2), f2.push(Ve2);\n const We2 = { portId: `${c4}:TJ2-P2`, region1: Pe2, region2: fe2, d: { x: p4, y: _3 } };\n Pe2.ports.push(We2), fe2.ports.push(We2), f2.push(We2);\n const Ge2 = { portId: `${c4}:TJ2-P7`, region1: Pe2, region2: ve2, d: { x: W2, y: G2 } };\n Pe2.ports.push(Ge2), ve2.ports.push(Ge2), f2.push(Ge2);\n const Ue2 = { portId: `${c4}:TJ3-P3`, region1: Me2, region2: _e2, d: { x: y3, y: b3 } };\n Me2.ports.push(Ue2), _e2.ports.push(Ue2), f2.push(Ue2);\n const Ze2 = { portId: `${c4}:TJ3-P6`, region1: Me2, region2: xe2, d: { x: H2, y: V2 } };\n Me2.ports.push(Ze2), xe2.ports.push(Ze2), f2.push(Ze2);\n const qe2 = { portId: `${c4}:TJ4-P4`, region1: we2, region2: ye2, d: { x: R3, y: E4 } };\n we2.ports.push(qe2), ye2.ports.push(qe2), f2.push(qe2);\n const Je2 = { portId: `${c4}:TJ4-P5`, region1: we2, region2: be2, d: { x: Y3, y: X2 } };\n if (we2.ports.push(Je2), be2.ports.push(Je2), f2.push(Je2), a4 \u003e 0) {\n const e37 = z2[n3][a4 - 1];\n f2.push(j2(`cell_${n3}_${a4 - 1}-\u003ecell_${n3}_${a4}:R-P1`, e37.right, ge2)), f2.push(j2(`cell_${n3}_${a4 - 1}-\u003ecell_${n3}_${a4}:R-P2`, e37.right, fe2)), f2.push(j2(`cell_${n3}_${a4 - 1}-\u003ecell_${n3}_${a4}:R-P3`, e37.right, _e2)), f2.push(j2(`cell_${n3}_${a4 - 1}-\u003ecell_${n3}_${a4}:R-P4`, e37.right, ye2)), s2 \u0026\u0026 (f2.push(j2(`cell_${n3}_${a4 - 1}-\u003ecell_${n3}_${a4}:R-LBP12`, e37.right, Te2)), f2.push(j2(`cell_${n3}_${a4 - 1}-\u003ecell_${n3}_${a4}:R-LBP23`, e37.right, Ee2)), f2.push(j2(`cell_${n3}_${a4 - 1}-\u003ecell_${n3}_${a4}:R-LBP34`, e37.right, Ae2))), je \u0026\u0026 e37.top \u0026\u0026 f2.push(...$2(`cell_${n3}_${a4 - 1}-\u003ecell_${n3}_${a4}:T-T`, e37.top, je, L2)), $e2 \u0026\u0026 e37.bottom \u0026\u0026 f2.push(...$2(`cell_${n3}_${a4 - 1}-\u003ecell_${n3}_${a4}:B-B`, e37.bottom, $e2, ze2 ? L2 : r3));\n }\n if (n3 \u003e 0) {\n const e37 = z2[n3 - 1][a4];\n if (Ye2 \u0026\u0026 f2.push(...$2(`cell_${n3 - 1}_${a4}-\u003ecell_${n3}_${a4}:B-L`, e37.bottom, Ye2, D2)), f2.push(j2(`cell_${n3 - 1}_${a4}-\u003ecell_${n3}_${a4}:B-P4`, e37.bottom, ye2)), s2) {\n const t3 = Se2.d.bounds, o4 = (t3.maxX - t3.minX) / (m2 + 1);\n for (let i4 = 1;i4 \u003c= m2; i4++) {\n const r4 = t3.minX + o4 * i4, s3 = { portId: `cell_${n3 - 1}_${a4}-\u003ecell_${n3}_${a4}:B-UJ${i4}`, region1: e37.bottom, region2: Se2, d: { x: r4, y: t3.maxY } };\n e37.bottom.ports.push(s3), Se2.ports.push(s3), f2.push(s3);\n }\n } else\n f2.push(j2(`cell_${n3 - 1}_${a4}-\u003ecell_${n3}_${a4}:B-UJ`, e37.bottom, Se2));\n f2.push(j2(`cell_${n3 - 1}_${a4}-\u003ecell_${n3}_${a4}:B-P5`, e37.bottom, be2)), f2.push(...$2(`cell_${n3 - 1}_${a4}-\u003ecell_${n3}_${a4}:B-R`, e37.bottom, Xe2, Be2 ? D2 : i3));\n }\n }\n }\n let Y2 = { regions: g2, ports: f2, jumperLocations: B2 };\n const X = d2 === \"horizontal\";\n if (X || u2 !== undefined || p3 !== undefined) {\n const e37 = WY(Y2.regions), t3 = hX(e37), n3 = [];\n let o4;\n o4 = u2 || (p3 ? hX(p3) : t3), n3.push(iX(o4.x, o4.y)), X \u0026\u0026 n3.push(function(e38, t4, n4) {\n const o5 = sX(e38), i5 = aX(e38), r4 = { a: o5, c: -i5, e: 0, b: i5, d: o5, f: 0 };\n return oX(t4) || oX(n4) ? r4 : rX([iX(t4, n4), r4, iX(-t4, -n4)]);\n }(-Math.PI / 2)), n3.push(iX(-t3.x, -t3.y));\n const i4 = function(...e38) {\n return rX(...e38);\n }(...n3);\n Y2 = dX(Y2, i4);\n }\n return Y2;\n};\nvar SX = true;\nvar CX = { CCW: -1, CW: 1, NOT_ORIENTABLE: 0 };\nvar PX = 2 * Math.PI;\nvar MX = Object.freeze({ __proto__: null, BOUNDARY: 2, CCW: SX, CONTAINS: 3, CW: false, END_VERTEX: 2, INSIDE: 1, INTERLACE: 4, NOT_VERTEX: 0, ORIENTATION: CX, OUTSIDE: 0, OVERLAP_OPPOSITE: 2, OVERLAP_SAME: 1, PIx2: PX, START_VERTEX: 1 });\nvar wX = 0.000001;\nfunction NX(e36) {\n wX = e36;\n}\nfunction RX() {\n return wX;\n}\nfunction TX(e36) {\n return e36 \u003c wX \u0026\u0026 e36 \u003e -wX;\n}\nfunction EX(e36, t2) {\n return e36 - t2 \u003c wX \u0026\u0026 e36 - t2 \u003e -wX;\n}\nfunction AX(e36, t2) {\n return e36 - t2 \u003e wX;\n}\nfunction OX(e36, t2) {\n return e36 - t2 \u003c -wX;\n}\nvar kX = { Utils: Object.freeze({ __proto__: null, DECIMALS: 3, EQ: EX, EQ_0: TX, GE: function(e36, t2) {\n return e36 - t2 \u003e -wX;\n}, GT: AX, LE: function(e36, t2) {\n return e36 - t2 \u003c wX;\n}, LT: OX, getTolerance: RX, setTolerance: NX }), Errors: undefined, Matrix: undefined, Planar_set: undefined, Point: undefined, Vector: undefined, Line: undefined, Circle: undefined, Segment: undefined, Arc: undefined, Box: undefined, Edge: undefined, Face: undefined, Ray: undefined, Ray_shooting: undefined, Multiline: undefined, Polygon: undefined, Distance: undefined, Inversion: undefined };\nfor (let e36 in MX)\n kX[e36] = MX[e36];\nObject.defineProperty(kX, \"DP_TOL\", { get: function() {\n return RX();\n}, set: function(e36) {\n NX(e36);\n} });\nvar DX = class {\n static get ILLEGAL_PARAMETERS() {\n return new ReferenceError(\"Illegal Parameters\");\n }\n static get ZERO_DIVISION() {\n return new Error(\"Zero division\");\n }\n static get UNRESOLVED_BOUNDARY_CONFLICT() {\n return new Error(\"Unresolved boundary conflict in boolean operation\");\n }\n static get INFINITE_LOOP() {\n return new Error(\"Infinite loop\");\n }\n static get CANNOT_COMPLETE_BOOLEAN_OPERATION() {\n return new Error(\"Cannot complete boolean operation\");\n }\n static get CANNOT_INVOKE_ABSTRACT_METHOD() {\n return new Error(\"Abstract method cannot be invoked\");\n }\n static get OPERATION_IS_NOT_SUPPORTED() {\n return new Error(\"Operation is not supported\");\n }\n static get UNSUPPORTED_SHAPE_TYPE() {\n return new Error(\"Unsupported shape type\");\n }\n};\nkX.Errors = DX;\nvar LX = class {\n constructor(e36, t2) {\n this.first = e36, this.last = t2 || this.first;\n }\n [Symbol.iterator]() {\n let e36;\n return { next: () =\u003e (e36 = e36 ? e36.next : this.first, { value: e36, done: e36 === undefined }) };\n }\n get size() {\n let e36 = 0;\n for (let t2 of this)\n e36++;\n return e36;\n }\n toArray(e36 = undefined, t2 = undefined) {\n let n2 = [], o3 = e36 || this.first, i3 = t2 || this.last, r3 = o3;\n if (r3 === undefined)\n return n2;\n do {\n n2.push(r3), r3 = r3.next;\n } while (r3 !== i3.next);\n return n2;\n }\n append(e36) {\n return this.isEmpty() ? this.first = e36 : (e36.prev = this.last, this.last.next = e36), this.last = e36, this.last.next = undefined, this.first.prev = undefined, this;\n }\n insert(e36, t2) {\n if (this.isEmpty())\n this.first = e36, this.last = e36;\n else if (t2 == null)\n e36.next = this.first, this.first.prev = e36, this.first = e36;\n else {\n let n2 = t2.next;\n t2.next = e36, n2 \u0026\u0026 (n2.prev = e36), e36.prev = t2, e36.next = n2, this.last === t2 \u0026\u0026 (this.last = e36);\n }\n return this.last.next = undefined, this.first.prev = undefined, this;\n }\n remove(e36) {\n return e36 === this.first \u0026\u0026 e36 === this.last ? (this.first = undefined, this.last = undefined) : (e36.prev \u0026\u0026 (e36.prev.next = e36.next), e36.next \u0026\u0026 (e36.next.prev = e36.prev), e36 === this.first \u0026\u0026 (this.first = e36.next), e36 === this.last \u0026\u0026 (this.last = e36.prev)), this;\n }\n isEmpty() {\n return this.first === undefined;\n }\n static testInfiniteLoop(e36) {\n let t2 = e36, n2 = e36;\n do {\n if (t2 != e36 \u0026\u0026 t2 === n2)\n throw DX.INFINITE_LOOP;\n t2 = t2.next, n2 = n2.next.next;\n } while (t2 != e36);\n }\n};\nvar zX = { stroke: \"black\" };\nvar BX = class {\n constructor(e36 = zX) {\n for (const t2 in e36)\n this[t2] = e36[t2];\n this.stroke = e36.stroke ?? zX.stroke;\n }\n toAttributesString() {\n return Object.keys(this).reduce((e36, t2) =\u003e e36 + (this[t2] !== undefined ? this.toAttrString(t2, this[t2]) : \"\"), \"\");\n }\n toAttrString(e36, t2) {\n const n2 = e36 === \"className\" ? \"class\" : this.convertCamelToKebabCase(e36);\n return t2 === null ? `${n2} ` : `${n2}=\"${t2.toString()}\" `;\n }\n convertCamelToKebabCase(e36) {\n return e36.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g).join(\"-\").toLowerCase();\n }\n};\nfunction FX(e36) {\n return new BX(e36).toAttributesString();\n}\nfunction jX(e36, t2) {\n let n2 = [], [o3, i3, r3] = e36.standard, [s2, a3, c3] = t2.standard, l3 = o3 * a3 - i3 * s2, h2 = r3 * a3 - i3 * c3, d2 = o3 * c3 - r3 * s2;\n if (!kX.Utils.EQ_0(l3)) {\n let e37, t3;\n i3 === 0 ? (e37 = r3 / o3, t3 = d2 / l3) : a3 === 0 ? (e37 = c3 / s2, t3 = d2 / l3) : o3 === 0 ? (e37 = h2 / l3, t3 = r3 / i3) : s2 === 0 ? (e37 = h2 / l3, t3 = c3 / a3) : (e37 = h2 / l3, t3 = d2 / l3), n2.push(new kX.Point(e37, t3));\n }\n return n2;\n}\nfunction $X(e36, t2) {\n let n2 = [], o3 = t2.pc.projectionOn(e36), i3 = t2.pc.distanceTo(o3)[0];\n if (kX.Utils.EQ(i3, t2.r))\n n2.push(o3);\n else if (kX.Utils.LT(i3, t2.r)) {\n let r3, s2, a3 = Math.sqrt(t2.r * t2.r - i3 * i3);\n r3 = e36.norm.rotate90CCW().multiply(a3), s2 = o3.translate(r3), n2.push(s2), r3 = e36.norm.rotate90CW().multiply(a3), s2 = o3.translate(r3), n2.push(s2);\n }\n return n2;\n}\nfunction YX(e36, t2) {\n let n2 = [];\n for (let o3 of t2.toSegments()) {\n let t3 = HX(o3, e36);\n for (let e37 of t3)\n cH(e37, n2) || n2.push(e37);\n }\n return n2;\n}\nfunction XX(e36, t2) {\n let n2 = [];\n if (YX(e36, t2.box).length === 0)\n return n2;\n let o3 = $X(e36, new kX.Circle(t2.pc, t2.r));\n for (let e37 of o3)\n e37.on(t2) \u0026\u0026 n2.push(e37);\n return n2;\n}\nfunction HX(e36, t2) {\n let n2 = [];\n return e36.ps.on(t2) \u0026\u0026 n2.push(e36.ps), e36.pe.on(t2) \u0026\u0026 !e36.isZeroLength() \u0026\u0026 n2.push(e36.pe), n2.length \u003e 0 || e36.isZeroLength() || e36.ps.leftTo(t2) \u0026\u0026 e36.pe.leftTo(t2) || !e36.ps.leftTo(t2) \u0026\u0026 !e36.pe.leftTo(t2) ? n2 : jX(new kX.Line(e36.ps, e36.pe), t2);\n}\nfunction VX(e36, t2) {\n let n2 = [];\n if (e36.isZeroLength())\n return e36.ps.on(t2) \u0026\u0026 n2.push(e36.ps), n2;\n if (t2.isZeroLength())\n return t2.ps.on(e36) \u0026\u0026 n2.push(t2.ps), n2;\n let o3 = new kX.Line(e36.ps, e36.pe), i3 = new kX.Line(t2.ps, t2.pe);\n if (o3.incidentTo(i3))\n e36.ps.on(t2) \u0026\u0026 n2.push(e36.ps), e36.pe.on(t2) \u0026\u0026 n2.push(e36.pe), !t2.ps.on(e36) || t2.ps.equalTo(e36.ps) || t2.ps.equalTo(e36.pe) || n2.push(t2.ps), !t2.pe.on(e36) || t2.pe.equalTo(e36.ps) || t2.pe.equalTo(e36.pe) || n2.push(t2.pe);\n else {\n let r3 = jX(o3, i3);\n r3.length \u003e 0 \u0026\u0026 WX(r3[0], e36) \u0026\u0026 WX(r3[0], t2) \u0026\u0026 n2.push(r3[0]);\n }\n return n2;\n}\nfunction WX(e36, t2) {\n const n2 = t2.box;\n return kX.Utils.LE(e36.x, n2.xmax) \u0026\u0026 kX.Utils.GE(e36.x, n2.xmin) \u0026\u0026 kX.Utils.LE(e36.y, n2.ymax) \u0026\u0026 kX.Utils.GE(e36.y, n2.ymin);\n}\nfunction GX(e36, t2) {\n let n2 = [];\n if (e36.isZeroLength()) {\n let [o4, i3] = e36.ps.distanceTo(t2.pc);\n return kX.Utils.EQ(o4, t2.r) \u0026\u0026 n2.push(e36.ps), n2;\n }\n let o3 = $X(new kX.Line(e36.ps, e36.pe), t2);\n for (let t3 of o3)\n t3.on(e36) \u0026\u0026 n2.push(t3);\n return n2;\n}\nfunction UX(e36, t2) {\n let n2 = [];\n if (e36.isZeroLength())\n return e36.ps.on(t2) \u0026\u0026 n2.push(e36.ps), n2;\n let o3 = $X(new kX.Line(e36.ps, e36.pe), new kX.Circle(t2.pc, t2.r));\n for (let i3 of o3)\n i3.on(e36) \u0026\u0026 i3.on(t2) \u0026\u0026 n2.push(i3);\n return n2;\n}\nfunction ZX(e36, t2) {\n let n2 = [], o3 = new kX.Vector(e36.pc, t2.pc), i3 = e36.r, r3 = t2.r;\n if (kX.Utils.EQ_0(i3) || kX.Utils.EQ_0(r3))\n return n2;\n if (kX.Utils.EQ_0(o3.x) \u0026\u0026 kX.Utils.EQ_0(o3.y) \u0026\u0026 kX.Utils.EQ(i3, r3))\n return n2.push(e36.pc.translate(-i3, 0)), n2;\n let s2, a3 = e36.pc.distanceTo(t2.pc)[0];\n if (kX.Utils.GT(a3, i3 + r3))\n return n2;\n if (kX.Utils.LT(a3, Math.abs(i3 - r3)))\n return n2;\n if (o3.x /= a3, o3.y /= a3, kX.Utils.EQ(a3, i3 + r3) || kX.Utils.EQ(a3, Math.abs(i3 - r3)))\n return s2 = e36.pc.translate(i3 * o3.x, i3 * o3.y), n2.push(s2), n2;\n let c3 = i3 * i3 / (2 * a3) - r3 * r3 / (2 * a3) + a3 / 2, l3 = e36.pc.translate(c3 * o3.x, c3 * o3.y), h2 = Math.sqrt(i3 * i3 - c3 * c3);\n return s2 = l3.translate(o3.rotate90CCW().multiply(h2)), n2.push(s2), s2 = l3.translate(o3.rotate90CW().multiply(h2)), n2.push(s2), n2;\n}\nfunction qX(e36, t2) {\n let n2 = [];\n if (e36.pc.equalTo(t2.pc) \u0026\u0026 kX.Utils.EQ(e36.r, t2.r)) {\n let o4;\n return o4 = e36.start, o4.on(t2) \u0026\u0026 n2.push(o4), o4 = e36.end, o4.on(t2) \u0026\u0026 n2.push(o4), o4 = t2.start, o4.on(e36) \u0026\u0026 n2.push(o4), o4 = t2.end, o4.on(e36) \u0026\u0026 n2.push(o4), n2;\n }\n let o3 = new kX.Circle(e36.pc, e36.r), i3 = new kX.Circle(t2.pc, t2.r), r3 = o3.intersect(i3);\n for (let o4 of r3)\n o4.on(e36) \u0026\u0026 o4.on(t2) \u0026\u0026 n2.push(o4);\n return n2;\n}\nfunction JX(e36, t2) {\n let n2 = [];\n if (t2.pc.equalTo(e36.pc) \u0026\u0026 kX.Utils.EQ(t2.r, e36.r))\n return n2.push(e36.start), n2.push(e36.end), n2;\n let o3 = ZX(t2, new kX.Circle(e36.pc, e36.r));\n for (let t3 of o3)\n t3.on(e36) \u0026\u0026 n2.push(t3);\n return n2;\n}\nfunction QX(e36, t2) {\n return e36.isSegment ? VX(e36.shape, t2) : UX(t2, e36.shape);\n}\nfunction KX(e36, t2) {\n return e36.isSegment ? UX(e36.shape, t2) : qX(e36.shape, t2);\n}\nfunction eH(e36, t2) {\n return e36.isSegment ? HX(e36.shape, t2) : XX(t2, e36.shape);\n}\nfunction tH(e36, t2) {\n return e36.isSegment ? GX(e36.shape, t2) : JX(e36.shape, t2);\n}\nfunction nH(e36, t2) {\n let n2 = [];\n for (let o3 of t2.edges)\n for (let t3 of QX(o3, e36))\n n2.push(t3);\n return n2;\n}\nfunction oH(e36, t2) {\n let n2 = [];\n for (let o3 of t2.edges)\n for (let t3 of KX(o3, e36))\n n2.push(t3);\n return n2;\n}\nfunction iH(e36, t2) {\n let n2 = [];\n if (t2.isEmpty())\n return n2;\n for (let o3 of t2.edges)\n for (let t3 of eH(o3, e36))\n cH(t3, n2) || n2.push(t3);\n return e36.sortPoints(n2);\n}\nfunction rH(e36, t2) {\n let n2 = [];\n if (t2.isEmpty())\n return n2;\n for (let o3 of t2.edges)\n for (let t3 of tH(o3, e36))\n n2.push(t3);\n return n2;\n}\nfunction sH(e36, t2) {\n return e36.isSegment ? QX(t2, e36.shape) : e36.isArc ? KX(t2, e36.shape) : e36.isLine ? eH(t2, e36.shape) : e36.isRay ? (n2 = t2, o3 = e36.shape, n2.isSegment ? hH(o3, n2.shape) : dH(o3, n2.shape)) : [];\n var n2, o3;\n}\nfunction aH(e36, t2) {\n let n2 = [];\n if (t2.isEmpty() || e36.shape.box.not_intersect(t2.box))\n return n2;\n let o3 = t2.edges.search(e36.shape.box);\n for (let t3 of o3)\n n2 = [...n2, ...sH(e36, t3)];\n return n2;\n}\nfunction cH(e36, t2) {\n return t2.some((t3) =\u003e t3.equalTo(e36));\n}\nfunction lH(e36) {\n return new kX.Line(e36.start, e36.norm);\n}\nfunction hH(e36, t2) {\n return HX(t2, lH(e36)).filter((t3) =\u003e e36.contains(t3));\n}\nfunction dH(e36, t2) {\n return XX(lH(e36), t2).filter((t3) =\u003e e36.contains(t3));\n}\nfunction uH(e36, t2) {\n return $X(lH(e36), t2).filter((t3) =\u003e e36.contains(t3));\n}\nfunction pH(e36, t2) {\n return jX(lH(e36), t2).filter((t3) =\u003e e36.contains(t3));\n}\nfunction mH(e36, t2) {\n return iH(lH(e36), t2).filter((t3) =\u003e e36.contains(t3));\n}\nfunction gH(e36, t2) {\n if (e36.intersect \u0026\u0026 e36.intersect instanceof Function)\n return e36.intersect(t2);\n throw DX.UNSUPPORTED_SHAPE_TYPE;\n}\nfunction fH(e36, t2) {\n let n2 = [];\n for (let o3 of t2)\n n2 = [...n2, ...gH(e36, o3.shape)];\n return n2;\n}\nvar _H = class e36 extends LX {\n constructor(...e37) {\n if (super(), this.isInfinite = false, e37.length === 1 \u0026\u0026 e37[0] instanceof Array \u0026\u0026 e37[0].length \u003e 0) {\n const t2 = e37[0], n2 = t2.length, o3 = (e38) =\u003e e38 instanceof kX.Segment || e38 instanceof kX.Arc || e38 instanceof kX.Ray, i3 = (e38) =\u003e e38 instanceof kX.Segment || e38 instanceof kX.Arc;\n if (!(n2 === 1 \u0026\u0026 ((e38) =\u003e e38 instanceof kX.Segment || e38 instanceof kX.Arc || e38 instanceof kX.Ray || e38 instanceof kX.Line)(t2[0]) || n2 \u003e 1 \u0026\u0026 o3(t2[0]) \u0026\u0026 o3(t2[n2 - 1]) \u0026\u0026 t2.slice(1, n2 - 1).every(i3)))\n throw kX.Errors.ILLEGAL_PARAMETERS;\n this.isInfinite = t2.some((e38) =\u003e e38 instanceof kX.Ray || e38 instanceof kX.Line);\n for (let e38 of t2) {\n let t3 = new kX.Edge(e38);\n this.append(t3);\n }\n this.setArcLength();\n }\n }\n get edges() {\n return [...this];\n }\n get box() {\n return this.edges.reduce((e37, t2) =\u003e e37.merge(t2.box), new kX.Box);\n }\n get vertices() {\n let e37 = this.edges.map((e38) =\u003e e38.start);\n return e37.push(this.last.end), e37;\n }\n get length() {\n if (this.isEmpty())\n return 0;\n if (this.isInfinite)\n return Number.POSITIVE_INFINITY;\n let e37 = 0;\n for (let t2 of this)\n e37 += t2.length;\n return e37;\n }\n clone() {\n return new e36(this.toShapes());\n }\n setArcLength() {\n for (let e37 of this)\n this.setOneEdgeArcLength(e37);\n }\n setOneEdgeArcLength(e37) {\n e37 === this.first ? e37.arc_length = 0 : e37.arc_length = e37.prev.arc_length + e37.prev.length;\n }\n pointAtLength(e37) {\n if (e37 \u003e this.length || e37 \u003c 0)\n return null;\n if (this.isInfinite)\n return null;\n let t2 = null;\n for (let n2 of this)\n if (e37 \u003e= n2.arc_length \u0026\u0026 (n2 === this.last || e37 \u003c n2.next.arc_length)) {\n t2 = n2.pointAtLength(e37 - n2.arc_length);\n break;\n }\n return t2;\n }\n addVertex(e37, t2) {\n let n2 = t2.shape.split(e37);\n if (n2[0] === null)\n return t2.prev;\n if (n2[1] === null)\n return t2;\n let o3 = new kX.Edge(n2[0]), i3 = t2.prev;\n return this.insert(o3, i3), t2.shape = n2[1], o3;\n }\n getChain(e37, t2) {\n let n2 = [];\n for (let o3 = e37;o3 !== t2.next; o3 = o3.next)\n n2.push(o3);\n return n2;\n }\n split(e37) {\n for (let t2 of e37) {\n let e38 = this.findEdgeByPoint(t2);\n this.addVertex(t2, e38);\n }\n return this;\n }\n findEdgeByPoint(e37) {\n let t2;\n for (let n2 of this)\n if (n2.shape.contains(e37)) {\n t2 = n2;\n break;\n }\n return t2;\n }\n distanceTo(e37) {\n if (e37 instanceof Point) {\n const [t2, n2] = kX.Distance.shape2multiline(e37, this);\n return [t2, n2.reverse()];\n }\n if (e37 instanceof kX.Line) {\n const [t2, n2] = kX.Distance.shape2multiline(e37, this);\n return [t2, n2.reverse()];\n }\n if (e37 instanceof kX.Circle) {\n const [t2, n2] = kX.Distance.shape2multiline(e37, this);\n return [t2, n2.reverse()];\n }\n if (e37 instanceof kX.Segment) {\n const [t2, n2] = kX.Distance.shape2multiline(e37, this);\n return [t2, n2.reverse()];\n }\n if (e37 instanceof kX.Arc) {\n const [t2, n2] = kX.Distance.shape2multiline(e37, this);\n return [t2, n2.reverse()];\n }\n if (e37 instanceof kX.Multiline)\n return kX.Distance.multiline2multiline(this, e37);\n throw kX.Errors.UNSUPPORTED_SHAPE_TYPE;\n }\n intersect(e37) {\n return e37 instanceof kX.Multiline ? function(e38, t2) {\n let n2 = [];\n for (let o3 of e38)\n for (let e39 of t2)\n n2 = [...n2, ...gH(o3.shape, e39.shape)];\n return n2;\n }(this, e37) : fH(e37, this);\n }\n contains(e37) {\n if (e37 instanceof kX.Point)\n return this.edges.some((t2) =\u003e t2.shape.contains(e37));\n throw kX.Errors.UNSUPPORTED_SHAPE_TYPE;\n }\n translate(t2) {\n return new e36(this.edges.map((e37) =\u003e e37.shape.translate(t2)));\n }\n rotate(t2 = 0, n2 = new kX.Point) {\n return new e36(this.edges.map((e37) =\u003e e37.shape.rotate(t2, n2)));\n }\n transform(t2 = new kX.Matrix) {\n return new e36(this.edges.map((e37) =\u003e e37.shape.transform(t2)));\n }\n toShapes() {\n return this.edges.map((e37) =\u003e e37.shape.clone());\n }\n toJSON() {\n return this.edges.map((e37) =\u003e e37.toJSON());\n }\n svgPoints() {\n return this.vertices.map((e37) =\u003e `${e37.x},${e37.y}`).join(\" \");\n }\n dpath() {\n let e37 = `M${this.first.start.x},${this.first.start.y}`;\n for (let t2 of this)\n e37 += t2.svg();\n return e37;\n }\n svg(e37 = {}) {\n let t2 = `\n\u003cpath ${FX({ fill: \"none\", ...e37 })} d=\"`;\n t2 += `\nM${this.first.start.x},${this.first.start.y}`;\n for (let e38 of this)\n t2 += e38.svg();\n return t2 += `\" \u003e\n\u003c/path\u003e`, t2;\n }\n};\nkX.Multiline = _H;\nfunction yH(e37, t2, n2) {\n let o3 = n2.length, i3 = e37.shape.split(t2);\n if (i3.length === 0)\n return;\n let r3 = 0;\n r3 = i3[0] === null ? 0 : i3[1] === null ? e37.shape.length : i3[0].length;\n let s2, a3 = 0;\n EX(r3, 0) \u0026\u0026 (a3 |= 1), EX(r3, e37.shape.length) \u0026\u0026 (a3 |= 2), s2 = r3 === 1 / 0 ? i3[0].coord(t2) : 2 \u0026 a3 \u0026\u0026 e37.next \u0026\u0026 e37.next.arc_length === 0 ? 0 : e37.arc_length + r3, n2.push({ id: o3, pt: t2, arc_length: s2, edge_before: e37, edge_after: undefined, face: e37.face, is_vertex: a3 });\n}\nfunction bH(e37) {\n e37.int_points1_sorted = xH(e37.int_points1), e37.int_points2_sorted = xH(e37.int_points2);\n}\nfunction xH(e37) {\n let t2 = new Map, n2 = 0;\n for (let o3 of e37)\n t2.has(o3.face) || (t2.set(o3.face, n2), n2++);\n for (let n3 of e37)\n n3.faceId = t2.get(n3.face);\n return e37.slice().sort(vH);\n}\nfunction vH(e37, t2) {\n return e37.faceId \u003c t2.faceId ? -1 : e37.faceId \u003e t2.faceId ? 1 : e37.arc_length \u003c t2.arc_length ? -1 : e37.arc_length \u003e t2.arc_length ? 1 : 0;\n}\nfunction IH(e37) {\n if (e37.int_points1.length \u003c 2)\n return;\n let t2, n2, o3, i3, r3 = false;\n for (let s2 = 0;s2 \u003c e37.int_points1_sorted.length; s2++)\n if (e37.int_points1_sorted[s2].id !== -1) {\n t2 = e37.int_points1_sorted[s2], n2 = e37.int_points2[t2.id];\n for (let a3 = s2 + 1;a3 \u003c e37.int_points1_sorted.length \u0026\u0026 (o3 = e37.int_points1_sorted[a3], EX(o3.arc_length, t2.arc_length)); a3++)\n o3.id !== -1 \u0026\u0026 (i3 = e37.int_points2[o3.id], i3.id !== -1 \u0026\u0026 o3.edge_before === t2.edge_before \u0026\u0026 o3.edge_after === t2.edge_after \u0026\u0026 i3.edge_before === n2.edge_before \u0026\u0026 i3.edge_after === n2.edge_after \u0026\u0026 (o3.id = -1, i3.id = -1, r3 = true));\n }\n n2 = e37.int_points2_sorted[0], t2 = e37.int_points1[n2.id];\n for (let o4 = 1;o4 \u003c e37.int_points2_sorted.length; o4++) {\n let i4 = e37.int_points2_sorted[o4];\n if (i4.id === -1)\n continue;\n if (n2.id === -1 || !EX(i4.arc_length, n2.arc_length)) {\n n2 = i4, t2 = e37.int_points1[n2.id];\n continue;\n }\n let s2 = e37.int_points1[i4.id];\n s2.edge_before === t2.edge_before \u0026\u0026 s2.edge_after === t2.edge_after \u0026\u0026 i4.edge_before === n2.edge_before \u0026\u0026 i4.edge_after === n2.edge_after \u0026\u0026 (s2.id = -1, i4.id = -1, r3 = true);\n }\n r3 \u0026\u0026 (e37.int_points1 = e37.int_points1.filter((e38) =\u003e e38.id \u003e= 0), e37.int_points2 = e37.int_points2.filter((e38) =\u003e e38.id \u003e= 0), e37.int_points1.forEach((e38, t3) =\u003e e38.id = t3), e37.int_points2.forEach((e38, t3) =\u003e e38.id = t3));\n}\nfunction SH(e37) {\n for (let t2 of e37)\n t2.edge_before \u0026\u0026 (t2.edge_before.bvStart = undefined, t2.edge_before.bvEnd = undefined, t2.edge_before.bv = undefined, t2.edge_before.overlap = undefined), t2.edge_after \u0026\u0026 (t2.edge_after.bvStart = undefined, t2.edge_after.bvEnd = undefined, t2.edge_after.bv = undefined, t2.edge_after.overlap = undefined);\n for (let t2 of e37)\n t2.edge_before \u0026\u0026 (t2.edge_before.bvEnd = 2), t2.edge_after \u0026\u0026 (t2.edge_after.bvStart = 2);\n}\nfunction CH(e37, t2) {\n for (let n2 of e37)\n n2.edge_before \u0026\u0026 n2.edge_before.setInclusion(t2), n2.edge_after \u0026\u0026 n2.edge_after.setInclusion(t2);\n}\nfunction PH(e37, t2, n2) {\n let o3, i3, r3 = 1;\n if (e37.length === 1)\n return 1;\n o3 = e37[t2];\n for (let s2 = t2 + 1;s2 \u003c e37.length \u0026\u0026 o3.face === n2 \u0026\u0026 (i3 = e37[s2], i3.pt.equalTo(o3.pt) \u0026\u0026 i3.edge_before === o3.edge_before \u0026\u0026 i3.edge_after === o3.edge_after); s2++)\n r3++;\n return r3;\n}\nfunction MH(e37, t2) {\n if (t2) {\n for (let n2 of t2) {\n let t3 = n2.edge_before;\n if (n2.is_vertex = 0, t3.shape.start \u0026\u0026 t3.shape.start.equalTo(n2.pt) \u0026\u0026 (n2.is_vertex |= 1), t3.shape.end \u0026\u0026 t3.shape.end.equalTo(n2.pt) \u0026\u0026 (n2.is_vertex |= 2), 1 \u0026 n2.is_vertex) {\n n2.edge_before = t3.prev, t3.prev \u0026\u0026 (n2.is_vertex = 2);\n continue;\n }\n if (2 \u0026 n2.is_vertex)\n continue;\n let o3 = e37.addVertex(n2.pt, t3);\n n2.edge_before = o3;\n }\n for (let n2 of t2)\n n2.edge_before ? n2.edge_after = n2.edge_before.next : e37 instanceof _H \u0026\u0026 1 \u0026 n2.is_vertex \u0026\u0026 (n2.edge_after = e37.first);\n }\n}\nfunction wH(e37, t2, n2) {\n const o3 = e37.edge_before, i3 = t2.edge_after, r3 = n2.length;\n o3.next = n2[0], n2[0].prev = o3, n2[r3 - 1].next = i3, i3.prev = n2[r3 - 1];\n}\nkX.multiline = (...e37) =\u003e new kX.Multiline(...e37);\nvar { INSIDE: NH, OUTSIDE: RH, BOUNDARY: TH, OVERLAP_SAME: EH, OVERLAP_OPPOSITE: AH } = MX;\nvar { NOT_VERTEX: OH, START_VERTEX: kH, END_VERTEX: DH } = MX;\nfunction LH(e37, t2) {\n let n2 = t2.clone().reverse(), [o3, i3] = YH(e37, n2, 3, true);\n return o3;\n}\nfunction zH(e37, t2) {\n let [n2, o3] = YH(e37, t2, 2, true);\n return n2;\n}\nfunction BH(e37, t2) {\n let [n2, o3] = YH(e37, t2, 2, false), i3 = [];\n for (let e38 of n2.faces)\n i3 = [...i3, ...[...e38.edges].map((e39) =\u003e e39.shape)];\n let r3 = [];\n for (let e38 of o3.faces)\n r3 = [...r3, ...[...e38.edges].map((e39) =\u003e e39.shape)];\n return [i3, r3];\n}\nfunction FH(e37, t2) {\n let [n2, o3] = YH(e37, t2, 3, false), i3 = [];\n for (let e38 of n2.faces)\n i3 = [...i3, ...[...e38.edges].map((e39) =\u003e e39.shape)];\n return i3;\n}\nfunction jH(e37, t2) {\n let n2 = e37.clone(), o3 = t2.clone(), i3 = XH(n2, o3);\n return bH(i3), MH(n2, i3.int_points1_sorted), MH(o3, i3.int_points2_sorted), IH(i3), bH(i3), [i3.int_points1_sorted.map((e38) =\u003e e38.pt), i3.int_points2_sorted.map((e38) =\u003e e38.pt)];\n}\nfunction $H(e37, t2, n2, o3) {\n let i3 = HH(e37, n2.int_points1), r3 = HH(t2, n2.int_points2);\n for (VH(i3, t2), VH(r3, e37), SH(n2.int_points1), SH(n2.int_points2), CH(n2.int_points1, t2), CH(n2.int_points2, e37);WH(e37, t2, n2.int_points1, n2.int_points1_sorted, n2.int_points2, n2); )\n ;\n (function(e38) {\n let t3, n3, o4, i4 = e38.int_points1.length;\n for (let r4 = 0;r4 \u003c i4; r4++) {\n let s2 = e38.int_points1_sorted[r4];\n s2.face !== t3 \u0026\u0026 (n3 = r4, t3 = s2.face);\n let a3, c3 = r4, l3 = PH(e38.int_points1_sorted, r4, t3);\n a3 = c3 + l3 \u003c i4 \u0026\u0026 e38.int_points1_sorted[c3 + l3].face === t3 ? c3 + l3 : n3;\n let h2 = PH(e38.int_points1_sorted, a3, t3);\n o4 = null;\n for (let n4 = a3;n4 \u003c a3 + h2; n4++) {\n let i5 = e38.int_points1_sorted[n4];\n if (i5.face === t3 \u0026\u0026 e38.int_points2[i5.id].face === e38.int_points2[s2.id].face) {\n o4 = i5;\n break;\n }\n }\n if (o4 === null)\n continue;\n let d2 = s2.edge_after, u2 = o4.edge_before;\n if (d2.bv !== 2 || u2.bv !== 2)\n continue;\n if (d2 !== u2)\n continue;\n let p3 = e38.int_points2[s2.id], m2 = e38.int_points2[o4.id], g2 = p3.edge_after, f2 = m2.edge_before;\n g2.bv === 2 \u0026\u0026 f2.bv === 2 \u0026\u0026 g2 === f2 || (p3 = e38.int_points2[o4.id], m2 = e38.int_points2[s2.id], g2 = p3.edge_after, f2 = m2.edge_before), g2.bv === 2 \u0026\u0026 f2.bv === 2 \u0026\u0026 g2 === f2 \u0026\u0026 d2.setOverlap(g2);\n }\n })(n2), GH(e37, o3, n2.int_points1_sorted, true), GH(t2, o3, n2.int_points2_sorted, false), qH(e37, i3, o3, true), qH(t2, r3, o3, false);\n}\nfunction YH(e37, t2, n2, o3) {\n let i3 = e37.clone(), r3 = t2.clone(), s2 = XH(i3, r3);\n return bH(s2), MH(i3, s2.int_points1_sorted), MH(r3, s2.int_points2_sorted), IH(s2), bH(s2), $H(i3, r3, s2, n2), o3 \u0026\u0026 function(e38, t3, n3) {\n (function(e39, t4, n4, o4) {\n for (let n5 of t4.faces) {\n for (let t5 of n5)\n e39.edges.add(t5);\n o4.find((e40) =\u003e e40.face === n5) === undefined \u0026\u0026 e39.addFace(n5.first, n5.last);\n }\n })(e38, t3, 0, n3.int_points2), function(e39, t4, n4) {\n if (n4.int_points1.length !== 0)\n for (let e40 = 0;e40 \u003c n4.int_points1.length; e40++) {\n let t5 = n4.int_points1[e40], o4 = n4.int_points2[e40];\n if (t5.edge_before !== undefined \u0026\u0026 t5.edge_after === undefined \u0026\u0026 o4.edge_before === undefined \u0026\u0026 o4.edge_after !== undefined \u0026\u0026 (t5.edge_before.next = o4.edge_after, o4.edge_after.prev = t5.edge_before, t5.edge_after = o4.edge_after, o4.edge_before = t5.edge_before), o4.edge_before !== undefined \u0026\u0026 o4.edge_after === undefined \u0026\u0026 t5.edge_before === undefined \u0026\u0026 t5.edge_after !== undefined \u0026\u0026 (o4.edge_before.next = t5.edge_after, t5.edge_after.prev = o4.edge_before, o4.edge_after = t5.edge_after, t5.edge_before = o4.edge_before), t5.edge_before !== undefined \u0026\u0026 t5.edge_after === undefined)\n for (let e41 of n4.int_points1_sorted)\n e41 !== t5 \u0026\u0026 e41.edge_before === undefined \u0026\u0026 e41.edge_after !== undefined \u0026\u0026 e41.pt.equalTo(t5.pt) \u0026\u0026 (t5.edge_before.next = e41.edge_after, e41.edge_after.prev = t5.edge_before, t5.edge_after = e41.edge_after, e41.edge_before = t5.edge_before);\n if (o4.edge_before !== undefined \u0026\u0026 o4.edge_after === undefined)\n for (let e41 of n4.int_points2_sorted)\n e41 !== o4 \u0026\u0026 e41.edge_before === undefined \u0026\u0026 e41.edge_after !== undefined \u0026\u0026 e41.pt.equalTo(o4.pt) \u0026\u0026 (o4.edge_before.next = e41.edge_after, e41.edge_after.prev = o4.edge_before, o4.edge_after = e41.edge_after, e41.edge_before = o4.edge_before);\n }\n }(0, 0, n3), UH(e38, n3.int_points1), UH(t3, n3.int_points2), ZH(e38, n3.int_points1, n3.int_points2), ZH(e38, n3.int_points2, n3.int_points1);\n }(i3, r3, s2), [i3, r3];\n}\nfunction XH(e37, t2) {\n let n2 = { int_points1: [], int_points2: [] };\n for (let o3 of e37.edges) {\n let e38 = t2.edges.search(o3.box);\n for (let t3 of e38) {\n let e39 = o3.shape.intersect(t3.shape);\n for (let i3 of e39)\n yH(o3, i3, n2.int_points1), yH(t3, i3, n2.int_points2);\n }\n }\n return n2;\n}\nfunction HH(e37, t2) {\n let n2 = [];\n for (let o3 of e37.faces)\n t2.find((e38) =\u003e e38.face === o3) || n2.push(o3);\n return n2;\n}\nfunction VH(e37, t2) {\n for (let n2 of e37)\n n2.first.bv = n2.first.bvStart = n2.first.bvEnd = undefined, n2.first.setInclusion(t2);\n}\nfunction WH(e37, t2, n2, o3, i3, r3) {\n let s2, a3, c3, l3 = o3.length, h2 = false;\n for (let d2 = 0;d2 \u003c l3; d2++) {\n let u2 = o3[d2];\n u2.face !== s2 \u0026\u0026 (a3 = d2, s2 = u2.face);\n let p3, m2 = d2, g2 = PH(o3, d2, s2);\n p3 = m2 + g2 \u003c l3 \u0026\u0026 o3[m2 + g2].face === s2 ? m2 + g2 : a3;\n let f2 = PH(o3, p3, s2);\n c3 = null;\n for (let e38 = p3;e38 \u003c p3 + f2; e38++) {\n let t3 = o3[e38];\n if (t3.face === s2 \u0026\u0026 i3[t3.id].face === i3[u2.id].face) {\n c3 = t3;\n break;\n }\n }\n if (c3 === null)\n continue;\n let _2 = u2.edge_after, y2 = c3.edge_before;\n if (_2.bv !== TH || y2.bv == TH)\n if (_2.bv == TH || y2.bv !== TH) {\n if (_2.bv === TH \u0026\u0026 y2.bv === TH \u0026\u0026 _2 != y2 || _2.bv === NH \u0026\u0026 y2.bv === RH || _2.bv === RH \u0026\u0026 y2.bv === NH) {\n let e38 = _2.next;\n for (;e38 != y2; )\n e38.bvStart = undefined, e38.bvEnd = undefined, e38.bv = undefined, e38.setInclusion(t2), e38 = e38.next;\n }\n if (_2.bv === TH \u0026\u0026 y2.bv === TH \u0026\u0026 _2 != y2) {\n let e38, t3 = _2.next;\n for (;t3 != y2; ) {\n if (t3.bv != TH) {\n if (e38 === undefined)\n e38 = t3.bv;\n else if (t3.bv != e38)\n throw DX.UNRESOLVED_BOUNDARY_CONFLICT;\n }\n t3 = t3.next;\n }\n e38 != null \u0026\u0026 (_2.bv = e38, y2.bv = e38);\n continue;\n }\n if (_2.bv === NH \u0026\u0026 y2.bv === RH || _2.bv === RH \u0026\u0026 y2.bv === NH) {\n let o4 = _2;\n for (;o4 != y2; ) {\n if (o4.bvStart === _2.bv \u0026\u0026 o4.bvEnd === y2.bv) {\n let [s3, a4] = o4.shape.distanceTo(t2);\n if (s3 \u003c 10 * kX.DP_TOL) {\n yH(o4, a4.ps, n2);\n let s4 = n2[n2.length - 1];\n if (s4.is_vertex \u0026 kH)\n s4.edge_after = o4, s4.edge_before = o4.prev, o4.bvStart = TH, o4.bv = undefined, o4.setInclusion(t2);\n else if (s4.is_vertex \u0026 DH)\n s4.edge_after = o4.next, o4.bvEnd = TH, o4.bv = undefined, o4.setInclusion(t2);\n else {\n let e38 = t2.addVertex(s4.pt, o4);\n s4.edge_before = e38, s4.edge_after = e38.next, e38.setInclusion(t2), e38.next.bvStart = TH, e38.next.bvEnd = undefined, e38.next.bv = undefined, e38.next.setInclusion(t2);\n }\n let c4 = t2.findEdgeByPoint(a4.pe);\n yH(c4, a4.pe, i3);\n let l4 = i3[i3.length - 1];\n if (l4.is_vertex \u0026 kH)\n l4.edge_after = c4, l4.edge_before = c4.prev;\n else if (l4.is_vertex \u0026 DH)\n l4.edge_after = c4.next;\n else {\n let n3 = i3.find((e38) =\u003e e38.edge_after === c4), o5 = t2.addVertex(l4.pt, c4);\n l4.edge_before = o5, l4.edge_after = o5.next, n3 \u0026\u0026 (n3.edge_after = o5), o5.bvStart = undefined, o5.bvEnd = TH, o5.bv = undefined, o5.setInclusion(e37), o5.next.bvStart = TH, o5.next.bvEnd = undefined, o5.next.bv = undefined, o5.next.setInclusion(e37);\n }\n bH(r3), h2 = true;\n break;\n }\n }\n o4 = o4.next;\n }\n if (h2)\n break;\n throw DX.UNRESOLVED_BOUNDARY_CONFLICT;\n }\n } else\n y2.bv = _2.bv;\n else\n _2.bv = y2.bv;\n }\n return h2;\n}\nfunction GH(e37, t2, n2, o3) {\n if (!n2)\n return;\n let i3, r3, s2, a3;\n for (let c3 = 0;c3 \u003c n2.length; c3++) {\n if (s2 = n2[c3], s2.face !== i3 \u0026\u0026 (r3 = c3, i3 = s2.face), i3.isEmpty())\n continue;\n let l3, h2 = c3, d2 = PH(n2, c3, i3);\n l3 = h2 + d2 \u003c n2.length \u0026\u0026 n2[h2 + d2].face === s2.face ? h2 + d2 : r3, a3 = n2[l3];\n let u2 = l3, p3 = PH(n2, u2, i3), m2 = s2.edge_after, g2 = a3.edge_before;\n if (m2.bv === NH \u0026\u0026 g2.bv === NH \u0026\u0026 t2 === 1 || m2.bv === RH \u0026\u0026 g2.bv === RH \u0026\u0026 t2 === 2 || (m2.bv === RH || g2.bv === RH) \u0026\u0026 t2 === 3 \u0026\u0026 !o3 || (m2.bv === NH || g2.bv === NH) \u0026\u0026 t2 === 3 \u0026\u0026 o3 || m2.bv === TH \u0026\u0026 g2.bv === TH \u0026\u0026 m2.overlap \u0026 EH \u0026\u0026 o3 || m2.bv === TH \u0026\u0026 g2.bv === TH \u0026\u0026 m2.overlap \u0026 AH) {\n e37.removeChain(i3, m2, g2);\n for (let e38 = h2;e38 \u003c h2 + d2; e38++)\n n2[e38].edge_after = undefined;\n for (let e38 = u2;e38 \u003c u2 + p3; e38++)\n n2[e38].edge_before = undefined;\n }\n c3 += d2 - 1;\n }\n}\nfunction UH(e37, t2) {\n for (let n2 of t2)\n e37.faces.delete(n2.face), n2.face = undefined, n2.edge_before \u0026\u0026 (n2.edge_before.face = undefined), n2.edge_after \u0026\u0026 (n2.edge_after.face = undefined);\n}\nfunction ZH(e37, t2, n2) {\n for (let o3 of t2) {\n if (o3.edge_before === undefined || o3.edge_after === undefined)\n continue;\n if (o3.face)\n continue;\n if (o3.edge_after.face || o3.edge_before.face)\n continue;\n let { edge_after: i3, edge_before: r3 } = o3;\n try {\n LX.testInfiniteLoop(i3);\n } catch (e38) {\n throw DX.CANNOT_COMPLETE_BOOLEAN_OPERATION;\n }\n let s2 = e37.addFace(i3, r3);\n for (let e38 of t2)\n e38.edge_before \u0026\u0026 e38.edge_after \u0026\u0026 e38.edge_before.face === s2 \u0026\u0026 e38.edge_after.face === s2 \u0026\u0026 (e38.face = s2);\n for (let e38 of n2)\n e38.edge_before \u0026\u0026 e38.edge_after \u0026\u0026 e38.edge_before.face === s2 \u0026\u0026 e38.edge_after.face === s2 \u0026\u0026 (e38.face = s2);\n }\n}\nfunction qH(e37, t2, n2, o3) {\n for (let i3 of t2) {\n let t3 = i3.first.bv;\n (n2 === 1 \u0026\u0026 t3 === NH || n2 === 3 \u0026\u0026 t3 === NH \u0026\u0026 o3 || n2 === 3 \u0026\u0026 t3 === RH \u0026\u0026 !o3 || n2 === 2 \u0026\u0026 t3 === RH) \u0026\u0026 e37.deleteFace(i3);\n }\n}\nvar JH = Object.freeze({ __proto__: null, BOOLEAN_INTERSECT: 2, BOOLEAN_SUBTRACT: 3, BOOLEAN_UNION: 1, calculateIntersections: jH, innerClip: BH, intersect: zH, outerClip: FH, removeNotRelevantChains: GH, removeOldFaces: UH, restoreFaces: ZH, subtract: LH, unify: function(e37, t2) {\n let [n2, o3] = YH(e37, t2, 1, true);\n return n2;\n} });\nvar QH = RegExp(\"T.F..FFF.|T.F...F..\");\nvar KH = RegExp(\"T........|.T.......|...T.....|....T....\");\nvar eV = RegExp(\"FT.......|F..T.....|F...T....\");\nvar tV = RegExp(\"T.F..F...\");\nvar nV = RegExp(\"T.F..F...|.TF..F...|..FT.F...|..F.TF...\");\nvar oV = class {\n constructor() {\n this.m = new Array(9).fill(undefined);\n }\n get I2I() {\n return this.m[0];\n }\n set I2I(e37) {\n this.m[0] = e37;\n }\n get I2B() {\n return this.m[1];\n }\n set I2B(e37) {\n this.m[1] = e37;\n }\n get I2E() {\n return this.m[2];\n }\n set I2E(e37) {\n this.m[2] = e37;\n }\n get B2I() {\n return this.m[3];\n }\n set B2I(e37) {\n this.m[3] = e37;\n }\n get B2B() {\n return this.m[4];\n }\n set B2B(e37) {\n this.m[4] = e37;\n }\n get B2E() {\n return this.m[5];\n }\n set B2E(e37) {\n this.m[5] = e37;\n }\n get E2I() {\n return this.m[6];\n }\n set E2I(e37) {\n this.m[6] = e37;\n }\n get E2B() {\n return this.m[7];\n }\n set E2B(e37) {\n this.m[7] = e37;\n }\n get E2E() {\n return this.m[8];\n }\n set E2E(e37) {\n this.m[8] = e37;\n }\n toString() {\n return this.m.map((e37) =\u003e e37 instanceof Array \u0026\u0026 e37.length \u003e 0 ? \"T\" : e37 instanceof Array \u0026\u0026 e37.length === 0 ? \"F\" : \"*\").join(\"\");\n }\n equal() {\n return QH.test(this.toString());\n }\n intersect() {\n return KH.test(this.toString());\n }\n touch() {\n return eV.test(this.toString());\n }\n inside() {\n return tV.test(this.toString());\n }\n covered() {\n return nV.test(this.toString());\n }\n};\nfunction iV(e37, t2) {\n let n2, o3 = new kX.Ray(t2), i3 = new kX.Line(o3.pt, o3.norm);\n const r3 = new kX.Box(o3.box.xmin - kX.DP_TOL, o3.box.ymin - kX.DP_TOL, o3.box.xmax + kX.DP_TOL, o3.box.ymax + kX.DP_TOL);\n if (e37.box.not_intersect(r3))\n return kX.OUTSIDE;\n let s2 = e37.edges.search(r3);\n if (s2.length === 0)\n return kX.OUTSIDE;\n for (let e38 of s2)\n if (e38.shape.contains(t2))\n return kX.BOUNDARY;\n let a3 = [...e37.faces], c3 = [];\n for (let e38 of s2)\n for (let n3 of o3.intersect(e38.shape)) {\n if (n3.equalTo(t2))\n return kX.BOUNDARY;\n c3.push({ pt: n3, edge: e38, face_index: a3.indexOf(e38.face) });\n }\n c3.sort((e38, t3) =\u003e OX(e38.pt.x, t3.pt.x) ? -1 : AX(e38.pt.x, t3.pt.x) ? 1 : e38.face_index \u003c t3.face_index ? -1 : e38.face_index \u003e t3.face_index ? 1 : e38.edge.arc_length \u003c t3.edge.arc_length ? -1 : e38.edge.arc_length \u003e t3.edge.arc_length ? 1 : 0);\n let l3 = 0;\n for (let e38 = 0;e38 \u003c c3.length; e38++) {\n let t3 = c3[e38];\n if (t3.pt.equalTo(t3.edge.shape.start)) {\n if (e38 \u003e 0 \u0026\u0026 t3.pt.equalTo(c3[e38 - 1].pt) \u0026\u0026 t3.face_index === c3[e38 - 1].face_index \u0026\u0026 t3.edge.prev === c3[e38 - 1].edge)\n continue;\n let n3 = t3.edge.prev;\n for (;TX(n3.length); )\n n3 = n3.prev;\n let o4 = n3.shape.tangentInEnd(), r4 = t3.pt.translate(o4), s3 = t3.edge.shape.tangentInStart(), a4 = t3.pt.translate(s3), h2 = r4.leftTo(i3), d2 = a4.leftTo(i3);\n (h2 \u0026\u0026 !d2 || !h2 \u0026\u0026 d2) \u0026\u0026 l3++;\n } else if (t3.pt.equalTo(t3.edge.shape.end)) {\n if (e38 \u003e 0 \u0026\u0026 t3.pt.equalTo(c3[e38 - 1].pt) \u0026\u0026 t3.face_index === c3[e38 - 1].face_index \u0026\u0026 t3.edge.next === c3[e38 - 1].edge)\n continue;\n let n3 = t3.edge.next;\n for (;TX(n3.length); )\n n3 = n3.next;\n let o4 = n3.shape.tangentInStart(), r4 = t3.pt.translate(o4), s3 = t3.edge.shape.tangentInEnd(), a4 = t3.pt.translate(s3), h2 = r4.leftTo(i3), d2 = a4.leftTo(i3);\n (h2 \u0026\u0026 !d2 || !h2 \u0026\u0026 d2) \u0026\u0026 l3++;\n } else if (t3.edge.shape instanceof kX.Segment)\n l3++;\n else {\n let e39 = t3.edge.shape.box;\n EX(t3.pt.y, e39.ymin) || EX(t3.pt.y, e39.ymax) || l3++;\n }\n }\n return n2 = l3 % 2 == 1 ? 1 : 0, n2;\n}\nfunction rV(e37, t2) {\n return lV(e37, t2).intersect();\n}\nfunction sV(e37, t2) {\n return lV(e37, t2).inside();\n}\nfunction aV(e37, t2) {\n return lV(e37, t2).covered();\n}\nfunction cV(e37, t2) {\n return aV(t2, e37);\n}\nfunction lV(e37, t2) {\n return e37 instanceof kX.Line \u0026\u0026 t2 instanceof kX.Line ? function(e38, t3) {\n let n2 = new oV, o3 = jX(e38, t3);\n o3.length === 0 ? e38.contains(t3.pt) \u0026\u0026 t3.contains(e38.pt) ? (n2.I2I = [e38], n2.I2E = [], n2.E2I = []) : (n2.I2I = [], n2.I2E = [e38], n2.E2I = [t3]) : (n2.I2I = o3, n2.I2E = e38.split(o3), n2.E2I = t3.split(o3));\n return n2;\n }(e37, t2) : e37 instanceof kX.Line \u0026\u0026 t2 instanceof kX.Circle ? function(e38, t3) {\n let n2 = new oV, o3 = $X(e38, t3);\n if (o3.length === 0)\n n2.I2I = [], n2.I2B = [], n2.I2E = [e38], n2.E2I = [t3];\n else if (o3.length === 1)\n n2.I2I = [], n2.I2B = o3, n2.I2E = e38.split(o3), n2.E2I = [t3];\n else {\n let i3 = new _H([e38]), r3 = e38.sortPoints(o3);\n i3.split(r3);\n let s2 = i3.toShapes();\n n2.I2I = [s2[1]], n2.I2B = r3, n2.I2E = [s2[0], s2[2]], n2.E2I = new kX.Polygon([t3.toArc()]).cutWithLine(e38);\n }\n return n2;\n }(e37, t2) : e37 instanceof kX.Line \u0026\u0026 t2 instanceof kX.Box ? function(e38, t3) {\n let n2 = new oV, o3 = YX(e38, t3);\n if (o3.length === 0)\n n2.I2I = [], n2.I2B = [], n2.I2E = [e38], n2.E2I = [t3];\n else if (o3.length === 1)\n n2.I2I = [], n2.I2B = o3, n2.I2E = e38.split(o3), n2.E2I = [t3];\n else {\n let i3 = new _H([e38]), r3 = e38.sortPoints(o3);\n i3.split(r3);\n let s2 = i3.toShapes();\n t3.toSegments().some((e39) =\u003e e39.contains(o3[0]) \u0026\u0026 e39.contains(o3[1])) ? (n2.I2I = [], n2.I2B = [s2[1]], n2.I2E = [s2[0], s2[2]], n2.E2I = [t3]) : (n2.I2I = [s2[1]], n2.I2B = r3, n2.I2E = [s2[0], s2[2]], n2.E2I = new kX.Polygon(t3.toSegments()).cutWithLine(e38));\n }\n return n2;\n }(e37, t2) : e37 instanceof kX.Line \u0026\u0026 t2 instanceof kX.Polygon ? function(e38, t3) {\n let n2 = new oV, o3 = iH(e38, t3), i3 = new _H([e38]), r3 = o3.length \u003e 0 ? o3.slice() : e38.sortPoints(o3);\n return i3.split(r3), [...i3].forEach((e39) =\u003e e39.setInclusion(t3)), n2.I2I = [...i3].filter((e39) =\u003e e39.bv === kX.INSIDE).map((e39) =\u003e e39.shape), n2.I2B = [...i3].slice(1).map((e39) =\u003e e39.bv === kX.BOUNDARY ? e39.shape : e39.shape.start), n2.I2E = [...i3].filter((e39) =\u003e e39.bv === kX.OUTSIDE).map((e39) =\u003e e39.shape), n2.E2I = t3.cutWithLine(e38), n2;\n }(e37, t2) : (e37 instanceof kX.Segment || e37 instanceof kX.Arc) \u0026\u0026 t2 instanceof kX.Polygon ? hV(e37, t2) : (e37 instanceof kX.Segment || e37 instanceof kX.Arc) \u0026\u0026 (t2 instanceof kX.Circle || t2 instanceof kX.Box) ? hV(e37, new kX.Polygon(t2)) : e37 instanceof kX.Polygon \u0026\u0026 t2 instanceof kX.Polygon ? dV(e37, t2) : (e37 instanceof kX.Circle || e37 instanceof kX.Box) \u0026\u0026 (t2 instanceof kX.Circle || t2 instanceof kX.Box) ? dV(new kX.Polygon(e37), new kX.Polygon(t2)) : (e37 instanceof kX.Circle || e37 instanceof kX.Box) \u0026\u0026 t2 instanceof kX.Polygon ? dV(new kX.Polygon(e37), t2) : e37 instanceof kX.Polygon \u0026\u0026 (t2 instanceof kX.Circle || t2 instanceof kX.Box) ? dV(e37, new kX.Polygon(t2)) : undefined;\n}\nfunction hV(e37, t2) {\n let n2 = new oV, o3 = function(e38, t3) {\n return e38 instanceof kX.Line ? iH(e38, t3) : e38 instanceof kX.Segment ? nH(e38, t3) : e38 instanceof kX.Arc ? oH(e38, t3) : [];\n }(e37, t2), i3 = o3.length \u003e 0 ? o3.slice() : e37.sortPoints(o3), r3 = new _H([e37]);\n r3.split(i3), [...r3].forEach((e38) =\u003e e38.setInclusion(t2)), n2.I2I = [...r3].filter((e38) =\u003e e38.bv === kX.INSIDE).map((e38) =\u003e e38.shape), n2.I2B = [...r3].slice(1).map((e38) =\u003e e38.bv === kX.BOUNDARY ? e38.shape : e38.shape.start), n2.I2E = [...r3].filter((e38) =\u003e e38.bv === kX.OUTSIDE).map((e38) =\u003e e38.shape), n2.B2I = [], n2.B2B = [], n2.B2E = [];\n for (let o4 of [e37.start, e37.end])\n switch (iV(t2, o4)) {\n case kX.INSIDE:\n n2.B2I.push(o4);\n break;\n case kX.BOUNDARY:\n n2.B2B.push(o4);\n break;\n case kX.OUTSIDE:\n n2.B2E.push(o4);\n }\n return n2;\n}\nfunction dV(e37, t2) {\n let n2 = new oV, [o3, i3] = jH(e37, t2), r3 = zH(e37, t2), s2 = LH(e37, t2), a3 = LH(t2, e37), [c3, l3] = BH(e37, t2), h2 = FH(e37, t2), d2 = FH(t2, e37);\n return n2.I2I = r3.isEmpty() ? [] : [r3], n2.I2B = l3, n2.I2E = s2.isEmpty() ? [] : [s2], n2.B2I = c3, n2.B2B = o3, n2.B2E = h2, n2.E2I = a3.isEmpty() ? [] : [a3], n2.E2B = d2, n2;\n}\nvar uV = Object.freeze({ __proto__: null, contain: function(e37, t2) {\n return sV(t2, e37);\n}, cover: cV, covered: aV, disjoint: function(e37, t2) {\n return !rV(e37, t2);\n}, equal: function(e37, t2) {\n return lV(e37, t2).equal();\n}, inside: sV, intersect: rV, relate: lV, touch: function(e37, t2) {\n return lV(e37, t2).touch();\n} });\nvar pV = class e37 {\n constructor(e38 = 1, t2 = 0, n2 = 0, o3 = 1, i3 = 0, r3 = 0) {\n this.a = e38, this.b = t2, this.c = n2, this.d = o3, this.tx = i3, this.ty = r3;\n }\n fromMatrix3x3(t2) {\n const [n2, o3, i3] = t2[0], [r3, s2, a3] = t2[1];\n return new e37(n2, r3, o3, s2, i3, a3);\n }\n toMatrix3x3() {\n return [[this.a, this.c, this.tx], [this.b, this.d, this.ty], [0, 0, 1]];\n }\n clone() {\n return new e37(this.a, this.b, this.c, this.d, this.tx, this.ty);\n }\n transform(e38) {\n return [e38[0] * this.a + e38[1] * this.c + this.tx, e38[0] * this.b + e38[1] * this.d + this.ty];\n }\n multiply(t2) {\n return new e37(this.a * t2.a + this.c * t2.b, this.b * t2.a + this.d * t2.b, this.a * t2.c + this.c * t2.d, this.b * t2.c + this.d * t2.d, this.a * t2.tx + this.c * t2.ty + this.tx, this.b * t2.tx + this.d * t2.ty + this.ty);\n }\n translate(...t2) {\n let n2, o3;\n if (t2.length != 1 || isNaN(t2[0].x) || isNaN(t2[0].y)) {\n if (t2.length !== 2 || typeof t2[0] != \"number\" || typeof t2[1] != \"number\")\n throw DX.ILLEGAL_PARAMETERS;\n n2 = t2[0], o3 = t2[1];\n } else\n n2 = t2[0].x, o3 = t2[0].y;\n return this.multiply(new e37(1, 0, 0, 1, n2, o3));\n }\n rotate(t2, n2 = 0, o3 = 0) {\n let i3 = Math.cos(t2), r3 = Math.sin(t2);\n return this.translate(n2, o3).multiply(new e37(i3, r3, -r3, i3, 0, 0)).translate(-n2, -o3);\n }\n scale(t2, n2) {\n return this.multiply(new e37(t2, 0, 0, n2, 0, 0));\n }\n equalTo(e38) {\n return !!kX.Utils.EQ(this.tx, e38.tx) \u0026\u0026 (!!kX.Utils.EQ(this.ty, e38.ty) \u0026\u0026 (!!kX.Utils.EQ(this.a, e38.a) \u0026\u0026 (!!kX.Utils.EQ(this.b, e38.b) \u0026\u0026 (!!kX.Utils.EQ(this.c, e38.c) \u0026\u0026 !!kX.Utils.EQ(this.d, e38.d)))));\n }\n};\nkX.Matrix = pV;\nkX.matrix = (...e38) =\u003e new kX.Matrix(...e38);\nvar mV = class {\n constructor(e38, t2) {\n this.low = e38, this.high = t2;\n }\n get max() {\n return this.clone();\n }\n less_than(e38) {\n return this.low \u003c e38.low || this.low === e38.low \u0026\u0026 this.high \u003c e38.high;\n }\n equal_to(e38) {\n return this.low === e38.low \u0026\u0026 this.high === e38.high;\n }\n intersect(e38) {\n return !this.not_intersect(e38);\n }\n not_intersect(e38) {\n return this.high \u003c e38.low || e38.high \u003c this.low;\n }\n merge(e38) {\n const t2 = this.low === undefined ? e38.low : this.low \u003c e38.low ? this.low : e38.low, n2 = this.high === undefined ? e38.high : this.high \u003e e38.high ? this.high : e38.high, o3 = this.clone();\n return o3.low = t2, o3.high = n2, o3;\n }\n output() {\n return [this.low, this.high];\n }\n comparable_less_than(e38, t2) {\n return e38 \u003c t2;\n }\n};\nvar gV = class e38 extends mV {\n clone() {\n return new e38(this.low, this.high);\n }\n};\nvar fV = class {\n constructor(e39, t2, n2 = null, o3 = null, i3 = null, r3 = 0) {\n if (this.left = n2, this.right = o3, this.parent = i3, this.color = r3, this.item = { key: undefined, values: [] }, t2 !== undefined \u0026\u0026 this.item.values.push(t2), e39 !== undefined)\n if (Array.isArray(e39)) {\n const [t3, n3] = e39;\n if (!Number.isNaN(t3) \u0026\u0026 !Number.isNaN(n3)) {\n let e40 = t3, o4 = n3;\n e40 \u003e o4 \u0026\u0026 ([e40, o4] = [o4, e40]), this.item.key = new gV(e40, o4);\n }\n } else\n this.item.key = e39;\n this.max = this.item.key ? this.item.key.max : undefined;\n }\n isNil() {\n return this.item.key === undefined \u0026\u0026 this.item.values.length === 0 \u0026\u0026 this.left === null \u0026\u0026 this.right === null \u0026\u0026 this.color === 0;\n }\n requireKey() {\n if (!this.item.key)\n throw new Error(\"Node key is undefined (nil/sentinel). Operation is not applicable.\");\n return this.item.key;\n }\n less_than(e39) {\n const t2 = this.requireKey(), n2 = e39.requireKey();\n return t2.less_than(n2);\n }\n _value_equal(e39) {\n const t2 = this.item.values[0], n2 = e39.item.values[0];\n return t2 \u0026\u0026 n2 \u0026\u0026 t2.equal_to ? t2.equal_to(n2) : t2 === n2;\n }\n equal_to(e39) {\n const t2 = this.requireKey(), n2 = e39.requireKey();\n return t2.equal_to(n2);\n }\n intersect(e39) {\n const t2 = this.requireKey(), n2 = e39.requireKey();\n return t2.intersect(n2);\n }\n copy_data(e39) {\n this.item.key = e39.item.key, this.item.values = e39.item.values.slice();\n }\n update_max() {\n this.max = this.item.key ? this.item.key.max : undefined, this.right \u0026\u0026 this.right.max \u0026\u0026 (this.max = this.max ? this.max.merge(this.right.max) : this.right.max), this.left \u0026\u0026 this.left.max \u0026\u0026 (this.max = this.max ? this.max.merge(this.left.max) : this.left.max);\n }\n not_intersect_left_subtree(e39) {\n if (!this.left)\n return true;\n const t2 = this.left.max ? this.left.max.high : this.left.item.key.high, n2 = this.requireKey(), o3 = e39.requireKey();\n return n2.comparable_less_than(t2, o3.low);\n }\n not_intersect_right_subtree(e39) {\n if (!this.right)\n return true;\n const t2 = this.right.max ? this.right.max.low : this.right.item.key.low, n2 = this.requireKey(), o3 = e39.requireKey();\n return n2.comparable_less_than(o3.high, t2);\n }\n};\nvar _V = class e39 {\n constructor() {\n this.root = null, this.nil_node = new fV;\n }\n get size() {\n let e40 = 0;\n return this.tree_walk(this.root, (t2) =\u003e e40 += t2.item.values.length), e40;\n }\n get keys() {\n const e40 = [];\n return this.tree_walk(this.root, (t2) =\u003e e40.push(t2.item.key.output())), e40;\n }\n get values() {\n const e40 = [];\n return this.tree_walk(this.root, (t2) =\u003e {\n for (const n2 of t2.item.values)\n e40.push(n2);\n }), e40;\n }\n get items() {\n const e40 = [];\n return this.tree_walk(this.root, (t2) =\u003e {\n const n2 = t2.item.key.output();\n for (const o3 of t2.item.values)\n e40.push({ key: n2, value: o3 });\n }), e40;\n }\n isEmpty() {\n return this.root == null || this.root === this.nil_node;\n }\n clear() {\n this.root = null;\n }\n insert(e40, t2 = e40) {\n if (e40 === undefined)\n return;\n const n2 = this.tree_search(this.root, new fV(e40));\n if (n2)\n return n2.item.values.push(t2), n2;\n const o3 = new fV(e40, t2, this.nil_node, this.nil_node, null, 1);\n return this.tree_insert(o3), this.recalc_max(o3), o3;\n }\n exist(e40, t2 = e40) {\n const n2 = this.tree_search(this.root, new fV(e40));\n return !!n2 \u0026\u0026 (arguments.length \u003c 2 || t2 === e40 || n2.item.values.some((e41) =\u003e e41 \u0026\u0026 e41.equal_to ? e41.equal_to(t2) : e41 === t2));\n }\n remove(e40, t2 = e40) {\n const n2 = this.tree_search(this.root, new fV(e40));\n if (!n2)\n return;\n if (arguments.length \u003c 2)\n return this.tree_delete(n2), n2;\n const o3 = n2.item.values.findIndex((e41) =\u003e e41 \u0026\u0026 e41.equal_to ? e41.equal_to(t2) : e41 === t2);\n return o3 \u003e= 0 ? (n2.item.values.splice(o3, 1), n2.item.values.length === 0 \u0026\u0026 this.tree_delete(n2), n2) : undefined;\n }\n search(e40, t2 = (e41, t3) =\u003e e41 === t3 ? t3.output() : e41) {\n const n2 = new fV(e40), o3 = [];\n this.tree_search_interval(this.root, n2, o3);\n const i3 = [];\n for (const e41 of o3)\n for (const n3 of e41.item.values)\n i3.push(t2(n3, e41.item.key));\n return i3;\n }\n intersect_any(e40) {\n const t2 = new fV(e40);\n return this.tree_find_any_interval(this.root, t2);\n }\n forEach(e40) {\n this.tree_walk(this.root, (t2) =\u003e {\n for (const n2 of t2.item.values)\n e40(t2.item.key, n2);\n });\n }\n map(t2) {\n const n2 = new e39;\n return this.tree_walk(this.root, (e40) =\u003e {\n for (const o3 of e40.item.values)\n n2.insert(e40.item.key, t2(o3, e40.item.key));\n }), n2;\n }\n *iterate(e40, t2 = (e41, t3) =\u003e e41 === t3 ? t3.output() : e41) {\n let n2 = null;\n for (e40 ? n2 = this.tree_search_nearest_forward(this.root, new fV(e40)) : this.root \u0026\u0026 (n2 = this.local_minimum(this.root));n2; ) {\n for (const e41 of n2.item.values)\n yield t2(e41, n2.item.key);\n n2 = this.tree_successor(n2);\n }\n }\n recalc_max(e40) {\n let t2 = e40;\n for (;t2.parent != null; )\n t2.parent.update_max(), t2 = t2.parent;\n }\n tree_insert(e40) {\n let t2 = this.root, n2 = null;\n if (this.root == null || this.root === this.nil_node)\n this.root = e40;\n else {\n for (;t2 !== this.nil_node; )\n n2 = t2, t2 = e40.less_than(t2) ? t2.left : t2.right;\n e40.parent = n2, e40.less_than(n2) ? n2.left = e40 : n2.right = e40;\n }\n this.insert_fixup(e40);\n }\n insert_fixup(e40) {\n let t2, n2;\n for (t2 = e40;t2 !== this.root \u0026\u0026 t2.parent.color === 1; )\n t2.parent === t2.parent.parent.left ? (n2 = t2.parent.parent.right, n2.color === 1 ? (t2.parent.color = 0, n2.color = 0, t2.parent.parent.color = 1, t2 = t2.parent.parent) : (t2 === t2.parent.right \u0026\u0026 (t2 = t2.parent, this.rotate_left(t2)), t2.parent.color = 0, t2.parent.parent.color = 1, this.rotate_right(t2.parent.parent))) : (n2 = t2.parent.parent.left, n2.color === 1 ? (t2.parent.color = 0, n2.color = 0, t2.parent.parent.color = 1, t2 = t2.parent.parent) : (t2 === t2.parent.left \u0026\u0026 (t2 = t2.parent, this.rotate_right(t2)), t2.parent.color = 0, t2.parent.parent.color = 1, this.rotate_left(t2.parent.parent)));\n this.root.color = 0;\n }\n tree_delete(e40) {\n let t2, n2;\n t2 = e40.left === this.nil_node || e40.right === this.nil_node ? e40 : this.tree_successor(e40), n2 = t2.left !== this.nil_node ? t2.left : t2.right, n2.parent = t2.parent, t2 === this.root ? this.root = n2 : (t2 === t2.parent.left ? t2.parent.left = n2 : t2.parent.right = n2, t2.parent.update_max()), this.recalc_max(n2), t2 !== e40 \u0026\u0026 (e40.copy_data(t2), e40.update_max(), this.recalc_max(e40)), t2.color === 0 \u0026\u0026 this.delete_fixup(n2);\n }\n delete_fixup(e40) {\n let t2, n2 = e40;\n for (;n2 !== this.root \u0026\u0026 n2.parent != null \u0026\u0026 n2.color === 0; )\n n2 === n2.parent.left ? (t2 = n2.parent.right, t2.color === 1 \u0026\u0026 (t2.color = 0, n2.parent.color = 1, this.rotate_left(n2.parent), t2 = n2.parent.right), t2.left.color === 0 \u0026\u0026 t2.right.color === 0 ? (t2.color = 1, n2 = n2.parent) : (t2.right.color === 0 \u0026\u0026 (t2.color = 1, t2.left.color = 0, this.rotate_right(t2), t2 = n2.parent.right), t2.color = n2.parent.color, n2.parent.color = 0, t2.right.color = 0, this.rotate_left(n2.parent), n2 = this.root)) : (t2 = n2.parent.left, t2.color === 1 \u0026\u0026 (t2.color = 0, n2.parent.color = 1, this.rotate_right(n2.parent), t2 = n2.parent.left), t2.left.color === 0 \u0026\u0026 t2.right.color === 0 ? (t2.color = 1, n2 = n2.parent) : (t2.left.color === 0 \u0026\u0026 (t2.color = 1, t2.right.color = 0, this.rotate_left(t2), t2 = n2.parent.left), t2.color = n2.parent.color, n2.parent.color = 0, t2.left.color = 0, this.rotate_right(n2.parent), n2 = this.root));\n n2.color = 0;\n }\n tree_search(e40, t2) {\n if (e40 != null \u0026\u0026 e40 !== this.nil_node)\n return t2.equal_to(e40) ? e40 : t2.less_than(e40) ? this.tree_search(e40.left, t2) : this.tree_search(e40.right, t2);\n }\n tree_search_nearest_forward(e40, t2) {\n let n2 = null, o3 = e40;\n for (;o3 \u0026\u0026 o3 !== this.nil_node; )\n o3.less_than(t2) ? o3.intersect(t2) ? (n2 = o3, o3 = o3.left) : o3 = o3.right : (n2 \u0026\u0026 !o3.less_than(n2) || (n2 = o3), o3 = o3.left);\n return n2 || null;\n }\n tree_search_interval(e40, t2, n2) {\n e40 != null \u0026\u0026 e40 !== this.nil_node \u0026\u0026 (e40.left === this.nil_node || e40.not_intersect_left_subtree(t2) || this.tree_search_interval(e40.left, t2, n2), e40.intersect(t2) \u0026\u0026 n2.push(e40), e40.right === this.nil_node || e40.not_intersect_right_subtree(t2) || this.tree_search_interval(e40.right, t2, n2));\n }\n tree_find_any_interval(e40, t2) {\n let n2 = false;\n return e40 != null \u0026\u0026 e40 !== this.nil_node \u0026\u0026 (e40.left === this.nil_node || e40.not_intersect_left_subtree(t2) || (n2 = this.tree_find_any_interval(e40.left, t2)), n2 || (n2 = e40.intersect(t2)), n2 || e40.right === this.nil_node || e40.not_intersect_right_subtree(t2) || (n2 = this.tree_find_any_interval(e40.right, t2))), n2;\n }\n local_minimum(e40) {\n let t2 = e40;\n for (;t2.left != null \u0026\u0026 t2.left !== this.nil_node; )\n t2 = t2.left;\n return t2;\n }\n local_maximum(e40) {\n let t2 = e40;\n for (;t2.right != null \u0026\u0026 t2.right !== this.nil_node; )\n t2 = t2.right;\n return t2;\n }\n tree_successor(e40) {\n let t2, n2, o3;\n if (e40.right !== this.nil_node)\n t2 = this.local_minimum(e40.right);\n else {\n for (n2 = e40, o3 = e40.parent;o3 != null \u0026\u0026 o3.right === n2; )\n n2 = o3, o3 = o3.parent;\n t2 = o3;\n }\n return t2;\n }\n rotate_left(e40) {\n const t2 = e40.right;\n e40.right = t2.left, t2.left !== this.nil_node \u0026\u0026 (t2.left.parent = e40), t2.parent = e40.parent, e40 === this.root ? this.root = t2 : e40 === e40.parent.left ? e40.parent.left = t2 : e40.parent.right = t2, t2.left = e40, e40.parent = t2, e40 !== null \u0026\u0026 e40 !== this.nil_node \u0026\u0026 e40.update_max(), t2 != null \u0026\u0026 t2 !== this.nil_node \u0026\u0026 t2.update_max();\n }\n rotate_right(e40) {\n const t2 = e40.left;\n e40.left = t2.right, t2.right !== this.nil_node \u0026\u0026 (t2.right.parent = e40), t2.parent = e40.parent, e40 === this.root ? this.root = t2 : e40 === e40.parent.left ? e40.parent.left = t2 : e40.parent.right = t2, t2.right = e40, e40.parent = t2, e40 !== null \u0026\u0026 e40 !== this.nil_node \u0026\u0026 e40.update_max(), t2 != null \u0026\u0026 t2 !== this.nil_node \u0026\u0026 t2.update_max();\n }\n tree_walk(e40, t2) {\n e40 != null \u0026\u0026 e40 !== this.nil_node \u0026\u0026 (this.tree_walk(e40.left, t2), t2(e40), this.tree_walk(e40.right, t2));\n }\n testRedBlackProperty() {\n let e40 = true;\n return this.tree_walk(this.root, function(t2) {\n t2.color === 1 \u0026\u0026 (t2.left.color === 0 \u0026\u0026 t2.right.color === 0 || (e40 = false));\n }), e40;\n }\n testBlackHeightProperty(e40) {\n let t2 = 0, n2 = 0, o3 = 0;\n if (e40.color === 0 \u0026\u0026 t2++, n2 = e40.left !== this.nil_node ? this.testBlackHeightProperty(e40.left) : 1, o3 = e40.right !== this.nil_node ? this.testBlackHeightProperty(e40.right) : 1, n2 !== o3)\n throw new Error(\"Red-black height property violated\");\n return t2 += n2, t2;\n }\n};\nvar yV = class extends Set {\n constructor(e40) {\n super(e40), this.index = new _V, this.forEach((e41) =\u003e this.index.insert(e41));\n }\n add(e40) {\n let t2 = this.size;\n const { key: n2, value: o3 } = e40, i3 = n2 || e40.box, r3 = o3 || e40;\n return super.add(r3), this.size \u003e t2 \u0026\u0026 this.index.insert(i3, r3), this;\n }\n delete(e40) {\n const { key: t2, value: n2 } = e40, o3 = t2 || e40.box, i3 = n2 || e40;\n let r3 = super.delete(i3);\n return r3 \u0026\u0026 this.index.remove(o3, i3), r3;\n }\n clear() {\n super.clear(), this.index = new _V;\n }\n search(e40) {\n return this.index.search(e40);\n }\n hit(e40) {\n let t2 = new kX.Box(e40.x - 1, e40.y - 1, e40.x + 1, e40.y + 1);\n return this.index.search(t2).filter((t3) =\u003e e40.on(t3));\n }\n svg() {\n return [...this].reduce((e40, t2) =\u003e e40 + t2.svg(), \"\");\n }\n};\nkX.PlanarSet = yV;\nvar bV = class {\n get name() {\n throw DX.CANNOT_INVOKE_ABSTRACT_METHOD;\n }\n get box() {\n throw DX.CANNOT_INVOKE_ABSTRACT_METHOD;\n }\n clone() {\n throw DX.CANNOT_INVOKE_ABSTRACT_METHOD;\n }\n translate(...e40) {\n return this.transform(new pV().translate(...e40));\n }\n rotate(e40, t2 = new kX.Point) {\n return this.transform(new pV().rotate(e40, t2.x, t2.y));\n }\n scale(e40, t2) {\n return this.transform(new pV().scale(e40, t2));\n }\n transform(...e40) {\n throw DX.CANNOT_INVOKE_ABSTRACT_METHOD;\n }\n toJSON() {\n return Object.assign({}, this, { name: this.name });\n }\n svg(e40 = {}) {\n throw DX.CANNOT_INVOKE_ABSTRACT_METHOD;\n }\n};\nkX.Point = class e40 extends bV {\n constructor(...e41) {\n if (super(), this.x = 0, this.y = 0, e41.length !== 0) {\n if (e41.length === 1 \u0026\u0026 e41[0] instanceof Array \u0026\u0026 e41[0].length === 2) {\n let t2 = e41[0];\n if (typeof t2[0] == \"number\" \u0026\u0026 typeof t2[1] == \"number\")\n return this.x = t2[0], void (this.y = t2[1]);\n }\n if (e41.length === 1 \u0026\u0026 e41[0] instanceof Object \u0026\u0026 e41[0].name === \"point\") {\n let { x: t2, y: n2 } = e41[0];\n return this.x = t2, void (this.y = n2);\n }\n if (e41.length === 2 \u0026\u0026 typeof e41[0] == \"number\" \u0026\u0026 typeof e41[1] == \"number\")\n return this.x = e41[0], void (this.y = e41[1]);\n throw DX.ILLEGAL_PARAMETERS;\n }\n }\n get box() {\n return new kX.Box(this.x, this.y, this.x, this.y);\n }\n clone() {\n return new kX.Point(this.x, this.y);\n }\n get vertices() {\n return [this.clone()];\n }\n equalTo(e41) {\n return kX.Utils.EQ(this.x, e41.x) \u0026\u0026 kX.Utils.EQ(this.y, e41.y);\n }\n lessThan(e41) {\n return !!kX.Utils.LT(this.y, e41.y) || !(!kX.Utils.EQ(this.y, e41.y) || !kX.Utils.LT(this.x, e41.x));\n }\n transform(e41) {\n return new kX.Point(e41.transform([this.x, this.y]));\n }\n projectionOn(e41) {\n if (this.equalTo(e41.pt))\n return this.clone();\n let t2 = new kX.Vector(this, e41.pt);\n if (kX.Utils.EQ_0(t2.cross(e41.norm)))\n return e41.pt.clone();\n let n2 = t2.dot(e41.norm), o3 = e41.norm.multiply(n2);\n return this.translate(o3);\n }\n leftTo(e41) {\n let t2 = new kX.Vector(e41.pt, this);\n return kX.Utils.GT(t2.dot(e41.norm), 0);\n }\n distanceTo(t2) {\n if (t2 instanceof e40) {\n let e41 = t2.x - this.x, n2 = t2.y - this.y;\n return [Math.sqrt(e41 * e41 + n2 * n2), new kX.Segment(this, t2)];\n }\n return t2 instanceof kX.Line ? kX.Distance.point2line(this, t2) : t2 instanceof kX.Circle ? kX.Distance.point2circle(this, t2) : t2 instanceof kX.Segment ? kX.Distance.point2segment(this, t2) : t2 instanceof kX.Arc ? kX.Distance.point2arc(this, t2) : t2 instanceof kX.Polygon ? kX.Distance.point2polygon(this, t2) : t2 instanceof kX.PlanarSet ? kX.Distance.shape2planarSet(this, t2) : t2 instanceof kX.Multiline ? kX.Distance.shape2multiline(this, t2) : undefined;\n }\n on(e41) {\n if (e41 instanceof kX.Point)\n return this.equalTo(e41);\n if (e41.contains \u0026\u0026 e41.contains instanceof Function)\n return e41.contains(this);\n throw kX.Errors.UNSUPPORTED_SHAPE_TYPE;\n }\n get name() {\n return \"point\";\n }\n svg(e41 = {}) {\n const t2 = e41.r ?? 3;\n return `\n\u003ccircle cx=\"${this.x}\" cy=\"${this.y}\" r=\"${t2}\"\n ${FX({ fill: \"red\", ...e41 })} /\u003e`;\n }\n};\nkX.point = (...e41) =\u003e new kX.Point(...e41);\nkX.Vector = class extends bV {\n constructor(...e41) {\n if (super(), this.x = 0, this.y = 0, e41.length !== 0) {\n if (e41.length === 1 \u0026\u0026 e41[0] instanceof Array \u0026\u0026 e41[0].length === 2) {\n let t2 = e41[0];\n if (typeof t2[0] == \"number\" \u0026\u0026 typeof t2[1] == \"number\")\n return this.x = t2[0], void (this.y = t2[1]);\n }\n if (e41.length === 1 \u0026\u0026 e41[0] instanceof Object \u0026\u0026 e41[0].name === \"vector\") {\n let { x: t2, y: n2 } = e41[0];\n return this.x = t2, void (this.y = n2);\n }\n if (e41.length === 1 \u0026\u0026 e41[0] instanceof Object \u0026\u0026 e41[0].name === \"segment\") {\n let { start: t2, end: n2 } = e41[0];\n return this.x = n2.x - t2.x, void (this.y = n2.y - t2.y);\n }\n if (e41.length === 2) {\n let t2 = e41[0], n2 = e41[1];\n if (typeof t2 == \"number\" \u0026\u0026 typeof n2 == \"number\")\n return this.x = t2, void (this.y = n2);\n if (t2 instanceof kX.Point \u0026\u0026 n2 instanceof kX.Point)\n return this.x = n2.x - t2.x, void (this.y = n2.y - t2.y);\n }\n throw DX.ILLEGAL_PARAMETERS;\n }\n }\n clone() {\n return new kX.Vector(this.x, this.y);\n }\n get slope() {\n let e41 = Math.atan2(this.y, this.x);\n return e41 \u003c 0 \u0026\u0026 (e41 = 2 * Math.PI + e41), e41;\n }\n get length() {\n return Math.sqrt(this.dot(this));\n }\n isZeroLength() {\n return kX.Utils.EQ_0(this.length);\n }\n equalTo(e41) {\n return kX.Utils.EQ(this.x, e41.x) \u0026\u0026 kX.Utils.EQ(this.y, e41.y);\n }\n multiply(e41) {\n return new kX.Vector(e41 * this.x, e41 * this.y);\n }\n dot(e41) {\n return this.x * e41.x + this.y * e41.y;\n }\n cross(e41) {\n return this.x * e41.y - this.y * e41.x;\n }\n normalize() {\n if (this.isZeroLength())\n throw DX.ZERO_DIVISION;\n return new kX.Vector(this.x / this.length, this.y / this.length);\n }\n rotate(e41, t2 = new kX.Point) {\n if (t2.x === 0 \u0026\u0026 t2.y === 0)\n return this.transform(new pV().rotate(e41));\n throw DX.OPERATION_IS_NOT_SUPPORTED;\n }\n transform(e41) {\n return new kX.Vector(e41.transform([this.x, this.y]));\n }\n rotate90CCW() {\n return new kX.Vector(-this.y, this.x);\n }\n rotate90CW() {\n return new kX.Vector(this.y, -this.x);\n }\n invert() {\n return new kX.Vector(-this.x, -this.y);\n }\n add(e41) {\n return new kX.Vector(this.x + e41.x, this.y + e41.y);\n }\n subtract(e41) {\n return new kX.Vector(this.x - e41.x, this.y - e41.y);\n }\n angleTo(e41) {\n let t2 = this.normalize(), n2 = e41.normalize(), o3 = Math.atan2(t2.cross(n2), t2.dot(n2));\n return o3 \u003c 0 \u0026\u0026 (o3 += 2 * Math.PI), o3;\n }\n projectionOn(e41) {\n let t2 = e41.normalize(), n2 = this.dot(t2);\n return t2.multiply(n2);\n }\n get name() {\n return \"vector\";\n }\n};\nvar xV = (...e41) =\u003e new kX.Vector(...e41);\nkX.vector = xV;\nkX.Segment = class e41 extends bV {\n constructor(...e42) {\n if (super(), this.ps = new kX.Point, this.pe = new kX.Point, e42.length !== 0) {\n if (e42.length === 1 \u0026\u0026 e42[0] instanceof Array \u0026\u0026 e42[0].length === 4) {\n let t2 = e42[0];\n return this.ps = new kX.Point(t2[0], t2[1]), void (this.pe = new kX.Point(t2[2], t2[3]));\n }\n if (e42.length === 1 \u0026\u0026 e42[0] instanceof Object \u0026\u0026 e42[0].name === \"segment\") {\n let { ps: t2, pe: n2 } = e42[0];\n return this.ps = new kX.Point(t2.x, t2.y), void (this.pe = new kX.Point(n2.x, n2.y));\n }\n if (!(e42.length === 1 \u0026\u0026 e42[0] instanceof kX.Point)) {\n if (e42.length === 2 \u0026\u0026 e42[0] instanceof kX.Point \u0026\u0026 e42[1] instanceof kX.Point)\n return this.ps = e42[0].clone(), void (this.pe = e42[1].clone());\n if (e42.length === 4)\n return this.ps = new kX.Point(e42[0], e42[1]), void (this.pe = new kX.Point(e42[2], e42[3]));\n throw DX.ILLEGAL_PARAMETERS;\n }\n this.ps = e42[0].clone();\n }\n }\n clone() {\n return new kX.Segment(this.start, this.end);\n }\n get start() {\n return this.ps;\n }\n get end() {\n return this.pe;\n }\n get vertices() {\n return [this.ps.clone(), this.pe.clone()];\n }\n get length() {\n return this.start.distanceTo(this.end)[0];\n }\n get slope() {\n return new kX.Vector(this.start, this.end).slope;\n }\n get box() {\n return new kX.Box(Math.min(this.start.x, this.end.x), Math.min(this.start.y, this.end.y), Math.max(this.start.x, this.end.x), Math.max(this.start.y, this.end.y));\n }\n equalTo(e42) {\n return this.ps.equalTo(e42.ps) \u0026\u0026 this.pe.equalTo(e42.pe);\n }\n contains(e42) {\n return kX.Utils.EQ_0(this.distanceToPoint(e42));\n }\n intersect(e42) {\n return e42 instanceof kX.Point ? this.contains(e42) ? [e42] : [] : e42 instanceof kX.Line ? HX(this, e42) : e42 instanceof kX.Ray ? hH(e42, this) : e42 instanceof kX.Segment ? VX(this, e42) : e42 instanceof kX.Circle ? GX(this, e42) : e42 instanceof kX.Box ? function(e43, t2) {\n let n2 = [];\n for (let o3 of t2.toSegments()) {\n let t3 = VX(o3, e43);\n for (let e44 of t3)\n n2.push(e44);\n }\n return n2;\n }(this, e42) : e42 instanceof kX.Arc ? UX(this, e42) : e42 instanceof kX.Polygon ? nH(this, e42) : e42 instanceof kX.Multiline ? fH(this, e42) : undefined;\n }\n distanceTo(e42) {\n if (e42 instanceof kX.Point) {\n let [t2, n2] = kX.Distance.point2segment(e42, this);\n return n2 = n2.reverse(), [t2, n2];\n }\n if (e42 instanceof kX.Circle) {\n let [t2, n2] = kX.Distance.segment2circle(this, e42);\n return [t2, n2];\n }\n if (e42 instanceof kX.Line) {\n let [t2, n2] = kX.Distance.segment2line(this, e42);\n return [t2, n2];\n }\n if (e42 instanceof kX.Segment) {\n let [t2, n2] = kX.Distance.segment2segment(this, e42);\n return [t2, n2];\n }\n if (e42 instanceof kX.Arc) {\n let [t2, n2] = kX.Distance.segment2arc(this, e42);\n return [t2, n2];\n }\n if (e42 instanceof kX.Polygon) {\n let [t2, n2] = kX.Distance.shape2polygon(this, e42);\n return [t2, n2];\n }\n if (e42 instanceof kX.PlanarSet) {\n let [t2, n2] = kX.Distance.shape2planarSet(this, e42);\n return [t2, n2];\n }\n if (e42 instanceof kX.Multiline)\n return kX.Distance.shape2multiline(this, e42);\n }\n tangentInStart() {\n return new kX.Vector(this.start, this.end).normalize();\n }\n tangentInEnd() {\n return new kX.Vector(this.end, this.start).normalize();\n }\n reverse() {\n return new e41(this.end, this.start);\n }\n split(e42) {\n return this.start.equalTo(e42) ? [null, this.clone()] : this.end.equalTo(e42) ? [this.clone(), null] : [new kX.Segment(this.start, e42), new kX.Segment(e42, this.end)];\n }\n middle() {\n return new kX.Point((this.start.x + this.end.x) / 2, (this.start.y + this.end.y) / 2);\n }\n pointAtLength(e42) {\n if (e42 \u003e this.length || e42 \u003c 0)\n return null;\n if (e42 == 0)\n return this.start;\n if (e42 == this.length)\n return this.end;\n let t2 = e42 / this.length;\n return new kX.Point((this.end.x - this.start.x) * t2 + this.start.x, (this.end.y - this.start.y) * t2 + this.start.y);\n }\n distanceToPoint(e42) {\n let [t2, ...n2] = kX.Distance.point2segment(e42, this);\n return t2;\n }\n definiteIntegral(e42 = 0) {\n return (this.end.x - this.start.x) * (this.start.y - e42 + (this.end.y - e42)) / 2;\n }\n transform(t2 = new kX.Matrix) {\n return new e41(this.ps.transform(t2), this.pe.transform(t2));\n }\n isZeroLength() {\n return this.ps.equalTo(this.pe);\n }\n sortPoints(e42) {\n return new kX.Line(this.start, this.end).sortPoints(e42);\n }\n get name() {\n return \"segment\";\n }\n svg(e42 = {}) {\n return `\n\u003cline x1=\"${this.start.x}\" y1=\"${this.start.y}\" x2=\"${this.end.x}\" y2=\"${this.end.y}\" ${FX(e42)} /\u003e`;\n }\n};\nkX.segment = (...e42) =\u003e new kX.Segment(...e42);\nvar { vector: vV } = kX;\nkX.Line = class e42 extends bV {\n constructor(...t2) {\n if (super(), this.pt = new kX.Point, this.norm = new kX.Vector(0, 1), t2.length !== 0) {\n if (t2.length === 1 \u0026\u0026 t2[0] instanceof Object \u0026\u0026 t2[0].name === \"line\") {\n let { pt: e43, norm: n2 } = t2[0];\n return this.pt = new kX.Point(e43), void (this.norm = new kX.Vector(n2));\n }\n if (t2.length === 2) {\n let n2 = t2[0], o3 = t2[1];\n if (n2 instanceof kX.Point \u0026\u0026 o3 instanceof kX.Point)\n return this.pt = n2, this.norm = e42.points2norm(n2, o3), void (this.norm.dot(vV(this.pt.x, this.pt.y)) \u003e= 0 \u0026\u0026 this.norm.invert());\n if (n2 instanceof kX.Point \u0026\u0026 o3 instanceof kX.Vector) {\n if (kX.Utils.EQ_0(o3.x) \u0026\u0026 kX.Utils.EQ_0(o3.y))\n throw DX.ILLEGAL_PARAMETERS;\n return this.pt = n2.clone(), this.norm = o3.clone(), this.norm = this.norm.normalize(), void (this.norm.dot(vV(this.pt.x, this.pt.y)) \u003e= 0 \u0026\u0026 this.norm.invert());\n }\n if (n2 instanceof kX.Vector \u0026\u0026 o3 instanceof kX.Point) {\n if (kX.Utils.EQ_0(n2.x) \u0026\u0026 kX.Utils.EQ_0(n2.y))\n throw DX.ILLEGAL_PARAMETERS;\n return this.pt = o3.clone(), this.norm = n2.clone(), this.norm = this.norm.normalize(), void (this.norm.dot(vV(this.pt.x, this.pt.y)) \u003e= 0 \u0026\u0026 this.norm.invert());\n }\n }\n throw DX.ILLEGAL_PARAMETERS;\n }\n }\n clone() {\n return new kX.Line(this.pt, this.norm);\n }\n get start() {}\n get end() {}\n get length() {\n return Number.POSITIVE_INFINITY;\n }\n get box() {\n return new kX.Box(Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY);\n }\n get middle() {}\n get slope() {\n return new kX.Vector(this.norm.y, -this.norm.x).slope;\n }\n get standard() {\n return [this.norm.x, this.norm.y, this.norm.dot(vV(this.pt.x, this.pt.y))];\n }\n parallelTo(e43) {\n return kX.Utils.EQ_0(this.norm.cross(e43.norm));\n }\n incidentTo(e43) {\n return this.parallelTo(e43) \u0026\u0026 this.pt.on(e43);\n }\n contains(e43) {\n if (this.pt.equalTo(e43))\n return true;\n let t2 = new kX.Vector(this.pt, e43);\n return kX.Utils.EQ_0(this.norm.dot(t2));\n }\n coord(e43) {\n return vV(e43.x, e43.y).cross(this.norm);\n }\n intersect(e43) {\n return e43 instanceof kX.Point ? this.contains(e43) ? [e43] : [] : e43 instanceof kX.Line ? jX(this, e43) : e43 instanceof kX.Ray ? pH(e43, this) : e43 instanceof kX.Circle ? $X(this, e43) : e43 instanceof kX.Box ? YX(this, e43) : e43 instanceof kX.Segment ? HX(e43, this) : e43 instanceof kX.Arc ? XX(this, e43) : e43 instanceof kX.Polygon ? iH(this, e43) : e43 instanceof kX.Multiline ? fH(this, e43) : undefined;\n }\n distanceTo(e43) {\n if (e43 instanceof kX.Point) {\n let [t2, n2] = kX.Distance.point2line(e43, this);\n return n2 = n2.reverse(), [t2, n2];\n }\n if (e43 instanceof kX.Circle) {\n let [t2, n2] = kX.Distance.circle2line(e43, this);\n return n2 = n2.reverse(), [t2, n2];\n }\n if (e43 instanceof kX.Segment) {\n let [t2, n2] = kX.Distance.segment2line(e43, this);\n return [t2, n2.reverse()];\n }\n if (e43 instanceof kX.Arc) {\n let [t2, n2] = kX.Distance.arc2line(e43, this);\n return [t2, n2.reverse()];\n }\n if (e43 instanceof kX.Polygon) {\n let [t2, n2] = kX.Distance.shape2polygon(this, e43);\n return [t2, n2];\n }\n }\n split(e43) {\n if (e43 instanceof kX.Point)\n return [new kX.Ray(e43, this.norm), new kX.Ray(e43, this.norm)];\n {\n let t2 = new kX.Multiline([this]), n2 = this.sortPoints(e43);\n return t2.split(n2), t2.toShapes();\n }\n }\n rotate(e43, t2 = new kX.Point) {\n return new kX.Line(this.pt.rotate(e43, t2), this.norm.rotate(e43));\n }\n transform(e43) {\n return new kX.Line(this.pt.transform(e43), this.norm.clone());\n }\n sortPoints(e43) {\n return e43.slice().sort((e44, t2) =\u003e this.coord(e44) \u003c this.coord(t2) ? -1 : this.coord(e44) \u003e this.coord(t2) ? 1 : 0);\n }\n get name() {\n return \"line\";\n }\n svg(e43, t2 = {}) {\n let n2 = YX(this, e43);\n if (n2.length === 0)\n return \"\";\n let o3 = n2[0], i3 = n2.length === 2 ? n2[1] : n2.find((e44) =\u003e !e44.equalTo(o3));\n return i3 === undefined \u0026\u0026 (i3 = o3), new kX.Segment(o3, i3).svg(t2);\n }\n static points2norm(e43, t2) {\n if (e43.equalTo(t2))\n throw DX.ILLEGAL_PARAMETERS;\n return new kX.Vector(e43, t2).normalize().rotate90CCW();\n }\n};\nkX.line = (...e43) =\u003e new kX.Line(...e43);\nkX.Circle = class extends bV {\n constructor(...e43) {\n if (super(), this.pc = new kX.Point, this.r = 1, e43.length === 1 \u0026\u0026 e43[0] instanceof Object \u0026\u0026 e43[0].name === \"circle\") {\n let { pc: t2, r: n2 } = e43[0];\n this.pc = new kX.Point(t2), this.r = n2;\n } else {\n let [t2, n2] = [...e43];\n t2 \u0026\u0026 t2 instanceof kX.Point \u0026\u0026 (this.pc = t2.clone()), n2 !== undefined \u0026\u0026 (this.r = n2);\n }\n }\n clone() {\n return new kX.Circle(this.pc.clone(), this.r);\n }\n get center() {\n return this.pc;\n }\n get box() {\n return new kX.Box(this.pc.x - this.r, this.pc.y - this.r, this.pc.x + this.r, this.pc.y + this.r);\n }\n contains(e43) {\n return e43 instanceof kX.Point ? kX.Utils.LE(e43.distanceTo(this.center)[0], this.r) : e43 instanceof kX.Segment ? kX.Utils.LE(e43.start.distanceTo(this.center)[0], this.r) \u0026\u0026 kX.Utils.LE(e43.end.distanceTo(this.center)[0], this.r) : e43 instanceof kX.Arc ? this.intersect(e43).length === 0 \u0026\u0026 kX.Utils.LE(e43.start.distanceTo(this.center)[0], this.r) \u0026\u0026 kX.Utils.LE(e43.end.distanceTo(this.center)[0], this.r) : e43 instanceof kX.Circle ? this.intersect(e43).length === 0 \u0026\u0026 kX.Utils.LE(e43.r, this.r) \u0026\u0026 kX.Utils.LE(e43.center.distanceTo(this.center)[0], this.r) : undefined;\n }\n toArc(e43 = true) {\n return new kX.Arc(this.center, this.r, Math.PI, -Math.PI, e43);\n }\n scale(e43, t2) {\n if (e43 !== t2)\n throw DX.OPERATION_IS_NOT_SUPPORTED;\n if (this.pc.x !== 0 || this.pc.y !== 0)\n throw DX.OPERATION_IS_NOT_SUPPORTED;\n return new kX.Circle(this.pc, this.r * e43);\n }\n transform(e43 = new kX.Matrix) {\n return new kX.Circle(this.pc.transform(e43), this.r);\n }\n intersect(e43) {\n return e43 instanceof kX.Point ? this.contains(e43) ? [e43] : [] : e43 instanceof kX.Line ? $X(e43, this) : e43 instanceof kX.Ray ? uH(e43, this) : e43 instanceof kX.Segment ? GX(e43, this) : e43 instanceof kX.Circle ? ZX(e43, this) : e43 instanceof kX.Box ? function(e44, t2) {\n let n2 = [];\n for (let o3 of t2.toSegments()) {\n let t3 = GX(o3, e44);\n for (let e45 of t3)\n n2.push(e45);\n }\n return n2;\n }(this, e43) : e43 instanceof kX.Arc ? JX(e43, this) : e43 instanceof kX.Polygon ? rH(this, e43) : e43 instanceof kX.Multiline ? fH(this, e43) : undefined;\n }\n distanceTo(e43) {\n if (e43 instanceof kX.Point) {\n let [t2, n2] = kX.Distance.point2circle(e43, this);\n return n2 = n2.reverse(), [t2, n2];\n }\n if (e43 instanceof kX.Circle) {\n let [t2, n2] = kX.Distance.circle2circle(this, e43);\n return [t2, n2];\n }\n if (e43 instanceof kX.Line) {\n let [t2, n2] = kX.Distance.circle2line(this, e43);\n return [t2, n2];\n }\n if (e43 instanceof kX.Segment) {\n let [t2, n2] = kX.Distance.segment2circle(e43, this);\n return n2 = n2.reverse(), [t2, n2];\n }\n if (e43 instanceof kX.Arc) {\n let [t2, n2] = kX.Distance.arc2circle(e43, this);\n return n2 = n2.reverse(), [t2, n2];\n }\n if (e43 instanceof kX.Polygon) {\n let [t2, n2] = kX.Distance.shape2polygon(this, e43);\n return [t2, n2];\n }\n if (e43 instanceof kX.PlanarSet) {\n let [t2, n2] = kX.Distance.shape2planarSet(this, e43);\n return [t2, n2];\n }\n if (e43 instanceof kX.Multiline) {\n let [t2, n2] = kX.Distance.shape2multiline(this, e43);\n return [t2, n2];\n }\n }\n get name() {\n return \"circle\";\n }\n svg(e43 = {}) {\n return `\n\u003ccircle cx=\"${this.pc.x}\" cy=\"${this.pc.y}\" r=\"${this.r}\"\n ${FX({ fill: \"none\", ...e43 })} /\u003e`;\n }\n};\nkX.circle = (...e43) =\u003e new kX.Circle(...e43);\nkX.Arc = class extends bV {\n constructor(...e43) {\n if (super(), this.pc = new kX.Point, this.r = 1, this.startAngle = 0, this.endAngle = 2 * Math.PI, this.counterClockwise = true, e43.length !== 0)\n if (e43.length === 1 \u0026\u0026 e43[0] instanceof Object \u0026\u0026 e43[0].name === \"arc\") {\n let { pc: t2, r: n2, startAngle: o3, endAngle: i3, counterClockwise: r3 } = e43[0];\n this.pc = new kX.Point(t2.x, t2.y), this.r = n2, this.startAngle = o3, this.endAngle = i3, this.counterClockwise = r3;\n } else {\n let [t2, n2, o3, i3, r3] = [...e43];\n t2 \u0026\u0026 t2 instanceof kX.Point \u0026\u0026 (this.pc = t2.clone()), n2 !== undefined \u0026\u0026 (this.r = n2), o3 !== undefined \u0026\u0026 (this.startAngle = o3), i3 !== undefined \u0026\u0026 (this.endAngle = i3), r3 !== undefined \u0026\u0026 (this.counterClockwise = r3);\n }\n }\n clone() {\n return new kX.Arc(this.pc.clone(), this.r, this.startAngle, this.endAngle, this.counterClockwise);\n }\n get sweep() {\n let e43 = this.startAngle, t2 = this.endAngle;\n if (kX.Utils.EQ(Math.abs(e43 - t2), kX.PIx2))\n return kX.PIx2;\n Math.abs(e43) \u003e kX.PIx2 \u0026\u0026 (e43 -= Math.trunc(e43 / kX.PIx2) * kX.PIx2), e43 \u003c 0 \u0026\u0026 (e43 += kX.PIx2), Math.abs(t2) \u003e kX.PIx2 \u0026\u0026 (t2 -= Math.trunc(t2 / kX.PIx2) * kX.PIx2), t2 \u003c 0 \u0026\u0026 (t2 += kX.PIx2);\n let n2 = this.counterClockwise ? t2 - e43 : e43 - t2;\n return n2 \u003c 0 \u0026\u0026 (n2 += kX.PIx2), n2;\n }\n get start() {\n return new kX.Point(this.pc.x + this.r, this.pc.y).rotate(this.startAngle, this.pc);\n }\n get end() {\n return new kX.Point(this.pc.x + this.r, this.pc.y).rotate(this.endAngle, this.pc);\n }\n get center() {\n return this.pc.clone();\n }\n get vertices() {\n return [this.start.clone(), this.end.clone()];\n }\n get length() {\n return Math.abs(this.sweep * this.r);\n }\n get box() {\n let e43 = this.breakToFunctional().reduce((e44, t2) =\u003e e44.merge(t2.start.box), new kX.Box);\n return e43 = e43.merge(this.end.box), e43;\n }\n contains(e43) {\n if (!kX.Utils.EQ(this.pc.distanceTo(e43)[0], this.r))\n return false;\n if (e43.equalTo(this.start))\n return true;\n let t2 = new kX.Vector(this.pc, e43).slope, n2 = new kX.Arc(this.pc, this.r, this.startAngle, t2, this.counterClockwise);\n return kX.Utils.LE(n2.length, this.length);\n }\n split(e43) {\n if (this.start.equalTo(e43))\n return [null, this.clone()];\n if (this.end.equalTo(e43))\n return [this.clone(), null];\n let t2 = new kX.Vector(this.pc, e43).slope;\n return [new kX.Arc(this.pc, this.r, this.startAngle, t2, this.counterClockwise), new kX.Arc(this.pc, this.r, t2, this.endAngle, this.counterClockwise)];\n }\n middle() {\n let e43 = this.counterClockwise ? this.startAngle + this.sweep / 2 : this.startAngle - this.sweep / 2;\n return new kX.Arc(this.pc, this.r, this.startAngle, e43, this.counterClockwise).end;\n }\n pointAtLength(e43) {\n if (e43 \u003e this.length || e43 \u003c 0)\n return null;\n if (e43 === 0)\n return this.start;\n if (e43 === this.length)\n return this.end;\n let t2 = e43 / this.length, n2 = this.counterClockwise ? this.startAngle + this.sweep * t2 : this.startAngle - this.sweep * t2;\n return new kX.Arc(this.pc, this.r, this.startAngle, n2, this.counterClockwise).end;\n }\n chordHeight() {\n return (1 - Math.cos(Math.abs(this.sweep / 2))) * this.r;\n }\n intersect(e43) {\n return e43 instanceof kX.Point ? this.contains(e43) ? [e43] : [] : e43 instanceof kX.Line ? XX(e43, this) : e43 instanceof kX.Ray ? dH(e43, this) : e43 instanceof kX.Circle ? JX(this, e43) : e43 instanceof kX.Segment ? UX(e43, this) : e43 instanceof kX.Box ? function(e44, t2) {\n let n2 = [];\n for (let o3 of t2.toSegments()) {\n let t3 = UX(o3, e44);\n for (let e45 of t3)\n n2.push(e45);\n }\n return n2;\n }(this, e43) : e43 instanceof kX.Arc ? qX(this, e43) : e43 instanceof kX.Polygon ? oH(this, e43) : e43 instanceof kX.Multiline ? fH(this, e43) : undefined;\n }\n distanceTo(e43) {\n if (e43 instanceof kX.Point) {\n let [t2, n2] = kX.Distance.point2arc(e43, this);\n return n2 = n2.reverse(), [t2, n2];\n }\n if (e43 instanceof kX.Circle) {\n let [t2, n2] = kX.Distance.arc2circle(this, e43);\n return [t2, n2];\n }\n if (e43 instanceof kX.Line) {\n let [t2, n2] = kX.Distance.arc2line(this, e43);\n return [t2, n2];\n }\n if (e43 instanceof kX.Segment) {\n let [t2, n2] = kX.Distance.segment2arc(e43, this);\n return n2 = n2.reverse(), [t2, n2];\n }\n if (e43 instanceof kX.Arc) {\n let [t2, n2] = kX.Distance.arc2arc(this, e43);\n return [t2, n2];\n }\n if (e43 instanceof kX.Polygon) {\n let [t2, n2] = kX.Distance.shape2polygon(this, e43);\n return [t2, n2];\n }\n if (e43 instanceof kX.PlanarSet) {\n let [t2, n2] = kX.Distance.shape2planarSet(this, e43);\n return [t2, n2];\n }\n if (e43 instanceof kX.Multiline)\n return kX.Distance.shape2multiline(this, e43);\n }\n breakToFunctional() {\n let e43 = [], t2 = [0, Math.PI / 2, Math.PI, 3 * Math.PI / 2], n2 = this.startAngle, o3 = this.endAngle;\n kX.Utils.EQ(Math.abs(n2 - o3), kX.PIx2) \u0026\u0026 (o3 = n2), Math.abs(n2) \u003e kX.PIx2 \u0026\u0026 (n2 -= Math.trunc(n2 / kX.PIx2) * kX.PIx2), n2 \u003c 0 \u0026\u0026 (n2 += kX.PIx2), Math.abs(o3) \u003e kX.PIx2 \u0026\u0026 (o3 -= Math.trunc(o3 / kX.PIx2) * kX.PIx2), o3 \u003c 0 \u0026\u0026 (o3 += kX.PIx2);\n let i3, r3, s2, a3 = n2;\n this.counterClockwise ? (r3 = Math.ceil(n2 / (Math.PI / 2)) % 4, s2 = 1) : (r3 = Math.floor(n2 / (Math.PI / 2)) % 4, s2 = -1);\n for (let o4 = 0, c3 = r3;o4 \u003c 4; o4++, c3 = (c3 + s2 + 4) % 4) {\n if (i3 = t2[c3], i3 === a3)\n continue;\n let o5 = this.counterClockwise ? i3 - n2 : n2 - i3;\n if (o5 \u003c 0 \u0026\u0026 (o5 += kX.PIx2), o5 \u003e this.sweep)\n break;\n e43.push(new kX.Arc(this.pc, this.r, a3, i3, this.counterClockwise)), a3 = i3;\n }\n return e43.length === 0 ? (e43.push(this), e43) : (i3 = o3, a3 !== i3 \u0026\u0026 e43.push(new kX.Arc(this.pc, this.r, a3, i3, this.counterClockwise)), e43);\n }\n tangentInStart() {\n let e43 = new kX.Vector(this.pc, this.start), t2 = this.counterClockwise ? Math.PI / 2 : -Math.PI / 2;\n return e43.rotate(t2).normalize();\n }\n tangentInEnd() {\n let e43 = new kX.Vector(this.pc, this.end), t2 = this.counterClockwise ? -Math.PI / 2 : Math.PI / 2;\n return e43.rotate(t2).normalize();\n }\n reverse() {\n return new kX.Arc(this.pc, this.r, this.endAngle, this.startAngle, !this.counterClockwise);\n }\n transform(e43 = new kX.Matrix) {\n let t2 = this.start.transform(e43), n2 = this.end.transform(e43), o3 = this.pc.transform(e43), i3 = this.counterClockwise;\n return e43.a * e43.d \u003c 0 \u0026\u0026 (i3 = !i3), kX.Arc.arcSE(o3, t2, n2, i3);\n }\n static arcSE(e43, t2, n2, o3) {\n let { vector: i3 } = kX, r3 = i3(e43, t2).slope, s2 = i3(e43, n2).slope;\n kX.Utils.EQ(r3, s2) \u0026\u0026 (s2 += 2 * Math.PI, o3 = true);\n let a3 = i3(e43, t2).length;\n return new kX.Arc(e43, a3, r3, s2, o3);\n }\n definiteIntegral(e43 = 0) {\n return this.breakToFunctional().reduce((t2, n2) =\u003e t2 + n2.circularSegmentDefiniteIntegral(e43), 0);\n }\n circularSegmentDefiniteIntegral(e43) {\n let t2 = new kX.Segment(this.start, this.end).definiteIntegral(e43), n2 = kX.Utils.EQ(this.sweep, kX.PIx2) ? 0 : this.circularSegmentArea();\n return this.counterClockwise ? t2 - n2 : t2 + n2;\n }\n circularSegmentArea() {\n return 0.5 * this.r * this.r * (this.sweep - Math.sin(this.sweep));\n }\n sortPoints(e43) {\n let { vector: t2 } = kX;\n return e43.slice().sort((e44, n2) =\u003e {\n let o3 = t2(this.pc, e44).slope, i3 = t2(this.pc, n2).slope;\n return o3 \u003c i3 ? -1 : o3 \u003e i3 ? 1 : 0;\n });\n }\n get name() {\n return \"arc\";\n }\n svg(e43 = {}) {\n let t2 = this.sweep \u003c= Math.PI ? \"0\" : \"1\", n2 = this.counterClockwise ? \"1\" : \"0\";\n if (kX.Utils.EQ(this.sweep, 2 * Math.PI)) {\n return new kX.Circle(this.pc, this.r).svg(e43);\n }\n return `\n\u003cpath d=\"M${this.start.x},${this.start.y}\n A${this.r},${this.r} 0 ${t2},${n2} ${this.end.x},${this.end.y}\"\n ${FX({ fill: \"none\", ...e43 })} /\u003e`;\n }\n};\nkX.arc = (...e43) =\u003e new kX.Arc(...e43);\nkX.Box = class e43 extends bV {\n constructor(e44 = undefined, t2 = undefined, n2 = undefined, o3 = undefined) {\n super(), this.xmin = e44, this.ymin = t2, this.xmax = n2, this.ymax = o3;\n }\n clone() {\n return new e43(this.xmin, this.ymin, this.xmax, this.ymax);\n }\n get low() {\n return new kX.Point(this.xmin, this.ymin);\n }\n get high() {\n return new kX.Point(this.xmax, this.ymax);\n }\n get max() {\n return this.clone();\n }\n get center() {\n return new kX.Point((this.xmin + this.xmax) / 2, (this.ymin + this.ymax) / 2);\n }\n get width() {\n return Math.abs(this.xmax - this.xmin);\n }\n get height() {\n return Math.abs(this.ymax - this.ymin);\n }\n get box() {\n return this.clone();\n }\n not_intersect(e44) {\n return this.xmax \u003c e44.xmin || this.xmin \u003e e44.xmax || this.ymax \u003c e44.ymin || this.ymin \u003e e44.ymax;\n }\n intersect(e44) {\n return !this.not_intersect(e44);\n }\n merge(t2) {\n return new e43(this.xmin === undefined ? t2.xmin : Math.min(this.xmin, t2.xmin), this.ymin === undefined ? t2.ymin : Math.min(this.ymin, t2.ymin), this.xmax === undefined ? t2.xmax : Math.max(this.xmax, t2.xmax), this.ymax === undefined ? t2.ymax : Math.max(this.ymax, t2.ymax));\n }\n less_than(e44) {\n return !!this.low.lessThan(e44.low) || !(!this.low.equalTo(e44.low) || !this.high.lessThan(e44.high));\n }\n equal_to(e44) {\n return this.low.equalTo(e44.low) \u0026\u0026 this.high.equalTo(e44.high);\n }\n output() {\n return this.clone();\n }\n comparable_less_than(e44, t2) {\n return e44.lessThan(t2);\n }\n set(e44, t2, n2, o3) {\n this.xmin = e44, this.ymin = t2, this.xmax = n2, this.ymax = o3;\n }\n extend(t2) {\n return t2 \u003c= 0 ? this.clone() : new e43(this.xmin - t2, this.ymin - t2, this.xmax + t2, this.ymax + t2);\n }\n toPoints() {\n return [new kX.Point(this.xmin, this.ymin), new kX.Point(this.xmax, this.ymin), new kX.Point(this.xmax, this.ymax), new kX.Point(this.xmin, this.ymax)];\n }\n toSegments() {\n let e44 = this.toPoints();\n return [new kX.Segment(e44[0], e44[1]), new kX.Segment(e44[1], e44[2]), new kX.Segment(e44[2], e44[3]), new kX.Segment(e44[3], e44[0])];\n }\n rotate(e44, t2 = new kX.Point) {\n throw DX.OPERATION_IS_NOT_SUPPORTED;\n }\n transform(t2 = new kX.Matrix) {\n return this.toPoints().map((e44) =\u003e e44.transform(t2)).reduce((e44, t3) =\u003e e44.merge(t3.box), new e43);\n }\n contains(e44) {\n return e44 instanceof kX.Point ? e44.x \u003e= this.xmin \u0026\u0026 e44.x \u003c= this.xmax \u0026\u0026 e44.y \u003e= this.ymin \u0026\u0026 e44.y \u003c= this.ymax : e44 instanceof kX.Segment ? e44.vertices.every((e45) =\u003e this.contains(e45)) : e44 instanceof kX.Box ? e44.toSegments().every((e45) =\u003e this.contains(e45)) : e44 instanceof kX.Circle ? this.contains(e44.box) : e44 instanceof kX.Arc ? e44.vertices.every((e45) =\u003e this.contains(e45)) \u0026\u0026 this.toSegments().every((t2) =\u003e UX(t2, e44).length === 0) : !(e44 instanceof kX.Line || e44 instanceof kX.Ray) \u0026\u0026 (e44 instanceof kX.Multiline ? e44.toShapes().every((e45) =\u003e this.contains(e45)) : e44 instanceof kX.Polygon ? this.contains(e44.box) : undefined);\n }\n distanceTo(e44) {\n const t2 = this.toSegments().map((t3) =\u003e t3.distanceTo(e44));\n let n2 = [Number.MAX_SAFE_INTEGER, null];\n return t2.forEach((e45) =\u003e {\n e45[0] \u003c n2[0] \u0026\u0026 (n2 = e45);\n }), n2;\n }\n get name() {\n return \"box\";\n }\n svg(e44 = {}) {\n const t2 = this.xmax - this.xmin, n2 = this.ymax - this.ymin;\n return `\n\u003crect x=\"${this.xmin}\" y=\"${this.ymin}\" width=\"${t2}\" height=\"${n2}\"\n ${FX({ fill: \"none\", ...e44 })} /\u003e`;\n }\n};\nkX.box = (...e44) =\u003e new kX.Box(...e44);\nkX.Edge = class {\n constructor(e44) {\n this.shape = e44, this.next = undefined, this.prev = undefined, this.face = undefined, this.arc_length = 0, this.bvStart = undefined, this.bvEnd = undefined, this.bv = undefined, this.overlap = undefined;\n }\n get start() {\n return this.shape.start;\n }\n get end() {\n return this.shape.end;\n }\n get length() {\n return this.shape.length;\n }\n get box() {\n return this.shape.box;\n }\n get isSegment() {\n return this.shape instanceof kX.Segment;\n }\n get isArc() {\n return this.shape instanceof kX.Arc;\n }\n get isLine() {\n return this.shape instanceof kX.Line;\n }\n get isRay() {\n return this.shape instanceof kX.Ray;\n }\n middle() {\n return this.shape.middle();\n }\n pointAtLength(e44) {\n return this.shape.pointAtLength(e44);\n }\n contains(e44) {\n return this.shape.contains(e44);\n }\n setInclusion(e44) {\n if (this.bv !== undefined)\n return this.bv;\n if (this.shape instanceof kX.Line || this.shape instanceof kX.Ray)\n return this.bv = kX.OUTSIDE, this.bv;\n if (this.bvStart === undefined \u0026\u0026 (this.bvStart = iV(e44, this.start)), this.bvEnd === undefined \u0026\u0026 (this.bvEnd = iV(e44, this.end)), this.bvStart === kX.OUTSIDE || this.bvEnd == kX.OUTSIDE)\n this.bv = kX.OUTSIDE;\n else if (this.bvStart === kX.INSIDE || this.bvEnd == kX.INSIDE)\n this.bv = kX.INSIDE;\n else {\n let t2 = iV(e44, this.middle());\n this.bv = t2;\n }\n return this.bv;\n }\n setOverlap(e44) {\n let t2, n2 = this.shape, o3 = e44.shape;\n n2 instanceof kX.Segment \u0026\u0026 o3 instanceof kX.Segment ? n2.start.equalTo(o3.start) \u0026\u0026 n2.end.equalTo(o3.end) ? t2 = kX.OVERLAP_SAME : n2.start.equalTo(o3.end) \u0026\u0026 n2.end.equalTo(o3.start) \u0026\u0026 (t2 = kX.OVERLAP_OPPOSITE) : (n2 instanceof kX.Arc \u0026\u0026 o3 instanceof kX.Arc || n2 instanceof kX.Segment \u0026\u0026 o3 instanceof kX.Arc || n2 instanceof kX.Arc \u0026\u0026 o3 instanceof kX.Segment) \u0026\u0026 (n2.start.equalTo(o3.start) \u0026\u0026 n2.end.equalTo(o3.end) \u0026\u0026 n2.middle().equalTo(o3.middle()) ? t2 = kX.OVERLAP_SAME : n2.start.equalTo(o3.end) \u0026\u0026 n2.end.equalTo(o3.start) \u0026\u0026 n2.middle().equalTo(o3.middle()) \u0026\u0026 (t2 = kX.OVERLAP_OPPOSITE)), this.overlap === undefined \u0026\u0026 (this.overlap = t2), e44.overlap === undefined \u0026\u0026 (e44.overlap = t2);\n }\n svg() {\n if (this.shape instanceof kX.Segment)\n return ` L${this.shape.end.x},${this.shape.end.y}`;\n if (this.shape instanceof kX.Arc) {\n let e44, t2 = this.shape, n2 = t2.counterClockwise ? \"1\" : \"0\";\n if (kX.Utils.EQ(t2.sweep, 2 * Math.PI)) {\n let o3 = t2.counterClockwise ? 1 : -1, i3 = new kX.Arc(t2.pc, t2.r, t2.startAngle, t2.startAngle + o3 * Math.PI, t2.counterClockwise), r3 = new kX.Arc(t2.pc, t2.r, t2.startAngle + o3 * Math.PI, t2.endAngle, t2.counterClockwise);\n return e44 = \"0\", ` A${i3.r},${i3.r} 0 ${e44},${n2} ${i3.end.x},${i3.end.y}\n A${r3.r},${r3.r} 0 ${e44},${n2} ${r3.end.x},${r3.end.y}`;\n }\n return e44 = t2.sweep \u003c= Math.PI ? \"0\" : \"1\", ` A${t2.r},${t2.r} 0 ${e44},${n2} ${t2.end.x},${t2.end.y}`;\n }\n }\n toJSON() {\n return this.shape.toJSON();\n }\n};\nvar IV = class extends LX {\n constructor(e44, t2) {\n super(e44, t2), this.setCircularLinks();\n }\n setCircularLinks() {\n this.isEmpty() || (this.last.next = this.first, this.first.prev = this.last);\n }\n [Symbol.iterator]() {\n let e44;\n return { next: () =\u003e {\n let t2 = e44 || this.first, n2 = !this.first || !!e44 \u0026\u0026 e44 === this.first;\n return e44 = t2 ? t2.next : undefined, { value: t2, done: n2 };\n } };\n }\n append(e44) {\n return super.append(e44), this.setCircularLinks(), this;\n }\n insert(e44, t2) {\n return super.insert(e44, t2), this.setCircularLinks(), this;\n }\n remove(e44) {\n return super.remove(e44), this;\n }\n};\nkX.Face = class e44 extends IV {\n constructor(t2, ...n2) {\n if (super(), this._box = undefined, this._orientation = undefined, n2.length !== 0) {\n if (n2.length === 1) {\n if (n2[0] instanceof Array) {\n let o3 = n2[0];\n if (o3.length === 0)\n return;\n if (o3.every((e45) =\u003e e45 instanceof kX.Point)) {\n let n3 = e44.points2segments(o3);\n this.shapes2face(t2.edges, n3);\n } else if (o3.every((e45) =\u003e e45 instanceof Array \u0026\u0026 e45.length === 2)) {\n let n3 = o3.map((e45) =\u003e new kX.Point(e45[0], e45[1])), i3 = e44.points2segments(n3);\n this.shapes2face(t2.edges, i3);\n } else if (o3.every((e45) =\u003e e45 instanceof kX.Segment || e45 instanceof kX.Arc))\n this.shapes2face(t2.edges, o3);\n else if (o3.every((e45) =\u003e e45.name === \"segment\" || e45.name === \"arc\")) {\n let e45 = [];\n for (let t3 of o3) {\n let n3;\n n3 = t3.name === \"segment\" ? new kX.Segment(t3) : new kX.Arc(t3), e45.push(n3);\n }\n this.shapes2face(t2.edges, e45);\n }\n } else if (n2[0] instanceof e44) {\n let e45 = n2[0];\n this.first = e45.first, this.last = e45.last;\n for (let n3 of e45)\n t2.edges.add(n3);\n } else if (n2[0] instanceof kX.Circle)\n this.shapes2face(t2.edges, [n2[0].toArc(SX)]);\n else if (n2[0] instanceof kX.Box) {\n let e45 = n2[0];\n this.shapes2face(t2.edges, [new kX.Segment(new kX.Point(e45.xmin, e45.ymin), new kX.Point(e45.xmax, e45.ymin)), new kX.Segment(new kX.Point(e45.xmax, e45.ymin), new kX.Point(e45.xmax, e45.ymax)), new kX.Segment(new kX.Point(e45.xmax, e45.ymax), new kX.Point(e45.xmin, e45.ymax)), new kX.Segment(new kX.Point(e45.xmin, e45.ymax), new kX.Point(e45.xmin, e45.ymin))]);\n }\n }\n n2.length === 2 \u0026\u0026 n2[0] instanceof kX.Edge \u0026\u0026 n2[1] instanceof kX.Edge \u0026\u0026 (this.first = n2[0], this.last = n2[1], this.last.next = this.first, this.first.prev = this.last, this.setArcLength());\n }\n }\n get edges() {\n return this.toArray();\n }\n get vertices() {\n return this.edges.map((e45) =\u003e e45.shape.start.clone());\n }\n get shapes() {\n return this.edges.map((e45) =\u003e e45.shape.clone());\n }\n get box() {\n if (this._box === undefined) {\n let e45 = new kX.Box;\n for (let t2 of this)\n e45 = e45.merge(t2.box);\n this._box = e45;\n }\n return this._box;\n }\n get perimeter() {\n return this.last.arc_length + this.last.length;\n }\n pointAtLength(e45) {\n if (e45 \u003e this.perimeter || e45 \u003c 0)\n return null;\n let t2 = null;\n for (let n2 of this)\n if (e45 \u003e= n2.arc_length \u0026\u0026 (n2 === this.last || e45 \u003c n2.next.arc_length)) {\n t2 = n2.pointAtLength(e45 - n2.arc_length);\n break;\n }\n return t2;\n }\n static points2segments(e45) {\n let t2 = [];\n for (let n2 = 0;n2 \u003c e45.length; n2++)\n e45[n2].equalTo(e45[(n2 + 1) % e45.length]) || t2.push(new kX.Segment(e45[n2], e45[(n2 + 1) % e45.length]));\n return t2;\n }\n shapes2face(e45, t2) {\n for (let n2 of t2) {\n let t3 = new kX.Edge(n2);\n this.append(t3), e45.add(t3);\n }\n }\n append(e45) {\n return super.append(e45), this.setOneEdgeArcLength(e45), e45.face = this, this;\n }\n insert(e45, t2) {\n return super.insert(e45, t2), this.setOneEdgeArcLength(e45), e45.face = this, this;\n }\n remove(e45) {\n return super.remove(e45), this.setArcLength(), this;\n }\n merge_with_next_edge(e45) {\n return e45.shape.end.x = e45.next.shape.end.x, e45.shape.end.y = e45.next.shape.end.y, this.remove(e45.next), this;\n }\n reverse() {\n let e45 = [], t2 = this.last;\n do {\n t2.shape = t2.shape.reverse(), e45.push(t2), t2 = t2.prev;\n } while (t2 !== this.last);\n this.first = undefined, this.last = undefined;\n for (let t3 of e45)\n this.first === undefined ? (t3.prev = t3, t3.next = t3, this.first = t3, this.last = t3) : (t3.prev = this.last, this.last.next = t3, this.last = t3, this.last.next = this.first, this.first.prev = this.last), this.setOneEdgeArcLength(t3);\n this._orientation !== undefined \u0026\u0026 (this._orientation = undefined, this._orientation = this.orientation());\n }\n setArcLength() {\n for (let e45 of this)\n this.setOneEdgeArcLength(e45), e45.face = this;\n }\n setOneEdgeArcLength(e45) {\n e45 === this.first ? e45.arc_length = 0 : e45.arc_length = e45.prev.arc_length + e45.prev.length;\n }\n area() {\n return Math.abs(this.signedArea());\n }\n signedArea() {\n let e45 = 0, t2 = this.box.ymin;\n for (let n2 of this)\n e45 += n2.shape.definiteIntegral(t2);\n return e45;\n }\n orientation() {\n if (this._orientation === undefined) {\n let e45 = this.signedArea();\n kX.Utils.EQ_0(e45) ? this._orientation = CX.NOT_ORIENTABLE : kX.Utils.LT(e45, 0) ? this._orientation = CX.CCW : this._orientation = CX.CW;\n }\n return this._orientation;\n }\n isSimple(t2) {\n return e44.getSelfIntersections(this, t2, true).length === 0;\n }\n static getSelfIntersections(e45, t2, n2 = false) {\n let o3 = [];\n for (let i3 of e45) {\n let r3 = t2.search(i3.box);\n for (let t3 of r3) {\n if (i3 === t3)\n continue;\n if (t3.face !== e45)\n continue;\n if (i3.shape instanceof kX.Segment \u0026\u0026 t3.shape instanceof kX.Segment \u0026\u0026 (i3.next === t3 || i3.prev === t3))\n continue;\n let r4 = i3.shape.intersect(t3.shape);\n for (let e46 of r4)\n if ((!e46.equalTo(i3.start) || !e46.equalTo(t3.end) || t3 !== i3.prev) \u0026\u0026 (!e46.equalTo(i3.end) || !e46.equalTo(t3.start) || t3 !== i3.next) \u0026\u0026 (o3.push(e46), n2))\n break;\n if (o3.length \u003e 0 \u0026\u0026 n2)\n break;\n }\n if (o3.length \u003e 0 \u0026\u0026 n2)\n break;\n }\n return o3;\n }\n findEdgeByPoint(e45) {\n let t2;\n for (let n2 of this)\n if (!e45.equalTo(n2.shape.start) \u0026\u0026 (e45.equalTo(n2.shape.end) || n2.shape.contains(e45))) {\n t2 = n2;\n break;\n }\n return t2;\n }\n toPolygon() {\n return new kX.Polygon(this.shapes);\n }\n toJSON() {\n return this.edges.map((e45) =\u003e e45.toJSON());\n }\n svg() {\n let e45 = `M${this.first.start.x},${this.first.start.y}`;\n for (let t2 of this)\n e45 += t2.svg();\n return e45 += \" z\", e45;\n }\n};\nkX.Ray = class e45 extends bV {\n constructor(...e46) {\n if (super(), this.pt = new kX.Point, this.norm = new kX.Vector(0, 1), e46.length !== 0 \u0026\u0026 (e46.length \u003e= 1 \u0026\u0026 e46[0] instanceof kX.Point \u0026\u0026 (this.pt = e46[0].clone()), e46.length !== 1)) {\n if (!(e46.length === 2 \u0026\u0026 e46[1] instanceof kX.Vector))\n throw DX.ILLEGAL_PARAMETERS;\n this.norm = e46[1].clone();\n }\n }\n clone() {\n return new e45(this.pt, this.norm);\n }\n get slope() {\n return new kX.Vector(this.norm.y, -this.norm.x).slope;\n }\n get box() {\n let e46 = this.slope;\n return new kX.Box(e46 \u003e Math.PI / 2 \u0026\u0026 e46 \u003c 3 * Math.PI / 2 ? Number.NEGATIVE_INFINITY : this.pt.x, e46 \u003e= 0 \u0026\u0026 e46 \u003c= Math.PI ? this.pt.y : Number.NEGATIVE_INFINITY, e46 \u003e= Math.PI / 2 \u0026\u0026 e46 \u003c= 3 * Math.PI / 2 ? this.pt.x : Number.POSITIVE_INFINITY, e46 \u003e= Math.PI \u0026\u0026 e46 \u003c= 2 * Math.PI || e46 === 0 ? this.pt.y : Number.POSITIVE_INFINITY);\n }\n get start() {\n return this.pt;\n }\n get end() {}\n get length() {\n return Number.POSITIVE_INFINITY;\n }\n contains(e46) {\n if (this.pt.equalTo(e46))\n return true;\n let t2 = new kX.Vector(this.pt, e46);\n return kX.Utils.EQ_0(this.norm.dot(t2)) \u0026\u0026 kX.Utils.GE(t2.cross(this.norm), 0);\n }\n coord(e46) {\n return xV(e46.x, e46.y).cross(this.norm);\n }\n split(e46) {\n return this.contains(e46) ? this.pt.equalTo(e46) ? [this] : [new kX.Segment(this.pt, e46), new kX.Ray(e46, this.norm)] : [];\n }\n intersect(e46) {\n return e46 instanceof kX.Point ? this.contains(e46) ? [e46] : [] : e46 instanceof kX.Segment ? hH(this, e46) : e46 instanceof kX.Arc ? dH(this, e46) : e46 instanceof kX.Line ? pH(this, e46) : e46 instanceof kX.Ray ? (n2 = e46, jX(lH(t2 = this), lH(n2)).filter((e47) =\u003e t2.contains(e47)).filter((e47) =\u003e n2.contains(e47))) : e46 instanceof kX.Circle ? uH(this, e46) : e46 instanceof kX.Box ? function(e47, t3) {\n return YX(lH(e47), t3).filter((t4) =\u003e e47.contains(t4));\n }(this, e46) : e46 instanceof kX.Polygon ? mH(this, e46) : e46 instanceof kX.Multiline ? fH(this, e46) : undefined;\n var t2, n2;\n }\n rotate(e46, t2 = new kX.Point) {\n return new kX.Ray(this.pt.rotate(e46, t2), this.norm.rotate(e46));\n }\n transform(e46) {\n return new kX.Ray(this.pt.transform(e46), this.norm.clone());\n }\n get name() {\n return \"ray\";\n }\n svg(e46, t2 = {}) {\n let n2 = YX(new kX.Line(this.pt, this.norm), e46);\n return n2 = n2.filter((e47) =\u003e this.contains(e47)), n2.length === 0 || n2.length === 2 ? \"\" : new kX.Segment(this.pt, n2[0]).svg(t2);\n }\n};\nkX.ray = (...e46) =\u003e new kX.Ray(...e46);\nkX.Polygon = class e46 {\n constructor() {\n this.faces = new kX.PlanarSet, this.edges = new kX.PlanarSet;\n let e47 = [...arguments];\n if (e47.length === 1 \u0026\u0026 (e47[0] instanceof Array \u0026\u0026 e47[0].length \u003e 0 || e47[0] instanceof kX.Circle || e47[0] instanceof kX.Box)) {\n let t2 = e47[0];\n if (e47[0] instanceof Array \u0026\u0026 e47[0].every((e48) =\u003e e48 instanceof Array))\n if (t2.every((e48) =\u003e e48 instanceof Array \u0026\u0026 e48.length === 2 \u0026\u0026 typeof e48[0] == \"number\" \u0026\u0026 typeof e48[1] == \"number\"))\n this.faces.add(new kX.Face(this, t2));\n else\n for (let e48 of t2)\n if (e48 instanceof Array \u0026\u0026 e48[0] instanceof Array \u0026\u0026 e48[0].every((e49) =\u003e e49 instanceof Array \u0026\u0026 e49.length === 2 \u0026\u0026 typeof e49[0] == \"number\" \u0026\u0026 typeof e49[1] == \"number\"))\n for (let t3 of e48)\n this.faces.add(new kX.Face(this, t3));\n else\n this.faces.add(new kX.Face(this, e48));\n else\n this.faces.add(new kX.Face(this, t2));\n }\n }\n get box() {\n return [...this.faces].reduce((e47, t2) =\u003e e47.merge(t2.box), new kX.Box);\n }\n get vertices() {\n return [...this.faces].flatMap((e47) =\u003e e47.vertices);\n }\n clone() {\n let t2 = new e46;\n for (let e47 of this.faces)\n t2.addFace(e47.shapes);\n return t2;\n }\n createFromArray(t2) {\n const n2 = new e46;\n return t2.forEach((e47) =\u003e [...e47.faces].forEach((e48) =\u003e n2.addFace(e48.shapes))), n2;\n }\n isEmpty() {\n return this.edges.size === 0 || this.faces.size === 0;\n }\n isValid() {\n let e47 = true;\n for (let t2 of this.faces)\n if (!t2.isSimple(this.edges)) {\n e47 = false;\n break;\n }\n return e47;\n }\n area() {\n let e47 = [...this.faces].reduce((e48, t2) =\u003e e48 + t2.signedArea(), 0);\n return Math.abs(e47);\n }\n addFace(...e47) {\n let t2 = new kX.Face(this, ...e47);\n return this.faces.add(t2), t2;\n }\n deleteFace(e47) {\n for (let t2 of e47)\n this.edges.delete(t2);\n return this.faces.delete(e47);\n }\n recreateFaces() {\n this.faces.clear();\n for (let e48 of this.edges)\n e48.face = null;\n let e47, t2 = true;\n for (;t2; ) {\n t2 = false;\n for (let n2 of this.edges)\n if (n2.face === null) {\n e47 = n2, t2 = true;\n break;\n }\n if (t2) {\n let t3 = e47;\n do {\n t3 = t3.next;\n } while (t3.next !== e47);\n this.addFace(e47, t3);\n }\n }\n }\n removeChain(e47, t2, n2) {\n if (n2.next !== t2) {\n for (let o3 = t2;o3 !== n2.next; o3 = o3.next)\n if (e47.remove(o3), this.edges.delete(o3), e47.isEmpty()) {\n this.deleteFace(e47);\n break;\n }\n } else\n this.deleteFace(e47);\n }\n addVertex(e47, t2) {\n let n2 = t2.shape.split(e47);\n if (n2[0] === null)\n return t2.prev;\n if (n2[1] === null)\n return t2;\n let o3 = new kX.Edge(n2[0]), i3 = t2.prev;\n return t2.face.insert(o3, i3), this.edges.delete(t2), this.edges.add(o3), t2.shape = n2[1], this.edges.add(t2), o3;\n }\n removeEndVertex(e47) {\n const t2 = e47.next;\n t2 !== e47 \u0026\u0026 (e47.face.merge_with_next_edge(e47), this.edges.delete(t2));\n }\n cut(e47) {\n const t2 = this.splitToIslands().flatMap((t3) =\u003e t3._cutSingleIsland(e47)).filter((e48) =\u003e e48.isValid() \u0026\u0026 e48.isEmpty() === false);\n return this.createFromArray(t2);\n }\n _cutSingleIsland(e47) {\n let t2 = this.clone();\n const n2 = e47.clone();\n let o3, i3, r3 = { int_points1: [], int_points2: [], int_points1_sorted: [], int_points2_sorted: [] };\n for (let e48 of n2.edges)\n for (let n3 of t2.edges) {\n let t3 = sH(e48, n3);\n for (let o4 of t3)\n yH(e48, o4, r3.int_points1), yH(n3, o4, r3.int_points2);\n }\n if (r3.int_points1.length === 0)\n return t2;\n r3.int_points1_sorted = xH(r3.int_points1), r3.int_points2_sorted = xH(r3.int_points2), MH(n2, r3.int_points1_sorted), MH(t2, r3.int_points2_sorted), IH(r3), r3.int_points1_sorted = xH(r3.int_points1), r3.int_points2_sorted = xH(r3.int_points2), SH(r3.int_points1), CH(r3.int_points1, t2);\n for (let e48 of r3.int_points1_sorted)\n e48.edge_before \u0026\u0026 e48.edge_after \u0026\u0026 e48.edge_before.bv === e48.edge_after.bv \u0026\u0026 (r3.int_points2[e48.id] = -1, e48.id = -1);\n if (r3.int_points1 = r3.int_points1.filter((e48) =\u003e e48.id \u003e= 0), r3.int_points2 = r3.int_points2.filter((e48) =\u003e e48.id \u003e= 0), r3.int_points1.forEach((e48, t3) =\u003e {\n e48.id = t3;\n }), r3.int_points2.forEach((e48, t3) =\u003e {\n e48.id = t3;\n }), r3.int_points1.length === 0)\n return t2;\n r3.int_points1_sorted = xH(r3.int_points1), r3.int_points2_sorted = xH(r3.int_points2);\n for (let e48 = 1;e48 \u003c r3.int_points1_sorted.length; e48++)\n if (i3 = r3.int_points1_sorted[e48], o3 = r3.int_points1_sorted[e48 - 1], i3.edge_before \u0026\u0026 i3.edge_before.bv === 1) {\n let e49 = o3.edge_after, s2 = i3.edge_before, a3 = n2.getChain(e49, s2);\n wH(r3.int_points2[o3.id], r3.int_points2[i3.id], a3), a3.forEach((e50) =\u003e t2.edges.add(e50)), a3 = a3.reverse().map((e50) =\u003e new kX.Edge(e50.shape.reverse()));\n for (let e50 = 0;e50 \u003c a3.length - 1; e50++)\n a3[e50].next = a3[e50 + 1], a3[e50 + 1].prev = a3[e50];\n wH(r3.int_points2[i3.id], r3.int_points2[o3.id], a3), a3.forEach((e50) =\u003e t2.edges.add(e50));\n }\n return t2.recreateFaces(), t2;\n }\n cutWithLine(e47) {\n let t2 = new _H([e47]);\n return this.cut(t2);\n }\n findEdgeByPoint(e47) {\n let t2;\n for (let n2 of this.faces)\n if (t2 = n2.findEdgeByPoint(e47), t2 !== undefined)\n break;\n return t2;\n }\n splitToIslands() {\n if (this.isEmpty())\n return [];\n let e47 = this.toArray();\n e47.sort((e48, t3) =\u003e t3.area() - e48.area());\n let t2 = [...e47[0].faces][0].orientation(), n2 = e47.filter((e48) =\u003e [...e48.faces][0].orientation() === t2);\n for (let o3 of e47) {\n let e48 = [...o3.faces][0];\n if (e48.orientation() !== t2) {\n for (let t3 of n2)\n if (e48.shapes.every((e49) =\u003e t3.contains(e49))) {\n t3.addFace(e48.shapes);\n break;\n }\n }\n }\n return n2;\n }\n rearrange() {\n if (this.faces.size \u003c= 1)\n return this.clone();\n const t2 = this.splitToIslands(), n2 = new e46;\n return t2.forEach((e47) =\u003e {\n e47.faces.forEach((e48) =\u003e n2.addFace(e48.shapes));\n }), n2;\n }\n orientation() {\n return this.isEmpty() ? CX.NOT_ORIENTABLE : [...this.faces][0].orientation();\n }\n isOuter(e47) {\n return e47.orientation() === this.orientation();\n }\n isMultiPolygon() {\n let e47 = 0;\n return this.faces.forEach((t2) =\u003e {\n this.isOuter(t2) \u0026\u0026 e47++;\n }), e47 \u003e 1;\n }\n reverse() {\n for (let e47 of this.faces)\n e47.reverse();\n return this;\n }\n contains(e47) {\n if (e47 instanceof kX.Point) {\n let t2 = iV(this, e47);\n return t2 === 1 || t2 === 2;\n }\n return cV(this, e47);\n }\n distanceTo(e47) {\n if (e47 instanceof kX.Point) {\n let [t2, n2] = kX.Distance.point2polygon(e47, this);\n return n2 = n2.reverse(), [t2, n2];\n }\n if (e47 instanceof kX.Circle || e47 instanceof kX.Line || e47 instanceof kX.Segment || e47 instanceof kX.Arc) {\n let [t2, n2] = kX.Distance.shape2polygon(e47, this);\n return n2 = n2.reverse(), [t2, n2];\n }\n if (e47 instanceof kX.Polygon) {\n let t2, n2, o3 = [Number.POSITIVE_INFINITY, new kX.Segment];\n for (let i3 of this.edges) {\n let r3 = o3[0];\n [t2, n2] = kX.Distance.shape2planarSet(i3.shape, e47.edges, r3), kX.Utils.LT(t2, r3) \u0026\u0026 (o3 = [t2, n2]);\n }\n return o3;\n }\n }\n intersect(e47) {\n return e47 instanceof kX.Point ? this.contains(e47) ? [e47] : [] : e47 instanceof kX.Line ? iH(e47, this) : e47 instanceof kX.Ray ? mH(e47, this) : e47 instanceof kX.Circle ? rH(e47, this) : e47 instanceof kX.Segment ? nH(e47, this) : e47 instanceof kX.Arc ? oH(e47, this) : e47 instanceof kX.Polygon ? function(e48, t2) {\n let n2 = [];\n if (e48.isEmpty() || t2.isEmpty())\n return n2;\n if (e48.box.not_intersect(t2.box))\n return n2;\n for (let o3 of e48.edges)\n n2 = [...n2, ...aH(o3, t2)];\n return n2;\n }(e47, this) : e47 instanceof kX.Multiline ? function(e48, t2) {\n let n2 = [];\n if (t2.isEmpty() || e48.size === 0)\n return n2;\n for (let o3 of e48)\n n2 = [...n2, ...aH(o3, t2)];\n return n2;\n }(e47, this) : undefined;\n }\n translate(t2) {\n let n2 = new e46;\n for (let e47 of this.faces)\n n2.addFace(e47.shapes.map((e48) =\u003e e48.translate(t2)));\n return n2;\n }\n rotate(t2 = 0, n2 = new kX.Point) {\n let o3 = new e46;\n for (let e47 of this.faces)\n o3.addFace(e47.shapes.map((e48) =\u003e e48.rotate(t2, n2)));\n return o3;\n }\n scale(t2, n2) {\n let o3 = new e46;\n for (let e47 of this.faces)\n o3.addFace(e47.shapes.map((e48) =\u003e e48.scale(t2, n2)));\n return o3;\n }\n transform(t2 = new kX.Matrix) {\n let n2 = new e46;\n for (let e47 of this.faces)\n n2.addFace(e47.shapes.map((e48) =\u003e e48.transform(t2)));\n return n2;\n }\n toJSON() {\n return [...this.faces].map((e47) =\u003e e47.toJSON());\n }\n toArray() {\n return [...this.faces].map((e47) =\u003e e47.toPolygon());\n }\n dpath() {\n return [...this.faces].reduce((e47, t2) =\u003e e47 + t2.svg(), \"\");\n }\n svg(e47 = {}) {\n let t2 = `\n\u003cpath ${FX({ fillRule: \"evenodd\", fill: \"lightcyan\", ...e47 })} d=\"`;\n for (let e48 of this.faces)\n t2 += `\n${e48.svg()}`;\n return t2 += `\" \u003e\n\u003c/path\u003e`, t2;\n }\n};\nkX.polygon = (...e47) =\u003e new kX.Polygon(...e47);\nvar { Circle: SV, Line: CV, Point: PV, Vector: MV, Utils: wV } = kX;\nkX.Inversion = class e47 {\n constructor(e48) {\n this.circle = e48;\n }\n get inversion_circle() {\n return this.circle;\n }\n static inversePoint(e48, t2) {\n const n2 = new MV(e48.pc, t2), o3 = e48.r * e48.r, i3 = n2.dot(n2);\n return wV.EQ_0(i3) ? new PV(Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY) : e48.pc.translate(n2.multiply(o3 / i3));\n }\n static inverseCircle(e48, t2) {\n const n2 = e48.pc.distanceTo(t2.pc)[0];\n if (wV.EQ(n2, t2.r)) {\n let n3 = e48.r * e48.r / (2 * t2.r), o3 = new MV(e48.pc, t2.pc);\n o3 = o3.normalize();\n let i3 = e48.pc.translate(o3.multiply(n3));\n return new CV(i3, o3);\n }\n {\n let n3 = new MV(e48.pc, t2.pc), o3 = e48.r * e48.r / (n3.dot(n3) - t2.r * t2.r), i3 = e48.pc.translate(n3.multiply(o3)), r3 = Math.abs(o3) * t2.r;\n return new SV(i3, r3);\n }\n }\n static inverseLine(e48, t2) {\n const [n2, o3] = e48.pc.distanceTo(t2);\n if (wV.EQ_0(n2))\n return t2.clone();\n {\n let t3 = e48.r * e48.r / (2 * n2), i3 = new MV(e48.pc, o3.end);\n return i3 = i3.multiply(t3 / n2), new SV(e48.pc.translate(i3), t3);\n }\n }\n inverse(t2) {\n return t2 instanceof PV ? e47.inversePoint(this.circle, t2) : t2 instanceof SV ? e47.inverseCircle(this.circle, t2) : t2 instanceof CV ? e47.inverseLine(this.circle, t2) : undefined;\n }\n};\nkX.inversion = (e48) =\u003e new kX.Inversion(e48);\nkX.Distance = class e48 {\n static point2point(e49, t2) {\n return e49.distanceTo(t2);\n }\n static point2line(e49, t2) {\n let n2 = e49.projectionOn(t2);\n return [new kX.Vector(e49, n2).length, new kX.Segment(e49, n2)];\n }\n static point2circle(e49, t2) {\n let [n2, o3] = e49.distanceTo(t2.center);\n if (kX.Utils.EQ_0(n2))\n return [t2.r, new kX.Segment(e49, t2.toArc().start)];\n {\n let o4 = Math.abs(n2 - t2.r), i3 = new kX.Vector(t2.pc, e49).normalize().multiply(t2.r), r3 = t2.pc.translate(i3);\n return [o4, new kX.Segment(e49, r3)];\n }\n }\n static point2segment(t2, n2) {\n if (n2.start.equalTo(n2.end))\n return e48.point2point(t2, n2.start);\n let o3, i3, r3 = new kX.Vector(n2.start, n2.end), s2 = new kX.Vector(n2.start, t2), a3 = new kX.Vector(n2.end, t2), c3 = r3.dot(s2), l3 = -r3.dot(a3);\n if (kX.Utils.GE(c3, 0) \u0026\u0026 kX.Utils.GE(l3, 0)) {\n let e49 = n2.tangentInStart();\n return o3 = Math.abs(e49.cross(s2)), i3 = n2.start.translate(e49.multiply(e49.dot(s2))), [o3, new kX.Segment(t2, i3)];\n }\n return c3 \u003c 0 ? t2.distanceTo(n2.start) : t2.distanceTo(n2.end);\n }\n static point2arc(t2, n2) {\n let o3, i3, r3 = new kX.Circle(n2.pc, n2.r), s2 = [];\n return [o3, i3] = e48.point2circle(t2, r3), i3.end.on(n2) \u0026\u0026 s2.push(e48.point2circle(t2, r3)), s2.push(e48.point2point(t2, n2.start)), s2.push(e48.point2point(t2, n2.end)), e48.sort(s2), s2[0];\n }\n static point2edge(t2, n2) {\n return n2.shape instanceof kX.Segment ? e48.point2segment(t2, n2.shape) : e48.point2arc(t2, n2.shape);\n }\n static segment2line(t2, n2) {\n let o3 = t2.intersect(n2);\n if (o3.length \u003e 0)\n return [0, new kX.Segment(o3[0], o3[0])];\n let i3 = [];\n return i3.push(e48.point2line(t2.start, n2)), i3.push(e48.point2line(t2.end, n2)), e48.sort(i3), i3[0];\n }\n static segment2segment(t2, n2) {\n let o3 = VX(t2, n2);\n if (o3.length \u003e 0)\n return [0, new kX.Segment(o3[0], o3[0])];\n let i3, r3, s2 = [];\n return [i3, r3] = e48.point2segment(n2.start, t2), s2.push([i3, r3.reverse()]), [i3, r3] = e48.point2segment(n2.end, t2), s2.push([i3, r3.reverse()]), s2.push(e48.point2segment(t2.start, n2)), s2.push(e48.point2segment(t2.end, n2)), e48.sort(s2), s2[0];\n }\n static segment2circle(t2, n2) {\n let o3 = t2.intersect(n2);\n if (o3.length \u003e 0)\n return [0, new kX.Segment(o3[0], o3[0])];\n let i3 = new kX.Line(t2.ps, t2.pe), [r3, s2] = e48.point2line(n2.center, i3);\n if (kX.Utils.GE(r3, n2.r) \u0026\u0026 s2.end.on(t2))\n return e48.point2circle(s2.end, n2);\n {\n let [o4, i4] = e48.point2circle(t2.start, n2), [r4, s3] = e48.point2circle(t2.end, n2);\n return kX.Utils.LT(o4, r4) ? [o4, i4] : [r4, s3];\n }\n }\n static segment2arc(t2, n2) {\n let o3 = t2.intersect(n2);\n if (o3.length \u003e 0)\n return [0, new kX.Segment(o3[0], o3[0])];\n let i3 = new kX.Line(t2.ps, t2.pe), r3 = new kX.Circle(n2.pc, n2.r), [s2, a3] = e48.point2line(r3.center, i3);\n if (kX.Utils.GE(s2, r3.r) \u0026\u0026 a3.end.on(t2)) {\n let [t3, o4] = e48.point2circle(a3.end, r3);\n if (o4.end.on(n2))\n return [t3, o4];\n }\n let c3, l3, h2 = [];\n return h2.push(e48.point2arc(t2.start, n2)), h2.push(e48.point2arc(t2.end, n2)), [c3, l3] = e48.point2segment(n2.start, t2), h2.push([c3, l3.reverse()]), [c3, l3] = e48.point2segment(n2.end, t2), h2.push([c3, l3.reverse()]), e48.sort(h2), h2[0];\n }\n static circle2circle(t2, n2) {\n let o3 = t2.intersect(n2);\n if (o3.length \u003e 0)\n return [0, new kX.Segment(o3[0], o3[0])];\n if (t2.center.equalTo(n2.center)) {\n let o4 = t2.toArc(), i3 = n2.toArc();\n return e48.point2point(o4.start, i3.start);\n }\n {\n let o4 = new kX.Line(t2.center, n2.center), i3 = o4.intersect(t2), r3 = o4.intersect(n2), s2 = [];\n return s2.push(e48.point2point(i3[0], r3[0])), s2.push(e48.point2point(i3[0], r3[1])), s2.push(e48.point2point(i3[1], r3[0])), s2.push(e48.point2point(i3[1], r3[1])), e48.sort(s2), s2[0];\n }\n }\n static circle2line(t2, n2) {\n let o3 = t2.intersect(n2);\n if (o3.length \u003e 0)\n return [0, new kX.Segment(o3[0], o3[0])];\n let [i3, r3] = e48.point2line(t2.center, n2), [s2, a3] = e48.point2circle(r3.end, t2);\n return a3 = a3.reverse(), [s2, a3];\n }\n static arc2line(t2, n2) {\n let o3 = n2.intersect(t2);\n if (o3.length \u003e 0)\n return [0, new kX.Segment(o3[0], o3[0])];\n let i3 = new kX.Circle(t2.center, t2.r), [r3, s2] = e48.point2line(i3.center, n2);\n if (!kX.Utils.GE(r3, i3.r)) {\n let o4 = [];\n return o4.push(e48.point2line(t2.start, n2)), o4.push(e48.point2line(t2.end, n2)), e48.sort(o4), o4[0];\n }\n {\n let [n3, o4] = e48.point2circle(s2.end, i3);\n if (o4.end.on(t2))\n return [n3, o4];\n }\n }\n static arc2circle(t2, n2) {\n let o3 = t2.intersect(n2);\n if (o3.length \u003e 0)\n return [0, new kX.Segment(o3[0], o3[0])];\n let i3 = new kX.Circle(t2.center, t2.r), [r3, s2] = e48.circle2circle(i3, n2);\n if (s2.start.on(t2))\n return [r3, s2];\n {\n let o4 = [];\n return o4.push(e48.point2circle(t2.start, n2)), o4.push(e48.point2circle(t2.end, n2)), e48.sort(o4), o4[0];\n }\n }\n static arc2arc(t2, n2) {\n let o3 = t2.intersect(n2);\n if (o3.length \u003e 0)\n return [0, new kX.Segment(o3[0], o3[0])];\n let i3 = new kX.Circle(t2.center, t2.r), r3 = new kX.Circle(n2.center, n2.r), [s2, a3] = e48.circle2circle(i3, r3);\n if (a3.start.on(t2) \u0026\u0026 a3.end.on(n2))\n return [s2, a3];\n {\n let o4, i4, r4 = [];\n return [o4, i4] = e48.point2arc(t2.start, n2), i4.end.on(n2) \u0026\u0026 r4.push([o4, i4]), [o4, i4] = e48.point2arc(t2.end, n2), i4.end.on(n2) \u0026\u0026 r4.push([o4, i4]), [o4, i4] = e48.point2arc(n2.start, t2), i4.end.on(t2) \u0026\u0026 r4.push([o4, i4.reverse()]), [o4, i4] = e48.point2arc(n2.end, t2), i4.end.on(t2) \u0026\u0026 r4.push([o4, i4.reverse()]), [o4, i4] = e48.point2point(t2.start, n2.start), r4.push([o4, i4]), [o4, i4] = e48.point2point(t2.start, n2.end), r4.push([o4, i4]), [o4, i4] = e48.point2point(t2.end, n2.start), r4.push([o4, i4]), [o4, i4] = e48.point2point(t2.end, n2.end), r4.push([o4, i4]), e48.sort(r4), r4[0];\n }\n }\n static point2polygon(t2, n2) {\n let o3 = [Number.POSITIVE_INFINITY, new kX.Segment];\n for (let i3 of n2.edges) {\n let [n3, r3] = e48.point2edge(t2, i3);\n kX.Utils.LT(n3, o3[0]) \u0026\u0026 (o3 = [n3, r3]);\n }\n return o3;\n }\n static shape2polygon(e49, t2) {\n let n2 = [Number.POSITIVE_INFINITY, new kX.Segment];\n for (let o3 of t2.edges) {\n let [t3, i3] = e49.distanceTo(o3.shape);\n kX.Utils.LT(t3, n2[0]) \u0026\u0026 (n2 = [t3, i3]);\n }\n return n2;\n }\n static polygon2polygon(e49, t2) {\n let n2 = [Number.POSITIVE_INFINITY, new kX.Segment];\n for (let o3 of e49.edges)\n for (let e50 of t2.edges) {\n let [t3, i3] = o3.shape.distanceTo(e50.shape);\n kX.Utils.LT(t3, n2[0]) \u0026\u0026 (n2 = [t3, i3]);\n }\n return n2;\n }\n static box2box_minmax(e49, t2) {\n let n2 = Math.max(Math.max(e49.xmin - t2.xmax, 0), Math.max(t2.xmin - e49.xmax, 0)), o3 = Math.max(Math.max(e49.ymin - t2.ymax, 0), Math.max(t2.ymin - e49.ymax, 0)), i3 = n2 * n2 + o3 * o3, r3 = e49.merge(t2), s2 = r3.xmax - r3.xmin, a3 = r3.ymax - r3.ymin;\n return [i3, s2 * s2 + a3 * a3];\n }\n static minmax_tree_process_level(t2, n2, o3, i3) {\n let r3, s2;\n for (let a4 of n2) {\n [r3, s2] = e48.box2box_minmax(t2.box, a4.item.key);\n for (let e49 of a4.item.values)\n e49 instanceof kX.Edge ? i3.insert([r3, s2], e49.shape) : i3.insert([r3, s2], e49);\n kX.Utils.LT(s2, o3) \u0026\u0026 (o3 = s2);\n }\n if (n2.length === 0)\n return o3;\n let a3 = [...n2.map((e49) =\u003e e49.left.isNil() ? undefined : e49.left).filter((e49) =\u003e e49 !== undefined), ...n2.map((e49) =\u003e e49.right.isNil() ? undefined : e49.right).filter((e49) =\u003e e49 !== undefined)].filter((n3) =\u003e {\n let [i4, r4] = e48.box2box_minmax(t2.box, n3.max);\n return kX.Utils.LE(i4, o3);\n });\n return o3 = e48.minmax_tree_process_level(t2, a3, o3, i3);\n }\n static minmax_tree(t2, n2, o3) {\n let i3 = new _V, r3 = [n2.index.root], s2 = o3 \u003c Number.POSITIVE_INFINITY ? o3 * o3 : Number.POSITIVE_INFINITY;\n return s2 = e48.minmax_tree_process_level(t2, r3, s2, i3), i3;\n }\n static minmax_tree_calc_distance(t2, n2, o3) {\n let i3, r3;\n if (n2 != null \u0026\u0026 !n2.isNil()) {\n if ([i3, r3] = e48.minmax_tree_calc_distance(t2, n2.left, o3), r3)\n return [i3, r3];\n if (kX.Utils.LT(i3[0], Math.sqrt(n2.item.key.low)))\n return [i3, true];\n let [s2, a3] = e48.distanceToArray(t2, n2.item.values);\n return kX.Utils.LT(s2, i3[0]) \u0026\u0026 (i3 = [s2, a3]), [i3, r3] = e48.minmax_tree_calc_distance(t2, n2.right, i3), [i3, r3];\n }\n return [o3, false];\n }\n static shape2planarSet(t2, n2, o3 = Number.POSITIVE_INFINITY) {\n let i3 = [o3, new kX.Segment], r3 = false;\n if (n2 instanceof kX.PlanarSet) {\n let s2 = e48.minmax_tree(t2, n2, o3);\n [i3, r3] = e48.minmax_tree_calc_distance(t2, s2.root, i3);\n }\n return i3;\n }\n static sort(e49) {\n e49.sort((e50, t2) =\u003e kX.Utils.LT(e50[0], t2[0]) ? -1 : kX.Utils.GT(e50[0], t2[0]) ? 1 : 0);\n }\n static distance(e49, t2) {\n return e49.distanceTo(t2);\n }\n static distanceToArray(e49, t2) {\n let n2 = [Number.POSITIVE_INFINITY, new kX.Segment];\n for (let o3 of t2) {\n let [t3, i3] = e49.distanceTo(o3);\n kX.Utils.LT(t3, n2[0]) \u0026\u0026 (n2 = [t3, i3]);\n }\n return n2;\n }\n static shape2multiline(t2, n2) {\n let o3 = [Number.POSITIVE_INFINITY, new kX.Segment];\n for (let i3 of n2) {\n let [n3, r3] = e48.distance(t2, i3.shape);\n kX.Utils.LT(n3, o3[0]) \u0026\u0026 (o3 = [n3, r3]);\n }\n return o3;\n }\n static multiline2multiline(t2, n2) {\n let o3 = [Number.POSITIVE_INFINITY, new kX.Segment];\n for (let i3 of t2)\n for (let t3 of n2) {\n let [n3, r3] = e48.distance(i3.shape, t3.shape);\n kX.Utils.LT(n3, o3[0]) \u0026\u0026 (o3 = [n3, r3]);\n }\n return o3;\n }\n};\nvar { Multiline: NV, Point: RV, Segment: TV, Polygon: EV } = kX;\nfunction AV(e49) {\n return new RV(e49.split(\" \").map(Number));\n}\nfunction OV(e49) {\n return e49.split(\", \").map(AV);\n}\nfunction kV(e49) {\n const t2 = OV(e49);\n let n2 = [];\n for (let e50 = 0;e50 \u003c t2.length - 1; e50++)\n n2.push(new TV(t2[e50], t2[e50 + 1]));\n return new NV(n2);\n}\nfunction DV(e49) {\n const t2 = e49.replace(/\\(\\(/, \"\").replace(/\\)\\)$/, \"\").split(\"), (\"), n2 = new EV;\n let o3;\n return t2.forEach((e50, t3) =\u003e {\n let i3 = e50.split(\", \").map((e51) =\u003e new RV(e51.split(\" \").map(Number)));\n const r3 = n2.addFace(i3);\n t3 === 0 ? o3 = r3.orientation() : r3.orientation() === o3 \u0026\u0026 r3.reverse();\n }), n2;\n}\nfunction LV(e49) {\n if (e49.startsWith(\"POLYGON\")) {\n return DV(e49.replace(/^POLYGON /, \"\"));\n }\n return function(e50) {\n const t2 = e50.split(/\\)\\), \\(\\(/).map((e51) =\u003e \"((\" + e51 + \"))\").map(DV), n2 = new EV;\n return t2.reduce((e51, t3) =\u003e [...e51, ...t3?.faces], []).forEach((e51) =\u003e n2.addFace([...e51?.shapes])), n2;\n }(e49.replace(/^MULTIPOLYGON \\(\\(\\((.*)\\)\\)\\)$/, \"$1\"));\n}\nfunction zV(e49) {\n return e49.split(`\n`)?.every((e50) =\u003e e50.includes(\"POINT\"));\n}\nfunction BV(e49) {\n return e49.split(`\n`)?.every((e50) =\u003e e50.includes(\"LINESTRING\"));\n}\nkX.isWktString = function(e50) {\n return e50.startsWith(\"POINT\") || zV(e50) || e50.startsWith(\"LINESTRING\") || BV(e50) || e50.startsWith(\"MULTILINESTRING\") || e50.startsWith(\"POLYGON\") || e50.startsWith(\"MULTIPOINT\") || e50.startsWith(\"MULTIPOLYGON\") || e50.startsWith(\"GEOMETRYCOLLECTION\");\n}, kX.parseWKT = function e49(t2) {\n if (t2.startsWith(\"POINT\")) {\n return AV(t2.replace(/^POINT \\(/, \"\").replace(/\\)$/, \"\"));\n }\n if (t2.startsWith(\"MULTIPOINT\")) {\n return OV(t2.replace(/^MULTIPOINT \\(/, \"\").replace(/\\)$/, \"\"));\n }\n if (t2.startsWith(\"LINESTRING\")) {\n return kV(t2.replace(/^LINESTRING \\(/, \"\").replace(/\\)$/, \"\"));\n }\n if (t2.startsWith(\"MULTILINESTRING\")) {\n return function(e50) {\n return e50.replace(/\\(\\(/, \"\").replace(/\\)\\)$/, \"\").split(\"), (\").map(kV);\n }(t2.replace(/^MULTILINESTRING /, \"\"));\n }\n if (t2.startsWith(\"POLYGON\") || t2.startsWith(\"MULTIPOLYGON\"))\n return LV(t2);\n if (t2.startsWith(\"GEOMETRYCOLLECTION\")) {\n const n2 = /(?\u003ctype\u003ePOINT|LINESTRING|POLYGON|MULTIPOINT|MULTILINESTRING|MULTIPOLYGON) \\((?:[^\\(\\)]|\\([^\\)]*\\))*\\)/g, o3 = t2.match(n2);\n o3[0].startsWith(\"GEOMETRYCOLLECTION\") \u0026\u0026 (o3[0] = o3[0].replace(\"GEOMETRYCOLLECTION (\", \"\"));\n return o3.map(e49).map((e50) =\u003e e50 instanceof Array ? e50 : [e50]).reduce((e50, t3) =\u003e [...e50, ...t3], []);\n }\n return zV(t2) ? function(e50) {\n return e50.split(`\n`).map((e51) =\u003e e51.match(/\\(([^)]+)\\)/)[1]).map(AV);\n }(t2) : BV(t2) ? function(e50) {\n return e50.split(`\n`).map((e51) =\u003e e51.match(/\\(([^)]+)\\)/)[1]).map(kV).reduce((e51, t3) =\u003e [...e51, ...t3], []);\n }(t2) : [];\n}, kX.BooleanOperations = JH, kX.Relations = uV;\nFV = SY(), jV = 1, $V = FV != null ? iY(cY(FV)) : {}, ((e50, t2, n2, o3) =\u003e {\n if (t2 \u0026\u0026 typeof t2 == \"object\" || typeof t2 == \"function\")\n for (let i3 of aY(t2))\n lY.call(e50, i3) || i3 === n2 || rY(e50, i3, { get: () =\u003e t2[i3], enumerable: !(o3 = sY(t2, i3)) || o3.enumerable });\n})(!jV \u0026\u0026 FV \u0026\u0026 FV.__esModule ? $V : rY($V, \"default\", { value: FV, enumerable: true }), FV);\nvar FV;\nvar jV;\nvar $V;\nvar YV = Object.create;\nvar XV = Object.defineProperty;\nvar HV = Object.getOwnPropertyDescriptor;\nvar VV = Object.getOwnPropertyNames;\nvar WV = Object.getPrototypeOf;\nvar GV = Object.prototype.hasOwnProperty;\nvar UV = (e50, t2) =\u003e function() {\n return t2 || (0, e50[VV(e50)[0]])((t2 = { exports: {} }).exports, t2), t2.exports;\n};\nvar ZV = (e50, t2, n2) =\u003e (n2 = e50 != null ? YV(WV(e50)) : {}, ((e51, t3, n3, o3) =\u003e {\n if (t3 \u0026\u0026 typeof t3 == \"object\" || typeof t3 == \"function\")\n for (let i3 of VV(t3))\n GV.call(e51, i3) || i3 === n3 || XV(e51, i3, { get: () =\u003e t3[i3], enumerable: !(o3 = HV(t3, i3)) || o3.enumerable });\n return e51;\n})(!t2 \u0026\u0026 e50 \u0026\u0026 e50.__esModule ? n2 : XV(n2, \"default\", { value: e50, enumerable: true }), e50));\nvar qV = UV({ \"node_modules/is-buffer/index.js\"(e50, t2) {\n function n2(e51) {\n return !!e51.constructor \u0026\u0026 typeof e51.constructor.isBuffer == \"function\" \u0026\u0026 e51.constructor.isBuffer(e51);\n }\n t2.exports = function(e51) {\n return e51 != null \u0026\u0026 (n2(e51) || function(e52) {\n return typeof e52.readFloatLE == \"function\" \u0026\u0026 typeof e52.slice == \"function\" \u0026\u0026 n2(e52.slice(0, 0));\n }(e51) || !!e51._isBuffer);\n };\n} });\nvar JV = UV({ \"node_modules/kind-of/index.js\"(e50, t2) {\n var n2 = qV(), o3 = Object.prototype.toString;\n t2.exports = function(e51) {\n if (e51 === undefined)\n return \"undefined\";\n if (e51 === null)\n return \"null\";\n if (e51 === true || e51 === false || e51 instanceof Boolean)\n return \"boolean\";\n if (typeof e51 == \"string\" || e51 instanceof String)\n return \"string\";\n if (typeof e51 == \"number\" || e51 instanceof Number)\n return \"number\";\n if (typeof e51 == \"function\" || e51 instanceof Function)\n return \"function\";\n if (Array.isArray !== undefined \u0026\u0026 Array.isArray(e51))\n return \"array\";\n if (e51 instanceof RegExp)\n return \"regexp\";\n if (e51 instanceof Date)\n return \"date\";\n var t3 = o3.call(e51);\n return t3 === \"[object RegExp]\" ? \"regexp\" : t3 === \"[object Date]\" ? \"date\" : t3 === \"[object Arguments]\" ? \"arguments\" : t3 === \"[object Error]\" ? \"error\" : n2(e51) ? \"buffer\" : t3 === \"[object Set]\" ? \"set\" : t3 === \"[object WeakSet]\" ? \"weakset\" : t3 === \"[object Map]\" ? \"map\" : t3 === \"[object WeakMap]\" ? \"weakmap\" : t3 === \"[object Symbol]\" ? \"symbol\" : t3 === \"[object Int8Array]\" ? \"int8array\" : t3 === \"[object Uint8Array]\" ? \"uint8array\" : t3 === \"[object Uint8ClampedArray]\" ? \"uint8clampedarray\" : t3 === \"[object Int16Array]\" ? \"int16array\" : t3 === \"[object Uint16Array]\" ? \"uint16array\" : t3 === \"[object Int32Array]\" ? \"int32array\" : t3 === \"[object Uint32Array]\" ? \"uint32array\" : t3 === \"[object Float32Array]\" ? \"float32array\" : t3 === \"[object Float64Array]\" ? \"float64array\" : \"object\";\n };\n} });\nvar QV = UV({ \"node_modules/rename-keys/index.js\"(e50, t2) {\n (function() {\n function e51(e52, t3) {\n if (typeof t3 != \"function\")\n return e52;\n var n2 = {};\n for (var o3 in e52)\n Object.prototype.hasOwnProperty.call(e52, o3) \u0026\u0026 (n2[t3(o3, e52[o3]) || o3] = e52[o3]);\n return n2;\n }\n t2 !== undefined \u0026\u0026 t2.exports ? t2.exports = e51 : typeof define == \"function\" \u0026\u0026 define.amd ? define([], function() {\n return e51;\n }) : window.rename = e51;\n })();\n} });\nvar KV = UV({ \"node_modules/deep-rename-keys/index.js\"(e50, t2) {\n var n2 = JV(), o3 = QV();\n t2.exports = function e51(t3, i3) {\n var r3 = n2(t3);\n if (r3 !== \"object\" \u0026\u0026 r3 !== \"array\")\n throw new Error(\"expected an object\");\n var s2 = [];\n for (var a3 in r3 === \"object\" \u0026\u0026 (t3 = o3(t3, i3), s2 = {}), t3)\n if (t3.hasOwnProperty(a3)) {\n var c3 = t3[a3];\n n2(c3) === \"object\" || n2(c3) === \"array\" ? s2[a3] = e51(c3, i3) : s2[a3] = c3;\n }\n return s2;\n };\n} });\nvar eW = UV({ \"node_modules/eventemitter3/index.js\"(e50, t2) {\n var n2 = Object.prototype.hasOwnProperty, o3 = \"~\";\n function i3() {}\n function r3(e51, t3, n3) {\n this.fn = e51, this.context = t3, this.once = n3 || false;\n }\n function s2() {\n this._events = new i3, this._eventsCount = 0;\n }\n Object.create \u0026\u0026 (i3.prototype = Object.create(null), new i3().__proto__ || (o3 = false)), s2.prototype.eventNames = function() {\n var e51, t3, i4 = [];\n if (this._eventsCount === 0)\n return i4;\n for (t3 in e51 = this._events)\n n2.call(e51, t3) \u0026\u0026 i4.push(o3 ? t3.slice(1) : t3);\n return Object.getOwnPropertySymbols ? i4.concat(Object.getOwnPropertySymbols(e51)) : i4;\n }, s2.prototype.listeners = function(e51, t3) {\n var n3 = o3 ? o3 + e51 : e51, i4 = this._events[n3];\n if (t3)\n return !!i4;\n if (!i4)\n return [];\n if (i4.fn)\n return [i4.fn];\n for (var r4 = 0, s3 = i4.length, a3 = new Array(s3);r4 \u003c s3; r4++)\n a3[r4] = i4[r4].fn;\n return a3;\n }, s2.prototype.emit = function(e51, t3, n3, i4, r4, s3) {\n var a3 = o3 ? o3 + e51 : e51;\n if (!this._events[a3])\n return false;\n var c3, l3, h2 = this._events[a3], d2 = arguments.length;\n if (h2.fn) {\n switch (h2.once \u0026\u0026 this.removeListener(e51, h2.fn, undefined, true), d2) {\n case 1:\n return h2.fn.call(h2.context), true;\n case 2:\n return h2.fn.call(h2.context, t3), true;\n case 3:\n return h2.fn.call(h2.context, t3, n3), true;\n case 4:\n return h2.fn.call(h2.context, t3, n3, i4), true;\n case 5:\n return h2.fn.call(h2.context, t3, n3, i4, r4), true;\n case 6:\n return h2.fn.call(h2.context, t3, n3, i4, r4, s3), true;\n }\n for (l3 = 1, c3 = new Array(d2 - 1);l3 \u003c d2; l3++)\n c3[l3 - 1] = arguments[l3];\n h2.fn.apply(h2.context, c3);\n } else {\n var u2, p3 = h2.length;\n for (l3 = 0;l3 \u003c p3; l3++)\n switch (h2[l3].once \u0026\u0026 this.removeListener(e51, h2[l3].fn, undefined, true), d2) {\n case 1:\n h2[l3].fn.call(h2[l3].context);\n break;\n case 2:\n h2[l3].fn.call(h2[l3].context, t3);\n break;\n case 3:\n h2[l3].fn.call(h2[l3].context, t3, n3);\n break;\n case 4:\n h2[l3].fn.call(h2[l3].context, t3, n3, i4);\n break;\n default:\n if (!c3)\n for (u2 = 1, c3 = new Array(d2 - 1);u2 \u003c d2; u2++)\n c3[u2 - 1] = arguments[u2];\n h2[l3].fn.apply(h2[l3].context, c3);\n }\n }\n return true;\n }, s2.prototype.on = function(e51, t3, n3) {\n var i4 = new r3(t3, n3 || this), s3 = o3 ? o3 + e51 : e51;\n return this._events[s3] ? this._events[s3].fn ? this._events[s3] = [this._events[s3], i4] : this._events[s3].push(i4) : (this._events[s3] = i4, this._eventsCount++), this;\n }, s2.prototype.once = function(e51, t3, n3) {\n var i4 = new r3(t3, n3 || this, true), s3 = o3 ? o3 + e51 : e51;\n return this._events[s3] ? this._events[s3].fn ? this._events[s3] = [this._events[s3], i4] : this._events[s3].push(i4) : (this._events[s3] = i4, this._eventsCount++), this;\n }, s2.prototype.removeListener = function(e51, t3, n3, r4) {\n var s3 = o3 ? o3 + e51 : e51;\n if (!this._events[s3])\n return this;\n if (!t3)\n return --this._eventsCount === 0 ? this._events = new i3 : delete this._events[s3], this;\n var a3 = this._events[s3];\n if (a3.fn)\n a3.fn !== t3 || r4 \u0026\u0026 !a3.once || n3 \u0026\u0026 a3.context !== n3 || (--this._eventsCount === 0 ? this._events = new i3 : delete this._events[s3]);\n else {\n for (var c3 = 0, l3 = [], h2 = a3.length;c3 \u003c h2; c3++)\n (a3[c3].fn !== t3 || r4 \u0026\u0026 !a3[c3].once || n3 \u0026\u0026 a3[c3].context !== n3) \u0026\u0026 l3.push(a3[c3]);\n l3.length ? this._events[s3] = l3.length === 1 ? l3[0] : l3 : --this._eventsCount === 0 ? this._events = new i3 : delete this._events[s3];\n }\n return this;\n }, s2.prototype.removeAllListeners = function(e51) {\n var t3;\n return e51 ? (t3 = o3 ? o3 + e51 : e51, this._events[t3] \u0026\u0026 (--this._eventsCount === 0 ? this._events = new i3 : delete this._events[t3])) : (this._events = new i3, this._eventsCount = 0), this;\n }, s2.prototype.off = s2.prototype.removeListener, s2.prototype.addListener = s2.prototype.on, s2.prototype.setMaxListeners = function() {\n return this;\n }, s2.prefixed = o3, s2.EventEmitter = s2, t2 !== undefined \u0026\u0026 (t2.exports = s2);\n} });\nvar tW = UV({ \"node_modules/xml-lexer/dist/lexer.js\"(e50, t2) {\n function n2(e51, t3, n3) {\n return t3 in e51 ? Object.defineProperty(e51, t3, { value: n3, enumerable: true, configurable: true, writable: true }) : e51[t3] = n3, e51;\n }\n var o3 = eW(), i3 = function() {}, r3 = { 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\" }, s2 = { 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\" }, c3 = { \" \": s2.space, \"\\t\": s2.space, \"\\n\": s2.space, \"\\r\": s2.space, \"\u003c\": s2.lt, \"\u003e\": s2.gt, '\"': s2.quote, \"'\": s2.quote, \"=\": s2.equal, \"/\": s2.slash };\n t2.exports = { State: r3, Action: s2, Type: a3, create: function(e51) {\n var t3, l3, h2, d2, u2, p3, m2, g2, f2, _2;\n e51 = Object.assign({ debug: false }, e51);\n var y2 = new o3, b2 = r3.data, x2 = \"\", v2 = \"\", I2 = \"\", S2 = \"\", C = \"\", P = \"\", M = function(t4, n3) {\n if (v2[0] !== \"?\" \u0026\u0026 v2[0] !== \"!\") {\n var o4 = { type: t4, value: n3 };\n e51.debug \u0026\u0026 console.log(\"emit:\", o4), y2.emit(\"data\", o4);\n }\n };\n y2.stateMachine = (n2(_2 = {}, r3.data, (n2(t3 = {}, s2.lt, function() {\n x2.trim() \u0026\u0026 M(a3.text, x2), v2 = \"\", C = false, b2 = r3.tagBegin;\n }), n2(t3, s2.char, function(e52) {\n x2 += e52;\n }), t3)), n2(_2, r3.cdata, n2({}, s2.char, function(e52) {\n (x2 += e52).substr(-3) === \"]]\u003e\" \u0026\u0026 (M(a3.text, x2.slice(0, -3)), x2 = \"\", b2 = r3.data);\n })), n2(_2, r3.tagBegin, (n2(l3 = {}, s2.space, i3), n2(l3, s2.char, function(e52) {\n v2 = e52, b2 = r3.tagName;\n }), n2(l3, s2.slash, function() {\n v2 = \"\", C = true;\n }), l3)), n2(_2, r3.tagName, (n2(h2 = {}, s2.space, function() {\n C ? b2 = r3.tagEnd : (b2 = r3.attributeNameStart, M(a3.openTag, v2));\n }), n2(h2, s2.gt, function() {\n M(C ? a3.closeTag : a3.openTag, v2), x2 = \"\", b2 = r3.data;\n }), n2(h2, s2.slash, function() {\n b2 = r3.tagEnd, M(a3.openTag, v2);\n }), n2(h2, s2.char, function(e52) {\n (v2 += e52) === \"![CDATA[\" \u0026\u0026 (b2 = r3.cdata, x2 = \"\", v2 = \"\");\n }), h2)), n2(_2, r3.tagEnd, (n2(d2 = {}, s2.gt, function() {\n M(a3.closeTag, v2), x2 = \"\", b2 = r3.data;\n }), n2(d2, s2.char, i3), d2)), n2(_2, r3.attributeNameStart, (n2(u2 = {}, s2.char, function(e52) {\n I2 = e52, b2 = r3.attributeName;\n }), n2(u2, s2.gt, function() {\n x2 = \"\", b2 = r3.data;\n }), n2(u2, s2.space, i3), n2(u2, s2.slash, function() {\n C = true, b2 = r3.tagEnd;\n }), u2)), n2(_2, r3.attributeName, (n2(p3 = {}, s2.space, function() {\n b2 = r3.attributeNameEnd;\n }), n2(p3, s2.equal, function() {\n M(a3.attributeName, I2), b2 = r3.attributeValueBegin;\n }), n2(p3, s2.gt, function() {\n S2 = \"\", M(a3.attributeName, I2), M(a3.attributeValue, S2), x2 = \"\", b2 = r3.data;\n }), n2(p3, s2.slash, function() {\n C = true, S2 = \"\", M(a3.attributeName, I2), M(a3.attributeValue, S2), b2 = r3.tagEnd;\n }), n2(p3, s2.char, function(e52) {\n I2 += e52;\n }), p3)), n2(_2, r3.attributeNameEnd, (n2(m2 = {}, s2.space, i3), n2(m2, s2.equal, function() {\n M(a3.attributeName, I2), b2 = r3.attributeValueBegin;\n }), n2(m2, s2.gt, function() {\n S2 = \"\", M(a3.attributeName, I2), M(a3.attributeValue, S2), x2 = \"\", b2 = r3.data;\n }), n2(m2, s2.char, function(e52) {\n S2 = \"\", M(a3.attributeName, I2), M(a3.attributeValue, S2), I2 = e52, b2 = r3.attributeName;\n }), m2)), n2(_2, r3.attributeValueBegin, (n2(g2 = {}, s2.space, i3), n2(g2, s2.quote, function(e52) {\n P = e52, S2 = \"\", b2 = r3.attributeValue;\n }), n2(g2, s2.gt, function() {\n M(a3.attributeValue, S2 = \"\"), x2 = \"\", b2 = r3.data;\n }), n2(g2, s2.char, function(e52) {\n P = \"\", S2 = e52, b2 = r3.attributeValue;\n }), g2)), n2(_2, r3.attributeValue, (n2(f2 = {}, s2.space, function(e52) {\n P ? S2 += e52 : (M(a3.attributeValue, S2), b2 = r3.attributeNameStart);\n }), n2(f2, s2.quote, function(e52) {\n P === e52 ? (M(a3.attributeValue, S2), b2 = r3.attributeNameStart) : S2 += e52;\n }), n2(f2, s2.gt, function(e52) {\n P ? S2 += e52 : (M(a3.attributeValue, S2), x2 = \"\", b2 = r3.data);\n }), n2(f2, s2.slash, function(e52) {\n P ? S2 += e52 : (M(a3.attributeValue, S2), C = true, b2 = r3.tagEnd);\n }), n2(f2, s2.char, function(e52) {\n S2 += e52;\n }), f2)), _2);\n var w = function(t4) {\n e51.debug \u0026\u0026 console.log(b2, t4);\n var n3 = y2.stateMachine[b2], o4 = n3[function(e52) {\n return c3[e52] || s2.char;\n }(t4)] || n3[s2.error] || n3[s2.char];\n o4(t4);\n };\n return y2.write = function(e52) {\n for (var t4 = e52.length, n3 = 0;n3 \u003c t4; n3++)\n w(e52[n3]);\n }, y2;\n } };\n} });\nvar nW = UV({ \"node_modules/xml-reader/dist/reader.js\"(e50, t2) {\n var n2 = eW(), o3 = tW(), i3 = o3.Type, r3 = { element: \"element\", text: \"text\" }, s2 = function(e51) {\n return Object.assign({ name: \"\", type: r3.element, value: \"\", parent: null, attributes: {}, children: [] }, e51);\n }, a3 = function(e51) {\n e51 = Object.assign({ stream: false, parentNodes: true, doneEvent: \"done\", tagPrefix: \"tag:\", emitTopLevelOnly: false, debug: false }, e51);\n var t3 = undefined, a4 = undefined, c3 = undefined, l3 = undefined, h2 = new n2, d2 = function(n3) {\n switch (n3.type) {\n case i3.openTag:\n if (c3 === null)\n (c3 = a4).name = n3.value;\n else {\n var o4 = s2({ name: n3.value, parent: c3 });\n c3.children.push(o4), c3 = o4;\n }\n break;\n case i3.closeTag:\n var d3 = c3.parent;\n if (e51.parentNodes || (c3.parent = null), c3.name !== n3.value)\n break;\n e51.stream \u0026\u0026 d3 === a4 \u0026\u0026 (a4.children = [], c3.parent = null), e51.emitTopLevelOnly \u0026\u0026 d3 !== a4 || (h2.emit(e51.tagPrefix + c3.name, c3), h2.emit(\"tag\", c3.name, c3)), c3 === a4 \u0026\u0026 (t3.removeAllListeners(\"data\"), h2.emit(e51.doneEvent, c3), a4 = null), c3 = d3;\n break;\n case i3.text:\n c3 \u0026\u0026 c3.children.push(s2({ type: r3.text, value: n3.value, parent: e51.parentNodes ? c3 : null }));\n break;\n case i3.attributeName:\n l3 = n3.value, c3.attributes[l3] = \"\";\n break;\n case i3.attributeValue:\n c3.attributes[l3] = n3.value;\n }\n };\n return h2.reset = function() {\n (t3 = o3.create({ debug: e51.debug })).on(\"data\", d2), a4 = s2(), c3 = null, l3 = \"\", h2.parse = t3.write;\n }, h2.reset(), h2;\n };\n t2.exports = { parseSync: function(e51, t3) {\n t3 = Object.assign({}, t3, { stream: false, tagPrefix: \":\" });\n var n3 = a3(t3), o4 = undefined;\n return n3.on(\"done\", function(e52) {\n o4 = e52;\n }), n3.parse(e51), o4;\n }, create: a3, NodeType: r3 };\n} });\nvar aW = (ZV(KV()), ZV(nW()), Object.create);\nvar cW = Object.defineProperty;\nvar lW = Object.getOwnPropertyDescriptor;\nvar hW = Object.getOwnPropertyNames;\nvar dW = Object.getPrototypeOf;\nvar uW = Object.prototype.hasOwnProperty;\nvar pW = (e50, t2) =\u003e function() {\n return t2 || (0, e50[hW(e50)[0]])((t2 = { exports: {} }).exports, t2), t2.exports;\n};\nvar mW = (e50, t2, n2) =\u003e (n2 = e50 != null ? aW(dW(e50)) : {}, ((e51, t3, n3, o3) =\u003e {\n if (t3 \u0026\u0026 typeof t3 == \"object\" || typeof t3 == \"function\")\n for (let i3 of hW(t3))\n uW.call(e51, i3) || i3 === n3 || cW(e51, i3, { get: () =\u003e t3[i3], enumerable: !(o3 = lW(t3, i3)) || o3.enumerable });\n return e51;\n})(!t2 \u0026\u0026 e50 \u0026\u0026 e50.__esModule ? n2 : cW(n2, \"default\", { value: e50, enumerable: true }), e50));\nvar gW = pW({ \"node_modules/is-buffer/index.js\"(e50, t2) {\n function n2(e51) {\n return !!e51.constructor \u0026\u0026 typeof e51.constructor.isBuffer == \"function\" \u0026\u0026 e51.constructor.isBuffer(e51);\n }\n t2.exports = function(e51) {\n return e51 != null \u0026\u0026 (n2(e51) || function(e52) {\n return typeof e52.readFloatLE == \"function\" \u0026\u0026 typeof e52.slice == \"function\" \u0026\u0026 n2(e52.slice(0, 0));\n }(e51) || !!e51._isBuffer);\n };\n} });\nvar fW = pW({ \"node_modules/kind-of/index.js\"(e50, t2) {\n var n2 = gW(), o3 = Object.prototype.toString;\n t2.exports = function(e51) {\n if (e51 === undefined)\n return \"undefined\";\n if (e51 === null)\n return \"null\";\n if (e51 === true || e51 === false || e51 instanceof Boolean)\n return \"boolean\";\n if (typeof e51 == \"string\" || e51 instanceof String)\n return \"string\";\n if (typeof e51 == \"number\" || e51 instanceof Number)\n return \"number\";\n if (typeof e51 == \"function\" || e51 instanceof Function)\n return \"function\";\n if (Array.isArray !== undefined \u0026\u0026 Array.isArray(e51))\n return \"array\";\n if (e51 instanceof RegExp)\n return \"regexp\";\n if (e51 instanceof Date)\n return \"date\";\n var t3 = o3.call(e51);\n return t3 === \"[object RegExp]\" ? \"regexp\" : t3 === \"[object Date]\" ? \"date\" : t3 === \"[object Arguments]\" ? \"arguments\" : t3 === \"[object Error]\" ? \"error\" : n2(e51) ? \"buffer\" : t3 === \"[object Set]\" ? \"set\" : t3 === \"[object WeakSet]\" ? \"weakset\" : t3 === \"[object Map]\" ? \"map\" : t3 === \"[object WeakMap]\" ? \"weakmap\" : t3 === \"[object Symbol]\" ? \"symbol\" : t3 === \"[object Int8Array]\" ? \"int8array\" : t3 === \"[object Uint8Array]\" ? \"uint8array\" : t3 === \"[object Uint8ClampedArray]\" ? \"uint8clampedarray\" : t3 === \"[object Int16Array]\" ? \"int16array\" : t3 === \"[object Uint16Array]\" ? \"uint16array\" : t3 === \"[object Int32Array]\" ? \"int32array\" : t3 === \"[object Uint32Array]\" ? \"uint32array\" : t3 === \"[object Float32Array]\" ? \"float32array\" : t3 === \"[object Float64Array]\" ? \"float64array\" : \"object\";\n };\n} });\nvar _W = pW({ \"node_modules/rename-keys/index.js\"(e50, t2) {\n (function() {\n function e51(e52, t3) {\n if (typeof t3 != \"function\")\n return e52;\n var n2 = {};\n for (var o3 in e52)\n Object.prototype.hasOwnProperty.call(e52, o3) \u0026\u0026 (n2[t3(o3, e52[o3]) || o3] = e52[o3]);\n return n2;\n }\n t2 !== undefined \u0026\u0026 t2.exports ? t2.exports = e51 : typeof define == \"function\" \u0026\u0026 define.amd ? define([], function() {\n return e51;\n }) : window.rename = e51;\n })();\n} });\nvar yW = pW({ \"node_modules/deep-rename-keys/index.js\"(e50, t2) {\n var n2 = fW(), o3 = _W();\n t2.exports = function e51(t3, i3) {\n var r3 = n2(t3);\n if (r3 !== \"object\" \u0026\u0026 r3 !== \"array\")\n throw new Error(\"expected an object\");\n var s2 = [];\n for (var a3 in r3 === \"object\" \u0026\u0026 (t3 = o3(t3, i3), s2 = {}), t3)\n if (t3.hasOwnProperty(a3)) {\n var c3 = t3[a3];\n n2(c3) === \"object\" || n2(c3) === \"array\" ? s2[a3] = e51(c3, i3) : s2[a3] = c3;\n }\n return s2;\n };\n} });\nvar bW = pW({ \"node_modules/eventemitter3/index.js\"(e50, t2) {\n var n2 = Object.prototype.hasOwnProperty, o3 = \"~\";\n function i3() {}\n function r3(e51, t3, n3) {\n this.fn = e51, this.context = t3, this.once = n3 || false;\n }\n function s2() {\n this._events = new i3, this._eventsCount = 0;\n }\n Object.create \u0026\u0026 (i3.prototype = Object.create(null), new i3().__proto__ || (o3 = false)), s2.prototype.eventNames = function() {\n var e51, t3, i4 = [];\n if (this._eventsCount === 0)\n return i4;\n for (t3 in e51 = this._events)\n n2.call(e51, t3) \u0026\u0026 i4.push(o3 ? t3.slice(1) : t3);\n return Object.getOwnPropertySymbols ? i4.concat(Object.getOwnPropertySymbols(e51)) : i4;\n }, s2.prototype.listeners = function(e51, t3) {\n var n3 = o3 ? o3 + e51 : e51, i4 = this._events[n3];\n if (t3)\n return !!i4;\n if (!i4)\n return [];\n if (i4.fn)\n return [i4.fn];\n for (var r4 = 0, s3 = i4.length, a3 = new Array(s3);r4 \u003c s3; r4++)\n a3[r4] = i4[r4].fn;\n return a3;\n }, s2.prototype.emit = function(e51, t3, n3, i4, r4, s3) {\n var a3 = o3 ? o3 + e51 : e51;\n if (!this._events[a3])\n return false;\n var c3, l3, h2 = this._events[a3], d2 = arguments.length;\n if (h2.fn) {\n switch (h2.once \u0026\u0026 this.removeListener(e51, h2.fn, undefined, true), d2) {\n case 1:\n return h2.fn.call(h2.context), true;\n case 2:\n return h2.fn.call(h2.context, t3), true;\n case 3:\n return h2.fn.call(h2.context, t3, n3), true;\n case 4:\n return h2.fn.call(h2.context, t3, n3, i4), true;\n case 5:\n return h2.fn.call(h2.context, t3, n3, i4, r4), true;\n case 6:\n return h2.fn.call(h2.context, t3, n3, i4, r4, s3), true;\n }\n for (l3 = 1, c3 = new Array(d2 - 1);l3 \u003c d2; l3++)\n c3[l3 - 1] = arguments[l3];\n h2.fn.apply(h2.context, c3);\n } else {\n var u2, p3 = h2.length;\n for (l3 = 0;l3 \u003c p3; l3++)\n switch (h2[l3].once \u0026\u0026 this.removeListener(e51, h2[l3].fn, undefined, true), d2) {\n case 1:\n h2[l3].fn.call(h2[l3].context);\n break;\n case 2:\n h2[l3].fn.call(h2[l3].context, t3);\n break;\n case 3:\n h2[l3].fn.call(h2[l3].context, t3, n3);\n break;\n case 4:\n h2[l3].fn.call(h2[l3].context, t3, n3, i4);\n break;\n default:\n if (!c3)\n for (u2 = 1, c3 = new Array(d2 - 1);u2 \u003c d2; u2++)\n c3[u2 - 1] = arguments[u2];\n h2[l3].fn.apply(h2[l3].context, c3);\n }\n }\n return true;\n }, s2.prototype.on = function(e51, t3, n3) {\n var i4 = new r3(t3, n3 || this), s3 = o3 ? o3 + e51 : e51;\n return this._events[s3] ? this._events[s3].fn ? this._events[s3] = [this._events[s3], i4] : this._events[s3].push(i4) : (this._events[s3] = i4, this._eventsCount++), this;\n }, s2.prototype.once = function(e51, t3, n3) {\n var i4 = new r3(t3, n3 || this, true), s3 = o3 ? o3 + e51 : e51;\n return this._events[s3] ? this._events[s3].fn ? this._events[s3] = [this._events[s3], i4] : this._events[s3].push(i4) : (this._events[s3] = i4, this._eventsCount++), this;\n }, s2.prototype.removeListener = function(e51, t3, n3, r4) {\n var s3 = o3 ? o3 + e51 : e51;\n if (!this._events[s3])\n return this;\n if (!t3)\n return --this._eventsCount === 0 ? this._events = new i3 : delete this._events[s3], this;\n var a3 = this._events[s3];\n if (a3.fn)\n a3.fn !== t3 || r4 \u0026\u0026 !a3.once || n3 \u0026\u0026 a3.context !== n3 || (--this._eventsCount === 0 ? this._events = new i3 : delete this._events[s3]);\n else {\n for (var c3 = 0, l3 = [], h2 = a3.length;c3 \u003c h2; c3++)\n (a3[c3].fn !== t3 || r4 \u0026\u0026 !a3[c3].once || n3 \u0026\u0026 a3[c3].context !== n3) \u0026\u0026 l3.push(a3[c3]);\n l3.length ? this._events[s3] = l3.length === 1 ? l3[0] : l3 : --this._eventsCount === 0 ? this._events = new i3 : delete this._events[s3];\n }\n return this;\n }, s2.prototype.removeAllListeners = function(e51) {\n var t3;\n return e51 ? (t3 = o3 ? o3 + e51 : e51, this._events[t3] \u0026\u0026 (--this._eventsCount === 0 ? this._events = new i3 : delete this._events[t3])) : (this._events = new i3, this._eventsCount = 0), this;\n }, s2.prototype.off = s2.prototype.removeListener, s2.prototype.addListener = s2.prototype.on, s2.prototype.setMaxListeners = function() {\n return this;\n }, s2.prefixed = o3, s2.EventEmitter = s2, t2 !== undefined \u0026\u0026 (t2.exports = s2);\n} });\nvar xW = pW({ \"node_modules/xml-lexer/dist/lexer.js\"(e50, t2) {\n function n2(e51, t3, n3) {\n return t3 in e51 ? Object.defineProperty(e51, t3, { value: n3, enumerable: true, configurable: true, writable: true }) : e51[t3] = n3, e51;\n }\n var o3 = bW(), i3 = function() {}, r3 = { 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\" }, s2 = { 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\" }, c3 = { \" \": s2.space, \"\\t\": s2.space, \"\\n\": s2.space, \"\\r\": s2.space, \"\u003c\": s2.lt, \"\u003e\": s2.gt, '\"': s2.quote, \"'\": s2.quote, \"=\": s2.equal, \"/\": s2.slash };\n t2.exports = { State: r3, Action: s2, Type: a3, create: function(e51) {\n var t3, l3, h2, d2, u2, p3, m2, g2, f2, _2;\n e51 = Object.assign({ debug: false }, e51);\n var y2 = new o3, b2 = r3.data, x2 = \"\", v2 = \"\", I2 = \"\", S2 = \"\", C = \"\", P = \"\", M = function(t4, n3) {\n if (v2[0] !== \"?\" \u0026\u0026 v2[0] !== \"!\") {\n var o4 = { type: t4, value: n3 };\n e51.debug \u0026\u0026 console.log(\"emit:\", o4), y2.emit(\"data\", o4);\n }\n };\n y2.stateMachine = (n2(_2 = {}, r3.data, (n2(t3 = {}, s2.lt, function() {\n x2.trim() \u0026\u0026 M(a3.text, x2), v2 = \"\", C = false, b2 = r3.tagBegin;\n }), n2(t3, s2.char, function(e52) {\n x2 += e52;\n }), t3)), n2(_2, r3.cdata, n2({}, s2.char, function(e52) {\n (x2 += e52).substr(-3) === \"]]\u003e\" \u0026\u0026 (M(a3.text, x2.slice(0, -3)), x2 = \"\", b2 = r3.data);\n })), n2(_2, r3.tagBegin, (n2(l3 = {}, s2.space, i3), n2(l3, s2.char, function(e52) {\n v2 = e52, b2 = r3.tagName;\n }), n2(l3, s2.slash, function() {\n v2 = \"\", C = true;\n }), l3)), n2(_2, r3.tagName, (n2(h2 = {}, s2.space, function() {\n C ? b2 = r3.tagEnd : (b2 = r3.attributeNameStart, M(a3.openTag, v2));\n }), n2(h2, s2.gt, function() {\n M(C ? a3.closeTag : a3.openTag, v2), x2 = \"\", b2 = r3.data;\n }), n2(h2, s2.slash, function() {\n b2 = r3.tagEnd, M(a3.openTag, v2);\n }), n2(h2, s2.char, function(e52) {\n (v2 += e52) === \"![CDATA[\" \u0026\u0026 (b2 = r3.cdata, x2 = \"\", v2 = \"\");\n }), h2)), n2(_2, r3.tagEnd, (n2(d2 = {}, s2.gt, function() {\n M(a3.closeTag, v2), x2 = \"\", b2 = r3.data;\n }), n2(d2, s2.char, i3), d2)), n2(_2, r3.attributeNameStart, (n2(u2 = {}, s2.char, function(e52) {\n I2 = e52, b2 = r3.attributeName;\n }), n2(u2, s2.gt, function() {\n x2 = \"\", b2 = r3.data;\n }), n2(u2, s2.space, i3), n2(u2, s2.slash, function() {\n C = true, b2 = r3.tagEnd;\n }), u2)), n2(_2, r3.attributeName, (n2(p3 = {}, s2.space, function() {\n b2 = r3.attributeNameEnd;\n }), n2(p3, s2.equal, function() {\n M(a3.attributeName, I2), b2 = r3.attributeValueBegin;\n }), n2(p3, s2.gt, function() {\n S2 = \"\", M(a3.attributeName, I2), M(a3.attributeValue, S2), x2 = \"\", b2 = r3.data;\n }), n2(p3, s2.slash, function() {\n C = true, S2 = \"\", M(a3.attributeName, I2), M(a3.attributeValue, S2), b2 = r3.tagEnd;\n }), n2(p3, s2.char, function(e52) {\n I2 += e52;\n }), p3)), n2(_2, r3.attributeNameEnd, (n2(m2 = {}, s2.space, i3), n2(m2, s2.equal, function() {\n M(a3.attributeName, I2), b2 = r3.attributeValueBegin;\n }), n2(m2, s2.gt, function() {\n S2 = \"\", M(a3.attributeName, I2), M(a3.attributeValue, S2), x2 = \"\", b2 = r3.data;\n }), n2(m2, s2.char, function(e52) {\n S2 = \"\", M(a3.attributeName, I2), M(a3.attributeValue, S2), I2 = e52, b2 = r3.attributeName;\n }), m2)), n2(_2, r3.attributeValueBegin, (n2(g2 = {}, s2.space, i3), n2(g2, s2.quote, function(e52) {\n P = e52, S2 = \"\", b2 = r3.attributeValue;\n }), n2(g2, s2.gt, function() {\n M(a3.attributeValue, S2 = \"\"), x2 = \"\", b2 = r3.data;\n }), n2(g2, s2.char, function(e52) {\n P = \"\", S2 = e52, b2 = r3.attributeValue;\n }), g2)), n2(_2, r3.attributeValue, (n2(f2 = {}, s2.space, function(e52) {\n P ? S2 += e52 : (M(a3.attributeValue, S2), b2 = r3.attributeNameStart);\n }), n2(f2, s2.quote, function(e52) {\n P === e52 ? (M(a3.attributeValue, S2), b2 = r3.attributeNameStart) : S2 += e52;\n }), n2(f2, s2.gt, function(e52) {\n P ? S2 += e52 : (M(a3.attributeValue, S2), x2 = \"\", b2 = r3.data);\n }), n2(f2, s2.slash, function(e52) {\n P ? S2 += e52 : (M(a3.attributeValue, S2), C = true, b2 = r3.tagEnd);\n }), n2(f2, s2.char, function(e52) {\n S2 += e52;\n }), f2)), _2);\n var w = function(t4) {\n e51.debug \u0026\u0026 console.log(b2, t4);\n var n3 = y2.stateMachine[b2], o4 = n3[function(e52) {\n return c3[e52] || s2.char;\n }(t4)] || n3[s2.error] || n3[s2.char];\n o4(t4);\n };\n return y2.write = function(e52) {\n for (var t4 = e52.length, n3 = 0;n3 \u003c t4; n3++)\n w(e52[n3]);\n }, y2;\n } };\n} });\nvar vW = pW({ \"node_modules/xml-reader/dist/reader.js\"(e50, t2) {\n var n2 = bW(), o3 = xW(), i3 = o3.Type, r3 = { element: \"element\", text: \"text\" }, s2 = function(e51) {\n return Object.assign({ name: \"\", type: r3.element, value: \"\", parent: null, attributes: {}, children: [] }, e51);\n }, a3 = function(e51) {\n e51 = Object.assign({ stream: false, parentNodes: true, doneEvent: \"done\", tagPrefix: \"tag:\", emitTopLevelOnly: false, debug: false }, e51);\n var t3 = undefined, a4 = undefined, c3 = undefined, l3 = undefined, h2 = new n2, d2 = function(n3) {\n switch (n3.type) {\n case i3.openTag:\n if (c3 === null)\n (c3 = a4).name = n3.value;\n else {\n var o4 = s2({ name: n3.value, parent: c3 });\n c3.children.push(o4), c3 = o4;\n }\n break;\n case i3.closeTag:\n var d3 = c3.parent;\n if (e51.parentNodes || (c3.parent = null), c3.name !== n3.value)\n break;\n e51.stream \u0026\u0026 d3 === a4 \u0026\u0026 (a4.children = [], c3.parent = null), e51.emitTopLevelOnly \u0026\u0026 d3 !== a4 || (h2.emit(e51.tagPrefix + c3.name, c3), h2.emit(\"tag\", c3.name, c3)), c3 === a4 \u0026\u0026 (t3.removeAllListeners(\"data\"), h2.emit(e51.doneEvent, c3), a4 = null), c3 = d3;\n break;\n case i3.text:\n c3 \u0026\u0026 c3.children.push(s2({ type: r3.text, value: n3.value, parent: e51.parentNodes ? c3 : null }));\n break;\n case i3.attributeName:\n l3 = n3.value, c3.attributes[l3] = \"\";\n break;\n case i3.attributeValue:\n c3.attributes[l3] = n3.value;\n }\n };\n return h2.reset = function() {\n (t3 = o3.create({ debug: e51.debug })).on(\"data\", d2), a4 = s2(), c3 = null, l3 = \"\", h2.parse = t3.write;\n }, h2.reset(), h2;\n };\n t2.exports = { parseSync: function(e51, t3) {\n t3 = Object.assign({}, t3, { stream: false, tagPrefix: \":\" });\n var n3 = a3(t3), o4 = undefined;\n return n3.on(\"done\", function(e52) {\n o4 = e52;\n }), n3.parse(e51), o4;\n }, create: a3, NodeType: r3 };\n} });\nmW(yW()), mW(vW());\nfunction MW(e50, t2) {\n if (e50.points)\n for (const n2 of e50.points)\n n2.step = t2;\n if (e50.lines)\n for (const n2 of e50.lines)\n n2.step = t2;\n if (e50.infiniteLines)\n for (const n2 of e50.infiniteLines)\n n2.step = t2;\n if (e50.polygons)\n for (const n2 of e50.polygons)\n n2.step = t2;\n if (e50.rects)\n for (const n2 of e50.rects)\n n2.step = t2;\n if (e50.circles)\n for (const n2 of e50.circles)\n n2.step = t2;\n if (e50.texts)\n for (const n2 of e50.texts)\n n2.step = t2;\n return e50;\n}\nvar wW = class {\n MAX_ITERATIONS = 1e5;\n solved = false;\n failed = false;\n iterations = 0;\n progress = 0;\n error = null;\n activeSubSolver;\n failedSubSolvers;\n timeToSolve;\n stats = {};\n _setupDone = false;\n getSolverName() {\n return this.constructor.name;\n }\n setup() {\n this._setupDone || (this._setup(), this._setupDone = true);\n }\n _setup() {}\n step() {\n if (this._setupDone || this.setup(), !this.solved \u0026\u0026 !this.failed) {\n this.iterations++;\n try {\n this._step();\n } catch (e50) {\n throw this.error = `${this.getSolverName()} error: ${e50}`, this.failed = true, e50;\n }\n !this.solved \u0026\u0026 this.iterations \u003e= this.MAX_ITERATIONS \u0026\u0026 this.tryFinalAcceptance(), !this.solved \u0026\u0026 this.iterations \u003e= this.MAX_ITERATIONS \u0026\u0026 (this.error = `${this.getSolverName()} ran out of iterations`, this.failed = true), \"computeProgress\" in this \u0026\u0026 (this.progress = this.computeProgress());\n }\n }\n _step() {}\n getConstructorParams() {\n throw new Error(\"getConstructorParams not implemented\");\n }\n getOutput() {\n return null;\n }\n solve() {\n const e50 = Date.now();\n for (;!this.solved \u0026\u0026 !this.failed; )\n this.step();\n const t2 = Date.now();\n this.timeToSolve = t2 - e50;\n }\n visualize() {\n return { lines: [], points: [], rects: [], circles: [] };\n }\n tryFinalAcceptance() {}\n preview() {\n return { lines: [], points: [], rects: [], circles: [] };\n }\n};\nfunction NW(e50, t2, n2, o3 = {}) {\n return { solverName: e50, solverClass: t2, getConstructorParams: n2, onSolved: o3.onSolved };\n}\nvar RW = class extends wW {\n startTimeOfStage = {};\n endTimeOfStage = {};\n timeSpentOnStage = {};\n firstIterationOfStage = {};\n currentPipelineStageIndex = 0;\n inputProblem;\n pipelineOutputs = {};\n constructor(e50) {\n super(), this.inputProblem = e50, this.MAX_ITERATIONS = 1e6;\n }\n _step() {\n const e50 = this.pipelineDef[this.currentPipelineStageIndex];\n if (!e50)\n return void (this.solved = true);\n if (this.activeSubSolver) {\n if (this.activeSubSolver.step(), this.activeSubSolver.solved) {\n this.endTimeOfStage[e50.solverName] = performance.now(), this.timeSpentOnStage[e50.solverName] = this.endTimeOfStage[e50.solverName] - this.startTimeOfStage[e50.solverName];\n const t3 = this.activeSubSolver.getOutput();\n t3 !== null \u0026\u0026 (this.pipelineOutputs[e50.solverName] = t3), e50.onSolved?.(this), this.activeSubSolver = null, this.currentPipelineStageIndex++;\n } else\n this.activeSubSolver.failed \u0026\u0026 (this.error = this.activeSubSolver?.error, this.failed = true, this.activeSubSolver = null);\n return;\n }\n const t2 = e50.getConstructorParams(this);\n this.activeSubSolver = new e50.solverClass(...t2), this[e50.solverName] = this.activeSubSolver, this.timeSpentOnStage[e50.solverName] = 0, this.startTimeOfStage[e50.solverName] = performance.now(), this.firstIterationOfStage[e50.solverName] = this.iterations;\n }\n solveUntilStage(e50) {\n for (;this.getCurrentStageName().toLowerCase() !== e50.toLowerCase() \u0026\u0026 (this.step(), !this.failed \u0026\u0026 !this.solved); )\n ;\n }\n getCurrentStageName() {\n return this.pipelineDef[this.currentPipelineStageIndex]?.solverName ?? \"none\";\n }\n getStageProgress() {\n const e50 = this.pipelineDef.length;\n if (e50 === 0)\n return 1;\n const t2 = this.activeSubSolver?.progress ?? 0;\n return (this.currentPipelineStageIndex + t2) / e50;\n }\n getStageStats() {\n const e50 = {};\n for (const t2 of this.pipelineDef) {\n const n2 = this.timeSpentOnStage[t2.solverName] || 0, o3 = this.firstIterationOfStage[t2.solverName] || 0, i3 = this.iterations, r3 = t2.solverName === this.getCurrentStageName() ? i3 - o3 : 0, s2 = this.currentPipelineStageIndex \u003e this.pipelineDef.findIndex((e51) =\u003e e51.solverName === t2.solverName);\n e50[t2.solverName] = { timeSpent: n2, iterations: r3, completed: s2 };\n }\n return e50;\n }\n initialVisualize() {\n return null;\n }\n finalVisualize() {\n return null;\n }\n visualize() {\n if (!this.solved \u0026\u0026 this.activeSubSolver)\n return this.activeSubSolver.visualize();\n let e50 = 0;\n const t2 = this.initialVisualize();\n t2 \u0026\u0026 (MW(t2, 0), e50 = 1);\n let n2 = null;\n this.solved \u0026\u0026 (n2 = this.finalVisualize());\n const o3 = [t2].filter(Boolean).concat(this.pipelineDef.map((t3, n3) =\u003e {\n const o4 = this[t3.solverName], i3 = o4?.visualize();\n return i3 ? (MW(i3, n3 + e50), i3) : null;\n }).filter(Boolean));\n return o3.length === 0 ? { points: [], rects: [], lines: [], circles: [], texts: [] } : (this.solved \u0026\u0026 n2 \u0026\u0026 (MW(n2, o3.length + e50 + 1), o3.push(n2)), o3.length === 1 ? o3[0] : { points: o3.flatMap((e51) =\u003e e51.points || []), rects: o3.flatMap((e51) =\u003e e51.rects || []), lines: o3.flatMap((e51) =\u003e e51.lines || []), circles: o3.flatMap((e51) =\u003e e51.circles || []), texts: o3.flatMap((e51) =\u003e e51.texts || []) });\n }\n preview() {\n return this.activeSubSolver ? this.activeSubSolver.preview() : super.preview();\n }\n computeProgress() {\n return this.getStageProgress();\n }\n getStageOutput(e50) {\n return this.pipelineOutputs[e50];\n }\n getAllOutputs() {\n return { ...this.pipelineOutputs };\n }\n hasStageOutput(e50) {\n return e50 in this.pipelineOutputs;\n }\n getSolver(e50) {\n return this[e50];\n }\n};\nvar TW = (e50, t2, n2) =\u003e (t2.x - e50.x) * (n2.y - e50.y) - (t2.y - e50.y) * (n2.x - e50.x);\nvar EW = (e50, t2) =\u003e {\n const n2 = [...new Set(e50)].map((e51) =\u003e {\n const n3 = t2[e51];\n return n3 ? { i: e51, x: n3.x, y: n3.y } : null;\n }).filter((e51) =\u003e e51 !== null);\n if (n2.sort((e51, t3) =\u003e e51.x - t3.x || e51.y - t3.y), n2.length \u003c= 2)\n return n2.map((e51) =\u003e e51.i);\n const o3 = [], i3 = [];\n for (const e51 of n2) {\n for (;o3.length \u003e= 2; ) {\n const t3 = o3[o3.length - 2], n3 = o3[o3.length - 1];\n if (!t3 || !n3 || TW(t3, n3, e51) \u003e 0.0000000001)\n break;\n o3.pop();\n }\n o3.push(e51);\n }\n for (let e51 = n2.length - 1;e51 \u003e= 0; e51--) {\n const t3 = n2[e51];\n if (t3) {\n for (;i3.length \u003e= 2; ) {\n const e52 = i3[i3.length - 2], n3 = i3[i3.length - 1];\n if (!e52 || !n3 || TW(e52, n3, t3) \u003e 0.0000000001)\n break;\n i3.pop();\n }\n i3.push(t3);\n }\n }\n return o3.pop(), i3.pop(), o3.concat(i3).map((e51) =\u003e e51.i);\n};\nvar AW = (e50) =\u003e e50 !== undefined;\nvar OW = class extends wW {\n input;\n output = null;\n constructor(e50) {\n super(), this.input = e50;\n }\n _step() {\n const { regions: e50, hulls: t2 } = { regions: (n2 = this.input).cells.map((e51) =\u003e e51.map((e52) =\u003e n2.pts[e52]).filter(AW)), hulls: n2.cells.map((e51) =\u003e EW(e51, n2.pts).map((e52) =\u003e n2.pts[e52]).filter(AW)) };\n var n2;\n this.output = { pts: this.input.pts, validTris: this.input.validTris, regions: e50, hulls: t2, depths: this.input.depths }, this.stats = { regions: e50.length }, this.solved = true;\n }\n getConstructorParams() {\n return [this.input];\n }\n getOutput() {\n return this.output;\n }\n visualize() {\n const e50 = this.output;\n return e50 ? { points: e50.pts.map((e51) =\u003e ({ x: e51.x, y: e51.y, color: \"#3b82f6\" })), lines: e50.regions.flatMap((e51) =\u003e e51.flatMap((t2, n2) =\u003e {\n const o3 = e51[(n2 + 1) % e51.length];\n return o3 ? [{ points: [t2, o3], strokeColor: \"#0f766e\" }] : [];\n })), rects: [], circles: [], texts: [{ x: 4, y: 12, text: `regions: ${e50.regions.length}`, color: \"#1f2937\" }] } : { points: [], lines: [], rects: [], circles: [], texts: [] };\n }\n};\nvar kW = (e50, t2, n2) =\u003e {\n const o3 = Math.cos(n2.ccwRotation), i3 = Math.sin(n2.ccwRotation);\n return { x: n2.center.x + e50 * o3 - t2 * i3, y: n2.center.y + e50 * i3 + t2 * o3 };\n};\nvar DW = (e50, t2 = [], n2, o3 = []) =\u003e {\n const i3 = [], { minX: r3, maxX: s2, minY: a3, maxY: c3 } = e50;\n i3.push({ x: r3, y: a3 }, { x: s2, y: a3 }, { x: s2, y: c3 }, { x: r3, y: c3 });\n for (let e51 = 1;e51 \u003c 10; e51++) {\n const t3 = e51 / 10;\n i3.push({ x: r3 + t3 * (s2 - r3), y: a3 }), i3.push({ x: s2, y: a3 + t3 * (c3 - a3) }), i3.push({ x: s2 - t3 * (s2 - r3), y: c3 }), i3.push({ x: r3, y: c3 - t3 * (c3 - a3) });\n }\n for (const e51 of t2) {\n const t3 = e51.diameter / 2 + n2;\n for (let n3 = 0;n3 \u003c 24; n3++) {\n const o4 = 2 * Math.PI * n3 / 24;\n i3.push({ x: e51.center.x + t3 * Math.cos(o4), y: e51.center.y + t3 * Math.sin(o4) });\n }\n }\n for (const e51 of o3) {\n const t3 = e51.width / 2 + n2, o4 = e51.height / 2 + n2, r4 = Math.max(2, Math.ceil(Math.max(2 * t3, 2 * o4) / 20));\n for (let n3 = 0;n3 \u003c r4; n3++) {\n const s3 = n3 / r4;\n i3.push(kW(2 * s3 * t3 - t3, -o4, e51)), i3.push(kW(t3, 2 * s3 * o4 - o4, e51)), i3.push(kW(t3 - 2 * s3 * t3, o4, e51)), i3.push(kW(-t3, o4 - 2 * s3 * o4, e51));\n }\n }\n return i3.map((e51, t3) =\u003e ({ x: e51.x + 0.000001 * (t3 % 7 - 3), y: e51.y + 0.000001 * (t3 % 5 - 2) }));\n};\nvar LW = class extends wW {\n input;\n output = null;\n constructor(e50) {\n super(), this.input = e50;\n }\n _step() {\n const e50 = this.input.vias ?? [], t2 = this.input.rects ?? [];\n this.output = { pts: DW(this.input.bounds, e50, this.input.clearance, t2) }, this.stats = { points: this.output.pts.length }, this.solved = true;\n }\n getConstructorParams() {\n return [this.input];\n }\n getOutput() {\n return this.output;\n }\n visualize() {\n const e50 = (this.output?.pts ?? []).map((e51) =\u003e ({ x: e51.x, y: e51.y, color: \"#2563eb\" }));\n return { points: e50, lines: [], rects: [], circles: (this.input.vias ?? []).map((e51) =\u003e ({ center: { x: e51.center.x, y: e51.center.y }, radius: e51.diameter / 2 + this.input.clearance, stroke: \"#ef4444\" })), texts: [{ x: this.input.bounds.minX + 6, y: this.input.bounds.minY + 12, text: `sample points: ${e50.length}`, color: \"#1f2937\" }] };\n }\n};\nvar zW = (e50, t2, n2) =\u003e {\n const o3 = n2.x - t2.x, i3 = n2.y - t2.y, r3 = o3 * o3 + i3 * i3;\n if (r3 \u003c 0.0000000001)\n return Math.hypot(e50.x - t2.x, e50.y - t2.y);\n let s2 = ((e50.x - t2.x) * o3 + (e50.y - t2.y) * i3) / r3;\n return s2 = Math.max(0, Math.min(1, s2)), Math.hypot(e50.x - t2.x - s2 * o3, e50.y - t2.y - s2 * i3);\n};\nvar BW = (e50, t2) =\u003e {\n if (e50.length \u003c= 3)\n return 0;\n const n2 = EW(e50, t2), o3 = new Set(n2), i3 = n2.map((e51) =\u003e t2[e51]).filter((e51) =\u003e Boolean(e51));\n let r3 = 0;\n for (const n3 of e50) {\n if (o3.has(n3))\n continue;\n const e51 = t2[n3];\n if (!e51)\n continue;\n let s2 = Number.POSITIVE_INFINITY;\n for (let t3 = 0;t3 \u003c i3.length; t3++) {\n const n4 = i3[t3], o4 = i3[(t3 + 1) % i3.length];\n n4 \u0026\u0026 o4 \u0026\u0026 (s2 = Math.min(s2, zW(e51, n4, o4)));\n }\n r3 = Math.max(r3, s2);\n }\n return r3;\n};\nvar FW = (e50, t2) =\u003e e50 \u003c t2 ? 1e5 * e50 + t2 : 1e5 * t2 + e50;\nvar jW = (e50, t2) =\u003e {\n const n2 = e50.map((t3, n3) =\u003e [t3, e50[(n3 + 1) % e50.length]]), o3 = t2.map((e51, n3) =\u003e [e51, t2[(n3 + 1) % t2.length]]), i3 = new Set;\n for (const [e51, t3] of n2)\n if (t3 !== undefined)\n for (const [n3, r4] of o3)\n r4 !== undefined \u0026\u0026 e51 === r4 \u0026\u0026 t3 === n3 \u0026\u0026 i3.add(FW(e51, t3));\n if (i3.size === 0)\n return null;\n const r3 = [];\n for (const [e51, t3] of n2)\n t3 !== undefined \u0026\u0026 (i3.has(FW(e51, t3)) || r3.push([e51, t3]));\n for (const [e51, t3] of o3)\n t3 !== undefined \u0026\u0026 (i3.has(FW(e51, t3)) || r3.push([e51, t3]));\n if (r3.length === 0)\n return null;\n const s2 = new Map;\n for (const [e51, t3] of r3)\n s2.set(e51, t3);\n const a3 = r3[0]?.[0];\n if (a3 === undefined)\n return null;\n const c3 = [a3];\n let l3 = s2.get(a3), h2 = 0;\n for (;l3 !== undefined \u0026\u0026 l3 !== a3 \u0026\u0026 h2++ \u003c r3.length + 5; )\n c3.push(l3), l3 = s2.get(l3);\n return l3 !== a3 || c3.length !== r3.length ? null : c3;\n};\nvar $W = (e50, t2) =\u003e e50 \u003c t2 ? 1e5 * e50 + t2 : 1e5 * t2 + e50;\nvar YW = class extends wW {\n input;\n output = null;\n constructor(e50) {\n super(), this.input = e50;\n }\n _step() {\n const e50 = ((e51, t2, n2) =\u003e {\n if (!e51.length)\n return { cells: [], depths: [] };\n const o3 = e51.map(([e52, n3, o4]) =\u003e {\n const i4 = t2[e52], r4 = t2[n3], s3 = t2[o4];\n return i4 \u0026\u0026 r4 \u0026\u0026 s3 \u0026\u0026 TW(i4, r4, s3) \u003c 0 ? [e52, o4, n3] : [e52, n3, o4];\n });\n let i3 = true, r3 = 0;\n for (;i3 \u0026\u0026 r3++ \u003c 800; ) {\n i3 = false;\n const e52 = new Map, r4 = o3.map(() =\u003e new Set);\n for (let t3 = 0;t3 \u003c o3.length; t3++) {\n const n3 = o3[t3];\n if (n3)\n for (let o4 = 0;o4 \u003c n3.length; o4++) {\n const i4 = n3[o4], s4 = n3[(o4 + 1) % n3.length];\n if (i4 === undefined || s4 === undefined)\n continue;\n const a4 = $W(i4, s4);\n if (e52.has(a4)) {\n const n4 = e52.get(a4);\n n4 !== undefined \u0026\u0026 (r4[t3]?.add(n4), r4[n4]?.add(t3));\n } else\n e52.set(a4, t3);\n }\n }\n let s3 = -1, a3 = -1, c3 = null, l3 = Number.POSITIVE_INFINITY;\n for (let e53 = 0;e53 \u003c o3.length; e53++) {\n const i4 = r4[e53];\n if (i4)\n for (const r5 of i4) {\n if (r5 \u003c= e53)\n continue;\n const i5 = jW(o3[e53] ?? [], o3[r5] ?? []);\n if (!i5)\n continue;\n const h2 = BW(i5, t2);\n h2 \u003c= n2 + 0.000001 \u0026\u0026 h2 \u003c l3 \u0026\u0026 (l3 = h2, s3 = e53, a3 = r5, c3 = i5);\n }\n }\n if (s3 \u003c 0 || a3 \u003c 0 || !c3)\n break;\n o3[s3] = c3, o3.splice(a3, 1), i3 = true;\n }\n const s2 = o3.map((e52) =\u003e BW(e52, t2));\n return { cells: o3, depths: s2 };\n })(this.input.validTris, this.input.pts, this.input.concavityTolerance);\n this.output = { pts: this.input.pts, validTris: this.input.validTris, cells: e50.cells, depths: e50.depths }, this.stats = { mergedCells: e50.cells.length, maxDepth: e50.depths.length ? Math.max(...e50.depths) : 0 }, this.solved = true;\n }\n getConstructorParams() {\n return [this.input];\n }\n getOutput() {\n return this.output;\n }\n visualize() {\n const e50 = this.output?.cells ?? [];\n return { points: this.input.pts.map((e51) =\u003e ({ x: e51.x, y: e51.y, color: \"#3b82f6\" })), lines: e50.flatMap((e51) =\u003e e51.flatMap((t2, n2) =\u003e {\n const o3 = this.input.pts[t2], i3 = e51[(n2 + 1) % e51.length], r3 = i3 === undefined ? undefined : this.input.pts[i3];\n return o3 \u0026\u0026 r3 ? [{ points: [o3, r3], strokeColor: \"#10b981\" }] : [];\n })), rects: [], circles: [], texts: [{ x: 4, y: 12, text: `merged cells: ${e50.length}`, color: \"#1f2937\" }] };\n }\n};\nvar XW = (e50, t2, n2) =\u003e {\n const o3 = 2 * (e50.x * (t2.y - n2.y) + t2.x * (n2.y - e50.y) + n2.x * (e50.y - t2.y));\n if (Math.abs(o3) \u003c 0.0000000001)\n return { x: 0, y: 0, r2: 1000000000000000000 };\n const i3 = e50.x * e50.x + e50.y * e50.y, r3 = t2.x * t2.x + t2.y * t2.y, s2 = n2.x * n2.x + n2.y * n2.y, a3 = (i3 * (t2.y - n2.y) + r3 * (n2.y - e50.y) + s2 * (e50.y - t2.y)) / o3, c3 = (i3 * (n2.x - t2.x) + r3 * (e50.x - n2.x) + s2 * (t2.x - e50.x)) / o3;\n return { x: a3, y: c3, r2: (e50.x - a3) ** 2 + (e50.y - c3) ** 2 };\n};\nvar HW = (e50, t2, n2) =\u003e [e50.a, e50.b, e50.c].includes(t2) \u0026\u0026 [e50.a, e50.b, e50.c].includes(n2);\nvar VW = (e50, t2, n2, o3 = [], i3, r3 = []) =\u003e e50.filter(([e51, s2, a3]) =\u003e {\n const c3 = t2[e51], l3 = t2[s2], h2 = t2[a3];\n if (!c3 || !l3 || !h2)\n return false;\n return ((e52, t3, n3, o4 = [], i4, r4 = []) =\u003e {\n const { minX: s3, maxX: a4, minY: c4, maxY: l4 } = n3;\n if (e52 \u003c s3 - 0.1 || e52 \u003e a4 + 0.1 || t3 \u003c c4 - 0.1 || t3 \u003e l4 + 0.1)\n return false;\n for (const n4 of o4) {\n const o5 = n4.diameter / 2 + i4;\n if ((e52 - n4.center.x) ** 2 + (t3 - n4.center.y) ** 2 \u003c o5 * o5 - 0.1)\n return false;\n }\n for (const n4 of r4) {\n const o5 = n4.width / 2 + i4, r5 = n4.height / 2 + i4, s4 = e52 - n4.center.x, a5 = t3 - n4.center.y, c5 = Math.cos(n4.ccwRotation), l5 = Math.sin(n4.ccwRotation), h3 = s4 * c5 + a5 * l5, d2 = -s4 * l5 + a5 * c5;\n if (Math.abs(h3) \u003c o5 - 0.1 \u0026\u0026 Math.abs(d2) \u003c r5 - 0.1)\n return false;\n }\n return true;\n })((c3.x + l3.x + h2.x) / 3, (c3.y + l3.y + h2.y) / 3, n2, o3, i3, r3);\n});\nvar WW = class extends wW {\n input;\n output = null;\n constructor(e50) {\n super(), this.input = e50;\n }\n _step() {\n const e50 = this.input.vias ?? [], t2 = this.input.rects ?? [], n2 = ((e51) =\u003e {\n const t3 = e51.map((e52, t4) =\u003e ({ ...e52, i: t4 }));\n if (t3.length \u003c 3)\n return [];\n let { POSITIVE_INFINITY: n3, POSITIVE_INFINITY: o4, NEGATIVE_INFINITY: i3, NEGATIVE_INFINITY: r3 } = Number;\n for (const e52 of t3)\n n3 = Math.min(n3, e52.x), o4 = Math.min(o4, e52.y), i3 = Math.max(i3, e52.x), r3 = Math.max(r3, e52.y);\n const s2 = Math.max(i3 - n3, r3 - o4) || 1, a3 = (n3 + i3) / 2, c3 = (o4 + r3) / 2, l3 = { x: a3 - 30 * s2, y: c3 - s2, i: -1 }, h2 = { x: a3, y: c3 + 30 * s2, i: -2 }, d2 = { x: a3 + 30 * s2, y: c3 - s2, i: -3 };\n let u2 = [{ a: l3, b: h2, c: d2, cc: XW(l3, h2, d2) }];\n for (const e52 of t3) {\n const t4 = u2.filter((t5) =\u003e {\n const n5 = e52.x - t5.cc.x, o6 = e52.y - t5.cc.y;\n return n5 * n5 + o6 * o6 \u003c t5.cc.r2 + 0.000001;\n }), n4 = new Set(t4), o5 = [];\n for (const e53 of t4) {\n const n5 = [[e53.a, e53.b], [e53.b, e53.c], [e53.c, e53.a]];\n for (const [i4, r4] of n5) {\n let n6 = false;\n for (const o6 of t4)\n if (o6 !== e53 \u0026\u0026 HW(o6, i4, r4)) {\n n6 = true;\n break;\n }\n n6 || o5.push([i4, r4]);\n }\n }\n u2 = u2.filter((e53) =\u003e !n4.has(e53));\n for (const [t5, n5] of o5)\n u2.push({ a: t5, b: n5, c: e52, cc: XW(t5, n5, e52) });\n }\n return u2.filter((e52) =\u003e e52.a.i \u003e= 0 \u0026\u0026 e52.b.i \u003e= 0 \u0026\u0026 e52.c.i \u003e= 0).map((e52) =\u003e [e52.a.i, e52.b.i, e52.c.i]);\n })(this.input.pts), o3 = VW(n2, this.input.pts, this.input.bounds, e50, this.input.clearance, t2);\n this.output = { pts: this.input.pts, validTris: o3 }, this.stats = { candidateTriangles: n2.length, validTriangles: o3.length }, this.solved = true;\n }\n getConstructorParams() {\n return [this.input];\n }\n getOutput() {\n return this.output;\n }\n visualize() {\n const e50 = this.output?.validTris ?? [];\n return { points: this.input.pts.map((e51) =\u003e ({ x: e51.x, y: e51.y, color: \"#2563eb\" })), lines: e50.flatMap(([e51, t2, n2]) =\u003e {\n const o3 = this.input.pts[e51], i3 = this.input.pts[t2], r3 = this.input.pts[n2];\n return o3 \u0026\u0026 i3 \u0026\u0026 r3 ? [{ points: [o3, i3], strokeColor: \"#64748b\" }, { points: [i3, r3], strokeColor: \"#64748b\" }, { points: [r3, o3], strokeColor: \"#64748b\" }] : [];\n }), rects: [], circles: [], texts: [{ x: this.input.bounds.minX + 6, y: this.input.bounds.minY + 12, text: `valid triangles: ${e50.length}`, color: \"#1f2937\" }] };\n }\n};\nvar GW = class extends RW {\n pipelineDef = [NW(\"generatePoints\", LW, (e50) =\u003e [e50.inputProblem]), NW(\"triangulate\", WW, (e50) =\u003e {\n const t2 = e50.getStageOutput(\"generatePoints\");\n if (!t2)\n throw new Error(\"generatePoints output missing\");\n return [{ pts: t2.pts, bounds: e50.inputProblem.bounds, vias: e50.inputProblem.vias, rects: e50.inputProblem.rects, clearance: e50.inputProblem.clearance }];\n }), NW(\"mergeCells\", YW, (e50) =\u003e {\n const t2 = e50.getStageOutput(\"triangulate\");\n if (!t2)\n throw new Error(\"triangulate output missing\");\n return [{ pts: t2.pts, validTris: t2.validTris, concavityTolerance: e50.inputProblem.concavityTolerance }];\n }), NW(\"buildRegions\", OW, (e50) =\u003e {\n const t2 = e50.getStageOutput(\"mergeCells\");\n if (!t2)\n throw new Error(\"mergeCells output missing\");\n return [t2];\n })];\n getConstructorParams() {\n return [this.inputProblem];\n }\n getOutput() {\n return this.getStageOutput(\"buildRegions\") ?? null;\n }\n visualize() {\n const e50 = this.getOutput();\n return e50 ? { points: e50.pts.map((e51) =\u003e ({ x: e51.x, y: e51.y, color: \"#38b6ff\" })), lines: e50.regions.flatMap((e51) =\u003e e51.map((t2, n2) =\u003e {\n const o3 = e51[(n2 + 1) % e51.length] ?? t2;\n return { points: [{ x: t2.x, y: t2.y }, { x: o3.x, y: o3.y }], strokeColor: \"#4ecb82\" };\n })), rects: [], circles: (this.inputProblem.vias ?? []).map((e51) =\u003e ({ center: { x: e51.center.x, y: e51.center.y }, radius: e51.diameter / 2, stroke: \"#ff6b6b\" })), texts: [{ x: this.inputProblem.bounds.minX + 8, y: this.inputProblem.bounds.minY + 16, text: `regions=${e50.regions.length}`, color: \"#ffffff\" }] } : { points: [], lines: [], rects: [], circles: [], texts: [] };\n }\n};\nvar UW = 0.000000001;\nvar ZW = (e50, t2) =\u003e {\n const n2 = [hG(e50)], o3 = [];\n let i3 = t2.maxSplitsPerRegion ?? 32;\n for (;n2.length \u003e 0; ) {\n const e51 = n2.pop();\n if (!e51)\n continue;\n if (e51.length \u003c 4) {\n o3.push(e51);\n continue;\n }\n const r3 = qW(e51, t2);\n if (!r3 || i3 \u003c= 0) {\n o3.push(e51);\n continue;\n }\n const [s2, a3] = QW(e51, r3.i, r3.j);\n i3 -= 1, n2.push(s2, a3);\n }\n return o3;\n};\nvar qW = (e50, t2) =\u003e {\n const n2 = eG(e50);\n if (!n2)\n return null;\n const { triangles: o3 } = n2, i3 = sG(e50);\n if (i3 \u003c= UW)\n return null;\n const r3 = Math.sqrt(i3), s2 = o3.map((t3) =\u003e aG(e50[t3[0]], e50[t3[1]], e50[t3[2]]));\n let a3 = null;\n for (const c3 of n2.internalEdges) {\n const { i: l3, j: h2, triA: d2, triB: u2 } = c3, p3 = cG(e50[l3], e50[h2]) / r3;\n if (p3 \u003e t2.maxNeckRatio)\n continue;\n const m2 = JW(d2, u2, o3.length, n2.triangleAdjacency, s2), g2 = i3 - m2, f2 = Math.min(m2, g2) / i3;\n if (f2 \u003c t2.minSplitBalanceRatio)\n continue;\n const _2 = p3 / Math.max(f2, UW);\n (!a3 || _2 \u003c a3.score) \u0026\u0026 (a3 = { i: l3, j: h2, score: _2 });\n }\n return a3 ? { i: a3.i, j: a3.j } : null;\n};\nvar JW = (e50, t2, n2, o3, i3) =\u003e {\n const r3 = new Array(n2).fill(false), s2 = [e50];\n r3[t2] = true;\n let a3 = 0;\n for (;s2.length \u003e 0; ) {\n const e51 = s2.pop();\n if (e51 === undefined || r3[e51])\n continue;\n r3[e51] = true, a3 += i3[e51] ?? 0;\n const t3 = o3[e51] ?? [];\n for (const e52 of t3)\n r3[e52] || s2.push(e52);\n }\n return a3;\n};\nvar QW = (e50, t2, n2) =\u003e [KW(e50, t2, n2), KW(e50, n2, t2)];\nvar KW = (e50, t2, n2) =\u003e {\n const o3 = [], i3 = e50.length;\n let r3 = t2;\n for (o3.push(e50[r3]);r3 !== n2; )\n r3 = (r3 + 1) % i3, o3.push(e50[r3]);\n return hG(o3);\n};\nvar eG = (e50) =\u003e {\n const t2 = e50.length;\n if (t2 \u003c 3)\n return null;\n const n2 = new Set;\n for (let e51 = 0;e51 \u003c t2; e51++) {\n const o4 = (e51 + 1) % t2;\n n2.add(lG(e51, o4));\n }\n const o3 = tG(e50);\n if (!o3 || o3.length === 0)\n return null;\n const i3 = new Map;\n o3.forEach((e51, t3) =\u003e {\n for (let n3 = 0;n3 \u003c 3; n3++) {\n const o4 = e51[n3], r4 = e51[(n3 + 1) % 3], s3 = lG(o4, r4), a3 = i3.get(s3);\n a3 ? a3.push(t3) : i3.set(s3, [t3]);\n }\n });\n const r3 = Array.from({ length: o3.length }, () =\u003e []), s2 = [];\n for (const [e51, t3] of i3.entries()) {\n if (n2.has(e51))\n continue;\n if (t3.length !== 2)\n continue;\n const [o4, i4] = e51.split(\"_\"), a3 = Number(o4), c3 = Number(i4), l3 = t3[0], h2 = t3[1];\n s2.push({ i: a3, j: c3, triA: l3, triB: h2 });\n const d2 = r3[l3], u2 = r3[h2];\n d2 \u0026\u0026 d2.push(h2), u2 \u0026\u0026 u2.push(l3);\n }\n return { triangles: o3, internalEdges: s2, triangleAdjacency: r3 };\n};\nvar tG = (e50) =\u003e {\n const t2 = e50.length;\n if (t2 \u003c 3)\n return null;\n const n2 = Math.sign(rG(e50));\n if (n2 === 0)\n return null;\n const o3 = [...Array(t2).keys()];\n n2 \u003c 0 \u0026\u0026 o3.reverse();\n const i3 = [];\n let r3 = 0;\n for (;o3.length \u003e 3 \u0026\u0026 r3 \u003c t2 * t2; ) {\n let t3 = false;\n for (let n3 = 0;n3 \u003c o3.length; n3++) {\n const r4 = o3[(n3 - 1 + o3.length) % o3.length], s2 = o3[n3], a3 = o3[(n3 + 1) % o3.length];\n if (r4 === undefined || s2 === undefined || a3 === undefined)\n continue;\n const c3 = e50[r4], l3 = e50[s2], h2 = e50[a3];\n if (!c3 || !l3 || !h2)\n continue;\n if (!nG(c3, l3, h2))\n continue;\n let d2 = false;\n for (const t4 of o3) {\n if (t4 === r4 || t4 === s2 || t4 === a3)\n continue;\n const n4 = e50[t4];\n if (n4 \u0026\u0026 oG(n4, c3, l3, h2)) {\n d2 = true;\n break;\n }\n }\n if (!d2) {\n i3.push([r4, s2, a3]), o3.splice(n3, 1), t3 = true;\n break;\n }\n }\n if (!t3)\n return null;\n r3 += 1;\n }\n if (o3.length === 3) {\n const [e51, t3, n3] = o3;\n e51 !== undefined \u0026\u0026 t3 !== undefined \u0026\u0026 n3 !== undefined \u0026\u0026 i3.push([e51, t3, n3]);\n }\n return i3;\n};\nvar nG = (e50, t2, n2) =\u003e iG(e50, t2, n2) \u003e UW;\nvar oG = (e50, t2, n2, o3) =\u003e {\n const i3 = iG(t2, n2, e50), r3 = iG(n2, o3, e50), s2 = iG(o3, t2, e50);\n return i3 \u003e= -0.000000001 \u0026\u0026 r3 \u003e= -0.000000001 \u0026\u0026 s2 \u003e= -0.000000001;\n};\nvar iG = (e50, t2, n2) =\u003e (t2.x - e50.x) * (n2.y - e50.y) - (t2.y - e50.y) * (n2.x - e50.x);\nvar rG = (e50) =\u003e {\n let t2 = 0;\n for (let n2 = 0;n2 \u003c e50.length; n2++) {\n const o3 = e50[n2], i3 = e50[(n2 + 1) % e50.length];\n o3 \u0026\u0026 i3 \u0026\u0026 (t2 += o3.x * i3.y - i3.x * o3.y);\n }\n return t2 / 2;\n};\nvar sG = (e50) =\u003e Math.abs(rG(e50));\nvar aG = (e50, t2, n2) =\u003e Math.abs(iG(e50, t2, n2)) / 2;\nvar cG = (e50, t2) =\u003e Math.hypot(e50.x - t2.x, e50.y - t2.y);\nvar lG = (e50, t2) =\u003e e50 \u003c t2 ? `${e50}_${t2}` : `${t2}_${e50}`;\nvar hG = (e50) =\u003e {\n if (e50.length \u003c 2)\n return e50;\n const t2 = e50[0], n2 = e50[e50.length - 1];\n return t2 \u0026\u0026 n2 \u0026\u0026 t2.x === n2.x \u0026\u0026 t2.y === n2.y ? e50.slice(0, -1) : e50;\n};\nvar dG = { pattern: \"grid\", pitchX: 2.2, pitchY: 1.8, staggerAxis: \"x\", staggerOffset: 1.1, staggerOffsetX: 1.1, padWidth: 0.9, padHeight: 1, padGap: 0.35, viaDiameter: 0.3, clearance: 0.2, concavityTolerance: 0.3, boundsPadding: 1.2, orientation: \"horizontal\", portSpacing: 0.25, maxNeckRatio: 0, minSplitBalanceRatio: 0.2 };\nvar uG = (e50, t2) =\u003e {\n let { POSITIVE_INFINITY: n2, POSITIVE_INFINITY: o3, NEGATIVE_INFINITY: i3, NEGATIVE_INFINITY: r3 } = Number;\n for (const s2 of e50)\n for (const e51 of s2.padCenters) {\n const s3 = t2.orientation === \"horizontal\" ? t2.padWidth / 2 : t2.padHeight / 2, a3 = t2.orientation === \"horizontal\" ? t2.padHeight / 2 : t2.padWidth / 2;\n e51.x - s3 \u003c n2 \u0026\u0026 (n2 = e51.x - s3), e51.y - a3 \u003c o3 \u0026\u0026 (o3 = e51.y - a3), e51.x + s3 \u003e i3 \u0026\u0026 (i3 = e51.x + s3), e51.y + a3 \u003e r3 \u0026\u0026 (r3 = e51.y + a3);\n }\n return { minX: n2 - t2.boundsPadding, minY: o3 - t2.boundsPadding, maxX: i3 + t2.boundsPadding, maxY: r3 + t2.boundsPadding };\n};\nvar pG = (e50) =\u003e e50.pattern === \"staggered\" ? ((e51) =\u003e {\n const t2 = [], n2 = [], o3 = e51.padGap / 2 + e51.padWidth / 2, i3 = -(e51.cols - 1) * e51.pitchX / 2, r3 = -(e51.rows - 1) * e51.pitchY / 2;\n for (let s2 = 0;s2 \u003c e51.rows; s2++) {\n const a3 = e51.staggerAxis === \"x\" \u0026\u0026 s2 % 2 == 1 ? e51.staggerOffset : 0;\n for (let c3 = 0;c3 \u003c e51.cols; c3++) {\n const l3 = e51.staggerAxis === \"y\" \u0026\u0026 c3 % 2 == 1 ? e51.staggerOffset : 0, h2 = { x: i3 + c3 * e51.pitchX + a3, y: r3 + s2 * e51.pitchY + l3 }, d2 = e51.orientation === \"horizontal\" ? { x: h2.x - o3, y: h2.y } : { x: h2.x, y: h2.y - o3 }, u2 = e51.orientation === \"horizontal\" ? { x: h2.x + o3, y: h2.y } : { x: h2.x, y: h2.y + o3 };\n t2.push({ jumperId: `jumper_r${s2}_c${c3}`, center: h2, orientation: e51.orientation, padCenters: [d2, u2] }), n2.push({ center: d2, diameter: e51.viaDiameter }, { center: u2, diameter: e51.viaDiameter });\n }\n }\n return { jumpers: t2, vias: n2, bounds: uG(t2, e51) };\n})(e50) : ((e51) =\u003e {\n const t2 = [], n2 = [], o3 = e51.padGap / 2 + e51.padWidth / 2, i3 = -(e51.cols - 1) * e51.pitchX / 2, r3 = -(e51.rows - 1) * e51.pitchY / 2;\n for (let s2 = 0;s2 \u003c e51.rows; s2++)\n for (let a3 = 0;a3 \u003c e51.cols; a3++) {\n const c3 = { x: i3 + a3 * e51.pitchX, y: r3 + s2 * e51.pitchY }, l3 = e51.orientation === \"horizontal\" ? { x: c3.x - o3, y: c3.y } : { x: c3.x, y: c3.y - o3 }, h2 = e51.orientation === \"horizontal\" ? { x: c3.x + o3, y: c3.y } : { x: c3.x, y: c3.y + o3 }, d2 = `jumper_r${s2}_c${a3}`;\n t2.push({ jumperId: d2, center: c3, orientation: e51.orientation, padCenters: [l3, h2] }), n2.push({ center: l3, diameter: e51.viaDiameter }, { center: h2, diameter: e51.viaDiameter });\n }\n return { jumpers: t2, vias: n2, bounds: { minX: i3 - o3 - e51.padWidth / 2 - e51.boundsPadding, maxX: i3 + (e51.cols - 1) * e51.pitchX + o3 + e51.padWidth / 2 + e51.boundsPadding, minY: r3 - o3 - e51.padHeight / 2 - e51.boundsPadding, maxY: r3 + (e51.rows - 1) * e51.pitchY + o3 + e51.padHeight / 2 + e51.boundsPadding } };\n})(e50);\nvar mG = (e50) =\u003e ({ x: (e50.minX + e50.maxX) / 2, y: (e50.minY + e50.maxY) / 2 });\nvar gG = (e50) =\u003e [{ x: e50.minX, y: e50.minY }, { x: e50.maxX, y: e50.minY }, { x: e50.maxX, y: e50.maxY }, { x: e50.minX, y: e50.maxY }];\nvar fG = (e50, t2, n2) =\u003e Math.abs(e50 - t2) \u003c= n2;\nvar _G = (e50, t2, n2) =\u003e fG(e50.x, t2.x, n2) \u0026\u0026 fG(e50.y, t2.y, n2);\nvar yG = (e50) =\u003e e50.map((e51, t2) =\u003e {\n const n2 = ((e52) =\u003e {\n let { POSITIVE_INFINITY: t3, POSITIVE_INFINITY: n3, NEGATIVE_INFINITY: o3, NEGATIVE_INFINITY: i3 } = Number;\n for (const r3 of e52)\n r3.x \u003c t3 \u0026\u0026 (t3 = r3.x), r3.y \u003c n3 \u0026\u0026 (n3 = r3.y), r3.x \u003e o3 \u0026\u0026 (o3 = r3.x), r3.y \u003e i3 \u0026\u0026 (i3 = r3.y);\n return { minX: t3, minY: n3, maxX: o3, maxY: i3 };\n })(e51);\n return { regionId: `top_${t2}`, ports: [], d: { bounds: n2, center: mG(n2), polygon: e51, isPad: false } };\n});\nvar bG = (e50) =\u003e {\n const t2 = e50.end.x - e50.start.x, n2 = e50.end.y - e50.start.y;\n return Math.hypot(t2, n2);\n};\nvar xG = (e50, t2) =\u003e ({ x: e50.start.x + (e50.end.x - e50.start.x) * t2, y: e50.start.y + (e50.end.y - e50.start.y) * t2 });\nvar vG = (e50, t2, n2) =\u003e {\n const o3 = [];\n if (!e50.d.polygon || !t2.d.polygon)\n return o3;\n for (let i3 = 0;i3 \u003c e50.d.polygon.length; i3++) {\n const r3 = e50.d.polygon[i3], s2 = e50.d.polygon[(i3 + 1) % e50.d.polygon.length];\n if (r3 \u0026\u0026 s2)\n for (let e51 = 0;e51 \u003c t2.d.polygon.length; e51++) {\n const i4 = t2.d.polygon[e51], a3 = t2.d.polygon[(e51 + 1) % t2.d.polygon.length];\n if (!i4 || !a3)\n continue;\n const c3 = PG({ start: r3, end: s2 }, { start: i4, end: a3 }, n2);\n if (!c3)\n continue;\n o3.some((e52) =\u003e CG(e52, c3, n2)) || o3.push(c3);\n }\n }\n return o3;\n};\nvar IG = (e50, t2) =\u003e {\n const n2 = [];\n for (const o3 of e50) {\n let e51 = o3, i3 = true;\n for (;i3; ) {\n i3 = false;\n for (let o4 = 0;o4 \u003c n2.length; o4++) {\n const r3 = n2[o4];\n if (!r3)\n continue;\n const s2 = SG(e51, r3, t2);\n if (s2) {\n e51 = s2, n2.splice(o4, 1), i3 = true;\n break;\n }\n }\n }\n n2.push(e51);\n }\n return n2;\n};\nvar SG = (e50, t2, n2) =\u003e {\n const o3 = e50.end.x - e50.start.x, i3 = e50.end.y - e50.start.y, r3 = t2.end.x - t2.start.x, s2 = t2.end.y - t2.start.y, a3 = o3 ** 2 + i3 ** 2;\n if (a3 \u003c= n2 ** 2)\n return null;\n if (!fG(o3 * s2 - i3 * r3, 0, n2))\n return null;\n const c3 = t2.start.x - e50.start.x, l3 = t2.start.y - e50.start.y, h2 = t2.end.x - e50.start.x, d2 = t2.end.y - e50.start.y, u2 = o3 * d2 - i3 * h2;\n if (!fG(o3 * l3 - i3 * c3, 0, n2) || !fG(u2, 0, n2))\n return null;\n const p3 = (c3 * o3 + l3 * i3) / a3, m2 = (h2 * o3 + d2 * i3) / a3, g2 = Math.min(p3, m2), f2 = Math.max(p3, m2), _2 = n2 / Math.sqrt(a3);\n if (g2 \u003e 1 + _2 || f2 \u003c 0 - _2)\n return null;\n const y2 = Math.min(0, g2), b2 = Math.max(1, f2);\n return { start: xG(e50, y2), end: xG(e50, b2) };\n};\nvar CG = (e50, t2, n2) =\u003e _G(e50.start, t2.start, n2) \u0026\u0026 _G(e50.end, t2.end, n2) || _G(e50.start, t2.end, n2) \u0026\u0026 _G(e50.end, t2.start, n2);\nvar PG = (e50, t2, n2) =\u003e {\n const o3 = e50.end.x - e50.start.x, i3 = e50.end.y - e50.start.y, r3 = t2.end.x - t2.start.x, s2 = t2.end.y - t2.start.y, a3 = o3 ** 2 + i3 ** 2;\n if (a3 \u003c= n2 ** 2)\n return null;\n if (!fG(o3 * s2 - i3 * r3, 0, n2))\n return null;\n const c3 = t2.start.x - e50.start.x, l3 = t2.start.y - e50.start.y, h2 = t2.end.x - e50.start.x, d2 = t2.end.y - e50.start.y, u2 = o3 * d2 - i3 * h2;\n if (!fG(o3 * l3 - i3 * c3, 0, n2) || !fG(u2, 0, n2))\n return null;\n const p3 = (c3 * o3 + l3 * i3) / a3, m2 = (h2 * o3 + d2 * i3) / a3, g2 = Math.max(0, Math.min(p3, m2)), f2 = Math.min(1, Math.max(p3, m2));\n return f2 - g2 \u003c= n2 / Math.sqrt(a3) ? null : { start: xG(e50, g2), end: xG(e50, f2) };\n};\nvar MG = (e50, t2, n2) =\u003e {\n const o3 = Math.max(e50.minX, t2.minX), i3 = Math.min(e50.maxX, t2.maxX), r3 = Math.max(e50.minY, t2.minY), s2 = Math.min(e50.maxY, t2.maxY);\n return i3 \u003c o3 - n2 || s2 \u003c r3 - n2 ? null : { minX: o3, maxX: i3, minY: r3, maxY: s2 };\n};\nvar wG = (e50) =\u003e {\n const t2 = ((e51) =\u003e {\n const t3 = e51.orientation ?? dG.orientation, n3 = e51.staggerAxis ?? dG.staggerAxis, o4 = e51.padWidth ?? dG.padWidth, i4 = e51.padHeight ?? dG.padHeight, r4 = e51.padGap ?? dG.padGap, s3 = e51.clearance ?? dG.clearance, a4 = e51.colSpacing ?? e51.pitchX ?? dG.pitchX, c4 = e51.rowSpacing ?? e51.pitchY ?? dG.pitchY, l4 = (h3 = o4, d3 = i4, u3 = r4, t3 === \"horizontal\" ? { x: u3 + 2 * h3, y: d3 } : { x: d3, y: u3 + 2 * h3 });\n var h3, d3, u3;\n const p4 = s3, m2 = ((e52, t4, n4, o5, i5) =\u003e e52 === \"horizontal\" ? t4 === \"x\" ? i5 + 2 * n4 : o5 : t4 === \"x\" ? o5 : i5 + 2 * n4)(t3, n3, o4, i4, r4) / 2, g2 = e51.staggerOffset ?? e51.staggerOffsetX ?? m2, f2 = { ...dG, ...e51, orientation: t3, staggerAxis: n3, pitchX: Math.max(a4, l4.x + p4), pitchY: Math.max(c4, l4.y + p4), padWidth: o4, padHeight: i4, padGap: r4, staggerOffset: g2, staggerOffsetX: g2, concavityTolerance: e51.concavityTolerance ?? dG.concavityTolerance, clearance: s3, portSpacing: e51.portSpacing ?? dG.portSpacing, maxNeckRatio: e51.maxNeckRatio ?? dG.maxNeckRatio, minSplitBalanceRatio: e51.minSplitBalanceRatio ?? dG.minSplitBalanceRatio };\n if (f2.cols \u003c= 0 || f2.rows \u003c= 0)\n throw new Error(\"rows and cols must be \u003e 0\");\n if (!Number.isFinite(f2.portSpacing) || f2.portSpacing \u003c= 0)\n throw new Error(\"portSpacing must be \u003e 0\");\n if (!Number.isFinite(f2.maxNeckRatio) || f2.maxNeckRatio \u003c 0)\n throw new Error(\"maxNeckRatio must be \u003e= 0\");\n if (!Number.isFinite(f2.minSplitBalanceRatio) || f2.minSplitBalanceRatio \u003c 0 || f2.minSplitBalanceRatio \u003e 0.5)\n throw new Error(\"minSplitBalanceRatio must be between 0 and 0.5\");\n return f2;\n })(e50), n2 = pG(t2), o3 = t2.orientation === \"horizontal\" ? t2.padWidth : t2.padHeight, i3 = t2.orientation === \"horizontal\" ? t2.padHeight : t2.padWidth, r3 = n2.jumpers.flatMap((e51) =\u003e e51.padCenters.map((e52) =\u003e ({ center: e52, width: o3, height: i3, ccwRotation: 0 }))), s2 = new GW({ bounds: n2.bounds, rects: r3, clearance: 0, concavityTolerance: t2.concavityTolerance });\n s2.solve();\n const a3 = s2.getOutput();\n if (!a3)\n throw new Error(s2.error ?? \"ConvexRegionsSolver failed\");\n const c3 = ((e51, t3) =\u003e {\n if (t3.maxNeckRatio \u003c= 0)\n return e51;\n const n3 = [];\n for (const o4 of e51)\n n3.push(...ZW(o4, t3));\n return n3;\n })(a3.regions, { maxNeckRatio: t2.maxNeckRatio, minSplitBalanceRatio: t2.minSplitBalanceRatio }), l3 = yG(c3), h2 = ((e51, t3) =\u003e e51.flatMap((e52) =\u003e {\n const [n3, o4] = e52.padCenters, i4 = t3.orientation === \"horizontal\" ? t3.padWidth / 2 : t3.padHeight / 2, r4 = t3.orientation === \"horizontal\" ? t3.padHeight / 2 : t3.padWidth / 2, s3 = { minX: n3.x - i4, maxX: n3.x + i4, minY: n3.y - r4, maxY: n3.y + r4 }, a4 = { minX: o4.x - i4, maxX: o4.x + i4, minY: o4.y - r4, maxY: o4.y + r4 }, c4 = i4 / 2, l4 = r4 / 2, h3 = t3.orientation === \"horizontal\" ? { minX: Math.min(n3.x, o4.x), maxX: Math.max(n3.x, o4.x), minY: e52.center.y - l4, maxY: e52.center.y + l4 } : { minX: e52.center.x - c4, maxX: e52.center.x + c4, minY: Math.min(n3.y, o4.y), maxY: Math.max(n3.y, o4.y) };\n return [{ regionId: `${e52.jumperId}_pad1`, ports: [], d: { bounds: s3, center: n3, polygon: gG(s3), isPad: true, isThroughJumper: false } }, { regionId: `${e52.jumperId}_bridge`, ports: [], d: { bounds: h3, center: e52.center, polygon: gG(h3), isPad: false, isThroughJumper: true } }, { regionId: `${e52.jumperId}_pad2`, ports: [], d: { bounds: a4, center: o4, polygon: gG(a4), isPad: true, isThroughJumper: false } }];\n }))(n2.jumpers, { orientation: t2.orientation, padWidth: t2.padWidth, padHeight: t2.padHeight }), d2 = ((e51, t3, n3 = 0.00001) =\u003e {\n const o4 = [];\n let i4 = 0;\n for (let r4 = 0;r4 \u003c e51.length; r4++) {\n const s3 = e51[r4];\n if (s3?.d.polygon)\n for (let a4 = r4 + 1;a4 \u003c e51.length; a4++) {\n const r5 = e51[a4];\n if (!r5?.d.polygon)\n continue;\n const c4 = vG(s3, r5, n3);\n for (const e52 of c4) {\n const n4 = bG(e52), a5 = Math.floor(n4 / t3), c5 = Math.max(1, a5 - 1);\n for (let t4 = 0;t4 \u003c c5; t4++) {\n const n5 = xG(e52, (t4 + 1) / (c5 + 1));\n o4.push({ portId: \"tp_\" + i4++, region1: s3, region2: r5, d: { x: n5.x, y: n5.y } });\n }\n }\n }\n }\n return o4;\n })(l3, t2.portSpacing), u2 = ((e51, t3, n3 = 0.00001) =\u003e {\n const o4 = [];\n let i4 = 0, r4 = 0;\n const s3 = e51.filter((e52) =\u003e e52.d.isPad), a4 = e51.filter((e52) =\u003e e52.d.isThroughJumper \u0026\u0026 !e52.d.isPad);\n for (const e52 of s3)\n for (const r5 of t3) {\n const t4 = vG(e52, r5, n3), s4 = IG(t4, n3);\n for (const t5 of s4) {\n const n4 = xG(t5, 0.5);\n o4.push({ portId: \"jp_\" + i4++, region1: e52, region2: r5, d: { x: n4.x, y: n4.y } });\n }\n }\n for (const e52 of a4)\n for (const t4 of s3) {\n const i5 = MG(e52.d.bounds, t4.d.bounds, n3);\n if (!i5)\n continue;\n const s4 = mG(i5);\n o4.push({ portId: \"jip_\" + r4++, region1: t4, region2: e52, d: { x: s4.x, y: s4.y } });\n }\n return o4;\n })(h2, l3), p3 = [...d2, ...u2];\n return ((e51) =\u003e {\n for (const t3 of e51)\n t3.region1.ports.push(t3), t3.region2.ports.push(t3);\n })(p3), { regions: [...l3, ...h2], ports: p3, jumperLocations: n2.jumpers.map((e51, t3) =\u003e ({ center: e51.center, orientation: e51.orientation, padRegions: [h2[3 * t3], h2[3 * t3 + 2]].filter((e52) =\u003e Boolean(e52)) })), topLayerRegions: l3, jumperRegions: h2, jumpers: n2.jumpers, vias: n2.vias, bounds: n2.bounds };\n};\nvar NG = class extends ni {\n getSolverName() {\n return \"JumperPrepatternSolver2_HyperGraph\";\n }\n constructorParams;\n nodeWithPortPoints;\n colorMap;\n traceWidth;\n obstacleMargin;\n hyperParameters;\n jumperGraphSolver = null;\n xyConnections = [];\n graphBounds = null;\n jumperLocations = [];\n solvedRoutes = [];\n jumpers = [];\n phase = \"jumperGraph\";\n curvySolvers = [];\n currentCurvySolverIndex = 0;\n routeInfos = [];\n regionCurvedPaths = new Map;\n constructor(e50) {\n super(), this.constructorParams = e50, this.nodeWithPortPoints = e50.nodeWithPortPoints, this.colorMap = e50.colorMap ?? {}, this.traceWidth = e50.traceWidth ?? 0.15, this.obstacleMargin = e50.obstacleMargin ?? 0.15, this.hyperParameters = e50.hyperParameters ?? {}, this.MAX_ITERATIONS = 1e6, Object.keys(this.colorMap).length === 0 \u0026\u0026 (this.colorMap = this._buildColorMap());\n }\n getConstructorParams() {\n return this.constructorParams;\n }\n _buildColorMap() {\n const e50 = [\"#e6194b\", \"#3cb44b\", \"#ffe119\", \"#4363d8\", \"#f58231\", \"#911eb4\", \"#46f0f0\", \"#f032e6\", \"#bcf60c\", \"#fabebe\"], t2 = {}, n2 = new Set;\n for (const e51 of this.nodeWithPortPoints.portPoints)\n n2.add(e51.connectionName);\n let o3 = 0;\n for (const i3 of Array.from(n2))\n t2[i3] = e50[o3 % e50.length], o3++;\n return t2;\n }\n _normalizeRegionPolygonsToBounds(e50) {\n for (const t2 of e50.regions) {\n const e51 = t2.d, n2 = e51?.polygon, o3 = e51?.bounds;\n if (!n2 || n2.length === 0 || !o3)\n continue;\n let i3 = 1 / 0, r3 = 1 / 0;\n for (const e52 of n2)\n i3 = Math.min(i3, e52.x), r3 = Math.min(r3, e52.y);\n const s2 = o3.minX - i3, a3 = o3.minY - r3;\n (Math.abs(s2) \u003e 0.000000000001 || Math.abs(a3) \u003e 0.000000000001) \u0026\u0026 (e51.polygon = n2.map((e52) =\u003e ({ x: e52.x + s2, y: e52.y + a3 }))), e51.polygonPerimeterCache \u0026\u0026 (e51.polygonPerimeterCache = undefined);\n }\n return e50;\n }\n _getPatternConfig() {\n return { cols: this.hyperParameters.COLS ?? 1, rows: this.hyperParameters.ROWS ?? 1 };\n }\n _generate0603Grid(e50, t2, n2, o3) {\n const i3 = t2 === \"horizontal\" ? e50.rows : e50.cols, r3 = t2 === \"horizontal\" ? e50.cols : e50.rows, s2 = o3.maxX - o3.minX, a3 = o3.maxY - o3.minY, c3 = 0.35, l3 = this.hyperParameters.TRACE_CHANNELS_BETWEEN_JUMPERS ?? 1, h2 = this.traceWidth * l3 + 2 * this.obstacleMargin, d2 = t2 === \"horizontal\" ? 2.15 : 1, u2 = t2 === \"horizontal\" ? 1 : 2.15, p3 = t2 === \"horizontal\" ? \"x\" : \"y\", m2 = n2 === \"staggered\", g2 = m2 \u0026\u0026 p3 === \"x\" ? d2 / 2 : m2 ? u2 / 2 : 0, f2 = Math.max(0, s2 - 1), _2 = Math.max(0, a3 - 1), y2 = Math.max(0, f2 - (m2 \u0026\u0026 p3 === \"x\" ? g2 : 0)), b2 = Math.max(0, _2 - (m2 \u0026\u0026 p3 === \"y\" ? g2 : 0)), x2 = i3 \u003e 1 ? Math.max(d2 + h2, (y2 - d2) / (i3 - 1)) : d2, v2 = r3 \u003e 1 ? Math.max(u2 + h2, (b2 - u2) / (r3 - 1)) : u2, I2 = wG({ cols: i3, rows: r3, orientation: t2, pattern: n2, staggerAxis: p3, colSpacing: x2, rowSpacing: v2, padWidth: 0.9, padHeight: 1, padGap: c3, clearance: h2, boundsPadding: 0, maxNeckRatio: 0.4, minSplitBalanceRatio: 0.2 }), S2 = I2.bounds, C = (S2.minX + S2.maxX) / 2, P = (S2.minY + S2.maxY) / 2, M = Gt((o3.minX + o3.maxX) / 2 - C, (o3.minY + o3.maxY) / 2 - P);\n return this._normalizeRegionPolygonsToBounds(dX(I2, M));\n }\n _initializeGraph() {\n const e50 = this.nodeWithPortPoints, t2 = this._getPatternConfig(), n2 = this.hyperParameters.ORIENTATION ?? \"vertical\", o3 = this.hyperParameters.JUMPER_TYPE ?? \"1206x4\", i3 = this.hyperParameters.PATTERN ?? \"grid\", r3 = { minX: e50.center.x - e50.width / 2, maxX: e50.center.x + e50.width / 2, minY: e50.center.y - e50.height / 2, maxY: e50.center.y + e50.height / 2 };\n let s2;\n if (this.graphBounds = r3, o3 === \"0603\") {\n const e51 = this._generate0603Grid(t2, n2, i3, r3);\n if (!e51)\n return this.error = `0603 grid (${t2.cols}x${t2.rows}) is too large to fit in node bounds`, this.failed = true, false;\n s2 = e51;\n } else\n s2 = IX({ cols: t2.cols, rows: t2.rows, marginX: Math.max(1.2, 0.3 * t2.cols), marginY: Math.max(1.2, 0.3 * t2.rows), outerPaddingX: 0.4, outerPaddingY: 0.4, parallelTracesUnderJumperCount: 2, innerColChannelPointCount: 3, innerRowChannelPointCount: 3, outerChannelXPointCount: 3, outerChannelYPointCount: 3, regionsBetweenPads: true, orientation: n2, bounds: r3 });\n if (s2.regions.length \u003e 0) {\n let e51 = 1 / 0, t3 = -1 / 0, n3 = 1 / 0, i4 = -1 / 0;\n for (const o4 of s2.regions) {\n if (!o4.d?.isPad)\n continue;\n const r4 = o4.d?.bounds;\n r4 \u0026\u0026 (e51 = Math.min(e51, r4.minX), t3 = Math.max(t3, r4.maxX), n3 = Math.min(n3, r4.minY), i4 = Math.max(i4, r4.maxY));\n }\n const a4 = o3 === \"0603\" ? 0.5 : 1;\n if (e51 - a4 \u003c r3.minX || t3 + a4 \u003e r3.maxX || n3 - a4 \u003c r3.minY || i4 + a4 \u003e r3.maxY)\n return this.error = `baseGraph bounds (${e51.toFixed(2)}, ${n3.toFixed(2)}, ${t3.toFixed(2)}, ${i4.toFixed(2)}) exceed node bounds (${r3.minX.toFixed(2)}, ${r3.minY.toFixed(2)}, ${r3.maxX.toFixed(2)}, ${r3.maxY.toFixed(2)})`, this.failed = true, false;\n }\n this.jumperLocations = s2.jumperLocations?.map((e51) =\u003e ({ center: e51.center, orientation: e51.orientation, padRegions: e51.padRegions })) ?? [];\n const a3 = new Map;\n for (const t3 of e50.portPoints) {\n const e51 = a3.get(t3.connectionName);\n e51 ? e51.points.push(t3) : a3.set(t3.connectionName, { points: [t3], rootConnectionName: t3.rootConnectionName });\n }\n this.xyConnections = [];\n for (const [e51, t3] of Array.from(a3.entries()))\n t3.points.length \u003c 2 || this.xyConnections.push({ start: { x: t3.points[0].x, y: t3.points[0].y }, end: { x: t3.points[1].x, y: t3.points[1].y }, connectionId: e51 });\n if (this.xyConnections.length === 0)\n return this.solved = true, true;\n const c3 = ((e51, t3) =\u003e {\n const n3 = [...e51.regions], o4 = [...e51.ports], i4 = [], r4 = WY(e51.regions);\n for (const s3 of t3) {\n const { start: t4, end: a4, connectionId: c4 } = s3, l3 = UY(`conn:${c4}:start`, t4.x, t4.y);\n n3.push(l3);\n const h2 = UY(`conn:${c4}:end`, a4.x, a4.y);\n n3.push(h2);\n const d2 = eX(t4.x, t4.y, e51.regions, r4);\n if (d2) {\n const e52 = GY(`conn:${c4}:start-port`, l3, d2.region, d2.portPosition);\n o4.push(e52);\n }\n const u2 = eX(a4.x, a4.y, e51.regions, r4);\n if (u2) {\n const e52 = GY(`conn:${c4}:end-port`, h2, u2.region, u2.portPosition);\n o4.push(e52);\n }\n const p3 = { connectionId: c4, mutuallyConnectedNetworkId: c4, startRegion: l3, endRegion: h2 };\n i4.push(p3);\n }\n return { regions: n3, ports: o4, connections: i4 };\n })(s2, this.xyConnections);\n return this.jumperGraphSolver = new xX({ inputGraph: { regions: c3.regions, ports: c3.ports }, inputConnections: c3.connections }), this.jumperGraphSolver.MAX_ITERATIONS *= 3, true;\n }\n _step() {\n switch (this.phase) {\n case \"jumperGraph\":\n this._stepJumperGraph();\n break;\n case \"curvyTrace\":\n this._stepCurvyTrace();\n break;\n case \"done\":\n this.solved = true;\n }\n }\n _stepJumperGraph() {\n if (!this.jumperGraphSolver) {\n if (this._initializeGraph(), this.solved)\n return;\n if (!this.jumperGraphSolver)\n return void (this.failed = true);\n }\n this.activeSubSolver = this.jumperGraphSolver, this.jumperGraphSolver.step(), this.jumperGraphSolver.solved ? (this._initializeCurvyTraceSolvers(), this.curvySolvers.length \u003e 0 ? this.phase = \"curvyTrace\" : (this._finalizeCurvyTraceResults(), this.phase = \"done\", this.solved = true)) : this.jumperGraphSolver.failed \u0026\u0026 (this.error = this.jumperGraphSolver.error, this.failed = true);\n }\n _stepCurvyTrace() {\n if (this.currentCurvySolverIndex \u003e= this.curvySolvers.length)\n return this._finalizeCurvyTraceResults(), this.phase = \"done\", void (this.solved = true);\n const e50 = this.curvySolvers[this.currentCurvySolverIndex], t2 = e50.solver;\n if (this.activeSubSolver = t2, t2.step(), t2.solved) {\n const n2 = e50.regionId;\n this.regionCurvedPaths.has(n2) || this.regionCurvedPaths.set(n2, new Map);\n for (const e51 of t2.outputTraces) {\n const t3 = e51.networkId ?? \"\", o3 = e51.points.map((e52) =\u003e ({ x: e52.x, y: e52.y })), i3 = { path: o3, start: o3[0] ?? { x: 0, y: 0 }, end: o3[o3.length - 1] ?? { x: 0, y: 0 } };\n this.regionCurvedPaths.get(n2).has(t3) || this.regionCurvedPaths.get(n2).set(t3, []), this.regionCurvedPaths.get(n2).get(t3).push(i3);\n }\n this.currentCurvySolverIndex++;\n } else\n t2.failed \u0026\u0026 this.currentCurvySolverIndex++;\n }\n _initializeCurvyTraceSolvers() {\n if (!this.jumperGraphSolver)\n return;\n const e50 = new Set, t2 = [];\n for (const e51 of this.jumperLocations)\n for (const n3 of e51.padRegions) {\n const e52 = n3.d.bounds, o3 = n3.d.center;\n t2.push({ minX: e52.minX, minY: e52.minY, maxX: e52.maxX, maxY: e52.maxY, center: { x: o3.x, y: o3.y }, networkIds: [] });\n }\n const n2 = new Map;\n for (let t3 = 0;t3 \u003c this.jumperGraphSolver.solvedRoutes.length; t3++) {\n const o3 = this.jumperGraphSolver.solvedRoutes[t3], i3 = o3.connection.connectionId, r3 = this.nodeWithPortPoints.portPoints.find((e51) =\u003e e51.connectionName === i3)?.rootConnectionName, s2 = [], a3 = [];\n let c3 = null, l3 = null;\n for (let h2 = 0;h2 \u003c o3.path.length; h2++) {\n const d2 = o3.path[h2], u2 = d2.port, p3 = d2.lastRegion, m2 = u2.region1, g2 = u2.region2;\n let f2;\n if (p3)\n m2 \u0026\u0026 m2.regionId !== p3.regionId ? f2 = m2 : g2 \u0026\u0026 g2.regionId !== p3.regionId \u0026\u0026 (f2 = g2);\n else {\n const e51 = o3.path[h2 + 1], t4 = e51?.lastRegion;\n if (t4 \u0026\u0026 (m2 \u0026\u0026 m2.regionId === t4.regionId ? f2 = m2 : g2 \u0026\u0026 g2.regionId === t4.regionId \u0026\u0026 (f2 = g2)), !f2) {\n const e52 = (e53) =\u003e e53?.regionId?.startsWith(\"conn:\");\n f2 = !m2 || e52(m2) || m2.d?.isPad || m2.d?.isThroughJumper ? !g2 || e52(g2) || g2.d?.isPad || g2.d?.isThroughJumper ? !m2 || m2.d?.isPad || m2.d?.isThroughJumper ? (!g2 || g2.d?.isPad || g2.d?.isThroughJumper) \u0026\u0026 m2 || g2 : m2 : g2 : m2;\n }\n }\n if (f2 \u0026\u0026 (!c3 || f2.regionId !== c3.regionId)) {\n if (c3 \u0026\u0026 l3) {\n a3.push({ regionId: c3.regionId, region: c3, entryPort: l3, exitPort: u2 });\n const e51 = c3.regionId;\n n2.has(e51) || n2.set(e51, []), n2.get(e51).push({ regionId: c3.regionId, region: c3, routeIndex: t3, connectionName: i3, rootConnectionName: r3, entryPort: l3, exitPort: u2 });\n }\n c3 = f2, l3 = u2;\n }\n if (p3?.d?.isThroughJumper \u0026\u0026 !e50.has(p3.regionId)) {\n e50.add(p3.regionId);\n const t4 = p3.d.bounds, n3 = p3.d.center, o4 = t4.maxX - t4.minX \u003e t4.maxY - t4.minY, i4 = (this.hyperParameters.JUMPER_TYPE ?? \"1206x4\") === \"0603\" ? \"0603\" : \"1206x4_pair\";\n o4 ? s2.push({ route_type: \"jumper\", start: { x: t4.minX, y: n3.y }, end: { x: t4.maxX, y: n3.y }, footprint: i4 }) : s2.push({ route_type: \"jumper\", start: { x: n3.x, y: t4.minY }, end: { x: n3.x, y: t4.maxY }, footprint: i4 });\n }\n }\n if (c3 \u0026\u0026 l3) {\n const e51 = o3.path[o3.path.length - 1];\n a3.push({ regionId: c3.regionId, region: c3, entryPort: l3, exitPort: e51?.port || null });\n }\n this.routeInfos.push({ connectionId: i3, rootConnectionName: r3, jumpers: s2, traversals: a3 });\n }\n for (let e51 = 0;e51 \u003c this.routeInfos.length; e51++) {\n const n3 = this.routeInfos[e51], o3 = n3.rootConnectionName ?? n3.connectionId;\n for (const e52 of n3.jumpers) {\n const n4 = [e52.start, e52.end];\n for (const e53 of n4)\n for (const n5 of t2) {\n const t3 = Math.abs(n5.center.x - e53.x), i3 = Math.abs(n5.center.y - e53.y);\n t3 \u003c 0.1 \u0026\u0026 i3 \u003c 0.1 \u0026\u0026 (n5.networkIds.includes(o3) || n5.networkIds.push(o3));\n }\n }\n }\n for (const [e51, o3] of n2) {\n if (o3.length === 0)\n continue;\n const n3 = o3[0].region;\n if (n3.d.isPad || n3.d.isThroughJumper)\n continue;\n const i3 = n3.d.bounds, r3 = [];\n for (const e52 of o3)\n r3.push({ start: { x: e52.entryPort.d.x, y: e52.entryPort.d.y }, end: { x: e52.exitPort.d.x, y: e52.exitPort.d.y }, networkId: e52.rootConnectionName ?? e52.connectionName });\n const s2 = 0.01, a3 = t2.filter((e52) =\u003e e52.minX \u003c= i3.maxX + s2 \u0026\u0026 e52.maxX \u003e= i3.minX - s2 \u0026\u0026 e52.minY \u003c= i3.maxY + s2 \u0026\u0026 e52.maxY \u003e= i3.minY - s2).map((e52) =\u003e {\n const t3 = o3.map((e53) =\u003e e53.rootConnectionName ?? e53.connectionName), n4 = e52.networkIds.find((e53) =\u003e t3.includes(e53));\n return { minX: e52.minX, minY: e52.minY, maxX: e52.maxX, maxY: e52.maxY, center: e52.center, networkId: n4 };\n }), c3 = { bounds: i3, waypointPairs: r3, obstacles: a3, preferredTraceToTraceSpacing: 2 * this.traceWidth, preferredObstacleToTraceSpacing: 2 * this.traceWidth }, l3 = new K$(c3);\n this.curvySolvers.push({ solver: l3, regionId: e51, traversals: o3.map((e52) =\u003e ({ routeIndex: e52.routeIndex, connectionName: e52.connectionName, rootConnectionName: e52.rootConnectionName })) });\n }\n }\n _finalizeCurvyTraceResults() {\n const e50 = (e51, t2) =\u003e Math.sqrt((e51.x - t2.x) ** 2 + (e51.y - t2.y) ** 2);\n for (let t2 = 0;t2 \u003c this.routeInfos.length; t2++) {\n const n2 = this.routeInfos[t2], o3 = [];\n for (const t3 of n2.traversals) {\n const i3 = t3.regionId, r3 = n2.rootConnectionName ?? n2.connectionId, s2 = this.regionCurvedPaths.get(i3)?.get(r3);\n let a3 = null;\n if (s2 \u0026\u0026 s2.length \u003e 0) {\n const n3 = { x: t3.entryPort.d.x, y: t3.entryPort.d.y }, o4 = t3.exitPort ? { x: t3.exitPort.d.x, y: t3.exitPort.d.y } : null;\n let i4 = null, r4 = 1 / 0;\n for (const t4 of s2) {\n const s3 = e50(t4.start, n3) + (o4 ? e50(t4.end, o4) : 0);\n s3 \u003c r4 \u0026\u0026 (r4 = s3, i4 = t4);\n }\n i4 \u0026\u0026 r4 \u003c 0.5 \u0026\u0026 (a3 = i4.path);\n }\n if (a3 \u0026\u0026 a3.length \u003e 0) {\n for (let e51 = o3.length \u003e 0 ? 1 : 0;e51 \u003c a3.length; e51++)\n o3.push({ x: a3[e51].x, y: a3[e51].y, z: 0 });\n } else\n o3.length === 0 \u0026\u0026 o3.push({ x: t3.entryPort.d.x, y: t3.entryPort.d.y, z: 0 }), t3.exitPort \u0026\u0026 o3.push({ x: t3.exitPort.d.x, y: t3.exitPort.d.y, z: 0 });\n }\n this.solvedRoutes.push({ connectionName: n2.connectionId, rootConnectionName: n2.rootConnectionName, traceThickness: this.traceWidth, route: o3, jumpers: n2.jumpers });\n }\n }\n getOutput() {\n return this.solvedRoutes;\n }\n getOutputJumpers() {\n if (this.jumpers.length \u003e 0)\n return this.jumpers;\n const e50 = new Map;\n for (const t3 of this.solvedRoutes)\n for (const n3 of t3.jumpers) {\n const o3 = [n3.start, n3.end];\n for (const n4 of o3) {\n const o4 = `${n4.x.toFixed(3)},${n4.y.toFixed(3)}`, i3 = e50.get(o4) ?? [];\n t3.rootConnectionName \u0026\u0026 !i3.includes(t3.rootConnectionName) \u0026\u0026 i3.push(t3.rootConnectionName), i3.includes(t3.connectionName) || i3.push(t3.connectionName), e50.set(o4, i3);\n }\n }\n const t2 = this.hyperParameters.JUMPER_TYPE ?? \"1206x4\", n2 = Xo[t2 === \"0603\" ? \"0603\" : \"1206x4_pair\"];\n for (const o3 of this.jumperLocations) {\n const i3 = o3.orientation === \"horizontal\", r3 = o3.padRegions.map((t3) =\u003e {\n const n3 = t3.d.bounds, o4 = t3.d.center, i4 = n3.maxX - n3.minX, r4 = n3.maxY - n3.minY, s3 = `${o4.x.toFixed(3)},${o4.y.toFixed(3)}`;\n return { type: \"rect\", center: o4, width: i4, height: r4, layers: [\"top\"], connectedTo: [...e50.get(s3) ?? []] };\n }), s2 = { jumper_footprint: t2, center: o3.center, orientation: o3.orientation, width: i3 ? n2.length : n2.width, height: i3 ? n2.width : n2.length, pads: r3 };\n this.jumpers.push(s2);\n }\n return this.jumpers = this.jumpers.filter((e51) =\u003e e51.pads.some((e52) =\u003e e52.connectedTo.length \u003e 0)), this.jumpers;\n }\n visualize() {\n if (this.jumperGraphSolver \u0026\u0026 !this.solved)\n return this.jumperGraphSolver.visualize();\n const e50 = { lines: [], points: [], rects: [], circles: [] }, t2 = this.nodeWithPortPoints, n2 = { minX: t2.center.x - t2.width / 2, maxX: t2.center.x + t2.width / 2, minY: t2.center.y - t2.height / 2, maxY: t2.center.y + t2.height / 2 };\n e50.lines.push({ points: [{ x: n2.minX, y: n2.minY }, { x: n2.maxX, y: n2.minY }, { x: n2.maxX, y: n2.maxY }, { x: n2.minX, y: n2.maxY }, { x: n2.minX, y: n2.minY }], strokeColor: \"rgba(255, 0, 0, 0.25)\", strokeDash: \"4 4\", layer: \"border\" });\n for (const n3 of t2.portPoints)\n e50.points.push({ x: n3.x, y: n3.y, label: n3.connectionName, color: this.colorMap[n3.connectionName] ?? \"blue\" });\n for (const t3 of this.solvedRoutes) {\n const n3 = this.colorMap[t3.connectionName] ?? \"blue\";\n for (let o3 = 0;o3 \u003c t3.route.length - 1; o3++) {\n const i3 = t3.route[o3], r3 = t3.route[o3 + 1];\n e50.lines.push({ points: [i3, r3], strokeColor: Ao(n3, 0.2), strokeWidth: t3.traceThickness, layer: \"route-layer-0\" });\n }\n for (const o3 of t3.jumpers)\n this._drawJumperPads(e50, o3, Ao(n3, 0.5));\n }\n return e50;\n }\n _drawJumperPads(e50, t2, n2) {\n const o3 = Xo[t2.footprint], i3 = t2.end.x - t2.start.x, r3 = t2.end.y - t2.start.y, s2 = Math.abs(i3) \u003e Math.abs(r3), a3 = s2 ? o3.padLength : o3.padWidth, c3 = s2 ? o3.padWidth : o3.padLength;\n e50.rects.push({ center: { x: t2.start.x, y: t2.start.y }, width: a3, height: c3, fill: n2, stroke: \"rgba(0, 0, 0, 0.5)\", layer: \"jumper\" }), e50.rects.push({ center: { x: t2.end.x, y: t2.end.y }, width: a3, height: c3, fill: n2, stroke: \"rgba(0, 0, 0, 0.5)\", layer: \"jumper\" }), e50.lines.push({ points: [t2.start, t2.end], strokeColor: \"rgba(100, 100, 100, 0.8)\", strokeWidth: 0.3 * o3.padWidth, layer: \"jumper-body\" });\n }\n};\nvar RG = class extends wa {\n constructorParams;\n nodeWithPortPoints;\n colorMap;\n traceWidth;\n obstacleMargin;\n connMap;\n baseHyperParameters;\n availableJumperTypes;\n solvedRoutes = [];\n jumpers = [];\n constructor(e50) {\n super(), this.constructorParams = e50, this.nodeWithPortPoints = e50.nodeWithPortPoints, this.colorMap = e50.colorMap ?? {}, this.traceWidth = e50.traceWidth ?? 0.15, this.obstacleMargin = e50.obstacleMargin ?? 0.15, this.connMap = e50.connMap, this.baseHyperParameters = e50.hyperParameters ?? {}, this.availableJumperTypes = e50.availableJumperTypes ?? [\"0603\"], this.MAX_ITERATIONS = 1e6, this.GREEDY_MULTIPLIER = 1, this.MIN_SUBSTEPS = 1000;\n }\n getConstructorParams() {\n return this.constructorParams;\n }\n getHyperParameterDefs() {\n const e50 = [], t2 = this.nodeWithPortPoints, n2 = this.calculateMax0603ConfigWithTraceChannels(t2.width, t2.height, \"vertical\", 1);\n e50.push({ name: \"0603_max_rows_and_cols_vert_1trace_grid\", possibleValues: [{ JUMPER_TYPE: \"0603\", COLS: n2.cols, ROWS: n2.rows, ORIENTATION: \"vertical\", PATTERN: \"grid\", TRACE_CHANNELS_BETWEEN_JUMPERS: 1 }] });\n const o3 = this.calculateMax0603ConfigWithTraceChannels(t2.width, t2.height, \"vertical\", 1, \"staggered\");\n e50.push({ name: \"0603_max_rows_and_cols_vert_1trace_staggered\", possibleValues: [{ JUMPER_TYPE: \"0603\", COLS: o3.cols, ROWS: o3.rows, ORIENTATION: \"vertical\", PATTERN: \"staggered\", TRACE_CHANNELS_BETWEEN_JUMPERS: 1 }] });\n const i3 = this.calculateMax0603ConfigWithTraceChannels(t2.width, t2.height, \"vertical\", 2);\n e50.push({ name: \"0603_max_rows_and_cols_vert_2trace_grid\", possibleValues: [{ JUMPER_TYPE: \"0603\", COLS: i3.cols, ROWS: i3.rows, ORIENTATION: \"vertical\", PATTERN: \"grid\", TRACE_CHANNELS_BETWEEN_JUMPERS: 2 }] });\n const r3 = this.calculateMax0603ConfigWithTraceChannels(t2.width, t2.height, \"vertical\", 2, \"staggered\");\n e50.push({ name: \"0603_max_rows_and_cols_vert_2trace_staggered\", possibleValues: [{ JUMPER_TYPE: \"0603\", COLS: r3.cols, ROWS: r3.rows, ORIENTATION: \"vertical\", PATTERN: \"staggered\", TRACE_CHANNELS_BETWEEN_JUMPERS: 2 }] });\n const s2 = this.calculateMax0603ConfigWithTraceChannels(t2.width, t2.height, \"horizontal\", 1);\n e50.push({ name: \"0603_max_rows_and_cols_horz_1trace_grid\", possibleValues: [{ JUMPER_TYPE: \"0603\", COLS: s2.cols, ROWS: s2.rows, ORIENTATION: \"horizontal\", PATTERN: \"grid\", TRACE_CHANNELS_BETWEEN_JUMPERS: 1 }] });\n const a3 = this.calculateMax0603ConfigWithTraceChannels(t2.width, t2.height, \"horizontal\", 1, \"staggered\");\n e50.push({ name: \"0603_max_rows_and_cols_horz_1trace_staggered\", possibleValues: [{ JUMPER_TYPE: \"0603\", COLS: a3.cols, ROWS: a3.rows, ORIENTATION: \"horizontal\", PATTERN: \"staggered\", TRACE_CHANNELS_BETWEEN_JUMPERS: 1 }] });\n const c3 = this.calculateMax0603ConfigWithTraceChannels(t2.width, t2.height, \"horizontal\", 2);\n e50.push({ name: \"0603_max_rows_and_cols_horz_2trace_grid\", possibleValues: [{ JUMPER_TYPE: \"0603\", COLS: c3.cols, ROWS: c3.rows, ORIENTATION: \"horizontal\", PATTERN: \"grid\", TRACE_CHANNELS_BETWEEN_JUMPERS: 2 }] });\n const l3 = this.calculateMax0603ConfigWithTraceChannels(t2.width, t2.height, \"horizontal\", 2, \"staggered\");\n e50.push({ name: \"0603_max_rows_and_cols_horz_2trace_staggered\", possibleValues: [{ JUMPER_TYPE: \"0603\", COLS: l3.cols, ROWS: l3.rows, ORIENTATION: \"horizontal\", PATTERN: \"staggered\", TRACE_CHANNELS_BETWEEN_JUMPERS: 2 }] }), e50.push({ name: \"1206x4\", possibleValues: [{ JUMPER_TYPE: \"1206x4\" }] });\n return e50.push({ name: \"1206x4_cols\", possibleValues: [1, 2, 3, 4, 6, 8, 10].map((e51) =\u003e ({ COLS: e51 })) }), e50.push({ name: \"1206x4_rows\", possibleValues: [1, 2, 3, 4, 8].map((e51) =\u003e ({ ROWS: e51 })) }), e50.push({ name: \"orientation\", possibleValues: [{ ORIENTATION: \"vertical\" }, { ORIENTATION: \"horizontal\" }] }), e50;\n }\n isValidCombination(e50) {\n const { JUMPER_TYPE: t2, COLS: n2, ROWS: o3 } = e50, i3 = [1, 2, 4, 6, 8], r3 = [1, 2, 3, 4, 6, 8, 10], s2 = [1, 2, 3, 4, 8];\n return t2 === \"0603\" ? i3.includes(n2) \u0026\u0026 i3.includes(o3) : t2 === \"1206x4\" \u0026\u0026 (r3.includes(n2) \u0026\u0026 s2.includes(o3));\n }\n getCombinationDefs() {\n return [[\"0603_max_rows_and_cols_vert_1trace_grid\"], [\"0603_max_rows_and_cols_vert_1trace_staggered\"], [\"0603_max_rows_and_cols_horz_1trace_grid\"], [\"0603_max_rows_and_cols_horz_1trace_staggered\"], [\"0603_max_rows_and_cols_vert_2trace_grid\"], [\"0603_max_rows_and_cols_vert_2trace_staggered\"], [\"0603_max_rows_and_cols_horz_2trace_grid\"], [\"0603_max_rows_and_cols_horz_2trace_staggered\"], [\"1206x4\", \"1206x4_cols\", \"1206x4_rows\", \"orientation\"]];\n }\n calculateMax0603ConfigWithTraceChannels(e50, t2, n2, o3, i3 = \"grid\") {\n const r3 = this.traceWidth * o3 + 2 * this.obstacleMargin, s2 = n2 === \"horizontal\" ? 2.15 : 1, a3 = n2 === \"horizontal\" ? 1 : 2.15, c3 = n2 === \"horizontal\" ? \"x\" : \"y\", l3 = i3 === \"staggered\" \u0026\u0026 c3 === \"x\" ? s2 / 2 : i3 === \"staggered\" ? a3 / 2 : 0, h2 = Math.max(0, e50 - 1), d2 = Math.max(0, t2 - 1), u2 = Math.max(0, h2 - (i3 === \"staggered\" \u0026\u0026 c3 === \"x\" ? l3 : 0)), p3 = Math.max(0, d2 - (i3 === \"staggered\" \u0026\u0026 c3 === \"y\" ? l3 : 0)), m2 = s2 + r3, g2 = a3 + r3, f2 = Math.max(1, Math.floor(1 + (u2 - s2) / m2)), _2 = Math.max(1, Math.floor(1 + (p3 - a3) / g2));\n return n2 === \"vertical\" ? { cols: f2, rows: _2 } : { cols: _2, rows: f2 };\n }\n initializeSolvers() {\n const e50 = this.getHyperParameterDefs(), t2 = this.getCombinationDefs();\n this.supervisedSolvers = [];\n for (const n2 of t2) {\n const t3 = n2.some((e51) =\u003e e51.startsWith(\"0603_max_rows_and_cols_\")), o3 = n2.includes(\"1206x4\");\n if (t3 \u0026\u0026 !this.availableJumperTypes.includes(\"0603\"))\n continue;\n if (o3 \u0026\u0026 !this.availableJumperTypes.includes(\"1206x4\"))\n continue;\n const i3 = this.getHyperParameterCombinations(e50.filter((e51) =\u003e n2.includes(e51.name)));\n for (const e51 of i3) {\n const t4 = this.generateSolver(e51), n3 = this.computeG(t4);\n this.supervisedSolvers.push({ hyperParameters: e51, solver: t4, h: 0, g: n3, f: n3 });\n }\n }\n }\n generateSolver(e50) {\n return new NG({ nodeWithPortPoints: this.nodeWithPortPoints, colorMap: this.colorMap, traceWidth: this.traceWidth, hyperParameters: { COLS: e50.COLS, ROWS: e50.ROWS, ORIENTATION: e50.ORIENTATION, JUMPER_TYPE: e50.JUMPER_TYPE, PATTERN: e50.PATTERN, TRACE_CHANNELS_BETWEEN_JUMPERS: e50.TRACE_CHANNELS_BETWEEN_JUMPERS }, obstacleMargin: this.obstacleMargin });\n }\n computeG(e50) {\n const t2 = e50.hyperParameters.COLS * e50.hyperParameters.ROWS;\n return e50.iterations / 1e4 + 0.25 * t2;\n }\n computeH(e50) {\n return 1 - (e50.progress || 0);\n }\n onSolve(e50) {\n this.solvedRoutes = e50.solver.solvedRoutes, this.jumpers = e50.solver.getOutputJumpers();\n }\n getOutput() {\n return this.solvedRoutes;\n }\n getOutputJumpers() {\n return this.jumpers;\n }\n visualize() {\n return this.winningSolver ? this.winningSolver.visualize() : super.visualize();\n }\n};\nfunction TG(e50) {\n return { connectionName: e50.connectionName, rootConnectionName: e50.rootConnectionName, regionId: e50.regionId, traceThickness: e50.traceThickness, viaDiameter: 0, route: e50.route, vias: [], jumpers: e50.jumpers };\n}\nvar EG = class extends ni {\n getSolverName() {\n return \"JumperHighDensitySolver\";\n }\n allNodes;\n nodeAnalyses;\n routes;\n colorMap;\n traceWidth;\n obstacleMargin;\n viaDiameter;\n connMap;\n hyperParameters;\n availableJumperTypes;\n capacityMeshNodes;\n capacityMeshEdges;\n capacityMeshNodeMap;\n nodeAdjacencyMap;\n nodesWithoutCrossings;\n nodesWithCrossings;\n curvyIntraNodeSolvers;\n currentCurvySolverIndex;\n jumperSolvers;\n currentJumperSolverIndex;\n phase;\n jumpers = [];\n constructor({ nodePortPoints: e50, colorMap: t2, traceWidth: n2 = 0.15, obstacleMargin: o3 = 0.15, viaDiameter: i3 = 0.3, connMap: r3, hyperParameters: s2, capacityMeshNodes: a3 = [], capacityMeshEdges: c3 = [], availableJumperTypes: l3 }) {\n super(), this.allNodes = [...e50], this.colorMap = t2 ?? {}, this.routes = [], this.traceWidth = n2, this.obstacleMargin = o3, this.viaDiameter = i3, this.connMap = r3, this.hyperParameters = s2, this.capacityMeshNodes = a3, this.capacityMeshEdges = c3, this.availableJumperTypes = l3 ?? [\"0603\"], this.capacityMeshNodeMap = new Map(a3.map((e51) =\u003e [e51.capacityMeshNodeId, e51])), this.nodeAdjacencyMap = this._buildNodeAdjacencyMap(), this.nodesWithoutCrossings = [], this.nodesWithCrossings = [], this.nodeAnalyses = [], this.curvyIntraNodeSolvers = [], this.currentCurvySolverIndex = 0, this.jumperSolvers = [], this.currentJumperSolverIndex = 0, this.phase = \"analyzing\", this._analyzeNodes();\n const h2 = 1000 * this.nodesWithoutCrossings.length, d2 = 1e5 * this.nodesWithCrossings.length;\n this.MAX_ITERATIONS = h2 + d2 + 100;\n }\n _buildNodeAdjacencyMap() {\n const e50 = new Map;\n for (const t2 of this.capacityMeshEdges) {\n const [n2, o3] = t2.nodeIds;\n e50.has(n2) || e50.set(n2, new Set), e50.has(o3) || e50.set(o3, new Set), e50.get(n2).add(o3), e50.get(o3).add(n2);\n }\n return e50;\n }\n _analyzeNodes() {\n for (const e50 of this.allNodes) {\n const t2 = Cz(e50), n2 = { node: e50, hasCrossings: t2.numSameLayerCrossings \u003e 0, numSameLayerCrossings: t2.numSameLayerCrossings };\n this.nodeAnalyses.push(n2), t2.numSameLayerCrossings \u003e 0 ? this.nodesWithCrossings.push(e50) : this.nodesWithoutCrossings.push(e50);\n }\n this.nodesWithoutCrossings.length \u003e 0 ? (this.phase = \"curvy\", this._initializeCurvySolvers()) : this.nodesWithCrossings.length \u003e 0 ? (this.phase = \"jumpers\", this._initializeJumperSolvers()) : this.phase = \"done\";\n }\n _step() {\n switch (this.phase) {\n case \"analyzing\":\n this.nodesWithoutCrossings.length \u003e 0 ? (this.phase = \"curvy\", this._initializeCurvySolvers()) : this.nodesWithCrossings.length \u003e 0 ? (this.phase = \"jumpers\", this._initializeJumperSolvers()) : this.phase = \"done\";\n break;\n case \"curvy\":\n this._stepCurvySolvers();\n break;\n case \"jumpers\":\n this._stepJumperSolvers();\n break;\n case \"done\":\n this.solved = true;\n }\n }\n _getAdjacentObstacles(e50) {\n const t2 = [], n2 = this.nodeAdjacencyMap.get(e50.capacityMeshNodeId);\n if (!n2 || n2.size === 0)\n return t2;\n const o3 = new Map(this.allNodes.map((e51) =\u003e [e51.capacityMeshNodeId, e51]));\n for (const e51 of n2) {\n const n3 = this.capacityMeshNodeMap.get(e51);\n if (!n3)\n continue;\n if (!n3._containsObstacle \u0026\u0026 !n3._containsTarget)\n continue;\n const i3 = n3.center.x - n3.width / 2, r3 = n3.center.y - n3.height / 2, s2 = n3.center.x + n3.width / 2, a3 = n3.center.y + n3.height / 2;\n let c3;\n if (n3._containsTarget)\n if (n3._targetConnectionName)\n c3 = n3._targetConnectionName;\n else {\n const t3 = o3.get(e51);\n t3 \u0026\u0026 t3.portPoints.length \u003e 0 \u0026\u0026 (c3 = t3.portPoints[0].rootConnectionName ?? t3.portPoints[0].connectionName);\n }\n t2.push({ minX: i3, minY: r3, maxX: s2, maxY: a3, networkId: c3 });\n }\n return t2;\n }\n _initializeCurvySolvers() {\n for (const e50 of this.nodesWithoutCrossings) {\n const t2 = this._getAdjacentObstacles(e50), n2 = new eY({ nodeWithPortPoints: e50, colorMap: this.colorMap, traceWidth: this.traceWidth, viaDiameter: this.viaDiameter, adjacentObstacles: t2 });\n this.curvyIntraNodeSolvers.push(n2);\n }\n }\n _stepCurvySolvers() {\n if (this.curvyIntraNodeSolvers.length === 0)\n return this.phase = this.nodesWithCrossings.length \u003e 0 ? \"jumpers\" : \"done\", void (this.phase === \"jumpers\" \u0026\u0026 this._initializeJumperSolvers());\n const e50 = this.curvyIntraNodeSolvers[this.currentCurvySolverIndex];\n if (this.activeSubSolver = e50, !e50)\n return this.phase = this.nodesWithCrossings.length \u003e 0 ? \"jumpers\" : \"done\", void (this.phase === \"jumpers\" \u0026\u0026 this._initializeJumperSolvers());\n if (e50.step(), e50.solved) {\n this.routes.push(...e50.routes), this.currentCurvySolverIndex++;\n for (let e51 = this.currentCurvySolverIndex;e51 \u003c this.curvyIntraNodeSolvers.length; e51++) {\n this.curvyIntraNodeSolvers[e51];\n const t2 = this.nodesWithoutCrossings[e51], n2 = this._getAdjacentObstacles(t2), o3 = new eY({ nodeWithPortPoints: t2, colorMap: this.colorMap, traceWidth: this.traceWidth, viaDiameter: this.viaDiameter, adjacentObstacles: n2 });\n this.curvyIntraNodeSolvers[e51] = o3;\n }\n this.currentCurvySolverIndex \u003e= this.curvyIntraNodeSolvers.length \u0026\u0026 (this.phase = this.nodesWithCrossings.length \u003e 0 ? \"jumpers\" : \"done\", this.phase === \"jumpers\" \u0026\u0026 this._initializeJumperSolvers());\n } else\n e50.failed \u0026\u0026 (this.error = `CurvyIntraNodeSolver failed for node: ${e50.nodeWithPortPoints.capacityMeshNodeId}: ${e50.error}`, this.failed = true);\n }\n _initializeJumperSolvers() {\n for (const e50 of this.nodesWithCrossings) {\n const t2 = new RG({ nodeWithPortPoints: e50, colorMap: this.colorMap, traceWidth: this.traceWidth, obstacleMargin: this.obstacleMargin, connMap: this.connMap, availableJumperTypes: this.availableJumperTypes });\n this.jumperSolvers.push(t2);\n }\n }\n _stepJumperSolvers() {\n if (this.jumperSolvers.length === 0)\n return this.phase = \"done\", void (this.solved = true);\n const e50 = this.jumperSolvers[this.currentJumperSolverIndex];\n if (this.activeSubSolver = e50, !e50)\n return this.phase = \"done\", void (this.solved = true);\n if (e50.step(), e50.solved) {\n for (const t2 of e50.solvedRoutes)\n this.routes.push(TG(t2));\n this.jumpers.push(...e50.getOutputJumpers()), this.currentJumperSolverIndex++, this.currentJumperSolverIndex \u003e= this.jumperSolvers.length \u0026\u0026 (this.phase = \"done\", this.solved = true);\n } else\n e50.failed \u0026\u0026 (this.error = `HyperJumperPrepatternSolver2 failed for node: ${e50.nodeWithPortPoints.capacityMeshNodeId}: ${e50.error}`, this.failed = true);\n }\n computeProgress() {\n const e50 = this.allNodes.length;\n if (e50 === 0)\n return 1;\n let t2 = 0;\n t2 += this.currentCurvySolverIndex;\n const n2 = this.curvyIntraNodeSolvers[this.currentCurvySolverIndex];\n n2 \u0026\u0026 (t2 += n2.progress), t2 += this.currentJumperSolverIndex;\n const o3 = this.jumperSolvers[this.currentJumperSolverIndex];\n return o3 \u0026\u0026 (t2 += o3.progress), t2 / e50;\n }\n getConstructorParams() {\n return { nodePortPoints: this.allNodes, colorMap: this.colorMap, traceWidth: this.traceWidth, obstacleMargin: this.obstacleMargin, viaDiameter: this.viaDiameter, connMap: this.connMap, hyperParameters: this.hyperParameters, capacityMeshNodes: this.capacityMeshNodes, capacityMeshEdges: this.capacityMeshEdges, availableJumperTypes: this.availableJumperTypes };\n }\n getOutputJumpers() {\n return this.jumpers;\n }\n visualize() {\n const e50 = { lines: [], points: [], rects: [], circles: [] };\n if (this.failed \u0026\u0026 this.activeSubSolver)\n return this.activeSubSolver.visualize();\n if (this.phase === \"curvy\" \u0026\u0026 this.curvyIntraNodeSolvers[this.currentCurvySolverIndex])\n return this.curvyIntraNodeSolvers[this.currentCurvySolverIndex].visualize();\n if (this.phase === \"jumpers\" \u0026\u0026 this.jumperSolvers[this.currentJumperSolverIndex])\n return this.jumperSolvers[this.currentJumperSolverIndex].visualize();\n for (const t2 of this.routes) {\n const n2 = t2.rootConnectionName ?? t2.connectionName, o3 = mi(t2.route, t2.connectionName, this.colorMap[n2]);\n for (const n3 of o3)\n e50.lines.push({ points: n3.points, label: n3.connectionName, strokeColor: n3.z === 0 ? n3.color : Ao(n3.color ?? \"gray\", 0.75), layer: `z${n3.z}`, strokeWidth: t2.traceThickness, strokeDash: n3.z !== 0 ? \"10, 5\" : undefined });\n for (const o4 of t2.vias)\n e50.circles.push({ center: o4, radius: t2.viaDiameter / 2, fill: Ao(this.colorMap[n2] ?? \"gray\", 0.5), layer: \"via\" });\n if (\"jumpers\" in t2 \u0026\u0026 t2.jumpers)\n for (const o4 of t2.jumpers) {\n const t3 = this.colorMap[n2] ?? \"gray\", i3 = o4.footprint ?? \"1206\", r3 = Xo[i3], s2 = o4.end.x - o4.start.x, a3 = o4.end.y - o4.start.y, c3 = Math.abs(s2) \u003e Math.abs(a3), l3 = c3 ? r3.padLength : r3.padWidth, h2 = c3 ? r3.padWidth : r3.padLength;\n e50.rects.push({ center: o4.start, width: l3, height: h2, fill: Ao(t3, 0.5), stroke: \"rgba(0, 0, 0, 0.5)\", layer: \"jumper\" }), e50.rects.push({ center: o4.end, width: l3, height: h2, fill: Ao(t3, 0.5), stroke: \"rgba(0, 0, 0, 0.5)\", layer: \"jumper\" }), e50.lines.push({ points: [o4.start, o4.end], strokeColor: \"rgba(100, 100, 100, 0.8)\", strokeWidth: 0.3 * r3.padWidth, layer: \"jumper-body\" });\n }\n }\n for (const t2 of this.nodeAnalyses) {\n const n2 = t2.node;\n n2.center.x, n2.width, n2.center.x, n2.width, n2.center.y, n2.height, n2.center.y, n2.height;\n e50.rects.push({ center: n2.center, width: n2.width, height: n2.height, fill: t2.hasCrossings ? \"rgba(255, 200, 0, 0.1)\" : \"rgba(0, 200, 0, 0.1)\", stroke: t2.hasCrossings ? \"rgba(255, 150, 0, 0.5)\" : \"rgba(0, 150, 0, 0.5)\", label: [n2.capacityMeshNodeId, t2.hasCrossings ? `crossings: ${t2.numSameLayerCrossings}` : \"no crossings\"].join(`\n`) });\n }\n return e50;\n }\n};\nfunction AG(e50, t2, n2, o3 = {}) {\n return { solverName: e50, solverClass: t2, getConstructorParams: n2, onSolved: o3.onSolved };\n}\nvar OG = class extends ni {\n constructor(e50, t2 = {}) {\n super(), this.srj = e50, this.opts = t2, this.srj = e50, this.opts = { ...t2 }, this.viaDiameter = Yo(e50).padDiameter, this.minTraceWidth = e50.minTraceWidth;\n const n2 = this.opts;\n if (this.effort = n2.effort ?? 1, this.MAX_ITERATIONS = 1e8 * this.effort, n2.capacityDepth === undefined) {\n const t3 = e50.bounds.maxX - e50.bounds.minX, o3 = e50.bounds.maxY - e50.bounds.minY, i3 = Math.max(t3, o3), r3 = n2.targetMinCapacity ?? 0.5;\n n2.capacityDepth = Fz(i3, r3);\n }\n this.connMap = ei(e50), this.colorMap = Eo(e50, this.connMap), this.cacheProvider = n2.cacheProvider === undefined ? no() : n2.cacheProvider === null ? null : n2.cacheProvider, this.startTimeOfPhase = {}, this.endTimeOfPhase = {}, this.timeSpentOnPhase = {};\n }\n getSolverName() {\n return \"AssignableAutoroutingPipeline3\";\n }\n netToPointPairsSolver;\n traceKeepoutSolver;\n nodeSolver;\n nodeTargetMerger;\n edgeSolver;\n relateNodesToOffBoardConnections;\n colorMap;\n highDensityRouteSolver;\n simpleHighDensityRouteSolver;\n highDensitySolver;\n highDensityStitchSolver;\n singleLayerNodeMerger;\n offboardPathFragmentSolver;\n strawSolver;\n deadEndSolver;\n traceSimplificationSolver;\n traceWidthSolver;\n availableSegmentPointSolver;\n portPointPathingSolver;\n multiSectionPortPointOptimizer;\n viaDiameter;\n minTraceWidth;\n effort;\n startTimeOfPhase;\n endTimeOfPhase;\n timeSpentOnPhase;\n activeSubSolver = null;\n connMap;\n srjWithPointPairs;\n capacityNodes = null;\n capacityEdges = null;\n cacheProvider = null;\n pipelineDef = [AG(\"netToPointPairsSolver\", uB, (e50) =\u003e [e50.srj, e50.colorMap, ti(e50.srj)], { onSolved: (e50) =\u003e {\n e50.srjWithPointPairs = e50.netToPointPairsSolver?.getNewSimpleRouteJson(), e50.colorMap = Eo(e50.srjWithPointPairs, this.connMap), e50.connMap = ei(e50.srjWithPointPairs);\n } }), AG(\"nodeSolver\", Jn, (e50) =\u003e [{ simpleRouteJson: e50.srjWithPointPairs, maxGapFillPasses: 4 }], { onSolved: (e50) =\u003e {\n e50.capacityNodes = e50.nodeSolver?.getOutput().meshNodes ?? [];\n } }), AG(\"relateNodesToOffBoardConnections\", h$, (e50) =\u003e [{ capacityMeshNodes: e50.capacityNodes, srj: e50.srj }], { onSolved: (e50) =\u003e {\n e50.capacityNodes = e50.relateNodesToOffBoardConnections?.getOutput().capacityNodes;\n } }), AG(\"edgeSolver\", ui, (e50) =\u003e [e50.capacityNodes], { onSolved: (e50) =\u003e {\n e50.capacityEdges = e50.edgeSolver?.edges;\n } }), AG(\"availableSegmentPointSolver\", ii, (e50) =\u003e [{ nodes: e50.capacityNodes, edges: e50.capacityEdges || [], traceWidth: e50.minTraceWidth, colorMap: e50.colorMap, shouldReturnCrampedPortPoints: false }]), AG(\"portPointPathingSolver\", Kz, (e50) =\u003e {\n const t2 = e50.capacityNodes.map((e51) =\u003e ({ capacityMeshNodeId: e51.capacityMeshNodeId, center: e51.center, width: e51.width, height: e51.height, portPoints: [], availableZ: e51.availableZ, _containsTarget: e51._containsTarget, _containsObstacle: e51._containsObstacle, _offBoardConnectionId: e51._offBoardConnectionId, _offBoardConnectedCapacityMeshNodeIds: e51._offBoardConnectedCapacityMeshNodeIds })), n2 = new Map(t2.map((e51) =\u003e [e51.capacityMeshNodeId, e51])), o3 = e50.availableSegmentPointSolver;\n for (const e51 of o3.sharedEdgeSegments)\n for (const t3 of e51.portPoints) {\n const [o4, i3] = t3.nodeIds, r3 = { portPointId: t3.segmentPortPointId, x: t3.x, y: t3.y, z: t3.availableZ[0] ?? 0, connectionNodeIds: [o4, i3], distToCentermostPortOnZ: t3.distToCentermostPortOnZ, connectsToOffBoardNode: e51.nodeIds.some((e52) =\u003e n2.get(e52)?._offBoardConnectionId) }, s2 = n2.get(o4);\n s2 \u0026\u0026 s2.portPoints.push(r3);\n }\n return [{ simpleRouteJson: e50.srjWithPointPairs, inputNodes: t2, capacityMeshNodes: e50.capacityNodes, colorMap: e50.colorMap, numShuffleSeeds: 10 * Math.min(1, e50.effort), hyperParameters: { JUMPER_PF_FN_ENABLED: true, NODE_PF_FACTOR: 100, MAX_RIPS: 100 * Math.min(1, e50.effort), RIPPING_ENABLED: true, MAX_RIPPING_PF_THRESHOLD: 0.9, MIN_RIPPING_PF_THRESHOLD: 0.1, RANDOM_RIP_FRACTION: 0.05, NODE_PF_MAX_PENALTY: 1000, STRAIGHT_LINE_DEVIATION_PENALTY_FACTOR: 0, CENTER_OFFSET_DIST_PENALTY_FACTOR: 0, FORCE_CENTER_FIRST: true } }];\n }, { onSolved: (e50) =\u003e {\n const t2 = e50.portPointPathingSolver;\n t2 \u0026\u0026 y$({ connMap: e50.connMap, connectionsWithResults: t2.connectionsWithResults, inputNodes: t2.inputNodes, obstacles: e50.srj.obstacles });\n } }), AG(\"highDensitySolver\", EG, (e50) =\u003e [{ nodePortPoints: e50.multiSectionPortPointOptimizer?.getNodesWithPortPoints() ?? e50.portPointPathingSolver?.getNodesWithPortPoints() ?? [], colorMap: e50.colorMap, viaDiameter: e50.viaDiameter, traceWidth: e50.minTraceWidth, obstacleMargin: e50.srj.defaultObstacleMargin ?? 0.15, connMap: e50.connMap, capacityMeshNodes: e50.capacityNodes ?? [], capacityMeshEdges: e50.capacityEdges ?? [], availableJumperTypes: e50.srj.availableJumperTypes }]), AG(\"highDensityStitchSolver\", v$, (e50) =\u003e [{ connections: e50.srjWithPointPairs.connections, hdRoutes: e50.highDensitySolver.routes, connectionPathResults: e50.multiSectionPortPointOptimizer?.connectionResults ?? e50.portPointPathingSolver?.connectionsWithResults ?? [], colorMap: e50.colorMap, layerCount: e50.srj.layerCount, defaultViaDiameter: e50.viaDiameter }]), AG(\"traceKeepoutSolver\", l$, (e50) =\u003e [{ hdRoutes: e50.traceSimplificationSolver?.simplifiedHdRoutes ?? e50.highDensityStitchSolver?.mergedHdRoutes ?? [], obstacles: e50.srj.obstacles, jumpers: e50.highDensitySolver?.getOutputJumpers() ?? [], connMap: e50.connMap, colorMap: e50.colorMap, srj: e50.srj }])];\n getConstructorParams() {\n return [this.srj, this.opts];\n }\n currentPipelineStepIndex = 0;\n _step() {\n const e50 = this.pipelineDef[this.currentPipelineStepIndex];\n if (!e50)\n return void (this.solved = true);\n if (this.activeSubSolver)\n return this.activeSubSolver.step(), void (this.activeSubSolver.solved ? (this.endTimeOfPhase[e50.solverName] = performance.now(), this.timeSpentOnPhase[e50.solverName] = this.endTimeOfPhase[e50.solverName] - this.startTimeOfPhase[e50.solverName], e50.onSolved?.(this), this.activeSubSolver = null, this.currentPipelineStepIndex++) : this.activeSubSolver.failed \u0026\u0026 (this.error = this.activeSubSolver?.error, this.failed = true, this.activeSubSolver = null));\n const t2 = e50.getConstructorParams(this);\n this.activeSubSolver = new e50.solverClass(...t2), this[e50.solverName] = this.activeSubSolver, this.timeSpentOnPhase[e50.solverName] = 0, this.startTimeOfPhase[e50.solverName] = performance.now();\n }\n solveUntilPhase(e50) {\n for (;this.getCurrentPhase() !== e50; )\n this.step();\n }\n getCurrentPhase() {\n return this.pipelineDef[this.currentPipelineStepIndex]?.solverName ?? \"none\";\n }\n visualize() {\n if (!this.solved \u0026\u0026 this.activeSubSolver)\n return this.activeSubSolver.visualize();\n const e50 = this.netToPointPairsSolver?.visualize(), t2 = this.nodeSolver?.visualize(), n2 = this.nodeTargetMerger?.visualize(), o3 = this.singleLayerNodeMerger?.visualize(), i3 = this.strawSolver?.visualize(), r3 = this.edgeSolver?.visualize(), s2 = this.traceKeepoutSolver?.visualize(), a3 = this.deadEndSolver?.visualize(), c3 = this.availableSegmentPointSolver?.visualize(), l3 = this.offboardPathFragmentSolver?.visualize(), h2 = this.portPointPathingSolver?.visualize(), d2 = this.multiSectionPortPointOptimizer?.visualize(), u2 = this.highDensityRouteSolver?.visualize(), p3 = this.highDensitySolver?.visualize(), m2 = this.simpleHighDensityRouteSolver?.visualize(), g2 = this.highDensityStitchSolver?.visualize(), f2 = this.traceSimplificationSolver?.visualize(), _2 = this.traceWidthSolver?.visualize(), y2 = this.srj.outline, b2 = [];\n if (b2.push({ points: [{ x: this.srj.bounds?.minX ?? -50, y: this.srj.bounds?.minY ?? -50 }, { x: this.srj.bounds?.maxX ?? 50, y: this.srj.bounds?.minY ?? -50 }, { x: this.srj.bounds?.maxX ?? 50, y: this.srj.bounds?.maxY ?? 50 }, { x: this.srj.bounds?.minX ?? -50, y: this.srj.bounds?.maxY ?? 50 }, { x: this.srj.bounds?.minX ?? -50, y: this.srj.bounds?.minY ?? -50 }], strokeColor: \"rgba(255,0,0,0.25)\" }), y2 \u0026\u0026 y2.length \u003e= 2) {\n const e51 = y2.map((e52) =\u003e ({ x: e52.x, y: e52.y }));\n e51.push({ ...e51[0] }), b2.push({ points: e51, strokeColor: \"rgba(0, 136, 255, 0.95)\" });\n }\n const x2 = Lo(this.srj), v2 = { points: [...this.srj.connections.flatMap((e51) =\u003e e51.pointsToConnect.map((t3) =\u003e ({ ...t3, layer: Bo(t3, this.srj.layerCount), label: `${e51.name} ${t3.pcb_port_id ?? \"\"}` })))], rects: [...(this.srj.obstacles ?? []).filter((e51) =\u003e !e51.isCopperPour).map((e51) =\u003e ({ ...e51, fill: e51.layers?.includes(\"top\") ? \"rgba(255,0,0,0.25)\" : e51.layers?.includes(\"bottom\") ? \"rgba(0,0,255,0.25)\" : \"rgba(255,0,0,0.25)\", layer: jo(e51, this.srj.layerCount), label: x2(e51) }))], lines: b2 }, I2 = [v2, e50, t2, n2, o3, i3, r3, a3, c3, l3, h2, d2, u2 ? pi(v2, u2) : null, p3 ? pi(v2, p3) : null, m2 ? pi(v2, m2) : null, g2, f2, s2, _2, this.solved ? pi({ lines: b2 }, Wo(this.getOutputSimpleRouteJson())) : null].filter(Boolean);\n return pi(...I2);\n }\n preview() {\n const e50 = this.highDensitySolver?.routes ?? this.simpleHighDensityRouteSolver?.routes ?? this.highDensityRouteSolver?.routes;\n if (e50) {\n const t2 = [];\n for (let n2 = e50.length - 1;n2 \u003e= 0; n2--) {\n const o3 = e50[n2];\n if (t2.push({ points: o3.route.map((e51) =\u003e ({ x: e51.x, y: e51.y })), strokeColor: this.colorMap[o3.connectionName] }), t2.length \u003e 200)\n break;\n }\n return { lines: t2 };\n }\n if (this.portPointPathingSolver) {\n const e51 = [];\n for (const t2 of this.portPointPathingSolver.connectionsWithResults)\n t2.path \u0026\u0026 e51.push({ points: t2.path.map((e52) =\u003e ({ x: e52.point.x, y: e52.point.y })), strokeColor: this.colorMap[t2.connection.name] });\n return { lines: e51 };\n }\n return this.netToPointPairsSolver ? this.netToPointPairsSolver?.visualize() : {};\n }\n _getOutputHdRoutes() {\n return this.traceWidthSolver?.hdRoutesWithWidths ?? this.traceKeepoutSolver?.redrawnHdRoutes ?? this.traceSimplificationSolver?.simplifiedHdRoutes ?? this.highDensityStitchSolver?.mergedHdRoutes ?? this.highDensitySolver?.routes ?? this.simpleHighDensityRouteSolver?.routes ?? this.highDensityRouteSolver?.routes;\n }\n getConnectedOffboardObstacles() {\n const e50 = {}, t2 = new Set(this.srj.connections.flatMap((e51) =\u003e e51.__rootConnectionNames ?? [e51.name]));\n for (const [n2, o3] of this.srj.obstacles.entries()) {\n if (!o3.offBoardConnectsTo?.length)\n continue;\n const i3 = o3.obstacleId ?? `__obs${n2}`;\n o3.obstacleId = i3;\n const r3 = this.connMap.getNetConnectedToId(i3);\n if (!r3)\n continue;\n const s2 = this.connMap.getIdsConnectedToNet(r3).find((e51) =\u003e t2.has(e51));\n s2 \u0026\u0026 (e50[i3] = s2);\n }\n return e50;\n }\n getOutputSimplifiedPcbTraces() {\n if (!this.solved || !this.highDensityRouteSolver \u0026\u0026 !this.simpleHighDensityRouteSolver \u0026\u0026 !this.highDensitySolver)\n throw new Error(\"Cannot get output before solving is complete\");\n const e50 = [], t2 = this._getOutputHdRoutes();\n for (const n2 of this.netToPointPairsSolver?.newConnections ?? []) {\n const o3 = n2.__netConnectionName ?? this.srj.connections.find((e51) =\u003e e51.name === n2.name)?.__netConnectionName, i3 = t2.filter((e51) =\u003e e51.connectionName === n2.name);\n for (let t3 = 0;t3 \u003c i3.length; t3++) {\n const r3 = i3[t3], s2 = { type: \"pcb_trace\", pcb_trace_id: `${n2.name}_${t3}`, connection_name: o3 ?? n2.__rootConnectionNames?.[0] ?? n2.name, route: Ro(r3, this.srj.layerCount) };\n e50.push(s2);\n }\n }\n return e50;\n }\n getOutputJumpers() {\n return this.highDensitySolver ? this.highDensitySolver.getOutputJumpers() : [];\n }\n getOutputSimpleRouteJson() {\n const e50 = this.getOutputJumpers();\n return { ...this.srj, traces: this.getOutputSimplifiedPcbTraces(), jumpers: e50.length \u003e 0 ? e50 : undefined };\n }\n};\nvar DG = (e50) =\u003e {\n const { candidates: t2, mapOfCapacityMeshNodeIdToRef: n2 } = e50;\n let o3 = true;\n for (const e51 of t2) {\n let t3 = false;\n e51.port.nodeIds.forEach((e52) =\u003e {\n const o4 = n2.get(e52);\n if (!o4)\n throw new Error(`Could not find capacity mesh node for id ${e52}`);\n o4._containsObstacle \u0026\u0026 (t3 = true);\n }), t3 || (o3 = false);\n }\n return o3;\n};\nvar LG = (e50) =\u003e e50.depth + 1000 * e50.countOfCrampedPortPointsInPath;\nvar BG = class extends BaseSolver {\n constructor(e50) {\n if (super(), this.input = e50, this.input.depthLimit \u003c 1)\n throw new Error(\"Depth limit must be at least 1\");\n this._setup();\n }\n queue = [];\n resultExploredPortPoints = [];\n currentExploredPortPoints = null;\n visitedExploredPortPoints = new Map;\n getSolverName() {\n return \"singleTargetNecessaryCrampedPortPointSolver\";\n }\n _setup() {\n const e50 = this.input.mapOfCapacityMeshNodeIdToSegmentPortPoints.get(this.input.target.capacityMeshNodeId) ?? [];\n for (const t2 of e50) {\n if (this.input.shouldIgnoreCrampedPortPoints \u0026\u0026 t2.cramped)\n continue;\n const e51 = { port: t2, depth: 1, parent: null, countOfCrampedPortPointsInPath: t2.cramped ? 1 : 0 }, n2 = this.visitedExploredPortPoints.get(t2);\n (!n2 || this.getCandidateCost(e51) \u003c this.getCandidateCost(n2)) \u0026\u0026 (this.visitedExploredPortPoints.set(t2, e51), this.queue.push(e51));\n }\n }\n _step() {\n if (this.queue.length === 0)\n return this.currentExploredPortPoints = null, void (this.solved = true);\n for (;this.queue.length \u003e 0; ) {\n this.currentExploredPortPoints = this.queue.shift();\n if (this.visitedExploredPortPoints.get(this.currentExploredPortPoints.port) !== this.currentExploredPortPoints)\n continue;\n if (this.currentExploredPortPoints.depth === this.input.depthLimit) {\n this.resultExploredPortPoints.push(this.currentExploredPortPoints);\n continue;\n }\n const e50 = this.currentExploredPortPoints.port.nodeIds.map((e51) =\u003e {\n const t2 = this.input.mapOfCapacityMeshNodeIdToRef.get(e51);\n if (!t2)\n throw new Error(`Could not find capacity mesh node for id ${e51}`);\n return t2;\n }).flatMap((e51) =\u003e this.input.mapOfCapacityMeshNodeIdToSegmentPortPoints.get(e51.capacityMeshNodeId) ?? []);\n for (const t2 of e50) {\n if (this.input.shouldIgnoreCrampedPortPoints \u0026\u0026 t2.cramped)\n continue;\n const e51 = { port: t2, depth: this.currentExploredPortPoints.depth + 1, parent: this.currentExploredPortPoints, countOfCrampedPortPointsInPath: this.currentExploredPortPoints.countOfCrampedPortPointsInPath + (t2.cramped ? 1 : 0) }, n2 = this.visitedExploredPortPoints.get(t2);\n n2 \u0026\u0026 this.getCandidateCost(n2) \u003c= this.getCandidateCost(e51) || (this.visitedExploredPortPoints.set(t2, e51), this.queue.push(e51));\n }\n }\n this.solved = true;\n }\n getCandidateCost(e50) {\n return e50.depth + 1000 * e50.countOfCrampedPortPointsInPath;\n }\n getOutput() {\n return this.resultExploredPortPoints;\n }\n visualize() {\n const e50 = { points: [], rects: [] };\n for (const t2 of this.visitedExploredPortPoints.keys())\n e50.points.push({ ...t2, color: t2.cramped ? \"blue\" : \"green\" });\n return e50;\n }\n};\nvar FG = class extends BaseSolver {\n constructor(e50) {\n super(), this.input = e50, this._setup();\n }\n unprocessedTargets = [];\n targetNode = [];\n currentTarget;\n crampedPortPointsToKeep = new Set;\n candidatesAtDepth = [];\n isRunningCrampedPass = false;\n filteredOutput;\n activeSubSolver = null;\n nodeMap = new Map;\n mapOfCapacityMeshNodeIdToSegmentPortPoints = new Map;\n getSolverName() {\n return \"multiTargetNecessaryCrampedPortPointSolver\";\n }\n _setup() {\n this.targetNode = this.input.capacityMeshNodes.filter((e50) =\u003e e50._containsObstacle), this.targetNode = this.targetNode.filter((e50) =\u003e {\n for (const t2 of this.input.simpleRouteJson.connections)\n for (const n2 of t2.pointsToConnect)\n if (Oe(n2, e50) \u003c= 0)\n return true;\n return false;\n }), this.unprocessedTargets = [...this.targetNode], this.unprocessedTargets.sort((e50, t2) =\u003e e50.center.x - t2.center.x);\n for (const e50 of this.input.capacityMeshNodes)\n this.nodeMap.set(e50.capacityMeshNodeId, e50);\n for (const e50 of this.input.sharedEdgeSegments)\n for (const t2 of e50.portPoints) {\n const e51 = t2.nodeIds;\n for (const n2 of e51) {\n if (!this.nodeMap.get(n2))\n throw new Error(`Could not find capacity mesh node for id ${n2}`);\n const e52 = this.mapOfCapacityMeshNodeIdToSegmentPortPoints.get(n2) || [];\n this.mapOfCapacityMeshNodeIdToSegmentPortPoints.set(n2, [...e52, t2]);\n }\n }\n }\n _step() {\n if (this.activeSubSolver) {\n if (this.activeSubSolver._step(), !this.activeSubSolver.solved)\n return;\n if (this.activeSubSolver.failed)\n return this.failed = true, void (this.error = this.activeSubSolver.error);\n if (this.candidatesAtDepth = this.activeSubSolver.getOutput(), this.activeSubSolver = null, !this.currentTarget)\n return this.failed = true, void (this.error = \"Missing current capacity mesh node while finishing BFS\");\n if (!this.isRunningCrampedPass) {\n return DG({ candidates: this.candidatesAtDepth, mapOfCapacityMeshNodeIdToRef: this.nodeMap }) || this.candidatesAtDepth.length === 0 ? (this.isRunningCrampedPass = true, void (this.activeSubSolver = new BG({ target: this.currentTarget, depthLimit: 3, shouldIgnoreCrampedPortPoints: false, mapOfCapacityMeshNodeIdToSegmentPortPoints: this.mapOfCapacityMeshNodeIdToSegmentPortPoints, mapOfCapacityMeshNodeIdToRef: this.nodeMap }))) : void (this.currentTarget = undefined);\n }\n let e50 = this.candidatesAtDepth.filter((e51) =\u003e {\n const t2 = e51.port;\n return t2.nodeIds.map((e52) =\u003e {\n const t3 = this.nodeMap.get(e52);\n if (!t3)\n throw this.failed = true, this.error = `Could not find capacity mesh node for id ${e52}`, new Error(`Could not find capacity mesh node for id ${e52}`);\n return t3;\n }).every((e52) =\u003e !e52._containsObstacle) \u0026\u0026 t2.cramped;\n });\n if (DG({ candidates: e50, mapOfCapacityMeshNodeIdToRef: this.nodeMap }) \u0026\u0026 (this.error = `All candidates are blocked by obstacles even after including cramped port points for capacity mesh node ${this.currentTarget.capacityMeshNodeId}`), this.candidatesAtDepth = [...e50].sort((e51, t2) =\u003e {\n const n2 = LG(e51) - LG(t2);\n return n2 !== 0 ? n2 : this.getCandidateExitCapacity(t2) - this.getCandidateExitCapacity(e51);\n }), this.candidatesAtDepth.length === 0)\n this.error = `No candidates found for capacity mesh node ${this.currentTarget.capacityMeshNodeId} even after including cramped port points`;\n else {\n const e51 = new Map;\n for (const t3 of this.candidatesAtDepth) {\n if (!t3.parent)\n throw new Error(`Missing parent for cramped escape candidate ${t3.port.segmentPortPointId}`);\n const n2 = `${t3.parent.port.segmentPortPointId}-\u003e${t3.port.segmentPortPointId}`;\n if (!e51.has(n2) \u0026\u0026 (e51.set(n2, t3), e51.size === 5))\n break;\n }\n const t2 = [...e51.values()];\n for (const e52 of t2)\n this.keepCandidatePath(e52);\n }\n return this.isRunningCrampedPass = false, void (this.currentTarget = undefined);\n }\n if (!this.currentTarget)\n return this.currentTarget = this.unprocessedTargets.shift(), this.currentTarget ? (this.isRunningCrampedPass = false, this.candidatesAtDepth = [], void (this.activeSubSolver = new BG({ target: this.currentTarget, depthLimit: 2, shouldIgnoreCrampedPortPoints: true, mapOfCapacityMeshNodeIdToSegmentPortPoints: this.mapOfCapacityMeshNodeIdToSegmentPortPoints, mapOfCapacityMeshNodeIdToRef: this.nodeMap }))) : void (this.solved = true);\n }\n getOutput() {\n return this.filteredOutput || (this.filteredOutput = this.input.sharedEdgeSegments.map((e50) =\u003e ({ ...e50, portPoints: e50.portPoints.flatMap((e51) =\u003e !e51.cramped || this.crampedPortPointsToKeep.has(e51) ? [e51] : this.isMultilayerEscapePort(e51) ? [{ ...e51, tinyHypergraphPortPenalty: 1000 }] : []) }))), this.filteredOutput;\n }\n getCandidateExitCapacity(e50) {\n if (!e50.parent)\n throw new Error(`Missing parent for cramped escape candidate ${e50.port.segmentPortPointId}`);\n const t2 = new Set(e50.parent.port.nodeIds), n2 = e50.port.nodeIds.filter((e51) =\u003e !t2.has(e51)).map((e51) =\u003e {\n const t3 = this.nodeMap.get(e51);\n if (!t3)\n throw new Error(`Could not find capacity mesh node for id ${e51}`);\n return t3;\n });\n if (n2.length === 0)\n throw new Error(`Could not find exit node for cramped escape candidate ${e50.port.segmentPortPointId}`);\n return Math.max(0, ...n2.map((e51) =\u003e e51.width * e51.height * e51.availableZ.length));\n }\n keepCandidatePath(e50) {\n this.crampedPortPointsToKeep.add(e50.port);\n let t2 = e50.parent;\n for (;t2; )\n this.crampedPortPointsToKeep.add(t2.port), t2 = t2.parent;\n }\n isMultilayerEscapePort(e50) {\n return e50.nodeIds.some((e51) =\u003e (this.nodeMap.get(e51)?.availableZ.length ?? 0) \u003e 1);\n }\n visualize() {\n const e50 = { rects: [], points: [] };\n for (const t2 of this.targetNode)\n e50.rects.push({ ...t2, fill: this.currentTarget?.capacityMeshNodeId === t2.capacityMeshNodeId ? \"rgba(255, 0, 0, 0.5)\" : \"rgba(255, 0, 0, 0.2)\" });\n for (const t2 of this.candidatesAtDepth)\n e50.points.push({ ...t2.port, color: t2.port.cramped ? \"blue\" : \"green\" });\n for (const t2 of this.crampedPortPointsToKeep)\n e50.points.push({ ...t2, color: \"blue\" });\n return this.activeSubSolver ? Gn(e50, this.activeSubSolver.visualize()) : e50;\n }\n};\nvar jG = (e50) =\u003e `${e50.x.toFixed(4)},${e50.y.toFixed(4)}`;\nvar $G = (e50) =\u003e e50.netIsAssignable === true \u0026\u0026 (e50.layers?.length ?? 0) \u003e 1;\nvar YG = (e50, t2) =\u003e e50.connectedTo?.find((e51) =\u003e e51.startsWith(\"pcb_via\")) ?? e50.obstacleId ?? `assignable_via_${t2}`;\nvar XG = (e50) =\u003e [...new Set(e50.obstacle.layers.map((t2) =\u003e mo(t2, e50.layerCount)))].sort((e51, t2) =\u003e e51 - t2);\nvar HG = (e50) =\u003e jG(e50.center);\nvar VG = (e50) =\u003e new Set(e50.filter($G).map(HG));\nfunction WG(e50, t2) {\n if (e50 == null)\n throw new Error(t2);\n}\nfunction GG({ point: e50, layerCount: t2 }) {\n const n2 = So(e50).map((e51) =\u003e mo(e51, t2));\n return [...new Set(n2)];\n}\nfunction UG(e50) {\n if (Oe(e50.point, e50.region.d) \u003c= 0.001) {\n return (e50.pointZLayers ?? GG(e50)).some((t2) =\u003e e50.region.d.availableZ.includes(t2));\n }\n return false;\n}\nfunction ZG({ region: e50, pointZLayers: t2 }) {\n return e50.ports.some((e51) =\u003e t2.includes(e51.d.z) \u0026\u0026 t2.some((t3) =\u003e e51.region1.d.availableZ.includes(t3)) \u0026\u0026 t2.some((t3) =\u003e e51.region2.d.availableZ.includes(t3)));\n}\nfunction qG({ graph: e50, point: t2, layerCount: n2 }) {\n const o3 = GG({ point: t2, layerCount: n2 });\n let i3;\n for (const r3 of e50.regions)\n if (UG({ point: t2, region: r3, layerCount: n2, pointZLayers: o3 }) \u0026\u0026 (i3 ??= r3, ZG({ region: r3, pointZLayers: o3 })))\n return r3;\n return i3;\n}\nvar JG = (e50, t2) =\u003e {\n const n2 = e50.getNetConnectedToId(t2);\n if (!n2)\n throw new Error(`Could not resolve net ID for connection \"${t2}\"`);\n return n2;\n};\nvar QG = (e50) =\u003e {\n const t2 = e50.graph.regions.filter((t3) =\u003e t3.d.availableZ.includes(e50.z) \u0026\u0026 !t3.d._assignableVia).map((t3) =\u003e ({ region: t3, distance: Oe(e50.point, t3.d) })).sort((e51, t3) =\u003e e51.distance - t3.distance || e51.region.d.width * e51.region.d.height - t3.region.d.width * t3.region.d.height), n2 = t2[0]?.distance;\n if (n2 === undefined)\n return [];\n const o3 = Math.max(n2 + 0.000001, e50.viaRadius + 0.15);\n return t2.filter((e51) =\u003e e51.distance \u003c= o3).slice(0, 4).map((e51) =\u003e e51.region);\n};\nfunction KG(e50) {\n const t2 = { ports: [], regions: [] }, n2 = [], o3 = new Map;\n for (const n3 of e50.capacityMeshNodes) {\n const i3 = n3._connectedTo?.map((t3) =\u003e JG(e50.connectivityMap, t3)), r3 = { regionId: n3.capacityMeshNodeId, d: i3 ? { ...n3, _connectedTo: [...new Set(i3)] } : n3, ports: [] };\n t2.regions.push(r3), o3.has(r3.regionId) || o3.set(r3.regionId, r3);\n }\n for (const n3 of e50.segmentPortPoints) {\n const [e51, i3] = n3.nodeIds, r3 = o3.get(e51), s2 = o3.get(i3);\n WG(r3, `Could not find region with id ${e51} for segment port point ${n3.segmentPortPointId}`), WG(s2, `Could not find region with id ${i3} for segment port point ${n3.segmentPortPointId}`);\n for (const e52 of n3.availableZ) {\n const o4 = n3._preloadedTracePortAssignments?.filter((t3) =\u003e t3.z === e52), i4 = { portId: `${n3.segmentPortPointId}::${e52}`, x: n3.x, y: n3.y, z: e52, distToCentermostPortOnZ: n3.distToCentermostPortOnZ, cramped: n3.cramped, regions: [r3, s2], tinyHypergraphPortPenalty: n3.tinyHypergraphPortPenalty, _preloadedFixedNetIds: o4 \u0026\u0026 o4.length \u003e 0 ? [...new Set(o4.map((e53) =\u003e e53.fixedNetId))].sort() : undefined, _preloadedTracePortAssignments: o4 }, a3 = { portId: n3.segmentPortPointId, d: i4, region1: r3, region2: s2 };\n t2.ports.push(a3), r3.ports.push(a3), s2.ports.push(a3);\n }\n }\n ((e51) =\u003e {\n for (const [t3, n3] of e51.assignableViaObstacles.entries()) {\n if (!$G(n3))\n continue;\n const o4 = XG({ obstacle: n3, layerCount: e51.layerCount });\n if (o4.length \u003c 2)\n continue;\n const i3 = `assignable-via:${YG(n3, t3)}`, r3 = Math.min(n3.width, n3.height) / 2, s2 = { regionId: i3, d: { capacityMeshNodeId: i3, center: { ...n3.center }, width: n3.width, height: n3.height, layer: `z${o4.join(\",\")}`, availableZ: o4, _containsObstacle: false, _completelyInsideObstacle: false, _containsTarget: false, _assignableVia: true, _assignedViaObstacle: n3 }, ports: [] }, a3 = [];\n for (const t4 of o4)\n for (const o5 of QG({ graph: e51.graph, point: n3.center, z: t4, viaRadius: r3 })) {\n const e52 = { portId: `${i3}:port:${o5.regionId}:z${t4}`, x: n3.center.x, y: n3.center.y, z: t4, distToCentermostPortOnZ: 0, cramped: false, regions: [o5, s2] }, r4 = { portId: e52.portId, d: e52, region1: o5, region2: s2 };\n a3.push(r4), o5.ports.push(r4);\n }\n if (new Set(a3.map((e52) =\u003e e52.d.z)).size \u003c 2)\n for (const e52 of a3)\n e52.region1.ports = e52.region1.ports.filter((t4) =\u003e t4 !== e52);\n else\n s2.ports.push(...a3), e51.graph.regions.push(s2), e51.graph.ports.push(...a3);\n }\n })({ graph: t2, assignableViaObstacles: e50.assignableViaObstacles ?? [], layerCount: e50.layerCount });\n for (const o4 of e50.simpleRouteJsonConnections) {\n const [i3, r3] = o4.pointsToConnect, s2 = qG({ graph: t2, point: i3, layerCount: e50.layerCount }), a3 = qG({ graph: t2, point: r3, layerCount: e50.layerCount });\n WG(s2, `Could not find start region for connection \"${o4.name}\"`), WG(a3, `Could not find end region for connection \"${o4.name}\"`), n2.push({ connectionId: o4.name, mutuallyConnectedNetworkId: JG(e50.connectivityMap, o4.name), startRegion: s2, endRegion: a3, simpleRouteConnection: o4 });\n }\n return { graph: t2, connections: n2 };\n}\nfunction eU(e50, t2) {\n const n2 = { lines: [], points: [] };\n if (!e50)\n return n2;\n let o3 = e50.shift();\n if (!o3)\n return n2;\n const i3 = [];\n n2.points.push({ ...o3.port.d, color: \"rgb(255, 50, 50)\", label: `g: ${o3.g}\nh: ${o3.h}\nf: ${o3.f}\nripRequired: ${o3.ripRequired}` });\n do {\n i3.push({ x: o3.port.d.x, y: o3.port.d.y, z: o3.port.d.z }), o3 = o3.parent;\n } while (o3);\n i3.reverse();\n const r3 = i3[0]?.z ?? 0;\n i3.unshift({ x: t2.x, y: t2.y, z: r3 });\n for (let e51 = 0;e51 \u003c i3.length - 1; e51++) {\n const t3 = i3[e51], o4 = i3[e51 + 1];\n let r4;\n r4 = t3.z === o4.z ? t3.z === 0 ? undefined : \"10 5\" : \"3 3 10\", n2.lines.push({ points: [{ x: t3.x, y: t3.y }, { x: o4.x, y: o4.y }], strokeColor: \"rgba(255, 250, 50, 1)\", strokeWidth: 0.01, strokeDash: r4 });\n }\n for (const t3 of e50)\n n2.points.push({ ...t3.port.d, color: \"rgb(0, 64, 255)\", label: `${t3.port.portId}\ng: ${t3.g}\nh: ${t3.h}\nf: ${t3.f}\nripRequired: ${t3.ripRequired}` });\n return n2;\n}\nfunction tU(e50, t2) {\n const n2 = { lines: [], points: [] };\n for (const o3 of e50) {\n const e51 = t2[o3.connection.connectionId] ?? \"rgba(255, 50, 50, 1)\", i3 = [{ x: o3.connection.startRegion.d.center.x, y: o3.connection.startRegion.d.center.y, z: o3.connection.startRegion.d?.availableZ?.[0] ?? 0 }];\n for (const e52 of o3.path)\n i3.push({ x: e52.port.d.x, y: e52.port.d.y, z: e52.port.d.z });\n i3.push({ x: o3.connection.endRegion.d.center.x, y: o3.connection.endRegion.d.center.y, z: o3.connection.endRegion.d?.availableZ?.[0] ?? 0 });\n for (let t3 = 0;t3 \u003c i3.length - 1; t3++) {\n const o4 = i3[t3], r3 = i3[t3 + 1];\n let s2;\n s2 = o4.z === r3.z ? o4.z === 0 ? undefined : \"10 5\" : \"3 3 10\";\n const a3 = { points: [{ x: o4.x, y: o4.y }, { x: r3.x, y: r3.y }], strokeColor: e51, strokeWidth: 0.01, strokeDash: s2 };\n n2.lines.push(a3);\n }\n }\n return n2;\n}\nfunction nU(e50, t2) {\n const n2 = { lines: [], points: [] };\n for (const o3 of e50) {\n const e51 = o3.startRegion.d.center, i3 = o3.endRegion.d.center, r3 = (e51.x + i3.x) / 2, s2 = (e51.y + i3.y) / 2, a3 = t2[o3.connectionId] ?? \"rgba(255, 50, 150, 0.8)\";\n n2.points.push({ x: r3, y: s2, color: a3, label: o3.connectionId }), n2.lines.push({ points: [e51, i3], strokeColor: a3, strokeWidth: 0.1, strokeDash: (o3.startRegion.d?.availableZ?.[0] ?? 0) === 0 ? undefined : \"10 5\" });\n }\n return n2;\n}\nfunction oU(e50) {\n const t2 = { rects: [], points: [] };\n for (const n2 of e50.regions)\n t2.rects.push({ center: n2.d.center, width: n2.d.width, height: n2.d.height, fill: \"rgba(200, 200, 200, 0.5)\", label: n2.regionId });\n for (const n2 of e50.ports)\n t2.points.push({ x: n2.d.x, y: n2.d.y, color: \"rgba(4, 90, 20, 0.3)\", label: n2.portId });\n return t2;\n}\nvar iU = class extends OY {\n constructor(e50) {\n super({ inputConnections: e50.connections, inputGraph: e50.graph, inputSolvedRoutes: e50.inputSolvedRoutes, greedyMultiplier: e50.weights.GREEDY_MULTIPLIER, ripCost: e50.weights.RIPPING_PF_COST, rippingEnabled: e50.flags.RIPPING_ENABLED }), this.params = e50, this.regionMemoryPfMap = e50.opts?.regionMemoryPfMap ?? new Map, this.baseRegionFailureCostMap = new Map, this.regionRipCountMap = new Map, this.totalRipCount = 0, e50.weights.MAX_ITERATIONS_PER_PATH \u003e 0 \u0026\u0026 (this.MAX_ITERATIONS = e50.weights.MAX_ITERATIONS_PER_PATH * e50.effort);\n }\n regionMemoryPfMap;\n baseRegionFailureCostMap;\n regionRipCountMap;\n totalRipCount;\n estimateCostToEnd(e50) {\n const t2 = this.currentEndRegion;\n return WG(t2, \"Current end region is undefined\"), me(e50.d, t2.d.center);\n }\n computeH(e50) {\n const t2 = e50, n2 = this.computeDistanceTraveled(t2);\n if (this.params.weights.RANDOM_WALK_DISTANCE \u003e 0 \u0026\u0026 n2 \u003c this.params.weights.RANDOM_WALK_DISTANCE)\n return 0;\n const o3 = this.estimateCostToEnd(e50.port), i3 = (e50.port.d.distToCentermostPortOnZ - this.params.weights.CENTER_OFFSET_FOCUS_SHIFT) * this.params.weights.CENTER_OFFSET_DIST_PENALTY_FACTOR, r3 = e50.nextRegion?.regionId ?? e50.lastRegion?.regionId, s2 = r3 ? this.regionMemoryPfMap.get(r3) ?? 0 : 0;\n return o3 + i3 + this.computeMemoryPfPenalty(s2) + this.computeDeviation(e50) * this.params.weights.STRAIGHT_LINE_DEVIATION_PENALTY_FACTOR;\n }\n computeIncreasedRegionCostIfPortsAreUsed(e50, t2, n2) {\n const o3 = this.currentConnection;\n WG(o3, \"Current connection is undefined\");\n const i3 = this.getBaseRegionFailureCost(e50), r3 = this.computeRegionPfWithAdditionalSegment(e50, t2, n2, o3.connectionId, o3.mutuallyConnectedNetworkId);\n if (r3 \u003e= this.NODE_MAX_PF)\n return this.params.weights.NODE_PF_MAX_PENALTY;\n const s2 = this.pfToFailureCost(r3), a3 = Math.max(0, s2 - i3);\n return Math.min(this.params.weights.NODE_PF_MAX_PENALTY, a3 * this.params.weights.NODE_PF_FACTOR);\n }\n computeG(e50) {\n const t2 = e50;\n let n2 = super.computeG(e50);\n return t2.lastPort \u0026\u0026 t2.lastPort.d.z !== t2.port.d.z \u0026\u0026 (n2 += this.params.weights.LAYER_CHANGE_COST), t2.nextRegion !== this.currentEndRegion ? n2 : n2 + this.computeEndRegionCloseCost(t2);\n }\n getPortUsagePenalty(e50) {\n const t2 = e50.assignment;\n if (!t2)\n return 0;\n const n2 = this.currentConnection?.mutuallyConnectedNetworkId;\n return t2.connection.mutuallyConnectedNetworkId === n2 ? 0 : 0.5 * Math.max(1, this.params.weights.NODE_PF_FACTOR) + this.params.weights.BASE_CANDIDATE_COST;\n }\n getRipsRequiredForPortUsage(e50, t2, n2) {\n const o3 = e50.assignments ?? [];\n if (o3.length === 0)\n return [];\n return o3.filter((e51) =\u003e e51.connection.mutuallyConnectedNetworkId !== this.currentConnection?.mutuallyConnectedNetworkId \u0026\u0026 (e51.regionPort1 !== t2 \u0026\u0026 e51.regionPort2 !== t2 \u0026\u0026 (e51.regionPort1 !== n2 \u0026\u0026 e51.regionPort2 !== n2 \u0026\u0026 he(e51.regionPort1.d, e51.regionPort2.d, t2.d, n2.d))));\n }\n selectCandidatesForEnteringRegion(e50) {\n const t2 = this.currentConnection?.startRegion, n2 = this.currentConnection?.endRegion;\n WG(t2, \"Current connection or start region is undefined\"), WG(n2, \"Current connection or end region is undefined\");\n const o3 = e50.filter((e51) =\u003e {\n const o4 = e51.nextRegion;\n return !o4?.d._containsObstacle || (o4 === t2 || o4 === n2);\n });\n let i3 = this.params.flags.FORCE_CENTER_FIRST ? this.getCenterFirstEnteringRegionCandidates(o3) : o3;\n const r3 = -this.params.weights.MIN_ALLOWED_BOARD_SCORE;\n if (r3 \u003e 0) {\n const e51 = i3.filter((e52) =\u003e e52.g + e52.h \u003c= r3);\n e51.length \u003e 0 \u0026\u0026 (i3 = e51);\n }\n return i3;\n }\n routeSolvedHook(e50) {\n this.baseRegionFailureCostMap.clear();\n const t2 = new Set;\n for (const n3 of e50.path) {\n const e51 = n3.lastRegion;\n e51 \u0026\u0026 t2.add(e51);\n }\n for (const e51 of t2) {\n const t3 = this.computeRegionPfFromAssignments(e51);\n this.regionMemoryPfMap.set(e51.regionId, t3);\n }\n if (!e50.requiredRip)\n return;\n if (this.unprocessedConnections.length \u003c 2)\n return;\n const [n2, ...o3] = this.unprocessedConnections;\n this.unprocessedConnections = [...o3, n2];\n }\n computeRoutesToRip(e50) {\n const t2 = super.computePortOverlapRoutes(e50), n2 = new Set(t2), o3 = new Map;\n e50.path.map((e51) =\u003e {\n if (!e51.lastPort || !e51.lastRegion)\n return;\n const t3 = this.getRipsRequiredForPortUsage(e51.lastRegion, e51.lastPort, e51.port);\n if (t3.length === 0)\n return null;\n const n3 = o3.get(e51.lastRegion) ?? new Set;\n for (const e52 of t3)\n n3.add(e52.solvedRoute);\n o3.set(e51.lastRegion, n3);\n });\n const i3 = e50.path.flatMap((e51) =\u003e e51.lastRegion ? [e51.lastRegion] : []), r3 = Array.from(new Set([...o3.keys(), ...i3])), s2 = this.params.weights.SHUFFLE_SEED + this.iterations + this.solvedRoutes.length + this.totalRipCount, a3 = Sr(r3, s2);\n for (const t3 of a3) {\n if (this.totalRipCount \u003e= this.params.weights.MAX_RIPS)\n break;\n const o4 = this.getRegionRippingPfThreshold(t3.regionId);\n let i4 = this.computeRegionPf({ region: t3, newlySolvedRoute: e50, routesToRip: n2 });\n if (this.regionMemoryPfMap.set(t3.regionId, i4), i4 \u003c= o4)\n continue;\n const r4 = new Set;\n let a4 = 0;\n for (;i4 \u003e o4 \u0026\u0026 !(this.totalRipCount \u003e= this.params.weights.MAX_RIPS); ) {\n if (!t3.assignments || t3.assignments.length === 0)\n throw new Error(\"We are trying to rip a region with no assignments, this should not happen\");\n const o5 = t3.assignments.map((t4) =\u003e {\n const o6 = t4.solvedRoute;\n return t4.connection.connectionId === e50.connection.connectionId ? null : n2.has(o6) ? undefined : o6;\n }).filter((e51) =\u003e !!e51);\n if (o5.length === 0)\n break;\n const c3 = Sr(o5, s2 + a4 + r4.size)[0];\n if (!c3)\n break;\n r4.add(c3.connection), n2.add(c3), this.totalRipCount++, a4++, this.regionRipCountMap.set(t3.regionId, (this.regionRipCountMap.get(t3.regionId) ?? 0) + 1), i4 = this.computeRegionPf({ region: t3, newlySolvedRoute: e50, routesToRip: n2 }), this.regionMemoryPfMap.set(t3.regionId, i4);\n }\n }\n if (n2.size \u003e t2.size) {\n if (this.totalRipCount \u003e= this.params.weights.MAX_RIPS)\n return n2;\n const t3 = this.solvedRoutes.filter((t4) =\u003e !n2.has(t4) \u0026\u0026 t4.connection.connectionId !== e50.connection.connectionId);\n if (t3.length === 0)\n return n2;\n const o4 = Math.max(1, Math.floor(this.params.weights.RANDOM_RIP_FRACTION * t3.length)), i4 = Sr(t3, s2);\n let r4 = 0;\n for (const e51 of i4) {\n if (r4 \u003e= o4)\n break;\n if (this.totalRipCount \u003e= this.params.weights.MAX_RIPS)\n break;\n n2.has(e51) || (n2.add(e51), r4++, this.totalRipCount++);\n }\n }\n return n2;\n }\n computeDeviation(e50) {\n const t2 = this.currentConnection?.startRegion.d.center, n2 = this.currentConnection?.endRegion.d.center;\n WG(t2, \"Current connection or start region is undefined\"), WG(n2, \"Current connection or end region is undefined\");\n return pe(e50.port.d, t2, n2);\n }\n computeDistanceTraveled(e50) {\n let t2 = 0, n2 = e50;\n for (;n2?.parent; )\n t2 += me(n2.parent.port.d, n2.port.d), n2 = n2.parent;\n return t2;\n }\n computeMemoryPfPenalty(e50) {\n const t2 = Math.min(Math.max(e50, 0), 0.999999), n2 = Math.min(this.params.weights.NODE_PF_MAX_PENALTY, -Math.log(1 - t2));\n return n2 * this.params.weights.MEMORY_PF_FACTOR + n2 * this.params.weights.NODE_PF_FACTOR * 0.01;\n }\n computeEndRegionCloseCost(e50) {\n const t2 = this.currentConnection, n2 = this.currentEndRegion;\n WG(t2, \"Current connection is undefined\"), WG(n2, \"Current end region is undefined\");\n const o3 = t2.endRegion.d.center, i3 = { portId: `end-target:${t2.connectionId}`, region1: n2, region2: n2, d: { portId: `end-target:${t2.connectionId}`, x: o3.x, y: o3.y, z: e50.port.d.z, distToCentermostPortOnZ: 0, regions: [n2, n2] } };\n return this.computeIncreasedRegionCostIfPortsAreUsed(n2, e50.port, i3);\n }\n getCenterFirstEnteringRegionCandidates(e50) {\n const t2 = new Map;\n for (const n3 of e50) {\n const e51 = n3.port.d.z, o3 = t2.get(e51) ?? [];\n o3.push(n3), t2.set(e51, o3);\n }\n const n2 = [];\n for (const e51 of t2.values()) {\n const t3 = e51.sort((e52, t4) =\u003e e52.port.d.distToCentermostPortOnZ - t4.port.d.distToCentermostPortOnZ)[0];\n if (!t3)\n continue;\n if (this.isPortAvailableForCurrentNet(t3.port)) {\n n2.push(t3);\n continue;\n }\n const o3 = e51.sort((e52, t4) =\u003e e52.port.d.x !== t4.port.d.x ? e52.port.d.x - t4.port.d.x : e52.port.d.y - t4.port.d.y), i3 = [];\n let r3 = [];\n for (const e52 of o3)\n this.isPortAvailableForCurrentNet(e52.port) ? r3.push(e52) : r3.length \u003e 0 \u0026\u0026 (i3.push(r3), r3 = []);\n r3.length \u003e 0 \u0026\u0026 i3.push(r3);\n for (const e52 of i3)\n n2.push(e52[Math.floor(e52.length / 2)]);\n }\n return n2;\n }\n isPortAvailableForCurrentNet(e50) {\n const t2 = e50.assignment;\n if (!t2)\n return true;\n const n2 = this.currentConnection?.mutuallyConnectedNetworkId;\n return t2.connection.mutuallyConnectedNetworkId === n2;\n }\n computeRegionPfFromAssignments(e50) {\n const t2 = this.getRegionAssignedPortPoints(e50), n2 = { ...e50.d, portPoints: t2 }, o3 = Cz(n2), i3 = e50.d;\n return jz(i3, o3.numSameLayerCrossings, o3.numEntryExitLayerChanges, o3.numTransitionPairCrossings);\n }\n clampPf(e50) {\n return Math.min(Math.max(e50, 0), 0.999999);\n }\n get NODE_MAX_PF() {\n return Math.min(0.99999, 1 - Math.exp(-this.params.weights.NODE_PF_MAX_PENALTY));\n }\n pfToFailureCost(e50) {\n const t2 = this.clampPf(e50);\n return t2 \u003e= this.NODE_MAX_PF ? this.params.weights.NODE_PF_MAX_PENALTY : -Math.log(1 - t2);\n }\n getBaseRegionFailureCost(e50) {\n const t2 = this.baseRegionFailureCostMap.get(e50.regionId);\n if (t2 != null)\n return t2;\n const n2 = this.computeRegionPfFromAssignments(e50), o3 = this.pfToFailureCost(n2);\n return this.baseRegionFailureCostMap.set(e50.regionId, o3), o3;\n }\n getRegionAssignedPortPoints(e50) {\n return (e50.assignments ?? []).flatMap((e51) =\u003e {\n const t2 = e51.regionPort1.d, n2 = e51.regionPort2.d, o3 = e51.connection.connectionId, i3 = e51.connection.simpleRouteConnection?.__rootConnectionNames?.[0];\n return [{ x: t2.x, y: t2.y, z: t2.z, connectionName: o3, rootConnectionName: i3 }, { x: n2.x, y: n2.y, z: n2.z, connectionName: o3, rootConnectionName: i3 }];\n });\n }\n computeRegionPfWithAdditionalSegment(e50, t2, n2, o3, i3) {\n const r3 = this.getRegionAssignedPortPoints(e50), s2 = [{ x: t2.d.x, y: t2.d.y, z: t2.d.z, connectionName: o3, rootConnectionName: i3 }, { x: n2.d.x, y: n2.d.y, z: n2.d.z, connectionName: o3, rootConnectionName: i3 }], a3 = { ...e50.d, portPoints: [...r3, ...s2] }, c3 = Cz(a3);\n return jz(e50.d, c3.numSameLayerCrossings, c3.numEntryExitLayerChanges, c3.numTransitionPairCrossings);\n }\n getRegionRippingPfThreshold(e50) {\n const t2 = this.regionRipCountMap.get(e50) ?? 0, n2 = Math.max(1, Math.floor(this.params.weights.MAX_RIPS / 10)), o3 = Math.min(1, t2 / n2);\n return (this.params.weights.START_RIPPING_PF_THRESHOLD || 0.3) * (1 - o3) + (this.params.weights.END_RIPPING_PF_THRESHOLD || 1) * o3;\n }\n computeRegionPf({ region: e50, newlySolvedRoute: t2, routesToRip: n2 }) {\n const o3 = [...(e50.assignments ?? []).filter((e51) =\u003e !n2.has(e51.solvedRoute)).flatMap((e51) =\u003e {\n const { regionPort1: t3, regionPort2: n3 } = e51, o4 = e51.connection.connectionId, i4 = e51.connection.simpleRouteConnection?.__rootConnectionNames?.[0];\n return [{ x: t3.d.x, y: t3.d.y, z: t3.d.z, connectionName: o4, rootConnectionName: i4 }, { x: n3.d.x, y: n3.d.y, z: n3.d.z, connectionName: o4, rootConnectionName: i4 }];\n }), ...t2.path.flatMap((n3) =\u003e {\n if (!n3.lastPort || n3.lastRegion !== e50)\n return [];\n const { lastPort: o4, port: i4 } = n3;\n return [{ x: o4.d.x, y: o4.d.y, z: o4.d.z, connectionName: t2.connection.connectionId, rootConnectionName: t2.connection.simpleRouteConnection?.__rootConnectionNames?.[0] }, { x: i4.d.x, y: i4.d.y, z: i4.d.z, connectionName: t2.connection.connectionId, rootConnectionName: t2.connection.simpleRouteConnection?.__rootConnectionNames?.[0] }];\n })], i3 = { capacityMeshNodeId: e50.d.capacityMeshNodeId, center: e50.d.center, width: e50.d.width, height: e50.d.height, portPoints: o3, availableZ: e50.d.availableZ }, r3 = Cz(i3), s2 = e50.d;\n return jz(s2, r3.numSameLayerCrossings, r3.numEntryExitLayerChanges, r3.numTransitionPairCrossings);\n }\n computeNodePf(e50) {\n const t2 = this.getOutput().nodesWithPortPoints.find((t3) =\u003e t3.capacityMeshNodeId === e50.capacityMeshNodeId), n2 = this.params.graph.regions.find((t3) =\u003e t3.d.capacityMeshNodeId === e50.capacityMeshNodeId);\n if (!t2 || !n2)\n return null;\n const o3 = Cz(t2);\n return jz(n2.d, o3.numSameLayerCrossings, o3.numEntryExitLayerChanges, o3.numTransitionPairCrossings);\n }\n getOutput() {\n new Map(this.params.graph.regions.map((e51) =\u003e [e51.regionId, e51]));\n const e50 = new Set;\n for (const t3 of this.params.connections)\n e50.add(t3.startRegion.regionId), e50.add(t3.endRegion.regionId);\n const t2 = new Map;\n for (const e51 of this.solvedRoutes) {\n const n3 = e51.path;\n if (n3.length === 0)\n continue;\n const o4 = n3[0]?.port, i3 = n3[n3.length - 1]?.port;\n if (!o4 || !i3)\n continue;\n const r3 = e51.connection.connectionId, s2 = e51.connection, a3 = s2.simpleRouteConnection?.__rootConnectionNames?.[0], c3 = e51.connection.startRegion.regionId, l3 = e51.connection.endRegion.regionId, h2 = t2.get(c3) ?? [];\n h2.push({ portPointId: o4.d.portId, x: o4.d.x, y: o4.d.y, z: o4.d.z, connectionName: r3, rootConnectionName: a3 }), t2.set(c3, h2);\n const d2 = t2.get(l3) ?? [];\n d2.push({ portPointId: i3.d.portId, x: i3.d.x, y: i3.d.y, z: i3.d.z, connectionName: r3, rootConnectionName: a3 }), t2.set(l3, d2);\n }\n const n2 = [], o3 = [];\n for (const i3 of this.params.graph.regions) {\n const r3 = (i3.assignments ?? []).flatMap((e51) =\u003e {\n const t3 = e51.connection.connectionId, n3 = e51.connection.simpleRouteConnection?.__rootConnectionNames?.[0];\n return [{ portPointId: e51.regionPort1.d.portId, x: e51.regionPort1.d.x, y: e51.regionPort1.d.y, z: e51.regionPort1.d.z, connectionName: t3, rootConnectionName: n3, nextPortPointId: e51.regionPort2.d.portId }, { portPointId: e51.regionPort2.d.portId, x: e51.regionPort2.d.x, y: e51.regionPort2.d.y, z: e51.regionPort2.d.z, connectionName: t3, rootConnectionName: n3, prevPortPointId: e51.regionPort1.d.portId }];\n }), s2 = [];\n if (i3.d._containsObstacle \u0026\u0026 e50.has(i3.regionId)) {\n const e51 = t2.get(i3.regionId) ?? [], n3 = [];\n for (const t3 of e51) {\n r3.some((e52) =\u003e e52.connectionName === t3.connectionName \u0026\u0026 e52.rootConnectionName === t3.rootConnectionName \u0026\u0026 e52.portPointId === t3.portPointId) || n3.push(t3);\n }\n r3.push(...n3);\n const o4 = new Map;\n for (const e52 of r3) {\n const t3 = `${e52.connectionName}::${e52.rootConnectionName ?? \"\"}`, n4 = o4.get(t3) ?? [];\n n4.push(e52), o4.set(t3, n4);\n }\n for (const [e52, t3] of o4.entries()) {\n const [n4, o5 = \"\"] = e52.split(\"::\"), r4 = t3[0];\n if (!r4)\n continue;\n const a4 = { portPointId: `center:${i3.regionId}:${n4}:${o5}`, x: i3.d.center.x, y: i3.d.center.y, z: r4.z, connectionName: n4, rootConnectionName: o5 || undefined };\n if (t3.length \u003e= 2) {\n const e53 = t3[t3.length - 1];\n r4.portPointId \u0026\u0026 (r4.nextPortPointId = a4.portPointId, a4.prevPortPointId = r4.portPointId), e53.portPointId \u0026\u0026 (e53.prevPortPointId = a4.portPointId, a4.nextPortPointId = e53.portPointId);\n }\n s2.push(a4);\n }\n }\n const a3 = [...r3, ...s2];\n a3.length \u003e 0 \u0026\u0026 n2.push({ capacityMeshNodeId: i3.d.capacityMeshNodeId, center: i3.d.center, width: i3.d.width, height: i3.d.height, portPoints: a3, availableZ: i3.d.availableZ });\n const c3 = i3.ports.map((e51) =\u003e {\n const t3 = e51.d, n3 = e51.d.regions.some((e52) =\u003e Boolean(e52.d._offBoardConnectionId));\n return { portPointId: e51.d.portId, x: e51.d.x, y: e51.d.y, z: e51.d.z, prevPortPointId: t3.prevPortPointId, nextPortPointId: t3.nextPortPointId, connectionNodeIds: e51.d.regions.map((e52) =\u003e e52.regionId), distToCentermostPortOnZ: e51.d.distToCentermostPortOnZ, connectsToOffBoardNode: n3 };\n });\n o3.push({ capacityMeshNodeId: i3.d.capacityMeshNodeId, center: i3.d.center, width: i3.d.width, height: i3.d.height, portPoints: c3, availableZ: i3.d.availableZ, _containsObstacle: i3.d._containsObstacle, _containsTarget: i3.d._containsTarget, _offBoardConnectionId: i3.d._offBoardConnectionId, _offBoardConnectedCapacityMeshNodeIds: i3.d._offBoardConnectedCapacityMeshNodeIds });\n }\n return { nodesWithPortPoints: n2, inputNodeWithPortPoints: o3 };\n }\n visualize() {\n return function(e50) {\n let t2 = {};\n return t2 = e50.reduce((e51, t3) =\u003e e51 \u0026\u0026 t3 ? Gn(e51, t3) : {}, t2), t2 || {};\n }([oU(this.params.graph), this.visualizePfOverlay(), nU(this.params.connections, this.params.colorMap ?? {}), eU(this.candidateQueue.peekMany(100), this.currentConnection?.startRegion.d.center), tU(this.solvedRoutes, this.params.colorMap ?? {})]);\n }\n visualizePfOverlay() {\n const e50 = this.getOutput(), t2 = e50?.inputNodeWithPortPoints ?? [], n2 = new Map((e50?.nodesWithPortPoints ?? []).map((e51) =\u003e [e51.capacityMeshNodeId, e51])), o3 = { rects: [] };\n for (const e51 of t2) {\n const t3 = this.computeNodePf(e51), i3 = t3 ?? 0, r3 = n2.get(e51.capacityMeshNodeId), s2 = r3 ? Cz(r3) : { numSameLayerCrossings: 0, numEntryExitLayerChanges: 0, numTransitionPairCrossings: 0 }, a3 = Math.min(255, Math.floor(512 * i3)), c3 = Math.max(0, 255 - Math.floor(512 * i3));\n let l3 = `rgba(${a3}, ${c3}, ${c3}, ${i3 \u003c 0.001 ? \"0.1\" : \"0.3\"})`;\n e51._containsObstacle \u0026\u0026 (l3 = \"rgba(255, 0, 0, 0.3)\"), e51._offBoardConnectedCapacityMeshNodeIds?.length \u0026\u0026 (l3 = \"rgba(255, 165, 0, 0.3)\"), o3.rects.push({ center: e51.center, width: e51.width - 0.2, height: e51.height - 0.2, layer: `z${e51?.availableZ?.join(\",\")}`, fill: l3, label: `${e51.capacityMeshNodeId}\npf: ${t3 === null ? \"n/a\" : t3.toFixed(3)}\nxSame: ${s2.numSameLayerCrossings}, xLC: ${s2.numEntryExitLayerChanges}, xTransition: ${s2.numTransitionPairCrossings}` });\n }\n return o3;\n }\n};\nvar rU = (e50) =\u003e {\n if (!e50.assignments || e50.assignments.length === 0)\n return e50.d?.assignment ? 0 : 1;\n const t2 = e50.assignments.flatMap((e51) =\u003e {\n const t3 = e51.regionPort1.d, n3 = e51.regionPort2.d, o4 = e51.connection.connectionId, i3 = e51.connection, r3 = i3.simpleRouteConnection?.__rootConnectionNames?.[0];\n return [{ x: t3.x, y: t3.y, z: t3.z, connectionName: o4, rootConnectionName: r3 }, { x: n3.x, y: n3.y, z: n3.z, connectionName: o4, rootConnectionName: r3 }];\n }), n2 = { ...e50.d, portPoints: t2 }, o3 = Cz(n2);\n return jz(e50.d, o3.numSameLayerCrossings, o3.numEntryExitLayerChanges, o3.numTransitionPairCrossings);\n};\nfunction sU(e50, t2, n2, o3 = {}) {\n return { solverName: e50, solverClass: t2, getConstructorParams: n2, onSolved: o3.onSolved };\n}\nvar aU = class extends ni {\n constructor(e50, t2 = {}) {\n super(), this.srj = e50, this.opts = t2, this.srj = e50, this.opts = { ...t2 }, this.viaDiameter = Yo(e50).padDiameter, this.minTraceWidth = e50.minTraceWidth;\n const n2 = this.opts;\n if (this.effort = n2.effort ?? 1, this.MAX_ITERATIONS = 1e8 * this.effort, n2.capacityDepth === undefined) {\n const t3 = e50.bounds.maxX - e50.bounds.minX, o3 = e50.bounds.maxY - e50.bounds.minY, i3 = Math.max(t3, o3), r3 = n2.targetMinCapacity ?? 0.5;\n n2.capacityDepth = Fz(i3, r3);\n }\n this.connMap = ei(e50), this.colorMap = Eo(e50, this.connMap), this.cacheProvider = n2.cacheProvider === undefined ? no() : n2.cacheProvider === null ? null : n2.cacheProvider, this.startTimeOfPhase = {}, this.endTimeOfPhase = {}, this.timeSpentOnPhase = {};\n }\n netToPointPairsSolver;\n nodeSolver;\n nodeTargetMerger;\n edgeSolver;\n colorMap;\n highDensityRouteSolver;\n highDensityStitchSolver;\n singleLayerNodeMerger;\n strawSolver;\n deadEndSolver;\n traceSimplificationSolver;\n availableSegmentPointSolver;\n portPointPathingSolver;\n multiSectionPortPointOptimizer;\n uniformPortDistributionSolver;\n traceWidthSolver;\n necessaryCrampedPortPointSolver;\n hyperGraphSectionOptimizer;\n viaDiameter;\n minTraceWidth;\n effort;\n startTimeOfPhase;\n endTimeOfPhase;\n timeSpentOnPhase;\n activeSubSolver = null;\n connMap;\n srjWithPointPairs;\n capacityNodes = null;\n capacityEdges = null;\n cacheProvider = null;\n pipelineDef = [sU(\"netToPointPairsSolver\", pB, (e50) =\u003e [e50.srj, e50.colorMap, ti(e50.srj)], { onSolved: (e50) =\u003e {\n e50.srjWithPointPairs = e50.netToPointPairsSolver?.getNewSimpleRouteJson(), e50.colorMap = Eo(e50.srjWithPointPairs, this.connMap), e50.connMap = ei(e50.srjWithPointPairs);\n } }), sU(\"nodeSolver\", Jn, (e50) =\u003e [{ simpleRouteJson: e50.srjWithPointPairs, maxGapFillPasses: 4 }], { onSolved: (e50) =\u003e {\n e50.capacityNodes = e50.nodeSolver?.getOutput().meshNodes ?? [];\n } }), sU(\"edgeSolver\", ui, (e50) =\u003e [e50.capacityNodes], { onSolved: (e50) =\u003e {\n e50.capacityEdges = e50.edgeSolver?.edges;\n } }), sU(\"availableSegmentPointSolver\", ii, (e50) =\u003e [{ nodes: e50.capacityNodes, edges: e50.capacityEdges || [], traceWidth: e50.minTraceWidth, colorMap: e50.colorMap, shouldReturnCrampedPortPoints: true }]), sU(\"necessaryCrampedPortPointSolver\", FG, (e50) =\u003e [{ capacityMeshNodes: e50.capacityNodes, sharedEdgeSegments: e50.availableSegmentPointSolver.getOutput(), simpleRouteJson: e50.srjWithPointPairs }]), sU(\"portPointPathingSolver\", iU, (e50) =\u003e {\n const t2 = e50.necessaryCrampedPortPointSolver?.getOutput() ?? e50.availableSegmentPointSolver.getOutput(), { graph: n2, connections: o3 } = KG({ capacityMeshNodes: e50.capacityNodes, layerCount: e50.srj.layerCount, connectivityMap: e50.connMap, segmentPortPoints: t2.flatMap((e51) =\u003e e51.portPoints), simpleRouteJsonConnections: e50.srjWithPointPairs.connections });\n return [{ graph: n2, connections: o3, layerCount: e50.srj.layerCount, effort: Math.min(1, e50.effort), flags: { FORCE_CENTER_FIRST: true, RIPPING_ENABLED: true }, weights: { SHUFFLE_SEED: 0, MEMORY_PF_FACTOR: 4, CENTER_OFFSET_DIST_PENALTY_FACTOR: 0, CENTER_OFFSET_FOCUS_SHIFT: 0, NODE_PF_FACTOR: 0, LAYER_CHANGE_COST: 0, RIPPING_PF_COST: 0, NODE_PF_MAX_PENALTY: 100, BASE_CANDIDATE_COST: 0.6, MAX_ITERATIONS_PER_PATH: 0, RANDOM_WALK_DISTANCE: 0, START_RIPPING_PF_THRESHOLD: 0.3, END_RIPPING_PF_THRESHOLD: 1, MAX_RIPS: 1000, RANDOM_RIP_FRACTION: 0.3, STRAIGHT_LINE_DEVIATION_PENALTY_FACTOR: 4, GREEDY_MULTIPLIER: 0.7, MIN_ALLOWED_BOARD_SCORE: -1e4 } }];\n }), sU(\"hyperGraphSectionOptimizer\", tX, (e50) =\u003e {\n const t2 = e50.portPointPathingSolver;\n return [{ hyperGraphSolver: t2, inputSolvedRoutes: t2.solvedRoutes, expansionHopsFromCentralRegion: 1, createHyperGraphSolver: (t3) =\u003e new iU({ graph: t3.inputGraph, connections: t3.inputConnections, inputSolvedRoutes: t3.inputSolvedRoutes, layerCount: e50.srj.layerCount, effort: Math.min(1, e50.effort), flags: { FORCE_CENTER_FIRST: true, RIPPING_ENABLED: true }, weights: { SHUFFLE_SEED: 0, MEMORY_PF_FACTOR: 4, CENTER_OFFSET_DIST_PENALTY_FACTOR: 0, CENTER_OFFSET_FOCUS_SHIFT: 0, NODE_PF_FACTOR: 0, LAYER_CHANGE_COST: 0, RIPPING_PF_COST: 0, NODE_PF_MAX_PENALTY: 100, BASE_CANDIDATE_COST: 0.6, MAX_ITERATIONS_PER_PATH: 0, RANDOM_WALK_DISTANCE: 0, START_RIPPING_PF_THRESHOLD: 0.3, END_RIPPING_PF_THRESHOLD: 1, MAX_RIPS: 1000, RANDOM_RIP_FRACTION: 0.3, STRAIGHT_LINE_DEVIATION_PENALTY_FACTOR: 4, GREEDY_MULTIPLIER: 0.7, MIN_ALLOWED_BOARD_SCORE: -1e4 } }), regionCost: rU, effort: Math.min(1, e50.effort), ACCEPTABLE_REGION_COST: 0.1, MAX_ATTEMPTS_PER_REGION: Math.max(3, 3 * Math.min(1, e50.effort)), MAX_ATTEMPTS_PER_SECTION: Math.max(50, 50 * Math.min(1, e50.effort)), FRACTION_TO_REPLACE: 1, alwaysRipConflicts: true }];\n }), sU(\"uniformPortDistributionSolver\", bo, (e50) =\u003e [{ nodeWithPortPoints: e50.portPointPathingSolver?.getOutput().nodesWithPortPoints ?? [], inputNodesWithPortPoints: e50.portPointPathingSolver?.getOutput().inputNodeWithPortPoints ?? [], minTraceWidth: e50.minTraceWidth, obstacles: e50.srj.obstacles, layerCount: e50.srj.layerCount }]), sU(\"highDensityRouteSolver\", Dz, (e50) =\u003e [{ nodePortPoints: e50.uniformPortDistributionSolver?.getOutput() ?? [], nodePfById: new Map((e50.portPointPathingSolver?.getOutput().inputNodeWithPortPoints ?? []).map((t2) =\u003e [t2.capacityMeshNodeId, e50.portPointPathingSolver?.computeNodePf(t2) ?? null])), colorMap: e50.colorMap, connMap: e50.connMap, viaDiameter: e50.viaDiameter, traceWidth: e50.minTraceWidth }]), sU(\"highDensityStitchSolver\", IB, (e50) =\u003e [{ connections: e50.srjWithPointPairs.connections, hdRoutes: e50.highDensityRouteSolver.routes, colorMap: e50.colorMap, layerCount: e50.srj.layerCount, defaultViaDiameter: e50.viaDiameter }]), sU(\"traceSimplificationSolver\", WF, (e50) =\u003e [{ hdRoutes: e50.highDensityStitchSolver.mergedHdRoutes, obstacles: e50.srj.obstacles, connMap: e50.connMap, colorMap: e50.colorMap, outline: e50.srj.outline, defaultViaDiameter: e50.viaDiameter, layerCount: e50.srj.layerCount, iterations: 2 }]), sU(\"traceWidthSolver\", QF, (e50) =\u003e [{ hdRoutes: e50.traceSimplificationSolver.simplifiedHdRoutes, obstacles: e50.srj.obstacles, connMap: e50.connMap, colorMap: e50.colorMap, minTraceWidth: e50.minTraceWidth, connection: e50.srj.connections, layerCount: e50.srj.layerCount }])];\n getConstructorParams() {\n return [this.srj, this.opts];\n }\n currentPipelineStepIndex = 0;\n _step() {\n const e50 = this.pipelineDef[this.currentPipelineStepIndex];\n if (!e50)\n return void (this.solved = true);\n if (this.activeSubSolver)\n return this.activeSubSolver.step(), void (this.activeSubSolver.solved ? (this.endTimeOfPhase[e50.solverName] = performance.now(), this.timeSpentOnPhase[e50.solverName] = this.endTimeOfPhase[e50.solverName] - this.startTimeOfPhase[e50.solverName], e50.onSolved?.(this), this.activeSubSolver = null, this.currentPipelineStepIndex++) : this.activeSubSolver.failed \u0026\u0026 (this.error = this.activeSubSolver?.error, this.failed = true, this.activeSubSolver = null));\n const t2 = e50.getConstructorParams(this);\n this.activeSubSolver = new e50.solverClass(...t2), this[e50.solverName] = this.activeSubSolver, this.timeSpentOnPhase[e50.solverName] = 0, this.startTimeOfPhase[e50.solverName] = performance.now();\n }\n solveUntilPhase(e50) {\n for (;this.getCurrentPhase() !== e50; )\n this.step();\n }\n getCurrentPhase() {\n return this.pipelineDef[this.currentPipelineStepIndex]?.solverName ?? \"none\";\n }\n visualize() {\n if (!this.solved \u0026\u0026 this.activeSubSolver)\n return this.activeSubSolver.visualize();\n const e50 = this.netToPointPairsSolver?.visualize(), t2 = this.nodeSolver?.visualize(), n2 = this.nodeTargetMerger?.visualize(), o3 = this.singleLayerNodeMerger?.visualize(), i3 = this.strawSolver?.visualize(), r3 = this.edgeSolver?.visualize(), s2 = this.deadEndSolver?.visualize(), a3 = this.availableSegmentPointSolver?.visualize(), c3 = this.portPointPathingSolver?.visualize(), l3 = this.multiSectionPortPointOptimizer?.visualize(), h2 = this.uniformPortDistributionSolver?.visualize(), d2 = this.highDensityRouteSolver?.visualize(), u2 = this.highDensityStitchSolver?.visualize(), p3 = this.traceSimplificationSolver?.visualize(), m2 = this.necessaryCrampedPortPointSolver?.visualize(), g2 = this.highDensityRouteSolver?.visualize(), f2 = this.srj.outline, _2 = [];\n if (_2.push({ points: [{ x: this.srj.bounds?.minX ?? -50, y: this.srj.bounds?.minY ?? -50 }, { x: this.srj.bounds?.maxX ?? 50, y: this.srj.bounds?.minY ?? -50 }, { x: this.srj.bounds?.maxX ?? 50, y: this.srj.bounds?.maxY ?? 50 }, { x: this.srj.bounds?.minX ?? -50, y: this.srj.bounds?.maxY ?? 50 }, { x: this.srj.bounds?.minX ?? -50, y: this.srj.bounds?.minY ?? -50 }], strokeColor: \"rgba(255,0,0,0.25)\" }), f2 \u0026\u0026 f2.length \u003e= 2) {\n const e51 = f2.map((e52) =\u003e ({ x: e52.x, y: e52.y }));\n e51.push({ ...e51[0] }), _2.push({ points: e51, strokeColor: \"rgba(0, 136, 255, 0.95)\" });\n }\n const y2 = Lo(this.srj), b2 = { points: [...this.srj.connections.flatMap((e51) =\u003e e51.pointsToConnect.map((t3) =\u003e ({ ...t3, layer: Bo(t3, this.srj.layerCount), label: `${e51.name} ${t3.pcb_port_id ?? \"\"}` })))], rects: [...(this.srj.obstacles ?? []).filter((e51) =\u003e !e51.isCopperPour).map((e51) =\u003e ({ ...e51, fill: e51.layers?.includes(\"top\") ? \"rgba(255,0,0,0.25)\" : e51.layers?.includes(\"bottom\") ? \"rgba(0,0,255,0.25)\" : \"rgba(255,0,0,0.25)\", layer: jo(e51, this.srj.layerCount), label: y2(e51) }))], lines: _2 }, x2 = [b2, e50, t2, n2, o3, i3, r3, s2, a3, m2, c3, g2, l3, h2, d2 ? pi(b2, d2) : null, u2, p3, this.solved ? pi({ lines: _2 }, Wo(this.getOutputSimpleRouteJson())) : null].filter(Boolean);\n return pi(...x2);\n }\n preview() {\n if (this.highDensityRouteSolver) {\n const e50 = [];\n for (let t2 = this.highDensityRouteSolver.routes.length - 1;t2 \u003e= 0; t2--) {\n const n2 = this.highDensityRouteSolver.routes[t2];\n if (e50.push({ points: n2.route.map((e51) =\u003e ({ x: e51.x, y: e51.y })), strokeColor: this.colorMap[n2.connectionName] }), e50.length \u003e 200)\n break;\n }\n return { lines: e50 };\n }\n return this.netToPointPairsSolver ? this.netToPointPairsSolver.visualize() : {};\n }\n _getOutputHdRoutes() {\n return this.traceWidthSolver?.getHdRoutesWithWidths() ?? this.traceSimplificationSolver?.simplifiedHdRoutes ?? this.highDensityStitchSolver.mergedHdRoutes;\n }\n getOutputSimplifiedPcbTraces() {\n if (!this.solved || !this.highDensityRouteSolver)\n throw new Error(\"Cannot get output before solving is complete\");\n const e50 = [], t2 = this._getOutputHdRoutes();\n for (const n2 of this.netToPointPairsSolver?.newConnections ?? []) {\n const o3 = n2.__netConnectionName ?? this.srj.connections.find((e51) =\u003e e51.name === n2.name)?.__netConnectionName, i3 = t2.filter((e51) =\u003e e51.connectionName === n2.name);\n for (let t3 = 0;t3 \u003c i3.length; t3++) {\n const r3 = i3[t3], s2 = { type: \"pcb_trace\", pcb_trace_id: `${n2.name}_${t3}`, connection_name: o3 ?? n2.__rootConnectionNames?.[0] ?? n2.name, route: Ro(r3, this.srj.layerCount) };\n e50.push(s2);\n }\n }\n return e50;\n }\n getOutputSimpleRouteJson() {\n return { ...this.srj, traces: this.getOutputSimplifiedPcbTraces() };\n }\n};\nvar cU = class {\n MAX_ITERATIONS = 1000;\n solved = false;\n failed = false;\n iterations = 0;\n progress = 0;\n error = null;\n activeSubSolver;\n failedSubSolvers;\n timeToSolve;\n stats = {};\n pendingEffects;\n cacheHit;\n cacheKey;\n cacheToSolveSpaceTransform;\n getSolverName() {\n return this.constructor.name;\n }\n step() {\n if (!this.solved \u0026\u0026 !this.failed) {\n this.iterations++;\n try {\n this._step();\n } catch (e50) {\n throw this.error = `${this.getSolverName()} error: ${e50}`, console.error(this.error), this.failed = true, e50;\n }\n !this.solved \u0026\u0026 this.iterations \u003e this.MAX_ITERATIONS \u0026\u0026 this.tryFinalAcceptance(), !this.solved \u0026\u0026 this.iterations \u003e this.MAX_ITERATIONS \u0026\u0026 (this.error = `${this.getSolverName()} ran out of iterations (MAX_ITERATIONS=${this.MAX_ITERATIONS})`, this.failed = true), \"computeProgress\" in this \u0026\u0026 (this.progress = this.computeProgress());\n }\n }\n _step() {}\n getConstructorParams() {\n throw new Error(\"getConstructorParams not implemented\");\n }\n solve() {\n const e50 = Date.now();\n for (;!this.solved \u0026\u0026 !this.failed; )\n this.step();\n const t2 = Date.now();\n this.timeToSolve = t2 - e50;\n }\n visualize() {\n return { lines: [], points: [], rects: [], circles: [] };\n }\n tryFinalAcceptance() {}\n preview() {\n return { lines: [], points: [], rects: [], circles: [] };\n }\n};\nvar lU = (e50, t2) =\u003e {\n const n2 = (e51) =\u003e e51 === \" \" || e51 === `\n` || e51 === \"\\r\" || e51 === \"\\t\", o3 = (e51) =\u003e {\n let t3 = 0, o4 = e51.length;\n for (;t3 \u003c o4 \u0026\u0026 n2(e51[t3]); )\n t3 += 1;\n for (;o4 \u003e t3 \u0026\u0026 n2(e51[o4 - 1]); )\n o4 -= 1;\n return e51.slice(t3, o4);\n }, i3 = (e51) =\u003e {\n const t3 = [];\n let n3 = 0, i4 = 0;\n for (let r4 = 0;r4 \u003c e51.length; r4 += 1) {\n const s3 = e51[r4];\n s3 !== \"(\" ? s3 !== \")\" ? s3 === \",\" \u0026\u0026 i4 === 0 \u0026\u0026 (t3.push(o3(e51.slice(n3, r4))), n3 = r4 + 1) : i4 \u003e 0 \u0026\u0026 (i4 -= 1) : i4 += 1;\n }\n return t3.push(o3(e51.slice(n3))), t3;\n }, r3 = (e51) =\u003e {\n return `${t3 = e51, Math.min(1, Math.max(0, t3))}`;\n var t3;\n }, s2 = ((e51) =\u003e {\n const t3 = o3(e51);\n if (!t3.startsWith(\"#\"))\n return null;\n const n3 = t3.slice(1);\n if (n3.length !== 3 \u0026\u0026 n3.length !== 6)\n return null;\n for (const e52 of n3) {\n const t4 = e52.toLowerCase();\n if (!(t4 \u003e= \"0\" \u0026\u0026 t4 \u003c= \"9\") \u0026\u0026 !(t4 \u003e= \"a\" \u0026\u0026 t4 \u003c= \"f\"))\n return null;\n }\n if (n3.length === 3) {\n const [e52, t4, o4] = n3;\n return { r: Number.parseInt(e52 + e52, 16), g: Number.parseInt(t4 + t4, 16), b: Number.parseInt(o4 + o4, 16) };\n }\n return { r: Number.parseInt(n3.slice(0, 2), 16), g: Number.parseInt(n3.slice(2, 4), 16), b: Number.parseInt(n3.slice(4, 6), 16) };\n })(t2);\n if (s2)\n return `rgba(${s2.r}, ${s2.g}, ${s2.b}, ${r3(1 - e50)})`;\n const a3 = ((e51) =\u003e {\n const t3 = o3(e51), n3 = t3.indexOf(\"(\");\n return n3 \u003c= 0 || t3[t3.length - 1] !== \")\" ? null : { name: o3(t3.slice(0, n3)).toLowerCase(), args: i3(t3.slice(n3 + 1, -1)) };\n })(t2);\n if (!a3)\n return t2;\n const { name: c3, args: l3 } = a3;\n if (c3 === \"hsl\" || c3 === \"rgb\")\n return l3.length !== 3 ? t2 : `${c3}a(${l3[0]}, ${l3[1]}, ${l3[2]}, ${r3(1 - e50)})`;\n if (c3 === \"hsla\" || c3 === \"rgba\") {\n if (l3.length !== 4)\n return t2;\n const n3 = ((e51) =\u003e {\n const t3 = o3(e51);\n if (!t3)\n return null;\n const n4 = Number.parseFloat(t3);\n return Number.isFinite(n4) ? n4 : null;\n })(l3[3]);\n return n3 === null ? t2 : `${c3}(${l3[0]}, ${l3[1]}, ${l3[2]}, ${r3(n3 - e50)})`;\n }\n return t2;\n};\nvar hU = (e50, t2) =\u003e {\n try {\n return lU(t2, e50);\n } catch (t3) {\n return console.error(t3), e50;\n }\n};\nvar dU = (e50) =\u003e e50.rootConnectionName ?? e50.connectionName;\nvar uU = (e50) =\u003e {\n const t2 = [];\n for (let n2 = 0;n2 \u003c e50.route.length - 1; n2 += 1) {\n const o3 = e50.route[n2], i3 = e50.route[n2 + 1];\n if (!o3 || !i3 || o3.z === i3.z)\n continue;\n if (Math.abs(o3.x - i3.x) \u003e 0.000001 || Math.abs(o3.y - i3.y) \u003e 0.000001)\n continue;\n const r3 = { x: Math.round(1000 * o3.x) / 1000, y: Math.round(1000 * o3.y) / 1000 }, s2 = t2.at(-1);\n s2 \u0026\u0026 s2.x === r3.x \u0026\u0026 s2.y === r3.y || t2.push(r3);\n }\n return t2;\n};\nvar pU = (e50, t2, n2 = 0.001) =\u003e Math.abs(e50.x - t2.x) \u003c= n2 \u0026\u0026 Math.abs(e50.y - t2.y) \u003c= n2;\nvar mU = (e50, t2) =\u003e ({ minX: e50.center.x - e50.width / 2 + t2, maxX: e50.center.x + e50.width / 2 - t2, minY: e50.center.y - e50.height / 2 + t2, maxY: e50.center.y + e50.height / 2 - t2 });\nvar gU = (e50, t2) =\u003e {\n const n2 = Math.max(Math.abs(e50), Math.abs(t2));\n if (n2 === 0 || n2 === Number.POSITIVE_INFINITY)\n return n2;\n const o3 = e50 / n2, i3 = t2 / n2;\n return n2 * Math.sqrt(o3 * o3 + i3 * i3);\n};\nvar fU = (e50, t2) =\u003e ({ x: e50.x - t2.x, y: e50.y - t2.y });\nvar _U = (e50, t2) =\u003e e50.x * t2.x + e50.y * t2.y;\nvar yU = (e50, t2, n2) =\u003e ({ x: e50.x + (t2.x - e50.x) * n2, y: e50.y + (t2.y - e50.y) * n2 });\nvar bU = (e50) =\u003e {\n const t2 = [];\n for (let n2 = 0;n2 \u003c e50.length; n2 += 1) {\n const o3 = e50[n2];\n if (o3)\n for (let e51 = 0;e51 \u003c o3.route.length - 1; e51 += 1) {\n const i3 = o3.route[e51], r3 = o3.route[e51 + 1];\n i3 \u0026\u0026 r3 \u0026\u0026 (i3.z !== r3.z || pU(i3, r3) || t2.push({ routeIndex: n2, rootConnectionName: dU(o3), startIndex: e51, endIndex: e51 + 1, start: i3, end: r3, z: i3.z, traceRadius: (o3.traceThickness ?? 0.1) / 2 }));\n }\n }\n return t2;\n};\nvar xU = (e50, t2, n2 = 0.000001) =\u003e {\n const o3 = t2.end.x - t2.start.x, i3 = t2.end.y - t2.start.y, r3 = o3 * o3 + i3 * i3;\n if (r3 \u003c= n2)\n return { x: t2.start.x, y: t2.start.y, t: 0 };\n const s2 = ((e50.x - t2.start.x) * o3 + (e50.y - t2.start.y) * i3) / r3, a3 = (c3 = s2, Math.max(0, Math.min(c3, 1)));\n var c3;\n return { x: t2.start.x + o3 * a3, y: t2.start.y + i3 * a3, t: a3 };\n};\nvar vU = (e50, t2, n2 = 0.000001) =\u003e {\n const o3 = fU(e50.end, e50.start), i3 = fU(t2.end, t2.start), r3 = fU(e50.start, t2.start), s2 = _U(o3, o3), a3 = _U(o3, i3), c3 = _U(i3, i3), l3 = _U(o3, r3), h2 = _U(i3, r3), d2 = s2 * c3 - a3 * a3, u2 = n2;\n let p3, m2, g2 = d2, f2 = d2;\n d2 \u003c= u2 ? (p3 = 0, g2 = 1, m2 = h2, f2 = c3) : (p3 = a3 * h2 - c3 * l3, m2 = s2 * h2 - a3 * l3, p3 \u003c 0 ? (p3 = 0, m2 = h2, f2 = c3) : p3 \u003e g2 \u0026\u0026 (p3 = g2, m2 = h2 + a3, f2 = c3)), m2 \u003c 0 ? (m2 = 0, -l3 \u003c 0 ? p3 = 0 : -l3 \u003e s2 ? p3 = g2 : (p3 = -l3, g2 = s2)) : m2 \u003e f2 \u0026\u0026 (m2 = f2, -l3 + a3 \u003c 0 ? p3 = 0 : -l3 + a3 \u003e s2 ? p3 = g2 : (p3 = -l3 + a3, g2 = s2));\n const _2 = Math.abs(p3) \u003c= u2 ? 0 : p3 / g2, y2 = Math.abs(m2) \u003c= u2 ? 0 : m2 / f2, b2 = yU(e50.start, e50.end, _2), x2 = yU(t2.start, t2.end, y2), v2 = xU(e50.start, t2, n2), I2 = xU(e50.end, t2, n2), S2 = xU(t2.start, e50, n2), C = xU(t2.end, e50, n2);\n return [{ leftT: _2, rightT: y2, leftPoint: b2, rightPoint: x2 }, { leftT: 0, rightT: v2.t, leftPoint: e50.start, rightPoint: v2 }, { leftT: 1, rightT: I2.t, leftPoint: e50.end, rightPoint: I2 }, { leftT: S2.t, rightT: 0, leftPoint: S2, rightPoint: t2.start }, { leftT: C.t, rightT: 1, leftPoint: C, rightPoint: t2.end }].sort((e51, t3) =\u003e gU(e51.leftPoint.x - e51.rightPoint.x, e51.leftPoint.y - e51.rightPoint.y) - gU(t3.leftPoint.x - t3.rightPoint.x, t3.leftPoint.y - t3.rightPoint.y));\n};\nvar IU = 0.000001;\nvar SU = (e50) =\u003e {\n const t2 = [];\n for (const n2 of e50) {\n const e51 = t2[n2.routeIndex] ?? [];\n e51[n2.startIndex] = n2, t2[n2.routeIndex] = e51;\n }\n return t2;\n};\nvar CU = (e50, t2) =\u003e e50 \u003c t2 ? [e50, t2] : [t2, e50];\nvar PU = (e50, t2) =\u003e e50.some(([e51, n2]) =\u003e e51 === t2[0] \u0026\u0026 n2 === t2[1]);\nvar MU = (e50, t2, n2) =\u003e {\n let o3, i3 = Number.POSITIVE_INFINITY;\n for (const r3 of e50) {\n if (r3.routeIndex !== t2.routeIndex || r3.z !== t2.z || r3.endIndex !== t2.startIndex \u0026\u0026 r3.startIndex !== t2.endIndex)\n continue;\n const [e51] = vU(r3, n2);\n if (!e51)\n continue;\n const s2 = gU(e51.leftPoint.x - e51.rightPoint.x, e51.leftPoint.y - e51.rightPoint.y);\n s2 \u003e= i3 || (i3 = s2, o3 = r3);\n }\n return o3;\n};\nvar wU = (e50, t2) =\u003e {\n const n2 = bU(t2), o3 = bU(e50), i3 = SU(o3), r3 = [];\n for (let e51 = 0;e51 \u003c n2.length; e51 += 1) {\n const t3 = n2[e51];\n if (t3)\n for (let s2 = e51 + 1;s2 \u003c n2.length; s2 += 1) {\n const e52 = n2[s2];\n if (!e52 || t3.z !== e52.z || t3.rootConnectionName === e52.rootConnectionName || Math.max(t3.start.x, t3.end.x) \u003c Math.min(e52.start.x, e52.end.x) || Math.max(e52.start.x, e52.end.x) \u003c Math.min(t3.start.x, t3.end.x) || Math.max(t3.start.y, t3.end.y) \u003c Math.min(e52.start.y, e52.end.y) || Math.max(e52.start.y, e52.end.y) \u003c Math.min(t3.start.y, t3.end.y))\n continue;\n const [a3] = vU(t3, e52);\n if (!a3 || gU(a3.leftPoint.x - a3.rightPoint.x, a3.leftPoint.y - a3.rightPoint.y) \u003e IU || a3.leftT \u003c= IU || a3.leftT \u003e= 0.999999 || a3.rightT \u003c= IU || a3.rightT \u003e= 0.999999)\n continue;\n const c3 = i3[t3.routeIndex]?.[t3.startIndex], l3 = i3[e52.routeIndex]?.[e52.startIndex];\n if (!c3 || !l3)\n continue;\n const [h2] = vU(c3, l3);\n if (!h2 || gU(h2.leftPoint.x - h2.rightPoint.x, h2.leftPoint.y - h2.rightPoint.y) \u003c= IU)\n continue;\n const d2 = MU(o3, c3, l3), u2 = MU(o3, l3, c3), p3 = d2 ? [c3, d2] : [c3], m2 = u2 ? [l3, u2] : [l3];\n for (const n3 of p3)\n for (const o4 of m2) {\n const i4 = { leftRouteIndex: t3.routeIndex, leftStartPointIndex: n3.startIndex, rightRouteIndex: e52.routeIndex, rightStartPointIndex: o4.startIndex };\n r3.some((e53) =\u003e e53.leftRouteIndex === i4.leftRouteIndex \u0026\u0026 e53.leftStartPointIndex === i4.leftStartPointIndex \u0026\u0026 e53.rightRouteIndex === i4.rightRouteIndex \u0026\u0026 e53.rightStartPointIndex === i4.rightStartPointIndex) || r3.push(i4);\n }\n }\n }\n return r3;\n};\nvar NU = (e50) =\u003e {\n const t2 = bU(e50), n2 = [];\n for (let e51 = 0;e51 \u003c t2.length; e51 += 1) {\n const o3 = t2[e51];\n if (o3)\n for (let i3 = e51 + 1;i3 \u003c t2.length; i3 += 1) {\n const e52 = t2[i3];\n if (!e52 || o3.z !== e52.z || o3.rootConnectionName === e52.rootConnectionName)\n continue;\n const [r3] = vU(o3, e52);\n if (!r3)\n continue;\n if (gU(r3.leftPoint.x - r3.rightPoint.x, r3.leftPoint.y - r3.rightPoint.y) + IU \u003c o3.traceRadius + e52.traceRadius) {\n const t3 = CU(o3.routeIndex, e52.routeIndex);\n PU(n2, t3) || n2.push(t3);\n }\n }\n }\n return n2;\n};\nvar RU = (e50, t2) =\u003e t2 \u003c= 1 || t2 \u003e= e50 - 2;\nvar TU = (e50, t2) =\u003e t2.some((t3) =\u003e RU(e50, t3));\nvar EU = 0.2;\nvar AU = 0.4;\nvar OU = 0.65 + 0.05;\nvar kU = 0.03;\nvar DU = 1000;\nvar LU = 0.000001;\nvar zU = 0.015;\nvar BU = (e50) =\u003e Math.round(e50 * DU) / DU;\nvar FU = (e50, t2) =\u003e ({ x: e50.x - t2.x, y: e50.y - t2.y });\nvar jU = (e50, t2) =\u003e ({ x: e50.x * t2, y: e50.y * t2 });\nvar $U = (e50, t2) =\u003e e50.x * t2.x + e50.y * t2.y;\nvar YU = (e50, t2, n2) =\u003e ({ x: e50.x + (t2.x - e50.x) * n2, y: e50.y + (t2.y - e50.y) * n2 });\nvar XU = (e50) =\u003e Math.max(0, Math.min(e50, 1));\nvar HU = (e50, t2, n2) =\u003e Math.max(t2, Math.min(e50, n2));\nvar VU = (e50, t2) =\u003e {\n const n2 = ((e51) =\u003e gU(e51.x, e51.y))(e50);\n return n2 \u003c= t2 || n2 \u003c= LU ? e50 : jU(e50, t2 / n2);\n};\nvar WU = (e50, t2 = 0) =\u003e ({ minX: e50.center.x - e50.width / 2 - t2, maxX: e50.center.x + e50.width / 2 + t2, minY: e50.center.y - e50.height / 2 - t2, maxY: e50.center.y + e50.height / 2 + t2 });\nvar GU = (e50, t2, n2 = 0) =\u003e {\n const o3 = WU(t2, n2);\n return e50.x \u003e= o3.minX \u0026\u0026 e50.x \u003c= o3.maxX \u0026\u0026 e50.y \u003e= o3.minY \u0026\u0026 e50.y \u003c= o3.maxY;\n};\nvar UU = (e50, t2, n2) =\u003e {\n if (e50.regionId) {\n const n3 = t2.findIndex((t3) =\u003e t3.capacityMeshNodeId === e50.regionId);\n if (n3 !== -1)\n return n3;\n }\n const o3 = [...e50.route.map(({ x: e51, y: t3 }) =\u003e ({ x: e51, y: t3 })), ...e50.vias.map(({ x: e51, y: t3 }) =\u003e ({ x: e51, y: t3 }))];\n let i3 = -1, r3 = Number.POSITIVE_INFINITY;\n for (let e51 = 0;e51 \u003c t2.length; e51++) {\n const s2 = t2[e51];\n if (!s2 || !o3.every((e52) =\u003e GU(e52, s2, n2)))\n continue;\n const a3 = s2.width * s2.height;\n a3 \u003c r3 \u0026\u0026 (r3 = a3, i3 = e51);\n }\n return i3;\n};\nvar ZU = (e50, t2, n2, o3) =\u003e {\n const i3 = ((e51, t3, n3) =\u003e {\n const o4 = Math.min(Math.abs(e51.originalX - n3.minX), Math.abs(n3.maxX - e51.originalX)), i4 = Math.min(Math.abs(e51.originalY - n3.minY), Math.abs(n3.maxY - e51.originalY));\n if (Math.abs(o4 - i4) \u003c= LU)\n return Math.abs(t3.x - e51.x) \u003e= Math.abs(t3.y - e51.y) ? \"y\" : \"x\";\n return o4 \u003c i4 ? \"y\" : \"x\";\n })(e50, t2, n2);\n return VU(i3 === \"x\" ? { x: 1.1 * (e50.x - t2.x) * o3, y: 0 } : { x: 0, y: 1.1 * (e50.y - t2.y) * o3 }, 0.06 * o3);\n};\nvar qU = (e50, t2, n2, o3, i3 = 3.5, r3 = 0.2, s2 = 0.4) =\u003e {\n const a3 = Math.max(e50, 0);\n if (a3 \u003e= s2)\n return 0;\n const c3 = a3 / r3;\n if (c3 \u003c 1) {\n const e51 = 1 - c3;\n return t2 * e51 ** 3 * (1 + e51 * i3);\n }\n const l3 = (a3 - r3) / Math.max(s2 - r3, LU), h2 = t2 * n2 * Math.exp(-l3 * o3);\n return h2 \u003c 0.00001 ? 0 : h2;\n};\nvar JU = (e50, t2) =\u003e {\n const n2 = e50.boundaryPadding \u003e 0 ? 0.001 : 0, o3 = t2.minX + e50.boundaryPadding + n2, i3 = t2.maxX - e50.boundaryPadding - n2, r3 = t2.minY + e50.boundaryPadding + n2, s2 = t2.maxY - e50.boundaryPadding - n2;\n e50.x = HU(e50.x, o3, i3), e50.y = HU(e50.y, r3, s2);\n};\nvar QU = (e50, t2) =\u003e {\n for (const n2 of e50)\n for (const e51 of n2.nodes)\n JU(e51, t2);\n};\nvar KU = (e50) =\u003e e50.kind === \"via\" ? 0.4 : 0.25;\nvar eZ = (e50) =\u003e (e50.kind, 0.5);\nvar tZ = (e50) =\u003e e50.kind === \"via\" ? 12 : 3.5;\nvar nZ = (e50) =\u003e e50.kind === \"via\" ? 0.18 : 0.06;\nvar oZ = (e50) =\u003e e50.kind === \"via\" ? 1.35 : 1.05;\nvar iZ = (e50, t2) =\u003e e50.kind === \"via\" ? 3 * t2 : t2;\nvar rZ = (e50, t2, n2, o3) =\u003e {\n const i3 = 2 * t2;\n e50[i3] = (e50[i3] ?? 0) + n2, e50[i3 + 1] = (e50[i3 + 1] ?? 0) + o3;\n};\nvar sZ = (e50, t2, n2, o3, i3, r3) =\u003e {\n if (e50.fixed || rZ(o3, e50.node.forceIndex, t2, n2), !e50.fixed \u0026\u0026 i3 \u0026\u0026 r3 !== undefined) {\n const e51 = 2 * r3;\n i3[e51] = (i3[e51] ?? 0) + t2, i3[e51 + 1] = (i3[e51 + 1] ?? 0) + n2;\n }\n};\nvar aZ = (e50, t2, n2, o3, i3 = 0.5) =\u003e {\n const { startNode: r3, endNode: s2 } = e50, a3 = 1 - XU(i3), c3 = XU(i3), l3 = r3.fixed ? 0 : a3, h2 = s2.fixed ? 0 : c3, d2 = l3 + h2;\n if (!(d2 \u003c= LU)) {\n if (!r3.fixed \u0026\u0026 l3 \u003e 0) {\n const e51 = l3 / d2;\n rZ(o3, r3.forceIndex, t2 * e51, n2 * e51);\n }\n if (!s2.fixed \u0026\u0026 h2 \u003e 0) {\n const e51 = h2 / d2;\n rZ(o3, s2.forceIndex, t2 * e51, n2 * e51);\n }\n }\n};\nvar cZ = (e50, t2, n2, o3, i3) =\u003e {\n if (t2.fixed)\n return { x: 0, y: 0 };\n const { minX: r3, maxX: s2, minY: a3, maxY: c3 } = e50, l3 = ((e51) =\u003e e51.kind === \"via\" ? 0.65 : EU)(t2), h2 = ((e51) =\u003e e51.kind === \"via\" ? OU : AU)(t2), d2 = ((e51) =\u003e e51.kind === \"via\" ? 0.015 : 0.08)(t2), u2 = ((e51) =\u003e e51.kind === \"via\" ? 80 : 20)(t2), p3 = tZ(t2);\n return { x: qU(n2 - r3, kU, d2, u2, p3, l3, h2) * i3 - qU(s2 - n2, kU, d2, u2, p3, l3, h2) * i3, y: qU(o3 - a3, kU, d2, u2, p3, l3, h2) * i3 - qU(c3 - o3, kU, d2, u2, p3, l3, h2) * i3 };\n};\nvar lZ = (e50) =\u003e {\n if (e50.length === 0)\n return null;\n const t2 = new E2(e50.length);\n for (const n2 of e50) {\n const { startNode: e51, endNode: o3 } = n2;\n t2.add(Math.min(e51.x, o3.x), Math.min(e51.y, o3.y), Math.max(e51.x, o3.x), Math.max(e51.y, o3.y));\n }\n return t2.finish(), { index: t2, segments: e50 };\n};\nvar hZ = (e50) =\u003e {\n const t2 = new Map, n2 = new Map;\n for (const t3 of e50) {\n const e51 = n2.get(t3.z) ?? [];\n e51.push(t3), n2.set(t3.z, e51);\n }\n for (const [e51, o3] of n2) {\n const n3 = lZ(o3);\n n3 \u0026\u0026 t2.set(e51, n3);\n }\n return { byLayer: t2 };\n};\nvar dZ = (e50, t2, n2, o3, i3) =\u003e {\n const r3 = (e51) =\u003e ({ candidateIndexes: e51.index.search(n2 - i3, o3 - i3, n2 + i3, o3 + i3), segments: e51.segments });\n if (t2.kind === \"point\") {\n const n3 = e50.byLayer.get(t2.z);\n return n3 ? [r3(n3)] : [];\n }\n const s2 = [];\n for (const t3 of e50.byLayer.values())\n s2.push(r3(t3));\n return s2;\n};\nvar uZ = (e50) =\u003e {\n const t2 = [];\n for (let n2 = 0;n2 \u003c e50.length; n2 += 1) {\n const o3 = e50[n2];\n if (!o3)\n continue;\n const i3 = new Set;\n for (let e51 = 0;e51 \u003c o3.route.length - 1; e51 += 1) {\n const r3 = o3.route[e51], s2 = o3.route[e51 + 1];\n if (!r3 || !s2)\n continue;\n if (r3.z === s2.z || !pU(r3, s2))\n continue;\n const a3 = [e51, e51 + 1];\n for (let t3 = e51 - 1;t3 \u003e= 0; t3 -= 1) {\n const e52 = o3.route[t3];\n if (!e52 || !pU(e52, r3))\n break;\n a3.push(t3);\n }\n for (let t3 = e51 + 2;t3 \u003c o3.route.length; t3 += 1) {\n const e52 = o3.route[t3];\n if (!e52 || !pU(e52, r3))\n break;\n a3.push(t3);\n }\n const c3 = [...new Set(a3)].sort((e52, t3) =\u003e e52 - t3);\n let l3 = false;\n for (const e52 of c3)\n if (i3.has(e52)) {\n l3 = true;\n break;\n }\n if (!l3) {\n for (const e52 of c3)\n i3.add(e52);\n t2.push({ routeIndex: n2, rootConnectionName: dU(o3), pointIndexes: c3, x: r3.x, y: r3.y, radius: (o3.viaDiameter ?? 0.3) / 2, movable: !TU(o3.route.length, c3) });\n }\n }\n }\n return t2;\n};\nvar pZ = (e50) =\u003e {\n const { routes: t2, via: n2, dx: o3, dy: i3, node: r3 } = e50;\n if (!n2.movable)\n return false;\n n2.x += o3, n2.y += i3, ((e51, t3) =\u003e {\n const n3 = mU(t3, e51.radius + LU);\n e51.x = HU(e51.x, n3.minX, n3.maxX), e51.y = HU(e51.y, n3.minY, n3.maxY);\n })(n2, r3);\n const s2 = t2[n2.routeIndex];\n if (!s2)\n return false;\n for (const e51 of n2.pointIndexes) {\n const t3 = s2.route[e51];\n t3 \u0026\u0026 (t3.x = n2.x, t3.y = n2.y);\n }\n return true;\n};\nvar mZ = (e50) =\u003e {\n const { routes: t2, node: n2, vias: o3 } = e50;\n let i3 = false;\n for (let e51 = 0;e51 \u003c o3.length; e51 += 1) {\n const r3 = o3[e51];\n if (r3)\n for (let s2 = e51 + 1;s2 \u003c o3.length; s2 += 1) {\n const a3 = o3[s2];\n if (!a3)\n continue;\n const c3 = r3.radius + a3.radius + 0.1 + zU, l3 = r3.x - a3.x, h2 = r3.y - a3.y, d2 = gU(l3, h2), u2 = c3 - d2;\n if (u2 \u003c= 0)\n continue;\n const p3 = 1.61803398875 * (97 * e51 + 13 * s2), m2 = d2 \u003e LU ? l3 / d2 : Math.cos(p3), g2 = d2 \u003e LU ? h2 / d2 : Math.sin(p3), f2 = Number(r3.movable) + Number(a3.movable);\n if (f2 === 0)\n continue;\n const _2 = Math.min(0.04, u2 / f2);\n i3 = pZ({ routes: t2, via: r3, dx: m2 * _2, dy: g2 * _2, node: n2 }) || i3, i3 = pZ({ routes: t2, via: a3, dx: -m2 * _2, dy: -g2 * _2, node: n2 }) || i3;\n }\n }\n return i3;\n};\nvar gZ = (e50) =\u003e {\n const { routes: t2, node: n2, vias: o3, segments: i3 } = e50;\n let r3 = false;\n for (let e51 = 0;e51 \u003c o3.length; e51 += 1) {\n const s2 = o3[e51];\n if (s2?.movable)\n for (const o4 of i3) {\n if (s2.rootConnectionName === o4.rootConnectionName)\n continue;\n const i4 = xU(s2, o4), a3 = s2.x - i4.x, c3 = s2.y - i4.y, l3 = gU(a3, c3), h2 = s2.radius + o4.traceRadius + 0.1 + zU - l3;\n if (h2 \u003c= 0)\n continue;\n const d2 = o4.end.x - o4.start.x, u2 = o4.end.y - o4.start.y, p3 = gU(d2, u2), m2 = e51 % 2 == 0 ? 1 : -1, g2 = l3 \u003e LU ? a3 / l3 : p3 \u003e LU ? -u2 / p3 * m2 : 1, f2 = l3 \u003e LU ? c3 / l3 : p3 \u003e LU ? d2 / p3 * m2 : 0, _2 = Math.min(0.04, h2);\n r3 = pZ({ routes: t2, via: s2, dx: g2 * _2, dy: f2 * _2, node: n2 }) || r3;\n }\n }\n return r3;\n};\nvar fZ = (e50) =\u003e {\n const { routes: t2, routeIndex: n2, pointIndex: o3, dx: i3, dy: r3, node: s2 } = e50, a3 = t2[n2];\n if (!a3 || o3 \u003c= 0 || o3 \u003e= a3.route.length - 1)\n return false;\n const c3 = ((e51, t3, n3 = 0.001) =\u003e {\n const o4 = e51[t3];\n if (!o4)\n return [];\n const i4 = [t3];\n for (let r4 = t3 - 1;r4 \u003e= 0; r4 -= 1) {\n const t4 = e51[r4];\n if (!t4 || !pU(t4, o4, n3))\n break;\n i4.push(r4);\n }\n for (let r4 = t3 + 1;r4 \u003c e51.length; r4 += 1) {\n const t4 = e51[r4];\n if (!t4 || !pU(t4, o4, n3))\n break;\n i4.push(r4);\n }\n return [...new Set(i4)];\n })(a3.route, o3);\n if (TU(a3.route.length, c3))\n return false;\n const l3 = mU(s2, LU);\n let h2 = false;\n for (const e51 of c3) {\n const t3 = a3.route[e51];\n t3 \u0026\u0026 (t3.x = HU(t3.x + i3, l3.minX, l3.maxX), t3.y = HU(t3.y + r3, l3.minY, l3.maxY), h2 = true);\n }\n return h2;\n};\nvar _Z = (e50) =\u003e {\n const { routes: t2, segment: n2, dx: o3, dy: i3, node: r3, t: s2 } = e50, a3 = 1 - XU(s2), c3 = XU(s2), l3 = fZ({ routes: t2, routeIndex: n2.routeIndex, pointIndex: n2.startIndex, dx: o3 * a3, dy: i3 * a3, node: r3 }), h2 = fZ({ routes: t2, routeIndex: n2.routeIndex, pointIndex: n2.endIndex, dx: o3 * c3, dy: i3 * c3, node: r3 });\n return l3 || h2;\n};\nvar yZ = (e50) =\u003e {\n const { routes: t2, node: n2, segments: o3, movableRouteIndexes: i3 } = e50;\n let r3 = false;\n for (let e51 = 0;e51 \u003c o3.length; e51 += 1) {\n const s2 = o3[e51];\n if (s2)\n for (let a3 = e51 + 1;a3 \u003c o3.length; a3 += 1) {\n const c3 = o3[a3];\n if (!c3 || s2.z !== c3.z || s2.rootConnectionName === c3.rootConnectionName)\n continue;\n const l3 = s2.traceRadius + c3.traceRadius + 0.1 + zU;\n if (Math.max(s2.start.x, s2.end.x) + l3 \u003c= Math.min(c3.start.x, c3.end.x) || Math.max(c3.start.x, c3.end.x) + l3 \u003c= Math.min(s2.start.x, s2.end.x) || Math.max(s2.start.y, s2.end.y) + l3 \u003c= Math.min(c3.start.y, c3.end.y) || Math.max(c3.start.y, c3.end.y) + l3 \u003c= Math.min(s2.start.y, s2.end.y))\n continue;\n const [h2] = vU(s2, c3);\n if (!h2)\n continue;\n const d2 = h2.leftPoint.x - h2.rightPoint.x, u2 = h2.leftPoint.y - h2.rightPoint.y, p3 = gU(d2, u2), m2 = l3 - p3;\n if (m2 \u003c= 0)\n continue;\n const g2 = !i3 || i3.has(s2.routeIndex), f2 = !i3 || i3.has(c3.routeIndex), _2 = Number(g2) + Number(f2);\n if (_2 === 0)\n continue;\n const y2 = s2.end.x - s2.start.x, b2 = s2.end.y - s2.start.y, x2 = gU(y2, b2), v2 = (e51 + a3) % 2 == 0 ? 1 : -1, I2 = p3 \u003e LU ? d2 / p3 : x2 \u003e LU ? -b2 / x2 * v2 : 1, S2 = p3 \u003e LU ? u2 / p3 : x2 \u003e LU ? y2 / x2 * v2 : 0, C = Math.min(0.025, m2 / _2);\n g2 \u0026\u0026 (r3 = _Z({ routes: t2, segment: s2, dx: I2 * C, dy: S2 * C, node: n2, t: h2.leftT }) || r3), f2 \u0026\u0026 (r3 = _Z({ routes: t2, segment: c3, dx: -I2 * C, dy: -S2 * C, node: n2, t: h2.rightT }) || r3);\n }\n }\n return r3;\n};\nvar bZ = (e50, t2) =\u003e {\n for (let n2 = 0;n2 \u003c 10; n2 += 1) {\n const n3 = uZ(t2), o3 = bU(t2), i3 = mZ({ routes: t2, node: e50, vias: n3 }), r3 = gZ({ routes: t2, node: e50, vias: n3, segments: o3 }), s2 = yZ({ routes: t2, node: e50, segments: o3 });\n if (!i3 \u0026\u0026 !r3 \u0026\u0026 !s2)\n break;\n }\n for (const e51 of t2)\n e51.vias = uU(e51);\n return t2;\n};\nvar xZ = (e50, t2, n2) =\u003e {\n for (let o3 = 0;o3 \u003c 10; o3 += 1) {\n if (!yZ({ routes: t2, node: e50, segments: bU(t2), movableRouteIndexes: n2 }))\n break;\n }\n for (const e51 of n2) {\n const n3 = t2[e51];\n n3 \u0026\u0026 (n3.vias = uU(n3));\n }\n return t2;\n};\nvar vZ = (e50, t2, n2, o3, i3, r3 = 3, s2 = 0.02) =\u003e {\n for (let a3 = 0;a3 \u003c r3; a3 += 1) {\n i3.fill(0);\n const r4 = hZ(o3);\n for (let e51 = 0;e51 \u003c n2.length; e51 += 1) {\n const t3 = n2[e51];\n if (!t3 || t3.kind !== \"via\")\n continue;\n const o4 = t3.node;\n for (let r5 = e51 + 1;r5 \u003c n2.length; r5 += 1) {\n const c3 = n2[r5];\n if (!c3 || c3.kind !== \"via\")\n continue;\n if (t3.rootConnectionName === c3.rootConnectionName)\n continue;\n const l3 = c3.node, h2 = o4.x - l3.x, d2 = o4.y - l3.y;\n if (Math.abs(h2) \u003e= EU || Math.abs(d2) \u003e= EU)\n continue;\n const u2 = gU(h2, d2), p3 = EU - u2;\n if (p3 \u003c= 0)\n continue;\n let m2 = 0, g2 = 0;\n if (u2 \u003e LU) {\n const e52 = 1 / u2;\n m2 = h2 * e52, g2 = d2 * e52;\n } else {\n const t4 = 1.61803398875 * (1009 * a3 + 97 * e51 + 13 * r5);\n m2 = Math.cos(t4), g2 = Math.sin(t4);\n }\n const f2 = Math.min(s2, 0.9 * p3), _2 = m2 * f2, y2 = g2 * f2;\n sZ(t3, _2, y2, i3), sZ(c3, -_2, -y2, i3);\n }\n }\n for (let e51 = 0;e51 \u003c n2.length; e51 += 1) {\n const t3 = n2[e51];\n if (!t3)\n continue;\n const o4 = t3.node, c3 = KU(t3), l3 = dZ(r4, t3, o4.x, o4.y, c3);\n for (const n3 of l3)\n for (const r5 of n3.candidateIndexes) {\n const l4 = n3.segments[r5];\n if (!l4)\n continue;\n if (t3.rootConnectionName === l4.rootConnectionName)\n continue;\n const { startNode: h2, endNode: d2 } = l4, u2 = d2.x - h2.x, p3 = d2.y - h2.y, m2 = u2 * u2 + p3 * p3;\n if (m2 \u003c= LU)\n continue;\n const g2 = o4.x - h2.x, f2 = o4.y - h2.y, _2 = XU((g2 * u2 + f2 * p3) / m2), y2 = h2.x + u2 * _2, b2 = h2.y + p3 * _2, x2 = o4.x - y2, v2 = o4.y - b2, I2 = gU(x2, v2), S2 = c3 - I2;\n if (S2 \u003c= 0)\n continue;\n const C = 1009 * a3 + 97 * e51 + 13 * l4.obstacleIndex;\n let P = 0, M = 0;\n if (I2 \u003e LU) {\n const e52 = 1 / I2;\n P = x2 * e52, M = v2 * e52;\n } else {\n const e52 = -p3, t4 = u2, n4 = gU(e52, t4);\n if (n4 \u003e LU) {\n const o5 = (C % 2 == 0 ? 1 : -1) / n4;\n P = e52 * o5, M = t4 * o5;\n } else {\n const e53 = 1.61803398875 * C;\n P = Math.cos(e53), M = Math.sin(e53);\n }\n }\n const w = Math.min(iZ(t3, s2), S2 * oZ(t3)), N = P * w, R2 = M * w;\n sZ(t3, N, R2, i3), aZ(l4, -N, -R2, i3, _2);\n }\n }\n for (let e51 = 0;e51 \u003c t2.length; e51 += 1) {\n const n3 = t2[e51];\n if (n3)\n for (let e52 = 0;e52 \u003c n3.nodes.length; e52 += 1) {\n const t3 = n3.nodes[e52];\n if (!t3 || t3.fixed)\n continue;\n const o4 = 2 * t3.forceIndex;\n let r5 = i3[o4] ?? 0, a4 = i3[o4 + 1] ?? 0;\n const c3 = gU(r5, a4);\n if (c3 \u003e s2 \u0026\u0026 c3 \u003e LU) {\n const e53 = s2 / c3;\n r5 *= e53, a4 *= e53;\n }\n t3.x += r5, t3.y += a4;\n }\n }\n QU(t2, e50);\n }\n};\nvar IZ = (e50, t2, n2, o3) =\u003e {\n const { mutableRoutes: i3, totalNodeCount: r3 } = ((e51) =\u003e {\n let t3 = 0;\n return { mutableRoutes: e51.map((e52) =\u003e {\n const n3 = [], o4 = new Int32Array(e52.route.length);\n o4.fill(-1);\n for (let i4 = 0;i4 \u003c e52.route.length; i4 += 1) {\n const r4 = e52.route[i4];\n if (!r4)\n continue;\n const s3 = e52.route[i4 - 1], a4 = n3.at(-1), c4 = n3.length - 1;\n a4 \u0026\u0026 s3 \u0026\u0026 s3.x === r4.x \u0026\u0026 s3.y === r4.y ? (s3.z !== r4.z \u0026\u0026 (a4.boundaryPadding = Math.max(a4.boundaryPadding, e52.viaDiameter / 2)), a4.pointIndexes.push(i4), a4.fixed ||= RU(e52.route.length, i4), o4[i4] = c4) : (n3.push({ x: r4.x, y: r4.y, originalX: r4.x, originalY: r4.y, boundaryPadding: 0, pointIndexes: [i4], fixed: RU(e52.route.length, i4), forceIndex: t3 }), o4[i4] = n3.length - 1, t3 += 1);\n }\n return { route: e52, rootConnectionName: e52.rootConnectionName ?? e52.connectionName, nodes: n3, pointNodeIndexes: o4 };\n }), totalNodeCount: t3 };\n })(t2), s2 = ((e51) =\u003e {\n const t3 = [];\n for (let n3 = 0;n3 \u003c e51.length; n3 += 1) {\n const o4 = e51[n3];\n if (o4)\n for (let e52 = 0;e52 \u003c o4.nodes.length; e52 += 1) {\n const i4 = o4.nodes[e52], r4 = i4?.pointIndexes[0], s3 = r4 === undefined ? undefined : o4.route.route[r4];\n i4 \u0026\u0026 s3 \u0026\u0026 (i4.pointIndexes.length \u003e 1 ? t3.push({ kind: \"via\", routeIndex: n3, rootConnectionName: o4.rootConnectionName, node: i4, fixed: i4.fixed }) : t3.push({ kind: \"point\", routeIndex: n3, rootConnectionName: o4.rootConnectionName, node: i4, z: s3.z, fixed: i4.fixed }));\n }\n }\n return t3;\n })(i3), a3 = ((e51) =\u003e {\n const t3 = [];\n for (let n3 = 0;n3 \u003c e51.length; n3 += 1) {\n const o4 = e51[n3];\n if (o4)\n for (let e52 = 0;e52 \u003c o4.nodes.length - 1; e52 += 1) {\n const n4 = o4.nodes[e52], i4 = o4.nodes[e52 + 1], r4 = n4?.pointIndexes[0], s3 = r4 === undefined ? undefined : o4.route.route[r4];\n n4 \u0026\u0026 i4 \u0026\u0026 s3 \u0026\u0026 t3.push({ obstacleIndex: t3.length, rootConnectionName: o4.rootConnectionName, z: s3.z, startNode: n4, endNode: i4 });\n }\n }\n return t3;\n })(i3), c3 = new Float64Array(2 * r3), l3 = new Float64Array(2 * r3), h2 = o3?.includeForceVectors ?? true;\n QU(i3, e50);\n let d2 = [];\n for (let t3 = 0;t3 \u003c n2; t3 += 1) {\n const o4 = n2 \u003c= 1 ? 0 : t3 / Math.max(n2 - 1, 1), r4 = 0.25 + 0.75 * (1 - o4), u3 = 1 - o4, p3 = h2 \u0026\u0026 t3 === n2 - 1, m2 = p3 ? new Float64Array(2 * s2.length) : undefined;\n c3.fill(0);\n for (let e51 = 0;e51 \u003c s2.length; e51 += 1) {\n const t4 = s2[e51];\n if (!t4 || t4.kind !== \"via\")\n continue;\n const n3 = t4.node;\n for (let o5 = e51 + 1;o5 \u003c s2.length; o5 += 1) {\n const i4 = s2[o5];\n if (!i4 || i4.kind !== \"via\")\n continue;\n if (t4.rootConnectionName === i4.rootConnectionName)\n continue;\n const a4 = i4.node, l4 = n3.x - a4.x, h3 = n3.y - a4.y;\n if (Math.abs(l4) \u003e= AU || Math.abs(h3) \u003e= AU)\n continue;\n const d3 = gU(l4, h3);\n let u4 = 0, p4 = 0;\n if (d3 \u003e LU) {\n const e52 = 1 / d3;\n u4 = l4 * e52, p4 = h3 * e52;\n } else {\n const t5 = 1.61803398875 * (97 * e51 + 13 * o5);\n u4 = Math.cos(t5), p4 = Math.sin(t5);\n }\n const g3 = qU(d3, 0.034, 0.08, 18) * r4;\n if (g3 \u003c= 0)\n continue;\n const f2 = u4 * g3, _2 = p4 * g3;\n sZ(t4, f2, _2, c3, m2, e51), sZ(i4, -f2, -_2, c3, m2, o5);\n }\n }\n const g2 = hZ(a3);\n for (let e51 = 0;e51 \u003c s2.length; e51 += 1) {\n const t4 = s2[e51];\n if (!t4)\n continue;\n const n3 = t4.node, o5 = eZ(t4), i4 = dZ(g2, t4, n3.x, n3.y, o5);\n for (const s3 of i4)\n for (const i5 of s3.candidateIndexes) {\n const a4 = s3.segments[i5];\n if (!a4)\n continue;\n if (t4.rootConnectionName === a4.rootConnectionName)\n continue;\n const { startNode: l4, endNode: h3 } = a4, d3 = h3.x - l4.x, u4 = h3.y - l4.y, p4 = d3 * d3 + u4 * u4;\n if (p4 \u003c= LU)\n continue;\n const g3 = n3.x - l4.x, f2 = n3.y - l4.y, _2 = XU((g3 * d3 + f2 * u4) / p4), y2 = l4.x + d3 * _2, b2 = l4.y + u4 * _2, x2 = n3.x - y2, v2 = n3.y - b2, I2 = gU(x2, v2), S2 = 97 * e51 + 13 * a4.obstacleIndex;\n let C = 0, P = 0;\n if (I2 \u003e LU) {\n const e52 = 1 / I2;\n C = x2 * e52, P = v2 * e52;\n } else {\n const e52 = -u4, t5 = d3, n4 = gU(e52, t5);\n if (n4 \u003e LU) {\n const o6 = (S2 % 2 == 0 ? 1 : -1) / n4;\n C = e52 * o6, P = t5 * o6;\n } else {\n const e53 = 1.61803398875 * S2;\n C = Math.cos(e53), P = Math.sin(e53);\n }\n }\n const M = qU(I2, nZ(t4), 0.08, 18, tZ(t4), KU(t4), o5) * r4;\n if (M \u003c= 0)\n continue;\n const w = C * M, N = P * M;\n sZ(t4, w, N, c3, m2, e51), aZ(a4, -w, -N, c3, _2);\n }\n }\n p3 \u0026\u0026 (d2 = new Array(s2.length));\n for (let t4 = 0;t4 \u003c s2.length; t4 += 1) {\n const n3 = s2[t4];\n if (!n3)\n continue;\n const o5 = n3.node, i4 = cZ(e50, n3, o5.x, o5.y, r4);\n if (sZ(n3, i4.x, i4.y, c3, m2, t4), p3 \u0026\u0026 m2) {\n const e51 = 2 * t4;\n d2[t4] = { kind: n3.kind, routeIndex: n3.routeIndex, rootConnectionName: n3.rootConnectionName, x: o5.x, y: o5.y, dx: m2[e51] ?? 0, dy: m2[e51 + 1] ?? 0 };\n }\n }\n for (let t4 = 0;t4 \u003c i3.length; t4 += 1) {\n const n3 = i3[t4];\n if (!n3)\n continue;\n const o5 = n3.nodes.length - 2;\n for (let t5 = 0;t5 \u003c n3.nodes.length; t5 += 1) {\n const i4 = n3.nodes[t5];\n if (!i4 || i4.fixed)\n continue;\n const s3 = 2 * i4.forceIndex;\n let a4 = (c3[s3] ?? 0) + 0.14 * (i4.originalX - i4.x), l4 = (c3[s3 + 1] ?? 0) + 0.14 * (i4.originalY - i4.y), h3 = 0, d3 = 0, p4 = 0, m3 = 0;\n const g3 = n3.nodes[t5 - 1], f2 = n3.nodes[t5 + 1];\n if (g3 || f2) {\n let e51 = 0, t6 = 0, n4 = 0;\n if (g3 \u0026\u0026 (e51 += g3.x, t6 += g3.y, n4 += 1), f2 \u0026\u0026 (e51 += f2.x, t6 += f2.y, n4 += 1), n4 \u003e 0) {\n const o6 = 1 / n4;\n a4 += 0.22 * (e51 * o6 - i4.x), l4 += 0.22 * (t6 * o6 - i4.y);\n }\n }\n if (g3 \u0026\u0026 f2 \u0026\u0026 u3 \u003e 0) {\n const e51 = FU(f2, g3), t6 = $U(e51, e51);\n if (t6 \u003e LU) {\n const n4 = XU($U(FU(i4, g3), e51) / t6), o6 = YU(g3, f2, n4), r5 = VU(jU(FU(o6, i4), 0.55 * u3), 0.02 * u3);\n h3 = r5.x, d3 = r5.y;\n }\n }\n if (u3 \u003e 0) {\n if (t5 === 1 \u0026\u0026 g3?.fixed) {\n const t6 = ZU(g3, i4, e50, u3);\n p4 += t6.x, m3 += t6.y;\n }\n if (t5 === o5 \u0026\u0026 f2?.fixed) {\n const t6 = ZU(f2, i4, e50, u3);\n p4 += t6.x, m3 += t6.y;\n }\n }\n let _2 = 0.85 * a4 * r4, y2 = 0.85 * l4 * r4;\n const b2 = gU(_2, y2), x2 = 0.012 * r4;\n if (b2 \u003e x2 \u0026\u0026 b2 \u003e LU) {\n const e51 = x2 / b2;\n _2 *= e51, y2 *= e51;\n }\n i4.x += _2 + h3 + p4, i4.y += y2 + d3 + m3;\n }\n }\n QU(i3, e50), vZ(e50, i3, s2, a3, l3, 3, 0.02);\n }\n vZ(e50, i3, s2, a3, l3, 8, 0.03);\n const u2 = ((e51) =\u003e e51.map(({ route: e52, nodes: t3, pointNodeIndexes: n3 }) =\u003e {\n const o4 = e52.route.map((e53, o5) =\u003e {\n const i5 = n3[o5] ?? -1, r4 = i5 \u003e= 0 ? t3[i5] : undefined;\n return r4 ? { ...e53, x: BU(r4.x), y: BU(r4.y) } : e53;\n }), i4 = { ...e52, route: o4, vias: [] };\n return i4.vias = uU(i4), i4;\n }))(i3);\n return { routes: u2, forceVectors: d2, stepsCompleted: n2 };\n};\nvar SZ = class extends cU {\n sampleEntries;\n originalHdRoutes;\n originalNodeWithPortPoints;\n colorMap;\n totalStepsPerNode;\n nodeAssignmentMargin;\n improvedRoutesByIndex = new Map;\n activeSampleIndex = 0;\n latestVisualization = {};\n constructor(e50) {\n super(), this.originalHdRoutes = e50.hdRoutes, this.originalNodeWithPortPoints = e50.nodeWithPortPoints, this.colorMap = e50.colorMap ?? {}, this.totalStepsPerNode = e50.totalStepsPerNode ?? 60, this.nodeAssignmentMargin = e50.nodeAssignmentMargin ?? 0.2;\n const t2 = new Map;\n for (let n2 = 0;n2 \u003c e50.hdRoutes.length; n2++) {\n const o3 = UU(e50.hdRoutes[n2], e50.nodeWithPortPoints, this.nodeAssignmentMargin);\n if (o3 === -1)\n continue;\n const i3 = t2.get(o3) ?? [];\n i3.push(n2), t2.set(o3, i3);\n }\n this.sampleEntries = Array.from(t2.entries()).map(([t3, n2]) =\u003e ({ node: e50.nodeWithPortPoints[t3], routeIndexes: n2 })), this.MAX_ITERATIONS = Math.max(10 * this.sampleEntries.length, 1000), this.stats = { nodeAssignmentMargin: this.nodeAssignmentMargin, sampleCount: this.sampleEntries.length, improvedNodeCount: 0, improvedRouteCount: 0, totalStepsPerNode: this.totalStepsPerNode };\n }\n getSolverName() {\n return \"HighDensityForceImproveSolver\";\n }\n getConstructorParams() {\n return [{ nodeWithPortPoints: this.originalNodeWithPortPoints, hdRoutes: this.originalHdRoutes, totalStepsPerNode: this.totalStepsPerNode, nodeAssignmentMargin: this.nodeAssignmentMargin, colorMap: this.colorMap }];\n }\n _step() {\n const e50 = this.sampleEntries[this.activeSampleIndex];\n if (!e50)\n return void (this.solved = true);\n const t2 = WU(e50.node), n2 = e50.routeIndexes.map((e51) =\u003e this.originalHdRoutes[e51]), o3 = IZ(t2, n2, this.totalStepsPerNode, { includeForceVectors: true });\n bZ(e50.node, o3.routes);\n const i3 = wU(n2, o3.routes);\n let r3 = i3.length === 0 ? o3 : IZ(t2, ((e51, t3) =\u003e {\n const { routes: n3, node: o4, selectors: i4 } = e51, r4 = structuredClone(n3), s2 = bU(n3), a3 = SU(s2), c3 = i4.flatMap((e52) =\u003e {\n const t4 = a3[e52.leftRouteIndex]?.[e52.leftStartPointIndex], n4 = a3[e52.rightRouteIndex]?.[e52.rightStartPointIndex];\n if (!t4 || !n4)\n return [];\n const [o5] = vU(t4, n4);\n if (!o5)\n return [];\n const i5 = o5.leftPoint.x - o5.rightPoint.x, r5 = o5.leftPoint.y - o5.rightPoint.y, s3 = gU(i5, r5);\n return s3 \u003c= IU ? [] : [{ selector: e52, directionX: i5 / s3, directionY: r5 / s3, requiredDistance: t4.traceRadius + n4.traceRadius + 0.015 }];\n });\n for (let e52 = 0;e52 \u003c 3; e52 += 1) {\n const e53 = bU(r4), n4 = SU(e53);\n for (const e54 of c3) {\n const i5 = n4[e54.selector.leftRouteIndex]?.[e54.selector.leftStartPointIndex], s3 = n4[e54.selector.rightRouteIndex]?.[e54.selector.rightStartPointIndex];\n if (!i5 || !s3)\n continue;\n const [a4] = vU(i5, s3);\n if (!a4)\n continue;\n const c4 = (a4.leftPoint.x - a4.rightPoint.x) * e54.directionX + (a4.leftPoint.y - a4.rightPoint.y) * e54.directionY, l3 = e54.requiredDistance - c4;\n if (l3 \u003c= 0)\n continue;\n const h2 = Math.min(0.025, l3 / 2);\n t3({ routes: r4, segment: i5, dx: e54.directionX * h2, dy: e54.directionY * h2, node: o4, t: a4.leftT }), t3({ routes: r4, segment: s3, dx: -e54.directionX * h2, dy: -e54.directionY * h2, node: o4, t: a4.rightT });\n }\n }\n for (const e52 of r4)\n e52.vias = uU(e52);\n return r4;\n })({ routes: n2, node: e50.node, selectors: i3 }, _Z), this.totalStepsPerNode, { includeForceVectors: true });\n if (r3 !== o3) {\n bZ(e50.node, r3.routes);\n const t3 = wU(n2, r3.routes);\n if (t3.length \u003e 0) {\n const o4 = ((e51, t4) =\u003e {\n const { originalRoutes: n3, guardedRoutes: o5, node: i4, crossingSelectors: r4, protectedSelectors: s2 } = e51, a3 = SU(bU(n3)), c3 = SU(bU(o5)), l3 = NU(o5), h2 = s2.map(({ leftRouteIndex: e52, rightRouteIndex: t5 }) =\u003e CU(e52, t5)), d2 = mU(i4, IU);\n for (const e52 of r4) {\n const r5 = c3[e52.leftRouteIndex]?.[e52.leftStartPointIndex], s3 = c3[e52.rightRouteIndex]?.[e52.rightStartPointIndex];\n if (!r5 || !s3)\n continue;\n const [u2] = vU(r5, s3);\n if (!(!u2 || gU(u2.leftPoint.x - u2.rightPoint.x, u2.leftPoint.y - u2.rightPoint.y) \u003e IU || u2.leftT \u003c= IU || u2.leftT \u003e= 0.999999 || u2.rightT \u003c= IU || u2.rightT \u003e= 0.999999))\n for (const r6 of [\"right\", \"left\"]) {\n const s4 = r6 === \"left\" ? e52.leftRouteIndex : e52.rightRouteIndex, u3 = r6 === \"left\" ? e52.leftStartPointIndex : e52.rightStartPointIndex, p3 = r6 === \"left\" ? e52.rightRouteIndex : e52.leftRouteIndex, m2 = r6 === \"left\" ? e52.rightStartPointIndex : e52.leftStartPointIndex, g2 = n3[s4], f2 = o5[s4], _2 = a3[p3]?.[m2], y2 = c3[p3]?.[m2];\n if (!(g2 \u0026\u0026 f2 \u0026\u0026 _2 \u0026\u0026 y2))\n continue;\n const b2 = g2.route[u3]?.z, x2 = [];\n for (let e53 = u3 - 2;e53 \u003c= u3 + 3; e53 += 1) {\n const t5 = g2.route[e53];\n !t5 || e53 \u003c= 0 || e53 \u003e= g2.route.length - 1 || t5.z !== b2 || [g2.route[e53 - 1], g2.route[e53 + 1]].some((e54) =\u003e e54 \u0026\u0026 e54.z !== t5.z) || x2.push(e53);\n }\n if (x2.length !== 0)\n for (const [e53, n4] of [[_2.start, y2.start], [_2.end, y2.end]])\n for (const r7 of [1.51, 1.25, 1.75, 2]) {\n const a4 = [...o5], c4 = structuredClone(f2);\n a4[s4] = c4;\n let u4 = true;\n for (const t5 of x2) {\n const o6 = g2.route[t5], i5 = c4.route[t5];\n if (!o6 || !i5)\n continue;\n const s5 = n4.x + (o6.x - e53.x) * r7, a5 = n4.y + (o6.y - e53.y) * r7;\n if (s5 \u003c= d2.minX || s5 \u003e= d2.maxX || a5 \u003c= d2.minY || a5 \u003e= d2.maxY) {\n u4 = false;\n break;\n }\n i5.x = s5, i5.y = a5;\n }\n if (!u4)\n continue;\n c4.vias = uU(c4);\n let p4 = a4, m3 = NU(p4);\n const _3 = new Set;\n for (const [e54, t5] of m3)\n PU(l3, [e54, t5]) || (e54 === s4 \u0026\u0026 t5 !== s4 ? _3.add(t5) : t5 === s4 \u0026\u0026 e54 !== s4 \u0026\u0026 _3.add(e54));\n if (_3.size \u003e 0) {\n const e54 = t4(i4, structuredClone(a4), _3), n5 = NU(e54);\n h2.every((e55) =\u003e !PU(n5, e55)) \u0026\u0026 n5.length \u003c m3.length \u0026\u0026 (p4 = e54, m3 = n5);\n }\n if (h2.every((e54) =\u003e !PU(m3, e54)) \u0026\u0026 m3.length \u003c l3.length)\n return p4;\n }\n }\n }\n })({ originalRoutes: n2, guardedRoutes: r3.routes, node: e50.node, crossingSelectors: t3, protectedSelectors: [...i3, ...t3] }, xZ);\n o4 \u0026\u0026 (r3 = { ...r3, routes: o4 });\n }\n }\n for (let t3 = 0;t3 \u003c e50.routeIndexes.length; t3++)\n this.improvedRoutesByIndex.set(e50.routeIndexes[t3], r3.routes[t3]);\n this.latestVisualization = CZ({ node: e50.node, routes: r3.routes, forceVectors: r3.forceVectors, colorMap: this.colorMap }), this.activeSampleIndex += 1, this.stats = { nodeAssignmentMargin: this.nodeAssignmentMargin, sampleCount: this.sampleEntries.length, improvedNodeCount: this.activeSampleIndex, improvedRouteCount: this.improvedRoutesByIndex.size, totalStepsPerNode: this.totalStepsPerNode }, this.activeSampleIndex \u003e= this.sampleEntries.length \u0026\u0026 (this.solved = true);\n }\n getOutput() {\n return this.originalHdRoutes.map((e50, t2) =\u003e this.improvedRoutesByIndex.get(t2) ?? e50);\n }\n visualize() {\n return this.solved ? CZ({ routes: this.getOutput(), colorMap: this.colorMap }) : this.latestVisualization;\n }\n};\nvar CZ = (e50) =\u003e {\n const t2 = [], n2 = [], o3 = [];\n e50.node \u0026\u0026 o3.push({ center: e50.node.center, width: e50.node.width, height: e50.node.height, stroke: \"rgba(14,165,233,0.7)\", fill: \"rgba(14,165,233,0.04)\", label: e50.node.capacityMeshNodeId });\n for (const o4 of e50.routes) {\n const i3 = e50.colorMap?.[o4.connectionName] ?? \"#0ea5e9\";\n for (let e51 = 0;e51 \u003c o4.route.length - 1; e51++) {\n const n3 = o4.route[e51], r3 = o4.route[e51 + 1];\n n3.z === r3.z \u0026\u0026 t2.push({ points: [{ x: n3.x, y: n3.y }, { x: r3.x, y: r3.y }], strokeColor: n3.z === 0 ? i3 : hU(i3, 0.5), strokeWidth: o4.traceThickness, layer: `z${n3.z}`, strokeDash: n3.z !== 0 ? [0.1, 0.3] : undefined });\n }\n for (const e51 of o4.vias)\n n2.push({ center: { x: e51.x, y: e51.y }, radius: o4.viaDiameter / 2, stroke: i3, fill: \"rgba(14,165,233,0.12)\" });\n }\n for (const n3 of e50.forceVectors ?? [])\n t2.push({ points: [{ x: n3.x, y: n3.y }, { x: n3.x + 5 * n3.dx, y: n3.y + 5 * n3.dy }], strokeColor: \"rgba(244,63,94,0.85)\", strokeWidth: 0.06, strokeDash: [0.08, 0.08] });\n return { lines: t2, circles: n2, rects: o3 };\n};\nvar PZ = 0.002;\nvar MZ = class extends ni {\n constructor(e50, t2, n2 = Number.POSITIVE_INFINITY, o3 = 0.010000000000000002) {\n super(), this.nodes = e50, this.maxNodeDimension = t2, this.maxNodeRatio = n2, this.minNodeArea = o3, this.outputNodes = [];\n }\n outputNodes;\n getSolverName() {\n return \"NodeDimensionSubdivisionSolver\";\n }\n getSubdivisionGrid(e50) {\n const t2 = Number.isFinite(this.maxNodeDimension) \u0026\u0026 this.maxNodeDimension \u003e 0, n2 = Number.isFinite(this.maxNodeRatio) \u0026\u0026 this.maxNodeRatio \u003e 0;\n let o3 = t2 ? Math.max(1, Math.ceil(e50.width / this.maxNodeDimension)) : 1, i3 = t2 ? Math.max(1, Math.ceil(e50.height / this.maxNodeDimension)) : 1;\n if (n2 \u0026\u0026 e50.width \u003e 0 \u0026\u0026 e50.height \u003e 0)\n for (;; ) {\n const t3 = e50.width / o3, n3 = e50.height / i3;\n if ((t3 \u003e= n3 ? t3 / n3 : n3 / t3) \u003c= this.maxNodeRatio)\n break;\n t3 \u003e= n3 ? o3++ : i3++;\n }\n return { cols: o3, rows: i3 };\n }\n shouldRemoveNode(e50, t2) {\n const n2 = Number.isFinite(this.minNodeArea) \u0026\u0026 this.minNodeArea \u003e 0;\n if (!Number.isFinite(e50.width) || !Number.isFinite(e50.height))\n return true;\n if (!n2 || e50.width * e50.height \u003e= this.minNodeArea)\n return false;\n if (Math.min(e50.width, e50.height) \u003c 0.002)\n return true;\n if (e50._containsTarget)\n return false;\n if (!Number.isFinite(e50.center.x) || !Number.isFinite(e50.center.y))\n return true;\n const { index: o3, originalNodeIndices: i3 } = t2.bridgeNodeIndex ??= ((e51) =\u003e {\n const t3 = [];\n for (let n4 = 0;n4 \u003c e51.length; n4++) {\n const o4 = e51[n4];\n Number.isFinite(o4.center.x) \u0026\u0026 Number.isFinite(o4.center.y) \u0026\u0026 !Number.isNaN(o4.width) \u0026\u0026 !Number.isNaN(o4.height) \u0026\u0026 t3.push(n4);\n }\n if (t3.length === 0)\n throw new Error(\"Connectivity bridge index has no original nodes\");\n const n3 = new E2(t3.length);\n for (const o4 of t3) {\n const t4 = e51[o4], i4 = t4.center.x - t4.width / 2, r4 = t4.center.x + t4.width / 2, s3 = t4.center.y - t4.height / 2, a3 = t4.center.y + t4.height / 2;\n n3.add(Math.max(-Number.MAX_VALUE, Math.min(i4, r4)), Math.max(-Number.MAX_VALUE, Math.min(s3, a3)), Math.min(Number.MAX_VALUE, Math.max(i4, r4)), Math.min(Number.MAX_VALUE, Math.max(s3, a3)));\n }\n return n3.finish(), { index: n3, originalNodeIndices: t3 };\n })(this.nodes), r3 = o3.search(e50.center.x - e50.width / 2 - PZ, e50.center.y - e50.height / 2 - PZ, e50.center.x + e50.width / 2 + PZ, e50.center.y + e50.height / 2 + PZ);\n r3.sort((e51, t3) =\u003e e51 - t3);\n let s2 = 0;\n for (const t3 of r3) {\n const n3 = this.nodes[i3[t3]];\n if (n3.capacityMeshNodeId !== e50.capacityMeshNodeId \u0026\u0026 (e50.availableZ.some((e51) =\u003e n3.availableZ.includes(e51)) \u0026\u0026 ri(e50, n3))) {\n if (n3._containsTarget)\n return false;\n if (s2++, s2 \u003e= 2)\n return false;\n }\n }\n return true;\n }\n subdivideNode(e50, t2) {\n if (this.shouldRemoveNode(e50, t2))\n return [];\n const { cols: n2, rows: o3 } = this.getSubdivisionGrid(e50);\n if (n2 === 1 \u0026\u0026 o3 === 1)\n return [e50];\n const i3 = e50.width / n2, r3 = e50.height / o3, s2 = e50.center.x - e50.width / 2, a3 = e50.center.y - e50.height / 2, c3 = [];\n for (let t3 = 0;t3 \u003c o3; t3++)\n for (let o4 = 0;o4 \u003c n2; o4++)\n c3.push({ ...e50, capacityMeshNodeId: `${e50.capacityMeshNodeId}__sub_${t3}_${o4}`, center: { x: s2 + i3 * (o4 + 0.5), y: a3 + r3 * (t3 + 0.5) }, width: i3, height: r3, availableZ: [...e50.availableZ] });\n return c3;\n }\n _step() {\n const e50 = this.nodes.length;\n let t2 = 0, n2 = 0, o3 = 0;\n const i3 = {};\n for (const e51 of this.nodes) {\n const r3 = !Number.isFinite(e51.width) || !Number.isFinite(e51.height), s2 = this.subdivideNode(e51, i3);\n s2.length !== 0 ? (s2.length \u003e 1 \u0026\u0026 t2++, this.outputNodes.push(...s2)) : r3 ? o3++ : n2++;\n }\n this.stats = { inputNodeCount: e50, outputNodeCount: this.outputNodes.length, subdividedNodeCount: t2, removedSmallNodeCount: n2, removedInvalidNodeCount: o3, maxNodeDimension: this.maxNodeDimension, maxNodeRatio: this.maxNodeRatio, minNodeArea: this.minNodeArea }, this.solved = true;\n }\n visualize() {\n return { rects: this.outputNodes.map((e50) =\u003e ({ center: e50.center, width: e50.width, height: e50.height, label: `${e50.capacityMeshNodeId}\n${e50.width.toFixed(2)}x${e50.height.toFixed(2)}`, layer: `z${e50.availableZ.join(\",\")}`, fill: \"rgba(0, 200, 255, 0.08)\", stroke: \"rgba(0, 120, 180, 0.5)\" })) };\n }\n};\nvar NZ = (e50) =\u003e {\n const t2 = [...new Set(e50.filter((e51) =\u003e typeof e51 == \"number\" \u0026\u0026 Number.isInteger(e51) \u0026\u0026 e51 \u003e= 0))].sort((e51, t3) =\u003e e51 - t3);\n if (t2.length !== 0)\n return `z${t2.join(\",\")}`;\n};\nvar RZ = (e50) =\u003e {\n const t2 = [];\n for (let n2 = 0;n2 \u003c 31; n2++)\n e50 \u0026 1 \u003c\u003c n2 \u0026\u0026 t2.push(n2);\n return t2;\n};\nvar TZ = (e50) =\u003e typeof e50 == \"object\" \u0026\u0026 e50 !== null;\nvar EZ = (e50) =\u003e TZ(e50) ? { ...e50 } : e50 === undefined ? {} : { value: e50 };\nvar AZ = (e50, t2) =\u003e {\n const n2 = e50.topology.regionMetadata?.[t2];\n if (TZ(n2)) {\n if (typeof n2.serializedRegionId == \"string\")\n return n2.serializedRegionId;\n if (typeof n2.regionId == \"string\")\n return n2.regionId;\n if (typeof n2.capacityMeshNodeId == \"string\")\n return n2.capacityMeshNodeId;\n }\n return `region-${t2}`;\n};\nvar OZ = (e50, t2) =\u003e {\n const n2 = e50.topology.portMetadata?.[t2];\n if (TZ(n2)) {\n if (typeof n2.serializedPortId == \"string\")\n return n2.serializedPortId;\n if (typeof n2.portId == \"string\")\n return (o3 = n2.portId).includes(\"::\") ? o3.slice(0, o3.indexOf(\"::\")) : o3;\n }\n var o3;\n return `port-${t2}`;\n};\nvar kZ = (e50, t2) =\u003e {\n const n2 = e50.problem.routeMetadata?.[t2];\n return TZ(n2) \u0026\u0026 typeof n2.connectionId == \"string\" ? n2.connectionId : `route-${t2}`;\n};\nvar DZ = (e50, t2) =\u003e {\n const n2 = EZ(e50.topology.regionMetadata?.[t2]);\n if (TZ(n2.center) || (n2.center = { x: e50.topology.regionCenterX[t2], y: e50.topology.regionCenterY[t2] }), typeof n2.width != \"number\" \u0026\u0026 (n2.width = e50.topology.regionWidth[t2]), typeof n2.height != \"number\" \u0026\u0026 (n2.height = e50.topology.regionHeight[t2]), !Array.isArray(n2.availableZ)) {\n const o3 = e50.topology.regionAvailableZMask?.[t2] ?? 0;\n o3 !== 0 \u0026\u0026 (n2.availableZ = RZ(o3));\n }\n return n2.layer = NZ(Array.isArray(n2.availableZ) ? n2.availableZ : []) ?? NZ((e50.topology.regionIncidentPorts[t2] ?? []).map((t3) =\u003e e50.topology.portZ[t3])) ?? \"z0\", n2;\n};\nvar LZ = (e50, t2) =\u003e {\n const n2 = EZ(e50.topology.portMetadata?.[t2]);\n return typeof n2.x != \"number\" \u0026\u0026 (n2.x = e50.topology.portX[t2]), typeof n2.y != \"number\" \u0026\u0026 (n2.y = e50.topology.portY[t2]), typeof n2.z != \"number\" \u0026\u0026 (n2.z = e50.topology.portZ[t2]), n2.layer = NZ([e50.topology.portZ[t2]]) ?? \"z0\", n2;\n};\nvar zZ = (e50, t2, n2) =\u003e {\n const o3 = (e50.topology.incidentPortRegion[t2] ?? []).find((e51) =\u003e e51 !== n2);\n if (o3 === undefined)\n throw new Error(`Port ${t2} is not incident to a region outside route region ${n2}`);\n return o3;\n};\nvar BZ = (e50, t2, n2) =\u003e {\n const { orderedPortIds: o3, orderedRegionIds: i3 } = ((e51, t3, n3) =\u003e {\n if (n3.length === 0)\n throw new Error(`Route ${t3} has no solved segments`);\n const o4 = e51.problem.routeStartPort[t3], i4 = e51.problem.routeEndPort[t3], r4 = o4 === i4, s3 = new Map;\n n3.forEach((e52, t4) =\u003e {\n const n4 = { ...e52, segmentIndex: t4 }, o5 = s3.get(e52.fromPortId) ?? [];\n o5.push(n4), s3.set(e52.fromPortId, o5);\n const i5 = s3.get(e52.toPortId) ?? [];\n i5.push(n4), s3.set(e52.toPortId, i5);\n });\n const a4 = [o4], c4 = [], l4 = (e52, t4, o5) =\u003e {\n if (e52 === i4 \u0026\u0026 (!r4 || t4.size === n3.length))\n return true;\n for (const h3 of s3.get(e52) ?? []) {\n if (t4.has(h3.segmentIndex))\n continue;\n const s4 = h3.fromPortId === e52 ? h3.toPortId : h3.fromPortId, d2 = r4 \u0026\u0026 s4 === i4 \u0026\u0026 t4.size + 1 === n3.length;\n if (o5.has(s4) \u0026\u0026 !d2)\n continue;\n t4.add(h3.segmentIndex);\n const u2 = !o5.has(s4);\n if (u2 \u0026\u0026 o5.add(s4), c4.push(h3.regionId), a4.push(s4), l4(s4, t4, o5))\n return true;\n a4.pop(), c4.pop(), u2 \u0026\u0026 o5.delete(s4), t4.delete(h3.segmentIndex);\n }\n return false;\n };\n if (!l4(o4, new Set, new Set([o4])))\n throw new Error(`Route ${t3} is not a single ordered path from ${o4} to ${i4}`);\n return { orderedPortIds: a4, orderedRegionIds: c4 };\n })(e50, t2, n2), r3 = i3[0], s2 = i3[i3.length - 1];\n if (r3 === undefined || s2 === undefined)\n throw new Error(`Route ${t2} could not determine endpoint regions`);\n const a3 = AZ(e50, zZ(e50, o3[0], r3)), c3 = AZ(e50, zZ(e50, o3[o3.length - 1], s2)), l3 = ((e51, t3, n3, o4) =\u003e {\n const i4 = e51.problem.routeMetadata?.[t3];\n return { connectionId: kZ(e51, t3), startRegionId: (TZ(i4) \u0026\u0026 typeof i4.startRegionId == \"string\" ? i4.startRegionId : undefined) ?? n3, endRegionId: (TZ(i4) \u0026\u0026 typeof i4.endRegionId == \"string\" ? i4.endRegionId : undefined) ?? o4, mutuallyConnectedNetworkId: (TZ(i4) \u0026\u0026 typeof i4.mutuallyConnectedNetworkId == \"string\" ? i4.mutuallyConnectedNetworkId : undefined) ?? `net-${e51.problem.routeNet[t3]}` };\n })(e50, t2, a3, c3), h2 = o3.map((t3, n3) =\u003e {\n const r4 = { portId: OZ(e50, t3), g: n3, h: 0, f: n3, hops: n3, ripRequired: false, nextRegionId: n3 \u003c i3.length ? AZ(e50, i3[n3]) : l3.endRegionId };\n return n3 \u003e 0 \u0026\u0026 (r4.lastPortId = OZ(e50, o3[n3 - 1]), r4.lastRegionId = AZ(e50, i3[n3 - 1])), r4;\n });\n return { connection: l3, solvedRoute: { connection: l3, path: h2, requiredRip: false } };\n};\nvar FZ = (e50) =\u003e {\n if (!e50.solved || e50.failed)\n throw new Error(\"convertToSerializedHyperGraph requires a solved, non-failed solver\");\n const { topology: t2 } = e50, n2 = ((e51) =\u003e {\n const t3 = Array.from({ length: e51.problem.routeCount }, () =\u003e []);\n return e51.state.regionSegments.forEach((e52, n3) =\u003e {\n for (const [o4, i4, r4] of e52)\n t3[o4].push({ regionId: n3, fromPortId: i4, toPortId: r4 });\n }), t3;\n })(e50), o3 = Array.from({ length: t2.regionCount }, (n3, o4) =\u003e {\n const i4 = e50.state.regionSegments[o4].map(([t3, n4, o5]) =\u003e ({ regionPort1Id: OZ(e50, n4), regionPort2Id: OZ(e50, o5), connectionId: kZ(e50, t3) }));\n return { regionId: AZ(e50, o4), pointIds: t2.regionIncidentPorts[o4].map((t3) =\u003e OZ(e50, t3)), d: DZ(e50, o4), ...i4.length \u003e 0 \u0026\u0026 { assignments: i4 } };\n }), i3 = Array.from({ length: t2.portCount }, (n3, o4) =\u003e {\n const [i4, r4] = t2.incidentPortRegion[o4] ?? [];\n if (i4 === undefined || r4 === undefined)\n throw new Error(`Port ${o4} is missing incident regions`);\n return { portId: OZ(e50, o4), region1Id: AZ(e50, i4), region2Id: AZ(e50, r4), d: LZ(e50, o4) };\n }), r3 = n2.map((t3, n3) =\u003e BZ(e50, n3, t3));\n return { regions: o3, ports: i3, connections: r3.map(({ connection: e51 }) =\u003e e51), solvedRoutes: r3.map(({ solvedRoute: e51 }) =\u003e e51) };\n};\nvar jZ = 0.3;\nvar $Z = (e50) =\u003e e50 \u003e 0 \u0026\u0026 !(e50 \u0026 e50 - 1);\nvar YZ = (e50, t2, n2, o3, i3, r3, s2 = 0, a3 = 0.3, c3 = 0) =\u003e XZ(e50 * t2, n2, o3, i3, r3, s2, a3, c3);\nvar XZ = (e50, t2, n2, o3, i3, r3 = 0, s2 = 0.3, a3 = 0) =\u003e (2 * t2 + 1 * n2 + 1 * o3) * (s2 + 0.15) ** 2 * (1 + i3 / 5) / e50 + ($Z(r3) ? 10 * t2 : 0) + a3 * (i3 / HZ(r3)) ** 2 * 0.1 ** 2 / e50;\nvar HZ = (e50) =\u003e {\n if (e50 === 0)\n return 2;\n let t2 = e50 \u003e\u003e\u003e 0, n2 = 0;\n for (;t2 !== 0; )\n n2 += 1 \u0026 t2, t2 \u003e\u003e\u003e= 1;\n return n2;\n};\nvar VZ = (e50, t2) =\u003e {\n const { netIds: n2, lesserAngles: o3, greaterAngles: i3, layerMasks: r3 } = e50, { netId: s2, lesserAngle: a3, greaterAngle: c3, layerMask: l3 } = t2;\n let h2 = 0, d2 = 0;\n for (let e51 = 0;e51 \u003c n2.length; e51++) {\n if (s2 === n2[e51])\n continue;\n (a3 \u003c o3[e51] \u0026\u0026 o3[e51] \u003c c3) !== (a3 \u003c i3[e51] \u0026\u0026 i3[e51] \u003c c3) \u0026\u0026 ((l3 \u0026 r3[e51]) !== 0 ? h2++ : d2++);\n }\n t2.sameLayerIntersectionCount = h2, t2.crossingLayerIntersectionCount = d2;\n};\nvar WZ = (e50, t2, n2) =\u003e {\n const o3 = e50.routeStartPort[t2], i3 = e50.routeEndPort[t2], r3 = new Map;\n for (const { fromPortId: e51, toPortId: t3 } of n2) {\n const n3 = r3.get(e51) ?? new Set;\n n3.add(t3), r3.set(e51, n3);\n const o4 = r3.get(t3) ?? new Set;\n o4.add(e51), r3.set(t3, o4);\n }\n const s2 = new Set, a3 = [o3];\n for (;a3.length \u003e 0; ) {\n const e51 = a3.pop();\n if (!s2.has(e51)) {\n s2.add(e51);\n for (const t3 of r3.get(e51) ?? [])\n a3.push(t3);\n }\n }\n if (!s2.has(i3))\n throw new Error(`Initial assignments for route ${t2} do not connect ${o3} to ${i3}`);\n if (n2.some(({ fromPortId: e51, toPortId: t3 }) =\u003e !s2.has(e51) || !s2.has(t3)))\n throw new Error(`Initial assignments for route ${t2} contain disconnected segments`);\n};\nvar GZ = ({ topology: e50, problem: t2, state: n2, routeSuccessCountByRouteId: o3, appendSegmentToRegionCache: i3 }) =\u003e {\n const r3 = t2.initialAssignments ?? [];\n if (r3.length === 0)\n return;\n const s2 = new Map;\n for (const n3 of r3) {\n const { routeId: o4, regionId: i4, fromPortId: r4, toPortId: a4 } = n3;\n if (!Number.isInteger(o4) || o4 \u003c 0 || o4 \u003e= t2.routeCount)\n throw new Error(`Initial assignment references invalid route ${o4}`);\n if (!Number.isInteger(i4) || i4 \u003c 0 || i4 \u003e= e50.regionCount)\n throw new Error(`Initial assignment references invalid region ${i4}`);\n for (const t3 of [r4, a4]) {\n if (!Number.isInteger(t3) || t3 \u003c 0 || t3 \u003e= e50.portCount)\n throw new Error(`Initial assignment references invalid port ${t3}`);\n if (!e50.incidentPortRegion[t3]?.includes(i4))\n throw new Error(`Initial assignment port ${t3} is not incident to region ${i4}`);\n }\n const c3 = s2.get(o4) ?? [];\n c3.push(n3), s2.set(o4, c3);\n }\n for (const [e51, n3] of s2)\n WZ(t2, e51, n3);\n const a3 = new Set(s2.keys());\n for (const { routeId: e51, regionId: o4, fromPortId: s3, toPortId: a4 } of r3) {\n const r4 = t2.routeNet[e51];\n for (const e52 of [s3, a4]) {\n const t3 = n2.portAssignment[e52];\n if (t3 !== -1 \u0026\u0026 t3 !== r4)\n throw new Error(`Initial assignment port ${e52} is assigned to multiple nets`);\n n2.portAssignment[e52] = r4;\n }\n n2.currentRouteNetId = r4, n2.regionSegments[o4].push([e51, s3, a4]), i3(o4, s3, a4);\n }\n n2.currentRouteNetId = undefined, n2.unroutedRoutes = n2.unroutedRoutes.filter((e51) =\u003e !a3.has(e51));\n for (const e51 of a3)\n o3[e51] = 1;\n return { initialAssignmentCount: r3.length, initiallyRoutedRouteCount: a3.size };\n};\nvar UZ = class {\n constructor(e50, t2) {\n this.items = e50, this.compare = t2;\n }\n get length() {\n return this.items.length;\n }\n toArray() {\n return [...this.items];\n }\n clear() {\n this.items.length = 0;\n }\n queue(e50) {\n this.items.push(e50), this.siftUp(this.items.length - 1);\n }\n dequeue() {\n const e50 = this.items[0];\n if (e50 === undefined)\n return;\n const t2 = this.items.pop();\n return this.items.length \u003e 0 \u0026\u0026 (this.items[0] = t2, this.siftDown(0)), e50;\n }\n siftUp(e50) {\n let t2 = e50;\n for (;t2 \u003e 0; ) {\n const e51 = t2 - 1 \u003e\u003e 1, n2 = this.items[e51], o3 = this.items[t2];\n if (this.compare(n2, o3) \u003c= 0)\n return;\n this.items[e51] = o3, this.items[t2] = n2, t2 = e51;\n }\n }\n siftDown(e50) {\n let t2 = e50;\n const n2 = this.items.length;\n for (;; ) {\n const e51 = 2 * t2 + 1;\n if (e51 \u003e= n2)\n return;\n const o3 = e51 + 1;\n let i3 = e51;\n o3 \u003c n2 \u0026\u0026 this.compare(this.items[o3], this.items[e51]) \u003c 0 \u0026\u0026 (i3 = o3);\n const r3 = this.items[t2], s2 = this.items[i3];\n if (this.compare(r3, s2) \u003c= 0)\n return;\n this.items[t2] = s2, this.items[i3] = r3, t2 = i3;\n }\n }\n};\nvar ZZ = class {\n constructor(e50, t2) {\n this.regionCount = e50, this.compactHopIndex = t2, t2 \u0026\u0026 (this.hopStateGeneration = new Uint32Array(t2.hopCapacity), this.hopIndexOrClosed = new Int32Array(t2.hopCapacity));\n }\n items = [];\n indexByHopId = new Map;\n closedHopIds = new Set;\n hopStateGeneration;\n hopIndexOrClosed;\n currentHopStateGeneration = 1;\n closureEpochToken = {};\n get closureEpoch() {\n return this.closureEpochToken;\n }\n get length() {\n return this.items.length;\n }\n toArray() {\n return [...this.items];\n }\n clear() {\n this.closureEpochToken = {}, this.items.length = 0, this.indexByHopId.clear(), this.closedHopIds.clear(), this.hopStateGeneration \u0026\u0026 (this.currentHopStateGeneration === 4294967295 ? (this.hopStateGeneration.fill(0), this.currentHopStateGeneration = 1) : this.currentHopStateGeneration += 1);\n }\n isClosedHop(e50, t2) {\n return this.isClosedHopId(this.getHopIdFromValues(e50, t2));\n }\n isClosedHopId(e50) {\n return this.isHopClosed(e50);\n }\n queue(e50) {\n const t2 = this.getHopId(e50);\n if (this.isHopClosed(t2))\n return;\n const n2 = this.getQueuedHopIndex(t2);\n if (n2 !== undefined) {\n const t3 = this.items[n2];\n if (e50.g \u003e= t3.g)\n return;\n return this.items[n2] = e50, void (e50.f \u003c= t3.f ? this.siftUp(n2) : this.siftDown(n2));\n }\n const o3 = this.items.length;\n this.items.push(e50), this.siftUp(o3);\n }\n dequeue() {\n const e50 = this.items[0];\n if (!e50)\n return;\n const t2 = this.getHopId(e50);\n this.closeHop(t2);\n const n2 = this.items.pop();\n return this.items.length \u003e 0 \u0026\u0026 (this.items[0] = n2, this.siftDown(0)), e50;\n }\n getHopId(e50) {\n if (e50.hopId !== undefined)\n return e50.hopId;\n const t2 = this.getHopIdFromValues(e50.portId, e50.nextRegionId);\n return e50.hopId = t2, t2;\n }\n getHopIdFromValues(e50, t2) {\n const n2 = this.compactHopIndex;\n if (!n2)\n return e50 * this.regionCount + t2;\n const o3 = e50 * n2.hopSlotStride;\n if (n2.firstRegionByPortId[e50] === t2)\n return o3;\n if (n2.secondRegionByPortId[e50] === t2)\n return o3 + 1;\n const i3 = n2.incidentPortRegion[e50];\n for (let e51 = 2;e51 \u003c (i3?.length ?? 0); e51++)\n if (i3[e51] === t2)\n return o3 + e51;\n return -(e50 * this.regionCount + t2) - 1;\n }\n getQueuedHopIndex(e50) {\n if (e50 \u003e= 0 \u0026\u0026 this.hopStateGeneration) {\n if (this.hopStateGeneration[e50] !== this.currentHopStateGeneration)\n return;\n const t2 = this.hopIndexOrClosed[e50];\n return t2 \u003e= 0 ? t2 : undefined;\n }\n return this.indexByHopId.get(e50);\n }\n isHopClosed(e50) {\n return e50 \u003e= 0 \u0026\u0026 this.hopStateGeneration ? this.hopStateGeneration[e50] === this.currentHopStateGeneration \u0026\u0026 this.hopIndexOrClosed[e50] === -1 : this.closedHopIds.has(e50);\n }\n setQueuedHopIndex(e50, t2) {\n if (e50 \u003e= 0 \u0026\u0026 this.hopStateGeneration)\n return this.hopStateGeneration[e50] = this.currentHopStateGeneration, void (this.hopIndexOrClosed[e50] = t2);\n this.indexByHopId.set(e50, t2);\n }\n closeHop(e50) {\n if (e50 \u003e= 0 \u0026\u0026 this.hopStateGeneration)\n return this.hopStateGeneration[e50] = this.currentHopStateGeneration, void (this.hopIndexOrClosed[e50] = -1);\n this.indexByHopId.delete(e50), this.closedHopIds.add(e50);\n }\n siftUp(e50) {\n const t2 = this.items[e50];\n let n2 = e50;\n for (;n2 \u003e 0; ) {\n const e51 = n2 - 1 \u003e\u003e 1, o3 = this.items[e51];\n if (o3.f \u003c= t2.f)\n break;\n this.items[n2] = o3, this.setQueuedHopIndex(this.getHopId(o3), n2), n2 = e51;\n }\n this.items[n2] = t2, this.setQueuedHopIndex(this.getHopId(t2), n2);\n }\n siftDown(e50) {\n const t2 = this.items[e50];\n let n2 = e50;\n for (;; ) {\n const e51 = 2 * n2 + 1;\n if (e51 \u003e= this.items.length)\n break;\n const o3 = e51 + 1, i3 = o3 \u003c this.items.length \u0026\u0026 this.items[o3].f \u003c this.items[e51].f ? o3 : e51, r3 = this.items[i3];\n if (t2.f \u003c= r3.f)\n break;\n this.items[n2] = r3, this.setQueuedHopIndex(this.getHopId(r3), n2), n2 = i3;\n }\n this.items[n2] = t2, this.setQueuedHopIndex(this.getHopId(t2), n2);\n }\n};\nvar qZ = (e50, t2) =\u003e {\n const n2 = [...e50], o3 = ((e51) =\u003e {\n let t3 = e51 \u003e\u003e\u003e 0;\n return () =\u003e {\n t3 += 1831565813;\n let e52 = t3;\n return e52 = Math.imul(e52 ^ e52 \u003e\u003e\u003e 15, 1 | e52), e52 ^= e52 + Math.imul(e52 ^ e52 \u003e\u003e\u003e 7, 61 | e52), ((e52 ^ e52 \u003e\u003e\u003e 14) \u003e\u003e\u003e 0) / 4294967296;\n };\n })(t2);\n for (let e51 = n2.length - 1;e51 \u003e 0; e51--) {\n const t3 = Math.floor(o3() * (e51 + 1));\n [n2[e51], n2[t3]] = [n2[t3], n2[e51]];\n }\n return n2;\n};\nvar JZ = (e50, t2) =\u003e e50.routeMetadata?.[t2];\nvar QZ = (e50) =\u003e e50?.simpleRouteConnection?.pointsToConnect?.map(({ pointId: e51 }) =\u003e typeof e51 == \"string\" ? e51 : null).filter((e51) =\u003e e51 !== null) ?? [];\nvar KZ = (e50, t2) =\u003e {\n const n2 = JZ(e50, t2)?.connectionId;\n return typeof n2 == \"string\" ? n2 : `route-${t2}`;\n};\nvar eq = (e50, t2, n2) =\u003e {\n const o3 = e50.portEndpointNetIds[n2];\n if (!o3)\n return false;\n for (const e51 of o3)\n if (e51 !== t2)\n return true;\n return false;\n};\nvar tq = (e50, t2, n2) =\u003e {\n const o3 = e50.regionNetId[n2];\n return o3 !== -1 \u0026\u0026 o3 !== t2;\n};\nvar nq = (e50) =\u003e [...new Set(e50.routeIds)].filter((t2) =\u003e !((e51, t3) =\u003e {\n const { topology: n2, problem: o3, problemSetup: i3, portAssignment: r3, maxPrecheckHops: s2 } = e51, a3 = o3.routeNet[t3], c3 = o3.routeStartPort[t3], l3 = o3.routeEndPort[t3];\n if (c3 === l3)\n return true;\n const h2 = e51.getStartingNextRegionId(t3, c3);\n if (h2 === undefined)\n return false;\n const d2 = [{ portId: c3, nextRegionId: h2 }], u2 = new Set([c3 * n2.regionCount + h2]);\n for (let e52 = 0;e52 \u003c d2.length; e52++) {\n const t4 = d2[e52];\n if (!tq(o3, a3, t4.nextRegionId))\n for (const e53 of n2.regionIncidentPorts[t4.nextRegionId] ?? []) {\n const c4 = r3[e53];\n if (eq(i3, a3, e53))\n continue;\n if (e53 === l3) {\n if (c4 !== -1 \u0026\u0026 c4 !== a3)\n continue;\n return true;\n }\n if (e53 === t4.portId)\n continue;\n if (c4 !== -1 \u0026\u0026 c4 !== a3)\n continue;\n if (o3.portSectionMask[e53] === 0)\n continue;\n const h3 = n2.incidentPortRegion[e53] ?? [], p3 = h3[0] === t4.nextRegionId ? h3[1] : h3[0];\n if (p3 === undefined || tq(o3, a3, p3))\n continue;\n const m2 = e53 * n2.regionCount + p3;\n if (!u2.has(m2)) {\n if (u2.size \u003e= s2)\n return true;\n u2.add(m2), d2.push({ portId: e53, nextRegionId: p3 });\n }\n }\n }\n return false;\n})(e50, t2)).map((t2) =\u003e e50.getRouteSummary(t2));\nvar oq = (e50) =\u003e {\n const t2 = new Array(e50);\n for (let n2 = 0;n2 \u003c e50; n2++)\n t2[n2] = n2;\n return t2;\n};\nvar iq = \"rgba(220, 38, 38, 0.98)\";\nvar rq = \"rgba(220, 38, 38, 0.18)\";\nvar sq = (...e50) =\u003e e50.filter((e51) =\u003e Boolean(e51)).join(`\n`);\nvar aq = (e50, t2) =\u003e {\n const n2 = 0.005 * e50.topology.portZ[t2];\n return { x: e50.topology.portX[t2] + n2, y: e50.topology.portY[t2] + n2 };\n};\nvar cq = (e50, t2) =\u003e NZ([e50.topology.portZ[t2]]) ?? \"z0\";\nvar lq = (e50, t2) =\u003e {\n const n2 = e50.topology.portMetadata?.[t2];\n return `port: ${n2?.serializedPortId ?? n2?.portId ?? `port-${t2}`}`;\n};\nvar hq = (e50, t2) =\u003e `z: ${e50.topology.portZ[t2]}`;\nvar dq = (e50, t2) =\u003e ((e51, t3, n2) =\u003e {\n const o3 = e51.topology.portZ[t3], i3 = e51.topology.portZ[n2];\n return o3 === i3 ? `z: ${o3}` : `z: ${o3} -\u003e ${i3}`;\n})(e50, e50.problem.routeStartPort[t2], e50.problem.routeEndPort[t2]);\nvar uq = (e50, t2) =\u003e `net: ${e50.problem.routeNet[t2]}`;\nvar pq = 0.05;\nvar mq = { r: 255, g: 64, b: 64, a: 0.72 };\nvar gq = \"rgba(220, 38, 38, 0.98)\";\nvar fq = \"rgba(220, 38, 38, 0.12)\";\nvar _q = \"10 6\";\nvar yq = (...e50) =\u003e e50.filter((e51) =\u003e Boolean(e51)).join(`\n`);\nvar bq = (e50) =\u003e Math.min(1, Math.max(0, e50));\nvar xq = (e50, t2, n2) =\u003e Math.round(e50 + (t2 - e50) * n2);\nvar vq = ({ r: e50, g: t2, b: n2, a: o3 }) =\u003e `rgba(${e50}, ${t2}, ${n2}, ${o3})`;\nvar Iq = (e50, t2) =\u003e {\n const n2 = e50.problem.routeMetadata?.[t2];\n return n2?.connectionId ?? n2?.mutuallyConnectedNetworkId ?? `route-${t2}`;\n};\nvar Sq = (e50) =\u003e typeof e50.centerRouteId == \"number\";\nvar Cq = (e50, t2) =\u003e Sq(e50) ? t2 === e50.centerRouteId ? 1 : 0.5 : 1;\nvar Pq = (e50, t2) =\u003e {\n const n2 = e50.match(/^(rgba|hsla)\\((.*),\\s*([0-9]*\\.?[0-9]+)\\)$/);\n if (!n2)\n return e50;\n const [, o3, i3, r3] = n2, s2 = bq(Number(r3) * t2);\n return `${o3}(${i3}, ${Number(s2.toFixed(3))})`;\n};\nvar Mq = (e50, t2, n2 = 0.8) =\u003e ((e51, t3, n3 = 0.8) =\u003e {\n const o3 = `${e51.problem.routeNet[t3]}:${Iq(e51, t3)}`;\n let i3 = 0;\n for (let e52 = 0;e52 \u003c o3.length; e52++)\n i3 = 17777 * o3.charCodeAt(e52) + ((i3 \u003c\u003c 5) - i3);\n return `hsla(${Math.abs(i3) % 360}, 70%, 50%, ${n3})`;\n})(e50, t2, n2 * Cq(e50, t2));\nvar wq = (e50, t2) =\u003e `net: ${e50.problem.routeNet[t2]}`;\nvar Nq = (e50, t2) =\u003e {\n const n2 = e50.topology.regionMetadata?.[t2], o3 = n2?.polygon;\n if (Array.isArray(o3) \u0026\u0026 o3.length \u003e= 3) {\n const e51 = o3.map((e52) =\u003e e52.x), t3 = o3.map((e52) =\u003e e52.y);\n return { minX: Math.min(...e51), maxX: Math.max(...e51), minY: Math.min(...t3), maxY: Math.max(...t3) };\n }\n const i3 = n2?.bounds;\n if (i3 \u0026\u0026 typeof i3.minX == \"number\" \u0026\u0026 typeof i3.maxX == \"number\" \u0026\u0026 typeof i3.minY == \"number\" \u0026\u0026 typeof i3.maxY == \"number\")\n return i3;\n const r3 = e50.topology.regionWidth[t2], s2 = e50.topology.regionHeight[t2], a3 = e50.topology.regionCenterX[t2], c3 = e50.topology.regionCenterY[t2];\n return { minX: a3 - r3 / 2, maxX: a3 + r3 / 2, minY: c3 - s2 / 2, maxY: c3 + s2 / 2 };\n};\nvar Rq = (e50, t2) =\u003e ({ x: e50.topology.regionCenterX[t2], y: e50.topology.regionCenterY[t2] });\nvar Tq = (e50, t2) =\u003e {\n const n2 = e50.topology.regionMetadata?.[t2], o3 = Array.isArray(n2?.availableZ) ? n2.availableZ.filter((e51) =\u003e typeof e51 == \"number\" \u0026\u0026 Number.isInteger(e51) \u0026\u0026 e51 \u003e= 0) : [];\n if (o3.length \u003e 0)\n return NZ(o3) ?? \"z0\";\n const i3 = RZ(e50.topology.regionAvailableZMask?.[t2] ?? 0);\n if (i3.length \u003e 0)\n return NZ(i3) ?? \"z0\";\n const r3 = [...new Set((e50.topology.regionIncidentPorts[t2] ?? []).map((t3) =\u003e e50.topology.portZ[t3]))].sort((e51, t3) =\u003e e51 - t3);\n return NZ(r3) ?? \"z0\";\n};\nvar Eq = (e50, t2) =\u003e {\n const n2 = e50.state.regionIntersectionCaches[t2], o3 = n2?.existingRegionCost ?? 0, i3 = e50.state.regionCongestionCost[t2] ?? 0, r3 = e50.problem.regionNetId[t2];\n return yq(`region: region-${t2}`, `net: ${r3 === -1 ? \"free\" : `${r3}`}`, e50.getAdditionalRegionLabel(t2), `cost: ${o3.toFixed(3)}`, `congestion: ${i3.toFixed(3)}`, `same layer X: ${n2?.existingSameLayerIntersections ?? 0}`, `trans X: ${n2?.existingCrossingLayerIntersections ?? 0}`, `entry exit X: ${n2?.existingEntryExitLayerChanges ?? 0}`);\n};\nvar Aq = (e50, t2) =\u003e {\n const n2 = e50.topology.regionMetadata?.[t2];\n return n2?.isConnectionRegion ? { r: 255, g: 100, b: 255, a: 0.6 } : n2?.isThroughJumper ? { r: 100, g: 200, b: 100, a: 0.5 } : n2?.isPad ? { r: 255, g: 200, b: 100, a: 0.5 } : n2?.layer === \"bottom\" ? { r: 52, g: 152, b: 219, a: 0.08 } : { r: 200, g: 200, b: 255, a: 0.1 };\n};\nvar Oq = (e50, t2) =\u003e {\n const n2 = Aq(e50, t2), o3 = bq(e50.state.regionIntersectionCaches[t2]?.existingRegionCost ?? 0);\n return vq((r3 = mq, s2 = o3 ** 0.8, { r: xq((i3 = n2).r, r3.r, s2), g: xq(i3.g, r3.g, s2), b: xq(i3.b, r3.b, s2), a: Number((i3.a + (r3.a - i3.a) * s2).toFixed(3)) }));\n var i3, r3, s2;\n};\nvar kq = (e50, t2) =\u003e {\n const n2 = ((e51, t3) =\u003e ({ x: e51.topology.portX[t3], y: e51.topology.portY[t3] }))(e50, t2), o3 = 0.005 * e50.topology.portZ[t2];\n return { x: n2.x + o3, y: n2.y + o3 };\n};\nvar Dq = kq;\nvar Lq = (e50, t2) =\u003e NZ([e50.topology.portZ[t2]]) ?? \"z0\";\nvar zq = (e50, t2) =\u003e {\n const n2 = e50.topology.portMetadata?.[t2];\n return `port: ${n2?.serializedPortId ?? n2?.portId ?? `port-${t2}`}`;\n};\nvar Bq = (e50, t2, n2) =\u003e {\n if (n2 !== undefined)\n return `net: ${e50.problem.routeNet[n2]}`;\n const o3 = e50.state.portAssignment[t2];\n if (o3 \u003e= 0)\n return `net: ${o3}`;\n const i3 = new Set;\n for (let n3 = 0;n3 \u003c e50.problem.routeCount; n3++)\n e50.problem.routeStartPort[n3] !== t2 \u0026\u0026 e50.problem.routeEndPort[n3] !== t2 || i3.add(e50.problem.routeNet[n3]);\n return i3.size !== 0 ? `net: ${Array.from(i3).sort((e51, t3) =\u003e e51 - t3).join(\", \")}` : undefined;\n};\nvar Fq = (e50, t2) =\u003e `z: ${e50.topology.portZ[t2]}`;\nvar jq = (e50, t2, n2) =\u003e {\n const o3 = e50.topology.portZ[t2], i3 = e50.topology.portZ[n2];\n return o3 === i3 ? `z: ${o3}` : `z: ${o3} -\u003e ${i3}`;\n};\nvar $q = (e50, t2) =\u003e jq(e50, e50.problem.routeStartPort[t2], e50.problem.routeEndPort[t2]);\nvar Yq = (e50, t2, n2) =\u003e yq(zq(e50, t2), ((e51, t3) =\u003e {\n const n3 = e51.topology.incidentPortRegion[t3]?.[0], o3 = e51.topology.incidentPortRegion[t3]?.[1];\n return `connects: region-${n3 ?? \"?\"} \u003c-\u003e region-${o3 ?? \"?\"}`;\n})(e50, t2), Bq(e50, t2, n2));\nvar Xq = (e50, t2, n2, o3) =\u003e {\n const i3 = e50.topology.portZ[n2];\n return i3 !== e50.topology.portZ[o3] ? { strokeColor: Pq(\"rgba(22, 160, 133, 0.95)\", Cq(e50, t2)), strokeDash: \"2 4 2\" } : i3 \u003e 0 ? { strokeColor: Pq(\"rgba(52, 152, 219, 0.95)\", Cq(e50, t2)), strokeDash: \"3 2\" } : { strokeColor: Mq(e50, t2) };\n};\nvar Hq = (e50, t2) =\u003e {\n for (let n2 = 0;n2 \u003c e50.state.regionSegments.length; n2++) {\n const o3 = e50.state.regionSegments[n2] ?? [];\n for (const [i3, r3, s2] of o3)\n t2.lines.push({ points: [kq(e50, r3), kq(e50, s2)], label: yq(`route: ${Iq(e50, i3)}`, `region: region-${n2}`, jq(e50, r3, s2)), layer: Lq(e50, r3), ...Xq(e50, i3, r3, s2) });\n }\n};\nvar Vq = (e50, t2) =\u003e {\n const n2 = new Set;\n for (let o3 = 0;o3 \u003c e50.state.regionSegments.length; o3++) {\n const i3 = e50.state.regionSegments[o3] ?? [];\n for (const [o4, r3, s2] of i3)\n for (const i4 of [r3, s2]) {\n const r4 = `${o4}:${i4}`;\n if (n2.has(r4))\n continue;\n n2.add(r4);\n const s3 = kq(e50, i4);\n t2.points.push({ x: s3.x, y: s3.y, color: Mq(e50, o4, 1), layer: Lq(e50, i4), label: yq(`route: ${Iq(e50, o4)}`, zq(e50, i4), Bq(e50, i4, o4), Fq(e50, i4)) });\n }\n }\n};\nvar Wq = (e50, t2) =\u003e {\n for (let n2 = 0;n2 \u003c e50.problem.routeCount; n2++)\n if (e50.problem.routeStartPort[n2] === t2 || e50.problem.routeEndPort[n2] === t2)\n return true;\n return false;\n};\nvar Gq = (e50, t2, n2) =\u003e {\n const o3 = ((e51, t3) =\u003e {\n const n3 = new Set;\n for (let o4 = 0;o4 \u003c t3.length; o4++)\n if (t3[o4] === 1)\n for (const t4 of e51.topology.incidentPortRegion[o4] ?? [])\n n3.add(t4);\n return n3;\n })(e50, n2), i3 = \"rgba(245, 158, 11, 0.95)\", r3 = \"rgba(245, 158, 11, 0.08)\";\n for (const n3 of o3) {\n const o4 = e50.topology.regionMetadata?.[n3], s2 = o4?.polygon, a3 = Nq(e50, n3), c3 = Rq(e50, n3), l3 = a3.maxX - a3.minX, h2 = a3.maxY - a3.minY, d2 = Tq(e50, n3), u2 = yq(\"section region\", Eq(e50, n3));\n Array.isArray(s2) \u0026\u0026 s2.length \u003e= 3 ? t2.polygons.push({ points: s2, fill: r3, stroke: i3, strokeWidth: 2, layer: d2, label: u2 }) : t2.rects.push({ center: c3, width: Math.max(l3 - pq, 0.05), height: Math.max(h2 - pq, 0.05), fill: r3, stroke: i3, layer: d2, label: u2 });\n }\n for (let o4 = 0;o4 \u003c n2.length; o4++)\n n2[o4] === 1 \u0026\u0026 t2.circles.push({ center: Dq(e50, o4), radius: 0.07, fill: \"rgba(251, 191, 36, 0.18)\", stroke: i3, layer: Lq(e50, o4), label: yq(Yq(e50, o4), Fq(e50, o4), \"section port\") });\n};\nvar Uq = (e50, t2 = {}) =\u003e {\n const n2 = { arrows: [], circles: [], infiniteLines: [], lines: [], points: [], polygons: [], rects: [], texts: [], title: \"Tiny HyperGraph\", coordinateSystem: \"cartesian\" }, o3 = ((e51, t3) =\u003e {\n if (!t3?.highlightSectionMask)\n return;\n const n3 = t3.sectionPortMask ?? e51.problem.portSectionMask;\n if (n3.length !== e51.topology.portCount)\n return;\n let o4 = 0, i4 = 0;\n for (let e52 = 0;e52 \u003c n3.length; e52++)\n n3[e52] === 1 ? o4 += 1 : i4 += 1;\n return o4 !== 0 \u0026\u0026 i4 !== 0 ? n3 : undefined;\n })(e50, t2), i3 = ((e51) =\u003e {\n const t3 = e51.getStaticallyUnroutableRoutes();\n if (t3.length !== 0)\n return new Set(t3.map((e52) =\u003e e52.routeId));\n })(e50);\n for (let t3 = 0;t3 \u003c e50.topology.regionCount; t3++) {\n const o4 = e50.topology.regionMetadata?.[t3], i4 = o4?.polygon, r4 = Nq(e50, t3), s3 = Rq(e50, t3), a3 = r4.maxX - r4.minX, c3 = r4.maxY - r4.minY, l3 = Tq(e50, t3), h2 = vq(Aq(e50, t3));\n Array.isArray(i4) \u0026\u0026 i4.length \u003e= 3 ? n2.polygons.push({ points: i4, fill: h2, layer: l3 }) : n2.rects.push({ center: s3, width: Math.max(a3 - pq, 0.05), height: Math.max(c3 - pq, 0.05), fill: Oq(e50, t3), layer: l3, label: Eq(e50, t3) });\n }\n if (((e51, t3, n3) =\u003e {\n for (let o4 = 0;o4 \u003c e51.problem.routeCount; o4++) {\n if (n3 \u0026\u0026 !n3.has(o4))\n continue;\n const i4 = e51.problem.routeStartPort[o4], r4 = e51.problem.routeEndPort[o4], s3 = kq(e51, i4), a3 = kq(e51, r4), c3 = Mq(e51, o4), l3 = Iq(e51, o4), h2 = wq(e51, o4);\n t3.points.push({ x: s3.x, y: s3.y, color: c3, layer: Lq(e51, i4), label: yq(`route: ${l3}`, h2, \"endpoint: start\", zq(e51, i4), Fq(e51, i4)) }), t3.points.push({ x: a3.x, y: a3.y, color: c3, layer: Lq(e51, r4), label: yq(`route: ${l3}`, h2, \"endpoint: end\", zq(e51, r4), Fq(e51, r4)) });\n }\n })(e50, n2, i3), e50.iterations === 0) {\n for (const e51 of n2.polygons)\n e51.stroke = \"rgba(128, 128, 128, 0.5)\";\n for (const e51 of n2.rects)\n e51.stroke = \"rgba(128, 128, 128, 0.5)\";\n }\n if (e50.iterations === 0) {\n for (let i4 = 0;i4 \u003c e50.topology.portCount; i4++) {\n const r4 = o3?.[i4] === 1;\n t2.showOnlySectionPortsOnIdle \u0026\u0026 !r4 || n2.circles.push({ center: Dq(e50, i4), radius: 0.05, fill: e50.topology.portZ[i4] \u003e 0 ? \"rgba(52, 152, 219, 0.55)\" : \"rgba(128, 128, 128, 0.5)\", layer: Lq(e50, i4), label: yq(Yq(e50, i4), Fq(e50, i4)) });\n }\n if (i3)\n ((e51, t3) =\u003e {\n for (const n3 of e51.getStaticallyUnroutableRoutes()) {\n const { routeId: o4, connectionId: i4, startPortId: r4, endPortId: s3 } = n3, a3 = aq(e51, r4), c3 = aq(e51, s3), l3 = sq(`static reachability failed: ${i4}`, uq(e51, o4), n3.startRegionId ? `startRegionId: ${n3.startRegionId}` : undefined, n3.endRegionId ? `endRegionId: ${n3.endRegionId}` : undefined, n3.pointIds.length \u003e= 2 ? `points: ${n3.pointIds.join(\" -\u003e \")}` : undefined, dq(e51, o4));\n t3.lines.push({ points: [a3, c3], strokeColor: iq, strokeDash: \"8 4\", label: l3 }), t3.circles.push({ center: a3, radius: 0.12, fill: rq, stroke: iq, layer: cq(e51, r4), label: sq(l3, \"endpoint: start\", lq(e51, r4), hq(e51, r4)) }), t3.circles.push({ center: c3, radius: 0.12, fill: rq, stroke: iq, layer: cq(e51, s3), label: sq(l3, \"endpoint: end\", lq(e51, s3), hq(e51, s3)) });\n }\n })(e50, n2);\n else {\n const o4 = new Set;\n for (const t3 of e50.state.regionSegments)\n for (const [e51] of t3)\n o4.add(e51);\n if (o4.size \u003e 0 \u0026\u0026 (Hq(e50, n2), Vq(e50, n2)), t2.showInitialRouteHints !== false) {\n const t3 = new Set(e50.state.unroutedRoutes);\n e50.state.currentRouteId !== undefined \u0026\u0026 t3.add(e50.state.currentRouteId), ((e51, t4, n3) =\u003e {\n for (let o5 = 0;o5 \u003c e51.problem.routeCount; o5++) {\n if (n3 \u0026\u0026 !n3.has(o5))\n continue;\n const i4 = e51.problem.routeStartPort[o5], r4 = e51.problem.routeEndPort[o5], s3 = kq(e51, i4), a3 = kq(e51, r4), c3 = { x: (s3.x + a3.x) / 2, y: (s3.y + a3.y) / 2 };\n t4.lines.push({ points: [s3, a3], strokeColor: Mq(e51, o5), strokeDash: \"3 3\", layer: Lq(e51, i4), label: yq(Iq(e51, o5), $q(e51, o5)) }), t4.points.push({ x: c3.x, y: c3.y, color: Mq(e51, o5, 1), layer: Lq(e51, i4), label: yq(Iq(e51, o5), $q(e51, o5)) });\n }\n })(e50, n2, t3);\n }\n }\n } else\n Hq(e50, n2), Vq(e50, n2), ((e51) =\u003e Sq(e51) \u0026\u0026 e51.showUnassignedPortsInVisualization === true)(e50) \u0026\u0026 ((e51, t3) =\u003e {\n for (let n3 = 0;n3 \u003c e51.topology.portCount; n3++)\n e51.state.portAssignment[n3] \u003e= 0 || Wq(e51, n3) || t3.circles.push({ center: Dq(e51, n3), radius: 0.04, fill: e51.topology.portZ[n3] \u003e 0 ? \"rgba(52, 152, 219, 0.2)\" : \"rgba(128, 128, 128, 0.2)\", stroke: e51.topology.portZ[n3] \u003e 0 ? \"rgba(52, 152, 219, 0.6)\" : \"rgba(128, 128, 128, 0.6)\", layer: Lq(e51, n3), label: yq(Yq(e51, n3), Fq(e51, n3), \"state: unassigned\") });\n })(e50, n2), Sq(e50) || (((e51, t3) =\u003e {\n const n3 = e51.state.currentRouteId;\n if (n3 === undefined || e51.solved)\n return;\n const o4 = e51.problem.routeStartPort[n3], i4 = e51.problem.routeEndPort[n3], r4 = kq(e51, o4), s3 = kq(e51, i4), a3 = Mq(e51, n3), c3 = Iq(e51, n3);\n t3.lines.push({ points: [r4, s3], strokeColor: a3, strokeDash: \"10 5\", label: yq(c3, $q(e51, n3)) });\n })(e50, n2), ((e51, t3) =\u003e {\n if (e51.solved)\n return;\n const n3 = e51.state.currentRouteId, o4 = e51.state.candidateQueue.toArray().sort((e52, t4) =\u003e e52.f - t4.f).slice(0, 10);\n for (let i5 = 0;i5 \u003c o4.length; i5++) {\n const r5 = o4[i5], s4 = kq(e51, r5.portId), a3 = i5 === 0;\n t3.points.push({ x: s4.x, y: s4.y, color: a3 ? \"green\" : \"rgba(128, 128, 128, 0.25)\", layer: Lq(e51, r5.portId), label: yq(Yq(e51, r5.portId, n3), Fq(e51, r5.portId), `g: ${r5.g.toFixed(2)}`, `h: ${r5.h.toFixed(2)}`, `f: ${r5.f.toFixed(2)}`) });\n }\n const i4 = o4[0];\n if (!i4)\n return;\n const r4 = [];\n let s3 = i4;\n for (;s3; )\n r4.unshift(kq(e51, s3.portId)), s3 = s3.prevCandidate;\n r4.length \u003e 1 \u0026\u0026 t3.lines.push({ points: r4, strokeColor: n3 !== undefined ? Mq(e51, n3) : \"rgba(0, 160, 120, 0.9)\" });\n })(e50, n2));\n o3 \u0026\u0026 Gq(e50, n2, o3), ((e51, t3) =\u003e {\n if (e51.failed)\n for (const n3 of e51.getNeverSuccessfullyRoutedRoutes()) {\n const { routeId: o4, connectionId: i4, attempts: r4, startPortId: s3, endPortId: a3 } = n3, c3 = wq(e51, o4), l3 = Dq(e51, s3), h2 = Dq(e51, a3), d2 = yq(`never routed: ${i4}`, `attempts: ${r4}`, c3, n3.startRegionId ? `startRegionId: ${n3.startRegionId}` : undefined, n3.endRegionId ? `endRegionId: ${n3.endRegionId}` : undefined);\n t3.lines.push({ points: [{ x: 0, y: 0 }, { x: l3.x, y: l3.y }], strokeColor: gq, strokeDash: _q, layer: Lq(e51, s3), label: yq(d2, \"origin guide\", \"endpoint: start\") }), t3.circles.push({ center: l3, radius: 1, fill: fq, stroke: gq, layer: Lq(e51, s3), label: yq(d2, \"endpoint: start\", zq(e51, s3), Fq(e51, s3)) }), t3.lines.push({ points: [{ x: 0, y: 0 }, { x: h2.x, y: h2.y }], strokeColor: gq, strokeDash: _q, layer: Lq(e51, a3), label: yq(d2, \"origin guide\", \"endpoint: end\") }), t3.circles.push({ center: h2, radius: 1, fill: fq, stroke: gq, layer: Lq(e51, a3), label: yq(d2, \"endpoint: end\", zq(e51, a3), Fq(e51, a3)) });\n }\n })(e50, n2);\n const r3 = e50.state.unroutedRoutes.length + (e50.state.currentRouteId === undefined ? 0 : 1), s2 = o3 ? o3.reduce((e51, t3) =\u003e e51 + Number(t3 === 1), 0) : 0;\n return n2.title = [\"Tiny HyperGraph\", `iter=${e50.iterations}`, `pending=${r3}`, o3 ? `sectionPorts=${s2}` : undefined, i3 ? `staticReachabilityFailed=${i3.size}` : undefined, e50.failed ? \"failed\" : e50.solved ? \"solved\" : \"running\"].filter(Boolean).join(\" | \"), n2;\n};\nvar Zq = () =\u003e ({ netIds: new Int32Array(0), lesserAngles: new Int32Array(0), greaterAngles: new Int32Array(0), layerMasks: new Int32Array(0), existingCrossingLayerIntersections: 0, existingSameLayerIntersections: 0, existingEntryExitLayerChanges: 0, existingRegionCost: 0, existingSegmentCount: 0 });\nvar qq = (e50) =\u003e ({ netIds: new Int32Array(e50.netIds), lesserAngles: new Int32Array(e50.lesserAngles), greaterAngles: new Int32Array(e50.greaterAngles), layerMasks: new Int32Array(e50.layerMasks), existingCrossingLayerIntersections: e50.existingCrossingLayerIntersections, existingSameLayerIntersections: e50.existingSameLayerIntersections, existingEntryExitLayerChanges: e50.existingEntryExitLayerChanges, existingRegionCost: e50.existingRegionCost, existingSegmentCount: e50.existingSegmentCount });\nvar Jq = (e50) =\u003e {\n return { portAssignment: new Int32Array(e50.portAssignment), regionSegments: (t2 = e50.regionSegments, t2.map((e51) =\u003e e51.map(([e52, t3, n2]) =\u003e [e52, t3, n2]))), regionIntersectionCaches: e50.regionIntersectionCaches.map(qq), regionCongestionCost: new Float64Array(e50.regionCongestionCost), ripCount: e50.ripCount };\n var t2;\n};\nvar Qq = (e50, t2) =\u003e {\n t2 \u0026\u0026 (t2.minViaPadDiameter !== undefined \u0026\u0026 (e50.minViaPadDiameter = t2.minViaPadDiameter), t2.DISTANCE_TO_COST !== undefined \u0026\u0026 (e50.DISTANCE_TO_COST = t2.DISTANCE_TO_COST), t2.RIP_THRESHOLD_START !== undefined \u0026\u0026 (e50.RIP_THRESHOLD_START = t2.RIP_THRESHOLD_START), t2.RIP_THRESHOLD_END !== undefined \u0026\u0026 (e50.RIP_THRESHOLD_END = t2.RIP_THRESHOLD_END), t2.RIP_THRESHOLD_RAMP_ATTEMPTS !== undefined \u0026\u0026 (e50.RIP_THRESHOLD_RAMP_ATTEMPTS = t2.RIP_THRESHOLD_RAMP_ATTEMPTS), t2.RIP_CONGESTION_REGION_COST_FACTOR !== undefined \u0026\u0026 (e50.RIP_CONGESTION_REGION_COST_FACTOR = t2.RIP_CONGESTION_REGION_COST_FACTOR), t2.TRACE_DENSITY_COST_FACTOR !== undefined \u0026\u0026 (e50.TRACE_DENSITY_COST_FACTOR = Math.max(0, t2.TRACE_DENSITY_COST_FACTOR)), t2.USE_LAZY_ROUTE_HEURISTIC !== undefined \u0026\u0026 (e50.USE_LAZY_ROUTE_HEURISTIC = t2.USE_LAZY_ROUTE_HEURISTIC), t2.USE_SPARSE_CANDIDATE_STORAGE !== undefined \u0026\u0026 (e50.USE_SPARSE_CANDIDATE_STORAGE = t2.USE_SPARSE_CANDIDATE_STORAGE), t2.OWNED_REGIONAL_HOP_FRONTIER !== undefined \u0026\u0026 (e50.OWNED_REGIONAL_HOP_FRONTIER = t2.OWNED_REGIONAL_HOP_FRONTIER), t2.MAX_ITERATIONS !== undefined \u0026\u0026 (e50.MAX_ITERATIONS = t2.MAX_ITERATIONS), t2.VERBOSE !== undefined \u0026\u0026 (e50.VERBOSE = t2.VERBOSE), t2.STATIC_REACHABILITY_PRECHECK !== undefined \u0026\u0026 (e50.STATIC_REACHABILITY_PRECHECK = t2.STATIC_REACHABILITY_PRECHECK), t2.STATIC_REACHABILITY_PRECHECK_MAX_HOPS !== undefined \u0026\u0026 (e50.STATIC_REACHABILITY_PRECHECK_MAX_HOPS = t2.STATIC_REACHABILITY_PRECHECK_MAX_HOPS), t2.ACCEPT_BEST_SOLUTION_ON_TIMEOUT !== undefined \u0026\u0026 (e50.ACCEPT_BEST_SOLUTION_ON_TIMEOUT = t2.ACCEPT_BEST_SOLUTION_ON_TIMEOUT), t2.GREEDY_FINAL_ROUTE_ITERS !== undefined \u0026\u0026 (e50.GREEDY_FINAL_ROUTE_ITERS = t2.GREEDY_FINAL_ROUTE_ITERS), t2.PARTIAL_RIP_ENABLED !== undefined \u0026\u0026 (e50.PARTIAL_RIP_ENABLED = t2.PARTIAL_RIP_ENABLED), t2.PARTIAL_RIP_MIN_ROUTE_COUNT !== undefined \u0026\u0026 (e50.PARTIAL_RIP_MIN_ROUTE_COUNT = t2.PARTIAL_RIP_MIN_ROUTE_COUNT), t2.PARTIAL_RIP_MAX_ROUTE_COUNT !== undefined \u0026\u0026 (e50.PARTIAL_RIP_MAX_ROUTE_COUNT = t2.PARTIAL_RIP_MAX_ROUTE_COUNT), t2.PARTIAL_RIP_MAX_DISTANCE !== undefined \u0026\u0026 (e50.PARTIAL_RIP_MAX_DISTANCE = t2.PARTIAL_RIP_MAX_DISTANCE), t2.PARTIAL_RIP_QUALITY_MAX_DISTANCE !== undefined \u0026\u0026 (e50.PARTIAL_RIP_QUALITY_MAX_DISTANCE = t2.PARTIAL_RIP_QUALITY_MAX_DISTANCE), t2.PARTIAL_RIP_MAX_ATTEMPTS !== undefined \u0026\u0026 (e50.PARTIAL_RIP_MAX_ATTEMPTS = t2.PARTIAL_RIP_MAX_ATTEMPTS), t2.PARTIAL_RIP_WARMUP_FULL_RIP_ATTEMPTS !== undefined \u0026\u0026 (e50.PARTIAL_RIP_WARMUP_FULL_RIP_ATTEMPTS = t2.PARTIAL_RIP_WARMUP_FULL_RIP_ATTEMPTS), t2.PARTIAL_RIP_COMPLEXITY_SELECTION_MIN_ROUTE_COUNT !== undefined \u0026\u0026 (e50.PARTIAL_RIP_COMPLEXITY_SELECTION_MIN_ROUTE_COUNT = t2.PARTIAL_RIP_COMPLEXITY_SELECTION_MIN_ROUTE_COUNT), t2.PARTIAL_RIP_TARGET_MAX_COST_IMPROVEMENT_RATIO !== undefined \u0026\u0026 (e50.PARTIAL_RIP_TARGET_MAX_COST_IMPROVEMENT_RATIO = t2.PARTIAL_RIP_TARGET_MAX_COST_IMPROVEMENT_RATIO), t2.PARTIAL_RIP_MAX_REGION_COST_GROWTH_RATIO !== undefined \u0026\u0026 (e50.PARTIAL_RIP_MAX_REGION_COST_GROWTH_RATIO = t2.PARTIAL_RIP_MAX_REGION_COST_GROWTH_RATIO), t2.PARTIAL_RIP_MAX_TOTAL_COST_GROWTH_RATIO !== undefined \u0026\u0026 (e50.PARTIAL_RIP_MAX_TOTAL_COST_GROWTH_RATIO = t2.PARTIAL_RIP_MAX_TOTAL_COST_GROWTH_RATIO), t2.OUTSIDE_IN_ROUTING !== undefined \u0026\u0026 (e50.OUTSIDE_IN_ROUTING = t2.OUTSIDE_IN_ROUTING), t2.OUTSIDE_IN_MAX_DISTANCE !== undefined \u0026\u0026 (e50.OUTSIDE_IN_MAX_DISTANCE = t2.OUTSIDE_IN_MAX_DISTANCE));\n};\nvar Kq = (e50) =\u003e ({ minViaPadDiameter: e50.minViaPadDiameter, DISTANCE_TO_COST: e50.DISTANCE_TO_COST, RIP_THRESHOLD_START: e50.RIP_THRESHOLD_START, RIP_THRESHOLD_END: e50.RIP_THRESHOLD_END, RIP_THRESHOLD_RAMP_ATTEMPTS: e50.RIP_THRESHOLD_RAMP_ATTEMPTS, RIP_CONGESTION_REGION_COST_FACTOR: e50.RIP_CONGESTION_REGION_COST_FACTOR, TRACE_DENSITY_COST_FACTOR: e50.TRACE_DENSITY_COST_FACTOR, USE_LAZY_ROUTE_HEURISTIC: e50.USE_LAZY_ROUTE_HEURISTIC, USE_SPARSE_CANDIDATE_STORAGE: e50.USE_SPARSE_CANDIDATE_STORAGE, OWNED_REGIONAL_HOP_FRONTIER: e50.OWNED_REGIONAL_HOP_FRONTIER, MAX_ITERATIONS: e50.MAX_ITERATIONS, VERBOSE: e50.VERBOSE, STATIC_REACHABILITY_PRECHECK: e50.STATIC_REACHABILITY_PRECHECK, STATIC_REACHABILITY_PRECHECK_MAX_HOPS: e50.STATIC_REACHABILITY_PRECHECK_MAX_HOPS, ACCEPT_BEST_SOLUTION_ON_TIMEOUT: e50.ACCEPT_BEST_SOLUTION_ON_TIMEOUT, GREEDY_FINAL_ROUTE_ITERS: e50.GREEDY_FINAL_ROUTE_ITERS, PARTIAL_RIP_ENABLED: e50.PARTIAL_RIP_ENABLED, PARTIAL_RIP_MIN_ROUTE_COUNT: e50.PARTIAL_RIP_MIN_ROUTE_COUNT, PARTIAL_RIP_MAX_ROUTE_COUNT: e50.PARTIAL_RIP_MAX_ROUTE_COUNT, PARTIAL_RIP_MAX_DISTANCE: e50.PARTIAL_RIP_MAX_DISTANCE, PARTIAL_RIP_QUALITY_MAX_DISTANCE: e50.PARTIAL_RIP_QUALITY_MAX_DISTANCE, PARTIAL_RIP_MAX_ATTEMPTS: e50.PARTIAL_RIP_MAX_ATTEMPTS, PARTIAL_RIP_WARMUP_FULL_RIP_ATTEMPTS: e50.PARTIAL_RIP_WARMUP_FULL_RIP_ATTEMPTS, PARTIAL_RIP_COMPLEXITY_SELECTION_MIN_ROUTE_COUNT: e50.PARTIAL_RIP_COMPLEXITY_SELECTION_MIN_ROUTE_COUNT, PARTIAL_RIP_TARGET_MAX_COST_IMPROVEMENT_RATIO: e50.PARTIAL_RIP_TARGET_MAX_COST_IMPROVEMENT_RATIO, PARTIAL_RIP_MAX_REGION_COST_GROWTH_RATIO: e50.PARTIAL_RIP_MAX_REGION_COST_GROWTH_RATIO, PARTIAL_RIP_MAX_TOTAL_COST_GROWTH_RATIO: e50.PARTIAL_RIP_MAX_TOTAL_COST_GROWTH_RATIO, OUTSIDE_IN_ROUTING: e50.OUTSIDE_IN_ROUTING, OUTSIDE_IN_MAX_DISTANCE: e50.OUTSIDE_IN_MAX_DISTANCE });\nvar eJ = (e50, t2) =\u003e e50.f - t2.f;\nvar tJ = class e50 extends BaseSolver {\n constructor(e51, t2, n2) {\n super(), this.topology = e51, this.problem = t2, Qq(this, n2);\n let o3 = 1;\n const i3 = new Int32Array(e51.portCount).fill(-1), r3 = new Int32Array(e51.portCount).fill(-1);\n for (let t3 = 0;t3 \u003c e51.portCount; t3++) {\n const n3 = e51.incidentPortRegion[t3] ?? [];\n n3.length \u003e o3 \u0026\u0026 (o3 = n3.length), i3[t3] = n3[0] ?? -1, r3[t3] = n3[1] ?? -1;\n }\n this.candidateHopSlotStride = o3, this.candidateFirstRegionByPortId = i3, this.candidateSecondRegionByPortId = r3, this.hCostByPortId = new Float64Array(e51.portCount), this.hCostRouteIdByPortId = new Int32Array(e51.portCount).fill(-1);\n const s2 = e51.portCount * o3;\n this.candidateHopCapacity = s2, this.state = { portAssignment: new Int32Array(e51.portCount).fill(-1), regionSegments: Array.from({ length: e51.regionCount }, () =\u003e []), regionIntersectionCaches: Array.from({ length: e51.regionCount }, () =\u003e Zq()), currentRouteId: undefined, currentRouteNetId: undefined, unroutedRoutes: oq(t2.routeCount), candidateQueue: new UZ([], eJ), candidateBestCostByHopId: this.USE_SPARSE_CANDIDATE_STORAGE ? new Map : new Float64Array(s2), candidateBestCostGenerationByHopId: this.USE_SPARSE_CANDIDATE_STORAGE ? new Map : new Uint32Array(s2), candidateBestCostGeneration: 1, goalPortId: -1, ripCount: 0, regionCongestionCost: new Float64Array(e51.regionCount).fill(0) }, this.routeAttemptCountByRouteId = new Uint32Array(t2.routeCount), this.routeSuccessCountByRouteId = new Uint32Array(t2.routeCount);\n const a3 = GZ({ topology: e51, problem: t2, state: this.state, routeSuccessCountByRouteId: this.routeSuccessCountByRouteId, appendSegmentToRegionCache: (e52, t3, n3) =\u003e this.appendSegmentToRegionCache(e52, t3, n3) });\n a3 \u0026\u0026 (this.stats = { ...this.stats, ...a3 });\n }\n state;\n candidateHopSlotStride;\n candidateHopCapacity;\n candidateFirstRegionByPortId;\n candidateSecondRegionByPortId;\n candidateOverflowBestCost;\n regionalHopFrontierQueue;\n regionalHopFrontierEpoch;\n regionalHopFrontierGoalPortId;\n regionalHopFrontierRouteId;\n regionalHopFrontierNetId;\n regionalHopFrontierBestCostGeneration;\n regionalHopFrontiers = new Map;\n _problemSetup;\n hCostByPortId;\n hCostRouteIdByPortId;\n hCostEndRouteId;\n hCostEndX = 0;\n hCostEndY = 0;\n routeAttemptCountByRouteId;\n routeSuccessCountByRouteId;\n bestSolvedStateSnapshot;\n bestSolvedStateSummary;\n hasLoggedNeverSuccessfullyRoutedRoutes = false;\n staticallyUnroutableRoutes = [];\n segmentGeometryScratch = { netId: 0, lesserAngle: 0, greaterAngle: 0, layerMask: 0, entryExitLayerChanges: 0, sameLayerIntersectionCount: 0, crossingLayerIntersectionCount: 0 };\n ADD_SEGMENT_DISTANCE_TO_G = false;\n costAwareFinalReripBudget = 0;\n DISTANCE_TO_COST = 0.05;\n minViaPadDiameter = jZ;\n RIP_THRESHOLD_START = 0.05;\n RIP_THRESHOLD_END = 0.8;\n RIP_THRESHOLD_RAMP_ATTEMPTS = 50;\n RIP_CONGESTION_REGION_COST_FACTOR = 0.1;\n TRACE_DENSITY_COST_FACTOR = 0;\n USE_LAZY_ROUTE_HEURISTIC = true;\n USE_SPARSE_CANDIDATE_STORAGE = false;\n OWNED_REGIONAL_HOP_FRONTIER = false;\n MAX_ITERATIONS = 1e6;\n VERBOSE = false;\n STATIC_REACHABILITY_PRECHECK = true;\n STATIC_REACHABILITY_PRECHECK_MAX_HOPS = 16;\n ACCEPT_BEST_SOLUTION_ON_TIMEOUT = true;\n GREEDY_FINAL_ROUTE_ITERS = 4;\n PARTIAL_RIP_ENABLED = false;\n PARTIAL_RIP_MIN_ROUTE_COUNT = 0;\n PARTIAL_RIP_MAX_ROUTE_COUNT = Number.POSITIVE_INFINITY;\n PARTIAL_RIP_MAX_DISTANCE = 12;\n PARTIAL_RIP_QUALITY_MAX_DISTANCE;\n PARTIAL_RIP_MAX_ATTEMPTS = Number.POSITIVE_INFINITY;\n PARTIAL_RIP_WARMUP_FULL_RIP_ATTEMPTS = 0;\n PARTIAL_RIP_COMPLEXITY_SELECTION_MIN_ROUTE_COUNT = Number.POSITIVE_INFINITY;\n PARTIAL_RIP_TARGET_MAX_COST_IMPROVEMENT_RATIO = 0;\n PARTIAL_RIP_MAX_REGION_COST_GROWTH_RATIO = 0.2;\n PARTIAL_RIP_MAX_TOTAL_COST_GROWTH_RATIO = 0.1;\n OUTSIDE_IN_ROUTING = false;\n OUTSIDE_IN_MAX_DISTANCE = 24;\n resetForProblem(t2) {\n if (this.constructor !== e50)\n throw new Error(\"TinyHyperGraphSolver.resetForProblem cannot reset subclass routing state\");\n this.problem = t2, this._problemSetup = undefined, this.hCostEndRouteId = undefined, this.hCostRouteIdByPortId.fill(-1), this.state.portAssignment.fill(-1);\n for (const e51 of this.state.regionSegments)\n e51.length = 0;\n this.state.regionIntersectionCaches.fill(Zq()), this.state.currentRouteId = undefined, this.state.currentRouteNetId = undefined, this.state.unroutedRoutes = oq(t2.routeCount), this.state.candidateQueue.clear(), this.state.candidateBestCostGeneration = 1, this.state.candidateBestCostByHopId instanceof Map ? this.state.candidateBestCostByHopId.clear() : this.state.candidateBestCostByHopId.fill(0), this.state.candidateBestCostGenerationByHopId instanceof Map ? this.state.candidateBestCostGenerationByHopId.clear() : this.state.candidateBestCostGenerationByHopId.fill(0), this.state.goalPortId = -1, this.state.ripCount = 0, this.state.regionCongestionCost.fill(0), this.routeAttemptCountByRouteId = new Uint32Array(t2.routeCount), this.routeSuccessCountByRouteId = new Uint32Array(t2.routeCount), this.bestSolvedStateSnapshot = undefined, this.bestSolvedStateSummary = undefined, this.hasLoggedNeverSuccessfullyRoutedRoutes = false, this.staticallyUnroutableRoutes = [], this.candidateOverflowBestCost?.clear(), this.solved = false, this.failed = false, this.iterations = 0, this.progress = 0, this.error = null, this.activeSubSolver = undefined, this.failedSubSolvers = undefined, this.timeToSolve = undefined, this.stats = {}, this._setupDone = false;\n const n2 = GZ({ topology: this.topology, problem: t2, state: this.state, routeSuccessCountByRouteId: this.routeSuccessCountByRouteId, appendSegmentToRegionCache: (e51, t3, n3) =\u003e this.appendSegmentToRegionCache(e51, t3, n3) });\n n2 \u0026\u0026 (this.stats = { ...this.stats, ...n2 });\n }\n get problemSetup() {\n return this._problemSetup || (this._problemSetup = this.computeProblemSetup()), this._problemSetup;\n }\n computeProblemSetup() {\n const { topology: e51, problem: t2 } = this, n2 = this.USE_LAZY_ROUTE_HEURISTIC ? undefined : new Float64Array(e51.portCount * t2.routeCount), o3 = e51.portX, i3 = e51.portY, r3 = [], s2 = new Int32Array(e51.portCount).fill(-1), a3 = (e52, t3) =\u003e {\n const n3 = r3[e52] ?? new Set;\n n3.add(t3), r3[e52] = n3;\n const o4 = s2[e52];\n o4 === -1 ? s2[e52] = t3 : o4 !== t3 \u0026\u0026 (s2[e52] = -2);\n };\n for (let r4 = 0;r4 \u003c t2.routeCount; r4++) {\n const s3 = t2.routeNet[r4];\n if (a3(t2.routeStartPort[r4], s3), a3(t2.routeEndPort[r4], s3), n2) {\n const s4 = t2.routeEndPort[r4], a4 = o3[s4], c3 = i3[s4];\n for (let s5 = 0;s5 \u003c e51.portCount; s5++) {\n const e52 = o3[s5] - a4, l3 = i3[s5] - c3;\n n2[s5 * t2.routeCount + r4] = Math.sqrt(e52 * e52 + l3 * l3) * this.DISTANCE_TO_COST;\n }\n }\n }\n return { ...n2 ? { portHCostToEndOfRoute: n2 } : {}, portEndpointNetIds: r3, portEndpointReservationNetId: s2 };\n }\n _setup() {\n if (this.problemSetup, this.STATIC_REACHABILITY_PRECHECK) {\n const e51 = nq({ topology: this.topology, problem: this.problem, problemSetup: this.problemSetup, portAssignment: this.state.portAssignment, routeIds: this.state.unroutedRoutes, maxPrecheckHops: Math.max(0, this.STATIC_REACHABILITY_PRECHECK_MAX_HOPS), getStartingNextRegionId: (e52, t2) =\u003e this.getStartingNextRegionId(e52, t2), getRouteSummary: (e52) =\u003e this.getRouteSummary(e52) });\n this.staticallyUnroutableRoutes = e51, e51.length \u003e 0 \u0026\u0026 (this.failed = true, this.error = ((e52) =\u003e {\n const t2 = e52.slice(0, 5).map((e53) =\u003e {\n const t3 = e53.pointIds.length \u003e= 2 ? `${e53.pointIds[0]}-\u003e${e53.pointIds[1]}` : `${e53.startPortId}-\u003e${e53.endPortId}`;\n return `${e53.connectionId} (${t3})`;\n }).join(\", \"), n2 = e52.length - 5;\n return [\"Static reachability precheck failed:\", `${e52.length} route(s) have no legal path under the current reservation and start-region rules`, n2 \u003e 0 ? `${t2}, +${n2} more` : t2].join(\" \");\n })(e51), this.stats = { ...this.stats, staticallyUnroutableRouteCount: e51.length });\n }\n }\n _step() {\n const { problem: e51, topology: t2, state: n2 } = this;\n if (n2.currentRouteId === undefined) {\n if (n2.unroutedRoutes.length === 0)\n return void this.onAllRoutesRouted();\n n2.currentRouteId = n2.unroutedRoutes.shift(), n2.currentRouteNetId = e51.routeNet[n2.currentRouteId], this.routeAttemptCountByRouteId[n2.currentRouteId] += 1, this.resetCandidateBestCosts();\n const t3 = this.getRouteStartPortId(n2.currentRouteId);\n n2.candidateQueue.clear();\n const o4 = this.getStartingNextRegionId(n2.currentRouteId, t3);\n if (o4 === undefined)\n return this.failed = true, void (this.error = `Start port ${t3} has no incident regions`);\n const i4 = this.getHopId(t3, o4);\n this.setCandidateBestCost(i4, 0), n2.candidateQueue.queue({ hopId: i4, nextRegionId: o4, portId: t3, f: 0, g: 0, h: 0 }), n2.goalPortId = this.getRouteEndPortId(n2.currentRouteId);\n }\n const o3 = n2.candidateQueue.dequeue();\n if (!o3)\n return void this.onOutOfCandidates();\n const i3 = o3.hopId ?? this.getHopId(o3.portId, o3.nextRegionId);\n if (o3.g \u003e this.getCandidateBestCost(i3))\n return;\n if (this.isRegionReservedForDifferentNet(o3.nextRegionId))\n return;\n const r3 = t2.regionIncidentPorts[o3.nextRegionId];\n if (this.OWNED_REGIONAL_HOP_FRONTIER) {\n const e52 = this.getRegionalHopFrontier(o3.nextRegionId, r3);\n if (e52)\n return void this.expandRegionalHopFrontier(o3, e52);\n }\n for (const i4 of r3) {\n if (i4 === n2.goalPortId) {\n const e52 = n2.portAssignment[i4];\n if (this.isPortReservedForDifferentNet(i4))\n continue;\n if (e52 !== -1 \u0026\u0026 e52 !== n2.currentRouteNetId)\n continue;\n return void this.onPathFound(o3);\n }\n if (i4 === o3.portId)\n continue;\n if (e51.portSectionMask[i4] === 0)\n continue;\n const r4 = t2.incidentPortRegion[i4][0] === o3.nextRegionId ? t2.incidentPortRegion[i4][1] : t2.incidentPortRegion[i4][0];\n if (r4 === undefined)\n continue;\n const s2 = this.getHopId(i4, r4);\n if ((n2.candidateQueue.isClosedHopId ? n2.candidateQueue.isClosedHopId(s2) : n2.candidateQueue.isClosedHop?.(i4, r4)) === true)\n continue;\n const a3 = n2.portAssignment[i4];\n if (this.isPortReservedForDifferentNet(i4))\n continue;\n if (a3 !== -1 \u0026\u0026 a3 !== n2.currentRouteNetId)\n continue;\n if (this.isRegionReservedForDifferentNet(r4))\n continue;\n const c3 = this.getCandidateBestCost(s2);\n if (o3.g \u003e= c3)\n continue;\n let l3, h2 = o3.g + n2.regionCongestionCost[o3.nextRegionId] + (e51.portPenalty?.[i4] ?? 0);\n if (this.ADD_SEGMENT_DISTANCE_TO_G) {\n const e52 = t2.portX[o3.portId] - t2.portX[i4], n3 = t2.portY[o3.portId] - t2.portY[i4];\n l3 = Math.sqrt(e52 * e52 + n3 * n3), h2 += l3 * this.DISTANCE_TO_COST;\n }\n if (h2 \u003e= c3)\n continue;\n const d2 = this.computeG(o3, i4, c3, l3);\n if (!Number.isFinite(d2) || d2 \u003e= c3)\n continue;\n const u2 = this.computeH(i4), p3 = { hopId: s2, prevRegionId: o3.nextRegionId, nextRegionId: r4, portId: i4, g: d2, h: u2, f: d2 + u2, prevCandidate: o3 };\n if (i4 === n2.goalPortId)\n return void this.onPathFound(p3);\n this.setCandidateBestCost(s2, d2), n2.candidateQueue.queue(p3);\n }\n }\n getRegionalHopFrontier(e51, t2) {\n const { state: n2 } = this, o3 = n2.candidateQueue;\n if (!(o3 instanceof ZZ))\n return this.regionalHopFrontierQueue = undefined, this.regionalHopFrontierEpoch = undefined, void this.regionalHopFrontiers.clear();\n const i3 = o3.closureEpoch;\n if (o3 === this.regionalHopFrontierQueue \u0026\u0026 i3 === this.regionalHopFrontierEpoch \u0026\u0026 n2.goalPortId === this.regionalHopFrontierGoalPortId \u0026\u0026 n2.currentRouteId === this.regionalHopFrontierRouteId \u0026\u0026 n2.currentRouteNetId === this.regionalHopFrontierNetId \u0026\u0026 n2.candidateBestCostGeneration === this.regionalHopFrontierBestCostGeneration || (this.regionalHopFrontierQueue = o3, this.regionalHopFrontierEpoch = i3, this.regionalHopFrontierGoalPortId = n2.goalPortId, this.regionalHopFrontierRouteId = n2.currentRouteId, this.regionalHopFrontierNetId = n2.currentRouteNetId, this.regionalHopFrontierBestCostGeneration = n2.candidateBestCostGeneration, this.regionalHopFrontiers.clear()), !Array.isArray(t2) || t2.length \u003e 2147483647)\n return;\n let r3 = this.regionalHopFrontiers.get(e51);\n if (!r3 || r3.neighbors !== t2) {\n const n3 = new Int32Array(t2.length);\n for (let e52 = 0;e52 \u003c t2.length; e52++)\n n3[e52] = e52 + 1 \u003c t2.length ? e52 + 1 : -1;\n r3 = { neighbors: t2, next: n3, prepared: new Uint8Array(t2.length), nextRegionIds: new Float64Array(t2.length), hopIds: new Float64Array(t2.length), head: t2.length \u003e 0 ? 0 : -1 }, this.regionalHopFrontiers.set(e51, r3);\n }\n return r3;\n }\n expandRegionalHopFrontier(e51, t2) {\n const { problem: n2, topology: o3, state: i3 } = this, { neighbors: r3, next: s2, prepared: a3, nextRegionIds: c3, hopIds: l3 } = t2;\n let h2 = t2.head, d2 = -1;\n for (;h2 !== -1; ) {\n const u2 = h2;\n h2 = s2[u2];\n const p3 = d2;\n d2 = u2;\n const m2 = r3[u2];\n if (m2 === i3.goalPortId) {\n const t3 = i3.portAssignment[m2];\n if (this.isPortReservedForDifferentNet(m2))\n continue;\n if (t3 !== -1 \u0026\u0026 t3 !== i3.currentRouteNetId)\n continue;\n return void this.onPathFound(e51);\n }\n if (m2 === e51.portId)\n continue;\n let g2, f2;\n if (a3[u2])\n g2 = c3[u2], f2 = l3[u2];\n else {\n if (n2.portSectionMask[m2] === 0)\n continue;\n const t3 = o3.incidentPortRegion[m2][0] === e51.nextRegionId ? o3.incidentPortRegion[m2][1] : o3.incidentPortRegion[m2][0];\n if (t3 === undefined)\n continue;\n g2 = t3, f2 = this.getHopId(m2, g2);\n }\n if ((i3.candidateQueue.isClosedHopId ? i3.candidateQueue.isClosedHopId(f2) : i3.candidateQueue.isClosedHop?.(m2, g2)) === true) {\n p3 === -1 ? t2.head = h2 : s2[p3] = h2, d2 = p3;\n continue;\n }\n if (!a3[u2]) {\n const e52 = i3.portAssignment[m2];\n if (this.isPortReservedForDifferentNet(m2))\n continue;\n if (e52 !== -1 \u0026\u0026 e52 !== i3.currentRouteNetId)\n continue;\n if (this.isRegionReservedForDifferentNet(g2))\n continue;\n c3[u2] = g2, l3[u2] = f2, a3[u2] = 1;\n }\n const _2 = this.getCandidateBestCost(f2);\n if (e51.g \u003e= _2)\n continue;\n let y2, b2 = e51.g + i3.regionCongestionCost[e51.nextRegionId] + (n2.portPenalty?.[m2] ?? 0);\n if (this.ADD_SEGMENT_DISTANCE_TO_G) {\n const t3 = o3.portX[e51.portId] - o3.portX[m2], n3 = o3.portY[e51.portId] - o3.portY[m2];\n y2 = Math.sqrt(t3 * t3 + n3 * n3), b2 += y2 * this.DISTANCE_TO_COST;\n }\n if (b2 \u003e= _2)\n continue;\n const x2 = this.computeG(e51, m2, _2, y2);\n if (!Number.isFinite(x2) || x2 \u003e= _2)\n continue;\n const v2 = this.computeH(m2), I2 = { hopId: f2, prevRegionId: e51.nextRegionId, nextRegionId: g2, portId: m2, g: x2, h: v2, f: x2 + v2, prevCandidate: e51 };\n if (m2 === i3.goalPortId)\n return void this.onPathFound(I2);\n this.setCandidateBestCost(f2, x2), i3.candidateQueue.queue(I2);\n }\n }\n resetCandidateBestCosts() {\n const { state: e51 } = this;\n if (this.candidateOverflowBestCost?.clear(), e51.candidateBestCostGeneration === 4294967295)\n return e51.candidateBestCostByHopId instanceof Map \u0026\u0026 e51.candidateBestCostByHopId.clear(), e51.candidateBestCostGenerationByHopId instanceof Map ? e51.candidateBestCostGenerationByHopId.clear() : e51.candidateBestCostGenerationByHopId.fill(0), void (e51.candidateBestCostGeneration = 1);\n e51.candidateBestCostGeneration += 1;\n }\n getCandidateBestCost(e51) {\n if (e51 \u003c 0)\n return this.candidateOverflowBestCost?.get(e51) ?? Number.POSITIVE_INFINITY;\n const { state: t2 } = this, n2 = t2.candidateBestCostGenerationByHopId;\n return (n2 instanceof Map ? n2.get(e51) : n2[e51]) === t2.candidateBestCostGeneration ? t2.candidateBestCostByHopId instanceof Map ? t2.candidateBestCostByHopId.get(e51) : t2.candidateBestCostByHopId[e51] : Number.POSITIVE_INFINITY;\n }\n setCandidateBestCost(e51, t2) {\n if (e51 \u003c 0)\n return this.candidateOverflowBestCost || (this.candidateOverflowBestCost = new Map), void this.candidateOverflowBestCost.set(e51, t2);\n const { state: n2 } = this;\n n2.candidateBestCostGenerationByHopId instanceof Map ? n2.candidateBestCostGenerationByHopId.set(e51, n2.candidateBestCostGeneration) : n2.candidateBestCostGenerationByHopId[e51] = n2.candidateBestCostGeneration, n2.candidateBestCostByHopId instanceof Map ? n2.candidateBestCostByHopId.set(e51, t2) : n2.candidateBestCostByHopId[e51] = t2;\n }\n getHopId(e51, t2) {\n const n2 = e51 * this.candidateHopSlotStride;\n if (this.candidateFirstRegionByPortId[e51] === t2)\n return n2;\n if (this.candidateSecondRegionByPortId[e51] === t2)\n return n2 + 1;\n const o3 = this.topology.incidentPortRegion[e51];\n for (let e52 = 2;e52 \u003c (o3?.length ?? 0); e52++)\n if (o3[e52] === t2)\n return n2 + e52;\n return -(e51 * this.topology.regionCount + t2) - 1;\n }\n getStartingNextRegionId(e51, t2) {\n const n2 = this.topology.incidentPortRegion[t2] ?? [], o3 = this.problem.routeNet[e51];\n return n2.find((e52) =\u003e this.problem.regionNetId[e52] === -1) ?? n2.find((e52) =\u003e this.problem.regionNetId[e52] === o3) ?? n2[0];\n }\n getRouteStartPortId(e51) {\n return this.problem.routeStartPort[e51];\n }\n getRouteEndPortId(e51) {\n return this.problem.routeEndPort[e51];\n }\n isPortReservedForDifferentNet(e51) {\n const t2 = this.problemSetup.portEndpointReservationNetId[e51] ?? -1;\n return t2 === -2 || t2 !== -1 \u0026\u0026 t2 !== this.state.currentRouteNetId;\n }\n isRegionReservedForDifferentNet(e51) {\n const t2 = this.problem.regionNetId[e51];\n return t2 !== -1 \u0026\u0026 t2 !== this.state.currentRouteNetId;\n }\n isKnownSingleLayerRegion(e51) {\n const t2 = this.topology.regionAvailableZMask?.[e51] ?? 0;\n return $Z(t2);\n }\n computeRegionCostForRegion(e51, t2, n2, o3, i3) {\n return YZ(this.topology.regionWidth[e51], this.topology.regionHeight[e51], t2, n2, o3, i3, this.topology.regionAvailableZMask?.[e51] ?? 0, this.minViaPadDiameter, this.TRACE_DENSITY_COST_FACTOR);\n }\n populateSegmentGeometryScratch(e51, t2, n2) {\n return this.populateBaseSegmentGeometryScratch(e51, t2, n2);\n }\n populateBaseSegmentGeometryScratch(e51, t2, n2) {\n const { state: o3, topology: i3 } = this, r3 = this.segmentGeometryScratch, s2 = this.candidateFirstRegionByPortId[t2] === e51 || this.candidateSecondRegionByPortId[t2] !== e51 ? i3.portAngleForRegion1[t2] : i3.portAngleForRegion2?.[t2] ?? i3.portAngleForRegion1[t2], a3 = this.candidateFirstRegionByPortId[n2] === e51 || this.candidateSecondRegionByPortId[n2] !== e51 ? i3.portAngleForRegion1[n2] : i3.portAngleForRegion2?.[n2] ?? i3.portAngleForRegion1[n2], c3 = i3.portZ[t2], l3 = i3.portZ[n2];\n return r3.lesserAngle = s2 \u003c a3 ? s2 : a3, r3.greaterAngle = s2 \u003c a3 ? a3 : s2, r3.layerMask = 1 \u003c\u003c c3 | 1 \u003c\u003c l3, r3.entryExitLayerChanges = c3 !== l3 ? 1 : 0, r3.netId = o3.currentRouteNetId, r3;\n }\n appendSegmentToRegionCache(e51, t2, n2) {\n const { state: o3 } = this, i3 = o3.regionIntersectionCaches[e51], r3 = this.populateSegmentGeometryScratch(e51, t2, n2);\n VZ(i3, r3);\n const { sameLayerIntersectionCount: s2, crossingLayerIntersectionCount: a3, entryExitLayerChanges: c3 } = r3, l3 = i3.netIds.length + 1, h2 = new Int32Array(l3);\n h2.set(i3.netIds), h2[l3 - 1] = o3.currentRouteNetId;\n const d2 = new Int32Array(l3);\n d2.set(i3.lesserAngles), d2[l3 - 1] = r3.lesserAngle;\n const u2 = new Int32Array(l3);\n u2.set(i3.greaterAngles), u2[l3 - 1] = r3.greaterAngle;\n const p3 = new Int32Array(l3);\n p3.set(i3.layerMasks), p3[l3 - 1] = r3.layerMask;\n const m2 = i3.existingSameLayerIntersections + s2, g2 = i3.existingCrossingLayerIntersections + a3, f2 = i3.existingEntryExitLayerChanges + c3, _2 = d2.length;\n o3.regionIntersectionCaches[e51] = { netIds: h2, lesserAngles: d2, greaterAngles: u2, layerMasks: p3, existingSameLayerIntersections: m2, existingCrossingLayerIntersections: g2, existingEntryExitLayerChanges: f2, existingSegmentCount: _2, existingRegionCost: this.computeRegionCostForRegion(e51, m2, g2, f2, _2) };\n }\n getSolvedPathSegments(e51) {\n const { state: t2 } = this, n2 = [];\n let o3 = e51;\n for (;o3; )\n n2.unshift(o3), o3 = o3.prevCandidate;\n const i3 = [];\n for (let e52 = 1;e52 \u003c n2.length; e52++)\n i3.push({ regionId: n2[e52 - 1].nextRegionId, fromPortId: n2[e52 - 1].portId, toPortId: n2[e52].portId });\n const r3 = n2[n2.length - 1];\n return r3 \u0026\u0026 r3.portId !== t2.goalPortId \u0026\u0026 i3.push({ regionId: r3.nextRegionId, fromPortId: r3.portId, toPortId: t2.goalPortId }), i3;\n }\n resetRoutingStateForRerip() {\n const { topology: e51, problem: t2, state: n2 } = this;\n n2.portAssignment.fill(-1), n2.regionSegments = Array.from({ length: e51.regionCount }, () =\u003e []), n2.regionIntersectionCaches = Array.from({ length: e51.regionCount }, () =\u003e Zq()), n2.currentRouteNetId = undefined, n2.currentRouteId = undefined, n2.unroutedRoutes = qZ(oq(t2.routeCount), n2.ripCount), n2.candidateQueue.clear(), this.resetCandidateBestCosts(), n2.goalPortId = -1;\n }\n getMaxRegionCost() {\n const { topology: e51, state: t2 } = this;\n let n2 = 0;\n for (let o3 = 0;o3 \u003c e51.regionCount; o3++) {\n const e52 = t2.regionIntersectionCaches[o3]?.existingRegionCost ?? 0;\n n2 = Math.max(n2, e52);\n }\n return n2;\n }\n getRouteMetadata(e51) {\n return this.problem.routeMetadata?.[e51];\n }\n getRouteConnectionId(e51) {\n const t2 = this.getRouteMetadata(e51)?.connectionId;\n return typeof t2 == \"string\" ? t2 : `route-${e51}`;\n }\n getRouteSummary(e51) {\n return (({ problem: e52, routeId: t2, getRouteMetadata: n2, getRouteConnectionId: o3 }) =\u003e {\n const i3 = n2?.(t2) ?? JZ(e52, t2);\n return { routeId: t2, connectionId: o3?.(t2) ?? KZ(e52, t2), startPortId: e52.routeStartPort[t2], endPortId: e52.routeEndPort[t2], startRegionId: typeof i3?.startRegionId == \"string\" ? i3.startRegionId : undefined, endRegionId: typeof i3?.endRegionId == \"string\" ? i3.endRegionId : undefined, pointIds: QZ(i3) };\n })({ problem: this.problem, routeId: e51, getRouteMetadata: (e52) =\u003e this.getRouteMetadata(e52), getRouteConnectionId: (e52) =\u003e this.getRouteConnectionId(e52) });\n }\n getAdditionalRegionLabel(e51) {}\n getNeverSuccessfullyRoutedRoutes() {\n const e51 = [];\n for (let t2 = 0;t2 \u003c this.problem.routeCount; t2++) {\n const n2 = this.routeAttemptCountByRouteId[t2];\n n2 === 0 || this.routeSuccessCountByRouteId[t2] \u003e 0 || e51.push({ ...this.getRouteSummary(t2), attempts: n2 });\n }\n return e51;\n }\n getStaticallyUnroutableRoutes() {\n return this.staticallyUnroutableRoutes;\n }\n logNeverSuccessfullyRoutedRoutes() {\n if (!this.VERBOSE || this.hasLoggedNeverSuccessfullyRoutedRoutes)\n return;\n const e51 = this.getNeverSuccessfullyRoutedRoutes();\n if (this.hasLoggedNeverSuccessfullyRoutedRoutes = true, e51.length !== 0) {\n console.log([\"[TinyHyperGraphSolver:never-routed-summary]\", `count=${e51.length}`].join(\" \"));\n for (const t2 of e51) {\n const e52 = t2.pointIds.length \u003e= 2 ? `${t2.pointIds[0]}-\u003e${t2.pointIds[1]}` : \"unknown\";\n console.log([\"[TinyHyperGraphSolver:never-routed]\", `routeId=${t2.routeId}`, `connectionId=${t2.connectionId}`, `attempts=${t2.attempts}`, `pointPath=${e52}`, `startRegionId=${t2.startRegionId ?? \"unknown\"}`, `endRegionId=${t2.endRegionId ?? \"unknown\"}`].join(\" \"));\n }\n }\n }\n logRipEvent(e51, t2, n2 = {}) {\n this.VERBOSE \u0026\u0026 console.log([\"[TinyHyperGraphSolver:rip]\", `ripCount=${this.state.ripCount}`, `maxRegionCostBeforeRip=${t2.toFixed(3)}`, `reason=${e51}`, ...Object.entries(n2).map(([e52, t3]) =\u003e `${e52}=${typeof t3 == \"number\" ? Number.isInteger(t3) ? String(t3) : t3.toFixed(3) : t3}`)].join(\" \"));\n }\n compareRegionCostSummaries(e51, t2) {\n return e51.maxRegionCost !== t2.maxRegionCost ? e51.maxRegionCost - t2.maxRegionCost : e51.totalRegionCost - t2.totalRegionCost;\n }\n captureBestSolvedState(e51) {\n this.bestSolvedStateSummary \u0026\u0026 this.compareRegionCostSummaries(e51, this.bestSolvedStateSummary) \u003e= 0 || this.replaceBestSolvedState(e51);\n }\n replaceBestSolvedState(e51) {\n this.bestSolvedStateSummary = e51, this.bestSolvedStateSnapshot = Jq({ portAssignment: this.state.portAssignment, regionSegments: this.state.regionSegments, regionIntersectionCaches: this.state.regionIntersectionCaches, regionCongestionCost: this.state.regionCongestionCost, ripCount: this.state.ripCount });\n }\n restoreBestSolvedState() {\n if (!this.bestSolvedStateSnapshot)\n return;\n const e51 = Jq(this.bestSolvedStateSnapshot);\n this.state.portAssignment = e51.portAssignment, this.state.regionSegments = e51.regionSegments, this.state.regionIntersectionCaches = e51.regionIntersectionCaches, this.state.regionCongestionCost = e51.regionCongestionCost, this.state.ripCount = e51.ripCount, this.state.currentRouteId = undefined, this.state.currentRouteNetId = undefined, this.state.unroutedRoutes = [], this.state.candidateQueue.clear(), this.resetCandidateBestCosts(), this.state.goalPortId = -1;\n }\n getRemainingRouteIdsForGreedyFinalRoute() {\n const e51 = new Set(this.state.unroutedRoutes);\n return this.state.currentRouteId !== undefined \u0026\u0026 e51.add(this.state.currentRouteId), [...e51];\n }\n applySnapshotToGreedyFinalRouteSolver(e51, t2, n2) {\n const o3 = Jq(t2);\n e51.state.portAssignment = o3.portAssignment, e51.state.regionSegments = o3.regionSegments, e51.state.regionIntersectionCaches = o3.regionIntersectionCaches, e51.state.regionCongestionCost = o3.regionCongestionCost, e51.state.ripCount = 0, e51.state.currentRouteId = undefined, e51.state.currentRouteNetId = undefined, e51.state.unroutedRoutes = [...n2], e51.state.candidateQueue.clear(), e51.resetCandidateBestCosts(), e51.state.goalPortId = -1;\n }\n summarizeSolvedState(e51) {\n let t2 = 0, n2 = 0;\n for (const o3 of e51.state.regionIntersectionCaches) {\n const e52 = o3.existingRegionCost;\n t2 = Math.max(t2, e52), n2 += e52;\n }\n return { maxRegionCost: t2, totalRegionCost: n2 };\n }\n createGreedyFinalRouteSolver(e51, t2) {\n return new nJ(this.topology, this.problem, e51);\n }\n tryGreedyFinalRouteAcceptance() {\n const e51 = Math.max(0, Math.floor(this.GREEDY_FINAL_ROUTE_ITERS));\n if (e51 === 0)\n return false;\n const t2 = this.getRemainingRouteIdsForGreedyFinalRoute();\n if (t2.length === 0)\n return false;\n const n2 = Jq({ portAssignment: this.state.portAssignment, regionSegments: this.state.regionSegments, regionIntersectionCaches: this.state.regionIntersectionCaches, regionCongestionCost: this.state.regionCongestionCost, ripCount: this.state.ripCount });\n let o3 = 50000;\n for (let i3 = this.state.ripCount \u003c this.costAwareFinalReripBudget ? -1 : 0;i3 \u003c e51; i3++) {\n const e52 = i3 \u003c= 0 ? t2 : qZ(t2, this.state.ripCount + i3), r3 = this.createGreedyFinalRouteSolver({ ...Kq(this), ACCEPT_BEST_SOLUTION_ON_TIMEOUT: false, GREEDY_FINAL_ROUTE_ITERS: 0, MAX_ITERATIONS: 50000, RIP_THRESHOLD_RAMP_ATTEMPTS: 0, STATIC_REACHABILITY_PRECHECK: false, OUTSIDE_IN_ROUTING: false, PARTIAL_RIP_ENABLED: false }, i3);\n if (o3 = r3.MAX_ITERATIONS, this.applySnapshotToGreedyFinalRouteSolver(r3, n2, e52), r3.solve(), r3.solved \u0026\u0026 !r3.failed)\n return this.bestSolvedStateSnapshot = Jq({ portAssignment: r3.state.portAssignment, regionSegments: r3.state.regionSegments, regionIntersectionCaches: r3.state.regionIntersectionCaches, regionCongestionCost: r3.state.regionCongestionCost, ripCount: r3.state.ripCount }), this.bestSolvedStateSummary = this.summarizeSolvedState(r3), this.restoreBestSolvedState(), this.stats = { ...this.stats, acceptedGreedyFinalRouteOnTimeout: true, greedyFinalRouteIter: Math.max(0, i3), finalRoutingStrategy: i3 \u003c 0 ? \"congestion-aware\" : \"greedy\", greedyFinalRouteRemainingRouteCount: t2.length, greedyFinalRouteMaxIterations: o3, neverSuccessfullyRoutedRouteCount: 0, maxRegionCost: this.bestSolvedStateSummary.maxRegionCost, totalRegionCost: this.bestSolvedStateSummary.totalRegionCost, bestMaxRegionCost: this.bestSolvedStateSummary.maxRegionCost, bestTotalRegionCost: this.bestSolvedStateSummary.totalRegionCost }, this.solved = true, this.failed = false, this.error = null, true;\n }\n return this.stats = { ...this.stats, greedyFinalRouteAttemptCount: e51, greedyFinalRouteRemainingRouteCount: t2.length, greedyFinalRouteMaxIterations: o3 }, false;\n }\n onAllRoutesRouted() {\n const { topology: e51, state: t2 } = this, n2 = this.RIP_THRESHOLD_RAMP_ATTEMPTS \u003c= 0 ? 1 : Math.min(1, t2.ripCount / this.RIP_THRESHOLD_RAMP_ATTEMPTS), o3 = this.RIP_THRESHOLD_START + (this.RIP_THRESHOLD_END - this.RIP_THRESHOLD_START) * n2, i3 = [], r3 = new Float64Array(e51.regionCount);\n let s2 = 0, a3 = 0;\n for (let n3 = 0;n3 \u003c e51.regionCount; n3++) {\n const e52 = t2.regionIntersectionCaches[n3]?.existingRegionCost ?? 0;\n r3[n3] = e52, s2 = Math.max(s2, e52), a3 += e52, e52 \u003e o3 \u0026\u0026 i3.push(n3);\n }\n const c3 = { maxRegionCost: s2, totalRegionCost: a3 }, l3 = i3.length === 0 || t2.ripCount \u003e= this.RIP_THRESHOLD_RAMP_ATTEMPTS;\n if (l3 ? (!this.bestSolvedStateSummary || this.compareRegionCostSummaries(c3, this.bestSolvedStateSummary) \u003c 0) \u0026\u0026 (this.bestSolvedStateSummary = c3) : this.captureBestSolvedState(c3), this.stats = { ...this.stats, currentRipThreshold: o3, hotRegionCount: i3.length, maxRegionCost: s2, totalRegionCost: a3, bestMaxRegionCost: this.bestSolvedStateSummary?.maxRegionCost, bestTotalRegionCost: this.bestSolvedStateSummary?.totalRegionCost, ripCount: t2.ripCount }, l3)\n this.solved = true;\n else {\n for (let n3 = 0;n3 \u003c e51.regionCount; n3++)\n t2.regionCongestionCost[n3] += r3[n3] * this.RIP_CONGESTION_REGION_COST_FACTOR;\n t2.ripCount += 1, this.resetRoutingStateForRerip(), this.stats = { ...this.stats, ripCount: t2.ripCount, maxRegionCostBeforeRip: s2, reripRegionCount: i3.length }, this.logRipEvent(\"hot_regions\", s2, { hotRegionCount: i3.length, currentRipThreshold: o3 });\n }\n }\n onOutOfCandidates() {\n const { topology: e51, state: t2 } = this, n2 = t2.currentRouteId, o3 = this.getMaxRegionCost();\n for (let n3 = 0;n3 \u003c e51.regionCount; n3++) {\n const e52 = t2.regionIntersectionCaches[n3]?.existingRegionCost ?? 0;\n t2.regionCongestionCost[n3] += e52 * this.RIP_CONGESTION_REGION_COST_FACTOR;\n }\n t2.ripCount += 1, this.resetRoutingStateForRerip(), this.stats = { ...this.stats, ripCount: t2.ripCount, maxRegionCost: o3, maxRegionCostBeforeRip: o3, reripReason: \"out_of_candidates\" }, this.logRipEvent(\"out_of_candidates\", o3, { ...n2 === undefined ? {} : { routeId: n2, connectionId: this.getRouteConnectionId(n2) } });\n }\n onPathFound(e51) {\n const { state: t2 } = this, n2 = t2.currentRouteId;\n if (n2 === undefined)\n return;\n this.routeSuccessCountByRouteId[n2] += 1;\n const o3 = this.getSolvedPathSegments(e51);\n for (const { regionId: e52, fromPortId: i3, toPortId: r3 } of o3)\n t2.regionSegments[e52].push([n2, i3, r3]), t2.portAssignment[i3] = t2.currentRouteNetId, t2.portAssignment[r3] = t2.currentRouteNetId, this.appendSegmentToRegionCache(e52, i3, r3);\n t2.candidateQueue.clear(), t2.currentRouteNetId = undefined, t2.currentRouteId = undefined;\n }\n computeG(e51, t2, n2 = Number.POSITIVE_INFINITY, o3) {\n const { state: i3, topology: r3 } = this, s2 = e51.nextRegionId, a3 = i3.regionIntersectionCaches[s2], c3 = i3.regionCongestionCost[s2], l3 = this.problem.portPenalty?.[t2] ?? 0;\n let h2 = 0;\n if (this.ADD_SEGMENT_DISTANCE_TO_G) {\n let n3 = o3;\n if (n3 === undefined) {\n const o4 = r3.portX[e51.portId] - r3.portX[t2], i4 = r3.portY[e51.portId] - r3.portY[t2];\n n3 = Math.sqrt(o4 * o4 + i4 * i4);\n }\n h2 = n3 * this.DISTANCE_TO_COST;\n }\n if (e51.g + c3 + l3 + h2 \u003e n2 + 0.000000001)\n return Number.POSITIVE_INFINITY;\n let d2 = 0, u2 = 0, p3 = r3.portZ[e51.portId] !== r3.portZ[t2] ? 1 : 0;\n if (a3.existingSegmentCount \u003e 0) {\n const n3 = this.populateBaseSegmentGeometryScratch(s2, e51.portId, t2);\n VZ(a3, n3), d2 = n3.sameLayerIntersectionCount, u2 = n3.crossingLayerIntersectionCount, p3 = n3.entryExitLayerChanges;\n }\n if (d2 \u003e 0 \u0026\u0026 this.isKnownSingleLayerRegion(s2))\n return Number.POSITIVE_INFINITY;\n const m2 = this.computeRegionCostForRegion(s2, a3.existingSameLayerIntersections + d2, a3.existingCrossingLayerIntersections + u2, a3.existingEntryExitLayerChanges + p3, a3.existingSegmentCount + 1) - a3.existingRegionCost;\n return e51.g + m2 + c3 + l3 + h2;\n }\n tryFinalAcceptance() {\n const e51 = this.getNeverSuccessfullyRoutedRoutes();\n if (this.stats = { ...this.stats, neverSuccessfullyRoutedRouteCount: e51.length }, this.ACCEPT_BEST_SOLUTION_ON_TIMEOUT \u0026\u0026 this.bestSolvedStateSnapshot \u0026\u0026 this.bestSolvedStateSummary)\n return this.restoreBestSolvedState(), this.stats = { ...this.stats, acceptedBestSolutionOnTimeout: true, maxRegionCost: this.bestSolvedStateSummary.maxRegionCost, totalRegionCost: this.bestSolvedStateSummary.totalRegionCost, bestMaxRegionCost: this.bestSolvedStateSummary.maxRegionCost, bestTotalRegionCost: this.bestSolvedStateSummary.totalRegionCost }, this.solved = true, this.failed = false, void (this.error = null);\n this.ACCEPT_BEST_SOLUTION_ON_TIMEOUT \u0026\u0026 this.tryGreedyFinalRouteAcceptance() || this.logNeverSuccessfullyRoutedRoutes();\n }\n getRouteHeuristic(e51, t2) {\n const n2 = this.problemSetup.portHCostToEndOfRoute;\n if (n2)\n return n2[t2 * this.problem.routeCount + e51];\n if (this.hCostEndRouteId !== e51) {\n this.hCostEndRouteId = e51;\n const t3 = this.getRouteEndPortId(e51);\n this.hCostEndX = this.topology.portX[t3], this.hCostEndY = this.topology.portY[t3];\n }\n if (this.hCostRouteIdByPortId[t2] !== e51) {\n const n3 = this.topology.portX[t2] - this.hCostEndX, o3 = this.topology.portY[t2] - this.hCostEndY;\n this.hCostByPortId[t2] = Math.sqrt(n3 * n3 + o3 * o3) * this.DISTANCE_TO_COST, this.hCostRouteIdByPortId[t2] = e51;\n }\n return this.hCostByPortId[t2];\n }\n computeH(e51) {\n return this.getRouteHeuristic(this.state.currentRouteId, e51);\n }\n visualize() {\n return Uq(this);\n }\n getOutput() {\n return FZ(this);\n }\n};\nvar nJ = class extends tJ {\n computeG(e51, t2) {\n return e51.g;\n }\n};\nvar oJ = (e51, t2) =\u003e {\n const n2 = e51.priorityOwnerCount - t2.priorityOwnerCount;\n if (n2 !== 0)\n return n2;\n const o3 = e51.estimatedTotalDistance - t2.estimatedTotalDistance;\n return o3 !== 0 ? o3 : e51.queueOrder - t2.queueOrder;\n};\nvar iJ = class {\n heap = [];\n push(e51) {\n this.heap.push(e51);\n let t2 = this.heap.length - 1;\n for (;t2 \u003e 0; ) {\n const e52 = Math.floor((t2 - 1) / 2);\n if (oJ(this.heap[e52], this.heap[t2]) \u003c= 0)\n break;\n [this.heap[e52], this.heap[t2]] = [this.heap[t2], this.heap[e52]], t2 = e52;\n }\n }\n pop() {\n const e51 = this.heap[0], t2 = this.heap.pop();\n if (!e51 || !t2)\n return null;\n if (this.heap.length === 0)\n return e51;\n this.heap[0] = t2;\n let n2 = 0;\n for (;; ) {\n const e52 = 2 * n2 + 1, t3 = e52 + 1;\n let o3 = n2;\n if (e52 \u003c this.heap.length \u0026\u0026 oJ(this.heap[e52], this.heap[o3]) \u003c 0 \u0026\u0026 (o3 = e52), t3 \u003c this.heap.length \u0026\u0026 oJ(this.heap[t3], this.heap[o3]) \u003c 0 \u0026\u0026 (o3 = t3), o3 === n2)\n break;\n [this.heap[n2], this.heap[o3]] = [this.heap[o3], this.heap[n2]], n2 = o3;\n }\n return e51;\n }\n};\nvar rJ = (e51, t2, n2) =\u003e {\n if (e51 === t2)\n return true;\n if (e51.size \u003e t2.size + n2.length)\n return false;\n for (const o3 of e51)\n if (!t2.has(o3) \u0026\u0026 !n2.includes(o3))\n return false;\n return true;\n};\nvar sJ = (e51, t2) =\u003e !(e51.distance \u003e t2.distance) \u0026\u0026 ((e52, t3) =\u003e {\n if (e52.size \u003e t3.size)\n return false;\n for (const n2 of e52)\n if (!t3.has(n2))\n return false;\n return true;\n})(e51.owners, t2.owners);\nvar aJ = (e51, t2) =\u003e {\n const n2 = [], o3 = [];\n let i3 = e51;\n for (;i3 !== null; )\n n2.push(i3.state), i3.incomingHop !== null \u0026\u0026 o3.push(i3.incomingHop), i3 = i3.parent;\n return n2.reverse(), o3.reverse(), { found: true, states: n2, hops: o3, owners: new Set(e51.owners), distance: e51.distance, expandedLabelCount: t2 };\n};\nvar cJ = (e51) =\u003e {\n for (;; ) {\n const t2 = e51.pop();\n if (t2 === null)\n return null;\n if (t2.active)\n return t2;\n }\n};\nvar lJ = (e51) =\u003e {\n const t2 = e51.maxExpandedLabels ?? Number.POSITIVE_INFINITY;\n if (t2 !== Number.POSITIVE_INFINITY \u0026\u0026 (!Number.isInteger(t2) || t2 \u003c 0))\n throw new Error(\"maxExpandedLabels must be a non-negative integer\");\n const n2 = e51.minimumOwnerCount ?? 0;\n if (!Number.isInteger(n2) || n2 \u003c 0)\n throw new Error(\"minimumOwnerCount must be a non-negative integer\");\n if (e51.checkReachability) {\n const n3 = ((e52, t3) =\u003e {\n const n4 = [e52.start], o4 = new Set([e52.getStateKey(e52.start)]);\n let i4 = 0, r4 = 0;\n for (let s3 = 0;s3 \u003c n4.length; s3++) {\n const a4 = n4[s3];\n if (e52.isGoal(a4))\n return;\n if (i4 \u003e= t3)\n return;\n i4++;\n for (const t4 of e52.getHops(a4)) {\n if (r4 += t4.distance, t4.distance \u003c 0 || !Number.isFinite(r4))\n return;\n const i5 = e52.getStateKey(t4.state);\n o4.has(i5) || (o4.add(i5), n4.push(t4.state));\n }\n }\n return { found: false, reason: \"no_path\", expandedLabelCount: i4 };\n })(e51, t2);\n if (n3)\n return n3;\n }\n const o3 = new Map, i3 = new iJ;\n let r3 = 0, s2 = 0;\n const a3 = { state: e51.start, stateKey: e51.getStateKey(e51.start), owners: new Set, priorityOwnerCount: n2, distance: 0, estimatedTotalDistance: e51.getRemainingDistance ? e51.getRemainingDistance(e51.start) : 0, parent: null, incomingHop: null, queueOrder: r3++, active: true };\n if (!Number.isFinite(a3.estimatedTotalDistance) || a3.estimatedTotalDistance \u003c 0)\n throw new Error(\"Distinct-owner blocker estimates must be finite and \u003e= 0\");\n for (o3.set(a3.stateKey, [a3]), i3.push(a3);; ) {\n const a4 = cJ(i3);\n if (a4 === null)\n return { found: false, reason: \"no_path\", expandedLabelCount: s2 };\n if (e51.isGoal(a4.state))\n return aJ(a4, s2);\n if (s2 \u003e= t2)\n return { found: false, reason: \"expansion_limit\", expandedLabelCount: s2 };\n s2++;\n for (const t3 of e51.getHops(a4.state)) {\n if (!Number.isFinite(t3.distance) || t3.distance \u003c 0)\n throw new Error(\"Distinct-owner blocker hops require finite distances \u003e= 0\");\n const s3 = a4.distance + t3.distance;\n if (!Number.isFinite(s3))\n throw new Error(\"Distinct-owner blocker path distance overflowed\");\n const c3 = e51.getStateKey(t3.state), l3 = r3++, h2 = o3.get(c3) ?? [], d2 = t3.owners ?? [];\n let u2 = false;\n for (const e52 of h2)\n if (e52.distance \u003c= s3 \u0026\u0026 rJ(e52.owners, a4.owners, d2)) {\n u2 = true;\n break;\n }\n if (u2)\n continue;\n let p3 = a4.owners;\n for (const e52 of d2)\n p3.has(e52) || (p3 === a4.owners \u0026\u0026 (p3 = new Set(a4.owners)), p3.add(e52));\n const m2 = e51.getRemainingDistance ? e51.getRemainingDistance(t3.state) : 0, g2 = s3 + m2;\n if (!Number.isFinite(m2) || m2 \u003c 0 || !Number.isFinite(g2))\n throw new Error(\"Distinct-owner blocker estimates must be finite and \u003e= 0\");\n const f2 = { state: t3.state, stateKey: c3, owners: p3, priorityOwnerCount: Math.max(n2, p3.size), distance: s3, estimatedTotalDistance: g2, parent: a4, incomingHop: t3, queueOrder: l3, active: true }, _2 = [];\n for (const e52 of h2)\n sJ(f2, e52) ? e52.active = false : _2.push(e52);\n _2.push(f2), o3.set(f2.stateKey, _2), i3.push(f2);\n }\n }\n};\nvar hJ = class extends tJ {\n constructor(e51, t2, n2) {\n super(e51, t2, n2), this.ADD_SEGMENT_DISTANCE_TO_G = true;\n }\n _setup() {\n super._setup(), this.state.candidateQueue = new ZZ(this.topology.regionCount, { hopCapacity: this.candidateHopCapacity, hopSlotStride: this.candidateHopSlotStride, firstRegionByPortId: this.candidateFirstRegionByPortId, secondRegionByPortId: this.candidateSecondRegionByPortId, incidentPortRegion: this.topology.incidentPortRegion });\n }\n onPathFound(e51) {\n const t2 = this.state.goalPortId;\n if (e51.portId === t2)\n return void super.onPathFound(e51);\n const n2 = this.computeG(e51, t2);\n if (!Number.isFinite(n2))\n return;\n const o3 = this.getHopId(t2, e51.nextRegionId);\n n2 \u003e= this.getCandidateBestCost(o3) || (this.setCandidateBestCost(o3, n2), this.state.candidateQueue.queue({ hopId: o3, prevRegionId: e51.nextRegionId, nextRegionId: e51.nextRegionId, portId: t2, g: n2, h: 0, f: n2, prevCandidate: e51 }));\n }\n};\nvar dJ = new Set;\nvar uJ = class extends hJ {\n partialRipRoutePlans = new Map;\n outsideInRouteSearch;\n oneSidedFallbackRouteId;\n partialRipWindowDistance;\n partialRipCount = 0;\n partiallyRippedRouteCount = 0;\n partiallyRippedSegmentCount = 0;\n retainedPartialRipSegmentCount = 0;\n outsideInRouteCount = 0;\n outsideInCompletedRouteCount = 0;\n outsideInFallbackRouteCount = 0;\n outsideInForwardExpansionCount = 0;\n outsideInReverseExpansionCount = 0;\n outsideInDistancePruneCount = 0;\n completedRoundSummaries = [];\n firstCompletedRoundSummary;\n partialRipQualityBaselineSummary;\n bestSolvedRoundSummary;\n partialRipTargetReached = false;\n useComplexityAwareSelection = false;\n constructor(e51, t2, n2) {\n super(e51, t2, n2), n2?.PARTIAL_RIP_ENABLED === undefined \u0026\u0026 (this.PARTIAL_RIP_ENABLED = true), n2?.OUTSIDE_IN_ROUTING === undefined \u0026\u0026 (this.OUTSIDE_IN_ROUTING = true), this.PARTIAL_RIP_ENABLED \u0026\u0026 n2?.PARTIAL_RIP_MAX_ATTEMPTS === undefined \u0026\u0026 (this.PARTIAL_RIP_MAX_ATTEMPTS = 10), (t2.routeCount \u003c Math.max(0, this.PARTIAL_RIP_MIN_ROUTE_COUNT) || t2.routeCount \u003e Math.max(0, this.PARTIAL_RIP_MAX_ROUTE_COUNT)) \u0026\u0026 (this.PARTIAL_RIP_ENABLED = false, this.OUTSIDE_IN_ROUTING = false), this.useComplexityAwareSelection = t2.routeCount \u003e= Math.max(0, this.PARTIAL_RIP_COMPLEXITY_SELECTION_MIN_ROUTE_COUNT);\n }\n getRouteStartPortId(e51) {\n return this.PARTIAL_RIP_ENABLED ? this.partialRipRoutePlans.get(e51)?.activeStartPortId ?? super.getRouteStartPortId(e51) : super.getRouteStartPortId(e51);\n }\n getRouteEndPortId(e51) {\n return this.PARTIAL_RIP_ENABLED ? this.partialRipRoutePlans.get(e51)?.activeEndPortId ?? super.getRouteEndPortId(e51) : super.getRouteEndPortId(e51);\n }\n getStartingNextRegionId(e51, t2) {\n if (!this.PARTIAL_RIP_ENABLED)\n return super.getStartingNextRegionId(e51, t2);\n const n2 = this.partialRipRoutePlans.get(e51);\n return n2 \u0026\u0026 n2.activeStartPortId === t2 ? n2.forcedStartRegionId : super.getStartingNextRegionId(e51, t2);\n }\n getEndingNextRegionId(e51, t2) {\n const n2 = this.partialRipRoutePlans.get(e51);\n return n2 \u0026\u0026 n2.activeEndPortId === t2 ? n2.forcedEndRegionId : super.getStartingNextRegionId(e51, t2);\n }\n computeH(e51) {\n if (!this.PARTIAL_RIP_ENABLED)\n return super.computeH(e51);\n const t2 = this.state.currentRouteId;\n if (t2 === undefined || !this.partialRipRoutePlans.has(t2))\n return super.computeH(e51);\n const n2 = this.getRouteEndPortId(t2), o3 = this.topology.portX[e51] - this.topology.portX[n2], i3 = this.topology.portY[e51] - this.topology.portY[n2];\n return Math.sqrt(o3 * o3 + i3 * i3) * this.DISTANCE_TO_COST;\n }\n onPathFound(e51) {\n if (!this.PARTIAL_RIP_ENABLED \u0026\u0026 !this.OUTSIDE_IN_ROUTING)\n return void super.onPathFound(e51);\n const t2 = this.state.currentRouteId, n2 = t2 !== undefined \u0026\u0026 this.outsideInRouteSearch?.routeId === t2;\n super.onPathFound(e51), t2 !== undefined \u0026\u0026 this.state.currentRouteId === undefined \u0026\u0026 (this.partialRipRoutePlans.delete(t2), n2 \u0026\u0026 (this.outsideInCompletedRouteCount += 1), this.oneSidedFallbackRouteId === t2 \u0026\u0026 (this.oneSidedFallbackRouteId = undefined)), this.outsideInRouteSearch = undefined, this.publishOutsideInStats();\n }\n resetRoutingStateForRerip() {\n this.PARTIAL_RIP_ENABLED || this.OUTSIDE_IN_ROUTING ? (this.partialRipRoutePlans.clear(), this.outsideInRouteSearch = undefined, this.oneSidedFallbackRouteId = undefined, super.resetRoutingStateForRerip()) : super.resetRoutingStateForRerip();\n }\n clearPartialRipPlans(e51) {\n for (const t2 of e51)\n this.partialRipRoutePlans.delete(t2);\n }\n getRouteIdsPreferredForPreservation() {\n return dJ;\n }\n getCommittedRouteSegments(e51) {\n const t2 = [];\n for (let n3 = 0;n3 \u003c this.state.regionSegments.length; n3++)\n for (const [o4, i4, r4] of this.state.regionSegments[n3] ?? [])\n o4 === e51 \u0026\u0026 t2.push({ segmentIndex: t2.length, regionId: n3, fromPortId: i4, toPortId: r4 });\n if (t2.length === 0)\n return;\n const n2 = new Map;\n for (const e52 of t2)\n for (const t3 of [e52.fromPortId, e52.toPortId]) {\n const o4 = n2.get(t3) ?? [];\n o4.push(e52.segmentIndex), n2.set(t3, o4);\n }\n const o3 = this.problem.routeEndPort[e51], i3 = [], r3 = new Set, s2 = new Set([this.problem.routeStartPort[e51]]), a3 = (e52) =\u003e {\n if (e52 === o3)\n return true;\n for (const o4 of n2.get(e52) ?? []) {\n if (r3.has(o4))\n continue;\n const n3 = t2[o4], c3 = n3.fromPortId === e52 ? n3.toPortId : n3.fromPortId;\n if (!s2.has(c3)) {\n if (r3.add(o4), s2.add(c3), i3.push({ regionId: n3.regionId, fromPortId: e52, toPortId: c3 }), a3(c3))\n return true;\n i3.pop(), s2.delete(c3), r3.delete(o4);\n }\n }\n return false;\n };\n return a3(this.problem.routeStartPort[e51]) \u0026\u0026 r3.size === t2.length ? i3 : undefined;\n }\n getSegmentDistance(e51) {\n const t2 = this.topology.portX[e51.fromPortId] - this.topology.portX[e51.toPortId], n2 = this.topology.portY[e51.fromPortId] - this.topology.portY[e51.toPortId];\n return Math.sqrt(t2 * t2 + n2 * n2);\n }\n getPartialRipWindow(e51, t2, n2) {\n let o3, i3 = Number.NEGATIVE_INFINITY;\n for (let r4 = 0;r4 \u003c e51.length; r4++) {\n const s3 = e51[r4];\n if (!t2.has(s3.regionId))\n continue;\n const a4 = n2[s3.regionId] ?? 0;\n a4 \u003e i3 \u0026\u0026 (i3 = a4, o3 = r4);\n }\n if (o3 === undefined)\n return;\n const r3 = Math.max(0, this.partialRipWindowDistance ?? this.PARTIAL_RIP_MAX_DISTANCE);\n let s2 = o3, a3 = o3, c3 = this.getSegmentDistance(e51[o3]) / 2, l3 = c3;\n for (;s2 \u003e 0; ) {\n const t3 = this.getSegmentDistance(e51[s2 - 1]);\n if (c3 + t3 \u003e r3)\n break;\n s2 -= 1, c3 += t3;\n }\n for (;a3 + 1 \u003c e51.length; ) {\n const t3 = this.getSegmentDistance(e51[a3 + 1]);\n if (l3 + t3 \u003e r3)\n break;\n a3 += 1, l3 += t3;\n }\n return { startIndex: s2, endIndex: a3 };\n }\n appendRetainedSegment(e51, t2, n2) {\n e51[n2.regionId].push([t2, n2.fromPortId, n2.toPortId]);\n }\n preparePartialRip(e51, t2) {\n if (!this.PARTIAL_RIP_ENABLED || e51.length === 0)\n return false;\n const n2 = new Set(e51);\n if (this.partialRipWindowDistance === undefined) {\n let n3 = 0;\n for (const o5 of e51)\n n3 = Math.max(n3, t2[o5] ?? 0);\n const o4 = Math.max(0, this.PARTIAL_RIP_MAX_DISTANCE), i4 = Math.max(o4, this.PARTIAL_RIP_QUALITY_MAX_DISTANCE ?? 2 * o4);\n this.partialRipWindowDistance = n3 \u003c= 1.5 * this.RIP_THRESHOLD_END ? i4 : o4;\n }\n const o3 = new Set;\n for (const t3 of e51)\n for (const [e52] of this.state.regionSegments[t3] ?? [])\n o3.add(e52);\n if (o3.size === 0)\n return false;\n const i3 = this.getRouteIdsPreferredForPreservation(), r3 = [...o3].some((e52) =\u003e !i3.has(e52)), s2 = Array.from({ length: this.topology.regionCount }, () =\u003e []), a3 = new Map;\n let c3 = 0, l3 = 0;\n for (let e52 = 0;e52 \u003c this.problem.routeCount; e52++) {\n const h2 = this.getCommittedRouteSegments(e52);\n if (!h2)\n return false;\n if (!o3.has(e52) || r3 \u0026\u0026 i3.has(e52)) {\n for (const t3 of h2)\n this.appendRetainedSegment(s2, e52, t3), l3 += 1;\n continue;\n }\n const d2 = this.getPartialRipWindow(h2, n2, t2);\n if (!d2)\n return false;\n for (let t3 = 0;t3 \u003c h2.length; t3++) {\n const n3 = h2[t3];\n t3 \u003e= d2.startIndex \u0026\u0026 t3 \u003c= d2.endIndex ? c3 += 1 : (this.appendRetainedSegment(s2, e52, n3), l3 += 1);\n }\n const u2 = h2[d2.startIndex], p3 = h2[d2.endIndex];\n a3.set(e52, { routeId: e52, activeStartPortId: u2.fromPortId, activeEndPortId: p3.toPortId, forcedStartRegionId: u2.regionId, forcedEndRegionId: p3.regionId, rippedSegmentCount: d2.endIndex - d2.startIndex + 1, retainedSegmentCount: h2.length - (d2.endIndex - d2.startIndex + 1) });\n }\n return a3.size !== 0 \u0026\u0026 c3 !== 0 \u0026\u0026 (this.partialRipRoutePlans = a3, this.rebuildRetainedRoutingState(s2, [...a3.keys()]), this.partialRipCount += 1, this.partiallyRippedRouteCount += a3.size, this.partiallyRippedSegmentCount += c3, this.retainedPartialRipSegmentCount += l3, this.publishPartialRipStats(), true);\n }\n rebuildRetainedRoutingState(e51, t2) {\n this.state.portAssignment.fill(-1), this.state.regionSegments = Array.from({ length: this.topology.regionCount }, () =\u003e []), this.state.regionIntersectionCaches = Array.from({ length: this.topology.regionCount }, () =\u003e Zq()), this.state.currentRouteId = undefined, this.state.currentRouteNetId = undefined, this.state.unroutedRoutes = t2, this.state.candidateQueue.clear(), this.resetCandidateBestCosts(), this.state.goalPortId = -1, this.outsideInRouteSearch = undefined, this.oneSidedFallbackRouteId = undefined;\n for (let t3 = 0;t3 \u003c e51.length; t3++)\n for (const [n2, o3, i3] of e51[t3] ?? []) {\n const e52 = this.problem.routeNet[n2];\n this.state.currentRouteNetId = e52;\n for (const t4 of [o3, i3]) {\n const n3 = this.state.portAssignment[t4];\n if (n3 !== -1 \u0026\u0026 n3 !== e52)\n throw new Error(`OutsideInPartialRipTinyHyperGraphSolver: retained port ${t4} belongs to multiple nets`);\n this.state.portAssignment[t4] = e52;\n }\n this.state.regionSegments[t3].push([n2, o3, i3]), this.appendSegmentToRegionCache(t3, o3, i3);\n }\n this.state.currentRouteNetId = undefined;\n }\n publishPartialRipStats() {\n this.stats = { ...this.stats, partialRipCount: this.partialRipCount, partiallyRippedRouteCount: this.partiallyRippedRouteCount, partiallyRippedSegmentCount: this.partiallyRippedSegmentCount, retainedPartialRipSegmentCount: this.retainedPartialRipSegmentCount, partialRipMaxDistance: this.partialRipWindowDistance ?? this.PARTIAL_RIP_MAX_DISTANCE, partialRipBaseMaxDistance: this.PARTIAL_RIP_MAX_DISTANCE, partialRipQualityMaxDistance: this.PARTIAL_RIP_QUALITY_MAX_DISTANCE ?? 2 * this.PARTIAL_RIP_MAX_DISTANCE, partialRipMaxAttempts: this.PARTIAL_RIP_MAX_ATTEMPTS };\n }\n publishOutsideInStats() {\n this.stats = { ...this.stats, outsideInRouteCount: this.outsideInRouteCount, outsideInCompletedRouteCount: this.outsideInCompletedRouteCount, outsideInFallbackRouteCount: this.outsideInFallbackRouteCount, outsideInForwardExpansionCount: this.outsideInForwardExpansionCount, outsideInReverseExpansionCount: this.outsideInReverseExpansionCount, outsideInDistancePruneCount: this.outsideInDistancePruneCount, outsideInMaxDistance: this.OUTSIDE_IN_MAX_DISTANCE };\n }\n createOutsideInFrontier(e51, t2, n2) {\n const o3 = new UZ([], (e52, t3) =\u003e e52.f === t3.f ? e52.g - t3.g : e52.f - t3.f), i3 = this.topology.portX[e51] - this.topology.portX[n2], r3 = this.topology.portY[e51] - this.topology.portY[n2], s2 = Math.sqrt(i3 * i3 + r3 * r3) * this.DISTANCE_TO_COST, a3 = { portId: e51, nextRegionId: t2, f: s2, g: 0, h: s2, travelDistance: 0 };\n return o3.queue(a3), { queue: o3, bestCostByHopId: new Map([[this.getHopId(e51, t2), 0]]), settledByPortId: new Map, settledByRegionId: new Map, targetPortId: n2 };\n }\n startOutsideInRouteSearch(e51) {\n const t2 = this.getRouteStartPortId(e51), n2 = this.getRouteEndPortId(e51), o3 = this.getStartingNextRegionId(e51, t2), i3 = this.getEndingNextRegionId(e51, n2);\n return o3 !== undefined \u0026\u0026 i3 !== undefined \u0026\u0026 (this.state.goalPortId = n2, this.state.candidateQueue.clear(), this.resetCandidateBestCosts(), this.outsideInRouteSearch = { routeId: e51, forward: this.createOutsideInFrontier(t2, o3, n2), reverse: this.createOutsideInFrontier(n2, i3, t2), expandForwardNext: true, distanceLimitHit: false, bestJoinedCost: Number.POSITIVE_INFINITY }, this.outsideInRouteCount += 1, this.publishOutsideInStats(), true);\n }\n dequeueFreshCandidate(e51) {\n for (;e51.queue.length \u003e 0; ) {\n const t2 = e51.queue.dequeue(), n2 = this.getHopId(t2.portId, t2.nextRegionId);\n if (t2.g \u003c= (e51.bestCostByHopId.get(n2) ?? 1 / 0))\n return t2;\n }\n }\n recordSettledCandidate(e51, t2) {\n const n2 = e51.settledByPortId.get(t2.portId);\n (!n2 || t2.g \u003c n2.g) \u0026\u0026 e51.settledByPortId.set(t2.portId, t2);\n const o3 = e51.settledByRegionId.get(t2.nextRegionId) ?? [];\n o3.push(t2), o3.sort((e52, t3) =\u003e e52.g - t3.g), o3.length \u003e 16 \u0026\u0026 (o3.length = 16), e51.settledByRegionId.set(t2.nextRegionId, o3);\n }\n getCandidatePath(e51) {\n const t2 = [];\n let n2 = e51;\n for (;n2; )\n t2.push(n2), n2 = n2.prevCandidate;\n return t2.reverse(), t2;\n }\n buildJoinedCandidate(e51, t2) {\n const n2 = this.getCandidatePath(e51), o3 = this.getCandidatePath(t2), i3 = n2.map(({ portId: e52 }) =\u003e e52), r3 = n2.slice(0, -1).map(({ nextRegionId: e52 }) =\u003e e52);\n if (e51.portId !== t2.portId) {\n if (e51.nextRegionId !== t2.nextRegionId)\n return;\n const n3 = this.topology.portX[e51.portId] - this.topology.portX[t2.portId], o4 = this.topology.portY[e51.portId] - this.topology.portY[t2.portId], s3 = Math.sqrt(n3 * n3 + o4 * o4);\n if (e51.travelDistance + t2.travelDistance + s3 \u003e 2 * this.OUTSIDE_IN_MAX_DISTANCE)\n return;\n const a4 = this.computeG(e51, t2.portId);\n if (!Number.isFinite(a4))\n return;\n r3.push(e51.nextRegionId), i3.push(t2.portId);\n }\n for (let e52 = o3.length - 2;e52 \u003e= 0; e52--) {\n const t3 = o3[e52];\n r3.push(t3.nextRegionId), i3.push(t3.portId);\n }\n if (new Set(i3).size !== i3.length || r3.length + 1 !== i3.length)\n return;\n let s2 = { portId: i3[0], nextRegionId: r3[0], f: 0, g: 0, h: 0 };\n for (let e52 = 1;e52 \u003c i3.length; e52++)\n s2 = { portId: i3[e52], prevRegionId: r3[e52 - 1], nextRegionId: r3[e52] ?? r3[e52 - 1], prevCandidate: s2, f: 0, g: 0, h: 0 };\n const a3 = e51.portId === t2.portId ? 0 : this.computeG(e51, t2.portId) - e51.g;\n return { candidate: s2, cost: e51.g + t2.g + a3 };\n }\n considerOutsideInJoins(e51, t2) {\n const n2 = this.outsideInRouteSearch, o3 = t2 ? n2.reverse : n2.forward, i3 = (e52) =\u003e {\n !e52 || e52.cost \u003e= n2.bestJoinedCost || (n2.bestJoinedCandidate = e52.candidate, n2.bestJoinedCost = e52.cost, n2.remainingPostMeetingExpansions = 24);\n }, r3 = o3.settledByPortId.get(e51.portId);\n r3 \u0026\u0026 i3(t2 ? this.buildJoinedCandidate(e51, r3) : this.buildJoinedCandidate(r3, e51));\n for (const n3 of o3.settledByRegionId.get(e51.nextRegionId) ?? [])\n i3(t2 ? this.buildJoinedCandidate(e51, n3) : this.buildJoinedCandidate(n3, e51));\n }\n commitBestOutsideInJoin() {\n const e51 = this.outsideInRouteSearch?.bestJoinedCandidate;\n return !!e51 \u0026\u0026 (this.onPathFound(e51), true);\n }\n expandOutsideInFrontier(e51) {\n const t2 = this.outsideInRouteSearch, n2 = e51 ? t2.forward : t2.reverse, o3 = this.dequeueFreshCandidate(n2);\n if (!o3)\n return false;\n if (e51 ? this.outsideInForwardExpansionCount += 1 : this.outsideInReverseExpansionCount += 1, this.isRegionReservedForDifferentNet(o3.nextRegionId))\n return true;\n this.recordSettledCandidate(n2, o3), this.considerOutsideInJoins(o3, e51);\n for (const e52 of this.topology.regionIncidentPorts[o3.nextRegionId] ?? []) {\n if (e52 === o3.portId)\n continue;\n if (this.isPortReservedForDifferentNet(e52))\n continue;\n const i3 = this.state.portAssignment[e52];\n if (i3 !== -1 \u0026\u0026 i3 !== this.state.currentRouteNetId)\n continue;\n if (e52 !== n2.targetPortId \u0026\u0026 this.problem.portSectionMask[e52] === 0)\n continue;\n const r3 = this.topology.portX[o3.portId] - this.topology.portX[e52], s2 = this.topology.portY[o3.portId] - this.topology.portY[e52], a3 = Math.sqrt(r3 * r3 + s2 * s2), c3 = o3.travelDistance + a3;\n if (c3 \u003e this.OUTSIDE_IN_MAX_DISTANCE) {\n t2.distanceLimitHit = true, this.outsideInDistancePruneCount += 1;\n continue;\n }\n const l3 = this.topology.incidentPortRegion[e52]?.[0] === o3.nextRegionId ? this.topology.incidentPortRegion[e52]?.[1] : this.topology.incidentPortRegion[e52]?.[0];\n if (l3 === undefined || this.isRegionReservedForDifferentNet(l3))\n continue;\n const h2 = this.getHopId(e52, l3), d2 = n2.bestCostByHopId.get(h2) ?? 1 / 0;\n if (o3.g \u003e= d2)\n continue;\n const u2 = this.computeG(o3, e52, d2, a3);\n if (!Number.isFinite(u2) || u2 \u003e= d2)\n continue;\n n2.bestCostByHopId.set(h2, u2);\n const p3 = this.topology.portX[e52] - this.topology.portX[n2.targetPortId], m2 = this.topology.portY[e52] - this.topology.portY[n2.targetPortId], g2 = Math.sqrt(p3 * p3 + m2 * m2) * this.DISTANCE_TO_COST;\n n2.queue.queue({ portId: e52, prevRegionId: o3.nextRegionId, nextRegionId: l3, prevCandidate: o3, f: u2 + g2, g: u2, h: g2, travelDistance: c3 });\n }\n return true;\n }\n fallBackToOneSidedRouteSearch() {\n const e51 = this.state.currentRouteId;\n e51 !== undefined \u0026\u0026 (this.outsideInRouteSearch = undefined, this.outsideInFallbackRouteCount += 1, this.oneSidedFallbackRouteId = e51, this.state.currentRouteId = undefined, this.state.currentRouteNetId = undefined, this.state.goalPortId = -1, this.state.candidateQueue.clear(), this.resetCandidateBestCosts(), this.state.unroutedRoutes.unshift(e51), this.publishOutsideInStats());\n }\n _step() {\n if (!this.OUTSIDE_IN_ROUTING)\n return void super._step();\n const e51 = this.state.currentRouteId ?? this.state.unroutedRoutes[0];\n if (e51 !== undefined \u0026\u0026 !this.partialRipRoutePlans.has(e51))\n return void super._step();\n if (this.oneSidedFallbackRouteId !== undefined)\n return void super._step();\n if (this.state.currentRouteId === undefined) {\n if (this.state.unroutedRoutes.length === 0)\n return void this.onAllRoutesRouted();\n const e52 = this.state.unroutedRoutes.shift();\n if (this.state.currentRouteId = e52, this.state.currentRouteNetId = this.problem.routeNet[e52], this.routeAttemptCountByRouteId[e52] += 1, !this.startOutsideInRouteSearch(e52))\n return this.failed = true, void (this.error = `Route ${e52} has an endpoint without an incident region`);\n }\n const t2 = this.outsideInRouteSearch;\n if (!t2)\n return;\n let n2 = this.expandOutsideInFrontier(t2.expandForwardNext);\n if (this.state.currentRouteId !== undefined \u0026\u0026 (n2 || (n2 = this.expandOutsideInFrontier(!t2.expandForwardNext), this.state.currentRouteId !== undefined)))\n if (t2.expandForwardNext = !t2.expandForwardNext, t2.bestJoinedCandidate \u0026\u0026 (t2.remainingPostMeetingExpansions = (t2.remainingPostMeetingExpansions ?? 1) - 1, (t2.remainingPostMeetingExpansions ?? 0) \u003c= 0))\n this.commitBestOutsideInJoin();\n else {\n if (!n2 \u0026\u0026 t2.forward.queue.length === 0 \u0026\u0026 t2.reverse.queue.length === 0) {\n if (this.commitBestOutsideInJoin())\n return;\n this.outsideInRouteSearch = undefined, t2.distanceLimitHit ? this.fallBackToOneSidedRouteSearch() : this.onOutOfCandidates();\n }\n this.publishOutsideInStats();\n }\n }\n shouldReplaceBestSolvedState(e51) {\n const t2 = this.bestSolvedRoundSummary;\n if (!t2)\n return true;\n if (!this.useComplexityAwareSelection)\n return this.compareRegionCostSummaries(e51, t2) \u003c 0;\n const n2 = this.partialRipQualityBaselineSummary;\n if (!n2)\n return this.compareRegionCostSummaries(e51, t2) \u003c 0;\n const o3 = this.firstCompletedRoundSummary ?? n2, i3 = o3.maxRegionCost * (1 + Math.max(0, this.PARTIAL_RIP_MAX_REGION_COST_GROWTH_RATIO)), r3 = o3.totalRegionCost * (1 + Math.max(0, this.PARTIAL_RIP_MAX_TOTAL_COST_GROWTH_RATIO)), s2 = e51.maxRegionCost \u003c= i3 \u0026\u0026 e51.totalRegionCost \u003c= r3;\n return s2 !== (t2.maxRegionCost \u003c= i3 \u0026\u0026 t2.totalRegionCost \u003c= r3) ? s2 : s2 \u0026\u0026 e51.segmentCount !== t2.segmentCount ? e51.segmentCount \u003c t2.segmentCount : this.compareRegionCostSummaries(e51, t2) \u003c 0;\n }\n onAllRoutesRouted() {\n if (!this.PARTIAL_RIP_ENABLED)\n return void super.onAllRoutesRouted();\n const { state: e51, topology: t2 } = this, n2 = Math.min(this.RIP_THRESHOLD_RAMP_ATTEMPTS, this.PARTIAL_RIP_MAX_ATTEMPTS), o3 = Math.max(0, this.RIP_THRESHOLD_RAMP_ATTEMPTS), i3 = o3 \u003c= 0 ? 1 : Math.min(1, e51.ripCount / o3), r3 = this.RIP_THRESHOLD_START + (this.RIP_THRESHOLD_END - this.RIP_THRESHOLD_START) * i3, s2 = new Float64Array(t2.regionCount), a3 = [];\n let c3 = 0, l3 = 0, h2 = 0, d2 = 0, u2 = 0;\n for (let n3 = 0;n3 \u003c t2.regionCount; n3++) {\n const t3 = e51.regionIntersectionCaches[n3]?.existingRegionCost ?? 0;\n s2[n3] = t3, c3 = Math.max(c3, t3), l3 += t3;\n const o4 = e51.regionSegments[n3]?.length ?? 0;\n h2 += o4, d2 = Math.max(d2, o4), u2 += o4 * o4, t3 \u003e r3 \u0026\u0026 a3.push(n3);\n }\n const p3 = { maxRegionCost: c3, totalRegionCost: l3 }, m2 = { ...p3, ripCount: e51.ripCount, segmentCount: h2, maxRegionSegmentCount: d2, squaredRegionSegmentCount: u2 };\n this.completedRoundSummaries.push(m2), this.firstCompletedRoundSummary ??= m2, this.partialRipQualityBaselineSummary === undefined \u0026\u0026 e51.ripCount \u003e= Math.max(0, this.PARTIAL_RIP_WARMUP_FULL_RIP_ATTEMPTS) \u0026\u0026 (this.partialRipQualityBaselineSummary = m2);\n this.shouldReplaceBestSolvedState(m2) \u0026\u0026 (this.replaceBestSolvedState(p3), this.bestSolvedRoundSummary = m2);\n const g2 = this.firstCompletedRoundSummary, f2 = this.partialRipQualityBaselineSummary ?? g2, _2 = Math.max(0, this.PARTIAL_RIP_TARGET_MAX_COST_IMPROVEMENT_RATIO), y2 = Math.max(0, this.PARTIAL_RIP_MAX_TOTAL_COST_GROWTH_RATIO), b2 = f2.maxRegionCost * (1 - _2), x2 = f2.totalRegionCost * (1 + y2), v2 = this.useComplexityAwareSelection \u0026\u0026 e51.ripCount \u003e f2.ripCount \u0026\u0026 _2 \u003e 0 \u0026\u0026 c3 \u003c= b2 \u0026\u0026 l3 \u003c= x2 \u0026\u0026 h2 \u003c= f2.segmentCount;\n if (v2 \u0026\u0026 (this.partialRipTargetReached = true), this.stats = { ...this.stats, currentRipThreshold: r3, hotRegionCount: a3.length, maxRegionCost: c3, totalRegionCost: l3, bestMaxRegionCost: this.bestSolvedStateSummary?.maxRegionCost, bestTotalRegionCost: this.bestSolvedStateSummary?.totalRegionCost, ripCount: e51.ripCount, completedRoundSummaries: this.completedRoundSummaries.map((e52) =\u003e ({ ...e52 })), firstMaxRegionCost: g2.maxRegionCost, firstTotalRegionCost: g2.totalRegionCost, firstSegmentCount: g2.segmentCount, firstMaxRegionSegmentCount: g2.maxRegionSegmentCount, firstSquaredRegionSegmentCount: g2.squaredRegionSegmentCount, partialRipQualityBaselineRipCount: f2.ripCount, partialRipQualityBaselineMaxRegionCost: f2.maxRegionCost, partialRipQualityBaselineTotalRegionCost: f2.totalRegionCost, partialRipQualityBaselineSegmentCount: f2.segmentCount, partialRipQualityBaselineMaxRegionSegmentCount: f2.maxRegionSegmentCount, partialRipQualityBaselineSquaredRegionSegmentCount: f2.squaredRegionSegmentCount, bestSolvedSegmentCount: this.bestSolvedRoundSummary?.segmentCount, bestSolvedMaxRegionSegmentCount: this.bestSolvedRoundSummary?.maxRegionSegmentCount, bestSolvedSquaredRegionSegmentCount: this.bestSolvedRoundSummary?.squaredRegionSegmentCount, partialRipTargetMaxRegionCost: b2, partialRipMaxTargetTotalRegionCost: x2, partialRipComplexityAwareSelection: this.useComplexityAwareSelection, partialRipComplexitySelectionMinRouteCount: this.PARTIAL_RIP_COMPLEXITY_SELECTION_MIN_ROUTE_COUNT, partialRipMaxRegionCostGrowthRatio: this.PARTIAL_RIP_MAX_REGION_COST_GROWTH_RATIO, partialRipTargetReached: this.partialRipTargetReached }, this.publishPartialRipStats(), a3.length === 0 || v2 || e51.ripCount \u003e= n2)\n return this.restoreBestSolvedState(), void (this.solved = true);\n for (let n3 = 0;n3 \u003c t2.regionCount; n3++)\n e51.regionCongestionCost[n3] += s2[n3] * this.RIP_CONGESTION_REGION_COST_FACTOR;\n const I2 = e51.ripCount \u003c Math.max(0, this.PARTIAL_RIP_WARMUP_FULL_RIP_ATTEMPTS);\n e51.ripCount += 1;\n const S2 = !I2 \u0026\u0026 this.preparePartialRip(a3, s2);\n S2 || this.resetRoutingStateForRerip();\n const C = I2 ? \"warmup_full\" : S2 ? \"partial\" : \"full_fallback\";\n this.stats = { ...this.stats, ripCount: e51.ripCount, maxRegionCostBeforeRip: c3, reripRegionCount: a3.length, reripMode: C, partialRipWarmupFullRipAttempts: this.PARTIAL_RIP_WARMUP_FULL_RIP_ATTEMPTS }, this.logRipEvent(\"hot_regions\", c3, { hotRegionCount: a3.length, currentRipThreshold: r3, reripMode: C, partialRouteCount: S2 ? this.partialRipRoutePlans.size : 0 });\n }\n};\nfunction pJ(e51, t2) {\n if (t2.totalHopDistance += e51.distance, e51.distance \u003c 0 || !Number.isFinite(t2.totalHopDistance))\n return false;\n const n2 = t2.search.solver.getHopId(e51.state.portId, e51.state.nextRegionId);\n return t2.ownerFreePhase ? (e51.owners.length \u003e 0 ? t2.ownerFreeByHopId.has(n2) || (t2.ownerFreeByHopId.set(n2, false), t2.ownedQueue.push(e51.state)) : t2.ownerFreeByHopId.get(n2) !== true \u0026\u0026 (t2.ownerFreeByHopId.set(n2, true), t2.ownerFreeQueue.push(e51.state)), true) : (t2.ownerFreeByHopId.has(n2) || (t2.ownerFreeByHopId.set(n2, false), t2.ownedQueue.push(e51.state)), true);\n}\nfunction mJ(e51, t2) {\n const { solver: n2 } = t2.search, o3 = n2.isKnownSingleLayerRegion(e51.nextRegionId);\n if (!o3) {\n const n3 = t2.expansionsByRegion.get(e51.nextRegionId);\n if (n3 === 2)\n return true;\n t2.expansionsByRegion.set(e51.nextRegionId, n3 === undefined ? 1 : 2);\n }\n if (n2.isRegionReservedForDifferentNet(e51.nextRegionId))\n return true;\n if (o3) {\n for (const n3 of t2.search.getHops(e51))\n if (!pJ(n3, t2))\n return false;\n return true;\n }\n const i3 = t2.search.getHopTemplates(e51), r3 = i3[0];\n if (!r3)\n return true;\n const s2 = { ...r3 };\n for (const o4 of i3)\n if (o4.state.portId !== e51.portId \u0026\u0026 (s2.state = o4.state, s2.owners = o4.owners, s2.data = o4.data, s2.distance = Math.hypot(n2.topology.portX[e51.portId] - n2.topology.portX[o4.state.portId], n2.topology.portY[e51.portId] - n2.topology.portY[o4.state.portId]), !pJ(s2, t2)))\n return false;\n return true;\n}\nvar gJ = class extends uJ {\n costAwareFinalReripBudget = 8;\n failedOwnerPairCounts = new Map;\n selectiveReripStats = { selectiveRipCount: 0, selectivelyRippedRouteCount: 0, globalReripCount: 0, alternateBlockerSearchCount: 0, alternateOwnerCount: 0, failedOwnerPairCount: 0, maxFailedOwnerPairCount: 0, failedOwnerPairs: [], lastDirectOwnerRouteIds: [], lastRepeatedOwnerRouteIds: [], lastAlternateOwnerRouteIds: [], lastRippedRouteIds: [], lastRelaxedSearchExpandedLabelCount: 0, lastAlternateSearchExpandedLabelCount: 0 };\n selectiveReripCongestionUpdateCount = 0;\n constructor(e51, t2, n2) {\n super(e51, t2, n2);\n }\n getSelectiveReripStats() {\n return { ...this.selectiveReripStats, failedOwnerPairs: this.selectiveReripStats.failedOwnerPairs.map((e51) =\u003e ({ ...e51 })), lastDirectOwnerRouteIds: [...this.selectiveReripStats.lastDirectOwnerRouteIds], lastRepeatedOwnerRouteIds: [...this.selectiveReripStats.lastRepeatedOwnerRouteIds], lastAlternateOwnerRouteIds: [...this.selectiveReripStats.lastAlternateOwnerRouteIds], lastRippedRouteIds: [...this.selectiveReripStats.lastRippedRouteIds] };\n }\n createGreedyFinalRouteSolver(e51, t2) {\n if (t2 \u003e= 0)\n return super.createGreedyFinalRouteSolver(e51, t2);\n const n2 = new fJ(this.topology, this.problem, { ...e51, MAX_ITERATIONS: Math.max(e51.MAX_ITERATIONS ?? 50000, 2 * this.MAX_ITERATIONS) });\n return n2.remainingReripBudget = this.costAwareFinalReripBudget - this.state.ripCount, n2;\n }\n onOutOfCandidates() {\n const e51 = this.state.currentRouteId;\n if (e51 === undefined)\n throw new Error(\"SelectiveReripTinyHyperGraphSolver: candidate search exhausted without a current route\");\n const t2 = this.findRelaxedBlockerPathPreferringPreservedRoutes();\n if (!t2.found || t2.owners.size === 0)\n return this.selectiveReripStats.globalReripCount += 1, this.selectiveReripStats.globalReripReason = t2.found ? \"no_blocker_path\" : t2.reason, this.selectiveReripStats.lastFailedRouteId = e51, this.selectiveReripStats.lastDirectOwnerRouteIds = [], this.selectiveReripStats.lastRepeatedOwnerRouteIds = [], this.selectiveReripStats.lastAlternateOwnerRouteIds = [], this.selectiveReripStats.lastRippedRouteIds = [], this.selectiveReripStats.lastRelaxedSearchExpandedLabelCount = t2.expandedLabelCount, this.selectiveReripStats.lastAlternateSearchExpandedLabelCount = 0, super.onOutOfCandidates(), void this.publishSelectiveReripStats();\n const n2 = [...t2.owners], o3 = [];\n for (const t3 of n2) {\n this.incrementFailedOwnerPair(e51, t3) \u003e= 2 \u0026\u0026 o3.push(t3);\n }\n if (n2.some((t3) =\u003e this.hasFailedOwnerPath(t3, e51)))\n return this.selectiveReripStats.globalReripCount += 1, this.selectiveReripStats.globalReripReason = \"failed_owner_cycle\", this.selectiveReripStats.lastFailedRouteId = e51, this.selectiveReripStats.lastDirectOwnerRouteIds = n2, this.selectiveReripStats.lastRepeatedOwnerRouteIds = o3, this.selectiveReripStats.lastAlternateOwnerRouteIds = [], this.selectiveReripStats.lastRippedRouteIds = [], this.selectiveReripStats.lastRelaxedSearchExpandedLabelCount = t2.expandedLabelCount, this.selectiveReripStats.lastAlternateSearchExpandedLabelCount = 0, this.failedOwnerPairCounts.clear(), super.onOutOfCandidates(), void this.publishSelectiveReripStats();\n let i3;\n if (o3.length \u003e 0 \u0026\u0026 (this.selectiveReripStats.alternateBlockerSearchCount += 1, i3 = this.findRelaxedBlockerPathPreferringPreservedRoutes(new Set(o3)), !i3.found))\n return this.selectiveReripStats.globalReripCount += 1, this.selectiveReripStats.globalReripReason = i3.reason, this.selectiveReripStats.lastFailedRouteId = e51, this.selectiveReripStats.lastDirectOwnerRouteIds = n2, this.selectiveReripStats.lastRepeatedOwnerRouteIds = o3, this.selectiveReripStats.lastAlternateOwnerRouteIds = [], this.selectiveReripStats.lastRippedRouteIds = [], this.selectiveReripStats.lastRelaxedSearchExpandedLabelCount = t2.expandedLabelCount, this.selectiveReripStats.lastAlternateSearchExpandedLabelCount = i3.expandedLabelCount, super.onOutOfCandidates(), void this.publishSelectiveReripStats();\n const r3 = i3?.found ? [...i3.owners] : undefined, s2 = function(e52) {\n const t3 = new Set(e52.alternateOwnerRouteIds ?? e52.directOwnerRouteIds);\n if (t3.delete(e52.failedRouteId), t3.size === 0)\n throw new Error(`SelectiveReripTinyHyperGraphSolver: route ${e52.failedRouteId} has blocker resources but no distinct committed owner can be reripped`);\n return t3;\n }({ failedRouteId: e51, directOwnerRouteIds: n2, alternateOwnerRouteIds: r3 });\n this.clearPartialRipPlans(s2);\n const a3 = (r3 ?? []).filter((e52) =\u003e !t2.owners.has(e52));\n this.selectiveReripCongestionUpdateCount \u003c 1 \u0026\u0026 (this.addCongestionCostForSelectiveRerip(), this.selectiveReripCongestionUpdateCount += 1), this.rebuildCommittedState(s2), this.state.ripCount += 1, this.state.currentRouteId = undefined, this.state.currentRouteNetId = undefined, this.state.unroutedRoutes = function(e52) {\n const t3 = e52.pendingRouteIds.filter((t4) =\u003e t4 !== e52.failedRouteId \u0026\u0026 !e52.rippedRouteIds.has(t4)), n3 = [...e52.rippedRouteIds].filter((t4) =\u003e t4 !== e52.failedRouteId);\n return [e52.failedRouteId, ...t3, ...n3];\n }({ failedRouteId: e51, pendingRouteIds: this.state.unroutedRoutes, rippedRouteIds: s2 }), this.state.candidateQueue.clear(), this.resetCandidateBestCosts(), this.state.goalPortId = -1, this.selectiveReripStats.selectiveRipCount += 1, this.selectiveReripStats.selectivelyRippedRouteCount += s2.size, this.selectiveReripStats.alternateOwnerCount += a3.length, this.selectiveReripStats.lastFailedRouteId = e51, this.selectiveReripStats.lastDirectOwnerRouteIds = n2, this.selectiveReripStats.lastRepeatedOwnerRouteIds = o3, this.selectiveReripStats.lastAlternateOwnerRouteIds = a3, this.selectiveReripStats.lastRippedRouteIds = [...s2], this.selectiveReripStats.lastRelaxedSearchExpandedLabelCount = t2.expandedLabelCount, this.selectiveReripStats.lastAlternateSearchExpandedLabelCount = i3?.expandedLabelCount ?? 0, this.publishSelectiveReripStats();\n }\n addCongestionCostForSelectiveRerip() {\n for (let e51 = 0;e51 \u003c this.topology.regionCount; e51++) {\n const t2 = this.state.regionIntersectionCaches[e51]?.existingRegionCost ?? 0;\n this.state.regionCongestionCost[e51] += t2 * this.RIP_CONGESTION_REGION_COST_FACTOR;\n }\n }\n findRelaxedBlockerPath(e51 = new Set) {\n const t2 = this.state.currentRouteId, n2 = this.state.currentRouteNetId;\n if (t2 === undefined || n2 === undefined)\n throw new Error(\"SelectiveReripTinyHyperGraphSolver: blocker search requires a current route and net\");\n const o3 = this.getRouteStartPortId(t2), i3 = this.getRouteEndPortId(t2), r3 = this.getStartingNextRegionId(t2, o3);\n if (r3 === undefined)\n throw new Error(`SelectiveReripTinyHyperGraphSolver: route ${this.describeRoute(t2)} has no starting region for blocker search`);\n const s2 = this.getPortOwners(), a3 = this.hasBoundedReachabilityGeometry({ startPortId: o3, goalPortId: i3 }), c3 = new Map, l3 = new Map, h2 = new Map, d2 = new Map, u2 = this.topology.portX[i3], p3 = this.topology.portY[i3], m2 = { goalPortId: i3, routeNetId: n2, portOwners: s2, portResources: c3, hopTemplatesByRegion: l3, forbiddenOwnerRouteIds: e51 }, g2 = this.getRelaxedSearchExpansionLimit(), f2 = { start: { portId: o3, nextRegionId: r3 }, getStateKey: ({ portId: e52, nextRegionId: t3 }) =\u003e this.getHopId(e52, t3), isGoal: ({ portId: e52 }) =\u003e e52 === i3, getHops: (e52) =\u003e {\n const t3 = this.getHopId(e52.portId, e52.nextRegionId), n3 = h2.get(t3);\n if (n3)\n return n3;\n const o4 = this.getRelaxedSearchHops({ state: e52 }, m2);\n return h2.set(t3, o4), o4;\n }, maxExpandedLabels: g2, getRemainingDistance: a3 ? ({ portId: e52 }) =\u003e {\n const t3 = d2.get(e52);\n if (t3 !== undefined)\n return t3;\n const n3 = this.topology.portX[e52], o4 = this.topology.portY[e52], i4 = 256 * Number.EPSILON * Math.max(1, Math.abs(n3), Math.abs(o4), Math.abs(u2), Math.abs(p3)), r4 = Math.max(0, Math.hypot(n3 - u2, o4 - p3) - i4);\n return d2.set(e52, r4), r4;\n } : undefined };\n if (!a3)\n return lJ({ ...f2, checkReachability: true });\n const _2 = function(e52, t3) {\n if (e52.maxExpandedStates !== 1 / 0 \u0026\u0026 (!Number.isInteger(e52.maxExpandedStates) || e52.maxExpandedStates \u003c 0))\n throw new Error(\"maxExpandedLabels must be a non-negative integer\");\n const n3 = { search: t3, ownerFreeQueue: [e52.start], ownedQueue: [], ownerFreeByHopId: new Map([[t3.solver.getHopId(e52.start.portId, e52.start.nextRegionId), true]]), expansionsByRegion: new Map, totalHopDistance: 0, ownerFreePhase: true };\n let o4 = 0;\n for (let i4 = 0;i4 \u003c n3.ownerFreeQueue.length; i4++) {\n const r4 = n3.ownerFreeQueue[i4];\n if (r4.portId === t3.goalPortId)\n return { kind: \"reachable\", minimumOwnerCount: 0 };\n if (o4 \u003e= e52.maxExpandedStates)\n return { kind: \"incomplete\", minimumOwnerCount: 0 };\n if (o4++, !mJ(r4, n3))\n return { kind: \"incomplete\", minimumOwnerCount: 0 };\n }\n n3.ownerFreePhase = false;\n for (let i4 = 0;i4 \u003c n3.ownedQueue.length; i4++) {\n const r4 = n3.ownedQueue[i4], s3 = t3.solver.getHopId(r4.portId, r4.nextRegionId);\n if (n3.ownerFreeByHopId.get(s3) !== true) {\n if (r4.portId === t3.goalPortId)\n return { kind: \"reachable\", minimumOwnerCount: 1 };\n if (o4 \u003e= e52.maxExpandedStates)\n return { kind: \"incomplete\", minimumOwnerCount: 1 };\n if (o4++, !mJ(r4, n3))\n return { kind: \"incomplete\", minimumOwnerCount: 1 };\n }\n }\n return { kind: \"disconnected\", expandedStateCount: o4 };\n }({ start: f2.start, maxExpandedStates: g2 }, { solver: this, goalPortId: i3, getHops: (e52) =\u003e this.getRelaxedSearchHops({ state: e52 }, m2), getHopTemplates: (e52) =\u003e this.getRelaxedSearchHopTemplates(e52, m2) });\n return _2.kind === \"disconnected\" ? { found: false, reason: \"no_path\", expandedLabelCount: _2.expandedStateCount } : lJ({ ...f2, minimumOwnerCount: _2.minimumOwnerCount });\n }\n findRelaxedBlockerPathPreferringPreservedRoutes(e51 = new Set) {\n const t2 = this.getRouteIdsPreferredForPreservation();\n if (t2.size === 0)\n return this.findRelaxedBlockerPath(e51);\n const n2 = new Set(e51);\n for (const e52 of t2)\n n2.add(e52);\n const o3 = this.findRelaxedBlockerPath(n2);\n return o3.found \u0026\u0026 o3.owners.size \u003e 0 ? o3 : this.findRelaxedBlockerPath(e51);\n }\n getRelaxedSearchExpansionLimit() {\n let e51 = 0;\n for (const t3 of this.topology.incidentPortRegion)\n e51 += t3.length;\n const t2 = Math.max(4, Math.ceil(Math.log2(this.problem.routeCount + 1)));\n return Math.max(4096, e51 * t2 * 4);\n }\n hasBoundedReachabilityGeometry({ startPortId: e51, goalPortId: t2 }) {\n const { portCount: n2, portX: o3, portY: i3, regionIncidentPorts: r3 } = this.topology;\n if (!Number.isInteger(n2) || n2 \u003c 0 || o3.length !== n2 || i3.length !== n2 || !Number.isInteger(e51) || e51 \u003c 0 || e51 \u003e= n2 || !Number.isInteger(t2) || t2 \u003c 0 || t2 \u003e= n2)\n return false;\n for (let e52 = 0;e52 \u003c n2; e52++)\n if (!(Math.abs(o3[e52]) \u003c= Number.MAX_SAFE_INTEGER \u0026\u0026 Math.abs(i3[e52]) \u003c= Number.MAX_SAFE_INTEGER))\n return false;\n for (const e52 of r3) {\n if (!e52)\n return false;\n for (const t3 of e52)\n if (!Number.isInteger(t3) || t3 \u003c 0 || t3 \u003e= n2)\n return false;\n }\n return true;\n }\n getRelaxedSearchHopTemplates(e51, t2) {\n let n2 = t2.hopTemplatesByRegion.get(e51.nextRegionId);\n return n2 || (n2 = this.getRelaxedSearchHops({ state: e51, buildRegionTemplates: true }, t2), t2.hopTemplatesByRegion.set(e51.nextRegionId, n2)), n2;\n }\n getRelaxedSearchHops(e51, t2) {\n const { state: n2 } = e51, { goalPortId: o3, routeNetId: i3 } = t2;\n if (this.isRegionReservedForDifferentNet(n2.nextRegionId))\n return [];\n if (!e51.buildRegionTemplates \u0026\u0026 !this.isKnownSingleLayerRegion(n2.nextRegionId)) {\n const e52 = this.getRelaxedSearchHopTemplates(n2, t2), o4 = [];\n for (const t3 of e52)\n t3.state.portId !== n2.portId \u0026\u0026 o4.push({ state: t3.state, owners: t3.owners, data: t3.data, distance: Math.hypot(this.topology.portX[n2.portId] - this.topology.portX[t3.state.portId], this.topology.portY[n2.portId] - this.topology.portY[t3.state.portId]) });\n return o4;\n }\n const r3 = [];\n for (const s2 of this.topology.regionIncidentPorts[n2.nextRegionId] ?? []) {\n if (s2 === n2.portId \u0026\u0026 !e51.buildRegionTemplates)\n continue;\n if (this.isPortReservedForDifferentNet(s2))\n continue;\n if (s2 !== o3 \u0026\u0026 this.problem.portSectionMask[s2] === 0)\n continue;\n const a3 = this.getHopBlockerResources({ regionId: n2.nextRegionId, fromPortId: n2.portId, toPortId: s2, routeNetId: i3, portOwners: t2.portOwners, portResources: t2.portResources }), c3 = [];\n for (const e52 of a3)\n for (const t3 of e52.owners)\n c3.includes(t3) || c3.push(t3);\n if (c3.some((e52) =\u003e t2.forbiddenOwnerRouteIds.has(e52)))\n continue;\n let l3 = n2.nextRegionId;\n if (s2 !== o3) {\n const [e52, t3] = this.topology.incidentPortRegion[s2] ?? [];\n if (l3 = e52 === n2.nextRegionId ? t3 : e52, l3 === undefined || this.isRegionReservedForDifferentNet(l3))\n continue;\n }\n r3.push({ state: { portId: s2, nextRegionId: l3 }, distance: Math.hypot(this.topology.portX[n2.portId] - this.topology.portX[s2], this.topology.portY[n2.portId] - this.topology.portY[s2]), owners: c3, data: { resources: a3 } });\n }\n return r3;\n }\n getHopBlockerResources(e51) {\n const t2 = [], n2 = this.state.portAssignment[e51.toPortId];\n if (n2 !== -1 \u0026\u0026 n2 !== e51.routeNetId) {\n let o4 = e51.portResources.get(e51.toPortId);\n if (!o4) {\n const t3 = [...e51.portOwners.get(e51.toPortId) ?? new Set].filter((t4) =\u003e this.problem.routeNet[t4] !== e51.routeNetId);\n if (t3.length === 0)\n throw new Error(`SelectiveReripTinyHyperGraphSolver: port ${e51.toPortId} is assigned to foreign net ${n2} without a committed route owner`);\n o4 = { kind: \"port\", portId: e51.toPortId, owners: t3 }, e51.portResources.set(e51.toPortId, o4);\n }\n t2.push(o4);\n }\n const o3 = this.getHardBlockedCrossingOwners(e51.regionId, e51.fromPortId, e51.toPortId);\n return o3.length \u003e 0 \u0026\u0026 t2.push({ kind: \"same_layer_intersection\", regionId: e51.regionId, fromPortId: e51.fromPortId, toPortId: e51.toPortId, owners: o3 }), t2;\n }\n getPortOwners() {\n const e51 = new Map;\n for (const t2 of this.state.regionSegments)\n for (const [n2, o3, i3] of t2)\n for (const t3 of [o3, i3]) {\n const o4 = e51.get(t3) ?? new Set;\n o4.add(n2), e51.set(t3, o4);\n }\n return e51;\n }\n getHardBlockedCrossingOwners(e51, t2, n2) {\n if (!this.isKnownSingleLayerRegion(e51))\n return [];\n const o3 = this.state.currentRouteNetId;\n if (o3 === undefined)\n throw new Error(\"SelectiveReripTinyHyperGraphSolver: crossing ownership requires a current route net\");\n const i3 = new Set;\n for (const [r3, s2, a3] of this.state.regionSegments[e51] ?? [])\n this.problem.routeNet[r3] !== o3 \u0026\u0026 this.segmentsCrossOnSameLayer(e51, t2, n2, s2, a3) \u0026\u0026 i3.add(r3);\n return [...i3];\n }\n segmentsCrossOnSameLayer(e51, t2, n2, o3, i3) {\n const r3 = this.populateSegmentGeometryScratch(e51, t2, n2), s2 = r3.lesserAngle, a3 = r3.greaterAngle, c3 = r3.layerMask, l3 = this.populateSegmentGeometryScratch(e51, o3, i3);\n if ((c3 \u0026 l3.layerMask) === 0)\n return false;\n if (s2 === l3.lesserAngle || s2 === l3.greaterAngle || a3 === l3.lesserAngle || a3 === l3.greaterAngle)\n return false;\n return (s2 \u003c l3.lesserAngle \u0026\u0026 l3.lesserAngle \u003c a3) !== (s2 \u003c l3.greaterAngle \u0026\u0026 l3.greaterAngle \u003c a3);\n }\n rebuildCommittedState(e51) {\n const t2 = this.state.regionSegments;\n this.state.regionSegments = this.state.regionSegments.map((t3) =\u003e t3.filter(([t4]) =\u003e !e51.has(t4))), this.state.portAssignment.fill(-1), this.state.regionIntersectionCaches = Array.from({ length: this.topology.regionCount }, (e52, n2) =\u003e this.state.regionSegments[n2].length === t2[n2].length ? this.state.regionIntersectionCaches[n2] : Zq());\n for (let e52 = 0;e52 \u003c this.state.regionSegments.length; e52++) {\n const n2 = this.state.regionSegments[e52].length !== t2[e52].length;\n for (const [t3, o3, i3] of this.state.regionSegments[e52]) {\n const r3 = this.problem.routeNet[t3];\n this.state.currentRouteNetId = r3;\n for (const e53 of [o3, i3]) {\n const t4 = this.state.portAssignment[e53];\n if (t4 !== -1 \u0026\u0026 t4 !== r3)\n throw new Error(`SelectiveReripTinyHyperGraphSolver: rebuilding committed routes found cross-net ownership at port ${e53} between net ${t4} and net ${r3}`);\n this.state.portAssignment[e53] = r3;\n }\n n2 \u0026\u0026 this.appendSegmentToRegionCache(e52, o3, i3);\n }\n if (!n2) {\n const t3 = this.state.regionIntersectionCaches[e52];\n if (t3.existingSegmentCount === 0)\n continue;\n const n3 = this.computeRegionCostForRegion(e52, t3.existingSameLayerIntersections, t3.existingCrossingLayerIntersections, t3.existingEntryExitLayerChanges, t3.existingSegmentCount);\n n3 !== t3.existingRegionCost \u0026\u0026 (this.state.regionIntersectionCaches[e52] = { ...t3, existingRegionCost: n3 });\n }\n }\n this.state.currentRouteNetId = undefined;\n }\n incrementFailedOwnerPair(e51, t2) {\n const n2 = this.failedOwnerPairCounts.get(e51) ?? new Map, o3 = (n2.get(t2) ?? 0) + 1;\n return n2.set(t2, o3), this.failedOwnerPairCounts.set(e51, n2), o3;\n }\n hasFailedOwnerPath(e51, t2) {\n const n2 = [e51], o3 = new Set;\n for (;n2.length \u003e 0; ) {\n const e52 = n2.pop();\n if (e52 === t2)\n return true;\n o3.has(e52) || (o3.add(e52), n2.push(...this.failedOwnerPairCounts.get(e52)?.keys() ?? []));\n }\n return false;\n }\n publishSelectiveReripStats() {\n const e51 = [];\n for (const [t2, n2] of this.failedOwnerPairCounts)\n for (const [o3, i3] of n2)\n e51.push({ failedRouteId: t2, ownerRouteId: o3, count: i3 });\n e51.sort((e52, t2) =\u003e e52.failedRouteId - t2.failedRouteId || e52.ownerRouteId - t2.ownerRouteId), this.selectiveReripStats.failedOwnerPairs = e51, this.selectiveReripStats.failedOwnerPairCount = e51.length, this.selectiveReripStats.maxFailedOwnerPairCount = Math.max(0, ...e51.map(({ count: e52 }) =\u003e e52)), this.stats = { ...this.stats, ...this.getSelectiveReripStats() };\n }\n describeRoute(e51) {\n const t2 = this.problem.routeMetadata?.[e51]?.connectionId;\n return t2 === undefined ? String(e51) : `${e51} (${String(t2)})`;\n }\n};\nvar fJ = class extends gJ {\n remainingReripBudget = 0;\n onOutOfCandidates() {\n super.onOutOfCandidates(), this.state.ripCount \u003e= this.remainingReripBudget \u0026\u0026 (this.failed = true, this.error = \"Congestion-aware final routing exhausted its rerip budget\");\n }\n};\nvar _J = class extends gJ {\n initialAssignmentRouteIds;\n getRouteIdsPreferredForPreservation() {\n return this.initialAssignmentRouteIds || (this.initialAssignmentRouteIds = new Set((this.problem.initialAssignments ?? []).map((e51) =\u003e e51.routeId))), this.initialAssignmentRouteIds;\n }\n resetRoutingStateForRerip() {\n super.resetRoutingStateForRerip(), this.problem.initialAssignments?.length \u0026\u0026 GZ({ topology: this.topology, problem: this.problem, state: this.state, routeSuccessCountByRouteId: this.routeSuccessCountByRouteId, appendSegmentToRegionCache: (e51, t2, n2) =\u003e this.appendSegmentToRegionCache(e51, t2, n2) });\n }\n};\nvar yJ = class {\n constructor(e51) {\n this.geometry = e51;\n }\n epoch;\n generation = -1;\n frontiers = new Map;\n rows = [];\n step(e51) {\n const { topology: t2, problem: n2, state: o3 } = e51, i3 = o3.candidateQueue;\n if (!(this.geometry.supported \u0026\u0026 o3.currentRouteId !== undefined \u0026\u0026 i3 instanceof ZZ \u0026\u0026 o3.candidateBestCostByHopId instanceof Float64Array \u0026\u0026 o3.candidateBestCostGenerationByHopId instanceof Uint32Array))\n return false;\n this.geometry.prepare(), this.epoch === i3.closureEpoch \u0026\u0026 this.generation === o3.candidateBestCostGeneration || (this.epoch = i3.closureEpoch, this.generation = o3.candidateBestCostGeneration, this.frontiers.clear());\n const r3 = i3.dequeue();\n if (!r3)\n return e51.onOutOfCandidates(), true;\n const s2 = r3.hopId ?? e51.getHopId(r3.portId, r3.nextRegionId);\n if (r3.g \u003e e51.getCandidateBestCost(s2) || e51.isRegionReservedForDifferentNet(r3.nextRegionId))\n return true;\n const a3 = r3.nextRegionId, c3 = o3.currentRouteNetId, l3 = o3.goalPortId, h2 = o3.portAssignment, d2 = e51.problemSetup.portEndpointReservationNetId, u2 = n2.regionNetId;\n let p3 = this.frontiers.get(a3);\n if (!p3) {\n const o4 = t2.regionIncidentPorts[a3], i4 = new Int32Array(o4.length).fill(-1), r4 = new Int32Array(o4.length), s3 = new Int32Array(o4.length);\n let m2 = -1, g2 = -1;\n for (let p4 = 0;p4 \u003c o4.length; p4++) {\n const f2 = o4[p4], _2 = d2[f2];\n if (_2 === -2 || _2 !== -1 \u0026\u0026 _2 !== c3 || h2[f2] !== -1 \u0026\u0026 h2[f2] !== c3)\n continue;\n let y2 = a3;\n if (f2 !== l3) {\n if (n2.portSectionMask[f2] === 0)\n continue;\n const e52 = t2.incidentPortRegion[f2], o5 = e52[0] === a3 ? e52[1] : e52[0];\n if (o5 === undefined || u2[o5] !== -1 \u0026\u0026 u2[o5] !== c3)\n continue;\n y2 = o5;\n }\n r4[p4] = y2, s3[p4] = e51.getHopId(f2, y2), g2 === -1 ? m2 = p4 : i4[g2] = p4, g2 = p4;\n }\n p3 = { neighbors: o4, next: i4, nextRegions: r4, hops: s3, head: m2 }, this.frontiers.set(a3, p3);\n }\n return this.expand(e51, r3, p3), true;\n }\n expand(e51, t2, n2) {\n const { topology: o3, problem: i3, state: r3 } = e51, s2 = t2.nextRegionId, a3 = r3.regionIntersectionCaches[s2];\n let c3 = this.rows[s2];\n if (!c3 || c3.cache !== a3 || c3.via !== e51.minViaPadDiameter || c3.density !== e51.TRACE_DENSITY_COST_FACTOR) {\n const t3 = o3.regionAvailableZMask?.[s2] ?? 0;\n c3 = { cache: a3, via: e51.minViaPadDiameter, density: e51.TRACE_DENSITY_COST_FACTOR, single: t3 \u003e 0 \u0026\u0026 !(t3 \u0026 t3 - 1), costs: new Float64Array(2 * a3.netIds.length + 2) };\n for (let e52 = 0;e52 \u003c c3.costs.length; e52++)\n c3.costs[e52] = YZ(o3.regionWidth[s2], o3.regionHeight[s2], a3.existingSameLayerIntersections, a3.existingCrossingLayerIntersections + e52, a3.existingEntryExitLayerChanges, a3.existingSegmentCount + 1, t3, c3.via, c3.density) - a3.existingRegionCost;\n this.rows[s2] = c3;\n }\n const { neighbors: l3, next: h2, nextRegions: d2, hops: u2 } = n2, p3 = r3.candidateBestCostByHopId, m2 = r3.candidateBestCostGenerationByHopId, g2 = r3.candidateBestCostGeneration, f2 = r3.currentRouteNetId, _2 = r3.candidateQueue, y2 = this.geometry.rowOffsets[2 * t2.portId + (o3.incidentPortRegion[t2.portId][0] === s2 ? 0 : 1)], b2 = this.geometry.distances, x2 = o3.incidentPortRegion[t2.portId][0] === s2 ? o3.portAngleForRegion1[t2.portId] : o3.portAngleForRegion2?.[t2.portId] ?? o3.portAngleForRegion1[t2.portId], v2 = o3.portZ[t2.portId], { netIds: I2, lesserAngles: S2, greaterAngles: C, layerMasks: P } = a3, M = r3.regionCongestionCost[s2], w = t2.g + M;\n let N = n2.head, R2 = -1;\n for (;N !== -1; ) {\n const a4 = N;\n N = h2[a4];\n const T2 = R2;\n R2 = a4;\n const E3 = l3[a4];\n if (E3 === r3.goalPortId)\n return void e51.onPathFound(t2);\n if (E3 === t2.portId)\n continue;\n const A2 = u2[a4];\n if (_2.isClosedHopId(A2)) {\n T2 === -1 ? n2.head = N : h2[T2] = N, R2 = T2;\n continue;\n }\n const O2 = m2[A2] === g2 ? p3[A2] : 1 / 0;\n if (t2.g \u003e= O2)\n continue;\n const k2 = b2[y2 + a4] * e51.DISTANCE_TO_COST, D2 = i3.portPenalty?.[E3] ?? 0;\n if (w + D2 + k2 \u003e= O2)\n continue;\n const L2 = o3.portZ[E3], z2 = o3.incidentPortRegion[E3][0] === s2 ? o3.portAngleForRegion1[E3] : o3.portAngleForRegion2?.[E3] ?? o3.portAngleForRegion1[E3], B2 = Math.min(x2, z2), F2 = Math.max(x2, z2), j2 = 1 \u003c\u003c v2 | 1 \u003c\u003c L2;\n let $2 = 0, Y2 = 0;\n for (let e52 = 0;e52 \u003c I2.length; e52++)\n I2[e52] !== f2 \u0026\u0026 (B2 \u003c S2[e52] \u0026\u0026 S2[e52] \u003c F2) != (B2 \u003c C[e52] \u0026\u0026 C[e52] \u003c F2) \u0026\u0026 (j2 \u0026 P[e52] ? $2++ : Y2++);\n if ($2 \u003e 0 \u0026\u0026 c3.single)\n continue;\n const X = t2.g + c3.costs[2 * $2 + Y2 + (v2 !== L2 ? 1 : 0)] + M + D2 + k2;\n if (!Number.isFinite(X) || X \u003e= O2)\n continue;\n const H2 = e51.computeH(E3);\n m2[A2] = g2, p3[A2] = X, _2.queue({ hopId: A2, prevRegionId: s2, nextRegionId: d2[a4], portId: E3, g: X, h: H2, f: X + H2, prevCandidate: t2 });\n }\n }\n};\nvar vJ = class extends BaseSolver {\n constructor(e51) {\n super(), this.input = e51;\n }\n static solverName = \"RegionDistancePreparationSolver\";\n output;\n _step() {\n const { portX: e51, portY: t2, regions: n2 } = this.input, o3 = new Float64Array(n2.reduce((e52, t3) =\u003e e52 + t3.length ** 2, 0));\n let i3 = 0;\n for (const r3 of n2)\n for (const n3 of r3)\n for (const s2 of r3) {\n const r4 = e51[n3] - e51[s2], a3 = t2[n3] - t2[s2];\n o3[i3++] = Math.sqrt(r4 * r4 + a3 * a3);\n }\n this.output = o3, this.solved = true;\n }\n getOutput() {\n if (!this.output)\n throw new Error(\"Region distances have not been prepared\");\n return this.output;\n }\n};\nSolverRuntime.registerSolver(vJ);\nvar IJ = class {\n constructor(e51) {\n this.topology = e51, this.rowOffsets = new Int32Array(2 * e51.portCount).fill(-1);\n let t2 = 0;\n if (this.supported = e51.incidentPortRegion.every((e52) =\u003e e52.length \u003c= 2) \u0026\u0026 e51.regionIncidentPorts.reduce((e52, t3) =\u003e e52 + t3.length ** 2, 0) \u003c= 16777216, !this.supported)\n return;\n for (let n3 = 0;n3 \u003c e51.regionCount; n3++) {\n const o4 = e51.regionIncidentPorts[n3];\n for (let i3 = 0;i3 \u003c o4.length; i3++) {\n const r3 = o4[i3], s2 = 2 * r3 + (e51.incidentPortRegion[r3][0] === n3 ? 0 : 1);\n this.rowOffsets[s2] = t2 + i3 * o4.length;\n }\n t2 += o4.length ** 2;\n }\n let n2 = [], o3 = 0;\n for (const i3 of e51.regionIncidentPorts)\n n2.push(i3), o3 += i3.length ** 2, o3 \u003e= t2 / 4 \u0026\u0026 this.jobs.length \u003c 3 \u0026\u0026 (this.jobs.push({ portX: e51.portX, portY: e51.portY, regions: n2 }), n2 = [], o3 = 0);\n n2.length \u0026\u0026 this.jobs.push({ portX: e51.portX, portY: e51.portY, regions: n2 });\n }\n rowOffsets;\n jobs = [];\n distances;\n supported;\n accept(e51) {\n this.distances = new Float64Array(e51.reduce((e52, t3) =\u003e e52 + t3.length, 0));\n let t2 = 0;\n for (const n2 of e51)\n this.distances.set(n2, t2), t2 += n2.length;\n }\n prepare() {\n !this.distances \u0026\u0026 this.supported \u0026\u0026 this.accept(this.jobs.map((e51) =\u003e {\n const t2 = new vJ(e51);\n return t2.solve(), t2.getOutput();\n }));\n }\n async prepareAsync(e51) {\n !this.distances \u0026\u0026 this.supported \u0026\u0026 this.accept(await Promise.all(this.jobs.map((t2) =\u003e e51.executeAsync(vJ, t2))));\n }\n};\nvar SJ = class extends gJ {\n workspace;\n remainingReripBudget = 0;\n constructor(e51, t2, n2, o3) {\n super(e51, t2, n2), this.workspace = new yJ(o3);\n }\n _step() {\n this.workspace.step(this) || super._step();\n }\n onOutOfCandidates() {\n super.onOutOfCandidates(), this.state.ripCount \u003e= this.remainingReripBudget \u0026\u0026 (this.failed = true, this.error = \"Congestion-aware final routing exhausted its rerip budget\");\n }\n};\nvar CJ = class extends _J {\n geometry = new IJ(this.topology);\n workspace = new yJ(this.geometry);\n asyncRunning = false;\n _step() {\n const e51 = this.state.currentRouteId;\n (e51 !== undefined \u0026\u0026 this.partialRipRoutePlans.has(e51) || !this.workspace.step(this)) \u0026\u0026 super._step();\n }\n createGreedyFinalRouteSolver(e51, t2) {\n if (t2 \u003e= 0)\n return super.createGreedyFinalRouteSolver(e51, t2);\n const n2 = new SJ(this.topology, this.problem, { ...e51, MAX_ITERATIONS: Math.max(e51.MAX_ITERATIONS ?? 50000, 2 * this.MAX_ITERATIONS) }, this.geometry);\n return n2.remainingReripBudget = this.costAwareFinalReripBudget - this.state.ripCount, n2;\n }\n async solveAsync(e51, t2 = 1 / 0) {\n if (this.asyncRunning)\n throw new Error(\"Prepared routing solveAsync is already running\");\n this.asyncRunning = true;\n try {\n for (e51 \u0026\u0026 !this.solved \u0026\u0026 !this.failed \u0026\u0026 this.iterations \u003c t2 \u0026\u0026 await this.geometry.prepareAsync(e51);!this.solved \u0026\u0026 !this.failed \u0026\u0026 this.iterations \u003c t2; )\n this.step();\n } catch (e52) {\n throw this.failed = true, this.error = `Prepared routing execution failed: ${e52}`, e52;\n } finally {\n this.asyncRunning = false;\n }\n }\n};\nvar MJ = (e51) =\u003e {\n const t2 = typeof e51.d?.netId == \"number\" ? e51.d.netId : typeof e51.d?.NetId == \"number\" ? e51.d.NetId : undefined;\n return Number.isFinite(t2) ? t2 : undefined;\n};\nvar wJ = (e51) =\u003e {\n const t2 = new Set;\n for (const n3 of e51.connections ?? [])\n t2.add(n3.startRegionId), t2.add(n3.endRegionId);\n const n2 = new Set(e51.regions.filter((e52) =\u003e ((e53) =\u003e {\n if (e53.d?._containsObstacle !== true)\n return false;\n const t3 = MJ(e53);\n return t3 === undefined || t3 === -1;\n })(e52) \u0026\u0026 !t2.has(e52.regionId)).map((e52) =\u003e e52.regionId));\n if (n2.size === 0)\n return e51;\n const o3 = e51.ports.filter((e52) =\u003e !n2.has(e52.region1Id) \u0026\u0026 !n2.has(e52.region2Id)), i3 = (e51.connections ?? []).find((e52) =\u003e n2.has(e52.startRegionId) || n2.has(e52.endRegionId));\n if (i3)\n throw new Error(`Connection \"${i3.connectionId}\" references full-obstacle region`);\n return { ...e51, regions: e51.regions.filter((e52) =\u003e !n2.has(e52.regionId)), ports: o3 };\n};\nvar NJ = (e51) =\u003e {\n const t2 = e51.d?.bounds;\n if (t2)\n return t2;\n const n2 = e51.d?.center, o3 = e51.d?.width, i3 = e51.d?.height;\n return n2 \u0026\u0026 typeof n2.x == \"number\" \u0026\u0026 typeof n2.y == \"number\" \u0026\u0026 typeof o3 == \"number\" \u0026\u0026 typeof i3 == \"number\" ? { minX: n2.x - o3 / 2, maxX: n2.x + o3 / 2, minY: n2.y - i3 / 2, maxY: n2.y + i3 / 2 } : { minX: 0, maxX: 0, minY: 0, maxY: 0 };\n};\nvar RJ = (e51) =\u003e Number(e51.d?.x ?? 0);\nvar TJ = (e51) =\u003e Number(e51.d?.y ?? 0);\nvar EJ = (e51, t2) =\u003e {\n if (!t2)\n return 0;\n const n2 = NJ(t2), o3 = RJ(e51), i3 = TJ(e51), r3 = n2.minX \u003c= o3 \u0026\u0026 o3 \u003c= n2.maxX, s2 = n2.minY \u003c= i3 \u0026\u0026 i3 \u003c= n2.maxY;\n if (s2 \u0026\u0026 o3 \u003e= n2.maxX) {\n const e52 = Math.max(n2.maxY - n2.minY, 0.000000001), t3 = (i3 - n2.minY) / e52;\n return Math.round(9000 * t3);\n }\n if (r3 \u0026\u0026 i3 \u003e= n2.maxY) {\n const e52 = Math.max(n2.maxX - n2.minX, 0.000000001), t3 = (n2.maxX - o3) / e52;\n return 9000 + Math.round(9000 * t3);\n }\n if (s2 \u0026\u0026 o3 \u003c= n2.minX) {\n const e52 = Math.max(n2.maxY - n2.minY, 0.000000001), t3 = (n2.maxY - i3) / e52;\n return 18000 + Math.round(9000 * t3);\n }\n if (r3 \u0026\u0026 i3 \u003c= n2.minY) {\n const e52 = Math.max(n2.maxX - n2.minX, 0.000000001), t3 = (o3 - n2.minX) / e52;\n return 27000 + Math.round(9000 * t3);\n }\n const a3 = Math.abs(o3 - n2.minX), c3 = Math.abs(o3 - n2.maxX), l3 = Math.abs(i3 - n2.minY), h2 = Math.abs(i3 - n2.maxY), d2 = Math.min(a3, c3, l3, h2), u2 = Math.max(n2.maxX - n2.minX, 0.000000001), p3 = Math.max(n2.maxY - n2.minY, 0.000000001);\n if (d2 === c3) {\n const e52 = (i3 - n2.minY) / p3;\n return Math.round(9000 * e52);\n }\n if (d2 === h2) {\n const e52 = (n2.maxX - o3) / u2;\n return 9000 + Math.round(9000 * e52);\n }\n if (d2 === a3) {\n const e52 = (n2.maxY - i3) / p3;\n return 18000 + Math.round(9000 * e52);\n }\n const m2 = (o3 - n2.minX) / u2;\n return 27000 + Math.round(9000 * m2);\n};\nvar AJ = (e51, t2) =\u003e {\n if (!e51)\n return;\n return [...e51.pointIds].sort((e52, n2) =\u003e {\n const o3 = t2.get(e52), i3 = t2.get(n2), r3 = Number(o3?.d?.distToCentermostPortOnZ ?? Number.POSITIVE_INFINITY), s2 = Number(i3?.d?.distToCentermostPortOnZ ?? Number.POSITIVE_INFINITY);\n if (r3 !== s2)\n return r3 - s2;\n const a3 = Number(o3?.d?.z ?? 0), c3 = Number(i3?.d?.z ?? 0);\n return a3 !== c3 ? a3 - c3 : e52.localeCompare(n2);\n })[0];\n};\nvar OJ = (e51) =\u003e {\n const t2 = wJ(e51), n2 = new Map, o3 = new Map, i3 = new Map, r3 = new Map((t2.solvedRoutes ?? []).map((e52) =\u003e [e52.connection.connectionId, e52]));\n t2.regions.forEach((e52, t3) =\u003e {\n n2.set(e52.regionId, t3);\n }), t2.ports.forEach((e52, t3) =\u003e {\n o3.set(e52.portId, t3), i3.set(e52.portId, e52);\n });\n const s2 = t2.regions.length, a3 = t2.ports.length, c3 = t2.regions.map((e52) =\u003e e52.pointIds.map((e53) =\u003e o3.get(e53)).filter((e53) =\u003e e53 !== undefined)), l3 = Array.from({ length: a3 }, () =\u003e []), h2 = new Float64Array(s2), d2 = new Float64Array(s2), u2 = new Float64Array(s2), p3 = new Float64Array(s2), m2 = new Int32Array(s2), g2 = new Int32Array(s2).fill(-1), f2 = new Int8Array(s2);\n t2.regions.forEach((e52, t3) =\u003e {\n const n3 = ((e53) =\u003e {\n const t4 = NJ(e53), n4 = typeof e53.d?.width == \"number\" ? e53.d.width : t4.maxX - t4.minX, o5 = typeof e53.d?.height == \"number\" ? e53.d.height : t4.maxY - t4.minY;\n return { centerX: typeof e53.d?.center?.x == \"number\" ? e53.d.center.x : (t4.minX + t4.maxX) / 2, centerY: typeof e53.d?.center?.y == \"number\" ? e53.d.center.y : (t4.minY + t4.maxY) / 2, width: n4, height: o5 };\n })(e52);\n h2[t3] = n3.width, d2[t3] = n3.height, u2[t3] = n3.centerX, p3[t3] = n3.centerY, m2[t3] = ((e53) =\u003e {\n const t4 = e53.d?.availableZ;\n if (!Array.isArray(t4))\n return 0;\n let n4 = 0;\n for (const e54 of t4)\n !Number.isInteger(e54) || e54 \u003c 0 || e54 \u003e= 31 || (n4 |= 1 \u003c\u003c e54);\n return n4;\n })(e52);\n const o4 = MJ(e52);\n o4 !== undefined \u0026\u0026 (g2[t3] = o4, f2[t3] = 1);\n });\n const _2 = new Int32Array(a3), y2 = new Int32Array(a3), b2 = new Float64Array(a3), x2 = new Float64Array(a3), v2 = new Int32Array(a3);\n t2.ports.forEach((e52, o4) =\u003e {\n const i4 = n2.get(e52.region1Id), r4 = n2.get(e52.region2Id);\n if (i4 === undefined || r4 === undefined)\n throw new Error(`Port \"${e52.portId}\" references missing regions \"${e52.region1Id}\" or \"${e52.region2Id}\"`);\n l3[o4] = [i4, r4], b2[o4] = RJ(e52), x2[o4] = TJ(e52), v2[o4] = ((e53) =\u003e {\n const t3 = Number(e53.d?.z ?? 0);\n return Number.isFinite(t3) ? t3 : 0;\n })(e52), _2[o4] = EJ(e52, t2.regions[i4]), y2[o4] = EJ(e52, t2.regions[r4]);\n });\n const I2 = t2.regions.map((e52, t3) =\u003e ((e53, t4) =\u003e {\n const n3 = e53.d \u0026\u0026 typeof e53.d == \"object\" \u0026\u0026 !Array.isArray(e53.d) ? { ...e53.d } : { value: e53.d };\n return n3.layer = t4, Object.defineProperty(n3, \"serializedRegionId\", { value: e53.regionId, enumerable: false, configurable: true, writable: true }), n3;\n })(e52, ((e53) =\u003e NZ(RZ(m2[e53])) ?? NZ((c3[e53] ?? []).map((e54) =\u003e v2[e54])) ?? \"z0\")(t3))), S2 = t2.ports.map((e52, t3) =\u003e ((e53, t4) =\u003e {\n const n3 = e53.d \u0026\u0026 typeof e53.d == \"object\" \u0026\u0026 !Array.isArray(e53.d) ? { ...e53.d } : { value: e53.d };\n return n3.layer = t4, Object.defineProperty(n3, \"serializedPortId\", { value: e53.portId, enumerable: false, configurable: true, writable: true }), n3;\n })(e52, NZ([v2[t3]]) ?? \"z0\")), C = t2.connections ?? [], P = new Map;\n let M = 0;\n const w = (e52) =\u003e {\n const t3 = e52.mutuallyConnectedNetworkId ?? e52.connectionId;\n let n3 = P.get(t3);\n return n3 === undefined \u0026\u0026 (n3 = M++, P.set(t3, n3)), n3;\n }, N = Array.from({ length: s2 }, () =\u003e new Set), R2 = (e52, t3) =\u003e {\n const o4 = n2.get(e52);\n if (o4 === undefined)\n throw new Error(`Connection references missing region \"${e52}\"`);\n N[o4].add(t3);\n };\n C.forEach((e52) =\u003e {\n const t3 = w(e52);\n R2(e52.startRegionId, t3), R2(e52.endRegionId, t3);\n }), N.forEach((e52, t3) =\u003e {\n f2[t3] !== 1 \u0026\u0026 e52.size === 1 \u0026\u0026 (g2[t3] = [...e52][0]);\n });\n const T2 = C.map((e52) =\u003e {\n const n3 = r3.get(e52.connectionId), o4 = ((e53, t3) =\u003e e53.ports.filter((e54) =\u003e e54.region1Id === t3.startRegionId \u0026\u0026 e54.region2Id === t3.endRegionId || e54.region2Id === t3.startRegionId \u0026\u0026 e54.region1Id === t3.endRegionId).map((e54) =\u003e e54.portId))(t2, e52);\n return { connection: e52, solvedRoute: n3, sharedPortIds: o4 };\n }).filter(({ solvedRoute: e52, sharedPortIds: t3 }) =\u003e t3.length === 0 || (e52?.path.length ?? 0) \u003e 1), E3 = T2.length, A2 = new Map(T2.map(({ connection: e52 }, t3) =\u003e [e52.connectionId, t3])), O2 = new Int8Array(a3).fill(1), k2 = new Int32Array(E3), D2 = new Int32Array(E3), L2 = new Int32Array(E3);\n T2.forEach(({ connection: e52, solvedRoute: n3 }, r4) =\u003e {\n const s3 = AJ(t2.regions.find((t3) =\u003e t3.regionId === e52.startRegionId), i3), a4 = AJ(t2.regions.find((t3) =\u003e t3.regionId === e52.endRegionId), i3), c4 = n3?.path[0]?.portId ?? s3, l4 = n3?.path[n3.path.length - 1]?.portId ?? a4, h3 = c4 !== undefined ? o3.get(c4) : undefined, d3 = l4 !== undefined ? o3.get(l4) : undefined;\n if (h3 === undefined || d3 === undefined)\n throw new Error(`Connection \"${e52.connectionId}\" could not be mapped to route endpoints`);\n k2[r4] = h3, D2[r4] = d3, L2[r4] = w(e52);\n });\n const z2 = { portCount: a3, regionCount: s2, regionIncidentPorts: c3, incidentPortRegion: l3, regionWidth: h2, regionHeight: d2, regionCenterX: u2, regionCenterY: p3, regionAvailableZMask: m2, regionMetadata: I2, portAngleForRegion1: _2, portAngleForRegion2: y2, portX: b2, portY: x2, portZ: v2, portMetadata: S2 }, B2 = t2.regions.flatMap((e52, t3) =\u003e (e52.assignments ?? []).map((n3) =\u003e {\n const i4 = A2.get(n3.connectionId);\n if (i4 === undefined)\n throw new Error(`Region \"${e52.regionId}\" assignment references unknown routable connection \"${n3.connectionId}\"`);\n const r4 = o3.get(n3.regionPort1Id), s3 = o3.get(n3.regionPort2Id);\n if (r4 === undefined || s3 === undefined)\n throw new Error(`Region \"${e52.regionId}\" assignment references missing port \"${r4 === undefined ? n3.regionPort1Id : n3.regionPort2Id}\"`);\n if (!c3[t3]?.includes(r4) || !c3[t3]?.includes(s3))\n throw new Error(`Region \"${e52.regionId}\" assignment ports must both belong to the region`);\n return { routeId: i4, regionId: t3, fromPortId: r4, toPortId: s3 };\n })), F2 = Float64Array.from(t2.ports, (e52) =\u003e {\n const t3 = Number(e52.d?.tinyHypergraphPortPenalty ?? 0);\n return Number.isFinite(t3) \u0026\u0026 t3 \u003e 0 ? t3 : 0;\n }), j2 = F2.some((e52) =\u003e e52 \u003e 0), $2 = { routeCount: E3, portSectionMask: O2, routeMetadata: T2.map(({ connection: e52 }) =\u003e e52), routeStartPort: k2, routeEndPort: D2, routeNet: L2, regionNetId: g2, ...B2.length \u003e 0 \u0026\u0026 { initialAssignments: B2 }, ...j2 \u0026\u0026 { portPenalty: F2 } }, Y2 = [], X = [];\n for (const { solvedRoute: e52 } of T2) {\n if (!e52) {\n Y2.push([]), X.push([]);\n continue;\n }\n const t3 = [], i4 = [];\n for (let r4 = 1;r4 \u003c e52.path.length; r4++) {\n const s3 = e52.path[r4 - 1], a4 = e52.path[r4], c4 = s3?.portId, l4 = a4?.portId, h3 = c4 !== undefined ? o3.get(c4) : undefined, d3 = l4 !== undefined ? o3.get(l4) : undefined;\n if (h3 === undefined || d3 === undefined)\n continue;\n const u3 = typeof s3?.nextRegionId == \"string\" ? s3.nextRegionId : typeof a4?.lastRegionId == \"string\" ? a4.lastRegionId : undefined;\n t3.push([h3, d3]), i4.push(u3 !== undefined ? n2.get(u3) : undefined);\n }\n Y2.push(t3), X.push(i4);\n }\n return { topology: z2, problem: $2, solution: { solvedRoutePathSegments: Y2, solvedRoutePathRegionIds: X } };\n};\nvar kJ = (e51) =\u003e typeof e51 == \"object\" \u0026\u0026 e51 !== null;\nvar DJ = (e51) =\u003e Array.isArray(e51) ? e51.map((e52) =\u003e DJ(e52)) : kJ(e51) ? Object.fromEntries(Object.entries(e51).map(([e52, t2]) =\u003e [e52, DJ(t2)])) : e51;\nvar LJ = (e51) =\u003e kJ(e51) ? { ...e51 } : e51 === undefined ? {} : { value: e51 };\nvar zJ = (e51, t2 = 0) =\u003e typeof e51 == \"number\" \u0026\u0026 Number.isFinite(e51) ? e51 : t2;\nvar BJ = (e51) =\u003e ({ x: zJ(e51.d?.x), y: zJ(e51.d?.y) });\nvar FJ = (e51) =\u003e [e51.region1Id, e51.region2Id].sort().join(\"\\x00\");\nvar jJ = (e51, t2) =\u003e Math.hypot(e51.x - t2.x, e51.y - t2.y);\nvar $J = (e51) =\u003e {\n const t2 = Math.hypot(e51.x, e51.y);\n if (!(t2 \u003c= 0.000000001))\n return { x: e51.x / t2, y: e51.y / t2 };\n};\nvar YJ = (e51) =\u003e {\n const t2 = e51?.d?.center;\n if (kJ(t2))\n return { x: zJ(t2.x), y: zJ(t2.y) };\n const n2 = ((e52) =\u003e {\n const t3 = e52?.d?.bounds;\n if (kJ(t3) \u0026\u0026 typeof t3.minX == \"number\" \u0026\u0026 typeof t3.maxX == \"number\" \u0026\u0026 typeof t3.minY == \"number\" \u0026\u0026 typeof t3.maxY == \"number\")\n return { minX: t3.minX, maxX: t3.maxX, minY: t3.minY, maxY: t3.maxY };\n const n3 = e52?.d?.center, o3 = zJ(e52?.d?.width), i3 = zJ(e52?.d?.height);\n if (kJ(n3)) {\n const e53 = zJ(n3.x), t4 = zJ(n3.y);\n return { minX: e53 - o3 / 2, maxX: e53 + o3 / 2, minY: t4 - i3 / 2, maxY: t4 + i3 / 2 };\n }\n return { minX: 0, maxX: 0, minY: 0, maxY: 0 };\n })(e51);\n return { x: (n2.minX + n2.maxX) / 2, y: (n2.minY + n2.maxY) / 2 };\n};\nvar XJ = (e51, t2) =\u003e {\n const n2 = BJ(e51);\n let o3, i3 = Number.POSITIVE_INFINITY;\n for (const r3 of t2) {\n if (r3.portId === e51.portId)\n continue;\n const t3 = jJ(n2, BJ(r3));\n t3 \u003c= 0.000000001 || t3 \u003e= i3 || (o3 = r3, i3 = t3);\n }\n return o3;\n};\nvar HJ = (e51, t2, n2) =\u003e {\n const o3 = BJ(e51);\n if (t2) {\n const e52 = BJ(t2), n3 = $J({ x: o3.x - e52.x, y: o3.y - e52.y });\n if (n3)\n return n3;\n }\n return ((e52, t3) =\u003e {\n const n3 = YJ(t3.get(e52.region1Id)), o4 = YJ(t3.get(e52.region2Id));\n return $J({ x: -(o4.y - n3.y), y: o4.x - n3.x }) ?? { x: 1, y: 0 };\n })(e51, n2);\n};\nvar VJ = (e51, t2, n2) =\u003e {\n const o3 = `${e51}::dup${t2}`;\n if (!n2.has(o3))\n return n2.add(o3), o3;\n for (let e52 = 2;; e52++) {\n const t3 = `${o3}-${e52}`;\n if (!n2.has(t3))\n return n2.add(t3), t3;\n }\n};\nvar WJ = (e51, t2, n2) =\u003e {\n const o3 = e51.indexOf(t2);\n o3 !== -1 ? e51.splice(o3 + 1, 0, ...n2) : e51.push(...n2);\n};\nvar GJ = (e51, t2) =\u003e {\n const n2 = e51.portMetadata?.[t2];\n if (kJ(n2)) {\n if (typeof n2.serializedPortId == \"string\")\n return n2.serializedPortId;\n if (typeof n2.portId == \"string\")\n return n2.portId;\n }\n return `port-${t2}`;\n};\nvar UJ = (e51, t2) =\u003e ({ routeCount: 1, portSectionMask: e51.portSectionMask, routeMetadata: e51.routeMetadata === undefined ? undefined : [e51.routeMetadata[t2]], routeStartPort: Int32Array.from([e51.routeStartPort[t2]]), routeEndPort: Int32Array.from([e51.routeEndPort[t2]]), routeNet: Int32Array.from([e51.routeNet[t2]]), regionNetId: e51.regionNetId, portPenalty: e51.portPenalty });\nvar ZJ = (e51) =\u003e {\n const t2 = new Set;\n for (const n2 of e51.state.regionSegments)\n for (const [, e52, o3] of n2)\n t2.add(e52), t2.add(o3);\n return t2.size === 0 \u0026\u0026 e51.problem.routeCount === 1 \u0026\u0026 (t2.add(e51.problem.routeStartPort[0]), t2.add(e51.problem.routeEndPort[0])), t2;\n};\nvar qJ = class extends BaseSolver {\n constructor(e51, t2 = {}) {\n super(), this.serializedHyperGraph = e51, this.options = t2;\n }\n revisedSerializedHyperGraph;\n report = { portUseCounts: {}, duplicatedPorts: [] };\n getDuplicatePortProximity() {\n return this.options.duplicatePortProximity ?? 0.05;\n }\n getIndividualRouteSolveOptions() {\n return { RIP_THRESHOLD_RAMP_ATTEMPTS: 0, STATIC_REACHABILITY_PRECHECK: false, ...this.options.routeSolveOptions };\n }\n getPortUseCounts() {\n const { topology: e51, problem: t2 } = OJ(this.serializedHyperGraph);\n this.options.useSerializedPortPenalties === false \u0026\u0026 (t2.portPenalty = undefined);\n const n2 = new Map;\n let o3;\n for (let i3 = 0;i3 \u003c t2.routeCount; i3++) {\n const r3 = UJ(t2, i3);\n if (o3 ? o3.resetForProblem(r3) : o3 = new tJ(e51, r3, this.getIndividualRouteSolveOptions()), o3.solve(), !o3.solved || o3.failed)\n throw new Error(`Route ${i3} could not be solved independently: ${o3.error ?? \"unknown error\"}`);\n for (const t3 of ZJ(o3)) {\n const o4 = GJ(e51, t3);\n n2.set(o4, (n2.get(o4) ?? 0) + 1);\n }\n }\n return n2;\n }\n duplicateCongestedPorts(e51) {\n const t2 = this.getDuplicatePortProximity();\n if (!(t2 \u003e 0))\n throw new Error(\"duplicatePortProximity must be greater than zero\");\n const { solvedRoutes: n2, ...o3 } = this.serializedHyperGraph, i3 = this.serializedHyperGraph.regions.map((e52) =\u003e ({ ...e52, pointIds: [...e52.pointIds], d: DJ(e52.d) })), r3 = this.serializedHyperGraph.ports.map((e52) =\u003e ({ ...e52, d: DJ(e52.d) })), s2 = new Map(i3.map((e52) =\u003e [e52.regionId, e52])), a3 = new Map(r3.map((e52) =\u003e [e52.portId, e52])), c3 = ((e52) =\u003e {\n const t3 = new Map;\n for (const n3 of e52) {\n const e53 = FJ(n3), o4 = t3.get(e53);\n o4 ? o4.push(n3) : t3.set(e53, [n3]);\n }\n return t3;\n })(this.serializedHyperGraph.ports), l3 = new Set(r3.map((e52) =\u003e e52.portId)), h2 = [];\n for (const [n3, o4] of [...e51.entries()].sort(([e52], [t3]) =\u003e e52.localeCompare(t3))) {\n if (o4 \u003c= 1)\n continue;\n const e52 = a3.get(n3);\n if (!e52)\n continue;\n const i4 = o4 - 1, d2 = c3.get(FJ(e52));\n if (!d2)\n throw new Error(`No boundary ports found for \"${n3}\"`);\n const u2 = XJ(e52, d2), p3 = HJ(e52, u2, s2), m2 = BJ(e52), g2 = [];\n for (let s3 = 1;s3 \u003c= i4; s3++) {\n const a4 = VJ(n3, s3, l3), c4 = t2 * s3 / (i4 + 1), h3 = LJ(DJ(e52.d));\n h3.x = m2.x + p3.x * c4, h3.y = m2.y + p3.y * c4, h3.duplicatedFromPortId = n3, h3.duplicateIndex = s3, h3.duplicatePortUseCount = o4, h3.duplicatePortProximity = t2, h3.repairReason = \"congested-port\", r3.push({ ...e52, portId: a4, d: h3 }), g2.push(a4);\n }\n for (const t3 of [e52.region1Id, e52.region2Id]) {\n const e53 = s2.get(t3);\n e53 \u0026\u0026 WJ(e53.pointIds, n3, g2);\n }\n h2.push({ sourcePortId: n3, duplicatePortIds: g2, useCount: o4 });\n }\n return this.report = { portUseCounts: Object.fromEntries([...e51.entries()].sort()), duplicatedPorts: h2 }, { ...o3, regions: i3, ports: r3, connections: this.serializedHyperGraph.connections === undefined ? undefined : DJ(this.serializedHyperGraph.connections) };\n }\n _setup() {\n try {\n const e51 = this.getPortUseCounts();\n this.revisedSerializedHyperGraph = this.duplicateCongestedPorts(e51), this.stats = { ...this.stats, duplicateSourcePortCount: this.report.duplicatedPorts.length, duplicatedPortCount: this.report.duplicatedPorts.reduce((e52, t2) =\u003e e52 + t2.duplicatePortIds.length, 0) }, this.solved = true;\n } catch (e51) {\n this.failed = true, this.error = e51 instanceof Error ? e51.message : String(e51);\n }\n }\n _step() {\n this.failed || (this.solved = true);\n }\n getOutput() {\n if (!this.revisedSerializedHyperGraph || this.failed)\n throw new Error(\"DuplicateCongestedPortSolver does not have a repaired topology output\");\n return this.revisedSerializedHyperGraph;\n }\n};\nvar QJ = (e51, t2) =\u003e {\n Qq(e51, t2), t2 \u0026\u0026 (t2.MAX_RIPS !== undefined \u0026\u0026 (e51.MAX_RIPS = t2.MAX_RIPS), t2.MAX_RIPS_WITHOUT_MAX_REGION_COST_IMPROVEMENT !== undefined \u0026\u0026 (e51.MAX_RIPS_WITHOUT_MAX_REGION_COST_IMPROVEMENT = t2.MAX_RIPS_WITHOUT_MAX_REGION_COST_IMPROVEMENT), t2.EXTRA_RIPS_AFTER_BEATING_BASELINE_MAX_REGION_COST !== undefined \u0026\u0026 (e51.EXTRA_RIPS_AFTER_BEATING_BASELINE_MAX_REGION_COST = t2.EXTRA_RIPS_AFTER_BEATING_BASELINE_MAX_REGION_COST));\n};\nvar KJ = (e51) =\u003e e51.map((e52) =\u003e e52.map(([e53, t2, n2]) =\u003e [e53, t2, n2]));\nvar eQ = (e51) =\u003e ({ netIds: new Int32Array(e51.netIds), lesserAngles: new Int32Array(e51.lesserAngles), greaterAngles: new Int32Array(e51.greaterAngles), layerMasks: new Int32Array(e51.layerMasks), existingCrossingLayerIntersections: e51.existingCrossingLayerIntersections, existingSameLayerIntersections: e51.existingSameLayerIntersections, existingEntryExitLayerChanges: e51.existingEntryExitLayerChanges, existingRegionCost: e51.existingRegionCost, existingSegmentCount: e51.existingSegmentCount });\nvar tQ = (e51) =\u003e ({ portAssignment: new Int32Array(e51.portAssignment), regionSegments: KJ(e51.regionSegments), regionIntersectionCaches: e51.regionIntersectionCaches.map(eQ) });\nvar nQ = (e51, t2) =\u003e {\n const n2 = tQ(t2);\n e51.state.portAssignment = n2.portAssignment, e51.state.regionSegments = n2.regionSegments, e51.state.regionIntersectionCaches = n2.regionIntersectionCaches;\n};\nvar oQ = (e51) =\u003e {\n let t2 = 0, n2 = 0;\n for (let o3 = 0;o3 \u003c e51.length; o3++) {\n const i3 = e51[o3]?.existingRegionCost ?? 0;\n t2 = Math.max(t2, i3), n2 += i3;\n }\n return { maxRegionCost: t2, totalRegionCost: n2 };\n};\nvar iQ = (e51, t2) =\u003e e51.maxRegionCost !== t2.maxRegionCost ? e51.maxRegionCost - t2.maxRegionCost : e51.totalRegionCost - t2.totalRegionCost;\nvar rQ = (e51, t2, n2) =\u003e {\n const o3 = e51.incidentPortRegion[t2] ?? [], i3 = e51.incidentPortRegion[n2] ?? [], r3 = o3.find((e52) =\u003e i3.includes(e52));\n if (r3 === undefined)\n throw new Error(`Ports ${t2} and ${n2} do not share a region`);\n return r3;\n};\nvar sQ = (e51, t2, n2, o3) =\u003e {\n const i3 = n2.solvedRoutePathSegments[o3] ?? [], r3 = n2.solvedRoutePathRegionIds?.[o3] ?? [], s2 = t2.routeStartPort[o3], a3 = t2.routeEndPort[o3];\n if (i3.length === 0) {\n if (s2 === a3)\n return { orderedPortIds: [s2], orderedRegionIds: [] };\n throw new Error(`Route ${o3} does not have an existing solved path`);\n }\n const c3 = new Map;\n i3.forEach(([e52, t3], n3) =\u003e {\n const o4 = { segmentIndex: n3, fromPortId: e52, toPortId: t3, regionId: r3[n3] }, i4 = c3.get(e52) ?? [];\n i4.push(o4), c3.set(e52, i4);\n const s3 = c3.get(t3) ?? [];\n s3.push(o4), c3.set(t3, s3);\n });\n const l3 = [s2], h2 = [], d2 = new Set;\n let u2, p3 = s2;\n for (;p3 !== a3 || d2.size \u003c i3.length; ) {\n const t3 = (c3.get(p3) ?? []).filter(({ segmentIndex: e52, fromPortId: t4, toPortId: n4 }) =\u003e {\n if (d2.has(e52))\n return false;\n const o4 = t4 === p3 ? n4 : t4, r5 = o4 === a3 \u0026\u0026 d2.size + 1 === i3.length;\n return o4 !== u2 || r5;\n }), n3 = p3 === a3 \u0026\u0026 d2.size === 0 \u0026\u0026 t3.length === 2 || t3.length === 1 ? t3[0] : undefined;\n if (!n3)\n throw new Error(`Route ${o3} is not a single ordered path from ${s2} to ${a3}`);\n const r4 = n3.fromPortId === p3 ? n3.toPortId : n3.fromPortId;\n d2.add(n3.segmentIndex), h2.push(n3.regionId ?? rQ(e51, n3.fromPortId, n3.toPortId)), l3.push(r4), u2 = p3, p3 = r4;\n }\n if (d2.size !== i3.length)\n throw new Error(`Route ${o3} contains disconnected solved segments`);\n return { orderedPortIds: l3, orderedRegionIds: h2 };\n};\nvar aQ = (e51, t2, n2, o3) =\u003e {\n const i3 = new tJ(e51, t2, o3);\n return ((e52, t3) =\u003e {\n e52.state.portAssignment.fill(-1), e52.state.regionSegments = Array.from({ length: e52.topology.regionCount }, () =\u003e []), e52.state.regionIntersectionCaches = Array.from({ length: e52.topology.regionCount }, () =\u003e Zq()), e52.state.currentRouteId = undefined, e52.state.currentRouteNetId = undefined, e52.state.unroutedRoutes = [], e52.state.candidateQueue.clear(), e52.resetCandidateBestCosts(), e52.state.goalPortId = -1, e52.state.ripCount = 0, e52.state.regionCongestionCost.fill(0);\n for (let n3 = 0;n3 \u003c t3.length; n3++)\n for (const [o4, i4, r3] of t3[n3] ?? [])\n e52.state.currentRouteNetId = e52.problem.routeNet[o4], e52.state.regionSegments[n3].push([o4, i4, r3]), e52.state.portAssignment[i4] = e52.state.currentRouteNetId, e52.state.portAssignment[r3] = e52.state.currentRouteNetId, e52.appendSegmentToRegionCache(n3, i4, r3);\n e52.state.currentRouteId = undefined, e52.state.currentRouteNetId = undefined, e52.solved = true, e52.failed = false, e52.error = null;\n })(i3, n2), i3;\n};\nvar cQ = (e51, t2, n2) =\u003e {\n const o3 = new Int32Array(t2.routeStartPort), i3 = new Int32Array(t2.routeEndPort), r3 = Array.from({ length: t2.routeCount }, (e52, t3) =\u003e ({ routeId: t3, fixedSegments: [] })), s2 = [];\n for (let a3 = 0;a3 \u003c t2.routeCount; a3++) {\n const c3 = r3[a3], { orderedPortIds: l3, orderedRegionIds: h2 } = sQ(e51, t2, n2, a3), d2 = [];\n let u2;\n for (let e52 = 0;e52 \u003c l3.length; e52++) {\n const n3 = l3[e52], o4 = t2.portSectionMask[n3] === 1;\n o4 \u0026\u0026 u2 === undefined ? u2 = e52 : o4 || u2 === undefined || (d2.push({ startIndex: u2, endIndex: e52 - 1 }), u2 = undefined);\n }\n if (u2 !== undefined \u0026\u0026 d2.push({ startIndex: u2, endIndex: l3.length - 1 }), d2.length === 0) {\n for (let e52 = 1;e52 \u003c l3.length; e52++)\n c3.fixedSegments.push({ regionId: h2[e52 - 1], fromPortId: l3[e52 - 1], toPortId: l3[e52] });\n continue;\n }\n if (d2.length \u003e 1)\n throw new Error(`Route ${a3} enters the section multiple times; only one contiguous section span is currently supported`);\n const p3 = d2[0], m2 = Math.max(0, p3.startIndex - 1), g2 = Math.min(l3.length - 1, p3.endIndex + 1);\n if (g2 \u003c= m2)\n throw new Error(`Route ${a3} does not have a valid section span`);\n for (let e52 = 1;e52 \u003c= m2; e52++)\n c3.fixedSegments.push({ regionId: h2[e52 - 1], fromPortId: l3[e52 - 1], toPortId: l3[e52] });\n for (let e52 = g2 + 1;e52 \u003c l3.length; e52++)\n c3.fixedSegments.push({ regionId: h2[e52 - 1], fromPortId: l3[e52 - 1], toPortId: l3[e52] });\n c3.activeStartPortId = l3[m2], c3.activeEndPortId = l3[g2], c3.forcedStartRegionId = h2[m2], o3[a3] = c3.activeStartPortId, i3[a3] = c3.activeEndPortId, s2.push(a3);\n }\n return { sectionProblem: { routeCount: t2.routeCount, portSectionMask: new Int8Array(t2.portSectionMask), routeMetadata: t2.routeMetadata, routeStartPort: o3, routeEndPort: i3, routeNet: new Int32Array(t2.routeNet), regionNetId: new Int32Array(t2.regionNetId), portPenalty: t2.portPenalty === undefined ? undefined : new Float64Array(t2.portPenalty) }, routePlans: r3, activeRouteIds: s2 };\n};\nvar lQ = (e51, t2, n2) =\u003e cQ(e51, t2, n2).activeRouteIds;\nvar hQ = class extends tJ {\n constructor(e51, t2, n2, o3, i3, r3, s2, a3) {\n super(e51, t2, a3), this.routePlans = n2, this.activeRouteIds = o3, this.mutableRegionIds = i3, this.immutableRegionSummary = r3, this.baselineSummary = s2, QJ(this, a3), this.state.unroutedRoutes = [...o3], this.applyFixedSegments(), this.fixedSnapshot = tQ({ portAssignment: this.state.portAssignment, regionSegments: this.state.regionSegments, regionIntersectionCaches: this.state.regionIntersectionCaches });\n }\n bestSnapshot;\n fixedSnapshot;\n bestSummary;\n baselineBeatRipCount;\n previousBestMaxRegionCost = Number.POSITIVE_INFINITY;\n ripsSinceBestMaxRegionCostImprovement = 0;\n MAX_RIPS = Number.POSITIVE_INFINITY;\n MAX_RIPS_WITHOUT_MAX_REGION_COST_IMPROVEMENT = Number.POSITIVE_INFINITY;\n EXTRA_RIPS_AFTER_BEATING_BASELINE_MAX_REGION_COST = Number.POSITIVE_INFINITY;\n applyFixedSegments() {\n for (const e51 of this.routePlans)\n for (const { regionId: t2, fromPortId: n2, toPortId: o3 } of e51.fixedSegments)\n this.state.currentRouteNetId = this.problem.routeNet[e51.routeId], this.state.regionSegments[t2].push([e51.routeId, n2, o3]), this.state.portAssignment[n2] = this.state.currentRouteNetId, this.state.portAssignment[o3] = this.state.currentRouteNetId, this.appendSegmentToRegionCache(t2, n2, o3);\n this.state.currentRouteId = undefined, this.state.currentRouteNetId = undefined;\n }\n captureBestState(e51) {\n this.bestSummary \u0026\u0026 iQ(e51, this.bestSummary) \u003e= 0 || (this.bestSummary = e51, this.bestSnapshot = tQ({ portAssignment: this.state.portAssignment, regionSegments: this.state.regionSegments, regionIntersectionCaches: this.state.regionIntersectionCaches }));\n }\n restoreBestState() {\n this.bestSnapshot \u0026\u0026 (nQ(this, this.bestSnapshot), this.state.currentRouteId = undefined, this.state.currentRouteNetId = undefined, this.state.unroutedRoutes = [], this.state.candidateQueue.clear(), this.resetCandidateBestCosts(), this.state.goalPortId = -1);\n }\n getStartingNextRegionId(e51, t2) {\n const n2 = this.routePlans[e51]?.forcedStartRegionId;\n return n2 !== undefined ? n2 : super.getStartingNextRegionId(e51, t2);\n }\n resetRoutingStateForRerip() {\n if (!this.fixedSnapshot)\n return super.resetRoutingStateForRerip(), this.state.unroutedRoutes = qZ([...this.activeRouteIds], this.state.ripCount), void this.applyFixedSegments();\n nQ(this, this.fixedSnapshot), this.state.currentRouteId = undefined, this.state.currentRouteNetId = undefined, this.state.unroutedRoutes = qZ([...this.activeRouteIds], this.state.ripCount), this.state.candidateQueue.clear(), this.resetCandidateBestCosts(), this.state.goalPortId = -1;\n }\n onAllRoutesRouted() {\n const { state: e51 } = this, t2 = Math.min(this.MAX_RIPS, this.RIP_THRESHOLD_RAMP_ATTEMPTS), n2 = t2 \u003c= 0 ? 1 : Math.min(1, e51.ripCount / t2), o3 = this.RIP_THRESHOLD_START + (this.RIP_THRESHOLD_END - this.RIP_THRESHOLD_START) * n2, i3 = [], r3 = new Float64Array(this.mutableRegionIds.length);\n let s2 = 0, a3 = 0;\n for (let t3 = 0;t3 \u003c this.mutableRegionIds.length; t3++) {\n const n3 = this.mutableRegionIds[t3], c4 = e51.regionIntersectionCaches[n3]?.existingRegionCost ?? 0;\n r3[t3] = c4, s2 = Math.max(s2, c4), a3 += c4, c4 \u003e o3 \u0026\u0026 i3.push(n3);\n }\n const c3 = Math.max(this.immutableRegionSummary.maxRegionCost, s2), l3 = this.immutableRegionSummary.totalRegionCost + a3;\n this.captureBestState({ maxRegionCost: c3, totalRegionCost: l3 });\n const h2 = this.bestSummary ?? { maxRegionCost: c3, totalRegionCost: l3 };\n if (h2.maxRegionCost \u003c this.previousBestMaxRegionCost - Number.EPSILON ? (this.previousBestMaxRegionCost = h2.maxRegionCost, this.ripsSinceBestMaxRegionCostImprovement = 0) : this.ripsSinceBestMaxRegionCostImprovement += 1, this.baselineBeatRipCount === undefined \u0026\u0026 h2.maxRegionCost \u003c this.baselineSummary.maxRegionCost - Number.EPSILON \u0026\u0026 (this.baselineBeatRipCount = e51.ripCount), this.stats = { ...this.stats, activeRouteCount: this.activeRouteIds.length, currentRipThreshold: o3, hotRegionCount: i3.length, maxRegionCost: c3, totalRegionCost: l3, bestMaxRegionCost: h2.maxRegionCost, bestTotalRegionCost: h2.totalRegionCost, ripCount: e51.ripCount }, i3.length === 0 || e51.ripCount \u003e= t2 || this.ripsSinceBestMaxRegionCostImprovement \u003e= this.MAX_RIPS_WITHOUT_MAX_REGION_COST_IMPROVEMENT || this.baselineBeatRipCount !== undefined \u0026\u0026 e51.ripCount - this.baselineBeatRipCount \u003e= this.EXTRA_RIPS_AFTER_BEATING_BASELINE_MAX_REGION_COST)\n return this.restoreBestState(), void (this.solved = true);\n for (let t3 = 0;t3 \u003c this.mutableRegionIds.length; t3++) {\n const n3 = this.mutableRegionIds[t3];\n e51.regionCongestionCost[n3] += r3[t3] * this.RIP_CONGESTION_REGION_COST_FACTOR;\n }\n e51.ripCount += 1, this.resetRoutingStateForRerip(), this.stats = { ...this.stats, ripCount: e51.ripCount, reripRegionCount: i3.length };\n }\n onOutOfCandidates() {\n const { state: e51 } = this;\n for (const t2 of this.mutableRegionIds) {\n const n2 = e51.regionIntersectionCaches[t2]?.existingRegionCost ?? 0;\n e51.regionCongestionCost[t2] += n2 * this.RIP_CONGESTION_REGION_COST_FACTOR;\n }\n e51.ripCount += 1, this.resetRoutingStateForRerip(), this.stats = { ...this.stats, ripCount: e51.ripCount, reripReason: \"out_of_candidates\" };\n }\n tryFinalAcceptance() {\n if (this.bestSnapshot)\n return this.restoreBestState(), void (this.solved = true);\n this.fixedSnapshot \u0026\u0026 nQ(this, this.fixedSnapshot), this.state.currentRouteId = undefined, this.state.currentRouteNetId = undefined, this.state.unroutedRoutes = [...this.activeRouteIds], this.state.candidateQueue.clear(), this.resetCandidateBestCosts(), this.state.goalPortId = -1, this.stats = { ...this.stats, acceptedFixedSectionStateOnTimeout: true }, this.solved = true;\n }\n visualize() {\n return Uq(this, { highlightSectionMask: true, showInitialRouteHints: false, showOnlySectionPortsOnIdle: true });\n }\n};\nvar dQ = class extends BaseSolver {\n constructor(e51, t2, n2, o3) {\n super(), this.topology = e51, this.problem = t2, this.initialSolution = n2, QJ(this, o3), this.baselineSolver = ((e52, t3, n3, o4) =\u003e {\n const i3 = Array.from({ length: e52.regionCount }, () =\u003e []);\n for (let o5 = 0;o5 \u003c t3.routeCount; o5++) {\n const { orderedPortIds: r3, orderedRegionIds: s2 } = sQ(e52, t3, n3, o5);\n for (let e53 = 1;e53 \u003c r3.length; e53++) {\n const t4 = r3[e53 - 1], n4 = r3[e53];\n i3[s2[e53 - 1]].push([o5, t4, n4]);\n }\n }\n return aQ(e52, t3, i3, o4);\n })(e51, t2, n2, Kq(this)), this.baselineSummary = oQ(this.baselineSolver.state.regionIntersectionCaches), this.sectionRegionIds = ((e52, t3) =\u003e {\n const n3 = new Set;\n for (let o4 = 0;o4 \u003c t3.portSectionMask.length; o4++)\n if (t3.portSectionMask[o4] === 1)\n for (const t4 of e52.incidentPortRegion[o4] ?? [])\n n3.add(t4);\n return [...n3];\n })(e51, t2), this.sectionBaselineSummary = ((e52, t3) =\u003e {\n let n3 = 0, o4 = 0;\n for (const i3 of t3) {\n const t4 = e52[i3]?.existingRegionCost ?? 0;\n n3 = Math.max(n3, t4), o4 += t4;\n }\n return { maxRegionCost: n3, totalRegionCost: o4 };\n })(this.baselineSolver.state.regionIntersectionCaches, this.sectionRegionIds), this.outsideSectionBaselineSummary = ((e52, t3) =\u003e {\n const n3 = new Set(t3);\n let o4 = 0, i3 = 0;\n for (let t4 = 0;t4 \u003c e52.length; t4++) {\n if (n3.has(t4))\n continue;\n const r3 = e52[t4]?.existingRegionCost ?? 0;\n o4 = Math.max(o4, r3), i3 += r3;\n }\n return { maxRegionCost: o4, totalRegionCost: i3 };\n })(this.baselineSolver.state.regionIntersectionCaches, this.sectionRegionIds), this.applySectionRipPolicy();\n }\n baselineSolver;\n baselineSummary;\n sectionBaselineSummary;\n outsideSectionBaselineSummary;\n sectionRegionIds;\n optimizedSolver;\n sectionSolver;\n activeRouteIds = [];\n DISTANCE_TO_COST = 0.05;\n minViaPadDiameter = jZ;\n VERBOSE = false;\n RIP_THRESHOLD_START = 0.05;\n RIP_THRESHOLD_END = 0.8;\n RIP_THRESHOLD_RAMP_ATTEMPTS = 50;\n MAX_RIPS = Number.POSITIVE_INFINITY;\n MAX_RIPS_WITHOUT_MAX_REGION_COST_IMPROVEMENT = 10;\n EXTRA_RIPS_AFTER_BEATING_BASELINE_MAX_REGION_COST = 10;\n RIP_CONGESTION_REGION_COST_FACTOR = 0.1;\n MAX_ITERATIONS = 1e6;\n STATIC_REACHABILITY_PRECHECK = false;\n STATIC_REACHABILITY_PRECHECK_MAX_HOPS = 16;\n ACCEPT_BEST_SOLUTION_ON_TIMEOUT = true;\n GREEDY_FINAL_ROUTE_ITERS = 4;\n applySectionRipPolicy() {\n this.RIP_THRESHOLD_START = 0.05, this.RIP_THRESHOLD_END = Math.max(this.RIP_THRESHOLD_START, this.sectionBaselineSummary.maxRegionCost), this.MAX_RIPS = Math.min(this.MAX_RIPS, 20);\n }\n _setup() {\n this.applySectionRipPolicy();\n const { sectionProblem: e51, routePlans: t2, activeRouteIds: n2 } = cQ(this.topology, this.problem, this.initialSolution);\n if (this.activeRouteIds = n2, n2.length === 0)\n return this.optimizedSolver = this.baselineSolver, this.stats = { ...this.stats, activeRouteCount: 0, initialMaxRegionCost: this.baselineSummary.maxRegionCost, finalMaxRegionCost: this.baselineSummary.maxRegionCost, optimized: false }, void (this.solved = true);\n var o3;\n this.sectionSolver = new hQ(this.topology, e51, t2, n2, this.sectionRegionIds, this.outsideSectionBaselineSummary, this.baselineSummary, { ...Kq(o3 = this), MAX_RIPS: o3.MAX_RIPS, MAX_RIPS_WITHOUT_MAX_REGION_COST_IMPROVEMENT: o3.MAX_RIPS_WITHOUT_MAX_REGION_COST_IMPROVEMENT, EXTRA_RIPS_AFTER_BEATING_BASELINE_MAX_REGION_COST: o3.EXTRA_RIPS_AFTER_BEATING_BASELINE_MAX_REGION_COST }), this.activeSubSolver = this.sectionSolver, this.stats = { ...this.stats, sectionBaselineMaxRegionCost: this.sectionBaselineSummary.maxRegionCost, sectionBaselineTotalRegionCost: this.sectionBaselineSummary.totalRegionCost, effectiveRipThresholdStart: this.RIP_THRESHOLD_START, effectiveRipThresholdEnd: this.RIP_THRESHOLD_END, effectiveMaxRips: this.MAX_RIPS };\n }\n _step() {\n if (!this.sectionSolver)\n return void (this.solved = true);\n if (this.sectionSolver.step(), this.stats = { ...this.stats, ...this.sectionSolver.stats, activeRouteCount: this.activeRouteIds.length }, this.sectionSolver.failed)\n return this.optimizedSolver = this.baselineSolver, this.stats = { ...this.stats, initialMaxRegionCost: this.baselineSummary.maxRegionCost, initialTotalRegionCost: this.baselineSummary.totalRegionCost, finalMaxRegionCost: this.baselineSummary.maxRegionCost, finalTotalRegionCost: this.baselineSummary.totalRegionCost, optimized: false, sectionSearchFailedFallbackToBaseline: true, sectionSearchError: this.sectionSolver.error }, void (this.solved = true);\n if (!this.sectionSolver.solved)\n return;\n const e51 = aQ(this.topology, this.problem, KJ(this.sectionSolver.state.regionSegments), Kq(this)), t2 = oQ(e51.state.regionIntersectionCaches), n2 = iQ(t2, this.baselineSummary) \u003c 0;\n this.optimizedSolver = n2 ? e51 : this.baselineSolver;\n const o3 = n2 ? t2 : this.baselineSummary;\n this.stats = { ...this.stats, initialMaxRegionCost: this.baselineSummary.maxRegionCost, initialTotalRegionCost: this.baselineSummary.totalRegionCost, candidateMaxRegionCost: t2.maxRegionCost, candidateTotalRegionCost: t2.totalRegionCost, finalMaxRegionCost: o3.maxRegionCost, finalTotalRegionCost: o3.totalRegionCost, optimized: n2 }, this.solved = true;\n }\n tryFinalAcceptance() {\n this.optimizedSolver = this.baselineSolver, this.stats = { ...this.stats, initialMaxRegionCost: this.baselineSummary.maxRegionCost, initialTotalRegionCost: this.baselineSummary.totalRegionCost, finalMaxRegionCost: this.baselineSummary.maxRegionCost, finalTotalRegionCost: this.baselineSummary.totalRegionCost, optimized: false, sectionSolverTimeoutFallbackToBaseline: true }, this.solved = true, this.failed = false, this.error = null;\n }\n getSolvedSolver() {\n if (!this.solved || this.failed || !this.optimizedSolver)\n throw new Error(\"TinyHyperGraphSectionSolver does not have a solved output yet\");\n return this.optimizedSolver;\n }\n visualize() {\n return this.optimizedSolver ? Uq(this.optimizedSolver, { highlightSectionMask: true }) : this.sectionSolver ? this.sectionSolver.visualize() : Uq(this.baselineSolver, { highlightSectionMask: true, showInitialRouteHints: false, showOnlySectionPortsOnIdle: true });\n }\n getOutput() {\n return this.getSolvedSolver().getOutput();\n }\n};\nvar pQ = [\"self-touch\", \"onehop-all\", \"onehop-touch\", \"twohop-all\", \"twohop-touch\"];\nvar mQ = { \"self-all\": 0, \"self-touch\": 0, \"onehop-all\": 1, \"onehop-touch\": 1, \"twohop-all\": 2, \"twohop-touch\": 2, \"threehop-all\": 3, \"threehop-touch\": 3, \"fourhop-all\": 4, \"fourhop-touch\": 4 };\nvar gQ = (e51, t2) =\u003e {\n const n2 = new Set(t2);\n for (const o3 of t2)\n for (const t3 of e51.regionIncidentPorts[o3] ?? [])\n for (const o4 of e51.incidentPortRegion[t3] ?? [])\n n2.add(o4);\n return [...n2];\n};\nvar fQ = (e51, t2, n2) =\u003e {\n let o3 = [...new Set(t2)];\n for (let t3 = 0;t3 \u003c n2; t3 += 1)\n o3 = gQ(e51, o3);\n return o3;\n};\nvar _Q = (e51, t2, n2) =\u003e t2.flatMap((t3) =\u003e n2.map((n3) =\u003e ((e52, t4, n4) =\u003e ({ label: `hot-${t4}-${n4}`, family: n4, regionIds: fQ(e52, [t4], mQ[n4]), portSelectionRule: n4.endsWith(\"-all\") ? \"all-incident-regions-selected\" : \"touches-selected-region\" }))(e51, t3, n3)));\nvar yQ = { RIP_THRESHOLD_RAMP_ATTEMPTS: 5 };\nvar bQ = { DISTANCE_TO_COST: 0.05, RIP_THRESHOLD_RAMP_ATTEMPTS: 16, RIP_CONGESTION_REGION_COST_FACTOR: 0.1, MAX_ITERATIONS: 50000, MAX_RIPS_WITHOUT_MAX_REGION_COST_IMPROVEMENT: 6, EXTRA_RIPS_AFTER_BEATING_BASELINE_MAX_REGION_COST: Number.POSITIVE_INFINITY };\nvar xQ = (e51) =\u003e e51.state.regionIntersectionCaches.reduce((e52, t2) =\u003e Math.max(e52, t2.existingRegionCost), 0);\nvar vQ = (e51, t2) =\u003e {\n const n2 = OJ(e51), o3 = new dQ(n2.topology, n2.problem, n2.solution, t2);\n return xQ(o3.baselineSolver);\n};\nvar IQ = (e51, t2, n2) =\u003e {\n const o3 = new Set(t2);\n return Int8Array.from({ length: e51.portCount }, (t3, i3) =\u003e {\n const r3 = e51.incidentPortRegion[i3] ?? [];\n return n2 === \"touches-selected-region\" ? r3.some((e52) =\u003e o3.has(e52)) ? 1 : 0 : r3.length \u003e 0 \u0026\u0026 r3.every((e52) =\u003e o3.has(e52)) ? 1 : 0;\n });\n};\nvar SQ = (e51, t2) =\u003e ({ routeCount: e51.routeCount, portSectionMask: t2, routeMetadata: e51.routeMetadata, routeStartPort: new Int32Array(e51.routeStartPort), routeEndPort: new Int32Array(e51.routeEndPort), routeNet: new Int32Array(e51.routeNet), regionNetId: new Int32Array(e51.regionNetId), portPenalty: e51.portPenalty === undefined ? undefined : new Float64Array(e51.portPenalty) });\nvar CQ = (e51, t2, n2, o3, i3, r3) =\u003e {\n const s2 = performance.now(), a3 = performance.now(), c3 = new dQ(t2, n2, o3, r3), l3 = xQ(c3.baselineSolver), h2 = performance.now() - a3;\n let d2, u2, p3 = l3, m2 = new Int8Array(t2.portCount), g2 = 0, f2 = 0, _2 = 0, y2 = 0, b2 = 0, x2 = 0, v2 = 0;\n const I2 = new Set, S2 = i3?.maxHotRegions ?? r3.MAX_HOT_REGIONS ?? 2;\n for (const s3 of ((e52, t3, n3, o4) =\u003e {\n const i4 = e52.state.regionIntersectionCaches.map((e53, t4) =\u003e ({ regionId: t4, regionCost: e53.existingRegionCost })).filter(({ regionCost: e53 }) =\u003e e53 \u003e 0).sort((e53, t4) =\u003e t4.regionCost - e53.regionCost).slice(0, n3).map(({ regionId: e53 }) =\u003e e53);\n return _Q(t3, i4, o4);\n })(e51, t2, S2, i3?.candidateFamilies ?? [...pQ])) {\n const e52 = SQ(n2, IQ(t2, s3.regionIds, s3.portSelectionRule));\n g2 += 1;\n const i4 = e52.portSectionMask.join(\",\");\n if (I2.has(i4))\n _2 += 1;\n else {\n I2.add(i4);\n try {\n const n3 = performance.now(), i5 = lQ(t2, e52, o3);\n if (y2 += performance.now() - n3, i5.length === 0)\n continue;\n f2 += 1;\n const a4 = performance.now(), c4 = new dQ(t2, e52, o3, r3);\n b2 += performance.now() - a4;\n const l4 = performance.now();\n if (c4.solve(), x2 += performance.now() - l4, c4.failed || !c4.solved)\n continue;\n if (Number(c4.stats.finalMaxRegionCost ?? xQ(c4.getSolvedSolver())) \u003c p3 - 0.000000001) {\n const t3 = performance.now(), n4 = vQ(c4.getOutput(), r3);\n v2 += performance.now() - t3, n4 \u003c p3 - 0.000000001 \u0026\u0026 (p3 = n4, m2 = new Int8Array(e52.portSectionMask), d2 = s3.label, u2 = s3.family);\n }\n } catch {}\n }\n }\n return { portSectionMask: m2, baselineMaxRegionCost: l3, finalMaxRegionCost: p3, generatedCandidateCount: g2, candidateCount: f2, duplicateCandidateCount: _2, totalMs: performance.now() - s2, baselineEvaluationMs: h2, candidateEligibilityMs: y2, candidateInitMs: b2, candidateSolveMs: x2, candidateReplayScoreMs: v2, winningCandidateLabel: d2, winningCandidateFamily: u2 };\n};\nvar PQ = class extends BasePipelineSolver {\n initialVisualizationSolver;\n selectedSectionMask;\n selectedSectionCandidateLabel;\n selectedSectionCandidateFamily;\n constructor(e51) {\n super(e51), this.MAX_ITERATIONS = 200000;\n }\n loadHyperGraph(e51) {\n return OJ(e51);\n }\n getSolveGraphOptions() {\n return { ...yQ, ...this.inputProblem.minViaPadDiameter === undefined ? {} : { minViaPadDiameter: this.inputProblem.minViaPadDiameter }, ...this.inputProblem.solveGraphOptions };\n }\n getSectionSolverOptions() {\n return { ...bQ, ...this.inputProblem.minViaPadDiameter === undefined ? {} : { minViaPadDiameter: this.inputProblem.minViaPadDiameter }, ...this.inputProblem.sectionSolverOptions };\n }\n pipelineDef = [{ solverName: \"solveGraph\", solverClass: tJ, getConstructorParams: (e51) =\u003e {\n const { topology: t2, problem: n2 } = e51.loadHyperGraph(e51.inputProblem.serializedHyperGraph);\n return [t2, n2, e51.getSolveGraphOptions()];\n } }, { solverName: \"optimizeSection\", solverClass: dQ, getConstructorParams: (e51) =\u003e e51.getSectionStageParams() }];\n getSectionStageParams() {\n const e51 = this.getStageOutput(\"solveGraph\");\n if (!e51)\n throw new Error(\"solveGraph did not produce a solved serialized hypergraph\");\n const t2 = this.getSolver(\"solveGraph\");\n if (!t2)\n throw new Error(\"solveGraph solver is unavailable\");\n const n2 = this.getSectionSolverOptions(), { topology: o3, problem: i3, solution: r3 } = this.loadHyperGraph(e51), s2 = this.inputProblem.createSectionMask ? this.inputProblem.createSectionMask({ serializedHyperGraph: this.inputProblem.serializedHyperGraph, solvedSerializedHyperGraph: e51, solvedSolver: t2, topology: o3, problem: i3, solution: r3 }) : (() =\u003e {\n const e52 = CQ(t2, o3, i3, r3, this.inputProblem.sectionSearchConfig, n2);\n return this.selectedSectionCandidateLabel = e52.winningCandidateLabel, this.selectedSectionCandidateFamily = e52.winningCandidateFamily, this.stats = { ...this.stats, sectionSearchGeneratedCandidateCount: e52.generatedCandidateCount, sectionSearchCandidateCount: e52.candidateCount, sectionSearchDuplicateCandidateCount: e52.duplicateCandidateCount, sectionSearchBaselineMaxRegionCost: e52.baselineMaxRegionCost, sectionSearchFinalMaxRegionCost: e52.finalMaxRegionCost, sectionSearchDelta: e52.baselineMaxRegionCost - e52.finalMaxRegionCost, selectedSectionCandidateLabel: e52.winningCandidateLabel ?? null, selectedSectionCandidateFamily: e52.winningCandidateFamily ?? null, sectionSearchMs: e52.totalMs, sectionSearchBaselineEvaluationMs: e52.baselineEvaluationMs, sectionSearchCandidateEligibilityMs: e52.candidateEligibilityMs, sectionSearchCandidateInitMs: e52.candidateInitMs, sectionSearchCandidateSolveMs: e52.candidateSolveMs, sectionSearchCandidateReplayScoreMs: e52.candidateReplayScoreMs }, e52.portSectionMask;\n })();\n return this.selectedSectionMask = new Int8Array(s2), i3.portSectionMask = new Int8Array(s2), this.stats = { ...this.stats, sectionMaskPortCount: [...s2].filter((e52) =\u003e e52 === 1).length }, [o3, i3, r3, n2];\n }\n getInitialVisualizationSolver() {\n if (!this.initialVisualizationSolver) {\n const { topology: e51, problem: t2 } = this.loadHyperGraph(this.inputProblem.serializedHyperGraph);\n this.initialVisualizationSolver = new tJ(e51, t2, this.getSolveGraphOptions());\n }\n return this.initialVisualizationSolver;\n }\n initialVisualize() {\n return this.getInitialVisualizationSolver().visualize();\n }\n visualize() {\n return this.iterations === 0 ? this.initialVisualize() ?? super.visualize() : super.visualize();\n }\n getOutput() {\n return this.getStageOutput(\"optimizeSection\") ?? this.getStageOutput(\"solveGraph\") ?? null;\n }\n tryFinalAcceptance() {\n this.getStageOutput(\"solveGraph\") \u0026\u0026 (this.stats = { ...this.stats, acceptedSolveGraphOutputOnSectionPipelineTimeout: true }, this.activeSubSolver = undefined, this.solved = true, this.failed = false, this.error = null);\n }\n};\nnew Int32Array(0);\nvar wQ = (e51) =\u003e {\n if (typeof e51 != \"object\" || e51 === null)\n return false;\n const t2 = e51, n2 = t2.preloadedTraceSection;\n return typeof t2.connectionId == \"string\" \u0026\u0026 typeof n2?.traceId == \"string\" \u0026\u0026 typeof n2.startRoutePosition == \"number\" \u0026\u0026 typeof n2.endRoutePosition == \"number\" \u0026\u0026 typeof n2.startPoint?.x == \"number\" \u0026\u0026 typeof n2.startPoint.y == \"number\" \u0026\u0026 typeof n2.startPoint.z == \"number\" \u0026\u0026 typeof n2.endPoint?.x == \"number\" \u0026\u0026 typeof n2.endPoint.y == \"number\" \u0026\u0026 typeof n2.endPoint.z == \"number\";\n};\nvar NQ = (e51, t2) =\u003e `__tscircuit_preloaded_trace__:${JSON.stringify([e51, t2])}`;\nvar RQ = (e51) =\u003e [e51.region1Id, e51.region2Id];\nvar TQ = (e51, t2) =\u003e {\n const n2 = new Set(RQ(t2));\n return RQ(e51).filter((e52) =\u003e n2.has(e52));\n};\nvar EQ = (e51, t2, n2) =\u003e {\n const o3 = e51[t2], i3 = e51[t2 + 1], r3 = TQ(o3.port, i3.port);\n if (r3.length === 0)\n return;\n if (r3.length === 1)\n return r3[0];\n const s2 = e51[t2 + 2];\n if (s2) {\n const e52 = new Set(TQ(i3.port, s2.port)), t3 = r3.find((t4) =\u003e e52.has(t4));\n if (t3)\n return t3;\n }\n return n2 \u0026\u0026 r3.includes(n2) ? n2 : [...r3].sort()[0];\n};\nvar AQ = (e51, t2) =\u003e RQ(e51).find((e52) =\u003e e52 !== t2) ?? t2;\nvar OQ = (e51) =\u003e {\n const t2 = new Set((e51.connections ?? []).filter(wQ).map((e52) =\u003e e52.connectionId)), n2 = e51.ports.filter((e52) =\u003e (e52.d?._preloadedTracePortAssignments?.length ?? 0) \u003e 0).length, o3 = e51.regions.reduce((e52, n3) =\u003e e52 + (n3.assignments ?? []).filter((e53) =\u003e t2.has(e53.connectionId)).length, 0);\n return { preloadedTraceCount: t2.size, preloadedPortCount: n2, preloadedAssignmentCount: o3 };\n};\nvar kQ = (e51) =\u003e typeof e51 == \"object\" \u0026\u0026 e51 !== null ? e51 : {};\nvar DQ = (e51) =\u003e typeof e51 == \"object\" \u0026\u0026 e51 !== null ? e51 : {};\nvar LQ = 0.000001;\nvar zQ = { DISTANCE_TO_COST: 0.05, RIP_THRESHOLD_START: 0.05, RIP_THRESHOLD_END: 0.8, RIP_CONGESTION_REGION_COST_FACTOR: 0.1, ACCEPT_BEST_SOLUTION_ON_TIMEOUT: true, GREEDY_FINAL_ROUTE_ITERS: 4, PARTIAL_RIP_MIN_ROUTE_COUNT: 100, PARTIAL_RIP_MAX_ROUTE_COUNT: 350, PARTIAL_RIP_MAX_ATTEMPTS: 7, PARTIAL_RIP_WARMUP_FULL_RIP_ATTEMPTS: 1, PARTIAL_RIP_COMPLEXITY_SELECTION_MIN_ROUTE_COUNT: 100, PARTIAL_RIP_TARGET_MAX_COST_IMPROVEMENT_RATIO: 0.02, PARTIAL_RIP_MAX_REGION_COST_GROWTH_RATIO: 0.05, PARTIAL_RIP_MAX_TOTAL_COST_GROWTH_RATIO: 0.1 };\nvar BQ = { DISTANCE_TO_COST: 0.05, RIP_THRESHOLD_START: 0.05, RIP_THRESHOLD_END: 0.8, RIP_CONGESTION_REGION_COST_FACTOR: 0.1, ACCEPT_BEST_SOLUTION_ON_TIMEOUT: true, GREEDY_FINAL_ROUTE_ITERS: 4, MAX_RIPS_WITHOUT_MAX_REGION_COST_IMPROVEMENT: 6, EXTRA_RIPS_AFTER_BEATING_BASELINE_MAX_REGION_COST: Number.POSITIVE_INFINITY };\nvar FQ = (e51) =\u003e Math.max(e51, 0.01);\nvar jQ = (e51) =\u003e Number.isFinite(e51) ? { minViaPadDiameter: e51 } : {};\nvar $Q = ({ effort: e51, portCount: t2, minViaPadDiameter: n2 }) =\u003e {\n const o3 = FQ(e51), i3 = Math.max(1, Math.floor(t2 / 125000));\n return { ...zQ, ...jQ(n2), OWNED_REGIONAL_HOP_FRONTIER: true, USE_SPARSE_CANDIDATE_STORAGE: false, RIP_THRESHOLD_RAMP_ATTEMPTS: Math.ceil(10 * o3), MAX_ITERATIONS: Math.ceil(2000000 * o3 * i3) };\n};\nvar YQ = (e51, t2) =\u003e {\n const n2 = FQ(e51);\n return { ...BQ, ...jQ(t2), USE_SPARSE_CANDIDATE_STORAGE: false, RIP_THRESHOLD_RAMP_ATTEMPTS: Math.ceil(16 * n2), MAX_ITERATIONS: Math.ceil(1e6 * n2) };\n};\nvar XQ = (e51) =\u003e (e51.solveGraphOptions?.MAX_ITERATIONS ?? 1e6) + (e51.sectionSolverOptions?.MAX_ITERATIONS ?? 1e6) + 1e6;\nvar HQ = (e51) =\u003e e51.mutuallyConnectedNetworkId;\nvar VQ = (e51, t2) =\u003e e51.simpleRouteConnection?.pointsToConnect[t2];\nvar WQ = (e51) =\u003e {\n const t2 = VQ(e51.routeMetadata, e51.endpointIndex);\n if (!t2)\n return e51.fallbackZ;\n const n2 = So(t2).map((t3) =\u003e mo(t3, e51.layerCount));\n return e51.regionAvailableZ.find((e52) =\u003e n2.includes(e52)) ?? e51.fallbackZ;\n};\nvar GQ = (e51, t2) =\u003e {\n const n2 = e51.d, o3 = n2.bounds;\n return { capacityMeshNodeId: e51.d.capacityMeshNodeId, center: { x: e51.d.center.x, y: e51.d.center.y }, width: e51.d.width, height: e51.d.height, availableZ: [...e51.d.availableZ], ...o3 ? { bounds: { minX: o3.minX, maxX: o3.maxX, minY: o3.minY, maxY: o3.maxY } } : {}, _containsObstacle: e51.d._containsObstacle, _containsTarget: e51.d._containsTarget, _offBoardConnectionId: e51.d._offBoardConnectionId, _offBoardConnectedCapacityMeshNodeIds: e51.d._offBoardConnectedCapacityMeshNodeIds === undefined ? undefined : [...e51.d._offBoardConnectedCapacityMeshNodeIds], _qfpRegionType: n2._qfpRegionType, _isNarrowQfpPadGap: n2._isNarrowQfpPadGap, ...t2 !== undefined ? { netId: t2 } : {} };\n};\nvar UQ = (e51) =\u003e {\n const t2 = e51.d;\n return { portId: e51.d.portId, x: e51.d.x, y: e51.d.y, z: e51.d.z, prevPortPointId: t2.prevPortPointId, nextPortPointId: t2.nextPortPointId, distToCentermostPortOnZ: e51.d.distToCentermostPortOnZ, tinyHypergraphPortPenalty: e51.d.tinyHypergraphPortPenalty, cramped: e51.d.cramped, _preloadedFixedNetIds: e51.d._preloadedFixedNetIds, _preloadedTracePortAssignments: e51.d._preloadedTracePortAssignments };\n};\nvar ZQ = (e51) =\u003e {\n const t2 = function() {\n const e52 = new Map;\n return (t3) =\u003e {\n const n3 = t3.mutuallyConnectedNetworkId;\n let o4 = e52.get(n3);\n return o4 === undefined \u0026\u0026 (o4 = e52.size, e52.set(n3, o4)), o4;\n };\n }(), n2 = function(e52) {\n const t3 = new Map, n3 = new Set, o4 = new Map;\n for (const i5 of e52.params.connections) {\n const r4 = i5.mutuallyConnectedNetworkId, s3 = e52.getNetIndex({ connectionId: i5.connectionId, mutuallyConnectedNetworkId: r4 });\n for (const e53 of [i5.connectionId, r4])\n o4.set(e53, s3);\n for (const o5 of i5.simpleRouteConnection.pointsToConnect) {\n const i6 = GG({ point: o5, layerCount: e52.params.layerCount });\n for (const r5 of e52.params.graph.regions) {\n if (!UG({ point: o5, region: r5, layerCount: e52.params.layerCount, pointZLayers: i6 }))\n continue;\n if (o5.pcb_port_id === undefined \u0026\u0026 r5.d._containsTarget !== true) {\n n3.add(r5.regionId);\n continue;\n }\n let a4 = t3.get(r5.regionId);\n a4 || (a4 = new Set, t3.set(r5.regionId, a4)), a4.add(s3);\n }\n }\n }\n for (const n4 of e52.params.graph.regions)\n for (const e53 of n4.d._connectedTo ?? []) {\n const i5 = o4.get(e53);\n if (i5 === undefined)\n continue;\n let r4 = t3.get(n4.regionId);\n r4 || (r4 = new Set, t3.set(n4.regionId, r4)), r4.add(i5);\n }\n const i4 = new Map;\n for (const e53 of n3)\n i4.set(e53, -1);\n for (const [e53, n4] of t3)\n n4.size === 1 \u0026\u0026 i4.set(e53, [...n4][0]);\n return i4;\n }({ params: e51, getNetIndex: t2 }), o3 = e51.graph.regions.map((e52) =\u003e ({ regionId: e52.regionId, pointIds: e52.ports.map((e53) =\u003e e53.d.portId), d: GQ(e52, n2.get(e52.regionId)) })), i3 = new Map;\n for (const e52 of o3)\n i3.has(e52.regionId) || i3.set(e52.regionId, e52);\n const r3 = e51.graph.ports.map((e52) =\u003e ({ portId: e52.d.portId, region1Id: e52.region1.regionId, region2Id: e52.region2.regionId, d: UQ(e52) })), s2 = e51.connections.map((e52) =\u003e ({ connectionId: e52.connectionId, mutuallyConnectedNetworkId: e52.mutuallyConnectedNetworkId, startRegionId: e52.startRegion.regionId, endRegionId: e52.endRegion.regionId, simpleRouteConnection: e52.simpleRouteConnection })), a3 = [];\n for (const n3 of e51.connections) {\n const s3 = { connectionId: n3.connectionId, mutuallyConnectedNetworkId: n3.mutuallyConnectedNetworkId, simpleRouteConnection: n3.simpleRouteConnection }, c4 = t2(s3), l3 = VQ(s3, 0), h2 = VQ(s3, 1), d2 = n3.startRegion.d.availableZ[0] ?? 0, u2 = n3.endRegion.d.availableZ[0] ?? 0, p3 = WQ({ routeMetadata: s3, endpointIndex: 0, fallbackZ: d2, regionAvailableZ: n3.startRegion.d.availableZ, layerCount: e51.layerCount }), m2 = WQ({ routeMetadata: s3, endpointIndex: 1, fallbackZ: u2, regionAvailableZ: n3.endRegion.d.availableZ, layerCount: e51.layerCount }), g2 = `tiny-terminal:start-region:${n3.connectionId}`, f2 = `tiny-terminal:end-region:${n3.connectionId}`, _2 = `tiny-terminal:start-port:${n3.connectionId}`, y2 = `tiny-terminal:end-port:${n3.connectionId}`;\n o3.push({ regionId: g2, pointIds: [_2], d: { capacityMeshNodeId: g2, center: { x: l3?.x ?? n3.startRegion.d.center.x, y: l3?.y ?? n3.startRegion.d.center.y }, width: LQ, height: LQ, availableZ: [p3], _containsTarget: true, _tinyTerminal: true, _tinyTerminalNetId: n3.mutuallyConnectedNetworkId, netId: c4 } }), o3.push({ regionId: f2, pointIds: [y2], d: { capacityMeshNodeId: f2, center: { x: h2?.x ?? n3.endRegion.d.center.x, y: h2?.y ?? n3.endRegion.d.center.y }, width: LQ, height: LQ, availableZ: [m2], _containsTarget: true, _tinyTerminal: true, _tinyTerminalNetId: n3.mutuallyConnectedNetworkId, netId: c4 } }), r3.push({ portId: _2, region1Id: n3.startRegion.regionId, region2Id: g2, d: { portId: _2, x: l3?.x ?? n3.startRegion.d.center.x, y: l3?.y ?? n3.startRegion.d.center.y, z: p3, distToCentermostPortOnZ: 0, _tinyTerminal: true, ...e51.preserveTerminalPcbPortIds \u0026\u0026 l3?.pcb_port_id ? { pcb_port_id: l3.pcb_port_id } : {} } }), r3.push({ portId: y2, region1Id: n3.endRegion.regionId, region2Id: f2, d: { portId: y2, x: h2?.x ?? n3.endRegion.d.center.x, y: h2?.y ?? n3.endRegion.d.center.y, z: m2, distToCentermostPortOnZ: 0, _tinyTerminal: true, ...e51.preserveTerminalPcbPortIds \u0026\u0026 h2?.pcb_port_id ? { pcb_port_id: h2.pcb_port_id } : {} } });\n const b2 = i3.get(n3.startRegion.regionId), x2 = i3.get(n3.endRegion.regionId);\n b2?.pointIds.push(_2), x2?.pointIds.push(y2), a3.push({ connection: { connectionId: n3.connectionId }, path: [{ portId: _2 }, { portId: y2 }] });\n }\n const c3 = { regions: o3, ports: r3, connections: s2, solvedRoutes: a3 };\n return ((e52) =\u003e {\n const t3 = new Map, n3 = new Map, o4 = new Set((e52.connections ?? []).flatMap((e53) =\u003e [e53.startRegionId, e53.endRegionId])), i4 = new Set(e52.regions.filter((e53) =\u003e {\n const t4 = typeof e53.d?.netId == \"number\" ? e53.d.netId : typeof e53.d?.NetId == \"number\" ? e53.d.NetId : undefined;\n return e53.d?._containsObstacle === true \u0026\u0026 (t4 === undefined || t4 === -1) \u0026\u0026 !o4.has(e53.regionId);\n }).map((e53) =\u003e e53.regionId));\n let r4 = 0;\n for (const o5 of e52.ports) {\n const e53 = o5.d, s4 = e53?._preloadedTracePortAssignments ?? [];\n if (s4.length \u003e 0 \u0026\u0026 r4++, !i4.has(o5.region1Id) \u0026\u0026 !i4.has(o5.region2Id))\n for (const e54 of s4) {\n const i5 = n3.get(e54.traceId);\n if (i5 !== undefined \u0026\u0026 i5 !== e54.fixedNetId)\n throw new Error(`Preloaded trace \"${e54.traceId}\" maps to multiple canonical nets`);\n n3.set(e54.traceId, e54.fixedNetId);\n const r5 = t3.get(e54.traceId) ?? [];\n r5.push({ port: o5, assignment: e54 }), t3.set(e54.traceId, r5);\n }\n }\n const s3 = new Map(e52.regions.map((e53) =\u003e [e53.regionId, e53])), a4 = e52.connections ??= [], c4 = e52.solvedRoutes ??= [];\n let l3 = 0, h2 = 0;\n for (const [e53, o5] of t3) {\n o5.sort((e54, t5) =\u003e e54.assignment.routePosition - t5.assignment.routePosition || e54.assignment.z - t5.assignment.z || e54.port.portId.localeCompare(t5.port.portId));\n const t4 = o5.filter(({ port: e54 }, t5) =\u003e t5 === 0 || e54.portId !== o5[t5 - 1].port.portId);\n if (t4.length \u003c 2)\n continue;\n const i5 = [];\n let r5;\n for (let e54 = 0;e54 \u003c t4.length - 1; e54++) {\n const n4 = t4[e54], o6 = t4[e54 + 1];\n if (n4.assignment.z === o6.assignment.z \u0026\u0026 Math.abs(n4.assignment.routePosition - o6.assignment.routePosition) \u003c= 0.000001) {\n r5 = undefined;\n continue;\n }\n const s4 = EQ(t4, e54, r5);\n s4 ? (i5.push({ regionId: s4, from: n4, to: o6 }), r5 = s4) : r5 = undefined;\n }\n const d2 = [];\n for (const e54 of i5) {\n const t5 = d2.at(-1);\n t5 \u0026\u0026 t5.at(-1).to.port.portId === e54.from.port.portId ? t5.push(e54) : d2.push([e54]);\n }\n for (const [t5, o6] of d2.entries()) {\n const i6 = NQ(e53, t5);\n for (const t6 of o6) {\n const n4 = s3.get(t6.regionId);\n if (!n4)\n throw new Error(`Preloaded trace \"${e53}\" references missing region \"${t6.regionId}\"`);\n n4.assignments = [...n4.assignments ?? [], { regionPort1Id: t6.from.port.portId, regionPort2Id: t6.to.port.portId, connectionId: i6 }], h2++;\n }\n const r6 = o6[0], l4 = o6.at(-1), d3 = r6.from.port, u2 = l4.to.port, p3 = { connectionId: i6, mutuallyConnectedNetworkId: n3.get(e53) ?? e53, startRegionId: AQ(d3, r6.regionId), endRegionId: AQ(u2, l4.regionId), preloadedTraceSection: { traceId: e53, startRoutePosition: r6.from.assignment.routePosition, endRoutePosition: l4.to.assignment.routePosition, startPoint: { x: r6.from.assignment.tracePoint.x, y: r6.from.assignment.tracePoint.y, z: r6.from.assignment.z }, endPoint: { x: l4.to.assignment.tracePoint.x, y: l4.to.assignment.tracePoint.y, z: l4.to.assignment.z } } };\n a4.push(p3), c4.push({ requiredRip: false, connection: p3, path: [d3, u2].map((e54) =\u003e ({ portId: e54.portId, g: 0, h: 0, f: 0, hops: 0, ripRequired: false })) });\n }\n d2.length \u003e 0 \u0026\u0026 l3++;\n }\n })(c3), c3;\n};\nvar qQ = (e51) =\u003e {\n const t2 = new Map;\n for (let n2 = 0;n2 \u003c e51.problem.routeNet.length; n2++) {\n const o3 = e51.problem.routeMetadata?.[n2], i3 = o3?.mutuallyConnectedNetworkId;\n if (typeof i3 != \"string\" || i3.length === 0)\n throw new Error(`Tiny hypergraph route ${n2} is missing a net ID`);\n t2.set(i3, e51.problem.routeNet[n2]);\n }\n for (let n2 = 0;n2 \u003c e51.problem.regionNetId.length; n2++) {\n const o3 = e51.topology.regionMetadata?.[n2]?._tinyTerminalNetId;\n if (typeof o3 != \"string\")\n continue;\n const i3 = t2.get(o3);\n i3 !== undefined \u0026\u0026 (e51.problem.regionNetId[n2] = i3);\n }\n};\nvar JQ = (e51) =\u003e {\n const t2 = new Map;\n e51.topology.regionMetadata?.forEach((e52, n3) =\u003e {\n typeof e52.serializedRegionId == \"string\" \u0026\u0026 t2.set(e52.serializedRegionId, n3);\n });\n const n2 = new Set;\n for (const t3 of e51.problem.routeMetadata ?? [])\n wQ(t3) || (typeof t3.startRegionId == \"string\" \u0026\u0026 n2.add(t3.startRegionId), typeof t3.endRegionId == \"string\" \u0026\u0026 n2.add(t3.endRegionId));\n for (const o3 of e51.problem.routeMetadata ?? [])\n if (wQ(o3))\n for (const i3 of [o3.startRegionId, o3.endRegionId]) {\n if (typeof i3 != \"string\" || n2.has(i3))\n continue;\n const o4 = t2.get(i3);\n if (o4 === undefined)\n continue;\n const r3 = e51.topology.regionMetadata?.[o4];\n typeof r3?.netId == \"number\" || typeof r3?.NetId == \"number\" || (e51.problem.regionNetId[o4] = -1);\n }\n};\nvar QQ = (e51) =\u003e {\n if (e51.problem.metadataPortPenaltiesApplied)\n return 0;\n let t2 = 0, n2 = e51.problem.portPenalty !== undefined;\n for (let o4 = 0;o4 \u003c e51.topology.portCount; o4++) {\n const i3 = Number(e51.topology.portMetadata?.[o4]?.tinyHypergraphPortPenalty), r3 = Number.isFinite(i3) \u0026\u0026 i3 \u003e 0 ? i3 : 0;\n r3 \u003e 0 \u0026\u0026 t2++, e51.problem.portPenalty?.[o4] !== r3 \u0026\u0026 (n2 = false);\n }\n if (n2)\n return e51.problem.metadataPortPenaltiesApplied = true, t2;\n t2 = 0;\n const o3 = e51.problem.portPenalty ? new Float64Array(e51.problem.portPenalty) : new Float64Array(e51.topology.portCount);\n for (let n3 = 0;n3 \u003c e51.topology.portCount; n3++) {\n const i3 = Number(e51.topology.portMetadata?.[n3]?.tinyHypergraphPortPenalty);\n !Number.isFinite(i3) || i3 \u003c= 0 || (o3[n3] += i3, t2++);\n }\n return t2 \u003e 0 \u0026\u0026 (e51.problem.portPenalty = o3), e51.problem.metadataPortPenaltiesApplied = true, t2;\n};\nvar KQ = class extends PQ {\n configuredSolvers = new WeakSet;\n duplicatePortPenaltyCount = 0;\n metadataPortPenaltyCount = 0;\n crampedPortPenaltyCount = 0;\n preloadedPortCount = 0;\n preloadedFixedSegmentCount = 0;\n crampedPortTraversalPenalty;\n useSelectiveReripRouting;\n constructor(e51, t2, n2 = false) {\n super(e51), this.useSelectiveReripRouting = t2, this.crampedPortTraversalPenalty = 150;\n const o3 = OQ(e51.serializedHyperGraph);\n if (this.preloadedPortCount = o3.preloadedPortCount, this.preloadedFixedSegmentCount = o3.preloadedAssignmentCount, t2) {\n const e52 = this.pipelineDef.find((e53) =\u003e e53.solverName === \"solveGraph\");\n if (!e52)\n throw new Error(\"Tiny hypergraph pipeline is missing the solveGraph stage\");\n e52.solverClass = n2 ? CJ : _J;\n }\n this.MAX_ITERATIONS = XQ(e51);\n }\n loadHyperGraph(e51) {\n const t2 = super.loadHyperGraph(e51);\n ((e52, t3) =\u003e {\n const n3 = new Map;\n for (const e53 of t3.connections ?? [])\n wQ(e53) \u0026\u0026 n3.set(e53.connectionId, e53.preloadedTraceSection);\n for (const t4 of e52.problem.routeMetadata ?? []) {\n const e53 = n3.get(t4.connectionId);\n e53 \u0026\u0026 (t4.preloadedTraceSection = e53);\n }\n })(t2, this.inputProblem.serializedHyperGraph);\n const n2 = QQ(t2), { duplicatePortPenaltyCount: o3, crampedPortPenaltyCount: i3 } = ((e52, t3) =\u003e {\n let n3 = 0, o4 = 0;\n const i4 = e52.problem.portPenalty ? new Float64Array(e52.problem.portPenalty) : new Float64Array(e52.topology.portCount);\n for (let r3 = 0;r3 \u003c e52.topology.portCount; r3++) {\n const s2 = e52.topology.portMetadata?.[r3];\n typeof s2?.duplicatedFromPortId == \"string\" \u0026\u0026 (i4[r3] += 150, n3++), s2?.cramped \u0026\u0026 t3 \u003e 0 \u0026\u0026 (i4[r3] += t3, o4++);\n }\n return (n3 \u003e 0 || o4 \u003e 0) \u0026\u0026 (e52.problem.portPenalty = i4), { duplicatePortPenaltyCount: n3, crampedPortPenaltyCount: o4 };\n })(t2, this.crampedPortTraversalPenalty);\n return qQ(t2), JQ(t2), this.metadataPortPenaltyCount = Math.max(this.metadataPortPenaltyCount, n2), this.duplicatePortPenaltyCount = Math.max(this.duplicatePortPenaltyCount, o3), this.crampedPortPenaltyCount = Math.max(this.crampedPortPenaltyCount, i3), t2;\n }\n _step() {\n super._step(), this.configureSolver(this.activeSubSolver);\n }\n getInitialVisualizationSolver() {\n if (this.useSelectiveReripRouting \u0026\u0026 !this.initialVisualizationSolver) {\n const { topology: e52, problem: t2 } = this.loadHyperGraph(this.inputProblem.serializedHyperGraph);\n this.initialVisualizationSolver = new _J(e52, t2, this.getSolveGraphOptions());\n }\n const e51 = super.getInitialVisualizationSolver();\n return this.configureSolver(e51), e51;\n }\n getSolvedTinySolver() {\n const e51 = this.getSolver(\"optimizeSection\");\n if (e51?.solved \u0026\u0026 !e51.failed)\n return e51.getSolvedSolver();\n const t2 = this.getSolver(\"solveGraph\");\n if (t2?.solved \u0026\u0026 !t2.failed)\n return t2;\n throw new Error(\"TinyHyperGraph section pipeline does not have a solved graph\");\n }\n configureSolver(e51) {\n if (e51 \u0026\u0026 !this.configuredSolvers.has(e51)) {\n if (e51 instanceof dQ || e51 instanceof tJ) {\n const t2 = e51;\n QQ(t2), qQ(t2), JQ(t2);\n }\n this.configuredSolvers.add(e51);\n }\n }\n};\nvar eK = class extends ni {\n constructor(e51) {\n super(), this.params = e51;\n const t2 = ((e52) =\u003e e52.map((e53) =\u003e {\n const t3 = e53.simpleRouteConnection;\n if (!t3)\n throw new Error(`TinyHypergraphPortPointPathingSolver requires a SimpleRouteConnection for \"${e53.connectionId}\"`);\n const n3 = e53.mutuallyConnectedNetworkId;\n if (!n3)\n throw new Error(`TinyHypergraphPortPointPathingSolver requires a net ID for \"${e53.connectionId}\"`);\n return { ...e53, mutuallyConnectedNetworkId: n3, simpleRouteConnection: t3 };\n }))(e51.connections), n2 = e51.flags.USE_SELECTIVE_RERIP_ROUTING ? function(e52, t3) {\n const n3 = new Map;\n for (const o4 of e52) {\n const e53 = t3(o4);\n n3.set(e53, (n3.get(e53) ?? 0) + 1);\n }\n return e52.map((e53, t4) =\u003e ({ connection: e53, index: t4 })).sort((e53, o4) =\u003e (n3.get(t3(o4.connection)) ?? 0) - (n3.get(t3(e53.connection)) ?? 0) || e53.index - o4.index).map(({ connection: e53 }) =\u003e e53);\n }(t2, HQ) : t2;\n this.rootConnectionNameByConnectionId = new Map(n2.map((e52) =\u003e [e52.connectionId, e52.simpleRouteConnection.__rootConnectionNames?.[0]]));\n const o3 = ZQ({ ...e51, connections: n2 });\n this.originalPreloadedSegmentKeysByConnectionId = ((e52) =\u003e {\n const t3 = new Map;\n for (const n3 of e52.connections ?? [])\n wQ(n3) \u0026\u0026 t3.set(n3.connectionId, new Set);\n for (const n3 of e52.regions)\n for (const e53 of n3.assignments ?? []) {\n const o4 = t3.get(e53.connectionId);\n if (!o4)\n continue;\n const [i4, r4] = [e53.regionPort1Id, e53.regionPort2Id].sort();\n o4.add(JSON.stringify([n3.regionId, i4, r4]));\n }\n return t3;\n })(o3);\n const i3 = OQ(o3), r3 = i3.preloadedPortCount \u003e 0, s2 = r3 \u0026\u0026 e51.flags.USE_PARTIAL_RIP_ROUTING_WITH_PRELOADED_TRACES === true, a3 = s2 ? Math.max(o3.connections?.length ?? 0, i3.preloadedAssignmentCount) : undefined;\n let c3 = o3;\n const l3 = new qJ(o3, { duplicatePortProximity: 0.05, useSerializedPortPenalties: false, routeSolveOptions: { ...jQ(e51.minViaPadDiameter), USE_SPARSE_CANDIDATE_STORAGE: false, ACCEPT_BEST_SOLUTION_ON_TIMEOUT: true, GREEDY_FINAL_ROUTE_ITERS: 4, MAX_ITERATIONS: Math.ceil(2000000 * FQ(e51.effort)), RIP_THRESHOLD_RAMP_ATTEMPTS: 0, STATIC_REACHABILITY_PRECHECK: true } });\n if (l3.solve(), l3.failed)\n this.duplicateCongestedPortError = l3.error ?? \"unknown error\";\n else {\n this.duplicateCongestedPortReport = l3.report, c3 = l3.getOutput();\n for (const e52 of c3.ports) {\n const t3 = DQ(e52.d);\n typeof t3.duplicatedFromPortId == \"string\" \u0026\u0026 (delete t3._preloadedFixedNetIds, delete t3._preloadedTracePortAssignments);\n }\n }\n this.duplicatedPortCount = this.duplicateCongestedPortReport?.duplicatedPorts.reduce((e52, t3) =\u003e e52 + t3.duplicatePortIds.length, 0) ?? 0;\n const h2 = ((e52, t3, n3, o4 = true, i4) =\u003e {\n const r4 = e52.connections?.length ?? 0, s3 = i4 ?? r4, a4 = zQ.PARTIAL_RIP_MIN_ROUTE_COUNT ?? 0, c4 = zQ.PARTIAL_RIP_MAX_ROUTE_COUNT ?? Number.POSITIVE_INFINITY, l4 = o4 \u0026\u0026 s3 \u003e= a4 \u0026\u0026 s3 \u003c= c4;\n return { serializedHyperGraph: e52, createSectionMask: ({ topology: e53 }) =\u003e new Int8Array(e53.portCount), solveGraphOptions: { ...$Q({ effort: t3, portCount: e52.ports.length, minViaPadDiameter: n3 }), ...l4 ? { PARTIAL_RIP_MIN_ROUTE_COUNT: 0, PARTIAL_RIP_MAX_ROUTE_COUNT: Number.POSITIVE_INFINITY, PARTIAL_RIP_COMPLEXITY_SELECTION_MIN_ROUTE_COUNT: 0 } : { PARTIAL_RIP_ENABLED: false, OUTSIDE_IN_ROUTING: false } }, sectionSolverOptions: { ...YQ(t3, n3) } };\n })({ ...c3, solvedRoutes: o3.solvedRoutes }, e51.effort, e51.minViaPadDiameter, !r3 || s2, a3);\n this.tinyPipelineSolver = new KQ(h2, e51.flags.USE_SELECTIVE_RERIP_ROUTING === true, e51.flags.USE_PREPARED_PORT_POINT_ROUTING === true), this.primaryTinyPipelineSolver = this.tinyPipelineSolver, n2.length \u003e= 30 \u0026\u0026 n2.length \u003c= 99 \u0026\u0026 (this.alternativeTinyPipelineInput = { ...h2, solveGraphOptions: { ...h2.solveGraphOptions, TRACE_DENSITY_COST_FACTOR: 1 } }), this.MAX_ITERATIONS = XQ(h2) * (this.alternativeTinyPipelineInput ? 2 : 1), this.originalRegionById = new Map(e51.graph.regions.map((e52) =\u003e [e52.regionId, e52])), this.originalRegionIds = new Set(this.originalRegionById.keys()), this.inputNodeWithPortPoints = ((e52, t3) =\u003e {\n const n3 = new Map(t3.regions.map((e53) =\u003e [e53.regionId, e53])), o4 = new Map(t3.ports.map((e53) =\u003e [e53.portId, e53]));\n return e52.graph.regions.map((e53) =\u003e {\n const t4 = n3.get(e53.regionId), i4 = (t4?.pointIds ?? e53.ports.map((e54) =\u003e e54.d.portId)).map((e54) =\u003e o4.get(e54)).filter((e54) =\u003e e54 \u0026\u0026 !DQ(e54.d)._tinyTerminal).map((e54) =\u003e {\n const t5 = e54, o5 = DQ(t5.d), i5 = n3.get(t5.region1Id), r4 = n3.get(t5.region2Id), s3 = Boolean(kQ(i5?.d)._offBoardConnectionId ?? kQ(r4?.d)._offBoardConnectionId);\n return { portPointId: t5.portId, x: Number(o5.x ?? 0), y: Number(o5.y ?? 0), z: Number(o5.z ?? 0), prevPortPointId: typeof o5.prevPortPointId == \"string\" ? o5.prevPortPointId : undefined, nextPortPointId: typeof o5.nextPortPointId == \"string\" ? o5.nextPortPointId : undefined, connectionNodeIds: [t5.region1Id, t5.region2Id], distToCentermostPortOnZ: Number(o5.distToCentermostPortOnZ ?? 0), cramped: Boolean(o5.cramped), connectsToOffBoardNode: s3 };\n });\n return { capacityMeshNodeId: e53.d.capacityMeshNodeId, center: e53.d.center, width: e53.d.width, height: e53.d.height, portPoints: i4, availableZ: e53.d.availableZ, _containsObstacle: e53.d._containsObstacle, _containsTarget: e53.d._containsTarget, _offBoardConnectionId: e53.d._offBoardConnectionId, _offBoardConnectedCapacityMeshNodeIds: e53.d._offBoardConnectedCapacityMeshNodeIds, _qfpRegionType: e53.d._qfpRegionType, _isNarrowQfpPadGap: e53.d._isNarrowQfpPadGap };\n });\n })(e51, c3), Object.defineProperty(this, \"stats\", { configurable: true, enumerable: true, get: () =\u003e this.getStatsSnapshot(), set: (e52) =\u003e {\n this.statsSnapshot = e52, this.statsSnapshotDirty = false;\n } });\n }\n tinyPipelineSolver;\n primaryTinyPipelineSolver;\n alternativeTinyPipelineSolver;\n alternativeTinyPipelineInput;\n candidatePortfolioPhase = \"primary\";\n primaryCandidateSummary;\n alternativeCandidateSummary;\n alternativeCandidateEvaluated = false;\n selectedCandidate = \"primary\";\n duplicateCongestedPortReport;\n duplicateCongestedPortError;\n duplicatedPortCount = 0;\n inputNodeWithPortPoints;\n originalRegionById;\n originalRegionIds;\n rootConnectionNameByConnectionId;\n originalPreloadedSegmentKeysByConnectionId;\n statsSnapshot = {};\n statsSnapshotDirty = false;\n asyncRunning = false;\n getSolverName() {\n return \"TinyHypergraphPortPointPathingSolver\";\n }\n getChangedPreloadedRouteIds(e51) {\n const t2 = new Map, n2 = new Map;\n for (let o4 = 0;o4 \u003c e51.problem.routeCount; o4++) {\n const i3 = this.getRouteMetadata(e51, o4);\n wQ(i3) \u0026\u0026 (t2.set(i3.connectionId, o4), n2.set(o4, new Set));\n }\n for (let t3 = 0;t3 \u003c e51.state.regionSegments.length; t3++) {\n const o4 = e51.topology.regionMetadata?.[t3]?.serializedRegionId;\n for (const [i3, r3, s2] of e51.state.regionSegments[t3] ?? []) {\n const t4 = n2.get(i3);\n if (!t4)\n continue;\n const a3 = e51.topology.portMetadata?.[r3]?.serializedPortId, c3 = e51.topology.portMetadata?.[s2]?.serializedPortId;\n if (typeof o4 != \"string\" || typeof a3 != \"string\" || typeof c3 != \"string\")\n throw new Error(`Tiny hypergraph preloaded route ${i3} has a segment without serialized topology IDs`);\n const [l3, h2] = [a3, c3].sort();\n t4.add(JSON.stringify([o4, l3, h2]));\n }\n }\n const o3 = new Set;\n for (const [e52, i3] of this.originalPreloadedSegmentKeysByConnectionId) {\n const r3 = t2.get(e52);\n if (r3 === undefined)\n throw new Error(`Tiny hypergraph lost preloaded trace section \"${e52}\"`);\n const s2 = n2.get(r3);\n if (i3.size \u003e 0 \u0026\u0026 s2.size === 0)\n throw new Error(`Tiny hypergraph lost preloaded trace section \"${e52}\"`);\n (i3.size !== s2.size || [...i3].some((e53) =\u003e !s2.has(e53))) \u0026\u0026 o3.add(r3);\n }\n return o3;\n }\n summarizePipelineCandidate(e51) {\n const t2 = e51.getSolvedTinySolver();\n let n2 = 0, o3 = 0, i3 = 0, r3 = 0, s2 = 0, a3 = 0;\n const c3 = t2.topology.regionMetadata ?? [];\n for (let e52 = 0;e52 \u003c t2.state.regionSegments.length; e52++) {\n const l3 = t2.state.regionSegments[e52];\n s2 += l3.length;\n for (const [, e53, n3] of l3)\n t2.topology.portZ[e53] !== t2.topology.portZ[n3] \u0026\u0026 (a3 += 1);\n const h2 = c3[e52]?.capacityMeshNodeId;\n if (!h2 || !this.originalRegionIds.has(h2))\n continue;\n const d2 = this.originalRegionById.get(h2);\n if (!d2 || l3.length === 0)\n continue;\n const u2 = l3.map(([e53, n3, o4]) =\u003e [this.createAssignedPortPoint(t2, e53, n3), this.createAssignedPortPoint(t2, e53, o4)]), p3 = { capacityMeshNodeId: d2.d.capacityMeshNodeId, center: d2.d.center, width: d2.d.width, height: d2.d.height, portPoints: u2.flat(), portPointsInPairs: u2, availableZ: d2.d.availableZ }, m2 = Cz(p3), g2 = jz(d2.d, m2.numSameLayerCrossings, m2.numEntryExitLayerChanges, m2.numTransitionPairCrossings);\n n2 += g2, o3 += g2 * g2, i3 = Math.max(i3, g2), r3 += p3.portPoints.length ** 2;\n }\n return { nodePfSum: n2, nodePfSquaredSum: o3, nodePfMax: i3, squaredNodePortPointCount: r3, segmentCount: s2, layerChangeCount: a3, changedPreloadedTraceSectionCount: this.getChangedPreloadedRouteIds(t2).size };\n }\n shouldEvaluateAlternative(e51) {\n const t2 = this.primaryTinyPipelineSolver.getSolvedTinySolver().problem.routeCount;\n return this.alternativeTinyPipelineInput !== undefined \u0026\u0026 ((e52, t3) =\u003e e52.nodePfSum \u003e 4 \u0026\u0026 e52.nodePfMax \u003e 1 \u0026\u0026 e52.squaredNodePortPointCount / Math.max(1, t3) \u003e= 125)(e51, t2);\n }\n shouldSelectAlternative(e51, t2) {\n return ((e52, t3, n2) =\u003e {\n if (t3.changedPreloadedTraceSectionCount \u003e e52.changedPreloadedTraceSectionCount)\n return false;\n const o3 = n2 \u003e 40 ? 0.92 : 0.95, i3 = t3.nodePfSum \u003c= 0.9 * e52.nodePfSum \u0026\u0026 t3.nodePfSquaredSum \u003c= 0.85 * e52.nodePfSquaredSum \u0026\u0026 t3.nodePfMax \u003c= 0.85 * e52.nodePfMax \u0026\u0026 t3.squaredNodePortPointCount \u003c 0.98 * e52.squaredNodePortPointCount \u0026\u0026 t3.segmentCount \u003c= 0.97 * e52.segmentCount;\n return t3.nodePfSum \u003c= 1.03 * e52.nodePfSum \u0026\u0026 t3.nodePfSquaredSum \u003c= 1.06 * e52.nodePfSquaredSum \u0026\u0026 (t3.squaredNodePortPointCount \u003c e52.squaredNodePortPointCount * o3 || i3);\n })(e51, t2, this.primaryTinyPipelineSolver.getSolvedTinySolver().problem.routeCount);\n }\n finishCandidatePortfolio() {\n this.candidatePortfolioPhase = \"complete\", this.solved = this.tinyPipelineSolver.solved, this.failed = this.tinyPipelineSolver.failed, this.error = this.tinyPipelineSolver.error ?? null;\n }\n getSolveGraphBenchmarkMetrics() {\n const e51 = this.tinyPipelineSolver.getSolver(\"solveGraph\");\n if (!e51)\n return;\n const t2 = e51.state.regionSegments.map((e52) =\u003e e52.length), n2 = this.selectedCandidate === \"alternative\" ? this.alternativeCandidateSummary : this.primaryCandidateSummary, o3 = e51.stats, i3 = this.tinyPipelineSolver.getStageStats().solveGraph;\n return { routeCount: e51.problem.routeCount, traceDensityCandidateEvaluated: this.alternativeCandidateEvaluated, traceDensityCandidateSelected: this.selectedCandidate === \"alternative\", downstreamNodePfSum: n2?.nodePfSum, downstreamNodePfSquaredSum: n2?.nodePfSquaredSum, downstreamNodePfMax: n2?.nodePfMax, downstreamSquaredNodePortPointCount: n2?.squaredNodePortPointCount, changedPreloadedTraceSectionCount: n2?.changedPreloadedTraceSectionCount, iterations: e51.iterations, timeMs: i3?.timeSpent, ripCount: o3.ripCount, partialRipCount: o3.partialRipCount, partiallyRippedRouteCount: o3.partiallyRippedRouteCount, partiallyRippedSegmentCount: o3.partiallyRippedSegmentCount, retainedPartialRipSegmentCount: o3.retainedPartialRipSegmentCount, firstMaxRegionCost: o3.firstMaxRegionCost, bestMaxRegionCost: o3.bestMaxRegionCost, firstTotalRegionCost: o3.firstTotalRegionCost, bestTotalRegionCost: o3.bestTotalRegionCost, firstSegmentCount: o3.firstSegmentCount, bestSolvedSegmentCount: o3.bestSolvedSegmentCount, bestSolvedMaxRegionSegmentCount: o3.bestSolvedMaxRegionSegmentCount, bestSolvedSquaredRegionSegmentCount: o3.bestSolvedSquaredRegionSegmentCount, finalMaxRegionSegmentCount: Math.max(0, ...t2), finalSquaredRegionSegmentCount: t2.reduce((e52, t3) =\u003e e52 + t3 * t3, 0), finalSegmentCount: n2?.segmentCount, finalLayerChangeCount: n2?.layerChangeCount, warmupFullRipAttempts: o3.partialRipWarmupFullRipAttempts, complexityAwareSelection: o3.partialRipComplexityAwareSelection, targetReached: o3.partialRipTargetReached, outsideInCompletedRouteCount: o3.outsideInCompletedRouteCount, outsideInFallbackRouteCount: o3.outsideInFallbackRouteCount, outsideInForwardExpansionCount: o3.outsideInForwardExpansionCount, outsideInReverseExpansionCount: o3.outsideInReverseExpansionCount };\n }\n _step() {\n this.tinyPipelineSolver.step(), this.candidatePortfolioPhase === \"primary\" \u0026\u0026 this.primaryTinyPipelineSolver.failed ? (this.alternativeTinyPipelineInput = undefined, this.finishCandidatePortfolio()) : this.candidatePortfolioPhase === \"primary\" \u0026\u0026 this.primaryTinyPipelineSolver.solved ? (this.primaryCandidateSummary = this.summarizePipelineCandidate(this.primaryTinyPipelineSolver), this.shouldEvaluateAlternative(this.primaryCandidateSummary) ? (this.alternativeCandidateEvaluated = true, this.alternativeTinyPipelineSolver = new KQ(this.alternativeTinyPipelineInput, this.params.flags.USE_SELECTIVE_RERIP_ROUTING === true, this.params.flags.USE_PREPARED_PORT_POINT_ROUTING === true), this.tinyPipelineSolver = this.alternativeTinyPipelineSolver, this.candidatePortfolioPhase = \"alternative\") : (this.alternativeTinyPipelineInput = undefined, this.finishCandidatePortfolio())) : this.candidatePortfolioPhase === \"alternative\" \u0026\u0026 (this.tinyPipelineSolver.solved || this.tinyPipelineSolver.failed) \u0026\u0026 (this.tinyPipelineSolver.solved \u0026\u0026 !this.tinyPipelineSolver.failed \u0026\u0026 (this.alternativeCandidateSummary = this.summarizePipelineCandidate(this.tinyPipelineSolver)), this.alternativeCandidateSummary \u0026\u0026 this.primaryCandidateSummary \u0026\u0026 this.shouldSelectAlternative(this.primaryCandidateSummary, this.alternativeCandidateSummary) ? (this.selectedCandidate = \"alternative\", this.primaryTinyPipelineSolver = undefined, this.alternativeTinyPipelineSolver = undefined) : (this.tinyPipelineSolver = this.primaryTinyPipelineSolver, this.alternativeTinyPipelineSolver = undefined), this.alternativeTinyPipelineInput = undefined, this.finishCandidatePortfolio()), this.solved = this.candidatePortfolioPhase === \"complete\" \u0026\u0026 this.tinyPipelineSolver.solved, this.failed = this.candidatePortfolioPhase === \"complete\" \u0026\u0026 this.tinyPipelineSolver.failed, this.error = this.failed ? this.tinyPipelineSolver.error ?? null : null, this.progress = this.candidatePortfolioPhase === \"complete\" ? 1 : this.candidatePortfolioPhase === \"alternative\" ? 0.5 + 0.5 * this.tinyPipelineSolver.progress : this.alternativeTinyPipelineInput ? 0.5 * this.tinyPipelineSolver.progress : this.tinyPipelineSolver.progress, this.statsSnapshotDirty = true, this.activeSubSolver = this.tinyPipelineSolver.activeSubSolver ?? null;\n }\n async solveAsync(e51, t2 = 1 / 0) {\n if (this.asyncRunning)\n throw new Error(\"Port-point solveAsync is already running\");\n this.asyncRunning = true;\n try {\n for (;!this.solved \u0026\u0026 !this.failed \u0026\u0026 this.iterations \u003c t2; ) {\n const n2 = this.tinyPipelineSolver.activeSubSolver;\n if (e51 \u0026\u0026 n2 instanceof CJ) {\n const o3 = n2.iterations;\n await n2.solveAsync(e51, o3 + Math.max(0, t2 - this.iterations));\n const i3 = n2.solved || n2.failed, r3 = Math.max(0, n2.iterations - o3 - (i3 ? 1 : 0));\n if (this.tinyPipelineSolver.iterations += r3, this.iterations += r3, this.iterations \u003e= t2)\n break;\n }\n this.step();\n }\n } catch (e52) {\n throw this.failed = true, this.error = `Port-point asynchronous solve failed: ${e52}`, e52;\n } finally {\n this.asyncRunning = false;\n }\n }\n getStatsSnapshot() {\n if (!this.statsSnapshotDirty)\n return this.statsSnapshot;\n const e51 = this.tinyPipelineSolver.getSolver(\"optimizeSection\"), t2 = this.getCurrentTinySolver();\n return this.statsSnapshot = { duplicateCongestedPortSourceCount: this.duplicateCongestedPortReport?.duplicatedPorts.length ?? 0, duplicateCongestedPortCount: this.duplicatedPortCount, duplicateCongestedPortFallbackToOriginal: Boolean(this.duplicateCongestedPortError), duplicateCongestedPortPenalty: this.duplicatedPortCount \u003e 0 ? 150 : 0, duplicateCongestedPortPenaltyCount: this.tinyPipelineSolver.duplicatePortPenaltyCount, metadataPortPenaltyCount: this.tinyPipelineSolver.metadataPortPenaltyCount, crampedPortPenalty: this.tinyPipelineSolver.crampedPortTraversalPenalty, crampedPortPenaltyCount: this.tinyPipelineSolver.crampedPortPenaltyCount, preloadedPortCount: this.tinyPipelineSolver.preloadedPortCount, preloadedFixedSegmentCount: this.tinyPipelineSolver.preloadedFixedSegmentCount, duplicateCongestedPortError: this.duplicateCongestedPortError, candidatePortfolioPhase: this.candidatePortfolioPhase, candidatePortfolioSelectedCandidate: this.selectedCandidate, candidatePortfolioPrimarySummary: this.primaryCandidateSummary, candidatePortfolioAlternativeSummary: this.alternativeCandidateSummary, ...this.tinyPipelineSolver.stats ?? {}, ...t2?.stats ?? {}, ...e51?.stats ?? {}, currentStage: this.tinyPipelineSolver.getCurrentStageName(), stageStats: this.tinyPipelineSolver.getStageStats() }, this.statsSnapshotDirty = false, this.statsSnapshot;\n }\n preview() {\n return this.visualize();\n }\n getCurrentTinySolver() {\n const e51 = this.tinyPipelineSolver.getSolver(\"optimizeSection\");\n if (e51?.solved \u0026\u0026 !e51.failed)\n return e51.getSolvedSolver();\n const t2 = this.tinyPipelineSolver.getSolver(\"solveGraph\");\n return t2 || undefined;\n }\n getSolvedTinySolver() {\n return this.tinyPipelineSolver.getSolvedTinySolver();\n }\n getRouteMetadata(e51, t2) {\n return e51.problem.routeMetadata?.[t2];\n }\n createAssignedPortPoint(e51, t2, n2) {\n const o3 = this.getRouteMetadata(e51, t2), i3 = o3 ? ((e52) =\u003e e52.simpleRouteConnection?.name ?? e52.connectionId)(o3) : `route-${t2}`, r3 = o3 ? this.rootConnectionNameByConnectionId.get(o3.connectionId) ?? o3.mutuallyConnectedNetworkId : undefined, s2 = e51.topology.portMetadata?.[n2];\n return { portPointId: String(s2?.serializedPortId ?? s2?.portId ?? `tiny-port-${n2}`), x: e51.topology.portX[n2], y: e51.topology.portY[n2], z: e51.topology.portZ[n2], connectionName: i3, rootConnectionName: r3, ...this.params.preserveTerminalPcbPortIds \u0026\u0026 typeof s2?.pcb_port_id == \"string\" ? { pcb_port_id: s2.pcb_port_id } : {}, prevPortPointId: typeof s2?.prevPortPointId == \"string\" ? s2.prevPortPointId : undefined, nextPortPointId: typeof s2?.nextPortPointId == \"string\" ? s2.nextPortPointId : undefined };\n }\n getOutput() {\n const e51 = this.getSolvedTinySolver(), t2 = [], n2 = e51.state.regionSegments, o3 = e51.topology.regionMetadata ?? [], i3 = this.getChangedPreloadedRouteIds(e51);\n for (let r4 = 0;r4 \u003c n2.length; r4++) {\n const s2 = o3[r4]?.capacityMeshNodeId;\n if (!s2 || !this.originalRegionIds.has(s2))\n continue;\n const a3 = this.originalRegionById.get(s2);\n if (!a3)\n continue;\n const c3 = n2[r4].filter(([t3]) =\u003e {\n const n3 = this.getRouteMetadata(e51, t3);\n return !wQ(n3) || i3.has(t3);\n }).map(([t3, n3, o4]) =\u003e {\n const i4 = this.createAssignedPortPoint(e51, t3, n3), r5 = this.createAssignedPortPoint(e51, t3, o4);\n return i4.portPointId \u0026\u0026 r5.portPointId \u0026\u0026 (i4.nextPortPointId = r5.portPointId, r5.prevPortPointId = i4.portPointId), [i4, r5];\n }), l3 = c3.flat();\n l3.length !== 0 \u0026\u0026 t2.push({ capacityMeshNodeId: a3.d.capacityMeshNodeId, center: a3.d.center, width: a3.d.width, height: a3.d.height, portPoints: l3, portPointsInPairs: c3, availableZ: a3.d.availableZ });\n }\n const r3 = [...i3].map((t3) =\u003e {\n const n3 = this.getRouteMetadata(e51, t3);\n if (!wQ(n3))\n throw new Error(`Changed preloaded hypergraph route ${t3} is missing section metadata`);\n const o4 = n3.preloadedTraceSection;\n return { connectionName: n3.connectionId, traceId: o4.traceId, startRoutePosition: o4.startRoutePosition, endRoutePosition: o4.endRoutePosition, connection: { name: n3.connectionId, __rootConnectionNames: [n3.mutuallyConnectedNetworkId], pointsToConnect: [{ x: o4.startPoint.x, y: o4.startPoint.y, layer: Co(o4.startPoint.z, this.params.layerCount) }, { x: o4.endPoint.x, y: o4.endPoint.y, layer: Co(o4.endPoint.z, this.params.layerCount) }] } };\n });\n return this.stats.changedPreloadedTraceSectionCount = r3.length, { nodesWithPortPoints: t2, inputNodeWithPortPoints: this.inputNodeWithPortPoints, changedPreloadedTraceSections: r3 };\n }\n computeNodePf(e51) {\n const t2 = this.getOutput().nodesWithPortPoints.find((t3) =\u003e t3.capacityMeshNodeId === e51.capacityMeshNodeId);\n return this.computeSolvedNodePf(e51.capacityMeshNodeId, t2);\n }\n computeNodePfMap() {\n const e51 = new Map(this.getOutput().nodesWithPortPoints.map((e52) =\u003e [e52.capacityMeshNodeId, e52]));\n return new Map(this.inputNodeWithPortPoints.map((t2) =\u003e [t2.capacityMeshNodeId, this.computeSolvedNodePf(t2.capacityMeshNodeId, e51.get(t2.capacityMeshNodeId))]));\n }\n computeSolvedNodePf(e51, t2) {\n const n2 = this.originalRegionById.get(e51);\n if (!t2 || !n2)\n return null;\n const o3 = Cz(t2);\n return jz(n2.d, o3.numSameLayerCrossings, o3.numEntryExitLayerChanges, o3.numTransitionPairCrossings);\n }\n tryFinalAcceptance() {}\n getConstructorParams() {\n return [this.params];\n }\n visualize() {\n return this.tinyPipelineSolver.visualize();\n }\n};\nvar tK = (e51, t2) =\u003e {\n if (!e51 || e51 === \"none\")\n return e51;\n try {\n const n2 = Tn(e51);\n return `rgba(${n2.red},${n2.green},${n2.blue},${t2})`;\n } catch {\n return Ao(e51, 1 - t2);\n }\n};\nvar nK = ({ srj: e51, opacity: t2 = 0.25, visualizationOptions: n2 = {} }) =\u003e {\n const o3 = Wo({ ...e51, obstacles: [] }, n2);\n return { ...o3, points: [], lines: o3.lines?.map((e52) =\u003e ({ ...e52, strokeColor: tK(e52.strokeColor, t2) })), rects: o3.rects?.map((e52) =\u003e ({ ...e52, fill: tK(e52.fill, t2), stroke: tK(e52.stroke, t2) })), circles: o3.circles?.map((e52) =\u003e ({ ...e52, fill: tK(e52.fill, t2), stroke: tK(e52.stroke, t2) })) };\n};\nfunction oK(e51, t2) {\n return e51.x \u003e= t2.center.x - t2.width / 2 \u0026\u0026 e51.x \u003c= t2.center.x + t2.width / 2 \u0026\u0026 e51.y \u003e= t2.center.y - t2.height / 2 \u0026\u0026 e51.y \u003c= t2.center.y + t2.height / 2;\n}\nvar iK = 0.000001;\nvar rK = (e51, t2, n2) =\u003e pe(e51, t2, n2) \u003c= iK;\nvar sK = (e51, t2) =\u003e Math.abs(e51.x - t2.x) \u003c= iK \u0026\u0026 Math.abs(e51.y - t2.y) \u003c= iK;\nvar aK = (e51, t2) =\u003e {\n if (!t2 || t2.length \u003c 3)\n return false;\n for (let n3 = 0;n3 \u003c t2.length; n3++) {\n const o3 = t2[n3], i3 = t2[(n3 + 1) % t2.length];\n if (rK(e51, o3, i3))\n return true;\n }\n let n2 = false;\n for (let o3 = 0, i3 = t2.length - 1;o3 \u003c t2.length; i3 = o3++) {\n const r3 = t2[o3], s2 = t2[i3];\n r3.y \u003e e51.y != s2.y \u003e e51.y \u0026\u0026 e51.x \u003c (s2.x - r3.x) * (e51.y - r3.y) / (s2.y - r3.y) + r3.x \u0026\u0026 (n2 = !n2);\n }\n return n2;\n};\nvar cK = \"escape-via:\";\nvar lK = 0.0001;\nvar hK = (e51) =\u003e e51.obstacleId ?? [e51.layers.join(\".\"), e51.center.x.toFixed(4), e51.center.y.toFixed(4), e51.width.toFixed(4), e51.height.toFixed(4)].join(\":\");\nvar dK = (e51, t2, n2 = 0.0001) =\u003e me(e51, t2) \u003c= n2;\nvar uK = class extends ni {\n constructor(e51, t2 = {}) {\n super(), this.ogSrj = e51, this.viaDiameter = t2.viaDiameter ?? Yo(e51).padDiameter, this.viaRadius = this.viaDiameter / 2, this.minTraceWidth = t2.minTraceWidth ?? e51.minTraceWidth, this.obstacleMargin = t2.obstacleMargin ?? e51.defaultObstacleMargin ?? 0.15, this.requiredViaToPadClearance = Math.max(this.obstacleMargin, e51.minViaEdgeToPadEdgeClearance ?? 0), this.escapeOffset = this.viaRadius + Math.max(this.minTraceWidth / 2, this.requiredViaToPadClearance), this.requiredTraceClearance = this.minTraceWidth / 2 + this.obstacleMargin / 2, this.requiredViaToViaClearance = this.viaDiameter + this.obstacleMargin, this.outputSrj = e51, this.escapeViaMetadataByPointId = new Map, this.createdEscapeVias = [];\n }\n getSolverName() {\n return \"EscapeViaLocationSolver\";\n }\n viaDiameter;\n viaRadius;\n minTraceWidth;\n obstacleMargin;\n escapeOffset;\n requiredTraceClearance;\n requiredViaToPadClearance;\n requiredViaToViaClearance;\n outputSrj;\n escapeViaMetadataByPointId;\n createdEscapeVias;\n nextEscapeViaIndex = 0;\n getConnectionNetIds(e51) {\n return new Set([e51.name, ...e51.__rootConnectionNames ?? [], e51.__netConnectionName].filter((e52) =\u003e Boolean(e52)));\n }\n obstacleMatchesConnectionNet(e51, t2) {\n return e51.connectedTo.some((e52) =\u003e t2.has(e52));\n }\n getObstacleZs(e51) {\n return e51.__zLayers \u0026\u0026 e51.__zLayers.length \u003e 0 ? e51.__zLayers : e51.layers.map((e52) =\u003e mo(e52, this.ogSrj.layerCount));\n }\n getViaSpanLayers(e51, t2) {\n const n2 = mo(e51, this.ogSrj.layerCount), o3 = mo(t2, this.ogSrj.layerCount), i3 = Math.min(n2, o3), r3 = Math.max(n2, o3), s2 = Array.from({ length: r3 - i3 + 1 }, (e52, t3) =\u003e i3 + t3);\n return { __zLayers: s2, layers: s2.map((e52) =\u003e Co(e52, this.ogSrj.layerCount)) };\n }\n createEscapeViaObstacle(e51) {\n const { escapeVia: t2, connectionNetIds: n2 } = e51, { layers: o3, __zLayers: i3 } = this.getViaSpanLayers(t2.sourceLayer, t2.targetLayer);\n return { obstacleId: `escape-via-obstacle:${t2.pointId}`, type: \"rect\", layers: o3, __zLayers: i3, center: { x: t2.x, y: t2.y }, width: this.viaDiameter, height: this.viaDiameter, connectedTo: Array.from(n2) };\n }\n selectSourceObstacle(e51) {\n const { point: t2, sourceLayer: n2, connectionNetIds: o3 } = e51;\n return this.ogSrj.obstacles.filter((e52) =\u003e !e52.isCopperPour \u0026\u0026 e52.layers.includes(n2) \u0026\u0026 oK(t2, e52)).sort((e52, n3) =\u003e {\n const i3 = e52.connectedTo.includes(t2.pointId ?? \"\") || e52.connectedTo.includes(t2.pcb_port_id ?? \"\") || this.obstacleMatchesConnectionNet(e52, o3);\n return i3 !== (n3.connectedTo.includes(t2.pointId ?? \"\") || n3.connectedTo.includes(t2.pcb_port_id ?? \"\") || this.obstacleMatchesConnectionNet(n3, o3)) ? i3 ? -1 : 1 : e52.width * e52.height - n3.width * n3.height;\n })[0];\n }\n getCandidatePositions(e51, t2) {\n if (!t2)\n return this.dedupeCandidatePositions([{ x: e51.x + this.escapeOffset, y: e51.y }, { x: e51.x - this.escapeOffset, y: e51.y }, { x: e51.x, y: e51.y + this.escapeOffset }, { x: e51.x, y: e51.y - this.escapeOffset }, { x: e51.x + this.escapeOffset, y: e51.y + this.escapeOffset }, { x: e51.x + this.escapeOffset, y: e51.y - this.escapeOffset }, { x: e51.x - this.escapeOffset, y: e51.y + this.escapeOffset }, { x: e51.x - this.escapeOffset, y: e51.y - this.escapeOffset }]);\n const n2 = t2.center.x - t2.width / 2, o3 = t2.center.x + t2.width / 2, i3 = t2.center.y - t2.height / 2, r3 = t2.center.y + t2.height / 2, s2 = n2 - this.escapeOffset, a3 = o3 + this.escapeOffset, c3 = i3 - this.escapeOffset, l3 = r3 + this.escapeOffset, h2 = this.getEdgeSamples(i3, r3, e51.y), d2 = this.getEdgeSamples(n2, o3, e51.x), u2 = [];\n for (const e52 of h2)\n u2.push({ x: s2, y: e52 }, { x: a3, y: e52 });\n for (const e52 of d2)\n u2.push({ x: e52, y: c3 }, { x: e52, y: l3 });\n return this.dedupeCandidatePositions(u2);\n }\n dedupeCandidatePositions(e51) {\n const t2 = [];\n for (const n2 of e51)\n t2.some((e52) =\u003e dK(e52, n2)) || t2.push(n2);\n return t2;\n }\n pushEdgeSample(e51, t2, n2, o3) {\n const i3 = Math.max(n2, Math.min(o3, t2));\n e51.some((e52) =\u003e Math.abs(e52 - i3) \u003c= lK) || e51.push(i3);\n }\n getEdgeSamples(e51, t2, n2) {\n const o3 = [], i3 = t2 - e51;\n if (this.pushEdgeSample(o3, n2, e51, t2), i3 \u003c= lK)\n return o3;\n this.pushEdgeSample(o3, e51, e51, t2), this.pushEdgeSample(o3, t2, e51, t2), this.pushEdgeSample(o3, (e51 + t2) / 2, e51, t2);\n const r3 = Math.max(e51, Math.min(t2, n2)), s2 = Math.max(this.requiredViaToViaClearance, lK), a3 = Math.ceil(i3 / s2);\n for (let n3 = 1;n3 \u003c= a3; n3++) {\n const i4 = n3 * s2;\n this.pushEdgeSample(o3, r3 + i4, e51, t2), this.pushEdgeSample(o3, r3 - i4, e51, t2);\n }\n return o3;\n }\n isInsideBoard(e51) {\n return !!(e51.x \u003e= this.ogSrj.bounds.minX + this.viaRadius \u0026\u0026 e51.x \u003c= this.ogSrj.bounds.maxX - this.viaRadius \u0026\u0026 e51.y \u003e= this.ogSrj.bounds.minY + this.viaRadius \u0026\u0026 e51.y \u003c= this.ogSrj.bounds.maxY - this.viaRadius) \u0026\u0026 (!(this.ogSrj.outline \u0026\u0026 this.ogSrj.outline.length \u003e= 3) || aK(e51, this.ogSrj.outline));\n }\n hasClearEscapePath(e51) {\n const { sourcePoint: t2, candidate: n2, sourceLayer: o3, sourceObstacle: i3 } = e51;\n if (this.ogSrj.outline \u0026\u0026 this.ogSrj.outline.length \u003e= 3) {\n if ((({ start: e52, end: t3, polygon: n3, margin: o4 = 0.2 }) =\u003e {\n if (!n3 || n3.length \u003c 3)\n return false;\n const i4 = aK(e52, n3), r3 = aK(t3, n3);\n if (!i4 || !r3)\n return true;\n for (let i5 = 0;i5 \u003c n3.length; i5++) {\n const r4 = n3[i5], s2 = n3[(i5 + 1) % n3.length], a3 = rK(e52, r4, s2), c3 = rK(t3, r4, s2);\n if (a3 \u0026\u0026 c3)\n continue;\n if (!he(e52, t3, r4, s2)) {\n if (!a3 \u0026\u0026 !c3 \u0026\u0026 qr(e52, t3, r4, s2) \u003c o4 - iK)\n return true;\n continue;\n }\n const l3 = ge(e52, t3, r4, s2);\n if (!(l3 \u0026\u0026 (a3 \u0026\u0026 sK(l3, e52) || c3 \u0026\u0026 sK(l3, t3)) || l3 \u0026\u0026 (sK(l3, e52) || sK(l3, t3))))\n return true;\n }\n return false;\n })({ start: t2, end: n2, polygon: this.ogSrj.outline, margin: this.requiredTraceClearance }))\n return false;\n }\n for (const e52 of this.ogSrj.obstacles) {\n if (e52 === i3)\n continue;\n if (!e52.layers.includes(o3))\n continue;\n if (oK(n2, e52))\n return false;\n const r3 = Kj(e52);\n if (Math.min(...r3.map((e53) =\u003e qr(t2, n2, e53.start, e53.end))) + lK \u003c this.requiredTraceClearance)\n return false;\n }\n return true;\n }\n getBoardBoundarySegments() {\n if (this.ogSrj.outline \u0026\u0026 this.ogSrj.outline.length \u003e= 3)\n return this.ogSrj.outline.map((e52, t3) =\u003e ({ start: e52, end: this.ogSrj.outline[(t3 + 1) % this.ogSrj.outline.length] }));\n const { minX: e51, maxX: t2, minY: n2, maxY: o3 } = this.ogSrj.bounds;\n return [{ start: { x: e51, y: n2 }, end: { x: t2, y: n2 } }, { start: { x: t2, y: n2 }, end: { x: t2, y: o3 } }, { start: { x: t2, y: o3 }, end: { x: e51, y: o3 } }, { start: { x: e51, y: o3 }, end: { x: e51, y: n2 } }];\n }\n getRayProbeDistance() {\n const { minX: e51, maxX: t2, minY: n2, maxY: o3 } = this.ogSrj.bounds;\n return 2 * Math.hypot(t2 - e51, o3 - n2) + this.viaDiameter;\n }\n getRayIntersectionDistance(e51) {\n const { rayStart: t2, rayEnd: n2, segmentStart: o3, segmentEnd: i3 } = e51;\n if (!he(t2, n2, o3, i3))\n return null;\n const r3 = ge(t2, n2, o3, i3);\n if (!r3)\n return null;\n const s2 = me(t2, r3);\n return s2 \u003c= lK ? null : s2;\n }\n getProjectedFreeSpace(e51) {\n const { sourcePoint: t2, candidate: n2 } = e51, o3 = n2.x - t2.x, i3 = n2.y - t2.y;\n return Math.abs(o3) \u003c= lK || Math.abs(i3) \u003c= lK ? this.getProjectedFreeSpaceAlongDirection({ ...e51, direction: { x: o3, y: i3 }, travelDistance: me(t2, n2) }) : Math.min(this.getProjectedFreeSpaceAlongDirection({ ...e51, direction: { x: 0, y: Math.sign(i3) }, travelDistance: Math.abs(i3) }), this.getProjectedFreeSpaceAlongDirection({ ...e51, direction: { x: Math.sign(o3), y: Math.sign(i3) }, travelDistance: me(t2, n2) }), this.getProjectedFreeSpaceAlongDirection({ ...e51, direction: { x: Math.sign(o3), y: 0 }, travelDistance: Math.abs(o3) }));\n }\n getProjectedFreeSpaceAlongDirection(e51) {\n const { sourcePoint: t2, sourceLayer: n2, sourceObstacle: o3, direction: i3, travelDistance: r3 } = e51, s2 = Math.hypot(i3.x, i3.y);\n if (s2 \u003c= lK || r3 \u003c= lK)\n return 0;\n const a3 = this.getRayProbeDistance(), c3 = i3.x / s2, l3 = i3.y / s2, h2 = { x: t2.x + c3 * a3, y: t2.y + l3 * a3 };\n let d2 = Number.POSITIVE_INFINITY;\n for (const e52 of this.ogSrj.obstacles)\n if (e52 !== o3 \u0026\u0026 e52.layers.includes(n2))\n for (const n3 of Kj(e52)) {\n const e53 = this.getRayIntersectionDistance({ rayStart: t2, rayEnd: h2, segmentStart: n3.start, segmentEnd: n3.end });\n e53 !== null \u0026\u0026 (d2 = Math.min(d2, e53));\n }\n for (const e52 of this.getBoardBoundarySegments()) {\n const n3 = this.getRayIntersectionDistance({ rayStart: t2, rayEnd: h2, segmentStart: e52.start, segmentEnd: e52.end });\n n3 !== null \u0026\u0026 (d2 = Math.min(d2, n3));\n }\n return Number.isFinite(d2) ? Math.max(0, d2 - r3) : 0;\n }\n getMinBlockingClearance(e51) {\n const { candidate: t2, connectionNetIds: n2, sourceZ: o3, targetZ: i3 } = e51, r3 = Math.min(o3, i3), s2 = Math.max(o3, i3);\n let a3 = Number.POSITIVE_INFINITY;\n for (const e52 of this.ogSrj.obstacles) {\n const n3 = this.getObstacleZs(e52);\n if (!n3.some((e53) =\u003e e53 \u003e= r3 \u0026\u0026 e53 \u003c= s2))\n continue;\n if (e52.isCopperPour \u0026\u0026 !n3.includes(o3))\n continue;\n const i4 = Oe(t2, e52) - this.viaRadius;\n if (a3 = Math.min(a3, i4), a3 + lK \u003c this.requiredViaToPadClearance)\n return a3;\n }\n return a3;\n }\n getMinPlacedEscapeViaClearance(e51) {\n let t2 = Number.POSITIVE_INFINITY;\n for (const n2 of this.createdEscapeVias) {\n const o3 = me(e51, n2) - this.viaDiameter;\n if (t2 = Math.min(t2, o3), t2 + lK \u003c this.obstacleMargin)\n return t2;\n }\n return t2;\n }\n selectPointOwner(e51) {\n const { point: t2, groupConnections: n2, matchingCopperPours: o3 } = e51, i3 = hB(t2), r3 = n2.map((e52) =\u003e ({ connection: e52, pointIndex: e52.pointsToConnect.findIndex((e53) =\u003e hB(e53) === i3) })).filter((e52) =\u003e e52.pointIndex !== -1);\n return r3.length === 0 ? null : (r3.sort((e52, t3) =\u003e {\n const n3 = o3.some((t4) =\u003e this.obstacleMatchesConnectionNet(t4, this.getConnectionNetIds(e52.connection)));\n return n3 !== o3.some((e53) =\u003e this.obstacleMatchesConnectionNet(e53, this.getConnectionNetIds(t3.connection))) ? n3 ? -1 : 1 : e52.pointIndex - t3.pointIndex;\n }), r3[0]);\n }\n findBestEscapeViaCandidate(e51) {\n const { connection: t2, point: n2, pointIndex: o3, matchingCopperPours: i3, connectionNetIds: r3, sourceObstacle: s2 } = e51;\n if (!vo(n2))\n return null;\n const a3 = n2.layer, c3 = mo(a3, this.ogSrj.layerCount), l3 = s2 ?? this.selectSourceObstacle({ point: n2, sourceLayer: a3, connectionNetIds: r3 }), h2 = this.getCandidatePositions(n2, l3);\n let d2 = null;\n for (const e52 of i3) {\n const i4 = e52.layers[0];\n if (!i4 || i4 === a3)\n continue;\n const s3 = mo(i4, this.ogSrj.layerCount), u2 = hK(e52);\n for (const p3 of h2) {\n if (!this.isInsideBoard(p3))\n continue;\n if (!oK(p3, e52))\n continue;\n if (!this.hasClearEscapePath({ sourcePoint: n2, candidate: p3, sourceLayer: a3, sourceObstacle: l3 }))\n continue;\n const h3 = this.getMinBlockingClearance({ candidate: p3, connectionNetIds: r3, sourceZ: c3, targetZ: s3 });\n if (h3 + lK \u003c this.requiredViaToPadClearance)\n continue;\n const m2 = this.getMinPlacedEscapeViaClearance(p3);\n if (m2 + lK \u003c this.obstacleMargin)\n continue;\n const g2 = this.getProjectedFreeSpace({ sourcePoint: n2, candidate: p3, sourceLayer: a3, sourceObstacle: l3 }), f2 = Math.min(g2, 3), _2 = 100 * h3 - me(n2, p3) - 0.5 * Math.abs(s3 - c3) + 2 * f2 + (Number.isFinite(m2) ? 10 * Math.min(m2, this.requiredViaToViaClearance) : 0);\n (!d2 || _2 \u003e d2.score) \u0026\u0026 (d2 = { pointId: `${cK}${t2.name}:${n2.pointId ?? `p${o3}`}:${i4}:${this.nextEscapeViaIndex++}`, x: p3.x, y: p3.y, connectionName: t2.name, rootConnectionName: t2.__rootConnectionNames?.[0] ?? t2.name, sourcePointIndex: o3, sourcePointId: n2.pointId, sourceLayer: a3, targetLayer: i4, targetPourKey: u2, score: _2 });\n }\n }\n return d2;\n }\n buildPointPlacementPlans(e51) {\n const { mergedConnection: t2, groupConnections: n2, matchingCopperPours: o3, connectionNetIds: i3 } = e51, r3 = [];\n for (const e52 of t2.pointsToConnect) {\n const t3 = this.selectPointOwner({ point: e52, groupConnections: n2, matchingCopperPours: o3 });\n if (!t3)\n continue;\n const s2 = vo(e52) ? this.selectSourceObstacle({ point: e52, sourceLayer: e52.layer, connectionNetIds: i3 }) : undefined, a3 = vo(e52) ? this.getCandidatePositions(e52, s2).length : 0;\n r3.push({ point: e52, pointOwner: t3, sourceObstacle: s2, candidateCount: a3 });\n }\n return r3.sort((e52, t3) =\u003e {\n if (e52.candidateCount !== t3.candidateCount)\n return e52.candidateCount - t3.candidateCount;\n const n3 = (e52.sourceObstacle?.width ?? 0) * (e52.sourceObstacle?.height ?? 0), o4 = (t3.sourceObstacle?.width ?? 0) * (t3.sourceObstacle?.height ?? 0);\n return n3 !== o4 ? n3 - o4 : e52.pointOwner.pointIndex - t3.pointOwner.pointIndex;\n });\n }\n _step() {\n const e51 = this.ogSrj.obstacles.filter((e52) =\u003e e52.isCopperPour), t2 = this.ogSrj.connections, n2 = t2.map((e52) =\u003e structuredClone(e52)), o3 = new Map(n2.map((e52) =\u003e [e52.name, e52])), i3 = structuredClone(this.ogSrj.obstacles), r3 = dB([...t2]);\n for (const n3 of r3) {\n const r4 = new Set(n3.__rootConnectionNames ?? [n3.name]), s2 = t2.filter((e52) =\u003e (e52.__rootConnectionNames ?? [e52.name]).some((e53) =\u003e r4.has(e53)));\n if (s2.length === 0)\n continue;\n const a3 = new Set;\n for (const e52 of s2)\n for (const t3 of this.getConnectionNetIds(e52))\n a3.add(t3);\n const c3 = e51.filter((e52) =\u003e this.obstacleMatchesConnectionNet(e52, a3));\n if (c3.length === 0)\n continue;\n const l3 = new Map, h2 = new Map, d2 = this.buildPointPlacementPlans({ mergedConnection: n3, groupConnections: s2, matchingCopperPours: c3, connectionNetIds: a3 });\n for (const { point: e52, pointOwner: t3, sourceObstacle: n4 } of d2) {\n const r5 = this.findBestEscapeViaCandidate({ connection: t3.connection, point: e52, pointIndex: t3.pointIndex, matchingCopperPours: c3, connectionNetIds: a3, sourceObstacle: n4 });\n if (!r5)\n continue;\n const s3 = o3.get(t3.connection.name);\n if (!s3)\n continue;\n if (s3.pointsToConnect.some((e53) =\u003e vo(e53) \u0026\u0026 e53.layer === r5.sourceLayer \u0026\u0026 dK(e53, r5)))\n continue;\n s3.pointsToConnect.push({ x: r5.x, y: r5.y, layer: r5.sourceLayer, pointId: r5.pointId, terminalVia: { toLayer: r5.targetLayer, viaDiameter: this.viaDiameter } }), this.escapeViaMetadataByPointId.set(r5.pointId, r5), this.createdEscapeVias.push(r5), i3.push(this.createEscapeViaObstacle({ escapeVia: r5, connectionNetIds: this.getConnectionNetIds(t3.connection) }));\n const d3 = l3.get(r5.targetPourKey);\n d3 ? d3.push(r5.pointId) : l3.set(r5.targetPourKey, [r5.pointId]), h2.has(r5.targetPourKey) || h2.set(r5.targetPourKey, t3.connection.name);\n }\n for (const [e52, t3] of l3.entries()) {\n if (t3.length \u003c= 1)\n continue;\n const n4 = h2.get(e52);\n if (!n4)\n continue;\n const i4 = o3.get(n4);\n i4 \u0026\u0026 (i4.externallyConnectedPointIds = [...i4.externallyConnectedPointIds ?? [], t3]);\n }\n }\n this.outputSrj = { ...structuredClone(this.ogSrj), connections: n2, obstacles: i3 }, this.solved = true;\n }\n getOutputSimpleRouteJson() {\n return structuredClone(this.outputSrj);\n }\n getEscapeViaMetadataByPointId() {\n return new Map(this.escapeViaMetadataByPointId);\n }\n visualize() {\n return { title: \"Escape Via Location Solver\", points: this.outputSrj.connections.flatMap((e51) =\u003e e51.pointsToConnect.map((t2) =\u003e ({ x: t2.x, y: t2.y, color: t2.pointId?.startsWith(cK) === true ? \"#0f766e\" : \"#dc2626\", label: t2.pointId?.startsWith(cK) === true ? `${e51.name}\nescape via` : e51.name }))), lines: this.createdEscapeVias.map((e51) =\u003e {\n const t2 = this.outputSrj.connections.find((t3) =\u003e t3.name === e51.connectionName)?.pointsToConnect[e51.sourcePointIndex] ?? null;\n return { points: t2 ? [{ x: t2.x, y: t2.y }, { x: e51.x, y: e51.y }] : [{ x: e51.x, y: e51.y }], strokeColor: \"#0f766e\" };\n }), circles: this.createdEscapeVias.map((e51) =\u003e ({ center: { x: e51.x, y: e51.y }, radius: this.viaRadius, strokeColor: \"#0f766e\", label: `${e51.connectionName}\n${e51.targetLayer}` })), rects: this.outputSrj.obstacles.filter((e51) =\u003e !e51.isCopperPour).map((e51) =\u003e ({ ...e51, fill: \"rgba(220,38,38,0.12)\" })) };\n }\n};\nvar mK = (e51) =\u003e ({ ...e51 });\nvar gK = (e51) =\u003e ({ ...e51, route: e51.route?.map(mK), vias: e51.vias?.map((e52) =\u003e ({ ...e52 })) });\nvar fK = (e51) =\u003e e51.map(gK);\nvar _K = \"#0000FF\";\nvar yK = 0.15;\nvar bK = 0.000001;\nvar xK = 0.1;\nvar vK = [\"top\", \"bottom\", \"left\", \"right\"];\nvar IK = (e51) =\u003e e51.x * e51.x + e51.y * e51.y;\nvar SK = (e51, t2) =\u003e ({ x: e51.x - t2.x, y: e51.y - t2.y });\nvar CK = (e51, t2, n2) =\u003e {\n const o3 = SK(n2, t2), i3 = IK(o3);\n if (i3 \u003c= bK)\n return Math.sqrt(IK(SK(e51, t2)));\n const r3 = (a3 = SK(e51, t2), c3 = o3, s2 = (a3.x * c3.x + a3.y * c3.y) / i3, Math.max(0, Math.min(1, s2)));\n var s2, a3, c3;\n const l3 = { x: t2.x + o3.x * r3, y: t2.y + o3.y * r3 };\n return Math.sqrt(IK(SK(e51, l3)));\n};\nvar PK = (e51) =\u003e e51?.z === 1 ? \"bottom\" : \"top\";\nvar MK = (e51, t2, n2) =\u003e (e51.z ?? 0) === (t2.z ?? 0) \u0026\u0026 ((t2.z ?? 0) === (n2.z ?? 0) \u0026\u0026 (e51.x === t2.x \u0026\u0026 t2.x === n2.x || e51.y === t2.y \u0026\u0026 t2.y === n2.y));\nvar wK = (e51, t2, n2) =\u003e {\n const o3 = n2?.get(e51);\n if (o3)\n return o3;\n const i3 = e51.route ?? [], r3 = e51.traceThickness ?? yK;\n let { POSITIVE_INFINITY: s2, POSITIVE_INFINITY: a3, NEGATIVE_INFINITY: c3, NEGATIVE_INFINITY: l3 } = Number, h2 = false;\n const d2 = (e52, t3, n3) =\u003e {\n s2 = Math.min(s2, e52 - n3), a3 = Math.min(a3, t3 - n3), c3 = Math.max(c3, e52 + n3), l3 = Math.max(l3, t3 + n3), h2 = true;\n }, u2 = { segments: [], segmentsByLayer: { top: [], bottom: [] }, vias: (e51.vias ?? []).map((n3) =\u003e {\n const o4 = (n3.diameter ?? e51.viaDiameter ?? 0.3) / 2;\n return d2(n3.x, n3.y, o4), { center: { x: n3.x, y: n3.y }, radius: o4, routeIndex: t2 };\n }), bounds: { minX: 0, minY: 0, maxX: 0, maxY: 0 } };\n for (let e52 = 0;e52 \u003c i3.length - 1; ) {\n const n3 = i3[e52];\n let o4 = e52 + 1, s3 = i3[o4];\n const a4 = r3 / 2;\n for (n3 \u0026\u0026 d2(n3.x, n3.y, a4), s3 \u0026\u0026 d2(s3.x, s3.y, a4);o4 \u003c i3.length - 1; ) {\n const e53 = i3[o4], t3 = i3[o4 + 1];\n if (!n3 || !e53 || !t3)\n break;\n if (PK(n3) !== PK(e53))\n break;\n if (PK(e53) !== PK(t3))\n break;\n if (!MK(n3, e53, t3))\n break;\n o4 += 1, s3 = t3, d2(t3.x, t3.y, a4);\n }\n if (!n3 || !s3) {\n e52 += 1;\n continue;\n }\n const c4 = PK(n3), l4 = { start: n3, end: s3, routeIndex: t2, pointIndex: e52, endPointIndex: o4, thickness: r3, halfThickness: a4, layer: c4, minX: Math.min(n3.x, s3.x) - a4, maxX: Math.max(n3.x, s3.x) + a4, minY: Math.min(n3.y, s3.y) - a4, maxY: Math.max(n3.y, s3.y) + a4 };\n u2.segments.push(l4), u2.segmentsByLayer[c4].push(l4), e52 = o4;\n }\n if (!h2)\n for (const e52 of i3)\n d2(e52.x, e52.y, r3 / 2);\n return u2.bounds = h2 ? { minX: s2, minY: a3, maxX: c3, maxY: l3 } : { minX: 0, minY: 0, maxX: 0, maxY: 0 }, n2?.set(e51, u2), u2;\n};\nvar NK = (e51, t2, n2) =\u003e t2.x \u003c= Math.max(e51.x, n2.x) + bK \u0026\u0026 t2.x \u003e= Math.min(e51.x, n2.x) - bK \u0026\u0026 t2.y \u003c= Math.max(e51.y, n2.y) + bK \u0026\u0026 t2.y \u003e= Math.min(e51.y, n2.y) - bK;\nvar RK = (e51, t2, n2) =\u003e (t2.y - e51.y) * (n2.x - t2.x) - (t2.x - e51.x) * (n2.y - t2.y);\nvar TK = (e51, t2, n2, o3) =\u003e ((e52, t3, n3, o4) =\u003e {\n const i3 = RK(e52, t3, n3), r3 = RK(e52, t3, o4), s2 = RK(n3, o4, e52), a3 = RK(n3, o4, t3);\n return !!(Math.abs(i3) \u003c= bK \u0026\u0026 NK(e52, n3, t3)) || !!(Math.abs(r3) \u003c= bK \u0026\u0026 NK(e52, o4, t3)) || !!(Math.abs(s2) \u003c= bK \u0026\u0026 NK(n3, e52, o4)) || !!(Math.abs(a3) \u003c= bK \u0026\u0026 NK(n3, t3, o4)) || i3 \u003e 0 != r3 \u003e 0 \u0026\u0026 s2 \u003e 0 != a3 \u003e 0;\n})(e51, t2, n2, o3) ? 0 : Math.min(CK(e51, n2, o3), CK(t2, n2, o3), CK(n2, e51, t2), CK(o3, e51, t2));\nvar EK = (e51, t2) =\u003e Math.abs(e51.x - t2.x) \u003c= bK \u0026\u0026 Math.abs(e51.y - t2.y) \u003c= bK;\nvar AK = (e51, t2) =\u003e EK(e51.start, t2.start) || EK(e51.start, t2.end) || EK(e51.end, t2.start) || EK(e51.end, t2.end);\nvar OK = (e51) =\u003e {\n if (!e51)\n return [];\n const t2 = [e51.connectionName, e51.rootConnectionName].filter((e52) =\u003e Boolean(e52));\n return Array.from(new Set(t2));\n};\nvar kK = (e51, t2) =\u003e {\n const n2 = OK(e51), o3 = OK(t2);\n return n2.length !== 0 \u0026\u0026 o3.length !== 0 \u0026\u0026 n2.some((e52) =\u003e o3.includes(e52));\n};\nvar DK = (e51, t2, n2) =\u003e e51.minX - n2 \u003c= t2.maxX \u0026\u0026 e51.maxX + n2 \u003e= t2.minX \u0026\u0026 e51.minY - n2 \u003c= t2.maxY \u0026\u0026 e51.maxY + n2 \u003e= t2.minY;\nvar LK = (e51, t2, n2) =\u003e {\n const o3 = n2 + e51.halfThickness + t2.halfThickness - bK;\n return e51.minX - n2 \u003c= t2.maxX \u0026\u0026 e51.maxX + n2 \u003e= t2.minX \u0026\u0026 e51.minY - n2 \u003c= t2.maxY \u0026\u0026 e51.maxY + n2 \u003e= t2.minY \u0026\u0026 o3 \u003e 0;\n};\nvar zK = (e51, t2, n2, o3) =\u003e {\n const i3 = o3 + n2.halfThickness + t2 - bK, r3 = e51.x - i3, s2 = e51.x + i3, a3 = e51.y - i3, c3 = e51.y + i3;\n return r3 \u003c= n2.maxX \u0026\u0026 s2 \u003e= n2.minX \u0026\u0026 a3 \u003c= n2.maxY \u0026\u0026 c3 \u003e= n2.minY;\n};\nvar BK = (e51, t2) =\u003e {\n const n2 = new WeakMap, o3 = e51.map((e52, t3) =\u003e wK(e52, t3, n2)), i3 = [], r3 = new Set, s2 = (e52) =\u003e {\n r3.has(e52.label) || (r3.add(e52.label), i3.push(e52));\n };\n for (let n3 = 0;n3 \u003c o3.length; n3 += 1) {\n const i4 = o3[n3];\n if (i4)\n for (let r4 = n3 + 1;r4 \u003c o3.length; r4 += 1) {\n const a3 = o3[r4];\n if (a3 \u0026\u0026 (!kK(e51[n3], e51[r4]) \u0026\u0026 DK(i4.bounds, a3.bounds, t2))) {\n for (const e52 of [\"top\", \"bottom\"]) {\n const o4 = i4.segmentsByLayer[e52], c3 = a3.segmentsByLayer[e52];\n for (const i5 of o4)\n for (const o5 of c3) {\n if (AK(i5, o5))\n continue;\n if (!LK(i5, o5, t2))\n continue;\n const a4 = t2 + (i5.thickness + o5.thickness) / 2 - bK;\n if (TK(i5.start, i5.end, o5.start, o5.end) \u003e= a4)\n continue;\n s2({ center: { x: (Math.max(i5.minX - t2, o5.minX - t2) + Math.min(i5.maxX + t2, o5.maxX + t2)) / 2, y: (Math.max(i5.minY - t2, o5.minY - t2) + Math.min(i5.maxY + t2, o5.maxY + t2)) / 2 }, label: `trace-violation:${n3}:s${i5.pointIndex}:${r4}:s${o5.pointIndex}:${e52}` });\n }\n }\n for (const e52 of i4.segments)\n for (const [o4, i5] of a3.vias.entries()) {\n if (!zK(i5.center, i5.radius, e52, t2))\n continue;\n const a4 = t2 + e52.halfThickness + i5.radius - bK;\n CK(i5.center, e52.start, e52.end) \u003e= a4 || s2({ center: i5.center, label: `trace-violation:${n3}:s${e52.pointIndex}:${r4}:v${o4}` });\n }\n for (const e52 of a3.segments)\n for (const [o4, a4] of i4.vias.entries()) {\n if (!zK(a4.center, a4.radius, e52, t2))\n continue;\n const i5 = t2 + e52.halfThickness + a4.radius - bK;\n CK(a4.center, e52.start, e52.end) \u003e= i5 || s2({ center: a4.center, label: `trace-violation:${n3}:v${o4}:${r4}:s${e52.pointIndex}` });\n }\n }\n }\n }\n return ((e52) =\u003e {\n const t3 = [];\n for (const n3 of e52) {\n const e53 = t3.find((e54) =\u003e {\n return t4 = e54.center, o4 = n3.center, Math.hypot(t4.x - o4.x, t4.y - o4.y) \u003c= 0.28;\n var t4, o4;\n });\n e53 ? (e53.center = { x: (e53.center.x * e53.count + n3.center.x) / (e53.count + 1), y: (e53.center.y * e53.count + n3.center.y) / (e53.count + 1) }, e53.labels.push(n3.label), e53.count += 1) : t3.push({ center: n3.center, labels: [n3.label], count: 1 });\n }\n return t3.map((e53, t4) =\u003e ({ center: e53.center, radius: Math.min(0.3, 0.2 + 0.035 * Math.sqrt(e53.count - 1)), stroke: \"#f59e0b\", fill: \"rgba(245, 158, 11, 0.46)\", label: e53.count === 1 ? e53.labels[0] : `trace-violations:${t4}:count-${e53.count}` }));\n })(i3);\n};\nvar FK = new WeakMap;\nvar jK = new WeakMap;\nvar $K = new WeakMap;\nvar YK = (e51) =\u003e {\n let t2 = FK.get(e51);\n return t2 === undefined \u0026\u0026 (t2 = e51.length \u003e 2 \u0026\u0026 e51[e51.length - 1] - e51[0] === e51.length - 1 ? `${e51[0]}..${e51[e51.length - 1]}` : e51.join(\",\"), FK.set(e51, t2)), t2;\n};\nvar XK = ({ routeIndexes: e51, layers: t2, routePointIndexes: n2 }) =\u003e `${e51[0]}:${t2[0]}:${YK(n2[0])}:${e51[1]}:${t2[1]}:${YK(n2[1])}`;\nvar HK = (e51, t2, n2, o3, i3, r3, s2) =\u003e {\n const a3 = ((e52, t3, n3, o4, i4, r4) =\u003e e52 \u003c n3 ? `${e52}:${t3}:${YK(i4)}:${n3}:${o4}:${YK(r4)}` : `${n3}:${o4}:${YK(r4)}:${e52}:${t3}:${YK(i4)}`)(t2, n2, o3, i3, r3, s2);\n e51.has(a3) || (t2 \u003c o3 ? e51.set(a3, { routeIndexes: [t2, o3], layers: [n2, i3], routePointIndexes: [r3, s2] }) : e51.set(a3, { routeIndexes: [o3, t2], layers: [i3, n2], routePointIndexes: [s2, r3] }));\n};\nvar VK = (e51) =\u003e {\n const t2 = jK.get(e51);\n if (t2)\n return t2;\n const n2 = [];\n for (let t3 = e51.pointIndex;t3 \u003c= e51.endPointIndex; t3 += 1)\n n2.push(t3);\n return jK.set(e51, n2), n2;\n};\nvar WK = (e51, t2) =\u003e !t2 || e51.some((e52) =\u003e t2.has(e52));\nvar GK = (e51, t2) =\u003e {\n const n2 = $K.get(t2);\n if (n2)\n return n2;\n const o3 = e51.route ?? [], i3 = [];\n for (let e52 = 0;e52 \u003c o3.length; e52 += 1) {\n const n3 = o3[e52];\n n3 \u0026\u0026 (Math.abs(n3.x - t2.center.x) \u003c= bK \u0026\u0026 Math.abs(n3.y - t2.center.y) \u003c= bK \u0026\u0026 i3.push(e52));\n }\n return $K.set(t2, i3), i3;\n};\nvar UK = (e51, t2, n2) =\u003e e51.minX - n2 \u003c= t2.maxX \u0026\u0026 e51.maxX + n2 \u003e= t2.minX \u0026\u0026 e51.minY - n2 \u003c= t2.maxY \u0026\u0026 e51.maxY + n2 \u003e= t2.minY;\nvar ZK = (e51, t2, n2) =\u003e {\n const o3 = n2 + e51.halfThickness + t2.halfThickness - bK;\n return e51.minX - n2 \u003c= t2.maxX \u0026\u0026 e51.maxX + n2 \u003e= t2.minX \u0026\u0026 e51.minY - n2 \u003c= t2.maxY \u0026\u0026 e51.maxY + n2 \u003e= t2.minY \u0026\u0026 o3 \u003e 0;\n};\nvar qK = (e51, t2, n2, o3) =\u003e {\n const i3 = o3 + n2.halfThickness + t2 - bK, r3 = e51.x - i3, s2 = e51.x + i3, a3 = e51.y - i3, c3 = e51.y + i3;\n return r3 \u003c= n2.maxX \u0026\u0026 s2 \u003e= n2.minX \u0026\u0026 a3 \u003c= n2.maxY \u0026\u0026 c3 \u003e= n2.minY;\n};\nvar JK = (e51, t2, n2) =\u003e {\n const o3 = n2 + e51.radius + t2.radius - bK;\n return Math.abs(e51.center.x - t2.center.x) \u003c= o3 \u0026\u0026 Math.abs(e51.center.y - t2.center.y) \u003c= o3;\n};\nvar QK = (e51, t2, n2, o3, i3) =\u003e {\n const r3 = e51.map((e52, t3) =\u003e wK(e52, t3, o3)), s2 = new Map;\n if (t2.size === 0)\n return [];\n const a3 = Array.from(t2), c3 = new Map, l3 = (e52) =\u003e {\n const t3 = c3.get(e52);\n if (t3)\n return t3;\n const o4 = r3[e52];\n if (!o4)\n return [];\n const i4 = [];\n for (let t4 = 0;t4 \u003c r3.length; t4 += 1) {\n if (t4 === e52)\n continue;\n const s3 = r3[t4];\n s3 \u0026\u0026 (UK(o4.bounds, s3.bounds, n2) \u0026\u0026 i4.push(t4));\n }\n return c3.set(e52, i4), i4;\n };\n for (const e52 of a3) {\n const o4 = r3[e52];\n if (!o4)\n continue;\n const a4 = l3(e52), c4 = i3?.get(e52);\n for (const l4 of o4.segments) {\n const o5 = VK(l4);\n if (WK(o5, c4))\n for (const c5 of a4) {\n if (e52 \u003e c5 \u0026\u0026 t2.has(c5))\n continue;\n const a5 = r3[c5];\n if (!a5)\n continue;\n const h2 = i3?.get(c5), d2 = a5.segmentsByLayer[l4.layer];\n for (const e53 of d2) {\n const t3 = VK(e53);\n if (!WK(t3, h2))\n continue;\n if (AK(l4, e53))\n continue;\n if (!ZK(l4, e53, n2))\n continue;\n const i4 = n2 + (l4.thickness + e53.thickness) / 2 - bK;\n TK(l4.start, l4.end, e53.start, e53.end) \u003c i4 \u0026\u0026 HK(s2, l4.routeIndex, l4.layer, e53.routeIndex, e53.layer, o5, t3);\n }\n }\n }\n }\n for (const o4 of a3) {\n const a4 = r3[o4];\n if (!a4)\n continue;\n const c4 = l3(o4), h2 = i3?.get(o4);\n for (const l4 of a4.vias) {\n const a5 = GK(e51[l4.routeIndex], l4);\n if (WK(a5, h2))\n for (const e52 of c4) {\n if (o4 \u003e e52 \u0026\u0026 t2.has(e52))\n continue;\n const c5 = r3[e52];\n if (!c5)\n continue;\n const h3 = i3?.get(e52);\n for (const e53 of c5.segments) {\n const t3 = VK(e53);\n if (!WK(t3, h3))\n continue;\n if (!qK(l4.center, l4.radius, e53, n2))\n continue;\n const o5 = n2 + e53.thickness / 2 + l4.radius - bK;\n CK(l4.center, e53.start, e53.end) \u003c o5 \u0026\u0026 HK(s2, e53.routeIndex, e53.layer, l4.routeIndex, \"via\", t3, a5);\n }\n }\n }\n }\n for (const t3 of a3) {\n const o4 = r3[t3];\n if (!o4)\n continue;\n const a4 = l3(t3), c4 = i3?.get(t3);\n for (const t4 of o4.segments) {\n const o5 = VK(t4);\n if (WK(o5, c4))\n for (const c5 of a4) {\n const a5 = r3[c5];\n if (!a5)\n continue;\n const l4 = i3?.get(c5);\n for (const i4 of a5.vias) {\n const r4 = GK(e51[i4.routeIndex], i4);\n if (!WK(r4, l4))\n continue;\n if (!qK(i4.center, i4.radius, t4, n2))\n continue;\n const a6 = n2 + t4.thickness / 2 + i4.radius - bK;\n CK(i4.center, t4.start, t4.end) \u003c a6 \u0026\u0026 HK(s2, t4.routeIndex, t4.layer, i4.routeIndex, \"via\", o5, r4);\n }\n }\n }\n }\n for (const o4 of a3) {\n const a4 = r3[o4];\n if (!a4)\n continue;\n const c4 = l3(o4), h2 = i3?.get(o4);\n for (const l4 of a4.vias) {\n const a5 = GK(e51[l4.routeIndex], l4);\n if (WK(a5, h2))\n for (const h3 of c4) {\n if (o4 \u003e h3 \u0026\u0026 t2.has(h3))\n continue;\n const c5 = r3[h3];\n if (!c5)\n continue;\n const d2 = i3?.get(h3);\n for (const t3 of c5.vias) {\n const o5 = GK(e51[t3.routeIndex], t3);\n if (!WK(o5, d2))\n continue;\n if (!JK(l4, t3, n2))\n continue;\n const i4 = n2 + l4.radius + t3.radius - bK;\n Math.hypot(l4.center.x - t3.center.x, l4.center.y - t3.center.y) \u003c i4 \u0026\u0026 HK(s2, l4.routeIndex, \"via\", t3.routeIndex, \"via\", a5, o5);\n }\n }\n }\n }\n return Array.from(s2.values());\n};\nvar KK = (e51, t2) =\u003e e51.x \u003e= t2.minX - bK \u0026\u0026 e51.x \u003c= t2.maxX + bK \u0026\u0026 e51.y \u003e= t2.minY - bK \u0026\u0026 e51.y \u003c= t2.maxY + bK;\nvar e0 = (e51, t2, n2) =\u003e {\n switch (t2) {\n case \"left\":\n return { minX: e51.minX, maxX: e51.minX + n2, minY: e51.minY, maxY: e51.maxY };\n case \"right\":\n return { minX: e51.maxX - n2, maxX: e51.maxX, minY: e51.minY, maxY: e51.maxY };\n case \"top\":\n return { minX: e51.minX, maxX: e51.maxX, minY: e51.maxY - n2, maxY: e51.maxY };\n case \"bottom\":\n return { minX: e51.minX, maxX: e51.maxX, minY: e51.minY, maxY: e51.minY + n2 };\n }\n};\nvar t0 = (e51, t2, n2) =\u003e {\n const o3 = t2.x - e51.x, i3 = t2.y - e51.y;\n let r3 = 0, s2 = 1;\n const a3 = (e52, t3) =\u003e {\n if (Math.abs(e52) \u003c= bK)\n return t3 \u003e= -0.000001;\n const n3 = t3 / e52;\n return e52 \u003c 0 ? !(n3 \u003e s2) \u0026\u0026 (n3 \u003e r3 \u0026\u0026 (r3 = n3), true) : !(n3 \u003c r3) \u0026\u0026 (n3 \u003c s2 \u0026\u0026 (s2 = n3), true);\n };\n if (!(a3(-o3, e51.x - n2.minX) \u0026\u0026 a3(o3, n2.maxX - e51.x) \u0026\u0026 a3(-i3, e51.y - n2.minY) \u0026\u0026 a3(i3, n2.maxY - e51.y)))\n return 0;\n const c3 = Math.hypot(o3, i3);\n return Math.max(0, s2 - r3) * c3;\n};\nvar n0 = (e51, t2) =\u003e vK.filter((n2) =\u003e {\n switch (n2) {\n case \"left\":\n return Math.abs(e51.x - t2.minX) \u003c= bK;\n case \"right\":\n return Math.abs(e51.x - t2.maxX) \u003c= bK;\n case \"top\":\n return Math.abs(e51.y - t2.maxY) \u003c= bK;\n case \"bottom\":\n return Math.abs(e51.y - t2.minY) \u003c= bK;\n }\n return false;\n});\nvar o0 = (e51, t2) =\u003e {\n const n2 = [];\n return e51.x \u003c t2.minX - bK \u0026\u0026 n2.push(\"left\"), e51.x \u003e t2.maxX + bK \u0026\u0026 n2.push(\"right\"), e51.y \u003e t2.maxY + bK \u0026\u0026 n2.push(\"top\"), e51.y \u003c t2.minY - bK \u0026\u0026 n2.push(\"bottom\"), n2;\n};\nvar i0 = (e51, t2, n2) =\u003e {\n const o3 = t2.x - e51.x, i3 = t2.y - e51.y;\n switch (n2) {\n case \"left\":\n case \"right\":\n return Math.abs(o3) \u003c= bK \u0026\u0026 Math.abs(i3) \u003e bK;\n case \"top\":\n case \"bottom\":\n return Math.abs(i3) \u003c= bK \u0026\u0026 Math.abs(o3) \u003e bK;\n }\n};\nvar r0 = (e51, t2, n2) =\u003e {\n const o3 = [], i3 = Math.max(n2, bK), r3 = Math.min(0.1, i3 / 4);\n for (let n3 = 0;n3 \u003c e51.length; n3 += 1) {\n const s2 = e51[n3], a3 = s2?.route ?? [];\n for (let e52 = 0;e52 \u003c a3.length - 1; e52 += 1) {\n const c3 = a3[e52], l3 = a3[e52 + 1];\n if (!c3 || !l3)\n continue;\n const h2 = o0(c3, t2), d2 = o0(l3, t2), u2 = n0(c3, t2), p3 = n0(l3, t2), m2 = vK.filter((e53) =\u003e {\n if (s2.connectedPadSides?.includes(e53))\n return false;\n return !(t0(c3, l3, e0(t2, e53, i3)) \u003c= r3) \u0026\u0026 !!i0(c3, l3, e53);\n }), g2 = !KK(c3, t2) || !KK(l3, t2), f2 = Array.from(new Set([...m2, ...h2, ...d2]));\n (g2 || f2.length !== 0) \u0026\u0026 o3.push({ routeIndex: n3, connectionName: s2.connectionName ?? s2.rootConnectionName ?? `route-${n3}`, segmentIndex: e52, touchedSides: f2, startSides: u2, endSides: p3, start: c3, end: l3 });\n }\n }\n return o3;\n};\nvar s0 = (e51) =\u003e e51?.center \u0026\u0026 e51.width \u0026\u0026 e51.height ? { minX: e51.center.x - e51.width / 2, maxX: e51.center.x + e51.width / 2, minY: e51.center.y - e51.height / 2, maxY: e51.center.y + e51.height / 2, width: e51.width, height: e51.height, center: e51.center } : null;\nvar a0 = (e51) =\u003e e51 === \"bottom\" ? _K : \"#FF0000\";\nvar c0 = (e51) =\u003e {\n const t2 = e51.route ?? [], n2 = [];\n if (t2.length \u003c 2)\n return n2;\n let o3 = PK(t2[0]), i3 = [t2[0]];\n for (let r3 = 1;r3 \u003c t2.length; r3 += 1) {\n const s2 = t2[r3], a3 = PK(s2);\n a3 === o3 ? i3.push(s2) : (i3.length \u003e= 2 \u0026\u0026 n2.push({ points: i3, strokeColor: a0(o3), strokeWidth: e51.traceThickness ?? yK, label: e51.connectionName ?? \"route\" }), o3 = a3, i3 = [t2[r3 - 1], s2]);\n }\n return i3.length \u003e= 2 \u0026\u0026 n2.push({ points: i3, strokeColor: a0(o3), strokeWidth: e51.traceThickness ?? yK, label: e51.connectionName ?? \"route\" }), n2;\n};\nvar l0 = (e51) =\u003e {\n const t2 = gK(e51), n2 = t2.route ?? [], o3 = t2.vias ?? [];\n for (let e52 = 1;e52 \u003c n2.length; e52++) {\n const i3 = n2[e52 - 1], r3 = n2[e52];\n if ((i3.z ?? 0) === (r3.z ?? 0))\n continue;\n if (i3.x !== r3.x || i3.y !== r3.y)\n throw new Error(\"Node repair requires coincident via transition endpoints\");\n let s2 = -1, a3 = 0.001;\n for (let e53 = 0;e53 \u003c o3.length; e53++) {\n const t3 = o3[e53], n3 = Math.hypot(t3.x - i3.x, t3.y - i3.y);\n n3 \u003c= a3 \u0026\u0026 (s2 = e53, a3 = n3);\n }\n s2 === -1 ? o3.push({ x: i3.x, y: i3.y, diameter: t2.viaDiameter }) : o3[s2] = { ...o3[s2], x: i3.x, y: i3.y };\n }\n return (o3.length || t2.vias) \u0026\u0026 (t2.vias = o3), t2;\n};\nvar h0 = class {\n scenes = new WeakMap;\n retainedBytes = 0;\n maximumBytes = 33554432;\n getCandidatePairs(e51, t2, n2, o3, i3) {\n if (!Number.isFinite(i3) || i3 \u003c 0)\n return;\n const r3 = o3[n2];\n for (const e52 of r3)\n if (!Number.isFinite(e52.start.x) || !Number.isFinite(e52.start.y) || !Number.isFinite(e52.end.x) || !Number.isFinite(e52.end.y) || !Number.isFinite(e52.radius) || e52.radius \u003c 0)\n return;\n let s2 = this.scenes.get(e51), a3 = s2?.get(n2);\n if (a3?.fixedRoutes !== t2 \u0026\u0026 (a3 = undefined), !a3) {\n let i4 = 0, r4 = 1;\n for (let e52 = 0;e52 \u003c o3.length; e52++)\n if (e52 !== n2)\n for (let t3 = 0;t3 \u003c o3[e52].length; t3++) {\n const n3 = o3[e52][t3];\n if (!Number.isFinite(n3.start.x) || !Number.isFinite(n3.start.y) || !Number.isFinite(n3.end.x) || !Number.isFinite(n3.end.y) || !Number.isFinite(n3.radius) || n3.radius \u003c 0)\n return;\n r4 = Math.max(r4, Math.abs(n3.start.x), Math.abs(n3.start.y), Math.abs(n3.end.x), Math.abs(n3.end.y), n3.radius), i4++;\n }\n if (i4 \u003c 32)\n return;\n const c4 = new E2(i4), l3 = new Uint32Array(i4), h2 = new Uint32Array(i4);\n let d2 = 0;\n for (let e52 = 0;e52 \u003c o3.length; e52++)\n if (e52 !== n2)\n for (let t3 = 0;t3 \u003c o3[e52].length; t3++) {\n const n3 = o3[e52][t3], i5 = Math.min(n3.start.x, n3.end.x) - n3.radius, r5 = Math.min(n3.start.y, n3.end.y) - n3.radius, s3 = Math.max(n3.start.x, n3.end.x) + n3.radius, a4 = Math.max(n3.start.y, n3.end.y) + n3.radius;\n if (!(Number.isFinite(i5) \u0026\u0026 Number.isFinite(r5) \u0026\u0026 Number.isFinite(s3) \u0026\u0026 Number.isFinite(a4)))\n return;\n c4.add(i5, r5, s3, a4), l3[d2] = e52, h2[d2] = t3, d2++;\n }\n c4.finish(), a3 = { index: c4, routeIndexes: l3, copperIndexes: h2, maxMagnitude: r4, fixedRoutes: t2, queries: [], queryHitCount: 0 };\n const u2 = c4.data.byteLength + l3.byteLength + h2.byteLength;\n this.retainedBytes + u2 \u003e this.maximumBytes \u0026\u0026 (this.scenes = new WeakMap, this.retainedBytes = 0, s2 = undefined), u2 \u003c= this.maximumBytes \u0026\u0026 (s2 || (s2 = new Map, this.scenes.set(e51, s2)), s2.set(n2, a3), this.retainedBytes += u2);\n }\n const c3 = new Map;\n for (let e52 = 0;e52 \u003c r3.length; e52++) {\n const t3 = r3[e52], o4 = i3 + t3.radius, s3 = 8 * Number.EPSILON * (a3.maxMagnitude + Math.abs(t3.start.x) + Math.abs(t3.start.y) + Math.abs(t3.end.x) + Math.abs(t3.end.y) + o4 + 1);\n if (!Number.isFinite(s3 + o4))\n return;\n const l3 = Math.min(t3.start.x, t3.end.x) - o4 - s3, h2 = Math.min(t3.start.y, t3.end.y) - o4 - s3, d2 = Math.max(t3.start.x, t3.end.x) + o4 + s3, u2 = Math.max(t3.start.y, t3.end.y) + o4 + s3, p3 = a3.queries[e52];\n let m2;\n if (p3 \u0026\u0026 p3.minX === l3 \u0026\u0026 p3.minY === h2 \u0026\u0026 p3.maxX === d2 \u0026\u0026 p3.maxY === u2)\n m2 = p3.hits;\n else {\n m2 = a3.index.search(l3, h2, d2, u2).sort((e53, t5) =\u003e e53 - t5);\n const t4 = a3.queryHitCount - (p3?.hits.length ?? 0) + m2.length;\n t4 \u003c= 65536 \u0026\u0026 (a3.queries[e52] = { minX: l3, minY: h2, maxX: d2, maxY: u2, hits: m2 }, a3.queryHitCount = t4);\n }\n for (const t4 of m2) {\n const o5 = a3.routeIndexes[t4], i4 = a3.copperIndexes[t4];\n let r4 = c3.get(o5);\n r4 || (r4 = [], c3.set(o5, r4));\n const s4 = o5 \u003c n2 ? i4 : e52, l4 = o5 \u003c n2 ? e52 : i4;\n (r4[s4] ??= []).push(l4);\n }\n }\n return c3;\n }\n};\nvar d0 = (e51) =\u003e {\n const t2 = e51.route ?? [], n2 = [];\n for (let o3 = 1;o3 \u003c t2.length; o3++) {\n const i3 = t2[o3 - 1], r3 = t2[o3];\n (i3.z ?? 0) === (r3.z ?? 0) \u0026\u0026 n2.push({ start: i3, end: r3, minX: Math.min(i3.x, r3.x), minY: Math.min(i3.y, r3.y), maxX: Math.max(i3.x, r3.x), maxY: Math.max(i3.y, r3.y), magnitude: 1 + Math.abs(i3.x) + Math.abs(i3.y) + Math.abs(r3.x) + Math.abs(r3.y), radius: (e51.traceThickness ?? yK) / 2, minZ: i3.z ?? 0, maxZ: i3.z ?? 0, indexes: [o3 - 1, o3], via: false });\n }\n for (const [o3, i3] of (e51.vias ?? []).entries()) {\n const r3 = t2.flatMap((e52, t3) =\u003e e52.x === i3.x \u0026\u0026 e52.y === i3.y ? [t3] : []), s2 = r3.map((e52) =\u003e t2[e52].z ?? 0);\n n2.push({ start: i3, end: i3, minX: i3.x, minY: i3.y, maxX: i3.x, maxY: i3.y, magnitude: 1 + 2 * (Math.abs(i3.x) + Math.abs(i3.y)), radius: (i3.diameter ?? e51.viaDiameter ?? 0.3) / 2, minZ: s2.length ? Math.min(...s2) : 0, maxZ: s2.length ? Math.max(...s2) : 1, indexes: r3, via: true, viaIndex: o3 });\n }\n return n2;\n};\nvar u0 = (e51, t2, n2, o3 = [], i3, r3 = new WeakMap, s2 = new h0, a3 = new WeakMap, c3 = new WeakMap) =\u003e {\n const l3 = [...e51, ...o3], h2 = l3.map((e52) =\u003e {\n let t3 = r3.get(e52);\n return t3 || (t3 = d0(e52), r3.set(e52, t3)), t3;\n }), d2 = i3 ? s2.getCandidatePairs(i3.routes, o3, i3.changedRoute, h2, t2) : undefined, u2 = i3 ? i3.evaluation.conflicts.filter((e52) =\u003e e52.firstRoute !== i3.changedRoute \u0026\u0026 e52.secondRoute !== i3.changedRoute) : [];\n let p3 = u2.reduce((e52, t3) =\u003e e52 + t3.penetration ** 2, 0);\n for (let o4 = 0;o4 \u003c e51.length \u0026\u0026 !(i3 \u0026\u0026 o4 \u003e i3.changedRoute); o4++) {\n const r4 = e51[o4];\n let s3 = c3.get(r4);\n if (s3 || (s3 = new Set([r4.connectionName, r4.rootConnectionName].filter(Boolean)), c3.set(r4, s3)), !i3 || o4 === i3.changedRoute) {\n const e52 = h2[o4].filter((e53) =\u003e e53.via);\n for (let n3 = 0;n3 \u003c e52.length; n3++) {\n const i4 = e52[n3];\n for (let r5 = n3 + 1;r5 \u003c e52.length; r5++) {\n const s4 = e52[r5];\n if (i4.maxZ \u003c s4.minZ || s4.maxZ \u003c i4.minZ)\n continue;\n const a4 = Math.hypot(i4.start.x - s4.start.x, i4.start.y - s4.start.y);\n if (a4 === 0)\n continue;\n const c4 = t2 + i4.radius + s4.radius - a4;\n c4 \u003c= bK || (u2.push({ key: `${o4}:vias:${n3}:${r5}`, firstRoute: o4, secondRoute: o4, first: i4, second: s4, penetration: c4 }), p3 += c4 ** 2);\n }\n }\n for (const [e53, i4] of n2.entries()) {\n if (i4.connectedTo?.some((e54) =\u003e s3.has(e54)))\n continue;\n let n3, r5 = a3.get(i4);\n !r5 \u0026\u0026 i4.center \u0026\u0026 i4.width !== undefined \u0026\u0026 i4.height !== undefined \u0026\u0026 i4.width \u003e= 0 \u0026\u0026 i4.height \u003e= 0 \u0026\u0026 (r5 = { minX: i4.center.x - i4.width / 2, minY: i4.center.y - i4.height / 2, maxX: i4.center.x + i4.width / 2, maxY: i4.center.y + i4.height / 2, magnitude: Math.abs(i4.center.x) + Math.abs(i4.center.y) + Math.abs(i4.width) + Math.abs(i4.height) }, a3.set(i4, r5));\n for (const s4 of h2[o4]) {\n if (i4.zLayers \u0026\u0026 !i4.zLayers.some((e54) =\u003e e54 \u003e= s4.minZ \u0026\u0026 e54 \u003c= s4.maxZ))\n continue;\n if (r5 \u0026\u0026 t2 + s4.radius \u003e= 0) {\n const e54 = t2 + s4.radius, n4 = 32 * Number.EPSILON * (s4.magnitude + r5.magnitude + Math.abs(e54));\n if (s4.minX \u003e r5.maxX + e54 + n4 || s4.maxX \u003c r5.minX - e54 - n4 || s4.minY \u003e r5.maxY + e54 + n4 || s4.maxY \u003c r5.minY - e54 - n4)\n continue;\n }\n const a4 = t2 - p0(s4, i4);\n a4 \u003c= bK || a4 \u003c= (n3?.penetration ?? 0) || (n3 = { key: `${o4}:pad:${e53}`, firstRoute: o4, secondRoute: -1, first: s4, second: s4, penetration: a4 });\n }\n n3 \u0026\u0026 (u2.push(n3), p3 += n3.penetration ** 2);\n }\n }\n const m2 = i3 \u0026\u0026 o4 !== i3.changedRoute, g2 = m2 ? i3.changedRoute : o4 + 1, f2 = m2 ? i3.changedRoute + 1 : l3.length;\n for (let e52 = g2;e52 \u003c f2; e52++) {\n const n3 = l3[e52], r5 = s3.has(n3.connectionName) || s3.has(n3.rootConnectionName), a4 = new Map, c4 = d2?.get(o4 === i3?.changedRoute ? e52 : o4);\n if (d2 \u0026\u0026 !c4)\n continue;\n const m3 = h2[o4], g3 = h2[e52];\n for (let n4 = 0;n4 \u003c m3.length; n4++) {\n const i4 = m3[n4], s4 = c4?.[n4];\n if (d2 \u0026\u0026 !s4)\n continue;\n const l4 = s4 ? s4.length : g3.length;\n for (let n5 = 0;n5 \u003c l4; n5++) {\n const c5 = g3[s4 ? s4[n5] : n5];\n if (r5 \u0026\u0026 (!i4.via || !c5.via))\n continue;\n if (i4.maxZ \u003c c5.minZ || c5.maxZ \u003c i4.minZ)\n continue;\n if (r5 \u0026\u0026 i4.start.x === c5.start.x \u0026\u0026 i4.start.y === c5.start.y)\n continue;\n const l5 = t2 + i4.radius + c5.radius;\n if (Math.min(i4.start.x, i4.end.x) \u003e Math.max(c5.start.x, c5.end.x) + l5 || Math.min(c5.start.x, c5.end.x) \u003e Math.max(i4.start.x, i4.end.x) + l5 || Math.min(i4.start.y, i4.end.y) \u003e Math.max(c5.start.y, c5.end.y) + l5 || Math.min(c5.start.y, c5.end.y) \u003e Math.max(i4.start.y, i4.end.y) + l5)\n continue;\n const h3 = l5 - TK(i4.start, i4.end, c5.start, c5.end);\n if (h3 \u003c= bK)\n continue;\n const d3 = `${i4.via ? `via:${i4.viaIndex}` : `trace:${i4.minZ}`}:${c5.via ? `via:${c5.viaIndex}` : `trace:${c5.minZ}`}`;\n h3 \u003c= (a4.get(d3)?.penetration ?? 0) || a4.set(d3, { key: `${o4}:${e52}:${d3}`, firstRoute: o4, secondRoute: e52, first: i4, second: c5, penetration: h3 });\n }\n }\n for (const e53 of a4.values())\n u2.push(e53), p3 += e53.penetration ** 2;\n }\n }\n return u2.sort((e52, t3) =\u003e t3.penetration - e52.penetration), { conflicts: u2, score: p3 };\n};\nvar p0 = (e51, t2) =\u003e {\n if (!t2.center || t2.width === undefined || t2.height === undefined)\n return 1 / 0;\n const n2 = t2.center.x - t2.width / 2, o3 = t2.center.x + t2.width / 2, i3 = t2.center.y - t2.height / 2, r3 = t2.center.y + t2.height / 2;\n let s2 = 0;\n for (const t3 of [e51.start, e51.end])\n t3.x \u003e= n2 \u0026\u0026 t3.x \u003c= o3 \u0026\u0026 t3.y \u003e= i3 \u0026\u0026 t3.y \u003c= r3 \u0026\u0026 (s2 = Math.max(s2, e51.radius + Math.min(t3.x - n2, o3 - t3.x, t3.y - i3, r3 - t3.y)));\n if (s2 \u003e 0)\n return -s2;\n const a3 = [{ x: n2, y: i3 }, { x: o3, y: i3 }, { x: o3, y: r3 }, { x: n2, y: r3 }];\n return Math.min(...a3.map((t3, n3) =\u003e TK(e51.start, e51.end, t3, a3[(n3 + 1) % 4]))) - e51.radius;\n};\nvar m0 = (e51, t2) =\u003e {\n const n2 = d0(e51).filter((e52) =\u003e !t2.zLayers || t2.zLayers.some((t3) =\u003e t3 \u003e= e52.minZ \u0026\u0026 t3 \u003c= e52.maxZ));\n return Math.min(...n2.map((e52) =\u003e p0(e52, t2)));\n};\nvar g0 = (e51, t2, n2, o3, i3) =\u003e {\n const r3 = gK(e51), s2 = r3.route ?? [], a3 = e51.route ?? [], c3 = (e52) =\u003e e52 === 0 || e52 === s2.length - 1, l3 = new Set;\n for (const e52 of t2.indexes) {\n if (c3(e52))\n continue;\n const t3 = a3[e52];\n a3.forEach((e53, n3) =\u003e {\n e53.x === t3.x \u0026\u0026 e53.y === t3.y \u0026\u0026 l3.add(n3);\n });\n }\n if (!([...l3].some(c3) || t2.via \u0026\u0026 t2.indexes.some(c3))) {\n if (l3.size === 0) {\n if (t2.via || t2.indexes.length !== 2)\n return;\n const [e52, i4] = t2.indexes, r4 = s2[e52], a4 = s2[i4], c4 = [0.25, 0.75].map((e53) =\u003e ({ ...r4, x: r4.x + (a4.x - r4.x) * e53 + n2, y: r4.y + (a4.y - r4.y) * e53 + o3 }));\n s2.splice(i4, 0, ...c4);\n } else {\n for (const e52 of l3)\n s2[e52].x += n2, s2[e52].y += o3;\n for (const e52 of r3.vias ?? [])\n [...l3].some((t3) =\u003e a3[t3].x === e52.x \u0026\u0026 a3[t3].y === e52.y) \u0026\u0026 (e52.x += n2, e52.y += o3);\n }\n if (!s2.some((e52, t3) =\u003e t3 \u003e 0 \u0026\u0026 t3 \u003c s2.length - 1 \u0026\u0026 (e52.x \u003c i3.minX || e52.x \u003e i3.maxX || e52.y \u003c i3.minY || e52.y \u003e i3.maxY)))\n return r3;\n }\n};\nvar f0 = (e51) =\u003e {\n const t2 = [], n2 = e51.route ?? [];\n for (let o3 = 1;o3 \u003c n2.length; o3++) {\n const i3 = n2[o3 - 1], r3 = n2[o3];\n (i3.z ?? 0) === (r3.z ?? 0) \u0026\u0026 t2.push({ start: i3, end: r3, radius: (e51.traceThickness ?? yK) / 2, minZ: i3.z ?? 0, maxZ: i3.z ?? 0 });\n }\n for (const o3 of e51.vias ?? []) {\n let i3 = 1 / 0, r3 = -1 / 0;\n for (let e52 = 1;e52 \u003c n2.length; e52++) {\n const t3 = n2[e52 - 1], s2 = n2[e52];\n Math.hypot(t3.x - o3.x, t3.y - o3.y) \u003e 0.001 || Math.hypot(s2.x - o3.x, s2.y - o3.y) \u003e 0.001 || t3.z === s2.z || (i3 = Math.min(i3, t3.z ?? 0, s2.z ?? 0), r3 = Math.max(r3, t3.z ?? 0, s2.z ?? 0));\n }\n t2.push({ start: o3, end: o3, radius: (o3.diameter ?? e51.viaDiameter ?? 0.3) / 2, minZ: i3 === 1 / 0 ? 0 : i3, maxZ: r3 === -1 / 0 ? 1 : r3 });\n }\n return t2;\n};\nvar _0 = (e51, t2) =\u003e {\n let n2 = 1 / 0;\n for (const o3 of e51)\n o3.maxZ \u003c t2.minZ || t2.maxZ \u003c o3.minZ || (n2 = Math.min(n2, TK(o3.start, o3.end, t2.start, t2.end) - o3.radius - t2.radius));\n return n2;\n};\nvar y0 = class {\n constructor(e51, t2, n2 = []) {\n this.minimumClearance = t2, this.obstacles = n2, this.fixedCopper = e51.map((e52) =\u003e ({ route: e52, copper: f0(e52) }));\n }\n fixedCopper;\n cache = new WeakMap;\n allows(e51, t2, n2, o3 = true) {\n if (o3 \u0026\u0026 ((e52, t3, n3) =\u003e {\n const o4 = new Map(u0(e52, n3, []).conflicts.map((e53) =\u003e [e53.key, e53.penetration]));\n return u0(t3, n3, []).conflicts.some((e53) =\u003e e53.penetration \u003e (o4.get(e53.key) ?? 0) + bK);\n })(e51, t2, this.minimumClearance))\n return false;\n if (this.fixedCopper.length === 0 \u0026\u0026 this.obstacles.length === 0)\n return true;\n for (const o4 of n2) {\n const n3 = e51[o4], i3 = t2[o4];\n if (n3 === i3)\n continue;\n const r3 = this.cache.get(n3) ?? f0(n3), s2 = this.cache.get(i3) ?? f0(i3);\n this.cache.set(n3, r3), this.cache.set(i3, s2);\n const a3 = new Set([n3.connectionName, n3.rootConnectionName].filter(Boolean));\n for (const e52 of this.obstacles) {\n if (e52.connectedTo?.some((e53) =\u003e a3.has(e53)))\n continue;\n const t3 = m0(i3, e52);\n if (t3 \u003e= this.minimumClearance - bK)\n continue;\n const o5 = m0(n3, e52);\n if (t3 \u003c Math.min(o5, this.minimumClearance) - bK)\n return false;\n }\n for (const e52 of this.fixedCopper)\n if (!a3.has(e52.route.connectionName) \u0026\u0026 !a3.has(e52.route.rootConnectionName))\n for (const t3 of e52.copper) {\n const e53 = _0(s2, t3);\n if (e53 \u003e= this.minimumClearance - bK)\n continue;\n const n4 = _0(r3, t3);\n if (e53 \u003c Math.min(n4, this.minimumClearance) - bK)\n return false;\n }\n }\n return true;\n }\n};\nvar b0 = (e51, t2) =\u003e ({ title: `HighDensityRepair02 Initial State (margin=${t2})`, routes: e51 });\nvar x0 = (e51) =\u003e {\n const t2 = [];\n for (const n2 of e51) {\n const e52 = t2[t2.length - 1];\n e52 \u0026\u0026 e52.z === n2.z \u0026\u0026 EK(e52, n2) || t2.push(n2);\n }\n return t2;\n};\nvar v0 = (e51, t2, n2) =\u003e {\n const o3 = Math.max(0, e51.minX - t2.maxX, t2.minX - e51.maxX), i3 = Math.max(0, e51.minY - t2.maxY, t2.minY - e51.maxY);\n return Math.hypot(o3, i3) \u003c= n2 + bK;\n};\nvar I0 = (e51, t2) =\u003e {\n let n2 = Number.POSITIVE_INFINITY;\n for (const o3 of e51.segments)\n for (const e52 of t2.segments) {\n if (o3.layer !== e52.layer)\n continue;\n const t3 = TK(o3.start, o3.end, e52.start, e52.end) - (o3.thickness + e52.thickness) / 2;\n n2 = Math.min(n2, t3);\n }\n return n2;\n};\nvar S0 = ({ currentRoutes: e51, candidateRoutes: t2, candidateRouteIndexes: n2, maximumAllowedClearance: o3 }) =\u003e {\n const i3 = new WeakMap, r3 = new WeakMap, s2 = [], a3 = Array.from(n2).sort((e52, t3) =\u003e e52 - t3), c3 = e51.map((e52, t3) =\u003e wK(e52, t3, i3)), l3 = t2.map((e52, t3) =\u003e wK(e52, t3, r3)), h2 = new Set;\n for (const e52 of a3)\n for (let n3 = 0;n3 \u003c t2.length; n3 += 1) {\n if (n3 === e52)\n continue;\n const t3 = Math.min(e52, n3), i4 = Math.max(e52, n3), r4 = `${t3}:${i4}`;\n if (h2.has(r4))\n continue;\n h2.add(r4);\n const a4 = l3[t3], d2 = l3[i4];\n if (!a4 || !d2 || !v0(a4.bounds, d2.bounds, o3))\n continue;\n const u2 = I0(a4, d2);\n if (!Number.isFinite(u2) || u2 \u003e o3 + bK || !c3[t3] || !c3[i4])\n continue;\n const p3 = I0(c3[t3], c3[i4]);\n !Number.isFinite(p3) || u2 \u003e= p3 - bK || s2.push({ routeIndexes: [t3, i4], previousClearance: p3, nextClearance: u2 });\n }\n return s2;\n};\nvar C0 = 0.001;\nvar P0 = (e51, t2) =\u003e e51.map((e52) =\u003e {\n const n2 = e52.route ?? [];\n return n2.length === 0 ? e52 : { ...e52, route: n2.map((e53, o3) =\u003e o3 === 0 || o3 === n2.length - 1 ? ((e54, t3) =\u003e {\n const n3 = { ...e54 };\n return Math.abs(n3.x - t3.minX) \u003c= C0 ? n3.x = t3.minX : Math.abs(n3.x - t3.maxX) \u003c= C0 \u0026\u0026 (n3.x = t3.maxX), Math.abs(n3.y - t3.minY) \u003c= C0 ? n3.y = t3.minY : Math.abs(n3.y - t3.maxY) \u003c= C0 \u0026\u0026 (n3.y = t3.maxY), n3;\n })(e53, t2) : e53) };\n});\nvar M0 = (e51, t2) =\u003e Array.from(t2).flatMap((t3) =\u003e c0(e51[t3]).map((e52) =\u003e ({ ...e52, strokeColor: \"#000000\", strokeWidth: e52.strokeWidth, label: `candidate:${e52.label}` })));\nvar w0 = (e51, t2, n2, o3, i3) =\u003e {\n const r3 = \"rgba(0, 0, 0, 0)\";\n switch (t2) {\n case \"left\":\n return { center: { x: e51.minX + n2 / 2, y: e51.center.y }, width: n2, height: e51.height, stroke: r3, fill: o3, label: i3 };\n case \"right\":\n return { center: { x: e51.maxX - n2 / 2, y: e51.center.y }, width: n2, height: e51.height, stroke: r3, fill: o3, label: i3 };\n case \"top\":\n return { center: { x: e51.center.x, y: e51.maxY - n2 / 2 }, width: e51.width, height: n2, stroke: r3, fill: o3, label: i3 };\n case \"bottom\":\n return { center: { x: e51.center.x, y: e51.minY + n2 / 2 }, width: e51.width, height: n2, stroke: r3, fill: o3, label: i3 };\n }\n};\nvar N0 = ({ routes: e51, candidateRoutes: t2, candidateRouteIndexes: n2, originalRoutes: o3, boundary: i3, side: r3, margin: s2, rejected: a3, rejectionReason: c3 }) =\u003e {\n const l3 = Array.from(n2).map((e52) =\u003e t2[e52].connectionName ?? `route-${e52}`);\n return { title: a3 ? `${r3} move rejected (${c3})` : `${r3} move accepted`, routes: a3 ? e51 : t2, originalRoutes: o3, activeSide: r3, candidateRouteNames: l3, overlayLines: a3 ? M0(t2, n2) : [], overlayRects: [w0(i3, r3, s2, a3 ? \"rgba(220, 38, 38, 0.14)\" : \"rgba(16, 185, 129, 0.14)\", a3 ? `rejected:${r3}` : `accepted:${r3}`)] };\n};\nvar R0 = (e51, t2, n2, o3) =\u003e {\n const i3 = (e51?.adjacentObstacles ?? []).some((e52) =\u003e ((e53, t3, n3, o4) =\u003e {\n const i4 = ((e54) =\u003e e54.center \u0026\u0026 e54.width \u0026\u0026 e54.height ? { minX: e54.center.x - e54.width / 2, maxX: e54.center.x + e54.width / 2, minY: e54.center.y - e54.height / 2, maxY: e54.center.y + e54.height / 2 } : null)(e53);\n if (!i4)\n return false;\n switch (n3) {\n case \"left\":\n return i4.maxX \u003e= t3.minX - bK \u0026\u0026 i4.minX \u003c= t3.minX + o4 + bK;\n case \"right\":\n return i4.minX \u003c= t3.maxX + bK \u0026\u0026 i4.maxX \u003e= t3.maxX - o4 - bK;\n case \"top\":\n return i4.minY \u003c= t3.maxY + bK \u0026\u0026 i4.maxY \u003e= t3.maxY - o4 - bK;\n case \"bottom\":\n return i4.maxY \u003e= t3.minY - bK \u0026\u0026 i4.minY \u003c= t3.minY + o4 + bK;\n }\n })(e52, t2, n2, o3));\n return { hasObstacle: i3, moveAmount: i3 ? o3 : o3 / 2 };\n};\nvar T0 = ({ start: e51, end: t2, side: n2, boundary: o3, amount: i3, targetAxisValue: r3 }) =\u003e {\n const s2 = (({ side: e52, boundary: t3, amount: n3, targetAxisValue: o4 }) =\u003e {\n const i4 = o4 ?? (() =\u003e {\n switch (e52) {\n case \"left\":\n return t3.minX + n3;\n case \"right\":\n return t3.maxX - n3;\n case \"top\":\n return t3.maxY - n3;\n case \"bottom\":\n return t3.minY + n3;\n }\n })();\n switch (e52) {\n case \"left\":\n case \"right\":\n return Math.min(Math.max(i4, t3.minX), t3.maxX);\n case \"top\":\n case \"bottom\":\n return Math.min(Math.max(i4, t3.minY), t3.maxY);\n }\n })({ side: n2, boundary: o3, amount: i3, targetAxisValue: r3 });\n switch (n2) {\n case \"left\":\n case \"right\":\n return x0([e51, { x: s2, y: e51.y, z: e51.z }, { x: s2, y: t2.y, z: t2.z }, t2]);\n case \"top\":\n case \"bottom\":\n return x0([e51, { x: e51.x, y: s2, z: e51.z }, { x: t2.x, y: s2, z: t2.z }, t2]);\n }\n};\nvar E0 = (e51, t2, n2, o3, i3, r3, s2, a3 = false) =\u003e {\n const c3 = e51.route ?? [];\n if (c3.length \u003c 2 || t2.length === 0)\n return gK(e51);\n const l3 = a3 ? i3 : Math.max(i3, r3), h2 = ((e52, t3) =\u003e {\n switch (e52) {\n case \"left\":\n return { x: t3, y: 0 };\n case \"right\":\n return { x: -t3, y: 0 };\n case \"top\":\n return { x: 0, y: -t3 };\n case \"bottom\":\n return { x: 0, y: t3 };\n }\n })(o3, l3);\n if (a3 || (e51.vias?.length ?? 0) \u003e 0 || c3.length \u003e 2) {\n const n3 = gK(e51), o4 = n3.route ?? [];\n for (const e52 of t2) {\n const t3 = o4[e52];\n t3 \u0026\u0026 (o4[e52] = { ...t3, x: t3.x + h2.x, y: t3.y + h2.y });\n }\n for (const o5 of n3.vias ?? []) {\n t2.some((t3) =\u003e {\n const n4 = e51.route?.[t3];\n return !!n4 \u0026\u0026 EK(n4, o5);\n }) \u0026\u0026 (o5.x += h2.x, o5.y += h2.y);\n }\n return n3;\n }\n const d2 = gK(e51);\n if (c3.length === 2 \u0026\u0026 t2.length === 2 \u0026\u0026 t2[0] === 0 \u0026\u0026 t2[1] === 1) {\n const t3 = c3[0], i4 = c3[1];\n return gK({ ...e51, route: T0({ start: t3, end: i4, side: o3, boundary: n2, amount: l3, targetAxisValue: s2 }) });\n }\n return d2;\n};\nvar A0 = (e51, t2, n2) =\u003e {\n switch (n2) {\n case \"left\":\n return e51.x - t2.minX;\n case \"right\":\n return t2.maxX - e51.x;\n case \"top\":\n return t2.maxY - e51.y;\n case \"bottom\":\n return e51.y - t2.minY;\n }\n};\nvar O0 = (e51, t2, n2) =\u003e {\n const o3 = ((e52) =\u003e {\n const t3 = e52.route ?? [];\n if (t3.length === 0)\n return [];\n const n3 = [];\n for (let e53 = 0;e53 \u003c t3.length; e53 += 1) {\n const o4 = t3[e53];\n if (!o4)\n continue;\n e53 === 0 || e53 === t3.length - 1 || n3.push(o4);\n const i3 = t3[e53 + 1];\n i3 \u0026\u0026 n3.push({ x: (o4.x + i3.x) / 2, y: (o4.y + i3.y) / 2 });\n }\n return n3;\n })(e51);\n return o3.length === 0 ? Number.POSITIVE_INFINITY : o3.reduce((e52, o4) =\u003e Math.min(e52, A0(o4, t2, n2)), Number.POSITIVE_INFINITY);\n};\nvar k0 = (e51, t2, n2 = []) =\u003e {\n const o3 = e51.route ?? [], i3 = [], r3 = new Set, s2 = t2.length === 0 || t2.includes(\"via\");\n if (o3.length === 2)\n return [0, 1];\n const a3 = (e52) =\u003e {\n if (e52 \u003c= 0 || e52 \u003e= o3.length - 1)\n return;\n if (r3.has(e52))\n return;\n const n3 = o3[e52];\n n3 \u0026\u0026 (s2 || t2.includes(PK(n3))) \u0026\u0026 (r3.add(e52), i3.push(e52));\n };\n if (n2.length \u003e 0)\n for (const e52 of n2)\n a3(e52);\n else\n for (let e52 = 1;e52 \u003c o3.length - 1; e52 += 1)\n a3(e52);\n for (let e52 = 0;e52 \u003c i3.length; e52 += 1) {\n const t3 = i3[e52], n3 = o3[t3];\n if (n3)\n for (let e53 = 1;e53 \u003c o3.length - 1; e53 += 1) {\n if (r3.has(e53))\n continue;\n const t4 = o3[e53];\n t4 \u0026\u0026 (t4.z !== n3.z \u0026\u0026 EK(t4, n3) \u0026\u0026 (r3.add(e53), i3.push(e53)));\n }\n }\n return i3.sort((e52, t3) =\u003e e52 - t3), i3;\n};\nvar D0 = (e51, t2) =\u003e Math.max(0, ...(e51.route ?? []).map((e52) =\u003e Math.max(t2.minX - e52.x, e52.x - t2.maxX, t2.minY - e52.y, e52.y - t2.maxY, 0)));\nvar L0 = (e51, t2, n2, o3) =\u003e A0(e51, t2, n2) \u003c= o3 + bK;\nvar z0 = (e51, t2, n2, o3) =\u003e {\n const i3 = e51.route ?? [], r3 = [], s2 = new Set;\n let a3 = 1, c3 = i3.length - 2;\n for (;a3 \u003c i3.length - 1 \u0026\u0026 EK(i3[a3], i3[0]); )\n a3 += 1;\n for (;c3 \u003e 0 \u0026\u0026 EK(i3[c3], i3[i3.length - 1]); )\n c3 -= 1;\n for (let e52 = a3;e52 \u003c= c3; e52 += 1)\n L0(i3[e52], t2, n2, o3) \u0026\u0026 (s2.add(e52), r3.push(e52));\n for (let e52 = 0;e52 \u003c r3.length; e52 += 1) {\n const t3 = i3[r3[e52]];\n if (t3)\n for (let e53 = a3;e53 \u003c= c3; e53 += 1) {\n if (s2.has(e53))\n continue;\n const n3 = i3[e53];\n n3 \u0026\u0026 (n3.z !== t3.z \u0026\u0026 EK(n3, t3) \u0026\u0026 (s2.add(e53), r3.push(e53)));\n }\n }\n return r3.length === 0 \u0026\u0026 i3.length === 2 \u0026\u0026 i3.some((e52) =\u003e L0(e52, t2, n2, o3)) ? [0, 1] : (r3.sort((e52, t3) =\u003e e52 - t3), r3);\n};\nvar B0 = (e51, t2, n2) =\u003e {\n const o3 = e51.route ?? [], i3 = n2 === 0 ? o3[0] : o3[o3.length - 1];\n return i3 ? vK.filter((e52) =\u003e A0(i3, t2, e52) \u003c= bK) : [];\n};\nvar F0 = (e51, t2, n2) =\u003e {\n const o3 = e51.route ?? [], i3 = t2.route ?? [];\n if (o3.length === 0 || i3.length === 0)\n return true;\n for (const t3 of [0, -1]) {\n const o4 = B0(e51, n2, t3);\n if (o4.length === 0)\n continue;\n const r3 = t3 === 0 ? i3[0] : i3[i3.length - 1];\n if (!r3)\n return false;\n for (const e52 of o4)\n if (A0(r3, n2, e52) \u003e bK)\n return false;\n }\n return true;\n};\nvar j0 = (e51, t2) =\u003e Math.hypot(t2.x - e51.x, t2.y - e51.y);\nvar $0 = (e51, t2, n2, o3) =\u003e {\n const i3 = e51.route ?? [];\n if (i3.length === 0)\n return \"none\";\n let r3 = false;\n for (let e52 = 0;e52 \u003c i3.length; e52 += 1) {\n const s2 = i3[e52];\n if (s2 \u0026\u0026 L0(s2, t2, n2, o3)) {\n if (e52 !== 0 \u0026\u0026 e52 !== i3.length - 1)\n return \"interior\";\n r3 = true;\n }\n }\n for (let e52 = 0;e52 \u003c i3.length - 1; e52 += 1) {\n const r4 = i3[e52], s2 = i3[e52 + 1];\n if (r4 \u0026\u0026 s2 \u0026\u0026 (L0(r4, t2, n2, o3) \u0026\u0026 L0(s2, t2, n2, o3) \u0026\u0026 !(j0(r4, s2) \u003c= bK)))\n return \"interior\";\n }\n return r3 ? \"endpoint\" : \"none\";\n};\nvar Y0 = ({ currentRoutes: e51, routeIndex: t2, side: n2, moveSide: o3 = n2, boundary: i3, margin: r3, moveAmount: s2, geometryCache: a3, fixedCopperGuard: c3 }) =\u003e {\n const l3 = e51[t2], h2 = (l3.route?.length ?? 0) === 2, d2 = z0(l3, i3, n2, r3);\n if (d2.length === 0)\n return null;\n const u2 = new Set, p3 = new Map, m2 = new Set, g2 = e51.slice();\n let f2 = false, _2 = \"overlap\";\n const y2 = new Set([t2]), b2 = new Map([[t2, new Set]]), x2 = new Map([[t2, new Set]]), v2 = [t2];\n let I2 = 0, S2 = null, C = null, P = null, M = null;\n const w = (e52) =\u003e new Set(e52.map((e53) =\u003e XK(e53))), N = () =\u003e S2 || (S2 = QK(e51, u2, r3, a3, p3), S2), R2 = () =\u003e P || (P = QK(e51, u2, 0, a3, p3), P), T2 = () =\u003e M || (M = QK(g2, u2, 0, a3, p3), M);\n for (;I2 \u003c v2.length \u0026\u0026 !f2; ) {\n const c4 = v2[I2];\n if (I2 += 1, y2.delete(c4), u2.has(c4))\n continue;\n const l4 = g2[c4], h3 = Array.from(b2.get(c4) ?? []), d3 = Array.from(x2.get(c4) ?? []);\n b2.delete(c4), x2.delete(c4);\n const R3 = c4 === t2 ? z0(l4, i3, n2, r3) : k0(l4, h3, d3);\n if (R3.length === 0) {\n if (c4 === t2)\n return null;\n f2 = true, _2 = \"eventual-overlap\";\n break;\n }\n const T3 = l4.route ?? [], E3 = c4 === t2 ? undefined : o3 === \"left\" || o3 === \"right\" ? (T3[R3[0]]?.x ?? 0) + (o3 === \"left\" ? s2 : -s2) : (T3[R3[0]]?.y ?? 0) + (o3 === \"top\" ? -s2 : s2);\n g2[c4] = E0(l4, R3, i3, o3, s2, r3, E3, c4 !== t2), u2.add(c4), p3.set(c4, new Set(R3)), S2 = null, C = null, P = null, M = null, (l4.route?.length ?? 0) === 2 \u0026\u0026 m2.add(c4);\n const A2 = D0(e51[c4], i3);\n if (D0(g2[c4], i3) \u003e A2 + 0.000001) {\n f2 = true, _2 = \"boundary\";\n break;\n }\n if (!F0(e51[c4], g2[c4], i3)) {\n f2 = true, _2 = \"endpoint-boundary\";\n break;\n }\n const O2 = QK(g2, new Set([c4]), r3, a3, new Map([[c4, new Set(R3)]]));\n for (const e52 of O2) {\n if (w(N()).has(XK(e52)))\n continue;\n const [t3, n3] = e52.routeIndexes, o4 = u2.has(t3), i4 = u2.has(n3);\n if (o4 \u0026\u0026 i4)\n continue;\n const r4 = o4 ? n3 : t3, s3 = o4 ? e52.layers[1] : e52.layers[0], a4 = o4 ? e52.routePointIndexes[1] : e52.routePointIndexes[0];\n if (u2.has(r4) || y2.has(r4)) {\n if (y2.has(r4)) {\n const e53 = b2.get(r4) ?? new Set;\n e53.add(s3), b2.set(r4, e53);\n const t4 = x2.get(r4) ?? new Set;\n for (const e54 of a4)\n t4.add(e54);\n x2.set(r4, t4);\n }\n } else\n y2.add(r4), v2.push(r4), b2.set(r4, new Set([s3])), x2.set(r4, new Set(a4));\n }\n }\n if (!f2 \u0026\u0026 u2.size \u003e 1) {\n const e52 = w(N()), t3 = w(C || (C = QK(g2, u2, r3, a3, p3), C));\n for (const n3 of t3)\n if (!e52.has(n3)) {\n f2 = true, _2 = \"eventual-overlap\";\n break;\n }\n }\n if (!f2 \u0026\u0026 u2.size \u003e 1) {\n const e52 = w(R2()), t3 = w(T2());\n for (const n3 of t3)\n if (!e52.has(n3)) {\n f2 = true, _2 = \"eventual-overlap\";\n break;\n }\n }\n if (!f2) {\n const t3 = new Set(QK(e51, u2, 0, a3).map((e52) =\u003e XK(e52))), n3 = QK(g2, u2, 0, a3);\n for (const e52 of n3) {\n const n4 = XK(e52);\n if (!t3.has(n4)) {\n f2 = true, _2 = \"eventual-overlap\";\n break;\n }\n }\n }\n if (!f2) {\n const t3 = (({ currentRoutes: e52, candidateRoutes: t4, candidateRouteIndexes: n3, boundary: o4, activeSide: i4 }) =\u003e {\n const r4 = vK.filter((e53) =\u003e e53 !== i4), s3 = [];\n for (const i5 of n3) {\n const n4 = e52[i5], a4 = t4[i5];\n if (n4 \u0026\u0026 a4)\n for (const e53 of r4) {\n const t5 = O0(n4, o4, e53), r5 = O0(a4, o4, e53);\n t5 \u003e bK \u0026\u0026 r5 \u003c= bK \u0026\u0026 s3.push({ routeIndex: i5, side: e53, previousClearance: t5, nextClearance: r5 });\n }\n }\n return s3;\n })({ currentRoutes: e51, candidateRoutes: g2, candidateRouteIndexes: u2, boundary: i3, activeSide: n2 });\n t3.length \u003e 0 \u0026\u0026 (f2 = true, _2 = \"boundary-touch\");\n }\n if (!f2) {\n const t3 = (({ currentRoutes: e52, candidateRoutes: t4, candidateRouteIndexes: n3, geometryCache: o4, currentConflicts: i4, candidateConflicts: r4 }) =\u003e {\n const s3 = i4 ?? QK(e52, n3, 0, o4), a4 = r4 ?? QK(t4, n3, 0, o4), c4 = new Set(s3.map((e53) =\u003e XK(e53)));\n return a4.filter((e53) =\u003e {\n const o5 = XK(e53);\n if (c4.has(o5))\n return false;\n const [i5, r5] = e53.routeIndexes, [s4, a5] = e53.layers, l4 = n3.has(i5), h3 = n3.has(r5);\n if (l4 \u0026\u0026 h3)\n return false;\n const d3 = l4 ? a5 : s4, u3 = t4[l4 ? r5 : i5];\n return !!u3 \u0026\u0026 k0(u3, [d3]).length === 0;\n });\n })({ currentRoutes: e51, candidateRoutes: g2, candidateRouteIndexes: u2, geometryCache: a3, currentConflicts: R2(), candidateConflicts: T2() });\n t3.length \u003e 0 \u0026\u0026 (f2 = true, _2 = \"fixed-trace-touch\");\n }\n if (!f2) {\n S0({ currentRoutes: e51, candidateRoutes: g2, candidateRouteIndexes: u2, maximumAllowedClearance: Math.min(r3 / 2, xK) }).length \u003e 0 \u0026\u0026 (f2 = true, _2 = \"trace-clearance\");\n }\n return !f2 \u0026\u0026 ((e52, t3, n3, o4, i4, r4) =\u003e Array.from(n3).some((n4) =\u003e {\n const s3 = e52[n4], a4 = t3[n4];\n return vK.filter((e53) =\u003e e53 !== i4).some((e53) =\u003e {\n const t4 = $0(s3, o4, e53, r4), n5 = $0(a4, o4, e53, r4);\n return t4 === \"none\" \u0026\u0026 n5 !== \"none\";\n });\n }))(e51, g2, u2, i3, n2, r3) \u0026\u0026 (f2 = true, _2 = \"side-regression\"), f2 || !c3 || c3.allows(e51, g2, u2) || (f2 = true, _2 = \"fixed-copper-clearance\"), { isTwoPointRoute: h2, movableIndexes: d2, candidateRouteIndexes: u2, movedTwoPointRouteIndexes: m2, candidateRoutes: g2, rejected: f2, rejectionReason: _2 };\n};\nvar X0 = (e51, t2, n2, o3, i3) =\u003e {\n const r3 = e51.route ?? [];\n if (t2.length === 0)\n return null;\n if (o3 === \"top\" || o3 === \"bottom\") {\n const e52 = t2.reduce((e53, t3) =\u003e e53 + (r3[t3]?.x ?? n2.center.x), 0) / t2.length;\n return e52 \u003c n2.center.x - i3 / 2 ? \"right\" : e52 \u003e n2.center.x + i3 / 2 ? \"left\" : null;\n }\n const s2 = t2.reduce((e52, t3) =\u003e e52 + (r3[t3]?.y ?? n2.center.y), 0) / t2.length;\n return s2 \u003e n2.center.y + i3 / 2 ? \"bottom\" : s2 \u003c n2.center.y - i3 / 2 ? \"top\" : null;\n};\nvar H0 = ({ side: e51, sample: t2, boundary: n2, margin: o3, repairedRoutes: i3, frames: r3, captureProgressFrames: s2, lockedTwoPointRoutes: a3, geometryCache: c3, fixedCopperGuard: l3, allowTwoPointWithoutObstacle: h2 = false }) =\u003e {\n const { hasObstacle: d2, moveAmount: u2 } = R0(t2, n2, e51, o3);\n s2 \u0026\u0026 r3.push(((e52, t3, n3, o4, i4, r4) =\u003e ({ title: `${n3} boundary analysis: move=${i4.toFixed(3)} (${r4 ? \"obstacle-side\" : \"clear-side\"})`, routes: e52, activeSide: n3, overlayRects: [w0(t3, n3, o4, \"rgba(245, 158, 11, 0.16)\", `strip:${n3}`)] }))(fK(i3), n2, e51, o3, u2, d2));\n const p3 = new Set;\n let m2 = 0;\n for (let t3 = 0;t3 \u003c i3.length; t3 += 1) {\n if (p3.has(t3))\n continue;\n if (a3.has(t3))\n continue;\n const g2 = i3[t3];\n if (g2.connectedPadSides?.includes(e51))\n continue;\n if ((g2.route?.length ?? 0) === 2 \u0026\u0026 !d2 \u0026\u0026 !h2)\n continue;\n let f2 = Y0({ currentRoutes: i3, routeIndex: t3, side: e51, boundary: n2, margin: o3, moveAmount: u2, geometryCache: c3, fixedCopperGuard: l3 });\n if (f2) {\n if (f2.rejected) {\n const r4 = X0(g2, f2.movableIndexes, n2, e51, o3);\n if (r4) {\n const s3 = Y0({ currentRoutes: i3, routeIndex: t3, side: e51, moveSide: r4, boundary: n2, margin: o3, moveAmount: u2, geometryCache: c3, fixedCopperGuard: l3 });\n s3 \u0026\u0026 !s3.rejected \u0026\u0026 (f2 = s3);\n }\n }\n if (s2 \u0026\u0026 r3.push(N0({ routes: fK(i3), candidateRoutes: f2.candidateRoutes, candidateRouteIndexes: f2.candidateRouteIndexes, originalRoutes: f2.rejected ? undefined : Array.from(f2.candidateRouteIndexes).map((e52) =\u003e gK(i3[e52])), boundary: n2, side: e51, margin: o3, rejected: f2.rejected, rejectionReason: f2.rejectionReason })), !f2.rejected) {\n i3.splice(0, i3.length, ...f2.candidateRoutes);\n for (const e52 of f2.movedTwoPointRouteIndexes)\n a3.add(e52);\n m2 += 1;\n }\n p3.add(t3);\n }\n }\n return { movesAccepted: m2 };\n};\nvar V0 = (e51, t2, n2, o3) =\u003e L0(e51, t2, n2, o3);\nvar W0 = (e51, t2, n2, o3) =\u003e {\n switch (n2) {\n case \"left\":\n return { ...e51, x: Math.min(t2.minX + o3, t2.maxX) };\n case \"right\":\n return { ...e51, x: Math.max(t2.maxX - o3, t2.minX) };\n case \"top\":\n return { ...e51, y: Math.max(t2.maxY - o3, t2.minY) };\n case \"bottom\":\n return { ...e51, y: Math.min(t2.minY + o3, t2.maxY) };\n }\n};\nvar G0 = (e51) =\u003e `${e51.routeIndexes[0]}:${e51.layers[0]}:${e51.routeIndexes[1]}:${e51.layers[1]}`;\nvar U0 = (e51) =\u003e {\n if (!e51)\n return [];\n const t2 = [e51.connectionName, e51.rootConnectionName].filter((e52) =\u003e Boolean(e52));\n return Array.from(new Set(t2));\n};\nvar Z0 = (e51, t2) =\u003e {\n const n2 = U0(e51), o3 = U0(t2);\n return n2.length !== 0 \u0026\u0026 o3.length !== 0 \u0026\u0026 n2.some((e52) =\u003e o3.includes(e52));\n};\nvar q0 = (e51, t2, n2) =\u003e e51 ? r0([e51], t2, n2).length : 0;\nvar J0 = (e51, t2, n2, o3) =\u003e {\n const i3 = new Set(QK(e51, new Set([n2]), o3).map(XK));\n return QK(t2, new Set([n2]), o3).some((e52) =\u003e !i3.has(XK(e52)));\n};\nvar Q0 = (e51, t2, n2) =\u003e r0(e51, t2, n2).length;\nvar K0 = (e51) =\u003e {\n if (!e51)\n return [];\n const t2 = [e51.connectionName, e51.rootConnectionName].filter((e52) =\u003e Boolean(e52));\n return Array.from(new Set(t2));\n};\nvar e1 = (e51, t2) =\u003e QK(e51, new Set(e51.map((e52, t3) =\u003e t3)), xK, t2).filter((t3) =\u003e !(t3.layers[0] === \"via\" \u0026\u0026 t3.layers[1] === \"via\" || ((e52, t4) =\u003e {\n const n2 = K0(e52), o3 = K0(t4);\n return n2.length !== 0 \u0026\u0026 o3.length !== 0 \u0026\u0026 n2.some((e53) =\u003e o3.includes(e53));\n})(e51[t3.routeIndexes[0]], e51[t3.routeIndexes[1]]))).length;\nvar t1 = (e51) =\u003e {\n const t2 = vK;\n return [...t2.slice(e51 % t2.length), ...t2.slice(0, e51 % t2.length)];\n};\nvar n1 = (e51, t2, n2 = false, o3 = true) =\u003e {\n const i3 = s0(e51?.nodeWithPortPoints), r3 = (e51?.nodeHdRoutes ?? []).map(l0), s2 = Math.max(t2 ?? 0.4, 0.05), a3 = new y0(e51?.fixedHdRoutes ?? [], Math.min(s2 / 2, xK), e51?.clearanceObstacles ?? e51?.adjacentObstacles), c3 = i3 \u0026\u0026 o3 ? ((e52, t3) =\u003e e52.map((e53) =\u003e {\n const n3 = e53.route ?? [];\n let o4 = false;\n const i4 = n3.map((e54) =\u003e {\n let { x: n4, y: i5 } = e54;\n return n4 \u003c t3.minX ? n4 = t3.minX : n4 \u003e t3.maxX \u0026\u0026 (n4 = t3.maxX), i5 \u003c t3.minY ? i5 = t3.minY : i5 \u003e t3.maxY \u0026\u0026 (i5 = t3.maxY), n4 === e54.x \u0026\u0026 i5 === e54.y ? e54 : (o4 = true, { ...e54, x: n4, y: i5 });\n });\n return o4 ? { ...e53, route: i4 } : e53;\n }))(P0(fK(r3), i3), i3) : fK(r3), l3 = o3 \u0026\u0026 a3.allows(r3, c3, r3.keys()) ? c3 : r3, h2 = fK(l3);\n if (!i3)\n return { boundary: null, baseRoutes: l3, repairedRoutes: h2, margin: s2, frames: [{ title: \"HighDensityRepair02 Missing Boundary\", routes: h2 }] };\n const d2 = n2 ? [b0(fK(h2), s2)] : [];\n if (o3) {\n const t3 = new WeakMap;\n let o4 = Q0(h2, i3, s2);\n for (let r5 = 0;r5 \u003c 1; r5 += 1) {\n const c5 = new Set;\n let l4 = 0;\n for (const o5 of t1(r5)) {\n const { movesAccepted: u4 } = H0({ side: o5, sample: e51, boundary: i3, frames: d2, margin: s2, repairedRoutes: h2, captureProgressFrames: n2, lockedTwoPointRoutes: c5, geometryCache: t3, fixedCopperGuard: a3, allowTwoPointWithoutObstacle: r5 \u003e= 1 });\n l4 += u4;\n }\n const u3 = Q0(h2, i3, s2);\n if (l4 === 0)\n break;\n if (u3 === 0)\n break;\n if (u3 \u003e= o4)\n break;\n o4 = u3;\n }\n const r4 = fK(h2), c4 = e1(h2, t3);\n (({ routes: e52, boundary: t4, margin: n3, geometryCache: o5, fixedCopperGuard: i4 }) =\u003e {\n const r5 = r0(e52, t4, n3);\n if (r5.length === 0)\n return { movesAccepted: 0 };\n const s3 = new Map;\n for (const e53 of r5) {\n const t5 = s3.get(e53.routeIndex) ?? new Set;\n for (const n4 of e53.touchedSides)\n t5.add(n4);\n s3.set(e53.routeIndex, t5);\n }\n const a4 = [0.000008, 0.01, n3 / 4, n3 / 2, n3 + 0.000008];\n let c5 = 0;\n const l4 = (r6, s4, a5) =\u003e {\n const c6 = s4.route ?? [];\n if (c6.length \u003c 2)\n return false;\n const l5 = { ...s4, route: x0(c6) };\n if ((l5.route?.length ?? 0) \u003c 2)\n return false;\n const h4 = e52.slice();\n if (h4[r6] = l5, i4 \u0026\u0026 !i4.allows(e52, h4, [r6]))\n return false;\n if (q0(h4[r6], t4, n3) \u003e= a5)\n return false;\n const d4 = (t5) =\u003e Z0(e52[t5.routeIndexes[0]], e52[t5.routeIndexes[1]]), u4 = new Set(QK(e52, new Set([r6]), 0, o5).filter((e53) =\u003e !d4(e53)).map(G0));\n return !QK(h4, new Set([r6]), 0, o5).filter((e53) =\u003e !d4(e53)).some((e53) =\u003e !u4.has(G0(e53))) \u0026\u0026 !(S0({ currentRoutes: e52, candidateRoutes: h4, candidateRouteIndexes: new Set([r6]), maximumAllowedClearance: Math.min(n3 / 2, xK) }).filter((t5) =\u003e !Z0(e52[t5.routeIndexes[0]], e52[t5.routeIndexes[1]])).length \u003e 0 || (e52[r6] = l5, 0));\n }, h3 = (n4, o6, i5, r6) =\u003e {\n if (o6.length === 0)\n return false;\n for (const s4 of a4) {\n const a5 = e52[n4], c6 = gK(a5), h4 = c6.route ?? [];\n let d4 = false;\n for (const e53 of k0(a5, [], o6)) {\n const n5 = h4[e53];\n n5 \u0026\u0026 (h4[e53] = W0(n5, t4, i5, s4), d4 = true);\n }\n if (!d4)\n return false;\n if (l4(n4, c6, r6))\n return true;\n }\n return false;\n }, d3 = (e53, n4) =\u003e {\n const o6 = [];\n return n4 === \"top\" || n4 === \"bottom\" ? (Math.abs(e53.x - t4.minX) \u003c= bK \u0026\u0026 o6.push(\"left\"), Math.abs(e53.x - t4.maxX) \u003c= bK \u0026\u0026 o6.push(\"right\")) : (Math.abs(e53.y - t4.minY) \u003c= bK \u0026\u0026 o6.push(\"bottom\"), Math.abs(e53.y - t4.maxY) \u003c= bK \u0026\u0026 o6.push(\"top\")), o6;\n }, u3 = (o6, i5, r6) =\u003e {\n const s4 = e52[o6], c6 = s4.route ?? [];\n if (c6.length !== 2)\n return false;\n const [h4, u4] = c6;\n if (!V0(h4, t4, i5, n3))\n return false;\n if (!V0(u4, t4, i5, n3))\n return false;\n const p3 = d3(h4, i5), m2 = d3(u4, i5);\n for (const e53 of a4) {\n let n4 = W0(h4, t4, i5, e53), a5 = W0(u4, t4, i5, e53);\n for (const o7 of p3)\n n4 = W0(n4, t4, o7, e53);\n for (const n5 of m2)\n a5 = W0(a5, t4, n5, e53);\n const c7 = { ...s4, route: [h4, n4, a5, u4] };\n if (l4(o6, c7, r6))\n return true;\n }\n return false;\n };\n for (const [o6, i5] of s3)\n if (e52[o6])\n for (const r6 of i5) {\n let i6 = true;\n for (;i6; ) {\n i6 = false;\n const s4 = e52[o6].route ?? [];\n if (s4.length === 2) {\n const i7 = q0(e52[o6], t4, n3);\n i7 \u003e 0 \u0026\u0026 u3(o6, r6, i7) \u0026\u0026 (c5 += 1);\n break;\n }\n if (s4.length \u003c 3)\n break;\n const a5 = q0(e52[o6], t4, n3);\n if (a5 === 0)\n break;\n const l5 = [];\n for (let e53 = 1;e53 \u003c s4.length - 1; e53 += 1) {\n const o7 = s4[e53];\n o7 \u0026\u0026 V0(o7, t4, r6, n3) \u0026\u0026 l5.push(e53);\n }\n if (l5.length === 0)\n break;\n if (h3(o6, l5, r6, a5)) {\n c5 += 1, i6 = true;\n continue;\n }\n let d4 = false, p3 = a5, m2 = 0;\n for (;m2 \u003c l5.length; ) {\n let i7 = m2;\n for (;i7 + 1 \u003c l5.length \u0026\u0026 l5[i7 + 1] === l5[i7] + 1; )\n i7 += 1;\n h3(o6, l5.slice(m2, i7 + 1), r6, p3) \u0026\u0026 (c5 += 1, d4 = true, p3 = q0(e52[o6], t4, n3)), m2 = i7 + 1;\n }\n if (!d4) {\n const i7 = e52[o6].route ?? [];\n let s5 = a5;\n for (let a6 = 1;a6 \u003c i7.length - 1; a6 += 1) {\n const l6 = i7[a6];\n l6 \u0026\u0026 V0(l6, t4, r6, n3) \u0026\u0026 h3(o6, [a6], r6, s5) \u0026\u0026 (c5 += 1, d4 = true, s5 = q0(e52[o6], t4, n3));\n }\n }\n d4 \u0026\u0026 (i6 = true);\n }\n }\n for (const [o6, i5] of s3) {\n const r6 = e52[o6];\n if (!r6)\n continue;\n const s4 = r6.route ?? [];\n if (s4.length \u003c= 2)\n continue;\n const a5 = q0(e52[o6], t4, n3);\n if (a5 !== 0)\n for (const l5 of i5) {\n if (!s4.every((e53) =\u003e V0(e53, t4, l5, n3)))\n continue;\n const i6 = s4[0]?.z;\n if (!s4.every((e53) =\u003e e53.z === i6))\n continue;\n const h4 = { ...r6, route: [s4[0], s4[s4.length - 1]] }, d4 = e52[o6];\n e52[o6] = h4, u3(o6, l5, a5) ? c5 += 1 : e52[o6] = d4;\n break;\n }\n }\n })({ routes: r4, boundary: i3, margin: s2, geometryCache: t3, fixedCopperGuard: a3 });\n e1(r4, t3) \u003c= c4 \u0026\u0026 h2.splice(0, h2.length, ...r4), (({ routes: e52, boundary: t4, clearanceMargin: n3, fixedCopperGuard: o5 }) =\u003e {\n for (let i4 = 0;i4 \u003c e52.length; i4 += 1) {\n const r5 = e52[i4];\n if ((r5.route ?? []).length \u003c= 2)\n continue;\n const s3 = n3, a4 = Math.max(t4.width / 2 - bK, 0), c5 = Math.max(t4.height / 2 - bK, 0), l4 = Math.min(s3, a4), h3 = Math.min(s3, c5), d3 = r5.connectedPadSides ?? [], u3 = t4.minX + (d3.includes(\"left\") ? 0 : l4), p3 = t4.maxX - (d3.includes(\"right\") ? 0 : l4), m2 = t4.minY + (d3.includes(\"bottom\") ? 0 : h3), g2 = t4.maxY - (d3.includes(\"top\") ? 0 : h3), f2 = gK(r5), _2 = f2.route ?? [];\n let y2 = false;\n for (let e53 = 1;e53 \u003c _2.length - 1; e53 += 1) {\n const t5 = _2[e53];\n if (!t5)\n continue;\n const n4 = Math.min(Math.max(t5.x, u3), p3), o6 = Math.min(Math.max(t5.y, m2), g2);\n (Math.abs(n4 - t5.x) \u003e bK || Math.abs(o6 - t5.y) \u003e bK) \u0026\u0026 (t5.x = n4, t5.y = o6, y2 = true);\n }\n if (!y2)\n continue;\n if (f2.route = x0(_2), (f2.route?.length ?? 0) \u003c 2)\n continue;\n const b2 = fK(e52);\n b2[i4] = f2;\n const x2 = J0(e52, b2, i4, 0), v2 = J0(e52, b2, i4, n3), I2 = S0({ currentRoutes: e52, candidateRoutes: b2, candidateRouteIndexes: new Set([i4]), maximumAllowedClearance: n3 }).length \u003e 0;\n x2 || v2 || I2 || !o5.allows(e52, b2, [i4]) || (e52[i4] = f2);\n }\n })({ routes: h2, boundary: i3, clearanceMargin: s2, fixedCopperGuard: a3 });\n }\n const u2 = (({ routes: e52, fixedRoutes: t3 = [], boundary: n3, fixedCopperGuard: o4, adjacentObstacles: i4 = [], clearanceObstacles: r4 = i4, clearance: s3 = 0.1, boundaryMargin: a4 = 0.2, maxCandidates: c4 }) =\u003e {\n let l4 = e52;\n const h3 = new WeakMap, d3 = new h0, u3 = new WeakMap, p3 = new WeakMap, m2 = new WeakMap, g2 = new WeakMap;\n let f2 = u0(l4, s3, r4, t3, undefined, h3, d3, p3, g2);\n const _2 = c4 ?? Math.max(256, 96 * f2.conflicts.length), y2 = { routes: e52, initialConflictCount: f2.conflicts.length, finalConflictCount: f2.conflicts.length, candidateCount: 0 };\n for (;f2.conflicts.length \u0026\u0026 y2.candidateCount \u003c _2; ) {\n let e53 = false;\n const i5 = new Map(f2.conflicts.map((e54) =\u003e [e54.key, e54.penetration]));\n for (const c5 of f2.conflicts) {\n for (const [b2, x2] of [[c5.firstRoute, c5.first], [c5.secondRoute, c5.second]]) {\n if (b2 \u003c 0 || b2 \u003e= l4.length)\n continue;\n const v2 = l4[b2], I2 = new Set([v2.connectionName, v2.rootConnectionName].filter(Boolean)), S2 = r4.filter((e54) =\u003e !e54.connectedTo?.some((e55) =\u003e I2.has(e55))), C = h3.get(v2);\n let P = m2.get(v2);\n P === undefined \u0026\u0026 (P = r0([v2], n3, a4).length, m2.set(v2, P));\n let M = u3.get(v2);\n M || (M = new Map, u3.set(v2, M));\n const w = S2.map((e54) =\u003e {\n const t4 = M.get(e54);\n if (t4 !== undefined)\n return t4;\n const n4 = Math.min(...C.filter((t5) =\u003e !e54.zLayers || e54.zLayers.some((e55) =\u003e e55 \u003e= t5.minZ \u0026\u0026 e55 \u003c= t5.maxZ)).map((t5) =\u003e p0(t5, e54)));\n return M.set(e54, n4), n4;\n });\n for (const u4 of [1.01, 2, 4]) {\n const m3 = Math.max(0.01, c5.penetration * u4);\n for (const [c6, u5] of [[1, 0], [-1, 0], [0, 1], [0, -1], [Math.SQRT1_2, Math.SQRT1_2], [-Math.SQRT1_2, Math.SQRT1_2], [Math.SQRT1_2, -Math.SQRT1_2], [-Math.SQRT1_2, -Math.SQRT1_2]]) {\n if (y2.candidateCount \u003e= _2)\n break;\n y2.candidateCount++;\n const I3 = g0(v2, x2, c6 * m3, u5 * m3, n3);\n if (!I3)\n continue;\n if (r0([I3], n3, a4).length \u003e P)\n continue;\n const C2 = [...l4];\n C2[b2] = I3;\n const M2 = u0(C2, s3, r4, t3, { evaluation: f2, changedRoute: b2, routes: l4 }, h3, d3, p3, g2);\n if (M2.conflicts.length \u003e f2.conflicts.length || M2.score \u003e= f2.score - 0.000000000001)\n continue;\n if (M2.conflicts.some((e54) =\u003e e54.penetration \u003e (i5.get(e54.key) ?? 0) + bK))\n continue;\n if (!o4.allows(l4, C2, [b2], false))\n continue;\n const N = h3.get(I3);\n if (!S2.some((e54, t4) =\u003e Math.min(...N.filter((t5) =\u003e !e54.zLayers || e54.zLayers.some((e55) =\u003e e55 \u003e= t5.minZ \u0026\u0026 e55 \u003c= t5.maxZ)).map((t5) =\u003e p0(t5, e54))) \u003c Math.min(s3, w[t4]) - bK)) {\n l4 = C2, f2 = M2, e53 = true;\n break;\n }\n }\n if (e53 || y2.candidateCount \u003e= _2)\n break;\n }\n if (e53 || y2.candidateCount \u003e= _2)\n break;\n }\n if (e53 || y2.candidateCount \u003e= _2)\n break;\n }\n if (!e53)\n break;\n }\n return { ...y2, routes: l4, finalConflictCount: f2.conflicts.length };\n })({ fixedRoutes: e51?.fixedHdRoutes, routes: h2, boundary: i3, fixedCopperGuard: a3, adjacentObstacles: e51?.adjacentObstacles, clearanceObstacles: e51?.clearanceObstacles, boundaryMargin: s2 });\n return h2.splice(0, h2.length, ...u2.routes), d2.push(((e52, t3, n3) =\u003e ({ title: `HighDensityRepair02 Final State (margin=${n3})`, routes: e52, originalRoutes: t3 }))(fK(h2), fK(l3), s2)), { boundary: i3, baseRoutes: l3, repairedRoutes: h2, frames: d2, margin: s2, clearanceRepairStats: { nodeClearanceInitialConflictCount: u2.initialConflictCount, nodeClearanceFinalConflictCount: u2.finalConflictCount, nodeClearanceCandidateCount: u2.candidateCount } };\n};\nvar o1 = class extends BaseSolver {\n constructor(e51 = {}) {\n super(), this.params = e51, this.showBoundryViolationMarkers = e51.showBoundryViolationMarkers ?? false;\n }\n frames = [];\n traceViolationCounts = new WeakMap;\n clearanceRepairStats = {};\n currentFrameIndex = 0;\n showBoundryViolationMarkers;\n repairedRoutes = [];\n _setup() {\n this.buildFrames();\n const e51 = this.getCurrentBoundryViolationCount(), t2 = this.getCurrentTraceViolationCount();\n this.stats = { ...this.clearanceRepairStats, boundryViolationCount: e51, traceViolationCount: t2, margin: this.params.margin ?? 0.4, frames: this.frames.length, currentFrame: this.currentFrameIndex };\n }\n _step() {\n if (this.frames.length \u003c= 1) {\n const e52 = this.getCurrentBoundryViolationCount(), t3 = this.getCurrentTraceViolationCount();\n return this.showBoundryViolationMarkers = true, this.stats = { ...this.stats, boundryViolationCount: e52, traceViolationCount: t3 }, void (this.solved = true);\n }\n this.currentFrameIndex \u003c this.frames.length - 1 \u0026\u0026 (this.currentFrameIndex += 1);\n const e51 = this.getCurrentBoundryViolationCount(), t2 = this.getCurrentTraceViolationCount();\n this.stats = { ...this.clearanceRepairStats, boundryViolationCount: e51, traceViolationCount: t2, margin: this.params.margin ?? 0.4, frames: this.frames.length, currentFrame: this.currentFrameIndex, title: this.frames[this.currentFrameIndex]?.title }, this.currentFrameIndex \u003e= this.frames.length - 1 \u0026\u0026 (this.showBoundryViolationMarkers = true, this.solved = true);\n }\n getConstructorParams() {\n return [this.params];\n }\n getOutput() {\n const e51 = this.getCurrentTraceViolationCount();\n return { ...this.clearanceRepairStats, margin: this.params.margin ?? 0.4, repairedRoutes: this.repairedRoutes, frameCount: this.frames.length, traceViolationCount: e51 };\n }\n setShowBoundryViolationMarkers(e51) {\n this.showBoundryViolationMarkers = e51;\n }\n buildFrames() {\n const e51 = n1(this.params.sample, this.params.margin, this.params.captureProgressFrames ?? false, this.params.repairBoundaryDiagonals ?? true);\n this.clearanceRepairStats = e51.clearanceRepairStats ?? {}, this.frames = e51.frames, this.repairedRoutes = e51.repairedRoutes;\n }\n getCurrentFrame() {\n const e51 = this.params.sample;\n return this.frames[this.currentFrameIndex] ?? { title: \"HighDensityRepair02\", routes: fK(e51?.nodeHdRoutes ?? []) };\n }\n getBoundryViolationsForFrame(e51) {\n const t2 = s0(this.params.sample?.nodeWithPortPoints);\n return t2 ? r0(e51.routes, t2, this.params.margin ?? 0.4) : [];\n }\n getCurrentBoundryViolationCount() {\n return this.getBoundryViolationsForFrame(this.getCurrentFrame()).length;\n }\n getRouteNetNames(e51) {\n if (!e51)\n return [];\n const t2 = [e51.connectionName, e51.rootConnectionName].filter((e52) =\u003e Boolean(e52));\n return Array.from(new Set(t2));\n }\n areRoutesSameNet(e51, t2) {\n const n2 = this.getRouteNetNames(e51), o3 = this.getRouteNetNames(t2);\n return n2.length !== 0 \u0026\u0026 o3.length !== 0 \u0026\u0026 n2.some((e52) =\u003e o3.includes(e52));\n }\n getCurrentTraceViolationCount() {\n const e51 = this.getCurrentFrame(), t2 = this.traceViolationCounts.get(e51);\n if (t2 !== undefined)\n return t2;\n const n2 = e51.routes, o3 = new Set(n2.map((e52, t3) =\u003e t3)), i3 = QK(n2, o3, xK).filter((e52) =\u003e !(e52.layers[0] === \"via\" \u0026\u0026 e52.layers[1] === \"via\" || this.areRoutesSameNet(n2[e52.routeIndexes[0]], n2[e52.routeIndexes[1]]))).length;\n return this.traceViolationCounts.set(e51, i3), i3;\n }\n visualize() {\n const e51 = this.params.sample, t2 = e51?.nodeWithPortPoints, n2 = e51?.adjacentObstacles ?? [], o3 = this.getCurrentFrame(), i3 = s0(t2), r3 = i3 \u0026\u0026 t2?.capacityMeshNodeId ? [{ center: i3.center, width: i3.width, height: i3.height, stroke: \"#1d4ed8\", fill: \"rgba(29, 78, 216, 0.08)\", label: t2.capacityMeshNodeId }] : i3 ? [{ center: i3.center, width: i3.width, height: i3.height, stroke: \"#1d4ed8\", fill: \"rgba(29, 78, 216, 0.08)\", label: \"capacity-node\" }] : [], s2 = n2.filter((e52) =\u003e e52.center \u0026\u0026 e52.width \u0026\u0026 e52.height).map((e52, t3) =\u003e ({ center: e52.center, width: e52.width, height: e52.height, stroke: e52.type === \"oval\" ? \"#a855f7\" : \"#dc2626\", fill: e52.type === \"oval\" ? \"rgba(168, 85, 247, 0.12)\" : \"rgba(220, 38, 38, 0.08)\", label: e52.type ? `obstacle:${e52.type}:${t3}` : `obstacle:${t3}` })), a3 = this.showBoundryViolationMarkers \u0026\u0026 i3 ? this.getBoundryViolationsForFrame(o3).map((e52) =\u003e {\n const t3 = e52.end.x - e52.start.x, n3 = e52.end.y - e52.start.y, o4 = Math.max(Math.hypot(t3, n3), 0.2), i4 = Math.abs(t3) \u003e= Math.abs(n3);\n return { center: { x: (e52.start.x + e52.end.x) / 2, y: (e52.start.y + e52.end.y) / 2 }, width: i4 ? o4 : 0.18, height: i4 ? 0.18 : o4, stroke: \"#b45309\", fill: \"rgba(250, 204, 21, 0.45)\", label: `boundry-violation:${e52.routeIndex}:${e52.segmentIndex}` };\n }) : [];\n const c3 = this.showBoundryViolationMarkers ? BK(o3.routes, xK) : [], l3 = [...(t2?.portPoints ?? []).map((e52) =\u003e ({ x: e52.x, y: e52.y, color: \"#0f766e\", label: e52.connectionName ?? e52.portPointId ?? \"port-point\" })), ...o3.routes.flatMap((e52) =\u003e e52.route ?? []).map((e52) =\u003e ({ x: e52.x, y: e52.y, color: PK(e52) === \"bottom\" ? _K : \"#0ea5e9\", label: \"\" })), ...o3.overlayPoints ?? []], h2 = [...(o3.originalRoutes ?? []).flatMap((e52) =\u003e c0(e52).map((e53) =\u003e ({ ...e53, strokeColor: \"#111111\", strokeWidth: Math.max(0.6 * e53.strokeWidth, 0.05), label: `original:${e53.label}` }))), ...o3.routes.filter((e52) =\u003e (e52.route?.length ?? 0) \u003e= 2).flatMap((e52) =\u003e c0(e52)), ...o3.overlayLines ?? []], d2 = o3.routes.flatMap((e52) =\u003e (e52.vias ?? []).map((t3) =\u003e ({ center: { x: t3.x, y: t3.y }, radius: (t3.diameter ?? e52.viaDiameter ?? 0.3) / 2, stroke: \"#7c3aed\", fill: \"rgba(124, 58, 237, 0.2)\", label: e52.connectionName ? `via:${e52.connectionName}` : \"via\" })));\n return d2.push(...c3), { coordinateSystem: \"cartesian\", title: o3.title, rects: [...r3, ...s2, ...o3.overlayRects ?? [], ...a3], points: l3, lines: h2, circles: d2, arrows: o3.overlayArrows };\n }\n};\nvar i1 = (e51, t2, n2, o3) =\u003e {\n const i3 = 0.001, r3 = new Set;\n for (const s2 of [t2.route[0], t2.route.at(-1)]) {\n if (!s2)\n continue;\n n2.some((e52) =\u003e e52.__zLayers.includes(s2.z) \u0026\u0026 Math.abs(s2.x - e52.center.x) \u003c= e52.width / 2 + i3 \u0026\u0026 Math.abs(s2.y - e52.center.y) \u003c= e52.height / 2 + i3 \u0026\u0026 xo(e52, t2, o3)) \u0026\u0026 (Math.abs(s2.x - (e51.center.x - e51.width / 2)) \u003c= i3 \u0026\u0026 r3.add(\"left\"), Math.abs(s2.x - (e51.center.x + e51.width / 2)) \u003c= i3 \u0026\u0026 r3.add(\"right\"), Math.abs(s2.y - (e51.center.y - e51.height / 2)) \u003c= i3 \u0026\u0026 r3.add(\"bottom\"), Math.abs(s2.y - (e51.center.y + e51.height / 2)) \u003c= i3 \u0026\u0026 r3.add(\"top\"));\n }\n return [...r3];\n};\nvar s1 = class extends ni {\n constructor(e51) {\n super(), this.input = e51;\n }\n static solverName = \"Pipeline4HighDensityRepairSampleSolver\";\n output;\n _step() {\n const e51 = n1(this.input.sample, this.input.margin, false, false);\n if (e51.frames.length !== 1)\n throw new Error(\"Node repair must complete in one frame\");\n this.output = { repairedRoutes: e51.repairedRoutes, clearanceStats: e51.clearanceRepairStats }, this.solved = true;\n }\n getOutput() {\n if (!this.output)\n throw new Error(\"Node repair sample has not completed\");\n return this.output;\n }\n};\nSolverRuntime.registerSolver(s1);\nvar a1 = (e51, t2) =\u003e e51.minX \u003c= t2.maxX \u0026\u0026 e51.maxX \u003e= t2.minX \u0026\u0026 e51.minY \u003c= t2.maxY \u0026\u0026 e51.maxY \u003e= t2.minY;\nvar c1 = (e51, t2 = 0) =\u003e ({ minX: e51.center.x - e51.width / 2 - t2, maxX: e51.center.x + e51.width / 2 + t2, minY: e51.center.y - e51.height / 2 - t2, maxY: e51.center.y + e51.height / 2 + t2 });\nvar l1 = (e51) =\u003e ({ minX: e51.center.x - e51.width / 2, maxX: e51.center.x + e51.width / 2, minY: e51.center.y - e51.height / 2, maxY: e51.center.y + e51.height / 2 });\nvar h1 = (e51, t2, n2 = 0) =\u003e {\n const o3 = c1(t2, n2);\n return e51.x \u003e= o3.minX \u0026\u0026 e51.x \u003c= o3.maxX \u0026\u0026 e51.y \u003e= o3.minY \u0026\u0026 e51.y \u003c= o3.maxY;\n};\nvar d1 = (e51, t2, n2) =\u003e e51.route.length \u003e 0 \u0026\u0026 t2.some((t3) =\u003e ((e52) =\u003e (e52.__zLayers?.length ?? e52.layers?.length ?? 0) \u003e 1)(t3) \u0026\u0026 e51.route.every((e52) =\u003e ((e53, t4) =\u003e {\n const n3 = t4.width / 2, o3 = t4.height / 2;\n return Math.abs(e53.x - t4.center.x) \u003c= n3 + 0.001 \u0026\u0026 Math.abs(e53.y - t4.center.y) \u003c= o3 + 0.001;\n})(e52, t3)) \u0026\u0026 xo(t3, e51, n2));\nvar u1 = (e51, t2, n2) =\u003e {\n if (e51.regionId) {\n const n3 = t2.findIndex((t3) =\u003e t3.capacityMeshNodeId === e51.regionId);\n if (n3 !== -1)\n return n3;\n }\n const o3 = [...e51.route.map(({ x: e52, y: t3 }) =\u003e ({ x: e52, y: t3 })), ...e51.vias.map(({ x: e52, y: t3 }) =\u003e ({ x: e52, y: t3 }))];\n for (let e52 = 0;e52 \u003c t2.length; e52++) {\n const i3 = t2[e52];\n if (o3.every((e53) =\u003e h1(e53, i3, n2)))\n return e52;\n }\n return -1;\n};\nvar p1 = (e51, t2) =\u003e ({ connectionName: e51.connectionName ?? t2.connectionName, rootConnectionName: t2.rootConnectionName, ...t2.startPcbPortId ? { startPcbPortId: t2.startPcbPortId } : {}, ...t2.endPcbPortId ? { endPcbPortId: t2.endPcbPortId } : {}, regionId: e51.capacityMeshNodeId ?? t2.regionId, traceThickness: t2.traceThickness, viaDiameter: e51.viaDiameter ?? t2.viaDiameter, route: e51.route?.map((e52) =\u003e ({ x: e52.x, y: e52.y, z: e52.z ?? 0 })) ?? t2.route, vias: e51.vias?.map((e52) =\u003e ({ x: e52.x, y: e52.y })) ?? t2.vias, jumpers: t2.jumpers });\nvar m1 = (e51, t2, n2, o3, i3) =\u003e {\n const r3 = c1(e51, n2);\n return t2.search(r3).filter((e52) =\u003e a1(r3, l1(e52))).filter((e52) =\u003e !i3 || !o3.some((t3) =\u003e xo(e52, t3, i3))).map((e52) =\u003e ({ type: e52.type, center: e52.center, width: e52.width, height: e52.height }));\n};\nvar g1 = class extends ni {\n repairMargin;\n minimumTraceWidth;\n sampleEntries;\n originalHdRoutes;\n originalNodeWithPortPoints;\n originalObstacles;\n obstacleSHI;\n colorMap;\n connMap;\n repairedRoutesByIndex = new Map;\n activeSampleIndex = 0;\n activeSubSolver = null;\n latestVisualization = {};\n asyncRunning = false;\n constructor(e51) {\n super(), this.repairMargin = e51.repairMargin ?? 0.2, this.minimumTraceWidth = e51.minimumTraceWidth, this.originalHdRoutes = e51.hdRoutes, this.originalNodeWithPortPoints = e51.nodeWithPortPoints, this.originalObstacles = e51.obstacles, this.obstacleSHI = new ZF(\"flatbush\", this.originalObstacles), this.colorMap = e51.colorMap ?? {}, this.connMap = e51.connMap;\n const t2 = new Map;\n for (let n3 = 0;n3 \u003c e51.hdRoutes.length; n3++) {\n if (d1(e51.hdRoutes[n3], e51.obstacles, e51.connMap))\n continue;\n const o4 = u1(e51.hdRoutes[n3], e51.nodeWithPortPoints, this.repairMargin);\n if (o4 === -1)\n continue;\n const i4 = t2.get(o4) ?? [];\n i4.push(n3), t2.set(o4, i4);\n }\n const n2 = ca(e51.obstacles, Math.max(2, ...e51.nodeWithPortPoints.flatMap((e52) =\u003e e52.availableZ?.map((e53) =\u003e e53 + 1) ?? []))), o3 = e51.hdRoutes.map((t3) =\u003e ((e52, t4, n3) =\u003e ({ capacityMeshNodeId: e52.regionId, connectionName: e52.connectionName, rootConnectionName: t4?.getNetConnectedToId(e52.connectionName) ?? e52.rootConnectionName, route: e52.route.map((e53) =\u003e ({ x: e53.x, y: e53.y, z: e53.z })), traceThickness: Math.max(e52.traceThickness, n3 ?? e52.traceThickness), vias: e52.vias.map((t5) =\u003e ({ x: t5.x, y: t5.y, diameter: e52.viaDiameter })), viaDiameter: e52.viaDiameter }))(t3, e51.connMap, e51.minimumTraceWidth)), i3 = new UF(e51.hdRoutes.length);\n for (const [t3, n3] of e51.hdRoutes.entries()) {\n const e52 = [...n3.route, ...n3.vias];\n if (e52.length === 0)\n throw new Error(`High density repair route \"${n3.connectionName}\" has no points`);\n const r4 = Math.max(o3[t3].traceThickness, n3.viaDiameter) / 2;\n i3.insert({ routeIndex: t3 }, Math.min(...e52.map((e53) =\u003e e53.x)) - r4, Math.min(...e52.map((e53) =\u003e e53.y)) - r4, Math.max(...e52.map((e53) =\u003e e53.x)) + r4, Math.max(...e52.map((e53) =\u003e e53.y)) + r4);\n }\n e51.hdRoutes.length \u003e 0 \u0026\u0026 i3.finish();\n const r3 = Array.from(t2.entries()).map(([t3, r4]) =\u003e {\n const s2 = e51.nodeWithPortPoints[t3], a3 = Math.max(...r4.map((t4) =\u003e Math.max(o3[t4].traceThickness, e51.hdRoutes[t4].viaDiameter) / 2)), c3 = c1(s2, Math.max(this.repairMargin, a3 + 0.1)), l3 = new Set(r4);\n return { node: s2, routeIndexes: r4, sample: { nodeWithPortPoints: { capacityMeshNodeId: s2.capacityMeshNodeId, center: s2.center, width: s2.width, height: s2.height, portPoints: s2.portPoints.map((e52) =\u003e ({ x: e52.x, y: e52.y, z: e52.z, connectionName: e52.connectionName, portPointId: e52.portPointId, prevPortPointId: e52.prevPortPointId, nextPortPointId: e52.nextPortPointId })) }, nodeHdRoutes: r4.map((t4) =\u003e ({ ...o3[t4], ...e51.connMap ? { connectedPadSides: i1(s2, e51.hdRoutes[t4], n2, e51.connMap) } : {} })), fixedHdRoutes: i3.search(c3.minX, c3.minY, c3.maxX, c3.maxY).filter(({ routeIndex: e52 }) =\u003e !l3.has(e52)).map(({ routeIndex: e52 }) =\u003e o3[e52]), clearanceObstacles: n2.filter((e52) =\u003e a1(c3, l1(e52))).map((t4) =\u003e ({ type: t4.type, center: t4.center, width: t4.width, height: t4.height, zLayers: t4.__zLayers, connectedTo: [...new Set(t4.connectedTo.flatMap((t5) =\u003e {\n const n3 = e51.connMap?.getNetConnectedToId(t5);\n return n3 ? [t5, n3] : [t5];\n }))] })), adjacentObstacles: m1(s2, this.obstacleSHI, this.repairMargin, r4.map((t4) =\u003e e51.hdRoutes[t4]), e51.connMap) } };\n });\n this.sampleEntries = r3, this.MAX_ITERATIONS = Math.max(1000 * this.sampleEntries.length, 1e5), this.stats = { sampleCount: this.sampleEntries.length, repairedNodeCount: 0, repairedRouteCount: 0 };\n }\n getSolverName() {\n return \"Pipeline4HighDensityRepairSolver\";\n }\n async solveAsync(e51, t2 = 1 / 0) {\n if (this.asyncRunning)\n throw new Error(\"High-density repair solveAsync is already running\");\n if (this.solved || this.failed || this.iterations \u003e= t2)\n return;\n const n2 = performance.now();\n try {\n if (e51 === undefined)\n return void (t2 === 1 / 0 ? this.solve() : this.solveUntilIteration(t2));\n for (;this.activeSubSolver \u0026\u0026 !this.solved \u0026\u0026 !this.failed \u0026\u0026 this.iterations \u003c t2; )\n this.step();\n if (this.solved || this.failed || this.iterations \u003e= t2)\n return;\n this.asyncRunning = true;\n const n3 = Math.max(0, Math.floor((Math.min(this.MAX_ITERATIONS, t2) - this.iterations) / 2)), o3 = this.sampleEntries.slice(this.activeSampleIndex, this.activeSampleIndex + n3).map((t3) =\u003e e51.executeAsync(s1, { sample: t3.sample, margin: this.repairMargin }).then((e52) =\u003e ({ type: \"result\", result: e52 }), (e52) =\u003e ({ type: \"error\", error: e52 })));\n for (const e52 of o3) {\n if (this.iterations + 2 \u003e Math.min(this.MAX_ITERATIONS, t2))\n return this.asyncRunning = false, void this.solveUntilIteration(t2);\n const n4 = await e52;\n if (n4.type === \"error\")\n throw n4.error;\n this.consumeRepairSample(n4.result), this.iterations += 2;\n }\n this.asyncRunning = false, this.solveUntilIteration(t2);\n } catch (e52) {\n throw this.failed = true, this.error = `High-density repair runtime error: ${e52}`, e52;\n } finally {\n this.asyncRunning = false, this.timeToSolve = performance.now() - n2;\n }\n }\n solveUntilIteration(e51) {\n for (;!this.solved \u0026\u0026 !this.failed \u0026\u0026 this.iterations \u003c e51; )\n this.step();\n }\n consumeRepairSample(e51) {\n const t2 = this.sampleEntries[this.activeSampleIndex];\n if (!t2)\n throw new Error(\"Node repair sample is missing\");\n const n2 = { nodeClearanceInitialConflictCount: Number(this.stats.nodeClearanceInitialConflictCount ?? 0) + Number(e51.clearanceStats?.nodeClearanceInitialConflictCount ?? 0), nodeClearanceFinalConflictCount: Number(this.stats.nodeClearanceFinalConflictCount ?? 0) + Number(e51.clearanceStats?.nodeClearanceFinalConflictCount ?? 0), nodeClearanceCandidateCount: Number(this.stats.nodeClearanceCandidateCount ?? 0) + Number(e51.clearanceStats?.nodeClearanceCandidateCount ?? 0) };\n for (let n3 = 0;n3 \u003c t2.routeIndexes.length; n3++) {\n const o3 = t2.routeIndexes[n3], i3 = this.originalHdRoutes[o3], r3 = e51.repairedRoutes[n3];\n this.repairedRoutesByIndex.set(o3, r3 ? p1(r3, i3) : i3);\n }\n this.activeSubSolver = null, this.activeSampleIndex += 1, this.stats = { ...n2, sampleCount: this.sampleEntries.length, repairedNodeCount: this.activeSampleIndex, repairedRouteCount: this.repairedRoutesByIndex.size }, this.activeSampleIndex \u003e= this.sampleEntries.length \u0026\u0026 (this.solved = true);\n }\n getConstructorParams() {\n return [{ nodeWithPortPoints: this.sampleEntries.map((e51) =\u003e e51.node), hdRoutes: this.originalHdRoutes, obstacles: this.originalObstacles, repairMargin: this.repairMargin, minimumTraceWidth: this.minimumTraceWidth, colorMap: this.colorMap, connMap: this.connMap }];\n }\n _step() {\n const e51 = this.sampleEntries[this.activeSampleIndex];\n if (e51)\n if (this.activeSubSolver) {\n if (this.activeSubSolver.step(), this.latestVisualization = this.activeSubSolver.visualize(), this.activeSubSolver.failed)\n return this.failed = true, this.error = this.activeSubSolver.error ?? `High density repair failed for node ${e51.node.capacityMeshNodeId}`, void (this.activeSubSolver = null);\n if (!this.activeSubSolver.solved)\n return;\n this.consumeRepairSample({ repairedRoutes: this.activeSubSolver.getOutput().repairedRoutes, clearanceStats: { nodeClearanceInitialConflictCount: this.activeSubSolver.stats.nodeClearanceInitialConflictCount, nodeClearanceFinalConflictCount: this.activeSubSolver.stats.nodeClearanceFinalConflictCount, nodeClearanceCandidateCount: this.activeSubSolver.stats.nodeClearanceCandidateCount } });\n } else\n this.activeSubSolver = new o1({ repairBoundaryDiagonals: false, sample: e51.sample, margin: this.repairMargin }), this.latestVisualization = this.activeSubSolver.visualize();\n else\n this.solved = true;\n }\n getOutput() {\n return this.originalHdRoutes.map((e51, t2) =\u003e this.repairedRoutesByIndex.get(t2) ?? e51);\n }\n visualize() {\n if (this.activeSubSolver)\n return this.activeSubSolver.visualize();\n if (!this.solved)\n return this.latestVisualization;\n const e51 = [], t2 = [];\n for (const n2 of this.getOutput()) {\n const o3 = this.colorMap[n2.connectionName] ?? \"#0ea5e9\";\n for (let t3 = 0;t3 \u003c n2.route.length - 1; t3++) {\n const i3 = n2.route[t3], r3 = n2.route[t3 + 1];\n i3.z === r3.z \u0026\u0026 e51.push({ points: [{ x: i3.x, y: i3.y }, { x: r3.x, y: r3.y }], strokeColor: i3.z === 0 ? o3 : Ao(o3, 0.5), strokeWidth: n2.traceThickness, layer: `z${i3.z}`, strokeDash: i3.z !== 0 ? [0.1, 0.3] : undefined });\n }\n for (const e52 of n2.vias)\n t2.push({ center: { x: e52.x, y: e52.y }, radius: n2.viaDiameter / 2, stroke: o3, fill: \"rgba(14,165,233,0.12)\" });\n }\n return { title: \"Pipeline4 High Density Repair\", lines: e51, circles: t2 };\n }\n};\nvar f1 = 0.000001;\nvar _1 = ({ startGap: e51, endGap: t2, segmentGap: n2, requiredGap: o3 }) =\u003e {\n const i3 = e51 \u003c o3 \u0026\u0026 t2 \u003e= o3 - f1 \u0026\u0026 n2 \u003e= e51 - f1, r3 = t2 \u003c o3 \u0026\u0026 e51 \u003e= o3 - f1 \u0026\u0026 n2 \u003e= t2 - f1, s2 = e51 \u003c o3 \u0026\u0026 t2 \u003c o3 \u0026\u0026 n2 \u003e= Math.min(e51, t2) - f1;\n return i3 || r3 || s2;\n};\nvar y1 = class {\n minClearance;\n rootsByConnection = new Map;\n sameNetCache = new Map;\n segments = [];\n vias = [];\n segmentIndexesByLayer;\n viaIndex;\n constructor({ hdRoutes: e51, minClearance: t2 = 0.1 }) {\n this.minClearance = t2;\n for (const t3 of e51)\n this.addRoute(t3);\n this.buildSpatialIndexes();\n }\n addRoute(e51) {\n const t2 = this.rootsByConnection.get(e51.connectionName) ?? new Set;\n t2.add(e51.rootConnectionName ?? e51.connectionName), this.rootsByConnection.set(e51.connectionName, t2), this.sameNetCache.clear();\n for (let t3 = 0;t3 \u003c e51.route.length - 1; t3 += 1) {\n const n2 = e51.route[t3], o3 = e51.route[t3 + 1];\n if (n2.z !== o3.z)\n continue;\n if (n2.insideJumperPad \u0026\u0026 o3.insideJumperPad)\n continue;\n const i3 = { connectionName: e51.connectionName, start: n2, end: o3, traceThickness: e51.traceThickness };\n this.segments.push(i3), this.insertSegmentIntoSpatialIndex(i3);\n }\n for (const t3 of e51.vias) {\n const n2 = { connectionName: e51.connectionName, x: t3.x, y: t3.y, diameter: e51.viaDiameter };\n this.vias.push(n2), this.insertViaIntoSpatialIndex(n2);\n }\n }\n insertSegmentIntoSpatialIndex(e51) {\n if (!this.segmentIndexesByLayer)\n return;\n let t2 = this.segmentIndexesByLayer.get(e51.start.z);\n t2 || (t2 = new GF, this.segmentIndexesByLayer.set(e51.start.z, t2));\n const n2 = e51.traceThickness / 2;\n t2.insert(e51, Math.min(e51.start.x, e51.end.x) - n2, Math.min(e51.start.y, e51.end.y) - n2, Math.max(e51.start.x, e51.end.x) + n2, Math.max(e51.start.y, e51.end.y) + n2);\n }\n insertViaIntoSpatialIndex(e51) {\n if (!this.viaIndex)\n return;\n const t2 = e51.diameter / 2;\n this.viaIndex.insert(e51, e51.x - t2, e51.y - t2, e51.x + t2, e51.y + t2);\n }\n buildSpatialIndexes() {\n this.segmentIndexesByLayer = new Map;\n const e51 = new Map;\n for (const t2 of this.segments) {\n const n2 = e51.get(t2.start.z);\n n2 ? n2.push(t2) : e51.set(t2.start.z, [t2]);\n }\n for (const [t2, n2] of e51) {\n const e52 = new GF;\n e52.bulkLoad(n2.map((e53) =\u003e {\n const t3 = e53.traceThickness / 2;\n return { item: e53, minX: Math.min(e53.start.x, e53.end.x) - t3, minY: Math.min(e53.start.y, e53.end.y) - t3, maxX: Math.max(e53.start.x, e53.end.x) + t3, maxY: Math.max(e53.start.y, e53.end.y) + t3 };\n })), this.segmentIndexesByLayer.set(t2, e52);\n }\n this.viaIndex = new GF, this.viaIndex.bulkLoad(this.vias.map((e52) =\u003e {\n const t2 = e52.diameter / 2;\n return { item: e52, minX: e52.x - t2, minY: e52.y - t2, maxX: e52.x + t2, maxY: e52.y + t2 };\n }));\n }\n areSameNet(e51, t2) {\n if (e51 === t2)\n return true;\n const n2 = this.sameNetCache.get(e51)?.get(t2);\n if (n2 !== undefined)\n return n2;\n const o3 = this.rootsByConnection.get(e51), i3 = this.rootsByConnection.get(t2);\n let r3 = false;\n if (o3 \u0026\u0026 i3) {\n for (const e52 of o3)\n if (i3.has(e52)) {\n r3 = true;\n break;\n }\n }\n let s2 = this.sameNetCache.get(e51);\n return s2 || (s2 = new Map, this.sameNetCache.set(e51, s2)), s2.set(t2, r3), r3;\n }\n isSegmentClear({ connectionName: e51, start: t2, end: n2, traceThickness: o3 }) {\n const i3 = o3 / 2, r3 = this.minClearance + i3, s2 = Math.min(t2.x, n2.x) - r3, a3 = Math.min(t2.y, n2.y) - r3, c3 = Math.max(t2.x, n2.x) + r3, l3 = Math.max(t2.y, n2.y) + r3, h2 = this.segmentIndexesByLayer?.get(t2.z)?.search(s2, a3, c3, l3) ?? [];\n for (const o4 of h2) {\n if (this.areSameNet(e51, o4.connectionName))\n continue;\n const r4 = this.minClearance + i3 + o4.traceThickness / 2, s3 = qr(t2, n2, o4.start, o4.end);\n if (s3 \u003c r4 \u0026\u0026 !_1({ startGap: pe(t2, o4.start, o4.end), endGap: pe(n2, o4.start, o4.end), segmentGap: s3, requiredGap: r4 }))\n return false;\n }\n const d2 = this.viaIndex?.search(s2, a3, c3, l3) ?? [];\n for (const o4 of d2) {\n if (this.areSameNet(e51, o4.connectionName))\n continue;\n const r4 = this.minClearance + i3 + o4.diameter / 2, s3 = pe(o4, t2, n2);\n if (s3 \u003c r4 \u0026\u0026 !_1({ startGap: Math.hypot(t2.x - o4.x, t2.y - o4.y), endGap: Math.hypot(n2.x - o4.x, n2.y - o4.y), segmentGap: s3, requiredGap: r4 }))\n return false;\n }\n return true;\n }\n};\nvar b1 = 0.000000001;\nvar x1 = 1.25;\nvar v1 = (e51, t2) =\u003e e51 \u003c t2 ? -1 : e51 \u003e t2 ? 1 : 0;\nvar I1 = (e51, t2) =\u003e v1(e51.z, t2.z) || v1(e51.x, t2.x) || v1(e51.y, t2.y);\nvar S1 = (e51) =\u003e `${e51.z.toFixed(6)}:${e51.x.toFixed(6)}:${e51.y.toFixed(6)}`;\nvar C1 = (e51) =\u003e {\n const t2 = e51.route.map(S1).join(\"|\"), n2 = [...e51.route].reverse().map(S1).join(\"|\");\n return t2 \u003c= n2 ? t2 : n2;\n};\nvar P1 = (e51, t2) =\u003e {\n const n2 = e51.connectionName.localeCompare(t2.connectionName);\n if (n2 !== 0)\n return n2;\n const o3 = (e51.rootConnectionName ?? \"\").localeCompare(t2.rootConnectionName ?? \"\");\n if (o3 !== 0)\n return o3;\n const i3 = C1(e51).localeCompare(C1(t2));\n return i3 !== 0 ? i3 : v1(e51.traceThickness, t2.traceThickness) || v1(e51.viaDiameter, t2.viaDiameter) || v1(e51.route.length, t2.route.length) || v1(e51.vias.length, t2.vias.length) || v1(e51.jumpers?.length ?? 0, t2.jumpers?.length ?? 0);\n};\nvar M1 = 1e5;\nvar w1 = 0.001;\nvar N1 = 1.000000001;\nvar R1 = ({ terminal: e51, point: t2, pcbPortId: n2, preserveTerminalPcbPortIds: o3 }) =\u003e o3 \u0026\u0026 e51.pcb_port_id \u0026\u0026 n2 \u0026\u0026 e51.pcb_port_id !== n2 ? 1 / 0 : me(e51, t2);\nvar T1 = class extends ni {\n getSolverName() {\n return \"SingleHighDensityRouteStitchSolver3\";\n }\n mergedHdRoute;\n remainingHdRoutes;\n start;\n end;\n colorMap;\n allowedLayerTransitionPointKeys;\n isStitchSegmentClear;\n stitchClearanceMode;\n isPlanarStitchClear(e51, t2) {\n return this.isStitchSegmentClear({ connectionName: this.mergedHdRoute.connectionName, start: e51, end: t2, traceThickness: this.mergedHdRoute.traceThickness });\n }\n constructor(e51) {\n super();\n const t2 = [...e51.hdRoutes].sort(P1);\n if (this.remainingHdRoutes = t2, this.colorMap = e51.colorMap ?? {}, this.allowedLayerTransitionPointKeys = e51.allowedLayerTransitionPointKeys, this.isStitchSegmentClear = e51.isStitchSegmentClear, this.stitchClearanceMode = e51.stitchClearanceMode, t2.length === 0) {\n this.start = e51.start, this.end = e51.end;\n const n3 = e51.defaultTraceThickness ?? 0.15, o4 = [{ x: e51.start.x, y: e51.start.y, z: e51.start.z }], i4 = [];\n if (e51.start.z !== e51.end.z) {\n if (e51.allowedLayerTransitionPointKeys \u0026\u0026 !e51.allowedLayerTransitionPointKeys.has(jG(e51.start)))\n return this.failed = true, void (this.error = `Layer transition at ${jG(e51.start)} is not allowed`);\n o4.push({ x: e51.start.x, y: e51.start.y, z: e51.end.z }), i4.push({ x: e51.start.x, y: e51.start.y });\n }\n const r4 = o4[o4.length - 1], s3 = { x: e51.end.x, y: e51.end.y, z: e51.end.z }, a4 = { connectionName: e51.connectionName, start: r4, end: s3, traceThickness: n3 };\n return me(r4, s3) \u003e w1 \u0026\u0026 !this.isStitchSegmentClear(a4) \u0026\u0026 this.stitchClearanceMode === \"require_clear\" ? (this.failed = true, void (this.error = `Terminal stitch for \"${e51.connectionName}\" violates copper clearance`)) : (o4.push(s3), this.mergedHdRoute = { connectionName: e51.connectionName, ...e51.preserveTerminalPcbPortIds \u0026\u0026 e51.start.pcb_port_id ? { startPcbPortId: e51.start.pcb_port_id } : {}, ...e51.preserveTerminalPcbPortIds \u0026\u0026 e51.end.pcb_port_id ? { endPcbPortId: e51.end.pcb_port_id } : {}, rootConnectionName: t2[0]?.rootConnectionName, route: o4, vias: i4, jumpers: [], viaDiameter: e51.defaultViaDiameter ?? 0.3, traceThickness: n3 }, void (this.solved = true));\n }\n const n2 = new Set((e51.preserveTerminalPcbPortIds ? [e51.start.pcb_port_id, e51.end.pcb_port_id] : []).filter((e52) =\u003e e52 !== undefined));\n if (e51.preserveTerminalPcbPortIds \u0026\u0026 e51.start.pcb_port_id \u0026\u0026 e51.start.pcb_port_id === e51.end.pcb_port_id)\n throw new Error(`SingleHighDensityRouteStitchSolver3 received duplicate PCB terminal \"${e51.start.pcb_port_id}\" for \"${e51.connectionName}\"`);\n const o3 = t2.flatMap((e52) =\u003e [e52.startPcbPortId, e52.endPcbPortId]).filter((e52) =\u003e e52 !== undefined);\n if (n2.size \u003e 0) {\n for (const t3 of o3)\n if (!n2.has(t3) \u0026\u0026 !e51.allowedTerminalPcbPortIds?.has(t3))\n throw new Error(`SingleHighDensityRouteStitchSolver3 found unknown PCB terminal \"${t3}\" on \"${e51.connectionName}\"`);\n }\n let i3 = 1 / 0, r3 = t2[0], s2 = \"start-to-end\";\n for (const n3 of t2) {\n const t3 = n3.route[0], o4 = n3.route[n3.route.length - 1], a4 = R1({ terminal: e51.start, point: t3, pcbPortId: n3.startPcbPortId, preserveTerminalPcbPortIds: e51.preserveTerminalPcbPortIds }), c4 = R1({ terminal: e51.start, point: o4, pcbPortId: n3.endPcbPortId, preserveTerminalPcbPortIds: e51.preserveTerminalPcbPortIds }), l4 = R1({ terminal: e51.end, point: t3, pcbPortId: n3.startPcbPortId, preserveTerminalPcbPortIds: e51.preserveTerminalPcbPortIds }), h3 = R1({ terminal: e51.end, point: o4, pcbPortId: n3.endPcbPortId, preserveTerminalPcbPortIds: e51.preserveTerminalPcbPortIds }), d3 = Math.min(a4, c4, l4, h3);\n (d3 \u003c i3 - b1 || Math.abs(d3 - i3) \u003c= b1 \u0026\u0026 P1(n3, r3) \u003c 0) \u0026\u0026 (i3 = d3, r3 = n3, s2 = Math.min(l4, h3) \u003c Math.min(a4, c4) - b1 || Math.abs(Math.min(l4, h3) - Math.min(a4, c4)) \u003c= b1 \u0026\u0026 I1(e51.end, e51.start) \u003c 0 ? \"end-to-start\" : \"start-to-end\");\n }\n s2 === \"start-to-end\" ? (this.start = e51.start, this.end = e51.end) : (this.start = e51.end, this.end = e51.start);\n const a3 = r3.route[0], c3 = r3.route[r3.route.length - 1], l3 = R1({ terminal: this.start, point: a3, pcbPortId: r3.startPcbPortId, preserveTerminalPcbPortIds: e51.preserveTerminalPcbPortIds }), h2 = R1({ terminal: this.start, point: c3, pcbPortId: r3.endPcbPortId, preserveTerminalPcbPortIds: e51.preserveTerminalPcbPortIds }), d2 = l3 \u003c h2 - b1 || Math.abs(l3 - h2) \u003c= b1 \u0026\u0026 I1(a3, c3) \u003c= 0 ? a3 : c3, u2 = d2 === a3 ? r3.startPcbPortId : r3.endPcbPortId;\n if (u2 \u0026\u0026 this.start.pcb_port_id \u0026\u0026 u2 !== this.start.pcb_port_id)\n throw new Error(`SingleHighDensityRouteStitchSolver3 terminal identity disagrees with route orientation for \"${e51.connectionName}\"`);\n this.mergedHdRoute = { connectionName: e51.connectionName, ...e51.preserveTerminalPcbPortIds \u0026\u0026 this.start.pcb_port_id ? { startPcbPortId: this.start.pcb_port_id } : {}, ...e51.preserveTerminalPcbPortIds \u0026\u0026 this.end.pcb_port_id ? { endPcbPortId: this.end.pcb_port_id } : {}, rootConnectionName: r3.rootConnectionName, route: [{ x: this.start.x, y: this.start.y, z: d2.z }], vias: [], jumpers: [], viaDiameter: r3.viaDiameter, traceThickness: r3.traceThickness };\n }\n getDisjointedRoute() {\n for (const e51 of this.remainingHdRoutes) {\n if ([e51.route[0], e51.route[e51.route.length - 1]].some((t2) =\u003e !this.remainingHdRoutes.some((n2) =\u003e {\n if (n2 === e51)\n return false;\n return [n2.route[0], n2.route[n2.route.length - 1]].some((e52) =\u003e e52.z === t2.z \u0026\u0026 me(t2, e52) \u003c 0.001);\n })))\n return { firstRoute: e51 };\n }\n return { firstRoute: this.remainingHdRoutes[0] };\n }\n _step() {\n const e51 = this.mergedHdRoute.route.at(-1), t2 = this.mergedHdRoute.endPcbPortId !== undefined \u0026\u0026 e51.z === this.end.z \u0026\u0026 me(e51, this.end) \u003c w1;\n if (this.remainingHdRoutes.length === 0 || t2) {\n const e52 = this.mergedHdRoute.route[this.mergedHdRoute.route.length - 1], t3 = { ...this.end, z: e52.z }, n3 = me(e52, t3);\n if (n3 \u003e w1 \u0026\u0026 n3 \u003c= x1) {\n if (!this.isPlanarStitchClear(e52, t3) \u0026\u0026 this.stitchClearanceMode === \"require_clear\")\n return this.failed = true, void (this.error = `Terminal stitch for \"${this.mergedHdRoute.connectionName}\" violates copper clearance`);\n this.mergedHdRoute.route.push({ x: this.end.x, y: this.end.y, z: e52.z });\n }\n return void (this.solved = true);\n }\n const n2 = this.mergedHdRoute.route[this.mergedHdRoute.route.length - 1];\n let o3 = -1, i3 = \"first\", r3 = 1 / 0, s2 = false;\n for (let e52 = 0;e52 \u003c this.remainingHdRoutes.length; e52++) {\n const t3 = this.remainingHdRoutes[e52], a4 = t3.route[0], c4 = t3.route[t3.route.length - 1], l3 = me(n2, a4), h2 = me(n2, c4);\n let d2 = 1 / 0;\n if (n2.z === a4.z) {\n if (l3 \u003c w1)\n d2 = l3;\n else if (l3 \u003c= 1) {\n const e53 = this.isPlanarStitchClear(n2, a4);\n if (e53 || this.stitchClearanceMode === \"prefer_clear\") {\n d2 = M1 + (e53 ? 0 : N1) + l3;\n } else\n s2 = true;\n }\n } else\n l3 \u003c w1 \u0026\u0026 (!this.allowedLayerTransitionPointKeys || this.allowedLayerTransitionPointKeys.has(jG(a4))) \u0026\u0026 (d2 = 1000 + l3);\n d2 \u003c r3 \u0026\u0026 (r3 = d2, o3 = e52, i3 = \"first\");\n let u2 = 1 / 0;\n if (n2.z === c4.z) {\n if (h2 \u003c w1)\n u2 = h2;\n else if (h2 \u003c= 1) {\n const e53 = this.isPlanarStitchClear(n2, c4);\n if (e53 || this.stitchClearanceMode === \"prefer_clear\") {\n u2 = M1 + (e53 ? 0 : N1) + h2;\n } else\n s2 = true;\n }\n } else\n h2 \u003c w1 \u0026\u0026 (!this.allowedLayerTransitionPointKeys || this.allowedLayerTransitionPointKeys.has(jG(c4))) \u0026\u0026 (u2 = 1000 + h2);\n u2 \u003c r3 \u0026\u0026 (r3 = u2, o3 = e52, i3 = \"last\");\n }\n if (o3 === -1)\n return s2 ? (this.failed = true, void (this.error = `Route stitch for \"${this.mergedHdRoute.connectionName}\" violates copper clearance`)) : void (this.remainingHdRoutes = []);\n const a3 = this.remainingHdRoutes[o3];\n let c3;\n this.remainingHdRoutes.splice(o3, 1), c3 = i3 === \"first\" ? a3.route : ((e52) =\u003e {\n const t3 = [...e52].reverse().map((e53) =\u003e {\n const { toNextSegmentType: t4, toNextSegmentCircuitJsonMetadata: n3, ...o4 } = e53;\n return o4;\n });\n for (let n3 = 0;n3 \u003c e52.length - 1; n3++) {\n const o4 = e52[n3]?.toNextSegmentType;\n if (!o4)\n continue;\n const i4 = e52.length - n3 - 2;\n t3[i4] = { ...t3[i4], toNextSegmentType: o4, ...e52[n3]?.toNextSegmentCircuitJsonMetadata \u0026\u0026 { toNextSegmentCircuitJsonMetadata: e52[n3].toNextSegmentCircuitJsonMetadata } };\n }\n return t3;\n })(a3.route), c3.length \u003e 0 \u0026\u0026 me(n2, c3[0]) \u003c w1 \u0026\u0026 n2.z === c3[0].z \u0026\u0026 (!c3[0].toNextSegmentType || n2.x === c3[0].x \u0026\u0026 n2.y === c3[0].y) ? (c3[0].toNextSegmentType \u0026\u0026 (n2.toNextSegmentType = c3[0].toNextSegmentType, c3[0].toNextSegmentCircuitJsonMetadata \u0026\u0026 (n2.toNextSegmentCircuitJsonMetadata = c3[0].toNextSegmentCircuitJsonMetadata)), this.mergedHdRoute.route.push(...c3.slice(1))) : this.mergedHdRoute.route.push(...c3), this.mergedHdRoute.vias.push(...a3.vias), a3.jumpers \u0026\u0026 this.mergedHdRoute.jumpers.push(...a3.jumpers);\n }\n visualize() {\n const e51 = { points: [], lines: [], circles: [], rects: [], title: \"Single High Density Route Stitch Solver 3\" };\n if (e51.points?.push({ x: this.start.x, y: this.start.y, color: \"green\", label: \"Start\" }, { x: this.end.x, y: this.end.y, color: \"red\", label: \"End\" }), this.mergedHdRoute \u0026\u0026 this.mergedHdRoute.route.length \u003e 1) {\n e51.lines?.push({ points: this.mergedHdRoute.route.map((e52) =\u003e ({ x: e52.x, y: e52.y })), strokeColor: \"green\" });\n for (const t2 of this.mergedHdRoute.route)\n e51.points?.push({ x: t2.x, y: t2.y, color: \"green\" });\n for (const t2 of this.mergedHdRoute.vias)\n e51.circles?.push({ center: { x: t2.x, y: t2.y }, radius: this.mergedHdRoute.viaDiameter / 2, fill: \"green\" });\n if (this.mergedHdRoute.jumpers \u0026\u0026 this.mergedHdRoute.jumpers.length \u003e 0) {\n const t2 = fB(this.mergedHdRoute.jumpers, { color: \"green\", label: this.mergedHdRoute.connectionName });\n e51.rects.push(...t2.rects ?? []), e51.lines.push(...t2.lines ?? []);\n }\n }\n for (const t2 of this.remainingHdRoutes) {\n e51.lines?.push({ points: t2.route.map((e52) =\u003e ({ x: e52.x, y: e52.y })), strokeColor: \"orange\" });\n for (const n2 of t2.route)\n e51.points?.push({ x: n2.x, y: n2.y, color: \"orange\" });\n for (const n2 of t2.vias)\n e51.circles?.push({ center: { x: n2.x, y: n2.y }, radius: t2.viaDiameter / 2, fill: \"orange\" });\n if (t2.jumpers \u0026\u0026 t2.jumpers.length \u003e 0) {\n const n2 = fB(t2.jumpers, { color: \"orange\", label: t2.connectionName });\n e51.rects.push(...n2.rects ?? []), e51.lines.push(...n2.lines ?? []);\n }\n }\n return e51;\n }\n};\nvar E1 = class {\n constructor(e51 = false) {\n this.preferSameLayerTerminalEndpoints = e51;\n }\n endpointClusters = new Map;\n getEndpointKey(e51, t2) {\n const n2 = this.endpointClusters.get(e51) ?? [];\n let o3, i3 = 1 / 0;\n for (const e52 of n2) {\n if (e52.point.z !== t2.z)\n continue;\n const n3 = me(e52.point, t2);\n n3 \u003c= 0.1 \u0026\u0026 (n3 \u003c i3 - b1 || Math.abs(n3 - i3) \u003c= b1 \u0026\u0026 (!o3 || I1(e52.point, o3.point) \u003c 0)) \u0026\u0026 (o3 = e52, i3 = n3);\n }\n if (o3)\n return o3.key;\n const r3 = `${e51}:endpoint_${n2.length}`;\n return n2.push({ key: r3, point: { x: t2.x, y: t2.y, z: t2.z } }), this.endpointClusters.set(e51, n2), r3;\n }\n getClusters(e51) {\n return this.endpointClusters.get(e51) ?? [];\n }\n getClosestEndpointKey(e51, t2, n2) {\n const o3 = t2.flatMap((e52) =\u003e [e52.route[0], e52.route[e52.route.length - 1]]), i3 = o3.filter((e52) =\u003e e52.z === n2.z), r3 = this.preferSameLayerTerminalEndpoints \u0026\u0026 i3.length \u003e 0 ? i3 : o3;\n let s2 = null, a3 = null, c3 = 1 / 0;\n for (const t3 of r3) {\n const o4 = me(n2, t3), i4 = this.getEndpointKey(e51, t3);\n (o4 \u003c c3 - b1 || Math.abs(o4 - c3) \u003c= b1 \u0026\u0026 (s2 === null || i4.localeCompare(s2) \u003c 0 || i4 === s2 \u0026\u0026 a3 !== null \u0026\u0026 I1(t3, a3) \u003c 0)) \u0026\u0026 (c3 = o4, s2 = i4, a3 = t3);\n }\n return s2;\n }\n};\nvar A1 = (e51, t2, n2) =\u003e {\n const o3 = e51.get(t2) ?? [];\n o3.some((e52) =\u003e e52.nextHash === n2.nextHash \u0026\u0026 e52.routeIndex === n2.routeIndex) || (o3.push(n2), e51.set(t2, o3));\n};\nvar O1 = (e51) =\u003e {\n const t2 = [...e51.possibleEndpoints].sort(I1), n2 = t2.reduce((t3, n3) =\u003e {\n const o4 = me(n3, e51.globalStart), i4 = me(t3, e51.globalStart);\n return o4 \u003c i4 - b1 || Math.abs(o4 - i4) \u003c= b1 \u0026\u0026 I1(n3, t3) \u003c 0 ? n3 : t3;\n }), o3 = t2.filter((e52) =\u003e e52 !== n2), i3 = (o3.length \u003e 0 ? o3 : e51.possibleEndpoints).reduce((t3, n3) =\u003e {\n const o4 = me(n3, e51.globalEnd), i4 = me(t3, e51.globalEnd);\n return o4 \u003c i4 - b1 || Math.abs(o4 - i4) \u003c= b1 \u0026\u0026 I1(n3, t3) \u003c 0 ? n3 : t3;\n });\n return { start: n2, end: i3 };\n};\nvar k1 = (e51) =\u003e {\n const t2 = e51.terminals.filter((t3) =\u003e t3.z === e51.islandEndpoint.z);\n if (e51.preferSameLayerTerminalEndpoints \u0026\u0026 t2.length === 0)\n return e51.islandEndpoint;\n const n2 = [...e51.preferSameLayerTerminalEndpoints ? t2 : e51.terminals].sort(I1);\n let o3 = n2[0], i3 = me(e51.islandEndpoint, o3);\n for (const t3 of n2.slice(1)) {\n const n3 = me(e51.islandEndpoint, t3);\n (n3 \u003c i3 - b1 || Math.abs(n3 - i3) \u003c= b1 \u0026\u0026 I1(t3, o3) \u003c 0) \u0026\u0026 (o3 = t3, i3 = n3);\n }\n return i3 \u003c= x1 ? o3 : e51.islandEndpoint;\n};\nvar D1 = (e51) =\u003e {\n if (e51.hdRoutes.length \u003c= 2)\n return e51.hdRoutes;\n const t2 = [...e51.hdRoutes].sort(P1), n2 = e51.endpointIndex.getClosestEndpointKey(e51.connectionName, t2, e51.start), o3 = e51.endpointIndex.getClosestEndpointKey(e51.connectionName, t2, e51.end);\n if (!n2 || !o3 || n2 === o3)\n return t2;\n const i3 = new Map;\n for (let n3 = 0;n3 \u003c t2.length; n3++) {\n const o4 = t2[n3], r4 = e51.endpointIndex.getEndpointKey(e51.connectionName, o4.route[0]), s3 = e51.endpointIndex.getEndpointKey(e51.connectionName, o4.route[o4.route.length - 1]);\n A1(i3, r4, { nextHash: s3, routeIndex: n3 }), A1(i3, s3, { nextHash: r4, routeIndex: n3 });\n }\n const r3 = [...e51.endpointIndex.getClusters(e51.connectionName)].sort((e52, t3) =\u003e I1(e52.point, t3.point));\n for (let e52 = 0;e52 \u003c r3.length; e52++) {\n const t3 = r3[e52];\n for (let n3 = e52 + 1;n3 \u003c r3.length; n3++) {\n const e53 = r3[n3];\n t3.point.z === e53.point.z \u0026\u0026 (me(t3.point, e53.point) \u003e 1 || (A1(i3, t3.key, { nextHash: e53.key, routeIndex: null }), A1(i3, e53.key, { nextHash: t3.key, routeIndex: null })));\n }\n }\n for (const [e52, n3] of i3.entries())\n i3.set(e52, [...n3].sort((e53, n4) =\u003e {\n if (e53.routeIndex === null \u0026\u0026 n4.routeIndex !== null)\n return 1;\n if (e53.routeIndex !== null \u0026\u0026 n4.routeIndex === null)\n return -1;\n if (e53.routeIndex !== null \u0026\u0026 n4.routeIndex !== null) {\n const o4 = P1(t2[e53.routeIndex], t2[n4.routeIndex]);\n if (o4 !== 0)\n return o4;\n }\n return e53.nextHash.localeCompare(n4.nextHash);\n }));\n const s2 = [n2], a3 = new Set([n2]), c3 = new Map;\n for (;s2.length \u003e 0; ) {\n const e52 = s2.shift();\n if (e52 === o3)\n break;\n for (const t3 of i3.get(e52) ?? [])\n a3.has(t3.nextHash) || (a3.add(t3.nextHash), c3.set(t3.nextHash, { prevHash: e52, routeIndex: t3.routeIndex }), s2.push(t3.nextHash));\n }\n if (!a3.has(o3))\n return t2;\n const l3 = [];\n let h2 = o3;\n for (;h2 !== n2; ) {\n const e52 = c3.get(h2);\n if (!e52)\n return t2;\n e52.routeIndex !== null \u0026\u0026 l3.push(e52.routeIndex), h2 = e52.prevHash;\n }\n if (l3.length === 0)\n return e51.hdRoutes;\n const d2 = l3.reverse().map((e52) =\u003e t2[e52]);\n return d2.length \u003e 0 \u0026\u0026 !e51.canStitchBetweenTerminals({ connectionName: e51.connectionName, hdRoutes: d2, start: e51.start, end: e51.end }) ? t2 : d2;\n};\nvar L1 = class extends ni {\n getSolverName() {\n return \"MultipleHighDensityRouteStitchSolver3\";\n }\n unsolvedRoutes;\n activeSolver = null;\n mergedHdRoutes = [];\n colorMap = {};\n defaultTraceThickness;\n defaultViaDiameter;\n allowedLayerTransitionPointKeys;\n preserveTerminalPcbPortIds;\n terminalPcbPortIdsByConnection = new Map;\n preferSameLayerTerminalEndpoints;\n endpointIndex;\n clearanceValidator;\n canStitchBetweenTerminals(e51) {\n const t2 = new T1({ connectionName: e51.connectionName, hdRoutes: e51.hdRoutes, start: e51.start, end: e51.end, colorMap: this.colorMap, defaultTraceThickness: this.defaultTraceThickness, defaultViaDiameter: this.defaultViaDiameter, allowedLayerTransitionPointKeys: this.allowedLayerTransitionPointKeys, preserveTerminalPcbPortIds: this.preserveTerminalPcbPortIds, allowedTerminalPcbPortIds: this.terminalPcbPortIdsByConnection.get(e51.connectionName), isStitchSegmentClear: (e52) =\u003e this.clearanceValidator.isSegmentClear(e52), stitchClearanceMode: \"require_clear\" });\n for (;!t2.solved \u0026\u0026 !t2.failed \u0026\u0026 t2.iterations \u003c t2.MAX_ITERATIONS; )\n t2.step();\n if (t2.failed)\n return false;\n const n2 = t2.mergedHdRoute.route[0], o3 = t2.mergedHdRoute.route[t2.mergedHdRoute.route.length - 1];\n return n2.z === t2.start.z \u0026\u0026 o3.z === t2.end.z \u0026\u0026 me(n2, t2.start) + me(o3, t2.end) \u003c= x1;\n }\n getSharedRootPathRoutes(e51) {\n const t2 = e51.rootConnectionName;\n if (!t2)\n return null;\n const n2 = new Set(e51.hdRoutes), o3 = e51.allHdRoutes.filter((e52) =\u003e (e52.rootConnectionName ?? e52.connectionName) === t2);\n if (o3.every((e52) =\u003e n2.has(e52)))\n return null;\n const i3 = D1({ connectionName: e51.connectionName, hdRoutes: o3, start: e51.start, end: e51.end, endpointIndex: this.endpointIndex, canStitchBetweenTerminals: (e52) =\u003e this.canStitchBetweenTerminals(e52) });\n return !i3.some((e52) =\u003e !n2.has(e52)) || i3.length \u003e= o3.length ? null : i3;\n }\n constructor(e51) {\n super(), this.preferSameLayerTerminalEndpoints = e51.preferSameLayerTerminalEndpoints ?? false, this.endpointIndex = new E1(e51.preferSameLayerTerminalEndpoints), this.colorMap = e51.colorMap ?? {}, this.allowedLayerTransitionPointKeys = e51.allowedLayerTransitionPointKeys, this.preserveTerminalPcbPortIds = e51.preserveTerminalPcbPortIds ?? false;\n const t2 = ei({ connections: e51.connections, layerCount: e51.layerCount, obstacles: [] }), n2 = new Map;\n for (const o4 of e51.connections) {\n const e52 = t2.getNetConnectedToId(o4.name) ?? o4.name;\n let i4 = n2.get(e52);\n i4 || (i4 = new Set, n2.set(e52, i4));\n for (const e53 of o4.pointsToConnect)\n e53.pcb_port_id \u0026\u0026 i4.add(e53.pcb_port_id);\n this.terminalPcbPortIdsByConnection.set(o4.name, i4);\n }\n const o3 = [...e51.hdRoutes].sort(P1);\n this.clearanceValidator = new y1({ hdRoutes: o3 });\n const i3 = o3[0];\n this.defaultTraceThickness = i3?.traceThickness ?? 0.15, this.defaultViaDiameter = i3?.viaDiameter ?? e51.defaultViaDiameter ?? 0.3;\n const r3 = new mB({}), s2 = [], a3 = new Map;\n for (let e52 = 0;e52 \u003c o3.length; e52++) {\n const t3 = o3[e52], n3 = t3.route[0], i4 = t3.route[t3.route.length - 1];\n s2.push([`route_island_${e52}`, this.endpointIndex.getEndpointKey(t3.connectionName, n3), this.endpointIndex.getEndpointKey(t3.connectionName, i4)]);\n }\n r3.addConnections(s2);\n for (const e52 of s2)\n for (const t3 of e52.slice(1))\n a3.set(t3, (a3.get(t3) ?? 0) + 1);\n this.unsolvedRoutes = [];\n const c3 = Array.from(new Set(Object.values(r3.idToNetMap)));\n for (const t3 of c3) {\n const n3 = r3.getIdsConnectedToNet(t3), i4 = o3.filter((e52, t4) =\u003e n3.includes(`route_island_${t4}`));\n if (i4.length === 0)\n continue;\n const s3 = e51.connections.find((e52) =\u003e e52.name === i4[0].connectionName), c4 = i4.flatMap((e52) =\u003e [e52.route[0], e52.route[e52.route.length - 1]]), l4 = new Map, h2 = [];\n for (const e52 of c4) {\n const t4 = this.endpointIndex.getEndpointKey(i4[0].connectionName, e52);\n l4.has(t4) || l4.set(t4, e52), a3.get(t4) === 1 \u0026\u0026 h2.push(e52);\n }\n const d2 = h2.length \u003e 0 ? h2 : [...l4.values()];\n if (d2.length === 0)\n continue;\n let u2, p3;\n if (d2.length \u003e= 2) {\n const t4 = { ...s3.pointsToConnect[0], z: mo(Io(s3.pointsToConnect[0]), e51.layerCount) }, n4 = { ...s3.pointsToConnect[1], z: mo(Io(s3.pointsToConnect[1]), e51.layerCount) };\n ({ start: u2, end: p3 } = O1({ possibleEndpoints: d2, globalStart: t4, globalEnd: n4 })), me(u2, s3.pointsToConnect[1]) \u003c me(p3, s3.pointsToConnect[0]) \u0026\u0026 ([u2, p3] = [p3, u2]), u2 = k1({ islandEndpoint: u2, terminals: [t4, n4], preferSameLayerTerminalEndpoints: this.preferSameLayerTerminalEndpoints }), p3 = k1({ islandEndpoint: p3, terminals: [t4, n4], preferSameLayerTerminalEndpoints: this.preferSameLayerTerminalEndpoints });\n } else\n u2 = { ...s3.pointsToConnect[0], z: mo(Io(s3.pointsToConnect[0]), e51.layerCount) }, p3 = { ...s3.pointsToConnect[1], z: mo(Io(s3.pointsToConnect[1]), e51.layerCount) };\n const m2 = D1({ connectionName: i4[0].connectionName, hdRoutes: i4, start: u2, end: p3, endpointIndex: this.endpointIndex, canStitchBetweenTerminals: (e52) =\u003e this.canStitchBetweenTerminals(e52) });\n this.unsolvedRoutes.push({ connectionName: i4[0].connectionName, hdRoutes: m2, start: u2, end: p3 });\n }\n const l3 = new Map;\n for (const e52 of this.unsolvedRoutes) {\n const t3 = l3.get(e52.connectionName);\n t3 ? t3.push(e52) : l3.set(e52.connectionName, [e52]);\n }\n this.unsolvedRoutes = Array.from(l3.entries()).flatMap(([t3, n3]) =\u003e {\n const i4 = e51.connections.find((e52) =\u003e e52.name === t3), r4 = n3.some((e52) =\u003e e52.hdRoutes.some((e53) =\u003e e53.route.length \u003c 2)), s3 = n3.length \u003e 1 \u0026\u0026 ((e52) =\u003e {\n for (let t4 = 0;t4 \u003c e52.length; t4++)\n for (let n4 = t4 + 1;n4 \u003c e52.length; n4++) {\n const o4 = [e52[t4].start, e52[t4].end], i5 = [e52[n4].start, e52[n4].end];\n for (const e53 of o4)\n for (const t5 of i5)\n if (e53.z === t5.z \u0026\u0026 me(e53, t5) \u003c= 1)\n return true;\n }\n return false;\n })(n3);\n if (!i4)\n return n3;\n const a4 = { ...i4.pointsToConnect[0], z: mo(Io(i4.pointsToConnect[0]), e51.layerCount) }, c4 = { ...i4.pointsToConnect[1], z: mo(Io(i4.pointsToConnect[1]), e51.layerCount) }, l4 = n3.flatMap((e52) =\u003e e52.hdRoutes), h2 = n3.length \u003e 1 ? this.getSharedRootPathRoutes({ connectionName: t3, rootConnectionName: i4.__rootConnectionNames?.[0] ?? l4[0]?.rootConnectionName, hdRoutes: l4, allHdRoutes: o3, start: a4, end: c4 }) : null;\n return r4 || s3 || h2 ? [{ connectionName: t3, hdRoutes: h2 ?? D1({ connectionName: t3, hdRoutes: l4, start: a4, end: c4, endpointIndex: this.endpointIndex, canStitchBetweenTerminals: (e52) =\u003e this.canStitchBetweenTerminals(e52) }), start: a4, end: c4 }] : n3;\n }), this.MAX_ITERATIONS = 1e5;\n }\n _step() {\n if (this.activeSolver)\n return this.activeSolver.step(), void (this.activeSolver.solved ? (this.activeSolver instanceof T1 \u0026\u0026 (this.clearanceValidator.addRoute(this.activeSolver.mergedHdRoute), this.mergedHdRoutes.push(this.activeSolver.mergedHdRoute)), this.activeSolver = null) : this.activeSolver.failed \u0026\u0026 (this.failed = true, this.error = this.activeSolver.error));\n const e51 = this.unsolvedRoutes.pop();\n if (!e51) {\n const e52 = new Set;\n for (const t2 of this.mergedHdRoutes)\n t2.startPcbPortId \u0026\u0026 t2.endPcbPortId \u0026\u0026 e52.add(t2.connectionName);\n return this.mergedHdRoutes = this.mergedHdRoutes.filter((t2) =\u003e !e52.has(t2.connectionName) || Boolean(t2.startPcbPortId \u0026\u0026 t2.endPcbPortId)), void (this.solved = true);\n }\n this.activeSolver = new T1({ connectionName: e51.connectionName, hdRoutes: e51.hdRoutes, start: e51.start, end: e51.end, colorMap: this.colorMap, defaultTraceThickness: this.defaultTraceThickness, defaultViaDiameter: this.defaultViaDiameter, allowedLayerTransitionPointKeys: this.allowedLayerTransitionPointKeys, preserveTerminalPcbPortIds: this.preserveTerminalPcbPortIds, allowedTerminalPcbPortIds: this.terminalPcbPortIdsByConnection.get(e51.connectionName), isStitchSegmentClear: (e52) =\u003e this.clearanceValidator.isSegmentClear(e52), stitchClearanceMode: \"prefer_clear\" });\n }\n visualize() {\n const e51 = { points: [], lines: [], circles: [], rects: [], title: \"Multiple High Density Route Stitch Solver 3\" };\n if (this.activeSolver) {\n const t2 = this.activeSolver.visualize();\n t2.points?.length \u0026\u0026 e51.points?.push(...t2.points), t2.lines?.length \u0026\u0026 e51.lines?.push(...t2.lines), t2.circles?.length \u0026\u0026 e51.circles?.push(...t2.circles), t2.rects?.length \u0026\u0026 (e51.rects || (e51.rects = []), e51.rects.push(...t2.rects));\n }\n for (const [t2, n2] of this.mergedHdRoutes.entries()) {\n const o3 = this.colorMap[n2.connectionName] ?? `hsl(120, 100%, ${40 + 10 * t2 % 40}%)`;\n for (let t3 = 0;t3 \u003c n2.route.length - 1; t3++) {\n const i3 = n2.route[t3], r3 = n2.route[t3 + 1], s2 = i3.z !== 0 ? Ao(o3, 0.5) : o3;\n e51.lines?.push({ points: [{ x: i3.x, y: i3.y }, { x: r3.x, y: r3.y }], strokeColor: s2, strokeWidth: n2.traceThickness });\n }\n for (const t3 of n2.route) {\n const n3 = t3.z !== 0 ? Ao(o3, 0.5) : o3;\n e51.points?.push({ x: t3.x, y: t3.y, color: n3 });\n }\n for (const t3 of n2.vias)\n e51.circles?.push({ center: { x: t3.x, y: t3.y }, radius: n2.viaDiameter / 2, fill: o3 });\n if (n2.jumpers \u0026\u0026 n2.jumpers.length \u003e 0) {\n const t3 = fB(n2.jumpers, { color: o3, label: n2.connectionName });\n e51.rects.push(...t3.rects ?? []), e51.lines.push(...t3.lines ?? []);\n }\n }\n return e51;\n }\n};\nvar z1 = 0.001;\nvar B1 = (e51) =\u003e e51.route_type === \"wire\";\nvar F1 = (e51) =\u003e e51.route_type === \"via\";\nvar j1 = (e51) =\u003e e51.route_type === \"through_obstacle\";\nvar $1 = (e51, t2, n2) =\u003e {\n const o3 = mo(e51, n2), i3 = mo(t2, n2), r3 = Math.min(o3, i3), s2 = Math.max(o3, i3);\n return Array.from({ length: s2 - r3 + 1 }, (e52, t3) =\u003e Co(r3 + t3, n2));\n};\nvar Y1 = ({ obstacleId: e51, start: t2, end: n2, width: o3, layer: i3, connectedTo: r3 }) =\u003e {\n const s2 = n2.x - t2.x, a3 = n2.y - t2.y, c3 = Math.hypot(s2, a3);\n return c3 \u003c= z1 ? null : { obstacleId: e51, type: \"rect\", layers: [i3], center: { x: (t2.x + n2.x) / 2, y: (t2.y + n2.y) / 2 }, width: c3, height: Math.max(o3, z1), ccwRotationDegrees: 180 * Math.atan2(a3, s2) / Math.PI, connectedTo: r3 };\n};\nfunction X1(e51) {\n if (!e51)\n return e51;\n const t2 = ((e52) =\u003e {\n if (!e52)\n return [];\n const t3 = [], n2 = Yo(e52);\n for (const [o3, i3] of (e52.traces ?? []).entries()) {\n const r3 = i3.connectsTo ?? [];\n for (let s2 = 0;s2 \u003c i3.route.length; s2++) {\n const a3 = i3.route[s2];\n if (F1(a3)) {\n const c3 = a3.via_diameter ?? n2.padDiameter;\n t3.push({ obstacleId: `trace_obstacle_${i3.pcb_trace_id}_${o3}_${s2}_via`, type: \"rect\", layers: $1(a3.from_layer, a3.to_layer, e52.layerCount), center: { x: a3.x, y: a3.y }, width: Math.max(c3, z1), height: Math.max(c3, z1), connectedTo: r3 });\n continue;\n }\n if (j1(a3)) {\n const n3 = Y1({ obstacleId: `trace_obstacle_${i3.pcb_trace_id}_${o3}_${s2}_through`, start: a3.start, end: a3.end, width: a3.width, layer: a3.from_layer, connectedTo: r3 });\n n3 \u0026\u0026 (n3.layers = $1(a3.from_layer, a3.to_layer, e52.layerCount), t3.push(n3));\n }\n }\n for (let e53 = 0;e53 \u003c i3.route.length - 1; e53++) {\n const n3 = i3.route[e53], s2 = i3.route[e53 + 1];\n if (!B1(n3) || !B1(s2) || n3.layer !== s2.layer)\n continue;\n const a3 = Y1({ obstacleId: `trace_obstacle_${i3.pcb_trace_id}_${o3}_${e53}_wire`, start: n3, end: s2, width: n3.width, layer: n3.layer, connectedTo: r3 });\n a3 \u0026\u0026 t3.push(a3);\n }\n }\n return t3;\n })(e51);\n return t2.length === 0 ? e51 : { ...e51, obstacles: [...e51.obstacles ?? [], ...t2] };\n}\nfunction H1(e51, t2) {\n const n2 = function(e52, t3) {\n const n3 = go(e52.__zLayers ?? e52.zLayers ?? [], t3);\n if (n3.length \u003e 0)\n return n3;\n const o3 = fo(e52.layers, t3);\n if (o3.length \u003e 0)\n return o3;\n throw new Error(`Obstacle \"${e52.obstacleId ?? \"unknown\"}\" has no layers on this ${t3}-layer board`);\n }(e51, t2);\n return { ...e51, layers: n2.map((e52) =\u003e Co(e52, t2)), zLayers: n2, __zLayers: n2 };\n}\nfunction V1(e51) {\n return { ...e51, obstacles: e51.obstacles.map((t2) =\u003e H1(t2, e51.layerCount)), jumpers: e51.jumpers?.map((t2) =\u003e ({ ...t2, pads: t2.pads.map((t3) =\u003e H1(t3, e51.layerCount)) })) };\n}\nvar W1 = (e51) =\u003e {\n const t2 = e51.obstacles.filter((t3) =\u003e !((e52, t4) =\u003e !((e53) =\u003e (e53.connectedTo?.length ?? 0) \u003e 0 || (e53.offBoardConnectsTo?.length ?? 0) \u003e 0 || e53.netIsAssignable === true)(e52) \u0026\u0026 (t4.outline \u0026\u0026 t4.outline.length \u003e= 3 ? !Se(e52, t4.outline) : !De({ minX: e52.center.x - e52.width / 2, maxX: e52.center.x + e52.width / 2, minY: e52.center.y - e52.height / 2, maxY: e52.center.y + e52.height / 2 }, t4.bounds)))(t3, e51)), n2 = t2.length !== e51.obstacles.length, o3 = n2 \u0026\u0026 e51.outline \u0026\u0026 e51.outline.length \u003e= 3 ? ((e52) =\u003e {\n if (e52.width \u0026\u0026 e52.height \u0026\u0026 e52.center) {\n const t4 = e52.width / 2, n4 = e52.height / 2;\n return { minX: e52.center.x - t4, minY: e52.center.y - n4, maxX: e52.center.x + t4, maxY: e52.center.y + n4, width: e52.width, height: e52.height, center: { x: e52.center.x, y: e52.center.y } };\n }\n if (!e52.outline || e52.outline.length === 0)\n throw new Error(\"Unable to compute board bounds. pcb_board must include width/height/center or a non-empty outline.\");\n let { POSITIVE_INFINITY: t3, POSITIVE_INFINITY: n3, NEGATIVE_INFINITY: o4, NEGATIVE_INFINITY: i3 } = Number;\n for (const r4 of e52.outline)\n t3 = Math.min(t3, r4.x), n3 = Math.min(n3, r4.y), o4 = Math.max(o4, r4.x), i3 = Math.max(i3, r4.y);\n const r3 = o4 - t3, s2 = i3 - n3;\n return { minX: t3, minY: n3, maxX: o4, maxY: i3, width: r3, height: s2, center: { x: t3 + r3 / 2, y: n3 + s2 / 2 } };\n })({ type: \"pcb_board\", pcb_board_id: \"__autorouting_board_outline__\", center: { x: 0, y: 0 }, thickness: 1, num_layers: e51.layerCount, material: \"fr4\", outline: e51.outline }) : e51.bounds;\n return n2 ? { ...e51, obstacles: t2, bounds: o3 } : e51;\n};\nfunction G1(e51) {\n const { minX: t2, maxX: n2, minY: o3, maxY: i3 } = e51.bounds;\n for (const r3 of e51.connections)\n if (!r3.isOffBoard) {\n for (const [e52, s2] of r3.pointsToConnect.entries())\n if (!(s2.x \u003e= t2 \u0026\u0026 s2.x \u003c= n2 \u0026\u0026 s2.y \u003e= o3 \u0026\u0026 s2.y \u003c= i3))\n return `Connection \"${r3.name}\" point \"${s2.pointId ?? e52}\" at (${s2.x}, ${s2.y}) is outside routing bounds: x [${t2}, ${n2}], y [${o3}, ${i3}]`;\n }\n return null;\n}\nvar U1 = class extends ni {\n constructor(e51, t2 = {}) {\n super(), this.inputSrj = e51, this.visualizationOptions = t2, this.MAX_ITERATIONS = 1;\n }\n outputSrj;\n _step() {\n if (this.error = G1(this.inputSrj), this.error)\n return void (this.failed = true);\n const e51 = V1(this.inputSrj), t2 = X1(e51) ?? e51, n2 = Zr(W1(t2));\n this.outputSrj = V1(n2), this.solved = true;\n }\n getOutputSimpleRouteJson() {\n if (!this.outputSrj)\n throw new Error(\"PreprocessSimpleRouteJsonSolver has not solved yet\");\n return this.outputSrj;\n }\n getConstructorParams() {\n return [this.inputSrj, this.visualizationOptions];\n }\n visualize() {\n return this.outputSrj ? pi(Wo({ ...this.outputSrj, traces: [] }, this.visualizationOptions), nK({ srj: this.outputSrj, visualizationOptions: this.visualizationOptions })) : { lines: [], points: [], rects: [], circles: [] };\n }\n};\nfunction Z1(e51, t2, n2, o3 = {}) {\n return { solverName: e51, solverClass: t2, getConstructorParams: n2, onSolved: o3.onSolved };\n}\nvar q1 = class extends ni {\n constructor(e51, t2 = {}) {\n super(), this.srj = e51, this.opts = t2, this.originalSrj = e51, this.opts = { ...t2 };\n const n2 = this.opts;\n if (this.effort = n2.effort ?? 1, this.MAX_ITERATIONS = 1e8 * this.effort, this.maxNodeDimension = n2.maxNodeDimension ?? 16, this.maxNodeRatio = n2.maxNodeRatio ?? 6, this.minNodeArea = n2.minNodeArea ?? 0.1 ** 2, this.setSimpleRouteJson(e51), n2.capacityDepth === undefined) {\n const e52 = this.srj.bounds.maxX - this.srj.bounds.minX, t3 = this.srj.bounds.maxY - this.srj.bounds.minY, o3 = Math.max(e52, t3), i3 = n2.targetMinCapacity ?? 0.5;\n n2.capacityDepth = Fz(o3, i3);\n }\n this.cacheProvider = n2.cacheProvider === undefined ? no() : n2.cacheProvider === null ? null : n2.cacheProvider, this.startTimeOfPhase = {}, this.endTimeOfPhase = {}, this.timeSpentOnPhase = {};\n }\n preprocessSimpleRouteJsonSolver;\n escapeViaLocationSolver;\n netToPointPairsSolver;\n nodeSolver;\n nodeDimensionSubdivisionSolver;\n nodeTargetMerger;\n edgeSolver;\n colorMap;\n highDensityRouteSolver;\n highDensityForceImproveSolver;\n highDensityRepairSolver;\n highDensityStitchSolver;\n globalDrcForceImproveSolver;\n singleLayerNodeMerger;\n strawSolver;\n deadEndSolver;\n traceSimplificationSolver;\n availableSegmentPointSolver;\n portPointPathingSolver;\n multiSectionPortPointOptimizer;\n uniformPortDistributionSolver;\n traceWidthSolver;\n necessaryCrampedPortPointSolver;\n viaDiameter;\n viaHoleDiameter;\n minTraceWidth;\n effort;\n maxNodeDimension;\n maxNodeRatio;\n minNodeArea;\n startTimeOfPhase;\n endTimeOfPhase;\n timeSpentOnPhase;\n activeSubSolver = null;\n connMap;\n srjWithEscapeViaLocations;\n srjWithPointPairs;\n originalSrj;\n capacityNodes = null;\n capacityEdges = null;\n highDensityNodePortPoints;\n cacheProvider = null;\n pipelineDef = [Z1(\"preprocessSimpleRouteJsonSolver\", U1, (e51) =\u003e [e51.originalSrj], { onSolved: (e51) =\u003e {\n e51.setSimpleRouteJson(e51.preprocessSimpleRouteJsonSolver.getOutputSimpleRouteJson());\n } }), Z1(\"escapeViaLocationSolver\", uK, (e51) =\u003e [e51.srj, { viaDiameter: e51.viaDiameter, minTraceWidth: e51.minTraceWidth, obstacleMargin: e51.srj.defaultObstacleMargin ?? 0.15 }], { onSolved: (e51) =\u003e {\n e51.srjWithEscapeViaLocations = e51.escapeViaLocationSolver?.getOutputSimpleRouteJson();\n } }), Z1(\"netToPointPairsSolver\", pB, (e51) =\u003e {\n const t2 = e51.srjWithEscapeViaLocations ?? e51.srj;\n return [t2, e51.colorMap, ti(t2)];\n }, { onSolved: (e51) =\u003e {\n e51.srjWithPointPairs = e51.netToPointPairsSolver?.getNewSimpleRouteJson(), e51.colorMap = Eo(e51.srjWithPointPairs, e51.connMap), e51.connMap = ei(e51.srjWithPointPairs);\n } }), Z1(\"nodeSolver\", Jn, (e51) =\u003e [{ simpleRouteJson: e51.srjWithPointPairs, maxGapFillPasses: 4 }], { onSolved: (e51) =\u003e {\n e51.capacityNodes = e51.nodeSolver?.getOutput().meshNodes ?? [];\n } }), Z1(\"nodeDimensionSubdivisionSolver\", MZ, (e51) =\u003e [e51.capacityNodes, e51.maxNodeDimension, e51.maxNodeRatio, e51.minNodeArea], { onSolved: (e51) =\u003e {\n e51.capacityNodes = e51.nodeDimensionSubdivisionSolver?.outputNodes ?? [];\n } }), Z1(\"edgeSolver\", ui, (e51) =\u003e [e51.capacityNodes], { onSolved: (e51) =\u003e {\n e51.capacityEdges = e51.edgeSolver?.edges;\n } }), Z1(\"availableSegmentPointSolver\", ii, (e51) =\u003e [{ nodes: e51.capacityNodes, edges: e51.capacityEdges || [], traceWidth: e51.minTraceWidth, colorMap: e51.colorMap, shouldReturnCrampedPortPoints: true }]), Z1(\"necessaryCrampedPortPointSolver\", FG, (e51) =\u003e [{ capacityMeshNodes: e51.capacityNodes, sharedEdgeSegments: e51.availableSegmentPointSolver.getOutput(), simpleRouteJson: e51.srjWithPointPairs }]), Z1(\"portPointPathingSolver\", eK, (e51) =\u003e {\n const t2 = e51.necessaryCrampedPortPointSolver?.getOutput() ?? e51.availableSegmentPointSolver.getOutput(), { graph: n2, connections: o3 } = KG({ capacityMeshNodes: e51.capacityNodes, layerCount: e51.srj.layerCount, connectivityMap: e51.connMap, segmentPortPoints: t2.flatMap((e52) =\u003e e52.portPoints), simpleRouteJsonConnections: e51.srjWithPointPairs.connections });\n return [{ graph: n2, connections: o3, layerCount: e51.srj.layerCount, effort: Math.min(1, e51.effort), minViaPadDiameter: e51.viaDiameter, flags: { FORCE_CENTER_FIRST: true, RIPPING_ENABLED: true }, weights: { SHUFFLE_SEED: 0, MEMORY_PF_FACTOR: 4, CENTER_OFFSET_DIST_PENALTY_FACTOR: 0, CENTER_OFFSET_FOCUS_SHIFT: 0, NODE_PF_FACTOR: 0, LAYER_CHANGE_COST: 0, RIPPING_PF_COST: 0, NODE_PF_MAX_PENALTY: 100, BASE_CANDIDATE_COST: 0.6, MAX_ITERATIONS_PER_PATH: 0, RANDOM_WALK_DISTANCE: 0, START_RIPPING_PF_THRESHOLD: 0.3, END_RIPPING_PF_THRESHOLD: 1, MAX_RIPS: 1000, RANDOM_RIP_FRACTION: 0.3, STRAIGHT_LINE_DEVIATION_PENALTY_FACTOR: 4, GREEDY_MULTIPLIER: 0.7, MIN_ALLOWED_BOARD_SCORE: -1e4 } }];\n }), Z1(\"uniformPortDistributionSolver\", bo, (e51) =\u003e [{ nodeWithPortPoints: e51.portPointPathingSolver?.getOutput().nodesWithPortPoints ?? [], inputNodesWithPortPoints: e51.portPointPathingSolver?.getOutput().inputNodeWithPortPoints ?? [], minTraceWidth: e51.minTraceWidth, obstacles: e51.srj.obstacles, layerCount: e51.srj.layerCount }]), Z1(\"highDensityRouteSolver\", Dz, (e51) =\u003e {\n const t2 = e51.uniformPortDistributionSolver?.getOutput() ?? [], n2 = e51.portPointPathingSolver?.getOutput().nodesWithPortPoints ?? [], o3 = (t2.length \u003e 0 ? t2 : n2).map((t3) =\u003e Mz(t3) ? { ...t3, availableZ: Array.from({ length: e51.srj.layerCount }, (e52, t4) =\u003e t4) } : t3);\n return e51.highDensityNodePortPoints = structuredClone(o3), [{ nodePortPoints: o3, nodePfById: new Map((e51.portPointPathingSolver?.getOutput().inputNodeWithPortPoints ?? []).map((t3) =\u003e [t3.capacityMeshNodeId, e51.portPointPathingSolver?.computeNodePf(t3) ?? null])), colorMap: e51.colorMap, connMap: e51.connMap, viaDiameter: e51.viaDiameter, traceWidth: e51.minTraceWidth, obstacleMargin: e51.srj.defaultObstacleMargin ?? 0.15, obstacles: e51.srj.obstacles, layerCount: e51.srj.layerCount, useGrowShrinkHighDensityIntraNodeSolver: true }];\n }), Z1(\"highDensityForceImproveSolver\", SZ, (e51) =\u003e [{ nodeWithPortPoints: e51.highDensityNodePortPoints ?? [], hdRoutes: e51.highDensityRouteSolver.routes, colorMap: e51.colorMap, totalStepsPerNode: Math.max(20, Math.round(60 * Math.min(1, e51.effort))), nodeAssignmentMargin: e51.srj.defaultObstacleMargin ?? 0.2 }]), Z1(\"highDensityRepairSolver\", g1, (e51) =\u003e [{ nodeWithPortPoints: e51.highDensityNodePortPoints ?? [], hdRoutes: e51.highDensityForceImproveSolver?.getOutput() ?? e51.highDensityRouteSolver.routes, obstacles: e51.srj.obstacles, colorMap: e51.colorMap, repairMargin: e51.srj.defaultObstacleMargin ?? 0.2, minimumTraceWidth: e51.srj.minTraceWidth, connMap: e51.connMap }]), Z1(\"highDensityStitchSolver\", L1, (e51) =\u003e [{ connections: e51.srjWithPointPairs.connections, hdRoutes: e51.highDensityRepairSolver?.getOutput() ?? e51.highDensityForceImproveSolver?.getOutput() ?? e51.highDensityRouteSolver.routes, colorMap: e51.colorMap, layerCount: e51.srj.layerCount, defaultViaDiameter: e51.viaDiameter }]), Z1(\"traceSimplificationSolver\", WF, (e51) =\u003e [{ hdRoutes: e51.highDensityStitchSolver.mergedHdRoutes, obstacles: e51.srj.obstacles, connMap: e51.connMap, colorMap: e51.colorMap, outline: e51.srj.outline, defaultViaDiameter: e51.viaDiameter, layerCount: e51.srj.layerCount, minTraceToPadEdgeClearance: e51.srj.minTraceToPadEdgeClearance, iterations: 2 }]), Z1(\"traceWidthSolver\", QF, (e51) =\u003e [{ hdRoutes: e51.traceSimplificationSolver.simplifiedHdRoutes, obstacles: e51.srj.obstacles, connMap: e51.connMap, colorMap: e51.colorMap, minTraceWidth: e51.minTraceWidth, connection: e51.srj.connections, obstacleMargin: e51.srj.minTraceToPadEdgeClearance ?? 0.15, layerCount: e51.srj.layerCount }]), Z1(\"globalDrcForceImproveSolver\", kN, (e51) =\u003e [{ srj: e51.srjWithPointPairs, hdRoutes: e51.traceWidthSolver.getHdRoutesWithWidths(), effort: Math.min(1, e51.effort) }])];\n setSimpleRouteJson(e51) {\n this.srj = e51;\n const t2 = Yo(this.srj);\n this.viaDiameter = t2.padDiameter, this.viaHoleDiameter = t2.holeDiameter, this.minTraceWidth = this.srj.minTraceWidth, this.connMap = ei(this.srj), this.colorMap = Eo(this.srj, this.connMap);\n }\n getConstructorParams() {\n return [this.srj, this.opts];\n }\n currentPipelineStepIndex = 0;\n _step() {\n const e51 = this.pipelineDef[this.currentPipelineStepIndex];\n if (!e51)\n return void (this.solved = true);\n if (this.activeSubSolver)\n return this.activeSubSolver.step(), void (this.activeSubSolver.solved ? (this.endTimeOfPhase[e51.solverName] = performance.now(), this.timeSpentOnPhase[e51.solverName] = this.endTimeOfPhase[e51.solverName] - this.startTimeOfPhase[e51.solverName], e51.onSolved?.(this), this.activeSubSolver = null, this.currentPipelineStepIndex++) : this.activeSubSolver.failed \u0026\u0026 (this.error = this.activeSubSolver?.error, this.failed = true, this.activeSubSolver = null));\n const t2 = e51.getConstructorParams(this);\n this.activeSubSolver = new e51.solverClass(...t2), this[e51.solverName] = this.activeSubSolver, this.timeSpentOnPhase[e51.solverName] = 0, this.startTimeOfPhase[e51.solverName] = performance.now();\n }\n solveUntilPhase(e51) {\n for (;this.getCurrentPhase() !== e51; )\n this.step();\n }\n getCurrentPhase() {\n return this.pipelineDef[this.currentPipelineStepIndex]?.solverName ?? \"none\";\n }\n visualize() {\n if (!this.solved \u0026\u0026 this.activeSubSolver)\n return this.activeSubSolver.visualize();\n const e51 = this.escapeViaLocationSolver?.visualize(), t2 = this.netToPointPairsSolver?.visualize(), n2 = this.nodeSolver?.visualize(), o3 = this.nodeDimensionSubdivisionSolver?.visualize(), i3 = this.nodeTargetMerger?.visualize(), r3 = this.singleLayerNodeMerger?.visualize(), s2 = this.strawSolver?.visualize(), a3 = this.edgeSolver?.visualize(), c3 = this.deadEndSolver?.visualize(), l3 = this.availableSegmentPointSolver?.visualize(), h2 = this.portPointPathingSolver?.visualize(), d2 = this.multiSectionPortPointOptimizer?.visualize(), u2 = this.uniformPortDistributionSolver?.visualize(), p3 = this.highDensityRouteSolver?.visualize(), m2 = this.highDensityForceImproveSolver?.visualize(), g2 = this.highDensityRepairSolver?.visualize(), f2 = this.highDensityStitchSolver?.visualize(), _2 = this.traceSimplificationSolver?.visualize(), y2 = this.necessaryCrampedPortPointSolver?.visualize(), b2 = (this.highDensityRouteSolver?.visualize(), this.originalSrj), x2 = b2.outline, v2 = [];\n if (v2.push({ points: [{ x: b2.bounds?.minX ?? -50, y: b2.bounds?.minY ?? -50 }, { x: b2.bounds?.maxX ?? 50, y: b2.bounds?.minY ?? -50 }, { x: b2.bounds?.maxX ?? 50, y: b2.bounds?.maxY ?? 50 }, { x: b2.bounds?.minX ?? -50, y: b2.bounds?.maxY ?? 50 }, { x: b2.bounds?.minX ?? -50, y: b2.bounds?.minY ?? -50 }], strokeColor: \"rgba(255,0,0,0.25)\" }), x2 \u0026\u0026 x2.length \u003e= 2) {\n const e52 = x2.map((e53) =\u003e ({ x: e53.x, y: e53.y }));\n e52.push({ ...e52[0] }), v2.push({ points: e52, strokeColor: \"rgba(0, 136, 255, 0.95)\" });\n }\n const I2 = Lo(b2), S2 = { points: [...b2.connections.flatMap((e52) =\u003e e52.pointsToConnect.map((t3) =\u003e ({ ...t3, layer: Bo(t3, b2.layerCount), label: `${e52.name} ${t3.pcb_port_id ?? \"\"}` })))], rects: [...(b2.obstacles ?? []).filter((e52) =\u003e !e52.isCopperPour).map((e52) =\u003e ({ ...e52, fill: e52.layers?.includes(\"top\") ? \"rgba(255,0,0,0.25)\" : e52.layers?.includes(\"bottom\") ? \"rgba(0,0,255,0.25)\" : \"rgba(255,0,0,0.25)\", layer: jo(e52, b2.layerCount), label: I2(e52) }))], lines: v2 }, C = nK({ srj: b2 }), P = [pi(S2, C), e51, t2, n2, o3, i3, r3, s2, a3, c3, l3, y2, h2, d2, u2, p3 ? pi(S2, p3) : null, m2, g2, f2, _2, this.solved ? pi({ lines: v2 }, nK({ srj: this.originalSrj }), Wo(this.getOutputSimpleRouteJson())) : null].filter(Boolean);\n return pi(...P);\n }\n preview() {\n if (this.highDensityRouteSolver) {\n const e51 = [];\n for (let t2 = this.highDensityRouteSolver.routes.length - 1;t2 \u003e= 0; t2--) {\n const n2 = this.highDensityRouteSolver.routes[t2];\n if (e51.push({ points: n2.route.map((e52) =\u003e ({ x: e52.x, y: e52.y })), strokeColor: this.colorMap[n2.connectionName] }), e51.length \u003e 200)\n break;\n }\n return { lines: e51 };\n }\n return this.portPointPathingSolver ? this.portPointPathingSolver.preview() : this.netToPointPairsSolver ? this.netToPointPairsSolver.visualize() : this.escapeViaLocationSolver ? this.escapeViaLocationSolver.visualize() : this.preprocessSimpleRouteJsonSolver ? this.preprocessSimpleRouteJsonSolver.visualize() : {};\n }\n _getOutputHdRoutes() {\n return this.globalDrcForceImproveSolver?.getOutput() ?? this.traceWidthSolver?.getHdRoutesWithWidths() ?? this.traceSimplificationSolver?.simplifiedHdRoutes ?? this.highDensityStitchSolver.mergedHdRoutes;\n }\n getOutputSimplifiedPcbTraces() {\n if (!this.solved || !this.highDensityRouteSolver)\n throw new Error(\"Cannot get output before solving is complete\");\n const e51 = [], t2 = this._getOutputHdRoutes();\n for (const n2 of this.netToPointPairsSolver?.newConnections ?? []) {\n const o3 = n2.__netConnectionName ?? this.originalSrj.connections.find((e52) =\u003e e52.name === n2.name)?.__netConnectionName, i3 = t2.filter((e52) =\u003e e52.connectionName === n2.name);\n for (let t3 = 0;t3 \u003c i3.length; t3++) {\n const r3 = i3[t3], s2 = { type: \"pcb_trace\", pcb_trace_id: `${n2.name}_${t3}`, connection_name: o3 ?? n2.__rootConnectionNames?.[0] ?? n2.name, route: Ro(r3, this.srj.layerCount, { connectionPoints: n2.pointsToConnect, defaultViaHoleDiameter: this.viaHoleDiameter, obstacles: this.srj.obstacles, connMap: this.connMap }) };\n e51.push(s2);\n }\n }\n return e51;\n }\n getOutputSimpleRouteJson() {\n return { ...this.originalSrj, traces: this.getOutputSimplifiedPcbTraces() };\n }\n};\nvar Q1 = (e51) =\u003e /\\/solve\\/?$/.test(e51) ? e51.replace(/\\/+$/, \"\") : `${e51.replace(/\\/+$/, \"\")}/solve`;\nvar K1 = (e51, t2, n2) =\u003e {\n const o3 = ((e52) =\u003e {\n const t3 = new Map;\n for (const n3 of e52.portPoints)\n n3.rootConnectionName \u0026\u0026 !t3.has(n3.connectionName) \u0026\u0026 t3.set(n3.connectionName, n3.rootConnectionName);\n return t3;\n })(e51);\n return t2.map((e52) =\u003e ({ connectionName: e52.connectionName, rootConnectionName: e52.rootConnectionName ?? o3.get(e52.connectionName) ?? undefined, traceThickness: e52.traceThickness ?? n2.traceWidth, viaDiameter: e52.viaDiameter ?? n2.viaDiameter, route: (e52.route ?? []).map((e53) =\u003e ({ x: e53.x, y: e53.y, z: e53.z, ...e53.insideJumperPad ? { insideJumperPad: true } : {} })), vias: (e52.vias ?? []).map((e53) =\u003e ({ x: e53.x, y: e53.y })), ...e52.jumpers ? { jumpers: e52.jumpers } : {} }));\n};\nvar e210 = (e51, t2) =\u003e {\n if (e51.length === 0)\n return null;\n const n2 = Math.min(Math.max(t2, 0), 1), o3 = (e51.length - 1) * n2, i3 = Math.floor(o3), r3 = Math.ceil(o3), s2 = e51[i3], a3 = e51[r3];\n return i3 === r3 ? s2 : s2 + (a3 - s2) * (o3 - i3);\n};\nvar t2 = (e51) =\u003e new Set(e51.portPoints.map((e52) =\u003e e52.connectionName)).size;\nvar n2 = (e51) =\u003e !(t2(e51) \u003c 3) \u0026\u0026 (e51.availableZ?.length ?? 0) !== 1;\nvar o22 = (e51) =\u003e e51?.MULTI_HEAD_POLYLINE_SOLVER ? \"MultiHeadPolyLineIntraNodeSolver3\" : e51?.CLOSED_FORM_SINGLE_TRANSITION ? \"SingleTransitionIntraNodeSolver\" : e51?.CLOSED_FORM_TWO_TRACE_SAME_LAYER ? \"TwoCrossingRoutesHighDensitySolver\" : e51?.CLOSED_FORM_TWO_TRACE_TRANSITION_CROSSING ? \"SingleTransitionCrossingRouteSolver\" : e51?.HIGH_DENSITY_A01 ? \"HighDensitySolverA01\" : e51?.HIGH_DENSITY_A03 ? \"HighDensitySolverA03\" : \"SingleHighDensityRouteSolver6_VertHorzLayer_FutureCost\";\nvar i22 = (e51) =\u003e {\n if (e51 instanceof jr) {\n const t4 = o22(e51.hyperParameters);\n return e51.cacheHit ? `${t4} [cached]` : t4;\n }\n if (e51 instanceof Lr)\n return o22(e51.hyperParameters);\n if (e51 \u0026\u0026 typeof e51 == \"object\" \u0026\u0026 \"getSolverName\" in e51 \u0026\u0026 typeof e51.getSolverName == \"function\")\n return e51.getSolverName();\n const t3 = e51?.constructor;\n return typeof t3?.name == \"string\" ? t3.name : \"unknown\";\n};\nvar r22 = (e51) =\u003e e51.winningSolver ? i22(e51.winningSolver) : i22(e51);\nvar s2 = class extends ni {\n getSolverName() {\n return \"Pipeline5HdCacheHighDensitySolver\";\n }\n unsolvedNodePortPoints;\n colorMap;\n connMap;\n viaDiameter;\n traceWidth;\n obstacleMargin;\n obstacles;\n layerCount;\n hdCacheBaseUrl;\n fetchImpl;\n nodePfById;\n routes = [];\n nodeSolveMetadataById = new Map;\n launchedRemoteSolves = false;\n solvedRoutesByNodeIndex = new Map;\n failedNodeResults = [];\n remoteResponseMeasurements = [];\n constructor({ nodePortPoints: e51, colorMap: t3, connMap: n3, viaDiameter: o3, traceWidth: i3, obstacleMargin: r3, obstacles: s3, layerCount: a3, nodePfById: c3, hdCacheBaseUrl: l3, fetchImpl: h2 }) {\n super(), this.unsolvedNodePortPoints = e51, this.colorMap = t3 ?? {}, this.connMap = n3, this.viaDiameter = o3 ?? 0.3, this.traceWidth = i3 ?? 0.15, this.obstacleMargin = r3 ?? 0.15, this.obstacles = s3 ?? [], this.layerCount = a3 ?? 2, this.hdCacheBaseUrl = l3 ?? \"https://hd-cache.tscircuit.com\", this.fetchImpl = (h2 ?? globalThis.fetch).bind(globalThis), this.nodePfById = c3 instanceof Map ? new Map(c3) : new Map(Object.entries(c3 ?? {})), this.pendingEffects = [], this.stats = { localDirectNodeCount: 0, localSolvedNodeCount: 0, localFallbackNodeCount: 0, remoteFallbackNodeCount: 0, remoteRequestsStarted: 0, remoteRequestsCompleted: 0, remoteResponseSampleCount: 0, remoteKOrderSampleCount: 0, slowestRemoteResponseMs: null, slowestRemoteResponseNodeId: null, p50RemoteResponseMs: null, p50RemoteKOrder: null, p95RemoteKOrder: null, remoteSources: {} };\n }\n computeProgress() {\n return this.unsolvedNodePortPoints.length === 0 ? 1 : this.nodeSolveMetadataById.size / this.unsolvedNodePortPoints.length;\n }\n solveNodeLocally(e51, t3, n3 = {}) {\n const o3 = new xz({ nodeWithPortPoints: e51, colorMap: this.colorMap, connMap: this.connMap, viaDiameter: this.viaDiameter, traceWidth: this.traceWidth, obstacleMargin: this.obstacleMargin, obstacles: this.obstacles, layerCount: this.layerCount });\n if (o3.solve(), o3.failed) {\n const t4 = o3.error ?? `Local intra-node solver failed for ${e51.capacityMeshNodeId}`, i4 = t2(e51);\n return this.failedNodeResults.push({ node: e51, error: n3.remoteFailure \u0026\u0026 n3.resolution === \"local-fallback\" ? `Remote solve failed (${n3.remoteFailure}); local fallback failed (${t4})` : t4 }), void this.recordNodeSolveMetadata(e51, { status: \"failed\", resolution: \"failed\", solverType: r22(o3), supervisorType: o3.getSolverName(), iterations: o3.iterations, pairCount: i4, routeCount: 0, remoteAttempt: n3.resolution === \"local-fallback\" ? { attempted: true, endpoint: Q1(this.hdCacheBaseUrl), source: \"error\", durationMs: n3.remoteDurationMs, error: n3.remoteFailure ?? t4 } : { attempted: false }, error: t4 });\n }\n this.solvedRoutesByNodeIndex.set(t3, o3.solvedRoutes);\n const i3 = t2(e51);\n this.recordNodeSolveMetadata(e51, { status: \"solved\", resolution: n3.resolution ?? \"local\", solverType: r22(o3), supervisorType: o3.getSolverName(), iterations: o3.iterations, pairCount: i3, routeCount: o3.solvedRoutes.length, remoteAttempt: n3.resolution === \"local-fallback\" ? { attempted: true, endpoint: Q1(this.hdCacheBaseUrl), source: \"error\", durationMs: n3.remoteDurationMs, error: n3.remoteFailure } : { attempted: false } }), n3.resolution === \"local-fallback\" ? (this.stats.localFallbackNodeCount += 1, this.stats.remoteFallbackNodeCount += 1) : this.stats.localDirectNodeCount += 1, this.stats.localSolvedNodeCount += 1;\n }\n async solveNodeViaHdCache(e51, t3) {\n const n3 = Q1(this.hdCacheBaseUrl), o3 = { \"content-type\": \"application/json\" }, i3 = { nodeWithPortPoints: e51 }, r3 = JSON.stringify(i3), s3 = Date.now();\n let a3, c3, l3, h2 = null, d2 = null;\n try {\n const i4 = await this.fetchImpl(n3, { method: \"POST\", headers: o3, body: r3 });\n if (a3 = i4.status, c3 = i4.ok, l3 = await i4.text(), h2 = Date.now() - s3, d2 = l3 ? JSON.parse(l3) : null, !i4.ok)\n throw new Error(d2?.message ?? l3 ?? `hd-cache request failed with status ${i4.status}`);\n if (!d2?.ok || d2.routes === null)\n throw new Error(d2?.message ?? `hd-cache returned no routes for ${e51.capacityMeshNodeId}`);\n const u3 = K1(e51, d2.routes, { traceWidth: this.traceWidth, viaDiameter: this.viaDiameter });\n this.solvedRoutesByNodeIndex.set(t3, u3), this.recordNodeSolveMetadata(e51, { status: \"solved\", resolution: \"remote\", solverType: `hd-cache.tscircuit.com [${d2.source}]`, iterations: null, pairCount: t2(e51), routeCount: u3.length, remoteAttempt: { attempted: true, endpoint: Q1(this.hdCacheBaseUrl), source: d2.source, durationMs: h2 } }), this.recordRemoteSource(d2.source);\n } catch (u3) {\n h2 ??= Date.now() - s3;\n const p3 = ((e52) =\u003e e52 instanceof Error ? e52.message : String(e52))(u3);\n this.recordFailedHdCacheRequest({ nodeId: e51.capacityMeshNodeId, pairCount: t2(e51), failedAt: new Date().toISOString(), durationMs: h2, error: p3, url: n3, request: { method: \"POST\", headers: o3, body: r3, bodyJson: i3 }, response: a3 !== undefined || c3 !== undefined || l3 !== undefined || d2 !== null ? { status: a3, ok: c3, text: l3, body: d2 } : undefined }), this.recordRemoteSource(\"error\"), this.solveNodeLocally(e51, t3, { resolution: \"local-fallback\", remoteFailure: p3, remoteDurationMs: h2 });\n } finally {\n this.recordRemoteResponseMetrics(e51.capacityMeshNodeId, h2 ?? Date.now() - s3, (u2 = d2?.kOrder, typeof u2 == \"number\" \u0026\u0026 Number.isFinite(u2) ? d2.kOrder : null)), this.stats.remoteRequestsCompleted += 1;\n }\n var u2;\n }\n launchRemoteSolves() {\n const e51 = [];\n this.unsolvedNodePortPoints.forEach((t3, n3) =\u003e {\n if (!n2(t3))\n return void this.solveNodeLocally(t3, n3);\n const o3 = { name: `hd-cache:${t3.capacityMeshNodeId}`, promise: Promise.resolve() };\n o3.promise = this.solveNodeViaHdCache(t3, n3).finally(() =\u003e {\n this.pendingEffects = this.pendingEffects?.filter((e52) =\u003e e52 !== o3);\n }), e51.push(o3);\n }), this.pendingEffects = e51, this.stats.remoteRequestsStarted = e51.length;\n }\n recordRemoteSource(e51) {\n this.stats.remoteSources[e51] = (this.stats.remoteSources[e51] ?? 0) + 1;\n }\n recordRemoteResponseMetrics(e51, t3, n3) {\n this.remoteResponseMeasurements.push({ nodeId: e51, durationMs: t3, kOrder: n3 }), this.stats.remoteResponseSampleCount = this.remoteResponseMeasurements.length, this.stats.remoteKOrderSampleCount = this.remoteResponseMeasurements.filter((e52) =\u003e e52.kOrder !== null).length;\n let o3 = null;\n for (const e52 of this.remoteResponseMeasurements)\n (!o3 || e52.durationMs \u003e o3.durationMs) \u0026\u0026 (o3 = e52);\n this.stats.slowestRemoteResponseMs = o3?.durationMs ?? null, this.stats.slowestRemoteResponseNodeId = o3?.nodeId ?? null;\n const i3 = this.remoteResponseMeasurements.map((e52) =\u003e e52.durationMs).sort((e52, t4) =\u003e e52 - t4);\n this.stats.p50RemoteResponseMs = e210(i3, 0.5);\n const r3 = this.remoteResponseMeasurements.map((e52) =\u003e e52.kOrder).filter((e52) =\u003e e52 !== null).sort((e52, t4) =\u003e e52 - t4);\n this.stats.p50RemoteKOrder = e210(r3, 0.5), this.stats.p95RemoteKOrder = e210(r3, 0.95);\n }\n recordFailedHdCacheRequest(e51) {\n const t3 = (() =\u003e {\n if (typeof window == \"undefined\")\n return null;\n const e52 = window;\n return Array.isArray(e52.__FAILED_HD_CACHE_REQUESTS) || (e52.__FAILED_HD_CACHE_REQUESTS = []), e52.__FAILED_HD_CACHE_REQUESTS;\n })();\n t3 \u0026\u0026 t3.push(e51);\n }\n recordNodeSolveMetadata(e51, t3) {\n this.nodeSolveMetadataById.set(e51.capacityMeshNodeId, { ...t3, node: e51, nodePf: this.nodePfById.get(e51.capacityMeshNodeId) ?? null });\n }\n ensureFailedNodeMetadata() {\n for (const e51 of this.failedNodeResults)\n this.nodeSolveMetadataById.has(e51.node.capacityMeshNodeId) || this.recordNodeSolveMetadata(e51.node, { status: \"failed\", resolution: \"failed\", solverType: \"unknown\", iterations: null, pairCount: t2(e51.node), routeCount: 0, remoteAttempt: { attempted: n2(e51.node), source: \"error\", error: e51.error }, error: e51.error });\n }\n getVisibleRoutes() {\n if (this.solved)\n return this.routes;\n const e51 = [];\n for (let t3 = 0;t3 \u003c this.unsolvedNodePortPoints.length; t3++)\n e51.push(...this.solvedRoutesByNodeIndex.get(t3) ?? []);\n return e51;\n }\n createNodeMarkerLabel(e51, t3) {\n return [\"hd_node_marker\", `node: ${e51}`, `status: ${t3.status}`, `resolution: ${t3.resolution}`, `solver: ${t3.solverType}`, ...t3.supervisorType ? [`supervisor: ${t3.supervisorType}`] : [], ...t3.iterations !== null ? [`iterations: ${t3.iterations}`] : [], `pairCount: ${t3.pairCount}`, `routes: ${t3.routeCount}`, `nodePf: ${t3.nodePf ?? \"n/a\"}`, \"remoteAttempted: \" + (t3.remoteAttempt.attempted ? \"yes\" : \"no\"), ...t3.remoteAttempt.source ? [`remoteSource: ${t3.remoteAttempt.source}`] : [], ...t3.remoteAttempt.durationMs !== undefined ? [`remoteDurationMs: ${t3.remoteAttempt.durationMs}`] : [], ...t3.remoteAttempt.error ? [`remoteError: ${t3.remoteAttempt.error}`] : [], `portPoints: ${t3.node.portPoints.length}`, ...t3.error ? [`error: ${t3.error}`] : []].join(`\n`);\n }\n _step() {\n if (!this.launchedRemoteSolves)\n return this.launchedRemoteSolves = true, void this.launchRemoteSolves();\n if (!((this.pendingEffects?.length ?? 0) \u003e 0)) {\n if (this.failedNodeResults.length \u003e 0) {\n this.ensureFailedNodeMetadata();\n const e51 = this.failedNodeResults[0];\n return this.failed = true, void (this.error = `Failed to solve ${this.failedNodeResults.length} nodes via hd-cache. First failure: ${e51?.node.capacityMeshNodeId} (${e51?.error})`);\n }\n this.routes = [];\n for (let e51 = 0;e51 \u003c this.unsolvedNodePortPoints.length; e51++)\n this.routes.push(...this.solvedRoutesByNodeIndex.get(e51) ?? []);\n this.solved = true;\n }\n }\n visualize() {\n const e51 = { lines: [], points: [], rects: [], circles: [] };\n for (const t3 of this.getVisibleRoutes()) {\n const n3 = mi(t3.route, t3.connectionName, this.colorMap[t3.connectionName]);\n for (const o3 of n3)\n e51.lines.push({ points: o3.points, label: o3.connectionName, strokeColor: o3.z === 0 ? o3.color : Ao(o3.color, 0.75), layer: `z${o3.z}`, strokeWidth: t3.traceThickness, strokeDash: o3.z !== 0 ? \"10, 5\" : undefined });\n for (const n4 of t3.vias)\n e51.circles.push({ center: n4, layer: \"z0,1\", radius: t3.viaDiameter / 2, fill: this.colorMap[t3.connectionName], label: `${t3.connectionName} via` });\n }\n for (const [t3, n3] of this.nodeSolveMetadataById) {\n const o3 = n3.node.center.x - n3.node.width / 2, i3 = n3.node.center.x + n3.node.width / 2, r3 = n3.node.center.y - n3.node.height / 2, s3 = n3.node.center.y + n3.node.height / 2, a3 = this.createNodeMarkerLabel(t3, n3), c3 = n3.status === \"solved\" ? \"blue\" : \"red\", l3 = n3.status === \"solved\" ? 0.03 : 0.08;\n if (e51.lines.push({ points: [{ x: o3, y: r3 }, { x: i3, y: r3 }], layer: \"hd_node_boundaries\", strokeColor: c3, strokeDash: \"6, 4\", strokeWidth: l3, label: a3 }, { points: [{ x: i3, y: r3 }, { x: i3, y: s3 }], layer: \"hd_node_boundaries\", strokeColor: c3, strokeDash: \"6, 4\", strokeWidth: l3, label: a3 }, { points: [{ x: i3, y: s3 }, { x: o3, y: s3 }], layer: \"hd_node_boundaries\", strokeColor: c3, strokeDash: \"6, 4\", strokeWidth: l3, label: a3 }, { points: [{ x: o3, y: s3 }, { x: o3, y: r3 }], layer: \"hd_node_boundaries\", strokeColor: c3, strokeDash: \"6, 4\", strokeWidth: l3, label: a3 }), n3.status === \"solved\")\n e51.points.push({ x: n3.node.center.x, y: n3.node.center.y, color: c3, layer: \"hd_node_markers\", label: a3 });\n else {\n e51.lines.push({ points: [{ x: 0, y: 0 }, { x: n3.node.center.x, y: n3.node.center.y }], layer: \"hd_failed_node_guides\", strokeColor: c3, strokeDash: \"8, 6\", strokeWidth: 0.05, label: a3 });\n const t4 = Math.max(n3.node.width, 1.2), o4 = Math.max(n3.node.height, 1.2), i4 = t4 / 2, r4 = o4 / 2;\n e51.rects.push({ center: n3.node.center, layer: \"hd_node_markers\", width: t4, height: o4, fill: \"rgba(255, 0, 0, 0.3)\", stroke: c3, label: a3 }), e51.circles.push({ center: n3.node.center, radius: Math.max(0.6 * Math.max(t4, o4), 1.1), layer: \"hd_node_markers\", fill: \"rgba(255, 0, 0, 0.08)\", stroke: c3, label: a3 }), e51.lines.push({ points: [{ x: n3.node.center.x - i4, y: n3.node.center.y - r4 }, { x: n3.node.center.x + i4, y: n3.node.center.y + r4 }], layer: \"hd_node_markers\", strokeColor: c3, strokeWidth: 0.16, label: a3 }, { points: [{ x: n3.node.center.x - i4, y: n3.node.center.y + r4 }, { x: n3.node.center.x + i4, y: n3.node.center.y - r4 }], layer: \"hd_node_markers\", strokeColor: c3, strokeWidth: 0.16, label: a3 });\n }\n }\n return e51;\n }\n};\nvar c22 = 0.000000001;\nvar l22 = Math.PI / 2;\nvar h2 = (e51, t3) =\u003e e51.x * t3.y - e51.y * t3.x;\nvar d2 = (e51, t3) =\u003e e51.x * t3.x + e51.y * t3.y;\nvar u2 = (e51) =\u003e {\n let t3 = e51 % l22;\n return t3 \u003c 0 \u0026\u0026 (t3 += l22), l22 - t3 \u003c 0.00000001 ? 0 : t3;\n};\nvar p22 = (e51) =\u003e {\n const t3 = Math.cos(e51), n3 = Math.sin(e51);\n return { u: { x: t3, y: n3 }, v: { x: -n3, y: t3 } };\n};\nvar m2 = (e51) =\u003e {\n let t3 = 0;\n for (let n3 = 0;n3 \u003c e51.length; n3++) {\n const o3 = e51[n3], i3 = e51[(n3 + 1) % e51.length];\n t3 += o3.x * i3.y - i3.x * o3.y;\n }\n return t3 / 2;\n};\nvar g2 = (e51) =\u003e Math.abs(m2(e51));\nvar f2 = (e51) =\u003e {\n const t3 = m2(e51);\n if (Math.abs(t3) \u003c c22) {\n const t4 = e51.reduce((e52, t5) =\u003e ({ x: e52.x + t5.x, y: e52.y + t5.y }), { x: 0, y: 0 });\n return { x: t4.x / Math.max(1, e51.length), y: t4.y / Math.max(1, e51.length) };\n }\n let n3 = 0, o3 = 0;\n for (let t4 = 0;t4 \u003c e51.length; t4++) {\n const i4 = e51[t4], r3 = e51[(t4 + 1) % e51.length], s3 = i4.x * r3.y - r3.x * i4.y;\n n3 += (i4.x + r3.x) * s3, o3 += (i4.y + r3.y) * s3;\n }\n const i3 = 1 / (6 * t3);\n return { x: n3 * i3, y: o3 * i3 };\n};\nvar _2 = (e51) =\u003e m2(e51) \u003e= 0 ? [...e51] : [...e51].reverse();\nvar y2 = (e51, t3) =\u003e {\n const n3 = new Set;\n n3.add(0);\n for (let e52 = 0;e52 \u003c 90; e52++)\n n3.add(e52 / 90 * l22);\n for (let t4 = 0;t4 \u003c e51.length; t4++) {\n const o4 = e51[t4], i4 = e51[(t4 + 1) % e51.length], r4 = Math.atan2(i4.y - o4.y, i4.x - o4.x);\n n3.add(u2(r4)), n3.add(u2(r4 + l22));\n }\n const o3 = (n4) =\u003e {\n const o4 = ((e52, t4 = f2(e52), n5 = 0) =\u003e {\n const o5 = _2(e52), { u: i4, v: r4 } = p22(n5), s4 = o5.map((e53, n6) =\u003e {\n const s5 = o5[(n6 + 1) % o5.length], a5 = s5.x - e53.x, c5 = s5.y - e53.y, l5 = { x: a5, y: c5 };\n return { hxCoeff: Math.abs(h2(l5, i4)), hyCoeff: Math.abs(h2(l5, r4)), limit: a5 * (t4.y - e53.y) - c5 * (t4.x - e53.x) };\n });\n if (s4.some((e53) =\u003e e53.limit \u003c -0.0000001))\n throw new Error(\"Projected rect center is outside polygon\");\n let a4 = Number.POSITIVE_INFINITY;\n for (const e53 of s4)\n e53.hxCoeff \u003e c22 \u0026\u0026 (a4 = Math.min(a4, e53.limit / e53.hxCoeff));\n if (!Number.isFinite(a4) || a4 \u003c= c22)\n return { center: t4, width: 0.000001, height: 0.000001, ccwRotationRadians: n5, ccwRotationDegrees: 180 * n5 / Math.PI };\n const c4 = (e53) =\u003e {\n let t5 = Number.POSITIVE_INFINITY;\n for (const n6 of s4) {\n const o6 = n6.limit - n6.hxCoeff * e53;\n if (o6 \u003c -0.00000001)\n return 0;\n n6.hyCoeff \u003e c22 \u0026\u0026 (t5 = Math.min(t5, o6 / n6.hyCoeff));\n }\n return Number.isFinite(t5) ? Math.max(0, t5) : 0;\n }, l4 = (e53) =\u003e e53 * c4(e53);\n let h3 = 0, d3 = a4;\n for (let e53 = 0;e53 \u003c 80; e53++) {\n const e54 = h3 + (d3 - h3) / 3, t5 = d3 - (d3 - h3) / 3;\n l4(e54) \u003c l4(t5) ? h3 = e54 : d3 = t5;\n }\n const u3 = (h3 + d3) / 2, p3 = c4(u3);\n return { center: t4, width: Math.max(0.000001, 2 * u3), height: Math.max(0.000001, 2 * p3), ccwRotationRadians: n5, ccwRotationDegrees: 180 * n5 / Math.PI };\n })(e51, t3, n4);\n return { rect: o4, area: o4.width * o4.height };\n };\n let i3 = o3(0), r3 = 0;\n for (const e52 of n3) {\n const t4 = o3(e52);\n t4.area \u003e i3.area + 0.00000001 \u0026\u0026 (i3 = t4, r3 = e52);\n }\n const s3 = l22 / 90;\n let a3 = r3 - s3, c3 = r3 + s3;\n for (let e52 = 0;e52 \u003c 60; e52++) {\n const e53 = a3 + (c3 - a3) / 3, t4 = c3 - (c3 - a3) / 3;\n o3(e53).area \u003c o3(t4).area ? a3 = e53 : c3 = t4;\n }\n const l3 = o3(u2((a3 + c3) / 2));\n return l3.area \u003e i3.area + 0.00000001 ? l3.rect : i3.rect;\n};\nvar b2 = (e51, t3, n3, o3) =\u003e {\n const i3 = o3.x - n3.x, r3 = o3.y - n3.y, s3 = t3.x * r3 - t3.y * i3;\n if (Math.abs(s3) \u003c c22)\n return;\n const a3 = n3.x - e51.x, c3 = n3.y - e51.y, l3 = (a3 * r3 - c3 * i3) / s3, h3 = (a3 * t3.y - c3 * t3.x) / s3;\n return l3 \u003c -0.00000001 || h3 \u003c -0.00000001 || h3 \u003e 1 + 0.00000001 ? undefined : { x: e51.x + t3.x * l3, y: e51.y + t3.y * l3, rayT: l3 };\n};\nvar x2 = (e51, t3) =\u003e {\n const n3 = [], o3 = [];\n for (let i4 = 0;i4 \u003c 4; i4++) {\n const { x: r3, y: s3 } = e51[i4], a3 = t3[i4].x, c3 = t3[i4].y;\n n3.push([r3, s3, 1, 0, 0, 0, -a3 * r3, -a3 * s3]), o3.push(a3), n3.push([0, 0, 0, r3, s3, 1, -c3 * r3, -c3 * s3]), o3.push(c3);\n }\n const i3 = ((e52, t4) =\u003e {\n const n4 = t4.length, o4 = e52.map((e53, n5) =\u003e [...e53, t4[n5]]);\n for (let e53 = 0;e53 \u003c n4; e53++) {\n let t5 = e53;\n for (let i5 = e53 + 1;i5 \u003c n4; i5++)\n Math.abs(o4[i5][e53]) \u003e Math.abs(o4[t5][e53]) \u0026\u0026 (t5 = i5);\n if (Math.abs(o4[t5][e53]) \u003c c22)\n throw new Error(\"Could not solve homography\");\n [o4[e53], o4[t5]] = [o4[t5], o4[e53]];\n const i4 = o4[e53][e53];\n for (let t6 = e53;t6 \u003c= n4; t6++)\n o4[e53][t6] = o4[e53][t6] / i4;\n for (let t6 = 0;t6 \u003c n4; t6++) {\n if (t6 === e53)\n continue;\n const i5 = o4[t6][e53];\n for (let r3 = e53;r3 \u003c= n4; r3++)\n o4[t6][r3] = o4[t6][r3] - i5 * o4[e53][r3];\n }\n }\n return o4.map((e53) =\u003e e53[n4]);\n })(n3, o3);\n return [i3[0], i3[1], i3[2], i3[3], i3[4], i3[5], i3[6], i3[7], 1];\n};\nvar v2 = (e51, t3) =\u003e {\n const n3 = Math.cos(t3), o3 = Math.sin(t3);\n return [n3, -o3, e51.x - n3 * e51.x + o3 * e51.y, o3, n3, e51.y - o3 * e51.x - n3 * e51.y, 0, 0, 1];\n};\nvar I2 = (e51, t3) =\u003e {\n const n3 = e51[6] * t3.x + e51[7] * t3.y + e51[8];\n return Math.abs(n3) \u003c c22 ? { x: t3.x, y: t3.y } : { x: (e51[0] * t3.x + e51[1] * t3.y + e51[2]) / n3, y: (e51[3] * t3.x + e51[4] * t3.y + e51[5]) / n3 };\n};\nvar S2 = (e51, t3, n3) =\u003e {\n const { u: o3, v: i3 } = p22(n3);\n return { x: t3.x + e51.x * o3.x + e51.y * i3.x, y: t3.y + e51.x * o3.y + e51.y * i3.y };\n};\nvar C2 = (e51, t3) =\u003e S2({ x: e51.x - t3.center.x, y: e51.y - t3.center.y }, t3.center, t3.ccwRotationRadians);\nvar P2 = (e51, t3) =\u003e {\n const n3 = ((e52, t4, n4) =\u003e {\n const { u: o4, v: i4 } = p22(n4), r4 = { x: e52.x - t4.x, y: e52.y - t4.y };\n return { x: d2(r4, o4), y: d2(r4, i4) };\n })(e51, t3.center, t3.ccwRotationRadians);\n if (Math.abs(n3.x) \u003c c22 \u0026\u0026 Math.abs(n3.y) \u003c c22)\n return { ...t3.center };\n const o3 = t3.width / 2, i3 = t3.height / 2, r3 = Math.abs(n3.x) \u003e c22 ? o3 / Math.abs(n3.x) : 1 / 0, s3 = Math.abs(n3.y) \u003e c22 ? i3 / Math.abs(n3.y) : 1 / 0, a3 = Math.min(r3, s3);\n return { x: t3.center.x + n3.x * a3, y: t3.center.y + n3.y * a3 };\n};\nvar M2 = (e51, t3 = 0, n3 = 0) =\u003e {\n const o3 = ((e52, t4) =\u003e {\n const n4 = _2(t4);\n for (let t5 = 0;t5 \u003c n4.length; t5++) {\n const o4 = n4[t5], i4 = n4[(t5 + 1) % n4.length];\n if ((i4.x - o4.x) * (e52.y - o4.y) - (i4.y - o4.y) * (e52.x - o4.x) \u003c -0.0000001)\n return false;\n }\n return true;\n })(f2(e51), e51) ? [...e51] : ((e52) =\u003e {\n const t4 = [...e52].filter((e53, t5, n5) =\u003e n5.findIndex((t6) =\u003e Math.abs(t6.x - e53.x) \u003c 0.000000001 \u0026\u0026 Math.abs(t6.y - e53.y) \u003c 0.000000001) === t5).sort((e53, t5) =\u003e e53.x - t5.x || e53.y - t5.y);\n if (t4.length \u003c= 3)\n return t4;\n const n4 = (e53, t5, n5) =\u003e (t5.x - e53.x) * (n5.y - e53.y) - (t5.y - e53.y) * (n5.x - e53.x), o4 = [];\n for (const e53 of t4) {\n for (;o4.length \u003e= 2 \u0026\u0026 n4(o4[o4.length - 2], o4[o4.length - 1], e53) \u003c= 0.000000001; )\n o4.pop();\n o4.push(e53);\n }\n const i4 = [];\n for (let e53 = t4.length - 1;e53 \u003e= 0; e53--) {\n const o5 = t4[e53];\n for (;i4.length \u003e= 2 \u0026\u0026 n4(i4[i4.length - 2], i4[i4.length - 1], o5) \u003c= 0.000000001; )\n i4.pop();\n i4.push(o5);\n }\n return o4.pop(), i4.pop(), [...o4, ...i4];\n })(e51), i3 = f2(o3), r3 = y2(o3, i3), s3 = g2(o3), a3 = r3.width * r3.height, c3 = (l3 = t3, Math.max(0, l3));\n var l3;\n const h3 = a3 + Math.max(0, s3 - a3) * c3, d3 = a3 \u003e c22 \u0026\u0026 h3 \u003e a3 ? Math.sqrt(h3 / a3) : 1, u3 = Math.max(0, n3), p3 = Math.max(r3.width * d3, u3), m3 = Math.max(r3.height * d3, u3), g3 = u2(r3.ccwRotationRadians), f3 = 180 * g3 / Math.PI, _3 = ((e52) =\u003e {\n const t4 = e52.width / 2, n4 = e52.height / 2;\n return [{ x: e52.center.x - t4, y: e52.center.y - n4 }, { x: e52.center.x + t4, y: e52.center.y - n4 }, { x: e52.center.x + t4, y: e52.center.y + n4 }, { x: e52.center.x - t4, y: e52.center.y + n4 }];\n })({ center: i3, width: p3, height: m3 }), y3 = ((e52) =\u003e {\n const t4 = e52.width / 2, n4 = e52.height / 2;\n return [S2({ x: -t4, y: -n4 }, e52.center, e52.ccwRotationRadians), S2({ x: t4, y: -n4 }, e52.center, e52.ccwRotationRadians), S2({ x: t4, y: n4 }, e52.center, e52.ccwRotationRadians), S2({ x: -t4, y: n4 }, e52.center, e52.ccwRotationRadians)];\n })({ center: i3, width: p3, height: m3, ccwRotationRadians: g3 }), b3 = y3.map((e52) =\u003e {\n const t4 = { x: e52.x - i3.x, y: e52.y - i3.y }, n4 = ((e53, t5, n5) =\u003e {\n let o4;\n for (let i4 = 0;i4 \u003c n5.length; i4++) {\n const r4 = b2(e53, t5, n5[i4], n5[(i4 + 1) % n5.length]);\n r4 \u0026\u0026 (!o4 || r4.rayT \u003c o4.rayT) \u0026\u0026 (o4 = r4);\n }\n return o4;\n })(i3, t4, o3);\n return n4 ? { x: n4.x, y: n4.y } : e52;\n });\n let x3 = g2(b3) \u003e c22 ? b3 : y3;\n let v3, I3;\n try {\n v3 = x2(_3, x3), I3 = ((e52) =\u003e {\n const [t4, n4, o4, i4, r4, s4, a4, c4, l4] = e52, h4 = r4 * l4 - s4 * c4, d4 = -(i4 * l4 - s4 * a4), u4 = i4 * c4 - r4 * a4, p4 = -(n4 * l4 - o4 * c4), m4 = t4 * l4 - o4 * a4, g4 = -(t4 * c4 - n4 * a4), f4 = n4 * s4 - o4 * r4, _4 = -(t4 * s4 - o4 * i4), y4 = t4 * r4 - n4 * i4, b4 = t4 * h4 + n4 * d4 + o4 * u4;\n if (Math.abs(b4) \u003c c22)\n throw new Error(\"Cannot invert singular 3x3 matrix\");\n const x4 = 1 / b4;\n return [h4 * x4, p4 * x4, f4 * x4, d4 * x4, m4 * x4, _4 * x4, u4 * x4, g4 * x4, y4 * x4];\n })(v3);\n } catch {\n x3 = y3, v3 = v2(i3, g3), I3 = v2(i3, -g3);\n }\n return { center: i3, width: p3, height: m3, innerWidth: r3.width, innerHeight: r3.height, ccwRotationDegrees: f3, ccwRotationRadians: g3, polygonArea: s3, equivalentAreaExpansionFactor: c3, targetQuad: x3, rectToPolygonMatrix: v3, polygonToRectMatrix: I3 };\n};\nvar w2 = class extends ni {\n constructor(e51) {\n super(), this.params = e51, this.MAX_ITERATIONS = 1;\n }\n getSolverName() {\n return \"AttachProjectedRectsSolver\";\n }\n outputNodes = [];\n projectionAdjustmentByNodeId = new Map;\n _step() {\n this.projectionAdjustmentByNodeId.clear(), this.outputNodes = this.params.nodesWithPortPoints.map((e51) =\u003e {\n const t3 = this.params.equivalentAreaExpansionFactor ?? 0, n3 = this.params.minProjectedRectDimension ?? 0, o3 = (({ traceWidth: e52, viaDiameter: t4, obstacleMargin: n4, minProjectedRectDimension: o4 }) =\u003e Math.max(o4, t4 ?? 0, (e52 ?? 0) + 2 * (n4 ?? 0)))({ traceWidth: this.params.traceWidth, viaDiameter: this.params.viaDiameter, obstacleMargin: this.params.obstacleMargin, minProjectedRectDimension: n3 });\n let i3 = M2(e51.polygon, t3, n3);\n if (Math.min(i3.width, i3.height) \u003e o3 + (this.params.traceWidth ?? 0))\n return { ...e51, center: i3.center, width: i3.width, height: i3.height, projectedRect: i3 };\n const r3 = M2(e51.polygon, 1, n3);\n return (({ node: e52, projectedRect: t4, conservativeProjectedRect: n4, requiredRoutingCorridorWidth: o4, traceWidth: i4 }) =\u003e {\n if (o4 \u003c= 0)\n return false;\n const r4 = Math.min(t4.width, t4.height), s3 = Math.min(n4.width, n4.height), a3 = Math.max(t4.width, t4.height), c3 = Math.max(n4.width, n4.height), l3 = o4 + (i4 ?? 0), h3 = Math.floor(r4 / o4), d3 = Math.floor(s3 / o4);\n return new Set(e52.portPoints.map((e53) =\u003e e53.connectionName)).size \u003e 1 \u0026\u0026 h3 \u003c= d3 \u0026\u0026 r4 \u003c= l3 \u0026\u0026 a3 - c3 \u003e= o4 \u0026\u0026 t4.equivalentAreaExpansionFactor \u003e 1;\n })({ node: e51, projectedRect: i3, conservativeProjectedRect: r3, requiredRoutingCorridorWidth: o3, traceWidth: this.params.traceWidth }) \u0026\u0026 (i3 = r3, this.projectionAdjustmentByNodeId.set(e51.capacityMeshNodeId, \"corridor-expansion-factor-1\")), { ...e51, center: i3.center, width: i3.width, height: i3.height, projectedRect: i3 };\n }), this.solved = true;\n }\n getOutput() {\n return this.outputNodes;\n }\n getConstructorParams() {\n return [this.params];\n }\n visualize() {\n const e51 = this.outputNodes.length \u003e 0 ? this.outputNodes : this.params.nodesWithPortPoints;\n return { polygons: e51.map((e52) =\u003e ({ points: e52.polygon, fill: \"rgba(40, 140, 220, 0.06)\", stroke: \"rgba(20, 70, 160, 0.95)\", strokeWidth: 0.04, label: `${e52.capacityMeshNodeId} polygon` })), lines: e51.map((e52) =\u003e ({ points: [...e52.polygon, e52.polygon[0]], strokeColor: \"rgba(20, 70, 160, 0.95)\", strokeWidth: 0.04, label: `${e52.capacityMeshNodeId} polygon outline` })), rects: e51.flatMap((e52) =\u003e e52.projectedRect ? [{ center: e52.projectedRect.center, width: e52.projectedRect.width, height: e52.projectedRect.height, ccwRotationDegrees: e52.projectedRect.ccwRotationDegrees, fill: \"rgba(255, 165, 0, 0.16)\", stroke: \"rgba(255, 140, 0, 0.8)\", label: `${e52.capacityMeshNodeId} projectedRect` }] : []), points: e51.flatMap((e52) =\u003e e52.portPoints.map((e53) =\u003e ({ x: e53.x, y: e53.y, color: \"rgba(30, 30, 30, 0.85)\", label: e53.connectionName }))) };\n }\n};\nvar N2 = class extends ni {\n constructor(e51) {\n super(), this.params = e51;\n const { nodeWithPortPoints: t3 } = e51;\n if (!t3.projectedRect)\n throw new Error(\"Poly node is missing projectedRect\");\n this.projectedPorts = t3.portPoints.map((e52) =\u003e {\n const n3 = P2(e52, t3.projectedRect);\n return { original: e52, projected: { ...e52, x: n3.x, y: n3.y } };\n }), this.projectedNode = { capacityMeshNodeId: t3.capacityMeshNodeId, center: t3.projectedRect.center, width: t3.projectedRect.width, height: t3.projectedRect.height, availableZ: t3.availableZ, portPoints: this.projectedPorts.map(({ projected: e52 }) =\u003e e52) }, this.highDensitySolver = new xz({ nodeWithPortPoints: this.projectedNode, colorMap: e51.colorMap, connMap: e51.connMap, viaDiameter: e51.viaDiameter, traceWidth: e51.traceWidth, obstacleMargin: e51.obstacleMargin, effort: e51.effort }), this.activeSubSolver = this.highDensitySolver, this.MAX_ITERATIONS = this.highDensitySolver.MAX_ITERATIONS + 1000;\n }\n getSolverName() {\n return \"PolySingleIntraNodeSolver\";\n }\n highDensitySolver;\n projectedNode;\n solvedRoutes = [];\n projectedPorts;\n _step() {\n this.highDensitySolver.step(), this.progress = this.highDensitySolver.progress, this.stats = this.highDensitySolver.stats, this.highDensitySolver.solved ? (this.solvedRoutes = this.highDensitySolver.solvedRoutes, this.solved = true, this.activeSubSolver = null) : this.highDensitySolver.failed \u0026\u0026 (this.error = this.highDensitySolver.error, this.failed = true, this.activeSubSolver = null);\n }\n getConstructorParams() {\n return [this.params];\n }\n visualize() {\n const e51 = this.params.nodeWithPortPoints, t3 = e51.projectedRect, n3 = { polygons: [{ points: e51.polygon, fill: \"rgba(60, 160, 220, 0.10)\", stroke: \"rgba(40, 90, 150, 0.7)\", label: `${e51.capacityMeshNodeId} polygon` }, ...t3 ? [{ points: t3.targetQuad, fill: \"rgba(255, 165, 0, 0.08)\", stroke: \"rgba(255, 120, 0, 0.65)\", label: `${e51.capacityMeshNodeId} distortion target` }] : []], rects: t3 ? [{ center: t3.center, width: t3.width, height: t3.height, ccwRotationDegrees: t3.ccwRotationDegrees, fill: \"rgba(255, 165, 0, 0.14)\", stroke: \"rgba(255, 120, 0, 0.8)\", label: `${e51.capacityMeshNodeId} projectedRect` }] : [], points: [...e51.portPoints.map((e52) =\u003e ({ x: e52.x, y: e52.y, color: \"rgba(0, 80, 160, 0.85)\", label: `${e52.connectionName} original` })), ...this.projectedPorts.map(({ projected: e52 }) =\u003e ({ x: e52.x, y: e52.y, color: \"rgba(255, 120, 0, 0.85)\", label: `${e52.connectionName} projected` }))] };\n return pi(n3, this.highDensitySolver.visualize());\n }\n};\nvar R2 = class extends ni {\n getSolverName() {\n return \"PolyHighDensitySolver\";\n }\n unsolvedNodePortPoints;\n nodePortPoints;\n routes = [];\n routesByNodeId = new Map;\n failedSolvers = [];\n activeSubSolver = null;\n colorMap;\n connMap;\n viaDiameter;\n traceWidth;\n obstacleMargin;\n effort;\n nodePfById;\n constructor({ nodePortPoints: e51, colorMap: t3, connMap: n3, viaDiameter: o3, traceWidth: i3, obstacleMargin: r3, effort: s3, nodePfById: a3 }) {\n super(), this.nodePortPoints = [...e51], this.unsolvedNodePortPoints = [...e51], this.colorMap = t3 ?? {}, this.connMap = n3, this.viaDiameter = o3 ?? 0.3, this.traceWidth = i3 ?? 0.15, this.obstacleMargin = r3 ?? 0.15, this.effort = s3 ?? 1, this.MAX_ITERATIONS = 1e7 * this.effort, this.nodePfById = a3 instanceof Map ? new Map(a3) : new Map(Object.entries(a3 ?? {}));\n }\n _step() {\n if (this.activeSubSolver) {\n if (this.activeSubSolver.step(), this.activeSubSolver.solved) {\n const e52 = this.activeSubSolver.params.nodeWithPortPoints.capacityMeshNodeId, t3 = this.activeSubSolver.solvedRoutes;\n this.routesByNodeId.set(e52, [...this.routesByNodeId.get(e52) ?? [], ...t3]), this.routes.push(...this.activeSubSolver.solvedRoutes), this.activeSubSolver = null;\n } else\n this.activeSubSolver.failed \u0026\u0026 (this.failedSolvers.push(this.activeSubSolver), this.activeSubSolver = null);\n return;\n }\n if (this.unsolvedNodePortPoints.length === 0)\n return this.failedSolvers.length \u003e 0 ? (this.failed = true, void (this.error = `Failed to solve ${this.failedSolvers.length} poly nodes, ${this.failedSolvers.slice(0, 5).map((e52) =\u003e e52.params.nodeWithPortPoints.capacityMeshNodeId).join(\", \")}. err0: ${this.failedSolvers[0]?.error}`)) : void (this.solved = true);\n const e51 = this.unsolvedNodePortPoints.pop();\n this.activeSubSolver = new N2({ nodeWithPortPoints: e51, colorMap: this.colorMap, connMap: this.connMap, viaDiameter: this.viaDiameter, traceWidth: this.traceWidth, obstacleMargin: this.obstacleMargin, effort: this.effort });\n }\n computeProgress() {\n const e51 = this.routes.length + this.failedSolvers.length + this.unsolvedNodePortPoints.length + (this.activeSubSolver ? 1 : 0);\n return e51 === 0 ? 1 : (this.routes.length + this.failedSolvers.length + (this.activeSubSolver?.progress ?? 0)) / e51;\n }\n getConstructorParams() {\n return [{ nodePortPoints: this.nodePortPoints, colorMap: this.colorMap, connMap: this.connMap, viaDiameter: this.viaDiameter, traceWidth: this.traceWidth, obstacleMargin: this.obstacleMargin, effort: this.effort, nodePfById: this.nodePfById }];\n }\n visualize() {\n const e51 = { polygons: this.nodePortPoints.map((e52) =\u003e ({ points: e52.polygon, fill: \"rgba(180, 180, 180, 0.05)\", stroke: \"rgba(120, 120, 120, 0.25)\", label: `${e52.capacityMeshNodeId} polygon` })), rects: this.nodePortPoints.flatMap((e52) =\u003e e52.projectedRect ? [{ center: e52.projectedRect.center, width: e52.projectedRect.width, height: e52.projectedRect.height, ccwRotationDegrees: e52.projectedRect.ccwRotationDegrees, fill: \"rgba(255, 165, 0, 0.08)\", stroke: \"rgba(255, 120, 0, 0.65)\", label: `${e52.capacityMeshNodeId} projectedRect` }] : []), lines: [], circles: [], points: this.nodePortPoints.flatMap((e52) =\u003e e52.portPoints.map((e53) =\u003e ({ x: e53.x, y: e53.y, color: \"rgba(80, 80, 80, 0.5)\", label: `${e53.connectionName} original` }))) };\n for (const [t4, n3] of this.routesByNodeId) {\n const o3 = this.nodePortPoints.find((e52) =\u003e e52.capacityMeshNodeId === t4), i3 = o3?.projectedRect;\n if (i3)\n for (const t5 of n3) {\n const n4 = this.colorMap[t5.connectionName] ?? \"#0000ff\", o4 = { ...t5, route: t5.route.map((e52) =\u003e ({ ...e52, ...C2(e52, i3) })), vias: t5.vias.map((e52) =\u003e C2(e52, i3)) }, r3 = mi(o4.route, t5.connectionName, n4);\n for (const n5 of r3)\n e51.lines.push({ points: n5.points, label: n5.connectionName, strokeColor: n5.z === 0 ? n5.color : Ao(n5.color, 0.5), layer: `z${n5.z}`, strokeWidth: t5.traceThickness, strokeDash: n5.z !== 0 ? [0.1, 0.3] : undefined });\n for (const i4 of o4.vias)\n e51.circles.push({ center: i4, layer: \"z0,1\", radius: t5.viaDiameter / 2, fill: n4, label: `${t5.connectionName} via` });\n }\n }\n const t3 = this.activeSubSolver?.visualize();\n return t3 \u0026\u0026 e51.polygons.push(...this.unsolvedNodePortPoints.map((e52) =\u003e ({ points: e52.polygon, fill: \"rgba(180, 180, 180, 0.08)\", stroke: \"rgba(120, 120, 120, 0.4)\", label: e52.capacityMeshNodeId }))), t3 ? pi(e51, t3) : e51;\n }\n};\nvar E22 = (e51) =\u003e {\n const { o: t3, a: n3, b: o3 } = e51;\n return (n3.x - t3.x) * (o3.y - t3.y) - (n3.y - t3.y) * (o3.x - t3.x);\n};\nvar A2 = (e51, t3) =\u003e {\n const n3 = [...new Set(e51)].map((e52) =\u003e {\n const n4 = t3[e52];\n return n4 ? { i: e52, x: n4.x, y: n4.y } : null;\n }).filter((e52) =\u003e e52 !== null);\n if (n3.sort((e52, t4) =\u003e e52.x - t4.x || e52.y - t4.y), n3.length \u003c= 2)\n return n3.map((e52) =\u003e e52.i);\n const o3 = [], i3 = [];\n for (const e52 of n3) {\n for (;o3.length \u003e= 2; ) {\n const t4 = o3[o3.length - 2], n4 = o3[o3.length - 1];\n if (!t4 || !n4 || E22({ o: t4, a: n4, b: e52 }) \u003e 0.0000000001)\n break;\n o3.pop();\n }\n o3.push(e52);\n }\n for (let e52 = n3.length - 1;e52 \u003e= 0; e52--) {\n const t4 = n3[e52];\n if (t4) {\n for (;i3.length \u003e= 2; ) {\n const e53 = i3[i3.length - 2], n4 = i3[i3.length - 1];\n if (!e53 || !n4 || E22({ o: e53, a: n4, b: t4 }) \u003e 0.0000000001)\n break;\n i3.pop();\n }\n i3.push(t4);\n }\n }\n return o3.pop(), i3.pop(), o3.concat(i3).map((e52) =\u003e e52.i);\n};\nvar O2 = (e51) =\u003e {\n const t3 = Math.max(0, Math.min(30, Math.floor(e51)));\n return t3 === 0 ? 0 : (1 \u003c\u003c t3) - 1;\n};\nvar k2 = (e51, t3 = 31) =\u003e {\n const n3 = [], o3 = Math.max(0, Math.min(31, Math.floor(t3)));\n for (let t4 = 0;t4 \u003c o3; t4++)\n e51 \u0026 1 \u003c\u003c t4 \u0026\u0026 n3.push(t4);\n return n3;\n};\nvar D2 = (e51) =\u003e {\n let t3 = 0;\n for (const n3 of e51)\n Number.isInteger(n3) \u0026\u0026 n3 \u003e= 0 \u0026\u0026 n3 \u003c 31 \u0026\u0026 (t3 |= 1 \u003c\u003c n3);\n return t3;\n};\nvar L2 = (e51, t3) =\u003e {\n const n3 = e51.trim().toLowerCase();\n if (n3 === \"top\")\n return 0;\n if (n3 === \"bottom\")\n return Math.max(0, t3 - 1);\n const o3 = n3.match(/^inner(\\d+)$/);\n if (o3?.[1]) {\n const e52 = Number(o3[1]);\n return e52 \u003e= 0 \u0026\u0026 e52 \u003c t3 ? e52 : undefined;\n }\n const i3 = n3.match(/^layer(\\d+)$/);\n if (i3?.[1]) {\n const e52 = Number(i3[1]) - 1;\n return e52 \u003e= 0 \u0026\u0026 e52 \u003c t3 ? e52 : undefined;\n }\n const r3 = n3.match(/^z(\\d+)$/);\n if (r3?.[1]) {\n const e52 = Number(r3[1]);\n return e52 \u003e= 0 \u0026\u0026 e52 \u003c t3 ? e52 : undefined;\n }\n};\nvar z2 = (e51, t3) =\u003e {\n const n3 = O2(t3), o3 = e51.zLayers;\n if (Array.isArray(o3) \u0026\u0026 o3.length \u003e 0)\n return D2(o3) \u0026 n3;\n const i3 = e51.layers;\n if (Array.isArray(i3) \u0026\u0026 i3.length \u003e 0) {\n let e52 = 0;\n for (const n4 of i3) {\n const o4 = L2(n4, t3);\n o4 !== undefined \u0026\u0026 (e52 |= 1 \u003c\u003c o4);\n }\n return e52 \u0026 n3;\n }\n return n3;\n};\nvar B2 = 0.1;\nvar F2 = 0.15;\nvar j2 = B2 + F2;\nvar $2 = 3 * j2 / 4;\nvar Y2 = 5;\nvar X2 = 0.000000001;\nvar H2 = (e51) =\u003e Math.round(1e6 * e51) / 1e6;\nvar V2 = (e51) =\u003e `${H2(e51.x)},${H2(e51.y)}`;\nvar W2 = (e51, t3) =\u003e {\n const n3 = V2(e51), o3 = V2(t3);\n return n3 \u003c o3 ? `${n3}|${o3}` : `${o3}|${n3}`;\n};\nvar G2 = (e51) =\u003e {\n let { POSITIVE_INFINITY: t3, NEGATIVE_INFINITY: n3, POSITIVE_INFINITY: o3, NEGATIVE_INFINITY: i3 } = Number;\n for (const r3 of e51)\n t3 = Math.min(t3, r3.x), n3 = Math.max(n3, r3.x), o3 = Math.min(o3, r3.y), i3 = Math.max(i3, r3.y);\n return { minX: t3, maxX: n3, minY: o3, maxY: i3 };\n};\nvar U2 = (e51, t3) =\u003e {\n const n3 = e51.x \u003c t3.minX ? t3.minX - e51.x : e51.x \u003e t3.maxX ? e51.x - t3.maxX : 0, o3 = e51.y \u003c t3.minY ? t3.minY - e51.y : e51.y \u003e t3.maxY ? e51.y - t3.maxY : 0;\n return n3 * n3 + o3 * o3;\n};\nvar Z2 = (e51, t3, n3) =\u003e {\n const o3 = n3.x - t3.x, i3 = n3.y - t3.y, r3 = o3 * o3 + i3 * i3;\n if (r3 \u003c 0.000000000000000001)\n return false;\n const s3 = ((e51.x - t3.x) * o3 + (e51.y - t3.y) * i3) / r3;\n if (s3 \u003c -0.000000001 || s3 \u003e 1 + 0.000000001)\n return false;\n const a3 = t3.x + s3 * o3, c3 = t3.y + s3 * i3;\n return (e51.x - a3) ** 2 + (e51.y - c3) ** 2 \u003c 0.000000000001;\n};\nvar q2 = (e51, t3, n3) =\u003e {\n const o3 = n3.x - t3.x, i3 = n3.y - t3.y, r3 = o3 * o3 + i3 * i3;\n if (r3 \u003c X2)\n return (e51.x - t3.x) ** 2 + (e51.y - t3.y) ** 2;\n const s3 = Math.max(0, Math.min(1, ((e51.x - t3.x) * o3 + (e51.y - t3.y) * i3) / r3)), a3 = t3.x + s3 * o3, c3 = t3.y + s3 * i3;\n return (e51.x - a3) ** 2 + (e51.y - c3) ** 2;\n};\nvar J2 = (e51, t3) =\u003e ({ x: (e51.x + t3.x) / 2, y: (e51.y + t3.y) / 2 });\nvar Q2 = (e51, t3, n3, o3 = 0.001) =\u003e {\n const i3 = o3 * o3;\n return ((e52, t4) =\u003e {\n let n4 = Number.POSITIVE_INFINITY;\n for (let o4 = 0;o4 \u003c t4.length; o4++) {\n const i4 = t4[o4], r3 = t4[(o4 + 1) % t4.length];\n n4 = Math.min(n4, q2(e52, i4, r3));\n }\n return n4;\n })(J2(e51, t3), n3) \u003c= i3;\n};\nvar K2 = (e51, t3) =\u003e {\n let n3 = false;\n for (let o3 = 0, i3 = t3.length - 1;o3 \u003c t3.length; i3 = o3++) {\n const r3 = t3[o3], s3 = t3[i3];\n if (Z2(e51, r3, s3))\n return true;\n r3.y \u003e e51.y != s3.y \u003e e51.y \u0026\u0026 e51.x \u003c (s3.x - r3.x) * (e51.y - r3.y) / (s3.y - r3.y + 0.000000000001) + r3.x \u0026\u0026 (n3 = !n3);\n }\n return n3;\n};\nvar e52 = (e51, t3, n3, o3) =\u003e {\n const i3 = t3.x - e51.x, r3 = t3.y - e51.y, s3 = o3.x - n3.x, a3 = o3.y - n3.y, c3 = i3 * a3 - r3 * s3;\n if (Math.abs(c3) \u003c X2) {\n for (const i4 of [e51, t3])\n if (Z2(i4, n3, o3))\n return i4;\n for (const i4 of [n3, o3])\n if (Z2(i4, e51, t3))\n return i4;\n return;\n }\n const l3 = ((n3.x - e51.x) * a3 - (n3.y - e51.y) * s3) / c3, h3 = ((n3.x - e51.x) * r3 - (n3.y - e51.y) * i3) / c3;\n if (!(l3 \u003c -0.000000001 || l3 \u003e 1.000000001 || h3 \u003c -0.000000001 || h3 \u003e 1.000000001))\n return { x: e51.x + l3 * i3, y: e51.y + l3 * r3 };\n};\nvar t5 = (e51, t3) =\u003e {\n for (const n3 of e51)\n if (K2(n3, t3))\n return n3;\n for (const n3 of t3)\n if (K2(n3, e51))\n return n3;\n for (let n3 = 0;n3 \u003c e51.length; n3++) {\n const o3 = e51[n3], i3 = e51[(n3 + 1) % e51.length];\n for (let e53 = 0;e53 \u003c t3.length; e53++) {\n const n4 = t3[e53], r3 = t3[(e53 + 1) % t3.length], s3 = e52(o3, i3, n4, r3);\n if (s3)\n return s3;\n }\n }\n};\nvar n5 = (e51, t3 = 0.000001) =\u003e [{ x: e51.x - t3, y: e51.y - t3 }, { x: e51.x + t3, y: e51.y - t3 }, { x: e51.x, y: e51.y + t3 }];\nvar o5 = (e51, t3, n3, o3, i3) =\u003e {\n const r3 = t3.x - e51.x, s3 = t3.y - e51.y, a3 = Math.hypot(r3, s3);\n if (a3 \u003c X2)\n return [];\n const c3 = Number.isFinite(n3) \u0026\u0026 n3 \u003e X2 ? n3 : j2, l3 = Number.isFinite(o3) ? Math.max(0, o3) : $2, h3 = Math.min(l3, a3 / 2), d3 = a3 - 2 * h3;\n if (d3 \u003c= 0.75 * c3)\n return [{ x: (e51.x + t3.x) / 2, y: (e51.y + t3.y) / 2, distToCentermostPortOnZ: 0, cramped: true }];\n const u3 = Math.max(1, Math.floor(d3 / c3) + 1), p3 = Number.isFinite(i3) \u0026\u0026 i3 \u003e 0 ? Math.floor(i3) : Y2, m3 = u3 \u003e p3 ? p3 + Math.floor(u3 / 4) : u3;\n if (m3 \u003c= 1)\n return [{ x: (e51.x + t3.x) / 2, y: (e51.y + t3.y) / 2, distToCentermostPortOnZ: 0, cramped: false }];\n const g3 = a3 / 2, f3 = Array.from({ length: m3 }, (t4, n4) =\u003e {\n const o4 = h3 + d3 * n4 / (m3 - 1), i4 = o4 / a3;\n return { x: e51.x + r3 * i4, y: e51.y + s3 * i4, distanceFromStart: o4 };\n }), _3 = f3.reduce((e53, t4) =\u003e Math.abs(t4.distanceFromStart - g3) \u003c Math.abs(e53 - g3) ? t4.distanceFromStart : e53, f3[0].distanceFromStart);\n return f3.map(({ x: e53, y: t4, distanceFromStart: n4 }) =\u003e ({ x: e53, y: t4, distToCentermostPortOnZ: Math.abs(n4 - _3), cramped: false }));\n};\nvar i5 = (e51, t3) =\u003e {\n if (!(Math.hypot(t3.x - e51.x, t3.y - e51.y) \u003c X2))\n return { ...J2(e51, t3), distToCentermostPortOnZ: 0, cramped: false };\n};\nvar r5 = (e51, t3) =\u003e {\n if (typeof e51 != \"object\" || e51 === null)\n return;\n const n3 = e51[t3];\n return typeof n3 == \"string\" ? n3 : undefined;\n};\nvar s5 = (e51) =\u003e {\n const t3 = new Set, n3 = (e53) =\u003e {\n typeof e53 == \"string\" \u0026\u0026 e53.length \u003e 0 \u0026\u0026 t3.add(e53);\n }, o3 = (e53) =\u003e {\n n3(e53.pointId), n3(e53.pcb_port_id);\n };\n n3(e51.connectionId), n3(e51.mutuallyConnectedNetworkId), o3(e51.start), o3(e51.end);\n const i3 = e51.simpleRouteConnection;\n n3(r5(i3, \"name\")), n3(r5(i3, \"source_trace_id\")), n3(r5(i3, \"rootConnectionName\"));\n const r3 = typeof i3 == \"object\" \u0026\u0026 i3 !== null ? i3.pointsToConnect : undefined;\n if (Array.isArray(r3))\n for (const e53 of r3)\n o3(e53);\n return t3;\n};\nvar a5 = (e51) =\u003e {\n const { regions: t3, availableZ: n3, layerCount: o3, connections: i3 = [], obstacleRegions: r3 = [], regionIdPrefix: s3 = \"free\", portIdPrefix: a3 = \"shared-port\", traceWidth: c3 = B2, obstacleMargin: l3 = F2, portSpacing: h3 = c3 + l3, portMarginFromSegmentEndpoint: d3 = 3 * h3 / 4, maxDensePortsBeforeDecimation: u3 = Y2 } = e51, p3 = Array.from({ length: o3 }, (e53, t4) =\u003e t4), m3 = new Map, g3 = new Map, f3 = (e53) =\u003e e53.mutuallyConnectedNetworkId ?? e53.connectionId;\n for (const e53 of i3) {\n const t4 = f3(e53);\n let n4 = m3.get(t4);\n n4 === undefined \u0026\u0026 (n4 = m3.size, m3.set(t4, n4));\n for (const t6 of s5(e53))\n g3.has(t6) || g3.set(t6, n4);\n }\n const _3 = t3.map((e53, t4) =\u003e {\n const o4 = G2(e53);\n return { regionId: `${s3}-${t4}`, pointIds: [], d: { polygon: e53, availableZ: n3?.[t4] ?? p3, center: { x: (o4.minX + o4.maxX) / 2, y: (o4.minY + o4.maxY) / 2 }, width: o4.maxX - o4.minX, height: o4.maxY - o4.minY } };\n }), y3 = _3.map((e53, t4) =\u003e ({ regionId: e53.regionId, serializedRegionIndex: t4, polygon: e53.d.polygon, availableZ: e53.d.availableZ, bounds: G2(e53.d.polygon), isObstacle: false, netId: undefined })), b3 = r3.flatMap((e53, t4) =\u003e {\n if (e53.polygon.length \u003c 3)\n return [];\n const n4 = ((e54) =\u003e {\n if (Number.isInteger(e54.netId) \u0026\u0026 e54.netId \u003e= 0)\n return e54.netId;\n if (typeof e54.mutuallyConnectedNetworkId == \"string\")\n return m3.get(e54.mutuallyConnectedNetworkId);\n for (const t6 of e54.connectedTo ?? []) {\n const e55 = g3.get(t6);\n if (e55 !== undefined)\n return e55;\n }\n })(e53);\n if (n4 === undefined)\n return [];\n const o4 = e53.polygon, i4 = G2(o4), r4 = e53.availableZ ?? p3, s4 = e53.regionId ?? `obstacle-${t4}`, a4 = _3.length;\n _3.push({ regionId: s4, pointIds: [], d: { ...e53.d ?? {}, polygon: o4, availableZ: r4, center: { x: (i4.minX + i4.maxX) / 2, y: (i4.minY + i4.maxY) / 2 }, width: i4.maxX - i4.minX, height: i4.maxY - i4.minY, _containsObstacle: true, _containsTarget: true, netId: n4 } });\n const c4 = { regionId: s4, serializedRegionIndex: a4, polygon: o4, availableZ: r4, bounds: i4, isObstacle: true, netId: n4 };\n return y3.push(c4), [c4];\n }), x3 = [], v3 = new Map;\n for (let e53 = 0;e53 \u003c t3.length; e53++) {\n const n4 = t3[e53];\n for (let t4 = 0;t4 \u003c n4.length; t4++) {\n const o4 = n4[t4], i4 = n4[(t4 + 1) % n4.length], r4 = W2(o4, i4), s4 = v3.get(r4) ?? [];\n s4.push({ regionIndex: e53, a: o4, b: i4 }), v3.set(r4, s4);\n }\n }\n let I3 = 0;\n const S3 = (e53) =\u003e {\n const { region1Id: t4, region2Id: n4, pointIndex: o4, portPoint: i4, z: r4, portIdSuffix: s4 } = e53, c4 = `${a3}-${String(I3).padStart(5, \"0\")}::p${o4}::z${r4}${s4 ?? \"\"}`;\n return x3.push({ portId: c4, region1Id: t4, region2Id: n4, d: { portId: c4, x: i4.x, y: i4.y, z: r4, distToCentermostPortOnZ: i4.distToCentermostPortOnZ, ...i4.cramped ? { cramped: true } : {} } }), I3 += 1, c4;\n };\n for (const e53 of v3.values()) {\n if (e53.length !== 2)\n continue;\n const [t4, o4] = e53, i4 = n3?.[t4.regionIndex] ?? p3, r4 = n3?.[o4.regionIndex] ?? p3, a4 = i4.filter((e54) =\u003e r4.includes(e54));\n if (a4.length === 0)\n continue;\n const c4 = o5(t4.a, t4.b, h3, d3, u3);\n if (c4.length !== 0)\n for (let e54 = 0;e54 \u003c c4.length; e54++) {\n const n4 = c4[e54];\n for (const i6 of a4) {\n if (b3.some((e55) =\u003e e55.availableZ.includes(i6) \u0026\u0026 Q2(t4.a, t4.b, e55.polygon)))\n continue;\n const r6 = S3({ region1Id: `${s3}-${t4.regionIndex}`, region2Id: `${s3}-${o4.regionIndex}`, pointIndex: e54, portPoint: n4, z: i6 });\n _3[t4.regionIndex].pointIds.push(r6), _3[o4.regionIndex].pointIds.push(r6);\n }\n }\n }\n for (const e53 of b3)\n for (const t4 of v3.values())\n for (const o4 of t4) {\n if (!Q2(o4.a, o4.b, e53.polygon))\n continue;\n const t6 = (n3?.[o4.regionIndex] ?? p3).filter((t7) =\u003e e53.availableZ.includes(t7));\n if (t6.length === 0)\n continue;\n const i4 = i5(o4.a, o4.b);\n if (i4)\n for (const n4 of t6) {\n const t7 = S3({ region1Id: `${s3}-${o4.regionIndex}`, region2Id: e53.regionId, pointIndex: 0, portPoint: i4, z: n4, portIdSuffix: \"::obstacle\" });\n _3[o4.regionIndex].pointIds.push(t7), _3[e53.serializedRegionIndex].pointIds.push(t7);\n }\n }\n for (let e53 = 0;e53 \u003c b3.length; e53++) {\n const t4 = b3[e53];\n for (let n4 = e53 + 1;n4 \u003c b3.length; n4++) {\n const e54 = b3[n4];\n if (t4.netId !== e54.netId)\n continue;\n const o4 = t4.availableZ.filter((t6) =\u003e e54.availableZ.includes(t6));\n if (o4.length === 0)\n continue;\n const i4 = t5(t4.polygon, e54.polygon);\n if (i4)\n for (const n6 of o4) {\n const o6 = S3({ region1Id: t4.regionId, region2Id: e54.regionId, pointIndex: 0, portPoint: { x: i4.x, y: i4.y, distToCentermostPortOnZ: 0 }, z: n6, portIdSuffix: \"::obstacle-contact\" });\n _3[t4.serializedRegionIndex].pointIds.push(o6), _3[e54.serializedRegionIndex].pointIds.push(o6);\n }\n }\n }\n const C = (e53, t4) =\u003e {\n const n4 = ((e54, t6) =\u003e {\n if (Number.isInteger(e54.z) \u0026\u0026 e54.z \u003e= 0 \u0026\u0026 e54.z \u003c t6)\n return [e54.z];\n if (Array.isArray(e54.zLayers) \u0026\u0026 e54.zLayers.length \u003e 0)\n return e54.zLayers.filter((e55) =\u003e Number.isInteger(e55) \u0026\u0026 e55 \u003e= 0 \u0026\u0026 e55 \u003c t6);\n if (typeof e54.layer == \"string\") {\n const n6 = L2(e54.layer, t6);\n return n6 === undefined ? [] : [n6];\n }\n return Array.isArray(e54.layers) \u0026\u0026 e54.layers.length \u003e 0 ? e54.layers.map((e55) =\u003e L2(e55, t6)).filter((e55) =\u003e e55 !== undefined) : [0];\n })(e53, o3);\n let i4;\n const r4 = y3.filter((e54) =\u003e e54.isObstacle \u0026\u0026 (t4 === undefined || e54.netId === t4));\n for (const t6 of r4) {\n const o4 = n4.find((e54) =\u003e t6.availableZ.includes(e54)) ?? t6.availableZ[0];\n if (o4 !== undefined \u0026\u0026 K2(e53, t6.polygon))\n return { regionId: t6.regionId, serializedRegionIndex: t6.serializedRegionIndex, z: o4 };\n }\n for (const t6 of y3.filter((e54) =\u003e !e54.isObstacle)) {\n const o4 = n4.find((e54) =\u003e t6.availableZ.includes(e54)) ?? t6.availableZ[0];\n if (o4 === undefined)\n continue;\n if (K2(e53, t6.polygon))\n return { regionId: t6.regionId, serializedRegionIndex: t6.serializedRegionIndex, z: o4 };\n const r6 = U2(e53, t6.bounds);\n (!i4 || r6 \u003c i4.distanceSq) \u0026\u0026 (i4 = { regionId: t6.regionId, serializedRegionIndex: t6.serializedRegionIndex, z: o4, distanceSq: r6 });\n }\n return i4;\n }, P = [];\n for (const e53 of i3) {\n const t4 = m3.get(f3(e53)), n4 = C(e53.start, t4), o4 = C(e53.end, t4);\n if (!n4 || !o4)\n throw new Error(`Could not map connection \"${e53.connectionId}\" endpoint into a generated region`);\n const i4 = `terminal-start-${e53.connectionId}`, r4 = `terminal-end-${e53.connectionId}`, s4 = `terminal-start-port-${e53.connectionId}`, a4 = `terminal-end-port-${e53.connectionId}`;\n _3.push({ regionId: i4, pointIds: [s4], d: { polygon: n5(e53.start), availableZ: [n4.z], center: { x: e53.start.x, y: e53.start.y }, width: 0.000001, height: 0.000001, _containsTarget: true } }), _3.push({ regionId: r4, pointIds: [a4], d: { polygon: n5(e53.end), availableZ: [o4.z], center: { x: e53.end.x, y: e53.end.y }, width: 0.000001, height: 0.000001, _containsTarget: true } }), x3.push({ portId: s4, region1Id: n4.regionId, region2Id: i4, d: { portId: s4, x: e53.start.x, y: e53.start.y, z: n4.z, distToCentermostPortOnZ: 0 } }), x3.push({ portId: a4, region1Id: o4.regionId, region2Id: r4, d: { portId: a4, x: e53.end.x, y: e53.end.y, z: o4.z, distToCentermostPortOnZ: 0 } }), _3[n4.serializedRegionIndex].pointIds.push(s4), _3[o4.serializedRegionIndex].pointIds.push(a4), P.push({ connectionId: e53.connectionId, mutuallyConnectedNetworkId: e53.mutuallyConnectedNetworkId, startRegionId: i4, endRegionId: r4, simpleRouteConnection: e53.simpleRouteConnection });\n }\n return { regions: _3, ports: x3, connections: P };\n};\nvar d5 = (e51) =\u003e {\n const { polygon: t3, clearance: n3, verticesOnly: o3 = false } = e51, i3 = t3.points, r3 = i3.length;\n if (r3 \u003c 3)\n return [];\n const s3 = new D_(i3.map((e53) =\u003e C_(e53.x, e53.y))).orientation() === Cg.CCW, a3 = [];\n for (let e53 = 0;e53 \u003c r3; e53++) {\n const t4 = i3[e53], o4 = i3[(e53 + 1) % r3], c4 = M_(o4.x - t4.x, o4.y - t4.y);\n if (c4.length === 0) {\n a3.push(T_(C_(t4.x, t4.y), M_(1, 0)));\n continue;\n }\n const l4 = c4.normalize(), h3 = s3 ? M_(l4.y, -l4.x) : M_(-l4.y, l4.x), d3 = C_(t4.x + n3 * h3.x, t4.y + n3 * h3.y);\n a3.push(T_(d3, h3));\n }\n const c3 = [];\n for (let e53 = 0;e53 \u003c r3; e53++) {\n const t4 = a3[(e53 - 1 + r3) % r3], n4 = a3[e53], o4 = t4.intersect(n4);\n if (o4.length \u003e 0) {\n const e54 = o4[0];\n c3.push({ x: e54.x, y: e54.y });\n } else\n c3.push({ x: n4.pt.x, y: n4.pt.y });\n }\n if (o3)\n return c3;\n const l3 = [];\n for (let e53 = 0;e53 \u003c r3; e53++) {\n const t4 = c3[e53], n4 = c3[(e53 + 1) % r3], o4 = N_(C_(t4.x, t4.y), C_(n4.x, n4.y)).length, i4 = Math.max(2, Math.ceil(o4 / 20));\n for (let e54 = 0;e54 \u003c i4; e54++) {\n const o6 = e54 / i4;\n l3.push({ x: t4.x + o6 * (n4.x - t4.x), y: t4.y + o6 * (n4.y - t4.y) });\n }\n }\n return l3;\n};\nvar u5 = (e51) =\u003e {\n const { localX: t3, localY: n3, rect: o3 } = e51, i3 = Math.cos(o3.ccwRotation), r3 = Math.sin(o3.ccwRotation);\n return { x: o3.center.x + t3 * i3 - n3 * r3, y: o3.center.y + t3 * r3 + n3 * i3 };\n};\nvar p5 = (e51) =\u003e new D_(e51.map((e53) =\u003e C_(e53.x, e53.y)));\nvar m5 = (e51) =\u003e {\n const t3 = [];\n for (const n3 of e51.faces) {\n const e53 = [];\n for (const t4 of n3.vertices)\n e53.push({ x: t4.x, y: t4.y });\n e53.length \u003e= 3 \u0026\u0026 t3.push(e53);\n }\n return t3;\n};\nvar g5 = (e51, t3, n3) =\u003e {\n const o3 = t3.length;\n t3.push(...e51);\n const i3 = e51.length;\n for (let e53 = 0;e53 \u003c i3; e53++)\n n3.push([o3 + e53, o3 + (e53 + 1) % i3]);\n};\nvar f5 = (e51) =\u003e {\n const { bounds: t3, vias: n3, clearance: o3, rects: i3, polygons: r3 = [], viaSegments: s3 = 8, preserveObstacleBoundaries: a3 = false } = e51, c3 = [], l3 = [], h3 = [], { minX: d3, maxX: u3, minY: p3, maxY: m3 } = t3, g3 = 10, f3 = [];\n for (let e53 = 0;e53 \u003c g3; e53++) {\n const t4 = e53 / g3;\n f3.push({ x: d3 + t4 * (u3 - d3), y: p3 });\n }\n for (let e53 = 0;e53 \u003c g3; e53++) {\n const t4 = e53 / g3;\n f3.push({ x: u3, y: p3 + t4 * (m3 - p3) });\n }\n for (let e53 = 0;e53 \u003c g3; e53++) {\n const t4 = e53 / g3;\n f3.push({ x: u3 - t4 * (u3 - d3), y: m3 });\n }\n for (let e53 = 0;e53 \u003c g3; e53++) {\n const t4 = e53 / g3;\n f3.push({ x: d3, y: m3 - t4 * (m3 - p3) });\n }\n h3.push(l3.length), g5(f3, c3, l3);\n const _3 = [];\n for (const e53 of n3) {\n const t4 = e53.diameter / 2 + o3, n4 = [];\n for (let o4 = 0;o4 \u003c s3; o4++) {\n const i4 = 2 * Math.PI * o4 / s3;\n n4.push({ x: e53.center.x + t4 * Math.cos(i4), y: e53.center.y + t4 * Math.sin(i4) });\n }\n _3.push(n4);\n }\n for (const e53 of i3) {\n const t4 = e53.width / 2 + o3, n4 = e53.height / 2 + o3, i4 = [u5({ localX: -t4, localY: -n4, rect: e53 }), u5({ localX: t4, localY: -n4, rect: e53 }), u5({ localX: t4, localY: n4, rect: e53 }), u5({ localX: -t4, localY: n4, rect: e53 })];\n _3.push(i4);\n }\n for (const e53 of r3) {\n if (e53.points.length \u003c 3)\n continue;\n const t4 = d5({ polygon: e53, clearance: o3, verticesOnly: true });\n _3.push(t4);\n }\n const y3 = a3 ? _3 : ((e53) =\u003e {\n if (e53.length \u003c= 1)\n return e53;\n try {\n let t4 = e53.map(p5);\n for (let e54 = 0;e54 \u003c 2; e54++) {\n const e55 = [], n6 = new Set;\n for (let o4 = 0;o4 \u003c t4.length; o4++) {\n if (n6.has(o4))\n continue;\n let i4 = t4[o4];\n for (let e56 = o4 + 1;e56 \u003c t4.length; e56++) {\n if (n6.has(e56))\n continue;\n const o6 = i4.box, r4 = t4[e56].box;\n if (!(o6.xmin \u003e r4.xmax + 0.000001 || o6.xmax \u003c r4.xmin - 0.000001 || o6.ymin \u003e r4.ymax + 0.000001 || o6.ymax \u003c r4.ymin - 0.000001))\n try {\n const o7 = e_.unify(i4, t4[e56]);\n o7.faces.size \u003e 0 \u0026\u0026 (i4 = o7, n6.add(e56));\n } catch {}\n }\n e55.push(i4), n6.add(o4);\n }\n t4 = e55;\n }\n const n4 = [];\n for (const e54 of t4) {\n const t6 = m5(e54);\n n4.push(...t6);\n }\n return n4.length \u003e 0 ? n4 : e53;\n } catch {\n return e53;\n }\n })(_3);\n for (const e53 of y3)\n h3.push(l3.length), g5(e53, c3, l3);\n const b3 = ((e53, t4, n4) =\u003e {\n const o4 = new Array(t4.length);\n for (let e54 = 0;e54 \u003c t4.length; e54++)\n for (let t6 = n4.length - 1;t6 \u003e= 0; t6--)\n if (e54 \u003e= n4[t6]) {\n o4[e54] = t6;\n break;\n }\n const i4 = new Map, r4 = e53.slice();\n for (let e54 = 0;e54 \u003c t4.length; e54++)\n for (let n6 = e54 + 1;n6 \u003c t4.length; n6++) {\n if (o4[e54] === o4[n6])\n continue;\n const [s6, a4] = t4[e54], [c4, l4] = t4[n6], h4 = r4[s6], d4 = r4[a4], u4 = r4[c4], p4 = r4[l4], m4 = d4.x - h4.x, g4 = d4.y - h4.y, f4 = p4.x - u4.x, _4 = p4.y - u4.y, y4 = m4 * _4 - g4 * f4;\n if (Math.abs(y4) \u003c 0.0000000001)\n continue;\n const b4 = ((u4.x - h4.x) * _4 - (u4.y - h4.y) * f4) / y4, x3 = ((u4.x - h4.x) * g4 - (u4.y - h4.y) * m4) / y4;\n if (b4 \u003e 0.000001 \u0026\u0026 b4 \u003c 0.999999 \u0026\u0026 x3 \u003e 0.000001 \u0026\u0026 x3 \u003c 0.999999) {\n const t6 = h4.x + b4 * m4, o6 = h4.y + b4 * g4, s7 = r4.length;\n r4.push({ x: t6, y: o6 }), i4.has(e54) || i4.set(e54, []), i4.get(e54).push({ t: b4, idx: s7 }), i4.has(n6) || i4.set(n6, []), i4.get(n6).push({ t: x3, idx: s7 });\n }\n }\n if (i4.size === 0)\n return { pts: e53, constraintEdges: t4, hadCrossings: false };\n const s4 = [];\n for (let e54 = 0;e54 \u003c t4.length; e54++) {\n const n6 = i4.get(e54);\n if (!n6 || n6.length === 0) {\n s4.push(t4[e54]);\n continue;\n }\n n6.sort((e55, t6) =\u003e e55.t - t6.t);\n const [o6, r6] = t4[e54];\n let a4 = o6;\n for (const e55 of n6)\n s4.push([a4, e55.idx]), a4 = e55.idx;\n s4.push([a4, r6]);\n }\n return { pts: r4, constraintEdges: s4, hadCrossings: true };\n })(c3, l3, h3);\n return { pts: b3.pts.map((e53, t4) =\u003e ({ x: e53.x + 0.000001 * (t4 % 7 - 3), y: e53.y + 0.000001 * (t4 % 5 - 2) })), constraintEdges: b3.constraintEdges, hadCrossings: b3.hadCrossings };\n};\nvar y5 = (e51) =\u003e {\n const { p: t3, a: n3, b: o3 } = e51, i3 = o3.x - n3.x, r3 = o3.y - n3.y, s3 = i3 * i3 + r3 * r3;\n if (s3 \u003c 0.0000000001)\n return Math.hypot(t3.x - n3.x, t3.y - n3.y);\n let a3 = ((t3.x - n3.x) * i3 + (t3.y - n3.y) * r3) / s3;\n return a3 = Math.max(0, Math.min(1, a3)), Math.hypot(t3.x - n3.x - a3 * i3, t3.y - n3.y - a3 * r3);\n};\nvar b5 = (e51, t3) =\u003e {\n if (e51.length \u003c= 3)\n return 0;\n const n3 = A2(e51, t3), o3 = new Set(n3), i3 = n3.map((e53) =\u003e t3[e53]).filter((e53) =\u003e Boolean(e53));\n let r3 = 0;\n for (const n4 of e51) {\n if (o3.has(n4))\n continue;\n const e53 = t3[n4];\n if (!e53)\n continue;\n let s3 = Number.POSITIVE_INFINITY;\n for (let t4 = 0;t4 \u003c i3.length; t4++) {\n const n6 = i3[t4], o4 = i3[(t4 + 1) % i3.length];\n n6 \u0026\u0026 o4 \u0026\u0026 (s3 = Math.min(s3, y5({ p: e53, a: n6, b: o4 })));\n }\n r3 = Math.max(r3, s3);\n }\n return r3;\n};\nvar x5 = (e51, t3) =\u003e e51 \u003c t3 ? 1e5 * e51 + t3 : 1e5 * t3 + e51;\nvar v5 = (e51, t3) =\u003e {\n const n3 = e51.map((t4, n4) =\u003e [t4, e51[(n4 + 1) % e51.length]]), o3 = t3.map((e53, n4) =\u003e [e53, t3[(n4 + 1) % t3.length]]), i3 = new Set;\n for (const [e53, t4] of n3)\n if (t4 !== undefined)\n for (const [n4, r4] of o3)\n r4 !== undefined \u0026\u0026 e53 === r4 \u0026\u0026 t4 === n4 \u0026\u0026 i3.add(x5(e53, t4));\n if (i3.size === 0)\n return null;\n const r3 = [];\n for (const [e53, t4] of n3)\n t4 !== undefined \u0026\u0026 (i3.has(x5(e53, t4)) || r3.push([e53, t4]));\n for (const [e53, t4] of o3)\n t4 !== undefined \u0026\u0026 (i3.has(x5(e53, t4)) || r3.push([e53, t4]));\n if (r3.length === 0)\n return null;\n const s3 = new Map;\n for (const [e53, t4] of r3)\n s3.set(e53, t4);\n const a3 = r3[0]?.[0];\n if (a3 === undefined)\n return null;\n const c3 = [a3];\n let l3 = s3.get(a3), h3 = 0;\n for (;l3 !== undefined \u0026\u0026 l3 !== a3 \u0026\u0026 h3++ \u003c r3.length + 5; )\n c3.push(l3), l3 = s3.get(l3);\n return l3 !== a3 || c3.length !== r3.length ? null : c3;\n};\nvar I5 = (e51, t3) =\u003e e51 \u003c t3 ? 1e5 * e51 + t3 : 1e5 * t3 + e51;\nvar S5 = (e51, t3) =\u003e e51 \u003c t3 ? 1e5 * e51 + t3 : 1e5 * t3 + e51;\nvar P5 = l(S(), 1);\nvar M5 = (e51) =\u003e {\n const { a: t3, b: n3, c: o3 } = e51, i3 = 2 * (t3.x * (n3.y - o3.y) + n3.x * (o3.y - t3.y) + o3.x * (t3.y - n3.y));\n if (Math.abs(i3) \u003c 0.0000000001)\n return { x: 0, y: 0, r2: 1000000000000000000 };\n const r3 = t3.x * t3.x + t3.y * t3.y, s3 = n3.x * n3.x + n3.y * n3.y, a3 = o3.x * o3.x + o3.y * o3.y, c3 = (r3 * (n3.y - o3.y) + s3 * (o3.y - t3.y) + a3 * (t3.y - n3.y)) / i3, l3 = (r3 * (o3.x - n3.x) + s3 * (t3.x - o3.x) + a3 * (n3.x - t3.x)) / i3;\n return { x: c3, y: l3, r2: (t3.x - c3) ** 2 + (t3.y - l3) ** 2 };\n};\nvar w5 = (e51, t3, n3) =\u003e [e51.a, e51.b, e51.c].includes(t3) \u0026\u0026 [e51.a, e51.b, e51.c].includes(n3);\nvar N5 = (e51) =\u003e {\n const { px: t3, py: n3, polygonPoints: o3, clearance: i3 } = e51;\n if (o3.length \u003c 3)\n return false;\n const r3 = o3.map((e53) =\u003e C_(e53.x, e53.y)), s3 = [];\n for (let e53 = 0;e53 \u003c r3.length; e53++) {\n const t4 = r3[e53], n4 = r3[(e53 + 1) % r3.length];\n s3.push(N_(t4, n4));\n }\n const a3 = new D_;\n a3.addFace(s3);\n const c3 = C_(t3, n3);\n if (a3.contains(c3))\n return true;\n const [l3] = a3.distanceTo(c3);\n return l3 \u003c i3 - 0.1;\n};\nvar R5 = (e51) =\u003e {\n const { point: t3, via: n3, clearance: o3 } = e51, i3 = t3.x - n3.center.x, r3 = t3.y - n3.center.y, s3 = n3.diameter / 2 + o3;\n return i3 * i3 + r3 * r3 \u003c= s3 * s3 + 0.000000001;\n};\nvar T5 = (e51) =\u003e {\n const { point: t3, rect: n3, clearance: o3 } = e51, i3 = Math.cos(-n3.ccwRotation), r3 = Math.sin(-n3.ccwRotation), s3 = t3.x - n3.center.x, a3 = t3.y - n3.center.y, c3 = s3 * i3 - a3 * r3, l3 = s3 * r3 + a3 * i3;\n return Math.abs(c3) \u003c= n3.width / 2 + o3 + 0.000000001 \u0026\u0026 Math.abs(l3) \u003c= n3.height / 2 + o3 + 0.000000001;\n};\nvar E5 = (e51) =\u003e N5({ px: e51.point.x, py: e51.point.y, polygonPoints: e51.polygon.points, clearance: e51.clearance });\nvar A5 = (e51, t3) =\u003e e51.x \u003e= t3.minX - 0.000000001 \u0026\u0026 e51.x \u003c= t3.maxX + 0.000000001 \u0026\u0026 e51.y \u003e= t3.minY - 0.000000001 \u0026\u0026 e51.y \u003c= t3.maxY + 0.000000001;\nvar O5 = (e51) =\u003e {\n const { point: t3, vias: n3, rects: o3, polygons: i3, clearance: r3, layerCount: s3 } = e51;\n let a3 = 0;\n for (const e53 of n3)\n R5({ point: t3, via: e53, clearance: r3 }) \u0026\u0026 (a3 |= z2(e53, s3));\n for (const e53 of o3)\n T5({ point: t3, rect: e53, clearance: r3 }) \u0026\u0026 (a3 |= z2(e53, s3));\n for (const e53 of i3)\n E5({ point: t3, polygon: e53, clearance: r3 }) \u0026\u0026 (a3 |= z2(e53, s3));\n return a3;\n};\nvar k5 = (e51) =\u003e {\n const { triangles: t3, pts: n3, bounds: o3, vias: i3, clearance: r3, rects: s3, polygons: a3, layerCount: c3 } = e51, l3 = O2(c3), h3 = [], d3 = [];\n for (const [e53, u3, p3] of t3) {\n const t4 = n3[e53], m3 = n3[u3], g3 = n3[p3];\n if (!t4 || !m3 || !g3)\n continue;\n const f3 = { x: (t4.x + m3.x + g3.x) / 3, y: (t4.y + m3.y + g3.y) / 3 };\n if (!A5(f3, o3))\n continue;\n const _3 = l3 \u0026 ~O5({ point: f3, vias: i3, rects: s3, polygons: a3, clearance: r3, layerCount: c3 });\n _3 !== 0 \u0026\u0026 (h3.push([e53, u3, p3]), d3.push(k2(_3, c3)));\n }\n return { triangles: h3, triangleAvailableZ: d3 };\n};\nvar D5 = (e51) =\u003e {\n const { triangles: t3, pts: n3, bounds: o3, vias: i3, clearance: r3, rects: s3, polygons: a3 } = e51;\n return t3.filter(([e53, t4, c3]) =\u003e {\n const l3 = n3[e53], h3 = n3[t4], d3 = n3[c3];\n if (!l3 || !h3 || !d3)\n return false;\n if (!((e54) =\u003e {\n const { px: t6, py: n4, bounds: o4, vias: i4, clearance: r4, rects: s4, polygons: a4 } = e54, { minX: c4, maxX: l4, minY: h4, maxY: d4 } = o4, u3 = 0.000001 * Math.max(l4 - c4, d4 - h4, 1);\n if (t6 \u003c c4 - u3 || t6 \u003e l4 + u3 || n4 \u003c h4 - u3 || n4 \u003e d4 + u3)\n return false;\n for (const e55 of i4) {\n const o6 = e55.diameter / 2 + r4, i6 = Math.max(0, o6 - u3);\n if ((t6 - e55.center.x) ** 2 + (n4 - e55.center.y) ** 2 \u003c i6 * i6)\n return false;\n }\n for (const e55 of s4) {\n const o6 = e55.width / 2 + r4, i6 = e55.height / 2 + r4, s6 = Math.max(0, o6 - u3), a6 = Math.max(0, i6 - u3), c5 = t6 - e55.center.x, l5 = n4 - e55.center.y, h5 = Math.cos(e55.ccwRotation), d6 = Math.sin(e55.ccwRotation), p3 = c5 * h5 + l5 * d6, m3 = -c5 * d6 + l5 * h5;\n if (Math.abs(p3) \u003c s6 \u0026\u0026 Math.abs(m3) \u003c a6)\n return false;\n }\n for (const e55 of a4)\n if (N5({ px: t6, py: n4, polygonPoints: e55.points, clearance: r4 }))\n return false;\n return true;\n })({ px: (l3.x + h3.x + d3.x) / 3, py: (l3.y + h3.y + d3.y) / 3, bounds: o3, vias: i3, clearance: r3, rects: s3, polygons: a3 }))\n return false;\n if (a3.length \u003e 0) {\n const e54 = [l3, h3, d3, { x: (l3.x + h3.x) / 2, y: (l3.y + h3.y) / 2 }, { x: (h3.x + d3.x) / 2, y: (h3.y + d3.y) / 2 }, { x: (d3.x + l3.x) / 2, y: (d3.y + l3.y) / 2 }];\n for (const t6 of e54)\n for (const e55 of a3)\n if (N5({ px: t6.x, py: t6.y, polygonPoints: e55.points, clearance: r3 }))\n return false;\n }\n return true;\n });\n};\nvar L5 = (e51) =\u003e e51 !== undefined;\nvar z5 = (e51) =\u003e {\n const { bounds: t3, clearance: n3, concavityTolerance: o3 } = e51, i3 = e51.vias ?? [], r3 = e51.rects ?? [], s3 = e51.polygons ?? [];\n let a3, c3, l3;\n if (e51.useConstrainedDelaunay !== false) {\n const o4 = f5({ bounds: t3, vias: i3, clearance: n3, rects: r3, polygons: s3, viaSegments: e51.viaSegments, preserveObstacleBoundaries: e51.layerCount !== undefined });\n a3 = o4.pts;\n const h4 = ((e53, t4, n4 = {}) =\u003e {\n const o6 = e53.map((e54) =\u003e [e54.x, e54.y]);\n return (0, P5.default)(o6, t4, { exterior: !!n4.includeConstraintInteriors });\n })(a3, o4.constraintEdges, { includeConstraintInteriors: e51.layerCount !== undefined });\n if (e51.layerCount !== undefined) {\n const o6 = k5({ triangles: h4, pts: a3, bounds: t3, vias: i3, clearance: n3, rects: r3, polygons: s3, layerCount: e51.layerCount });\n c3 = o6.triangles, l3 = o6.triangleAvailableZ;\n } else {\n c3 = i3.length \u003e 0 || r3.length \u003e 0 || s3.length \u003e 0 ? D5({ triangles: h4, pts: a3, bounds: t3, vias: i3, clearance: n3, rects: r3, polygons: s3 }) : h4;\n }\n } else {\n a3 = ((e53) =\u003e {\n const { bounds: t4, vias: n4, clearance: o6, rects: i4, polygons: r4 = [], viaSegments: s4 = 24 } = e53, a4 = [], { minX: c4, maxX: l4, minY: h4, maxY: d4 } = t4;\n a4.push({ x: c4, y: h4 }, { x: l4, y: h4 }, { x: l4, y: d4 }, { x: c4, y: d4 });\n for (let e54 = 1;e54 \u003c 10; e54++) {\n const t6 = e54 / 10;\n a4.push({ x: c4 + t6 * (l4 - c4), y: h4 }), a4.push({ x: l4, y: h4 + t6 * (d4 - h4) }), a4.push({ x: l4 - t6 * (l4 - c4), y: d4 }), a4.push({ x: c4, y: d4 - t6 * (d4 - h4) });\n }\n for (const e54 of n4) {\n const t6 = e54.diameter / 2 + o6;\n for (let n6 = 0;n6 \u003c s4; n6++) {\n const o7 = 2 * Math.PI * n6 / s4;\n a4.push({ x: e54.center.x + t6 * Math.cos(o7), y: e54.center.y + t6 * Math.sin(o7) });\n }\n }\n for (const e54 of i4) {\n const t6 = e54.width / 2 + o6, n6 = e54.height / 2 + o6, i6 = Math.max(2, Math.ceil(Math.max(2 * t6, 2 * n6) / 20));\n for (let o7 = 0;o7 \u003c i6; o7++) {\n const r6 = o7 / i6;\n a4.push(u5({ localX: 2 * r6 * t6 - t6, localY: -n6, rect: e54 })), a4.push(u5({ localX: t6, localY: 2 * r6 * n6 - n6, rect: e54 })), a4.push(u5({ localX: t6 - 2 * r6 * t6, localY: n6, rect: e54 })), a4.push(u5({ localX: -t6, localY: n6 - 2 * r6 * n6, rect: e54 }));\n }\n }\n for (const e54 of r4) {\n if (e54.points.length \u003c 3)\n continue;\n const t6 = d5({ polygon: e54, clearance: o6 });\n a4.push(...t6);\n }\n return a4.map((e54, t6) =\u003e ({ x: e54.x + 0.000001 * (t6 % 7 - 3), y: e54.y + 0.000001 * (t6 % 5 - 2) }));\n })({ bounds: t3, vias: i3, clearance: n3, rects: r3, polygons: s3, viaSegments: e51.viaSegments });\n const o4 = ((e53) =\u003e {\n const t4 = e53.map((e54, t6) =\u003e ({ ...e54, i: t6 }));\n if (t4.length \u003c 3)\n return [];\n let { POSITIVE_INFINITY: n4, POSITIVE_INFINITY: o6, NEGATIVE_INFINITY: i4, NEGATIVE_INFINITY: r4 } = Number;\n for (const e54 of t4)\n n4 = Math.min(n4, e54.x), o6 = Math.min(o6, e54.y), i4 = Math.max(i4, e54.x), r4 = Math.max(r4, e54.y);\n const s4 = Math.max(i4 - n4, r4 - o6) || 1, a4 = (n4 + i4) / 2, c4 = (o6 + r4) / 2, l4 = { x: a4 - 30 * s4, y: c4 - s4, i: -1 }, h4 = { x: a4, y: c4 + 30 * s4, i: -2 }, d4 = { x: a4 + 30 * s4, y: c4 - s4, i: -3 };\n let u4 = [{ a: l4, b: h4, c: d4, cc: M5({ a: l4, b: h4, c: d4 }) }];\n for (const e54 of t4) {\n const t6 = u4.filter((t7) =\u003e {\n const n7 = e54.x - t7.cc.x, o8 = e54.y - t7.cc.y;\n return n7 * n7 + o8 * o8 \u003c t7.cc.r2 + 0.000001;\n }), n6 = new Set(t6), o7 = [];\n for (const e55 of t6) {\n const n7 = [[e55.a, e55.b], [e55.b, e55.c], [e55.c, e55.a]];\n for (const [i6, r6] of n7) {\n let n8 = false;\n for (const o8 of t6)\n if (o8 !== e55 \u0026\u0026 w5(o8, i6, r6)) {\n n8 = true;\n break;\n }\n n8 || o7.push([i6, r6]);\n }\n }\n u4 = u4.filter((e55) =\u003e !n6.has(e55));\n for (const [t7, n7] of o7)\n u4.push({ a: t7, b: n7, c: e54, cc: M5({ a: t7, b: n7, c: e54 }) });\n }\n return u4.filter((e54) =\u003e e54.a.i \u003e= 0 \u0026\u0026 e54.b.i \u003e= 0 \u0026\u0026 e54.c.i \u003e= 0).map((e54) =\u003e [e54.a.i, e54.b.i, e54.c.i]);\n })(a3);\n if (e51.layerCount !== undefined) {\n const h4 = k5({ triangles: o4, pts: a3, bounds: t3, vias: i3, clearance: n3, rects: r3, polygons: s3, layerCount: e51.layerCount });\n c3 = h4.triangles, l3 = h4.triangleAvailableZ;\n } else\n c3 = D5({ triangles: o4, pts: a3, bounds: t3, vias: i3, clearance: n3, rects: r3, polygons: s3 });\n }\n const { cells: h3, depths: d3, availableZ: u3 } = e51.usePolyanyaMerge !== false ? ((e53) =\u003e {\n const { triangles: t4, pts: n4, cellAvailableZ: o4, layerMergeMode: i4 = \"same\" } = e53;\n if (!t4.length)\n return { cells: [], depths: [] };\n const r4 = t4.length, s4 = t4.map(([e54, t6, o6]) =\u003e {\n const i6 = n4[e54], r6 = n4[t6], s6 = n4[o6];\n return i6 \u0026\u0026 r6 \u0026\u0026 s6 \u0026\u0026 E22({ o: i6, a: r6, b: s6 }) \u003c 0 ? [e54, o6, t6] : [e54, t6, o6];\n }), a4 = o4?.map(D2), c4 = new Array(r4).fill(null);\n for (let e54 = 0;e54 \u003c r4; e54++)\n c4[e54] = new Map;\n function l4() {\n for (let e55 = 0;e55 \u003c c4.length; e55++)\n c4[e55] \u0026\u0026 c4[e55].clear();\n const e54 = new Map;\n for (let t6 = 0;t6 \u003c s4.length; t6++) {\n const n6 = s4[t6];\n if (n6)\n for (let o6 = 0;o6 \u003c n6.length; o6++) {\n const i6 = n6[o6], r6 = n6[(o6 + 1) % n6.length], s6 = S5(i6, r6), a6 = e54.get(s6);\n a6 ? (c4[t6].set(o6, { neighbor: a6.cellIdx, neighborEdge: a6.edgePos }), c4[a6.cellIdx].set(a6.edgePos, { neighbor: t6, neighborEdge: o6 })) : e54.set(s6, { cellIdx: t6, edgePos: o6 });\n }\n }\n }\n function h4(e54) {\n let t6 = 0;\n for (let o6 = 0;o6 \u003c e54.length; o6++) {\n const i6 = n4[e54[o6]], r6 = n4[e54[(o6 + 1) % e54.length]];\n t6 += i6.x * r6.y - r6.x * i6.y;\n }\n return Math.abs(t6) / 2;\n }\n function d4(e54, t6) {\n const n6 = s4[e54], o6 = c4[e54], i6 = n6.length;\n let r6 = -1;\n for (const [e55, n7] of o6)\n if (n7.neighbor === t6) {\n r6 = e55;\n break;\n }\n if (r6 === -1)\n return null;\n let a6 = r6;\n for (;; ) {\n const e55 = (a6 - 1 + i6) % i6;\n if (e55 === r6)\n break;\n const n7 = o6.get(e55);\n if (!n7 || n7.neighbor !== t6)\n break;\n a6 = e55;\n }\n let l5 = r6;\n for (;; ) {\n const e55 = (l5 + 1) % i6;\n if (e55 === a6)\n break;\n const n7 = o6.get(e55);\n if (!n7 || n7.neighbor !== t6)\n break;\n l5 = e55;\n }\n return { firstK: a6, lastK: l5, sharedCount: (l5 - a6 + i6) % i6 + 1 };\n }\n function u4(e54, t6) {\n const o6 = s4[e54], r6 = s4[t6], c5 = d4(e54, t6);\n if (!c5)\n return false;\n const { firstK: l5, lastK: h5, sharedCount: u6 } = c5, p6 = o6.length, m6 = r6.length, g6 = o6[l5], f4 = o6[(h5 + 1) % p6];\n let _4 = -1;\n for (let e55 = 0;e55 \u003c m6; e55++)\n if (r6[e55] === g6) {\n _4 = e55;\n break;\n }\n if (_4 === -1)\n return false;\n const y4 = (_4 - u6 + m6) % m6;\n if (r6[y4] !== f4)\n return false;\n const b4 = n4[o6[(l5 - 1 + p6) % p6]], x4 = n4[g6], v4 = n4[r6[(_4 + 1) % m6]];\n if (E22({ o: b4, a: x4, b: v4 }) \u003c -0.00000001)\n return false;\n const I4 = n4[r6[(y4 - 1 + m6) % m6]], S3 = n4[f4], C = n4[o6[(h5 + 2) % p6]];\n if (E22({ o: I4, a: S3, b: C }) \u003c -0.00000001)\n return false;\n if (a4) {\n if ((a4[e54] \u0026 a4[t6]) === 0)\n return false;\n if (i4 === \"same\" \u0026\u0026 a4[e54] !== a4[t6])\n return false;\n }\n return true;\n }\n function p4(e54, t6) {\n const n6 = s4[e54], o6 = s4[t6], i6 = d4(e54, t6), { firstK: r6, lastK: c5, sharedCount: l5 } = i6, h5 = n6.length, u6 = o6.length, p6 = n6[r6], m6 = n6[(c5 + 1) % h5];\n let g6 = -1;\n for (let e55 = 0;e55 \u003c u6; e55++)\n if (o6[e55] === p6) {\n g6 = e55;\n break;\n }\n const f4 = [];\n f4.push(p6);\n const _4 = u6 - l5 - 1;\n for (let e55 = 1;e55 \u003c= _4; e55++)\n f4.push(o6[(g6 + e55) % u6]);\n f4.push(m6);\n const y4 = h5 - l5 - 1;\n for (let e55 = 2;e55 \u003c= y4 + 1; e55++)\n f4.push(n6[(c5 + e55) % h5]);\n s4[e54] = f4, s4[t6] = null, a4 \u0026\u0026 (a4[e54] = a4[e54] \u0026 a4[t6], a4[t6] = 0);\n }\n l4();\n let m4 = true;\n for (;m4; ) {\n m4 = false, l4();\n for (let e54 = 0;e54 \u003c s4.length; e54++) {\n if (!s4[e54])\n continue;\n const t6 = c4[e54], n6 = new Set;\n for (const [, e55] of t6)\n s4[e55.neighbor] \u0026\u0026 n6.add(e55.neighbor);\n if (n6.size === 1) {\n const t7 = n6.values().next().value;\n u4(e54, t7) \u0026\u0026 (p4(e54, t7), m4 = true);\n }\n }\n }\n l4();\n const g4 = new Array(s4.length).fill(0);\n for (let e54 = 0;e54 \u003c s4.length; e54++)\n s4[e54] \u0026\u0026 (g4[e54] = h4(s4[e54]));\n const f3 = [];\n function _3(e54) {\n f3.push(e54);\n let t6 = f3.length - 1;\n for (;t6 \u003e 0; ) {\n const e55 = t6 - 1 \u003e\u003e 1;\n if (f3[e55].area \u003e= f3[t6].area)\n break;\n const n6 = f3[e55];\n f3[e55] = f3[t6], f3[t6] = n6, t6 = e55;\n }\n }\n function y3() {\n if (f3.length === 0)\n return;\n const e54 = f3[0], t6 = f3.pop();\n if (f3.length \u003e 0) {\n f3[0] = t6;\n let e55 = 0;\n for (;; ) {\n let t7 = e55;\n const n6 = 2 * e55 + 1, o6 = 2 * e55 + 2;\n if (n6 \u003c f3.length \u0026\u0026 f3[n6].area \u003e f3[t7].area \u0026\u0026 (t7 = n6), o6 \u003c f3.length \u0026\u0026 f3[o6].area \u003e f3[t7].area \u0026\u0026 (t7 = o6), t7 === e55)\n break;\n const i6 = f3[e55];\n f3[e55] = f3[t7], f3[t7] = i6, e55 = t7;\n }\n }\n return e54;\n }\n const b3 = new Set;\n for (let e54 = 0;e54 \u003c s4.length; e54++) {\n if (!s4[e54])\n continue;\n const t6 = c4[e54], n6 = new Set;\n for (const [, e55] of t6)\n s4[e55.neighbor] \u0026\u0026 n6.add(e55.neighbor);\n for (const t7 of n6) {\n const n7 = e54 \u003c t7 ? 1e5 * e54 + t7 : 1e5 * t7 + e54;\n b3.has(n7) || (b3.add(n7), u4(e54, t7) \u0026\u0026 _3({ area: g4[e54] + g4[t7], xIdx: e54, yIdx: t7 }));\n }\n }\n for (;f3.length \u003e 0; ) {\n const e54 = y3(), { xIdx: t6, yIdx: n6 } = e54;\n if (!s4[t6] || !s4[n6])\n continue;\n const o6 = g4[t6] + g4[n6];\n if (Math.abs(o6 - e54.area) \u003e 0.0000000001) {\n u4(t6, n6) \u0026\u0026 _3({ area: o6, xIdx: t6, yIdx: n6 });\n continue;\n }\n if (!u4(t6, n6))\n continue;\n p4(t6, n6), g4[t6] = h4(s4[t6]), l4();\n const i6 = c4[t6], r6 = new Set;\n for (const [, e55] of i6)\n s4[e55.neighbor] \u0026\u0026 r6.add(e55.neighbor);\n for (const e55 of r6)\n u4(t6, e55) \u0026\u0026 _3({ area: g4[t6] + g4[e55], xIdx: t6, yIdx: e55 });\n }\n const x3 = s4.filter((e54) =\u003e e54 !== null), v3 = a4 ? s4.flatMap((e54, t6) =\u003e e54 === null ? [] : [k2(a4[t6])]) : undefined, I3 = x3.map(() =\u003e 0);\n return { cells: x3, depths: I3, ...v3 ? { availableZ: v3 } : {} };\n })({ triangles: c3, pts: a3, cellAvailableZ: l3, layerMergeMode: e51.layerMergeMode }) : ((e53) =\u003e {\n const { triangles: t4, pts: n4, concavityTolerance: o4, cellAvailableZ: i4, layerMergeMode: r4 = \"same\" } = e53;\n if (!t4.length)\n return { cells: [], depths: [] };\n const s4 = t4.map(([e54, t6, o6]) =\u003e {\n const i6 = n4[e54], r6 = n4[t6], s6 = n4[o6];\n return i6 \u0026\u0026 r6 \u0026\u0026 s6 \u0026\u0026 E22({ o: i6, a: r6, b: s6 }) \u003c 0 ? [e54, o6, t6] : [e54, t6, o6];\n }), a4 = i4?.map(D2), c4 = (e54, t6) =\u003e {\n if (!a4)\n return;\n const n6 = a4[e54] \u0026 a4[t6];\n return n6 === 0 || r4 === \"same\" \u0026\u0026 a4[e54] !== a4[t6] ? 0 : n6;\n };\n let l4 = true, h4 = 0;\n for (;l4 \u0026\u0026 h4++ \u003c 800; ) {\n l4 = false;\n const e54 = new Map, t6 = s4.map(() =\u003e new Set);\n for (let n6 = 0;n6 \u003c s4.length; n6++) {\n const o6 = s4[n6];\n if (o6)\n for (let i7 = 0;i7 \u003c o6.length; i7++) {\n const r7 = o6[i7], s6 = o6[(i7 + 1) % o6.length];\n if (r7 === undefined || s6 === undefined)\n continue;\n const a6 = I5(r7, s6);\n if (e54.has(a6)) {\n const o7 = e54.get(a6);\n o7 !== undefined \u0026\u0026 (t6[n6]?.add(o7), t6[o7]?.add(n6));\n } else\n e54.set(a6, n6);\n }\n }\n let i6 = -1, r6 = -1, h5 = null, d6 = Number.POSITIVE_INFINITY;\n for (let e55 = 0;e55 \u003c s4.length; e55++) {\n const a6 = t6[e55];\n if (a6)\n for (const t7 of a6) {\n if (t7 \u003c= e55)\n continue;\n const a7 = v5(s4[e55] ?? [], s4[t7] ?? []);\n if (!a7)\n continue;\n if (c4(e55, t7) === 0)\n continue;\n const l5 = b5(a7, n4);\n l5 \u003c= o4 + 0.000001 \u0026\u0026 l5 \u003c d6 \u0026\u0026 (d6 = l5, i6 = e55, r6 = t7, h5 = a7);\n }\n }\n if (i6 \u003c 0 || r6 \u003c 0 || !h5)\n break;\n s4[i6] = h5, a4 \u0026\u0026 (a4[i6] = c4(i6, r6), a4.splice(r6, 1)), s4.splice(r6, 1), l4 = true;\n }\n const d4 = s4.map((e54) =\u003e b5(e54, n4));\n return { cells: s4, depths: d4, ...a4 ? { availableZ: a4.map((e54) =\u003e k2(e54)) } : {} };\n })({ triangles: c3, pts: a3, concavityTolerance: o3, cellAvailableZ: l3, layerMergeMode: e51.layerMergeMode }), p3 = a3.map((e53) =\u003e ((e54, t4) =\u003e ({ x: Math.min(t4.maxX, Math.max(t4.minX, e54.x)), y: Math.min(t4.maxY, Math.max(t4.minY, e54.y)) }))(e53, t3)), m3 = h3.map((e53) =\u003e e53.map((e54) =\u003e p3[e54]).filter(L5)), g3 = h3.map((e53) =\u003e A2(e53, p3).map((e54) =\u003e p3[e54]).filter(L5));\n return { pts: p3, validTris: c3, regions: m3, hulls: g3, depths: d3, ...u3 ? { availableZ: u3 } : {} };\n};\nvar F5 = (e51) =\u003e {\n const t3 = [...new Set(e51.filter((e53) =\u003e typeof e53 == \"number\" \u0026\u0026 Number.isInteger(e53) \u0026\u0026 e53 \u003e= 0))].sort((e53, t4) =\u003e e53 - t4);\n if (t3.length !== 0)\n return `z${t3.join(\",\")}`;\n};\nvar j5 = (e51) =\u003e {\n const t3 = [];\n for (let n3 = 0;n3 \u003c 31; n3++)\n e51 \u0026 1 \u003c\u003c n3 \u0026\u0026 t3.push(n3);\n return t3;\n};\nvar $5 = (e51) =\u003e typeof e51 == \"object\" \u0026\u0026 e51 !== null;\nvar Y5 = (e51) =\u003e $5(e51) ? { ...e51 } : e51 === undefined ? {} : { value: e51 };\nvar X5 = (e51, t3) =\u003e {\n const n3 = e51.topology.regionMetadata?.[t3];\n if ($5(n3)) {\n if (typeof n3.serializedRegionId == \"string\")\n return n3.serializedRegionId;\n if (typeof n3.regionId == \"string\")\n return n3.regionId;\n if (typeof n3.capacityMeshNodeId == \"string\")\n return n3.capacityMeshNodeId;\n }\n return `region-${t3}`;\n};\nvar H5 = (e51, t3) =\u003e {\n const n3 = e51.topology.portMetadata?.[t3];\n if ($5(n3)) {\n if (typeof n3.serializedPortId == \"string\")\n return n3.serializedPortId;\n if (typeof n3.portId == \"string\")\n return (o3 = n3.portId).includes(\"::\") ? o3.slice(0, o3.indexOf(\"::\")) : o3;\n }\n var o3;\n return `port-${t3}`;\n};\nvar V5 = (e51, t3) =\u003e {\n const n3 = Y5(e51.topology.regionMetadata?.[t3]);\n if ($5(n3.center) || (n3.center = { x: e51.topology.regionCenterX[t3], y: e51.topology.regionCenterY[t3] }), typeof n3.width != \"number\" \u0026\u0026 (n3.width = e51.topology.regionWidth[t3]), typeof n3.height != \"number\" \u0026\u0026 (n3.height = e51.topology.regionHeight[t3]), !Array.isArray(n3.availableZ)) {\n const o3 = e51.topology.regionAvailableZMask?.[t3] ?? 0;\n o3 !== 0 \u0026\u0026 (n3.availableZ = j5(o3));\n }\n return n3.layer = F5(Array.isArray(n3.availableZ) ? n3.availableZ : []) ?? F5((e51.topology.regionIncidentPorts[t3] ?? []).map((t4) =\u003e e51.topology.portZ[t4])) ?? \"z0\", n3;\n};\nvar W5 = (e51, t3) =\u003e {\n const n3 = Y5(e51.topology.portMetadata?.[t3]);\n return typeof n3.x != \"number\" \u0026\u0026 (n3.x = e51.topology.portX[t3]), typeof n3.y != \"number\" \u0026\u0026 (n3.y = e51.topology.portY[t3]), typeof n3.z != \"number\" \u0026\u0026 (n3.z = e51.topology.portZ[t3]), n3.layer = F5([e51.topology.portZ[t3]]) ?? \"z0\", n3;\n};\nvar G5 = (e51, t3, n3) =\u003e {\n const o3 = (e51.topology.incidentPortRegion[t3] ?? []).find((e53) =\u003e e53 !== n3);\n if (o3 === undefined)\n throw new Error(`Port ${t3} is not incident to a region outside route region ${n3}`);\n return o3;\n};\nvar U5 = (e51, t3, n3) =\u003e {\n const { orderedPortIds: o3, orderedRegionIds: i3 } = ((e53, t4, n4) =\u003e {\n if (n4.length === 0)\n throw new Error(`Route ${t4} has no solved segments`);\n const o4 = e53.problem.routeStartPort[t4], i4 = e53.problem.routeEndPort[t4], r4 = new Map;\n n4.forEach((e54, t6) =\u003e {\n const n6 = { ...e54, segmentIndex: t6 }, o6 = r4.get(e54.fromPortId) ?? [];\n o6.push(n6), r4.set(e54.fromPortId, o6);\n const i6 = r4.get(e54.toPortId) ?? [];\n i6.push(n6), r4.set(e54.toPortId, i6);\n });\n const s4 = [o4], a4 = [], c4 = new Set;\n let l4, h4 = o4;\n for (;h4 !== i4; ) {\n const e54 = (r4.get(h4) ?? []).filter((e55) =\u003e !c4.has(e55.segmentIndex) \u0026\u0026 (e55.fromPortId === h4 ? e55.toPortId : e55.fromPortId) !== l4);\n if (e54.length !== 1)\n throw new Error(`Route ${t4} is not a single ordered path from ${o4} to ${i4}`);\n const n6 = e54[0], d3 = n6.fromPortId === h4 ? n6.toPortId : n6.fromPortId;\n c4.add(n6.segmentIndex), a4.push(n6.regionId), s4.push(d3), l4 = h4, h4 = d3;\n }\n if (c4.size !== n4.length)\n throw new Error(`Route ${t4} contains disconnected solved segments`);\n return { orderedPortIds: s4, orderedRegionIds: a4 };\n })(e51, t3, n3), r3 = i3[0], s3 = i3[i3.length - 1];\n if (r3 === undefined || s3 === undefined)\n throw new Error(`Route ${t3} could not determine endpoint regions`);\n const a3 = X5(e51, G5(e51, o3[0], r3)), c3 = X5(e51, G5(e51, o3[o3.length - 1], s3)), l3 = ((e53, t4, n4, o4) =\u003e {\n const i4 = e53.problem.routeMetadata?.[t4];\n return { connectionId: ($5(i4) \u0026\u0026 typeof i4.connectionId == \"string\" ? i4.connectionId : undefined) ?? `route-${t4}`, startRegionId: ($5(i4) \u0026\u0026 typeof i4.startRegionId == \"string\" ? i4.startRegionId : undefined) ?? n4, endRegionId: ($5(i4) \u0026\u0026 typeof i4.endRegionId == \"string\" ? i4.endRegionId : undefined) ?? o4, mutuallyConnectedNetworkId: ($5(i4) \u0026\u0026 typeof i4.mutuallyConnectedNetworkId == \"string\" ? i4.mutuallyConnectedNetworkId : undefined) ?? `net-${e53.problem.routeNet[t4]}` };\n })(e51, t3, a3, c3), h3 = o3.map((t4, n4) =\u003e {\n const r4 = { portId: H5(e51, t4), g: n4, h: 0, f: n4, hops: n4, ripRequired: false, nextRegionId: n4 \u003c i3.length ? X5(e51, i3[n4]) : l3.endRegionId };\n return n4 \u003e 0 \u0026\u0026 (r4.lastPortId = H5(e51, o3[n4 - 1]), r4.lastRegionId = X5(e51, i3[n4 - 1])), r4;\n });\n return { connection: l3, solvedRoute: { connection: l3, path: h3, requiredRip: false } };\n};\nvar Z5 = (e51) =\u003e {\n if (!e51.solved || e51.failed)\n throw new Error(\"convertToSerializedHyperGraph requires a solved, non-failed solver\");\n const { topology: t3 } = e51, n3 = ((e53) =\u003e {\n const t4 = Array.from({ length: e53.problem.routeCount }, () =\u003e []);\n return e53.state.regionSegments.forEach((e54, n4) =\u003e {\n for (const [o4, i4, r4] of e54)\n t4[o4].push({ regionId: n4, fromPortId: i4, toPortId: r4 });\n }), t4;\n })(e51), o3 = Array.from({ length: t3.regionCount }, (n4, o4) =\u003e ({ regionId: X5(e51, o4), pointIds: t3.regionIncidentPorts[o4].map((t4) =\u003e H5(e51, t4)), d: V5(e51, o4) })), i3 = Array.from({ length: t3.portCount }, (n4, o4) =\u003e {\n const [i4, r4] = t3.incidentPortRegion[o4] ?? [];\n if (i4 === undefined || r4 === undefined)\n throw new Error(`Port ${o4} is missing incident regions`);\n return { portId: H5(e51, o4), region1Id: X5(e51, i4), region2Id: X5(e51, r4), d: W5(e51, o4) };\n }), r3 = n3.map((t4, n4) =\u003e U5(e51, n4, t4));\n return { regions: o3, ports: i3, connections: r3.map(({ connection: e53 }) =\u003e e53), solvedRoutes: r3.map(({ solvedRoute: e53 }) =\u003e e53) };\n};\nvar q5 = (e51) =\u003e e51 \u003e 0 \u0026\u0026 !(e51 \u0026 e51 - 1);\nvar J5 = (e51, t3, n3, o3, i3, r3 = 0) =\u003e 0.2025 * (2 * t3 + 1 * n3 + 1 * o3) * (1 + i3 / 5) / e51 + (q5(r3) ? 10 * t3 : 0);\nvar Q5 = (e51, t3, n3, o3, i3, r3) =\u003e {\n const { netIds: s3, lesserAngles: a3, greaterAngles: c3, layerMasks: l3 } = e51;\n let h3 = 0, d3 = 0;\n for (let e53 = 0;e53 \u003c s3.length; e53++) {\n if (t3 === s3[e53])\n continue;\n (n3 \u003c a3[e53] \u0026\u0026 a3[e53] \u003c o3) !== (n3 \u003c c3[e53] \u0026\u0026 c3[e53] \u003c o3) \u0026\u0026 ((i3 \u0026 l3[e53]) !== 0 ? h3++ : d3++);\n }\n return [h3, d3, r3];\n};\nvar K5 = class {\n constructor(e51, t3) {\n this.items = e51, this.compare = t3;\n }\n get length() {\n return this.items.length;\n }\n toArray() {\n return [...this.items];\n }\n clear() {\n this.items.length = 0;\n }\n queue(e51) {\n this.items.push(e51), this.siftUp(this.items.length - 1);\n }\n dequeue() {\n const e51 = this.items[0];\n if (e51 === undefined)\n return;\n const t3 = this.items.pop();\n return this.items.length \u003e 0 \u0026\u0026 (this.items[0] = t3, this.siftDown(0)), e51;\n }\n siftUp(e51) {\n let t3 = e51;\n for (;t3 \u003e 0; ) {\n const e53 = t3 - 1 \u003e\u003e 1, n3 = this.items[e53], o3 = this.items[t3];\n if (this.compare(n3, o3) \u003c= 0)\n return;\n this.items[e53] = o3, this.items[t3] = n3, t3 = e53;\n }\n }\n siftDown(e51) {\n let t3 = e51;\n const n3 = this.items.length;\n for (;; ) {\n const e53 = 2 * t3 + 1;\n if (e53 \u003e= n3)\n return;\n const o3 = e53 + 1;\n let i3 = e53;\n o3 \u003c n3 \u0026\u0026 this.compare(this.items[o3], this.items[e53]) \u003c 0 \u0026\u0026 (i3 = o3);\n const r3 = this.items[t3], s3 = this.items[i3];\n if (this.compare(r3, s3) \u003c= 0)\n return;\n this.items[t3] = s3, this.items[i3] = r3, t3 = i3;\n }\n }\n};\nvar e310 = (e51, t3) =\u003e {\n const n3 = [...e51], o3 = ((e53) =\u003e {\n let t4 = e53 \u003e\u003e\u003e 0;\n return () =\u003e {\n t4 += 1831565813;\n let e54 = t4;\n return e54 = Math.imul(e54 ^ e54 \u003e\u003e\u003e 15, 1 | e54), e54 ^= e54 + Math.imul(e54 ^ e54 \u003e\u003e\u003e 7, 61 | e54), ((e54 ^ e54 \u003e\u003e\u003e 14) \u003e\u003e\u003e 0) / 4294967296;\n };\n })(t3);\n for (let e53 = n3.length - 1;e53 \u003e 0; e53--) {\n const t4 = Math.floor(o3() * (e53 + 1));\n [n3[e53], n3[t4]] = [n3[t4], n3[e53]];\n }\n return n3;\n};\nvar t3 = (e51, t4) =\u003e e51.routeMetadata?.[t4];\nvar n3 = (e51) =\u003e e51?.simpleRouteConnection?.pointsToConnect?.map(({ pointId: e53 }) =\u003e typeof e53 == \"string\" ? e53 : null).filter((e53) =\u003e e53 !== null) ?? [];\nvar o3 = (e51, t4) =\u003e {\n const n4 = t3(e51, t4)?.connectionId;\n return typeof n4 == \"string\" ? n4 : `route-${t4}`;\n};\nvar i3 = (e51, t4, n4) =\u003e {\n const o4 = e51.portEndpointNetIds[n4];\n if (!o4)\n return false;\n for (const e53 of o4)\n if (e53 !== t4)\n return true;\n return false;\n};\nvar r3 = (e51, t4, n4) =\u003e {\n const o4 = e51.regionNetId[n4];\n return o4 !== -1 \u0026\u0026 o4 !== t4;\n};\nvar s3 = (e51) =\u003e [...new Set(e51.routeIds)].filter((t4) =\u003e !((e53, t6) =\u003e {\n const { topology: n4, problem: o4, problemSetup: i4, portAssignment: r4, maxPrecheckHops: s4 } = e53, a3 = o4.routeNet[t6], c3 = o4.routeStartPort[t6], l3 = o4.routeEndPort[t6];\n if (c3 === l3)\n return true;\n const h3 = e53.getStartingNextRegionId(t6, c3);\n if (h3 === undefined)\n return false;\n const d3 = [{ portId: c3, nextRegionId: h3 }], u3 = new Set([c3 * n4.regionCount + h3]);\n for (let e54 = 0;e54 \u003c d3.length; e54++) {\n const t7 = d3[e54];\n if (!r3(o4, a3, t7.nextRegionId))\n for (const e55 of n4.regionIncidentPorts[t7.nextRegionId] ?? []) {\n const c4 = r4[e55];\n if (i3(i4, a3, e55))\n continue;\n if (e55 === l3) {\n if (c4 !== -1 \u0026\u0026 c4 !== a3)\n continue;\n return true;\n }\n if (e55 === t7.portId)\n continue;\n if (c4 !== -1 \u0026\u0026 c4 !== a3)\n continue;\n if (o4.portSectionMask[e55] === 0)\n continue;\n const h4 = n4.incidentPortRegion[e55] ?? [], p3 = h4[0] === t7.nextRegionId ? h4[1] : h4[0];\n if (p3 === undefined || r3(o4, a3, p3))\n continue;\n const m3 = e55 * n4.regionCount + p3;\n if (!u3.has(m3)) {\n if (u3.size \u003e= s4)\n return true;\n u3.add(m3), d3.push({ portId: e55, nextRegionId: p3 });\n }\n }\n }\n return false;\n})(e51, t4)).map((t4) =\u003e e51.getRouteSummary(t4));\nvar a3 = (e51) =\u003e {\n const t4 = new Array(e51);\n for (let n4 = 0;n4 \u003c e51; n4++)\n t4[n4] = n4;\n return t4;\n};\nvar c3 = 0.05;\nvar l3 = { r: 255, g: 64, b: 64, a: 0.72 };\nvar h3 = \"rgba(220, 38, 38, 0.98)\";\nvar d3 = \"rgba(220, 38, 38, 0.12)\";\nvar u3 = \"10 6\";\nvar p3 = (...e51) =\u003e e51.filter((e53) =\u003e Boolean(e53)).join(`\n`);\nvar m3 = (e51) =\u003e Math.min(1, Math.max(0, e51));\nvar g3 = (e51, t4, n4) =\u003e Math.round(e51 + (t4 - e51) * n4);\nvar f3 = ({ r: e51, g: t4, b: n4, a: o4 }) =\u003e `rgba(${e51}, ${t4}, ${n4}, ${o4})`;\nvar _3 = (e51, t4) =\u003e {\n const n4 = e51.problem.routeMetadata?.[t4];\n return n4?.connectionId ?? n4?.mutuallyConnectedNetworkId ?? `route-${t4}`;\n};\nvar y3 = (e51) =\u003e typeof e51.centerRouteId == \"number\";\nvar b3 = (e51, t4) =\u003e y3(e51) ? t4 === e51.centerRouteId ? 1 : 0.5 : 1;\nvar x3 = (e51, t4) =\u003e {\n const n4 = e51.match(/^(rgba|hsla)\\((.*),\\s*([0-9]*\\.?[0-9]+)\\)$/);\n if (!n4)\n return e51;\n const [, o4, i4, r4] = n4, s4 = m3(Number(r4) * t4);\n return `${o4}(${i4}, ${Number(s4.toFixed(3))})`;\n};\nvar v3 = (e51, t4, n4 = 0.8) =\u003e ((e53, t6, n6 = 0.8) =\u003e {\n const o4 = `${e53.problem.routeNet[t6]}:${_3(e53, t6)}`;\n let i4 = 0;\n for (let e54 = 0;e54 \u003c o4.length; e54++)\n i4 = 17777 * o4.charCodeAt(e54) + ((i4 \u003c\u003c 5) - i4);\n return `hsla(${Math.abs(i4) % 360}, 70%, 50%, ${n6})`;\n})(e51, t4, n4 * b3(e51, t4));\nvar I3 = (e51, t4) =\u003e `net: ${e51.problem.routeNet[t4]}`;\nvar S3 = (e51, t4) =\u003e {\n const n4 = e51.topology.regionMetadata?.[t4], o4 = n4?.polygon;\n if (Array.isArray(o4) \u0026\u0026 o4.length \u003e= 3) {\n const e53 = o4.map((e54) =\u003e e54.x), t6 = o4.map((e54) =\u003e e54.y);\n return { minX: Math.min(...e53), maxX: Math.max(...e53), minY: Math.min(...t6), maxY: Math.max(...t6) };\n }\n const i4 = n4?.bounds;\n if (i4 \u0026\u0026 typeof i4.minX == \"number\" \u0026\u0026 typeof i4.maxX == \"number\" \u0026\u0026 typeof i4.minY == \"number\" \u0026\u0026 typeof i4.maxY == \"number\")\n return i4;\n const r4 = e51.topology.regionWidth[t4], s4 = e51.topology.regionHeight[t4], a4 = e51.topology.regionCenterX[t4], c4 = e51.topology.regionCenterY[t4];\n return { minX: a4 - r4 / 2, maxX: a4 + r4 / 2, minY: c4 - s4 / 2, maxY: c4 + s4 / 2 };\n};\nvar C3 = (e51, t4) =\u003e ({ x: e51.topology.regionCenterX[t4], y: e51.topology.regionCenterY[t4] });\nvar P3 = (e51, t4) =\u003e {\n const n4 = e51.topology.regionMetadata?.[t4], o4 = Array.isArray(n4?.availableZ) ? n4.availableZ.filter((e53) =\u003e typeof e53 == \"number\" \u0026\u0026 Number.isInteger(e53) \u0026\u0026 e53 \u003e= 0) : [];\n if (o4.length \u003e 0)\n return F5(o4) ?? \"z0\";\n const i4 = j5(e51.topology.regionAvailableZMask?.[t4] ?? 0);\n if (i4.length \u003e 0)\n return F5(i4) ?? \"z0\";\n const r4 = [...new Set((e51.topology.regionIncidentPorts[t4] ?? []).map((t6) =\u003e e51.topology.portZ[t6]))].sort((e53, t6) =\u003e e53 - t6);\n return F5(r4) ?? \"z0\";\n};\nvar M3 = (e51, t4) =\u003e {\n const n4 = e51.state.regionIntersectionCaches[t4], o4 = n4?.existingRegionCost ?? 0, i4 = e51.state.regionCongestionCost[t4] ?? 0, r4 = e51.problem.regionNetId[t4];\n return p3(`region: region-${t4}`, `net: ${r4 === -1 ? \"free\" : `${r4}`}`, e51.getAdditionalRegionLabel(t4), `cost: ${o4.toFixed(3)}`, `congestion: ${i4.toFixed(3)}`, `same layer X: ${n4?.existingSameLayerIntersections ?? 0}`, `trans X: ${n4?.existingCrossingLayerIntersections ?? 0}`, `entry exit X: ${n4?.existingEntryExitLayerChanges ?? 0}`);\n};\nvar w3 = (e51, t4) =\u003e {\n const n4 = e51.topology.regionMetadata?.[t4];\n return n4?.isConnectionRegion ? { r: 255, g: 100, b: 255, a: 0.6 } : n4?.isThroughJumper ? { r: 100, g: 200, b: 100, a: 0.5 } : n4?.isPad ? { r: 255, g: 200, b: 100, a: 0.5 } : n4?.layer === \"bottom\" ? { r: 52, g: 152, b: 219, a: 0.08 } : { r: 200, g: 200, b: 255, a: 0.1 };\n};\nvar N3 = (e51, t4) =\u003e {\n const n4 = w3(e51, t4), o4 = m3(e51.state.regionIntersectionCaches[t4]?.existingRegionCost ?? 0), i4 = Math.pow(o4, 0.8);\n return f3((s4 = l3, a4 = i4, { r: g3((r4 = n4).r, s4.r, a4), g: g3(r4.g, s4.g, a4), b: g3(r4.b, s4.b, a4), a: Number((r4.a + (s4.a - r4.a) * a4).toFixed(3)) }));\n var r4, s4, a4;\n};\nvar R3 = (e51, t4) =\u003e ({ x: e51.topology.portX[t4], y: e51.topology.portY[t4] });\nvar T3 = R3;\nvar E3 = R3;\nvar A3 = (e51, t4) =\u003e F5([e51.topology.portZ[t4]]) ?? \"z0\";\nvar O3 = (e51, t4) =\u003e {\n const n4 = e51.topology.portMetadata?.[t4];\n return `port: ${n4?.serializedPortId ?? n4?.portId ?? `port-${t4}`}`;\n};\nvar k3 = (e51, t4, n4) =\u003e {\n if (n4 !== undefined)\n return `net: ${e51.problem.routeNet[n4]}`;\n const o4 = e51.state.portAssignment[t4];\n if (o4 \u003e= 0)\n return `net: ${o4}`;\n const i4 = new Set;\n for (let n6 = 0;n6 \u003c e51.problem.routeCount; n6++)\n e51.problem.routeStartPort[n6] !== t4 \u0026\u0026 e51.problem.routeEndPort[n6] !== t4 || i4.add(e51.problem.routeNet[n6]);\n return i4.size !== 0 ? `net: ${Array.from(i4).sort((e53, t6) =\u003e e53 - t6).join(\", \")}` : undefined;\n};\nvar D3 = (e51, t4) =\u003e `z: ${e51.topology.portZ[t4]}`;\nvar L3 = (e51, t4, n4) =\u003e p3(O3(e51, t4), ((e53, t6) =\u003e {\n const n6 = e53.topology.incidentPortRegion[t6]?.[0], o4 = e53.topology.incidentPortRegion[t6]?.[1];\n return `connects: region-${n6 ?? \"?\"} \u003c-\u003e region-${o4 ?? \"?\"}`;\n})(e51, t4), k3(e51, t4, n4));\nvar z3 = (e51, t4, n4, o4) =\u003e {\n const i4 = e51.topology.portZ[n4], r4 = e51.topology.portZ[o4];\n return i4 \u003e 0 \u0026\u0026 r4 \u003e 0 ? { strokeColor: x3(\"rgba(52, 152, 219, 0.95)\", b3(e51, t4)), strokeDash: \"3 2\" } : i4 !== r4 ? { strokeColor: x3(\"rgba(22, 160, 133, 0.95)\", b3(e51, t4)), strokeDash: \"2 4 2\" } : { strokeColor: v3(e51, t4) };\n};\nvar B3 = (e51, t4) =\u003e {\n for (let n4 = 0;n4 \u003c e51.problem.routeCount; n4++)\n if (e51.problem.routeStartPort[n4] === t4 || e51.problem.routeEndPort[n4] === t4)\n return true;\n return false;\n};\nvar F3 = (e51, t4, n4) =\u003e {\n const o4 = ((e53, t6) =\u003e {\n const n6 = new Set;\n for (let o6 = 0;o6 \u003c t6.length; o6++)\n if (t6[o6] === 1)\n for (const t7 of e53.topology.incidentPortRegion[o6] ?? [])\n n6.add(t7);\n return n6;\n })(e51, n4), i4 = \"rgba(245, 158, 11, 0.95)\", r4 = \"rgba(245, 158, 11, 0.08)\";\n for (const n6 of o4) {\n const o6 = e51.topology.regionMetadata?.[n6], s4 = o6?.polygon, a4 = S3(e51, n6), c4 = C3(e51, n6), l4 = a4.maxX - a4.minX, h4 = a4.maxY - a4.minY, d4 = P3(e51, n6), u4 = p3(\"section region\", M3(e51, n6));\n Array.isArray(s4) \u0026\u0026 s4.length \u003e= 3 ? t4.polygons.push({ points: s4, fill: r4, stroke: i4, strokeWidth: 2, layer: d4, label: u4 }) : t4.rects.push({ center: c4, width: Math.max(l4 - c3, 0.05), height: Math.max(h4 - c3, 0.05), fill: r4, stroke: i4, layer: d4, label: u4 });\n }\n for (let o6 = 0;o6 \u003c n4.length; o6++)\n n4[o6] === 1 \u0026\u0026 t4.circles.push({ center: E3(e51, o6), radius: 0.07, fill: \"rgba(251, 191, 36, 0.18)\", stroke: i4, layer: A3(e51, o6), label: p3(L3(e51, o6), D3(e51, o6), \"section port\") });\n};\nvar j3 = (e51, t4 = {}) =\u003e {\n const n4 = { arrows: [], circles: [], infiniteLines: [], lines: [], points: [], polygons: [], rects: [], texts: [], title: \"Tiny HyperGraph\", coordinateSystem: \"cartesian\" }, o4 = ((e53, t6) =\u003e {\n if (!t6?.highlightSectionMask)\n return;\n const n6 = t6.sectionPortMask ?? e53.problem.portSectionMask;\n if (n6.length !== e53.topology.portCount)\n return;\n let o6 = 0, i6 = 0;\n for (let e54 = 0;e54 \u003c n6.length; e54++)\n n6[e54] === 1 ? o6 += 1 : i6 += 1;\n return o6 !== 0 \u0026\u0026 i6 !== 0 ? n6 : undefined;\n })(e51, t4);\n for (let t6 = 0;t6 \u003c e51.topology.regionCount; t6++) {\n const o6 = e51.topology.regionMetadata?.[t6], i6 = o6?.polygon, r6 = S3(e51, t6), s4 = C3(e51, t6), a4 = r6.maxX - r6.minX, c4 = r6.maxY - r6.minY, l4 = P3(e51, t6), h4 = f3(w3(e51, t6));\n Array.isArray(i6) \u0026\u0026 i6.length \u003e= 3 ? n4.polygons.push({ points: i6, fill: h4, layer: l4 }) : n4.rects.push({ center: s4, width: Math.max(a4 - c3, 0.05), height: Math.max(c4 - c3, 0.05), fill: N3(e51, t6), layer: l4, label: M3(e51, t6) });\n }\n if (((e53, t6) =\u003e {\n for (let n6 = 0;n6 \u003c e53.problem.routeCount; n6++) {\n const o6 = e53.problem.routeStartPort[n6], i6 = e53.problem.routeEndPort[n6], r6 = T3(e53, o6), s4 = T3(e53, i6), a4 = v3(e53, n6), c4 = _3(e53, n6), l4 = I3(e53, n6);\n t6.points.push({ x: r6.x, y: r6.y, color: a4, layer: A3(e53, o6), label: p3(`route: ${c4}`, l4, \"endpoint: start\", O3(e53, o6), D3(e53, o6)) }), t6.points.push({ x: s4.x, y: s4.y, color: a4, layer: A3(e53, i6), label: p3(`route: ${c4}`, l4, \"endpoint: end\", O3(e53, i6), D3(e53, i6)) });\n }\n })(e51, n4), e51.iterations === 0) {\n for (const e53 of n4.polygons)\n e53.stroke = \"rgba(128, 128, 128, 0.5)\";\n for (const e53 of n4.rects)\n e53.stroke = \"rgba(128, 128, 128, 0.5)\";\n }\n if (e51.iterations === 0) {\n for (let i6 = 0;i6 \u003c e51.topology.portCount; i6++) {\n const r6 = o4?.[i6] === 1;\n t4.showOnlySectionPortsOnIdle \u0026\u0026 !r6 || n4.circles.push({ center: E3(e51, i6), radius: 0.05, fill: e51.topology.portZ[i6] \u003e 0 ? \"rgba(52, 152, 219, 0.55)\" : \"rgba(128, 128, 128, 0.5)\", layer: A3(e51, i6), label: p3(L3(e51, i6), D3(e51, i6)) });\n }\n t4.showInitialRouteHints !== false \u0026\u0026 ((e53, t6) =\u003e {\n for (let n6 = 0;n6 \u003c e53.problem.routeCount; n6++) {\n const o6 = e53.problem.routeStartPort[n6], i6 = e53.problem.routeEndPort[n6], r6 = T3(e53, o6), s4 = T3(e53, i6), a4 = { x: (r6.x + s4.x) / 2, y: (r6.y + s4.y) / 2 };\n t6.lines.push({ points: [r6, s4], strokeColor: v3(e53, n6), strokeDash: \"3 3\", label: _3(e53, n6) }), t6.points.push({ x: a4.x, y: a4.y, color: v3(e53, n6, 1), label: _3(e53, n6) });\n }\n })(e51, n4);\n } else\n ((e53, t6) =\u003e {\n for (let n6 = 0;n6 \u003c e53.state.regionSegments.length; n6++) {\n const o6 = e53.state.regionSegments[n6] ?? [];\n for (const [i6, r6, s4] of o6)\n t6.lines.push({ points: [T3(e53, r6), T3(e53, s4)], label: p3(`route: ${_3(e53, i6)}`, `region: region-${n6}`), ...z3(e53, i6, r6, s4) });\n }\n })(e51, n4), ((e53, t6) =\u003e {\n const n6 = new Set;\n for (let o6 = 0;o6 \u003c e53.state.regionSegments.length; o6++) {\n const i6 = e53.state.regionSegments[o6] ?? [];\n for (const [o7, r6, s4] of i6)\n for (const i7 of [r6, s4]) {\n const r7 = `${o7}:${i7}`;\n if (n6.has(r7))\n continue;\n n6.add(r7);\n const s6 = T3(e53, i7);\n t6.points.push({ x: s6.x, y: s6.y, color: v3(e53, o7, 1), layer: A3(e53, i7), label: p3(`route: ${_3(e53, o7)}`, O3(e53, i7), k3(e53, i7, o7), D3(e53, i7)) });\n }\n }\n })(e51, n4), ((e53) =\u003e y3(e53) \u0026\u0026 e53.showUnassignedPortsInVisualization === true)(e51) \u0026\u0026 ((e53, t6) =\u003e {\n for (let n6 = 0;n6 \u003c e53.topology.portCount; n6++)\n e53.state.portAssignment[n6] \u003e= 0 || B3(e53, n6) || t6.circles.push({ center: E3(e53, n6), radius: 0.04, fill: e53.topology.portZ[n6] \u003e 0 ? \"rgba(52, 152, 219, 0.2)\" : \"rgba(128, 128, 128, 0.2)\", stroke: e53.topology.portZ[n6] \u003e 0 ? \"rgba(52, 152, 219, 0.6)\" : \"rgba(128, 128, 128, 0.6)\", layer: A3(e53, n6), label: p3(L3(e53, n6), D3(e53, n6), \"state: unassigned\") });\n })(e51, n4), y3(e51) || (((e53, t6) =\u003e {\n const n6 = e53.state.currentRouteId;\n if (n6 === undefined || e53.solved)\n return;\n const o6 = e53.problem.routeStartPort[n6], i6 = e53.problem.routeEndPort[n6], r6 = T3(e53, o6), s4 = T3(e53, i6), a4 = v3(e53, n6), c4 = _3(e53, n6);\n t6.lines.push({ points: [r6, s4], strokeColor: a4, strokeDash: \"10 5\", label: c4 });\n })(e51, n4), ((e53, t6) =\u003e {\n if (e53.solved)\n return;\n const n6 = e53.state.currentRouteId, o6 = e53.state.candidateQueue.toArray().sort((e54, t7) =\u003e e54.f - t7.f).slice(0, 10);\n for (let i7 = 0;i7 \u003c o6.length; i7++) {\n const r7 = o6[i7], s6 = T3(e53, r7.portId), a4 = i7 === 0;\n t6.points.push({ x: s6.x, y: s6.y, color: a4 ? \"green\" : \"rgba(128, 128, 128, 0.25)\", layer: A3(e53, r7.portId), label: p3(L3(e53, r7.portId, n6), D3(e53, r7.portId), `g: ${r7.g.toFixed(2)}`, `h: ${r7.h.toFixed(2)}`, `f: ${r7.f.toFixed(2)}`) });\n }\n const i6 = o6[0];\n if (!i6)\n return;\n const r6 = [];\n let s4 = i6;\n for (;s4; )\n r6.unshift(T3(e53, s4.portId)), s4 = s4.prevCandidate;\n r6.length \u003e 1 \u0026\u0026 t6.lines.push({ points: r6, strokeColor: n6 !== undefined ? v3(e53, n6) : \"rgba(0, 160, 120, 0.9)\" });\n })(e51, n4));\n o4 \u0026\u0026 F3(e51, n4, o4), ((e53, t6) =\u003e {\n if (e53.failed)\n for (const n6 of e53.getNeverSuccessfullyRoutedRoutes()) {\n const { routeId: o6, connectionId: i6, attempts: r6, startPortId: s4, endPortId: a4 } = n6, c4 = I3(e53, o6), l4 = E3(e53, s4), h4 = E3(e53, a4), d4 = p3(`never routed: ${i6}`, `attempts: ${r6}`, c4, n6.startRegionId ? `startRegionId: ${n6.startRegionId}` : undefined, n6.endRegionId ? `endRegionId: ${n6.endRegionId}` : undefined);\n t6.lines.push({ points: [{ x: 0, y: 0 }, { x: l4.x, y: l4.y }], strokeColor: h3, strokeDash: u3, layer: A3(e53, s4), label: p3(d4, \"origin guide\", \"endpoint: start\") }), t6.circles.push({ center: l4, radius: 1, fill: d3, stroke: h3, layer: A3(e53, s4), label: p3(d4, \"endpoint: start\", O3(e53, s4), D3(e53, s4)) }), t6.lines.push({ points: [{ x: 0, y: 0 }, { x: h4.x, y: h4.y }], strokeColor: h3, strokeDash: u3, layer: A3(e53, a4), label: p3(d4, \"origin guide\", \"endpoint: end\") }), t6.circles.push({ center: h4, radius: 1, fill: d3, stroke: h3, layer: A3(e53, a4), label: p3(d4, \"endpoint: end\", O3(e53, a4), D3(e53, a4)) });\n }\n })(e51, n4);\n const i4 = e51.state.unroutedRoutes.length + (e51.state.currentRouteId === undefined ? 0 : 1), r4 = o4 ? o4.reduce((e53, t6) =\u003e e53 + Number(t6 === 1), 0) : 0;\n return n4.title = [\"Tiny HyperGraph\", `iter=${e51.iterations}`, `pending=${i4}`, o4 ? `sectionPorts=${r4}` : undefined, e51.failed ? \"failed\" : e51.solved ? \"solved\" : \"running\"].filter(Boolean).join(\" | \"), n4;\n};\nvar $3 = () =\u003e ({ netIds: new Int32Array(0), lesserAngles: new Int32Array(0), greaterAngles: new Int32Array(0), layerMasks: new Int32Array(0), existingCrossingLayerIntersections: 0, existingSameLayerIntersections: 0, existingEntryExitLayerChanges: 0, existingRegionCost: 0, existingSegmentCount: 0 });\nvar Y3 = (e51, t4) =\u003e e51.f - t4.f;\nvar X3 = class extends BaseSolver {\n constructor(e51, t4, n4) {\n super(), this.topology = e51, this.problem = t4, ((e53, t6) =\u003e {\n t6 \u0026\u0026 (t6.DISTANCE_TO_COST !== undefined \u0026\u0026 (e53.DISTANCE_TO_COST = t6.DISTANCE_TO_COST), t6.RIP_THRESHOLD_START !== undefined \u0026\u0026 (e53.RIP_THRESHOLD_START = t6.RIP_THRESHOLD_START), t6.RIP_THRESHOLD_END !== undefined \u0026\u0026 (e53.RIP_THRESHOLD_END = t6.RIP_THRESHOLD_END), t6.RIP_THRESHOLD_RAMP_ATTEMPTS !== undefined \u0026\u0026 (e53.RIP_THRESHOLD_RAMP_ATTEMPTS = t6.RIP_THRESHOLD_RAMP_ATTEMPTS), t6.RIP_CONGESTION_REGION_COST_FACTOR !== undefined \u0026\u0026 (e53.RIP_CONGESTION_REGION_COST_FACTOR = t6.RIP_CONGESTION_REGION_COST_FACTOR), t6.MAX_ITERATIONS !== undefined \u0026\u0026 (e53.MAX_ITERATIONS = t6.MAX_ITERATIONS), t6.VERBOSE !== undefined \u0026\u0026 (e53.VERBOSE = t6.VERBOSE), t6.STATIC_REACHABILITY_PRECHECK !== undefined \u0026\u0026 (e53.STATIC_REACHABILITY_PRECHECK = t6.STATIC_REACHABILITY_PRECHECK), t6.STATIC_REACHABILITY_PRECHECK_MAX_HOPS !== undefined \u0026\u0026 (e53.STATIC_REACHABILITY_PRECHECK_MAX_HOPS = t6.STATIC_REACHABILITY_PRECHECK_MAX_HOPS));\n })(this, n4), this.state = { portAssignment: new Int32Array(e51.portCount).fill(-1), regionSegments: Array.from({ length: e51.regionCount }, () =\u003e []), regionIntersectionCaches: Array.from({ length: e51.regionCount }, () =\u003e $3()), currentRouteId: undefined, currentRouteNetId: undefined, unroutedRoutes: a3(t4.routeCount), candidateQueue: new K5([], Y3), candidateBestCostByHopId: new Float64Array(e51.portCount * e51.regionCount), candidateBestCostGenerationByHopId: new Uint32Array(e51.portCount * e51.regionCount), candidateBestCostGeneration: 1, goalPortId: -1, ripCount: 0, regionCongestionCost: new Float64Array(e51.regionCount).fill(0) }, this.routeAttemptCountByRouteId = new Uint32Array(t4.routeCount), this.routeSuccessCountByRouteId = new Uint32Array(t4.routeCount);\n }\n state;\n _problemSetup;\n routeAttemptCountByRouteId;\n routeSuccessCountByRouteId;\n hasLoggedNeverSuccessfullyRoutedRoutes = false;\n segmentGeometryScratch = { lesserAngle: 0, greaterAngle: 0, layerMask: 0, entryExitLayerChanges: 0 };\n DISTANCE_TO_COST = 0.05;\n RIP_THRESHOLD_START = 0.05;\n RIP_THRESHOLD_END = 0.8;\n RIP_THRESHOLD_RAMP_ATTEMPTS = 50;\n RIP_CONGESTION_REGION_COST_FACTOR = 0.1;\n MAX_ITERATIONS = 1e6;\n VERBOSE = false;\n STATIC_REACHABILITY_PRECHECK = true;\n STATIC_REACHABILITY_PRECHECK_MAX_HOPS = 16;\n get problemSetup() {\n return this._problemSetup || (this._problemSetup = this.computeProblemSetup()), this._problemSetup;\n }\n computeProblemSetup() {\n const { topology: e51, problem: t4 } = this, n4 = e51.portX, o4 = e51.portY, i4 = new Float64Array(e51.portCount * t4.routeCount), r4 = Array.from({ length: e51.portCount }, () =\u003e new Set);\n for (let s4 = 0;s4 \u003c t4.routeCount; s4++) {\n r4[t4.routeStartPort[s4]].add(t4.routeNet[s4]), r4[t4.routeEndPort[s4]].add(t4.routeNet[s4]);\n const a4 = t4.routeEndPort[s4], c4 = n4[a4], l4 = o4[a4];\n for (let r6 = 0;r6 \u003c e51.portCount; r6++) {\n const e53 = n4[r6] - c4, a6 = o4[r6] - l4;\n i4[r6 * t4.routeCount + s4] = Math.hypot(e53, a6) * this.DISTANCE_TO_COST;\n }\n }\n return { portHCostToEndOfRoute: i4, portEndpointNetIds: r4 };\n }\n _setup() {\n if (this.problemSetup, this.STATIC_REACHABILITY_PRECHECK) {\n const e51 = s3({ topology: this.topology, problem: this.problem, problemSetup: this.problemSetup, portAssignment: this.state.portAssignment, routeIds: this.state.unroutedRoutes, maxPrecheckHops: Math.max(0, this.STATIC_REACHABILITY_PRECHECK_MAX_HOPS), getStartingNextRegionId: (e53, t4) =\u003e this.getStartingNextRegionId(e53, t4), getRouteSummary: (e53) =\u003e this.getRouteSummary(e53) });\n e51.length \u003e 0 \u0026\u0026 (this.failed = true, this.error = ((e53) =\u003e {\n const t4 = e53.slice(0, 5).map((e54) =\u003e {\n const t6 = e54.pointIds.length \u003e= 2 ? `${e54.pointIds[0]}-\u003e${e54.pointIds[1]}` : `${e54.startPortId}-\u003e${e54.endPortId}`;\n return `${e54.connectionId} (${t6})`;\n }).join(\", \"), n4 = e53.length - 5;\n return [\"Static reachability precheck failed:\", `${e53.length} route(s) have no legal path under the current reservation and start-region rules`, n4 \u003e 0 ? `${t4}, +${n4} more` : t4].join(\" \");\n })(e51), this.stats = { ...this.stats, staticallyUnroutableRouteCount: e51.length });\n }\n }\n _step() {\n const { problem: e51, topology: t4, state: n4 } = this;\n if (n4.currentRouteId === undefined) {\n if (n4.unroutedRoutes.length === 0)\n return void this.onAllRoutesRouted();\n n4.currentRouteId = n4.unroutedRoutes.shift(), n4.currentRouteNetId = e51.routeNet[n4.currentRouteId], this.routeAttemptCountByRouteId[n4.currentRouteId] += 1, this.resetCandidateBestCosts();\n const t6 = e51.routeStartPort[n4.currentRouteId];\n n4.candidateQueue.clear();\n const o6 = this.getStartingNextRegionId(n4.currentRouteId, t6);\n if (o6 === undefined)\n return this.failed = true, void (this.error = `Start port ${t6} has no incident regions`);\n this.setCandidateBestCost(this.getHopId(t6, o6), 0), n4.candidateQueue.queue({ nextRegionId: o6, portId: t6, f: 0, g: 0, h: 0 }), n4.goalPortId = e51.routeEndPort[n4.currentRouteId];\n }\n const o4 = n4.candidateQueue.dequeue();\n if (!o4)\n return void this.onOutOfCandidates();\n const i4 = this.getHopId(o4.portId, o4.nextRegionId);\n if (o4.g \u003e this.getCandidateBestCost(i4))\n return;\n if (this.isRegionReservedForDifferentNet(o4.nextRegionId))\n return;\n const r4 = t4.regionIncidentPorts[o4.nextRegionId];\n for (const i6 of r4) {\n const r6 = n4.portAssignment[i6];\n if (this.isPortReservedForDifferentNet(i6))\n continue;\n if (i6 === n4.goalPortId) {\n if (r6 !== -1 \u0026\u0026 r6 !== n4.currentRouteNetId)\n continue;\n return void this.onPathFound(o4);\n }\n if (r6 !== -1 \u0026\u0026 r6 !== n4.currentRouteNetId)\n continue;\n if (i6 === o4.portId)\n continue;\n if (e51.portSectionMask[i6] === 0)\n continue;\n const s4 = this.computeG(o4, i6);\n if (!Number.isFinite(s4))\n continue;\n const a4 = this.computeH(i6), c4 = t4.incidentPortRegion[i6][0] === o4.nextRegionId ? t4.incidentPortRegion[i6][1] : t4.incidentPortRegion[i6][0];\n if (c4 === undefined || this.isRegionReservedForDifferentNet(c4))\n continue;\n const l4 = { prevRegionId: o4.nextRegionId, nextRegionId: c4, portId: i6, g: s4, h: a4, f: s4 + a4, prevCandidate: o4 };\n if (i6 === n4.goalPortId)\n return void this.onPathFound(l4);\n const h4 = this.getHopId(i6, c4);\n s4 \u003e= this.getCandidateBestCost(h4) || (this.setCandidateBestCost(h4, s4), n4.candidateQueue.queue(l4));\n }\n }\n resetCandidateBestCosts() {\n const { state: e51 } = this;\n if (e51.candidateBestCostGeneration === 4294967295)\n return e51.candidateBestCostGenerationByHopId.fill(0), void (e51.candidateBestCostGeneration = 1);\n e51.candidateBestCostGeneration += 1;\n }\n getCandidateBestCost(e51) {\n const { state: t4 } = this;\n return t4.candidateBestCostGenerationByHopId[e51] === t4.candidateBestCostGeneration ? t4.candidateBestCostByHopId[e51] : Number.POSITIVE_INFINITY;\n }\n setCandidateBestCost(e51, t4) {\n const { state: n4 } = this;\n n4.candidateBestCostGenerationByHopId[e51] = n4.candidateBestCostGeneration, n4.candidateBestCostByHopId[e51] = t4;\n }\n getHopId(e51, t4) {\n return e51 * this.topology.regionCount + t4;\n }\n getStartingNextRegionId(e51, t4) {\n const n4 = this.topology.incidentPortRegion[t4] ?? [], o4 = this.problem.routeNet[e51];\n return n4.find((e53) =\u003e this.problem.regionNetId[e53] === -1) ?? n4.find((e53) =\u003e this.problem.regionNetId[e53] === o4) ?? n4[0];\n }\n isPortReservedForDifferentNet(e51) {\n const t4 = this.problemSetup.portEndpointNetIds[e51];\n if (!t4)\n return false;\n for (const e53 of t4)\n if (e53 !== this.state.currentRouteNetId)\n return true;\n return false;\n }\n isRegionReservedForDifferentNet(e51) {\n const t4 = this.problem.regionNetId[e51];\n return t4 !== -1 \u0026\u0026 t4 !== this.state.currentRouteNetId;\n }\n isKnownSingleLayerRegion(e51) {\n const t4 = this.topology.regionAvailableZMask?.[e51] ?? 0;\n return q5(t4);\n }\n computeRegionCostForRegion(e51, t4, n4, o4, i4) {\n return ((e53, t6, n6, o6, i6, r4, s4 = 0) =\u003e J5(e53 * t6, n6, o6, i6, r4, s4))(this.topology.regionWidth[e51], this.topology.regionHeight[e51], t4, n4, o4, i4, this.topology.regionAvailableZMask?.[e51] ?? 0);\n }\n populateSegmentGeometryScratch(e51, t4, n4) {\n const { topology: o4 } = this, i4 = this.segmentGeometryScratch, r4 = o4.incidentPortRegion[t4], s4 = o4.incidentPortRegion[n4], a4 = r4[0] === e51 || r4[1] !== e51 ? o4.portAngleForRegion1[t4] : o4.portAngleForRegion2?.[t4] ?? o4.portAngleForRegion1[t4], c4 = s4[0] === e51 || s4[1] !== e51 ? o4.portAngleForRegion1[n4] : o4.portAngleForRegion2?.[n4] ?? o4.portAngleForRegion1[n4], l4 = o4.portZ[t4], h4 = o4.portZ[n4];\n return i4.lesserAngle = a4 \u003c c4 ? a4 : c4, i4.greaterAngle = a4 \u003c c4 ? c4 : a4, i4.layerMask = 1 \u003c\u003c l4 | 1 \u003c\u003c h4, i4.entryExitLayerChanges = l4 !== h4 ? 1 : 0, i4;\n }\n appendSegmentToRegionCache(e51, t4, n4) {\n const { topology: o4, state: i4 } = this, r4 = i4.regionIntersectionCaches[e51], s4 = this.populateSegmentGeometryScratch(e51, t4, n4), [a4, c4, l4] = Q5(r4, i4.currentRouteNetId, s4.lesserAngle, s4.greaterAngle, s4.layerMask, s4.entryExitLayerChanges), h4 = r4.netIds.length + 1, d4 = new Int32Array(h4);\n d4.set(r4.netIds), d4[h4 - 1] = i4.currentRouteNetId;\n const u4 = new Int32Array(h4);\n u4.set(r4.lesserAngles), u4[h4 - 1] = s4.lesserAngle;\n const p4 = new Int32Array(h4);\n p4.set(r4.greaterAngles), p4[h4 - 1] = s4.greaterAngle;\n const m4 = new Int32Array(h4);\n m4.set(r4.layerMasks), m4[h4 - 1] = s4.layerMask;\n const g4 = r4.existingSameLayerIntersections + a4, f4 = r4.existingCrossingLayerIntersections + c4, _4 = r4.existingEntryExitLayerChanges + l4, y4 = u4.length;\n i4.regionIntersectionCaches[e51] = { netIds: d4, lesserAngles: u4, greaterAngles: p4, layerMasks: m4, existingSameLayerIntersections: g4, existingCrossingLayerIntersections: f4, existingEntryExitLayerChanges: _4, existingSegmentCount: y4, existingRegionCost: this.computeRegionCostForRegion(e51, g4, f4, _4, y4) };\n }\n getSolvedPathSegments(e51) {\n const { state: t4 } = this, n4 = [];\n let o4 = e51;\n for (;o4; )\n n4.unshift(o4), o4 = o4.prevCandidate;\n const i4 = [];\n for (let e53 = 1;e53 \u003c n4.length; e53++)\n i4.push({ regionId: n4[e53 - 1].nextRegionId, fromPortId: n4[e53 - 1].portId, toPortId: n4[e53].portId });\n const r4 = n4[n4.length - 1];\n return r4 \u0026\u0026 r4.portId !== t4.goalPortId \u0026\u0026 i4.push({ regionId: r4.nextRegionId, fromPortId: r4.portId, toPortId: t4.goalPortId }), i4;\n }\n resetRoutingStateForRerip() {\n const { topology: e51, problem: t4, state: n4 } = this;\n n4.portAssignment.fill(-1), n4.regionSegments = Array.from({ length: e51.regionCount }, () =\u003e []), n4.regionIntersectionCaches = Array.from({ length: e51.regionCount }, () =\u003e $3()), n4.currentRouteNetId = undefined, n4.currentRouteId = undefined, n4.unroutedRoutes = e310(a3(t4.routeCount), n4.ripCount), n4.candidateQueue.clear(), this.resetCandidateBestCosts(), n4.goalPortId = -1;\n }\n getMaxRegionCost() {\n const { topology: e51, state: t4 } = this;\n let n4 = 0;\n for (let o4 = 0;o4 \u003c e51.regionCount; o4++) {\n const e53 = t4.regionIntersectionCaches[o4]?.existingRegionCost ?? 0;\n n4 = Math.max(n4, e53);\n }\n return n4;\n }\n getRouteMetadata(e51) {\n return this.problem.routeMetadata?.[e51];\n }\n getRouteConnectionId(e51) {\n const t4 = this.getRouteMetadata(e51)?.connectionId;\n return typeof t4 == \"string\" ? t4 : `route-${e51}`;\n }\n getRouteSummary(e51) {\n return (({ problem: e53, routeId: t4, getRouteMetadata: n4, getRouteConnectionId: o4 }) =\u003e {\n const i4 = n4?.(t4) ?? t3(e53, t4);\n return { routeId: t4, connectionId: o4?.(t4) ?? o3(e53, t4), startPortId: e53.routeStartPort[t4], endPortId: e53.routeEndPort[t4], startRegionId: typeof i4?.startRegionId == \"string\" ? i4.startRegionId : undefined, endRegionId: typeof i4?.endRegionId == \"string\" ? i4.endRegionId : undefined, pointIds: n3(i4) };\n })({ problem: this.problem, routeId: e51, getRouteMetadata: (e53) =\u003e this.getRouteMetadata(e53), getRouteConnectionId: (e53) =\u003e this.getRouteConnectionId(e53) });\n }\n getAdditionalRegionLabel(e51) {}\n getNeverSuccessfullyRoutedRoutes() {\n const e51 = [];\n for (let t4 = 0;t4 \u003c this.problem.routeCount; t4++) {\n const n4 = this.routeAttemptCountByRouteId[t4];\n n4 === 0 || this.routeSuccessCountByRouteId[t4] \u003e 0 || e51.push({ ...this.getRouteSummary(t4), attempts: n4 });\n }\n return e51;\n }\n logNeverSuccessfullyRoutedRoutes() {\n if (!this.VERBOSE || this.hasLoggedNeverSuccessfullyRoutedRoutes)\n return;\n const e51 = this.getNeverSuccessfullyRoutedRoutes();\n if (this.hasLoggedNeverSuccessfullyRoutedRoutes = true, e51.length !== 0) {\n console.log([\"[TinyHyperGraphSolver:never-routed-summary]\", `count=${e51.length}`].join(\" \"));\n for (const t4 of e51) {\n const e53 = t4.pointIds.length \u003e= 2 ? `${t4.pointIds[0]}-\u003e${t4.pointIds[1]}` : \"unknown\";\n console.log([\"[TinyHyperGraphSolver:never-routed]\", `routeId=${t4.routeId}`, `connectionId=${t4.connectionId}`, `attempts=${t4.attempts}`, `pointPath=${e53}`, `startRegionId=${t4.startRegionId ?? \"unknown\"}`, `endRegionId=${t4.endRegionId ?? \"unknown\"}`].join(\" \"));\n }\n }\n }\n logRipEvent(e51, t4, n4 = {}) {\n this.VERBOSE \u0026\u0026 console.log([\"[TinyHyperGraphSolver:rip]\", `ripCount=${this.state.ripCount}`, `maxRegionCostBeforeRip=${t4.toFixed(3)}`, `reason=${e51}`, ...Object.entries(n4).map(([e53, t6]) =\u003e `${e53}=${typeof t6 == \"number\" ? Number.isInteger(t6) ? String(t6) : t6.toFixed(3) : t6}`)].join(\" \"));\n }\n onAllRoutesRouted() {\n const { topology: e51, state: t4 } = this, n4 = this.RIP_THRESHOLD_RAMP_ATTEMPTS \u003c= 0 ? 1 : Math.min(1, t4.ripCount / this.RIP_THRESHOLD_RAMP_ATTEMPTS), o4 = this.RIP_THRESHOLD_START + (this.RIP_THRESHOLD_END - this.RIP_THRESHOLD_START) * n4, i4 = [], r4 = new Float64Array(e51.regionCount);\n let s4 = 0;\n for (let n6 = 0;n6 \u003c e51.regionCount; n6++) {\n const e53 = t4.regionIntersectionCaches[n6]?.existingRegionCost ?? 0;\n r4[n6] = e53, s4 = Math.max(s4, e53), e53 \u003e o4 \u0026\u0026 i4.push(n6);\n }\n if (this.stats = { ...this.stats, currentRipThreshold: o4, hotRegionCount: i4.length, maxRegionCost: s4, ripCount: t4.ripCount }, i4.length === 0 || t4.ripCount \u003e= this.RIP_THRESHOLD_RAMP_ATTEMPTS)\n this.solved = true;\n else {\n for (let n6 = 0;n6 \u003c e51.regionCount; n6++)\n t4.regionCongestionCost[n6] += r4[n6] * this.RIP_CONGESTION_REGION_COST_FACTOR;\n t4.ripCount += 1, this.resetRoutingStateForRerip(), this.stats = { ...this.stats, ripCount: t4.ripCount, maxRegionCostBeforeRip: s4, reripRegionCount: i4.length }, this.logRipEvent(\"hot_regions\", s4, { hotRegionCount: i4.length, currentRipThreshold: o4 });\n }\n }\n onOutOfCandidates() {\n const { topology: e51, state: t4 } = this, n4 = t4.currentRouteId, o4 = this.getMaxRegionCost();\n for (let n6 = 0;n6 \u003c e51.regionCount; n6++) {\n const e53 = t4.regionIntersectionCaches[n6]?.existingRegionCost ?? 0;\n t4.regionCongestionCost[n6] += e53 * this.RIP_CONGESTION_REGION_COST_FACTOR;\n }\n t4.ripCount += 1, this.resetRoutingStateForRerip(), this.stats = { ...this.stats, ripCount: t4.ripCount, maxRegionCost: o4, maxRegionCostBeforeRip: o4, reripReason: \"out_of_candidates\" }, this.logRipEvent(\"out_of_candidates\", o4, { ...n4 === undefined ? {} : { routeId: n4, connectionId: this.getRouteConnectionId(n4) } });\n }\n onPathFound(e51) {\n const { state: t4 } = this, n4 = t4.currentRouteId;\n if (n4 === undefined)\n return;\n this.routeSuccessCountByRouteId[n4] += 1;\n const o4 = this.getSolvedPathSegments(e51);\n for (const { regionId: e53, fromPortId: i4, toPortId: r4 } of o4)\n t4.regionSegments[e53].push([n4, i4, r4]), t4.portAssignment[i4] = t4.currentRouteNetId, t4.portAssignment[r4] = t4.currentRouteNetId, this.appendSegmentToRegionCache(e53, i4, r4);\n t4.candidateQueue.clear(), t4.currentRouteNetId = undefined, t4.currentRouteId = undefined;\n }\n computeG(e51, t4) {\n const { topology: n4, state: o4 } = this, i4 = e51.nextRegionId, r4 = o4.regionIntersectionCaches[i4], s4 = this.populateSegmentGeometryScratch(i4, e51.portId, t4), [a4, c4, l4] = Q5(r4, o4.currentRouteNetId, s4.lesserAngle, s4.greaterAngle, s4.layerMask, s4.entryExitLayerChanges);\n if (a4 \u003e 0 \u0026\u0026 this.isKnownSingleLayerRegion(i4))\n return Number.POSITIVE_INFINITY;\n const h4 = this.computeRegionCostForRegion(i4, r4.existingSameLayerIntersections + a4, r4.existingCrossingLayerIntersections + c4, r4.existingEntryExitLayerChanges + l4, r4.existingSegmentCount + 1) - r4.existingRegionCost;\n return e51.g + h4 + o4.regionCongestionCost[i4];\n }\n tryFinalAcceptance() {\n const e51 = this.getNeverSuccessfullyRoutedRoutes();\n this.stats = { ...this.stats, neverSuccessfullyRoutedRouteCount: e51.length }, this.logNeverSuccessfullyRoutedRoutes();\n }\n computeH(e51) {\n return this.problemSetup.portHCostToEndOfRoute[e51 * this.problem.routeCount + this.state.currentRouteId];\n }\n visualize() {\n return j3(this);\n }\n getOutput() {\n return Z5(this);\n }\n};\nvar H3 = (e51) =\u003e {\n const t4 = typeof e51.d?.netId == \"number\" ? e51.d.netId : typeof e51.d?.NetId == \"number\" ? e51.d.NetId : undefined;\n return Number.isFinite(t4) ? t4 : undefined;\n};\nvar V3 = (e51) =\u003e {\n const t4 = new Set;\n for (const n6 of e51.connections ?? [])\n t4.add(n6.startRegionId), t4.add(n6.endRegionId);\n const n4 = new Set(e51.regions.filter((e53) =\u003e ((e54) =\u003e {\n if (e54.d?._containsObstacle !== true)\n return false;\n if (e54.d?._containsTarget !== true)\n return true;\n const t6 = H3(e54);\n return t6 === undefined || t6 === -1;\n })(e53) \u0026\u0026 !t4.has(e53.regionId)).map((e53) =\u003e e53.regionId));\n if (n4.size === 0)\n return e51;\n const o4 = e51.ports.filter((e53) =\u003e !n4.has(e53.region1Id) \u0026\u0026 !n4.has(e53.region2Id)), i4 = (e51.connections ?? []).find((e53) =\u003e n4.has(e53.startRegionId) || n4.has(e53.endRegionId));\n if (i4)\n throw new Error(`Connection \"${i4.connectionId}\" references full-obstacle region`);\n return { ...e51, regions: e51.regions.filter((e53) =\u003e !n4.has(e53.regionId)), ports: o4 };\n};\nvar W3 = (e51) =\u003e {\n const t4 = e51.d?.bounds;\n if (t4)\n return t4;\n const n4 = e51.d?.center, o4 = e51.d?.width, i4 = e51.d?.height;\n return n4 \u0026\u0026 typeof n4.x == \"number\" \u0026\u0026 typeof n4.y == \"number\" \u0026\u0026 typeof o4 == \"number\" \u0026\u0026 typeof i4 == \"number\" ? { minX: n4.x - o4 / 2, maxX: n4.x + o4 / 2, minY: n4.y - i4 / 2, maxY: n4.y + i4 / 2 } : { minX: 0, maxX: 0, minY: 0, maxY: 0 };\n};\nvar G3 = (e51) =\u003e {\n const t4 = Number(e51.d?.z ?? 0);\n return Number.isFinite(t4) ? t4 : 0;\n};\nvar U3 = (e51) =\u003e 0.005 * G3(e51);\nvar Z3 = (e51) =\u003e Number(e51.d?.x ?? 0) + U3(e51);\nvar q3 = (e51) =\u003e Number(e51.d?.y ?? 0) + U3(e51);\nvar J3 = (e51, t4) =\u003e {\n if (!t4)\n return 0;\n const n4 = W3(t4), o4 = Z3(e51), i4 = q3(e51), r4 = n4.minX \u003c= o4 \u0026\u0026 o4 \u003c= n4.maxX, s4 = n4.minY \u003c= i4 \u0026\u0026 i4 \u003c= n4.maxY;\n if (s4 \u0026\u0026 o4 \u003e= n4.maxX) {\n const e53 = Math.max(n4.maxY - n4.minY, 0.000000001), t6 = (i4 - n4.minY) / e53;\n return Math.round(9000 * t6);\n }\n if (r4 \u0026\u0026 i4 \u003e= n4.maxY) {\n const e53 = Math.max(n4.maxX - n4.minX, 0.000000001), t6 = (n4.maxX - o4) / e53;\n return 9000 + Math.round(9000 * t6);\n }\n if (s4 \u0026\u0026 o4 \u003c= n4.minX) {\n const e53 = Math.max(n4.maxY - n4.minY, 0.000000001), t6 = (n4.maxY - i4) / e53;\n return 18000 + Math.round(9000 * t6);\n }\n if (r4 \u0026\u0026 i4 \u003c= n4.minY) {\n const e53 = Math.max(n4.maxX - n4.minX, 0.000000001), t6 = (o4 - n4.minX) / e53;\n return 27000 + Math.round(9000 * t6);\n }\n const a4 = Math.abs(o4 - n4.minX), c4 = Math.abs(o4 - n4.maxX), l4 = Math.abs(i4 - n4.minY), h4 = Math.abs(i4 - n4.maxY), d4 = Math.min(a4, c4, l4, h4), u4 = Math.max(n4.maxX - n4.minX, 0.000000001), p4 = Math.max(n4.maxY - n4.minY, 0.000000001);\n if (d4 === c4) {\n const e53 = (i4 - n4.minY) / p4;\n return Math.round(9000 * e53);\n }\n if (d4 === h4) {\n const e53 = (n4.maxX - o4) / u4;\n return 9000 + Math.round(9000 * e53);\n }\n if (d4 === a4) {\n const e53 = (n4.maxY - i4) / p4;\n return 18000 + Math.round(9000 * e53);\n }\n const m4 = (o4 - n4.minX) / u4;\n return 27000 + Math.round(9000 * m4);\n};\nvar Q3 = (e51, t4) =\u003e {\n if (!e51)\n return;\n return [...e51.pointIds].sort((e53, n4) =\u003e {\n const o4 = t4.get(e53), i4 = t4.get(n4), r4 = Number(o4?.d?.distToCentermostPortOnZ ?? Number.POSITIVE_INFINITY), s4 = Number(i4?.d?.distToCentermostPortOnZ ?? Number.POSITIVE_INFINITY);\n if (r4 !== s4)\n return r4 - s4;\n const a4 = Number(o4?.d?.z ?? 0), c4 = Number(i4?.d?.z ?? 0);\n return a4 !== c4 ? a4 - c4 : e53.localeCompare(n4);\n })[0];\n};\nvar K3 = (e51) =\u003e {\n const t4 = V3(e51), n4 = new Map, o4 = new Map, i4 = new Map, r4 = new Map((t4.solvedRoutes ?? []).map((e53) =\u003e [e53.connection.connectionId, e53]));\n t4.regions.forEach((e53, t6) =\u003e {\n n4.set(e53.regionId, t6);\n }), t4.ports.forEach((e53, t6) =\u003e {\n o4.set(e53.portId, t6), i4.set(e53.portId, e53);\n });\n const s4 = t4.regions.length, a4 = t4.ports.length, c4 = t4.regions.map((e53) =\u003e e53.pointIds.map((e54) =\u003e o4.get(e54)).filter((e54) =\u003e e54 !== undefined)), l4 = Array.from({ length: a4 }, () =\u003e []), h4 = new Float64Array(s4), d4 = new Float64Array(s4), u4 = new Float64Array(s4), p4 = new Float64Array(s4), m4 = new Int32Array(s4), g4 = new Int32Array(s4).fill(-1), f4 = new Int8Array(s4);\n t4.regions.forEach((e53, t6) =\u003e {\n const n6 = ((e54) =\u003e {\n const t7 = W3(e54), n7 = typeof e54.d?.width == \"number\" ? e54.d.width : t7.maxX - t7.minX, o7 = typeof e54.d?.height == \"number\" ? e54.d.height : t7.maxY - t7.minY;\n return { centerX: typeof e54.d?.center?.x == \"number\" ? e54.d.center.x : (t7.minX + t7.maxX) / 2, centerY: typeof e54.d?.center?.y == \"number\" ? e54.d.center.y : (t7.minY + t7.maxY) / 2, width: n7, height: o7 };\n })(e53);\n h4[t6] = n6.width, d4[t6] = n6.height, u4[t6] = n6.centerX, p4[t6] = n6.centerY, m4[t6] = ((e54) =\u003e {\n const t7 = e54.d?.availableZ;\n if (!Array.isArray(t7))\n return 0;\n let n7 = 0;\n for (const e55 of t7)\n !Number.isInteger(e55) || e55 \u003c 0 || e55 \u003e= 31 || (n7 |= 1 \u003c\u003c e55);\n return n7;\n })(e53);\n const o6 = H3(e53);\n o6 !== undefined \u0026\u0026 (g4[t6] = o6, f4[t6] = 1);\n });\n const _4 = new Int32Array(a4), y4 = new Int32Array(a4), b4 = new Float64Array(a4), x4 = new Float64Array(a4), v4 = new Int32Array(a4);\n t4.ports.forEach((e53, o6) =\u003e {\n const i6 = n4.get(e53.region1Id), r6 = n4.get(e53.region2Id);\n if (i6 === undefined || r6 === undefined)\n throw new Error(`Port \"${e53.portId}\" references missing regions \"${e53.region1Id}\" or \"${e53.region2Id}\"`);\n l4[o6] = [i6, r6], b4[o6] = Z3(e53), x4[o6] = q3(e53), v4[o6] = G3(e53), _4[o6] = J3(e53, t4.regions[i6]), y4[o6] = J3(e53, t4.regions[r6]);\n });\n const I4 = t4.regions.map((e53, t6) =\u003e ((e54, t7) =\u003e {\n const n6 = e54.d \u0026\u0026 typeof e54.d == \"object\" \u0026\u0026 !Array.isArray(e54.d) ? { ...e54.d } : { value: e54.d };\n return n6.layer = t7, Object.defineProperty(n6, \"serializedRegionId\", { value: e54.regionId, enumerable: false, configurable: true, writable: true }), n6;\n })(e53, ((e54) =\u003e F5(j5(m4[e54])) ?? F5((c4[e54] ?? []).map((e55) =\u003e v4[e55])) ?? \"z0\")(t6))), S4 = t4.ports.map((e53, t6) =\u003e ((e54, t7) =\u003e {\n const n6 = e54.d \u0026\u0026 typeof e54.d == \"object\" \u0026\u0026 !Array.isArray(e54.d) ? { ...e54.d } : { value: e54.d };\n return n6.layer = t7, Object.defineProperty(n6, \"serializedPortId\", { value: e54.portId, enumerable: false, configurable: true, writable: true }), n6;\n })(e53, F5([v4[t6]]) ?? \"z0\")), C = t4.connections ?? [], P = new Map;\n let M = 0;\n const w = (e53) =\u003e {\n const t6 = e53.mutuallyConnectedNetworkId ?? e53.connectionId;\n let n6 = P.get(t6);\n return n6 === undefined \u0026\u0026 (n6 = M++, P.set(t6, n6)), n6;\n }, N = Array.from({ length: s4 }, () =\u003e new Set), R4 = (e53, t6) =\u003e {\n const o6 = n4.get(e53);\n if (o6 === undefined)\n throw new Error(`Connection references missing region \"${e53}\"`);\n N[o6].add(t6);\n };\n C.forEach((e53) =\u003e {\n const t6 = w(e53);\n R4(e53.startRegionId, t6), R4(e53.endRegionId, t6);\n }), N.forEach((e53, t6) =\u003e {\n f4[t6] !== 1 \u0026\u0026 e53.size === 1 \u0026\u0026 (g4[t6] = [...e53][0]);\n });\n const T2 = C.map((e53) =\u003e {\n const n6 = r4.get(e53.connectionId), o6 = ((e54, t6) =\u003e e54.ports.filter((e55) =\u003e e55.region1Id === t6.startRegionId \u0026\u0026 e55.region2Id === t6.endRegionId || e55.region2Id === t6.startRegionId \u0026\u0026 e55.region1Id === t6.endRegionId).map((e55) =\u003e e55.portId))(t4, e53);\n return { connection: e53, solvedRoute: n6, sharedPortIds: o6 };\n }).filter(({ solvedRoute: e53, sharedPortIds: t6 }) =\u003e t6.length === 0 || (e53?.path.length ?? 0) \u003e 1), E4 = T2.length, A4 = new Int8Array(a4).fill(1), O4 = new Int32Array(E4), k4 = new Int32Array(E4), D4 = new Int32Array(E4);\n T2.forEach(({ connection: e53, solvedRoute: n6 }, r6) =\u003e {\n const s6 = Q3(t4.regions.find((t6) =\u003e t6.regionId === e53.startRegionId), i4), a6 = Q3(t4.regions.find((t6) =\u003e t6.regionId === e53.endRegionId), i4), c5 = n6?.path[0]?.portId ?? s6, l5 = n6?.path[n6.path.length - 1]?.portId ?? a6, h5 = c5 !== undefined ? o4.get(c5) : undefined, d6 = l5 !== undefined ? o4.get(l5) : undefined;\n if (h5 === undefined || d6 === undefined)\n throw new Error(`Connection \"${e53.connectionId}\" could not be mapped to route endpoints`);\n O4[r6] = h5, k4[r6] = d6, D4[r6] = w(e53);\n });\n const L4 = { portCount: a4, regionCount: s4, regionIncidentPorts: c4, incidentPortRegion: l4, regionWidth: h4, regionHeight: d4, regionCenterX: u4, regionCenterY: p4, regionAvailableZMask: m4, regionMetadata: I4, portAngleForRegion1: _4, portAngleForRegion2: y4, portX: b4, portY: x4, portZ: v4, portMetadata: S4 }, z4 = { routeCount: E4, portSectionMask: A4, routeMetadata: T2.map(({ connection: e53 }) =\u003e e53), routeStartPort: O4, routeEndPort: k4, routeNet: D4, regionNetId: g4 }, B4 = [], F4 = [];\n for (const { solvedRoute: e53 } of T2) {\n if (!e53) {\n B4.push([]), F4.push([]);\n continue;\n }\n const t6 = [], i6 = [];\n for (let r6 = 1;r6 \u003c e53.path.length; r6++) {\n const s6 = e53.path[r6 - 1], a6 = e53.path[r6], c5 = s6?.portId, l5 = a6?.portId, h5 = c5 !== undefined ? o4.get(c5) : undefined, d6 = l5 !== undefined ? o4.get(l5) : undefined;\n if (h5 === undefined || d6 === undefined)\n continue;\n const u6 = typeof s6?.nextRegionId == \"string\" ? s6.nextRegionId : typeof a6?.lastRegionId == \"string\" ? a6.lastRegionId : undefined;\n t6.push([h5, d6]), i6.push(u6 !== undefined ? n4.get(u6) : undefined);\n }\n B4.push(t6), F4.push(i6);\n }\n return { topology: L4, problem: z4, solution: { solvedRoutePathSegments: B4, solvedRoutePathRegionIds: F4 } };\n};\nNumber.POSITIVE_INFINITY;\nvar n4 = 0.000000001;\nvar o4 = (e51) =\u003e typeof e51 == \"object\" \u0026\u0026 e51 !== null;\nvar i4 = (e51, t4 = 0) =\u003e typeof e51 == \"number\" \u0026\u0026 Number.isFinite(e51) ? e51 : t4;\nvar r4 = (e51) =\u003e {\n const t4 = ((e53) =\u003e {\n const t6 = Math.min(e53.minX, e53.maxX), n6 = Math.max(e53.minX, e53.maxX), o6 = Math.min(e53.minY, e53.maxY), i6 = Math.max(e53.minY, e53.maxY);\n return { minX: t6, maxX: n6 \u003e t6 ? n6 : t6 + n4, minY: o6, maxY: i6 \u003e o6 ? i6 : o6 + n4 };\n })(e51);\n return [{ x: t4.maxX, y: t4.minY }, { x: t4.maxX, y: t4.maxY }, { x: t4.minX, y: t4.maxY }, { x: t4.minX, y: t4.minY }];\n};\nvar s4 = (e51, t4) =\u003e {\n const n6 = e51.filter((e53) =\u003e Number.isFinite(e53.x) \u0026\u0026 Number.isFinite(e53.y)), o6 = n6.length \u003e= 3 ? n6 : r4(t4), i6 = ((e53) =\u003e {\n let t6 = 0;\n for (let n7 = 0;n7 \u003c e53.length; n7++) {\n const o7 = e53[n7], i7 = e53[(n7 + 1) % e53.length];\n t6 += o7.x * i7.y - o7.y * i7.x;\n }\n return t6;\n })(o6);\n if (Math.abs(i6) \u003c= Number.EPSILON)\n return r4(t4);\n return ((e53) =\u003e {\n if (e53.length \u003c 3)\n throw new Error(\"Convex polygon requires at least three points\");\n return e53;\n })(i6 \u003c 0 ? [...o6].reverse() : [...o6]);\n};\nvar a4 = (e51) =\u003e {\n const t4 = ((e53) =\u003e {\n const t6 = e53.d, n6 = t6?.bounds;\n if (n6 \u0026\u0026 typeof n6.minX == \"number\" \u0026\u0026 typeof n6.maxX == \"number\" \u0026\u0026 typeof n6.minY == \"number\" \u0026\u0026 typeof n6.maxY == \"number\")\n return { minX: n6.minX, maxX: n6.maxX, minY: n6.minY, maxY: n6.maxY };\n const o6 = t6?.center, i6 = i4(t6?.width, 0), r6 = i4(t6?.height, 0);\n return o6 \u0026\u0026 typeof o6.x == \"number\" \u0026\u0026 typeof o6.y == \"number\" ? { minX: o6.x - i6 / 2, maxX: o6.x + i6 / 2, minY: o6.y - r6 / 2, maxY: o6.y + r6 / 2 } : { minX: 0, maxX: n4, minY: 0, maxY: n4 };\n })(e51);\n return s4(((e53) =\u003e {\n const t6 = e53.d, n6 = t6?.polygon ?? t6?.points ?? t6?.vertices;\n if (!Array.isArray(n6))\n return;\n const o6 = n6.map((e54) =\u003e {\n if (!o4(e54))\n return;\n const { x: t7, y: n7 } = e54;\n return typeof t7 == \"number\" \u0026\u0026 typeof n7 == \"number\" ? { x: t7, y: n7 } : undefined;\n }).filter((e54) =\u003e e54 !== undefined);\n if (o6.length \u003e 1) {\n const e54 = o6[0], t7 = o6[o6.length - 1];\n e54.x === t7.x \u0026\u0026 e54.y === t7.y \u0026\u0026 o6.pop();\n }\n return o6.length \u003e= 3 ? o6 : undefined;\n })(e51) ?? r4(t4), t4);\n};\nvar c4 = (e51) =\u003e {\n let t4 = 0, n6 = 0, o6 = 0, i6 = 0, r6 = Number.POSITIVE_INFINITY, s6 = Number.NEGATIVE_INFINITY, a6 = Number.POSITIVE_INFINITY, c5 = Number.NEGATIVE_INFINITY;\n for (let l5 = 0;l5 \u003c e51.length; l5++) {\n const h5 = e51[l5], d6 = e51[(l5 + 1) % e51.length], u4 = h5.x * d6.y - d6.x * h5.y;\n t4 += u4, n6 += (h5.x + d6.x) * u4, o6 += (h5.y + d6.y) * u4, i6 += Math.hypot(d6.x - h5.x, d6.y - h5.y), r6 = Math.min(r6, h5.x), s6 = Math.max(s6, h5.x), a6 = Math.min(a6, h5.y), c5 = Math.max(c5, h5.y);\n }\n const l4 = Math.abs(t4) / 2, h4 = Math.abs(t4) \u003e Number.EPSILON ? 3 * t4 : Number.NaN, d4 = e51.reduce((t6, n7) =\u003e ({ x: t6.x + n7.x / e51.length, y: t6.y + n7.y / e51.length }), { x: 0, y: 0 });\n return { area: l4, perimeter: i6, centerX: Number.isFinite(h4) ? n6 / h4 : d4.x, centerY: Number.isFinite(h4) ? o6 / h4 : d4.y, bounds: { minX: r6, maxX: s6, minY: a6, maxY: c5 } };\n};\nvar l4 = (e51, t4, n6, o6) =\u003e {\n if (n6 \u003c= 0)\n return { boundaryPosition: 0, edgeIndex: 0, edgeT: 0 };\n let i6 = Number.POSITIVE_INFINITY, r6 = 0, s6 = 0, a6 = 0, c5 = 0;\n for (let n7 = 0;n7 \u003c t4.length; n7++) {\n const o7 = t4[n7], l5 = t4[(n7 + 1) % t4.length], h4 = l5.x - o7.x, d4 = l5.y - o7.y, u4 = h4 * h4 + d4 * d4, p4 = Math.sqrt(u4), m4 = u4 \u003c= Number.EPSILON ? 0 : ((e51.x - o7.x) * h4 + (e51.y - o7.y) * d4) / u4, g4 = Math.min(1, Math.max(0, m4)), f4 = o7.x + h4 * g4, _4 = o7.y + d4 * g4, y4 = e51.x - f4, b4 = e51.y - _4, x4 = y4 * y4 + b4 * b4;\n x4 \u003c i6 \u0026\u0026 (i6 = x4, r6 = n7, s6 = g4, a6 = c5 + p4 * g4), c5 += p4;\n }\n return { boundaryPosition: Math.round(a6 / n6 * o6) % o6, edgeIndex: r6, edgeT: s6 };\n};\nvar h4 = (e51, t4) =\u003e {\n const n6 = e51.regionMetadata?.[t4];\n return o4(n6) \u0026\u0026 typeof n6.serializedRegionId == \"string\" ? n6.serializedRegionId : `region-${t4}`;\n};\nvar d4 = (e51, t4) =\u003e {\n const n6 = e51.portMetadata?.[t4];\n return o4(n6) \u0026\u0026 typeof n6.serializedPortId == \"string\" ? n6.serializedPortId : `port-${t4}`;\n};\nvar u4 = (e51, t4, n6, o6) =\u003e {\n const i6 = { ...o4(e51) ? { ...e51 } : e51 === undefined ? {} : { value: e51 }, polygon: n6, sourceBounds: o6 };\n return Object.defineProperty(i6, \"serializedRegionId\", { value: t4, enumerable: false, configurable: true, writable: true }), i6;\n};\nvar p4 = (e51, t4) =\u003e {\n const n6 = new Map, o6 = new Map, i6 = new Map, r6 = new Map;\n for (let t6 = 0;t6 \u003c e51.regionCount; t6++)\n n6.set(h4(e51, t6), t6);\n for (let t6 = 0;t6 \u003c e51.portCount; t6++)\n o6.set(d4(e51, t6), t6);\n for (let e53 = 0;e53 \u003c t4.routeCount; e53++) {\n const n7 = t4.routeMetadata?.[e53];\n if (!o4(n7))\n continue;\n typeof n7.connectionId == \"string\" \u0026\u0026 i6.set(n7.connectionId, e53);\n const o7 = typeof n7.mutuallyConnectedNetworkId == \"string\" ? n7.mutuallyConnectedNetworkId : typeof n7.connectionId == \"string\" ? n7.connectionId : undefined;\n o7 !== undefined \u0026\u0026 r6.set(o7, t4.routeNet[e53]);\n }\n return { serializedRegionIdToRegionId: n6, serializedPortIdToPortId: o6, connectionIdToRouteId: i6, netIdToNetIndex: r6 };\n};\nvar m4 = (e51, t4, n6) =\u003e {\n const o6 = e51.incidentPortRegion[t4];\n return o6[0] === n6 || o6[1] !== n6 ? e51.portBoundaryPositionForRegion1[t4] : e51.portBoundaryPositionForRegion2[t4];\n};\nvar g4 = class extends X3 {\n constructor(e51, t4, n6) {\n super(e51, t4, n6), this.topology = e51, this.problem = t4;\n }\n polySegmentGeometryScratch = { lesserAngle: 0, greaterAngle: 0, layerMask: 0, entryExitLayerChanges: 0 };\n populateSegmentGeometryScratch(e51, t4, n6) {\n const { topology: o6 } = this, i6 = this.polySegmentGeometryScratch, r6 = m4(o6, t4, e51), s6 = m4(o6, n6, e51), a6 = o6.portZ[t4], c5 = o6.portZ[n6];\n return i6.lesserAngle = r6 \u003c s6 ? r6 : s6, i6.greaterAngle = r6 \u003c s6 ? s6 : r6, i6.layerMask = 1 \u003c\u003c a6 | 1 \u003c\u003c c5, i6.entryExitLayerChanges = a6 !== c5 ? 1 : 0, i6;\n }\n computeRegionCostForRegion(e51, t4, n6, o6, i6) {\n return J5(this.topology.regionArea[e51], t4, n6, o6, i6, this.topology.regionAvailableZMask?.[e51] ?? 0);\n }\n visualize() {\n return M4(this);\n }\n};\nvar f4 = (...e51) =\u003e e51.filter((e53) =\u003e Boolean(e53)).join(`\n`);\nvar _4 = (e51, t4) =\u003e {\n const n6 = e51.problem.routeMetadata?.[t4];\n return n6?.connectionId ?? n6?.mutuallyConnectedNetworkId ?? `route-${t4}`;\n};\nvar y4 = (e51, t4, n6 = 0.85) =\u003e {\n const o6 = `${e51.problem.routeNet[t4]}:${_4(e51, t4)}`;\n let i6 = 0;\n for (let e53 = 0;e53 \u003c o6.length; e53++)\n i6 = 17777 * o6.charCodeAt(e53) + ((i6 \u003c\u003c 5) - i6);\n return `hsla(${Math.abs(i6) % 360}, 70%, 45%, ${n6})`;\n};\nvar b4 = (e51, t4) =\u003e {\n const n6 = e51.regionVertexStart[t4], o6 = e51.regionVertexCount[t4], i6 = [];\n for (let t6 = 0;t6 \u003c o6; t6++) {\n const o7 = n6 + t6;\n i6.push({ x: e51.regionVertexX[o7], y: e51.regionVertexY[o7] });\n }\n return i6;\n};\nvar x4 = (e51, t4) =\u003e {\n const n6 = e51.state.regionIntersectionCaches[t4]?.existingRegionCost ?? 0, o6 = Math.min(1, Math.max(0, Math.pow(n6, 0.8))), i6 = Math.round(245 - 105 * o6);\n return `rgba(245, ${Math.round(248 - 168 * o6)}, ${i6}, ${0.18 + 0.48 * o6})`;\n};\nvar v4 = (e51, t4) =\u003e {\n const n6 = e51.state.regionIntersectionCaches[t4], o6 = h4(e51.topology, t4), i6 = e51.problem.regionNetId[t4];\n return f4(`region: ${o6}`, `net: ${i6 === -1 ? \"free\" : i6}`, `area: ${e51.topology.regionArea[t4].toFixed(3)}`, `cost: ${(n6?.existingRegionCost ?? 0).toFixed(3)}`, `same layer X: ${n6?.existingSameLayerIntersections ?? 0}`, `trans X: ${n6?.existingCrossingLayerIntersections ?? 0}`, `entry exit X: ${n6?.existingEntryExitLayerChanges ?? 0}`);\n};\nvar I4 = (e51, t4) =\u003e F5(j5(e51.topology.regionAvailableZMask?.[t4] ?? 0)) ?? F5((e51.topology.regionIncidentPorts[t4] ?? []).map((t6) =\u003e e51.topology.portZ[t6])) ?? \"z0\";\nvar S4 = (e51, t4) =\u003e ({ x: e51.topology.portX[t4], y: e51.topology.portY[t4] });\nvar C4 = (e51, t4) =\u003e F5([e51.topology.portZ[t4]]) ?? \"z0\";\nvar P4 = (e51, t4) =\u003e {\n const [n6, o6] = e51.topology.incidentPortRegion[t4] ?? [];\n return f4(`port: ${d4(e51.topology, t4)}`, `connects: ${n6 ?? \"?\"} \u003c-\u003e ${o6 ?? \"?\"}`, `z: ${e51.topology.portZ[t4]}`);\n};\nvar M4 = (e51) =\u003e {\n const t4 = { arrows: [], circles: [], infiniteLines: [], lines: [], points: [], polygons: [], rects: [], texts: [], title: \"Poly HyperGraph\", coordinateSystem: \"cartesian\" };\n for (let n7 = 0;n7 \u003c e51.topology.regionCount; n7++)\n t4.polygons.push({ points: b4(e51.topology, n7), fill: x4(e51, n7), stroke: \"rgba(80, 80, 120, 0.55)\", layer: I4(e51, n7), label: v4(e51, n7) });\n for (let n7 = 0;n7 \u003c e51.topology.portCount; n7++)\n t4.circles.push({ center: S4(e51, n7), radius: 0.05, fill: e51.topology.portZ[n7] \u003e 0 ? \"rgba(52, 152, 219, 0.55)\" : \"rgba(80, 80, 80, 0.45)\", layer: C4(e51, n7), label: P4(e51, n7) });\n ((e53, t6) =\u003e {\n for (let n7 = 0;n7 \u003c e53.problem.routeCount; n7++) {\n const o6 = e53.problem.routeStartPort[n7], i6 = e53.problem.routeEndPort[n7], r6 = _4(e53, n7), s6 = y4(e53, n7);\n t6.points.push({ ...S4(e53, o6), color: s6, layer: C4(e53, o6), label: f4(`route: ${r6}`, \"endpoint: start\", P4(e53, o6)) }), t6.points.push({ ...S4(e53, i6), color: s6, layer: C4(e53, i6), label: f4(`route: ${r6}`, \"endpoint: end\", P4(e53, i6)) });\n }\n })(e51, t4), ((e53, t6) =\u003e {\n for (let n7 = 0;n7 \u003c e53.state.regionSegments.length; n7++)\n for (const [o6, i6, r6] of e53.state.regionSegments[n7] ?? [])\n t6.lines.push({ points: [S4(e53, i6), S4(e53, r6)], strokeColor: y4(e53, o6), layer: F5([e53.topology.portZ[i6], e53.topology.portZ[r6]]) ?? \"z0\", label: f4(`route: ${_4(e53, o6)}`, `region: ${h4(e53.topology, n7)}`) });\n })(e51, t4), ((e53, t6) =\u003e {\n if (e53.solved)\n return;\n const n7 = e53.state.candidateQueue.toArray().sort((e54, t7) =\u003e e54.f - t7.f).slice(0, 10);\n for (let o7 = 0;o7 \u003c n7.length; o7++) {\n const i7 = n7[o7];\n t6.points.push({ ...S4(e53, i7.portId), color: o7 === 0 ? \"green\" : \"rgba(128, 128, 128, 0.4)\", layer: C4(e53, i7.portId), label: f4(P4(e53, i7.portId), `g: ${i7.g.toFixed(2)}`, `h: ${i7.h.toFixed(2)}`, `f: ${i7.f.toFixed(2)}`) });\n }\n const o6 = n7[0];\n if (!o6)\n return;\n const i6 = [];\n let r6 = o6;\n for (;r6; )\n i6.unshift(S4(e53, r6.portId)), r6 = r6.prevCandidate;\n if (i6.length \u003c= 1)\n return;\n const s6 = e53.state.currentRouteId;\n t6.lines.push({ points: i6, strokeColor: s6 !== undefined ? y4(e53, s6, 0.95) : \"rgba(0, 160, 120, 0.95)\", strokeDash: \"4 3\", layer: C4(e53, o6.portId), label: f4(s6 !== undefined ? `route: ${_4(e53, s6)}` : undefined, \"active candidate path\", `candidate port: ${d4(e53.topology, o6.portId)}`) });\n })(e51, t4);\n const n6 = e51.state.unroutedRoutes.length + (e51.state.currentRouteId === undefined ? 0 : 1);\n return t4.title = [\"Poly HyperGraph\", `iter=${e51.iterations}`, `pending=${n6}`, e51.failed ? \"failed\" : e51.solved ? \"solved\" : \"running\"].join(\" | \"), t4;\n};\nnew Int32Array(0);\nvar N4 = (e51) =\u003e (e51.ccwRotationDegrees ?? 0) * Math.PI / 180;\nvar R4 = (e51, t4 = 8) =\u003e {\n const n6 = e51.width / 2, o6 = e51.height / 2, i6 = N4(e51), r6 = Math.cos(i6), s6 = Math.sin(i6);\n return Array.from({ length: t4 }, (i7, a6) =\u003e {\n const c5 = 2 * Math.PI * a6 / t4, l5 = n6 * Math.cos(c5), h5 = o6 * Math.sin(c5);\n return { x: e51.center.x + l5 * r6 - h5 * s6, y: e51.center.y + l5 * s6 + h5 * r6 };\n });\n};\nvar T4 = (e51) =\u003e (e51.obstacles ?? []).filter((e53) =\u003e e53.type === \"oval\").map((e53) =\u003e ({ points: R4(e53), layers: e53.layers, zLayers: e53.__zLayers, isCopperPour: e53.isCopperPour }));\nvar E4 = (e51, t4) =\u003e (e51.obstacles ?? []).flatMap((n6, o6) =\u003e {\n if (!Array.isArray(n6.connectedTo) || n6.connectedTo.length === 0)\n return [];\n const i6 = k2(z2(n6, e51.layerCount), e51.layerCount);\n if (i6.length === 0)\n return [];\n let r6;\n const s6 = n6.type;\n if (s6 === \"rect\")\n r6 = ((e53, t6 = 0) =\u003e {\n const n7 = e53.width / 2 + t6, o7 = e53.height / 2 + t6, i7 = N4(e53), r7 = Math.cos(i7), s7 = Math.sin(i7);\n return [{ localX: -n7, localY: -o7 }, { localX: n7, localY: -o7 }, { localX: n7, localY: o7 }, { localX: -n7, localY: o7 }].map(({ localX: t7, localY: n8 }) =\u003e ({ x: e53.center.x + t7 * r7 - n8 * s7, y: e53.center.y + t7 * s7 + n8 * r7 }));\n })(n6, t4);\n else {\n if (s6 !== \"oval\")\n return [];\n r6 = d5({ polygon: { points: R4(n6), layers: n6.layers, zLayers: n6.__zLayers, isCopperPour: n6.isCopperPour }, clearance: t4, verticesOnly: true });\n }\n return [{ regionId: `connected-obstacle-${o6}`, polygon: r6, availableZ: i6, connectedTo: n6.connectedTo, d: { obstacleIndex: o6, obstacleType: s6, connectedTo: n6.connectedTo } }];\n});\nvar A4 = (e51) =\u003e typeof e51 == \"object\" \u0026\u0026 e51 !== null ? e51 : {};\nvar O4 = (e51) =\u003e typeof e51 == \"object\" \u0026\u0026 e51 !== null ? e51 : {};\nvar k4 = (e51, t4) =\u003e {\n const n6 = A4(e51).serializedRegionId;\n return typeof n6 == \"string\" ? n6 : `region-${t4}`;\n};\nvar D4 = (e51, t4) =\u003e {\n const n6 = O4(e51);\n return typeof n6.serializedPortId == \"string\" ? n6.serializedPortId : typeof n6.portId == \"string\" ? n6.portId : `poly-port-${t4}`;\n};\nvar L4 = (e51) =\u003e {\n const t4 = O4(e51);\n return { prevPortPointId: typeof t4.prevPortPointId == \"string\" ? t4.prevPortPointId : undefined, nextPortPointId: typeof t4.nextPortPointId == \"string\" ? t4.nextPortPointId : undefined };\n};\nvar z4 = (e51) =\u003e {\n const t4 = A4(e51).polygon;\n if (Array.isArray(t4) \u0026\u0026 !(t4.length \u003c 3))\n return t4.every((e53) =\u003e typeof e53 == \"object\" \u0026\u0026 e53 !== null \u0026\u0026 typeof e53.x == \"number\" \u0026\u0026 typeof e53.y == \"number\") ? t4 : undefined;\n};\nvar B4 = class extends ni {\n constructor(e51) {\n super(), this.params = e51, this.effort = e51.effort ?? 1, this.clearance = e51.srj.defaultObstacleMargin ?? e51.srj.minTraceWidth;\n const t4 = (t6) =\u003e {\n return z5({ bounds: e51.srj.bounds, rects: (n7 = e51.srj, (n7.obstacles ?? []).filter((e53) =\u003e e53.type === \"rect\").map((e53) =\u003e ({ center: e53.center, width: e53.width, height: e53.height, ccwRotation: N4(e53), layers: e53.layers, zLayers: e53.__zLayers, isCopperPour: e53.isCopperPour }))), polygons: T4(e51.srj), clearance: this.clearance, concavityTolerance: e51.concavityTolerance ?? 0, layerCount: e51.srj.layerCount, layerMergeMode: e51.layerMergeMode ?? \"same\", useConstrainedDelaunay: t6, usePolyanyaMerge: e51.usePolyanyaMerge ?? false, viaSegments: e51.viaSegments ?? 8 });\n var n7;\n }, n6 = e51.useConstrainedDelaunay ?? true;\n try {\n this.convexRegions = t4(n6);\n } catch (e53) {\n if (!n6)\n throw e53;\n this.usedUnconstrainedDelaunayFallback = true, this.convexRegions = t4(false);\n }\n var o6;\n this.serializedGraph = a5({ regions: this.convexRegions.regions, availableZ: this.convexRegions.availableZ, layerCount: e51.srj.layerCount, connections: (o6 = e51.srj, o6.connections.flatMap((e53) =\u003e {\n const t6 = e53.pointsToConnect ?? [];\n if (t6.length \u003c 2)\n return [];\n const n7 = t6[0];\n return t6.slice(1).map((t7, o7) =\u003e {\n const i7 = ((e54, t8, n8, o8) =\u003e {\n const i8 = e54.pointsToConnect.length === 2 ? e54.name : `${e54.name}::${o8}`;\n return { ...e54, name: i8, __rootConnectionNames: e54.__rootConnectionNames ?? [e54.name], pointsToConnect: [t8, n8] };\n })(e53, n7, t7, o7);\n return { connectionId: i7.name, mutuallyConnectedNetworkId: i7.__rootConnectionNames?.[0] ?? i7.name, start: n7, end: t7, simpleRouteConnection: i7 };\n });\n })), obstacleRegions: E4(e51.srj, this.clearance), portSpacing: e51.portSpacing ?? j2, portMarginFromSegmentEndpoint: e51.portMarginFromSegmentEndpoint ?? $2 }), this.loaded = ((e53, t6 = {}) =\u003e {\n const n7 = t6.boundaryCoordinateScale ?? 36000, o7 = K3(e53), { topology: i7, problem: r6, solution: s6 } = o7, a6 = new Map(e53.regions.map((e54) =\u003e [e54.regionId, e54])), c5 = [];\n for (let e54 = 0;e54 \u003c i7.regionCount; e54++) {\n const t7 = h4(i7, e54), n8 = a6.get(t7), o8 = n8 ? a4(n8) : r4({ minX: i7.regionCenterX[e54] - i7.regionWidth[e54] / 2, maxX: i7.regionCenterX[e54] + i7.regionWidth[e54] / 2, minY: i7.regionCenterY[e54] - i7.regionHeight[e54] / 2, maxY: i7.regionCenterY[e54] + i7.regionHeight[e54] / 2 });\n c5.push(o8);\n }\n const l5 = c5.reduce((e54, t7) =\u003e e54 + t7.length, 0), h5 = new Int32Array(i7.regionCount), d6 = new Int32Array(i7.regionCount), u6 = new Float64Array(l5), p6 = new Float64Array(l5), m6 = new Float64Array(i7.regionCount), g6 = new Float64Array(i7.regionCount), f6 = new Float64Array(i7.regionCount), _5 = new Float64Array(i7.regionCount), y6 = new Float64Array(i7.regionCount), b6 = new Float64Array(i7.regionCount), x6 = new Float64Array(i7.regionCount), v6 = new Float64Array(i7.regionCount), I6 = new Float64Array(i7.regionCount), S6 = new Float64Array(i7.regionCount), C = new Array(i7.regionCount);\n let P = 0;\n for (let e54 = 0;e54 \u003c i7.regionCount; e54++) {\n const t7 = c5[e54], n8 = c4(t7), o8 = Math.sqrt(Math.max(n8.area, n4));\n h5[e54] = P, d6[e54] = t7.length, m6[e54] = n8.area, g6[e54] = n8.perimeter, f6[e54] = n8.centerX, _5[e54] = n8.centerY, y6[e54] = n8.bounds.minX, b6[e54] = n8.bounds.maxX, x6[e54] = n8.bounds.minY, v6[e54] = n8.bounds.maxY, I6[e54] = o8, S6[e54] = o8, C[e54] = u4(i7.regionMetadata?.[e54], h4(i7, e54), t7, n8.bounds);\n for (const e55 of t7)\n u6[P] = e55.x, p6[P] = e55.y, P += 1;\n }\n const M = new Int32Array(i7.portCount), w = new Int32Array(i7.portCount), N = new Int32Array(i7.portCount), R6 = new Int32Array(i7.portCount), T2 = new Float64Array(i7.portCount), E6 = new Float64Array(i7.portCount);\n for (let e54 = 0;e54 \u003c i7.portCount; e54++) {\n const t7 = { x: i7.portX[e54], y: i7.portY[e54] }, [o8, r7] = i7.incidentPortRegion[e54] ?? [];\n if (o8 !== undefined) {\n const i8 = l4(t7, c5[o8], g6[o8], n7);\n M[e54] = i8.boundaryPosition, N[e54] = i8.edgeIndex, T2[e54] = i8.edgeT;\n }\n if (r7 !== undefined) {\n const o9 = l4(t7, c5[r7], g6[r7], n7);\n w[e54] = o9.boundaryPosition, R6[e54] = o9.edgeIndex, E6[e54] = o9.edgeT;\n }\n }\n for (let e54 = 0;e54 \u003c i7.regionCount; e54++)\n C[e54].layer = F5(j5(i7.regionAvailableZMask?.[e54] ?? 0)) ?? F5((i7.regionIncidentPorts[e54] ?? []).map((e55) =\u003e i7.portZ[e55])) ?? \"z0\";\n const A6 = { ...i7, regionWidth: I6, regionHeight: S6, regionCenterX: f6, regionCenterY: _5, regionMetadata: C, portAngleForRegion1: M, portAngleForRegion2: w, regionVertexStart: h5, regionVertexCount: d6, regionVertexX: u6, regionVertexY: p6, regionArea: m6, regionPerimeter: g6, regionBoundsMinX: y6, regionBoundsMaxX: b6, regionBoundsMinY: x6, regionBoundsMaxY: v6, portBoundaryPositionForRegion1: M, portBoundaryPositionForRegion2: w, portEdgeIndexForRegion1: N, portEdgeIndexForRegion2: R6, portEdgeTForRegion1: T2, portEdgeTForRegion2: E6 };\n return { topology: A6, problem: r6, solution: s6, mapping: p4(A6, r6) };\n })(this.serializedGraph), this.reservedRegionCount = ((e53, t6) =\u003e {\n const n7 = e53.problem.regionNetId;\n if (!n7)\n return 0;\n const o7 = new Map;\n for (const e54 of t6.regions) {\n const t7 = typeof e54.d?.netId == \"number\" ? e54.d.netId : typeof e54.d?.NetId == \"number\" ? e54.d.NetId : undefined;\n Number.isInteger(t7) \u0026\u0026 t7 \u003e= 0 \u0026\u0026 o7.set(e54.regionId, t7);\n }\n let i7 = 0;\n for (let t7 = 0;t7 \u003c e53.topology.regionCount; t7++) {\n const r6 = e53.topology.regionMetadata?.[t7], s6 = typeof r6 == \"object\" \u0026\u0026 r6 !== null ? r6.serializedRegionId : undefined;\n if (typeof s6 != \"string\")\n continue;\n const a6 = o7.get(s6);\n a6 !== undefined \u0026\u0026 (n7[t7] = a6, i7 += 1);\n }\n return i7;\n })(this.loaded, this.serializedGraph);\n const i6 = { DISTANCE_TO_COST: 0.05, RIP_THRESHOLD_START: 0.05, RIP_THRESHOLD_END: 0.8, RIP_CONGESTION_REGION_COST_FACTOR: 0.1, RIP_THRESHOLD_RAMP_ATTEMPTS: Math.max(1, Math.ceil(10 * this.effort)), MAX_ITERATIONS: Math.max(1e5, Math.ceil(1e7 * this.effort)) };\n this.polySolver = new g4(this.loaded.topology, this.loaded.problem, i6), this.activeSubSolver = this.polySolver, this.MAX_ITERATIONS = i6.MAX_ITERATIONS + 1000, this.inputNodeWithPortPoints = this.createInputNodesWithPortPoints();\n }\n getSolverName() {\n return \"PolyHypergraphPortPointPathingSolver\";\n }\n convexRegions;\n serializedGraph;\n loaded;\n polySolver;\n inputNodeWithPortPoints = [];\n nodesWithPortPoints = [];\n reservedRegionCount = 0;\n clearance;\n effort;\n usedUnconstrainedDelaunayFallback = false;\n createInputNodesWithPortPoints() {\n const { topology: e51 } = this.loaded, t4 = [];\n for (let n6 = 0;n6 \u003c e51.regionCount; n6++) {\n const o6 = A4(e51.regionMetadata?.[n6] ?? {}), i6 = k4(o6, n6);\n if (i6.startsWith(\"terminal-\"))\n continue;\n const r6 = (e51.regionIncidentPorts[n6] ?? []).map((t6) =\u003e {\n const n7 = e51.incidentPortRegion[t6] ?? [], o7 = e51.portMetadata?.[t6];\n return { portPointId: D4(o7, t6), x: e51.portX[t6], y: e51.portY[t6], z: e51.portZ[t6], ...L4(o7), connectionNodeIds: n7.map((t7) =\u003e k4(e51.regionMetadata?.[t7], t7)), distToCentermostPortOnZ: e51.portMetadata?.[t6]?.distToCentermostPortOnZ ?? 0, connectsToOffBoardNode: false };\n });\n t4.push({ capacityMeshNodeId: i6, center: { x: e51.regionCenterX[n6], y: e51.regionCenterY[n6] }, width: e51.regionWidth[n6], height: e51.regionHeight[n6], portPoints: r6, availableZ: o6.availableZ ?? Array.from({ length: this.params.srj.layerCount }, (e53, t6) =\u003e t6), _containsObstacle: Boolean(o6._containsObstacle), _containsTarget: Boolean(o6._containsTarget) });\n }\n return t4;\n }\n createAssignedPortPoint(e51, t4) {\n const n6 = this.polySolver.problem.routeMetadata?.[e51], o6 = n6 ? ((e53) =\u003e e53.simpleRouteConnection?.name ?? e53.connectionId)(n6) : `route-${e51}`, i6 = n6 ? ((e53) =\u003e e53.simpleRouteConnection?.rootConnectionName ?? e53.mutuallyConnectedNetworkId)(n6) : undefined, r6 = this.polySolver.topology.portMetadata?.[t4];\n return { portPointId: D4(r6, t4), x: this.polySolver.topology.portX[t4], y: this.polySolver.topology.portY[t4], z: this.polySolver.topology.portZ[t4], connectionName: o6, rootConnectionName: i6, ...L4(r6) };\n }\n buildOutputNodes() {\n const { topology: e51, state: t4 } = this.polySolver, n6 = [];\n for (let o6 = 0;o6 \u003c t4.regionSegments.length; o6++) {\n const i6 = A4(e51.regionMetadata?.[o6] ?? {}), r6 = k4(i6, o6);\n if (r6.startsWith(\"terminal-\"))\n continue;\n const s6 = z4(i6);\n if (!s6)\n continue;\n const a6 = (t4.regionSegments[o6] ?? []).flatMap(([e53, t6, n7]) =\u003e {\n const o7 = this.createAssignedPortPoint(e53, t6), i7 = this.createAssignedPortPoint(e53, n7);\n return o7.portPointId \u0026\u0026 i7.portPointId \u0026\u0026 (o7.nextPortPointId = i7.portPointId, i7.prevPortPointId = o7.portPointId), [o7, i7];\n });\n a6.length !== 0 \u0026\u0026 n6.push({ capacityMeshNodeId: r6, center: { x: e51.regionCenterX[o6], y: e51.regionCenterY[o6] }, width: e51.regionWidth[o6], height: e51.regionHeight[o6], polygon: s6, portPoints: a6, availableZ: i6.availableZ });\n }\n this.nodesWithPortPoints = n6;\n }\n _step() {\n this.polySolver.step(), this.progress = this.polySolver.progress, this.stats = { ...this.polySolver.stats ?? {}, reservedRegionCount: this.reservedRegionCount, usedUnconstrainedDelaunayFallback: this.usedUnconstrainedDelaunayFallback, regionCount: this.loaded.topology.regionCount, portCount: this.loaded.topology.portCount, routeCount: this.loaded.problem.routeCount }, this.polySolver.solved ? (this.buildOutputNodes(), this.solved = true, this.activeSubSolver = null) : this.polySolver.failed \u0026\u0026 (this.error = this.polySolver.error, this.failed = true, this.activeSubSolver = null);\n }\n getOutput() {\n return { nodesWithPortPoints: this.nodesWithPortPoints, inputNodeWithPortPoints: this.inputNodeWithPortPoints };\n }\n computeNodePf(e51) {\n const t4 = this.nodesWithPortPoints.find((t6) =\u003e t6.capacityMeshNodeId === e51.capacityMeshNodeId);\n if (!t4)\n return null;\n const n6 = Cz(t4);\n return jz({ capacityMeshNodeId: t4.capacityMeshNodeId, center: t4.center, width: t4.width, height: t4.height, layer: \"top\", availableZ: t4.availableZ ?? [] }, n6.numSameLayerCrossings, n6.numEntryExitLayerChanges, n6.numTransitionPairCrossings);\n }\n getConstructorParams() {\n return [this.params];\n }\n preview() {\n return this.visualize();\n }\n visualize() {\n return this.polySolver.visualize();\n }\n};\nvar F4 = class extends ni {\n constructor(e51) {\n super(), this.inputSrj = e51, this.MAX_ITERATIONS = 1;\n }\n outputSrj;\n _step() {\n this.error = G1(this.inputSrj), this.error ? this.failed = true : (this.outputSrj = X1(this.inputSrj) ?? this.inputSrj, this.solved = true);\n }\n getOutputSimpleRouteJson() {\n if (!this.outputSrj)\n throw new Error(\"PreprocessSimpleRouteJsonSolver has not solved yet\");\n return this.outputSrj;\n }\n getConstructorParams() {\n return [this.inputSrj];\n }\n visualize() {\n return this.outputSrj ? pi(Wo({ ...this.outputSrj, traces: [] }), nK({ srj: this.outputSrj })) : { lines: [], points: [], rects: [], circles: [] };\n }\n};\nvar j4 = (e51, t4) =\u003e (e51.x - t4.x) ** 2 + (e51.y - t4.y) ** 2;\nvar $4 = (e51, t4, n6) =\u003e {\n if (!n6)\n return;\n const o6 = e51.filter(({ projected: e53 }) =\u003e e53.connectionName === t4 \u0026\u0026 (n6.z === undefined || e53.z === n6.z));\n return o6.length !== 0 ? o6.reduce((e53, t6) =\u003e j4(t6.projected, n6) \u003c j4(e53.projected, n6) ? t6 : e53).original : undefined;\n};\nvar Y4 = (e51, t4) =\u003e {\n const n6 = t4.projectedRect;\n if (!n6)\n throw new Error(\"Poly node is missing projectedRect\");\n const o6 = n6.rectToPolygonMatrix, i6 = ((e53) =\u003e {\n if (!e53.projectedRect)\n throw new Error(\"Poly node is missing projectedRect\");\n return e53.portPoints.map((t6) =\u003e {\n const n7 = P2(t6, e53.projectedRect);\n return { original: t6, projected: { ...t6, x: n7.x, y: n7.y } };\n });\n })(t4), r6 = e51.route.map((e53) =\u003e ({ ...e53, ...I2(o6, e53) })), s6 = e51.vias.map((e53) =\u003e I2(o6, e53)), a6 = $4(i6, e51.connectionName, e51.route[0]), c5 = $4(i6, e51.connectionName, e51.route[e51.route.length - 1]);\n return a6 \u0026\u0026 r6[0] \u0026\u0026 (r6[0] = { ...r6[0], x: a6.x, y: a6.y, z: a6.z }), c5 \u0026\u0026 r6[r6.length - 1] \u0026\u0026 (r6[r6.length - 1] = { ...r6[r6.length - 1], x: c5.x, y: c5.y, z: c5.z }), { ...e51, route: r6, vias: s6, jumpers: e51.jumpers?.map((e53) =\u003e ({ ...e53, start: I2(o6, e53.start), end: I2(o6, e53.end) })) };\n};\nvar X4 = class extends ni {\n getSolverName() {\n return \"ProjectHighDensityToPolygonSolver\";\n }\n routes = [];\n routesByNodeId = new Map;\n colorMap;\n nodePortPoints;\n rawRoutesByNodeId;\n constructor({ nodePortPoints: e51, routesByNodeId: t4, colorMap: n6 }) {\n super(), this.MAX_ITERATIONS = 1, this.nodePortPoints = e51, this.rawRoutesByNodeId = t4 instanceof Map ? new Map(t4) : new Map(Object.entries(t4)), this.colorMap = n6 ?? {};\n }\n _step() {\n this.routes = [], this.routesByNodeId = new Map;\n for (const e51 of this.nodePortPoints) {\n const t4 = (this.rawRoutesByNodeId.get(e51.capacityMeshNodeId) ?? []).map((t6) =\u003e Y4(t6, e51));\n t4.length \u003e 0 \u0026\u0026 (this.routesByNodeId.set(e51.capacityMeshNodeId, t4), this.routes.push(...t4));\n }\n this.solved = true;\n }\n getOutput() {\n return this.routes;\n }\n getConstructorParams() {\n return [{ nodePortPoints: this.nodePortPoints, routesByNodeId: this.rawRoutesByNodeId, colorMap: this.colorMap }];\n }\n visualize() {\n const e51 = { polygons: this.nodePortPoints.flatMap((e53) =\u003e [{ points: e53.polygon, fill: \"rgba(40, 140, 220, 0.06)\", stroke: \"rgba(20, 70, 160, 0.65)\", label: `${e53.capacityMeshNodeId} polygon` }, ...e53.projectedRect ? [{ points: e53.projectedRect.targetQuad, fill: \"rgba(255, 165, 0, 0.05)\", stroke: \"rgba(255, 120, 0, 0.45)\", label: `${e53.capacityMeshNodeId} projection target` }] : []]), lines: [], circles: [] };\n for (const t4 of this.routes) {\n const n6 = this.colorMap[t4.connectionName] ?? \"#0000ff\", o6 = mi(t4.route, t4.connectionName, n6);\n for (const n7 of o6)\n e51.lines.push({ points: n7.points, label: n7.connectionName, strokeColor: n7.z === 0 ? n7.color : Ao(n7.color, 0.5), layer: `z${n7.z}`, strokeWidth: t4.traceThickness, strokeDash: n7.z !== 0 ? [0.1, 0.3] : undefined });\n for (const o7 of t4.vias)\n e51.circles.push({ center: o7, layer: \"z0,1\", radius: t4.viaDiameter / 2, fill: n6, label: `${t4.connectionName} via` });\n }\n return e51;\n }\n};\nfunction H4(e51, t4, n6, o6 = {}) {\n return { solverName: e51, solverClass: t4, getConstructorParams: n6, onSolved: o6.onSolved };\n}\nvar V4 = class extends ni {\n constructor(e51, t4 = {}) {\n super(), this.srj = e51, this.opts = t4, this.originalSrj = e51, this.opts = { ...t4 };\n const n6 = this.opts;\n if (this.effort = n6.effort ?? 1, this.MAX_ITERATIONS = 1e8 * this.effort, this.maxNodeDimension = n6.maxNodeDimension ?? 16, this.maxNodeRatio = n6.maxNodeRatio ?? 6, this.minNodeArea = n6.minNodeArea ?? 0.1 ** 2, this.setSimpleRouteJson(e51), this.equivalentAreaExpansionFactor = n6.equivalentAreaExpansionFactor ?? 2, this.minProjectedRectDimension = n6.minProjectedRectDimension ?? 3 * this.minTraceWidth, n6.capacityDepth === undefined) {\n const e53 = this.srj.bounds.maxX - this.srj.bounds.minX, t6 = this.srj.bounds.maxY - this.srj.bounds.minY, o6 = Math.max(e53, t6), i6 = n6.targetMinCapacity ?? 0.5;\n n6.capacityDepth = Fz(o6, i6);\n }\n this.cacheProvider = n6.cacheProvider === undefined ? no() : n6.cacheProvider === null ? null : n6.cacheProvider, this.startTimeOfPhase = {}, this.endTimeOfPhase = {}, this.timeSpentOnPhase = {};\n }\n preprocessSimpleRouteJsonSolver;\n escapeViaLocationSolver;\n netToPointPairsSolver;\n polyGraphSolver;\n attachProjectedRectsSolver;\n highDensityRouteSolver;\n projectHighDensityToPolgonSolver;\n highDensityStitchSolver;\n traceSimplificationSolver;\n traceWidthSolver;\n globalDrcForceImproveSolver;\n colorMap;\n viaDiameter;\n viaHoleDiameter;\n minTraceWidth;\n effort;\n maxNodeDimension;\n maxNodeRatio;\n minNodeArea;\n equivalentAreaExpansionFactor;\n minProjectedRectDimension;\n startTimeOfPhase;\n endTimeOfPhase;\n timeSpentOnPhase;\n activeSubSolver = null;\n connMap;\n srjWithEscapeViaLocations;\n srjWithPointPairs;\n originalSrj;\n highDensityNodePortPoints;\n projectedHighDensityNodePortPoints;\n cacheProvider = null;\n pipelineDef = [H4(\"preprocessSimpleRouteJsonSolver\", F4, (e51) =\u003e [e51.originalSrj], { onSolved: (e51) =\u003e {\n e51.setSimpleRouteJson(e51.preprocessSimpleRouteJsonSolver.getOutputSimpleRouteJson());\n } }), H4(\"escapeViaLocationSolver\", uK, (e51) =\u003e [e51.srj, { viaDiameter: e51.viaDiameter, minTraceWidth: e51.minTraceWidth, obstacleMargin: e51.srj.defaultObstacleMargin ?? 0.15 }], { onSolved: (e51) =\u003e {\n e51.srjWithEscapeViaLocations = e51.escapeViaLocationSolver?.getOutputSimpleRouteJson();\n } }), H4(\"netToPointPairsSolver\", pB, (e51) =\u003e {\n const t4 = e51.srjWithEscapeViaLocations ?? e51.srj;\n return [t4, e51.colorMap, ti(t4)];\n }, { onSolved: (e51) =\u003e {\n e51.srjWithPointPairs = e51.netToPointPairsSolver?.getNewSimpleRouteJson(), e51.colorMap = Eo(e51.srjWithPointPairs, e51.connMap), e51.connMap = ei(e51.srjWithPointPairs);\n } }), H4(\"polyGraphSolver\", B4, (e51) =\u003e [{ srj: e51.srjWithPointPairs, effort: Math.min(1, e51.effort), concavityTolerance: e51.opts.polyConcavityTolerance, portSpacing: e51.opts.polyPortSpacing, portMarginFromSegmentEndpoint: e51.opts.polyPortMarginFromSegmentEndpoint }], { onSolved: (e51) =\u003e {\n e51.highDensityNodePortPoints = e51.polyGraphSolver?.getOutput().nodesWithPortPoints ?? [];\n } }), H4(\"attachProjectedRectsSolver\", w2, (e51) =\u003e [{ nodesWithPortPoints: e51.highDensityNodePortPoints ?? [], equivalentAreaExpansionFactor: e51.equivalentAreaExpansionFactor, minProjectedRectDimension: e51.minProjectedRectDimension, traceWidth: e51.minTraceWidth, viaDiameter: e51.viaDiameter, obstacleMargin: e51.srj.defaultObstacleMargin ?? 0.15 }], { onSolved: (e51) =\u003e {\n e51.projectedHighDensityNodePortPoints = e51.attachProjectedRectsSolver?.getOutput() ?? [];\n } }), H4(\"highDensityRouteSolver\", R2, (e51) =\u003e [{ nodePortPoints: e51.projectedHighDensityNodePortPoints ?? [], nodePfById: new Map((e51.polyGraphSolver?.getOutput().inputNodeWithPortPoints ?? []).map((t4) =\u003e [t4.capacityMeshNodeId, e51.polyGraphSolver?.computeNodePf(t4) ?? null])), colorMap: e51.colorMap, connMap: e51.connMap, viaDiameter: e51.viaDiameter, traceWidth: e51.minTraceWidth, obstacleMargin: e51.srj.defaultObstacleMargin ?? 0.15, effort: Math.min(1, e51.effort) }]), H4(\"projectHighDensityToPolgonSolver\", X4, (e51) =\u003e [{ nodePortPoints: e51.projectedHighDensityNodePortPoints ?? [], routesByNodeId: e51.highDensityRouteSolver.routesByNodeId, colorMap: e51.colorMap }]), H4(\"highDensityStitchSolver\", L1, (e51) =\u003e [{ connections: e51.srjWithPointPairs.connections, hdRoutes: e51.projectHighDensityToPolgonSolver.routes, colorMap: e51.colorMap, layerCount: e51.srj.layerCount, defaultViaDiameter: e51.viaDiameter }]), H4(\"traceSimplificationSolver\", WF, (e51) =\u003e [{ hdRoutes: e51.highDensityStitchSolver.mergedHdRoutes, obstacles: e51.srj.obstacles, connMap: e51.connMap, colorMap: e51.colorMap, outline: e51.srj.outline, defaultViaDiameter: e51.viaDiameter, layerCount: e51.srj.layerCount, iterations: 2 }]), H4(\"traceWidthSolver\", QF, (e51) =\u003e [{ hdRoutes: e51.traceSimplificationSolver.simplifiedHdRoutes, obstacles: e51.srj.obstacles, connMap: e51.connMap, colorMap: e51.colorMap, minTraceWidth: e51.minTraceWidth, connection: e51.srj.connections, layerCount: e51.srj.layerCount }]), H4(\"globalDrcForceImproveSolver\", kN, (e51) =\u003e [{ srj: e51.srjWithPointPairs, hdRoutes: e51.traceWidthSolver.getHdRoutesWithWidths(), effort: Math.min(1, e51.effort) }])];\n setSimpleRouteJson(e51) {\n this.srj = e51;\n const t4 = Yo(this.srj);\n this.viaDiameter = t4.padDiameter, this.viaHoleDiameter = t4.holeDiameter, this.minTraceWidth = this.srj.minTraceWidth, this.connMap = ei(this.srj), this.colorMap = Eo(this.srj, this.connMap);\n }\n getConstructorParams() {\n return [this.srj, this.opts];\n }\n currentPipelineStepIndex = 0;\n _step() {\n const e51 = this.pipelineDef[this.currentPipelineStepIndex];\n if (!e51)\n return void (this.solved = true);\n if (this.activeSubSolver)\n return this.activeSubSolver.step(), void (this.activeSubSolver.solved ? (this.endTimeOfPhase[e51.solverName] = performance.now(), this.timeSpentOnPhase[e51.solverName] = this.endTimeOfPhase[e51.solverName] - this.startTimeOfPhase[e51.solverName], e51.onSolved?.(this), this.activeSubSolver = null, this.currentPipelineStepIndex++) : this.activeSubSolver.failed \u0026\u0026 (this.error = this.activeSubSolver?.error, this.failed = true, this.activeSubSolver = null));\n const t4 = e51.getConstructorParams(this);\n this.activeSubSolver = new e51.solverClass(...t4), this[e51.solverName] = this.activeSubSolver, this.timeSpentOnPhase[e51.solverName] = 0, this.startTimeOfPhase[e51.solverName] = performance.now();\n }\n solveUntilPhase(e51) {\n for (;this.getCurrentPhase() !== e51; )\n this.step();\n }\n getCurrentPhase() {\n return this.pipelineDef[this.currentPipelineStepIndex]?.solverName ?? \"none\";\n }\n getProblemVisualization({ includeRoutes: e51 = true } = {}) {\n const t4 = this.originalSrj, n6 = [{ points: [{ x: t4.bounds?.minX ?? -50, y: t4.bounds?.minY ?? -50 }, { x: t4.bounds?.maxX ?? 50, y: t4.bounds?.minY ?? -50 }, { x: t4.bounds?.maxX ?? 50, y: t4.bounds?.maxY ?? 50 }, { x: t4.bounds?.minX ?? -50, y: t4.bounds?.maxY ?? 50 }, { x: t4.bounds?.minX ?? -50, y: t4.bounds?.minY ?? -50 }], strokeColor: \"rgba(255,0,0,0.25)\" }];\n if (t4.outline \u0026\u0026 t4.outline.length \u003e= 2) {\n const e53 = t4.outline.map((e54) =\u003e ({ x: e54.x, y: e54.y }));\n e53.push({ ...e53[0] }), n6.push({ points: e53, strokeColor: \"rgba(0, 136, 255, 0.95)\" });\n }\n const o6 = Lo(t4), i6 = { points: [...t4.connections.flatMap((e53) =\u003e e53.pointsToConnect.map((n7) =\u003e ({ ...n7, layer: Bo(n7, t4.layerCount), label: `${e53.name} ${n7.pcb_port_id ?? \"\"}` })))], rects: [...(t4.obstacles ?? []).filter((e53) =\u003e !e53.isCopperPour).map((e53) =\u003e ({ ...e53, fill: e53.layers?.includes(\"top\") ? \"rgba(255,0,0,0.25)\" : e53.layers?.includes(\"bottom\") ? \"rgba(0,0,255,0.25)\" : \"rgba(255,0,0,0.25)\", layer: jo(e53, t4.layerCount), label: o6(e53) }))], lines: n6 };\n if (!e51)\n return i6;\n const r6 = nK({ srj: t4 });\n return pi(i6, r6);\n }\n visualize() {\n if (!this.solved \u0026\u0026 this.activeSubSolver)\n return this.activeSubSolver.visualize();\n const e51 = this.getProblemVisualization(), t4 = this.getProblemVisualization({ includeRoutes: false }), n6 = this.polyGraphSolver?.visualize(), o6 = this.attachProjectedRectsSolver?.visualize(), i6 = this.highDensityRouteSolver?.visualize(), r6 = this.projectHighDensityToPolgonSolver?.visualize(), s6 = this.highDensityStitchSolver?.visualize(), a6 = this.traceSimplificationSolver?.visualize();\n return pi(...[e51, this.escapeViaLocationSolver?.visualize(), this.netToPointPairsSolver?.visualize(), n6, o6, i6 ? pi(t4, i6) : null, r6 ? pi(t4, r6) : null, s6, a6, this.solved ? pi({ lines: t4.lines }, nK({ srj: this.originalSrj }), Wo(this.getOutputSimpleRouteJson())) : null].filter(Boolean));\n }\n preview() {\n if (this.projectHighDensityToPolgonSolver) {\n const e51 = [];\n for (let t4 = this.projectHighDensityToPolgonSolver.routes.length - 1;t4 \u003e= 0; t4--) {\n const n6 = this.projectHighDensityToPolgonSolver.routes[t4];\n if (e51.push({ points: n6.route.map((e53) =\u003e ({ x: e53.x, y: e53.y })), strokeColor: this.colorMap[n6.connectionName] }), e51.length \u003e 200)\n break;\n }\n return { lines: e51 };\n }\n if (this.highDensityRouteSolver) {\n const e51 = [];\n for (let t4 = this.highDensityRouteSolver.routes.length - 1;t4 \u003e= 0; t4--) {\n const n6 = this.highDensityRouteSolver.routes[t4];\n if (e51.push({ points: n6.route.map((e53) =\u003e ({ x: e53.x, y: e53.y })), strokeColor: this.colorMap[n6.connectionName] }), e51.length \u003e 200)\n break;\n }\n return { lines: e51 };\n }\n return this.polyGraphSolver ? this.polyGraphSolver.preview() : this.netToPointPairsSolver ? this.netToPointPairsSolver.visualize() : this.escapeViaLocationSolver ? this.escapeViaLocationSolver.visualize() : this.preprocessSimpleRouteJsonSolver ? this.preprocessSimpleRouteJsonSolver.visualize() : {};\n }\n _getOutputHdRoutes() {\n return this.globalDrcForceImproveSolver?.getOutput() ?? this.traceWidthSolver?.getHdRoutesWithWidths() ?? this.traceSimplificationSolver?.simplifiedHdRoutes ?? this.highDensityStitchSolver.mergedHdRoutes;\n }\n getOutputSimplifiedPcbTraces() {\n if (!this.solved || !this.highDensityRouteSolver)\n throw new Error(\"Cannot get output before solving is complete\");\n const e51 = [], t4 = this._getOutputHdRoutes();\n for (const n6 of this.netToPointPairsSolver?.newConnections ?? []) {\n const o6 = n6.__netConnectionName ?? this.originalSrj.connections.find((e53) =\u003e e53.name === n6.name)?.__netConnectionName, i6 = t4.filter((e53) =\u003e e53.connectionName === n6.name);\n for (let t6 = 0;t6 \u003c i6.length; t6++) {\n const r6 = i6[t6], s6 = { type: \"pcb_trace\", pcb_trace_id: `${n6.name}_${t6}`, connection_name: o6 ?? n6.__rootConnectionNames?.[0] ?? n6.name, route: Ro(r6, this.srj.layerCount, { connectionPoints: n6.pointsToConnect, defaultViaHoleDiameter: this.viaHoleDiameter }) };\n e51.push(s6);\n }\n }\n return e51;\n }\n getOutputSimpleRouteJson() {\n return { ...this.originalSrj, traces: this.getOutputSimplifiedPcbTraces() };\n }\n};\nvar G4 = (e51, t4) =\u003e {\n if (e51 === \"top\")\n return 0;\n if (e51 === \"bottom\")\n return t4 - 1;\n const n6 = /^inner(\\d+)$/.exec(e51);\n if (!n6)\n return -1;\n const o6 = Number(n6[1]);\n return o6 \u003e 0 \u0026\u0026 o6 \u003c t4 - 1 ? o6 : -1;\n};\nvar U4 = (e51, t4) =\u003e e51 === 0 ? \"top\" : e51 === t4 - 1 ? \"bottom\" : `inner${e51}`;\nvar Z4 = (e51, t4, n6) =\u003e {\n const o6 = G4(e51, n6), i6 = G4(t4, n6);\n if (o6 \u003c 0 || i6 \u003c 0)\n return [];\n const r6 = Math.min(o6, i6), s6 = Math.max(o6, i6);\n return Array.from({ length: s6 - r6 + 1 }, (e53, t6) =\u003e U4(r6 + t6, n6));\n};\nvar q4 = (e51, t4) =\u003e {\n const n6 = [], o6 = [], i6 = e51.route.find((e53) =\u003e e53.route_type === \"wire\"), r6 = i6?.route_type === \"wire\" ? i6.width : null, s6 = { \"0603\": 0.95, 1206: 1.8, \"1206x4_pair\": 1.8 };\n let a6 = null;\n for (let i7 = 0;i7 \u003c e51.route.length; i7++) {\n const c5 = e51.route[i7];\n if (c5.route_type === \"wire\") {\n if (!Number.isFinite(c5.x) || !Number.isFinite(c5.y) || !Number.isFinite(c5.width) || c5.width \u003c= 0 || G4(c5.layer, t4) \u003c 0)\n throw new Error(`PostProcessingSolver: immutable trace \"${e51.connection_name}\" has an invalid wire`);\n if (a6 \u0026\u0026 a6.layer !== c5.layer)\n throw new Error(`PostProcessingSolver: immutable trace \"${e51.connection_name}\" changes layer without a transition`);\n a6 \u0026\u0026 n6.push({ start: a6, end: c5, layer: c5.layer, width: Math.max(a6.width, c5.width), connectionName: e51.connection_name, terminal: null }), a6 = c5;\n continue;\n }\n if (c5.route_type === \"via\") {\n const s7 = Z4(c5.from_layer, c5.to_layer, t4), l6 = a6, h6 = c5.via_diameter ?? l6?.width ?? r6;\n if (!Number.isFinite(c5.x) || !Number.isFinite(c5.y) || s7.length \u003c 2 || h6 === null || !Number.isFinite(h6) || h6 \u003c= 0 || c5.via_hole_diameter !== undefined \u0026\u0026 (!Number.isFinite(c5.via_hole_diameter) || c5.via_hole_diameter \u003c= 0 || h6 !== null \u0026\u0026 c5.via_hole_diameter \u003e= h6))\n throw new Error(`PostProcessingSolver: immutable trace \"${e51.connection_name}\" has an invalid via`);\n l6 \u0026\u0026 Math.hypot(l6.x - c5.x, l6.y - c5.y) \u003e 0.00000001 \u0026\u0026 n6.push({ start: l6, end: c5, layer: l6.layer, width: l6.width, connectionName: e51.connection_name, terminal: null }), o6.push({ x: c5.x, y: c5.y, layers: s7, diameter: h6, connectionName: e51.connection_name, terminal: i7 === 0 ? \"start\" : i7 === e51.route.length - 1 ? \"end\" : null });\n const d7 = e51.route.slice(i7 + 1).find((e53) =\u003e e53.route_type === \"wire\"), u6 = l6?.layer === c5.from_layer ? c5.to_layer : l6?.layer === c5.to_layer ? c5.from_layer : d7?.route_type !== \"wire\" || d7.layer !== c5.from_layer \u0026\u0026 d7.layer !== c5.to_layer ? null : d7.layer;\n if (!u6)\n throw new Error(`PostProcessingSolver: immutable trace \"${e51.connection_name}\" has a discontinuous via`);\n a6 = { x: c5.x, y: c5.y, layer: u6, width: l6?.width ?? r6 ?? h6 };\n continue;\n }\n if (c5.route_type === \"jumper\") {\n const o7 = s6[c5.footprint];\n if (!Number.isFinite(c5.start.x) || !Number.isFinite(c5.start.y) || !Number.isFinite(c5.end.x) || !Number.isFinite(c5.end.y) || G4(c5.layer, t4) \u003c 0)\n throw new Error(`PostProcessingSolver: immutable trace \"${e51.connection_name}\" has an invalid jumper`);\n if (a6 \u0026\u0026 (a6.layer !== c5.layer || Math.hypot(a6.x - c5.start.x, a6.y - c5.start.y) \u003e 0.00000001))\n throw new Error(`PostProcessingSolver: immutable trace \"${e51.connection_name}\" has a discontinuous jumper`);\n n6.push({ start: c5.start, end: c5.end, layer: c5.layer, width: o7, connectionName: e51.connection_name, terminal: null }), a6 = { ...c5.end, layer: c5.layer, width: o7 };\n continue;\n }\n const l5 = Z4(c5.from_layer, c5.to_layer, t4);\n if (!Number.isFinite(c5.start.x) || !Number.isFinite(c5.start.y) || !Number.isFinite(c5.end.x) || !Number.isFinite(c5.end.y) || !Number.isFinite(c5.width) || c5.width \u003c= 0 || l5.length \u003c 2)\n throw new Error(`PostProcessingSolver: immutable trace \"${e51.connection_name}\" has invalid through-obstacle copper`);\n if (a6 \u0026\u0026 (a6.layer !== c5.from_layer \u0026\u0026 a6.layer !== c5.to_layer || Math.hypot(a6.x - c5.start.x, a6.y - c5.start.y) \u003e 0.00000001))\n throw new Error(`PostProcessingSolver: immutable trace \"${e51.connection_name}\" has discontinuous through-obstacle copper`);\n for (const t6 of l5)\n n6.push({ start: c5.start, end: c5.end, layer: t6, width: c5.width, connectionName: e51.connection_name, terminal: null });\n const h5 = a6, d6 = h5?.layer === c5.to_layer ? c5.from_layer : c5.to_layer;\n a6 = { ...c5.end, layer: d6, width: c5.width };\n }\n return { segments: n6, vias: o6 };\n};\nvar J4 = (e51) =\u003e e51.rootConnectionName ?? e51.connectionName;\nvar Q4 = (e51, t4) =\u003e e51.flatMap((e53, n6) =\u003e J4(e53) === t4 ? [n6] : []);\nvar K4 = (e51, t4, n6, o6) =\u003e {\n const i6 = (e53, t6, n7) =\u003e {\n const o7 = n7.x - t6.x, i7 = n7.y - t6.y, r7 = e53.x - t6.x, s7 = e53.y - t6.y, a7 = o7 ** 2 + i7 ** 2, c6 = a7 === 0 ? 0 : Math.max(0, Math.min(1, (r7 * o7 + s7 * i7) / a7));\n return Math.hypot(e53.x - (t6.x + c6 * o7), e53.y - (t6.y + c6 * i7));\n }, r6 = { x: t4.x - e51.x, y: t4.y - e51.y }, s6 = { x: o6.x - n6.x, y: o6.y - n6.y }, a6 = { x: n6.x - e51.x, y: n6.y - e51.y }, c5 = (e53, t6) =\u003e e53.x * t6.y - e53.y * t6.x, l5 = c5(r6, s6), h5 = Math.hypot(r6.x, r6.y), d6 = 0.000000000001 * (h5 * Math.hypot(s6.x, s6.y) + 1);\n if (Math.abs(l5) \u003e d6) {\n const e53 = c5(a6, s6) / l5, t6 = c5(a6, r6) / l5;\n if (e53 \u003e= -0.000000000001 \u0026\u0026 e53 \u003c= 1 + 0.000000000001 \u0026\u0026 t6 \u003e= -0.000000000001 \u0026\u0026 t6 \u003c= 1 + 0.000000000001)\n return 0;\n } else if (h5 \u003e 0.000000000001 \u0026\u0026 Math.abs(c5(a6, r6)) \u003c= d6) {\n const i7 = Math.abs(r6.x) \u003e= Math.abs(r6.y), s7 = Math.min(i7 ? e51.x : e51.y, i7 ? t4.x : t4.y), a7 = Math.max(i7 ? e51.x : e51.y, i7 ? t4.x : t4.y), c6 = Math.min(i7 ? n6.x : n6.y, i7 ? o6.x : o6.y), l6 = Math.max(i7 ? n6.x : n6.y, i7 ? o6.x : o6.y);\n if (Math.max(s7, c6) \u003c= Math.min(a7, l6) + 0.000000000001)\n return 0;\n }\n return Math.min(i6(e51, n6, o6), i6(t4, n6, o6), i6(n6, e51, t4), i6(o6, e51, t4));\n};\nvar e62 = (e51, t4) =\u003e Math.hypot(t4.x - e51.x, t4.y - e51.y);\nvar t6 = (e51) =\u003e {\n let t4 = 0;\n for (let n6 = 0;n6 \u003c e51.route.length - 1; n6++)\n t4 += e62(e51.route[n6], e51.route[n6 + 1]);\n return t4;\n};\nvar n6 = (e51, t4) =\u003e t4.reduce((t7, n7) =\u003e t7 + t6(e51[n7]), 0);\nvar o6 = (e51, t4) =\u003e {\n const { __zLayers: n7, zLayers: o7 } = e51, i6 = n7 !== undefined ? n7 : o7;\n if (i6 !== undefined) {\n if (!Array.isArray(i6) || i6.length === 0 || i6.some((e53) =\u003e !Number.isInteger(e53) || e53 \u003c 0 || e53 \u003e= t4))\n throw new Error(\"Obstacle has invalid z-layer indexes\");\n return i6;\n }\n if (e51.layers.length === 0)\n throw new Error(\"Obstacle has no declared layers\");\n return e51.layers.map((e53) =\u003e {\n if (e53 === \"top\")\n return 0;\n if (e53 === \"bottom\")\n return t4 - 1;\n const n8 = /^inner(\\d+)$/.exec(e53), o8 = n8 ? Number(n8[1]) : -1;\n if (o8 \u003c= 0 || o8 \u003e= t4 - 1)\n throw new Error(`Obstacle has invalid layer name \"${e53}\"`);\n return o8;\n });\n};\nvar i6 = (e51) =\u003e {\n const t4 = (e53, t7, n8, o8) =\u003e {\n const i8 = n8.center.x - n8.width / 2 - o8, r7 = n8.center.x + n8.width / 2 + o8, s7 = n8.center.y - n8.height / 2 - o8, a6 = n8.center.y + n8.height / 2 + o8;\n if (e53.x \u003e= i8 \u0026\u0026 e53.x \u003c= r7 \u0026\u0026 e53.y \u003e= s7 \u0026\u0026 e53.y \u003c= a6 || t7.x \u003e= i8 \u0026\u0026 t7.x \u003c= r7 \u0026\u0026 t7.y \u003e= s7 \u0026\u0026 t7.y \u003c= a6)\n return true;\n const c5 = [{ x: i8, y: s7 }, { x: r7, y: s7 }, { x: r7, y: a6 }, { x: i8, y: a6 }];\n return c5.some((n9, o9) =\u003e K4(e53, t7, n9, c5[(o9 + 1) % c5.length]) === 0);\n };\n if (e51.bounds \u0026\u0026 e51.meanderPoints.some((t7) =\u003e t7.x \u003c e51.bounds.minX || t7.x \u003e e51.bounds.maxX || t7.y \u003c e51.bounds.minY || t7.y \u003e e51.bounds.maxY))\n return false;\n const n7 = (e53, t7, n8) =\u003e {\n const o8 = n8.x - t7.x, i8 = n8.y - t7.y, r7 = o8 * o8 + i8 * i8, s7 = r7 === 0 ? 0 : Math.max(0, Math.min(1, ((e53.x - t7.x) * o8 + (e53.y - t7.y) * i8) / r7));\n return Math.hypot(e53.x - (t7.x + s7 * o8), e53.y - (t7.y + s7 * i8));\n }, o7 = e51.meanderPoints.some((t7) =\u003e !e51.route.route.slice(1).some((o8, i8) =\u003e {\n const r7 = e51.route.route[i8];\n return r7.z === t7.z \u0026\u0026 o8.z === t7.z \u0026\u0026 n7(t7, r7, o8) \u003c= 0.000000001;\n })), i7 = (e51.traces ?? []).map((t7) =\u003e q4(t7, e51.layerCount)), r6 = J4(e51.route), s6 = e51.route.traceThickness / 2 + e51.obstacleMargin;\n for (let a6 = 0;a6 \u003c e51.meanderPoints.length - 1; a6++) {\n const c5 = e51.meanderPoints[a6], l5 = e51.meanderPoints[a6 + 1], h5 = e51.route.route.slice(1).some((t7, o8) =\u003e {\n const i8 = e51.route.route[o8];\n return c5.z === l5.z \u0026\u0026 i8.z === c5.z \u0026\u0026 t7.z === l5.z \u0026\u0026 n7(c5, i8, t7) \u003c= 0.000000001 \u0026\u0026 n7(l5, i8, t7) \u003c= 0.000000001;\n });\n if (o7 \u0026\u0026 h5)\n continue;\n for (const n8 of e51.obstacles) {\n if (!o6(n8, e51.layerCount).includes(c5.z))\n continue;\n const o8 = a6 === 0 || a6 === e51.meanderPoints.length - 2;\n if ((!n8.connectedTo.includes(r6) || !o8) \u0026\u0026 t4(c5, l5, n8, s6))\n return false;\n }\n const d6 = U4(c5.z, e51.layerCount);\n for (const { segments: e53, vias: t7 } of i7) {\n for (const t8 of e53)\n if (t8.layer === d6 \u0026\u0026 K4(c5, l5, t8.start, t8.end) \u003c s6 + t8.width / 2)\n return false;\n for (const e54 of t7)\n if (e54.layers.includes(d6) \u0026\u0026 n7(e54, c5, l5) \u003c s6 + e54.diameter / 2)\n return false;\n }\n for (const t7 of e51.routedRoutes) {\n const o8 = J4(t7) === r6;\n for (const i8 of t7.vias) {\n if (i8.zLayers \u0026\u0026 !i8.zLayers.includes(c5.z))\n continue;\n const r7 = Math.hypot(i8.x - c5.x, i8.y - c5.y) \u003c= 0.00000001 || Math.hypot(i8.x - l5.x, i8.y - l5.y) \u003c= 0.00000001, s7 = e51.route.traceThickness / 2 + t7.viaDiameter / 2 + e51.obstacleMargin;\n if ((!o8 || !r7) \u0026\u0026 n7(i8, c5, l5) \u003c s7)\n return false;\n }\n if (!o8)\n for (let n8 = 0;n8 \u003c t7.route.length - 1; n8++) {\n const o9 = t7.route[n8], i8 = t7.route[n8 + 1];\n if (c5.z !== o9.z || c5.z !== i8.z)\n continue;\n const r7 = e51.route.traceThickness / 2 + t7.traceThickness / 2 + e51.obstacleMargin;\n if (K4(c5, l5, o9, i8) \u003c r7)\n return false;\n }\n }\n }\n return true;\n};\nvar r6 = (e51) =\u003e {\n const t4 = [];\n for (const n8 of e51.routeIndexes) {\n const o7 = e51.routes[n8], i7 = e51.minMeanderGap ?? Math.max(0.3, 2 * o7.traceThickness), r7 = o7.traceThickness + i7, s6 = Math.max(e51.minimumToothPitch ?? 0, 2 * r7), a6 = e51.minMeanderHeight ?? r7;\n for (let i8 = 0;i8 \u003c o7.route.length - 1; i8++) {\n const r8 = o7.route[i8], c5 = o7.route[i8 + 1], l5 = e62(r8, c5);\n if (l5 \u003c= 0 || r8.z !== c5.z)\n continue;\n const h5 = Math.min(Math.max(0, Math.floor(l5 / s6) - 1), e51.maxToothCount);\n for (let o8 = 1;o8 \u003c= h5; o8++) {\n const r9 = l5 / (o8 + 1), c6 = [r9, Math.sqrt(s6 * r9), s6].filter((e53, t7, n9) =\u003e n9.findIndex((t8) =\u003e Math.abs(t8 - e53) \u003c 0.000000001) === t7), h6 = o8 % 2 == 0 ? [\"balanced\", \"negative\", \"positive\"] : [\"negative\", \"positive\"];\n for (const r10 of c6)\n for (const s7 of h6)\n t4.push({ routeIndex: n8, segmentIndex: i8, segmentLength: l5, toothCount: o8, maximumDepth: e51.maximumDepth, minimumHeight: a6, toothPitch: r10, placement: s7, heightProfile: o8 \u003e 1 ? \"tapered\" : \"uniform\" });\n }\n }\n }\n const n7 = { balanced: 0, negative: 1, positive: 2 };\n return t4.sort((e53, t7) =\u003e e53.toothCount - t7.toothCount || n7[e53.placement] - n7[t7.placement] || t7.toothPitch - e53.toothPitch || t7.segmentLength - e53.segmentLength);\n};\nvar s6 = (e51) =\u003e {\n if (e51.centerlineDistanceCost === null)\n return 0;\n const t4 = e51.predictedToothDepths.flatMap((e53, t7) =\u003e e53 \u003e 0 ? [t7] : []);\n if (t4.length === 0)\n return 0;\n const n7 = t4.map((t7) =\u003e e51.predictedToothDepths[t7]), o7 = Math.max(...n7), i7 = n7.reduce((e53, t7) =\u003e e53 + t7, 0) / n7.length, r7 = Math.sqrt(n7.reduce((e53, t7) =\u003e e53 + (t7 - i7) ** 2, 0) / n7.length), s7 = t4[0], a6 = (t4.at(-1) - s7 + 1) * e51.toothPitch, c5 = o7 / (e51.toothPitch / 2), l5 = e51.addedLength / a6, h5 = c5 / (1 + c5) * 40, d6 = l5 / (1 + l5) * 30, u6 = e51.predictedToothDepths.map((t7, n8) =\u003e Math.sin(Math.PI * (n8 + 1) / (e51.predictedToothDepths.length + 1))), p6 = Math.max(...u6), m6 = Math.sqrt(e51.predictedToothDepths.reduce((e53, t7, n8) =\u003e e53 + (t7 - o7 * u6[n8] / p6) ** 2, 0) / e51.predictedToothDepths.length), g6 = 100 - h5 - d6 - Math.min(10, (e51.heightProfile === \"tapered\" ? m6 : r7) / i7 * 10) - 2 * (n7.length - 1) - 7 * Math.min(1, e51.addedLength / e51.segmentLength) - 100 * e51.centerlineDistanceCost, f6 = e51.centerlineDistanceCost \u003e 0 ? g6 : Math.max(0, g6);\n return Math.round(1e6 * f6) / 1e6;\n};\nvar a6 = (e51) =\u003e {\n if (e51.toothDepths.length !== e51.toothCount)\n throw new Error(`LengthMatchingSolver: expected ${e51.toothCount} tooth depths, received ${e51.toothDepths.length}`);\n if (e51.toothDepths.some((e53) =\u003e !Number.isFinite(e53) || e53 \u003c 0))\n throw new Error(\"LengthMatchingSolver: every meander tooth depth must be a non-negative finite number\");\n const t4 = e51.route.route[e51.segmentIndex], n7 = e51.route.route[e51.segmentIndex + 1], o7 = e62(t4, n7), i7 = (n7.x - t4.x) / o7, r7 = (n7.y - t4.y) / o7, s7 = (o7 - (e51.toothCount - 0.5) * e51.toothPitch) / 2, a7 = [{ ...t4 }];\n for (let n8 = 0;n8 \u003c e51.toothCount; n8++) {\n const o8 = e51.toothDepths[n8];\n if (o8 === 0)\n continue;\n const c5 = e51.placement === \"balanced\" ? n8 % 2 == 0 ? -1 : 1 : e51.placement === \"negative\" ? -1 : 1, l5 = { x: -r7 * c5, y: i7 * c5 }, h5 = s7 + n8 * e51.toothPitch, d6 = h5 + e51.toothPitch / 2, u6 = { ...t4, x: t4.x + i7 * h5, y: t4.y + r7 * h5 };\n a7.push(u6, { ...u6, x: u6.x + l5.x * o8, y: u6.y + l5.y * o8 }, { ...t4, x: t4.x + i7 * d6 + l5.x * o8, y: t4.y + r7 * d6 + l5.y * o8 }, { ...t4, x: t4.x + i7 * d6, y: t4.y + r7 * d6 });\n }\n return a7.push({ ...n7 }), ((e53) =\u003e {\n if (e53.length \u003c 3)\n return e53;\n const t7 = [{ ...e53[0] }];\n for (let n8 = 1;n8 \u003c e53.length - 1; n8++) {\n const o8 = e53[n8 - 1], i8 = e53[n8], r8 = e53[n8 + 1], s8 = Math.hypot(i8.x - o8.x, i8.y - o8.y), a8 = Math.hypot(r8.x - i8.x, r8.y - i8.y);\n if (s8 === 0 || a8 === 0)\n throw new Error(\"LengthMatchingSolver: meander contains a zero-length segment\");\n const c5 = { x: (i8.x - o8.x) / s8, y: (i8.y - o8.y) / s8 }, l5 = { x: (r8.x - i8.x) / a8, y: (r8.y - i8.y) / a8 };\n if (Math.abs(c5.x * l5.y - c5.y * l5.x) \u003c 0.000000001) {\n t7.push({ ...i8 });\n continue;\n }\n const h5 = Math.min(s8, a8) / 2, d6 = { ...i8, x: i8.x - c5.x * h5, y: i8.y - c5.y * h5 }, u6 = { ...i8, x: i8.x + l5.x * h5, y: i8.y + l5.y * h5 }, p6 = t7.at(-1);\n d6.x === p6.x \u0026\u0026 d6.y === p6.y || t7.push(d6);\n for (let e54 = 1;e54 \u003c 6; e54++) {\n const n9 = e54 / 6, o9 = 1 - n9;\n t7.push({ ...i8, x: o9 ** 2 * d6.x + 2 * o9 * n9 * i8.x + n9 ** 2 * u6.x, y: o9 ** 2 * d6.y + 2 * o9 * n9 * i8.y + n9 ** 2 * u6.y });\n }\n t7.push(u6);\n }\n return t7.push({ ...e53[e53.length - 1] }), t7;\n })(a7);\n};\nvar c6 = (e51) =\u003e [...e51.route.route.slice(0, e51.segmentIndex), ...a6(e51), ...e51.route.route.slice(e51.segmentIndex + 2)];\nvar l6 = (e51) =\u003e {\n const t4 = t6(e51.route), n7 = (() =\u003e {\n const t7 = [];\n for (let n8 = 0;n8 \u003c e51.candidate.toothCount; n8++) {\n const o8 = Array(e51.candidate.toothCount).fill(0);\n o8[n8] = e51.candidate.maximumDepth;\n const i8 = a6({ ...e51.candidate, route: e51.route, toothDepths: o8 });\n if (e51.isGeometryValid(i8)) {\n t7.push(e51.candidate.maximumDepth);\n continue;\n }\n let r8 = 0, s8 = e51.candidate.maximumDepth;\n for (let t8 = 0;t8 \u003c 32; t8++) {\n const t9 = (r8 + s8) / 2, o9 = Array(e51.candidate.toothCount).fill(0);\n o9[n8] = t9;\n const i9 = a6({ ...e51.candidate, route: e51.route, toothDepths: o9 });\n e51.isGeometryValid(i9) ? r8 = t9 : s8 = t9;\n }\n t7.push(r8);\n }\n return t7;\n })(), o7 = ((e53) =\u003e {\n if (e53.heightProfile !== \"tapered\")\n return Array(e53.toothCount).fill(1);\n const t7 = Array.from({ length: e53.toothCount }, (t8, n9) =\u003e Math.sin(Math.PI * (n9 + 1) / (e53.toothCount + 1))), n8 = Math.max(...t7);\n return t7.map((e54) =\u003e e54 / n8);\n })(e51.candidate), i7 = e51.candidate.maximumDepth, r7 = n7.map((e53, t7) =\u003e Math.min(e53, i7 * o7[t7])), s7 = [0.25, 0.75], a7 = r7.map((e53) =\u003e e53 * s7[0]), c5 = r7.map((e53) =\u003e e53 * s7[1]), l5 = c6({ ...e51.candidate, route: e51.route, toothDepths: a7 }), h5 = c6({ ...e51.candidate, route: e51.route, toothDepths: c5 }), d6 = [t6({ ...e51.route, route: l5 }) - t4, t6({ ...e51.route, route: h5 }) - t4], u6 = c6({ ...e51.candidate, route: e51.route, toothDepths: r7 }), p6 = t6({ ...e51.route, route: u6 }) - t4, m6 = (d6[1] - d6[0]) / (s7[1] - s7[0]), g6 = d6[0] - m6 * s7[0], f6 = m6 \u003e 0 \u0026\u0026 Number.isFinite(m6) ? (e51.targetAddedLength - g6) / m6 : 0, _5 = Math.min(e51.targetAddedLength, p6), y6 = e51.targetAddedLength \u003e 0 \u0026\u0026 _5 \u003e 0 ? ((t7) =\u003e {\n let n8 = 0, o8 = e51.candidate.maximumDepth;\n for (let i9 = 0;i9 \u003c 32; i9++) {\n const i10 = (n8 + o8) / 2, r8 = t7.maximumToothDepths.map((e53, n9) =\u003e Math.min(e53, i10 * t7.toothHeightWeights[n9])), s8 = c6({ ...e51.candidate, route: e51.route, toothDepths: r8 }), a8 = t6({ ...e51.route, route: s8 }) - t7.originalLength, c7 = a6({ ...e51.candidate, route: e51.route, toothDepths: r8 });\n e51.isGeometryValid(c7) ? a8 \u003c t7.targetAddedLength ? n8 = i10 : o8 = i10 : o8 = i10;\n }\n const i8 = (n8 + o8) / 2;\n return { depthLevel: i8, toothDepths: t7.maximumToothDepths.map((e53, n9) =\u003e Math.min(e53, i8 * t7.toothHeightWeights[n9])) };\n })({ maximumToothDepths: n7, toothHeightWeights: o7, originalLength: t4, targetAddedLength: _5 }) : { depthLevel: f6 * i7, toothDepths: r7.map((e53) =\u003e Math.max(0, e53 * f6)) }, b6 = y6.depthLevel / i7, x6 = y6.toothDepths, v6 = c6({ ...e51.candidate, route: e51.route, toothDepths: x6 }), I6 = t6({ ...e51.route, route: v6 }) - t4, S6 = Math.abs(_5 - I6), C = a6({ ...e51.candidate, route: e51.route, toothDepths: x6 });\n let P = 0;\n if (e51.getCenterlineDistanceCost \u0026\u0026 (P = e51.getCenterlineDistanceCost(C)), P !== null \u0026\u0026 (!Number.isFinite(P) || P \u003c 0))\n throw new Error(\"LengthMatchingSolver: meander centerline distance cost must be a non-negative finite number\");\n const M = Number.isFinite(b6) \u0026\u0026 b6 \u003e 0 \u0026\u0026 b6 \u003c= 1, w = x6.every((t7) =\u003e t7 === 0 || t7 \u003e= e51.candidate.minimumHeight), N = e51.isGeometryValid(C);\n let R6, T2 = null;\n P === null ? T2 = \"no-paired-same-layer-geometry\" : M ? S6 \u003e e51.lengthTolerance ? T2 = \"target-error\" : N ? w || (T2 = \"below-minimum-height\") : T2 = \"invalid-geometry\" : T2 = \"invalid-scale\", R6 = T2 ? { valid: false, invalidReason: T2 } : { valid: true, invalidReason: null };\n const E6 = { ...e51.candidate, connectionName: e51.connectionName, maximumToothDepths: n7, sampleScaleFactors: s7, sampleAddedLengths: d6, slope: m6, intercept: g6, predictedScaleFactor: b6, predictedToothDepths: x6, predictedRoute: v6, addedLength: I6, maximumAddedLength: p6, resultingError: S6, testedSegment: [{ ...e51.route.route[e51.candidate.segmentIndex] }, { ...e51.route.route[e51.candidate.segmentIndex + 1] }], meanderPoints: C, centerlineDistanceCost: P, qualityScore: 0, ...R6 };\n return { ...E6, qualityScore: s6(E6) };\n};\nvar h6 = (e51) =\u003e {\n const t4 = ((e53) =\u003e {\n if (e53.heightProfile !== \"tapered\")\n return Array(e53.toothCount).fill(1);\n const t7 = Array.from({ length: e53.toothCount }, (t8, n9) =\u003e Math.sin(Math.PI * (n9 + 1) / (e53.toothCount + 1))), n8 = Math.max(...t7);\n return t7.map((e54) =\u003e e54 / n8);\n })(e51.candidate), n7 = Math.max(...t4.map((t7) =\u003e e51.candidate.minimumHeight / t7)), o7 = e51.candidate.maximumDepth / 2 ** 30, i7 = t4.map((e53) =\u003e e53 * (n7 + o7));\n if (i7.some((t7) =\u003e t7 \u003e e51.candidate.maximumDepth))\n return null;\n const r7 = a6({ ...e51.candidate, route: e51.route, toothDepths: i7 });\n if (!e51.isGeometryValid(r7))\n return null;\n const s7 = c6({ ...e51.candidate, route: e51.route, toothDepths: i7 }), a7 = t6({ ...e51.route, route: s7 }) - t6(e51.route), c5 = l6({ ...e51, targetAddedLength: a7 });\n return c5.valid ? c5 : null;\n};\nvar d6 = (e51) =\u003e {\n const t4 = (e53, t7) =\u003e {\n const n8 = e53[t7.routeIndex];\n if (!n8)\n throw new Error(`LengthMatchingSolver: dual meander references missing route ${t7.routeIndex}`);\n const o8 = [...e53];\n return o8[t7.routeIndex] = { ...n8, route: t7.predictedRoute }, o8;\n }, n7 = (() =\u003e {\n if (e51.targetAddedLength + e51.config.lengthTolerance \u003c e51.plan.minimumAddedLength || e51.targetAddedLength - e51.config.lengthTolerance \u003e e51.plan.maximumAddedLength)\n return null;\n const t7 = e51.plan.attemptOptions.map((e53) =\u003e Math.min(...e53.map((e54) =\u003e e54.attempt.addedLength)));\n let n8 = Math.max(0, e51.targetAddedLength - e51.plan.minimumAddedLength), o8 = t7.map((e53, t8) =\u003e t8);\n for (;n8 \u003e 0.000000001 \u0026\u0026 o8.length \u003e 0; ) {\n const i8 = n8 / o8.length;\n let r8 = 0;\n const s8 = [];\n for (const n9 of o8) {\n const o9 = Math.max(...e51.plan.attemptOptions[n9].map((e53) =\u003e e53.attempt.maximumAddedLength)) - t7[n9], a8 = Math.min(o9, i8);\n t7[n9] += a8, r8 += a8, o9 - a8 \u003e 0.000000001 \u0026\u0026 s8.push(n9);\n }\n if (r8 \u003c= 0.000000001)\n break;\n n8 -= r8, o8 = s8;\n }\n return n8 \u003c= e51.config.lengthTolerance ? t7 : null;\n })();\n if (!n7)\n return null;\n const o7 = e51.plan.attemptOptions.map((e53, t7) =\u003e ({ attemptOptions: e53, targetAddedLength: n7[t7] })).sort((e53, t7) =\u003e t7.attemptOptions[0].candidate.routeIndex - e53.attemptOptions[0].candidate.routeIndex || t7.attemptOptions[0].candidate.segmentIndex - e53.attemptOptions[0].candidate.segmentIndex);\n let i7 = [...e51.routes];\n const r7 = [];\n for (const n8 of o7) {\n const o8 = n8.attemptOptions[0]?.candidate;\n if (!o8)\n throw new Error(\"LengthMatchingSolver: empty dual-meander segment options\");\n const s8 = i7[o8.routeIndex];\n if (!s8)\n throw new Error(`LengthMatchingSolver: missing planned dual-meander route ${o8.routeIndex}`);\n let a8 = null;\n for (const t7 of n8.attemptOptions) {\n if (t7.attempt.addedLength - e51.config.lengthTolerance \u003e n8.targetAddedLength || t7.attempt.maximumAddedLength + e51.config.lengthTolerance \u003c n8.targetAddedLength)\n continue;\n const o9 = l6({ candidate: t7.candidate, route: s8, connectionName: e51.connectionName, targetAddedLength: n8.targetAddedLength, lengthTolerance: e51.config.lengthTolerance, isGeometryValid: (t8) =\u003e i6({ route: s8, meanderPoints: t8, routedRoutes: e51.excludedConnectionName ? i7.filter((t9) =\u003e J4(t9) !== e51.excludedConnectionName) : i7, ...e51.config }) });\n o9.valid \u0026\u0026 (!a8 || o9.qualityScore \u003e a8.qualityScore) \u0026\u0026 (a8 = o9);\n }\n if (!a8)\n return null;\n i7 = t4(i7, a8), r7.push(a8);\n }\n const s7 = r7.reduce((e53, t7) =\u003e e53 + t7.addedLength, 0);\n if (Math.abs(s7 - e51.targetAddedLength) \u003e e51.config.lengthTolerance)\n return null;\n const a7 = r7[0];\n if (!a7)\n throw new Error(\"LengthMatchingSolver: fitted an empty dual-meander plan\");\n return { attempts: [a7, ...r7.slice(1)], routes: i7, addedLength: s7 };\n};\nvar u6 = (e51) =\u003e {\n if (e51.length === 0)\n throw new Error(\"LengthMatchingSolver: cannot score an empty meander plan\");\n return e51.reduce((e53, t4) =\u003e e53 + t4.qualityScore, 0) / e51.length - 3 * (e51.length - 1);\n};\nvar p6 = (e51) =\u003e {\n const t4 = (e53) =\u003e [e53.candidate.toothCount, e53.candidate.placement, e53.candidate.heightProfile].join(\":\"), n7 = new Map;\n for (const o8 of e51) {\n const e53 = t4(o8), i7 = `${o8.candidate.routeIndex}:${o8.candidate.segmentIndex}`, r7 = n7.get(e53);\n if (!r7) {\n n7.set(e53, new Map([[i7, [o8]]]));\n continue;\n }\n const s7 = r7.get(i7);\n s7 ? s7.push(o8) : r7.set(i7, [o8]);\n }\n const o7 = [];\n for (const e53 of n7.values()) {\n const t7 = [...e53.values()].map((e54) =\u003e ({ attempts: e54, maximumAddedLength: Math.max(...e54.map((e55) =\u003e e55.attempt.maximumAddedLength)), minimumAddedLength: Math.min(...e54.map((e55) =\u003e e55.attempt.addedLength)), rankingAttempt: e54.reduce((e55, t8) =\u003e t8.attempt.qualityScore \u003e e55.attempt.qualityScore ? t8 : e55) })).sort((e54, t8) =\u003e t8.maximumAddedLength - e54.maximumAddedLength);\n for (const e54 of t7)\n o7.push({ attempts: [e54.rankingAttempt], attemptOptions: [e54.attempts], minimumAddedLength: e54.minimumAddedLength, maximumAddedLength: e54.maximumAddedLength, rankingQualityScore: e54.rankingAttempt.attempt.qualityScore });\n for (let e54 = 2;e54 \u003c= t7.length; e54++) {\n const n8 = t7.slice(0, e54), i7 = n8.map((e55) =\u003e e55.rankingAttempt);\n o7.push({ attempts: i7, attemptOptions: n8.map((e55) =\u003e e55.attempts), minimumAddedLength: n8.reduce((e55, t8) =\u003e e55 + t8.minimumAddedLength, 0), maximumAddedLength: n8.reduce((e55, t8) =\u003e e55 + t8.maximumAddedLength, 0), rankingQualityScore: u6(i7.map((e55) =\u003e e55.attempt)) });\n }\n }\n return o7;\n};\nvar m6 = class extends Error {\n connectionName;\n reason;\n constructor(e51) {\n super(e51.message), this.name = \"LengthMatchingNoSolutionError\", this.connectionName = e51.connectionName, this.reason = e51.reason;\n }\n};\nvar g6 = (e51) =\u003e [e51.routeIndex, e51.segmentIndex, e51.toothCount, e51.placement, e51.toothPitch, e51.heightProfile, e51.maximumDepth, e51.minimumHeight].join(\":\");\nvar f6 = (e51) =\u003e {\n const t4 = new Map, n7 = [...e51.attempts].sort((e53, t7) =\u003e e53.addedLength - t7.addedLength);\n let o7 = e51.targetAddedLength;\n for (let e53 = 0;e53 \u003c n7.length; e53++) {\n const i7 = n7[e53], r7 = Math.min(i7.addedLength, o7 / (n7.length - e53));\n t4.set(g6(i7), { routeIndex: i7.routeIndex, segmentIndex: i7.segmentIndex, targetAddedLength: r7 }), o7 -= r7;\n }\n return t4;\n};\nvar _6 = (e51, t4) =\u003e `z${o6(e51, t4).join(\",\")}`;\nvar y6 = (e51) =\u003e `z${e51}`;\nvar b6 = (e51) =\u003e {\n if (!e51.showAttempt)\n return;\n if (!e51.attempt)\n return void ((e53) =\u003e {\n const t7 = e53.activePair?.candidates[e53.activePair.candidateIndex];\n if (!t7)\n return;\n const n8 = e53.routes[t7.routeIndex];\n if (!n8)\n return;\n const o8 = n8.route[t7.segmentIndex], i8 = n8.route[t7.segmentIndex + 1];\n o8 \u0026\u0026 i8 \u0026\u0026 e53.graphics.lines.push({ points: [o8, i8], strokeColor: \"rgba(234, 179, 8, 0.6)\", strokeWidth: 2 * n8.traceThickness, strokeDash: [0.1, 0.1], layer: y6(o8.z) });\n })(e51);\n const t4 = e51.routes[e51.attempt.routeIndex], [n7, o7] = e51.attempt.testedSegment, i7 = e51.theme.getConnectionColor(e51.attempt.connectionName);\n e51.graphics.lines.push({ points: [n7, o7], strokeColor: e51.theme.getTestedSegmentColor(i7), strokeWidth: t4.traceThickness, strokeDash: [0.15, 0.15], layer: y6(n7.z) }), e51.attempt.valid ? e51.graphics.lines.push({ points: e51.attempt.meanderPoints.map(({ x: e53, y: t7 }) =\u003e ({ x: e53, y: t7 })), strokeColor: \"rgba(234, 179, 8, 0.6)\", strokeWidth: 2 * t4.traceThickness, strokeDash: [0.1, 0.1], layer: y6(n7.z) }) : e51.graphics.lines.push({ points: e51.attempt.meanderPoints.map(({ x: e53, y: t7 }) =\u003e ({ x: e53, y: t7 })), strokeColor: e51.theme.getRejectedCandidateColor(i7), strokeWidth: t4.traceThickness, strokeDash: [0.1, 0.1], layer: y6(n7.z) }), e51.graphics.points.push({ x: n7.x, y: n7.y, color: i7, layer: y6(n7.z) }, { x: o7.x, y: o7.y, color: i7, layer: y6(o7.z) });\n};\nvar x6 = (e51) =\u003e {\n const t4 = { lines: [], points: [], rects: [], circles: [] }, n7 = ((e53) =\u003e {\n for (const t7 of Object.values(e53))\n Hn(0, t7);\n return { getConnectionColor: (t7, n8) =\u003e e53[t7] ?? (n8 ? e53[n8] : undefined) ?? ((e54) =\u003e e54 ? `hsl(${300 * e54.split(\"\").reduce((e55, t8) =\u003e e55 + t8.charCodeAt(0), 0) / e54.length % 360}, 100%, 50%)` : \"rgba(0, 0, 0, 0.5)\")(t7), getInnerLayerConnectionColor: (e54) =\u003e Hn(0.5, e54), getTestedSegmentColor: (e54) =\u003e Hn(0.55, e54), getRejectedCandidateColor: (e54) =\u003e Hn(0.45, e54), boardBounds: { fill: \"rgba(30,41,59,0.03)\", stroke: \"rgba(30,41,59,0.55)\" }, obstacle: { fill: \"rgba(255,0,0,0.25)\", stroke: \"rgba(255,0,0,0.5)\" }, via: { fill: \"blue\", stroke: \"none\" } };\n })(e51.colorMap);\n return ((e53) =\u003e {\n for (const t7 of e53.routes) {\n const n8 = J4(t7), o7 = e53.theme.getConnectionColor(n8, t7.connectionName);\n for (let n9 = 0;n9 \u003c t7.route.length - 1; n9++) {\n const i8 = t7.route[n9], r7 = t7.route[n9 + 1];\n i8.z === r7.z \u0026\u0026 e53.graphics.lines.push({ points: [i8, r7], strokeColor: i8.z === 0 ? o7 : e53.theme.getInnerLayerConnectionColor(o7), strokeWidth: t7.traceThickness, ...i8.z === 0 ? {} : { strokeDash: [0.2, 0.2] }, layer: y6(i8.z) });\n }\n const i7 = [...new Set(t7.route.map((e54) =\u003e e54.z))];\n for (const n9 of t7.vias)\n e53.graphics.circles.push({ center: n9, radius: t7.viaDiameter / 2, fill: e53.theme.via.fill, stroke: e53.theme.via.stroke, layer: `z${(n9.zLayers ?? i7).join(\",\")}` });\n }\n })({ routes: e51.routes, theme: n7, graphics: t4 }), ((e53) =\u003e {\n if (e53.bounds) {\n const { minX: t7, maxX: n8, minY: o7, maxY: i7 } = e53.bounds;\n e53.graphics.rects.push({ center: { x: (t7 + n8) / 2, y: (o7 + i7) / 2 }, width: n8 - t7, height: i7 - o7, fill: e53.theme.boardBounds.fill, stroke: e53.theme.boardBounds.stroke, layer: `z${Array.from({ length: e53.layerCount }, (e54, t8) =\u003e t8).join(\",\")}` });\n }\n for (const t7 of e53.obstacles)\n e53.graphics.rects.push({ center: t7.center, width: t7.width, height: t7.height, ccwRotationDegrees: t7.ccwRotationDegrees, fill: e53.theme.obstacle.fill, stroke: e53.theme.obstacle.stroke, layer: _6(t7, e53.layerCount) });\n })({ obstacles: e51.obstacles, bounds: e51.bounds, layerCount: e51.layerCount, theme: n7, graphics: t4 }), b6({ routes: e51.routes, attempt: e51.currentAttempt, activePair: e51.activePair, showAttempt: !e51.solved, theme: n7, graphics: t4 }), { ...t4 };\n};\nvar v6 = class extends BaseSolver {\n constructor(e51) {\n super(), this.params = e51, this.MAX_ITERATIONS = 1e5, this.matchedHdRoutes = e51.hdRoutes.map((e53) =\u003e ({ ...e53, route: e53.route.map((e54) =\u003e ({ ...e54 })) })), this.pairs = e51.differentialPairs ?? [];\n }\n matchedHdRoutes;\n pairs;\n nextPairIndex = 0;\n activePair = null;\n currentAttempt = null;\n config = null;\n candidatesTried = 0;\n getSolverName() {\n return \"LengthMatchingSolver\";\n }\n startNextPair() {\n const e51 = this.pairs[this.nextPairIndex++];\n if (!e51)\n return void (this.solved = true);\n ((e53, t7) =\u003e {\n if (e53.connectionNames[0] === e53.connectionNames[1])\n throw new Error(\"LengthMatchingSolver: a differential pair must reference two distinct connections\");\n if (!Number.isFinite(e53.lengthTolerance) || e53.lengthTolerance \u003c 0)\n throw new Error(\"LengthMatchingSolver: differential pair lengthTolerance must be a non-negative finite number\");\n for (const t8 of [e53.minimumCenterlineDistance, e53.maximumCenterlineDistance])\n if (t8 !== undefined \u0026\u0026 (!Number.isFinite(t8) || t8 \u003c= 0))\n throw new Error(\"LengthMatchingSolver: differential pair centerline distances must be positive finite numbers\");\n if (e53.minimumCenterlineDistance !== undefined \u0026\u0026 e53.maximumCenterlineDistance !== undefined \u0026\u0026 e53.minimumCenterlineDistance \u003e e53.maximumCenterlineDistance)\n throw new Error(\"LengthMatchingSolver: differential pair minimumCenterlineDistance cannot exceed maximumCenterlineDistance\");\n const n8 = new Map(t7.map((e54) =\u003e [e54.name, e54]));\n for (const t8 of e53.connectionNames) {\n const e54 = n8.get(t8);\n if (!e54)\n throw new Error(`LengthMatchingSolver: differential pair references unknown connection \"${t8}\"`);\n if (e54.pointsToConnect.length !== 2)\n throw new Error(`LengthMatchingSolver: differential pair connection \"${t8}\" must have exactly two points before MST splitting`);\n }\n })(e51, this.params.originalConnections);\n const t4 = Q4(this.matchedHdRoutes, e51.connectionNames[0]), n7 = Q4(this.matchedHdRoutes, e51.connectionNames[1]);\n if (t4.length === 0 \u0026\u0026 n7.length === 0)\n return;\n if (t4.length === 0 || n7.length === 0)\n throw new Error(`LengthMatchingSolver: differential pair ${e51.connectionNames.join(\"/\")} has routed geometry for only one connection`);\n const o7 = n6(this.matchedHdRoutes, t4), i7 = n6(this.matchedHdRoutes, n7), r7 = Math.abs(o7 - i7);\n if (r7 \u003c= e51.lengthTolerance)\n return;\n const s7 = o7 \u003c i7, a7 = e51.connectionNames[s7 ? 0 : 1], c5 = e51.connectionNames[s7 ? 1 : 0], l5 = r6({ routes: this.matchedHdRoutes, routeIndexes: s7 ? t4 : n7, maximumDepth: this.getConfig().maximumMeanderDepth, minimumToothPitch: this.getConfig().minimumToothPitch, minMeanderGap: this.getConfig().minMeanderGap, minMeanderHeight: this.getConfig().minMeanderHeight, maxToothCount: this.getConfig().maxToothCount });\n if (l5.length === 0)\n throw new m6({ message: `LengthMatchingSolver: no same-layer straight segment can tune connection \"${a7}\"`, connectionName: a7, reason: \"no-meander-candidate\" });\n this.activePair = { pair: e51, longerConnectionName: c5, longerRouteIndexes: s7 ? n7 : t4, shorterConnectionName: a7, targetAddedLength: r7, remainingAddedLength: r7, candidates: l5, candidateIndex: 0, lastMatchedSegmentIndexByRoute: new Map, partialAttempts: [], fullAttempts: [], plannedAttemptTargets: null, hasMinimumHeightBlockedAttempt: false };\n }\n acceptAttempt(e51, t4) {\n const n7 = this.matchedHdRoutes[t4.routeIndex];\n this.matchedHdRoutes[t4.routeIndex] = { ...n7, route: t4.predictedRoute }, e51.remainingAddedLength -= t4.addedLength, e51.lastMatchedSegmentIndexByRoute.set(t4.routeIndex, t4.segmentIndex), e51.candidateIndex = 0, e51.partialAttempts = [], e51.fullAttempts = [], e51.plannedAttemptTargets?.delete(g6(t4)), e51.plannedAttemptTargets?.size === 0 \u0026\u0026 (e51.plannedAttemptTargets = null), e51.remainingAddedLength \u003c= e51.pair.lengthTolerance \u0026\u0026 (this.activePair = null);\n }\n tryCandidate(e51) {\n let t4;\n for (;!t4; ) {\n const n8 = e51.candidates[e51.candidateIndex++];\n if (!n8)\n break;\n const o8 = e51.lastMatchedSegmentIndexByRoute.get(n8.routeIndex);\n (o8 === undefined || n8.segmentIndex \u003c o8) \u0026\u0026 (!e51.plannedAttemptTargets || e51.plannedAttemptTargets.has(g6(n8)) \u0026\u0026 ![...e51.plannedAttemptTargets.values()].some((e53) =\u003e e53.routeIndex === n8.routeIndex \u0026\u0026 e53.segmentIndex \u003e n8.segmentIndex)) \u0026\u0026 (t4 = n8);\n }\n if (!t4) {\n const t7 = e51.fullAttempts.reduce((e53, t8) =\u003e !e53 || t8.qualityScore \u003e e53.qualityScore ? t8 : e53, null), n8 = ((e53) =\u003e {\n const t8 = (e54) =\u003e [e54.toothCount, e54.placement, e54.heightProfile].join(\":\"), n9 = new Map;\n for (const o9 of e53.attempts) {\n const e54 = `${o9.routeIndex}:${o9.segmentIndex}`, i8 = t8(o9), r7 = n9.get(i8);\n if (!r7) {\n n9.set(i8, new Map([[e54, [o9]]]));\n continue;\n }\n const s7 = r7.get(e54);\n s7 ? s7.push(o9) : r7.set(e54, [o9]);\n }\n let o8 = null;\n for (const t9 of n9.values()) {\n const n10 = [...t9.values()].map((e54) =\u003e ({ attempts: e54, maximumCapacityAttempt: e54.reduce((e55, t10) =\u003e t10.addedLength \u003e e55.addedLength ? t10 : e55) })).sort((e54, t10) =\u003e t10.maximumCapacityAttempt.addedLength - e54.maximumCapacityAttempt.addedLength);\n let i8 = 0;\n for (let t10 = 0;t10 \u003c n10.length; t10++) {\n if (i8 += n10[t10].maximumCapacityAttempt.addedLength, i8 + e53.lengthTolerance \u003c e53.targetAddedLength)\n continue;\n const r7 = n10.slice(0, t10 + 1), s7 = r7.map((e54) =\u003e e54.maximumCapacityAttempt), a7 = f6({ attempts: s7, targetAddedLength: e53.targetAddedLength }), c5 = r7.map((t11) =\u003e {\n const n11 = a7.get(g6(t11.maximumCapacityAttempt));\n if (!n11)\n throw new Error(`LengthMatchingSolver: missing capacity target for ${g6(t11.maximumCapacityAttempt)}`);\n const o9 = t11.attempts.filter((t12) =\u003e t12.addedLength + e53.lengthTolerance \u003e= n11.targetAddedLength);\n if (o9.length === 0)\n throw new Error(`LengthMatchingSolver: no pitch can supply planned target for route ${t11.maximumCapacityAttempt.routeIndex} segment ${t11.maximumCapacityAttempt.segmentIndex}`);\n return o9.reduce((e54, t12) =\u003e t12.qualityScore \u003e e54.qualityScore || t12.qualityScore === e54.qualityScore \u0026\u0026 t12.toothPitch \u003e e54.toothPitch ? t12 : e54);\n }), l5 = u6(c5);\n if (!o8) {\n o8 = { attempts: c5 };\n break;\n }\n const h5 = u6(o8.attempts);\n (c5.length \u003c o8.attempts.length || c5.length === o8.attempts.length \u0026\u0026 l5 \u003e h5) \u0026\u0026 (o8 = { attempts: c5 });\n break;\n }\n }\n return o8;\n })({ attempts: e51.partialAttempts, targetAddedLength: e51.remainingAddedLength, lengthTolerance: e51.pair.lengthTolerance });\n if (t7 \u0026\u0026 (!n8 || t7.qualityScore \u003e= u6(n8.attempts)))\n return void this.acceptAttempt(e51, t7);\n if (!n8) {\n if (!(e51.hasMinimumHeightBlockedAttempt \u0026\u0026 e51.plannedAttemptTargets === null \u0026\u0026 e51.lastMatchedSegmentIndexByRoute.size === 0))\n throw new m6({ message: `LengthMatchingSolver: linear regression exhausted all segment/tooth combinations for \"${e51.shorterConnectionName}\"; required ${e51.targetAddedLength.toFixed(4)}mm`, connectionName: e51.shorterConnectionName, reason: \"meander-search-exhausted\" });\n return this.tryDualMeanderPlan(e51);\n }\n return e51.plannedAttemptTargets = f6({ attempts: n8.attempts, targetAddedLength: e51.remainingAddedLength }), e51.candidateIndex = 0, e51.partialAttempts = [], void (e51.fullAttempts = []);\n }\n const n7 = this.matchedHdRoutes[t4.routeIndex], o7 = this.getConfig(), i7 = e51.plannedAttemptTargets?.get(g6(t4));\n if (e51.plannedAttemptTargets !== null \u0026\u0026 i7 === undefined)\n throw new Error(`LengthMatchingSolver: missing planned target for ${g6(t4)}`);\n this.currentAttempt = l6({ candidate: t4, route: n7, connectionName: e51.shorterConnectionName, targetAddedLength: i7 === undefined ? e51.remainingAddedLength : i7.targetAddedLength, lengthTolerance: e51.pair.lengthTolerance, isGeometryValid: (e53) =\u003e i6({ route: n7, meanderPoints: e53, routedRoutes: this.matchedHdRoutes, traces: o7.traces, obstacles: o7.obstacles, bounds: o7.bounds, layerCount: o7.layerCount, obstacleMargin: o7.obstacleMargin }), getCenterlineDistanceCost: e51.pair.minimumCenterlineDistance === undefined \u0026\u0026 e51.pair.maximumCenterlineDistance === undefined ? undefined : (t7) =\u003e ((e53) =\u003e {\n let t8 = 0, n8 = 0;\n for (let o8 = 0;o8 \u003c e53.meanderPoints.length - 1; o8++) {\n const i8 = e53.meanderPoints[o8], r7 = e53.meanderPoints[o8 + 1], s7 = Math.hypot(r7.x - i8.x, r7.y - i8.y);\n if (s7 !== 0) {\n for (let t9 = 0;t9 \u003c 4; t9++) {\n const o9 = (t9 + 0.5) / 4, a7 = { x: i8.x + (r7.x - i8.x) * o9, y: i8.y + (r7.y - i8.y) * o9 }, c5 = [];\n for (const t10 of e53.pairedRoutes)\n for (let e54 = 0;e54 \u003c t10.route.length - 1; e54++) {\n const n9 = t10.route[e54], o10 = t10.route[e54 + 1];\n i8.z === n9.z \u0026\u0026 i8.z === o10.z \u0026\u0026 c5.push(K4(a7, a7, n9, o10));\n }\n if (c5.length === 0)\n return null;\n const l5 = Math.min(...c5);\n n8 += s7 * Math.max(0, (e53.minimumCenterlineDistance ?? Number.NEGATIVE_INFINITY) - l5, l5 - (e53.maximumCenterlineDistance ?? Number.POSITIVE_INFINITY)) / 4;\n }\n t8 += s7;\n }\n }\n if (t8 === 0)\n throw new Error(\"LengthMatchingSolver: cannot measure a zero-length meander centerline\");\n return n8 / t8;\n })({ meanderPoints: t7, pairedRoutes: e51.longerRouteIndexes.map((e53) =\u003e this.matchedHdRoutes[e53]), minimumCenterlineDistance: e51.pair.minimumCenterlineDistance, maximumCenterlineDistance: e51.pair.maximumCenterlineDistance }) }), this.candidatesTried++, this.currentAttempt.invalidReason === \"below-minimum-height\" \u0026\u0026 (e51.hasMinimumHeightBlockedAttempt = true), this.stats = { pair: `${e51.pair.connectionNames[0]}/${e51.pair.connectionNames[1]}`, candidatesTried: this.candidatesTried, segmentIndex: t4.segmentIndex, toothCount: t4.toothCount, toothPitch: t4.toothPitch, placement: t4.placement, predictedScaleFactor: this.currentAttempt.predictedScaleFactor, predictedToothDepths: this.currentAttempt.predictedToothDepths, resultingError: this.currentAttempt.resultingError, qualityScore: this.currentAttempt.qualityScore, accepted: this.currentAttempt.valid }, this.currentAttempt.valid \u0026\u0026 (e51.plannedAttemptTargets === null ? e51.remainingAddedLength - this.currentAttempt.addedLength \u003c= e51.pair.lengthTolerance ? e51.fullAttempts.push(this.currentAttempt) : e51.partialAttempts.push(this.currentAttempt) : this.acceptAttempt(e51, this.currentAttempt));\n }\n tryDualMeanderPlan(e51) {\n if (e51.remainingAddedLength !== e51.targetAddedLength)\n throw new Error(`LengthMatchingSolver: cannot start a dual-meander plan after partially tuning \"${e51.shorterConnectionName}\"`);\n const t4 = this.getConfig(), n7 = r6({ routes: this.matchedHdRoutes, routeIndexes: e51.longerRouteIndexes, maximumDepth: t4.maximumMeanderDepth, minimumToothPitch: t4.minimumToothPitch, minMeanderGap: t4.minMeanderGap, minMeanderHeight: t4.minMeanderHeight, maxToothCount: t4.maxToothCount }), o7 = ((e53) =\u003e {\n const t7 = (e54, t8) =\u003e e54.rankingQualityScore !== t8.rankingQualityScore ? e54.rankingQualityScore \u003e t8.rankingQualityScore : e54.leftIndex !== t8.leftIndex ? e54.leftIndex \u003c t8.leftIndex : e54.rightIndex \u003c t8.rightIndex, n8 = (e54, n9) =\u003e {\n e54.push(n9);\n let o9 = e54.length - 1;\n for (;o9 \u003e 0; ) {\n const i9 = Math.floor((o9 - 1) / 2), r9 = e54[i9];\n if (t7(r9, n9))\n break;\n e54[o9] = r9, o9 = i9;\n }\n e54[o9] = n9;\n }, o8 = (e54) =\u003e {\n const n9 = e54[0], o9 = e54.pop();\n if (!n9 || !o9 || e54.length === 0)\n return n9;\n let i9 = 0;\n for (;; ) {\n const n10 = 2 * i9 + 1, r9 = n10 + 1;\n if (n10 \u003e= e54.length)\n break;\n const s9 = r9 \u003c e54.length \u0026\u0026 t7(e54[r9], e54[n10]) ? r9 : n10, a8 = e54[s9];\n if (t7(o9, a8))\n break;\n e54[i9] = a8, i9 = s9;\n }\n return e54[i9] = o9, n9;\n }, i8 = function* (e54) {\n const t8 = [...e54.leftOptions].sort((t9, n9) =\u003e e54.getLeftQualityScore(n9) - e54.getLeftQualityScore(t9)), i9 = [...e54.rightOptions].sort((t9, n9) =\u003e e54.getRightQualityScore(n9) - e54.getRightQualityScore(t9)), r9 = [];\n for (let o9 = 0;o9 \u003c t8.length; o9++) {\n const s9 = i9[0];\n if (!s9)\n break;\n n8(r9, { leftIndex: o9, rightIndex: 0, rankingQualityScore: (e54.getLeftQualityScore(t8[o9]) + e54.getRightQualityScore(s9)) / 2 });\n }\n for (;r9.length \u003e 0; ) {\n const s9 = o8(r9);\n yield [t8[s9.leftIndex], i9[s9.rightIndex]];\n const a8 = s9.rightIndex + 1, c7 = i9[a8];\n c7 \u0026\u0026 n8(r9, { leftIndex: s9.leftIndex, rightIndex: a8, rankingQualityScore: (e54.getLeftQualityScore(t8[s9.leftIndex]) + e54.getRightQualityScore(c7)) / 2 });\n }\n }, r8 = (e54, t8) =\u003e {\n const n9 = e54[t8.routeIndex];\n if (!n9)\n throw new Error(`LengthMatchingSolver: dual meander references missing route ${t8.routeIndex}`);\n const o9 = [...e54];\n return o9[t8.routeIndex] = { ...n9, route: t8.predictedRoute }, o9;\n }, s8 = (e54) =\u003e {\n const t8 = e54.routes[e54.attempt.routeIndex];\n if (!t8)\n throw new Error(`LengthMatchingSolver: cannot validate missing dual-meander route ${e54.attempt.routeIndex}`);\n return i6({ route: t8, meanderPoints: e54.attempt.meanderPoints, routedRoutes: e54.routes, ...e54.config });\n }, a7 = (e54) =\u003e {\n const t8 = e54.routes.filter((t9) =\u003e J4(t9) !== e54.counterpartConnectionName), n9 = [];\n for (const o9 of e54.candidates) {\n const i9 = e54.routes[o9.routeIndex];\n if (!i9)\n throw new Error(`LengthMatchingSolver: dual-meander candidate references missing route ${o9.routeIndex}`);\n const r9 = h6({ candidate: o9, route: i9, connectionName: e54.connectionName, lengthTolerance: e54.config.lengthTolerance, isGeometryValid: (n10) =\u003e i6({ route: i9, meanderPoints: n10, routedRoutes: t8, ...e54.config }) });\n r9 \u0026\u0026 n9.push({ candidate: o9, attempt: r9 });\n }\n return n9;\n }, c5 = { traces: e53.traces, obstacles: e53.obstacles, bounds: e53.bounds, layerCount: e53.layerCount, obstacleMargin: e53.obstacleMargin }, l5 = a7({ candidates: e53.shorterCandidates, routes: e53.routes, connectionName: e53.shorterConnectionName, counterpartConnectionName: e53.longerConnectionName, config: { ...c5, lengthTolerance: e53.lengthTolerance } });\n if (l5.length === 0)\n return null;\n const h5 = a7({ candidates: e53.longerCandidates, routes: e53.routes, connectionName: e53.longerConnectionName, counterpartConnectionName: e53.shorterConnectionName, config: { ...c5, lengthTolerance: e53.lengthTolerance } }), d7 = i8({ leftOptions: h5, rightOptions: l5, getLeftQualityScore: (e54) =\u003e e54.attempt.qualityScore, getRightQualityScore: (e54) =\u003e e54.attempt.qualityScore });\n for (const [t8, n9] of d7) {\n const o9 = Math.max(t8.attempt.addedLength, n9.attempt.addedLength - e53.originalLengthDifference), i9 = o9 + e53.originalLengthDifference;\n if (o9 - e53.lengthTolerance \u003e t8.attempt.maximumAddedLength || i9 - e53.lengthTolerance \u003e n9.attempt.maximumAddedLength)\n continue;\n const a8 = e53.routes[t8.candidate.routeIndex];\n if (!a8)\n throw new Error(`LengthMatchingSolver: missing longer route ${t8.candidate.routeIndex}`);\n const l7 = e53.routes[n9.candidate.routeIndex];\n if (!l7)\n throw new Error(`LengthMatchingSolver: missing shorter route ${n9.candidate.routeIndex}`);\n const h7 = e53.routes.filter((t9) =\u003e J4(t9) !== e53.shorterConnectionName), d8 = l6({ candidate: t8.candidate, route: a8, connectionName: e53.longerConnectionName, targetAddedLength: o9, lengthTolerance: e53.lengthTolerance, isGeometryValid: (e54) =\u003e i6({ route: a8, meanderPoints: e54, routedRoutes: h7, ...c5 }) });\n if (!d8.valid || Math.abs(d8.addedLength - o9) \u003e e53.lengthTolerance)\n continue;\n const u8 = r8(e53.routes, d8), p7 = d8.addedLength + e53.originalLengthDifference, m7 = l6({ candidate: n9.candidate, route: l7, connectionName: e53.shorterConnectionName, targetAddedLength: p7, lengthTolerance: e53.lengthTolerance, isGeometryValid: (e54) =\u003e i6({ route: l7, meanderPoints: e54, routedRoutes: u8, ...c5 }) });\n if (!m7.valid)\n continue;\n const g7 = r8(u8, m7), f7 = Q4(g7, e53.longerConnectionName), _5 = Q4(g7, e53.shorterConnectionName);\n if (!(Math.abs(n6(g7, _5) - n6(g7, f7)) \u003e e53.lengthTolerance) \u0026\u0026 s8({ attempt: d8, routes: g7, config: c5 }) \u0026\u0026 s8({ attempt: m7, routes: g7, config: c5 }))\n return { longerAttempts: [d8], shorterAttempts: [m7] };\n }\n const u7 = i8({ leftOptions: p6(h5), rightOptions: p6(l5), getLeftQualityScore: (e54) =\u003e e54.rankingQualityScore, getRightQualityScore: (e54) =\u003e e54.rankingQualityScore });\n for (const [t8, n9] of u7) {\n if (t8.attempts.length === 1 \u0026\u0026 n9.attempts.length === 1)\n continue;\n const o9 = Math.max(t8.minimumAddedLength, n9.minimumAddedLength - e53.originalLengthDifference), i9 = o9 + e53.originalLengthDifference;\n if (o9 - e53.lengthTolerance \u003e t8.maximumAddedLength || i9 - e53.lengthTolerance \u003e n9.maximumAddedLength)\n continue;\n const r9 = d6({ plan: t8, targetAddedLength: o9, routes: e53.routes, connectionName: e53.longerConnectionName, excludedConnectionName: e53.shorterConnectionName, config: { ...c5, lengthTolerance: e53.lengthTolerance } });\n if (!r9)\n continue;\n const a8 = d6({ plan: n9, targetAddedLength: r9.addedLength + e53.originalLengthDifference, routes: r9.routes, connectionName: e53.shorterConnectionName, config: { ...c5, lengthTolerance: e53.lengthTolerance } });\n if (!a8)\n continue;\n const l7 = Q4(a8.routes, e53.longerConnectionName), h7 = Q4(a8.routes, e53.shorterConnectionName), d8 = Math.abs(n6(a8.routes, h7) - n6(a8.routes, l7)), u8 = [...r9.attempts, ...a8.attempts];\n if (!(d8 \u003e e53.lengthTolerance || u8.some((e54) =\u003e !s8({ attempt: e54, routes: a8.routes, config: c5 }))))\n return { longerAttempts: r9.attempts, shorterAttempts: a8.attempts };\n }\n return null;\n })({ routes: this.matchedHdRoutes, longerConnectionName: e51.longerConnectionName, shorterConnectionName: e51.shorterConnectionName, originalLengthDifference: e51.targetAddedLength, lengthTolerance: e51.pair.lengthTolerance, longerCandidates: n7, shorterCandidates: e51.candidates, traces: t4.traces, obstacles: t4.obstacles, bounds: t4.bounds, layerCount: t4.layerCount, obstacleMargin: t4.obstacleMargin });\n if (!o7)\n throw new m6({ message: `LengthMatchingSolver: linear regression exhausted all segment/tooth combinations for \"${e51.shorterConnectionName}\"; required ${e51.targetAddedLength.toFixed(4)}mm`, connectionName: e51.shorterConnectionName, reason: \"meander-search-exhausted\" });\n const i7 = [...this.matchedHdRoutes];\n for (const e53 of [...o7.longerAttempts, ...o7.shorterAttempts]) {\n const t7 = this.matchedHdRoutes[e53.routeIndex];\n if (!t7)\n throw new Error(`LengthMatchingSolver: cannot commit dual meander to missing route ${e53.routeIndex}`);\n i7[e53.routeIndex] = { ...t7, route: e53.predictedRoute };\n }\n this.matchedHdRoutes = i7, this.currentAttempt = o7.shorterAttempts[0];\n const r7 = o7.longerAttempts.reduce((e53, t7) =\u003e e53 + t7.addedLength, 0), s7 = o7.shorterAttempts.reduce((e53, t7) =\u003e e53 + t7.addedLength, 0);\n this.stats = { pair: `${e51.pair.connectionNames[0]}/${e51.pair.connectionNames[1]}`, mode: \"dual-meander\", longerAddedLength: r7, shorterAddedLength: s7, resultingError: Math.abs(s7 - r7 - e51.targetAddedLength) }, this.activePair = null;\n }\n getConfig() {\n return this.config || (this.config = ((e51) =\u003e {\n const t4 = e51.maximumMeanderDepth ?? 5, n7 = e51.maxToothCount ?? 12;\n if (!Number.isFinite(t4) || t4 \u003c= 0)\n throw new Error(\"LengthMatchingSolver: maximumMeanderDepth must be a positive finite number\");\n if (e51.minimumToothPitch !== undefined \u0026\u0026 (!Number.isFinite(e51.minimumToothPitch) || e51.minimumToothPitch \u003c= 0))\n throw new Error(\"LengthMatchingSolver: minimumToothPitch must be a positive finite number\");\n if (e51.minMeanderGap !== undefined \u0026\u0026 (!Number.isFinite(e51.minMeanderGap) || e51.minMeanderGap \u003c= 0))\n throw new Error(\"LengthMatchingSolver: minMeanderGap must be a positive finite number\");\n if (e51.minMeanderHeight !== undefined \u0026\u0026 (!Number.isFinite(e51.minMeanderHeight) || e51.minMeanderHeight \u003c= 0))\n throw new Error(\"LengthMatchingSolver: minMeanderHeight must be a positive finite number\");\n if (e51.minMeanderHeight !== undefined \u0026\u0026 e51.minMeanderHeight \u003e t4)\n throw new Error(\"LengthMatchingSolver: minMeanderHeight cannot exceed maximumMeanderDepth\");\n if (!Number.isFinite(n7) || !Number.isInteger(n7) || n7 \u003c= 0)\n throw new Error(\"LengthMatchingSolver: maxToothCount must be a positive finite integer\");\n for (const t7 of e51.traces ?? [])\n q4(t7, e51.layerCount ?? 2);\n return { maximumMeanderDepth: t4, minimumToothPitch: e51.minimumToothPitch, minMeanderGap: e51.minMeanderGap, minMeanderHeight: e51.minMeanderHeight, maxToothCount: n7, traces: e51.traces ?? [], obstacles: e51.obstacles ?? [], bounds: e51.bounds, obstacleMargin: e51.obstacleMargin ?? 0.15, layerCount: e51.layerCount ?? 2, colorMap: e51.colorMap ?? {} };\n })(this.params)), this.config;\n }\n _step() {\n this.getConfig(), this.activePair ? this.tryCandidate(this.activePair) : this.startNextPair();\n }\n getConstructorParams() {\n return [this.params];\n }\n getOutput() {\n if (!this.solved)\n throw new Error(\"LengthMatchingSolver: getOutput() called before the solver completed\");\n return { matchedHdRoutes: this.matchedHdRoutes };\n }\n getBestEffortOutput() {\n const e51 = structuredClone(this.matchedHdRoutes), t4 = this.activePair?.fullAttempts ?? [];\n let n7 = null;\n for (const e53 of t4)\n (!n7 || e53.qualityScore \u003e n7.qualityScore) \u0026\u0026 (n7 = e53);\n if (!n7)\n for (const e53 of this.activePair?.partialAttempts ?? [])\n (!n7 || e53.addedLength \u003e n7.addedLength || e53.addedLength === n7.addedLength \u0026\u0026 e53.qualityScore \u003e n7.qualityScore) \u0026\u0026 (n7 = e53);\n if (n7) {\n const t7 = e51[n7.routeIndex];\n t7 \u0026\u0026 (e51[n7.routeIndex] = { ...t7, route: structuredClone(n7.predictedRoute) });\n }\n return { matchedHdRoutes: e51 };\n }\n computeProgress() {\n if (this.solved)\n return 1;\n if (this.pairs.length === 0)\n return this.config ? 1 : 0;\n const e51 = Math.max(0, this.nextPairIndex - 1), t4 = this.activePair ? this.activePair.candidateIndex / this.activePair.candidates.length : 0;\n return Math.min(0.99, (e51 + t4) / this.pairs.length);\n }\n visualize() {\n const e51 = this.getConfig();\n return x6({ routes: this.matchedHdRoutes, obstacles: e51.obstacles, bounds: e51.bounds, layerCount: e51.layerCount, colorMap: e51.colorMap, activePair: this.activePair, currentAttempt: this.currentAttempt, solved: this.solved });\n }\n};\nvar C6 = 0.00000001;\nvar P6 = (e51, t4) =\u003e {\n if (e51.route.length === 0)\n throw new Error(`trace \"${e51.connection_name}\" has an empty route`);\n if (e51.route.some((e53) =\u003e e53.route_type !== \"wire\" \u0026\u0026 e53.route_type !== \"via\"))\n throw new Error(`trace \"${e51.connection_name}\" contains unsupported jumper or through-obstacle geometry`);\n const n7 = e51.route.findIndex((e53) =\u003e e53.route_type === \"wire\"), o7 = e51.route[n7], i7 = e51.route.findLast((e53) =\u003e e53.route_type === \"wire\");\n if (o7?.route_type !== \"wire\" || !i7)\n throw new Error(`trace \"${e51.connection_name}\" must contain a wire point`);\n const r7 = [], s7 = [], a7 = [], c5 = [];\n let l5 = null, h5 = o7.width;\n if (n7 \u003e 0) {\n let t7 = o7.layer;\n for (let o8 = n7 - 1;o8 \u003e= 0; o8--) {\n const n8 = e51.route[o8];\n if (n8?.route_type !== \"via\")\n throw new Error(`trace \"${e51.connection_name}\" has unsupported geometry before its first wire`);\n if (t7 === n8.to_layer)\n t7 = n8.from_layer;\n else {\n if (t7 !== n8.from_layer)\n throw new Error(`trace \"${e51.connection_name}\" has discontinuous leading vias`);\n t7 = n8.to_layer;\n }\n }\n const i8 = e51.route[0];\n if (i8.route_type !== \"via\")\n throw new Error(`trace \"${e51.connection_name}\" has an invalid leading entry`);\n l5 = { x: i8.x, y: i8.y, layer: t7, width: o7.width }, r7.push(l5);\n }\n for (const n8 of e51.route) {\n if (n8.route_type === \"wire\") {\n if (!Number.isFinite(n8.x) || !Number.isFinite(n8.y) || !Number.isFinite(n8.width) || n8.width \u003c= 0 || G4(n8.layer, t4) \u003c 0)\n throw new Error(`trace \"${e51.connection_name}\" has an invalid wire point`);\n h5 = Math.max(h5, n8.width);\n const o9 = { x: n8.x, y: n8.y, layer: n8.layer, width: n8.width };\n if (l5) {\n if (l5.layer !== o9.layer)\n throw new Error(`trace \"${e51.connection_name}\" changes layers without a via`);\n Math.hypot(l5.x - o9.x, l5.y - o9.y) \u003e C6 \u0026\u0026 s7.push({ start: l5, end: o9, layer: o9.layer, width: Math.max(l5.width, o9.width), connectionName: e51.connection_name, terminal: null });\n }\n r7.push(o9), l5 = o9;\n continue;\n }\n if (n8.route_type !== \"via\")\n throw new Error(`trace \"${e51.connection_name}\" contains unsupported route geometry`);\n if (!l5)\n throw new Error(`trace \"${e51.connection_name}\" has a leading via`);\n const o8 = G4(n8.from_layer, t4), i8 = G4(n8.to_layer, t4), d8 = n8.via_diameter ?? l5.width;\n if (!Number.isFinite(n8.x) || !Number.isFinite(n8.y) || o8 \u003c 0 || i8 \u003c 0 || o8 === i8 || n8.via_diameter !== undefined \u0026\u0026 (!Number.isFinite(n8.via_diameter) || n8.via_diameter \u003c= 0) || n8.via_hole_diameter !== undefined \u0026\u0026 (!Number.isFinite(n8.via_hole_diameter) || n8.via_hole_diameter \u003c= 0 || n8.via_hole_diameter \u003e= d8))\n throw new Error(`trace \"${e51.connection_name}\" has an invalid via`);\n const u7 = l5.layer === n8.from_layer ? n8.from_layer : l5.layer === n8.to_layer ? n8.to_layer : null;\n if (!u7)\n throw new Error(`trace \"${e51.connection_name}\" has a discontinuous via transition`);\n Math.hypot(l5.x - n8.x, l5.y - n8.y) \u003e C6 \u0026\u0026 s7.push({ start: l5, end: n8, layer: l5.layer, width: l5.width, connectionName: e51.connection_name, terminal: null });\n const p7 = u7 === n8.from_layer ? n8.to_layer : n8.from_layer;\n c5.push({ ...n8, from_layer: u7, to_layer: p7 }), a7.push({ x: n8.x, y: n8.y, layers: Z4(u7, p7, t4), diameter: d8, connectionName: e51.connection_name, terminal: r7.length === 1 ? \"start\" : null }), l5 = { x: n8.x, y: n8.y, layer: p7, width: l5.width }, r7.push(l5);\n }\n if (r7.length \u003c 2 || s7.length === 0)\n throw new Error(`trace \"${e51.connection_name}\" does not contain a routable path`);\n s7[0].terminal = s7.length === 1 ? \"both\" : \"start\", s7[s7.length - 1].terminal = s7.length === 1 ? \"both\" : \"end\";\n const d7 = a7.at(-1);\n return d7 \u0026\u0026 Math.hypot(d7.x - i7.x, d7.y - i7.y) \u003c= C6 \u0026\u0026 (d7.terminal = \"end\"), { source: e51, points: r7, segments: s7, vias: a7, transitions: c5, width: h5, viaDiameter: e51.__postProcessingViaDiameter ?? h5, ...o7.start_pcb_port_id ? { startPortId: o7.start_pcb_port_id } : {}, ...i7.end_pcb_port_id ? { endPortId: i7.end_pcb_port_id } : {} };\n};\nvar M6 = (e51) =\u003e e51.segments.reduce((e53, t4) =\u003e e53 + Math.hypot(t4.end.x - t4.start.x, t4.end.y - t4.start.y), 0);\nvar w6 = (e51) =\u003e {\n const { simpleRouteJson: t4 } = e51.params, n7 = ((e53) =\u003e {\n const t7 = new Set(e53.reroutedPairs.map((e54) =\u003e e54.connectionNames.join(\"\\x00\")));\n return e53.declaredPairs.filter((n8) =\u003e {\n const o8 = n8.connectionNames.map((t8) =\u003e e53.traces.filter((e54) =\u003e e54.connection_name === t8));\n if (o8.some((e54) =\u003e e54.length !== 1))\n return false;\n if (t7.has(n8.connectionNames.join(\"\\x00\")))\n return true;\n const i8 = o8.map((e54) =\u003e e54[0]);\n if (i8.some((e54) =\u003e e54.route.length \u003c 2 || e54.route[0]?.route_type !== \"wire\" || !e54.route.every((e55) =\u003e e55.route_type === \"wire\" || e55.route_type === \"via\")))\n return false;\n const r8 = i8.map((t8) =\u003e M6(P6(t8, e53.layerCount)));\n return Math.abs(r8[0] - r8[1]) \u003e n8.lengthTolerance + 0.0000001;\n }).map((e54) =\u003e structuredClone(e54));\n })({ traces: e51.result.traces, declaredPairs: t4.differentialPairs, reroutedPairs: e51.result.reroutedPairs, layerCount: t4.layerCount }), o7 = new Set(n7.flatMap((e53) =\u003e e53.connectionNames)), i7 = [], r7 = [], s7 = [], a7 = new Set;\n for (let n8 = 0;n8 \u003c e51.result.traces.length; n8++) {\n const c7 = e51.result.traces[n8];\n if (!o7.has(c7.connection_name))\n continue;\n const l7 = c7.route.every((e53) =\u003e e53.route_type === \"wire\" || e53.route_type === \"via\"), h5 = c7.route[0]?.route_type === \"wire\";\n if (!l7 || !h5)\n throw new Error(`PostProcessingSolver: rerouted connection \"${c7.connection_name}\" cannot be bound to LengthMatchingSolver`);\n const d7 = P6(c7, t4.layerCount), u7 = c7.route[0];\n if (u7.route_type !== \"wire\")\n throw new Error(`PostProcessingSolver: trace \"${c7.connection_name}\" lost its first wire during binding`);\n const p7 = [{ x: u7.x, y: u7.y, z: G4(u7.layer, t4.layerCount), traceThickness: u7.width }], m7 = [], g7 = [];\n let { layer: f7, width: _5 } = u7;\n for (const e53 of c7.route.slice(1)) {\n if (e53.route_type === \"wire\") {\n if (e53.layer !== f7)\n throw new Error(`PostProcessingSolver: trace \"${c7.connection_name}\" changes layers without a via while binding`);\n p7.push({ x: e53.x, y: e53.y, z: G4(e53.layer, t4.layerCount), traceThickness: e53.width }), _5 = e53.width;\n continue;\n }\n if (e53.route_type !== \"via\")\n throw new Error(`PostProcessingSolver: trace \"${c7.connection_name}\" contains unsupported bound geometry`);\n const n9 = f7 === e53.from_layer ? e53.to_layer : f7 === e53.to_layer ? e53.from_layer : null;\n if (!n9)\n throw new Error(`PostProcessingSolver: trace \"${c7.connection_name}\" has a discontinuous bound via`);\n const o8 = p7.at(-1);\n Math.hypot(o8.x - e53.x, o8.y - e53.y) \u003e 0.00000001 \u0026\u0026 p7.push({ x: e53.x, y: e53.y, z: G4(f7, t4.layerCount), traceThickness: _5 }), p7.push({ x: e53.x, y: e53.y, z: G4(n9, t4.layerCount), traceThickness: _5 }), m7.push({ x: e53.x, y: e53.y, zLayers: Z4(e53.from_layer, e53.to_layer, t4.layerCount).map((e54) =\u003e G4(e54, t4.layerCount)) }), g7.push({ ...e53 }), f7 = n9;\n }\n if (p7.length \u003c 2)\n throw new Error(`PostProcessingSolver: trace \"${c7.connection_name}\" has no bound copper segments`);\n const y7 = Math.max(...p7.map((e53) =\u003e e53.traceThickness ?? d7.width)), b7 = d7.viaDiameter, x7 = i7.length;\n i7.push({ connectionName: c7.connection_name, traceThickness: y7, viaDiameter: b7, route: p7, vias: m7 });\n const v7 = p7[0], I6 = p7.at(-1);\n r7.push({ name: c7.connection_name, pointsToConnect: [{ x: v7.x, y: v7.y, layer: u7.layer, ...d7.startPortId ? { pcb_port_id: d7.startPortId } : {} }, { x: I6.x, y: I6.y, layer: d7.points.at(-1).layer, ...d7.endPortId ? { pcb_port_id: d7.endPortId } : {} }] }), s7.push({ traceIndex: n8, matchedRouteIndex: x7, viaTemplates: g7, startEndpoint: { ...v7 }, endEndpoint: { ...I6 }, ...d7.startPortId ? { startPortId: d7.startPortId } : {}, ...d7.endPortId ? { endPortId: d7.endPortId } : {} }), a7.add(c7.connection_name);\n }\n for (const e53 of o7)\n if (!a7.has(e53))\n throw new Error(`PostProcessingSolver: missing LengthMatchingSolver binding for rerouted connection \"${e53}\"`);\n const c5 = e51.result.traces.filter((e53) =\u003e !o7.has(e53.connection_name)), l5 = t4.minTraceToPadEdgeClearance ?? Math.max(0, ...i7.filter((e53) =\u003e e53.route.length \u003e= 2).map((e53) =\u003e e53.traceThickness), ...c5.flatMap((e53) =\u003e q4(e53, t4.layerCount).segments.map((e54) =\u003e e54.width)));\n return { solverParams: { hdRoutes: i7, traces: c5, originalConnections: r7, differentialPairs: n7, obstacles: t4.obstacles, bounds: t4.bounds, layerCount: t4.layerCount, obstacleMargin: l5 }, traceBindings: s7, baseTraces: structuredClone(e51.result.traces) };\n};\nvar N6 = (e51) =\u003e {\n const t4 = new Map;\n for (const n8 of e51.differentialPairs)\n for (const o8 of n8.connectionNames) {\n const n9 = e51.hdRoutes.map((e53, t7) =\u003e ({ route: e53, hdRouteIndex: t7 })).filter(({ route: e53 }) =\u003e e53.connectionName === o8);\n n9.length === 1 \u0026\u0026 t4.set(n9[0].hdRouteIndex, o8);\n }\n const n7 = e51.hdRoutes.map((t7, n8) =\u003e {\n const o8 = [], i8 = new Map;\n for (let e53 = 0;e53 \u003c (t7.jumpers?.length ?? 0); e53++) {\n const n9 = t7.jumpers[e53], o9 = t7.route.map((e54, t8) =\u003e ({ point: e54, index: t8 })).filter(({ point: e54 }) =\u003e Math.hypot(e54.x - n9.start.x, e54.y - n9.start.y) \u003c= 0.00000001).map(({ index: e54 }) =\u003e e54), r8 = t7.route.map((e54, t8) =\u003e ({ point: e54, index: t8 })).filter(({ point: e54 }) =\u003e Math.hypot(e54.x - n9.end.x, e54.y - n9.end.y) \u003c= 0.00000001).map(({ index: e54 }) =\u003e e54), s8 = [...o9.flatMap((e54) =\u003e r8.filter((t8) =\u003e t8 \u003e e54).map((t8) =\u003e ({ startIndex: e54, endIndex: t8 }))), ...r8.flatMap((e54) =\u003e o9.filter((t8) =\u003e t8 \u003e e54).map((t8) =\u003e ({ startIndex: e54, endIndex: t8 })))];\n if (s8.length !== 1)\n throw new Error(`PostProcessingSolver: immutable HD route \"${t7.connectionName}\" has an ambiguous jumper traversal`);\n const a7 = s8[0];\n if (i8.has(a7.startIndex) || [...i8.values()].some(({ endIndex: e54 }) =\u003e a7.startIndex \u003c e54 || a7.endIndex \u003c= e54))\n throw new Error(`PostProcessingSolver: immutable HD route \"${t7.connectionName}\" has overlapping or unordered jumpers`);\n i8.set(a7.startIndex, { endIndex: a7.endIndex, jumperIndex: e53 });\n }\n if (t7.route.length \u003e 0) {\n const n9 = t7.route[0];\n o8.push({ route_type: \"wire\", x: n9.x, y: n9.y, width: n9.traceThickness ?? t7.traceThickness, layer: U4(n9.z, e51.layerCount) });\n for (let n10 = 0;n10 \u003c t7.route.length - 1; n10++) {\n const r9 = t7.route[n10], s9 = i8.get(n10);\n if (s9) {\n const i9 = t7.route[s9.endIndex], a9 = t7.jumpers[s9.jumperIndex];\n if (r9.z !== i9.z)\n throw new Error(`PostProcessingSolver: immutable HD route \"${t7.connectionName}\" changes layers through a jumper`);\n o8.push({ route_type: \"jumper\", start: { x: r9.x, y: r9.y }, end: { x: i9.x, y: i9.y }, footprint: a9.footprint, layer: U4(r9.z, e51.layerCount) }), o8.push({ route_type: \"wire\", x: i9.x, y: i9.y, width: i9.traceThickness ?? t7.traceThickness, layer: U4(i9.z, e51.layerCount) }), n10 = s9.endIndex - 1;\n continue;\n }\n const a8 = t7.route[n10 + 1], c5 = U4(r9.z, e51.layerCount), l5 = U4(a8.z, e51.layerCount);\n r9.z !== a8.z \u0026\u0026 (r9.toNextSegmentType === \"through_obstacle\" ? o8.push({ route_type: \"through_obstacle\", start: { x: r9.x, y: r9.y }, end: { x: a8.x, y: a8.y }, from_layer: c5, to_layer: l5, width: r9.traceThickness ?? t7.traceThickness }) : o8.push({ route_type: \"via\", x: a8.x, y: a8.y, from_layer: c5, to_layer: l5, via_diameter: t7.viaDiameter })), o8.push({ route_type: \"wire\", x: a8.x, y: a8.y, width: a8.traceThickness ?? t7.traceThickness, layer: l5 });\n }\n const r8 = o8.filter((e53) =\u003e e53.route_type === \"wire\"), s8 = t7.startPcbPortId ?? t7.route[0]?.pcb_port_id, a7 = t7.endPcbPortId ?? t7.route.at(-1)?.pcb_port_id;\n s8 \u0026\u0026 r8[0] \u0026\u0026 (r8[0].start_pcb_port_id = s8), a7 \u0026\u0026 r8.at(-1) \u0026\u0026 (r8.at(-1).end_pcb_port_id = a7);\n }\n return { type: \"pcb_trace\", pcb_trace_id: `post_processing_hd_route_${n8}`, connection_name: t7.connectionName, __postProcessingViaDiameter: t7.viaDiameter, route: o8 };\n }), o7 = new Set(n7.map((e53) =\u003e e53.connection_name));\n for (const [t7, i8] of (e51.traces ?? []).entries()) {\n let e53 = `post_processing_fixed_trace_${t7}`;\n for (;o7.has(e53); )\n e53 += \"_\";\n o7.add(e53), n7.push({ ...structuredClone(i8), connection_name: e53 });\n }\n const i7 = structuredClone(e51.obstacles), r7 = new Map, s7 = new Map;\n for (const e53 of i7)\n for (const t7 of e53.connectedTo) {\n let n8 = r7.get(t7);\n n8 || (n8 = new Set, r7.set(t7, n8)), n8.add(e53);\n }\n for (let n8 = 0;n8 \u003c e51.hdRoutes.length; n8++) {\n const o8 = e51.hdRoutes[n8], i8 = new Set([o8.connectionName, o8.rootConnectionName, o8.startPcbPortId, o8.endPcbPortId, o8.route[0]?.pcb_port_id, o8.route.at(-1)?.pcb_port_id, t4.get(n8)].filter((e53) =\u003e e53 !== undefined)), a7 = new Set;\n for (const e53 of i8) {\n const t7 = r7.get(e53);\n if (t7)\n for (const e54 of t7)\n a7.add(e54);\n }\n for (const e53 of a7) {\n let t7 = s7.get(e53);\n t7 || (t7 = new Set(e53.connectedTo), s7.set(e53, t7), e53.connectedTo = [...t7]);\n for (const n9 of i8) {\n if (t7.has(n9))\n continue;\n t7.add(n9), e53.connectedTo.push(n9);\n let o9 = r7.get(n9);\n o9 || (o9 = new Set, r7.set(n9, o9)), o9.add(e53);\n }\n }\n }\n return { params: { simpleRouteJson: { traces: n7, differentialPairs: structuredClone(e51.differentialPairs), obstacles: i7, bounds: structuredClone(e51.bounds), layerCount: e51.layerCount, minTraceToPadEdgeClearance: e51.minTraceToPadEdgeClearance }, ...e51.routingGrid ? { routingGrid: structuredClone(e51.routingGrid) } : {} }, routeBindings: [...t4.entries()].map(([e53, t7]) =\u003e ({ hdRouteIndex: e53, traceIndex: e53, internalConnectionName: t7 })), sourceHdRoutes: structuredClone(e51.hdRoutes) };\n};\nfunction R6(e51) {\n const t4 = structuredClone(e51.model.sourceHdRoutes);\n for (const n7 of e51.model.routeBindings) {\n const o7 = e51.binding.traceBindings.find((e53) =\u003e e53.traceIndex === n7.traceIndex);\n if (!o7)\n continue;\n const i7 = e51.result.matchedHdRoutes[o7.matchedRouteIndex], r7 = t4[n7.hdRouteIndex];\n if (!i7 || !r7)\n throw new Error(`PostProcessingSolver: missing matched or source HD route for \"${n7.internalConnectionName}\"`);\n if (i7.connectionName !== n7.internalConnectionName)\n throw new Error(`PostProcessingSolver: matched HD binding changed \"${n7.internalConnectionName}\" to \"${i7.connectionName}\"`);\n const s7 = i7.route.map((e53) =\u003e ({ ...e53 })), a7 = (t7, o8) =\u003e {\n if (t7 \u0026\u0026 o8 \u0026\u0026 (o8.pcb_port_id \u0026\u0026 (t7.pcb_port_id = o8.pcb_port_id), o8.insideJumperPad \u0026\u0026 e51.rejectInsideJumperPad))\n throw new Error(`PostProcessingSolver: cannot restore jumper-pad metadata on rerouted connection \"${n7.internalConnectionName}\"`);\n };\n a7(s7[0], r7.route[0]), a7(s7.at(-1), r7.route.at(-1)), t4[n7.hdRouteIndex] = { ...r7, route: s7, vias: structuredClone(i7.vias) };\n }\n return { hdRoutes: t4, postProcessingErrors: [] };\n}\nvar T6 = class extends Error {\n connectionNames;\n reason;\n constructor(e51) {\n super(`PostProcessingSolver: differential pair ${e51.connectionNames.join(\"/\")} ${e51.message}`), this.name = \"DifferentialPairRoutingError\", this.connectionNames = [e51.connectionNames[0], e51.connectionNames[1]], this.reason = e51.reason;\n }\n};\nvar E6 = class extends Error {\n connectionNames;\n reason;\n constructor(e51) {\n super(e51.message), this.name = \"PostProcessingConstraintError\", this.connectionNames = [...e51.connectionNames], this.reason = e51.reason;\n }\n};\nvar A6 = class extends Error {\n reason = \"grid-capacity-exhausted\";\n constructor(e51) {\n super(e51), this.name = \"PostProcessingGridCapacityError\";\n }\n};\nvar O6 = (e51) =\u003e {\n const t4 = 75000 * e51.simpleRouteJson.differentialPairs.length;\n if (!Number.isSafeInteger(t4))\n throw new Error(\"PostProcessingSolver: derived rerouting iteration bound exceeds the safe integer range\");\n const n7 = Math.min(t4, 80000);\n return Math.max(1, n7);\n};\nvar D6 = (e51) =\u003e structuredClone(e51);\nvar L6 = (e51, t4, n7) =\u003e {\n const o7 = (e53) =\u003e {\n const n8 = -(t4.ccwRotationDegrees ?? 0) * Math.PI / 180, o8 = e53.x - t4.center.x, i8 = e53.y - t4.center.y;\n return { x: o8 * Math.cos(n8) - i8 * Math.sin(n8), y: o8 * Math.sin(n8) + i8 * Math.cos(n8) };\n }, i7 = o7(e51.start), r7 = o7(e51.end), s7 = t4.width / 2 + n7, a7 = t4.height / 2 + n7;\n if (Math.abs(i7.x) \u003c= s7 \u0026\u0026 Math.abs(i7.y) \u003c= a7 || Math.abs(r7.x) \u003c= s7 \u0026\u0026 Math.abs(r7.y) \u003c= a7)\n return true;\n const c5 = [{ x: -s7, y: -a7 }, { x: s7, y: -a7 }, { x: s7, y: a7 }, { x: -s7, y: a7 }];\n return c5.some((e53, t7) =\u003e K4(i7, r7, e53, c5[(t7 + 1) % c5.length]) \u003c= 0.0000001);\n};\nvar z6 = (e51) =\u003e {\n const t4 = [], n7 = [];\n for (const o8 of e51.immutableTraces) {\n const i8 = q4(o8, e51.layerCount);\n t4.push(...i8.segments), n7.push(...i8.vias);\n }\n const o7 = Array.from({ length: e51.layerCount }, () =\u003e []);\n for (const n8 of t4) {\n const t7 = G4(n8.layer, e51.layerCount);\n o7[t7].push(n8);\n }\n const i7 = (e53, t7) =\u003e Math.hypot(e53.x - t7.x, e53.y - t7.y) \u003c= 0.00000001, r7 = (e53, t7, n8) =\u003e {\n const o8 = n8.x - t7.x, i8 = n8.y - t7.y, r8 = o8 * o8 + i8 * i8, s8 = r8 === 0 ? 0 : Math.max(0, Math.min(1, ((e53.x - t7.x) * o8 + (e53.y - t7.y) * i8) / r8));\n return Math.hypot(e53.x - t7.x - o8 * s8, e53.y - t7.y - i8 * s8);\n }, s7 = (e53, t7, n8) =\u003e {\n const o8 = -(t7.ccwRotationDegrees ?? 0) * Math.PI / 180, i8 = e53.x - t7.center.x, r8 = e53.y - t7.center.y, s8 = i8 * Math.cos(o8) - r8 * Math.sin(o8), a8 = i8 * Math.sin(o8) + r8 * Math.cos(o8);\n return Math.abs(s8) \u003c= t7.width / 2 + n8 \u0026\u0026 Math.abs(a8) \u003c= t7.height / 2 + n8;\n }, a7 = (t7, n8) =\u003e {\n const o8 = G4(n8, e51.layerCount);\n return o6(t7, e51.layerCount).includes(o8);\n }, c5 = (t7, n8, o8) =\u003e {\n const i8 = ((t8, n9, o9) =\u003e {\n const i9 = Math.hypot(n9.x, n9.y);\n if (i9 \u003c= 0.0000000001)\n throw new Error(\"PostProcessingSolver: cannot orient terminal fanout on a zero-length spine\");\n const r9 = -n9.y / i9 * e51.side * e51.centerlineSpacing / 2, s8 = n9.x / i9 * e51.side * e51.centerlineSpacing / 2, a8 = o9 === \"start\" ? [e51.firstStartTerminal, e51.secondStartTerminal] : [e51.firstEndTerminal, e51.secondEndTerminal], c7 = [e51.firstWidth, e51.secondWidth], l7 = [e51.firstConnectionName, e51.secondConnectionName];\n return a8.map((e53, n10) =\u003e {\n const i10 = n10 === 0 ? 1 : -1, a9 = { x: t8.x + r9 * i10, y: t8.y + s8 * i10 };\n return { start: o9 === \"start\" ? e53 : a9, end: o9 === \"start\" ? a9 : e53, layer: t8.layer, width: c7[n10], connectionName: l7[n10], terminal: o9 };\n });\n })(t7, n8, o8), r8 = i8.map((e53) =\u003e o8 === \"start\" ? e53.end : e53.start);\n return i8.every(l5) \u0026\u0026 r8.every((n9, o9) =\u003e e51.obstacles.every((r9) =\u003e !a7(r9, t7.layer) || !s7(n9, r9, 1.5 * i8[o9].width + (e51.terminalMiterMargin ?? 0)))) \u0026\u0026 K4(i8[0].start, i8[0].end, i8[1].start, i8[1].end) \u003e= i8[0].width / 2 + i8[1].width / 2 - 0.0000001;\n }, l5 = (t7) =\u003e {\n const i8 = t7.width / 2, c7 = i8 + (e51.minTraceToPadEdgeClearance ?? t7.width), l7 = G4(t7.layer, e51.layerCount), h7 = Math.min(t7.start.x, t7.end.x), d7 = Math.max(t7.start.x, t7.end.x), u7 = Math.min(t7.start.y, t7.end.y), p7 = Math.max(t7.start.y, t7.end.y);\n for (const n8 of [t7.start, t7.end])\n if (n8.x - i8 \u003c e51.bounds.minX || n8.x + i8 \u003e e51.bounds.maxX || n8.y - i8 \u003c e51.bounds.minY || n8.y + i8 \u003e e51.bounds.maxY)\n return false;\n for (const n8 of e51.obstacles) {\n if (!a7(n8, t7.layer))\n continue;\n const o8 = Math.hypot(n8.width / 2 + c7, n8.height / 2 + c7);\n if (d7 \u003c n8.center.x - o8 || h7 \u003e n8.center.x + o8 || p7 \u003c n8.center.y - o8 || u7 \u003e n8.center.y + o8)\n continue;\n const [i9, r8] = t7.connectionName === e51.firstConnectionName ? [e51.firstStartTerminal, e51.firstEndTerminal] : [e51.secondStartTerminal, e51.secondEndTerminal], l8 = s7(i9, n8, 0) \u0026\u0026 (s7(t7.start, n8, c7) || s7(t7.end, n8, c7)) \u0026\u0026 Math.hypot(t7.end.x - i9.x, t7.end.y - i9.y) \u003e= Math.hypot(t7.start.x - i9.x, t7.start.y - i9.y), m7 = s7(r8, n8, 0) \u0026\u0026 (s7(t7.start, n8, c7) || s7(t7.end, n8, c7)) \u0026\u0026 Math.hypot(t7.end.x - r8.x, t7.end.y - r8.y) \u003c= Math.hypot(t7.start.x - r8.x, t7.start.y - r8.y);\n if (!(n8.connectedTo.includes(t7.connectionName) \u0026\u0026 (l8 || m7)) \u0026\u0026 L6(t7, n8, c7))\n return false;\n }\n for (const e53 of o7[l7]) {\n const n8 = t7.width / 2 + e53.width / 2 + Math.max(t7.width, e53.width);\n if (!(d7 + n8 \u003c Math.min(e53.start.x, e53.end.x) || h7 - n8 \u003e Math.max(e53.start.x, e53.end.x) || p7 + n8 \u003c Math.min(e53.start.y, e53.end.y) || u7 - n8 \u003e Math.max(e53.start.y, e53.end.y)) \u0026\u0026 K4(t7.start, t7.end, e53.start, e53.end) \u003c n8)\n return false;\n }\n for (const e53 of n7)\n if (e53.layers.includes(t7.layer) \u0026\u0026 r7(e53, t7.start, t7.end) \u003c t7.width / 2 + e53.diameter / 2 + t7.width)\n return false;\n return true;\n }, h5 = (o8) =\u003e {\n const i8 = o8.diameter / 2;\n if (o8.x - i8 \u003c e51.bounds.minX || o8.x + i8 \u003e e51.bounds.maxX || o8.y - i8 \u003c e51.bounds.minY || o8.y + i8 \u003e e51.bounds.maxY)\n return false;\n for (const t7 of e51.obstacles) {\n if (!o8.layers.some((e53) =\u003e a7(t7, e53)))\n continue;\n if (!(o8.terminal !== null \u0026\u0026 t7.connectedTo.includes(o8.connectionName) \u0026\u0026 s7(o8, t7, 0)) \u0026\u0026 s7(o8, t7, i8 + o8.diameter))\n return false;\n }\n for (const e53 of t4) {\n if (!o8.layers.includes(e53.layer))\n continue;\n const t7 = i8 + e53.width / 2 + Math.max(o8.diameter, e53.width);\n if (r7(o8, e53.start, e53.end) \u003c t7)\n return false;\n }\n for (const e53 of n7) {\n if (!e53.layers.some((e54) =\u003e o8.layers.includes(e54)))\n continue;\n const t7 = i8 + e53.diameter / 2 + Math.max(o8.diameter, e53.diameter);\n if (Math.hypot(o8.x - e53.x, o8.y - e53.y) \u003c t7)\n return false;\n }\n return true;\n };\n return { isEdgeValid: (t7, n8) =\u003e {\n if (t7.layer !== n8.layer || !((t8, n9) =\u003e {\n const o9 = Math.hypot(n9.x - t8.x, n9.y - t8.y);\n if (o9 === 0)\n return [];\n const r8 = -(n9.y - t8.y) / o9 * e51.side * e51.centerlineSpacing / 2, s8 = (n9.x - t8.x) / o9 * e51.side * e51.centerlineSpacing / 2, a8 = i7(t8, e51.start), c7 = i7(n9, e51.end), l7 = e51.terminalFanout ? a8 \u0026\u0026 c7 ? \"both\" : a8 ? \"start\" : c7 ? \"end\" : null : null, h7 = a8 \u0026\u0026 e51.terminalFanout ? e51.firstStartTerminal : { x: t8.x + r8, y: t8.y + s8 }, d7 = c7 \u0026\u0026 e51.terminalFanout ? e51.firstEndTerminal : { x: n9.x + r8, y: n9.y + s8 }, u7 = a8 \u0026\u0026 e51.terminalFanout ? e51.secondStartTerminal : { x: t8.x - r8, y: t8.y - s8 }, p7 = c7 \u0026\u0026 e51.terminalFanout ? e51.secondEndTerminal : { x: n9.x - r8, y: n9.y - s8 };\n return [{ start: h7, end: d7, layer: t8.layer, width: e51.firstWidth, connectionName: e51.firstConnectionName, terminal: l7 }, { start: u7, end: p7, layer: t8.layer, width: e51.secondWidth, connectionName: e51.secondConnectionName, terminal: l7 }];\n })(t7, n8).every(l5))\n return false;\n if (e51.terminalFanout || e51.terminalMiterMargin === undefined)\n return true;\n const o8 = { x: n8.x - t7.x, y: n8.y - t7.y };\n return !(i7(t7, e51.start) \u0026\u0026 !c5(t7, o8, \"start\")) \u0026\u0026 !(i7(n8, e51.end) \u0026\u0026 !c5(n8, o8, \"end\"));\n }, isTerminalFanoutValid: c5, isViaValid: (t7, n8, o8) =\u003e {\n const r8 = Math.hypot(o8.x, o8.y);\n if (r8 \u003c= 0.0000000001)\n throw new Error(\"PostProcessingSolver: cannot orient a coupled via on a zero-length spine\");\n const s8 = Z4(t7.layer, n8, e51.layerCount), a8 = -o8.y / r8 * e51.side * e51.centerlineSpacing / 2, c7 = o8.x / r8 * e51.side * e51.centerlineSpacing / 2, l7 = i7(t7, e51.start) ? \"start\" : i7(t7, e51.end) ? \"end\" : null;\n return [{ x: t7.x + a8, y: t7.y + c7, layers: s8, diameter: e51.firstViaDiameter, connectionName: e51.firstConnectionName, terminal: l7 }, { x: t7.x - a8, y: t7.y - c7, layers: s8, diameter: e51.secondViaDiameter, connectionName: e51.secondConnectionName, terminal: l7 }].every(h5);\n } };\n};\nvar B6 = (e51, t4, n7) =\u003e {\n const o7 = 0.0000001, i7 = (e53, t7) =\u003e {\n const n8 = -(t7.ccwRotationDegrees ?? 0) * Math.PI / 180, o8 = e53.x - t7.center.x, i8 = e53.y - t7.center.y;\n return { x: o8 * Math.cos(n8) - i8 * Math.sin(n8), y: o8 * Math.sin(n8) + i8 * Math.cos(n8) };\n }, r7 = (e53, t7, n8) =\u003e {\n const o8 = n8.x - t7.x, i8 = n8.y - t7.y, r8 = o8 * o8 + i8 * i8, s8 = r8 === 0 ? 0 : Math.max(0, Math.min(1, ((e53.x - t7.x) * o8 + (e53.y - t7.y) * i8) / r8));\n return Math.hypot(e53.x - (t7.x + s8 * o8), e53.y - (t7.y + s8 * i8));\n }, s7 = (e53, t7, n8) =\u003e {\n const o8 = G4(t7, n8);\n return o6(e53, n8).includes(o8);\n }, a7 = (e53, t7, n8) =\u003e {\n const a8 = e53.width / 2;\n if (e53.start.x - a8 \u003c t7.bounds.minX - o7 || e53.start.x + a8 \u003e t7.bounds.maxX + o7 || e53.start.y - a8 \u003c t7.bounds.minY - o7 || e53.start.y + a8 \u003e t7.bounds.maxY + o7 || e53.end.x - a8 \u003c t7.bounds.minX - o7 || e53.end.x + a8 \u003e t7.bounds.maxX + o7 || e53.end.y - a8 \u003c t7.bounds.minY - o7 || e53.end.y + a8 \u003e t7.bounds.maxY + o7)\n return false;\n for (const n9 of t7.obstacles) {\n if (!s7(n9, e53.layer, t7.layerCount))\n continue;\n const r8 = e53.terminal === \"both\" ? [e53.start, e53.end] : e53.terminal === \"start\" ? [e53.start] : e53.terminal === \"end\" ? [e53.end] : [];\n if (!(n9.connectedTo.includes(e53.connectionName) \u0026\u0026 r8.some((e54) =\u003e {\n const t8 = i7(e54, n9);\n return Math.abs(t8.x) \u003c= n9.width / 2 + o7 \u0026\u0026 Math.abs(t8.y) \u003c= n9.height / 2 + o7;\n })) \u0026\u0026 L6(e53, n9, a8 + (t7.minTraceToPadEdgeClearance ?? e53.width)))\n return false;\n }\n for (const t8 of n8.segments) {\n if (t8.layer !== e53.layer)\n continue;\n const n9 = e53.width / 2 + t8.width / 2 + Math.max(e53.width, t8.width);\n if (K4(e53.start, e53.end, t8.start, t8.end) \u003c n9 - o7)\n return false;\n }\n for (const t8 of n8.vias) {\n if (!t8.layers.includes(e53.layer))\n continue;\n const n9 = e53.width / 2 + t8.diameter / 2 + e53.width;\n if (r7(t8, e53.start, e53.end) \u003c n9 - o7)\n return false;\n }\n return true;\n }, c5 = (e53, t7, n8) =\u003e {\n const a8 = e53.diameter / 2;\n if (e53.x - a8 \u003c t7.bounds.minX - o7 || e53.x + a8 \u003e t7.bounds.maxX + o7 || e53.y - a8 \u003c t7.bounds.minY - o7 || e53.y + a8 \u003e t7.bounds.maxY + o7)\n return false;\n for (const n9 of t7.obstacles) {\n if (!e53.layers.some((e54) =\u003e s7(n9, e54, t7.layerCount)))\n continue;\n const r8 = i7(e53, n9);\n if (!(e53.terminal !== null \u0026\u0026 n9.connectedTo.includes(e53.connectionName) \u0026\u0026 Math.abs(r8.x) \u003c= n9.width / 2 + o7 \u0026\u0026 Math.abs(r8.y) \u003c= n9.height / 2 + o7) \u0026\u0026 Math.abs(r8.x) \u003c= n9.width / 2 + a8 + e53.diameter \u0026\u0026 Math.abs(r8.y) \u003c= n9.height / 2 + a8 + e53.diameter)\n return false;\n }\n for (const t8 of n8.segments) {\n if (!e53.layers.includes(t8.layer))\n continue;\n const n9 = a8 + t8.width / 2 + Math.max(e53.diameter, t8.width);\n if (r7(e53, t8.start, t8.end) \u003c n9 - o7)\n return false;\n }\n for (const t8 of n8.vias) {\n if (!t8.layers.some((t9) =\u003e e53.layers.includes(t9)))\n continue;\n const n9 = a8 + t8.diameter / 2 + Math.max(e53.diameter, t8.diameter);\n if (Math.hypot(e53.x - t8.x, e53.y - t8.y) \u003c n9 - o7)\n return false;\n }\n return true;\n }, l5 = (e53) =\u003e {\n for (let t7 = 0;t7 \u003c e53.segments.length; t7++) {\n const n8 = e53.segments[t7];\n for (let i8 = t7 + 2;i8 \u003c e53.segments.length; i8++) {\n const r8 = e53.segments[i8];\n if (n8.layer !== r8.layer)\n continue;\n if (!(e53.segments.slice(t7 + 1, i8).reduce((e54, t8) =\u003e e54 + Math.hypot(t8.end.x - t8.start.x, t8.end.y - t8.start.y), 0) \u003c= n8.width + r8.width + o7) \u0026\u0026 K4(n8.start, n8.end, r8.start, r8.end) \u003c n8.width / 2 + r8.width / 2 - o7)\n return true;\n }\n }\n for (const t7 of e53.vias)\n for (const n8 of e53.segments) {\n if (!t7.layers.includes(n8.layer))\n continue;\n if (!(Math.hypot(t7.x - n8.start.x, t7.y - n8.start.y) \u003c= o7 || Math.hypot(t7.x - n8.end.x, t7.y - n8.end.y) \u003c= o7) \u0026\u0026 r7(t7, n8.start, n8.end) \u003c t7.diameter / 2 + n8.width / 2 - o7)\n return true;\n }\n return false;\n }, h5 = ((e53, t7) =\u003e {\n const n8 = [], o8 = [];\n for (const i8 of e53) {\n const e54 = q4(i8, t7);\n n8.push(...e54.segments), o8.push(...e54.vias);\n }\n return { segments: n8, vias: o8 };\n })(n7.immutableTraces, n7.layerCount);\n if (!((e53, t7) =\u003e {\n for (const n8 of e53.segments)\n for (const e54 of t7.segments) {\n if (n8.layer !== e54.layer)\n continue;\n const t8 = n8.width / 2 + e54.width / 2;\n if (K4(n8.start, n8.end, e54.start, e54.end) \u003c t8 - o7)\n return false;\n }\n for (const [n8, i8] of [[e53.vias, t7.segments], [t7.vias, e53.segments]])\n for (const e54 of n8)\n for (const t8 of i8)\n if (e54.layers.includes(t8.layer) \u0026\u0026 r7(e54, t8.start, t8.end) \u003c e54.diameter / 2 + t8.width / 2 - o7)\n return false;\n for (const n8 of e53.vias)\n for (const e54 of t7.vias)\n if (n8.layers.some((t8) =\u003e e54.layers.includes(t8)) \u0026\u0026 Math.hypot(n8.x - e54.x, n8.y - e54.y) \u003c n8.diameter / 2 + e54.diameter / 2 - o7)\n return false;\n return true;\n })(e51, t4) || l5(e51) || l5(t4))\n return false;\n for (const o8 of [e51, t4])\n if (o8.segments.some((e53) =\u003e !a7(e53, n7, h5)) || o8.vias.some((e53) =\u003e !c5(e53, n7, h5)))\n return false;\n return true;\n};\nvar F6 = [{ x: 1, y: 0 }, { x: 1, y: 1 }, { x: 0, y: 1 }, { x: -1, y: 1 }, { x: -1, y: 0 }, { x: -1, y: -1 }, { x: 0, y: -1 }, { x: 1, y: -1 }];\nvar j6 = class {\n constructor(e51) {\n this.input = e51;\n const { bounds: t4, grid: n7 } = e51, o7 = { minX: t4.minX + n7.outerPerimeterWidth, maxX: t4.maxX - n7.outerPerimeterWidth, minY: t4.minY + n7.outerPerimeterWidth, maxY: t4.maxY - n7.outerPerimeterWidth }, i7 = this.createAxis(t4.minX, t4.maxX, n7.outerGridStep, [o7.minX, o7.maxX]), r7 = this.createAxis(t4.minY, t4.maxY, n7.outerGridStep, [o7.minY, o7.maxY]), s7 = this.createAxis(o7.minX, o7.maxX, n7.innerGridStep, [], e51.start.x), a7 = this.createAxis(o7.minY, o7.maxY, n7.innerGridStep, [], e51.start.y), c5 = this.createGrid(i7, r7, (e53) =\u003e e53.x \u003c= o7.minX || e53.x \u003e= o7.maxX || e53.y \u003c= o7.minY || e53.y \u003e= o7.maxY), l5 = this.createGrid(s7, a7, () =\u003e true);\n this.connectLocalNeighbors(c5), this.connectLocalNeighbors(l5);\n for (const e53 of [\"left\", \"right\", \"bottom\", \"top\"])\n this.connectBoundaries(e53, c5, l5, o7);\n const h5 = this.nodes.map((e53, t7) =\u003e t7);\n this.connectEndpoint(e51.start, h5), this.connectEndpoint(e51.end, h5);\n }\n nodes = [];\n nodeIdByPoint = new Map;\n endpointNodeIdByPoint = new Map;\n getPlanarNeighbors(e51) {\n const t4 = this.endpointNodeIdByPoint.get(this.exactKeyFor(e51)) ?? this.nodeIdByPoint.get(this.keyFor(e51));\n if (t4 === undefined)\n throw new Error(`PostProcessingSolver: coupled path point (${e51.x}, ${e51.y}) is not on the composite grid`);\n return [...this.nodes[t4].neighborIds].map((t7) =\u003e ({ ...this.nodes[t7].point, layer: e51.layer }));\n }\n getNodeCount() {\n return this.nodes.length;\n }\n getSearchStateCountUpperBound(e51) {\n const t4 = this.nodes.reduce((e53, t7) =\u003e e53 + t7.neighborIds.size, 0) * e51 + 1;\n if (!Number.isSafeInteger(t4))\n throw new Error(\"PostProcessingSolver: composite-grid search-state bound exceeds the safe integer range\");\n return t4;\n }\n createAxis(e51, t4, n7, o7, i7 = e51) {\n const r7 = [e51, t4, ...o7].map((e53) =\u003e ({ value: e53, fixed: true }));\n for (let o8 = Math.ceil((e51 - i7) / n7);i7 + o8 * n7 \u003c t4 - 0.00000001; o8++)\n r7.push({ value: i7 + o8 * n7, fixed: false });\n r7.sort((e53, t7) =\u003e e53.value - t7.value || Number(t7.fixed) - Number(e53.fixed));\n const s7 = [];\n for (const e53 of r7) {\n const t7 = s7.at(-1);\n !t7 || Math.abs(e53.value - t7.value) \u003e 0.00000001 ? s7.push(e53) : e53.fixed \u0026\u0026 !t7.fixed \u0026\u0026 (s7[s7.length - 1] = e53);\n }\n return s7.map((e53) =\u003e e53.value);\n }\n createGrid(e51, t4, n7) {\n return t4.map((t7) =\u003e e51.map((e53) =\u003e {\n const o7 = { x: e53, y: t7 };\n return n7(o7) ? this.addNode(o7) : null;\n }));\n }\n connectLocalNeighbors(e51) {\n for (let t4 = 0;t4 \u003c e51.length; t4++)\n for (let n7 = 0;n7 \u003c (e51[t4]?.length ?? 0); n7++) {\n const o7 = e51[t4][n7];\n if (o7 !== null)\n for (const i7 of F6) {\n const r7 = e51[t4 + i7.y]?.[n7 + i7.x];\n r7 != null \u0026\u0026 this.connect(o7, r7);\n }\n }\n }\n connectBoundaries(e51, t4, n7, o7) {\n const i7 = e51 === \"left\" ? o7.minX : e51 === \"right\" ? o7.maxX : e51 === \"bottom\" ? o7.minY : o7.maxY, r7 = e51 === \"left\" || e51 === \"right\", s7 = (e53) =\u003e Math.abs((r7 ? e53.x : e53.y) - i7) \u003c= 0.00000001, a7 = (e53) =\u003e {\n const t7 = new Set;\n for (const n8 of e53)\n for (const e54 of n8)\n e54 !== null \u0026\u0026 s7(this.nodes[e54].point) \u0026\u0026 t7.add(e54);\n return [...t7].sort((e54, t8) =\u003e {\n const n8 = this.nodes[e54].point, o8 = this.nodes[t8].point;\n return (r7 ? n8.y - o8.y : n8.x - o8.x) || e54 - t8;\n });\n }, c5 = a7(t4), l5 = a7(n7);\n if (c5.length === 0 || l5.length === 0)\n throw new Error(`PostProcessingSolver: composite grid has no ${e51} boundary bridge candidates`);\n for (const e53 of c5)\n this.connect(e53, this.findNearestAlongBoundary(e53, l5, r7));\n for (const e53 of l5)\n this.connect(e53, this.findNearestAlongBoundary(e53, c5, r7));\n }\n findNearestAlongBoundary(e51, t4, n7) {\n const o7 = this.nodes[e51].point;\n let i7 = t4[0], r7 = Number.POSITIVE_INFINITY;\n for (const e53 of t4) {\n const t7 = this.nodes[e53].point, s7 = Math.abs(n7 ? o7.y - t7.y : o7.x - t7.x);\n (s7 \u003c r7 - 0.00000001 || Math.abs(s7 - r7) \u003c= 0.00000001 \u0026\u0026 e53 \u003c i7) \u0026\u0026 (r7 = s7, i7 = e53);\n }\n return i7;\n }\n connectEndpoint(e51, t4) {\n const n7 = this.nodeIdByPoint.get(this.keyFor(e51)), o7 = n7 === undefined ? null : this.nodes[n7].point, i7 = o7?.x === e51.x \u0026\u0026 o7.y === e51.y ? n7 : this.nodes.push({ point: { x: e51.x, y: e51.y }, neighborIds: new Set }) - 1;\n this.endpointNodeIdByPoint.set(this.exactKeyFor(e51), i7);\n const r7 = (e53, n8) =\u003e {\n const o8 = this.nodes[e53].point, i8 = t4.filter((t7) =\u003e t7 !== e53).map((e54) =\u003e ({ nodeId: e54, distance: Math.hypot(this.nodes[e54].point.x - o8.x, this.nodes[e54].point.y - o8.y) })).filter(({ distance: e54 }) =\u003e e54 \u003e 0.0000000001).sort((e54, t7) =\u003e e54.distance - t7.distance || e54.nodeId - t7.nodeId).slice(0, n8);\n if (i8.length === 0)\n throw new Error(\"PostProcessingSolver: composite grid has no endpoint connection candidates\");\n for (const { nodeId: t7 } of i8)\n this.connect(e53, t7);\n };\n r7(i7, 8);\n for (const t7 of F6) {\n const n8 = { x: e51.x + t7.x * this.input.grid.innerGridStep, y: e51.y + t7.y * this.input.grid.innerGridStep };\n if (n8.x \u003c this.input.bounds.minX || n8.x \u003e this.input.bounds.maxX || n8.y \u003c this.input.bounds.minY || n8.y \u003e this.input.bounds.maxY)\n continue;\n const o8 = this.addNode(n8);\n this.connect(i7, o8), r7(o8, 4);\n }\n }\n addNode(e51) {\n const t4 = this.keyFor(e51), n7 = this.nodeIdByPoint.get(t4);\n if (n7 !== undefined)\n return n7;\n const o7 = this.nodes.length;\n return this.nodes.push({ point: { x: e51.x, y: e51.y }, neighborIds: new Set }), this.nodeIdByPoint.set(t4, o7), o7;\n }\n connect(e51, t4) {\n if (e51 === t4)\n return;\n const n7 = this.nodes[e51], o7 = this.nodes[t4];\n n7.neighborIds.add(t4), o7.neighborIds.add(e51);\n }\n keyFor(e51) {\n const t4 = Object.is(e51.x, -0) ? 0 : e51.x, n7 = Object.is(e51.y, -0) ? 0 : e51.y;\n return `${t4.toFixed(12)}:${n7.toFixed(12)}`;\n }\n exactKeyFor(e51) {\n return `${Object.is(e51.x, -0) ? 0 : e51.x}:${Object.is(e51.y, -0) ? 0 : e51.y}`;\n }\n};\nvar $6 = class {\n constructor(e51) {\n if (this.input = e51, this.startLayer = G4(e51.start.layer, e51.layerCount), this.endLayer = G4(e51.end.layer, e51.layerCount), this.grid = new j6(e51), this.maxSearchStates = this.grid.getSearchStateCountUpperBound(e51.layerCount), this.exploredStateLimit = Math.min(this.maxSearchStates, 20000), this.startLayer \u003c 0 || this.endLayer \u003c 0)\n return this.queue = [], void (this.status = \"exhausted\");\n const t4 = { point: e51.start, direction: null, cost: 0, estimate: this.estimate(e51.start), parent: null, sequence: 0 };\n this.queue = [t4], this.bestCosts.set(this.keyFor(e51.start, null), 0);\n }\n queue;\n bestCosts = new Map;\n startLayer;\n endLayer;\n grid;\n maxSearchStates;\n exploredStateLimit;\n current = null;\n result = null;\n status = \"searching\";\n explored = 0;\n nextSequence = 1;\n isComplete() {\n return this.status !== \"searching\";\n }\n getPath() {\n return this.result;\n }\n getPreviewPath() {\n return this.current ? this.createPath(this.current) : [this.input.start];\n }\n getExploredCount() {\n return this.explored;\n }\n getProgress() {\n return this.status !== \"searching\" ? 1 : Math.min(0.99, this.explored / this.exploredStateLimit);\n }\n getGridNodeCount() {\n return this.grid.getNodeCount();\n }\n step() {\n if (this.status !== \"searching\")\n return;\n const e51 = this.popQueue();\n if (!e51)\n return void (this.status = \"exhausted\");\n const t4 = this.bestCosts.get(this.keyFor(e51.point, e51.direction));\n if (t4 === undefined)\n throw new Error(\"PostProcessingSolver: coupled path queue contains an untracked state\");\n if (e51.cost \u003e t4 + 0.0000000001)\n this.queue.length === 0 \u0026\u0026 (this.status = \"exhausted\");\n else {\n if (this.current = e51, this.explored++, this.explored \u003e this.maxSearchStates)\n throw new Error(`PostProcessingSolver: coupled path search exceeded its ${this.maxSearchStates}-state graph invariant limit`);\n if (this.isEnd(e51.point)) {\n const t7 = this.createPath(e51);\n return t7[t7.length - 1] = this.input.end, this.result = this.simplifyPath(t7), void (this.status = \"found\");\n }\n this.explored \u003e= this.exploredStateLimit ? this.status = \"exhausted\" : (this.enqueuePlanarNeighbors(e51), this.enqueueViaNeighbors(e51), this.queue.length === 0 \u0026\u0026 (this.status = \"exhausted\"));\n }\n }\n isEnd(e51) {\n return e51.layer === this.input.end.layer \u0026\u0026 e51.x === this.input.end.x \u0026\u0026 e51.y === this.input.end.y;\n }\n estimate(e51) {\n return Math.hypot(e51.x - this.input.end.x, e51.y - this.input.end.y) + 3 * Math.abs(G4(e51.layer, this.input.layerCount) - this.endLayer);\n }\n keyFor(e51, t4) {\n return `${Object.is(e51.x, -0) ? 0 : e51.x}:${Object.is(e51.y, -0) ? 0 : e51.y}:${e51.layer}:${t4?.key ?? \"start\"}`;\n }\n createDirection(e51, t4) {\n const n7 = t4.x - e51.x, o7 = t4.y - e51.y, i7 = Math.hypot(n7, o7);\n if (i7 \u003c= 0.0000000001)\n throw new Error(\"PostProcessingSolver: composite grid produced a zero-length planar edge\");\n const r7 = n7 / i7, s7 = o7 / i7;\n return { x: r7, y: s7, key: `${r7.toFixed(6)}:${s7.toFixed(6)}` };\n }\n createPath(e51) {\n const t4 = [];\n let n7 = e51;\n for (;n7; )\n t4.push(n7.point), n7 = n7.parent;\n return t4.reverse();\n }\n simplifyPath(e51) {\n return e51.filter((t4, n7) =\u003e {\n if (n7 === 0 || n7 === e51.length - 1)\n return true;\n const o7 = e51[n7 - 1], i7 = e51[n7 + 1], r7 = { x: t4.x - o7.x, y: t4.y - o7.y }, s7 = { x: i7.x - t4.x, y: i7.y - t4.y }, a7 = r7.x * s7.y - r7.y * s7.x, c5 = Math.hypot(r7.x, r7.y) * Math.hypot(s7.x, s7.y);\n return Math.abs(a7) \u003e 0.0000000001 * c5 || t4.layer !== o7.layer || t4.layer !== i7.layer;\n });\n }\n hasHigherQueuePriority(e51, t4) {\n return e51.estimate !== t4.estimate ? e51.estimate \u003c t4.estimate : e51.cost !== t4.cost ? e51.cost \u003c t4.cost : e51.point.x !== t4.point.x ? e51.point.x \u003c t4.point.x : e51.point.y !== t4.point.y ? e51.point.y \u003c t4.point.y : e51.point.layer !== t4.point.layer ? e51.point.layer \u003c t4.point.layer : e51.sequence \u003c t4.sequence;\n }\n pushQueue(e51) {\n this.queue.push(e51);\n let t4 = this.queue.length - 1;\n for (;t4 \u003e 0; ) {\n const n7 = Math.floor((t4 - 1) / 2), o7 = this.queue[n7];\n if (!this.hasHigherQueuePriority(e51, o7))\n break;\n this.queue[t4] = o7, t4 = n7;\n }\n this.queue[t4] = e51;\n }\n popQueue() {\n const e51 = this.queue[0], t4 = this.queue.pop();\n if (!e51 || !t4 || this.queue.length === 0)\n return e51;\n let n7 = 0;\n for (;; ) {\n const e53 = 2 * n7 + 1;\n if (e53 \u003e= this.queue.length)\n break;\n const o7 = e53 + 1;\n let i7 = e53;\n o7 \u003c this.queue.length \u0026\u0026 this.hasHigherQueuePriority(this.queue[o7], this.queue[e53]) \u0026\u0026 (i7 = o7);\n const r7 = this.queue[i7];\n if (!this.hasHigherQueuePriority(r7, t4))\n break;\n this.queue[n7] = r7, n7 = i7;\n }\n return this.queue[n7] = t4, e51;\n }\n enqueuePlanarNeighbors(e51) {\n for (const t4 of this.grid.getPlanarNeighbors(e51.point)) {\n if (!this.input.isEdgeValid(e51.point, t4))\n continue;\n const n7 = this.createDirection(e51.point, t4), o7 = e51.direction === null || e51.direction.key === n7.key ? 0 : 0.18, i7 = e51.cost + Math.hypot(t4.x - e51.point.x, t4.y - e51.point.y) + o7, r7 = this.keyFor(t4, n7);\n (this.bestCosts.get(r7) ?? Number.POSITIVE_INFINITY) \u003c= i7 || (this.bestCosts.set(r7, i7), this.pushQueue({ point: t4, direction: n7, cost: i7, estimate: i7 + this.estimate(t4), parent: e51, sequence: this.nextSequence++ }));\n }\n }\n enqueueViaNeighbors(e51) {\n if (!e51.direction)\n return;\n const t4 = G4(e51.point.layer, this.input.layerCount);\n for (const n7 of [t4 - 1, t4 + 1]) {\n if (n7 \u003c 0 || n7 \u003e= this.input.layerCount)\n continue;\n const t7 = U4(n7, this.input.layerCount);\n if (!this.input.isViaValid(e51.point, t7, e51.direction))\n continue;\n const o7 = { ...e51.point, layer: t7 }, i7 = e51.cost + 4, r7 = this.keyFor(o7, e51.direction);\n (this.bestCosts.get(r7) ?? Number.POSITIVE_INFINITY) \u003c= i7 || (this.bestCosts.set(r7, i7), this.pushQueue({ point: o7, direction: e51.direction, cost: i7, estimate: i7 + this.estimate(o7), parent: e51, sequence: this.nextSequence++ }));\n }\n }\n};\nvar Y6 = (e51) =\u003e {\n const t4 = Math.min(e51.bounds.maxX - e51.bounds.minX, e51.bounds.maxY - e51.bounds.minY), n7 = e51.config?.innerGridStep ?? e51.defaultInnerGridStep, o7 = e51.config?.outerGridStep ?? 4 * n7, i7 = e51.config?.outerPerimeterWidth ?? Math.min(o7, t4 / 4);\n if (!Number.isFinite(n7) || n7 \u003c 0.0001)\n throw new Error(\"PostProcessingSolver: routingGrid.innerGridStep must be finite and at least 0.0001\");\n if (!Number.isFinite(o7) || o7 \u003c= n7)\n throw new Error(\"PostProcessingSolver: routingGrid.outerGridStep must be finite and greater than innerGridStep\");\n if (!Number.isFinite(i7) || i7 \u003c= 0 || 2 * i7 \u003e= t4)\n throw new Error(\"PostProcessingSolver: routingGrid.outerPerimeterWidth must be finite, positive, and less than half the smaller board extent\");\n const r7 = e51.bounds.maxX - e51.bounds.minX, s7 = e51.bounds.maxY - e51.bounds.minY;\n if ((Math.ceil(r7 / o7) + 4) * (Math.ceil(s7 / o7) + 4) + (Math.ceil((r7 - 2 * i7) / n7) + 2) * (Math.ceil((s7 - 2 * i7) / n7) + 2) + 18 \u003e 250000)\n throw new A6(\"PostProcessingSolver: valid input exceeds the 250000-node optimization grid capacity\");\n return { innerGridStep: n7, outerGridStep: o7, outerPerimeterWidth: i7 };\n};\nvar X6 = (e51) =\u003e {\n const t4 = -e51.pathDirection.y, n7 = e51.pathDirection.x, o7 = Math.tan(e51.maximumTurnDegrees * Math.PI / 180), i7 = Math.max(0, ...e51.lanes.map(({ point: i8, polarity: r8 }) =\u003e {\n const s8 = i8.x - e51.anchor.x, a8 = i8.y - e51.anchor.y, c5 = s8 * e51.escapeDirection.x + a8 * e51.escapeDirection.y, l5 = s8 * t4 + a8 * n7, h5 = r8 * e51.side * e51.centerlineSpacing / 2;\n return c5 + Math.abs(l5 - h5) / o7;\n })), r7 = e51.maxUncoupledLength ?? i7;\n if (i7 \u003e r7 + 0.00000001)\n return null;\n const s7 = Math.max(0.05, Math.min(0.25, e51.searchStep / 2)), a7 = Math.max(1, Math.ceil((r7 - i7) / s7) + 1);\n for (let o8 = 0;o8 \u003c a7; o8++) {\n const a8 = Math.min(r7, i7 + o8 * s7), c5 = { x: e51.anchor.x + e51.escapeDirection.x * a8, y: e51.anchor.y + e51.escapeDirection.y * a8, layer: e51.anchor.layer };\n if (e51.lanes.every(({ point: o9, polarity: i8 }) =\u003e {\n const r8 = i8 * e51.side * e51.centerlineSpacing / 2, s8 = c5.x + t4 * r8, a9 = c5.y + n7 * r8;\n return e51.maxUncoupledLength === undefined || Math.hypot(s8 - o9.x, a9 - o9.y) \u003c= e51.maxUncoupledLength + 0.00000001;\n }) \u0026\u0026 e51.isValid(c5))\n return c5;\n }\n return null;\n};\nvar H6 = [0.75, 0.5, 1, 0.25, 1.25];\nvar V6 = 100;\nvar W6 = class {\n constructor(e51) {\n this.input = e51, this.pairName = e51.pair.connectionNames.join(\"/\"), this.prepared = this.prepare();\n }\n pairName;\n prepared;\n candidates = [];\n result = null;\n search = null;\n nextAttempt = 0;\n exploredNodeCount = 0;\n isComplete() {\n return this.result !== null;\n }\n getResult() {\n if (!this.result)\n throw new Error(`PostProcessingSolver: differential pair ${this.pairName} is not complete`);\n return this.result;\n }\n getPreviewPath() {\n return this.search?.getPreviewPath() ?? null;\n }\n getProgress() {\n if (this.result)\n return 1;\n const e51 = this.prepared.attempts.length, t4 = this.search?.getProgress() ?? 0;\n return Math.min(0.99, (this.nextAttempt + t4) / e51);\n }\n getStats() {\n return { phase: this.search ? \"searching\" : \"candidate-selection\", pair: this.pairName, attemptIndex: this.nextAttempt, attemptCount: this.prepared.attempts.length, exploredNodeCount: this.exploredNodeCount + (this.search?.getExploredCount() ?? 0), gridNodeCount: this.search?.getGridNodeCount() ?? 0, acceptedCandidateCount: this.candidates.length };\n }\n step() {\n if (this.result)\n return;\n const e51 = this.prepared;\n if (!this.search) {\n const t7 = e51.attempts[this.nextAttempt];\n return t7 ? void (this.search = new $6(t7.input)) : void this.complete();\n }\n if (this.search.step(), !this.search.isComplete())\n return;\n const t4 = this.search.getPath();\n this.exploredNodeCount += this.search.getExploredCount();\n const n7 = e51.attempts[this.nextAttempt];\n if (!n7)\n throw new Error(`PostProcessingSolver: differential pair ${this.pairName} lost its active attempt`);\n if (this.search = null, this.nextAttempt++, !t4)\n return;\n const o7 = ((e53) =\u003e {\n const t7 = (e54, t8) =\u003e Math.hypot(e54.x - t8.x, e54.y - t8.y) \u003c= 0.00000001;\n if (e53.path.length \u003c 2)\n throw new Error(\"PostProcessingSolver: coupled path has fewer than two stations\");\n const n8 = (n9, o9) =\u003e {\n for (let i8 = n9 + o9;i8 \u003e= 0 \u0026\u0026 i8 \u003c e53.path.length; i8 += o9) {\n const o10 = e53.path[i8];\n if (!t7(o10, e53.path[n9]))\n return o10;\n }\n return null;\n }, o8 = (t8) =\u003e {\n const o9 = e53.path[t8], i8 = n8(t8, -1), r8 = n8(t8, 1), s8 = (e54, t9) =\u003e {\n const n9 = t9.x - e54.x, o10 = t9.y - e54.y, i9 = Math.hypot(n9, o10);\n if (i9 \u003c= 0.0000000001)\n throw new Error(\"PostProcessingSolver: cannot offset a zero-length spine\");\n return { x: -o10 / i9, y: n9 / i9 };\n }, a8 = e53.side * e53.centerlineSpacing / 2;\n if (!i8 || !r8) {\n const e54 = s8(i8 ?? o9, r8 ?? o9);\n return { x: e54.x * a8, y: e54.y * a8 };\n }\n if (e53.terminalFanout \u0026\u0026 t8 === 1)\n return s8(i8, o9);\n if (e53.terminalFanout \u0026\u0026 t8 === e53.path.length - 2)\n return s8(o9, r8);\n if (e53.terminalFanout \u0026\u0026 e53.path[t8 + 1]?.layer !== o9.layer)\n return s8(i8, o9);\n const c7 = s8(i8, o9), l7 = s8(o9, r8), h7 = { x: c7.x + l7.x, y: c7.y + l7.y }, d8 = Math.hypot(h7.x, h7.y);\n if (d8 \u003c= 0.0000000001)\n return null;\n const u8 = h7.x / d8, p8 = h7.y / d8, m8 = a8 / (u8 * c7.x + p8 * c7.y);\n return { x: u8 * m8, y: p8 * m8 };\n }, i7 = e53.first.points[0], r7 = e53.first.points.at(-1), s7 = e53.reverseSecond ? e53.second.points.at(-1) : e53.second.points[0], a7 = e53.reverseSecond ? e53.second.points[0] : e53.second.points.at(-1), c5 = [[{ route_type: \"wire\", x: i7.x, y: i7.y, width: i7.width, layer: i7.layer }], [{ route_type: \"wire\", x: s7.x, y: s7.y, width: s7.width, layer: s7.layer }]], l5 = [e53.first.transitions[0], e53.second.transitions[0]];\n let h5 = 0;\n const d7 = e53.terminalFanout ? 1 : 0, u7 = e53.path.length - 2, p7 = e53.path[u7], m7 = e53.path[u7 - 1], g7 = e53.terminalFanout \u0026\u0026 p7?.layer === r7.layer \u0026\u0026 m7?.layer === p7.layer, f7 = e53.terminalFanout ? g7 ? u7 - 1 : e53.path.length - 1 : e53.path.length;\n for (let n9 = d7;n9 \u003c f7; n9++) {\n const i8 = e53.path[n9], r8 = o8(n9);\n if (!r8)\n return null;\n for (const o9 of [0, 1]) {\n const s8 = o9 === 0 ? 1 : -1, a8 = { x: i8.x + r8.x * s8, y: i8.y + r8.y * s8 }, h7 = c5[o9], d8 = e53.path[n9 - 1];\n if (d8 \u0026\u0026 d8.layer !== i8.layer) {\n if (!t7(d8, i8))\n throw new Error(\"PostProcessingSolver: a coupled layer transition moved in the plane\");\n const n10 = [...h7].reverse().find((e54) =\u003e e54.route_type === \"wire\");\n if (!n10)\n throw new Error(\"PostProcessingSolver: generated via has no preceding wire\");\n const r9 = l5[o9];\n h7.push({ route_type: \"via\", x: n10.x, y: n10.y, from_layer: d8.layer, to_layer: i8.layer, via_diameter: r9?.via_diameter ?? (o9 === 0 ? e53.first.viaDiameter : e53.second.viaDiameter), ...r9?.via_hole_diameter !== undefined ? { via_hole_diameter: r9.via_hole_diameter } : {} }), h7.push({ route_type: \"wire\", x: n10.x, y: n10.y, width: o9 === 0 ? e53.first.width : e53.second.width, layer: i8.layer });\n } else {\n const n10 = h7.at(-1);\n n10?.route_type === \"wire\" \u0026\u0026 t7(n10, a8) \u0026\u0026 n10.layer === i8.layer || h7.push({ route_type: \"wire\", ...a8, width: o9 === 0 ? e53.first.width : e53.second.width, layer: i8.layer });\n }\n }\n e53.path[n9 - 1]?.layer !== i8.layer \u0026\u0026 n9 \u003e 0 \u0026\u0026 h5++;\n }\n const _5 = (t8, n9) =\u003e {\n const o9 = t8.at(-1);\n if (!o9 || o9.route_type !== \"wire\")\n throw new Error(\"PostProcessingSolver: terminal fanout has no preceding wire\");\n const i8 = t8.at(-2);\n let r8 = false;\n if (i8?.route_type === \"wire\" \u0026\u0026 i8.layer === o9.layer \u0026\u0026 o9.layer === n9.layer) {\n const e54 = { x: o9.x - i8.x, y: o9.y - i8.y }, t9 = { x: n9.x - o9.x, y: n9.y - o9.y }, s8 = Math.hypot(e54.x, e54.y), a8 = Math.hypot(t9.x, t9.y);\n if (s8 \u003e 0.00000001 \u0026\u0026 a8 \u003e 0.00000001 \u0026\u0026 Math.abs(e54.x * t9.x + e54.y * t9.y) \u003c= 0.00000001) {\n const t10 = { x: o9.x - e54.x / s8 * a8, y: o9.y - e54.y / s8 * a8 };\n (t10.x - i8.x) * (e54.x / s8) + (t10.y - i8.y) * (e54.y / s8) \u003e 0.00000001 \u0026\u0026 (o9.x = t10.x, o9.y = t10.y, r8 = true);\n }\n }\n e53.terminalFanout \u0026\u0026 !r8 \u0026\u0026 o9.x !== n9.x \u0026\u0026 o9.y !== n9.y \u0026\u0026 t8.push({ route_type: \"wire\", x: n9.x, y: o9.y, width: n9.width, layer: n9.layer }), t8.push({ route_type: \"wire\", x: n9.x, y: n9.y, width: n9.width, layer: n9.layer });\n };\n _5(c5[0], r7), _5(c5[1], a7), e53.reverseSecond \u0026\u0026 (c5[1] = c5[1].reverse().map((e54) =\u003e e54.route_type === \"via\" ? { ...e54, from_layer: e54.to_layer, to_layer: e54.from_layer } : e54));\n const y7 = (e54, t8) =\u003e {\n const n9 = e54.filter((e55) =\u003e e55.route_type === \"wire\");\n for (const e55 of n9)\n delete e55.start_pcb_port_id, delete e55.end_pcb_port_id;\n t8.startPortId \u0026\u0026 (n9[0].start_pcb_port_id = t8.startPortId), t8.endPortId \u0026\u0026 (n9.at(-1).end_pcb_port_id = t8.endPortId);\n };\n y7(c5[0], e53.first), y7(c5[1], e53.second);\n const b7 = { ...e53.first.source, route: c5[0] }, x7 = { ...e53.second.source, route: c5[1] };\n return { first: b7, second: x7, firstParsed: P6(b7, e53.layerCount), secondParsed: P6(x7, e53.layerCount), edgeGap: e53.edgeGap, centerlineDistance: e53.centerlineSpacing, bendCount: Math.max(0, e53.path.length - h5 - 2), viaPairCount: h5 };\n })({ first: e51.first, second: e51.second, reverseSecond: e51.reverseSecond, path: t4, centerlineSpacing: n7.edgeGap + e51.first.width / 2 + e51.second.width / 2, edgeGap: n7.edgeGap, side: n7.side, layerCount: this.input.layerCount, terminalFanout: e51.terminalFanout });\n o7 \u0026\u0026 B6(o7.firstParsed, o7.secondParsed, e51.context) \u0026\u0026 this.candidates.push(o7);\n }\n prepare() {\n const e51 = this.input.traces.map((e53, t7) =\u003e ({ trace: e53, index: t7 })).filter(({ trace: e53 }) =\u003e e53.connection_name === this.input.pair.connectionNames[0]), t4 = this.input.traces.map((e53, t7) =\u003e ({ trace: e53, index: t7 })).filter(({ trace: e53 }) =\u003e e53.connection_name === this.input.pair.connectionNames[1]);\n if (e51.length !== 1 || t4.length !== 1)\n throw new T6({ connectionNames: this.input.pair.connectionNames, reason: \"trace-resolution-failure\", message: \"must resolve each connection_name to exactly one non-branching trace\" });\n if (e51[0].index === t4[0].index)\n throw new T6({ connectionNames: this.input.pair.connectionNames, reason: \"trace-resolution-failure\", message: \"resolved both members to one trace\" });\n let n7, o7;\n try {\n n7 = P6(e51[0].trace, this.input.layerCount), o7 = P6(t4[0].trace, this.input.layerCount);\n } catch (e53) {\n throw new T6({ connectionNames: this.input.pair.connectionNames, reason: \"invalid-routed-geometry\", message: `has unsupported or invalid routed geometry: ${e53 instanceof Error ? e53.message : String(e53)}` });\n }\n const i7 = n7.points[0], r7 = n7.points.at(-1), s7 = Math.hypot(i7.x - o7.points[0].x, i7.y - o7.points[0].y) + Math.hypot(r7.x - o7.points.at(-1).x, r7.y - o7.points.at(-1).y), a7 = Math.hypot(i7.x - o7.points.at(-1).x, i7.y - o7.points.at(-1).y) + Math.hypot(r7.x - o7.points[0].x, r7.y - o7.points[0].y) + 0.00000001 \u003c s7, c5 = a7 ? o7.points.at(-1) : o7.points[0], l5 = a7 ? o7.points[0] : o7.points.at(-1);\n if (i7.layer !== c5.layer || r7.layer !== l5.layer)\n throw new T6({ connectionNames: this.input.pair.connectionNames, reason: \"terminal-layer-mismatch\", message: \"does not have common paired layers at both terminal stations\" });\n const h5 = { x: (i7.x + c5.x) / 2, y: (i7.y + c5.y) / 2, layer: i7.layer }, d7 = { x: (r7.x + l5.x) / 2, y: (r7.y + l5.y) / 2, layer: r7.layer }, u7 = Math.hypot(d7.x - h5.x, d7.y - h5.y);\n if (u7 \u003c 0.000001)\n throw new T6({ connectionNames: this.input.pair.connectionNames, reason: \"coincident-terminal-midpoints\", message: \"has coincident terminal-pair midpoints\" });\n const p7 = { x: -(d7.y - h5.y) / u7, y: (d7.x - h5.x) / u7 }, m7 = i7.x - c5.x, g7 = i7.y - c5.y, f7 = m7 * p7.x + g7 * p7.y \u003e= 0 ? 1 : -1, _5 = (e53, t7) =\u003e {\n const n8 = e53.x - t7.x, o8 = e53.y - t7.y, i8 = Math.hypot(n8, o8);\n return i8 \u003e 0.00000001 \u0026\u0026 Math.abs(n8 * p7.x + o8 * p7.y) / i8 \u003c 0.5;\n }, y7 = _5(i7, c5) \u0026\u0026 _5(r7, l5), b7 = { x: p7.y, y: -p7.x }, x7 = [i7, c5].some((e53) =\u003e (e53.x - h5.x) * b7.x + (e53.y - h5.y) * b7.y \u003e 0.00000001), v7 = { immutableTraces: this.input.traces.filter((n8, o8) =\u003e o8 !== e51[0].index \u0026\u0026 o8 !== t4[0].index), obstacles: this.input.obstacles, bounds: this.input.bounds, layerCount: this.input.layerCount, minTraceToPadEdgeClearance: this.input.minTraceToPadEdgeClearance }, I6 = ((e53) =\u003e {\n const { minimumCenterlineDistance: t7, maximumCenterlineDistance: n8 } = e53;\n if (t7 === undefined \u0026\u0026 n8 === undefined)\n return e53.legacyCenterlineDistances;\n const o8 = [...t7 !== undefined \u0026\u0026 n8 !== undefined ? [(t7 + n8) / 2, t7, n8, t7 - 0.25, n8 + 0.25] : t7 !== undefined ? [t7, t7 + 0.25, t7 + 0.5, t7 - 0.25, t7 + 1] : [n8, n8 - 0.25, n8 - 0.5, n8 + 0.25, n8 - 1], ...e53.legacyCenterlineDistances];\n return o8.filter((t8, n9) =\u003e t8 \u003e e53.minimumPhysicalDistance \u0026\u0026 o8.findIndex((e54) =\u003e Math.abs(e54 - t8) \u003c 0.00000001) === n9);\n })({ minimumCenterlineDistance: this.input.pair.minimumCenterlineDistance, maximumCenterlineDistance: this.input.pair.maximumCenterlineDistance, minimumPhysicalDistance: n7.width / 2 + o7.width / 2, legacyCenterlineDistances: H6.map((e53) =\u003e e53 + n7.width / 2 + o7.width / 2) }).flatMap((e53) =\u003e {\n const t7 = e53 - n7.width / 2 - o7.width / 2;\n return [f7, f7 === 1 ? -1 : 1].flatMap((s8) =\u003e {\n const a8 = Y6({ config: this.input.routingGrid, bounds: this.input.bounds, defaultInnerGridStep: Math.max(0.25, Math.min(0.5, e53 / 2)) }), u8 = (t8, a9) =\u003e z6({ ...v7, start: t8, end: a9, firstConnectionName: n7.source.connection_name, secondConnectionName: o7.source.connection_name, firstStartTerminal: i7, firstEndTerminal: r7, secondStartTerminal: c5, secondEndTerminal: l5, firstWidth: n7.width, secondWidth: o7.width, firstViaDiameter: n7.transitions[0]?.via_diameter ?? n7.viaDiameter, secondViaDiameter: o7.transitions[0]?.via_diameter ?? o7.viaDiameter, centerlineSpacing: e53, side: s8, terminalFanout: y7, terminalMiterMargin: this.input.pair.maxUncoupledLength === undefined ? undefined : e53 / 2 });\n let m8 = this.input.pair.maxUncoupledLength === undefined ? ((e54, t8) =\u003e {\n if (!x7 || y7)\n return h5;\n const n8 = [{ terminal: i7, offset: t8 * e54 / 2 }, { terminal: c5, offset: -t8 * e54 / 2 }], o8 = Math.tan(55 * Math.PI / 180), r8 = Math.max(...n8.map(({ terminal: e55, offset: t9 }) =\u003e {\n const n9 = (e55.x - h5.x) * b7.x + (e55.y - h5.y) * b7.y, i8 = (e55.x - h5.x) * p7.x + (e55.y - h5.y) * p7.y;\n return n9 + Math.abs(i8 - t9) / o8;\n }));\n return { x: h5.x + b7.x * r8, y: h5.y + b7.y * r8, layer: h5.layer };\n })(e53, s8) : h5, g8 = d7;\n if (!y7 \u0026\u0026 this.input.pair.maxUncoupledLength !== undefined) {\n const t8 = u8(h5, d7), n8 = X6({ anchor: h5, escapeDirection: b7, pathDirection: b7, centerlineSpacing: e53, side: s8, lanes: [{ point: i7, polarity: 1 }, { point: c5, polarity: -1 }], maxUncoupledLength: this.input.pair.maxUncoupledLength, maximumTurnDegrees: 55, searchStep: a8.innerGridStep, isValid: (e54) =\u003e t8.isTerminalFanoutValid(e54, b7, \"start\") }), o8 = X6({ anchor: d7, escapeDirection: { x: -b7.x, y: -b7.y }, pathDirection: b7, centerlineSpacing: e53, side: s8, lanes: [{ point: r7, polarity: 1 }, { point: l5, polarity: -1 }], maxUncoupledLength: this.input.pair.maxUncoupledLength, maximumTurnDegrees: 45, searchStep: a8.innerGridStep, isValid: (e54) =\u003e t8.isTerminalFanoutValid(e54, b7, \"end\") });\n if (!n8 || !o8)\n return [];\n m8 = n8, g8 = o8;\n if ((g8.x - m8.x) * b7.x + (g8.y - m8.y) * b7.y \u003c= a8.innerGridStep)\n return [];\n }\n const f8 = u8(m8, g8);\n return [{ edgeGap: t7, side: s8, input: { start: m8, end: g8, bounds: this.input.bounds, layerCount: this.input.layerCount, grid: a8, ...f8 } }];\n });\n });\n return { first: n7, second: o7, reverseSecond: a7, terminalFanout: y7, context: v7, attempts: I6 };\n }\n complete() {\n if (this.candidates.length === 0)\n throw new T6({ connectionNames: this.input.pair.connectionNames, reason: \"no-valid-candidate\", message: \"could not be improved without violating bounds, copper clearance, or coupled-via constraints\" });\n this.candidates.sort((e51, t4) =\u003e this.score(e51) - this.score(t4) || e51.edgeGap - t4.edgeGap), this.result = { status: \"accepted\", candidate: this.candidates[0] };\n }\n score(e51) {\n return (this.input.pair.minimumCenterlineDistance !== undefined || this.input.pair.maximumCenterlineDistance !== undefined ? Math.max(0, (this.input.pair.minimumCenterlineDistance ?? Number.NEGATIVE_INFINITY) - e51.centerlineDistance) * V6 + Math.max(0, e51.centerlineDistance - (this.input.pair.maximumCenterlineDistance ?? Number.POSITIVE_INFINITY)) * V6 : e51.edgeGap \u003c 0.5 ? (0.5 - e51.edgeGap) * V6 : e51.edgeGap \u003e 1 ? (e51.edgeGap - 1) * V6 : 0) + M6(e51.firstParsed) + M6(e51.secondParsed) + 0.15 * e51.bendCount + 8 * e51.viaPairCount;\n }\n};\nvar G6 = (e51) =\u003e {\n const t4 = { lines: [], points: [], rects: [], circles: [] };\n t4.rects.push({ center: { x: (e51.bounds.minX + e51.bounds.maxX) / 2, y: (e51.bounds.minY + e51.bounds.maxY) / 2 }, width: e51.bounds.maxX - e51.bounds.minX, height: e51.bounds.maxY - e51.bounds.minY, fill: \"rgba(30, 70, 120, 0.04)\", stroke: \"rgba(30, 70, 120, 0.55)\", layer: `z${Array.from({ length: e51.layerCount }, (e53, t7) =\u003e t7).join(\",\")}` });\n for (const n7 of e51.obstacles) {\n const o7 = o6(n7, e51.layerCount);\n t4.rects.push({ center: n7.center, width: n7.width, height: n7.height, ccwRotationDegrees: n7.ccwRotationDegrees, fill: \"rgba(220, 60, 60, 0.16)\", stroke: \"rgba(190, 40, 40, 0.75)\", layer: `z${o7.join(\",\")}` });\n }\n for (let n7 = 0;n7 \u003c (e51.previewPath?.length ?? 0) - 1; n7++) {\n const o7 = e51.previewPath[n7], i7 = e51.previewPath[n7 + 1];\n if (o7.layer !== i7.layer)\n continue;\n const r7 = G4(o7.layer, e51.layerCount);\n t4.lines.push({ points: [o7, i7], strokeColor: \"#16a34a\", strokeWidth: 0.08, strokeDash: [0.18, 0.12], layer: `z${r7}` });\n }\n for (const n7 of e51.traces) {\n if (e51.activeConnectionNames?.includes(n7.connection_name))\n continue;\n const o7 = \"#2563eb\";\n let i7 = null;\n for (const r7 of n7.route)\n if (r7.route_type === \"wire\") {\n if (i7 \u0026\u0026 i7.layer === r7.layer) {\n const n8 = G4(r7.layer, e51.layerCount);\n t4.lines.push({ points: [i7, r7], strokeColor: o7, strokeWidth: Math.max(i7.width, r7.width), ...n8 === 0 ? {} : { strokeDash: [0.2, 0.16] }, layer: `z${n8}` });\n }\n i7 = r7;\n } else if (r7.route_type === \"via\") {\n const n8 = Z4(r7.from_layer, r7.to_layer, e51.layerCount).map((t7) =\u003e G4(t7, e51.layerCount));\n if (t4.circles.push({ center: r7, radius: (r7.via_diameter ?? i7?.width ?? 0.2) / 2, fill: \"rgba(37, 99, 235, 0.45)\", stroke: o7, layer: `z${n8.join(\",\")}` }), i7) {\n const e53 = i7.width;\n i7 = { x: r7.x, y: r7.y, layer: r7.to_layer, width: e53 };\n }\n }\n }\n return t4;\n};\nvar U6 = class extends BaseSolver {\n constructor(e51) {\n super(), this.params = e51, this.outputTraces = D6(e51.simpleRouteJson.traces), this.MAX_ITERATIONS = O6(e51);\n }\n outputTraces;\n reroutedPairs = [];\n failures = [];\n nextPairIndex = 0;\n activeConnectionNames = null;\n activeSession = null;\n getSolverName() {\n return \"DifferentialPairReroutingSolver\";\n }\n _step() {\n const e51 = this.params.simpleRouteJson.differentialPairs[this.nextPairIndex];\n if (!e51)\n return void this.finish();\n this.activeConnectionNames = e51.connectionNames;\n try {\n if (!this.activeSession)\n return this.activeSession = new W6({ pair: e51, traces: this.outputTraces, obstacles: this.params.simpleRouteJson.obstacles, bounds: this.params.simpleRouteJson.bounds, layerCount: this.params.simpleRouteJson.layerCount, minTraceToPadEdgeClearance: this.params.simpleRouteJson.minTraceToPadEdgeClearance, routingGrid: this.params.routingGrid }), void (this.stats = this.activeSession.getStats());\n this.activeSession.step();\n } catch (t7) {\n if (!(t7 instanceof T6))\n throw t7;\n return void this.skipFailedPair(e51, t7);\n }\n if (this.stats = this.activeSession.getStats(), !this.activeSession.isComplete())\n return;\n const t4 = this.activeSession.getResult();\n this.activeSession = null;\n for (const e53 of [t4.candidate.first, t4.candidate.second]) {\n const t7 = this.outputTraces.findIndex((t8) =\u003e t8.connection_name === e53.connection_name);\n if (t7 \u003c 0)\n throw new Error(`DifferentialPairReroutingSolver: accepted replacement for unknown connection \"${e53.connection_name}\"`);\n this.outputTraces[t7] = e53;\n }\n this.reroutedPairs.push(e51), this.nextPairIndex++, this.nextPairIndex !== this.params.simpleRouteJson.differentialPairs.length ? this.stats = { phase: \"accepted\", pair: e51.connectionNames.join(\"/\"), pairIndex: this.nextPairIndex - 1, pairCount: this.params.simpleRouteJson.differentialPairs.length } : this.finish();\n }\n finish() {\n this.activeConnectionNames = null, this.solved = true, this.stats = { phase: \"complete\", acceptedPairCount: this.reroutedPairs.length, skippedPairCount: this.failures.length };\n }\n skipFailedPair(e51, t4) {\n this.failures.push({ connectionNames: [...e51.connectionNames], reason: t4.reason, message: t4.message }), this.activeSession = null, this.nextPairIndex++, this.nextPairIndex !== this.params.simpleRouteJson.differentialPairs.length ? this.stats = { phase: \"skipped\", pair: e51.connectionNames.join(\"/\"), pairIndex: this.nextPairIndex - 1, pairCount: this.params.simpleRouteJson.differentialPairs.length, skippedPairCount: this.failures.length } : this.finish();\n }\n getConstructorParams() {\n return [this.params];\n }\n getOutput() {\n if (!this.solved)\n throw new Error(\"DifferentialPairReroutingSolver: getOutput() called before completion\");\n return this.getBestEffortOutput();\n }\n getBestEffortOutput() {\n return { traces: D6(this.outputTraces), reroutedPairs: this.reroutedPairs.map((e51) =\u003e ({ ...e51, connectionNames: [...e51.connectionNames] })), failures: this.failures.map((e51) =\u003e ({ ...e51, connectionNames: [...e51.connectionNames] })) };\n }\n computeProgress() {\n return this.solved ? 1 : this.params.simpleRouteJson.differentialPairs.length === 0 ? 0 : (this.nextPairIndex + (this.activeSession?.getProgress() ?? 0)) / this.params.simpleRouteJson.differentialPairs.length;\n }\n visualize() {\n return G6({ traces: this.outputTraces, obstacles: this.params.simpleRouteJson.obstacles, bounds: this.params.simpleRouteJson.bounds, layerCount: this.params.simpleRouteJson.layerCount, activeConnectionNames: this.activeConnectionNames, previewPath: this.activeSession?.getPreviewPath() ?? null });\n }\n};\nvar q6 = 0.00000001;\nvar J6 = class extends BaseSolver {\n constructor(e51) {\n super(), this.input = e51, this.traces = D6(e51.traces), this.MAX_ITERATIONS = Math.max(1, e51.reroutedPairs.length + 1);\n }\n traces;\n nextPairIndex = 0;\n getSolverName() {\n return \"FortyFiveDegreeSimplificationSolver\";\n }\n _step() {\n const e51 = this.input.reroutedPairs[this.nextPairIndex];\n if (!e51)\n return this.solved = true, void (this.stats = { phase: \"complete\", simplifiedPairCount: this.nextPairIndex });\n this.traces = ((e53) =\u003e {\n const t4 = e53.pair.connectionNames.join(\"/\"), n7 = e53.pair.connectionNames.map((t7) =\u003e e53.traces.map((e54, t8) =\u003e ({ trace: e54, index: t8 })).filter(({ trace: e54 }) =\u003e e54.connection_name === t7));\n if (n7[0].length !== 1 || n7[1].length !== 1)\n throw new Error(`FortyFiveDegreeSimplificationSolver: pair ${t4} must resolve to exactly two traces`);\n const o7 = n7[0][0].index, i7 = n7[1][0].index;\n if (o7 === i7)\n throw new Error(`FortyFiveDegreeSimplificationSolver: pair ${t4} resolved both members to one trace`);\n const r7 = structuredClone(e53.traces), s7 = { immutableTraces: r7.filter((e54, t7) =\u003e t7 !== o7 \u0026\u0026 t7 !== i7), obstacles: e53.obstacles, bounds: e53.bounds, layerCount: e53.layerCount, minTraceToPadEdgeClearance: e53.minTraceToPadEdgeClearance }, a7 = (n8) =\u003e {\n const r8 = P6(n8[o7], e53.layerCount), s8 = P6(n8[i7], e53.layerCount);\n let a8 = 0;\n for (const [e54, n9] of [[r8.segments, s8.segments], [s8.segments, r8.segments]])\n for (const o8 of e54) {\n if (o8.terminal !== null)\n continue;\n const e55 = n9.filter((e56) =\u003e e56.layer === o8.layer);\n if (e55.length === 0)\n throw new Error(`FortyFiveDegreeSimplificationSolver: pair ${t4} lost common-layer interior copper`);\n a8 = Math.max(a8, Math.min(...e55.map((e56) =\u003e K4(o8.start, o8.end, e56.start, e56.end))));\n }\n return a8;\n }, c5 = (t7) =\u003e {\n const n8 = P6(t7[o7], e53.layerCount), r8 = P6(t7[i7], e53.layerCount);\n let s8 = Number.POSITIVE_INFINITY;\n for (const [e54, t8] of [[n8.segments, r8.segments], [r8.segments, n8.segments]])\n for (const n9 of e54)\n if (n9.terminal === null)\n for (const e55 of t8)\n e55.layer === n9.layer \u0026\u0026 (s8 = Math.min(s8, K4(n9.start, n9.end, e55.start, e55.end) - n9.width / 2 - e55.width / 2));\n return Number.isFinite(s8) ? s8 : null;\n }, l5 = (t7) =\u003e {\n const n8 = P6(t7[o7], e53.layerCount), r8 = P6(t7[i7], e53.layerCount);\n return B6(n8, r8, s7);\n };\n if (!l5(r7))\n throw new Error(`FortyFiveDegreeSimplificationSolver: rerouted pair ${t4} has invalid complete copper before simplification`);\n if (e53.pair.maxUncoupledLength !== undefined \u0026\u0026 e53.pair.minimumCenterlineDistance !== undefined \u0026\u0026 e53.pair.maximumCenterlineDistance !== undefined \u0026\u0026 Math.abs(e53.pair.minimumCenterlineDistance - e53.pair.maximumCenterlineDistance) \u003c= q6)\n return r7;\n const h5 = P6(r7[o7], e53.layerCount), d7 = P6(r7[i7], e53.layerCount), u7 = Math.abs(M6(h5) - M6(d7)), p7 = c5(r7), m7 = e53.pair.maximumCenterlineDistance ?? 1 + h5.width / 2 + d7.width / 2, g7 = Math.min(a7(r7), m7), f7 = (e54) =\u003e {\n if (!l5(e54))\n return false;\n if (a7(e54) \u003e g7 + q6)\n return false;\n const t7 = c5(e54);\n return p7 === null || t7 === null || t7 \u003e= p7 - q6;\n }, _5 = (e54, t7) =\u003e {\n const n8 = Math.abs(t7.x - e54.x), o8 = Math.abs(t7.y - e54.y), i8 = t7.x \u003e= e54.x ? 1 : -1, r8 = t7.y \u003e= e54.y ? 1 : -1, s8 = [], a8 = { x: t7.x - i8 * o8, y: e54.y };\n (a8.x - e54.x) * i8 \u003e= -0.00000001 \u0026\u0026 (a8.x - t7.x) * i8 \u003c= q6 \u0026\u0026 s8.push([e54, a8, t7]);\n const c7 = { x: e54.x, y: t7.y - r8 * n8 };\n (c7.y - e54.y) * r8 \u003e= -0.00000001 \u0026\u0026 (c7.y - t7.y) * r8 \u003c= q6 \u0026\u0026 s8.push([e54, c7, t7]);\n const l7 = { x: e54.x + i8 * Math.min(n8, o8), y: e54.y + r8 * Math.min(n8, o8) };\n return s8.push([e54, l7, t7]), s8.map((e55, t8) =\u003e {\n const n9 = e55.filter((t9, n10) =\u003e n10 === 0 || Math.hypot(t9.x - e55[n10 - 1].x, t9.y - e55[n10 - 1].y) \u003e q6), o9 = n9.slice(0, -1).map((e56, t9) =\u003e {\n const o10 = n9[t9 + 1], i9 = Math.abs(o10.x - e56.x), r9 = Math.abs(o10.y - e56.y);\n return { length: Math.hypot(i9, r9), straight: i9 \u003c= q6 || r9 \u003c= q6 ? Math.hypot(i9, r9) : 0 };\n });\n return { points: n9, usableStraightLength: Math.max(0, ...o9.map((e56) =\u003e e56.straight)), bendCount: Math.max(0, n9.length - 2), priority: t8 };\n }).filter((e55, t8, n9) =\u003e n9.findIndex((t9) =\u003e JSON.stringify(t9.points) === JSON.stringify(e55.points)) === t8).sort((e55, t8) =\u003e t8.usableStraightLength - e55.usableStraightLength || e55.bendCount - t8.bendCount || e55.priority - t8.priority);\n }, y7 = (e54) =\u003e {\n const t7 = [];\n for (let n8 = 0;n8 \u003c e54.route.length - 1; n8++) {\n const o8 = e54.route[n8];\n if (o8?.route_type === \"wire\")\n for (let i8 = e54.route.length - 1;i8 \u003e= n8 + 1; i8--) {\n if (n8 === 0 || i8 === e54.route.length - 1)\n continue;\n const r8 = e54.route[i8];\n r8?.route_type === \"wire\" \u0026\u0026 r8.layer === o8.layer \u0026\u0026 (e54.route.slice(n8 + 1, i8).some((e55) =\u003e e55.route_type !== \"wire\" || e55.layer !== o8.layer) || t7.push({ startIndex: n8, endIndex: i8, skippedPointCount: i8 - n8 - 1 }));\n }\n }\n return t7.sort((e55, t8) =\u003e t8.skippedPointCount - e55.skippedPointCount || e55.startIndex - t8.startIndex || t8.endIndex - e55.endIndex);\n }, b7 = (e54, t7, n8) =\u003e {\n const o8 = e54.route[t7.startIndex], i8 = e54.route[t7.endIndex], r8 = Math.max(o8.width, i8.width), s8 = n8.points.slice(1, -1).map((e55) =\u003e ({ route_type: \"wire\", ...e55, width: r8, layer: o8.layer }));\n return { ...e54, route: [...e54.route.slice(0, t7.startIndex + 1), ...s8, ...e54.route.slice(t7.endIndex)] };\n };\n for (const e54 of [o7, i7]) {\n let t7 = true;\n for (;t7; ) {\n t7 = false;\n const n8 = r7[e54];\n for (const s8 of y7(n8)) {\n const a8 = n8.route[s8.startIndex], c7 = n8.route[s8.endIndex], l7 = n8.route.slice(s8.startIndex, s8.endIndex + 1), h7 = l7.slice(0, -1).every((e55, t8) =\u003e {\n const n9 = l7[t8 + 1], o8 = Math.abs(n9.x - e55.x), i8 = Math.abs(n9.y - e55.y);\n return o8 \u003c= q6 || i8 \u003c= q6 || Math.abs(o8 - i8) \u003c= q6;\n });\n for (const d8 of _5(a8, c7)) {\n if (d8.points.length \u003e= l7.length \u0026\u0026 h7)\n continue;\n const a9 = b7(n8, s8, d8), c8 = [...r7];\n if (c8[e54] = a9, JSON.stringify(a9.route) === JSON.stringify(n8.route))\n continue;\n if (f7(c8)) {\n r7[e54] = a9, t7 = true;\n break;\n }\n const u8 = e54 === o7 ? i7 : o7, p8 = r7[u8], m8 = y7(p8).find((e55) =\u003e e55.startIndex === s8.startIndex \u0026\u0026 e55.endIndex === s8.endIndex);\n if (!m8)\n continue;\n const g8 = p8.route[m8.startIndex], x8 = p8.route[m8.endIndex];\n for (const n9 of _5(g8, x8)) {\n const o8 = b7(p8, m8, n9), i8 = [...c8];\n if (i8[u8] = o8, f7(i8)) {\n r7[e54] = a9, r7[u8] = o8, t7 = true;\n break;\n }\n }\n if (t7)\n break;\n }\n if (t7)\n break;\n }\n }\n }\n if (!f7(r7))\n throw new Error(`FortyFiveDegreeSimplificationSolver: pair ${t4} produced invalid complete copper`);\n const x7 = P6(r7[o7], e53.layerCount), v7 = P6(r7[i7], e53.layerCount), I6 = Math.abs(M6(x7) - M6(v7));\n return Math.abs(I6 - u7) \u003e e53.pair.lengthTolerance + q6 ? structuredClone(e53.traces) : r7;\n })({ traces: this.traces, pair: e51, obstacles: this.input.obstacles, bounds: this.input.bounds, layerCount: this.input.layerCount, minTraceToPadEdgeClearance: this.input.minTraceToPadEdgeClearance }), this.nextPairIndex++, this.stats = { phase: \"simplifying\", pair: e51.connectionNames.join(\"/\"), pairIndex: this.nextPairIndex - 1, pairCount: this.input.reroutedPairs.length };\n }\n getConstructorParams() {\n return [this.input];\n }\n getOutput() {\n if (!this.solved)\n throw new Error(\"FortyFiveDegreeSimplificationSolver: getOutput() called before completion\");\n return this.getBestEffortOutput();\n }\n getBestEffortOutput() {\n return { traces: D6(this.traces), reroutedPairs: this.input.reroutedPairs.map((e51) =\u003e ({ ...e51, connectionNames: [...e51.connectionNames] })) };\n }\n computeProgress() {\n return this.solved ? 1 : this.input.reroutedPairs.length === 0 ? 0 : this.nextPairIndex / this.input.reroutedPairs.length;\n }\n visualize() {\n return G6({ traces: this.traces, obstacles: this.input.obstacles, bounds: this.input.bounds, layerCount: this.input.layerCount, activeConnectionNames: this.input.reroutedPairs[this.nextPairIndex]?.connectionNames ?? null, previewPath: null });\n }\n};\nvar K6 = (e51, t4) =\u003e Math.abs(e51 - t4) \u003c= 0.0000001;\nvar e92 = (e51, t4) =\u003e K6(e51.x, t4.x) \u0026\u0026 K6(e51.y, t4.y);\nvar t9 = (e51) =\u003e {\n const t4 = e51.candidatePair.map((t7, n7) =\u003e {\n const o7 = e51.originalPair[n7];\n return { ...t7, segments: t7.segments.filter((e53) =\u003e !o7.segments.some((t8) =\u003e {\n return o8 = e53, (n8 = t8).layer === o8.layer \u0026\u0026 !!K6(n8.width, o8.width) \u0026\u0026 !!e92(n8.start, o8.start) \u0026\u0026 !!e92(n8.end, o8.end);\n var n8, o8;\n })), vias: t7.vias.filter((e53) =\u003e !o7.vias.some((t8) =\u003e {\n return !!e92(n8 = t8, o8 = e53) \u0026\u0026 !!K6(n8.diameter, o8.diameter) \u0026\u0026 n8.layers.length === o8.layers.length \u0026\u0026 !!n8.layers.every((e54) =\u003e o8.layers.includes(e54));\n var n8, o8;\n })) };\n });\n return [t4[0], t4[1]];\n};\nvar n9 = class extends BaseSolver {\n constructor(e51) {\n super(), this.input = e51;\n }\n output = null;\n visualizationTraces = null;\n getSolverName() {\n return \"HdRouteReconstructionSolver\";\n }\n _step() {\n this.visualizationTraces = ((e51) =\u003e {\n const { simpleRouteJson: t4 } = e51.params;\n if (e51.result.matchedHdRoutes.length !== e51.binding.solverParams.hdRoutes.length)\n throw new Error(\"PostProcessingSolver: LengthMatchingSolver changed the search route count\");\n const n7 = structuredClone(e51.binding.baseTraces);\n for (const o7 of e51.binding.traceBindings) {\n const i7 = e51.result.matchedHdRoutes[o7.matchedRouteIndex];\n if (!i7)\n throw new Error(`PostProcessingSolver: missing matched route at index ${o7.matchedRouteIndex}`);\n const r7 = n7[o7.traceIndex];\n if (!r7)\n throw new Error(`PostProcessingSolver: missing simplified trace binding at index ${o7.traceIndex}`);\n if (r7.connection_name !== i7.connectionName)\n throw new Error(`PostProcessingSolver: route binding changed connection \"${r7.connection_name}\" to \"${i7.connectionName}\"`);\n if (i7.route.length \u003c 2)\n throw new Error(`PostProcessingSolver: matched connection \"${i7.connectionName}\" has incomplete geometry`);\n const s7 = i7.route[0], a7 = i7.route.at(-1);\n if (Math.hypot(s7.x - o7.startEndpoint.x, s7.y - o7.startEndpoint.y) \u003e 0.00000001 || s7.z !== o7.startEndpoint.z || Math.hypot(a7.x - o7.endEndpoint.x, a7.y - o7.endEndpoint.y) \u003e 0.00000001 || a7.z !== o7.endEndpoint.z)\n throw new Error(`PostProcessingSolver: matched connection \"${i7.connectionName}\" moved a preserved endpoint`);\n const c5 = [];\n let l5 = 0;\n const h5 = (e53) =\u003e ({ route_type: \"wire\", x: e53.x, y: e53.y, width: e53.traceThickness ?? i7.traceThickness, layer: U4(e53.z, t4.layerCount) });\n c5.push(h5(i7.route[0]));\n for (let e53 = 1;e53 \u003c i7.route.length; e53++) {\n const n8 = i7.route[e53 - 1], r8 = i7.route[e53];\n if (n8.z === r8.z) {\n c5.push(h5(r8));\n continue;\n }\n if (Math.hypot(n8.x - r8.x, n8.y - r8.y) \u003e 0.00000001)\n throw new Error(`PostProcessingSolver: matched connection \"${i7.connectionName}\" moves while changing layers`);\n const s8 = o7.viaTemplates[l5++];\n if (!s8)\n throw new Error(`PostProcessingSolver: matched connection \"${i7.connectionName}\" added an unbound via`);\n if (Math.hypot(s8.x - r8.x, s8.y - r8.y) \u003e 0.00000001)\n throw new Error(`PostProcessingSolver: matched connection \"${i7.connectionName}\" moved a preserved via`);\n const a8 = U4(n8.z, t4.layerCount), d8 = U4(r8.z, t4.layerCount), u7 = new Set([s8.from_layer, s8.to_layer]);\n if (!u7.has(a8) || !u7.has(d8))\n throw new Error(`PostProcessingSolver: matched connection \"${i7.connectionName}\" changed a preserved via span`);\n c5.push({ ...s8 }), c5.push(h5(r8));\n }\n if (l5 !== o7.viaTemplates.length)\n throw new Error(`PostProcessingSolver: matched connection \"${i7.connectionName}\" removed a preserved via`);\n const d7 = c5.filter((e53) =\u003e e53.route_type === \"wire\");\n for (const e53 of d7)\n delete e53.start_pcb_port_id, delete e53.end_pcb_port_id;\n o7.startPortId \u0026\u0026 (d7[0].start_pcb_port_id = o7.startPortId), o7.endPortId \u0026\u0026 (d7.at(-1).end_pcb_port_id = o7.endPortId), n7[o7.traceIndex] = { ...r7, route: c5 };\n }\n for (const o7 of e51.binding.solverParams.differentialPairs) {\n const i7 = o7.connectionNames.join(\"/\"), r7 = o7.connectionNames.map((e53) =\u003e n7.map((e54, t7) =\u003e ({ trace: e54, index: t7 })).filter(({ trace: t7 }) =\u003e t7.connection_name === e53));\n if (r7[0].length !== 1 || r7[1].length !== 1)\n throw new Error(`PostProcessingSolver: reconstructed pair ${i7} does not resolve to complete copper`);\n const s7 = r7[0][0], a7 = r7[1][0], c5 = o7.connectionNames.map((t7) =\u003e {\n const n8 = e51.binding.baseTraces.filter((e53) =\u003e e53.connection_name === t7);\n if (n8.length !== 1)\n throw new Error(`PostProcessingSolver: original pair ${i7} does not resolve to complete copper`);\n return n8[0];\n }), l5 = P6(s7.trace, t4.layerCount), h5 = P6(a7.trace, t4.layerCount), d7 = P6(c5[0], t4.layerCount), u7 = P6(c5[1], t4.layerCount), p7 = Math.abs(M6(l5) - M6(h5));\n if (p7 \u003e o7.lengthTolerance + 0.0000001)\n throw new E6({ message: `PostProcessingSolver: reconstructed pair ${i7} exceeds length tolerance ${o7.lengthTolerance} with error ${p7}`, connectionNames: [...o7.connectionNames], reason: \"length-tolerance-unsatisfied\" });\n const m7 = { immutableTraces: n7.filter((e53, t7) =\u003e t7 !== s7.index \u0026\u0026 t7 !== a7.index), obstacles: t4.obstacles, bounds: t4.bounds, layerCount: t4.layerCount, minTraceToPadEdgeClearance: t4.minTraceToPadEdgeClearance }, g7 = B6(l5, h5, { ...m7, obstacles: [] }), f7 = t9({ candidatePair: [l5, h5], originalPair: [d7, u7] }), _5 = B6(f7[0], f7[1], { ...m7, immutableTraces: [] });\n if (!g7 || !_5)\n throw new E6({ message: `PostProcessingSolver: length matching produced invalid complete copper for pair ${i7}`, connectionNames: [...o7.connectionNames], reason: \"invalid-final-copper\" });\n }\n return n7;\n })(this.input), this.output = R6({ ...this.input, rejectInsideJumperPad: true }), this.stats = { phase: \"complete\", routeCount: this.output.hdRoutes.length }, this.solved = true;\n }\n getConstructorParams() {\n return [this.input];\n }\n getOutput() {\n if (!this.output || !this.solved)\n throw new Error(\"HdRouteReconstructionSolver: getOutput() called before completion\");\n return structuredClone(this.output);\n }\n visualize() {\n const e51 = this.visualizationTraces ?? this.input.simplified.traces, { obstacles: t4, bounds: n7, layerCount: o7 } = this.input.params.simpleRouteJson;\n return G6({ traces: e51, obstacles: t4, bounds: n7, layerCount: o7, activeConnectionNames: null, previewPath: null });\n }\n};\nvar o9 = class extends BasePipelineSolver {\n differentialPairReroutingSolver;\n fortyFiveDegreeSimplificationSolver;\n lengthMatchingSolver;\n hdRouteReconstructionSolver;\n lengthMatchingBinding = null;\n model;\n fallbackOutput = null;\n postProcessingErrors = [];\n pipelineDef = [definePipelineStep(\"differentialPairReroutingSolver\", U6, (e51) =\u003e [e51.model.params]), definePipelineStep(\"fortyFiveDegreeSimplificationSolver\", J6, (e51) =\u003e {\n const t4 = e51.getStageOutput(\"differentialPairReroutingSolver\");\n if (!t4)\n throw new Error(\"PostProcessingSolver: rerouting stage completed without output\");\n const { obstacles: n7, bounds: o7, layerCount: i7, minTraceToPadEdgeClearance: r7 } = e51.model.params.simpleRouteJson;\n return [{ ...t4, obstacles: n7, bounds: o7, layerCount: i7, minTraceToPadEdgeClearance: r7 }];\n }), definePipelineStep(\"lengthMatchingSolver\", v6, (e51) =\u003e {\n const t4 = e51.getStageOutput(\"fortyFiveDegreeSimplificationSolver\");\n if (!t4)\n throw new Error(\"PostProcessingSolver: 45-degree simplification stage completed without output\");\n return e51.lengthMatchingBinding = w6({ result: t4, params: e51.model.params }), [e51.lengthMatchingBinding.solverParams];\n }), definePipelineStep(\"hdRouteReconstructionSolver\", n9, (e51) =\u003e {\n const t4 = e51.getStageOutput(\"fortyFiveDegreeSimplificationSolver\"), n7 = e51.getStageOutput(\"lengthMatchingSolver\");\n if (!t4 || !n7 || !e51.lengthMatchingBinding)\n throw new Error(\"PostProcessingSolver: reconstruction stage is missing a required binding or output\");\n return [{ binding: e51.lengthMatchingBinding, result: n7, simplified: t4, params: e51.model.params, model: e51.model }];\n }, { onSolved: (e51) =\u003e {\n const t4 = e51.getStageOutput(\"differentialPairReroutingSolver\");\n if (!t4)\n throw new Error(\"PostProcessingSolver: cannot summarize missing rerouting output\");\n e51.stats = { phase: \"complete\", acceptedPairCount: t4.reroutedPairs.length }, t4.failures.length \u003e 0 \u0026\u0026 (e51.stats.skippedPairCount = t4.failures.length, e51.stats.postProcessingErrorCount = t4.failures.length);\n } })];\n constructor(e51) {\n super(structuredClone(e51));\n let t4 = null;\n try {\n (function(e53) {\n if (!e53 || typeof e53 != \"object\")\n throw new Error(\"PostProcessingSolver: params must be an object\");\n if (!Array.isArray(e53.hdRoutes))\n throw new Error(\"PostProcessingSolver: hdRoutes must be an array\");\n if (!Array.isArray(e53.differentialPairs))\n throw new Error(\"PostProcessingSolver: differentialPairs must be an array\");\n if (!Array.isArray(e53.obstacles))\n throw new Error(\"PostProcessingSolver: obstacles must be an array\");\n if (e53.minTraceToPadEdgeClearance !== undefined \u0026\u0026 (!Number.isFinite(e53.minTraceToPadEdgeClearance) || e53.minTraceToPadEdgeClearance \u003c 0))\n throw new Error(\"PostProcessingSolver: minTraceToPadEdgeClearance must be finite and nonnegative\");\n if (!Number.isInteger(e53.layerCount) || e53.layerCount \u003c 1)\n throw new Error(\"PostProcessingSolver: layerCount must be a positive integer\");\n for (const t8 of e53.obstacles) {\n if (!t8 || typeof t8 != \"object\" || t8.type !== \"rect\" || !t8.center || !Number.isFinite(t8.center.x) || !Number.isFinite(t8.center.y) || !Number.isFinite(t8.width) || t8.width \u003c= 0 || !Number.isFinite(t8.height) || t8.height \u003c= 0 || !Array.isArray(t8.layers) || t8.layers.some((e54) =\u003e typeof e54 != \"string\") || !Array.isArray(t8.connectedTo) || t8.connectedTo.some((e54) =\u003e typeof e54 != \"string\" || e54.length === 0) || t8.ccwRotationDegrees !== undefined \u0026\u0026 !Number.isFinite(t8.ccwRotationDegrees))\n throw new Error(\"PostProcessingSolver: obstacle declaration is invalid\");\n o6(t8, e53.layerCount);\n }\n const { minX: t7, maxX: n8, minY: o7, maxY: i7 } = e53.bounds ?? {};\n if (![t7, n8, o7, i7].every(Number.isFinite) || t7 \u003e= n8 || o7 \u003e= i7)\n throw new Error(\"PostProcessingSolver: bounds must have finite positive extents\");\n const r7 = new Set(e53.differentialPairs.flatMap((e54) =\u003e e54.connectionNames));\n for (const t8 of e53.hdRoutes) {\n if (!t8 || typeof t8 != \"object\" || typeof t8.connectionName != \"string\" || t8.connectionName.length === 0 || t8.rootConnectionName !== undefined \u0026\u0026 (typeof t8.rootConnectionName != \"string\" || t8.rootConnectionName.length === 0) || !Number.isFinite(t8.traceThickness) || t8.traceThickness \u003c= 0 || !Number.isFinite(t8.viaDiameter) || t8.viaDiameter \u003c 0 || t8.viaDiameter === 0 \u0026\u0026 r7.has(t8.connectionName) || !Array.isArray(t8.route) || !Array.isArray(t8.vias) || t8.jumpers !== undefined \u0026\u0026 !Array.isArray(t8.jumpers))\n throw new Error(\"PostProcessingSolver: HD route declaration is invalid\");\n if (t8.startPcbPortId !== undefined \u0026\u0026 (typeof t8.startPcbPortId != \"string\" || t8.startPcbPortId.length === 0) || t8.endPcbPortId !== undefined \u0026\u0026 (typeof t8.endPcbPortId != \"string\" || t8.endPcbPortId.length === 0))\n throw new Error(`PostProcessingSolver: HD route \"${t8.connectionName}\" has invalid terminal metadata`);\n for (const n10 of t8.route)\n if (!n10 || typeof n10 != \"object\" || !Number.isFinite(n10.x) || !Number.isFinite(n10.y) || !Number.isInteger(n10.z) || n10.z \u003c 0 || n10.z \u003e= e53.layerCount || n10.traceThickness !== undefined \u0026\u0026 (!Number.isFinite(n10.traceThickness) || n10.traceThickness \u003c= 0))\n throw new Error(`PostProcessingSolver: HD route \"${t8.connectionName}\" has an invalid route point`);\n for (const n10 of t8.vias)\n if (!n10 || typeof n10 != \"object\" || !Number.isFinite(n10.x) || !Number.isFinite(n10.y) || n10.zLayers !== undefined \u0026\u0026 (!Array.isArray(n10.zLayers) || n10.zLayers.some((t10) =\u003e !Number.isInteger(t10) || t10 \u003c 0 || t10 \u003e= e53.layerCount)))\n throw new Error(`PostProcessingSolver: HD route \"${t8.connectionName}\" has an invalid via`);\n if (t8.vias.length \u003e 0 \u0026\u0026 t8.viaDiameter \u003c= 0)\n throw new Error(`PostProcessingSolver: HD route \"${t8.connectionName}\" has a non-positive via diameter`);\n for (const e54 of t8.jumpers ?? [])\n if (!(e54 \u0026\u0026 typeof e54 == \"object\" \u0026\u0026 e54.route_type === \"jumper\" \u0026\u0026 Number.isFinite(e54.start?.x) \u0026\u0026 Number.isFinite(e54.start?.y) \u0026\u0026 Number.isFinite(e54.end?.x) \u0026\u0026 Number.isFinite(e54.end?.y) \u0026\u0026 [\"0603\", \"1206\", \"1206x4_pair\"].includes(e54.footprint)))\n throw new Error(`PostProcessingSolver: HD route \"${t8.connectionName}\" has an invalid jumper`);\n }\n const s7 = new Set;\n for (const t8 of e53.differentialPairs) {\n if (!t8 || typeof t8 != \"object\" || !Array.isArray(t8.connectionNames) || t8.connectionNames.length !== 2 || t8.connectionNames[0] === t8.connectionNames[1] || !t8.connectionNames.every((e54) =\u003e typeof e54 == \"string\" \u0026\u0026 e54.length \u003e 0) || !Number.isFinite(t8.lengthTolerance) || t8.lengthTolerance \u003c 0)\n throw new Error(\"PostProcessingSolver: differential pair declaration is invalid\");\n for (const e54 of [t8.minimumCenterlineDistance, t8.maximumCenterlineDistance])\n if (e54 !== undefined \u0026\u0026 (!Number.isFinite(e54) || e54 \u003c= 0))\n throw new Error(\"PostProcessingSolver: differential pair centerline distances must be positive finite numbers\");\n if (t8.maxUncoupledLength !== undefined \u0026\u0026 (!Number.isFinite(t8.maxUncoupledLength) || t8.maxUncoupledLength \u003c 0))\n throw new Error(\"PostProcessingSolver: differential pair maxUncoupledLength must be a non-negative finite number\");\n if (t8.minimumCenterlineDistance !== undefined \u0026\u0026 t8.maximumCenterlineDistance !== undefined \u0026\u0026 t8.minimumCenterlineDistance \u003e t8.maximumCenterlineDistance)\n throw new Error(\"PostProcessingSolver: differential pair minimumCenterlineDistance cannot exceed maximumCenterlineDistance\");\n for (const e54 of t8.connectionNames) {\n if (s7.has(e54))\n throw new Error(`PostProcessingSolver: connection \"${e54}\" belongs to multiple differential pairs`);\n s7.add(e54);\n }\n }\n for (const t8 of [0.25, 0.5])\n Y6({ config: e53.routingGrid, bounds: e53.bounds, defaultInnerGridStep: t8 });\n })(e51);\n } catch (e53) {\n if (!(e53 instanceof A6))\n throw e53;\n t4 = e53;\n }\n if (this.model = N6(e51), t4)\n return void this.finishWithBestEffortOutput({ stage: \"differentialPairReroutingSolver\", message: t4.message, reason: t4.reason });\n const n7 = O6(this.model.params) + Math.max(1, e51.differentialPairs.length + 1) + 1e5 + 10;\n if (!Number.isSafeInteger(n7))\n throw new Error(\"PostProcessingSolver: derived pipeline iteration bound exceeds the safe integer range\");\n this.MAX_ITERATIONS = n7;\n }\n getSolverName() {\n return \"PostProcessingSolver\";\n }\n getConstructorParams() {\n return [structuredClone(this.inputProblem)];\n }\n _step() {\n const e51 = this.getCurrentStageName();\n try {\n super._step();\n } catch (t7) {\n const n7 = this.classifyOptimizationFailure(t7, e51);\n if (!n7)\n throw t7;\n return void this.finishWithBestEffortOutput(n7);\n }\n if (!this.failed)\n return;\n const t4 = this.classifyIterationFailure(this.error, e51);\n if (!t4)\n throw new Error(this.error ?? \"PostProcessingSolver failed without an error message\");\n this.finishWithBestEffortOutput(t4);\n }\n tryFinalAcceptance() {\n const e51 = this.getCurrentStageName();\n e51 !== \"differentialPairReroutingSolver\" \u0026\u0026 e51 !== \"lengthMatchingSolver\" || this.finishWithBestEffortOutput({ stage: e51, message: \"PostProcessingSolver reached its iteration limit\", reason: \"iteration-limit-exhausted\" });\n }\n classifyOptimizationFailure(e51, t4) {\n return t4 === \"lengthMatchingSolver\" \u0026\u0026 e51 instanceof m6 ? { stage: t4, message: e51.message, connectionName: e51.connectionName, reason: e51.reason } : t4 === \"hdRouteReconstructionSolver\" \u0026\u0026 e51 instanceof E6 || t4 === \"differentialPairReroutingSolver\" \u0026\u0026 e51 instanceof T6 \u0026\u0026 e51.reason === \"no-valid-candidate\" ? { stage: t4, message: e51.message, connectionNames: [...e51.connectionNames], reason: e51.reason } : null;\n }\n classifyIterationFailure(e51, t4) {\n return t4 !== \"differentialPairReroutingSolver\" \u0026\u0026 t4 !== \"lengthMatchingSolver\" ? null : e51 \u0026\u0026 e51.endsWith(\"ran out of iterations\") ? { stage: t4, message: e51, reason: \"iteration-limit-exhausted\" } : null;\n }\n createBestEffortOutput(e51) {\n let t4 = this.lengthMatchingBinding;\n if (!t4) {\n const e53 = this.getStageOutput(\"fortyFiveDegreeSimplificationSolver\") ?? this.fortyFiveDegreeSimplificationSolver?.getBestEffortOutput(), n8 = this.getStageOutput(\"differentialPairReroutingSolver\") ?? this.differentialPairReroutingSolver?.getBestEffortOutput(), o7 = e53 ?? n8;\n o7 \u0026\u0026 (t4 = w6({ result: o7, params: this.model.params }));\n }\n if (!t4)\n return { output: { hdRoutes: structuredClone(this.inputProblem.hdRoutes), postProcessingErrors: [] }, source: \"input-hd-routes\" };\n let n7 = this.getStageOutput(\"lengthMatchingSolver\");\n return n7 || (n7 = this.lengthMatchingSolver?.getBestEffortOutput()), n7 \u0026\u0026 e51.reason !== \"invalid-final-copper\" || (n7 = { matchedHdRoutes: t4.solverParams.hdRoutes }), { output: R6({ binding: t4, result: n7, model: this.model }), source: \"best-effort-hd-routes\" };\n }\n finishWithBestEffortOutput(e51) {\n const t4 = this.createBestEffortOutput(e51), n7 = { type: \"post_processing_error\", ...e51, returnedRouteSource: t4.source };\n this.postProcessingErrors.push(n7), this.fallbackOutput = t4.output, this.activeSubSolver = null, this.error = null, this.failed = false, this.solved = true, this.progress = 1, this.stats = { phase: \"complete\", postProcessingErrorCount: this.postProcessingErrors.length };\n }\n getOutput() {\n if (!this.solved)\n throw new Error(\"PostProcessingSolver: getOutput() called before the solver completed\");\n const e51 = this.fallbackOutput ?? this.getStageOutput(\"hdRouteReconstructionSolver\");\n if (!e51)\n throw new Error(\"PostProcessingSolver: completed pipeline is missing reconstruction output\");\n const t4 = this.getStageOutput(\"differentialPairReroutingSolver\") ?? this.differentialPairReroutingSolver?.getBestEffortOutput(), n7 = t4?.failures ?? [];\n let o7 = \"input-hd-routes\";\n (t4?.reroutedPairs.length ?? 0) \u003e 0 \u0026\u0026 (o7 = \"best-effort-hd-routes\");\n const i7 = [...n7.map((e53) =\u003e ({ type: \"post_processing_error\", stage: \"differentialPairReroutingSolver\", message: e53.message, connectionNames: [...e53.connectionNames], reason: e53.reason, returnedRouteSource: o7 })), ...this.postProcessingErrors], r7 = structuredClone(e51);\n return r7.postProcessingErrors = structuredClone(i7), r7;\n }\n initialVisualize() {\n if (this.fallbackOutput)\n return { lines: this.fallbackOutput.hdRoutes.map((e53) =\u003e ({ points: e53.route.map(({ x: e54, y: t7 }) =\u003e ({ x: e54, y: t7 })), strokeWidth: e53.traceThickness })) };\n const { traces: e51, obstacles: t4, bounds: n7, layerCount: o7 } = this.model.params.simpleRouteJson;\n return G6({ traces: structuredClone(e51), obstacles: t4, bounds: n7, layerCount: o7, activeConnectionNames: null, previewPath: null });\n }\n finalVisualize() {\n if (this.fallbackOutput)\n return this.initialVisualize();\n const e51 = N6({ ...this.inputProblem, hdRoutes: this.getOutput().hdRoutes }), { traces: t4, obstacles: n7, bounds: o7, layerCount: i7 } = e51.params.simpleRouteJson;\n return G6({ traces: t4, obstacles: n7, bounds: o7, layerCount: i7, activeConnectionNames: null, previewPath: null });\n }\n};\nvar l9 = class e51 {\n static generators = new Map;\n static register(t4) {\n e51.generators.set(t4.componentKind, t4);\n }\n static create(t4) {\n const n7 = t4.detectedComponent.componentKind, o7 = e51.generators.get(n7);\n if (!o7)\n throw new Error(`No topology generator registered for component kind \"${n7}\"`);\n return new o7(t4);\n }\n};\nvar g9 = (e53) =\u003e [e53.obstacle.obstacleId ?? e53.obstacle.componentId ?? \"obstacle\", e53.start.x.toFixed(4), e53.start.y.toFixed(4), e53.end.x.toFixed(4), e53.end.y.toFixed(4), e53.expansionDirection.x, e53.expansionDirection.y].join(\":\");\nvar f9 = (e53) =\u003e {\n let t4 = 0;\n for (const n7 of e53)\n t4 = 31 * t4 + n7.charCodeAt(0) \u003e\u003e\u003e 0;\n return t4;\n};\nvar _9 = (e53, t4) =\u003e `hsla(${f9(g9(e53)) % 360},72%,36%,${t4})`;\nvar y9 = (e53) =\u003e {\n const t4 = e53.expansionDirection;\n return t4.x \u003c 0 ? \"left\" : t4.x \u003e 0 ? \"right\" : t4.y \u003c 0 ? \"bottom\" : \"top\";\n};\nvar b9 = (e53) =\u003e ({ x: (e53.start.x + e53.end.x) / 2, y: (e53.start.y + e53.end.y) / 2 });\nvar x9 = (e53) =\u003e {\n const t4 = /^bga-gapfill-(\\d+)-/.exec(e53.capacityMeshNodeId);\n return t4 ? Number.parseInt(t4[1], 10) : null;\n};\nvar v9 = (e53, t4) =\u003e {\n const n7 = b9(e53), o7 = b9(t4), i7 = n7.y - o7.y;\n if (Math.abs(i7) \u003e 0.000001)\n return i7;\n const r7 = n7.x - o7.x;\n return Math.abs(r7) \u003e 0.000001 ? r7 : g9(e53).localeCompare(g9(t4));\n};\nvar I9 = (e53) =\u003e {\n const t4 = [...e53].sort(v9), n7 = [];\n let o7 = t4.shift();\n for (;o7 \u0026\u0026 (n7.push(o7), t4.length !== 0); ) {\n const e54 = b9(o7);\n let n8 = 0, i7 = Number.POSITIVE_INFINITY;\n for (let o8 = 0;o8 \u003c t4.length; o8++) {\n const r7 = t4[o8], s7 = b9(r7), a7 = (s7.x - e54.x) ** 2 + (s7.y - e54.y) ** 2;\n a7 \u003c i7 - 0.000000001 ? (i7 = a7, n8 = o8) : Math.abs(a7 - i7) \u003c= 0.000000001 \u0026\u0026 v9(r7, t4[n8]) \u003c 0 \u0026\u0026 (n8 = o8);\n }\n o7 = t4.splice(n8, 1)[0];\n }\n return n7;\n};\nvar S9 = (e53, t4) =\u003e {\n const n7 = g9(e53), o7 = t4.findIndex((e54) =\u003e g9(e54) === n7);\n return o7 \u003e= 0 ? `E${o7 + 1}` : `E${f9(n7).toString(36).slice(0, 4)}`;\n};\nvar C9 = (e53) =\u003e e53.flatMap((e54) =\u003e {\n const t4 = Le(e54);\n return [{ obstacle: e54, start: { x: t4.minX, y: t4.minY }, end: { x: t4.minX, y: t4.maxY }, expansionDirection: { x: -1, y: 0 } }, { obstacle: e54, start: { x: t4.maxX, y: t4.minY }, end: { x: t4.maxX, y: t4.maxY }, expansionDirection: { x: 1, y: 0 } }, { obstacle: e54, start: { x: t4.minX, y: t4.minY }, end: { x: t4.maxX, y: t4.minY }, expansionDirection: { x: 0, y: -1 } }, { obstacle: e54, start: { x: t4.minX, y: t4.maxY }, end: { x: t4.maxX, y: t4.maxY }, expansionDirection: { x: 0, y: 1 } }];\n});\nvar P9 = 0.001;\nvar M9 = 0.001;\nvar w9 = class extends BaseSolver {\n constructor(e53) {\n super(), this.inputProblem = e53;\n }\n meshIndex;\n allEdges = [];\n queueEdges = [];\n disconnectedEdges = [];\n currentEdge = null;\n lastSearchBounds = null;\n lastCandidateMeshNodes = [];\n lastMatchedMeshNode = null;\n _setup() {\n const e53 = Math.max(this.inputProblem.meshNodes.length, 1);\n this.meshIndex = new E2(e53);\n for (const e54 of this.inputProblem.meshNodes) {\n const t7 = Le(e54);\n this.meshIndex.add(t7.minX, t7.minY, t7.maxX, t7.maxY);\n }\n this.meshIndex.finish();\n const t4 = C9(this.inputProblem.unmarkedComponentObstacles);\n this.queueEdges = t4, this.allEdges = I9(t4), this.currentEdge = null, this.lastSearchBounds = null, this.lastCandidateMeshNodes = [], this.lastMatchedMeshNode = null;\n }\n _step() {\n const e53 = this.queueEdges.shift();\n if (!e53)\n return this.currentEdge = null, this.lastSearchBounds = null, this.lastCandidateMeshNodes = [], this.lastMatchedMeshNode = null, void (this.solved = true);\n this.currentEdge = e53, this.lastMatchedMeshNode = null;\n const t4 = Math.abs(e53.start.x - e53.end.x) \u003c= P9, n7 = t4 ? { minX: e53.start.x - M9, maxX: e53.start.x + M9, minY: Math.min(e53.start.y, e53.end.y), maxY: Math.max(e53.start.y, e53.end.y) } : { minX: Math.min(e53.start.x, e53.end.x), maxX: Math.max(e53.start.x, e53.end.x), minY: e53.start.y - M9, maxY: e53.start.y + M9 };\n this.lastSearchBounds = n7;\n const o7 = this.meshIndex.search(n7.minX, n7.minY, n7.maxX, n7.maxY);\n this.lastCandidateMeshNodes = o7.map((e54) =\u003e this.inputProblem.meshNodes[e54]);\n let i7 = false;\n for (const n8 of o7) {\n const o8 = this.inputProblem.meshNodes[n8], r7 = Le(o8);\n if (t4) {\n if (!(Math.min(r7.maxY, Math.max(e53.start.y, e53.end.y)) - Math.max(r7.minY, Math.min(e53.start.y, e53.end.y)) \u003e P9))\n continue;\n if (e53.expansionDirection.x === -1 \u0026\u0026 Math.abs(r7.maxX - e53.start.x) \u003c= P9) {\n i7 = true, this.lastMatchedMeshNode = o8;\n break;\n }\n if (e53.expansionDirection.x === 1 \u0026\u0026 Math.abs(r7.minX - e53.start.x) \u003c= P9) {\n i7 = true, this.lastMatchedMeshNode = o8;\n break;\n }\n continue;\n }\n if (Math.min(r7.maxX, Math.max(e53.start.x, e53.end.x)) - Math.max(r7.minX, Math.min(e53.start.x, e53.end.x)) \u003e P9) {\n if (e53.expansionDirection.y === -1 \u0026\u0026 Math.abs(r7.maxY - e53.start.y) \u003c= P9) {\n i7 = true, this.lastMatchedMeshNode = o8;\n break;\n }\n if (e53.expansionDirection.y === 1 \u0026\u0026 Math.abs(r7.minY - e53.start.y) \u003c= P9) {\n i7 = true, this.lastMatchedMeshNode = o8;\n break;\n }\n }\n }\n i7 || this.disconnectedEdges.push(e53);\n }\n getOutput() {\n return this.disconnectedEdges;\n }\n visualize() {\n const e53 = this.disconnectedEdges, t4 = this.allEdges.length \u003e 0 ? this.allEdges : [...e53, ...this.currentEdge ? [this.currentEdge] : []], n7 = this.currentEdge ? _9(this.currentEdge, 0.88) : \"rgba(40,40,40,0.4)\", o7 = this.inputProblem.meshNodes.map((e54) =\u003e ({ ...dj(e54, { rectMargin: 0.01 }), fill: e54._containsObstacle ? \"rgba(120,120,120,0.18)\" : \"rgba(120,120,120,0.08)\", stroke: e54._containsObstacle ? \"rgba(120,120,120,0.42)\" : \"rgba(120,120,120,0.24)\" })), i7 = this.lastSearchBounds \u0026\u0026 this.currentEdge ? [{ center: (r7 = this.lastSearchBounds, { x: (r7.minX + r7.maxX) / 2, y: (r7.minY + r7.maxY) / 2 }), width: this.lastSearchBounds.maxX - this.lastSearchBounds.minX, height: this.lastSearchBounds.maxY - this.lastSearchBounds.minY, fill: _9(this.currentEdge, 0.1), stroke: _9(this.currentEdge, 0.36), label: [S9(this.currentEdge, t4), \"search band\"].join(\" \") }] : [];\n var r7;\n const s7 = this.lastCandidateMeshNodes.map((e54) =\u003e ({ ...dj(e54, { rectMargin: 0.018 }), fill: e54 === this.lastMatchedMeshNode ? \"rgba(0,180,90,0.24)\" : this.currentEdge ? _9(this.currentEdge, 0.16) : \"rgba(80,120,160,0.16)\", stroke: e54 === this.lastMatchedMeshNode ? \"rgba(0,150,80,0.88)\" : n7, label: [e54 === this.lastMatchedMeshNode ? \"matched\" : \"candidate\", e54.capacityMeshNodeId, `z:${e54.availableZ.join(\",\")}`].join(`\n`) })), a7 = this.inputProblem.unmarkedComponentObstacles.map((e54) =\u003e ({ center: e54.center, width: e54.width, height: e54.height, fill: \"rgba(160,160,160,0.10)\", stroke: \"rgba(160,160,160,0.40)\", label: e54.obstacleId ?? e54.componentId ?? \"obstacle\" })), c5 = e53.map((e54) =\u003e ({ points: [e54.start, e54.end], strokeColor: _9(e54, 0.14), strokeWidth: 0.01, strokeDash: \"5 4\", label: [S9(e54, t4), y9(e54), \"disconnected\"].join(\" \") })), l5 = [], h5 = [];\n if (this.currentEdge) {\n const e54 = b9(this.currentEdge);\n l5.push({ points: [this.currentEdge.start, this.currentEdge.end], strokeColor: _9(this.currentEdge, 1), strokeWidth: 0.06, label: [S9(this.currentEdge, t4), y9(this.currentEdge), \"checking\"].join(\" \") }, { points: [e54, { x: e54.x + 0.16 * this.currentEdge.expansionDirection.x, y: e54.y + 0.16 * this.currentEdge.expansionDirection.y }], strokeColor: _9(this.currentEdge, 0.82), strokeWidth: 0.02, strokeDash: \"3 3\" }), h5.push({ ...e54, color: _9(this.currentEdge, 1), label: S9(this.currentEdge, t4) });\n }\n return { rects: [...o7, ...i7, ...s7, ...a7], lines: [...c5, ...l5], points: h5 };\n }\n};\nvar R9 = 0.001;\nvar T9 = 0.001;\nvar E9 = 0.000001;\nvar A9 = class extends BaseSolver {\n constructor(e53) {\n super(), this.inputProblem = e53;\n }\n meshIndex;\n meshBounds;\n expandedNodes = [];\n _setup() {\n const e53 = Math.max(this.inputProblem.meshNodes.length, 1);\n this.meshIndex = new E2(e53);\n let { POSITIVE_INFINITY: t4, NEGATIVE_INFINITY: n7, POSITIVE_INFINITY: o7, NEGATIVE_INFINITY: i7 } = Number;\n for (const e54 of this.inputProblem.meshNodes) {\n const r7 = Le(e54);\n this.meshIndex.add(r7.minX, r7.minY, r7.maxX, r7.maxY), t4 = Math.min(t4, r7.minX), n7 = Math.max(n7, r7.maxX), o7 = Math.min(o7, r7.minY), i7 = Math.max(i7, r7.maxY);\n }\n this.meshIndex.finish(), this.meshBounds = this.inputProblem.meshNodes.length ? { minX: t4, maxX: n7, minY: o7, maxY: i7 } : { minX: 0, maxX: 0, minY: 0, maxY: 0 };\n }\n getObstacleAvailableZ(e53) {\n return e53.__zLayers ?? e53.layers.map((e54) =\u003e mo(e54, this.inputProblem.layerCount));\n }\n getSharedOverlapArea(e53, t4) {\n if (!e53.availableZ.some((e54) =\u003e t4.availableZ.includes(e54)))\n return 0;\n const n7 = Le(e53), o7 = Le(t4), i7 = Math.min(n7.maxX, o7.maxX) - Math.max(n7.minX, o7.minX), r7 = Math.min(n7.maxY, o7.maxY) - Math.max(n7.minY, o7.minY);\n return i7 \u003c= E9 || r7 \u003c= E9 ? 0 : i7 * r7;\n }\n getNodeObstacleOverlapArea(e53, t4) {\n const n7 = this.getObstacleAvailableZ(t4);\n if (!e53.availableZ.some((e54) =\u003e n7.includes(e54)))\n return 0;\n const o7 = Le(e53), i7 = Le(t4), r7 = Math.min(o7.maxX, i7.maxX) - Math.max(o7.minX, i7.minX), s7 = Math.min(o7.maxY, i7.maxY) - Math.max(o7.minY, i7.minY);\n return r7 \u003c= E9 || s7 \u003c= E9 ? 0 : r7 * s7;\n }\n getClosestMeshNode(e53, t4) {\n const n7 = Math.abs(e53.start.x - e53.end.x) \u003c= R9, o7 = this.getObstacleAvailableZ(e53.obstacle), i7 = n7 ? e53.expansionDirection.x \u003c 0 ? { minX: this.meshBounds.minX, maxX: e53.start.x, minY: Math.min(e53.start.y, e53.end.y) - T9, maxY: Math.max(e53.start.y, e53.end.y) + T9 } : { minX: e53.start.x, maxX: this.meshBounds.maxX, minY: Math.min(e53.start.y, e53.end.y) - T9, maxY: Math.max(e53.start.y, e53.end.y) + T9 } : e53.expansionDirection.y \u003c 0 ? { minX: Math.min(e53.start.x, e53.end.x) - T9, maxX: Math.max(e53.start.x, e53.end.x) + T9, minY: this.meshBounds.minY, maxY: e53.start.y } : { minX: Math.min(e53.start.x, e53.end.x) - T9, maxX: Math.max(e53.start.x, e53.end.x) + T9, minY: e53.start.y, maxY: this.meshBounds.maxY }, r7 = this.meshIndex.search(i7.minX, i7.minY, i7.maxX, i7.maxY);\n let s7 = null, a7 = Number.POSITIVE_INFINITY;\n const c5 = [...r7.map((e54) =\u003e this.inputProblem.meshNodes[e54]), ...t4];\n for (const t7 of c5) {\n if (t7._containsObstacle)\n continue;\n if (!t7.availableZ.some((e54) =\u003e o7.includes(e54)))\n continue;\n const i8 = Le(t7);\n if ((n7 ? Math.min(Math.max(e53.start.y, e53.end.y), i8.maxY) - Math.max(Math.min(e53.start.y, e53.end.y), i8.minY) : Math.min(Math.max(e53.start.x, e53.end.x), i8.maxX) - Math.max(Math.min(e53.start.x, e53.end.x), i8.minX)) \u003c= R9)\n continue;\n const r8 = n7 ? e53.expansionDirection.x \u003c 0 ? e53.start.x - i8.maxX : i8.minX - e53.start.x : e53.expansionDirection.y \u003c 0 ? e53.start.y - i8.maxY : i8.minY - e53.start.y;\n r8 \u003c R9 || (r8 \u003e= a7 || (a7 = r8, s7 = t7));\n }\n return s7;\n }\n createExpandedNode(e53, t4, n7) {\n const o7 = Le(t4), i7 = this.getObstacleAvailableZ(e53.obstacle);\n if (Math.abs(e53.start.x - e53.end.x) \u003c= R9) {\n const r8 = Math.max(Math.min(e53.start.y, e53.end.y), o7.minY), s8 = Math.min(Math.max(e53.start.y, e53.end.y), o7.maxY), a8 = e53.expansionDirection.x \u003c 0 ? o7.maxX : e53.start.x, c7 = e53.expansionDirection.x \u003c 0 ? e53.start.x : o7.minX;\n return c7 - a8 \u003c= R9 || s8 - r8 \u003c= R9 ? null : { capacityMeshNodeId: `bga-gapfill-${n7}-${e53.obstacle.obstacleId ?? \"no-obstacle\"}-${t4.capacityMeshNodeId}`, center: { x: (a8 + c7) / 2, y: (r8 + s8) / 2 }, width: c7 - a8, height: s8 - r8, layer: `z${i7.join(\",\")}`, availableZ: i7 };\n }\n const r7 = Math.max(Math.min(e53.start.x, e53.end.x), o7.minX), s7 = Math.min(Math.max(e53.start.x, e53.end.x), o7.maxX), a7 = e53.expansionDirection.y \u003c 0 ? o7.maxY : e53.start.y, c5 = e53.expansionDirection.y \u003c 0 ? e53.start.y : o7.minY;\n return s7 - r7 \u003c= R9 || c5 - a7 \u003c= R9 ? null : { capacityMeshNodeId: `bga-gapfill-${n7}-${e53.obstacle.obstacleId ?? \"no-obstacle\"}-${t4.capacityMeshNodeId}`, center: { x: (r7 + s7) / 2, y: (a7 + c5) / 2 }, width: s7 - r7, height: c5 - a7, layer: `z${i7.join(\",\")}`, availableZ: i7 };\n }\n overlapsExistingGeometry(e53, t4) {\n for (const t7 of this.inputProblem.meshNodes)\n if (this.getSharedOverlapArea(e53, t7) \u003e 0)\n return true;\n for (const n7 of t4)\n if (this.getSharedOverlapArea(e53, n7) \u003e 0)\n return true;\n for (const t7 of this.inputProblem.edgesWithObstacle)\n if (this.getNodeObstacleOverlapArea(e53, t7.obstacle) \u003e 0)\n return true;\n return false;\n }\n _step() {\n const e53 = [];\n for (const [t4, n7] of this.inputProblem.edgesWithObstacle.entries()) {\n const o7 = this.getClosestMeshNode(n7, e53);\n if (!o7)\n continue;\n const i7 = this.createExpandedNode(n7, o7, t4);\n i7 \u0026\u0026 (this.overlapsExistingGeometry(i7, e53) || e53.push(i7));\n }\n this.expandedNodes = e53, this.solved = true;\n }\n getOutput() {\n return this.expandedNodes;\n }\n visualize() {\n const e53 = this.inputProblem.edgesWithObstacle, t4 = I9(e53);\n return { rects: [...this.inputProblem.meshNodes.map((e54) =\u003e ({ ...dj(e54, { rectMargin: 0.01 }), fill: e54._containsObstacle ? \"rgba(255,0,0,0.16)\" : \"rgba(0,120,255,0.08)\", stroke: e54._containsObstacle ? \"rgba(255,0,0,0.35)\" : \"rgba(0,120,255,0.28)\" })), ...this.expandedNodes.map((n7) =\u003e {\n const o7 = x9(n7), i7 = o7 === null ? null : e53[o7] ?? null;\n return { ...dj(n7, { rectMargin: 0.012, zOffset: 0.01 }), fill: i7 ? _9(i7, 0.24) : \"rgba(0,160,100,0.24)\", stroke: i7 ? _9(i7, 0.72) : \"rgba(0,160,100,0.68)\", label: [i7 ? S9(i7, t4) : \"E?\", \"expanded\", n7.capacityMeshNodeId, `z:${n7.availableZ.join(\",\")}`].join(`\n`) };\n })], lines: [...this.inputProblem.edgesWithObstacle.map((e54) =\u003e ({ points: [e54.start, e54.end], strokeColor: _9(e54, 0.9), strokeWidth: 0.034, label: [S9(e54, t4), y9(e54)].join(\" \") })), ...this.inputProblem.edgesWithObstacle.map((e54) =\u003e {\n const t7 = b9(e54);\n return { points: [t7, { x: t7.x + 0.16 * e54.expansionDirection.x, y: t7.y + 0.16 * e54.expansionDirection.y }], strokeColor: _9(e54, 0.7), strokeWidth: 0.016, strokeDash: \"3 3\" };\n })], points: this.inputProblem.edgesWithObstacle.map((e54) =\u003e ({ ...b9(e54), color: _9(e54, 0.95), label: S9(e54, t4) })) };\n }\n};\nvar O9 = 0.001;\nvar k9 = class extends BasePipelineSolver {\n constructor(e53) {\n super(e53), this.inputProblem = e53;\n }\n detectEdgesNotConnectedToMesh;\n expandUnconnectedEdgesToMesh;\n pipelineDef = [definePipelineStep(\"detectEdgesNotConnectedToMesh\", w9, (e53) =\u003e [e53.inputProblem]), definePipelineStep(\"expandUnconnectedEdgesToMesh\", A9, (e53) =\u003e [{ meshNodes: e53.inputProblem.meshNodes, edgesWithObstacle: e53.detectEdgesNotConnectedToMesh.getOutput(), layerCount: e53.inputProblem.layerCount }])];\n getOutput() {\n return [...this.inputProblem.meshNodes, ...this.expandUnconnectedEdgesToMesh.getOutput()];\n }\n getExpandedNodes() {\n return this.expandUnconnectedEdgesToMesh.getOutput();\n }\n getObstacleLayer(e53) {\n return `z${(e53.obstacle.__zLayers ?? e53.obstacle.layers.map((e54) =\u003e mo(e54, this.inputProblem.layerCount))).join(\",\")}`;\n }\n getObstacleRects() {\n return this.inputProblem.unmarkedComponentObstacles.map((e53) =\u003e {\n const t4 = e53.__zLayers ?? e53.layers.map((e54) =\u003e mo(e54, this.inputProblem.layerCount));\n return { center: e53.center, width: e53.width, height: e53.height, fill: \"rgba(150,150,150,0.08)\", stroke: \"rgba(90,90,90,0.42)\", label: e53.obstacleId ?? e53.componentId ?? \"bga obstacle\", layer: `z${t4.join(\",\")}` };\n });\n }\n getBaseMeshRects() {\n return this.inputProblem.meshNodes.map((e53) =\u003e ({ ...dj(e53, { rectMargin: 0.025, zOffset: 0.01 }), fill: e53._containsObstacle ? \"rgba(210,60,60,0.14)\" : \"rgba(80,120,160,0.08)\", stroke: e53._containsObstacle ? \"rgba(190,40,40,0.42)\" : \"rgba(80,120,160,0.28)\", label: `mesh ${e53.capacityMeshNodeId}\nz:${e53.availableZ.join(\",\")}` }));\n }\n initialVisualize() {\n const e53 = C9(this.inputProblem.unmarkedComponentObstacles), t4 = I9(e53), n7 = [...e53.map((e54) =\u003e ({ points: [e54.start, e54.end], strokeColor: _9(e54, 0.72), strokeWidth: 0.018, strokeDash: \"0.05 0.035\", layer: this.getObstacleLayer(e54), label: [S9(e54, t4), y9(e54)].join(\" \") })), ...e53.map((e54) =\u003e {\n const t7 = b9(e54);\n return { points: [t7, { x: t7.x + 0.18 * e54.expansionDirection.x, y: t7.y + 0.18 * e54.expansionDirection.y }], strokeColor: _9(e54, 0.64), strokeWidth: 0.012, strokeDash: \"0.035 0.025\", layer: this.getObstacleLayer(e54) };\n })];\n return { title: \"BGA GapFill: candidate obstacle edges\", rects: [...this.getBaseMeshRects(), ...this.getObstacleRects()], lines: n7 };\n }\n finalVisualize() {\n const e53 = this.getStageOutput(\"detectEdgesNotConnectedToMesh\") ?? [], t4 = this.getStageOutput(\"expandUnconnectedEdgesToMesh\") ?? [], n7 = I9(C9(this.inputProblem.unmarkedComponentObstacles)), o7 = new Map;\n for (const e54 of t4) {\n const t7 = x9(e54);\n t7 !== null \u0026\u0026 o7.set(t7, e54);\n }\n const i7 = t4.map((t7) =\u003e {\n const o8 = x9(t7), i8 = o8 === null ? null : e53[o8] ?? null, r8 = i8 ? (({ expandedNode: e54, edge: t8, meshNodes: n8 }) =\u003e {\n const o10 = Le(e54), i9 = Math.abs(t8.start.x - t8.end.x) \u003c= O9;\n return n8.filter((n10) =\u003e {\n if (n10._containsObstacle)\n return false;\n if (!e54.availableZ.some((e55) =\u003e n10.availableZ.includes(e55)))\n return false;\n const r9 = Le(n10);\n return i9 ? !(Math.min(o10.maxY, r9.maxY) - Math.max(o10.minY, r9.minY) \u003c= O9) \u0026\u0026 (t8.expansionDirection.x \u003c 0 ? Math.abs(r9.maxX - o10.minX) \u003c= O9 : Math.abs(r9.minX - o10.maxX) \u003c= O9) : !(Math.min(o10.maxX, r9.maxX) - Math.max(o10.minX, r9.minX) \u003c= O9) \u0026\u0026 (t8.expansionDirection.y \u003c 0 ? Math.abs(r9.maxY - o10.minY) \u003c= O9 : Math.abs(r9.minY - o10.maxY) \u003c= O9);\n }).map((e55) =\u003e e55.capacityMeshNodeId);\n })({ expandedNode: t7, edge: i8, meshNodes: this.inputProblem.meshNodes }) : [], s8 = i8 ? S9(i8, n7) : \"E?\", a8 = i8 === null ? \"rgba(0,160,100,0.72)\" : _9(i8, 0.72);\n return { ...dj(t7, { rectMargin: 0.012, zOffset: 0.01 }), fill: i8 === null ? \"rgba(0,160,100,0.24)\" : _9(i8, 0.16), stroke: a8, label: [`${s8} gap fill`, r8.length \u003e 0 ? `to ${r8.join(\",\")}` : \"target mesh not adjacent\", `z:${t7.availableZ.join(\",\")}`].join(`\n`) };\n }), r7 = e53.map((e54, t7) =\u003e {\n const i8 = o7.get(t7);\n return { points: [e54.start, e54.end], strokeColor: i8 ? _9(e54, 0.68) : \"rgba(80,80,80,0.14)\", strokeWidth: i8 ? 0.026 : 0.008, ...i8 ? {} : { strokeDash: \"5 4\" }, layer: this.getObstacleLayer(e54), label: [[S9(e54, n7), y9(e54)].join(\" \"), i8 ? \"filled\" : \"no fill created\"].join(`\n`) };\n }), s7 = e53.flatMap((e54, t7) =\u003e {\n const n8 = b9(e54), i8 = o7.get(t7);\n return i8 ? [{ points: [n8, i8.center], strokeColor: _9(e54, 0.42), strokeWidth: 0.012, strokeDash: \"0.035 0.025\", layer: this.getObstacleLayer(e54) }] : [];\n }), a7 = e53.flatMap((e54, t7) =\u003e o7.has(t7) ? [{ ...b9(e54), color: _9(e54, 0.82), label: S9(e54, n7), layer: this.getObstacleLayer(e54) }] : []);\n return { title: \"BGA GapFill: disconnected edges and created mesh\", rects: [...this.getBaseMeshRects(), ...this.getObstacleRects(), ...i7], lines: [...r7, ...s7], points: a7 };\n }\n};\nfunction L9(e53, t4) {\n const n7 = [];\n for (let o7 = 0;o7 \u003c e53.length; o7++) {\n const i7 = e53[o7];\n n7.push(i7);\n const r7 = e53[o7 + 1];\n if (r7 === undefined)\n continue;\n const s7 = Math.round((r7 - i7) / t4);\n if (!(s7 \u003c= 1))\n for (let e54 = 1;e54 \u003c s7; e54++) {\n const t7 = e54 / s7;\n n7.push(Number((i7 + (r7 - i7) * t7).toFixed(6)));\n }\n }\n return n7;\n}\nvar z9 = 0.001;\nfunction B9(e53) {\n const t4 = [];\n for (let n8 = 1;n8 \u003c e53.length; n8++) {\n const o8 = e53[n8] - e53[n8 - 1];\n o8 \u003e z9 \u0026\u0026 t4.push(o8);\n }\n if (t4.length === 0)\n return null;\n const n7 = Math.min(...t4), o7 = t4.filter((e54) =\u003e e54 \u003c= 1.5 * n7).sort((e54, t7) =\u003e e54 - t7), i7 = Math.floor(o7.length / 2);\n return o7.length % 2 == 0 ? (o7[i7 - 1] + o7[i7]) / 2 : o7[i7];\n}\nfunction F9(e53) {\n return [...new Set(e53)].sort((e54, t4) =\u003e e54 - t4);\n}\nfunction j9(e53) {\n return Number(e53.toFixed(6));\n}\nvar $9 = class e53 {\n static fromObstacles(t4) {\n if (t4.length === 0)\n return null;\n const n7 = F9(t4.map((e54) =\u003e e54.center.x)), o7 = F9(t4.map((e54) =\u003e e54.center.y)), i7 = B9(n7), r7 = B9(o7);\n return i7 === null || r7 === null ? null : new e53({ obstacles: t4, xCoordinates: L9(n7, i7), yCoordinates: L9(o7, r7), pitchX: i7, pitchY: r7 });\n }\n xCoordinates;\n yCoordinates;\n pitchX;\n pitchY;\n originX;\n originY;\n rowCount;\n colCount;\n padWidth;\n padHeight;\n slots = new Map;\n constructor(e54) {\n this.xCoordinates = e54.xCoordinates, this.yCoordinates = e54.yCoordinates, this.pitchX = e54.pitchX, this.pitchY = e54.pitchY, this.originX = this.xCoordinates[0], this.originY = this.yCoordinates[0], this.colCount = this.xCoordinates.length, this.rowCount = this.yCoordinates.length, this.padWidth = e54.obstacles[0].width, this.padHeight = e54.obstacles[0].height;\n for (const t4 of e54.obstacles) {\n const e55 = this.getSlotForObstacle(t4);\n e55 \u0026\u0026 this.slots.set(this.getSlotKey(e55.row, e55.col), { ...e55, obstacle: t4 });\n }\n }\n getSlotKey(e54, t4) {\n return `${e54}:${t4}`;\n }\n getAxisIndex(e54, t4) {\n let n7 = -1, o7 = Number.POSITIVE_INFINITY;\n for (let i7 = 0;i7 \u003c e54.length; i7++) {\n const r7 = Math.abs(e54[i7] - t4);\n r7 \u003c o7 \u0026\u0026 (o7 = r7, n7 = i7);\n }\n return o7 \u003c= z9 ? n7 : null;\n }\n getAxisCoordinate(e54, t4) {\n return e54[t4];\n }\n hasPadAt(e54, t4) {\n return this.slots.has(this.getSlotKey(e54, t4));\n }\n getSlotForObstacle(e54) {\n const t4 = this.getAxisIndex(this.yCoordinates, e54.center.y), n7 = this.getAxisIndex(this.xCoordinates, e54.center.x);\n return t4 === null || n7 === null || t4 \u003c 0 || t4 \u003e= this.rowCount || n7 \u003c 0 || n7 \u003e= this.colCount ? null : { row: t4, col: n7 };\n }\n getSlotCenter(e54, t4) {\n return { x: this.getAxisCoordinate(this.xCoordinates, t4), y: this.getAxisCoordinate(this.yCoordinates, e54) };\n }\n getHorizontalGap(e54, t4) {\n const n7 = this.getSlotCenter(e54, t4), o7 = this.getSlotCenter(e54, t4 + 1), i7 = Math.abs(o7.x - n7.x);\n return { orientation: \"horizontal\", row: e54, col: t4, center: { x: j9((n7.x + o7.x) / 2), y: n7.y }, width: i7 - this.padWidth, height: this.padHeight, isBetweenTwoPads: this.hasPadAt(e54, t4) \u0026\u0026 this.hasPadAt(e54, t4 + 1) };\n }\n getVerticalGap(e54, t4) {\n const n7 = this.getSlotCenter(e54, t4), o7 = this.getSlotCenter(e54 + 1, t4), i7 = Math.abs(o7.y - n7.y);\n return { orientation: \"vertical\", row: e54, col: t4, center: { x: n7.x, y: j9((n7.y + o7.y) / 2) }, width: this.padWidth, height: i7 - this.padHeight, isBetweenTwoPads: this.hasPadAt(e54, t4) \u0026\u0026 this.hasPadAt(e54 + 1, t4) };\n }\n getDiagonalGap(e54, t4) {\n const n7 = this.getSlotCenter(e54, t4), o7 = this.getSlotCenter(e54 + 1, t4 + 1), i7 = Math.abs(o7.x - n7.x), r7 = Math.abs(o7.y - n7.y);\n return { orientation: \"diagonal\", row: e54, col: t4, center: { x: j9((n7.x + o7.x) / 2), y: j9((n7.y + o7.y) / 2) }, width: i7 - this.padWidth, height: r7 - this.padHeight, isBetweenTwoPads: this.hasPadAt(e54, t4) \u0026\u0026 this.hasPadAt(e54 + 1, t4 + 1) };\n }\n getDiagonalGaps() {\n const e54 = [];\n for (let t4 = 0;t4 \u003c this.rowCount - 1; t4++)\n for (let n7 = 0;n7 \u003c this.colCount - 1; n7++)\n e54.push(this.getDiagonalGap(t4, n7));\n return e54.filter((e55) =\u003e e55.width \u003e z9 \u0026\u0026 e55.height \u003e z9);\n }\n getAxisGaps() {\n const e54 = [];\n for (let t4 = 0;t4 \u003c this.rowCount; t4++)\n for (let n7 = 0;n7 \u003c this.colCount - 1; n7++)\n e54.push(this.getHorizontalGap(t4, n7));\n for (let t4 = 0;t4 \u003c this.rowCount - 1; t4++)\n for (let n7 = 0;n7 \u003c this.colCount; n7++)\n e54.push(this.getVerticalGap(t4, n7));\n return e54.filter((e55) =\u003e e55.width \u003e z9 \u0026\u0026 e55.height \u003e z9);\n }\n getMissingSlots() {\n const e54 = [];\n for (let t4 = 0;t4 \u003c this.rowCount; t4++)\n for (let n7 = 0;n7 \u003c this.colCount; n7++)\n this.hasPadAt(t4, n7) || e54.push({ row: t4, col: n7, center: this.getSlotCenter(t4, n7), width: this.padWidth, height: this.padHeight });\n return e54;\n }\n};\nfunction Y9(e54) {\n if ([e54.point.pointId, e54.point.pcb_port_id].filter((e55) =\u003e typeof e55 == \"string\").some((t7) =\u003e e54.obstacle.connectedTo.includes(t7)))\n return true;\n if (e54.obstacle.connectedTo.length === 0)\n return false;\n if (Oe(e54.point, e54.obstacle) \u003e 0.001)\n return false;\n const t4 = So(e54.point).map((t7) =\u003e mo(t7, e54.layerCount)), n7 = e54.obstacle.layers.map((t7) =\u003e mo(t7, e54.layerCount));\n return t4.some((e55) =\u003e n7.includes(e55));\n}\nfunction X9(e54) {\n return e54.obstacleId ?? [e54.componentId ?? \"no-component\", e54.center.x, e54.center.y, e54.width, e54.height, e54.layers.join(\",\")].join(\":\");\n}\nfunction H9({ componentId: e54, orientationKey: t4, row: n7, col: o7, center: i7, width: r7, height: s7 }) {\n return [\"cmn\", t4, e54, n7, o7, i7.x, i7.y, r7, s7].join(\"_\");\n}\nfunction V9(e54) {\n const { componentId: t4, bgaGap: n7, freeLayers: o7, multiLayerThreshold: i7 } = e54, r7 = n7.width \u003e i7 \u0026\u0026 n7.height \u003e i7;\n let s7 = \"d\";\n n7.orientation === \"horizontal\" \u0026\u0026 (s7 = \"h\"), n7.orientation === \"vertical\" \u0026\u0026 (s7 = \"v\");\n const a7 = H9({ componentId: t4, orientationKey: s7, row: n7.row, col: n7.col, center: n7.center, width: n7.width, height: n7.height });\n return n7.orientation === \"diagonal\" \u0026\u0026 r7 || !n7.isBetweenTwoPads \u0026\u0026 r7 ? [{ center: n7.center, width: n7.width, height: n7.height, availableZ: [...o7], capacityMeshNodeId: `${a7}_all`, layer: \"\" }] : o7.map((e55) =\u003e ({ center: n7.center, width: n7.width, height: n7.height, availableZ: [e55], capacityMeshNodeId: `${a7}_${e55}`, layer: \"\" }));\n}\nfunction W9(e54) {\n const { componentId: t4, obstacle: n7, freeLayers: o7, layerCount: i7 } = e54, r7 = n7.layers.map((e55) =\u003e mo(e55, i7)), s7 = o7.filter((e55) =\u003e !r7.includes(e55)), a7 = X9(n7);\n return s7.map((e55) =\u003e ({ capacityMeshNodeId: `free-${t4}-${a7}-${e55}`, center: n7.center, width: n7.width, height: n7.height, layer: `z${e55}`, availableZ: [e55] }));\n}\nfunction G9(e54, t4, n7) {\n const o7 = t4.layers.map((e55) =\u003e mo(e55, n7.layerCount)), i7 = X9(t4), r7 = function(e55) {\n for (const t7 of e55.srj.connections)\n for (const n8 of t7.pointsToConnect)\n if (Y9({ point: n8, obstacle: e55.obstacle, layerCount: e55.srj.layerCount }))\n return t7.__rootConnectionNames?.[0] ?? t7.name;\n }({ obstacle: t4, srj: n7 });\n return { capacityMeshNodeId: `obstacle-${e54}-${i7}-${o7.join(\",\")}-${t4.center.x}-${t4.center.y}`, _containsObstacle: true, ...r7 ? { _containsTarget: true, _targetConnectionName: r7 } : {}, center: t4.center, width: t4.width, height: t4.height, layer: `z${o7.join(\",\")}`, availableZ: o7 };\n}\nvar U9 = class extends BaseSolver {\n constructor(e54) {\n super(), this.inputProblem = e54;\n }\n componentObstacles = [];\n meshNodes = [];\n getConstructorParams() {\n return [this.inputProblem];\n }\n _step() {\n const { srj: e54, componentBounds: t4, componentId: n7, markedComponentObstacles: o7, unmarkedComponentObstacles: i7 } = this.inputProblem, r7 = e54.obstacles.filter((e55) =\u003e e55.isCopperPour === true).filter((e55) =\u003e De(Le(e55), t4)).flatMap((t7) =\u003e t7.layers.map((t8) =\u003e mo(t8, e54.layerCount))), s7 = Array.from({ length: e54.layerCount }, (e55, t7) =\u003e t7).filter((e55) =\u003e !r7.includes(e55));\n if (this.componentObstacles = o7, o7.length === 0 || s7.length === 0)\n return void (this.solved = true);\n const a7 = $9.fromObstacles(o7);\n if (!a7)\n return void (this.solved = true);\n const c5 = a7.getAxisGaps(), l5 = a7.getDiagonalGaps(), h5 = a7.getMissingSlots(), d7 = 1.2 * (this.inputProblem.viaDiameter ?? Yo(e54).padDiameter);\n this.meshNodes = [...c5.flatMap((e55) =\u003e V9({ componentId: n7, bgaGap: e55, freeLayers: s7, multiLayerThreshold: d7 })), ...l5.flatMap((e55) =\u003e V9({ componentId: n7, bgaGap: e55, freeLayers: s7, multiLayerThreshold: d7 })), ...h5.flatMap((e55) =\u003e function(e56) {\n const { componentId: t7, missingBgaSlot: n8, freeLayers: o8, multiLayerThreshold: i8 } = e56, r8 = H9({ componentId: t7, orientationKey: \"missing\", row: n8.row, col: n8.col, center: n8.center, width: n8.width, height: n8.height });\n return n8.width \u003e i8 \u0026\u0026 n8.height \u003e i8 ? [{ center: n8.center, width: n8.width, height: n8.height, availableZ: [...o8], capacityMeshNodeId: `${r8}_all`, layer: \"\" }] : o8.map((e57) =\u003e ({ center: n8.center, width: n8.width, height: n8.height, availableZ: [e57], capacityMeshNodeId: `${r8}_${e57}`, layer: \"\" }));\n }({ componentId: n7, missingBgaSlot: e55, freeLayers: s7, multiLayerThreshold: d7 })), ...o7.flatMap((t7) =\u003e [...W9({ componentId: n7, obstacle: t7, freeLayers: s7, layerCount: e54.layerCount }), G9(n7, t7, e54)]), ...i7.flatMap((t7) =\u003e [G9(n7, t7, e54)])], this.meshNodes = function(e55) {\n const t7 = new Map;\n return e55.map((e56) =\u003e {\n const n8 = t7.get(e56.capacityMeshNodeId) ?? 0;\n return t7.set(e56.capacityMeshNodeId, n8 + 1), n8 === 0 ? e56 : { ...e56, capacityMeshNodeId: `${e56.capacityMeshNodeId}__dup${n8}` };\n });\n }(this.meshNodes), this.solved = true;\n }\n getOutput() {\n return this.meshNodes;\n }\n visualize() {\n return { rects: [{ center: { x: (this.inputProblem.componentBounds.minX + this.inputProblem.componentBounds.maxX) / 2, y: (this.inputProblem.componentBounds.minY + this.inputProblem.componentBounds.maxY) / 2 }, width: this.inputProblem.componentBounds.maxX - this.inputProblem.componentBounds.minX, height: this.inputProblem.componentBounds.maxY - this.inputProblem.componentBounds.minY, fill: \"rgba(0,0,0,0)\", stroke: \"rgba(30,30,30,0.65)\", label: `component ${this.inputProblem.componentId}` }, ...this.inputProblem.markedComponentObstacles.map((e54) =\u003e ({ center: e54.center, width: e54.width, height: e54.height, fill: \"rgba(255,0,0,0.18)\", stroke: \"rgba(255,0,0,0.52)\", label: `pad ${e54.obstacleId ?? \"obstacle\"}` })), ...this.inputProblem.unmarkedComponentObstacles.map((e54) =\u003e ({ center: e54.center, width: e54.width, height: e54.height, fill: \"rgba(255,140,0,0.14)\", stroke: \"rgba(255,140,0,0.42)\", label: `foreign ${e54.obstacleId ?? \"obstacle\"}` })), ...this.meshNodes.map((e54) =\u003e ({ ...dj(e54, { rectMargin: 0.01 }), fill: e54._containsObstacle ? \"rgba(255,0,0,0.14)\" : e54.capacityMeshNodeId.includes(\"missing\") ? \"rgba(0,200,120,0.18)\" : \"rgba(0,120,255,0.12)\", stroke: e54._containsObstacle ? \"rgba(255,0,0,0.36)\" : e54.capacityMeshNodeId.includes(\"missing\") ? \"rgba(0,200,120,0.52)\" : \"rgba(0,120,255,0.38)\" }))] };\n }\n};\nfunction q9(e54) {\n return e54.capacityMeshNodeId.startsWith(\"bga-gapfill-\");\n}\nfunction J9(e54) {\n return JSON.stringify({ availableZ: [...e54.availableZ].sort((e55, t4) =\u003e e55 - t4), _containsTarget: e54._containsTarget ?? false, _targetConnectionName: e54._targetConnectionName ?? null, _depth: e54._depth ?? null, _strawNode: e54._strawNode ?? false, _strawParentCapacityMeshNodeId: e54._strawParentCapacityMeshNodeId ?? null, _qfpRegionType: e54._qfpRegionType ?? null, _isNarrowQfpPadGap: e54._isNarrowQfpPadGap ?? false, _soicRegionType: e54._soicRegionType ?? null, _offBoardConnectionId: e54._offBoardConnectionId ?? null, _offboardNetName: e54._offboardNetName ?? null, _isVirtualOffboard: e54._isVirtualOffboard ?? false, _containsObstacle: e54._containsObstacle ?? false });\n}\nfunction Q9(e54, t4) {\n const n7 = Le(e54);\n for (const o7 of t4) {\n if (!e54.availableZ.some((e55) =\u003e o7.availableZ.includes(e55)))\n continue;\n const t7 = Le(o7);\n if (De(n7, t7))\n return true;\n }\n return false;\n}\nfunction K9(e54) {\n const t4 = e54[0];\n if (!t4)\n throw new Error(\"createMergedNode requires at least one source node\");\n let { POSITIVE_INFINITY: n7, NEGATIVE_INFINITY: o7, POSITIVE_INFINITY: i7, NEGATIVE_INFINITY: r7 } = Number;\n for (const t7 of e54) {\n const e55 = Le(t7);\n n7 = Math.min(n7, e55.minX), o7 = Math.max(o7, e55.maxX), i7 = Math.min(i7, e55.minY), r7 = Math.max(r7, e55.maxY);\n }\n return { ...t4, capacityMeshNodeId: `merge:${e54.map((e55) =\u003e e55.capacityMeshNodeId).join(\":\")}`, center: { x: (n7 + o7) / 2, y: (i7 + r7) / 2 }, width: o7 - n7, height: r7 - i7 };\n}\nfunction e82(e54, t4, n7) {\n return { center: e54.center, width: e54.width, height: e54.height, fill: t4, stroke: t4, label: n7 };\n}\nvar t8 = class extends BaseSolver {\n constructor(e54) {\n super(), this.inputProblem = e54;\n }\n obstacleNodes = [];\n passthroughNodes = [];\n mergedNodes = [];\n pendingGroups = [];\n totalGroupCount = 0;\n processedGroupCount = 0;\n debugFilteredNodes = [];\n debugMergeEvents = [];\n currentGroupKey = null;\n currentRootNodeId = null;\n lastMergedNodeId = null;\n _setup() {\n this.obstacleNodes = this.inputProblem.meshNodes.filter((e55) =\u003e e55._containsObstacle === true), this.passthroughNodes = [], this.mergedNodes = [], this.pendingGroups = [], this.totalGroupCount = 0, this.processedGroupCount = 0, this.debugFilteredNodes = [], this.debugMergeEvents = [], this.currentGroupKey = null, this.currentRootNodeId = null, this.lastMergedNodeId = null;\n const e54 = new Map;\n for (const t4 of this.inputProblem.meshNodes) {\n if (t4._containsObstacle === true) {\n this.passthroughNodes.push(t4), this.debugFilteredNodes.push({ type: \"preserved-obstacle\", node: t4, reason: \"contains-obstacle\" });\n continue;\n }\n if (q9(t4)) {\n this.passthroughNodes.push(t4);\n continue;\n }\n if (t4.availableZ.length !== this.inputProblem.layerCount) {\n this.passthroughNodes.push(t4);\n continue;\n }\n let n7 = false;\n for (let e55 = 0;e55 \u003c this.inputProblem.layerCount; e55 += 1)\n if (!t4.availableZ.includes(e55)) {\n n7 = true;\n break;\n }\n if (n7) {\n this.passthroughNodes.push(t4);\n continue;\n }\n if (Q9(t4, this.obstacleNodes)) {\n this.passthroughNodes.push(t4), this.debugFilteredNodes.push({ type: \"preserved-overlap\", node: t4, reason: \"overlaps-obstacle\" });\n continue;\n }\n const o7 = J9(t4), i7 = e54.get(o7);\n i7 ? i7.push(t4) : e54.set(o7, [t4]);\n }\n for (const [t4, n7] of e54.entries())\n n7.length \u003c= 1 ? this.passthroughNodes.push(...n7) : this.pendingGroups.push({ groupKey: t4, nodes: n7 });\n this.pendingGroups.sort((e55, t4) =\u003e t4.nodes.length - e55.nodes.length), this.totalGroupCount = this.pendingGroups.length, this.updateStats(\"setup\");\n }\n _step() {\n const e54 = this.pendingGroups.shift();\n if (!e54)\n return this.currentGroupKey = null, this.currentRootNodeId = null, this.solved = true, void this.updateStats(\"done\");\n const t4 = e54.nodes[0];\n this.currentGroupKey = e54.groupKey, this.currentRootNodeId = t4 ? t4.capacityMeshNodeId : null;\n const n7 = function(e55) {\n if (!e55.nodes[0])\n return { outputNodes: [], mergeEvents: [] };\n let { POSITIVE_INFINITY: t7, POSITIVE_INFINITY: n8, POSITIVE_INFINITY: o8, POSITIVE_INFINITY: i7 } = Number;\n for (const r8 of e55.nodes) {\n t7 = Math.min(t7, r8.width), n8 = Math.min(n8, r8.height);\n const e56 = Le(r8);\n o8 = Math.min(o8, e56.minX), i7 = Math.min(i7, e56.minY);\n }\n const r7 = new Map, s7 = [];\n for (const a8 of e55.nodes) {\n const e56 = Le(a8), c7 = Math.round((e56.minX - o8) / t7), l7 = Math.round((e56.minY - i7) / n8), h5 = Math.max(1, Math.round(a8.width / t7)), d7 = Math.max(1, Math.round(a8.height / n8));\n for (let e57 = 0;e57 \u003c d7; e57 += 1)\n for (let t10 = 0;t10 \u003c h5; t10 += 1)\n r7.set(`${c7 + t10},${l7 + e57}`, a8);\n s7.push({ col: c7, row: l7 });\n }\n s7.sort((e56, t10) =\u003e e56.row - t10.row || e56.col - t10.col);\n const a7 = new Set, c5 = [], l5 = [];\n for (const o10 of s7) {\n const i8 = `${o10.col},${o10.row}`;\n if (a7.has(i8))\n continue;\n let s8 = 0;\n for (;; ) {\n const e56 = `${o10.col + s8},${o10.row}`;\n if (!r7.has(e56))\n break;\n if (a7.has(e56))\n break;\n s8 += 1;\n }\n let h5 = s8, d7 = 1, u7 = 1, p7 = 1;\n for (let e56 = 1;; e56 += 1) {\n const i9 = o10.row + e56 - 1;\n let s9 = 0;\n for (;s9 \u003c h5; ) {\n const e57 = `${o10.col + s9},${i9}`;\n if (!r7.has(e57))\n break;\n if (a7.has(e57))\n break;\n s9 += 1;\n }\n if (s9 === 0)\n break;\n h5 = Math.min(h5, s9);\n for (let o11 = h5;o11 \u003e= 1; o11 -= 1) {\n const i10 = o11 * t7, r8 = e56 * n8, s10 = Math.min(i10, r8);\n if ((s10 \u003c= 0.000001 ? Number.POSITIVE_INFINITY : Math.max(i10, r8) / s10) \u003e 4)\n continue;\n const a8 = o11 * e56;\n a8 \u003e p7 \u0026\u0026 (p7 = a8, d7 = o11, u7 = e56);\n break;\n }\n }\n const m7 = new Map;\n for (let e56 = 0;e56 \u003c u7; e56 += 1)\n for (let t10 = 0;t10 \u003c d7; t10 += 1) {\n const n10 = `${o10.col + t10},${o10.row + e56}`, i9 = r7.get(n10);\n i9 \u0026\u0026 (a7.add(n10), m7.set(i9.capacityMeshNodeId, i9));\n }\n const g7 = [...m7.values()];\n if (g7.length \u003c= 1) {\n const e56 = g7[0];\n e56 \u0026\u0026 c5.push(e56);\n continue;\n }\n const f7 = K9(g7);\n c5.push(f7), l5.push({ type: \"merge\", groupKey: e55.groupKey, sourceNodes: g7, mergedNode: f7 });\n }\n return { outputNodes: c5, mergeEvents: l5 };\n }(e54);\n this.mergedNodes.push(...n7.outputNodes), this.processedGroupCount += 1, this.debugMergeEvents.push(...n7.mergeEvents);\n const o7 = n7.mergeEvents[n7.mergeEvents.length - 1];\n o7 \u0026\u0026 (this.lastMergedNodeId = o7.mergedNode.capacityMeshNodeId), this.updateStats(n7.mergeEvents.length \u003e 0 ? \"merged-group\" : \"passthrough-group\");\n }\n computeProgress() {\n return this.totalGroupCount === 0 ? 1 : this.processedGroupCount / this.totalGroupCount;\n }\n updateStats(e54) {\n const t4 = new Set(this.debugMergeEvents.map((e55) =\u003e e55.groupKey)), n7 = { lastAction: e54, totalGroupCount: this.totalGroupCount, processedGroupCount: this.processedGroupCount, pendingGroupCount: this.pendingGroups.length, mergedNodeCount: this.mergedNodes.length, passthroughNodeCount: this.passthroughNodes.length, gapFillNodeCount: this.passthroughNodes.filter(q9).length, preservedObstacleNodeCount: this.debugFilteredNodes.filter((e55) =\u003e e55.type === \"preserved-obstacle\").length, preservedOverlapNodeCount: this.debugFilteredNodes.filter((e55) =\u003e e55.type === \"preserved-overlap\").length, mergeCount: this.debugMergeEvents.length, mergedGroupCount: t4.size, currentGroupKey: this.currentGroupKey, currentRootNodeId: this.currentRootNodeId, lastMergedNodeId: this.lastMergedNodeId };\n this.stats = n7;\n }\n getConstructorParams() {\n return [this.inputProblem];\n }\n getOutput() {\n return [...this.mergedNodes, ...this.passthroughNodes];\n }\n visualize() {\n const e54 = this.getOutput(), t4 = this.currentRootNodeId ? e54.find((e55) =\u003e e55.capacityMeshNodeId === this.currentRootNodeId) ?? null : null, n7 = this.lastMergedNodeId ? e54.find((e55) =\u003e e55.capacityMeshNodeId === this.lastMergedNodeId) ?? null : null;\n return { rects: [...this.debugFilteredNodes.map((e55) =\u003e e82(e55.node, e55.type === \"preserved-obstacle\" ? \"rgba(255,64,64,0.35)\" : \"rgba(255,160,64,0.35)\", e55.reason)), ...this.passthroughNodes.map((e55) =\u003e e82(e55, e55._containsObstacle ? \"rgba(255,0,0,0.35)\" : q9(e55) ? \"rgba(0,120,255,0.18)\" : \"rgba(160,160,160,0.12)\")), ...this.mergedNodes.map((e55) =\u003e e82(e55, \"rgba(120,120,120,0.14)\")), ...t4 ? [e82(t4, \"rgba(255,215,0,0.35)\", \"active-group\")] : [], ...n7 ? [e82(n7, \"rgba(0,200,120,0.28)\", \"merged\")] : []] };\n }\n};\nvar o8 = class extends BaseSolver {\n constructor(e54) {\n super(), this.inputProblem = e54;\n }\n obstacleQueue = [];\n obstacleQueueIndex = 0;\n meshNodes = [];\n _setup() {\n this.obstacleQueue = this.inputProblem.obstacles, this.obstacleQueueIndex = 0, this.meshNodes = [...this.inputProblem.meshNodes];\n }\n _step() {\n if (this.obstacleQueueIndex \u003e= this.obstacleQueue.length)\n return void (this.solved = true);\n const e54 = this.obstacleQueue[this.obstacleQueueIndex], t4 = e54.layers.map((e55) =\u003e mo(e55, this.inputProblem.layerCount)), n7 = [];\n for (const o7 of this.meshNodes) {\n if (o7._containsObstacle) {\n n7.push(o7);\n continue;\n }\n if (!t4.some((e55) =\u003e o7.availableZ.includes(e55))) {\n n7.push(o7);\n continue;\n }\n if (!De(Le(o7), Le(e54))) {\n n7.push(o7);\n continue;\n }\n if (o7.availableZ.length === 1)\n continue;\n const i7 = o7.availableZ.filter((e55) =\u003e !t4.includes(e55));\n for (const e55 of i7) {\n const t7 = { ...o7, capacityMeshNodeId: `${o7.capacityMeshNodeId}:z${e55}`, availableZ: [e55], layer: `z${e55}` };\n n7.push(t7);\n }\n }\n this.meshNodes = n7, this.obstacleQueueIndex += 1, this.stats = { obstaclesProcessed: this.obstacleQueueIndex, obstacleCount: this.obstacleQueue.length, meshNodeCount: this.meshNodes.length };\n }\n computeProgress() {\n return this.obstacleQueue.length === 0 ? 1 : this.obstacleQueueIndex / this.obstacleQueue.length;\n }\n getConstructorParams() {\n return [this.inputProblem];\n }\n getOutput() {\n return this.meshNodes;\n }\n visualize() {\n const e54 = this.obstacleQueueIndex \u003c this.obstacleQueue.length ? this.obstacleQueue[this.obstacleQueueIndex] ?? null : null, t4 = this.obstacleQueue.slice(0, this.obstacleQueueIndex), n7 = e54 ? this.obstacleQueue.slice(this.obstacleQueueIndex + 1) : [];\n return { rects: [...t4.map((e55) =\u003e ({ center: e55.center, width: e55.width, height: e55.height, fill: \"rgba(160,160,160,0.10)\", stroke: \"rgba(160,160,160,0.35)\", label: `processed ${e55.obstacleId ?? \"obstacle\"}` })), ...e54 ? [{ center: e54.center, width: e54.width, height: e54.height, fill: \"rgba(255,140,0,0.22)\", stroke: \"rgba(255,140,0,0.75)\", label: `active ${e54.obstacleId ?? \"obstacle\"}` }] : [], ...n7.map((e55) =\u003e ({ center: e55.center, width: e55.width, height: e55.height, fill: \"rgba(255,0,0,0.05)\", stroke: \"rgba(255,0,0,0.22)\", label: `pending ${e55.obstacleId ?? \"obstacle\"}` })), ...this.meshNodes.map((e55) =\u003e ({ ...dj(e55, { rectMargin: 0.01 }), fill: e55._containsObstacle ? \"rgba(255,0,0,0.18)\" : \"rgba(0,120,255,0.12)\", stroke: e55._containsObstacle ? \"rgba(255,0,0,0.45)\" : \"rgba(0,120,255,0.45)\" }))] };\n }\n};\nl9.register(class extends BasePipelineSolver {\n constructor(e54) {\n super(e54), this.inputProblem = e54;\n }\n static componentKind = \"bga\";\n initialTopologySolver;\n removeMeshNodeOverlappingWithUnmarkedObstacle;\n gapfillDueToNodeRemoval;\n mergeMeshNodes;\n markedComponentObstacles = [];\n unmarkedComponentObstacles = [];\n pipelineDef = [definePipelineStep(\"initialTopologySolver\", U9, (e54) =\u003e [{ srj: e54.inputProblem.inputSrj, componentBounds: e54.inputProblem.detectedComponent.bounds, componentId: e54.inputProblem.detectedComponent.componentId, markedComponentObstacles: e54.markedComponentObstacles, unmarkedComponentObstacles: e54.unmarkedComponentObstacles, viaDiameter: e54.inputProblem.viaDiameter }]), definePipelineStep(\"removeMeshNodeOverlappingWithUnmarkedObstacle\", o8, (e54) =\u003e [{ meshNodes: e54.initialTopologySolver.getOutput(), obstacles: e54.unmarkedComponentObstacles, layerCount: e54.inputProblem.inputSrj.layerCount }]), definePipelineStep(\"gapfillDueToNodeRemoval\", k9, (e54) =\u003e [{ meshNodes: e54.removeMeshNodeOverlappingWithUnmarkedObstacle.getOutput(), unmarkedComponentObstacles: e54.unmarkedComponentObstacles, layerCount: e54.inputProblem.inputSrj.layerCount }]), definePipelineStep(\"mergeMeshNodes\", t8, (e54) =\u003e [{ meshNodes: e54.gapfillDueToNodeRemoval.getOutput(), layerCount: e54.inputProblem.inputSrj.layerCount }])];\n _setup() {\n const e54 = this.inputProblem.detectedComponent.bounds, t4 = this.inputProblem.detectedComponent.componentId, n7 = [], o7 = [];\n for (const i7 of this.inputProblem.inputSrj.obstacles) {\n const r7 = Le(i7);\n De(e54, r7) \u0026\u0026 (i7.componentId !== t4 ? o7.push(i7) : n7.push(i7));\n }\n this.markedComponentObstacles = n7, this.unmarkedComponentObstacles = o7;\n }\n getConstructorParams() {\n return [this.inputProblem];\n }\n getOutput() {\n return { routingRegions: this.mergeMeshNodes?.getOutput() ?? this.gapfillDueToNodeRemoval?.getOutput() ?? this.removeMeshNodeOverlappingWithUnmarkedObstacle?.getOutput() ?? [] };\n }\n initialVisualize() {\n return { rects: [{ center: { x: (this.inputProblem.detectedComponent.bounds.minX + this.inputProblem.detectedComponent.bounds.maxX) / 2, y: (this.inputProblem.detectedComponent.bounds.minY + this.inputProblem.detectedComponent.bounds.maxY) / 2 }, width: this.inputProblem.detectedComponent.bounds.maxX - this.inputProblem.detectedComponent.bounds.minX, height: this.inputProblem.detectedComponent.bounds.maxY - this.inputProblem.detectedComponent.bounds.minY, fill: \"rgba(0,0,0,0)\", stroke: \"rgba(30,30,30,0.65)\", label: `bga ${this.inputProblem.detectedComponent.componentId}` }, ...this.markedComponentObstacles.map((e54) =\u003e ({ center: e54.center, width: e54.width, height: e54.height, fill: \"rgba(255,0,0,0.18)\", stroke: \"rgba(255,0,0,0.52)\", label: `pad ${e54.obstacleId ?? \"obstacle\"}` })), ...this.unmarkedComponentObstacles.map((e54) =\u003e ({ center: e54.center, width: e54.width, height: e54.height, fill: \"rgba(255,140,0,0.14)\", stroke: \"rgba(255,140,0,0.42)\", label: `foreign ${e54.obstacleId ?? \"obstacle\"}` }))] };\n }\n finalVisualize() {\n return { rects: this.getOutput().routingRegions.map((e54) =\u003e ({ ...dj(e54, { rectMargin: 0.01 }), fill: e54._containsObstacle ? \"rgba(255,0,0,0.16)\" : \"rgba(0,120,255,0.12)\", stroke: e54._containsObstacle ? \"rgba(255,0,0,0.36)\" : \"rgba(0,120,255,0.42)\" })) };\n }\n});\nvar r8 = 0.000001;\nfunction s8(e54, t4) {\n return e54.__zLayers \u0026\u0026 e54.__zLayers.length \u003e 0 ? go(e54.__zLayers, t4) : fo(e54.layers, t4);\n}\nfunction a8(e54) {\n const t4 = [...e54].sort((e55, t7) =\u003e e55 - t7), n7 = [];\n for (let e55 = 1;e55 \u003c t4.length; e55++) {\n const o10 = t4[e55] - t4[e55 - 1];\n o10 \u003e r8 \u0026\u0026 n7.push(o10);\n }\n const o7 = n7.length \u003e 0 ? Math.max(r8, Math.min(...n7) / 4) : 0.001, i7 = [];\n for (const e55 of t4) {\n const t7 = i7[i7.length - 1];\n (t7 === undefined || Math.abs(e55 - t7) \u003e o7) \u0026\u0026 i7.push(e55);\n }\n return i7;\n}\nfunction c8(e54) {\n return Array.from({ length: Math.max(0, e54) }, (e55, t4) =\u003e t4);\n}\nvar l8 = 0.000001;\nfunction h8(e54) {\n return e54.maxX - e54.minX \u003e l8 \u0026\u0026 e54.maxY - e54.minY \u003e l8;\n}\nfunction d8(e54) {\n return function(e55) {\n const t4 = Math.min(e55.width, e55.height), n7 = Math.max(e55.width, e55.height);\n return t4 \u003c= 0 ? 0 : n7 / t4;\n }(e54) \u003e= 1.5;\n}\nfunction u8(e54, t4) {\n const n7 = [{ side: \"top\", distance: Math.abs(e54.center.y - t4.minY) }, { side: \"right\", distance: Math.abs(t4.maxX - e54.center.x) }, { side: \"bottom\", distance: Math.abs(t4.maxY - e54.center.y) }, { side: \"left\", distance: Math.abs(e54.center.x - t4.minX) }];\n return n7.sort((e55, t7) =\u003e e55.distance - t7.distance), n7[0].side;\n}\nfunction p8(e54, t4) {\n return e54.map((e55, n7) =\u003e ({ key: `pad:${e55.obstacleId ?? n7}`, bounds: Pe(e55), regionType: \"pad\", obstacleZ: s8(e55, t4), connectedTo: [...e55.connectedTo] }));\n}\nfunction m8(e54, t4) {\n return e54.map((e55, n7) =\u003e ({ key: `thermal-pad:${e55.obstacleId ?? n7}`, bounds: Pe(e55), regionType: \"pad\", obstacleZ: s8(e55, t4), connectedTo: [...e55.connectedTo] }));\n}\nfunction g8(e54, t4) {\n return !!h8(e54) \u0026\u0026 Math.min(e54.maxX - e54.minX, e54.maxY - e54.minY) \u003c= t4;\n}\nfunction f8({ side: e54, sideObstacles: t4, bounds: n7, innerBounds: o7, narrowThreshold: i7 }) {\n const r7 = [];\n for (let s7 = 0;s7 \u003c t4.length - 1; s7++) {\n const a7 = Pe(t4[s7]), c5 = Pe(t4[s7 + 1]);\n let l5;\n l5 = e54 === \"top\" ? { minX: a7.maxX, maxX: c5.minX, minY: n7.minY, maxY: o7.minY } : e54 === \"right\" ? { minX: o7.maxX, maxX: n7.maxX, minY: a7.maxY, maxY: c5.minY } : e54 === \"bottom\" ? { minX: a7.maxX, maxX: c5.minX, minY: o7.maxY, maxY: n7.maxY } : { minX: n7.minX, maxX: o7.minX, minY: a7.maxY, maxY: c5.minY }, r7.push({ key: `${e54}-gap-${s7}`, bounds: l5, regionType: \"pad-gap\", isNarrowPadGap: g8(l5, i7) });\n }\n return r7;\n}\nfunction _8({ side: e54, sideObstacles: t4, thermalPadBounds: n7, narrowThreshold: o7 }) {\n const i7 = [];\n for (let r7 = 0;r7 \u003c t4.length; r7++) {\n const s7 = Pe(t4[r7]), a7 = t4[r7 - 1] ? Pe(t4[r7 - 1]) : null, c5 = t4[r7 + 1] ? Pe(t4[r7 + 1]) : null;\n let l5;\n l5 = e54 === \"top\" ? { minX: a7 ? (a7.maxX + s7.minX) / 2 : s7.minX, maxX: c5 ? (s7.maxX + c5.minX) / 2 : s7.maxX, minY: s7.maxY, maxY: n7.minY } : e54 === \"right\" ? { minX: n7.maxX, maxX: s7.minX, minY: a7 ? (a7.maxY + s7.minY) / 2 : s7.minY, maxY: c5 ? (s7.maxY + c5.minY) / 2 : s7.maxY } : e54 === \"bottom\" ? { minX: a7 ? (a7.maxX + s7.minX) / 2 : s7.minX, maxX: c5 ? (s7.maxX + c5.minX) / 2 : s7.maxX, minY: n7.maxY, maxY: s7.minY } : { minX: s7.maxX, maxX: n7.minX, minY: a7 ? (a7.maxY + s7.minY) / 2 : s7.minY, maxY: c5 ? (s7.maxY + c5.minY) / 2 : s7.maxY }, i7.push({ key: `inner-${e54}-pad-${r7}`, bounds: l5, regionType: \"pad-gap\", isNarrowPadGap: g8(l5, o7) });\n }\n return i7;\n}\nfunction y8({ bounds: e54, innerBounds: t4, sideGroups: n7 }) {\n const o7 = n7.top[0] ? Pe(n7.top[0]) : null, i7 = n7.top.at(-1) ? Pe(n7.top.at(-1)) : null, r7 = n7.right[0] ? Pe(n7.right[0]) : null, s7 = n7.right.at(-1) ? Pe(n7.right.at(-1)) : null, a7 = n7.bottom[0] ? Pe(n7.bottom[0]) : null, c5 = n7.bottom.at(-1) ? Pe(n7.bottom.at(-1)) : null, l5 = n7.left[0] ? Pe(n7.left[0]) : null, h5 = n7.left.at(-1) ? Pe(n7.left.at(-1)) : null;\n return [{ key: \"corner-nw-outer\", regionType: \"corner\", bounds: { minX: e54.minX, maxX: t4.minX, minY: e54.minY, maxY: t4.minY } }, { key: \"corner-nw-top\", regionType: \"corner\", bounds: { minX: t4.minX, maxX: o7?.minX ?? t4.minX, minY: e54.minY, maxY: t4.minY } }, { key: \"corner-nw-left\", regionType: \"corner\", bounds: { minX: e54.minX, maxX: t4.minX, minY: t4.minY, maxY: l5?.minY ?? t4.minY } }, { key: \"corner-ne-outer\", regionType: \"corner\", bounds: { minX: t4.maxX, maxX: e54.maxX, minY: e54.minY, maxY: t4.minY } }, { key: \"corner-ne-top\", regionType: \"corner\", bounds: { minX: i7?.maxX ?? t4.maxX, maxX: t4.maxX, minY: e54.minY, maxY: t4.minY } }, { key: \"corner-ne-right\", regionType: \"corner\", bounds: { minX: t4.maxX, maxX: e54.maxX, minY: t4.minY, maxY: r7?.minY ?? t4.minY } }, { key: \"corner-se-outer\", regionType: \"corner\", bounds: { minX: t4.maxX, maxX: e54.maxX, minY: t4.maxY, maxY: e54.maxY } }, { key: \"corner-se-right\", regionType: \"corner\", bounds: { minX: t4.maxX, maxX: e54.maxX, minY: s7?.maxY ?? t4.maxY, maxY: t4.maxY } }, { key: \"corner-se-bottom\", regionType: \"corner\", bounds: { minX: c5?.maxX ?? t4.maxX, maxX: t4.maxX, minY: t4.maxY, maxY: e54.maxY } }, { key: \"corner-sw-outer\", regionType: \"corner\", bounds: { minX: e54.minX, maxX: t4.minX, minY: t4.maxY, maxY: e54.maxY } }, { key: \"corner-sw-bottom\", regionType: \"corner\", bounds: { minX: t4.minX, maxX: a7?.minX ?? t4.minX, minY: t4.maxY, maxY: e54.maxY } }, { key: \"corner-sw-left\", regionType: \"corner\", bounds: { minX: e54.minX, maxX: t4.minX, minY: h5?.maxY ?? t4.maxY, maxY: t4.maxY } }];\n}\nfunction b8({ innerBounds: e54, thermalPadBounds: t4, sideGroups: n7 }) {\n const o7 = n7.top[0] ? Pe(n7.top[0]) : null, i7 = n7.top.at(-1) ? Pe(n7.top.at(-1)) : null, r7 = n7.right[0] ? Pe(n7.right[0]) : null, s7 = n7.right.at(-1) ? Pe(n7.right.at(-1)) : null, a7 = n7.bottom[0] ? Pe(n7.bottom[0]) : null, c5 = n7.bottom.at(-1) ? Pe(n7.bottom.at(-1)) : null, l5 = n7.left[0] ? Pe(n7.left[0]) : null, h5 = n7.left.at(-1) ? Pe(n7.left.at(-1)) : null;\n return [{ key: \"inner-corner-nw-core\", regionType: \"corner\", bounds: { minX: e54.minX, maxX: t4.minX, minY: e54.minY, maxY: t4.minY } }, { key: \"inner-corner-nw-top\", regionType: \"corner\", bounds: { minX: t4.minX, maxX: o7?.minX ?? t4.minX, minY: e54.minY, maxY: t4.minY } }, { key: \"inner-corner-nw-left\", regionType: \"corner\", bounds: { minX: e54.minX, maxX: t4.minX, minY: t4.minY, maxY: l5?.minY ?? t4.minY } }, { key: \"inner-corner-ne-core\", regionType: \"corner\", bounds: { minX: t4.maxX, maxX: e54.maxX, minY: e54.minY, maxY: t4.minY } }, { key: \"inner-corner-ne-top\", regionType: \"corner\", bounds: { minX: i7?.maxX ?? t4.maxX, maxX: t4.maxX, minY: e54.minY, maxY: t4.minY } }, { key: \"inner-corner-ne-right\", regionType: \"corner\", bounds: { minX: t4.maxX, maxX: e54.maxX, minY: t4.minY, maxY: r7?.minY ?? t4.minY } }, { key: \"inner-corner-se-core\", regionType: \"corner\", bounds: { minX: t4.maxX, maxX: e54.maxX, minY: t4.maxY, maxY: e54.maxY } }, { key: \"inner-corner-se-right\", regionType: \"corner\", bounds: { minX: t4.maxX, maxX: e54.maxX, minY: s7?.maxY ?? t4.maxY, maxY: t4.maxY } }, { key: \"inner-corner-se-bottom\", regionType: \"corner\", bounds: { minX: c5?.maxX ?? t4.maxX, maxX: t4.maxX, minY: t4.maxY, maxY: e54.maxY } }, { key: \"inner-corner-sw-core\", regionType: \"corner\", bounds: { minX: e54.minX, maxX: t4.minX, minY: t4.maxY, maxY: e54.maxY } }, { key: \"inner-corner-sw-bottom\", regionType: \"corner\", bounds: { minX: t4.minX, maxX: a7?.minX ?? t4.minX, minY: t4.maxY, maxY: e54.maxY } }, { key: \"inner-corner-sw-left\", regionType: \"corner\", bounds: { minX: e54.minX, maxX: t4.minX, minY: h5?.maxY ?? t4.maxY, maxY: t4.maxY } }];\n}\nl9.register(class extends BaseSolver {\n constructor(e54) {\n super(), this.inputProblem = e54;\n }\n static componentKind = \"qfp_thermalpad\";\n output = null;\n getConstructorParams() {\n return [this.inputProblem];\n }\n _step() {\n if (this.output)\n return void (this.solved = true);\n const { layerCount: e54, obstacles: t4 } = this.inputProblem.inputSrj, { bounds: n7, componentId: o7 } = this.inputProblem.detectedComponent, i7 = c8(e54), r7 = t4.filter((e55) =\u003e e55.componentId === o7), s7 = r7.length \u003e 0 ? r7 : t4, { padRingObstacles: a7, thermalPadObstacles: c5 } = function(e55) {\n return { padRingObstacles: e55.filter(d8), thermalPadObstacles: e55.filter((e56) =\u003e !d8(e56)) };\n }(s7), l5 = function(e55, t7) {\n const n8 = { top: [], right: [], bottom: [], left: [] };\n for (const o10 of e55)\n n8[u8(o10, t7)].push(o10);\n return n8.top.sort((e56, t10) =\u003e e56.center.x - t10.center.x), n8.bottom.sort((e56, t10) =\u003e e56.center.x - t10.center.x), n8.left.sort((e56, t10) =\u003e e56.center.y - t10.center.y), n8.right.sort((e56, t10) =\u003e e56.center.y - t10.center.y), n8;\n }(a7, n7), h5 = function({ bounds: e55, sideGroups: t7 }) {\n return { minX: t7.left.length \u003e 0 ? Math.max(...t7.left.map((e56) =\u003e Pe(e56).maxX)) : e55.minX, maxX: t7.right.length \u003e 0 ? Math.min(...t7.right.map((e56) =\u003e Pe(e56).minX)) : e55.maxX, minY: t7.top.length \u003e 0 ? Math.max(...t7.top.map((e56) =\u003e Pe(e56).maxY)) : e55.minY, maxY: t7.bottom.length \u003e 0 ? Math.min(...t7.bottom.map((e56) =\u003e Pe(e56).minY)) : e55.maxY };\n }({ bounds: n7, sideGroups: l5 }), d7 = function(e55) {\n return e55.length === 0 ? null : e55.reduce((e56, t7) =\u003e {\n const n8 = Pe(t7);\n return { minX: Math.min(e56.minX, n8.minX), maxX: Math.max(e56.maxX, n8.maxX), minY: Math.min(e56.minY, n8.minY), maxY: Math.max(e56.maxY, n8.maxY) };\n }, Pe(e55[0]));\n }(c5);\n if (!d7)\n return this.failed = true, void (this.error = \"QfpThermalPadTopologyGeneratorSolver requires a thermal pad\");\n const u7 = o7, p7 = this.inputProblem.viaDiameter ?? Yo(this.inputProblem.inputSrj).padDiameter, m7 = this.inputProblem.obstacleMargin ?? this.inputProblem.inputSrj.defaultObstacleMargin ?? 0.15, g7 = p7 + 2 * m7, f7 = this.inputProblem.inputSrj.minTraceWidth + 2 * m7, _5 = [...p8(a7, e54), ...m8(c5, e54), ...f8({ side: \"top\", sideObstacles: l5.top, bounds: n7, innerBounds: h5, narrowThreshold: f7 }), ...f8({ side: \"right\", sideObstacles: l5.right, bounds: n7, innerBounds: h5, narrowThreshold: f7 }), ...f8({ side: \"bottom\", sideObstacles: l5.bottom, bounds: n7, innerBounds: h5, narrowThreshold: f7 }), ...f8({ side: \"left\", sideObstacles: l5.left, bounds: n7, innerBounds: h5, narrowThreshold: f7 }), ..._8({ side: \"top\", sideObstacles: l5.top, thermalPadBounds: d7, narrowThreshold: f7 }), ..._8({ side: \"right\", sideObstacles: l5.right, thermalPadBounds: d7, narrowThreshold: f7 }), ..._8({ side: \"bottom\", sideObstacles: l5.bottom, thermalPadBounds: d7, narrowThreshold: f7 }), ..._8({ side: \"left\", sideObstacles: l5.left, thermalPadBounds: d7, narrowThreshold: f7 }), ...b8({ innerBounds: h5, thermalPadBounds: d7, sideGroups: l5 }), ...y8({ bounds: n7, innerBounds: h5, sideGroups: l5 })].flatMap((e55) =\u003e function({ nodeId: e56, bounds: t7, availableZ: n8, multiLayerThreshold: o10, regionType: i8, isNarrowPadGap: r9 = false, obstacleZ: s9 = [], connectedTo: a9 }) {\n if (!h8(t7))\n return [];\n const c7 = function(e57) {\n return { center: { x: (e57.minX + e57.maxX) / 2, y: (e57.minY + e57.maxY) / 2 }, width: e57.maxX - e57.minX, height: e57.maxY - e57.minY };\n }(t7), l7 = Math.min(c7.width, c7.height) \u003e o10, h7 = l7 ? [{ availableZ: n8.filter((e57) =\u003e !s9.includes(e57)), containsObstacle: false }, { availableZ: n8.filter((e57) =\u003e s9.includes(e57)), containsObstacle: true }].filter((e57) =\u003e e57.availableZ.length \u003e 0) : n8.map((e57) =\u003e ({ availableZ: [e57], containsObstacle: s9.includes(e57) }));\n return h7.map((t10) =\u003e ({ capacityMeshNodeId: h7.length === 1 ? e56 : l7 ? `${e56}:${t10.containsObstacle ? \"obstacle\" : \"free\"}` : `${e56}:z${t10.availableZ[0]}`, center: c7.center, width: c7.width, height: c7.height, layer: `z${t10.availableZ.join(\",\")}`, availableZ: t10.availableZ, _qfpRegionType: i8, _isNarrowQfpPadGap: r9, _containsObstacle: t10.containsObstacle, _connectedTo: t10.containsObstacle ? a9 : undefined }));\n }({ nodeId: `qfp_thermalpad:${u7}:${e55.key}`, bounds: e55.bounds, availableZ: i7, multiLayerThreshold: g7, regionType: e55.regionType, isNarrowPadGap: e55.isNarrowPadGap, obstacleZ: e55.obstacleZ, connectedTo: e55.connectedTo }));\n this.output = { routingRegions: _5 }, this.stats = { componentId: o7, layerCount: e54, viaDiameter: p7, obstacleMargin: m7, multiLayerThreshold: g7, narrowPadGapThreshold: f7, thermalPadCount: c5.length, perimeterPadCount: a7.length, innerCornerRectCount: _5.filter((e55) =\u003e e55.capacityMeshNodeId.includes(\":inner-corner-\")).length, narrowPadGapNodeCount: _5.filter((e55) =\u003e e55._isNarrowQfpPadGap).length, topPadCount: l5.top.length, rightPadCount: l5.right.length, bottomPadCount: l5.bottom.length, leftPadCount: l5.left.length, multiLayerNodeCount: _5.filter((e55) =\u003e e55.availableZ.length \u003e 1).length, totalMeshNodeCount: _5.length }, this.solved = true;\n }\n getOutput() {\n if (!this.output)\n throw new Error(\"QfpThermalPadTopologyGeneratorSolver has not solved yet\");\n return this.output;\n }\n});\nvar v8 = 0.000001;\nfunction I8(e54) {\n return e54.maxX - e54.minX \u003e v8 \u0026\u0026 e54.maxY - e54.minY \u003e v8;\n}\nfunction S8(e54, t4) {\n const n7 = [{ side: \"top\", distance: Math.abs(e54.center.y - t4.minY) }, { side: \"right\", distance: Math.abs(t4.maxX - e54.center.x) }, { side: \"bottom\", distance: Math.abs(t4.maxY - e54.center.y) }, { side: \"left\", distance: Math.abs(e54.center.x - t4.minX) }];\n return n7.sort((e55, t7) =\u003e e55.distance - t7.distance), n7[0].side;\n}\nfunction C8(e54, t4) {\n return e54.map((e55, n7) =\u003e ({ key: `pad:${e55.obstacleId ?? n7}`, bounds: Pe(e55), regionType: \"pad\", obstacleZ: s8(e55, t4), connectedTo: [...e55.connectedTo] }));\n}\nfunction P8(e54, t4) {\n return !!I8(e54) \u0026\u0026 Math.min(e54.maxX - e54.minX, e54.maxY - e54.minY) \u003c= t4;\n}\nfunction M8({ side: e54, sideObstacles: t4, bounds: n7, centralBounds: o7, narrowThreshold: i7 }) {\n const r7 = [];\n for (let s7 = 0;s7 \u003c t4.length - 1; s7++) {\n const a7 = Pe(t4[s7]), c5 = Pe(t4[s7 + 1]);\n let l5;\n l5 = e54 === \"top\" ? { minX: a7.maxX, maxX: c5.minX, minY: n7.minY, maxY: o7.minY } : e54 === \"right\" ? { minX: o7.maxX, maxX: n7.maxX, minY: a7.maxY, maxY: c5.minY } : e54 === \"bottom\" ? { minX: a7.maxX, maxX: c5.minX, minY: o7.maxY, maxY: n7.maxY } : { minX: n7.minX, maxX: o7.minX, minY: a7.maxY, maxY: c5.minY }, r7.push({ key: `${e54}-gap-${s7}`, bounds: l5, regionType: \"pad-gap\", isNarrowPadGap: P8(l5, i7) });\n }\n return r7;\n}\nfunction w8({ bounds: e54, centralBounds: t4, sideGroups: n7 }) {\n const o7 = n7.top[0] ? Pe(n7.top[0]) : null, i7 = n7.top.at(-1) ? Pe(n7.top.at(-1)) : null, r7 = n7.right[0] ? Pe(n7.right[0]) : null, s7 = n7.right.at(-1) ? Pe(n7.right.at(-1)) : null, a7 = n7.bottom[0] ? Pe(n7.bottom[0]) : null, c5 = n7.bottom.at(-1) ? Pe(n7.bottom.at(-1)) : null, l5 = n7.left[0] ? Pe(n7.left[0]) : null, h5 = n7.left.at(-1) ? Pe(n7.left.at(-1)) : null;\n return [{ key: \"corner-nw-outer\", regionType: \"corner\", bounds: { minX: e54.minX, maxX: t4.minX, minY: e54.minY, maxY: t4.minY } }, { key: \"corner-nw-top\", regionType: \"corner\", bounds: { minX: t4.minX, maxX: o7?.minX ?? t4.minX, minY: e54.minY, maxY: t4.minY } }, { key: \"corner-nw-left\", regionType: \"corner\", bounds: { minX: e54.minX, maxX: t4.minX, minY: t4.minY, maxY: l5?.minY ?? t4.minY } }, { key: \"corner-ne-outer\", regionType: \"corner\", bounds: { minX: t4.maxX, maxX: e54.maxX, minY: e54.minY, maxY: t4.minY } }, { key: \"corner-ne-top\", regionType: \"corner\", bounds: { minX: i7?.maxX ?? t4.maxX, maxX: t4.maxX, minY: e54.minY, maxY: t4.minY } }, { key: \"corner-ne-right\", regionType: \"corner\", bounds: { minX: t4.maxX, maxX: e54.maxX, minY: t4.minY, maxY: r7?.minY ?? t4.minY } }, { key: \"corner-se-outer\", regionType: \"corner\", bounds: { minX: t4.maxX, maxX: e54.maxX, minY: t4.maxY, maxY: e54.maxY } }, { key: \"corner-se-right\", regionType: \"corner\", bounds: { minX: t4.maxX, maxX: e54.maxX, minY: s7?.maxY ?? t4.maxY, maxY: t4.maxY } }, { key: \"corner-se-bottom\", regionType: \"corner\", bounds: { minX: c5?.maxX ?? t4.maxX, maxX: t4.maxX, minY: t4.maxY, maxY: e54.maxY } }, { key: \"corner-sw-outer\", regionType: \"corner\", bounds: { minX: e54.minX, maxX: t4.minX, minY: t4.maxY, maxY: e54.maxY } }, { key: \"corner-sw-bottom\", regionType: \"corner\", bounds: { minX: t4.minX, maxX: a7?.minX ?? t4.minX, minY: t4.maxY, maxY: e54.maxY } }, { key: \"corner-sw-left\", regionType: \"corner\", bounds: { minX: e54.minX, maxX: t4.minX, minY: h5?.maxY ?? t4.maxY, maxY: t4.maxY } }];\n}\nl9.register(class extends BaseSolver {\n constructor(e54) {\n super(), this.inputProblem = e54;\n }\n static componentKind = \"qfp\";\n output = null;\n getConstructorParams() {\n return [this.inputProblem];\n }\n _step() {\n if (this.output)\n return void (this.solved = true);\n const { layerCount: e54, obstacles: t4 } = this.inputProblem.inputSrj, { bounds: n7, componentId: o7 } = this.inputProblem.detectedComponent, i7 = c8(e54), r7 = t4.filter((e55) =\u003e e55.componentId === o7), s7 = r7.length \u003e 0 ? r7 : t4, a7 = function(e55, t7) {\n const n8 = { top: [], right: [], bottom: [], left: [] };\n for (const o10 of e55)\n n8[S8(o10, t7)].push(o10);\n return n8.top.sort((e56, t10) =\u003e e56.center.x - t10.center.x), n8.bottom.sort((e56, t10) =\u003e e56.center.x - t10.center.x), n8.left.sort((e56, t10) =\u003e e56.center.y - t10.center.y), n8.right.sort((e56, t10) =\u003e e56.center.y - t10.center.y), n8;\n }(s7, n7), c5 = function({ bounds: e55, sideGroups: t7 }) {\n return { minX: t7.left.length \u003e 0 ? Math.max(...t7.left.map((e56) =\u003e Pe(e56).maxX)) : e55.minX, maxX: t7.right.length \u003e 0 ? Math.min(...t7.right.map((e56) =\u003e Pe(e56).minX)) : e55.maxX, minY: t7.top.length \u003e 0 ? Math.max(...t7.top.map((e56) =\u003e Pe(e56).maxY)) : e55.minY, maxY: t7.bottom.length \u003e 0 ? Math.min(...t7.bottom.map((e56) =\u003e Pe(e56).minY)) : e55.maxY };\n }({ bounds: n7, sideGroups: a7 }), l5 = o7, h5 = this.inputProblem.viaDiameter ?? Yo(this.inputProblem.inputSrj).padDiameter, d7 = this.inputProblem.obstacleMargin ?? this.inputProblem.inputSrj.defaultObstacleMargin ?? 0.15, u7 = h5 + 2 * d7, p7 = this.inputProblem.inputSrj.minTraceWidth + 2 * d7, m7 = [{ key: \"center\", bounds: c5, regionType: \"center\" }, ...C8(s7, e54), ...M8({ side: \"top\", sideObstacles: a7.top, bounds: n7, centralBounds: c5, narrowThreshold: p7 }), ...M8({ side: \"right\", sideObstacles: a7.right, bounds: n7, centralBounds: c5, narrowThreshold: p7 }), ...M8({ side: \"bottom\", sideObstacles: a7.bottom, bounds: n7, centralBounds: c5, narrowThreshold: p7 }), ...M8({ side: \"left\", sideObstacles: a7.left, bounds: n7, centralBounds: c5, narrowThreshold: p7 }), ...w8({ bounds: n7, centralBounds: c5, sideGroups: a7 })].flatMap((e55) =\u003e function({ nodeId: e56, bounds: t7, availableZ: n8, multiLayerThreshold: o10, regionType: i8, isNarrowPadGap: r9 = false, obstacleZ: s9 = [], connectedTo: a9 }) {\n if (!I8(t7))\n return [];\n const c7 = function(e57) {\n return { center: { x: (e57.minX + e57.maxX) / 2, y: (e57.minY + e57.maxY) / 2 }, width: e57.maxX - e57.minX, height: e57.maxY - e57.minY };\n }(t7), l7 = Math.min(c7.width, c7.height) \u003e o10, h7 = l7 ? [{ availableZ: n8.filter((e57) =\u003e !s9.includes(e57)), containsObstacle: false }, { availableZ: n8.filter((e57) =\u003e s9.includes(e57)), containsObstacle: true }].filter((e57) =\u003e e57.availableZ.length \u003e 0) : n8.map((e57) =\u003e ({ availableZ: [e57], containsObstacle: s9.includes(e57) }));\n return h7.map((t10) =\u003e ({ capacityMeshNodeId: h7.length === 1 ? e56 : l7 ? `${e56}:${t10.containsObstacle ? \"obstacle\" : \"free\"}` : `${e56}:z${t10.availableZ[0]}`, center: c7.center, width: c7.width, height: c7.height, layer: `z${t10.availableZ.join(\",\")}`, availableZ: t10.availableZ, _qfpRegionType: i8, _isNarrowQfpPadGap: r9, _containsObstacle: t10.containsObstacle, _connectedTo: t10.containsObstacle ? a9 : undefined }));\n }({ nodeId: `qfp:${l5}:${e55.key}`, bounds: e55.bounds, availableZ: i7, multiLayerThreshold: u7, regionType: e55.regionType, isNarrowPadGap: e55.isNarrowPadGap, obstacleZ: e55.obstacleZ, connectedTo: e55.connectedTo }));\n this.output = { routingRegions: m7 }, this.stats = { componentId: o7, layerCount: e54, viaDiameter: h5, obstacleMargin: d7, multiLayerThreshold: u7, narrowPadGapThreshold: p7, narrowPadGapNodeCount: m7.filter((e55) =\u003e e55._isNarrowQfpPadGap).length, topPadCount: a7.top.length, rightPadCount: a7.right.length, bottomPadCount: a7.bottom.length, leftPadCount: a7.left.length, multiLayerNodeCount: m7.filter((e55) =\u003e e55.availableZ.length \u003e 1).length, totalMeshNodeCount: m7.length }, this.solved = true;\n }\n getOutput() {\n if (!this.output)\n throw new Error(\"QfpTopologyGeneratorSolver has not solved yet\");\n return this.output;\n }\n});\nvar R8 = 0.000001;\nfunction T8({ nodeId: e54, bounds: t4, availableZ: n7, multiLayerThreshold: o7, regionType: i7, obstacleZ: r7 = [], connectedTo: s7 }) {\n if (!function(e55) {\n return e55.maxX - e55.minX \u003e R8 \u0026\u0026 e55.maxY - e55.minY \u003e R8;\n }(t4))\n return [];\n const a7 = function(e55) {\n return { center: { x: (e55.minX + e55.maxX) / 2, y: (e55.minY + e55.maxY) / 2 }, width: e55.maxX - e55.minX, height: e55.maxY - e55.minY };\n }(t4), c5 = Math.min(a7.width, a7.height) \u003e o7, l5 = c5 ? [{ availableZ: n7.filter((e55) =\u003e !r7.includes(e55)), containsObstacle: false }, { availableZ: n7.filter((e55) =\u003e r7.includes(e55)), containsObstacle: true }].filter((e55) =\u003e e55.availableZ.length \u003e 0) : n7.map((e55) =\u003e ({ availableZ: [e55], containsObstacle: r7.includes(e55) }));\n return l5.map((t7) =\u003e ({ capacityMeshNodeId: l5.length === 1 ? e54 : c5 ? `${e54}:${t7.containsObstacle ? \"obstacle\" : \"free\"}` : `${e54}:z${t7.availableZ[0]}`, center: a7.center, width: a7.width, height: a7.height, layer: `z${t7.availableZ.join(\",\")}`, availableZ: t7.availableZ, _soicRegionType: i7, _containsObstacle: t7.containsObstacle, _connectedTo: t7.containsObstacle ? s7 : undefined }));\n}\nfunction E8(e54, t4) {\n let n7 = 0, o7 = Number.POSITIVE_INFINITY;\n for (let i7 = 0;i7 \u003c t4.length; i7++) {\n const r7 = Math.abs(e54 - t4[i7]);\n r7 \u003c o7 \u0026\u0026 (n7 = i7, o7 = r7);\n }\n return n7;\n}\nfunction A8(e54, t4) {\n return e54.map((e55, n7) =\u003e ({ key: `pad:${e55.obstacleId ?? n7}`, bounds: Pe(e55), regionType: \"pad\", obstacleZ: s8(e55, t4), connectedTo: [...e55.connectedTo] }));\n}\nfunction O8(e54, t4) {\n if (e54.componentId !== t4.componentId)\n return false;\n const { bounds: n7 } = t4;\n return e54.center.x \u003e= n7.minX \u0026\u0026 e54.center.x \u003c= n7.maxX \u0026\u0026 e54.center.y \u003e= n7.minY \u0026\u0026 e54.center.y \u003c= n7.maxY;\n}\nfunction k8({ detectedComponent: e54, inputSrj: t4 }) {\n const n7 = t4.obstacles.filter((t7) =\u003e O8(t7, e54)), o7 = Array.from({ length: t4.layerCount }, (e55, t7) =\u003e t7), i7 = o7.map((e55) =\u003e Co(e55, t4.layerCount)), r7 = Array.from(new Set(n7.flatMap((e55) =\u003e e55.connectedTo))), { bounds: s7 } = e54;\n return { obstacleId: `${e54.componentId}_component_bounds`, componentId: e54.componentId, type: \"rect\", layers: i7, __zLayers: o7, center: { x: (s7.minX + s7.maxX) / 2, y: (s7.minY + s7.maxY) / 2 }, width: s7.maxX - s7.minX, height: s7.maxY - s7.minY, connectedTo: r7 };\n}\nfunction D8(e54) {\n if (e54.length === 0)\n return { minX: 0, maxX: 0, minY: 0, maxY: 0 };\n let { POSITIVE_INFINITY: t4, NEGATIVE_INFINITY: n7, POSITIVE_INFINITY: o7, NEGATIVE_INFINITY: i7 } = Number;\n for (const r7 of e54) {\n const e55 = Pe(r7);\n t4 = Math.min(t4, e55.minX), n7 = Math.max(n7, e55.maxX), o7 = Math.min(o7, e55.minY), i7 = Math.max(i7, e55.maxY);\n }\n return { minX: t4, maxX: n7, minY: o7, maxY: i7 };\n}\nfunction L8(e54) {\n const t4 = e54.componentDetectionOutput ?? [], n7 = function({ detectedComponents: e55, inputSrj: t7 }) {\n return e55.map((e56) =\u003e {\n const n8 = t7.obstacles.filter((t10) =\u003e O8(t10, e56));\n return { componentId: e56.componentId, componentKind: e56.componentKind, memberObstacleIds: n8.map((t10, n10) =\u003e t10.obstacleId ?? `${e56.componentId}:member:${n10}`), memberObstacles: n8, replacementObstacle: k8({ detectedComponent: e56, inputSrj: t7 }) };\n });\n }({ detectedComponents: t4, inputSrj: e54.inputSrj }), o7 = e54.globalNoConnectionSrj ?? (t4.length \u003e 0 ? function({ detectedComponents: e55, inputSrj: t7 }) {\n return { ...structuredClone(t7), obstacles: [...t7.obstacles.filter((t10) =\u003e !e55.some((e56) =\u003e O8(t10, e56))), ...e55.map((e56) =\u003e k8({ detectedComponent: e56, inputSrj: t7 }))] };\n }({ detectedComponents: t4, inputSrj: e54.inputSrj }) : e54.inputSrj) ?? e54.brokenSrj?.componentsAsObstaclesSrj, i7 = e54.components ?? n7 ?? e54.brokenSrj?.components ?? [];\n if (!o7)\n throw new Error(\"MultiGraphTopologyPlannerSolver requires globalNoConnectionSrj or detected components\");\n return { globalNoConnectionSrj: o7, components: i7 };\n}\nfunction z8({ rects: e54, components: t4 }) {\n return e54 \u0026\u0026 t4.length !== 0 ? e54.filter((e55) =\u003e !function(e56) {\n return typeof e56.label == \"string\" \u0026\u0026 e56.label.startsWith(\"node \");\n }(e55) || !t4.some((t7) =\u003e function({ rect: e56, obstacle: t10 }) {\n if (!e56.center || e56.width === undefined || e56.height === undefined)\n return false;\n const n7 = 0.000000001, o7 = Le({ center: e56.center, width: e56.width, height: e56.height }), i7 = Le({ center: t10.center, width: t10.width, height: t10.height });\n return B8({ bounds: o7, outerBounds: i7, epsilon: n7 });\n }({ rect: e55, obstacle: t7.replacementObstacle }))) : e54;\n}\nfunction B8({ bounds: e54, outerBounds: t4, epsilon: n7 }) {\n return e54.minX \u003e= t4.minX - n7 \u0026\u0026 e54.maxX \u003c= t4.maxX + n7 \u0026\u0026 e54.minY \u003e= t4.minY - n7 \u0026\u0026 e54.maxY \u003c= t4.maxY + n7;\n}\nl9.register(class extends BaseSolver {\n constructor(e54) {\n super(), this.inputProblem = e54;\n }\n static componentKind = \"soic\";\n output = null;\n getConstructorParams() {\n return [this.inputProblem];\n }\n _step() {\n if (this.output)\n return void (this.solved = true);\n const { layerCount: e54, obstacles: t4 } = this.inputProblem.inputSrj, { bounds: n7, componentId: o7 } = this.inputProblem.detectedComponent, i7 = c8(e54), r7 = t4.filter((e55) =\u003e e55.componentId === o7), s7 = r7.length \u003e 0 ? r7 : t4, a7 = function(e55) {\n const t7 = a8(e55.map((e56) =\u003e e56.center.y)).length;\n return a8(e55.map((e56) =\u003e e56.center.x)).length === 2 \u0026\u0026 t7 !== 2 ? \"vertical-columns\" : \"horizontal-rows\";\n }(s7), c5 = function({ obstacles: e55, orientation: t7 }) {\n const n8 = { left: [], right: [], top: [], bottom: [] };\n if (t7 === \"vertical-columns\") {\n const t10 = a8(e55.map((e56) =\u003e e56.center.x));\n for (const o11 of e55)\n n8[E8(o11.center.x, t10) === 0 ? \"left\" : \"right\"].push(o11);\n return n8.left.sort((e56, t11) =\u003e e56.center.y - t11.center.y), n8.right.sort((e56, t11) =\u003e e56.center.y - t11.center.y), n8;\n }\n const o10 = a8(e55.map((e56) =\u003e e56.center.y));\n for (const t10 of e55)\n n8[E8(t10.center.y, o10) === 0 ? \"top\" : \"bottom\"].push(t10);\n return n8.top.sort((e56, t10) =\u003e e56.center.x - t10.center.x), n8.bottom.sort((e56, t10) =\u003e e56.center.x - t10.center.x), n8;\n }({ obstacles: s7, orientation: a7 }), l5 = function({ bounds: e55, orientation: t7, sideGroups: n8 }) {\n return t7 === \"vertical-columns\" ? { minX: Math.max(...n8.left.map((e56) =\u003e Pe(e56).maxX)), maxX: Math.min(...n8.right.map((e56) =\u003e Pe(e56).minX)), minY: e55.minY, maxY: e55.maxY } : { minX: e55.minX, maxX: e55.maxX, minY: Math.max(...n8.top.map((e56) =\u003e Pe(e56).maxY)), maxY: Math.min(...n8.bottom.map((e56) =\u003e Pe(e56).minY)) };\n }({ bounds: n7, orientation: a7, sideGroups: c5 }), h5 = o7, d7 = this.inputProblem.viaDiameter ?? Yo(this.inputProblem.inputSrj).padDiameter, u7 = this.inputProblem.obstacleMargin ?? this.inputProblem.inputSrj.defaultObstacleMargin ?? 0.15, p7 = 2 * (d7 + u7), m7 = a7 === \"vertical-columns\" ? [\"left\", \"right\"] : [\"top\", \"bottom\"], g7 = [{ key: \"center\", bounds: l5, regionType: \"center\" }, ...A8(s7, e54), ...m7.flatMap((e55) =\u003e function({ side: e56, sideObstacles: t7, bounds: n8, centralBounds: o10 }) {\n const i8 = [];\n for (let r9 = 0;r9 \u003c t7.length - 1; r9++) {\n const s9 = Pe(t7[r9]), a9 = Pe(t7[r9 + 1]);\n let c7;\n c7 = e56 === \"left\" ? { minX: n8.minX, maxX: o10.minX, minY: s9.maxY, maxY: a9.minY } : e56 === \"right\" ? { minX: o10.maxX, maxX: n8.maxX, minY: s9.maxY, maxY: a9.minY } : e56 === \"top\" ? { minX: s9.maxX, maxX: a9.minX, minY: n8.minY, maxY: o10.minY } : { minX: s9.maxX, maxX: a9.minX, minY: o10.maxY, maxY: n8.maxY }, i8.push({ key: `${e56}-gap-${r9}`, bounds: c7, regionType: \"pad-gap\" });\n }\n return i8;\n }({ side: e55, sideObstacles: c5[e55], bounds: n7, centralBounds: l5 }))], f7 = g7.flatMap((e55) =\u003e T8({ nodeId: `soic:${h5}:${e55.key}`, bounds: e55.bounds, availableZ: i7, multiLayerThreshold: p7, regionType: e55.regionType, obstacleZ: e55.obstacleZ, connectedTo: e55.connectedTo }));\n this.output = { routingRegions: f7 }, this.stats = { componentId: o7, layerCount: e54, orientation: a7, viaDiameter: d7, obstacleMargin: u7, multiLayerThreshold: p7, firstSidePadCount: c5[m7[0]].length, secondSidePadCount: c5[m7[1]].length, multiLayerNodeCount: f7.filter((e55) =\u003e e55.availableZ.length \u003e 1).length, totalMeshNodeCount: f7.length }, this.solved = true;\n }\n getOutput() {\n if (!this.output)\n throw new Error(\"SoicTopologyGeneratorSolver has not solved yet\");\n return this.output;\n }\n});\nvar F8 = class extends BaseSolver {\n constructor(e54) {\n super(), this.inputProblem = e54;\n }\n activeSubSolver = null;\n currentIndex = 0;\n componentMeshNodes = [];\n getConstructorParams() {\n return [this.inputProblem];\n }\n _step() {\n if (this.activeSubSolver) {\n if (this.activeSubSolver.step(), this.activeSubSolver.failed)\n return this.error = this.activeSubSolver.error, this.failed = true, void (this.activeSubSolver = null);\n if (!this.activeSubSolver.solved)\n return;\n return this.componentMeshNodes.push(this.activeSubSolver.getOutput().routingRegions), this.currentIndex += 1, void (this.activeSubSolver = null);\n }\n if (this.currentIndex \u003e= this.inputProblem.componentSrjs.length)\n return void (this.solved = true);\n const e54 = this.inputProblem.componentKinds[this.currentIndex], t4 = this.inputProblem.componentSrjs[this.currentIndex], n7 = { inputSrj: t4, detectedComponent: { componentId: this.inputProblem.componentIds[this.currentIndex], componentKind: e54, bounds: { __type: \"rect\", ...t4.bounds } }, viaDiameter: this.inputProblem.viaDiameter, obstacleMargin: this.inputProblem.obstacleMargin };\n this.activeSubSolver = l9.create(n7);\n }\n getOutput() {\n return { componentMeshNodes: this.componentMeshNodes };\n }\n visualize() {\n if (this.activeSubSolver)\n return this.activeSubSolver.visualize();\n const e54 = this.inputProblem.componentSrjs[this.currentIndex] ?? null, t4 = this.componentMeshNodes.flatMap((e55) =\u003e e55);\n return { rects: [...e54 ? [{ center: { x: (e54.bounds.minX + e54.bounds.maxX) / 2, y: (e54.bounds.minY + e54.bounds.maxY) / 2 }, width: e54.bounds.maxX - e54.bounds.minX, height: e54.bounds.maxY - e54.bounds.minY, fill: \"rgba(0,0,0,0)\", stroke: \"rgba(255,140,0,0.72)\", label: `active component ${this.inputProblem.componentIds[this.currentIndex] ?? this.currentIndex}` }, ...e54.obstacles.map((e55) =\u003e ({ center: e55.center, width: e55.width, height: e55.height, fill: \"rgba(255,140,0,0.10)\", stroke: \"rgba(255,140,0,0.30)\", label: e55.obstacleId ?? e55.componentId ?? \"obstacle\" }))] : [], ...t4.map((e55) =\u003e ({ ...dj(e55, { rectMargin: 0.01 }), fill: e55._containsObstacle ? \"rgba(255,0,0,0.14)\" : \"rgba(0,120,255,0.12)\", stroke: e55._containsObstacle ? \"rgba(255,0,0,0.34)\" : \"rgba(0,120,255,0.38)\" }))] };\n }\n};\nvar j8 = 0.001;\nfunction $8(e54) {\n const t4 = [...e54].sort((e55, t7) =\u003e e55 - t7), n7 = [];\n for (const e55 of t4) {\n const t7 = n7[n7.length - 1];\n (t7 === undefined || Math.abs(e55 - t7) \u003e j8) \u0026\u0026 n7.push(e55);\n }\n return n7;\n}\nfunction Y8(e54) {\n const t4 = Math.min(...e54), n7 = Math.max(...e54);\n return !(t4 \u003c= 0) \u0026\u0026 n7 / t4 \u003c= 1.01;\n}\nfunction X8(e54) {\n if (!function(e55) {\n return Y8(e55.map((e56) =\u003e e56.width)) \u0026\u0026 Y8(e55.map((e56) =\u003e e56.height));\n }(e54))\n return false;\n if (!function(e55) {\n return e55.every((e56) =\u003e {\n const t7 = Math.min(e56.width, e56.height), n8 = Math.max(e56.width, e56.height);\n return !(t7 \u003c= 0) \u0026\u0026 n8 / t7 \u003c= 1.5;\n });\n }(e54))\n return false;\n const t4 = $8(e54.map((e55) =\u003e e55.center.y)), n7 = $8(e54.map((e55) =\u003e e55.center.x)), o7 = t4.length, i7 = n7.length;\n if (o7 \u003c 3 || i7 \u003c 3)\n return false;\n const r7 = o7 * i7;\n return !((r7 \u003e 0 ? e54.length / r7 : 0) \u003c 0.5) \u0026\u0026 !!function(e55, t7, n8) {\n if (t7.length \u003c 3)\n return false;\n if (n8.length \u003c 3)\n return false;\n const o10 = new Set(t7.slice(1, -1)), i8 = new Set(n8.slice(1, -1));\n let r9 = 0;\n for (const t10 of e55)\n o10.has(t10.center.y) \u0026\u0026 i8.has(t10.center.x) \u0026\u0026 (r9 += 1);\n return r9 \u003e= 1;\n }(e54, t4, n7);\n}\nfunction H8(e54) {\n return [Math.round(e54.width / j8), Math.round(e54.height / j8), e54.layers.join(\",\")].join(\":\");\n}\nfunction V8(e54) {\n if (e54.length \u003c 3)\n return false;\n const t4 = [...e54].sort((e55, t7) =\u003e e55 - t7), n7 = t4[1] - t4[0];\n return !(n7 \u003c= j8) \u0026\u0026 t4.every((e55, o7) =\u003e o7 === 0 || Math.abs(e55 - t4[o7 - 1] - n7) \u003c= j8);\n}\nfunction W8(e54) {\n const t4 = function(e55) {\n const t7 = new Map;\n for (const n8 of e55) {\n const e56 = Math.round(n8.center.y / j8), o7 = Math.round(n8.center.x / j8), i7 = t7.get(e56) ?? { y: n8.center.y, obstaclesByX: new Map };\n i7.obstaclesByX.set(o7, n8), t7.set(e56, i7);\n }\n return [...t7.values()];\n }(e54);\n let n7 = [];\n for (const e55 of t4) {\n const o7 = [...e55.obstaclesByX.keys()];\n if (!V8([...e55.obstaclesByX.values()].map((e56) =\u003e e56.center.x)))\n continue;\n const i7 = t4.filter((e56) =\u003e o7.every((t7) =\u003e e56.obstaclesByX.has(t7)));\n if (!V8(i7.map((e56) =\u003e e56.y)))\n continue;\n const r7 = i7.flatMap((e56) =\u003e o7.map((t7) =\u003e e56.obstaclesByX.get(t7)));\n r7.length \u003e n7.length \u0026\u0026 (n7 = r7);\n }\n return n7;\n}\nfunction G8(e54) {\n if (X8(e54))\n return e54;\n const t4 = Map.groupBy(e54, H8);\n let n7 = [];\n for (const e55 of t4.values()) {\n const t7 = W8(e55);\n t7.length \u003e n7.length \u0026\u0026 (n7 = t7);\n }\n return n7.length \u003e 0 ? n7 : null;\n}\nfunction U8(e54) {\n const t4 = Math.min(e54.width, e54.height), n7 = Math.max(e54.width, e54.height);\n return t4 \u003e 0 \u0026\u0026 n7 / t4 \u003e= 1.5;\n}\nfunction Z8({ perimeterPadObstacles: e54, thermalPadObstacles: t4 }) {\n if (t4.length === 0)\n return true;\n if (t4.length \u003e 4)\n return false;\n const n7 = D8(e54), o7 = n7.maxX - n7.minX, i7 = n7.maxY - n7.minY, r7 = n7.minX + 0.2 * o7, s7 = n7.maxX - 0.2 * o7, a7 = n7.minY + 0.2 * i7, c5 = n7.maxY - 0.2 * i7, l5 = Math.min(...e54.map((e55) =\u003e Math.min(e55.width, e55.height)));\n return t4.every((e55) =\u003e {\n const t7 = Math.min(e55.width, e55.height);\n return e55.center.x \u003e= r7 \u0026\u0026 e55.center.x \u003c= s7 \u0026\u0026 e55.center.y \u003e= a7 \u0026\u0026 e55.center.y \u003c= c5 \u0026\u0026 t7 \u003e l5;\n });\n}\nfunction q8(e54) {\n if (e54.length \u003c 12)\n return false;\n if (e54.length \u003e 32)\n return false;\n const { counts: t4, maxNearestSideRatio: n7 } = function(e55) {\n const t7 = D8(e55), n8 = t7.maxX - t7.minX, o7 = t7.maxY - t7.minY, i7 = { top: 0, right: 0, bottom: 0, left: 0 };\n if (n8 \u003c= 0 || o7 \u003c= 0)\n return { counts: i7, maxNearestSideRatio: 1 };\n let r7 = 0;\n for (const s7 of e55) {\n const e56 = s7.width \u003e s7.height, a7 = [{ side: \"top\", distance: Math.abs(s7.center.y - t7.minY), axisSpan: o7, orientationMatches: !e56 }, { side: \"right\", distance: Math.abs(t7.maxX - s7.center.x), axisSpan: n8, orientationMatches: e56 }, { side: \"bottom\", distance: Math.abs(t7.maxY - s7.center.y), axisSpan: o7, orientationMatches: !e56 }, { side: \"left\", distance: Math.abs(s7.center.x - t7.minX), axisSpan: n8, orientationMatches: e56 }].filter((e57) =\u003e e57.orientationMatches).sort((e57, t10) =\u003e e57.distance - t10.distance)[0];\n i7[a7.side] += 1, r7 = Math.max(r7, a7.distance / a7.axisSpan);\n }\n return { counts: i7, maxNearestSideRatio: r7 };\n }(e54);\n return t4.top \u003e= 3 \u0026\u0026 t4.right \u003e= 3 \u0026\u0026 t4.bottom \u003e= 3 \u0026\u0026 t4.left \u003e= 3 \u0026\u0026 n7 \u003c= 0.25;\n}\nfunction J8(e54) {\n const t4 = function(e55) {\n return e55.filter(U8);\n }(e54);\n return { perimeterPadObstacles: t4, thermalPadObstacles: e54.filter((e55) =\u003e !U8(e55)) };\n}\nfunction Q8(e54) {\n const t4 = Math.min(...e54), n7 = Math.max(...e54);\n return !(t4 \u003c= 0) \u0026\u0026 n7 / t4 \u003c= 1.01;\n}\nfunction K8(e54, t4) {\n let n7 = 0, o7 = Number.POSITIVE_INFINITY;\n for (let i7 = 0;i7 \u003c t4.length; i7++) {\n const r7 = Math.abs(e54 - t4[i7]);\n r7 \u003c o7 \u0026\u0026 (n7 = i7, o7 = r7);\n }\n return n7;\n}\nfunction e72({ memberObstacles: e54, inputSrj: t4 }) {\n if (!function(e55) {\n return Q8(e55.map((e56) =\u003e e56.width)) \u0026\u0026 Q8(e55.map((e56) =\u003e e56.height));\n }(e54))\n return false;\n const n7 = $8(e54.map((e55) =\u003e e55.center.y)), o7 = $8(e54.map((e55) =\u003e e55.center.x));\n if (!(n7.length === 2 \u0026\u0026 o7.length \u003e= 4 || o7.length === 2 \u0026\u0026 n7.length \u003e= 4))\n return false;\n const i7 = function({ memberObstacles: e55, rowAxisValues: t7, columnAxisValues: n8 }) {\n if (t7.length === 2 \u0026\u0026 n8.length \u003e= 4) {\n const n10 = [[], []];\n for (const o10 of e55)\n n10[K8(o10.center.y, t7)].push(o10);\n return Math.min(...n10[1].map((e56) =\u003e e56.center.y - e56.height / 2)) - Math.max(...n10[0].map((e56) =\u003e e56.center.y + e56.height / 2));\n }\n if (n8.length === 2 \u0026\u0026 t7.length \u003e= 4) {\n const t10 = [[], []];\n for (const o10 of e55)\n t10[K8(o10.center.x, n8)].push(o10);\n return Math.min(...t10[1].map((e56) =\u003e e56.center.x - e56.width / 2)) - Math.max(...t10[0].map((e56) =\u003e e56.center.x + e56.width / 2));\n }\n return null;\n }({ memberObstacles: e54, rowAxisValues: n7, columnAxisValues: o7 });\n if (i7 === null)\n return false;\n return i7 \u003e 2 * (Yo(t4).padDiameter + (t4.defaultObstacleMargin ?? 0.15));\n}\nvar t7 = [class e55 {\n constructor(e54) {\n this.params = e54;\n }\n static componentKind = \"qfp_thermalpad\";\n componentKind = e55.componentKind;\n static isMatch({ memberObstacles: e54 }) {\n return function(e59) {\n const { perimeterPadObstacles: t4, thermalPadObstacles: n7 } = J8(e59);\n return n7.length !== 0 \u0026\u0026 !!q8(t4) \u0026\u0026 Z8({ perimeterPadObstacles: t4, thermalPadObstacles: n7 });\n }(e54);\n }\n}, class e56 {\n constructor(e54) {\n this.params = e54;\n }\n static componentKind = \"qfp\";\n componentKind = e56.componentKind;\n static isMatch({ memberObstacles: e54 }) {\n return function(e59) {\n const { perimeterPadObstacles: t4, thermalPadObstacles: n7 } = J8(e59);\n return !(n7.length \u003e 0) \u0026\u0026 !!Z8({ perimeterPadObstacles: t4, thermalPadObstacles: n7 }) \u0026\u0026 q8(t4);\n }(e54);\n }\n}, class e57 {\n constructor(e54) {\n this.params = e54;\n }\n static componentKind = \"soic\";\n componentKind = e57.componentKind;\n static isMatch(e54) {\n return e72(e54);\n }\n}, class e58 {\n constructor(e54) {\n this.params = e54;\n }\n static componentKind = \"bga\";\n componentKind = e58.componentKind;\n static isMatch({ memberObstacles: e54 }) {\n return function(e59) {\n return G8(e59) !== null;\n }(e54);\n }\n}];\nfunction n7(e54) {\n return function(e59) {\n for (const t4 of t7)\n if (t4.isMatch(e59))\n return new t4(e59);\n return null;\n }(e54)?.componentKind ?? null;\n}\nvar o7 = class extends BaseSolver {\n inputSrj;\n initialized = false;\n groupedComponentObstacles = {};\n groupedComponentKinds = {};\n unprocessedComponentIds = [];\n detectedComponents = [];\n currentComponentId = null;\n currentMemberObstacles = [];\n output = null;\n constructor({ inputSrj: e54 }) {\n super(), this.inputSrj = e54;\n }\n getConstructorParams() {\n return [{ inputSrj: this.inputSrj }];\n }\n _step() {\n this.initialized ? this.output ? this.solved = true : this.currentComponentId !== null || this.unprocessedComponentIds.length \u003e 0 ? this.processNextComponent() : (this.finalizeOutput(), this.solved = true) : this.initializeDetectionState();\n }\n getOutput() {\n if (!this.output)\n throw new Error(\"ComponentDetectionSolver has not solved yet\");\n return this.output;\n }\n visualize() {\n const e54 = [];\n e54.push(...this.inputSrj.obstacles.filter((e59) =\u003e !e59.componentId).map((e59) =\u003e ({ center: e59.center, width: e59.width, height: e59.height, fill: \"rgba(120, 120, 120, 0.10)\", stroke: \"rgba(120, 120, 120, 0.40)\", label: e59.obstacleId, layer: e59.layers.join(\",\"), step: 0 })));\n const t4 = new Set(this.detectedComponents.map((e59) =\u003e e59.componentId));\n for (const n8 of this.inputSrj.obstacles) {\n if (!n8.componentId)\n continue;\n if (t4.has(n8.componentId))\n continue;\n const o10 = n8.componentId === this.currentComponentId, i7 = Oo(n8.componentId), r7 = this.groupedComponentKinds[n8.componentId];\n e54.push({ center: n8.center, width: n8.width, height: n8.height, fill: Ao(i7, o10 ? 0.55 : 0.82), stroke: Ao(i7, o10 ? 0.1 : 0.45), label: r7 ? `${n8.componentId} ${r7.toUpperCase()}` : n8.componentId, layer: n8.layers.join(\",\"), step: o10 ? 1 : 0 });\n }\n for (const t10 of this.detectedComponents) {\n const n8 = Oo(t10.componentId);\n e54.push({ center: { x: (t10.bounds.minX + t10.bounds.maxX) / 2, y: (t10.bounds.minY + t10.bounds.maxY) / 2 }, width: t10.bounds.maxX - t10.bounds.minX, height: t10.bounds.maxY - t10.bounds.minY, fill: Ao(n8, 0.88), stroke: Ao(n8, 0.1), label: `${t10.componentId} ${t10.componentKind.toUpperCase()} region`, step: 2 });\n }\n return { title: this.getVisualizationTitle(), rects: e54, lines: [], points: [], circles: [] };\n }\n preview() {\n return this.visualize();\n }\n initializeDetectionState() {\n this.initialized = true, this.groupedComponentKinds = {}, this.groupedComponentObstacles = this.groupObstaclesByComponentId({ obstacles: this.inputSrj.obstacles }), this.unprocessedComponentIds = Object.keys(this.groupedComponentObstacles).sort(), this.detectedComponents = [], this.currentComponentId = null, this.currentMemberObstacles = [], this.output = null;\n }\n processNextComponent() {\n if (!this.currentComponentId) {\n const e54 = this.unprocessedComponentIds.shift();\n return e54 ? (this.currentComponentId = e54, void (this.currentMemberObstacles = this.groupedComponentObstacles[e54] ?? [])) : (this.currentComponentId = null, void (this.currentMemberObstacles = []));\n }\n if (this.currentMemberObstacles.length === 0)\n return this.currentComponentId = null, void (this.currentMemberObstacles = []);\n this.detectedComponents.push(this.createDetectedComponent({ componentId: this.currentComponentId, componentKind: this.groupedComponentKinds[this.currentComponentId], memberObstacles: this.currentMemberObstacles })), this.currentComponentId = null, this.currentMemberObstacles = [];\n }\n finalizeOutput() {\n this.output = this.detectedComponents.map((e54) =\u003e ({ ...e54, bounds: { ...e54.bounds } })), this.stats = { initialized: this.initialized, totalComponentCount: Object.keys(this.groupedComponentObstacles).length, detectedComponentCount: this.detectedComponents.length, detectedBgaComponentCount: this.detectedComponents.filter((e54) =\u003e e54.componentKind === \"bga\").length, detectedQfpComponentCount: this.detectedComponents.filter((e54) =\u003e e54.componentKind === \"qfp\").length, detectedQfpComponentIds: this.detectedComponents.filter((e54) =\u003e e54.componentKind === \"qfp\").map((e54) =\u003e e54.componentId), detectedQfpThermalPadComponentCount: this.detectedComponents.filter((e54) =\u003e e54.componentKind === \"qfp_thermalpad\").length, detectedQfpThermalPadComponentIds: this.detectedComponents.filter((e54) =\u003e e54.componentKind === \"qfp_thermalpad\").map((e54) =\u003e e54.componentId), detectedSoicComponentCount: this.detectedComponents.filter((e54) =\u003e e54.componentKind === \"soic\").length, detectedSoicComponentIds: this.detectedComponents.filter((e54) =\u003e e54.componentKind === \"soic\").map((e54) =\u003e e54.componentId), remainingComponentCount: this.unprocessedComponentIds.length, hasActiveComponent: this.currentComponentId !== null };\n }\n groupObstaclesByComponentId({ obstacles: e54 }) {\n const t4 = {}, n8 = {};\n for (const n10 of e54)\n n10.componentId \u0026\u0026 (t4[n10.componentId] ??= [], t4[n10.componentId].push(n10));\n const o10 = Object.entries(t4).flatMap(([e59, t10]) =\u003e {\n const o11 = this.inputSrj.bounds;\n if (t10.some((e60) =\u003e !B8({ bounds: Pe(e60), outerBounds: o11, epsilon: 0 })))\n return [];\n const i7 = n7({ memberObstacles: t10, inputSrj: this.inputSrj });\n if (!i7)\n return [];\n n8[e59] = i7;\n return [[e59, i7 === \"bga\" ? G8(t10) : t10]];\n });\n return this.groupedComponentKinds = n8, Object.fromEntries(o10);\n }\n createDetectedComponent({ componentId: e54, componentKind: t4, memberObstacles: n8 }) {\n return { componentId: e54, componentKind: t4, bounds: { __type: \"rect\", ...D8(n8) } };\n }\n getVisualizationTitle() {\n const e54 = Object.keys(this.groupedComponentObstacles).length || new Set(this.inputSrj.obstacles.map((e59) =\u003e e59.componentId).filter((e59) =\u003e Boolean(e59))).size, t4 = this.detectedComponents.length;\n return this.initialized ? this.output || this.solved ? `Component Detection: done ${t4}/${e54}` : this.currentComponentId !== null || this.unprocessedComponentIds.length \u003e 0 ? `Component Detection: ${t4}/${e54} processed` : `Component Detection: finalizing ${t4}/${e54}` : \"Component Detection: setup\";\n }\n};\nvar i7 = (e54) =\u003e e54.componentId \u0026\u0026 e54.obstacleId ? `${e54.componentId}\n${e54.obstacleId}` : e54.componentId ?? e54.obstacleId ?? \"obstacle\";\nvar r7 = class extends BasePipelineSolver {\n rectBoundsComponentDetection;\n pipelineDef = [definePipelineStep(\"rectBoundsComponentDetection\", o7, (e54) =\u003e [{ inputSrj: e54.inputProblem.inputSrj }])];\n getConstructorParams() {\n return [this.inputProblem];\n }\n getOutput() {\n const e54 = this.getStageOutput(\"rectBoundsComponentDetection\");\n if (!e54)\n throw new Error(\"ComponentDetectionSolver has not solved yet\");\n return e54;\n }\n initialVisualize() {\n const { bounds: e54 } = this.inputProblem.inputSrj;\n return { title: \"Component Detection: board and grouped component pads\", rects: [{ center: { x: (e54.minX + e54.maxX) / 2, y: (e54.minY + e54.maxY) / 2 }, width: e54.maxX - e54.minX, height: e54.maxY - e54.minY, fill: \"rgba(0, 0, 0, 0)\", stroke: \"rgba(40, 40, 40, 0.7)\", label: \"Board bounds\", step: 0 }, ...this.inputProblem.inputSrj.obstacles.map((e59) =\u003e {\n const t4 = e59.componentId ? Oo(e59.componentId) : null;\n return { center: e59.center, width: e59.width, height: e59.height, fill: t4 ? Ao(t4, 0.72) : \"rgba(120, 120, 120, 0.10)\", stroke: t4 ? Ao(t4, 0.28) : \"rgba(120, 120, 120, 0.40)\", label: i7(e59), layer: e59.layers.join(\",\"), step: e59.componentId ? 1 : 0 };\n })], lines: [], points: [], circles: [] };\n }\n};\nfunction a7(e54) {\n (function(e59) {\n if (!Number.isInteger(e59.layerCount))\n throw new Error(\"TopologyMergingSolver: layerCount must be an integer\");\n if (e59.layerCount \u003c= 0)\n throw new Error(\"TopologyMergingSolver: layerCount must be positive\");\n if (e59.nodeGroups.length === 0)\n throw new Error(\"TopologyMergingSolver: at least one node group is required\");\n const t10 = new Set;\n let n10 = 0;\n for (const o10 of e59.nodeGroups) {\n if (t10.has(o10.groupId))\n throw new Error(`TopologyMergingSolver: duplicate topology group id \"${o10.groupId}\"`);\n if (t10.add(o10.groupId), n10 += o10.nodes.length, o10.nodes.length === 0)\n throw new Error(`TopologyMergingSolver: topology group \"${o10.groupId}\" is empty`);\n const i8 = new Set;\n for (const t11 of o10.nodes) {\n if (i8.has(t11.capacityMeshNodeId))\n throw new Error(`TopologyMergingSolver: duplicate node id \"${t11.capacityMeshNodeId}\" in group \"${o10.groupId}\"`);\n i8.add(t11.capacityMeshNodeId), c7({ node: t11, groupId: o10.groupId, layerCount: e59.layerCount });\n }\n }\n if (n10 === 0)\n throw new Error(\"TopologyMergingSolver: topology node groups are empty\");\n })(e54);\n const t4 = [], n8 = new Map;\n for (let o10 = 0;o10 \u003c e54.nodeGroups.length; o10++) {\n const i8 = e54.nodeGroups[o10];\n for (const e59 of i8.nodes) {\n const r9 = { sourceKey: `${i8.groupId}:${e59.capacityMeshNodeId}`, groupIndex: o10, node: e59, bounds: ai(e59) };\n t4.push(r9), n8.set(r9.sourceKey, r9);\n }\n }\n return { preparedNodes: t4, preparedNodeBySourceKey: n8 };\n}\nfunction c7({ node: e54, groupId: t4, layerCount: n8 }) {\n if (!li(ai(e54)))\n throw new Error(`TopologyMergingSolver: node \"${e54.capacityMeshNodeId}\" in group \"${t4}\" has invalid bounds`);\n if (e54.availableZ.length === 0)\n throw new Error(`TopologyMergingSolver: node \"${e54.capacityMeshNodeId}\" in group \"${t4}\" has no available layers`);\n const o10 = [...new Set(e54.availableZ)].sort((e59, t10) =\u003e e59 - t10), i8 = o10.some((e59) =\u003e !Number.isInteger(e59) || e59 \u003c 0 || e59 \u003e= n8), r9 = o10.length === e54.availableZ.length \u0026\u0026 o10.every((t10, n10) =\u003e t10 === e54.availableZ[n10]);\n if (i8 || !r9)\n throw new Error(`TopologyMergingSolver: node \"${e54.capacityMeshNodeId}\" in group \"${t4}\" has invalid or unsorted availableZ`);\n}\nvar l7 = 0.00001;\nvar h7 = 0.00004;\nfunction d7({ regions: e54, preparedNodeBySourceKey: t4, nodeGroups: n8, provenance: o10, preserveSourceIds: i8 = true }) {\n i8 \u0026\u0026 (o10.groupIndexesByNodeId.clear(), o10.sourceKeysByNodeId.clear());\n const r9 = [...e54].sort((e59, t10) =\u003e e59.bounds.minX - t10.bounds.minX || e59.bounds.minY - t10.bounds.minY || e59.bounds.maxX - t10.bounds.maxX || e59.bounds.maxY - t10.bounds.maxY || e59.availableZ[0] - t10.availableZ[0]), s7 = new Set;\n return r9.map((e59, r10) =\u003e {\n const a9 = e59.sourceKeys.map((e60) =\u003e {\n const n10 = t4.get(e60);\n if (!n10)\n throw new Error(`TopologyMergingSolver: missing source node for \"${e60}\"`);\n return n10;\n }), c5 = a9.map(({ node: e60 }) =\u003e e60), l5 = function({ sourceNodes: e60, isComponentTopologyNode: t10 }) {\n if (e60.length === 1)\n return { _isComponentTopologyNode: !!t10 || e60[0]._isComponentTopologyNode };\n const n10 = e60.map((e61) =\u003e e61.capacityMeshNodeId), o11 = u7(e60.map((e61) =\u003e e61._targetConnectionName), \"target connection\", n10), i9 = u7(e60.map((e61) =\u003e e61._offBoardConnectionId), \"off-board connection\", n10), r11 = u7(e60.map((e61) =\u003e e61._offboardNetName), \"off-board net\", n10), s9 = Array.from(new Set(e60.flatMap((e61) =\u003e e61._offBoardConnectedCapacityMeshNodeIds ?? []))), a10 = Array.from(new Set(e60.flatMap((e61) =\u003e e61._connectedTo ?? [])));\n return { _containsObstacle: e60.some((e61) =\u003e e61._containsObstacle) || undefined, _completelyInsideObstacle: e60.some((e61) =\u003e e61._completelyInsideObstacle) || undefined, _containsTarget: e60.some((e61) =\u003e e61._containsTarget) || undefined, _targetConnectionName: o11, _isVirtualOffboard: e60.some((e61) =\u003e e61._isVirtualOffboard) || undefined, _offboardNetName: r11, _offBoardConnectionId: i9, _offBoardConnectedCapacityMeshNodeIds: s9.length \u003e 0 ? s9 : undefined, _qfpRegionType: p7(e60.map((e61) =\u003e e61._qfpRegionType)), _isNarrowQfpPadGap: e60.some((e61) =\u003e e61._isNarrowQfpPadGap) || undefined, _soicRegionType: p7(e60.map((e61) =\u003e e61._soicRegionType)), _isComponentTopologyNode: t10 || undefined, _connectedTo: a10.length \u003e 0 ? a10 : undefined };\n }({ sourceNodes: c5, isComponentTopologyNode: e59.topologyMode !== \"free\" \u0026\u0026 a9.some(({ groupIndex: e60 }) =\u003e n8[e60].isComponent) });\n e59.topologyMode === \"free\" \u0026\u0026 (l5._isComponentTopologyNode = undefined, l5._isNarrowQfpPadGap = undefined);\n const h5 = i8 \u0026\u0026 a9.length === 1 ? a9[0].node : null, d9 = Boolean(h5 \u0026\u0026 function({ region: e60, sourceNode: t10, usedNodeIds: n10 }) {\n const o11 = ai(t10), i9 = Math.abs(e60.bounds.minX - o11.minX) \u003c= l7 \u0026\u0026 Math.abs(e60.bounds.maxX - o11.maxX) \u003c= l7 \u0026\u0026 Math.abs(e60.bounds.minY - o11.minY) \u003c= l7 \u0026\u0026 Math.abs(e60.bounds.maxY - o11.maxY) \u003c= l7, r11 = e60.availableZ.length === t10.availableZ.length \u0026\u0026 e60.availableZ.every((e61, n11) =\u003e e61 === t10.availableZ[n11]);\n return i9 \u0026\u0026 r11 \u0026\u0026 !n10.has(t10.capacityMeshNodeId);\n }({ region: e59, sourceNode: h5, usedNodeIds: s7 }));\n let u7 = d9 ? h5.capacityMeshNodeId : `topology_merge_${r10}`;\n for (;s7.has(u7); )\n u7 = `${u7}_next`;\n return s7.add(u7), i8 \u0026\u0026 (o10.groupIndexesByNodeId.set(u7, [...new Set(a9.map(({ groupIndex: e60 }) =\u003e e60))]), o10.sourceKeysByNodeId.set(u7, [...e59.sourceKeys])), { ...h5 ?? c5[0], ...l5, capacityMeshNodeId: u7, center: { x: (e59.bounds.minX + e59.bounds.maxX) / 2, y: (e59.bounds.minY + e59.bounds.maxY) / 2 }, width: e59.bounds.maxX - e59.bounds.minX, height: e59.bounds.maxY - e59.bounds.minY, layer: `z${e59.availableZ.join(\",\")}`, availableZ: [...e59.availableZ], _adjacentNodeIds: undefined, _parent: undefined, _strawNode: undefined, _strawParentCapacityMeshNodeId: undefined };\n });\n}\nfunction u7(e54, t4, n8) {\n const o10 = Array.from(new Set(e54.filter((e59) =\u003e e59 !== undefined)));\n if (o10.length \u003e 1)\n throw new Error(`TopologyMergingSolver: conflicting ${t4} values for overlapping source nodes ${n8.join(\", \")}`);\n return o10[0];\n}\nfunction p7(e54) {\n const t4 = Array.from(new Set(e54.filter((e59) =\u003e e59 !== undefined)));\n return t4.length === 1 ? t4[0] : undefined;\n}\nfunction m7({ node: e54, sourceKey: t4, preparedNodeBySourceKey: n8 }) {\n const o10 = n8.get(t4);\n if (!o10)\n throw new Error(`TopologyMergingSolver: missing source node for output \"${e54.capacityMeshNodeId}\"`);\n const i8 = ai(e54), r9 = i8.minX \u003e= o10.bounds.minX - h7 \u0026\u0026 i8.maxX \u003c= o10.bounds.maxX + h7 \u0026\u0026 i8.minY \u003e= o10.bounds.minY - h7 \u0026\u0026 i8.maxY \u003c= o10.bounds.maxY + h7, s7 = e54.availableZ.every((e59) =\u003e o10.node.availableZ.includes(e59));\n if (!r9 || !s7)\n throw new Error(`TopologyMergingSolver: output node \"${e54.capacityMeshNodeId}\" escapes its source geometry or layers`);\n}\nfunction g7({ groupIndexesA: e54, groupIndexesB: t4, sourceKeysA: n8, sourceKeysB: o10, sharedLayers: i8, preparedNodeBySourceKey: r9 }) {\n if (e54.length !== 1 || t4.length !== 1 || e54[0] !== t4[0] || n8.length !== 1 || o10.length !== 1 || n8[0] === o10[0])\n return false;\n const s7 = r9.get(n8[0]), a9 = r9.get(o10[0]);\n if (!s7 || !a9 || i8.length === 0)\n return false;\n return i8.some((e59) =\u003e s7.node.availableZ.includes(e59) \u0026\u0026 a9.node.availableZ.includes(e59)) \u0026\u0026 ci(s7.bounds, a9.bounds) !== null;\n}\nfunction f7(e54) {\n const t4 = [...e54].sort((e59, t10) =\u003e e59 - t10), n8 = [];\n for (const e59 of t4) {\n const t10 = n8[n8.length - 1];\n (t10 === undefined || Math.abs(e59 - t10) \u003e l7) \u0026\u0026 n8.push(e59);\n }\n return n8;\n}\nfunction _7(e54, t4) {\n return t4.x \u003e= e54.minX - l7 \u0026\u0026 t4.x \u003c= e54.maxX + l7 \u0026\u0026 t4.y \u003e= e54.minY - l7 \u0026\u0026 t4.y \u003c= e54.maxY + l7;\n}\nfunction y7({ coveringNodes: e54, nodeGroups: t4, layerCount: n8, allowBlindAndBuriedVias: o10 = false }) {\n const i8 = new Map, r9 = new Set;\n let s7 = -2, a9 = 0;\n for (let c5 = 0;c5 \u003c n8; c5++) {\n const n10 = e54.filter(({ node: e59 }) =\u003e e59.availableZ.includes(c5)).sort((e59, t10) =\u003e e59.sourceKey.localeCompare(t10.sourceKey));\n if (n10.length === 0)\n continue;\n const l5 = new Set(n10.map(({ groupIndex: e59 }) =\u003e e59)), h5 = n10.filter(({ node: e59 }) =\u003e e59._containsObstacle \u0026\u0026 e59._containsTarget), d9 = h5.filter(({ groupIndex: e59 }) =\u003e !t4[e59].isComponent), u9 = new Set(h5.map(({ groupIndex: e59 }) =\u003e e59)), p9 = h5.length \u003e 0 ? d9.length \u003e 0 || u9.size === 1 ? \"target-passthrough\" : \"target-merged\" : l5.size === 1 ? \"passthrough\" : \"merged\";\n if (p9 === \"target-passthrough\" \u0026\u0026 d9.length \u003e 0)\n for (const { sourceKey: e59, groupIndex: n11 } of h5)\n t4[n11].isComponent \u0026\u0026 r9.add(e59);\n const m9 = o10 \u0026\u0026 n10.every(({ node: e59 }) =\u003e !e59._containsObstacle \u0026\u0026 !e59._containsTarget \u0026\u0026 !e59._isVirtualOffboard);\n m9 \u0026\u0026 (c5 !== s7 + 1 \u0026\u0026 (a9 = c5), s7 = c5);\n const g10 = S7({ topologyMode: p9, nodesOnLayer: n10, targetObstacleNodes: h5, globalTargetObstacleNodes: d9 });\n for (const e59 of g10) {\n const t10 = m9 ? `free:${a9}` : JSON.stringify({ mode: p9, sourceKeys: e59 }), n11 = i8.get(t10);\n n11 ? (n11.availableZ.at(-1) !== c5 \u0026\u0026 n11.availableZ.push(c5), n11.sourceKeys = [...new Set([...n11.sourceKeys, ...e59])].sort()) : i8.set(t10, { availableZ: [c5], sourceKeys: e59, topologyMode: m9 ? \"free\" : p9, topologySignature: t10 });\n }\n }\n return { layerTopologies: [...i8.values()], overruledTargetSourceKeys: [...r9] };\n}\nfunction b7(e54) {\n return JSON.stringify({ availableZ: e54.availableZ, topologySignature: e54.topologySignature });\n}\nfunction x7(e54) {\n return JSON.stringify({ mergeKey: b7(e54), minY: e54.bounds.minY.toPrecision(15), maxY: e54.bounds.maxY.toPrecision(15) });\n}\nfunction v7(e54) {\n return JSON.stringify({ mergeKey: b7(e54), minX: e54.bounds.minX.toPrecision(15), maxX: e54.bounds.maxX.toPrecision(15) });\n}\nfunction I7(e54, t4) {\n const n8 = new Map;\n for (const o10 of e54) {\n const e59 = t4 === \"horizontal\" ? x7(o10) : v7(o10), i8 = n8.get(e59) ?? [];\n i8.push(o10), n8.set(e59, i8);\n }\n return [...n8.values()].flatMap((e59) =\u003e function(e60, t10) {\n const n10 = [...e60].sort((e61, n11) =\u003e t10 === \"horizontal\" ? e61.bounds.minX - n11.bounds.minX : e61.bounds.minY - n11.bounds.minY), o10 = [];\n for (const e61 of n10) {\n const n11 = o10[o10.length - 1], i8 = n11 !== undefined \u0026\u0026 (t10 === \"horizontal\" ? Math.abs(n11.bounds.maxX - e61.bounds.minX) \u003c= l7 : Math.abs(n11.bounds.maxY - e61.bounds.minY) \u003c= l7);\n n11 \u0026\u0026 i8 ? (n11.sourceKeys = [...new Set([...n11.sourceKeys, ...e61.sourceKeys])].sort(), t10 === \"horizontal\" ? n11.bounds.maxX = e61.bounds.maxX : n11.bounds.maxY = e61.bounds.maxY) : o10.push({ ...e61, bounds: { ...e61.bounds }, availableZ: [...e61.availableZ], sourceKeys: [...e61.sourceKeys] });\n }\n return o10;\n }(e59, t4));\n}\nfunction S7({ topologyMode: e54, nodesOnLayer: t4, targetObstacleNodes: n8, globalTargetObstacleNodes: o10 }) {\n if (e54 === \"target-passthrough\") {\n return (o10.length \u003e 0 ? o10 : n8).map(({ sourceKey: e59 }) =\u003e [e59]);\n }\n return e54 === \"target-merged\" ? [n8.map(({ sourceKey: e59 }) =\u003e e59).sort()] : e54 === \"passthrough\" ? t4.map(({ sourceKey: e59 }) =\u003e [e59]) : [t4.map(({ sourceKey: e59 }) =\u003e e59).sort()];\n}\nvar C7 = class extends BaseSolver {\n constructor(e54) {\n super(), this.inputProblem = e54, this.MAX_ITERATIONS = 1e5;\n const { preparedNodes: t4, preparedNodeBySourceKey: n8 } = a7(e54);\n this.preparedNodes = t4, this.preparedNodeBySourceKey = n8, this.xCoordinates = f7(this.preparedNodes.flatMap(({ bounds: e59 }) =\u003e [e59.minX, e59.maxX])), this.stats = { inputNodeCount: this.preparedNodes.length, xSlabCount: Math.max(0, this.xCoordinates.length - 1), processedXSlabCount: 0, atomicRegionCount: 0, outputNodeCount: 0 };\n }\n preparedNodes;\n preparedNodeBySourceKey;\n outputProvenance = { groupIndexesByNodeId: new Map, sourceKeysByNodeId: new Map };\n xCoordinates;\n atomicRegions = [];\n horizontalRegionByBucket = new Map;\n overruledTargetSourceKeys = new Set;\n outputNodes = [];\n currentXIndex = 0;\n getConstructorParams() {\n return [this.inputProblem];\n }\n _step() {\n if (this.inputProblem.nodeGroups.length === 1)\n return void this.completePassthroughTopology();\n if (this.currentXIndex \u003c this.xCoordinates.length - 1)\n return this.processCurrentXSlab(), this.currentXIndex += 1, this.stats.processedXSlabCount = this.currentXIndex, void (this.stats.atomicRegionCount = this.atomicRegions.length);\n const e54 = function(e59) {\n let t4 = e59;\n for (;; ) {\n const e60 = I7(t4, \"horizontal\"), n8 = I7(e60, \"vertical\");\n if (n8.length === t4.length)\n return n8;\n t4 = n8;\n }\n }(function({ regions: e59, preparedNodeBySourceKey: t4, overruledTargetSourceKeys: n8 }) {\n const o10 = new Map;\n for (const t10 of e59)\n for (const e60 of t10.sourceKeys) {\n const n10 = o10.get(e60) ?? new Set;\n n10.add(t10.topologyMode), o10.set(e60, n10);\n }\n const i8 = new Set([...o10.entries()].filter(([e60, t10]) =\u003e t10.size === 1 \u0026\u0026 t10.has(\"target-passthrough\") \u0026\u0026 !n8.has(e60)).map(([e60]) =\u003e e60));\n return i8.size === 0 ? e59 : [...e59.filter((e60) =\u003e e60.topologyMode !== \"target-passthrough\" || !i8.has(e60.sourceKeys[0])), ...[...i8].map((e60) =\u003e {\n const n10 = t4.get(e60);\n if (!n10)\n throw new Error(`TopologyMergingSolver: missing authoritative target source \"${e60}\"`);\n return { bounds: { ...n10.bounds }, availableZ: [...n10.node.availableZ], sourceKeys: [e60], topologyMode: \"target-passthrough\", topologySignature: JSON.stringify({ mode: \"target-passthrough\", sourceKeys: [e60] }) };\n })];\n }({ regions: this.atomicRegions, preparedNodeBySourceKey: this.preparedNodeBySourceKey, overruledTargetSourceKeys: this.overruledTargetSourceKeys }));\n this.outputNodes = d7({ regions: e54, preparedNodeBySourceKey: this.preparedNodeBySourceKey, nodeGroups: this.inputProblem.nodeGroups, provenance: this.outputProvenance }), function({ nodes: e59, preparedNodeBySourceKey: t4, provenance: n8 }) {\n const o10 = new Set;\n for (const i8 of e59) {\n if (o10.has(i8.capacityMeshNodeId))\n throw new Error(`TopologyMergingSolver: duplicate output node id \"${i8.capacityMeshNodeId}\"`);\n if (o10.add(i8.capacityMeshNodeId), !li(ai(i8)))\n throw new Error(`TopologyMergingSolver: output node \"${i8.capacityMeshNodeId}\" has invalid bounds`);\n if (i8.availableZ.length === 0)\n throw new Error(`TopologyMergingSolver: output node \"${i8.capacityMeshNodeId}\" has no available layers`);\n const e60 = n8.sourceKeysByNodeId.get(i8.capacityMeshNodeId);\n if (!e60)\n throw new Error(`TopologyMergingSolver: missing output provenance for node \"${i8.capacityMeshNodeId}\"`);\n e60.length === 1 \u0026\u0026 m7({ node: i8, sourceKey: e60[0], preparedNodeBySourceKey: t4 });\n }\n for (let o11 = 0;o11 \u003c e59.length; o11++) {\n const i8 = e59[o11], r9 = ai(i8);\n for (let s7 = o11 + 1;s7 \u003c e59.length; s7++) {\n const o12 = e59[s7];\n if (o12.center.x - o12.width / 2 \u003e r9.maxX || o12.center.x + o12.width / 2 \u003c r9.minX || o12.center.y - o12.height / 2 \u003e r9.maxY || o12.center.y + o12.height / 2 \u003c r9.minY)\n continue;\n const a9 = i8.availableZ.filter((e60) =\u003e o12.availableZ.includes(e60));\n if (a9.length === 0)\n continue;\n const c5 = ci(r9, ai(o12));\n if (!c5)\n continue;\n const l5 = c5.maxX - c5.minX, h5 = c5.maxY - c5.minY;\n if (l5 \u003c= h7 || h5 \u003c= h7)\n continue;\n const d9 = n8.groupIndexesByNodeId.get(i8.capacityMeshNodeId), u9 = n8.groupIndexesByNodeId.get(o12.capacityMeshNodeId);\n if (!d9 || !u9)\n throw new Error(`TopologyMergingSolver: missing output provenance for overlapping nodes \"${i8.capacityMeshNodeId}\" and \"${o12.capacityMeshNodeId}\"`);\n const p9 = n8.sourceKeysByNodeId.get(i8.capacityMeshNodeId), m9 = n8.sourceKeysByNodeId.get(o12.capacityMeshNodeId);\n if (!p9 || !m9)\n throw new Error(`TopologyMergingSolver: missing source provenance for overlapping nodes \"${i8.capacityMeshNodeId}\" and \"${o12.capacityMeshNodeId}\"`);\n if (!g7({ groupIndexesA: d9, groupIndexesB: u9, sourceKeysA: p9, sourceKeysB: m9, sharedLayers: a9, preparedNodeBySourceKey: t4 }))\n throw new Error(`TopologyMergingSolver: output nodes \"${i8.capacityMeshNodeId}\" and \"${o12.capacityMeshNodeId}\" have an unresolved inter-group overlap on a shared layer`);\n }\n }\n }({ nodes: this.outputNodes, preparedNodeBySourceKey: this.preparedNodeBySourceKey, provenance: this.outputProvenance }), this.stats.outputNodeCount = this.outputNodes.length, this.stats.compactedRegionCount = e54.length, this.solved = true;\n }\n getOutput() {\n if (!this.solved)\n throw new Error(\"TopologyMergingSolver: getOutput() called before the solver completed\");\n return this.outputNodes;\n }\n computeProgress() {\n const e54 = Math.max(1, this.xCoordinates.length - 1);\n return this.solved ? 1 : Math.min(0.99, this.currentXIndex / e54);\n }\n visualize() {\n const e54 = this.solved ? this.outputNodes : d7({ regions: this.atomicRegions, preparedNodeBySourceKey: this.preparedNodeBySourceKey, nodeGroups: this.inputProblem.nodeGroups, provenance: this.outputProvenance, preserveSourceIds: false });\n return { title: `Topology Merging: ${e54.length} refined regions`, coordinateSystem: \"cartesian\", rects: e54.map((e59) =\u003e ({ ...dj(e59, { rectMargin: 0.01, zOffset: 0.02 }), label: `${e59.capacityMeshNodeId}\navailableZ: ${e59.availableZ.join(\",\")}\ncomponent: ${e59._isComponentTopologyNode ? \"yes\" : \"no\"}` })), lines: [], points: [], circles: [], texts: [] };\n }\n completePassthroughTopology() {\n const e54 = this.inputProblem.nodeGroups[0];\n this.outputNodes = e54.nodes;\n for (const t4 of this.outputNodes)\n this.outputProvenance.groupIndexesByNodeId.set(t4.capacityMeshNodeId, [0]), this.outputProvenance.sourceKeysByNodeId.set(t4.capacityMeshNodeId, [`${e54.groupId}:${t4.capacityMeshNodeId}`]);\n this.stats.processedXSlabCount = this.stats.xSlabCount, this.stats.atomicRegionCount = 0, this.stats.compactedRegionCount = 0, this.stats.outputNodeCount = this.outputNodes.length, this.stats.passthroughNodeCount = this.outputNodes.length, this.solved = true;\n }\n processCurrentXSlab() {\n const e54 = this.xCoordinates[this.currentXIndex], t4 = this.xCoordinates[this.currentXIndex + 1];\n if (t4 - e54 \u003c= l7)\n return;\n const n8 = (e54 + t4) / 2, o10 = this.preparedNodes.filter(({ bounds: e59 }) =\u003e n8 \u003e= e59.minX - l7 \u0026\u0026 n8 \u003c= e59.maxX + l7), i8 = f7(o10.flatMap(({ bounds: e59 }) =\u003e [e59.minY, e59.maxY])), r9 = new Map;\n for (let s7 = 0;s7 \u003c i8.length - 1; s7++) {\n const a9 = i8[s7], c5 = i8[s7 + 1];\n if (c5 - a9 \u003c= l7)\n continue;\n const l5 = { x: n8, y: (a9 + c5) / 2 }, h5 = o10.filter(({ bounds: e59 }) =\u003e _7(e59, l5));\n if (h5.length === 0)\n continue;\n const { layerTopologies: d9, overruledTargetSourceKeys: u9 } = y7({ coveringNodes: h5, nodeGroups: this.inputProblem.nodeGroups, layerCount: this.inputProblem.layerCount, allowBlindAndBuriedVias: this.inputProblem.allowBlindAndBuriedVias });\n for (const e59 of u9)\n this.overruledTargetSourceKeys.add(e59);\n for (const n10 of d9) {\n const o11 = { bounds: { minX: e54, maxX: t4, minY: a9, maxY: c5 }, availableZ: n10.availableZ, sourceKeys: n10.sourceKeys, topologyMode: n10.topologyMode, topologySignature: n10.topologySignature }, i9 = x7(o11), s9 = r9.get(i9) ?? this.horizontalRegionByBucket.get(i9);\n s9 \u0026\u0026 Math.abs(s9.bounds.maxX - e54) \u003c= l7 ? (s9.sourceKeys = [...new Set([...s9.sourceKeys, ...o11.sourceKeys])].sort(), s9.bounds.maxX = t4, r9.set(i9, s9)) : (this.atomicRegions.push(o11), r9.set(i9, o11));\n }\n }\n this.horizontalRegionByBucket = r9;\n }\n};\nfunction w7({ meshNodes: e54, components: t4 }) {\n return t4.length === 0 ? e54 : e54.map((e59) =\u003e {\n const n8 = t4.some((t10) =\u003e function({ node: e60, component: t11 }) {\n const { replacementObstacle: n10 } = t11, o10 = Math.abs(e60.center.x - n10.center.x) \u003c= si \u0026\u0026 Math.abs(e60.center.y - n10.center.y) \u003c= si \u0026\u0026 Math.abs(e60.width - n10.width) \u003c= si \u0026\u0026 Math.abs(e60.height - n10.height) \u003c= si;\n if (t11.componentKind !== \"qfp\" \u0026\u0026 t11.componentKind !== \"qfp_thermalpad\" \u0026\u0026 t11.componentKind !== \"soic\")\n return o10;\n const i8 = n10.center.x - n10.width / 2, r9 = n10.center.x + n10.width / 2, s7 = n10.center.y - n10.height / 2, a9 = n10.center.y + n10.height / 2, c5 = e60.center.x \u003e= i8 - si \u0026\u0026 e60.center.x \u003c= r9 + si \u0026\u0026 e60.center.y \u003e= s7 - si \u0026\u0026 e60.center.y \u003c= a9 + si, l5 = e60.width * e60.height, h5 = n10.width * n10.height, d9 = c5 \u0026\u0026 l5 \u003e= 0.2 * h5;\n return o10 || d9;\n }({ node: e59, component: t10 }));\n return n8 ? { ...e59, _containsObstacle: undefined, _completelyInsideObstacle: undefined, _containsTarget: undefined, _targetConnectionName: undefined, _connectedTo: undefined } : e59;\n });\n}\nvar N7 = class extends BasePipelineSolver {\n globalTopologySolver;\n componentTopologyBatchSolver;\n normalizedInput;\n pipelineDef = [definePipelineStep(\"globalTopologySolver\", Jn, (e54) =\u003e [e54.getGlobalTopologySolverInput()]), definePipelineStep(\"componentTopologyBatchSolver\", F8, (e54) =\u003e [{ componentSrjs: e54.getComponentNoConnectionSrjs(), componentIds: e54.normalizedInput.components.map((e59) =\u003e e59.componentId), componentKinds: e54.normalizedInput.components.map((e59) =\u003e e59.componentKind), viaDiameter: e54.inputProblem.viaDiameter, obstacleMargin: e54.inputProblem.obstacleMargin }])];\n constructor(e54) {\n super(e54), this.normalizedInput = L8(e54);\n }\n getConstructorParams() {\n return [this.inputProblem];\n }\n getOutput() {\n const e54 = w7({ meshNodes: this.getStageOutput(\"globalTopologySolver\")?.meshNodes ?? [], components: this.normalizedInput.components }), t4 = this.getStageOutput(\"componentTopologyBatchSolver\")?.componentMeshNodes ?? [], n8 = this.getComponentNoConnectionSrjs();\n return { globalNoConnectionSrj: this.normalizedInput.globalNoConnectionSrj, componentNoConnectionSrjs: n8, globalMeshNodes: e54, componentMeshNodes: t4 };\n }\n finalVisualize() {\n const e54 = this.getOutput();\n return { title: \"Topology Planning: generated topology groups\", rects: [...e54.componentNoConnectionSrjs.flatMap((e59, t4) =\u003e {\n const n8 = this.normalizedInput.components[t4] ?? null;\n return e59.obstacles.map((e60) =\u003e ({ center: e60.center, width: e60.width, height: e60.height, fill: \"rgba(120, 120, 120, 0.06)\", stroke: \"rgba(120, 120, 120, 0.35)\", label: e60.obstacleId ?? n8?.componentId ?? \"component-pad\", layer: e60.layers.join(\",\") }));\n }), ...[...e54.globalMeshNodes, ...e54.componentMeshNodes.flat()].map((e59) =\u003e {\n const t4 = this.normalizedInput.components.find((t10) =\u003e e59.capacityMeshNodeId.includes(t10.componentId));\n return { ...dj(e59, { rectMargin: 0.01 }), fill: e59._containsObstacle ? Ao(\"red\", 0.82) : \"rgba(0, 120, 255, 0.12)\", stroke: e59._containsObstacle ? Ao(\"red\", 0.3) : \"rgba(0, 120, 255, 0.55)\", label: t4 ? `${t4.componentKind.toUpperCase()} ${e59.capacityMeshNodeId}` : e59.capacityMeshNodeId };\n })], lines: [], points: [], circles: [], texts: [] };\n }\n visualize() {\n return this.filterGlobalRectDiffNodesFromVisualization({ visualization: super.visualize() });\n }\n preview() {\n return this.filterGlobalRectDiffNodesFromVisualization({ visualization: super.preview() });\n }\n getComponentNoConnectionSrjs() {\n return this.normalizedInput.components.map((e54) =\u003e function({ inputSrj: e59, component: t4 }) {\n const n8 = D8(t4.memberObstacles), o10 = Math.max(e59.minViaPadDiameter ?? e59.min_via_pad_diameter ?? e59.minViaDiameter ?? 0.3, e59.defaultObstacleMargin ?? 0.15, 2 * e59.minTraceWidth), i8 = new Set(t4.memberObstacles.flatMap((e60) =\u003e e60.connectedTo)), r9 = e59.connections.flatMap((e60) =\u003e e60.pointsToConnect.filter((e61) =\u003e {\n const t10 = [e61.pointId, e61.pcb_port_id].filter((e63) =\u003e typeof e63 == \"string\").some((e63) =\u003e i8.has(e63)), r10 = e61.x \u003e= n8.minX - o10 \u0026\u0026 e61.x \u003c= n8.maxX + o10 \u0026\u0026 e61.y \u003e= n8.minY - o10 \u0026\u0026 e61.y \u003c= n8.maxY + o10;\n return t10 \u0026\u0026 r10;\n })).reduce((e60, t10) =\u003e ({ minX: Math.min(e60.minX, t10.x), maxX: Math.max(e60.maxX, t10.x), minY: Math.min(e60.minY, t10.y), maxY: Math.max(e60.maxY, t10.y) }), n8), s7 = e59.obstacles.filter((e60) =\u003e De(Pe(e60), r9)).map((e60) =\u003e ({ ...e60 }));\n return { ...structuredClone(e59), bounds: r9, obstacles: s7 };\n }({ inputSrj: this.inputProblem.inputSrj, component: e54 }));\n }\n getGlobalTopologySolverInput() {\n return { simpleRouteJson: this.normalizedInput.globalNoConnectionSrj, maxGapFillPasses: 4 };\n }\n filterGlobalRectDiffNodesFromVisualization({ visualization: e54 }) {\n return { ...e54, rects: z8({ rects: e54.rects, components: this.normalizedInput.components }) };\n }\n};\nvar R7 = (e54, t4) =\u003e {\n if (e54)\n return Object.entries(t4).sort(([e59], [t10]) =\u003e t10.length - e59.length).find(([t10]) =\u003e e54.includes(t10))?.[1];\n};\nvar T7 = (e54, t4) =\u003e ({ ...e54, points: e54.points?.map((e59) =\u003e ({ ...e59, color: R7(e59.label, t4) ?? e59.color })), lines: e54.lines?.map((e59) =\u003e ({ ...e59, strokeColor: R7(e59.label, t4) ?? e59.strokeColor })), circles: e54.circles?.map((e59) =\u003e {\n const n8 = R7(e59.label, t4);\n return n8 ? { ...e59, fill: n8, stroke: n8 } : e59;\n}) });\nvar E7 = class extends ni {\n constructor(e54) {\n super(), this.topologyPlanningSolver = e54, this.solved = e54.solved, this.failed = e54.failed, this.error = e54.error, this.stats = e54.stats;\n }\n getOutput() {\n return this.topologyPlanningSolver.getOutput().componentMeshNodes.flat();\n }\n visualize() {\n return this.topologyPlanningSolver.finalVisualize() ?? this.topologyPlanningSolver.visualize();\n }\n preview() {\n return this.visualize();\n }\n};\nvar O7 = (e54) =\u003e e54.filter((e59) =\u003e Boolean(e59));\nvar k7 = (e54, t4, n8) =\u003e {\n const o10 = `${Math.round(100 * e54.x)},${Math.round(100 * e54.y)}`, i8 = t4.map((e59) =\u003e ((e60, t10) =\u003e e60 === \"top\" ? 0 : e60 === \"bottom\" ? t10 - 1 : Number.parseInt(e60.slice(5), 10))(e59, n8)).sort().join(\"-\");\n return `${o10}:${i8}`;\n};\nvar D7 = class {\n parent = new Map;\n cachedObstacles;\n canonicalSetsByAliases = new Map;\n constructor(e54, t4 = e54.traces ?? [], n8 = {}) {\n for (const t10 of e54.connections)\n this.unionAll(O7([t10.name, t10.source_trace_id, t10.rootConnectionName, t10.netConnectionName, ...t10.mergedConnectionNames ?? [], ...t10.pointsToConnect.flatMap((t11) =\u003e [t11.pointId, t11.pcb_port_id, ...n8.includePhysicalPositionAliases ? [k7(t11, t11.layers ?? [t11.layer], e54.layerCount)] : []])]));\n for (const n10 of [...t4, ...e54.fixedTraces ?? []])\n this.unionAll(O7([n10.pcb_trace_id, n10.connection_name, n10.source_trace_id, n10.rootConnectionName, ...n10.mergedConnectionNames ?? [], ...n10.connectsTo ?? []]));\n for (const t10 of e54.obstacles)\n this.unionAll(n8.includePhysicalPositionAliases ? O7([t10.obstacleId, ...t10.connectedTo, ...t10.offBoardConnectsTo ?? [], k7(t10.center, t10.layers, e54.layerCount)]) : t10.connectedTo);\n this.setCacheableObstacles(e54.obstacles);\n }\n setCacheableObstacles(e54) {\n if (this.cachedObstacles !== e54) {\n this.cachedObstacles = e54, this.canonicalSetsByAliases.clear();\n for (const t4 of e54)\n this.canonicalSetsByAliases.set(t4.connectedTo, null);\n }\n }\n canonicalize(e54) {\n return [...new Set(e54.map((e59) =\u003e this.find(e59)))];\n }\n canonicalizeToSet(e54) {\n const t4 = this.canonicalSetsByAliases.get(e54);\n if (t4 \u0026\u0026 e54.length === t4.aliases.length \u0026\u0026 e54.every((e59, n10) =\u003e e59 === t4.aliases[n10]))\n return t4.canonicalNames;\n const n8 = new Set(this.canonicalize(e54));\n return this.canonicalSetsByAliases.has(e54) \u0026\u0026 this.canonicalSetsByAliases.set(e54, { aliases: [...e54], canonicalNames: n8 }), n8;\n }\n unionAll(e54) {\n const t4 = e54[0];\n if (t4) {\n this.add(t4);\n for (let n8 = 1;n8 \u003c e54.length; n8++)\n this.union(t4, e54[n8]);\n }\n }\n add(e54) {\n this.parent.has(e54) || this.parent.set(e54, e54);\n }\n find(e54) {\n this.add(e54);\n const t4 = this.parent.get(e54);\n if (t4 === e54)\n return e54;\n const n8 = this.find(t4);\n return this.parent.set(e54, n8), n8;\n }\n union(e54, t4) {\n const n8 = this.find(e54), o10 = this.find(t4);\n n8 !== o10 \u0026\u0026 this.parent.set(o10, n8);\n }\n};\nvar L7 = 0.000001;\nvar z7 = (e54, t4) =\u003e Math.hypot(t4.x - e54.x, t4.y - e54.y);\nvar B7 = (e54, t4, n8) =\u003e {\n const o10 = n8.x - t4.x, i8 = n8.y - t4.y, r9 = o10 * o10 + i8 * i8;\n if (r9 \u003c= 0.000000000001)\n return z7(e54, t4);\n const s7 = j7(((e54.x - t4.x) * o10 + (e54.y - t4.y) * i8) / r9, 0, 1);\n return Math.hypot(e54.x - (t4.x + o10 * s7), e54.y - (t4.y + i8 * s7));\n};\nvar F7 = (e54, t4, n8 = 0.000001) =\u003e Math.abs(e54.x - t4.x) \u003c= n8 \u0026\u0026 Math.abs(e54.y - t4.y) \u003c= n8;\nvar j7 = (e54, t4, n8) =\u003e Math.max(t4, Math.min(n8, e54));\nvar $7 = (e54, t4, n8) =\u003e (t4.x - e54.x) * (n8.y - e54.y) - (t4.y - e54.y) * (n8.x - e54.x);\nvar Y7 = (e54, t4, n8) =\u003e Math.abs($7(t4, n8, e54)) \u003c= 0.000000001 \u0026\u0026 e54.x \u003e= Math.min(t4.x, n8.x) - 0.000000001 \u0026\u0026 e54.x \u003c= Math.max(t4.x, n8.x) + 0.000000001 \u0026\u0026 e54.y \u003e= Math.min(t4.y, n8.y) - 0.000000001 \u0026\u0026 e54.y \u003c= Math.max(t4.y, n8.y) + 0.000000001;\nvar X7 = (e54, t4, n8, o10) =\u003e {\n const i8 = $7(e54, t4, n8), r9 = $7(e54, t4, o10), s7 = $7(n8, o10, e54), a9 = $7(n8, o10, t4);\n return i8 * r9 \u003c 0 \u0026\u0026 s7 * a9 \u003c 0 || (Math.abs(i8) \u003c= 0.000000001 \u0026\u0026 Y7(n8, e54, t4) || Math.abs(r9) \u003c= 0.000000001 \u0026\u0026 Y7(o10, e54, t4) || Math.abs(s7) \u003c= 0.000000001 \u0026\u0026 Y7(e54, n8, o10) || Math.abs(a9) \u003c= 0.000000001 \u0026\u0026 Y7(t4, n8, o10));\n};\nvar H7 = (e54, t4, n8, o10) =\u003e X7(e54, t4, n8, o10) ? 0 : Math.min(B7(e54, n8, o10), B7(t4, n8, o10), B7(n8, e54, t4), B7(o10, e54, t4));\nvar V7 = (e54, t4) =\u003e {\n let n8 = false;\n for (let o10 = 0, i8 = t4.length - 1;o10 \u003c t4.length; i8 = o10++) {\n const r9 = t4[o10], s7 = t4[i8];\n if (Y7(e54, s7, r9))\n return true;\n r9.y \u003e e54.y != s7.y \u003e e54.y \u0026\u0026 e54.x \u003c (s7.x - r9.x) * (e54.y - r9.y) / (s7.y - r9.y) + r9.x \u0026\u0026 (n8 = !n8);\n }\n return n8;\n};\nvar W7 = (e54, t4, n8) =\u003e {\n if (V7(e54, n8) || V7(t4, n8))\n return 0;\n let o10 = Number.POSITIVE_INFINITY;\n for (let i8 = 0;i8 \u003c n8.length; i8++) {\n const r9 = n8[i8], s7 = n8[(i8 + 1) % n8.length];\n o10 = Math.min(o10, H7(e54, t4, r9, s7));\n }\n return o10;\n};\nvar G7 = (e54, t4, n8, o10, i8) =\u003e {\n const r9 = Math.max(Math.min(e54.x, t4.x) - Math.max(n8.x, o10.x), Math.min(n8.x, o10.x) - Math.max(e54.x, t4.x), Math.min(e54.y, t4.y) - Math.max(n8.y, o10.y), Math.min(n8.y, o10.y) - Math.max(e54.y, t4.y));\n return !(r9 \u003e Math.max(0, i8) + 0.000000001) \u0026\u0026 (r9 \u003c= 0.000000001 \u0026\u0026 X7(e54, t4, n8, o10) ? 0 \u003c= i8 : B7(e54, n8, o10) \u003c= i8 || B7(t4, n8, o10) \u003c= i8 || B7(n8, e54, t4) \u003c= i8 || B7(o10, e54, t4) \u003c= i8);\n};\nfunction U7(e54, t4, n8) {\n let o10 = 0, i8 = 1;\n const r9 = t4.x - e54.x, s7 = t4.y - e54.y, a9 = [[-r9, e54.x - n8.minX], [r9, n8.maxX - e54.x], [-s7, e54.y - n8.minY], [s7, n8.maxY - e54.y]];\n for (const [e59, t10] of a9) {\n if (Math.abs(e59) \u003c 0.000000000001) {\n if (t10 \u003c 0)\n return false;\n continue;\n }\n const n10 = t10 / e59;\n if (e59 \u003c 0 ? o10 = Math.max(o10, n10) : i8 = Math.min(i8, n10), o10 \u003e i8)\n return false;\n }\n return true;\n}\nfunction Z7({ start: e54, end: t4, width: n8, base: o10 }) {\n const i8 = n8 / 2, r9 = { x: t4.x, y: t4.y };\n return [{ ...o10, minX: Math.min(e54.x, r9.x) - i8, minY: Math.min(e54.y, r9.y) - i8, maxX: Math.max(e54.x, r9.x) + i8, maxY: Math.max(e54.y, r9.y) + i8, exactShape: { type: \"segment\", start: { x: e54.x, y: e54.y }, end: r9, width: n8 } }];\n}\nfunction q7({ start: e54, end: t4, width: n8, base: o10 }) {\n const i8 = z7(e54, t4), r9 = ((e59) =\u003e j7(1.25 * e59, 0.25, 0.75))(n8), s7 = Math.max(1, Math.ceil(i8 / r9)), a9 = n8 / 2, c5 = [];\n for (let i9 = 0;i9 \u003c s7; i9++) {\n const r10 = i9 / s7, l5 = (i9 + 1) / s7, h5 = e54.x + (t4.x - e54.x) * r10, d9 = e54.y + (t4.y - e54.y) * r10, u9 = e54.x + (t4.x - e54.x) * l5, p9 = e54.y + (t4.y - e54.y) * l5;\n c5.push({ ...o10, minX: Math.min(h5, u9) - a9, minY: Math.min(d9, p9) - a9, maxX: Math.max(h5, u9) + a9, maxY: Math.max(d9, p9) + a9, exactShape: { type: \"segment\", start: { x: h5, y: d9 }, end: { x: u9, y: p9 }, width: n8 } });\n }\n return c5;\n}\nvar J7 = (e54, t4, n8) =\u003e {\n const o10 = Math.cos(n8), i8 = Math.sin(n8), r9 = e54.x - t4.x, s7 = e54.y - t4.y;\n return { x: t4.x + r9 * o10 - s7 * i8, y: t4.y + r9 * i8 + s7 * o10 };\n};\nvar Q7 = (e54) =\u003e e54.isNonPlatedHole ? \"hole\" : e54.connectedTo[0]?.startsWith(\"pcb_via_\") ? \"via\" : e54.connectedTo[0]?.startsWith(\"pcb_smtpad_\") || e54.connectedTo[0]?.startsWith(\"pcb_plated_hole_\") ? \"pad\" : \"other\";\nfunction K7(e54) {\n if (e54.type !== \"rect\" || e54.isNonPlatedHole \u0026\u0026 e54.shape === \"circle\")\n return function(e59, t10 = 0.6) {\n if (e59.isNonPlatedHole \u0026\u0026 e59.shape === \"circle\") {\n const t11 = e59.width / 2;\n return [{ minX: e59.center.x - t11, minY: e59.center.y - t11, maxX: e59.center.x + t11, maxY: e59.center.y + t11, layers: e59.layers, kind: \"obstacle\", obstacleKind: \"hole\", connectionNames: e59.connectedTo, exactShape: { type: \"circle\", center: e59.center, radius: t11 } }];\n }\n const n10 = (e59.ccwRotationDegrees ?? 0) * Math.PI / 180, o11 = Math.max(1, Math.ceil(e59.width / t10)), i9 = Math.max(1, Math.ceil(e59.height / t10)), r10 = e59.width / o11, s7 = e59.height / i9, a9 = [];\n for (let t11 = 0;t11 \u003c i9; t11++)\n for (let i10 = 0;i10 \u003c o11; i10++) {\n const o12 = { x: e59.center.x - e59.width / 2 + (i10 + 0.5) * r10, y: e59.center.y - e59.height / 2 + (t11 + 0.5) * s7 }, c5 = r10 / 2, l5 = s7 / 2, h5 = [{ x: o12.x - c5, y: o12.y - l5 }, { x: o12.x + c5, y: o12.y - l5 }, { x: o12.x + c5, y: o12.y + l5 }, { x: o12.x - c5, y: o12.y + l5 }].map((t12) =\u003e J7(t12, e59.center, n10));\n a9.push({ minX: Math.min(...h5.map((e60) =\u003e e60.x)), minY: Math.min(...h5.map((e60) =\u003e e60.y)), maxX: Math.max(...h5.map((e60) =\u003e e60.x)), maxY: Math.max(...h5.map((e60) =\u003e e60.y)), layers: e59.layers, kind: \"obstacle\", obstacleKind: Q7(e59), connectionNames: e59.connectedTo, exactShape: { type: \"polygon\", points: h5 } });\n }\n return a9;\n }(e54);\n const { center: t4, width: n8, height: o10 } = e54, i8 = (e54.ccwRotationDegrees ?? 0) * Math.PI / 180, r9 = [{ x: t4.x - n8 / 2, y: t4.y - o10 / 2 }, { x: t4.x + n8 / 2, y: t4.y - o10 / 2 }, { x: t4.x + n8 / 2, y: t4.y + o10 / 2 }, { x: t4.x - n8 / 2, y: t4.y + o10 / 2 }].map((e59) =\u003e J7(e59, t4, i8));\n return [{ minX: Math.min(...r9.map((e59) =\u003e e59.x)), minY: Math.min(...r9.map((e59) =\u003e e59.y)), maxX: Math.max(...r9.map((e59) =\u003e e59.x)), maxY: Math.max(...r9.map((e59) =\u003e e59.y)), layers: e54.layers, kind: \"obstacle\", obstacleKind: Q7(e54), connectionNames: e54.connectedTo, exactShape: { type: \"polygon\", points: r9 } }];\n}\nvar tee = class {\n nodeIndices = [];\n priorities = [];\n get size() {\n return this.nodeIndices.length;\n }\n push(e54, t4) {\n let n8 = this.nodeIndices.length;\n for (this.nodeIndices.push(e54), this.priorities.push(t4);n8 \u003e 0; ) {\n const e59 = n8 - 1 \u003e\u003e 1;\n if (this.priorities[e59] \u003c= t4)\n break;\n this.swap(n8, e59), n8 = e59;\n }\n }\n pop() {\n const e54 = this.nodeIndices[0], t4 = this.nodeIndices.pop(), n8 = this.priorities.pop();\n if (this.nodeIndices.length === 0)\n return e54;\n this.nodeIndices[0] = t4, this.priorities[0] = n8;\n let o10 = 0;\n for (;; ) {\n const e59 = 2 * o10 + 1, t10 = e59 + 1;\n if (e59 \u003e= this.nodeIndices.length)\n break;\n let n10 = e59;\n if (t10 \u003c this.nodeIndices.length \u0026\u0026 this.priorities[t10] \u003c this.priorities[e59] \u0026\u0026 (n10 = t10), this.priorities[o10] \u003c= this.priorities[n10])\n break;\n this.swap(o10, n10), o10 = n10;\n }\n return e54;\n }\n swap(e54, t4) {\n [this.nodeIndices[e54], this.nodeIndices[t4]] = [this.nodeIndices[t4], this.nodeIndices[e54]], [this.priorities[e54], this.priorities[t4]] = [this.priorities[t4], this.priorities[e54]];\n }\n};\nvar nee = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]];\nvar oee = [\"#d53535\", \"#3478c8\", \"#8e44ad\", \"#15956f\"];\nvar iee = class extends BaseSolver {\n problem;\n searchBounds;\n rows;\n columns;\n origin;\n nodes = [];\n open = new tee;\n bestCost = new Map;\n closed = new Set;\n baseStateCount;\n stateSpaceUpperBound;\n endLayerIndices;\n targetCell;\n segmentWidthCache = new Map;\n closedStateCount = 0;\n output = null;\n constructor(e54) {\n super(), this.problem = e54;\n const t4 = Math.max(e54.traceWidth, e54.viaDiameter) / 2 + e54.obstacleIndex.clearance, n8 = j7(Math.min(e54.start.x, e54.end.x) - e54.searchPadding, e54.bounds.minX + t4, e54.bounds.maxX - t4), o10 = j7(Math.max(e54.start.x, e54.end.x) + e54.searchPadding, e54.bounds.minX + t4, e54.bounds.maxX - t4), i8 = j7(Math.min(e54.start.y, e54.end.y) - e54.searchPadding, e54.bounds.minY + t4, e54.bounds.maxY - t4), r9 = j7(Math.max(e54.start.y, e54.end.y) + e54.searchPadding, e54.bounds.minY + t4, e54.bounds.maxY - t4), s7 = Math.floor((n8 - e54.gridOffset.x) / e54.gridSize) * e54.gridSize + e54.gridOffset.x, a9 = Math.floor((i8 - e54.gridOffset.y) / e54.gridSize) * e54.gridSize + e54.gridOffset.y;\n this.origin = { x: s7, y: a9 }, this.columns = Math.max(2, Math.floor((o10 - s7) / e54.gridSize) + 1), this.rows = Math.max(2, Math.floor((r9 - a9) / e54.gridSize) + 1), this.searchBounds = { minX: s7, minY: a9, maxX: s7 + (this.columns - 1) * e54.gridSize, maxY: a9 + (this.rows - 1) * e54.gridSize };\n const c5 = this.rows * this.columns * e54.layers.length * (e54.maxViaCount + 1);\n this.baseStateCount = c5, this.stateSpaceUpperBound = c5 * (this.rows * this.columns + 1), this.targetCell = this.pointToCell(e54.end), this.endLayerIndices = new Set(e54.endLayers.map((t10) =\u003e e54.layers.indexOf(t10)).filter((e59) =\u003e e59 \u003e= 0));\n const l5 = this.pointToCell(e54.start);\n for (const t10 of e54.startLayers) {\n const n10 = e54.layers.indexOf(t10);\n if (n10 \u003c 0 || this.endpointCollides(e54.start, n10))\n continue;\n const o11 = { ...l5, ...e54.start, layerIndex: n10, viaCount: 0, viaPoints: [], g: 0, f: this.heuristic(e54.start), parentIndex: -1 }, i9 = this.nodes.length;\n this.nodes.push(o11), this.open.push(i9, o11.f), this.bestCost.set(this.toStateIndex(o11), 0);\n }\n this.open.size !== 0 \u0026\u0026 this.endLayerIndices.size !== 0 || (this.failed = true, this.error = \"No collision-free multilayer route endpoint\"), this.MAX_ITERATIONS = Math.min(15000, Math.max(2000, 2 * c5)), this.stats = this.createStats();\n }\n getSolverName() {\n return `LayerAwareGridRouteSolver(${this.problem.gridSize.toFixed(3)}mm)`;\n }\n _step() {\n if (this.open.size === 0)\n return this.failed = true, void (this.error = \"No collision-free multilayer grid route found\");\n const e54 = this.open.pop(), t4 = this.nodes[e54], n8 = this.toStateIndex(t4);\n if (!this.closed.has(n8)) {\n if (this.closed.add(n8), this.closedStateCount++, t4.row === this.targetCell.row \u0026\u0026 t4.column === this.targetCell.column \u0026\u0026 this.endLayerIndices.has(t4.layerIndex) \u0026\u0026 t4.viaCount \u003e= this.problem.minViaCount \u0026\u0026 !this.segmentCollides(t4, this.problem.end))\n return this.output = this.reconstructRoute(e54), this.solved = true, void (this.stats = this.createStats());\n this.expandPlanarMoves(e54, t4), this.expandViaMoves(e54, t4), this.stats = this.createStats();\n }\n }\n expandPlanarMoves(e54, t4) {\n for (const [n8, o10] of nee) {\n const i8 = t4.row + n8, r9 = t4.column + o10;\n if (i8 \u003c 0 || i8 \u003e= this.rows || r9 \u003c 0 || r9 \u003e= this.columns)\n continue;\n const s7 = this.cellToPoint(i8, r9), a9 = this.getSafeSegmentWidth(t4, s7);\n if (a9 \u003c= 0)\n continue;\n const c5 = this.problem.gridSize * (n8 !== 0 \u0026\u0026 o10 !== 0 ? Math.SQRT2 : 1) * Math.max(1, (this.problem.traceWidth / a9) ** this.problem.neckPenaltyExponent);\n this.enqueueNode({ row: i8, column: r9, ...s7, layerIndex: t4.layerIndex, viaCount: t4.viaCount, viaPoints: t4.viaPoints, g: t4.g + c5, parentIndex: e54 });\n }\n }\n expandViaMoves(e54, t4) {\n if (t4.viaCount \u003e= this.problem.maxViaCount)\n return;\n const n8 = 0.5 * this.problem.gridSize;\n if (z7(t4, this.problem.start) \u003c n8 - 0.000000001 || z7(t4, this.problem.end) \u003c n8 - 0.000000001)\n return;\n const o10 = t4.parentIndex \u003e= 0 ? this.nodes[t4.parentIndex] : undefined;\n if (!o10 || o10.layerIndex === t4.layerIndex || !F7(o10, t4))\n for (let n10 = 0;n10 \u003c this.problem.layers.length; n10++)\n n10 !== t4.layerIndex \u0026\u0026 (this.problem.obstacleIndex.collidesVia({ point: t4, layers: this.problem.layers, padDiameter: this.problem.viaDiameter, holeDiameter: this.problem.viaHoleDiameter, connectionNames: this.problem.connectionNames, ignoreTraceIndex: this.problem.ignoreTraceIndex, ignoreTraceIndices: this.problem.softTraceIndices, ignoreRouteRange: this.problem.ignoreRouteRange, obstacleClearance: this.problem.obstacleClearance, blockSameNetObstacles: true, sameNetObstacleClearance: 0, otherNewViaPoints: t4.viaPoints, fixedVias: this.problem.fixedVias }) || this.enqueueNode({ row: t4.row, column: t4.column, x: t4.x, y: t4.y, layerIndex: n10, viaCount: t4.viaCount + 1, viaPoints: [...t4.viaPoints, { x: t4.x, y: t4.y }], g: t4.g + this.problem.viaCost, parentIndex: e54 }));\n }\n enqueueNode(e54) {\n const t4 = this.toStateIndex(e54);\n if (this.closed.has(t4) || e54.g \u003e= (this.bestCost.get(t4) ?? Number.POSITIVE_INFINITY))\n return;\n this.bestCost.set(t4, e54.g);\n const n8 = e54.g + this.heuristic(e54), o10 = this.nodes.length;\n this.nodes.push({ ...e54, f: n8 }), this.open.push(o10, n8);\n }\n endpointCollides(e54, t4) {\n return this.getSafeSegmentWidth({ ...e54, layerIndex: t4, viaCount: 0 }, e54) \u003c= 0;\n }\n segmentCollides(e54, t4) {\n return this.getSafeSegmentWidth(e54, t4) \u003c= 0;\n }\n getSafeSegmentWidth(e54, t4) {\n const n8 = this.problem.layers[e54.layerIndex], o10 = this.problem.startLayers.length === 1 \u0026\u0026 e54.viaCount === 0 \u0026\u0026 n8 === this.problem.originalStartLayer \u0026\u0026 z7(this.problem.start, e54) \u003c= this.problem.maxStartNeckLength + 0.000000001 \u0026\u0026 z7(this.problem.start, t4) \u003c= this.problem.maxStartNeckLength + 0.000000001, i8 = this.problem.endLayers.length === 1 \u0026\u0026 n8 === this.problem.originalEndLayer \u0026\u0026 z7(this.problem.end, e54) \u003c= this.problem.maxEndNeckLength + 0.000000001 \u0026\u0026 z7(this.problem.end, t4) \u003c= this.problem.maxEndNeckLength + 0.000000001, r9 = Math.max(o10 ? this.problem.startNeckWidth : 0, i8 ? this.problem.endNeckWidth : 0), s7 = [e54.x, e54.y, t4.x, t4.y, e54.layerIndex, e54.viaCount, r9].join(\":\"), a9 = this.segmentWidthCache.get(s7);\n if (a9 !== undefined)\n return a9;\n const c5 = (o11) =\u003e !this.problem.obstacleIndex.collides({ start: e54, end: t4, layer: n8, width: o11, connectionNames: this.problem.connectionNames, ignoreTraceIndex: this.problem.ignoreTraceIndex, ignoreTraceIndices: this.problem.softTraceIndices, ignoreRouteRange: this.problem.ignoreRouteRange, obstacleClearance: this.problem.obstacleClearance });\n let l5 = 0;\n if (o10 || i8) {\n const e59 = 0.025;\n let t10 = Math.ceil((r9 - 0.000000001) / e59), n10 = Math.floor((this.problem.traceWidth + 0.000000001) / e59);\n for (;t10 \u003c= n10; ) {\n const o11 = Math.floor((t10 + n10) / 2), i9 = Number((o11 * e59).toFixed(6));\n c5(i9) ? (l5 = i9, t10 = o11 + 1) : n10 = o11 - 1;\n }\n l5 \u003c r9 - 0.000000001 \u0026\u0026 c5(r9) \u0026\u0026 (l5 = r9);\n } else\n l5 = c5(this.problem.traceWidth) ? this.problem.traceWidth : 0;\n return this.segmentWidthCache.set(s7, l5), l5;\n }\n reconstructRoute(e54) {\n const t4 = [];\n let n8 = e54;\n for (;n8 \u003e= 0; ) {\n const e59 = this.nodes[n8];\n t4.push(e59), n8 = e59.parentIndex;\n }\n t4.reverse();\n const o10 = t4[t4.length - 1];\n F7(o10, this.problem.end) || t4.push({ ...o10, ...this.problem.end, row: this.targetCell.row, column: this.targetCell.column, parentIndex: -1 });\n const i8 = [];\n let r9 = [t4[0]];\n for (let e59 = 1;e59 \u003c t4.length; e59++) {\n const n10 = t4[e59 - 1], o11 = t4[e59];\n o11.layerIndex !== n10.layerIndex ? (i8.push(r9), r9 = [o11]) : r9.push(o11);\n }\n i8.push(r9);\n const s7 = [];\n for (let e59 = 0;e59 \u003c i8.length; e59++) {\n const t10 = this.simplifySection(i8[e59]), n10 = t10.slice(0, -1).map((e60, n11) =\u003e this.getSafeSegmentWidth(e60, t10[n11 + 1])), o11 = t10.map((e60, o12) =\u003e ({ route_type: \"wire\", x: e60.x, y: e60.y, layer: this.problem.layers[e60.layerIndex], width: n10.length === 0 ? Math.min(this.problem.startNeckWidth, this.problem.endNeckWidth) : o12 === 0 ? n10[0] : o12 === t10.length - 1 ? n10[n10.length - 1] : Math.min(n10[o12 - 1], n10[o12]) }));\n s7.push(...o11);\n const r10 = i8[e59 + 1];\n if (r10) {\n const e60 = this.problem.layers[t10.at(-1).layerIndex], n11 = this.problem.layers[r10[0].layerIndex], o12 = t10.at(-1);\n s7.push({ route_type: \"via\", x: o12.x, y: o12.y, from_layer: e60, to_layer: n11, via_diameter: this.problem.viaDiameter, via_hole_diameter: this.problem.viaHoleDiameter });\n }\n }\n return { route: s7, traceWidth: this.problem.traceWidth, startNeckWidth: this.problem.startNeckWidth, endNeckWidth: this.problem.endNeckWidth, gridSize: this.problem.gridSize, gridOffset: this.problem.gridOffset, viaCount: i8.length - 1 };\n }\n simplifySection(e54) {\n return e54.length \u003c= 2 ? e54 : this.problem.neckPenaltyExponent \u003e 1 ? this.simplifyStrictSection(e54) : this.simplifyWidthPreservingSection(e54);\n }\n simplifyStrictSection(e54) {\n const t4 = e54.slice(0, -1).map((t10, n10) =\u003e this.getSafeSegmentWidth(t10, e54[n10 + 1])), n8 = [0];\n for (let o11 = 0;o11 \u003c t4.length; o11++)\n n8.push(n8[o11] + this.getWidthPenalizedCost(e54[o11], e54[o11 + 1], t4[o11]));\n const o10 = [e54[0]];\n let i8 = 0;\n for (;i8 \u003c e54.length - 1; ) {\n let r9 = e54.length - 1;\n for (;r9 \u003e i8 + 1 \u0026\u0026 !this.shortcutPreservesRouteQuality(e54, t4, n8, i8, r9); )\n r9--;\n o10.push(e54[r9]), i8 = r9;\n }\n return this.removeRedundantCollinearPoints(o10);\n }\n shortcutPreservesRouteQuality(e54, t4, n8, o10, i8) {\n const r9 = this.getSafeSegmentWidth(e54[o10], e54[i8]);\n if (r9 \u003c= 0)\n return false;\n let s7 = Number.POSITIVE_INFINITY;\n for (let e59 = o10;e59 \u003c i8; e59++)\n s7 = Math.min(s7, t4[e59]);\n const a9 = n8[i8] - n8[o10];\n return r9 \u003e= s7 - 0.000000001 \u0026\u0026 this.getWidthPenalizedCost(e54[o10], e54[i8], r9) \u003c= a9 + 0.000000001;\n }\n getWidthPenalizedCost(e54, t4, n8) {\n return z7(e54, t4) * Math.max(1, (this.problem.traceWidth / n8) ** this.problem.neckPenaltyExponent);\n }\n simplifyWidthPreservingSection(e54) {\n const t4 = e54.slice(0, -1).map((t10, n10) =\u003e this.getSafeSegmentWidth(t10, e54[n10 + 1])), n8 = [0];\n for (let o11 = 0;o11 \u003c t4.length; o11++)\n n8.push(n8[o11] + z7(e54[o11], e54[o11 + 1]) * Math.max(1, (this.problem.traceWidth / t4[o11]) ** this.problem.neckPenaltyExponent));\n const o10 = new Float64Array(e54.length).fill(Number.POSITIVE_INFINITY), i8 = new Float64Array(e54.length).fill(Number.POSITIVE_INFINITY), r9 = new Int32Array(e54.length).fill(-1);\n o10[0] = 0, i8[0] = 0;\n for (let s9 = 1;s9 \u003c e54.length; s9++) {\n let a10 = Number.POSITIVE_INFINITY;\n for (let c5 = s9 - 1;c5 \u003e= 0; c5--) {\n if (a10 = Math.min(a10, t4[c5]), !Number.isFinite(o10[c5]))\n continue;\n const l5 = this.getSafeSegmentWidth(e54[c5], e54[s9]);\n if (l5 \u003c a10 - 0.000000001)\n continue;\n const h5 = z7(e54[c5], e54[s9]);\n if (h5 * Math.max(1, (this.problem.traceWidth / l5) ** this.problem.neckPenaltyExponent) \u003e n8[s9] - n8[c5] + 0.000000001)\n continue;\n const d9 = o10[c5] + h5 * Math.max(0, this.problem.traceWidth - l5), u9 = i8[c5] + h5;\n (d9 \u003c o10[s9] - 0.000000001 || Math.abs(d9 - o10[s9]) \u003c= 0.000000001 \u0026\u0026 u9 \u003c i8[s9] - 0.000000001) \u0026\u0026 (o10[s9] = d9, i8[s9] = u9, r9[s9] = c5);\n }\n }\n const s7 = [];\n let a9 = e54.length - 1;\n for (;a9 \u003e= 0 \u0026\u0026 (s7.push(e54[a9]), a9 !== 0); )\n if (a9 = r9[a9], a9 \u003c 0)\n return e54;\n return s7.reverse(), this.removeRedundantCollinearPoints(s7);\n }\n removeRedundantCollinearPoints(e54) {\n return e54.filter((e59, t4, n8) =\u003e {\n if (t4 === 0 || t4 === n8.length - 1)\n return true;\n const o10 = n8[t4 - 1], i8 = n8[t4 + 1], r9 = (e59.x - o10.x) * (i8.y - e59.y) - (e59.y - o10.y) * (i8.x - e59.x), s7 = Math.abs(this.getSafeSegmentWidth(o10, e59) - this.getSafeSegmentWidth(e59, i8)) \u003c 0.000000001;\n return Math.abs(r9) \u003e 0.00000001 || !s7;\n });\n }\n pointToCell(e54) {\n return { column: j7(Math.round((e54.x - this.origin.x) / this.problem.gridSize), 0, this.columns - 1), row: j7(Math.round((e54.y - this.origin.y) / this.problem.gridSize), 0, this.rows - 1) };\n }\n cellToPoint(e54, t4) {\n return { x: this.origin.x + t4 * this.problem.gridSize, y: this.origin.y + e54 * this.problem.gridSize };\n }\n toStateIndex(e54) {\n const t4 = ((e54.viaCount * this.problem.layers.length + e54.layerIndex) * this.rows + e54.row) * this.columns + e54.column;\n if (e54.viaCount !== 1 || e54.viaPoints.length === 0 || z7(e54, e54.viaPoints[0]) \u003e= this.problem.viaHoleDiameter + this.problem.obstacleIndex.minViaHoleEdgeToViaHoleEdgeClearance - 0.000000001)\n return t4;\n const n8 = this.pointToCell(e54.viaPoints[0]);\n return t4 + (1 + n8.row * this.columns + n8.column) * this.baseStateCount;\n }\n heuristic(e54) {\n return z7(e54, this.problem.end);\n }\n createStats() {\n return { phase: \"layer-aware-grid-search\", gridSize: this.problem.gridSize, traceWidth: this.problem.traceWidth, startNeckWidth: this.problem.startNeckWidth, endNeckWidth: this.problem.endNeckWidth, maxViaCount: this.problem.maxViaCount, minViaCount: this.problem.minViaCount, openStates: this.open.size, closedStates: this.closedStateCount, trackedStates: this.bestCost.size, stateSpaceUpperBound: this.stateSpaceUpperBound };\n }\n computeProgress() {\n return Math.min(0.99, this.iterations / this.MAX_ITERATIONS);\n }\n getOutput() {\n return this.output;\n }\n getConstructorParams() {\n const { obstacleIndex: e54, ...t4 } = this.problem;\n return [t4];\n }\n visualize() {\n const e54 = this.nodes.filter((e59) =\u003e this.closed.has(this.toStateIndex(e59))).slice(-2000).map((e59) =\u003e ({ x: e59.x, y: e59.y, color: `${oee[e59.layerIndex % oee.length]}55` })), t4 = [], n8 = [], o10 = this.output?.route ?? [];\n for (let e59 = 0;e59 \u003c o10.length - 1; e59++) {\n const i8 = o10[e59], r9 = o10[e59 + 1];\n if (i8?.route_type === \"wire\" \u0026\u0026 r9?.route_type === \"wire\" \u0026\u0026 i8.layer === r9.layer) {\n const e60 = this.problem.layers.indexOf(i8.layer);\n t4.push({ points: [i8, r9], strokeColor: oee[e60 % oee.length] ?? \"#333\", strokeWidth: i8.width });\n }\n i8?.route_type === \"via\" \u0026\u0026 n8.push({ center: i8, radius: (i8.via_diameter ?? this.problem.viaDiameter) / 2, fill: \"#d4a017\" });\n }\n return { coordinateSystem: \"cartesian\", title: this.getSolverName(), rects: [{ center: { x: (this.searchBounds.minX + this.searchBounds.maxX) / 2, y: (this.searchBounds.minY + this.searchBounds.maxY) / 2 }, width: this.searchBounds.maxX - this.searchBounds.minX, height: this.searchBounds.maxY - this.searchBounds.minY, stroke: \"#777\" }], points: [...e54, { ...this.problem.start, color: \"green\", label: \"reroute start\" }, { ...this.problem.end, color: \"purple\", label: \"reroute target\" }], lines: t4, circles: n8, texts: [] };\n }\n};\nvar aee = [{ direction: 1, strength: 0.7 }, { direction: -1, strength: 0.7 }, { direction: 1, strength: 1 }, { direction: -1, strength: 1 }];\nvar cee = (e54, t4, n8) =\u003e {\n const o10 = n8.x - t4.x, i8 = n8.y - t4.y, r9 = o10 * o10 + i8 * i8;\n if (r9 \u003c= 0.000000000001)\n return { ...t4 };\n const s7 = j7(((e54.x - t4.x) * o10 + (e54.y - t4.y) * i8) / r9, 0, 1);\n return { x: t4.x + o10 * s7, y: t4.y + i8 * s7 };\n};\nvar lee = class extends BaseSolver {\n problem;\n phase = \"prepare-candidate\";\n variantCursor = 0;\n relaxationIteration = 0;\n candidatePoints = [];\n sampledPoints;\n output = null;\n constructor(e54) {\n super(), this.problem = e54, this.sampledPoints = this.sampleRoute(), this.MAX_ITERATIONS = 100, this.stats = this.createStats();\n }\n getSolverName() {\n return \"ElasticTracePushSolver\";\n }\n _step() {\n switch (this.phase) {\n case \"prepare-candidate\":\n if (this.variantCursor \u003e= aee.length)\n return this.failed = true, void (this.error = \"No collision-free elastic displacement found\");\n this.candidatePoints = this.sampledPoints.map((e54) =\u003e ({ ...e54 })), this.relaxationIteration = 0, this.phase = \"relax-candidate\";\n break;\n case \"relax-candidate\":\n this.relaxCandidate(), this.relaxationIteration++, this.relaxationIteration \u003e= 10 \u0026\u0026 (this.phase = \"validate-candidate\");\n break;\n case \"validate-candidate\": {\n const e54 = this.simplifyCandidate(this.candidatePoints);\n this.pathCollides(e54) ? (this.variantCursor++, this.phase = \"prepare-candidate\") : (this.output = { points: e54, traceWidth: this.problem.traceWidth }, this.phase = \"complete\");\n break;\n }\n case \"complete\":\n this.solved = true;\n }\n this.stats = this.createStats();\n }\n sampleRoute() {\n const e54 = [], t4 = j7(2 * this.problem.traceWidth, 0.2, 0.45), n8 = this.problem.trace.route;\n for (let o10 = this.problem.range.startIndex;o10 \u003c this.problem.range.endIndex; o10++) {\n const i8 = n8[o10], r9 = n8[o10 + 1];\n if (i8?.route_type !== \"wire\" || r9?.route_type !== \"wire\" || i8.layer !== r9.layer)\n continue;\n e54.length === 0 \u0026\u0026 e54.push({ x: i8.x, y: i8.y });\n const s7 = z7(i8, r9), a9 = Math.max(1, Math.ceil(s7 / t4));\n for (let t10 = 1;t10 \u003c= a9; t10++) {\n const n10 = t10 / a9;\n e54.push({ x: i8.x + (r9.x - i8.x) * n10, y: i8.y + (r9.y - i8.y) * n10 });\n }\n }\n return e54;\n }\n relaxCandidate() {\n const e54 = aee[this.variantCursor], t4 = this.candidatePoints.map((e59) =\u003e ({ ...e59 })), n8 = new Uint8Array(this.candidatePoints.length);\n for (let o10 = 1;o10 \u003c this.candidatePoints.length - 1; o10++) {\n const i8 = this.candidatePoints[o10], r9 = this.findNearestCorridorSegment(i8);\n if (!r9)\n continue;\n const s7 = z7(r9.segment.start, r9.segment.end);\n if (s7 \u003c= 0.000000001)\n continue;\n const a9 = r9.segment.width / 2 + this.problem.traceWidth / 2 + this.problem.obstacleIndex.clearance + 0.025;\n if (r9.distance \u003e a9 + 0.35)\n continue;\n const c5 = { x: (r9.segment.start.y - r9.segment.end.y) / s7 * e54.direction, y: (r9.segment.end.x - r9.segment.start.x) / s7 * e54.direction }, l5 = a9 - ((i8.x - r9.closest.x) * c5.x + (i8.y - r9.closest.y) * c5.y);\n if (l5 \u003c= 0)\n continue;\n const h5 = Math.min(0.35, l5 * e54.strength);\n t4[o10] = { x: i8.x + c5.x * h5, y: i8.y + c5.y * h5 }, n8[o10] = 1;\n }\n for (let e59 = 1;e59 \u003c t4.length - 1; e59++) {\n if (!n8[e59])\n continue;\n const o10 = t4[e59 - 1], i8 = t4[e59], r9 = t4[e59 + 1];\n t4[e59] = { x: 0.85 * i8.x + (o10.x + r9.x) / 2 * 0.15, y: 0.85 * i8.y + (o10.y + r9.y) / 2 * 0.15 };\n }\n this.candidatePoints = t4;\n }\n findNearestCorridorSegment(e54) {\n let t4;\n for (const n8 of this.problem.corridor) {\n if (n8.layer !== this.problem.layer)\n continue;\n const o10 = cee(e54, n8.start, n8.end), i8 = z7(e54, o10);\n (!t4 || i8 \u003c t4.distance) \u0026\u0026 (t4 = { segment: n8, closest: o10, distance: i8 });\n }\n return t4;\n }\n simplifyCandidate(e54) {\n if (e54.length \u003c= 2)\n return e54;\n const t4 = [e54[0]];\n let n8 = 0;\n for (;n8 \u003c e54.length - 1; ) {\n let o10 = e54.length - 1;\n for (;o10 \u003e n8 + 1 \u0026\u0026 this.segmentCollides(e54[n8], e54[o10]); )\n o10--;\n t4.push(e54[o10]), n8 = o10;\n }\n return t4.filter((e59, t10, n10) =\u003e t10 === 0 || !F7(e59, n10[t10 - 1]));\n }\n pathCollides(e54) {\n if (e54.length \u003c 2)\n return true;\n for (let t4 = 0;t4 \u003c e54.length - 1; t4++)\n if (this.segmentCollides(e54[t4], e54[t4 + 1]))\n return true;\n return false;\n }\n segmentCollides(e54, t4) {\n return this.problem.obstacleIndex.collides({ start: e54, end: t4, layer: this.problem.layer, width: this.problem.traceWidth, connectionNames: this.problem.connectionNames, ignoreTraceIndex: -1 });\n }\n createStats() {\n const e54 = aee[this.variantCursor];\n return { phase: this.phase, direction: e54?.direction, strength: e54?.strength, variantCursor: this.variantCursor, relaxationIteration: this.relaxationIteration, sampledPointCount: this.sampledPoints.length };\n }\n computeProgress() {\n return Math.min(0.99, (this.variantCursor + this.relaxationIteration / 12) / aee.length);\n }\n getOutput() {\n return this.output;\n }\n getConstructorParams() {\n return [this.problem];\n }\n visualize() {\n return { coordinateSystem: \"cartesian\", title: `Elastic trace push: ${this.phase}`, lines: [...this.problem.corridor.map((e54) =\u003e ({ points: [e54.start, e54.end], strokeColor: \"rgba(255, 128, 0, 0.6)\", strokeWidth: e54.width })), ...this.candidatePoints.length \u003e 1 ? [{ points: this.candidatePoints, strokeColor: \"#1769d2\", strokeWidth: this.problem.traceWidth }] : []], points: [], rects: [], circles: [], texts: [] };\n }\n};\nvar dee = (e54, t4) =\u003e {\n const n8 = Math.abs(t4.x - e54.x), o10 = Math.abs(t4.y - e54.y);\n return n8 \u003c= L7 || o10 \u003c= L7 || Math.abs(n8 - o10) \u003c= L7;\n};\nvar uee = (e54) =\u003e {\n let t4 = 0;\n for (let n8 = 0;n8 \u003c e54.length - 1; n8++)\n dee(e54[n8], e54[n8 + 1]) || t4++;\n return t4;\n};\nvar pee = (e54) =\u003e {\n let t4 = 0;\n for (let n8 = 0;n8 \u003c e54.length - 1; n8++)\n t4 += z7(e54[n8], e54[n8 + 1]);\n return t4;\n};\nvar mee = (e54) =\u003e e54.filter((t4, n8) =\u003e n8 === 0 || !F7(t4, e54[n8 - 1]));\nvar gee = (e54, t4) =\u003e {\n const n8 = t4.x - e54.x, o10 = t4.y - e54.y, i8 = Math.abs(n8), r9 = Math.abs(o10), s7 = Math.sign(n8), a9 = Math.sign(o10), c5 = [];\n dee(e54, t4) \u0026\u0026 c5.push([e54, t4]), c5.push([e54, { x: t4.x, y: e54.y }, t4], [e54, { x: e54.x, y: t4.y }, t4]), i8 \u003e= r9 ? c5.push([e54, { x: t4.x - s7 * r9, y: e54.y }, t4], [e54, { x: e54.x + s7 * r9, y: t4.y }, t4]) : c5.push([e54, { x: e54.x, y: t4.y - a9 * i8 }, t4], [e54, { x: t4.x, y: e54.y + a9 * i8 }, t4]);\n const l5 = new Map;\n for (const e59 of c5) {\n const t10 = mee(e59);\n if (t10.length \u003c 2 || t10.some((e60, n11) =\u003e n11 \u003c t10.length - 1 \u0026\u0026 !dee(e60, t10[n11 + 1])))\n continue;\n const n10 = t10.map((e60) =\u003e `${e60.x.toFixed(6)},${e60.y.toFixed(6)}`).join(\";\");\n l5.set(n10, t10);\n }\n return [...l5.values()].sort((e59, t10) =\u003e pee(e59) - pee(t10) || e59.length - t10.length);\n};\nvar fee = class {\n nodeIndices = [];\n priorities = [];\n get size() {\n return this.nodeIndices.length;\n }\n push(e54, t4) {\n let n8 = this.nodeIndices.length;\n for (this.nodeIndices.push(e54), this.priorities.push(t4);n8 \u003e 0; ) {\n const e59 = n8 - 1 \u003e\u003e 1;\n if (this.priorities[e59] \u003c= t4)\n break;\n this.swap(n8, e59), n8 = e59;\n }\n }\n pop() {\n const e54 = this.nodeIndices[0], t4 = this.nodeIndices.pop(), n8 = this.priorities.pop();\n if (this.nodeIndices.length === 0)\n return e54;\n this.nodeIndices[0] = t4, this.priorities[0] = n8;\n let o10 = 0;\n for (;; ) {\n const e59 = 2 * o10 + 1, t10 = e59 + 1;\n if (e59 \u003e= this.nodeIndices.length)\n break;\n let n10 = e59;\n if (t10 \u003c this.nodeIndices.length \u0026\u0026 this.priorities[t10] \u003c this.priorities[e59] \u0026\u0026 (n10 = t10), this.priorities[o10] \u003c= this.priorities[n10])\n break;\n this.swap(o10, n10), o10 = n10;\n }\n return e54;\n }\n swap(e54, t4) {\n [this.nodeIndices[e54], this.nodeIndices[t4]] = [this.nodeIndices[t4], this.nodeIndices[e54]], [this.priorities[e54], this.priorities[t4]] = [this.priorities[t4], this.priorities[e54]];\n }\n};\nvar _ee = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]];\nvar yee = class extends BaseSolver {\n problem;\n searchBounds;\n rows;\n columns;\n origin;\n nodes = [];\n open = new fee;\n bestCost;\n closed;\n closedCellCount = 0;\n targetCell;\n output = null;\n collisionChecker;\n constructor(e54) {\n super(), this.problem = e54;\n const t4 = e54.traceWidth / 2 + e54.obstacleIndex.clearance, n8 = j7(Math.min(e54.start.x, e54.end.x) - e54.searchPadding, e54.bounds.minX + t4, e54.bounds.maxX - t4), o10 = j7(Math.max(e54.start.x, e54.end.x) + e54.searchPadding, e54.bounds.minX + t4, e54.bounds.maxX - t4), i8 = j7(Math.min(e54.start.y, e54.end.y) - e54.searchPadding, e54.bounds.minY + t4, e54.bounds.maxY - t4), r9 = j7(Math.max(e54.start.y, e54.end.y) + e54.searchPadding, e54.bounds.minY + t4, e54.bounds.maxY - t4), s7 = Math.floor((n8 - e54.gridOffset.x) / e54.gridSize) * e54.gridSize + e54.gridOffset.x, a9 = Math.floor((i8 - e54.gridOffset.y) / e54.gridSize) * e54.gridSize + e54.gridOffset.y;\n if (this.origin = { x: s7, y: a9 }, this.columns = Math.max(2, Math.floor((o10 - s7) / e54.gridSize) + 1), this.rows = Math.max(2, Math.floor((r9 - a9) / e54.gridSize) + 1), this.searchBounds = { minX: s7, minY: a9, maxX: s7 + (this.columns - 1) * e54.gridSize, maxY: a9 + (this.rows - 1) * e54.gridSize }, this.bestCost = new Float64Array(this.rows * this.columns).fill(Number.POSITIVE_INFINITY), this.closed = new Uint8Array(this.rows * this.columns), this.endpointCollides(e54.start) || this.endpointCollides(e54.end))\n return this.failed = true, this.error = \"Grid-route endpoint violates obstacle clearance\", this.targetCell = { row: 0, column: 0 }, this.MAX_ITERATIONS = 1, void (this.stats = this.createStats());\n this.collisionChecker = e54.obstacleIndex.createSegmentCollisionChecker({ start: e54.start, end: e54.end, layer: e54.layer, width: e54.traceWidth, connectionNames: e54.connectionNames, ignoreTraceIndex: e54.ignoreTraceIndex, ignoreRouteRange: e54.ignoreRouteRange, obstacleClearance: e54.obstacleClearance }, { minX: Math.min(this.searchBounds.minX, e54.start.x, e54.end.x), minY: Math.min(this.searchBounds.minY, e54.start.y, e54.end.y), maxX: Math.max(this.searchBounds.maxX, e54.start.x, e54.end.x), maxY: Math.max(this.searchBounds.maxY, e54.start.y, e54.end.y) });\n const c5 = this.pointToCell(e54.start);\n this.targetCell = this.pointToCell(e54.end);\n const l5 = { ...c5, x: e54.start.x, y: e54.start.y, g: 0, f: this.heuristic(e54.start), parentIndex: -1 };\n this.nodes.push(l5), this.open.push(0, l5.f), this.bestCost[this.toFlatIndex(c5.row, c5.column)] = 0, this.MAX_ITERATIONS = Math.min(5000, Math.max(1000, this.rows * this.columns * 2)), this.stats = this.createStats();\n }\n endpointCollides(e54) {\n return this.problem.obstacleIndex.collides({ start: e54, end: e54, layer: this.problem.layer, width: this.problem.traceWidth, connectionNames: this.problem.connectionNames, ignoreTraceIndex: this.problem.ignoreTraceIndex, ignoreRouteRange: this.problem.ignoreRouteRange, obstacleClearance: this.problem.obstacleClearance });\n }\n getSolverName() {\n return `ObstacleAwareGridRouteSolver(${this.problem.gridSize.toFixed(3)}mm)`;\n }\n _step() {\n if (this.open.size === 0)\n return this.failed = true, void (this.error = \"No collision-free grid route found\");\n const e54 = this.open.pop(), t4 = this.nodes[e54], n8 = this.toFlatIndex(t4.row, t4.column);\n if (!this.closed[n8]) {\n if (this.closed[n8] = 1, this.closedCellCount++, t4.row === this.targetCell.row \u0026\u0026 t4.column === this.targetCell.column \u0026\u0026 this.getAllowedConnector(t4, this.problem.end) !== null)\n return this.output = { points: this.reconstructPath(e54), traceWidth: this.problem.traceWidth, gridSize: this.problem.gridSize, gridOffset: this.problem.gridOffset }, this.solved = true, void (this.stats = this.createStats());\n for (const [n10, o10] of _ee) {\n const i8 = t4.row + n10, r9 = t4.column + o10;\n if (i8 \u003c 0 || i8 \u003e= this.rows || r9 \u003c 0 || r9 \u003e= this.columns)\n continue;\n const s7 = this.toFlatIndex(i8, r9);\n if (this.closed[s7])\n continue;\n const a9 = t4.parentIndex === -1 \u0026\u0026 this.problem.requireOctilinear;\n let c5 = this.problem.gridSize * (n10 !== 0 \u0026\u0026 o10 !== 0 ? Math.SQRT2 : 1);\n if (!a9 \u0026\u0026 t4.g + c5 \u003e= this.bestCost[s7])\n continue;\n const l5 = this.cellToPoint(i8, r9), h5 = this.getAllowedConnector(t4, l5);\n if (h5 === null)\n continue;\n a9 \u0026\u0026 (c5 = pee(h5));\n const d9 = t4.g + c5;\n if (d9 \u003e= this.bestCost[s7])\n continue;\n this.bestCost[s7] = d9;\n const u9 = d9 + this.heuristic(l5), p9 = this.nodes.length;\n this.nodes.push({ row: i8, column: r9, ...l5, g: d9, f: u9, parentIndex: e54 }), this.open.push(p9, u9);\n }\n this.stats = this.createStats();\n }\n }\n segmentCollides(e54, t4) {\n return this.collisionChecker(e54, t4);\n }\n getAllowedConnector(e54, t4) {\n return this.problem.requireOctilinear \u0026\u0026 ((\"parentIndex\" in e54) \u0026\u0026 e54.parentIndex === -1 || F7(t4, this.problem.end)) ? gee(e54, t4).find((e59) =\u003e e59.slice(0, -1).every((t10, n8) =\u003e !this.segmentCollides(t10, e59[n8 + 1]))) ?? null : this.segmentCollides(e54, t4) ? null : [e54, t4];\n }\n pointToCell(e54) {\n return { column: j7(Math.round((e54.x - this.origin.x) / this.problem.gridSize), 0, this.columns - 1), row: j7(Math.round((e54.y - this.origin.y) / this.problem.gridSize), 0, this.rows - 1) };\n }\n cellToPoint(e54, t4) {\n return { x: this.origin.x + t4 * this.problem.gridSize, y: this.origin.y + e54 * this.problem.gridSize };\n }\n toFlatIndex(e54, t4) {\n return e54 * this.columns + t4;\n }\n heuristic(e54) {\n return Math.hypot(this.problem.end.x - e54.x, this.problem.end.y - e54.y);\n }\n reconstructPath(e54) {\n const t4 = [];\n let n8 = e54;\n for (;n8 \u003e= 0; ) {\n const e59 = this.nodes[n8];\n t4.push({ x: e59.x, y: e59.y }), n8 = e59.parentIndex;\n }\n if (t4.reverse(), F7(t4[0], this.problem.start) || t4.unshift({ ...this.problem.start }), F7(t4[t4.length - 1], this.problem.end) || t4.push({ ...this.problem.end }), this.problem.requireOctilinear) {\n const e59 = [t4[0]];\n for (let n10 = 0;n10 \u003c t4.length - 1; n10++) {\n const o11 = t4[n10], i9 = t4[n10 + 1], r9 = n10 === 0 || n10 === t4.length - 2 ? this.getAllowedConnector(n10 === 0 ? { ...o11, parentIndex: -1 } : o11, i9) : [o11, i9];\n if (!r9)\n return t4;\n e59.push(...r9.slice(1));\n }\n return e59.filter((e60, t10, n10) =\u003e {\n if (t10 === 0 || t10 === n10.length - 1)\n return true;\n const o11 = n10[t10 - 1], i9 = n10[t10 + 1], r9 = (e60.x - o11.x) * (i9.y - e60.y) - (e60.y - o11.y) * (i9.x - e60.x);\n return Math.abs(r9) \u003e 0.00000001 || !dee(o11, i9);\n });\n }\n const o10 = [t4[0]];\n let i8 = 0;\n for (;i8 \u003c t4.length - 1; ) {\n let e59 = t4.length - 1;\n for (;e59 \u003e i8 + 1 \u0026\u0026 this.segmentCollides(t4[i8], t4[e59]); )\n e59--;\n o10.push(t4[e59]), i8 = e59;\n }\n return o10.filter((e59, t10, n10) =\u003e {\n if (t10 === 0 || t10 === n10.length - 1)\n return true;\n const o11 = n10[t10 - 1], i9 = n10[t10 + 1], r9 = (e59.x - o11.x) * (i9.y - e59.y) - (e59.y - o11.y) * (i9.x - e59.x);\n return Math.abs(r9) \u003e 0.00000001;\n });\n }\n createStats() {\n return { phase: \"obstacle-aware-grid-search\", gridSize: this.problem.gridSize, traceWidth: this.problem.traceWidth, gridOffset: this.problem.gridOffset, openCells: this.open.size, closedCells: this.closedCellCount, gridCells: this.rows * this.columns };\n }\n computeProgress() {\n return Math.min(0.99, this.iterations / this.MAX_ITERATIONS);\n }\n getOutput() {\n return this.output;\n }\n getConstructorParams() {\n const { obstacleIndex: e54, ...t4 } = this.problem;\n return [t4];\n }\n visualize() {\n const e54 = this.nodes.filter((e59) =\u003e this.closed[this.toFlatIndex(e59.row, e59.column)]).slice(-2000).map((e59) =\u003e ({ x: e59.x, y: e59.y, color: \"rgba(0,90,255,0.22)\" })), t4 = this.output?.points ?? [];\n return { coordinateSystem: \"cartesian\", title: this.getSolverName(), rects: [{ center: { x: (this.searchBounds.minX + this.searchBounds.maxX) / 2, y: (this.searchBounds.minY + this.searchBounds.maxY) / 2 }, width: this.searchBounds.maxX - this.searchBounds.minX, height: this.searchBounds.maxY - this.searchBounds.minY, stroke: \"#777\" }], points: [...e54, { ...this.problem.start, color: \"green\", label: \"reroute start\" }, { ...this.problem.end, color: \"purple\", label: \"reroute target\" }], lines: t4.length \u003e 1 ? [{ points: t4, strokeColor: \"#00a050\", strokeWidth: this.problem.traceWidth }] : [], circles: [], texts: [] };\n }\n};\nvar bee = [Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array];\nvar xee = class e59 {\n static from(t4, n8 = 0) {\n if (n8 % 8 != 0)\n throw new Error(\"byteOffset must be 8-byte aligned.\");\n if (!t4 || t4.byteLength === undefined || \"buffer\" in t4)\n throw new Error(\"Data must be an instance of ArrayBuffer or SharedArrayBuffer.\");\n const [o10, i8] = new Uint8Array(t4, n8 + 0, 2);\n if (o10 !== 251)\n throw new Error(\"Data does not appear to be in a Flatbush format.\");\n const r9 = i8 \u003e\u003e 4;\n if (r9 !== 3)\n throw new Error(`Got v${r9} data when expected v3.`);\n const s7 = bee[15 \u0026 i8];\n if (!s7)\n throw new Error(\"Unrecognized array type.\");\n const [a9] = new Uint16Array(t4, n8 + 2, 1), [c5] = new Uint32Array(t4, n8 + 4, 1);\n return new e59(c5, a9, s7, undefined, t4, n8);\n }\n constructor(e54, t4 = 16, n8 = Float64Array, o10 = ArrayBuffer, i8, r9 = 0) {\n if (e54 === undefined)\n throw new Error(\"Missing required argument: numItems.\");\n if (isNaN(e54) || e54 \u003c= 0)\n throw new Error(`Unexpected numItems value: ${e54}.`);\n this.numItems = +e54, this.nodeSize = Math.min(Math.max(+t4, 2), 65535), this.byteOffset = r9;\n let s7 = e54, a9 = s7;\n this._levelBounds = [4 * s7];\n do {\n s7 = Math.ceil(s7 / this.nodeSize), a9 += s7, this._levelBounds.push(4 * a9);\n } while (s7 !== 1);\n this.ArrayType = n8, this.IndexArrayType = a9 \u003c 16384 ? Uint16Array : Uint32Array;\n const c5 = bee.indexOf(n8), l5 = 4 * a9 * n8.BYTES_PER_ELEMENT;\n if (c5 \u003c 0)\n throw new Error(`Unexpected typed array class: ${n8}.`);\n const h5 = n8, d9 = this.IndexArrayType;\n if (i8)\n this.data = i8, this._boxes = new h5(i8, r9 + 8, 4 * a9), this._indices = new d9(i8, r9 + 8 + l5, a9), this._pos = 4 * a9, 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];\n else {\n const n10 = this.data = new o10(8 + l5 + a9 * this.IndexArrayType.BYTES_PER_ELEMENT);\n this._boxes = new h5(n10, 8, 4 * a9), this._indices = new d9(n10, 8 + l5, a9), this._pos = 0, this.minX = 1 / 0, this.minY = 1 / 0, this.maxX = -1 / 0, this.maxY = -1 / 0, new Uint8Array(n10, 0, 2).set([251, 48 + c5]), new Uint16Array(n10, 2, 1)[0] = t4, new Uint32Array(n10, 4, 1)[0] = e54;\n }\n this._queue = new R;\n }\n add(e54, t4, n8 = e54, o10 = t4) {\n const i8 = this._pos, r9 = i8 \u003e\u003e 2, s7 = this._boxes;\n return this._indices[r9] = r9, s7[i8] = e54, s7[i8 + 1] = t4, s7[i8 + 2] = n8, s7[i8 + 3] = o10, this._pos = i8 + 4, e54 \u003c this.minX \u0026\u0026 (this.minX = e54), t4 \u003c this.minY \u0026\u0026 (this.minY = t4), n8 \u003e this.maxX \u0026\u0026 (this.maxX = n8), o10 \u003e this.maxY \u0026\u0026 (this.maxY = o10), r9;\n }\n finish() {\n if (this._pos \u003e\u003e 2 !== this.numItems)\n throw new Error(`Added ${this._pos \u003e\u003e 2} items when expected ${this.numItems}.`);\n const e54 = this._boxes;\n if (this.numItems \u003c= this.nodeSize)\n return e54[this._pos++] = this.minX, e54[this._pos++] = this.minY, e54[this._pos++] = this.maxX, void (e54[this._pos++] = this.maxY);\n const { numItems: t4, minX: n8, minY: o10, nodeSize: i8, _indices: r9, _levelBounds: s7 } = this, a9 = this.maxX - n8 || 1, c5 = this.maxY - o10 || 1, l5 = new Int32Array(t4), h5 = 65535 / a9, d9 = 65535 / c5;\n for (let i9 = 0, r10 = 0;i9 \u003c t4; i9++) {\n const t10 = e54[r10++], s9 = e54[r10++], a10 = h5 * ((t10 + e54[r10++]) / 2 - n8) | 0, c9 = d9 * ((s9 + e54[r10++]) / 2 - o10) | 0;\n l5[i9] = See(a10, c9);\n }\n (function(e60, t10, n10, o11, i9, r10) {\n const s9 = [o11, i9];\n for (;s9.length; ) {\n const o12 = s9.pop() || 0, i10 = s9.pop() || 0;\n if (o12 - i10 \u003c= r10 \u0026\u0026 Math.floor(i10 / r10) \u003e= Math.floor(o12 / r10))\n continue;\n const a10 = e60[i10], c9 = e60[i10 + o12 \u003e\u003e 1], l10 = e60[o12], h9 = a10 \u003e c9 != a10 \u003e l10 ? a10 : c9 \u003c a10 != c9 \u003c l10 ? c9 : l10;\n let d10 = i10 - 1, u10 = o12 + 1;\n for (;; ) {\n do {\n d10++;\n } while (e60[d10] \u003c h9);\n do {\n u10--;\n } while (e60[u10] \u003e h9);\n if (d10 \u003e= u10)\n break;\n Iee(e60, t10, n10, d10, u10);\n }\n s9.push(i10, u10, u10 + 1, o12);\n }\n })(l5, e54, r9, 0, t4 - 1, i8);\n let u9 = 4 * t4;\n for (let t10 = 0, n10 = 0;t10 \u003c s7.length - 1; t10++) {\n const o11 = s7[t10];\n for (;n10 \u003c o11; ) {\n const t11 = n10;\n let s9 = e54[n10++], a10 = e54[n10++], c9 = e54[n10++], l10 = e54[n10++];\n for (let t12 = 1;t12 \u003c i8 \u0026\u0026 n10 \u003c o11; t12++)\n s9 = Math.min(s9, e54[n10++]), a10 = Math.min(a10, e54[n10++]), c9 = Math.max(c9, e54[n10++]), l10 = Math.max(l10, e54[n10++]);\n r9[u9 \u003e\u003e 2] = t11, e54[u9++] = s9, e54[u9++] = a10, e54[u9++] = c9, e54[u9++] = l10;\n }\n }\n this._pos = u9;\n }\n collides(e54, t4, n8, o10, i8) {\n if (this._pos !== this._boxes.length)\n throw new Error(\"Data not yet indexed - call index.finish().\");\n const { _boxes: r9, _levelBounds: s7, _indices: a9, nodeSize: c5 } = this, l5 = 4 * this.numItems;\n let h5 = r9.length - 4, d9 = s7.length - 1;\n const u9 = [];\n for (;h5 !== undefined; ) {\n const p9 = Math.min(h5 + 4 * c5, s7[d9]), m9 = h5 \u003e= l5;\n for (let s9 = h5;s9 \u003c p9; s9 += 4) {\n const c9 = r9[s9];\n if (n8 \u003c c9)\n continue;\n const l10 = r9[s9 + 1];\n if (o10 \u003c l10)\n continue;\n const h9 = r9[s9 + 2];\n if (e54 \u003e h9)\n continue;\n const p10 = r9[s9 + 3];\n if (t4 \u003e p10)\n continue;\n const g10 = 0 | a9[s9 \u003e\u003e 2];\n if (m9)\n u9.push(g10, d9 - 1);\n else if (i8 === undefined || i8(g10, c9, l10, h9, p10))\n return true;\n }\n d9 = u9.pop(), h5 = u9.pop();\n }\n return false;\n }\n search(e54, t4, n8, o10, i8) {\n if (this._pos !== this._boxes.length)\n throw new Error(\"Data not yet indexed - call index.finish().\");\n const { _boxes: r9, _levelBounds: s7, _indices: a9, nodeSize: c5 } = this, l5 = 4 * this.numItems;\n let h5 = r9.length - 4, d9 = s7.length - 1;\n const u9 = [], p9 = [];\n let m9 = false;\n for (;h5 !== undefined; ) {\n const g10 = Math.min(h5 + 4 * c5, s7[d9]), f10 = h5 \u003e= l5;\n if (m9)\n this._collectContained(h5, g10, d9, l5, p9, i8);\n else\n for (let s9 = h5;s9 \u003c g10; s9 += 4) {\n const c9 = r9[s9];\n if (n8 \u003c c9)\n continue;\n const l10 = r9[s9 + 1];\n if (o10 \u003c l10)\n continue;\n const h9 = r9[s9 + 2];\n if (e54 \u003e h9)\n continue;\n const m10 = r9[s9 + 3];\n if (t4 \u003e m10)\n continue;\n const g11 = 0 | a9[s9 \u003e\u003e 2];\n if (f10) {\n const i9 = +(e54 \u003c= c9 \u0026\u0026 t4 \u003c= l10 \u0026\u0026 n8 \u003e= h9 \u0026\u0026 o10 \u003e= m10);\n u9.push(g11 | i9, d9 - 1);\n } else\n (i8 === undefined || i8(g11, c9, l10, h9, m10)) \u0026\u0026 p9.push(g11);\n }\n d9 = u9.pop(), h5 = u9.pop(), h5 !== undefined \u0026\u0026 (m9 = !(1 \u0026 ~h5), h5 \u0026= -2);\n }\n return p9;\n }\n _collectContained(e54, t4, n8, o10, i8, r9) {\n const s7 = this._boxes, a9 = this._indices;\n let c5 = e54;\n for (let e60 = n8;e60 \u003e 0; e60--)\n c5 = a9[c5 \u003e\u003e 2];\n const l5 = Math.min(c5 + (t4 - e54) * this.nodeSize ** n8, o10);\n if (r9 === undefined)\n for (;c5 \u003c l5; c5 += 4)\n i8.push(0 | a9[c5 \u003e\u003e 2]);\n else\n for (;c5 \u003c l5; c5 += 4) {\n const e60 = 0 | a9[c5 \u003e\u003e 2];\n r9(e60, s7[c5], s7[c5 + 1], s7[c5 + 2], s7[c5 + 3]) \u0026\u0026 i8.push(e60);\n }\n }\n neighbors(e54, t4, n8 = 1 / 0, o10 = 1 / 0, i8) {\n if (this._pos !== this._boxes.length)\n throw new Error(\"Data not yet indexed - call index.finish().\");\n const { _boxes: r9, _levelBounds: s7, _indices: a9, _queue: c5, nodeSize: l5 } = this, h5 = 4 * this.numItems, d9 = 4 * l5, u9 = [], p9 = n8 === 1;\n let m9 = o10 * o10;\n for (c5.push(r9.length - 4 \u003c\u003c 1, 0);c5.length; ) {\n const o11 = c5.ids[0];\n if (1 \u0026 o11) {\n if (c5.pop(), u9.push(o11 \u003e\u003e 1), u9.length === n8)\n break;\n continue;\n }\n c5.pop();\n const l10 = o11 \u003e\u003e 1, g10 = l10 \u003c h5, f10 = Math.min(l10 + d9, vee(l10, s7));\n for (let n10 = l10;n10 \u003c f10; n10 += 4) {\n const o12 = r9[n10], s9 = r9[n10 + 1], l11 = r9[n10 + 2], h9 = r9[n10 + 3], d10 = Math.max(Math.max(o12 - e54, e54 - l11), 0), u10 = Math.max(Math.max(s9 - t4, t4 - h9), 0), f11 = d10 * d10 + u10 * u10;\n if (f11 \u003e m9)\n continue;\n const _5 = 0 | a9[n10 \u003e\u003e 2];\n g10 ? (i8 === undefined || i8(_5)) \u0026\u0026 (c5.push(_5 \u003c\u003c 1 | 1, f11), p9 \u0026\u0026 f11 \u003c m9 \u0026\u0026 (m9 = f11)) : c5.push(_5 \u003c\u003c 1, f11);\n }\n }\n return c5.clear(), u9;\n }\n};\nfunction vee(e54, t4) {\n let n8 = 0, o10 = t4.length - 1;\n for (;n8 \u003c o10; ) {\n const i8 = n8 + o10 \u003e\u003e 1;\n t4[i8] \u003e e54 ? o10 = i8 : n8 = i8 + 1;\n }\n return t4[n8];\n}\nfunction Iee(e54, t4, n8, o10, i8) {\n const r9 = e54[o10];\n e54[o10] = e54[i8], e54[i8] = r9;\n const s7 = 4 * o10, a9 = 4 * i8, c5 = t4[s7], l5 = t4[s7 + 1], h5 = t4[s7 + 2], d9 = t4[s7 + 3];\n t4[s7] = t4[a9], t4[s7 + 1] = t4[a9 + 1], t4[s7 + 2] = t4[a9 + 2], t4[s7 + 3] = t4[a9 + 3], t4[a9] = c5, t4[a9 + 1] = l5, t4[a9 + 2] = h5, t4[a9 + 3] = d9;\n const u9 = n8[o10];\n n8[o10] = n8[i8], n8[i8] = u9;\n}\nfunction See(e54, t4) {\n let n8 = e54 ^ t4, o10 = 65535 ^ n8, i8 = 65535 ^ (e54 | t4), r9 = e54 \u0026 (65535 ^ t4), s7 = n8 | o10 \u003e\u003e 1, a9 = n8 \u003e\u003e 1 ^ n8, c5 = i8 ^ i8 \u003e\u003e 1 ^ o10 \u0026 r9 \u003e\u003e 1, l5 = r9 ^ n8 \u0026 i8 \u003e\u003e 1 ^ r9 \u003e\u003e 1;\n return n8 = s7 \u0026 s7 \u003e\u003e 2 ^ a9 \u0026 a9 \u003e\u003e 2, o10 = s7 \u0026 a9 \u003e\u003e 2 ^ a9 \u0026 (s7 ^ a9) \u003e\u003e 2, i8 = c5 ^ s7 \u0026 c5 \u003e\u003e 2 ^ a9 \u0026 l5 \u003e\u003e 2, r9 = l5 ^ a9 \u0026 c5 \u003e\u003e 2 ^ (s7 ^ a9) \u0026 l5 \u003e\u003e 2, s7 = n8 \u0026 n8 \u003e\u003e 4 ^ o10 \u0026 o10 \u003e\u003e 4, a9 = n8 \u0026 o10 \u003e\u003e 4 ^ o10 \u0026 (n8 ^ o10) \u003e\u003e 4, c5 = i8 ^ n8 \u0026 i8 \u003e\u003e 4 ^ o10 \u0026 r9 \u003e\u003e 4, l5 = r9 ^ o10 \u0026 i8 \u003e\u003e 4 ^ (n8 ^ o10) \u0026 r9 \u003e\u003e 4, i8 = c5 ^ s7 \u0026 c5 \u003e\u003e 8 ^ a9 \u0026 l5 \u003e\u003e 8, r9 = l5 ^ a9 \u0026 c5 \u003e\u003e 8 ^ (s7 ^ a9) \u0026 l5 \u003e\u003e 8, i8 ^= i8 \u003e\u003e 1, r9 ^= r9 \u003e\u003e 1, n8 = e54 ^ t4, o10 = r9 | 65535 ^ (n8 | i8), n8 = 16711935 \u0026 (n8 | n8 \u003c\u003c 8), n8 = 252645135 \u0026 (n8 | n8 \u003c\u003c 4), n8 = 858993459 \u0026 (n8 | n8 \u003c\u003c 2), n8 = 1431655765 \u0026 (n8 | n8 \u003c\u003c 1), o10 = 16711935 \u0026 (o10 | o10 \u003c\u003c 8), o10 = 252645135 \u0026 (o10 | o10 \u003c\u003c 4), o10 = 858993459 \u0026 (o10 | o10 \u003c\u003c 2), o10 = 1431655765 \u0026 (o10 | o10 \u003c\u003c 1), ((o10 \u003c\u003c 1 | n8) \u003e\u003e\u003e 0) - 2147483648;\n}\nvar Cee = class {\n items;\n clearance;\n minViaEdgeToPadEdgeClearance;\n minPadEdgeToPadEdgeClearance;\n holeClearance;\n boardEdgeClearance;\n boardLayers;\n minViaHoleEdgeToViaHoleEdgeClearance;\n defaultViaHoleDiameter;\n bounds;\n maxIndexedViaHoleDiameter;\n index;\n collisionIndexesByLayer = new Map;\n connectionNameSets;\n copperObjectIds;\n connectionNameResolver;\n connectedPads;\n dynamicTraceIndex;\n constructor(e54, t4, n8, o10 = [], i8 = new D7(e54, t4)) {\n var r9;\n this.bounds = e54.bounds, this.boardLayers = (r9 = e54.layerCount, [\"top\", ...Array.from({ length: Math.max(0, r9 - 2) }, (e60, t10) =\u003e `inner${t10 + 1}`), ...r9 \u003e 1 ? [\"bottom\"] : []]), this.dynamicTraceIndex = n8, this.clearance = Math.max(e54.defaultObstacleMargin ?? 0, e54.minTraceToPadEdgeClearance ?? 0, 0.1), this.minViaEdgeToPadEdgeClearance = e54.minViaEdgeToPadEdgeClearance, this.holeClearance = e54.minTraceToHoleEdgeClearance ?? this.clearance, this.minPadEdgeToPadEdgeClearance = e54.minPadEdgeToPadEdgeClearance ?? this.clearance, this.boardEdgeClearance = e54.minBoardEdgeClearance ?? this.clearance, this.minViaHoleEdgeToViaHoleEdgeClearance = Math.max(e54.minViaHoleEdgeToViaHoleEdgeClearance ?? 0, 0.1), this.defaultViaHoleDiameter = e54.min_via_hole_diameter ?? e54.minViaHoleDiameter ?? 0.3, this.items = [...e54.obstacles.flatMap((e60, t10) =\u003e K7(e60).map((e61) =\u003e ({ ...e61, copperObjectId: `obstacle:${t10}` }))), ...this.createTraceItems(e54.fixedTraces ?? [], true), ...this.createTraceItems(t4), ...o10], this.maxIndexedViaHoleDiameter = this.items.reduce((e60, t10) =\u003e t10.kind === \"via\" ? Math.max(e60, t10.viaHoleDiameter ?? this.defaultViaHoleDiameter) : e60, this.defaultViaHoleDiameter), this.connectionNameResolver = i8, i8.setCacheableObstacles(e54.obstacles);\n const s7 = new Map;\n this.connectionNameSets = this.items.map((e60) =\u003e {\n let t10 = s7.get(e60.connectionNames);\n return t10 || (t10 = i8.canonicalizeToSet(e60.connectionNames), s7.set(e60.connectionNames, t10)), t10;\n }), this.copperObjectIds = this.items.map((e60, t10) =\u003e e60.copperObjectId ?? `indexed-item:${t10}`), this.connectedPads = e54.obstacles.flatMap((e60) =\u003e e60.connectedTo.some((e61) =\u003e e61.startsWith(\"pcb_smtpad_\") || e61.startsWith(\"pcb_plated_hole_\")) ? [{ obstacle: e60, canonicalConnectionNames: i8.canonicalizeToSet(e60.connectedTo) }] : []), this.index = this.items.length \u003e 0 ? new xee(this.items.length) : null;\n for (const e60 of this.items)\n this.index.add(e60.minX, e60.minY, e60.maxX, e60.maxY);\n this.index?.finish();\n }\n createTraceItems(e54, t4 = false) {\n const n8 = [];\n for (let o10 = 0;o10 \u003c e54.length; o10++) {\n const i8 = e54[o10], r9 = t4 ? undefined : o10, s7 = `${t4 ? \"fixed-trace\" : \"trace\"}:${o10}`, a9 = !t4 \u0026\u0026 o10 === this.dynamicTraceIndex, c5 = [i8.connection_name, i8.source_trace_id, i8.rootConnectionName, ...i8.mergedConnectionNames ?? [], ...i8.connectsTo ?? []].filter((e60) =\u003e Boolean(e60));\n for (let e60 = 0;e60 \u003c i8.route.length; e60++) {\n const t10 = i8.route[e60];\n if (t10.route_type === \"via\") {\n const o12 = t10.via_diameter ?? 0.6;\n n8.push({ minX: t10.x - o12 / 2, minY: t10.y - o12 / 2, maxX: t10.x + o12 / 2, maxY: t10.y + o12 / 2, layers: this.boardLayers, kind: \"via\", connectionNames: c5, copperObjectId: s7, traceIndex: r9, routeStartIndex: e60, routeEndIndex: e60, viaHoleDiameter: t10.via_hole_diameter ?? this.defaultViaHoleDiameter, exactShape: { type: \"circle\", center: { x: t10.x, y: t10.y }, radius: o12 / 2 } });\n continue;\n }\n if (a9)\n continue;\n const o11 = i8.route[e60 + 1];\n t10.route_type === \"wire\" \u0026\u0026 o11?.route_type === \"wire\" \u0026\u0026 t10.layer === o11.layer \u0026\u0026 n8.push(...Z7({ start: t10, end: o11, width: t10.width, base: { layers: [t10.layer], kind: \"trace\", connectionNames: c5, copperObjectId: s7, traceIndex: r9, routeStartIndex: e60, routeEndIndex: e60 + 1 } }));\n }\n }\n return n8;\n }\n collides(e54) {\n if (this.isOutsideBounds(e54))\n return true;\n const { radius: t4, candidates: n8, canonicalConnectionNames: o10 } = this.getCollisionCandidates(e54, true);\n for (const i8 of n8)\n if (this.itemCollides(i8, e54, t4, o10))\n return true;\n return false;\n }\n createSegmentCollisionChecker(e54, t4) {\n const { radius: n8, candidates: o10, canonicalConnectionNames: i8 } = this.getCollisionCandidates({ ...e54, start: { x: t4.minX, y: t4.minY }, end: { x: t4.maxX, y: t4.maxY } }, true), r9 = [];\n for (const t10 of o10) {\n const n10 = this.getItemCollisionRadius(t10, e54, i8);\n n10 !== null \u0026\u0026 r9.push({ item: this.items[t10], radius: n10 });\n }\n const s7 = r9.length ? new xee(r9.length) : null;\n for (const { item: e60, radius: t10 } of r9) {\n const n10 = Math.max(Math.abs(e60.minX), Math.abs(e60.minY), Math.abs(e60.maxX), Math.abs(e60.maxY)), o11 = t10 + 0.000000001 + Number.EPSILON * (n10 + Math.abs(t10)) * 4;\n s7.add(e60.minX - o11, e60.minY - o11, e60.maxX + o11, e60.maxY + o11);\n }\n s7?.finish();\n const a9 = { ...e54 };\n let c5 = 0, l5 = 0, h5 = 0, d9 = 0;\n const u9 = (e60) =\u003e {\n const t10 = r9[e60], n10 = t10.item;\n return !(h5 \u003c n10.minX || d9 \u003c n10.minY || c5 \u003e n10.maxX || l5 \u003e n10.maxY) \u0026\u0026 this.itemGeometryCollides(n10, a9, t10.radius);\n };\n return (e60, o11) =\u003e {\n if (Math.min(e60.x, o11.x) \u003c t4.minX || Math.min(e60.y, o11.y) \u003c t4.minY || Math.max(e60.x, o11.x) \u003e t4.maxX || Math.max(e60.y, o11.y) \u003e t4.maxY)\n throw new Error(\"Segment exceeds its prepared collision bounds\");\n return a9.start = e60, a9.end = o11, !!this.isOutsideBounds(a9) || (c5 = Math.min(e60.x, o11.x) - n8, l5 = Math.min(e60.y, o11.y) - n8, h5 = Math.max(e60.x, o11.x) + n8, d9 = Math.max(e60.y, o11.y) + n8, s7?.collides(Math.min(e60.x, o11.x), Math.min(e60.y, o11.y), Math.max(e60.x, o11.x), Math.max(e60.y, o11.y), u9) ?? false);\n };\n }\n findCollisions(e54) {\n const { radius: t4, candidates: n8, canonicalConnectionNames: o10 } = this.getCollisionCandidates(e54), i8 = [];\n for (const r9 of n8)\n this.itemCollides(r9, e54, t4, o10) \u0026\u0026 i8.push(this.items[r9]);\n return i8;\n }\n getSameNetCopperContactIds(e54) {\n const t4 = e54.width / 2, n8 = this.index?.search(Math.min(e54.start.x, e54.end.x) - t4, Math.min(e54.start.y, e54.end.y) - t4, Math.max(e54.start.x, e54.end.x) + t4, Math.max(e54.start.y, e54.end.y) + t4) ?? [], o10 = new Set(this.connectionNameResolver.canonicalize(e54.connectionNames)), i8 = new Set;\n for (const r9 of n8) {\n const n10 = this.items[r9];\n n10.layers.includes(e54.layer) \u0026\u0026 (n10.traceIndex === e54.ignoreTraceIndex || e54.ignoreTraceIndices?.includes(n10.traceIndex ?? -1) || [...this.connectionNameSets[r9]].some((e60) =\u003e o10.has(e60)) \u0026\u0026 this.itemCopperTouches(n10, e54, t4) \u0026\u0026 i8.add(this.copperObjectIds[r9]));\n }\n return i8;\n }\n getConnectedPadWidthLimit(e54) {\n if (Math.hypot(e54.end.x - e54.start.x, e54.end.y - e54.start.y) \u003c= 0.00001)\n return null;\n const t4 = this.getConnectedPadWidthLimitAtPoint(e54, e54.start), n8 = this.getConnectedPadWidthLimitAtPoint(e54, e54.end);\n return t4 === null ? n8 : n8 === null ? t4 : Math.min(t4, n8);\n }\n getConnectedPadWidthLimitAtPoint(e54, t4) {\n const n8 = this.getConnectedPadsAtPoint(e54, t4);\n return n8.length === 0 ? null : Math.max(...n8.map(({ obstacle: t10 }) =\u003e this.getPadWidthNormalToQuery(t10, e54)));\n }\n getConnectedPadEndpointWidthLimitAtPoint(e54, t4) {\n const n8 = this.getConnectedPadsAtPoint(e54, t4);\n return n8.length === 0 ? null : Math.max(...n8.map(({ obstacle: e60 }) =\u003e {\n const n10 = this.getObstacleLocalPoint(t4, e60);\n return Math.max(0, 2 * Math.min(e60.width / 2 - Math.abs(n10.x), e60.height / 2 - Math.abs(n10.y)));\n }));\n }\n getConnectedPadBoundaryPoint(e54, t4) {\n const n8 = t4 === \"start\" ? e54.start : e54.end, o10 = t4 === \"start\" ? e54.end : e54.start, i8 = this.getConnectedPadsAtPoint(e54, n8).sort((t10, n10) =\u003e this.getPadWidthNormalToQuery(n10.obstacle, e54) - this.getPadWidthNormalToQuery(t10.obstacle, e54))[0];\n return !i8 || this.pointIsInsideObstacle(o10, i8.obstacle) ? null : this.getObstacleBoundaryPoint(n8, o10, i8.obstacle);\n }\n getConnectedPadsAtPoint(e54, t4) {\n const n8 = new Set(this.connectionNameResolver.canonicalize(e54.connectionNames));\n return this.connectedPads.filter(({ obstacle: o10, canonicalConnectionNames: i8 }) =\u003e o10.layers.includes(e54.layer) \u0026\u0026 [...i8].some((e60) =\u003e n8.has(e60)) \u0026\u0026 this.pointIsInsideObstacle(t4, o10));\n }\n pointIsInsideObstacle(e54, t4) {\n const { x: n8, y: o10 } = this.getObstacleLocalPoint(e54, t4);\n return Math.abs(n8) \u003c= t4.width / 2 + 0.000000001 \u0026\u0026 Math.abs(o10) \u003c= t4.height / 2 + 0.000000001;\n }\n getObstacleLocalPoint(e54, t4) {\n const n8 = -(t4.ccwRotationDegrees ?? 0) * Math.PI / 180, o10 = Math.cos(n8), i8 = Math.sin(n8), r9 = e54.x - t4.center.x, s7 = e54.y - t4.center.y;\n return { x: r9 * o10 - s7 * i8, y: r9 * i8 + s7 * o10 };\n }\n getPadWidthNormalToQuery(e54, t4) {\n const n8 = t4.end.x - t4.start.x, o10 = t4.end.y - t4.start.y, i8 = Math.hypot(n8, o10);\n if (i8 \u003c= 0.000000001)\n return Math.min(e54.width, e54.height);\n const r9 = -o10 / i8, s7 = n8 / i8, a9 = -(e54.ccwRotationDegrees ?? 0) * Math.PI / 180, c5 = Math.cos(a9), l5 = Math.sin(a9), h5 = r9 * c5 - s7 * l5, d9 = r9 * l5 + s7 * c5;\n return Math.abs(h5) * e54.width + Math.abs(d9) * e54.height;\n }\n getObstacleBoundaryPoint(e54, t4, n8) {\n const o10 = -(n8.ccwRotationDegrees ?? 0) * Math.PI / 180, i8 = Math.cos(o10), r9 = Math.sin(o10), s7 = (e60) =\u003e {\n const t10 = e60.x - n8.center.x, o11 = e60.y - n8.center.y;\n return { x: t10 * i8 - o11 * r9, y: t10 * r9 + o11 * i8 };\n }, a9 = s7(e54), c5 = s7(t4), l5 = { x: c5.x - a9.x, y: c5.y - a9.y }, h5 = [];\n if (Math.abs(l5.x) \u003e 0.000000000001) {\n const e60 = l5.x \u003e 0 ? n8.width / 2 : -n8.width / 2;\n h5.push((e60 - a9.x) / l5.x);\n }\n if (Math.abs(l5.y) \u003e 0.000000000001) {\n const e60 = l5.y \u003e 0 ? n8.height / 2 : -n8.height / 2;\n h5.push((e60 - a9.y) / l5.y);\n }\n const d9 = Math.min(...h5.filter((e60) =\u003e e60 \u003e= 0 \u0026\u0026 e60 \u003c= 1));\n return Number.isFinite(d9) ? { x: e54.x + (t4.x - e54.x) * d9, y: e54.y + (t4.y - e54.y) * d9 } : null;\n }\n getConnectedLayersAtPoint(e54, t4) {\n const n8 = new Set(this.connectionNameResolver.canonicalize(t4)), o10 = new Set, i8 = this.index?.search(e54.x, e54.y, e54.x, e54.y) ?? [];\n for (const t10 of i8) {\n const i9 = this.items[t10];\n if (i9.kind !== \"obstacle\")\n continue;\n if (![...this.connectionNameSets[t10]].some((e60) =\u003e n8.has(e60)))\n continue;\n if (i9.exactShape?.type === \"polygon\" ? W7(e54, e54, i9.exactShape.points) \u003c= 0.000000001 : i9.exactShape?.type === \"circle\" ? Math.hypot(i9.exactShape.center.x - e54.x, i9.exactShape.center.y - e54.y) \u003c= i9.exactShape.radius + 0.000000001 : e54.x \u003e= i9.minX - 0.000000001 \u0026\u0026 e54.x \u003c= i9.maxX + 0.000000001 \u0026\u0026 e54.y \u003e= i9.minY - 0.000000001 \u0026\u0026 e54.y \u003c= i9.maxY + 0.000000001)\n for (const e60 of i9.layers)\n o10.add(e60);\n }\n return [...o10];\n }\n collidesVia(e54) {\n return this.getViaViolationSignatures(e54).size \u003e 0;\n }\n getViaViolationSignatures(e54) {\n const t4 = new Set;\n for (const n10 of e54.layers) {\n const o11 = { isVia: true, start: e54.point, end: e54.point, layer: n10, width: e54.padDiameter, connectionNames: e54.connectionNames, ignoreTraceIndex: e54.ignoreTraceIndex, ignoreTraceIndices: e54.ignoreTraceIndices, ignoreRouteRange: e54.ignoreRouteRange, obstacleClearance: Math.max(e54.obstacleClearance ?? this.clearance, this.minViaEdgeToPadEdgeClearance ?? 0), blockSameNetObstacles: e54.blockSameNetObstacles, sameNetObstacleClearance: e54.sameNetObstacleClearance };\n this.isOutsideBounds(o11) \u0026\u0026 t4.add(`board-edge:${n10}`);\n const { radius: i9, candidates: r10, canonicalConnectionNames: s9 } = this.getCollisionCandidates(o11);\n for (const e60 of r10)\n this.itemCollides(e60, o11, i9, s9) \u0026\u0026 t4.add(`copper:${n10}:${this.getViolationObjectId(e60)}`);\n }\n const n8 = e54.holeDiameter + this.minViaHoleEdgeToViaHoleEdgeClearance;\n for (const o11 of e54.otherNewViaPoints ?? [])\n Math.hypot(o11.x - e54.point.x, o11.y - e54.point.y) \u003c n8 - 0.000000001 \u0026\u0026 t4.add(`new-via-drill:${o11.x},${o11.y}:${e54.holeDiameter}`);\n const o10 = e54.fixedVias ?? [];\n for (let n10 = 0;n10 \u003c o10.length; n10++) {\n const i9 = o10[n10], r10 = e54.holeDiameter / 2 + i9.holeDiameter / 2 + this.minViaHoleEdgeToViaHoleEdgeClearance;\n Math.hypot(i9.point.x - e54.point.x, i9.point.y - e54.point.y) \u003c r10 - 0.000000001 \u0026\u0026 t4.add(`fixed-via-drill:${n10}:${i9.point.x},${i9.point.y}:${i9.holeDiameter}`);\n }\n const i8 = e54.holeDiameter / 2 + this.maxIndexedViaHoleDiameter / 2 + this.minViaHoleEdgeToViaHoleEdgeClearance, r9 = this.index?.search(e54.point.x - i8, e54.point.y - i8, e54.point.x + i8, e54.point.y + i8) ?? [], s7 = new Set;\n for (const n10 of r9) {\n const o11 = this.items[n10];\n if (o11.kind !== \"via\" || o11.exactShape?.type !== \"circle\")\n continue;\n if (o11.traceIndex === e54.ignoreTraceIndex \u0026\u0026 e54.ignoreRouteRange \u0026\u0026 (o11.routeEndIndex ?? -1) \u003e= e54.ignoreRouteRange.start \u0026\u0026 (o11.routeStartIndex ?? Number.POSITIVE_INFINITY) \u003c= e54.ignoreRouteRange.end)\n continue;\n if (e54.ignoreTraceIndices?.includes(o11.traceIndex ?? -1))\n continue;\n const i9 = `${this.copperObjectIds[n10] ?? \"unknown\"}:${o11.routeStartIndex ?? -1}`;\n if (s7.has(i9))\n continue;\n s7.add(i9);\n const r10 = o11.viaHoleDiameter ?? this.defaultViaHoleDiameter, a9 = e54.holeDiameter / 2 + r10 / 2 + this.minViaHoleEdgeToViaHoleEdgeClearance;\n Math.hypot(o11.exactShape.center.x - e54.point.x, o11.exactShape.center.y - e54.point.y) \u003c a9 - 0.000000001 \u0026\u0026 t4.add(`indexed-via-drill:${this.getViolationObjectId(n10)}`);\n }\n return t4;\n }\n getViolationObjectId(e54) {\n const t4 = this.items[e54], n8 = this.copperObjectIds[e54], o10 = `${t4.routeStartIndex ?? \"\"}-${t4.routeEndIndex ?? \"\"}`;\n if (t4.kind === \"obstacle\")\n return n8;\n if (t4.exactShape?.type === \"segment\") {\n const { start: e60, end: i8, width: r9 } = t4.exactShape;\n return `${n8}:${t4.kind}:${o10}:${e60.x},${e60.y}:${i8.x},${i8.y}:${r9}`;\n }\n if (t4.exactShape?.type === \"circle\") {\n const { center: e60, radius: i8 } = t4.exactShape;\n return `${n8}:${t4.kind}:${o10}:${e60.x},${e60.y}:${i8}`;\n }\n return t4.exactShape?.type === \"polygon\" ? `${n8}:${t4.kind}:${o10}:${t4.exactShape.points.map((e60) =\u003e `${e60.x},${e60.y}`).join(\";\")}` : `${n8}:${t4.kind}:${o10}:${t4.minX},${t4.minY},${t4.maxX},${t4.maxY}`;\n }\n getLayerCollisionIndex(e54) {\n const t4 = this.collisionIndexesByLayer.get(e54);\n if (t4)\n return t4;\n const n8 = [];\n for (let t10 = 0;t10 \u003c this.items.length; t10++)\n this.items[t10].layers.includes(e54) \u0026\u0026 n8.push(t10);\n const o10 = n8.length ? new xee(n8.length) : null;\n for (const e60 of n8) {\n const t10 = this.items[e60];\n o10.add(t10.minX, t10.minY, t10.maxX, t10.maxY);\n }\n o10?.finish();\n const i8 = { index: o10, itemIndices: n8 };\n return this.collisionIndexesByLayer.set(e54, i8), i8;\n }\n getCollisionCandidates(e54, t4 = false) {\n const n8 = Math.max(this.clearance, this.holeClearance, e54.isVia ? this.minPadEdgeToPadEdgeClearance : 0, e54.obstacleClearance ?? this.clearance, e54.sameNetObstacleClearance ?? 0), o10 = e54.width / 2 + n8, i8 = { minX: Math.min(e54.start.x, e54.end.x) - o10, minY: Math.min(e54.start.y, e54.end.y) - o10, maxX: Math.max(e54.start.x, e54.end.x) + o10, maxY: Math.max(e54.start.y, e54.end.y) + o10 }, r9 = t4 ? this.getLayerCollisionIndex(e54.layer) : null, s7 = r9 ? r9.index : this.index;\n let a9 = s7?.search(i8.minX, i8.minY, i8.maxX, i8.maxY) ?? [];\n return r9 \u0026\u0026 (a9 = a9.map((e60) =\u003e r9.itemIndices[e60])), { radius: o10, candidates: a9, canonicalConnectionNames: this.connectionNameResolver.canonicalize(e54.connectionNames) };\n }\n itemCollides(e54, t4, n8, o10) {\n const i8 = this.getItemCollisionRadius(e54, t4, o10);\n return i8 !== null \u0026\u0026 this.itemGeometryCollides(this.items[e54], t4, i8);\n }\n getItemCollisionRadius(e54, t4, n8) {\n const o10 = this.items[e54];\n if (!o10.layers.includes(t4.layer))\n return null;\n const i8 = this.connectionNameSets[e54], r9 = n8.some((e60) =\u003e i8.has(e60));\n if (r9 \u0026\u0026 (!t4.blockSameNetObstacles || o10.kind !== \"obstacle\" || o10.obstacleKind === \"via\"))\n return null;\n if (o10.kind === \"trace\" \u0026\u0026 t4.ignoreTraceIndices?.includes(o10.traceIndex ?? -1))\n return null;\n if (o10.kind === \"trace\" \u0026\u0026 o10.traceIndex === t4.ignoreTraceIndex \u0026\u0026 t4.ignoreRouteRange \u0026\u0026 (o10.routeEndIndex ?? -1) \u003e= t4.ignoreRouteRange.start \u0026\u0026 (o10.routeStartIndex ?? Number.POSITIVE_INFINITY) \u003c= t4.ignoreRouteRange.end)\n return null;\n const s7 = t4.isVia \u0026\u0026 (o10.kind === \"via\" || o10.kind === \"obstacle\" \u0026\u0026 o10.obstacleKind === \"via\") ? this.minPadEdgeToPadEdgeClearance : o10.kind !== \"obstacle\" || o10.obstacleKind !== \"hole\" || t4.isVia ? o10.kind === \"obstacle\" \u0026\u0026 o10.obstacleKind === \"pad\" ? r9 \u0026\u0026 t4.blockSameNetObstacles ? t4.sameNetObstacleClearance ?? t4.obstacleClearance ?? this.clearance : t4.obstacleClearance ?? this.clearance : this.clearance : this.holeClearance;\n return t4.width / 2 + s7;\n }\n itemGeometryCollides(e54, t4, n8) {\n return e54.exactShape?.type === \"segment\" ? G7(t4.start, t4.end, e54.exactShape.start, e54.exactShape.end, n8 + e54.exactShape.width / 2 + 0.000000001) : e54.exactShape?.type === \"polygon\" ? ((e60, t10, n10, o10) =\u003e {\n if (V7(e60, n10) || V7(t10, n10))\n return 0 \u003c= o10;\n for (let i8 = 0;i8 \u003c n10.length; i8++)\n if (G7(e60, t10, n10[i8], n10[(i8 + 1) % n10.length], o10))\n return true;\n return Number.POSITIVE_INFINITY \u003c= o10;\n })(t4.start, t4.end, e54.exactShape.points, n8 + 0.000000001) : e54.exactShape?.type === \"circle\" ? B7(e54.exactShape.center, t4.start, t4.end) \u003c= n8 + e54.exactShape.radius + 0.000000001 : U7(t4.start, t4.end, { minX: e54.minX - n8, minY: e54.minY - n8, maxX: e54.maxX + n8, maxY: e54.maxY + n8 });\n }\n itemCopperTouches(e54, t4, n8) {\n return e54.exactShape?.type === \"segment\" ? H7(t4.start, t4.end, e54.exactShape.start, e54.exactShape.end) \u003c= n8 + e54.exactShape.width / 2 + 0.000000001 : e54.exactShape?.type === \"polygon\" ? W7(t4.start, t4.end, e54.exactShape.points) \u003c= n8 + 0.000000001 : e54.exactShape?.type === \"circle\" ? B7(e54.exactShape.center, t4.start, t4.end) \u003c= n8 + e54.exactShape.radius + 0.000000001 : U7(t4.start, t4.end, { minX: e54.minX - n8, minY: e54.minY - n8, maxX: e54.maxX + n8, maxY: e54.maxY + n8 });\n }\n isOutsideBounds(e54) {\n const t4 = e54.width / 2 + this.boardEdgeClearance;\n return Math.min(e54.start.x, e54.end.x) - t4 \u003c this.bounds.minX || Math.max(e54.start.x, e54.end.x) + t4 \u003e this.bounds.maxX || Math.min(e54.start.y, e54.end.y) - t4 \u003c this.bounds.minY || Math.max(e54.start.y, e54.end.y) + t4 \u003e this.bounds.maxY;\n }\n};\nvar Pee = [{ x: 0, y: 0 }, { x: 0.5, y: 0 }, { x: 0, y: 0.5 }, { x: 0.5, y: 0.5 }];\nvar Mee = (e54) =\u003e e54?.route_type === \"wire\";\nvar wee = class extends BaseSolver {\n inputProblem;\n traces;\n corridor;\n phase = \"scan-corridor\";\n corridorCursor = 0;\n blockerCursor = 0;\n offsetCursor = 0;\n resolutionCursor = 0;\n attemptedGridCount = 0;\n blockerIndex;\n connectionNameResolver;\n connectionByTraceId = new Map;\n mutableTraceIndices;\n blockersByTrace = new Map;\n blockers = [];\n currentBlocker = null;\n currentRange = null;\n currentTraceWidth = 0;\n gridResolutions = [];\n currentObstacleIndex = null;\n output = null;\n constructor(e54, t4 = new D7(e54.simpleRouteJson, e54.traces)) {\n super(), this.inputProblem = structuredClone(e54), this.traces = this.inputProblem.traces.slice(), this.corridor = structuredClone(e54.corridor), this.mutableTraceIndices = e54.mutableTraceIndices ? new Set(e54.mutableTraceIndices) : null, this.connectionNameResolver = t4, this.blockerIndex = new Cee(this.inputProblem.simpleRouteJson, this.traces, e54.powerTraceIndex, [], this.connectionNameResolver), this.activeSubSolver = null, this.MAX_ITERATIONS = 25000, this.stats = this.createStats();\n }\n getSolverName() {\n return \"LocalTraceInflationSolver\";\n }\n _step() {\n if (this.activeSubSolver) {\n const e54 = this.activeSubSolver;\n return this.stepActiveSubSolver(), void ((e54.solved || e54.failed) \u0026\u0026 (this.stats = this.createStats()));\n }\n switch (this.phase) {\n case \"scan-corridor\":\n this.scanNextCorridorSegment();\n break;\n case \"select-blocker\":\n this.selectNextBlocker();\n break;\n case \"try-elastic-push\":\n break;\n case \"try-grid-candidate\":\n this.startNextGridCandidate();\n break;\n case \"complete\":\n this.output ? this.solved = true : (this.failed = true, this.error = \"No locally reroutable trace blocks the power corridor\");\n }\n this.stats = this.createStats();\n }\n scanNextCorridorSegment() {\n const e54 = this.corridor[this.corridorCursor];\n if (!e54)\n return this.blockers = [...this.blockersByTrace.values()].sort((e60, t10) =\u003e e60.traceIndex - t10.traceIndex), void (this.phase = \"select-blocker\");\n const t4 = this.traces[this.inputProblem.powerTraceIndex], n8 = this.blockerIndex.findCollisions({ start: e54.start, end: e54.end, layer: e54.layer, width: e54.width, connectionNames: t4 ? this.getTraceConnectionNames(t4) : [] });\n for (const e60 of n8)\n this.recordBlockingTrace(e60);\n this.corridorCursor++;\n }\n recordBlockingTrace(e54) {\n if (e54.kind !== \"trace\" || e54.traceIndex === undefined || e54.routeStartIndex === undefined || e54.routeEndIndex === undefined || e54.traceIndex === this.inputProblem.powerTraceIndex || this.mutableTraceIndices !== null \u0026\u0026 !this.mutableTraceIndices.has(e54.traceIndex))\n return;\n const t4 = this.traces[e54.traceIndex];\n if (!t4)\n return;\n const n8 = this.findConnectionForTrace(t4);\n if ((n8 ? this.resolveNominalTraceWidth(n8) : this.getTraceNominalWidth(t4)) \u003e= (this.inputProblem.pushOnlyNominalWidthsBelow ?? this.inputProblem.nominalPowerWidth) - L7)\n return;\n const o10 = this.blockersByTrace.get(e54.traceIndex);\n if (o10)\n return o10.firstRouteIndex = Math.min(o10.firstRouteIndex, e54.routeStartIndex), void (o10.lastRouteIndex = Math.max(o10.lastRouteIndex, e54.routeEndIndex));\n this.blockersByTrace.set(e54.traceIndex, { traceIndex: e54.traceIndex, firstRouteIndex: e54.routeStartIndex, lastRouteIndex: e54.routeEndIndex });\n }\n selectNextBlocker() {\n if (this.currentBlocker = this.blockers[this.blockerCursor] ?? null, !this.currentBlocker)\n return void (this.phase = \"complete\");\n const e54 = this.findStableAnchorRange(this.currentBlocker);\n if (!e54)\n return void this.blockerCursor++;\n const t4 = this.traces[this.currentBlocker.traceIndex];\n this.currentRange = e54, this.currentTraceWidth = this.getRangeWidth(t4, e54), this.gridResolutions = this.getGridResolutions(this.currentTraceWidth), this.resolutionCursor = 0, this.offsetCursor = 0, this.currentObstacleIndex = new Cee(this.inputProblem.simpleRouteJson, this.traces, this.currentBlocker.traceIndex, this.createInflatedCorridorItems(), this.connectionNameResolver), this.activeSubSolver = new lee({ trace: t4, range: e54, layer: t4.route[e54.startIndex].layer, traceWidth: this.currentTraceWidth, corridor: this.corridor, obstacleIndex: this.currentObstacleIndex, connectionNames: this.getTraceConnectionNames(t4) }), this.phase = \"try-elastic-push\";\n }\n findStableAnchorRange(e54) {\n const t4 = this.traces[e54.traceIndex];\n if (!t4)\n return null;\n let { firstRouteIndex: n8, lastRouteIndex: o10 } = e54;\n for (;n8 \u003e 0; ) {\n const e60 = t4.route[n8];\n if (Mee(e60) \u0026\u0026 this.pointClearsCorridor(e60))\n break;\n n8--;\n }\n for (;o10 \u003c t4.route.length - 1; ) {\n const e60 = t4.route[o10];\n if (Mee(e60) \u0026\u0026 this.pointClearsCorridor(e60))\n break;\n o10++;\n }\n const i8 = t4.route[n8], r9 = t4.route[o10];\n if (!Mee(i8) || !Mee(r9) || i8.layer !== r9.layer || !this.pointClearsCorridor(i8) || !this.pointClearsCorridor(r9) || n8 \u003e= o10)\n return null;\n const s7 = { startIndex: n8, endIndex: o10 }, a9 = this.getRangeLength(t4, s7);\n return !Number.isFinite(a9) || a9 \u003e (this.inputProblem.maxRerouteLength ?? 10) + L7 ? null : s7;\n }\n pointClearsCorridor(e54) {\n return this.corridor.every((t4) =\u003e {\n if (t4.layer !== e54.layer)\n return true;\n const n8 = t4.width / 2 + e54.width / 2 + this.blockerIndex.clearance;\n return B7(e54, t4.start, t4.end) \u003e= n8 - L7;\n });\n }\n startNextGridCandidate() {\n if (!this.currentBlocker || !this.currentRange)\n return void (this.phase = \"select-blocker\");\n if (this.resolutionCursor \u003e= this.gridResolutions.length)\n return this.blockerCursor++, void (this.phase = \"select-blocker\");\n if (this.offsetCursor \u003e= Pee.length)\n return this.resolutionCursor++, void (this.offsetCursor = 0);\n const e54 = this.traces[this.currentBlocker.traceIndex], t4 = e54.route[this.currentRange.startIndex], n8 = e54.route[this.currentRange.endIndex];\n if (!Mee(t4) || !Mee(n8))\n return this.blockerCursor++, void (this.phase = \"select-blocker\");\n const o10 = this.gridResolutions[this.resolutionCursor], i8 = Pee[this.offsetCursor], r9 = this.currentObstacleIndex;\n if (!r9)\n return this.blockerCursor++, void (this.phase = \"select-blocker\");\n this.attemptedGridCount++, this.activeSubSolver = new yee({ start: t4, end: n8, layer: t4.layer, traceWidth: this.currentTraceWidth, gridSize: o10, gridOffset: { x: i8.x * o10, y: i8.y * o10 }, connectionNames: this.getTraceConnectionNames(e54), obstacleIndex: r9, ignoreTraceIndex: this.currentBlocker.traceIndex, ignoreRouteRange: { start: this.currentRange.startIndex, end: this.currentRange.endIndex }, bounds: this.inputProblem.simpleRouteJson.bounds, searchPadding: j7(2.5 * this.inputProblem.nominalPowerWidth, 1.5, 4) });\n }\n stepActiveSubSolver() {\n const e54 = this.activeSubSolver;\n if (e54.step(), e54.solved || e54.failed) {\n if (e54.solved) {\n const t4 = e54.getOutput();\n if (t4)\n return this.applyRoute(t4, e54 instanceof lee ? \"elastic\" : \"grid\"), this.activeSubSolver = null, void (this.phase = \"complete\");\n }\n this.failedSubSolvers ??= [], this.failedSubSolvers.push(e54), this.activeSubSolver = null, e54 instanceof lee ? this.phase = \"try-grid-candidate\" : this.offsetCursor++;\n }\n }\n applyRoute(e54, t4) {\n const n8 = this.currentBlocker, o10 = this.currentRange;\n this.traces = structuredClone(this.traces);\n const i8 = this.traces[n8.traceIndex], r9 = i8.route[o10.startIndex], s7 = i8.route[o10.endIndex], a9 = e54.points.map((e60) =\u003e ({ route_type: \"wire\", x: e60.x, y: e60.y, width: this.currentTraceWidth, layer: r9.layer }));\n a9[0].width = Math.max(a9[0].width, r9.width), a9[a9.length - 1].width = Math.max(a9[a9.length - 1].width, s7.width), i8.route.splice(o10.startIndex, o10.endIndex - o10.startIndex + 1, ...a9), this.output = { traces: this.traces, pushedTraceIndex: n8.traceIndex, replacedRange: o10, strategy: t4 };\n }\n createInflatedCorridorItems() {\n return this.corridor.flatMap((e54) =\u003e q7({ start: e54.start, end: e54.end, width: e54.width, base: { layers: [e54.layer], kind: \"obstacle\", connectionNames: [] } }));\n }\n getGridResolutions(e54) {\n return [j7(1.5 * e54, 0.1, 0.3), j7(0.75 * e54, 0.08, 0.18)].filter((e60, t4, n8) =\u003e n8.findIndex((t10) =\u003e Math.abs(t10 - e60) \u003c L7) === t4);\n }\n getRangeWidth(e54, t4) {\n let n8 = this.inputProblem.simpleRouteJson.minTraceWidth;\n for (let o10 = t4.startIndex;o10 \u003c= t4.endIndex; o10++) {\n const t10 = e54.route[o10];\n Mee(t10) \u0026\u0026 (n8 = Math.max(n8, t10.width));\n }\n return n8;\n }\n getRangeLength(e54, t4) {\n let n8 = 0;\n for (let o10 = t4.startIndex;o10 \u003c t4.endIndex; o10++) {\n const t10 = e54.route[o10], i8 = e54.route[o10 + 1];\n if (!Mee(t10) || !Mee(i8) || t10.layer !== i8.layer)\n return Number.POSITIVE_INFINITY;\n n8 += z7(t10, i8);\n }\n return n8;\n }\n resolveNominalTraceWidth(e54) {\n return Math.max(e54.nominalTraceWidth ?? e54.width ?? this.inputProblem.simpleRouteJson.nominalTraceWidth ?? this.inputProblem.simpleRouteJson.minTraceWidth, this.inputProblem.simpleRouteJson.minTraceWidth);\n }\n getTraceNominalWidth(e54) {\n return e54.route.reduce((e60, t4) =\u003e t4.route_type === \"wire\" ? Math.max(e60, t4.width) : e60, this.inputProblem.simpleRouteJson.minTraceWidth);\n }\n findConnectionForTrace(e54) {\n const t4 = this.connectionByTraceId.get(e54.pcb_trace_id);\n if (t4 !== undefined)\n return t4 ?? undefined;\n const n8 = this.getTraceConnectionNames(e54), o10 = this.inputProblem.simpleRouteJson.connections.find((e60) =\u003e [e60.name, e60.source_trace_id, e60.rootConnectionName, e60.netConnectionName, ...e60.mergedConnectionNames ?? []].filter((e61) =\u003e Boolean(e61)).some((e61) =\u003e n8.includes(e61))) ?? null;\n return this.connectionByTraceId.set(e54.pcb_trace_id, o10), o10 ?? undefined;\n }\n getTraceConnectionNames(e54) {\n return [e54.connection_name, e54.source_trace_id, e54.rootConnectionName, ...e54.mergedConnectionNames ?? []].filter((e60) =\u003e Boolean(e60));\n }\n createStats() {\n return { phase: this.phase, corridorSegment: this.corridorCursor, corridorSegmentCount: this.corridor.length, blockingTraceCount: this.blockersByTrace.size, blockerCursor: this.blockerCursor, pushedTraceIndex: this.currentBlocker?.traceIndex, anchorRange: this.currentRange, traceWidth: this.currentTraceWidth, gridSize: this.gridResolutions[this.resolutionCursor], gridOffsetVariant: this.offsetCursor, attemptedGridCount: this.attemptedGridCount };\n }\n computeProgress() {\n return this.phase === \"scan-corridor\" ? this.corridor.length === 0 ? 0.25 : this.corridorCursor / this.corridor.length * 0.25 : this.blockers.length === 0 ? 0.5 : Math.min(0.99, 0.25 + this.blockerCursor / this.blockers.length);\n }\n getOutput() {\n return this.output;\n }\n getConstructorParams() {\n return [this.inputProblem];\n }\n visualize() {\n const e54 = [];\n for (let t4 = 0;t4 \u003c this.traces.length; t4++) {\n const n8 = this.traces[t4];\n for (let o10 = 0;o10 \u003c n8.route.length - 1; o10++) {\n const i8 = n8.route[o10], r9 = n8.route[o10 + 1];\n Mee(i8) \u0026\u0026 Mee(r9) \u0026\u0026 i8.layer === r9.layer \u0026\u0026 e54.push({ points: [i8, r9], strokeColor: t4 === this.currentBlocker?.traceIndex ? \"#1769d2\" : \"#777\", strokeWidth: Math.max(i8.width, r9.width) });\n }\n }\n for (const t4 of this.corridor)\n e54.push({ points: [t4.start, t4.end], strokeColor: \"rgba(255, 128, 0, 0.55)\", strokeWidth: t4.width });\n return { coordinateSystem: \"cartesian\", title: this.getSolverName(), lines: e54, points: [], rects: [], circles: [], texts: [] };\n }\n};\nvar Nee = 0.000001;\nvar Ree = (e54, t4) =\u003e Math.hypot(e54.x - t4.x, e54.y - t4.y);\nvar Tee = (e54, t4, n8) =\u003e {\n const o10 = n8.x - t4.x, i8 = n8.y - t4.y, r9 = o10 * o10 + i8 * i8, s7 = r9 \u003c= 0.000000000001 ? 0 : Math.max(0, Math.min(1, ((e54.x - t4.x) * o10 + (e54.y - t4.y) * i8) / r9));\n return Math.hypot(e54.x - (t4.x + s7 * o10), e54.y - (t4.y + s7 * i8));\n};\nvar Eee = (e54, t4, n8) =\u003e (t4.x - e54.x) * (n8.y - e54.y) - (t4.y - e54.y) * (n8.x - e54.x);\nvar Aee = (e54, t4, n8, o10) =\u003e ((e60, t10, n10, o11) =\u003e {\n const i8 = Eee(n10, o11, e60), r9 = Eee(n10, o11, t10), s7 = Eee(e60, t10, n10), a9 = Eee(e60, t10, o11);\n return (i8 \u003e 0 \u0026\u0026 r9 \u003c 0 || i8 \u003c 0 \u0026\u0026 r9 \u003e 0) \u0026\u0026 (s7 \u003e 0 \u0026\u0026 a9 \u003c 0 || s7 \u003c 0 \u0026\u0026 a9 \u003e 0);\n})(e54, t4, n8, o10) ? 0 : Math.min(Tee(e54, n8, o10), Tee(t4, n8, o10), Tee(n8, e54, t4), Tee(o10, e54, t4));\nvar Oee = (e54) =\u003e {\n const t4 = (e54.ccwRotationDegrees ?? 0) * Math.PI / 180, n8 = Math.cos(t4), o10 = Math.sin(t4);\n return [{ x: -e54.width / 2, y: -e54.height / 2 }, { x: e54.width / 2, y: -e54.height / 2 }, { x: e54.width / 2, y: e54.height / 2 }, { x: -e54.width / 2, y: e54.height / 2 }].map((t10) =\u003e ({ x: e54.center.x + t10.x * n8 - t10.y * o10, y: e54.center.y + t10.x * o10 + t10.y * n8 }));\n};\nvar kee = (e54) =\u003e {\n if (!(e54.type === \"oval\" || e54.shape === \"circle\"))\n return false;\n if (Math.abs(e54.width - e54.height) \u003e Nee)\n throw new Error(`Physical connectivity does not yet support non-circular oval obstacle ${e54.obstacleId ?? \"\u003cunknown\u003e\"}`);\n return true;\n};\nvar Dee = (e54, t4) =\u003e {\n for (let n10 = 0;n10 \u003c t4.length; n10++)\n if (Tee(e54, t4[n10], t4[(n10 + 1) % t4.length]) \u003c= Nee)\n return true;\n let n8 = false;\n for (let o10 = 0, i8 = t4.length - 1;o10 \u003c t4.length; i8 = o10++) {\n const r9 = t4[o10], s7 = t4[i8];\n r9.y \u003e e54.y != s7.y \u003e e54.y \u0026\u0026 e54.x \u003c (s7.x - r9.x) * (e54.y - r9.y) / (s7.y - r9.y) + r9.x \u0026\u0026 (n8 = !n8);\n }\n return n8;\n};\nvar Lee = (e54, t4) =\u003e {\n if (kee(t4))\n return Math.max(0, Ree(e54, t4.center) - t4.width / 2);\n const n8 = Oee(t4);\n return Dee(e54, n8) ? 0 : Math.min(...n8.map((t10, o10) =\u003e Tee(e54, t10, n8[(o10 + 1) % n8.length])));\n};\nvar zee = (e54, t4) =\u003e {\n if (kee(e54))\n return kee(t4) ? Math.max(0, Ree(e54.center, t4.center) - e54.width / 2 - t4.width / 2) : Math.max(0, Lee(e54.center, t4) - e54.width / 2);\n if (kee(t4))\n return zee(t4, e54);\n const n8 = Oee(e54), o10 = Oee(t4);\n if (Dee(n8[0], o10) || Dee(o10[0], n8))\n return 0;\n let i8 = Number.POSITIVE_INFINITY;\n for (let e60 = 0;e60 \u003c n8.length; e60++)\n for (let t10 = 0;t10 \u003c o10.length; t10++)\n i8 = Math.min(i8, Aee(n8[e60], n8[(e60 + 1) % n8.length], o10[t10], o10[(t10 + 1) % o10.length]));\n return i8;\n};\nvar Bee = (e54, t4) =\u003e ({ minX: e54.minX - t4, minY: e54.minY - t4, maxX: e54.maxX + t4, maxY: e54.maxY + t4 });\nvar Fee = (e54) =\u003e ({ minX: e54.x, minY: e54.y, maxX: e54.x, maxY: e54.y });\nvar jee = (e54) =\u003e {\n if (kee(e54))\n return Bee(Fee(e54.center), e54.width / 2);\n const t4 = Oee(e54);\n return { minX: Math.min(...t4.map((e60) =\u003e e60.x)), minY: Math.min(...t4.map((e60) =\u003e e60.y)), maxX: Math.max(...t4.map((e60) =\u003e e60.x)), maxY: Math.max(...t4.map((e60) =\u003e e60.y)) };\n};\nvar $ee = (e54, t4) =\u003e {\n if (!((e60, t10) =\u003e e60.layers.some((e61) =\u003e t10.layers.includes(e61)))(e54, t4) || !((e60, t10) =\u003e e60.maxX + Nee \u003e= t10.minX \u0026\u0026 t10.maxX + Nee \u003e= e60.minX \u0026\u0026 e60.maxY + Nee \u003e= t10.minY \u0026\u0026 t10.maxY + Nee \u003e= e60.minY)(e54.bounds, t4.bounds))\n return false;\n if (e54.kind === \"bridge-pad\") {\n const n8 = { kind: \"obstacle\", obstacle: e54.obstacle, layers: e54.layers, bounds: e54.bounds };\n return t4.kind === \"bridge-pad\" ? $ee(n8, { kind: \"obstacle\", obstacle: t4.obstacle, layers: t4.layers, bounds: t4.bounds }) : $ee(n8, t4);\n }\n return t4.kind === \"bridge-pad\" ? $ee(t4, e54) : e54.kind === \"endpoint\" ? t4.kind === \"endpoint\" ? Ree(e54.point, t4.point) \u003c= Nee : t4.kind === \"obstacle\" ? Lee(e54.point, t4.obstacle) \u003c= Nee : t4.kind === \"segment\" ? Tee(e54.point, t4.start, t4.end) \u003c= t4.width / 2 + Nee : Ree(e54.point, t4.center) \u003c= t4.diameter / 2 + Nee : t4.kind === \"endpoint\" ? $ee(t4, e54) : e54.kind === \"obstacle\" ? t4.kind === \"obstacle\" ? zee(e54.obstacle, t4.obstacle) \u003c= Nee : t4.kind === \"segment\" ? ((e60, t10, n8) =\u003e {\n if (kee(n8))\n return Math.max(0, Tee(n8.center, e60, t10) - n8.width / 2);\n const o10 = Oee(n8);\n return Dee(e60, o10) || Dee(t10, o10) ? 0 : Math.min(...o10.map((n10, i8) =\u003e Aee(e60, t10, n10, o10[(i8 + 1) % o10.length])));\n })(t4.start, t4.end, e54.obstacle) \u003c= t4.width / 2 + Nee : Lee(t4.center, e54.obstacle) \u003c= t4.diameter / 2 + Nee : t4.kind === \"obstacle\" ? $ee(t4, e54) : e54.kind === \"segment\" ? t4.kind === \"segment\" ? Aee(e54.start, e54.end, t4.start, t4.end) \u003c= (e54.width + t4.width) / 2 + Nee : Tee(t4.center, e54.start, e54.end) \u003c= e54.width / 2 + t4.diameter / 2 + Nee : t4.kind === \"segment\" ? $ee(t4, e54) : Ree(e54.center, t4.center) \u003c= (e54.diameter + t4.diameter) / 2 + Nee;\n};\nvar Yee = class {\n parent;\n constructor(e54) {\n this.parent = Array.from({ length: e54 }, (e60, t4) =\u003e t4);\n }\n find(e54) {\n const t4 = this.parent[e54];\n if (t4 === e54)\n return e54;\n const n8 = this.find(t4);\n return this.parent[e54] = n8, n8;\n }\n union(e54, t4) {\n const n8 = this.find(e54), o10 = this.find(t4);\n n8 !== o10 \u0026\u0026 (this.parent[o10] = n8);\n }\n};\nvar Xee = (e54, t4) =\u003e {\n const n8 = t4.indexOf(e54.from_layer), o10 = t4.indexOf(e54.to_layer);\n return n8 \u003c 0 || o10 \u003c 0 ? [...new Set([e54.from_layer, e54.to_layer])] : t4.slice(Math.min(n8, o10), Math.max(n8, o10) + 1);\n};\nvar Hee = (e54) =\u003e [e54.pcb_trace_id, e54.connection_name, e54.source_trace_id, e54.rootConnectionName, ...e54.mergedConnectionNames ?? [], ...e54.connectsTo ?? []].filter((e60) =\u003e Boolean(e60));\nvar Vee = (e54) =\u003e [e54.name, e54.source_trace_id, e54.rootConnectionName, ...e54.mergedConnectionNames ?? [], e54.netConnectionName, ...e54.pointsToConnect.flatMap((e60) =\u003e [e60.pointId, e60.pcb_port_id])].filter((e60) =\u003e Boolean(e60));\nvar Wee = (e54) =\u003e [e54.obstacleId, ...e54.connectedTo, ...e54.offBoardConnectsTo ?? []].filter((e60) =\u003e Boolean(e60));\nvar Gee = (e54, t4, n8, o10) =\u003e ({ kind: \"bridge-contact\", center: { x: e54.x, y: e54.y }, diameter: t4, layers: n8, bridgeId: o10, bounds: Bee(Fee(e54), t4 / 2) });\nvar Uee = 0.01;\nvar Zee = { \"0603\": { horizontalWidth: 0.8, horizontalHeight: 0.95, centerSpacings: [1.65, 1.8] }, 1206: { horizontalWidth: 0.6, horizontalHeight: 1.6, centerSpacings: [3.2] }, \"1206x4_pair\": { horizontalWidth: 0.8, horizontalHeight: 0.5, centerSpacings: [2.7] } };\nvar qee = (e54, t4, n8) =\u003e {\n if (!e54.layer)\n throw new Error(`Jumper ${n8} is missing its layer`);\n const o10 = Zee[e54.footprint];\n if (!o10)\n throw new Error(`Unsupported jumper footprint ${String(e54.footprint)} on ${n8}`);\n const i8 = Math.abs(e54.end.x - e54.start.x), r9 = Math.abs(e54.end.y - e54.start.y), s7 = (e60) =\u003e o10.centerSpacings.some((t10) =\u003e Math.abs(e60 - t10) \u003c Uee), a9 = r9 \u003c Uee \u0026\u0026 s7(i8), c5 = i8 \u003c Uee \u0026\u0026 s7(r9);\n if (!a9 \u0026\u0026 !c5)\n throw new Error(`Jumper ${n8} does not match ${e54.footprint} pad spacing`);\n const l5 = { type: \"rect\", center: { ...t4 }, width: a9 ? o10.horizontalWidth : o10.horizontalHeight, height: a9 ? o10.horizontalHeight : o10.horizontalWidth, layers: [e54.layer], connectedTo: [] };\n return { kind: \"bridge-pad\", obstacle: l5, layers: l5.layers, bridgeId: n8, bounds: jee(l5) };\n};\nvar Jee = (e54, t4, n8) =\u003e {\n if (e54.layer !== n8.layer || t4.layer !== n8.layer)\n return false;\n const o10 = (e60, t10) =\u003e Math.abs(e60.x - t10.x) \u003c Uee \u0026\u0026 Math.abs(e60.y - t10.y) \u003c Uee, i8 = o10(e54, n8.start) \u0026\u0026 o10(t4, n8.end), r9 = o10(e54, n8.end) \u0026\u0026 o10(t4, n8.start);\n return i8 || r9;\n};\nvar Qee = (e54, t4, n8, o10) =\u003e {\n const i8 = [], r9 = e54.route.flatMap((e60, t10) =\u003e e60.route_type === \"jumper\" ? [{ routePoint: e60, routePointIndex: t10 }] : []), s7 = new Map;\n for (const t10 of r9) {\n const n10 = [];\n for (let o12 = 1;o12 \u003c e54.route.length; o12++) {\n const i9 = e54.route[o12 - 1], r10 = e54.route[o12];\n i9?.route_type === \"wire\" \u0026\u0026 r10?.route_type === \"wire\" \u0026\u0026 Jee(i9, r10, t10.routePoint) \u0026\u0026 n10.push(o12);\n }\n if (n10.length !== 1)\n throw new Error(`Jumper ${e54.pcb_trace_id}:${t10.routePointIndex} matched ${n10.length} placeholder wire segments`);\n const o11 = n10[0];\n if (s7.has(o11))\n throw new Error(`Multiple jumpers matched placeholder segment ${o11} on ${e54.pcb_trace_id}`);\n s7.set(o11, t10);\n }\n let a9;\n for (let r10 = 0;r10 \u003c e54.route.length; r10++) {\n const c5 = e54.route[r10];\n if (c5.route_type === \"wire\") {\n if (a9 \u0026\u0026 a9.layer === c5.layer \u0026\u0026 Ree(a9, c5) \u003e Nee) {\n const e60 = a9;\n if (s7.get(r10))\n ;\n else {\n const t10 = e60.width / 2;\n i8.push({ kind: \"segment\", start: { x: e60.x, y: e60.y }, end: { x: c5.x, y: c5.y }, width: e60.width, layers: [e60.layer], bounds: Bee({ minX: Math.min(e60.x, c5.x), minY: Math.min(e60.y, c5.y), maxX: Math.max(e60.x, c5.x), maxY: Math.max(e60.y, c5.y) }, t10) });\n }\n }\n a9 = c5;\n continue;\n }\n if (a9 = undefined, c5.route_type === \"via\") {\n const o11 = e54.route[r10 - 1], s9 = e54.route[r10 + 1];\n for (const t10 of [o11, s9])\n if (t10?.route_type === \"wire\" \u0026\u0026 Ree(t10, c5) \u003e Nee)\n throw new Error(`Via ${e54.pcb_trace_id}:${r10} is adjacent to a non-colocated wire endpoint`);\n const a10 = c5.via_diameter ?? n8;\n i8.push({ kind: \"via\", center: { x: c5.x, y: c5.y }, diameter: a10, layers: Xee(c5, t4), bounds: Bee(Fee(c5), a10 / 2) });\n continue;\n }\n const l5 = `${e54.pcb_trace_id}:${r10}:${c5.route_type}`;\n if (c5.route_type === \"jumper\") {\n i8.push(qee(c5, c5.start, l5), qee(c5, c5.end, l5));\n continue;\n }\n if (c5.route_type === \"through_obstacle\") {\n if (!o10.find((e60) =\u003e e60.layers.includes(c5.from_layer) \u0026\u0026 e60.layers.includes(c5.to_layer) \u0026\u0026 Lee(c5.start, e60) \u003c= Nee \u0026\u0026 Lee(c5.end, e60) \u003c= Nee))\n throw new Error(`Through-obstacle marker ${l5} has no same-net multilayer obstacle witness`);\n i8.push(Gee(c5.start, 0, [c5.from_layer], l5), Gee(c5.end, 0, [c5.to_layer], l5));\n continue;\n }\n throw new Error(`Unsupported route primitive: ${String(c5.route_type)}`);\n }\n return i8;\n};\nvar Kee = (e54, t4, n8) =\u003e {\n const o10 = e54.pointsToConnect[n8];\n return o10.pointId ?? o10.pcb_port_id ?? `${e54.name}[${t4}:${n8}]`;\n};\nvar ete = (e54) =\u003e {\n const t4 = {}, n8 = {}, o10 = [];\n for (let i8 = 0;i8 \u003c e54.connections.length; i8++) {\n const r9 = e54.connections[i8];\n for (let e60 = 0;e60 \u003c r9.pointsToConnect.length; e60++) {\n const s7 = `${i8}:${e60}`;\n t4[s7] = Kee(r9, i8, e60), n8[s7] = s7, o10.push([s7]);\n }\n }\n return { endpointCount: Object.keys(t4).length, endpointLabels: t4, componentByEndpointKey: n8, endpointComponents: o10 };\n};\nvar tte = (e54) =\u003e {\n if (e54 === null || typeof e54 != \"object\")\n return JSON.stringify(e54) ?? String(e54);\n if (Array.isArray(e54))\n return `[${e54.map((e60) =\u003e tte(e60)).join(\",\")}]`;\n const t4 = e54;\n return `{${Object.keys(t4).sort().map((e60) =\u003e `${JSON.stringify(e60)}:${tte(t4[e60])}`).join(\",\")}}`;\n};\nvar nte = (e54, t4) =\u003e {\n const n8 = new D7(e54, t4, { includePhysicalPositionAliases: true }), o10 = (i8 = e54.layerCount) \u003c= 1 ? [\"top\"] : i8 === 2 ? [\"top\", \"bottom\"] : [\"top\", ...Array.from({ length: i8 - 2 }, (e60, t10) =\u003e `inner${t10 + 1}`), \"bottom\"];\n var i8;\n const r9 = ((e60) =\u003e {\n const t10 = e60.min_via_hole_diameter ?? e60.minViaHoleDiameter ?? 0;\n return Math.max(t10, e60.min_via_pad_diameter ?? e60.minViaPadDiameter ?? e60.minViaDiameter ?? 0.6);\n })(e54), s7 = new Map, a9 = new Map, c5 = {}, l5 = (e60, t10) =\u003e {\n const n10 = s7.get(e60) ?? [];\n n10.push(t10), s7.set(e60, n10);\n };\n for (let t10 = 0;t10 \u003c e54.connections.length; t10++) {\n const o11 = e54.connections[t10], i9 = n8.canonicalize(Vee(o11));\n if (i9.length !== 1)\n throw new Error(`Connection ${o11.name} resolved to ${i9.length} canonical nets`);\n for (let e60 = 0;e60 \u003c o11.pointsToConnect.length; e60++) {\n const n10 = o11.pointsToConnect[e60], r10 = `${t10}:${e60}`, s9 = Kee(o11, t10, e60);\n c5[r10] = s9;\n const a10 = { kind: \"endpoint\", endpointKey: r10, endpointLabel: s9, point: { x: n10.x, y: n10.y }, layers: n10.layers ?? [n10.layer], bounds: Fee(n10) };\n for (const e61 of i9)\n l5(e61, a10);\n }\n }\n for (const t10 of e54.obstacles) {\n const e60 = { kind: \"obstacle\", obstacle: t10, layers: t10.layers, bounds: jee(t10) };\n for (const o11 of n8.canonicalize(Wee(t10))) {\n const n10 = a9.get(o11) ?? [];\n n10.push(t10), a9.set(o11, n10), s7.has(o11) \u0026\u0026 l5(o11, e60);\n }\n }\n for (const i9 of [...t4, ...e54.fixedTraces ?? []]) {\n const e60 = n8.canonicalize(Hee(i9));\n if (e60.length !== 1)\n throw new Error(`Trace ${i9.pcb_trace_id} resolved to ${e60.length} canonical nets`);\n const t10 = a9.get(e60[0]) ?? [], c9 = Qee(i9, o10, r9, t10);\n for (const t11 of e60)\n if (s7.has(t11))\n for (const e61 of c9)\n l5(t11, e61);\n }\n const h5 = {}, d9 = [];\n for (const e60 of s7.values()) {\n const t10 = new Yee(e60.length), n10 = new Map;\n for (let o12 = 0;o12 \u003c e60.length; o12++) {\n const i10 = e60[o12];\n if (i10.kind !== \"bridge-contact\" \u0026\u0026 i10.kind !== \"bridge-pad\")\n continue;\n const r10 = n10.get(i10.bridgeId);\n r10 === undefined ? n10.set(i10.bridgeId, o12) : t10.union(r10, o12);\n }\n const o11 = e60.length \u003e 0 ? new xee(e60.length) : null;\n if (o11) {\n for (const t11 of e60)\n o11.add(t11.bounds.minX, t11.bounds.minY, t11.bounds.maxX, t11.bounds.maxY);\n o11.finish();\n }\n for (let n11 = 0;n11 \u003c e60.length; n11++) {\n const i10 = e60[n11], r10 = o11?.search(i10.bounds.minX - Nee, i10.bounds.minY - Nee, i10.bounds.maxX + Nee, i10.bounds.maxY + Nee) ?? [];\n for (const o12 of r10)\n o12 \u003c= n11 || $ee(i10, e60[o12]) \u0026\u0026 t10.union(n11, o12);\n }\n const i9 = new Map;\n for (let n11 = 0;n11 \u003c e60.length; n11++) {\n const o12 = e60[n11];\n if (o12.kind !== \"endpoint\")\n continue;\n const r10 = t10.find(n11), s9 = i9.get(r10) ?? [];\n s9.push(o12.endpointKey), i9.set(r10, s9);\n }\n for (const e61 of i9.values()) {\n e61.sort();\n const t11 = e61[0];\n d9.push(e61);\n for (const n11 of e61) {\n if (h5[n11] !== undefined)\n throw new Error(`Endpoint ${n11} was assigned to multiple canonical nets`);\n h5[n11] = t11;\n }\n }\n }\n return d9.sort(([e60 = \"\"], [t10 = \"\"]) =\u003e e60.localeCompare(t10)), { endpointCount: Object.keys(c5).length, endpointLabels: c5, componentByEndpointKey: h5, endpointComponents: d9 };\n};\nvar ote = class {\n baseline;\n inputProblem;\n baselineCaptureError;\n baselineTraceSignature;\n constructor(e54, t4) {\n this.inputProblem = e54, this.baselineTraceSignature = tte(t4);\n try {\n this.baseline = nte(e54, t4), this.baselineCaptureError = null;\n } catch (t10) {\n this.baseline = ete(e54), this.baselineCaptureError = t10 instanceof Error ? t10.message : String(t10);\n }\n }\n validate(e54) {\n if (this.baselineCaptureError) {\n const t10 = tte(e54) === this.baselineTraceSignature;\n return { safe: t10, candidate: this.baseline, regressions: [], validationError: t10 ? `Connectivity validation is limited to exact trace preservation: ${this.baselineCaptureError}` : `Connectivity validation failed closed: ${this.baselineCaptureError}` };\n }\n let t4;\n try {\n t4 = nte(this.inputProblem, e54);\n } catch (e60) {\n return { safe: false, candidate: ete(this.inputProblem), regressions: [], validationError: `Connectivity validation failed closed: ${e60 instanceof Error ? e60.message : String(e60)}` };\n }\n const n8 = [];\n for (const e60 of this.baseline.endpointComponents) {\n if (e60.length \u003c 2)\n continue;\n const o10 = new Map;\n for (const n10 of e60) {\n const e61 = t4.componentByEndpointKey[n10] ?? `missing:${n10}`, i8 = o10.get(e61) ?? [];\n i8.push(n10), o10.set(e61, i8);\n }\n o10.size \u003c= 1 || n8.push({ baselineEndpointKeys: [...e60], baselineEndpointLabels: e60.map((e61) =\u003e this.baseline.endpointLabels[e61]), candidateComponents: [...o10.values()] });\n }\n return { safe: n8.length === 0, candidate: t4, regressions: n8 };\n }\n};\nvar rte = [{ x: 0, y: 0 }, { x: 0.5, y: 0.5 }];\nvar ste = [0.15, 0.2, 0.25, 0.3, 0.4, 0.5];\nvar ate = (e54) =\u003e e54?.route_type === \"wire\";\nvar cte = (e54) =\u003e e54?.route_type === \"via\";\nvar lte = Array.from({ length: 24 }, (e54, t4) =\u003e {\n const n8 = t4 * Math.PI / 12;\n return { x: Math.cos(n8), y: Math.sin(n8) };\n});\nvar hte = (e54) =\u003e [...new Set(e54.map((e60) =\u003e Number(e60.toFixed(6))))].sort((e60, t4) =\u003e t4 - e60);\nvar dte = class extends BaseSolver {\n inputProblem;\n traces;\n obstacleIndex;\n phase = \"repair-vias\";\n traceCursor = 0;\n routeCursor = 0;\n candidateCursor = 0;\n clearanceTierCursor = 0;\n attemptedCandidateCount = 0;\n attemptedClearanceShoveCount = 0;\n attemptedViaGridCount = 0;\n committedClearanceShoveCount = 0;\n viaPairCountRemoved = 0;\n viaCountRemoved = 0;\n simplifiedPathCount = 0;\n normalizedSegmentCount = 0;\n achievedExtraClearanceCount = 0;\n relocatedViaCount = 0;\n unresolvedViaCount = 0;\n attemptedPushedViaRepairCount = 0;\n committedPushedViaRepairCount = 0;\n padClearanceRerouteCount = 0;\n unresolvedPadClearanceCount = 0;\n initialPadClearanceViolationCount = 0;\n remainingPadClearanceViolationCount = 0;\n initialPadClearanceViolationCountByClearance = {};\n remainingPadClearanceViolationCountByClearance = {};\n budgetLimited = false;\n connectivityValidationCount = 0;\n connectivityRollbackCount = 0;\n connectivityRegressionEndpointIds = [];\n connectivityValidationError = null;\n connectivityRollbackMutationStats = null;\n connectionNameResolver;\n connectionByTraceId = new Map;\n connectivityInvariant;\n initialConnectivitySafeTraces;\n mutableTraceIndices;\n mutableTraceIndexSet;\n viaRepairTraceIndices;\n traceIndices;\n maxRerouteLength;\n clearancePaddingTiers;\n desiredPadClearance;\n initialTraceLengths = new Map;\n candidates = [];\n candidateShoveCount = 0;\n rollbackTraces = null;\n baseCandidateValidated = false;\n activeShovePadding = 0;\n viaGridAttempt = null;\n candidateSetMayUseGridFallback = false;\n pendingPushedViaRepair = null;\n alternatePushedViaRepairs = [];\n pushedViaRepairRollbackTraces = null;\n connectivityFinalized = false;\n finalizedMutatedTraceIndices = [];\n resumePhase = \"scan-via-pairs\";\n constructor(e54) {\n super(), this.inputProblem = structuredClone(e54), this.traces = structuredClone(e54.traces), this.initialConnectivitySafeTraces = structuredClone(e54.traces), this.connectivityInvariant = new ote(this.inputProblem.simpleRouteJson, this.initialConnectivitySafeTraces), this.connectionNameResolver = new D7(e54.simpleRouteJson, this.traces), this.maxRerouteLength = e54.maxRerouteLength ?? 10, this.desiredPadClearance = e54.desiredPadClearance, this.clearancePaddingTiers = hte([...e54.clearancePaddingTiers ?? [0.1, 0.05, 0], 0]).filter((e60) =\u003e e60 \u003e= 0);\n const t4 = this.traces.map((e60, t10) =\u003e t10), n8 = (e60, t10, n10) =\u003e {\n const o11 = [...new Set(e60 ?? n10)];\n for (const e61 of o11)\n if (!Number.isInteger(e61) || e61 \u003c 0 || e61 \u003e= this.traces.length)\n throw new RangeError(`Invalid cleanup ${t10} index: ${e61}`);\n return o11;\n }, o10 = n8(e54.traceIndices, \"trace\", t4);\n this.viaRepairTraceIndices = n8(e54.viaRepairTraceIndices, \"via repair trace\", o10), this.mutableTraceIndices = n8(e54.mutableTraceIndices, \"mutable trace\", o10), this.mutableTraceIndexSet = new Set(this.mutableTraceIndices), this.traceIndices = o10.filter((e60) =\u003e this.resolveNominalTraceWidth(this.traces[e60]) \u003e= 0.499999);\n for (const e60 of this.traceIndices)\n this.initialTraceLengths.set(e60, this.measureTraceLength(this.traces[e60]));\n this.obstacleIndex = this.createObstacleIndex(), this.initialPadClearanceViolationCount = this.countPadClearanceViolations(), this.remainingPadClearanceViolationCount = this.initialPadClearanceViolationCount, this.initialPadClearanceViolationCountByClearance = this.countPadClearanceViolationsByTier(), this.remainingPadClearanceViolationCountByClearance = { ...this.initialPadClearanceViolationCountByClearance }, this.activeSubSolver = null, this.MAX_ITERATIONS = 1e6, this.stats = this.createStats();\n }\n getSolverName() {\n return \"PowerTraceCleanupSolver\";\n }\n _step() {\n if (this.activeSubSolver) {\n const e54 = this.activeSubSolver;\n return this.stepActiveShoveSolver(), void ((e54.solved || e54.failed) \u0026\u0026 (this.stats = this.createStats()));\n }\n switch (this.phase) {\n case \"repair-vias\":\n this.repairNextVia();\n break;\n case \"scan-via-pairs\":\n this.scanNextViaPair();\n break;\n case \"scan-pad-clearance\":\n this.scanNextPadClearance();\n break;\n case \"scan-simplification\":\n this.scanNextSimplification();\n break;\n case \"evaluate-candidate\":\n this.evaluateCurrentCandidate();\n break;\n case \"shove-clearance\":\n break;\n case \"route-via-pair\":\n this.startNextViaGridCandidate();\n break;\n case \"complete\":\n this.ensureConnectivitySafeOutput(), this.solved = true;\n }\n this.stats = this.createStats();\n }\n repairNextVia() {\n const e54 = this.viaRepairTraceIndices[this.traceCursor], t4 = e54 === undefined ? undefined : this.traces[e54];\n if (!t4)\n return this.traceCursor = 0, this.routeCursor = 0, this.phase = \"scan-via-pairs\", void this.rebuildObstacleIndex();\n const n8 = t4.route.findIndex((e60, t10) =\u003e t10 \u003e= this.routeCursor \u0026\u0026 cte(e60));\n if (n8 === -1)\n return this.traceCursor++, void (this.routeCursor = 0);\n this.routeCursor = n8 + 1;\n const o10 = t4.route[n8], i8 = t4.route[n8 - 1], r9 = t4.route[n8 + 1];\n if (!cte(o10) || !ate(i8) || !ate(r9))\n return;\n const s7 = this.getTraceConnectionNames(t4), a9 = this.getBaseObstacleClearance();\n if (!this.obstacleIndex.collidesVia({ point: o10, layers: this.obstacleIndex.boardLayers, padDiameter: o10.via_diameter ?? 0.6, holeDiameter: o10.via_hole_diameter ?? this.obstacleIndex.defaultViaHoleDiameter, connectionNames: s7, ignoreTraceIndex: e54, ignoreRouteRange: { start: n8, end: n8 }, obstacleClearance: a9, blockSameNetObstacles: true, sameNetObstacleClearance: 0 }))\n return;\n const c5 = this.findViaRepair(t4, n8, a9);\n if (!c5) {\n const e60 = this.findPushableViaRepairs(t4, n8, a9), o11 = e60.shift();\n return o11 ? (this.alternatePushedViaRepairs = e60, void this.startPushedViaRepair(o11)) : void this.unresolvedViaCount++;\n }\n t4.route.splice(c5.startIndex, c5.endIndex - c5.startIndex + 1, ...c5.route), this.relocatedViaCount++, this.routeCursor = c5.startIndex + c5.route.length, this.rebuildObstacleIndex();\n }\n findViaRepair(e54, t4, n8) {\n const o10 = this.createViaRepairContext(e54, t4);\n if (!o10)\n return null;\n const i8 = o10.candidates.map((e60) =\u003e ({ point: e60, movedLength: z7(o10.leftAnchor, e60) + z7(e60, o10.rightAnchor) })).filter(({ movedLength: e60 }) =\u003e e60 \u003c= o10.originalLength + Math.min(6, this.maxRerouteLength) + L7);\n i8.sort((e60, t10) =\u003e e60.movedLength - t10.movedLength || z7(e60.point, o10.via) - z7(t10.point, o10.via));\n for (const e60 of i8)\n if (this.isViaRepairPointSafe(o10, e60.point, n8))\n return this.createViaRepairReplacement(o10, e60.point);\n return null;\n }\n findPushableViaRepairs(e54, t4, n8) {\n const o10 = this.viaRepairTraceIndices[this.traceCursor];\n if (o10 === undefined)\n return [];\n const i8 = this.createViaRepairContext(e54, t4);\n if (!i8)\n return [];\n const r9 = i8.candidates.flatMap((e60) =\u003e {\n const t10 = z7(i8.leftAnchor, e60) + z7(e60, i8.rightAnchor);\n if (t10 \u003e i8.originalLength + Math.min(6, this.maxRerouteLength) + L7)\n return [];\n const r10 = new Set, s7 = this.getViaRepairCollisionQueries(i8, e60, n8);\n for (const e61 of s7)\n for (const t11 of this.obstacleIndex.findCollisions(e61)) {\n if (t11.kind !== \"trace\" || t11.traceIndex === undefined || t11.traceIndex === o10 || !this.mutableTraceIndexSet.has(t11.traceIndex))\n return [];\n r10.add(t11.traceIndex);\n }\n if (r10.size === 0 || r10.size \u003e 2)\n return [];\n const a9 = [...r10];\n return this.isViaRepairPointSafe(i8, e60, n8, a9) ? [{ point: e60, movedLength: t10, blockerCount: r10.size, blockerKey: [...r10].sort((e61, t11) =\u003e e61 - t11).join(\",\") }] : [];\n });\n r9.sort((e60, t10) =\u003e e60.blockerCount - t10.blockerCount || e60.movedLength - t10.movedLength || z7(e60.point, i8.via) - z7(t10.point, i8.via));\n return [...new Map([...r9].reverse().map((e60) =\u003e [e60.blockerKey, e60])).values(), ...r9].filter((e60, t10, n10) =\u003e n10.findIndex((t11) =\u003e t11.point.x === e60.point.x \u0026\u0026 t11.point.y === e60.point.y) === t10).slice(0, 12).map((e60) =\u003e ({ traceIndex: o10, viaIndex: t4, point: e60.point, padClearance: n8, corridor: [{ start: i8.leftAnchor, end: e60.point, layer: i8.leftWire.layer, width: i8.leftWire.width }, { start: e60.point, end: i8.rightAnchor, layer: i8.rightWire.layer, width: i8.rightWire.width }, ...this.obstacleIndex.boardLayers.map((t10) =\u003e ({ start: e60.point, end: e60.point, layer: t10, width: i8.viaDiameter }))] }));\n }\n createViaRepairContext(e54, t4) {\n const n8 = e54.route[t4], o10 = e54.route[t4 - 1], i8 = e54.route[t4 + 1];\n if (!cte(n8) || !ate(o10) || !ate(i8))\n return null;\n const r9 = t4 - 1 == 0 || !ate(e54.route[t4 - 2]), s7 = t4 + 1 === e54.route.length - 1 || !ate(e54.route[t4 + 2]), a9 = r9 ? o10 : e54.route[t4 - 2], c5 = s7 ? i8 : e54.route[t4 + 2], l5 = z7(a9, n8) + z7(n8, c5), h5 = this.getTraceConnectionNames(e54), d9 = n8.via_diameter ?? 0.6, u9 = n8.via_hole_diameter ?? this.obstacleIndex.defaultViaHoleDiameter, p9 = Math.max(0.3, u9 + this.obstacleIndex.minViaHoleEdgeToViaHoleEdgeClearance + 0.05), m9 = [p9, p9 + 0.15, p9 + 0.3, p9 + 0.5, p9 + 0.75, p9 + 1, p9 + 1.5, p9 + 2].flatMap((e60) =\u003e lte.map((t10) =\u003e ({ x: 0.025 * Math.round((n8.x + t10.x * e60) / 0.025), y: 0.025 * Math.round((n8.y + t10.y * e60) / 0.025) }))), g10 = [...m9, ...m9.flatMap((e60) =\u003e [{ x: e60.x, y: Math.floor(10 * n8.y) / 10 }, { x: e60.x, y: Math.ceil(10 * n8.y) / 10 }, { x: Math.floor(10 * n8.x) / 10, y: e60.y }, { x: Math.ceil(10 * n8.x) / 10, y: e60.y }])].filter((e60, t10, n10) =\u003e n10.findIndex((t11) =\u003e t11.x === e60.x \u0026\u0026 t11.y === e60.y) === t10);\n return { trace: e54, viaIndex: t4, via: n8, leftWire: o10, rightWire: i8, leftIsEndpoint: r9, rightIsEndpoint: s7, leftAnchor: a9, rightAnchor: c5, originalLength: l5, connectionNames: h5, viaDiameter: d9, holeDiameter: u9, ignoreRouteRange: { start: Math.max(0, t4 - 2), end: Math.min(e54.route.length - 1, t4 + 2) }, candidates: g10 };\n }\n getViaRepairCollisionQueries(e54, t4, n8, o10) {\n const i8 = this.viaRepairTraceIndices[this.traceCursor], r9 = { connectionNames: e54.connectionNames, ignoreTraceIndex: i8, ignoreTraceIndices: o10, ignoreRouteRange: e54.ignoreRouteRange, obstacleClearance: n8 };\n return [...this.obstacleIndex.boardLayers.map((n10) =\u003e ({ ...r9, start: t4, end: t4, layer: n10, width: e54.viaDiameter, blockSameNetObstacles: true, sameNetObstacleClearance: 0 })), { ...r9, start: e54.leftAnchor, end: t4, layer: e54.leftWire.layer, width: e54.leftWire.width }, { ...r9, start: t4, end: e54.rightAnchor, layer: e54.rightWire.layer, width: e54.rightWire.width }];\n }\n isViaRepairPointSafe(e54, t4, n8, o10) {\n const i8 = this.viaRepairTraceIndices[this.traceCursor];\n return !this.obstacleIndex.collidesVia({ point: t4, layers: this.obstacleIndex.boardLayers, padDiameter: e54.viaDiameter, holeDiameter: e54.holeDiameter, connectionNames: e54.connectionNames, ignoreTraceIndex: i8, ignoreTraceIndices: o10, ignoreRouteRange: { start: e54.viaIndex, end: e54.viaIndex }, obstacleClearance: n8, blockSameNetObstacles: true, sameNetObstacleClearance: 0 }) \u0026\u0026 !this.getViaRepairCollisionQueries(e54, t4, n8, o10).slice(this.obstacleIndex.boardLayers.length).some((e60) =\u003e this.obstacleIndex.collides(e60));\n }\n createViaRepairReplacement(e54, t4) {\n const n8 = { ...e54.leftWire, ...t4 }, o10 = { ...e54.via, ...t4 }, i8 = { ...e54.rightWire, ...t4 };\n return { startIndex: e54.viaIndex - 1, endIndex: e54.viaIndex + 1, route: [...e54.leftIsEndpoint ? [e54.leftWire] : [], n8, o10, i8, ...e54.rightIsEndpoint ? [e54.rightWire] : []] };\n }\n startPushedViaRepair(e54) {\n this.pendingPushedViaRepair = e54, this.pushedViaRepairRollbackTraces = structuredClone(this.traces), this.attemptedPushedViaRepairCount++, this.activeSubSolver = new wee({ simpleRouteJson: this.inputProblem.simpleRouteJson, traces: this.traces, powerTraceIndex: e54.traceIndex, nominalPowerWidth: Math.max(...e54.corridor.map((e60) =\u003e e60.width)), pushOnlyNominalWidthsBelow: Number.POSITIVE_INFINITY, mutableTraceIndices: this.mutableTraceIndices, corridor: e54.corridor, maxRerouteLength: this.maxRerouteLength }, this.connectionNameResolver);\n }\n finishPushedViaRepairSolver(e54) {\n const t4 = this.pendingPushedViaRepair;\n if (this.activeSubSolver = null, !t4)\n return;\n if (e54.solved) {\n const n10 = e54.getOutput();\n if (n10) {\n this.traces = n10.traces, this.rebuildObstacleIndex();\n const e60 = this.traces[t4.traceIndex], o10 = e60 ? this.createViaRepairContext(e60, t4.viaIndex) : null;\n if (o10 \u0026\u0026 this.isViaRepairPointSafe(o10, t4.point, t4.padClearance)) {\n const n11 = this.createViaRepairReplacement(o10, t4.point);\n return e60.route.splice(n11.startIndex, n11.endIndex - n11.startIndex + 1, ...n11.route), this.relocatedViaCount++, this.committedPushedViaRepairCount++, this.routeCursor = n11.startIndex + n11.route.length, this.pendingPushedViaRepair = null, this.alternatePushedViaRepairs = [], this.pushedViaRepairRollbackTraces = null, void this.rebuildObstacleIndex();\n }\n }\n }\n this.pushedViaRepairRollbackTraces \u0026\u0026 (this.traces = this.pushedViaRepairRollbackTraces), this.pendingPushedViaRepair = null, this.pushedViaRepairRollbackTraces = null;\n const n8 = this.alternatePushedViaRepairs.shift();\n if (n8)\n return this.rebuildObstacleIndex(), void this.startPushedViaRepair(n8);\n this.alternatePushedViaRepairs = [], this.unresolvedViaCount++, this.rebuildObstacleIndex();\n }\n scanNextViaPair() {\n const e54 = this.traceIndices[this.traceCursor];\n if (e54 === undefined)\n return this.traceCursor = 0, this.routeCursor = 0, void (this.phase = \"scan-pad-clearance\");\n const t4 = this.traces[e54], n8 = t4.route.findIndex((e60, t10) =\u003e t10 \u003e= this.routeCursor \u0026\u0026 e60.route_type === \"via\");\n if (n8 === -1)\n return void this.advanceTrace();\n const o10 = t4.route.slice(n8 + 1).findIndex((e60) =\u003e e60.route_type === \"via\");\n if (o10 === -1)\n return void this.advanceTrace();\n const i8 = n8 - 1, r9 = n8 + 1 + o10 + 1, s7 = t4.route[i8], a9 = t4.route[r9];\n if (this.routeCursor = n8 + 1, !ate(s7) || !ate(a9) || s7.layer !== a9.layer || z7(s7, a9) \u003e this.maxRerouteLength + L7)\n return;\n const c5 = this.createCandidates({ kind: \"via-pair\", traceIndex: e54, startIndex: i8, endIndex: r9 }), l5 = c5[0]?.width ?? Math.max(s7.width, a9.width), h5 = c5[0]?.padClearance ?? this.getCandidatePadClearance(\"via-pair\", e54, i8, r9), d9 = (n10) =\u003e {\n const o11 = t4.route[n10];\n return !!ate(o11) \u0026\u0026 this.obstacleIndex.findCollisions({ start: o11, end: o11, layer: o11.layer, width: l5, connectionNames: this.getTraceConnectionNames(t4), ignoreTraceIndex: e54, ignoreRouteRange: { start: Math.max(0, i8 - 1), end: Math.min(t4.route.length - 1, r9 + 1) }, obstacleClearance: h5 }).some((e60) =\u003e e60.kind === \"obstacle\" \u0026\u0026 e60.obstacleKind === \"pad\");\n }, u9 = t4.route[i8 - 1], p9 = t4.route[r9 + 1], m9 = c5.length \u003e 0 \u0026\u0026 d9(i8) \u0026\u0026 ate(u9) \u0026\u0026 u9.layer === s7.layer ? i8 - 1 : i8, g10 = c5.length \u003e 0 \u0026\u0026 d9(r9) \u0026\u0026 ate(p9) \u0026\u0026 p9.layer === a9.layer ? r9 + 1 : r9, f10 = [{ startIndex: i8, endIndex: r9 }, { startIndex: m9, endIndex: r9 }, { startIndex: i8, endIndex: g10 }, { startIndex: m9, endIndex: g10 }].filter((e60, t10, n10) =\u003e n10.findIndex((t11) =\u003e t11.startIndex === e60.startIndex \u0026\u0026 t11.endIndex === e60.endIndex) === t10).flatMap((t10) =\u003e t10.startIndex === i8 \u0026\u0026 t10.endIndex === r9 ? c5 : this.createCandidates({ kind: \"via-pair\", traceIndex: e54, startIndex: t10.startIndex, endIndex: t10.endIndex }));\n f10.length !== 0 \u0026\u0026 this.beginCandidates(f10, \"scan-via-pairs\", true);\n }\n scanNextPadClearance() {\n const e54 = this.traceIndices[this.traceCursor];\n if (e54 === undefined)\n return this.traceCursor = 0, this.routeCursor = 0, void (this.phase = \"scan-simplification\");\n const t4 = this.traces[e54];\n if (this.resolveNominalTraceWidth(t4) \u003c 0.499999)\n return void this.advanceTrace();\n const n8 = this.routeCursor, o10 = t4.route[n8], i8 = t4.route[n8 + 1];\n if (!ate(o10) || !ate(i8) || o10.layer !== i8.layer)\n return void (n8 \u003e= t4.route.length - 1 ? this.advanceTrace() : this.routeCursor++);\n if (this.routeCursor++, !this.segmentHasPadClearanceViolation(e54, n8))\n return;\n const r9 = this.getPadClearanceIntervals(t4, n8).flatMap((t10) =\u003e this.getImprovedPadClearanceTiers(e54, t10.startIndex, t10.endIndex).flatMap((n10) =\u003e this.createCandidates({ kind: \"pad-clearance\", traceIndex: e54, startIndex: t10.startIndex, endIndex: t10.endIndex, padClearance: n10 }).slice(0, 8)));\n r9.length !== 0 ? this.beginCandidates(r9.slice(0, 72), \"scan-pad-clearance\", true) : this.unresolvedPadClearanceCount++;\n }\n segmentHasPadClearanceViolation(e54, t4) {\n const n8 = this.traces[e54], o10 = n8.route[t4], i8 = n8.route[t4 + 1];\n return !(!ate(o10) || !ate(i8) || o10.layer !== i8.layer) \u0026\u0026 this.obstacleIndex.findCollisions({ start: o10, end: i8, layer: o10.layer, width: Math.max(o10.width, i8.width), connectionNames: this.getTraceConnectionNames(n8), ignoreTraceIndex: e54, ignoreRouteRange: { start: Math.max(0, t4 - 1), end: Math.min(n8.route.length - 1, t4 + 2) }, obstacleClearance: this.getPadClearanceForTrace(n8) }).some((e60) =\u003e e60.kind === \"obstacle\" \u0026\u0026 e60.obstacleKind === \"pad\");\n }\n getPadClearanceIntervals(e54, t4) {\n const n8 = e54.route[t4];\n if (!ate(n8))\n return [];\n const o10 = [t4];\n let i8 = 0;\n for (let r10 = t4 - 1;r10 \u003e= 0; r10--) {\n const t10 = e54.route[r10], s7 = e54.route[r10 + 1];\n if (!ate(t10) || !ate(s7) || t10.layer !== n8.layer || s7.layer !== n8.layer)\n break;\n if (i8 += z7(t10, s7), i8 \u003e this.maxRerouteLength / 2 + L7)\n break;\n o10.push(r10);\n }\n const r9 = [t4 + 1];\n i8 = 0;\n for (let o11 = t4 + 1;o11 \u003c e54.route.length - 1; o11++) {\n const t10 = e54.route[o11], s7 = e54.route[o11 + 1];\n if (!ate(t10) || !ate(s7) || t10.layer !== n8.layer || s7.layer !== n8.layer)\n break;\n if (i8 += z7(t10, s7), i8 \u003e this.maxRerouteLength / 2 + L7)\n break;\n r9.push(o11 + 1);\n }\n return o10.flatMap((t10) =\u003e r9.map((n10) =\u003e ({ startIndex: t10, endIndex: n10, length: this.measureRouteRange(e54, t10, n10).length }))).filter((e60) =\u003e e60.length \u003c= this.maxRerouteLength + L7 \u0026\u0026 e60.startIndex \u003c e60.endIndex).sort((e60, t10) =\u003e t10.length - e60.length).slice(0, 8);\n }\n scanNextSimplification() {\n const e54 = this.traceIndices[this.traceCursor];\n if (e54 === undefined)\n return this.remainingPadClearanceViolationCount = this.countPadClearanceViolations(), this.remainingPadClearanceViolationCountByClearance = this.countPadClearanceViolationsByTier(), void (this.phase = \"complete\");\n const t4 = this.traces[e54], n8 = this.routeCursor, o10 = t4.route[n8];\n if (!ate(o10) || n8 \u003e= t4.route.length - 1)\n return void (n8 \u003e= t4.route.length - 1 ? this.advanceTrace() : this.routeCursor++);\n let i8 = 0;\n const r9 = [];\n for (let e60 = n8 + 1;e60 \u003c t4.route.length; e60++) {\n const s9 = t4.route[e60 - 1], a9 = t4.route[e60];\n if (!ate(s9) || !ate(a9) || s9.layer !== o10.layer || a9.layer !== o10.layer)\n break;\n if (i8 += z7(s9, a9), i8 \u003e this.maxRerouteLength + L7)\n break;\n const c5 = this.measureRouteRange(t4, n8, e60);\n (c5.nonOctilinearSegmentCount \u003e 0 || c5.pointCount \u003e 3) \u0026\u0026 r9.push(e60);\n }\n const s7 = r9.slice(-6).reverse().flatMap((t10) =\u003e this.createCandidates({ kind: \"simplification\", traceIndex: e54, startIndex: n8, endIndex: t10 }));\n s7.length !== 0 ? this.beginCandidates(s7, \"scan-simplification\") : this.routeCursor++;\n }\n createCandidates({ kind: e54, traceIndex: t4, startIndex: n8, endIndex: o10, padClearance: i8 }) {\n const r9 = this.traces[t4], s7 = r9.route[n8], a9 = r9.route[o10];\n if (!ate(s7) || !ate(a9) || s7.layer !== a9.layer)\n return [];\n const c5 = this.resolveNominalTraceWidth(r9), l5 = this.measureRouteRange(r9, n8, o10), h5 = i8 ?? this.getCandidatePadClearance(e54, t4, n8, o10), d9 = [], u9 = gee(s7, a9);\n if (e54 === \"pad-clearance\" \u0026\u0026 uee([s7, a9]) === 0) {\n const e60 = z7(s7, a9);\n if (e60 \u003e L7) {\n const t10 = { x: -(a9.y - s7.y) / e60, y: (a9.x - s7.x) / e60 };\n for (const e61 of [0.25, 0.5, 0.75, 1, 1.5, 2])\n for (const n10 of [-1, 1])\n u9.push([s7, { x: s7.x + t10.x * e61 * n10, y: s7.y + t10.y * e61 * n10 }, { x: a9.x + t10.x * e61 * n10, y: a9.y + t10.y * e61 * n10 }, a9]);\n }\n }\n const p9 = new Map(u9.map((e60) =\u003e [e60.map((e61) =\u003e `${e61.x.toFixed(6)},${e61.y.toFixed(6)}`).join(\";\"), e60]));\n for (const i9 of p9.values()) {\n const u10 = pee(i9);\n if (u10 \u003e this.maxRerouteLength + L7 || e54 === \"pad-clearance\" \u0026\u0026 u10 \u003e 1.35 * l5.length + 0.5 || e54 === \"simplification\" \u0026\u0026 (u10 \u003e 1.1 * l5.length + L7 || this.measureTraceLength(r9) - l5.length + u10 \u003e 1.01 * (this.initialTraceLengths.get(t4) ?? this.measureTraceLength(r9)) + L7))\n continue;\n const p10 = u10 \u003c= L7 ? c5 : c5 - l5.deficitArea / u10;\n if (p10 \u003e c5 + L7)\n continue;\n const m9 = 0.05 * Math.ceil(Math.max(this.inputProblem.simpleRouteJson.minTraceWidth, p10) / 0.05 - L7), g10 = hte([c5, Math.min(c5, m9), Math.min(c5, Math.max(this.inputProblem.simpleRouteJson.minTraceWidth, p10))].map((e60) =\u003e Math.max(e60, s7.width)));\n for (const r10 of g10) {\n const u11 = this.measureCandidate(i9, r10, c5, a9.width, s7.width);\n u11.deficitArea \u003e l5.deficitArea + L7 || u11.conservativeDeficitArea \u003e l5.conservativeDeficitArea + L7 || !this.preservesCoverage(u11, l5) || (e54 !== \"simplification\" || l5.nonOctilinearSegmentCount !== 0 || u11.pointCount \u003c l5.pointCount \u0026\u0026 u11.length \u003c l5.length - L7) \u0026\u0026 d9.push({ kind: e54, traceIndex: t4, startIndex: n8, endIndex: o10, layer: s7.layer, points: i9, width: r10, padClearance: h5, originalQuality: l5 });\n }\n }\n return d9.slice(0, 18);\n }\n beginCandidates(e54, t4, n8 = false) {\n this.candidates = e54, this.candidateCursor = 0, this.clearanceTierCursor = 0, this.candidateShoveCount = 0, this.rollbackTraces = null, this.baseCandidateValidated = false, this.resumePhase = t4, this.candidateSetMayUseGridFallback = n8, this.phase = \"evaluate-candidate\";\n }\n evaluateCurrentCandidate() {\n const e54 = this.candidates[this.candidateCursor];\n if (!e54)\n return void this.finishCandidateSet(false);\n if (!this.baseCandidateValidated) {\n if (!this.candidateCollides(e54, 0))\n return this.candidateShoveCount \u003e 0 ? void this.applyCandidate(e54, 0) : (this.baseCandidateValidated = true, void (this.clearanceTierCursor = 0));\n return this.getPushableTraceIndices(e54, 0) \u0026\u0026 this.candidateShoveCount \u003c 2 \u0026\u0026 this.attemptedClearanceShoveCount \u003c 48 ? void this.startClearanceShove(e54, 0) : void this.advanceCandidate();\n }\n const t4 = this.clearancePaddingTiers[this.clearanceTierCursor];\n if (t4 === undefined || t4 \u003c= L7)\n return void this.applyCandidate(e54, 0);\n if (this.attemptedCandidateCount++, !this.candidateCollides(e54, t4))\n return void this.applyCandidate(e54, t4);\n this.getPushableTraceIndices(e54, t4) \u0026\u0026 this.candidateShoveCount \u003c 2 \u0026\u0026 this.attemptedClearanceShoveCount \u003c 48 ? this.startClearanceShove(e54, t4) : (this.rollbackCandidateShoves(), this.clearanceTierCursor++, this.candidateShoveCount = 0);\n }\n advanceCandidate() {\n this.rollbackCandidateShoves(), this.candidateCursor++, this.clearanceTierCursor = 0, this.candidateShoveCount = 0, this.baseCandidateValidated = false;\n }\n candidateCollides(e54, t4) {\n const n8 = this.traces[e54.traceIndex], o10 = this.getTraceConnectionNames(n8);\n for (let i8 = 0;i8 \u003c e54.points.length - 1; i8++) {\n const r9 = this.getCandidateSegmentWidth(e54, i8);\n if (this.obstacleIndex.collides({ start: e54.points[i8], end: e54.points[i8 + 1], layer: e54.layer, width: r9 + 2 * t4, connectionNames: o10, ignoreTraceIndex: e54.traceIndex, ignoreRouteRange: { start: Math.max(0, e54.startIndex - 1), end: Math.min(n8.route.length - 1, e54.endIndex + 1) }, obstacleClearance: e54.padClearance }))\n return true;\n }\n return false;\n }\n getPushableTraceIndices(e54, t4) {\n const n8 = this.traces[e54.traceIndex], o10 = this.getTraceConnectionNames(n8), i8 = new Set;\n for (let r9 = 0;r9 \u003c e54.points.length - 1; r9++) {\n const s7 = this.getCandidateSegmentWidth(e54, r9), a9 = { start: e54.points[r9], end: e54.points[r9 + 1], layer: e54.layer, width: s7 + 2 * t4, connectionNames: o10, ignoreTraceIndex: e54.traceIndex, ignoreRouteRange: { start: Math.max(0, e54.startIndex - 1), end: Math.min(n8.route.length - 1, e54.endIndex + 1) }, obstacleClearance: e54.padClearance };\n if (!this.obstacleIndex.collides(a9))\n continue;\n const c5 = this.obstacleIndex.findCollisions(a9);\n if (c5.length === 0)\n return null;\n for (const t10 of c5) {\n if (t10.kind !== \"trace\" || t10.traceIndex === undefined || t10.traceIndex === e54.traceIndex || !this.mutableTraceIndexSet.has(t10.traceIndex))\n return null;\n const n10 = this.traces[t10.traceIndex];\n if (!n10 || this.resolveNominalTraceWidth(n10) \u003e= e54.width - L7)\n return null;\n i8.add(t10.traceIndex);\n }\n }\n return i8.size \u003e 0 \u0026\u0026 i8.size \u003c= 2 ? [...i8] : null;\n }\n startClearanceShove(e54, t4) {\n this.rollbackTraces ??= structuredClone(this.traces), this.activeShovePadding = t4;\n const n8 = e54.width + 2 * t4, o10 = e54.points.slice(0, -1).map((n10, o11) =\u003e ({ start: n10, end: e54.points[o11 + 1], layer: e54.layer, width: this.getCandidateSegmentWidth(e54, o11) + 2 * t4 }));\n this.attemptedClearanceShoveCount++, this.activeSubSolver = new wee({ simpleRouteJson: this.inputProblem.simpleRouteJson, traces: this.traces, powerTraceIndex: e54.traceIndex, nominalPowerWidth: n8, pushOnlyNominalWidthsBelow: e54.width, mutableTraceIndices: this.mutableTraceIndices, corridor: o10, maxRerouteLength: this.maxRerouteLength }, this.connectionNameResolver), this.phase = \"shove-clearance\";\n }\n getCandidateSegmentWidth(e54, t4) {\n const n8 = this.traces[e54.traceIndex], o10 = n8.route[e54.startIndex], i8 = n8.route[e54.endIndex], r9 = t4 === 0 \u0026\u0026 ate(o10) ? o10.width : e54.width, s7 = t4 === e54.points.length - 2 \u0026\u0026 ate(i8) ? i8.width : e54.width;\n return Math.max(r9, s7);\n }\n stepActiveShoveSolver() {\n const e54 = this.activeSubSolver;\n if (e54.step(), e54.solved || e54.failed)\n if (this.pendingPushedViaRepair \u0026\u0026 e54 instanceof wee)\n this.finishPushedViaRepairSolver(e54);\n else if (e54 instanceof yee)\n this.finishViaGridSolver(e54);\n else {\n if (this.activeSubSolver = null, this.phase = \"evaluate-candidate\", e54.solved) {\n const t4 = e54.getOutput();\n if (t4)\n return this.traces = t4.traces, this.candidateShoveCount++, void this.rebuildObstacleIndex();\n }\n this.failedSubSolvers ??= [], this.failedSubSolvers.push(e54), this.rollbackCandidateShoves(), this.activeShovePadding \u003c= L7 ? this.advanceCandidate() : this.clearanceTierCursor++, this.candidateShoveCount = 0;\n }\n }\n rollbackCandidateShoves() {\n this.rollbackTraces \u0026\u0026 (this.traces = this.rollbackTraces, this.rollbackTraces = null, this.rebuildObstacleIndex());\n }\n applyCandidate(e54, t4) {\n const n8 = this.traces[e54.traceIndex], o10 = n8.route[e54.startIndex], i8 = n8.route[e54.endIndex], r9 = e54.points.map((t10, n10) =\u003e ({ ...n10 === 0 ? o10 : n10 === e54.points.length - 1 ? i8 : { route_type: \"wire\", layer: e54.layer, width: e54.width }, x: t10.x, y: t10.y, layer: e54.layer, width: n10 === 0 ? o10.width : n10 === e54.points.length - 1 ? i8.width : e54.width })), s7 = n8.route.slice(e54.startIndex, e54.endIndex + 1), a9 = e54.originalQuality.nonOctilinearSegmentCount;\n if (n8.route.splice(e54.startIndex, e54.endIndex - e54.startIndex + 1, ...r9), e54.kind === \"via-pair\") {\n const t10 = s7.filter((e60) =\u003e e60.route_type === \"via\").length;\n this.viaPairCountRemoved++, this.viaCountRemoved += t10, this.routeCursor = Math.max(0, e54.startIndex - 1);\n } else\n e54.kind === \"pad-clearance\" ? (this.padClearanceRerouteCount++, this.routeCursor = e54.startIndex + Math.max(1, r9.length - 1)) : (this.simplifiedPathCount++, this.normalizedSegmentCount += a9, this.routeCursor = e54.startIndex + Math.max(1, r9.length - 1));\n this.committedClearanceShoveCount += this.candidateShoveCount, t4 \u003e L7 \u0026\u0026 this.achievedExtraClearanceCount++, this.rollbackTraces = null, this.candidateShoveCount = 0, this.rebuildObstacleIndex(), this.finishCandidateSet(true);\n }\n finishCandidateSet(e54) {\n const t4 = this.candidates[0], n8 = hte(this.candidates.filter((e60) =\u003e e60.kind === t4?.kind).map((e60) =\u003e e60.width)), o10 = hte(this.candidates.filter((e60) =\u003e e60.kind === t4?.kind \u0026\u0026 e60.traceIndex === t4.traceIndex \u0026\u0026 e60.startIndex === t4.startIndex \u0026\u0026 e60.endIndex === t4.endIndex).map((e60) =\u003e e60.padClearance));\n if (this.rollbackCandidateShoves(), this.candidates = [], this.candidateCursor = 0, this.clearanceTierCursor = 0, this.candidateShoveCount = 0, this.baseCandidateValidated = false, !e54 \u0026\u0026 this.candidateSetMayUseGridFallback \u0026\u0026 t4)\n return this.candidateSetMayUseGridFallback = false, void this.beginViaGridAttempt(t4, n8, o10);\n this.candidateSetMayUseGridFallback = false, e54 || this.routeCursor++, this.phase = this.resumePhase;\n }\n beginViaGridAttempt(e54, t4, n8 = [e54.padClearance]) {\n this.viaGridAttempt = { kind: e54.kind, traceIndex: e54.traceIndex, startIndex: e54.startIndex, endIndex: e54.endIndex, layer: e54.layer, padClearances: n8, padClearanceCursor: 0, originalQuality: e54.originalQuality, widths: t4, widthCursor: 0, gridSizes: [], gridSizeCursor: 0, offsetCursor: 0 }, this.phase = \"route-via-pair\";\n }\n startNextViaGridCandidate() {\n const e54 = this.viaGridAttempt;\n if (!e54)\n return void (this.phase = this.resumePhase);\n if (e54.padClearanceCursor \u003e= e54.padClearances.length)\n return e54.kind === \"pad-clearance\" \u0026\u0026 this.unresolvedPadClearanceCount++, this.viaGridAttempt = null, this.routeCursor++, void (this.phase = this.resumePhase);\n if (e54.widthCursor \u003e= e54.widths.length)\n return e54.padClearanceCursor++, e54.widthCursor = 0, e54.gridSizes = [], e54.gridSizeCursor = 0, void (e54.offsetCursor = 0);\n const t4 = e54.widths[e54.widthCursor], n8 = e54.padClearances[e54.padClearanceCursor];\n if (e54.gridSizes.length === 0 \u0026\u0026 (e54.gridSizes = hte([j7(t4 / 2, 0.2, 0.4), j7(t4 / 3, 0.15, 0.25)])), e54.gridSizeCursor \u003e= e54.gridSizes.length)\n return e54.widthCursor++, e54.gridSizes = [], e54.gridSizeCursor = 0, void (e54.offsetCursor = 0);\n if (e54.offsetCursor \u003e= rte.length)\n return e54.gridSizeCursor++, void (e54.offsetCursor = 0);\n const o10 = this.traces[e54.traceIndex], i8 = o10.route[e54.startIndex], r9 = o10.route[e54.endIndex];\n if (!ate(i8) || !ate(r9))\n return this.viaGridAttempt = null, this.routeCursor++, void (this.phase = this.resumePhase);\n const s7 = e54.gridSizes[e54.gridSizeCursor], a9 = rte[e54.offsetCursor];\n this.attemptedViaGridCount++, this.activeSubSolver = new yee({ start: i8, end: r9, layer: e54.layer, traceWidth: t4, gridSize: s7, gridOffset: { x: a9.x * s7, y: a9.y * s7 }, connectionNames: this.getTraceConnectionNames(o10), obstacleIndex: this.obstacleIndex, ignoreTraceIndex: e54.traceIndex, ignoreRouteRange: { start: Math.max(0, e54.startIndex - 1), end: Math.min(o10.route.length - 1, e54.endIndex + 1) }, bounds: this.inputProblem.simpleRouteJson.bounds, obstacleClearance: n8, searchPadding: Math.min(4, Math.max(2, z7(i8, r9) / 2, 3 * t4)), requireOctilinear: true });\n }\n finishViaGridSolver(e54) {\n const t4 = this.viaGridAttempt;\n if (this.activeSubSolver = null, e54.solved \u0026\u0026 t4) {\n const n8 = e54.getOutput(), o10 = this.traces[t4.traceIndex];\n if (n8 \u0026\u0026 o10) {\n const e60 = this.resolveNominalTraceWidth(o10), i8 = this.measureCandidate(n8.points, n8.traceWidth, e60, o10.route[t4.endIndex].width, o10.route[t4.startIndex].width);\n if (i8.nonOctilinearSegmentCount === 0 \u0026\u0026 i8.length \u003c= this.maxRerouteLength + L7 \u0026\u0026 i8.deficitArea \u003c= t4.originalQuality.deficitArea + L7 \u0026\u0026 i8.conservativeDeficitArea \u003c= t4.originalQuality.conservativeDeficitArea + L7 \u0026\u0026 this.preservesCoverage(i8, t4.originalQuality)) {\n const e61 = { kind: t4.kind, traceIndex: t4.traceIndex, startIndex: t4.startIndex, endIndex: t4.endIndex, layer: t4.layer, points: n8.points, width: n8.traceWidth, padClearance: t4.padClearances[t4.padClearanceCursor], originalQuality: t4.originalQuality };\n return this.viaGridAttempt = null, void this.beginCandidates([e61], this.resumePhase, false);\n }\n }\n }\n e54.failed \u0026\u0026 (this.failedSubSolvers ??= [], this.failedSubSolvers.push(e54)), t4 \u0026\u0026 t4.offsetCursor++, this.phase = \"route-via-pair\";\n }\n measureRouteRange(e54, t4, n8) {\n const o10 = this.resolveNominalTraceWidth(e54);\n let i8 = 0, r9 = 0, s7 = 0, a9 = 0, c5 = 0, l5 = 0, h5 = 0;\n for (let d9 = t4;d9 \u003c= n8; d9++) {\n if (ate(e54.route[d9]) \u0026\u0026 h5++, d9 \u003e= n8)\n continue;\n const t10 = e54.route[d9], u9 = e54.route[d9 + 1];\n if (!ate(t10) || !ate(u9) || t10.layer !== u9.layer)\n continue;\n const p9 = z7(t10, u9);\n i8 += p9, r9 += p9 * Math.max(0, o10 - t10.width), t10.width \u003e= o10 - L7 \u0026\u0026 (a9 += p9), s7 += p9 * Math.max(0, o10 - Math.min(t10.width, u9.width)), Math.min(t10.width, u9.width) \u003e= o10 - L7 \u0026\u0026 (c5 += p9), l5 += uee([t10, u9]);\n }\n return { length: i8, deficitArea: r9, conservativeDeficitArea: s7, nominalLength: a9, conservativeNominalLength: c5, nonOctilinearSegmentCount: l5, pointCount: h5 };\n }\n measureTraceLength(e54) {\n let t4 = 0;\n for (let n8 = 0;n8 \u003c e54.route.length - 1; n8++) {\n const o10 = e54.route[n8], i8 = e54.route[n8 + 1];\n ate(o10) \u0026\u0026 ate(i8) \u0026\u0026 o10.layer === i8.layer \u0026\u0026 (t4 += z7(o10, i8));\n }\n return t4;\n }\n measureCandidate(e54, t4, n8, o10 = t4, i8 = t4) {\n const r9 = pee(e54);\n let s7 = 0, a9 = 0, c5 = 0, l5 = 0;\n for (let r10 = 0;r10 \u003c e54.length - 1; r10++) {\n const h5 = z7(e54[r10], e54[r10 + 1]), d9 = r10 === 0 ? i8 : t4, u9 = r10 === e54.length - 2 ? o10 : t4, p9 = Math.min(d9, u9);\n s7 += h5 * Math.max(0, n8 - d9), a9 += h5 * Math.max(0, n8 - p9), d9 \u003e= n8 - L7 \u0026\u0026 (c5 += h5), p9 \u003e= n8 - L7 \u0026\u0026 (l5 += h5);\n }\n return { length: r9, deficitArea: s7, conservativeDeficitArea: a9, nominalLength: c5, conservativeNominalLength: l5, nonOctilinearSegmentCount: uee(e54), pointCount: e54.length };\n }\n preservesCoverage(e54, t4) {\n const n8 = t4.length \u003c= L7 ? 1 : t4.nominalLength / t4.length, o10 = e54.length \u003c= L7 ? 1 : e54.nominalLength / e54.length, i8 = t4.length \u003c= L7 ? 1 : t4.conservativeNominalLength / t4.length, r9 = e54.length \u003c= L7 ? 1 : e54.conservativeNominalLength / e54.length;\n return !(o10 + L7 \u003c n8 || r9 + L7 \u003c i8) \u0026\u0026 !(e54.length \u003e t4.length + L7 \u0026\u0026 o10 \u003c 0.999999);\n }\n advanceTrace() {\n this.traceCursor++, this.routeCursor = 0, this.rebuildObstacleIndex();\n }\n createObstacleIndex() {\n return new Cee(this.inputProblem.simpleRouteJson, this.traces, this.phase === \"repair-vias\" ? undefined : this.traceIndices?.[this.traceCursor], [], this.connectionNameResolver);\n }\n rebuildObstacleIndex() {\n this.obstacleIndex = this.createObstacleIndex();\n }\n resolveNominalTraceWidth(e54) {\n const t4 = this.findConnectionForTrace(e54);\n return Math.max(t4?.nominalTraceWidth ?? t4?.width ?? this.inputProblem.simpleRouteJson.nominalTraceWidth ?? this.inputProblem.simpleRouteJson.minTraceWidth, this.inputProblem.simpleRouteJson.minTraceWidth);\n }\n getPadClearanceForTrace(e54) {\n const t4 = this.getBaseObstacleClearance();\n return this.resolveNominalTraceWidth(e54) \u003e= 0.499999 ? Math.max(t4, this.desiredPadClearance ?? this.resolveNominalTraceWidth(e54) / 2) : t4;\n }\n getBaseObstacleClearance() {\n return Math.max(this.inputProblem.simpleRouteJson.defaultObstacleMargin ?? 0, this.inputProblem.simpleRouteJson.minTraceToPadEdgeClearance ?? 0, 0.1);\n }\n getCandidatePadClearance(e54, t4, n8, o10) {\n const i8 = this.traces[t4], r9 = this.getBaseObstacleClearance(), s7 = this.getPadClearanceForTrace(i8);\n if (e54 === \"pad-clearance\")\n return s7;\n const a9 = e54 === \"via-pair\" ? Math.min(s7, Math.max(r9, 0.15)) : s7;\n return this.findExistingPadClearance(t4, n8, o10, r9, a9);\n }\n getImprovedPadClearanceTiers(e54, t4, n8) {\n const o10 = this.traces[e54], i8 = this.getBaseObstacleClearance(), r9 = this.getPadClearanceForTrace(o10), s7 = this.findExistingPadClearance(e54, t4, n8, i8, r9), a9 = Math.max(0.025, Math.min(0.05, r9 / 10)), c5 = [r9];\n for (let e60 = r9 - a9;e60 \u003e s7 + a9 / 2; e60 -= a9)\n c5.push(e60);\n return hte(c5).filter((e60) =\u003e e60 \u003e s7 + L7);\n }\n findExistingPadClearance(e54, t4, n8, o10, i8) {\n if (this.routeRangeHasPadClearanceViolation(e54, t4, n8, o10))\n return o10;\n if (!this.routeRangeHasPadClearanceViolation(e54, t4, n8, i8))\n return i8;\n let r9 = o10, s7 = i8;\n for (let o11 = 0;o11 \u003c 7; o11++) {\n const o12 = (r9 + s7) / 2;\n this.routeRangeHasPadClearanceViolation(e54, t4, n8, o12) ? s7 = o12 : r9 = o12;\n }\n return Math.max(o10, Number((r9 - 0.001).toFixed(6)));\n }\n routeRangeHasPadClearanceViolation(e54, t4, n8, o10) {\n const i8 = this.traces[e54], r9 = this.getTraceConnectionNames(i8);\n for (let s7 = t4;s7 \u003c n8; s7++) {\n const a9 = i8.route[s7], c5 = i8.route[s7 + 1];\n if (!ate(a9) || !ate(c5) || a9.layer !== c5.layer)\n continue;\n if (this.obstacleIndex.findCollisions({ start: a9, end: c5, layer: a9.layer, width: Math.max(a9.width, c5.width), connectionNames: r9, ignoreTraceIndex: e54, ignoreRouteRange: { start: Math.max(0, t4 - 1), end: Math.min(i8.route.length - 1, n8 + 1) }, obstacleClearance: o10 }).some((e60) =\u003e e60.kind === \"obstacle\" \u0026\u0026 e60.obstacleKind === \"pad\"))\n return true;\n }\n return false;\n }\n countPadClearanceViolations(e54) {\n let t4 = 0;\n for (const n8 of this.traceIndices) {\n const o10 = this.traces[n8];\n if (!o10)\n continue;\n const i8 = this.getTraceConnectionNames(o10);\n for (let r9 = 0;r9 \u003c o10.route.length - 1; r9++) {\n const s7 = o10.route[r9], a9 = o10.route[r9 + 1];\n if (!ate(s7) || !ate(a9) || s7.layer !== a9.layer)\n continue;\n this.obstacleIndex.findCollisions({ start: s7, end: a9, layer: s7.layer, width: Math.max(s7.width, a9.width), connectionNames: i8, ignoreTraceIndex: n8, ignoreRouteRange: { start: Math.max(0, r9 - 1), end: Math.min(o10.route.length - 1, r9 + 2) }, obstacleClearance: e54 ?? this.getPadClearanceForTrace(o10) }).some((e60) =\u003e e60.kind === \"obstacle\" \u0026\u0026 e60.obstacleKind === \"pad\") \u0026\u0026 t4++;\n }\n }\n return t4;\n }\n countPadClearanceViolationsByTier() {\n return Object.fromEntries(ste.map((e54) =\u003e [e54.toFixed(2), this.countPadClearanceViolations(e54)]));\n }\n findConnectionForTrace(e54) {\n const t4 = this.connectionByTraceId.get(e54.pcb_trace_id);\n if (t4 !== undefined)\n return t4 ?? undefined;\n const n8 = new Set(this.connectionNameResolver.canonicalize(this.getTraceConnectionNames(e54))), o10 = this.inputProblem.simpleRouteJson.connections.find((e60) =\u003e this.connectionNameResolver.canonicalize(this.getConnectionNames(e60)).some((e61) =\u003e n8.has(e61))) ?? null;\n return this.connectionByTraceId.set(e54.pcb_trace_id, o10), o10 ?? undefined;\n }\n getConnectionNames(e54) {\n return [e54.name, e54.source_trace_id, e54.rootConnectionName, e54.netConnectionName, ...e54.mergedConnectionNames ?? []].filter((e60) =\u003e Boolean(e60));\n }\n getTraceConnectionNames(e54) {\n return [e54.pcb_trace_id, e54.connection_name, e54.source_trace_id, e54.rootConnectionName, ...e54.mergedConnectionNames ?? [], ...e54.connectsTo ?? []].filter((e60) =\u003e Boolean(e60));\n }\n ensureConnectivitySafeOutput() {\n if (!this.connectivityFinalized) {\n this.connectivityFinalized = true, this.connectivityValidationCount++;\n try {\n const e54 = this.connectivityInvariant.validate(this.traces);\n if (this.connectivityValidationError ??= e54.validationError ?? null, e54.safe)\n return void (this.finalizedMutatedTraceIndices = this.getMutatedTraceIndices());\n this.connectivityRegressionEndpointIds = [...new Set(e54.regressions.flatMap((e60) =\u003e e60.baselineEndpointLabels))];\n } catch (e54) {\n this.connectivityValidationError = e54 instanceof Error ? e54.message : String(e54);\n }\n this.connectivityRollbackCount++, this.connectivityRollbackMutationStats = { committedClearanceShoveCount: this.committedClearanceShoveCount, viaPairCountRemoved: this.viaPairCountRemoved, viaCountRemoved: this.viaCountRemoved, simplifiedPathCount: this.simplifiedPathCount, normalizedSegmentCount: this.normalizedSegmentCount, achievedExtraClearanceCount: this.achievedExtraClearanceCount, relocatedViaCount: this.relocatedViaCount, committedPushedViaRepairCount: this.committedPushedViaRepairCount, padClearanceRerouteCount: this.padClearanceRerouteCount }, this.committedClearanceShoveCount = 0, this.viaPairCountRemoved = 0, this.viaCountRemoved = 0, this.simplifiedPathCount = 0, this.normalizedSegmentCount = 0, this.achievedExtraClearanceCount = 0, this.relocatedViaCount = 0, this.committedPushedViaRepairCount = 0, this.padClearanceRerouteCount = 0, this.traces = structuredClone(this.initialConnectivitySafeTraces), this.obstacleIndex = new Cee(this.inputProblem.simpleRouteJson, this.traces, undefined, [], this.connectionNameResolver), this.remainingPadClearanceViolationCount = this.countPadClearanceViolations(), this.remainingPadClearanceViolationCountByClearance = this.countPadClearanceViolationsByTier(), this.finalizedMutatedTraceIndices = this.getMutatedTraceIndices();\n }\n }\n getMutatedTraceIndices() {\n const e54 = Math.max(this.initialConnectivitySafeTraces.length, this.traces.length);\n return Array.from({ length: e54 }, (e60, t4) =\u003e t4).filter((e60) =\u003e JSON.stringify(this.initialConnectivitySafeTraces[e60]) !== JSON.stringify(this.traces[e60]));\n }\n createStats() {\n const e54 = this.candidates[this.candidateCursor], t4 = this.phase === \"repair-vias\" ? this.viaRepairTraceIndices : this.traceIndices;\n return { phase: this.phase, budgetLimited: this.budgetLimited, completionReason: this.phase === \"complete\" || this.solved ? this.connectivityRollbackCount \u003e 0 ? \"connectivity_rollback\" : this.budgetLimited ? \"iteration_budget\" : this.connectivityValidationError ? \"connectivity_validation_unavailable\" : \"completed\" : null, resultStatus: this.connectivityRollbackCount \u003e 0 || this.budgetLimited || this.connectivityValidationError !== null ? \"best_effort\" : \"complete\", traceCursor: this.traceCursor, traceCount: t4.length, traceIndex: t4[this.traceCursor], routeCursor: this.routeCursor, candidateCursor: this.candidateCursor, candidateCount: this.candidates.length, candidateKind: e54?.kind, candidateWidth: e54?.width, candidatePointCount: e54?.points.length, clearancePadding: this.clearancePaddingTiers[this.clearanceTierCursor], candidateShoveCount: this.candidateShoveCount, attemptedCandidateCount: this.attemptedCandidateCount, attemptedClearanceShoveCount: this.attemptedClearanceShoveCount, attemptedViaGridCount: this.attemptedViaGridCount, committedClearanceShoveCount: this.committedClearanceShoveCount, viaPairCountRemoved: this.viaPairCountRemoved, viaCountRemoved: this.viaCountRemoved, simplifiedPathCount: this.simplifiedPathCount, normalizedSegmentCount: this.normalizedSegmentCount, achievedExtraClearanceCount: this.achievedExtraClearanceCount, relocatedViaCount: this.relocatedViaCount, unresolvedViaCount: this.unresolvedViaCount, attemptedPushedViaRepairCount: this.attemptedPushedViaRepairCount, committedPushedViaRepairCount: this.committedPushedViaRepairCount, padClearanceRerouteCount: this.padClearanceRerouteCount, unresolvedPadClearanceCount: this.unresolvedPadClearanceCount, initialPadClearanceViolationCount: this.initialPadClearanceViolationCount, remainingPadClearanceViolationCount: this.remainingPadClearanceViolationCount, initialPadClearanceViolationCountByClearance: { ...this.initialPadClearanceViolationCountByClearance }, remainingPadClearanceViolationCountByClearance: { ...this.remainingPadClearanceViolationCountByClearance }, connectivityValidationCount: this.connectivityValidationCount, connectivityRollbackCount: this.connectivityRollbackCount, connectivityRegressionEndpointIds: [...this.connectivityRegressionEndpointIds], connectivityValidationError: this.connectivityValidationError, connectivityRollbackMutationStats: this.connectivityRollbackMutationStats === null ? null : { ...this.connectivityRollbackMutationStats }, mutatedTraceIndices: [...this.finalizedMutatedTraceIndices], spatialIndexRectCount: this.obstacleIndex.items.length };\n }\n computeProgress() {\n if (this.solved || this.phase === \"complete\")\n return 1;\n const e54 = this.phase === \"repair-vias\" ? this.viaRepairTraceIndices : this.traceIndices;\n if (e54.length === 0)\n return 1;\n const t4 = this.resumePhase === \"scan-via-pairs\" ? 0 : 0.5;\n return Math.min(0.99, t4 + this.traceCursor / e54.length * 0.5);\n }\n getConstructorParams() {\n return [this.inputProblem];\n }\n tryFinalAcceptance() {\n const e54 = this.pushedViaRepairRollbackTraces ?? this.rollbackTraces;\n e54 \u0026\u0026 (this.traces = e54), this.activeSubSolver = null, this.rollbackTraces = null, this.pushedViaRepairRollbackTraces = null, this.pendingPushedViaRepair = null, this.alternatePushedViaRepairs = [], this.viaGridAttempt = null, this.candidates = [], this.candidateCursor = 0, this.clearanceTierCursor = 0, this.candidateShoveCount = 0, this.baseCandidateValidated = false, this.candidateSetMayUseGridFallback = false, this.ensureConnectivitySafeOutput(), this.obstacleIndex = new Cee(this.inputProblem.simpleRouteJson, this.traces, undefined, [], this.connectionNameResolver), this.remainingPadClearanceViolationCount = this.countPadClearanceViolations(), this.remainingPadClearanceViolationCountByClearance = this.countPadClearanceViolationsByTier(), this.budgetLimited = true, this.phase = \"complete\", this.solved = true, this.progress = 1, this.stats = this.createStats();\n }\n getOutput() {\n return structuredClone(this.solved ? this.traces : this.initialConnectivitySafeTraces);\n }\n visualize() {\n const e54 = [], t4 = [], n8 = this.candidates[this.candidateCursor];\n for (let n10 = 0;n10 \u003c this.traces.length; n10++) {\n const o10 = this.traces[n10];\n for (const e60 of o10.route)\n e60.route_type === \"via\" \u0026\u0026 t4.push({ center: e60, radius: (e60.via_diameter ?? 0.6) / 2, fill: \"#d4a017\", stroke: \"#7a5700\" });\n for (let t10 = 0;t10 \u003c o10.route.length - 1; t10++) {\n const n11 = o10.route[t10], i8 = o10.route[t10 + 1];\n ate(n11) \u0026\u0026 ate(i8) \u0026\u0026 n11.layer === i8.layer \u0026\u0026 e54.push({ points: [n11, i8], strokeColor: n11.layer === \"bottom\" ? \"#376fc4\" : \"#777\", strokeWidth: n11.width });\n }\n }\n if (n8)\n for (let t10 = 0;t10 \u003c n8.points.length - 1; t10++)\n e54.push({ points: [n8.points[t10], n8.points[t10 + 1]], strokeColor: \"#ff7400\", strokeWidth: n8.width + 2 * (this.clearancePaddingTiers[this.clearanceTierCursor] ?? 0) });\n return { coordinateSystem: \"cartesian\", title: `Power trace cleanup: ${this.phase}`, lines: e54, points: [], circles: t4, rects: [], texts: [] };\n }\n};\nvar pte = (e54) =\u003e e54?.route_type === \"wire\";\nvar mte = class extends BaseSolver {\n inputProblem;\n traces;\n obstacleIndex;\n traceCursor = 0;\n routeCursor = 0;\n repairedSegmentCount = 0;\n repairedPadNeckSegmentCount = 0;\n unresolvedSegmentCount = 0;\n totalWidthReduction = 0;\n budgetLimited = false;\n connectivityValidationCount = 0;\n connectivityRollbackCount = 0;\n connectivityRegressionEndpointIds = [];\n connectivityValidationError = null;\n connectivityRollbackMutationStats = null;\n connectionNameResolver;\n nominalWidthByTraceId = new Map;\n connectivityInvariant;\n initialConnectivitySafeTraces;\n minimumTraceWidth;\n traceIndices;\n connectivityFinalized = false;\n constructor(e54) {\n super(), this.inputProblem = structuredClone(e54), this.traces = structuredClone(e54.traces), this.initialConnectivitySafeTraces = structuredClone(e54.traces), this.connectivityInvariant = new ote(this.inputProblem.simpleRouteJson, this.initialConnectivitySafeTraces), this.connectionNameResolver = new D7(e54.simpleRouteJson, this.traces), this.minimumTraceWidth = e54.simpleRouteJson.minTraceWidth;\n const t4 = e54.traceIndices ? [...new Set(e54.traceIndices)] : this.traces.map((e60, t10) =\u003e t10);\n for (const e60 of t4)\n if (!Number.isInteger(e60) || e60 \u003c 0 || e60 \u003e= this.traces.length)\n throw new RangeError(`Invalid clearance-repair trace index: ${e60}`);\n this.traceIndices = t4, this.obstacleIndex = this.createConservativeObstacleIndex();\n const n8 = this.traceIndices.reduce((e60, t10) =\u003e e60 + Math.max(0, this.traces[t10].route.length - 1), 0);\n this.MAX_ITERATIONS = Math.max(10, 8 * n8 + 2 * this.traceIndices.length), this.stats = this.createStats();\n }\n getSolverName() {\n return \"PowerTraceClearanceRepairSolver\";\n }\n _step() {\n const e54 = this.traceIndices[this.traceCursor], t4 = e54 === undefined ? undefined : this.traces[e54];\n if (!t4)\n return this.ensureConnectivitySafeOutput(), this.solved = true, void (this.stats = this.createStats());\n if (this.routeCursor \u003e= t4.route.length - 1)\n return this.traceCursor++, this.routeCursor = 0, void (this.stats = this.createStats());\n const n8 = this.routeCursor++, o10 = t4.route[n8], i8 = t4.route[n8 + 1];\n if (!pte(o10) || !pte(i8) || o10.layer !== i8.layer)\n return void (this.stats = this.createStats());\n const r9 = Math.max(o10.width, i8.width), s7 = { start: o10, end: i8, layer: o10.layer, width: r9, connectionNames: this.getTraceConnectionNames(t4), ignoreTraceIndex: e54, ignoreRouteRange: { start: n8, end: n8 + 1 } };\n if (this.repairConnectedPadNeck(t4, n8, s7))\n return void (this.stats = this.createStats());\n if (!this.segmentHasForeignTraceCollision(n8, r9))\n return void (this.stats = this.createStats());\n if (this.segmentHasForeignTraceCollision(n8, this.minimumTraceWidth))\n return this.unresolvedSegmentCount++, void (this.stats = this.createStats());\n let a9 = this.minimumTraceWidth, c5 = r9;\n for (let e60 = 0;e60 \u003c 10; e60++) {\n const e61 = (a9 + c5) / 2;\n this.segmentHasForeignTraceCollision(n8, e61) ? c5 = e61 : a9 = e61;\n }\n const l5 = r9 \u003e= 0.5 ? 0.025 : 0.0125, h5 = Math.max(this.minimumTraceWidth, Math.floor((a9 + L7) / l5) * l5), d9 = this.segmentHasForeignTraceCollision(n8, h5) ? a9 : h5, u9 = o10.width, p9 = i8.width;\n o10.width = Math.min(o10.width, d9), i8.width = Math.min(i8.width, d9);\n const m9 = u9 - o10.width + (p9 - i8.width);\n if (m9 \u003c= L7)\n return this.unresolvedSegmentCount++, void (this.stats = this.createStats());\n this.repairedSegmentCount++, this.totalWidthReduction += m9, this.obstacleIndex = this.createConservativeObstacleIndex(), this.routeCursor = Math.max(0, n8 - 1), this.stats = this.createStats();\n }\n repairConnectedPadNeck(e54, t4, n8) {\n const o10 = e54.route[t4], i8 = e54.route[t4 + 1];\n if (!pte(o10) || !pte(i8))\n return false;\n let r9 = this.obstacleIndex.getConnectedPadWidthLimitAtPoint(n8, o10), s7 = this.obstacleIndex.getConnectedPadWidthLimitAtPoint(n8, i8);\n t4 === 0 \u0026\u0026 (r9 = this.getSmallerLimit(r9, this.obstacleIndex.getConnectedPadEndpointWidthLimitAtPoint(n8, o10))), t4 + 1 === e54.route.length - 1 \u0026\u0026 (s7 = this.getSmallerLimit(s7, this.obstacleIndex.getConnectedPadEndpointWidthLimitAtPoint(n8, i8)));\n const a9 = r9, c5 = s7;\n if ((a9 === null || o10.width \u003c= a9 + L7) \u0026\u0026 (c5 === null || i8.width \u003c= c5 + L7))\n return false;\n const l5 = o10.width, h5 = i8.width;\n if (a9 !== null \u0026\u0026 (o10.width = Math.min(o10.width, a9)), c5 !== null \u0026\u0026 (i8.width = Math.min(i8.width, c5)), a9 !== null \u0026\u0026 c5 === null)\n this.insertPadBoundaryTransition(e54, t4, n8, \"start\", o10.width, h5);\n else if (a9 === null \u0026\u0026 c5 !== null)\n this.insertPadBoundaryTransition(e54, t4, n8, \"end\", i8.width, l5);\n else if (a9 !== null \u0026\u0026 c5 !== null) {\n const r10 = this.obstacleIndex.getConnectedPadBoundaryPoint(n8, \"start\"), s9 = this.obstacleIndex.getConnectedPadBoundaryPoint(n8, \"end\");\n r10 \u0026\u0026 s9 \u0026\u0026 (this.insertPadBoundaryTransition(e54, t4, n8, \"start\", o10.width, h5), this.insertPadBoundaryTransition(e54, t4 + 2, n8, \"end\", i8.width, l5));\n }\n return this.totalWidthReduction += l5 - o10.width + (h5 - i8.width), this.repairedPadNeckSegmentCount++, this.obstacleIndex = this.createConservativeObstacleIndex(), this.routeCursor = Math.max(0, t4 - 1), true;\n }\n getSmallerLimit(e54, t4) {\n return e54 === null ? t4 : t4 === null ? e54 : Math.min(e54, t4);\n }\n insertPadBoundaryTransition(e54, t4, n8, o10, i8, r9) {\n const s7 = this.obstacleIndex.getConnectedPadBoundaryPoint(n8, o10);\n if (!s7)\n return;\n const a9 = o10 === \"start\" ? n8.start : n8.end, c5 = o10 === \"start\" ? n8.end : n8.start, l5 = Math.hypot(c5.x - a9.x, c5.y - a9.y);\n if (l5 \u003c= 0.000000001)\n return;\n const h5 = Math.min(0.000001, l5 / 4), d9 = (c5.x - a9.x) / l5, u9 = (c5.y - a9.y) / l5, p9 = { route_type: \"wire\", x: s7.x - d9 * h5, y: s7.y - u9 * h5, width: i8, layer: n8.layer }, m9 = { ...p9, x: s7.x + d9 * h5, y: s7.y + u9 * h5, width: r9 }, g10 = o10 === \"start\" ? e54.route[t4 + 1] : e54.route[t4], f10 = o10 === \"start\" ? e54.route[t4 + 2] : e54.route[t4 - 1];\n if (pte(g10) \u0026\u0026 f10?.route_type === \"via\") {\n const t10 = this.resolveNominalTraceWidth(e54);\n this.obstacleIndex.collides({ ...n8, start: g10, end: m9, width: t10 }) || (g10.width = Math.max(g10.width, t10), m9.width = g10.width);\n }\n e54.route.splice(t4 + 1, 0, ...o10 === \"start\" ? [p9, m9] : [m9, p9]);\n }\n resolveNominalTraceWidth(e54) {\n const t4 = this.nominalWidthByTraceId.get(e54.pcb_trace_id);\n if (t4 !== undefined)\n return t4;\n const n8 = new Set(this.connectionNameResolver.canonicalize(this.getTraceConnectionNames(e54))), o10 = this.inputProblem.simpleRouteJson.connections.find((e60) =\u003e this.connectionNameResolver.canonicalize([e60.name, e60.source_trace_id, e60.rootConnectionName, e60.netConnectionName, ...e60.mergedConnectionNames ?? []].filter((e61) =\u003e Boolean(e61))).some((e61) =\u003e n8.has(e61))), i8 = Math.max(o10?.nominalTraceWidth ?? o10?.width ?? this.inputProblem.simpleRouteJson.nominalTraceWidth ?? this.minimumTraceWidth, this.minimumTraceWidth);\n return this.nominalWidthByTraceId.set(e54.pcb_trace_id, i8), i8;\n }\n segmentHasForeignTraceCollision(e54, t4) {\n const n8 = this.traceIndices[this.traceCursor], o10 = n8 === undefined ? undefined : this.traces[n8], i8 = o10?.route[e54], r9 = o10?.route[e54 + 1];\n return !!(o10 \u0026\u0026 pte(i8) \u0026\u0026 pte(r9) \u0026\u0026 i8.layer === r9.layer) \u0026\u0026 this.obstacleIndex.findCollisions({ start: i8, end: r9, layer: i8.layer, width: t4, connectionNames: this.getTraceConnectionNames(o10), ignoreTraceIndex: n8, ignoreRouteRange: { start: e54, end: e54 + 1 } }).some((e60) =\u003e e60.kind === \"trace\" \u0026\u0026 e60.traceIndex !== undefined \u0026\u0026 e60.traceIndex !== n8);\n }\n createConservativeObstacleIndex() {\n const e54 = structuredClone(this.traces);\n for (const t4 of e54)\n for (let e60 = 0;e60 \u003c t4.route.length - 1; e60++) {\n const n8 = t4.route[e60], o10 = t4.route[e60 + 1];\n pte(n8) \u0026\u0026 pte(o10) \u0026\u0026 n8.layer === o10.layer \u0026\u0026 (n8.width = Math.max(n8.width, o10.width));\n }\n return new Cee(this.inputProblem.simpleRouteJson, e54, undefined, [], this.connectionNameResolver);\n }\n getTraceConnectionNames(e54) {\n return [e54.pcb_trace_id, e54.connection_name, e54.source_trace_id, e54.rootConnectionName, ...e54.mergedConnectionNames ?? [], ...e54.connectsTo ?? []].filter((e60) =\u003e Boolean(e60));\n }\n ensureConnectivitySafeOutput() {\n if (!this.connectivityFinalized) {\n this.connectivityFinalized = true, this.connectivityValidationCount++;\n try {\n const e54 = this.connectivityInvariant.validate(this.traces);\n if (this.connectivityValidationError ??= e54.validationError ?? null, e54.safe)\n return;\n this.connectivityRegressionEndpointIds = [...new Set(e54.regressions.flatMap((e60) =\u003e e60.baselineEndpointLabels))];\n } catch (e54) {\n this.connectivityValidationError = e54 instanceof Error ? e54.message : String(e54);\n }\n this.connectivityRollbackCount++, this.connectivityRollbackMutationStats = { repairedSegmentCount: this.repairedSegmentCount, repairedPadNeckSegmentCount: this.repairedPadNeckSegmentCount, totalWidthReduction: this.totalWidthReduction }, this.repairedSegmentCount = 0, this.repairedPadNeckSegmentCount = 0, this.totalWidthReduction = 0, this.traces = structuredClone(this.initialConnectivitySafeTraces), this.obstacleIndex = this.createConservativeObstacleIndex();\n }\n }\n createStats() {\n return { phase: this.solved ? \"complete\" : \"repair-trace-clearance\", budgetLimited: this.budgetLimited, completionReason: this.solved ? this.connectivityRollbackCount \u003e 0 ? \"connectivity_rollback\" : this.budgetLimited ? \"iteration_budget\" : this.connectivityValidationError ? \"connectivity_validation_unavailable\" : \"completed\" : null, resultStatus: this.connectivityRollbackCount \u003e 0 || this.budgetLimited || this.connectivityValidationError !== null ? \"best_effort\" : \"complete\", traceCursor: this.traceCursor, traceCount: this.traceIndices.length, traceIndex: this.traceIndices[this.traceCursor], routeCursor: this.routeCursor, repairedSegmentCount: this.repairedSegmentCount, repairedPadNeckSegmentCount: this.repairedPadNeckSegmentCount, unresolvedSegmentCount: this.unresolvedSegmentCount, totalWidthReduction: this.totalWidthReduction, connectivityValidationCount: this.connectivityValidationCount, connectivityRollbackCount: this.connectivityRollbackCount, connectivityRegressionEndpointIds: [...this.connectivityRegressionEndpointIds], connectivityValidationError: this.connectivityValidationError, connectivityRollbackMutationStats: this.connectivityRollbackMutationStats === null ? null : { ...this.connectivityRollbackMutationStats }, spatialIndexRectCount: this.obstacleIndex.items.length };\n }\n computeProgress() {\n return this.solved || this.traceIndices.length === 0 ? 1 : Math.min(0.99, this.traceCursor / this.traceIndices.length);\n }\n tryFinalAcceptance() {\n this.ensureConnectivitySafeOutput(), this.budgetLimited = true, this.solved = true, this.progress = 1, this.stats = this.createStats();\n }\n getConstructorParams() {\n return [this.inputProblem];\n }\n getOutput() {\n return structuredClone(this.solved ? this.traces : this.initialConnectivitySafeTraces);\n }\n visualize() {\n const e54 = [];\n for (let t4 = 0;t4 \u003c this.traces.length; t4++) {\n const n8 = this.traces[t4];\n for (let o10 = 0;o10 \u003c n8.route.length - 1; o10++) {\n const i8 = n8.route[o10], r9 = n8.route[o10 + 1];\n pte(i8) \u0026\u0026 pte(r9) \u0026\u0026 i8.layer === r9.layer \u0026\u0026 e54.push({ points: [i8, r9], strokeColor: t4 === this.traceIndices[this.traceCursor] \u0026\u0026 o10 === this.routeCursor ? \"#ff7400\" : i8.layer === \"bottom\" ? \"#376fc4\" : \"#777\", strokeWidth: Math.max(i8.width, r9.width) });\n }\n }\n return { coordinateSystem: \"cartesian\", title: \"Power trace direction-independent clearance repair\", lines: e54, points: [], circles: [], rects: [], texts: [] };\n }\n};\nvar gte = [{ x: 0, y: 0 }, { x: 0.5, y: 0 }, { x: 0, y: 0.5 }, { x: 0.5, y: 0.5 }];\nvar fte = [{ offset: { x: 0, y: 0 }, strictNecking: true }, { offset: { x: 0.5, y: 0.5 }, strictNecking: true }, { offset: { x: 0, y: 0 }, strictNecking: false }, { offset: { x: 0.5, y: 0.5 }, strictNecking: false }];\nvar _te = 64;\nvar yte = (e54) =\u003e [...new Set(e54.map((e60) =\u003e Number(e60.toFixed(6))))].sort((e60, t4) =\u003e t4 - e60);\nvar bte = (e54) =\u003e e54?.route_type === \"wire\";\nvar xte = class extends BaseSolver {\n inputProblem;\n options;\n operationIndex = 0;\n traces;\n obstacleIndex;\n connectionNameResolver;\n connectionByTraceId = new Map;\n connectivityInvariant;\n lastConnectivitySafeTraces;\n traceOrder;\n selectedOwnedTraceIndices;\n selectedCleanupTraceIndices;\n selectedViaRepairTraceIndices;\n mutableBlockerTraceIndices;\n immutableTraceIndices;\n initialImmutableTraceSignatures = new Map;\n traceOrderCursor = -1;\n maxPassCount = 4;\n previousWidthDeficit = 0;\n passIndex = 0;\n completedPassCount = 0;\n lastNormalizedWidthDeficitGain = 0;\n normalizedWidthDeficitGainByPass = [];\n plateauReached = false;\n phase = \"scan-trace\";\n traceIndex = -1;\n routeSegmentIndex = 0;\n nominalTraceWidth = 0;\n currentIntervals = [];\n intervalCursor = 0;\n candidateWidths = [];\n widthCursor = 0;\n gridResolutions = [];\n resolutionCursor = 0;\n offsetCursor = 0;\n keptTraceCount = 0;\n recreatedTraceCount = 0;\n expandedSegmentCount = 0;\n intermediateExpandedSegmentCount = 0;\n pathWidthUpgradeCount = 0;\n inPlaceWidthProbeCount = 0;\n reroutedSegmentCount = 0;\n unresolvedSegmentCount = 0;\n attemptedGridCount = 0;\n attemptedLayerGridCount = 0;\n attemptedInflationCount = 0;\n pushedTraceCount = 0;\n elasticPushedTraceCount = 0;\n layerReroutedTraceCount = 0;\n insertedViaCount = 0;\n neckedLayerSegmentCount = 0;\n removedViaPairCount = 0;\n removedViaCount = 0;\n simplifiedPathCount = 0;\n normalizedSegmentCount = 0;\n cleanupClearanceShoveCount = 0;\n relocatedViaCount = 0;\n unresolvedViaCount = 0;\n initialImmutableViaViolationCount = 0;\n remainingImmutableViaViolationCount = 0;\n initialImmutableViaViolationPairCount = 0;\n remainingImmutableViaViolationPairCount = 0;\n immutableTraceMutationIds = [];\n lastSafeImmutableViaViolationSignatures = new Set;\n immutableViaViolationRollbackCount = 0;\n attemptedImmutableViaViolationCount = null;\n attemptedImmutableViaViolationPairCount = null;\n immutableViaViolationRegressionIds = [];\n padClearanceRerouteCount = 0;\n unresolvedPadClearanceCount = 0;\n repairedTraceClearanceSegmentCount = 0;\n repairedPadNeckSegmentCount = 0;\n unresolvedTraceClearanceSegmentCount = 0;\n sameNetContactRejectionCount = 0;\n connectivityValidationCount = 0;\n connectivityRollbackCount = 0;\n connectivityRollbackPhases = [];\n immutableSafetyRollbackCount = 0;\n immutableSafetyRollbackPhases = [];\n connectivityRegressionEndpointIds = [];\n connectivityValidationError = null;\n connectivityRollbackMutationStats = null;\n immutableSafetyRollbackMutationStats = null;\n discardedExpansionMutationStats = null;\n initialPadClearanceViolationCount = 0;\n remainingPadClearanceViolationCount = 0;\n initialPadClearanceViolationCountByClearance = {};\n remainingPadClearanceViolationCountByClearance = {};\n budgetLimitedExpansion = false;\n finalAcceptanceUsed = false;\n cleanupCompleted = false;\n clearanceRepairCompleted = false;\n cleanupBestEffortAccepted = false;\n clearanceRepairBestEffortAccepted = false;\n cleanupIterationBudget = 0;\n clearanceRepairIterationBudget = 0;\n expansionPushedTraceIndices = new Set;\n cleanupMutatedTraceIndices = [];\n failedSubSolverCount = 0;\n inflationAttemptsBySegment = new Map;\n layerAttemptCountByTrace = new Map;\n layerRerouteCountByTrace = new Map;\n activeInflationKey = null;\n activeInflationWidth = null;\n layerAttempt = null;\n pendingLayerOutput = null;\n pendingLayerPushCount = 0;\n statsMaxIterations = 0;\n constructor(e54, t4 = {}) {\n super(), this.inputProblem = structuredClone(e54), this.options = structuredClone(t4), this.traces = structuredClone(e54.traces ?? []), this.connectionNameResolver = new D7(this.inputProblem, this.traces), this.lastConnectivitySafeTraces = structuredClone(this.traces), this.connectivityInvariant = new ote(this.inputProblem, this.lastConnectivitySafeTraces);\n const n8 = t4.onlyConnectionNames ? new Set(this.connectionNameResolver.canonicalize([...t4.onlyConnectionNames])) : null, o10 = this.traces.flatMap((e60, t10) =\u003e {\n if (!n8)\n return [t10];\n return this.connectionNameResolver.canonicalize(this.getTraceConnectionNames(e60)).some((e61) =\u003e n8.has(e61)) ? [t10] : [];\n }), i8 = new Map(o10.map((e60) =\u003e [e60, this.getInitialTracePriority(this.traces[e60])]));\n this.traceOrder = o10.sort((e60, t10) =\u003e i8.get(t10) - i8.get(e60) || e60 - t10), this.selectedOwnedTraceIndices = this.traceOrder.filter((e60) =\u003e this.findConnectionForTrace(this.traces[e60])), this.selectedCleanupTraceIndices = [...this.selectedOwnedTraceIndices], this.selectedViaRepairTraceIndices = [...this.selectedOwnedTraceIndices], this.mutableBlockerTraceIndices = this.traces.flatMap((e60, t10) =\u003e this.findConnectionForTrace(e60) ? [t10] : []);\n const r9 = new Set(this.mutableBlockerTraceIndices);\n this.immutableTraceIndices = this.traces.flatMap((e60, t10) =\u003e r9.has(t10) ? [] : (this.initialImmutableTraceSignatures.set(t10, JSON.stringify(e60)), [t10])), this.previousWidthDeficit = this.calculateWidthDeficit().deficit, this.obstacleIndex = new Cee(this.inputProblem, this.traces, this.traceIndex \u003e= 0 ? this.traceIndex : undefined, [], this.connectionNameResolver), this.lastSafeImmutableViaViolationSignatures = this.getImmutableViaViolationSignatures(this.traces), this.initialImmutableViaViolationCount = this.countViolatingImmutableVias(this.lastSafeImmutableViaViolationSignatures), this.remainingImmutableViaViolationCount = this.initialImmutableViaViolationCount, this.initialImmutableViaViolationPairCount = this.lastSafeImmutableViaViolationSignatures.size, this.remainingImmutableViaViolationPairCount = this.initialImmutableViaViolationPairCount, this.activeSubSolver = null, this.MAX_ITERATIONS = 125000, this.stats = this.createStats();\n }\n getSolverName() {\n return \"PowerTraceExpanderSolver\";\n }\n _step() {\n const e54 = this.activeSubSolver;\n for (let e60 = 0;e60 \u003c _te \u0026\u0026 (this.operationIndex = e60, this.stepOperation(), !this.solved \u0026\u0026 !this.failed); e60++)\n ;\n (!e54 || this.activeSubSolver !== e54 || e54.solved || e54.failed || this.MAX_ITERATIONS !== this.statsMaxIterations) \u0026\u0026 (this.stats = this.createStats());\n }\n stepOperation() {\n if (this.shouldStartBudgetFinalization())\n this.startBudgetFinalization();\n else if (this.activeSubSolver)\n this.stepActiveGridSolver();\n else\n switch (this.phase) {\n case \"scan-trace\":\n this.scanNextTrace();\n break;\n case \"evaluate-segment\":\n this.evaluateNextSegment();\n break;\n case \"try-trace-inflation\":\n case \"cleanup\":\n case \"repair-trace-clearance\":\n break;\n case \"try-layer-candidate\":\n this.startNextLayerCandidate();\n break;\n case \"try-grid-candidate\":\n this.startNextGridCandidate();\n break;\n case \"complete\":\n this.acceptConnectivityCheckpoint(this.traces, \"final\"), this.solved = true;\n }\n }\n scanNextTrace() {\n if (this.traceOrderCursor++, this.routeSegmentIndex = 0, this.traceOrderCursor \u003e= this.traceOrder.length)\n return void this.finishOrStartNextPass();\n this.traceIndex = this.traceOrder[this.traceOrderCursor];\n const e54 = this.traces[this.traceIndex];\n this.findConnectionForTrace(e54) ? (this.nominalTraceWidth = this.resolveNominalTraceWidth(e54), this.traceMeetsNominalWidth(e54, this.nominalTraceWidth) ? this.keptTraceCount++ : (this.rebuildObstacleIndex(), e54.route = function(e60, t4) {\n if (e60.length \u003c 2)\n return e60.map((e61) =\u003e ({ ...e61 }));\n const n8 = [];\n for (let o10 = 0;o10 \u003c e60.length - 1; o10++) {\n const i8 = e60[o10], r9 = e60[o10 + 1];\n if (n8.push({ ...i8 }), i8.route_type !== \"wire\" || r9.route_type !== \"wire\" || i8.layer !== r9.layer || i8.width \u003e= t4 - L7)\n continue;\n const s7 = z7(i8, r9), a9 = Math.max(1, Math.ceil(s7 / t4));\n for (let e61 = 1;e61 \u003c a9; e61++) {\n const t10 = e61 / a9;\n n8.push({ route_type: \"wire\", x: i8.x + (r9.x - i8.x) * t10, y: i8.y + (r9.y - i8.y) * t10, width: i8.width, layer: i8.layer });\n }\n }\n return n8.push({ ...e60[e60.length - 1] }), n8;\n }(e54.route, this.nominalTraceWidth), this.recreatedTraceCount++, this.phase = \"evaluate-segment\")) : this.keptTraceCount++;\n }\n finishOrStartNextPass() {\n const { deficit: e54, nominalArea: t4 } = this.calculateWidthDeficit(), n8 = this.previousWidthDeficit - e54;\n if (this.lastNormalizedWidthDeficitGain = t4 \u003c= L7 ? 0 : n8 / t4, this.normalizedWidthDeficitGainByPass.push(this.lastNormalizedWidthDeficitGain), this.plateauReached = this.lastNormalizedWidthDeficitGain \u003c 0.001, this.completedPassCount = this.passIndex + 1, this.passIndex + 1 \u003c this.maxPassCount \u0026\u0026 this.lastNormalizedWidthDeficitGain \u003e= 0.001)\n return this.previousWidthDeficit = e54, this.passIndex++, this.traceOrderCursor = -1, this.traceIndex = -1, this.routeSegmentIndex = 0, this.inflationAttemptsBySegment.clear(), void (this.phase = \"scan-trace\");\n this.startCleanup();\n }\n startCleanup() {\n this.acceptConnectivityCheckpoint(this.traces, \"expansion\"), this.traceIndex = this.traces.length, this.phase = \"cleanup\";\n const e54 = new dte({ simpleRouteJson: this.inputProblem, traces: this.traces, traceIndices: this.selectedCleanupTraceIndices, viaRepairTraceIndices: this.selectedViaRepairTraceIndices, mutableTraceIndices: this.mutableBlockerTraceIndices, maxRerouteLength: 10, desiredPadClearance: this.options.powerTraceToPadClearance }), t4 = this.getRemainingChildStepBudget(), n8 = t4 === 0 ? 0 : Math.max(1, Math.floor(0.75 * t4));\n e54.MAX_ITERATIONS = Math.min(e54.MAX_ITERATIONS, n8), this.cleanupIterationBudget = e54.MAX_ITERATIONS, this.activeSubSolver = e54;\n }\n shouldStartBudgetFinalization() {\n return !this.budgetLimitedExpansion \u0026\u0026 (this.phase !== \"cleanup\" \u0026\u0026 this.phase !== \"repair-trace-clearance\" \u0026\u0026 this.phase !== \"complete\" \u0026\u0026 this.getOperationCount() \u003e= this.getExpansionOperationBudget());\n }\n getExpansionOperationBudget() {\n const e54 = this.MAX_ITERATIONS * _te, t4 = Math.min(Math.max(0, e54 - 1), Math.max(1, Math.floor(0.125 * e54)));\n return Math.max(1, e54 - t4);\n }\n getFinalizationIterationReserve() {\n return Math.max(0, this.MAX_ITERATIONS - this.getExpansionIterationBudget());\n }\n getExpansionIterationBudget() {\n return Math.ceil(this.getExpansionOperationBudget() / _te);\n }\n startBudgetFinalization() {\n this.budgetLimitedExpansion = true, this.activeSubSolver = null, this.pendingLayerOutput = null, this.pendingLayerPushCount = 0, this.activeInflationKey = null, this.activeInflationWidth = null, this.layerAttempt = null, this.discardInFlightExpansion(), this.startCleanup();\n }\n discardInFlightExpansion() {\n this.discardedExpansionMutationStats = this.captureAndResetExpansionMutationStats(), this.restoreLastConnectivitySafeTraces();\n }\n rollbackConnectivityRegressedExpansion() {\n this.connectivityRollbackMutationStats = this.captureAndResetExpansionMutationStats(), this.restoreLastConnectivitySafeTraces();\n }\n rollbackImmutableUnsafeExpansion() {\n this.immutableSafetyRollbackMutationStats = this.captureAndResetExpansionMutationStats(), this.restoreLastConnectivitySafeTraces();\n }\n captureAndResetExpansionMutationStats() {\n const e54 = { recreatedTraceCount: this.recreatedTraceCount, expandedSegmentCount: this.expandedSegmentCount, intermediateExpandedSegmentCount: this.intermediateExpandedSegmentCount, pathWidthUpgradeCount: this.pathWidthUpgradeCount, reroutedSegmentCount: this.reroutedSegmentCount, pushedTraceCount: this.pushedTraceCount, elasticPushedTraceCount: this.elasticPushedTraceCount, layerReroutedTraceCount: this.layerReroutedTraceCount, insertedViaCount: this.insertedViaCount, neckedLayerSegmentCount: this.neckedLayerSegmentCount };\n return this.recreatedTraceCount = 0, this.expandedSegmentCount = 0, this.intermediateExpandedSegmentCount = 0, this.pathWidthUpgradeCount = 0, this.reroutedSegmentCount = 0, this.pushedTraceCount = 0, this.elasticPushedTraceCount = 0, this.layerReroutedTraceCount = 0, this.insertedViaCount = 0, this.neckedLayerSegmentCount = 0, this.expansionPushedTraceIndices.clear(), e54;\n }\n restoreLastConnectivitySafeTraces() {\n this.traces = structuredClone(this.lastConnectivitySafeTraces), this.rebuildObstacleIndex();\n }\n getOperationCount() {\n return this.iterations === 0 ? 0 : (this.iterations - 1) * _te + this.operationIndex + 1;\n }\n getRemainingChildStepBudget() {\n return Math.max(0, this.MAX_ITERATIONS * _te - this.getOperationCount() - 1);\n }\n calculateWidthDeficit() {\n let e54 = 0, t4 = 0;\n for (const n8 of this.traceOrder) {\n const o10 = this.traces[n8];\n if (!this.findConnectionForTrace(o10))\n continue;\n const i8 = this.resolveNominalTraceWidth(o10);\n for (let n10 = 0;n10 \u003c o10.route.length - 1; n10++) {\n const r9 = o10.route[n10], s7 = o10.route[n10 + 1];\n if (!bte(r9) || !bte(s7) || r9.layer !== s7.layer)\n continue;\n const a9 = z7(r9, s7), c5 = r9.width;\n t4 += a9 * i8, e54 += a9 * Math.max(0, i8 - c5);\n }\n }\n return { deficit: e54, nominalArea: t4 };\n }\n getInitialTracePriority(e54) {\n const t4 = this.resolveNominalTraceWidth(e54);\n let n8 = 0;\n for (let o10 = 0;o10 \u003c e54.route.length - 1; o10++) {\n const i8 = e54.route[o10], r9 = e54.route[o10 + 1];\n bte(i8) \u0026\u0026 bte(r9) \u0026\u0026 i8.layer === r9.layer \u0026\u0026 (n8 += z7(i8, r9) * Math.max(0, t4 - Math.min(i8.width, r9.width)));\n }\n return t4 * n8;\n }\n evaluateNextSegment() {\n const e54 = this.traces[this.traceIndex];\n if (!e54)\n return void (this.phase = \"scan-trace\");\n const t4 = this.findNextUnderWidthSegment(e54, this.routeSegmentIndex, this.nominalTraceWidth);\n if (t4 === -1)\n return void (this.phase = \"scan-trace\");\n this.routeSegmentIndex = t4;\n const n8 = e54.route[t4], o10 = e54.route[t4 + 1];\n if (!bte(n8) || !bte(o10))\n return void this.routeSegmentIndex++;\n const i8 = this.getTraceConnectionNames(e54), r9 = Math.min(n8.width, o10.width), s7 = this.findMaximumSafeInPlaceWidth(e54, t4, i8);\n if (s7 \u003e r9 + L7) {\n if (n8.width = Math.max(n8.width, s7), o10.width = Math.max(o10.width, s7), s7 \u003e= this.nominalTraceWidth - L7)\n return this.expandedSegmentCount++, void this.routeSegmentIndex++;\n this.intermediateExpandedSegmentCount++;\n }\n this.startTraceInflation(e54, t4) || this.prepareLayerRouteAttempt(e54, t4) || this.prepareRegularGridCandidates(e54, t4);\n }\n prepareRegularGridCandidates(e54, t4) {\n if (this.currentIntervals = this.getExponentialIntervalCandidates(e54, t4, this.nominalTraceWidth), this.intervalCursor = 0, this.candidateWidths = this.getCandidateWidths(this.nominalTraceWidth), this.widthCursor = 0, this.gridResolutions = [], this.resolutionCursor = 0, this.offsetCursor = 0, this.currentIntervals.length === 0)\n return this.unresolvedSegmentCount++, void this.routeSegmentIndex++;\n this.phase = \"try-grid-candidate\";\n }\n prepareLayerRouteAttempt(e54, t4) {\n if (this.nominalTraceWidth \u003c 0.499999)\n return false;\n const n8 = this.options.allowNewVias !== false \u0026\u0026 this.inputProblem.layerCount \u003e= 2, o10 = n8 ? 2 : this.maxPassCount, i8 = this.layerAttemptCountByTrace.get(this.traceIndex) ?? 0, r9 = this.layerRerouteCountByTrace.get(this.traceIndex) ?? 0;\n if (r9 \u003e= o10 || i8 \u003e= o10 || i8 \u003e this.passIndex || i8 \u003e 0 \u0026\u0026 r9 === 0)\n return false;\n const s7 = e54.route[t4], a9 = e54.route[t4 + 1];\n if (!bte(s7) || !bte(a9) || Math.min(s7.width, a9.width) \u003e= 0.5 * this.nominalTraceWidth - L7)\n return false;\n const c5 = this.getExponentialIntervalCandidates(e54, t4, this.nominalTraceWidth).filter((t10) =\u003e this.intervalSupportsLayerRouting(e54, t10)).sort((t10, n10) =\u003e n10.endIndex - t10.endIndex || t10.startIndex - n10.startIndex || this.getRouteIntervalLength(e54, n10.startIndex, n10.endIndex) - this.getRouteIntervalLength(e54, t10.startIndex, t10.endIndex))[0];\n if (!c5)\n return false;\n const l5 = this.getRouteQuality(e54.route.slice(c5.startIndex, c5.endIndex + 1));\n if (l5.deficitArea \u003c this.nominalTraceWidth)\n return false;\n if (i8 \u003e 0 \u0026\u0026 l5.deficitArea / Math.max(l5.length, L7) \u003c 0.25)\n return false;\n const h5 = e54.route[c5.startIndex], d9 = e54.route[c5.endIndex], u9 = this.getTraceConnectionNames(e54), p9 = n8 ? this.getEndpointLayers(h5, u9) : [h5.layer], m9 = n8 ? this.getEndpointLayers(d9, u9) : [d9.layer], g10 = Math.min(this.nominalTraceWidth, Math.max(h5.width, this.findMaximumSafeInPlaceWidth(e54, c5.startIndex, u9))), f10 = Math.min(this.nominalTraceWidth, Math.max(d9.width, this.findMaximumSafeInPlaceWidth(e54, c5.endIndex - 1, u9))), _5 = this.getSoftTraceIndices(this.nominalTraceWidth);\n return this.layerAttemptCountByTrace.set(this.traceIndex, i8 + 1), this.layerAttempt = { interval: c5, minViaCount: n8 ? 1 : 0, maxViaCount: n8 ? 2 : 0, candidateWidths: [this.nominalTraceWidth], widthCursor: 0, gridResolutions: [j7(this.nominalTraceWidth / 4, 0.2, 0.3)], resolutionCursor: 0, offsetCursor: 0, startLayers: p9, endLayers: m9, startNeckWidth: g10, endNeckWidth: f10, softTraceIndices: _5 }, this.phase = \"try-layer-candidate\", true;\n }\n intervalSupportsLayerRouting(e54, t4) {\n if (t4.startIndex \u003e= t4.endIndex)\n return false;\n for (let n10 = t4.startIndex;n10 \u003c= t4.endIndex; n10++) {\n const t10 = e54.route[n10];\n if (!bte(t10))\n return false;\n }\n const n8 = e54.route[t4.startIndex], o10 = e54.route[t4.endIndex];\n return n8.layer === o10.layer;\n }\n getEndpointLayers(e54, t4) {\n return [...new Set([e54.layer, ...this.obstacleIndex.getConnectedLayersAtPoint({ x: e54.x, y: e54.y }, t4)])].filter((e60) =\u003e this.obstacleIndex.boardLayers.includes(e60));\n }\n getSoftTraceIndices(e54) {\n const t4 = [];\n for (let n8 = 0;n8 \u003c this.traces.length; n8++) {\n if (n8 === this.traceIndex)\n continue;\n const o10 = this.traces[n8], i8 = this.findConnectionForTrace(o10);\n if (!i8)\n continue;\n Math.max(i8.nominalTraceWidth ?? i8.width ?? this.inputProblem.nominalTraceWidth ?? this.inputProblem.minTraceWidth, this.inputProblem.minTraceWidth) \u003c e54 - L7 \u0026\u0026 t4.push(n8);\n }\n return t4;\n }\n startNextLayerCandidate() {\n const e54 = this.layerAttempt, t4 = this.traces[this.traceIndex];\n if (!e54 || !t4)\n return this.layerAttempt = null, void (this.phase = \"evaluate-segment\");\n if (e54.widthCursor \u003e= e54.candidateWidths.length) {\n const e60 = this.routeSegmentIndex;\n return this.layerAttempt = null, void this.prepareRegularGridCandidates(t4, e60);\n }\n const n8 = e54.candidateWidths[e54.widthCursor];\n if (e54.gridResolutions.length === 0 \u0026\u0026 (e54.gridResolutions = this.getGridResolutions(n8)), e54.resolutionCursor \u003e= e54.gridResolutions.length)\n return e54.widthCursor++, e54.gridResolutions = [], e54.resolutionCursor = 0, void (e54.offsetCursor = 0);\n if (e54.offsetCursor \u003e= fte.length)\n return e54.resolutionCursor++, void (e54.offsetCursor = 0);\n const o10 = t4.route[e54.interval.startIndex], i8 = t4.route[e54.interval.endIndex];\n if (!bte(o10) || !bte(i8))\n return this.layerAttempt = null, void this.prepareRegularGridCandidates(t4, this.routeSegmentIndex);\n const r9 = e54.gridResolutions[e54.resolutionCursor], s7 = fte[e54.offsetCursor], a9 = s7.offset, c5 = Math.min(e54.startNeckWidth, e54.endNeckWidth), l5 = this.inputProblem.min_via_hole_diameter ?? this.inputProblem.minViaHoleDiameter ?? 0.3, h5 = Math.max(l5, this.inputProblem.min_via_pad_diameter ?? this.inputProblem.minViaPadDiameter ?? this.inputProblem.minViaDiameter ?? 0.6), d9 = Math.max(this.inputProblem.minTraceWidth, Math.min(s7.strictNecking ? e54.startNeckWidth : c5, n8)), u9 = Math.max(this.inputProblem.minTraceWidth, Math.min(s7.strictNecking ? e54.endNeckWidth : c5, n8)), p9 = j7(3 * this.nominalTraceWidth, 1.5, 3);\n e54.maxViaCount \u003e 0 ? this.attemptedLayerGridCount++ : this.attemptedGridCount++, this.activeSubSolver = new iee({ start: o10, end: i8, originalStartLayer: o10.layer, originalEndLayer: i8.layer, startLayers: e54.startLayers, endLayers: e54.endLayers, layers: this.obstacleIndex.boardLayers, traceWidth: n8, startNeckWidth: d9, endNeckWidth: u9, maxStartNeckLength: p9, maxEndNeckLength: p9, neckPenaltyExponent: s7.strictNecking ? 2 : 1, viaDiameter: h5, viaHoleDiameter: l5, minViaCount: e54.minViaCount, maxViaCount: e54.maxViaCount, viaCost: Math.max(1, 2 * this.nominalTraceWidth), gridSize: r9, gridOffset: { x: a9.x * r9, y: a9.y * r9 }, connectionNames: this.getTraceConnectionNames(t4), obstacleIndex: this.obstacleIndex, ignoreTraceIndex: this.traceIndex, ignoreRouteRange: { start: Math.max(0, e54.interval.startIndex - 1), end: Math.min(t4.route.length - 1, e54.interval.endIndex + 1) }, softTraceIndices: e54.softTraceIndices, fixedVias: this.getFixedViasOutsideInterval(t4, e54.interval), bounds: this.inputProblem.bounds, obstacleClearance: this.getDesiredPadClearance(n8), searchPadding: Math.min(5, Math.max(2.5, z7(o10, i8) / 2, 4 * n8)) });\n }\n startNextGridCandidate() {\n const e54 = this.traces[this.traceIndex];\n if (!e54)\n return void (this.phase = \"scan-trace\");\n if (this.widthCursor \u003e= this.candidateWidths.length)\n return this.unresolvedSegmentCount++, this.routeSegmentIndex++, void (this.phase = \"evaluate-segment\");\n if (this.intervalCursor \u003e= this.currentIntervals.length)\n return this.widthCursor++, this.intervalCursor = 0, this.gridResolutions = [], this.resolutionCursor = 0, void (this.offsetCursor = 0);\n const t4 = this.candidateWidths[this.widthCursor], n8 = e54.route[this.routeSegmentIndex], o10 = e54.route[this.routeSegmentIndex + 1];\n if (bte(n8) \u0026\u0026 bte(o10) \u0026\u0026 t4 \u003c= Math.min(n8.width, o10.width) + L7)\n return void (this.widthCursor = this.candidateWidths.length);\n if (this.gridResolutions.length === 0 \u0026\u0026 (this.gridResolutions = this.getGridResolutions(t4)), this.resolutionCursor \u003e= this.gridResolutions.length)\n return this.intervalCursor++, this.resolutionCursor = 0, void (this.offsetCursor = 0);\n if (this.offsetCursor \u003e= gte.length)\n return this.resolutionCursor++, void (this.offsetCursor = 0);\n const i8 = this.currentIntervals[this.intervalCursor], r9 = e54.route[i8.startIndex], s7 = e54.route[i8.endIndex];\n if (!bte(r9) || !bte(s7) || r9.layer !== s7.layer)\n return this.intervalCursor++, this.resolutionCursor = 0, void (this.offsetCursor = 0);\n if (this.endpointCollides(e54, i8, r9, t4) || this.endpointCollides(e54, i8, s7, t4))\n return this.intervalCursor++, this.resolutionCursor = 0, void (this.offsetCursor = 0);\n const a9 = this.gridResolutions[this.resolutionCursor], c5 = gte[this.offsetCursor], l5 = { x: c5.x * a9, y: c5.y * a9 };\n this.attemptedGridCount++, this.activeSubSolver = new yee({ start: r9, end: s7, layer: r9.layer, traceWidth: t4, gridSize: a9, gridOffset: l5, connectionNames: this.getTraceConnectionNames(e54), obstacleIndex: this.obstacleIndex, ignoreTraceIndex: this.traceIndex, ignoreRouteRange: { start: Math.max(0, i8.startIndex - 1), end: Math.min(e54.route.length - 1, i8.endIndex + 1) }, bounds: this.inputProblem.bounds, obstacleClearance: this.getDesiredPadClearance(t4), searchPadding: Math.min(5, Math.max(1.5, z7(r9, s7) / 2, 3 * t4)) });\n }\n endpointCollides(e54, t4, n8, o10) {\n return this.obstacleIndex.collides({ start: n8, end: n8, layer: n8.layer, width: o10, connectionNames: this.getTraceConnectionNames(e54), ignoreTraceIndex: this.traceIndex, ignoreRouteRange: { start: Math.max(0, t4.startIndex - 1), end: Math.min(e54.route.length - 1, t4.endIndex + 1) }, obstacleClearance: this.getDesiredPadClearance(o10) });\n }\n stepActiveGridSolver() {\n if (this.activeSubSolver instanceof mte)\n return void this.stepActiveTraceClearanceRepairSolver();\n if (this.activeSubSolver instanceof dte)\n return void this.stepActiveCleanupSolver();\n if (this.activeSubSolver instanceof wee)\n return void this.stepActiveInflationSolver();\n if (this.activeSubSolver instanceof iee)\n return void this.stepActiveLayerSolver();\n const e54 = this.activeSubSolver;\n if (e54.step(), e54.solved || e54.failed) {\n if (e54.solved) {\n const t4 = e54.getOutput();\n if (t4) {\n const e60 = this.gridRouteReplacementCollides(t4) || this.gridRouteBoundaryCollides(t4);\n if (!e60 \u0026\u0026 this.gridRoutePreservesSameNetContacts(t4))\n return this.applyGridRoute(this.maximizeGridRouteWidth(t4)), void (this.activeSubSolver = null);\n e60 || this.sameNetContactRejectionCount++;\n }\n }\n this.retainFailedSubSolver(e54), this.activeSubSolver = null, this.offsetCursor++;\n }\n }\n stepActiveCleanupSolver() {\n const e54 = this.activeSubSolver;\n if (e54.step(), e54.solved || e54.failed) {\n if (e54.solved)\n return this.adoptCleanupOutput(e54), this.activeSubSolver = null, void this.startTraceClearanceRepair();\n this.retainFailedSubSolver(e54), this.activeSubSolver = null, this.startTraceClearanceRepair();\n }\n }\n adoptCleanupOutput(e54) {\n const t4 = this.acceptConnectivityCheckpoint(e54.getOutput(), \"cleanup\");\n this.cleanupCompleted = !e54.budgetLimited;\n const n8 = e54.stats;\n this.connectivityValidationError ??= n8.connectivityValidationError ?? null, this.connectivityValidationCount += Number(n8.connectivityValidationCount ?? 0);\n const o10 = Number(n8.connectivityRollbackCount ?? 0);\n o10 \u003e 0 \u0026\u0026 (this.connectivityRollbackCount += o10, this.connectivityRollbackPhases.includes(\"cleanup\") || this.connectivityRollbackPhases.push(\"cleanup\"), this.connectivityRegressionEndpointIds = [...new Set([...this.connectivityRegressionEndpointIds, ...n8.connectivityRegressionEndpointIds ?? []])]);\n const i8 = t4 \u0026\u0026 o10 === 0;\n this.cleanupBestEffortAccepted = e54.budgetLimited \u0026\u0026 i8, this.cleanupMutatedTraceIndices = i8 ? [...n8.mutatedTraceIndices ?? []] : [], this.removedViaPairCount = i8 ? Number(n8.viaPairCountRemoved ?? 0) : 0, this.removedViaCount = i8 ? Number(n8.viaCountRemoved ?? 0) : 0, this.simplifiedPathCount = i8 ? Number(n8.simplifiedPathCount ?? 0) : 0, this.normalizedSegmentCount = i8 ? Number(n8.normalizedSegmentCount ?? 0) : 0, this.cleanupClearanceShoveCount = i8 ? Number(n8.committedClearanceShoveCount ?? 0) : 0, this.relocatedViaCount = i8 ? Number(n8.relocatedViaCount ?? 0) : 0, this.unresolvedViaCount = Number(n8.unresolvedViaCount ?? 0), this.padClearanceRerouteCount = i8 ? Number(n8.padClearanceRerouteCount ?? 0) : 0, this.unresolvedPadClearanceCount = Number(n8.unresolvedPadClearanceCount ?? 0), this.initialPadClearanceViolationCount = Number(n8.initialPadClearanceViolationCount ?? 0), this.remainingPadClearanceViolationCount = Number(n8.remainingPadClearanceViolationCount ?? 0), this.initialPadClearanceViolationCountByClearance = { ...n8.initialPadClearanceViolationCountByClearance ?? {} }, this.remainingPadClearanceViolationCountByClearance = { ...n8.remainingPadClearanceViolationCountByClearance ?? {} }, this.rebuildObstacleIndex();\n }\n startTraceClearanceRepair() {\n this.phase = \"repair-trace-clearance\";\n const e54 = [...new Set([...this.getOwnedTraceIndices(), ...this.expansionPushedTraceIndices, ...this.cleanupMutatedTraceIndices])], t4 = new mte({ simpleRouteJson: this.inputProblem, traces: this.traces, traceIndices: e54 });\n t4.MAX_ITERATIONS = Math.min(t4.MAX_ITERATIONS, this.getRemainingChildStepBudget()), this.clearanceRepairIterationBudget = t4.MAX_ITERATIONS, this.activeSubSolver = t4;\n }\n stepActiveTraceClearanceRepairSolver() {\n const e54 = this.activeSubSolver;\n if (e54.step(), e54.solved || e54.failed) {\n if (e54.solved)\n return this.adoptClearanceRepairOutput(e54), this.activeSubSolver = null, void (this.phase = \"complete\");\n this.retainFailedSubSolver(e54), this.activeSubSolver = null, this.phase = \"complete\";\n }\n }\n adoptClearanceRepairOutput(e54) {\n const t4 = this.acceptConnectivityCheckpoint(e54.getOutput(), \"clearance-repair\");\n this.clearanceRepairCompleted = !e54.budgetLimited;\n const n8 = e54.stats;\n this.connectivityValidationError ??= n8.connectivityValidationError ?? null, this.connectivityValidationCount += Number(n8.connectivityValidationCount ?? 0);\n const o10 = Number(n8.connectivityRollbackCount ?? 0);\n o10 \u003e 0 \u0026\u0026 (this.connectivityRollbackCount += o10, this.connectivityRollbackPhases.includes(\"clearance-repair\") || this.connectivityRollbackPhases.push(\"clearance-repair\"), this.connectivityRegressionEndpointIds = [...new Set([...this.connectivityRegressionEndpointIds, ...n8.connectivityRegressionEndpointIds ?? []])]);\n const i8 = t4 \u0026\u0026 o10 === 0;\n this.clearanceRepairBestEffortAccepted = e54.budgetLimited \u0026\u0026 i8, this.repairedTraceClearanceSegmentCount = i8 ? Number(n8.repairedSegmentCount ?? 0) : 0, this.repairedPadNeckSegmentCount = i8 ? Number(n8.repairedPadNeckSegmentCount ?? 0) : 0, this.unresolvedTraceClearanceSegmentCount = Number(n8.unresolvedSegmentCount ?? 0), this.rebuildObstacleIndex();\n }\n stepActiveLayerSolver() {\n const e54 = this.activeSubSolver;\n if (e54.step(), e54.solved || e54.failed) {\n if (e54.solved) {\n const t4 = e54.getOutput();\n if (t4) {\n const e60 = !this.layerRouteReplacementCollides(t4, true) \u0026\u0026 this.layerRouteImprovesInterval(t4), n8 = e60 \u0026\u0026 this.layerRoutePreservesSameNetContacts(t4);\n if (n8) {\n if (this.activeSubSolver = null, this.pendingLayerOutput = t4, this.pendingLayerPushCount = 0, !this.layerRouteReplacementCollides(t4, false))\n return void this.applyLayerRoute(t4);\n if (this.startPendingLayerInflation())\n return;\n this.pendingLayerOutput = null;\n }\n e60 \u0026\u0026 !n8 \u0026\u0026 this.sameNetContactRejectionCount++;\n }\n }\n this.retainFailedSubSolver(e54), this.activeSubSolver = null, this.layerAttempt \u0026\u0026 this.layerAttempt.offsetCursor++, this.phase = \"try-layer-candidate\";\n }\n }\n layerRouteReplacementCollides(e54, t4) {\n const n8 = this.traces[this.traceIndex], o10 = this.layerAttempt;\n if (!n8 || !o10)\n return true;\n const i8 = this.getTraceConnectionNames(n8), r9 = t4 ? o10.softTraceIndices : undefined, s7 = { start: Math.max(0, o10.interval.startIndex - 1), end: Math.min(n8.route.length - 1, o10.interval.endIndex + 1) }, a9 = this.getFixedViasOutsideInterval(n8, o10.interval);\n for (let t10 = 0;t10 \u003c e54.route.length; t10++) {\n const n10 = e54.route[t10];\n if (n10?.route_type === \"via\") {\n if (this.obstacleIndex.collidesVia({ point: n10, layers: this.obstacleIndex.boardLayers, padDiameter: n10.via_diameter ?? 0.6, holeDiameter: n10.via_hole_diameter ?? this.obstacleIndex.defaultViaHoleDiameter, connectionNames: i8, ignoreTraceIndex: this.traceIndex, ignoreTraceIndices: r9, otherNewViaPoints: e54.route.slice(0, t10).filter((e60) =\u003e e60.route_type === \"via\").map((e60) =\u003e ({ x: e60.x, y: e60.y })), fixedVias: a9, ignoreRouteRange: s7, obstacleClearance: this.getDesiredPadClearance(e54.traceWidth), blockSameNetObstacles: true, sameNetObstacleClearance: 0 }))\n return true;\n continue;\n }\n const o11 = e54.route[t10 + 1];\n if (n10?.route_type === \"wire\" \u0026\u0026 o11?.route_type === \"wire\" \u0026\u0026 n10.layer === o11.layer \u0026\u0026 this.obstacleIndex.collides({ start: n10, end: o11, layer: n10.layer, width: Math.max(n10.width, o11.width), connectionNames: i8, ignoreTraceIndex: this.traceIndex, ignoreTraceIndices: r9, ignoreRouteRange: s7, obstacleClearance: this.getDesiredPadClearance(e54.traceWidth) }))\n return true;\n }\n return this.layerRouteBoundaryCollides(e54, t4);\n }\n getFixedViasOutsideInterval(e54, t4) {\n return e54.route.flatMap((e60, n8) =\u003e e60.route_type !== \"via\" || n8 \u003e= t4.startIndex \u0026\u0026 n8 \u003c= t4.endIndex ? [] : [{ point: { x: e60.x, y: e60.y }, padDiameter: e60.via_diameter ?? 0.6, holeDiameter: e60.via_hole_diameter ?? this.obstacleIndex.defaultViaHoleDiameter }]);\n }\n layerRouteBoundaryCollides(e54, t4) {\n const n8 = this.traces[this.traceIndex], o10 = this.layerAttempt, i8 = e54.route.find((e60) =\u003e e60.route_type === \"wire\");\n let r9;\n for (let t10 = e54.route.length - 1;t10 \u003e= 0; t10--) {\n const n10 = e54.route[t10];\n if (n10?.route_type === \"wire\") {\n r9 = n10;\n break;\n }\n }\n if (!i8 || !r9)\n return true;\n const s7 = [{ outside: n8.route[o10.interval.startIndex - 1], inside: i8 }, { outside: n8.route[o10.interval.endIndex + 1], inside: r9 }];\n for (const i9 of s7)\n if (bte(i9.outside) \u0026\u0026 i9.outside.layer === i9.inside.layer \u0026\u0026 this.obstacleIndex.collides({ start: i9.outside, end: i9.inside, layer: i9.inside.layer, width: Math.max(i9.outside.width, i9.inside.width), connectionNames: this.getTraceConnectionNames(n8), ignoreTraceIndex: this.traceIndex, ignoreTraceIndices: t4 ? o10.softTraceIndices : undefined, ignoreRouteRange: { start: Math.max(0, o10.interval.startIndex - 1), end: Math.min(n8.route.length - 1, o10.interval.endIndex + 1) }, obstacleClearance: this.getDesiredPadClearance(e54.traceWidth) }))\n return true;\n return false;\n }\n layerRouteImprovesInterval(e54) {\n const t4 = this.traces[this.traceIndex], n8 = this.layerAttempt.interval, o10 = this.getRouteQuality(t4.route.slice(n8.startIndex, n8.endIndex + 1)), i8 = this.getRouteQuality(e54.route);\n return i8.length \u003c= o10.length + 10 + L7 \u0026\u0026 i8.deficitArea \u003c= o10.deficitArea - Math.max(0.05, 0.1 * o10.deficitArea);\n }\n getRouteQuality(e54) {\n let t4 = 0, n8 = 0;\n for (let o10 = 0;o10 \u003c e54.length - 1; o10++) {\n const i8 = e54[o10], r9 = e54[o10 + 1];\n if (!bte(i8) || !bte(r9) || i8.layer !== r9.layer)\n continue;\n const s7 = z7(i8, r9), a9 = Math.min(i8.width, r9.width);\n t4 += s7, n8 += s7 * Math.max(0, this.nominalTraceWidth - a9);\n }\n return { length: t4, deficitArea: n8 };\n }\n getLayerInflationCorridor(e54) {\n const t4 = [];\n for (let n8 = 0;n8 \u003c e54.route.length; n8++) {\n const o10 = e54.route[n8];\n if (o10?.route_type === \"via\") {\n for (const e60 of this.obstacleIndex.boardLayers)\n t4.push({ start: o10, end: o10, layer: e60, width: o10.via_diameter ?? 0.6 });\n continue;\n }\n const i8 = e54.route[n8 + 1];\n o10?.route_type === \"wire\" \u0026\u0026 i8?.route_type === \"wire\" \u0026\u0026 o10.layer === i8.layer \u0026\u0026 t4.push({ start: o10, end: i8, layer: o10.layer, width: Math.max(o10.width, i8.width) });\n }\n return t4;\n }\n startPendingLayerInflation() {\n const e54 = this.pendingLayerOutput;\n if (!e54 || this.pendingLayerPushCount \u003e= 2)\n return false;\n const t4 = this.getLayerInflationCorridor(e54);\n return t4.length !== 0 \u0026\u0026 (this.pendingLayerPushCount++, this.attemptedInflationCount++, this.activeSubSolver = new wee({ simpleRouteJson: this.inputProblem, traces: this.traces, powerTraceIndex: this.traceIndex, nominalPowerWidth: e54.traceWidth, mutableTraceIndices: this.mutableBlockerTraceIndices, corridor: t4, maxRerouteLength: 10 }, this.connectionNameResolver), this.phase = \"try-trace-inflation\", true);\n }\n applyLayerRoute(e54) {\n const t4 = this.traces[this.traceIndex], n8 = this.layerAttempt.interval, o10 = this.createLayerRouteReplacement(e54);\n t4.route.splice(n8.startIndex, n8.endIndex - n8.startIndex + 1, ...o10), e54.viaCount \u003e 0 \u0026\u0026 this.layerReroutedTraceCount++, this.layerRerouteCountByTrace.set(this.traceIndex, (this.layerRerouteCountByTrace.get(this.traceIndex) ?? 0) + 1), this.reroutedSegmentCount++, this.insertedViaCount += e54.viaCount, e54.viaCount \u003e 0 \u0026\u0026 (this.neckedLayerSegmentCount += o10.filter((e60) =\u003e e60.route_type === \"wire\" \u0026\u0026 e60.width \u003c this.nominalTraceWidth - L7).length), this.routeSegmentIndex = n8.startIndex, this.currentIntervals = [], this.layerAttempt = null, this.pendingLayerOutput = null, this.pendingLayerPushCount = 0, this.phase = \"evaluate-segment\";\n }\n createLayerRouteReplacement(e54) {\n const t4 = this.traces[this.traceIndex], n8 = this.layerAttempt.interval, o10 = t4.route[n8.startIndex], i8 = t4.route[n8.endIndex], r9 = structuredClone(e54.route), s7 = r9.findIndex((e60) =\u003e e60.route_type === \"wire\");\n let a9 = -1;\n for (let e60 = r9.length - 1;e60 \u003e= 0; e60--)\n if (r9[e60]?.route_type === \"wire\") {\n a9 = e60;\n break;\n }\n return s7 \u003e= 0 \u0026\u0026 (r9[s7] = { ...o10, ...r9[s7] }), a9 \u003e= 0 \u0026\u0026 (r9[a9] = { ...i8, ...r9[a9] }), r9;\n }\n layerRoutePreservesSameNetContacts(e54) {\n const t4 = this.traces[this.traceIndex], n8 = this.layerAttempt.interval;\n return this.routeReplacementPreservesSameNetContacts(t4, n8, this.createLayerRouteReplacement(e54));\n }\n startTraceInflation(e54, t4) {\n const n8 = e54.route[t4], o10 = e54.route[t4 + 1];\n if (!bte(n8) || !bte(o10))\n return false;\n const i8 = Math.min(n8.width, o10.width), r9 = this.findBestPushableInflationWidth(e54, t4, i8);\n if (!r9)\n return false;\n const s7 = this.getLocalInflationCorridor(e54, t4, r9);\n if (s7.length === 0)\n return false;\n const a9 = [this.traceIndex, n8.x, n8.y, o10.x, o10.y].join(\":\"), c5 = this.inflationAttemptsBySegment.get(a9) ?? 0;\n return !(c5 \u003e= 2) \u0026\u0026 (this.inflationAttemptsBySegment.set(a9, c5 + 1), this.activeInflationKey = a9, this.activeInflationWidth = r9, this.attemptedInflationCount++, this.activeSubSolver = new wee({ simpleRouteJson: this.inputProblem, traces: this.traces, powerTraceIndex: this.traceIndex, nominalPowerWidth: r9, mutableTraceIndices: this.mutableBlockerTraceIndices, corridor: s7, maxRerouteLength: 10 }, this.connectionNameResolver), this.phase = \"try-trace-inflation\", true);\n }\n hasOnlyPushableTraceBlockers(e54, t4, n8) {\n const o10 = Math.max(0, t4 - 1), i8 = Math.min(e54.route.length - 2, t4 + 1), r9 = new Set;\n for (let t10 = o10;t10 \u003c= i8; t10++) {\n const s7 = e54.route[t10], a9 = e54.route[t10 + 1];\n if (!bte(s7) || !bte(a9) || s7.layer !== a9.layer)\n continue;\n const c5 = { start: s7, end: a9, layer: s7.layer, width: n8, connectionNames: this.getTraceConnectionNames(e54), ignoreTraceIndex: this.traceIndex, ignoreRouteRange: { start: o10, end: i8 + 1 }, obstacleClearance: this.getDesiredPadClearance(n8) }, l5 = this.obstacleIndex.findCollisions(c5);\n if (l5.length === 0 \u0026\u0026 this.obstacleIndex.collides(c5))\n return false;\n for (const e60 of l5) {\n if (e60.kind !== \"trace\" || e60.traceIndex === undefined)\n return false;\n const t11 = this.traces[e60.traceIndex];\n if (!t11)\n return false;\n const o11 = this.findConnectionForTrace(t11);\n if (!o11 || (o11.nominalTraceWidth ?? o11.width ?? this.inputProblem.nominalTraceWidth ?? this.inputProblem.minTraceWidth) \u003e= n8 - L7)\n return false;\n r9.add(e60.traceIndex);\n }\n }\n return r9.size \u003e 0 \u0026\u0026 r9.size \u003c= 2;\n }\n findBestPushableInflationWidth(e54, t4, n8) {\n const o10 = this.nominalTraceWidth \u003e= 0.5 ? 0.05 : 0.0125;\n for (let i8 = this.nominalTraceWidth;i8 \u003e n8 + L7; i8 -= o10) {\n const n10 = Number(i8.toFixed(6));\n if (this.hasOnlyPushableTraceBlockers(e54, t4, n10))\n return n10;\n }\n return null;\n }\n stepActiveInflationSolver() {\n const e54 = this.activeSubSolver;\n if (e54.step(), e54.solved || e54.failed) {\n if (e54.solved) {\n const t4 = e54.getOutput(), n8 = t4 \u0026\u0026 this.sameNetContactsArePreserved(this.traces[t4.pushedTraceIndex].route, t4.traces[t4.pushedTraceIndex].route, this.getTraceConnectionNames(this.traces[t4.pushedTraceIndex]), t4.pushedTraceIndex);\n if (t4 \u0026\u0026 n8) {\n if (this.traces = t4.traces, this.pushedTraceCount++, this.expansionPushedTraceIndices.add(t4.pushedTraceIndex), t4.strategy === \"elastic\" \u0026\u0026 this.elasticPushedTraceCount++, this.activeSubSolver = null, this.activeInflationKey = null, this.activeInflationWidth = null, this.rebuildObstacleIndex(), this.pendingLayerOutput) {\n if (!this.layerRouteReplacementCollides(this.pendingLayerOutput, false) \u0026\u0026 this.layerRoutePreservesSameNetContacts(this.pendingLayerOutput))\n return void this.applyLayerRoute(this.pendingLayerOutput);\n if (this.startPendingLayerInflation())\n return;\n return this.pendingLayerOutput = null, this.pendingLayerPushCount = 0, this.layerAttempt \u0026\u0026 this.layerAttempt.offsetCursor++, void (this.phase = \"try-layer-candidate\");\n }\n return void (this.phase = \"evaluate-segment\");\n }\n t4 \u0026\u0026 !n8 \u0026\u0026 this.sameNetContactRejectionCount++;\n }\n if (this.retainFailedSubSolver(e54), this.activeInflationKey \u0026\u0026 this.inflationAttemptsBySegment.set(this.activeInflationKey, 2), this.activeInflationKey = null, this.activeInflationWidth = null, this.activeSubSolver = null, this.pendingLayerOutput)\n return this.pendingLayerOutput = null, this.pendingLayerPushCount = 0, this.layerAttempt \u0026\u0026 this.layerAttempt.offsetCursor++, void (this.phase = \"try-layer-candidate\");\n this.phase = \"evaluate-segment\";\n }\n }\n getLocalInflationCorridor(e54, t4, n8) {\n const o10 = e54.route[t4], i8 = e54.route[t4 + 1];\n if (!bte(o10) || !bte(i8) || o10.layer !== i8.layer)\n return [];\n const r9 = j7(4 * n8, 2, 4), s7 = r9 / 2;\n let a9 = t4, c5 = 0;\n for (;a9 \u003e 0; ) {\n const t10 = e54.route[a9 - 1], n10 = e54.route[a9];\n if (!bte(t10) || !bte(n10) || t10.layer !== n10.layer)\n break;\n const o11 = z7(t10, n10);\n if (c5 + o11 \u003e s7 + L7)\n break;\n c5 += o11, a9--;\n }\n let l5 = t4 + 1, h5 = 0;\n for (;l5 \u003c e54.route.length - 1; ) {\n const t10 = e54.route[l5], n10 = e54.route[l5 + 1];\n if (!bte(t10) || !bte(n10) || t10.layer !== n10.layer)\n break;\n const o11 = z7(t10, n10);\n if (h5 + o11 \u003e s7 + L7)\n break;\n h5 += o11, l5++;\n }\n let d9 = r9 - c5 - h5;\n for (;d9 \u003e L7 \u0026\u0026 a9 \u003e 0; ) {\n const t10 = e54.route[a9 - 1], n10 = e54.route[a9];\n if (!bte(t10) || !bte(n10) || t10.layer !== n10.layer)\n break;\n const o11 = z7(t10, n10);\n if (o11 \u003e d9 + L7)\n break;\n d9 -= o11, a9--;\n }\n for (;d9 \u003e L7 \u0026\u0026 l5 \u003c e54.route.length - 1; ) {\n const t10 = e54.route[l5], n10 = e54.route[l5 + 1];\n if (!bte(t10) || !bte(n10) || t10.layer !== n10.layer)\n break;\n const o11 = z7(t10, n10);\n if (o11 \u003e d9 + L7)\n break;\n d9 -= o11, l5++;\n }\n const u9 = [];\n for (let t10 = a9;t10 \u003c l5; t10++) {\n const o11 = e54.route[t10], i9 = e54.route[t10 + 1];\n bte(o11) \u0026\u0026 bte(i9) \u0026\u0026 o11.layer === i9.layer \u0026\u0026 u9.push({ start: o11, end: i9, layer: o11.layer, width: n8 });\n }\n return u9;\n }\n applyGridRoute(e54) {\n const t4 = this.traces[this.traceIndex], n8 = this.currentIntervals[this.intervalCursor], o10 = this.createGridRouteReplacement(e54);\n t4.route.splice(n8.startIndex, n8.endIndex - n8.startIndex + 1, ...o10), this.reroutedSegmentCount++, this.routeSegmentIndex = n8.startIndex + o10.length - 1, this.currentIntervals = [], this.phase = \"evaluate-segment\";\n }\n createGridRouteReplacement(e54) {\n const t4 = this.traces[this.traceIndex], n8 = this.currentIntervals[this.intervalCursor], o10 = t4.route[n8.startIndex], i8 = t4.route[n8.endIndex], r9 = e54.points.map((t10) =\u003e ({ route_type: \"wire\", x: t10.x, y: t10.y, width: e54.traceWidth, layer: o10.layer }));\n return r9[0].width = Math.max(o10.width, e54.traceWidth), r9[r9.length - 1].width = Math.max(i8.width, e54.traceWidth), r9;\n }\n gridRoutePreservesSameNetContacts(e54) {\n const t4 = this.traces[this.traceIndex], n8 = this.currentIntervals[this.intervalCursor];\n return this.routeReplacementPreservesSameNetContacts(t4, n8, this.createGridRouteReplacement(e54));\n }\n routeReplacementPreservesSameNetContacts(e54, t4, n8) {\n const o10 = this.getTraceConnectionNames(e54), i8 = this.getSameNetContactIds(e54.route.slice(t4.startIndex, t4.endIndex + 1), o10, this.traceIndex), r9 = new Set([...this.getSameNetContactIds(e54.route.slice(0, t4.startIndex + 1), o10, this.traceIndex), ...this.getSameNetContactIds(e54.route.slice(t4.endIndex), o10, this.traceIndex)]), s7 = new Set([...i8].filter((e60) =\u003e !r9.has(e60)));\n if (s7.size === 0)\n return true;\n const a9 = this.getSameNetContactIds(n8, o10, this.traceIndex);\n return [...s7].every((e60) =\u003e a9.has(e60));\n }\n sameNetContactsArePreserved(e54, t4, n8, o10) {\n const i8 = this.getSameNetContactIds(e54, n8, o10);\n if (i8.size === 0)\n return true;\n const r9 = this.getSameNetContactIds(t4, n8, o10);\n return [...i8].every((e60) =\u003e r9.has(e60));\n }\n getSameNetContactIds(e54, t4, n8) {\n const o10 = new Set;\n for (let i8 = 0;i8 \u003c e54.length; i8++) {\n const r9 = e54[i8];\n if (r9?.route_type === \"via\") {\n for (const e60 of this.getViaLayers(r9))\n for (const i9 of this.obstacleIndex.getSameNetCopperContactIds({ start: r9, end: r9, layer: e60, width: r9.via_diameter ?? 0.6, connectionNames: t4, ignoreTraceIndex: n8 }))\n o10.add(i9);\n continue;\n }\n const s7 = e54[i8 + 1];\n if (r9?.route_type === \"wire\" \u0026\u0026 s7?.route_type === \"wire\" \u0026\u0026 r9.layer === s7.layer)\n for (const e60 of this.obstacleIndex.getSameNetCopperContactIds({ start: r9, end: s7, layer: r9.layer, width: Math.min(r9.width, s7.width), connectionNames: t4, ignoreTraceIndex: n8 }))\n o10.add(e60);\n }\n return o10;\n }\n getViaLayers(e54) {\n const t4 = this.obstacleIndex.boardLayers.indexOf(e54.from_layer), n8 = this.obstacleIndex.boardLayers.indexOf(e54.to_layer);\n return t4 \u003c 0 || n8 \u003c 0 ? this.obstacleIndex.boardLayers : this.obstacleIndex.boardLayers.slice(Math.min(t4, n8), Math.max(t4, n8) + 1);\n }\n gridRouteReplacementCollides(e54) {\n const t4 = this.traces[this.traceIndex], n8 = this.currentIntervals[this.intervalCursor], o10 = t4.route[n8.startIndex], i8 = t4.route[n8.endIndex], r9 = this.getTraceConnectionNames(t4);\n for (let s7 = 0;s7 \u003c e54.points.length - 1; s7++) {\n const a9 = Math.max(e54.traceWidth, s7 === 0 ? o10.width : 0, s7 === e54.points.length - 2 ? i8.width : 0);\n if (this.obstacleIndex.collides({ start: e54.points[s7], end: e54.points[s7 + 1], layer: o10.layer, width: a9, connectionNames: r9, ignoreTraceIndex: this.traceIndex, ignoreRouteRange: { start: Math.max(0, n8.startIndex - 1), end: Math.min(t4.route.length - 1, n8.endIndex + 1) }, obstacleClearance: this.getDesiredPadClearance(a9) }))\n return true;\n }\n return false;\n }\n gridRouteBoundaryCollides(e54) {\n const t4 = this.traces[this.traceIndex], n8 = this.currentIntervals[this.intervalCursor], o10 = this.getTraceConnectionNames(t4), i8 = [{ startIndex: n8.startIndex - 1, endIndex: n8.startIndex }, { startIndex: n8.endIndex, endIndex: n8.endIndex + 1 }];\n for (const n10 of i8) {\n const i9 = t4.route[n10.startIndex], r9 = t4.route[n10.endIndex];\n if (bte(i9) \u0026\u0026 bte(r9) \u0026\u0026 i9.layer === r9.layer \u0026\u0026 this.obstacleIndex.collides({ start: i9, end: r9, layer: i9.layer, width: Math.max(i9.width, r9.width, e54.traceWidth), connectionNames: o10, ignoreTraceIndex: this.traceIndex, ignoreRouteRange: { start: n10.startIndex, end: n10.endIndex }, obstacleClearance: this.getDesiredPadClearance(Math.max(i9.width, r9.width, e54.traceWidth)) }))\n return true;\n }\n return false;\n }\n canExpandSegmentAndEndpoints(e54, t4, n8, o10 = this.nominalTraceWidth) {\n const i8 = Math.max(0, t4 - 1), r9 = Math.min(e54.route.length - 2, t4 + 1);\n for (let s7 = i8;s7 \u003c= r9; s7++) {\n const a9 = e54.route[s7], c5 = e54.route[s7 + 1];\n if (!bte(a9) || !bte(c5) || a9.layer !== c5.layer)\n continue;\n const l5 = s7 \u003c= t4 + 1 \u0026\u0026 s7 + 1 \u003e= t4, h5 = Math.max(a9.width, c5.width, l5 ? o10 : 0);\n if (this.obstacleIndex.collides({ start: a9, end: c5, layer: a9.layer, width: h5, connectionNames: n8, ignoreTraceIndex: this.traceIndex, ignoreRouteRange: { start: i8, end: r9 + 1 }, obstacleClearance: this.getDesiredPadClearance(h5) }))\n return false;\n }\n return true;\n }\n findMaximumSafeInPlaceWidth(e54, t4, n8) {\n const o10 = e54.route[t4], i8 = e54.route[t4 + 1];\n if (!bte(o10) || !bte(i8))\n return 0;\n const r9 = Math.min(o10.width, i8.width);\n if (this.probeInPlaceWidth(e54, t4, n8, this.nominalTraceWidth))\n return this.nominalTraceWidth;\n let s7 = r9, a9 = this.nominalTraceWidth;\n for (let o11 = 0;o11 \u003c 7; o11++) {\n const o12 = (s7 + a9) / 2;\n if (o12 \u003c= s7 + L7)\n break;\n this.probeInPlaceWidth(e54, t4, n8, o12) ? s7 = o12 : a9 = o12;\n }\n const c5 = this.nominalTraceWidth \u003e= 0.5 ? 0.025 : 0.0125, l5 = Math.max(r9, Math.floor((s7 + L7) / c5) * c5);\n return l5 \u003e r9 + L7 \u0026\u0026 this.probeInPlaceWidth(e54, t4, n8, l5) ? l5 : r9;\n }\n probeInPlaceWidth(e54, t4, n8, o10) {\n return this.inPlaceWidthProbeCount++, this.canExpandSegmentAndEndpoints(e54, t4, n8, o10);\n }\n maximizeGridRouteWidth(e54) {\n if (e54.traceWidth \u003e= this.nominalTraceWidth - L7)\n return e54;\n let t4 = e54.traceWidth, n8 = this.nominalTraceWidth;\n for (let o11 = 0;o11 \u003c 7; o11++) {\n const o12 = (t4 + n8) / 2, i9 = { ...e54, traceWidth: o12 };\n this.gridRouteReplacementCollides(i9) || this.gridRouteBoundaryCollides(i9) ? n8 = o12 : t4 = o12;\n }\n const o10 = this.nominalTraceWidth \u003e= 0.5 ? 0.025 : 0.0125, i8 = Math.max(e54.traceWidth, Math.floor((t4 + L7) / o10) * o10);\n if (i8 \u003e e54.traceWidth + L7) {\n const t10 = { ...e54, traceWidth: i8 };\n if (!this.gridRouteReplacementCollides(t10) \u0026\u0026 !this.gridRouteBoundaryCollides(t10))\n return this.pathWidthUpgradeCount++, t10;\n }\n return e54;\n }\n getExponentialIntervalCandidates(e54, t4, n8) {\n const o10 = this.getExponentialIndices(e54, t4, -1, n8, 5), i8 = this.getExponentialIndices(e54, t4, 1, n8, 10).filter((e60) =\u003e e60 \u003e t4), r9 = [];\n for (const t10 of o10)\n for (const n10 of i8) {\n const o11 = this.getRouteIntervalLength(e54, t10, n10);\n o11 \u003e 10.000001 || r9.push({ startIndex: t10, endIndex: n10, routeLength: o11 });\n }\n return r9.sort((e60, t10) =\u003e e60.routeLength - t10.routeLength).filter((e60, t10, n10) =\u003e n10.findIndex((t11) =\u003e t11.startIndex === e60.startIndex \u0026\u0026 t11.endIndex === e60.endIndex) === t10).slice(0, 10).map(({ startIndex: e60, endIndex: t10 }) =\u003e ({ startIndex: e60, endIndex: t10 }));\n }\n getExponentialIndices(e54, t4, n8, o10, i8) {\n const r9 = [t4];\n let s7 = 0, a9 = Math.max(o10, 0.3), c5 = t4, l5 = t4;\n for (;; ) {\n const t10 = c5 + n8;\n if (t10 \u003c 0 || t10 \u003e= e54.route.length)\n break;\n const o11 = e54.route[c5], h5 = e54.route[t10];\n if (!bte(o11) || !bte(h5) || o11.layer !== h5.layer)\n break;\n const d9 = z7(o11, h5);\n if (s7 + d9 \u003e i8 + L7)\n break;\n s7 += d9, c5 = t10, l5 = t10, s7 + L7 \u003e= a9 \u0026\u0026 (r9.push(t10), a9 *= 2);\n }\n return r9.includes(l5) || r9.push(l5), r9;\n }\n getRouteIntervalLength(e54, t4, n8) {\n let o10 = 0;\n for (let i8 = t4;i8 \u003c n8; i8++) {\n const t10 = e54.route[i8], n10 = e54.route[i8 + 1];\n if (!bte(t10) || !bte(n10) || t10.layer !== n10.layer)\n return Number.POSITIVE_INFINITY;\n o10 += z7(t10, n10);\n }\n return o10;\n }\n getCandidateWidths(e54) {\n const t4 = this.inputProblem.minTraceWidth;\n return yte([e54, 0.875 * e54, 0.75 * e54, 0.625 * e54, 0.5 * e54, 0.375 * e54, 0.25 * e54, t4]).filter((e60) =\u003e e60 \u003e= t4 - L7);\n }\n getGridResolutions(e54) {\n return yte([Math.max(0.1, Math.min(0.5, e54 / 2)), Math.max(0.1, Math.min(0.25, e54 / 3))]);\n }\n resolveNominalTraceWidth(e54) {\n const t4 = this.findConnectionForTrace(e54);\n return Math.max(t4?.nominalTraceWidth ?? t4?.width ?? this.inputProblem.nominalTraceWidth ?? this.inputProblem.minTraceWidth, this.inputProblem.minTraceWidth);\n }\n getDesiredPadClearance(e54 = this.nominalTraceWidth) {\n const t4 = Math.max(this.inputProblem.defaultObstacleMargin ?? 0, this.inputProblem.minTraceToPadEdgeClearance ?? 0, 0.1);\n return e54 \u003c 0.499999 || this.phase !== \"cleanup\" ? t4 : Math.max(t4, this.options.powerTraceToPadClearance ?? e54 / 2);\n }\n findConnectionForTrace(e54) {\n const t4 = this.connectionByTraceId.get(e54.pcb_trace_id);\n if (t4 !== undefined)\n return t4 ?? undefined;\n const n8 = this.getTraceConnectionNames(e54), o10 = this.inputProblem.connections.find((e60) =\u003e this.connectionMatchesTrace(e60, n8)) ?? null;\n return this.connectionByTraceId.set(e54.pcb_trace_id, o10), o10 ?? undefined;\n }\n getOwnedTraceIndices() {\n return [...this.selectedOwnedTraceIndices];\n }\n connectionMatchesTrace(e54, t4) {\n return [e54.name, e54.source_trace_id, e54.rootConnectionName, e54.netConnectionName, ...e54.mergedConnectionNames ?? []].filter((e60) =\u003e Boolean(e60)).some((e60) =\u003e t4.includes(e60));\n }\n getTraceConnectionNames(e54) {\n return [e54.connection_name, e54.source_trace_id, e54.rootConnectionName, ...e54.mergedConnectionNames ?? []].filter((e60) =\u003e Boolean(e60));\n }\n traceMeetsNominalWidth(e54, t4) {\n return e54.route.every((e60) =\u003e e60.route_type !== \"wire\" || e60.width \u003e= t4 - L7);\n }\n findNextUnderWidthSegment(e54, t4, n8) {\n for (let o10 = t4;o10 \u003c e54.route.length - 1; o10++) {\n const t10 = e54.route[o10], i8 = e54.route[o10 + 1];\n if (bte(t10) \u0026\u0026 bte(i8) \u0026\u0026 t10.layer === i8.layer \u0026\u0026 (t10.width \u003c n8 - L7 || i8.width \u003c n8 - L7))\n return o10;\n }\n return -1;\n }\n getMutatedImmutableTraceIds(e54) {\n return this.immutableTraceIndices.flatMap((t4) =\u003e {\n const n8 = e54[t4];\n return JSON.stringify(n8) === this.initialImmutableTraceSignatures.get(t4) ? [] : [n8?.pcb_trace_id ?? this.traces[t4]?.pcb_trace_id ?? String(t4)];\n });\n }\n getImmutableViaViolationSignatures(e54) {\n const t4 = new Set;\n if (this.immutableTraceIndices.length === 0)\n return t4;\n const n8 = new D7(this.inputProblem, e54), o10 = new Cee(this.inputProblem, e54, undefined, [], n8);\n for (const n10 of this.immutableTraceIndices) {\n const i8 = e54[n10];\n if (!i8)\n continue;\n const r9 = [i8.pcb_trace_id, i8.connection_name, i8.source_trace_id, i8.rootConnectionName, ...i8.mergedConnectionNames ?? [], ...i8.connectsTo ?? []].filter((e60) =\u003e Boolean(e60));\n for (let e60 = 0;e60 \u003c i8.route.length; e60++) {\n const s7 = i8.route[e60];\n if (s7?.route_type !== \"via\")\n continue;\n const a9 = `${i8.pcb_trace_id}:${e60}`, c5 = o10.getViaViolationSignatures({ point: s7, layers: o10.boardLayers, padDiameter: s7.via_diameter ?? this.inputProblem.min_via_pad_diameter ?? this.inputProblem.minViaPadDiameter ?? this.inputProblem.minViaDiameter ?? 0.6, holeDiameter: s7.via_hole_diameter ?? o10.defaultViaHoleDiameter, connectionNames: r9, ignoreTraceIndex: n10, ignoreRouteRange: { start: e60, end: e60 }, blockSameNetObstacles: true, sameNetObstacleClearance: 0 });\n for (const e61 of c5)\n t4.add(`${a9}|${e61}`);\n }\n }\n return t4;\n }\n countViolatingImmutableVias(e54) {\n return new Set([...e54].map((e60) =\u003e e60.split(\"|\")[0])).size;\n }\n acceptConnectivityCheckpoint(e54, t4) {\n this.connectivityValidationCount++;\n let n8 = false, o10 = false;\n try {\n const t10 = this.connectivityInvariant.validate(e54), i8 = this.getMutatedImmutableTraceIds(e54), r9 = this.getImmutableViaViolationSignatures(e54), s7 = [...r9].filter((e60) =\u003e !this.lastSafeImmutableViaViolationSignatures.has(e60)), a9 = s7.length \u003e 0;\n if (n8 = !t10.safe, o10 = i8.length \u003e 0 || a9, this.connectivityValidationError ??= t10.validationError ?? null, !n8 \u0026\u0026 !o10)\n return this.traces = structuredClone(e54), this.lastConnectivitySafeTraces = structuredClone(e54), this.remainingImmutableViaViolationCount = this.countViolatingImmutableVias(r9), this.remainingImmutableViaViolationPairCount = r9.size, this.lastSafeImmutableViaViolationSignatures = r9, this.connectivityInvariant = new ote(this.inputProblem, this.lastConnectivitySafeTraces), true;\n this.immutableTraceMutationIds = [...new Set([...this.immutableTraceMutationIds, ...i8])], a9 \u0026\u0026 (this.immutableViaViolationRollbackCount++, this.attemptedImmutableViaViolationCount = this.countViolatingImmutableVias(r9), this.attemptedImmutableViaViolationPairCount = r9.size, this.immutableViaViolationRegressionIds = [...new Set([...this.immutableViaViolationRegressionIds, ...s7])]), this.connectivityRegressionEndpointIds = [...new Set([...this.connectivityRegressionEndpointIds, ...t10.regressions.flatMap((e60) =\u003e e60.baselineEndpointLabels)])];\n } catch (e60) {\n n8 = true, this.connectivityValidationError = e60 instanceof Error ? e60.message : String(e60);\n }\n return n8 \u0026\u0026 (this.connectivityRollbackCount++, this.connectivityRollbackPhases.includes(t4) || this.connectivityRollbackPhases.push(t4)), o10 \u0026\u0026 (this.immutableSafetyRollbackCount++, this.immutableSafetyRollbackPhases.includes(t4) || this.immutableSafetyRollbackPhases.push(t4)), t4 === \"expansion\" ? n8 ? this.rollbackConnectivityRegressedExpansion() : this.rollbackImmutableUnsafeExpansion() : this.restoreLastConnectivitySafeTraces(), this.remainingImmutableViaViolationCount = this.countViolatingImmutableVias(this.lastSafeImmutableViaViolationSignatures), this.remainingImmutableViaViolationPairCount = this.lastSafeImmutableViaViolationSignatures.size, false;\n }\n rebuildObstacleIndex() {\n this.obstacleIndex = new Cee(this.inputProblem, this.traces, this.traceIndex, [], this.connectionNameResolver);\n }\n retainFailedSubSolver(e54) {\n this.failedSubSolverCount++, this.failedSubSolvers ??= [], this.failedSubSolvers.length \u003c 16 ? this.failedSubSolvers.push(e54) : this.failedSubSolvers[15] = e54;\n }\n tryFinalAcceptance() {\n this.finalAcceptanceUsed = true;\n let e54 = false;\n this.activeSubSolver instanceof dte ? (this.activeSubSolver.tryFinalAcceptance(), this.adoptCleanupOutput(this.activeSubSolver), e54 = true) : this.activeSubSolver instanceof mte \u0026\u0026 (this.activeSubSolver.tryFinalAcceptance(), this.adoptClearanceRepairOutput(this.activeSubSolver), e54 = true), e54 || this.phase === \"cleanup\" || this.phase === \"repair-trace-clearance\" || this.phase === \"complete\" || this.discardInFlightExpansion(), this.activeSubSolver = null, this.pendingLayerOutput = null, this.pendingLayerPushCount = 0, this.activeInflationKey = null, this.activeInflationWidth = null, this.layerAttempt = null, this.acceptConnectivityCheckpoint(this.traces, \"final\"), this.traceIndex = this.traces.length, this.phase = \"complete\", this.rebuildObstacleIndex(), this.progress = 1, this.solved = true, this.stats = this.createStats();\n }\n createStats() {\n return this.statsMaxIterations = this.MAX_ITERATIONS, { phase: this.phase, pass: this.passIndex + 1, completedPassCount: this.completedPassCount, lastNormalizedWidthDeficitGain: this.lastNormalizedWidthDeficitGain, normalizedWidthDeficitGainByPass: [...this.normalizedWidthDeficitGainByPass], plateauReached: this.plateauReached, traceIndex: this.traceIndex, traceCount: this.traces.length, selectedTraceCount: this.traceOrder.length, routeSegmentIndex: this.routeSegmentIndex, nominalTraceWidth: this.nominalTraceWidth, intervalCursor: this.intervalCursor, intervalCount: this.currentIntervals.length, candidateWidth: this.candidateWidths[this.widthCursor], gridSize: this.gridResolutions[this.resolutionCursor], gridOffsetVariant: this.offsetCursor, keptTraceCount: this.keptTraceCount, recreatedTraceCount: this.recreatedTraceCount, expandedSegmentCount: this.expandedSegmentCount, intermediateExpandedSegmentCount: this.intermediateExpandedSegmentCount, pathWidthUpgradeCount: this.pathWidthUpgradeCount, inPlaceWidthProbeCount: this.inPlaceWidthProbeCount, reroutedSegmentCount: this.reroutedSegmentCount, unresolvedSegmentCount: this.unresolvedSegmentCount, attemptedGridCount: this.attemptedGridCount, attemptedLayerGridCount: this.attemptedLayerGridCount, attemptedInflationCount: this.attemptedInflationCount, activeInflationWidth: this.activeInflationWidth, pushedTraceCount: this.pushedTraceCount, elasticPushedTraceCount: this.elasticPushedTraceCount, layerReroutedTraceCount: this.layerReroutedTraceCount, insertedViaCount: this.insertedViaCount, neckedLayerSegmentCount: this.neckedLayerSegmentCount, removedViaPairCount: this.removedViaPairCount, removedViaCount: this.removedViaCount, simplifiedPathCount: this.simplifiedPathCount, normalizedSegmentCount: this.normalizedSegmentCount, cleanupClearanceShoveCount: this.cleanupClearanceShoveCount, relocatedViaCount: this.relocatedViaCount, unresolvedViaCount: this.unresolvedViaCount, initialImmutableViaViolationCount: this.initialImmutableViaViolationCount, remainingImmutableViaViolationCount: this.remainingImmutableViaViolationCount, initialImmutableViaViolationPairCount: this.initialImmutableViaViolationPairCount, remainingImmutableViaViolationPairCount: this.remainingImmutableViaViolationPairCount, skippedImmutableViaRepairCount: this.remainingImmutableViaViolationCount, immutableViaViolationRollbackCount: this.immutableViaViolationRollbackCount, attemptedImmutableViaViolationCount: this.attemptedImmutableViaViolationCount, attemptedImmutableViaViolationPairCount: this.attemptedImmutableViaViolationPairCount, immutableViaViolationRegressionIds: [...this.immutableViaViolationRegressionIds], immutableTraceMutationIds: [...this.immutableTraceMutationIds], padClearanceRerouteCount: this.padClearanceRerouteCount, unresolvedPadClearanceCount: this.unresolvedPadClearanceCount, repairedTraceClearanceSegmentCount: this.repairedTraceClearanceSegmentCount, repairedPadNeckSegmentCount: this.repairedPadNeckSegmentCount, unresolvedTraceClearanceSegmentCount: this.unresolvedTraceClearanceSegmentCount, sameNetContactRejectionCount: this.sameNetContactRejectionCount, connectivityValidationCount: this.connectivityValidationCount, connectivityRollbackCount: this.connectivityRollbackCount, connectivityRollbackPhases: [...this.connectivityRollbackPhases], immutableSafetyRollbackCount: this.immutableSafetyRollbackCount, immutableSafetyRollbackPhases: [...this.immutableSafetyRollbackPhases], connectivityRegressionEndpointIds: [...this.connectivityRegressionEndpointIds], connectivityValidationError: this.connectivityValidationError, connectivityRollbackMutationStats: this.connectivityRollbackMutationStats === null ? null : { ...this.connectivityRollbackMutationStats }, immutableSafetyRollbackMutationStats: this.immutableSafetyRollbackMutationStats === null ? null : { ...this.immutableSafetyRollbackMutationStats }, expansionPushedTraceIndices: [...this.expansionPushedTraceIndices], cleanupMutatedTraceIndices: [...this.cleanupMutatedTraceIndices], discardedExpansionMutationStats: this.discardedExpansionMutationStats === null ? null : { ...this.discardedExpansionMutationStats }, initialPadClearanceViolationCount: this.initialPadClearanceViolationCount, remainingPadClearanceViolationCount: this.remainingPadClearanceViolationCount, initialPadClearanceViolationCountByClearance: { ...this.initialPadClearanceViolationCountByClearance }, remainingPadClearanceViolationCountByClearance: { ...this.remainingPadClearanceViolationCountByClearance }, budgetLimitedExpansion: this.budgetLimitedExpansion, finalAcceptanceUsed: this.finalAcceptanceUsed, cleanupCompleted: this.cleanupCompleted, clearanceRepairCompleted: this.clearanceRepairCompleted, cleanupBestEffortAccepted: this.cleanupBestEffortAccepted, clearanceRepairBestEffortAccepted: this.clearanceRepairBestEffortAccepted, cleanupStatus: this.connectivityRollbackPhases.includes(\"cleanup\") ? \"connectivity_rollback\" : this.immutableSafetyRollbackPhases.includes(\"cleanup\") ? \"immutable_safety_rollback\" : this.cleanupBestEffortAccepted ? \"budget_limited\" : this.cleanupCompleted ? \"completed\" : this.phase === \"cleanup\" ? \"in_progress\" : \"not_started\", clearanceRepairStatus: this.connectivityRollbackPhases.includes(\"clearance-repair\") ? \"connectivity_rollback\" : this.immutableSafetyRollbackPhases.includes(\"clearance-repair\") ? \"immutable_safety_rollback\" : this.clearanceRepairBestEffortAccepted ? \"budget_limited\" : this.clearanceRepairCompleted ? \"completed\" : this.phase === \"repair-trace-clearance\" ? \"in_progress\" : \"not_started\", cleanupIterationBudget: this.cleanupIterationBudget, clearanceRepairIterationBudget: this.clearanceRepairIterationBudget, completionReason: this.phase === \"complete\" || this.solved ? this.connectivityRollbackCount \u003e 0 ? \"connectivity_rollback\" : this.immutableSafetyRollbackCount \u003e 0 ? \"immutable_safety_rollback\" : this.connectivityValidationError ? \"connectivity_validation_unavailable\" : this.finalAcceptanceUsed ? \"total_iteration_budget\" : this.budgetLimitedExpansion ? \"expansion_budget\" : this.cleanupBestEffortAccepted ? \"cleanup_budget\" : this.clearanceRepairBestEffortAccepted ? \"clearance_repair_budget\" : this.remainingImmutableViaViolationCount \u003e 0 ? \"immutable_via_violations_preserved\" : \"completed\" : null, resultStatus: this.finalAcceptanceUsed || this.budgetLimitedExpansion || this.cleanupBestEffortAccepted || this.clearanceRepairBestEffortAccepted || this.connectivityRollbackCount \u003e 0 || this.immutableSafetyRollbackCount \u003e 0 || this.connectivityValidationError !== null || this.remainingImmutableViaViolationCount \u003e 0 ? \"best_effort\" : \"complete\", failedSubSolverCount: this.failedSubSolverCount, retainedFailedSubSolverCount: this.failedSubSolvers?.length ?? 0, expansionIterationBudget: this.getExpansionIterationBudget(), finalizationIterationReserve: this.getFinalizationIterationReserve(), spatialIndexRectCount: this.obstacleIndex.items.length };\n }\n computeProgress() {\n return this.solved || this.phase === \"complete\" ? 1 : this.budgetLimitedExpansion ? 0.99 : this.traceOrder.length === 0 ? 1 : Math.min(0.99, (this.passIndex + Math.max(0, this.traceOrderCursor) / this.traceOrder.length) / this.maxPassCount);\n }\n getConstructorParams() {\n return [this.inputProblem, this.options];\n }\n getOutput() {\n return structuredClone(this.lastConnectivitySafeTraces);\n }\n visualize() {\n const e54 = [], t4 = [];\n for (let n8 = 0;n8 \u003c this.traces.length; n8++) {\n const o10 = this.traces[n8], i8 = this.resolveNominalTraceWidth(o10);\n for (const e60 of o10.route)\n e60.route_type === \"via\" \u0026\u0026 t4.push({ center: e60, radius: (e60.via_diameter ?? 0.6) / 2, fill: \"#d4a017\", stroke: \"#7a5700\" });\n for (let t10 = 0;t10 \u003c o10.route.length - 1; t10++) {\n const r9 = o10.route[t10], s7 = o10.route[t10 + 1];\n if (!bte(r9) || !bte(s7) || r9.layer !== s7.layer)\n continue;\n const a9 = n8 === this.traceIndex \u0026\u0026 t10 === this.routeSegmentIndex, c5 = r9.width \u003e= i8 - L7 \u0026\u0026 s7.width \u003e= i8 - L7, l5 = r9.layer === \"bottom\";\n e54.push({ points: [r9, s7], strokeColor: a9 ? \"#ff8c00\" : c5 ? l5 ? \"#2468c7\" : \"#169c45\" : l5 ? \"#8b4bb8\" : \"#cc3344\", strokeWidth: Math.max(r9.width, s7.width) });\n }\n }\n return { coordinateSystem: \"cartesian\", title: `Power trace expander: ${this.phase}`, lines: e54, points: [], circles: t4, rects: this.obstacleIndex.items.filter((e60) =\u003e e60.kind === \"obstacle\").slice(0, 2000).map((e60) =\u003e ({ center: { x: (e60.minX + e60.maxX) / 2, y: (e60.minY + e60.maxY) / 2 }, width: e60.maxX - e60.minX, height: e60.maxY - e60.minY, fill: \"rgba(80,80,80,0.12)\", stroke: \"rgba(80,80,80,0.35)\" })), texts: [] };\n }\n};\nvar vte = (e54) =\u003e e54.minViaEdgeToPadEdgeClearance === undefined ? e54.minPadEdgeToPadEdgeClearance : Math.max(e54.minViaEdgeToPadEdgeClearance, e54.minPadEdgeToPadEdgeClearance ?? 0);\nvar Ite = class extends ni {\n constructor(e54, t4 = {}) {\n if (super(), this.inputSrj = e54, this.options = t4, this.powerTraceExpanderSolver = new xte({ ...e54, minViaEdgeToPadEdgeClearance: vte(e54) }, t4), t4.onlyConnectionNames?.length === 0)\n return this.MAX_ITERATIONS = 1, this.progress = 1, this.solved = true, void (this.stats = { selectedTraceCount: 0, bypassed: true });\n this.MAX_ITERATIONS = this.powerTraceExpanderSolver.MAX_ITERATIONS + 1;\n }\n powerTraceExpanderSolver;\n _step() {\n const e54 = this.powerTraceExpanderSolver;\n if (e54.step(), this.progress = e54.progress, this.stats = e54.stats, e54.failed)\n return this.error = e54.error, void (this.failed = true);\n e54.solved \u0026\u0026 (this.solved = true);\n }\n getConstructorParams() {\n return [this.inputSrj, this.options];\n }\n getOutput() {\n if (!this.solved)\n throw new Error(\"Cannot get power trace expansion output before solving\");\n return this.powerTraceExpanderSolver.getOutput();\n }\n visualize() {\n return Wo({ ...this.inputSrj, traces: this.getOutput() }, { traceColorMode: \"layer\" });\n }\n};\nvar Ste = ({ connections: e54, originalConnections: t4, layerCount: n8, obstacles: o10, defaultViaHoleDiameter: i8, connMap: r9 }) =\u003e {\n const s7 = new Map;\n for (const e60 of t4)\n s7.has(e60.name) || s7.set(e60.name, e60.__netConnectionName);\n const a9 = e54.map((e60) =\u003e {\n if (e60.pointsToConnect.length !== 2)\n throw new Error(`Expected Pipeline7 output connection \"${e60.name}\" to have two points, got ${e60.pointsToConnect.length}`);\n const [t10, n10] = e60.pointsToConnect;\n return { connection: e60, connectsTo: [t10?.pointId, n10?.pointId].filter((e61) =\u003e Boolean(e61)), outputConnectionName: e60.__netConnectionName ?? s7.get(e60.name) ?? e60.__rootConnectionNames?.[0] ?? e60.name };\n }), c5 = o10.filter((e60) =\u003e (e60.__zLayers?.length ?? e60.layers?.length ?? 0) \u003e 1), l5 = new Map, h5 = (e60) =\u003e {\n let t10 = l5.get(e60.connectionName);\n t10 || (t10 = new Map, l5.set(e60.connectionName, t10));\n const n10 = t10.get(e60.rootConnectionName);\n if (n10)\n return n10;\n const o11 = c5.filter((t11) =\u003e xo(t11, e60, r9));\n return t10.set(e60.rootConnectionName, o11), o11;\n };\n return (e60) =\u003e {\n const t10 = [], o11 = new Map;\n for (const t11 of e60) {\n const e61 = o11.get(t11.connectionName);\n e61 ? e61.push(t11) : o11.set(t11.connectionName, [t11]);\n }\n for (const { connection: e61, connectsTo: s9, outputConnectionName: c9 } of a9) {\n const a10 = o11.get(e61.name) ?? [];\n for (let o12 = 0;o12 \u003c a10.length; o12 += 1) {\n const l10 = a10[o12];\n t10.push({ type: \"pcb_trace\", pcb_trace_id: `${e61.name}_${o12}`, connection_name: c9, connectsTo: s9, route: Ro(l10, n8, { connectionPoints: e61.pointsToConnect, defaultViaHoleDiameter: i8, connectedMultilayerObstacles: h5(l10), connMap: r9 }) });\n }\n }\n return t10;\n };\n};\nvar Cte = ({ connections: e54, originalConnections: t4, hdRoutes: n8, layerCount: o10, obstacles: i8, defaultViaHoleDiameter: r9, connMap: s7 }) =\u003e Ste({ connections: e54, originalConnections: t4, layerCount: o10, obstacles: i8, defaultViaHoleDiameter: r9, connMap: s7 })(n8);\nvar Pte = (e54) =\u003e {\n const t4 = Math.max(e54.minTraceWidth + 0.1, 2 * e54.minTraceWidth);\n return e54.connections.flatMap((n8) =\u003e (n8.nominalTraceWidth ?? e54.nominalTraceWidth ?? e54.minTraceWidth) + 0.000001 \u003e= t4 ? [n8.name] : []);\n};\nvar Mte = ({ hdRoutes: e54, connections: t4 }) =\u003e {\n const n8 = new Map(t4.map((e60) =\u003e [e60.name, e60]));\n return e54.map((e60) =\u003e {\n if (e60.route.length === 0)\n throw new Error(`Cannot lock PCB terminals for empty route \"${e60.connectionName}\"`);\n const t10 = n8.get(e60.connectionName);\n if (!t10)\n throw new Error(`Cannot lock PCB terminals: connection \"${e60.connectionName}\" was not found`);\n if (t10.pointsToConnect.length !== 2)\n throw new Error(`Cannot lock PCB terminals for \"${e60.connectionName}\": expected 2 connection points, found ${t10.pointsToConnect.length}`);\n const o10 = new Map;\n for (const n10 of t10.pointsToConnect)\n if (n10.pcb_port_id) {\n if (o10.has(n10.pcb_port_id))\n throw new Error(`Cannot lock duplicate PCB terminal \"${n10.pcb_port_id}\" for \"${e60.connectionName}\"`);\n o10.set(n10.pcb_port_id, n10);\n }\n if (o10.size === 0)\n return e60;\n const i8 = [e60.startPcbPortId, e60.endPcbPortId].filter((e61) =\u003e e61 !== undefined);\n if (i8.length === 0)\n return e60;\n if (new Set(i8).size !== i8.length || i8.some((e61) =\u003e !o10.has(e61)))\n throw new Error(`Cannot lock PCB terminals for \"${e60.connectionName}\": route endpoint IDs do not match connection terminal IDs`);\n const r9 = e60.startPcbPortId ? o10.get(e60.startPcbPortId) : undefined, s7 = e60.endPcbPortId ? o10.get(e60.endPcbPortId) : undefined, a9 = e60.route.map((t11, n10) =\u003e {\n if (n10 === 0 \u0026\u0026 r9)\n return { ...t11, x: r9.x, y: r9.y, pcb_port_id: r9.pcb_port_id };\n if (n10 === e60.route.length - 1 \u0026\u0026 s7)\n return { ...t11, x: s7.x, y: s7.y, pcb_port_id: s7.pcb_port_id };\n const o11 = { ...t11 };\n return delete o11.pcb_port_id, o11;\n });\n return { ...e60, route: a9 };\n });\n};\nvar wte = ({ originalSrj: e54, newlyRoutedTraces: t4, currentPreloadedTraces: n8, expandedConnectionNames: o10, resolveConnectedTraceAliases: i8 = false }) =\u003e {\n const r9 = n8 ?? e54.traces ?? [], s7 = i8 ? Nte({ originalSrj: e54, newlyRoutedTraces: t4, preloadedTraces: r9, expandedConnectionNames: o10 }) : new Set(r9.filter((e60) =\u003e o10.includes(e60.connection_name))), a9 = r9.filter((e60) =\u003e !s7.has(e60)), c5 = new Set([...t4.map((e60) =\u003e e60.pcb_trace_id), ...a9.map((e60) =\u003e e60.pcb_trace_id)]), l5 = r9.filter((e60) =\u003e s7.has(e60)).map((e60) =\u003e {\n const t10 = e60.pcb_trace_id;\n let n10 = t10, o11 = 2;\n for (;c5.has(n10); )\n n10 = `${t10}_power_expansion_${o11++}`;\n return c5.add(n10), { ...e60, pcb_trace_id: n10, __replaces_pcb_trace_id: e60.__replaces_pcb_trace_id ?? e60.pcb_trace_id };\n });\n return { ...e54, traces: [...t4, ...l5], fixedTraces: a9 };\n};\nvar Nte = ({ originalSrj: e54, newlyRoutedTraces: t4, preloadedTraces: n8, expandedConnectionNames: o10 }) =\u003e {\n const i8 = new Set(n8.map((e60) =\u003e e60.pcb_trace_id)), r9 = new Set([...i8, ...t4.map((e60) =\u003e e60.pcb_trace_id)]), s7 = t4.map((e60, t10) =\u003e {\n if (!i8.has(e60.pcb_trace_id))\n return e60;\n const n10 = `__pipeline7_new_trace_${t10}_${e60.pcb_trace_id}`;\n let o11 = n10, s9 = 2;\n for (;r9.has(o11); )\n o11 = `${n10}_${s9++}`;\n return r9.add(o11), { ...e60, pcb_trace_id: o11 };\n }), a9 = new D7({ ...e54, traces: [...s7, ...n8] }), c5 = new Set(a9.canonicalize([...o10]));\n return new Set(n8.filter((e60) =\u003e a9.canonicalize([e60.connection_name]).some((e61) =\u003e c5.has(e61))));\n};\nfunction Rte(e54) {\n return new Set((e54 ?? []).filter((e60) =\u003e e60._isComponentTopologyNode).map((e60) =\u003e e60.capacityMeshNodeId));\n}\nfunction Tte(e54, t4) {\n return e54.nodeIds.some((e60) =\u003e t4.has(e60));\n}\nfunction Ete({ sharedEdgeSegments: e54, componentCapacityMeshNodeIds: t4 }) {\n return e54.filter((e60) =\u003e !Tte(e60, t4));\n}\nfunction Ate(e54, t4, n8, o10 = {}) {\n return { solverName: e54, solverClass: t4, getConstructorParams: n8, onSolved: o10.onSolved };\n}\nvar Ote = class extends ni {\n constructor(e54, t4 = {}) {\n super(), this.srj = e54, this.opts = t4;\n const n8 = V1(e54);\n this.originalSrj = n8, this.opts = { ...t4 };\n const o10 = this.opts;\n if (this.effort = o10.effort ?? 1, this.MAX_ITERATIONS = 1e8 * this.effort, this.maxNodeDimension = o10.maxNodeDimension ?? 16, this.maxNodeRatio = o10.maxNodeRatio ?? 6, this.minNodeArea = o10.minNodeArea ?? 0.1 ** 2, this.visualizationTraceColorMode = o10.visualizationTraceColorMode ?? \"layer\", this.setSimpleRouteJson(n8), o10.capacityDepth === undefined) {\n const e60 = this.srj.bounds.maxX - this.srj.bounds.minX, t10 = this.srj.bounds.maxY - this.srj.bounds.minY, n10 = Math.max(e60, t10), i8 = o10.targetMinCapacity ?? 0.5;\n o10.capacityDepth = Fz(n10, i8);\n }\n this.cacheProvider = o10.cacheProvider === undefined ? no() : o10.cacheProvider === null ? null : o10.cacheProvider, this.startTimeOfPhase = {}, this.endTimeOfPhase = {}, this.timeSpentOnPhase = {};\n }\n getSolverName() {\n return \"AutoroutingPipelineSolver7_MultiGraph\";\n }\n preprocessSimpleRouteJsonSolver;\n escapeViaLocationSolver;\n netToPointPairsSolver;\n componentTopologyGeneratorSolver;\n topologyPlanningSolver;\n topologyMergingSolver;\n globalTopologyGeneratorSolver;\n nodeDimensionSubdivisionSolver;\n nodeTargetMerger;\n edgeSolver;\n colorMap;\n highDensityRouteSolver;\n highDensityForceImproveSolver;\n highDensityRepairSolver;\n highDensityStitchSolver;\n globalDrcForceImproveSolver;\n exactGeometryDrcForceImproveSolver;\n singleLayerNodeMerger;\n strawSolver;\n deadEndSolver;\n traceSimplificationSolver;\n lengthMatchingPostProcessingSolver;\n powerTraceExpansionSolver;\n availableSegmentPointSolver;\n portPointPathingSolver;\n multiSectionPortPointOptimizer;\n uniformPortDistributionSolver;\n traceWidthSolver;\n necessaryCrampedPortPointSolver;\n componentDetectionSolver;\n viaDiameter;\n viaHoleDiameter;\n minTraceWidth;\n effort;\n maxNodeDimension;\n maxNodeRatio;\n minNodeArea;\n visualizationTraceColorMode;\n startTimeOfPhase;\n endTimeOfPhase;\n timeSpentOnPhase;\n activeSubSolver = null;\n connMap;\n srjWithEscapeViaLocations;\n srjWithPointPairs;\n originalSrj;\n capacityNodes = null;\n capacityEdges = null;\n sharedEdgeSegmentsWithNecessaryCrampedPortPoints;\n highDensityNodePortPoints;\n cacheProvider = null;\n pipelineDef = [Ate(\"preprocessSimpleRouteJsonSolver\", U1, (e54) =\u003e [e54.originalSrj, { traceColorMode: e54.visualizationTraceColorMode }], { onSolved: (e54) =\u003e {\n e54.setSimpleRouteJson(e54.preprocessSimpleRouteJsonSolver.getOutputSimpleRouteJson());\n } }), Ate(\"componentDetectionSolver\", r7, (e54) =\u003e [{ inputSrj: e54.srj }]), Ate(\"escapeViaLocationSolver\", uK, (e54) =\u003e [e54.srj, { viaDiameter: e54.viaDiameter, minTraceWidth: e54.minTraceWidth, obstacleMargin: e54.srj.defaultObstacleMargin ?? 0.15 }], { onSolved: (e54) =\u003e {\n e54.srjWithEscapeViaLocations = e54.escapeViaLocationSolver?.getOutputSimpleRouteJson();\n } }), Ate(\"netToPointPairsSolver\", pB, (e54) =\u003e {\n const t4 = e54.srjWithEscapeViaLocations ?? e54.srj;\n return [t4, e54.colorMap, ti(t4)];\n }, { onSolved: (e54) =\u003e {\n e54.srjWithPointPairs = e54.netToPointPairsSolver?.getNewSimpleRouteJson(), e54.colorMap = Eo(e54.srjWithPointPairs, e54.connMap), e54.connMap = ei(e54.srjWithPointPairs);\n } }), Ate(\"topologyPlanningSolver\", N7, (e54) =\u003e [{ inputSrj: e54.srjWithPointPairs, componentDetectionOutput: e54.componentDetectionSolver.getOutput(), viaDiameter: e54.viaDiameter, obstacleMargin: e54.srj.defaultObstacleMargin ?? 0.15 }], { onSolved: (e54) =\u003e {\n e54.topologyPlanningSolver.getOutput();\n e54.globalTopologyGeneratorSolver = e54.topologyPlanningSolver.globalTopologySolver, e54.componentTopologyGeneratorSolver = new E7(e54.topologyPlanningSolver);\n } }), Ate(\"topologyMergingSolver\", C7, (e54) =\u003e {\n const t4 = e54.topologyPlanningSolver.getOutput();\n return [{ layerCount: e54.srj.layerCount, allowBlindAndBuriedVias: e54.srj.allowBlindAndBuriedVias, nodeGroups: [{ groupId: \"global\", nodes: t4.globalMeshNodes, isComponent: false }, ...t4.componentMeshNodes.map((e60, t10) =\u003e ({ groupId: `component-${t10}`, nodes: e60, isComponent: true }))] }];\n }, { onSolved: (e54) =\u003e {\n e54.capacityNodes = e54.topologyMergingSolver.getOutput();\n } }), Ate(\"nodeDimensionSubdivisionSolver\", MZ, (e54) =\u003e [e54.capacityNodes, e54.maxNodeDimension, e54.maxNodeRatio, e54.minNodeArea], { onSolved: (e54) =\u003e {\n e54.capacityNodes = e54.nodeDimensionSubdivisionSolver.outputNodes;\n } }), Ate(\"edgeSolver\", ui, (e54) =\u003e [e54.capacityNodes], { onSolved: (e54) =\u003e {\n e54.capacityEdges = e54.edgeSolver?.edges;\n } }), Ate(\"availableSegmentPointSolver\", ii, (e54) =\u003e [{ nodes: e54.capacityNodes, edges: e54.capacityEdges || [], traceWidth: e54.minTraceWidth, colorMap: e54.colorMap, shouldReturnCrampedPortPoints: true }]), Ate(\"necessaryCrampedPortPointSolver\", FG, (e54) =\u003e {\n const t4 = Rte(e54.capacityNodes);\n return [{ capacityMeshNodes: e54.capacityNodes.filter((e60) =\u003e !t4.has(e60.capacityMeshNodeId)), sharedEdgeSegments: Ete({ sharedEdgeSegments: e54.availableSegmentPointSolver.getOutput(), componentCapacityMeshNodeIds: t4 }), simpleRouteJson: e54.srjWithPointPairs }];\n }, { onSolved: (e54) =\u003e {\n const t4 = Rte(e54.capacityNodes);\n e54.sharedEdgeSegmentsWithNecessaryCrampedPortPoints = function({ originalSharedEdgeSegments: e60, filteredSharedEdgeSegments: t10, componentCapacityMeshNodeIds: n8 }) {\n const o10 = new Map(t10.map((e61) =\u003e [e61.edgeId, e61]));\n return e60.map((e61) =\u003e Tte(e61, n8) ? e61 : o10.get(e61.edgeId) ?? e61);\n }({ originalSharedEdgeSegments: e54.availableSegmentPointSolver.getOutput(), filteredSharedEdgeSegments: e54.necessaryCrampedPortPointSolver.getOutput(), componentCapacityMeshNodeIds: t4 });\n } }), Ate(\"portPointPathingSolver\", eK, (e54) =\u003e {\n const t4 = e54.sharedEdgeSegmentsWithNecessaryCrampedPortPoints ?? e54.necessaryCrampedPortPointSolver?.getOutput() ?? e54.availableSegmentPointSolver.getOutput(), { graph: n8, connections: o10 } = KG({ capacityMeshNodes: e54.capacityNodes, layerCount: e54.srj.layerCount, connectivityMap: e54.connMap, segmentPortPoints: t4.flatMap((e60) =\u003e e60.portPoints), simpleRouteJsonConnections: e54.srjWithPointPairs.connections });\n return [{ graph: n8, connections: o10, layerCount: e54.srj.layerCount, effort: Math.min(1, e54.effort), preserveTerminalPcbPortIds: true, minViaPadDiameter: e54.viaDiameter, flags: { FORCE_CENTER_FIRST: true, RIPPING_ENABLED: true, USE_SELECTIVE_RERIP_ROUTING: true }, weights: { SHUFFLE_SEED: 0, MEMORY_PF_FACTOR: 4, CENTER_OFFSET_DIST_PENALTY_FACTOR: 0, CENTER_OFFSET_FOCUS_SHIFT: 0, NODE_PF_FACTOR: 0, LAYER_CHANGE_COST: 0, RIPPING_PF_COST: 0, NODE_PF_MAX_PENALTY: 100, BASE_CANDIDATE_COST: 0.6, MAX_ITERATIONS_PER_PATH: 0, RANDOM_WALK_DISTANCE: 0, START_RIPPING_PF_THRESHOLD: 0.3, END_RIPPING_PF_THRESHOLD: 1, MAX_RIPS: 1000, RANDOM_RIP_FRACTION: 0.3, STRAIGHT_LINE_DEVIATION_PENALTY_FACTOR: 4, GREEDY_MULTIPLIER: 0.7, MIN_ALLOWED_BOARD_SCORE: -1e4 } }];\n }), Ate(\"uniformPortDistributionSolver\", bo, (e54) =\u003e [{ nodeWithPortPoints: e54.portPointPathingSolver?.getOutput().nodesWithPortPoints ?? [], inputNodesWithPortPoints: e54.portPointPathingSolver?.getOutput().inputNodeWithPortPoints ?? [], minTraceWidth: e54.minTraceWidth, obstacles: e54.srj.obstacles, layerCount: e54.srj.layerCount }]), Ate(\"highDensityRouteSolver\", Dz, (e54) =\u003e {\n const t4 = e54.uniformPortDistributionSolver?.getOutput() ?? [], n8 = e54.portPointPathingSolver?.getOutput().nodesWithPortPoints ?? [], o10 = t4.length \u003e 0 ? t4 : n8;\n return e54.highDensityNodePortPoints = structuredClone(o10), [{ nodePortPoints: o10, nodePfById: new Map((e54.portPointPathingSolver?.getOutput().inputNodeWithPortPoints ?? []).map((t10) =\u003e [t10.capacityMeshNodeId, e54.portPointPathingSolver?.computeNodePf(t10) ?? null])), colorMap: e54.colorMap, connMap: e54.connMap, viaDiameter: e54.viaDiameter, traceWidth: e54.minTraceWidth, obstacleMargin: e54.srj.defaultObstacleMargin ?? 0.15, obstacles: e54.srj.obstacles, layerCount: e54.srj.layerCount, useGrowShrinkHighDensityIntraNodeSolver: true, preserveTerminalPcbPortIds: true, growShrinkFallbackToInvalidGeometryOnFailure: true, captureSearchDebug: false }];\n }), Ate(\"highDensityForceImproveSolver\", SZ, (e54) =\u003e [{ nodeWithPortPoints: e54.highDensityNodePortPoints ?? [], hdRoutes: e54.highDensityRouteSolver.routes, colorMap: e54.colorMap, totalStepsPerNode: Math.max(12, Math.round(20 * Math.min(1, e54.effort))), nodeAssignmentMargin: e54.srj.defaultObstacleMargin ?? 0.2 }]), Ate(\"highDensityRepairSolver\", g1, (e54) =\u003e [{ nodeWithPortPoints: e54.highDensityNodePortPoints ?? [], hdRoutes: e54.highDensityForceImproveSolver?.getOutput() ?? e54.highDensityRouteSolver.routes, obstacles: e54.srj.obstacles, colorMap: e54.colorMap, repairMargin: e54.srj.defaultObstacleMargin ?? 0.2, minimumTraceWidth: e54.srj.minTraceWidth, connMap: e54.connMap }]), Ate(\"highDensityStitchSolver\", L1, (e54) =\u003e [{ connections: e54.srjWithPointPairs.connections, hdRoutes: e54.highDensityRepairSolver?.getOutput() ?? e54.highDensityForceImproveSolver?.getOutput() ?? e54.highDensityRouteSolver.routes, colorMap: e54.colorMap, layerCount: e54.srj.layerCount, defaultViaDiameter: e54.viaDiameter, preserveTerminalPcbPortIds: true }]), Ate(\"traceSimplificationSolver\", WF, (e54) =\u003e [{ hdRoutes: e54.highDensityStitchSolver.mergedHdRoutes, obstacles: e54.srj.obstacles, connMap: e54.connMap, colorMap: e54.colorMap, outline: e54.srj.outline, defaultViaDiameter: e54.viaDiameter, layerCount: e54.srj.layerCount, minTraceToPadEdgeClearance: e54.srj.minTraceToPadEdgeClearance, minBoardEdgeClearance: e54.srj.minBoardEdgeClearance, enableCrossingViaReduction: true, iterations: 2 }]), Ate(\"traceWidthSolver\", QF, (e54) =\u003e [{ hdRoutes: e54.traceSimplificationSolver.simplifiedHdRoutes, obstacles: e54.srj.obstacles, connMap: e54.connMap, colorMap: e54.colorMap, minTraceWidth: e54.minTraceWidth, connection: e54.srj.connections, obstacleMargin: e54.srj.minTraceToPadEdgeClearance ?? 0.15, layerCount: e54.srj.layerCount }]), Ate(\"globalDrcForceImproveSolver\", kN, (e54) =\u003e [{ srj: e54.srjWithPointPairs, hdRoutes: Mte({ hdRoutes: e54.traceWidthSolver.getHdRoutesWithWidths(), connections: e54.netToPointPairsSolver?.newConnections ?? [] }), connMap: e54.connMap, effort: Math.min(1, e54.effort), maxIterations: 16, enableLargeBoardBroadFallback: false, enablePostSolveClearanceRelaxation: false }]), Ate(\"exactGeometryDrcForceImproveSolver\", LN, (e54) =\u003e {\n const t4 = e54.globalDrcForceImproveSolver.getOutput(), n8 = ((e60) =\u003e {\n const t10 = { ...e60.srjWithPointPairs, obstacles: e60.originalSrj.obstacles, minTraceWidth: e60.originalSrj.minTraceWidth, minViaDiameter: e60.originalSrj.minViaDiameter ?? e60.srjWithPointPairs.minViaDiameter }, n10 = vte(e60.originalSrj), o10 = Math.max(Yo(e60.originalSrj).padDiameter, t10.minTraceWidth) + Math.max(0.1, 0.1), i8 = new mb(t10, { connMap: e60.connMap, includeTraceViaOwnerMetadata: true, traceClearance: 0.1, viaClearance: 0.1, viaToPadClearance: n10, spatialCellSize: o10 }), r9 = Ste(e60), s7 = e60.originalSrj.traces ?? [];\n return ({ routes: e61, hdRoutes: t11 }) =\u003e {\n const n11 = e61 ?? t11;\n if (!n11)\n throw new Error(\"Pipeline7 autorouting DRC evaluation requires HD routes\");\n const o11 = r9(n11), a9 = s7.length ? [...s7, ...o11] : o11;\n return i8.evaluate(a9);\n };\n })({ connections: e54.netToPointPairsSolver?.newConnections ?? [], originalConnections: e54.originalSrj.connections, layerCount: e54.srj.layerCount, obstacles: e54.srj.obstacles, defaultViaHoleDiameter: e54.viaHoleDiameter, connMap: e54.connMap, srjWithPointPairs: e54.srjWithPointPairs, originalSrj: e54.originalSrj });\n return [{ srj: e54.srjWithPointPairs, hdRoutes: t4, connMap: e54.connMap, effort: Math.min(1, e54.effort), viaHoleDiameter: e54.viaHoleDiameter, drcEvaluator: n8, viaInPadDrcEvaluator: n8, maxIterations: 32, enableLargeBoardBroadFallback: false, enableBroadFallback: false, enableTargetedErrorSweep: true, enablePostSolveClearanceRelaxation: false, enableSafeTraceLayerMoves: true, enableViaInPadLayerMoves: e54.originalSrj.allowViaInPad ?? false, viaInPadMaxIterations: 32, broadMaxIterations: 12, broadPassMultiplier: 3 }];\n }), Ate(\"lengthMatchingPostProcessingSolver\", o9, (e54) =\u003e {\n const t4 = e54.netToPointPairsSolver;\n if (!t4)\n throw new Error(\"Pipeline7: length-matching post-processing requires NetToPointPairsSolver output\");\n const n8 = t4.newConnections, o10 = new Map;\n for (const t10 of e54.srj.differentialPairs ?? [])\n for (const e60 of t10.connectionNames) {\n const t11 = n8.filter((t12) =\u003e t12.name === e60 || t12.__rootConnectionNames?.includes(e60) || t12.__netConnectionName === e60);\n if (t11.length !== 1)\n throw new Error(`Pipeline7: differential pair connection \"${e60}\" must resolve to exactly one final point-pair connection, got ${t11.length}`);\n o10.set(e60, t11[0].name);\n }\n const i8 = e54.exactGeometryDrcForceImproveSolver.getOutput(), r9 = (e54.srj.differentialPairs ?? []).map((e60) =\u003e {\n const t10 = e60.connectionNames.map((e61) =\u003e {\n const t11 = o10.get(e61);\n if (!t11)\n throw new Error(`Pipeline7: differential pair connection \"${e61}\" is missing from final routed output`);\n return t11;\n });\n if (t10[0] === t10[1])\n throw new Error(`Pipeline7: differential pair ${e60.connectionNames.join(\"/\")} resolves both members to \"${t10[0]}\"`);\n if (e60.traceGap === undefined)\n return { connectionNames: t10, lengthTolerance: e60.lengthTolerance, maxUncoupledLength: e60.maxUncoupledLength };\n const n10 = t10.map((e61) =\u003e {\n const t11 = i8.filter((t12) =\u003e t12.connectionName === e61);\n if (t11.length !== 1)\n throw new Error(`Pipeline7: differential pair connection \"${e61}\" must resolve to exactly one final HD route, got ${t11.length}`);\n return t11[0];\n }), r10 = e60.traceGap + n10.reduce((e61, t11) =\u003e e61 + t11.traceThickness / 2, 0);\n return { connectionNames: t10, lengthTolerance: e60.lengthTolerance, maxUncoupledLength: e60.maxUncoupledLength, minimumCenterlineDistance: r10, maximumCenterlineDistance: r10 };\n });\n return [{ hdRoutes: i8, differentialPairs: r9, obstacles: e54.srj.obstacles, bounds: e54.srj.bounds, layerCount: e54.srj.layerCount }];\n }), Ate(\"powerTraceExpansionSolver\", Ite, (e54) =\u003e {\n const t4 = e54.opts.powerTraceExpansion ?? {}, n8 = t4.onlyConnectionNames ?? Pte(e54.originalSrj);\n return [wte({ originalSrj: e54.originalSrj, newlyRoutedTraces: e54.getPrePowerTraceOutputSimplifiedPcbTraces(), expandedConnectionNames: n8 }), { allowNewVias: false, ...t4, onlyConnectionNames: n8 }];\n })];\n setSimpleRouteJson(e54) {\n this.srj = e54;\n const t4 = Yo(this.srj);\n this.viaDiameter = t4.padDiameter, this.viaHoleDiameter = t4.holeDiameter, this.minTraceWidth = this.srj.minTraceWidth, this.connMap = ei(this.srj), this.colorMap = Eo(this.srj, this.connMap);\n }\n getConstructorParams() {\n return [this.srj, this.opts];\n }\n currentPipelineStepIndex = 0;\n computeProgress() {\n const e54 = this.activeSubSolver?.progress ?? 0;\n return (this.currentPipelineStepIndex + e54) / this.pipelineDef.length;\n }\n _step() {\n const e54 = this.pipelineDef[this.currentPipelineStepIndex];\n if (!e54)\n return void (this.solved = true);\n if (this.activeSubSolver)\n return this.activeSubSolver.step(), void (this.activeSubSolver.solved ? (this.endTimeOfPhase[e54.solverName] = performance.now(), this.timeSpentOnPhase[e54.solverName] = this.endTimeOfPhase[e54.solverName] - this.startTimeOfPhase[e54.solverName], e54.onSolved?.(this), this.activeSubSolver = null, this.currentPipelineStepIndex++) : this.activeSubSolver.failed \u0026\u0026 (this.error = this.activeSubSolver?.error, this.failed = true, this.activeSubSolver = null));\n const t4 = e54.getConstructorParams(this);\n this.activeSubSolver = new e54.solverClass(...t4), this.activeSubSolver instanceof WF \u0026\u0026 (this.activeSubSolver.MAX_SIMPLIFICATION_PIPELINE_LOOPS = Math.ceil(this.activeSubSolver.MAX_SIMPLIFICATION_PIPELINE_LOOPS * Math.min(1, this.effort))), e54.solverName !== \"lengthMatchingPostProcessingSolver\" \u0026\u0026 e54.solverName !== \"powerTraceExpansionSolver\" || (this.MAX_ITERATIONS = Math.max(this.MAX_ITERATIONS, this.iterations + this.activeSubSolver.MAX_ITERATIONS + 1)), this[e54.solverName] = this.activeSubSolver, this.timeSpentOnPhase[e54.solverName] = 0, this.startTimeOfPhase[e54.solverName] = performance.now();\n }\n solveUntilPhase(e54) {\n for (;this.getCurrentPhase() !== e54; )\n this.step();\n }\n getCurrentPhase() {\n return this.pipelineDef[this.currentPipelineStepIndex]?.solverName ?? \"none\";\n }\n visualize() {\n if (!this.solved \u0026\u0026 this.activeSubSolver)\n return this.visualizeStage(this.activeSubSolver);\n const e54 = this.escapeViaLocationSolver?.visualize(), t4 = this.netToPointPairsSolver?.visualize(), n8 = this.componentDetectionSolver?.visualize(), o10 = this.componentTopologyGeneratorSolver?.visualize(), i8 = this.globalTopologyGeneratorSolver?.visualize(), r9 = this.topologyMergingSolver?.visualize(), s7 = this.nodeDimensionSubdivisionSolver?.visualize(), a9 = this.nodeTargetMerger?.visualize(), c5 = this.singleLayerNodeMerger?.visualize(), l5 = this.strawSolver?.visualize(), h5 = this.edgeSolver?.visualize(), d9 = this.deadEndSolver?.visualize(), u9 = this.availableSegmentPointSolver?.visualize(), p9 = this.portPointPathingSolver?.visualize(), m9 = this.multiSectionPortPointOptimizer?.visualize(), g10 = this.uniformPortDistributionSolver?.visualize(), f10 = this.highDensityRouteSolver?.visualize(), _5 = this.highDensityForceImproveSolver?.visualize(), y10 = this.highDensityRepairSolver?.visualize(), b10 = this.highDensityStitchSolver?.visualize(), x8 = this.traceSimplificationSolver?.visualize(), v10 = this.lengthMatchingPostProcessingSolver?.visualize(), I6 = this.traceWidthSolver?.visualize(), S6 = this.necessaryCrampedPortPointSolver?.visualize(), C = (this.highDensityRouteSolver?.visualize(), this.originalSrj), P = C.outline, M = [];\n if (M.push({ points: [{ x: C.bounds?.minX ?? -50, y: C.bounds?.minY ?? -50 }, { x: C.bounds?.maxX ?? 50, y: C.bounds?.minY ?? -50 }, { x: C.bounds?.maxX ?? 50, y: C.bounds?.maxY ?? 50 }, { x: C.bounds?.minX ?? -50, y: C.bounds?.maxY ?? 50 }, { x: C.bounds?.minX ?? -50, y: C.bounds?.minY ?? -50 }], strokeColor: \"rgba(255,0,0,0.25)\" }), P \u0026\u0026 P.length \u003e= 2) {\n const e60 = P.map((e61) =\u003e ({ x: e61.x, y: e61.y }));\n e60.push({ ...e60[0] }), M.push({ points: e60, strokeColor: \"rgba(0, 136, 255, 0.95)\" });\n }\n const w = Lo(C), N = { points: [...C.connections.flatMap((e60) =\u003e e60.pointsToConnect.map((t10) =\u003e ({ ...t10, layer: Bo(t10, C.layerCount), label: `${e60.name} ${t10.pcb_port_id ?? \"\"}` })))], rects: [...(C.obstacles ?? []).filter((e60) =\u003e !e60.isCopperPour).map((e60) =\u003e ({ ...e60, fill: e60.layers?.includes(\"top\") ? \"rgba(255,0,0,0.25)\" : e60.layers?.includes(\"bottom\") ? \"rgba(0,0,255,0.25)\" : \"rgba(255,0,0,0.25)\", layer: jo(e60, C.layerCount), label: w(e60) }))], lines: M }, R10 = { traceColorMode: this.visualizationTraceColorMode }, T2 = nK({ srj: C, visualizationOptions: R10 }), E10 = pi(N, T2), A7 = this.preprocessSimpleRouteJsonSolver?.visualize(), O10 = this.globalDrcForceImproveSolver?.visualize(), k6 = this.exactGeometryDrcForceImproveSolver?.visualize(), D9 = [E10, A7, n8, o10, e54, t4, i8, r9, s7, a9, c5, l5, h5, d9, u9, S6, p9, m9, g10, f10 ? pi(N, f10) : null, _5, y10, b10, x8, I6, O10, k6, v10, this.solved ? pi({ lines: M }, nK({ srj: this.originalSrj, visualizationOptions: R10 }), this.visualizeFinalOutput()) : null].filter(Boolean), L10 = pi(...D9);\n return this.visualizationTraceColorMode === \"net\" ? T7(L10, this.colorMap) : L10;\n }\n visualizeStage(e54) {\n const t4 = e54.visualize();\n return this.visualizationTraceColorMode === \"net\" ? T7(t4, this.colorMap) : t4;\n }\n visualizeFinalOutput() {\n const e54 = this.visualizationTraceColorMode, t4 = this.getOutputSimpleRouteJson();\n return Wo(t4, { traceColorMode: e54 });\n }\n preview() {\n if (this.highDensityRouteSolver) {\n const e54 = [];\n for (let t4 = this.highDensityRouteSolver.routes.length - 1;t4 \u003e= 0; t4--) {\n const n8 = this.highDensityRouteSolver.routes[t4];\n if (e54.push({ points: n8.route.map((e60) =\u003e ({ x: e60.x, y: e60.y })), strokeColor: this.colorMap[n8.connectionName] }), e54.length \u003e 200)\n break;\n }\n return { lines: e54 };\n }\n return this.portPointPathingSolver ? this.portPointPathingSolver.preview() : this.netToPointPairsSolver ? this.netToPointPairsSolver.visualize() : this.escapeViaLocationSolver ? this.escapeViaLocationSolver.visualize() : this.componentTopologyGeneratorSolver ? this.componentTopologyGeneratorSolver.visualize() : this.componentDetectionSolver ? this.componentDetectionSolver.visualize() : this.preprocessSimpleRouteJsonSolver ? this.preprocessSimpleRouteJsonSolver.visualize() : {};\n }\n _getOutputHdRoutes() {\n if (this.lengthMatchingPostProcessingSolver) {\n const { hdRoutes: e54 } = this.lengthMatchingPostProcessingSolver.getOutput();\n return e54;\n }\n return this.exactGeometryDrcForceImproveSolver?.getOutput() ?? this.globalDrcForceImproveSolver?.getOutput() ?? this.traceWidthSolver?.getHdRoutesWithWidths() ?? this.traceSimplificationSolver?.simplifiedHdRoutes ?? this.highDensityStitchSolver.mergedHdRoutes;\n }\n getOutputSimplifiedPcbTraces() {\n if (!this.solved || !this.highDensityRouteSolver)\n throw new Error(\"Cannot get output before solving is complete\");\n return this.powerTraceExpansionSolver ? this.powerTraceExpansionSolver.getOutput() : this.getPrePowerTraceOutputSimplifiedPcbTraces();\n }\n getPrePowerTraceOutputSimplifiedPcbTraces() {\n return Cte({ connections: this.netToPointPairsSolver?.newConnections ?? [], originalConnections: this.originalSrj.connections, hdRoutes: this._getOutputHdRoutes(), layerCount: this.srj.layerCount, obstacles: this.srj.obstacles, defaultViaHoleDiameter: this.viaHoleDiameter, connMap: this.connMap });\n }\n getOutputSimpleRouteJson() {\n return { ...this.originalSrj, traces: this.getOutputSimplifiedPcbTraces() };\n }\n};\nvar kte = (e54) =\u003e [...new Set(e54)].sort((e60, t4) =\u003e e60 - t4);\nvar Dte = class extends ni {\n constructor(e54) {\n super(), this.params = e54, this.MAX_ITERATIONS = 1;\n }\n outputNodes = [];\n outputSharedEdgeSegments = [];\n nodeIdByOriginalAndZ = new Map;\n getSolverName() {\n return \"SplitNodesIntoSingleLayerNodeSolver\";\n }\n _step() {\n this.outputNodes = this.params.capacityMeshNodes.flatMap((e54) =\u003e kte(e54.availableZ).map((t4) =\u003e {\n const n8 = ((e60, t10) =\u003e `${e60}__z${t10}`)(e54.capacityMeshNodeId, t4);\n return this.nodeIdByOriginalAndZ.set(`${e54.capacityMeshNodeId}:${t4}`, n8), { ...e54, capacityMeshNodeId: n8, layer: `z${t4}`, availableZ: [t4], _parent: e54 };\n })), this.outputSharedEdgeSegments = this.params.sharedEdgeSegments.flatMap((e54) =\u003e this.splitSharedEdgeSegment(e54)), this.stats = { inputNodeCount: this.params.capacityMeshNodes.length, outputNodeCount: this.outputNodes.length, inputPortPointCount: this.params.sharedEdgeSegments.reduce((e54, t4) =\u003e e54 + t4.portPoints.length, 0), outputPortPointCount: this.outputSharedEdgeSegments.reduce((e54, t4) =\u003e e54 + t4.portPoints.length, 0) }, this.solved = true;\n }\n getSplitNodeId(e54, t4) {\n return this.nodeIdByOriginalAndZ.get(`${e54}:${t4}`);\n }\n splitPortPoint(e54) {\n return kte(e54.availableZ).flatMap((t4) =\u003e {\n const n8 = e54.nodeIds.map((e60) =\u003e this.getSplitNodeId(e60, t4));\n return n8[0] \u0026\u0026 n8[1] ? [{ ...e54, segmentPortPointId: `${e54.segmentPortPointId}__z${t4}`, availableZ: [t4], nodeIds: [n8[0], n8[1]] }] : [];\n });\n }\n splitSharedEdgeSegment(e54) {\n const t4 = new Map;\n for (const n8 of e54.portPoints.flatMap((e60) =\u003e this.splitPortPoint(e60))) {\n const e60 = n8.availableZ[0];\n if (e60 === undefined)\n continue;\n const o10 = t4.get(e60) ?? [];\n o10.push(n8), t4.set(e60, o10);\n }\n return [...t4.entries()].map(([t10, n8]) =\u003e ({ ...e54, edgeId: `${e54.edgeId}__z${t10}`, nodeIds: n8[0].nodeIds, availableZ: [t10], portPoints: n8 }));\n }\n getOutput() {\n return { capacityMeshNodes: this.outputNodes, sharedEdgeSegments: this.outputSharedEdgeSegments };\n }\n getConstructorParams() {\n return [this.params];\n }\n visualize() {\n return { rects: this.outputNodes.map((e54) =\u003e ({ ...dj(e54), label: `${e54.capacityMeshNodeId}\n${e54.layer}` })), points: this.outputSharedEdgeSegments.flatMap((e54) =\u003e e54.portPoints.map((e60) =\u003e ({ x: e60.x, y: e60.y, label: `${e60.segmentPortPointId}\nz${e60.availableZ.join(\",\")}` }))) };\n }\n};\nfunction Lte(e54, t4, n8, o10 = {}) {\n return { solverName: e54, solverClass: t4, getConstructorParams: n8, onSolved: o10.onSolved };\n}\nvar zte = class extends ni {\n constructor(e54, t4 = {}) {\n super(), this.srj = e54, this.opts = t4, this.originalSrj = e54, this.opts = { ...t4 };\n const n8 = this.opts;\n if (this.effort = n8.effort ?? 1, this.MAX_ITERATIONS = 1e8 * this.effort, this.maxNodeDimension = n8.maxNodeDimension ?? 16, this.maxNodeRatio = n8.maxNodeRatio ?? 6, this.minNodeArea = n8.minNodeArea ?? 0.1 ** 2, this.setSimpleRouteJson(e54), n8.capacityDepth === undefined) {\n const e60 = this.srj.bounds.maxX - this.srj.bounds.minX, t10 = this.srj.bounds.maxY - this.srj.bounds.minY, o10 = Math.max(e60, t10), i8 = n8.targetMinCapacity ?? 0.5;\n n8.capacityDepth = Fz(o10, i8);\n }\n this.cacheProvider = n8.cacheProvider === undefined ? no() : n8.cacheProvider === null ? null : n8.cacheProvider, this.startTimeOfPhase = {}, this.endTimeOfPhase = {}, this.timeSpentOnPhase = {};\n }\n preprocessSimpleRouteJsonSolver;\n escapeViaLocationSolver;\n netToPointPairsSolver;\n nodeSolver;\n nodeDimensionSubdivisionSolver;\n nodeTargetMerger;\n edgeSolver;\n colorMap;\n highDensityRouteSolver;\n highDensityForceImproveSolver;\n highDensityForceImproveRoutes;\n highDensityRepairSolver;\n highDensityRepairRoutes;\n highDensityStitchSolver;\n globalDrcForceImproveSolver;\n singleLayerNodeMerger;\n strawSolver;\n deadEndSolver;\n traceSimplificationSolver;\n availableSegmentPointSolver;\n splitNodesIntoSingleLayerNodeSolver;\n portPointPathingSolver;\n multiSectionPortPointOptimizer;\n uniformPortDistributionSolver;\n traceWidthSolver;\n necessaryCrampedPortPointSolver;\n viaDiameter;\n viaHoleDiameter;\n minTraceWidth;\n effort;\n maxNodeDimension;\n maxNodeRatio;\n minNodeArea;\n startTimeOfPhase;\n endTimeOfPhase;\n timeSpentOnPhase;\n activeSubSolver = null;\n connMap;\n srjWithEscapeViaLocations;\n srjWithPointPairs;\n originalSrj;\n capacityNodes = null;\n capacityEdges = null;\n highDensityNodePortPoints;\n cacheProvider = null;\n pipelineDef = [Lte(\"preprocessSimpleRouteJsonSolver\", U1, (e54) =\u003e [e54.originalSrj], { onSolved: (e54) =\u003e {\n e54.setSimpleRouteJson(e54.preprocessSimpleRouteJsonSolver.getOutputSimpleRouteJson());\n } }), Lte(\"escapeViaLocationSolver\", uK, (e54) =\u003e [e54.srj, { viaDiameter: e54.viaDiameter, minTraceWidth: e54.minTraceWidth, obstacleMargin: e54.srj.defaultObstacleMargin ?? 0.15 }], { onSolved: (e54) =\u003e {\n e54.srjWithEscapeViaLocations = e54.escapeViaLocationSolver?.getOutputSimpleRouteJson();\n } }), Lte(\"netToPointPairsSolver\", pB, (e54) =\u003e {\n const t4 = e54.srjWithEscapeViaLocations ?? e54.srj;\n return [t4, e54.colorMap, ti(t4)];\n }, { onSolved: (e54) =\u003e {\n e54.srjWithPointPairs = e54.netToPointPairsSolver?.getNewSimpleRouteJson(), e54.colorMap = Eo(e54.srjWithPointPairs, e54.connMap), e54.connMap = ei(e54.srjWithPointPairs);\n } }), Lte(\"nodeSolver\", Jn, (e54) =\u003e [{ simpleRouteJson: e54.srjWithPointPairs, maxGapFillPasses: 4 }], { onSolved: (e54) =\u003e {\n e54.capacityNodes = e54.nodeSolver?.getOutput().meshNodes ?? [];\n } }), Lte(\"nodeDimensionSubdivisionSolver\", MZ, (e54) =\u003e [e54.capacityNodes, e54.maxNodeDimension, e54.maxNodeRatio, e54.minNodeArea], { onSolved: (e54) =\u003e {\n e54.capacityNodes = e54.nodeDimensionSubdivisionSolver?.outputNodes ?? [];\n } }), Lte(\"edgeSolver\", ui, (e54) =\u003e [e54.capacityNodes], { onSolved: (e54) =\u003e {\n e54.capacityEdges = e54.edgeSolver?.edges;\n } }), Lte(\"availableSegmentPointSolver\", ii, (e54) =\u003e [{ nodes: e54.capacityNodes, edges: e54.capacityEdges || [], traceWidth: e54.minTraceWidth, colorMap: e54.colorMap, shouldReturnCrampedPortPoints: true }]), Lte(\"necessaryCrampedPortPointSolver\", FG, (e54) =\u003e [{ capacityMeshNodes: e54.capacityNodes, sharedEdgeSegments: e54.availableSegmentPointSolver.getOutput(), simpleRouteJson: e54.srjWithPointPairs }]), Lte(\"splitNodesIntoSingleLayerNodeSolver\", Dte, (e54) =\u003e [{ capacityMeshNodes: e54.capacityNodes, sharedEdgeSegments: e54.necessaryCrampedPortPointSolver?.getOutput() ?? e54.availableSegmentPointSolver.getOutput() }], { onSolved: (e54) =\u003e {\n e54.capacityNodes = e54.splitNodesIntoSingleLayerNodeSolver.getOutput().capacityMeshNodes;\n } }), Lte(\"portPointPathingSolver\", eK, (e54) =\u003e {\n const t4 = e54.splitNodesIntoSingleLayerNodeSolver.getOutput(), { graph: n8, connections: o10 } = KG({ capacityMeshNodes: t4.capacityMeshNodes, layerCount: e54.srj.layerCount, connectivityMap: e54.connMap, segmentPortPoints: t4.sharedEdgeSegments.flatMap((e60) =\u003e e60.portPoints), simpleRouteJsonConnections: e54.srjWithPointPairs.connections, assignableViaObstacles: e54.originalSrj.obstacles });\n return [{ graph: n8, connections: o10, layerCount: e54.srj.layerCount, effort: Math.min(1, e54.effort), minViaPadDiameter: e54.viaDiameter, flags: { FORCE_CENTER_FIRST: true, RIPPING_ENABLED: true }, weights: { SHUFFLE_SEED: 0, MEMORY_PF_FACTOR: 4, CENTER_OFFSET_DIST_PENALTY_FACTOR: 0, CENTER_OFFSET_FOCUS_SHIFT: 0, NODE_PF_FACTOR: 0, LAYER_CHANGE_COST: 0, RIPPING_PF_COST: 0, NODE_PF_MAX_PENALTY: 100, BASE_CANDIDATE_COST: 0.6, MAX_ITERATIONS_PER_PATH: 0, RANDOM_WALK_DISTANCE: 0, START_RIPPING_PF_THRESHOLD: 0.3, END_RIPPING_PF_THRESHOLD: 1, MAX_RIPS: 1000, RANDOM_RIP_FRACTION: 0.3, STRAIGHT_LINE_DEVIATION_PENALTY_FACTOR: 4, GREEDY_MULTIPLIER: 0.7, MIN_ALLOWED_BOARD_SCORE: -1e4 } }];\n }), Lte(\"uniformPortDistributionSolver\", bo, (e54) =\u003e [{ nodeWithPortPoints: e54.portPointPathingSolver?.getOutput().nodesWithPortPoints ?? [], inputNodesWithPortPoints: e54.portPointPathingSolver?.getOutput().inputNodeWithPortPoints ?? [], minTraceWidth: e54.minTraceWidth, obstacles: e54.srj.obstacles, layerCount: e54.srj.layerCount }]), Lte(\"highDensityRouteSolver\", Dz, (e54) =\u003e {\n const t4 = e54.uniformPortDistributionSolver?.getOutput() ?? [], n8 = e54.portPointPathingSolver?.getOutput().nodesWithPortPoints ?? [], o10 = t4.length \u003e 0 ? t4 : n8;\n return e54.highDensityNodePortPoints = structuredClone(o10), [{ nodePortPoints: o10, nodePfById: new Map((e54.portPointPathingSolver?.getOutput().inputNodeWithPortPoints ?? []).map((t10) =\u003e [t10.capacityMeshNodeId, e54.portPointPathingSolver?.computeNodePf(t10) ?? null])), colorMap: e54.colorMap, connMap: e54.connMap, viaDiameter: e54.viaDiameter, traceWidth: e54.minTraceWidth, obstacleMargin: e54.srj.defaultObstacleMargin ?? 0.15, obstacles: e54.srj.obstacles, layerCount: e54.srj.layerCount }];\n }), Lte(\"highDensityForceImproveSolver\", SZ, (e54) =\u003e [{ nodeWithPortPoints: e54.getHighDensityNodePortPointsWithAssignableViasFirst(), hdRoutes: e54.getMovableHighDensityRoutes(e54.highDensityRouteSolver.routes), colorMap: e54.colorMap, totalStepsPerNode: Math.max(20, Math.round(60 * Math.min(1, e54.effort))), nodeAssignmentMargin: e54.srj.defaultObstacleMargin ?? 0.2 }], { onSolved: (e54) =\u003e {\n e54.highDensityForceImproveRoutes = e54.mergeMovableHighDensityRoutesBack(e54.highDensityRouteSolver.routes, e54.highDensityForceImproveSolver.getOutput());\n } }), Lte(\"highDensityRepairSolver\", g1, (e54) =\u003e [{ nodeWithPortPoints: e54.getHighDensityNodePortPointsWithAssignableViasFirst(), hdRoutes: e54.getMovableHighDensityRoutes(e54.highDensityForceImproveRoutes ?? e54.highDensityForceImproveSolver?.getOutput() ?? e54.highDensityRouteSolver.routes), obstacles: e54.srj.obstacles, colorMap: e54.colorMap, repairMargin: e54.srj.defaultObstacleMargin ?? 0.2, minimumTraceWidth: e54.srj.minTraceWidth, connMap: e54.connMap }], { onSolved: (e54) =\u003e {\n const t4 = e54.highDensityForceImproveRoutes ?? e54.highDensityForceImproveSolver?.getOutput() ?? e54.highDensityRouteSolver.routes;\n e54.highDensityRepairRoutes = e54.mergeMovableHighDensityRoutesBack(t4, e54.highDensityRepairSolver.getOutput());\n } }), Lte(\"highDensityStitchSolver\", L1, (e54) =\u003e [{ connections: e54.srjWithPointPairs.connections, hdRoutes: e54.highDensityRepairRoutes ?? e54.highDensityRepairSolver?.getOutput() ?? e54.highDensityForceImproveRoutes ?? e54.highDensityForceImproveSolver?.getOutput() ?? e54.highDensityRouteSolver.routes, colorMap: e54.colorMap, layerCount: e54.srj.layerCount, defaultViaDiameter: e54.viaDiameter, allowedLayerTransitionPointKeys: VG(e54.originalSrj.obstacles) }]), Lte(\"traceSimplificationSolver\", WF, (e54) =\u003e [{ hdRoutes: e54.highDensityStitchSolver.mergedHdRoutes, obstacles: e54.srj.obstacles, connMap: e54.connMap, colorMap: e54.colorMap, outline: e54.srj.outline, defaultViaDiameter: e54.viaDiameter, layerCount: e54.srj.layerCount, minTraceToPadEdgeClearance: e54.srj.minTraceToPadEdgeClearance, iterations: 2 }]), Lte(\"traceWidthSolver\", QF, (e54) =\u003e [{ hdRoutes: e54.traceSimplificationSolver.simplifiedHdRoutes, obstacles: e54.srj.obstacles, connMap: e54.connMap, colorMap: e54.colorMap, minTraceWidth: e54.minTraceWidth, connection: e54.srj.connections, obstacleMargin: e54.srj.minTraceToPadEdgeClearance ?? 0.15, layerCount: e54.srj.layerCount }]), Lte(\"globalDrcForceImproveSolver\", kN, (e54) =\u003e [{ srj: e54.srjWithPointPairs, hdRoutes: e54.traceWidthSolver.getHdRoutesWithWidths(), effort: Math.min(1, e54.effort) }])];\n setSimpleRouteJson(e54) {\n this.srj = e54;\n const t4 = Yo(this.srj);\n this.viaDiameter = t4.padDiameter, this.viaHoleDiameter = t4.holeDiameter, this.minTraceWidth = this.srj.minTraceWidth, this.connMap = ei(this.srj), this.colorMap = Eo(this.srj, this.connMap);\n }\n getConstructorParams() {\n return [this.srj, this.opts];\n }\n currentPipelineStepIndex = 0;\n _step() {\n const e54 = this.pipelineDef[this.currentPipelineStepIndex];\n if (!e54)\n return void (this.solved = true);\n if (this.activeSubSolver)\n return this.activeSubSolver.step(), void (this.activeSubSolver.solved ? (this.endTimeOfPhase[e54.solverName] = performance.now(), this.timeSpentOnPhase[e54.solverName] = this.endTimeOfPhase[e54.solverName] - this.startTimeOfPhase[e54.solverName], e54.onSolved?.(this), this.activeSubSolver = null, this.currentPipelineStepIndex++) : this.activeSubSolver.failed \u0026\u0026 (this.error = this.activeSubSolver?.error, this.failed = true, this.activeSubSolver = null));\n const t4 = e54.getConstructorParams(this);\n this.activeSubSolver = new e54.solverClass(...t4), this[e54.solverName] = this.activeSubSolver, this.timeSpentOnPhase[e54.solverName] = 0, this.startTimeOfPhase[e54.solverName] = performance.now();\n }\n solveUntilPhase(e54) {\n for (;this.getCurrentPhase() !== e54; )\n this.step();\n }\n getCurrentPhase() {\n return this.pipelineDef[this.currentPipelineStepIndex]?.solverName ?? \"none\";\n }\n visualize() {\n if (!this.solved \u0026\u0026 this.activeSubSolver)\n return this.activeSubSolver.visualize();\n const e54 = this.escapeViaLocationSolver?.visualize(), t4 = this.netToPointPairsSolver?.visualize(), n8 = this.nodeSolver?.visualize(), o10 = this.nodeDimensionSubdivisionSolver?.visualize(), i8 = this.nodeTargetMerger?.visualize(), r9 = this.singleLayerNodeMerger?.visualize(), s7 = this.strawSolver?.visualize(), a9 = this.edgeSolver?.visualize(), c5 = this.deadEndSolver?.visualize(), l5 = this.availableSegmentPointSolver?.visualize(), h5 = this.splitNodesIntoSingleLayerNodeSolver?.visualize(), d9 = this.portPointPathingSolver?.visualize(), u9 = this.multiSectionPortPointOptimizer?.visualize(), p9 = this.uniformPortDistributionSolver?.visualize(), m9 = this.highDensityRouteSolver?.visualize(), g10 = this.highDensityForceImproveSolver?.visualize(), f10 = this.highDensityRepairSolver?.visualize(), _5 = this.highDensityStitchSolver?.visualize(), y10 = this.traceSimplificationSolver?.visualize(), b10 = this.necessaryCrampedPortPointSolver?.visualize(), x8 = (this.highDensityRouteSolver?.visualize(), this.originalSrj), v10 = x8.outline, I6 = [];\n if (I6.push({ points: [{ x: x8.bounds?.minX ?? -50, y: x8.bounds?.minY ?? -50 }, { x: x8.bounds?.maxX ?? 50, y: x8.bounds?.minY ?? -50 }, { x: x8.bounds?.maxX ?? 50, y: x8.bounds?.maxY ?? 50 }, { x: x8.bounds?.minX ?? -50, y: x8.bounds?.maxY ?? 50 }, { x: x8.bounds?.minX ?? -50, y: x8.bounds?.minY ?? -50 }], strokeColor: \"rgba(255,0,0,0.25)\" }), v10 \u0026\u0026 v10.length \u003e= 2) {\n const e60 = v10.map((e61) =\u003e ({ x: e61.x, y: e61.y }));\n e60.push({ ...e60[0] }), I6.push({ points: e60, strokeColor: \"rgba(0, 136, 255, 0.95)\" });\n }\n const S6 = Lo(x8), C = { points: [...x8.connections.flatMap((e60) =\u003e e60.pointsToConnect.map((t10) =\u003e ({ ...t10, layer: Bo(t10, x8.layerCount), label: `${e60.name} ${t10.pcb_port_id ?? \"\"}` })))], rects: [...(x8.obstacles ?? []).filter((e60) =\u003e !e60.isCopperPour).map((e60) =\u003e ({ ...e60, fill: e60.layers?.includes(\"top\") ? \"rgba(255,0,0,0.25)\" : e60.layers?.includes(\"bottom\") ? \"rgba(0,0,255,0.25)\" : \"rgba(255,0,0,0.25)\", layer: jo(e60, x8.layerCount), label: S6(e60) }))], lines: I6 }, P = nK({ srj: x8 }), M = [pi(C, P), e54, t4, n8, o10, i8, r9, s7, a9, c5, l5, b10, h5, d9, u9, p9, m9 ? pi(C, m9) : null, g10, f10, _5, y10, this.solved ? pi({ lines: I6 }, nK({ srj: this.originalSrj }), Wo(this.getOutputSimpleRouteJson())) : null].filter(Boolean);\n return pi(...M);\n }\n preview() {\n if (this.highDensityRouteSolver) {\n const e54 = [];\n for (let t4 = this.highDensityRouteSolver.routes.length - 1;t4 \u003e= 0; t4--) {\n const n8 = this.highDensityRouteSolver.routes[t4];\n if (e54.push({ points: n8.route.map((e60) =\u003e ({ x: e60.x, y: e60.y })), strokeColor: this.colorMap[n8.connectionName] }), e54.length \u003e 200)\n break;\n }\n return { lines: e54 };\n }\n return this.portPointPathingSolver ? this.portPointPathingSolver.preview() : this.netToPointPairsSolver ? this.netToPointPairsSolver.visualize() : this.escapeViaLocationSolver ? this.escapeViaLocationSolver.visualize() : this.preprocessSimpleRouteJsonSolver ? this.preprocessSimpleRouteJsonSolver.visualize() : {};\n }\n _getOutputHdRoutes() {\n const e54 = this.globalDrcForceImproveSolver?.getOutput();\n return e54 \u0026\u0026 this.routesOnlyUsePreplacedVias(e54) ? e54 : this.traceWidthSolver?.getHdRoutesWithWidths() ?? this.traceSimplificationSolver?.simplifiedHdRoutes ?? this.highDensityRepairRoutes ?? this.highDensityForceImproveRoutes ?? this.highDensityStitchSolver.mergedHdRoutes;\n }\n routesOnlyUsePreplacedVias(e54) {\n const t4 = VG(this.originalSrj.obstacles);\n return t4.size === 0 || e54.every((e60) =\u003e e60.vias.every((e61) =\u003e t4.has(jG(e61))));\n }\n getHighDensityNodePortPointsWithAssignableViasFirst() {\n return [...this.highDensityNodePortPoints ?? []].sort((e54, t4) =\u003e {\n const n8 = e54.capacityMeshNodeId.startsWith(\"assignable-via:\");\n return n8 === t4.capacityMeshNodeId.startsWith(\"assignable-via:\") ? 0 : n8 ? -1 : 1;\n });\n }\n getPreplacedAssignableViaObstacles() {\n return this.originalSrj.obstacles.filter((e54) =\u003e e54.netIsAssignable === true \u0026\u0026 (e54.layers?.length ?? 0) \u003e 1);\n }\n isFixedPreplacedViaRoute(e54) {\n const t4 = this.getPreplacedAssignableViaObstacles();\n return t4.length !== 0 \u0026\u0026 e54.vias.length !== 0 \u0026\u0026 t4.some((t10) =\u003e [...e54.route, ...e54.vias].every((e60) =\u003e Oe(e60, t10) \u003c= 0));\n }\n getMovableHighDensityRouteIndexes(e54) {\n return e54.map((e60, t4) =\u003e this.isFixedPreplacedViaRoute(e60) ? -1 : t4).filter((e60) =\u003e e60 !== -1);\n }\n getMovableHighDensityRoutes(e54) {\n return this.getMovableHighDensityRouteIndexes(e54).map((t4) =\u003e e54[t4]);\n }\n mergeMovableHighDensityRoutesBack(e54, t4) {\n const n8 = this.getMovableHighDensityRouteIndexes(e54), o10 = [...e54];\n for (let e60 = 0;e60 \u003c n8.length; e60++)\n o10[n8[e60]] = t4[e60];\n return o10;\n }\n getOutputSimplifiedPcbTraces() {\n if (!this.solved || !this.highDensityRouteSolver)\n throw new Error(\"Cannot get output before solving is complete\");\n const e54 = [], t4 = this._getOutputHdRoutes();\n for (const n8 of this.netToPointPairsSolver?.newConnections ?? []) {\n const o10 = n8.__netConnectionName ?? this.originalSrj.connections.find((e60) =\u003e e60.name === n8.name)?.__netConnectionName, i8 = t4.filter((e60) =\u003e e60.connectionName === n8.name);\n for (let t10 = 0;t10 \u003c i8.length; t10++) {\n const r9 = i8[t10], s7 = { type: \"pcb_trace\", pcb_trace_id: `${n8.name}_${t10}`, connection_name: o10 ?? n8.__rootConnectionNames?.[0] ?? n8.name, route: Ro(r9, this.srj.layerCount, { connectionPoints: n8.pointsToConnect, defaultViaHoleDiameter: this.viaHoleDiameter, obstacles: this.srj.obstacles, connMap: this.connMap }) };\n e54.push(s7);\n }\n }\n return e54;\n }\n getOutputSimpleRouteJson() {\n return { ...this.originalSrj, traces: this.getOutputSimplifiedPcbTraces() };\n }\n};\nvar Bte = class extends ni {\n bestRoutes;\n bestCost;\n completedPasses = 0;\n cleanupPasses;\n simplifier;\n viaRemovalSolver;\n params;\n constructor(e54) {\n super(), this.params = e54, this.bestRoutes = structuredClone([...e54.config.hdRoutes]), this.bestCost = e54.getCost(this.bestRoutes), this.cleanupPasses = e54.effort \u003c= 1 ? e54.viaRemovalPasses ?? 1 : Math.ceil(2 * e54.effort), this.MAX_ITERATIONS = 1e8 * Math.max(1, this.cleanupPasses), e54.effort \u003c= 1 ? this.viaRemovalSolver = this.createViaRemovalSolver() : (this.simplifier = new WF({ ...e54.config, enableRoutedTraceDetours: true, hdRoutes: structuredClone(this.bestRoutes) }), this.simplifier.simplificationPipelineLoops = 2, this.simplifier.MAX_SIMPLIFICATION_PIPELINE_LOOPS = 2 + this.cleanupPasses, this.simplifier.MAX_ITERATIONS = this.MAX_ITERATIONS);\n }\n createViaRemovalSolver() {\n const e54 = this.params.config, t4 = new aF({ unsimplifiedHdRoutes: structuredClone(this.bestRoutes), otherHdRoutes: e54.otherHdRoutes, obstacles: [...e54.obstacles], colorMap: e54.colorMap, layerCount: e54.layerCount, connMap: e54.connMap, outline: e54.outline ? [...e54.outline] : undefined, geometryShortcutTraceMargin: 0.1, geometryShortcutObstacleMargin: e54.minTraceToPadEdgeClearance ?? 0.15, enableGeometryShortcuts: true, enableRoutedTraceDetours: true, enableObstacleDetourShortcuts: e54.enableCrossingViaReduction, preserveRouteEndpoints: e54.preserveRouteEndpoints, terminalLayerIndicesByPcbPortId: e54.terminalLayerIndicesByPcbPortId });\n return t4.MAX_ITERATIONS = this.MAX_ITERATIONS, t4;\n }\n _step() {\n if (this.viaRemovalSolver) {\n const e60 = this.viaRemovalSolver;\n if (e60.step(), e60.failed)\n return this.failed = true, void (this.error = e60.error);\n if (!e60.solved)\n return;\n const t10 = e60.getOptimizedHdRoutes();\n if (!t10)\n throw new Error(\"Via removal has no output\");\n const n10 = this.params.getCost(t10), o11 = n10.vias \u003c this.bestCost.vias \u0026\u0026 this.params.isValid(t10);\n return o11 \u0026\u0026 (this.bestRoutes = structuredClone(t10), this.bestCost = n10), this.completedPasses++, o11 \u0026\u0026 this.completedPasses \u003c this.cleanupPasses ? void (this.viaRemovalSolver = this.createViaRemovalSolver()) : void (this.solved = true);\n }\n const e54 = this.simplifier;\n if (!e54)\n throw new Error(\"Cleanup has no active simplifier\");\n const { currentPhase: t4, simplificationPipelineLoops: n8 } = e54;\n if (e54.step(), e54.failed)\n return this.failed = true, void (this.error = e54.error);\n const o10 = e54.simplificationPipelineLoops - 2;\n if (this.completedPasses = o10, e54.currentPhase !== t4 || e54.simplificationPipelineLoops !== n8) {\n const t10 = e54.simplifiedHdRoutes, n10 = this.params.getCost(t10);\n (n10.vias \u003c this.bestCost.vias || n10.vias === this.bestCost.vias \u0026\u0026 n10.points \u003c this.bestCost.points) \u0026\u0026 this.params.isValid(t10) \u0026\u0026 (this.bestRoutes = structuredClone(t10), this.bestCost = n10);\n }\n this.solved = e54.solved;\n }\n getOutput() {\n if (!this.solved)\n throw new Error(\"Cleanup is not complete\");\n return this.bestRoutes;\n }\n};\nvar Fte = (e54, t4) =\u003e {\n const n8 = Math.min(e54.start.x, e54.end.x), o10 = Math.min(e54.start.y, e54.end.y), i8 = Math.max(e54.start.x, e54.end.x), r9 = Math.max(e54.start.y, e54.end.y), s7 = (e54.start.width + t4.start.width) / 2, a9 = Math.max(0, s7) + 0.000000001;\n return !(Number.isFinite(n8) \u0026\u0026 Number.isFinite(o10) \u0026\u0026 Number.isFinite(i8) \u0026\u0026 Number.isFinite(r9) \u0026\u0026 Number.isFinite(t4.start.x) \u0026\u0026 Number.isFinite(t4.start.y) \u0026\u0026 Number.isFinite(t4.end.x) \u0026\u0026 Number.isFinite(t4.end.y) \u0026\u0026 Number.isFinite(s7) \u0026\u0026 (Math.min(t4.start.x, t4.end.x) \u003e i8 + a9 || Math.max(t4.start.x, t4.end.x) \u003c n8 - a9 || Math.min(t4.start.y, t4.end.y) \u003e r9 + a9 || Math.max(t4.start.y, t4.end.y) \u003c o10 - a9)) \u0026\u0026 le([e54.start, e54.end], [t4.start, t4.end], { lineThickness: s7 });\n};\nvar jte = (e54, t4) =\u003e {\n if (t4.shape === \"circle\") {\n const n10 = t4.type === \"pcb_smtpad\" ? t4.radius : t4.outer_diameter / 2;\n return Math.hypot(e54.x - t4.x, e54.y - t4.y) \u003c= n10 + 0.000000001;\n }\n if (t4.type === \"pcb_smtpad\" \u0026\u0026 t4.shape === \"rect\")\n return Math.abs(e54.x - t4.x) \u003c= t4.width / 2 + 0.000000001 \u0026\u0026 Math.abs(e54.y - t4.y) \u003c= t4.height / 2 + 0.000000001;\n let n8, o10, i8;\n if (t4.type === \"pcb_smtpad\" \u0026\u0026 t4.shape === \"rotated_rect\")\n n8 = t4.width, o10 = t4.height, i8 = t4.ccw_rotation ?? 0;\n else {\n if (!(\"rect_pad_width\" in t4) || !(\"rect_pad_height\" in t4))\n throw new Error(`Unsupported autorouting continuity pad shape: ${t4.shape}`);\n n8 = t4.rect_pad_width, o10 = t4.rect_pad_height, i8 = \"rect_ccw_rotation\" in t4 \u0026\u0026 typeof t4.rect_ccw_rotation == \"number\" ? t4.rect_ccw_rotation : 0;\n }\n const r9 = i8 * Math.PI / 180, s7 = [{ x: -n8 / 2, y: -o10 / 2 }, { x: n8 / 2, y: -o10 / 2 }, { x: n8 / 2, y: o10 / 2 }, { x: -n8 / 2, y: o10 / 2 }].map(({ x: e60, y: n10 }) =\u003e ({ x: t4.x + e60 * Math.cos(r9) - n10 * Math.sin(r9), y: t4.y + e60 * Math.sin(r9) + n10 * Math.cos(r9) }));\n for (let t10 = 0;t10 \u003c s7.length; t10++) {\n const n10 = s7[t10], o11 = s7[(t10 + 1) % s7.length], i9 = o11.x - n10.x, r10 = o11.y - n10.y, a9 = (e54.y - n10.y) * i9 - (e54.x - n10.x) * r10, c5 = (e54.x - n10.x) * i9 + (e54.y - n10.y) * r10;\n if (Math.abs(a9) \u003c= 0.000000001 \u0026\u0026 c5 \u003e= -0.000000001 \u0026\u0026 c5 \u003c= i9 * i9 + r10 * r10 + 0.000000001)\n return true;\n }\n return ve(e54, s7);\n};\nvar $te = (e54, t4) =\u003e e54.route_type === \"wire\" \u0026\u0026 (e54.start_pcb_port_id === t4 || e54.end_pcb_port_id === t4);\nvar Yte = (e54, t4) =\u003e {\n if (e54.route_type !== \"wire\")\n return false;\n return (t4.type === \"pcb_smtpad\" ? [t4.layer] : t4.layers).includes(e54.layer) \u0026\u0026 jte(e54, t4);\n};\nvar Xte = (e54, t4) =\u003e {\n if (e54.radius === undefined)\n return jte(e54, t4);\n if (t4.shape === \"circle\") {\n const n10 = t4.type === \"pcb_smtpad\" ? t4.radius : t4.outer_diameter / 2;\n return Math.hypot(e54.x - t4.x, e54.y - t4.y) \u003c= n10 + e54.radius + 0.000000001;\n }\n const n8 = \"rect_pad_width\" in t4 ? t4.rect_pad_width : (\"width\" in t4) ? t4.width : undefined, o10 = \"rect_pad_height\" in t4 ? t4.rect_pad_height : (\"height\" in t4) ? t4.height : undefined;\n if (n8 === undefined || o10 === undefined || !(\"x\" in t4) || !(\"y\" in t4))\n throw new Error(`Unsupported autorouting continuity pad shape: ${t4.shape}`);\n const i8 = (\"rect_ccw_rotation\" in t4 ? t4.rect_ccw_rotation ?? 0 : (\"ccw_rotation\" in t4) ? t4.ccw_rotation ?? 0 : 0) * Math.PI / 180, r9 = e54.x - t4.x, s7 = e54.y - t4.y, a9 = r9 * Math.cos(i8) + s7 * Math.sin(i8), c5 = -r9 * Math.sin(i8) + s7 * Math.cos(i8);\n return Math.hypot(Math.max(Math.abs(a9) - n8 / 2, 0), Math.max(Math.abs(c5) - o10 / 2, 0)) \u003c= e54.radius + 0.000000001;\n};\nvar Hte = (e54, t4, n8, o10, i8) =\u003e {\n const r9 = [e54, t4];\n for (const e60 of r9)\n if (e60.route_type === \"wire\" \u0026\u0026 $te(e60, n8.pcb_port_id))\n return { x: e60.x, y: e60.y };\n for (let e60 = 0;e60 \u003c r9.length; e60++) {\n const t10 = r9[e60], s9 = r9[1 - e60];\n if (t10.route_type === \"wire\" \u0026\u0026 s9.route_type === \"wire\" \u0026\u0026 o10.some((e61) =\u003e e61.pcb_port_id !== n8.pcb_port_id \u0026\u0026 i8.get(e61.pcb_port_id)?.some((e63) =\u003e Yte(t10, e63))))\n return { x: s9.x, y: s9.y };\n }\n if (e54.route_type === \"wire\" \u0026\u0026 t4.route_type === \"wire\") {\n const o11 = Math.hypot(e54.x - n8.x, e54.y - n8.y) \u003c= Math.hypot(t4.x - n8.x, t4.y - n8.y) ? e54 : t4;\n return { x: o11.x, y: o11.y };\n }\n for (const e60 of r9)\n if (e60.route_type === \"wire\")\n return { x: e60.x, y: e60.y };\n const s7 = r9.map((e60) =\u003e e60.route_type === \"through_pad\" ? { x: (e60.start.x + e60.end.x) / 2, y: (e60.start.y + e60.end.y) / 2 } : { x: e60.x, y: e60.y });\n return { x: (s7[0].x + s7[1].x) / 2, y: (s7[0].y + s7[1].y) / 2 };\n};\nvar Vte = (e54) =\u003e {\n const t4 = [], n8 = e54.filter((e60) =\u003e e60.type === \"pcb_port\"), o10 = e54.filter((e60) =\u003e e60.type === \"pcb_trace\"), i8 = e54.filter((e60) =\u003e e60.type === \"source_trace\"), r9 = new Map(i8.map((e60) =\u003e [e60.source_trace_id, e60])), s7 = new Map, a9 = [...e54.filter((e60) =\u003e e60.type === \"pcb_smtpad\"), ...e54.filter((e60) =\u003e e60.type === \"pcb_plated_hole\")];\n for (const e60 of a9) {\n if (!e60.pcb_port_id)\n continue;\n const t10 = s7.get(e60.pcb_port_id);\n t10 ? t10.push(e60) : s7.set(e60.pcb_port_id, [e60]);\n }\n const c5 = e54.find((e60) =\u003e e60.type === \"pcb_board\"), l5 = [\"top\", ...fE.filter((e60) =\u003e e60.startsWith(\"inner\")).slice(0, c5 ? Math.max(0, c5.num_layers - 2) : undefined), ...c5?.num_layers === 1 ? [] : [\"bottom\"]], h5 = Qo(e54), d9 = e54.filter((e60) =\u003e e60.type === \"pcb_via\"), u9 = d9.filter((e60) =\u003e Number.isFinite(e60.outer_diameter) \u0026\u0026 e60.outer_diameter \u003e 0).map((e60) =\u003e ({ id: e60.pcb_via_id, x: e60.x, y: e60.y, radius: e60.outer_diameter / 2, layers: e60.layers, ownerTraceId: e60.pcb_trace_id })), p9 = [...u9], m9 = [];\n for (const e60 of o10)\n for (let t10 = 0;t10 \u003c e60.route.length; t10++) {\n const n10 = e60.route[t10], o11 = e60.route[t10 + 1];\n if (n10.route_type === \"wire\" \u0026\u0026 o11?.route_type === \"wire\" \u0026\u0026 n10.layer === o11.layer \u0026\u0026 m9.push({ trace: e60, start: n10, end: o11 }), n10.route_type !== \"via\")\n continue;\n const i9 = l5.indexOf(n10.from_layer), r10 = l5.indexOf(n10.to_layer);\n if (i9 \u003c 0 || r10 \u003c 0)\n continue;\n const s9 = n10.outer_diameter;\n if (s9 !== undefined \u0026\u0026 (!Number.isFinite(s9) || s9 \u003c= 0))\n continue;\n const a10 = { id: e60.pcb_trace_id, x: n10.x, y: n10.y, radius: s9 === undefined ? undefined : s9 / 2, layers: l5.slice(Math.min(i9, r10), Math.max(i9, r10) + 1), ownerTraceId: e60.pcb_trace_id }, c9 = d9.filter((e61) =\u003e Math.hypot(e61.x - n10.x, e61.y - n10.y) \u003c= 0.000000001);\n c9.length === 0 \u0026\u0026 p9.push(a10), c9.some((t11) =\u003e t11.pcb_trace_id === e60.pcb_trace_id || !t11.pcb_trace_id \u0026\u0026 h5.areIdsConnected(t11.pcb_via_id, e60.pcb_trace_id)) || u9.push(a10);\n }\n const g10 = new Map(n8.map((e60) =\u003e [e60.pcb_port_id, e60])), f10 = (e60, t10) =\u003e {\n const n10 = s7.get(t10.pcb_port_id), o11 = n10?.length ? [...new Set(n10.flatMap((e61) =\u003e e61.type === \"pcb_smtpad\" ? [e61.layer] : e61.layers))] : t10.layers;\n return !!o11.includes(e60.layer) || p9.some((i9) =\u003e {\n if (!i9.layers.includes(e60.layer) || !o11.some((e61) =\u003e i9.layers.includes(e61)))\n return false;\n const r10 = i9.radius === undefined ? 0 : i9.radius + e60.width / 2;\n return !(Math.hypot(e60.x - i9.x, e60.y - i9.y) \u003e r10 + 0.000000001) \u0026\u0026 (n10?.length ? n10.some((e61) =\u003e (e61.type === \"pcb_smtpad\" ? [e61.layer] : e61.layers).some((e63) =\u003e i9.layers.includes(e63)) \u0026\u0026 Xte(i9, e61)) : Math.hypot(t10.x - i9.x, t10.y - i9.y) \u003c= 0.000000001);\n });\n };\n for (const n10 of o10)\n for (const [o11, i9] of n10.route.entries())\n if (i9.route_type === \"wire\")\n for (const r10 of new Set([i9.start_pcb_port_id, i9.end_pcb_port_id])) {\n if (!r10)\n continue;\n const a10 = g10.get(r10);\n if (!a10 || f10(i9, a10))\n continue;\n const c9 = s7.get(r10), l10 = c9?.length ? [...new Set(c9.flatMap((e60) =\u003e e60.type === \"pcb_smtpad\" ? [e60.layer] : e60.layers))] : a10.layers;\n t4.push({ type: \"pcb_trace_error\", error_type: \"pcb_trace_error\", pcb_trace_error_id: `missing_layer_connection_${n10.pcb_trace_id}_${o11}_${a10.pcb_port_id}`, pcb_trace_id: n10.pcb_trace_id, source_trace_id: n10.source_trace_id ?? `!${n10.pcb_trace_id}`, pcb_port_ids: [a10.pcb_port_id], pcb_component_ids: a10.pcb_component_id ? [a10.pcb_component_id] : [], center: { x: i9.x, y: i9.y }, message: `Trace [${oz(e54, n10.pcb_trace_id)}] on ${i9.layer} is missing a via connection to port [${nz(e54, a10.pcb_port_id)}] on ${l10.join(\", \")}.` });\n }\n const _5 = new Map(o10.map((e60) =\u003e [e60.pcb_trace_id, new Set([...s7].filter(([, t10]) =\u003e [e60.route[0], e60.route.at(-1)].some((e61) =\u003e e61 \u0026\u0026 t10.some((t11) =\u003e Yte(e61, t11)))).map(([e61]) =\u003e e61))])), y10 = new Map;\n for (const [e60, t10] of _5)\n for (const n10 of t10) {\n const t11 = y10.get(n10);\n t11 ? t11.push(e60) : y10.set(n10, [e60]);\n }\n const b10 = new Map, x8 = (e60, t10) =\u003e {\n const n10 = b10.get(e60);\n if (n10)\n return n10.has(t10);\n const o11 = [e60], i9 = new Set(o11), r10 = new Set;\n for (;o11.length \u003e 0; ) {\n const e61 = o11.pop();\n for (const t11 of _5.get(e61))\n if (!r10.has(t11)) {\n r10.add(t11);\n for (const e63 of y10.get(t11))\n i9.has(e63) || (i9.add(e63), o11.push(e63));\n }\n }\n for (const e61 of i9)\n b10.set(e61, r10);\n return r10.has(t10);\n };\n let v10;\n const I6 = () =\u003e {\n if (v10)\n return v10;\n const e60 = new Jo({}), t10 = [], n10 = m9.map((e61, t11) =\u003e ({ ...e61, order: t11, minX: Math.min(e61.start.x, e61.end.x) - e61.start.width / 2 - 0.000000001, minY: Math.min(e61.start.y, e61.end.y) - e61.start.width / 2 - 0.000000001, maxX: Math.max(e61.start.x, e61.end.x) + e61.start.width / 2 + 0.000000001, maxY: Math.max(e61.start.y, e61.end.y) + e61.start.width / 2 + 0.000000001 })), i9 = new G().load(n10);\n for (const e61 of n10)\n for (const n11 of i9.search(e61))\n n11.order \u003c= e61.order || n11.trace.pcb_trace_id === e61.trace.pcb_trace_id || n11.start.layer !== e61.start.layer || Fte(e61, n11) \u0026\u0026 t10.push([e61.trace.pcb_trace_id, n11.trace.pcb_trace_id]);\n for (const e61 of o10) {\n for (const n11 of _5.get(e61.pcb_trace_id))\n t10.push([e61.pcb_trace_id, n11]);\n for (const n11 of e61.route)\n if (n11.route_type === \"wire\")\n for (const o11 of new Set([n11.start_pcb_port_id, n11.end_pcb_port_id])) {\n if (!o11)\n continue;\n const i10 = g10.get(o11);\n i10 \u0026\u0026 f10(n11, i10) \u0026\u0026 t10.push([e61.pcb_trace_id, o11]);\n }\n }\n const r10 = [], s9 = (e61, t11, n11, o11, i10 = false) =\u003e {\n if (n11.isEmpty())\n return;\n const s10 = n11.scale(1e6, 1e6), a10 = s10.box;\n r10.push({ id: e61, layers: t11, geometry: { kind: \"polygon\", polygon: s10 }, bridge: o11, platedPort: i10, minX: a10.xmin, minY: a10.ymin, maxX: a10.xmax, maxY: a10.ymax });\n };\n for (const e61 of u9)\n e61.radius !== undefined \u0026\u0026 (s9(e61.id, e61.layers, ZL(e61, e61.radius), true), e61.ownerTraceId \u0026\u0026 t10.push([e61.id, e61.ownerTraceId]));\n for (const e61 of a9)\n e61.type === \"pcb_plated_hole\" \u0026\u0026 e61.pcb_port_id \u0026\u0026 s9(e61.pcb_port_id, e61.layers, QL(e61), true, true);\n for (const e61 of m9) {\n if (e61.trace.route_thickness_mode === \"interpolated\" || e61.start.x === e61.end.x \u0026\u0026 e61.start.y === e61.end.y)\n continue;\n const t11 = e61.start.width / 2;\n !Number.isFinite(t11) || t11 \u003c= 0 ? s9(e61.trace.pcb_trace_id, [e61.start.layer], KL(e61.start, e61.end, e61.start.width), false) : r10.push({ id: e61.trace.pcb_trace_id, layers: [e61.start.layer], geometry: { kind: \"segment\", segment: e61 }, bridge: false, platedPort: false, minX: 1e6 * (Math.min(e61.start.x, e61.end.x) - t11) - 0.1, minY: 1e6 * (Math.min(e61.start.y, e61.end.y) - t11) - 0.1, maxX: 1e6 * (Math.max(e61.start.x, e61.end.x) + t11) + 0.1, maxY: 1e6 * (Math.max(e61.start.y, e61.end.y) + t11) + 0.1 });\n }\n const c9 = (e61) =\u003e {\n const t11 = e61.geometry;\n if (t11.kind === \"polygon\")\n return t11.polygon;\n if (!t11.polygon) {\n const { start: e63, end: n11 } = t11.segment;\n t11.polygon = KL(e63, n11, e63.width).scale(1e6, 1e6);\n }\n return t11.polygon;\n }, l10 = new G().load(r10);\n for (const e61 of r10)\n if (e61.bridge)\n for (const n11 of l10.search({ minX: e61.minX - 0.1, minY: e61.minY - 0.1, maxX: e61.maxX + 0.1, maxY: e61.maxY + 0.1 })) {\n if (n11.id === e61.id || e61.platedPort \u0026\u0026 n11.bridge || n11.platedPort \u0026\u0026 e61.bridge || !n11.layers.some((t11) =\u003e e61.layers.includes(t11)))\n continue;\n const o11 = c9(n11), i10 = o11.box;\n o11.isEmpty() || i10.xmax \u003c e61.minX - 0.1 || i10.ymax \u003c e61.minY - 0.1 || i10.xmin \u003e e61.maxX + 0.1 || i10.ymin \u003e e61.maxY + 0.1 || ez(c9(e61), o11, 0.1) \u0026\u0026 t10.push([e61.id, n11.id]);\n }\n return e60.addConnections(t10), v10 = e60, e60;\n }, S6 = (e60, t10) =\u003e {\n const n10 = t10 === \"start\" ? e60.route[0] : e60.route.at(-1), o11 = ((e61, t11) =\u003e {\n if (e61.route_thickness_mode === \"interpolated\")\n return;\n let n11 = t11 === \"start\" ? 0 : e61.route.length - 2;\n const o12 = t11 === \"start\" ? 1 : -1;\n for (;n11 \u003e= 0 \u0026\u0026 n11 \u003c e61.route.length - 1; ) {\n const t12 = e61.route[n11], i10 = e61.route[n11 + 1];\n if (t12.route_type !== \"wire\" || i10.route_type !== \"wire\" || t12.layer !== i10.layer)\n return;\n if (Math.hypot(t12.x - i10.x, t12.y - i10.y) \u003e 0.000000001)\n return t12.width;\n n11 += o12;\n }\n })(e60, t10);\n if (n10?.route_type !== \"wire\" || o11 === undefined)\n return false;\n const i9 = h5.getNetConnectedToId(e60.pcb_trace_id);\n if (!i9)\n return false;\n const r10 = m9.filter((e61) =\u003e e61.trace.route_thickness_mode !== \"interpolated\" \u0026\u0026 h5.getNetConnectedToId(e61.trace.pcb_trace_id) === i9 \u0026\u0026 Math.hypot(e61.start.x - e61.end.x, e61.start.y - e61.end.y) \u003e 0.000000001);\n return !!r10.some((t11) =\u003e t11.trace.pcb_trace_id !== e60.pcb_trace_id \u0026\u0026 t11.start.layer === n10.layer \u0026\u0026 pe(n10, t11.start, t11.end) \u003c= (o11 + t11.start.width) / 2 + 0.000000001) || !(!Number.isFinite(o11) || o11 \u003c= 0) \u0026\u0026 u9.some((t11) =\u003e {\n if (t11.ownerTraceId === e60.pcb_trace_id || !t11.layers.includes(n10.layer) || h5.getNetConnectedToId(t11.id) !== i9)\n return false;\n const s9 = t11.radius === undefined ? 0 : t11.radius + o11 / 2;\n return !(Math.hypot(n10.x - t11.x, n10.y - t11.y) \u003e s9 + 0.000000001) \u0026\u0026 (!!a9.some((e61) =\u003e h5.getNetConnectedToId(jL(e61)) === i9 \u0026\u0026 (e61.type === \"pcb_smtpad\" ? [e61.layer] : e61.layers).some((e63) =\u003e t11.layers.includes(e63)) \u0026\u0026 Xte(t11, e61)) || r10.some((n11) =\u003e n11.trace.pcb_trace_id !== e60.pcb_trace_id \u0026\u0026 t11.layers.includes(n11.start.layer) \u0026\u0026 Number.isFinite(n11.start.width) \u0026\u0026 n11.start.width \u003e 0 \u0026\u0026 pe(t11, n11.start, n11.end) \u003c= (t11.radius === undefined ? 0 : t11.radius + n11.start.width / 2) + 0.000000001));\n });\n }, C = new Set;\n for (const i9 of o10) {\n if (i9.route.length === 0)\n continue;\n const o11 = i9.route[0], a10 = i9.route.at(-1), c9 = r9.get(i9.source_trace_id), h9 = c9 ? n8.filter((e60) =\u003e c9.connected_source_port_ids?.includes(e60.source_port_id)) : [];\n let u10;\n const p10 = { type: \"pcb_trace_error\", error_type: \"pcb_trace_error\", source_trace_id: c9?.source_trace_id || i9.source_trace_id || `!${i9.pcb_trace_id}`, pcb_trace_id: i9.pcb_trace_id, pcb_component_ids: [] };\n for (let n10 = 1;n10 \u003c i9.route.length - 1; n10++) {\n const o12 = i9.route[n10 - 1], r10 = i9.route[n10], s9 = i9.route[n10 + 1];\n if (r10.route_type !== \"via\" || o12.route_type !== \"wire\" || s9.route_type !== \"wire\")\n continue;\n const a11 = l5.indexOf(r10.from_layer), c10 = l5.indexOf(r10.to_layer), h10 = d9.filter((e60) =\u003e e60.pcb_trace_id === i9.pcb_trace_id \u0026\u0026 Math.abs(e60.x - r10.x) \u003c 0.01 \u0026\u0026 Math.abs(e60.y - r10.y) \u003c 0.01), m11 = h10.length \u003e 0 ? h10.map((e60) =\u003e e60.layers) : [l5.slice(Math.min(a11, c10), Math.max(a11, c10) + 1)], g12 = Math.abs(o12.x - r10.x) \u003c 0.01 \u0026\u0026 Math.abs(o12.y - r10.y) \u003c 0.01, f11 = Math.abs(s9.x - r10.x) \u003c 0.01 \u0026\u0026 Math.abs(s9.y - r10.y) \u003c 0.01;\n a11 \u003e= 0 \u0026\u0026 c10 \u003e= 0 \u0026\u0026 l5.includes(o12.layer) \u0026\u0026 l5.includes(s9.layer) \u0026\u0026 m11.some((e60) =\u003e e60.includes(o12.layer) \u0026\u0026 e60.includes(s9.layer)) \u0026\u0026 (g12 || o12.layer === r10.from_layer) \u0026\u0026 (f11 || s9.layer === r10.to_layer) || (u10 ??= oz(e54, i9.pcb_trace_id), t4.push({ ...p10, message: `Via in trace [${u10}] does not connect its adjacent wire layers at position {x: ${r10.x}, y: ${r10.y}}.`, pcb_trace_error_id: `misaligned_via_${i9.pcb_trace_id}_${n10}`, pcb_port_ids: [] }));\n }\n if (c9 \u0026\u0026 h9.length \u003e 0) {\n if (C.has(c9.source_trace_id))\n continue;\n C.add(c9.source_trace_id);\n }\n for (const n10 of h9) {\n const r10 = s7.get(n10.pcb_port_id);\n if (!r10?.length)\n continue;\n if ([o11, a10].some((e60) =\u003e r10.some((t10) =\u003e Yte(e60, t10))))\n continue;\n if (x8(i9.pcb_trace_id, n10.pcb_port_id))\n continue;\n const c10 = I6(), l10 = c10.getNetConnectedToId(i9.pcb_trace_id);\n if (l10 !== undefined \u0026\u0026 c10.getIdsConnectedToNet(l10).some((e60) =\u003e _5.get(e60)?.has(n10.pcb_port_id)))\n continue;\n const d10 = nz(e54, n10.pcb_port_id);\n u10 ??= oz(e54, i9.pcb_trace_id), t4.push({ ...p10, message: `Trace [${u10}] is missing a connection to ${r10[0].type === \"pcb_smtpad\" ? \"SMD pad\" : \"through-hole pad\"} ${d10}`, pcb_trace_error_id: `missing_connection_${i9.pcb_trace_id}_${n10.pcb_port_id}`, center: Hte(o11, a10, n10, h9, s7), pcb_port_ids: [n10.pcb_port_id] });\n }\n if (h9.length \u003e 0)\n continue;\n const m10 = [...s7.values()].some((e60) =\u003e e60.some((e61) =\u003e Yte(o11, e61))) || S6(i9, \"start\"), g11 = o11.route_type === \"wire\" \u0026\u0026 a10.route_type === \"wire\" \u0026\u0026 o11.layer === a10.layer \u0026\u0026 Math.hypot(o11.x - a10.x, o11.y - a10.y) \u003c= 0.000000001;\n for (const [n10, r10] of [o11, a10].entries())\n r10.route_type === \"wire\" \u0026\u0026 (n10 === 1 \u0026\u0026 g11 \u0026\u0026 !m10 || [...s7.values()].some((e60) =\u003e e60.some((e61) =\u003e Yte(r10, e61))) || S6(i9, n10 === 0 ? \"start\" : \"end\") || (u10 ??= oz(e54, i9.pcb_trace_id), t4.push({ ...p10, message: `Trace [${u10}] has disconnected endpoint at (${r10.x.toFixed(2)}, ${r10.y.toFixed(2)})`, pcb_trace_error_id: `disconnected_endpoint_${i9.pcb_trace_id}_${n10 === 0 ? \"start\" : \"end\"}`, center: { x: r10.x, y: r10.y }, pcb_port_ids: [] })));\n }\n return t4;\n};\nvar Wte = (e54, t4) =\u003e {\n const n8 = new Set(t4.flatMap((e60) =\u003e e60.__replaces_pcb_trace_id ? [e60.__replaces_pcb_trace_id] : []));\n return [...e54.filter((e60) =\u003e !n8.has(e60.pcb_trace_id)), ...t4];\n};\nvar Gte = ({ inputSrj: e54, srjWithPointPairs: t4, drcOptions: n8 = {}, includeBoardClearance: o10 = false, connectivityMaps: i8 }) =\u003e {\n const r9 = { minTraceWidth: e54.minTraceWidth, minViaDiameter: e54.minViaDiameter, originalSrj: e54, includeOriginalConnections: true, connectivityMaps: i8 }, s7 = o10 ? rR({ ...e54, minBoardEdgeClearance: e54.minBoardEdgeClearance ?? 0 }) : undefined, a9 = sR(t4, [], r9);\n s7 \u0026\u0026 a9.push(s7);\n const c5 = dz(a9, { traceClearance: n8.traceClearance ?? hR, holeClearance: n8.holeClearance ?? e54.minTraceToHoleEdgeClearance }), l5 = uz(a9, { allowViaInPad: e54.allowViaInPad, minClearance: n8.viaToPadClearance ?? vte(e54) });\n return (o11, i9 = {}) =\u003e {\n const a10 = Wte(e54.traces ?? [], o11), h5 = sR(t4, a10, r9);\n s7 \u0026\u0026 h5.push(s7);\n const d9 = qy(h5);\n aR(h5);\n const u9 = c5(h5, d9), p9 = [...u9.traceErrors, ...lR(h5, { board: s7 }), ...(i9.includeTraceContinuity ?? n8.includeTraceContinuity) === false ? [] : Vte(h5), ...n8.includeTypedTraceClearance === false ? [] : [...u9.viaErrors, ...u9.padErrors], ...u9.holeErrors, ...l5(h5, d9), ...rz(h5, d9, { viaClearance: n8.viaClearance ?? dR })], m9 = new Map(h5.flatMap((e60) =\u003e e60.type === \"pcb_via\" ? [[e60.pcb_via_id, e60]] : [])), g10 = p9.map((e60) =\u003e {\n if (e60.type === \"pcb_via_trace_clearance_error\") {\n const t10 = m9.get(e60.pcb_via_id);\n if (t10)\n return { ...e60, center: { x: t10.x, y: t10.y } };\n }\n return e60.center ? e60 : e60.pcb_center ? { ...e60, center: e60.pcb_center } : e60;\n });\n return { circuitJson: h5, errors: p9, errorsWithCenters: g10, locationAwareErrors: g10.filter((e60) =\u003e Boolean(e60.center)) };\n };\n};\nvar Zte = class extends ni {\n constructor(e54) {\n super(), this.input = e54;\n }\n static solverName = \"Pipeline9HighDensityForceImproveSampleSolver\";\n output;\n _step() {\n const e54 = new SZ(this.input), t4 = e54.sampleEntries[0];\n if (this.input.nodeWithPortPoints.length !== 1 || e54.sampleEntries.length !== 1 || t4.routeIndexes.length !== this.input.hdRoutes.length || t4.routeIndexes.some((e60, t10) =\u003e e60 !== t10))\n throw new Error(\"Force-improve task must contain one preassigned node\");\n if (e54.step(), !e54.solved || e54.failed || e54.iterations !== 1)\n throw new Error(\"Force-improve node must complete in one step\");\n this.output = { routes: e54.getOutput(), latestVisualization: e54.latestVisualization }, this.solved = true;\n }\n getOutput() {\n if (!this.output)\n throw new Error(\"Force-improve node has not completed\");\n return this.output;\n }\n};\nSolverRuntime.registerSolver(Zte);\nvar qte = class extends SZ {\n asyncRunning = false;\n completedSample;\n async solveAsync(e54, t4 = 1 / 0) {\n if (this.asyncRunning)\n throw new Error(\"High-density force improvement solveAsync is already running\");\n if (this.solved || this.failed || this.iterations \u003e= t4)\n return;\n const n8 = performance.now();\n this.asyncRunning = true;\n try {\n if (e54 === undefined)\n return void this.solveUntilIteration(t4);\n const n10 = Math.max(0, Math.floor(Math.min(this.MAX_ITERATIONS, t4) - this.iterations)), o10 = this.sampleEntries.slice(this.activeSampleIndex, this.activeSampleIndex + n10).map((t10) =\u003e e54.executeAsync(Zte, { nodeWithPortPoints: [t10.node], hdRoutes: t10.routeIndexes.map((e60) =\u003e this.originalHdRoutes[e60]), totalStepsPerNode: this.totalStepsPerNode, nodeAssignmentMargin: this.nodeAssignmentMargin, colorMap: Object.fromEntries(t10.routeIndexes.map((e60) =\u003e {\n const t11 = this.originalHdRoutes[e60].connectionName;\n return [t11, this.colorMap[t11]];\n })) }).then((e60) =\u003e ({ type: \"result\", result: e60 }), (e60) =\u003e ({ type: \"error\", error: e60 })));\n for (const e60 of o10) {\n if (this.solved || this.failed || this.iterations \u003e= Math.min(this.MAX_ITERATIONS, t4))\n break;\n const n11 = await e60;\n if (n11.type === \"error\")\n throw n11.error;\n this.completedSample = n11.result, this.step();\n }\n this.solveUntilIteration(t4);\n } catch (e60) {\n throw this.failed = true, this.error = `High-density force improvement runtime error: ${e60}`, e60;\n } finally {\n this.completedSample = undefined, this.asyncRunning = false, this.timeToSolve = performance.now() - n8;\n }\n }\n solveUntilIteration(e54) {\n for (;!this.solved \u0026\u0026 !this.failed \u0026\u0026 this.iterations \u003c e54; )\n this.step();\n }\n _step() {\n const e54 = this.completedSample;\n if (!e54)\n return void super._step();\n this.completedSample = undefined;\n const t4 = this.sampleEntries[this.activeSampleIndex];\n if (!t4 || e54.routes.length !== t4.routeIndexes.length)\n throw new Error(\"Force-improve result does not match the current node\");\n for (const [n8, o10] of t4.routeIndexes.entries())\n this.improvedRoutesByIndex.set(o10, e54.routes[n8]);\n this.latestVisualization = e54.latestVisualization, this.activeSampleIndex += 1, this.stats = { nodeAssignmentMargin: this.nodeAssignmentMargin, sampleCount: this.sampleEntries.length, improvedNodeCount: this.activeSampleIndex, improvedRouteCount: this.improvedRoutesByIndex.size, totalStepsPerNode: this.totalStepsPerNode }, this.activeSampleIndex \u003e= this.sampleEntries.length \u0026\u0026 (this.solved = true);\n }\n};\nvar Jte = (e54, t4) =\u003e {\n const n8 = e54.filter((e60) =\u003e (e60.rootConnectionName ?? e60.connectionName) === t4);\n if (n8.length !== 0)\n return n8.reduce((e60, t10) =\u003e e60 + t10.route.slice(1).reduce((e61, n10, o10) =\u003e {\n const i8 = t10.route[o10];\n return e61 + Math.hypot(n10.x - i8.x, n10.y - i8.y);\n }, 0), 0);\n};\nvar Qte = (e54, t4) =\u003e {\n const n8 = new Set(e54.flatMap((e60) =\u003e e60.maxLengthSkew === undefined ? [] : e60.connectionNames));\n return t4.flatMap((e60) =\u003e {\n if (!n8.has(e60.name))\n return [];\n const t10 = e60.pointsToConnect[0], o10 = e60.pointsToConnect.at(-1);\n if (!t10 || !o10 || t10 === o10)\n throw new Error(`Length matching: bus connection \"${e60.name}\" needs at least two points`);\n return [{ ...e60, pointsToConnect: [t10, o10] }];\n });\n};\nvar Kte = class extends ni {\n constructor(e54) {\n super(), this.params = e54, this.differentialPairSolver = new o9({ hdRoutes: e54.hdRoutes, differentialPairs: e54.differentialPairs, traces: e54.traces, obstacles: e54.obstacles, bounds: e54.bounds, layerCount: e54.layerCount, minTraceToPadEdgeClearance: e54.obstacleMargin }), this.MAX_ITERATIONS = this.differentialPairSolver.MAX_ITERATIONS + 1e5 + 10;\n }\n differentialPairSolver;\n busLengthMatchingSolver;\n outputHdRoutes;\n getSolverName() {\n return \"LengthMatchingPostProcessingSolver\";\n }\n _step() {\n if (!this.differentialPairSolver.solved)\n return this.differentialPairSolver.step(), void (this.differentialPairSolver.failed \u0026\u0026 (this.failed = true, this.error = this.differentialPairSolver.error));\n if (!this.busLengthMatchingSolver) {\n const n8 = this.differentialPairSolver.getOutput().hdRoutes, o10 = (e54 = this.params.buses, t4 = n8, e54.flatMap((e60) =\u003e {\n const n10 = e60.maxLengthSkew;\n if (n10 === undefined || e60.connectionNames.length \u003c 2)\n return [];\n const o11 = e60.connectionNames.map((n11) =\u003e {\n const o12 = Jte(t4, n11);\n if (o12 === undefined)\n throw new Error(`Length matching: bus \"${e60.busId}\" has no routed geometry for connection \"${n11}\"`);\n return { connectionName: n11, length: o12 };\n }), i8 = o11.reduce((e61, t10) =\u003e t10.length \u003e e61.length ? t10 : e61);\n return o11.flatMap((e61) =\u003e e61.connectionName === i8.connectionName ? [] : [{ connectionNames: [e61.connectionName, i8.connectionName], lengthTolerance: n10 }]);\n }));\n return o10.length === 0 ? (this.outputHdRoutes = n8, void (this.solved = true)) : void (this.busLengthMatchingSolver = new v6({ hdRoutes: n8, originalConnections: Qte(this.params.buses, this.params.connections), differentialPairs: o10, traces: this.params.traces, obstacles: this.params.obstacles, bounds: this.params.bounds, layerCount: this.params.layerCount, obstacleMargin: this.params.obstacleMargin }));\n }\n var e54, t4;\n if (this.busLengthMatchingSolver.step(), this.busLengthMatchingSolver.failed)\n return this.failed = true, void (this.error = this.busLengthMatchingSolver.error);\n this.busLengthMatchingSolver.solved \u0026\u0026 (this.outputHdRoutes = this.busLengthMatchingSolver.getOutput().matchedHdRoutes, ((e60, t10) =\u003e {\n for (const n8 of e60) {\n if (n8.maxLengthSkew === undefined || n8.connectionNames.length \u003c 2)\n continue;\n const e61 = n8.connectionNames.map((e63) =\u003e {\n const o11 = Jte(t10, e63);\n if (o11 === undefined)\n throw new Error(`Length matching: bus \"${n8.busId}\" lost routed geometry for connection \"${e63}\"`);\n return o11;\n }), o10 = Math.max(...e61) - Math.min(...e61);\n if (o10 \u003e n8.maxLengthSkew + 0.000001)\n throw new Error(`Length matching: bus \"${n8.busId}\" routed length skew ${o10.toFixed(4)}mm exceeds ${n8.maxLengthSkew.toFixed(4)}mm`);\n }\n })(this.params.buses, this.outputHdRoutes), this.solved = true);\n }\n getOutput() {\n if (!this.solved || !this.outputHdRoutes)\n throw new Error(\"LengthMatchingPostProcessingSolver output requested before completion\");\n return { hdRoutes: this.outputHdRoutes };\n }\n visualize() {\n return this.busLengthMatchingSolver?.visualize() ?? this.differentialPairSolver.visualize();\n }\n};\nvar ene = 0.000000001;\nvar tne = (e54, t4) =\u003e Math.abs(e54.x - t4.x) \u003c= ene \u0026\u0026 Math.abs(e54.y - t4.y) \u003c= ene \u0026\u0026 e54.z === t4.z;\nvar nne = (e54, t4) =\u003e {\n if (e54.length === 0)\n return void e54.push(...t4.route);\n const n8 = e54.at(-1);\n if (t4.route[0] \u0026\u0026 tne(n8, t4.route[0]))\n e54.push(...t4.route.slice(1));\n else {\n if (!t4.route.at(-1) || !tne(n8, t4.route.at(-1)))\n throw new Error(`Pipeline9 could not reconnect mutated preloaded segment \"${t4.connectionName}\"`);\n e54.push(...t4.route.slice(0, -1).reverse());\n }\n};\nvar one = (e54, t4) =\u003e {\n const n8 = e54.preloadedRoutePositionStart ?? e54.preloadedRouteIndex, o10 = t4.preloadedRoutePositionStart ?? t4.preloadedRouteIndex, i8 = e54.preloadedRoutePositionEnd ?? n8, r9 = t4.preloadedRoutePositionEnd ?? o10;\n return n8 - o10 || i8 - r9 || e54.preloadedRouteIndex - t4.preloadedRouteIndex || e54.connectionName.localeCompare(t4.connectionName);\n};\nvar ine = (e54) =\u003e {\n const t4 = e54.route.flatMap((e60) =\u003e e60.route_type === \"wire\" || e60.route_type === \"through_obstacle\" ? [e60.width] : []);\n return t4.length \u003e 0 ? Math.max(...t4) : undefined;\n};\nvar rne = ({ trace: e54, updatedTraceRoutes: t4, layerCount: n8, defaultViaHoleDiameter: o10, obstacles: i8, connMap: r9 }) =\u003e {\n if (t4.length === 0)\n throw new Error(`Pipeline9 lost every fixed route for mutated trace \"${e54.pcb_trace_id}\"`);\n const s7 = [];\n let a9, c5 = 0, l5 = 0;\n for (const e60 of [...t4].sort(one))\n nne(s7, e60), c5 = Math.max(c5, e60.traceThickness), l5 = Math.max(l5, e60.viaDiameter), a9 ??= e60.rootConnectionName;\n const h5 = { connectionName: e54.connection_name, rootConnectionName: a9, traceThickness: ine(e54) ?? c5, viaDiameter: l5, route: s7, vias: s7.slice(0, -1).flatMap((e60, t10) =\u003e {\n const n10 = s7[t10 + 1];\n return e60.z !== n10.z \u0026\u0026 Math.abs(e60.x - n10.x) \u003c= ene \u0026\u0026 Math.abs(e60.y - n10.y) \u003c= ene ? [{ x: n10.x, y: n10.y }] : [];\n }) };\n return Ro(h5, n8, { defaultViaHoleDiameter: o10, obstacles: i8, connMap: r9 });\n};\nvar sne = (e54, t4) =\u003e e54.filter((e60) =\u003e {\n if (e60.isThroughObstacle === true)\n return false;\n const { preloadedRoutePositionStart: n8, preloadedRoutePositionEnd: o10 } = e60;\n if (n8 === undefined || o10 === undefined)\n throw new Error(`Pipeline9 fixed route \"${e60.connectionName}\" is missing route-position metadata`);\n const i8 = Math.min(n8, o10), r9 = Math.max(n8, o10);\n return i8 \u003e= t4.routePositionStart - ene \u0026\u0026 r9 \u003c= t4.routePositionEnd + ene;\n});\nvar ane = ({ trace: e54, originalTraceRoutes: t4, updatedTraceRoutes: n8, layerCount: o10, defaultViaHoleDiameter: i8, obstacles: r9, connMap: s7 }) =\u003e {\n if (n8.length === 0)\n throw new Error(`Pipeline9 lost every fixed route for mutated trace \"${e54.pcb_trace_id}\"`);\n const a9 = ((e60) =\u003e {\n const t10 = [];\n let n10 = 0;\n for (let o11 = 0;o11 \u003c e60.route.length; o11++)\n e60.route[o11]?.route_type === \"through_obstacle\" \u0026\u0026 (n10 \u003c o11 \u0026\u0026 t10.push({ routePositionStart: n10, routePositionEnd: o11 - 1 }), n10 = o11 + 1);\n return n10 \u003c e60.route.length \u0026\u0026 t10.push({ routePositionStart: n10, routePositionEnd: e60.route.length - 1 }), t10;\n })(e54), c5 = n8.filter((e60) =\u003e e60.isThroughObstacle !== true);\n for (const e60 of c5) {\n if (a9.filter((t10) =\u003e sne([e60], t10).includes(e60)).length !== 1)\n throw new Error(`Pipeline9 fixed route \"${e60.connectionName}\" crosses an immutable through-obstacle primitive`);\n }\n const l5 = [];\n let h5 = 0;\n for (const c9 of a9) {\n l5.push(...e54.route.slice(h5, c9.routePositionStart));\n const a10 = sne(t4, c9), d9 = sne(n8, c9);\n if (a10.length \u003e 0 \u0026\u0026 d9.length === 0)\n throw new Error(`Pipeline9 lost every fixed route for an ordinary section of mutated trace \"${e54.pcb_trace_id}\"`);\n l5.push(...d9.length \u003e 0 ? rne({ trace: e54, updatedTraceRoutes: d9, layerCount: o10, defaultViaHoleDiameter: i8, obstacles: r9, connMap: s7 }) : e54.route.slice(c9.routePositionStart, c9.routePositionEnd + 1)), h5 = c9.routePositionEnd + 1;\n }\n return l5.push(...e54.route.slice(h5)), l5;\n};\nvar cne = (e54, t4) =\u003e {\n const n8 = new Set(t4.map((e60) =\u003e e60.pcb_trace_id));\n return e54.map((e60) =\u003e {\n if (!n8.has(e60.pcb_trace_id))\n return n8.add(e60.pcb_trace_id), e60;\n const t10 = `${e60.pcb_trace_id}_routed`;\n let o10 = t10, i8 = 2;\n for (;n8.has(o10); )\n o10 = `${t10}_${i8}`, i8 += 1;\n return n8.add(o10), { ...e60, pcb_trace_id: o10 };\n });\n};\nvar lne = (e54, t4, n8) =\u003e {\n const o10 = (e60) =\u003e `${e60.x}:${e60.y}`, i8 = new Map;\n for (const e60 of t4) {\n const t10 = o10(e60.center), n10 = i8.get(t10) ?? [];\n n10.push(e60), i8.set(t10, n10);\n }\n const r9 = new Map;\n for (const t10 of e54)\n for (const e60 of t10.pointsToConnect) {\n if (!e60.pcb_port_id)\n continue;\n const t11 = r9.get(e60.pcb_port_id) ?? new Set, s7 = So(e60);\n for (const e61 of s7)\n t11.add(mo(e61, n8));\n for (const r10 of i8.get(o10(e60)) ?? [])\n if (!(r10.layers.length \u003c= 1) \u0026\u0026 r10.connectedTo.includes(e60.pcb_port_id))\n for (const e61 of r10.layers)\n t11.add(mo(e61, n8));\n r9.set(e60.pcb_port_id, t11);\n }\n return r9;\n};\nvar hne = (e54, t4) =\u003e new Map(e54.flatMap((e60) =\u003e {\n const n8 = t4.getNetConnectedToId(e60.connectionName) ?? (e60.rootConnectionName ? t4.getNetConnectedToId(e60.rootConnectionName) ?? (t4.netMap[e60.rootConnectionName] ? e60.rootConnectionName : undefined) : undefined);\n return n8 ? [[e60.connectionName, n8]] : [];\n}));\nvar dne = 0.000000001;\nvar une = 0.000001;\nvar pne = (e54, t4) =\u003e Math.abs(e54.x - t4.x) \u003c= une \u0026\u0026 Math.abs(e54.y - t4.y) \u003c= une \u0026\u0026 e54.z === t4.z;\nvar mne = (e54) =\u003e new Map(e54.map((e60, t4) =\u003e [e60.pcb_trace_id, t4]));\nvar gne = (e54, t4) =\u003e {\n const n8 = e54[0], o10 = e54.at(-1);\n if (!n8 || !o10)\n throw new Error(\"Pipeline9 cannot split an empty preloaded route\");\n if (n8.z !== o10.z)\n throw new Error(\"Pipeline9 cannot partially split a preloaded layer transition\");\n return { ...n8, x: n8.x + (o10.x - n8.x) * t4, y: n8.y + (o10.y - n8.y) * t4 };\n};\nvar fne = ({ traces: e54, fixedHdRoutes: t4, sections: n8 }) =\u003e {\n const o10 = (({ traces: e60, sections: t10 }) =\u003e {\n const n10 = mne(e60), o11 = new Map;\n for (const e61 of t10) {\n const t11 = n10.get(e61.traceId);\n if (t11 === undefined)\n throw new Error(`Pipeline9 hypergraph changed missing preloaded trace \"${e61.traceId}\"`);\n const i8 = o11.get(t11) ?? [];\n i8.push({ start: Math.min(e61.startRoutePosition, e61.endRoutePosition), end: Math.max(e61.startRoutePosition, e61.endRoutePosition) }), o11.set(t11, i8);\n }\n for (const e61 of o11.values())\n e61.sort((e63, t11) =\u003e e63.start - t11.start || e63.end - t11.end);\n return o11;\n })({ traces: e54, sections: n8 });\n return t4.flatMap((e60) =\u003e {\n const t10 = o10.get(e60.preloadedTraceIndex);\n if (!t10?.length)\n return [e60];\n const { preloadedRoutePositionStart: n10, preloadedRoutePositionEnd: i8 } = e60;\n if (n10 === undefined || i8 === undefined)\n throw new Error(`Pipeline9 fixed route \"${e60.connectionName}\" is missing route-position metadata`);\n if (Math.abs(i8 - n10) \u003c= dne)\n return t10.some((e61) =\u003e e61.start - dne \u003c= n10 \u0026\u0026 n10 \u003c= e61.end + dne) ? [] : [e60];\n let r9 = [{ start: n10, end: i8 }];\n for (const e61 of t10)\n r9 = r9.flatMap((t11) =\u003e {\n if (e61.end \u003c= t11.start + dne || e61.start \u003e= t11.end - dne)\n return [t11];\n const n11 = [];\n return e61.start \u003e t11.start + dne \u0026\u0026 n11.push({ start: t11.start, end: Math.min(e61.start, t11.end) }), e61.end \u003c t11.end - dne \u0026\u0026 n11.push({ start: Math.max(e61.end, t11.start), end: t11.end }), n11;\n });\n return r9.map((t11, o11) =\u003e {\n const r10 = (t11.start - n10) / (i8 - n10), s7 = (t11.end - n10) / (i8 - n10);\n return { ...e60, connectionName: `${e60.connectionName}_hypergraph_fixed_${o11}`, preloadedRoutePositionStart: t11.start, preloadedRoutePositionEnd: t11.end, route: [gne(e60.route, r10), gne(e60.route, s7)], vias: [] };\n });\n });\n};\nvar _ne = ({ traces: e54, sections: t4, stitchedHdRoutes: n8, layerCount: o10 }) =\u003e {\n const i8 = mne(e54);\n return t4.map((e60, r9) =\u003e {\n const s7 = i8.get(e60.traceId);\n if (s7 === undefined)\n throw new Error(`Pipeline9 cannot materialize missing preloaded trace \"${e60.traceId}\"`);\n const [a9, c5] = ((e61, t10) =\u003e {\n const n10 = e61.connection.pointsToConnect.map((e63) =\u003e ({ x: e63.x, y: e63.y, z: mo(Io(e63), t10) }));\n if (!n10[0] || !n10[1])\n throw new Error(`Pipeline9 changed section \"${e61.connectionName}\" is missing an endpoint`);\n return [n10[0], n10[1]];\n })(e60, o10), l5 = n8.flatMap((t10) =\u003e {\n if (t10.connectionName !== e60.connectionName)\n return [];\n const n10 = (({ route: e61, sectionStart: t11, sectionEnd: n11 }) =\u003e {\n const o11 = e61.route[0], i9 = e61.route.at(-1);\n if (!o11 || !i9)\n return null;\n const r10 = o11.z === t11.z \u0026\u0026 i9.z === n11.z, s9 = o11.z === n11.z \u0026\u0026 i9.z === t11.z, a10 = r10 ? me(o11, t11) + me(i9, n11) : Number.POSITIVE_INFINITY, c9 = s9 ? me(o11, n11) + me(i9, t11) : Number.POSITIVE_INFINITY;\n return Number.isFinite(a10) || Number.isFinite(c9) ? a10 \u003c= c9 ? { score: a10, reverse: false } : { score: c9, reverse: true } : null;\n })({ route: t10, sectionStart: a9, sectionEnd: c5 });\n return n10 ? [{ route: t10, ...n10 }] : [];\n });\n l5.sort((e61, t10) =\u003e e61.score - t10.score);\n const h5 = l5[0], d9 = l5[1];\n if (!h5 || d9 \u0026\u0026 Math.abs(d9.score - h5.score) \u003c= une)\n throw new Error(`Pipeline9 expected one nearest stitched route for changed preloaded section \"${e60.connectionName}\", got ${l5.length}`);\n const u9 = (({ route: e61, reverse: t10, sectionStart: n10, sectionEnd: o11 }) =\u003e {\n const i9 = t10 ? ((e63) =\u003e {\n const t11 = [...e63].reverse().map((e64) =\u003e {\n const { toNextSegmentType: t12, ...n11 } = e64;\n return n11;\n });\n for (let n11 = 0;n11 \u003c e63.length - 1; n11++) {\n const o12 = e63[n11]?.toNextSegmentType;\n o12 \u0026\u0026 (t11[e63.length - n11 - 2] = { ...t11[e63.length - n11 - 2], toNextSegmentType: o12 });\n }\n return t11;\n })(e61.route) : [...e61.route];\n if (!i9[0] || !i9.at(-1))\n throw new Error(`Pipeline9 cannot materialize empty route \"${e61.connectionName}\"`);\n return pne(i9[0], n10) || i9.unshift(n10), pne(i9.at(-1), o11) || i9.push(o11), { ...e61, route: i9 };\n })({ route: h5.route, reverse: h5.reverse, sectionStart: a9, sectionEnd: c5 });\n return { ...u9, preloadedTraceIndex: s7, preloadedRouteIndex: Number.MAX_SAFE_INTEGER - t4.length + r9, preloadedRoutePositionStart: e60.startRoutePosition, preloadedRoutePositionEnd: e60.endRoutePosition, isThroughObstacle: false };\n });\n};\nvar yne = (e54) =\u003e e54.map((e60) =\u003e {\n const t4 = [];\n for (const n8 of e60.route) {\n const o10 = t4.at(-1);\n if (!o10 || o10.z === n8.z || o10.toNextSegmentType === \"through_obstacle\") {\n t4.push(n8);\n continue;\n }\n const i8 = ts({ hdRoute: e60, start: o10, end: n8 });\n i8 !== \"colocated\" ? (i8 === \"start\" ? t4.push({ x: o10.x, y: o10.y, z: n8.z }) : t4.push({ x: n8.x, y: n8.y, z: o10.z }), t4.push(n8)) : t4.push(n8);\n }\n return { ...e60, route: t4 };\n});\nvar bne = (e54) =\u003e yne(e54).map((e60) =\u003e ({ ...e60, route: e60.route.flatMap((t4, n8) =\u003e {\n const o10 = e60.route[n8 - 1];\n return !o10 || o10.z === t4.z || o10.toNextSegmentType === \"through_obstacle\" || o10.x === t4.x \u0026\u0026 o10.y === t4.y ? [t4] : [{ x: t4.x, y: t4.y, z: o10.z }, t4];\n}) }));\nvar xne = (e54) =\u003e {\n const t4 = new Map;\n for (const n8 of e54)\n n8.regionId \u0026\u0026 t4.set(n8.regionId, (t4.get(n8.regionId) ?? 0) + n8.route.length);\n return e54.map((e60) =\u003e {\n if (!e60.regionId || t4.get(e60.regionId) \u003c 4096)\n return e60;\n const n8 = [], o10 = [];\n for (const [t10, i9] of e60.route.entries()) {\n for (;n8.length \u003e= 2; ) {\n const t11 = n8[n8.length - 2], r9 = n8[n8.length - 1];\n if (t11.z !== r9.z || r9.z !== i9.z || t11.toNextSegmentType || t11.traceThickness !== undefined || Object.keys(r9).some((e61) =\u003e e61 !== \"x\" \u0026\u0026 e61 !== \"y\" \u0026\u0026 e61 !== \"z\") || e60.vias.some((e61) =\u003e Math.hypot(e61.x - r9.x, e61.y - r9.y) \u003c 0.000000001))\n break;\n const s7 = r9.x - t11.x, a9 = r9.y - t11.y, c5 = i9.x - r9.x, l5 = i9.y - r9.y, h5 = Math.hypot(i9.x - t11.x, i9.y - t11.y);\n if (h5 === 0 || s7 * c5 + a9 * l5 \u003c 0 || Math.abs(s7 * l5 - a9 * c5) \u003e 0.000000001 * h5)\n break;\n n8.pop(), o10.pop();\n }\n n8.push(i9), o10.push(t10);\n }\n const i8 = [];\n for (let t10 = 0;t10 \u003c n8.length; t10++) {\n const r9 = n8[t10];\n if (n8[t10 - 1]) {\n const n10 = o10[t10 - 1], r10 = o10[t10];\n r10 - n10 \u003c 64 \u0026\u0026 i8.push(...e60.route.slice(n10 + 1, r10));\n }\n i8.push(r9);\n }\n return { ...e60, route: i8 };\n });\n};\nvar vne = 0.000000001;\nvar Ine = (e54) =\u003e ({ minX: e54.center.x - e54.width / 2, maxX: e54.center.x + e54.width / 2, minY: e54.center.y - e54.height / 2, maxY: e54.center.y + e54.height / 2 });\nvar Sne = (e54, t4) =\u003e e54.x \u003e= t4.minX - vne \u0026\u0026 e54.x \u003c= t4.maxX + vne \u0026\u0026 e54.y \u003e= t4.minY - vne \u0026\u0026 e54.y \u003c= t4.maxY + vne;\nvar Cne = (e54, t4, n8) =\u003e n8 \u003c= vne ? e54 : n8 \u003e= 0.999999999 ? t4 : { x: e54.x + (t4.x - e54.x) * n8, y: e54.y + (t4.y - e54.y) * n8, z: e54.z };\nvar Pne = (e54, t4, n8) =\u003e {\n const o10 = t4.x - e54.x, i8 = t4.y - e54.y;\n if (Math.abs(o10) \u003c= vne \u0026\u0026 Math.abs(i8) \u003c= vne)\n return Sne(e54, n8) \u0026\u0026 Sne(t4, n8) ? { start: e54, end: t4 } : null;\n let r9 = 0, s7 = 1;\n const a9 = [[-o10, e54.x - n8.minX], [o10, n8.maxX - e54.x], [-i8, e54.y - n8.minY], [i8, n8.maxY - e54.y]];\n for (const [e60, t10] of a9) {\n if (Math.abs(e60) \u003c= vne) {\n if (t10 \u003c 0)\n return null;\n continue;\n }\n const n10 = t10 / e60;\n if (e60 \u003c 0 ? r9 = Math.max(r9, n10) : s7 = Math.min(s7, n10), r9 \u003e s7 + vne)\n return null;\n }\n return { start: Cne(e54, t4, r9), end: Cne(e54, t4, s7) };\n};\nvar Mne = (e54) =\u003e {\n const t4 = e54.sourceRoutes[0], n8 = `pipeline9_fallback:${t4.connectionName}`, o10 = `${n8}:start`, i8 = `${n8}:end`;\n return [{ ...e54.start.point, portPointId: o10, nextPortPointId: i8, connectionName: t4.connectionName, rootConnectionName: t4.rootConnectionName }, { ...e54.end.point, portPointId: i8, prevPortPointId: o10, connectionName: t4.connectionName, rootConnectionName: t4.rootConnectionName }];\n};\nvar wne = (e54, t4) =\u003e Math.abs(e54.x - t4.x) \u003c= vne \u0026\u0026 Math.abs(e54.y - t4.y) \u003c= vne \u0026\u0026 e54.z === t4.z;\nvar Nne = (e54, t4) =\u003e e54.sourceRoute.preloadedTraceIndex === t4.sourceRoute.preloadedTraceIndex \u0026\u0026 wne(e54.sourceRoute.route.at(-1), t4.sourceRoute.route[0]);\nvar Rne = (e54, t4, n8 = new Set) =\u003e {\n const o10 = new Map, i8 = [], r9 = new Set(e54.portPoints.map((e60) =\u003e e60.z)), s7 = t4.map((t10) =\u003e ((e60, t11) =\u003e {\n const n10 = Ine(t11);\n let o11, i9;\n for (let t12 = 0;t12 \u003c e60.route.length - 1; t12++) {\n const r10 = Pne(e60.route[t12], e60.route[t12 + 1], n10);\n r10 \u0026\u0026 (o11 ??= { segmentIndex: t12, point: r10.start }, i9 = { segmentIndex: t12, point: r10.end });\n }\n return o11 \u0026\u0026 i9 ? { sourceRoute: e60, start: o11, end: i9 } : null;\n })(t10, e54)).filter((e60) =\u003e e60 !== null), a9 = s7.filter((e60) =\u003e e60.sourceRoute.isThroughObstacle !== true \u0026\u0026 (((e61, t10) =\u003e t10.size === 0 || [e61.start.point, ...e61.sourceRoute.route.slice(e61.start.segmentIndex + 1, e61.end.segmentIndex + 1), e61.end.point].some((e63) =\u003e t10.has(e63.z)))(e60, r9) || n8.has(e60.sourceRoute.connectionName))).sort((e60, t10) =\u003e e60.sourceRoute.preloadedTraceIndex - t10.sourceRoute.preloadedTraceIndex || e60.sourceRoute.preloadedRouteIndex - t10.sourceRoute.preloadedRouteIndex), c5 = new Set(a9.map((e60) =\u003e e60.sourceRoute)), l5 = s7.map((e60) =\u003e e60.sourceRoute).filter((e60) =\u003e !c5.has(e60)), h5 = [];\n for (let e60 = 0;e60 \u003c a9.length; e60++) {\n const t10 = a9[e60], n10 = a9[e60 - 1], o11 = h5.at(-1);\n n10 \u0026\u0026 o11 \u0026\u0026 Nne(n10, t10) ? (o11.sourceRoutes.push(t10.sourceRoute), o11.end = t10.end) : h5.push({ sourceRoutes: [t10.sourceRoute], start: t10.start, end: t10.end });\n }\n for (const e60 of h5) {\n if (wne(e60.start.point, e60.end.point))\n continue;\n const t10 = e60.sourceRoutes[0].connectionName;\n if (o10.has(t10))\n throw new Error(`Pipeline9 regional fallback found duplicate fixed route section identity \"${t10}\"`);\n o10.set(t10, e60), i8.push(Mne(e60));\n }\n return { nodeWithPortPoints: { ...e54, portPoints: [...e54.portPoints, ...i8.flatMap((e60) =\u003e e60)], portPointsInPairs: [...e54.portPointsInPairs ?? [], ...i8] }, fixedRouteSectionsByConnectionName: o10, fixedObstacleRoutes: l5 };\n};\nvar Tne = (e54) =\u003e {\n const t4 = [];\n for (let n8 = 0;n8 \u003c e54.length - 1; n8++) {\n const o10 = e54[n8], i8 = e54[n8 + 1];\n o10.z !== i8.z \u0026\u0026 Math.abs(o10.x - i8.x) \u003c= vne \u0026\u0026 Math.abs(o10.y - i8.y) \u003c= vne \u0026\u0026 t4.push({ x: i8.x, y: i8.y });\n }\n return t4;\n};\nvar Ene = (e54, t4) =\u003e Ane({ section: e54, replacement: t4, sourceMutationMasks: new Map, replacementIsMutated: false }).route;\nvar Ane = ({ section: e54, replacement: t4, sourceMutationMasks: n8, replacementIsMutated: o10 }) =\u003e {\n const i8 = e54.sourceRoutes[0], r9 = e54.sourceRoutes.at(-1), s7 = ((e60, t10) =\u003e {\n const n10 = e60.route, o11 = n10[0], i9 = n10.at(-1);\n if (!o11 || !i9)\n throw new Error(`Pipeline9 regional fallback produced an empty replacement for \"${t10.sourceRoutes[0].connectionName}\"`);\n const r10 = Math.hypot(o11.x - t10.start.point.x, o11.y - t10.start.point.y) + Math.hypot(i9.x - t10.end.point.x, i9.y - t10.end.point.y);\n return Math.hypot(i9.x - t10.start.point.x, i9.y - t10.start.point.y) + Math.hypot(o11.x - t10.end.point.x, o11.y - t10.end.point.y) \u003c r10 ? [...n10].reverse() : n10;\n })(t4, e54), a9 = [], c5 = [], l5 = (e60, t10) =\u003e {\n const o11 = n8.get(e60.connectionName);\n if (o11 \u0026\u0026 o11.length !== e60.route.length - 1)\n throw new Error(`Pipeline9 fixed route mutation mask for \"${e60.connectionName}\" has ${o11.length} segments, expected ${e60.route.length - 1}`);\n return o11?.[t10] ?? false;\n }, h5 = (e60, t10) =\u003e {\n const n10 = a9.at(-1);\n if (!n10)\n return void a9.push(e60);\n const o11 = n10.x === e60.x \u0026\u0026 n10.y === e60.y;\n if (!o11 || n10.z !== e60.z) {\n if (n10.z !== e60.z \u0026\u0026 !o11) {\n const o12 = { ...e60, z: n10.z };\n a9.push(o12), c5.push(t10);\n }\n a9.push(e60), c5.push(t10);\n }\n };\n h5(i8.route[0], false);\n for (let t10 = 1;t10 \u003c= e54.start.segmentIndex; t10++)\n h5(i8.route[t10], l5(i8, t10 - 1));\n h5(e54.start.point, l5(i8, e54.start.segmentIndex));\n const d9 = c5.length;\n for (const e60 of s7.slice(1, -1))\n h5(e60, o10);\n h5(e54.end.point, o10);\n const u9 = c5.length \u003e d9;\n for (let t10 = e54.end.segmentIndex + 1;t10 \u003c r9.route.length; t10++)\n h5(r9.route[t10], l5(r9, t10 - 1));\n if (c5.length !== a9.length - 1)\n throw new Error(`Pipeline9 produced an invalid mutation mask while splicing \"${i8.connectionName}\"`);\n return { route: { ...i8, preloadedRoutePositionStart: i8.preloadedRoutePositionStart, preloadedRoutePositionEnd: r9.preloadedRoutePositionEnd, traceThickness: Math.max(...e54.sourceRoutes.map((e60) =\u003e e60.traceThickness)), viaDiameter: Math.max(...e54.sourceRoutes.map((e60) =\u003e e60.viaDiameter)), route: a9, vias: Tne(a9) }, mutatedSegments: c5, replacementProducedSegment: u9 };\n};\nvar One = 0.000001;\nvar kne = (e54, t4) =\u003e Math.abs(e54.x - t4.x) \u003c= One \u0026\u0026 Math.abs(e54.y - t4.y) \u003c= One \u0026\u0026 e54.z === t4.z;\nvar Dne = (e54, t4) =\u003e {\n for (const n8 of t4)\n e54.at(-1) \u0026\u0026 kne(e54.at(-1), n8) || e54.push(n8);\n};\nvar Lne = (e54) =\u003e e54.slice(0, -1).flatMap((t4, n8) =\u003e {\n const o10 = e54[n8 + 1];\n return t4.z !== o10.z \u0026\u0026 Math.abs(t4.x - o10.x) \u003c= One \u0026\u0026 Math.abs(t4.y - o10.y) \u003c= One ? [{ x: o10.x, y: o10.y }] : [];\n});\nvar zne = (e54) =\u003e {\n const { preloadedRoutePositionStart: t4, preloadedRoutePositionEnd: n8 } = e54;\n if (t4 === undefined || n8 === undefined)\n throw new Error(`Pipeline9 fixed route \"${e54.connectionName}\" is missing route-position metadata`);\n return { start: Math.min(t4, n8), end: Math.max(t4, n8) };\n};\nvar Bne = (e54, t4) =\u003e {\n const n8 = zne(e54), o10 = zne(t4);\n return e54.preloadedTraceIndex - t4.preloadedTraceIndex || n8.start - o10.start || n8.end - o10.end || e54.preloadedRouteIndex - t4.preloadedRouteIndex || e54.connectionName.localeCompare(t4.connectionName);\n};\nvar Fne = (e54, t4) =\u003e {\n const n8 = e54.route.at(-1), o10 = t4.route[0];\n return Boolean(n8 \u0026\u0026 o10 \u0026\u0026 e54.preloadedTraceIndex === t4.preloadedTraceIndex \u0026\u0026 kne(n8, o10));\n};\nvar jne = (e54, t4) =\u003e {\n const n8 = e54.preloadedRoutePositionStart ?? e54.preloadedRouteIndex;\n return n8 + ((e54.preloadedRoutePositionEnd ?? e54.preloadedRouteIndex) - n8) * t4 / (e54.route.length - 1);\n};\nvar $ne = (e54, t4) =\u003e e54.route[t4].z !== e54.route[t4 + 1].z;\nvar Yne = ({ updatedFixedRoutes: e54, regionalMutationMasks: t4 }) =\u003e {\n const n8 = [], o10 = (({ updatedFixedRoutes: e60, regionalMutationMasks: t10 }) =\u003e {\n const n10 = new Map;\n for (const o12 of e60) {\n if (o12.route.length === 0)\n throw new Error(`Pipeline9 cannot normalize empty fixed route \"${o12.connectionName}\"`);\n const e61 = o12.route.length - 1;\n if (n10.has(o12.connectionName))\n throw new Error(`Pipeline9 cannot normalize duplicate fixed route \"${o12.connectionName}\"`);\n const i9 = t10.get(o12.connectionName);\n if (i9 \u0026\u0026 i9.length !== e61)\n throw new Error(`Pipeline9 fixed route mutation mask for \"${o12.connectionName}\" has ${i9.length} segments, expected ${e61}`);\n const r10 = o12.isThroughObstacle !== true \u0026\u0026 (o12.jumpers?.length ?? 0) === 0;\n n10.set(o12.connectionName, Array.from({ length: e61 }, (e63, t11) =\u003e r10 \u0026\u0026 (i9?.[t11] ?? false)));\n }\n let o11 = [];\n const i8 = () =\u003e {\n for (;o11[0] \u0026\u0026 $ne(o11[0].route, o11[0].segmentIndex); ) {\n const e61 = o11.shift();\n n10.get(e61.route.connectionName)[e61.segmentIndex] = false;\n }\n for (;o11.at(-1) \u0026\u0026 $ne(o11.at(-1).route, o11.at(-1).segmentIndex); ) {\n const e61 = o11.pop();\n n10.get(e61.route.connectionName)[e61.segmentIndex] = false;\n }\n o11 = [];\n };\n let r9;\n for (const t11 of [...e60].sort(Bne)) {\n r9 \u0026\u0026 !Fne(r9, t11) \u0026\u0026 i8();\n const e61 = n10.get(t11.connectionName);\n if (e61.length !== 0) {\n for (let n11 = 0;n11 \u003c e61.length; n11++)\n e61[n11] ? o11.push({ route: t11, segmentIndex: n11 }) : i8();\n r9 = t11;\n } else\n i8(), r9 = t11;\n }\n return i8(), n10;\n })({ updatedFixedRoutes: e54, regionalMutationMasks: t4 });\n for (const t10 of e54) {\n const e60 = t10.route.length - 1, i8 = o10.get(t10.connectionName);\n if (e60 === 0) {\n n8.push({ route: t10, mutated: false });\n continue;\n }\n const r9 = [];\n for (let t11 = 0;t11 \u003c e60; t11++) {\n const e61 = i8[t11], n10 = r9.at(-1);\n n10?.mutated === e61 ? n10.end = t11 + 1 : r9.push({ start: t11, end: t11 + 1, mutated: e61 });\n }\n for (const [e61, o11] of r9.entries()) {\n const i9 = t10.route.slice(o11.start, o11.end + 1), s7 = { ...t10, connectionName: r9.length === 1 ? t10.connectionName : `${t10.connectionName}_mutation_fragment_${e61}`, preloadedRouteIndex: t10.preloadedRouteIndex + e61 / (r9.length + 1), preloadedRoutePositionStart: jne(t10, o11.start), preloadedRoutePositionEnd: jne(t10, o11.end), route: i9, vias: Lne(i9) };\n n8.push({ route: s7, mutated: o11.mutated });\n }\n }\n return n8;\n};\nvar Xne = ({ updatedFixedRoutes: e54, regionalMutationMasks: t4 }) =\u003e {\n const n8 = Yne({ updatedFixedRoutes: e54, regionalMutationMasks: t4 }), o10 = n8.map(({ route: e60 }) =\u003e e60), i8 = ((e60) =\u003e {\n const t10 = [];\n let n10;\n for (const o11 of [...e60].sort((e61, t11) =\u003e Bne(e61.route, t11.route))) {\n const e61 = o11.route;\n if (!o11.mutated) {\n n10 = undefined;\n continue;\n }\n const i9 = e61.route[0], r10 = e61.route.at(-1);\n if (!i9 || !r10 || e61.route.length \u003c 2)\n throw new Error(`Pipeline9 cannot simplify empty fixed route \"${e61.connectionName}\"`);\n const s9 = n10?.sourceRoutes.at(-1);\n n10 \u0026\u0026 s9 \u0026\u0026 Fne(s9, e61) ? (n10.sourceRoutes.push(e61), n10.end = { segmentIndex: e61.route.length - 2, point: r10 }) : (n10 = { sourceRoutes: [e61], start: { segmentIndex: 0, point: i9 }, end: { segmentIndex: e61.route.length - 2, point: r10 } }, t10.push(n10));\n }\n return t10;\n })(n8), r9 = i8.map((e60, t10) =\u003e {\n const n10 = ((e61, t11) =\u003e {\n const n11 = e61.sourceRoutes[0], o11 = e61.sourceRoutes.at(-1);\n if (!n11 || !o11)\n throw new Error(\"Pipeline9 cannot simplify an empty mutation section\");\n const i9 = [e61.start.point];\n for (const [t12, n12] of e61.sourceRoutes.entries()) {\n const o12 = t12 === 0, r10 = t12 === e61.sourceRoutes.length - 1, s9 = o12 ? e61.start.segmentIndex + 1 : 0, a9 = r10 ? e61.end.segmentIndex + 1 : n12.route.length;\n Dne(i9, n12.route.slice(s9, a9));\n }\n if (Dne(i9, [e61.end.point]), i9.length \u003c 2)\n throw new Error(`Pipeline9 mutation section for \"${n11.connectionName}\" has no routable span`);\n return { connectionName: `pipeline9_mutated_preload_${n11.preloadedTraceIndex}_${t11}`, rootConnectionName: n11.rootConnectionName, traceThickness: Math.max(...e61.sourceRoutes.map((e63) =\u003e e63.traceThickness)), viaDiameter: Math.max(...e61.sourceRoutes.map((e63) =\u003e e63.viaDiameter)), route: i9, vias: Lne(i9) };\n })(e60, t10);\n return { connectionName: n10.connectionName, section: e60, hdRoute: n10 };\n }), s7 = new Set(r9.flatMap(({ section: e60 }) =\u003e e60.sourceRoutes.map((e61) =\u003e e61.connectionName)));\n return { sections: r9, immutableHdRoutes: o10.filter((e60) =\u003e !s7.has(e60.connectionName)), normalizedFixedRoutes: o10 };\n};\nvar Hne = 0.000000001;\nvar Vne = (e54, t4, n8, o10, i8) =\u003e {\n const r9 = i8.getNetConnectedToId(e54.connection_name) ?? e54.connection_name, s7 = [], a9 = (n10, i9, a10 = o10, c5 = [], l5, h5, d9 = false) =\u003e {\n n10.length \u003c 2 || s7.push({ connectionName: `${e54.connection_name}_fixed_${t4}_${s7.length}`, rootConnectionName: r9, preloadedTraceIndex: t4, preloadedRouteIndex: s7.length, preloadedRoutePositionStart: l5, preloadedRoutePositionEnd: h5, isThroughObstacle: d9, traceThickness: Math.max(Hne, i9), viaDiameter: Math.max(Hne, a10), route: n10, vias: c5 });\n };\n for (let t10 = 0;t10 \u003c e54.route.length; t10++) {\n const i9 = e54.route[t10];\n if (i9.route_type === \"via\") {\n a9([{ x: i9.x, y: i9.y, z: mo(i9.from_layer, n8) }, { x: i9.x, y: i9.y, z: mo(i9.to_layer, n8) }], Hne, i9.via_diameter ?? o10, [{ x: i9.x, y: i9.y }], t10, t10);\n continue;\n }\n if (i9.route_type === \"through_obstacle\") {\n const e60 = mo(i9.from_layer, n8), r11 = mo(i9.to_layer, n8);\n for (let n10 = Math.min(e60, r11);n10 \u003c= Math.max(e60, r11); n10++)\n a9([{ ...i9.start, z: n10 }, { ...i9.end, z: n10 }], i9.width, o10, [], t10, t10 + 1, true);\n continue;\n }\n const r10 = e54.route[t10 + 1];\n i9.route_type === \"wire\" \u0026\u0026 r10?.route_type === \"wire\" \u0026\u0026 i9.layer === r10.layer \u0026\u0026 a9([{ x: i9.x, y: i9.y, z: mo(i9.layer, n8) }, { x: r10.x, y: r10.y, z: mo(r10.layer, n8) }], Math.max(i9.width, r10.width), o10, [], t10, t10 + 1);\n }\n return s7;\n};\nvar Gne = class extends ni {\n constructor(e54) {\n super(), this.input = e54;\n }\n static solverName = \"Pipeline9HighDensityBatchSolver\";\n output;\n _step() {\n if (this.input.fixedHdRoutes.length !== 0)\n throw new Error(\"Parallel high-density batches cannot mutate preloaded copper\");\n const e54 = new Jo(this.input.connectivityNetMap);\n this.output = [];\n for (const t4 of this.input.nodePortPoints) {\n const n8 = new Loe({ ...this.input, nodePortPoints: [t4], connMap: e54 });\n n8.MAX_ITERATIONS = this.input.maxIterations, n8.solve(), this.output.push({ routes: n8.routes, stats: n8.stats, benchmarkDiagnosticCounters: n8.benchmarkDiagnosticCounters, iterations: n8.iterations, consumedNodeCount: 1 - n8.unsolvedNodePortPoints.length, solved: n8.solved, error: n8.error });\n }\n this.solved = true;\n }\n getOutput() {\n if (!this.output)\n throw new Error(\"High-density batch has not completed\");\n return this.output;\n }\n};\nfunction Une(e54, t4) {\n return { x: e54.a * t4.x + e54.b * t4.y + e54.c, y: e54.d * t4.x + e54.e * t4.y + e54.f };\n}\nSolverRuntime.registerSolver(Gne);\nvar Zne = { highResolutionCellSize: 0.1, highResolutionCellThickness: 8, lowResolutionCellSize: 0.4, traceMargin: 0.15, traceThickness: 0.1, viaDiameter: 0.3, viaMinDistFromBorder: 0.15 };\nvar qne = { ...Zne };\nvar Qne = (e54, t4, n8) =\u003e {\n const [o10, i8] = e54;\n if (o10 === i8)\n return;\n const r9 = ((e60, t10) =\u003e {\n const n10 = e60.portPointId ?? `${e60.connectionName}:${e60.x}:${e60.y}:${e60.z}`, o11 = t10.portPointId ?? `${t10.connectionName}:${t10.x}:${t10.y}:${t10.z}`;\n return n10 \u003c o11 ? `${n10}|${o11}` : `${o11}|${n10}`;\n })(o10, i8);\n t4.has(r9) || (t4.add(r9), n8.push(e54));\n};\nvar Kne = (e54, t4, n8) =\u003e {\n for (let o10 = 0;o10 \u003c e54.length - 1; o10++)\n Qne([e54[o10], e54[o10 + 1]], t4, n8);\n};\nvar eoe = (e54) =\u003e {\n const t4 = [], n8 = new Set, o10 = ((e60) =\u003e {\n const t10 = new Map;\n for (const n10 of e60)\n n10.portPointId \u0026\u0026 t10.set(n10.portPointId, n10);\n return t10;\n })(e54);\n for (const i9 of e54) {\n if (i9.prevPortPointId) {\n const e60 = o10.get(i9.prevPortPointId);\n e60 \u0026\u0026 e60.connectionName === i9.connectionName \u0026\u0026 Qne([e60, i9], n8, t4);\n }\n if (i9.nextPortPointId) {\n const e60 = o10.get(i9.nextPortPointId);\n e60 \u0026\u0026 e60.connectionName === i9.connectionName \u0026\u0026 Qne([i9, e60], n8, t4);\n }\n }\n if (t4.length === 0)\n return Kne(e54, n8, t4), t4;\n const i8 = ((e60) =\u003e {\n const t10 = new Set;\n for (const [n10, o11] of e60)\n n10.portPointId \u0026\u0026 t10.add(n10.portPointId), o11.portPointId \u0026\u0026 t10.add(o11.portPointId);\n return t10;\n })(t4), r9 = e54.filter((e60) =\u003e !e60.portPointId || !i8.has(e60.portPointId));\n return Kne(r9, n8, t4), t4;\n};\nfunction toe(e54, t4, n8) {\n return Math.max(t4, Math.min(n8, e54));\n}\nvar hoe = [\"left\", \"top\", \"right\", \"bottom\", \"middle\"];\nvar doe = class {\n f = new Float64Array(1024);\n seq = new Uint32Array(1024);\n id = new Int32Array(1024);\n n = 0;\n push(e54, t4, n8) {\n this.ensureCapacity(this.n + 1);\n let o10 = this.n++;\n for (this.f[o10] = e54, this.seq[o10] = t4, this.id[o10] = n8;o10 \u003e 0; ) {\n const e60 = o10 - 1 \u003e\u003e 1;\n if (this.less(e60, o10))\n break;\n this.swap(o10, e60), o10 = e60;\n }\n }\n pop() {\n const e54 = this.id[0];\n return this.n--, this.n \u003e 0 \u0026\u0026 (this.f[0] = this.f[this.n], this.seq[0] = this.seq[this.n], this.id[0] = this.id[this.n], this.siftDown(0)), e54;\n }\n get size() {\n return this.n;\n }\n clear() {\n this.n = 0;\n }\n ensureCapacity(e54) {\n if (e54 \u003c= this.f.length)\n return;\n let t4 = this.f.length;\n for (;t4 \u003c e54; )\n t4 *= 2;\n const n8 = new Float64Array(t4);\n n8.set(this.f), this.f = n8;\n const o10 = new Uint32Array(t4);\n o10.set(this.seq), this.seq = o10;\n const i8 = new Int32Array(t4);\n i8.set(this.id), this.id = i8;\n }\n siftDown(e54) {\n for (;; ) {\n const t4 = 2 * e54 + 1, n8 = t4 + 1;\n if (t4 \u003e= this.n)\n return;\n let o10 = t4;\n if (n8 \u003c this.n \u0026\u0026 !this.less(t4, n8) \u0026\u0026 (o10 = n8), this.less(e54, o10))\n return;\n this.swap(e54, o10), e54 = o10;\n }\n }\n less(e54, t4) {\n const n8 = this.f[e54], o10 = this.f[t4];\n return n8 !== o10 ? n8 \u003c o10 : this.seq[e54] \u003c this.seq[t4];\n }\n swap(e54, t4) {\n const n8 = this.f[e54];\n this.f[e54] = this.f[t4], this.f[t4] = n8;\n const o10 = this.seq[e54];\n this.seq[e54] = this.seq[t4], this.seq[t4] = o10;\n const i8 = this.id[e54];\n this.id[e54] = this.id[t4], this.id[t4] = i8;\n }\n};\nvar uoe = class {\n z = new Int32Array(1024);\n cellId = new Int32Array(1024);\n g = new Float64Array(1024);\n parent = new Int32Array(1024);\n ripHead = new Int32Array(1024).fill(-1);\n ripCount = new Int32Array(1024);\n length = 0;\n clear() {\n this.length = 0;\n }\n push(e54, t4, n8, o10, i8, r9) {\n this.ensureCapacity(this.length + 1);\n const s7 = this.length++;\n return this.z[s7] = e54, this.cellId[s7] = t4, this.g[s7] = n8, this.parent[s7] = o10, this.ripHead[s7] = i8, this.ripCount[s7] = r9, s7;\n }\n ensureCapacity(e54) {\n if (e54 \u003c= this.z.length)\n return;\n let t4 = this.z.length;\n for (;t4 \u003c e54; )\n t4 *= 2;\n const n8 = new Int32Array(t4);\n n8.set(this.z), this.z = n8;\n const o10 = new Int32Array(t4);\n o10.set(this.cellId), this.cellId = o10;\n const i8 = new Float64Array(t4);\n i8.set(this.g), this.g = i8;\n const r9 = new Int32Array(t4);\n r9.set(this.parent), this.parent = r9;\n const s7 = new Int32Array(t4);\n s7.fill(-1), s7.set(this.ripHead.subarray(0, this.length)), this.ripHead = s7;\n const a9 = new Int32Array(t4);\n a9.set(this.ripCount.subarray(0, this.length)), this.ripCount = a9;\n }\n};\nvar poe = class {\n connId = new Int32Array(1024);\n prev = new Int32Array(1024).fill(-1);\n length = 0;\n clear() {\n this.length = 0;\n }\n append(e54, t4) {\n this.ensureCapacity(this.length + 1);\n const n8 = this.length++;\n return this.connId[n8] = t4, this.prev[n8] = e54, n8;\n }\n contains(e54, t4) {\n for (let n8 = e54;n8 \u003e= 0; n8 = this.prev[n8])\n if (this.connId[n8] === t4)\n return true;\n return false;\n }\n collect(e54, t4) {\n t4.length = 0;\n for (let n8 = e54;n8 \u003e= 0; n8 = this.prev[n8])\n t4.push(this.connId[n8]);\n }\n ensureCapacity(e54) {\n if (e54 \u003c= this.connId.length)\n return;\n let t4 = this.connId.length;\n for (;t4 \u003c e54; )\n t4 *= 2;\n const n8 = new Int32Array(t4);\n n8.set(this.connId), this.connId = n8;\n const o10 = new Int32Array(t4);\n o10.fill(-1), o10.set(this.prev.subarray(0, this.length)), this.prev = o10;\n }\n};\nfunction moe(e54, t4) {\n if (e54.length === 0)\n return null;\n const n8 = new E2(e54.length);\n for (const o10 of e54) {\n const e60 = t4(o10);\n n8.add(e60.minX, e60.minY, e60.maxX, e60.maxY);\n }\n return n8.finish(), n8;\n}\nfunction goe(e54, t4) {\n return t4 ?? e54.replace(/_mst\\d+$/, \"\");\n}\nfunction foe(e54, t4) {\n const n8 = e54.x - t4.center.x, o10 = e54.y - t4.center.y, i8 = Math.cos(-t4.rotationRadians), r9 = Math.sin(-t4.rotationRadians);\n return { x: n8 * i8 - o10 * r9, y: n8 * r9 + o10 * i8 };\n}\nfunction _oe(e54) {\n return { minX: -e54.width / 2, minY: -e54.height / 2, maxX: e54.width / 2, maxY: e54.height / 2 };\n}\nfunction yoe(e54, t4, n8) {\n return Math.max(t4, Math.min(n8, e54));\n}\nfunction boe(e54, t4) {\n for (let n8 = 0;n8 \u003c e54.length; n8++)\n if (e54[n8] === t4)\n return;\n e54.push(t4);\n}\nfunction xoe(e54, t4) {\n for (let n8 = 0;n8 \u003c e54.length; n8++)\n if (e54[n8].cellId === t4.cellId)\n return;\n e54.push(t4);\n}\nfunction voe(e54, t4, n8, o10, i8, r9, s7) {\n const a9 = e54 - yoe(e54, o10, r9), c5 = t4 - yoe(t4, i8, s7);\n return a9 * a9 + c5 * c5 \u003c= n8 * n8;\n}\nfunction Ioe(e54) {\n const t4 = e54.segmentEnd.x - e54.segmentStart.x, n8 = e54.segmentEnd.y - e54.segmentStart.y, o10 = t4 ** 2 + n8 ** 2;\n if (o10 === 0)\n return (e54.point.x - e54.segmentStart.x) ** 2 + (e54.point.y - e54.segmentStart.y) ** 2;\n const i8 = yoe(((e54.point.x - e54.segmentStart.x) * t4 + (e54.point.y - e54.segmentStart.y) * n8) / o10, 0, 1), r9 = e54.segmentStart.x + i8 * t4, s7 = e54.segmentStart.y + i8 * n8;\n return (e54.point.x - r9) ** 2 + (e54.point.y - s7) ** 2;\n}\nfunction Soe(e54) {\n const t4 = yoe(e54.point.x, e54.rect.minX, e54.rect.maxX), n8 = yoe(e54.point.y, e54.rect.minY, e54.rect.maxY), o10 = e54.point.x - t4, i8 = e54.point.y - n8;\n return o10 * o10 + i8 * i8;\n}\nfunction Coe(e54) {\n return (e54.second.x - e54.first.x) * (e54.third.y - e54.first.y) - (e54.second.y - e54.first.y) * (e54.third.x - e54.first.x);\n}\nfunction Poe(e54) {\n return !(Math.abs(Coe({ first: e54.segmentStart, second: e54.segmentEnd, third: e54.point })) \u003e 0.000000001) \u0026\u0026 (e54.point.x \u003e= Math.min(e54.segmentStart.x, e54.segmentEnd.x) \u0026\u0026 e54.point.x \u003c= Math.max(e54.segmentStart.x, e54.segmentEnd.x) \u0026\u0026 e54.point.y \u003e= Math.min(e54.segmentStart.y, e54.segmentEnd.y) \u0026\u0026 e54.point.y \u003c= Math.max(e54.segmentStart.y, e54.segmentEnd.y));\n}\nfunction Moe(e54) {\n const t4 = Coe({ first: e54.firstStart, second: e54.firstEnd, third: e54.secondStart }), n8 = Coe({ first: e54.firstStart, second: e54.firstEnd, third: e54.secondEnd }), o10 = Coe({ first: e54.secondStart, second: e54.secondEnd, third: e54.firstStart }), i8 = Coe({ first: e54.secondStart, second: e54.secondEnd, third: e54.firstEnd });\n return t4 * n8 \u003c 0 \u0026\u0026 o10 * i8 \u003c 0 || (Poe({ point: e54.secondStart, segmentStart: e54.firstStart, segmentEnd: e54.firstEnd }) || Poe({ point: e54.secondEnd, segmentStart: e54.firstStart, segmentEnd: e54.firstEnd }) || Poe({ point: e54.firstStart, segmentStart: e54.secondStart, segmentEnd: e54.secondEnd }) || Poe({ point: e54.firstEnd, segmentStart: e54.secondStart, segmentEnd: e54.secondEnd }));\n}\nfunction woe(e54) {\n return Moe(e54) ? 0 : Math.min(Ioe({ point: e54.firstStart, segmentStart: e54.secondStart, segmentEnd: e54.secondEnd }), Ioe({ point: e54.firstEnd, segmentStart: e54.secondStart, segmentEnd: e54.secondEnd }), Ioe({ point: e54.secondStart, segmentStart: e54.firstStart, segmentEnd: e54.firstEnd }), Ioe({ point: e54.secondEnd, segmentStart: e54.firstStart, segmentEnd: e54.firstEnd }));\n}\nfunction Noe(e54) {\n if (function(e60) {\n if (Soe({ point: e60.segmentStart, rect: e60.rect }) === 0 || Soe({ point: e60.segmentEnd, rect: e60.rect }) === 0)\n return true;\n const t10 = [{ x: e60.rect.minX, y: e60.rect.minY }, { x: e60.rect.maxX, y: e60.rect.minY }, { x: e60.rect.maxX, y: e60.rect.maxY }, { x: e60.rect.minX, y: e60.rect.maxY }];\n for (let n8 = 0;n8 \u003c t10.length; n8++) {\n const o10 = (n8 + 1) % t10.length;\n if (Moe({ firstStart: e60.segmentStart, firstEnd: e60.segmentEnd, secondStart: t10[n8], secondEnd: t10[o10] }))\n return true;\n }\n return false;\n }(e54))\n return true;\n const t4 = e54.radius ** 2;\n if (Soe({ point: e54.segmentStart, rect: e54.rect }) \u003c= t4 || Soe({ point: e54.segmentEnd, rect: e54.rect }) \u003c= t4)\n return true;\n return [{ x: e54.rect.minX, y: e54.rect.minY }, { x: e54.rect.maxX, y: e54.rect.minY }, { x: e54.rect.maxX, y: e54.rect.maxY }, { x: e54.rect.minX, y: e54.rect.maxY }].some((n8) =\u003e Ioe({ point: n8, segmentStart: e54.segmentStart, segmentEnd: e54.segmentEnd }) \u003c= t4);\n}\nvar Roe = class extends BaseSolver {\n getSolverName() {\n return \"HighDensitySolverB01\";\n }\n nodeWithPortPoints;\n obstacles;\n highResolutionCellSize;\n highResolutionCellThickness;\n lowResolutionCellSize;\n viaDiameter;\n MAX_RIPS;\n maxCellCount;\n traceThickness;\n traceMargin;\n obstacleClearanceMargin;\n viaMinDistFromBorder;\n showPenaltyMap;\n showUsedCellMap;\n effort;\n stepMultiplier;\n hyperParameters;\n initialPenaltyFn;\n boundsMinX;\n boundsMaxX;\n boundsMinY;\n boundsMaxY;\n gridToBoundsTransform;\n availableZ;\n zToLayer;\n layerToZ;\n layers;\n fineRows;\n fineCols;\n lowScale;\n bandRows;\n bandCols;\n regions;\n planeSize;\n cellCenterX;\n cellCenterY;\n cellMinX;\n cellMinY;\n cellMaxX;\n cellMaxY;\n cellWidth;\n cellHeight;\n cellRegion;\n cellRow;\n cellCol;\n viaAllowed;\n neighborOffset;\n neighborIds;\n neighborCosts;\n usedCellsFlat;\n sharedCellsFlat;\n portOwnerFlat;\n penalty2d;\n ripStateBuckets;\n visitedStamp;\n bestGStamp;\n bestGValue;\n visitedFlatStamp;\n sharedCrossRootPortFlat;\n stamp = 0;\n connNameToId;\n connIdToName;\n connIdToRootNet;\n overlapFriendlyRootNets;\n usedIndicesByConn;\n unsolvedSegs;\n solvedRoutes;\n activeConnSeg = null;\n activeConnId = -1;\n nodePool;\n heap;\n ripChain;\n seqCounter = 0;\n _viaOccs = [];\n _cellOccs = [];\n _rippedIds = [];\n ripCount;\n totalRipEvents = 0;\n searchIterations = 0;\n consecutiveSkips = 0;\n penaltyCap;\n baseSearchBudgetIters;\n _moveCost = 0;\n _moveRippedHead = -1;\n _moveRipCount = 0;\n traceKeepoutRadius;\n viaKeepoutRadius;\n obstacleTraceRootIdsFlat;\n obstacleViaRootIdsByCell;\n obstacleRootNameToId;\n obstacleRootNames;\n obstacleTracePrimitives;\n obstacleViaPrimitives;\n obstacleRectPrimitives;\n obstacleTraceSpatialIndex = null;\n obstacleViaSpatialIndex = null;\n obstacleRectSpatialIndex = null;\n obstacleTraceBlockedCellCount = 0;\n obstacleViaBlockedCellCount = 0;\n get unsolvedConnections() {\n return this.unsolvedSegs;\n }\n get solvedConnectionsMap() {\n const e54 = new Map;\n for (let t4 = 0;t4 \u003c this.solvedRoutes.length; t4++) {\n const n8 = this.getSolvedRoutesForConn(t4);\n n8.length \u003e 0 \u0026\u0026 e54.set(t4, n8);\n }\n return e54;\n }\n get activeConnection() {\n if (!this.activeConnSeg)\n return null;\n const e54 = this.activeConnSeg.startCellId, t4 = this.activeConnSeg.endCellId;\n return { connectionName: this.connIdToName[this.activeConnSeg.connId] ?? \"\", start: { cellId: e54, region: hoe[this.cellRegion[e54]], row: this.cellRow[e54], col: this.cellCol[e54], x: this.cellCenterX[e54], y: this.cellCenterY[e54], z: this.activeConnSeg.startZ }, end: { cellId: t4, region: hoe[this.cellRegion[t4]], row: this.cellRow[t4], col: this.cellCol[t4], x: this.cellCenterX[t4], y: this.cellCenterY[t4], z: this.activeConnSeg.endZ } };\n }\n get openSet() {\n return { length: this.heap?.size ?? 0 };\n }\n get gridStats() {\n 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((e54) =\u003e [e54.name, e54.rows * e54.cols])) : {}, obstacleTraceBlockedCells: this.obstacleTraceBlockedCellCount, obstacleViaBlockedCells: this.obstacleViaBlockedCellCount, obstacleRootCount: this.obstacleRootNames?.length ?? 0, obstacleRectCount: this.obstacleRectPrimitives?.length ?? 0 };\n }\n constructor(e54) {\n super(), this.nodeWithPortPoints = e54.nodeWithPortPoints, this.obstacles = e54.obstacles, this.highResolutionCellSize = e54.highResolutionCellSize ?? 0.1, this.highResolutionCellThickness = Math.max(1, Math.floor(e54.highResolutionCellThickness ?? 8)), this.lowResolutionCellSize = e54.lowResolutionCellSize ?? 0.4, this.viaDiameter = e54.viaDiameter, this.maxCellCount = e54.maxCellCount, this.traceThickness = e54.traceThickness ?? 0.1, this.traceMargin = e54.traceMargin ?? 0.15, this.obstacleClearanceMargin = e54.obstacleClearanceMargin ?? 0, this.viaMinDistFromBorder = e54.viaMinDistFromBorder ?? 0.15, this.showPenaltyMap = e54.showPenaltyMap ?? false, this.showUsedCellMap = e54.showUsedCellMap ?? false, this.effort = e54.effort ?? 1, this.stepMultiplier = Math.max(1, Math.floor(e54.stepMultiplier ?? 1)), this.hyperParameters = { shuffleSeed: 0, ripCost: 8, ripTracePenalty: 0.5, ripViaPenalty: 0.75, viaBaseCost: 0.1, greedyMultiplier: 1.5, sameRootObstacleCostMultiplier: 1, ...e54.hyperParameters }, this.MAX_ITERATIONS = 1e8, this.MAX_RIPS = 200, this.initialPenaltyFn = e54.initialPenaltyFn;\n }\n getConstructorParams() {\n return [{ nodeWithPortPoints: this.nodeWithPortPoints, obstacles: this.obstacles, highResolutionCellSize: this.highResolutionCellSize, highResolutionCellThickness: this.highResolutionCellThickness, lowResolutionCellSize: this.lowResolutionCellSize, viaDiameter: this.viaDiameter, maxCellCount: this.maxCellCount, stepMultiplier: this.stepMultiplier, traceThickness: this.traceThickness, traceMargin: this.traceMargin, obstacleClearanceMargin: this.obstacleClearanceMargin, viaMinDistFromBorder: this.viaMinDistFromBorder, showPenaltyMap: this.showPenaltyMap, showUsedCellMap: this.showUsedCellMap, effort: this.effort, hyperParameters: this.hyperParameters, initialPenaltyFn: this.initialPenaltyFn }];\n }\n _setup() {\n const { nodeWithPortPoints: e54 } = this, { width: t4, height: n8, center: o10 } = e54;\n if (t4 \u003e 15 || n8 \u003e 15)\n return this.error = `HighDensitySolverB01 only supports routing windows up to 15x15mm; received ${t4}x${n8}mm`, void (this.failed = true);\n const i8 = this.lowResolutionCellSize / this.highResolutionCellSize, r9 = Math.round(i8);\n if (!Number.isFinite(i8) || i8 \u003c= 0 || Math.abs(i8 - r9) \u003e 0.000000001)\n return this.error = \"lowResolutionCellSize must be a positive integer multiple of highResolutionCellSize\", void (this.failed = true);\n this.lowScale = Math.max(1, r9), this.availableZ = e54.availableZ ?? [...new Set(e54.portPoints.map((e60) =\u003e e60.z))].sort((e60, t10) =\u003e e60 - t10), this.layers = this.availableZ.length, this.zToLayer = new Map, this.layerToZ = new Map;\n for (let e60 = 0;e60 \u003c this.availableZ.length; e60++) {\n const t10 = this.availableZ[e60];\n this.zToLayer.set(t10, e60), this.layerToZ.set(e60, t10);\n }\n this.boundsMinX = o10.x - t4 / 2, this.boundsMaxX = o10.x + t4 / 2, this.boundsMinY = o10.y - n8 / 2, this.boundsMaxY = o10.y + n8 / 2, this.traceKeepoutRadius = this.traceMargin + this.traceThickness / 2, this.viaKeepoutRadius = this.viaDiameter / 2 + this.traceKeepoutRadius, this.buildFiveRegionGrid(t4, n8), this.gridToBoundsTransform = this.computeGridToBoundsTransform();\n const s7 = this.layers * this.planeSize;\n if (this.maxCellCount !== undefined \u0026\u0026 s7 \u003e this.maxCellCount)\n return this.error = `Cell count ${s7} exceeds maxCellCount ${this.maxCellCount}`, void (this.failed = true);\n this.connNameToId = new Map, this.connIdToName = [], this.connIdToRootNet = [], this.overlapFriendlyRootNets = new Set, this.unsolvedSegs = this.buildConnectionSegs(), this.penalty2d = new Float64Array(this.planeSize);\n const a9 = t4 \u003e 0 ? 1 / t4 : 0, c5 = n8 \u003e 0 ? 1 / n8 : 0;\n for (let e60 = 0;e60 \u003c this.planeSize; e60++) {\n let t10 = 0;\n this.initialPenaltyFn \u0026\u0026 (t10 += this.initialPenaltyFn({ x: this.cellCenterX[e60], y: this.cellCenterY[e60], px: (this.cellCenterX[e60] - this.boundsMinX) * a9, py: (this.cellCenterY[e60] - this.boundsMinY) * c5, cellId: e60, region: hoe[this.cellRegion[e60]], row: this.cellRow[e60], col: this.cellCol[e60] })), this.penalty2d[e60] = t10;\n }\n this.usedCellsFlat = new Int32Array(s7).fill(-1), this.sharedCellsFlat = Array.from({ length: s7 }, () =\u003e {}), this.portOwnerFlat = new Int32Array(s7).fill(-1), this.sharedCrossRootPortFlat = new Uint8Array(s7), this.obstacleTraceRootIdsFlat = Array.from({ length: s7 }, () =\u003e {}), this.obstacleViaRootIdsByCell = Array.from({ length: this.planeSize }, () =\u003e {}), this.obstacleRootNameToId = new Map, this.obstacleRootNames = [], this.obstacleTracePrimitives = [], this.obstacleViaPrimitives = [], this.obstacleRectPrimitives = [];\n const l5 = this.rasterizeObstacles();\n if (l5)\n return this.error = l5, void (this.failed = true);\n this.buildObstacleSpatialIndexes(), this.ripStateBuckets = 1;\n const h5 = s7;\n this.visitedStamp = new Uint32Array(h5), this.bestGStamp = new Uint32Array(h5), this.bestGValue = new Float64Array(h5), this.visitedFlatStamp = new Uint32Array(s7), this.stamp = 0;\n const d9 = new Map;\n for (const e60 of this.nodeWithPortPoints.portPoints) {\n const t10 = this.connNameToId.get(e60.connectionName);\n if (t10 === undefined)\n continue;\n const n10 = this.pointToCell(e60), o11 = n10.z * this.planeSize + n10.cellId, i9 = this.connIdToRootNet[t10], r10 = d9.get(o11);\n r10 === undefined ? d9.set(o11, i9) : r10 !== i9 \u0026\u0026 (this.sharedCrossRootPortFlat[o11] = 1);\n const s9 = this.portOwnerFlat[o11];\n this.portOwnerFlat[o11] = s9 === -1 || s9 === t10 ? t10 : -2;\n }\n this.solvedRoutes = [], this.usedIndicesByConn = [], this.ripCount = [], this.consecutiveSkips = 0, this.penaltyCap = 0.5 * this.hyperParameters.ripCost, this.shuffleConnections();\n const u9 = function(e60) {\n const t10 = e60.planeSize * e60.layers, n10 = e60.connectionCount, o11 = Math.sqrt(n10), i9 = Math.max(1, e60.maxIterations), r10 = toe(Math.round(t10 * (8 + 1.2 * o11)), 150000, 12000000), s9 = toe(Math.round(r10 * e60.effort), 150000, 12000000), a10 = toe(Math.round(0.2 * i9), 150000, 2000000);\n return { maxIterationsIters: Math.max(1, Math.min(i9, Math.max(a10, s9))), baseSearchBudgetIters: toe(Math.round(t10 * (10 + 0.8 * o11) * e60.effort), 50000, 4000000) };\n }({ planeSize: this.planeSize, layers: this.layers, connectionCount: this.unsolvedSegs.length, effort: this.effort, maxIterations: this.MAX_ITERATIONS });\n this.baseSearchBudgetIters = u9.baseSearchBudgetIters, this.MAX_ITERATIONS = u9.maxIterationsIters, this.activeConnSeg = null, this.activeConnId = -1, this.nodePool = new uoe, this.heap = new doe, this.ripChain = new poe, this.seqCounter = 0;\n }\n _step() {\n for (let e54 = 0;e54 \u003c this.stepMultiplier; e54++) {\n if (this.solved || this.failed)\n return;\n this.stepOnce();\n }\n }\n rasterizeObstacles() {\n for (let e54 = 0;e54 \u003c this.obstacles.length; e54++) {\n const t4 = this.obstacles[e54];\n if (t4.type === \"rect\") {\n const n10 = this.rasterizeRectObstacle(t4, e54);\n if (n10)\n return n10;\n continue;\n }\n if (t4.traceThickness \u003c= 0 || t4.viaDiameter \u003c= 0 || t4.route.length \u003c 2)\n return `Obstacle ${e54} must have positive trace/via sizes and at least two route points`;\n const n8 = goe(t4.connectionName, t4.rootConnectionName), o10 = this.internObstacleRootName(n8);\n for (let n10 = 1;n10 \u003c t4.route.length; n10++) {\n const i8 = t4.route[n10 - 1], r9 = t4.route[n10];\n if (!(Number.isFinite(i8.x) \u0026\u0026 Number.isFinite(i8.y) \u0026\u0026 Number.isFinite(i8.z) \u0026\u0026 Number.isFinite(r9.x) \u0026\u0026 Number.isFinite(r9.y) \u0026\u0026 Number.isFinite(r9.z)))\n return `Obstacle ${e54} contains non-finite route coordinates`;\n if (i8.z === r9.z) {\n const n11 = this.zToLayer.get(i8.z);\n if (n11 === undefined)\n return `Obstacle ${e54} uses unavailable layer z=${i8.z}`;\n this.rasterizeObstacleTraceSegment({ segmentStart: i8, segmentEnd: r9, layer: n11, obstacleRootId: o10, obstacleTraceThickness: t4.traceThickness });\n } else if (!t4.vias.some((e60) =\u003e e60.x === r9.x \u0026\u0026 e60.y === r9.y)) {\n const n11 = this.rasterizeObstacleVia({ center: r9, obstacleRootId: o10, obstacleViaDiameter: t4.viaDiameter, zStart: i8.z, zEnd: r9.z, obstacleIndex: e54 });\n if (n11)\n return n11;\n }\n }\n for (const n10 of t4.vias) {\n if (!Number.isFinite(n10.x) || !Number.isFinite(n10.y))\n return `Obstacle ${e54} contains non-finite via coordinates`;\n const i8 = this.rasterizeObstacleVia({ center: n10, obstacleRootId: o10, obstacleViaDiameter: t4.viaDiameter, zStart: n10.zStart, zEnd: n10.zEnd, obstacleIndex: e54 });\n if (i8)\n return i8;\n }\n }\n return this.obstacleTraceBlockedCellCount = this.obstacleTraceRootIdsFlat.reduce((e54, t4) =\u003e e54 + (t4 ? 1 : 0), 0), this.obstacleViaBlockedCellCount = this.obstacleViaRootIdsByCell.reduce((e54, t4) =\u003e e54 + (t4 ? 1 : 0), 0), null;\n }\n rasterizeRectObstacle(e54, t4) {\n if (!Number.isFinite(e54.center.x) || !Number.isFinite(e54.center.y) || !Number.isFinite(e54.width) || !Number.isFinite(e54.height) || e54.width \u003c= 0 || e54.height \u003c= 0)\n return `Rect obstacle ${t4} must have finite geometry and positive dimensions`;\n const n8 = [];\n for (const o11 of e54.zLayers) {\n const e60 = this.zToLayer.get(o11);\n if (e60 === undefined)\n return `Rect obstacle ${t4} uses unavailable layer z=${o11}`;\n boe(n8, e60);\n }\n if (n8.length === 0)\n return `Rect obstacle ${t4} must apply to at least one layer`;\n const o10 = this.internObstacleRootName(goe(e54.connectionName, e54.rootConnectionName)), i8 = { rootId: o10, center: e54.center, width: e54.width, height: e54.height, rotationRadians: (e54.ccwRotationDegrees ?? 0) * Math.PI / 180, layers: n8 };\n this.obstacleRectPrimitives.push(i8);\n const r9 = this.transformBoundsPointToGrid(e54.center), s7 = Math.hypot(e54.width / 2, e54.height / 2), a9 = this.getConservativeGridRadius(s7 + this.traceThickness / 2 + this.traceMargin);\n this.forEachCellNearCircle(r9.x, r9.y, a9, (e60) =\u003e {\n for (const t10 of n8)\n this.addObstacleRootId({ rootIdsByCell: this.obstacleTraceRootIdsFlat, cellIndex: t10 * this.planeSize + e60, obstacleRootId: o10 });\n });\n const c5 = this.getConservativeGridRadius(s7 + this.viaDiameter / 2 + this.traceMargin);\n return this.forEachCellNearCircle(r9.x, r9.y, c5, (e60) =\u003e {\n this.addObstacleRootId({ rootIdsByCell: this.obstacleViaRootIdsByCell, cellIndex: e60, obstacleRootId: o10 });\n }), null;\n }\n internObstacleRootName(e54) {\n const t4 = this.obstacleRootNameToId.get(e54);\n if (t4 !== undefined)\n return t4;\n const n8 = this.obstacleRootNames.length;\n return this.obstacleRootNames.push(e54), this.obstacleRootNameToId.set(e54, n8), n8;\n }\n rasterizeObstacleTraceSegment(e54) {\n this.obstacleTracePrimitives.push({ rootId: e54.obstacleRootId, layer: e54.layer, segmentStart: e54.segmentStart, segmentEnd: e54.segmentEnd, traceRadius: e54.obstacleTraceThickness / 2 });\n const t4 = this.transformBoundsPointToGrid(e54.segmentStart), n8 = this.transformBoundsPointToGrid(e54.segmentEnd), o10 = this.getConservativeGridRadius(e54.obstacleTraceThickness / 2 + this.traceMargin), i8 = this.getConservativeGridRadius(e54.obstacleTraceThickness / 2 + this.viaDiameter / 2 + this.traceMargin);\n this.forEachCellNearSegment({ segmentStart: t4, segmentEnd: n8, radius: o10 }, (t10) =\u003e {\n this.addObstacleRootId({ rootIdsByCell: this.obstacleTraceRootIdsFlat, cellIndex: e54.layer * this.planeSize + t10, obstacleRootId: e54.obstacleRootId });\n }), this.forEachCellNearSegment({ segmentStart: t4, segmentEnd: n8, radius: i8 }, (t10) =\u003e {\n this.addObstacleRootId({ rootIdsByCell: this.obstacleViaRootIdsByCell, cellIndex: t10, obstacleRootId: e54.obstacleRootId });\n });\n }\n rasterizeObstacleVia(e54) {\n if (e54.zStart === undefined != (e54.zEnd === undefined))\n return `Obstacle ${e54.obstacleIndex} via must provide both zStart and zEnd`;\n let t4 = Array.from({ length: this.layers }, (e60, t10) =\u003e t10);\n if (e54.zStart !== undefined \u0026\u0026 e54.zEnd !== undefined) {\n if (!Number.isFinite(e54.zStart) || !Number.isFinite(e54.zEnd))\n return `Obstacle ${e54.obstacleIndex} contains a non-finite via layer span`;\n const n10 = Math.min(e54.zStart, e54.zEnd), o11 = Math.max(e54.zStart, e54.zEnd);\n t4 = this.availableZ.flatMap((e60, t10) =\u003e e60 \u003e= n10 \u0026\u0026 e60 \u003c= o11 ? [t10] : []);\n }\n if (t4.length === 0)\n return null;\n this.obstacleViaPrimitives.push({ rootId: e54.obstacleRootId, center: e54.center, viaRadius: e54.obstacleViaDiameter / 2, layers: t4 });\n const n8 = this.transformBoundsPointToGrid(e54.center), o10 = this.getConservativeGridRadius(e54.obstacleViaDiameter / 2 + this.traceThickness / 2 + this.traceMargin), i8 = this.getConservativeGridRadius(e54.obstacleViaDiameter / 2 + this.viaDiameter / 2 + this.traceMargin);\n return this.forEachCellNearCircle(n8.x, n8.y, Math.max(o10, i8), (r9) =\u003e {\n const s7 = this.getCellRect(r9);\n if (voe(n8.x, n8.y, o10, s7.minX, s7.minY, s7.maxX, s7.maxY))\n for (const n10 of t4)\n this.addObstacleRootId({ rootIdsByCell: this.obstacleTraceRootIdsFlat, cellIndex: n10 * this.planeSize + r9, obstacleRootId: e54.obstacleRootId });\n voe(n8.x, n8.y, i8, s7.minX, s7.minY, s7.maxX, s7.maxY) \u0026\u0026 this.addObstacleRootId({ rootIdsByCell: this.obstacleViaRootIdsByCell, cellIndex: r9, obstacleRootId: e54.obstacleRootId });\n }), null;\n }\n forEachCellNearSegment(e54, t4) {\n const n8 = { x: (e54.segmentStart.x + e54.segmentEnd.x) / 2, y: (e54.segmentStart.y + e54.segmentEnd.y) / 2 }, o10 = Math.hypot(e54.segmentEnd.x - e54.segmentStart.x, e54.segmentEnd.y - e54.segmentStart.y) / 2 + e54.radius;\n this.forEachCellNearCircle(n8.x, n8.y, o10, (n10) =\u003e {\n Noe({ segmentStart: e54.segmentStart, segmentEnd: e54.segmentEnd, radius: e54.radius, rect: this.getCellRect(n10) }) \u0026\u0026 t4(n10);\n });\n }\n getCellRect(e54) {\n return { minX: this.cellMinX[e54], minY: this.cellMinY[e54], maxX: this.cellMaxX[e54], maxY: this.cellMaxY[e54] };\n }\n transformBoundsPointToGrid(e54) {\n const t4 = this.gridToBoundsTransform;\n return { x: (e54.x - t4.c) / t4.a, y: (e54.y - t4.f) / t4.e };\n }\n getConservativeGridRadius(e54) {\n return e54 / Math.min(Math.abs(this.gridToBoundsTransform.a), Math.abs(this.gridToBoundsTransform.e));\n }\n buildObstacleSpatialIndexes() {\n const e54 = Math.max(Math.abs(this.traceThickness / 2 + this.obstacleClearanceMargin), Math.abs(this.viaDiameter / 2 + this.obstacleClearanceMargin));\n this.obstacleTraceSpatialIndex = moe(this.obstacleTracePrimitives, (t4) =\u003e {\n const n8 = t4.traceRadius + e54;\n return { minX: Math.min(t4.segmentStart.x, t4.segmentEnd.x) - n8, minY: Math.min(t4.segmentStart.y, t4.segmentEnd.y) - n8, maxX: Math.max(t4.segmentStart.x, t4.segmentEnd.x) + n8, maxY: Math.max(t4.segmentStart.y, t4.segmentEnd.y) + n8 };\n }), this.obstacleViaSpatialIndex = moe(this.obstacleViaPrimitives, (t4) =\u003e {\n const n8 = t4.viaRadius + e54;\n return { minX: t4.center.x - n8, minY: t4.center.y - n8, maxX: t4.center.x + n8, maxY: t4.center.y + n8 };\n }), this.obstacleRectSpatialIndex = moe(this.obstacleRectPrimitives, (t4) =\u003e {\n const n8 = Math.hypot(t4.width / 2, t4.height / 2) + e54;\n return { minX: t4.center.x - n8, minY: t4.center.y - n8, maxX: t4.center.x + n8, maxY: t4.center.y + n8 };\n });\n }\n addObstacleRootId(e54) {\n let t4 = e54.rootIdsByCell[e54.cellIndex];\n t4 || (t4 = [], e54.rootIdsByCell[e54.cellIndex] = t4), boe(t4, e54.obstacleRootId);\n }\n isBlockedByObstacleRoots(e54, t4) {\n if (!e54)\n return false;\n const n8 = this.connIdToRootNet[t4];\n for (const t10 of e54)\n if (this.obstacleRootNames[t10] !== n8)\n return true;\n return false;\n }\n hasSameRootObstacle(e54, t4) {\n if (!e54)\n return false;\n const n8 = this.connIdToRootNet[t4];\n return e54.some((e60) =\u003e this.obstacleRootNames[e60] === n8);\n }\n isLateralMoveBlockedByObstacleGeometry(e54) {\n const t4 = this.connIdToRootNet[e54.activeConn], n8 = this.activeConnSeg, o10 = n8 \u0026\u0026 e54.layer === n8.startZ \u0026\u0026 e54.fromCellId === n8.startCellId ? n8.startPoint : Une(this.gridToBoundsTransform, { x: this.cellCenterX[e54.fromCellId], y: this.cellCenterY[e54.fromCellId] }), i8 = n8 \u0026\u0026 e54.layer === n8.endZ \u0026\u0026 e54.toCellId === n8.endCellId ? n8.endPoint : Une(this.gridToBoundsTransform, { x: this.cellCenterX[e54.toCellId], y: this.cellCenterY[e54.toCellId] }), r9 = Math.min(o10.x, i8.x), s7 = Math.min(o10.y, i8.y), a9 = Math.max(o10.x, i8.x), c5 = Math.max(o10.y, i8.y), l5 = this.obstacleTraceSpatialIndex?.search(r9, s7, a9, c5) ?? [];\n for (const n10 of l5) {\n const r10 = this.obstacleTracePrimitives[n10];\n if (r10.layer !== e54.layer || this.obstacleRootNames[r10.rootId] === t4)\n continue;\n const s9 = r10.traceRadius + this.traceThickness / 2 + this.obstacleClearanceMargin;\n if (woe({ firstStart: o10, firstEnd: i8, secondStart: r10.segmentStart, secondEnd: r10.segmentEnd }) \u003c s9 * s9)\n return true;\n }\n const h5 = this.obstacleViaSpatialIndex?.search(r9, s7, a9, c5) ?? [];\n for (const n10 of h5) {\n const r10 = this.obstacleViaPrimitives[n10];\n if (!r10.layers.includes(e54.layer) || this.obstacleRootNames[r10.rootId] === t4)\n continue;\n const s9 = r10.viaRadius + this.traceThickness / 2 + this.obstacleClearanceMargin;\n if (Ioe({ point: r10.center, segmentStart: o10, segmentEnd: i8 }) \u003c s9 * s9)\n return true;\n }\n const d9 = this.obstacleRectSpatialIndex?.search(r9, s7, a9, c5) ?? [];\n for (const n10 of d9) {\n const r10 = this.obstacleRectPrimitives[n10];\n if (r10.layers.includes(e54.layer) \u0026\u0026 this.obstacleRootNames[r10.rootId] !== t4 \u0026\u0026 Noe({ segmentStart: foe(o10, r10), segmentEnd: foe(i8, r10), radius: this.traceThickness / 2 + this.obstacleClearanceMargin, rect: _oe(r10) }))\n return true;\n }\n return false;\n }\n isViaMoveBlockedByObstacleGeometry(e54) {\n const t4 = this.connIdToRootNet[e54.activeConn], n8 = Une(this.gridToBoundsTransform, { x: this.cellCenterX[e54.cellId], y: this.cellCenterY[e54.cellId] }), o10 = this.obstacleTraceSpatialIndex?.search(n8.x, n8.y, n8.x, n8.y) ?? [];\n for (const e60 of o10) {\n const o11 = this.obstacleTracePrimitives[e60];\n if (this.obstacleRootNames[o11.rootId] === t4)\n continue;\n const i9 = o11.traceRadius + this.viaDiameter / 2 + this.obstacleClearanceMargin;\n if (Ioe({ point: n8, segmentStart: o11.segmentStart, segmentEnd: o11.segmentEnd }) \u003c i9 * i9)\n return true;\n }\n const i8 = this.obstacleViaSpatialIndex?.search(n8.x, n8.y, n8.x, n8.y) ?? [];\n for (const e60 of i8) {\n const o11 = this.obstacleViaPrimitives[e60];\n if (this.obstacleRootNames[o11.rootId] === t4)\n continue;\n const i9 = o11.viaRadius + this.viaDiameter / 2 + this.obstacleClearanceMargin;\n if ((n8.x - o11.center.x) ** 2 + (n8.y - o11.center.y) ** 2 \u003c i9 * i9)\n return true;\n }\n const r9 = this.obstacleRectSpatialIndex?.search(n8.x, n8.y, n8.x, n8.y) ?? [];\n for (const e60 of r9) {\n const o11 = this.obstacleRectPrimitives[e60];\n if (this.obstacleRootNames[o11.rootId] === t4)\n continue;\n const i9 = foe(n8, o11), r10 = this.viaDiameter / 2 + this.obstacleClearanceMargin;\n if (Soe({ point: i9, rect: _oe(o11) }) \u003c r10 * r10)\n return true;\n }\n return false;\n }\n buildFiveRegionGrid(e54, t4) {\n this.fineCols = Math.max(1, Math.ceil(e54 / this.highResolutionCellSize)), this.fineRows = Math.max(1, Math.ceil(t4 / this.highResolutionCellSize)), this.bandCols = Math.min(this.highResolutionCellThickness, Math.floor(this.fineCols / 2)), this.bandRows = Math.min(this.highResolutionCellThickness, Math.floor(this.fineRows / 2));\n const n8 = Math.max(0, this.fineCols - 2 * this.bandCols), o10 = Math.max(0, this.fineRows - 2 * this.bandRows), i8 = n8, r9 = n8;\n this.regions = [{ id: 0, name: \"left\", fineOriginRow: 0, fineOriginCol: 0, fineRows: this.fineRows, fineCols: this.bandCols, cellScale: 1, rows: this.fineRows, cols: this.bandCols, offset: 0 }, { id: 1, name: \"top\", fineOriginRow: 0, fineOriginCol: this.bandCols, fineRows: this.bandRows, fineCols: i8, cellScale: 1, rows: this.bandRows, cols: i8, offset: 0 }, { id: 2, 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: 3, name: \"bottom\", fineOriginRow: this.fineRows - this.bandRows, fineOriginCol: this.bandCols, fineRows: this.bandRows, fineCols: r9, cellScale: 1, rows: this.bandRows, cols: r9, offset: 0 }, { id: 4, name: \"middle\", fineOriginRow: this.bandRows, fineOriginCol: this.bandCols, fineRows: o10, fineCols: n8, cellScale: this.lowScale, rows: o10 \u003e 0 ? Math.ceil(o10 / this.lowScale) : 0, cols: n8 \u003e 0 ? Math.ceil(n8 / this.lowScale) : 0, offset: 0 }];\n let s7 = 0;\n for (let e60 = 0;e60 \u003c this.regions.length; e60++)\n this.regions[e60].offset = s7, s7 += this.regions[e60].rows * this.regions[e60].cols;\n this.planeSize = s7, 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);\n for (let e60 = 0;e60 \u003c this.regions.length; e60++) {\n const t10 = this.regions[e60];\n for (let e61 = 0;e61 \u003c t10.rows; e61++) {\n const n10 = t10.fineOriginRow + e61 * t10.cellScale, o11 = Math.min(t10.fineOriginRow + t10.fineRows, n10 + t10.cellScale), i9 = this.boundsMinY + n10 * this.highResolutionCellSize, r10 = Math.min(this.boundsMaxY, this.boundsMinY + o11 * this.highResolutionCellSize);\n for (let n11 = 0;n11 \u003c t10.cols; n11++) {\n const o12 = t10.fineOriginCol + n11 * t10.cellScale, s9 = Math.min(t10.fineOriginCol + t10.fineCols, o12 + t10.cellScale), a10 = this.boundsMinX + o12 * this.highResolutionCellSize, c9 = Math.min(this.boundsMaxX, this.boundsMinX + s9 * this.highResolutionCellSize), l10 = this.cellIdFor(t10.id, e61, n11);\n this.cellCenterX[l10] = (a10 + c9) / 2, this.cellCenterY[l10] = (i9 + r10) / 2, this.cellMinX[l10] = a10, this.cellMinY[l10] = i9, this.cellMaxX[l10] = c9, this.cellMaxY[l10] = r10, this.cellWidth[l10] = c9 - a10, this.cellHeight[l10] = r10 - i9, this.cellRegion[l10] = t10.id, this.cellRow[l10] = e61, this.cellCol[l10] = n11;\n const h9 = Math.min(this.cellCenterX[l10] - this.boundsMinX, this.boundsMaxX - this.cellCenterX[l10], this.cellCenterY[l10] - this.boundsMinY, this.boundsMaxY - this.cellCenterY[l10]);\n this.viaAllowed[l10] = h9 \u003e= this.viaMinDistFromBorder ? 1 : 0;\n }\n }\n }\n const a9 = Array.from({ length: this.planeSize }, () =\u003e []), c5 = (e60, t10) =\u003e {\n if (e60 === t10 || e60 \u003c 0 || t10 \u003c 0)\n return;\n const n10 = this.cellCenterX[e60] - this.cellCenterX[t10], o11 = this.cellCenterY[e60] - this.cellCenterY[t10], i9 = Math.hypot(n10, o11);\n xoe(a9[e60], { cellId: t10, cost: i9 }), xoe(a9[t10], { cellId: e60, cost: i9 });\n };\n for (let e60 = 0;e60 \u003c this.regions.length; e60++) {\n const t10 = this.regions[e60];\n for (let e61 = 0;e61 \u003c t10.rows; e61++)\n for (let n10 = 0;n10 \u003c t10.cols; n10++) {\n const o11 = this.cellIdFor(t10.id, e61, n10);\n e61 + 1 \u003c t10.rows \u0026\u0026 c5(o11, this.cellIdFor(t10.id, e61 + 1, n10)), n10 + 1 \u003c t10.cols \u0026\u0026 c5(o11, this.cellIdFor(t10.id, e61, n10 + 1));\n }\n }\n const l5 = this.regions[0], h5 = this.regions[1], d9 = this.regions[2], u9 = this.regions[3], p9 = this.regions[4], m9 = l5.rows \u003e 0 \u0026\u0026 l5.cols \u003e 0, g10 = h5.rows \u003e 0 \u0026\u0026 h5.cols \u003e 0, f10 = d9.rows \u003e 0 \u0026\u0026 d9.cols \u003e 0, _5 = u9.rows \u003e 0 \u0026\u0026 u9.cols \u003e 0, y10 = p9.rows \u003e 0 \u0026\u0026 p9.cols \u003e 0;\n if (m9 \u0026\u0026 g10)\n for (let e60 = 0;e60 \u003c this.bandRows; e60++)\n c5(this.cellIdFor(0, e60, l5.cols - 1), this.cellIdFor(1, e60, 0));\n if (g10 \u0026\u0026 f10)\n for (let e60 = 0;e60 \u003c this.bandRows; e60++)\n c5(this.cellIdFor(1, e60, h5.cols - 1), this.cellIdFor(2, e60, 0));\n if (m9 \u0026\u0026 _5)\n for (let e60 = this.fineRows - this.bandRows;e60 \u003c this.fineRows; e60++)\n c5(this.cellIdFor(0, e60, l5.cols - 1), this.cellIdFor(3, e60 - (this.fineRows - this.bandRows), 0));\n if (_5 \u0026\u0026 f10)\n for (let e60 = this.fineRows - this.bandRows;e60 \u003c this.fineRows; e60++)\n c5(this.cellIdFor(3, e60 - (this.fineRows - this.bandRows), u9.cols - 1), this.cellIdFor(2, e60, 0));\n if (m9 \u0026\u0026 y10)\n for (let e60 = this.bandRows;e60 \u003c this.fineRows - this.bandRows; e60++)\n c5(this.cellIdFor(0, e60, l5.cols - 1), this.cellIdFor(4, Math.floor((e60 - this.bandRows) / this.lowScale), 0));\n if (f10 \u0026\u0026 y10)\n for (let e60 = this.bandRows;e60 \u003c this.fineRows - this.bandRows; e60++)\n c5(this.cellIdFor(4, Math.floor((e60 - this.bandRows) / this.lowScale), p9.cols - 1), this.cellIdFor(2, e60, 0));\n if (g10 \u0026\u0026 y10)\n for (let e60 = this.bandCols;e60 \u003c this.fineCols - this.bandCols; e60++)\n c5(this.cellIdFor(1, h5.rows - 1, e60 - this.bandCols), this.cellIdFor(4, 0, Math.floor((e60 - this.bandCols) / this.lowScale)));\n if (_5 \u0026\u0026 y10)\n for (let e60 = this.bandCols;e60 \u003c this.fineCols - this.bandCols; e60++)\n c5(this.cellIdFor(4, p9.rows - 1, Math.floor((e60 - this.bandCols) / this.lowScale)), this.cellIdFor(3, 0, e60 - this.bandCols));\n if (!y10 \u0026\u0026 !g10 \u0026\u0026 !_5 \u0026\u0026 m9 \u0026\u0026 f10)\n for (let e60 = 0;e60 \u003c Math.min(l5.rows, d9.rows); e60++)\n c5(this.cellIdFor(0, e60, l5.cols - 1), this.cellIdFor(2, e60, 0));\n if (!y10 \u0026\u0026 !m9 \u0026\u0026 !f10 \u0026\u0026 g10 \u0026\u0026 _5)\n for (let e60 = 0;e60 \u003c Math.min(h5.cols, u9.cols); e60++)\n c5(this.cellIdFor(1, h5.rows - 1, e60), this.cellIdFor(3, 0, e60));\n const b10 = this.flattenNeighborLists(a9);\n this.neighborOffset = b10.offset, this.neighborIds = b10.ids, this.neighborCosts = b10.costs;\n }\n cellIdFor(e54, t4, n8) {\n const o10 = this.regions[e54];\n return o10.offset + t4 * o10.cols + n8;\n }\n stepOnce() {\n if (!this.activeConnSeg) {\n if (this.unsolvedSegs.length === 0)\n return void (this.solved = true);\n const e60 = this.unsolvedSegs.shift();\n this.activeConnSeg = e60, this.activeConnId = e60.connId, this.nodePool.clear(), this.ripChain.clear(), this.heap.clear(), this.seqCounter = 0, this.searchIterations = 0, this.nextStamp();\n const t10 = this.computeH(e60.startZ, e60.startCellId, e60.endZ, e60.endCellId) * this.hyperParameters.greedyMultiplier, n10 = this.nodePool.push(e60.startZ, e60.startCellId, 0, -1, -1, 0), o11 = e60.startZ * this.planeSize + e60.startCellId, i9 = this.getSearchStateIdx(o11, 0);\n return this.bestGStamp[i9] = this.stamp, this.bestGValue[i9] = 0, void this.heap.push(t10, this.seqCounter++, n10);\n }\n this.searchIterations++;\n const e54 = this.ripCount[this.activeConnId] ?? 0, t4 = Math.round(this.baseSearchBudgetIters * (1 + 0.25 * Math.min(e54, 10)));\n if (this.searchIterations \u003e t4) {\n const e60 = this.penalty2d;\n for (let t10 = 0;t10 \u003c e60.length; t10++)\n e60[t10] = 0.9 * e60[t10];\n return this.unsolvedSegs.push(this.activeConnSeg), this.activeConnSeg = null, this.activeConnId = -1, this.heap.clear(), this.nodePool.clear(), this.consecutiveSkips++, void (this.consecutiveSkips \u003e= Math.max(3, 3 * this.unsolvedSegs.length) \u0026\u0026 (this.error = `Convergence failure: ${this.unsolvedSegs.length} connections stuck`, this.failed = true));\n }\n if (this.heap.size === 0)\n return this.error = `No path found for ${this.connIdToName[this.activeConnId]}`, void (this.failed = true);\n const n8 = this.heap.pop(), o10 = this.nodePool.z[n8], i8 = this.nodePool.cellId[n8], r9 = this.nodePool.g[n8], s7 = this.nodePool.ripHead[n8], a9 = this.nodePool.ripCount[n8], c5 = o10 * this.planeSize + i8, l5 = this.getSearchStateIdx(c5, a9);\n if (this.visitedStamp[l5] === this.stamp)\n return;\n this.visitedStamp[l5] = this.stamp, this.visitedFlatStamp[c5] = this.stamp;\n const h5 = this.activeConnSeg;\n if (o10 === h5.endZ \u0026\u0026 i8 === h5.endCellId)\n return this.finalizeRoute(n8), this.activeConnSeg = null, void (this.activeConnId = -1);\n const d9 = this.visitedStamp, u9 = this.stamp, p9 = this.activeConnId, m9 = h5.endZ, g10 = h5.endCellId, f10 = this.neighborOffset[i8], _5 = this.neighborOffset[i8 + 1];\n for (let e60 = f10;e60 \u003c _5; e60++) {\n const t10 = this.neighborIds[e60], c9 = o10 * this.planeSize + t10;\n if (this.computeMoveCostAndRips(p9, o10, i8, t10, false, s7, a9, this.neighborCosts[e60]), this._moveCost \u003c 0)\n continue;\n const l10 = this.getSearchStateIdx(c9, this._moveRipCount);\n if (d9[l10] === u9)\n continue;\n const h9 = r9 + this._moveCost;\n if (this.bestGStamp[l10] === u9 \u0026\u0026 h9 \u003e= this.bestGValue[l10])\n continue;\n this.bestGStamp[l10] = u9, this.bestGValue[l10] = h9;\n const f11 = h9 + this.computeH(o10, t10, m9, g10) * this.hyperParameters.greedyMultiplier, _10 = this.nodePool.push(o10, t10, h9, n8, this._moveRippedHead, this._moveRipCount);\n this.heap.push(f11, this.seqCounter++, _10);\n }\n if (this.viaAllowed[i8])\n for (let e60 = 0;e60 \u003c this.layers; e60++) {\n if (e60 === o10)\n continue;\n const t10 = e60 * this.planeSize + i8;\n if (this.computeMoveCostAndRips(p9, e60, i8, i8, true, s7, a9, 0), this._moveCost \u003c 0)\n continue;\n const c9 = this.getSearchStateIdx(t10, this._moveRipCount);\n if (d9[c9] === u9)\n continue;\n const l10 = r9 + this._moveCost;\n if (this.bestGStamp[c9] === u9 \u0026\u0026 l10 \u003e= this.bestGValue[c9])\n continue;\n this.bestGStamp[c9] = u9, this.bestGValue[c9] = l10;\n const h9 = l10 + this.computeH(e60, i8, m9, g10) * this.hyperParameters.greedyMultiplier, f11 = this.nodePool.push(e60, i8, l10, n8, this._moveRippedHead, this._moveRipCount);\n this.heap.push(h9, this.seqCounter++, f11);\n }\n }\n computeMoveCostAndRips(e54, t4, n8, o10, i8, r9, s7, a9) {\n let c5 = 0, l5 = r9, h5 = s7;\n const d9 = t4 * this.planeSize + o10, u9 = i8 ? this.obstacleViaRootIdsByCell[o10] : [...this.obstacleTraceRootIdsFlat[t4 * this.planeSize + n8] ?? [], ...this.obstacleTraceRootIdsFlat[d9] ?? []];\n if (this.isBlockedByObstacleRoots(u9, e54) \u0026\u0026 (i8 ? this.isViaMoveBlockedByObstacleGeometry({ activeConn: e54, cellId: o10 }) : this.isLateralMoveBlockedByObstacleGeometry({ activeConn: e54, layer: t4, fromCellId: n8, toCellId: o10 })))\n return this._moveCost = -1, this._moveRippedHead = l5, void (this._moveRipCount = h5);\n const p9 = this.hasSameRootObstacle(u9, e54);\n if (i8) {\n c5 += this.hyperParameters.viaBaseCost, c5 += Math.min(this.penalty2d[o10], this.penaltyCap);\n const n10 = this.portOwnerFlat[d9], i9 = this.allowSharedUse(e54, n10), r10 = this.activeConnSeg, s9 = !!r10 \u0026\u0026 t4 === r10.endZ \u0026\u0026 o10 === r10.endCellId;\n if (n10 \u003e= 0 \u0026\u0026 n10 !== e54 \u0026\u0026 !i9 \u0026\u0026 !s9)\n return this._moveCost = -1, void (this._moveRippedHead = l5);\n this.fillViaOccupants(o10, e54);\n const a10 = this._viaOccs;\n for (let e60 = 0;e60 \u003c a10.length; e60++) {\n const t10 = a10[e60];\n this.ripChain.contains(l5, t10) || (c5 += this.hyperParameters.ripCost, l5 = this.ripChain.append(l5, t10), h5++), c5 += this.hyperParameters.ripViaPenalty;\n }\n } else {\n c5 += a9, c5 += Math.min(this.penalty2d[o10], this.penaltyCap);\n const n10 = this.portOwnerFlat[d9], i9 = this.allowSharedUse(e54, n10), r10 = this.activeConnSeg, s9 = !!r10 \u0026\u0026 t4 === r10.endZ \u0026\u0026 o10 === r10.endCellId;\n if (n10 \u003e= 0 \u0026\u0026 n10 !== e54 \u0026\u0026 !i9 \u0026\u0026 !s9)\n return this._moveCost = -1, void (this._moveRippedHead = l5);\n this.fillTraceOccupants(d9, e54, this._cellOccs);\n for (let e60 = 0;e60 \u003c this._cellOccs.length; e60++) {\n const t10 = this._cellOccs[e60];\n this.ripChain.contains(l5, t10) || (c5 += this.hyperParameters.ripCost, l5 = this.ripChain.append(l5, t10), h5++), c5 += this.hyperParameters.ripTracePenalty;\n }\n }\n p9 \u0026\u0026 (c5 *= this.hyperParameters.sameRootObstacleCostMultiplier), this._moveCost = c5, this._moveRippedHead = l5, this._moveRipCount = h5;\n }\n fillViaOccupants(e54, t4) {\n const n8 = this._viaOccs;\n n8.length = 0;\n const o10 = this.cellCenterX[e54], i8 = this.cellCenterY[e54];\n this.forEachCellNearCircle(o10, i8, this.viaKeepoutRadius, (e60) =\u003e {\n if (voe(o10, i8, this.viaKeepoutRadius, this.cellMinX[e60], this.cellMinY[e60], this.cellMaxX[e60], this.cellMaxY[e60]))\n for (let o11 = 0;o11 \u003c this.layers; o11++)\n this.pushFlatOccupants(o11 * this.planeSize + e60, t4, n8);\n });\n }\n fillTraceOccupants(e54, t4, n8) {\n n8.length = 0, this.pushFlatOccupants(e54, t4, n8);\n }\n pushFlatOccupants(e54, t4, n8) {\n const o10 = this.usedCellsFlat[e54];\n o10 === -1 || o10 === t4 || this.allowSharedUse(t4, o10) || boe(n8, o10);\n const i8 = this.sharedCellsFlat[e54];\n if (i8)\n for (let e60 = 0;e60 \u003c i8.length; e60++) {\n const o11 = i8[e60];\n o11 !== t4 \u0026\u0026 (this.allowSharedUse(t4, o11) || boe(n8, o11));\n }\n }\n addSharedOccupant(e54, t4) {\n if (this.usedCellsFlat[e54] === t4)\n return;\n let n8 = this.sharedCellsFlat[e54];\n n8 || (n8 = [], this.sharedCellsFlat[e54] = n8), boe(n8, t4);\n }\n replaceOccupants(e54, t4) {\n this.usedCellsFlat[e54] = t4, this.sharedCellsFlat[e54] = undefined;\n }\n removeOccupant(e54, t4) {\n const n8 = this.sharedCellsFlat[e54];\n if (this.usedCellsFlat[e54] === t4)\n return void (n8 \u0026\u0026 n8.length \u003e 0 ? (this.usedCellsFlat[e54] = n8.pop(), n8.length === 0 \u0026\u0026 (this.sharedCellsFlat[e54] = undefined)) : this.usedCellsFlat[e54] = -1);\n if (!n8)\n return;\n const o10 = n8.indexOf(t4);\n o10 !== -1 \u0026\u0026 (n8.splice(o10, 1), n8.length === 0 \u0026\u0026 (this.sharedCellsFlat[e54] = undefined));\n }\n allowSharedUse(e54, t4) {\n if (t4 \u003c 0)\n return false;\n return this.connIdToRootNet[t4] === this.connIdToRootNet[e54];\n }\n shouldSkipFixedPortHalo(e54, t4) {\n const n8 = this.portOwnerFlat[e54];\n return n8 !== t4 \u0026\u0026 (n8 === -2 || !(n8 \u003c 0) \u0026\u0026 !this.allowSharedUse(t4, n8));\n }\n nextStamp() {\n this.stamp = this.stamp + 1 \u003e\u003e\u003e 0, this.stamp === 0 \u0026\u0026 (this.visitedStamp.fill(0), this.bestGStamp.fill(0), this.visitedFlatStamp.fill(0), this.stamp = 1);\n }\n getSearchStateIdx(e54, t4) {\n return e54;\n }\n computeH(e54, t4, n8, o10) {\n const i8 = Math.hypot(this.cellCenterX[t4] - this.cellCenterX[o10], this.cellCenterY[t4] - this.cellCenterY[o10]);\n return e54 === n8 ? i8 : i8 + this.hyperParameters.viaBaseCost;\n }\n internConn(e54, t4) {\n const n8 = this.connNameToId.get(e54);\n if (n8 !== undefined)\n return n8;\n const o10 = this.connIdToName.length;\n return this.connIdToName.push(e54), this.connIdToRootNet.push(goe(e54, t4)), this.connNameToId.set(e54, o10), o10;\n }\n buildConnectionSegs() {\n const e54 = new Map;\n for (const t10 of this.nodeWithPortPoints.portPoints) {\n const n10 = t10.connectionName;\n e54.has(n10) || e54.set(n10, { points: [], rootConnectionName: t10.rootConnectionName }), e54.get(n10).points.push(t10);\n }\n const t4 = [], n8 = new Map;\n for (const [o10, i8] of e54) {\n const e60 = i8.points, r9 = eoe(e60);\n if (r9.length === 0)\n continue;\n const s7 = this.internConn(o10, i8.rootConnectionName);\n for (const [e61, i9] of r9) {\n const r10 = this.pointToCell(e61), a9 = this.pointToCell(i9), c5 = `${r10.z}:${r10.cellId}`, l5 = `${a9.z}:${a9.cellId}`, h5 = c5 \u003c l5 ? `${c5}|${l5}` : `${l5}|${c5}`, d9 = this.connIdToRootNet[s7], u9 = `${d9}|${h5}`, p9 = n8.get(u9);\n if (p9) {\n if (this.overlapFriendlyRootNets.add(d9), !p9.connectionAliases.some((e63) =\u003e e63.connectionName === o10)) {\n const t10 = p9.startZ === r10.z \u0026\u0026 p9.startCellId === r10.cellId \u0026\u0026 p9.endZ === a9.z \u0026\u0026 p9.endCellId === a9.cellId, n10 = p9.startZ === a9.z \u0026\u0026 p9.startCellId === a9.cellId \u0026\u0026 p9.endZ === r10.z \u0026\u0026 p9.endCellId === r10.cellId;\n if (!t10 \u0026\u0026 !n10)\n throw new Error(`Connection alias ${o10} does not match canonical segment ${u9}`);\n p9.connectionAliases.push({ connectionName: o10, rootConnectionName: d9, startPoint: e61, endPoint: i9, reversedFromCanonical: !t10 \u0026\u0026 n10 });\n }\n continue;\n }\n const m9 = { connId: s7, startZ: r10.z, startCellId: r10.cellId, startPoint: e61, endZ: a9.z, endCellId: a9.cellId, endPoint: i9, connectionAliases: [{ connectionName: o10, rootConnectionName: d9, startPoint: e61, endPoint: i9, reversedFromCanonical: false }] };\n n8.set(u9, m9), t4.push(m9);\n }\n }\n return t4;\n }\n pointToCell(e54) {\n const t4 = yoe(Math.floor((e54.x - this.boundsMinX) / this.highResolutionCellSize), 0, this.fineCols - 1), n8 = yoe(Math.floor((e54.y - this.boundsMinY) / this.highResolutionCellSize), 0, this.fineRows - 1);\n let o10 = 4;\n t4 \u003c this.bandCols ? o10 = 0 : t4 \u003e= this.fineCols - this.bandCols ? o10 = 2 : n8 \u003c this.bandRows ? o10 = 1 : n8 \u003e= this.fineRows - this.bandRows \u0026\u0026 (o10 = 3);\n const i8 = this.regions[o10], r9 = n8 - i8.fineOriginRow, s7 = t4 - i8.fineOriginCol, a9 = yoe(Math.floor(r9 / i8.cellScale), 0, Math.max(0, i8.rows - 1)), c5 = yoe(Math.floor(s7 / i8.cellScale), 0, Math.max(0, i8.cols - 1));\n return { z: this.zToLayer.get(e54.z) ?? 0, cellId: this.cellIdFor(o10, a9, c5) };\n }\n shuffleConnections() {\n const e54 = this.unsolvedSegs;\n let t4 = this.hyperParameters.shuffleSeed \u003e\u003e\u003e 0;\n const n8 = () =\u003e (t4 = Math.imul(t4, 1664525) + 1013904223 \u003e\u003e\u003e 0, t4 / 4294967295);\n for (let t10 = e54.length - 1;t10 \u003e 0; t10--) {\n const o10 = Math.floor(n8() * (t10 + 1)), i8 = e54[t10];\n e54[t10] = e54[o10], e54[o10] = i8;\n }\n }\n finalizeRoute(e54) {\n this.consecutiveSkips = Math.max(0, this.consecutiveSkips - 1);\n const t4 = [];\n let n8 = e54;\n for (;n8 \u003e= 0; ) {\n const e60 = this.nodePool.z[n8], o11 = this.nodePool.cellId[n8];\n t4.push(e60 * this.planeSize + o11), n8 = this.nodePool.parent[n8];\n }\n for (t4.reverse();t4.length \u003e 1 \u0026\u0026 this.sharedCrossRootPortFlat[t4[0]]; )\n t4.shift();\n for (;t4.length \u003e 1 \u0026\u0026 this.sharedCrossRootPortFlat[t4[t4.length - 1]]; )\n t4.pop();\n const o10 = this.extractViaCellIds(t4), i8 = this.activeConnId;\n this.ripChain.collect(this.nodePool.ripHead[e54], this._rippedIds);\n for (let e60 = 0;e60 \u003c this._rippedIds.length; e60++)\n if (this.ripTrace(this._rippedIds[e60]), this.failed)\n return;\n const r9 = [];\n for (let e60 = 0;e60 \u003c t4.length; e60++) {\n const n10 = t4[e60], o11 = Math.floor(n10 / this.planeSize), s9 = n10 - o11 * this.planeSize;\n this.markTraceFootprint(i8, o11, s9, r9);\n }\n const s7 = [];\n for (let e60 = 0;e60 \u003c o10.length; e60++)\n this.markViaFootprint(i8, o10[e60], r9, s7);\n for (;this.usedIndicesByConn.length \u003c= i8; )\n this.usedIndicesByConn.push(undefined);\n const a9 = this.usedIndicesByConn[i8] ?? [];\n for (a9.push(...r9), this.usedIndicesByConn[i8] = a9;this.solvedRoutes.length \u003c= i8; )\n this.solvedRoutes.push(undefined);\n const c5 = this.solvedRoutes[i8] ?? [];\n c5.push({ connId: i8, states: Int32Array.from(t4), viaCellIds: Int32Array.from(o10), startPoint: this.activeConnSeg.startPoint, endPoint: this.activeConnSeg.endPoint, connectionAliases: this.activeConnSeg.connectionAliases }), this.solvedRoutes[i8] = c5;\n for (let e60 = 0;e60 \u003c s7.length; e60++)\n if (this.ripTrace(s7[e60]), this.failed)\n return;\n if (this._rippedIds.length \u003e 0 || s7.length \u003e 0) {\n const e60 = this.penalty2d, t10 = this.penaltyCap;\n if (this.totalRipEvents \u003e 50)\n for (let t11 = 0;t11 \u003c e60.length; t11++)\n e60[t11] = 0.99 * e60[t11];\n else\n for (let n10 = 0;n10 \u003c e60.length; n10++)\n e60[n10] \u003e t10 \u0026\u0026 (e60[n10] = 0.5 * e60[n10]);\n }\n }\n extractViaCellIds(e54) {\n const t4 = [];\n for (let n8 = 1;n8 \u003c e54.length; n8++) {\n const o10 = e54[n8 - 1], i8 = e54[n8], r9 = Math.floor(o10 / this.planeSize), s7 = Math.floor(i8 / this.planeSize);\n r9 !== s7 \u0026\u0026 t4.push(i8 - s7 * this.planeSize);\n }\n return t4;\n }\n markTraceFootprint(e54, t4, n8, o10) {\n const i8 = this.cellCenterX[n8], r9 = this.cellCenterY[n8];\n this.forEachCellNearCircle(i8, r9, this.traceKeepoutRadius, (s7) =\u003e {\n if (!voe(i8, r9, this.traceKeepoutRadius, this.cellMinX[s7], this.cellMinY[s7], this.cellMaxX[s7], this.cellMaxY[s7]))\n return;\n const a9 = t4 * this.planeSize + s7;\n if (s7 !== n8 \u0026\u0026 this.shouldSkipFixedPortHalo(a9, e54))\n return;\n const c5 = this.usedCellsFlat[a9], l5 = this.allowSharedUse(e54, c5);\n (c5 === -1 || c5 === e54 || l5) \u0026\u0026 (c5 !== -1 \u0026\u0026 c5 !== e54 ? this.addSharedOccupant(a9, e54) : this.usedCellsFlat[a9] = e54, o10.push(a9));\n });\n }\n markViaFootprint(e54, t4, n8, o10) {\n const i8 = this.cellCenterX[t4], r9 = this.cellCenterY[t4];\n this.forEachCellNearCircle(i8, r9, this.viaKeepoutRadius, (s7) =\u003e {\n if (voe(i8, r9, this.viaKeepoutRadius, this.cellMinX[s7], this.cellMinY[s7], this.cellMaxX[s7], this.cellMaxY[s7]))\n for (let i9 = 0;i9 \u003c this.layers; i9++) {\n const r10 = i9 * this.planeSize + s7;\n if (s7 !== t4 \u0026\u0026 this.shouldSkipFixedPortHalo(r10, e54))\n continue;\n if (this.fillTraceOccupants(r10, e54, this._cellOccs), this._cellOccs.length \u003e 0) {\n for (let e60 = 0;e60 \u003c this._cellOccs.length; e60++)\n boe(o10, this._cellOccs[e60]);\n this.replaceOccupants(r10, e54), n8.push(r10);\n continue;\n }\n const a9 = this.usedCellsFlat[r10];\n a9 !== -1 \u0026\u0026 a9 !== e54 ? this.addSharedOccupant(r10, e54) : this.usedCellsFlat[r10] = e54, n8.push(r10);\n }\n });\n }\n forEachCellNearCircle(e54, t4, n8, o10) {\n const i8 = yoe(Math.floor((e54 - n8 - this.boundsMinX) / this.highResolutionCellSize), 0, this.fineCols - 1), r9 = yoe(Math.floor((e54 + n8 - this.boundsMinX) / this.highResolutionCellSize), 0, this.fineCols - 1), s7 = yoe(Math.floor((t4 - n8 - this.boundsMinY) / this.highResolutionCellSize), 0, this.fineRows - 1), a9 = yoe(Math.floor((t4 + n8 - this.boundsMinY) / this.highResolutionCellSize), 0, this.fineRows - 1);\n for (let e60 = 0;e60 \u003c this.regions.length; e60++) {\n const t10 = this.regions[e60];\n if (t10.rows === 0 || t10.cols === 0)\n continue;\n const n10 = Math.max(s7, t10.fineOriginRow), c5 = Math.min(a9, t10.fineOriginRow + t10.fineRows - 1), l5 = Math.max(i8, t10.fineOriginCol), h5 = Math.min(r9, t10.fineOriginCol + t10.fineCols - 1);\n if (n10 \u003e c5)\n continue;\n if (l5 \u003e h5)\n continue;\n const d9 = Math.floor((n10 - t10.fineOriginRow) / t10.cellScale), u9 = Math.floor((c5 - t10.fineOriginRow) / t10.cellScale), p9 = Math.floor((l5 - t10.fineOriginCol) / t10.cellScale), m9 = Math.floor((h5 - t10.fineOriginCol) / t10.cellScale);\n for (let e61 = d9;e61 \u003c= u9; e61++)\n for (let n11 = p9;n11 \u003c= m9; n11++)\n o10(this.cellIdFor(t10.id, e61, n11));\n }\n }\n ripTrace(e54) {\n for (;this.ripCount.length \u003c= e54; )\n this.ripCount.push(0);\n if (this.ripCount[e54]++, this.totalRipEvents++, this.totalRipEvents \u003e= this.MAX_RIPS)\n return this.error = `Convergence failure: exceeded MAX_RIPS ${this.MAX_RIPS}`, void (this.failed = true);\n const t4 = this.getSolvedRoutesForConn(e54);\n if (t4.length \u003e 0)\n for (const e60 of t4) {\n for (let t10 = 0;t10 \u003c e60.states.length; t10++) {\n const n10 = e60.states[t10] % this.planeSize;\n this.penalty2d[n10] = this.penalty2d[n10] + this.hyperParameters.ripTracePenalty;\n }\n for (let t10 = 0;t10 \u003c e60.viaCellIds.length; t10++) {\n const n10 = e60.viaCellIds[t10];\n this.penalty2d[n10] = this.penalty2d[n10] + this.hyperParameters.ripViaPenalty;\n }\n }\n const n8 = this.usedIndicesByConn[e54];\n if (n8) {\n for (let t10 = 0;t10 \u003c n8.length; t10++)\n this.removeOccupant(n8[t10], e54);\n this.usedIndicesByConn[e54] = undefined;\n }\n if (t4.length \u003e 0) {\n this.solvedRoutes[e54] = undefined;\n for (const n10 of t4) {\n const t10 = n10.states[0], o10 = n10.states[n10.states.length - 1], i8 = Math.floor(t10 / this.planeSize), r9 = Math.floor(o10 / this.planeSize);\n this.unsolvedSegs.push({ connId: e54, startZ: i8, startCellId: t10 - i8 * this.planeSize, startPoint: n10.startPoint, endZ: r9, endCellId: o10 - r9 * this.planeSize, endPoint: n10.endPoint, connectionAliases: n10.connectionAliases });\n }\n }\n }\n flattenNeighborLists(e54) {\n const t4 = new Int32Array(e54.length + 1);\n let n8 = 0;\n for (let o11 = 0;o11 \u003c e54.length; o11++)\n t4[o11] = n8, n8 += e54[o11].length;\n t4[e54.length] = n8;\n const o10 = new Int32Array(n8), i8 = new Float32Array(n8);\n let r9 = 0;\n for (let t10 = 0;t10 \u003c e54.length; t10++) {\n const n10 = e54[t10];\n for (let e60 = 0;e60 \u003c n10.length; e60++) {\n const t11 = n10[e60];\n o10[r9] = t11.cellId, i8[r9] = t11.cost, r9++;\n }\n }\n return { offset: t4, ids: o10, costs: i8 };\n }\n visualize() {\n const e54 = [\"red\", \"blue\", \"orange\", \"green\"], t4 = this.gridToBoundsTransform, n8 = [], o10 = [], i8 = [], r9 = [];\n r9.push({ center: { x: this.nodeWithPortPoints.center.x, y: this.nodeWithPortPoints.center.y }, width: this.nodeWithPortPoints.width, height: this.nodeWithPortPoints.height, stroke: \"gray\" });\n const s7 = ({ route: t10, connectionName: n10, strokeWidth: i9, strokeDash: r10, labelPrefix: s9 }) =\u003e {\n if (t10.length \u003c 2)\n return;\n let a10 = 0;\n for (let c9 = 1;c9 \u003c t10.length; c9 += 1) {\n const l5 = t10[c9 - 1];\n t10[c9].z !== l5.z \u0026\u0026 (c9 - a10 \u003e= 2 \u0026\u0026 o10.push({ points: t10.slice(a10, c9).map((e60) =\u003e ({ x: e60.x, y: e60.y })), strokeColor: e54[l5.z] ?? \"rgba(128,128,128,0.75)\", strokeWidth: i9, strokeDash: r10, label: `${s9} ${n10} z=${l5.z}` }), a10 = c9);\n }\n if (t10.length - a10 \u003c 2)\n return;\n const c5 = t10[a10].z;\n o10.push({ points: t10.slice(a10).map((e60) =\u003e ({ x: e60.x, y: e60.y })), strokeColor: e54[c5] ?? \"rgba(128,128,128,0.75)\", strokeWidth: i9, strokeDash: r10, label: `${s9} ${n10} z=${c5}` });\n };\n for (const e60 of this.obstacles)\n if (e60.type !== \"rect\") {\n s7({ route: e60.route, connectionName: e60.connectionName, strokeWidth: e60.traceThickness, strokeDash: [0.12, 0.08], labelPrefix: \"fixed obstacle\" });\n for (const t10 of e60.vias)\n i8.push({ center: { x: t10.x, y: t10.y }, radius: e60.viaDiameter / 2, fill: \"rgba(128,0,128,0.25)\", stroke: \"purple\", label: `fixed obstacle ${e60.connectionName} via` });\n } else\n r9.push({ center: e60.center, width: e60.width, height: e60.height, fill: \"rgba(128,0,128,0.12)\", stroke: \"purple\", label: `fixed obstacle ${e60.connectionName}` });\n if (this.showPenaltyMap \u0026\u0026 this.penalty2d) {\n let e60 = 0;\n for (let t10 = 0;t10 \u003c this.penalty2d.length; t10++)\n this.penalty2d[t10] \u003e e60 \u0026\u0026 (e60 = this.penalty2d[t10]);\n if (e60 \u003e 0)\n for (let n10 = 0;n10 \u003c this.planeSize; n10++) {\n const o11 = this.penalty2d[n10];\n if (o11 \u003c= 0)\n continue;\n const i9 = Une(t4, { x: this.cellCenterX[n10], y: this.cellCenterY[n10] }), s9 = Math.min(0.6, o11 / e60 * 0.6);\n r9.push({ center: i9, width: this.cellWidth[n10] * t4.a, height: this.cellHeight[n10] * t4.e, fill: `rgba(255,165,0,${s9.toFixed(3)})` });\n }\n }\n if (this.showUsedCellMap \u0026\u0026 this.usedCellsFlat)\n for (let e60 = 0;e60 \u003c this.layers; e60++) {\n const n10 = e60 * this.planeSize;\n for (let e61 = 0;e61 \u003c this.planeSize; e61++) {\n if (this.usedCellsFlat[n10 + e61] === -1)\n continue;\n const o11 = Une(t4, { x: this.cellCenterX[e61], y: this.cellCenterY[e61] });\n r9.push({ center: o11, width: this.cellWidth[e61] * t4.a, height: this.cellHeight[e61] * t4.e, fill: \"rgba(0,0,255,0.5)\" });\n }\n }\n for (const t10 of this.nodeWithPortPoints.portPoints)\n n8.push({ x: t10.x, y: t10.y, color: e54[t10.z] ?? \"gray\", label: t10.connectionName });\n const a9 = this.getOutput();\n for (const e60 of a9)\n s7({ route: e60.route, connectionName: e60.connectionName, strokeWidth: this.traceThickness, labelPrefix: \"B01 route\" });\n for (const e60 of a9)\n for (const t10 of e60.vias)\n i8.push({ center: { x: t10.x, y: t10.y }, radius: this.viaDiameter / 2, fill: \"rgba(0,0,0,0.3)\", stroke: \"black\", label: `B01 route ${e60.connectionName} via` });\n if (this.activeConnSeg \u0026\u0026 this.visitedFlatStamp) {\n const e60 = this.stamp;\n for (let o11 = 0;o11 \u003c this.layers; o11++) {\n const i9 = o11 * this.planeSize;\n for (let o12 = 0;o12 \u003c this.planeSize; o12++) {\n if (this.visitedFlatStamp[i9 + o12] !== e60)\n continue;\n const r10 = Une(t4, { x: this.cellCenterX[o12], y: this.cellCenterY[o12] });\n n8.push({ x: r10.x, y: r10.y, color: \"rgba(0,0,255,0.2)\" });\n }\n }\n }\n return { points: n8, lines: o10, circles: i8, rects: r9, coordinateSystem: \"cartesian\", title: `HighDensityB01 [${this.getSolvedRouteCount()} solved, ${this.unsolvedSegs?.length ?? 0} remaining]` };\n }\n getOutput() {\n const e54 = this.gridToBoundsTransform, t4 = [];\n for (let n8 = 0;n8 \u003c this.solvedRoutes.length; n8++) {\n const o10 = this.getSolvedRoutesForConn(n8);\n if (o10.length !== 0)\n for (const n10 of o10) {\n const o11 = Array.from(n10.states, (t10) =\u003e {\n const n11 = Math.floor(t10 / this.planeSize), o12 = t10 - n11 * this.planeSize, i9 = Une(e54, { x: this.cellCenterX[o12], y: this.cellCenterY[o12] });\n return { x: i9.x, y: i9.y, z: this.layerToZ.get(n11) ?? n11 };\n }), i8 = Array.from(n10.viaCellIds, (t10) =\u003e Une(e54, { x: this.cellCenterX[t10], y: this.cellCenterY[t10] }));\n for (const e60 of n10.connectionAliases) {\n const n11 = (e60.reversedFromCanonical ? [...o11].reverse() : o11).map((e61) =\u003e ({ ...e61 }));\n n11.length \u003e 0 \u0026\u0026 (n11[0] = { ...e60.startPoint }, n11.length \u003e 1 \u0026\u0026 (n11[n11.length - 1] = { ...e60.endPoint })), t4.push({ connectionName: e60.connectionName, rootConnectionName: e60.rootConnectionName, regionId: this.nodeWithPortPoints.capacityMeshNodeId, traceThickness: this.traceThickness, viaDiameter: this.viaDiameter, route: n11, vias: i8.map((e61) =\u003e ({ ...e61 })) });\n }\n }\n }\n return t4;\n }\n getSolvedRoutesForConn(e54) {\n const t4 = this.solvedRoutes[e54];\n return t4 ? Array.isArray(t4) ? t4 : [t4] : [];\n }\n getSolvedRouteCount() {\n let e54 = 0;\n for (let t4 = 0;t4 \u003c this.solvedRoutes.length; t4++)\n e54 += this.getSolvedRoutesForConn(t4).length;\n return e54;\n }\n computeGridToBoundsTransform() {\n let e54 = 1 / 0, t4 = -1 / 0, n8 = 1 / 0, o10 = -1 / 0;\n for (let i9 = 0;i9 \u003c this.planeSize; i9++) {\n const r10 = this.cellCenterX[i9], s9 = this.cellCenterY[i9];\n r10 \u003c e54 \u0026\u0026 (e54 = r10), r10 \u003e t4 \u0026\u0026 (t4 = r10), s9 \u003c n8 \u0026\u0026 (n8 = s9), s9 \u003e o10 \u0026\u0026 (o10 = s9);\n }\n const i8 = t4 - e54, r9 = o10 - n8, s7 = this.boundsMaxX - this.boundsMinX, a9 = this.boundsMaxY - this.boundsMinY, c5 = i8 \u003e 0 ? s7 / i8 : 1, l5 = r9 \u003e 0 ? a9 / r9 : 1;\n return { a: c5, b: 0, c: i8 \u003e 0 ? this.boundsMinX - c5 * e54 : (this.boundsMinX + this.boundsMaxX) / 2 - e54, d: 0, e: l5, f: r9 \u003e 0 ? this.boundsMinY - l5 * n8 : (this.boundsMinY + this.boundsMaxY) / 2 - n8 };\n }\n};\nvar Toe = ({ routes: e54, movablePreloadedConnectionNames: t4, boardObstacles: n8, connMap: o10, layerCount: i8, viaToPadClearance: r9, allowBlindAndBuriedVias: s7 }) =\u003e e54.some((e60) =\u003e {\n if (!t4.has(e60.connectionName))\n return false;\n return os(e60, { layerCount: i8, allowBlindAndBuriedVias: s7 }).viaSpans.some((t10) =\u003e n8.some((n10) =\u003e {\n if ((({ obstacle: e61, route: t11, connMap: n11 }) =\u003e {\n if (xo(e61, t11, n11))\n return true;\n if (!t11.rootConnectionName)\n return false;\n const o11 = n11.getNetConnectedToId(t11.connectionName) ?? n11.getNetConnectedToId(t11.rootConnectionName) ?? (n11.netMap[t11.rootConnectionName] ? t11.rootConnectionName : undefined);\n return !!o11 \u0026\u0026 e61.connectedTo.some((e63) =\u003e (n11.getNetConnectedToId(e63) ?? (n11.netMap[e63] ? e63 : undefined)) === o11);\n })({ obstacle: n10, route: e60, connMap: o10 }))\n return false;\n const s9 = ((e61, t11) =\u003e {\n const n11 = e61.__zLayers ?? e61.zLayers;\n return n11 || e61.layers.map((e63) =\u003e mo(e63, t11));\n })(n10, i8);\n return !!s9.some((e61) =\u003e e61 \u003e= t10.minZ \u0026\u0026 e61 \u003c= t10.maxZ) \u0026\u0026 ((e61, t11) =\u003e {\n const n11 = -1 * (t11.ccwRotationDegrees ?? 0) * Math.PI / 180, o11 = e61.x - t11.center.x, i9 = e61.y - t11.center.y, r10 = o11 * Math.cos(n11) - i9 * Math.sin(n11), s10 = o11 * Math.sin(n11) + i9 * Math.cos(n11), a9 = Math.max(Math.abs(r10) - t11.width / 2, 0), c5 = Math.max(Math.abs(s10) - t11.height / 2, 0);\n return Math.hypot(a9, c5);\n })(t10.center, n10) \u003c t10.diameter / 2 + r9;\n }));\n});\nvar Eoe = class extends ni {\n params;\n highDensitySolver;\n forceImproveSolver;\n repairSolver;\n phase = \"route\";\n constructor(e54) {\n super(), this.params = e54, this.stats = { preloadedViaCandidateRejectionCount: 0, forceImproveCandidateRejectionCount: 0, repairCandidateRejectionCount: 0 }, this.highDensitySolver = new Dz({ captureSearchDebug: e54.captureSearchDebug, nodePortPoints: [e54.nodeWithPortPoints], colorMap: e54.colorMap, connMap: e54.connMap, viaDiameter: e54.viaDiameter, traceWidth: e54.traceWidth, obstacleMargin: e54.obstacleMargin, effort: e54.effort, nodePfById: e54.nodePfById, obstacles: e54.obstacles, layerCount: e54.layerCount, useGrowShrinkHighDensityIntraNodeSolver: true, preserveTerminalPcbPortIds: false, growShrinkFallbackToInvalidGeometryOnFailure: false, growShrinkSolutionValidator: e54.boardObstacles \u0026\u0026 e54.movablePreloadedConnectionNames \u0026\u0026 e54.viaToPadClearance !== undefined ? (e60) =\u003e this.validateCandidateRoutes(e60) : undefined }), this.activeSubSolver = this.highDensitySolver, this.MAX_ITERATIONS = 1e8 * e54.effort;\n }\n getSolverName() {\n return \"Pipeline9RegionalFallbackSolver\";\n }\n validateCandidateRoutes(e54) {\n const { boardObstacles: t4, movablePreloadedConnectionNames: n8, viaToPadClearance: o10 } = this.params;\n if (!t4 || !n8 || o10 === undefined)\n return true;\n const i8 = Toe({ routes: e54, movablePreloadedConnectionNames: n8, boardObstacles: t4, connMap: this.params.connMap, layerCount: this.params.layerCount, allowBlindAndBuriedVias: this.params.allowBlindAndBuriedVias, viaToPadClearance: o10 });\n return i8 \u0026\u0026 (this.stats.preloadedViaCandidateRejectionCount = Number(this.stats.preloadedViaCandidateRejectionCount ?? 0) + 1), !i8;\n }\n _step() {\n if (this.phase === \"route\") {\n if (this.highDensitySolver.step(), this.highDensitySolver.failed)\n return this.error = this.highDensitySolver.error, void (this.failed = true);\n if (!this.highDensitySolver.solved)\n return;\n const e54 = yne(this.highDensitySolver.routes);\n return this.validateCandidateRoutes(e54) ? (this.forceImproveSolver = new SZ({ nodeWithPortPoints: [this.params.nodeWithPortPoints], hdRoutes: e54, colorMap: this.params.colorMap, totalStepsPerNode: Math.max(12, Math.round(20 * this.params.effort)), nodeAssignmentMargin: this.params.obstacleMargin }), this.activeSubSolver = this.forceImproveSolver, void (this.phase = \"improve\")) : (this.error = \"Pipeline9 regional route output failed its candidate validator\", void (this.failed = true));\n }\n if (this.phase === \"improve\") {\n if (this.forceImproveSolver.step(), this.forceImproveSolver.failed)\n return this.error = this.forceImproveSolver.error, void (this.failed = true);\n if (!this.forceImproveSolver.solved)\n return;\n const e54 = this.forceImproveSolver.getOutput();\n return this.validateCandidateRoutes(e54) ? (this.repairSolver = new g1({ nodeWithPortPoints: [this.params.nodeWithPortPoints], hdRoutes: e54, obstacles: this.params.obstacles, colorMap: this.params.colorMap, repairMargin: this.params.obstacleMargin, minimumTraceWidth: this.params.traceWidth, connMap: this.params.connMap }), this.activeSubSolver = this.repairSolver, void (this.phase = \"repair\")) : (this.stats.forceImproveCandidateRejectionCount = Number(this.stats.forceImproveCandidateRejectionCount ?? 0) + 1, this.error = \"Pipeline9 regional force-improve output failed its candidate validator\", void (this.failed = true));\n }\n if (this.phase === \"repair\") {\n if (this.repairSolver.step(), this.repairSolver.failed)\n return this.error = this.repairSolver.error, void (this.failed = true);\n if (!this.repairSolver.solved)\n return;\n const e54 = this.repairSolver.getOutput();\n return this.validateCandidateRoutes(e54) ? (this.activeSubSolver = null, this.phase = \"done\", void (this.solved = true)) : (this.stats.repairCandidateRejectionCount = Number(this.stats.repairCandidateRejectionCount ?? 0) + 1, this.error = \"Pipeline9 regional repair output failed its candidate validator\", void (this.failed = true));\n }\n }\n getOutput() {\n return this.repairSolver?.getOutput() ?? this.forceImproveSolver?.getOutput() ?? this.highDensitySolver.routes;\n }\n visualize() {\n return this.repairSolver?.visualize() ?? this.forceImproveSolver?.visualize() ?? this.highDensitySolver.visualize();\n }\n};\nvar Aoe = (e54, t4) =\u003e ({ minX: e54.center.x - e54.width / 2 - t4, maxX: e54.center.x + e54.width / 2 + t4, minY: e54.center.y - e54.height / 2 - t4, maxY: e54.center.y + e54.height / 2 + t4 });\nvar Ooe = (e54, t4, n8, o10, i8) =\u003e {\n const r9 = new Set(t4.availableZ ?? t4.portPoints.map((e60) =\u003e e60.z)), s7 = os(e54, i8);\n return s7.wireSegments.some((e60) =\u003e r9.has(e60.z) \u0026\u0026 ((e61, t10, n10, o11) =\u003e Math.min(e61.x, t10.x) - n10 \u003c= o11.maxX \u0026\u0026 Math.max(e61.x, t10.x) + n10 \u003e= o11.minX \u0026\u0026 Math.min(e61.y, t10.y) - n10 \u003c= o11.maxY \u0026\u0026 Math.max(e61.y, t10.y) + n10 \u003e= o11.minY)(e60.start, e60.end, e60.width / 2 + o10, n8)) || s7.viaSpans.some((e60) =\u003e [...r9].some((t10) =\u003e t10 \u003e= e60.minZ \u0026\u0026 t10 \u003c= e60.maxZ) \u0026\u0026 ((e61, t10, n10) =\u003e {\n const o11 = Math.max(n10.minX - e61.x, 0, e61.x - n10.maxX), i9 = Math.max(n10.minY - e61.y, 0, e61.y - n10.maxY);\n return o11 * o11 + i9 * i9 \u003c= t10 * t10;\n })(e60.center, e60.diameter / 2 + o10, n8));\n};\nvar koe = (e54, t4) =\u003e {\n const n8 = (e60) =\u003e ({ ...e60, rootConnectionName: t4.getNetConnectedToId(e60.rootConnectionName ?? e60.connectionName) ?? e60.rootConnectionName ?? e60.connectionName });\n return { ...e54, portPoints: e54.portPoints.map(n8), portPointsInPairs: e54.portPointsInPairs?.map(([e60, t10]) =\u003e [n8(e60), n8(t10)]) };\n};\nvar Doe = ({ nodeWithPortPoints: e54, connMap: t4, colorMap: n8, viaDiameter: o10, viaHoleDiameter: i8, minViaHoleEdgeToViaHoleEdgeClearance: r9, allowBlindAndBuriedVias: s7, priorityDiagnostics: a9, priorityDagSearch: c5 = false, captureSearchDebug: l5 = false, traceWidth: h5, obstacleMargin: d9, effort: u9, nodePfById: p9, obstacles: m9, boardGeometry: g10, layerCount: f10 }) =\u003e new Dz({ nodePortPoints: [koe(e54, t4)], colorMap: n8, connMap: t4, viaDiameter: o10, traceWidth: h5, obstacleMargin: d9, effort: u9, nodePfById: p9, obstacles: m9, layerCount: f10, useGrowShrinkHighDensityIntraNodeSolver: true, enableNegotiatedSearch: true, gridSearchSegmentWork: 500, gridSearchWorkScale: f10 \u003e 2 ? 0.25 : 1, rejectOverlappingTerminals: f10 \u003e 2, boardGeometry: g10, preserveTerminalPcbPortIds: false, growShrinkFallbackToInvalidGeometryOnFailure: false, captureSearchDebug: l5, priorityDagSearch: c5, priorityDiagnostics: a9, viaHoleDiameter: i8, minViaHoleEdgeToViaHoleEdgeClearance: r9, allowBlindAndBuriedVias: s7 });\nvar Loe = class extends ni {\n constructor(e54) {\n super(), this.params = e54, this.fixedHdRoutes = e54.fixedHdRoutes, this.connMap = e54.connMap, this.colorMap = e54.colorMap ?? {}, this.obstacles = e54.obstacles, this.boardGeometry = e54.boardGeometry, this.layerCount = e54.layerCount, this.allowBlindAndBuriedVias = e54.allowBlindAndBuriedVias ?? false, this.viaDiameter = e54.viaDiameter, this.traceWidth = e54.traceWidth, this.obstacleMargin = e54.obstacleMargin, this.viaToPadClearance = e54.viaToPadClearance, this.effort = e54.effort, this.nodePfById = e54.nodePfById instanceof Map ? new Map(e54.nodePfById) : new Map(Object.entries(e54.nodePfById ?? {})), this.preserveTerminalPcbPortIds = e54.preserveTerminalPcbPortIds ?? false, this.includeBoardObstacles = e54.includeBoardObstacles ?? false, this.enableRegionalFallback = e54.enableRegionalFallback ?? true, this.maxB01Rips = e54.maxB01Rips, this.unsolvedNodePortPoints = [...e54.nodePortPoints], this.MAX_ITERATIONS = 1e8 * this.effort, this.stats = { nodeCount: e54.nodePortPoints.length, solvedNodeCount: 0, fixedObstacleCount: e54.fixedHdRoutes.length, fixedObstacleUses: 0, boardObstacleUses: 0, fallbackNodeCount: 0, regularNodeCount: 0, b01NodeCount: 0, reroutedFixedRouteCount: 0, reroutedFixedRouteSectionCount: 0, promotedFallbackAttemptCount: 0, promotedFixedRouteCount: 0, regionalPreloadedViaCandidateRejectionCount: 0, regionalForceImproveCandidateRejectionCount: 0, regionalRepairCandidateRejectionCount: 0 };\n }\n fixedHdRoutes;\n connMap;\n colorMap;\n obstacles;\n boardGeometry;\n layerCount;\n allowBlindAndBuriedVias;\n viaDiameter;\n traceWidth;\n obstacleMargin;\n viaToPadClearance;\n effort;\n nodePfById;\n preserveTerminalPcbPortIds;\n includeBoardObstacles;\n enableRegionalFallback;\n maxB01Rips;\n routes = [];\n failedSolvers = [];\n unsolvedNodePortPoints;\n fixedRouteReplacements = new Map;\n removedFixedRouteConnectionNames = new Set;\n preloadedTraceMutationMasks = new Map;\n activeRegularSolver = null;\n activeB01Solver = null;\n activeFallbackSolver = null;\n activeFallbackFixedRouteSections = new Map;\n activeFallbackFixedObstacleRoutes = [];\n activeFallbackPromotedFixedRouteConnectionNames = new Set;\n activeFallbackReason = null;\n activeNode = null;\n asyncRunning = false;\n benchmarkDiagnosticCounters = {};\n getSolverName() {\n return \"Pipeline9HighDensitySolver\";\n }\n async solveAsync(e54, t4 = 1 / 0) {\n if (this.asyncRunning)\n throw new Error(\"High-density solveAsync is already running\");\n if (this.solved || this.failed || this.iterations \u003e= t4)\n return;\n const n8 = performance.now();\n try {\n if (e54 === undefined)\n return void (t4 === 1 / 0 ? this.solve() : this.solveUntilIteration(t4));\n if (this.fixedHdRoutes.length \u003e 0)\n return void this.solveUntilIteration(t4);\n for (;this.activeNode \u0026\u0026 !this.solved \u0026\u0026 !this.failed \u0026\u0026 this.iterations \u003c t4; )\n this.step();\n if (this.solved || this.failed || this.iterations \u003e= t4)\n return;\n this.asyncRunning = true;\n const n10 = [...this.unsolvedNodePortPoints].reverse(), { connMap: o10, nodePortPoints: i8, ...r9 } = this.params, s7 = Array.from({ length: Math.min(16, n10.length) }, () =\u003e ({ work: 0, nodes: [] })), a9 = n10.map((e60, t10) =\u003e ({ node: e60, index: t10 })).sort((e60, t10) =\u003e t10.node.portPoints.length - e60.node.portPoints.length);\n for (const e60 of a9) {\n const t10 = s7.reduce((e61, t11) =\u003e t11.work \u003c e61.work ? t11 : e61);\n t10.nodes.push(e60), t10.work += Math.max(1, e60.node.portPoints.length) ** 3;\n }\n const c5 = [];\n for (const t10 of s7) {\n const n11 = new Map(t10.nodes.map(({ node: e60 }) =\u003e [e60.capacityMeshNodeId, this.nodePfById.get(e60.capacityMeshNodeId) ?? null])), i9 = e54.executeAsync(Gne, { ...r9, nodePortPoints: t10.nodes.map(({ node: e60 }) =\u003e e60), nodePfById: n11, connectivityNetMap: o10.netMap, maxIterations: this.MAX_ITERATIONS }).then((e60) =\u003e {\n for (const t11 of e60)\n for (const [e61, n12] of Object.entries(t11.benchmarkDiagnosticCounters))\n this.benchmarkDiagnosticCounters[e61] = (this.benchmarkDiagnosticCounters[e61] ?? 0) + n12;\n return this.benchmarkDiagnosticCounters.priorityWorkerBatchesCompleted = (this.benchmarkDiagnosticCounters.priorityWorkerBatchesCompleted ?? 0) + 1, this.benchmarkDiagnosticCounters.priorityWorkerNodesCompleted = (this.benchmarkDiagnosticCounters.priorityWorkerNodesCompleted ?? 0) + e60.length, { type: \"result\", results: e60 };\n }, (e60) =\u003e ({ type: \"error\", error: e60 }));\n for (const [e60, { index: n12 }] of t10.nodes.entries())\n c5[n12] = i9.then((t11) =\u003e t11.type === \"error\" ? t11 : { type: \"result\", result: t11.results[e60] });\n }\n this.benchmarkDiagnosticCounters.priorityWorkerBatchesDispatched = (this.benchmarkDiagnosticCounters.priorityWorkerBatchesDispatched ?? 0) + s7.length, this.benchmarkDiagnosticCounters.priorityWorkerNodesDispatched = (this.benchmarkDiagnosticCounters.priorityWorkerNodesDispatched ?? 0) + n10.length;\n for (const e60 of c5) {\n const n11 = await e60;\n if (n11.type === \"error\")\n throw n11.error;\n const o11 = n11.result, i9 = o11.iterations - (o11.solved ? 1 : 0);\n if (this.iterations + i9 \u003e Math.min(this.MAX_ITERATIONS, t4))\n return this.asyncRunning = false, void this.solveUntilIteration(t4);\n this.benchmarkDiagnosticCounters.priorityWorkerNodesAccepted = (this.benchmarkDiagnosticCounters.priorityWorkerNodesAccepted ?? 0) + 1, this.iterations += i9, this.routes.push(...o11.routes);\n for (const [e61, t10] of Object.entries(o11.stats))\n e61 !== \"nodeCount\" \u0026\u0026 e61 !== \"fixedObstacleCount\" \u0026\u0026 (this.stats[e61] += t10);\n if (this.unsolvedNodePortPoints.splice(-o11.consumedNodeCount, o11.consumedNodeCount), this.progress = this.computeProgress(), !o11.solved)\n return this.error = o11.error, void (this.failed = true);\n }\n this.asyncRunning = false, this.iterations \u003c t4 \u0026\u0026 this.step();\n } catch (e60) {\n throw this.failed = true, this.error = `Pipeline9 high-density runtime error: ${e60}`, e60;\n } finally {\n this.asyncRunning = false, this.timeToSolve = performance.now() - n8;\n }\n }\n solveUntilIteration(e54) {\n for (;!this.solved \u0026\u0026 !this.failed \u0026\u0026 this.iterations \u003c e54; )\n this.step();\n }\n getUpdatedFixedHdRoutes() {\n return this.fixedHdRoutes.flatMap((e54) =\u003e this.removedFixedRouteConnectionNames.has(e54.connectionName) ? [] : [this.fixedRouteReplacements.get(e54.connectionName) ?? e54]);\n }\n finishActiveNode(e54) {\n const t4 = this.activeNode ? ((e60, t10) =\u003e e60.map((e61) =\u003e ({ ...e61, rootConnectionName: t10.portPoints.find((t11) =\u003e t11.connectionName === e61.connectionName)?.rootConnectionName ?? e61.rootConnectionName })))(e54, this.activeNode) : e54;\n this.routes.push(...this.preserveTerminalPcbPortIds \u0026\u0026 this.activeNode ? ((e60, t10) =\u003e {\n const n8 = t10.portPoints.filter((e61) =\u003e e61.pcb_port_id !== undefined);\n return e60.map((e61) =\u003e {\n const t11 = e61.route[0], o10 = e61.route.at(-1), i8 = n8.find((n10) =\u003e t11 !== undefined \u0026\u0026 n10.connectionName === e61.connectionName \u0026\u0026 n10.x === t11.x \u0026\u0026 n10.y === t11.y \u0026\u0026 n10.z === t11.z), r9 = n8.find((t12) =\u003e o10 !== undefined \u0026\u0026 t12.connectionName === e61.connectionName \u0026\u0026 t12.x === o10.x \u0026\u0026 t12.y === o10.y \u0026\u0026 t12.z === o10.z);\n return { ...e61, startPcbPortId: i8?.pcb_port_id, endPcbPortId: r9?.pcb_port_id };\n });\n })(t4, this.activeNode) : t4), this.stats.solvedNodeCount = Number(this.stats.solvedNodeCount ?? 0) + 1, this.activeB01Solver = null, this.activeRegularSolver = null, this.activeFallbackSolver = null, this.activeFallbackFixedRouteSections.clear(), this.activeFallbackFixedObstacleRoutes = [], this.activeFallbackPromotedFixedRouteConnectionNames.clear(), this.activeFallbackReason = null, this.activeNode = null;\n }\n startRegularSolver(e54) {\n this.activeNode = e54, this.activeRegularSolver = Doe({ nodeWithPortPoints: e54, colorMap: this.colorMap, connMap: this.connMap, viaDiameter: this.viaDiameter, traceWidth: this.traceWidth, obstacleMargin: this.obstacleMargin, effort: this.effort, nodePfById: this.nodePfById, obstacles: this.obstacles, boardGeometry: this.boardGeometry, layerCount: this.layerCount, viaHoleDiameter: this.params.viaHoleDiameter, minViaHoleEdgeToViaHoleEdgeClearance: this.params.minViaHoleEdgeToViaHoleEdgeClearance, allowBlindAndBuriedVias: this.params.allowBlindAndBuriedVias, priorityDiagnostics: this.benchmarkDiagnosticCounters, priorityDagSearch: true, captureSearchDebug: this.params.captureSearchDebug }), this.stats.regularNodeCount = Number(this.stats.regularNodeCount ?? 0) + 1;\n }\n startRegionalFallback(e54 = new Set) {\n if (!this.activeNode)\n throw new Error(\"Pipeline9 cannot start a regional fallback without an active node\");\n const t4 = { ...koe(this.activeNode, this.connMap), availableZ: Array.from({ length: this.layerCount }, (e60, t10) =\u003e t10) }, n8 = Rne(t4, this.getUpdatedFixedHdRoutes(), e54), o10 = new Set([...n8.fixedRouteSectionsByConnectionName.values()].flatMap((e60) =\u003e e60.sourceRoutes.map((e61) =\u003e e61.connectionName)));\n for (const t10 of e54)\n if (!o10.has(t10))\n throw new Error(`Pipeline9 could not promote fixed route \"${t10}\" into the active regional fallback`);\n const i8 = [...e54].filter((e60) =\u003e !this.activeFallbackPromotedFixedRouteConnectionNames.has(e60)).length;\n this.activeFallbackFixedRouteSections = n8.fixedRouteSectionsByConnectionName, this.activeFallbackFixedObstacleRoutes = n8.fixedObstacleRoutes, this.activeFallbackPromotedFixedRouteConnectionNames = new Set(e54);\n const r9 = rs({ fixedObstacleRoutes: this.activeFallbackFixedObstacleRoutes, layerCount: this.layerCount, allowBlindAndBuriedVias: this.allowBlindAndBuriedVias });\n this.activeFallbackSolver = new Eoe({ captureSearchDebug: this.params.captureSearchDebug, nodeWithPortPoints: n8.nodeWithPortPoints, colorMap: this.colorMap, connMap: this.connMap, viaDiameter: this.viaDiameter, traceWidth: this.traceWidth, obstacleMargin: this.obstacleMargin, effort: this.effort, nodePfById: this.nodePfById, obstacles: [...this.obstacles, ...r9], boardObstacles: this.obstacles, movablePreloadedConnectionNames: o10, viaToPadClearance: this.viaToPadClearance, layerCount: this.layerCount, allowBlindAndBuriedVias: this.allowBlindAndBuriedVias }), e54.size === 0 ? this.stats.fallbackNodeCount = Number(this.stats.fallbackNodeCount ?? 0) + 1 : (this.stats.promotedFallbackAttemptCount = Number(this.stats.promotedFallbackAttemptCount ?? 0) + 1, this.stats.promotedFixedRouteCount = Number(this.stats.promotedFixedRouteCount ?? 0) + i8);\n }\n finishRegionalFallback() {\n if (!this.activeFallbackSolver)\n return;\n if (!this.activeNode)\n throw new Error(\"Pipeline9 cannot finish a regional fallback without an active node\");\n this.recordRegionalCandidateRejections();\n const e54 = [], t4 = new Map;\n for (const n10 of this.activeFallbackSolver.getOutput()) {\n if (!this.activeFallbackFixedRouteSections.has(n10.connectionName)) {\n e54.push(n10);\n continue;\n }\n const o11 = t4.get(n10.connectionName) ?? [];\n o11.push(n10), t4.set(n10.connectionName, o11);\n }\n const n8 = [], o10 = [];\n for (const [e60, i9] of this.activeFallbackFixedRouteSections) {\n const r10 = t4.get(e60) ?? [];\n if (r10.length === 0) {\n o10.push(i9);\n continue;\n }\n if (r10.length \u003e 1)\n return this.error = `Pipeline9 regional fallback expected one replacement for fixed route \"${e60}\", got ${r10.length}`, void (this.failed = true);\n const s9 = Ane({ section: i9, replacement: r10[0], sourceMutationMasks: this.preloadedTraceMutationMasks, replacementIsMutated: true });\n n8.push({ connectionName: e60, section: i9, replacement: s9.route, mutatedSegments: s9.mutatedSegments, replacementProducedSegment: s9.replacementProducedSegment });\n }\n const i8 = [...e54, ...n8.map(({ replacement: e60 }) =\u003e e60)], r9 = [...this.activeFallbackFixedObstacleRoutes, ...o10.flatMap((e60) =\u003e e60.sourceRoutes)], s7 = Aoe(this.activeNode, this.obstacleMargin + Math.max(this.traceWidth, this.viaDiameter) / 2), a9 = new Map;\n for (const e60 of i8)\n for (const t10 of r9)\n ss(e60, t10, this.connMap) || cs({ left: e60, right: t10, clearance: this.obstacleMargin, leftBounds: s7, layerCount: this.layerCount, allowBlindAndBuriedVias: this.allowBlindAndBuriedVias }) \u0026\u0026 a9.set(t10.connectionName, t10);\n if (a9.size \u003e 0) {\n const e60 = [...a9.keys()], t10 = [...a9].flatMap(([e61, t11]) =\u003e t11.isThroughObstacle === true ? [] : [e61]), n10 = new Set(this.activeFallbackPromotedFixedRouteConnectionNames);\n for (const e61 of t10)\n n10.add(e61);\n if (n10.size === this.activeFallbackPromotedFixedRouteConnectionNames.size) {\n const t11 = [...a9].flatMap(([e61, t12]) =\u003e t12.isThroughObstacle === true ? [e61] : []);\n return this.error = t11.length \u003e 0 ? `Pipeline9 regional fallback conflicts with immutable through-obstacle route(s): ${t11.join(\", \")}` : `Pipeline9 promoted regional fallback could not resolve immutable fixed route conflict(s): ${e60.join(\", \")}`, void (this.failed = true);\n }\n return void this.startRegionalFallback(n10);\n }\n const c5 = new Map;\n for (const { section: e60, replacementProducedSegment: t10 } of n8)\n if (t10)\n for (const t11 of e60.sourceRoutes) {\n const { preloadedRoutePositionStart: e61, preloadedRoutePositionEnd: n10 } = t11;\n if (e61 === undefined != (n10 === undefined))\n throw new Error(`Pipeline9 fixed route \"${t11.connectionName}\" has incomplete route-position metadata`);\n const o11 = Math.min(e61 ?? t11.preloadedRouteIndex, n10 ?? t11.preloadedRouteIndex), i9 = Math.max(e61 ?? t11.preloadedRouteIndex, n10 ?? t11.preloadedRouteIndex), r10 = c5.get(t11.preloadedTraceIndex);\n c5.set(t11.preloadedTraceIndex, { start: Math.min(r10?.start ?? o11, o11), end: Math.max(r10?.end ?? i9, i9) });\n }\n for (const { connectionName: e60, section: t10, replacement: o11, mutatedSegments: i9 } of n8) {\n this.fixedRouteReplacements.set(e60, o11), this.preloadedTraceMutationMasks.set(e60, i9);\n for (const e61 of t10.sourceRoutes.slice(1))\n this.removedFixedRouteConnectionNames.add(e61.connectionName), this.preloadedTraceMutationMasks.delete(e61.connectionName);\n }\n const l5 = Rne({ ...koe(this.activeNode, this.connMap), portPoints: [], portPointsInPairs: [], availableZ: Array.from({ length: this.layerCount }, (e60, t10) =\u003e t10) }, this.getUpdatedFixedHdRoutes()), h5 = new Set;\n for (const e60 of l5.fixedRouteSectionsByConnectionName.values()) {\n const t10 = e60.sourceRoutes[0];\n if (!t10)\n continue;\n const n10 = c5.get(t10.preloadedTraceIndex);\n if (n10)\n for (const [o11, i9] of e60.sourceRoutes.entries()) {\n const r10 = i9.preloadedRoutePositionStart ?? i9.preloadedRouteIndex, s9 = i9.preloadedRoutePositionEnd ?? i9.preloadedRouteIndex, a10 = { start: Math.min(r10, s9), end: Math.max(r10, s9) }, c9 = a10.start === a10.end, l10 = n10.start === n10.end;\n if (!(c9 || l10 ? a10.start \u003c= n10.end \u0026\u0026 n10.start \u003c= a10.end : a10.start \u003c n10.end \u0026\u0026 n10.start \u003c a10.end))\n continue;\n h5.add(t10.preloadedTraceIndex);\n const d10 = [...this.preloadedTraceMutationMasks.get(i9.connectionName) ?? Array(i9.route.length - 1).fill(false)];\n if (d10.length !== i9.route.length - 1)\n throw new Error(`Pipeline9 fixed route mutation mask for \"${i9.connectionName}\" has ${d10.length} segments, expected ${i9.route.length - 1}`);\n const u9 = o11 === 0 ? e60.start.segmentIndex : 0, p9 = o11 === e60.sourceRoutes.length - 1 ? e60.end.segmentIndex : i9.route.length - 2;\n for (let e61 = u9;e61 \u003c= p9; e61++)\n d10[e61] = true;\n this.preloadedTraceMutationMasks.set(i9.connectionName, d10);\n }\n }\n for (const e60 of c5.keys())\n if (!h5.has(e60))\n throw new Error(`Pipeline9 could not capture accepted mutation provenance for trace ${e60}`);\n const d9 = n8.reduce((e60, { section: t10 }) =\u003e e60 + t10.sourceRoutes.length, 0);\n this.stats.reroutedFixedRouteCount = Number(this.stats.reroutedFixedRouteCount ?? 0) + d9, this.stats.reroutedFixedRouteSectionCount = Number(this.stats.reroutedFixedRouteSectionCount ?? 0) + n8.length, this.finishActiveNode(e54);\n }\n recordRegionalCandidateRejections() {\n if (!this.activeFallbackSolver)\n return;\n const e54 = this.activeFallbackSolver.stats;\n this.stats.regionalPreloadedViaCandidateRejectionCount = Number(this.stats.regionalPreloadedViaCandidateRejectionCount ?? 0) + Number(e54.preloadedViaCandidateRejectionCount ?? 0), this.stats.regionalForceImproveCandidateRejectionCount = Number(this.stats.regionalForceImproveCandidateRejectionCount ?? 0) + Number(e54.forceImproveCandidateRejectionCount ?? 0), this.stats.regionalRepairCandidateRejectionCount = Number(this.stats.regionalRepairCandidateRejectionCount ?? 0) + Number(e54.repairCandidateRejectionCount ?? 0);\n }\n finishRegularSolverFailure(e54) {\n if (this.activeFallbackReason = `regular high-density routing failed: ${e54}`, this.activeRegularSolver = null, !this.enableRegionalFallback)\n return this.error = `Pipeline9 ${this.activeFallbackReason}`, this.failed = true, void (this.activeNode = null);\n this.startRegionalFallback();\n }\n _step() {\n this.stepNodeRouting(), this.activeSubSolver = this.activeFallbackSolver ?? this.activeRegularSolver ?? this.activeB01Solver;\n }\n computeProgress() {\n if (this.solved)\n return 1;\n const e54 = Number(this.stats.nodeCount);\n if (e54 === 0)\n return 0;\n const t4 = Math.max(0, Math.min(1, this.activeSubSolver?.progress ?? 0));\n return Math.max(this.progress, (Number(this.stats.solvedNodeCount) + t4) / e54);\n }\n stepNodeRouting() {\n if (this.activeFallbackSolver) {\n if (this.activeFallbackSolver.step(), this.activeFallbackSolver.failed)\n return this.recordRegionalCandidateRejections(), this.error = [`Pipeline9 primary high-density routing failed: ${this.activeFallbackReason ?? \"unknown error\"}`, `regional fallback failed: ${this.activeFallbackSolver.error ?? \"unknown error\"}`].join(\"; \"), this.failed = true, this.activeFallbackSolver = null, this.activeFallbackFixedRouteSections.clear(), this.activeFallbackFixedObstacleRoutes = [], this.activeFallbackPromotedFixedRouteConnectionNames.clear(), void (this.activeNode = null);\n if (!this.activeFallbackSolver.solved)\n return;\n return void this.finishRegionalFallback();\n }\n if (this.activeRegularSolver) {\n if (this.activeRegularSolver.step(), this.activeRegularSolver.failed)\n return void this.finishRegularSolverFailure(this.activeRegularSolver.error ?? \"unknown error\");\n if (!this.activeRegularSolver.solved)\n return;\n return void this.finishActiveNode(this.activeRegularSolver.routes);\n }\n if (this.activeB01Solver) {\n if (this.activeB01Solver.step(), this.activeB01Solver.failed)\n return this.failedSolvers.push(this.activeB01Solver), this.activeFallbackReason = `B01 failed: ${this.activeB01Solver.error ?? \"unknown error\"}`, this.activeB01Solver = null, this.enableRegionalFallback ? void this.startRegionalFallback() : (this.error = `Pipeline9 ${this.activeFallbackReason}`, this.failed = true, void (this.activeNode = null));\n if (!this.activeB01Solver.solved)\n return;\n return void this.finishActiveNode(this.activeB01Solver.getOutput());\n }\n const e54 = this.unsolvedNodePortPoints.pop();\n if (!e54)\n return void (this.solved = true);\n const t4 = Aoe(e54, this.obstacleMargin), n8 = Math.max(this.traceWidth, this.viaDiameter) / 2, o10 = this.getUpdatedFixedHdRoutes().filter((o11) =\u003e Ooe(o11, e54, t4, n8, this)).flatMap((t10) =\u003e ((e60, t11, n10) =\u003e {\n const o11 = new Set(t11.availableZ ?? t11.portPoints.map((e61) =\u003e e61.z));\n if (o11.size === 0)\n throw new Error(`Pipeline9 B01 node \"${t11.capacityMeshNodeId}\" has no available layers`);\n const i9 = { type: \"route\", connectionName: e60.connectionName, rootConnectionName: e60.rootConnectionName, traceThickness: e60.traceThickness, viaDiameter: e60.viaDiameter }, r10 = [], s7 = os(e60, n10);\n for (const e61 of s7.wireSegments)\n o11.has(e61.z) \u0026\u0026 r10.push({ ...i9, traceThickness: e61.width, route: [e61.start, e61.end], vias: [] });\n for (const e61 of s7.viaSpans)\n [...o11].some((t12) =\u003e t12 \u003e= e61.minZ \u0026\u0026 t12 \u003c= e61.maxZ) \u0026\u0026 r10.push({ ...i9, viaDiameter: e61.diameter, route: [{ ...e61.center, z: e61.minZ }, { ...e61.center, z: e61.maxZ }], vias: [{ ...e61.center, zStart: e61.minZ, zEnd: e61.maxZ }] });\n return r10;\n })(t10, e54, this));\n if (this.stats.fixedObstacleUses = Number(this.stats.fixedObstacleUses ?? 0) + o10.length, o10.length === 0 \u0026\u0026 !this.params.b01RepairOptions)\n return void this.startRegularSolver(e54);\n const i8 = (this.includeBoardObstacles ? this.obstacles : []).filter((e60) =\u003e ((e61, t10) =\u003e {\n const n10 = (e61.ccwRotationDegrees ?? 0) * Math.PI / 180, o11 = Math.abs(Math.cos(n10)), i9 = Math.abs(Math.sin(n10)), r10 = e61.width / 2 * o11 + e61.height / 2 * i9, s7 = e61.width / 2 * i9 + e61.height / 2 * o11;\n return e61.center.x - r10 \u003c= t10.maxX \u0026\u0026 e61.center.x + r10 \u003e= t10.minX \u0026\u0026 e61.center.y - s7 \u003c= t10.maxY \u0026\u0026 e61.center.y + s7 \u003e= t10.minY;\n })(e60, t4)).map((t10) =\u003e (({ obstacle: e60, node: t11, connMap: n10, layerCount: o11 }) =\u003e {\n const i9 = new Set(t11.availableZ ?? t11.portPoints.map((e61) =\u003e e61.z)), r10 = (e60.zLayers ?? e60.layers.map((e61) =\u003e mo(e61, o11))).filter((e61) =\u003e i9.has(e61));\n if (r10.length === 0)\n return;\n const s7 = e60.connectedTo[0] ?? e60.obstacleId ?? `pipeline9_obstacle_${e60.center.x}_${e60.center.y}`;\n return { type: \"rect\", connectionName: s7, rootConnectionName: n10.getNetConnectedToId(s7) ?? s7, center: e60.center, width: e60.width, height: e60.height, ccwRotationDegrees: e60.ccwRotationDegrees, zLayers: r10 };\n })({ obstacle: t10, node: e54, connMap: this.connMap, layerCount: this.layerCount })).filter((e60) =\u003e e60 !== undefined);\n if (this.stats.boardObstacleUses = Number(this.stats.boardObstacleUses ?? 0) + i8.length, this.activeNode = e54, e54.width \u003e 15 || e54.height \u003e 15)\n return this.activeFallbackReason = `B01 node \"${e54.capacityMeshNodeId}\" exceeds the 15x15mm routing limit (${e54.width}x${e54.height}mm)`, void this.startRegionalFallback();\n const r9 = koe(e54, this.connMap);\n this.stats.b01NodeCount = Number(this.stats.b01NodeCount ?? 0) + 1, this.activeB01Solver = new Roe({ ...qne, nodeWithPortPoints: r9, obstacles: [...o10, ...i8], viaDiameter: this.viaDiameter, viaMinDistFromBorder: this.viaDiameter / 2, traceThickness: this.traceWidth, traceMargin: this.obstacleMargin, obstacleClearanceMargin: 0.15, ...this.params.b01RepairOptions, effort: this.effort }), this.maxB01Rips !== undefined \u0026\u0026 (this.activeB01Solver.MAX_RIPS = this.maxB01Rips);\n }\n visualize() {\n return this.activeFallbackSolver?.visualize() ?? this.activeRegularSolver?.visualize() ?? this.activeB01Solver?.visualize() ?? { lines: this.routes.flatMap((e54) =\u003e e54.route.slice(0, -1).map((t4, n8) =\u003e ({ points: [t4, e54.route[n8 + 1]], strokeWidth: e54.traceThickness, layer: `z${t4.z}`, label: e54.connectionName }))), points: [], rects: [], circles: [] };\n }\n};\nvar zoe = (e54, t4) =\u003e {\n const n8 = e54({ hdRoutes: t4, traces: [] });\n return Array.isArray(n8) ? n8 : n8.errorsWithCenters ?? n8.errors;\n};\nvar Boe = (e54) =\u003e {\n const t4 = typeof e54.pcb_trace_id == \"string\" ? e54.pcb_trace_id : undefined, n8 = Array.isArray(e54.pcb_trace_ids) ? e54.pcb_trace_ids.filter((e60) =\u003e typeof e60 == \"string\") : [], o10 = [...typeof e54.pcb_via_id == \"string\" ? [e54.pcb_via_id] : [], ...Array.isArray(e54.pcb_via_ids) ? e54.pcb_via_ids : []].filter((e60) =\u003e typeof e60 == \"string\"), i8 = t4 ? `overlap_${t4}_` : undefined, r9 = i8 \u0026\u0026 typeof e54.pcb_trace_error_id == \"string\" \u0026\u0026 e54.pcb_trace_error_id.startsWith(i8) ? e54.pcb_trace_error_id.slice(i8.length) : undefined;\n if (n8.length \u003e 0) {\n const e60 = t4 \u0026\u0026 !n8.includes(t4) ? [t4, ...n8] : [...n8];\n return e60.length \u003c 2 \u0026\u0026 r9 \u0026\u0026 !o10.includes(r9) \u0026\u0026 e60.push(r9), e60;\n }\n return [t4, r9].filter((e60) =\u003e typeof e60 == \"string\" \u0026\u0026 !o10.includes(e60));\n};\nvar Foe = (e54) =\u003e Boe(e54).filter((e60, t4, n8) =\u003e n8.indexOf(e60) === t4);\nvar joe = (e54) =\u003e e54.reduce((e60, t4) =\u003e {\n if (typeof t4.actual_clearance == \"number\" \u0026\u0026 typeof t4.minimum_clearance == \"number\")\n return e60 + Math.max(0, t4.minimum_clearance - t4.actual_clearance);\n const n8 = (typeof t4.message == \"string\" ? t4.message : \"\").match(/gap: (-?\\d+(?:\\.\\d+)?)mm/);\n return n8 ? e60 + Math.max(0, 0.1 - Number.parseFloat(n8[1])) : e60 + 1;\n}, 0);\nvar $oe = (e54, t4) =\u003e e54.length \u003c t4.length || e54.length === t4.length \u0026\u0026 joe(e54) \u003c joe(t4) - 0.000000001;\nvar Yoe = ({ routes: e54, newConnections: t4, syntheticConnectionNames: n8 }) =\u003e {\n const o10 = new Set([...t4.map((e60) =\u003e e60.name), ...n8]), i8 = new Map, r9 = new Map;\n for (let t10 = 0;t10 \u003c e54.length; t10++) {\n const n10 = e54[t10];\n if (!o10.has(n10.connectionName))\n continue;\n const s7 = i8.get(n10.connectionName) ?? 0;\n i8.set(n10.connectionName, s7 + 1), r9.set(`${n10.connectionName}_${s7}`, t10);\n }\n return r9;\n};\nvar Xoe = 0.01;\nvar Hoe = [0.03, 0.1, 0.25];\nvar Voe = (e54) =\u003e {\n let t4 = 0;\n for (const n8 of e54) {\n if (typeof n8.actual_clearance != \"number\" || !Number.isFinite(n8.actual_clearance) || typeof n8.minimum_clearance != \"number\" || !Number.isFinite(n8.minimum_clearance))\n return;\n if (t4 += Math.max(0, n8.minimum_clearance - n8.actual_clearance), !Number.isFinite(t4))\n return;\n }\n return t4;\n};\nvar Woe = ({ errors: e54, errorsWithCenters: t4, routeIndexByTraceId: n8, padPositionById: o10 }) =\u003e {\n const i8 = [];\n let r9 = 0;\n for (const s7 of e54) {\n const e60 = s7.type === \"pcb_via_trace_clearance_error\", a9 = s7.type === \"pcb_pad_trace_clearance_error\";\n if (!e60 \u0026\u0026 !a9 || typeof s7.pcb_trace_id != \"string\" || !n8.has(s7.pcb_trace_id) || typeof s7.actual_clearance != \"number\" || !Number.isFinite(s7.actual_clearance) || typeof s7.minimum_clearance != \"number\" || !Number.isFinite(s7.minimum_clearance))\n return;\n const c5 = Foe(s7);\n if (e60 \u0026\u0026 c5.length \u003c 2 || c5.some((e61) =\u003e !n8.has(e61)))\n return;\n const l5 = t4.find((e61) =\u003e e61.type === s7.type \u0026\u0026 e61.pcb_trace_id === s7.pcb_trace_id \u0026\u0026 e61.pcb_pad_id === s7.pcb_pad_id \u0026\u0026 e61.pcb_via_id === s7.pcb_via_id), h5 = a9 ? typeof s7.pcb_pad_id == \"string\" ? o10.get(s7.pcb_pad_id) : undefined : l5?.center ?? s7.center;\n if (!h5 || typeof h5 != \"object\")\n return;\n if (!((\"x\" in h5) \u0026\u0026 (\"y\" in h5) \u0026\u0026 typeof h5.x == \"number\" \u0026\u0026 Number.isFinite(h5.x) \u0026\u0026 typeof h5.y == \"number\" \u0026\u0026 Number.isFinite(h5.y)))\n return;\n const d9 = { ...s7, pcb_trace_id: s7.pcb_trace_id, actual_clearance: s7.actual_clearance, minimum_clearance: s7.minimum_clearance, center: { x: h5.x, y: h5.y } };\n if (e60) {\n if (typeof s7.pcb_via_id != \"string\")\n return;\n i8.push({ ...d9, type: \"pcb_via_trace_clearance_error\", pcb_via_id: s7.pcb_via_id, pcb_pad_id: undefined });\n } else {\n if (typeof s7.pcb_pad_id != \"string\")\n return;\n i8.push({ ...d9, type: \"pcb_pad_trace_clearance_error\", pcb_pad_id: s7.pcb_pad_id, pcb_via_id: undefined });\n }\n if (r9 += Math.max(0, s7.minimum_clearance - s7.actual_clearance), !Number.isFinite(r9))\n return;\n }\n return { errors: i8, deficit: r9 };\n};\nvar Goe = (e54) =\u003e {\n if (e54.type !== \"pcb_pad_pad_clearance_error\" || typeof e54.pcb_trace_id != \"string\")\n return false;\n const { pcb_via_ids: t4, pcb_pad_ids: n8 } = e54;\n return !(!Array.isArray(t4) || t4.length !== 1 || typeof t4[0] != \"string\") \u0026\u0026 (Array.isArray(n8) \u0026\u0026 n8.length === 2 \u0026\u0026 typeof n8[0] == \"string\" \u0026\u0026 typeof n8[1] == \"string\" \u0026\u0026 n8.includes(t4[0]));\n};\nvar Uoe = (e54) =\u003e ((e60) =\u003e {\n const t4 = typeof e60.pcb_trace_id == \"string\" ? e60.pcb_trace_id : undefined, n8 = Array.isArray(e60.pcb_trace_ids) ? e60.pcb_trace_ids.filter((e61) =\u003e typeof e61 == \"string\") : [], o10 = [...typeof e60.pcb_via_id == \"string\" ? [e60.pcb_via_id] : [], ...Array.isArray(e60.pcb_via_ids) ? e60.pcb_via_ids : []].filter((e61) =\u003e typeof e61 == \"string\"), i8 = t4 ? `overlap_${t4}_` : undefined, r9 = i8 \u0026\u0026 typeof e60.pcb_trace_error_id == \"string\" \u0026\u0026 e60.pcb_trace_error_id.startsWith(i8) ? e60.pcb_trace_error_id.slice(i8.length) : undefined;\n if (n8.length \u003e 0) {\n const e61 = t4 \u0026\u0026 !n8.includes(t4) ? [t4, ...n8] : [...n8];\n return e61.length \u003c 2 \u0026\u0026 r9 \u0026\u0026 !o10.includes(r9) \u0026\u0026 e61.push(r9), e61;\n }\n return [t4, r9].filter((e61) =\u003e typeof e61 == \"string\" \u0026\u0026 !o10.includes(e61));\n})(e54).filter((e60, t4, n8) =\u003e n8.indexOf(e60) === t4);\nvar Zoe = (e54, t4) =\u003e {\n const n8 = [...new Set(t4.flatMap(Uoe))];\n return e54.map((e60) =\u003e {\n if (e60.jumpers?.length || !n8.some((t11) =\u003e t11 === e60.connectionName || t11.startsWith(`${e60.connectionName}_`)))\n return e60;\n const t10 = e60.route.flatMap((t11, n10) =\u003e {\n const o10 = e60.route[n10 + 1];\n if (!o10 || t11.z !== o10.z || t11.toNextSegmentType || t11.insideJumperPad || o10.insideJumperPad || (t11.traceThickness ?? e60.traceThickness) !== (o10.traceThickness ?? e60.traceThickness))\n return [t11];\n const i8 = Math.min(32, Math.ceil(((e61, t12) =\u003e {\n const n11 = Math.max(Math.abs(e61), Math.abs(t12));\n if (n11 === 0 || n11 === Number.POSITIVE_INFINITY)\n return n11;\n const o11 = e61 / n11, i9 = t12 / n11;\n return n11 * Math.sqrt(o11 * o11 + i9 * i9);\n })(o10.x - t11.x, o10.y - t11.y) / 0.25));\n return [t11, ...Array.from({ length: Math.max(0, i8 - 1) }, (e61, n11) =\u003e ({ x: t11.x + (o10.x - t11.x) * (n11 + 1) / i8, y: t11.y + (o10.y - t11.y) * (n11 + 1) / i8, z: t11.z, traceThickness: t11.traceThickness }))];\n });\n return t10.length === e60.route.length ? e60 : { ...e60, route: t10 };\n });\n};\nvar qoe = class extends ni {\n params;\n state = { phase: \"initialize\" };\n constructor(e54) {\n super(), this.params = e54;\n }\n _step() {\n const e54 = this.state, t4 = this.params;\n if (e54.phase === \"initialize\") {\n const e60 = t4.drcEvaluator({ traces: [], routes: t4.routes, hdRoutes: t4.routes }), n10 = Array.isArray(e60) ? e60 : e60.errors;\n if (n10.length === 0)\n return this.state = { phase: \"finished\", output: t4.routes }, void (this.solved = true);\n const o11 = { ...V1(t4.originalSrj), traces: undefined }, i9 = bne(t4.routes), r10 = t4.subdivideSegments ? Zoe(i9, n10) : i9, s9 = new Zy({ srj: o11, routes: r10, bounds: o11.bounds, boundaryMargin: 0, boardEdgeClearance: t4.originalSrj.minBoardEdgeClearance ?? 0, lockedPointIndices: r10.map((e61) =\u003e e61.route.map((n11) =\u003e n11.terminalApproach !== undefined || t4.lockedConnectionNames?.has(e61.connectionName) === true || t4.movableRegions !== undefined \u0026\u0026 !t4.movableRegions.some(({ center: e63, radius: t10 }) =\u003e Math.hypot(n11.x - e63.x, n11.y - e63.y) \u003c= t10))), allowViaMovement: !t4.allowPartialRepair, traceClearance: (t4.originalSrj.minTraceToPadEdgeClearance ?? hR) + (t4.allowPartialRepair || t4.usePrecisionMargin ? Xoe : 0), viaClearance: (t4.originalSrj.minPadEdgeToPadEdgeClearance ?? dR) + 0.00001 + (t4.usePrecisionMargin ? Xoe : 0) });\n return this.MAX_ITERATIONS = s9.MAX_ITERATIONS + 4, this.activeSubSolver = s9, void (this.state = { phase: \"relax\", context: { srj: o11, errors: n10, originalCanonicalRoutes: i9, canonicalRoutes: r10 }, solver: s9 });\n }\n if (e54.phase === \"relax\") {\n if (e54.solver.step(), this.MAX_ITERATIONS = e54.solver.MAX_ITERATIONS + 4, e54.solver.failed)\n throw new Error(`Clearance relaxation failed: ${e54.solver.error}`);\n return void (e54.solver.solved \u0026\u0026 (this.activeSubSolver = null, this.state = { phase: \"select\", context: e54.context, candidate: e54.solver.getOutput() }));\n }\n if (e54.phase === \"finished\")\n throw new Error(\"Clearance projection stepped after completion\");\n const { srj: n8, errors: o10, originalCanonicalRoutes: i8, canonicalRoutes: r9 } = e54.context;\n if (e54.phase === \"select\") {\n let o11 = e54.candidate;\n return t4.allowPartialRepair \u0026\u0026 (o11 = (({ srj: e60, routes: t10, proposedRoutes: n10 }) =\u003e {\n if (t10.length !== n10.length)\n throw new Error(\"Clearance projection changed the route count\");\n if (e60.allowBlindAndBuriedVias || t10.some((e61) =\u003e e61.jumpers?.length || e61.route.some((e63) =\u003e e63.toNextSegmentType || e63.insideJumperPad)))\n return t10;\n const { holeDiameter: o12 } = Yo(e60), i9 = (t11, n11) =\u003e ({ type: \"pcb_trace\", pcb_trace_id: `projection_${n11}`, connection_name: t11.rootConnectionName ?? t11.connectionName, route: Ro(t11, e60.layerCount, { defaultViaHoleDiameter: o12 }) }), r10 = t10.map(i9), s9 = { ...e60, minBoardEdgeClearance: e60.minBoardEdgeClearance ?? 0, traces: r10 }, a10 = new D7(s9), c9 = new Set(a10.canonicalize([...(e60.differentialPairs ?? []).flatMap((e61) =\u003e e61.connectionNames), ...(e60.buses ?? []).flatMap((e61) =\u003e e61.connectionNames)])), l5 = [...t10], h5 = [];\n for (const [e61, o13] of n10.entries()) {\n const n11 = t10[e61];\n if (o13.route.length !== n11.route.length)\n throw new Error(\"Partial clearance projection changed routing topology\");\n const i10 = [r10[e61].pcb_trace_id];\n if (!a10.canonicalize(i10).some((e63) =\u003e c9.has(e63))) {\n l5[e61] = { ...n11, route: [...o13.route] };\n for (let t11 = 0;t11 \u003c o13.route.length; t11++)\n o13.route[t11].x === n11.route[t11].x \u0026\u0026 o13.route[t11].y === n11.route[t11].y || h5.push({ routeIndex: e61, pointIndex: t11 });\n }\n }\n let d9 = new Cee(s9, l5.map(i9), undefined, [], a10);\n const u9 = ({ routeIndex: t11, pointIndex: n11 }) =\u003e {\n const o13 = l5[t11];\n for (let i10 = Math.max(1, n11);i10 \u003c= Math.min(n11 + 1, o13.route.length - 1); i10++) {\n const n12 = o13.route[i10 - 1], s10 = o13.route[i10];\n if (n12.z !== s10.z)\n throw new Error(\"Partial clearance projection moved a layer transition\");\n if (d9.collides({ start: n12, end: s10, layer: Co(n12.z, e60.layerCount), width: Math.max(n12.traceThickness ?? o13.traceThickness, s10.traceThickness ?? o13.traceThickness), connectionNames: [r10[t11].pcb_trace_id] }))\n return false;\n }\n return true;\n };\n let p9 = h5;\n for (;p9.length \u003e 0; ) {\n const e61 = p9.filter((e63) =\u003e !u9(e63));\n if (e61.length === 0)\n break;\n for (const { routeIndex: n12, pointIndex: o13 } of e61)\n l5[n12].route[o13] = t10[n12].route[o13];\n const n11 = new Set(e61);\n p9 = p9.filter((e63) =\u003e !n11.has(e63)), d9 = new Cee(s9, l5.map(i9), undefined, [], a10);\n }\n const m9 = new Set(p9);\n for (let e61 = 0;e61 \u003c h5.length; e61++) {\n const o13 = h5[e61];\n if (m9.has(o13))\n continue;\n let r11 = [o13];\n for (;e61 + 1 \u003c h5.length; ) {\n const t11 = h5[e61 + 1];\n if (m9.has(t11) || t11.routeIndex !== o13.routeIndex || t11.pointIndex !== h5[e61].pointIndex + 1)\n break;\n r11.push(t11), e61++;\n }\n for (const { routeIndex: e63, pointIndex: t11 } of r11)\n l5[e63].route[t11] = n10[e63].route[t11];\n for (;r11.length \u003e 0; ) {\n const e63 = r11.filter((e64) =\u003e !u9(e64));\n if (e63.length === 0)\n break;\n for (const { routeIndex: n12, pointIndex: o14 } of e63)\n l5[n12].route[o14] = t10[n12].route[o14];\n const n11 = new Set(e63);\n r11 = r11.filter((e64) =\u003e !n11.has(e64));\n }\n if (r11.length !== 0) {\n for (const e63 of r11)\n m9.add(e63);\n d9 = new Cee(s9, l5.map(i9), undefined, [], a10);\n }\n }\n const g10 = new Set([...m9].map(({ routeIndex: e61 }) =\u003e e61));\n return l5.map((e61, n11) =\u003e g10.has(n11) ? e61 : t10[n11]);\n })({ srj: n8, routes: r9, proposedRoutes: o11 }), o11 = o11.map((e60, t10) =\u003e e60 === r9[t10] ? i8[t10] : e60)), void (this.state = { phase: \"physical-validation\", context: e54.context, candidate: o11 });\n }\n if (e54.phase === \"physical-validation\") {\n const o11 = new Map(ay({ srj: n8, routes: r9 }).map((e60) =\u003e [e60.key, e60.severity]));\n return ay({ srj: n8, routes: e54.candidate }).some(({ key: e60, severity: t10 }) =\u003e !o11.has(e60) || t10 \u003e o11.get(e60) + 0.00000001) || ly({ srj: n8, previousRoutes: t4.previousRoutes ?? r9, routes: e54.candidate }).length \u003e 0 ? (this.state = { phase: \"finished\", output: t4.routes }, void (this.solved = true)) : void (this.state = { ...e54, phase: \"reference-validation\" });\n }\n const s7 = t4.drcEvaluator({ traces: [], routes: e54.candidate, hdRoutes: e54.candidate }), a9 = Array.isArray(s7) ? s7 : s7.errors, c5 = t4.allowPartialRepair ? ((e60, t10) =\u003e {\n if (t10.length \u003e= e60.length)\n return false;\n const n10 = (e61) =\u003e e61.type === \"pcb_via_trace_clearance_error\" ? JSON.stringify([e61.type, e61.pcb_trace_id, e61.pcb_via_id]) : e61.type === \"pcb_pad_trace_clearance_error\" ? JSON.stringify([e61.type, e61.pcb_trace_id, e61.pcb_pad_id]) : Goe(e61) ? JSON.stringify([e61.type, e61.pcb_trace_id, [...e61.pcb_pad_ids].sort()]) : e61.type === \"pcb_via_clearance_error\" \u0026\u0026 Array.isArray(e61.pcb_via_ids) ? JSON.stringify([e61.type, [...e61.pcb_via_ids].sort()]) : e61.type === \"pcb_trace_error\" \u0026\u0026 typeof e61.pcb_trace_error_id == \"string\" \u0026\u0026 e61.pcb_trace_error_id.startsWith(`overlap_${e61.pcb_trace_id}_`) ? JSON.stringify([e61.type, e61.pcb_trace_error_id]) : undefined, o11 = [...e60];\n for (const e61 of t10) {\n const t11 = n10(e61);\n if (t11 === undefined)\n return false;\n const i9 = o11.findIndex((e63) =\u003e n10(e63) === t11);\n if (i9 \u003c 0)\n return false;\n const r10 = o11.splice(i9, 1)[0];\n if (e61.type !== \"pcb_trace_error\" \u0026\u0026 (typeof e61.actual_clearance != \"number\" || !Number.isFinite(e61.actual_clearance) || typeof r10.actual_clearance != \"number\" || !Number.isFinite(r10.actual_clearance) || e61.minimum_clearance !== r10.minimum_clearance || e61.actual_clearance \u003c r10.actual_clearance - 0.000000001))\n return false;\n }\n return true;\n })(o10, a9) : a9.length \u003c o10.length;\n this.state = { phase: \"finished\", output: c5 ? e54.candidate : t4.routes }, this.solved = true;\n }\n getOutput() {\n if (!this.solved || this.state.phase !== \"finished\")\n throw new Error(\"Clearance projection is not complete\");\n return this.state.output;\n }\n computeProgress() {\n switch (this.state.phase) {\n case \"initialize\":\n return 0;\n case \"relax\":\n return 0.9 * this.state.solver.progress;\n case \"select\":\n return 0.9;\n case \"physical-validation\":\n return 0.93;\n case \"reference-validation\":\n return 0.96;\n case \"finished\":\n return 1;\n }\n }\n};\nvar Joe = { maxRegions: 4, maxCandidateAttempts: 1024, maxPathSearchNodes: 480000 };\nvar Qoe = (e54, t4, n8) =\u003e {\n if (!Number.isFinite(n8) || n8 \u003c= 0)\n throw new Error(\"Pipeline9 regional repair effort must be positive and finite\");\n const o10 = Math.max(1, n8);\n return { maxRegions: Math.ceil(24 * o10), maxCandidateAttempts: Math.ceil(4096 * o10), maxPathSearchNodes: Math.ceil(40000000 * o10), initialMaxRegions: Math.ceil(4 * o10), initialMaxCandidateAttempts: Math.ceil(1024 * o10), initialMaxPathSearchNodes: Math.ceil(2000000 * o10), regionsPerAcceptedRepair: 2, candidateAttemptsPerAcceptedRepair: 512, pathSearchNodesPerAcceptedRepair: 2000000, maxCandidateAttemptsPerRegion: 512, maxPathSearchNodesPerCall: 1e6, pathGridSizeScale: 2, pathHeuristicWeight: 3, searchDirectionCount: 2, revisitChangedRegions: true, regionSizes: [16, 32] };\n};\nvar Koe = (e54, t4) =\u003e ({ maxRegions: Math.min(e54.maxRegions, (e54.initialMaxRegions ?? e54.maxRegions) + t4 * (e54.regionsPerAcceptedRepair ?? 0)), maxCandidateAttempts: Math.min(e54.maxCandidateAttempts, (e54.initialMaxCandidateAttempts ?? e54.maxCandidateAttempts) + t4 * (e54.candidateAttemptsPerAcceptedRepair ?? 0)), maxPathSearchNodes: Math.min(e54.maxPathSearchNodes, (e54.initialMaxPathSearchNodes ?? e54.maxPathSearchNodes) + t4 * (e54.pathSearchNodesPerAcceptedRepair ?? 0)) });\nfunction eie({ routes: e54, srj: t4 }) {\n const { holeDiameter: n8 } = Yo(t4);\n return e54.flatMap((e60, o10) =\u003e {\n if (\"type\" in e60) {\n const n10 = { ...e60, route: e60.route.filter((e61) =\u003e e61.route_type === \"via\") };\n return sR({ ...t4, obstacles: [], connections: [], traces: undefined }, [n10]).filter((e61) =\u003e e61.type === \"pcb_via\");\n }\n return cy(e60, t4.layerCount).map((e61, i8) =\u003e {\n let r9 = 0, s7 = t4.layerCount - 1;\n return t4.allowBlindAndBuriedVias === true \u0026\u0026 (r9 = e61.minZ, s7 = e61.maxZ), { type: \"pcb_via\", pcb_via_id: `repair_via_${o10}_${i8}`, x: e61.x, y: e61.y, hole_diameter: n8, outer_diameter: e61.diameter, layers: Array.from({ length: s7 - r9 + 1 }, (e63, n10) =\u003e Co(r9 + n10, t4.layerCount)) };\n });\n });\n}\nvar tie = [3, 4, 5, 6, 8];\nvar nie = (e54) =\u003e {\n const t4 = e54.center;\n return t4 \u0026\u0026 typeof t4 == \"object\" \u0026\u0026 \"x\" in t4 \u0026\u0026 \"y\" in t4 \u0026\u0026 typeof t4.x == \"number\" \u0026\u0026 typeof t4.y == \"number\" ? { x: t4.x, y: t4.y } : undefined;\n};\nvar oie = (e54, t4) =\u003e {\n const n8 = nie(e54);\n if (n8)\n return n8;\n const o10 = typeof e54.pcb_pad_id == \"string\" ? e54.pcb_pad_id : typeof e54.pcb_trace_error_id == \"string\" ? e54.pcb_trace_error_id.match(/(pcb_(?:smtpad|plated_hole|hole|keepout)_\\d+)$/)?.[1] : undefined;\n if (o10) {\n const e60 = t4.obstacles.find((e61) =\u003e e61.obstacleId === o10 || e61.connectedTo[0] === o10);\n if (e60)\n return e60.center;\n }\n return nie(e54);\n};\nvar iie = ({ error: e54, routeIndexByTraceId: t4 }) =\u003e {\n const n8 = typeof e54.pcb_trace_id == \"string\" ? e54.pcb_trace_id : undefined, o10 = [...typeof e54.pcb_via_id == \"string\" ? [e54.pcb_via_id] : [], ...Array.isArray(e54.pcb_via_ids) ? e54.pcb_via_ids.filter((e60) =\u003e typeof e60 == \"string\") : []], i8 = n8 ? `overlap_${n8}_` : undefined, r9 = i8 \u0026\u0026 typeof e54.pcb_trace_error_id == \"string\" \u0026\u0026 e54.pcb_trace_error_id.startsWith(i8) ? e54.pcb_trace_error_id.slice(i8.length) : undefined, s7 = r9 !== undefined \u0026\u0026 o10.includes(r9);\n return [n8, ...Array.isArray(e54.pcb_trace_ids) ? e54.pcb_trace_ids : [], s7 ? undefined : r9].filter((e60) =\u003e typeof e60 == \"string\" \u0026\u0026 t4.has(e60)).filter((e60, t10, n10) =\u003e n10.indexOf(e60) === t10);\n};\nvar rie = (e54, t4) =\u003e !(e54.type !== \"pcb_trace_error\" || typeof e54.pcb_via_id == \"string\" || Array.isArray(e54.pcb_via_ids) \u0026\u0026 e54.pcb_via_ids.length \u003e 0) \u0026\u0026 iie({ error: e54, routeIndexByTraceId: t4 }).length === 2;\nvar sie = (e54) =\u003e e54.filter((e60) =\u003e e60.type === \"pcb_via_clearance_error\" || Array.isArray(e60.pcb_via_ids)).length;\nvar aie = (e54, t4) =\u003e {\n const n8 = new Map;\n for (const t10 of e54)\n n8.set(t10.connectionName, (n8.get(t10.connectionName) ?? 0) + 1);\n return e54.map((e60, o10) =\u003e {\n const i8 = n8.get(e60.connectionName) \u003e 1 ? `${e60.connectionName}_regional_${o10}` : e60.connectionName;\n return i8 !== e60.connectionName \u0026\u0026 t4.addConnections([[i8, e60.connectionName, e60.rootConnectionName ?? e60.connectionName]]), { ...e60, connectionName: i8, preloadedTraceId: `pipeline9_joint_candidate_${o10}`, preloadedTraceIndex: o10, preloadedRouteIndex: 0, isThroughObstacle: false };\n });\n};\nvar cie = (e54, t4) =\u003e e54.minX \u003c= t4.maxX \u0026\u0026 e54.maxX \u003e= t4.minX \u0026\u0026 e54.minY \u003c= t4.maxY \u0026\u0026 e54.maxY \u003e= t4.minY;\nvar lie = (e54) =\u003e ({ minX: e54.center.x - e54.diameter / 2, maxX: e54.center.x + e54.diameter / 2, minY: e54.center.y - e54.diameter / 2, maxY: e54.center.y + e54.diameter / 2 });\nvar hie = (e54) =\u003e ({ minX: e54.center.x - e54.width / 2, maxX: e54.center.x + e54.width / 2, minY: e54.center.y - e54.height / 2, maxY: e54.center.y + e54.height / 2 });\nvar die = (e54, t4, n8) =\u003e {\n const o10 = os(e54, n8);\n return o10.wireSegments.some((e60) =\u003e cie(((e61) =\u003e ({ minX: Math.min(e61.start.x, e61.end.x) - e61.width / 2, maxX: Math.max(e61.start.x, e61.end.x) + e61.width / 2, minY: Math.min(e61.start.y, e61.end.y) - e61.width / 2, maxY: Math.max(e61.start.y, e61.end.y) + e61.width / 2 }))(e60), t4)) || o10.viaSpans.some((e60) =\u003e cie(lie(e60), t4));\n};\nvar uie = ({ routes: e54, fixedRouteCopperSpatialIndex: t4, center: n8, regionSize: o10, srj: i8, connMap: r9, colorMap: s7, viaDiameter: a9, traceWidth: c5, obstacleMargin: l5, effort: h5 }) =\u003e {\n const d9 = aie(e54, r9), u9 = { capacityMeshNodeId: \"pipeline9_joint_drc_regular_fallback\", center: n8, width: o10, height: o10, availableZ: Array.from({ length: i8.layerCount }, (e60, t10) =\u003e t10), portPoints: [], portPointsInPairs: [] }, p9 = Rne(u9, d9);\n if (p9.fixedRouteSectionsByConnectionName.size === 0)\n return;\n if (!((e60) =\u003e {\n const t10 = Ine(e60);\n return e60.portPoints.every((e61) =\u003e ga({ point: e61, bounds: t10 }) === \"on-boundary\");\n })(p9.nodeWithPortPoints))\n return;\n const m9 = [...p9.fixedRouteSectionsByConnectionName.values()].flatMap((e60) =\u003e e60.sourceRoutes).reduce((e60, t10) =\u003e {\n const n10 = os(t10, i8);\n return Math.max(e60, t10.viaDiameter / 2, ...n10.wireSegments.map((e61) =\u003e e61.width / 2), ...n10.viaSpans.map((e61) =\u003e e61.diameter / 2));\n }, Math.max(c5 / 2, a9 / 2)), g10 = { minX: n8.x - o10 / 2 - l5 - m9, maxX: n8.x + o10 / 2 + l5 + m9, minY: n8.y - o10 / 2 - l5 - m9, maxY: n8.y + o10 / 2 + l5 + m9 }, f10 = t4.getRoutesOverlappingBounds(g10), _5 = rs({ fixedObstacleRoutes: f10, layerCount: i8.layerCount, allowBlindAndBuriedVias: i8.allowBlindAndBuriedVias });\n return { solver: new Eoe({ nodeWithPortPoints: p9.nodeWithPortPoints, colorMap: s7, connMap: r9, viaDiameter: a9, traceWidth: c5, obstacleMargin: l5, effort: h5, obstacles: [...i8.obstacles, ..._5], layerCount: i8.layerCount, allowBlindAndBuriedVias: i8.allowBlindAndBuriedVias }), routes: e54, regionalRoutes: d9, problem: p9, candidateBounds: g10, localFixedObstacleRoutes: f10, obstacleMargin: l5, connMap: r9, srj: i8 };\n};\nvar pie = ({ solver: e54, routes: t4, regionalRoutes: n8, problem: o10, candidateBounds: i8, localFixedObstacleRoutes: r9, obstacleMargin: s7, connMap: a9, srj: c5 }) =\u003e {\n if (!e54.solved || e54.failed)\n return;\n const l5 = e54.getOutput(), h5 = new Map(l5.map((e60) =\u003e [e60.connectionName, e60])), d9 = new Map, u9 = new Set;\n for (const [e60, t10] of o10.fixedRouteSectionsByConnectionName) {\n const n10 = h5.get(e60);\n if (!n10)\n return;\n d9.set(t10.sourceRoutes[0].preloadedTraceIndex, Ene(t10, n10));\n for (const e61 of t10.sourceRoutes.slice(1))\n u9.add(e61.preloadedTraceIndex);\n }\n const p9 = n8.flatMap((e60, n10) =\u003e u9.has(n10) ? [] : [{ ...d9.get(n10) ?? e60, connectionName: t4[n10].connectionName }]);\n return (({ candidateRoutes: e60, fixedObstacleRoutes: t10, obstacleMargin: n10, connMap: o11, candidateBounds: i9, srj: r10 }) =\u003e {\n for (const s9 of e60)\n for (const e61 of t10)\n if (!ss(s9, e61, o11) \u0026\u0026 cs({ left: s9, right: e61, clearance: n10, leftBounds: i9, layerCount: r10.layerCount, allowBlindAndBuriedVias: r10.allowBlindAndBuriedVias }))\n return true;\n return false;\n })({ candidateRoutes: p9, fixedObstacleRoutes: r9, obstacleMargin: s7, connMap: a9, candidateBounds: i8, srj: c5 }) ? undefined : p9;\n};\nvar mie = class extends ni {\n evaluateViaInPad;\n params;\n candidateSearchBudget;\n phase = \"initialize\";\n result;\n currentRoutes;\n currentErrors = [];\n bestRoutes;\n bestErrors = [];\n fixedRouteCopperSpatialIndex;\n routeIndexByTraceId = new Map;\n repairableErrors = [];\n passIndex = 0;\n errorIndex = 0;\n traceIndex = 0;\n regionIndex = 0;\n traceIds = [];\n repairCenter;\n stopB01SearchForError = false;\n acceptedOnPass = false;\n attemptedCandidateCount = 0;\n acceptedCandidateCount = 0;\n fallbackCandidateCount = 0;\n candidateSearchCount = 0;\n candidateSearchBudgetExhausted = false;\n safeTraceLayerRepairSkippedForBudget = false;\n preloadEligibleDrcIssueCount = 0;\n pairCandidate;\n b01Candidate;\n regularCandidate;\n safeTraceLayerSolver;\n viaPadProjectionSolver;\n cleanup;\n constructor(e54) {\n super(), this.params = e54, this.evaluateViaInPad = function({ srj: e60, previousRoutes: t4 }) {\n const n8 = oR(V1(e60)), o10 = new G, i8 = n8.filter((e61) =\u003e e61.type === \"pcb_smtpad\" || e61.type === \"pcb_plated_hole\");\n o10.load(i8.map(az));\n const r9 = new Set(eie({ routes: t4, srj: e60 }).map((e61) =\u003e JSON.stringify([e61.x, e61.y, e61.hole_diameter, e61.layers])));\n return (t10) =\u003e {\n const n10 = eie({ routes: t10, srj: e60 }).filter((e61) =\u003e !r9.has(JSON.stringify([e61.x, e61.y, e61.hole_diameter, e61.layers])));\n for (const e61 of n10) {\n const t11 = e61.hole_diameter / 2, n11 = o10.search({ minX: e61.x - t11, minY: e61.y - t11, maxX: e61.x + t11, maxY: e61.y + t11 });\n for (const t12 of n11)\n if (e61.layers.some((e63) =\u003e t12.layers.includes(e63)) \u0026\u0026 lz(e61, e61, e61.hole_diameter, t12).gap \u003c -0.000001)\n return true;\n }\n return false;\n };\n }({ srj: e54.srj, previousRoutes: e54.routes }), this.currentRoutes = e54.routes, this.bestRoutes = e54.routes, this.candidateSearchBudget = ((e60) =\u003e {\n if (!Number.isInteger(e60) || e60 \u003c 0)\n throw new Error(\"Pipeline9 regional repair route count must be nonnegative\");\n const t4 = Math.floor(7000 / Math.max(1, e60));\n return Math.max(16, Math.min(192, t4));\n })(e54.routes.length), this.MAX_ITERATIONS = 64 + 8 * this.candidateSearchBudget;\n }\n introducesViaInPad(e54) {\n return this.params.srj.allowViaInPad !== true \u0026\u0026 this.evaluateViaInPad(e54);\n }\n initializeRepair() {\n const { initialErrors: e54, drcEvaluator: t4, newConnections: n8, syntheticConnectionNames: o10 } = this.params;\n this.currentErrors = e54 ?? zoe(t4, this.currentRoutes), this.MAX_ITERATIONS += 16 * this.currentErrors.length, this.preloadEligibleDrcIssueCount = this.currentErrors.filter((e60) =\u003e (({ error: e61, preloadRepairTraceIds: t10 }) =\u003e !!Boe(e61).some((e63) =\u003e t10.has(e63)) || (e61.__collapsed_trace_participants ?? []).flatMap((e63) =\u003e new Set(e63.evaluationTraceIds).size \u003e 1 ? [e63.solverTraceId] : []).some((e63) =\u003e t10.collidingFixedTraceIds?.has(e63)))({ error: e60, preloadRepairTraceIds: this.params.preloadRepairTraceIds })).length;\n const i8 = Yoe({ routes: this.currentRoutes, newConnections: n8, syntheticConnectionNames: o10 }), r9 = this.params.allowTracePairRepair === true \u0026\u0026 this.currentErrors.some((e60) =\u003e rie(e60, i8));\n this.preloadEligibleDrcIssueCount !== 0 || r9 ? (this.fixedRouteCopperSpatialIndex = ((e60, t10) =\u003e {\n const n10 = new Map, o11 = (e61, t11) =\u003e {\n const o12 = Math.floor(t11.minX / 4), i9 = Math.floor(t11.maxX / 4), r10 = Math.floor(t11.minY / 4), s7 = Math.floor(t11.maxY / 4);\n for (let t12 = o12;t12 \u003c= i9; t12++)\n for (let o13 = r10;o13 \u003c= s7; o13++) {\n const i10 = `${t12}:${o13}`, r11 = n10.get(i10) ?? new Set;\n r11.add(e61), n10.set(i10, r11);\n }\n };\n for (let n11 = 0;n11 \u003c e60.length; n11++) {\n const i9 = os(e60[n11], t10);\n for (const e61 of i9.wireSegments)\n for (const t11 of is(e61, 4, 1))\n o11(n11, hie(t11));\n for (const e61 of i9.viaSpans)\n o11(n11, lie(e61));\n }\n return { getRoutesOverlappingBounds: (o12) =\u003e {\n const i9 = new Set, r10 = Math.floor(o12.minX / 4), s7 = Math.floor(o12.maxX / 4), a9 = Math.floor(o12.minY / 4), c5 = Math.floor(o12.maxY / 4);\n for (let e61 = r10;e61 \u003c= s7; e61++)\n for (let t11 = a9;t11 \u003c= c5; t11++)\n for (const o13 of n10.get(`${e61}:${t11}`) ?? [])\n i9.add(o13);\n return [...i9].sort((e61, t11) =\u003e e61 - t11).map((t11) =\u003e e60[t11]).filter((e61) =\u003e die(e61, o12, t10));\n } };\n })(this.params.fixedObstacleRoutes, this.params.srj), this.phase = \"begin-pass\") : this.finishRepair();\n }\n beginPass() {\n this.candidateSearchBudgetExhausted || this.passIndex \u003e= 2 ? this.beginCleanup({ kind: \"accepted-routes\", routes: this.currentRoutes, errors: this.currentErrors }) : (this.acceptedOnPass = false, this.routeIndexByTraceId = Yoe({ routes: this.currentRoutes, newConnections: this.params.newConnections, syntheticConnectionNames: this.params.syntheticConnectionNames }), this.repairableErrors = this.currentErrors.filter((e54) =\u003e (e54.type === \"pcb_trace_error\" || e54.type === \"pcb_pad_trace_clearance_error\" || e54.type === \"pcb_via_trace_clearance_error\" || e54.type === \"pcb_via_clearance_error\" || Goe(e54)) \u0026\u0026 typeof e54.pcb_trace_id == \"string\"), this.errorIndex = 0, this.phase = \"begin-error\");\n }\n beginError() {\n if (this.candidateSearchBudgetExhausted || this.errorIndex \u003e= this.repairableErrors.length)\n return void (this.phase = \"finish-pass\");\n const e54 = this.repairableErrors[this.errorIndex];\n this.repairCenter = oie(e54, this.params.srj), this.traceIds = iie({ error: e54, routeIndexByTraceId: this.routeIndexByTraceId }).slice(0, 2), this.repairCenter ? (this.bestRoutes = this.currentRoutes, this.bestErrors = this.currentErrors, this.traceIndex = 0, this.regionIndex = 0, this.stopB01SearchForError = false, this.phase = rie(e54, this.routeIndexByTraceId) ? \"prepare-pair\" : \"prepare-b01\") : this.errorIndex++;\n }\n preparePairCandidate() {\n if (this.candidateSearchCount \u003e= this.candidateSearchBudget)\n return this.candidateSearchBudgetExhausted = true, void (this.phase = \"commit-error\");\n const e54 = this.traceIds.map((e60) =\u003e this.routeIndexByTraceId.get(e60));\n this.pairCandidate = (({ routeIndexes: e60, ...t4 }) =\u003e {\n const { routes: n8, connMap: o10, srj: i8, fixedObstacleRoutes: r9 } = t4, s7 = e60.map((e61) =\u003e n8[e61]);\n if (s7.some((e61) =\u003e t4.syntheticConnectionNames.has(e61.connectionName) || (e61.jumpers?.length ?? 0) \u003e 0 || e61.route.some((t10, n10) =\u003e t10.insideJumperPad || t10.toNextSegmentType !== undefined || t10.toNextSegmentCircuitJsonMetadata !== undefined || t10.traceThickness !== undefined \u0026\u0026 t10.traceThickness !== e61.traceThickness || t10.pcb_port_id !== undefined \u0026\u0026 n10 \u003e 0 \u0026\u0026 n10 \u003c e61.route.length - 1)))\n return;\n const a9 = s7.flatMap((e61) =\u003e e61.route);\n if (a9.some((e61) =\u003e e61.x \u003c i8.bounds.minX || e61.x \u003e i8.bounds.maxX || e61.y \u003c i8.bounds.minY || e61.y \u003e i8.bounds.maxY))\n return;\n for (const e61 of s7) {\n const t10 = e61.route[0], i9 = e61.route.at(-1), s9 = [...n8, ...r9].filter((t11) =\u003e t11 !== e61 \u0026\u0026 ss(e61, t11, o10));\n for (const n10 of s9)\n for (const o11 of [n10.route[0], n10.route.at(-1)])\n if (!(o11.z === t10.z \u0026\u0026 Math.hypot(o11.x - t10.x, o11.y - t10.y) \u003c 0.000000001 || o11.z === i9.z \u0026\u0026 Math.hypot(o11.x - i9.x, o11.y - i9.y) \u003c 0.000000001))\n for (let t11 = 1;t11 \u003c e61.route.length; t11++) {\n const n11 = e61.route[t11 - 1], i10 = e61.route[t11];\n if (o11.z \u003e= Math.min(n11.z, i10.z) \u0026\u0026 o11.z \u003c= Math.max(n11.z, i10.z) \u0026\u0026 pe(o11, n11, i10) \u003c 0.000000001)\n return;\n }\n }\n const c5 = Math.max(t4.traceWidth, ...s7.map((e61) =\u003e e61.traceThickness), ...a9.map((e61) =\u003e e61.traceThickness ?? t4.traceWidth)), l5 = Math.max(t4.viaDiameter, ...s7.map((e61) =\u003e e61.viaDiameter)), h5 = Math.max(t4.obstacleMargin, i8.minViaEdgeToPadEdgeClearance ?? t4.obstacleMargin, i8.minTraceToHoleEdgeClearance ?? t4.obstacleMargin), d9 = l5 + h5, u9 = Math.max(i8.bounds.minX, Math.min(...a9.map((e61) =\u003e e61.x)) - d9), p9 = Math.min(i8.bounds.maxX, Math.max(...a9.map((e61) =\u003e e61.x)) + d9), m9 = Math.max(i8.bounds.minY, Math.min(...a9.map((e61) =\u003e e61.y)) - d9), g10 = Math.min(i8.bounds.maxY, Math.max(...a9.map((e61) =\u003e e61.y)) + d9);\n if (p9 - u9 \u003e 15 || g10 - m9 \u003e 15)\n return;\n const f10 = aie(n8, o10), _5 = { capacityMeshNodeId: \"pipeline9_trace_pair_repair\", center: { x: (u9 + p9) / 2, y: (m9 + g10) / 2 }, width: p9 - u9, height: g10 - m9, availableZ: Array.from({ length: i8.layerCount }, (e61, t10) =\u003e t10), portPoints: [], portPointsInPairs: [] }, y10 = Rne(_5, e60.map((e61) =\u003e f10[e61]));\n if (y10.fixedRouteSectionsByConnectionName.size !== 2)\n return;\n const b10 = new Map;\n for (const t10 of e60)\n b10.set(t10, y10.fixedRouteSectionsByConnectionName.get(f10[t10].connectionName));\n const x8 = f10.filter((e61, t10) =\u003e !b10.has(t10));\n return { solver: new Loe({ nodePortPoints: [y10.nodeWithPortPoints], fixedHdRoutes: [...x8, ...r9].map((e61) =\u003e ({ ...e61, rootConnectionName: o10.getNetConnectedToId(e61.rootConnectionName ?? e61.connectionName) ?? e61.rootConnectionName ?? e61.connectionName })), connMap: o10, colorMap: t4.colorMap, obstacles: i8.obstacles, layerCount: i8.layerCount, allowBlindAndBuriedVias: i8.allowBlindAndBuriedVias, viaDiameter: l5, traceWidth: c5, obstacleMargin: t4.obstacleMargin, effort: t4.effort, preserveTerminalPcbPortIds: true, includeBoardObstacles: true, enableRegionalFallback: false, maxB01Rips: 120, b01RepairOptions: { lowResolutionCellSize: qne.highResolutionCellSize, obstacleClearanceMargin: h5 } }), routes: n8, sections: b10 };\n })({ ...this.params, routes: this.currentRoutes, routeIndexes: [e54[0], e54[1]] }), this.pairCandidate ? (this.candidateSearchCount++, this.startChildSolver(this.pairCandidate.solver), this.phase = \"route-pair\") : this.phase = \"prepare-b01\";\n }\n stepPairCandidate() {\n const e54 = this.pairCandidate;\n if (!e54)\n throw new Error(\"Regional pair repair has no candidate\");\n e54.solver.step(), (e54.solver.solved || e54.solver.failed) \u0026\u0026 (this.activeSubSolver = null, this.phase = \"validate-pair\");\n }\n validatePairCandidate() {\n const e54 = this.pairCandidate;\n if (!e54)\n throw new Error(\"Regional pair repair has no completed candidate\");\n const t4 = (({ solver: e60, routes: t10, sections: n10 }) =\u003e {\n if (e60.solved \u0026\u0026 !e60.failed)\n return t10.map((t11, o10) =\u003e {\n const i8 = n10.get(o10);\n if (!i8)\n return t11;\n const r9 = e60.routes.find((e61) =\u003e e61.connectionName === i8.sourceRoutes[0].connectionName);\n if (!r9)\n throw new Error(\"Completed pair repair is missing a route\");\n return { ...Ene(i8, r9), connectionName: t11.connectionName };\n });\n })(e54);\n if (this.pairCandidate = undefined, this.phase = \"prepare-b01\", !t4)\n return;\n this.attemptedCandidateCount++;\n const n8 = zoe(this.params.drcEvaluator, t4);\n $oe(n8, this.bestErrors) \u0026\u0026 !this.introducesViaInPad(t4) \u0026\u0026 (this.bestRoutes = t4, this.bestErrors = n8, this.phase = \"commit-error\");\n }\n startChildSolver(e54) {\n const t4 = Math.floor(e54.MAX_ITERATIONS) + 1;\n if (!Number.isSafeInteger(t4) || t4 \u003c 1)\n throw new Error(\"Regional B01 child has an invalid iteration limit\");\n this.MAX_ITERATIONS += t4, this.activeSubSolver = e54;\n }\n prepareB01Candidate() {\n if (this.stopB01SearchForError || this.candidateSearchBudgetExhausted || this.traceIndex \u003e= this.traceIds.length)\n return void (this.phase = \"prepare-regional\");\n const e54 = this.routeIndexByTraceId.get(this.traceIds[this.traceIndex]);\n if (e54 === undefined)\n return this.traceIndex++, void (this.regionIndex = 0);\n if (this.regionIndex \u003e= tie.length)\n return void (this.bestErrors.length === 0 ? this.stopB01SearchForError = true : (this.traceIndex++, this.regionIndex = 0));\n if (this.candidateSearchCount \u003e= this.candidateSearchBudget)\n return this.candidateSearchBudgetExhausted = true, void (this.phase = \"prepare-regional\");\n const t4 = this.repairCenter;\n if (!t4)\n throw new Error(\"Regional B01 candidate has no repair center\");\n const n8 = tie[this.regionIndex];\n this.regionIndex++, this.candidateSearchCount++, this.b01Candidate = (({ routes: e60, fixedObstacleRoutes: t10, routeIndex: n10, center: o10, regionSize: i8, srj: r9, connMap: s7, colorMap: a9, viaDiameter: c5, traceWidth: l5, obstacleMargin: h5, effort: d9 }) =\u003e {\n const u9 = aie(e60, s7), p9 = u9[n10];\n if (!p9)\n return;\n const m9 = { capacityMeshNodeId: `pipeline9_joint_drc_${n10}_${i8}`, center: o10, width: i8, height: i8, availableZ: Array.from({ length: r9.layerCount }, (e61, t11) =\u003e t11), portPoints: [], portPointsInPairs: [] }, g10 = Rne(m9, [p9]), f10 = g10.fixedRouteSectionsByConnectionName.get(p9.connectionName);\n if (!f10)\n return;\n const _5 = u9.filter((e61, t11) =\u003e t11 !== n10);\n return { solver: new Loe({ nodePortPoints: [g10.nodeWithPortPoints], fixedHdRoutes: [..._5, ...t10].map((e61) =\u003e ({ ...e61, rootConnectionName: s7.getNetConnectedToId(e61.rootConnectionName ?? e61.connectionName) ?? e61.rootConnectionName ?? e61.connectionName })), connMap: s7, colorMap: a9, obstacles: r9.obstacles, layerCount: r9.layerCount, allowBlindAndBuriedVias: r9.allowBlindAndBuriedVias, viaDiameter: c5, traceWidth: l5, obstacleMargin: h5, effort: d9, preserveTerminalPcbPortIds: true, includeBoardObstacles: true, enableRegionalFallback: false, maxB01Rips: 120 }), routes: e60, movableRoute: p9, movableSection: f10, routeIndex: n10 };\n })({ ...this.params, routes: this.currentRoutes, routeIndex: e54, center: t4, regionSize: n8 }), this.b01Candidate \u0026\u0026 (this.startChildSolver(this.b01Candidate.solver), this.phase = \"route-b01\");\n }\n stepB01Candidate() {\n const e54 = this.b01Candidate;\n if (!e54)\n throw new Error(\"Regional B01 has no active candidate\");\n e54.solver.step(), (e54.solver.solved || e54.solver.failed) \u0026\u0026 (this.activeSubSolver = null, this.phase = \"validate-b01\");\n }\n validateB01Candidate() {\n const e54 = this.b01Candidate;\n if (!e54)\n throw new Error(\"Regional B01 has no completed candidate\");\n const t4 = (({ solver: e60, routes: t10, movableRoute: n8, movableSection: o10, routeIndex: i8 }) =\u003e {\n if (!e60.solved || e60.failed)\n return;\n const r9 = e60.routes.find((e61) =\u003e e61.connectionName === n8.connectionName);\n return r9 ? { routes: t10.map((e61, t11) =\u003e t11 === i8 ? { ...Ene(o10, r9), connectionName: e61.connectionName } : e61), usedFallback: Number(e60.stats.fallbackNodeCount ?? 0) \u003e 0 } : undefined;\n })(e54);\n if (this.b01Candidate = undefined, t4) {\n this.attemptedCandidateCount++, t4.usedFallback \u0026\u0026 this.fallbackCandidateCount++;\n const e60 = zoe(this.params.drcEvaluator, t4.routes);\n $oe(e60, this.bestErrors) \u0026\u0026 !this.introducesViaInPad(t4.routes) \u0026\u0026 (this.bestRoutes = t4.routes, this.bestErrors = e60), this.bestErrors.length === 0 \u0026\u0026 (this.stopB01SearchForError = true);\n }\n this.phase = \"prepare-b01\";\n }\n prepareRegularCandidate() {\n if (this.bestRoutes !== this.currentRoutes || this.candidateSearchBudgetExhausted)\n return void (this.phase = \"commit-error\");\n if (this.candidateSearchCount \u003e= this.candidateSearchBudget)\n return this.candidateSearchBudgetExhausted = true, void (this.phase = \"commit-error\");\n this.candidateSearchCount++;\n const e54 = this.repairCenter, t4 = this.fixedRouteCopperSpatialIndex;\n if (!e54 || !t4)\n throw new Error(\"Regional fallback candidate is missing its fixed context\");\n this.regularCandidate = uie({ ...this.params, routes: this.currentRoutes, fixedRouteCopperSpatialIndex: t4, center: e54, regionSize: 3 }), this.regularCandidate ? (this.startChildSolver(this.regularCandidate.solver), this.phase = \"route-regional\") : this.phase = \"commit-error\";\n }\n stepRegularCandidate() {\n const e54 = this.regularCandidate;\n if (!e54)\n throw new Error(\"Regional fallback has no active candidate\");\n e54.solver.step(), (e54.solver.solved || e54.solver.failed) \u0026\u0026 (this.activeSubSolver = null, this.phase = \"validate-regional\");\n }\n validateRegularCandidate() {\n const e54 = this.regularCandidate;\n if (!e54)\n throw new Error(\"Regional fallback has no completed candidate\");\n const t4 = pie(e54);\n if (this.regularCandidate = undefined, t4) {\n this.attemptedCandidateCount++, this.fallbackCandidateCount++;\n const e60 = zoe(this.params.drcEvaluator, t4);\n if ($oe(e60, this.bestErrors)) {\n if (this.introducesViaInPad(t4))\n return void this.beginCleanup({ kind: \"regular-candidate\", routes: t4, errors: e60 });\n this.bestRoutes = t4, this.bestErrors = e60;\n }\n }\n this.phase = \"commit-error\";\n }\n commitErrorRepair() {\n this.bestRoutes !== this.currentRoutes \u0026\u0026 (this.currentRoutes = this.bestRoutes, this.currentErrors = this.bestErrors, this.acceptedCandidateCount++, this.acceptedOnPass = true), this.errorIndex++, this.phase = this.candidateSearchBudgetExhausted ? \"finish-pass\" : \"begin-error\";\n }\n finishPass() {\n this.passIndex++, this.acceptedOnPass \u0026\u0026 this.currentErrors.length !== 0 \u0026\u0026 !this.candidateSearchBudgetExhausted ? this.phase = \"begin-pass\" : this.beginCleanup({ kind: \"accepted-routes\", routes: this.currentRoutes, errors: this.currentErrors });\n }\n beginCleanup(e54) {\n if (this.cleanup)\n throw new Error(\"Regional B01 cleanup is already active\");\n this.cleanup = e54, this.phase = \"refine\";\n }\n getCleanupOrThrow() {\n const e54 = this.cleanup;\n if (!e54)\n throw new Error(\"Regional B01 repair has no active cleanup\");\n return e54;\n }\n refineCleanupRoutes() {\n const e54 = this.getCleanupOrThrow();\n if ((e54.kind === \"regular-candidate\" || this.acceptedCandidateCount \u003e 0) \u0026\u0026 e54.errors.length \u003e 0) {\n const t4 = ((e60, t10) =\u003e {\n if (e60 === t10)\n return t10;\n let n8 = t10;\n for (const [o10, i8] of e60.entries()) {\n const e61 = i8.route.filter((e63) =\u003e e63.terminalApproach !== undefined);\n if (e61.length === 0)\n continue;\n const r9 = t10[o10], s7 = [...r9.route];\n for (const t11 of e61) {\n const e63 = r9.route.flatMap((e64, n10) =\u003e e64.terminalApproach === t11.terminalApproach ? [n10] : []);\n if (e63.length !== 1)\n return;\n s7[e63[0]] = t11;\n }\n n8 === t10 \u0026\u0026 (n8 = [...t10]), n8[o10] = { ...r9, route: s7 };\n }\n return n8;\n })(e54.routes, ow({ ...this.params.srj, traces: undefined }, e54.routes, this.params.effort, 1, this.params.connMap));\n if (t4 \u0026\u0026 t4 !== e54.routes) {\n const n8 = zoe(this.params.drcEvaluator, t4);\n sie(n8) \u003c= sie(e54.errors) \u0026\u0026 $oe(n8, e54.errors) \u0026\u0026 !this.introducesViaInPad(t4) \u0026\u0026 (e54.routes = t4, e54.errors = n8);\n }\n }\n this.phase = \"prepare-via-pad-projection\";\n }\n prepareViaPadProjection() {\n const e54 = this.getCleanupOrThrow(), t4 = e54.errors.filter(Goe).flatMap((e60) =\u003e {\n const t10 = oie(e60, this.params.srj);\n return t10 ? [{ center: t10, radius: tie[0] / 2 }] : [];\n });\n if (t4.length === 0)\n return void (this.phase = \"prepare-safe-layer\");\n const n8 = e54.routes.length;\n this.viaPadProjectionSolver = new qoe({ originalSrj: this.params.srj, routes: [...e54.routes, ...this.params.fixedObstacleRoutes], lockedConnectionNames: new Set([...this.params.syntheticConnectionNames, ...this.params.fixedObstacleRoutes.map((e60) =\u003e e60.connectionName)]), movableRegions: t4, usePrecisionMargin: true, drcEvaluator: ({ hdRoutes: e60 }) =\u003e {\n if (!e60)\n throw new Error(\"Via-pad projection requires HD routes\");\n return this.params.drcEvaluator({ traces: [], hdRoutes: e60.slice(0, n8) });\n } }), this.startChildSolver(this.viaPadProjectionSolver), this.phase = \"project-via-pad\";\n }\n stepViaPadProjection() {\n const e54 = this.getCleanupOrThrow(), t4 = this.viaPadProjectionSolver;\n if (!t4)\n throw new Error(\"Regional B01 has no via-pad projection\");\n if (t4.step(), this.MAX_ITERATIONS = Math.max(this.MAX_ITERATIONS, this.iterations + t4.MAX_ITERATIONS - t4.iterations + 16), t4.failed)\n throw new Error(`Regional via-pad projection failed: ${t4.error}`);\n t4.solved \u0026\u0026 (e54.routes = t4.getOutput().slice(0, e54.routes.length), e54.errors = zoe(this.params.drcEvaluator, e54.routes), this.activeSubSolver = null, this.phase = \"prepare-safe-layer\");\n }\n prepareSafeLayerRepair() {\n const e54 = this.getCleanupOrThrow(), t4 = e54.errors.some((e60) =\u003e e60.type === \"pcb_trace_error\" || e60.type === \"pcb_pad_trace_clearance_error\");\n this.safeTraceLayerRepairSkippedForBudget = t4 \u0026\u0026 this.candidateSearchBudgetExhausted, t4 \u0026\u0026 !this.candidateSearchBudgetExhausted ? (this.safeTraceLayerSolver = new kN({ srj: { ...this.params.srj, traces: undefined }, hdRoutes: e54.routes, connMap: this.params.connMap, effort: this.params.effort, drcEvaluator: this.params.drcEvaluator, maxIterations: 8, enableLargeBoardBroadFallback: false, enableTargetedErrorSweep: false, enablePostSolveClearanceRelaxation: false, enableSafeTraceLayerMoves: true, enableViaInPadLayerMoves: false }), this.startChildSolver(this.safeTraceLayerSolver), this.phase = \"route-safe-layer\") : this.finishCleanup();\n }\n stepSafeLayerRepair() {\n const e54 = this.safeTraceLayerSolver;\n if (!e54)\n throw new Error(\"Regional B01 has no safe trace-layer solver\");\n if (e54.step(), e54.failed)\n throw new Error(`Pipeline9 post-regional safe trace-layer repair failed: ${e54.error ?? \"unknown error\"}`);\n e54.solved \u0026\u0026 (this.activeSubSolver = null, this.phase = \"validate-safe-layer\");\n }\n validateSafeLayerRepair() {\n const e54 = this.getCleanupOrThrow(), t4 = this.safeTraceLayerSolver;\n if (!t4)\n throw new Error(\"Regional B01 has no completed safe trace-layer solver\");\n const n8 = t4.getOutput(), o10 = zoe(this.params.drcEvaluator, n8);\n $oe(o10, e54.errors) \u0026\u0026 !this.introducesViaInPad(n8) \u0026\u0026 (e54.routes = n8, e54.errors = o10), this.safeTraceLayerSolver = undefined, this.finishCleanup();\n }\n finishCleanup() {\n const e54 = this.getCleanupOrThrow();\n this.cleanup = undefined;\n const t4 = this.introducesViaInPad(e54.routes);\n if (e54.kind === \"regular-candidate\")\n return !t4 \u0026\u0026 $oe(e54.errors, this.bestErrors) \u0026\u0026 (this.bestRoutes = e54.routes, this.bestErrors = e54.errors), void (this.phase = \"commit-error\");\n t4 || (this.currentRoutes = e54.routes, this.currentErrors = e54.errors), this.finishRepair();\n }\n finishRepair() {\n if (this.activeSubSolver = null, this.introducesViaInPad(this.currentRoutes))\n return this.error = \"Pipeline9 regional repair introduced a forbidden via-in-pad\", void (this.failed = true);\n this.result = { routes: this.currentRoutes, attemptedCandidateCount: this.attemptedCandidateCount, acceptedCandidateCount: this.acceptedCandidateCount, fallbackCandidateCount: this.fallbackCandidateCount, candidateSearchCount: this.candidateSearchCount, candidateSearchBudget: this.candidateSearchBudget, candidateSearchBudgetExhausted: this.candidateSearchBudgetExhausted, safeTraceLayerRepairSkippedForBudget: this.safeTraceLayerRepairSkippedForBudget, remainingDrcIssueCount: this.currentErrors.length, preloadEligibleDrcIssueCount: this.preloadEligibleDrcIssueCount, preloadRepairAttempted: this.preloadEligibleDrcIssueCount \u003e 0 }, this.stats = { ...this.result, routes: undefined }, this.phase = \"done\", this.solved = true;\n }\n _step() {\n switch (this.phase) {\n case \"initialize\":\n return this.initializeRepair();\n case \"begin-pass\":\n return this.beginPass();\n case \"begin-error\":\n return this.beginError();\n case \"prepare-pair\":\n return this.preparePairCandidate();\n case \"route-pair\":\n return this.stepPairCandidate();\n case \"validate-pair\":\n return this.validatePairCandidate();\n case \"prepare-b01\":\n return this.prepareB01Candidate();\n case \"route-b01\":\n return this.stepB01Candidate();\n case \"validate-b01\":\n return this.validateB01Candidate();\n case \"prepare-regional\":\n return this.prepareRegularCandidate();\n case \"route-regional\":\n return this.stepRegularCandidate();\n case \"validate-regional\":\n return this.validateRegularCandidate();\n case \"commit-error\":\n return this.commitErrorRepair();\n case \"finish-pass\":\n return this.finishPass();\n case \"refine\":\n return this.refineCleanupRoutes();\n case \"prepare-via-pad-projection\":\n return this.prepareViaPadProjection();\n case \"project-via-pad\":\n return this.stepViaPadProjection();\n case \"prepare-safe-layer\":\n return this.prepareSafeLayerRepair();\n case \"route-safe-layer\":\n return this.stepSafeLayerRepair();\n case \"validate-safe-layer\":\n return this.validateSafeLayerRepair();\n case \"done\":\n throw new Error(\"Regional B01 repair was stepped after completion\");\n }\n }\n computeProgress() {\n if (this.solved)\n return 1;\n const e54 = this.activeSubSolver ? Math.max(0, Math.min(1, this.activeSubSolver.progress)) : 1;\n return Math.max(this.progress, Math.min(1, (Math.max(0, this.candidateSearchCount - 1) + e54) / (this.candidateSearchBudget + 1)));\n }\n getResult() {\n if (!this.solved || this.failed || !this.result)\n throw new Error(\"Pipeline9 regional B01 repair is not complete\");\n return this.result;\n }\n};\nvar gie = class extends ni {\n params;\n merger;\n result;\n phase = \"initialize\";\n physicalSrj;\n movableRoutes = [];\n candidateRoutes;\n beforeErrorCount = 0;\n constructor(e54) {\n super(), this.params = e54, this.MAX_ITERATIONS = 1000004;\n }\n initializeMerge() {\n const { srj: e54, routes: t4, connMap: n8, drcEvaluator: o10, referenceResult: i8 } = this.params, r9 = i8 ?? o10({ traces: [], routes: t4, hdRoutes: t4 });\n this.result = { routes: t4, referenceResult: r9, referenceValidationCount: i8 === undefined ? 1 : 0, accepted: false };\n const s7 = Array.isArray(r9) ? r9 : r9.errors;\n this.beforeErrorCount = s7.length;\n const a9 = s7.filter((e60) =\u003e e60.type === \"pcb_via_clearance_error\").flatMap(Uoe);\n if (this.movableRoutes = t4.filter((e60) =\u003e a9.some((t10) =\u003e t10 === e60.connectionName || t10.startsWith(`${e60.connectionName}_`))), this.movableRoutes.length === 0)\n return this.phase = \"done\", void (this.solved = true);\n this.physicalSrj = { ...V1(e54), traces: undefined };\n const c5 = new Set(this.movableRoutes);\n this.merger = new PF({ inputHdRoutes: this.movableRoutes, otherHdRoutes: t4.filter((e60) =\u003e !c5.has(e60)), netByConnectionName: hne(t4, n8), obstacles: this.physicalSrj.obstacles, layerCount: this.physicalSrj.layerCount, connMap: n8, colorMap: {}, preserveRouteEndpoints: true }), this.MAX_ITERATIONS = this.merger.MAX_ITERATIONS + 4, this.activeSubSolver = this.merger, this.phase = \"merge\";\n }\n stepMerge() {\n const e54 = this.merger;\n if (!e54)\n throw new Error(\"Reported via merge has no active merger\");\n if (e54.step(), e54.failed)\n throw new Error(`Reported via merge failed: ${e54.error}`);\n if (!e54.solved)\n return;\n if (e54.mergedViaHdRoutes.length !== this.movableRoutes.length)\n throw new Error(\"Reported via merge changed the number of route pieces\");\n const t4 = new Map(this.movableRoutes.map((t10, n8) =\u003e [t10, e54.mergedViaHdRoutes[n8]]));\n this.candidateRoutes = this.params.routes.map((e60) =\u003e t4.get(e60) ?? e60), this.activeSubSolver = null, this.phase = \"physical-check\";\n }\n validatePhysicalProposal() {\n const e54 = this.physicalSrj, t4 = this.candidateRoutes;\n if (!e54 || !t4)\n throw new Error(\"Reported via merge has no physical proposal\");\n const n8 = this.params.routes, o10 = new Map(ay({ srj: e54, routes: n8 }).map(({ key: e60, severity: t10 }) =\u003e [e60, t10]));\n if (!ay({ srj: e54, routes: t4 }).every(({ key: e60, severity: t10 }) =\u003e o10.has(e60) \u0026\u0026 t10 \u003c= o10.get(e60) + 0.00000001) || ly({ srj: e54, previousRoutes: n8, routes: t4 }).length \u003e 0)\n return this.phase = \"done\", void (this.solved = true);\n this.phase = \"reference-check\";\n }\n validateReferenceProposal() {\n const e54 = this.result, t4 = this.candidateRoutes;\n if (!e54 || !t4)\n throw new Error(\"Reported via merge has no reference proposal\");\n const n8 = this.params.drcEvaluator({ traces: [], routes: t4, hdRoutes: t4 });\n e54.referenceValidationCount++;\n (Array.isArray(n8) ? n8 : n8.errors).length \u003c this.beforeErrorCount \u0026\u0026 (this.result = { ...e54, routes: t4, referenceResult: n8, accepted: true }), this.phase = \"done\", this.solved = true;\n }\n _step() {\n switch (this.phase) {\n case \"initialize\":\n return this.initializeMerge();\n case \"merge\":\n return this.stepMerge();\n case \"physical-check\":\n return this.validatePhysicalProposal();\n case \"reference-check\":\n return this.validateReferenceProposal();\n case \"done\":\n throw new Error(\"Reported via merge was stepped after completion\");\n }\n }\n getResult() {\n if (!this.solved || this.failed || !this.result)\n throw new Error(\"Reported via merge is not complete\");\n return this.result;\n }\n};\nvar fie = [10, 16];\nvar _ie = class extends ni {\n params;\n budget;\n state = { phase: \"initialize\" };\n result;\n reservedChildMaximum = 0;\n constructor(e54) {\n super(), this.params = e54, this.budget = e54.budget ?? Joe, this.result = { routes: e54.routes, attemptedRegionCount: 0, acceptedRegionCount: 0, candidateAttemptCount: 0, pathSearchNodeCount: 0, referenceValidationCount: 0, initialDrcIssueCount: undefined, finalDrcIssueCount: undefined, publishedDrcIssueCount: undefined, repaired: false }, this.MAX_ITERATIONS = 16 * this.budget.maxRegions + 32;\n }\n updateProgress() {\n const e54 = Koe(this.budget, this.result.acceptedRegionCount), t4 = this.state.phase === \"negotiate\" ? this.state.solver : undefined, n8 = typeof t4?.stats.pathSearchCalls == \"number\" ? t4.stats.pathSearchCalls : 0, o10 = typeof t4?.stats.pathSearchNodes == \"number\" ? t4.stats.pathSearchNodes : 0;\n this.stats = { ...this.result, routes: undefined, phase: this.state.phase, candidateAttemptCount: this.result.candidateAttemptCount + n8, pathSearchNodeCount: this.result.pathSearchNodeCount + o10, allowedRegionCount: e54.maxRegions, allowedCandidateAttemptCount: e54.maxCandidateAttempts, allowedPathSearchNodeCount: e54.maxPathSearchNodes };\n const i8 = Math.max(this.result.attemptedRegionCount / Math.max(1, this.budget.maxRegions), this.stats.candidateAttemptCount / Math.max(1, this.budget.maxCandidateAttempts), this.stats.pathSearchNodeCount / Math.max(1, this.budget.maxPathSearchNodes));\n this.progress = this.solved ? 1 : Math.max(this.progress, Math.min(0.99, i8));\n }\n startChild(e54) {\n if (this.activeSubSolver)\n throw new Error(\"Regional repair started a child before the previous stage completed\");\n this.activeSubSolver = e54, this.reservedChildMaximum = e54.MAX_ITERATIONS, this.MAX_ITERATIONS += this.reservedChildMaximum + 1;\n }\n finish() {\n if (this.activeSubSolver)\n throw new Error(\"Regional repair finished with an active child solver\");\n this.solved = true, this.state = { phase: \"done\" };\n }\n publish(e54, t4) {\n this.result.routes = e54.currentRoutes, this.result.publishedDrcIssueCount = e54.currentErrors.length, this.result.finalDrcIssueCount = e54.currentErrors.length, this.result.repaired = t4, this.finish();\n }\n initialize() {\n const { originalSrj: e54, routes: t4, syntheticConnectionNames: n8 } = this.params;\n if (e54.traces?.length || n8.size \u003e 0)\n return void this.finish();\n const o10 = Math.max(e54.defaultObstacleMargin ?? 0.2, e54.minTraceToPadEdgeClearance ?? 0, e54.minTraceToHoleEdgeClearance ?? 0, e54.minViaEdgeToPadEdgeClearance ?? 0);\n let i8 = Math.max(e54.minTraceWidth, e54.minViaDiameter ?? 0);\n for (const e60 of t4) {\n i8 = Math.max(i8, e60.traceThickness, e60.viaDiameter);\n for (const t10 of e60.route)\n i8 = Math.max(i8, t10.traceThickness ?? 0);\n }\n const r9 = Math.max(0.5, i8 + o10), s7 = (this.budget.regionSizes ?? fie).filter((e60) =\u003e !Number.isFinite(r9) || 2 * r9 \u003c e60);\n s7.length !== 0 ? this.state = { phase: \"initial-reference\", context: { boundaryMargin: r9, regionSizes: s7 } } : this.finish();\n }\n initialReference(e54) {\n const t4 = this.params.drcEvaluator({ traces: [], routes: this.params.routes, hdRoutes: this.params.routes });\n this.result.referenceValidationCount++;\n const n8 = Array.isArray(t4) ? t4 : t4.errors, o10 = { ...e54, currentRoutes: this.params.routes, reference: t4, currentErrors: n8, initialErrors: n8 };\n if (this.result.initialDrcIssueCount = n8.length, this.result.finalDrcIssueCount = n8.length, this.result.publishedDrcIssueCount = n8.length, n8.length === 0)\n return void this.finish();\n const i8 = [], r9 = Array.isArray(t4) ? t4 : t4.errorsWithCenters ?? t4.errors;\n for (const t10 of r9) {\n const n10 = t10.center ?? t10.pcb_center;\n n10 \u0026\u0026 typeof n10 == \"object\" \u0026\u0026 \"x\" in n10 \u0026\u0026 typeof n10.x == \"number\" \u0026\u0026 Number.isFinite(n10.x) \u0026\u0026 \"y\" in n10 \u0026\u0026 typeof n10.y == \"number\" \u0026\u0026 Number.isFinite(n10.y) \u0026\u0026 i8.push({ center: { x: n10.x, y: n10.y }, radius: e54.regionSizes[0] / 2 });\n }\n const s7 = new qoe({ originalSrj: this.params.originalSrj, routes: o10.currentRoutes, movableRegions: i8, drcEvaluator: (e60) =\u003e (this.result.referenceValidationCount++, this.params.drcEvaluator(e60)) });\n this.state = { phase: \"initial-projection\", context: o10, solver: s7 }, this.startChild(s7);\n }\n initialProjectionReference(e54) {\n const t4 = this.params.drcEvaluator({ traces: [], routes: e54.currentRoutes, hdRoutes: e54.currentRoutes });\n this.result.referenceValidationCount++, e54.reference = t4, e54.currentErrors = Array.isArray(t4) ? t4 : t4.errors, this.result.finalDrcIssueCount = e54.currentErrors.length, e54.currentErrors.length !== 0 ? this.state = { phase: \"prepare-regions\", context: e54 } : this.publish(e54, true);\n }\n prepareRegions(e54) {\n const t4 = { ...V1(this.params.originalSrj), traces: undefined }, n8 = new Map;\n for (const e60 of this.params.originalSrj.obstacles)\n for (const t10 of [e60.obstacleId, e60.circuitJsonMetadata?.pcb_smtpad_id, e60.circuitJsonMetadata?.pcb_plated_hole_id, e60.connectedTo[0]])\n typeof t10 == \"string\" \u0026\u0026 n8.set(t10, e60.center);\n const o10 = bne(e54.currentRoutes), i8 = { ...e54, srj: t4, obstacleCenterById: n8, currentRoutes: o10, attemptedRegions: [], fixedViolations: new Map(ay({ srj: t4, routes: o10 }).map(({ key: e60, severity: t10 }) =\u003e [e60, t10])) };\n this.state = { phase: \"select-region\", context: i8 };\n }\n selectRegion(e54) {\n const t4 = Koe(this.budget, this.result.acceptedRegionCount);\n if (this.result.attemptedRegionCount \u003e= t4.maxRegions || this.result.candidateAttemptCount \u003e= t4.maxCandidateAttempts || this.result.pathSearchNodeCount \u003e= t4.maxPathSearchNodes)\n return void (this.state = { phase: \"publish-partial\", context: e54 });\n const n8 = Array.isArray(e54.reference) ? e54.reference : e54.reference.errorsWithCenters ?? e54.reference.errors, o10 = n8.filter((e60) =\u003e !uw(e60)), i8 = o10.length \u003e 0 ? o10 : n8, r9 = i8.map((t10) =\u003e {\n const n10 = `overlap_${t10.pcb_trace_id}_`, o11 = typeof t10.pcb_pad_id == \"string\" ? t10.pcb_pad_id : typeof t10.pcb_trace_error_id == \"string\" \u0026\u0026 t10.pcb_trace_error_id.startsWith(n10) ? t10.pcb_trace_error_id.slice(n10.length) : undefined;\n return (o11 ? e54.obstacleCenterById.get(o11) : undefined) ?? t10.center ?? t10.pcb_center;\n }).filter((e60) =\u003e e60 !== null \u0026\u0026 typeof e60 == \"object\" \u0026\u0026 (\"x\" in e60) \u0026\u0026 (\"y\" in e60) \u0026\u0026 typeof e60.x == \"number\" \u0026\u0026 typeof e60.y == \"number\" \u0026\u0026 Number.isFinite(e60.x) \u0026\u0026 Number.isFinite(e60.y));\n let s7;\n for (const t10 of e54.regionSizes) {\n const n10 = r9.filter(({ x: n11, y: o12 }) =\u003e !e54.attemptedRegions.some(({ bounds: e60, size: i10 }) =\u003e t10 === i10 \u0026\u0026 n11 \u003e= e60.minX \u0026\u0026 n11 \u003c= e60.maxX \u0026\u0026 o12 \u003e= e60.minY \u0026\u0026 o12 \u003c= e60.maxY)), o11 = n10[0];\n if (!o11)\n continue;\n let { x: i9, x: a10, y: c9, y: l10 } = o11;\n const h9 = t10 - 2 * e54.boundaryMargin;\n for (const e60 of n10.slice(1)) {\n const t11 = Math.min(i9, e60.x), n11 = Math.max(a10, e60.x), o12 = Math.min(c9, e60.y), r10 = Math.max(l10, e60.y);\n n11 - t11 \u003e= h9 || r10 - o12 \u003e= h9 || (i9 = t11, a10 = n11, c9 = o12, l10 = r10);\n }\n s7 = { center: { x: (i9 + a10) / 2, y: (c9 + l10) / 2 }, size: t10 };\n break;\n }\n if (!s7)\n return void (this.state = { phase: \"publish-partial\", context: e54 });\n const { center: a9, size: c5 } = s7, l5 = Iy({ srj: e54.srj, routes: e54.currentRoutes, bounds: { minX: a9.x - c5 / 2, maxX: a9.x + c5 / 2, minY: a9.y - c5 / 2, maxY: a9.y + c5 / 2 } });\n if (e54.attemptedRegions.push({ bounds: l5.mutableBounds, size: c5 }), this.result.attemptedRegionCount++, l5.routes.length === 0)\n return;\n const h5 = e54.currentErrors.map(Uoe);\n if (this.params.prioritizeConflictedRoutes) {\n const e60 = i8.map(Uoe), t10 = l5.routes.map((t11) =\u003e e60.filter((e61) =\u003e e61.some((e63) =\u003e e63 === t11.connectionName || e63.startsWith(`${t11.connectionName}_`))).length), n10 = l5.routes.map((e61, t11) =\u003e t11).sort((e61, n11) =\u003e t10[n11] - t10[e61]);\n l5.routes = n10.map((e61) =\u003e l5.routes[e61]), l5.lockedPointIndices = n10.map((e61) =\u003e l5.lockedPointIndices[e61]), l5.routeMappings = n10.map((e61) =\u003e l5.routeMappings[e61]);\n }\n const d9 = new Set(h5.flat()), u9 = l5.routes.flatMap((e60, t10) =\u003e [...d9].some((t11) =\u003e t11 === e60.connectionName || t11.startsWith(`${e60.connectionName}_`)) ? [t10] : []), p9 = Math.min(this.budget.maxCandidateAttemptsPerRegion ?? (this.budget.revisitChangedRegions ? Math.ceil(t4.maxCandidateAttempts / 2) : t4.maxCandidateAttempts), t4.maxCandidateAttempts - this.result.candidateAttemptCount), m9 = l5.routes;\n for (const [t10, n10] of m9.entries()) {\n const o11 = l5.routeMappings[t10].sourceRouteIndex, i9 = e54.currentRoutes[o11].route.filter((e60) =\u003e e60.terminalApproach !== undefined);\n if (i9.length !== 0)\n for (const [e60, o12] of n10.route.entries())\n i9.some((e61) =\u003e e61.terminalApproach === o12.terminalApproach \u0026\u0026 e61.x === o12.x \u0026\u0026 e61.y === o12.y \u0026\u0026 e61.z === o12.z) \u0026\u0026 (l5.lockedPointIndices[t10][e60] = true);\n }\n const g10 = new Xy({ srj: l5.srj, routes: m9, bounds: l5.mutableBounds, dirtyRouteIndices: u9, isLocked: (e60, t10) =\u003e l5.lockedPointIndices[e60][t10], maxPathSearchCalls: p9, maxPathSearchNodes: t4.maxPathSearchNodes - this.result.pathSearchNodeCount, maxPathSearchNodesPerCall: this.budget.maxPathSearchNodesPerCall, pathHeuristicWeight: this.budget.pathHeuristicWeight, pathGridSizeScale: this.budget.pathGridSizeScale === undefined ? undefined : this.budget.pathGridSizeScale * (e54.regionSizes[0] / c5), allowLayerChanges: true, traceClearance: hR, viaClearance: e54.srj.minPadEdgeToPadEdgeClearance ?? dR, viaHoleDiameter: this.params.viaHoleDiameter, searchDirectionCount: this.budget.searchDirectionCount ?? 1 });\n this.state = { phase: \"negotiate\", negotiation: { context: e54, allowance: t4, maxPathSearchCalls: p9, region: l5 }, solver: g10 }, this.startChild(g10);\n }\n completeNegotiation(e54) {\n const t4 = e54.solver.getOutput(), { context: n8, allowance: o10, maxPathSearchCalls: i8 } = e54.negotiation, { pathSearchCalls: r9, pathSearchNodes: s7 } = t4;\n if (this.budget.revisitChangedRegions \u0026\u0026 t4.unresolvedSpanCount \u003e 0 \u0026\u0026 r9 \u003c i8 \u0026\u0026 s7 \u003c o10.maxPathSearchNodes - this.result.pathSearchNodeCount \u0026\u0026 n8.regionSizes.sort((e60, t10) =\u003e t10 - e60), !Number.isSafeInteger(r9) || r9 \u003c 0 || r9 + this.result.candidateAttemptCount \u003e this.budget.maxCandidateAttempts || !Number.isSafeInteger(s7) || s7 \u003c 0 || s7 + this.result.pathSearchNodeCount \u003e this.budget.maxPathSearchNodes)\n throw new Error(\"Pipeline9 bounded regional repair exceeded its work budget\");\n this.result.candidateAttemptCount += r9, this.result.pathSearchNodeCount += s7, this.state = { phase: \"splice-region\", negotiation: e54.negotiation, repair: t4 };\n }\n spliceRegion(e54) {\n const { context: t4, region: n8 } = e54.negotiation, o10 = ((e60, t10) =\u003e {\n let n10 = t10;\n for (const [o11, i9] of t10.entries()) {\n if (!i9.route.some((e61) =\u003e e61.terminalApproach !== undefined))\n continue;\n const r9 = e60[o11].route.filter((e61) =\u003e e61.terminalApproach !== undefined);\n let s7 = i9.route;\n for (const [e61, t11] of i9.route.entries()) {\n if (t11.terminalApproach === undefined || r9.some((e63) =\u003e e63.terminalApproach === t11.terminalApproach \u0026\u0026 e63.x === t11.x \u0026\u0026 e63.y === t11.y \u0026\u0026 e63.z === t11.z))\n continue;\n s7 === i9.route \u0026\u0026 (s7 = [...i9.route]);\n const n11 = { ...t11 };\n delete n11.terminalApproach, s7[e61] = n11;\n }\n s7 !== i9.route \u0026\u0026 (n10 === t10 \u0026\u0026 (n10 = [...t10]), n10[o11] = { ...i9, route: s7 });\n }\n return n10;\n })(t4.currentRoutes, (({ routes: e60, region: t10, repairedRoutes: n10 }) =\u003e {\n if (n10.length !== t10.routeMappings.length || t10.lockedPointIndices.length !== n10.length)\n throw new Error(\"repair04 merge requires exactly one replacement for every extracted fragment\");\n const o11 = new Map;\n for (let i9 = 0;i9 \u003c n10.length; i9 += 1) {\n const r9 = t10.routeMappings[i9], s7 = n10[i9];\n if (!e60[r9.sourceRouteIndex])\n throw new Error(\"repair04 merge source route no longer exists\");\n if (Py(r9.originalFragment, s7, t10.lockedPointIndices[i9], t10.mutableBounds, t10.contextBounds, t10.srj.layerCount), za(r9.originalFragment) === za(s7))\n continue;\n const a9 = o11.get(r9.sourceRouteIndex) ?? [];\n a9.push({ mapping: r9, repaired: s7 }), o11.set(r9.sourceRouteIndex, a9);\n }\n return e60.map((e61, t11) =\u003e {\n const n11 = o11.get(t11);\n if (!n11)\n return e61;\n n11.sort((e63, t12) =\u003e Ny(e63.mapping.start) - Ny(t12.mapping.start));\n const i9 = [];\n let r9 = 0;\n for (const { mapping: t12, repaired: o12 } of n11) {\n const n12 = Ny(t12.start), s9 = Ny(t12.end);\n if (n12 \u003c r9 - Aa || s9 \u003c n12 || s9 \u003e e61.route.length - 1 + Aa)\n throw new Error(\"repair04 merge received overlapping or stale fragment provenance\");\n if (Fa(e61, n12, s9) !== t12.sourceGeometryKey)\n throw new Error(\"repair04 merge rejected stale source geometry\");\n My(i9, Ba(e61, r9, n12)), My(i9, o12.route), r9 = s9;\n }\n My(i9, Ba(e61, r9, e61.route.length - 1));\n const s7 = new Set(n11.flatMap(({ mapping: e63 }) =\u003e e63.originalFragment.vias.map((e64) =\u003e `${e64.x},${e64.y}`))), a9 = e61.vias.filter((e63) =\u003e !s7.has(`${e63.x},${e63.y}`)).map((e63) =\u003e structuredClone(e63));\n for (const { repaired: e63 } of n11)\n for (const t12 of e63.vias)\n a9.some((e64) =\u003e Math.abs(e64.x - t12.x) \u003c= Aa \u0026\u0026 Math.abs(e64.y - t12.y) \u003c= Aa) || a9.push(structuredClone(t12));\n return { ...e61, route: wy(i9, e61, n11.map(({ mapping: e63 }) =\u003e e63)), vias: a9 };\n });\n })({ routes: t4.currentRoutes, region: n8, repairedRoutes: e54.repair.routes }));\n if (o10.every((e60, n10) =\u003e e60 === t4.currentRoutes[n10]))\n return void (this.state = { phase: \"select-region\", context: t4 });\n const i8 = new qoe({ originalSrj: this.params.originalSrj, routes: o10, previousRoutes: t4.currentRoutes, subdivideSegments: true, drcEvaluator: (e60) =\u003e (this.result.referenceValidationCount++, this.params.drcEvaluator(e60)) });\n this.state = { phase: \"candidate-projection\", context: t4, solver: i8 }, this.startChild(i8);\n }\n prepareViaMerge(e54) {\n if (!this.params.connMap)\n return void (this.state = { ...e54, phase: \"candidate-physical\" });\n const t4 = new gie({ srj: e54.context.srj, routes: e54.candidateRoutes, connMap: this.params.connMap, drcEvaluator: this.params.drcEvaluator });\n this.state = { ...e54, phase: \"via-merge\", solver: t4 }, this.startChild(t4);\n }\n validateCandidate(e54) {\n const { context: t4, candidateRoutes: n8 } = e54, o10 = ay({ srj: t4.srj, routes: n8 });\n !o10.every(({ key: e60, severity: n10 }) =\u003e t4.fixedViolations.has(e60) \u0026\u0026 n10 \u003c= t4.fixedViolations.get(e60) + 0.00000001) || ly({ srj: t4.srj, previousRoutes: t4.currentRoutes, routes: n8 }).length \u003e 0 ? this.state = { phase: \"select-region\", context: t4 } : this.state = e54.candidateReference === undefined ? { phase: \"candidate-reference\", context: t4, candidateRoutes: n8, candidateFixedViolations: o10 } : { phase: \"accept-candidate\", context: t4, candidateRoutes: n8, candidateFixedViolations: o10, candidateReference: e54.candidateReference };\n }\n referenceCandidate(e54) {\n const t4 = this.params.drcEvaluator({ traces: [], routes: e54.candidateRoutes, hdRoutes: e54.candidateRoutes });\n this.result.referenceValidationCount++, this.state = { ...e54, phase: \"accept-candidate\", candidateReference: t4 };\n }\n acceptCandidate(e54) {\n const { context: t4, candidateReference: n8 } = e54, o10 = Array.isArray(n8) ? n8 : n8.errors;\n o10.length \u003e= t4.currentErrors.length ? this.state = { phase: \"select-region\", context: t4 } : (t4.currentRoutes = e54.candidateRoutes, t4.currentErrors = o10, t4.reference = n8, t4.fixedViolations = new Map(e54.candidateFixedViolations.map(({ key: e60, severity: t10 }) =\u003e [e60, t10])), this.result.acceptedRegionCount++, this.budget.revisitChangedRegions \u0026\u0026 (t4.attemptedRegions.length = 0), this.result.finalDrcIssueCount = o10.length, o10.length !== 0 ? this.state = { phase: \"select-region\", context: t4 } : this.publish(t4, true));\n }\n publishPartial(e54) {\n (({ originalSrj: e60, initialErrors: t4, remainingErrors: n8 }) =\u003e {\n if (n8.length \u003e= t4.length)\n return false;\n if (n8.length === 0)\n return true;\n const o10 = new Set(oR(e60).flatMap((e61) =\u003e e61.type === \"pcb_smtpad\" ? [e61.pcb_smtpad_id] : e61.type === \"pcb_plated_hole\" ? [e61.pcb_plated_hole_id] : [])), i8 = [...t4];\n for (const e61 of n8) {\n if (typeof e61.pcb_trace_id != \"string\")\n return false;\n const t10 = `overlap_${e61.pcb_trace_id}_`, n10 = e61.type === \"pcb_trace_error\" \u0026\u0026 typeof e61.pcb_trace_error_id == \"string\" \u0026\u0026 e61.pcb_trace_error_id.startsWith(t10) ? e61.pcb_trace_error_id.slice(t10.length) : undefined, r9 = Goe(e61), s7 = e61.type === \"pcb_pad_trace_clearance_error\" || r9, a9 = r9 ? e61.pcb_pad_ids.find((e63) =\u003e o10.has(e63)) : s7 ? e61.pcb_pad_id : n10;\n if (typeof a9 != \"string\" || !o10.has(a9))\n return false;\n const c5 = i8.findIndex((t11) =\u003e t11.type === e61.type \u0026\u0026 t11.pcb_trace_id === e61.pcb_trace_id \u0026\u0026 (r9 ? Goe(t11) \u0026\u0026 t11.pcb_pad_ids.includes(a9) : s7 ? t11.pcb_pad_id === a9 : t11.pcb_trace_error_id === e61.pcb_trace_error_id));\n if (c5 === -1)\n return false;\n const l5 = i8.splice(c5, 1)[0];\n if (s7 \u0026\u0026 (typeof e61.actual_clearance != \"number\" || !Number.isFinite(e61.actual_clearance) || typeof l5.actual_clearance != \"number\" || !Number.isFinite(l5.actual_clearance) || typeof e61.minimum_clearance != \"number\" || !Number.isFinite(e61.minimum_clearance) || e61.minimum_clearance !== l5.minimum_clearance || e61.actual_clearance \u003c l5.actual_clearance))\n return false;\n }\n return true;\n })({ originalSrj: this.params.originalSrj, initialErrors: e54.initialErrors, remainingErrors: e54.currentErrors }) ? this.publish(e54, false) : this.state = { phase: \"prepare-independent-projection\", context: e54 };\n }\n prepareIndependentProjection(e54) {\n const t4 = new qoe({ originalSrj: this.params.originalSrj, routes: this.params.routes, allowPartialRepair: true, drcEvaluator: (e60) =\u003e (this.result.referenceValidationCount++, this.params.drcEvaluator(e60)) });\n this.state = { phase: \"independent-projection\", context: e54, solver: t4 }, this.startChild(t4);\n }\n prepareIndependentSubdivision(e54) {\n const t4 = new qoe({ originalSrj: this.params.originalSrj, routes: e54.independentRoutes, allowPartialRepair: true, subdivideSegments: true, drcEvaluator: (e60) =\u003e (this.result.referenceValidationCount++, this.params.drcEvaluator(e60)) });\n this.state = { phase: \"independent-subdivision\", context: e54.context, solver: t4 }, this.startChild(t4);\n }\n prepareIndependentCoupled(e54) {\n const t4 = new qoe({ originalSrj: this.params.originalSrj, routes: e54.independentRoutes, usePrecisionMargin: true, drcEvaluator: (e60) =\u003e (this.result.referenceValidationCount++, this.params.drcEvaluator(e60)) });\n this.state = { phase: \"independent-coupled\", context: e54.context, solver: t4 }, this.startChild(t4);\n }\n referenceIndependent(e54) {\n const t4 = this.params.drcEvaluator({ traces: [], routes: e54.independentRoutes, hdRoutes: e54.independentRoutes });\n this.result.referenceValidationCount++;\n const n8 = Array.isArray(t4) ? t4 : t4.errors;\n this.result.routes = e54.independentRoutes, this.result.publishedDrcIssueCount = n8.length, this.result.finalDrcIssueCount = n8.length, this.result.repaired = n8.length === 0, this.finish();\n }\n completeChild() {\n const e54 = this.state;\n switch (e54.phase) {\n case \"initial-projection\": {\n const t4 = e54.solver.getOutput();\n t4 !== e54.context.currentRoutes ? (e54.context.currentRoutes = t4, this.state = { phase: \"initial-projection-reference\", context: e54.context }) : this.state = { phase: \"prepare-regions\", context: e54.context };\n break;\n }\n case \"negotiate\":\n this.completeNegotiation(e54);\n break;\n case \"candidate-projection\": {\n const t4 = new qoe({ originalSrj: this.params.originalSrj, routes: e54.solver.getOutput(), previousRoutes: e54.context.currentRoutes, usePrecisionMargin: true, drcEvaluator: (e60) =\u003e (this.result.referenceValidationCount++, this.params.drcEvaluator(e60)) });\n this.state = { phase: \"candidate-margin-projection\", context: e54.context, solver: t4 }, this.startChild(t4);\n break;\n }\n case \"candidate-margin-projection\":\n this.state = { phase: \"prepare-via-merge\", context: e54.context, candidateRoutes: e54.solver.getOutput() };\n break;\n case \"via-merge\": {\n const t4 = e54.solver.getResult();\n this.result.referenceValidationCount += t4.referenceValidationCount, this.state = { phase: \"candidate-physical\", context: e54.context, candidateRoutes: t4.routes, candidateReference: t4.referenceResult };\n break;\n }\n case \"independent-projection\":\n this.state = { phase: \"prepare-independent-subdivision\", context: e54.context, independentRoutes: e54.solver.getOutput() };\n break;\n case \"independent-subdivision\": {\n const t4 = e54.solver.getOutput();\n t4 === this.params.routes ? this.finish() : this.state = { phase: \"prepare-independent-coupled\", context: e54.context, independentRoutes: t4 };\n break;\n }\n case \"independent-coupled\":\n this.state = { phase: \"independent-reference\", context: e54.context, independentRoutes: e54.solver.getOutput() };\n break;\n default:\n throw new Error(`Regional repair child completed during phase ${e54.phase}`);\n }\n }\n _step() {\n const e54 = this.activeSubSolver;\n if (e54)\n return e54.step(), e54.MAX_ITERATIONS \u003e this.reservedChildMaximum \u0026\u0026 (this.MAX_ITERATIONS += e54.MAX_ITERATIONS - this.reservedChildMaximum, this.reservedChildMaximum = e54.MAX_ITERATIONS), e54.failed ? (this.failed = true, this.error = e54.error) : e54.solved \u0026\u0026 (this.activeSubSolver = null, this.reservedChildMaximum = 0, this.completeChild()), void this.updateProgress();\n const t4 = this.state;\n switch (t4.phase) {\n case \"initialize\":\n this.initialize();\n break;\n case \"initial-reference\":\n this.initialReference(t4.context);\n break;\n case \"initial-projection-reference\":\n this.initialProjectionReference(t4.context);\n break;\n case \"prepare-regions\":\n this.prepareRegions(t4.context);\n break;\n case \"select-region\":\n this.selectRegion(t4.context);\n break;\n case \"splice-region\":\n this.spliceRegion(t4);\n break;\n case \"prepare-via-merge\":\n this.prepareViaMerge(t4);\n break;\n case \"candidate-physical\":\n this.validateCandidate(t4);\n break;\n case \"candidate-reference\":\n this.referenceCandidate(t4);\n break;\n case \"accept-candidate\":\n this.acceptCandidate(t4);\n break;\n case \"publish-partial\":\n this.publishPartial(t4.context);\n break;\n case \"prepare-independent-projection\":\n this.prepareIndependentProjection(t4.context);\n break;\n case \"prepare-independent-subdivision\":\n this.prepareIndependentSubdivision(t4);\n break;\n case \"prepare-independent-coupled\":\n this.prepareIndependentCoupled(t4);\n break;\n case \"independent-reference\":\n this.referenceIndependent(t4);\n break;\n default:\n throw new Error(`Regional repair has no active child during phase ${t4.phase}`);\n }\n this.updateProgress();\n }\n getResult() {\n if (!this.solved || this.failed)\n throw new Error(\"Pipeline9 bounded regional repair result requested before completion\");\n return this.result;\n }\n};\nvar yie = [0.9, 0.72];\nvar bie = Array.from({ length: 16 }, (e54, t4) =\u003e t4 * Math.PI / 8);\nvar xie = (e54) =\u003e e54.type === \"pcb_pad_trace_clearance_error\" || e54.type === \"pcb_trace_error\" \u0026\u0026 !(Array.isArray(e54.pcb_trace_ids) \u0026\u0026 e54.pcb_trace_ids.length \u003e= 2);\nvar vie = (e54) =\u003e {\n if (typeof e54.pcb_pad_id == \"string\")\n return e54.pcb_pad_id;\n if (typeof e54.pcb_trace_error_id == \"string\") {\n const t10 = e54.pcb_trace_error_id.match(/(pcb_(?:smtpad|plated_hole|hole|keepout)_\\d+)$/)?.[1];\n if (t10)\n return t10;\n }\n const t4 = typeof e54.message == \"string\" ? e54.message : \"\";\n return t4.match(/(?:pcb_smtpad|pcb_plated_hole|pcb_hole|pcb_keepout)\\[#?([^\\]\"]+)\\]/)?.[1];\n};\nvar Iie = (e54, t4) =\u003e {\n if (!t4)\n return;\n const n8 = t4.startsWith(\"pcb_\") ? t4 : `pcb_${t4}`;\n return e54.obstacles.find((e60) =\u003e e60.obstacleId === n8 || e60.connectedTo[0] === n8);\n};\nvar Sie = ({ srj: e54, pcbPortId: t4, z: n8, portPositionMap: o10 }) =\u003e {\n const i8 = Co(n8, e54.layerCount), r9 = o10.get(t4), s7 = e54.obstacles.filter((e60) =\u003e e60.layers.includes(i8) \u0026\u0026 e60.connectedTo.includes(t4));\n return r9 ? s7.reduce((e60, t10) =\u003e e60 ? Math.hypot(t10.center.x - r9.x, t10.center.y - r9.y) \u003c Math.hypot(e60.center.x - r9.x, e60.center.y - r9.y) ? t10 : e60 : t10, undefined) : s7[0];\n};\nvar Cie = (e54, t4) =\u003e ({ x: e54.x * Math.cos(t4) - e54.y * Math.sin(t4), y: e54.x * Math.sin(t4) + e54.y * Math.cos(t4) });\nvar Pie = (e54, t4, n8, o10) =\u003e {\n if (n8.type !== \"pcb_pad_trace_clearance_error\" \u0026\u0026 n8.type !== \"pcb_trace_error\" || typeof n8.actual_clearance != \"number\" || n8.actual_clearance \u003c 0)\n return false;\n for (const i8 of [0, e54.route.length - 1]) {\n const r9 = e54.route[i8], s7 = e54.route[i8 === 0 ? 1 : i8 - 1];\n if (!r9?.pcb_port_id || !s7 || r9.z !== s7.z || r9.toNextSegmentType || s7.toNextSegmentType || !t4.layers.includes(Co(r9.z, o10)))\n continue;\n const a9 = ((i8 === 0 ? r9 : s7).traceThickness ?? e54.traceThickness) / 2, c5 = Cie({ x: r9.x - t4.center.x, y: r9.y - t4.center.y }, -(t4.ccwRotationDegrees ?? 0) * Math.PI / 180);\n if ((t4.shape === \"circle\" ? Math.max(0, Math.hypot(c5.x, c5.y) - t4.width / 2) : Math.hypot(Math.max(0, Math.abs(c5.x) - t4.width / 2), Math.max(0, Math.abs(c5.y) - t4.height / 2))) - a9 \u003c= n8.actual_clearance + 0.000000001)\n return true;\n }\n return false;\n};\nvar Mie = ({ terminalObstacle: e54, conflictingObstacle: t4, traceRadius: n8 }) =\u003e {\n const o10 = Math.max(0, e54.width / 2 - n8), i8 = Math.max(0, e54.height / 2 - n8), r9 = (e54.ccwRotationDegrees ?? 0) * Math.PI / 180;\n return yie.flatMap((t10) =\u003e bie.map((n10) =\u003e {\n const s7 = { x: Math.cos(n10) * o10 * t10, y: Math.sin(n10) * i8 * t10 }, a9 = Cie(s7, r9);\n return { x: e54.center.x + a9.x, y: e54.center.y + a9.y };\n })).sort((e60, n10) =\u003e Math.hypot(n10.x - t4.center.x, n10.y - t4.center.y) - Math.hypot(e60.x - t4.center.x, e60.y - t4.center.y)).slice(0, 16);\n};\nvar wie = ({ routes: e54, routeIndex: t4, endpointIndex: n8, point: o10, bounds: i8, collapseAdjacent: r9 }) =\u003e {\n const s7 = e54[t4];\n if (!s7 || s7.route.length \u003c 2)\n return;\n const a9 = n8 === 0 ? 0 : s7.route.length - 1, c5 = n8 === 0 ? 1 : a9 - 1, l5 = s7.route[a9], h5 = s7.route[c5];\n if (!l5 || !h5 || l5.z !== h5.z)\n return;\n if (l5.toNextSegmentType || h5.toNextSegmentType)\n return;\n const d9 = s7.traceThickness / 2;\n if (o10.x - d9 \u003c i8.minX || o10.x + d9 \u003e i8.maxX || o10.y - d9 \u003c i8.minY || o10.y + d9 \u003e i8.maxY)\n return;\n const u9 = n8 === 0 ? \"start\" : \"end\", p9 = { ...h5, ...o10, terminalApproach: u9 };\n if (r9) {\n const e60 = n8 === 0 ? c5 + 1 : c5 - 1, t10 = s7.route[e60], o11 = s7.vias.some((e61) =\u003e e61.x === h5.x \u0026\u0026 e61.y === h5.y);\n if (!t10 || t10.z !== l5.z || h5.pcb_port_id !== undefined || o11)\n return;\n }\n const m9 = [...e54], g10 = ((e60) =\u003e e60.map((e61) =\u003e ({ ...e61, route: e61.route.map((e63) =\u003e ({ ...e63 })), vias: e61.vias.map((e63) =\u003e ({ ...e63 })) })))([s7])[0];\n m9[t4] = g10;\n for (const e60 of g10.route)\n e60.terminalApproach === u9 \u0026\u0026 delete e60.terminalApproach;\n if (r9)\n g10.route[c5] = p9;\n else {\n const e60 = n8 === 0 ? l5 : h5;\n g10.route.splice(n8 === 0 ? 1 : a9, 0, { x: o10.x, y: o10.y, z: l5.z, terminalApproach: u9, ...e60.traceThickness !== undefined ? { traceThickness: e60.traceThickness } : {} });\n }\n return m9;\n};\nvar Nie = ({ srj: e54, originalSrj: t4, routes: n8, newConnections: o10, syntheticConnectionNames: i8, drcEvaluator: r9, effort: s7 = 1 }) =\u003e {\n let a9 = n8, c5 = zoe(r9, a9), l5 = 0, h5 = 0;\n const d9 = c5.length \u003c 20 || n8.length \u003c= 120 ? 256 : Math.max(32, Math.min(256, Math.floor(16384 * Math.max(1, s7) / n8.length))), u9 = ((e60) =\u003e {\n const t10 = new Map;\n for (const n10 of e60.connections)\n for (const e61 of n10.pointsToConnect)\n e61.pcb_port_id \u0026\u0026 t10.set(e61.pcb_port_id, e61);\n return t10;\n })(t4);\n for (let n10 = 0;n10 \u003c 2; n10++) {\n let n11 = false;\n const s9 = Yoe({ routes: a9, newConnections: o10, syntheticConnectionNames: i8 });\n for (const o11 of c5.filter(xie)) {\n if (l5 \u003e= d9)\n break;\n if (typeof o11.pcb_trace_id != \"string\")\n continue;\n const i9 = s9.get(o11.pcb_trace_id), p9 = Iie(e54, vie(o11));\n if (i9 === undefined || !p9)\n continue;\n const m9 = a9[i9], g10 = Iie(t4, vie(o11));\n if (c5.length === 1 \u0026\u0026 c5[0] === o11 \u0026\u0026 g10 \u0026\u0026 Pie(m9, g10, o11, t4.layerCount))\n continue;\n let f10 = a9, _5 = c5;\n e:\n for (const n12 of [0, -1]) {\n const o12 = n12 === 0 ? m9.route[0] : m9.route.at(-1);\n if (!o12 || typeof o12.pcb_port_id != \"string\")\n continue;\n const s10 = Sie({ srj: t4, pcbPortId: o12.pcb_port_id, z: o12.z, portPositionMap: u9 });\n if (!s10 || s10 === p9)\n continue;\n const c9 = Math.hypot(p9.width, p9.height) / 2 + Math.hypot(s10.width, s10.height) / 2 + 0.5;\n if (!(Math.hypot(o12.x - p9.center.x, o12.y - p9.center.y) \u003e c9))\n for (const t10 of Mie({ terminalObstacle: s10, conflictingObstacle: p9, traceRadius: m9.traceThickness / 2 }))\n for (const o13 of [false, true]) {\n if (l5 \u003e= d9)\n break e;\n const s11 = wie({ routes: a9, routeIndex: i9, endpointIndex: n12, point: t10, bounds: e54.bounds, collapseAdjacent: o13 });\n if (!s11)\n continue;\n l5++;\n const c10 = zoe(r9, s11);\n if ($oe(c10, _5) \u0026\u0026 (f10 = s11, _5 = c10, _5.length === 0))\n return { routes: f10, attemptedCandidateCount: l5, acceptedCandidateCount: h5 + 1, remainingErrors: _5 };\n }\n }\n f10 !== a9 \u0026\u0026 (a9 = f10, c5 = _5, h5++, n11 = true);\n }\n if (!n11 || c5.length === 0)\n break;\n }\n return { routes: a9, attemptedCandidateCount: l5, acceptedCandidateCount: h5, remainingErrors: c5 };\n};\nvar Rie = [\"pcb_trace_error_id\", \"pcb_error_id\", \"pcb_via_trace_clearance_error_id\", \"pcb_pad_trace_clearance_error_id\"];\nvar Tie = (e54, t4) =\u003e {\n let n8 = e54;\n const o10 = [...t4].sort(([e60], [t10]) =\u003e t10.length - e60.length);\n for (const [e60, t10] of o10)\n n8 = n8.replaceAll(e60, t10);\n return n8;\n};\nvar Eie = (e54, t4) =\u003e {\n const n8 = String(e54.type ?? e54.error_type ?? \"unknown\");\n if (n8 === \"pcb_via_clearance_error\")\n return ((e60, t10) =\u003e {\n const n10 = [...typeof e60.pcb_trace_id == \"string\" ? [e60.pcb_trace_id] : [], ...Array.isArray(e60.pcb_trace_ids) ? e60.pcb_trace_ids.filter((e61) =\u003e typeof e61 == \"string\") : []].map((e61) =\u003e Tie(e61, t10)).filter((e61, t11, n11) =\u003e n11.indexOf(e61) === t11).sort(), o11 = e60.center \u0026\u0026 typeof e60.center == \"object\" ? e60.center : e60.pcb_center \u0026\u0026 typeof e60.pcb_center == \"object\" ? e60.pcb_center : undefined, i8 = typeof o11?.x == \"number\" \u0026\u0026 typeof o11.y == \"number\" ? { x: o11.x, y: o11.y } : undefined, r9 = typeof e60.pcb_via_pair_net_relation == \"string\" ? e60.pcb_via_pair_net_relation : undefined;\n if (n10.length !== 0 \u0026\u0026 i8 \u0026\u0026 r9)\n return `pcb_via_clearance_error:${JSON.stringify({ traceIds: n10, center: i8, netRelation: r9 })}`;\n })(e54, t4);\n for (const o11 of Rie) {\n const i8 = e54[o11];\n if (typeof i8 == \"string\")\n return `${n8}:${Tie(i8, t4)}`;\n }\n const o10 = Object.fromEntries(Object.entries(e54).filter(([e60, t10]) =\u003e (e60.endsWith(\"_id\") || e60.endsWith(\"_ids\")) \u0026\u0026 (typeof t10 == \"string\" || Array.isArray(t10))).sort(([e60], [t10]) =\u003e e60.localeCompare(t10)).map(([e60, n10]) =\u003e [e60, typeof n10 == \"string\" ? Tie(n10, t4) : n10]));\n return `${n8}:${JSON.stringify(o10)}`;\n};\nvar Aie = ({ errors: e54, baselineErrors: t4, originalTraceIdByPreparedTraceId: n8 = new Map }) =\u003e {\n const o10 = new Set(t4.filter((e60) =\u003e !((e61) =\u003e typeof e61.pcb_trace_error_id == \"string\" \u0026\u0026 e61.pcb_trace_error_id.startsWith(\"missing_connection_\"))(e60)).map((e60) =\u003e Eie(e60, new Map)));\n return o10.delete(undefined), e54.filter((e60) =\u003e {\n const t10 = Eie(e60, n8);\n return t10 === undefined || !o10.has(t10);\n });\n};\nvar Oie = 1.5;\nvar kie = ({ errorsWithCenters: e54, traces: t4, layerCount: n8, defaultViaDiameter: o10, connMap: i8 }) =\u003e {\n const r9 = ((e60) =\u003e e60.flatMap((e61) =\u003e {\n if (e61.type !== \"pcb_trace_error\" || !Array.isArray(e61.pcb_port_ids) || e61.pcb_port_ids.length \u003c 4)\n return [];\n const t10 = e61.center;\n return t10 \u0026\u0026 typeof t10 == \"object\" \u0026\u0026 \"x\" in t10 \u0026\u0026 \"y\" in t10 \u0026\u0026 typeof t10.x == \"number\" \u0026\u0026 typeof t10.y == \"number\" ? [{ x: t10.x, y: t10.y }] : [];\n }))(e54), s7 = new Set;\n for (let e60 = 0;e60 \u003c t4.length; e60++) {\n const a9 = t4[e60], c5 = Vne(a9, e60, n8, o10, i8);\n r9.some((e61) =\u003e c5.some((t10) =\u003e {\n const n10 = t10.route.map((e63) =\u003e e63.x), o11 = t10.route.map((e63) =\u003e e63.y);\n return Math.min(...n10) \u003c= e61.x + Oie \u0026\u0026 Math.max(...n10) \u003e= e61.x - Oie \u0026\u0026 Math.min(...o11) \u003c= e61.y + Oie \u0026\u0026 Math.max(...o11) \u003e= e61.y - Oie;\n })) \u0026\u0026 s7.add(a9.pcb_trace_id);\n }\n return s7;\n};\nvar Die = ({ routes: e54, otherHdRoutes: t4, obstacles: n8, colorMap: o10, layerCount: i8, connMap: r9 }) =\u003e {\n const s7 = hne([...e54, ...t4], r9), a9 = new PF({ inputHdRoutes: e54, otherHdRoutes: t4, netByConnectionName: s7, obstacles: n8, colorMap: o10, layerCount: i8, connMap: r9 });\n if (a9.solve(), a9.failed)\n throw new Error(`Pipeline9 could not merge movable preloaded vias: ${a9.error ?? \"unknown error\"}`);\n return a9.getMergedViaHdRoutes() ?? e54;\n};\nvar Lie = ({ errors: e54, circuitJson: t4, newTraceIds: n8 }) =\u003e {\n const o10 = new Map(t4.flatMap((e60) =\u003e e60.type === \"pcb_via\" \u0026\u0026 typeof e60.pcb_via_id == \"string\" \u0026\u0026 typeof e60.pcb_trace_id == \"string\" ? [[e60.pcb_via_id, e60.pcb_trace_id]] : []));\n return e54.map((e60) =\u003e {\n const t10 = typeof e60.pcb_trace_id == \"string\" ? e60.pcb_trace_id : undefined, i8 = Array.isArray(e60.pcb_trace_ids) ? e60.pcb_trace_ids.filter((e61) =\u003e typeof e61 == \"string\") : [], r9 = [...typeof e60.pcb_via_id == \"string\" ? [e60.pcb_via_id] : [], ...Array.isArray(e60.pcb_via_ids) ? e60.pcb_via_ids.filter((e61) =\u003e typeof e61 == \"string\") : []].filter((e61, t11, n10) =\u003e n10.indexOf(e61) === t11);\n if (t10 \u0026\u0026 typeof e60.pcb_trace_error_id == \"string\") {\n const s9 = `overlap_${t10}_`, a10 = e60.pcb_trace_error_id.startsWith(s9) ? e60.pcb_trace_error_id.slice(s9.length) : undefined, c9 = a10 !== undefined \u0026\u0026 (r9.includes(a10) || o10.has(a10) \u0026\u0026 !i8.includes(a10)), l5 = i8.find((e61) =\u003e e61 !== t10 \u0026\u0026 n8.has(e61)) ?? (a10 \u0026\u0026 !c9 ? a10 : undefined);\n if (!n8.has(t10) \u0026\u0026 r9.length === 0 \u0026\u0026 l5 \u0026\u0026 n8.has(l5)) {\n const n10 = [l5, t10, ...i8].filter((e61, t11, n11) =\u003e n11.indexOf(e61) === t11);\n return { ...e60, pcb_trace_id: l5, pcb_trace_ids: n10, pcb_trace_error_id: `overlap_${l5}_${t10}` };\n }\n }\n const s7 = r9.flatMap((e61) =\u003e {\n const t11 = o10.get(e61);\n return t11 ? [t11] : [];\n }).filter((e61, t11, n10) =\u003e n10.indexOf(e61) === t11), a9 = s7.length \u003e 0 ? s7 : i8.filter((e61) =\u003e e61 !== t10), c5 = a9.find((e61) =\u003e n8.has(e61));\n if (c5 \u0026\u0026 (!t10 || !n8.has(t10))) {\n const n10 = [c5, ...t10 ? [t10] : [], ...i8, ...a9].filter((e61, t11, n11) =\u003e n11.indexOf(e61) === t11);\n return { ...e60, pcb_trace_id: c5, pcb_trace_ids: n10, pcb_via_id: r9[0], pcb_via_ids: r9 };\n }\n if (r9.length \u003e 0) {\n const n10 = [...t10 ? [t10] : [], ...i8, ...a9].filter((e61, t11, n11) =\u003e n11.indexOf(e61) === t11);\n return { ...e60, pcb_trace_ids: n10, pcb_via_id: r9[0], pcb_via_ids: r9 };\n }\n return e60;\n });\n};\nvar zie = 0.000000001;\nvar Bie = (e54) =\u003e {\n const t4 = new Set, n8 = [];\n for (const o10 of e54)\n for (const e60 of o10.route) {\n if (e60.route_type !== \"via\")\n continue;\n const i8 = `${e60.x},${e60.y},${e60.from_layer},${e60.to_layer}`;\n t4.has(i8) || (t4.add(i8), n8.push({ type: \"pcb_via\", pcb_via_id: `via_${n8.length}`, pcb_trace_id: o10.pcb_trace_id }));\n }\n return n8;\n};\nvar Fie = ({ errors: e54, circuitJson: t4, evaluatedTraceIds: n8 }) =\u003e {\n const o10 = new Map(t4.flatMap((e60) =\u003e e60.type === \"pcb_via\" \u0026\u0026 typeof e60.pcb_via_id == \"string\" \u0026\u0026 typeof e60.pcb_trace_id == \"string\" ? [[e60.pcb_via_id, e60.pcb_trace_id]] : []));\n return e54.map((e60) =\u003e {\n const t10 = [...typeof e60.pcb_via_id == \"string\" ? [e60.pcb_via_id] : [], ...Array.isArray(e60.pcb_via_ids) ? e60.pcb_via_ids.filter((e61) =\u003e typeof e61 == \"string\") : []], i8 = typeof e60.pcb_trace_id == \"string\" ? e60.pcb_trace_id : undefined, r9 = i8 ? `overlap_${i8}_` : undefined, s7 = r9 \u0026\u0026 typeof e60.pcb_trace_error_id == \"string\" \u0026\u0026 e60.pcb_trace_error_id.startsWith(r9) ? e60.pcb_trace_error_id.slice(r9.length) : undefined, a9 = typeof e60.pcb_trace_error_id == \"string\" ? e60.pcb_trace_error_id.match(/_(via_\\d+)$/)?.[1] : undefined, c5 = t10.length !== 0 || !a9 || !o10.has(a9) || s7 \u0026\u0026 n8.has(s7) ? undefined : a9, l5 = [...t10, ...c5 ? [c5] : []].filter((e61, t11, n10) =\u003e n10.indexOf(e61) === t11), h5 = [...typeof e60.pcb_trace_id == \"string\" ? [e60.pcb_trace_id] : [], ...Array.isArray(e60.pcb_trace_ids) ? e60.pcb_trace_ids.filter((e61) =\u003e typeof e61 == \"string\") : [], ...l5.flatMap((e61) =\u003e {\n const t11 = o10.get(e61);\n return t11 ? [t11] : [];\n })].filter((e61, t11, n10) =\u003e n10.indexOf(e61) === t11);\n return { ...e60, ...l5.length \u003e 0 ? { pcb_via_id: l5[0], pcb_via_ids: l5 } : {}, ...l5.length \u003e 0 \u0026\u0026 h5.length \u003e 0 ? { pcb_trace_ids: h5 } : {} };\n });\n};\nvar jie = (e54, t4) =\u003e Math.abs(e54.x - t4.x) \u003c= zie \u0026\u0026 Math.abs(e54.y - t4.y) \u003c= zie \u0026\u0026 e54.z === t4.z;\nvar $ie = ({ trace: e54, sectionGroup: t4, syntheticConnectionName: n8, connMap: o10 }) =\u003e {\n const i8 = t4.routes;\n if (i8.length === 0)\n throw new Error(`Pipeline9 cannot exactly repair empty preloaded section for trace \"${e54.pcb_trace_id}\"`);\n const r9 = [];\n for (const t10 of i8) {\n if (r9.length === 0) {\n r9.push(...t10.route);\n continue;\n }\n const n10 = r9.at(-1);\n if (t10.route[0] \u0026\u0026 jie(n10, t10.route[0]))\n r9.push(...t10.route.slice(1));\n else {\n if (!t10.route.at(-1) || !jie(n10, t10.route.at(-1)))\n throw new Error(`Pipeline9 cannot reconnect preloaded trace \"${e54.pcb_trace_id}\" for exact repair`);\n r9.push(...t10.route.slice(0, -1).reverse());\n }\n }\n const s7 = t4.routePositionStart === 0, a9 = t4.routePositionEnd === e54.route.length - 1, c5 = s7 ? e54.connectsTo?.[0] : null, l5 = a9 ? e54.connectsTo?.at(-1) : null;\n return c5 \u0026\u0026 r9[0] \u0026\u0026 (r9[0] = { ...r9[0], pcb_port_id: c5 }), l5 \u0026\u0026 r9.at(-1) \u0026\u0026 (r9[r9.length - 1] = { ...r9.at(-1), pcb_port_id: l5 }), { connectionName: n8, rootConnectionName: o10.getNetConnectedToId(e54.connection_name) ?? e54.connection_name, traceThickness: Math.max(...i8.map((e60) =\u003e e60.traceThickness)), viaDiameter: Math.max(...i8.map((e60) =\u003e e60.viaDiameter)), route: r9, vias: r9.slice(0, -1).flatMap((e60, t10) =\u003e {\n const n10 = r9[t10 + 1];\n return e60.z !== n10.z \u0026\u0026 (o11 = e60, i9 = n10, Math.abs(o11.x - i9.x) \u003c= zie \u0026\u0026 Math.abs(o11.y - i9.y) \u003c= zie) ? [{ x: n10.x, y: n10.y }] : [];\n var o11, i9;\n }) };\n};\nvar Yie = ({ trace: e54, traceIndex: t4, layerCount: n8, defaultViaDiameter: o10, connMap: i8 }) =\u003e {\n const r9 = e54.route.flatMap((e60, t10) =\u003e e60.route_type === \"through_obstacle\" ? [t10] : []), s7 = new Map, a9 = Vne(e54, t4, n8, o10, i8);\n for (const t10 of a9) {\n const { preloadedRoutePositionStart: n10, preloadedRoutePositionEnd: o11 } = t10;\n if (n10 === undefined || o11 === undefined)\n throw new Error(`Pipeline9 preloaded trace section is missing route positions for \"${e54.pcb_trace_id}\"`);\n if (e54.route[n10]?.route_type === \"through_obstacle\")\n continue;\n const i9 = r9.filter((e60) =\u003e e60 \u003c n10).length, a10 = s7.get(i9) ?? { routePositionStart: n10, routePositionEnd: o11, routes: [] };\n a10.routePositionStart = Math.min(a10.routePositionStart, n10), a10.routePositionEnd = Math.max(a10.routePositionEnd, o11), a10.routes.push(t10), s7.set(i9, a10);\n }\n return [...s7.values()];\n};\nvar Xie = (e54, t4) =\u003e e54.map((e60) =\u003e {\n const n8 = Array.isArray(e60.pcb_trace_ids) ? e60.pcb_trace_ids.filter((e61) =\u003e typeof e61 == \"string\") : [], o10 = typeof e60.pcb_trace_id == \"string\" ? e60.pcb_trace_id : undefined, i8 = o10 ? `overlap_${o10}_` : undefined, r9 = i8 \u0026\u0026 typeof e60.pcb_trace_error_id == \"string\" \u0026\u0026 e60.pcb_trace_error_id.startsWith(i8) ? e60.pcb_trace_error_id.slice(i8.length) : undefined, s7 = [...typeof e60.pcb_via_id == \"string\" ? [e60.pcb_via_id] : [], ...Array.isArray(e60.pcb_via_ids) ? e60.pcb_via_ids.filter((e61) =\u003e typeof e61 == \"string\") : []], a9 = r9 !== undefined \u0026\u0026 s7.includes(r9), c5 = [o10, ...n8, a9 ? undefined : r9].filter((e61) =\u003e typeof e61 == \"string\"), l5 = new Map;\n for (const e61 of c5) {\n const n10 = t4.get(e61) ?? e61, o11 = l5.get(n10) ?? new Set;\n o11.add(e61), l5.set(n10, o11);\n }\n const h5 = [...l5].flatMap(([e61, t10]) =\u003e t10.size \u003e 1 ? [{ solverTraceId: e61, evaluationTraceIds: [...t10] }] : []), d9 = o10 ? t4.get(o10) ?? o10 : undefined, u9 = n8.map((e61) =\u003e t4.get(e61) ?? e61), p9 = r9 ? a9 ? r9 : t4.get(r9) ?? r9 : undefined;\n return d9 !== o10 || u9.some((e61, t10) =\u003e e61 !== n8[t10]) || p9 !== r9 ? { ...e60, ...o10 ? { pcb_trace_id: d9 } : {}, ...Array.isArray(e60.pcb_trace_ids) ? { pcb_trace_ids: u9 } : {}, ...d9 \u0026\u0026 p9 ? { pcb_trace_error_id: `overlap_${d9}_${p9}` } : {}, ...h5.length \u003e 0 ? { __collapsed_trace_participants: h5 } : {} } : e60;\n});\nvar Hie = (e54, t4) =\u003e {\n const n8 = e54.hdRoute.route[0], o10 = e54.hdRoute.route.at(-1);\n return { name: e54.syntheticConnectionName, rootConnectionName: e54.hdRoute.rootConnectionName, __netConnectionName: e54.originalTrace.connection_name, nominalTraceWidth: e54.hdRoute.traceThickness, pointsToConnect: [{ x: n8.x, y: n8.y, layer: Co(n8.z, t4), pointId: `${e54.syntheticConnectionName}:start` }, { x: o10.x, y: o10.y, layer: Co(o10.z, t4), pointId: `${e54.syntheticConnectionName}:end` }] };\n};\nvar Vie = ({ originalTrace: e54, repairedSections: t4 }) =\u003e {\n const n8 = [];\n let o10 = 0;\n for (const i8 of [...t4].sort((e60, t10) =\u003e e60.routePositionStart - t10.routePositionStart)) {\n if (i8.routePositionStart \u003c o10)\n throw new Error(`Pipeline9 found overlapping repaired sections for preloaded trace \"${e54.pcb_trace_id}\"`);\n n8.push(...e54.route.slice(o10, i8.routePositionStart), ...i8.route), o10 = i8.routePositionEnd + 1;\n }\n return n8.push(...e54.route.slice(o10)), { ...e54, __replaces_pcb_trace_id: e54.pcb_trace_id, route: n8 };\n};\nvar Wie = class extends ni {\n params;\n inputNewHdRoutes;\n inputUpdatedPreloadedTraces;\n movablePreloadedSections;\n fixedPreloadedObstacleRoutes;\n syntheticConnectionNames;\n exactRepairSolver;\n traceContactRepairSolver;\n traceContactGuard;\n traceContactInputHdRoutes;\n exactRepairParams;\n clearanceProjectionSolver;\n drcEvaluator;\n cachedReferenceDrcEvaluator;\n clearancePrecisionDrcEvaluator;\n clearancePrecisionIndexedDrcEvaluator;\n clearanceMarginDrcEvaluator;\n referenceDrcValidationCount = 0;\n referenceDrcFalseNegativeCount = 0;\n indexedDrcEvaluationCount = 0;\n indexedDrcCacheHitCount = 0;\n indexedDrcEvaluationTimeMs = 0;\n indexedDrcCandidateCache = new Map;\n combinedOutput;\n currentPipelineStepIndex = 0;\n regionalB01Params;\n boundedRegionalParams;\n boundedRegionalRepairStartedAt;\n initialBoundedRegionalRepairSolver;\n initialBoundedRegionalRepairStartedAt;\n prioritizeConflictedRoutes;\n pipelineDef = [{ solverName: \"clearanceProjectionSolver\", createSolver: () =\u003e {\n if (!this.exactRepairParams)\n throw new Error(\"Pipeline9 clearance projection is missing its input\");\n return this.clearanceProjectionSolver = new qoe({ originalSrj: this.params.originalSrj, routes: this.exactRepairParams.hdRoutes, drcEvaluator: this.cachedReferenceDrcEvaluator }), this.clearanceProjectionSolver;\n }, onSolved: () =\u003e {} }, { solverName: \"initialBoundedRegionalRepairSolver\", createSolver: () =\u003e {\n if (!this.exactRepairParams || !this.cachedReferenceDrcEvaluator)\n throw new Error(\"Pipeline9 initial regional repair is missing its input\");\n return this.initialBoundedRegionalRepairStartedAt = performance.now(), this.initialBoundedRegionalRepairSolver = new _ie({ connMap: this.params.connMap, originalSrj: { ...this.params.originalSrj, connections: [...this.params.originalSrj.connections, ...this.params.newConnections] }, routes: this.clearanceProjectionSolver?.getOutput() ?? this.exactRepairParams.hdRoutes, viaHoleDiameter: this.params.defaultViaHoleDiameter, syntheticConnectionNames: this.syntheticConnectionNames, drcEvaluator: this.cachedReferenceDrcEvaluator, prioritizeConflictedRoutes: this.prioritizeConflictedRoutes, budget: Qoe(this.exactRepairParams.hdRoutes.length, this.stats.initialJointDrcIssueCount, this.params.effort) }), this.initialBoundedRegionalRepairSolver;\n }, onSolved: () =\u003e this.finishInitialBoundedRegionalRepair() }, { solverName: \"exactRepairSolver\", createSolver: () =\u003e {\n if (!this.exactRepairParams)\n throw new Error(\"Pipeline9 exact repair stage is missing its input\");\n return this.exactRepairSolver = new LN({ ...this.exactRepairParams, hdRoutes: this.clearanceProjectionSolver?.getOutput() ?? this.exactRepairParams.hdRoutes }), this.exactRepairSolver;\n }, onSolved: () =\u003e this.finishExactRepair() }, { solverName: \"regionalB01RepairSolver\", createSolver: () =\u003e {\n if (!this.regionalB01Params)\n throw new Error(\"Pipeline9 regional B01 stage is missing its input\");\n return this.regionalB01RepairSolver = new mie(this.regionalB01Params), this.regionalB01RepairSolver;\n }, onSolved: () =\u003e this.finishRegionalB01Repair() }, { solverName: \"boundedRegionalRepairSolver\", createSolver: () =\u003e {\n if (!this.boundedRegionalParams)\n throw new Error(\"Pipeline9 bounded regional stage is missing its input\");\n return this.boundedRegionalRepairStartedAt = performance.now(), this.boundedRegionalRepairSolver = new _ie(this.boundedRegionalParams), this.boundedRegionalRepairSolver;\n }, onSolved: () =\u003e this.finishBoundedRegionalRepair() }];\n boundedRegionalRepairSolver;\n regionalB01RepairSolver;\n cacheIndexedDrcResult(e54, t4) {\n if (this.indexedDrcCandidateCache.size \u003e= 64) {\n const e60 = this.indexedDrcCandidateCache.keys().next().value;\n e60 !== undefined \u0026\u0026 this.indexedDrcCandidateCache.delete(e60);\n }\n this.indexedDrcCandidateCache.set(e54, t4);\n }\n constructor(e54) {\n if (super(), e54.obstacles.some((e60) =\u003e e60.isNonPlatedHole)) {\n const t10 = e54.originalSrj.minTraceToHoleEdgeClearance ?? 0.2;\n e54 = { ...e54, srj: { ...e54.srj, minTraceToHoleEdgeClearance: t10 }, originalSrj: { ...e54.originalSrj, minTraceToHoleEdgeClearance: t10 } };\n }\n this.params = e54, this.inputNewHdRoutes = e54.newHdRoutes, this.inputUpdatedPreloadedTraces = e54.updatedPreloadedTraces;\n const t4 = e54.updatedPreloadedTraces.filter((t10) =\u003e e54.mutatedPreloadedTraceIds.has(t10.pcb_trace_id)), n8 = Ste({ connections: e54.newConnections, originalConnections: e54.originalSrj.connections, layerCount: e54.layerCount, obstacles: e54.obstacles, defaultViaHoleDiameter: e54.defaultViaHoleDiameter, connMap: e54.connMap }), o10 = n8(e54.newHdRoutes), i8 = new Set(o10.map((e60) =\u003e e60.pcb_trace_id)), r9 = (({ originalPreloadedTraces: e60, mutatedPreloadedTraces: t10, newTraces: n10 }) =\u003e {\n const o11 = new Set(n10.map((e61) =\u003e e61.pcb_trace_id)), i9 = new Map(t10.map((e61) =\u003e [e61.pcb_trace_id, e61])), r10 = new Set([...e60.map((e61) =\u003e e61.pcb_trace_id), ...o11]), s9 = new Map;\n return { routedTraces: [...e60.filter((e61) =\u003e o11.has(e61.pcb_trace_id)).map((e61) =\u003e {\n const t11 = i9.get(e61.pcb_trace_id) ?? e61, n11 = `${e61.pcb_trace_id}_preloaded`;\n let o12 = n11, a10 = 2;\n for (;r10.has(o12); )\n o12 = `${n11}_${a10}`, a10 += 1;\n return r10.add(o12), s9.set(o12, e61.pcb_trace_id), { ...t11, pcb_trace_id: o12, __replaces_pcb_trace_id: e61.pcb_trace_id };\n }), ...t10.filter((e61) =\u003e !o11.has(e61.pcb_trace_id)), ...n10], originalPreloadedTraceIdByPreparedTraceId: s9 };\n })({ originalPreloadedTraces: e54.originalSrj.traces ?? [], mutatedPreloadedTraces: t4, newTraces: o10 }), s7 = e54.originalSrj.minTraceToPadEdgeClearance ?? e54.originalSrj.defaultObstacleMargin ?? hR, a9 = dR, c5 = vte(e54.originalSrj), l5 = e54.originalSrj.minViaHoleEdgeToViaHoleEdgeClearance ?? dR, h5 = Gte({ includeBoardClearance: true, inputSrj: e54.originalSrj, srjWithPointPairs: e54.srjWithPointPairs, drcOptions: { traceClearance: s7, viaClearance: l5 } }), d9 = h5([]), u9 = new Set((e54.originalSrj.traces ?? []).map((e60) =\u003e e60.pcb_trace_id)), p9 = Fie({ errors: d9.errors, circuitJson: d9.circuitJson, evaluatedTraceIds: u9 }), m9 = Fie({ errors: d9.errorsWithCenters, circuitJson: d9.circuitJson, evaluatedTraceIds: u9 }), g10 = h5(r9.routedTraces), f10 = new Set(Wte(e54.originalSrj.traces ?? [], r9.routedTraces).map((e60) =\u003e e60.pcb_trace_id)), _5 = Fie({ errors: g10.errors, circuitJson: g10.circuitJson, evaluatedTraceIds: f10 }), y10 = Fie({ errors: g10.errorsWithCenters, circuitJson: g10.circuitJson, evaluatedTraceIds: f10 }), b10 = { ...g10, errors: Aie({ errors: _5, baselineErrors: p9, originalTraceIdByPreparedTraceId: r9.originalPreloadedTraceIdByPreparedTraceId }), errorsWithCenters: Aie({ errors: y10, baselineErrors: m9, originalTraceIdByPreparedTraceId: r9.originalPreloadedTraceIdByPreparedTraceId }) }, x8 = (({ errors: e60, circuitJson: t10 }) =\u003e {\n const n10 = new Map(t10.flatMap((e61) =\u003e e61.type === \"pcb_via\" \u0026\u0026 typeof e61.pcb_via_id == \"string\" \u0026\u0026 typeof e61.pcb_trace_id == \"string\" ? [[e61.pcb_via_id, e61.pcb_trace_id]] : [])), o11 = new Set;\n for (const t11 of e60) {\n const e61 = typeof t11.pcb_trace_id == \"string\" ? t11.pcb_trace_id : undefined, i9 = [...typeof t11.pcb_via_id == \"string\" ? [t11.pcb_via_id] : [], ...Array.isArray(t11.pcb_via_ids) ? t11.pcb_via_ids.filter((e63) =\u003e typeof e63 == \"string\") : []];\n if (typeof t11.pcb_trace_id == \"string\" \u0026\u0026 o11.add(t11.pcb_trace_id), Array.isArray(t11.pcb_trace_ids))\n for (const e63 of t11.pcb_trace_ids)\n typeof e63 == \"string\" \u0026\u0026 o11.add(e63);\n if (typeof t11.pcb_via_id == \"string\") {\n const e63 = n10.get(t11.pcb_via_id);\n e63 \u0026\u0026 o11.add(e63);\n }\n if (Array.isArray(t11.pcb_via_ids))\n for (const e63 of t11.pcb_via_ids) {\n if (typeof e63 != \"string\")\n continue;\n const t12 = n10.get(e63);\n t12 \u0026\u0026 o11.add(t12);\n }\n const r10 = e61 ? `overlap_${e61}_` : undefined;\n if (r10 \u0026\u0026 typeof t11.pcb_trace_error_id == \"string\" \u0026\u0026 t11.pcb_trace_error_id.startsWith(r10)) {\n const e63 = t11.pcb_trace_error_id.slice(r10.length);\n i9.includes(e63) || o11.add(e63);\n }\n }\n return o11;\n })({ errors: b10.errors, circuitJson: b10.circuitJson }), v10 = new Map(e54.updatedPreloadedTraces.map((e60) =\u003e [e60.pcb_trace_id, e60])), I6 = new Set;\n for (const e60 of x8) {\n const t10 = r9.originalPreloadedTraceIdByPreparedTraceId.get(e60);\n t10 \u0026\u0026 v10.has(t10) ? I6.add(t10) : !i8.has(e60) \u0026\u0026 v10.has(e60) \u0026\u0026 I6.add(e60);\n }\n for (const t10 of kie({ errorsWithCenters: b10.errorsWithCenters, traces: e54.updatedPreloadedTraces, layerCount: e54.layerCount, defaultViaDiameter: e54.defaultViaDiameter, connMap: e54.connMap }))\n I6.add(t10);\n this.movablePreloadedSections = [];\n for (const t10 of I6) {\n const n10 = v10.get(t10);\n if (!n10)\n throw new Error(`Pipeline9 cannot find preloaded trace \"${t10}\" selected for exact repair`);\n const o11 = e54.updatedPreloadedTraces.findIndex((e60) =\u003e e60.pcb_trace_id === t10), i9 = Yie({ trace: n10, traceIndex: o11, layerCount: e54.layerCount, defaultViaDiameter: e54.defaultViaDiameter, connMap: e54.connMap });\n for (const [t11, o12] of i9.entries()) {\n const i10 = `pipeline9_preloaded_drc_${this.movablePreloadedSections.length}`;\n this.movablePreloadedSections.push({ originalTrace: n10, originalRoutePositionStart: o12.routePositionStart, originalRoutePositionEnd: o12.routePositionEnd, syntheticConnectionName: i10, evaluationTraceId: `${n10.pcb_trace_id}__pipeline9_section_${t11}`, hdRoute: $ie({ trace: n10, sectionGroup: o12, syntheticConnectionName: i10, connMap: e54.connMap }) });\n }\n }\n this.syntheticConnectionNames = new Set(this.movablePreloadedSections.map((e60) =\u003e e60.syntheticConnectionName));\n const S6 = new Set(this.movablePreloadedSections.map((e60) =\u003e e60.originalTrace.pcb_trace_id));\n this.fixedPreloadedObstacleRoutes = e54.updatedPreloadedTraces.flatMap((t10, n10) =\u003e {\n const o11 = Vne(t10, n10, e54.layerCount, e54.defaultViaDiameter, e54.connMap);\n return S6.has(t10.pcb_trace_id) ? o11.filter((e60) =\u003e {\n const n11 = e60.preloadedRoutePositionStart;\n return n11 !== undefined \u0026\u0026 t10.route[n11]?.route_type === \"through_obstacle\";\n }) : o11;\n });\n const C = new Map;\n for (const [e60, t10] of this.movablePreloadedSections.entries()) {\n const n10 = t10.originalTrace.pcb_trace_id, o11 = C.get(n10) ?? [];\n o11.push(e60), C.set(n10, o11);\n }\n for (const t10 of (({ errors: e60, circuitJson: t11, originalTraceIdByPreparedTraceId: n10 }) =\u003e {\n const o11 = new Map(t11.flatMap((e61) =\u003e e61.type === \"pcb_via\" \u0026\u0026 typeof e61.pcb_via_id == \"string\" \u0026\u0026 typeof e61.pcb_trace_id == \"string\" ? [[e61.pcb_via_id, e61.pcb_trace_id]] : []));\n return e60.flatMap((e61) =\u003e {\n if (e61.type !== \"pcb_via_clearance_error\" || !Array.isArray(e61.pcb_via_ids) || typeof e61.actual_clearance != \"number\" || e61.actual_clearance \u003e= 0)\n return [];\n const t12 = e61.pcb_via_ids.flatMap((e63) =\u003e {\n if (typeof e63 != \"string\")\n return [];\n const t13 = o11.get(e63);\n return t13 ? [n10.get(t13) ?? t13] : [];\n }).filter((e63, t13, n11) =\u003e n11.indexOf(e63) === t13);\n return t12.length \u003e 0 ? [t12] : [];\n });\n })({ errors: b10.errors, circuitJson: b10.circuitJson, originalTraceIdByPreparedTraceId: r9.originalPreloadedTraceIdByPreparedTraceId })) {\n const n10 = t10.flatMap((e60) =\u003e C.get(e60) ?? []).filter((e60, t11, n11) =\u003e n11.indexOf(e60) === t11);\n if (n10.length === 0)\n continue;\n const o11 = new Set(n10), i9 = Die({ routes: n10.map((e60) =\u003e this.movablePreloadedSections[e60].hdRoute), otherHdRoutes: [...e54.newHdRoutes, ...this.fixedPreloadedObstacleRoutes, ...this.movablePreloadedSections.flatMap((e60, t11) =\u003e o11.has(t11) ? [] : [e60.hdRoute])], obstacles: e54.obstacles, colorMap: e54.colorMap, layerCount: e54.layerCount, connMap: e54.connMap });\n for (let e60 = 0;e60 \u003c n10.length; e60++)\n this.movablePreloadedSections[n10[e60]].hdRoute = i9[e60];\n }\n const P = e54.newHdRoutes.length + this.movablePreloadedSections.length, M = b10.errors.length \u003e= 20 \u0026\u0026 P \u003e 120 ? Math.min(1, 120 * Math.max(1, e54.effort) / P) : 1, w = b10.errors.length \u003e= 200 ? M ** 2 : M, N = Math.max(b10.errors.length \u003e= 200 ? 2 : 8, Math.floor(32 * w)), R10 = Math.max(b10.errors.length \u003e= 200 ? 1 : 4, Math.floor(12 * w)), T2 = b10.errors.filter((e60) =\u003e e60.type === \"pcb_trace_error\").length;\n this.prioritizeConflictedRoutes = T2 \u003e b10.errors.length / 2, this.stats = { initialJointDrcIssueCount: b10.errors.length, baselineJointDrcIssueCount: d9.errors.length, initialJointDrcIssueCountByType: b10.errors.reduce((e60, t10) =\u003e {\n const n10 = String(t10.type ?? t10.error_type ?? \"unknown\");\n return e60[n10] = (e60[n10] ?? 0) + 1, e60;\n }, {}), movablePreloadedTraceCount: S6.size, movablePreloadedSectionCount: this.movablePreloadedSections.length, exactRepairConfiguredMaxIterations: N, exactRepairConfiguredViaInPadMaxIterations: N, exactRepairConfiguredBroadMaxIterations: R10 }, this.traceContactInputHdRoutes = structuredClone([...e54.originalNewHdRoutes ?? e54.newHdRoutes, ...this.movablePreloadedSections.map((e60) =\u003e e60.hdRoute)]), this.traceContactGuard = new RN({ srj: e54.srjWithPointPairs, inputRoutes: this.traceContactInputHdRoutes, connMap: e54.connMap });\n const E10 = [...e54.newHdRoutes, ...this.movablePreloadedSections.map((e60) =\u003e e60.hdRoute)];\n if (b10.errors.length === 0 \u0026\u0026 this.traceContactGuard.getNewContactPairs(E10).length === 0)\n return void (this.solved = true);\n const A7 = new Set(this.movablePreloadedSections.map((e60) =\u003e e60.originalTrace.pcb_trace_id)), O10 = t4.filter((e60) =\u003e !A7.has(e60.pcb_trace_id)), k6 = new Map(this.movablePreloadedSections.map((t10) =\u003e [t10.syntheticConnectionName, Hie(t10, e54.layerCount)])), { traces: D9, ...L10 } = e54.srjWithPointPairs, z10 = { ...L10, connections: [...e54.srjWithPointPairs.connections, ...k6.values()] }, B5 = new mb({ ...z10, obstacles: e54.originalSrj.obstacles, minTraceWidth: e54.originalSrj.minTraceWidth, minViaDiameter: e54.originalSrj.minViaDiameter ?? e54.defaultViaDiameter }, { connMap: e54.connMap, traceClearance: s7, viaClearance: a9, viaToPadClearance: c5, includeTraceViaOwnerMetadata: true, spatialCellSize: Math.max(e54.defaultViaDiameter, e54.originalSrj.minTraceWidth) + Math.max(s7, a9) }), F10 = B5.evaluate(e54.originalSrj.traces ?? []), j10 = Bie(e54.originalSrj.traces ?? []), $10 = { ...F10, errors: Fie({ errors: F10.errors, circuitJson: j10, evaluatedTraceIds: u9 }), errorsWithCenters: Fie({ errors: F10.errorsWithCenters, circuitJson: j10, evaluatedTraceIds: u9 }) }, Y10 = new Map, X = (t10) =\u003e {\n const o11 = t10.filter((e60) =\u003e !this.syntheticConnectionNames.has(e60.connectionName)), i9 = n8(o11), r10 = cne(i9, e54.originalSrj.traces ?? []), s9 = new Set, a10 = new Map, c9 = this.movablePreloadedSections.map((n10) =\u003e {\n const o12 = t10.find((e60) =\u003e e60.connectionName === n10.syntheticConnectionName);\n if (!o12)\n throw new Error(`Pipeline9 joint DRC repair lost preloaded section \"${n10.syntheticConnectionName}\"`);\n const i10 = n10.originalTrace.pcb_trace_id;\n a10.set(n10.evaluationTraceId, i10);\n const r11 = !s9.has(i10);\n return s9.add(i10), { ...n10.originalTrace, pcb_trace_id: n10.evaluationTraceId, ...r11 ? { __replaces_pcb_trace_id: i10 } : { __replaces_pcb_trace_id: undefined }, route: Ro(o12, e54.layerCount, { defaultViaHoleDiameter: e54.defaultViaHoleDiameter, obstacles: e54.obstacles, connMap: e54.connMap }) };\n }), l10 = new Map;\n for (let e60 = 0;e60 \u003c i9.length; e60++)\n l10.set(r10[e60].pcb_trace_id, i9[e60].pcb_trace_id);\n for (const e60 of this.movablePreloadedSections)\n l10.set(e60.evaluationTraceId, `${e60.syntheticConnectionName}_0`);\n const h9 = new Set(l10.values()), d10 = [...O10, ...c9, ...r10];\n return { evaluatedTraces: Wte(e54.originalSrj.traces ?? [], d10), movableTraceIds: h9, originalTraceIdByEvaluationTraceId: a10, routedTraces: d10, solverTraceIdByEvaluationTraceId: l10 };\n }, H10 = ({ errors: e60, errorsWithCenters: t10, circuitJson: n10, movableTraceIds: o11, solverTraceIdByEvaluationTraceId: i9 }) =\u003e {\n const r10 = n10.map((e61) =\u003e {\n if (!(\"pcb_trace_id\" in e61) || typeof e61.pcb_trace_id != \"string\")\n return e61;\n const t11 = i9.get(e61.pcb_trace_id);\n return t11 ? { ...e61, pcb_trace_id: t11 } : e61;\n });\n return { errors: Lie({ errors: Xie(e60, i9), circuitJson: r10, newTraceIds: o11 }), errorsWithCenters: Lie({ errors: Xie(t10, i9), circuitJson: r10, newTraceIds: o11 }) };\n }, V10 = { source: ei(e54.originalSrj === e54.srjWithPointPairs ? e54.originalSrj : { ...e54.originalSrj, connections: [...e54.srjWithPointPairs.connections, ...e54.originalSrj.connections] }), route: ei(e54.srjWithPointPairs) }, W4 = Gte({ includeBoardClearance: true, connectivityMaps: V10, inputSrj: e54.originalSrj, srjWithPointPairs: e54.srjWithPointPairs, drcOptions: { traceClearance: s7, viaClearance: l5 } }), G10 = ({ routes: e60, hdRoutes: t10 }, n10 = true) =\u003e {\n const o11 = e60 ?? t10;\n if (!o11)\n throw new Error(\"Pipeline9 reference DRC repair requires HD routes\");\n const i9 = X(o11), r10 = W4(i9.routedTraces, { includeTraceContinuity: n10 }), s9 = new Set(i9.evaluatedTraces.map((e61) =\u003e e61.pcb_trace_id)), a10 = Fie({ errors: r10.errors, circuitJson: r10.circuitJson, evaluatedTraceIds: s9 }), c9 = Fie({ errors: r10.errorsWithCenters, circuitJson: r10.circuitJson, evaluatedTraceIds: s9 }), l10 = Aie({ errors: a10, baselineErrors: p9, originalTraceIdByPreparedTraceId: i9.originalTraceIdByEvaluationTraceId }), h9 = Aie({ errors: c9, baselineErrors: m9, originalTraceIdByPreparedTraceId: i9.originalTraceIdByEvaluationTraceId });\n return H10({ errors: l10, errorsWithCenters: h9, circuitJson: r10.circuitJson, movableTraceIds: i9.movableTraceIds, solverTraceIdByEvaluationTraceId: i9.solverTraceIdByEvaluationTraceId });\n }, U10 = ({ routes: e60, hdRoutes: t10 }) =\u003e {\n const n10 = e60 ?? t10;\n if (!n10)\n throw new Error(\"Pipeline9 cached reference DRC requires HD routes\");\n const o11 = JSON.stringify(n10), i9 = Y10.get(o11);\n if (i9 !== undefined)\n return i9;\n this.referenceDrcValidationCount += 1;\n const r10 = G10({ traces: [], routes: n10, hdRoutes: n10 });\n if (Y10.size \u003e= 2) {\n const e61 = Y10.keys().next().value;\n e61 !== undefined \u0026\u0026 Y10.delete(e61);\n }\n return Y10.set(o11, r10), r10;\n };\n U10.inputMode = \"routes-only\", this.cachedReferenceDrcEvaluator = U10, this.clearancePrecisionDrcEvaluator = ({ routes: e60, hdRoutes: t10 }) =\u003e G10({ traces: [], routes: e60, hdRoutes: t10 }, false);\n const Z6 = (t10) =\u003e {\n const n10 = X(t10);\n return sR(e54.srjWithPointPairs, n10.routedTraces, { minTraceWidth: e54.originalSrj.minTraceWidth, minViaDiameter: e54.originalSrj.minViaDiameter, originalSrj: e54.originalSrj, includeOriginalConnections: true, connectivityMaps: V10 });\n };\n let q10;\n this.clearanceMarginDrcEvaluator = (e60, t10, n10) =\u003e (q10?.routes !== n10 \u0026\u0026 (q10 = { routes: n10, circuitJson: Z6(n10) }), (({ circuitJson: e61, originalCircuitJson: t11, targets: n11 }) =\u003e {\n const o11 = new Map(e61.filter((e63) =\u003e e63.type === \"pcb_trace\").map((e63) =\u003e [e63.pcb_trace_id, e63])), i9 = new Map(t11.filter((e63) =\u003e e63.type === \"pcb_trace\").map((e63) =\u003e [e63.pcb_trace_id, e63])), r10 = e61.filter((e63) =\u003e e63.type === \"pcb_via\"), s9 = new Map;\n for (const t12 of e61)\n t12.type === \"pcb_via\" ? s9.set(t12.pcb_via_id, t12) : t12.type === \"pcb_smtpad\" ? s9.set(t12.pcb_smtpad_id, t12) : t12.type === \"pcb_plated_hole\" \u0026\u0026 s9.set(t12.pcb_plated_hole_id, t12);\n const a10 = [];\n for (const e63 of n11) {\n const n12 = e63.type === \"pcb_via_trace_clearance_error\", c9 = n12 ? e63.pcb_via_id : e63.pcb_pad_id;\n if (!n12 \u0026\u0026 e63.type !== \"pcb_pad_trace_clearance_error\" || typeof e63.pcb_trace_id != \"string\" || typeof c9 != \"string\" || typeof e63.minimum_clearance != \"number\" || !Number.isFinite(e63.minimum_clearance) || e63.minimum_clearance \u003c= 0)\n throw new Error(\"Pipeline9 clearance margin requires a valid target pair\");\n const l10 = i9.get(e63.pcb_trace_id), h9 = t11.find((e64) =\u003e n12 ? e64.type === \"pcb_via\" \u0026\u0026 e64.pcb_via_id === c9 : e64.type === \"pcb_smtpad\" \u0026\u0026 e64.pcb_smtpad_id === c9 || e64.type === \"pcb_plated_hole\" \u0026\u0026 e64.pcb_plated_hole_id === c9);\n if (!l10 || !h9)\n throw new Error(`Pipeline9 clearance margin has no original target ${c9}/${e63.pcb_trace_id}`);\n const d10 = o11.get(e63.pcb_trace_id);\n let u10 = s9.get(c9);\n if (n12) {\n if (h9.type !== \"pcb_via\" || typeof h9.pcb_trace_id != \"string\")\n throw new Error(\"Pipeline9 clearance margin requires the original via owner\");\n const e64 = i9.get(h9.pcb_trace_id);\n if (!e64)\n throw new Error(\"Pipeline9 clearance margin lost the original via owner\");\n const t12 = e64.route.filter((e65) =\u003e e65.route_type === \"via\"), n13 = t12.map((e65, t13) =\u003e ({ segment: e65, index: t13 })).filter(({ segment: e65 }) =\u003e e65.x === h9.x \u0026\u0026 e65.y === h9.y \u0026\u0026 h9.layers.includes(e65.from_layer) \u0026\u0026 h9.layers.includes(e65.to_layer)).filter(({ segment: e65 }, t13, n14) =\u003e n14.findIndex((t14) =\u003e t14.segment.from_layer === e65.from_layer \u0026\u0026 t14.segment.to_layer === e65.to_layer) === t13);\n if (n13.length === 0)\n throw new Error(\"Pipeline9 clearance margin lost the original via transition\");\n if (n13.length !== 1)\n return { status: \"unsupported-identity\" };\n const s10 = n13[0].index, a11 = o11.get(h9.pcb_trace_id), c10 = a11?.route.filter((e65) =\u003e e65.route_type === \"via\");\n if (!c10 || c10.length !== t12.length || c10.some((e65, n14) =\u003e e65.from_layer !== t12[n14].from_layer || e65.to_layer !== t12[n14].to_layer))\n return { status: \"unsupported-identity\" };\n const l11 = c10[s10];\n u10 = r10.filter((e65) =\u003e e65.x === l11.x \u0026\u0026 e65.y === l11.y \u0026\u0026 e65.layers.join() === h9.layers.join()).reduce((e65, t13) =\u003e !e65 || t13.outer_diameter \u003e e65.outer_diameter ? t13 : e65, undefined);\n }\n if (!(d10 \u0026\u0026 u10 \u0026\u0026 (\"x\" in u10) \u0026\u0026 (\"y\" in u10)))\n return { status: \"unsupported-identity\" };\n const p10 = [d10, u10], m10 = dz([u10], { traceClearance: e63.minimum_clearance + 1 })(p10, Qo(p10)), g11 = n12 ? m10.viaErrors : m10.padErrors, f11 = e63.minimum_clearance + Xoe;\n for (const t12 of g11) {\n const n13 = t12.actual_clearance;\n if (typeof n13 != \"number\" || !Number.isFinite(n13))\n throw new Error(\"Pipeline9 clearance margin requires a finite measurement\");\n n13 \u003e= f11 || a10.push({ ...e63, ...u10.type === \"pcb_via\" ? { pcb_via_id: u10.pcb_via_id, pcb_via_ids: [u10.pcb_via_id] } : {}, actual_clearance: n13, minimum_clearance: f11, center: { x: u10.x, y: u10.y } });\n }\n }\n return { status: \"measured\", errors: a10 };\n })({ circuitJson: Z6(e60), originalCircuitJson: q10.circuitJson, targets: t10 })), this.clearancePrecisionIndexedDrcEvaluator = ({ routes: e60, hdRoutes: t10 }) =\u003e {\n const n10 = e60 ?? t10;\n if (!n10)\n throw new Error(\"Pipeline9 clearance ranking requires HD routes\");\n const o11 = X(n10);\n return B5.evaluate(o11.evaluatedTraces);\n };\n const J10 = ({ routes: e60, hdRoutes: t10 }) =\u003e {\n const n10 = e60 ?? t10;\n if (!n10)\n throw new Error(\"Pipeline9 joint DRC repair requires HD routes\");\n const o11 = JSON.stringify(n10), i9 = this.indexedDrcCandidateCache.get(o11);\n if (i9 !== undefined)\n return this.indexedDrcCacheHitCount += 1, i9;\n const r10 = performance.now();\n this.indexedDrcEvaluationCount += 1;\n const s9 = X(n10), a10 = B5.evaluate(s9.evaluatedTraces), c9 = Bie(s9.evaluatedTraces), l10 = new Set(s9.evaluatedTraces.map((e61) =\u003e e61.pcb_trace_id)), h9 = Fie({ errors: a10.errors, circuitJson: c9, evaluatedTraceIds: l10 }), d10 = Fie({ errors: a10.errorsWithCenters, circuitJson: c9, evaluatedTraceIds: l10 }), u10 = Aie({ errors: h9, baselineErrors: $10.errors, originalTraceIdByPreparedTraceId: s9.originalTraceIdByEvaluationTraceId }), p10 = Aie({ errors: d10, baselineErrors: $10.errorsWithCenters, originalTraceIdByPreparedTraceId: s9.originalTraceIdByEvaluationTraceId });\n if (u10.length === 0) {\n const e61 = this.referenceDrcValidationCount, t11 = U10({ traces: [], routes: n10, hdRoutes: n10 }), i10 = Array.isArray(t11) ? t11 : t11.errors;\n return this.referenceDrcValidationCount \u003e e61 \u0026\u0026 i10.length \u003e 0 \u0026\u0026 (this.referenceDrcFalseNegativeCount += 1), this.indexedDrcEvaluationTimeMs += performance.now() - r10, this.cacheIndexedDrcResult(o11, t11), t11;\n }\n const m10 = H10({ errors: u10, errorsWithCenters: p10, circuitJson: c9, movableTraceIds: s9.movableTraceIds, solverTraceIdByEvaluationTraceId: s9.solverTraceIdByEvaluationTraceId });\n return this.indexedDrcEvaluationTimeMs += performance.now() - r10, this.cacheIndexedDrcResult(o11, m10), m10;\n };\n if (J10.inputMode = \"routes-only\", this.drcEvaluator = J10, this.exactRepairParams = { srj: z10, hdRoutes: [...e54.newHdRoutes, ...this.movablePreloadedSections.map((e60) =\u003e e60.hdRoute)], connMap: e54.connMap, effort: e54.effort, viaHoleDiameter: e54.defaultViaHoleDiameter, drcEvaluator: J10, viaInPadDrcEvaluator: J10, maxIterations: N, enableBroadFallback: false, enableLargeBoardBroadFallback: false, enableTargetedErrorSweep: true, enableTraceViaOwnerTargeting: true, enablePostSolveClearanceRelaxation: false, deferTraceContactGuard: true, prioritizeMultipleTraceContactRepair: true, enableSafeTraceLayerMoves: true, enableViaInPadLayerMoves: e54.originalSrj.allowViaInPad ?? false, viaInPadMaxIterations: N, broadMaxIterations: R10, broadPassMultiplier: 3 * w }, b10.errors.length === 0)\n return this.combinedOutput = E10, void this.finishWithTraceContactCheck();\n (e54.updatedPreloadedTraces.length \u003e 0 || (e54.originalSrj.traces?.length ?? 0) \u003e 0) \u0026\u0026 this.pipelineDef.splice(1, 1), (e54.updatedPreloadedTraces.length \u003e 0 || !e54.obstacles.some((e60) =\u003e e60.isNonPlatedHole)) \u0026\u0026 (this.currentPipelineStepIndex = 1), this.activeSubSolver = this.pipelineDef[this.currentPipelineStepIndex].createSolver(), this.MAX_ITERATIONS = this.activeSubSolver.MAX_ITERATIONS + 1;\n }\n getSolverName() {\n return \"Pipeline9JointDrcRepairSolver\";\n }\n _step() {\n if (this.traceContactRepairSolver) {\n const e60 = this.traceContactRepairSolver;\n if (e60.step(), e60.failed)\n throw new Error(`Pipeline9 trace contact repair failed: ${e60.error}`);\n if (!e60.solved)\n return;\n if (this.combinedOutput = e60.getOutput(), this.traceContactGuard.getNewContactPairs(this.combinedOutput).length \u003e 0)\n throw new Error(\"Pipeline9 trace contact repair published a new short\");\n return this.stats = { ...this.stats, ...e60.stats }, this.activeSubSolver = null, void (this.solved = true);\n }\n const e54 = this.pipelineDef[this.currentPipelineStepIndex];\n if (e54) {\n if (this.activeSubSolver) {\n const t4 = this.activeSubSolver;\n if (t4.step(), this.MAX_ITERATIONS = Math.max(this.MAX_ITERATIONS, this.iterations + t4.MAX_ITERATIONS - t4.iterations + 2), t4.failed)\n this.failed = true, this.error = t4.error, this.activeSubSolver = null;\n else if (t4.solved) {\n if (e54.onSolved(), this.traceContactRepairSolver)\n return void (this.activeSubSolver = this.traceContactRepairSolver);\n this.activeSubSolver = null, this.currentPipelineStepIndex++;\n }\n return;\n }\n this.activeSubSolver = e54.createSolver(), this.MAX_ITERATIONS = Math.max(this.MAX_ITERATIONS, this.iterations + this.activeSubSolver.MAX_ITERATIONS + 2);\n } else\n this.solved = true;\n }\n computeProgress() {\n return this.solved ? 1 : Math.max(this.progress, (this.currentPipelineStepIndex + (this.activeSubSolver?.progress ?? 0)) / this.pipelineDef.length);\n }\n getCurrentPhase() {\n return this.pipelineDef[this.currentPipelineStepIndex]?.solverName ?? \"none\";\n }\n finishInitialBoundedRegionalRepair() {\n if (!this.initialBoundedRegionalRepairSolver?.solved || this.initialBoundedRegionalRepairStartedAt === undefined || !this.cachedReferenceDrcEvaluator)\n throw new Error(\"Pipeline9 initial regional repair is not complete\");\n const e54 = this.initialBoundedRegionalRepairSolver.getResult();\n if (this.stats = { ...this.stats, initialBoundedRegionalRepairAccepted: false, initialBoundedRegionalRepairAttemptedRegionCount: e54.attemptedRegionCount, initialBoundedRegionalRepairAcceptedRegionCount: e54.acceptedRegionCount, initialBoundedRegionalRepairCandidateAttemptCount: e54.candidateAttemptCount, initialBoundedRegionalRepairPathSearchNodeCount: e54.pathSearchNodeCount, initialBoundedRegionalRepairReferenceValidationCount: e54.referenceValidationCount, initialBoundedRegionalRepairPublishedDrcIssueCount: e54.publishedDrcIssueCount, initialBoundedRegionalRepairTimeMs: performance.now() - this.initialBoundedRegionalRepairStartedAt }, e54.publishedDrcIssueCount !== 0)\n return;\n const t4 = this.cachedReferenceDrcEvaluator({ traces: [], routes: e54.routes, hdRoutes: e54.routes });\n if ((Array.isArray(t4) ? t4 : t4.errors).length !== 0)\n throw new Error(\"Pipeline9 initial regional repair lost its zero-DRC validation\");\n this.combinedOutput = e54.routes, this.stats = { ...this.stats, finalDrcIssueCount: 0, initialBoundedRegionalRepairAccepted: true, boundedRegionalRepairMaxRegions: this.initialBoundedRegionalRepairSolver.budget.maxRegions, boundedRegionalRepairMaxCandidateAttempts: this.initialBoundedRegionalRepairSolver.budget.maxCandidateAttempts, boundedRegionalRepairMaxPathSearchNodes: this.initialBoundedRegionalRepairSolver.budget.maxPathSearchNodes, boundedRegionalRepairAttemptedRegionCount: e54.attemptedRegionCount, boundedRegionalRepairAcceptedRegionCount: e54.acceptedRegionCount, boundedRegionalRepairCandidateAttemptCount: e54.candidateAttemptCount, boundedRegionalRepairPathSearchNodeCount: e54.pathSearchNodeCount, boundedRegionalRepairReferenceValidationCount: e54.referenceValidationCount, boundedRegionalRepairRepaired: e54.repaired, boundedRegionalRepairPublishedDrcIssueCount: e54.publishedDrcIssueCount, initialBoundedRegionalRepairAddedViaCount: Math.max(0, e54.routes.reduce((e60, t10) =\u003e e60 + t10.vias.length, 0) - this.inputNewHdRoutes.reduce((e60, t10) =\u003e e60 + t10.vias.length, 0)), terminalEscapeCandidateCount: 0, terminalEscapeAcceptedCount: 0, regionalB01RepairAttempted: false, regionalB01RepairCandidateSearchCount: 0, regionalB01RepairCandidateSearchBudget: 0, clearancePrecisionCandidateCount: 0, clearancePrecisionCandidateValidationCount: 0, clearancePrecisionReferenceValidationCount: 0, clearancePrecisionRepaired: false, referenceDrcValidationCount: this.referenceDrcValidationCount, referenceDrcFalseNegativeCount: this.referenceDrcFalseNegativeCount, indexedDrcEvaluationCount: this.indexedDrcEvaluationCount, indexedDrcCacheHitCount: this.indexedDrcCacheHitCount, indexedDrcEvaluationTimeMs: this.indexedDrcEvaluationTimeMs, indexedDrcCandidateCacheSize: this.indexedDrcCandidateCache.size, indexedDrcCandidateCacheCapacity: 64 }, this.finishWithTraceContactCheck();\n }\n finishExactRepair() {\n if (!this.exactRepairSolver)\n throw new Error(\"Pipeline9 post-exact repair requires the exact solver\");\n let e54 = this.exactRepairSolver.getOutput();\n const t4 = this.exactRepairSolver.stats.finalDrcIssueCount, n8 = typeof t4 == \"number\" \u0026\u0026 Number.isFinite(t4) \u0026\u0026 t4 \u003e= 0 ? t4 : undefined;\n let o10, i8 = 0, r9 = 0, s7 = 0, a9 = false;\n const c5 = this.cachedReferenceDrcEvaluator({ traces: [], routes: e54, hdRoutes: e54 }), l5 = Array.isArray(c5) ? c5 : c5.errors;\n if (o10 = l5.length, l5.length \u003e 0) {\n const t10 = (({ srj: e60, routes: t11, newConnections: n10, syntheticConnectionNames: o11, connMap: i9, indexedDrcEvaluator: r10, candidateDrcEvaluator: s9, marginDrcEvaluator: a10, drcEvaluator: c9, initialErrors: l10, initialErrorsWithCenters: h9 = l10 }) =\u003e {\n const d10 = { routes: t11, attemptedCandidateCount: 0, candidateValidationCount: 0, referenceValidationCount: 0, repaired: false };\n if ((e60.traces?.length ?? 0) \u003e 0 || o11.size \u003e 0)\n return d10;\n if (l10.length === 0)\n return d10;\n const u9 = Yoe({ routes: t11, newConnections: n10, syntheticConnectionNames: o11 }), p9 = new Map;\n for (const t12 of e60.obstacles)\n for (const e61 of [t12.obstacleId, t12.circuitJsonMetadata?.pcb_smtpad_id, t12.circuitJsonMetadata?.pcb_plated_hole_id, t12.connectedTo[0]])\n typeof e61 == \"string\" \u0026\u0026 p9.set(e61, t12.center);\n const m9 = Woe({ errors: l10, errorsWithCenters: h9, routeIndexByTraceId: u9, padPositionById: p9 });\n if (!m9)\n return d10;\n let g10 = m9;\n const f10 = m9.errors, _5 = m9.errors.map((e61) =\u003e ({ ...e61, minimum_clearance: e61.minimum_clearance + Xoe })), y10 = Voe(_5);\n if (y10 === undefined)\n return d10;\n let b10 = { errors: _5, deficit: y10 }, x8 = t11, v10 = 0, I6 = 0, S6 = 0;\n for (let n11 = 0;n11 \u003c 8; n11++) {\n const n12 = new Map;\n for (const e61 of [...b10.errors, ...g10.errors]) {\n const t12 = JSON.stringify([e61.type, e61.pcb_trace_id, e61.pcb_pad_id, e61.pcb_via_id]);\n n12.set(t12, e61);\n }\n const o12 = [...n12.values()];\n let l11;\n for (const t12 of Hoe) {\n const n13 = AP(x8);\n if (!Ww(e60, n13, o12, u9, t12, i9, true, true, true, false))\n continue;\n const s10 = sw(n13);\n v10++;\n const a11 = r10({ traces: [], routes: s10, hdRoutes: s10 }), c10 = Voe(Array.isArray(a11) ? a11 : a11.errors);\n c10 !== undefined \u0026\u0026 (!l11 || c10 \u003c l11.deficit) \u0026\u0026 (l11 = { routes: s10, deficit: c10 });\n }\n if (!l11)\n break;\n I6++;\n const h10 = s9({ traces: [], routes: l11.routes, hdRoutes: l11.routes }), d11 = Array.isArray(h10) ? h10 : h10.errors, m10 = Woe({ errors: d11, errorsWithCenters: Array.isArray(h10) ? h10 : h10.errorsWithCenters ?? h10.errors, routeIndexByTraceId: u9, padPositionById: p9 });\n if (!m10)\n break;\n const _10 = a10(l11.routes, f10, t11);\n if (_10.status === \"unsupported-identity\")\n break;\n const y11 = _10.errors, C = Woe({ errors: y11, errorsWithCenters: y11, routeIndexByTraceId: u9, padPositionById: p9 });\n if (!C)\n break;\n if (d11.length === 0 \u0026\u0026 y11.length === 0) {\n S6++;\n const e61 = c9({ traces: [], routes: l11.routes, hdRoutes: l11.routes });\n if ((Array.isArray(e61) ? e61 : e61.errors).length === 0)\n return { routes: l11.routes, attemptedCandidateCount: v10, candidateValidationCount: I6, referenceValidationCount: S6, repaired: true };\n break;\n }\n if (m10.deficit + C.deficit \u003e= g10.deficit + b10.deficit - 0.000000001)\n break;\n x8 = l11.routes, g10 = m10, b10 = C;\n }\n return { routes: t11, attemptedCandidateCount: v10, candidateValidationCount: I6, referenceValidationCount: S6, repaired: false };\n })({ srj: this.params.srj, routes: e54, newConnections: this.params.newConnections, syntheticConnectionNames: this.syntheticConnectionNames, connMap: this.params.connMap, indexedDrcEvaluator: this.clearancePrecisionIndexedDrcEvaluator, candidateDrcEvaluator: this.clearancePrecisionDrcEvaluator, marginDrcEvaluator: this.clearanceMarginDrcEvaluator, drcEvaluator: this.cachedReferenceDrcEvaluator, initialErrors: l5, initialErrorsWithCenters: Array.isArray(c5) ? c5 : c5.errorsWithCenters ?? c5.errors });\n i8 = t10.attemptedCandidateCount, r9 = t10.candidateValidationCount, s7 = t10.referenceValidationCount, a9 = t10.repaired, t10.repaired \u0026\u0026 (e54 = t10.routes, o10 = 0);\n }\n if (o10 === 0)\n return this.combinedOutput = e54, this.stats = { ...this.stats, ...this.exactRepairSolver.stats, postExactIndexedDrcIssueCount: n8, postExactReferenceValidationAttempted: true, postExactReferenceDrcIssueCount: 0, postExactReferenceAccepted: true, clearancePrecisionCandidateCount: i8, clearancePrecisionCandidateValidationCount: r9, clearancePrecisionReferenceValidationCount: s7, clearancePrecisionRepaired: a9, boundedRegionalRepairMaxRegions: 0, boundedRegionalRepairMaxCandidateAttempts: 0, boundedRegionalRepairMaxPathSearchNodes: 0, boundedRegionalRepairAttemptedRegionCount: 0, boundedRegionalRepairAcceptedRegionCount: 0, boundedRegionalRepairCandidateAttemptCount: 0, boundedRegionalRepairPathSearchNodeCount: 0, boundedRegionalRepairReferenceValidationCount: 0, boundedRegionalRepairRepaired: false, boundedRegionalRepairTimeMs: 0, regionalB01RepairCandidateCount: 0, regionalB01RepairAcceptedCount: 0, regionalB01RepairFallbackCandidateCount: 0, regionalB01RepairCandidateSearchCount: 0, regionalB01RepairCandidateSearchBudget: 0, regionalB01RepairCandidateSearchBudgetExhausted: false, regionalB01RepairSafeTraceLayerSkippedForBudget: false, regionalB01RepairRemainingDrcIssueCount: 0, regionalB01RepairPreloadEligibleDrcIssueCount: 0, regionalB01RepairAttempted: false, regionalB01RepairTraceIdCount: 0, terminalEscapeCandidateCount: 0, terminalEscapeAcceptedCount: 0, referenceDrcValidationCount: this.referenceDrcValidationCount, referenceDrcFalseNegativeCount: this.referenceDrcFalseNegativeCount, indexedDrcEvaluationCount: this.indexedDrcEvaluationCount, indexedDrcCacheHitCount: this.indexedDrcCacheHitCount, indexedDrcEvaluationTimeMs: this.indexedDrcEvaluationTimeMs, indexedDrcCandidateCacheSize: this.indexedDrcCandidateCache.size, indexedDrcCandidateCacheCapacity: 64 }, void this.finishWithTraceContactCheck();\n const h5 = Nie({ srj: this.params.srj, originalSrj: this.params.originalSrj, routes: e54, newConnections: this.params.newConnections, syntheticConnectionNames: this.syntheticConnectionNames, drcEvaluator: this.drcEvaluator, effort: this.params.effort }), d9 = (({ routes: e60, newConnections: t10, syntheticConnectionNames: n10, fixedPreloadedObstacleRoutes: o11, updatedPreloadedTraces: i9 }) =\u003e {\n const r10 = new Set, s9 = Object.assign(new Set, { collidingFixedTraceIds: r10 }), a10 = Yoe({ routes: e60, newConnections: t10, syntheticConnectionNames: n10 }), c9 = new Set;\n for (const [t11, o12] of a10)\n n10.has(e60[o12].connectionName) ? s9.add(t11) : c9.add(t11);\n for (const e61 of o11) {\n const t11 = i9[e61.preloadedTraceIndex];\n if (!t11)\n throw new Error(`Pipeline9 fixed preload route has invalid trace index ${e61.preloadedTraceIndex}`);\n c9.has(t11.pcb_trace_id) ? r10.add(t11.pcb_trace_id) : s9.add(t11.pcb_trace_id);\n }\n return s9;\n })({ routes: h5.routes, newConnections: this.params.newConnections, syntheticConnectionNames: this.syntheticConnectionNames, fixedPreloadedObstacleRoutes: this.fixedPreloadedObstacleRoutes, updatedPreloadedTraces: this.params.updatedPreloadedTraces });\n this.regionalB01Params = { srj: this.params.srj, routes: h5.routes, fixedObstacleRoutes: this.fixedPreloadedObstacleRoutes, newConnections: this.params.newConnections, syntheticConnectionNames: this.syntheticConnectionNames, drcEvaluator: this.drcEvaluator, initialErrors: h5.remainingErrors, allowTracePairRepair: true, preloadRepairTraceIds: d9, connMap: this.params.connMap, colorMap: this.params.colorMap, viaDiameter: this.params.defaultViaDiameter, traceWidth: this.params.srj.minTraceWidth, obstacleMargin: this.params.srj.defaultObstacleMargin ?? this.params.srj.minTraceToPadEdgeClearance ?? 0.15, effort: this.params.effort }, this.stats = { ...this.stats, ...this.exactRepairSolver.stats, postExactIndexedDrcIssueCount: n8, postExactReferenceValidationAttempted: true, postExactReferenceDrcIssueCount: o10, postExactReferenceAccepted: false, clearancePrecisionCandidateCount: i8, clearancePrecisionCandidateValidationCount: r9, clearancePrecisionReferenceValidationCount: s7, clearancePrecisionRepaired: a9, regionalB01RepairTraceIdCount: d9.size + (d9.collidingFixedTraceIds?.size ?? 0), terminalEscapeCandidateCount: h5.attemptedCandidateCount, terminalEscapeAcceptedCount: h5.acceptedCandidateCount }, this.exactRepairSolver.stats.drcBranchPortfolioStoppedForTraceContacts === true \u0026\u0026 this.traceContactGuard.getNewContactPairs(h5.routes).length \u003e 1 \u0026\u0026 (this.combinedOutput = h5.routes, this.finishWithTraceContactCheck());\n }\n finishRegionalB01Repair() {\n if (!this.regionalB01RepairSolver?.solved)\n throw new Error(\"Pipeline9 regional B01 stage must solve before completion\");\n const e54 = this.regionalB01RepairSolver.getResult(), t4 = this.cachedReferenceDrcEvaluator({ traces: [], routes: e54.routes, hdRoutes: e54.routes }), n8 = Qoe(e54.routes.length, (Array.isArray(t4) ? t4 : t4.errors).length, this.params.effort);\n this.boundedRegionalParams = { connMap: this.params.connMap, originalSrj: { ...this.params.originalSrj, connections: [...this.params.originalSrj.connections, ...this.params.newConnections] }, routes: e54.routes, viaHoleDiameter: this.params.defaultViaHoleDiameter, syntheticConnectionNames: this.syntheticConnectionNames, drcEvaluator: this.cachedReferenceDrcEvaluator, budget: n8 };\n }\n finishBoundedRegionalRepair() {\n if (!this.boundedRegionalRepairSolver?.solved || !this.regionalB01RepairSolver?.solved || !this.boundedRegionalParams?.budget || this.boundedRegionalRepairStartedAt === undefined)\n throw new Error(\"Pipeline9 bounded regional stage is missing its completed inputs\");\n const e54 = this.regionalB01RepairSolver.getResult(), t4 = this.boundedRegionalRepairSolver.getResult(), n8 = this.boundedRegionalParams.budget;\n this.combinedOutput = t4.routes, this.stats = { ...this.stats, boundedRegionalRepairMaxRegions: n8.maxRegions, boundedRegionalRepairMaxCandidateAttempts: n8.maxCandidateAttempts, boundedRegionalRepairMaxPathSearchNodes: n8.maxPathSearchNodes, boundedRegionalRepairAttemptedRegionCount: t4.attemptedRegionCount, boundedRegionalRepairAcceptedRegionCount: t4.acceptedRegionCount, boundedRegionalRepairCandidateAttemptCount: t4.candidateAttemptCount, boundedRegionalRepairPathSearchNodeCount: t4.pathSearchNodeCount, boundedRegionalRepairReferenceValidationCount: t4.referenceValidationCount, boundedRegionalRepairRepaired: t4.repaired, boundedRegionalRepairPublishedDrcIssueCount: t4.publishedDrcIssueCount, boundedRegionalRepairTimeMs: performance.now() - this.boundedRegionalRepairStartedAt, regionalB01RepairCandidateCount: e54.attemptedCandidateCount, regionalB01RepairAcceptedCount: e54.acceptedCandidateCount, regionalB01RepairFallbackCandidateCount: e54.fallbackCandidateCount, regionalB01RepairCandidateSearchCount: e54.candidateSearchCount, regionalB01RepairCandidateSearchBudget: e54.candidateSearchBudget, regionalB01RepairCandidateSearchBudgetExhausted: e54.candidateSearchBudgetExhausted, regionalB01RepairSafeTraceLayerSkippedForBudget: e54.safeTraceLayerRepairSkippedForBudget, regionalB01RepairRemainingDrcIssueCount: e54.remainingDrcIssueCount, regionalB01RepairPreloadEligibleDrcIssueCount: e54.preloadEligibleDrcIssueCount, regionalB01RepairAttempted: e54.preloadRepairAttempted, referenceDrcValidationCount: this.referenceDrcValidationCount, referenceDrcFalseNegativeCount: this.referenceDrcFalseNegativeCount, indexedDrcEvaluationCount: this.indexedDrcEvaluationCount, indexedDrcCacheHitCount: this.indexedDrcCacheHitCount, indexedDrcEvaluationTimeMs: this.indexedDrcEvaluationTimeMs, indexedDrcCandidateCacheSize: this.indexedDrcCandidateCache.size, indexedDrcCandidateCacheCapacity: 64 }, this.finishWithTraceContactCheck();\n }\n finishWithTraceContactCheck() {\n if (!this.combinedOutput || !this.exactRepairParams)\n throw new Error(\"Pipeline9 final trace contact check is missing repair state\");\n this.traceContactGuard.getNewContactPairs(this.combinedOutput).length !== 0 ? (this.traceContactRepairSolver = new HN({ ...this.exactRepairParams, hdRoutes: this.combinedOutput, inputHdRoutes: this.traceContactInputHdRoutes, deferTraceContactGuard: false }), this.activeSubSolver = this.traceContactRepairSolver, this.MAX_ITERATIONS += this.traceContactRepairSolver.MAX_ITERATIONS) : this.solved = true;\n }\n getCombinedOutput() {\n return this.combinedOutput ?? this.exactRepairSolver?.getOutput() ?? this.inputNewHdRoutes;\n }\n getOutput() {\n return this.getCombinedOutput().filter((e54) =\u003e !this.syntheticConnectionNames.has(e54.connectionName));\n }\n getUpdatedPreloadedTraces() {\n const e54 = new Map(this.getCombinedOutput().map((e60) =\u003e [e60.connectionName, e60])), t4 = new Map;\n for (const n10 of this.movablePreloadedSections) {\n const o10 = e54.get(n10.syntheticConnectionName);\n if (!o10)\n throw new Error(`Pipeline9 joint DRC repair output is missing \"${n10.syntheticConnectionName}\"`);\n const i8 = n10.originalTrace.pcb_trace_id, r9 = t4.get(i8) ?? [];\n r9.push({ routePositionStart: n10.originalRoutePositionStart, routePositionEnd: n10.originalRoutePositionEnd, route: Ro(o10, this.params.layerCount, { defaultViaHoleDiameter: this.params.defaultViaHoleDiameter, obstacles: this.params.obstacles, connMap: this.params.connMap }) }), t4.set(i8, r9);\n }\n const n8 = new Map([...t4].map(([e60, t10]) =\u003e {\n const n10 = this.inputUpdatedPreloadedTraces.find((t11) =\u003e t11.pcb_trace_id === e60);\n if (!n10)\n throw new Error(`Pipeline9 cannot find preloaded trace \"${e60}\" while rebuilding repaired sections`);\n return [e60, Vie({ originalTrace: n10, repairedSections: t10 })];\n }));\n return this.inputUpdatedPreloadedTraces.map((e60) =\u003e n8.get(e60.pcb_trace_id) ?? e60);\n }\n getMutatedPreloadedTraces() {\n const e54 = new Set([...this.params.mutatedPreloadedTraceIds, ...this.movablePreloadedSections.map((e60) =\u003e e60.originalTrace.pcb_trace_id)]);\n return this.getUpdatedPreloadedTraces().filter((t4) =\u003e e54.has(t4.pcb_trace_id));\n }\n visualize() {\n return this.exactRepairSolver?.visualize() ?? {};\n }\n};\nvar Gie = 0.000001;\nvar Uie = (e54, t4, n8) =\u003e {\n const o10 = mo(e54, n8), i8 = mo(t4, n8);\n return Array.from({ length: Math.abs(i8 - o10) + 1 }, (e60, t10) =\u003e Math.min(o10, i8) + t10);\n};\nvar Zie = (e54) =\u003e e54.route_type === \"wire\";\nvar qie = (e54, t4, n8) =\u003e e54.portPoints.filter((e60) =\u003e e60.availableZ.includes(n8) \u0026\u0026 !(e60._preloadedTracePortAssignments ?? []).some((e61) =\u003e e61.z === n8 \u0026\u0026 e61.fixedNetId !== t4.fixedNetId)).map((e60) =\u003e ({ portPoint: e60, distance: pe(e60, t4.start, t4.end) })).sort((e60, t10) =\u003e e60.distance - t10.distance || e60.portPoint.distToCentermostPortOnZ - t10.portPoint.distToCentermostPortOnZ || e60.portPoint.segmentPortPointId.localeCompare(t10.portPoint.segmentPortPointId))[0]?.portPoint;\nvar Jie = (e54, t4, n8) =\u003e {\n e54._preloadedFixedNetIds = [...new Set([...e54._preloadedFixedNetIds ?? [], t4.fixedNetId])].sort();\n const o10 = t4.end.x - t4.start.x, i8 = t4.end.y - t4.start.y, r9 = o10 * o10 + i8 * i8, s7 = r9 === 0 ? 0 : Math.max(0, Math.min(1, ((e54.x - t4.start.x) * o10 + (e54.y - t4.start.y) * i8) / r9)), a9 = { traceId: t4.traceId, fixedNetId: t4.fixedNetId, routePosition: t4.routePositionStart + s7 * (t4.routePositionEnd - t4.routePositionStart), tracePoint: { x: t4.start.x + s7 * o10, y: t4.start.y + s7 * i8 }, z: n8 }, c5 = e54._preloadedTracePortAssignments ?? [];\n c5.some((e60) =\u003e e60.traceId === a9.traceId \u0026\u0026 e60.fixedNetId === a9.fixedNetId \u0026\u0026 e60.z === a9.z \u0026\u0026 Math.abs(e60.routePosition - a9.routePosition) \u003c= Gie) || (e54._preloadedTracePortAssignments = [...c5, a9].sort((e60, t10) =\u003e e60.traceId.localeCompare(t10.traceId) || e60.routePosition - t10.routePosition || e60.z - t10.z));\n};\nvar Qie = class extends ni {\n constructor(e54, t4) {\n if (super(), this.sharedEdgeSegments = e54, this.srj = t4, this.MAX_ITERATIONS = 1, this.primitives = ((e60) =\u003e {\n const t10 = [], n8 = ei(e60);\n for (const o10 of e60.traces ?? []) {\n if (!o10.connection_name)\n throw new Error(`Preloaded trace \"${o10.pcb_trace_id}\" is missing a connection name`);\n const i8 = n8.getNetConnectedToId(o10.connection_name) ?? o10.connection_name;\n for (const [n10, r9] of o10.route.entries())\n if (r9.route_type === \"via\")\n t10.push({ traceId: o10.pcb_trace_id, fixedNetId: i8, connectionName: o10.connection_name, routePositionStart: n10, routePositionEnd: n10, zLayers: Uie(r9.from_layer, r9.to_layer, e60.layerCount), start: r9, end: r9 });\n else if (r9.route_type === \"through_obstacle\")\n t10.push({ traceId: o10.pcb_trace_id, fixedNetId: i8, connectionName: o10.connection_name, routePositionStart: n10, routePositionEnd: n10 + 1, zLayers: Uie(r9.from_layer, r9.to_layer, e60.layerCount), start: r9.start, end: r9.end });\n else if (r9.route_type === \"jumper\") {\n const s7 = mo(r9.layer, e60.layerCount);\n for (const [e61, a9] of [r9.start, r9.end].entries())\n t10.push({ traceId: o10.pcb_trace_id, fixedNetId: i8, connectionName: o10.connection_name, routePositionStart: n10 + e61, routePositionEnd: n10 + e61, zLayers: [s7], start: a9, end: a9 });\n }\n for (let n10 = 0;n10 \u003c o10.route.length - 1; n10++) {\n const r9 = o10.route[n10], s7 = o10.route[n10 + 1];\n Zie(r9) \u0026\u0026 Zie(s7) \u0026\u0026 r9.layer === s7.layer \u0026\u0026 t10.push({ traceId: o10.pcb_trace_id, fixedNetId: i8, connectionName: o10.connection_name, routePositionStart: n10, routePositionEnd: n10 + 1, zLayers: [mo(r9.layer, e60.layerCount)], start: r9, end: s7 });\n }\n }\n return t10;\n })(t4), this.boundaryIndex = e54.length \u003e 0 ? new E2(e54.length) : null, this.boundaryIndex) {\n for (const t10 of e54)\n this.boundaryIndex.add(Math.min(t10.start.x, t10.end.x), Math.min(t10.start.y, t10.end.y), Math.max(t10.start.x, t10.end.x), Math.max(t10.start.y, t10.end.y));\n this.boundaryIndex.finish();\n }\n }\n primitives;\n boundaryIndex;\n getSolverName() {\n return \"PreloadedTraceGraphSolver\";\n }\n _step() {\n let e54 = 0;\n for (const t10 of this.primitives) {\n if (this.boundaryIndex === null)\n break;\n const n10 = this.boundaryIndex.search(Math.min(t10.start.x, t10.end.x) - Gie, Math.min(t10.start.y, t10.end.y) - Gie, Math.max(t10.start.x, t10.end.x) + Gie, Math.max(t10.start.y, t10.end.y) + Gie).sort((e60, t11) =\u003e e60 - t11);\n for (const o10 of n10) {\n const n11 = this.sharedEdgeSegments[o10];\n if (e54++, !(qr(t10.start, t10.end, n11.start, n11.end) \u003e Gie))\n for (const e60 of t10.zLayers) {\n if (!n11.availableZ.includes(e60))\n continue;\n const o11 = qie(n11, t10, e60);\n o11 \u0026\u0026 Jie(o11, t10, e60);\n }\n }\n }\n const t4 = this.sharedEdgeSegments.flatMap((e60) =\u003e e60.portPoints), n8 = t4.filter((e60) =\u003e (e60._preloadedFixedNetIds?.length ?? 0) \u003e 0);\n this.stats = { boundaryDistanceCheckCount: e54, preloadedTraceCount: this.srj.traces?.length ?? 0, preloadedTraceShapeCount: this.primitives.length, inputBoundaryCount: this.sharedEdgeSegments.length, outputBoundaryCount: this.sharedEdgeSegments.length, inputPortCount: t4.length, outputPortCount: t4.length, preloadedPortCount: n8.length, tracePortAssignmentCount: n8.reduce((e60, t10) =\u003e e60 + (t10._preloadedTracePortAssignments?.length ?? 0), 0), topologyChanged: false }, this.solved = true;\n }\n getOutput() {\n if (!this.solved)\n throw new Error(\"PreloadedTraceGraphSolver has not solved yet\");\n return this.sharedEdgeSegments;\n }\n};\nvar Kie = class extends U1 {\n _step() {\n if (this.error = G1(this.inputSrj), this.error)\n return void (this.failed = true);\n const { traces: e54, ...t4 } = this.inputSrj, n8 = V1(t4), o10 = V1(Zr(W1(n8)));\n this.error = G1(o10), this.error ? this.failed = true : (this.outputSrj = e54 === undefined ? o10 : { ...o10, traces: e54 }, this.solved = true);\n }\n};\nfunction ere(e54) {\n return new Set((e54 ?? []).filter((e60) =\u003e e60._isComponentTopologyNode).map((e60) =\u003e e60.capacityMeshNodeId));\n}\nfunction tre(e54, t4) {\n return e54.nodeIds.some((e60) =\u003e t4.has(e60));\n}\nfunction nre({ sharedEdgeSegments: e54, componentCapacityMeshNodeIds: t4 }) {\n return e54.filter((e60) =\u003e !tre(e60, t4));\n}\nfunction ore(e54, t4, n8, o10 = {}) {\n return { solverName: e54, solverClass: t4, getConstructorParams: n8, onSolved: o10.onSolved };\n}\nvar ire = class extends ni {\n constructor(e54, t4 = {}) {\n super(), this.srj = e54, this.opts = t4;\n const n8 = V1(e54);\n this.originalSrj = n8, this.opts = { ...t4 };\n const o10 = this.opts;\n if (this.effort = o10.effort ?? 1, this.MAX_ITERATIONS = 1e8 * this.effort, this.maxNodeDimension = o10.maxNodeDimension ?? 15, this.maxNodeRatio = o10.maxNodeRatio ?? 6, this.minNodeArea = o10.minNodeArea ?? 0.1 ** 2, this.visualizationTraceColorMode = o10.visualizationTraceColorMode ?? \"layer\", this.setSimpleRouteJson(n8), o10.capacityDepth === undefined) {\n const e60 = this.srj.bounds.maxX - this.srj.bounds.minX, t10 = this.srj.bounds.maxY - this.srj.bounds.minY, n10 = Math.max(e60, t10), i8 = o10.targetMinCapacity ?? 0.5;\n o10.capacityDepth = Fz(n10, i8);\n }\n this.cacheProvider = o10.cacheProvider === undefined ? no() : o10.cacheProvider === null ? null : o10.cacheProvider, this.startTimeOfPhase = {}, this.endTimeOfPhase = {}, this.timeSpentOnPhase = {};\n }\n getSolverName() {\n return \"AutoroutingPipelineSolver9_PreloadedTraceGraph\";\n }\n preprocessSimpleRouteJsonSolver;\n escapeViaLocationSolver;\n netToPointPairsSolver;\n componentTopologyGeneratorSolver;\n topologyPlanningSolver;\n topologyMergingSolver;\n globalTopologyGeneratorSolver;\n nodeDimensionSubdivisionSolver;\n nodeTargetMerger;\n edgeSolver;\n colorMap;\n highDensityRouteSolver;\n highDensityForceImproveSolver;\n highDensityRepairSolver;\n highDensityStitchSolver;\n globalDrcForceImproveSolver;\n pipeline9JointDrcRepairSolver;\n singleLayerNodeMerger;\n strawSolver;\n deadEndSolver;\n traceSimplificationSolver;\n mutatedPreloadedTraceSimplificationSolver;\n lengthMatchingPostProcessingSolver;\n powerTraceExpansionSolver;\n availableSegmentPointSolver;\n portPointPathingSolver;\n multiSectionPortPointOptimizer;\n uniformPortDistributionSolver;\n traceWidthSolver;\n necessaryCrampedPortPointSolver;\n preloadedTraceGraphSolver;\n componentDetectionSolver;\n viaDiameter;\n viaHoleDiameter;\n minTraceWidth;\n effort;\n effortCleanupSolver;\n maxNodeDimension;\n maxNodeRatio;\n minNodeArea;\n visualizationTraceColorMode;\n startTimeOfPhase;\n endTimeOfPhase;\n timeSpentOnPhase;\n activeSubSolver = null;\n connMap;\n srjWithEscapeViaLocations;\n srjWithPointPairs;\n originalSrj;\n capacityNodes = null;\n capacityEdges = null;\n sharedEdgeSegmentsWithNecessaryCrampedPortPoints;\n highDensityNodePortPoints;\n cacheProvider = null;\n pipelineDef = [ore(\"preprocessSimpleRouteJsonSolver\", Kie, (e54) =\u003e [e54.originalSrj, { traceColorMode: e54.visualizationTraceColorMode }], { onSolved: (e54) =\u003e {\n e54.setSimpleRouteJson(e54.preprocessSimpleRouteJsonSolver.getOutputSimpleRouteJson());\n } }), ore(\"componentDetectionSolver\", r7, (e54) =\u003e [{ inputSrj: e54.srj }]), ore(\"escapeViaLocationSolver\", uK, (e54) =\u003e [e54.srj, { viaDiameter: e54.viaDiameter, minTraceWidth: e54.minTraceWidth, obstacleMargin: e54.srj.defaultObstacleMargin ?? 0.15 }], { onSolved: (e54) =\u003e {\n e54.srjWithEscapeViaLocations = e54.escapeViaLocationSolver?.getOutputSimpleRouteJson();\n } }), ore(\"netToPointPairsSolver\", pB, (e54) =\u003e {\n const t4 = e54.srjWithEscapeViaLocations ?? e54.srj;\n return [t4, e54.colorMap, ti(t4)];\n }, { onSolved: (e54) =\u003e {\n e54.srjWithPointPairs = e54.netToPointPairsSolver?.getNewSimpleRouteJson(), e54.colorMap = Eo(e54.srjWithPointPairs, e54.connMap), e54.connMap = ei(e54.srjWithPointPairs);\n } }), ore(\"topologyPlanningSolver\", N7, (e54) =\u003e [{ inputSrj: e54.srjWithPointPairs, componentDetectionOutput: e54.componentDetectionSolver.getOutput(), viaDiameter: e54.viaDiameter, obstacleMargin: e54.srj.defaultObstacleMargin ?? 0.15 }], { onSolved: (e54) =\u003e {\n e54.topologyPlanningSolver.getOutput();\n e54.globalTopologyGeneratorSolver = e54.topologyPlanningSolver.globalTopologySolver, e54.componentTopologyGeneratorSolver = new E7(e54.topologyPlanningSolver);\n } }), ore(\"topologyMergingSolver\", C7, (e54) =\u003e {\n const t4 = e54.topologyPlanningSolver.getOutput();\n return [{ layerCount: e54.srj.layerCount, allowBlindAndBuriedVias: e54.srj.allowBlindAndBuriedVias, nodeGroups: [{ groupId: \"global\", nodes: t4.globalMeshNodes, isComponent: false }, ...t4.componentMeshNodes.map((e60, t10) =\u003e ({ groupId: `component-${t10}`, nodes: e60, isComponent: true }))] }];\n }, { onSolved: (e54) =\u003e {\n e54.capacityNodes = e54.topologyMergingSolver.getOutput();\n } }), ore(\"nodeDimensionSubdivisionSolver\", MZ, (e54) =\u003e [e54.capacityNodes, e54.maxNodeDimension, e54.maxNodeRatio, e54.minNodeArea], { onSolved: (e54) =\u003e {\n e54.capacityNodes = e54.nodeDimensionSubdivisionSolver.outputNodes;\n } }), ore(\"edgeSolver\", ui, (e54) =\u003e [e54.capacityNodes], { onSolved: (e54) =\u003e {\n e54.capacityEdges = e54.edgeSolver?.edges;\n } }), ore(\"availableSegmentPointSolver\", ii, (e54) =\u003e [{ nodes: e54.capacityNodes, edges: e54.capacityEdges || [], traceWidth: e54.minTraceWidth, colorMap: e54.colorMap, shouldReturnCrampedPortPoints: true }]), ore(\"necessaryCrampedPortPointSolver\", FG, (e54) =\u003e {\n const t4 = ere(e54.capacityNodes);\n return [{ capacityMeshNodes: e54.capacityNodes.filter((e60) =\u003e !t4.has(e60.capacityMeshNodeId)), sharedEdgeSegments: nre({ sharedEdgeSegments: e54.availableSegmentPointSolver.getOutput(), componentCapacityMeshNodeIds: t4 }), simpleRouteJson: e54.srjWithPointPairs }];\n }, { onSolved: (e54) =\u003e {\n const t4 = ere(e54.capacityNodes);\n e54.sharedEdgeSegmentsWithNecessaryCrampedPortPoints = function({ originalSharedEdgeSegments: e60, filteredSharedEdgeSegments: t10, componentCapacityMeshNodeIds: n8 }) {\n const o10 = new Map(t10.map((e61) =\u003e [e61.edgeId, e61]));\n return e60.map((e61) =\u003e tre(e61, n8) ? e61 : o10.get(e61.edgeId) ?? e61);\n }({ originalSharedEdgeSegments: e54.availableSegmentPointSolver.getOutput(), filteredSharedEdgeSegments: e54.necessaryCrampedPortPointSolver.getOutput(), componentCapacityMeshNodeIds: t4 });\n } }), ore(\"preloadedTraceGraphSolver\", Qie, (e54) =\u003e [e54.sharedEdgeSegmentsWithNecessaryCrampedPortPoints, e54.srjWithPointPairs]), ore(\"portPointPathingSolver\", eK, (e54) =\u003e {\n const t4 = e54.sharedEdgeSegmentsWithNecessaryCrampedPortPoints ?? e54.necessaryCrampedPortPointSolver?.getOutput() ?? e54.availableSegmentPointSolver.getOutput(), { graph: n8, connections: o10 } = KG({ capacityMeshNodes: e54.capacityNodes, layerCount: e54.srj.layerCount, connectivityMap: e54.connMap, segmentPortPoints: t4.flatMap((e60) =\u003e e60.portPoints), simpleRouteJsonConnections: e54.srjWithPointPairs.connections });\n return [{ graph: n8, connections: o10, layerCount: e54.srj.layerCount, effort: Math.min(1, e54.effort), preserveTerminalPcbPortIds: true, captureSearchDebug: e54.opts.captureSearchDebug ?? false, minViaPadDiameter: e54.viaDiameter, flags: { FORCE_CENTER_FIRST: true, RIPPING_ENABLED: true, USE_SELECTIVE_RERIP_ROUTING: true, USE_PREPARED_PORT_POINT_ROUTING: true, USE_PARTIAL_RIP_ROUTING_WITH_PRELOADED_TRACES: true }, weights: { SHUFFLE_SEED: 0, MEMORY_PF_FACTOR: 4, CENTER_OFFSET_DIST_PENALTY_FACTOR: 0, CENTER_OFFSET_FOCUS_SHIFT: 0, NODE_PF_FACTOR: 0, LAYER_CHANGE_COST: 0, RIPPING_PF_COST: 0, NODE_PF_MAX_PENALTY: 100, BASE_CANDIDATE_COST: 0.6, MAX_ITERATIONS_PER_PATH: 0, RANDOM_WALK_DISTANCE: 0, START_RIPPING_PF_THRESHOLD: 0.3, END_RIPPING_PF_THRESHOLD: 1, MAX_RIPS: 1000, RANDOM_RIP_FRACTION: 0.3, STRAIGHT_LINE_DEVIATION_PENALTY_FACTOR: 4, GREEDY_MULTIPLIER: 0.7, MIN_ALLOWED_BOARD_SCORE: -1e4 } }];\n }), ore(\"uniformPortDistributionSolver\", bo, (e54) =\u003e [{ nodeWithPortPoints: e54.portPointPathingSolver?.getOutput().nodesWithPortPoints ?? [], inputNodesWithPortPoints: e54.portPointPathingSolver?.getOutput().inputNodeWithPortPoints ?? [], minTraceWidth: e54.minTraceWidth, obstacles: e54.srj.obstacles, layerCount: e54.srj.layerCount, useLayerAwareGeometry: e54.srj.layerCount \u003e 2, preserveSolitaryPorts: Boolean(e54.srj.traces?.length) }]), ore(\"highDensityRouteSolver\", Loe, (e54) =\u003e {\n const t4 = e54.portPointPathingSolver;\n if (!t4)\n throw new Error(\"Pipeline9 invariant violated: high-density routing requires the completed port-point pathing solver\");\n const n8 = t4.getOutput(), o10 = e54.uniformPortDistributionSolver?.getOutput() ?? [], i8 = n8.nodesWithPortPoints, r9 = o10.length \u003e 0 ? o10 : i8;\n e54.highDensityNodePortPoints = structuredClone(r9);\n const s7 = (e54.originalSrj.traces ?? []).flatMap((t10, n10) =\u003e Vne(t10, n10, e54.originalSrj.layerCount, e54.viaDiameter, e54.connMap)), a9 = fne({ traces: e54.originalSrj.traces ?? [], fixedHdRoutes: s7, sections: e54.getChangedPreloadedTraceSections() });\n return [{ nodePortPoints: r9, boardGeometry: { bounds: e54.originalSrj.bounds, outline: e54.originalSrj.outline, minBoardEdgeClearance: e54.originalSrj.minBoardEdgeClearance }, fixedHdRoutes: a9, connMap: e54.connMap, colorMap: e54.colorMap, obstacles: e54.srj.obstacles, layerCount: e54.srj.layerCount, allowBlindAndBuriedVias: e54.srj.allowBlindAndBuriedVias, viaDiameter: e54.viaDiameter, viaHoleDiameter: e54.viaHoleDiameter, minViaHoleEdgeToViaHoleEdgeClearance: e54.originalSrj.minViaHoleEdgeToViaHoleEdgeClearance ?? 0.1, traceWidth: e54.minTraceWidth, obstacleMargin: e54.srj.defaultObstacleMargin ?? 0.15, viaToPadClearance: e54.srj.minViaEdgeToPadEdgeClearance, effort: Math.min(1, e54.effort), includeBoardObstacles: true, nodePfById: t4.computeNodePfMap(), preserveTerminalPcbPortIds: true }];\n }), ore(\"highDensityForceImproveSolver\", qte, (e54) =\u003e [{ nodeWithPortPoints: e54.highDensityNodePortPoints ?? [], hdRoutes: xne(yne(e54.highDensityRouteSolver.routes)), colorMap: e54.colorMap, totalStepsPerNode: Math.max(12, Math.round(20 * Math.min(1, e54.effort))), nodeAssignmentMargin: e54.srj.defaultObstacleMargin ?? 0.2 }]), ore(\"highDensityRepairSolver\", g1, (e54) =\u003e [{ nodeWithPortPoints: e54.highDensityNodePortPoints ?? [], hdRoutes: e54.highDensityForceImproveSolver?.getOutput() ?? e54.highDensityRouteSolver.routes, obstacles: e54.srj.obstacles, colorMap: e54.colorMap, repairMargin: e54.srj.defaultObstacleMargin ?? 0.2, minimumTraceWidth: e54.srj.minTraceWidth, connMap: e54.connMap }]), ore(\"highDensityStitchSolver\", L1, (e54) =\u003e [{ connections: [...e54.srjWithPointPairs.connections, ...e54.getChangedPreloadedTraceSections().map((e60) =\u003e e60.connection)], hdRoutes: e54.highDensityRepairSolver?.getOutput() ?? e54.highDensityForceImproveSolver?.getOutput() ?? e54.highDensityRouteSolver.routes, colorMap: e54.colorMap, layerCount: e54.srj.layerCount, defaultViaDiameter: e54.viaDiameter, preserveTerminalPcbPortIds: true, preferSameLayerTerminalEndpoints: true }]), ore(\"traceSimplificationSolver\", WF, (e54) =\u003e {\n const t4 = e54.getPreloadedTraceUpdatesAfterHighDensity().updatedPreloadedTraces.flatMap((t10, n10) =\u003e Vne(t10, n10, e54.originalSrj.layerCount, e54.viaDiameter, e54.connMap).map((e60) =\u003e ({ ...e60, rootConnectionName: t10.connection_name }))), n8 = new Set(e54.getChangedPreloadedTraceSections().map((e60) =\u003e e60.connectionName)), o10 = e54.highDensityStitchSolver.mergedHdRoutes.filter((e60) =\u003e !n8.has(e60.connectionName)), i8 = hne([...o10, ...t4], e54.connMap);\n return [{ hdRoutes: o10, obstacles: e54.srj.obstacles, connMap: e54.connMap, colorMap: e54.colorMap, outline: e54.srj.outline, defaultViaDiameter: e54.viaDiameter, layerCount: e54.srj.layerCount, minTraceToPadEdgeClearance: e54.srj.minTraceToPadEdgeClearance, minBoardEdgeClearance: e54.srj.minBoardEdgeClearance, otherHdRoutes: t4, netByConnectionName: i8, enableCrossingViaReduction: true, terminalLayerIndicesByPcbPortId: lne(e54.srj.connections, e54.srj.obstacles, e54.srj.layerCount), iterations: 2 }];\n }), ore(\"mutatedPreloadedTraceSimplificationSolver\", WF, (e54) =\u003e {\n const t4 = e54.getPreparedMutatedPreloadedTraceSections(), n8 = t4.sections.map((e60) =\u003e e60.hdRoute), o10 = [...t4.immutableHdRoutes, ...e54.traceSimplificationSolver.simplifiedHdRoutes];\n return [{ hdRoutes: n8, obstacles: e54.srj.obstacles, connMap: e54.connMap, colorMap: e54.colorMap, outline: e54.srj.outline, defaultViaDiameter: e54.viaDiameter, layerCount: e54.srj.layerCount, minTraceToPadEdgeClearance: e54.srj.minTraceToPadEdgeClearance, minBoardEdgeClearance: e54.srj.minBoardEdgeClearance, otherHdRoutes: o10, netByConnectionName: hne([...n8, ...o10], e54.connMap), enableCrossingViaReduction: true, preserveRouteEndpoints: true, enableVertexShortcuts: true, iterations: 2 }];\n }), ore(\"traceWidthSolver\", QF, (e54) =\u003e [{ hdRoutes: e54.traceSimplificationSolver.simplifiedHdRoutes, obstacles: e54.srj.obstacles, connMap: e54.connMap, colorMap: e54.colorMap, minTraceWidth: e54.minTraceWidth, connection: e54.srjWithPointPairs.connections, obstacleMargin: e54.srj.minTraceToPadEdgeClearance ?? 0.15, minTraceToHoleEdgeClearance: e54.srj.minTraceToHoleEdgeClearance, layerCount: e54.srj.layerCount }]), ore(\"globalDrcForceImproveSolver\", kN, (e54) =\u003e [{ srj: e54.getSrjWithMaterializedPreloadedTraces(), hdRoutes: Mte({ hdRoutes: bne(e54.traceWidthSolver.getHdRoutesWithWidths()), connections: e54.netToPointPairsSolver?.newConnections ?? [] }), connMap: e54.connMap, effort: Math.min(1, e54.effort), maxIterations: 16, enableLargeBoardBroadFallback: false, enablePostSolveClearanceRelaxation: false, deferTraceContactGuard: true }]), ore(\"pipeline9JointDrcRepairSolver\", Wie, (e54) =\u003e {\n const t4 = e54.getPreloadedTraceUpdatesAfterHighDensity(), n8 = e54.getSrjWithMaterializedPreloadedTraces();\n return [{ srj: n8, srjWithPointPairs: n8, originalSrj: e54.originalSrj, newConnections: e54.netToPointPairsSolver?.newConnections ?? [], newHdRoutes: e54.globalDrcForceImproveSolver.getOutput(), originalNewHdRoutes: e54.globalDrcForceImproveSolver.guardedInputHdRoutes, updatedPreloadedTraces: t4.updatedPreloadedTraces, mutatedPreloadedTraceIds: new Set(t4.mutatedPreloadedTraces.map((e60) =\u003e e60.pcb_trace_id)), connMap: e54.connMap, obstacles: e54.srj.obstacles, layerCount: e54.srj.layerCount, defaultViaDiameter: e54.viaDiameter, defaultViaHoleDiameter: e54.viaHoleDiameter, effort: Math.min(1, e54.effort), colorMap: e54.colorMap }];\n }), ore(\"effortCleanupSolver\", Bte, (e54) =\u003e {\n const t4 = e54.getUpdatedPreloadedTraces(), n8 = { ...e54.originalSrj, traces: t4 }, o10 = bne(e54.pipeline9JointDrcRepairSolver.getOutput()), i8 = (t10) =\u003e cne(Cte({ connections: e54.netToPointPairsSolver.newConnections, originalConnections: e54.originalSrj.connections, hdRoutes: bne(t10), layerCount: e54.srj.layerCount, obstacles: e54.srj.obstacles, defaultViaHoleDiameter: e54.viaHoleDiameter, connMap: e54.connMap }), e54.originalSrj.traces ?? []), r9 = Gte({ inputSrj: n8, srjWithPointPairs: e54.srjWithPointPairs, includeBoardClearance: true, drcOptions: { traceClearance: e54.originalSrj.minTraceToPadEdgeClearance ?? e54.originalSrj.defaultObstacleMargin ?? 0.1, viaClearance: e54.originalSrj.minViaHoleEdgeToViaHoleEdgeClearance ?? 0.1 } });\n return [{ effort: e54.effort, viaRemovalPasses: e54.pipeline9JointDrcRepairSolver.stats.initialBoundedRegionalRepairAddedViaCount \u003e 0 ? 2 : 1, config: { hdRoutes: o10, preserveRouteEndpoints: true, obstacles: e54.srj.obstacles, connMap: e54.connMap, colorMap: e54.colorMap, outline: e54.srj.outline, defaultViaDiameter: e54.viaDiameter, layerCount: e54.srj.layerCount, minTraceToPadEdgeClearance: e54.srj.minTraceToPadEdgeClearance, minBoardEdgeClearance: e54.srj.minBoardEdgeClearance, otherHdRoutes: t4.flatMap((t10, n10) =\u003e Vne(t10, n10, e54.srj.layerCount, e54.viaDiameter, e54.connMap)), enableCrossingViaReduction: true, terminalLayerIndicesByPcbPortId: lne(e54.srj.connections, e54.srj.obstacles, e54.srj.layerCount) }, getCost: (e60) =\u003e {\n const t10 = i8(e60);\n return { vias: t10.reduce((e61, t11) =\u003e e61 + t11.route.filter((e63) =\u003e e63.route_type === \"via\").length, 0), points: t10.reduce((e61, t11) =\u003e e61 + t11.route.length, 0) };\n }, isValid: (e60) =\u003e r9(i8(e60)).errors.length === 0 }];\n }), ore(\"lengthMatchingPostProcessingSolver\", Kte, (e54) =\u003e {\n const t4 = e54.netToPointPairsSolver;\n if (!t4)\n throw new Error(\"Pipeline9: length-matching post-processing requires NetToPointPairsSolver output\");\n const n8 = t4.newConnections, o10 = new Map;\n for (const t10 of e54.srj.differentialPairs ?? [])\n for (const e60 of t10.connectionNames) {\n const t11 = n8.filter((t12) =\u003e t12.name === e60 || t12.__rootConnectionNames?.includes(e60) || t12.__netConnectionName === e60);\n if (t11.length !== 1)\n throw new Error(`Pipeline9: differential pair connection \"${e60}\" must resolve to exactly one final point-pair connection, got ${t11.length}`);\n o10.set(e60, t11[0].name);\n }\n const i8 = e54.effortCleanupSolver.getOutput(), r9 = (e54.srj.differentialPairs ?? []).map((e60) =\u003e {\n const t10 = e60.connectionNames.map((e61) =\u003e {\n const t11 = o10.get(e61);\n if (!t11)\n throw new Error(`Pipeline9: differential pair connection \"${e61}\" is missing from final routed output`);\n return t11;\n });\n if (t10[0] === t10[1])\n throw new Error(`Pipeline9: differential pair ${e60.connectionNames.join(\"/\")} resolves both members to \"${t10[0]}\"`);\n const n10 = { connectionNames: t10, lengthTolerance: e60.lengthTolerance };\n if (e60.maxUncoupledLength !== undefined \u0026\u0026 (n10.maxUncoupledLength = e60.maxUncoupledLength), e60.traceGap === undefined)\n return n10;\n const r10 = t10.map((e61) =\u003e {\n const t11 = i8.filter((t12) =\u003e t12.connectionName === e61);\n if (t11.length !== 1)\n throw new Error(`Pipeline9: differential pair connection \"${e61}\" must resolve to exactly one final HD route, got ${t11.length}`);\n return t11[0];\n }), s7 = e60.traceGap + r10.reduce((e61, t11) =\u003e e61 + t11.traceThickness / 2, 0);\n return { ...n10, minimumCenterlineDistance: s7, maximumCenterlineDistance: s7 };\n });\n return [{ hdRoutes: i8, differentialPairs: r9, buses: e54.srj.buses ?? [], connections: e54.srj.connections, obstacles: e54.srj.obstacles, traces: e54.getUpdatedPreloadedTraces(), bounds: e54.srj.bounds, layerCount: e54.srj.layerCount, obstacleMargin: e54.srj.minTraceToPadEdgeClearance ?? 0.15 }];\n }), ore(\"powerTraceExpansionSolver\", Ite, (e54) =\u003e {\n const t4 = e54.opts.powerTraceExpansion ?? {}, n8 = t4.onlyConnectionNames ?? Pte(e54.originalSrj);\n return [wte({ originalSrj: e54.originalSrj, newlyRoutedTraces: e54.getNewTracesBeforePowerExpansion(), currentPreloadedTraces: e54.getUpdatedPreloadedTraces(), expandedConnectionNames: n8, resolveConnectedTraceAliases: true }), { allowNewVias: false, ...t4, onlyConnectionNames: n8 }];\n })];\n setSimpleRouteJson(e54) {\n this.srj = e54;\n const t4 = Yo(this.srj);\n this.viaDiameter = t4.padDiameter, this.viaHoleDiameter = t4.holeDiameter, this.minTraceWidth = this.srj.minTraceWidth, this.connMap = ei(this.srj), this.colorMap = Eo(this.srj, this.connMap);\n }\n getConstructorParams() {\n return [this.srj, this.opts];\n }\n currentPipelineStepIndex = 0;\n asyncRunning = false;\n async solveAsync(e54) {\n if (this.asyncRunning)\n throw new Error(\"Pipeline9 solveAsync is already running\");\n const t4 = performance.now();\n let n8 = t4;\n this.asyncRunning = true;\n try {\n if (e54 === undefined)\n return void this.solve();\n for (;!this.solved \u0026\u0026 !this.failed; ) {\n if (this.activeSubSolver instanceof Loe || this.activeSubSolver instanceof eK || this.activeSubSolver instanceof g1 || this.activeSubSolver instanceof qte) {\n const t10 = this.activeSubSolver, n10 = t10.iterations;\n await t10.solveAsync(e54, n10 + Math.max(0, this.MAX_ITERATIONS - this.iterations));\n const o10 = t10.solved || t10.failed;\n this.iterations += Math.max(0, t10.iterations - n10 - (o10 ? 1 : 0));\n }\n this.step(), this.iterations % 1024 == 0 \u0026\u0026 performance.now() - n8 \u003e= 16 \u0026\u0026 (await new Promise((e60) =\u003e setTimeout(e60, 0)), n8 = performance.now());\n }\n } catch (e60) {\n throw this.failed = true, this.error = `Pipeline9 asynchronous solve error: ${e60}`, e60;\n } finally {\n this.asyncRunning = false, this.timeToSolve = performance.now() - t4;\n }\n }\n computeProgress() {\n const e54 = this.activeSubSolver?.progress ?? 0;\n return (this.currentPipelineStepIndex + e54) / this.pipelineDef.length;\n }\n _step() {\n const e54 = this.pipelineDef[this.currentPipelineStepIndex];\n if (!e54)\n return void (this.solved = true);\n if (this.activeSubSolver)\n return this.activeSubSolver.step(), void (this.activeSubSolver.solved ? (this.endTimeOfPhase[e54.solverName] = performance.now(), this.timeSpentOnPhase[e54.solverName] = this.endTimeOfPhase[e54.solverName] - this.startTimeOfPhase[e54.solverName], e54.onSolved?.(this), this.activeSubSolver = null, this.currentPipelineStepIndex++) : this.activeSubSolver.failed \u0026\u0026 (this.error = this.activeSubSolver?.error, this.failed = true, this.activeSubSolver = null));\n const t4 = e54.getConstructorParams(this);\n this.activeSubSolver = new e54.solverClass(...t4), this.activeSubSolver instanceof WF \u0026\u0026 (this.activeSubSolver.MAX_SIMPLIFICATION_PIPELINE_LOOPS = Math.ceil(this.activeSubSolver.MAX_SIMPLIFICATION_PIPELINE_LOOPS * Math.min(1, this.effort))), e54.solverName !== \"lengthMatchingPostProcessingSolver\" \u0026\u0026 e54.solverName !== \"powerTraceExpansionSolver\" \u0026\u0026 e54.solverName !== \"effortCleanupSolver\" || (this.MAX_ITERATIONS = Math.max(this.MAX_ITERATIONS, this.iterations + this.activeSubSolver.MAX_ITERATIONS + 1)), this[e54.solverName] = this.activeSubSolver, this.timeSpentOnPhase[e54.solverName] = 0, this.startTimeOfPhase[e54.solverName] = performance.now();\n }\n solveUntilPhase(e54) {\n for (;this.getCurrentPhase() !== e54; )\n this.step();\n }\n getCurrentPhase() {\n return this.pipelineDef[this.currentPipelineStepIndex]?.solverName ?? \"none\";\n }\n visualize() {\n if (!this.solved \u0026\u0026 this.activeSubSolver)\n return this.visualizeStage(this.activeSubSolver);\n const e54 = this.escapeViaLocationSolver?.visualize(), t4 = this.netToPointPairsSolver?.visualize(), n8 = this.componentDetectionSolver?.visualize(), o10 = this.componentTopologyGeneratorSolver?.visualize(), i8 = this.globalTopologyGeneratorSolver?.visualize(), r9 = this.topologyMergingSolver?.visualize(), s7 = this.nodeDimensionSubdivisionSolver?.visualize(), a9 = this.nodeTargetMerger?.visualize(), c5 = this.singleLayerNodeMerger?.visualize(), l5 = this.strawSolver?.visualize(), h5 = this.edgeSolver?.visualize(), d9 = this.deadEndSolver?.visualize(), u9 = this.availableSegmentPointSolver?.visualize(), p9 = this.portPointPathingSolver?.visualize(), m9 = this.multiSectionPortPointOptimizer?.visualize(), g10 = this.uniformPortDistributionSolver?.visualize(), f10 = this.highDensityRouteSolver?.visualize(), _5 = this.highDensityForceImproveSolver?.visualize(), y10 = this.highDensityRepairSolver?.visualize(), b10 = this.highDensityStitchSolver?.visualize(), x8 = this.traceSimplificationSolver?.visualize(), v10 = this.mutatedPreloadedTraceSimplificationSolver?.visualize(), I6 = this.lengthMatchingPostProcessingSolver?.visualize(), S6 = this.powerTraceExpansionSolver?.visualize(), C = this.traceWidthSolver?.visualize(), P = this.necessaryCrampedPortPointSolver?.visualize(), M = (this.highDensityRouteSolver?.visualize(), this.originalSrj), w = M.outline, N = [];\n if (N.push({ points: [{ x: M.bounds?.minX ?? -50, y: M.bounds?.minY ?? -50 }, { x: M.bounds?.maxX ?? 50, y: M.bounds?.minY ?? -50 }, { x: M.bounds?.maxX ?? 50, y: M.bounds?.maxY ?? 50 }, { x: M.bounds?.minX ?? -50, y: M.bounds?.maxY ?? 50 }, { x: M.bounds?.minX ?? -50, y: M.bounds?.minY ?? -50 }], strokeColor: \"rgba(255,0,0,0.25)\" }), w \u0026\u0026 w.length \u003e= 2) {\n const e60 = w.map((e61) =\u003e ({ x: e61.x, y: e61.y }));\n e60.push({ ...e60[0] }), N.push({ points: e60, strokeColor: \"rgba(0, 136, 255, 0.95)\" });\n }\n const R10 = Lo(M), T2 = { points: [...M.connections.flatMap((e60) =\u003e e60.pointsToConnect.map((t10) =\u003e ({ ...t10, layer: Bo(t10, M.layerCount), label: `${e60.name} ${t10.pcb_port_id ?? \"\"}` })))], rects: [...(M.obstacles ?? []).filter((e60) =\u003e !e60.isCopperPour).map((e60) =\u003e ({ ...e60, fill: e60.layers?.includes(\"top\") ? \"rgba(255,0,0,0.25)\" : e60.layers?.includes(\"bottom\") ? \"rgba(0,0,255,0.25)\" : \"rgba(255,0,0,0.25)\", layer: jo(e60, M.layerCount), label: R10(e60) }))], lines: N }, E10 = { traceColorMode: this.visualizationTraceColorMode }, A7 = nK({ srj: M, visualizationOptions: E10 }), O10 = pi(T2, A7), k6 = this.preprocessSimpleRouteJsonSolver?.visualize(), D9 = this.globalDrcForceImproveSolver?.visualize(), L10 = this.pipeline9JointDrcRepairSolver?.visualize(), z10 = [O10, k6, n8, o10, e54, t4, i8, r9, s7, a9, c5, l5, h5, d9, u9, P, p9, m9, g10, f10 ? pi(T2, f10) : null, _5, y10, b10, x8, v10, C, D9, L10, I6, S6, this.solved ? pi({ lines: N }, nK({ srj: this.originalSrj, visualizationOptions: E10 }), this.visualizeFinalOutput()) : null].filter(Boolean), B5 = pi(...z10);\n return this.visualizationTraceColorMode === \"net\" ? T7(B5, this.colorMap) : B5;\n }\n visualizeStage(e54) {\n const t4 = e54.visualize();\n return this.visualizationTraceColorMode === \"net\" ? T7(t4, this.colorMap) : t4;\n }\n visualizeFinalOutput() {\n const e54 = this.visualizationTraceColorMode, t4 = this.getOutputSimpleRouteJson();\n return Wo(t4, { traceColorMode: e54 });\n }\n preview() {\n if (this.highDensityRouteSolver) {\n const e54 = [];\n for (let t4 = this.highDensityRouteSolver.routes.length - 1;t4 \u003e= 0; t4--) {\n const n8 = this.highDensityRouteSolver.routes[t4];\n if (e54.push({ points: n8.route.map((e60) =\u003e ({ x: e60.x, y: e60.y })), strokeColor: this.colorMap[n8.connectionName] }), e54.length \u003e 200)\n break;\n }\n return { lines: e54 };\n }\n return this.portPointPathingSolver ? this.portPointPathingSolver.preview() : this.netToPointPairsSolver ? this.netToPointPairsSolver.visualize() : this.escapeViaLocationSolver ? this.escapeViaLocationSolver.visualize() : this.componentTopologyGeneratorSolver ? this.componentTopologyGeneratorSolver.visualize() : this.componentDetectionSolver ? this.componentDetectionSolver.visualize() : this.preprocessSimpleRouteJsonSolver ? this.preprocessSimpleRouteJsonSolver.visualize() : {};\n }\n _getOutputHdRoutes() {\n if (((this.originalSrj.differentialPairs?.length ?? 0) \u003e 0 || (this.originalSrj.buses ?? []).some((e54) =\u003e e54.maxLengthSkew !== undefined)) \u0026\u0026 this.lengthMatchingPostProcessingSolver) {\n const { hdRoutes: e54 } = this.lengthMatchingPostProcessingSolver.getOutput();\n return e54;\n }\n return (this.effortCleanupSolver?.solved ? this.effortCleanupSolver.getOutput() : undefined) ?? this.pipeline9JointDrcRepairSolver?.getOutput() ?? this.globalDrcForceImproveSolver?.getOutput() ?? this.traceWidthSolver?.getHdRoutesWithWidths() ?? this.traceSimplificationSolver?.simplifiedHdRoutes ?? this.highDensityStitchSolver.mergedHdRoutes;\n }\n getOriginalFixedHdRoutes() {\n return (this.originalSrj.traces ?? []).flatMap((e54, t4) =\u003e Vne(e54, t4, this.originalSrj.layerCount, this.viaDiameter, this.connMap));\n }\n getChangedPreloadedTraceSections() {\n return this.portPointPathingSolver?.getOutput().changedPreloadedTraceSections ?? [];\n }\n getPreloadedFixedRouteStateAfterHighDensity() {\n const e54 = this.getOriginalFixedHdRoutes(), t4 = this.getChangedPreloadedTraceSections(), n8 = fne({ traces: this.originalSrj.traces ?? [], fixedHdRoutes: e54, sections: t4 }), o10 = t4.length === 0 ? [] : _ne({ traces: this.originalSrj.traces ?? [], sections: t4, stitchedHdRoutes: this.highDensityStitchSolver?.mergedHdRoutes ?? [], layerCount: this.originalSrj.layerCount }), i8 = new Set(t4.map((e60) =\u003e e60.traceId)), r9 = e54.filter((e60) =\u003e i8.has(this.originalSrj.traces?.[e60.preloadedTraceIndex]?.pcb_trace_id ?? \"\")).map((e60) =\u003e e60.connectionName);\n return { originalFixedRoutes: e54, updatedFixedRoutes: [...this.highDensityRouteSolver?.getUpdatedFixedHdRoutes() ?? n8, ...o10], replacedConnectionNames: new Set([...this.highDensityRouteSolver?.fixedRouteReplacements.keys() ?? [], ...r9]), mutationMasks: new Map([...this.highDensityRouteSolver?.preloadedTraceMutationMasks ?? [], ...o10.map((e60) =\u003e [e60.connectionName, Array(e60.route.length - 1).fill(true)])]) };\n }\n getPreparedMutatedPreloadedTraceSections() {\n const e54 = this.getPreloadedFixedRouteStateAfterHighDensity();\n return Xne({ updatedFixedRoutes: e54.updatedFixedRoutes, regionalMutationMasks: e54.mutationMasks });\n }\n getPreloadedTraceUpdatesAfterHighDensity() {\n const e54 = this.getPreloadedFixedRouteStateAfterHighDensity(), t4 = this.getPreparedMutatedPreloadedTraceSections(), n8 = this.mutatedPreloadedTraceSimplificationSolver?.solved === true ? (({ updatedFixedRoutes: e60, sections: t10, simplifiedHdRoutes: n10 }) =\u003e {\n const o10 = new Set(t10.map((e61) =\u003e e61.connectionName)), i8 = new Map(n10.map((e61) =\u003e [e61.connectionName, e61]));\n if (i8.size !== t10.length || n10.some((e61) =\u003e !o10.has(e61.connectionName)))\n throw new Error(`Pipeline9 trace simplification changed the mutation-section set (expected ${t10.length}, got ${n10.length})`);\n const r9 = new Map, s7 = new Set;\n for (const e61 of t10) {\n const t11 = i8.get(e61.connectionName);\n if (!t11)\n throw new Error(`Pipeline9 trace simplification lost mutation section \"${e61.connectionName}\"`);\n const n11 = t11.route[0], o11 = t11.route.at(-1);\n if (!(n11 \u0026\u0026 o11 \u0026\u0026 kne(n11, e61.section.start.point) \u0026\u0026 kne(o11, e61.section.end.point)))\n throw new Error(`Pipeline9 trace simplification changed mutation-section boundary \"${e61.connectionName}\"`);\n const a9 = Ene(e61.section, t11), c5 = e61.section.sourceRoutes[0];\n s7.add(c5.connectionName);\n for (const t12 of e61.section.sourceRoutes) {\n if (r9.has(t12.connectionName))\n throw new Error(`Pipeline9 attempted to simplify fixed route \"${t12.connectionName}\" more than once`);\n r9.set(t12.connectionName, a9);\n }\n }\n return e60.flatMap((e61) =\u003e {\n const t11 = r9.get(e61.connectionName);\n return t11 ? s7.has(e61.connectionName) ? [t11] : [] : [e61];\n });\n })({ updatedFixedRoutes: t4.normalizedFixedRoutes, sections: t4.sections, simplifiedHdRoutes: this.mutatedPreloadedTraceSimplificationSolver.simplifiedHdRoutes }) : e54.updatedFixedRoutes;\n return (({ originalTraces: e60, originalFixedRoutes: t10, updatedFixedRoutes: n10, replacedConnectionNames: o10, layerCount: i8, defaultViaHoleDiameter: r9, obstacles: s7, connMap: a9 }) =\u003e {\n const c5 = new Map, l5 = new Map;\n for (const e61 of t10) {\n const t11 = c5.get(e61.preloadedTraceIndex) ?? [];\n t11.push(e61), c5.set(e61.preloadedTraceIndex, t11);\n }\n for (const e61 of n10) {\n const t11 = l5.get(e61.preloadedTraceIndex) ?? [];\n t11.push(e61), l5.set(e61.preloadedTraceIndex, t11);\n }\n const h5 = [];\n return { updatedPreloadedTraces: e60.map((e61, t11) =\u003e {\n const n11 = (c5.get(t11) ?? []).sort(one);\n if (!n11.some((e63) =\u003e o10.has(e63.connectionName)))\n return e61;\n const d9 = (l5.get(t11) ?? []).sort(one), u9 = e61.route.some((e63) =\u003e e63.route_type === \"through_obstacle\"), p9 = { ...e61, __replaces_pcb_trace_id: e61.pcb_trace_id, route: u9 ? ane({ trace: e61, originalTraceRoutes: n11, updatedTraceRoutes: d9, layerCount: i8, defaultViaHoleDiameter: r9, obstacles: s7, connMap: a9 }) : rne({ trace: e61, updatedTraceRoutes: d9, layerCount: i8, defaultViaHoleDiameter: r9, obstacles: s7, connMap: a9 }) };\n return h5.push(p9), p9;\n }), mutatedPreloadedTraces: h5 };\n })({ originalTraces: this.originalSrj.traces ?? [], originalFixedRoutes: e54.originalFixedRoutes, updatedFixedRoutes: n8, replacedConnectionNames: e54.replacedConnectionNames, layerCount: this.originalSrj.layerCount, defaultViaHoleDiameter: this.viaHoleDiameter, obstacles: this.originalSrj.obstacles, connMap: this.connMap });\n }\n getSrjWithMaterializedPreloadedTraces() {\n return { ...this.srjWithPointPairs, traces: this.getPreloadedTraceUpdatesAfterHighDensity().updatedPreloadedTraces };\n }\n getUpdatedPreloadedTraces() {\n return this.pipeline9JointDrcRepairSolver?.getUpdatedPreloadedTraces() ?? this.getPreloadedTraceUpdatesAfterHighDensity().updatedPreloadedTraces;\n }\n getMutatedPreloadedTraces() {\n return this.pipeline9JointDrcRepairSolver?.getMutatedPreloadedTraces() ?? this.getPreloadedTraceUpdatesAfterHighDensity().mutatedPreloadedTraces;\n }\n getNewTracesBeforePowerExpansion() {\n if (!this.highDensityRouteSolver)\n throw new Error(\"Cannot get new traces before high-density routing\");\n const e54 = Cte({ connections: this.netToPointPairsSolver?.newConnections ?? [], originalConnections: this.originalSrj.connections, hdRoutes: bne(this._getOutputHdRoutes()), layerCount: this.srj.layerCount, obstacles: this.srj.obstacles, defaultViaHoleDiameter: this.viaHoleDiameter, connMap: this.connMap });\n return cne(e54, this.originalSrj.traces ?? []);\n }\n getPowerTraceExpansionFixedTraces() {\n if (!this.powerTraceExpansionSolver)\n throw new Error(\"Pipeline9 invariant violated: solved pipeline is missing the unconditional power-trace expansion solver\");\n return this.powerTraceExpansionSolver.inputSrj.fixedTraces;\n }\n getOutputSimplifiedPcbTraces() {\n if (!this.solved)\n throw new Error(\"Cannot get output before solving is complete\");\n if (!this.powerTraceExpansionSolver)\n throw new Error(\"Pipeline9 invariant violated: solved pipeline is missing the unconditional power-trace expansion solver\");\n return [...this.getPowerTraceExpansionFixedTraces().filter((e54) =\u003e e54.__replaces_pcb_trace_id !== undefined), ...this.powerTraceExpansionSolver.getOutput()];\n }\n getOutputSimpleRouteJson() {\n if (!this.solved)\n throw new Error(\"Cannot get output before solving is complete\");\n if (!this.powerTraceExpansionSolver)\n throw new Error(\"Pipeline9 invariant violated: solved pipeline is missing the unconditional power-trace expansion solver\");\n const e54 = [...this.getPowerTraceExpansionFixedTraces(), ...this.powerTraceExpansionSolver.getOutput()];\n return { ...this.originalSrj, traces: e54 };\n }\n};\nvar rre = String(\"0.0.1038\");\nvar sre = ({ nodeWithPortPoints: e54, obstacleMargin: t4, traceWidth: n8, viaDiameter: o10 }) =\u003e {\n const i8 = ro(e54), r9 = t4 + Math.max(n8, o10) / 2 + 0.000001;\n return { minX: e54.center.x + 8 * (i8.minX - e54.center.x) - r9, maxX: e54.center.x + 8 * (i8.maxX - e54.center.x) + r9, minY: e54.center.y + 8 * (i8.minY - e54.center.y) - r9, maxY: e54.center.y + 8 * (i8.maxY - e54.center.y) + r9 };\n};\nvar are = (e54, t4) =\u003e {\n const n8 = (e54.ccwRotationDegrees ?? 0) * Math.PI / 180, o10 = Math.abs(Math.cos(n8)), i8 = Math.abs(Math.sin(n8)), r9 = e54.width / 2, s7 = e54.height / 2, a9 = Math.max(r9, r9 * o10 + s7 * i8), c5 = Math.max(s7, r9 * i8 + s7 * o10);\n return e54.center.x - a9 \u003c= t4.maxX \u0026\u0026 e54.center.x + a9 \u003e= t4.minX \u0026\u0026 e54.center.y - c5 \u003c= t4.maxY \u0026\u0026 e54.center.y + c5 \u003e= t4.minY;\n};\nvar cre = (e54, t4) =\u003e {\n for (const n8 of [t4.connectionName, t4.rootConnectionName, t4.portPointId, t4.pcb_port_id, t4.prevPortPointId, t4.nextPortPointId])\n n8 !== undefined \u0026\u0026 e54.add(n8);\n};\nvar lre = (e54, t4) =\u003e Object.fromEntries(Object.entries(e54.netMap).flatMap(([e60, n8]) =\u003e {\n const o10 = n8.filter((e61) =\u003e t4.has(e61));\n return o10.length \u003e 0 || t4.has(e60) ? [[e60, o10]] : [];\n}));\nvar hre = ({ obstacle: e54, connectedTo: t4, preserveRotation: n8 }) =\u003e ({ type: \"rect\", layers: e54.layers, ...e54.zLayers === undefined ? {} : { zLayers: e54.zLayers }, ...e54.__zLayers === undefined ? {} : { __zLayers: e54.__zLayers }, center: e54.center, width: e54.width, height: e54.height, ...n8 \u0026\u0026 e54.ccwRotationDegrees !== undefined ? { ccwRotationDegrees: e54.ccwRotationDegrees } : {}, connectedTo: t4, ...e54.circuitJsonMetadata === undefined ? {} : { circuitJsonMetadata: e54.circuitJsonMetadata } });\nfunction dre({ nodeWithPortPoints: e54, connMap: t4, obstacles: n8, obstacleMargin: o10, traceWidth: i8, viaDiameter: r9 }) {\n const s7 = sre({ nodeWithPortPoints: e54, obstacleMargin: o10, traceWidth: i8, viaDiameter: r9 }), a9 = new Set;\n for (const t10 of e54.portPoints)\n cre(a9, t10);\n for (const t10 of e54.portPointsInPairs ?? [])\n cre(a9, t10[0]), cre(a9, t10[1]);\n const c5 = n8.flatMap((n10) =\u003e {\n if (!are(n10, s7))\n return [];\n const o11 = (({ obstacle: e60, nodeWithPortPoints: t10, connMap: n11 }) =\u003e {\n const o12 = new Set(t10.portPoints.flatMap((e61) =\u003e {\n const t11 = n11.getNetConnectedToId(e61.rootConnectionName ?? e61.connectionName) ?? e61.rootConnectionName ?? e61.connectionName;\n return [e61.connectionName, t11];\n })), i9 = new Set(e60.connectedTo.filter((e61) =\u003e o12.has(e61))), r10 = new Map;\n for (const e61 of o12) {\n const t11 = n11.getNetConnectedToId(e61) ?? e61, o13 = r10.get(t11) ?? [];\n o13.push(e61), r10.set(t11, o13);\n }\n for (const t11 of r10.values()) {\n if ([...i9].some((e61) =\u003e t11.some((t12) =\u003e t12 === e61 || n11.areIdsConnected(t12, e61))))\n continue;\n const o13 = e60.connectedTo.find((e61) =\u003e t11.some((t12) =\u003e t12 === e61 || n11.areIdsConnected(t12, e61)));\n o13 !== undefined \u0026\u0026 i9.add(o13);\n }\n return [...i9];\n })({ obstacle: n10, nodeWithPortPoints: e54, connMap: t4 });\n for (const e60 of o11)\n a9.add(e60);\n return [hre({ obstacle: n10, connectedTo: o11, preserveRotation: true })];\n });\n return { connectivityNetMap: lre(t4, a9), obstacles: c5 };\n}\nvar ure = (...e54) =\u003e {\n const t4 = new Map;\n for (const n8 of e54)\n for (const [e60, o10] of Object.entries(n8)) {\n const n10 = t4.get(e60) ?? new Set;\n for (const e61 of o10)\n n10.add(e61);\n t4.set(e60, n10);\n }\n return Object.fromEntries([...t4].map(([e60, t10]) =\u003e [e60, [...t10]]));\n};\nfunction pre({ nodeWithPortPoints: e54, connMap: t4, colorMap: n8, obstacles: o10, obstacleMargin: i8, traceWidth: r9, viaDiameter: s7 }) {\n const a9 = sre({ nodeWithPortPoints: e54, obstacleMargin: i8, traceWidth: r9, viaDiameter: s7 }), c5 = ((e60) =\u003e [...new Set(e60.portPoints.map((e61) =\u003e e61.connectionName))])(e54), l5 = o10.flatMap((e60) =\u003e {\n if (!are(e60, a9))\n return [];\n const n10 = c5.filter((n11) =\u003e e60.connectedTo.some((e61) =\u003e e61 === n11 || t4.areIdsConnected(n11, e61)));\n return n10.length === 0 ? [] : [hre({ obstacle: e60, connectedTo: n10, preserveRotation: false })];\n }), h5 = new Set;\n for (const t10 of e54.portPoints)\n cre(h5, t10);\n for (const t10 of e54.portPointsInPairs ?? [])\n cre(h5, t10[0]), cre(h5, t10[1]);\n for (const e60 of l5)\n for (const t10 of [e60.circuitJsonMetadata?.pcb_smtpad_id, e60.circuitJsonMetadata?.pcb_plated_hole_id, e60.circuitJsonMetadata?.pcb_port_id, e60.circuitJsonMetadata?.pcb_via_id, ...e60.connectedTo ?? []])\n t10 !== undefined \u0026\u0026 h5.add(t10);\n return { connectivityNetMap: lre(t4, h5), colorMap: Object.fromEntries(Object.entries(n8 ?? {}).filter(([e60]) =\u003e h5.has(e60))), obstacles: l5 };\n}\nvar mre = \"https://hd-cache2.tscircuit.com\";\nvar gre = 310000;\nvar fre = 1835008;\nvar _re = 16777216;\nvar yre = class extends Error {\n constructor(e54, t4) {\n super(t4), this.reason = e54, this.name = \"HdCache2RequestError\";\n }\n};\nvar bre = (e54) =\u003e e54 instanceof Error ? e54.message : String(e54);\nvar xre = new Set([\"pcb_smtpad_id\", \"pcb_plated_hole_id\", \"pcb_port_id\", \"pcb_via_id\", \"source_component_name\", \"source_port_name\"]);\nvar vre = (e54) =\u003e !(!e54 || typeof e54 != \"object\" || Array.isArray(e54)) \u0026\u0026 Object.entries(e54).every(([e60, t4]) =\u003e xre.has(e60) \u0026\u0026 typeof t4 == \"string\");\nvar Ire = (e54, t4) =\u003e Math.abs(e54 - t4) \u003c= 0.000000001 * Math.max(1, Math.abs(e54), Math.abs(t4));\nvar Sre = 0.000001;\nvar Cre = (e54, t4) =\u003e {\n const n8 = t4 === \"ordinary\" ? Sre : 0.001, o10 = new Set;\n for (let i9 = 0;i9 \u003c e54.route.length - 1; i9++) {\n const r9 = e54.route[i9], s7 = e54.route[i9 + 1], a9 = r9.z !== s7.z;\n if (r9.toNextSegmentType === \"through_obstacle\") {\n if (!a9)\n return false;\n continue;\n }\n if (r9.toNextSegmentCircuitJsonMetadata !== undefined)\n return false;\n if (!a9)\n continue;\n const c5 = [], l5 = [];\n for (const [t10, o11] of e54.vias.entries())\n Math.hypot(o11.x - r9.x, o11.y - r9.y) \u003c= n8 \u0026\u0026 c5.push(t10), Math.hypot(o11.x - s7.x, o11.y - s7.y) \u003c= n8 \u0026\u0026 l5.push(t10);\n if (Math.hypot(r9.x - s7.x, r9.y - s7.y) \u003c= Sre) {\n if (c5.length === 0)\n return false;\n for (const e60 of c5)\n o10.add(e60);\n } else {\n if (t4 === \"regional-fallback\")\n return false;\n if (c5.length === 0 == (l5.length === 0))\n return false;\n for (const e60 of [...c5, ...l5])\n o10.add(e60);\n }\n }\n const i8 = e54.route.at(-1);\n return i8.toNextSegmentType === undefined \u0026\u0026 i8.toNextSegmentCircuitJsonMetadata === undefined \u0026\u0026 e54.vias.every((e60, t10) =\u003e o10.has(t10));\n};\nvar Pre = (e54, t4, n8) =\u003e {\n if (!Array.isArray(e54))\n return false;\n const o10 = new Map;\n for (const e60 of t4.nodeWithPortPoints.portPoints) {\n const t10 = o10.get(e60.connectionName) ?? [];\n t10.push(e60), o10.set(e60.connectionName, t10);\n }\n const i8 = new Set(t4.nodeWithPortPoints.availableZ ?? t4.nodeWithPortPoints.portPoints.map((e60) =\u003e e60.z)), r9 = sre({ nodeWithPortPoints: t4.nodeWithPortPoints, obstacleMargin: t4.obstacleMargin, traceWidth: t4.traceWidth, viaDiameter: t4.viaDiameter }), s7 = (e60, t10) =\u003e (o10.get(t10) ?? []).some((t11) =\u003e typeof e60.x == \"number\" \u0026\u0026 Ire(e60.x, t11.x) \u0026\u0026 typeof e60.y == \"number\" \u0026\u0026 Ire(e60.y, t11.y) \u0026\u0026 e60.z === t11.z);\n for (const a10 of e54) {\n if (!a10 || typeof a10 != \"object\")\n return false;\n const e60 = a10;\n if (typeof e60.connectionName != \"string\" || e60.connectionName.length === 0 || !o10.has(e60.connectionName) || typeof e60.traceThickness != \"number\" || !Number.isFinite(e60.traceThickness) || e60.traceThickness \u003c= 0 || typeof e60.viaDiameter != \"number\" || !Number.isFinite(e60.viaDiameter) || e60.viaDiameter \u003c= 0 || !Ire(e60.viaDiameter, t4.viaDiameter) || !Array.isArray(e60.route) || e60.route.length \u003c 2 || !Array.isArray(e60.vias))\n return false;\n for (const t10 of [e60.rootConnectionName, e60.startPcbPortId, e60.endPcbPortId, e60.regionId])\n if (t10 !== undefined \u0026\u0026 typeof t10 != \"string\")\n return false;\n for (const o11 of e60.route) {\n if (!o11 || typeof o11 != \"object\")\n return false;\n const e61 = o11;\n if (typeof e61.x != \"number\" || !Number.isFinite(e61.x) || typeof e61.y != \"number\" || !Number.isFinite(e61.y) || e61.x \u003c r9.minX || e61.x \u003e r9.maxX || e61.y \u003c r9.minY || e61.y \u003e r9.maxY || typeof e61.z != \"number\" || !Number.isInteger(e61.z) || e61.z \u003c 0 || e61.z \u003e= t4.layerCount || n8 === \"ordinary\" \u0026\u0026 !i8.has(e61.z))\n return false;\n if (e61.traceThickness !== undefined \u0026\u0026 (typeof e61.traceThickness != \"number\" || !Number.isFinite(e61.traceThickness) || e61.traceThickness \u003c= 0))\n return false;\n if (e61.pcb_port_id !== undefined \u0026\u0026 typeof e61.pcb_port_id != \"string\")\n return false;\n if (e61.insideJumperPad !== undefined \u0026\u0026 typeof e61.insideJumperPad != \"boolean\")\n return false;\n if (e61.toNextSegmentType !== undefined \u0026\u0026 e61.toNextSegmentType !== \"through_obstacle\")\n return false;\n if (e61.toNextSegmentCircuitJsonMetadata !== undefined \u0026\u0026 !vre(e61.toNextSegmentCircuitJsonMetadata))\n return false;\n }\n const c5 = e60.route;\n if (!(n8 !== \"ordinary\" || s7(c5[0], e60.connectionName) \u0026\u0026 s7(c5.at(-1), e60.connectionName)))\n return false;\n for (const t10 of e60.vias) {\n if (!t10 || typeof t10 != \"object\")\n return false;\n const e61 = t10;\n if (typeof e61.x != \"number\" || !Number.isFinite(e61.x) || typeof e61.y != \"number\" || !Number.isFinite(e61.y) || e61.x \u003c r9.minX || e61.x \u003e r9.maxX || e61.y \u003c r9.minY || e61.y \u003e r9.maxY)\n return false;\n }\n if (!Cre(e60, n8))\n return false;\n if (e60.jumpers !== undefined) {\n if (!Array.isArray(e60.jumpers))\n return false;\n for (const t10 of e60.jumpers) {\n if (!t10 || typeof t10 != \"object\")\n return false;\n const e61 = t10, n10 = e61.start, o11 = e61.end;\n if (e61.route_type !== \"jumper\" || e61.footprint !== \"0603\" \u0026\u0026 e61.footprint !== \"1206\" \u0026\u0026 e61.footprint !== \"1206x4_pair\" || !n10 || typeof n10.x != \"number\" || !Number.isFinite(n10.x) || typeof n10.y != \"number\" || !Number.isFinite(n10.y) || !o11 || typeof o11.x != \"number\" || !Number.isFinite(o11.x) || typeof o11.y != \"number\" || !Number.isFinite(o11.y) || n10.x \u003c r9.minX || n10.x \u003e r9.maxX || n10.y \u003c r9.minY || n10.y \u003e r9.maxY || o11.x \u003c r9.minX || o11.x \u003e r9.maxX || o11.y \u003c r9.minY || o11.y \u003e r9.maxY)\n return false;\n }\n }\n }\n const a9 = e54;\n return n8 === \"ordinary\" ? ((e60, t10) =\u003e {\n const n10 = t10.portPointsInPairs ?? [];\n if (n10.length \u003e 0) {\n for (const [t11, o12] of n10)\n if (!yz(e60, t11.connectionName, fz(t11)).has(fz(o12)))\n return false;\n return true;\n }\n const o11 = new Map;\n for (const e61 of t10.portPoints) {\n const t11 = o11.get(e61.connectionName) ?? [];\n t11.push(e61), o11.set(e61.connectionName, t11);\n }\n for (const [t11, n11] of o11)\n for (const [o12, i9] of Ws(n11))\n if (!yz(e60, t11, fz(o12)).has(fz(i9)))\n return false;\n return true;\n })(a9, t4.nodeWithPortPoints) : ((e60, t10) =\u003e {\n const n10 = (e61, t11) =\u003e {\n if (e61.z !== t11.z)\n return false;\n const n11 = e61.x - t11.x, o12 = e61.y - t11.y;\n return Math.hypot(n11, o12) \u003c= 0.001;\n }, o11 = new Map;\n for (const i10 of e60) {\n const e61 = i10.route.some((e63, t11) =\u003e {\n const n11 = i10.route[t11 + 1];\n return !(n11 === undefined || Ire(e63.x, n11.x) \u0026\u0026 Ire(e63.y, n11.y) \u0026\u0026 e63.z === n11.z);\n }), r11 = i10.route[0], s10 = i10.route.at(-1);\n if (!e61 || !r11 || !s10)\n return false;\n const a10 = t10.portPoints.filter((e63) =\u003e e63.connectionName === i10.connectionName);\n if (!a10.some((e63) =\u003e n10(r11, e63)) || !a10.some((e63) =\u003e n10(s10, e63)))\n return false;\n const c5 = o11.get(i10.connectionName) ?? [];\n c5.push({ start: r11, end: s10 }), o11.set(i10.connectionName, c5);\n }\n const i9 = (e61, t11, i10) =\u003e {\n if (n10(t11, i10))\n return true;\n const r11 = o11.get(e61) ?? [], s10 = [], a10 = new Set;\n for (const [e63, o12] of r11.entries())\n (n10(t11, o12.start) || n10(t11, o12.end)) \u0026\u0026 (s10.push(e63), a10.add(e63));\n for (;s10.length \u003e 0; ) {\n const e63 = r11[s10.pop()];\n if (n10(i10, e63.start) || n10(i10, e63.end))\n return true;\n for (const [t12, o12] of r11.entries())\n a10.has(t12) || (n10(e63.start, o12.start) || n10(e63.start, o12.end) || n10(e63.end, o12.start) || n10(e63.end, o12.end)) \u0026\u0026 (a10.add(t12), s10.push(t12));\n }\n return false;\n }, r10 = t10.portPointsInPairs ?? [];\n if (r10.length \u003e 0)\n return r10.every(([e61, t11]) =\u003e i9(e61.connectionName, e61, t11));\n const s9 = new Map;\n for (const e61 of t10.portPoints) {\n const t11 = s9.get(e61.connectionName) ?? [];\n t11.push(e61), s9.set(e61.connectionName, t11);\n }\n return [...s9].every(([, e61]) =\u003e Ws(e61).every(([e63, t11]) =\u003e i9(e63.connectionName, e63, t11)));\n })(a9, t4.nodeWithPortPoints);\n};\nvar Mre = class {\n constructor(e54, t4 = mre, n8 = {}) {\n this.autorouterVersion = e54, this.serverUrl = t4;\n const { cacheVersion: o10 } = n8;\n if (o10 !== undefined \u0026\u0026 o10.trim().length === 0)\n throw new Error(\"hd-cache2 cacheVersion must not be empty\");\n this.cacheVersion = o10;\n }\n cacheVersion;\n stats = { batchRequestsStarted: 0, batchRequestsCompleted: 0, batchItemsStarted: 0, batchBodyBytesStarted: 0, batchMaxBodyBytes: 0, batchCacheMisses: 0, singleRequestsStarted: 0, batchInvalidLines: 0, batchUnknownRequestIds: 0, batchDuplicateRequestIds: 0 };\n solveMany(e54) {\n const t4 = e54.map((e60, t10) =\u003e this.createPendingSolve(String(t10), e60)), n8 = t4.filter((e60) =\u003e e60.serializedItem !== null), { batches: o10, singletonSolves: i8 } = this.prepareBatches(n8);\n for (const e60 of o10)\n this.fetchBatch(e60);\n for (const e60 of i8)\n this.launchSingleSolve(e60);\n return t4.map((e60) =\u003e e60.promise);\n }\n createPendingSolve(e54, t4) {\n let n8;\n const o10 = { requestId: e54, input: t4, serializedItem: null, promise: new Promise((e60) =\u003e {\n n8 = e60;\n }), resolve: n8, settled: false, singleSolveStarted: false };\n try {\n o10.serializedItem = JSON.stringify({ requestId: e54, input: t4 });\n } catch (e60) {\n this.settleWithFallback(o10, \"request_serialization_error\", bre(e60));\n }\n return o10;\n }\n settle(e54, t4) {\n e54.settled || (e54.settled = true, e54.resolve(t4));\n }\n settleWithFallback(e54, t4, n8) {\n this.settle(e54, { kind: \"local-fallback\", reason: t4, error: n8 });\n }\n parseSuccessfulResponse(e54, t4) {\n if (!e54 || typeof e54 != \"object\" || Array.isArray(e54))\n throw new yre(\"invalid_response\", \"hd-cache2 returned a non-object response\");\n const n8 = e54;\n if (n8.ok !== true)\n throw new yre(\"remote_error\", typeof n8.message == \"string\" ? n8.message : \"hd-cache2 returned an unsuccessful response\");\n if (n8.autorouterVersion !== this.autorouterVersion)\n throw new yre(\"version_mismatch\", `hd-cache2 returned autorouter version ${String(n8.autorouterVersion)}, expected ${this.autorouterVersion}`);\n if (n8.cacheVersion !== this.cacheVersion)\n throw new yre(\"cache_version_mismatch\", `hd-cache2 returned cache version ${String(n8.cacheVersion)}, expected ${String(this.cacheVersion)}`);\n if (n8.source !== \"cache\" \u0026\u0026 n8.source !== \"solver\")\n throw new yre(\"invalid_response\", \"hd-cache2 returned an invalid cache source\");\n if (n8.solutionStage !== \"ordinary\" \u0026\u0026 n8.solutionStage !== \"regional-fallback\")\n throw new yre(\"invalid_response\", \"hd-cache2 returned an invalid solution stage\");\n if (n8.solutionStage === \"regional-fallback\" \u0026\u0026 (!t4.enableRegionalFallback || typeof n8.ordinaryFailure != \"string\" || n8.ordinaryFailure.length === 0))\n throw new yre(\"invalid_response\", \"hd-cache2 returned invalid regional fallback metadata\");\n if (n8.solutionStage === \"ordinary\" \u0026\u0026 Object.prototype.hasOwnProperty.call(n8, \"ordinaryFailure\"))\n throw new yre(\"invalid_response\", \"hd-cache2 returned regional metadata on an ordinary result\");\n if (n8.solutionStage === \"ordinary\" \u0026\u0026 n8.status === \"failed\" \u0026\u0026 t4.enableRegionalFallback)\n throw new yre(\"invalid_response\", \"hd-cache2 returned an intermediate ordinary failure\");\n if (n8.status === \"solved\" \u0026\u0026 Pre(n8.routes, t4, n8.solutionStage))\n return n8;\n if (n8.status === \"failed\" \u0026\u0026 typeof n8.error == \"string\" \u0026\u0026 n8.error.length \u003e 0)\n return n8;\n throw new yre(\"invalid_response\", \"hd-cache2 returned an invalid solve result\");\n }\n parseBatchCacheMiss(e54) {\n if (e54.ok !== false || e54.code !== \"CACHE_MISS\")\n return null;\n if (e54.autorouterVersion !== this.autorouterVersion)\n throw new yre(\"version_mismatch\", `hd-cache2 returned autorouter version ${String(e54.autorouterVersion)}, expected ${this.autorouterVersion}`);\n if (e54.cacheVersion !== this.cacheVersion)\n throw new yre(\"cache_version_mismatch\", `hd-cache2 returned cache version ${String(e54.cacheVersion)}, expected ${String(this.cacheVersion)}`);\n if (typeof e54.message != \"string\")\n throw new yre(\"invalid_response\", \"hd-cache2 returned an invalid cache miss response\");\n return e54;\n }\n async fetchSingle(e54) {\n const t4 = new AbortController;\n let n8 = false;\n const o10 = setTimeout(() =\u003e {\n n8 = true, t4.abort(new Error(\"hd-cache2 transport timed out after 310000ms\"));\n }, gre);\n o10.unref?.();\n try {\n const n10 = { autorouterVersion: this.autorouterVersion, ...this.cacheVersion === undefined ? {} : { cacheVersion: this.cacheVersion }, input: e54.input };\n let o11;\n try {\n o11 = JSON.stringify(n10);\n } catch (e60) {\n throw new yre(\"request_serialization_error\", bre(e60));\n }\n const r9 = await fetch((i8 = this.serverUrl, /\\/solve\\/?$/.test(i8) ? i8.replace(/\\/+$/, \"\") : `${i8.replace(/\\/+$/, \"\")}/solve`), { method: \"POST\", headers: { accept: \"application/json\", \"content-type\": \"application/json\" }, body: o11, signal: t4.signal }), s7 = await r9.text();\n let a9 = null;\n try {\n a9 = s7 ? JSON.parse(s7) : null;\n } catch {\n if (!r9.ok)\n throw new yre(\"http_error\", `hd-cache2 request failed with status ${r9.status}`);\n throw new yre(\"invalid_json\", `hd-cache2 returned invalid JSON with status ${r9.status}`);\n }\n if (!r9.ok) {\n const e60 = a9 \u0026\u0026 typeof a9 == \"object\" \u0026\u0026 \"message\" in a9 \u0026\u0026 typeof a9.message == \"string\" ? a9.message : `hd-cache2 request failed with status ${r9.status}`;\n throw new yre(\"http_error\", e60);\n }\n this.settle(e54, { kind: \"remote\", response: this.parseSuccessfulResponse(a9, e54.input) });\n } catch (t10) {\n const o11 = t10 instanceof yre ? t10.reason : n8 ? \"transport_timeout\" : \"transport_error\";\n this.settleWithFallback(e54, o11, bre(t10));\n } finally {\n clearTimeout(o10);\n }\n var i8;\n }\n launchSingleSolve(e54) {\n e54.singleSolveStarted || e54.settled || (e54.singleSolveStarted = true, this.stats.singleRequestsStarted += 1, this.fetchSingle(e54));\n }\n handleBatchResponseLine(e54, t4, n8) {\n if (e54.trim().length === 0)\n return;\n if (e54.length \u003e _re)\n throw new yre(\"response_too_large\", \"hd-cache2 returned an oversized batch result line\");\n let o10;\n try {\n o10 = JSON.parse(e54);\n } catch {\n return void (this.stats.batchInvalidLines += 1);\n }\n if (!o10 || typeof o10 != \"object\" || Array.isArray(o10))\n return void (this.stats.batchInvalidLines += 1);\n const i8 = o10, r9 = i8.requestId;\n if (typeof r9 != \"string\")\n return void (this.stats.batchInvalidLines += 1);\n const s7 = t4.get(r9);\n if (s7)\n if (n8.has(r9))\n this.stats.batchDuplicateRequestIds += 1;\n else {\n n8.add(r9);\n try {\n if (this.parseBatchCacheMiss(i8))\n return this.stats.batchCacheMisses += 1, void this.launchSingleSolve(s7);\n this.settle(s7, { kind: \"remote\", response: this.parseSuccessfulResponse(i8, s7.input) });\n } catch (e60) {\n this.stats.batchInvalidLines += 1, this.settleWithFallback(s7, e60 instanceof yre ? e60.reason : \"invalid_response\", bre(e60));\n }\n }\n else\n this.stats.batchUnknownRequestIds += 1;\n }\n async readBatchResponse(e54, t4) {\n if (!e54.body)\n throw new yre(\"invalid_response\", \"hd-cache2 returned an empty batch response body\");\n const n8 = new Map(t4.items.map((e60) =\u003e [e60.requestId, e60])), o10 = new Set, i8 = new TextDecoder, r9 = e54.body.getReader();\n let s7 = \"\";\n for (;o10.size \u003c t4.items.length; ) {\n const { done: e60, value: t10 } = await r9.read();\n if (s7 += i8.decode(t10, { stream: !e60 }), s7.length \u003e _re \u0026\u0026 !s7.includes(`\n`))\n throw new yre(\"response_too_large\", \"hd-cache2 returned an oversized unterminated batch result line\");\n let a9 = s7.indexOf(`\n`);\n for (;a9 \u003e= 0; ) {\n const e61 = s7.slice(0, a9);\n s7 = s7.slice(a9 + 1), this.handleBatchResponseLine(e61, n8, o10), a9 = s7.indexOf(`\n`);\n }\n if (e60) {\n s7.trim().length \u003e 0 \u0026\u0026 this.handleBatchResponseLine(s7, n8, o10);\n break;\n }\n }\n if (o10.size !== t4.items.length)\n for (const e60 of t4.items)\n o10.has(e60.requestId) || this.settleWithFallback(e60, \"missing_response\", `hd-cache2 batch ended without result ${e60.requestId}`);\n else\n await r9.cancel().catch(() =\u003e {});\n }\n async fetchBatch(e54) {\n const t4 = new AbortController;\n let n8 = false;\n const o10 = setTimeout(() =\u003e {\n n8 = true, t4.abort(new Error(\"hd-cache2 batch transport timed out after 310000ms\"));\n }, gre);\n o10.unref?.(), this.stats.batchRequestsStarted += 1, this.stats.batchItemsStarted += e54.items.length, this.stats.batchBodyBytesStarted += e54.bodyBytes, this.stats.batchMaxBodyBytes = Math.max(this.stats.batchMaxBodyBytes, e54.bodyBytes);\n try {\n const n10 = await fetch(((e60) =\u003e {\n const t10 = e60.replace(/\\/+$/, \"\");\n return /\\/solve-batch$/.test(t10) ? t10 : /\\/solve$/.test(t10) ? t10.replace(/\\/solve$/, \"/solve-batch\") : `${t10}/solve-batch`;\n })(this.serverUrl), { method: \"POST\", headers: { accept: \"application/x-ndjson\", \"content-type\": \"application/json\" }, body: e54.body, signal: t4.signal });\n if (!n10.ok) {\n const e60 = await n10.text().catch(() =\u003e \"\");\n let t10 = `hd-cache2 batch request failed with status ${n10.status}`;\n try {\n const n11 = e60 ? JSON.parse(e60) : null;\n n11 \u0026\u0026 typeof n11 == \"object\" \u0026\u0026 \"message\" in n11 \u0026\u0026 typeof n11.message == \"string\" \u0026\u0026 (t10 = n11.message);\n } catch {}\n throw new yre(\"http_error\", t10);\n }\n await this.readBatchResponse(n10, e54);\n } catch (t10) {\n const o11 = t10 instanceof yre ? t10.reason : n8 ? \"transport_timeout\" : \"transport_error\";\n for (const n10 of e54.items)\n n10.singleSolveStarted || this.settleWithFallback(n10, o11, bre(t10));\n } finally {\n clearTimeout(o10), this.stats.batchRequestsCompleted += 1;\n }\n }\n prepareBatches(e54) {\n const t4 = new TextEncoder, n8 = this.cacheVersion === undefined ? \"\" : `,\"cacheVersion\":${JSON.stringify(this.cacheVersion)}`, o10 = `{\"autorouterVersion\":${JSON.stringify(this.autorouterVersion)}${n8},\"items\":[`, i8 = t4.encode(o10 + \"]}\").byteLength, r9 = [], s7 = [];\n let a9 = [], c5 = i8;\n const l5 = () =\u003e {\n a9.length !== 0 \u0026\u0026 (r9.push({ body: `${o10}${a9.map((e60) =\u003e e60.serializedItem).join(\",\")}]}`, bodyBytes: c5, items: a9 }), a9 = [], c5 = i8);\n };\n for (const n10 of e54) {\n const e60 = t4.encode(n10.serializedItem).byteLength, o11 = a9.length === 0 ? 0 : 1;\n i8 + e60 \u003e fre ? (l5(), s7.push(n10)) : ((a9.length \u003e= 100 || c5 + o11 + e60 \u003e fre) \u0026\u0026 l5(), a9.push(n10), c5 += (a9.length === 1 ? 0 : 1) + e60);\n }\n return l5(), { batches: r9, singletonSolves: s7 };\n }\n};\nvar wre = \"ordinary_then_regional_without_fixed_copper_v1\";\nvar Nre = class extends Loe {\n autorouterVersion;\n hdCache2ServerUrl;\n hdCache2CacheVersion;\n requestTimeoutMs;\n hdCache2Client;\n launchedRemoteSolves = false;\n waitingForRemoteNode = null;\n remoteRequestByNode = new Map;\n remoteResultByNode = new Map;\n logicallyTimedOutNodes = new Set;\n constructor({ autorouterVersion: e54, hdCache2ServerUrl: t4, hdCache2CacheVersion: n8, requestTimeoutMs: o10, ...i8 }) {\n if (super(i8), i8.effort !== 1)\n throw new Error(`Pipeline9 networked high-density routing requires effort=1, received ${i8.effort}`);\n if (this.requestTimeoutMs = o10 ?? 30000, !Number.isFinite(this.requestTimeoutMs) || this.requestTimeoutMs \u003c= 0)\n throw new Error(`Pipeline9 network request timeout must be a positive number, received ${this.requestTimeoutMs}`);\n this.autorouterVersion = e54, this.hdCache2ServerUrl = t4 ?? mre, this.hdCache2CacheVersion = n8, this.hdCache2Client = new Mre(this.autorouterVersion, this.hdCache2ServerUrl, { cacheVersion: n8 }), this.pendingEffects = [], this.stats = { ...this.stats, remoteRequestsStarted: 0, remoteRequestsCompleted: 0, remoteBatchRequestsStarted: 0, remoteBatchRequestsCompleted: 0, remoteBatchItemsStarted: 0, remoteBatchBodyBytesStarted: 0, remoteBatchMaxBodyBytes: 0, remoteBatchCacheMisses: 0, remoteSingleRequestsStarted: 0, remoteBatchInvalidLines: 0, remoteBatchUnknownRequestIds: 0, remoteBatchDuplicateRequestIds: 0, remoteCacheHits: 0, remoteSolverResults: 0, remoteSolvedResults: 0, remoteFailedResults: 0, remoteOrdinaryResults: 0, remoteRegionalFallbackResults: 0, remoteRegionalFallbackResultsApplied: 0, remoteRegionalFallbackResultsDeferredToLocal: 0, remoteTransportFallbacks: 0, remoteLogicalTimeoutFallbacks: 0, remoteFallbackReasonCounts: {} };\n }\n getSolverName() {\n return \"Pipeline9NetworkedHighDensitySolver\";\n }\n async waitForAllRemoteRequests() {\n const e54 = [...this.remoteRequestByNode.values()];\n e54.length !== 0 ? (await Promise.all(e54.map(({ promise: e60 }) =\u003e e60)), this.syncClientStats()) : this.syncClientStats();\n }\n createNodeInput(e54) {\n const t4 = this.enableRegionalFallback ? dre({ nodeWithPortPoints: e54, connMap: this.connMap, obstacles: this.obstacles, obstacleMargin: this.obstacleMargin, traceWidth: this.traceWidth, viaDiameter: this.viaDiameter }) : { connectivityNetMap: {}, obstacles: [] }, n8 = pre({ nodeWithPortPoints: e54, connMap: this.connMap, colorMap: this.colorMap, obstacles: this.enableRegionalFallback ? t4.obstacles : this.obstacles, obstacleMargin: this.obstacleMargin, traceWidth: this.traceWidth, viaDiameter: this.viaDiameter });\n return { solvePolicy: wre, enableRegionalFallback: this.enableRegionalFallback, nodeWithPortPoints: e54, connectivityNetMap: ure(n8.connectivityNetMap, t4.connectivityNetMap), colorMap: n8.colorMap, viaDiameter: this.viaDiameter, traceWidth: this.traceWidth, obstacleMargin: this.obstacleMargin, effort: 1, obstacles: n8.obstacles, boardGeometry: this.boardGeometry, regionalObstacles: t4.obstacles, layerCount: this.layerCount, nodePf: this.nodePfById.get(e54.capacityMeshNodeId) ?? null };\n }\n syncClientStats() {\n const e54 = this.hdCache2Client.stats;\n this.stats.remoteBatchRequestsStarted = e54.batchRequestsStarted, this.stats.remoteBatchRequestsCompleted = e54.batchRequestsCompleted, this.stats.remoteBatchItemsStarted = e54.batchItemsStarted, this.stats.remoteBatchBodyBytesStarted = e54.batchBodyBytesStarted, this.stats.remoteBatchMaxBodyBytes = e54.batchMaxBodyBytes, this.stats.remoteBatchCacheMisses = e54.batchCacheMisses, this.stats.remoteSingleRequestsStarted = e54.singleRequestsStarted, this.stats.remoteBatchInvalidLines = e54.batchInvalidLines, this.stats.remoteBatchUnknownRequestIds = e54.batchUnknownRequestIds, this.stats.remoteBatchDuplicateRequestIds = e54.batchDuplicateRequestIds;\n }\n recordFallbackReason(e54) {\n const t4 = this.stats.remoteFallbackReasonCounts;\n t4[e54] = (t4[e54] ?? 0) + 1;\n }\n trackRemoteSolve(e54, t4) {\n const n8 = performance.now() + this.requestTimeoutMs;\n this.stats.remoteRequestsStarted += 1;\n const o10 = t4.then((t10) =\u003e {\n const n10 = this.logicallyTimedOutNodes.has(e54);\n n10 || this.remoteResultByNode.set(e54, t10), t10.kind === \"remote\" ? (t10.response.source === \"cache\" \u0026\u0026 (this.stats.remoteCacheHits += 1), t10.response.source === \"solver\" \u0026\u0026 (this.stats.remoteSolverResults += 1), t10.response.status === \"solved\" ? this.stats.remoteSolvedResults += 1 : this.stats.remoteFailedResults += 1) : n10 || (this.stats.remoteTransportFallbacks += 1, this.recordFallbackReason(t10.reason)), this.stats.remoteRequestsCompleted += 1, this.syncClientStats();\n });\n this.remoteRequestByNode.set(e54, { promise: o10, deadlineAt: n8 });\n }\n launchRemoteSolves() {\n const e54 = [], t4 = [...this.unsolvedNodePortPoints].reverse();\n for (const n10 of t4)\n try {\n e54.push({ node: n10, input: this.createNodeInput(n10) });\n } catch (e60) {\n this.trackRemoteSolve(n10, Promise.resolve({ kind: \"local-fallback\", reason: \"request_serialization_error\", error: e60 instanceof Error ? e60.message : String(e60) }));\n }\n const n8 = this.hdCache2Client.solveMany(e54.map(({ input: e60 }) =\u003e e60));\n for (const [t10, o10] of n8.entries())\n this.trackRemoteSolve(e54[t10].node, o10);\n this.syncClientStats();\n }\n async waitForCurrentRemoteNode(e54, t4) {\n const n8 = t4.deadlineAt - performance.now();\n if (n8 \u003c= 0)\n return void this.recordLogicalTimeout(e54);\n let o10;\n const i8 = await Promise.race([t4.promise.then(() =\u003e \"request-settled\"), new Promise((e60) =\u003e {\n o10 = setTimeout(() =\u003e e60(\"logical-timeout\"), n8);\n })]);\n o10 !== undefined \u0026\u0026 clearTimeout(o10), i8 === \"logical-timeout\" \u0026\u0026 this.recordLogicalTimeout(e54);\n }\n recordLogicalTimeout(e54) {\n this.logicallyTimedOutNodes.add(e54), this.stats.remoteLogicalTimeoutFallbacks += 1, this.stats.remoteTransportFallbacks += 1, this.recordFallbackReason(\"logical_timeout\");\n }\n startRegularSolver(e54) {\n const t4 = this.remoteResultByNode.get(e54);\n if (!t4) {\n const t10 = this.remoteRequestByNode.get(e54);\n if (t10) {\n this.waitingForRemoteNode = e54;\n const n8 = this.waitForCurrentRemoteNode(e54, t10);\n n8.then(() =\u003e {\n this.waitingForRemoteNode === e54 \u0026\u0026 (this.pendingEffects = []);\n });\n const o10 = { name: `hd-cache2:${e54.capacityMeshNodeId}`, promise: n8 };\n return void (this.pendingEffects = [o10]);\n }\n return void super.startRegularSolver(e54);\n }\n this.applyRemoteResultToRegularNode(e54, t4);\n }\n applyRemoteResultToRegularNode(e54, t4) {\n if (t4.kind !== \"local-fallback\") {\n if (this.stats.regularNodeCount = Number(this.stats.regularNodeCount ?? 0) + 1, this.activeNode = e54, t4.response.solutionStage === \"regional-fallback\") {\n if (this.stats.remoteRegionalFallbackResults += 1, !this.canUseNoFixedCopperRegionalResult(e54))\n return this.stats.remoteRegionalFallbackResultsDeferredToLocal += 1, void this.finishRegularSolverFailure(t4.response.ordinaryFailure);\n this.stats.remoteRegionalFallbackResultsApplied += 1, this.stats.fallbackNodeCount = Number(this.stats.fallbackNodeCount ?? 0) + 1;\n } else\n this.stats.remoteOrdinaryResults += 1;\n if (t4.response.status === \"failed\")\n return this.error = t4.response.error, this.failed = true, void (this.activeNode = null);\n this.finishActiveNode(t4.response.routes);\n } else\n super.startRegularSolver(e54);\n }\n canUseNoFixedCopperRegionalResult(e54) {\n const t4 = { ...koe(e54, this.connMap), availableZ: Array.from({ length: this.layerCount }, (e60, t10) =\u003e t10) }, n8 = Rne(t4, this.getUpdatedFixedHdRoutes());\n return n8.fixedRouteSectionsByConnectionName.size === 0 \u0026\u0026 n8.fixedObstacleRoutes.length === 0;\n }\n _step() {\n if (this.syncClientStats(), this.launchedRemoteSolves || (this.launchedRemoteSolves = true, this.launchRemoteSolves()), this.waitingForRemoteNode) {\n const e54 = this.waitingForRemoteNode;\n if (this.logicallyTimedOutNodes.has(e54))\n return this.waitingForRemoteNode = null, this.pendingEffects = [], void super.startRegularSolver(e54);\n const t4 = this.remoteResultByNode.get(e54);\n if (!t4)\n return;\n return this.waitingForRemoteNode = null, this.pendingEffects = [], void this.applyRemoteResultToRegularNode(e54, t4);\n }\n super._step();\n }\n};\nfunction Are(e54) {\n const t4 = `${e54.connectionName}:source-${e54.sourcePointIndex}`;\n return { boundaryExitPointId: `fanout-exit:${t4}`, planeExitPointId: `fanout-plane:${t4}`, traceId: `fanout:${t4}`, viaObstacleId: `fanout-via:${t4}`, planeEndpointPointId: `fanout-plane-endpoint-point:${t4}`, planeEndpointTraceId: `fanout-plane-endpoint:${t4}`, planeEndpointViaObstacleId: `fanout-plane-endpoint-via:${t4}` };\n}\nfunction Ore(e54, t4, n8 = false) {\n const o10 = n8 ? e54.planeEndpointVia : e54.via;\n if (!o10)\n return null;\n const i8 = o10.spanLayers.map((n10) =\u003e {\n const o11 = t4.indexOf(n10);\n if (o11 \u003c 0)\n throw new Error(`FanoutSolver: via for \"${e54.connectionName}\" uses unknown layer \"${n10}\"`);\n return o11;\n }), r9 = Are(e54);\n return { obstacleId: n8 ? r9.planeEndpointViaObstacleId : r9.viaObstacleId, type: \"rect\", center: o10.center, width: o10.diameter, height: o10.diameter, layers: o10.spanLayers, zLayers: i8, __zLayers: i8, connectedTo: [e54.connectionName, e54.trace.pcb_trace_id] };\n}\nfunction kre(e54) {\n const { inputSrj: t4, plans: n8, layerNames: o10 } = e54, i8 = t4.connections.map((e60) =\u003e ({ ...e60, pointsToConnect: e60.pointsToConnect.map((e61) =\u003e ({ ...e61 })) })), r9 = [], s7 = new Set;\n for (const e60 of n8) {\n const t10 = i8[e60.connectionIndex];\n if (!t10)\n throw new Error(`FanoutSolver: output connection index ${e60.connectionIndex} is missing`);\n const n10 = Are(e60);\n t10.pointsToConnect[e60.sourcePointIndex] = { x: e60.exitPoint.x, y: e60.exitPoint.y, layer: e60.targetLayer, pointId: e60.termination.type === \"plane\" ? n10.planeExitPointId : n10.boundaryExitPointId }, e60.termination.type === \"plane\" \u0026\u0026 s7.add(e60.connectionName);\n const a10 = Ore(e60, o10);\n a10 \u0026\u0026 r9.push(a10);\n const c9 = Ore(e60, o10, true);\n c9 \u0026\u0026 r9.push(c9);\n }\n const a9 = n8.flatMap((e60) =\u003e [e60.trace, ...e60.planeEndpointTrace ? [e60.planeEndpointTrace] : []]), c5 = a9.flatMap((e60) =\u003e e60.route.filter((e61) =\u003e (\"x\" in e61) \u0026\u0026 (\"y\" in e61))), l5 = Math.max(t4.defaultObstacleMargin ?? 0, t4.minTraceWidth), h5 = c5.length === 0 ? { ...t4.bounds } : { minX: Math.min(t4.bounds.minX, ...c5.map((e60) =\u003e e60.x - l5)), maxX: Math.max(t4.bounds.maxX, ...c5.map((e60) =\u003e e60.x + l5)), minY: Math.min(t4.bounds.minY, ...c5.map((e60) =\u003e e60.y - l5)), maxY: Math.max(t4.bounds.maxY, ...c5.map((e60) =\u003e e60.y + l5)) };\n return { ...t4, fanoutPlaneConnectivity: n8.flatMap((e60) =\u003e e60.termination.type === \"plane\" ? [{ connectionName: e60.connectionName, layer: e60.termination.layer }] : []), bounds: h5, connections: i8.filter((e60) =\u003e !s7.has(e60.name)), buses: t4.buses?.map((e60) =\u003e ({ ...e60, connectionNames: e60.connectionNames.filter((e61) =\u003e !s7.has(e61)) })).filter((e60) =\u003e e60.connectionNames.length \u003e 0), obstacles: [...t4.obstacles.map((e60) =\u003e ({ ...e60, center: { ...e60.center }, layers: [...e60.layers], connectedTo: [...e60.connectedTo] })), ...r9], traces: [...(t4.traces ?? []).map((e60) =\u003e ({ ...e60, route: e60.route.map((e61) =\u003e ({ ...e61 })) })), ...a9] };\n}\nvar Dre = 0.000000001;\nfunction Lre(e54) {\n return e54.shape === \"circle\";\n}\nfunction zre(e54, t4) {\n const n8 = -(t4.ccwRotationDegrees ?? 0) * Math.PI / 180, o10 = e54.x - t4.center.x, i8 = e54.y - t4.center.y;\n return { x: o10 * Math.cos(n8) - i8 * Math.sin(n8), y: o10 * Math.sin(n8) + i8 * Math.cos(n8) };\n}\nfunction Bre(e54, t4) {\n return Math.hypot(e54.x - t4.x, e54.y - t4.y);\n}\nfunction Fre(e54, t4, n8) {\n const o10 = n8.x - t4.x, i8 = n8.y - t4.y, r9 = o10 * o10 + i8 * i8, s7 = r9 \u003c Dre ? 0 : ((e54.x - t4.x) * o10 + (e54.y - t4.y) * i8) / r9, a9 = Math.max(0, Math.min(1, s7));\n return Math.hypot(e54.x - (t4.x + a9 * o10), e54.y - (t4.y + a9 * i8));\n}\nfunction jre(e54, t4, n8) {\n return (t4.x - e54.x) * (n8.y - e54.y) - (t4.y - e54.y) * (n8.x - e54.x);\n}\nfunction $re(e54, t4, n8, o10) {\n return function(e60, t10, n10, o11) {\n const i8 = jre(n10, o11, e60), r9 = jre(n10, o11, t10), s7 = jre(e60, t10, n10), a9 = jre(e60, t10, o11);\n return (i8 \u003e 0 \u0026\u0026 r9 \u003c 0 || i8 \u003c 0 \u0026\u0026 r9 \u003e 0) \u0026\u0026 (s7 \u003e 0 \u0026\u0026 a9 \u003c 0 || s7 \u003c 0 \u0026\u0026 a9 \u003e 0);\n }(e54, t4, n8, o10) ? 0 : Math.min(Fre(e54, n8, o10), Fre(t4, n8, o10), Fre(n8, e54, t4), Fre(o10, e54, t4));\n}\nfunction Yre(e54, t4, n8 = 0.000000001) {\n if (Lre(t4))\n return Bre(e54, t4.center) \u003c= t4.width / 2 + n8;\n const o10 = zre(e54, t4);\n return Math.abs(o10.x) \u003c= t4.width / 2 + n8 \u0026\u0026 Math.abs(o10.y) \u003c= t4.height / 2 + n8;\n}\nfunction Xre(e54, t4) {\n if (Lre(t4))\n return Math.max(0, Bre(e54, t4.center) - t4.width / 2);\n const n8 = zre(e54, t4), o10 = Math.max(Math.abs(n8.x) - t4.width / 2, 0), i8 = Math.max(Math.abs(n8.y) - t4.height / 2, 0);\n return Math.hypot(o10, i8);\n}\nfunction Hre(e54, t4) {\n if (Lre(t4))\n return Math.max(0, Fre(t4.center, e54.start, e54.end) - t4.width / 2);\n const n8 = zre(e54.start, t4), o10 = zre(e54.end, t4);\n if (Math.abs(n8.x) \u003c= t4.width / 2 + Dre \u0026\u0026 Math.abs(n8.y) \u003c= t4.height / 2 + Dre)\n return 0;\n if (Math.abs(o10.x) \u003c= t4.width / 2 + Dre \u0026\u0026 Math.abs(o10.y) \u003c= t4.height / 2 + Dre)\n return 0;\n const i8 = -t4.width / 2, r9 = t4.width / 2, s7 = -t4.height / 2, a9 = t4.height / 2, c5 = [{ x: i8, y: s7 }, { x: r9, y: s7 }, { x: r9, y: a9 }, { x: i8, y: a9 }];\n let l5 = Number.POSITIVE_INFINITY;\n for (let e60 = 0;e60 \u003c c5.length; e60++)\n l5 = Math.min(l5, $re(n8, o10, c5[e60], c5[(e60 + 1) % c5.length]));\n return l5;\n}\nfunction Vre(e54, t4, n8) {\n if (e54.layer !== t4.layer)\n return true;\n const o10 = (e54.width + t4.width) / 2 + n8;\n return $re(e54.start, e54.end, t4.start, t4.end) \u003e= o10 - Dre;\n}\nfunction Wre(e54) {\n if (!Number.isInteger(e54) || e54 \u003c 1)\n throw new Error(`FanoutSolver: layerCount must be a positive integer, received ${e54}`);\n return e54 === 1 ? [\"top\"] : e54 === 2 ? [\"top\", \"bottom\"] : [\"top\", ...Array.from({ length: e54 - 2 }, (e60, t4) =\u003e `inner${t4 + 1}`), \"bottom\"];\n}\nfunction Gre(e54, t4, n8) {\n const o10 = n8.indexOf(e54), i8 = n8.indexOf(t4);\n if (o10 \u003c 0 || i8 \u003c 0)\n throw new Error(`FanoutSolver: cannot build via span from \"${e54}\" to \"${t4}\"`);\n const r9 = Math.min(o10, i8), s7 = Math.max(o10, i8);\n return n8.slice(r9, s7 + 1);\n}\nvar Ure = new WeakMap;\nfunction Zre(e54) {\n return e54.netConnectionName ?? e54.rootConnectionName ?? e54.name;\n}\nfunction qre(e54, t4, n8) {\n if (!t4)\n return false;\n const o10 = e54.get(t4) ?? new Set, i8 = o10.size;\n return o10.add(n8), e54.set(t4, o10), o10.size !== i8;\n}\nfunction Jre(e54, t4) {\n const n8 = new Set;\n for (const o10 of t4)\n for (const t10 of e54.get(o10) ?? [])\n n8.add(t10);\n return n8;\n}\nfunction Qre(e54) {\n const t4 = Ure.get(e54);\n if (t4)\n return t4;\n const n8 = function(e60) {\n const t10 = new Map, n10 = new Map;\n for (const o11 of e60.connections) {\n const e61 = Zre(o11);\n t10.set(o11.name, e61), qre(n10, o11.name, e61), qre(n10, o11.rootConnectionName, e61), qre(n10, o11.netConnectionName, e61);\n for (const t11 of o11.pointsToConnect)\n qre(n10, t11.pointId, e61), qre(n10, t11.pcb_port_id, e61);\n }\n for (const o11 of e60.traces ?? []) {\n const e61 = o11.connection_name ? t10.get(o11.connection_name) : undefined;\n if (e61) {\n qre(n10, o11.pcb_trace_id, e61);\n for (const t11 of o11.connectsTo ?? [])\n qre(n10, t11, e61);\n }\n }\n for (let t11 = 0;t11 \u003c 2; t11++) {\n let t12 = false;\n for (const o11 of e60.obstacles) {\n const e61 = Jre(n10, o11.connectedTo);\n if (e61.size !== 1)\n continue;\n const i9 = [...e61][0];\n for (const e63 of o11.connectedTo)\n t12 = qre(n10, e63, i9) || t12;\n }\n if (!t12)\n break;\n }\n const o10 = new Map, i8 = (e61) =\u003e {\n const t11 = o10.get(e61) ?? e61;\n if (o10.set(e61, t11), t11 === e61)\n return e61;\n const n11 = i8(t11);\n return o10.set(e61, n11), n11;\n }, r9 = (e61, t11) =\u003e {\n const n11 = i8(e61), r10 = i8(t11);\n n11 !== r10 \u0026\u0026 o10.set(r10, n11);\n };\n for (const e61 of n10.values()) {\n const [t11, ...n11] = [...e61];\n if (t11)\n for (const e63 of n11)\n r9(t11, e63);\n }\n for (const t11 of [...e60.obstacles.map((e61) =\u003e e61.connectedTo), ...(e60.traces ?? []).map((e61) =\u003e e61.connectsTo ?? [])]) {\n const [e61, ...o11] = [...Jre(n10, t11)];\n if (e61)\n for (const t12 of o11)\n r9(e61, t12);\n }\n for (const [e61, n11] of t10)\n t10.set(e61, i8(n11));\n for (const [e61, t11] of n10)\n n10.set(e61, new Set([...t11].map((e63) =\u003e i8(e63))));\n return { connectionNetKeys: t10, tokenNetKeys: n10 };\n }(e54);\n return Ure.set(e54, n8), n8;\n}\nfunction Kre(e54, t4, n8) {\n const o10 = Qre(e54), i8 = o10.connectionNetKeys.get(t4), r9 = o10.connectionNetKeys.get(n8);\n return i8 !== undefined \u0026\u0026 i8 === r9;\n}\nfunction ese(e54, t4, n8) {\n const o10 = Qre(e54), i8 = o10.connectionNetKeys.get(n8);\n return !!i8 \u0026\u0026 t4.connectedTo.some((e60) =\u003e o10.tokenNetKeys.get(e60)?.has(i8));\n}\nvar tse = 0.000001;\nfunction nse(e54) {\n return \"layer\" in e54 ? [e54.layer] : e54.layers;\n}\nfunction ose(e54, t4) {\n return e54.some((e60) =\u003e t4.includes(e60));\n}\nfunction ise(e54, t4) {\n const n8 = [];\n let o10;\n for (const i8 of e54.route)\n i8.route_type !== \"via\" ? i8.route_type === \"wire\" \u0026\u0026 (o10 \u0026\u0026 o10.layer === i8.layer \u0026\u0026 Bre(o10, i8) \u003e tse \u0026\u0026 n8.push({ type: \"segment\", segment: { start: { x: o10.x, y: o10.y }, end: { x: i8.x, y: i8.y }, width: i8.width, layer: i8.layer } }), o10 = i8) : (n8.push({ type: \"via\", center: { x: i8.x, y: i8.y }, diameter: i8.via_diameter ?? 0, layers: Gre(i8.from_layer, i8.to_layer, t4) }), o10 = undefined);\n return n8;\n}\nfunction rse(e54, t4) {\n return e54.type === \"plane\" \u0026\u0026 t4.type === \"plane\" ? e54.layer === t4.layer : e54.type === \"plane\" \u0026\u0026 t4.type === \"via\" ? t4.layers.includes(e54.layer) : e54.type === \"via\" \u0026\u0026 t4.type === \"plane\" ? rse(t4, e54) : e54.type === \"plane\" \u0026\u0026 t4.type === \"segment\" ? e54.layer === t4.segment.layer : e54.type === \"segment\" \u0026\u0026 t4.type === \"plane\" ? rse(t4, e54) : e54.type === \"endpoint\" \u0026\u0026 t4.type === \"endpoint\" ? ose(e54.layers, t4.layers) \u0026\u0026 Bre(e54.point, t4.point) \u003c= tse : e54.type === \"endpoint\" \u0026\u0026 t4.type === \"obstacle\" ? ose(e54.layers, t4.obstacle.layers) \u0026\u0026 Yre(e54.point, t4.obstacle, tse) : e54.type === \"obstacle\" \u0026\u0026 t4.type === \"endpoint\" ? rse(t4, e54) : e54.type === \"endpoint\" \u0026\u0026 t4.type === \"segment\" ? e54.layers.includes(t4.segment.layer) \u0026\u0026 Fre(e54.point, t4.segment.start, t4.segment.end) \u003c= t4.segment.width / 2 + tse : e54.type === \"segment\" \u0026\u0026 t4.type === \"endpoint\" ? rse(t4, e54) : e54.type === \"endpoint\" \u0026\u0026 t4.type === \"via\" ? ose(e54.layers, t4.layers) \u0026\u0026 Bre(e54.point, t4.center) \u003c= t4.diameter / 2 + tse : e54.type === \"via\" \u0026\u0026 t4.type === \"endpoint\" ? rse(t4, e54) : e54.type === \"obstacle\" \u0026\u0026 t4.type === \"segment\" ? e54.obstacle.layers.includes(t4.segment.layer) \u0026\u0026 Hre(t4.segment, e54.obstacle) \u003c= t4.segment.width / 2 + tse : e54.type === \"segment\" \u0026\u0026 t4.type === \"obstacle\" ? rse(t4, e54) : e54.type === \"obstacle\" \u0026\u0026 t4.type === \"via\" ? ose(e54.obstacle.layers, t4.layers) \u0026\u0026 Xre(t4.center, e54.obstacle) \u003c= t4.diameter / 2 + tse : e54.type === \"via\" \u0026\u0026 t4.type === \"obstacle\" ? rse(t4, e54) : e54.type === \"segment\" \u0026\u0026 t4.type === \"segment\" ? e54.segment.layer === t4.segment.layer \u0026\u0026 $re(e54.segment.start, e54.segment.end, t4.segment.start, t4.segment.end) \u003c= (e54.segment.width + t4.segment.width) / 2 + tse : e54.type === \"segment\" \u0026\u0026 t4.type === \"via\" ? t4.layers.includes(e54.segment.layer) \u0026\u0026 Fre(t4.center, e54.segment.start, e54.segment.end) \u003c= t4.diameter / 2 + e54.segment.width / 2 + tse : e54.type === \"via\" \u0026\u0026 t4.type === \"segment\" ? rse(t4, e54) : e54.type === \"via\" \u0026\u0026 t4.type === \"via\" \u0026\u0026 (ose(e54.layers, t4.layers) \u0026\u0026 Bre(e54.center, t4.center) \u003c= (e54.diameter + t4.diameter) / 2 + tse);\n}\nvar sse = class {\n parent;\n constructor(e54) {\n this.parent = Array.from({ length: e54 }, (e60, t4) =\u003e t4);\n }\n find(e54) {\n const t4 = this.parent[e54];\n if (t4 === e54)\n return e54;\n const n8 = this.find(t4);\n return this.parent[e54] = n8, n8;\n }\n union(e54, t4) {\n const n8 = this.find(e54), o10 = this.find(t4);\n n8 !== o10 \u0026\u0026 (this.parent[o10] = n8);\n }\n};\nfunction ase(e54, t4, n8) {\n return Boolean(t4.connection_name \u0026\u0026 Kre(e54, t4.connection_name, n8.name));\n}\nfunction cse(e54) {\n const { inputSrj: t4, routedSrj: n8 } = e54, o10 = n8.fanoutPlaneConnectivity, i8 = Wre(n8.layerCount), r9 = new Map;\n for (const e60 of t4.connections) {\n const t10 = Zre(e60), n10 = r9.get(t10) ?? [];\n n10.push(e60), r9.set(t10, n10);\n }\n const s7 = [];\n let a9 = 0, c5 = 0;\n for (const e60 of r9.values()) {\n const r10 = e60[0], l10 = e60.flatMap((e61) =\u003e e61.pointsToConnect.map((t10, n10) =\u003e ({ type: \"endpoint\", connectionName: e61.name, endpointIndex: n10, point: t10, layers: nse(t10) }))), h5 = t4.obstacles.filter((e61) =\u003e ese(t4, e61, r10.name)).map((e61) =\u003e ({ type: \"obstacle\", obstacle: e61 })), d9 = (n8.traces ?? []).filter((e61) =\u003e ase(t4, e61, r10)).flatMap((e61) =\u003e ise(e61, i8)), u9 = [...new Set((o10 ?? []).flatMap((e61) =\u003e Kre(t4, e61.connectionName, r10.name) ? [e61.layer] : []))].map((e61) =\u003e ({ type: \"plane\", layer: e61 })), p9 = [...l10, ...h5, ...d9, ...u9], m9 = new sse(p9.length);\n for (let e61 = 0;e61 \u003c p9.length; e61++)\n for (let t10 = e61 + 1;t10 \u003c p9.length; t10++)\n rse(p9[e61], p9[t10]) \u0026\u0026 m9.union(e61, t10);\n const g10 = new Map;\n for (let e61 = 0;e61 \u003c l10.length; e61++) {\n const t10 = l10[e61], n10 = g10.get(t10.connectionName) ?? [];\n n10[t10.endpointIndex] = e61, g10.set(t10.connectionName, n10);\n }\n for (const t10 of e60) {\n const e61 = g10.get(t10.name) ?? [], n10 = e61[0], o11 = n10 === undefined ? undefined : m9.find(n10), i9 = e61.flatMap((e63, t11) =\u003e o11 === undefined || m9.find(e63) !== o11 ? [t11] : []);\n c5 += e61.length - i9.length, i9.length === 0 ? a9++ : s7.push({ code: \"original-endpoints-disconnected\", connectionName: t10.name, disconnectedEndpointIndices: i9, message: `Connection ${t10.name} has no physical copper path from endpoint 0 to original endpoint${i9.length === 1 ? \"\" : \"s\"} ${i9.join(\", \")}` });\n }\n }\n const l5 = t4.connections.reduce((e60, t10) =\u003e e60 + t10.pointsToConnect.length, 0);\n return { valid: s7.length === 0, checkedConnectionCount: t4.connections.length, connectedConnectionCount: a9, checkedEndpointCount: l5, connectedEndpointCount: c5, issues: s7 };\n}\nvar lse = 0.000001;\nfunction hse(e54) {\n const { inputSrj: t4, segment: n8, bodyObstacle: o10, connectionName: i8 } = e54;\n if (o10.connectedTo.length \u003e 0 || !o10.componentId)\n return false;\n const r9 = t4.obstacles.filter((e60) =\u003e e60.componentId === o10.componentId \u0026\u0026 e60.layers.includes(n8.layer) \u0026\u0026 ese(t4, e60, i8));\n for (const e60 of r9)\n for (const [t10, i9] of [[n8.start, n8.end], [n8.end, n8.start]]) {\n if (!Yre(t10, e60, lse))\n continue;\n const n10 = { x: t10.x - o10.center.x, y: t10.y - o10.center.y }, r10 = { x: i9.x - t10.x, y: i9.y - t10.y };\n if (n10.x * r10.x + n10.y * r10.y \u003e lse)\n return true;\n }\n return false;\n}\nfunction dse(e54, t4) {\n return Bre(e54, t4) \u003c= lse;\n}\nfunction use(e54, t4) {\n e54.push(t4);\n}\nfunction pse(e54) {\n const { srj: t4, trace: n8, connectionName: o10, layerNames: i8, issues: r9 } = e54, s7 = [], a9 = [];\n let c5, l5;\n for (const e60 of n8.route) {\n if (e60.route_type === \"via\") {\n const s9 = Gre(e60.from_layer, e60.to_layer, i8);\n a9.push({ center: { x: e60.x, y: e60.y }, diameter: e60.via_diameter ?? t4.minViaPadDiameter ?? t4.minTraceWidth, spanLayers: s9 }), c5 \u0026\u0026 dse(c5, e60) \u0026\u0026 c5.layer === e60.from_layer || use(r9, { code: \"disconnected-trace\", traceId: n8.pcb_trace_id, connectionName: o10, message: `Trace ${n8.pcb_trace_id} reaches a via without a matching ${e60.from_layer} wire endpoint` }), l5 = e60;\n continue;\n }\n e60.route_type === \"wire\" ? l5 ? (dse(e60, l5) \u0026\u0026 e60.layer === l5.to_layer || use(r9, { code: \"disconnected-trace\", traceId: n8.pcb_trace_id, connectionName: o10, message: `Trace ${n8.pcb_trace_id} does not continue from its via on ${l5.to_layer}` }), c5 = e60, l5 = undefined) : (c5 \u0026\u0026 (c5.layer !== e60.layer ? use(r9, { code: \"disconnected-trace\", traceId: n8.pcb_trace_id, connectionName: o10, message: `Trace ${n8.pcb_trace_id} changes from ${c5.layer} to ${e60.layer} without a via` }) : dse(c5, e60) || s7.push({ start: { x: c5.x, y: c5.y }, end: { x: e60.x, y: e60.y }, width: e60.width, layer: e60.layer })), c5 = e60) : (use(r9, { code: \"unsupported-route-point\", traceId: n8.pcb_trace_id, connectionName: o10, message: `Trace ${n8.pcb_trace_id} contains unsupported ${e60.route_type} geometry` }), c5 = undefined, l5 = undefined);\n }\n return l5 \u0026\u0026 use(r9, { code: \"disconnected-trace\", traceId: n8.pcb_trace_id, connectionName: o10, message: `Trace ${n8.pcb_trace_id} ends at a via without a wire on ${l5.to_layer}` }), { trace: n8, connectionName: o10, segments: s7, vias: a9 };\n}\nfunction mse(e54) {\n const { inputSrj: t4, routedSrj: n8, clearance: o10 } = e54, i8 = [], r9 = Wre(n8.layerCount), s7 = [], a9 = [t4, n8].flatMap((e60) =\u003e e60.connections.flatMap((e61) =\u003e e61.pointsToConnect.map((t10) =\u003e ({ connectionName: e61.name, point: t10 }))));\n for (const e60 of n8.traces ?? []) {\n const o11 = e60.connection_name;\n o11 \u0026\u0026 t4.connections.some((e61) =\u003e e61.name === o11) ? s7.push(pse({ srj: n8, trace: e60, connectionName: o11, layerNames: r9, issues: i8 })) : use(i8, { code: \"unknown-trace-connection\", traceId: e60.pcb_trace_id, ...o11 ? { connectionName: o11 } : {}, message: `Trace ${e60.pcb_trace_id} does not identify an input connection` });\n }\n for (const e60 of s7) {\n for (const n10 of e60.segments)\n for (const r10 of t4.obstacles) {\n if (!r10.layers.includes(n10.layer) || ese(t4, r10, e60.connectionName))\n continue;\n if (hse({ inputSrj: t4, segment: n10, bodyObstacle: r10, connectionName: e60.connectionName }))\n continue;\n const s9 = Hre(n10, r10), a10 = n10.width / 2 + o10;\n s9 \u003c a10 - lse \u0026\u0026 use(i8, { code: \"trace-obstacle-clearance\", traceId: e60.trace.pcb_trace_id, connectionName: e60.connectionName, layer: n10.layer, obstacleId: r10.obstacleId, message: `Trace ${e60.trace.pcb_trace_id} on ${n10.layer} is ${s9.toFixed(4)}mm from different-net obstacle ${r10.obstacleId}; ${a10.toFixed(4)}mm is required` });\n }\n for (const n10 of e60.vias) {\n const r10 = a9.find(({ point: e61 }) =\u003e Bre(n10.center, e61) \u003c= lse);\n r10 \u0026\u0026 use(i8, { code: \"via-at-endpoint\", traceId: e60.trace.pcb_trace_id, connectionName: e60.connectionName, otherConnectionName: r10.connectionName, message: `Via in ${e60.trace.pcb_trace_id} is placed directly at an original or routed connection endpoint` });\n for (const r11 of t4.obstacles) {\n if (!r11.layers.some((e61) =\u003e n10.spanLayers.includes(e61)) || ese(t4, r11, e60.connectionName))\n continue;\n const s9 = Xre(n10.center, r11), a10 = n10.diameter / 2 + o10;\n s9 \u003c a10 - lse \u0026\u0026 use(i8, { code: \"via-obstacle-clearance\", traceId: e60.trace.pcb_trace_id, connectionName: e60.connectionName, obstacleId: r11.obstacleId, message: `Via in ${e60.trace.pcb_trace_id} is ${s9.toFixed(4)}mm from different-net obstacle ${r11.obstacleId} on its layer span; ${a10.toFixed(4)}mm is required` });\n }\n }\n }\n for (let e60 = 0;e60 \u003c s7.length; e60++) {\n const n10 = s7[e60];\n for (let r10 = e60 + 1;r10 \u003c s7.length; r10++) {\n const e61 = s7[r10];\n if (!Kre(t4, n10.connectionName, e61.connectionName)) {\n for (const t10 of n10.segments) {\n for (const r11 of e61.segments)\n Vre(t10, r11, o10) || use(i8, { code: \"different-net-trace-clearance\", traceId: n10.trace.pcb_trace_id, connectionName: n10.connectionName, otherTraceId: e61.trace.pcb_trace_id, otherConnectionName: e61.connectionName, layer: t10.layer, message: `Different-net traces ${n10.trace.pcb_trace_id} and ${e61.trace.pcb_trace_id} intersect or violate clearance on ${t10.layer}` });\n for (const r11 of e61.vias)\n !r11.spanLayers.includes(t10.layer) || Fre(r11.center, t10.start, t10.end) \u003e= r11.diameter / 2 + t10.width / 2 + o10 - lse || use(i8, { code: \"different-net-trace-via-clearance\", traceId: n10.trace.pcb_trace_id, connectionName: n10.connectionName, otherTraceId: e61.trace.pcb_trace_id, otherConnectionName: e61.connectionName, layer: t10.layer, message: `Trace ${n10.trace.pcb_trace_id} violates via clearance to ${e61.trace.pcb_trace_id} on ${t10.layer}` });\n }\n for (const t10 of n10.vias) {\n for (const r11 of e61.segments)\n !t10.spanLayers.includes(r11.layer) || Fre(t10.center, r11.start, r11.end) \u003e= t10.diameter / 2 + r11.width / 2 + o10 - lse || use(i8, { code: \"different-net-trace-via-clearance\", traceId: n10.trace.pcb_trace_id, connectionName: n10.connectionName, otherTraceId: e61.trace.pcb_trace_id, otherConnectionName: e61.connectionName, layer: r11.layer, message: `Via in ${n10.trace.pcb_trace_id} violates trace clearance to ${e61.trace.pcb_trace_id} on ${r11.layer}` });\n for (const r11 of e61.vias)\n !t10.spanLayers.some((e63) =\u003e r11.spanLayers.includes(e63)) || Bre(t10.center, r11.center) \u003e= (t10.diameter + r11.diameter) / 2 + o10 - lse || use(i8, { code: \"different-net-via-clearance\", traceId: n10.trace.pcb_trace_id, connectionName: n10.connectionName, otherTraceId: e61.trace.pcb_trace_id, otherConnectionName: e61.connectionName, message: `Different-net vias in ${n10.trace.pcb_trace_id} and ${e61.trace.pcb_trace_id} violate clearance on an overlapping layer span` });\n }\n }\n }\n }\n return { valid: i8.length === 0, checkedTraceCount: n8.traces?.length ?? 0, checkedSegmentCount: s7.reduce((e60, t10) =\u003e e60 + t10.segments.length, 0), checkedViaCount: s7.reduce((e60, t10) =\u003e e60 + t10.vias.length, 0), issues: i8 };\n}\nvar gse = 0.000000001;\nfunction fse(e54, t4) {\n if (\"layer\" in e54)\n return e54.layer;\n if (t4 \u0026\u0026 e54.layers.includes(t4))\n return t4;\n const n8 = e54.layers[0];\n if (!n8)\n throw new Error(\"Endpoint completion received a layerless point\");\n return n8;\n}\nfunction _se(e54) {\n const t4 = [];\n for (const n8 of e54)\n t4.at(-1) \u0026\u0026 Bre(t4.at(-1), n8) \u003c gse || t4.push(n8);\n return t4;\n}\nfunction yse(e54, t4) {\n const n8 = _se(e54);\n if (n8.length \u003c 3)\n return n8;\n const o10 = [n8[0]];\n for (let e60 = 1;e60 \u003c n8.length - 1; e60++) {\n const i8 = n8[e60 - 1], r9 = n8[e60], s7 = n8[e60 + 1], a9 = Bre(i8, r9), c5 = Bre(r9, s7), l5 = { x: (r9.x - i8.x) / a9, y: (r9.y - i8.y) / a9 }, h5 = { x: (s7.x - r9.x) / c5, y: (s7.y - r9.y) / c5 };\n if (Math.abs(l5.x * h5.x + l5.y * h5.y) \u003e 0.000001) {\n o10.push(r9);\n continue;\n }\n const d9 = Math.min(t4, a9 / 2, c5 / 2);\n o10.push({ x: r9.x - l5.x * d9, y: r9.y - l5.y * d9 }), o10.push({ x: r9.x + h5.x * d9, y: r9.y + h5.y * d9 });\n }\n return o10.push(n8.at(-1)), _se(o10);\n}\nfunction bse(e54) {\n const { inputSrj: t4, plan: n8 } = e54, o10 = fse(n8.targetPoint), i8 = function(e60) {\n const { inputSrj: t10, connectionName: n10, target: o11, targetLayer: i9 } = e60;\n return t10.obstacles.find((e61) =\u003e e61.layers.includes(i9) \u0026\u0026 ese(t10, e61, n10) \u0026\u0026 Yre(o11, e61, 0.000001));\n }({ inputSrj: t4, connectionName: n8.connectionName, target: n8.targetPoint, targetLayer: o10 }), r9 = t4.obstacles.find((e60) =\u003e e60.componentId === i8?.componentId \u0026\u0026 e60.connectedTo.length === 0), s7 = r9 ? { x: n8.targetPoint.x - r9.center.x, y: n8.targetPoint.y - r9.center.y } : { x: n8.targetPoint.x - n8.sourcePoint.x, y: n8.targetPoint.y - n8.sourcePoint.y }, a9 = Math.hypot(s7.x, s7.y), c5 = a9 \u003e gse ? { x: s7.x / a9, y: s7.y / a9 } : { x: 1, y: 0 };\n return { outward: c5, perpendicular: { x: -c5.y, y: c5.x } };\n}\nfunction xse(e54) {\n const { plan: t4, branchStart: n8, viaPoint: o10, assignedLayerPath: i8, terminalApproach: r9, traceWidth: s7, viaDiameter: a9, viaHoleDiameter: c5, candidateIndex: l5, chamfer: h5 } = e54, d9 = fse(t4.targetPoint), u9 = yse(i8, h5), p9 = yse([o10, ...r9 ? [r9] : [], t4.targetPoint], h5), m9 = u9.map((e60) =\u003e ({ route_type: \"wire\", x: e60.x, y: e60.y, width: s7, layer: n8.layer }));\n n8.layer !== d9 \u0026\u0026 (m9.push({ route_type: \"via\", x: o10.x, y: o10.y, from_layer: n8.layer, to_layer: d9, via_diameter: a9, via_hole_diameter: c5 }), m9.push({ route_type: \"wire\", x: o10.x, y: o10.y, width: s7, layer: d9 }));\n for (const e60 of p9.slice(1))\n m9.push({ route_type: \"wire\", x: e60.x, y: e60.y, width: s7, layer: d9 });\n return { type: \"pcb_trace\", pcb_trace_id: (g10 = { connectionName: t4.connectionName, sourcePointIndex: t4.sourcePointIndex, candidateIndex: l5 }, `fanout-completion:${g10.connectionName}:source-${g10.sourcePointIndex}:${g10.candidateIndex}`), connection_name: t4.connectionName, route: m9 };\n var g10;\n}\nfunction vse(e54, t4) {\n return !e54.issues.some((e60) =\u003e e60.connectionName === t4);\n}\nfunction Ise(e54) {\n const { trace: t4, endpointSrjs: n8 } = e54, o10 = n8.flatMap((e60) =\u003e e60.connections.flatMap((e61) =\u003e e61.pointsToConnect));\n return t4.route.some((e60) =\u003e e60.route_type === \"via\" \u0026\u0026 o10.some((t10) =\u003e Bre(e60, t10) \u003c= 0.000001));\n}\nfunction Sse(e54) {\n const { inputSrj: t4, fanoutSrj: n8, plan: o10, acceptedTraces: i8, traceWidth: r9, viaDiameter: s7, viaHoleDiameter: a9, clearance: c5 } = e54, { outward: l5, perpendicular: h5 } = bse({ inputSrj: t4, plan: o10 }), d9 = [...o10.via ? [{ x: o10.via.center.x, y: o10.via.center.y, layer: o10.targetLayer }] : [], { x: o10.sourcePoint.x, y: o10.sourcePoint.y, layer: o10.sourceLayer }];\n let u9 = [], p9 = Number.POSITIVE_INFINITY, m9 = 0;\n const g10 = t4.connections.length \u003e 32 ? 600 : Number.POSITIVE_INFINITY, f10 = o10.termination.type === \"plane\" ? wse({ trace: o10.trace, endpoint: o10.exitPoint, layer: o10.sourceLayer, distances: [0.2, 0.3, 0.4] }) : [], _5 = [...o10.termination.type === \"plane\" \u0026\u0026 o10.via ? [{ ...o10.via.center }] : [], ...f10, ...[0.4, 0.8, 1.2, 1.6].flatMap((e60) =\u003e [0, 0.4, -0.4, 0.8, -0.8, 1.2, -1.2, 1.6, -1.6].map((t10) =\u003e ({ x: o10.sourcePoint.x + l5.x * e60 + h5.x * t10, y: o10.sourcePoint.y + l5.y * e60 + h5.y * t10 })))];\n for (const e60 of _5) {\n const _10 = [...o10.termination.type === \"plane\" ? [{ ...e60, layer: o10.targetLayer }] : [], ...d9, ...f10.flatMap((t10) =\u003e Bre(t10, e60) \u003c= 0.000001 ? [{ ...t10, layer: o10.sourceLayer }] : [])];\n for (const d10 of _10) {\n const f11 = Bre(d10, e60) \u003c= 0.000001 ? [[d10]] : [[d10, e60], [d10, { x: e60.x, y: d10.y }, e60], [d10, { x: d10.x, y: e60.y }, e60], ...[0.4, -0.4].map((t10) =\u003e [d10, { x: d10.x + t10, y: d10.y }, { x: d10.x + t10, y: e60.y }, e60])];\n for (const _11 of f11) {\n const f12 = [undefined, ...[0.4, 0.8].map((e61) =\u003e ({ x: o10.targetPoint.x + l5.x * e61, y: o10.targetPoint.y + l5.y * e61 })), ...[0.4, -0.4].map((e61) =\u003e ({ x: o10.targetPoint.x + 0.4 * l5.x + h5.x * e61, y: o10.targetPoint.y + 0.4 * l5.y + h5.y * e61 }))];\n for (const l10 of f12) {\n if (m9 \u003e= g10)\n return { blockingConnectionNames: u9 };\n const h9 = xse({ plan: o10, branchStart: d10, viaPoint: e60, assignedLayerPath: _11, terminalApproach: l10, traceWidth: r9, viaDiameter: s7, viaHoleDiameter: a9, candidateIndex: m9++, chamfer: 0 });\n if (Ise({ trace: h9, endpointSrjs: [t4, n8] }))\n continue;\n const f13 = { ...n8, traces: [...n8.traces ?? [], ...i8, h9] }, y10 = mse({ inputSrj: t4, routedSrj: f13, clearance: c5 });\n if (!y10.valid) {\n y10.issues.length \u003c p9 \u0026\u0026 (p9 = y10.issues.length, u9 = [...new Set(y10.issues.flatMap((e61) =\u003e [e61.connectionName, e61.otherConnectionName].flatMap((e63) =\u003e e63 \u0026\u0026 e63 !== o10.connectionName ? [e63] : [])))]);\n continue;\n }\n if (vse(cse({ inputSrj: t4, routedSrj: f13 }), o10.connectionName))\n return { trace: h9, blockingConnectionNames: [] };\n }\n }\n }\n }\n return { blockingConnectionNames: u9 };\n}\nfunction Cse(e54) {\n const { inputSrj: t4, fanoutSrj: n8, plans: o10, traceWidth: i8, viaDiameter: r9, viaHoleDiameter: s7, clearance: a9 } = e54, c5 = [], l5 = [], h5 = new Set;\n for (const e60 of o10) {\n const o11 = Sse({ inputSrj: t4, fanoutSrj: n8, plan: e60, acceptedTraces: c5, traceWidth: i8, viaDiameter: r9, viaHoleDiameter: s7, clearance: a9 });\n if (o11.trace)\n c5.push(o11.trace);\n else {\n l5.push(e60.connectionName);\n for (const e61 of o11.blockingConnectionNames)\n h5.add(e61);\n }\n }\n const d9 = { ...n8, traces: [...n8.traces ?? [], ...c5] };\n return { traces: c5, failedConnectionNames: l5, blockingConnectionNames: [...h5], connectivity: cse({ inputSrj: t4, routedSrj: d9 }), drc: mse({ inputSrj: t4, routedSrj: d9, clearance: a9 }) };\n}\nfunction Pse(e54) {\n let t4, n8 = 0;\n for (const o10 of e54.route)\n o10.route_type === \"wire\" ? (t4?.layer === o10.layer \u0026\u0026 (n8 += Bre(t4, o10)), t4 = o10) : t4 = undefined;\n return n8;\n}\nfunction Mse(e54) {\n const t4 = Wre(e54.layerCount), n8 = [];\n for (const o10 of e54.traces ?? []) {\n let i8;\n for (const r9 of o10.route)\n if (r9.route_type !== \"via\")\n if (r9.route_type === \"wire\") {\n if (i8?.layer === r9.layer) {\n const e60 = Bre(i8, r9);\n e60 \u003e gse \u0026\u0026 n8.push({ obstacleId: `endpoint-completion-keepout:${o10.pcb_trace_id}:segment:${n8.length}`, type: \"rect\", center: { x: (i8.x + r9.x) / 2, y: (i8.y + r9.y) / 2 }, width: e60, height: Math.max(i8.width, r9.width), ccwRotationDegrees: 180 * Math.atan2(r9.y - i8.y, r9.x - i8.x) / Math.PI, layers: [r9.layer], connectedTo: [o10.connection_name] });\n }\n i8 = r9;\n } else\n i8 = undefined;\n else\n n8.push({ obstacleId: `endpoint-completion-keepout:${o10.pcb_trace_id}:via:${n8.length}`, type: \"rect\", center: { x: r9.x, y: r9.y }, width: r9.via_diameter ?? e54.minViaPadDiameter ?? 0.3, height: r9.via_diameter ?? e54.minViaPadDiameter ?? 0.3, layers: Gre(r9.from_layer, r9.to_layer, t4), connectedTo: [o10.connection_name] }), i8 = undefined;\n }\n return n8;\n}\nfunction wse(e54) {\n const { trace: t4, endpoint: n8, layer: o10, distances: i8 } = e54, r9 = t4.route.findLastIndex((e60) =\u003e e60.route_type === \"wire\" \u0026\u0026 e60.layer === o10 \u0026\u0026 Bre(e60, n8) \u003c= 0.000001);\n return r9 \u003c 0 ? [] : i8.flatMap((e60) =\u003e {\n let i9 = e60, s7 = n8;\n for (let e61 = r9 - 1;e61 \u003e= 0; e61--) {\n const n10 = t4.route[e61];\n if (n10?.route_type !== \"wire\" || n10.layer !== o10)\n break;\n const r10 = Bre(s7, n10);\n if (!(r10 \u003c= gse)) {\n if (i9 \u003c r10 - 0.000001)\n return [{ x: s7.x + (n10.x - s7.x) * i9 / r10, y: s7.y + (n10.y - s7.y) * i9 / r10 }];\n i9 -= r10, s7 = n10;\n }\n }\n return [];\n });\n}\nfunction Nse(e54) {\n const { inputSrj: t4, fanoutSrj: n8, plan: o10, acceptedTraces: i8, traceWidth: r9, viaDiameter: s7, viaHoleDiameter: a9, clearance: c5 } = e54, l5 = { x: o10.exitPoint.x, y: o10.exitPoint.y, layer: o10.targetLayer }, h5 = o10.targetPoint, d9 = fse(h5);\n let u9 = 0;\n const p9 = (e60) =\u003e {\n const l10 = xse({ plan: o10, branchStart: e60.start, viaPoint: e60.viaPoint, assignedLayerPath: [e60.start, e60.viaPoint], terminalApproach: e60.terminalApproach, traceWidth: r9, viaDiameter: s7, viaHoleDiameter: a9, candidateIndex: 1e4 + u9++, chamfer: Math.max(r9, 0.1) });\n if (Ise({ trace: l10, endpointSrjs: [t4, n8] }))\n return;\n const h9 = { ...n8, traces: [...n8.traces ?? [], ...i8, l10] };\n return mse({ inputSrj: t4, routedSrj: h9, clearance: c5 }).valid \u0026\u0026 vse(cse({ inputSrj: t4, routedSrj: h9 }), o10.connectionName) ? l10 : undefined;\n };\n if (l5.layer !== d9) {\n const e60 = wse({ trace: o10.trace, endpoint: o10.exitPoint, layer: o10.targetLayer, distances: [0.4, 0.8, 1.2, 1.6] });\n for (const t10 of e60) {\n const e61 = { ...t10, layer: o10.targetLayer };\n for (const n10 of [undefined, { x: h5.x, y: t10.y }, { x: t10.x, y: h5.y }]) {\n const o11 = p9({ start: e61, viaPoint: t10, terminalApproach: n10 });\n if (o11)\n return o11;\n }\n }\n }\n const m9 = [[h5], [{ x: h5.x, y: l5.y }, h5], [{ x: l5.x, y: h5.y }, h5]];\n for (const e60 of m9) {\n const t10 = e60[0], n10 = Bre(l5, t10), o11 = l5.layer === d9 ? [0] : [0.4, 0.8, 1.2, 1.6];\n for (const i9 of o11) {\n if (l5.layer !== d9 \u0026\u0026 (n10 \u003c= i9 + 0.2 || i9 \u003c= 0.000001))\n continue;\n const o12 = p9({ start: l5, viaPoint: l5.layer === d9 ? { x: l5.x, y: l5.y } : { x: l5.x + (t10.x - l5.x) * i9 / n10, y: l5.y + (t10.y - l5.y) * i9 / n10 }, terminalApproach: e60.length \u003e 1 ? t10 : undefined });\n if (o12)\n return o12;\n }\n }\n}\nfunction Rse(e54) {\n const { inputSrj: t4, fanoutSrj: n8, plans: o10, traceWidth: i8, viaDiameter: r9, viaHoleDiameter: s7, clearance: a9, effort: c5 = 1, routeDownstreamConnections: l5 } = e54, h5 = [], d9 = mse({ inputSrj: t4, routedSrj: n8, clearance: a9 }), u9 = cse({ inputSrj: t4, routedSrj: n8 }), p9 = o10.filter((e60) =\u003e fse(e60.sourcePoint) !== fse(e60.targetPoint) \u0026\u0026 Bre(e60.sourcePoint, e60.targetPoint) \u003c= 0.25 \u0026\u0026 !vse(u9, e60.connectionName));\n let m9 = { traces: [], failedConnectionNames: p9.map((e60) =\u003e e60.connectionName), blockingConnectionNames: [], connectivity: u9, drc: d9 }, g10 = 0;\n if (d9.valid) {\n let e60 = [];\n const o11 = new Map(p9.map((e61, t10) =\u003e [e61.connectionName, t10])), c9 = t4.connections.length \u003e 32 ? 1 : 3;\n for (let l10 = 0;l10 \u003c c9; l10++) {\n const c10 = new Map(e60.map((e61, t10) =\u003e [e61, t10])), l11 = Cse({ inputSrj: t4, fanoutSrj: n8, plans: p9.toSorted((e61, t10) =\u003e (c10.get(e61.connectionName) ?? Number.MAX_SAFE_INTEGER) - (c10.get(t10.connectionName) ?? Number.MAX_SAFE_INTEGER) || (o11.get(e61.connectionName) ?? 0) - (o11.get(t10.connectionName) ?? 0)), traceWidth: i8, viaDiameter: r9, viaHoleDiameter: s7, clearance: a9 });\n if (g10++, l11.drc.valid \u0026\u0026 (l11.connectivity.connectedConnectionCount \u003e m9.connectivity.connectedConnectionCount || l11.connectivity.connectedConnectionCount === m9.connectivity.connectedConnectionCount \u0026\u0026 l11.traces.length \u003c m9.traces.length) \u0026\u0026 (m9 = l11), e60 = [...new Set([...l11.failedConnectionNames, ...l11.blockingConnectionNames, ...e60])], l11.failedConnectionNames.length === 0)\n break;\n }\n } else\n h5.push(\"Fanout prefix failed emitted-copper DRC; skipped completion\");\n const f10 = new Set(p9.map((e60) =\u003e e60.connectionName)), _5 = o10.filter((e60) =\u003e !f10.has(e60.connectionName) \u0026\u0026 !vse(u9, e60.connectionName)), y10 = [];\n if (d9.valid)\n for (const e60 of _5) {\n const o11 = Nse({ inputSrj: t4, fanoutSrj: n8, plan: e60, acceptedTraces: [...m9.traces, ...y10], traceWidth: i8, viaDiameter: r9, viaHoleDiameter: s7, clearance: a9 });\n o11 \u0026\u0026 y10.push(o11);\n }\n const b10 = { ...n8, traces: [...n8.traces ?? [], ...m9.traces, ...y10] }, x8 = new Set(cse({ inputSrj: t4, routedSrj: b10 }).issues.map((e60) =\u003e e60.connectionName)), v10 = n8.connections.filter((e60) =\u003e !f10.has(e60.name) \u0026\u0026 x8.has(e60.name));\n let I6 = [];\n if (d9.valid \u0026\u0026 v10.length \u003e 0 \u0026\u0026 v10.length \u003c= 12 \u0026\u0026 l5) {\n const e60 = new Set(v10.map((e61) =\u003e e61.name)), o11 = { ...n8, connections: v10, buses: n8.buses?.map((t10) =\u003e ({ ...t10, connectionNames: t10.connectionNames.filter((t11) =\u003e e60.has(t11)) })).filter((e61) =\u003e e61.connectionNames.length \u003e 0), obstacles: [...n8.obstacles, ...Mse(n8)], traces: [] };\n try {\n const i9 = l5(o11, { effort: c5 });\n I6 = function(e61) {\n const { inputSrj: t10, fanoutSrj: n10, localTraces: o12, candidates: i10, clearance: r10 } = e61, s9 = [...n10.traces ?? [], ...o12], a10 = { ...n10, traces: s9 }, c9 = cse({ inputSrj: t10, routedSrj: a10 }), l10 = i10.filter((e63) =\u003e e63.route.length \u003e 1 \u0026\u0026 e63.route.every((e64) =\u003e e64.route_type === \"wire\" || e64.route_type === \"via\") \u0026\u0026 !Ise({ trace: e63, endpointSrjs: [t10, n10] })).filter((e63) =\u003e {\n const o13 = cse({ inputSrj: t10, routedSrj: { ...n10, traces: [...s9, e63] } });\n return o13.connectedConnectionCount \u003e c9.connectedConnectionCount \u0026\u0026 vse(o13, e63.connection_name);\n }), h9 = { ...n10, traces: [...s9, ...l10] };\n if (mse({ inputSrj: t10, routedSrj: h9, clearance: r10 }).valid)\n return l10;\n const d10 = [];\n for (const e63 of l10.toSorted((e64, t11) =\u003e Pse(e64) - Pse(t11))) {\n const o13 = { ...n10, traces: [...s9, ...d10, e63] };\n if (!mse({ inputSrj: t10, routedSrj: o13, clearance: r10 }).valid)\n continue;\n const i11 = cse({ inputSrj: t10, routedSrj: { ...n10, traces: [...s9, ...d10] } }), a11 = cse({ inputSrj: t10, routedSrj: o13 });\n a11.connectedConnectionCount \u003e i11.connectedConnectionCount \u0026\u0026 vse(a11, e63.connection_name) \u0026\u0026 d10.push(e63);\n }\n return d10;\n }({ inputSrj: t4, fanoutSrj: n8, localTraces: [...m9.traces, ...y10], candidates: i9.filter((t10) =\u003e e60.has(t10.connection_name)), clearance: a9 });\n } catch (e61) {\n h5.push(`Downstream router failed: ${e61 instanceof Error ? e61.message : String(e61)}`);\n }\n } else\n !d9.valid \u0026\u0026 v10.length \u003e 0 ? h5.push(\"Skipped downstream router because the endpoint-completion baseline failed emitted-copper DRC\") : v10.length \u003e 12 ? h5.push(`Skipped downstream router for ${v10.length} unresolved connections (bounded at 12)`) : v10.length \u003e 0 \u0026\u0026 !l5 \u0026\u0026 h5.push(`Skipped downstream router for ${v10.length} unresolved connections because no routeDownstreamConnections callback was provided`);\n const S6 = [...m9.traces, ...y10, ...I6];\n for (const e60 of _5) {\n if (vse(cse({ inputSrj: t4, routedSrj: { ...n8, traces: [...n8.traces ?? [], ...S6] } }), e60.connectionName))\n continue;\n const o11 = Nse({ inputSrj: t4, fanoutSrj: n8, plan: e60, acceptedTraces: S6, traceWidth: i8, viaDiameter: r9, viaHoleDiameter: s7, clearance: a9 });\n o11 \u0026\u0026 S6.push(o11);\n }\n const C = function(e60) {\n const { fanoutSrj: t10, completionTraces: n10 } = e60, o11 = new Map(n10.flatMap((e61) =\u003e {\n const t11 = e61.route.find((e63) =\u003e e63.route_type === \"wire\");\n return t11 ? [[e61.connection_name, { x: t11.x, y: t11.y, layer: t11.layer }]] : [];\n })), i9 = (t10.traces ?? []).map((e61) =\u003e {\n if (!e61.pcb_trace_id.startsWith(\"fanout:\"))\n return e61;\n const t11 = o11.get(e61.connection_name);\n if (!t11)\n return e61;\n let n11;\n for (let o12 = 0;o12 \u003c e61.route.length; o12++) {\n const i10 = e61.route[o12];\n if (i10?.route_type === \"wire\") {\n if (n11 !== undefined) {\n const o13 = e61.route[n11];\n if (o13?.route_type === \"wire\" \u0026\u0026 o13.layer === t11.layer \u0026\u0026 i10.layer === t11.layer \u0026\u0026 Fre(t11, o13, i10) \u003c= 0.000001) {\n const r10 = e61.route.slice(0, n11 + 1);\n return Bre(o13, t11) \u003e 0.000001 \u0026\u0026 r10.push({ route_type: \"wire\", x: t11.x, y: t11.y, width: i10.width, layer: t11.layer }), { ...e61, route: r10 };\n }\n }\n n11 = o12;\n } else\n n11 = undefined;\n }\n return e61;\n });\n return { ...t10, traces: i9 };\n }({ fanoutSrj: { ...n8, traces: [...n8.traces ?? [], ...S6] }, completionTraces: S6 }), P = cse({ inputSrj: t4, routedSrj: C }), M = mse({ inputSrj: t4, routedSrj: C, clearance: a9 });\n return M.valid ? { simpleRouteJson: C, traces: S6, report: { attemptedLocalConnectionCount: p9.length, attemptedDownstreamConnectionCount: _5.length, completionTraceCount: S6.length, searchPassCount: g10, errors: h5, connectivity: P, drc: M } } : (h5.push(\"Final endpoint-completion output failed emitted-copper DRC\"), { simpleRouteJson: n8, traces: [], report: { attemptedLocalConnectionCount: p9.length, attemptedDownstreamConnectionCount: _5.length, completionTraceCount: 0, searchPassCount: g10, errors: h5, connectivity: cse({ inputSrj: t4, routedSrj: n8 }), drc: d9 } });\n}\nvar Tse = new Set([\"left\", \"right\", \"top\", \"bottom\", \"top-left\", \"top-right\", \"bottom-left\", \"bottom-right\"]);\nvar Ese = { top_left: { direction: \"up\", preferredExit: \"top-left\" }, top_middle: { direction: \"up\", preferredExit: \"top\" }, top_right: { direction: \"up\", preferredExit: \"top-right\" }, right_top: { direction: \"right\", preferredExit: \"top-right\" }, right_middle: { direction: \"right\", preferredExit: \"right\" }, right_bottom: { direction: \"right\", preferredExit: \"bottom-right\" }, bottom_right: { direction: \"down\", preferredExit: \"bottom-right\" }, bottom_middle: { direction: \"down\", preferredExit: \"bottom\" }, bottom_left: { direction: \"down\", preferredExit: \"bottom-left\" }, left_bottom: { direction: \"left\", preferredExit: \"bottom-left\" }, left_middle: { direction: \"left\", preferredExit: \"left\" }, left_top: { direction: \"left\", preferredExit: \"top-left\" }, top: { direction: \"up\", preferredExit: \"top\" }, right: { direction: \"right\", preferredExit: \"right\" }, bottom: { direction: \"down\", preferredExit: \"bottom\" }, left: { direction: \"left\", preferredExit: \"left\" } };\nfunction Ase(e54) {\n const t4 = [...e54].sort((e60, t10) =\u003e e60 - t10), n8 = [];\n for (const e60 of t4)\n (n8.length === 0 || Math.abs(n8[n8.length - 1] - e60) \u003e 0.000001) \u0026\u0026 n8.push(e60);\n return n8;\n}\nfunction Ose(e54) {\n let t4 = Number.POSITIVE_INFINITY;\n for (let n8 = 1;n8 \u003c e54.length; n8++) {\n const o10 = e54[n8] - e54[n8 - 1];\n o10 \u003e 0.000001 \u0026\u0026 (t4 = Math.min(t4, o10));\n }\n return t4;\n}\nfunction kse(e54, t4) {\n const n8 = t4 === \"x\" ? \"y\" : \"x\";\n let o10 = Number.POSITIVE_INFINITY;\n for (let i8 = 0;i8 \u003c e54.length; i8++) {\n const r9 = e54[i8];\n for (let s7 = i8 + 1;s7 \u003c e54.length; s7++) {\n const i9 = e54[s7];\n if (Math.abs(r9.center[n8] - i9.center[n8]) \u003e 0.000001)\n continue;\n const a9 = Math.abs(r9.center[t4] - i9.center[t4]);\n a9 \u003e 0.000001 \u0026\u0026 (o10 = Math.min(o10, a9));\n }\n }\n return o10;\n}\nfunction Dse(e54) {\n return { minX: Math.min(...e54.map((e60) =\u003e e60.center.x - e60.width / 2)), maxX: Math.max(...e54.map((e60) =\u003e e60.center.x + e60.width / 2)), minY: Math.min(...e54.map((e60) =\u003e e60.center.y - e60.height / 2)), maxY: Math.max(...e54.map((e60) =\u003e e60.center.y + e60.height / 2)) };\n}\nfunction Lse(e54, t4) {\n const n8 = t4.componentBounds?.[e54.componentId];\n if (!n8) {\n const t10 = 2.25 * e54.pitchX, n10 = 2.25 * e54.pitchY;\n return { minX: e54.bounds.minX - t10, maxX: e54.bounds.maxX + t10, minY: e54.bounds.minY - n10, maxY: e54.bounds.maxY + n10 };\n }\n if ([n8.minX, n8.maxX, n8.minY, n8.maxY].some((e60) =\u003e !Number.isFinite(e60)) || n8.minX \u003e= n8.maxX || n8.minY \u003e= n8.maxY)\n throw new Error(`FanoutSolver: componentBounds for \"${e54.componentId}\" must contain finite, increasing bounds`);\n if (n8.minX \u003e e54.bounds.minX + 0.000001 || n8.maxX \u003c e54.bounds.maxX - 0.000001 || n8.minY \u003e e54.bounds.minY + 0.000001 || n8.maxY \u003c e54.bounds.maxY - 0.000001)\n throw new Error(`FanoutSolver: componentBounds for \"${e54.componentId}\" must contain every component pad`);\n return { ...n8 };\n}\nfunction zse(e54, t4) {\n if ([e54.minX, e54.maxX, e54.minY, e54.maxY].some((e60) =\u003e !Number.isFinite(e60)) || e54.minX \u003e= e54.maxX || e54.minY \u003e= e54.maxY)\n throw new Error(\"FanoutSolver: sharedBoundary must contain finite, increasing bounds\");\n for (const n8 of t4)\n if (e54.minX \u003e n8.bounds.minX + 0.000001 || e54.maxX \u003c n8.bounds.maxX - 0.000001 || e54.minY \u003e n8.bounds.minY + 0.000001 || e54.maxY \u003c n8.bounds.maxY - 0.000001)\n throw new Error(`FanoutSolver: sharedBoundary must contain every pad of component \"${n8.componentId}\"`);\n return { ...e54 };\n}\nfunction Bse(e54) {\n return \"layer\" in e54 ? [e54.layer] : e54.layers;\n}\nfunction Fse(e54) {\n const { point: t4, connection: n8, componentGrids: o10 } = e54, i8 = Bse(t4), r9 = [];\n for (const e60 of o10) {\n const o11 = e60.obstacles.filter((e61) =\u003e e61.layers.some((e63) =\u003e i8.includes(e63))).filter((e61) =\u003e Yre(t4, e61, 0.00001)).sort((e61, o12) =\u003e {\n const i9 = e61.connectedTo.includes(n8.name) || e61.connectedTo.includes(t4.pointId ?? \"\") || e61.connectedTo.includes(t4.pcb_port_id ?? \"\");\n return i9 !== (o12.connectedTo.includes(n8.name) || o12.connectedTo.includes(t4.pointId ?? \"\") || o12.connectedTo.includes(t4.pcb_port_id ?? \"\")) ? i9 ? -1 : 1 : e61.width * e61.height - o12.width * o12.height;\n });\n o11[0] \u0026\u0026 r9.push({ grid: e60, obstacle: o11[0] });\n }\n return r9;\n}\nfunction jse(e54) {\n for (const t10 of e54.pointsToConnect)\n if (\"layers\" in t10 \u0026\u0026 t10.busId)\n return t10.busId;\n const t4 = /^BUS[_:-]([^_:-]+)(?:[_:-]\\d+)?$/i.exec(e54.name);\n return t4?.[1] ?? null;\n}\nfunction $se(e54, t4) {\n if (t4 !== undefined) {\n if (!Tse.has(t4))\n throw new Error(`FanoutSolver: bus \"${e54}\" has invalid preferredExit \"${t4}\"`);\n return t4;\n }\n}\nfunction Yse(e54) {\n if (e54 === undefined)\n return;\n if (e54.length === 0)\n throw new Error(\"FanoutSolver: availableCornersAndSides must contain at least one boundary region\");\n const t4 = [], n8 = new Set;\n for (const o10 of e54) {\n const e60 = Ese[o10];\n if (!e60)\n throw new Error(`FanoutSolver: invalid availableCornersAndSides value \"${o10}\"`);\n const i8 = `${e60.direction}:${e60.preferredExit}`;\n n8.has(i8) || (n8.add(i8), t4.push(e60));\n }\n return t4;\n}\nfunction Xse(e54, t4) {\n if (t4 === undefined || t4.type === \"boundary\")\n return { type: \"boundary\" };\n if (t4.type !== \"plane\" || typeof t4.layer != \"string\" || t4.layer.length === 0)\n throw new Error(`FanoutSolver: bus \"${e54}\" has an invalid termination target`);\n return { type: \"plane\", layer: t4.layer };\n}\nfunction Hse(e54, t4, n8, o10) {\n const i8 = t4.pointsToConnect.filter((e60, t10) =\u003e t10 !== n8).sort((t10, n10) =\u003e Bre(e54, n10) - Bre(e54, t10))[0];\n if (!i8 \u0026\u0026 o10.type === \"plane\")\n return e54;\n if (!i8)\n throw new Error(`FanoutSolver: connection \"${t4.name}\" has no target beyond its BGA pad`);\n return i8;\n}\nfunction Vse(e54, t4) {\n let n8 = 0, o10 = 0;\n for (const e60 of t4) {\n const t10 = e60.exitTargetPoint ?? e60.targetPoint;\n n8 += t10.x - e60.sourcePoint.x, o10 += t10.y - e60.sourcePoint.y;\n }\n if (Math.abs(n8) \u003c 0.000000001 \u0026\u0026 Math.abs(o10) \u003c 0.000000001)\n throw new Error(`FanoutSolver: cannot infer an escape direction for bus \"${e54}\"`);\n return Math.abs(n8) \u003e= Math.abs(o10) ? n8 \u003e= 0 ? \"right\" : \"left\" : o10 \u003e= 0 ? \"up\" : \"down\";\n}\nfunction Wse(e54) {\n return { x: e54.reduce((e60, t4) =\u003e e60 + t4.sourcePoint.x, 0) / e54.length, y: e54.reduce((e60, t4) =\u003e e60 + t4.sourcePoint.y, 0) / e54.length };\n}\nfunction Gse(e54, t4, n8) {\n switch (t4) {\n case \"left\":\n return e54.x - n8.minX;\n case \"right\":\n return n8.maxX - e54.x;\n case \"up\":\n return n8.maxY - e54.y;\n case \"down\":\n return e54.y - n8.minY;\n }\n}\nfunction Use(e54, t4) {\n return e54.direction === \"up\" || e54.direction === \"down\" ? e54.preferredExit.endsWith(\"left\") ? t4.minX : e54.preferredExit.endsWith(\"right\") ? t4.maxX : (t4.minX + t4.maxX) / 2 : e54.preferredExit.startsWith(\"top\") ? t4.maxY : e54.preferredExit.startsWith(\"bottom\") ? t4.minY : (t4.minY + t4.maxY) / 2;\n}\nfunction Zse(e54, t4) {\n return t4 === \"up\" || t4 === \"down\" ? e54.x : e54.y;\n}\nfunction qse(e54) {\n const { busId: t4, explicitDirection: n8, preferredExit: o10, connections: i8, sharedBoundary: r9, availableRegions: s7 } = e54, a9 = s7.filter((e60) =\u003e !(n8 !== undefined \u0026\u0026 e60.direction !== n8 || o10 !== undefined \u0026\u0026 e60.preferredExit !== o10));\n if (a9.length === 0)\n throw new Error(`FanoutSolver: bus \"${t4}\" cannot use its requested exit with availableCornersAndSides`);\n const c5 = n8 ? undefined : function(e60, t10) {\n try {\n return Vse(e60, t10);\n } catch {\n return;\n }\n }(t4, i8), l5 = c5 ? a9.filter((e60) =\u003e e60.direction === c5) : [], h5 = l5.length \u003e 0 ? l5 : a9, d9 = Wse(i8);\n return [...h5].toSorted((e60, t10) =\u003e Gse(d9, e60.direction, r9) - Gse(d9, t10.direction, r9) || Math.abs(Zse(d9, e60.direction) - Use(e60, r9)) - Math.abs(Zse(d9, t10.direction) - Use(t10, r9)) || e60.preferredExit.localeCompare(t10.preferredExit))[0];\n}\nfunction Jse(e54) {\n const { busId: t4, explicitDirection: n8, preferredExit: o10, connections: i8, sharedBoundary: r9, availableRegions: s7 } = e54;\n if (s7)\n return qse({ busId: t4, explicitDirection: n8, preferredExit: o10, connections: i8, sharedBoundary: r9, availableRegions: s7 });\n if (!o10)\n return { direction: n8 ?? Vse(t4, i8) };\n const a9 = function(e60) {\n switch (e60) {\n case \"left\":\n return [\"left\"];\n case \"right\":\n return [\"right\"];\n case \"top\":\n return [\"up\"];\n case \"bottom\":\n return [\"down\"];\n case \"top-left\":\n return [\"up\", \"left\"];\n case \"top-right\":\n return [\"up\", \"right\"];\n case \"bottom-left\":\n return [\"down\", \"left\"];\n case \"bottom-right\":\n return [\"down\", \"right\"];\n }\n }(o10);\n if (n8) {\n if (!a9.includes(n8))\n throw new Error(`FanoutSolver: bus \"${t4}\" direction \"${n8}\" is incompatible with preferredExit \"${o10}\"`);\n return { direction: n8, preferredExit: o10 };\n }\n if (a9.length === 1)\n return { direction: a9[0], preferredExit: o10 };\n let c5;\n try {\n c5 = Vse(t4, i8);\n } catch {\n c5 = undefined;\n }\n if (c5 \u0026\u0026 a9.includes(c5))\n return { direction: c5, preferredExit: o10 };\n const l5 = Wse(i8);\n return { direction: a9.toSorted((e60, t10) =\u003e Gse(l5, e60, r9) - Gse(l5, t10, r9) || e60.localeCompare(t10))[0], preferredExit: o10 };\n}\nfunction Qse(e54, t4) {\n const n8 = function(e60) {\n const t10 = new Map;\n for (const n11 of e60) {\n if (!n11.componentId || n11.isCopperPour)\n continue;\n const e61 = t10.get(n11.componentId) ?? [];\n e61.push(n11), t10.set(n11.componentId, e61);\n }\n const n10 = [];\n for (const [e61, o11] of t10) {\n const t11 = Ase(o11.map((e63) =\u003e e63.center.x)), i9 = Ase(o11.map((e63) =\u003e e63.center.y)), r10 = kse(o11, \"x\"), s9 = kse(o11, \"y\"), a10 = Ose(t11), c5 = Ose(i9), l5 = Math.min(...[r10, s9, a10, c5].filter(Number.isFinite)), h5 = Math.max(...o11.flatMap((e63) =\u003e [e63.width, e63.height])), d9 = Number.isFinite(l5) ? l5 : h5, u9 = Number.isFinite(r10) ? r10 : Number.isFinite(a10) ? a10 : d9, p9 = Number.isFinite(s9) ? s9 : Number.isFinite(c5) ? c5 : d9;\n n10.push({ componentId: e61, obstacles: o11, xCoordinates: t11, yCoordinates: i9, pitchX: u9, pitchY: p9, bounds: Dse(o11) });\n }\n return n10;\n }(e54.obstacles);\n if (n8.length === 0 \u0026\u0026 e54.connections.length \u003e 0)\n throw new Error(\"FanoutSolver: no componentId-tagged pad footprint was found\");\n const o10 = new Map(e54.connections.map((e60, t10) =\u003e [e60.name, t10])), i8 = function(e60, t10) {\n const n10 = t10.buses ?? e60.buses, o11 = new Map, i9 = new Set, r10 = new Set(e60.connections.map((e61) =\u003e e61.name));\n for (const e61 of n10 ?? []) {\n if (o11.has(e61.busId))\n throw new Error(`FanoutSolver: duplicate bus id \"${e61.busId}\"`);\n for (const t11 of e61.connectionNames) {\n if (!r10.has(t11))\n throw new Error(`FanoutSolver: bus \"${e61.busId}\" references unknown connection \"${t11}\"`);\n if (i9.has(t11))\n throw new Error(`FanoutSolver: connection \"${t11}\" belongs to more than one bus`);\n i9.add(t11);\n }\n const n11 = Xse(e61.busId, e61.termination), s9 = $se(e61.busId, t10.busExitPreferences?.[e61.busId] ?? e61.preferredExit ?? t10.defaultPreferredExit);\n if (n11.type === \"plane\" \u0026\u0026 s9 !== undefined)\n throw new Error(`FanoutSolver: plane-terminated bus \"${e61.busId}\" cannot also specify preferredExit`);\n o11.set(e61.busId, { ...e61, sourceComponentId: e61.sourceComponentId ?? t10.sourceComponentId, direction: t10.busDirections?.[e61.busId] ?? e61.direction ?? t10.defaultDirection, preferredExit: s9, termination: n11 });\n }\n for (const n11 of e60.connections) {\n if (i9.has(n11.name))\n continue;\n const e61 = jse(n11);\n if (e61) {\n const i10 = o11.get(e61);\n o11.set(e61, { busId: e61, connectionNames: [...i10?.connectionNames ?? [], n11.name], direction: t10.busDirections?.[e61] ?? i10?.direction ?? t10.defaultDirection, sourceComponentId: i10?.sourceComponentId ?? t10.sourceComponentId, preferredExit: $se(e61, t10.busExitPreferences?.[e61] ?? i10?.preferredExit ?? t10.defaultPreferredExit), termination: i10?.termination ?? { type: \"boundary\" } });\n } else {\n const e63 = `connection:${n11.name}`;\n o11.set(e63, { busId: e63, connectionNames: [n11.name], sourceComponentId: t10.sourceComponentId, direction: t10.busDirections?.[e63] ?? t10.defaultDirection, preferredExit: $se(e63, t10.busExitPreferences?.[e63] ?? t10.defaultPreferredExit), termination: { type: \"boundary\" } });\n }\n }\n return [...o11.values()];\n }(e54, t4).map((t10) =\u003e {\n for (const [e60, n10] of Object.entries(t10.connectionExitTargets ?? {})) {\n if (!t10.connectionNames.includes(e60))\n throw new Error(`FanoutSolver: connectionExitTargets contains connection \"${e60}\" outside bus \"${t10.busId}\"`);\n if (!Number.isFinite(n10.x) || !Number.isFinite(n10.y))\n throw new Error(`FanoutSolver: connectionExitTargets for connection \"${e60}\" must contain finite x and y coordinates`);\n }\n const i9 = t10.connectionNames.map((t11) =\u003e {\n const n10 = o10.get(t11);\n if (n10 === undefined)\n throw new Error(`FanoutSolver: connection \"${t11}\" is missing from the input`);\n return e54.connections[n10];\n }), r10 = function(e60) {\n const { busSpec: t11, connections: n10, componentGrids: o11 } = e60, i10 = new Map;\n for (const e61 of n10) {\n const t12 = new Set;\n for (const n11 of e61.pointsToConnect)\n for (const i11 of Fse({ point: n11, connection: e61, componentGrids: o11 }))\n t12.add(i11.grid.componentId);\n for (const e63 of t12)\n i10.set(e63, (i10.get(e63) ?? 0) + 1);\n }\n const r11 = [...o11].sort((e61, t12) =\u003e {\n const n11 = (i10.get(t12.componentId) ?? 0) - (i10.get(e61.componentId) ?? 0);\n return n11 !== 0 ? n11 : t12.obstacles.length - e61.obstacles.length;\n })[0], s10 = t11.sourceComponentId ? o11.find((e61) =\u003e e61.componentId === t11.sourceComponentId) : undefined;\n if (t11.sourceComponentId \u0026\u0026 !s10)\n throw new Error(`FanoutSolver: source component \"${t11.sourceComponentId}\" for bus \"${t11.busId}\" was not found`);\n const a10 = s10 ?? r11, c5 = a10 ? i10.get(a10.componentId) ?? 0 : 0;\n if (!a10 || c5 !== n10.length)\n throw new Error(t11.sourceComponentId ? `FanoutSolver: source component \"${t11.sourceComponentId}\" is not an endpoint on every connection in bus \"${t11.busId}\"` : `FanoutSolver: bus \"${t11.busId}\" does not have one component endpoint on every connection`);\n return a10;\n }({ busSpec: t10, connections: i9, componentGrids: n8 }), s9 = i9.map((e60) =\u003e function(e61) {\n const { connection: t11, connectionIndex: n10, sourceGrid: o11, componentGrids: i10, termination: r11, exitTargetPoint: s10 } = e61;\n for (let e63 = 0;e63 \u003c t11.pointsToConnect.length; e63++) {\n const a10 = t11.pointsToConnect[e63], c5 = Fse({ point: a10, connection: t11, componentGrids: i10 }).find((e64) =\u003e e64.grid.componentId === o11.componentId);\n if (!c5)\n continue;\n const l5 = Bse(a10).find((e64) =\u003e c5.obstacle.layers.includes(e64));\n if (!l5)\n throw new Error(`FanoutSolver: connection \"${t11.name}\" has no source layer shared with its BGA pad`);\n const h5 = Hse(a10, t11, e63, r11);\n return { connection: t11, connectionIndex: n10, sourcePoint: a10, sourcePointIndex: e63, sourceLayer: l5, sourceObstacle: c5.obstacle, targetPoint: h5, exitTargetPoint: s10 ?? h5 };\n }\n throw new Error(`FanoutSolver: connection \"${t11.name}\" does not touch component \"${o11.componentId}\"`);\n }({ connection: e60, connectionIndex: o10.get(e60.name), sourceGrid: r10, componentGrids: n8, termination: t10.termination ?? { type: \"boundary\" }, exitTargetPoint: t10.connectionExitTargets?.[e60.name] }));\n return { busSpec: t10, sourceGrid: r10, preparedConnections: s9 };\n }), r9 = function(e60, t10) {\n if (t10.sharedBoundary)\n return zse(t10.sharedBoundary, e60);\n const n10 = e60.map((e61) =\u003e Lse(e61, t10)), o11 = 2.25 * Math.max(...e60.flatMap((e61) =\u003e [e61.pitchX, e61.pitchY]));\n return zse({ minX: Math.min(...n10.map((e61) =\u003e e61.minX)) - o11, maxX: Math.max(...n10.map((e61) =\u003e e61.maxX)) + o11, minY: Math.min(...n10.map((e61) =\u003e e61.minY)) - o11, maxY: Math.max(...n10.map((e61) =\u003e e61.maxY)) + o11 }, e60);\n }([...new Map(i8.map(({ sourceGrid: e60 }) =\u003e [e60.componentId, e60])).values()], t4), s7 = Yse(t4.availableCornersAndSides), a9 = [];\n for (const { busSpec: e60, sourceGrid: n10, preparedConnections: o11 } of i8) {\n const i9 = Jse({ busId: e60.busId, explicitDirection: e60.direction ?? t4.busDirections?.[e60.busId], preferredExit: e60.preferredExit, connections: o11, sharedBoundary: r9, availableRegions: e60.termination?.type === \"plane\" ? undefined : s7 });\n a9.push({ busId: e60.busId, direction: i9.direction, preferredExit: i9.preferredExit, termination: e60.termination ?? { type: \"boundary\" }, connections: o11, componentId: n10.componentId, componentObstacles: n10.obstacles, componentBounds: Lse(n10, t4), sharedBoundary: r9, xCoordinates: [...n10.xCoordinates], yCoordinates: [...n10.yCoordinates], pitchX: n10.pitchX, pitchY: n10.pitchY });\n }\n return a9;\n}\nfunction Kse(e54) {\n return e54 === \"left\" || e54 === \"right\";\n}\nfunction eae(e54) {\n return e54 === \"right\" || e54 === \"up\" ? 1 : -1;\n}\nfunction tae(e54, t4) {\n return Kse(t4) ? e54.x : e54.y;\n}\nfunction nae(e54, t4) {\n return Kse(t4) ? e54.y : e54.x;\n}\nfunction oae(e54, t4, n8) {\n return Kse(n8) ? { x: e54, y: t4 } : { x: t4, y: e54 };\n}\nfunction iae(e54) {\n switch (e54.direction) {\n case \"right\":\n return e54.sharedBoundary.maxX;\n case \"left\":\n return e54.sharedBoundary.minX;\n case \"up\":\n return e54.sharedBoundary.maxY;\n case \"down\":\n return e54.sharedBoundary.minY;\n }\n}\nfunction rae(e54) {\n return Kse(e54.direction) ? e54.pitchX : e54.pitchY;\n}\nfunction sae(e54) {\n const t4 = Kse(e54.direction) ? e54.xCoordinates : e54.yCoordinates, n8 = e54.connections.reduce((t10, n10) =\u003e t10 + tae(n10.sourcePoint, e54.direction), 0) / e54.connections.length, o10 = eae(e54.direction) \u003e 0 ? Math.max(...t4) : Math.min(...t4);\n return Math.abs(n8 - o10) \u003c 0.000001;\n}\nfunction aae(e54, t4) {\n const n8 = [...e54.connections].sort((t10, n10) =\u003e nae(t10.sourcePoint, e54.direction) - nae(n10.sourcePoint, e54.direction)).findIndex((e60) =\u003e e60.connectionIndex === t4.connectionIndex);\n if (n8 \u003c 0)\n throw new Error(`FanoutSolver: connection \"${t4.connection.name}\" is missing from bus \"${e54.busId}\"`);\n return n8;\n}\nfunction cae(e54, t4) {\n return e54.x \u003e= t4.minX - 0.000001 \u0026\u0026 e54.x \u003c= t4.maxX + 0.000001 \u0026\u0026 e54.y \u003e= t4.minY - 0.000001 \u0026\u0026 e54.y \u003c= t4.maxY + 0.000001;\n}\nfunction lae(e54, t4, n8, o10, i8) {\n const r9 = t4 - e54, s7 = Math.floor((r9 - o10) / (n8 + o10) + 0.000000001);\n if (s7 \u003c 1)\n return [];\n const a9 = e54 + (r9 - (s7 * n8 + (s7 - 1) * o10)) / 2 + n8 / 2;\n return Array.from({ length: s7 }, (e60, t10) =\u003e ({ value: a9 + t10 * (n8 + o10), kind: i8 }));\n}\nfunction hae(e54) {\n const t4 = nae(e54.connection.exitTargetPoint ?? e54.connection.targetPoint, e54.bus.direction), n8 = Kse(e54.bus.direction) ? e54.bus.sharedBoundary.minY : e54.bus.sharedBoundary.minX, o10 = Kse(e54.bus.direction) ? e54.bus.sharedBoundary.maxY : e54.bus.sharedBoundary.maxX;\n return Math.max(n8 + e54.traceWidth / 2, Math.min(o10 - e54.traceWidth / 2, t4));\n}\nfunction dae(e54) {\n const { bus: t4, connection: n8, targetUsesVia: o10, interstitialEscape: i8, compactBusTracks: r9, traceWidth: s7, viaDiameter: a9, clearance: c5 } = e54, l5 = (Kse(t4.direction) ? t4.yCoordinates : t4.xCoordinates).toSorted((e60, t10) =\u003e e60 - t10), h5 = nae(n8.sourcePoint, t4.direction);\n if (r9) {\n const e60 = aae(t4, n8);\n return (l5[0] + l5.at(-1)) / 2 + (e60 - (t4.connections.length - 1) / 2) * (s7 + c5);\n }\n if (!o10 || !i8)\n return h5;\n const d9 = function(e60) {\n const t10 = (Kse(e60.direction) ? e60.xCoordinates : e60.yCoordinates).toSorted((e61, t11) =\u003e e61 - t11), n10 = e60.connections.reduce((t11, n11) =\u003e t11 + tae(n11.sourcePoint, e60.direction), 0) / e60.connections.length, o11 = eae(e60.direction) \u003e 0 ? t10.at(-1) : t10[0];\n return Math.abs(o11 - n10) / rae(e60);\n }(t4), u9 = s7 + c5, p9 = Math.ceil(t4.connections.length / 2), m9 = (p9 - 1) * u9, g10 = a9 / 2 + s7 / 2 + c5 + 0.001, f10 = Math.round(d9) + 1, _5 = f10 * g10 + (f10 - 1) * m9, y10 = aae(t4, n8), b10 = l5[0], x8 = l5.at(-1), v10 = y10 \u003c p9 ? b10 - _5 - (p9 - y10 - 1) * u9 : x8 + _5 + (y10 - p9) * u9, I6 = Kse(t4.direction) ? t4.sharedBoundary.minY : t4.sharedBoundary.minX, S6 = Kse(t4.direction) ? t4.sharedBoundary.maxY : t4.sharedBoundary.maxX;\n return Math.max(I6 + s7 / 2, Math.min(S6 - s7 / 2, v10));\n}\nfunction uae(e54) {\n const t4 = eae(e54.direction), n8 = [...e54.connections].sort((n10, o11) =\u003e {\n const i9 = t4 * (tae(o11.sourcePoint, e54.direction) - tae(n10.sourcePoint, e54.direction));\n return Math.abs(i9) \u003e 0.000001 ? i9 : nae(n10.sourcePoint, e54.direction) - nae(o11.sourcePoint, e54.direction);\n }), o10 = [...e54.connections].sort((n10, o11) =\u003e nae(n10.sourcePoint, e54.direction) - nae(o11.sourcePoint, e54.direction) || t4 * (tae(o11.sourcePoint, e54.direction) - tae(n10.sourcePoint, e54.direction))), i8 = [n8, [...n8].reverse(), o10, [...o10].reverse()];\n for (let e60 = 1;e60 \u003c Math.min(n8.length, 8); e60++)\n i8.push([...n8.slice(e60), ...n8.slice(0, e60)]);\n return i8;\n}\nfunction pae(e54, t4, n8, o10, i8) {\n Bre(t4, n8) \u003c 0.000000001 || e54.push({ start: t4, end: n8, width: o10, layer: i8 });\n}\nfunction mae(e54) {\n const { preparedConnection: t4, bus: n8, targetLayer: o10, track: i8, exitAxis: r9, layerNames: s7, traceWidth: a9, viaDiameter: c5, viaHoleDiameter: l5, viaHandedness: h5, interstitialEscape: d9, spreadLaneIndex: u9, clearance: p9, terminateAtVia: m9 } = e54, g10 = { x: t4.sourcePoint.x, y: t4.sourcePoint.y }, f10 = eae(n8.direction), _5 = rae(n8), y10 = function(e60) {\n return Kse(e60.direction) ? e60.pitchY : e60.pitchX;\n }(n8), b10 = o10 !== t4.sourceLayer, x8 = Kse(n8.direction) ? t4.sourceObstacle.width : t4.sourceObstacle.height, v10 = b10 \u0026\u0026 !sae(n8) ? x8 \u003e= _5 ? x8 / 2 + c5 / 2 + p9 + 0.001 : 0.5 * _5 : b10 ? Math.max(0.5 * _5, x8 / 2 + (b10 ? c5 : a9) / 2 + p9 + 0.001) : x8 / 2 + a9 / 2 + p9 + 0.001, I6 = tae(g10, n8.direction) + f10 * v10, S6 = nae(g10, n8.direction) + h5 * y10 * 0.5, C = oae(I6, S6, n8.direction), P = c5 / 2 + a9 / 2 + p9 + 0.001 + u9 * (a9 + p9), M = d9 \u0026\u0026 _5 \u003e= P + c5 / 2 + p9, w = M ? oae(I6 + f10 * P, S6, n8.direction) : C, N = oae(M ? tae(w, n8.direction) : I6 + f10 * Math.abs(i8 - S6), i8, n8.direction), R10 = m9 ? C : oae(r9, i8, n8.direction), T2 = [], E10 = [];\n let A7;\n if (E10.push({ route_type: \"wire\", x: g10.x, y: g10.y, width: a9, layer: t4.sourceLayer, start_pcb_port_id: t4.sourcePoint.pcb_port_id }), pae(T2, g10, C, a9, t4.sourceLayer), E10.push({ route_type: \"wire\", x: C.x, y: C.y, width: a9, layer: t4.sourceLayer }), o10 !== t4.sourceLayer) {\n const e60 = Gre(t4.sourceLayer, o10, s7);\n A7 = { center: C, diameter: c5, holeDiameter: l5, fromLayer: t4.sourceLayer, toLayer: o10, spanLayers: e60 }, E10.push({ route_type: \"via\", x: C.x, y: C.y, from_layer: t4.sourceLayer, to_layer: o10, via_diameter: c5, via_hole_diameter: l5 }), E10.push({ route_type: \"wire\", x: C.x, y: C.y, width: a9, layer: o10 });\n }\n const O10 = m9 ? [C] : M ? function(e60, t10) {\n if (e60.length \u003c 3)\n return e60;\n const n10 = [e60[0]];\n for (let o11 = 1;o11 \u003c e60.length - 1; o11++) {\n const i9 = e60[o11 - 1], r10 = e60[o11], s9 = e60[o11 + 1], a10 = Bre(i9, r10), c9 = Bre(r10, s9);\n if (a10 \u003c 0.000000001 || c9 \u003c 0.000000001)\n continue;\n const l10 = { x: (r10.x - i9.x) / a10, y: (r10.y - i9.y) / a10 }, h9 = { x: (s9.x - r10.x) / c9, y: (s9.y - r10.y) / c9 }, d10 = l10.x * h9.x + l10.y * h9.y;\n if (Math.abs(d10) \u003e 0.000001) {\n n10.push(r10);\n continue;\n }\n const u10 = Math.min(t10, a10 / 2, c9 / 2);\n n10.push({ x: r10.x - l10.x * u10, y: r10.y - l10.y * u10 }), n10.push({ x: r10.x + h9.x * u10, y: r10.y + h9.y * u10 });\n }\n return n10.push(e60.at(-1)), n10;\n }([C, w, N, R10], Math.max(a9 + p9, 2 * a9)) : [C, N, R10];\n for (let e60 = 1;e60 \u003c O10.length; e60++) {\n const t10 = O10[e60 - 1], n10 = O10[e60];\n pae(T2, t10, n10, a9, o10), E10.push({ route_type: \"wire\", x: n10.x, y: n10.y, width: a9, layer: o10 });\n }\n const k6 = Are({ connectionName: t4.connection.name, sourcePointIndex: t4.sourcePointIndex });\n return { busId: n8.busId, connectionName: t4.connection.name, connectionIndex: t4.connectionIndex, sourcePointIndex: t4.sourcePointIndex, sourcePoint: t4.sourcePoint, sourceObstacle: t4.sourceObstacle, sourceLayer: t4.sourceLayer, targetPoint: t4.targetPoint, targetLayer: o10, termination: n8.termination, direction: n8.direction, exitPoint: R10, trace: { type: \"pcb_trace\", pcb_trace_id: k6.traceId, connection_name: t4.connection.name, connectsTo: [...t4.sourcePoint.pointId ? [t4.sourcePoint.pointId] : [], ...t4.sourcePoint.pcb_port_id ? [t4.sourcePoint.pcb_port_id] : [], k6.boundaryExitPointId], route: E10 }, segments: T2, via: A7, length: T2.reduce((e60, t10) =\u003e e60 + Bre(t10.start, t10.end), 0) };\n}\nfunction gae(e54) {\n const { preparedConnection: t4, bus: n8, viaDiameter: o10, clearance: i8 } = e54, { sourcePoint: r9, targetPoint: s7 } = t4, a9 = 0.5 * Math.max(n8.pitchX, n8.pitchY);\n if (Bre(r9, s7) \u003c= 0.000001 || Bre(r9, s7) \u003e a9)\n return [];\n const c5 = (() =\u003e {\n switch (n8.direction) {\n case \"left\":\n return { x: -1, y: 0 };\n case \"right\":\n return { x: 1, y: 0 };\n case \"up\":\n return { x: 0, y: 1 };\n case \"down\":\n return { x: 0, y: -1 };\n }\n })(), l5 = Math.SQRT1_2, h5 = [c5, ...[{ x: l5, y: l5 }, { x: l5, y: -l5 }, { x: -l5, y: l5 }, { x: -l5, y: -l5 }, { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 }].toSorted((e60, t10) =\u003e t10.x * c5.x + t10.y * c5.y - (e60.x * c5.x + e60.y * c5.y))], d9 = Math.max(o10, o10 / 2 + i8), u9 = [d9, Math.max(d9, 0.5 * Math.min(n8.pitchX, n8.pitchY)), Math.max(d9, 0.625 * Math.min(n8.pitchX, n8.pitchY)), Math.max(d9, 0.75 * Math.min(n8.pitchX, n8.pitchY))], p9 = [];\n for (const e60 of [r9, s7])\n for (const t10 of u9)\n for (const n10 of h5) {\n const o11 = { x: e60.x + n10.x * t10, y: e60.y + n10.y * t10 };\n Bre(o11, r9) \u003c= 0.000001 || Bre(o11, s7) \u003c= 0.000001 || p9.some((e61) =\u003e Bre(e61, o11) \u003c= 0.000001) || p9.push(o11);\n }\n return p9;\n}\nfunction fae(e54) {\n const { plan: t4, preparedConnection: n8, planeLayer: o10, viaPoint: i8, layerNames: r9, traceWidth: s7, viaDiameter: a9, viaHoleDiameter: c5 } = e54, l5 = { x: n8.targetPoint.x, y: n8.targetPoint.y }, h5 = function(e60) {\n const t10 = \"layer\" in e60 ? e60.layer : e60.layers[0];\n if (!t10)\n throw new Error(\"FanoutSolver: plane endpoint has no copper layer\");\n return t10;\n }(n8.targetPoint), d9 = Gre(o10, h5, r9);\n if (!d9.includes(o10))\n throw new Error(`FanoutSolver: via for \"${n8.connection.name}\" does not cross plane ${o10}`);\n const u9 = [{ start: i8, end: l5, width: s7, layer: h5 }], p9 = { center: i8, diameter: a9, holeDiameter: c5, fromLayer: o10, toLayer: h5, spanLayers: d9 }, m9 = Are({ connectionName: n8.connection.name, sourcePointIndex: n8.sourcePointIndex }), g10 = { type: \"pcb_trace\", pcb_trace_id: m9.planeEndpointTraceId, connection_name: n8.connection.name, connectsTo: [...n8.targetPoint.pointId ? [n8.targetPoint.pointId] : [], ...n8.targetPoint.pcb_port_id ? [n8.targetPoint.pcb_port_id] : [], m9.planeEndpointPointId], route: [{ route_type: \"wire\", ...i8, width: s7, layer: o10 }, { route_type: \"via\", ...i8, from_layer: o10, to_layer: h5, via_diameter: a9, via_hole_diameter: c5 }, { route_type: \"wire\", ...i8, width: s7, layer: h5 }, { route_type: \"wire\", ...l5, width: s7, layer: h5 }] };\n return { ...t4, planeEndpointTrace: g10, planeEndpointSegments: u9, planeEndpointVia: p9, length: t4.length + u9.reduce((e60, t10) =\u003e e60 + Bre(t10.start, t10.end), 0) };\n}\nfunction _ae(e54) {\n const { segment: t4, plan: n8, segmentIndex: o10, srj: i8, allowSameNetMerges: r9, obstacles: s7, clearance: a9 } = e54;\n for (const e60 of s7)\n if (e60.layers.includes(t4.layer) \u0026\u0026 !e60.connectedTo.includes(n8.connectionName) \u0026\u0026 !(r9 \u0026\u0026 ese(i8, e60, n8.connectionName) || hse({ inputSrj: i8, segment: t4, bodyObstacle: e60, connectionName: n8.connectionName }) || o10 === 0 \u0026\u0026 e60 === n8.sourceObstacle \u0026\u0026 t4.layer === n8.sourceLayer || !(Hre(t4, e60) \u003c t4.width / 2 + a9 - 0.000000001)))\n return false;\n return true;\n}\nfunction yae(e54) {\n return [...e54.segments, ...e54.planeEndpointSegments ?? []];\n}\nfunction bae(e54) {\n return [e54.via, e54.planeEndpointVia].filter((e60) =\u003e Boolean(e60));\n}\nfunction xae(e54) {\n const { plan: t4, srj: n8, sharedBoundary: o10, clearance: i8, allowSameNetMerges: r9 } = e54, s7 = function(e60, t10) {\n return { minX: Math.min(e60.minX, t10.minX), maxX: Math.max(e60.maxX, t10.maxX), minY: Math.min(e60.minY, t10.minY), maxY: Math.max(e60.maxY, t10.maxY) };\n }(n8.bounds, o10);\n if (!cae(t4.exitPoint, s7) || yae(t4).some((e60) =\u003e !cae(e60.start, s7) || !cae(e60.end, s7)))\n return false;\n const a9 = yae(t4);\n for (let e60 = 0;e60 \u003c a9.length; e60++)\n if (!_ae({ segment: a9[e60], plan: t4, segmentIndex: e60 \u003c t4.segments.length ? e60 : -1, srj: n8, allowSameNetMerges: r9, obstacles: n8.obstacles, clearance: i8 }))\n return false;\n for (const e60 of bae(t4))\n for (const o11 of n8.obstacles)\n if (o11.layers.some((t10) =\u003e e60.spanLayers.includes(t10)) \u0026\u0026 (!r9 || !ese(n8, o11, t4.connectionName)) \u0026\u0026 Xre(e60.center, o11) \u003c e60.diameter / 2 + i8 - 0.000000001)\n return false;\n return true;\n}\nfunction vae(e54) {\n const { plan: t4, otherPlans: n8, staticClearanceCache: o10, blockingBusCounts: i8, cacheKey: r9, srj: s7, sharedBoundary: a9, clearance: c5, allowSameNetMerges: l5 } = e54;\n let h5 = o10?.get(r9);\n return h5 === undefined \u0026\u0026 (h5 = xae({ plan: t4, srj: s7, sharedBoundary: a9, clearance: c5, allowSameNetMerges: l5 }), o10?.set(r9, h5)), h5 \u0026\u0026 function(e60) {\n const { plan: t10, otherPlans: n10, srj: o11, allowSameNetMerges: i9, clearance: r10, blockingBusCounts: s9 } = e60;\n for (const e61 of n10) {\n if (i9 \u0026\u0026 Kre(o11, t10.connectionName, e61.connectionName))\n continue;\n if (t10.sourcePoint.pcb_port_id \u0026\u0026 t10.sourcePoint.pcb_port_id === e61.sourcePoint.pcb_port_id || t10.sourcePoint.pointId \u0026\u0026 t10.sourcePoint.pointId === e61.sourcePoint.pointId)\n continue;\n const n11 = () =\u003e {\n e61.busId !== t10.busId \u0026\u0026 s9?.set(e61.busId, (s9.get(e61.busId) ?? 0) + 1);\n }, a10 = yae(t10), c9 = yae(e61), l10 = bae(t10), h9 = bae(e61);\n for (const e63 of a10) {\n for (const t11 of c9)\n if (!Vre(e63, t11, r10))\n return n11(), false;\n for (const t11 of h9)\n if (t11.spanLayers.includes(e63.layer) \u0026\u0026 Fre(t11.center, e63.start, e63.end) \u003c t11.diameter / 2 + e63.width / 2 + r10 - 0.000000001)\n return n11(), false;\n }\n for (const e63 of l10) {\n for (const t11 of c9)\n if (e63.spanLayers.includes(t11.layer) \u0026\u0026 Fre(e63.center, t11.start, t11.end) \u003c e63.diameter / 2 + t11.width / 2 + r10 - 0.000000001)\n return n11(), false;\n for (const t11 of h9)\n if (e63.spanLayers.some((e64) =\u003e t11.spanLayers.includes(e64)) \u0026\u0026 Bre(e63.center, t11.center) \u003c (e63.diameter + t11.diameter) / 2 + r10 - 0.000000001)\n return n11(), false;\n }\n }\n return true;\n }({ plan: t4, otherPlans: n8, srj: s7, allowSameNetMerges: l5, clearance: c5, blockingBusCounts: i8 });\n}\nfunction Iae(e54, t4 = 1) {\n const { srj: n8, bus: o10, targetLayer: i8, acceptedPlans: r9, layerNames: s7, traceWidth: a9, viaDiameter: c5, viaHoleDiameter: l5, clearance: h5, compactBusTracks: d9, staticClearanceCache: u9, blockingBusCounts: p9, allowSameNetMerges: m9 = false } = e54;\n if (!Number.isInteger(t4) || t4 \u003c 1)\n throw new Error(`FanoutSolver: maxAlternatives must be a positive integer, received ${t4}`);\n if (o10.termination.type === \"plane\") {\n const t10 = function(e60) {\n const { srj: t11, bus: n10, targetLayer: o11, acceptedPlans: i9, layerNames: r10, traceWidth: s9, viaDiameter: a10, viaHoleDiameter: c9, clearance: l10, staticClearanceCache: h9, blockingBusCounts: d10, allowSameNetMerges: u10 = false } = e60, p10 = n10.connections[0]?.sourceObstacle;\n if (!p10 || n10.termination.type !== \"plane\")\n return null;\n const m10 = n10.connections[0].sourceLayer;\n if (o11 === m10)\n return null;\n const g11 = [n10.direction, ...[\"left\", \"right\", \"up\", \"down\"].filter((e61) =\u003e e61 !== n10.direction)];\n for (const e61 of g11) {\n const m11 = e61 === n10.direction ? n10 : { ...n10, direction: e61 }, g12 = Kse(e61) ? p10.width : p10.height, f11 = rae(m11) / 2 - g12 / 2 \u003e= a10 / 2 + l10 - 0.000000001, _10 = f11 ? [0] : [1, -1];\n for (const p11 of _10)\n for (const g13 of uae(m11)) {\n const _11 = [];\n let y11 = true;\n for (const b11 of g13) {\n const g14 = nae(b11.sourcePoint, e61), x10 = mae({ preparedConnection: b11, bus: m11, targetLayer: o11, track: g14, exitAxis: iae(m11), layerNames: r10, traceWidth: s9, viaDiameter: a10, viaHoleDiameter: c9, viaHandedness: p11, interstitialEscape: !f11, spreadLaneIndex: 0, clearance: l10, terminateAtVia: true }), v11 = [...gae({ preparedConnection: b11, bus: m11, viaDiameter: a10, clearance: l10 }).map((e63) =\u003e fae({ plan: x10, preparedConnection: b11, planeLayer: o11, viaPoint: e63, layerNames: r10, traceWidth: s9, viaDiameter: a10, viaHoleDiameter: c9 })), x10].find((r11, s10) =\u003e vae({ plan: r11, otherPlans: [...i9, ..._11], staticClearanceCache: h9, blockingBusCounts: d10, cacheKey: `plane:${n10.busId}:${o11}:${e61}:${b11.connectionIndex}:${p11}:${s10}`, srj: t11, sharedBoundary: n10.sharedBoundary, clearance: l10, allowSameNetMerges: u10 }));\n if (!v11) {\n y11 = false;\n break;\n }\n _11.push(v11);\n }\n if (y11)\n return _11;\n }\n }\n return null;\n }(e54);\n return t10 ? [t10] : [];\n }\n const g10 = iae(o10), f10 = o10.connections[0]?.sourceObstacle;\n if (!f10)\n return [[]];\n const _5 = Kse(o10.direction) ? f10.width : f10.height, y10 = o10.connections[0].sourceLayer, b10 = i8 !== y10, x8 = sae(o10), v10 = rae(o10) / 2 - _5 / 2 \u003e= c5 / 2 + h5 - 0.000000001, I6 = b10 \u0026\u0026 !x8 \u0026\u0026 !v10, S6 = b10 ? v10 || x8 ? [0] : [1, -1] : [0], C = [], P = new Set, M = (e60, f11, _10, y11) =\u003e {\n if (C.length \u003e= t4)\n return;\n if (_10 \u003e= e60.length)\n return void ((e61) =\u003e {\n const t10 = e61.map((e63) =\u003e `${e63.connectionIndex}:${e63.targetLayer}:${e63.exitPoint.x}:${e63.exitPoint.y}:${e63.segments.map((e64) =\u003e `${e64.start.x},${e64.start.y},${e64.end.x},${e64.end.y},${e64.layer}`).join(\";\")}`).join(\"|\");\n P.has(t10) || (P.add(t10), C.push(e61));\n })(y11);\n const x10 = e60[_10], v11 = aae(o10, x10), S10 = [hae({ bus: o10, connection: x10, traceWidth: a9 }), dae({ bus: o10, connection: x10, targetUsesVia: b10, interstitialEscape: I6, compactBusTracks: d9, traceWidth: a9, viaDiameter: c5, clearance: h5 })].filter((e61, t10, n10) =\u003e n10.findIndex((t11) =\u003e Math.abs(t11 - e61) \u003c 0.000000001) === t10).flatMap((e61) =\u003e function(e63) {\n const { bus: t10, connection: n10, preferredTrack: o11, traceWidth: i9, clearance: r10 } = e63, s9 = (Kse(t10.direction) ? t10.yCoordinates : t10.xCoordinates).toSorted((e64, t11) =\u003e e64 - t11), a10 = Math.max(...t10.componentObstacles.map((e64) =\u003e Kse(t10.direction) ? e64.height / 2 : e64.width / 2)), c9 = Kse(t10.direction) ? t10.sharedBoundary.minY : t10.sharedBoundary.minX, l10 = Kse(t10.direction) ? t10.sharedBoundary.maxY : t10.sharedBoundary.maxX, h9 = l10 - c9, d10 = l10, u10 = [{ value: o11, kind: \"preferred\" }, ...lae(c9, s9[0] - a10, i9, r10, \"margin\")];\n for (let e64 = 0;e64 \u003c s9.length; e64++)\n u10.push({ value: s9[e64], kind: \"corridor\" }), e64 \u003c s9.length - 1 \u0026\u0026 u10.push(...lae(s9[e64] + a10, s9[e64 + 1] - a10, i9, r10, \"gap\"));\n u10.push(...lae(s9.at(-1) + a10, d10, i9, r10, \"margin\"));\n const p10 = nae(n10.sourcePoint, t10.direction), m10 = (s9[0] + s9.at(-1)) / 2;\n return u10.filter((e64) =\u003e Math.abs(e64.value - p10) \u003c= h9 + 0.000000001).filter((e64, t11, n11) =\u003e n11.findIndex((t12) =\u003e Math.abs(t12.value - e64.value) \u003c 0.000000001) === t11).sort((e64, t11) =\u003e Math.abs(e64.value - o11) - Math.abs(t11.value - o11) - 0.001 * (Math.abs(e64.value - m10) - Math.abs(t11.value - m10)));\n }({ bus: o10, connection: x10, preferredTrack: e61, traceWidth: a9, clearance: h5 })).filter((e61, t10, n10) =\u003e n10.findIndex((t11) =\u003e Math.abs(t11.value - e61.value) \u003c 0.000000001) === t10);\n for (let d10 = 0;d10 \u003c S10.length; d10++) {\n const b11 = S10[d10], P7 = mae({ preparedConnection: x10, bus: o10, targetLayer: i8, track: b11.value, exitAxis: g10, layerNames: s7, traceWidth: a9, viaDiameter: c5, viaHoleDiameter: l5, viaHandedness: f11, interstitialEscape: I6, spreadLaneIndex: Math.min(v11, o10.connections.length - v11 - 1), clearance: h5, terminateAtVia: false });\n if (vae({ plan: P7, otherPlans: [...r9, ...y11], staticClearanceCache: u9, blockingBusCounts: p9, cacheKey: `boundary:${o10.busId}:${i8}:${x10.connectionIndex}:${f11}:${d10}`, srj: n8, sharedBoundary: o10.sharedBoundary, clearance: h5, allowSameNetMerges: m9 })) {\n if (M(e60, f11, _10 + 1, [...y11, P7]), C.length \u003e= t4)\n return;\n if (t4 === 1)\n return;\n }\n }\n };\n for (const e60 of S6)\n for (const n10 of uae(o10))\n if (M(n10, e60, 0, []), C.length \u003e= t4)\n return C;\n return C;\n}\nfunction Sae(e54) {\n return Iae(e54, 1)[0] ?? null;\n}\nvar Cae = 0.000000001;\nvar Pae = globalThis.process?.env?.FANOUT_FLOW_DEBUG === \"1\";\nfunction Mae(e54) {\n const t4 = e54.connection;\n return e54.sourceObstacle.connectedTo.find((e60) =\u003e e60.startsWith(\"connectivity_net\")) ?? t4.netConnectionName ?? e54.connection.name.replace(/::fanout:\\d+$/, \"\");\n}\nfunction wae(e54, t4) {\n return e54 === t4.connection.sourceObstacle || e54.connectedTo.includes(t4.connection.connection.name) || e54.connectedTo.includes(t4.netKey);\n}\nfunction Nae(e54, t4) {\n const n8 = t4.x - e54.x, o10 = t4.y - e54.y, i8 = Math.abs(n8), r9 = Math.abs(o10);\n return i8 \u003c Cae || r9 \u003c Cae || Math.abs(i8 - r9) \u003c Cae ? [e54, t4] : i8 \u003e r9 ? [e54, { x: e54.x + Math.sign(n8) * r9, y: t4.y }, t4] : [e54, { x: t4.x, y: e54.y + Math.sign(o10) * i8 }, t4];\n}\nfunction Rae(e54) {\n if (e54.length \u003c 2)\n return e54;\n const t4 = [e54[0]];\n for (const n8 of e54.slice(1)) {\n const e60 = t4.at(-1), o10 = Math.abs(n8.x - e60.x), i8 = Math.abs(n8.y - e60.y);\n o10 \u003c Cae || i8 \u003c Cae || Math.abs(o10 - i8) \u003c Cae ? t4.push(n8) : t4.push(...Nae(n8, e60).reverse().slice(1));\n }\n return Tae(t4);\n}\nfunction Tae(e54) {\n if (e54.length \u003c 3)\n return e54;\n const t4 = [e54[0]];\n for (let n8 = 1;n8 \u003c e54.length - 1; n8++) {\n const o10 = t4.at(-1), i8 = e54[n8], r9 = e54[n8 + 1];\n Math.sign(i8.x - o10.x) === Math.sign(r9.x - i8.x) \u0026\u0026 Math.sign(i8.y - o10.y) === Math.sign(r9.y - i8.y) || t4.push(i8);\n }\n return t4.push(e54.at(-1)), t4;\n}\nfunction Eae(e54, t4) {\n if (e54.length \u003c 3)\n return e54;\n const n8 = [e54[0]];\n for (let o10 = 1;o10 \u003c e54.length - 1; o10++) {\n const i8 = e54[o10 - 1], r9 = e54[o10], s7 = e54[o10 + 1], a9 = Bre(i8, r9), c5 = Bre(r9, s7);\n if (a9 \u003c Cae || c5 \u003c Cae)\n continue;\n const l5 = { x: (r9.x - i8.x) / a9, y: (r9.y - i8.y) / a9 }, h5 = { x: (s7.x - r9.x) / c5, y: (s7.y - r9.y) / c5 };\n if (Math.abs(l5.x * h5.x + l5.y * h5.y) \u003e 0.000001) {\n n8.push(r9);\n continue;\n }\n const d9 = Math.min(t4, a9 / 2, c5 / 2);\n n8.push({ x: r9.x - l5.x * d9, y: r9.y - l5.y * d9 }), n8.push({ x: r9.x + h5.x * d9, y: r9.y + h5.y * d9 });\n }\n return n8.push(e54.at(-1)), Tae(n8);\n}\nfunction Aae(e54, t4) {\n const n8 = [];\n for (let o10 = 1;o10 \u003c e54.length; o10++)\n Bre(e54[o10 - 1], e54[o10]) \u003c Cae || n8.push({ start: e54[o10 - 1], end: e54[o10], width: t4, layer: \"top\" });\n return n8;\n}\nvar Oae = class {\n edges;\n levels;\n nextEdges;\n constructor(e54) {\n this.edges = Array.from({ length: e54 }, () =\u003e []), this.levels = new Int32Array(e54), this.nextEdges = new Int32Array(e54);\n }\n addEdge(e54, t4, n8, o10 = {}) {\n const i8 = { to: t4, reverseIndex: this.edges[t4].length, capacity: n8, initialCapacity: n8, ...o10 }, r9 = { to: e54, reverseIndex: this.edges[e54].length, capacity: 0, initialCapacity: 0 };\n this.edges[e54].push(i8), this.edges[t4].push(r9);\n }\n buildLevels(e54, t4) {\n this.levels.fill(-1);\n const n8 = new Int32Array(this.edges.length);\n let o10 = 0, i8 = 0;\n for (n8[i8++] = e54, this.levels[e54] = 0;o10 \u003c i8; ) {\n const e60 = n8[o10++];\n for (const t10 of this.edges[e60])\n t10.capacity \u003c= 0 || this.levels[t10.to] \u003e= 0 || (this.levels[t10.to] = this.levels[e60] + 1, n8[i8++] = t10.to);\n }\n return this.levels[t4] \u003e= 0;\n }\n sendFlow(e54, t4) {\n if (e54 === t4)\n return 1;\n for (let n8 = this.nextEdges[e54];n8 \u003c this.edges[e54].length; n8++, this.nextEdges[e54] = n8) {\n const o10 = this.edges[e54][n8];\n if (o10.capacity \u003c= 0 || this.levels[o10.to] !== this.levels[e54] + 1)\n continue;\n const i8 = this.sendFlow(o10.to, t4);\n if (i8 !== 0)\n return o10.capacity -= i8, this.edges[o10.to][o10.reverseIndex].capacity += i8, i8;\n }\n return 0;\n }\n maximumFlow(e54, t4, n8) {\n let o10 = 0;\n for (;o10 \u003c n8 \u0026\u0026 this.buildLevels(e54, t4); )\n for (this.nextEdges.fill(0);o10 \u003c n8; ) {\n const n10 = this.sendFlow(e54, t4);\n if (n10 === 0)\n break;\n o10 += n10;\n }\n return o10;\n }\n};\nfunction kae(e54) {\n const { direction: t4, availableDirections: n8, items: o10, grid: i8, obstacles: r9, traceWidth: s7, clearance: a9, occupiedNodes: c5, acceptedSegments: l5, connectorSelectionOffset: h5 = 0 } = e54;\n if (o10.length === 0)\n return { routes: [], usedNodes: [], unmatchedItems: [] };\n const { boundary: d9, step: u9, columnCount: p9, rowCount: m9, nodeCount: g10 } = i8, f10 = (e60) =\u003e i8.points[e60], _5 = s7 / 2 + a9, y10 = s7 + a9, b10 = new Uint8Array(g10);\n for (let e60 = 0;e60 \u003c g10; e60++)\n !c5[e60] \u0026\u0026 i8.obstacleFreeNodes[e60] \u0026\u0026 (b10[e60] = 1);\n const x8 = (e60, t10) =\u003e {\n const n10 = Aae(e60, s7);\n return n10.every((e61) =\u003e r9.every((n11) =\u003e wae(n11, t10) || Hre(e61, n11) \u003e= _5 - Cae)) \u0026\u0026 n10.every((e61) =\u003e l5.every((t11) =\u003e $re(e61.start, e61.end, t11.start, t11.end) \u003e= y10 - Cae));\n }, v10 = new Map;\n for (const e60 of o10) {\n const t10 = `${e60.source.x.toFixed(6)}:${e60.source.y.toFixed(6)}:${e60.netKey}`, n10 = v10.get(t10) ?? [];\n n10.push(e60), v10.set(t10, n10);\n }\n const I6 = Array.from({ length: 3721 }, (e60, t10) =\u003e {\n const n10 = t10 % 61 - 30, o11 = Math.floor(t10 / 61) - 30;\n return { x: n10, y: o11, distanceSquared: n10 * n10 + o11 * o11 };\n }).sort((e60, t10) =\u003e e60.distanceSquared - t10.distanceSquared), S6 = [];\n for (const e60 of v10.values()) {\n const t10 = e60[0], n10 = Math.hypot(t10.connection.sourceObstacle.width / 2, t10.connection.sourceObstacle.height / 2) + a9 + 2 * u9, o11 = Math.round((t10.source.x - d9.minX) / u9), i9 = Math.round((t10.source.y - d9.minY) / u9), r10 = [], s9 = new Set;\n for (const e61 of I6) {\n const a10 = o11 + e61.x, c9 = i9 + e61.y;\n if (a10 \u003c 0 || a10 \u003e= p9 || c9 \u003c 0 || c9 \u003e= m9)\n continue;\n const l10 = c9 * p9 + a10;\n if (!b10[l10] || s9.has(l10))\n continue;\n if (Bre(t10.source, f10(l10)) \u003e n10)\n continue;\n const h9 = Nae(t10.source, f10(l10));\n if (x8(h9, t10) \u0026\u0026 (s9.add(l10), r10.push({ node: l10, connectorPoints: h9 }), r10.length \u003e= 12))\n break;\n }\n if (r10.length === 0)\n return null;\n S6.push({ item: t10, equivalentItems: e60, candidates: r10 });\n }\n const C = [];\n for (const e60 of [...S6].sort((e61, t10) =\u003e e61.candidates.length - t10.candidates.length)) {\n const t10 = e60.candidates.length === 0 ? 0 : h5 % e60.candidates.length, n10 = [...e60.candidates.slice(t10), ...e60.candidates.slice(0, t10)].find((t11) =\u003e {\n const n11 = Aae(t11.connectorPoints, s7);\n return C.every((t12) =\u003e t12.netKey === e60.item.netKey || n11.every((e61) =\u003e t12.segments.every((t13) =\u003e $re(e61.start, e61.end, t13.start, t13.end) \u003e= y10 - Cae)));\n });\n if (!n10)\n return null;\n e60.candidates = [n10], C.push({ netKey: e60.item.netKey, segments: Aae(n10.connectorPoints, s7) });\n }\n const P = new Set(S6.map((e60) =\u003e e60.candidates[0].node));\n for (const e60 of C)\n for (const t10 of e60.segments) {\n const e61 = Math.max(0, Math.floor((Math.min(t10.start.x, t10.end.x) - y10 - d9.minX) / u9)), n10 = Math.min(p9 - 1, Math.ceil((Math.max(t10.start.x, t10.end.x) + y10 - d9.minX) / u9)), o11 = Math.max(0, Math.floor((Math.min(t10.start.y, t10.end.y) - y10 - d9.minY) / u9)), i9 = Math.min(m9 - 1, Math.ceil((Math.max(t10.start.y, t10.end.y) + y10 - d9.minY) / u9));\n for (let r10 = o11;r10 \u003c= i9; r10++)\n for (let o12 = e61;o12 \u003c= n10; o12++) {\n const e63 = r10 * p9 + o12;\n if (!b10[e63] || P.has(e63))\n continue;\n const n11 = f10(e63);\n $re(t10.start, t10.end, n11, n11) \u003c y10 - Cae \u0026\u0026 (b10[e63] = 0);\n }\n }\n const M = 1 + S6.length, w = M + g10, N = w + g10, R10 = new Oae(N + 1);\n for (let e60 = 0;e60 \u003c S6.length; e60++) {\n const t10 = 1 + e60;\n R10.addEdge(0, t10, 1);\n for (const n10 of S6[e60].candidates)\n R10.addEdge(t10, M + n10.node, 1, { gridNode: n10.node });\n }\n for (let e60 = 0;e60 \u003c g10; e60++) {\n if (!b10[e60])\n continue;\n R10.addEdge(M + e60, w + e60, 1);\n const o11 = e60 % p9, r10 = Math.floor(e60 / p9);\n for (const t10 of i8.neighbors[e60])\n b10[t10] \u0026\u0026 R10.addEdge(w + e60, M + t10, 1, { gridNode: t10 });\n (t4 === \"any\" \u0026\u0026 ((!n8 || n8.has(\"left\")) \u0026\u0026 o11 === 0 || (!n8 || n8.has(\"right\")) \u0026\u0026 o11 === p9 - 1 || (!n8 || n8.has(\"down\")) \u0026\u0026 r10 === 0 || (!n8 || n8.has(\"up\")) \u0026\u0026 r10 === m9 - 1) || t4 === \"left\" \u0026\u0026 o11 === 0 || t4 === \"right\" \u0026\u0026 o11 === p9 - 1 || t4 === \"down\" \u0026\u0026 r10 === 0 || t4 === \"up\" \u0026\u0026 r10 === m9 - 1) \u0026\u0026 R10.addEdge(w + e60, N, 1, { isSink: true });\n }\n const T2 = R10.maximumFlow(0, N, S6.length), E10 = (e60) =\u003e {\n const t10 = 1 + e60;\n return R10.edges[0].some((e61) =\u003e e61.to === t10 \u0026\u0026 e61.initialCapacity === 1 \u0026\u0026 e61.capacity === 0);\n };\n if (T2 !== S6.length \u0026\u0026 Pae) {\n const e60 = S6.flatMap((e61, t10) =\u003e E10(t10) ? [] : [e61.item.connection.connection.name]);\n console.error(\"single-layer flow group failed\", { direction: t4, achievedFlow: T2, requiredFlow: S6.length, unmatchedConnections: e60 });\n }\n const A7 = [], O10 = [], k6 = [];\n for (let e60 = 0;e60 \u003c S6.length; e60++) {\n const t10 = S6[e60];\n if (!E10(e60)) {\n k6.push(...t10.equivalentItems);\n continue;\n }\n const n10 = 1 + e60, o11 = R10.edges[n10].find((e61) =\u003e e61.initialCapacity === 1 \u0026\u0026 e61.capacity === 0 \u0026\u0026 e61.gridNode !== undefined);\n if (o11?.gridNode === undefined)\n return null;\n const i9 = t10.candidates.find((e61) =\u003e e61.node === o11.gridNode);\n if (!i9)\n return null;\n const r10 = [f10(i9.node)];\n let a10 = i9.node;\n const c9 = [a10];\n for (let e61 = 0;e61 \u003c= g10; e61++) {\n const e63 = w + a10, t11 = R10.edges[e63].find((e64) =\u003e e64.initialCapacity === 1 \u0026\u0026 e64.capacity === 0 \u0026\u0026 (e64.gridNode !== undefined || e64.isSink));\n if (!t11)\n return null;\n if (t11.isSink)\n break;\n if (t11.gridNode === undefined)\n return null;\n a10 = t11.gridNode, c9.push(a10), r10.push(f10(a10));\n }\n O10.push(...c9);\n const l10 = Rae(Eae(Tae([...i9.connectorPoints, ...r10.slice(1)]), u9 / 2)), h9 = Aae(l10, s7);\n for (const e61 of t10.equivalentItems)\n A7.push({ item: e61, points: l10, segments: h9 });\n }\n return { routes: A7, usedNodes: O10, unmatchedItems: k6 };\n}\nfunction Dae(e54, t4) {\n const n8 = Nae(e54, t4), o10 = Nae(t4, e54).reverse();\n return n8.length === o10.length \u0026\u0026 n8.every((e60, t10) =\u003e Bre(e60, o10[t10]) \u003c Cae) ? [n8] : [n8, o10];\n}\nfunction Lae(e54, t4) {\n return Math.abs(e54.x - t4.minX) \u003c Cae ? \"left\" : Math.abs(e54.x - t4.maxX) \u003c Cae ? \"right\" : Math.abs(e54.y - t4.minY) \u003c Cae ? \"down\" : Math.abs(e54.y - t4.maxY) \u003c Cae ? \"up\" : null;\n}\nfunction zae(e54) {\n const { items: t4, grid: n8, obstacles: o10, traceWidth: i8, clearance: r9, availableBoundaryRegions: s7 } = e54, a9 = s7 ? new Set(s7.map((e60) =\u003e e60.direction)) : undefined, c5 = new Set(t4.filter((e60) =\u003e e60.connection.sourceObstacle.width \u003e 2 \u0026\u0026 e60.connection.sourceObstacle.height \u003e 2));\n let l5 = null;\n for (let e60 = 0;e60 \u003c 4; e60++) {\n const e61 = t4.filter((e63) =\u003e !c5.has(e63));\n let s9 = null;\n for (let t10 = 0;t10 \u003c 4; t10++) {\n const c9 = kae({ direction: \"any\", availableDirections: a9, items: e61, grid: n8, obstacles: o10, traceWidth: i8, clearance: r9, occupiedNodes: new Uint8Array(n8.nodeCount), acceptedSegments: [], connectorSelectionOffset: t10 });\n if (c9 \u0026\u0026 ((!s9 || c9.routes.length \u003e s9.routes.length) \u0026\u0026 (s9 = c9), c9.routes.length === e61.length))\n break;\n }\n if (!s9)\n return null;\n if (s9.routes.length === e61.length) {\n l5 = s9;\n break;\n }\n const h9 = new Map;\n for (const t10 of e61)\n h9.set(t10.netKey, (h9.get(t10.netKey) ?? 0) + 1);\n let d10 = false;\n for (const e63 of s9.unmatchedItems)\n (h9.get(e63.netKey) ?? 0) \u003c 2 || (c5.add(e63), d10 = true);\n if (!d10)\n return null;\n }\n if (!l5)\n return null;\n const h5 = [...l5.routes], d9 = i8 / 2 + r9, u9 = i8 + r9;\n for (const e60 of c5) {\n const t10 = h5.filter((t11) =\u003e t11.item.netKey === e60.netKey).flatMap((e61) =\u003e e61.points.map((t11, n11) =\u003e ({ route: e61, point: t11, pointIndex: n11 }))).sort((t11, n11) =\u003e Number(n11.route.item.bus.componentId === e60.bus.componentId) - Number(t11.route.item.bus.componentId === e60.bus.componentId) || Bre(e60.source, t11.point) - Bre(e60.source, n11.point));\n let n10 = null;\n for (const r10 of t10) {\n for (const t11 of Dae(e60.source, r10.point)) {\n const s9 = Aae(t11, i8), a10 = s9.every((t12) =\u003e o10.every((n11) =\u003e wae(n11, e60) || Hre(t12, n11) \u003e= d9 - Cae)), c9 = s9.every((t12) =\u003e h5.every((n11) =\u003e n11.item.netKey === e60.netKey || n11.segments.every((e61) =\u003e $re(t12.start, t12.end, e61.start, e61.end) \u003e= u9 - Cae)));\n if (!a10 || !c9)\n continue;\n const l10 = Rae(Tae([...t11, ...r10.route.points.slice(r10.pointIndex + 1)]));\n n10 = { item: e60, points: l10, segments: Aae(l10, i8) };\n break;\n }\n if (n10)\n break;\n }\n if (!n10)\n return null;\n h5.push(n10);\n }\n const p9 = h5.map((e60) =\u003e function(e61, t10) {\n const { item: n10, points: o11, segments: i9 } = e61, r10 = o11.map((e63, o12) =\u003e ({ route_type: \"wire\", x: e63.x, y: e63.y, width: t10, layer: \"top\", ...o12 === 0 \u0026\u0026 n10.connection.sourcePoint.pcb_port_id ? { start_pcb_port_id: n10.connection.sourcePoint.pcb_port_id } : {} })), s9 = Are({ connectionName: n10.connection.connection.name, sourcePointIndex: n10.connection.sourcePointIndex });\n return { busId: n10.bus.busId, connectionName: n10.connection.connection.name, connectionIndex: n10.connection.connectionIndex, sourcePointIndex: n10.connection.sourcePointIndex, sourcePoint: n10.connection.sourcePoint, sourceObstacle: n10.connection.sourceObstacle, sourceLayer: n10.connection.sourceLayer, targetPoint: n10.connection.targetPoint, targetLayer: \"top\", termination: n10.bus.termination, direction: n10.bus.direction, exitPoint: o11.at(-1), trace: { type: \"pcb_trace\", pcb_trace_id: s9.traceId, connection_name: n10.connection.connection.name, connectsTo: [...n10.connection.sourcePoint.pointId ? [n10.connection.sourcePoint.pointId] : [], ...n10.connection.sourcePoint.pcb_port_id ? [n10.connection.sourcePoint.pcb_port_id] : [], s9.boundaryExitPointId], route: r10 }, segments: i9, length: i9.reduce((e63, t11) =\u003e e63 + Bre(t11.start, t11.end), 0) };\n }(e60, i8));\n if (!function(e60) {\n const { plans: t10, items: n10, obstacles: o11, traceWidth: i9, clearance: r10 } = e60, s9 = new Map(n10.map((e61) =\u003e [e61.connection.connection.name, e61.netKey])), a10 = new Map, c9 = new Map;\n for (const e61 of t10) {\n const t11 = s9.get(e61.connectionName), n11 = a10.get(t11) ?? [], o12 = c9.get(t11) ?? new Set;\n for (const t12 of e61.segments) {\n const e63 = [t12.start, t12.end].map((e64) =\u003e `${e64.x.toFixed(6)}:${e64.y.toFixed(6)}`).sort().join(\":\");\n o12.has(e63) || (o12.add(e63), n11.push(t12));\n }\n a10.set(t11, n11), c9.set(t11, o12);\n }\n const l10 = i9 / 2 + r10;\n for (const [e61, t11] of a10)\n for (const n11 of t11)\n for (const t12 of o11)\n if (!(t12.connectedTo.includes(e61) || Hre(n11, t12) \u003e= l10 - Cae))\n return Pae \u0026\u0026 console.error(\"single-layer route violates obstacle clearance\", { netKey: e61, segment: n11, obstacleId: t12.obstacleId, distance: Hre(n11, t12), requiredObstacleDistance: l10 }), false;\n const h9 = i9 + r10, d10 = [...a10];\n for (let e61 = 0;e61 \u003c d10.length; e61++)\n for (let t11 = e61 + 1;t11 \u003c d10.length; t11++)\n for (const n11 of d10[e61][1])\n for (const o12 of d10[t11][1])\n if ($re(n11.start, n11.end, o12.start, o12.end) \u003c h9 - Cae)\n return Pae \u0026\u0026 console.error(\"single-layer routes violate copper clearance\", { firstNetKey: d10[e61][0], secondNetKey: d10[t11][0], first: n11, second: o12, distance: $re(n11.start, n11.end, o12.start, o12.end), requiredRouteDistance: h9 }), false;\n return true;\n }({ plans: p9, items: t4, obstacles: o10, traceWidth: i8, clearance: r9 }))\n return Pae \u0026\u0026 console.error(\"single-layer adaptive exits failed exact clearance\"), null;\n for (const e60 of p9) {\n const o11 = Lae(e60.exitPoint, n8.boundary);\n if (!o11 || a9 \u0026\u0026 !a9.has(o11))\n return null;\n const i9 = t4.find((t10) =\u003e t10.connection.connection.name === e60.connectionName);\n i9.bus.direction = o11;\n const r10 = s7?.filter((e61) =\u003e e61.direction === o11), c9 = o11 === \"up\" || o11 === \"down\" ? e60.exitPoint.x : e60.exitPoint.y;\n i9.bus.preferredExit = r10?.toSorted((e61, t10) =\u003e Math.abs(c9 - Use(e61, n8.boundary)) - Math.abs(c9 - Use(t10, n8.boundary)))[0]?.preferredExit ?? (o11 === \"up\" ? \"top\" : o11 === \"down\" ? \"bottom\" : o11), e60.direction = o11;\n }\n const m9 = new Map(p9.map((e60) =\u003e [e60.connectionName, e60]));\n return t4.map((e60) =\u003e m9.get(e60.connection.connection.name));\n}\nfunction Bae(e54) {\n const { srj: t4, buses: n8, traceWidth: o10, clearance: i8, availableBoundaryRegions: r9 } = e54;\n if (n8.some((e60) =\u003e e60.connections.length !== 1))\n return null;\n const s7 = n8.flatMap((e60) =\u003e e60.connections.map((t10) =\u003e ({ bus: e60, connection: t10, source: { x: t10.sourcePoint.x, y: t10.sourcePoint.y }, netKey: Mae(t10) }))), a9 = t4.obstacles.filter((e60) =\u003e e60.layers.includes(\"top\")), c5 = n8[0]?.sharedBoundary;\n if (!c5)\n return [];\n const l5 = function(e60) {\n const { boundary: t10, obstacles: n10, traceWidth: o11, clearance: i9 } = e60, r10 = o11 + i9, s9 = Math.round((t10.maxX - t10.minX) / r10) + 1, a10 = Math.round((t10.maxY - t10.minY) / r10) + 1, c9 = s9 * a10, l10 = Array.from({ length: c9 }, (e61, n11) =\u003e ({ x: t10.minX + n11 % s9 * r10, y: t10.minY + Math.floor(n11 / s9) * r10 })), h9 = o11 / 2 + i9, d9 = new Map;\n for (let e61 = 0;e61 \u003c n10.length; e61++) {\n const t11 = n10[e61], o12 = Math.floor((t11.center.x - t11.width / 2 - h9) / 1), i10 = Math.floor((t11.center.x + t11.width / 2 + h9) / 1), r11 = Math.floor((t11.center.y - t11.height / 2 - h9) / 1), s10 = Math.floor((t11.center.y + t11.height / 2 + h9) / 1);\n for (let t12 = o12;t12 \u003c= i10; t12++)\n for (let n11 = r11;n11 \u003c= s10; n11++) {\n const o13 = `${t12}:${n11}`, i11 = d9.get(o13) ?? [];\n i11.push(e61), d9.set(o13, i11);\n }\n }\n const u9 = (e61, t11 = e61) =\u003e {\n const o12 = Math.floor(Math.min(e61.x, t11.x) / 1), i10 = Math.floor(Math.max(e61.x, t11.x) / 1), r11 = Math.floor(Math.min(e61.y, t11.y) / 1), s10 = Math.floor(Math.max(e61.y, t11.y) / 1), a11 = new Set;\n for (let e63 = o12;e63 \u003c= i10; e63++)\n for (let t12 = r11;t12 \u003c= s10; t12++)\n for (const n11 of d9.get(`${e63}:${t12}`) ?? [])\n a11.add(n11);\n return [...a11].map((e63) =\u003e n10[e63]);\n }, p9 = new Uint8Array(c9);\n for (let e61 = 0;e61 \u003c c9; e61++) {\n const t11 = l10[e61];\n u9(t11).every((e63) =\u003e Xre(t11, e63) \u003e= h9 - Cae) \u0026\u0026 (p9[e61] = 1);\n }\n const m9 = Array.from({ length: c9 }, () =\u003e []);\n for (let e61 = 0;e61 \u003c c9; e61++) {\n if (!p9[e61])\n continue;\n const t11 = e61 % s9, n11 = Math.floor(e61 / s9);\n for (const [i10, r11] of [[1, 0], [0, 1]]) {\n const c10 = t11 + i10, d10 = n11 + r11;\n if (c10 \u003e= s9 || d10 \u003e= a10)\n continue;\n const g10 = d10 * s9 + c10;\n if (!p9[g10])\n continue;\n const f10 = { start: l10[e61], end: l10[g10], width: o11, layer: \"top\" };\n u9(f10.start, f10.end).some((e63) =\u003e Hre(f10, e63) \u003c h9 - Cae) || (m9[e61].push(g10), m9[g10].push(e61));\n }\n }\n return { boundary: t10, step: r10, columnCount: s9, rowCount: a10, nodeCount: c9, points: l10, obstacleFreeNodes: p9, neighbors: m9 };\n }({ boundary: c5, obstacles: a9, traceWidth: o10, clearance: i8 });\n Pae \u0026\u0026 console.error(\"single-layer adaptive-exit grid ready\", { nodeCount: l5.nodeCount });\n const h5 = zae({ items: s7, grid: l5, obstacles: a9, traceWidth: o10, clearance: i8, availableBoundaryRegions: r9 });\n return h5 || null;\n}\nfunction Fae(e54) {\n return e54 === \"left\" || e54 === \"right\";\n}\nfunction jae(e54) {\n return e54 === \"right\" || e54 === \"up\" ? 1 : -1;\n}\nfunction $ae(e54, t4) {\n return Fae(t4) ? e54.x : e54.y;\n}\nfunction Yae(e54, t4) {\n return Fae(t4) ? e54.y : e54.x;\n}\nfunction Xae(e54, t4, n8) {\n return Fae(n8) ? { x: e54, y: t4 } : { x: t4, y: e54 };\n}\nfunction Hae(e54) {\n switch (e54.direction) {\n case \"right\":\n return e54.sharedBoundary.maxX;\n case \"left\":\n return e54.sharedBoundary.minX;\n case \"up\":\n return e54.sharedBoundary.maxY;\n case \"down\":\n return e54.sharedBoundary.minY;\n }\n}\nfunction Vae(e54) {\n if (e54.length \u003c 3)\n return e54;\n const t4 = [e54[0]];\n for (let n8 = 1;n8 \u003c e54.length - 1; n8++) {\n const o10 = t4.at(-1), i8 = e54[n8], r9 = e54[n8 + 1], s7 = { x: Math.sign(i8.x - o10.x), y: Math.sign(i8.y - o10.y) }, a9 = { x: Math.sign(r9.x - i8.x), y: Math.sign(r9.y - i8.y) };\n s7.x === a9.x \u0026\u0026 s7.y === a9.y || t4.push(i8);\n }\n return t4.push(e54.at(-1)), t4;\n}\nfunction Wae(e54, t4) {\n const n8 = [];\n for (let o10 = 1;o10 \u003c e54.length; o10++)\n Bre(e54[o10 - 1], e54[o10]) \u003c 0.000000001 || n8.push({ start: e54[o10 - 1], end: e54[o10], width: t4, layer: \"top\" });\n return n8;\n}\nfunction Gae(e54) {\n const { item: t4, srj: n8, acceptedSegments: o10, traceWidth: i8, clearance: r9 } = e54, s7 = t4.cornerChannelPrefixes;\n if (!s7)\n return null;\n const a9 = t4.direction, c5 = jae(a9), l5 = Hae(t4.bus), h5 = i8 + r9, d9 = i8 / 2 + r9, u9 = Fae(a9) ? t4.bus.sharedBoundary.minY : t4.bus.sharedBoundary.minX, p9 = Fae(a9) ? t4.bus.sharedBoundary.maxY : t4.bus.sharedBoundary.maxX, m9 = u9 + i8 / 2, g10 = p9 - i8 / 2, f10 = Yae(t4.connection.exitTargetPoint ?? t4.connection.targetPoint, a9), _5 = h5 / 2, y10 = new Set([Math.max(m9, Math.min(g10, f10))]);\n for (let e60 = Math.ceil(m9 / _5) * _5;e60 \u003c= g10 + 0.000000001; e60 += _5)\n y10.add(Number(e60.toFixed(9)));\n const b10 = [...y10].toSorted((e60, t10) =\u003e Math.abs(e60 - f10) - Math.abs(t10 - f10));\n for (const e60 of s7) {\n const s9 = e60.at(-1), u10 = Yae(s9, a9);\n for (const p10 of b10) {\n const m10 = Math.abs(p10 - u10), g11 = Xae($ae(s9, a9) + c5 * h5, u10, a9), f11 = Xae($ae(g11, a9) + c5 * m10, p10, a9);\n if (c5 * (l5 - $ae(f11, a9)) \u003c -0.000000001)\n continue;\n const _10 = Xae(l5, p10, a9), y11 = [...e60, g11, ...m10 \u003e 0.000000001 ? [f11] : []];\n Bre(y11.at(-1), _10) \u003e 0.000000001 \u0026\u0026 y11.push(_10);\n const b11 = Vae(y11), x8 = Wae(b11, i8);\n if (!x8.every((e61) =\u003e n8.obstacles.every((n10) =\u003e n10 === t4.connection.sourceObstacle || !n10.layers.includes(\"top\") || Hre(e61, n10) \u003e= d9 - 0.000000001)))\n continue;\n if (x8.every((e61) =\u003e o10.every((t10) =\u003e $re(e61.start, e61.end, t10.start, t10.end) \u003e= i8 + r9 - 0.000000001)))\n return { item: t4, points: b11, track: p10 };\n }\n }\n return null;\n}\nfunction Uae(e54) {\n const { route: t4, direction: n8, exitAxis: o10, signedShift: i8, maximumShift: r9, obstacles: s7, requiredObstacleDistance: a9 } = e54;\n if (r9 \u003c= 0.000000001 || Math.abs(i8) \u003c= 0.000000001)\n return 0;\n const c5 = Math.sign(i8), l5 = (e60) =\u003e {\n if (e60 \u003c= 0.000000001)\n return true;\n const i9 = { start: Xae(o10 - jae(n8) * e60, t4.track, n8), end: Xae(o10, t4.track + c5 * e60, n8), width: 0, layer: \"top\" };\n return s7.every((e61) =\u003e e61 === t4.item.connection.sourceObstacle || !e61.layers.includes(\"top\") || Hre(i9, e61) \u003e= a9 - 0.000000001);\n };\n if (l5(r9))\n return r9;\n let h5 = 0, d9 = r9;\n for (let e60 = 0;e60 \u003c 32; e60++) {\n const e61 = (h5 + d9) / 2;\n l5(e61) ? h5 = e61 : d9 = e61;\n }\n return h5;\n}\nfunction Zae(e54) {\n const { requestedTracks: t4, currentTracks: n8, candidateTracks: o10, maximumShifts: i8 } = e54, r9 = t4.length + 1, s7 = o10.length + 1, a9 = Array.from({ length: r9 }, () =\u003e new Float64Array(s7).fill(Number.POSITIVE_INFINITY)), c5 = Array.from({ length: r9 }, () =\u003e new Uint8Array(s7));\n a9[0].fill(0);\n for (let e60 = 1;e60 \u003c r9; e60++)\n for (let r10 = 1;r10 \u003c s7; r10++) {\n const s9 = a9[e60][r10 - 1], l10 = Math.abs(t4[e60 - 1] - o10[r10 - 1]), h9 = Math.abs(n8[e60 - 1] - o10[r10 - 1]) \u003e i8[e60 - 1] + 0.000000001 ? Number.POSITIVE_INFINITY : a9[e60 - 1][r10 - 1] + l10;\n h9 \u003c s9 ? (a9[e60][r10] = h9, c5[e60][r10] = 1) : a9[e60][r10] = s9;\n }\n if (!Number.isFinite(a9.at(-1).at(-1)))\n return null;\n const l5 = [];\n let h5 = t4.length, d9 = o10.length;\n for (;h5 \u003e 0 \u0026\u0026 d9 \u003e 0; )\n c5[h5][d9] \u0026\u0026 (l5.push(o10[d9 - 1]), h5--), d9--;\n return h5 \u003e 0 ? null : l5.reverse();\n}\nfunction qae(e54) {\n const { direction: t4, activeRoutes: n8, obstacles: o10, boundaryMinimum: i8, boundaryMaximum: r9, traceWidth: s7, clearance: a9, requestedTracks: c5, maximumShifts: l5 } = e54, h5 = s7 + a9, d9 = s7 / 2 + a9;\n let u9 = null, p9 = Number.POSITIVE_INFINITY;\n for (const e60 of Array.from({ length: Math.round(h5 / s7) }, (e61, t10) =\u003e t10 * s7)) {\n const a10 = [];\n for (let n10 = Math.ceil((i8 - e60) / h5) * h5 + e60;n10 \u003c= r9 + 0.000000001; n10 += h5) {\n const e61 = Math.round(n10 / s7) * s7;\n o10.every((n11) =\u003e {\n const o11 = Yae(n11.center, t4), i9 = Fae(t4) ? n11.height : n11.width;\n return Math.abs(e61 - o11) \u003e= i9 / 2 + d9 - 0.000000001;\n }) \u0026\u0026 a10.push(e61);\n }\n const m9 = Zae({ requestedTracks: c5, currentTracks: n8.map((e61) =\u003e e61.track), candidateTracks: a10, maximumShifts: l5 });\n if (!m9)\n continue;\n const g10 = m9.reduce((e61, t10, n10) =\u003e e61 + Math.abs(t10 - c5[n10]), 0);\n g10 \u003c p9 \u0026\u0026 (p9 = g10, u9 = m9);\n }\n return u9;\n}\nfunction Jae(e54, t4) {\n switch (t4) {\n case \"up\":\n return e54 === \"top-left\" ? \"minimum\" : e54 === \"top-right\" ? \"maximum\" : null;\n case \"down\":\n return e54 === \"bottom-left\" ? \"minimum\" : e54 === \"bottom-right\" ? \"maximum\" : null;\n case \"left\":\n return e54 === \"bottom-left\" ? \"minimum\" : e54 === \"top-left\" ? \"maximum\" : null;\n case \"right\":\n return e54 === \"bottom-right\" ? \"minimum\" : e54 === \"top-right\" ? \"maximum\" : null;\n }\n}\nfunction Qae(e54) {\n const { items: t4, direction: n8, boundaryMinimum: o10, boundaryMaximum: i8, traceWidth: r9, clearance: s7, borderDistribution: a9, currentTrackByConnectionName: c5 } = e54, l5 = (e60) =\u003e c5.get(e60.connection.connection.name) ?? Yae(e60.source, n8), h5 = [...t4].toSorted((e60, t10) =\u003e l5(e60) - l5(t10) || e60.connection.connection.name.localeCompare(t10.connection.connection.name)), d9 = r9 + s7, u9 = o10 + r9 / 2, p9 = i8 - r9 / 2;\n if (p9 - u9 \u003c d9 * Math.max(h5.length - 1, 0) - 0.000000001)\n return null;\n const m9 = h5.map(l5);\n let g10 = [...m9], f10 = d9;\n const _5 = new Set;\n if (a9 === \"even\" \u0026\u0026 h5.length \u003e 1) {\n const e60 = m9[0], t10 = m9.at(-1), n10 = Math.max(d9, (t10 - e60) / (h5.length - 1)), o11 = (e61) =\u003e {\n const t11 = [...m9], n11 = Math.floor(h5.length / 2), o12 = h5.length % 2 == 0 ? n11 - 1 : n11;\n if (o12 !== n11) {\n const i10 = t11[n11] - t11[o12];\n if (i10 \u003c e61) {\n const r10 = (e61 - i10) / 2;\n t11[o12] = t11[o12] - r10, t11[n11] = t11[n11] + r10;\n }\n }\n for (let n12 = o12 - 1;n12 \u003e= 0; n12--)\n t11[n12] = Math.min(t11[n12], t11[n12 + 1] - e61);\n for (let o13 = n11 + 1;o13 \u003c t11.length; o13++)\n t11[o13] = Math.max(t11[o13], t11[o13 - 1] + e61);\n return t11;\n }, i9 = (e61) =\u003e e61[0] \u003e= u9 - 0.000000001 \u0026\u0026 e61.at(-1) \u003c= p9 + 0.000000001;\n if (g10 = o11(n10), i9(g10))\n f10 = n10;\n else {\n let e61 = d9, t11 = n10;\n if (g10 = o11(e61), !i9(g10))\n return null;\n for (let n11 = 0;n11 \u003c 32; n11++) {\n const n12 = (e61 + t11) / 2, r10 = o11(n12);\n i9(r10) ? (e61 = n12, g10 = r10) : t11 = n12;\n }\n f10 = e61;\n }\n for (const e61 of h5)\n _5.add(e61.connection.connection.name);\n }\n const y10 = [], b10 = [];\n for (let e60 = 0;e60 \u003c h5.length; e60++) {\n const t10 = h5[e60], o11 = t10.bus.preferredExit;\n if (!o11?.includes(\"-\"))\n continue;\n const i9 = Jae(o11, n8);\n if (!i9)\n return null;\n _5.add(t10.connection.connection.name), i9 === \"minimum\" ? y10.push(e60) : b10.push(e60);\n }\n if (y10.some((e60, t10) =\u003e e60 !== t10) || b10.some((e60, t10) =\u003e e60 !== h5.length - b10.length + t10))\n return null;\n const x8 = 2 * d9;\n if (y10.length \u003e 0) {\n g10[0] = u9 + x8;\n for (let e60 = 1;e60 \u003c y10.length; e60++) {\n const t10 = Math.max(f10, m9[e60] - m9[e60 - 1]);\n g10[e60] = g10[e60 - 1] + t10;\n }\n }\n if (b10.length \u003e 0) {\n const e60 = h5.length - 1;\n g10[e60] = p9 - x8;\n for (let t10 = e60 - 1;t10 \u003e= h5.length - b10.length; t10--) {\n const e61 = Math.max(f10, m9[t10 + 1] - m9[t10]);\n g10[t10] = g10[t10 + 1] - e61;\n }\n }\n return { byConnectionName: new Map(h5.map((e60, t10) =\u003e [e60.connection.connection.name, g10[t10]])), enforcedConnectionNames: _5 };\n}\nfunction Kae(e54) {\n const { item: t4, points: n8, segments: o10 } = e54, i8 = n8.map((e60, n10) =\u003e ({ route_type: \"wire\", x: e60.x, y: e60.y, width: o10[0]?.width ?? 0.1, layer: \"top\", ...n10 === 0 \u0026\u0026 t4.connection.sourcePoint.pcb_port_id ? { start_pcb_port_id: t4.connection.sourcePoint.pcb_port_id } : {} })), r9 = Are({ connectionName: t4.connection.connection.name, sourcePointIndex: t4.connection.sourcePointIndex });\n return { busId: t4.bus.busId, connectionName: t4.connection.connection.name, connectionIndex: t4.connection.connectionIndex, sourcePointIndex: t4.connection.sourcePointIndex, sourcePoint: t4.connection.sourcePoint, sourceObstacle: t4.connection.sourceObstacle, sourceLayer: t4.connection.sourceLayer, targetPoint: t4.connection.targetPoint, targetLayer: \"top\", termination: t4.bus.termination, direction: t4.direction, exitPoint: n8.at(-1), trace: { type: \"pcb_trace\", pcb_trace_id: r9.traceId, connection_name: t4.connection.connection.name, connectsTo: [...t4.connection.sourcePoint.pointId ? [t4.connection.sourcePoint.pointId] : [], ...t4.connection.sourcePoint.pcb_port_id ? [t4.connection.sourcePoint.pcb_port_id] : [], r9.boundaryExitPointId], route: i8 }, segments: o10, length: o10.reduce((e60, t10) =\u003e e60 + Bre(t10.start, t10.end), 0) };\n}\nfunction ece(e54) {\n const { srj: t4, buses: n8, traceWidth: o10, clearance: i8, borderDistribution: r9 } = e54, s7 = o10 / 2 + i8, a9 = new Map, c5 = new Map, l5 = n8.flatMap((e60) =\u003e e60.connections.map((n10) =\u003e {\n const r10 = { x: n10.sourcePoint.x, y: n10.sourcePoint.y }, s9 = function(e61) {\n const { srj: t10, bus: n11, connection: o11, traceWidth: i9, clearance: r11 } = e61, s10 = n11.direction, a10 = jae(s10), c9 = { x: o11.sourcePoint.x, y: o11.sourcePoint.y }, l10 = $ae(c9, s10), h9 = Yae(c9, s10), d10 = i9 / 2 + r11, u10 = (() =\u003e {\n switch (s10) {\n case \"right\":\n return n11.componentBounds.maxX + d10;\n case \"left\":\n return n11.componentBounds.minX - d10;\n case \"up\":\n return n11.componentBounds.maxY + d10;\n case \"down\":\n return n11.componentBounds.minY - d10;\n }\n })(), p9 = (e63) =\u003e Math.min(...t10.obstacles.filter((e64) =\u003e e64 !== o11.sourceObstacle \u0026\u0026 e64.layers.includes(\"top\")).map((t11) =\u003e Hre(e63, t11))), m9 = { start: c9, end: Xae(u10, h9, s10), width: i9, layer: \"top\" };\n if (p9(m9) \u003e= d10 - 0.000000001)\n return null;\n const g10 = Fae(s10) ? { minimum: n11.componentBounds.minY, maximum: n11.componentBounds.maxY } : { minimum: n11.componentBounds.minX, maximum: n11.componentBounds.maxX }, f10 = a10 * (u10 - l10), _5 = Yae(o11.exitTargetPoint ?? o11.targetPoint, s10), y10 = i9 + r11, b10 = Hae(n11), x8 = [-1, 1].map((e63) =\u003e {\n const t11 = e63 * ((e63 \u003c 0 ? g10.minimum - d10 : g10.maximum + d10) - h9), o12 = Math.max(f10, t11), r12 = Xae(l10 + a10 * o12, h9 + e63 * o12, s10);\n if (a10 * (b10 - $ae(r12, s10)) \u003c y10 - 0.000000001)\n return null;\n const u11 = [c9, r12];\n if (!u11.every((e64) =\u003e e64.x \u003e= n11.sharedBoundary.minX - 0.000000001 \u0026\u0026 e64.x \u003c= n11.sharedBoundary.maxX + 0.000000001 \u0026\u0026 e64.y \u003e= n11.sharedBoundary.minY - 0.000000001 \u0026\u0026 e64.y \u003c= n11.sharedBoundary.maxY + 0.000000001))\n return null;\n const m10 = Math.min(...Wae(u11, i9).map(p9));\n return m10 \u003c d10 - 0.000000001 ? null : { points: u11, obstacleDistance: m10, targetDistance: Math.abs(Yae(r12, s10) - _5) };\n }).filter((e63) =\u003e e63 !== null).toSorted((e63, t11) =\u003e t11.obstacleDistance - e63.obstacleDistance || e63.targetDistance - t11.targetDistance);\n return x8.length \u003e 0 ? x8.map((e63) =\u003e e63.points) : null;\n }({ srj: t4, bus: e60, connection: n10, traceWidth: o10, clearance: i8 });\n return { bus: e60, connection: n10, direction: e60.direction, source: r10, ...s9 ? { cornerChannelPrefixes: s9 } : {} };\n }));\n for (const e60 of [\"left\", \"right\", \"up\", \"down\"]) {\n const n10 = jae(e60), h9 = l5.filter((t10) =\u003e t10.direction === e60 \u0026\u0026 !t10.cornerChannelPrefixes);\n if (h9.length === 0)\n continue;\n const d10 = Fae(e60) ? h9[0].bus.sharedBoundary.minY : h9[0].bus.sharedBoundary.minX, u10 = Fae(e60) ? h9[0].bus.sharedBoundary.maxY : h9[0].bus.sharedBoundary.maxX, p9 = Hae(h9[0].bus), m9 = new Map, g10 = new Map, f10 = new Map;\n for (const t10 of h9) {\n const n11 = $ae(t10.source, e60), o11 = n11.toFixed(6);\n f10.set(o11, n11);\n const i9 = m9.get(o11) ?? [];\n i9.push(t10), m9.set(o11, i9);\n }\n for (const [n11, o11] of m9) {\n const i9 = f10.get(n11), r10 = new Set(o11.map((e61) =\u003e e61.bus.componentId));\n g10.set(n11, t4.obstacles.filter((t10) =\u003e t10.layers.includes(\"top\") \u0026\u0026 !!t10.componentId \u0026\u0026 r10.has(t10.componentId) \u0026\u0026 Math.abs($ae(t10.center, e60) - i9) \u003c 0.000001));\n }\n const _5 = [...f10.values()].toSorted((e61, t10) =\u003e n10 * (e61 - t10)), y10 = new Map;\n for (let t10 = 0;t10 \u003c _5.length; t10++) {\n const r10 = _5[t10], a10 = r10.toFixed(6);\n for (const t11 of m9.get(a10) ?? []) {\n const o11 = Fae(e60) ? t11.connection.sourceObstacle.width : t11.connection.sourceObstacle.height, i9 = Math.max(t11.connection.sourceObstacle.width, t11.connection.sourceObstacle.height) \u003c 1.5 ? o11 / 2 + s7 : 0, a11 = Xae(r10 + n10 * i9, Yae(t11.source, e60), e60);\n y10.set(t11.connection.connection.name, { item: t11, points: Bre(t11.source, a11) \u003e 0.000000001 ? [t11.source, a11] : [t11.source], track: Yae(t11.source, e60) });\n }\n const c9 = _5[t10 + 1] ?? p9;\n if (y10.size === 0 || n10 * (c9 - r10) \u003c= 0.000000001)\n continue;\n const l10 = [...y10.values()].toSorted((e61, t11) =\u003e e61.track - t11.track || e61.item.connection.connection.name.localeCompare(t11.item.connection.connection.name)), h10 = _5.slice(t10 + 1, t10 + 3).flatMap((e61) =\u003e g10.get(e61.toFixed(6)) ?? []), f11 = l10.map((t11) =\u003e Math.abs(c9 - $ae(t11.points.at(-1), e60))), b11 = qae({ direction: e60, activeRoutes: l10, obstacles: h10, boundaryMinimum: d10, boundaryMaximum: u10, traceWidth: o10, clearance: i8, requestedTracks: l10.map((e61) =\u003e e61.track), maximumShifts: f11 });\n if (!b11)\n return null;\n for (let t11 = 0;t11 \u003c l10.length; t11++) {\n const o11 = l10[t11], i9 = b11[t11], r11 = Math.abs(i9 - o11.track), s9 = Xae($ae(o11.points.at(-1), e60) + n10 * r11, i9, e60);\n Bre(o11.points.at(-1), s9) \u003e 0.000000001 \u0026\u0026 o11.points.push(s9);\n const a11 = Xae(c9, i9, e60);\n Bre(o11.points.at(-1), a11) \u003e 0.000000001 \u0026\u0026 o11.points.push(a11), o11.track = i9;\n }\n }\n const b10 = Qae({ items: h9, direction: e60, boundaryMinimum: d10, boundaryMaximum: u10, traceWidth: o10, clearance: i8, borderDistribution: r9, currentTrackByConnectionName: new Map([...y10.values()].map((e61) =\u003e [e61.item.connection.connection.name, e61.track])) });\n if (!b10)\n return null;\n const x8 = [...y10.values()].toSorted((e61, t10) =\u003e e61.track - t10.track || e61.item.connection.connection.name.localeCompare(t10.item.connection.connection.name)), v10 = new Map, I6 = o10 + i8;\n let S6 = I6;\n for (const e61 of x8) {\n const t10 = e61.item.connection.connection.name;\n if (!b10.enforcedConnectionNames.has(t10))\n continue;\n b10.byConnectionName.get(t10) - e61.track \u003e= -0.000000001 || (v10.set(t10, S6), S6 += 2 * I6);\n }\n let C = I6;\n for (let e61 = x8.length - 1;e61 \u003e= 0; e61--) {\n const t10 = x8[e61], n11 = t10.item.connection.connection.name;\n if (!b10.enforcedConnectionNames.has(n11))\n continue;\n b10.byConnectionName.get(n11) - t10.track \u003c= 0.000000001 || (v10.set(n11, C), C += 2 * I6);\n }\n for (const o11 of x8) {\n const i9 = o11.item.connection.connection.name, r10 = b10.byConnectionName.get(i9) ?? o11.track, a10 = v10.get(i9) ?? 0, c9 = o11.points.at(-2), l10 = c9 ? n10 * (p9 - $ae(c9, e60)) : 0, h10 = r10 - o11.track, d11 = Math.min(Math.abs(h10), Math.max(0, l10 - a10)), u11 = Uae({ route: o11, direction: e60, exitAxis: p9, signedShift: h10, maximumShift: d11, obstacles: t4.obstacles, requiredObstacleDistance: s7 }), m10 = Math.sign(h10) * u11;\n b10.byConnectionName.set(i9, o11.track + m10);\n }\n for (const e61 of b10.enforcedConnectionNames)\n c5.set(e61, b10.byConnectionName.get(e61));\n for (const t10 of x8) {\n const o11 = t10.item.connection.connection.name, i9 = b10.byConnectionName.get(o11) ?? t10.track, r10 = Math.abs(i9 - t10.track), s9 = v10.get(o11) ?? 0, a10 = p9 - n10 * (r10 \u003e 0.000000001 ? s9 + r10 : 0), c9 = t10.points.at(-1);\n if (Math.abs($ae(c9, e60) - p9) \u003e 0.000001)\n return null;\n const l10 = t10.points.at(-2);\n if (l10 \u0026\u0026 (Math.abs(Yae(l10, e60) - t10.track) \u003e 0.000001 || n10 * (a10 - $ae(l10, e60)) \u003c -0.000001))\n return null;\n const h10 = Xae(a10, t10.track, e60);\n l10 \u0026\u0026 Bre(l10, h10) \u003c 0.000000001 ? t10.points.pop() : t10.points[t10.points.length - 1] = h10;\n }\n for (const t10 of x8) {\n const o11 = t10.item.connection.connection.name, i9 = b10.byConnectionName.get(o11) ?? t10.track, r10 = Math.abs(i9 - t10.track), s9 = v10.get(o11) ?? 0;\n r10 \u003e 0.000000001 \u0026\u0026 s9 \u003e 0.000000001 \u0026\u0026 t10.points.push(Xae($ae(t10.points.at(-1), e60) + n10 * s9, t10.track, e60)), r10 \u003e 0.000000001 \u0026\u0026 (t10.points.push(Xae($ae(t10.points.at(-1), e60) + n10 * r10, i9, e60)), t10.track = i9);\n const c9 = Xae(p9, t10.track, e60);\n if (Bre(t10.points.at(-1), c9) \u003e 0.000000001) {\n if (n10 * (p9 - $ae(t10.points.at(-1), e60)) \u003c -0.000001)\n return null;\n t10.points.push(c9);\n }\n a9.set(o11, t10);\n }\n }\n const h5 = [...a9.values()].flatMap((e60) =\u003e Wae(Vae(e60.points), o10));\n for (const e60 of l5) {\n if (!e60.cornerChannelPrefixes)\n continue;\n const n10 = Gae({ item: e60, srj: t4, acceptedSegments: h5, traceWidth: o10, clearance: i8 });\n if (!n10)\n return null;\n a9.set(e60.connection.connection.name, n10), h5.push(...Wae(Vae(n10.points), o10));\n }\n if (a9.size !== l5.length)\n return null;\n const d9 = (o10 + i8) / 2 + 0.000001;\n for (const [e60, t10] of c5) {\n const n10 = a9.get(e60);\n if (!n10 || Math.abs(n10.track - t10) \u003e d9)\n return null;\n }\n const u9 = l5.map((e60) =\u003e {\n const t10 = Vae(a9.get(e60.connection.connection.name).points);\n return { item: e60, points: t10, segments: Wae(t10, o10) };\n });\n return function(e60) {\n const { paths: t10, obstacles: n10, traceWidth: o11, clearance: i9 } = e60, r10 = o11 / 2 + i9, s9 = o11 + i9;\n for (const e61 of t10) {\n if (Math.abs($ae(e61.points.at(-1), e61.item.direction) - Hae(e61.item.bus)) \u003e 0.000001)\n return false;\n for (const t11 of e61.segments)\n for (const o12 of n10)\n if (o12 !== e61.item.connection.sourceObstacle \u0026\u0026 o12.layers.includes(\"top\") \u0026\u0026 Hre(t11, o12) \u003c r10 - 0.000000001)\n return false;\n }\n for (let e61 = 0;e61 \u003c t10.length; e61++)\n for (let n11 = e61 + 1;n11 \u003c t10.length; n11++)\n for (const o12 of t10[e61].segments)\n for (const e63 of t10[n11].segments)\n if ($re(o12.start, o12.end, e63.start, e63.end) \u003c s9 - 0.000000001)\n return false;\n return true;\n }({ paths: u9, obstacles: t4.obstacles, traceWidth: o10, clearance: i8 }) ? u9.map(Kae) : null;\n}\nvar tce = 0.000001;\nfunction nce(e54, t4) {\n return Bre(e54, t4) \u003c= tce;\n}\nfunction oce(e54) {\n return \"layer\" in e54 ? [e54.layer] : e54.layers;\n}\nfunction ice(e54) {\n return [...e54.segments, ...e54.planeEndpointSegments ?? []];\n}\nfunction rce(e54) {\n return [e54.via, e54.planeEndpointVia].filter((e60) =\u003e Boolean(e60));\n}\nfunction sce(e54, t4) {\n return nce(e54, t4) \u0026\u0026 oce(e54).join(\"\\x00\") === oce(t4).join(\"\\x00\") \u0026\u0026 e54.pointId === t4.pointId \u0026\u0026 e54.pcb_port_id === t4.pcb_port_id;\n}\nfunction ace(e54, t4) {\n const n8 = e54.x \u003e= t4.minX - tce \u0026\u0026 e54.x \u003c= t4.maxX + tce \u0026\u0026 e54.y \u003e= t4.minY - tce \u0026\u0026 e54.y \u003c= t4.maxY + tce, o10 = Math.abs(e54.x - t4.minX) \u003c= tce || Math.abs(e54.x - t4.maxX) \u003c= tce || Math.abs(e54.y - t4.minY) \u003c= tce || Math.abs(e54.y - t4.maxY) \u003c= tce;\n return n8 \u0026\u0026 o10;\n}\nfunction cce(e54, t4) {\n return e54.x \u003e= t4.minX - tce \u0026\u0026 e54.x \u003c= t4.maxX + tce \u0026\u0026 e54.y \u003e= t4.minY - tce \u0026\u0026 e54.y \u003c= t4.maxY + tce;\n}\nfunction lce(e54, t4, n8, o10, i8) {\n e54.push({ code: t4, message: n8, ...o10 ? { connectionName: o10.connectionName, busId: o10.busId } : {}, ...i8 ? { otherConnectionName: i8 } : {} });\n}\nfunction hce(e54) {\n const { trace: t4, plan: n8, issues: o10 } = e54, i8 = [];\n let r9, s7;\n for (const e60 of t4.route)\n e60.route_type !== \"via\" ? e60.route_type === \"wire\" ? s7 ? (nce(e60, s7) \u0026\u0026 e60.layer === s7.to_layer || lce(o10, \"disconnected-trace\", `Trace ${t4.pcb_trace_id} does not continue from its via on ${s7.to_layer}`, n8), r9 = e60, s7 = undefined) : (r9 \u0026\u0026 (r9.layer !== e60.layer ? lce(o10, \"disconnected-trace\", `Trace ${t4.pcb_trace_id} changes from ${r9.layer} to ${e60.layer} without a via`, n8) : nce(r9, e60) || i8.push({ start: { x: r9.x, y: r9.y }, end: { x: e60.x, y: e60.y }, width: e60.width, layer: e60.layer })), r9 = e60) : lce(o10, \"unsupported-route-point\", `Trace ${t4.pcb_trace_id} contains unsupported ${e60.route_type} geometry`, n8) : (r9 \u0026\u0026 nce(r9, e60) \u0026\u0026 r9.layer === e60.from_layer || lce(o10, \"disconnected-trace\", `Trace ${t4.pcb_trace_id} reaches a via without a matching ${e60.from_layer} wire endpoint`, n8), s7 = e60);\n return s7 \u0026\u0026 lce(o10, \"disconnected-trace\", `Trace ${t4.pcb_trace_id} ends at a via without a wire on ${s7.to_layer}`, n8), i8;\n}\nfunction dce(e54) {\n const { plan: t4, preparedBus: n8, inputSrj: o10, outputSrj: i8, sharedBoundary: r9, issues: s7 } = e54, a9 = o10.connections[t4.connectionIndex];\n if (!a9 || a9.name !== t4.connectionName)\n return void lce(s7, \"connection-mismatch\", `Plan index ${t4.connectionIndex} does not identify connection ${t4.connectionName}`, t4);\n const c5 = n8?.connections.find((e60) =\u003e e60.connectionIndex === t4.connectionIndex);\n if (c5 \u0026\u0026 c5.sourcePointIndex === t4.sourcePointIndex \u0026\u0026 sce(c5.sourcePoint, t4.sourcePoint) \u0026\u0026 c5.sourceObstacle.obstacleId === t4.sourceObstacle.obstacleId || lce(s7, \"source-mismatch\", `Plan ${t4.connectionName} does not start at its prepared component endpoint`, t4), n8?.termination.type !== t4.termination.type \u0026\u0026 lce(s7, \"termination-mismatch\", `Plan ${t4.connectionName} does not use its bus termination`, t4), t4.segments.length === 0 || t4.length \u003c= tce)\n lce(s7, \"not-broken-out\", `Plan ${t4.connectionName} has no non-zero escape geometry`, t4);\n else {\n const e60 = { minX: Math.min(o10.bounds.minX, r9.minX), maxX: Math.max(o10.bounds.maxX, r9.maxX), minY: Math.min(o10.bounds.minY, r9.minY), maxY: Math.max(o10.bounds.maxY, r9.maxY) };\n t4.segments.some((t10) =\u003e !cce(t10.start, e60) || !cce(t10.end, e60)) \u0026\u0026 lce(s7, \"outside-routing-bounds\", `Plan ${t4.connectionName} leaves the routable SRJ/shared-boundary area`, t4), nce(t4.segments[0].start, t4.sourcePoint) || lce(s7, \"disconnected-trace\", `Plan ${t4.connectionName} does not start at its source pad`, t4), nce(t4.segments.at(-1).end, t4.exitPoint) || lce(s7, \"disconnected-trace\", `Plan ${t4.connectionName} does not end at its declared exit`, t4);\n for (let e61 = 1;e61 \u003c t4.segments.length; e61++) {\n const n10 = t4.segments[e61 - 1], o11 = t4.segments[e61];\n nce(n10.end, o11.start) || lce(s7, \"disconnected-trace\", `Plan ${t4.connectionName} has a gap between route segments`, t4), n10.layer === o11.layer || t4.via \u0026\u0026 nce(n10.end, t4.via.center) \u0026\u0026 t4.via.spanLayers.includes(n10.layer) \u0026\u0026 t4.via.spanLayers.includes(o11.layer) || lce(s7, \"disconnected-trace\", `Plan ${t4.connectionName} changes layers without a connecting via`, t4);\n }\n }\n const l5 = hce({ trace: t4.trace, plan: t4, issues: s7 });\n if ((l5.length !== t4.segments.length || l5.some((e60, n10) =\u003e {\n const o11 = t4.segments[n10];\n return !o11 || e60.layer !== o11.layer || Math.abs(e60.width - o11.width) \u003e tce || !nce(e60.start, o11.start) || !nce(e60.end, o11.end);\n })) \u0026\u0026 lce(s7, \"trace-plan-mismatch\", `Trace ${t4.trace.pcb_trace_id} does not encode its declared route segments`, t4), t4.planeEndpointTrace || t4.planeEndpointSegments || t4.planeEndpointVia)\n if (t4.planeEndpointTrace \u0026\u0026 t4.planeEndpointSegments \u0026\u0026 t4.planeEndpointVia) {\n const e60 = hce({ trace: t4.planeEndpointTrace, plan: t4, issues: s7 });\n (e60.length !== t4.planeEndpointSegments.length || e60.some((e61, n10) =\u003e {\n const o11 = t4.planeEndpointSegments?.[n10];\n return !o11 || e61.layer !== o11.layer || Math.abs(e61.width - o11.width) \u003e tce || !nce(e61.start, o11.start) || !nce(e61.end, o11.end);\n }) || Bre(t4.planeEndpointVia.center, t4.targetPoint) \u003c= tce) \u0026\u0026 lce(s7, \"trace-plan-mismatch\", `Trace ${t4.planeEndpointTrace.pcb_trace_id} does not encode a valid offset plane-to-endpoint dogbone`, t4);\n } else\n lce(s7, \"trace-plan-mismatch\", `Plane endpoint geometry for ${t4.connectionName} is incomplete`, t4);\n const h5 = t4.trace.route.find((e60) =\u003e (\"x\" in e60) \u0026\u0026 (\"y\" in e60)), d9 = [...t4.trace.route].reverse().find((e60) =\u003e (\"x\" in e60) \u0026\u0026 (\"y\" in e60));\n h5 \u0026\u0026 d9 \u0026\u0026 nce(h5, t4.sourcePoint) \u0026\u0026 nce(d9, t4.exitPoint) || lce(s7, \"disconnected-trace\", `Trace ${t4.trace.pcb_trace_id} does not span its source and exit`, t4);\n const u9 = i8.connections.find((e60) =\u003e e60.name === t4.connectionName);\n if (t4.termination.type === \"boundary\")\n if (u9) {\n const e60 = u9.pointsToConnect[t4.sourcePointIndex];\n e60 \u0026\u0026 nce(e60, t4.exitPoint) \u0026\u0026 \"layer\" in e60 \u0026\u0026 e60.layer === t4.targetLayer || lce(s7, \"output-exit-mismatch\", `Output connection ${t4.connectionName} is not attached to its fanout exit`, t4);\n for (let e61 = 0;e61 \u003c a9.pointsToConnect.length; e61++) {\n if (e61 === t4.sourcePointIndex)\n continue;\n const n10 = a9.pointsToConnect[e61], o11 = u9.pointsToConnect[e61];\n n10 \u0026\u0026 o11 \u0026\u0026 sce(n10, o11) || lce(s7, \"downstream-endpoint-lost\", `Output connection ${t4.connectionName} did not retain downstream endpoint ${e61}`, t4);\n }\n } else\n lce(s7, \"output-connection-missing\", `Boundary connection ${t4.connectionName} was removed from the output`, t4);\n else\n u9 \u0026\u0026 lce(s7, \"plane-connection-retained\", `Plane-terminated connection ${t4.connectionName} remains in the output`, t4);\n}\nfunction uce(e54, t4) {\n const n8 = ice(e54), o10 = ice(t4), i8 = rce(e54), r9 = rce(t4);\n for (const e60 of n8) {\n for (const t10 of o10)\n if (e60.layer === t10.layer \u0026\u0026 $re(e60.start, e60.end, t10.start, t10.end) \u003c= (e60.width + t10.width) / 2 + tce)\n return true;\n for (const t10 of r9)\n if (t10.spanLayers.includes(e60.layer) \u0026\u0026 Fre(t10.center, e60.start, e60.end) \u003c= t10.diameter / 2 + e60.width / 2 + tce)\n return true;\n }\n for (const e60 of i8) {\n for (const t10 of o10)\n if (e60.spanLayers.includes(t10.layer) \u0026\u0026 Fre(e60.center, t10.start, t10.end) \u003c= e60.diameter / 2 + t10.width / 2 + tce)\n return true;\n for (const t10 of r9)\n if (e60.spanLayers.some((e61) =\u003e t10.spanLayers.includes(e61)) \u0026\u0026 Bre(e60.center, t10.center) \u003c= (e60.diameter + t10.diameter) / 2 + tce)\n return true;\n }\n return false;\n}\nfunction pce(e54) {\n const { inputSrj: t4, outputSrj: n8, plans: o10, preparedBuses: i8, sharedBoundary: r9, clearance: s7 } = e54, a9 = [], c5 = new Map, l5 = new Map(i8.map((e60) =\u003e [e60.busId, e60]));\n for (const e60 of o10) {\n const t10 = c5.get(e60.connectionName) ?? [];\n t10.push(e60), c5.set(e60.connectionName, t10);\n }\n for (const e60 of t4.connections) {\n const t10 = c5.get(e60.name) ?? [];\n t10.length === 0 ? lce(a9, \"missing-plan\", `Connection ${e60.name} has no fanout plan`) : t10.length \u003e 1 \u0026\u0026 lce(a9, \"duplicate-plan\", `Connection ${e60.name} has ${t10.length} fanout plans`, t10[0]);\n }\n for (const e60 of o10)\n t4.connections.some((t10) =\u003e t10.name === e60.connectionName) ? dce({ plan: e60, preparedBus: l5.get(e60.busId), inputSrj: t4, outputSrj: n8, sharedBoundary: r9, issues: a9 }) : lce(a9, \"unknown-plan\", `Plan ${e60.connectionName} is not an input connection`, e60);\n const h5 = function(e60) {\n const { plans: t10, inputSrj: n10, sharedBoundary: o11, issues: i9 } = e60, r10 = new Set, s9 = new Map;\n for (const e61 of t10)\n s9.set(e61, []);\n for (let e61 = 0;e61 \u003c t10.length; e61++) {\n const i10 = t10[e61];\n (i10.termination.type === \"plane\" ? Boolean(i10.via) : i10.segments.some((e63) =\u003e ace(e63.start, o11) || ace(e63.end, o11))) \u0026\u0026 r10.add(i10);\n for (let o12 = e61 + 1;o12 \u003c t10.length; o12++) {\n const e63 = t10[o12];\n Kre(n10, i10.connectionName, e63.connectionName) \u0026\u0026 uce(i10, e63) \u0026\u0026 (s9.get(i10).push(e63), s9.get(e63).push(i10));\n }\n }\n const a10 = [...r10];\n for (;a10.length \u003e 0; ) {\n const e61 = a10.shift();\n for (const t11 of s9.get(e61) ?? [])\n r10.has(t11) || (r10.add(t11), a10.push(t11));\n }\n for (const e61 of t10)\n r10.has(e61) || lce(i9, \"not-broken-out\", e61.termination.type === \"boundary\" ? `Connection ${e61.connectionName} has no continuous same-net copper path to the shared boundary` : `Plane connection ${e61.connectionName} has no terminating via`, e61);\n return r10;\n }({ plans: o10, inputSrj: t4, sharedBoundary: r9, issues: a9 });\n return function(e60) {\n const { plans: t10, inputSrj: n10, clearance: o11, issues: i9 } = e60;\n for (const e61 of t10) {\n const t11 = ice(e61);\n for (let r10 = 0;r10 \u003c t11.length; r10++) {\n const s9 = t11[r10];\n for (const t12 of n10.obstacles) {\n if (!t12.layers.includes(s9.layer))\n continue;\n if (ese(n10, t12, e61.connectionName))\n continue;\n if (r10 === 0 \u0026\u0026 t12.obstacleId === e61.sourceObstacle.obstacleId \u0026\u0026 s9.layer === e61.sourceLayer)\n continue;\n if (hse({ inputSrj: n10, segment: s9, bodyObstacle: t12, connectionName: e61.connectionName }))\n continue;\n const a10 = Hre(s9, t12), c9 = s9.width / 2 + o11;\n a10 \u003c c9 - 0.000000001 \u0026\u0026 lce(i9, \"obstacle-clearance\", `Trace ${e61.connectionName} on ${s9.layer} is ${a10.toFixed(4)}mm from different-net obstacle ${t12.obstacleId}; ${c9.toFixed(4)}mm is required`, e61);\n }\n }\n for (const t12 of rce(e61))\n for (const r10 of n10.obstacles) {\n if (!r10.layers.some((e63) =\u003e t12.spanLayers.includes(e63)) || ese(n10, r10, e61.connectionName))\n continue;\n const s9 = Xre(t12.center, r10), a10 = t12.diameter / 2 + o11;\n s9 \u003c a10 - 0.000000001 \u0026\u0026 lce(i9, \"via-obstacle-clearance\", `Via ${e61.connectionName} is ${s9.toFixed(4)}mm from different-net obstacle ${r10.obstacleId} on its layer span; ${a10.toFixed(4)}mm is required`, e61);\n }\n }\n for (let e61 = 0;e61 \u003c t10.length; e61++) {\n const r10 = t10[e61];\n for (let s9 = e61 + 1;s9 \u003c t10.length; s9++) {\n const e63 = t10[s9];\n if (Kre(n10, r10.connectionName, e63.connectionName))\n continue;\n const a10 = ice(r10), c9 = ice(e63), l10 = rce(r10), h9 = rce(e63);\n for (const t11 of a10) {\n for (const n11 of c9)\n Vre(t11, n11, o11) || lce(i9, \"different-net-trace-clearance\", `Different-net traces ${r10.connectionName} and ${e63.connectionName} intersect or violate clearance on ${t11.layer}`, r10, e63.connectionName);\n for (const n11 of h9)\n n11.spanLayers.includes(t11.layer) \u0026\u0026 Fre(n11.center, t11.start, t11.end) \u003c n11.diameter / 2 + t11.width / 2 + o11 - 0.000000001 \u0026\u0026 lce(i9, \"different-net-trace-via-clearance\", `Trace ${r10.connectionName} violates via clearance to ${e63.connectionName} on ${t11.layer}`, r10, e63.connectionName);\n }\n for (const t11 of l10) {\n for (const n11 of c9)\n t11.spanLayers.includes(n11.layer) \u0026\u0026 Fre(t11.center, n11.start, n11.end) \u003c t11.diameter / 2 + n11.width / 2 + o11 - 0.000000001 \u0026\u0026 lce(i9, \"different-net-trace-via-clearance\", `Via ${r10.connectionName} violates trace clearance to ${e63.connectionName} on ${n11.layer}`, r10, e63.connectionName);\n for (const n11 of h9)\n t11.spanLayers.some((e64) =\u003e n11.spanLayers.includes(e64)) \u0026\u0026 Bre(t11.center, n11.center) \u003c (t11.diameter + n11.diameter) / 2 + o11 - 0.000000001 \u0026\u0026 lce(i9, \"different-net-via-clearance\", `Vias ${r10.connectionName} and ${e63.connectionName} violate clearance on an overlapping layer span`, r10, e63.connectionName);\n }\n }\n }\n }({ plans: o10, inputSrj: t4, clearance: s7, issues: a9 }), { valid: a9.length === 0, checkedConnectionCount: t4.connections.length, brokenOutConnectionCount: new Set([...h5].map((e60) =\u003e e60.connectionName)).size, issues: a9 };\n}\nvar mce = [\"#ef4444\", \"#2563eb\", \"#16a34a\", \"#9333ea\", \"#f59e0b\", \"#0891b2\", \"#db2777\", \"#65a30d\", \"#4f46e5\", \"#ea580c\"];\nfunction gce(e54) {\n if (!Number.isInteger(e54) || e54 \u003c 0)\n throw new Error(`FanoutSolver: copper layer index must be a non-negative integer, received ${e54}`);\n return mce[e54 % mce.length];\n}\nvar fce = new Set([\"top\", \"bottom\", \"inner1\", \"inner2\", \"inner3\", \"inner4\", \"inner5\", \"inner6\", \"inner7\", \"inner8\"]);\nvar _ce = { \"0603\": { padLength: 0.8, padWidth: 0.95 }, 1206: { padLength: 0.6, padWidth: 1.6 }, \"1206x4_pair\": { padLength: 0.8, padWidth: 0.5 } };\nvar yce = (e54, t4) =\u003e {\n const n8 = e54.indexOf(t4);\n if (n8 \u003c 0)\n throw new Error(`FanoutSolver: cannot visualize unknown copper layer \"${t4}\"`);\n return n8;\n};\nvar bce = (e54, t4) =\u003e `z${[...new Set(t4.map((t10) =\u003e yce(e54, t10)))].sort((e60, t10) =\u003e e60 - t10).join(\",\")}`;\nvar xce = (e54) =\u003e {\n const t4 = \"layers\" in e54 ? e54.layers : undefined;\n return t4 \u0026\u0026 t4.length \u003e 0 ? t4 : [e54.layer];\n};\nvar vce = (e54, t4) =\u003e e54.__zLayers \u0026\u0026 e54.__zLayers.length \u003e 0 ? [...new Set(e54.__zLayers)].filter((e60) =\u003e Number.isInteger(e60) \u0026\u0026 e60 \u003e= 0 \u0026\u0026 e60 \u003c t4.length).sort((e60, t10) =\u003e e60 - t10) : [...new Set(e54.layers.map((e60) =\u003e yce(t4, e60)))].sort((e60, t10) =\u003e e60 - t10);\nvar Ice = (e54, t4, n8) =\u003e {\n const o10 = yce(e54, t4), i8 = yce(e54, n8);\n return e54.slice(Math.min(o10, i8), Math.max(o10, i8) + 1);\n};\nvar Sce = (...e54) =\u003e e54.find((e60) =\u003e typeof e60 == \"number\" \u0026\u0026 Number.isFinite(e60));\nvar Cce = (e54) =\u003e {\n const t4 = Sce(e54.min_via_hole_diameter, e54.minViaHoleDiameter), n8 = Sce(e54.min_via_pad_diameter, e54.minViaPadDiameter, e54.minViaDiameter);\n return Math.max(n8 ?? e54.minViaDiameter ?? 0.3, t4 ?? 0);\n};\nvar Pce = (e54, t4) =\u003e {\n let n8 = { blue: [0, 0, 255], orange: [255, 165, 0], purple: [128, 0, 128], red: [255, 0, 0] }[e54], o10 = 1;\n const i8 = /^rgba?\\(\\s*([\\d.]+)\\s*,\\s*([\\d.]+)\\s*,\\s*([\\d.]+)(?:\\s*,\\s*([\\d.]+))?\\s*\\)$/.exec(e54);\n i8 \u0026\u0026 (n8 = [Number(i8[1]), Number(i8[2]), Number(i8[3])], o10 = i8[4] === undefined ? 1 : Number(i8[4]));\n const r9 = /^hsl\\(\\s*([\\d.-]+)\\s*,\\s*([\\d.]+)%\\s*,\\s*([\\d.]+)%\\s*\\)$/.exec(e54);\n if (r9 \u0026\u0026 (n8 = ((e60, t10, n10) =\u003e {\n const o11 = (1 - Math.abs(2 * n10 - 1)) * t10, i9 = (e60 % 360 + 360) % 360 / 60, r10 = o11 * (1 - Math.abs(i9 % 2 - 1)), [s9, a9, c5] = i9 \u003c 1 ? [o11, r10, 0] : i9 \u003c 2 ? [r10, o11, 0] : i9 \u003c 3 ? [0, o11, r10] : i9 \u003c 4 ? [0, r10, o11] : i9 \u003c 5 ? [r10, 0, o11] : [o11, 0, r10], l5 = n10 - o11 / 2;\n return [s9, a9, c5].map((e61) =\u003e Math.round(255 * (e61 + l5)));\n })(Number(r9[1]), Number(r9[2]) / 100, Number(r9[3]) / 100)), !n8)\n return e54;\n const s7 = +Math.max(0, 100 * o10 - 100 * t4).toFixed(2) / 100;\n if (s7 \u003e= 1) {\n const e60 = n8.map((e61) =\u003e Math.round(e61).toString(16).padStart(2, \"0\")).join(\"\");\n return e60[0] === e60[1] \u0026\u0026 e60[2] === e60[3] \u0026\u0026 e60[4] === e60[5] ? `#${e60[0]}${e60[2]}${e60[4]}` : `#${e60}`;\n }\n return `rgba(${n8.join(\",\")},${s7})`;\n};\nvar Mce = (e54) =\u003e {\n const t4 = new Map, n8 = (e60, n10) =\u003e {\n if (!e60)\n return;\n const o10 = t4.get(e60) ?? [];\n o10.includes(n10) || o10.push(n10), t4.set(e60, o10);\n };\n for (const t10 of e54.connections) {\n const e60 = t10.__rootConnectionNames ?? [t10.name];\n for (const o10 of e60) {\n n8(t10.name, o10), n8(o10, o10), n8(t10.__netConnectionName, o10);\n for (const e61 of t10.pointsToConnect)\n n8(e61.pointId, o10), n8(e61.pcb_port_id, o10);\n }\n }\n return (e60) =\u003e {\n const n10 = ((e61) =\u003e {\n const t10 = new Set;\n return e61.filter((e63) =\u003e !t10.has(e63) \u0026\u0026 (t10.add(e63), true));\n })([...e60.connectedTo.flatMap((e61) =\u003e t4.get(e61) ?? []), ...(e60.offBoardConnectsTo ?? []).flatMap((e61) =\u003e t4.get(e61) ?? [])]).join(\", \");\n return e60.layers.map((e61) =\u003e n10 ? `${e61}\n${n10}` : e61).join(`\n`);\n };\n};\nfunction wce(e54) {\n const t4 = Wre(e54.layerCount), n8 = (e54.traces ?? []).some((e60) =\u003e e60.route.some((t10, n10) =\u003e {\n const o11 = e60.route[n10 + 1];\n return t10.route_type === \"wire\" \u0026\u0026 o11?.route_type === \"wire\" \u0026\u0026 o11.layer === t10.layer \u0026\u0026 !fce.has(t10.layer);\n })), o10 = new Set(e54.connections.map(({ name: e60 }) =\u003e e60)), i8 = n8 ? [...new Set((e54.traces ?? []).map(({ connection_name: e60 }) =\u003e e60).filter((e60) =\u003e e60 \u0026\u0026 !o10.has(e60)))].map((e60) =\u003e ({ name: e60, pointsToConnect: [] })) : [], r9 = [...e54.connections, ...i8], s7 = (a9 = r9, Object.fromEntries(a9.map((e60, t10) =\u003e [e60.name, `hsl(${340 * t10 / a9.length}, 100%, 50%)`])));\n var a9;\n const c5 = Mce({ ...e54, connections: r9 }), l5 = [], h5 = [], d9 = [], u9 = [];\n for (const e60 of r9)\n for (const n10 of e60.pointsToConnect) {\n const o11 = xce(n10), i9 = e60.__rootConnectionNames ?? [e60.name];\n u9.push({ x: n10.x, y: n10.y, color: s7[e60.name], layer: bce(t4, o11), label: [e60.name, i9.join(\", \"), o11.join(\",\")].join(`\n`) });\n }\n for (const o11 of e54.traces ?? []) {\n const i9 = o11.route.filter((e60) =\u003e e60.route_type === \"jumper\"), r10 = (e60, t10) =\u003e i9.some((n10) =\u003e {\n const o12 = 0.01;\n return Math.abs(e60.x - n10.start.x) \u003c o12 \u0026\u0026 Math.abs(e60.y - n10.start.y) \u003c o12 \u0026\u0026 Math.abs(t10.x - n10.end.x) \u003c o12 \u0026\u0026 Math.abs(t10.y - n10.end.y) \u003c o12 || Math.abs(e60.x - n10.end.x) \u003c o12 \u0026\u0026 Math.abs(e60.y - n10.end.y) \u003c o12 \u0026\u0026 Math.abs(t10.x - n10.start.x) \u003c o12 \u0026\u0026 Math.abs(t10.y - n10.start.y) \u003c o12;\n });\n for (const i10 of o11.route)\n if (i10.route_type === \"via\") {\n const r11 = Ice(t4, i10.from_layer, i10.to_layer);\n h5.push({ center: { x: i10.x, y: i10.y }, radius: (i10.via_diameter ?? Cce(e54)) / 2, fill: n8 ? s7[o11.connection_name] : \"blue\", stroke: \"none\", layer: bce(t4, r11) });\n } else\n i10.route_type === \"through_obstacle\" \u0026\u0026 l5.push({ points: [i10.start, i10.end], strokeColor: Pce(s7[o11.connection_name] ?? \"purple\", 0.35), strokeWidth: i10.width, strokeDash: [0.1, 0.1], layer: bce(t4, [i10.from_layer, i10.to_layer]), label: `${o11.connection_name} through_obstacle` });\n for (let e60 = 0;e60 \u003c o11.route.length - 1; e60++) {\n const i10 = o11.route[e60], a10 = o11.route[e60 + 1];\n if (i10.route_type === \"jumper\") {\n const e61 = s7[o11.connection_name] ?? \"rgba(255, 165, 0, 0.8)\", n10 = _ce[i10.footprint === \"1206x4_pair\" ? \"1206x4_pair\" : \"0603\"], r11 = Math.abs(i10.end.x - i10.start.x) \u003e Math.abs(i10.end.y - i10.start.y), a11 = r11 ? n10.padLength : n10.padWidth, c9 = r11 ? n10.padWidth : n10.padLength, h9 = bce(t4, [i10.layer]);\n for (const t10 of [i10.start, i10.end])\n d9.push({ center: t10, width: a11, height: c9, fill: Pce(e61, 0.5), stroke: \"rgba(0, 0, 0, 0.5)\", layer: h9 });\n l5.push({ points: [i10.start, i10.end], strokeColor: \"rgba(100, 100, 100, 0.8)\", strokeWidth: 0.3 * n10.padWidth, layer: h9 });\n } else if (i10.route_type === \"wire\" \u0026\u0026 a10.route_type === \"wire\" \u0026\u0026 a10.layer === i10.layer \u0026\u0026 !r10(i10, a10)) {\n const e61 = yce(t4, i10.layer);\n l5.push({ points: [{ x: i10.x, y: i10.y }, { x: a10.x, y: a10.y }], layer: `z${e61}`, strokeWidth: i10.width, strokeColor: gce(e61), ...n8 ? { label: o11.connection_name } : {} });\n }\n }\n }\n for (const n10 of e54.obstacles) {\n if (n10.isCopperPour)\n continue;\n const e60 = vce(n10, t4);\n if (e60.length === 0)\n throw new Error(`FanoutSolver: cannot visualize obstacle \"${n10.obstacleId ?? \"unknown\"}\" without a valid layer`);\n const o11 = e60.length === 1 ? t4[e60[0]] : undefined, i9 = Pce(o11 === \"bottom\" ? \"blue\" : \"red\", 0.5 ** e60.length), r10 = n10.shape, s9 = { center: n10.center, fill: i9, layer: `z${e60.join(\",\")}`, label: c5(n10) };\n r10 === \"circle\" ? h5.push({ ...s9, radius: Math.min(n10.width, n10.height) / 2 }) : d9.push({ ...s9, width: n10.width, height: n10.height, ccwRotationDegrees: n10.ccwRotationDegrees });\n }\n for (const n10 of e54.jumpers ?? [])\n for (const e60 of n10.pads)\n d9.push({ center: e60.center, width: e60.width, height: e60.height, ccwRotationDegrees: e60.ccwRotationDegrees, fill: \"rgba(255, 165, 0, 0.3)\", stroke: \"rgba(255, 165, 0, 0.8)\", layer: bce(t4, e60.layers) });\n return { rects: d9, circles: h5, lines: l5, points: u9 };\n}\nfunction Nce(e54, t4) {\n if (!Number.isFinite(t4) || t4 \u003c= 0)\n throw new Error(`FanoutSolver: ${e54} must be a positive number, received ${t4}`);\n return t4;\n}\nfunction Rce(e54, t4, n8) {\n const o10 = new Map(t4.map((e60) =\u003e [e60.busId, e60.connections.length])), i8 = new Map;\n for (const [t10, r9] of Object.entries(e54))\n i8.set(r9, (i8.get(r9) ?? 0) + (n8 ? o10.get(t10) ?? 1 : 1));\n return [...i8.values()].reduce((e60, t10) =\u003e e60 + t10 * t10, 0);\n}\nfunction Tce(e54) {\n return e54.balanceLayerLoadByConnectionCount ? 0.25 : 0.01;\n}\nfunction Ece(e54) {\n return e54.reduce((e60, t4) =\u003e e60 + Number(Boolean(t4.via)) + Number(Boolean(t4.planeEndpointVia)), 0);\n}\nfunction Ace(e54) {\n const t4 = e54.connections.reduce((t10, n8) =\u003e t10 + (e54.direction === \"left\" || e54.direction === \"right\" ? n8.sourcePoint.x : n8.sourcePoint.y), 0) / e54.connections.length;\n switch (e54.direction) {\n case \"right\":\n return e54.sharedBoundary.maxX - t4;\n case \"left\":\n return t4 - e54.sharedBoundary.minX;\n case \"up\":\n return e54.sharedBoundary.maxY - t4;\n case \"down\":\n return t4 - e54.sharedBoundary.minY;\n }\n}\nfunction Oce(e54) {\n const t4 = e54.direction === \"left\" || e54.direction === \"right\";\n return e54.connections.some((e60) =\u003e {\n const n8 = e60.exitTargetPoint ?? e60.targetPoint, o10 = t4 ? e60.sourcePoint.y : e60.sourcePoint.x, i8 = t4 ? n8.y : n8.x;\n return Math.abs(o10 - i8) \u003e 0.000001;\n });\n}\nfunction kce(e54) {\n const t4 = e54.direction === \"left\" || e54.direction === \"right\", n8 = t4 ? e54.xCoordinates : e54.yCoordinates, o10 = e54.connections.reduce((e60, n10) =\u003e e60 + (t4 ? n10.sourcePoint.x : n10.sourcePoint.y), 0) / e54.connections.length, i8 = e54.direction === \"right\" || e54.direction === \"up\" ? Math.max(...n8) : Math.min(...n8);\n return Math.abs(o10 - i8) \u003c 0.000001;\n}\nfunction Dce(e54) {\n const t4 = e54.direction === \"left\" || e54.direction === \"right\", n8 = t4 ? e54.xCoordinates : e54.yCoordinates, o10 = e54.connections.reduce((e60, n10) =\u003e e60 + (t4 ? n10.sourcePoint.x : n10.sourcePoint.y), 0) / e54.connections.length, i8 = e54.direction === \"right\" || e54.direction === \"up\" ? Math.max(...n8) : Math.min(...n8), r9 = t4 ? e54.pitchX : e54.pitchY;\n return Math.round(Math.abs(o10 - i8) / r9);\n}\nfunction Lce(e54) {\n const { buses: t4, escapeLayers: n8, escapeLayersByBusId: o10 } = e54, i8 = {}, r9 = new Map;\n let s7 = 0;\n for (const e60 of t4) {\n const t10 = r9.get(e60.componentId) ?? new Set;\n t10.add(e60.direction), r9.set(e60.componentId, t10);\n }\n for (const e60 of t4) {\n const t10 = e60.connections[0]?.sourceLayer;\n if (!t10)\n throw new Error(`FanoutSolver: bus \"${e60.busId}\" has no connections`);\n if (e60.termination.type === \"plane\") {\n i8[e60.busId] = e60.termination.layer;\n continue;\n }\n const a9 = o10[e60.busId] ?? n8, c5 = a9.filter((e61) =\u003e e61 !== t10);\n if (a9.includes(t10) \u0026\u0026 (Oce(e60) || kce(e60)))\n i8[e60.busId] = t10;\n else if (c5.length \u003e 0) {\n const t11 = r9.get(e60.componentId);\n if (t11.has(\"left\") \u0026\u0026 t11.has(\"right\") || t11.has(\"up\") \u0026\u0026 t11.has(\"down\")) {\n const t12 = Dce(e60);\n i8[e60.busId] = c5[Math.max(t12 - 1, 0) % c5.length];\n } else\n i8[e60.busId] = c5[s7 % c5.length], s7++;\n } else\n i8[e60.busId] = t10;\n }\n return i8;\n}\nfunction zce(e54) {\n const { bus: t4, srj: n8, config: o10, staticClearanceCache: i8 } = e54, r9 = o10.escapeLayers.filter((e60) =\u003e Sae({ srj: n8, bus: t4, targetLayer: e60, acceptedPlans: [], layerNames: o10.layerNames, traceWidth: o10.traceWidth, viaDiameter: o10.viaDiameter, viaHoleDiameter: o10.viaHoleDiameter, clearance: o10.clearance, compactBusTracks: o10.compactBusTracks, allowSameNetMerges: o10.allowSameNetMerges, staticClearanceCache: i8 }) !== null);\n return r9.length \u003e 0 ? r9 : o10.escapeLayers;\n}\nvar Bce = class extends BaseSolver {\n constructor(e54, t4 = {}) {\n super(), this.inputSrj = e54, this.options = t4, this.config = function(e60, t10) {\n const n10 = Nce(\"traceWidth\", t10.traceWidth ?? e60.nominalTraceWidth ?? e60.minTraceWidth), o11 = Nce(\"viaDiameter\", t10.viaDiameter ?? e60.minViaPadDiameter ?? e60.min_via_pad_diameter ?? e60.minViaDiameter ?? Math.max(2 * n10, 0.3)), i9 = Nce(\"viaHoleDiameter\", t10.viaHoleDiameter ?? e60.minViaHoleDiameter ?? e60.min_via_hole_diameter ?? 0.5 * o11);\n if (i9 \u003e= o11)\n throw new Error(`FanoutSolver: viaHoleDiameter ${i9} must be smaller than viaDiameter ${o11}`);\n const r10 = Nce(\"clearance\", t10.clearance ?? e60.minViaEdgeToPadEdgeClearance ?? e60.minTraceToPadEdgeClearance ?? e60.defaultObstacleMargin ?? e60.minTraceWidth), s7 = Wre(e60.layerCount), a9 = t10.escapeLayers ?? s7;\n for (const t11 of a9)\n if (!s7.includes(t11))\n throw new Error(`FanoutSolver: escape layer \"${t11}\" is not available in a ${e60.layerCount}-layer SimpleRouteJson`);\n if (new Set(a9).size !== a9.length)\n throw new Error(\"FanoutSolver: escapeLayers contains duplicates\");\n const c5 = t10.borderDistribution ?? \"preserve\";\n if (c5 !== \"preserve\" \u0026\u0026 c5 !== \"even\")\n throw new Error(`FanoutSolver: borderDistribution must be \"preserve\" or \"even\", received \"${c5}\"`);\n return { traceWidth: n10, viaDiameter: o11, viaHoleDiameter: i9, clearance: r10, compactBusTracks: t10.compactBusTracks ?? false, allowSameNetMerges: t10.allowSameNetMerges ?? false, singleLayerPushAndShove: t10.singleLayerPushAndShove ?? false, singleLayerAdaptiveExits: t10.singleLayerAdaptiveExits ?? false, borderDistribution: c5, layerNames: s7, escapeLayers: a9, maxLayerCombinations: t10.maxLayerCombinations === undefined ? 256 : Nce(\"maxLayerCombinations\", t10.maxLayerCombinations), balanceLayerLoadByConnectionCount: t10.balanceLayerLoadByConnectionCount ?? false };\n }(e54, t4), this.preparedBuses = Qse(e54, t4);\n for (const e60 of this.preparedBuses) {\n if (e60.termination.type !== \"plane\")\n continue;\n const t10 = e60.termination.layer;\n if (!this.config.layerNames.includes(t10))\n throw new Error(`FanoutSolver: plane-terminated bus \"${e60.busId}\" targets unavailable layer \"${t10}\"`);\n if (e60.connections.some((e61) =\u003e e61.sourceLayer === t10))\n throw new Error(`FanoutSolver: plane-terminated bus \"${e60.busId}\" must target a layer below its source pad`);\n }\n const n8 = this.preparedBuses.filter((e60) =\u003e e60.termination.type === \"boundary\").map((e60) =\u003e e60.busId), o10 = Object.fromEntries(this.preparedBuses.flatMap((e60) =\u003e e60.termination.type === \"plane\" ? [[e60.busId, e60.termination.layer]] : [])), i8 = Object.fromEntries(this.preparedBuses.flatMap((t10) =\u003e t10.termination.type === \"plane\" ? [] : [[t10.busId, zce({ bus: t10, srj: e54, config: this.config, staticClearanceCache: this.routeStaticClearanceCache })]]));\n this.escapeLayersByBusId = i8;\n const r9 = function(e60) {\n const { busIds: t10, layers: n10, layersByBusId: o11, maxAssignments: i9 } = e60;\n if (n10.length === 0)\n throw new Error(\"FanoutSolver: no escape layers are available\");\n if (!Number.isInteger(i9) || i9 \u003c 1)\n throw new Error(`FanoutSolver: maxLayerCombinations must be positive, received ${i9}`);\n const r10 = t10.map((e61) =\u003e o11?.[e61] ?? n10), s7 = r10.findIndex((e61) =\u003e e61.length === 0);\n if (s7 \u003e= 0)\n throw new Error(`FanoutSolver: no escape layers are available for bus \"${t10[s7]}\"`);\n const a9 = r10.reduce((e61, t11) =\u003e e61 * t11.length, 1), c5 = Math.min(i9, Number.isFinite(a9) ? a9 : i9), l5 = [], h5 = new Set;\n function d9(e61) {\n const n11 = {};\n for (let o13 = 0;o13 \u003c t10.length; o13++)\n n11[t10[o13]] = r10[o13][e61[o13]];\n const o12 = JSON.stringify(n11);\n h5.has(o12) || (h5.add(o12), l5.push(n11));\n }\n if (a9 \u003c= i9) {\n for (let e61 = 0;e61 \u003c c5; e61++) {\n const n11 = [];\n let o12 = e61;\n for (let e63 = 0;e63 \u003c t10.length; e63++) {\n const t11 = r10[e63].length, i10 = o12 % t11;\n o12 = Math.floor(o12 / t11), n11.push((i10 + e63) % t11);\n }\n d9(n11);\n }\n return l5;\n }\n function u9(e61) {\n let t11 = 0 | e61;\n return t11 = Math.imul(t11 ^ t11 \u003e\u003e\u003e 16, 569420461), t11 = Math.imul(t11 ^ t11 \u003e\u003e\u003e 15, 1935289751), (t11 ^ t11 \u003e\u003e\u003e 15) \u003e\u003e\u003e 0;\n }\n const p9 = t10.map((e61, t11) =\u003e t11 % r10[t11].length);\n d9(p9);\n const m9 = Math.max(...r10.map((e61) =\u003e e61.length));\n for (let e61 = 1;e61 \u003c m9 \u0026\u0026 l5.length \u003c c5; e61++)\n d9(p9.map((t11, n11) =\u003e (t11 + e61) % r10[n11].length));\n for (let e61 = 0;e61 \u003c t10.length \u0026\u0026 l5.length \u003c c5; e61++)\n for (let t11 = 1;t11 \u003c r10[e61].length \u0026\u0026 l5.length \u003c c5; t11++) {\n const n11 = [...p9];\n n11[e61] = (p9[e61] + t11) % r10[e61].length, d9(n11);\n }\n for (let e61 = 1;l5.length \u003c c5 \u0026\u0026 e61 \u003c 20 * c5; e61++)\n d9(t10.map((t11, n11) =\u003e u9(2654435761 * e61 + 2246822507 * n11) % r10[n11].length));\n return l5;\n }({ busIds: n8, layers: this.config.escapeLayers, layersByBusId: i8, maxAssignments: this.config.maxLayerCombinations }).map((e60) =\u003e ({ ...e60, ...o10 }));\n this.layerAssignments = function(e60) {\n const { preferredAssignment: t10, generatedAssignments: n10, maxAssignments: o11 } = e60, i9 = JSON.stringify(t10);\n return [t10, ...n10.filter((e61) =\u003e JSON.stringify(e61) !== i9)].slice(0, o11);\n }({ preferredAssignment: Lce({ buses: this.preparedBuses, escapeLayers: this.config.escapeLayers, escapeLayersByBusId: i8 }), generatedAssignments: r9, maxAssignments: this.config.maxLayerCombinations }), this.MAX_ITERATIONS = this.config.maxLayerCombinations + 2;\n }\n preparedBuses;\n attempts = [];\n layerAssignments;\n config;\n escapeLayersByBusId;\n evaluatedAssignmentKeys = new Set;\n queuedAssignmentKeys = new Set;\n assignmentRepairDepthByKey = new Map;\n pendingRepairAssignments = [];\n routeStaticClearanceCache = new Map;\n routingPrefixCache = new Map;\n groupedBeamEvaluated = false;\n nextAssignmentIndex = 0;\n nextGeneratedAssignmentIndex = 0;\n bestAttempt = null;\n endpointCompletion = null;\n getSolverName() {\n return \"FanoutSolver\";\n }\n completeBestAttemptEndpoints() {\n this.options.completeOriginalEndpoints \u0026\u0026 !this.endpointCompletion \u0026\u0026 this.bestAttempt \u0026\u0026 (this.endpointCompletion = Rse({ inputSrj: this.inputSrj, fanoutSrj: this.bestAttempt.outputSrj, plans: this.bestAttempt.plans, traceWidth: this.config.traceWidth, viaDiameter: this.config.viaDiameter, viaHoleDiameter: this.config.viaHoleDiameter, clearance: this.config.clearance, effort: this.options.endpointCompletionEffort, routeDownstreamConnections: this.options.routeDownstreamConnections }));\n }\n getValidationBoundary() {\n if (this.options.sharedBoundary)\n return this.options.sharedBoundary;\n const e54 = this.preparedBuses[0]?.sharedBoundary;\n return e54 ? this.preparedBuses.slice(1).reduce((e60, t4) =\u003e ({ minX: Math.min(e60.minX, t4.sharedBoundary.minX), maxX: Math.max(e60.maxX, t4.sharedBoundary.maxX), minY: Math.min(e60.minY, t4.sharedBoundary.minY), maxY: Math.max(e60.maxY, t4.sharedBoundary.maxY) }), { ...e54 }) : this.inputSrj.bounds;\n }\n validateCompletePlans(e54, t4) {\n return pce({ inputSrj: this.inputSrj, outputSrj: t4, plans: e54, preparedBuses: this.preparedBuses, sharedBoundary: this.getValidationBoundary(), clearance: this.config.clearance });\n }\n evaluateAssignmentWithStrategy(e54, t4, n8) {\n let o10 = [], i8 = [], r9 = new Map;\n const s7 = this.config.escapeLayers.length === 1;\n if (s7 \u0026\u0026 this.config.singleLayerPushAndShove) {\n const e60 = { srj: this.inputSrj, buses: this.preparedBuses, traceWidth: this.config.traceWidth, clearance: this.config.clearance, borderDistribution: this.config.borderDistribution }, t10 = ece(e60) ?? (this.config.singleLayerAdaptiveExits ? Bae({ ...e60, availableBoundaryRegions: Yse(this.options.availableCornersAndSides) }) : null);\n t10 ? o10.push(...t10) : i8.push(...this.preparedBuses.map((e61) =\u003e e61.busId));\n }\n const a9 = [...this.preparedBuses].sort((e60, o11) =\u003e Number(o11.termination.type === \"plane\") - Number(e60.termination.type === \"plane\") || (n8 === \"group-by-layer\" ? (t4[e60.busId] ?? \"\").localeCompare(t4[o11.busId] ?? \"\") : 0) || o11.componentObstacles.length - e60.componentObstacles.length || (s7 ? Ace(o11) - Ace(e60) : o11.connections.length - e60.connections.length || (n8 === \"deep-first\" ? Ace(o11) - Ace(e60) : Ace(e60) - Ace(o11))));\n let c5, l5 = `${n8}|`;\n for (const n10 of s7 \u0026\u0026 this.config.singleLayerPushAndShove ? [] : a9) {\n const s9 = t4[n10.busId];\n if (!s9)\n throw new Error(`FanoutSolver: assignment ${e54} has no layer for bus \"${n10.busId}\"`);\n l5 += `${n10.busId.length}:${n10.busId};${s9.length}:${s9};`;\n const a10 = this.routingPrefixCache.get(l5);\n if (a10) {\n o10 = [...a10.plans], i8 = [...a10.failedBusIds], r9 = new Map(a10.blockingBusCounts);\n continue;\n }\n const c9 = new Map, h9 = Sae({ srj: this.inputSrj, bus: n10, targetLayer: s9, acceptedPlans: o10, layerNames: this.config.layerNames, traceWidth: this.config.traceWidth, viaDiameter: this.config.viaDiameter, viaHoleDiameter: this.config.viaHoleDiameter, clearance: this.config.clearance, compactBusTracks: this.config.compactBusTracks, allowSameNetMerges: this.config.allowSameNetMerges, staticClearanceCache: this.routeStaticClearanceCache, blockingBusCounts: c9 });\n if (h9)\n o10.push(...h9);\n else {\n i8.push(n10.busId);\n for (const [e60, t10] of c9)\n r9.set(e60, (r9.get(e60) ?? 0) + t10);\n }\n this.routingPrefixCache.set(l5, { plans: [...o10], failedBusIds: [...i8], blockingBusCounts: new Map(r9) });\n }\n let h5 = kre({ inputSrj: this.inputSrj, plans: o10, layerNames: this.config.layerNames });\n const d9 = o10.length === this.inputSrj.connections.length ? this.validateCompletePlans(o10, h5) : null;\n d9 \u0026\u0026 !d9.valid \u0026\u0026 (c5 = d9.issues, o10 = [], i8 = this.preparedBuses.map((e60) =\u003e e60.busId), r9.clear(), h5 = kre({ inputSrj: this.inputSrj, plans: o10, layerNames: this.config.layerNames }));\n const u9 = this.preparedBuses.length - i8.length, p9 = o10.reduce((e60, t10) =\u003e e60 + t10.length, 0), m9 = 1e6 * (this.inputSrj.connections.length - o10.length) + 1e5 * i8.length + p9 + 0.1 * Ece(o10) + Rce(t4, this.preparedBuses, this.config.balanceLayerLoadByConnectionCount) * Tce(this.config);\n return { summary: { assignmentIndex: e54, busLayerAssignments: t4, routedBusCount: u9, routedConnectionCount: o10.length, failedBusIds: i8, score: m9, ...c5 ? { validationIssues: c5 } : {} }, plans: o10, blockingBusIds: [...r9.entries()].toSorted(([, e60], [, t10]) =\u003e t10 - e60).map(([e60]) =\u003e e60), outputSrj: h5 };\n }\n evaluateAssignment(e54, t4) {\n let n8 = this.evaluateAssignmentWithStrategy(e54, t4, \"default\");\n if (n8.summary.routedConnectionCount === this.inputSrj.connections.length)\n return n8;\n for (const o10 of [\"group-by-layer\", \"deep-first\"]) {\n const i8 = this.evaluateAssignmentWithStrategy(e54, t4, o10);\n if (i8.summary.score \u003c n8.summary.score \u0026\u0026 (n8 = i8), n8.summary.routedConnectionCount === this.inputSrj.connections.length)\n return n8;\n }\n return n8;\n }\n evaluateGroupedBeam(e54, t4 = false) {\n if (this.config.escapeLayers.length \u003c 2)\n return null;\n if (this.preparedBuses.length \u003e 56)\n return null;\n const n8 = this.inputSrj.connections.length;\n if (n8 \u003e 64)\n return null;\n if (new Set(this.preparedBuses.map((e60) =\u003e e60.componentId)).size !== 1)\n return null;\n const o10 = [...this.preparedBuses].sort((e60, n10) =\u003e {\n const o11 = e60.termination.type === \"plane\" ? 1 : this.escapeLayersByBusId[e60.busId]?.length ?? this.config.escapeLayers.length, i9 = n10.termination.type === \"plane\" ? 1 : this.escapeLayersByBusId[n10.busId]?.length ?? this.config.escapeLayers.length;\n return Number(n10.termination.type === \"plane\") - Number(e60.termination.type === \"plane\") || (t4 ? e60.direction.localeCompare(n10.direction) : 0) || o11 - i9 || n10.componentObstacles.length - e60.componentObstacles.length || n10.connections.length - e60.connections.length || Dce(n10) - Dce(e60) || e60.busId.localeCompare(n10.busId);\n }), i8 = n8 \u003c= 24, r9 = this.preparedBuses.some((e60) =\u003e e60.connections.length \u003e 1), s7 = i8 ? 48 : n8 \u003c= 32 ? 24 : 12, a9 = i8 \u0026\u0026 !r9 ? 4 : 1;\n let c5 = [{ assignment: {}, plans: [] }];\n const l5 = (e60) =\u003e e60.plans.reduce((e61, t10) =\u003e e61 + t10.length, 0) + 0.1 * Ece(e60.plans) + 1e4 * this.preparedBuses.reduce((t10, n10) =\u003e {\n if (n10.termination.type !== \"boundary\" || !Oce(n10))\n return t10;\n const o11 = n10.connections[0]?.sourceLayer;\n return e60.assignment[n10.busId] === o11 ? t10 : t10 + n10.connections.length;\n }, 0) + Rce(e60.assignment, this.preparedBuses, this.config.balanceLayerLoadByConnectionCount) * Tce(this.config);\n for (const e60 of o10) {\n const t10 = [];\n for (const n11 of c5) {\n const o11 = e60.termination.type === \"plane\" ? [e60.termination.layer] : this.escapeLayersByBusId[e60.busId] ?? this.config.escapeLayers, i9 = new Map;\n for (const [e61, t11] of Object.entries(n11.assignment)) {\n const n12 = this.preparedBuses.find((t12) =\u003e t12.busId === e61);\n i9.set(t11, (i9.get(t11) ?? 0) + (this.config.balanceLayerLoadByConnectionCount ? n12?.connections.length ?? 1 : 1));\n }\n const r10 = e60.connections[0]?.sourceLayer, s9 = Oce(e60), c9 = o11.toSorted((e61, t11) =\u003e (i9.get(e61) ?? 0) - (i9.get(t11) ?? 0) || (s9 ? Number(t11 === r10) - Number(e61 === r10) : Number(e61 === r10) - Number(t11 === r10)) || e61.localeCompare(t11));\n for (const o12 of c9) {\n const i10 = Iae({ srj: this.inputSrj, bus: e60, targetLayer: o12, acceptedPlans: n11.plans, layerNames: this.config.layerNames, traceWidth: this.config.traceWidth, viaDiameter: this.config.viaDiameter, viaHoleDiameter: this.config.viaHoleDiameter, clearance: this.config.clearance, compactBusTracks: this.config.compactBusTracks, allowSameNetMerges: this.config.allowSameNetMerges, staticClearanceCache: this.routeStaticClearanceCache }, a9);\n for (const r11 of i10)\n t10.push({ assignment: { ...n11.assignment, [e60.busId]: o12 }, plans: [...n11.plans, ...r11] });\n }\n }\n if (t10.length === 0)\n return null;\n t10.sort((e61, t11) =\u003e {\n const n11 = l5(e61) - l5(t11);\n return Math.abs(n11) \u003e 0.000000001 ? n11 : JSON.stringify(e61.assignment).localeCompare(JSON.stringify(t11.assignment));\n });\n const n10 = new Map;\n c5 = [];\n for (const e61 of t10) {\n const t11 = JSON.stringify(e61.assignment), o11 = n10.get(t11) ?? 0;\n if (!(o11 \u003e= 2) \u0026\u0026 (n10.set(t11, o11 + 1), c5.push(e61), c5.length \u003e= s7))\n break;\n }\n }\n const h5 = c5[0];\n if (!h5)\n return null;\n const d9 = kre({ inputSrj: this.inputSrj, plans: h5.plans, layerNames: this.config.layerNames });\n if (h5.plans.length === this.inputSrj.connections.length \u0026\u0026 !this.validateCompletePlans(h5.plans, d9).valid)\n return null;\n const u9 = h5.plans.length === this.inputSrj.connections.length ? h5.plans.reduce((e60, t10) =\u003e e60 + t10.length, 0) + 0.1 * Ece(h5.plans) + Rce(h5.assignment, this.preparedBuses, this.config.balanceLayerLoadByConnectionCount) * Tce(this.config) : Number.POSITIVE_INFINITY;\n if (!Number.isFinite(u9))\n return null;\n return { summary: { assignmentIndex: e54, busLayerAssignments: h5.assignment, routedBusCount: this.preparedBuses.length, routedConnectionCount: h5.plans.length, failedBusIds: [], score: u9 }, plans: h5.plans, blockingBusIds: [], outputSrj: d9 };\n }\n prioritizeFailedBusRepairs(e54, t4, n8) {\n const o10 = JSON.stringify(e54), i8 = this.assignmentRepairDepthByKey.get(o10) ?? 0;\n if (i8 \u003e= 2)\n return;\n const r9 = [], s7 = new Set, a9 = (e60) =\u003e {\n const t10 = JSON.stringify(e60);\n s7.has(t10) || this.evaluatedAssignmentKeys.has(t10) || this.queuedAssignmentKeys.has(t10) || (s7.add(t10), this.queuedAssignmentKeys.add(t10), this.assignmentRepairDepthByKey.set(t10, i8 + 1), r9.push(e60));\n }, c5 = [];\n for (let e60 = 0;e60 \u003c Math.max(t4.length, n8.length); e60++) {\n const o11 = t4[e60], i9 = n8[e60];\n o11 \u0026\u0026 !c5.includes(o11) \u0026\u0026 c5.push(o11), i9 \u0026\u0026 !c5.includes(i9) \u0026\u0026 c5.push(i9);\n }\n for (const o11 of t4) {\n const t10 = e54[o11], i9 = this.escapeLayersByBusId[o11];\n if (t10 \u0026\u0026 i9) {\n for (const s9 of n8.slice(0, 4)) {\n const n10 = e54[s9], c9 = this.escapeLayersByBusId[s9];\n if (n10 \u0026\u0026 c9 \u0026\u0026 i9.includes(n10) \u0026\u0026 c9.includes(t10) \u0026\u0026 (a9({ ...e54, [o11]: n10, [s9]: t10 }), r9.length \u003e= 8))\n break;\n }\n if (r9.length \u003e= 8)\n break;\n }\n }\n for (const t10 of c5) {\n const n10 = e54[t10], o11 = this.escapeLayersByBusId[t10];\n if (!n10 || !o11)\n continue;\n const i9 = o11.indexOf(n10);\n for (let s9 = 1;s9 \u003c o11.length; s9++) {\n const c9 = o11[(Math.max(i9, 0) + s9) % o11.length];\n if (c9 !== n10 \u0026\u0026 (a9({ ...e54, [t10]: c9 }), r9.length \u003e= 8))\n break;\n }\n if (r9.length \u003e= 8)\n break;\n }\n this.pendingRepairAssignments.push(...r9);\n }\n hasCompleteBestAttempt() {\n return this.bestAttempt?.summary.routedConnectionCount === this.inputSrj.connections.length;\n }\n shouldEvaluateGroupedBeam() {\n if (this.groupedBeamEvaluated || this.nextAssignmentIndex === 0)\n return false;\n return this.hasCompleteBestAttempt() || this.pendingRepairAssignments.length === 0 || this.nextAssignmentIndex \u003e= this.config.maxLayerCombinations;\n }\n _step() {\n if (this.shouldEvaluateGroupedBeam()) {\n this.groupedBeamEvaluated = true;\n let e60 = this.evaluateGroupedBeam(-1);\n if (e60 || (e60 = this.evaluateGroupedBeam(-1, true)), e60) {\n this.attempts.push(e60.summary), (!this.bestAttempt || e60.summary.score \u003c this.bestAttempt.summary.score) \u0026\u0026 (this.bestAttempt = e60);\n const t10 = this.bestAttempt.summary;\n return this.stats = { assignment: t10.assignmentIndex \u003c 0 ? 0 : t10.assignmentIndex + 1, assignmentCount: this.config.maxLayerCombinations, routedBuses: `${t10.routedBusCount}/${this.preparedBuses.length}`, routedConnections: `${t10.routedConnectionCount}/${this.inputSrj.connections.length}`, failedBuses: \"none\", bestScore: t10.score }, this.completeBestAttemptEndpoints(), void (this.solved = true);\n }\n if (this.hasCompleteBestAttempt())\n return this.completeBestAttemptEndpoints(), void (this.solved = true);\n }\n let e54;\n for (;!e54 \u0026\u0026 this.nextAssignmentIndex \u003c this.config.maxLayerCombinations; ) {\n const t10 = this.nextAssignmentIndex % 3 == 0;\n let n8, o10 = false;\n if (!this.groupedBeamEvaluated \u0026\u0026 this.nextAssignmentIndex \u003e 0 ? (n8 = this.pendingRepairAssignments.pop(), o10 = n8 !== undefined) : t10 ? n8 = this.layerAssignments[this.nextGeneratedAssignmentIndex++] : (n8 = this.pendingRepairAssignments.pop(), o10 = n8 !== undefined), n8 || !this.groupedBeamEvaluated \u0026\u0026 this.nextAssignmentIndex !== 0 || (n8 = t10 ? this.pendingRepairAssignments.pop() : this.layerAssignments[this.nextGeneratedAssignmentIndex++], o10 = t10 \u0026\u0026 n8 !== undefined), !n8)\n break;\n const i8 = JSON.stringify(n8);\n o10 \u0026\u0026 this.queuedAssignmentKeys.delete(i8), this.evaluatedAssignmentKeys.has(i8) || (e54 = n8);\n }\n if (!e54 \u0026\u0026 !this.groupedBeamEvaluated)\n return;\n if (!e54)\n return void (this.hasCompleteBestAttempt() ? (this.completeBestAttemptEndpoints(), this.solved = true) : (this.failed = true, this.error = this.bestAttempt ? `FanoutSolver: best layer assignment routed ${this.bestAttempt.summary.routedConnectionCount}/${this.inputSrj.connections.length} connections` : \"FanoutSolver: no layer assignment could be evaluated\"));\n const t4 = this.evaluateAssignment(this.nextAssignmentIndex, e54);\n this.nextAssignmentIndex++, this.evaluatedAssignmentKeys.add(JSON.stringify(e54)), (!this.bestAttempt || t4.summary.routedConnectionCount \u003e= this.bestAttempt.summary.routedConnectionCount) \u0026\u0026 this.prioritizeFailedBusRepairs(e54, t4.summary.failedBusIds, t4.blockingBusIds), this.attempts.push(t4.summary), (!this.bestAttempt || t4.summary.score \u003c this.bestAttempt.summary.score) \u0026\u0026 (this.bestAttempt = t4), this.stats = { assignment: t4.summary.assignmentIndex + 1, assignmentCount: this.config.maxLayerCombinations, routedBuses: `${t4.summary.routedBusCount}/${this.preparedBuses.length}`, routedConnections: `${t4.summary.routedConnectionCount}/${this.inputSrj.connections.length}`, failedBuses: t4.summary.failedBusIds.join(\", \") || \"none\", bestScore: this.bestAttempt.summary.score }, this.groupedBeamEvaluated \u0026\u0026 t4.summary.routedConnectionCount === this.inputSrj.connections.length \u0026\u0026 (this.completeBestAttemptEndpoints(), this.solved = true);\n }\n computeProgress() {\n return this.solved || this.failed ? 1 : this.nextAssignmentIndex / this.config.maxLayerCombinations;\n }\n getConstructorParams() {\n return [this.inputSrj, this.options];\n }\n getOutput() {\n if (!this.solved || !this.bestAttempt)\n throw new Error(\"FanoutSolver: getOutput() called before a complete fanout was solved\");\n const e54 = this.validateCompletePlans(this.bestAttempt.plans, this.bestAttempt.outputSrj);\n if (!e54.valid)\n throw new Error(`FanoutSolver: completed output failed validation: ${e54.issues[0]?.message ?? \"unknown validation error\"}`);\n const t4 = this.endpointCompletion?.simpleRouteJson ?? this.bestAttempt.outputSrj, n8 = new Map((t4.traces ?? []).map((e60) =\u003e [e60.pcb_trace_id, e60]));\n return { simpleRouteJson: this.endpointCompletion?.simpleRouteJson ?? this.bestAttempt.outputSrj, fanoutTraces: this.bestAttempt.plans.flatMap((e60) =\u003e [n8.get(e60.trace.pcb_trace_id) ?? e60.trace, ...e60.planeEndpointTrace ? [n8.get(e60.planeEndpointTrace.pcb_trace_id) ?? e60.planeEndpointTrace] : []]), completionTraces: this.endpointCompletion?.traces ?? [], ...this.endpointCompletion ? { endpointCompletion: this.endpointCompletion.report } : {}, planeTerminations: this.bestAttempt.plans.flatMap((e60) =\u003e e60.termination.type === \"plane\" \u0026\u0026 e60.via ? [{ busId: e60.busId, connectionName: e60.connectionName, layer: e60.termination.layer, via: e60.via }] : []), busLayerAssignments: this.bestAttempt.summary.busLayerAssignments, busDirections: Object.fromEntries(this.preparedBuses.map((e60) =\u003e [e60.busId, e60.direction])), attempts: [...this.attempts], validation: e54 };\n }\n getOutputSimpleRouteJson() {\n return this.getOutput().simpleRouteJson;\n }\n visualize() {\n return wce(this.endpointCompletion?.simpleRouteJson ?? this.bestAttempt?.outputSrj ?? this.inputSrj);\n }\n};\nfunction Yce(e54) {\n const { minX: t4, maxX: n8 } = e54.bounds, o10 = (t4 + n8) / 2;\n if (!Number.isFinite(o10))\n throw new Error(`Detected component ${e54.componentId} has bad bounds`);\n return o10;\n}\nfunction Xce(e54) {\n const { minY: t4, maxY: n8 } = e54.bounds, o10 = (t4 + n8) / 2;\n if (!Number.isFinite(o10))\n throw new Error(`Detected component ${e54.componentId} has bad bounds`);\n return o10;\n}\nfunction Hce(e54, t4) {\n const n8 = (function(e60, t10) {\n const [n10, o10] = Yce(e60) \u003c Yce(t10) ? [e60, t10] : [t10, e60];\n return o10.bounds.minX - n10.bounds.maxX;\n }(e54, t4) - 2) / 2;\n return Math.min(4.5, n8);\n}\nfunction Vce(e54, t4) {\n const n8 = t4.filter((e60) =\u003e e60.componentKind === \"bga\").map((t10) =\u003e function(e60, t11) {\n const n10 = e60.obstacles.filter((e61) =\u003e e61.componentId === t11.componentId);\n if (n10.length === 0)\n throw new Error(`Detected component ${t11.componentId} has no physical obstacles`);\n return { ...t11, bounds: { __type: \"rect\", minX: Math.min(...n10.map((e61) =\u003e e61.center.x - e61.width / 2)), maxX: Math.max(...n10.map((e61) =\u003e e61.center.x + e61.width / 2)), minY: Math.min(...n10.map((e61) =\u003e e61.center.y - e61.height / 2)), maxY: Math.max(...n10.map((e61) =\u003e e61.center.y + e61.height / 2)) } };\n }(e54, t10)).toSorted((e60, t10) =\u003e Yce(e60) - Yce(t10));\n if (n8.length !== 2)\n throw new Error(`Pipeline 10 requires exactly two detected BGAs; found ${n8.map((e60) =\u003e e60.componentId).join(\", \") || \"none\"}`);\n const [o10, i8] = n8;\n if (o10.componentId === i8.componentId)\n throw new Error(\"Pipeline 10 requires two distinct BGA component IDs\");\n if (Hce(o10, i8) \u003c 2)\n throw new Error(\"Pipeline 10 cannot provide 2mm fanout margins while retaining a 2mm routing corridor\");\n return { first: o10, second: i8 };\n}\nfunction Wce(e54, t4) {\n const { minX: n8, maxX: o10, minY: i8, maxY: r9 } = e54.bounds;\n return { minX: n8 - t4, maxX: o10 + t4, minY: i8 - t4, maxY: r9 + t4 };\n}\nfunction Gce(e54) {\n const { minX: t4, maxX: n8, minY: o10, maxY: i8 } = e54.bounds;\n return { minX: t4, maxX: n8, minY: o10, maxY: i8 };\n}\nfunction Uce({ inputSrj: e54, source: t4, target: n8 }) {\n const o10 = Hce(t4, n8), i8 = Wce(t4, o10), r9 = Yce(n8) \u003e Yce(t4) ? \"right\" : \"left\", s7 = r9 === \"right\" ? \"left\" : \"right\";\n return e54.connections.map((e60, n10) =\u003e {\n const a9 = e60.pointsToConnect.filter((e61) =\u003e e61.x \u003e= t4.bounds.minX \u0026\u0026 e61.x \u003c= t4.bounds.maxX \u0026\u0026 e61.y \u003e= t4.bounds.minY \u0026\u0026 e61.y \u003c= t4.bounds.maxY);\n if (a9.length !== 1)\n throw new Error(`Connection ${e60.name} must touch ${t4.componentId} exactly once before fanout`);\n const c5 = a9[0], l5 = r9 === \"right\" ? i8.maxX - c5.x : c5.x - i8.minX, h5 = [{ direction: \"up\", distance: i8.maxY - c5.y }, { direction: \"down\", distance: c5.y - i8.minY }, { direction: s7, distance: s7 === \"right\" ? i8.maxX - c5.x : c5.x - i8.minX }].toSorted((e61, t10) =\u003e e61.distance - t10.distance)[0].direction, d9 = l5 \u003c= o10 + 1.2 ? r9 : h5;\n let u9 = d9 === \"up\" ? \"top\" : d9 === \"down\" ? \"bottom\" : d9;\n return d9 === \"up\" ? u9 = c5.x \u003c Yce(t4) ? \"top-left\" : \"top-right\" : d9 === \"down\" ? u9 = c5.x \u003c Yce(t4) ? \"bottom-left\" : \"bottom-right\" : c5.y \u003e Xce(t4) + 0.000001 ? u9 = d9 === \"right\" ? \"top-right\" : \"top-left\" : c5.y \u003c Xce(t4) - 0.000001 \u0026\u0026 (u9 = d9 === \"right\" ? \"bottom-right\" : \"bottom-left\"), { busId: `pipeline10_fanout:${t4.componentId}:${n10}`, connectionNames: [e60.name], sourceComponentId: t4.componentId, direction: d9, preferredExit: u9, termination: { type: \"boundary\" } };\n });\n}\nfunction Zce({ inputSrj: e54, source: t4, target: n8 }) {\n const o10 = Hce(t4, n8);\n return { buses: Uce({ inputSrj: e54, source: t4, target: n8 }), sourceComponentId: t4.componentId, availableCornersAndSides: [\"top_left\", \"top_middle\", \"top_right\", \"right_top\", \"right_middle\", \"right_bottom\", \"bottom_right\", \"bottom_middle\", \"bottom_left\", \"left_bottom\", \"left_middle\", \"left_top\"], componentBounds: { [t4.componentId]: Gce(t4) }, sharedBoundary: Wce(t4, o10), maxLayerCombinations: 256, balanceLayerLoadByConnectionCount: true, compactBusTracks: true, borderDistribution: \"even\" };\n}\nvar qce = class extends BaseSolver {\n constructor(e54) {\n super(), this.inputProblem = e54, this.fanoutSolver = new Bce(e54.inputSrj, e54.options), this.activeSubSolver = this.fanoutSolver, this.MAX_ITERATIONS = this.fanoutSolver.MAX_ITERATIONS + 1;\n }\n fanoutSolver;\n _step() {\n if (this.fanoutSolver.step(), this.progress = this.fanoutSolver.progress, this.stats = { ...this.fanoutSolver.stats }, this.fanoutSolver.failed)\n return this.error = this.fanoutSolver.error ?? \"Fanout solver failed\", this.failed = true, void (this.activeSubSolver = null);\n this.fanoutSolver.solved \u0026\u0026 (this.solved = true, this.activeSubSolver = null);\n }\n getConstructorParams() {\n return [this.inputProblem];\n }\n getOutput() {\n return this.fanoutSolver.getOutput();\n }\n getOutputSimpleRouteJson() {\n return this.fanoutSolver.getOutputSimpleRouteJson();\n }\n visualize() {\n return this.fanoutSolver.visualize();\n }\n preview() {\n return this.fanoutSolver.preview();\n }\n};\nvar Jce = class extends BaseSolver {\n constructor(e54) {\n super(), this.inputProblem = e54, this.autoroutingPipelineSolver = new ire(e54.inputSrj, e54.options), this.activeSubSolver = this.autoroutingPipelineSolver, this.MAX_ITERATIONS = this.autoroutingPipelineSolver.MAX_ITERATIONS + 1;\n }\n autoroutingPipelineSolver;\n _step() {\n if (this.autoroutingPipelineSolver.step(), this.progress = this.autoroutingPipelineSolver.progress, this.stats = { ...this.autoroutingPipelineSolver.stats }, this.autoroutingPipelineSolver.failed)\n return this.error = this.autoroutingPipelineSolver.error ?? \"Autorouting pipeline failed\", this.failed = true, void (this.activeSubSolver = null);\n this.autoroutingPipelineSolver.solved \u0026\u0026 (this.solved = true, this.activeSubSolver = null);\n }\n getConstructorParams() {\n return [this.inputProblem];\n }\n getOutput() {\n return this.autoroutingPipelineSolver.getOutputSimpleRouteJson();\n }\n visualize() {\n return this.autoroutingPipelineSolver.visualize();\n }\n preview() {\n return this.autoroutingPipelineSolver.preview();\n }\n};\nvar Qce = class extends BasePipelineSolver {\n componentDetectionSolver;\n firstBgaFanoutSolver;\n secondBgaFanoutSolver;\n autoroutingPipelineSolver;\n get currentPipelineStepIndex() {\n return this.currentPipelineStageIndex;\n }\n get startTimeOfPhase() {\n return this.startTimeOfStage;\n }\n get timeSpentOnPhase() {\n return this.timeSpentOnStage;\n }\n pipelineDef = [definePipelineStep(\"componentDetectionSolver\", r7, (e54) =\u003e [{ inputSrj: e54.inputProblem.inputSrj }]), definePipelineStep(\"firstBgaFanoutSolver\", qce, (e54) =\u003e {\n const t4 = Vce(e54.inputProblem.inputSrj, e54.componentDetectionSolver.getOutput());\n return [{ inputSrj: e54.inputProblem.inputSrj, options: Zce({ inputSrj: e54.inputProblem.inputSrj, source: t4.first, target: t4.second }) }];\n }), definePipelineStep(\"secondBgaFanoutSolver\", qce, (e54) =\u003e {\n const t4 = Vce(e54.inputProblem.inputSrj, e54.componentDetectionSolver.getOutput()), n8 = e54.firstBgaFanoutSolver.getOutputSimpleRouteJson();\n return [{ inputSrj: n8, options: Zce({ inputSrj: n8, source: t4.second, target: t4.first }) }];\n }), definePipelineStep(\"autoroutingPipelineSolver\", Jce, (e54) =\u003e [{ inputSrj: e54.secondBgaFanoutSolver.getOutputSimpleRouteJson(), options: e54.inputProblem.options }])];\n constructor(e54, t4 = {}) {\n super({ inputSrj: e54, options: t4 }), this.MAX_ITERATIONS = 1e8 * (t4.effort ?? 1) + 1024;\n }\n getSolverName() {\n return \"AutoroutingPipelineSolver10_BgaFanout\";\n }\n getConstructorParams() {\n return [this.inputProblem.inputSrj, this.inputProblem.options];\n }\n getOutput() {\n if (!this.autoroutingPipelineSolver?.solved)\n throw new Error(\"Pipeline 10 has not solved yet\");\n return this.autoroutingPipelineSolver.getOutput();\n }\n getOutputSimpleRouteJson() {\n return this.getOutput();\n }\n getOutputSimplifiedPcbTraces() {\n return this.getOutput().traces ?? [];\n }\n get srjWithPointPairs() {\n return this.autoroutingPipelineSolver?.autoroutingPipelineSolver.srjWithPointPairs;\n }\n initialVisualize() {\n return Wo(this.inputProblem.inputSrj);\n }\n finalVisualize() {\n return Wo(this.getOutput());\n }\n};\nvar nle = class extends BaseSolver {\n constructor(e54) {\n super(), this.inputProblem = e54, this.simplifiedRouteByTraceId = new Map(e54.simplifiedHdRoutes.map((e60) =\u003e [e60.connectionName, e60])), this.MAX_ITERATIONS = e54.preparedInput.preparedTraces.length + 1;\n }\n simplifiedRouteByTraceId;\n outputTraces = [];\n nextTraceIndex = 0;\n getSolverName() {\n return \"ApplyTraceSimplificationSolver\";\n }\n _step() {\n const e54 = this.inputProblem.preparedInput.preparedTraces, t4 = e54[this.nextTraceIndex];\n t4 ? (this.outputTraces.push(this.applyTrace(t4)), this.nextTraceIndex++, this.progress = this.nextTraceIndex / Math.max(1, e54.length)) : this.finishApplication();\n }\n applyTrace(e54) {\n if (!e54.mutableHdRoute)\n return structuredClone(e54.originalTrace);\n const t4 = this.simplifiedRouteByTraceId.get(e54.originalTrace.pcb_trace_id);\n if (!t4 || e54.uniformTraceWidth === undefined)\n throw new Error(`Simplification removed trace \"${e54.originalTrace.pcb_trace_id}\"`);\n const n8 = Ro(t4, this.inputProblem.preparedInput.srj.layerCount, { defaultViaHoleDiameter: e54.viaHoleDiameter, obstacles: this.inputProblem.preparedInput.srj.obstacles, connMap: this.inputProblem.preparedInput.connMap }), o10 = n8.filter((e60) =\u003e e60.route_type === \"jumper\"), i8 = ((e60, t10) =\u003e e60.map((e61) =\u003e e61.route_type === \"wire\" || e61.route_type === \"through_obstacle\" ? { ...e61, width: t10 } : e61))([...structuredClone(e54.leadingTerminalVias), ...n8.filter((e60) =\u003e e60.route_type !== \"jumper\"), ...structuredClone(e54.trailingTerminalVias), ...o10], e54.uniformTraceWidth);\n return ((e60, t10) =\u003e {\n const n10 = e60.filter((e61) =\u003e e61.route_type === \"wire\");\n t10.startPcbPortId \u0026\u0026 n10[0] \u0026\u0026 (n10[0].start_pcb_port_id = t10.startPcbPortId), t10.endPcbPortId \u0026\u0026 n10.at(-1) \u0026\u0026 (n10.at(-1).end_pcb_port_id = t10.endPcbPortId);\n })(i8, t4), { ...structuredClone(e54.originalTrace), route: i8 };\n }\n finishApplication() {\n const e54 = this.inputProblem.preparedInput.preparedTraces;\n this.stats = { inputTraceCount: e54.length, outputTraceCount: this.outputTraces.length, inputRoutePointCount: e54.reduce((e60, t4) =\u003e e60 + t4.originalTrace.route.length, 0), outputRoutePointCount: this.outputTraces.reduce((e60, t4) =\u003e e60 + t4.route.length, 0) }, this.progress = 1, this.solved = true;\n }\n getConstructorParams() {\n return [this.inputProblem];\n }\n getOutput() {\n if (!this.solved)\n throw new Error(\"Cannot get applied traces before conversion completes\");\n return { ...structuredClone(this.inputProblem.preparedInput.originalSrj), traces: structuredClone(this.outputTraces) };\n }\n};\nvar ile = (e54, t4) =\u003e {\n const n8 = e54.at(-1);\n if (n8 \u0026\u0026 (o10 = n8, i8 = t4, Math.abs(o10.x - i8.x) \u003c= 0.000000001 \u0026\u0026 Math.abs(o10.y - i8.y) \u003c= 0.000000001 \u0026\u0026 o10.z === i8.z))\n return t4.traceThickness !== undefined \u0026\u0026 (n8.traceThickness = t4.traceThickness), void (t4.pcb_port_id !== undefined \u0026\u0026 (n8.pcb_port_id = t4.pcb_port_id));\n var o10, i8;\n e54.push(t4);\n};\nvar rle = (e54, t4, n8) =\u003e {\n for (let o10 = t4 + 1;o10 \u003c e54.length; o10++) {\n const t10 = e54[o10];\n if (t10.route_type === \"wire\")\n return mo(t10.layer, n8);\n if (t10.route_type === \"through_obstacle\")\n return mo(t10.from_layer, n8);\n }\n};\nvar sle = ({ fromZ: e54, toZ: t4, previousZ: n8, nextZ: o10 }) =\u003e n8 === e54 ? [e54, t4] : n8 === t4 ? [t4, e54] : o10 === t4 ? [e54, t4] : o10 === e54 ? [t4, e54] : [e54, t4];\nvar ale = (e54, t4) =\u003e {\n for (const t10 of e54)\n if (t10.route_type === \"via\" \u0026\u0026 t10.via_diameter !== undefined)\n return t10.via_diameter;\n return t4;\n};\nvar cle = (e54, t4) =\u003e {\n const n8 = t4 === \"start\" ? e54 : [...e54].reverse();\n for (const e60 of n8) {\n if (e60.route_type !== \"wire\")\n continue;\n const n10 = t4 === \"start\" ? e60.start_pcb_port_id : e60.end_pcb_port_id;\n if (n10)\n return n10;\n }\n};\nvar lle = (e54) =\u003e ({ route_type: \"jumper\", start: { ...e54.start }, end: { ...e54.end }, footprint: e54.footprint });\nvar hle = (e54, t4) =\u003e {\n for (const t10 of e54.route)\n if (t10.route_type === \"via\" \u0026\u0026 t10.via_hole_diameter !== undefined)\n return t10.via_hole_diameter;\n return t4;\n};\nvar dle = class extends BaseSolver {\n preparedInput;\n seenTraceIds = new Set;\n nextTraceIndex = 0;\n constructor(e54) {\n super();\n const t4 = structuredClone(e54.inputSrj), n8 = V1(t4), o10 = ei(n8);\n this.preparedInput = { originalSrj: t4, srj: n8, connMap: o10, colorMap: Eo(n8, o10), immutableHdRoutes: [], mutableHdRoutes: [], netByConnectionName: new Map, options: { ...e54.options }, preparedTraces: [] }, this.MAX_ITERATIONS = (n8.traces?.length ?? 0) + 1;\n }\n getSolverName() {\n return \"PrepareTraceSimplificationSolver\";\n }\n _step() {\n const e54 = this.preparedInput.srj.traces ?? [], t4 = e54[this.nextTraceIndex];\n if (!t4)\n return this.stats = { inputTraceCount: e54.length, mutableTraceCount: this.preparedInput.mutableHdRoutes.length, immutableTraceCount: e54.length - this.preparedInput.mutableHdRoutes.length }, this.progress = 1, void (this.solved = true);\n this.prepareTrace(t4, this.nextTraceIndex), this.nextTraceIndex++, this.progress = this.nextTraceIndex / Math.max(1, e54.length);\n }\n prepareTrace(e54, t4) {\n if (this.seenTraceIds.has(e54.pcb_trace_id))\n throw new Error(`Duplicate pcb_trace_id \"${e54.pcb_trace_id}\"`);\n this.seenTraceIds.add(e54.pcb_trace_id);\n const n8 = Yo(this.preparedInput.srj), o10 = ((e60) =\u003e {\n const t10 = e60.route.flatMap((e61) =\u003e e61.route_type === \"wire\" || e61.route_type === \"through_obstacle\" ? [e61.width] : []), n10 = t10[0];\n if (n10 !== undefined \u0026\u0026 !t10.some((e61) =\u003e Math.abs(e61 - n10) \u003e 0.000000001))\n return n10;\n })(e54), { traceToSimplify: i8, leadingTerminalVias: r9, trailingTerminalVias: s7 } = ((e60) =\u003e {\n let t10 = 0;\n for (;e60.route[t10]?.route_type === \"via\"; )\n t10++;\n let n10 = e60.route.length;\n for (;e60.route[n10 - 1]?.route_type === \"jumper\"; )\n n10--;\n let o11 = n10;\n for (;o11 \u003e t10 \u0026\u0026 e60.route[o11 - 1]?.route_type === \"via\"; )\n o11--;\n return { traceToSimplify: { ...e60, route: [...e60.route.slice(t10, o11), ...e60.route.slice(n10)] }, leadingTerminalVias: e60.route.slice(0, t10), trailingTerminalVias: e60.route.slice(o11, n10) };\n })(e54), a9 = this.preparedInput.connMap.getNetConnectedToId(e54.connection_name) ?? e54.connection_name, c5 = o10 === undefined ? undefined : ((e60, t10) =\u003e {\n const n10 = [], o11 = [], i9 = [], r10 = ((e61, t11) =\u003e {\n for (const t12 of e61)\n if (t12.route_type === \"wire\" || t12.route_type === \"through_obstacle\")\n return t12.width;\n return t11;\n })(e60.route, t10.defaultTraceThickness);\n for (let s9 = 0;s9 \u003c e60.route.length; s9++) {\n const a10 = e60.route[s9];\n if (a10.route_type === \"jumper\") {\n i9.push(lle(a10));\n continue;\n }\n if (a10.route_type === \"wire\") {\n ile(n10, { x: a10.x, y: a10.y, z: mo(a10.layer, t10.layerCount), traceThickness: a10.width, pcb_port_id: a10.start_pcb_port_id ?? a10.end_pcb_port_id });\n continue;\n }\n const c9 = mo(a10.from_layer, t10.layerCount), l10 = mo(a10.to_layer, t10.layerCount), [h9, d9] = sle({ fromZ: c9, toZ: l10, previousZ: n10.at(-1)?.z, nextZ: rle(e60.route, s9, t10.layerCount) });\n if (a10.route_type === \"via\") {\n ile(n10, { x: a10.x, y: a10.y, z: h9, traceThickness: r10 }), ile(n10, { x: a10.x, y: a10.y, z: d9, traceThickness: r10 }), o11.push({ x: a10.x, y: a10.y });\n continue;\n }\n const u9 = h9 === c9, p9 = u9 ? a10.start : a10.end, m9 = u9 ? a10.end : a10.start;\n ile(n10, { ...p9, z: h9, traceThickness: a10.width, toNextSegmentType: \"through_obstacle\", ...a10.circuitJsonMetadata ? { toNextSegmentCircuitJsonMetadata: a10.circuitJsonMetadata } : {} }), ile(n10, { ...m9, z: d9, traceThickness: a10.width });\n }\n return { connectionName: e60.pcb_trace_id, rootConnectionName: t10.rootConnectionName, startPcbPortId: cle(e60.route, \"start\"), endPcbPortId: cle(e60.route, \"end\"), traceThickness: r10, viaDiameter: ale(e60.route, t10.defaultViaDiameter), route: n10, vias: o11, ...i9.length \u003e 0 ? { jumpers: i9 } : {} };\n })(i8, { layerCount: this.preparedInput.srj.layerCount, defaultTraceThickness: o10, defaultViaDiameter: n8.padDiameter, rootConnectionName: a9 }), l5 = c5 \u0026\u0026 c5.route.length \u003e= 2 ? c5 : undefined;\n if (this.preparedInput.preparedTraces.push({ originalTrace: e54, mutableHdRoute: l5, leadingTerminalVias: r9, trailingTerminalVias: s7, uniformTraceWidth: o10, viaHoleDiameter: hle(e54, n8.holeDiameter) }), !l5)\n return void this.preparedInput.immutableHdRoutes.push(...Vne(e54, t4, this.preparedInput.srj.layerCount, n8.padDiameter, this.preparedInput.connMap));\n this.preparedInput.mutableHdRoutes.push(l5), this.preparedInput.netByConnectionName.set(l5.connectionName, a9), this.preparedInput.colorMap[l5.connectionName] = this.preparedInput.colorMap[a9] ?? this.preparedInput.colorMap[e54.connection_name] ?? \"#2563eb\";\n const h5 = { ...e54, route: [...r9, ...s7] };\n this.preparedInput.immutableHdRoutes.push(...Vne(h5, t4, this.preparedInput.srj.layerCount, n8.padDiameter, this.preparedInput.connMap));\n }\n getOutput() {\n if (!this.solved)\n throw new Error(\"Cannot get prepared traces before preparation completes\");\n return this.preparedInput;\n }\n};\nvar ple = class extends BaseSolver {\n constructor(e54) {\n super(), this.inputProblem = e54;\n const t4 = e54.preparedInput, n8 = Yo(t4.srj);\n this.traceSimplificationSolver = new WF({ hdRoutes: t4.mutableHdRoutes, otherHdRoutes: t4.immutableHdRoutes, obstacles: t4.srj.obstacles, connMap: t4.connMap, colorMap: t4.colorMap, outline: t4.srj.outline, defaultViaDiameter: n8.padDiameter, layerCount: t4.srj.layerCount, minTraceToPadEdgeClearance: t4.srj.minTraceToPadEdgeClearance, minBoardEdgeClearance: t4.srj.minBoardEdgeClearance, netByConnectionName: t4.netByConnectionName, enableCrossingViaReduction: t4.options.enableCrossingViaReduction ?? true, preserveRouteEndpoints: true, useTraceWidthAwareClearance: true, enableVertexShortcuts: t4.options.enableVertexShortcuts ?? true }), this.traceSimplificationSolver.MAX_SIMPLIFICATION_PIPELINE_LOOPS = t4.options.iterations ?? 2, this.activeSubSolver = this.traceSimplificationSolver, this.MAX_ITERATIONS = this.traceSimplificationSolver.MAX_ITERATIONS + 1;\n }\n traceSimplificationSolver;\n getSolverName() {\n return \"TraceSimplificationStageSolver\";\n }\n _step() {\n if (this.traceSimplificationSolver.step(), this.progress = this.traceSimplificationSolver.progress, this.stats = { ...this.traceSimplificationSolver.stats }, this.traceSimplificationSolver.failed)\n return this.error = this.traceSimplificationSolver.error ?? \"Trace simplification failed\", this.failed = true, void (this.activeSubSolver = null);\n this.traceSimplificationSolver.solved \u0026\u0026 (this.progress = 1, this.solved = true, this.activeSubSolver = null);\n }\n getConstructorParams() {\n return [this.inputProblem];\n }\n getOutput() {\n if (!this.solved)\n throw new Error(\"Cannot get simplified routes before cleanup completes\");\n return structuredClone(this.traceSimplificationSolver.simplifiedHdRoutes);\n }\n visualize() {\n return this.traceSimplificationSolver.visualize();\n }\n preview() {\n return this.traceSimplificationSolver.preview();\n }\n};\nvar gle = class extends BaseSolver {\n constructor(e54) {\n super(), this.inputProblem = e54;\n const t4 = e54.preparedInput;\n this.drcEngine = new mb(t4.srj, { connMap: t4.connMap, traceClearance: t4.srj.minTraceToPadEdgeClearance ?? 0.1, viaClearance: 0.1, viaToPadClearance: vte(t4.originalSrj) }), this.MAX_ITERATIONS = 3;\n }\n drcEngine;\n phase = \"baseline\";\n baselineErrorCounts = {};\n outputErrorCounts = {};\n getSolverName() {\n return \"ValidateTraceSimplificationSolver\";\n }\n _step() {\n return this.phase === \"baseline\" ? (this.baselineErrorCounts = this.evaluateErrorCounts(this.inputProblem.preparedInput.originalSrj), this.phase = \"output\", void (this.progress = 1 / 3)) : this.phase === \"output\" ? (this.outputErrorCounts = this.evaluateErrorCounts(this.inputProblem.outputSrj), this.phase = \"compare\", void (this.progress = 2 / 3)) : (this.assertNoNewDrcErrors(), this.stats = { baselineErrorCounts: this.baselineErrorCounts, outputErrorCounts: this.outputErrorCounts }, this.progress = 1, void (this.solved = true));\n }\n evaluateErrorCounts(e54) {\n return ((e60) =\u003e {\n const t4 = {};\n for (const n8 of e60.errors)\n t4[n8.type] = (t4[n8.type] ?? 0) + 1;\n return t4;\n })(this.drcEngine.evaluate(e54.traces ?? []));\n }\n assertNoNewDrcErrors() {\n const e54 = [...new Set([...Object.keys(this.baselineErrorCounts), ...Object.keys(this.outputErrorCounts)])].filter((e60) =\u003e (this.outputErrorCounts[e60] ?? 0) \u003e (this.baselineErrorCounts[e60] ?? 0));\n if (e54.length === 0)\n return;\n const t4 = e54.map((e60) =\u003e `${e60}: ${this.baselineErrorCounts[e60] ?? 0} -\u003e ${this.outputErrorCounts[e60] ?? 0}`).join(\", \");\n throw new Error(`Pipeline 11 simplification introduced DRC errors (${t4})`);\n }\n getConstructorParams() {\n return [this.inputProblem];\n }\n getOutput() {\n if (!this.solved)\n throw new Error(\"Cannot get Pipeline 11 output before DRC validation\");\n return structuredClone(this.inputProblem.outputSrj);\n }\n};\nvar fle = class extends BasePipelineSolver {\n prepareTraceSimplificationSolver;\n traceSimplificationStageSolver;\n applyTraceSimplificationSolver;\n validateTraceSimplificationSolver;\n pipelineDef = [definePipelineStep(\"prepareTraceSimplificationSolver\", dle, (e54) =\u003e [{ inputSrj: e54.inputProblem.inputSrj, options: e54.inputProblem.options }]), definePipelineStep(\"traceSimplificationStageSolver\", ple, (e54) =\u003e [{ preparedInput: e54.prepareTraceSimplificationSolver.getOutput() }]), definePipelineStep(\"applyTraceSimplificationSolver\", nle, (e54) =\u003e [{ preparedInput: e54.prepareTraceSimplificationSolver.getOutput(), simplifiedHdRoutes: e54.traceSimplificationStageSolver.getOutput() }]), definePipelineStep(\"validateTraceSimplificationSolver\", gle, (e54) =\u003e [{ preparedInput: e54.prepareTraceSimplificationSolver.getOutput(), outputSrj: e54.applyTraceSimplificationSolver.getOutput() }])];\n constructor(e54, t4 = {}) {\n if (t4.iterations !== undefined \u0026\u0026 (!Number.isInteger(t4.iterations) || t4.iterations \u003c 1))\n throw new Error(\"Simplification iterations must be a positive integer\");\n super({ inputSrj: e54, options: { ...t4 } }), this.MAX_ITERATIONS = 1e8;\n }\n getSolverName() {\n return \"AutoroutingPipelineSolver11_Simplification\";\n }\n getConstructorParams() {\n return [this.inputProblem.inputSrj, this.inputProblem.options];\n }\n getOutput() {\n if (!this.validateTraceSimplificationSolver?.solved)\n throw new Error(\"Pipeline 11 simplification has not solved yet\");\n return this.validateTraceSimplificationSolver.getOutput();\n }\n getOutputSimpleRouteJson() {\n return this.getOutput();\n }\n getOutputSimplifiedPcbTraces() {\n return structuredClone(this.getOutput().traces ?? []);\n }\n initialVisualize() {\n return Wo(this.inputProblem.inputSrj);\n }\n finalVisualize() {\n return Wo(this.getOutput());\n }\n};\nvar _le = class extends lj {\n constructor(e54, t4 = {}) {\n super(e54, t4), this.srj = e54, this.opts = t4;\n }\n MAX_SIZE_FOR_SINGLE_LAYER_NODES = 2;\n isObstacleAssignable(e54) {\n return Boolean(e54?.netIsAssignable);\n }\n getOverlappingAssignableObstacles(e54) {\n return this.getXYZOverlappingObstacles(e54).filter((e60) =\u003e this.isObstacleAssignable(e60));\n }\n shouldNodeBeXYSubdivided(e54) {\n return !(e54._depth \u003e= this.MAX_DEPTH) \u0026\u0026 (!!e54._containsTarget || (!(!e54._containsObstacle || e54._completelyInsideObstacle) || e54.availableZ.length === 1 \u0026\u0026 (e54.width \u003e this.MAX_SIZE_FOR_SINGLE_LAYER_NODES || e54.height \u003e this.MAX_SIZE_FOR_SINGLE_LAYER_NODES)));\n }\n shouldFilterNodeForObstacle(e54) {\n if (!e54._containsObstacle)\n return false;\n return !(this.getOverlappingAssignableObstacles(e54).length \u003e 0) \u0026\u0026 (e54.availableZ.length !== 1 || this.shouldFilterSingleLayerNodeForObstacle(e54));\n }\n insertAssignableObstaclesAsNodes() {\n const e54 = this.srj.obstacles.filter((e60) =\u003e this.isObstacleAssignable(e60)), t4 = new Map;\n for (const n10 of e54) {\n const e60 = [];\n for (const t10 of this.finishedNodes) {\n this.getXYZOverlappingObstacles(t10).some((e61) =\u003e e61 === n10) \u0026\u0026 e60.push(t10);\n }\n t4.set(n10, e60);\n }\n const n8 = new Set;\n for (const e60 of t4.values())\n for (const t10 of e60)\n n8.add(t10);\n this.finishedNodes = this.finishedNodes.filter((e60) =\u003e !n8.has(e60));\n for (const n10 of e54) {\n const e60 = t4.get(n10) || [], o10 = n10.layers \u0026\u0026 n10.layers.length \u003e 0 ? Array.from(new Set(n10.layers.map((e61) =\u003e mo(e61, this.srj.layerCount)))).sort((e61, t10) =\u003e e61 - t10) : Array.from({ length: this.srj.layerCount }, (e61, t10) =\u003e this.srj.layerCount - t10 - 1);\n let i8 = n10.center.x - n10.width / 2, r9 = n10.center.x + n10.width / 2, s7 = n10.center.y - n10.height / 2, a9 = n10.center.y + n10.height / 2;\n for (const t10 of e60) {\n const e61 = t10.center.x - t10.width / 2, n11 = t10.center.x + t10.width / 2, o11 = t10.center.y - t10.height / 2, c9 = t10.center.y + t10.height / 2;\n i8 = Math.min(i8, e61), r9 = Math.max(r9, n11), s7 = Math.min(s7, o11), a9 = Math.max(a9, c9);\n }\n const c5 = r9 - i8, l5 = a9 - s7, h5 = (i8 + r9) / 2, d9 = (s7 + a9) / 2;\n let u9 = false;\n for (const e61 of this.srj.connections) {\n for (const t10 of e61.pointsToConnect)\n if (t10.x \u003e= i8 \u0026\u0026 t10.x \u003c= r9 \u0026\u0026 t10.y \u003e= s7 \u0026\u0026 t10.y \u003c= a9) {\n u9 = true;\n break;\n }\n if (u9)\n break;\n }\n const p9 = { capacityMeshNodeId: `assignable_via_${n10.center.x}_${n10.center.y}`, center: { x: h5, y: d9 }, width: c5, height: l5, layer: o10.length === 1 ? `z${o10[0]}` : `z${o10.join(\",\")}`, availableZ: o10, _depth: 0, _containsTarget: u9, _containsObstacle: false, _completelyInsideObstacle: false };\n p9._assignedViaObstacle = n10, this.finishedNodes.push(p9);\n }\n }\n _step() {\n const e54 = this.unfinishedNodes.pop();\n if (!e54)\n return this.insertAssignableObstaclesAsNodes(), void (this.solved = true);\n const t4 = this.getChildNodes(e54), n8 = [], o10 = [];\n for (const e60 of t4) {\n const t10 = this.shouldNodeBeXYSubdivided(e60), i8 = e60.availableZ.length \u003e 1 \u0026\u0026 !t10;\n if (t10)\n o10.push(e60);\n else {\n if (i8) {\n const t11 = this.getZSubdivisionChildNodes(e60);\n for (const e61 of t11)\n !e61._containsTarget \u0026\u0026 this.shouldFilterNodeForObstacle(e61) || (this.shouldNodeBeXYSubdivided(e61) ? o10.push(e61) : (e61._containsObstacle = false, n8.push(e61)));\n continue;\n }\n this.shouldFilterNodeForObstacle(e60) \u0026\u0026 !e60._containsTarget || n8.push(e60);\n }\n }\n this.unfinishedNodes.push(...o10), this.finishedNodes.push(...n8);\n }\n};\nvar yle = 0.005;\nvar ble = class extends ni {\n getSolverName() {\n return \"SingleLayerNodeMergerSolver_OnlyMergeTargets\";\n }\n nodeMap;\n currentBatchNodeIds;\n absorbedNodeIds;\n nextBatchNodeIds;\n batchHadModifications;\n hasComputedAdjacentNodeIds = false;\n newNodes;\n constructor(e54) {\n super(), this.nodeMap = new Map, this.MAX_ITERATIONS = 1e5;\n for (const t10 of e54)\n this.nodeMap.set(t10.capacityMeshNodeId, t10);\n this.newNodes = [], this.absorbedNodeIds = new Set;\n const t4 = [];\n for (const n8 of e54)\n n8._assignedViaObstacle ? (this.newNodes.push(n8), this.absorbedNodeIds.add(n8.capacityMeshNodeId)) : n8._containsTarget ? n8.availableZ.length \u003e 1 ? (this.newNodes.push(n8), this.absorbedNodeIds.add(n8.capacityMeshNodeId)) : t4.push([n8, n8.width * n8.height]) : (this.newNodes.push(n8), this.absorbedNodeIds.add(n8.capacityMeshNodeId));\n t4.sort((e60, t10) =\u003e e60[1] - t10[1]);\n for (const [e60, n8] of t4) {\n const t10 = { ...e60, center: { ...e60.center } };\n this.nodeMap.set(e60.capacityMeshNodeId, t10);\n }\n this.currentBatchNodeIds = t4.map(([e60]) =\u003e e60.capacityMeshNodeId), this.nextBatchNodeIds = [], this.batchHadModifications = false;\n }\n computeAdjacentNodeIdsForFirstBatch(e54) {\n const t4 = Math.max(...e54.map((e60) =\u003e Math.max(...e60.availableZ))), n8 = [];\n for (let o10 = 0;o10 \u003c= t4; o10++)\n n8.push(new di(e54.filter((e60) =\u003e e60.availableZ[0] === o10)));\n for (const t10 of e54) {\n const e60 = [], o10 = n8[t10.availableZ[0]].getNodesInArea(t10.center.x, t10.center.y, 4 * t10.width, 4 * t10.height);\n for (const n10 of o10)\n n10._containsTarget \u0026\u0026 n10._targetConnectionName !== t10._targetConnectionName || t10._containsTarget \u0026\u0026 (!n10._containsTarget || n10._targetConnectionName !== t10._targetConnectionName) || n10.capacityMeshNodeId !== t10.capacityMeshNodeId \u0026\u0026 ri(t10, n10) \u0026\u0026 e60.push(n10);\n t10._adjacentNodeIds = e60.map((e61) =\u003e e61.capacityMeshNodeId);\n }\n }\n getAdjacentSameLayerUnprocessedNodes(e54) {\n const t4 = [], n8 = Array.from(new Set((e54._adjacentNodeIds ?? []).map((e60) =\u003e this.nodeMap.get(e60)))).filter((t10) =\u003e t10 \u0026\u0026 t10.capacityMeshNodeId !== e54.capacityMeshNodeId);\n n8.sort((e60, t10) =\u003e e60.width * e60.height - t10.width * t10.height);\n for (const e60 of n8)\n this.absorbedNodeIds.has(e60.capacityMeshNodeId) || t4.push(e60);\n return t4;\n }\n _step() {\n this.hasComputedAdjacentNodeIds || (this.computeAdjacentNodeIdsForFirstBatch(this.currentBatchNodeIds.map((e60) =\u003e this.nodeMap.get(e60))), this.hasComputedAdjacentNodeIds = true);\n let e54 = this.currentBatchNodeIds.pop();\n for (;e54 \u0026\u0026 this.absorbedNodeIds.has(e54); )\n e54 = this.currentBatchNodeIds.pop();\n if (!e54)\n return this.batchHadModifications ? (this.currentBatchNodeIds = this.nextBatchNodeIds.sort((e60, t10) =\u003e {\n const n10 = this.nodeMap.get(e60), o11 = this.nodeMap.get(t10);\n return n10.width * n10.height - o11.width * o11.height;\n }), this.nextBatchNodeIds = [], void (this.batchHadModifications = false)) : (this.solved = true, void this.newNodes.push(...this.nextBatchNodeIds.map((e60) =\u003e this.nodeMap.get(e60))));\n const t4 = this.nodeMap.get(e54);\n let n8 = false;\n const o10 = this.getAdjacentSameLayerUnprocessedNodes(t4);\n if (o10.length === 0)\n return void this.nextBatchNodeIds.push(e54);\n const i8 = (e60) =\u003e {\n for (const t10 of e60)\n this.absorbedNodeIds.add(t10.capacityMeshNodeId);\n t4._adjacentNodeIds = Array.from(new Set([...t4._adjacentNodeIds ?? [], ...e60.flatMap((e61) =\u003e e61._adjacentNodeIds ?? [])].filter((e61) =\u003e e61 !== t4.capacityMeshNodeId \u0026\u0026 !this.absorbedNodeIds.has(e61))));\n }, r9 = o10.filter((e60) =\u003e e60.center.x \u003c t4.center.x \u0026\u0026 Math.abs(e60.center.y - t4.center.y) \u003c t4.height / 2);\n if (r9.length \u003e 0) {\n const { width: e60, height: o11 } = r9[0], s9 = r9.every((t10) =\u003e t10.width === e60 \u0026\u0026 t10.height === o11);\n Math.abs(r9.reduce((e61, t10) =\u003e e61 + t10.height, 0) - t4.height) \u003c yle \u0026\u0026 s9 \u0026\u0026 (t4.width += e60, t4.center.x = t4.center.x - e60 / 2, i8(r9), n8 = true);\n }\n const s7 = o10.filter((e60) =\u003e e60.center.x \u003e t4.center.x \u0026\u0026 Math.abs(e60.center.y - t4.center.y) \u003c t4.height / 2);\n if (s7.length \u003e 0 \u0026\u0026 !n8) {\n const { width: e60, height: o11 } = s7[0], r10 = s7.every((t10) =\u003e t10.width === e60 \u0026\u0026 t10.height === o11);\n Math.abs(s7.reduce((e61, t10) =\u003e e61 + t10.height, 0) - t4.height) \u003c yle \u0026\u0026 r10 \u0026\u0026 (t4.width += e60, t4.center.x = t4.center.x + e60 / 2, i8(s7), n8 = true);\n }\n const a9 = o10.filter((e60) =\u003e e60.center.y \u003e t4.center.y \u0026\u0026 Math.abs(e60.center.x - t4.center.x) \u003c t4.width / 2);\n if (a9.length \u003e 0 \u0026\u0026 !n8) {\n const { width: e60, height: o11 } = a9[0], r10 = a9.every((t10) =\u003e t10.width === e60 \u0026\u0026 t10.height === o11);\n Math.abs(a9.reduce((e61, t10) =\u003e e61 + t10.width, 0) - t4.width) \u003c yle \u0026\u0026 r10 \u0026\u0026 (t4.height += o11, t4.center.y = t4.center.y + o11 / 2, i8(a9), n8 = true);\n }\n const c5 = o10.filter((e60) =\u003e e60.center.y \u003c t4.center.y \u0026\u0026 Math.abs(e60.center.x - t4.center.x) \u003c t4.width / 2);\n if (c5.length \u003e 0 \u0026\u0026 !n8) {\n const { width: e60, height: o11 } = c5[0], r10 = c5.every((t10) =\u003e t10.width === e60 \u0026\u0026 t10.height === o11);\n Math.abs(c5.reduce((e61, t10) =\u003e e61 + t10.width, 0) - t4.width) \u003c yle \u0026\u0026 r10 \u0026\u0026 (t4.height += o11, t4.center.y = t4.center.y - o11 / 2, i8(c5), n8 = true);\n }\n n8 ? (this.batchHadModifications = true, this.currentBatchNodeIds.push(e54)) : this.nextBatchNodeIds.unshift(e54);\n }\n visualize() {\n const e54 = { circles: [], lines: [], points: [], rects: [], coordinateSystem: \"cartesian\", title: \"Single Layer Node Merger (Only Merge Targets)\" };\n for (const t10 of this.newNodes)\n e54.rects.push(dj(t10));\n const t4 = this.currentBatchNodeIds[this.currentBatchNodeIds.length - 1];\n let n8;\n t4 \u0026\u0026 (n8 = this.getAdjacentSameLayerUnprocessedNodes(this.nodeMap.get(t4)));\n for (const o10 of this.currentBatchNodeIds) {\n const i8 = this.nodeMap.get(o10);\n if (!this.absorbedNodeIds.has(o10) \u0026\u0026 i8) {\n const r9 = dj(i8, { rectMargin: 0.01 });\n o10 === t4 ? r9.stroke = \"rgba(0, 255, 0, 0.8)\" : n8?.some((e60) =\u003e e60.capacityMeshNodeId === o10) ? r9.stroke = \"rgba(128, 0, 128, 0.8)\" : r9.stroke = \"rgba(255, 165, 0, 0.8)\", r9.layer = `z${i8.availableZ.join(\",\")}`, r9.label = `${r9.label}\n(unprocessed)`, e54.rects.push(r9);\n }\n }\n for (const t10 of this.nextBatchNodeIds) {\n const n10 = this.nodeMap.get(t10);\n if (!this.absorbedNodeIds.has(t10) \u0026\u0026 n10) {\n const t11 = dj(n10, { rectMargin: 0.01 });\n t11.layer = `z${n10.availableZ.join(\",\")}`, t11.stroke = \"rgba(0, 217, 255, 0.8)\", t11.label = `${t11.label}\nx: ${n10.center.x}, y: ${n10.center.y}\n${n10.width}x${n10.height}\n(next batch)`, e54.rects.push(t11);\n }\n }\n return e54;\n }\n};\nvar xle = class extends ni {\n getSolverName() {\n return \"AssignableViaNodeMergerSolver\";\n }\n newNodes;\n obstacleToNodesMap;\n obstaclesToProcess;\n mergedNodeIds;\n constructor(e54) {\n super(), this.MAX_ITERATIONS = 1e4, this.newNodes = [], this.obstacleToNodesMap = new Map, this.mergedNodeIds = new Set;\n for (const t4 of e54) {\n const e60 = t4._assignedViaObstacle;\n if (e60) {\n const n8 = this.obstacleToNodesMap.get(e60) || [];\n n8.push(t4), this.obstacleToNodesMap.set(e60, n8);\n } else\n this.newNodes.push(t4);\n }\n this.obstaclesToProcess = Array.from(this.obstacleToNodesMap.keys());\n }\n _step() {\n const e54 = this.obstaclesToProcess.pop();\n if (!e54)\n return void (this.solved = true);\n const t4 = this.obstacleToNodesMap.get(e54);\n if (!t4 || t4.length === 0)\n return;\n let { POSITIVE_INFINITY: n8, NEGATIVE_INFINITY: o10, POSITIVE_INFINITY: i8, NEGATIVE_INFINITY: r9 } = Number;\n const s7 = new Set;\n let a9 = false;\n for (const e60 of t4) {\n const t10 = e60.center.x - e60.width / 2, c9 = e60.center.x + e60.width / 2, l10 = e60.center.y - e60.height / 2, h9 = e60.center.y + e60.height / 2;\n n8 = Math.min(n8, t10), o10 = Math.max(o10, c9), i8 = Math.min(i8, l10), r9 = Math.max(r9, h9);\n for (const t11 of e60.availableZ)\n s7.add(t11);\n e60._containsTarget \u0026\u0026 (a9 = true);\n }\n const c5 = o10 - n8, l5 = r9 - i8, h5 = (n8 + o10) / 2, d9 = (i8 + r9) / 2, u9 = Array.from(s7).sort((e60, t10) =\u003e e60 - t10), p9 = { capacityMeshNodeId: `merged_via_${e54.center.x}_${e54.center.y}`, center: { x: h5, y: d9 }, width: c5, height: l5, layer: u9.length === 1 ? `z${u9[0]}` : `z${u9.join(\",\")}`, availableZ: u9, _containsTarget: a9, _containsObstacle: false, _completelyInsideObstacle: false };\n p9._assignedViaObstacle = e54;\n for (const e60 of t4)\n this.mergedNodeIds.add(e60.capacityMeshNodeId);\n this.newNodes.push(p9);\n }\n visualize() {\n const e54 = { circles: [], lines: [], points: [], rects: [], coordinateSystem: \"cartesian\", title: \"Assignable Via Node Merger\" };\n for (const t10 of this.newNodes) {\n const n8 = dj(t10);\n t10._assignedViaObstacle \u0026\u0026 (n8.stroke = \"rgba(255, 0, 255, 0.8)\", n8.label = `${n8.label || \"\"}\n(merged via)`), e54.rects.push(n8);\n }\n const t4 = this.obstaclesToProcess[this.obstaclesToProcess.length - 1];\n if (t4) {\n const n8 = this.obstacleToNodesMap.get(t4) || [];\n for (const t10 of n8) {\n const n10 = dj(t10, { rectMargin: 0.01 });\n n10.stroke = \"rgba(0, 255, 0, 0.8)\", n10.label = `${n10.label || \"\"}\n(to be merged)`, e54.rects.push(n10);\n }\n }\n return e54;\n }\n};\nvar vle = class extends ni {\n constructor(e54) {\n const { simpleRouteJson: t4, nodes: n8, edges: o10, colorMap: i8, MAX_ITERATIONS: r9 = 1e6, hyperParameters: s7 = {} } = e54;\n super(), this.inputParams = e54, this.hyperParameters = s7, this.MAX_ITERATIONS = r9, this.simpleRouteJson = t4, this.nodes = n8, this.edges = o10, this.colorMap = i8 ?? {}, this.nodeMap = new Map(this.nodes.map((e60) =\u003e [e60.capacityMeshNodeId, e60])), this.nodeEdgeMap = oi(this.edges);\n const a9 = this.nodes.filter((e60) =\u003e e60._containsTarget);\n this.unprocessedConnectionPairs = Sr(this.simpleRouteJson.connections.map((e60) =\u003e {\n const [t10, n10] = e60.pointsToConnect;\n return { start: a9.find((e61) =\u003e me(e61.center, t10) \u003c e61.width / 2), end: a9.find((e61) =\u003e me(e61.center, n10) \u003c e61.width / 2), connection: e60 };\n }), this.hyperParameters.SHUFFLE_SEED ?? 0), this.viaNodes = this.nodes.filter((e60) =\u003e e60.availableZ.length \u003e 1);\n }\n getSolverName() {\n return \"AssignableViaCapacityPathingSolver_DirectiveSubOptimal\";\n }\n GREEDY_MULTIPLIER = 1.5;\n simpleRouteJson;\n nodes;\n edges;\n colorMap;\n MAX_ITERATIONS;\n hyperParameters;\n usedNodeMap = new Map;\n nodeMap;\n nodeEdgeMap;\n unprocessedConnectionPairs;\n solvedRoutes = [];\n activeConnectionPair = null;\n ogUnprocessedSubpaths = null;\n unprocessedSubpaths = null;\n solvedSubpaths = null;\n activeSubpath = null;\n viaNodes = [];\n closestViaForConnectionStartMap = new Map;\n closestViaForConnectionEndMap = new Map;\n getConstructorParams() {\n return this.inputParams;\n }\n lastStepOperation = \"none\";\n computeClosestViaForAllConnections() {\n this.closestViaForConnectionStartMap.clear(), this.closestViaForConnectionEndMap.clear();\n for (const e54 of this.unprocessedConnectionPairs) {\n const t4 = this.viaNodes.filter((e60) =\u003e !e60._completelyInsideObstacle \u0026\u0026 !e60._containsObstacle).filter((e60) =\u003e !this.usedNodeMap.has(e60.capacityMeshNodeId));\n if (t4.length \u003e 0) {\n const n8 = t4.reduce((t10, n10) =\u003e {\n const o11 = this._dist(t10, e54.start);\n return this._dist(n10, e54.start) \u003c o11 ? n10 : t10;\n });\n this.closestViaForConnectionStartMap.set(e54, n8);\n const o10 = t4.reduce((t10, n10) =\u003e {\n const o11 = this._dist(t10, e54.end);\n return this._dist(n10, e54.end) \u003c o11 ? n10 : t10;\n });\n this.closestViaForConnectionEndMap.set(e54, o10);\n }\n }\n }\n _step() {\n if (!this.activeConnectionPair)\n return this.activeConnectionPair = this.unprocessedConnectionPairs.shift(), this.activeConnectionPair ? (this.computeClosestViaForAllConnections(), void (this.lastStepOperation = \"dequeueConnectionPair\")) : void (this.solved = true);\n if (this.activeConnectionPair \u0026\u0026 !this.unprocessedSubpaths)\n return this.unprocessedSubpaths = this.breakConnectionPairIntoSubpaths(this.activeConnectionPair), this.ogUnprocessedSubpaths = this.unprocessedSubpaths.slice(), this.solvedSubpaths = [], void (this.lastStepOperation = \"breakConnectionPairIntoSubpaths\");\n if (this.activeSubpath) {\n if (this.activeSubpath \u0026\u0026 (this.stepSolveSubpath(this.activeSubpath), this.activeSubpath.solved))\n return this.solvedSubpaths.push(this.activeSubpath), this.activeSubpath = null, this.clearCandidateNodes(), void (this.lastStepOperation = \"finishedSolvingSubpath\");\n this.lastStepOperation = \"stepSolveSubpath\";\n } else {\n if (this.activeSubpath = this.unprocessedSubpaths.shift(), !this.activeSubpath) {\n const e54 = this.activeConnectionPair;\n return this.activeConnectionPair = null, this.unprocessedSubpaths = null, this.ogUnprocessedSubpaths = null, this.activeSubpath = null, this.solvedRoutes.push(this.createSolvedRoute(this.solvedSubpaths, e54)), void (this.lastStepOperation = \"finishedSolvingConnectionPair\");\n }\n this.lastStepOperation = \"dequeueSubpath\";\n }\n }\n queuedCandidateNodes = [];\n visitedNodes = new Set;\n _dist(e54, t4) {\n return Math.hypot(e54.center.x - t4.center.x, e54.center.y - t4.center.y);\n }\n stepSolveSubpath(e54) {\n const { start: t4, end: n8 } = e54;\n if (t4.capacityMeshNodeId === n8.capacityMeshNodeId)\n return e54.path = [t4], e54.solved = true, void this.usedNodeMap.set(t4.capacityMeshNodeId, true);\n if (this.queuedCandidateNodes.length === 0 \u0026\u0026 this.visitedNodes.size === 0) {\n const e60 = this._dist(t4, n8), o11 = { prevCandidate: null, node: t4, g: 0, h: e60, f: this.GREEDY_MULTIPLIER * e60 };\n this.queuedCandidateNodes.push(o11);\n }\n let o10;\n for (this.queuedCandidateNodes.sort((e60, t10) =\u003e e60.f - t10.f);this.queuedCandidateNodes.length \u0026\u0026 !o10; ) {\n const e60 = this.queuedCandidateNodes.shift();\n this.visitedNodes.has(e60.node.capacityMeshNodeId) || (o10 = e60);\n }\n if (!o10)\n return this.failed = true, void (this.error = \"No viable candidates left\");\n if (this.visitedNodes.add(o10.node.capacityMeshNodeId), o10.node.capacityMeshNodeId === n8.capacityMeshNodeId) {\n const t10 = [];\n let n10 = o10;\n for (;n10; )\n t10.unshift(n10.node), this.usedNodeMap.set(n10.node.capacityMeshNodeId, true), n10 = n10.prevCandidate;\n return e54.path = t10, void (e54.solved = true);\n }\n const i8 = this.getNeighbors(o10.node);\n for (const e60 of i8) {\n const t10 = e60.capacityMeshNodeId;\n if (this.visitedNodes.has(t10))\n continue;\n const i9 = this.computeG(o10, e60, n8), r9 = this.computeH(o10, e60, n8), s7 = i9 + this.GREEDY_MULTIPLIER * r9, a9 = this.queuedCandidateNodes.findIndex((e61) =\u003e e61.node.capacityMeshNodeId === t10);\n if (a9 \u003e= 0) {\n if (this.queuedCandidateNodes[a9].g \u003c= i9)\n continue;\n this.queuedCandidateNodes.splice(a9, 1);\n }\n this.queuedCandidateNodes.push({ prevCandidate: o10, node: e60, g: i9, h: r9, f: s7 });\n }\n }\n getNeighbors(e54) {\n const t4 = new Set, n8 = this.nodeEdgeMap.get(e54.capacityMeshNodeId) ?? [];\n for (const o11 of n8) {\n const [n10, i8] = o11.nodeIds, r9 = n10 === e54.capacityMeshNodeId ? i8 : n10, s7 = this.nodeMap.get(r9);\n s7 \u0026\u0026 t4.add(s7);\n }\n const o10 = this.activeSubpath?.layer;\n return Array.from(t4).filter((e60) =\u003e !(e60.capacityMeshNodeId !== this.activeSubpath?.end.capacityMeshNodeId) || !e60._containsObstacle \u0026\u0026 (!e60._containsTarget \u0026\u0026 (!this.usedNodeMap.has(e60.capacityMeshNodeId) \u0026\u0026 !(o10 !== undefined \u0026\u0026 !e60.availableZ.includes(o10)))));\n }\n clearCandidateNodes() {\n this.queuedCandidateNodes = [], this.visitedNodes = new Set;\n }\n computeG(e54, t4, n8) {\n const o10 = this._dist(e54.node, t4);\n return e54.g + o10;\n }\n computeH(e54, t4, n8) {\n return this._dist(t4, n8);\n }\n createSolvedRoute(e54, t4) {\n const n8 = [];\n for (let t10 = 0;t10 \u003c e54.length; t10++) {\n const o10 = e54[t10];\n o10.path ? t10 === 0 ? n8.push(...o10.path) : n8.push(...o10.path.slice(1)) : (t10 === 0 \u0026\u0026 n8.push(o10.start), t10 === e54.length - 1 \u0026\u0026 n8.push(o10.end));\n }\n return { connection: t4.connection, path: n8 };\n }\n breakConnectionPairIntoSubpaths(e54) {\n var t4, n8;\n if (!(t4 = [this.hyperParameters.DIRECTIVE_SEED ?? 0, this.solvedRoutes.length], n8 = this.hyperParameters.FORCE_VIA_TRAVEL_CHANCE ?? 0, vr(t4.reduce((e60, t10) =\u003e e60 + 16807 * t10 % 2147483647, 0))() \u003c n8))\n return [{ start: e54.start, end: e54.end, solved: false, layer: e54.start.availableZ[0] ?? 0 }];\n const o10 = this.getClosestVia(e54.start), i8 = this.getFarVia(o10, e54.end), r9 = e54.start.availableZ[0] ?? 0, s7 = e54.end.availableZ[0] ?? 0, a9 = [];\n return a9.push({ start: e54.start, end: o10, solved: false, layer: r9 }), r9 === s7 ? (a9.push({ start: o10, end: i8, solved: false, layer: r9 === 0 ? 1 : 0 }), a9.push({ start: i8, end: e54.end, solved: false, layer: s7 })) : a9.push({ start: o10, end: e54.end, solved: false, layer: s7 }), a9;\n }\n getClosestVia(e54) {\n if (this.viaNodes.length === 0)\n return e54;\n const t4 = new Set;\n for (const [e60, n10] of this.closestViaForConnectionStartMap)\n e60 !== this.activeConnectionPair \u0026\u0026 t4.add(n10.capacityMeshNodeId);\n for (const [e60, n10] of this.closestViaForConnectionEndMap)\n e60 !== this.activeConnectionPair \u0026\u0026 t4.add(n10.capacityMeshNodeId);\n const n8 = this.viaNodes.filter((e60) =\u003e !e60._completelyInsideObstacle \u0026\u0026 !e60._containsObstacle).filter((e60) =\u003e !this.usedNodeMap.has(e60.capacityMeshNodeId)).filter((e60) =\u003e !t4.has(e60.capacityMeshNodeId));\n if (n8.length === 0) {\n const t10 = this.viaNodes.filter((e60) =\u003e !e60._completelyInsideObstacle \u0026\u0026 !e60._containsObstacle).filter((e60) =\u003e !this.usedNodeMap.has(e60.capacityMeshNodeId));\n return t10.length === 0 ? e54 : (t10.sort((t11, n10) =\u003e this._dist(t11, e54) - this._dist(n10, e54)), t10[0]);\n }\n n8.sort((t10, n10) =\u003e this._dist(t10, e54) - this._dist(n10, e54));\n const o10 = this.hyperParameters.MAX_CLOSEST_VIA_SKIP ?? 0;\n if (o10 \u003e 0 \u0026\u0026 n8.length \u003e 1) {\n const e60 = vr((this.hyperParameters.DIRECTIVE_SEED ?? 0) + this.solvedRoutes.length), t10 = Math.floor(e60() * (o10 + 1));\n return n8[Math.min(t10, n8.length - 1)];\n }\n return n8[0];\n }\n getFarVia(e54, t4) {\n if (this.viaNodes.length === 0)\n return e54;\n const n8 = this.hyperParameters.FAR_VIA_MIN_DISTANCE != null ? this.hyperParameters.FAR_VIA_MIN_DISTANCE : 50, o10 = new Set;\n for (const [e60, t10] of this.closestViaForConnectionStartMap)\n e60 !== this.activeConnectionPair \u0026\u0026 o10.add(t10.capacityMeshNodeId);\n for (const [e60, t10] of this.closestViaForConnectionEndMap)\n e60 !== this.activeConnectionPair \u0026\u0026 o10.add(t10.capacityMeshNodeId);\n const i8 = this.viaNodes.filter((t10) =\u003e !this.usedNodeMap.has(t10.capacityMeshNodeId) \u0026\u0026 t10.capacityMeshNodeId !== e54.capacityMeshNodeId \u0026\u0026 !t10._completelyInsideObstacle \u0026\u0026 !t10._containsObstacle \u0026\u0026 !o10.has(t10.capacityMeshNodeId) \u0026\u0026 this._dist(t10, e54) \u003e= n8);\n if (i8.length === 0) {\n const o11 = this.viaNodes.filter((t10) =\u003e t10.capacityMeshNodeId !== e54.capacityMeshNodeId \u0026\u0026 !t10._completelyInsideObstacle \u0026\u0026 !t10._containsObstacle \u0026\u0026 !this.usedNodeMap.has(t10.capacityMeshNodeId) \u0026\u0026 this._dist(t10, e54) \u003e= n8).sort((e60, n10) =\u003e this._dist(e60, t4) - this._dist(n10, t4));\n if (o11.length \u003e 0)\n return o11[0];\n return this.viaNodes.filter((t10) =\u003e t10.capacityMeshNodeId !== e54.capacityMeshNodeId \u0026\u0026 !t10._completelyInsideObstacle \u0026\u0026 !t10._containsObstacle \u0026\u0026 !this.usedNodeMap.has(t10.capacityMeshNodeId)).sort((e60, n10) =\u003e this._dist(e60, t4) - this._dist(n10, t4))[0] ?? e54;\n }\n i8.sort((e60, n10) =\u003e this._dist(e60, t4) - this._dist(n10, t4));\n const r9 = this.hyperParameters.MAX_FURTHEST_VIA_SKIP ?? 0;\n if (r9 \u003e 0 \u0026\u0026 i8.length \u003e 1) {\n const e60 = vr((this.hyperParameters.DIRECTIVE_SEED ?? 0) + this.solvedRoutes.length + 1000), t10 = Math.floor(e60() * (r9 + 1));\n return i8[Math.min(t10, i8.length - 1)];\n }\n return i8[0];\n }\n getCapacityPaths() {\n const e54 = [];\n for (const t4 of this.solvedRoutes) {\n const n8 = t4.path;\n n8 \u0026\u0026 n8.length \u003e 0 \u0026\u0026 e54.push({ capacityPathId: t4.connection.name, connectionName: t4.connection.name, nodeIds: n8.map((e60) =\u003e e60.capacityMeshNodeId) });\n }\n return e54;\n }\n visualize() {\n const e54 = { lines: [], points: [], rects: [], circles: [] }, t4 = (e60) =\u003e !!e60 \u0026\u0026 typeof e60.x == \"number\" \u0026\u0026 typeof e60.y == \"number\" \u0026\u0026 !Number.isNaN(e60.x) \u0026\u0026 !Number.isNaN(e60.y) \u0026\u0026 Number.isFinite(e60.x) \u0026\u0026 Number.isFinite(e60.y), n8 = (e60) =\u003e typeof e60 == \"number\" \u0026\u0026 !Number.isNaN(e60) \u0026\u0026 Number.isFinite(e60);\n for (const o11 of this.nodes) {\n const i8 = this.queuedCandidateNodes.some((e60) =\u003e e60.node.capacityMeshNodeId === o11.capacityMeshNodeId), r9 = this.queuedCandidateNodes.find((e60) =\u003e e60.node.capacityMeshNodeId === o11.capacityMeshNodeId);\n if (t4(o11.center) \u0026\u0026 n8(o11.width) \u0026\u0026 n8(o11.height)) {\n const t10 = dj(o11, { rectMargin: 0.025, zOffset: 0.01 });\n e54.rects.push({ ...t10, fill: i8 ? \"rgba(255, 128, 255, 0.5)\" : o11._containsTarget ? \"rgba(0, 150, 255, 0.15)\" : o11._containsObstacle ? \"rgba(255, 0, 0, 0.1)\" : \"rgba(200, 200, 200, 0.05)\", label: [`ID: ${o11.capacityMeshNodeId}`, `Size: ${o11.width.toFixed(2)}x${o11.height.toFixed(2)}`, `Z: ${o11.availableZ.join(\", \")}`, r9 ? `g: ${r9.g.toFixed(2)}` : \"\", r9 ? `h: ${r9.h.toFixed(2)}` : \"\", r9 ? `f: ${r9.f.toFixed(2)}` : \"\", o11._containsTarget ? \"TARGET\" : \"\", o11._containsObstacle ? \"OBSTACLE\" : \"\"].filter((e60) =\u003e e60).join(`\n`) });\n }\n }\n for (const n10 of this.edges) {\n const [o11, i8] = n10.nodeIds, r9 = this.nodeMap.get(o11), s7 = this.nodeMap.get(i8);\n r9?.center \u0026\u0026 s7?.center \u0026\u0026 t4(r9.center) \u0026\u0026 t4(s7.center) \u0026\u0026 e54.lines.push({ points: [r9.center, s7.center], strokeColor: \"rgba(150, 150, 150, 0.2)\" });\n }\n for (let n10 = 0;n10 \u003c this.solvedRoutes.length; n10++) {\n const o11 = this.solvedRoutes[n10], i8 = o11.path, r9 = \"blue\";\n for (let o12 = 0;o12 \u003c i8.length - 1; o12++) {\n const s7 = i8[o12], a9 = i8[o12 + 1];\n if (s7?.center \u0026\u0026 a9?.center \u0026\u0026 t4(s7.center) \u0026\u0026 t4(a9.center)) {\n const t10 = s7.availableZ.includes(1) \u0026\u0026 a9.availableZ.includes(1), o13 = n10 % 5 * 0.02;\n e54.lines.push({ points: [{ x: s7.center.x + o13, y: s7.center.y + o13 }, { x: a9.center.x + o13, y: a9.center.y + o13 }], strokeColor: r9, strokeDash: t10 ? \"5 5\" : undefined });\n }\n }\n if (i8.length \u003e 0) {\n const n11 = i8[0], r10 = i8[i8.length - 1];\n n11?.center \u0026\u0026 t4(n11.center) \u0026\u0026 e54.points.push({ x: n11.center.x, y: n11.center.y, label: `START: ${o11.connection.name}` }), r10?.center \u0026\u0026 t4(r10.center) \u0026\u0026 e54.points.push({ x: r10.center.x, y: r10.center.y, label: `END: ${o11.connection.name}` });\n }\n }\n if (this.solvedSubpaths)\n for (let n10 = 0;n10 \u003c this.solvedSubpaths.length; n10++) {\n const o11 = this.solvedSubpaths[n10];\n if (o11.path \u0026\u0026 o11.path.length \u003e 1)\n for (let n11 = 0;n11 \u003c o11.path.length - 1; n11++) {\n const i8 = o11.path[n11], r9 = o11.path[n11 + 1];\n i8?.center \u0026\u0026 r9?.center \u0026\u0026 t4(i8.center) \u0026\u0026 t4(r9.center) \u0026\u0026 e54.lines.push({ points: [i8.center, r9.center], strokeColor: \"green\", strokeDash: o11.layer === 1 ? \"3 3\" : undefined });\n }\n }\n if (this.activeSubpath) {\n const n10 = this.activeSubpath.start?.center, o11 = this.activeSubpath.end?.center;\n n10 \u0026\u0026 o11 \u0026\u0026 t4(n10) \u0026\u0026 t4(o11) \u0026\u0026 (e54.lines.push({ points: [n10, o11], strokeColor: \"orange\", strokeDash: \"5 5\" }), e54.points.push({ x: n10.x, y: n10.y, label: \"ACTIVE START\" }), e54.points.push({ x: o11.x, y: o11.y, label: \"ACTIVE END\" }));\n }\n const o10 = this.queuedCandidateNodes.slice(0, 10).sort((e60, t10) =\u003e e60.f - t10.f);\n for (let n10 = 0;n10 \u003c o10.length; n10++) {\n const i8 = 0.6 * (1 - n10 / 10), r9 = [];\n let s7 = o10[n10];\n for (;s7; )\n r9.push(s7.node), s7 = s7.prevCandidate;\n if (r9.reverse(), r9.length \u003e 1) {\n const n11 = r9.map((e60) =\u003e e60.center).filter((e60) =\u003e t4(e60));\n n11.length \u003e 1 \u0026\u0026 e54.lines.push({ points: n11, strokeColor: Ao(\"purple\", 1 - i8), strokeDash: this.activeSubpath?.layer === 1 ? \"4 2\" : undefined });\n }\n }\n if (this.activeConnectionPair) {\n const n10 = this.activeConnectionPair.start?.center, o11 = this.activeConnectionPair.end?.center;\n n10 \u0026\u0026 o11 \u0026\u0026 t4(n10) \u0026\u0026 t4(o11) \u0026\u0026 e54.lines.push({ points: [n10, o11], strokeColor: \"cyan\", strokeDash: \"20 5\" });\n }\n if (this.ogUnprocessedSubpaths \u0026\u0026 this.ogUnprocessedSubpaths.length === 3) {\n const [, o11] = this.ogUnprocessedSubpaths;\n if (o11.start?.center \u0026\u0026 t4(o11.start.center)) {\n const t10 = Math.max(o11.start.width || 0, o11.start.height || 0);\n n8(t10) \u0026\u0026 t10 \u003e 0 \u0026\u0026 (e54.circles.push({ center: o11.start.center, radius: t10, stroke: \"blue\" }), e54.points.push({ x: o11.start.center.x, y: o11.start.center.y, label: \"DIRECTIVE VIA 1\" }));\n }\n if (o11.end?.center \u0026\u0026 t4(o11.end.center)) {\n const t10 = Math.max(o11.end.width || 0, o11.end.height || 0);\n n8(t10) \u0026\u0026 t10 \u003e 0 \u0026\u0026 (e54.circles.push({ center: o11.end.center, radius: t10, stroke: \"purple\" }), e54.points.push({ x: o11.end.center.x, y: o11.end.center.y, label: \"DIRECTIVE VIA 2\" }));\n }\n }\n if (this.queuedCandidateNodes.length \u003e 0)\n for (const n10 of this.queuedCandidateNodes) {\n const o11 = n10.node;\n o11?.center \u0026\u0026 t4(o11.center) \u0026\u0026 e54.circles.push({ center: o11.center, radius: 0.05, fill: \"rgba(255, 255, 0, 0.6)\", stroke: \"yellow\" });\n }\n if (this.visitedNodes.size \u003e 0)\n for (const n10 of this.visitedNodes) {\n const o11 = this.nodeMap.get(n10);\n o11?.center \u0026\u0026 t4(o11.center) \u0026\u0026 e54.circles.push({ center: o11.center, radius: 0.08, fill: \"rgba(128, 128, 128, 0.5)\", stroke: \"gray\" });\n }\n return e54;\n }\n};\nvar Ile = class extends wa {\n getSolverName() {\n return \"HyperAssignableViaCapacityPathingSolver\";\n }\n constructorParams;\n constructor(e54) {\n super(), this.constructorParams = e54, this.MAX_ITERATIONS = e54.MAX_ITERATIONS ?? 120000, this.MIN_SUBSTEPS = 5, this.GREEDY_MULTIPLIER = 1.35;\n }\n getHyperParameterDefs() {\n return [{ name: \"traceOrderingSeed\", possibleValues: [{ SHUFFLE_SEED: 0 }, { SHUFFLE_SEED: 1 }, { SHUFFLE_SEED: 2 }, { SHUFFLE_SEED: 3 }, { SHUFFLE_SEED: 4 }, { SHUFFLE_SEED: 5 }, { SHUFFLE_SEED: 6 }, { SHUFFLE_SEED: 7 }, { SHUFFLE_SEED: 8 }, { SHUFFLE_SEED: 9 }] }, { name: \"forceViaTravelChance\", possibleValues: [{ FORCE_VIA_TRAVEL_CHANCE: 0.6 }, { FORCE_VIA_TRAVEL_CHANCE: 0.8 }, { FORCE_VIA_TRAVEL_CHANCE: 0.9 }] }];\n }\n computeG(e54) {\n const t4 = e54.unprocessedConnectionPairs.length + e54.solvedRoutes.length + (e54.activeConnectionPair ? 1 : 0), n8 = e54.solvedRoutes.length, o10 = t4 \u003e 0 ? n8 / t4 : 0;\n return e54.iterations / e54.MAX_ITERATIONS + (1 - o10);\n }\n computeH(e54) {\n const t4 = e54.unprocessedConnectionPairs.length + e54.solvedRoutes.length + (e54.activeConnectionPair ? 1 : 0), n8 = e54.solvedRoutes.length;\n return t4 \u003e 0 ? 1 - n8 / t4 : 0;\n }\n generateSolver(e54) {\n return new vle({ ...this.constructorParams, hyperParameters: { ...this.constructorParams.hyperParameters, ...e54 } });\n }\n};\nfunction Sle(e54) {\n const t4 = new Map;\n for (const n8 of e54)\n t4.set(n8.capacityMeshNodeId, n8);\n return t4;\n}\nfunction Cle(e54, t4) {\n return { x: (e54.x + t4.x) / 2, y: (e54.y + t4.y) / 2 };\n}\nvar Ple = class extends ni {\n getSolverName() {\n return \"OffboardCapacityNodeSolver\";\n }\n capacityNodes;\n capacityEdges;\n enhancedEdges = [];\n animationState = \"showing_nodes\";\n assignableNodes = [];\n shownNodes = [];\n pendingEdges = [];\n createdEdges = [];\n nextEdgeId = 0;\n nodeMap = new Map;\n constructor(e54) {\n super(), this.capacityNodes = e54.capacityNodes, this.capacityEdges = e54.capacityEdges, this.nodeMap = Sle(this.capacityNodes), this.enhancedEdges = [...this.capacityEdges], this.initializeAssignableNodes(), this.initializePendingEdges(), this.MAX_ITERATIONS = this.assignableNodes.length + this.pendingEdges.length + 10;\n }\n initializeAssignableNodes() {\n for (const e54 of this.capacityNodes) {\n const t4 = e54._assignedViaObstacle;\n t4?.offBoardConnectsTo \u0026\u0026 t4.offBoardConnectsTo.length \u003e 0 \u0026\u0026 this.assignableNodes.push(e54);\n }\n }\n initializePendingEdges() {\n const e54 = new Map;\n for (const t4 of this.assignableNodes) {\n const n8 = t4._assignedViaObstacle;\n if (n8?.offBoardConnectsTo)\n for (const o10 of n8.offBoardConnectsTo)\n e54.has(o10) || e54.set(o10, []), e54.get(o10).push(t4);\n }\n this.pendingEdges = [];\n for (const [t4, n8] of e54)\n if (n8.length \u003e 1)\n for (let e60 = 0;e60 \u003c n8.length; e60++)\n for (let o10 = e60 + 1;o10 \u003c n8.length; o10++)\n this.pendingEdges.push({ node1: n8[e60], node2: n8[o10], netName: t4 });\n }\n _step() {\n switch (this.animationState) {\n case \"showing_nodes\":\n if (this.assignableNodes.length \u003e 0) {\n const e54 = this.assignableNodes.shift();\n this.shownNodes.push(e54);\n } else\n this.animationState = \"showing_edges\";\n break;\n case \"showing_edges\":\n if (this.pendingEdges.length \u003e 0) {\n const { node1: e54, node2: t4, netName: n8 } = this.pendingEdges.shift(), o10 = this.createOffboardEdge(e54, t4, n8);\n this.enhancedEdges.push(o10), this.createdEdges.push(o10);\n } else\n this.animationState = \"done\", this.solved = true;\n break;\n case \"done\":\n this.solved = true;\n }\n }\n createOffboardEdge(e54, t4, n8) {\n return { capacityMeshEdgeId: \"offboard_\" + this.nextEdgeId++, nodeIds: [e54.capacityMeshNodeId, t4.capacityMeshNodeId], isOffboardEdge: true, offboardNetName: n8 };\n }\n visualize() {\n const e54 = [], t4 = [], n8 = [], o10 = new Set(this.shownNodes.map((e60) =\u003e e60.capacityMeshNodeId));\n for (const t10 of this.capacityEdges) {\n if (t10.isOffboardEdge)\n continue;\n if (o10.has(t10.nodeIds[0]) || o10.has(t10.nodeIds[1])) {\n const n10 = this.nodeMap.get(t10.nodeIds[0]), o11 = this.nodeMap.get(t10.nodeIds[1]);\n n10 \u0026\u0026 o11 \u0026\u0026 e54.push({ points: [n10.center, o11.center], strokeColor: \"rgba(0, 200, 0, 0.5)\", strokeWidth: 0.05 });\n }\n }\n for (let e60 = 0;e60 \u003c this.shownNodes.length; e60++) {\n const o11 = this.shownNodes[e60], i9 = o11._assignedViaObstacle, r9 = e60 === this.shownNodes.length - 1 \u0026\u0026 this.animationState === \"showing_nodes\";\n n8.push({ center: o11.center, width: o11.width, height: o11.height, fill: r9 ? \"rgba(255, 165, 0, 0.5)\" : \"rgba(173, 216, 230, 0.5)\", stroke: r9 ? \"orange\" : \"blue\", strokeWidth: r9 ? 0.15 : 0.1 }), t4.push({ x: o11.center.x, y: o11.center.y, color: r9 ? \"orange\" : \"blue\", label: `${r9 ? \"NEW: \" : \"\"}${o11.capacityMeshNodeId}\n${i9?.offBoardConnectsTo?.join(\", \") || \"\"}` });\n }\n for (let n10 = 0;n10 \u003c this.createdEdges.length; n10++) {\n const o11 = this.createdEdges[n10], i9 = n10 === this.createdEdges.length - 1 \u0026\u0026 this.animationState === \"showing_edges\", r9 = this.nodeMap.get(o11.nodeIds[0]), s7 = this.nodeMap.get(o11.nodeIds[1]);\n if (r9 \u0026\u0026 s7) {\n e54.push({ points: [r9.center, s7.center], strokeColor: i9 ? \"red\" : \"orange\", strokeWidth: i9 ? 0.2 : 0.1, strokeDasharray: \"0.3,0.15\" });\n const n11 = Cle(r9.center, s7.center);\n t4.push({ x: n11.x, y: n11.y, color: i9 ? \"red\" : \"orange\", label: `${i9 ? \"NEW: \" : \"\"}⚡ ${o11.offboardNetName}` });\n }\n }\n let i8 = \"Offboard Capacity Node Solver\";\n switch (this.animationState) {\n case \"showing_nodes\":\n i8 += ` - Showing nodes (${this.shownNodes.length}/${this.shownNodes.length + this.assignableNodes.length})`;\n break;\n case \"showing_edges\":\n i8 += ` - Creating edges (${this.createdEdges.length}/${this.createdEdges.length + this.pendingEdges.length})`;\n break;\n case \"done\":\n i8 += ` - Done (${this.shownNodes.length} nodes, ${this.createdEdges.length} edges)`;\n }\n return { lines: e54, points: t4, rects: n8, title: i8 };\n }\n getVirtualOffboardNodes() {\n return [];\n }\n getOffboardEdges() {\n return this.enhancedEdges.filter((e54) =\u003e e54.isOffboardEdge);\n }\n};\nvar Mle = class extends ni {\n getSolverName() {\n return \"OffboardPathFragmentSolver\";\n }\n inputPaths;\n capacityEdges;\n originalConnections;\n fragmentedPaths = [];\n fragmentedConnections = [];\n fragmentedOriginalConnectionNames = new Set;\n nextFragmentId = 0;\n animationState = \"showing_original_path\";\n currentPath = null;\n currentFragments = [];\n currentFragmentIndex = 0;\n nodeMap = new Map;\n constructor({ capacityPaths: e54, capacityEdges: t4, capacityNodes: n8, connections: o10 }) {\n super(), this.inputPaths = [...e54], this.capacityEdges = t4, this.originalConnections = o10, this.nodeMap = Sle(n8);\n }\n _step() {\n switch (this.animationState) {\n case \"showing_original_path\":\n if (this.inputPaths.length === 0)\n return this.animationState = \"done\", void (this.solved = true);\n this.currentPath = this.inputPaths.shift(), this.currentFragments = this.splitPath(this.currentPath), this.currentFragmentIndex = 0;\n this.currentFragments.some((e54) =\u003e e54.isFragmentedPath) ? this.animationState = \"showing_fragment\" : this.fragmentedPaths.push(...this.currentFragments);\n break;\n case \"showing_fragment\":\n if (this.currentFragmentIndex \u003c this.currentFragments.length) {\n const e54 = this.currentFragments[this.currentFragmentIndex];\n this.fragmentedPaths.push(e54), this.currentFragmentIndex++;\n } else\n this.currentPath \u0026\u0026 (this.fragmentedOriginalConnectionNames.add(this.currentPath.connectionName), this.createFragmentConnections(this.currentPath, this.currentFragments)), this.currentPath = null, this.currentFragments = [], this.currentFragmentIndex = 0, this.animationState = \"showing_original_path\";\n break;\n case \"done\":\n this.solved = true;\n }\n }\n createFragmentConnections(e54, t4) {\n const n8 = this.originalConnections.find((t10) =\u003e t10.name === e54.connectionName);\n if (n8)\n for (let e60 = 0;e60 \u003c t4.length; e60++) {\n const o10 = t4[e60];\n if (!o10.isFragmentedPath)\n continue;\n const i8 = n8.pointsToConnect.filter((e61) =\u003e {\n for (const t10 of o10.nodeIds) {\n const n10 = this.nodeMap.get(t10);\n if (n10 \u0026\u0026 oK(e61, n10))\n return true;\n }\n return false;\n }), r9 = e60 === 0, s7 = r9 ? o10.nodeIds[o10.nodeIds.length - 1] : o10.nodeIds[0], a9 = this.nodeMap.get(s7);\n if (i8.length \u003e 0 \u0026\u0026 a9) {\n const e61 = i8[0], t10 = { x: a9.center.x, y: a9.center.y, layer: Io(e61) }, s9 = r9 ? [...i8, t10] : [t10, ...i8];\n this.fragmentedConnections.push({ name: o10.connectionName, pointsToConnect: s9, __netConnectionName: n8.__netConnectionName, __rootConnectionNames: n8.__rootConnectionNames });\n }\n }\n }\n splitPath(e54) {\n const { nodeIds: t4 } = e54;\n if (t4.length \u003c 2)\n return [e54];\n const n8 = [];\n for (let e60 = 0;e60 \u003c t4.length - 1; e60++) {\n const o11 = this.capacityEdges.find((n10) =\u003e n10.nodeIds[0] === t4[e60] \u0026\u0026 n10.nodeIds[1] === t4[e60 + 1] || n10.nodeIds[0] === t4[e60 + 1] \u0026\u0026 n10.nodeIds[1] === t4[e60]);\n o11 \u0026\u0026 o11.isOffboardEdge \u0026\u0026 n8.push(e60);\n }\n if (n8.length === 0)\n return [e54];\n const o10 = [];\n let i8 = 0, r9 = 0;\n for (const s7 of n8) {\n const n10 = t4.slice(i8, s7 + 1);\n if (n10.length \u003e= 1) {\n const t10 = this.nextFragmentId++;\n o10.push({ capacityPathId: `${e54.capacityPathId}_frag_${t10}`, connectionName: `${e54.connectionName}_frag_${r9++}`, rootConnectionName: e54.rootConnectionName, nodeIds: n10, isFragmentedPath: true, mstPairConnectionName: e54.connectionName });\n }\n i8 = s7 + 1;\n }\n if (i8 \u003c t4.length) {\n const n10 = t4.slice(i8);\n if (n10.length \u003e= 1) {\n const t10 = this.nextFragmentId++;\n o10.push({ capacityPathId: `${e54.capacityPathId}_frag_${t10}`, connectionName: `${e54.connectionName}_frag_${r9++}`, rootConnectionName: e54.rootConnectionName, nodeIds: n10, isFragmentedPath: true, mstPairConnectionName: e54.connectionName });\n }\n }\n return o10.length \u003e 0 ? o10 : [e54];\n }\n getFragmentedPaths() {\n return this.fragmentedPaths;\n }\n getFragmentedConnections() {\n return this.fragmentedConnections;\n }\n getFragmentedOriginalConnectionNames() {\n return this.fragmentedOriginalConnectionNames;\n }\n visualize() {\n const e54 = [], t4 = [], n8 = [];\n if (this.animationState === \"showing_original_path\" \u0026\u0026 this.currentPath \u0026\u0026 this.drawPath({ path: this.currentPath, color: \"gray\", lines: e54, points: t4, rects: n8, labelPrefix: \"Original: \" }), this.fragmentedPaths.forEach((o11, i8) =\u003e {\n if (o11.isFragmentedPath) {\n const r9 = i8 % 2 == 0 ? \"blue\" : \"red\";\n this.drawPath({ path: o11, color: r9, lines: e54, points: t4, rects: n8, labelPrefix: `Frag ${i8}: ` });\n } else\n this.drawPath({ path: o11, color: \"green\", lines: e54, points: t4, rects: n8, labelPrefix: \"\" });\n }), this.animationState === \"showing_fragment\" \u0026\u0026 this.currentFragmentIndex \u003e 0) {\n const o11 = this.fragmentedPaths.length - 1;\n if (o11 \u003e= 0) {\n const i8 = this.fragmentedPaths[o11];\n i8.isFragmentedPath \u0026\u0026 this.drawPath({ path: i8, color: \"orange\", lines: e54, points: t4, rects: n8, labelPrefix: \"NEW: \" });\n }\n }\n for (const t10 of this.capacityEdges)\n if (t10.isOffboardEdge) {\n const n10 = this.nodeMap.get(t10.nodeIds[0]), o11 = this.nodeMap.get(t10.nodeIds[1]);\n n10 \u0026\u0026 o11 \u0026\u0026 e54.push({ points: [n10.center, o11.center], strokeColor: \"orange\", strokeWidth: 0.15, strokeDasharray: \"0.3,0.15\" });\n }\n let o10 = \"Offboard Path Fragment Solver\";\n return this.animationState === \"showing_original_path\" ? o10 += \" - Analyzing path...\" : this.animationState === \"showing_fragment\" ? o10 += ` - Fragment ${this.currentFragmentIndex}/${this.currentFragments.length}` : o10 += ` - Done (${this.fragmentedPaths.filter((e60) =\u003e e60.isFragmentedPath).length} fragments)`, { lines: e54, points: t4, rects: n8, title: o10 };\n }\n drawPath(e54) {\n const { path: t4, color: n8, lines: o10, points: i8, rects: r9, labelPrefix: s7 } = e54, a9 = [];\n for (let e60 = 0;e60 \u003c t4.nodeIds.length; e60++) {\n const o11 = t4.nodeIds[e60], c5 = this.nodeMap.get(o11);\n c5 \u0026\u0026 (a9.push(c5.center), r9.push({ center: c5.center, width: 0.8 * c5.width, height: 0.8 * c5.height, stroke: n8, strokeWidth: 0.05, fill: `${n8}33` }), e60 !== 0 \u0026\u0026 e60 !== t4.nodeIds.length - 1 || i8.push({ x: c5.center.x, y: c5.center.y, color: n8, label: `${s7}${t4.connectionName}\n${o11}` }));\n }\n a9.length \u003e 1 \u0026\u0026 o10.push({ points: a9, strokeColor: n8, strokeWidth: 0.1 });\n }\n};\nfunction wle(e54, t4, n8, o10 = {}) {\n return { solverName: e54, solverClass: t4, getConstructorParams: n8, onSolved: o10.onSolved };\n}\nvar Nle = class extends ni {\n constructor(e54, t4 = {}) {\n super(), this.srj = e54, this.opts = t4, this.srj = e54, this.opts = { ...t4 }, this.MAX_ITERATIONS = 1e8;\n const n8 = this.opts;\n if (n8.capacityDepth === undefined) {\n const t10 = e54.bounds.maxX - e54.bounds.minX, o10 = e54.bounds.maxY - e54.bounds.minY, i8 = Math.max(t10, o10), r9 = n8.targetMinCapacity ?? 0.5;\n n8.capacityDepth = Fz(i8, r9);\n }\n this.connMap = ei(e54), this.colorMap = Eo(e54, this.connMap), this.cacheProvider = n8.cacheProvider === undefined ? no() : n8.cacheProvider === null ? null : n8.cacheProvider, this.startTimeOfPhase = {}, this.endTimeOfPhase = {}, this.timeSpentOnPhase = {};\n }\n getSolverName() {\n return \"AssignableAutoroutingPipeline1Solver\";\n }\n netToPointPairsSolver;\n nodeSolver;\n nodeTargetMerger;\n edgeSolver;\n initialPathingSolver;\n initialPathingHyperSolver;\n pathingOptimizer;\n edgeToPortSegmentSolver;\n colorMap;\n segmentToPointSolver;\n unravelMultiSectionSolver;\n segmentToPointOptimizer;\n highDensityRouteSolver;\n highDensityStitchSolver;\n singleLayerNodeMerger;\n mergeAssignableViaNodes;\n offboardCapacityNodeSolver;\n offboardPathFragmentSolver;\n strawSolver;\n deadEndSolver;\n uselessViaRemovalSolver1;\n uselessViaRemovalSolver2;\n multiSimplifiedPathSolver1;\n multiSimplifiedPathSolver2;\n startTimeOfPhase;\n endTimeOfPhase;\n timeSpentOnPhase;\n activeSubSolver = null;\n connMap;\n srjWithPointPairs;\n capacityNodes = null;\n capacityEdges = null;\n cacheProvider = null;\n pipelineDef = [wle(\"netToPointPairsSolver\", uB, (e54) =\u003e [e54.srj, e54.colorMap, ti(e54.srj)], { onSolved: (e54) =\u003e {\n e54.srjWithPointPairs = e54.netToPointPairsSolver?.getNewSimpleRouteJson(), e54.colorMap = Eo(e54.srjWithPointPairs, this.connMap), e54.connMap = ei(e54.srjWithPointPairs);\n } }), wle(\"nodeSolver\", _le, (e54) =\u003e [e54.netToPointPairsSolver?.getNewSimpleRouteJson() || e54.srj, e54.opts], { onSolved: (e54) =\u003e {\n e54.capacityNodes = e54.nodeSolver?.finishedNodes;\n } }), wle(\"mergeAssignableViaNodes\", xle, (e54) =\u003e [e54.nodeSolver?.finishedNodes], { onSolved: (e54) =\u003e {\n e54.capacityNodes = e54.mergeAssignableViaNodes?.newNodes;\n } }), wle(\"singleLayerNodeMerger\", ble, (e54) =\u003e [e54.capacityNodes], { onSolved: (e54) =\u003e {\n e54.capacityNodes = e54.singleLayerNodeMerger?.newNodes;\n } }), wle(\"edgeSolver\", ui, (e54) =\u003e [e54.capacityNodes], { onSolved: (e54) =\u003e {\n e54.capacityEdges = e54.edgeSolver?.edges;\n } }), wle(\"offboardCapacityNodeSolver\", Ple, (e54) =\u003e [{ capacityNodes: e54.capacityNodes, capacityEdges: e54.capacityEdges || [] }], { onSolved: (e54) =\u003e {\n e54.capacityEdges = e54.offboardCapacityNodeSolver?.enhancedEdges || e54.capacityEdges;\n } }), wle(\"deadEndSolver\", Nj, (e54) =\u003e [{ nodes: e54.capacityNodes, edges: e54.capacityEdges }], { onSolved: (e54) =\u003e {\n const t4 = e54.deadEndSolver?.removedNodeIds;\n e54.capacityNodes = e54.capacityNodes.filter((e60) =\u003e !t4.has(e60.capacityMeshNodeId)), e54.capacityEdges = e54.capacityEdges.filter((e60) =\u003e e60.nodeIds.every((e61) =\u003e !t4.has(e61)));\n } }), wle(\"initialPathingHyperSolver\", Ile, (e54) =\u003e [{ simpleRouteJson: e54.srjWithPointPairs, nodes: e54.capacityNodes, edges: e54.capacityEdges || [], colorMap: e54.colorMap, hyperParameters: { MAX_CAPACITY_FACTOR: 1 } }], { onSolved: (e54) =\u003e {\n const t4 = e54.initialPathingHyperSolver?.winningSolver;\n t4 \u0026\u0026 (e54.initialPathingSolver = t4);\n } }), wle(\"offboardPathFragmentSolver\", Mle, (e54) =\u003e [{ capacityPaths: e54.initialPathingSolver?.getCapacityPaths() || [], capacityEdges: e54.capacityEdges || [], capacityNodes: e54.capacityNodes || [], connections: e54.srjWithPointPairs?.connections || [] }], { onSolved: (e54) =\u003e {\n const t4 = e54.offboardPathFragmentSolver;\n if (!t4)\n return;\n const n8 = t4.getFragmentedPaths();\n for (const t10 of n8)\n if (t10.isFragmentedPath \u0026\u0026 t10.mstPairConnectionName) {\n const n10 = e54.colorMap[t10.mstPairConnectionName];\n n10 \u0026\u0026 !e54.colorMap[t10.connectionName] \u0026\u0026 (e54.colorMap[t10.connectionName] = n10);\n }\n const o10 = t4.getFragmentedOriginalConnectionNames(), i8 = t4.getFragmentedConnections();\n o10.size \u003e 0 \u0026\u0026 e54.srjWithPointPairs \u0026\u0026 (e54.srjWithPointPairs = { ...e54.srjWithPointPairs, connections: [...e54.srjWithPointPairs.connections.filter((e60) =\u003e !o10.has(e60.name)), ...i8] }, e54.connMap = ei(e54.srjWithPointPairs));\n } }), wle(\"edgeToPortSegmentSolver\", nj, (e54) =\u003e [{ nodes: e54.capacityNodes, edges: e54.capacityEdges || [], capacityPaths: e54.offboardPathFragmentSolver?.getFragmentedPaths() || e54.initialPathingSolver?.getCapacityPaths() || [], colorMap: e54.colorMap }]), wle(\"segmentToPointSolver\", hj, (e54) =\u003e {\n const t4 = [];\n return e54.edgeToPortSegmentSolver?.nodePortSegments \u0026\u0026 e54.edgeToPortSegmentSolver.nodePortSegments.forEach((e60) =\u003e {\n t4.push(...e60);\n }), [{ segments: t4, colorMap: e54.colorMap, nodes: e54.capacityNodes }];\n }), wle(\"unravelMultiSectionSolver\", Hj, (e54) =\u003e [{ assignedSegments: e54.segmentToPointSolver?.solvedSegments || [], colorMap: e54.colorMap, nodes: e54.capacityNodes, cacheProvider: this.cacheProvider }]), wle(\"highDensityRouteSolver\", Dz, (e54) =\u003e [{ nodePortPoints: e54.unravelMultiSectionSolver?.getNodesWithPortPoints() ?? e54.segmentToPointOptimizer?.getNodesWithPortPoints() ?? [], colorMap: e54.colorMap, connMap: e54.connMap }]), wle(\"highDensityStitchSolver\", IB, (e54) =\u003e [{ connections: e54.srjWithPointPairs.connections, hdRoutes: e54.highDensityRouteSolver.routes, colorMap: e54.colorMap, layerCount: e54.srj.layerCount }]), wle(\"uselessViaRemovalSolver1\", aF, (e54) =\u003e [{ unsimplifiedHdRoutes: e54.highDensityStitchSolver.mergedHdRoutes, obstacles: e54.srj.obstacles, colorMap: e54.colorMap, layerCount: e54.srj.layerCount, connMap: e54.connMap }]), wle(\"multiSimplifiedPathSolver1\", xF, (e54) =\u003e [{ unsimplifiedHdRoutes: e54.uselessViaRemovalSolver1?.getOptimizedHdRoutes() || e54.highDensityStitchSolver.mergedHdRoutes, obstacles: e54.srj.obstacles, connMap: e54.connMap, colorMap: e54.colorMap, outline: e54.srj.outline }]), wle(\"uselessViaRemovalSolver2\", aF, (e54) =\u003e [{ unsimplifiedHdRoutes: e54.multiSimplifiedPathSolver1.simplifiedHdRoutes, obstacles: e54.srj.obstacles, colorMap: e54.colorMap, layerCount: e54.srj.layerCount, connMap: e54.connMap }]), wle(\"multiSimplifiedPathSolver2\", xF, (e54) =\u003e [{ unsimplifiedHdRoutes: e54.uselessViaRemovalSolver2?.getOptimizedHdRoutes(), obstacles: e54.srj.obstacles, connMap: e54.connMap, colorMap: e54.colorMap, outline: e54.srj.outline }])];\n getConstructorParams() {\n return [this.srj, this.opts];\n }\n currentPipelineStepIndex = 0;\n _step() {\n const e54 = this.pipelineDef[this.currentPipelineStepIndex];\n if (!e54)\n return void (this.solved = true);\n if (this.activeSubSolver)\n return this.activeSubSolver.step(), void (this.activeSubSolver.solved ? (this.endTimeOfPhase[e54.solverName] = performance.now(), this.timeSpentOnPhase[e54.solverName] = this.endTimeOfPhase[e54.solverName] - this.startTimeOfPhase[e54.solverName], e54.onSolved?.(this), this.activeSubSolver = null, this.currentPipelineStepIndex++) : this.activeSubSolver.failed \u0026\u0026 (this.error = this.activeSubSolver?.error, this.failed = true, this.activeSubSolver = null));\n const t4 = e54.getConstructorParams(this);\n this.activeSubSolver = new e54.solverClass(...t4), this[e54.solverName] = this.activeSubSolver, this.timeSpentOnPhase[e54.solverName] = 0, this.startTimeOfPhase[e54.solverName] = performance.now();\n }\n solveUntilPhase(e54) {\n for (;this.getCurrentPhase() !== e54; )\n this.step();\n }\n getCurrentPhase() {\n return this.pipelineDef[this.currentPipelineStepIndex]?.solverName ?? \"none\";\n }\n visualize() {\n if (!this.solved \u0026\u0026 this.activeSubSolver)\n return this.activeSubSolver.visualize();\n const e54 = this.netToPointPairsSolver?.visualize(), t4 = this.nodeSolver?.visualize(), n8 = this.nodeTargetMerger?.visualize(), o10 = this.mergeAssignableViaNodes?.visualize(), i8 = this.singleLayerNodeMerger?.visualize(), r9 = this.strawSolver?.visualize(), s7 = this.edgeSolver?.visualize(), a9 = (this.offboardCapacityNodeSolver?.visualize(), this.deadEndSolver?.visualize()), c5 = this.initialPathingSolver?.visualize(), l5 = this.offboardPathFragmentSolver?.visualize(), h5 = this.pathingOptimizer?.visualize(), d9 = this.edgeToPortSegmentSolver?.visualize(), u9 = this.segmentToPointSolver?.visualize(), p9 = this.unravelMultiSectionSolver?.visualize() ?? this.segmentToPointOptimizer?.visualize(), m9 = this.highDensityRouteSolver?.visualize(), g10 = this.highDensityStitchSolver?.visualize(), f10 = this.uselessViaRemovalSolver1?.visualize(), _5 = this.uselessViaRemovalSolver2?.visualize(), y10 = this.multiSimplifiedPathSolver1?.visualize(), b10 = this.multiSimplifiedPathSolver2?.visualize(), x8 = this.srj.outline, v10 = [];\n if (v10.push({ points: [{ x: this.srj.bounds?.minX ?? -50, y: this.srj.bounds?.minY ?? -50 }, { x: this.srj.bounds?.maxX ?? 50, y: this.srj.bounds?.minY ?? -50 }, { x: this.srj.bounds?.maxX ?? 50, y: this.srj.bounds?.maxY ?? 50 }, { x: this.srj.bounds?.minX ?? -50, y: this.srj.bounds?.maxY ?? 50 }, { x: this.srj.bounds?.minX ?? -50, y: this.srj.bounds?.minY ?? -50 }], strokeColor: \"rgba(255,0,0,0.25)\" }), x8 \u0026\u0026 x8.length \u003e= 2) {\n const e60 = x8.map((e61) =\u003e ({ x: e61.x, y: e61.y }));\n e60.push({ ...e60[0] }), v10.push({ points: e60, strokeColor: \"rgba(0, 136, 255, 0.95)\" });\n }\n const I6 = Lo(this.srj), S6 = { points: [...this.srj.connections.flatMap((e60) =\u003e e60.pointsToConnect.map((t10) =\u003e ({ ...t10, layer: Bo(t10, this.srj.layerCount), label: `${e60.name} ${t10.pcb_port_id ?? \"\"}` })))], rects: [...(this.srj.obstacles ?? []).filter((e60) =\u003e !e60.isCopperPour).map((e60) =\u003e ({ ...e60, fill: e60.layers?.includes(\"top\") ? \"rgba(255,0,0,0.25)\" : e60.layers?.includes(\"bottom\") ? \"rgba(0,0,255,0.25)\" : \"rgba(255,0,0,0.25)\", layer: jo(e60, this.srj.layerCount), label: I6(e60) }))], lines: v10 }, C = [S6, e54, t4, n8, o10, i8, r9, s7, a9, c5, l5, h5, d9, u9, p9, m9 ? pi(S6, m9) : null, g10, f10, y10, _5, b10, this.solved ? pi({ lines: v10 }, Wo(this.getOutputSimpleRouteJson())) : null].filter(Boolean);\n return pi(...C);\n }\n preview() {\n if (this.highDensityRouteSolver) {\n const e54 = [];\n for (let t4 = this.highDensityRouteSolver.routes.length - 1;t4 \u003e= 0; t4--) {\n const n8 = this.highDensityRouteSolver.routes[t4];\n if (e54.push({ points: n8.route.map((e60) =\u003e ({ x: e60.x, y: e60.y })), strokeColor: this.colorMap[n8.connectionName] }), e54.length \u003e 200)\n break;\n }\n return { lines: e54 };\n }\n if (this.pathingOptimizer) {\n const e54 = [];\n for (const t4 of this.pathingOptimizer.connectionsWithNodes)\n t4.path \u0026\u0026 e54.push({ points: t4.path.map((e60) =\u003e ({ x: e60.center.x, y: e60.center.y })), strokeColor: this.colorMap[t4.connection.name] });\n return { lines: e54 };\n }\n return this.netToPointPairsSolver ? this.netToPointPairsSolver?.visualize() : {};\n }\n _getOutputHdRoutes() {\n return this.multiSimplifiedPathSolver2?.simplifiedHdRoutes ?? this.uselessViaRemovalSolver2?.getOptimizedHdRoutes() ?? this.multiSimplifiedPathSolver1?.simplifiedHdRoutes ?? this.uselessViaRemovalSolver1?.getOptimizedHdRoutes() ?? this.highDensityStitchSolver.mergedHdRoutes;\n }\n getOutputSimplifiedPcbTraces() {\n if (!this.solved || !this.highDensityRouteSolver)\n throw new Error(\"Cannot get output before solving is complete\");\n const e54 = [], t4 = this._getOutputHdRoutes(), n8 = this.srjWithPointPairs?.connections ?? [];\n for (const o10 of n8) {\n const n10 = o10.__netConnectionName, i8 = o10.__rootConnectionNames?.[0], r9 = t4.filter((e60) =\u003e e60.connectionName === o10.name);\n for (let t10 = 0;t10 \u003c r9.length; t10++) {\n const s7 = r9[t10], a9 = { type: \"pcb_trace\", pcb_trace_id: `${o10.name}_${t10}`, connection_name: n10 ?? i8 ?? o10.name, route: Ro(s7, this.srj.layerCount) };\n e54.push(a9);\n }\n }\n return e54;\n }\n getOutputSimpleRouteJson() {\n return { ...this.srj, traces: this.getOutputSimplifiedPcbTraces() };\n }\n};\n/*! Bundled license information:\n\nis-buffer/index.js:\n (*!\n * Determine if an object is a Buffer\n *\n * @author Feross Aboukhadijeh \u003chttps://feross.org\u003e\n * @license MIT\n *)\n\ndeep-rename-keys/index.js:\n (*!\n * deep-rename-keys \u003chttps://github.com/jonschlinkert/deep-rename-keys\u003e\n *\n * Copyright (c) 2015 Jon Schlinkert, contributors.\n * Licensed under the MIT license.\n *)\n\n@tscircuit/curvy-trace-solver/dist/index.js:\n@tscircuit/find-convex-regions/dist/index.js:\n (*! Bundled license information:\n \n is-buffer/index.js:\n (*!\n * Determine if an object is a Buffer\n *\n * @author Feross Aboukhadijeh \u003chttps://feross.org\u003e\n * @license MIT\n *)\n \n deep-rename-keys/index.js:\n (*!\n * deep-rename-keys \u003chttps://github.com/jonschlinkert/deep-rename-keys\u003e\n *\n * Copyright (c) 2015 Jon Schlinkert, contributors.\n * Licensed under the MIT license.\n *)\n *)\n\n@tscircuit/hypergraph/dist/index.js:\n (*! Bundled license information:\n \n @tscircuit/find-convex-regions/dist/index.js:\n (*! Bundled license information:\n \n is-buffer/index.js:\n (*!\n * Determine if an object is a Buffer\n *\n * @author Feross Aboukhadijeh \u003chttps://feross.org\u003e\n * @license MIT\n *)\n \n deep-rename-keys/index.js:\n (*!\n * deep-rename-keys \u003chttps://github.com/jonschlinkert/deep-rename-keys\u003e\n *\n * Copyright (c) 2015 Jon Schlinkert, contributors.\n * Licensed under the MIT license.\n *)\n *)\n *)\n*/\n\n// routing.ts\nasync function routeRemaining(input) {\n const solver = new Ote(input, {\n powerTraceExpansion: { onlyConnectionNames: [] }\n });\n const existing = new Set((input.traces ?? []).map((trace) =\u003e trace.pcb_trace_id));\n const handlers = {\n complete: [],\n error: [],\n progress: []\n };\n let stopped = false;\n const run = () =\u003e {\n if (stopped)\n return;\n try {\n const until = Date.now() + 40;\n while (!solver.solved \u0026\u0026 !solver.failed \u0026\u0026 Date.now() \u003c until)\n solver.step();\n if (solver.failed) {\n handlers.error.forEach((handler) =\u003e handler({ error: new Error(solver.error || \"Routing failed\") }));\n return;\n }\n if (solver.solved) {\n const traces = (solver.getOutputSimpleRouteJson().traces ?? []).filter((trace) =\u003e !existing.has(trace.pcb_trace_id));\n handlers.complete.forEach((handler) =\u003e handler({ traces }));\n return;\n }\n setTimeout(run, 0);\n } catch (error) {\n handlers.error.forEach((handler) =\u003e handler({ error }));\n }\n };\n return {\n on: (event, handler) =\u003e {\n handlers[event].push(handler);\n },\n start: () =\u003e setTimeout(run, 0),\n stop: () =\u003e {\n stopped = true;\n }\n };\n}\n\n// props-schema.ts\nvar propsJsonSchema = {\n $schema: \"http://json-schema.org/draft-07/schema#\",\n type: \"object\",\n additionalProperties: false,\n properties: {\n externalLfCrystal: { type: \"boolean\", title: \"External LF crystal\", default: true },\n debugHeader: { type: \"boolean\", title: \"SWD header\", default: true },\n supplyVoltage: { type: \"number\", title: \"Supply voltage\", enum: [1.8, 2.5, 3, 3.3], default: 2.5, \"x-unit\": \"V\" },\n inputBulkCapacitance: { type: \"string\", title: \"Input bulk capacitor\", enum: [\"10uF\", \"22uF\"], default: \"10uF\", \"x-unit\": \"F\" },\n resetPullupResistance: { type: \"string\", title: \"Reset pull-up\", enum: [\"100k\", \"10k\"], default: \"100k\", \"x-unit\": \"Ω\" }\n },\n required: [\"externalLfCrystal\", \"debugHeader\", \"supplyVoltage\", \"inputBulkCapacitance\", \"resetPullupResistance\"]\n};\n\n// scripts/shared/props-parser.ts\nimport Ajv from \"ajv\";\nfunction createPropsParser(schema) {\n const ajv = new Ajv({ useDefaults: true, strictSchema: false, allErrors: true });\n const validate = ajv.compile(schema);\n return {\n parse(input) {\n const value = structuredClone(input);\n if (!validate(value))\n throw new Error(ajv.errorsText(validate.errors));\n return value;\n }\n };\n}\n// imports/cc2340r52e0rger.tsx\nimport { jsxDEV } from \"react/jsx-dev-runtime\";\nvar pinLabels = {\n pin1: [\"ANT\"],\n pin2: [\"VDDR1\"],\n pin3: [\"DIO8\"],\n pin4: [\"DIO11\"],\n pin5: [\"DIO12\"],\n pin6: [\"DIO13\"],\n pin7: [\"DIO16_SWDIO\"],\n pin8: [\"DIO17_SWDCK\"],\n pin9: [\"DIO20_A11\"],\n pin10: [\"DIO21_A10\"],\n pin11: [\"VDDS1\"],\n pin12: [\"DIO24_A7\"],\n pin13: [\"RSTN\"],\n pin14: [\"DIO3_X32P\"],\n pin15: [\"DIO4_X32N\"],\n pin16: [\"VDDD\"],\n pin17: [\"DCDC\"],\n pin18: [\"VDDS2\"],\n pin19: [\"DIO6_A1\"],\n pin20: [\"VDDR2\"],\n pin21: [\"X48P\"],\n pin22: [\"X48N\"],\n pin23: [\"GND\"],\n pin24: [\"VDDS3\"],\n pin25: [\"EP\"]\n};\nvar cc2340PinAttributes = {\n pin23: { requiresGround: true, mustBeConnected: true },\n pin1: { isBidirectional: true },\n pin2: {\n mustBeConnected: true,\n shouldHaveDecouplingCapacitor: true,\n recommendedDecouplingCapacitorCapacitance: \"10uF\"\n },\n pin3: {\n isBidirectional: true,\n capabilities: [\"spi_sck\", \"i2c_sda\"],\n canUseInternalPullup: true,\n canUseInternalPulldown: true,\n canUseOpenDrain: true,\n canUsePushPull: true,\n isGpio: true\n },\n pin4: {\n isBidirectional: true,\n capabilities: [\"spi_cs\", \"spi_miso\"],\n canUseInternalPullup: true,\n canUseInternalPulldown: true,\n canUseOpenDrain: true,\n canUsePushPull: true,\n isGpio: true\n },\n pin5: {\n isBidirectional: true,\n capabilities: [\"spi_miso\", \"spi_mosi\", \"uart_rx\", \"i2c_sda\"],\n canUseInternalPullup: true,\n canUseInternalPulldown: true,\n canUseOpenDrain: true,\n canUsePushPull: true,\n isGpio: true\n },\n pin6: {\n isBidirectional: true,\n capabilities: [\"spi_miso\", \"spi_mosi\", \"uart_tx\"],\n canUseInternalPullup: true,\n canUseInternalPulldown: true,\n canUseOpenDrain: true,\n canUsePushPull: true,\n isGpio: true\n },\n pin7: {\n isBidirectional: true,\n capabilities: [\"spi_mosi\", \"uart_rx\", \"i2c_sda\"],\n canUseInternalPullup: true,\n canUseInternalPulldown: true,\n canUseOpenDrain: true,\n canUsePushPull: true,\n isGpio: true\n },\n pin8: {\n isBidirectional: true,\n capabilities: [\"spi_sck\", \"uart_tx\", \"i2c_scl\"],\n canUseInternalPullup: true,\n canUseInternalPulldown: true,\n canUseOpenDrain: true,\n canUsePushPull: true,\n isGpio: true\n },\n pin9: {\n isBidirectional: true,\n capabilities: [\"uart_tx\", \"uart_rx\", \"spi_miso\"],\n canUseInternalPullup: true,\n canUseInternalPulldown: true,\n canUseOpenDrain: true,\n canUsePushPull: true,\n isGpio: true\n },\n pin10: {\n isBidirectional: true,\n capabilities: [\"spi_miso\"],\n canUseInternalPullup: true,\n canUseInternalPulldown: true,\n canUseOpenDrain: true,\n canUsePushPull: true,\n isGpio: true\n },\n pin11: {\n requiresPower: true,\n mustBeConnected: true,\n shouldHaveDecouplingCapacitor: true\n },\n pin12: {\n isBidirectional: true,\n capabilities: [\"spi_sck\", \"i2c_scl\"],\n canUseInternalPullup: true,\n canUseInternalPulldown: true,\n canUseOpenDrain: true,\n canUsePushPull: true,\n isGpio: true\n },\n pin13: { isInput: true },\n pin14: {\n isBidirectional: true,\n canUseInternalPullup: true,\n canUseInternalPulldown: true,\n canUseOpenDrain: true,\n canUsePushPull: true,\n isGpio: true\n },\n pin15: {\n isBidirectional: true,\n capabilities: [\"uart_tx\", \"spi_mosi\"],\n canUseInternalPullup: true,\n canUseInternalPulldown: true,\n canUseOpenDrain: true,\n canUsePushPull: true,\n isGpio: true\n },\n pin16: { mustBeConnected: true, shouldHaveDecouplingCapacitor: true },\n pin18: {\n requiresPower: true,\n mustBeConnected: true,\n shouldHaveDecouplingCapacitor: true\n },\n pin19: {\n isBidirectional: true,\n capabilities: [\"spi_cs\", \"i2c_scl\", \"uart_tx\"],\n canUseInternalPullup: true,\n canUseInternalPulldown: true,\n canUseOpenDrain: true,\n canUsePushPull: true,\n isGpio: true\n },\n pin20: {\n mustBeConnected: true,\n shouldHaveDecouplingCapacitor: true,\n recommendedDecouplingCapacitorCapacitance: \"10uF\"\n },\n pin24: {\n requiresPower: true,\n mustBeConnected: true,\n shouldHaveDecouplingCapacitor: true\n },\n pin25: { mustBeConnected: true }\n};\nvar CC2340R52E0RGER = ({\n pinAttributes: selectedPinAttributes,\n ...props\n}) =\u003e {\n const overrides = selectedPinAttributes ?? {};\n const pinAttributes = Object.fromEntries(Object.keys({ ...cc2340PinAttributes, ...overrides }).map((pin) =\u003e [\n pin,\n { ...cc2340PinAttributes[pin], ...overrides[pin] }\n ]));\n return /* @__PURE__ */ jsxDEV(\"chip\", {\n pinLabels,\n pinAttributes,\n supplierPartNumbers: {\n jlcpcb: [\"C20416850\"]\n },\n manufacturerPartNumber: \"CC2340R52E0RGER\",\n footprint: /* @__PURE__ */ jsxDEV(\"footprint\", {\n children: [\n /* @__PURE__ */ jsxDEV(\"smtpad\", {\n portHints: [\"pin1\"],\n pcbX: \"-1.89992mm\",\n pcbY: \"1.250061mm\",\n width: \"0.5999988mm\",\n height: \"0.2500122mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV(\"smtpad\", {\n portHints: [\"pin2\"],\n pcbX: \"-1.89992mm\",\n pcbY: \"0.750189mm\",\n width: \"0.5999988mm\",\n height: \"0.2500122mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV(\"smtpad\", {\n portHints: [\"pin3\"],\n pcbX: \"-1.89992mm\",\n pcbY: \"0.250063mm\",\n width: \"0.5999988mm\",\n height: \"0.2500122mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV(\"smtpad\", {\n portHints: [\"pin4\"],\n pcbX: \"-1.89992mm\",\n pcbY: \"-0.249809mm\",\n width: \"0.5999988mm\",\n height: \"0.2500122mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV(\"smtpad\", {\n portHints: [\"pin5\"],\n pcbX: \"-1.89992mm\",\n pcbY: \"-0.749935mm\",\n width: \"0.5999988mm\",\n height: \"0.2500122mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV(\"smtpad\", {\n portHints: [\"pin6\"],\n pcbX: \"-1.89992mm\",\n pcbY: \"-1.249807mm\",\n width: \"0.5999988mm\",\n height: \"0.2500122mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV(\"smtpad\", {\n portHints: [\"pin7\"],\n pcbX: \"-1.250188mm\",\n pcbY: \"-1.900047mm\",\n width: \"0.2500122mm\",\n height: \"0.5999988mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV(\"smtpad\", {\n portHints: [\"pin8\"],\n pcbX: \"-0.750316mm\",\n pcbY: \"-1.900047mm\",\n width: \"0.2500122mm\",\n height: \"0.5999988mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV(\"smtpad\", {\n portHints: [\"pin9\"],\n pcbX: \"-0.25019mm\",\n pcbY: \"-1.900047mm\",\n width: \"0.2500122mm\",\n height: \"0.5999988mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV(\"smtpad\", {\n portHints: [\"pin10\"],\n pcbX: \"0.249682mm\",\n pcbY: \"-1.900047mm\",\n width: \"0.2500122mm\",\n height: \"0.5999988mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV(\"smtpad\", {\n portHints: [\"pin11\"],\n pcbX: \"0.749808mm\",\n pcbY: \"-1.900047mm\",\n width: \"0.2500122mm\",\n height: \"0.5999988mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV(\"smtpad\", {\n portHints: [\"pin12\"],\n pcbX: \"1.24968mm\",\n pcbY: \"-1.900047mm\",\n width: \"0.2500122mm\",\n height: \"0.5999988mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV(\"smtpad\", {\n portHints: [\"pin13\"],\n pcbX: \"1.89992mm\",\n pcbY: \"-1.250061mm\",\n width: \"0.5999988mm\",\n height: \"0.2500122mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV(\"smtpad\", {\n portHints: [\"pin14\"],\n pcbX: \"1.89992mm\",\n pcbY: \"-0.749935mm\",\n width: \"0.5999988mm\",\n height: \"0.2500122mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV(\"smtpad\", {\n portHints: [\"pin15\"],\n pcbX: \"1.89992mm\",\n pcbY: \"-0.250063mm\",\n width: \"0.5999988mm\",\n height: \"0.2500122mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV(\"smtpad\", {\n portHints: [\"pin16\"],\n pcbX: \"1.89992mm\",\n pcbY: \"0.250063mm\",\n width: \"0.5999988mm\",\n height: \"0.2500122mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV(\"smtpad\", {\n portHints: [\"pin17\"],\n pcbX: \"1.89992mm\",\n pcbY: \"0.749935mm\",\n width: \"0.5999988mm\",\n height: \"0.2500122mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV(\"smtpad\", {\n portHints: [\"pin18\"],\n pcbX: \"1.89992mm\",\n pcbY: \"1.250061mm\",\n width: \"0.5999988mm\",\n height: \"0.2500122mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV(\"smtpad\", {\n portHints: [\"pin19\"],\n pcbX: \"1.24968mm\",\n pcbY: \"1.900047mm\",\n width: \"0.2500122mm\",\n height: \"0.5999988mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV(\"smtpad\", {\n portHints: [\"pin20\"],\n pcbX: \"0.749808mm\",\n pcbY: \"1.900047mm\",\n width: \"0.2500122mm\",\n height: \"0.5999988mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV(\"smtpad\", {\n portHints: [\"pin21\"],\n pcbX: \"0.249682mm\",\n pcbY: \"1.900047mm\",\n width: \"0.2500122mm\",\n height: \"0.5999988mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV(\"smtpad\", {\n portHints: [\"pin22\"],\n pcbX: \"-0.25019mm\",\n pcbY: \"1.900047mm\",\n width: \"0.2500122mm\",\n height: \"0.5999988mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV(\"smtpad\", {\n portHints: [\"pin23\"],\n pcbX: \"-0.750316mm\",\n pcbY: \"1.900047mm\",\n width: \"0.2500122mm\",\n height: \"0.5999988mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV(\"smtpad\", {\n portHints: [\"pin24\"],\n pcbX: \"-1.250188mm\",\n pcbY: \"1.900047mm\",\n width: \"0.2500122mm\",\n height: \"0.5999988mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV(\"smtpad\", {\n portHints: [\"pin25\"],\n pcbX: \"0mm\",\n pcbY: \"-0.000127mm\",\n width: \"2.4500078mm\",\n height: \"2.4500078mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV(\"silkscreenpath\", {\n route: [\n { x: -2.1044915999999603, y: 1.7001743999999235 },\n { x: -2.1044915999999603, y: 2.100148200000035 },\n { x: -1.7001743999999235, y: 2.1000212000000147 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV(\"silkscreenpath\", {\n route: [\n { x: -2.1001990000000887, y: -1.6998696000000564 },\n { x: -2.1001990000000887, y: -2.0999704000000747 },\n { x: -1.7001743999999235, y: -2.0999704000000747 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV(\"silkscreenpath\", {\n route: [\n { x: 2.0997926000000007, y: -1.5999713999999585 },\n { x: 2.0997926000000007, y: -2.0999704000000747 },\n { x: 1.6998188000001164, y: -2.0999704000000747 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV(\"silkscreenpath\", {\n route: [\n { x: 1.6954753999999639, y: 2.100148200000035 },\n { x: 2.095449199999962, y: 2.100148200000035 },\n { x: 2.095449199999962, y: 1.7001743999999235 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV(\"silkscreencircle\", {\n pcbX: -1.65,\n pcbY: 1.65,\n radius: 0.12\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV(\"courtyardoutline\", {\n outline: [\n { x: -2.45, y: -2.45 },\n { x: 2.45, y: -2.45 },\n { x: 2.45, y: 2.45 },\n { x: -2.45, y: 2.45 },\n { x: -2.45, y: -2.45 }\n ]\n }, undefined, false, undefined, this)\n ]\n }, undefined, true, undefined, this),\n cadModel: {\n objUrl: \"https://modelcdn.tscircuit.com/easyeda_models/assets/C20416850.obj?uuid=d7837941ee5a48928cbbb5a65ba7a879\",\n stepUrl: \"https://modelcdn.tscircuit.com/easyeda_models/assets/C20416850.step?uuid=d7837941ee5a48928cbbb5a65ba7a879\",\n pcbRotationOffset: 0,\n modelOriginPosition: { x: 0, y: 0.000025400000026820635, z: 0 }\n },\n ...props\n }, undefined, false, undefined, this);\n};\n\n// imports/abm11w-48-0000mhz-8-d1x-t3.tsx\nimport { jsxDEV as jsxDEV2 } from \"react/jsx-dev-runtime\";\nvar pinLabels2 = {\n pin1: [\"OSC1\", \"X1\"],\n pin2: [\"GND1\"],\n pin3: [\"OSC2\", \"X2\"],\n pin4: [\"GND2\"]\n};\nvar pinAttributes = {\n pin2: { requiresGround: true },\n pin4: { requiresGround: true }\n};\nvar ABM11W_48_0000MHZ_8_D1X_T3 = (props) =\u003e {\n return /* @__PURE__ */ jsxDEV2(\"crystal\", {\n frequency: \"48MHz\",\n loadCapacitance: \"8pF\",\n pinVariant: \"four_pin\",\n pinLabels: pinLabels2,\n pinAttributes,\n supplierPartNumbers: {\n jlcpcb: [\"C1986112\"]\n },\n manufacturerPartNumber: \"ABM11W-48.0000MHZ-8-D1X-T3\",\n footprint: /* @__PURE__ */ jsxDEV2(\"footprint\", {\n children: [\n /* @__PURE__ */ jsxDEV2(\"smtpad\", {\n portHints: [\"pin2\"],\n pcbX: \"0.6375mm\",\n pcbY: \"-0.4875mm\",\n width: \"0.875mm\",\n height: \"0.775mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV2(\"smtpad\", {\n portHints: [\"pin3\"],\n pcbX: \"0.6375mm\",\n pcbY: \"0.4875mm\",\n width: \"0.875mm\",\n height: \"0.775mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV2(\"smtpad\", {\n portHints: [\"pin4\"],\n pcbX: \"-0.6375mm\",\n pcbY: \"0.4875mm\",\n width: \"0.875mm\",\n height: \"0.775mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV2(\"smtpad\", {\n portHints: [\"pin1\"],\n pcbX: \"-0.6375mm\",\n pcbY: \"-0.4875mm\",\n width: \"0.875mm\",\n height: \"0.775mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV2(\"silkscreenrect\", {\n pcbX: \"0mm\",\n pcbY: \"0mm\",\n width: \"2.05mm\",\n height: \"1.65mm\",\n strokeWidth: \"0.151999696mm\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV2(\"courtyardoutline\", {\n outline: [\n { x: -1.4, y: -1.2 },\n { x: 1.4, y: -1.2 },\n { x: 1.4, y: 1.2 },\n { x: -1.4, y: 1.2 },\n { x: -1.4, y: -1.2 }\n ]\n }, undefined, false, undefined, this)\n ]\n }, undefined, true, undefined, this),\n cadModel: {\n objUrl: \"https://modelcdn.tscircuit.com/easyeda_models/assets/C1986112.obj?uuid=51ae9b24ba7a408881f7752b57b66e45\",\n stepUrl: \"https://modelcdn.tscircuit.com/easyeda_models/assets/C1986112.step?uuid=51ae9b24ba7a408881f7752b57b66e45\",\n pcbRotationOffset: 0,\n modelOriginPosition: { x: 0, y: -0.00011430000006384944, z: -0.01 }\n },\n ...props\n }, undefined, false, undefined, this);\n};\n\n// imports/abs07-32-768khz-7-t.tsx\nimport { jsxDEV as jsxDEV3 } from \"react/jsx-dev-runtime\";\nvar pinLabels3 = {\n pin1: [\"OSC1\"],\n pin2: [\"OSC2\"]\n};\nvar ABS07_32_768KHZ_7_T = (props) =\u003e {\n return /* @__PURE__ */ jsxDEV3(\"crystal\", {\n frequency: \"32.768kHz\",\n loadCapacitance: \"7pF\",\n pinLabels: pinLabels3,\n supplierPartNumbers: {\n jlcpcb: [\"C276424\"]\n },\n manufacturerPartNumber: \"ABS07_32_768KHZ_7_T\",\n footprint: /* @__PURE__ */ jsxDEV3(\"footprint\", {\n children: [\n /* @__PURE__ */ jsxDEV3(\"smtpad\", {\n portHints: [\"pin1\"],\n pcbX: \"-1.1549888mm\",\n pcbY: \"0mm\",\n width: \"0.850011mm\",\n height: \"1.6999966mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV3(\"smtpad\", {\n portHints: [\"pin2\"],\n pcbX: \"1.1549888mm\",\n pcbY: \"0mm\",\n width: \"0.850011mm\",\n height: \"1.6999966mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV3(\"silkscreenpath\", {\n route: [\n { x: -2.028596400000083, y: -1.0786109999999098 },\n { x: -2.028596400000083, y: 1.0786110000000235 },\n { x: 2.0285963999999694, y: 1.0786110000000235 },\n { x: 2.0285963999999694, y: -1.0786109999999098 },\n { x: -2.028596400000083, y: -1.0786109999999098 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV3(\"courtyardoutline\", {\n outline: [\n { x: -2.282000000000039, y: 1.3167999999999438 },\n { x: 2.2819999999999254, y: 1.3167999999999438 },\n { x: 2.2819999999999254, y: -1.3421999999999343 },\n { x: -2.282000000000039, y: -1.3421999999999343 },\n { x: -2.282000000000039, y: 1.3167999999999438 }\n ]\n }, undefined, false, undefined, this)\n ]\n }, undefined, true, undefined, this),\n cadModel: {\n objUrl: \"https://modelcdn.tscircuit.com/easyeda_models/assets/C276424.obj?uuid=b374b09d4a6d4557b2ff8af51e7e333f\",\n stepUrl: \"https://modelcdn.tscircuit.com/easyeda_models/assets/C276424.step?uuid=b374b09d4a6d4557b2ff8af51e7e333f\",\n pcbRotationOffset: 0,\n modelOriginPosition: { x: 0, y: -0.000012700000070253736, z: 0 }\n },\n ...props\n }, undefined, false, undefined, this);\n};\n\n// imports/bm05b-srss-tb-lf-sn.tsx\nimport { jsxDEV as jsxDEV4 } from \"react/jsx-dev-runtime\";\nvar pinLabels4 = {\n pin1: [\"VTREF\", \"pin1\"],\n pin2: [\"SWDIO\", \"pin2\"],\n pin3: [\"SWCLK\", \"pin3\"],\n pin4: [\"GND\", \"pin4\"],\n pin5: [\"RESET_N\", \"pin5\"],\n pin6: [\"SHIELD1\", \"MT1\", \"pin6\"],\n pin7: [\"SHIELD2\", \"MT2\", \"pin7\"]\n};\nvar BM05B_SRSS_TB_LF__SN_ = (props) =\u003e {\n return /* @__PURE__ */ jsxDEV4(\"connector\", {\n pinLabels: pinLabels4,\n supplierPartNumbers: {\n jlcpcb: [\"C160391\"]\n },\n manufacturerPartNumber: \"BM05B-SRSS-TB(LF)(SN)\",\n footprint: /* @__PURE__ */ jsxDEV4(\"footprint\", {\n insertionDirection: \"from_above\",\n children: [\n /* @__PURE__ */ jsxDEV4(\"smtpad\", {\n portHints: [\"pin7\"],\n pcbX: \"-3.299968mm\",\n pcbY: \"-1.1998833mm\",\n width: \"1.1999976mm\",\n height: \"1.7999964mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV4(\"smtpad\", {\n portHints: [\"pin6\"],\n pcbX: \"3.299968mm\",\n pcbY: \"-1.1998833mm\",\n width: \"1.1999976mm\",\n height: \"1.7999964mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV4(\"smtpad\", {\n portHints: [\"pin5\"],\n pcbX: \"-1.999996mm\",\n pcbY: \"1.3248767mm\",\n width: \"0.5999988mm\",\n height: \"1.5500096mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV4(\"smtpad\", {\n portHints: [\"pin4\"],\n pcbX: \"-0.999998mm\",\n pcbY: \"1.3248767mm\",\n width: \"0.5999988mm\",\n height: \"1.5500096mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV4(\"smtpad\", {\n portHints: [\"pin3\"],\n pcbX: \"0mm\",\n pcbY: \"1.3248767mm\",\n width: \"0.5999988mm\",\n height: \"1.5500096mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV4(\"smtpad\", {\n portHints: [\"pin2\"],\n pcbX: \"0.999998mm\",\n pcbY: \"1.3248767mm\",\n width: \"0.5999988mm\",\n height: \"1.5500096mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV4(\"smtpad\", {\n portHints: [\"pin1\"],\n pcbX: \"1.999996mm\",\n pcbY: \"1.3248767mm\",\n width: \"0.5999988mm\",\n height: \"1.5500096mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV4(\"silkscreenpath\", {\n route: [\n { x: -2.468829199999959, y: -1.8425033000000894 },\n { x: 2.4688800000001265, y: -1.8425033000000894 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV4(\"silkscreenpath\", {\n route: [\n { x: 2.5311607999999524, y: 1.0784966999999597 },\n { x: 3.556025400000067, y: 1.0784966999999597 },\n { x: 3.556025400000067, y: -0.0688466999999946 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV4(\"silkscreenpath\", {\n route: [\n { x: -3.555974600000013, y: -0.0688466999999946 },\n { x: -3.555974600000013, y: 1.0784966999999597 },\n { x: -2.5311099999998987, y: 1.0784966999999597 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV4(\"silkscreencircle\", {\n pcbX: \"2.921mm\",\n pcbY: \"1.7134967mm\",\n radius: \"0.179578mm\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV4(\"courtyardoutline\", {\n outline: [\n { x: -4.159568000000036, y: 2.354402700000037 },\n { x: 4.138232000000016, y: 2.354402700000037 },\n { x: 4.138232000000016, y: -2.336597299999994 },\n { x: -4.159568000000036, y: -2.336597299999994 },\n { x: -4.159568000000036, y: 2.354402700000037 }\n ]\n }, undefined, false, undefined, this)\n ]\n }, undefined, true, undefined, this),\n cadModel: {\n objUrl: \"https://modelcdn.tscircuit.com/easyeda_models/assets/C160391.obj?uuid=eaf9e23008df4ce1b5a7b451075b7284\",\n stepUrl: \"https://modelcdn.tscircuit.com/easyeda_models/assets/C160391.step?uuid=eaf9e23008df4ce1b5a7b451075b7284\",\n pcbRotationOffset: 180,\n modelOriginPosition: {\n x: 2.000025400000027,\n y: -0.43250299999996966,\n z: -0.01\n }\n },\n ...props\n }, undefined, false, undefined, this);\n};\n\n// imports/a-2450at18a100e.tsx\nimport { jsxDEV as jsxDEV5 } from \"react/jsx-dev-runtime\";\nvar pinLabels5 = {\n pin1: [\"ANT\"],\n pin2: [\"NC\"]\n};\nvar A_2450AT18A100E = (props) =\u003e {\n return /* @__PURE__ */ jsxDEV5(\"antenna\", {\n pinLabels: pinLabels5,\n symbol: /* @__PURE__ */ jsxDEV5(\"symbol\", {\n children: [\n /* @__PURE__ */ jsxDEV5(\"schematictext\", {\n text: props.name,\n schX: 0.5,\n schY: 0,\n fontSize: 0.18\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV5(\"schematicpath\", {\n points: [\n { x: 0, y: 0 },\n { x: -0.2, y: 0.2 }\n ],\n strokeColor: \"#8D2323\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV5(\"schematicpath\", {\n points: [\n { x: 0.2, y: 0.2 },\n { x: 0, y: 0 }\n ],\n strokeColor: \"#8D2323\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV5(\"schematicpath\", {\n points: [\n { x: 0, y: 0 },\n { x: 0, y: -0.2 }\n ],\n strokeColor: \"#8D2323\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV5(\"port\", {\n name: \"pin1\",\n pinNumber: 1,\n aliases: [\"ANT\"],\n direction: \"down\",\n schX: 0,\n schY: -0.4,\n schStemLength: 0.2\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV5(\"schematicpath\", {\n points: [\n { x: 0, y: 0 },\n { x: 0, y: 0.3 }\n ],\n strokeColor: \"#880000\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV5(\"port\", {\n name: \"pin2\",\n pinNumber: 2,\n aliases: [\"2\"],\n direction: \"up\",\n schX: 0,\n schY: 0.3,\n schStemLength: 0.2\n }, undefined, false, undefined, this)\n ]\n }, undefined, true, undefined, this),\n supplierPartNumbers: {\n jlcpcb: [\"C89334\"]\n },\n manufacturerPartNumber: \"2450AT18A100E\",\n footprint: /* @__PURE__ */ jsxDEV5(\"footprint\", {\n children: [\n /* @__PURE__ */ jsxDEV5(\"smtpad\", {\n portHints: [\"pin1\"],\n pcbX: \"-1.7mm\",\n pcbY: \"0mm\",\n width: \"0.8mm\",\n height: \"1.6mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV5(\"smtpad\", {\n portHints: [\"pin2\"],\n pcbX: \"1.7mm\",\n pcbY: \"0mm\",\n width: \"0.8mm\",\n height: \"1.6mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV5(\"silkscreenpath\", {\n route: [\n { x: -0.7619999999998299, y: 0.2540000000000191 },\n { x: -0.7619999999998299, y: -0.2539999999999054 },\n { x: -0.2539999999999054, y: -0.2539999999999054 },\n { x: -0.2539999999999054, y: 0.2540000000000191 },\n { x: -0.7619999999998299, y: 0.2540000000000191 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV5(\"silkscreenpath\", {\n route: [\n { x: -1.6759935999999698, y: 1.059967400000005 },\n { x: 1.6759936000000835, y: 1.0499852000000374 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV5(\"silkscreenpath\", {\n route: [\n { x: 1.5240000000001146, y: -1.0500105999999505 },\n { x: -1.6759428000000298, y: -1.0499852000000374 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV5(\"fabricationnotepath\", {\n route: [\n { x: -1.2597129999999197, y: 0.22793960000001334 },\n { x: -0.2838195999999016, y: 0.22793960000001334 },\n { x: -0.2838195999999016, y: -0.20652739999991354 },\n { x: -1.2599669999999605, y: -0.2116073999999344 },\n { x: -1.2597129999999197, y: -0.17978119999997944 },\n { x: -1.2597129999999197, y: 0.22793960000001334 }\n ],\n strokeWidth: \"0.254mm\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV5(\"courtyardoutline\", {\n outline: [\n { x: -2.3330539999998336, y: 1.3167999999999438 },\n { x: 2.3325459999999794, y: 1.3167999999999438 },\n { x: 2.3325459999999794, y: -1.291400000000067 },\n { x: -2.3330539999998336, y: -1.291400000000067 },\n { x: -2.3330539999998336, y: 1.3167999999999438 }\n ]\n }, undefined, false, undefined, this)\n ]\n }, undefined, true, undefined, this),\n cadModel: {\n objUrl: \"https://modelcdn.tscircuit.com/easyeda_models/assets/C89334.obj?uuid=cbaa998426f54032b453ce6fafc2cd5a\",\n stepUrl: \"https://modelcdn.tscircuit.com/easyeda_models/assets/C89334.step?uuid=cbaa998426f54032b453ce6fafc2cd5a\",\n pcbRotationOffset: 180,\n modelOriginPosition: { x: 0, y: 0, z: -0.65 }\n },\n ...props\n }, undefined, false, undefined, this);\n};\n\n// imports/cl05b104ko5nnnc.tsx\nimport { jsxDEV as jsxDEV6 } from \"react/jsx-dev-runtime\";\nvar CL05B104KO5NNNC = (props) =\u003e {\n const { name = \"C1\", ...restProps } = props;\n return /* @__PURE__ */ jsxDEV6(\"capacitor\", {\n name,\n capacitance: \"100nF\",\n supplierPartNumbers: {\n jlcpcb: [\"C1525\"]\n },\n manufacturerPartNumber: \"CL05B104KO5NNNC\",\n footprint: /* @__PURE__ */ jsxDEV6(\"footprint\", {\n children: [\n /* @__PURE__ */ jsxDEV6(\"smtpad\", {\n portHints: [\"pin2\"],\n pcbX: \"0.420116mm\",\n pcbY: \"0mm\",\n width: \"0.499999mm\",\n height: \"0.540004mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV6(\"smtpad\", {\n portHints: [\"pin1\"],\n pcbX: \"-0.420116mm\",\n pcbY: \"0mm\",\n width: \"0.499999mm\",\n height: \"0.540004mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV6(\"silkscreenpath\", {\n route: [\n { x: -0.721385400000031, y: 0.49753519999990203 },\n { x: -0.22138640000002852, y: 0.49753519999990203 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV6(\"silkscreenpath\", {\n route: [\n { x: -0.8738108000000011, y: -0.34724340000002485 },\n { x: -0.8738108000000011, y: 0.3451606000000993 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV6(\"silkscreenpath\", {\n route: [\n { x: -0.22138640000002852, y: -0.4996433999999681 },\n { x: -0.721385400000031, y: -0.4996433999999681 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV6(\"silkscreenpath\", {\n route: [\n { x: 0.7213853999999174, y: -0.4975097999999889 },\n { x: 0.22138639999991483, y: -0.4975097999999889 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV6(\"silkscreenpath\", {\n route: [\n { x: 0.22138639999991483, y: 0.49961800000005496 },\n { x: 0.7213853999999174, y: 0.49961800000005496 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV6(\"silkscreenpath\", {\n route: [\n { x: 0.8738108000000011, y: 0.34726880000005167 },\n { x: 0.8738108000000011, y: -0.3451606000000993 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV6(\"silkscreenpath\", {\n route: [\n { x: 0.7213853999999174, y: 0.4996433999998544 },\n { x: 0.829148473452733, y: 0.4550064734527268 },\n { x: 0.8737853999998606, y: 0.34724340000002485 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV6(\"silkscreenpath\", {\n route: [\n { x: 0.8737853999998606, y: -0.3451606000000993 },\n { x: 0.829148473452733, y: -0.4529236734526876 },\n { x: 0.7213853999999174, y: -0.49756059999992885 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV6(\"silkscreenpath\", {\n route: [\n { x: -0.721385400000031, y: -0.4996433999997407 },\n { x: -0.829148473452733, y: -0.45500647345261314 },\n { x: -0.8737853999999743, y: -0.34724340000002485 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV6(\"silkscreenpath\", {\n route: [\n { x: -0.8737853999999743, y: 0.3451606000000993 },\n { x: -0.829148473452733, y: 0.45292367345280127 },\n { x: -0.721385400000031, y: 0.49756060000004254 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV6(\"courtyardoutline\", {\n outline: [\n { x: -1.1136000000000195, y: 0.7580000000000382 },\n { x: 1.1389999999998963, y: 0.7580000000000382 },\n { x: 1.1389999999998963, y: -0.7326000000000477 },\n { x: -1.1136000000000195, y: -0.7326000000000477 },\n { x: -1.1136000000000195, y: 0.7580000000000382 }\n ]\n }, undefined, false, undefined, this)\n ]\n }, undefined, true, undefined, this),\n cadModel: {\n objUrl: \"https://modelcdn.tscircuit.com/easyeda_models/assets/C1525.obj?uuid=32fe2cf9314f444ca2785a33c2db7189\",\n stepUrl: \"https://modelcdn.tscircuit.com/easyeda_models/assets/C1525.step?uuid=32fe2cf9314f444ca2785a33c2db7189\",\n pcbRotationOffset: 0,\n modelOriginPosition: { x: 0, y: -0.000012700000070253736, z: -0.25 }\n },\n ...restProps\n }, undefined, false, undefined, this);\n};\n\n// imports/grm033r61a104ke15d.tsx\nimport { jsxDEV as jsxDEV7 } from \"react/jsx-dev-runtime\";\nvar GRM033R61A104KE15D = (props) =\u003e {\n const { name = \"C1\", ...restProps } = props;\n return /* @__PURE__ */ jsxDEV7(\"capacitor\", {\n name,\n capacitance: \"100nF\",\n supplierPartNumbers: {\n jlcpcb: [\"C76934\"]\n },\n manufacturerPartNumber: \"GRM033R61A104KE15D\",\n footprint: /* @__PURE__ */ jsxDEV7(\"footprint\", {\n children: [\n /* @__PURE__ */ jsxDEV7(\"smtpad\", {\n portHints: [\"pin2\"],\n pcbX: \"0.27432mm\",\n pcbY: \"0mm\",\n width: \"0.368427mm\",\n height: \"0.3240024mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV7(\"smtpad\", {\n portHints: [\"pin1\"],\n pcbX: \"-0.27432mm\",\n pcbY: \"0mm\",\n width: \"0.368427mm\",\n height: \"0.3240024mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV7(\"silkscreenpath\", {\n route: [\n { x: 0.5346445999999787, y: 0.3906011999999919 },\n { x: 0.16619220000006862, y: 0.3906011999999919 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV7(\"silkscreenpath\", {\n route: [\n { x: 0.16619220000006862, y: -0.3906011999999919 },\n { x: 0.5346445999999787, y: -0.3906011999999919 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV7(\"silkscreenpath\", {\n route: [\n { x: 0.6870446000000356, y: -0.23820120000004863 },\n { x: 0.6870446000000356, y: 0.23820120000004863 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV7(\"silkscreenpath\", {\n route: [\n { x: -0.5346446000000924, y: 0.3906011999999919 },\n { x: -0.16619220000006862, y: 0.3906011999999919 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV7(\"silkscreenpath\", {\n route: [\n { x: -0.16619220000006862, y: -0.3906011999999919 },\n { x: -0.5346446000000924, y: -0.3906011999999919 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV7(\"silkscreenpath\", {\n route: [\n { x: -0.6870446000001493, y: -0.23820120000004863 },\n { x: -0.6870446000001493, y: 0.23820120000004863 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV7(\"silkscreenpath\", {\n route: [\n { x: 0.5346445999999787, y: -0.3906011999998782 },\n { x: 0.6424076734527944, y: -0.3459642734528643 },\n { x: 0.6870446000000356, y: -0.23820120000004863 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV7(\"silkscreenpath\", {\n route: [\n { x: 0.6870446000000356, y: 0.23820120000004863 },\n { x: 0.6424076734527944, y: 0.3459642734528643 },\n { x: 0.5346445999999787, y: 0.3906011999999919 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV7(\"silkscreenpath\", {\n route: [\n { x: -0.5346446000000924, y: -0.3906011999998782 },\n { x: -0.6424076734529081, y: -0.3459642734528643 },\n { x: -0.6870446000001493, y: -0.23820120000004863 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV7(\"silkscreenpath\", {\n route: [\n { x: -0.6870446000001493, y: 0.23820120000004863 },\n { x: -0.6424076734529081, y: 0.3459642734528643 },\n { x: -0.5346446000000924, y: 0.3906011999999919 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV7(\"courtyardoutline\", {\n outline: [\n { x: -0.935799999999972, y: 0.6309999999999718 },\n { x: 0.9358000000000857, y: 0.6309999999999718 },\n { x: 0.9358000000000857, y: -0.6563999999999623 },\n { x: -0.935799999999972, y: -0.6563999999999623 },\n { x: -0.935799999999972, y: 0.6309999999999718 }\n ]\n }, undefined, false, undefined, this)\n ]\n }, undefined, true, undefined, this),\n cadModel: {\n objUrl: \"https://modelcdn.tscircuit.com/easyeda_models/assets/C76934.obj?uuid=c3e75c3d90204c70b153866ab54c789f\",\n stepUrl: \"https://modelcdn.tscircuit.com/easyeda_models/assets/C76934.step?uuid=c3e75c3d90204c70b153866ab54c789f\",\n pcbRotationOffset: 0,\n modelOriginPosition: { x: 0, y: -0.000012700000070253736, z: -0.15 }\n },\n ...restProps\n }, undefined, false, undefined, this);\n};\n\n// imports/grm188z71a106ka73d.tsx\nimport { jsxDEV as jsxDEV8 } from \"react/jsx-dev-runtime\";\nvar GRM188Z71A106KA73D = (props) =\u003e {\n const { name = \"C1\", ...restProps } = props;\n return /* @__PURE__ */ jsxDEV8(\"capacitor\", {\n name,\n capacitance: \"10uF\",\n supplierPartNumbers: {\n jlcpcb: [\"C2959727\"]\n },\n manufacturerPartNumber: \"GRM188Z71A106KA73D\",\n footprint: /* @__PURE__ */ jsxDEV8(\"footprint\", {\n children: [\n /* @__PURE__ */ jsxDEV8(\"smtpad\", {\n portHints: [\"pin2\"],\n pcbX: \"0.700024mm\",\n pcbY: \"0mm\",\n width: \"0.7999984mm\",\n height: \"0.8999982mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV8(\"smtpad\", {\n portHints: [\"pin1\"],\n pcbX: \"-0.700024mm\",\n pcbY: \"0mm\",\n width: \"0.7999984mm\",\n height: \"0.8999982mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV8(\"silkscreenpath\", {\n route: [\n { x: -0.2801873999999316, y: -0.7095743999998376 },\n { x: -1.080160400000068, y: -0.7095743999998376 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV8(\"silkscreenpath\", {\n route: [\n { x: 0.28026359999989836, y: -0.7100315999998656 },\n { x: 1.080236599999921, y: -0.7100315999998656 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV8(\"silkscreenpath\", {\n route: [\n { x: -0.2801873999999316, y: 0.7101078000000598 },\n { x: -1.080160400000068, y: 0.7101078000000598 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV8(\"silkscreenpath\", {\n route: [\n { x: 0.28026359999989836, y: 0.7096252000001186 },\n { x: 1.080236599999921, y: 0.7096252000001186 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV8(\"silkscreenpath\", {\n route: [\n { x: -1.3899134000000686, y: -0.3997452000000976 },\n { x: -1.3899134000000686, y: 0.40030400000000554 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV8(\"silkscreenpath\", {\n route: [\n { x: 1.3900149999998348, y: 0.39977060000001075 },\n { x: 1.3900149999998348, y: -0.4002531999999519 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV8(\"silkscreenpath\", {\n route: [\n { x: 1.080185799999981, y: 0.7096252000001186 },\n { x: 1.299277109074751, y: 0.6188693482574763 },\n { x: 1.3900149999998348, y: 0.39977060000001075 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV8(\"silkscreenpath\", {\n route: [\n { x: 1.3900149999998348, y: -0.40020240000012564 },\n { x: 1.2992681283295724, y: -0.6192847283296032 },\n { x: 1.080185799999981, y: -0.7100315999998656 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV8(\"silkscreenpath\", {\n route: [\n { x: -1.0801096000000143, y: -0.7095743999998376 },\n { x: -1.2991755087698493, y: -0.6188185485625581 },\n { x: -1.3899134000000686, y: -0.3997452000000976 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV8(\"silkscreenpath\", {\n route: [\n { x: -1.3899134000000686, y: 0.40022780000003877 },\n { x: -1.2991934705021322, y: 0.6193339880503572 },\n { x: -1.0801096000000143, y: 0.7101078000000598 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV8(\"courtyardoutline\", {\n outline: [\n { x: -1.647000000000162, y: 0.9612000000000762 },\n { x: 1.6216000000000577, y: 0.9612000000000762 },\n { x: 1.6216000000000577, y: -0.9611999999999625 },\n { x: -1.647000000000162, y: -0.9611999999999625 },\n { x: -1.647000000000162, y: 0.9612000000000762 }\n ]\n }, undefined, false, undefined, this)\n ]\n }, undefined, true, undefined, this),\n cadModel: {\n objUrl: \"https://modelcdn.tscircuit.com/easyeda_models/assets/C2959727.obj?uuid=ac9b32e974bc448eab36b1293f859dcb\",\n stepUrl: \"https://modelcdn.tscircuit.com/easyeda_models/assets/C2959727.step?uuid=ac9b32e974bc448eab36b1293f859dcb\",\n pcbRotationOffset: 0,\n modelOriginPosition: { x: 0, y: 0, z: -0.4 }\n },\n ...restProps\n }, undefined, false, undefined, this);\n};\n\n// imports/cl05a105ka5nqnc.tsx\nimport { jsxDEV as jsxDEV9 } from \"react/jsx-dev-runtime\";\nvar CL05A105KA5NQNC = (props) =\u003e {\n const { name = \"C1\", ...restProps } = props;\n return /* @__PURE__ */ jsxDEV9(\"capacitor\", {\n name,\n capacitance: \"1uF\",\n supplierPartNumbers: {\n jlcpcb: [\"C52923\"]\n },\n manufacturerPartNumber: \"CL05A105KA5NQNC\",\n footprint: /* @__PURE__ */ jsxDEV9(\"footprint\", {\n children: [\n /* @__PURE__ */ jsxDEV9(\"smtpad\", {\n portHints: [\"pin2\"],\n pcbX: \"0.420116mm\",\n pcbY: \"0mm\",\n width: \"0.499999mm\",\n height: \"0.540004mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV9(\"smtpad\", {\n portHints: [\"pin1\"],\n pcbX: \"-0.420116mm\",\n pcbY: \"0mm\",\n width: \"0.499999mm\",\n height: \"0.540004mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV9(\"silkscreenpath\", {\n route: [\n { x: -0.721385400000031, y: 0.49753519999990203 },\n { x: -0.22138640000002852, y: 0.49753519999990203 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV9(\"silkscreenpath\", {\n route: [\n { x: -0.8738108000000011, y: -0.34724340000002485 },\n { x: -0.8738108000000011, y: 0.3451606000000993 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV9(\"silkscreenpath\", {\n route: [\n { x: -0.22138640000002852, y: -0.4996433999999681 },\n { x: -0.721385400000031, y: -0.4996433999999681 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV9(\"silkscreenpath\", {\n route: [\n { x: 0.7213853999999174, y: -0.4975097999999889 },\n { x: 0.22138639999991483, y: -0.4975097999999889 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV9(\"silkscreenpath\", {\n route: [\n { x: 0.22138639999991483, y: 0.49961800000005496 },\n { x: 0.7213853999999174, y: 0.49961800000005496 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV9(\"silkscreenpath\", {\n route: [\n { x: 0.8738108000000011, y: 0.34726880000005167 },\n { x: 0.8738108000000011, y: -0.3451606000000993 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV9(\"silkscreenpath\", {\n route: [\n { x: 0.7213853999999174, y: 0.4996433999998544 },\n { x: 0.829148473452733, y: 0.4550064734527268 },\n { x: 0.8737853999998606, y: 0.34724340000002485 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV9(\"silkscreenpath\", {\n route: [\n { x: 0.8737853999998606, y: -0.3451606000000993 },\n { x: 0.829148473452733, y: -0.4529236734526876 },\n { x: 0.7213853999999174, y: -0.49756059999992885 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV9(\"silkscreenpath\", {\n route: [\n { x: -0.721385400000031, y: -0.4996433999997407 },\n { x: -0.829148473452733, y: -0.45500647345261314 },\n { x: -0.8737853999999743, y: -0.34724340000002485 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV9(\"silkscreenpath\", {\n route: [\n { x: -0.8737853999999743, y: 0.3451606000000993 },\n { x: -0.829148473452733, y: 0.45292367345280127 },\n { x: -0.721385400000031, y: 0.49756060000004254 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV9(\"courtyardoutline\", {\n outline: [\n { x: -1.1136000000000195, y: 0.7580000000000382 },\n { x: 1.1389999999998963, y: 0.7580000000000382 },\n { x: 1.1389999999998963, y: -0.7326000000000477 },\n { x: -1.1136000000000195, y: -0.7326000000000477 },\n { x: -1.1136000000000195, y: 0.7580000000000382 }\n ]\n }, undefined, false, undefined, this)\n ]\n }, undefined, true, undefined, this),\n cadModel: {\n objUrl: \"https://modelcdn.tscircuit.com/easyeda_models/assets/C52923.obj?uuid=32fe2cf9314f444ca2785a33c2db7189\",\n stepUrl: \"https://modelcdn.tscircuit.com/easyeda_models/assets/C52923.step?uuid=32fe2cf9314f444ca2785a33c2db7189\",\n pcbRotationOffset: 0,\n modelOriginPosition: { x: 0, y: -0.000012700000070253736, z: -0.25 }\n },\n ...restProps\n }, undefined, false, undefined, this);\n};\n\n// imports/gjm0335c1h1r5bb01d.tsx\nimport { jsxDEV as jsxDEV10 } from \"react/jsx-dev-runtime\";\nvar GJM0335C1H1R5BB01D = (props) =\u003e {\n const { name = \"C1\", ...restProps } = props;\n return /* @__PURE__ */ jsxDEV10(\"capacitor\", {\n name,\n capacitance: \"1.5pF\",\n supplierPartNumbers: {\n jlcpcb: [\"C237515\"]\n },\n manufacturerPartNumber: \"GJM0335C1H1R5BB01D\",\n footprint: /* @__PURE__ */ jsxDEV10(\"footprint\", {\n children: [\n /* @__PURE__ */ jsxDEV10(\"smtpad\", {\n portHints: [\"pin2\"],\n pcbX: \"0.27432mm\",\n pcbY: \"0mm\",\n width: \"0.368427mm\",\n height: \"0.3240024mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV10(\"smtpad\", {\n portHints: [\"pin1\"],\n pcbX: \"-0.27432mm\",\n pcbY: \"0mm\",\n width: \"0.368427mm\",\n height: \"0.3240024mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV10(\"silkscreenpath\", {\n route: [\n { x: 0.5346445999999787, y: 0.3906011999999919 },\n { x: 0.16619220000006862, y: 0.3906011999999919 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV10(\"silkscreenpath\", {\n route: [\n { x: 0.16619220000006862, y: -0.3906011999999919 },\n { x: 0.5346445999999787, y: -0.3906011999999919 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV10(\"silkscreenpath\", {\n route: [\n { x: 0.6870446000000356, y: -0.23820120000004863 },\n { x: 0.6870446000000356, y: 0.23820120000004863 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV10(\"silkscreenpath\", {\n route: [\n { x: -0.5346446000000924, y: 0.3906011999999919 },\n { x: -0.16619220000006862, y: 0.3906011999999919 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV10(\"silkscreenpath\", {\n route: [\n { x: -0.16619220000006862, y: -0.3906011999999919 },\n { x: -0.5346446000000924, y: -0.3906011999999919 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV10(\"silkscreenpath\", {\n route: [\n { x: -0.6870446000001493, y: -0.23820120000004863 },\n { x: -0.6870446000001493, y: 0.23820120000004863 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV10(\"silkscreenpath\", {\n route: [\n { x: 0.5346445999999787, y: -0.3906011999998782 },\n { x: 0.6424076734527944, y: -0.3459642734528643 },\n { x: 0.6870446000000356, y: -0.23820120000004863 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV10(\"silkscreenpath\", {\n route: [\n { x: 0.6870446000000356, y: 0.23820120000004863 },\n { x: 0.6424076734527944, y: 0.3459642734528643 },\n { x: 0.5346445999999787, y: 0.3906011999999919 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV10(\"silkscreenpath\", {\n route: [\n { x: -0.5346446000000924, y: -0.3906011999998782 },\n { x: -0.6424076734529081, y: -0.3459642734528643 },\n { x: -0.6870446000001493, y: -0.23820120000004863 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV10(\"silkscreenpath\", {\n route: [\n { x: -0.6870446000001493, y: 0.23820120000004863 },\n { x: -0.6424076734529081, y: 0.3459642734528643 },\n { x: -0.5346446000000924, y: 0.3906011999999919 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV10(\"courtyardoutline\", {\n outline: [\n { x: -0.935799999999972, y: 0.6309999999999718 },\n { x: 0.9358000000000857, y: 0.6309999999999718 },\n { x: 0.9358000000000857, y: -0.6563999999999623 },\n { x: -0.935799999999972, y: -0.6563999999999623 },\n { x: -0.935799999999972, y: 0.6309999999999718 }\n ]\n }, undefined, false, undefined, this)\n ]\n }, undefined, true, undefined, this),\n cadModel: {\n objUrl: \"https://modelcdn.tscircuit.com/easyeda_models/assets/C237515.obj?uuid=c3e75c3d90204c70b153866ab54c789f\",\n stepUrl: \"https://modelcdn.tscircuit.com/easyeda_models/assets/C237515.step?uuid=c3e75c3d90204c70b153866ab54c789f\",\n pcbRotationOffset: 0,\n modelOriginPosition: { x: 0, y: -0.000012700000070253736, z: -0.15 }\n },\n ...restProps\n }, undefined, false, undefined, this);\n};\n\n// imports/gjm1555c1h1r0bb01d.tsx\nimport { jsxDEV as jsxDEV11 } from \"react/jsx-dev-runtime\";\nvar GJM1555C1H1R0BB01D = (props) =\u003e {\n const { name = \"C1\", ...restProps } = props;\n return /* @__PURE__ */ jsxDEV11(\"capacitor\", {\n name,\n capacitance: \"1pF\",\n supplierPartNumbers: {\n jlcpcb: [\"C76898\"]\n },\n manufacturerPartNumber: \"GJM1555C1H1R0BB01D\",\n footprint: /* @__PURE__ */ jsxDEV11(\"footprint\", {\n children: [\n /* @__PURE__ */ jsxDEV11(\"smtpad\", {\n portHints: [\"pin2\"],\n pcbX: \"0.420116mm\",\n pcbY: \"0mm\",\n width: \"0.499999mm\",\n height: \"0.540004mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV11(\"smtpad\", {\n portHints: [\"pin1\"],\n pcbX: \"-0.420116mm\",\n pcbY: \"0mm\",\n width: \"0.499999mm\",\n height: \"0.540004mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV11(\"silkscreenpath\", {\n route: [\n { x: -0.721385400000031, y: 0.49753519999990203 },\n { x: -0.22138640000002852, y: 0.49753519999990203 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV11(\"silkscreenpath\", {\n route: [\n { x: -0.8738108000000011, y: -0.34724340000002485 },\n { x: -0.8738108000000011, y: 0.3451606000000993 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV11(\"silkscreenpath\", {\n route: [\n { x: -0.22138640000002852, y: -0.4996433999999681 },\n { x: -0.721385400000031, y: -0.4996433999999681 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV11(\"silkscreenpath\", {\n route: [\n { x: 0.7213853999999174, y: -0.4975097999999889 },\n { x: 0.22138639999991483, y: -0.4975097999999889 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV11(\"silkscreenpath\", {\n route: [\n { x: 0.22138639999991483, y: 0.49961800000005496 },\n { x: 0.7213853999999174, y: 0.49961800000005496 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV11(\"silkscreenpath\", {\n route: [\n { x: 0.8738108000000011, y: 0.34726880000005167 },\n { x: 0.8738108000000011, y: -0.3451606000000993 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV11(\"silkscreenpath\", {\n route: [\n { x: 0.7213853999999174, y: 0.4996433999998544 },\n { x: 0.829148473452733, y: 0.4550064734527268 },\n { x: 0.8737853999998606, y: 0.34724340000002485 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV11(\"silkscreenpath\", {\n route: [\n { x: 0.8737853999998606, y: -0.3451606000000993 },\n { x: 0.829148473452733, y: -0.4529236734526876 },\n { x: 0.7213853999999174, y: -0.49756059999992885 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV11(\"silkscreenpath\", {\n route: [\n { x: -0.721385400000031, y: -0.4996433999997407 },\n { x: -0.829148473452733, y: -0.45500647345261314 },\n { x: -0.8737853999999743, y: -0.34724340000002485 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV11(\"silkscreenpath\", {\n route: [\n { x: -0.8737853999999743, y: 0.3451606000000993 },\n { x: -0.829148473452733, y: 0.45292367345280127 },\n { x: -0.721385400000031, y: 0.49756060000004254 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV11(\"courtyardoutline\", {\n outline: [\n { x: -1.1136000000000195, y: 0.7580000000000382 },\n { x: 1.1389999999998963, y: 0.7580000000000382 },\n { x: 1.1389999999998963, y: -0.7326000000000477 },\n { x: -1.1136000000000195, y: -0.7326000000000477 },\n { x: -1.1136000000000195, y: 0.7580000000000382 }\n ]\n }, undefined, false, undefined, this)\n ]\n }, undefined, true, undefined, this),\n cadModel: {\n objUrl: \"https://modelcdn.tscircuit.com/easyeda_models/assets/C76898.obj?uuid=32fe2cf9314f444ca2785a33c2db7189\",\n stepUrl: \"https://modelcdn.tscircuit.com/easyeda_models/assets/C76898.step?uuid=32fe2cf9314f444ca2785a33c2db7189\",\n pcbRotationOffset: 0,\n modelOriginPosition: { x: 0, y: -0.000012700000070253736, z: -0.25 }\n },\n ...restProps\n }, undefined, false, undefined, this);\n};\n\n// imports/lqm18dn100m70l.tsx\nimport { jsxDEV as jsxDEV12 } from \"react/jsx-dev-runtime\";\nvar pinLabels6 = {\n pin1: [\"pin1\"],\n pin2: [\"pin2\"]\n};\nvar LQM18DN100M70L = (props) =\u003e {\n return /* @__PURE__ */ jsxDEV12(\"chip\", {\n pinLabels: pinLabels6,\n symbol: /* @__PURE__ */ jsxDEV12(\"symbol\", {\n children: [\n /* @__PURE__ */ jsxDEV12(\"schematicpath\", {\n svgPath: \"M 0.174 0.00138 A 0.08 0.078 0 1 0 0.3333 0.00128\",\n strokeColor: \"#880000\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV12(\"schematicpath\", {\n svgPath: \"M 0.00134 0.00142 A 0.08 0.078 0 1 0 0.16064 0.00132\",\n strokeColor: \"#880000\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV12(\"schematicpath\", {\n svgPath: \"M -0.168 0.00142 A 0.08 0.078 0 1 0 -0.0087 0.00132\",\n strokeColor: \"#880000\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV12(\"schematicpath\", {\n svgPath: \"M -0.33766 0.00136 A 0.08 0.078 0 1 0 -0.17836 0.00128\",\n strokeColor: \"#880000\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV12(\"port\", {\n name: \"pin1\",\n pinNumber: 1,\n aliases: [\"1\"],\n direction: \"left\",\n schX: -0.4,\n schY: 0,\n schStemLength: 0.06\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV12(\"port\", {\n name: \"pin2\",\n pinNumber: 2,\n aliases: [\"2\"],\n direction: \"right\",\n schX: 0.4,\n schY: 0,\n schStemLength: 0.06\n }, undefined, false, undefined, this)\n ]\n }, undefined, true, undefined, this),\n supplierPartNumbers: {\n jlcpcb: [\"C713281\"]\n },\n manufacturerPartNumber: \"LQM18DN100M70L\",\n footprint: /* @__PURE__ */ jsxDEV12(\"footprint\", {\n children: [\n /* @__PURE__ */ jsxDEV12(\"smtpad\", {\n portHints: [\"pin1\"],\n pcbX: \"-0.699897mm\",\n pcbY: \"0mm\",\n width: \"0.7999984mm\",\n height: \"0.8640064mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV12(\"smtpad\", {\n portHints: [\"pin2\"],\n pcbX: \"0.699897mm\",\n pcbY: \"0mm\",\n width: \"0.7999984mm\",\n height: \"0.8640064mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV12(\"silkscreenpath\", {\n route: [\n { x: -1.2700000000000955, y: -0.6513575999998693 },\n { x: -1.4241018000001304, y: -0.499008399999866 },\n { x: -1.4241018000001304, y: 0.5174234000000979 },\n { x: -1.2700000000000955, y: 0.6499860000001263 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV12(\"silkscreenpath\", {\n route: [\n { x: 1.2699999999998681, y: 0.6499860000001263 },\n { x: 1.4241525999999567, y: 0.49898300000006657 },\n { x: 1.4241525999999567, y: -0.5174487999998973 },\n { x: 1.2699999999998681, y: -0.6500114000000394 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV12(\"silkscreenpath\", {\n route: [\n { x: -1.272006600000168, y: 0.6499860000001263 },\n { x: -0.5100066000001107, y: 0.6499860000001263 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV12(\"silkscreenpath\", {\n route: [\n { x: 1.2720573999999942, y: -0.6500114000000394 },\n { x: 0.5100573999999369, y: -0.6500114000000394 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV12(\"silkscreenpath\", {\n route: [\n { x: -1.272006600000168, y: -0.6500114000000394 },\n { x: -0.5100066000001107, y: -0.6500114000000394 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV12(\"silkscreenpath\", {\n route: [\n { x: 1.2720573999999942, y: 0.6499860000001263 },\n { x: 0.5100573999999369, y: 0.6499860000001263 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV12(\"courtyardoutline\", {\n outline: [\n { x: -1.6628750000002128, y: 0.8875400000000582 },\n { x: 1.6819249999998647, y: 0.8875400000000582 },\n { x: 1.6819249999998647, y: -0.9078599999998005 },\n { x: -1.6628750000002128, y: -0.9078599999998005 },\n { x: -1.6628750000002128, y: 0.8875400000000582 }\n ]\n }, undefined, false, undefined, this)\n ]\n }, undefined, true, undefined, this),\n cadModel: {\n objUrl: \"https://modelcdn.tscircuit.com/easyeda_models/assets/C713281.obj?uuid=a7f84688c5004aa68dbcbddc99bd5473\",\n stepUrl: \"https://modelcdn.tscircuit.com/easyeda_models/assets/C713281.step?uuid=a7f84688c5004aa68dbcbddc99bd5473\",\n pcbRotationOffset: 180,\n modelOriginPosition: {\n x: 0.0023875999999063424,\n y: 0.015976600000044527,\n z: -0.25\n }\n },\n ...props\n }, undefined, false, undefined, this);\n};\n\n// imports/lqp03tn2n8b02d.tsx\nimport { jsxDEV as jsxDEV13 } from \"react/jsx-dev-runtime\";\nvar pinLabels7 = {\n pin1: [\"pin1\"],\n pin2: [\"pin2\"]\n};\nvar LQP03TN2N8B02D = (props) =\u003e {\n return /* @__PURE__ */ jsxDEV13(\"chip\", {\n pinLabels: pinLabels7,\n symbol: /* @__PURE__ */ jsxDEV13(\"symbol\", {\n children: [\n /* @__PURE__ */ jsxDEV13(\"port\", {\n name: \"pin2\",\n pinNumber: 2,\n aliases: [\"2\"],\n direction: \"right\",\n schX: 0.4,\n schY: 0,\n schStemLength: 0.06\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV13(\"port\", {\n name: \"pin1\",\n pinNumber: 1,\n aliases: [\"1\"],\n direction: \"left\",\n schX: -0.4,\n schY: 0,\n schStemLength: 0.06\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV13(\"schematicpath\", {\n svgPath: \"M -0.33766 0.00136 A 0.08 0.078 0 1 0 -0.17836 0.00128\",\n strokeColor: \"#880000\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV13(\"schematicpath\", {\n svgPath: \"M -0.168 0.00142 A 0.08 0.078 0 1 0 -0.0087 0.00132\",\n strokeColor: \"#880000\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV13(\"schematicpath\", {\n svgPath: \"M 0.00134 0.00142 A 0.08 0.078 0 1 0 0.16064 0.00132\",\n strokeColor: \"#880000\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV13(\"schematicpath\", {\n svgPath: \"M 0.174 0.00138 A 0.08 0.078 0 1 0 0.3333 0.00128\",\n strokeColor: \"#880000\"\n }, undefined, false, undefined, this)\n ]\n }, undefined, true, undefined, this),\n supplierPartNumbers: {\n jlcpcb: [\"C206433\"]\n },\n manufacturerPartNumber: \"LQP03TN2N8B02D\",\n footprint: /* @__PURE__ */ jsxDEV13(\"footprint\", {\n children: [\n /* @__PURE__ */ jsxDEV13(\"smtpad\", {\n portHints: [\"pin2\"],\n pcbX: \"0.27432mm\",\n pcbY: \"0mm\",\n width: \"0.368427mm\",\n height: \"0.3240024mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV13(\"smtpad\", {\n portHints: [\"pin1\"],\n pcbX: \"-0.27432mm\",\n pcbY: \"0mm\",\n width: \"0.368427mm\",\n height: \"0.3240024mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV13(\"silkscreenpath\", {\n route: [\n { x: 0.16619220000006862, y: -0.3906011999999919 },\n { x: 0.5346445999999787, y: -0.3906011999999919 },\n { x: 0.6870446000000356, y: -0.23820120000004863 },\n { x: 0.6870446000000356, y: 0.23820120000004863 },\n { x: 0.5346445999999787, y: 0.3906011999999919 },\n { x: 0.16619220000006862, y: 0.3906011999999919 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV13(\"silkscreenpath\", {\n route: [\n { x: -0.16619220000006862, y: -0.3906011999999919 },\n { x: -0.5346446000000924, y: -0.3906011999999919 },\n { x: -0.6870446000001493, y: -0.23820120000004863 },\n { x: -0.6870446000001493, y: 0.23820120000004863 },\n { x: -0.5346446000000924, y: 0.3906011999999919 },\n { x: -0.16619220000006862, y: 0.3906011999999919 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV13(\"courtyardoutline\", {\n outline: [\n { x: -0.935799999999972, y: 0.6309999999999718 },\n { x: 0.9358000000000857, y: 0.6309999999999718 },\n { x: 0.9358000000000857, y: -0.6563999999999623 },\n { x: -0.935799999999972, y: -0.6563999999999623 },\n { x: -0.935799999999972, y: 0.6309999999999718 }\n ]\n }, undefined, false, undefined, this)\n ]\n }, undefined, true, undefined, this),\n cadModel: {\n objUrl: \"https://modelcdn.tscircuit.com/easyeda_models/assets/C206433.obj?uuid=fa57e36e003e4ee2b14b14feaebd32e1\",\n stepUrl: \"https://modelcdn.tscircuit.com/easyeda_models/assets/C206433.step?uuid=fa57e36e003e4ee2b14b14feaebd32e1\",\n pcbRotationOffset: 0,\n modelOriginPosition: { x: 0, y: 0.000012699999956566899, z: -0.01 }\n },\n ...props\n }, undefined, false, undefined, this);\n};\n\n// imports/lqg15hs2n7s02d.tsx\nimport { jsxDEV as jsxDEV14 } from \"react/jsx-dev-runtime\";\nvar pinLabels8 = {\n pin1: [\"pin1\"],\n pin2: [\"pin2\"]\n};\nvar LQG15HS2N7S02D = (props) =\u003e {\n return /* @__PURE__ */ jsxDEV14(\"chip\", {\n pinLabels: pinLabels8,\n symbol: /* @__PURE__ */ jsxDEV14(\"symbol\", {\n children: [\n /* @__PURE__ */ jsxDEV14(\"port\", {\n name: \"pin2\",\n pinNumber: 2,\n aliases: [\"2\"],\n direction: \"right\",\n schX: 0.4,\n schY: 0,\n schStemLength: 0.06\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV14(\"port\", {\n name: \"pin1\",\n pinNumber: 1,\n aliases: [\"1\"],\n direction: \"left\",\n schX: -0.4,\n schY: 0,\n schStemLength: 0.06\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV14(\"schematicpath\", {\n svgPath: \"M -0.3376 0.0014 A 0.08 0.078 0 1 0 -0.1784 0.0012\",\n strokeColor: \"#880000\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV14(\"schematicpath\", {\n svgPath: \"M -0.168 0.0014 A 0.08 0.078 0 1 0 -0.0088 0.0014\",\n strokeColor: \"#880000\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV14(\"schematicpath\", {\n svgPath: \"M 0.0014 0.0014 A 0.08 0.078 0 1 0 0.1606 0.0014\",\n strokeColor: \"#880000\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV14(\"schematicpath\", {\n svgPath: \"M 0.174 0.0014 A 0.08 0.078 0 1 0 0.3334 0.0012\",\n strokeColor: \"#880000\"\n }, undefined, false, undefined, this)\n ]\n }, undefined, true, undefined, this),\n supplierPartNumbers: {\n jlcpcb: [\"C77108\"]\n },\n manufacturerPartNumber: \"LQG15HS2N7S02D\",\n footprint: /* @__PURE__ */ jsxDEV14(\"footprint\", {\n children: [\n /* @__PURE__ */ jsxDEV14(\"smtpad\", {\n portHints: [\"pin2\"],\n pcbX: \"0.419989mm\",\n pcbY: \"0mm\",\n width: \"0.540004mm\",\n height: \"0.540004mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV14(\"smtpad\", {\n portHints: [\"pin1\"],\n pcbX: \"-0.419989mm\",\n pcbY: \"0mm\",\n width: \"0.540004mm\",\n height: \"0.540004mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV14(\"silkscreenpath\", {\n route: [\n { x: -0.12687300000004598, y: -0.5080000000000382 },\n { x: -0.9169654000000946, y: -0.5080000000000382 },\n { x: -1.0693908000000647, y: -0.3556253999998944 },\n { x: -1.0693908000000647, y: 0.3367785999998887 },\n { x: -0.9169654000000946, y: 0.4891532000000325 },\n { x: -0.12687300000004598, y: 0.4891532000000325 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV14(\"silkscreenpath\", {\n route: [\n { x: 0.12712699999997312, y: -0.5080000000000382 },\n { x: 0.9170669999998609, y: -0.5080000000000382 },\n { x: 1.0694670000000315, y: -0.3555999999998676 },\n { x: 1.0694670000000315, y: 0.32766000000003714 },\n { x: 0.9069069999999329, y: 0.4902200000000221 },\n { x: 0.12712699999997312, y: 0.4902200000000221 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV14(\"courtyardoutline\", {\n outline: [\n { x: -1.3168000000000575, y: 0.7326000000000477 },\n { x: 1.3168000000000575, y: 0.7326000000000477 },\n { x: 1.3168000000000575, y: -0.7580000000000382 },\n { x: -1.3168000000000575, y: -0.7580000000000382 },\n { x: -1.3168000000000575, y: 0.7326000000000477 }\n ]\n }, undefined, false, undefined, this)\n ]\n }, undefined, true, undefined, this),\n cadModel: {\n objUrl: \"https://modelcdn.tscircuit.com/easyeda_models/assets/C77108.obj?uuid=c498e8771bc24312a11c6413631665a8\",\n stepUrl: \"https://modelcdn.tscircuit.com/easyeda_models/assets/C77108.step?uuid=c498e8771bc24312a11c6413631665a8\",\n pcbRotationOffset: 0,\n modelOriginPosition: { x: 0, y: -0.000012700000070253736, z: -0.25 }\n },\n ...props\n }, undefined, false, undefined, this);\n};\n\n// imports/lqg15hs3n9s02d.tsx\nimport { jsxDEV as jsxDEV15 } from \"react/jsx-dev-runtime\";\nvar pinLabels9 = {\n pin1: [\"pin1\"],\n pin2: [\"pin2\"]\n};\nvar LQG15HS3N9S02D = (props) =\u003e {\n return /* @__PURE__ */ jsxDEV15(\"chip\", {\n pinLabels: pinLabels9,\n symbol: /* @__PURE__ */ jsxDEV15(\"symbol\", {\n children: [\n /* @__PURE__ */ jsxDEV15(\"port\", {\n name: \"pin2\",\n pinNumber: 2,\n aliases: [\"2\"],\n direction: \"right\",\n schX: 0.4,\n schY: 0,\n schStemLength: 0.06\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV15(\"port\", {\n name: \"pin1\",\n pinNumber: 1,\n aliases: [\"1\"],\n direction: \"left\",\n schX: -0.4,\n schY: 0,\n schStemLength: 0.06\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV15(\"schematicpath\", {\n svgPath: \"M -0.3376 0.0014 A 0.08 0.078 0 1 0 -0.1784 0.0012\",\n strokeColor: \"#880000\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV15(\"schematicpath\", {\n svgPath: \"M -0.168 0.0014 A 0.08 0.078 0 1 0 -0.0088 0.0014\",\n strokeColor: \"#880000\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV15(\"schematicpath\", {\n svgPath: \"M 0.0014 0.0014 A 0.08 0.078 0 1 0 0.1606 0.0014\",\n strokeColor: \"#880000\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV15(\"schematicpath\", {\n svgPath: \"M 0.174 0.0014 A 0.08 0.078 0 1 0 0.3334 0.0012\",\n strokeColor: \"#880000\"\n }, undefined, false, undefined, this)\n ]\n }, undefined, true, undefined, this),\n supplierPartNumbers: {\n jlcpcb: [\"C77109\"]\n },\n manufacturerPartNumber: \"LQG15HS3N9S02D\",\n footprint: /* @__PURE__ */ jsxDEV15(\"footprint\", {\n children: [\n /* @__PURE__ */ jsxDEV15(\"smtpad\", {\n portHints: [\"pin2\"],\n pcbX: \"0.419989mm\",\n pcbY: \"0mm\",\n width: \"0.540004mm\",\n height: \"0.540004mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV15(\"smtpad\", {\n portHints: [\"pin1\"],\n pcbX: \"-0.419989mm\",\n pcbY: \"0mm\",\n width: \"0.540004mm\",\n height: \"0.540004mm\",\n shape: \"rect\"\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV15(\"silkscreenpath\", {\n route: [\n { x: -0.12687300000004598, y: -0.5080000000000382 },\n { x: -0.9169654000000946, y: -0.5080000000000382 },\n { x: -1.0693908000000647, y: -0.3556253999998944 },\n { x: -1.0693908000000647, y: 0.3367785999998887 },\n { x: -0.9169654000000946, y: 0.4891532000000325 },\n { x: -0.12687300000004598, y: 0.4891532000000325 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV15(\"silkscreenpath\", {\n route: [\n { x: 0.12712699999997312, y: -0.5080000000000382 },\n { x: 0.9170669999998609, y: -0.5080000000000382 },\n { x: 1.0694670000000315, y: -0.3555999999998676 },\n { x: 1.0694670000000315, y: 0.32766000000003714 },\n { x: 0.9069069999999329, y: 0.4902200000000221 },\n { x: 0.12712699999997312, y: 0.4902200000000221 }\n ]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV15(\"courtyardoutline\", {\n outline: [\n { x: -1.3168000000000575, y: 0.7326000000000477 },\n { x: 1.3168000000000575, y: 0.7326000000000477 },\n { x: 1.3168000000000575, y: -0.7580000000000382 },\n { x: -1.3168000000000575, y: -0.7580000000000382 },\n { x: -1.3168000000000575, y: 0.7326000000000477 }\n ]\n }, undefined, false, undefined, this)\n ]\n }, undefined, true, undefined, this),\n cadModel: {\n objUrl: \"https://modelcdn.tscircuit.com/easyeda_models/assets/C77109.obj?uuid=c498e8771bc24312a11c6413631665a8\",\n stepUrl: \"https://modelcdn.tscircuit.com/easyeda_models/assets/C77109.step?uuid=c498e8771bc24312a11c6413631665a8\",\n pcbRotationOffset: 0,\n modelOriginPosition: { x: 0, y: -0.000012700000070253736, z: -0.25 }\n },\n ...props\n }, undefined, false, undefined, this);\n};\n\n// index.circuit.tsx\nimport { jsxDEV as jsxDEV16, Fragment as Fragment2 } from \"react/jsx-dev-runtime\";\nvar Note = (props) =\u003e /* @__PURE__ */ jsxDEV16(\"schematictext\", {\n ...props,\n schSheetName: \"reference\"\n}, undefined, false, undefined, this);\nvar sectionMembers = {\n mcu: [\"U1\"],\n power_input: [\"J1\"],\n vdds: [\"C1\", \"C2\", \"C19\", \"C20\"],\n vddr: [\"L1\", \"C21\", \"C22\", \"C25\"],\n vddd: [\"C23\"],\n rf: [\"C26\", \"C27\", \"C28\", \"L2\", \"L3\", \"L4\", \"ANT1\"],\n hf: [\"Y2\"],\n lf: [\"Y1\", \"C14\", \"C15\"],\n reset: [\"R14\", \"C24\"],\n debug: [\"J4\", \"TP1\", \"TP2\"]\n};\nvar schematic = Object.fromEntries(Object.entries(sectionMembers).flatMap(([section, names]) =\u003e names.map((name) =\u003e [\n name,\n { schSheetName: \"reference\", schSectionName: section }\n])));\nvar propsSchema = createPropsParser(propsJsonSchema);\nvar referenceProps = propsSchema;\nfunction Cc2340Reference(input = {}) {\n const {\n externalLfCrystal,\n debugHeader,\n supplyVoltage,\n inputBulkCapacitance,\n resetPullupResistance\n } = referenceProps.parse(input);\n const supplyLabel = `${supplyVoltage.toFixed(1)}V`;\n const nets = {\n VDDS: [\n \"J1.1\",\n \"U1.11\",\n \"U1.18\",\n \"U1.24\",\n \"C1.1\",\n \"C2.1\",\n \"C19.1\",\n \"C20.1\",\n \"R14.1\"\n ],\n GND: [\n \"J1.2\",\n \"U1.23\",\n \"U1.25\",\n \"Y2.2\",\n \"Y2.4\",\n \"C1.2\",\n \"C2.2\",\n \"C19.2\",\n \"C20.2\",\n \"C21.2\",\n \"C22.2\",\n \"C23.2\",\n \"C24.2\",\n \"C25.2\",\n \"C26.2\",\n \"C27.2\",\n \"L3.2\"\n ],\n VDDR: [\"U1.2\", \"U1.20\", \"L1.2\", \"C21.1\", \"C22.1\", \"C25.1\"],\n VDDD: [\"U1.16\", \"C23.1\"],\n DCDC: [\"U1.17\", \"L1.1\"],\n RESET_N: [\"U1.13\", \"R14.2\", \"C24.1\"],\n HF_P: [\"U1.21\", \"Y2.1\"],\n HF_N: [\"U1.22\", \"Y2.3\"],\n RF_IC: [\"U1.1\", \"C26.1\", \"L2.2\"],\n RF_50: [\"L2.1\", \"C27.1\", \"C28.1\"],\n RF_MATCH: [\"C28.2\", \"L3.1\", \"L4.1\"],\n RF_ANT: [\"L4.2\", \"ANT1.1\"],\n SWDIO: [\"U1.7\", \"TP1.1\"],\n SWCLK: [\"U1.8\", \"TP2.1\"]\n };\n if (externalLfCrystal) {\n nets.LF_P = [\"U1.14\", \"Y1.1\", \"C14.1\"];\n nets.LF_N = [\"U1.15\", \"Y1.2\", \"C15.1\"];\n nets.GND.push(\"C14.2\", \"C15.2\");\n }\n if (debugHeader) {\n nets.VDDS.push(\"J4.1\");\n nets.SWDIO.push(\"J4.2\");\n nets.SWCLK.push(\"J4.3\");\n nets.GND.push(\"J4.4\", \"J4.6\", \"J4.7\");\n nets.RESET_N.push(\"J4.5\");\n }\n const unusedPins = [\n \"pin3\",\n \"pin4\",\n \"pin5\",\n \"pin6\",\n \"pin9\",\n \"pin10\",\n \"pin12\",\n \"pin19\",\n ...!externalLfCrystal ? [\"pin14\", \"pin15\"] : []\n ];\n const inductorParts = [\n [\"L1\", \"10uH\", LQM18DN100M70L, 7, 5, -10, -5, 0],\n [\"L2\", \"2.8nH\", LQP03TN2N8B02D, -6.8, 3.25, 5.5, 7, 0],\n [\"L3\", \"2.7nH\", LQG15HS2N7S02D, -12, 0, 12.3, 5, 270],\n [\"L4\", \"3.9nH\", LQG15HS3N9S02D, -15, 3.25, 14.8, 7, 180]\n ];\n const criticalRoutes = [\n { from: \"U1.1\", to: \"L2.2\", rf: true },\n { from: \"U1.1\", to: \"C26.1\", points: [{ x: -4.7, y: 1.25 }], rf: true },\n { from: \"L2.1\", to: \"C28.1\", rf: true },\n { from: \"L2.1\", to: \"C27.1\", points: [{ x: -1.9, y: 0 }], rf: true },\n { from: \"C28.2\", to: \"L4.1\", rf: true },\n { from: \"C28.2\", to: \"L3.1\", points: [{ x: 1.6, y: 0 }], rf: true },\n { from: \"L4.2\", to: \"ANT1.1\", rf: true },\n { from: \"U1.21\", to: \"Y2.1\" },\n {\n from: \"U1.22\",\n to: \"Y2.3\",\n points: [\n { x: -0.25019, y: 2.7 },\n { x: -1.6, y: 3.5 },\n { x: -1.6, y: 5.6375 }\n ]\n },\n ...externalLfCrystal ? [\n {\n from: \"U1.14\",\n to: \"Y1.1\",\n points: [\n { x: 2.7, y: -0.749935 },\n { x: 2.7, y: -2.4 }\n ]\n },\n { from: \"Y1.1\", to: \"C14.1\" },\n {\n from: \"U1.15\",\n to: \"Y1.2\",\n points: [\n { x: 2.8, y: -0.250063 },\n { x: 6.6549888, y: -0.250063 }\n ]\n },\n { from: \"Y1.2\", to: \"C15.1\" }\n ] : []\n ];\n const selector = (pin) =\u003e {\n const [ref, num] = pin.split(\".\");\n return `.${ref} \u003e .pin${num}`;\n };\n return /* @__PURE__ */ jsxDEV16(\"board\", {\n width: 44,\n height: 30,\n layers: 2,\n borderRadius: 1.5,\n title: \"CC2340R5 / radio reference\",\n schMaxTraceDistance: 20,\n schStyle: {\n defaultPassiveSize: \"md\",\n defaultCapacitorOrientation: \"vertical\"\n },\n autorouter: {\n local: true,\n groupMode: \"subcircuit\",\n algorithmFn: routeRemaining,\n traceClearance: 0.15\n },\n minTraceWidth: 0.15,\n defaultTraceWidth: 0.18,\n pcbStyle: { silkscreenFontSize: 0.65 },\n solderMaskColor: \"green\",\n children: [\n /* @__PURE__ */ jsxDEV16(\"schematicsheet\", {\n name: \"reference\",\n displayName: \"CC2340R5 radio reference\",\n sheetIndex: 0,\n sheetSize: \"A4\"\n }, undefined, false, undefined, this),\n Object.keys(sectionMembers).map((name) =\u003e /* @__PURE__ */ jsxDEV16(Fragment, {\n children: /* @__PURE__ */ jsxDEV16(\"schematicsection\", {\n name\n }, undefined, false, undefined, this)\n }, name, false, undefined, this)),\n /* @__PURE__ */ jsxDEV16(Note, {\n text: \"CC2340R5 / RADIO REFERENCE\",\n schX: -11.7,\n schY: 8.775,\n anchor: \"left\",\n fontSize: 0.65\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV16(Note, {\n text: `CC2340R52E0RGER · RGE QFN-24 · ${supplyVoltage.toFixed(1)} V supply`,\n schX: -11.7,\n schY: 8.06,\n anchor: \"left\",\n fontSize: 0.3\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV16(Note, {\n text: \"01 MCU\",\n schX: -11.7,\n schY: 7.02,\n anchor: \"left\",\n fontSize: 0.34\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV16(Note, {\n text: \"02 2.4 GHz FILTER \u0026 ANTENNA\",\n schX: 0.65,\n schY: 7.02,\n anchor: \"left\",\n fontSize: 0.34\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV16(Note, {\n text: \"03 DC/DC \u0026 DECOUPLING\",\n schX: -11.7,\n schY: -1.82,\n anchor: \"left\",\n fontSize: 0.34\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV16(Note, {\n text: \"04 CLOCKS\",\n schX: 0.975,\n schY: 0.91,\n anchor: \"left\",\n fontSize: 0.34\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV16(Note, {\n text: \"05 RESET \u0026 DEBUG\",\n schX: 0.975,\n schY: -4.03,\n anchor: \"left\",\n fontSize: 0.34\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV16(CC2340R52E0RGER, {\n name: \"U1\",\n ...schematic.U1,\n schX: -6.5,\n schY: 2.665,\n pcbX: 0,\n pcbY: 2,\n schWidth: 4.2,\n schHeight: 5,\n schPinStyle: Object.fromEntries(Array.from({ length: 25 }, (_5, i8) =\u003e [\n `pin${i8 + 1}`,\n {\n marginTop: 0.1,\n marginBottom: 0.1,\n marginLeft: 0.08,\n marginRight: 0.08\n }\n ])),\n schPinArrangement: {\n leftSide: [\n \"VDDS1\",\n \"VDDS2\",\n \"VDDS3\",\n \"VDDR1\",\n \"VDDR2\",\n \"VDDD\",\n \"DCDC\",\n \"GND\",\n \"EP\"\n ],\n rightSide: [\n \"ANT\",\n \"X48P\",\n \"X48N\",\n \"DIO3_X32P\",\n \"DIO4_X32N\",\n \"RSTN\",\n \"DIO16_SWDIO\",\n \"DIO17_SWDCK\"\n ],\n bottomSide: [\n \"DIO8\",\n \"DIO11\",\n \"DIO12\",\n \"DIO13\",\n \"DIO20_A11\",\n \"DIO21_A10\",\n \"DIO24_A7\",\n \"DIO6_A1\"\n ]\n },\n noConnect: unusedPins,\n pinAttributes: Object.fromEntries(unusedPins.map((pin) =\u003e [pin, { doNotConnect: true }]))\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV16(\"pinheader\", {\n name: \"J1\",\n ...schematic.J1,\n manufacturerPartNumber: \"TSW-102-07-G-S\",\n pinCount: 2,\n pitch: \"2.54mm\",\n schX: -10.4,\n schY: -3.51,\n schPinArrangement: { rightSide: [1, 2] },\n pcbX: 16,\n pcbY: 9,\n pinLabels: [supplyVoltage.toFixed(1).replace(\".\", \"V\"), \"GND\"],\n pinAttributes: {\n pin1: { providesPower: true, providesVoltage: supplyVoltage },\n pin2: { providesGround: true }\n }\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV16(\"capacitor\", {\n name: \"C1\",\n schRotation: 270,\n ...schematic.C1,\n capacitance: \"100nF\",\n footprint: \"0402\",\n pcbX: -1,\n pcbY: -1.8,\n schX: -10.4,\n schY: -5.59\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV16(\"capacitor\", {\n name: \"C2\",\n schRotation: 270,\n ...schematic.C2,\n capacitance: inputBulkCapacitance,\n maxVoltageRating: \"10V\",\n footprint: inputBulkCapacitance === \"22uF\" ? \"0805\" : \"0603\",\n pcbX: 12,\n pcbY: 1.5,\n schX: -8.775,\n schY: -5.59\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV16(CL05B104KO5NNNC, {\n name: \"C19\",\n schRotation: 270,\n ...schematic.C19,\n pcbX: 3.8,\n pcbY: 5.2,\n schX: -7.15,\n schY: -5.59\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV16(GRM033R61A104KE15D, {\n name: \"C20\",\n schRotation: 270,\n ...schematic.C20,\n pcbX: -3.6,\n pcbY: 5.2,\n schX: -5.525,\n schY: -5.59\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV16(GRM188Z71A106KA73D, {\n name: \"C21\",\n schRotation: 270,\n ...schematic.C21,\n pcbX: 8.8,\n pcbY: 8.8,\n schX: -4.55,\n schY: -3.38\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV16(CL05B104KO5NNNC, {\n name: \"C22\",\n schRotation: 270,\n ...schematic.C22,\n pcbX: 3.8,\n pcbY: 7,\n schX: -2.925,\n schY: -3.38\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV16(CL05B104KO5NNNC, {\n name: \"C25\",\n schRotation: 270,\n ...schematic.C25,\n pcbX: -3.8,\n pcbY: 0.5,\n schX: -1.3,\n schY: -3.38\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV16(CL05A105KA5NQNC, {\n name: \"C23\",\n schRotation: 270,\n ...schematic.C23,\n pcbX: 3.6,\n pcbY: 3,\n schX: -2.925,\n schY: -5.59\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV16(GJM0335C1H1R5BB01D, {\n name: \"C26\",\n schRotation: 270,\n ...schematic.C26,\n pcbX: -4.7,\n pcbY: 2.8,\n pcbRotation: 270,\n schX: 1.95,\n schY: 3.25\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV16(GJM0335C1H1R5BB01D, {\n name: \"C27\",\n schRotation: 270,\n ...schematic.C27,\n pcbX: -8.7,\n pcbY: 1.5,\n pcbRotation: 270,\n schX: 5.2,\n schY: 3.25\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV16(GJM1555C1H1R0BB01D, {\n name: \"C28\",\n ...schematic.C28,\n pcbX: -10.4,\n pcbY: 3.25,\n pcbRotation: 180,\n schX: 6.565,\n schY: 4.55,\n schRotation: 0\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV16(A_2450AT18A100E, {\n name: \"ANT1\",\n ...schematic.ANT1,\n pcbX: -19.5,\n pcbY: 3.25,\n pcbRotation: 180,\n schX: 11.375,\n schY: 5.2,\n noConnect: [\"pin2\"],\n pinAttributes: {\n pin1: {},\n ANT: {},\n pin2: { doNotConnect: true },\n NC: { doNotConnect: true }\n }\n }, undefined, false, undefined, this),\n inductorParts.map(([name, inductance, Part, pcbX, pcbY, schX, schY, rotation]) =\u003e {\n const imported = Part({ name }).props;\n return /* @__PURE__ */ jsxDEV16(\"inductor\", {\n name,\n ...schematic[name],\n inductance,\n footprint: imported.footprint,\n cadModel: imported.cadModel,\n manufacturerPartNumber: imported.manufacturerPartNumber,\n supplierPartNumbers: imported.supplierPartNumbers,\n pcbX,\n pcbY,\n pcbRotation: rotation,\n schX: schX * 0.65,\n schY: schY * 0.65,\n schRotation: name === \"L3\" ? 270 : name === \"L2\" ? 180 : 0\n }, name, false, undefined, this);\n }),\n /* @__PURE__ */ jsxDEV16(Note, {\n text: \"Values retained from the pedometer RF network.\",\n schX: 0.65,\n schY: 2.015,\n anchor: \"left\",\n fontSize: 0.24\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV16(Note, {\n text: \"Antenna match requires tuning on the assembled PCB.\",\n schX: 0.65,\n schY: 1.69,\n anchor: \"left\",\n fontSize: 0.24\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV16(ABM11W_48_0000MHZ_8_D1X_T3, {\n name: \"Y2\",\n ...schematic.Y2,\n pcbX: 0,\n pcbY: 7,\n pcbRotation: 90,\n schX: 3.38,\n schY: -0.65\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV16(Note, {\n text: \"48 MHz / CL = 8 pF in SysConfig\",\n schX: 0.65,\n schY: 0.52,\n anchor: \"left\",\n fontSize: 0.25\n }, undefined, false, undefined, this),\n externalLfCrystal ? /* @__PURE__ */ jsxDEV16(Fragment2, {\n children: [\n /* @__PURE__ */ jsxDEV16(ABS07_32_768KHZ_7_T, {\n name: \"Y1\",\n ...schematic.Y1,\n pcbX: 5.5,\n pcbY: -0.8,\n schX: 8.775,\n schY: -0.65\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV16(\"capacitor\", {\n name: \"C14\",\n schRotation: 270,\n ...schematic.C14,\n capacitance: \"12pF\",\n footprint: \"0402\",\n pcbX: 4.5,\n pcbY: -2.8,\n schX: 7.475,\n schY: -2.275\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV16(\"capacitor\", {\n name: \"C15\",\n schRotation: 270,\n ...schematic.C15,\n capacitance: \"15pF\",\n footprint: \"0402\",\n pcbX: 6.6,\n pcbY: -2.8,\n schX: 10.075,\n schY: -2.275\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV16(Note, {\n text: \"32.768 kHz / external LF clock\",\n schX: 6.5,\n schY: 0.52,\n anchor: \"left\",\n fontSize: 0.25\n }, undefined, false, undefined, this)\n ]\n }, undefined, true, undefined, this) : null,\n /* @__PURE__ */ jsxDEV16(\"resistor\", {\n name: \"R14\",\n ...schematic.R14,\n resistance: resetPullupResistance,\n footprint: \"0402\",\n pcbX: 1,\n pcbY: -3.5,\n pcbRotation: 90,\n schX: 2.6,\n schY: -5.33,\n schRotation: 270\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV16(CL05B104KO5NNNC, {\n name: \"C24\",\n schRotation: 270,\n ...schematic.C24,\n pcbX: 3,\n pcbY: -5,\n schX: 2.6,\n schY: -7.15\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV16(\"testpoint\", {\n doNotPlace: true,\n name: \"TP1\",\n ...schematic.TP1,\n footprint: /* @__PURE__ */ jsxDEV16(\"footprint\", {\n children: /* @__PURE__ */ jsxDEV16(\"smtpad\", {\n portHints: [\"pin1\"],\n pcbX: 0,\n pcbY: 0,\n shape: \"circle\",\n radius: 0.6\n }, undefined, false, undefined, this)\n }, undefined, false, undefined, this),\n pcbX: -4,\n pcbY: -8,\n schX: 5.85,\n schY: -5.85\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV16(\"testpoint\", {\n doNotPlace: true,\n name: \"TP2\",\n ...schematic.TP2,\n footprint: /* @__PURE__ */ jsxDEV16(\"footprint\", {\n children: /* @__PURE__ */ jsxDEV16(\"smtpad\", {\n portHints: [\"pin1\"],\n pcbX: 0,\n pcbY: 0,\n shape: \"circle\",\n radius: 0.6\n }, undefined, false, undefined, this)\n }, undefined, false, undefined, this),\n pcbX: 0,\n pcbY: -8,\n schX: 5.85,\n schY: -7.15\n }, undefined, false, undefined, this),\n debugHeader ? /* @__PURE__ */ jsxDEV16(BM05B_SRSS_TB_LF__SN_, {\n name: \"J4\",\n ...schematic.J4,\n schWidth: 2.2,\n schHeight: 2.4,\n schPinStyle: Object.fromEntries(Array.from({ length: 7 }, (_5, i8) =\u003e [\n `pin${i8 + 1}`,\n { marginTop: 0.08, marginBottom: 0.08 }\n ])),\n schX: 10.075,\n schY: -6.37,\n schPinArrangement: { leftSide: [1, 2, 3, 4, 5], bottomSide: [6, 7] },\n pcbX: 10,\n pcbY: -9,\n pinLabels: {\n pin1: [\"VTREF\"],\n pin2: [\"SWDIO\"],\n pin3: [\"SWCLK\"],\n pin4: [\"GND\"],\n pin5: [\"RESET_N\"],\n pin6: [\"SHIELD1\"],\n pin7: [\"SHIELD2\"]\n },\n pinAttributes: {\n pin1: { requiresPower: true, requiresVoltage: supplyVoltage }\n }\n }, undefined, false, undefined, this) : null,\n criticalRoutes.map(({ from: from2, to: to2, points, rf: rf2 }) =\u003e /* @__PURE__ */ jsxDEV16(\"trace\", {\n name: `${from2.replaceAll(\".\", \"_\")}_to_${to2.replaceAll(\".\", \"_\")}`,\n from: selector(from2),\n to: selector(to2),\n pcbPath: points ?? [],\n maxViaCount: 0,\n thickness: rf2 ? 0.2 : 0.15\n }, `route:${from2}:${to2}`, false, undefined, this)),\n Object.keys(nets).map((name) =\u003e /* @__PURE__ */ jsxDEV16(Fragment2, {\n children: /* @__PURE__ */ jsxDEV16(\"net\", {\n name,\n isGroundNet: name === \"GND\"\n }, undefined, false, undefined, this)\n }, name, false, undefined, this)),\n Object.entries(nets).flatMap(([net, pins]) =\u003e pins.map((pin) =\u003e {\n const [ref, num] = pin.split(\".\");\n return /* @__PURE__ */ jsxDEV16(\"trace\", {\n from: `.${ref} \u003e .pin${num}`,\n to: `net.${net}`,\n schDisplayLabel: net\n }, `${net}:${pin}`, false, undefined, this);\n })),\n Object.entries({\n U1: [0.6, 4.9],\n Y2: [-1.8, 8.8],\n Y1: [5.5, 1.1],\n ANT1: [-19, 5.5],\n C19: [3.8, 6.2],\n C20: [-3.6, 6.4],\n C21: [8.8, 10.4],\n C22: [3.8, 8.2],\n C23: [5.1, 3],\n C24: [3, -6.2],\n C25: [-3.8, -0.8],\n C26: [-4.6, 4.1],\n C27: [-8.7, 0.2],\n C28: [-10.4, 4.3],\n L1: [7.2, 6.5],\n L2: [-6.8, 4.3],\n L3: [-12, -1.8],\n L4: [-15, 4.3],\n ...debugHeader ? { J4: [10, -12] } : {}\n }).filter(([name]) =\u003e externalLfCrystal || name !== \"Y1\").map(([text, [pcbX, pcbY]]) =\u003e /* @__PURE__ */ jsxDEV16(Fragment2, {\n children: /* @__PURE__ */ jsxDEV16(\"silkscreentext\", {\n text,\n pcbX,\n pcbY,\n fontSize: 0.5\n }, undefined, false, undefined, this)\n }, `label:${text}`, false, undefined, this)),\n /* @__PURE__ */ jsxDEV16(\"silkscreentext\", {\n text: \"CC2340R5 REFERENCE\",\n pcbX: 1,\n pcbY: 12.3,\n fontSize: 0.85\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV16(\"silkscreentext\", {\n text: \"VDDS / GND\",\n pcbX: 16,\n pcbY: 6.5,\n fontSize: 0.65\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV16(\"silkscreentext\", {\n text: \"SWDIO\",\n pcbX: -4,\n pcbY: -10,\n fontSize: 0.6\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV16(\"silkscreentext\", {\n text: \"SWCLK\",\n pcbX: 0,\n pcbY: -10,\n fontSize: 0.6\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV16(\"keepout\", {\n shape: \"rect\",\n pcbX: -20,\n pcbY: 3.25,\n width: 4,\n height: 7,\n layers: [\"top\", \"bottom\"],\n excludeRefs: [\".ANT1\"]\n }, undefined, false, undefined, this),\n /* @__PURE__ */ jsxDEV16(Note, {\n text: \"Derived from imrishabh18/pedometer 1.1.8\",\n schX: -11.7,\n schY: -9.165,\n anchor: \"left\",\n fontSize: 0.25\n }, undefined, false, undefined, this)\n ]\n }, undefined, true, undefined, this);\n}\nexport {\n referenceProps,\n propsSchema,\n propsJsonSchema,\n Cc2340Reference as default\n};\n","content_mimetype":"application/javascript","created_at":"2026-11-10T22:10:54.769Z"}; window.SSR_PACKAGE_BUILDS = []; window.SSR_PACKAGE_ROUTE = {"author":"ShiboSoftwareDev","packageName":"cc2340r5-reference-design","packageNameWithScope":"ShiboSoftwareDev/cc2340r5-reference-design","version":null,"isLegacyRoute":false,"kind":"file","filePath":"dist/index.js"};

ShiboSoftwareDev/cc2340r5-reference-design

A CC2340R5 wireless MCU reference board integrating a 2.4 GHz RF matching network and antenna, 48 MHz/optional 32.768 kHz crystals, DC/DC inductors, decoupling capacitors, reset circuitry, power input, and SWD debug connector.

Version
1.4.0
License
unset
Stars
0

dist/index.js

var __create = Object.create;
var __getProtoOf = Object.getPrototypeOf;
var __defProp = Object.defineProperty;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __hasOwnProp = Object.prototype.hasOwnProperty;
function __accessProp(key) {
  return this[key];
}
var __toESMCache_node;
var __toESMCache_esm;
var __toESM = (mod, isNodeMode, target) => {
  var canCache = mod != null && typeof mod === "object";
  if (canCache) {
    var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
    var cached = cache.get(mod);
    if (cached)
      return cached;
  }
  target = mod != null ? __create(__getProtoOf(mod)) : {};
  const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
  for (let key of __getOwnPropNames(mod))
    if (!__hasOwnProp.call(to, key))
      __defProp(to, key, {
        get: __accessProp.bind(mod, key),
        enumerable: true
      });
  if (canCache)
    cache.set(mod, to);
  return to;
};
var __toCommonJS = (from) => {
  var entry = (__moduleCache ??= new WeakMap).get(from), desc;
  if (entry)
    return entry;
  entry = __defProp({}, "__esModule", { value: true });
  if (from && typeof from === "object" || typeof from === "function") {
    for (var key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(entry, key))
        __defProp(entry, key, {
          get: __accessProp.bind(from, key),
          enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
        });
  }
  __moduleCache.set(from, entry);
  return entry;
};
var __moduleCache;
var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
var __returnValue = (v) => v;
function __exportSetter(name, newValue) {
  this[name] = __returnValue.bind(null, newValue);
}
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, {
      get: all[name],
      enumerable: true,
      configurable: true,
      set: __exportSetter.bind(all, name)
    });
};
var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
}) : x)(function(x) {
  if (typeof require !== "undefined")
    return require.apply(this, arguments);
  throw Error('Dynamic require of "' + x + '" is not supported');
});

// node_modules/is-buffer/index.js
var require_is_buffer = __commonJS((exports, module) => {
  /*!
   * Determine if an object is a Buffer
   *
   * @author   Feross Aboukhadijeh <https://feross.org>
   * @license  MIT
   */
  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));
  }
});

// node_modules/kind-of/index.js
var require_kind_of = __commonJS((exports, module) => {
  var isBuffer = require_is_buffer();
  var toString2 = Object.prototype.toString;
  module.exports = function kindOf(val) {
    if (typeof val === "undefined") {
      return "undefined";
    }
    if (val === null) {
      return "null";
    }
    if (val === true || val === false || 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 !== "undefined" && Array.isArray(val)) {
      return "array";
    }
    if (val instanceof RegExp) {
      return "regexp";
    }
    if (val instanceof Date) {
      return "date";
    }
    var type = toString2.call(val);
    if (type === "[object RegExp]") {
      return "regexp";
    }
    if (type === "[object Date]") {
      return "date";
    }
    if (type === "[object Arguments]") {
      return "arguments";
    }
    if (type === "[object Error]") {
      return "error";
    }
    if (isBuffer(val)) {
      return "buffer";
    }
    if (type === "[object Set]") {
      return "set";
    }
    if (type === "[object WeakSet]") {
      return "weakset";
    }
    if (type === "[object Map]") {
      return "map";
    }
    if (type === "[object WeakMap]") {
      return "weakmap";
    }
    if (type === "[object Symbol]") {
      return "symbol";
    }
    if (type === "[object Int8Array]") {
      return "int8array";
    }
    if (type === "[object Uint8Array]") {
      return "uint8array";
    }
    if (type === "[object Uint8ClampedArray]") {
      return "uint8clampedarray";
    }
    if (type === "[object Int16Array]") {
      return "int16array";
    }
    if (type === "[object Uint16Array]") {
      return "uint16array";
    }
    if (type === "[object Int32Array]") {
      return "int32array";
    }
    if (type === "[object Uint32Array]") {
      return "uint32array";
    }
    if (type === "[object Float32Array]") {
      return "float32array";
    }
    if (type === "[object Float64Array]") {
      return "float64array";
    }
    return "object";
  };
});

// node_modules/rename-keys/index.js
var require_rename_keys = __commonJS((exports, module) => {
  (function() {
    function rename(obj, fn) {
      if (typeof fn !== "function") {
        return obj;
      }
      var res = {};
      for (var key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
          res[fn(key, obj[key]) || key] = obj[key];
        }
      }
      return res;
    }
    if (typeof module !== "undefined" && module.exports) {
      module.exports = rename;
    } else {
      if (typeof define === "function" && define.amd) {
        define([], function() {
          return rename;
        });
      } else {
        window.rename = rename;
      }
    }
  })();
});

// node_modules/deep-rename-keys/index.js
var require_deep_rename_keys = __commonJS((exports, module) => {
  /*!
   * deep-rename-keys <https://github.com/jonschlinkert/deep-rename-keys>
   *
   * Copyright (c) 2015 Jon Schlinkert, contributors.
   * Licensed under the MIT license.
   */
  var typeOf = require_kind_of();
  var rename = require_rename_keys();
  module.exports = function renameDeep(obj, cb) {
    var type = typeOf(obj);
    if (type !== "object" && type !== "array") {
      throw new Error("expected an object");
    }
    var res = [];
    if (type === "object") {
      obj = rename(obj, cb);
      res = {};
    }
    for (var key in obj) {
      if (obj.hasOwnProperty(key)) {
        var val = obj[key];
        if (typeOf(val) === "object" || typeOf(val) === "array") {
          res[key] = renameDeep(val, cb);
        } else {
          res[key] = val;
        }
      }
    }
    return res;
  };
});

// node_modules/eventemitter3/index.js
var require_eventemitter3 = __commonJS((exports, module) => {
  var has = Object.prototype.hasOwnProperty;
  var prefix = "~";
  function Events() {}
  if (Object.create) {
    Events.prototype = Object.create(null);
    if (!new Events().__proto__)
      prefix = false;
  }
  function EE(fn, context, once) {
    this.fn = fn;
    this.context = context;
    this.once = once || false;
  }
  function EventEmitter() {
    this._events = new Events;
    this._eventsCount = 0;
  }
  EventEmitter.prototype.eventNames = function eventNames() {
    var names = [], events, name;
    if (this._eventsCount === 0)
      return names;
    for (name in events = this._events) {
      if (has.call(events, name))
        names.push(prefix ? name.slice(1) : name);
    }
    if (Object.getOwnPropertySymbols) {
      return names.concat(Object.getOwnPropertySymbols(events));
    }
    return names;
  };
  EventEmitter.prototype.listeners = function listeners(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 i = 0, l2 = available.length, ee = new Array(l2);i < l2; i++) {
      ee[i] = available[i].fn;
    }
    return ee;
  };
  EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
    var evt = prefix ? prefix + event : event;
    if (!this._events[evt])
      return false;
    var listeners = this._events[evt], len = arguments.length, args, i;
    if (listeners.fn) {
      if (listeners.once)
        this.removeListener(event, listeners.fn, undefined, true);
      switch (len) {
        case 1:
          return listeners.fn.call(listeners.context), true;
        case 2:
          return listeners.fn.call(listeners.context, a1), true;
        case 3:
          return listeners.fn.call(listeners.context, a1, a2), true;
        case 4:
          return listeners.fn.call(listeners.context, a1, a2, a3), true;
        case 5:
          return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
        case 6:
          return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
      }
      for (i = 1, args = new Array(len - 1);i < len; i++) {
        args[i - 1] = arguments[i];
      }
      listeners.fn.apply(listeners.context, args);
    } else {
      var length = listeners.length, j;
      for (i = 0;i < length; i++) {
        if (listeners[i].once)
          this.removeListener(event, listeners[i].fn, undefined, true);
        switch (len) {
          case 1:
            listeners[i].fn.call(listeners[i].context);
            break;
          case 2:
            listeners[i].fn.call(listeners[i].context, a1);
            break;
          case 3:
            listeners[i].fn.call(listeners[i].context, a1, a2);
            break;
          case 4:
            listeners[i].fn.call(listeners[i].context, a1, a2, a3);
            break;
          default:
            if (!args)
              for (j = 1, args = new Array(len - 1);j < len; j++) {
                args[j - 1] = arguments[j];
              }
            listeners[i].fn.apply(listeners[i].context, args);
        }
      }
    }
    return true;
  };
  EventEmitter.prototype.on = function on(event, fn, context) {
    var listener = new EE(fn, context || this), evt = prefix ? prefix + event : event;
    if (!this._events[evt])
      this._events[evt] = listener, this._eventsCount++;
    else if (!this._events[evt].fn)
      this._events[evt].push(listener);
    else
      this._events[evt] = [this._events[evt], listener];
    return this;
  };
  EventEmitter.prototype.once = function once(event, fn, context) {
    var listener = new EE(fn, context || this, true), evt = prefix ? prefix + event : event;
    if (!this._events[evt])
      this._events[evt] = listener, this._eventsCount++;
    else if (!this._events[evt].fn)
      this._events[evt].push(listener);
    else
      this._events[evt] = [this._events[evt], listener];
    return this;
  };
  EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
    var evt = prefix ? prefix + event : event;
    if (!this._events[evt])
      return this;
    if (!fn) {
      if (--this._eventsCount === 0)
        this._events = new Events;
      else
        delete this._events[evt];
      return this;
    }
    var listeners = this._events[evt];
    if (listeners.fn) {
      if (listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context)) {
        if (--this._eventsCount === 0)
          this._events = new Events;
        else
          delete this._events[evt];
      }
    } else {
      for (var i = 0, events = [], length = listeners.length;i < length; i++) {
        if (listeners[i].fn !== fn || once && !listeners[i].once || context && listeners[i].context !== context) {
          events.push(listeners[i]);
        }
      }
      if (events.length)
        this._events[evt] = events.length === 1 ? events[0] : events;
      else if (--this._eventsCount === 0)
        this._events = new Events;
      else
        delete this._events[evt];
    }
    return this;
  };
  EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
    var evt;
    if (event) {
      evt = prefix ? prefix + event : event;
      if (this._events[evt]) {
        if (--this._eventsCount === 0)
          this._events = new Events;
        else
          delete this._events[evt];
      }
    } else {
      this._events = new Events;
      this._eventsCount = 0;
    }
    return this;
  };
  EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  EventEmitter.prototype.addListener = EventEmitter.prototype.on;
  EventEmitter.prototype.setMaxListeners = function setMaxListeners() {
    return this;
  };
  EventEmitter.prefixed = prefix;
  EventEmitter.EventEmitter = EventEmitter;
  if (typeof module !== "undefined") {
    module.exports = EventEmitter;
  }
});

// node_modules/xml-lexer/dist/lexer.js
var require_lexer = __commonJS((exports, module) => {
  function _defineProperty(obj, key, value) {
    if (key in obj) {
      Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
    } else {
      obj[key] = value;
    }
    return obj;
  }
  var EventEmitter = require_eventemitter3();
  var noop = function noop2() {};
  var State = {
    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"
  };
  var 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"
  };
  var Type = {
    text: "text",
    openTag: "open-tag",
    closeTag: "close-tag",
    attributeName: "attribute-name",
    attributeValue: "attribute-value"
  };
  var charToAction = {
    " ": Action.space,
    "\t": Action.space,
    "\n": Action.space,
    "\r": Action.space,
    "<": Action.lt,
    ">": Action.gt,
    '"': Action.quote,
    "'": Action.quote,
    "=": Action.equal,
    "/": Action.slash
  };
  var getAction = function getAction2(char) {
    return charToAction[char] || Action.char;
  };
  var create = function create2(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: false }, options);
    var lexer = new EventEmitter;
    var state = State.data;
    var data = "";
    var tagName = "";
    var attrName = "";
    var attrValue = "";
    var isClosing = "";
    var openingQuote = "";
    var emit = function emit2(type, value) {
      if (tagName[0] === "?" || tagName[0] === "!") {
        return;
      }
      var event = { type, value };
      if (options.debug) {
        console.log("emit:", event);
      }
      lexer.emit("data", event);
    };
    lexer.stateMachine = (_lexer$stateMachine = {}, _defineProperty(_lexer$stateMachine, State.data, (_State$data = {}, _defineProperty(_State$data, Action.lt, function() {
      if (data.trim()) {
        emit(Type.text, data);
      }
      tagName = "";
      isClosing = false;
      state = State.tagBegin;
    }), _defineProperty(_State$data, Action.char, function(char) {
      data += char;
    }), _State$data)), _defineProperty(_lexer$stateMachine, State.cdata, _defineProperty({}, Action.char, function(char) {
      data += char;
      if (data.substr(-3) === "]]>") {
        emit(Type.text, data.slice(0, -3));
        data = "";
        state = State.data;
      }
    })), _defineProperty(_lexer$stateMachine, State.tagBegin, (_State$tagBegin = {}, _defineProperty(_State$tagBegin, Action.space, noop), _defineProperty(_State$tagBegin, Action.char, function(char) {
      tagName = char;
      state = State.tagName;
    }), _defineProperty(_State$tagBegin, Action.slash, function() {
      tagName = "";
      isClosing = true;
    }), _State$tagBegin)), _defineProperty(_lexer$stateMachine, State.tagName, (_State$tagName = {}, _defineProperty(_State$tagName, Action.space, function() {
      if (isClosing) {
        state = State.tagEnd;
      } else {
        state = State.attributeNameStart;
        emit(Type.openTag, tagName);
      }
    }), _defineProperty(_State$tagName, Action.gt, function() {
      if (isClosing) {
        emit(Type.closeTag, tagName);
      } else {
        emit(Type.openTag, tagName);
      }
      data = "";
      state = State.data;
    }), _defineProperty(_State$tagName, Action.slash, function() {
      state = State.tagEnd;
      emit(Type.openTag, tagName);
    }), _defineProperty(_State$tagName, Action.char, function(char) {
      tagName += char;
      if (tagName === "![CDATA[") {
        state = State.cdata;
        data = "";
        tagName = "";
      }
    }), _State$tagName)), _defineProperty(_lexer$stateMachine, State.tagEnd, (_State$tagEnd = {}, _defineProperty(_State$tagEnd, Action.gt, function() {
      emit(Type.closeTag, tagName);
      data = "";
      state = State.data;
    }), _defineProperty(_State$tagEnd, Action.char, noop), _State$tagEnd)), _defineProperty(_lexer$stateMachine, State.attributeNameStart, (_State$attributeNameS = {}, _defineProperty(_State$attributeNameS, Action.char, function(char) {
      attrName = char;
      state = State.attributeName;
    }), _defineProperty(_State$attributeNameS, Action.gt, function() {
      data = "";
      state = State.data;
    }), _defineProperty(_State$attributeNameS, Action.space, noop), _defineProperty(_State$attributeNameS, Action.slash, function() {
      isClosing = true;
      state = State.tagEnd;
    }), _State$attributeNameS)), _defineProperty(_lexer$stateMachine, State.attributeName, (_State$attributeName = {}, _defineProperty(_State$attributeName, Action.space, function() {
      state = State.attributeNameEnd;
    }), _defineProperty(_State$attributeName, Action.equal, function() {
      emit(Type.attributeName, attrName);
      state = State.attributeValueBegin;
    }), _defineProperty(_State$attributeName, Action.gt, function() {
      attrValue = "";
      emit(Type.attributeName, attrName);
      emit(Type.attributeValue, attrValue);
      data = "";
      state = State.data;
    }), _defineProperty(_State$attributeName, Action.slash, function() {
      isClosing = true;
      attrValue = "";
      emit(Type.attributeName, attrName);
      emit(Type.attributeValue, attrValue);
      state = State.tagEnd;
    }), _defineProperty(_State$attributeName, Action.char, function(char) {
      attrName += char;
    }), _State$attributeName)), _defineProperty(_lexer$stateMachine, State.attributeNameEnd, (_State$attributeNameE = {}, _defineProperty(_State$attributeNameE, Action.space, noop), _defineProperty(_State$attributeNameE, Action.equal, function() {
      emit(Type.attributeName, attrName);
      state = State.attributeValueBegin;
    }), _defineProperty(_State$attributeNameE, Action.gt, function() {
      attrValue = "";
      emit(Type.attributeName, attrName);
      emit(Type.attributeValue, attrValue);
      data = "";
      state = State.data;
    }), _defineProperty(_State$attributeNameE, Action.char, function(char) {
      attrValue = "";
      emit(Type.attributeName, attrName);
      emit(Type.attributeValue, attrValue);
      attrName = char;
      state = State.attributeName;
    }), _State$attributeNameE)), _defineProperty(_lexer$stateMachine, State.attributeValueBegin, (_State$attributeValue = {}, _defineProperty(_State$attributeValue, Action.space, noop), _defineProperty(_State$attributeValue, Action.quote, function(char) {
      openingQuote = char;
      attrValue = "";
      state = State.attributeValue;
    }), _defineProperty(_State$attributeValue, Action.gt, function() {
      attrValue = "";
      emit(Type.attributeValue, attrValue);
      data = "";
      state = State.data;
    }), _defineProperty(_State$attributeValue, Action.char, function(char) {
      openingQuote = "";
      attrValue = char;
      state = State.attributeValue;
    }), _State$attributeValue)), _defineProperty(_lexer$stateMachine, State.attributeValue, (_State$attributeValue2 = {}, _defineProperty(_State$attributeValue2, Action.space, function(char) {
      if (openingQuote) {
        attrValue += char;
      } else {
        emit(Type.attributeValue, attrValue);
        state = State.attributeNameStart;
      }
    }), _defineProperty(_State$attributeValue2, Action.quote, function(char) {
      if (openingQuote === char) {
        emit(Type.attributeValue, attrValue);
        state = State.attributeNameStart;
      } else {
        attrValue += char;
      }
    }), _defineProperty(_State$attributeValue2, Action.gt, function(char) {
      if (openingQuote) {
        attrValue += char;
      } else {
        emit(Type.attributeValue, attrValue);
        data = "";
        state = State.data;
      }
    }), _defineProperty(_State$attributeValue2, Action.slash, function(char) {
      if (openingQuote) {
        attrValue += char;
      } else {
        emit(Type.attributeValue, attrValue);
        isClosing = true;
        state = State.tagEnd;
      }
    }), _defineProperty(_State$attributeValue2, Action.char, function(char) {
      attrValue += char;
    }), _State$attributeValue2)), _lexer$stateMachine);
    var step = function step2(char) {
      if (options.debug) {
        console.log(state, char);
      }
      var actions = lexer.stateMachine[state];
      var action = actions[getAction(char)] || actions[Action.error] || actions[Action.char];
      action(char);
    };
    lexer.write = function(str) {
      var len = str.length;
      for (var i = 0;i < len; i++) {
        step(str[i]);
      }
    };
    return lexer;
  };
  module.exports = {
    State,
    Action,
    Type,
    create
  };
});

// node_modules/xml-reader/dist/reader.js
var require_reader = __commonJS((exports, module) => {
  var EventEmitter = require_eventemitter3();
  var Lexer = require_lexer();
  var Type = Lexer.Type;
  var NodeType = {
    element: "element",
    text: "text"
  };
  var createNode = function createNode2(params) {
    return Object.assign({
      name: "",
      type: NodeType.element,
      value: "",
      parent: null,
      attributes: {},
      children: []
    }, params);
  };
  var create = function create2(options) {
    options = Object.assign({
      stream: false,
      parentNodes: true,
      doneEvent: "done",
      tagPrefix: "tag:",
      emitTopLevelOnly: false,
      debug: false
    }, options);
    var lexer = undefined, rootNode = undefined, current = undefined, attrName = undefined;
    var reader = new EventEmitter;
    var handleLexerData = function handleLexerData2(data) {
      switch (data.type) {
        case Type.openTag:
          if (current === null) {
            current = rootNode;
            current.name = data.value;
          } else {
            var node = createNode({
              name: data.value,
              parent: current
            });
            current.children.push(node);
            current = node;
          }
          break;
        case Type.closeTag:
          var parent = current.parent;
          if (!options.parentNodes) {
            current.parent = null;
          }
          if (current.name !== data.value) {
            break;
          }
          if (options.stream && parent === rootNode) {
            rootNode.children = [];
            current.parent = null;
          }
          if (!options.emitTopLevelOnly || parent === rootNode) {
            reader.emit(options.tagPrefix + current.name, current);
            reader.emit("tag", current.name, current);
          }
          if (current === rootNode) {
            lexer.removeAllListeners("data");
            reader.emit(options.doneEvent, current);
            rootNode = null;
          }
          current = parent;
          break;
        case Type.text:
          if (current) {
            current.children.push(createNode({
              type: NodeType.text,
              value: data.value,
              parent: options.parentNodes ? current : null
            }));
          }
          break;
        case Type.attributeName:
          attrName = data.value;
          current.attributes[attrName] = "";
          break;
        case Type.attributeValue:
          current.attributes[attrName] = data.value;
          break;
      }
    };
    reader.reset = function() {
      lexer = Lexer.create({ debug: options.debug });
      lexer.on("data", handleLexerData);
      rootNode = createNode();
      current = null;
      attrName = "";
      reader.parse = lexer.write;
    };
    reader.reset();
    return reader;
  };
  var parseSync = function parseSync2(xml, options) {
    options = Object.assign({}, options, { stream: false, tagPrefix: ":" });
    var reader = create(options);
    var res = undefined;
    reader.on("done", function(ast) {
      res = ast;
    });
    reader.parse(xml);
    return res;
  };
  module.exports = {
    parseSync,
    create,
    NodeType
  };
});

// node:buffer
var exports_buffer = {};
__export(exports_buffer, {
  transcode: () => transcode,
  resolveObjectURL: () => resolveObjectURL,
  kStringMaxLength: () => kStringMaxLength,
  kMaxLength: () => kMaxLength,
  isUtf8: () => isUtf8,
  isAscii: () => isAscii,
  default: () => buffer_default,
  constants: () => constants,
  btoa: () => btoa,
  atob: () => atob2,
  INSPECT_MAX_BYTES: () => INSPECT_MAX_BYTES,
  File: () => File,
  Buffer: () => Buffer2,
  Blob: () => Blob
});
function getLens(b64) {
  var len2 = b64.length;
  if (len2 % 4 > 0)
    throw Error("Invalid string. Length must be a multiple of 4");
  var validLen = b64.indexOf("=");
  if (validLen === -1)
    validLen = len2;
  var placeHoldersLen = validLen === len2 ? 0 : 4 - validLen % 4;
  return [validLen, placeHoldersLen];
}
function _byteLength(validLen, placeHoldersLen) {
  return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
}
function toByteArray(b64) {
  var tmp, lens = getLens(b64), validLen = lens[0], placeHoldersLen = lens[1], arr = new Uint8Array(_byteLength(validLen, placeHoldersLen)), curByte = 0, len2 = placeHoldersLen > 0 ? validLen - 4 : validLen, i2;
  for (i2 = 0;i2 < len2; i2 += 4)
    tmp = revLookup[b64.charCodeAt(i2)] << 18 | revLookup[b64.charCodeAt(i2 + 1)] << 12 | revLookup[b64.charCodeAt(i2 + 2)] << 6 | revLookup[b64.charCodeAt(i2 + 3)], arr[curByte++] = tmp >> 16 & 255, arr[curByte++] = tmp >> 8 & 255, arr[curByte++] = tmp & 255;
  if (placeHoldersLen === 2)
    tmp = revLookup[b64.charCodeAt(i2)] << 2 | revLookup[b64.charCodeAt(i2 + 1)] >> 4, arr[curByte++] = tmp & 255;
  if (placeHoldersLen === 1)
    tmp = revLookup[b64.charCodeAt(i2)] << 10 | revLookup[b64.charCodeAt(i2 + 1)] << 4 | revLookup[b64.charCodeAt(i2 + 2)] >> 2, arr[curByte++] = tmp >> 8 & 255, arr[curByte++] = tmp & 255;
  return arr;
}
function tripletToBase64(num) {
  return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63];
}
function encodeChunk(uint83, start, end) {
  var tmp, output = [];
  for (var i2 = start;i2 < end; i2 += 3)
    tmp = (uint83[i2] << 16 & 16711680) + (uint83[i2 + 1] << 8 & 65280) + (uint83[i2 + 2] & 255), output.push(tripletToBase64(tmp));
  return output.join("");
}
function fromByteArray(uint83) {
  var tmp, len2 = uint83.length, extraBytes = len2 % 3, parts = [], maxChunkLength = 16383;
  for (var i2 = 0, len22 = len2 - extraBytes;i2 < len22; i2 += maxChunkLength)
    parts.push(encodeChunk(uint83, i2, i2 + maxChunkLength > len22 ? len22 : i2 + maxChunkLength));
  if (extraBytes === 1)
    tmp = uint83[len2 - 1], parts.push(lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "==");
  else if (extraBytes === 2)
    tmp = (uint83[len2 - 2] << 8) + uint83[len2 - 1], parts.push(lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "=");
  return parts.join("");
}
function read(buffer, offset, isLE, mLen, nBytes) {
  var e2, m, eLen = nBytes * 8 - mLen - 1, eMax = (1 << eLen) - 1, eBias = eMax >> 1, nBits = -7, i2 = isLE ? nBytes - 1 : 0, d = isLE ? -1 : 1, s = buffer[offset + i2];
  i2 += d, e2 = s & (1 << -nBits) - 1, s >>= -nBits, nBits += eLen;
  for (;nBits > 0; e2 = e2 * 256 + buffer[offset + i2], i2 += d, nBits -= 8)
    ;
  m = e2 & (1 << -nBits) - 1, e2 >>= -nBits, nBits += mLen;
  for (;nBits > 0; m = m * 256 + buffer[offset + i2], i2 += d, nBits -= 8)
    ;
  if (e2 === 0)
    e2 = 1 - eBias;
  else if (e2 === eMax)
    return m ? NaN : (s ? -1 : 1) * (1 / 0);
  else
    m = m + Math.pow(2, mLen), e2 = e2 - eBias;
  return (s ? -1 : 1) * m * Math.pow(2, e2 - mLen);
}
function write(buffer, value, offset, isLE, mLen, nBytes) {
  var e2, m, c2, eLen = nBytes * 8 - mLen - 1, eMax = (1 << eLen) - 1, eBias = eMax >> 1, rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0, i2 = isLE ? 0 : nBytes - 1, d = isLE ? 1 : -1, s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
  if (value = Math.abs(value), isNaN(value) || value === 1 / 0)
    m = isNaN(value) ? 1 : 0, e2 = eMax;
  else {
    if (e2 = Math.floor(Math.log(value) / Math.LN2), value * (c2 = Math.pow(2, -e2)) < 1)
      e2--, c2 *= 2;
    if (e2 + eBias >= 1)
      value += rt / c2;
    else
      value += rt * Math.pow(2, 1 - eBias);
    if (value * c2 >= 2)
      e2++, c2 /= 2;
    if (e2 + eBias >= eMax)
      m = 0, e2 = eMax;
    else if (e2 + eBias >= 1)
      m = (value * c2 - 1) * Math.pow(2, mLen), e2 = e2 + eBias;
    else
      m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen), e2 = 0;
  }
  for (;mLen >= 8; buffer[offset + i2] = m & 255, i2 += d, m /= 256, mLen -= 8)
    ;
  e2 = e2 << mLen | m, eLen += mLen;
  for (;eLen > 0; buffer[offset + i2] = e2 & 255, i2 += d, e2 /= 256, eLen -= 8)
    ;
  buffer[offset + i2 - d] |= s * 128;
}
function createBuffer(length) {
  if (length > kMaxLength)
    throw RangeError('The value "' + length + '" is invalid for option "size"');
  let buf = new Uint8Array(length);
  return Object.setPrototypeOf(buf, Buffer2.prototype), buf;
}
function E(sym, getMessage, Base) {
  return class extends Base {
    constructor() {
      super();
      Object.defineProperty(this, "message", { value: getMessage.apply(this, arguments), writable: true, configurable: true }), this.name = `${this.name} [${sym}]`, this.stack, delete this.name;
    }
    get code() {
      return sym;
    }
    set code(value) {
      Object.defineProperty(this, "code", { configurable: true, enumerable: true, value, writable: true });
    }
    toString() {
      return `${this.name} [${sym}]: ${this.message}`;
    }
  };
}
function Buffer2(arg, encodingOrOffset, length) {
  if (typeof arg === "number") {
    if (typeof encodingOrOffset === "string")
      throw TypeError('The "string" argument must be of type string. Received type number');
    return allocUnsafe(arg);
  }
  return from(arg, encodingOrOffset, length);
}
function from(value, encodingOrOffset, length) {
  if (typeof value === "string")
    return fromString2(value, encodingOrOffset);
  if (ArrayBuffer.isView(value))
    return fromArrayView(value);
  if (value == null)
    throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value);
  if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer))
    return fromArrayBuffer(value, encodingOrOffset, length);
  if (typeof SharedArrayBuffer < "u" && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer)))
    return fromArrayBuffer(value, encodingOrOffset, length);
  if (typeof value === "number")
    throw TypeError('The "value" argument must not be of type number. Received type number');
  let valueOf = value.valueOf && value.valueOf();
  if (valueOf != null && valueOf !== value)
    return Buffer2.from(valueOf, encodingOrOffset, length);
  let b = fromObject3(value);
  if (b)
    return b;
  if (typeof Symbol < "u" && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === "function")
    return Buffer2.from(value[Symbol.toPrimitive]("string"), encodingOrOffset, length);
  throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value);
}
function assertSize(size) {
  if (typeof size !== "number")
    throw TypeError('"size" argument must be of type number');
  else if (size < 0)
    throw RangeError('The value "' + size + '" is invalid for option "size"');
}
function alloc(size, fill, encoding) {
  if (assertSize(size), size <= 0)
    return createBuffer(size);
  if (fill !== undefined)
    return typeof encoding === "string" ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill);
  return createBuffer(size);
}
function allocUnsafe(size) {
  return assertSize(size), createBuffer(size < 0 ? 0 : checked(size) | 0);
}
function fromString2(string, encoding) {
  if (typeof encoding !== "string" || encoding === "")
    encoding = "utf8";
  if (!Buffer2.isEncoding(encoding))
    throw TypeError("Unknown encoding: " + encoding);
  let length = byteLength(string, encoding) | 0, buf = createBuffer(length), actual = buf.write(string, encoding);
  if (actual !== length)
    buf = buf.slice(0, actual);
  return buf;
}
function fromArrayLike(array) {
  let length = array.length < 0 ? 0 : checked(array.length) | 0, buf = createBuffer(length);
  for (let i2 = 0;i2 < length; i2 += 1)
    buf[i2] = array[i2] & 255;
  return buf;
}
function fromArrayView(arrayView) {
  if (isInstance(arrayView, Uint8Array)) {
    let copy = new Uint8Array(arrayView);
    return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength);
  }
  return fromArrayLike(arrayView);
}
function fromArrayBuffer(array, byteOffset, length) {
  if (byteOffset < 0 || array.byteLength < byteOffset)
    throw RangeError('"offset" is outside of buffer bounds');
  if (array.byteLength < byteOffset + (length || 0))
    throw RangeError('"length" is outside of buffer bounds');
  let buf;
  if (byteOffset === undefined && length === undefined)
    buf = new Uint8Array(array);
  else if (length === undefined)
    buf = new Uint8Array(array, byteOffset);
  else
    buf = new Uint8Array(array, byteOffset, length);
  return Object.setPrototypeOf(buf, Buffer2.prototype), buf;
}
function fromObject3(obj) {
  if (Buffer2.isBuffer(obj)) {
    let len2 = checked(obj.length) | 0, buf = createBuffer(len2);
    if (buf.length === 0)
      return buf;
    return obj.copy(buf, 0, 0, len2), buf;
  }
  if (obj.length !== undefined) {
    if (typeof obj.length !== "number" || Number.isNaN(obj.length))
      return createBuffer(0);
    return fromArrayLike(obj);
  }
  if (obj.type === "Buffer" && Array.isArray(obj.data))
    return fromArrayLike(obj.data);
}
function checked(length) {
  if (length >= kMaxLength)
    throw RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + kMaxLength.toString(16) + " bytes");
  return length | 0;
}
function byteLength(string, encoding) {
  if (Buffer2.isBuffer(string))
    return string.length;
  if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer))
    return string.byteLength;
  if (typeof string !== "string")
    throw TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof string);
  let len2 = string.length, mustMatch = arguments.length > 2 && arguments[2] === true;
  if (!mustMatch && len2 === 0)
    return 0;
  let loweredCase = false;
  for (;; )
    switch (encoding) {
      case "ascii":
      case "latin1":
      case "binary":
        return len2;
      case "utf8":
      case "utf-8":
        return utf8ToBytes(string).length;
      case "ucs2":
      case "ucs-2":
      case "utf16le":
      case "utf-16le":
        return len2 * 2;
      case "hex":
        return len2 >>> 1;
      case "base64":
        return base64ToBytes(string).length;
      default:
        if (loweredCase)
          return mustMatch ? -1 : utf8ToBytes(string).length;
        encoding = ("" + encoding).toLowerCase(), loweredCase = true;
    }
}
function slowToString(encoding, start, end) {
  let loweredCase = false;
  if (start === undefined || start < 0)
    start = 0;
  if (start > this.length)
    return "";
  if (end === undefined || end > this.length)
    end = this.length;
  if (end <= 0)
    return "";
  if (end >>>= 0, start >>>= 0, end <= start)
    return "";
  if (!encoding)
    encoding = "utf8";
  while (true)
    switch (encoding) {
      case "hex":
        return hexSlice(this, start, end);
      case "utf8":
      case "utf-8":
        return utf8Slice(this, start, end);
      case "ascii":
        return asciiSlice(this, start, end);
      case "latin1":
      case "binary":
        return latin1Slice(this, start, end);
      case "base64":
        return base64Slice(this, start, end);
      case "ucs2":
      case "ucs-2":
      case "utf16le":
      case "utf-16le":
        return utf16leSlice(this, start, end);
      default:
        if (loweredCase)
          throw TypeError("Unknown encoding: " + encoding);
        encoding = (encoding + "").toLowerCase(), loweredCase = true;
    }
}
function swap(b, n2, m) {
  let i2 = b[n2];
  b[n2] = b[m], b[m] = i2;
}
function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) {
  if (buffer.length === 0)
    return -1;
  if (typeof byteOffset === "string")
    encoding = byteOffset, byteOffset = 0;
  else if (byteOffset > 2147483647)
    byteOffset = 2147483647;
  else if (byteOffset < -2147483648)
    byteOffset = -2147483648;
  if (byteOffset = +byteOffset, Number.isNaN(byteOffset))
    byteOffset = dir ? 0 : buffer.length - 1;
  if (byteOffset < 0)
    byteOffset = buffer.length + byteOffset;
  if (byteOffset >= buffer.length)
    if (dir)
      return -1;
    else
      byteOffset = buffer.length - 1;
  else if (byteOffset < 0)
    if (dir)
      byteOffset = 0;
    else
      return -1;
  if (typeof val === "string")
    val = Buffer2.from(val, encoding);
  if (Buffer2.isBuffer(val)) {
    if (val.length === 0)
      return -1;
    return arrayIndexOf(buffer, val, byteOffset, encoding, dir);
  } else if (typeof val === "number") {
    if (val = val & 255, typeof Uint8Array.prototype.indexOf === "function")
      if (dir)
        return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset);
      else
        return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset);
    return arrayIndexOf(buffer, [val], byteOffset, encoding, dir);
  }
  throw TypeError("val must be string, number or Buffer");
}
function arrayIndexOf(arr, val, byteOffset, encoding, dir) {
  let indexSize = 1, arrLength = arr.length, valLength = val.length;
  if (encoding !== undefined) {
    if (encoding = String(encoding).toLowerCase(), encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") {
      if (arr.length < 2 || val.length < 2)
        return -1;
      indexSize = 2, arrLength /= 2, valLength /= 2, byteOffset /= 2;
    }
  }
  function read2(buf, i3) {
    if (indexSize === 1)
      return buf[i3];
    else
      return buf.readUInt16BE(i3 * indexSize);
  }
  let i2;
  if (dir) {
    let foundIndex = -1;
    for (i2 = byteOffset;i2 < arrLength; i2++)
      if (read2(arr, i2) === read2(val, foundIndex === -1 ? 0 : i2 - foundIndex)) {
        if (foundIndex === -1)
          foundIndex = i2;
        if (i2 - foundIndex + 1 === valLength)
          return foundIndex * indexSize;
      } else {
        if (foundIndex !== -1)
          i2 -= i2 - foundIndex;
        foundIndex = -1;
      }
  } else {
    if (byteOffset + valLength > arrLength)
      byteOffset = arrLength - valLength;
    for (i2 = byteOffset;i2 >= 0; i2--) {
      let found = true;
      for (let j = 0;j < valLength; j++)
        if (read2(arr, i2 + j) !== read2(val, j)) {
          found = false;
          break;
        }
      if (found)
        return i2;
    }
  }
  return -1;
}
function hexWrite(buf, string, offset, length) {
  offset = Number(offset) || 0;
  let remaining = buf.length - offset;
  if (!length)
    length = remaining;
  else if (length = Number(length), length > remaining)
    length = remaining;
  let strLen = string.length;
  if (length > strLen / 2)
    length = strLen / 2;
  let i2;
  for (i2 = 0;i2 < length; ++i2) {
    let parsed = parseInt(string.substr(i2 * 2, 2), 16);
    if (Number.isNaN(parsed))
      return i2;
    buf[offset + i2] = parsed;
  }
  return i2;
}
function utf8Write(buf, string, offset, length) {
  return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length);
}
function asciiWrite(buf, string, offset, length) {
  return blitBuffer(asciiToBytes(string), buf, offset, length);
}
function base64Write(buf, string, offset, length) {
  return blitBuffer(base64ToBytes(string), buf, offset, length);
}
function ucs2Write(buf, string, offset, length) {
  return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length);
}
function base64Slice(buf, start, end) {
  if (start === 0 && end === buf.length)
    return fromByteArray(buf);
  else
    return fromByteArray(buf.slice(start, end));
}
function utf8Slice(buf, start, end) {
  end = Math.min(buf.length, end);
  let res = [], i2 = start;
  while (i2 < end) {
    let firstByte = buf[i2], codePoint = null, bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1;
    if (i2 + bytesPerSequence <= end) {
      let secondByte, thirdByte, fourthByte, tempCodePoint;
      switch (bytesPerSequence) {
        case 1:
          if (firstByte < 128)
            codePoint = firstByte;
          break;
        case 2:
          if (secondByte = buf[i2 + 1], (secondByte & 192) === 128) {
            if (tempCodePoint = (firstByte & 31) << 6 | secondByte & 63, tempCodePoint > 127)
              codePoint = tempCodePoint;
          }
          break;
        case 3:
          if (secondByte = buf[i2 + 1], thirdByte = buf[i2 + 2], (secondByte & 192) === 128 && (thirdByte & 192) === 128) {
            if (tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63, tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343))
              codePoint = tempCodePoint;
          }
          break;
        case 4:
          if (secondByte = buf[i2 + 1], thirdByte = buf[i2 + 2], fourthByte = buf[i2 + 3], (secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) {
            if (tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63, tempCodePoint > 65535 && tempCodePoint < 1114112)
              codePoint = tempCodePoint;
          }
      }
    }
    if (codePoint === null)
      codePoint = 65533, bytesPerSequence = 1;
    else if (codePoint > 65535)
      codePoint -= 65536, res.push(codePoint >>> 10 & 1023 | 55296), codePoint = 56320 | codePoint & 1023;
    res.push(codePoint), i2 += bytesPerSequence;
  }
  return decodeCodePointsArray(res);
}
function decodeCodePointsArray(codePoints) {
  let len2 = codePoints.length;
  if (len2 <= MAX_ARGUMENTS_LENGTH)
    return String.fromCharCode.apply(String, codePoints);
  let res = "", i2 = 0;
  while (i2 < len2)
    res += String.fromCharCode.apply(String, codePoints.slice(i2, i2 += MAX_ARGUMENTS_LENGTH));
  return res;
}
function asciiSlice(buf, start, end) {
  let ret = "";
  end = Math.min(buf.length, end);
  for (let i2 = start;i2 < end; ++i2)
    ret += String.fromCharCode(buf[i2] & 127);
  return ret;
}
function latin1Slice(buf, start, end) {
  let ret = "";
  end = Math.min(buf.length, end);
  for (let i2 = start;i2 < end; ++i2)
    ret += String.fromCharCode(buf[i2]);
  return ret;
}
function hexSlice(buf, start, end) {
  let len2 = buf.length;
  if (!start || start < 0)
    start = 0;
  if (!end || end < 0 || end > len2)
    end = len2;
  let out = "";
  for (let i2 = start;i2 < end; ++i2)
    out += hexSliceLookupTable[buf[i2]];
  return out;
}
function utf16leSlice(buf, start, end) {
  let bytes = buf.slice(start, end), res = "";
  for (let i2 = 0;i2 < bytes.length - 1; i2 += 2)
    res += String.fromCharCode(bytes[i2] + bytes[i2 + 1] * 256);
  return res;
}
function checkOffset(offset, ext, length) {
  if (offset % 1 !== 0 || offset < 0)
    throw RangeError("offset is not uint");
  if (offset + ext > length)
    throw RangeError("Trying to access beyond buffer length");
}
function checkInt(buf, value, offset, ext, max, min) {
  if (!Buffer2.isBuffer(buf))
    throw TypeError('"buffer" argument must be a Buffer instance');
  if (value > max || value < min)
    throw RangeError('"value" argument is out of bounds');
  if (offset + ext > buf.length)
    throw RangeError("Index out of range");
}
function wrtBigUInt64LE(buf, value, offset, min, max) {
  checkIntBI(value, min, max, buf, offset, 7);
  let lo = Number(value & BigInt(4294967295));
  buf[offset++] = lo, lo = lo >> 8, buf[offset++] = lo, lo = lo >> 8, buf[offset++] = lo, lo = lo >> 8, buf[offset++] = lo;
  let hi = Number(value >> BigInt(32) & BigInt(4294967295));
  return buf[offset++] = hi, hi = hi >> 8, buf[offset++] = hi, hi = hi >> 8, buf[offset++] = hi, hi = hi >> 8, buf[offset++] = hi, offset;
}
function wrtBigUInt64BE(buf, value, offset, min, max) {
  checkIntBI(value, min, max, buf, offset, 7);
  let lo = Number(value & BigInt(4294967295));
  buf[offset + 7] = lo, lo = lo >> 8, buf[offset + 6] = lo, lo = lo >> 8, buf[offset + 5] = lo, lo = lo >> 8, buf[offset + 4] = lo;
  let hi = Number(value >> BigInt(32) & BigInt(4294967295));
  return buf[offset + 3] = hi, hi = hi >> 8, buf[offset + 2] = hi, hi = hi >> 8, buf[offset + 1] = hi, hi = hi >> 8, buf[offset] = hi, offset + 8;
}
function checkIEEE754(buf, value, offset, ext, max, min) {
  if (offset + ext > buf.length)
    throw RangeError("Index out of range");
  if (offset < 0)
    throw RangeError("Index out of range");
}
function writeFloat(buf, value, offset, littleEndian, noAssert) {
  if (value = +value, offset = offset >>> 0, !noAssert)
    checkIEEE754(buf, value, offset, 4, 340282346638528860000000000000000000000, -340282346638528860000000000000000000000);
  return write(buf, value, offset, littleEndian, 23, 4), offset + 4;
}
function writeDouble(buf, value, offset, littleEndian, noAssert) {
  if (value = +value, offset = offset >>> 0, !noAssert)
    checkIEEE754(buf, value, offset, 8, 179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000, -179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000);
  return write(buf, value, offset, littleEndian, 52, 8), offset + 8;
}
function addNumericalSeparator(val) {
  let res = "", i2 = val.length, start = val[0] === "-" ? 1 : 0;
  for (;i2 >= start + 4; i2 -= 3)
    res = `_${val.slice(i2 - 3, i2)}${res}`;
  return `${val.slice(0, i2)}${res}`;
}
function checkBounds(buf, offset, byteLength2) {
  if (validateNumber(offset, "offset"), buf[offset] === undefined || buf[offset + byteLength2] === undefined)
    boundsError(offset, buf.length - (byteLength2 + 1));
}
function checkIntBI(value, min, max, buf, offset, byteLength2) {
  if (value > max || value < min) {
    let n2 = typeof min === "bigint" ? "n" : "", range;
    if (byteLength2 > 3)
      if (min === 0 || min === BigInt(0))
        range = `>= 0${n2} and < 2${n2} ** ${(byteLength2 + 1) * 8}${n2}`;
      else
        range = `>= -(2${n2} ** ${(byteLength2 + 1) * 8 - 1}${n2}) and < 2 ** ${(byteLength2 + 1) * 8 - 1}${n2}`;
    else
      range = `>= ${min}${n2} and <= ${max}${n2}`;
    throw new ERR_OUT_OF_RANGE("value", range, value);
  }
  checkBounds(buf, offset, byteLength2);
}
function validateNumber(value, name) {
  if (typeof value !== "number")
    throw new ERR_INVALID_ARG_TYPE(name, "number", value);
}
function boundsError(value, length, type) {
  if (Math.floor(value) !== value)
    throw validateNumber(value, type), new ERR_OUT_OF_RANGE(type || "offset", "an integer", value);
  if (length < 0)
    throw new ERR_BUFFER_OUT_OF_BOUNDS;
  throw new ERR_OUT_OF_RANGE(type || "offset", `>= ${type ? 1 : 0} and <= ${length}`, value);
}
function base64clean(str) {
  if (str = str.split("=")[0], str = str.trim().replace(INVALID_BASE64_RE, ""), str.length < 2)
    return "";
  while (str.length % 4 !== 0)
    str = str + "=";
  return str;
}
function utf8ToBytes(string, units) {
  units = units || 1 / 0;
  let codePoint, length = string.length, leadSurrogate = null, bytes = [];
  for (let i2 = 0;i2 < length; ++i2) {
    if (codePoint = string.charCodeAt(i2), codePoint > 55295 && codePoint < 57344) {
      if (!leadSurrogate) {
        if (codePoint > 56319) {
          if ((units -= 3) > -1)
            bytes.push(239, 191, 189);
          continue;
        } else if (i2 + 1 === length) {
          if ((units -= 3) > -1)
            bytes.push(239, 191, 189);
          continue;
        }
        leadSurrogate = codePoint;
        continue;
      }
      if (codePoint < 56320) {
        if ((units -= 3) > -1)
          bytes.push(239, 191, 189);
        leadSurrogate = codePoint;
        continue;
      }
      codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536;
    } else if (leadSurrogate) {
      if ((units -= 3) > -1)
        bytes.push(239, 191, 189);
    }
    if (leadSurrogate = null, codePoint < 128) {
      if ((units -= 1) < 0)
        break;
      bytes.push(codePoint);
    } else if (codePoint < 2048) {
      if ((units -= 2) < 0)
        break;
      bytes.push(codePoint >> 6 | 192, codePoint & 63 | 128);
    } else if (codePoint < 65536) {
      if ((units -= 3) < 0)
        break;
      bytes.push(codePoint >> 12 | 224, codePoint >> 6 & 63 | 128, codePoint & 63 | 128);
    } else if (codePoint < 1114112) {
      if ((units -= 4) < 0)
        break;
      bytes.push(codePoint >> 18 | 240, codePoint >> 12 & 63 | 128, codePoint >> 6 & 63 | 128, codePoint & 63 | 128);
    } else
      throw Error("Invalid code point");
  }
  return bytes;
}
function asciiToBytes(str) {
  let byteArray = [];
  for (let i2 = 0;i2 < str.length; ++i2)
    byteArray.push(str.charCodeAt(i2) & 255);
  return byteArray;
}
function utf16leToBytes(str, units) {
  let c2, hi, lo, byteArray = [];
  for (let i2 = 0;i2 < str.length; ++i2) {
    if ((units -= 2) < 0)
      break;
    c2 = str.charCodeAt(i2), hi = c2 >> 8, lo = c2 % 256, byteArray.push(lo), byteArray.push(hi);
  }
  return byteArray;
}
function base64ToBytes(str) {
  return toByteArray(base64clean(str));
}
function blitBuffer(src, dst, offset, length) {
  let i2;
  for (i2 = 0;i2 < length; ++i2) {
    if (i2 + offset >= dst.length || i2 >= src.length)
      break;
    dst[i2 + offset] = src[i2];
  }
  return i2;
}
function isInstance(obj, type) {
  return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name;
}
function defineBigIntMethod(fn) {
  return typeof BigInt > "u" ? BufferBigIntNotDefined : fn;
}
function BufferBigIntNotDefined() {
  throw Error("BigInt not supported");
}
function notimpl(name) {
  return () => {
    throw Error(name + " is not implemented for node:buffer browser polyfill");
  };
}
var lookup, revLookup, code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", i, len, customInspectSymbol, INSPECT_MAX_BYTES = 50, kMaxLength = 2147483647, kStringMaxLength = 536870888, btoa, atob2, File, Blob, constants, ERR_BUFFER_OUT_OF_BOUNDS, ERR_INVALID_ARG_TYPE, ERR_OUT_OF_RANGE, MAX_ARGUMENTS_LENGTH = 4096, INVALID_BASE64_RE, hexSliceLookupTable, resolveObjectURL, isUtf8, isAscii = (str) => {
  for (let char of str)
    if (char.charCodeAt(0) > 127)
      return false;
  return true;
}, transcode, buffer_default;
var init_buffer = __esm(() => {
  lookup = [];
  revLookup = [];
  for (i = 0, len = code.length;i < len; ++i)
    lookup[i] = code[i], revLookup[code.charCodeAt(i)] = i;
  revLookup[45] = 62;
  revLookup[95] = 63;
  customInspectSymbol = typeof Symbol === "function" && typeof Symbol.for === "function" ? Symbol.for("nodejs.util.inspect.custom") : null;
  btoa = globalThis.btoa;
  atob2 = globalThis.atob;
  File = globalThis.File;
  Blob = globalThis.Blob;
  constants = { MAX_LENGTH: kMaxLength, MAX_STRING_LENGTH: kStringMaxLength };
  ERR_BUFFER_OUT_OF_BOUNDS = E("ERR_BUFFER_OUT_OF_BOUNDS", function(name) {
    if (name)
      return `${name} is outside of buffer bounds`;
    return "Attempt to access memory outside buffer bounds";
  }, RangeError);
  ERR_INVALID_ARG_TYPE = E("ERR_INVALID_ARG_TYPE", function(name, actual) {
    return `The "${name}" argument must be of type number. Received type ${typeof actual}`;
  }, TypeError);
  ERR_OUT_OF_RANGE = E("ERR_OUT_OF_RANGE", function(str, range, input) {
    let msg = `The value of "${str}" is out of range.`, received = input;
    if (Number.isInteger(input) && Math.abs(input) > 4294967296)
      received = addNumericalSeparator(String(input));
    else if (typeof input === "bigint") {
      if (received = String(input), input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32)))
        received = addNumericalSeparator(received);
      received += "n";
    }
    return msg += ` It must be ${range}. Received ${received}`, msg;
  }, RangeError);
  Object.defineProperty(Buffer2.prototype, "parent", { enumerable: true, get: function() {
    if (!Buffer2.isBuffer(this))
      return;
    return this.buffer;
  } });
  Object.defineProperty(Buffer2.prototype, "offset", { enumerable: true, get: function() {
    if (!Buffer2.isBuffer(this))
      return;
    return this.byteOffset;
  } });
  Buffer2.poolSize = 8192;
  Buffer2.from = function(value, encodingOrOffset, length) {
    return from(value, encodingOrOffset, length);
  };
  Object.setPrototypeOf(Buffer2.prototype, Uint8Array.prototype);
  Object.setPrototypeOf(Buffer2, Uint8Array);
  Buffer2.alloc = function(size, fill, encoding) {
    return alloc(size, fill, encoding);
  };
  Buffer2.allocUnsafe = function(size) {
    return allocUnsafe(size);
  };
  Buffer2.allocUnsafeSlow = function(size) {
    return allocUnsafe(size);
  };
  Buffer2.isBuffer = function(b) {
    return b != null && b._isBuffer === true && b !== Buffer2.prototype;
  };
  Buffer2.compare = function(a2, b) {
    if (isInstance(a2, Uint8Array))
      a2 = Buffer2.from(a2, a2.offset, a2.byteLength);
    if (isInstance(b, Uint8Array))
      b = Buffer2.from(b, b.offset, b.byteLength);
    if (!Buffer2.isBuffer(a2) || !Buffer2.isBuffer(b))
      throw TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');
    if (a2 === b)
      return 0;
    let x = a2.length, y = b.length;
    for (let i2 = 0, len2 = Math.min(x, y);i2 < len2; ++i2)
      if (a2[i2] !== b[i2]) {
        x = a2[i2], y = b[i2];
        break;
      }
    if (x < y)
      return -1;
    if (y < x)
      return 1;
    return 0;
  };
  Buffer2.isEncoding = function(encoding) {
    switch (String(encoding).toLowerCase()) {
      case "hex":
      case "utf8":
      case "utf-8":
      case "ascii":
      case "latin1":
      case "binary":
      case "base64":
      case "ucs2":
      case "ucs-2":
      case "utf16le":
      case "utf-16le":
        return true;
      default:
        return false;
    }
  };
  Buffer2.concat = function(list, length) {
    if (!Array.isArray(list))
      throw TypeError('"list" argument must be an Array of Buffers');
    if (list.length === 0)
      return Buffer2.alloc(0);
    let i2;
    if (length === undefined) {
      length = 0;
      for (i2 = 0;i2 < list.length; ++i2)
        length += list[i2].length;
    }
    let buffer = Buffer2.allocUnsafe(length), pos = 0;
    for (i2 = 0;i2 < list.length; ++i2) {
      let buf = list[i2];
      if (isInstance(buf, Uint8Array))
        if (pos + buf.length > buffer.length) {
          if (!Buffer2.isBuffer(buf))
            buf = Buffer2.from(buf);
          buf.copy(buffer, pos);
        } else
          Uint8Array.prototype.set.call(buffer, buf, pos);
      else if (!Buffer2.isBuffer(buf))
        throw TypeError('"list" argument must be an Array of Buffers');
      else
        buf.copy(buffer, pos);
      pos += buf.length;
    }
    return buffer;
  };
  Buffer2.byteLength = byteLength;
  Buffer2.prototype._isBuffer = true;
  Buffer2.prototype.swap16 = function() {
    let len2 = this.length;
    if (len2 % 2 !== 0)
      throw RangeError("Buffer size must be a multiple of 16-bits");
    for (let i2 = 0;i2 < len2; i2 += 2)
      swap(this, i2, i2 + 1);
    return this;
  };
  Buffer2.prototype.swap32 = function() {
    let len2 = this.length;
    if (len2 % 4 !== 0)
      throw RangeError("Buffer size must be a multiple of 32-bits");
    for (let i2 = 0;i2 < len2; i2 += 4)
      swap(this, i2, i2 + 3), swap(this, i2 + 1, i2 + 2);
    return this;
  };
  Buffer2.prototype.swap64 = function() {
    let len2 = this.length;
    if (len2 % 8 !== 0)
      throw RangeError("Buffer size must be a multiple of 64-bits");
    for (let i2 = 0;i2 < len2; i2 += 8)
      swap(this, i2, i2 + 7), swap(this, i2 + 1, i2 + 6), swap(this, i2 + 2, i2 + 5), swap(this, i2 + 3, i2 + 4);
    return this;
  };
  Buffer2.prototype.toString = function() {
    let length = this.length;
    if (length === 0)
      return "";
    if (arguments.length === 0)
      return utf8Slice(this, 0, length);
    return slowToString.apply(this, arguments);
  };
  Buffer2.prototype.toLocaleString = Buffer2.prototype.toString;
  Buffer2.prototype.equals = function(b) {
    if (!Buffer2.isBuffer(b))
      throw TypeError("Argument must be a Buffer");
    if (this === b)
      return true;
    return Buffer2.compare(this, b) === 0;
  };
  Buffer2.prototype.inspect = function() {
    let str = "", max = INSPECT_MAX_BYTES;
    if (str = this.toString("hex", 0, max).replace(/(.{2})/g, "$1 ").trim(), this.length > max)
      str += " ... ";
    return "<Buffer " + str + ">";
  };
  if (customInspectSymbol)
    Buffer2.prototype[customInspectSymbol] = Buffer2.prototype.inspect;
  Buffer2.prototype.compare = function(target, start, end, thisStart, thisEnd) {
    if (isInstance(target, Uint8Array))
      target = Buffer2.from(target, target.offset, target.byteLength);
    if (!Buffer2.isBuffer(target))
      throw TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof target);
    if (start === undefined)
      start = 0;
    if (end === undefined)
      end = target ? target.length : 0;
    if (thisStart === undefined)
      thisStart = 0;
    if (thisEnd === undefined)
      thisEnd = this.length;
    if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length)
      throw RangeError("out of range index");
    if (thisStart >= thisEnd && start >= end)
      return 0;
    if (thisStart >= thisEnd)
      return -1;
    if (start >= end)
      return 1;
    if (start >>>= 0, end >>>= 0, thisStart >>>= 0, thisEnd >>>= 0, this === target)
      return 0;
    let x = thisEnd - thisStart, y = end - start, len2 = Math.min(x, y), thisCopy = this.slice(thisStart, thisEnd), targetCopy = target.slice(start, end);
    for (let i2 = 0;i2 < len2; ++i2)
      if (thisCopy[i2] !== targetCopy[i2]) {
        x = thisCopy[i2], y = targetCopy[i2];
        break;
      }
    if (x < y)
      return -1;
    if (y < x)
      return 1;
    return 0;
  };
  Buffer2.prototype.includes = function(val, byteOffset, encoding) {
    return this.indexOf(val, byteOffset, encoding) !== -1;
  };
  Buffer2.prototype.indexOf = function(val, byteOffset, encoding) {
    return bidirectionalIndexOf(this, val, byteOffset, encoding, true);
  };
  Buffer2.prototype.lastIndexOf = function(val, byteOffset, encoding) {
    return bidirectionalIndexOf(this, val, byteOffset, encoding, false);
  };
  Buffer2.prototype.write = function(string, offset, length, encoding) {
    if (offset === undefined)
      encoding = "utf8", length = this.length, offset = 0;
    else if (length === undefined && typeof offset === "string")
      encoding = offset, length = this.length, offset = 0;
    else if (isFinite(offset))
      if (offset = offset >>> 0, isFinite(length)) {
        if (length = length >>> 0, encoding === undefined)
          encoding = "utf8";
      } else
        encoding = length, length = undefined;
    else
      throw Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");
    let remaining = this.length - offset;
    if (length === undefined || length > remaining)
      length = remaining;
    if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length)
      throw RangeError("Attempt to write outside buffer bounds");
    if (!encoding)
      encoding = "utf8";
    let loweredCase = false;
    for (;; )
      switch (encoding) {
        case "hex":
          return hexWrite(this, string, offset, length);
        case "utf8":
        case "utf-8":
          return utf8Write(this, string, offset, length);
        case "ascii":
        case "latin1":
        case "binary":
          return asciiWrite(this, string, offset, length);
        case "base64":
          return base64Write(this, string, offset, length);
        case "ucs2":
        case "ucs-2":
        case "utf16le":
        case "utf-16le":
          return ucs2Write(this, string, offset, length);
        default:
          if (loweredCase)
            throw TypeError("Unknown encoding: " + encoding);
          encoding = ("" + encoding).toLowerCase(), loweredCase = true;
      }
  };
  Buffer2.prototype.toJSON = function() {
    return { type: "Buffer", data: Array.prototype.slice.call(this._arr || this, 0) };
  };
  Buffer2.prototype.slice = function(start, end) {
    let len2 = this.length;
    if (start = ~~start, end = end === undefined ? len2 : ~~end, start < 0) {
      if (start += len2, start < 0)
        start = 0;
    } else if (start > len2)
      start = len2;
    if (end < 0) {
      if (end += len2, end < 0)
        end = 0;
    } else if (end > len2)
      end = len2;
    if (end < start)
      end = start;
    let newBuf = this.subarray(start, end);
    return Object.setPrototypeOf(newBuf, Buffer2.prototype), newBuf;
  };
  Buffer2.prototype.readUintLE = Buffer2.prototype.readUIntLE = function(offset, byteLength2, noAssert) {
    if (offset = offset >>> 0, byteLength2 = byteLength2 >>> 0, !noAssert)
      checkOffset(offset, byteLength2, this.length);
    let val = this[offset], mul = 1, i2 = 0;
    while (++i2 < byteLength2 && (mul *= 256))
      val += this[offset + i2] * mul;
    return val;
  };
  Buffer2.prototype.readUintBE = Buffer2.prototype.readUIntBE = function(offset, byteLength2, noAssert) {
    if (offset = offset >>> 0, byteLength2 = byteLength2 >>> 0, !noAssert)
      checkOffset(offset, byteLength2, this.length);
    let val = this[offset + --byteLength2], mul = 1;
    while (byteLength2 > 0 && (mul *= 256))
      val += this[offset + --byteLength2] * mul;
    return val;
  };
  Buffer2.prototype.readUint8 = Buffer2.prototype.readUInt8 = function(offset, noAssert) {
    if (offset = offset >>> 0, !noAssert)
      checkOffset(offset, 1, this.length);
    return this[offset];
  };
  Buffer2.prototype.readUint16LE = Buffer2.prototype.readUInt16LE = function(offset, noAssert) {
    if (offset = offset >>> 0, !noAssert)
      checkOffset(offset, 2, this.length);
    return this[offset] | this[offset + 1] << 8;
  };
  Buffer2.prototype.readUint16BE = Buffer2.prototype.readUInt16BE = function(offset, noAssert) {
    if (offset = offset >>> 0, !noAssert)
      checkOffset(offset, 2, this.length);
    return this[offset] << 8 | this[offset + 1];
  };
  Buffer2.prototype.readUint32LE = Buffer2.prototype.readUInt32LE = function(offset, noAssert) {
    if (offset = offset >>> 0, !noAssert)
      checkOffset(offset, 4, this.length);
    return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 16777216;
  };
  Buffer2.prototype.readUint32BE = Buffer2.prototype.readUInt32BE = function(offset, noAssert) {
    if (offset = offset >>> 0, !noAssert)
      checkOffset(offset, 4, this.length);
    return this[offset] * 16777216 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]);
  };
  Buffer2.prototype.readBigUInt64LE = defineBigIntMethod(function(offset) {
    offset = offset >>> 0, validateNumber(offset, "offset");
    let first = this[offset], last = this[offset + 7];
    if (first === undefined || last === undefined)
      boundsError(offset, this.length - 8);
    let lo = first + this[++offset] * 256 + this[++offset] * 65536 + this[++offset] * 16777216, hi = this[++offset] + this[++offset] * 256 + this[++offset] * 65536 + last * 16777216;
    return BigInt(lo) + (BigInt(hi) << BigInt(32));
  });
  Buffer2.prototype.readBigUInt64BE = defineBigIntMethod(function(offset) {
    offset = offset >>> 0, validateNumber(offset, "offset");
    let first = this[offset], last = this[offset + 7];
    if (first === undefined || last === undefined)
      boundsError(offset, this.length - 8);
    let hi = first * 16777216 + this[++offset] * 65536 + this[++offset] * 256 + this[++offset], lo = this[++offset] * 16777216 + this[++offset] * 65536 + this[++offset] * 256 + last;
    return (BigInt(hi) << BigInt(32)) + BigInt(lo);
  });
  Buffer2.prototype.readIntLE = function(offset, byteLength2, noAssert) {
    if (offset = offset >>> 0, byteLength2 = byteLength2 >>> 0, !noAssert)
      checkOffset(offset, byteLength2, this.length);
    let val = this[offset], mul = 1, i2 = 0;
    while (++i2 < byteLength2 && (mul *= 256))
      val += this[offset + i2] * mul;
    if (mul *= 128, val >= mul)
      val -= Math.pow(2, 8 * byteLength2);
    return val;
  };
  Buffer2.prototype.readIntBE = function(offset, byteLength2, noAssert) {
    if (offset = offset >>> 0, byteLength2 = byteLength2 >>> 0, !noAssert)
      checkOffset(offset, byteLength2, this.length);
    let i2 = byteLength2, mul = 1, val = this[offset + --i2];
    while (i2 > 0 && (mul *= 256))
      val += this[offset + --i2] * mul;
    if (mul *= 128, val >= mul)
      val -= Math.pow(2, 8 * byteLength2);
    return val;
  };
  Buffer2.prototype.readInt8 = function(offset, noAssert) {
    if (offset = offset >>> 0, !noAssert)
      checkOffset(offset, 1, this.length);
    if (!(this[offset] & 128))
      return this[offset];
    return (255 - this[offset] + 1) * -1;
  };
  Buffer2.prototype.readInt16LE = function(offset, noAssert) {
    if (offset = offset >>> 0, !noAssert)
      checkOffset(offset, 2, this.length);
    let val = this[offset] | this[offset + 1] << 8;
    return val & 32768 ? val | 4294901760 : val;
  };
  Buffer2.prototype.readInt16BE = function(offset, noAssert) {
    if (offset = offset >>> 0, !noAssert)
      checkOffset(offset, 2, this.length);
    let val = this[offset + 1] | this[offset] << 8;
    return val & 32768 ? val | 4294901760 : val;
  };
  Buffer2.prototype.readInt32LE = function(offset, noAssert) {
    if (offset = offset >>> 0, !noAssert)
      checkOffset(offset, 4, this.length);
    return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24;
  };
  Buffer2.prototype.readInt32BE = function(offset, noAssert) {
    if (offset = offset >>> 0, !noAssert)
      checkOffset(offset, 4, this.length);
    return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3];
  };
  Buffer2.prototype.readBigInt64LE = defineBigIntMethod(function(offset) {
    offset = offset >>> 0, validateNumber(offset, "offset");
    let first = this[offset], last = this[offset + 7];
    if (first === undefined || last === undefined)
      boundsError(offset, this.length - 8);
    let val = this[offset + 4] + this[offset + 5] * 256 + this[offset + 6] * 65536 + (last << 24);
    return (BigInt(val) << BigInt(32)) + BigInt(first + this[++offset] * 256 + this[++offset] * 65536 + this[++offset] * 16777216);
  });
  Buffer2.prototype.readBigInt64BE = defineBigIntMethod(function(offset) {
    offset = offset >>> 0, validateNumber(offset, "offset");
    let first = this[offset], last = this[offset + 7];
    if (first === undefined || last === undefined)
      boundsError(offset, this.length - 8);
    let val = (first << 24) + this[++offset] * 65536 + this[++offset] * 256 + this[++offset];
    return (BigInt(val) << BigInt(32)) + BigInt(this[++offset] * 16777216 + this[++offset] * 65536 + this[++offset] * 256 + last);
  });
  Buffer2.prototype.readFloatLE = function(offset, noAssert) {
    if (offset = offset >>> 0, !noAssert)
      checkOffset(offset, 4, this.length);
    return read(this, offset, true, 23, 4);
  };
  Buffer2.prototype.readFloatBE = function(offset, noAssert) {
    if (offset = offset >>> 0, !noAssert)
      checkOffset(offset, 4, this.length);
    return read(this, offset, false, 23, 4);
  };
  Buffer2.prototype.readDoubleLE = function(offset, noAssert) {
    if (offset = offset >>> 0, !noAssert)
      checkOffset(offset, 8, this.length);
    return read(this, offset, true, 52, 8);
  };
  Buffer2.prototype.readDoubleBE = function(offset, noAssert) {
    if (offset = offset >>> 0, !noAssert)
      checkOffset(offset, 8, this.length);
    return read(this, offset, false, 52, 8);
  };
  Buffer2.prototype.writeUintLE = Buffer2.prototype.writeUIntLE = function(value, offset, byteLength2, noAssert) {
    if (value = +value, offset = offset >>> 0, byteLength2 = byteLength2 >>> 0, !noAssert) {
      let maxBytes = Math.pow(2, 8 * byteLength2) - 1;
      checkInt(this, value, offset, byteLength2, maxBytes, 0);
    }
    let mul = 1, i2 = 0;
    this[offset] = value & 255;
    while (++i2 < byteLength2 && (mul *= 256))
      this[offset + i2] = value / mul & 255;
    return offset + byteLength2;
  };
  Buffer2.prototype.writeUintBE = Buffer2.prototype.writeUIntBE = function(value, offset, byteLength2, noAssert) {
    if (value = +value, offset = offset >>> 0, byteLength2 = byteLength2 >>> 0, !noAssert) {
      let maxBytes = Math.pow(2, 8 * byteLength2) - 1;
      checkInt(this, value, offset, byteLength2, maxBytes, 0);
    }
    let i2 = byteLength2 - 1, mul = 1;
    this[offset + i2] = value & 255;
    while (--i2 >= 0 && (mul *= 256))
      this[offset + i2] = value / mul & 255;
    return offset + byteLength2;
  };
  Buffer2.prototype.writeUint8 = Buffer2.prototype.writeUInt8 = function(value, offset, noAssert) {
    if (value = +value, offset = offset >>> 0, !noAssert)
      checkInt(this, value, offset, 1, 255, 0);
    return this[offset] = value & 255, offset + 1;
  };
  Buffer2.prototype.writeUint16LE = Buffer2.prototype.writeUInt16LE = function(value, offset, noAssert) {
    if (value = +value, offset = offset >>> 0, !noAssert)
      checkInt(this, value, offset, 2, 65535, 0);
    return this[offset] = value & 255, this[offset + 1] = value >>> 8, offset + 2;
  };
  Buffer2.prototype.writeUint16BE = Buffer2.prototype.writeUInt16BE = function(value, offset, noAssert) {
    if (value = +value, offset = offset >>> 0, !noAssert)
      checkInt(this, value, offset, 2, 65535, 0);
    return this[offset] = value >>> 8, this[offset + 1] = value & 255, offset + 2;
  };
  Buffer2.prototype.writeUint32LE = Buffer2.prototype.writeUInt32LE = function(value, offset, noAssert) {
    if (value = +value, offset = offset >>> 0, !noAssert)
      checkInt(this, value, offset, 4, 4294967295, 0);
    return this[offset + 3] = value >>> 24, this[offset + 2] = value >>> 16, this[offset + 1] = value >>> 8, this[offset] = value & 255, offset + 4;
  };
  Buffer2.prototype.writeUint32BE = Buffer2.prototype.writeUInt32BE = function(value, offset, noAssert) {
    if (value = +value, offset = offset >>> 0, !noAssert)
      checkInt(this, value, offset, 4, 4294967295, 0);
    return this[offset] = value >>> 24, this[offset + 1] = value >>> 16, this[offset + 2] = value >>> 8, this[offset + 3] = value & 255, offset + 4;
  };
  Buffer2.prototype.writeBigUInt64LE = defineBigIntMethod(function(value, offset = 0) {
    return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff"));
  });
  Buffer2.prototype.writeBigUInt64BE = defineBigIntMethod(function(value, offset = 0) {
    return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff"));
  });
  Buffer2.prototype.writeIntLE = function(value, offset, byteLength2, noAssert) {
    if (value = +value, offset = offset >>> 0, !noAssert) {
      let limit = Math.pow(2, 8 * byteLength2 - 1);
      checkInt(this, value, offset, byteLength2, limit - 1, -limit);
    }
    let i2 = 0, mul = 1, sub = 0;
    this[offset] = value & 255;
    while (++i2 < byteLength2 && (mul *= 256)) {
      if (value < 0 && sub === 0 && this[offset + i2 - 1] !== 0)
        sub = 1;
      this[offset + i2] = (value / mul >> 0) - sub & 255;
    }
    return offset + byteLength2;
  };
  Buffer2.prototype.writeIntBE = function(value, offset, byteLength2, noAssert) {
    if (value = +value, offset = offset >>> 0, !noAssert) {
      let limit = Math.pow(2, 8 * byteLength2 - 1);
      checkInt(this, value, offset, byteLength2, limit - 1, -limit);
    }
    let i2 = byteLength2 - 1, mul = 1, sub = 0;
    this[offset + i2] = value & 255;
    while (--i2 >= 0 && (mul *= 256)) {
      if (value < 0 && sub === 0 && this[offset + i2 + 1] !== 0)
        sub = 1;
      this[offset + i2] = (value / mul >> 0) - sub & 255;
    }
    return offset + byteLength2;
  };
  Buffer2.prototype.writeInt8 = function(value, offset, noAssert) {
    if (value = +value, offset = offset >>> 0, !noAssert)
      checkInt(this, value, offset, 1, 127, -128);
    if (value < 0)
      value = 255 + value + 1;
    return this[offset] = value & 255, offset + 1;
  };
  Buffer2.prototype.writeInt16LE = function(value, offset, noAssert) {
    if (value = +value, offset = offset >>> 0, !noAssert)
      checkInt(this, value, offset, 2, 32767, -32768);
    return this[offset] = value & 255, this[offset + 1] = value >>> 8, offset + 2;
  };
  Buffer2.prototype.writeInt16BE = function(value, offset, noAssert) {
    if (value = +value, offset = offset >>> 0, !noAssert)
      checkInt(this, value, offset, 2, 32767, -32768);
    return this[offset] = value >>> 8, this[offset + 1] = value & 255, offset + 2;
  };
  Buffer2.prototype.writeInt32LE = function(value, offset, noAssert) {
    if (value = +value, offset = offset >>> 0, !noAssert)
      checkInt(this, value, offset, 4, 2147483647, -2147483648);
    return this[offset] = value & 255, this[offset + 1] = value >>> 8, this[offset + 2] = value >>> 16, this[offset + 3] = value >>> 24, offset + 4;
  };
  Buffer2.prototype.writeInt32BE = function(value, offset, noAssert) {
    if (value = +value, offset = offset >>> 0, !noAssert)
      checkInt(this, value, offset, 4, 2147483647, -2147483648);
    if (value < 0)
      value = 4294967295 + value + 1;
    return this[offset] = value >>> 24, this[offset + 1] = value >>> 16, this[offset + 2] = value >>> 8, this[offset + 3] = value & 255, offset + 4;
  };
  Buffer2.prototype.writeBigInt64LE = defineBigIntMethod(function(value, offset = 0) {
    return wrtBigUInt64LE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff"));
  });
  Buffer2.prototype.writeBigInt64BE = defineBigIntMethod(function(value, offset = 0) {
    return wrtBigUInt64BE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff"));
  });
  Buffer2.prototype.writeFloatLE = function(value, offset, noAssert) {
    return writeFloat(this, value, offset, true, noAssert);
  };
  Buffer2.prototype.writeFloatBE = function(value, offset, noAssert) {
    return writeFloat(this, value, offset, false, noAssert);
  };
  Buffer2.prototype.writeDoubleLE = function(value, offset, noAssert) {
    return writeDouble(this, value, offset, true, noAssert);
  };
  Buffer2.prototype.writeDoubleBE = function(value, offset, noAssert) {
    return writeDouble(this, value, offset, false, noAssert);
  };
  Buffer2.prototype.copy = function(target, targetStart, start, end) {
    if (!Buffer2.isBuffer(target))
      throw TypeError("argument should be a Buffer");
    if (!start)
      start = 0;
    if (!end && end !== 0)
      end = this.length;
    if (targetStart >= target.length)
      targetStart = target.length;
    if (!targetStart)
      targetStart = 0;
    if (end > 0 && end < start)
      end = start;
    if (end === start)
      return 0;
    if (target.length === 0 || this.length === 0)
      return 0;
    if (targetStart < 0)
      throw RangeError("targetStart out of bounds");
    if (start < 0 || start >= this.length)
      throw RangeError("Index out of range");
    if (end < 0)
      throw RangeError("sourceEnd out of bounds");
    if (end > this.length)
      end = this.length;
    if (target.length - targetStart < end - start)
      end = target.length - targetStart + start;
    let len2 = end - start;
    if (this === target && typeof Uint8Array.prototype.copyWithin === "function")
      this.copyWithin(targetStart, start, end);
    else
      Uint8Array.prototype.set.call(target, this.subarray(start, end), targetStart);
    return len2;
  };
  Buffer2.prototype.fill = function(val, start, end, encoding) {
    if (typeof val === "string") {
      if (typeof start === "string")
        encoding = start, start = 0, end = this.length;
      else if (typeof end === "string")
        encoding = end, end = this.length;
      if (encoding !== undefined && typeof encoding !== "string")
        throw TypeError("encoding must be a string");
      if (typeof encoding === "string" && !Buffer2.isEncoding(encoding))
        throw TypeError("Unknown encoding: " + encoding);
      if (val.length === 1) {
        let code2 = val.charCodeAt(0);
        if (encoding === "utf8" && code2 < 128 || encoding === "latin1")
          val = code2;
      }
    } else if (typeof val === "number")
      val = val & 255;
    else if (typeof val === "boolean")
      val = Number(val);
    if (start < 0 || this.length < start || this.length < end)
      throw RangeError("Out of range index");
    if (end <= start)
      return this;
    if (start = start >>> 0, end = end === undefined ? this.length : end >>> 0, !val)
      val = 0;
    let i2;
    if (typeof val === "number")
      for (i2 = start;i2 < end; ++i2)
        this[i2] = val;
    else {
      let bytes = Buffer2.isBuffer(val) ? val : Buffer2.from(val, encoding), len2 = bytes.length;
      if (len2 === 0)
        throw TypeError('The value "' + val + '" is invalid for argument "value"');
      for (i2 = 0;i2 < end - start; ++i2)
        this[i2 + start] = bytes[i2 % len2];
    }
    return this;
  };
  INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;
  hexSliceLookupTable = function() {
    let table = Array(256);
    for (let i2 = 0;i2 < 16; ++i2) {
      let i16 = i2 * 16;
      for (let j = 0;j < 16; ++j)
        table[i16 + j] = "0123456789abcdef"[i2] + "0123456789abcdef"[j];
    }
    return table;
  }();
  resolveObjectURL = notimpl("resolveObjectURL");
  isUtf8 = notimpl("isUtf8");
  transcode = notimpl("transcode");
  buffer_default = Buffer2;
});

// node:util
var exports_util = {};
__export(exports_util, {
  types: () => types2,
  promisify: () => promisify,
  log: () => log,
  isUndefined: () => isUndefined2,
  isSymbol: () => isSymbol,
  isString: () => isString,
  isRegExp: () => isRegExp,
  isPrimitive: () => isPrimitive,
  isObject: () => isObject2,
  isNumber: () => isNumber,
  isNullOrUndefined: () => isNullOrUndefined,
  isNull: () => isNull,
  isFunction: () => isFunction,
  isError: () => isError,
  isDate: () => isDate,
  isBuffer: () => isBuffer,
  isBoolean: () => isBoolean,
  isArray: () => isArray,
  inspect: () => inspect,
  inherits: () => inherits,
  format: () => format,
  deprecate: () => deprecate,
  default: () => util_default,
  debuglog: () => debuglog,
  callbackifyOnRejected: () => callbackifyOnRejected,
  callbackify: () => callbackify,
  _extend: () => _extend,
  TextEncoder: () => TextEncoder2,
  TextDecoder: () => TextDecoder2
});
function format(f, ...args) {
  if (!isString(f)) {
    var objects = [f];
    for (var i2 = 0;i2 < args.length; i2++)
      objects.push(inspect(args[i2]));
    return objects.join(" ");
  }
  var i2 = 0, len2 = args.length, str = String(f).replace(formatRegExp, function(x2) {
    if (x2 === "%%")
      return "%";
    if (i2 >= len2)
      return x2;
    switch (x2) {
      case "%s":
        return String(args[i2++]);
      case "%d":
        return Number(args[i2++]);
      case "%j":
        try {
          return JSON.stringify(args[i2++]);
        } catch (_) {
          return "[Circular]";
        }
      default:
        return x2;
    }
  });
  for (var x = args[i2];i2 < len2; x = args[++i2])
    if (isNull(x) || !isObject2(x))
      str += " " + x;
    else
      str += " " + inspect(x);
  return str;
}
function deprecate(fn, msg) {
  if (typeof process > "u" || process?.noDeprecation === true)
    return fn;
  var warned = false;
  function deprecated(...args) {
    if (!warned) {
      if (process.throwDeprecation)
        throw Error(msg);
      else if (process.traceDeprecation)
        console.trace(msg);
      else
        console.error(msg);
      warned = true;
    }
    return fn.apply(this, ...args);
  }
  return deprecated;
}
function stylizeWithColor(str, styleType) {
  var style = inspect.styles[styleType];
  if (style)
    return "\x1B[" + inspect.colors[style][0] + "m" + str + "\x1B[" + inspect.colors[style][1] + "m";
  else
    return str;
}
function stylizeNoColor(str, styleType) {
  return str;
}
function arrayToHash(array) {
  var hash = {};
  return array.forEach(function(val, idx) {
    hash[val] = true;
  }), hash;
}
function formatValue(ctx, value, recurseTimes) {
  if (ctx.customInspect && value && isFunction(value.inspect) && value.inspect !== inspect && !(value.constructor && value.constructor.prototype === value)) {
    var ret = value.inspect(recurseTimes, ctx);
    if (!isString(ret))
      ret = formatValue(ctx, ret, recurseTimes);
    return ret;
  }
  var primitive = formatPrimitive(ctx, value);
  if (primitive)
    return primitive;
  var keys = Object.keys(value), visibleKeys = arrayToHash(keys);
  if (ctx.showHidden)
    keys = Object.getOwnPropertyNames(value);
  if (isError(value) && (keys.indexOf("message") >= 0 || keys.indexOf("description") >= 0))
    return formatError(value);
  if (keys.length === 0) {
    if (isFunction(value)) {
      var name = value.name ? ": " + value.name : "";
      return ctx.stylize("[Function" + name + "]", "special");
    }
    if (isRegExp(value))
      return ctx.stylize(RegExp.prototype.toString.call(value), "regexp");
    if (isDate(value))
      return ctx.stylize(Date.prototype.toString.call(value), "date");
    if (isError(value))
      return formatError(value);
  }
  var base = "", array = false, braces = ["{", "}"];
  if (isArray(value))
    array = true, braces = ["[", "]"];
  if (isFunction(value)) {
    var n2 = value.name ? ": " + value.name : "";
    base = " [Function" + n2 + "]";
  }
  if (isRegExp(value))
    base = " " + RegExp.prototype.toString.call(value);
  if (isDate(value))
    base = " " + Date.prototype.toUTCString.call(value);
  if (isError(value))
    base = " " + formatError(value);
  if (keys.length === 0 && (!array || value.length == 0))
    return braces[0] + base + braces[1];
  if (recurseTimes < 0)
    if (isRegExp(value))
      return ctx.stylize(RegExp.prototype.toString.call(value), "regexp");
    else
      return ctx.stylize("[Object]", "special");
  ctx.seen.push(value);
  var output;
  if (array)
    output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  else
    output = keys.map(function(key) {
      return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
    });
  return ctx.seen.pop(), reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
  if (isUndefined2(value))
    return ctx.stylize("undefined", "undefined");
  if (isString(value)) {
    var simple = "'" + JSON.stringify(value).replace(/^"|"$/g, "").replace(/'/g, "\\'").replace(/\\"/g, '"') + "'";
    return ctx.stylize(simple, "string");
  }
  if (isNumber(value))
    return ctx.stylize("" + value, "number");
  if (isBoolean(value))
    return ctx.stylize("" + value, "boolean");
  if (isNull(value))
    return ctx.stylize("null", "null");
}
function formatError(value) {
  return "[" + Error.prototype.toString.call(value) + "]";
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  var output = [];
  for (var i2 = 0, l2 = value.length;i2 < l2; ++i2)
    if (hasOwnProperty(value, String(i2)))
      output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i2), true));
    else
      output.push("");
  return keys.forEach(function(key) {
    if (!key.match(/^\d+$/))
      output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true));
  }), output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  var name, str, desc;
  if (desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }, desc.get)
    if (desc.set)
      str = ctx.stylize("[Getter/Setter]", "special");
    else
      str = ctx.stylize("[Getter]", "special");
  else if (desc.set)
    str = ctx.stylize("[Setter]", "special");
  if (!hasOwnProperty(visibleKeys, key))
    name = "[" + key + "]";
  if (!str)
    if (ctx.seen.indexOf(desc.value) < 0) {
      if (isNull(recurseTimes))
        str = formatValue(ctx, desc.value, null);
      else
        str = formatValue(ctx, desc.value, recurseTimes - 1);
      if (str.indexOf(`
`) > -1)
        if (array)
          str = str.split(`
`).map(function(line) {
            return "  " + line;
          }).join(`
`).slice(2);
        else
          str = `
` + str.split(`
`).map(function(line) {
            return "   " + line;
          }).join(`
`);
    } else
      str = ctx.stylize("[Circular]", "special");
  if (isUndefined2(name)) {
    if (array && key.match(/^\d+$/))
      return str;
    if (name = JSON.stringify("" + key), name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/))
      name = name.slice(1, -1), name = ctx.stylize(name, "name");
    else
      name = name.replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'"), name = ctx.stylize(name, "string");
  }
  return name + ": " + str;
}
function reduceToSingleString(output, base, braces) {
  var numLinesEst = 0, length = output.reduce(function(prev, cur) {
    if (numLinesEst++, cur.indexOf(`
`) >= 0)
      numLinesEst++;
    return prev + cur.replace(/\u001b\[\d\d?m/g, "").length + 1;
  }, 0);
  if (length > 60)
    return braces[0] + (base === "" ? "" : base + `
 `) + " " + output.join(`,
  `) + " " + braces[1];
  return braces[0] + base + " " + output.join(", ") + " " + braces[1];
}
function isArray(ar) {
  return Array.isArray(ar);
}
function isBoolean(arg) {
  return typeof arg === "boolean";
}
function isNull(arg) {
  return arg === null;
}
function isNullOrUndefined(arg) {
  return arg == null;
}
function isNumber(arg) {
  return typeof arg === "number";
}
function isString(arg) {
  return typeof arg === "string";
}
function isSymbol(arg) {
  return typeof arg === "symbol";
}
function isUndefined2(arg) {
  return arg === undefined;
}
function isRegExp(re) {
  return isObject2(re) && objectToString(re) === "[object RegExp]";
}
function isObject2(arg) {
  return typeof arg === "object" && arg !== null;
}
function isDate(d) {
  return isObject2(d) && objectToString(d) === "[object Date]";
}
function isError(e2) {
  return isObject2(e2) && (objectToString(e2) === "[object Error]" || e2 instanceof Error);
}
function isFunction(arg) {
  return typeof arg === "function";
}
function isPrimitive(arg) {
  return arg === null || typeof arg === "boolean" || typeof arg === "number" || typeof arg === "string" || typeof arg === "symbol" || typeof arg > "u";
}
function isBuffer(arg) {
  return arg instanceof Buffer;
}
function objectToString(o2) {
  return Object.prototype.toString.call(o2);
}
function pad(n2) {
  return n2 < 10 ? "0" + n2.toString(10) : n2.toString(10);
}
function timestamp() {
  var d = new Date, time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(":");
  return [d.getDate(), months[d.getMonth()], time].join(" ");
}
function log(...args) {
  console.log("%s - %s", timestamp(), format.apply(null, args));
}
function inherits(ctor, superCtor) {
  if (superCtor)
    ctor.super_ = superCtor, ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } });
}
function _extend(origin, add) {
  if (!add || !isObject2(add))
    return origin;
  var keys = Object.keys(add), i2 = keys.length;
  while (i2--)
    origin[keys[i2]] = add[keys[i2]];
  return origin;
}
function hasOwnProperty(obj, prop) {
  return Object.prototype.hasOwnProperty.call(obj, prop);
}
function callbackifyOnRejected(reason, cb) {
  if (!reason) {
    var newReason = Error("Promise was rejected with a falsy value");
    newReason.reason = reason, reason = newReason;
  }
  return cb(reason);
}
function callbackify(original) {
  if (typeof original !== "function")
    throw TypeError('The "original" argument must be of type Function');
  function callbackified(...args) {
    var maybeCb = args.pop();
    if (typeof maybeCb !== "function")
      throw TypeError("The last argument must be of type Function");
    var self2 = this, cb = function(...args2) {
      return maybeCb.apply(self2, ...args2);
    };
    original.apply(this, args).then(function(ret) {
      process.nextTick(cb.bind(null, null, ret));
    }, function(rej) {
      process.nextTick(callbackifyOnRejected.bind(null, rej, cb));
    });
  }
  return Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original)), Object.defineProperties(callbackified, Object.getOwnPropertyDescriptors(original)), callbackified;
}
var formatRegExp, debuglog, inspect, types2 = () => {}, months, promisify, TextEncoder2, TextDecoder2, util_default;
var init_util = __esm(() => {
  formatRegExp = /%[sdj%]/g;
  debuglog = ((debugs = {}, debugEnvRegex = {}, debugEnv) => ((debugEnv = typeof process < "u" && false) && (debugEnv = debugEnv.replace(/[|\\{}()[\]^$+?.]/g, "\\$&").replace(/\*/g, ".*").replace(/,/g, "$|^").toUpperCase()), debugEnvRegex = new RegExp("^" + debugEnv + "$", "i"), (set) => {
    if (set = set.toUpperCase(), !debugs[set])
      if (debugEnvRegex.test(set))
        debugs[set] = function(...args) {
          console.error("%s: %s", set, pid, format.apply(null, ...args));
        };
      else
        debugs[set] = function() {};
    return debugs[set];
  }))();
  inspect = ((i2) => (i2.colors = { bold: [1, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], white: [37, 39], grey: [90, 39], black: [30, 39], blue: [34, 39], cyan: [36, 39], green: [32, 39], magenta: [35, 39], red: [31, 39], yellow: [33, 39] }, i2.styles = { special: "cyan", number: "yellow", boolean: "yellow", undefined: "grey", null: "bold", string: "green", date: "magenta", regexp: "red" }, i2.custom = Symbol.for("nodejs.util.inspect.custom"), i2))(function(obj, opts, ...rest) {
    var ctx = { seen: [], stylize: stylizeNoColor };
    if (rest.length >= 1)
      ctx.depth = rest[0];
    if (rest.length >= 2)
      ctx.colors = rest[1];
    if (isBoolean(opts))
      ctx.showHidden = opts;
    else if (opts)
      _extend(ctx, opts);
    if (isUndefined2(ctx.showHidden))
      ctx.showHidden = false;
    if (isUndefined2(ctx.depth))
      ctx.depth = 2;
    if (isUndefined2(ctx.colors))
      ctx.colors = false;
    if (ctx.colors)
      ctx.stylize = stylizeWithColor;
    return formatValue(ctx, obj, ctx.depth);
  });
  months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
  promisify = ((x) => (x.custom = Symbol.for("nodejs.util.promisify.custom"), x))(function(original) {
    if (typeof original !== "function")
      throw TypeError('The "original" argument must be of type Function');
    if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) {
      var fn = original[kCustomPromisifiedSymbol];
      if (typeof fn !== "function")
        throw TypeError('The "nodejs.util.promisify.custom" argument must be of type Function');
      return Object.defineProperty(fn, kCustomPromisifiedSymbol, { value: fn, enumerable: false, writable: false, configurable: true }), fn;
    }
    function fn(...args) {
      var promiseResolve, promiseReject, promise = new Promise(function(resolve, reject) {
        promiseResolve = resolve, promiseReject = reject;
      });
      args.push(function(err, value) {
        if (err)
          promiseReject(err);
        else
          promiseResolve(value);
      });
      try {
        original.apply(this, args);
      } catch (err) {
        promiseReject(err);
      }
      return promise;
    }
    if (Object.setPrototypeOf(fn, Object.getPrototypeOf(original)), kCustomPromisifiedSymbol)
      Object.defineProperty(fn, kCustomPromisifiedSymbol, { value: fn, enumerable: false, writable: false, configurable: true });
    return Object.defineProperties(fn, Object.getOwnPropertyDescriptors(original));
  });
  ({ TextEncoder: TextEncoder2, TextDecoder: TextDecoder2 } = globalThis);
  util_default = { TextEncoder: TextEncoder2, TextDecoder: TextDecoder2, promisify, log, inherits, _extend, callbackifyOnRejected, callbackify };
});

// node:events
var exports_events = {};
__export(exports_events, {
  setMaxListeners: () => setMaxListeners2,
  once: () => once2,
  listenerCount: () => listenerCount2,
  init: () => EventEmitter,
  getMaxListeners: () => getMaxListeners2,
  getEventListeners: () => getEventListeners,
  default: () => events_default,
  captureRejectionSymbol: () => captureRejectionSymbol,
  addAbortListener: () => addAbortListener,
  EventEmitter: () => EventEmitter
});
function emitError(emitter, args) {
  var { _events: events } = emitter;
  if (args[0] ??= Error("Unhandled error."), !events)
    throw args[0];
  var errorMonitor = events[kErrorMonitor];
  if (errorMonitor)
    for (var handler of ArrayPrototypeSlice.call(errorMonitor))
      handler.apply(emitter, args);
  var handlers = events.error;
  if (!handlers)
    throw args[0];
  for (var handler of ArrayPrototypeSlice.call(handlers))
    handler.apply(emitter, args);
  return true;
}
function addCatch(emitter, promise, type, args) {
  promise.then(undefined, function(err) {
    queueMicrotask(() => emitUnhandledRejectionOrErr(emitter, err, type, args));
  });
}
function emitUnhandledRejectionOrErr(emitter, err, type, args) {
  if (typeof emitter[kRejection] === "function")
    emitter[kRejection](err, type, ...args);
  else
    try {
      emitter[kCapture] = false, emitter.emit("error", err);
    } finally {
      emitter[kCapture] = true;
    }
}
function overflowWarning(emitter, type, handlers) {
  handlers.warned = true;
  let warn = Error(`Possible EventEmitter memory leak detected. ${handlers.length} ${String(type)} listeners added to [${emitter.constructor.name}]. Use emitter.setMaxListeners() to increase limit`);
  warn.name = "MaxListenersExceededWarning", warn.emitter = emitter, warn.type = type, warn.count = handlers.length, console.warn(warn);
}
function onceWrapper(type, listener, ...args) {
  this.removeListener(type, listener), listener.apply(this, args);
}
function once2(emitter, type, options) {
  var signal = options?.signal;
  if (validateAbortSignal(signal, "options.signal"), signal?.aborted)
    throw new AbortError(undefined, { cause: signal?.reason });
  let { resolve, reject, promise } = $newPromiseCapability(Promise), errorListener = (err) => {
    if (emitter.removeListener(type, resolver), signal != null)
      eventTargetAgnosticRemoveListener(signal, "abort", abortListener);
    reject(err);
  }, resolver = (...args) => {
    if (typeof emitter.removeListener === "function")
      emitter.removeListener("error", errorListener);
    if (signal != null)
      eventTargetAgnosticRemoveListener(signal, "abort", abortListener);
    resolve(args);
  };
  if (eventTargetAgnosticAddListener(emitter, type, resolver, { once: true }), type !== "error" && typeof emitter.once === "function")
    emitter.once("error", errorListener);
  function abortListener() {
    eventTargetAgnosticRemoveListener(emitter, type, resolver), eventTargetAgnosticRemoveListener(emitter, "error", errorListener), reject(new AbortError(undefined, { cause: signal?.reason }));
  }
  if (signal != null)
    eventTargetAgnosticAddListener(signal, "abort", abortListener, { once: true });
  return promise;
}
function getEventListeners(emitter, type) {
  return emitter.listeners(type);
}
function setMaxListeners2(n2, ...eventTargets) {
  validateNumber2(n2, "setMaxListeners", 0);
  var length;
  if (eventTargets && (length = eventTargets.length))
    for (let i2 = 0;i2 < length; i2++)
      eventTargets[i2].setMaxListeners(n2);
  else
    defaultMaxListeners = n2;
}
function listenerCount2(emitter, type) {
  return emitter.listenerCount(type);
}
function eventTargetAgnosticRemoveListener(emitter, name, listener, flags) {
  if (typeof emitter.removeListener === "function")
    emitter.removeListener(name, listener);
  else
    emitter.removeEventListener(name, listener, flags);
}
function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
  if (typeof emitter.on === "function")
    if (flags.once)
      emitter.once(name, listener);
    else
      emitter.on(name, listener);
  else
    emitter.addEventListener(name, listener, flags);
}
function ERR_INVALID_ARG_TYPE2(name, type, value) {
  let err = TypeError(`The "${name}" argument must be of type ${type}. Received ${value}`);
  return err.code = "ERR_INVALID_ARG_TYPE", err;
}
function ERR_OUT_OF_RANGE2(name, range, value) {
  let err = RangeError(`The "${name}" argument is out of range. It must be ${range}. Received ${value}`);
  return err.code = "ERR_OUT_OF_RANGE", err;
}
function validateAbortSignal(signal, name) {
  if (signal !== undefined && (signal === null || typeof signal !== "object" || !("aborted" in signal)))
    throw ERR_INVALID_ARG_TYPE2(name, "AbortSignal", signal);
}
function validateNumber2(value, name, min, max) {
  if (typeof value !== "number")
    throw ERR_INVALID_ARG_TYPE2(name, "number", value);
  if (min != null && value < min || max != null && value > max || (min != null || max != null) && Number.isNaN(value))
    throw ERR_OUT_OF_RANGE2(name, `${min != null ? `>= ${min}` : ""}${min != null && max != null ? " && " : ""}${max != null ? `<= ${max}` : ""}`, value);
}
function checkListener(listener) {
  if (typeof listener !== "function")
    throw TypeError("The listener must be a function");
}
function validateBoolean(value, name) {
  if (typeof value !== "boolean")
    throw ERR_INVALID_ARG_TYPE2(name, "boolean", value);
}
function getMaxListeners2(emitterOrTarget) {
  return emitterOrTarget?._maxListeners ?? defaultMaxListeners;
}
function addAbortListener(signal, listener) {
  if (signal === undefined)
    throw ERR_INVALID_ARG_TYPE2("signal", "AbortSignal", signal);
  if (validateAbortSignal(signal, "signal"), typeof listener !== "function")
    throw ERR_INVALID_ARG_TYPE2("listener", "function", listener);
  let removeEventListener;
  if (signal.aborted)
    queueMicrotask(() => listener());
  else
    signal.addEventListener("abort", listener, { __proto__: null, once: true }), removeEventListener = () => {
      signal.removeEventListener("abort", listener);
    };
  return { __proto__: null, [Symbol.dispose]() {
    removeEventListener?.();
  } };
}
var SymbolFor, kCapture, kErrorMonitor, kMaxEventTargetListeners, kMaxEventTargetListenersWarned, kRejection, captureRejectionSymbol, ArrayPrototypeSlice, defaultMaxListeners = 10, EventEmitter = function(opts) {
  if (this._events === undefined || this._events === this.__proto__._events)
    this._events = { __proto__: null }, this._eventsCount = 0;
  if (this._maxListeners ??= undefined, this[kCapture] = opts?.captureRejections ? Boolean(opts?.captureRejections) : EventEmitterPrototype[kCapture])
    this.emit = emitWithRejectionCapture;
}, EventEmitterPrototype, emitWithoutRejectionCapture = function(type, ...args) {
  if (type === "error")
    return emitError(this, args);
  var { _events: events } = this;
  if (events === undefined)
    return false;
  var handlers = events[type];
  if (handlers === undefined)
    return false;
  let maybeClonedHandlers = handlers.length > 1 ? handlers.slice() : handlers;
  for (let i2 = 0, { length } = maybeClonedHandlers;i2 < length; i2++) {
    let handler = maybeClonedHandlers[i2];
    switch (args.length) {
      case 0:
        handler.call(this);
        break;
      case 1:
        handler.call(this, args[0]);
        break;
      case 2:
        handler.call(this, args[0], args[1]);
        break;
      case 3:
        handler.call(this, args[0], args[1], args[2]);
        break;
      default:
        handler.apply(this, args);
        break;
    }
  }
  return true;
}, emitWithRejectionCapture = function(type, ...args) {
  if (type === "error")
    return emitError(this, args);
  var { _events: events } = this;
  if (events === undefined)
    return false;
  var handlers = events[type];
  if (handlers === undefined)
    return false;
  let maybeClonedHandlers = handlers.length > 1 ? handlers.slice() : handlers;
  for (let i2 = 0, { length } = maybeClonedHandlers;i2 < length; i2++) {
    let handler = maybeClonedHandlers[i2], result;
    switch (args.length) {
      case 0:
        result = handler.call(this);
        break;
      case 1:
        result = handler.call(this, args[0]);
        break;
      case 2:
        result = handler.call(this, args[0], args[1]);
        break;
      case 3:
        result = handler.call(this, args[0], args[1], args[2]);
        break;
      default:
        result = handler.apply(this, args);
        break;
    }
    if (result !== undefined && typeof result?.then === "function" && result.then === Promise.prototype.then)
      addCatch(this, result, type, args);
  }
  return true;
}, AbortError, events_default;
var init_events = __esm(() => {
  SymbolFor = Symbol.for;
  kCapture = Symbol("kCapture");
  kErrorMonitor = SymbolFor("events.errorMonitor");
  kMaxEventTargetListeners = Symbol("events.maxEventTargetListeners");
  kMaxEventTargetListenersWarned = Symbol("events.maxEventTargetListenersWarned");
  kRejection = SymbolFor("nodejs.rejection");
  captureRejectionSymbol = SymbolFor("nodejs.rejection");
  ArrayPrototypeSlice = Array.prototype.slice;
  EventEmitterPrototype = EventEmitter.prototype = {};
  EventEmitterPrototype._events = undefined;
  EventEmitterPrototype._eventsCount = 0;
  EventEmitterPrototype._maxListeners = undefined;
  EventEmitterPrototype.setMaxListeners = function(n2) {
    return validateNumber2(n2, "setMaxListeners", 0), this._maxListeners = n2, this;
  };
  EventEmitterPrototype.constructor = EventEmitter;
  EventEmitterPrototype.getMaxListeners = function() {
    return this?._maxListeners ?? defaultMaxListeners;
  };
  EventEmitterPrototype.emit = emitWithoutRejectionCapture;
  EventEmitterPrototype.addListener = function(type, fn) {
    checkListener(fn);
    var events = this._events;
    if (!events)
      events = this._events = { __proto__: null }, this._eventsCount = 0;
    else if (events.newListener)
      this.emit("newListener", type, fn.listener ?? fn);
    var handlers = events[type];
    if (!handlers)
      events[type] = [fn], this._eventsCount++;
    else {
      handlers.push(fn);
      var m = this._maxListeners ?? defaultMaxListeners;
      if (m > 0 && handlers.length > m && !handlers.warned)
        overflowWarning(this, type, handlers);
    }
    return this;
  };
  EventEmitterPrototype.on = EventEmitterPrototype.addListener;
  EventEmitterPrototype.prependListener = function(type, fn) {
    checkListener(fn);
    var events = this._events;
    if (!events)
      events = this._events = { __proto__: null }, this._eventsCount = 0;
    else if (events.newListener)
      this.emit("newListener", type, fn.listener ?? fn);
    var handlers = events[type];
    if (!handlers)
      events[type] = [fn], this._eventsCount++;
    else {
      handlers.unshift(fn);
      var m = this._maxListeners ?? defaultMaxListeners;
      if (m > 0 && handlers.length > m && !handlers.warned)
        overflowWarning(this, type, handlers);
    }
    return this;
  };
  EventEmitterPrototype.once = function(type, fn) {
    checkListener(fn);
    let bound = onceWrapper.bind(this, type, fn);
    return bound.listener = fn, this.addListener(type, bound), this;
  };
  EventEmitterPrototype.prependOnceListener = function(type, fn) {
    checkListener(fn);
    let bound = onceWrapper.bind(this, type, fn);
    return bound.listener = fn, this.prependListener(type, bound), this;
  };
  EventEmitterPrototype.removeListener = function(type, fn) {
    checkListener(fn);
    var { _events: events } = this;
    if (!events)
      return this;
    var handlers = events[type];
    if (!handlers)
      return this;
    var length = handlers.length;
    let position = -1;
    for (let i2 = length - 1;i2 >= 0; i2--)
      if (handlers[i2] === fn || handlers[i2].listener === fn) {
        position = i2;
        break;
      }
    if (position < 0)
      return this;
    if (position === 0)
      handlers.shift();
    else
      handlers.splice(position, 1);
    if (handlers.length === 0)
      delete events[type], this._eventsCount--;
    return this;
  };
  EventEmitterPrototype.off = EventEmitterPrototype.removeListener;
  EventEmitterPrototype.removeAllListeners = function(type) {
    var { _events: events } = this;
    if (type && events) {
      if (events[type])
        delete events[type], this._eventsCount--;
    } else
      this._events = { __proto__: null };
    return this;
  };
  EventEmitterPrototype.listeners = function(type) {
    var { _events: events } = this;
    if (!events)
      return [];
    var handlers = events[type];
    if (!handlers)
      return [];
    return handlers.map((x) => x.listener ?? x);
  };
  EventEmitterPrototype.rawListeners = function(type) {
    var { _events } = this;
    if (!_events)
      return [];
    var handlers = _events[type];
    if (!handlers)
      return [];
    return handlers.slice();
  };
  EventEmitterPrototype.listenerCount = function(type) {
    var { _events: events } = this;
    if (!events)
      return 0;
    return events[type]?.length ?? 0;
  };
  EventEmitterPrototype.eventNames = function() {
    return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
  };
  EventEmitterPrototype[kCapture] = false;
  AbortError = class AbortError extends Error {
    constructor(message = "The operation was aborted", options = undefined) {
      if (options !== undefined && typeof options !== "object")
        throw ERR_INVALID_ARG_TYPE2("options", "Object", options);
      super(message, options);
      this.code = "ABORT_ERR", this.name = "AbortError";
    }
  };
  Object.defineProperties(EventEmitter, { captureRejections: { get() {
    return EventEmitterPrototype[kCapture];
  }, set(value) {
    validateBoolean(value, "EventEmitter.captureRejections"), EventEmitterPrototype[kCapture] = value;
  }, enumerable: true }, defaultMaxListeners: { enumerable: true, get: () => {
    return defaultMaxListeners;
  }, set: (arg) => {
    validateNumber2(arg, "defaultMaxListeners", 0), defaultMaxListeners = arg;
  } }, kMaxEventTargetListeners: { value: kMaxEventTargetListeners, enumerable: false, configurable: false, writable: false }, kMaxEventTargetListenersWarned: { value: kMaxEventTargetListenersWarned, enumerable: false, configurable: false, writable: false } });
  Object.assign(EventEmitter, { once: once2, getEventListeners, getMaxListeners: getMaxListeners2, setMaxListeners: setMaxListeners2, EventEmitter, usingDomains: false, captureRejectionSymbol, errorMonitor: kErrorMonitor, addAbortListener, init: EventEmitter, listenerCount: listenerCount2 });
  events_default = EventEmitter;
});

// node:stream
var require_stream = __commonJS((exports, module) => {
  var __commonJS2 = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
  var require_primordials = __commonJS2((exports2, module2) => {

    class AggregateError2 extends Error {
      constructor(errors) {
        if (!Array.isArray(errors))
          throw TypeError(`Expected input to be an Array, got ${typeof errors}`);
        let message = "";
        for (let i2 = 0;i2 < errors.length; i2++)
          message += `    ${errors[i2].stack}
`;
        super(message);
        this.name = "AggregateError", this.errors = errors;
      }
    }
    module2.exports = { AggregateError: AggregateError2, ArrayIsArray(self2) {
      return Array.isArray(self2);
    }, ArrayPrototypeIncludes(self2, el) {
      return self2.includes(el);
    }, ArrayPrototypeIndexOf(self2, el) {
      return self2.indexOf(el);
    }, ArrayPrototypeJoin(self2, sep) {
      return self2.join(sep);
    }, ArrayPrototypeMap(self2, fn) {
      return self2.map(fn);
    }, ArrayPrototypePop(self2, el) {
      return self2.pop(el);
    }, ArrayPrototypePush(self2, el) {
      return self2.push(el);
    }, ArrayPrototypeSlice(self2, start, end) {
      return self2.slice(start, end);
    }, Error, FunctionPrototypeCall(fn, thisArgs, ...args) {
      return fn.call(thisArgs, ...args);
    }, FunctionPrototypeSymbolHasInstance(self2, instance) {
      return Function.prototype[Symbol.hasInstance].call(self2, instance);
    }, MathFloor: Math.floor, Number, NumberIsInteger: Number.isInteger, NumberIsNaN: Number.isNaN, NumberMAX_SAFE_INTEGER: Number.MAX_SAFE_INTEGER, NumberMIN_SAFE_INTEGER: Number.MIN_SAFE_INTEGER, NumberParseInt: Number.parseInt, ObjectDefineProperties(self2, props) {
      return Object.defineProperties(self2, props);
    }, ObjectDefineProperty(self2, name, prop) {
      return Object.defineProperty(self2, name, prop);
    }, ObjectGetOwnPropertyDescriptor(self2, name) {
      return Object.getOwnPropertyDescriptor(self2, name);
    }, ObjectKeys(obj) {
      return Object.keys(obj);
    }, ObjectSetPrototypeOf(target, proto) {
      return Object.setPrototypeOf(target, proto);
    }, Promise, PromisePrototypeCatch(self2, fn) {
      return self2.catch(fn);
    }, PromisePrototypeThen(self2, thenFn, catchFn) {
      return self2.then(thenFn, catchFn);
    }, PromiseReject(err) {
      return Promise.reject(err);
    }, PromiseResolve(val) {
      return Promise.resolve(val);
    }, ReflectApply: Reflect.apply, RegExpPrototypeTest(self2, value) {
      return self2.test(value);
    }, SafeSet: Set, String, StringPrototypeSlice(self2, start, end) {
      return self2.slice(start, end);
    }, StringPrototypeToLowerCase(self2) {
      return self2.toLowerCase();
    }, StringPrototypeToUpperCase(self2) {
      return self2.toUpperCase();
    }, StringPrototypeTrim(self2) {
      return self2.trim();
    }, Symbol, SymbolFor: Symbol.for, SymbolAsyncIterator: Symbol.asyncIterator, SymbolHasInstance: Symbol.hasInstance, SymbolIterator: Symbol.iterator, SymbolDispose: Symbol.dispose || Symbol("Symbol.dispose"), SymbolAsyncDispose: Symbol.asyncDispose || Symbol("Symbol.asyncDispose"), TypedArrayPrototypeSet(self2, buf, len2) {
      return self2.set(buf, len2);
    }, Boolean, Uint8Array };
  });
  var require_inspect = __commonJS2((exports2, module2) => {
    module2.exports = { format(format2, ...args) {
      return format2.replace(/%([sdifj])/g, function(...[_unused, type]) {
        let replacement = args.shift();
        if (type === "f")
          return replacement.toFixed(6);
        else if (type === "j")
          return JSON.stringify(replacement);
        else if (type === "s" && typeof replacement === "object")
          return `${replacement.constructor !== Object ? replacement.constructor.name : ""} {}`.trim();
        else
          return replacement.toString();
      });
    }, inspect(value) {
      switch (typeof value) {
        case "string":
          if (value.includes("'")) {
            if (!value.includes('"'))
              return `"${value}"`;
            else if (!value.includes("`") && !value.includes("${"))
              return `\`${value}\``;
          }
          return `'${value}'`;
        case "number":
          if (isNaN(value))
            return "NaN";
          else if (Object.is(value, -0))
            return String(value);
          return value;
        case "bigint":
          return `${String(value)}n`;
        case "boolean":
        case "undefined":
          return String(value);
        case "object":
          return "{}";
      }
    } };
  });
  var require_errors = __commonJS2((exports2, module2) => {
    var { format: format2, inspect: inspect2 } = require_inspect(), { AggregateError: CustomAggregateError } = require_primordials(), AggregateError2 = globalThis.AggregateError || CustomAggregateError, kIsNodeError = Symbol("kIsNodeError"), kTypes = ["string", "function", "number", "object", "Function", "Object", "boolean", "bigint", "symbol"], classRegExp = /^([A-Z][a-z0-9]*)+$/, codes = {};
    function assert(value, message) {
      if (!value)
        throw new codes.ERR_INTERNAL_ASSERTION(message);
    }
    function addNumericalSeparator2(val) {
      let res = "", i2 = val.length, start = val[0] === "-" ? 1 : 0;
      for (;i2 >= start + 4; i2 -= 3)
        res = `_${val.slice(i2 - 3, i2)}${res}`;
      return `${val.slice(0, i2)}${res}`;
    }
    function getMessage(key, msg, args) {
      if (typeof msg === "function")
        return assert(msg.length <= args.length, `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${msg.length}).`), msg(...args);
      let expectedLength = (msg.match(/%[dfijoOs]/g) || []).length;
      if (assert(expectedLength === args.length, `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${expectedLength}).`), args.length === 0)
        return msg;
      return format2(msg, ...args);
    }
    function E2(code2, message, Base) {
      if (!Base)
        Base = Error;

      class NodeError extends Base {
        constructor(...args) {
          super(getMessage(code2, message, args));
        }
        toString() {
          return `${this.name} [${code2}]: ${this.message}`;
        }
      }
      Object.defineProperties(NodeError.prototype, { name: { value: Base.name, writable: true, enumerable: false, configurable: true }, toString: { value() {
        return `${this.name} [${code2}]: ${this.message}`;
      }, writable: true, enumerable: false, configurable: true } }), NodeError.prototype.code = code2, NodeError.prototype[kIsNodeError] = true, codes[code2] = NodeError;
    }
    function hideStackFrames(fn) {
      let hidden = "__node_internal_" + fn.name;
      return Object.defineProperty(fn, "name", { value: hidden }), fn;
    }
    function aggregateTwoErrors(innerError, outerError) {
      if (innerError && outerError && innerError !== outerError) {
        if (Array.isArray(outerError.errors))
          return outerError.errors.push(innerError), outerError;
        let err = new AggregateError2([outerError, innerError], outerError.message);
        return err.code = outerError.code, err;
      }
      return innerError || outerError;
    }

    class AbortError2 extends Error {
      constructor(message = "The operation was aborted", options = undefined) {
        if (options !== undefined && typeof options !== "object")
          throw new codes.ERR_INVALID_ARG_TYPE("options", "Object", options);
        super(message, options);
        this.code = "ABORT_ERR", this.name = "AbortError";
      }
    }
    E2("ERR_ASSERTION", "%s", Error);
    E2("ERR_INVALID_ARG_TYPE", (name, expected, actual) => {
      if (assert(typeof name === "string", "'name' must be a string"), !Array.isArray(expected))
        expected = [expected];
      let msg = "The ";
      if (name.endsWith(" argument"))
        msg += `${name} `;
      else
        msg += `"${name}" ${name.includes(".") ? "property" : "argument"} `;
      msg += "must be ";
      let types3 = [], instances = [], other = [];
      for (let value of expected)
        if (assert(typeof value === "string", "All expected entries have to be of type string"), kTypes.includes(value))
          types3.push(value.toLowerCase());
        else if (classRegExp.test(value))
          instances.push(value);
        else
          assert(value !== "object", 'The value "object" should be written as "Object"'), other.push(value);
      if (instances.length > 0) {
        let pos = types3.indexOf("object");
        if (pos !== -1)
          types3.splice(types3, pos, 1), instances.push("Object");
      }
      if (types3.length > 0) {
        switch (types3.length) {
          case 1:
            msg += `of type ${types3[0]}`;
            break;
          case 2:
            msg += `one of type ${types3[0]} or ${types3[1]}`;
            break;
          default: {
            let last = types3.pop();
            msg += `one of type ${types3.join(", ")}, or ${last}`;
          }
        }
        if (instances.length > 0 || other.length > 0)
          msg += " or ";
      }
      if (instances.length > 0) {
        switch (instances.length) {
          case 1:
            msg += `an instance of ${instances[0]}`;
            break;
          case 2:
            msg += `an instance of ${instances[0]} or ${instances[1]}`;
            break;
          default: {
            let last = instances.pop();
            msg += `an instance of ${instances.join(", ")}, or ${last}`;
          }
        }
        if (other.length > 0)
          msg += " or ";
      }
      switch (other.length) {
        case 0:
          break;
        case 1:
          if (other[0].toLowerCase() !== other[0])
            msg += "an ";
          msg += `${other[0]}`;
          break;
        case 2:
          msg += `one of ${other[0]} or ${other[1]}`;
          break;
        default: {
          let last = other.pop();
          msg += `one of ${other.join(", ")}, or ${last}`;
        }
      }
      if (actual == null)
        msg += `. Received ${actual}`;
      else if (typeof actual === "function" && actual.name)
        msg += `. Received function ${actual.name}`;
      else if (typeof actual === "object") {
        var _actual$constructor;
        if ((_actual$constructor = actual.constructor) !== null && _actual$constructor !== undefined && _actual$constructor.name)
          msg += `. Received an instance of ${actual.constructor.name}`;
        else {
          let inspected = inspect2(actual, { depth: -1 });
          msg += `. Received ${inspected}`;
        }
      } else {
        let inspected = inspect2(actual, { colors: false });
        if (inspected.length > 25)
          inspected = `${inspected.slice(0, 25)}...`;
        msg += `. Received type ${typeof actual} (${inspected})`;
      }
      return msg;
    }, TypeError);
    E2("ERR_INVALID_ARG_VALUE", (name, value, reason = "is invalid") => {
      let inspected = inspect2(value);
      if (inspected.length > 128)
        inspected = inspected.slice(0, 128) + "...";
      return `The ${name.includes(".") ? "property" : "argument"} '${name}' ${reason}. Received ${inspected}`;
    }, TypeError);
    E2("ERR_INVALID_RETURN_VALUE", (input, name, value) => {
      var _value$constructor;
      let type = value !== null && value !== undefined && (_value$constructor = value.constructor) !== null && _value$constructor !== undefined && _value$constructor.name ? `instance of ${value.constructor.name}` : `type ${typeof value}`;
      return `Expected ${input} to be returned from the "${name}" function but got ${type}.`;
    }, TypeError);
    E2("ERR_MISSING_ARGS", (...args) => {
      assert(args.length > 0, "At least one arg needs to be specified");
      let msg, len2 = args.length;
      switch (args = (Array.isArray(args) ? args : [args]).map((a2) => `"${a2}"`).join(" or "), len2) {
        case 1:
          msg += `The ${args[0]} argument`;
          break;
        case 2:
          msg += `The ${args[0]} and ${args[1]} arguments`;
          break;
        default:
          {
            let last = args.pop();
            msg += `The ${args.join(", ")}, and ${last} arguments`;
          }
          break;
      }
      return `${msg} must be specified`;
    }, TypeError);
    E2("ERR_OUT_OF_RANGE", (str, range, input) => {
      assert(range, 'Missing "range" argument');
      let received;
      if (Number.isInteger(input) && Math.abs(input) > 4294967296)
        received = addNumericalSeparator2(String(input));
      else if (typeof input === "bigint") {
        received = String(input);
        let limit = BigInt(2) ** BigInt(32);
        if (input > limit || input < -limit)
          received = addNumericalSeparator2(received);
        received += "n";
      } else
        received = inspect2(input);
      return `The value of "${str}" is out of range. It must be ${range}. Received ${received}`;
    }, RangeError);
    E2("ERR_MULTIPLE_CALLBACK", "Callback called multiple times", Error);
    E2("ERR_METHOD_NOT_IMPLEMENTED", "The %s method is not implemented", Error);
    E2("ERR_STREAM_ALREADY_FINISHED", "Cannot call %s after a stream was finished", Error);
    E2("ERR_STREAM_CANNOT_PIPE", "Cannot pipe, not readable", Error);
    E2("ERR_STREAM_DESTROYED", "Cannot call %s after a stream was destroyed", Error);
    E2("ERR_STREAM_NULL_VALUES", "May not write null values to stream", TypeError);
    E2("ERR_STREAM_PREMATURE_CLOSE", "Premature close", Error);
    E2("ERR_STREAM_PUSH_AFTER_EOF", "stream.push() after EOF", Error);
    E2("ERR_STREAM_UNSHIFT_AFTER_END_EVENT", "stream.unshift() after end event", Error);
    E2("ERR_STREAM_WRITE_AFTER_END", "write after end", Error);
    E2("ERR_UNKNOWN_ENCODING", "Unknown encoding: %s", TypeError);
    module2.exports = { AbortError: AbortError2, aggregateTwoErrors: hideStackFrames(aggregateTwoErrors), hideStackFrames, codes };
  });
  var require_event_target_shim = __commonJS2((exports2, module2) => {
    Object.defineProperty(exports2, "__esModule", { value: true });
    var privateData = new WeakMap, wrappers = new WeakMap;
    function pd(event) {
      let retv = privateData.get(event);
      return console.assert(retv != null, "'this' is expected an Event object, but got", event), retv;
    }
    function setCancelFlag(data) {
      if (data.passiveListener != null) {
        if (typeof console < "u" && typeof console.error === "function")
          console.error("Unable to preventDefault inside passive event listener invocation.", data.passiveListener);
        return;
      }
      if (!data.event.cancelable)
        return;
      if (data.canceled = true, typeof data.event.preventDefault === "function")
        data.event.preventDefault();
    }
    function Event(eventTarget, event) {
      privateData.set(this, { eventTarget, event, eventPhase: 2, currentTarget: eventTarget, canceled: false, stopped: false, immediateStopped: false, passiveListener: null, timeStamp: event.timeStamp || Date.now() }), Object.defineProperty(this, "isTrusted", { value: false, enumerable: true });
      let keys = Object.keys(event);
      for (let i2 = 0;i2 < keys.length; ++i2) {
        let key = keys[i2];
        if (!(key in this))
          Object.defineProperty(this, key, defineRedirectDescriptor(key));
      }
    }
    Event.prototype = { get type() {
      return pd(this).event.type;
    }, get target() {
      return pd(this).eventTarget;
    }, get currentTarget() {
      return pd(this).currentTarget;
    }, composedPath() {
      let currentTarget = pd(this).currentTarget;
      if (currentTarget == null)
        return [];
      return [currentTarget];
    }, get NONE() {
      return 0;
    }, get CAPTURING_PHASE() {
      return 1;
    }, get AT_TARGET() {
      return 2;
    }, get BUBBLING_PHASE() {
      return 3;
    }, get eventPhase() {
      return pd(this).eventPhase;
    }, stopPropagation() {
      let data = pd(this);
      if (data.stopped = true, typeof data.event.stopPropagation === "function")
        data.event.stopPropagation();
    }, stopImmediatePropagation() {
      let data = pd(this);
      if (data.stopped = true, data.immediateStopped = true, typeof data.event.stopImmediatePropagation === "function")
        data.event.stopImmediatePropagation();
    }, get bubbles() {
      return Boolean(pd(this).event.bubbles);
    }, get cancelable() {
      return Boolean(pd(this).event.cancelable);
    }, preventDefault() {
      setCancelFlag(pd(this));
    }, get defaultPrevented() {
      return pd(this).canceled;
    }, get composed() {
      return Boolean(pd(this).event.composed);
    }, get timeStamp() {
      return pd(this).timeStamp;
    }, get srcElement() {
      return pd(this).eventTarget;
    }, get cancelBubble() {
      return pd(this).stopped;
    }, set cancelBubble(value) {
      if (!value)
        return;
      let data = pd(this);
      if (data.stopped = true, typeof data.event.cancelBubble === "boolean")
        data.event.cancelBubble = true;
    }, get returnValue() {
      return !pd(this).canceled;
    }, set returnValue(value) {
      if (!value)
        setCancelFlag(pd(this));
    }, initEvent() {} };
    Object.defineProperty(Event.prototype, "constructor", { value: Event, configurable: true, writable: true });
    if (typeof window < "u" && typeof window.Event < "u")
      Object.setPrototypeOf(Event.prototype, window.Event.prototype), wrappers.set(window.Event.prototype, Event);
    function defineRedirectDescriptor(key) {
      return { get() {
        return pd(this).event[key];
      }, set(value) {
        pd(this).event[key] = value;
      }, configurable: true, enumerable: true };
    }
    function defineCallDescriptor(key) {
      return { value() {
        let event = pd(this).event;
        return event[key].apply(event, arguments);
      }, configurable: true, enumerable: true };
    }
    function defineWrapper(BaseEvent, proto) {
      let keys = Object.keys(proto);
      if (keys.length === 0)
        return BaseEvent;
      function CustomEvent(eventTarget, event) {
        BaseEvent.call(this, eventTarget, event);
      }
      CustomEvent.prototype = Object.create(BaseEvent.prototype, { constructor: { value: CustomEvent, configurable: true, writable: true } });
      for (let i2 = 0;i2 < keys.length; ++i2) {
        let key = keys[i2];
        if (!(key in BaseEvent.prototype)) {
          let isFunc = typeof Object.getOwnPropertyDescriptor(proto, key).value === "function";
          Object.defineProperty(CustomEvent.prototype, key, isFunc ? defineCallDescriptor(key) : defineRedirectDescriptor(key));
        }
      }
      return CustomEvent;
    }
    function getWrapper(proto) {
      if (proto == null || proto === Object.prototype)
        return Event;
      let wrapper = wrappers.get(proto);
      if (wrapper == null)
        wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto), wrappers.set(proto, wrapper);
      return wrapper;
    }
    function wrapEvent(eventTarget, event) {
      return new (getWrapper(Object.getPrototypeOf(event)))(eventTarget, event);
    }
    function isStopped(event) {
      return pd(event).immediateStopped;
    }
    function setEventPhase(event, eventPhase) {
      pd(event).eventPhase = eventPhase;
    }
    function setCurrentTarget(event, currentTarget) {
      pd(event).currentTarget = currentTarget;
    }
    function setPassiveListener(event, passiveListener) {
      pd(event).passiveListener = passiveListener;
    }
    var listenersMap = new WeakMap, CAPTURE = 1, BUBBLE = 2, ATTRIBUTE = 3;
    function isObject3(x) {
      return x !== null && typeof x === "object";
    }
    function getListeners(eventTarget) {
      let listeners = listenersMap.get(eventTarget);
      if (listeners == null)
        throw TypeError("'this' is expected an EventTarget object, but got another value.");
      return listeners;
    }
    function defineEventAttributeDescriptor(eventName) {
      return { get() {
        let node = getListeners(this).get(eventName);
        while (node != null) {
          if (node.listenerType === ATTRIBUTE)
            return node.listener;
          node = node.next;
        }
        return null;
      }, set(listener) {
        if (typeof listener !== "function" && !isObject3(listener))
          listener = null;
        let listeners = getListeners(this), prev = null, node = listeners.get(eventName);
        while (node != null) {
          if (node.listenerType === ATTRIBUTE)
            if (prev !== null)
              prev.next = node.next;
            else if (node.next !== null)
              listeners.set(eventName, node.next);
            else
              listeners.delete(eventName);
          else
            prev = node;
          node = node.next;
        }
        if (listener !== null) {
          let newNode = { listener, listenerType: ATTRIBUTE, passive: false, once: false, next: null };
          if (prev === null)
            listeners.set(eventName, newNode);
          else
            prev.next = newNode;
        }
      }, configurable: true, enumerable: true };
    }
    function defineEventAttribute(eventTargetPrototype, eventName) {
      Object.defineProperty(eventTargetPrototype, `on${eventName}`, defineEventAttributeDescriptor(eventName));
    }
    function defineCustomEventTarget(eventNames) {
      function CustomEventTarget() {
        EventTarget.call(this);
      }
      CustomEventTarget.prototype = Object.create(EventTarget.prototype, { constructor: { value: CustomEventTarget, configurable: true, writable: true } });
      for (let i2 = 0;i2 < eventNames.length; ++i2)
        defineEventAttribute(CustomEventTarget.prototype, eventNames[i2]);
      return CustomEventTarget;
    }
    function EventTarget() {
      if (this instanceof EventTarget) {
        listenersMap.set(this, new Map);
        return;
      }
      if (arguments.length === 1 && Array.isArray(arguments[0]))
        return defineCustomEventTarget(arguments[0]);
      if (arguments.length > 0) {
        let types3 = Array(arguments.length);
        for (let i2 = 0;i2 < arguments.length; ++i2)
          types3[i2] = arguments[i2];
        return defineCustomEventTarget(types3);
      }
      throw TypeError("Cannot call a class as a function");
    }
    EventTarget.prototype = { addEventListener(eventName, listener, options) {
      if (listener == null)
        return;
      if (typeof listener !== "function" && !isObject3(listener))
        throw TypeError("'listener' should be a function or an object.");
      let listeners = getListeners(this), optionsIsObj = isObject3(options), listenerType = (optionsIsObj ? Boolean(options.capture) : Boolean(options)) ? CAPTURE : BUBBLE, newNode = { listener, listenerType, passive: optionsIsObj && Boolean(options.passive), once: optionsIsObj && Boolean(options.once), next: null }, node = listeners.get(eventName);
      if (node === undefined) {
        listeners.set(eventName, newNode);
        return;
      }
      let prev = null;
      while (node != null) {
        if (node.listener === listener && node.listenerType === listenerType)
          return;
        prev = node, node = node.next;
      }
      prev.next = newNode;
    }, removeEventListener(eventName, listener, options) {
      if (listener == null)
        return;
      let listeners = getListeners(this), listenerType = (isObject3(options) ? Boolean(options.capture) : Boolean(options)) ? CAPTURE : BUBBLE, prev = null, node = listeners.get(eventName);
      while (node != null) {
        if (node.listener === listener && node.listenerType === listenerType) {
          if (prev !== null)
            prev.next = node.next;
          else if (node.next !== null)
            listeners.set(eventName, node.next);
          else
            listeners.delete(eventName);
          return;
        }
        prev = node, node = node.next;
      }
    }, dispatchEvent(event) {
      if (event == null || typeof event.type !== "string")
        throw TypeError('"event.type" should be a string.');
      let listeners = getListeners(this), eventName = event.type, node = listeners.get(eventName);
      if (node == null)
        return true;
      let wrappedEvent = wrapEvent(this, event), prev = null;
      while (node != null) {
        if (node.once)
          if (prev !== null)
            prev.next = node.next;
          else if (node.next !== null)
            listeners.set(eventName, node.next);
          else
            listeners.delete(eventName);
        else
          prev = node;
        if (setPassiveListener(wrappedEvent, node.passive ? node.listener : null), typeof node.listener === "function")
          try {
            node.listener.call(this, wrappedEvent);
          } catch (err) {
            if (typeof console < "u" && typeof console.error === "function")
              console.error(err);
          }
        else if (node.listenerType !== ATTRIBUTE && typeof node.listener.handleEvent === "function")
          node.listener.handleEvent(wrappedEvent);
        if (isStopped(wrappedEvent))
          break;
        node = node.next;
      }
      return setPassiveListener(wrappedEvent, null), setEventPhase(wrappedEvent, 0), setCurrentTarget(wrappedEvent, null), !wrappedEvent.defaultPrevented;
    } };
    Object.defineProperty(EventTarget.prototype, "constructor", { value: EventTarget, configurable: true, writable: true });
    if (typeof window < "u" && typeof window.EventTarget < "u")
      Object.setPrototypeOf(EventTarget.prototype, window.EventTarget.prototype);
    exports2.defineEventAttribute = defineEventAttribute;
    exports2.EventTarget = EventTarget;
    exports2.default = EventTarget;
    module2.exports = EventTarget;
    module2.exports.EventTarget = module2.exports.default = EventTarget;
    module2.exports.defineEventAttribute = defineEventAttribute;
  });
  var require_abort_controller = __commonJS2((exports2, module2) => {
    Object.defineProperty(exports2, "__esModule", { value: true });
    var eventTargetShim = require_event_target_shim();

    class AbortSignal extends eventTargetShim.EventTarget {
      constructor() {
        super();
        throw TypeError("AbortSignal cannot be constructed directly");
      }
      get aborted() {
        let aborted = abortedFlags.get(this);
        if (typeof aborted !== "boolean")
          throw TypeError(`Expected 'this' to be an 'AbortSignal' object, but got ${this === null ? "null" : typeof this}`);
        return aborted;
      }
    }
    eventTargetShim.defineEventAttribute(AbortSignal.prototype, "abort");
    function createAbortSignal() {
      let signal = Object.create(AbortSignal.prototype);
      return eventTargetShim.EventTarget.call(signal), abortedFlags.set(signal, false), signal;
    }
    function abortSignal(signal) {
      if (abortedFlags.get(signal) !== false)
        return;
      abortedFlags.set(signal, true), signal.dispatchEvent({ type: "abort" });
    }
    var abortedFlags = new WeakMap;
    Object.defineProperties(AbortSignal.prototype, { aborted: { enumerable: true } });
    if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol")
      Object.defineProperty(AbortSignal.prototype, Symbol.toStringTag, { configurable: true, value: "AbortSignal" });

    class AbortController2 {
      constructor() {
        signals.set(this, createAbortSignal());
      }
      get signal() {
        return getSignal(this);
      }
      abort() {
        abortSignal(getSignal(this));
      }
    }
    var signals = new WeakMap;
    function getSignal(controller) {
      let signal = signals.get(controller);
      if (signal == null)
        throw TypeError(`Expected 'this' to be an 'AbortController' object, but got ${controller === null ? "null" : typeof controller}`);
      return signal;
    }
    Object.defineProperties(AbortController2.prototype, { signal: { enumerable: true }, abort: { enumerable: true } });
    if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol")
      Object.defineProperty(AbortController2.prototype, Symbol.toStringTag, { configurable: true, value: "AbortController" });
    exports2.AbortController = AbortController2;
    exports2.AbortSignal = AbortSignal;
    exports2.default = AbortController2;
    module2.exports = AbortController2;
    module2.exports.AbortController = module2.exports.default = AbortController2;
    module2.exports.AbortSignal = AbortSignal;
  });
  var require_util = __commonJS2((exports2, module2) => {
    var bufferModule = (init_buffer(), __toCommonJS(exports_buffer)), { format: format2, inspect: inspect2 } = require_inspect(), { codes: { ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE3 } } = require_errors(), { kResistStopPropagation, AggregateError: AggregateError2, SymbolDispose } = require_primordials(), AbortSignal = globalThis.AbortSignal || require_abort_controller().AbortSignal, AbortController2 = globalThis.AbortController || require_abort_controller().AbortController, AsyncFunction = Object.getPrototypeOf(async function() {}).constructor, Blob2 = globalThis.Blob || bufferModule.Blob, isBlob = typeof Blob2 < "u" ? function(b) {
      return b instanceof Blob2;
    } : function(b) {
      return false;
    }, validateAbortSignal2 = (signal, name) => {
      if (signal !== undefined && (signal === null || typeof signal !== "object" || !("aborted" in signal)))
        throw new ERR_INVALID_ARG_TYPE3(name, "AbortSignal", signal);
    }, validateFunction = (value, name) => {
      if (typeof value !== "function")
        throw new ERR_INVALID_ARG_TYPE3(name, "Function", value);
    };
    module2.exports = { AggregateError: AggregateError2, kEmptyObject: Object.freeze({}), once(callback) {
      let called = false;
      return function(...args) {
        if (called)
          return;
        called = true, callback.apply(this, args);
      };
    }, createDeferredPromise: function() {
      let resolve, reject;
      return { promise: new Promise((res, rej) => {
        resolve = res, reject = rej;
      }), resolve, reject };
    }, promisify(fn) {
      return new Promise((resolve, reject) => {
        fn((err, ...args) => {
          if (err)
            return reject(err);
          return resolve(...args);
        });
      });
    }, debuglog() {
      return function() {};
    }, format: format2, inspect: inspect2, types: { isAsyncFunction(fn) {
      return fn instanceof AsyncFunction;
    }, isArrayBufferView(arr) {
      return ArrayBuffer.isView(arr);
    } }, isBlob, deprecate(fn, message) {
      return fn;
    }, addAbortListener: (init_events(), __toCommonJS(exports_events)).addAbortListener || function(signal, listener) {
      if (signal === undefined)
        throw new ERR_INVALID_ARG_TYPE3("signal", "AbortSignal", signal);
      validateAbortSignal2(signal, "signal"), validateFunction(listener, "listener");
      let removeEventListener;
      if (signal.aborted)
        queueMicrotask(() => listener());
      else
        signal.addEventListener("abort", listener, { __proto__: null, once: true, [kResistStopPropagation]: true }), removeEventListener = () => {
          signal.removeEventListener("abort", listener);
        };
      return { __proto__: null, [SymbolDispose]() {
        var _removeEventListener;
        (_removeEventListener = removeEventListener) === null || _removeEventListener === undefined || _removeEventListener();
      } };
    }, AbortSignalAny: AbortSignal.any || function(signals) {
      if (signals.length === 1)
        return signals[0];
      let ac = new AbortController2, abort = () => ac.abort();
      return signals.forEach((signal) => {
        validateAbortSignal2(signal, "signals"), signal.addEventListener("abort", abort, { once: true });
      }), ac.signal.addEventListener("abort", () => {
        signals.forEach((signal) => signal.removeEventListener("abort", abort));
      }, { once: true }), ac.signal;
    } };
    module2.exports.promisify.custom = Symbol.for("nodejs.util.promisify.custom");
  });
  var require_validators = __commonJS2((exports2, module2) => {
    var { ArrayIsArray, ArrayPrototypeIncludes, ArrayPrototypeJoin, ArrayPrototypeMap, NumberIsInteger, NumberIsNaN, NumberMAX_SAFE_INTEGER, NumberMIN_SAFE_INTEGER, NumberParseInt, ObjectPrototypeHasOwnProperty, RegExpPrototypeExec, String: String2, StringPrototypeToUpperCase, StringPrototypeTrim } = require_primordials(), { hideStackFrames, codes: { ERR_SOCKET_BAD_PORT, ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE3, ERR_INVALID_ARG_VALUE, ERR_OUT_OF_RANGE: ERR_OUT_OF_RANGE3, ERR_UNKNOWN_SIGNAL } } = require_errors(), { normalizeEncoding } = require_util(), { isAsyncFunction, isArrayBufferView } = require_util().types, signals = {};
    function isInt32(value) {
      return value === (value | 0);
    }
    function isUint32(value) {
      return value === value >>> 0;
    }
    var octalReg = /^[0-7]+$/, modeDesc = "must be a 32-bit unsigned integer or an octal string";
    function parseFileMode(value, name, def) {
      if (typeof value > "u")
        value = def;
      if (typeof value === "string") {
        if (RegExpPrototypeExec(octalReg, value) === null)
          throw new ERR_INVALID_ARG_VALUE(name, value, modeDesc);
        value = NumberParseInt(value, 8);
      }
      return validateUint32(value, name), value;
    }
    var validateInteger = hideStackFrames((value, name, min = NumberMIN_SAFE_INTEGER, max = NumberMAX_SAFE_INTEGER) => {
      if (typeof value !== "number")
        throw new ERR_INVALID_ARG_TYPE3(name, "number", value);
      if (!NumberIsInteger(value))
        throw new ERR_OUT_OF_RANGE3(name, "an integer", value);
      if (value < min || value > max)
        throw new ERR_OUT_OF_RANGE3(name, `>= ${min} && <= ${max}`, value);
    }), validateInt32 = hideStackFrames((value, name, min = -2147483648, max = 2147483647) => {
      if (typeof value !== "number")
        throw new ERR_INVALID_ARG_TYPE3(name, "number", value);
      if (!NumberIsInteger(value))
        throw new ERR_OUT_OF_RANGE3(name, "an integer", value);
      if (value < min || value > max)
        throw new ERR_OUT_OF_RANGE3(name, `>= ${min} && <= ${max}`, value);
    }), validateUint32 = hideStackFrames((value, name, positive = false) => {
      if (typeof value !== "number")
        throw new ERR_INVALID_ARG_TYPE3(name, "number", value);
      if (!NumberIsInteger(value))
        throw new ERR_OUT_OF_RANGE3(name, "an integer", value);
      let min = positive ? 1 : 0, max = 4294967295;
      if (value < min || value > max)
        throw new ERR_OUT_OF_RANGE3(name, `>= ${min} && <= ${max}`, value);
    });
    function validateString(value, name) {
      if (typeof value !== "string")
        throw new ERR_INVALID_ARG_TYPE3(name, "string", value);
    }
    function validateNumber3(value, name, min = undefined, max) {
      if (typeof value !== "number")
        throw new ERR_INVALID_ARG_TYPE3(name, "number", value);
      if (min != null && value < min || max != null && value > max || (min != null || max != null) && NumberIsNaN(value))
        throw new ERR_OUT_OF_RANGE3(name, `${min != null ? `>= ${min}` : ""}${min != null && max != null ? " && " : ""}${max != null ? `<= ${max}` : ""}`, value);
    }
    var validateOneOf = hideStackFrames((value, name, oneOf) => {
      if (!ArrayPrototypeIncludes(oneOf, value)) {
        let reason = "must be one of: " + ArrayPrototypeJoin(ArrayPrototypeMap(oneOf, (v) => typeof v === "string" ? `'${v}'` : String2(v)), ", ");
        throw new ERR_INVALID_ARG_VALUE(name, value, reason);
      }
    });
    function validateBoolean2(value, name) {
      if (typeof value !== "boolean")
        throw new ERR_INVALID_ARG_TYPE3(name, "boolean", value);
    }
    function getOwnPropertyValueOrDefault(options, key, defaultValue) {
      return options == null || !ObjectPrototypeHasOwnProperty(options, key) ? defaultValue : options[key];
    }
    var validateObject = hideStackFrames((value, name, options = null) => {
      let allowArray = getOwnPropertyValueOrDefault(options, "allowArray", false), allowFunction = getOwnPropertyValueOrDefault(options, "allowFunction", false);
      if (!getOwnPropertyValueOrDefault(options, "nullable", false) && value === null || !allowArray && ArrayIsArray(value) || typeof value !== "object" && (!allowFunction || typeof value !== "function"))
        throw new ERR_INVALID_ARG_TYPE3(name, "Object", value);
    }), validateDictionary = hideStackFrames((value, name) => {
      if (value != null && typeof value !== "object" && typeof value !== "function")
        throw new ERR_INVALID_ARG_TYPE3(name, "a dictionary", value);
    }), validateArray = hideStackFrames((value, name, minLength = 0) => {
      if (!ArrayIsArray(value))
        throw new ERR_INVALID_ARG_TYPE3(name, "Array", value);
      if (value.length < minLength) {
        let reason = `must be longer than ${minLength}`;
        throw new ERR_INVALID_ARG_VALUE(name, value, reason);
      }
    });
    function validateStringArray(value, name) {
      validateArray(value, name);
      for (let i2 = 0;i2 < value.length; i2++)
        validateString(value[i2], `${name}[${i2}]`);
    }
    function validateBooleanArray(value, name) {
      validateArray(value, name);
      for (let i2 = 0;i2 < value.length; i2++)
        validateBoolean2(value[i2], `${name}[${i2}]`);
    }
    function validateAbortSignalArray(value, name) {
      validateArray(value, name);
      for (let i2 = 0;i2 < value.length; i2++) {
        let signal = value[i2], indexedName = `${name}[${i2}]`;
        if (signal == null)
          throw new ERR_INVALID_ARG_TYPE3(indexedName, "AbortSignal", signal);
        validateAbortSignal2(signal, indexedName);
      }
    }
    function validateSignalName(signal, name = "signal") {
      if (validateString(signal, name), signals[signal] === undefined) {
        if (signals[StringPrototypeToUpperCase(signal)] !== undefined)
          throw new ERR_UNKNOWN_SIGNAL(signal + " (signals must use all capital letters)");
        throw new ERR_UNKNOWN_SIGNAL(signal);
      }
    }
    var validateBuffer = hideStackFrames((buffer, name = "buffer") => {
      if (!isArrayBufferView(buffer))
        throw new ERR_INVALID_ARG_TYPE3(name, ["Buffer", "TypedArray", "DataView"], buffer);
    });
    function validateEncoding(data, encoding) {
      let normalizedEncoding = normalizeEncoding(encoding), length = data.length;
      if (normalizedEncoding === "hex" && length % 2 !== 0)
        throw new ERR_INVALID_ARG_VALUE("encoding", encoding, `is invalid for data of length ${length}`);
    }
    function validatePort(port, name = "Port", allowZero = true) {
      if (typeof port !== "number" && typeof port !== "string" || typeof port === "string" && StringPrototypeTrim(port).length === 0 || +port !== +port >>> 0 || port > 65535 || port === 0 && !allowZero)
        throw new ERR_SOCKET_BAD_PORT(name, port, allowZero);
      return port | 0;
    }
    var validateAbortSignal2 = hideStackFrames((signal, name) => {
      if (signal !== undefined && (signal === null || typeof signal !== "object" || !("aborted" in signal)))
        throw new ERR_INVALID_ARG_TYPE3(name, "AbortSignal", signal);
    }), validateFunction = hideStackFrames((value, name) => {
      if (typeof value !== "function")
        throw new ERR_INVALID_ARG_TYPE3(name, "Function", value);
    }), validatePlainFunction = hideStackFrames((value, name) => {
      if (typeof value !== "function" || isAsyncFunction(value))
        throw new ERR_INVALID_ARG_TYPE3(name, "Function", value);
    }), validateUndefined = hideStackFrames((value, name) => {
      if (value !== undefined)
        throw new ERR_INVALID_ARG_TYPE3(name, "undefined", value);
    });
    function validateUnion(value, name, union) {
      if (!ArrayPrototypeIncludes(union, value))
        throw new ERR_INVALID_ARG_TYPE3(name, `('${ArrayPrototypeJoin(union, "|")}')`, value);
    }
    var linkValueRegExp = /^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;
    function validateLinkHeaderFormat(value, name) {
      if (typeof value > "u" || !RegExpPrototypeExec(linkValueRegExp, value))
        throw new ERR_INVALID_ARG_VALUE(name, value, 'must be an array or string of format "</styles.css>; rel=preload; as=style"');
    }
    function validateLinkHeaderValue(hints) {
      if (typeof hints === "string")
        return validateLinkHeaderFormat(hints, "hints"), hints;
      else if (ArrayIsArray(hints)) {
        let hintsLength = hints.length, result = "";
        if (hintsLength === 0)
          return result;
        for (let i2 = 0;i2 < hintsLength; i2++) {
          let link = hints[i2];
          if (validateLinkHeaderFormat(link, "hints"), result += link, i2 !== hintsLength - 1)
            result += ", ";
        }
        return result;
      }
      throw new ERR_INVALID_ARG_VALUE("hints", hints, 'must be an array or string of format "</styles.css>; rel=preload; as=style"');
    }
    module2.exports = { isInt32, isUint32, parseFileMode, validateArray, validateStringArray, validateBooleanArray, validateAbortSignalArray, validateBoolean: validateBoolean2, validateBuffer, validateDictionary, validateEncoding, validateFunction, validateInt32, validateInteger, validateNumber: validateNumber3, validateObject, validateOneOf, validatePlainFunction, validatePort, validateSignalName, validateString, validateUint32, validateUndefined, validateUnion, validateAbortSignal: validateAbortSignal2, validateLinkHeaderValue };
  });
  var require_process = __commonJS2((exports2, module2) => {
    module2.exports = globalThis.process;
  });
  var require_utils = __commonJS2((exports2, module2) => {
    var { SymbolAsyncIterator, SymbolIterator, SymbolFor: SymbolFor2 } = require_primordials(), kIsDestroyed = SymbolFor2("nodejs.stream.destroyed"), kIsErrored = SymbolFor2("nodejs.stream.errored"), kIsReadable = SymbolFor2("nodejs.stream.readable"), kIsWritable = SymbolFor2("nodejs.stream.writable"), kIsDisturbed = SymbolFor2("nodejs.stream.disturbed"), kIsClosedPromise = SymbolFor2("nodejs.webstream.isClosedPromise"), kControllerErrorFunction = SymbolFor2("nodejs.webstream.controllerErrorFunction");
    function isReadableNodeStream(obj, strict = false) {
      var _obj$_readableState;
      return !!(obj && typeof obj.pipe === "function" && typeof obj.on === "function" && (!strict || typeof obj.pause === "function" && typeof obj.resume === "function") && (!obj._writableState || ((_obj$_readableState = obj._readableState) === null || _obj$_readableState === undefined ? undefined : _obj$_readableState.readable) !== false) && (!obj._writableState || obj._readableState));
    }
    function isWritableNodeStream(obj) {
      var _obj$_writableState;
      return !!(obj && typeof obj.write === "function" && typeof obj.on === "function" && (!obj._readableState || ((_obj$_writableState = obj._writableState) === null || _obj$_writableState === undefined ? undefined : _obj$_writableState.writable) !== false));
    }
    function isDuplexNodeStream(obj) {
      return !!(obj && typeof obj.pipe === "function" && obj._readableState && typeof obj.on === "function" && typeof obj.write === "function");
    }
    function isNodeStream(obj) {
      return obj && (obj._readableState || obj._writableState || typeof obj.write === "function" && typeof obj.on === "function" || typeof obj.pipe === "function" && typeof obj.on === "function");
    }
    function isReadableStream(obj) {
      return !!(obj && !isNodeStream(obj) && typeof obj.pipeThrough === "function" && typeof obj.getReader === "function" && typeof obj.cancel === "function");
    }
    function isWritableStream(obj) {
      return !!(obj && !isNodeStream(obj) && typeof obj.getWriter === "function" && typeof obj.abort === "function");
    }
    function isTransformStream(obj) {
      return !!(obj && !isNodeStream(obj) && typeof obj.readable === "object" && typeof obj.writable === "object");
    }
    function isWebStream(obj) {
      return isReadableStream(obj) || isWritableStream(obj) || isTransformStream(obj);
    }
    function isIterable(obj, isAsync) {
      if (obj == null)
        return false;
      if (isAsync === true)
        return typeof obj[SymbolAsyncIterator] === "function";
      if (isAsync === false)
        return typeof obj[SymbolIterator] === "function";
      return typeof obj[SymbolAsyncIterator] === "function" || typeof obj[SymbolIterator] === "function";
    }
    function isDestroyed(stream) {
      if (!isNodeStream(stream))
        return null;
      let { _writableState: wState, _readableState: rState } = stream, state = wState || rState;
      return !!(stream.destroyed || stream[kIsDestroyed] || state !== null && state !== undefined && state.destroyed);
    }
    function isWritableEnded(stream) {
      if (!isWritableNodeStream(stream))
        return null;
      if (stream.writableEnded === true)
        return true;
      let wState = stream._writableState;
      if (wState !== null && wState !== undefined && wState.errored)
        return false;
      if (typeof (wState === null || wState === undefined ? undefined : wState.ended) !== "boolean")
        return null;
      return wState.ended;
    }
    function isWritableFinished(stream, strict) {
      if (!isWritableNodeStream(stream))
        return null;
      if (stream.writableFinished === true)
        return true;
      let wState = stream._writableState;
      if (wState !== null && wState !== undefined && wState.errored)
        return false;
      if (typeof (wState === null || wState === undefined ? undefined : wState.finished) !== "boolean")
        return null;
      return !!(wState.finished || strict === false && wState.ended === true && wState.length === 0);
    }
    function isReadableEnded(stream) {
      if (!isReadableNodeStream(stream))
        return null;
      if (stream.readableEnded === true)
        return true;
      let rState = stream._readableState;
      if (!rState || rState.errored)
        return false;
      if (typeof (rState === null || rState === undefined ? undefined : rState.ended) !== "boolean")
        return null;
      return rState.ended;
    }
    function isReadableFinished(stream, strict) {
      if (!isReadableNodeStream(stream))
        return null;
      let rState = stream._readableState;
      if (rState !== null && rState !== undefined && rState.errored)
        return false;
      if (typeof (rState === null || rState === undefined ? undefined : rState.endEmitted) !== "boolean")
        return null;
      return !!(rState.endEmitted || strict === false && rState.ended === true && rState.length === 0);
    }
    function isReadable(stream) {
      if (stream && stream[kIsReadable] != null)
        return stream[kIsReadable];
      if (typeof (stream === null || stream === undefined ? undefined : stream.readable) !== "boolean")
        return null;
      if (isDestroyed(stream))
        return false;
      return isReadableNodeStream(stream) && stream.readable && !isReadableFinished(stream);
    }
    function isWritable(stream) {
      if (stream && stream[kIsWritable] != null)
        return stream[kIsWritable];
      if (typeof (stream === null || stream === undefined ? undefined : stream.writable) !== "boolean")
        return null;
      if (isDestroyed(stream))
        return false;
      return isWritableNodeStream(stream) && stream.writable && !isWritableEnded(stream);
    }
    function isFinished(stream, opts) {
      if (!isNodeStream(stream))
        return null;
      if (isDestroyed(stream))
        return true;
      if ((opts === null || opts === undefined ? undefined : opts.readable) !== false && isReadable(stream))
        return false;
      if ((opts === null || opts === undefined ? undefined : opts.writable) !== false && isWritable(stream))
        return false;
      return true;
    }
    function isWritableErrored(stream) {
      var _stream$_writableStat, _stream$_writableStat2;
      if (!isNodeStream(stream))
        return null;
      if (stream.writableErrored)
        return stream.writableErrored;
      return (_stream$_writableStat = (_stream$_writableStat2 = stream._writableState) === null || _stream$_writableStat2 === undefined ? undefined : _stream$_writableStat2.errored) !== null && _stream$_writableStat !== undefined ? _stream$_writableStat : null;
    }
    function isReadableErrored(stream) {
      var _stream$_readableStat, _stream$_readableStat2;
      if (!isNodeStream(stream))
        return null;
      if (stream.readableErrored)
        return stream.readableErrored;
      return (_stream$_readableStat = (_stream$_readableStat2 = stream._readableState) === null || _stream$_readableStat2 === undefined ? undefined : _stream$_readableStat2.errored) !== null && _stream$_readableStat !== undefined ? _stream$_readableStat : null;
    }
    function isClosed(stream) {
      if (!isNodeStream(stream))
        return null;
      if (typeof stream.closed === "boolean")
        return stream.closed;
      let { _writableState: wState, _readableState: rState } = stream;
      if (typeof (wState === null || wState === undefined ? undefined : wState.closed) === "boolean" || typeof (rState === null || rState === undefined ? undefined : rState.closed) === "boolean")
        return (wState === null || wState === undefined ? undefined : wState.closed) || (rState === null || rState === undefined ? undefined : rState.closed);
      if (typeof stream._closed === "boolean" && isOutgoingMessage(stream))
        return stream._closed;
      return null;
    }
    function isOutgoingMessage(stream) {
      return typeof stream._closed === "boolean" && typeof stream._defaultKeepAlive === "boolean" && typeof stream._removedConnection === "boolean" && typeof stream._removedContLen === "boolean";
    }
    function isServerResponse(stream) {
      return typeof stream._sent100 === "boolean" && isOutgoingMessage(stream);
    }
    function isServerRequest(stream) {
      var _stream$req;
      return typeof stream._consuming === "boolean" && typeof stream._dumped === "boolean" && ((_stream$req = stream.req) === null || _stream$req === undefined ? undefined : _stream$req.upgradeOrConnect) === undefined;
    }
    function willEmitClose(stream) {
      if (!isNodeStream(stream))
        return null;
      let { _writableState: wState, _readableState: rState } = stream, state = wState || rState;
      return !state && isServerResponse(stream) || !!(state && state.autoDestroy && state.emitClose && state.closed === false);
    }
    function isDisturbed(stream) {
      var _stream$kIsDisturbed;
      return !!(stream && ((_stream$kIsDisturbed = stream[kIsDisturbed]) !== null && _stream$kIsDisturbed !== undefined ? _stream$kIsDisturbed : stream.readableDidRead || stream.readableAborted));
    }
    function isErrored(stream) {
      var _ref, _ref2, _ref3, _ref4, _ref5, _stream$kIsErrored, _stream$_readableStat3, _stream$_writableStat3, _stream$_readableStat4, _stream$_writableStat4;
      return !!(stream && ((_ref = (_ref2 = (_ref3 = (_ref4 = (_ref5 = (_stream$kIsErrored = stream[kIsErrored]) !== null && _stream$kIsErrored !== undefined ? _stream$kIsErrored : stream.readableErrored) !== null && _ref5 !== undefined ? _ref5 : stream.writableErrored) !== null && _ref4 !== undefined ? _ref4 : (_stream$_readableStat3 = stream._readableState) === null || _stream$_readableStat3 === undefined ? undefined : _stream$_readableStat3.errorEmitted) !== null && _ref3 !== undefined ? _ref3 : (_stream$_writableStat3 = stream._writableState) === null || _stream$_writableStat3 === undefined ? undefined : _stream$_writableStat3.errorEmitted) !== null && _ref2 !== undefined ? _ref2 : (_stream$_readableStat4 = stream._readableState) === null || _stream$_readableStat4 === undefined ? undefined : _stream$_readableStat4.errored) !== null && _ref !== undefined ? _ref : (_stream$_writableStat4 = stream._writableState) === null || _stream$_writableStat4 === undefined ? undefined : _stream$_writableStat4.errored));
    }
    module2.exports = { isDestroyed, kIsDestroyed, isDisturbed, kIsDisturbed, isErrored, kIsErrored, isReadable, kIsReadable, kIsClosedPromise, kControllerErrorFunction, kIsWritable, isClosed, isDuplexNodeStream, isFinished, isIterable, isReadableNodeStream, isReadableStream, isReadableEnded, isReadableFinished, isReadableErrored, isNodeStream, isWebStream, isWritable, isWritableNodeStream, isWritableStream, isWritableEnded, isWritableFinished, isWritableErrored, isServerRequest, isServerResponse, willEmitClose, isTransformStream };
  });
  var require_end_of_stream = __commonJS2((exports2, module2) => {
    var process2 = require_process(), { AbortError: AbortError2, codes } = require_errors(), { ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE3, ERR_STREAM_PREMATURE_CLOSE } = codes, { kEmptyObject, once } = require_util(), { validateAbortSignal: validateAbortSignal2, validateFunction, validateObject, validateBoolean: validateBoolean2 } = require_validators(), { Promise: Promise2, PromisePrototypeThen, SymbolDispose } = require_primordials(), { isClosed, isReadable, isReadableNodeStream, isReadableStream, isReadableFinished, isReadableErrored, isWritable, isWritableNodeStream, isWritableStream, isWritableFinished, isWritableErrored, isNodeStream, willEmitClose: _willEmitClose, kIsClosedPromise } = require_utils(), addAbortListener2;
    function isRequest(stream) {
      return stream.setHeader && typeof stream.abort === "function";
    }
    var nop = () => {};
    function eos(stream, options, callback) {
      var _options$readable, _options$writable;
      if (arguments.length === 2)
        callback = options, options = kEmptyObject;
      else if (options == null)
        options = kEmptyObject;
      else
        validateObject(options, "options");
      if (validateFunction(callback, "callback"), validateAbortSignal2(options.signal, "options.signal"), callback = once(callback), isReadableStream(stream) || isWritableStream(stream))
        return eosWeb(stream, options, callback);
      if (!isNodeStream(stream))
        throw new ERR_INVALID_ARG_TYPE3("stream", ["ReadableStream", "WritableStream", "Stream"], stream);
      let readable = (_options$readable = options.readable) !== null && _options$readable !== undefined ? _options$readable : isReadableNodeStream(stream), writable = (_options$writable = options.writable) !== null && _options$writable !== undefined ? _options$writable : isWritableNodeStream(stream), wState = stream._writableState, rState = stream._readableState, onlegacyfinish = () => {
        if (!stream.writable)
          onfinish();
      }, willEmitClose = _willEmitClose(stream) && isReadableNodeStream(stream) === readable && isWritableNodeStream(stream) === writable, writableFinished = isWritableFinished(stream, false), onfinish = () => {
        if (writableFinished = true, stream.destroyed)
          willEmitClose = false;
        if (willEmitClose && (!stream.readable || readable))
          return;
        if (!readable || readableFinished)
          callback.call(stream);
      }, readableFinished = isReadableFinished(stream, false), onend = () => {
        if (readableFinished = true, stream.destroyed)
          willEmitClose = false;
        if (willEmitClose && (!stream.writable || writable))
          return;
        if (!writable || writableFinished)
          callback.call(stream);
      }, onerror = (err) => {
        callback.call(stream, err);
      }, closed = isClosed(stream), onclose = () => {
        closed = true;
        let errored = isWritableErrored(stream) || isReadableErrored(stream);
        if (errored && typeof errored !== "boolean")
          return callback.call(stream, errored);
        if (readable && !readableFinished && isReadableNodeStream(stream, true)) {
          if (!isReadableFinished(stream, false))
            return callback.call(stream, new ERR_STREAM_PREMATURE_CLOSE);
        }
        if (writable && !writableFinished) {
          if (!isWritableFinished(stream, false))
            return callback.call(stream, new ERR_STREAM_PREMATURE_CLOSE);
        }
        callback.call(stream);
      }, onclosed = () => {
        closed = true;
        let errored = isWritableErrored(stream) || isReadableErrored(stream);
        if (errored && typeof errored !== "boolean")
          return callback.call(stream, errored);
        callback.call(stream);
      }, onrequest = () => {
        stream.req.on("finish", onfinish);
      };
      if (isRequest(stream)) {
        if (stream.on("complete", onfinish), !willEmitClose)
          stream.on("abort", onclose);
        if (stream.req)
          onrequest();
        else
          stream.on("request", onrequest);
      } else if (writable && !wState)
        stream.on("end", onlegacyfinish), stream.on("close", onlegacyfinish);
      if (!willEmitClose && typeof stream.aborted === "boolean")
        stream.on("aborted", onclose);
      if (stream.on("end", onend), stream.on("finish", onfinish), options.error !== false)
        stream.on("error", onerror);
      if (stream.on("close", onclose), closed)
        process2.nextTick(onclose);
      else if (wState !== null && wState !== undefined && wState.errorEmitted || rState !== null && rState !== undefined && rState.errorEmitted) {
        if (!willEmitClose)
          process2.nextTick(onclosed);
      } else if (!readable && (!willEmitClose || isReadable(stream)) && (writableFinished || isWritable(stream) === false))
        process2.nextTick(onclosed);
      else if (!writable && (!willEmitClose || isWritable(stream)) && (readableFinished || isReadable(stream) === false))
        process2.nextTick(onclosed);
      else if (rState && stream.req && stream.aborted)
        process2.nextTick(onclosed);
      let cleanup = () => {
        if (callback = nop, stream.removeListener("aborted", onclose), stream.removeListener("complete", onfinish), stream.removeListener("abort", onclose), stream.removeListener("request", onrequest), stream.req)
          stream.req.removeListener("finish", onfinish);
        stream.removeListener("end", onlegacyfinish), stream.removeListener("close", onlegacyfinish), stream.removeListener("finish", onfinish), stream.removeListener("end", onend), stream.removeListener("error", onerror), stream.removeListener("close", onclose);
      };
      if (options.signal && !closed) {
        let abort = () => {
          let endCallback = callback;
          cleanup(), endCallback.call(stream, new AbortError2(undefined, { cause: options.signal.reason }));
        };
        if (options.signal.aborted)
          process2.nextTick(abort);
        else {
          addAbortListener2 = addAbortListener2 || require_util().addAbortListener;
          let disposable = addAbortListener2(options.signal, abort), originalCallback = callback;
          callback = once((...args) => {
            disposable[SymbolDispose](), originalCallback.apply(stream, args);
          });
        }
      }
      return cleanup;
    }
    function eosWeb(stream, options, callback) {
      let isAborted = false, abort = nop;
      if (options.signal)
        if (abort = () => {
          isAborted = true, callback.call(stream, new AbortError2(undefined, { cause: options.signal.reason }));
        }, options.signal.aborted)
          process2.nextTick(abort);
        else {
          addAbortListener2 = addAbortListener2 || require_util().addAbortListener;
          let disposable = addAbortListener2(options.signal, abort), originalCallback = callback;
          callback = once((...args) => {
            disposable[SymbolDispose](), originalCallback.apply(stream, args);
          });
        }
      let resolverFn = (...args) => {
        if (!isAborted)
          process2.nextTick(() => callback.apply(stream, args));
      };
      return PromisePrototypeThen(stream[kIsClosedPromise].promise, resolverFn, resolverFn), nop;
    }
    function finished(stream, opts) {
      var _opts;
      let autoCleanup = false;
      if (opts === null)
        opts = kEmptyObject;
      if ((_opts = opts) !== null && _opts !== undefined && _opts.cleanup)
        validateBoolean2(opts.cleanup, "cleanup"), autoCleanup = opts.cleanup;
      return new Promise2((resolve, reject) => {
        let cleanup = eos(stream, opts, (err) => {
          if (autoCleanup)
            cleanup();
          if (err)
            reject(err);
          else
            resolve();
        });
      });
    }
    module2.exports = eos;
    module2.exports.finished = finished;
  });
  var require_destroy = __commonJS2((exports2, module2) => {
    var process2 = require_process(), { aggregateTwoErrors, codes: { ERR_MULTIPLE_CALLBACK }, AbortError: AbortError2 } = require_errors(), { Symbol: Symbol2 } = require_primordials(), { kIsDestroyed, isDestroyed, isFinished, isServerRequest } = require_utils(), kDestroy = Symbol2("kDestroy"), kConstruct = Symbol2("kConstruct");
    function checkError(err, w, r2) {
      if (err) {
        if (err.stack, w && !w.errored)
          w.errored = err;
        if (r2 && !r2.errored)
          r2.errored = err;
      }
    }
    function destroy(err, cb) {
      let r2 = this._readableState, w = this._writableState, s = w || r2;
      if (w !== null && w !== undefined && w.destroyed || r2 !== null && r2 !== undefined && r2.destroyed) {
        if (typeof cb === "function")
          cb();
        return this;
      }
      if (checkError(err, w, r2), w)
        w.destroyed = true;
      if (r2)
        r2.destroyed = true;
      if (!s.constructed)
        this.once(kDestroy, function(er) {
          _destroy(this, aggregateTwoErrors(er, err), cb);
        });
      else
        _destroy(this, err, cb);
      return this;
    }
    function _destroy(self2, err, cb) {
      let called = false;
      function onDestroy(err2) {
        if (called)
          return;
        called = true;
        let { _readableState: r2, _writableState: w } = self2;
        if (checkError(err2, w, r2), w)
          w.closed = true;
        if (r2)
          r2.closed = true;
        if (typeof cb === "function")
          cb(err2);
        if (err2)
          process2.nextTick(emitErrorCloseNT, self2, err2);
        else
          process2.nextTick(emitCloseNT, self2);
      }
      try {
        self2._destroy(err || null, onDestroy);
      } catch (err2) {
        onDestroy(err2);
      }
    }
    function emitErrorCloseNT(self2, err) {
      emitErrorNT(self2, err), emitCloseNT(self2);
    }
    function emitCloseNT(self2) {
      let { _readableState: r2, _writableState: w } = self2;
      if (w)
        w.closeEmitted = true;
      if (r2)
        r2.closeEmitted = true;
      if (w !== null && w !== undefined && w.emitClose || r2 !== null && r2 !== undefined && r2.emitClose)
        self2.emit("close");
    }
    function emitErrorNT(self2, err) {
      let { _readableState: r2, _writableState: w } = self2;
      if (w !== null && w !== undefined && w.errorEmitted || r2 !== null && r2 !== undefined && r2.errorEmitted)
        return;
      if (w)
        w.errorEmitted = true;
      if (r2)
        r2.errorEmitted = true;
      self2.emit("error", err);
    }
    function undestroy() {
      let r2 = this._readableState, w = this._writableState;
      if (r2)
        r2.constructed = true, r2.closed = false, r2.closeEmitted = false, r2.destroyed = false, r2.errored = null, r2.errorEmitted = false, r2.reading = false, r2.ended = r2.readable === false, r2.endEmitted = r2.readable === false;
      if (w)
        w.constructed = true, w.destroyed = false, w.closed = false, w.closeEmitted = false, w.errored = null, w.errorEmitted = false, w.finalCalled = false, w.prefinished = false, w.ended = w.writable === false, w.ending = w.writable === false, w.finished = w.writable === false;
    }
    function errorOrDestroy(stream, err, sync) {
      let { _readableState: r2, _writableState: w } = stream;
      if (w !== null && w !== undefined && w.destroyed || r2 !== null && r2 !== undefined && r2.destroyed)
        return this;
      if (r2 !== null && r2 !== undefined && r2.autoDestroy || w !== null && w !== undefined && w.autoDestroy)
        stream.destroy(err);
      else if (err) {
        if (err.stack, w && !w.errored)
          w.errored = err;
        if (r2 && !r2.errored)
          r2.errored = err;
        if (sync)
          process2.nextTick(emitErrorNT, stream, err);
        else
          emitErrorNT(stream, err);
      }
    }
    function construct(stream, cb) {
      if (typeof stream._construct !== "function")
        return;
      let { _readableState: r2, _writableState: w } = stream;
      if (r2)
        r2.constructed = false;
      if (w)
        w.constructed = false;
      if (stream.once(kConstruct, cb), stream.listenerCount(kConstruct) > 1)
        return;
      process2.nextTick(constructNT, stream);
    }
    function constructNT(stream) {
      let called = false;
      function onConstruct(err) {
        if (called) {
          errorOrDestroy(stream, err !== null && err !== undefined ? err : new ERR_MULTIPLE_CALLBACK);
          return;
        }
        called = true;
        let { _readableState: r2, _writableState: w } = stream, s = w || r2;
        if (r2)
          r2.constructed = true;
        if (w)
          w.constructed = true;
        if (s.destroyed)
          stream.emit(kDestroy, err);
        else if (err)
          errorOrDestroy(stream, err, true);
        else
          process2.nextTick(emitConstructNT, stream);
      }
      try {
        stream._construct((err) => {
          process2.nextTick(onConstruct, err);
        });
      } catch (err) {
        process2.nextTick(onConstruct, err);
      }
    }
    function emitConstructNT(stream) {
      stream.emit(kConstruct);
    }
    function isRequest(stream) {
      return (stream === null || stream === undefined ? undefined : stream.setHeader) && typeof stream.abort === "function";
    }
    function emitCloseLegacy(stream) {
      stream.emit("close");
    }
    function emitErrorCloseLegacy(stream, err) {
      stream.emit("error", err), process2.nextTick(emitCloseLegacy, stream);
    }
    function destroyer(stream, err) {
      if (!stream || isDestroyed(stream))
        return;
      if (!err && !isFinished(stream))
        err = new AbortError2;
      if (isServerRequest(stream))
        stream.socket = null, stream.destroy(err);
      else if (isRequest(stream))
        stream.abort();
      else if (isRequest(stream.req))
        stream.req.abort();
      else if (typeof stream.destroy === "function")
        stream.destroy(err);
      else if (typeof stream.close === "function")
        stream.close();
      else if (err)
        process2.nextTick(emitErrorCloseLegacy, stream, err);
      else
        process2.nextTick(emitCloseLegacy, stream);
      if (!stream.destroyed)
        stream[kIsDestroyed] = true;
    }
    module2.exports = { construct, destroyer, destroy, undestroy, errorOrDestroy };
  });
  var require_legacy = __commonJS2((exports2, module2) => {
    var { ArrayIsArray, ObjectSetPrototypeOf } = require_primordials(), { EventEmitter: EE } = (init_events(), __toCommonJS(exports_events));
    function Stream(opts) {
      EE.call(this, opts);
    }
    ObjectSetPrototypeOf(Stream.prototype, EE.prototype);
    ObjectSetPrototypeOf(Stream, EE);
    Stream.prototype.pipe = function(dest, options) {
      let source = this;
      function ondata(chunk) {
        if (dest.writable && dest.write(chunk) === false && source.pause)
          source.pause();
      }
      source.on("data", ondata);
      function ondrain() {
        if (source.readable && source.resume)
          source.resume();
      }
      if (dest.on("drain", ondrain), !dest._isStdio && (!options || options.end !== false))
        source.on("end", onend), source.on("close", onclose);
      let didOnEnd = false;
      function onend() {
        if (didOnEnd)
          return;
        didOnEnd = true, dest.end();
      }
      function onclose() {
        if (didOnEnd)
          return;
        if (didOnEnd = true, typeof dest.destroy === "function")
          dest.destroy();
      }
      function onerror(er) {
        if (cleanup(), EE.listenerCount(this, "error") === 0)
          this.emit("error", er);
      }
      prependListener(source, "error", onerror), prependListener(dest, "error", onerror);
      function cleanup() {
        source.removeListener("data", ondata), dest.removeListener("drain", ondrain), source.removeListener("end", onend), source.removeListener("close", onclose), source.removeListener("error", onerror), dest.removeListener("error", onerror), source.removeListener("end", cleanup), source.removeListener("close", cleanup), dest.removeListener("close", cleanup);
      }
      return source.on("end", cleanup), source.on("close", cleanup), dest.on("close", cleanup), dest.emit("pipe", source), dest;
    };
    function prependListener(emitter, event, fn) {
      if (typeof emitter.prependListener === "function")
        return emitter.prependListener(event, fn);
      if (!emitter._events || !emitter._events[event])
        emitter.on(event, fn);
      else if (ArrayIsArray(emitter._events[event]))
        emitter._events[event].unshift(fn);
      else
        emitter._events[event] = [fn, emitter._events[event]];
    }
    module2.exports = { Stream, prependListener };
  });
  var require_add_abort_signal = __commonJS2((exports2, module2) => {
    var { SymbolDispose } = require_primordials(), { AbortError: AbortError2, codes } = require_errors(), { isNodeStream, isWebStream, kControllerErrorFunction } = require_utils(), eos = require_end_of_stream(), { ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE3 } = codes, addAbortListener2, validateAbortSignal2 = (signal, name) => {
      if (typeof signal !== "object" || !("aborted" in signal))
        throw new ERR_INVALID_ARG_TYPE3(name, "AbortSignal", signal);
    };
    module2.exports.addAbortSignal = function(signal, stream) {
      if (validateAbortSignal2(signal, "signal"), !isNodeStream(stream) && !isWebStream(stream))
        throw new ERR_INVALID_ARG_TYPE3("stream", ["ReadableStream", "WritableStream", "Stream"], stream);
      return module2.exports.addAbortSignalNoValidate(signal, stream);
    };
    module2.exports.addAbortSignalNoValidate = function(signal, stream) {
      if (typeof signal !== "object" || !("aborted" in signal))
        return stream;
      let onAbort = isNodeStream(stream) ? () => {
        stream.destroy(new AbortError2(undefined, { cause: signal.reason }));
      } : () => {
        stream[kControllerErrorFunction](new AbortError2(undefined, { cause: signal.reason }));
      };
      if (signal.aborted)
        onAbort();
      else {
        addAbortListener2 = addAbortListener2 || require_util().addAbortListener;
        let disposable = addAbortListener2(signal, onAbort);
        eos(stream, disposable[SymbolDispose]);
      }
      return stream;
    };
  });
  var require_buffer_list = __commonJS2((exports2, module2) => {
    var { StringPrototypeSlice, SymbolIterator, TypedArrayPrototypeSet, Uint8Array: Uint8Array2 } = require_primordials(), { Buffer: Buffer3 } = (init_buffer(), __toCommonJS(exports_buffer)), { inspect: inspect2 } = require_util();
    module2.exports = class {
      constructor() {
        this.head = null, this.tail = null, this.length = 0;
      }
      push(v) {
        let entry = { data: v, next: null };
        if (this.length > 0)
          this.tail.next = entry;
        else
          this.head = entry;
        this.tail = entry, ++this.length;
      }
      unshift(v) {
        let entry = { data: v, next: this.head };
        if (this.length === 0)
          this.tail = entry;
        this.head = entry, ++this.length;
      }
      shift() {
        if (this.length === 0)
          return;
        let ret = this.head.data;
        if (this.length === 1)
          this.head = this.tail = null;
        else
          this.head = this.head.next;
        return --this.length, ret;
      }
      clear() {
        this.head = this.tail = null, this.length = 0;
      }
      join(s) {
        if (this.length === 0)
          return "";
        let p2 = this.head, ret = "" + p2.data;
        while ((p2 = p2.next) !== null)
          ret += s + p2.data;
        return ret;
      }
      concat(n2) {
        if (this.length === 0)
          return Buffer3.alloc(0);
        let ret = Buffer3.allocUnsafe(n2 >>> 0), p2 = this.head, i2 = 0;
        while (p2)
          TypedArrayPrototypeSet(ret, p2.data, i2), i2 += p2.data.length, p2 = p2.next;
        return ret;
      }
      consume(n2, hasStrings) {
        let data = this.head.data;
        if (n2 < data.length) {
          let slice = data.slice(0, n2);
          return this.head.data = data.slice(n2), slice;
        }
        if (n2 === data.length)
          return this.shift();
        return hasStrings ? this._getString(n2) : this._getBuffer(n2);
      }
      first() {
        return this.head.data;
      }
      *[SymbolIterator]() {
        for (let p2 = this.head;p2; p2 = p2.next)
          yield p2.data;
      }
      _getString(n2) {
        let ret = "", p2 = this.head, c2 = 0;
        do {
          let str = p2.data;
          if (n2 > str.length)
            ret += str, n2 -= str.length;
          else {
            if (n2 === str.length)
              if (ret += str, ++c2, p2.next)
                this.head = p2.next;
              else
                this.head = this.tail = null;
            else
              ret += StringPrototypeSlice(str, 0, n2), this.head = p2, p2.data = StringPrototypeSlice(str, n2);
            break;
          }
          ++c2;
        } while ((p2 = p2.next) !== null);
        return this.length -= c2, ret;
      }
      _getBuffer(n2) {
        let ret = Buffer3.allocUnsafe(n2), retLen = n2, p2 = this.head, c2 = 0;
        do {
          let buf = p2.data;
          if (n2 > buf.length)
            TypedArrayPrototypeSet(ret, buf, retLen - n2), n2 -= buf.length;
          else {
            if (n2 === buf.length)
              if (TypedArrayPrototypeSet(ret, buf, retLen - n2), ++c2, p2.next)
                this.head = p2.next;
              else
                this.head = this.tail = null;
            else
              TypedArrayPrototypeSet(ret, new Uint8Array2(buf.buffer, buf.byteOffset, n2), retLen - n2), this.head = p2, p2.data = buf.slice(n2);
            break;
          }
          ++c2;
        } while ((p2 = p2.next) !== null);
        return this.length -= c2, ret;
      }
      [Symbol.for("nodejs.util.inspect.custom")](_, options) {
        return inspect2(this, { ...options, depth: 0, customInspect: false });
      }
    };
  });
  var require_state = __commonJS2((exports2, module2) => {
    var { MathFloor, NumberIsInteger } = require_primordials(), { validateInteger } = require_validators(), { ERR_INVALID_ARG_VALUE } = require_errors().codes, defaultHighWaterMarkBytes = 16384, defaultHighWaterMarkObjectMode = 16;
    function highWaterMarkFrom(options, isDuplex, duplexKey) {
      return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
    }
    function getDefaultHighWaterMark(objectMode) {
      return objectMode ? defaultHighWaterMarkObjectMode : defaultHighWaterMarkBytes;
    }
    function setDefaultHighWaterMark(objectMode, value) {
      if (validateInteger(value, "value", 0), objectMode)
        defaultHighWaterMarkObjectMode = value;
      else
        defaultHighWaterMarkBytes = value;
    }
    function getHighWaterMark(state, options, duplexKey, isDuplex) {
      let hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
      if (hwm != null) {
        if (!NumberIsInteger(hwm) || hwm < 0) {
          let name = isDuplex ? `options.${duplexKey}` : "options.highWaterMark";
          throw new ERR_INVALID_ARG_VALUE(name, hwm);
        }
        return MathFloor(hwm);
      }
      return getDefaultHighWaterMark(state.objectMode);
    }
    module2.exports = { getHighWaterMark, getDefaultHighWaterMark, setDefaultHighWaterMark };
  });
  var require_safe_buffer = __commonJS2((exports2, module2) => {
    /*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
    var buffer = (init_buffer(), __toCommonJS(exports_buffer)), Buffer3 = buffer.Buffer;
    function copyProps(src, dst) {
      for (var key in src)
        dst[key] = src[key];
    }
    if (Buffer3.from && Buffer3.alloc && Buffer3.allocUnsafe && Buffer3.allocUnsafeSlow)
      module2.exports = buffer;
    else
      copyProps(buffer, exports2), exports2.Buffer = SafeBuffer;
    function SafeBuffer(arg, encodingOrOffset, length) {
      return Buffer3(arg, encodingOrOffset, length);
    }
    SafeBuffer.prototype = Object.create(Buffer3.prototype);
    copyProps(Buffer3, SafeBuffer);
    SafeBuffer.from = function(arg, encodingOrOffset, length) {
      if (typeof arg === "number")
        throw TypeError("Argument must not be a number");
      return Buffer3(arg, encodingOrOffset, length);
    };
    SafeBuffer.alloc = function(size, fill, encoding) {
      if (typeof size !== "number")
        throw TypeError("Argument must be a number");
      var buf = Buffer3(size);
      if (fill !== undefined)
        if (typeof encoding === "string")
          buf.fill(fill, encoding);
        else
          buf.fill(fill);
      else
        buf.fill(0);
      return buf;
    };
    SafeBuffer.allocUnsafe = function(size) {
      if (typeof size !== "number")
        throw TypeError("Argument must be a number");
      return Buffer3(size);
    };
    SafeBuffer.allocUnsafeSlow = function(size) {
      if (typeof size !== "number")
        throw TypeError("Argument must be a number");
      return buffer.SlowBuffer(size);
    };
  });
  var require_string_decoder = __commonJS2((exports2) => {
    var Buffer3 = require_safe_buffer().Buffer, isEncoding = Buffer3.isEncoding || function(encoding) {
      switch (encoding = "" + encoding, encoding && encoding.toLowerCase()) {
        case "hex":
        case "utf8":
        case "utf-8":
        case "ascii":
        case "binary":
        case "base64":
        case "ucs2":
        case "ucs-2":
        case "utf16le":
        case "utf-16le":
        case "raw":
          return true;
        default:
          return false;
      }
    };
    function _normalizeEncoding(enc) {
      if (!enc)
        return "utf8";
      var retried;
      while (true)
        switch (enc) {
          case "utf8":
          case "utf-8":
            return "utf8";
          case "ucs2":
          case "ucs-2":
          case "utf16le":
          case "utf-16le":
            return "utf16le";
          case "latin1":
          case "binary":
            return "latin1";
          case "base64":
          case "ascii":
          case "hex":
            return enc;
          default:
            if (retried)
              return;
            enc = ("" + enc).toLowerCase(), retried = true;
        }
    }
    function normalizeEncoding(enc) {
      var nenc = _normalizeEncoding(enc);
      if (typeof nenc !== "string" && (Buffer3.isEncoding === isEncoding || !isEncoding(enc)))
        throw Error("Unknown encoding: " + enc);
      return nenc || enc;
    }
    exports2.StringDecoder = StringDecoder;
    function StringDecoder(encoding) {
      this.encoding = normalizeEncoding(encoding);
      var nb;
      switch (this.encoding) {
        case "utf16le":
          this.text = utf16Text, this.end = utf16End, nb = 4;
          break;
        case "utf8":
          this.fillLast = utf8FillLast, nb = 4;
          break;
        case "base64":
          this.text = base64Text, this.end = base64End, nb = 3;
          break;
        default:
          this.write = simpleWrite, this.end = simpleEnd;
          return;
      }
      this.lastNeed = 0, this.lastTotal = 0, this.lastChar = Buffer3.allocUnsafe(nb);
    }
    StringDecoder.prototype.write = function(buf) {
      if (buf.length === 0)
        return "";
      var r2, i2;
      if (this.lastNeed) {
        if (r2 = this.fillLast(buf), r2 === undefined)
          return "";
        i2 = this.lastNeed, this.lastNeed = 0;
      } else
        i2 = 0;
      if (i2 < buf.length)
        return r2 ? r2 + this.text(buf, i2) : this.text(buf, i2);
      return r2 || "";
    };
    StringDecoder.prototype.end = utf8End;
    StringDecoder.prototype.text = utf8Text;
    StringDecoder.prototype.fillLast = function(buf) {
      if (this.lastNeed <= buf.length)
        return buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed), this.lastChar.toString(this.encoding, 0, this.lastTotal);
      buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length), this.lastNeed -= buf.length;
    };
    function utf8CheckByte(byte) {
      if (byte <= 127)
        return 0;
      else if (byte >> 5 === 6)
        return 2;
      else if (byte >> 4 === 14)
        return 3;
      else if (byte >> 3 === 30)
        return 4;
      return byte >> 6 === 2 ? -1 : -2;
    }
    function utf8CheckIncomplete(self2, buf, i2) {
      var j = buf.length - 1;
      if (j < i2)
        return 0;
      var nb = utf8CheckByte(buf[j]);
      if (nb >= 0) {
        if (nb > 0)
          self2.lastNeed = nb - 1;
        return nb;
      }
      if (--j < i2 || nb === -2)
        return 0;
      if (nb = utf8CheckByte(buf[j]), nb >= 0) {
        if (nb > 0)
          self2.lastNeed = nb - 2;
        return nb;
      }
      if (--j < i2 || nb === -2)
        return 0;
      if (nb = utf8CheckByte(buf[j]), nb >= 0) {
        if (nb > 0)
          if (nb === 2)
            nb = 0;
          else
            self2.lastNeed = nb - 3;
        return nb;
      }
      return 0;
    }
    function utf8CheckExtraBytes(self2, buf, p2) {
      if ((buf[0] & 192) !== 128)
        return self2.lastNeed = 0, "�";
      if (self2.lastNeed > 1 && buf.length > 1) {
        if ((buf[1] & 192) !== 128)
          return self2.lastNeed = 1, "�";
        if (self2.lastNeed > 2 && buf.length > 2) {
          if ((buf[2] & 192) !== 128)
            return self2.lastNeed = 2, "�";
        }
      }
    }
    function utf8FillLast(buf) {
      var p2 = this.lastTotal - this.lastNeed, r2 = utf8CheckExtraBytes(this, buf, p2);
      if (r2 !== undefined)
        return r2;
      if (this.lastNeed <= buf.length)
        return buf.copy(this.lastChar, p2, 0, this.lastNeed), this.lastChar.toString(this.encoding, 0, this.lastTotal);
      buf.copy(this.lastChar, p2, 0, buf.length), this.lastNeed -= buf.length;
    }
    function utf8Text(buf, i2) {
      var total = utf8CheckIncomplete(this, buf, i2);
      if (!this.lastNeed)
        return buf.toString("utf8", i2);
      this.lastTotal = total;
      var end = buf.length - (total - this.lastNeed);
      return buf.copy(this.lastChar, 0, end), buf.toString("utf8", i2, end);
    }
    function utf8End(buf) {
      var r2 = buf && buf.length ? this.write(buf) : "";
      if (this.lastNeed)
        return r2 + "�";
      return r2;
    }
    function utf16Text(buf, i2) {
      if ((buf.length - i2) % 2 === 0) {
        var r2 = buf.toString("utf16le", i2);
        if (r2) {
          var c2 = r2.charCodeAt(r2.length - 1);
          if (c2 >= 55296 && c2 <= 56319)
            return this.lastNeed = 2, this.lastTotal = 4, this.lastChar[0] = buf[buf.length - 2], this.lastChar[1] = buf[buf.length - 1], r2.slice(0, -1);
        }
        return r2;
      }
      return this.lastNeed = 1, this.lastTotal = 2, this.lastChar[0] = buf[buf.length - 1], buf.toString("utf16le", i2, buf.length - 1);
    }
    function utf16End(buf) {
      var r2 = buf && buf.length ? this.write(buf) : "";
      if (this.lastNeed) {
        var end = this.lastTotal - this.lastNeed;
        return r2 + this.lastChar.toString("utf16le", 0, end);
      }
      return r2;
    }
    function base64Text(buf, i2) {
      var n2 = (buf.length - i2) % 3;
      if (n2 === 0)
        return buf.toString("base64", i2);
      if (this.lastNeed = 3 - n2, this.lastTotal = 3, n2 === 1)
        this.lastChar[0] = buf[buf.length - 1];
      else
        this.lastChar[0] = buf[buf.length - 2], this.lastChar[1] = buf[buf.length - 1];
      return buf.toString("base64", i2, buf.length - n2);
    }
    function base64End(buf) {
      var r2 = buf && buf.length ? this.write(buf) : "";
      if (this.lastNeed)
        return r2 + this.lastChar.toString("base64", 0, 3 - this.lastNeed);
      return r2;
    }
    function simpleWrite(buf) {
      return buf.toString(this.encoding);
    }
    function simpleEnd(buf) {
      return buf && buf.length ? this.write(buf) : "";
    }
  });
  var require_from = __commonJS2((exports2, module2) => {
    var process2 = require_process(), { PromisePrototypeThen, SymbolAsyncIterator, SymbolIterator } = require_primordials(), { Buffer: Buffer3 } = (init_buffer(), __toCommonJS(exports_buffer)), { ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE3, ERR_STREAM_NULL_VALUES } = require_errors().codes;
    function from2(Readable, iterable, opts) {
      let iterator;
      if (typeof iterable === "string" || iterable instanceof Buffer3)
        return new Readable({ objectMode: true, ...opts, read() {
          this.push(iterable), this.push(null);
        } });
      let isAsync;
      if (iterable && iterable[SymbolAsyncIterator])
        isAsync = true, iterator = iterable[SymbolAsyncIterator]();
      else if (iterable && iterable[SymbolIterator])
        isAsync = false, iterator = iterable[SymbolIterator]();
      else
        throw new ERR_INVALID_ARG_TYPE3("iterable", ["Iterable"], iterable);
      let readable = new Readable({ objectMode: true, highWaterMark: 1, ...opts }), reading = false;
      readable._read = function() {
        if (!reading)
          reading = true, next();
      }, readable._destroy = function(error, cb) {
        PromisePrototypeThen(close(error), () => process2.nextTick(cb, error), (e2) => process2.nextTick(cb, e2 || error));
      };
      async function close(error) {
        let hadError = error !== undefined && error !== null, hasThrow = typeof iterator.throw === "function";
        if (hadError && hasThrow) {
          let { value, done } = await iterator.throw(error);
          if (await value, done)
            return;
        }
        if (typeof iterator.return === "function") {
          let { value } = await iterator.return();
          await value;
        }
      }
      async function next() {
        for (;; ) {
          try {
            let { value, done } = isAsync ? await iterator.next() : iterator.next();
            if (done)
              readable.push(null);
            else {
              let res = value && typeof value.then === "function" ? await value : value;
              if (res === null)
                throw reading = false, new ERR_STREAM_NULL_VALUES;
              else if (readable.push(res))
                continue;
              else
                reading = false;
            }
          } catch (err) {
            readable.destroy(err);
          }
          break;
        }
      }
      return readable;
    }
    module2.exports = from2;
  });
  var require_readable = __commonJS2((exports2, module2) => {
    var process2 = require_process(), { ArrayPrototypeIndexOf, NumberIsInteger, NumberIsNaN, NumberParseInt, ObjectDefineProperties, ObjectKeys, ObjectSetPrototypeOf, Promise: Promise2, SafeSet, SymbolAsyncDispose, SymbolAsyncIterator, Symbol: Symbol2 } = require_primordials();
    module2.exports = Readable;
    Readable.ReadableState = ReadableState;
    var { EventEmitter: EE } = (init_events(), __toCommonJS(exports_events)), { Stream, prependListener } = require_legacy(), { Buffer: Buffer3 } = (init_buffer(), __toCommonJS(exports_buffer)), { addAbortSignal } = require_add_abort_signal(), eos = require_end_of_stream(), debug = require_util().debuglog("stream", (fn) => {
      debug = fn;
    }), BufferList = require_buffer_list(), destroyImpl = require_destroy(), { getHighWaterMark, getDefaultHighWaterMark } = require_state(), { aggregateTwoErrors, codes: { ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE3, ERR_METHOD_NOT_IMPLEMENTED, ERR_OUT_OF_RANGE: ERR_OUT_OF_RANGE3, ERR_STREAM_PUSH_AFTER_EOF, ERR_STREAM_UNSHIFT_AFTER_END_EVENT }, AbortError: AbortError2 } = require_errors(), { validateObject } = require_validators(), kPaused = Symbol2("kPaused"), { StringDecoder } = require_string_decoder(), from2 = require_from();
    ObjectSetPrototypeOf(Readable.prototype, Stream.prototype);
    ObjectSetPrototypeOf(Readable, Stream);
    var nop = () => {}, { errorOrDestroy } = destroyImpl, kObjectMode = 1, kEnded = 2, kEndEmitted = 4, kReading = 8, kConstructed = 16, kSync = 32, kNeedReadable = 64, kEmittedReadable = 128, kReadableListening = 256, kResumeScheduled = 512, kErrorEmitted = 1024, kEmitClose = 2048, kAutoDestroy = 4096, kDestroyed = 8192, kClosed = 16384, kCloseEmitted = 32768, kMultiAwaitDrain = 65536, kReadingMore = 131072, kDataEmitted = 262144;
    function makeBitMapDescriptor(bit) {
      return { enumerable: false, get() {
        return (this.state & bit) !== 0;
      }, set(value) {
        if (value)
          this.state |= bit;
        else
          this.state &= ~bit;
      } };
    }
    ObjectDefineProperties(ReadableState.prototype, { objectMode: makeBitMapDescriptor(kObjectMode), ended: makeBitMapDescriptor(kEnded), endEmitted: makeBitMapDescriptor(kEndEmitted), reading: makeBitMapDescriptor(kReading), constructed: makeBitMapDescriptor(kConstructed), sync: makeBitMapDescriptor(kSync), needReadable: makeBitMapDescriptor(kNeedReadable), emittedReadable: makeBitMapDescriptor(kEmittedReadable), readableListening: makeBitMapDescriptor(kReadableListening), resumeScheduled: makeBitMapDescriptor(kResumeScheduled), errorEmitted: makeBitMapDescriptor(kErrorEmitted), emitClose: makeBitMapDescriptor(kEmitClose), autoDestroy: makeBitMapDescriptor(kAutoDestroy), destroyed: makeBitMapDescriptor(kDestroyed), closed: makeBitMapDescriptor(kClosed), closeEmitted: makeBitMapDescriptor(kCloseEmitted), multiAwaitDrain: makeBitMapDescriptor(kMultiAwaitDrain), readingMore: makeBitMapDescriptor(kReadingMore), dataEmitted: makeBitMapDescriptor(kDataEmitted) });
    function ReadableState(options, stream, isDuplex) {
      if (typeof isDuplex !== "boolean")
        isDuplex = stream instanceof require_duplex();
      if (this.state = kEmitClose | kAutoDestroy | kConstructed | kSync, options && options.objectMode)
        this.state |= kObjectMode;
      if (isDuplex && options && options.readableObjectMode)
        this.state |= kObjectMode;
      if (this.highWaterMark = options ? getHighWaterMark(this, options, "readableHighWaterMark", isDuplex) : getDefaultHighWaterMark(false), this.buffer = new BufferList, this.length = 0, this.pipes = [], this.flowing = null, this[kPaused] = null, options && options.emitClose === false)
        this.state &= ~kEmitClose;
      if (options && options.autoDestroy === false)
        this.state &= ~kAutoDestroy;
      if (this.errored = null, this.defaultEncoding = options && options.defaultEncoding || "utf8", this.awaitDrainWriters = null, this.decoder = null, this.encoding = null, options && options.encoding)
        this.decoder = new StringDecoder(options.encoding), this.encoding = options.encoding;
    }
    function Readable(options) {
      if (!(this instanceof Readable))
        return new Readable(options);
      let isDuplex = this instanceof require_duplex();
      if (this._readableState = new ReadableState(options, this, isDuplex), options) {
        if (typeof options.read === "function")
          this._read = options.read;
        if (typeof options.destroy === "function")
          this._destroy = options.destroy;
        if (typeof options.construct === "function")
          this._construct = options.construct;
        if (options.signal && !isDuplex)
          addAbortSignal(options.signal, this);
      }
      Stream.call(this, options), destroyImpl.construct(this, () => {
        if (this._readableState.needReadable)
          maybeReadMore(this, this._readableState);
      });
    }
    Readable.prototype.destroy = destroyImpl.destroy;
    Readable.prototype._undestroy = destroyImpl.undestroy;
    Readable.prototype._destroy = function(err, cb) {
      cb(err);
    };
    Readable.prototype[EE.captureRejectionSymbol] = function(err) {
      this.destroy(err);
    };
    Readable.prototype[SymbolAsyncDispose] = function() {
      let error;
      if (!this.destroyed)
        error = this.readableEnded ? null : new AbortError2, this.destroy(error);
      return new Promise2((resolve, reject) => eos(this, (err) => err && err !== error ? reject(err) : resolve(null)));
    };
    Readable.prototype.push = function(chunk, encoding) {
      return readableAddChunk(this, chunk, encoding, false);
    };
    Readable.prototype.unshift = function(chunk, encoding) {
      return readableAddChunk(this, chunk, encoding, true);
    };
    function readableAddChunk(stream, chunk, encoding, addToFront) {
      debug("readableAddChunk", chunk);
      let state = stream._readableState, err;
      if ((state.state & kObjectMode) === 0) {
        if (typeof chunk === "string") {
          if (encoding = encoding || state.defaultEncoding, state.encoding !== encoding)
            if (addToFront && state.encoding)
              chunk = Buffer3.from(chunk, encoding).toString(state.encoding);
            else
              chunk = Buffer3.from(chunk, encoding), encoding = "";
        } else if (chunk instanceof Buffer3)
          encoding = "";
        else if (Stream._isUint8Array(chunk))
          chunk = Stream._uint8ArrayToBuffer(chunk), encoding = "";
        else if (chunk != null)
          err = new ERR_INVALID_ARG_TYPE3("chunk", ["string", "Buffer", "Uint8Array"], chunk);
      }
      if (err)
        errorOrDestroy(stream, err);
      else if (chunk === null)
        state.state &= ~kReading, onEofChunk(stream, state);
      else if ((state.state & kObjectMode) !== 0 || chunk && chunk.length > 0)
        if (addToFront)
          if ((state.state & kEndEmitted) !== 0)
            errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT);
          else if (state.destroyed || state.errored)
            return false;
          else
            addChunk(stream, state, chunk, true);
        else if (state.ended)
          errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF);
        else if (state.destroyed || state.errored)
          return false;
        else if (state.state &= ~kReading, state.decoder && !encoding)
          if (chunk = state.decoder.write(chunk), state.objectMode || chunk.length !== 0)
            addChunk(stream, state, chunk, false);
          else
            maybeReadMore(stream, state);
        else
          addChunk(stream, state, chunk, false);
      else if (!addToFront)
        state.state &= ~kReading, maybeReadMore(stream, state);
      return !state.ended && (state.length < state.highWaterMark || state.length === 0);
    }
    function addChunk(stream, state, chunk, addToFront) {
      if (state.flowing && state.length === 0 && !state.sync && stream.listenerCount("data") > 0) {
        if ((state.state & kMultiAwaitDrain) !== 0)
          state.awaitDrainWriters.clear();
        else
          state.awaitDrainWriters = null;
        state.dataEmitted = true, stream.emit("data", chunk);
      } else {
        if (state.length += state.objectMode ? 1 : chunk.length, addToFront)
          state.buffer.unshift(chunk);
        else
          state.buffer.push(chunk);
        if ((state.state & kNeedReadable) !== 0)
          emitReadable(stream);
      }
      maybeReadMore(stream, state);
    }
    Readable.prototype.isPaused = function() {
      let state = this._readableState;
      return state[kPaused] === true || state.flowing === false;
    };
    Readable.prototype.setEncoding = function(enc) {
      let decoder = new StringDecoder(enc);
      this._readableState.decoder = decoder, this._readableState.encoding = this._readableState.decoder.encoding;
      let buffer = this._readableState.buffer, content = "";
      for (let data of buffer)
        content += decoder.write(data);
      if (buffer.clear(), content !== "")
        buffer.push(content);
      return this._readableState.length = content.length, this;
    };
    var MAX_HWM = 1073741824;
    function computeNewHighWaterMark(n2) {
      if (n2 > MAX_HWM)
        throw new ERR_OUT_OF_RANGE3("size", "<= 1GiB", n2);
      else
        n2--, n2 |= n2 >>> 1, n2 |= n2 >>> 2, n2 |= n2 >>> 4, n2 |= n2 >>> 8, n2 |= n2 >>> 16, n2++;
      return n2;
    }
    function howMuchToRead(n2, state) {
      if (n2 <= 0 || state.length === 0 && state.ended)
        return 0;
      if ((state.state & kObjectMode) !== 0)
        return 1;
      if (NumberIsNaN(n2)) {
        if (state.flowing && state.length)
          return state.buffer.first().length;
        return state.length;
      }
      if (n2 <= state.length)
        return n2;
      return state.ended ? state.length : 0;
    }
    Readable.prototype.read = function(n2) {
      if (debug("read", n2), n2 === undefined)
        n2 = NaN;
      else if (!NumberIsInteger(n2))
        n2 = NumberParseInt(n2, 10);
      let state = this._readableState, nOrig = n2;
      if (n2 > state.highWaterMark)
        state.highWaterMark = computeNewHighWaterMark(n2);
      if (n2 !== 0)
        state.state &= ~kEmittedReadable;
      if (n2 === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {
        if (debug("read: emitReadable", state.length, state.ended), state.length === 0 && state.ended)
          endReadable(this);
        else
          emitReadable(this);
        return null;
      }
      if (n2 = howMuchToRead(n2, state), n2 === 0 && state.ended) {
        if (state.length === 0)
          endReadable(this);
        return null;
      }
      let doRead = (state.state & kNeedReadable) !== 0;
      if (debug("need readable", doRead), state.length === 0 || state.length - n2 < state.highWaterMark)
        doRead = true, debug("length less than watermark", doRead);
      if (state.ended || state.reading || state.destroyed || state.errored || !state.constructed)
        doRead = false, debug("reading, ended or constructing", doRead);
      else if (doRead) {
        if (debug("do read"), state.state |= kReading | kSync, state.length === 0)
          state.state |= kNeedReadable;
        try {
          this._read(state.highWaterMark);
        } catch (err) {
          errorOrDestroy(this, err);
        }
        if (state.state &= ~kSync, !state.reading)
          n2 = howMuchToRead(nOrig, state);
      }
      let ret;
      if (n2 > 0)
        ret = fromList(n2, state);
      else
        ret = null;
      if (ret === null)
        state.needReadable = state.length <= state.highWaterMark, n2 = 0;
      else if (state.length -= n2, state.multiAwaitDrain)
        state.awaitDrainWriters.clear();
      else
        state.awaitDrainWriters = null;
      if (state.length === 0) {
        if (!state.ended)
          state.needReadable = true;
        if (nOrig !== n2 && state.ended)
          endReadable(this);
      }
      if (ret !== null && !state.errorEmitted && !state.closeEmitted)
        state.dataEmitted = true, this.emit("data", ret);
      return ret;
    };
    function onEofChunk(stream, state) {
      if (debug("onEofChunk"), state.ended)
        return;
      if (state.decoder) {
        let chunk = state.decoder.end();
        if (chunk && chunk.length)
          state.buffer.push(chunk), state.length += state.objectMode ? 1 : chunk.length;
      }
      if (state.ended = true, state.sync)
        emitReadable(stream);
      else
        state.needReadable = false, state.emittedReadable = true, emitReadable_(stream);
    }
    function emitReadable(stream) {
      let state = stream._readableState;
      if (debug("emitReadable", state.needReadable, state.emittedReadable), state.needReadable = false, !state.emittedReadable)
        debug("emitReadable", state.flowing), state.emittedReadable = true, process2.nextTick(emitReadable_, stream);
    }
    function emitReadable_(stream) {
      let state = stream._readableState;
      if (debug("emitReadable_", state.destroyed, state.length, state.ended), !state.destroyed && !state.errored && (state.length || state.ended))
        stream.emit("readable"), state.emittedReadable = false;
      state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark, flow(stream);
    }
    function maybeReadMore(stream, state) {
      if (!state.readingMore && state.constructed)
        state.readingMore = true, process2.nextTick(maybeReadMore_, stream, state);
    }
    function maybeReadMore_(stream, state) {
      while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {
        let len2 = state.length;
        if (debug("maybeReadMore read 0"), stream.read(0), len2 === state.length)
          break;
      }
      state.readingMore = false;
    }
    Readable.prototype._read = function(n2) {
      throw new ERR_METHOD_NOT_IMPLEMENTED("_read()");
    };
    Readable.prototype.pipe = function(dest, pipeOpts) {
      let src = this, state = this._readableState;
      if (state.pipes.length === 1) {
        if (!state.multiAwaitDrain)
          state.multiAwaitDrain = true, state.awaitDrainWriters = new SafeSet(state.awaitDrainWriters ? [state.awaitDrainWriters] : []);
      }
      state.pipes.push(dest), debug("pipe count=%d opts=%j", state.pipes.length, pipeOpts);
      let endFn = (!pipeOpts || pipeOpts.end !== false) && dest !== process2.stdout && dest !== process2.stderr ? onend : unpipe;
      if (state.endEmitted)
        process2.nextTick(endFn);
      else
        src.once("end", endFn);
      dest.on("unpipe", onunpipe);
      function onunpipe(readable, unpipeInfo) {
        if (debug("onunpipe"), readable === src) {
          if (unpipeInfo && unpipeInfo.hasUnpiped === false)
            unpipeInfo.hasUnpiped = true, cleanup();
        }
      }
      function onend() {
        debug("onend"), dest.end();
      }
      let ondrain, cleanedUp = false;
      function cleanup() {
        if (debug("cleanup"), dest.removeListener("close", onclose), dest.removeListener("finish", onfinish), ondrain)
          dest.removeListener("drain", ondrain);
        if (dest.removeListener("error", onerror), dest.removeListener("unpipe", onunpipe), src.removeListener("end", onend), src.removeListener("end", unpipe), src.removeListener("data", ondata), cleanedUp = true, ondrain && state.awaitDrainWriters && (!dest._writableState || dest._writableState.needDrain))
          ondrain();
      }
      function pause() {
        if (!cleanedUp) {
          if (state.pipes.length === 1 && state.pipes[0] === dest)
            debug("false write response, pause", 0), state.awaitDrainWriters = dest, state.multiAwaitDrain = false;
          else if (state.pipes.length > 1 && state.pipes.includes(dest))
            debug("false write response, pause", state.awaitDrainWriters.size), state.awaitDrainWriters.add(dest);
          src.pause();
        }
        if (!ondrain)
          ondrain = pipeOnDrain(src, dest), dest.on("drain", ondrain);
      }
      src.on("data", ondata);
      function ondata(chunk) {
        debug("ondata");
        let ret = dest.write(chunk);
        if (debug("dest.write", ret), ret === false)
          pause();
      }
      function onerror(er) {
        if (debug("onerror", er), unpipe(), dest.removeListener("error", onerror), dest.listenerCount("error") === 0) {
          let s = dest._writableState || dest._readableState;
          if (s && !s.errorEmitted)
            errorOrDestroy(dest, er);
          else
            dest.emit("error", er);
        }
      }
      prependListener(dest, "error", onerror);
      function onclose() {
        dest.removeListener("finish", onfinish), unpipe();
      }
      dest.once("close", onclose);
      function onfinish() {
        debug("onfinish"), dest.removeListener("close", onclose), unpipe();
      }
      dest.once("finish", onfinish);
      function unpipe() {
        debug("unpipe"), src.unpipe(dest);
      }
      if (dest.emit("pipe", src), dest.writableNeedDrain === true)
        pause();
      else if (!state.flowing)
        debug("pipe resume"), src.resume();
      return dest;
    };
    function pipeOnDrain(src, dest) {
      return function() {
        let state = src._readableState;
        if (state.awaitDrainWriters === dest)
          debug("pipeOnDrain", 1), state.awaitDrainWriters = null;
        else if (state.multiAwaitDrain)
          debug("pipeOnDrain", state.awaitDrainWriters.size), state.awaitDrainWriters.delete(dest);
        if ((!state.awaitDrainWriters || state.awaitDrainWriters.size === 0) && src.listenerCount("data"))
          src.resume();
      };
    }
    Readable.prototype.unpipe = function(dest) {
      let state = this._readableState, unpipeInfo = { hasUnpiped: false };
      if (state.pipes.length === 0)
        return this;
      if (!dest) {
        let dests = state.pipes;
        state.pipes = [], this.pause();
        for (let i2 = 0;i2 < dests.length; i2++)
          dests[i2].emit("unpipe", this, { hasUnpiped: false });
        return this;
      }
      let index = ArrayPrototypeIndexOf(state.pipes, dest);
      if (index === -1)
        return this;
      if (state.pipes.splice(index, 1), state.pipes.length === 0)
        this.pause();
      return dest.emit("unpipe", this, unpipeInfo), this;
    };
    Readable.prototype.on = function(ev, fn) {
      let res = Stream.prototype.on.call(this, ev, fn), state = this._readableState;
      if (ev === "data") {
        if (state.readableListening = this.listenerCount("readable") > 0, state.flowing !== false)
          this.resume();
      } else if (ev === "readable") {
        if (!state.endEmitted && !state.readableListening) {
          if (state.readableListening = state.needReadable = true, state.flowing = false, state.emittedReadable = false, debug("on readable", state.length, state.reading), state.length)
            emitReadable(this);
          else if (!state.reading)
            process2.nextTick(nReadingNextTick, this);
        }
      }
      return res;
    };
    Readable.prototype.addListener = Readable.prototype.on;
    Readable.prototype.removeListener = function(ev, fn) {
      let res = Stream.prototype.removeListener.call(this, ev, fn);
      if (ev === "readable")
        process2.nextTick(updateReadableListening, this);
      return res;
    };
    Readable.prototype.off = Readable.prototype.removeListener;
    Readable.prototype.removeAllListeners = function(ev) {
      let res = Stream.prototype.removeAllListeners.apply(this, arguments);
      if (ev === "readable" || ev === undefined)
        process2.nextTick(updateReadableListening, this);
      return res;
    };
    function updateReadableListening(self2) {
      let state = self2._readableState;
      if (state.readableListening = self2.listenerCount("readable") > 0, state.resumeScheduled && state[kPaused] === false)
        state.flowing = true;
      else if (self2.listenerCount("data") > 0)
        self2.resume();
      else if (!state.readableListening)
        state.flowing = null;
    }
    function nReadingNextTick(self2) {
      debug("readable nexttick read 0"), self2.read(0);
    }
    Readable.prototype.resume = function() {
      let state = this._readableState;
      if (!state.flowing)
        debug("resume"), state.flowing = !state.readableListening, resume(this, state);
      return state[kPaused] = false, this;
    };
    function resume(stream, state) {
      if (!state.resumeScheduled)
        state.resumeScheduled = true, process2.nextTick(resume_, stream, state);
    }
    function resume_(stream, state) {
      if (debug("resume", state.reading), !state.reading)
        stream.read(0);
      if (state.resumeScheduled = false, stream.emit("resume"), flow(stream), state.flowing && !state.reading)
        stream.read(0);
    }
    Readable.prototype.pause = function() {
      if (debug("call pause flowing=%j", this._readableState.flowing), this._readableState.flowing !== false)
        debug("pause"), this._readableState.flowing = false, this.emit("pause");
      return this._readableState[kPaused] = true, this;
    };
    function flow(stream) {
      let state = stream._readableState;
      debug("flow", state.flowing);
      while (state.flowing && stream.read() !== null)
        ;
    }
    Readable.prototype.wrap = function(stream) {
      let paused = false;
      stream.on("data", (chunk) => {
        if (!this.push(chunk) && stream.pause)
          paused = true, stream.pause();
      }), stream.on("end", () => {
        this.push(null);
      }), stream.on("error", (err) => {
        errorOrDestroy(this, err);
      }), stream.on("close", () => {
        this.destroy();
      }), stream.on("destroy", () => {
        this.destroy();
      }), this._read = () => {
        if (paused && stream.resume)
          paused = false, stream.resume();
      };
      let streamKeys = ObjectKeys(stream);
      for (let j = 1;j < streamKeys.length; j++) {
        let i2 = streamKeys[j];
        if (this[i2] === undefined && typeof stream[i2] === "function")
          this[i2] = stream[i2].bind(stream);
      }
      return this;
    };
    Readable.prototype[SymbolAsyncIterator] = function() {
      return streamToAsyncIterator(this);
    };
    Readable.prototype.iterator = function(options) {
      if (options !== undefined)
        validateObject(options, "options");
      return streamToAsyncIterator(this, options);
    };
    function streamToAsyncIterator(stream, options) {
      if (typeof stream.read !== "function")
        stream = Readable.wrap(stream, { objectMode: true });
      let iter = createAsyncIterator(stream, options);
      return iter.stream = stream, iter;
    }
    async function* createAsyncIterator(stream, options) {
      let callback = nop;
      function next(resolve) {
        if (this === stream)
          callback(), callback = nop;
        else
          callback = resolve;
      }
      stream.on("readable", next);
      let error, cleanup = eos(stream, { writable: false }, (err) => {
        error = err ? aggregateTwoErrors(error, err) : null, callback(), callback = nop;
      });
      try {
        while (true) {
          let chunk = stream.destroyed ? null : stream.read();
          if (chunk !== null)
            yield chunk;
          else if (error)
            throw error;
          else if (error === null)
            return;
          else
            await new Promise2(next);
        }
      } catch (err) {
        throw error = aggregateTwoErrors(error, err), error;
      } finally {
        if ((error || (options === null || options === undefined ? undefined : options.destroyOnReturn) !== false) && (error === undefined || stream._readableState.autoDestroy))
          destroyImpl.destroyer(stream, null);
        else
          stream.off("readable", next), cleanup();
      }
    }
    ObjectDefineProperties(Readable.prototype, { readable: { __proto__: null, get() {
      let r2 = this._readableState;
      return !!r2 && r2.readable !== false && !r2.destroyed && !r2.errorEmitted && !r2.endEmitted;
    }, set(val) {
      if (this._readableState)
        this._readableState.readable = !!val;
    } }, readableDidRead: { __proto__: null, enumerable: false, get: function() {
      return this._readableState.dataEmitted;
    } }, readableAborted: { __proto__: null, enumerable: false, get: function() {
      return !!(this._readableState.readable !== false && (this._readableState.destroyed || this._readableState.errored) && !this._readableState.endEmitted);
    } }, readableHighWaterMark: { __proto__: null, enumerable: false, get: function() {
      return this._readableState.highWaterMark;
    } }, readableBuffer: { __proto__: null, enumerable: false, get: function() {
      return this._readableState && this._readableState.buffer;
    } }, readableFlowing: { __proto__: null, enumerable: false, get: function() {
      return this._readableState.flowing;
    }, set: function(state) {
      if (this._readableState)
        this._readableState.flowing = state;
    } }, readableLength: { __proto__: null, enumerable: false, get() {
      return this._readableState.length;
    } }, readableObjectMode: { __proto__: null, enumerable: false, get() {
      return this._readableState ? this._readableState.objectMode : false;
    } }, readableEncoding: { __proto__: null, enumerable: false, get() {
      return this._readableState ? this._readableState.encoding : null;
    } }, errored: { __proto__: null, enumerable: false, get() {
      return this._readableState ? this._readableState.errored : null;
    } }, closed: { __proto__: null, get() {
      return this._readableState ? this._readableState.closed : false;
    } }, destroyed: { __proto__: null, enumerable: false, get() {
      return this._readableState ? this._readableState.destroyed : false;
    }, set(value) {
      if (!this._readableState)
        return;
      this._readableState.destroyed = value;
    } }, readableEnded: { __proto__: null, enumerable: false, get() {
      return this._readableState ? this._readableState.endEmitted : false;
    } } });
    ObjectDefineProperties(ReadableState.prototype, { pipesCount: { __proto__: null, get() {
      return this.pipes.length;
    } }, paused: { __proto__: null, get() {
      return this[kPaused] !== false;
    }, set(value) {
      this[kPaused] = !!value;
    } } });
    Readable._fromList = fromList;
    function fromList(n2, state) {
      if (state.length === 0)
        return null;
      let ret;
      if (state.objectMode)
        ret = state.buffer.shift();
      else if (!n2 || n2 >= state.length) {
        if (state.decoder)
          ret = state.buffer.join("");
        else if (state.buffer.length === 1)
          ret = state.buffer.first();
        else
          ret = state.buffer.concat(state.length);
        state.buffer.clear();
      } else
        ret = state.buffer.consume(n2, state.decoder);
      return ret;
    }
    function endReadable(stream) {
      let state = stream._readableState;
      if (debug("endReadable", state.endEmitted), !state.endEmitted)
        state.ended = true, process2.nextTick(endReadableNT, state, stream);
    }
    function endReadableNT(state, stream) {
      if (debug("endReadableNT", state.endEmitted, state.length), !state.errored && !state.closeEmitted && !state.endEmitted && state.length === 0) {
        if (state.endEmitted = true, stream.emit("end"), stream.writable && stream.allowHalfOpen === false)
          process2.nextTick(endWritableNT, stream);
        else if (state.autoDestroy) {
          let wState = stream._writableState;
          if (!wState || wState.autoDestroy && (wState.finished || wState.writable === false))
            stream.destroy();
        }
      }
    }
    function endWritableNT(stream) {
      if (stream.writable && !stream.writableEnded && !stream.destroyed)
        stream.end();
    }
    Readable.from = function(iterable, opts) {
      return from2(Readable, iterable, opts);
    };
    var webStreamsAdapters;
    function lazyWebStreams() {
      if (webStreamsAdapters === undefined)
        webStreamsAdapters = {};
      return webStreamsAdapters;
    }
    Readable.fromWeb = function(readableStream, options) {
      return lazyWebStreams().newStreamReadableFromReadableStream(readableStream, options);
    };
    Readable.toWeb = function(streamReadable, options) {
      return lazyWebStreams().newReadableStreamFromStreamReadable(streamReadable, options);
    };
    Readable.wrap = function(src, options) {
      var _ref, _src$readableObjectMo;
      return new Readable({ objectMode: (_ref = (_src$readableObjectMo = src.readableObjectMode) !== null && _src$readableObjectMo !== undefined ? _src$readableObjectMo : src.objectMode) !== null && _ref !== undefined ? _ref : true, ...options, destroy(err, callback) {
        destroyImpl.destroyer(src, err), callback(err);
      } }).wrap(src);
    };
  });
  var require_writable = __commonJS2((exports2, module2) => {
    var process2 = require_process(), { ArrayPrototypeSlice: ArrayPrototypeSlice2, Error: Error2, FunctionPrototypeSymbolHasInstance, ObjectDefineProperty, ObjectDefineProperties, ObjectSetPrototypeOf, StringPrototypeToLowerCase, Symbol: Symbol2, SymbolHasInstance } = require_primordials();
    module2.exports = Writable;
    Writable.WritableState = WritableState;
    var { EventEmitter: EE } = (init_events(), __toCommonJS(exports_events)), Stream = require_legacy().Stream, { Buffer: Buffer3 } = (init_buffer(), __toCommonJS(exports_buffer)), destroyImpl = require_destroy(), { addAbortSignal } = require_add_abort_signal(), { getHighWaterMark, getDefaultHighWaterMark } = require_state(), { ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE3, ERR_METHOD_NOT_IMPLEMENTED, ERR_MULTIPLE_CALLBACK, ERR_STREAM_CANNOT_PIPE, ERR_STREAM_DESTROYED, ERR_STREAM_ALREADY_FINISHED, ERR_STREAM_NULL_VALUES, ERR_STREAM_WRITE_AFTER_END, ERR_UNKNOWN_ENCODING } = require_errors().codes, { errorOrDestroy } = destroyImpl;
    ObjectSetPrototypeOf(Writable.prototype, Stream.prototype);
    ObjectSetPrototypeOf(Writable, Stream);
    function nop() {}
    var kOnFinished = Symbol2("kOnFinished");
    function WritableState(options, stream, isDuplex) {
      if (typeof isDuplex !== "boolean")
        isDuplex = stream instanceof require_duplex();
      if (this.objectMode = !!(options && options.objectMode), isDuplex)
        this.objectMode = this.objectMode || !!(options && options.writableObjectMode);
      this.highWaterMark = options ? getHighWaterMark(this, options, "writableHighWaterMark", isDuplex) : getDefaultHighWaterMark(false), this.finalCalled = false, this.needDrain = false, this.ending = false, this.ended = false, this.finished = false, this.destroyed = false;
      let noDecode = !!(options && options.decodeStrings === false);
      this.decodeStrings = !noDecode, this.defaultEncoding = options && options.defaultEncoding || "utf8", this.length = 0, this.writing = false, this.corked = 0, this.sync = true, this.bufferProcessing = false, this.onwrite = onwrite.bind(undefined, stream), this.writecb = null, this.writelen = 0, this.afterWriteTickInfo = null, resetBuffer(this), this.pendingcb = 0, this.constructed = true, this.prefinished = false, this.errorEmitted = false, this.emitClose = !options || options.emitClose !== false, this.autoDestroy = !options || options.autoDestroy !== false, this.errored = null, this.closed = false, this.closeEmitted = false, this[kOnFinished] = [];
    }
    function resetBuffer(state) {
      state.buffered = [], state.bufferedIndex = 0, state.allBuffers = true, state.allNoop = true;
    }
    WritableState.prototype.getBuffer = function() {
      return ArrayPrototypeSlice2(this.buffered, this.bufferedIndex);
    };
    ObjectDefineProperty(WritableState.prototype, "bufferedRequestCount", { __proto__: null, get() {
      return this.buffered.length - this.bufferedIndex;
    } });
    function Writable(options) {
      let isDuplex = this instanceof require_duplex();
      if (!isDuplex && !FunctionPrototypeSymbolHasInstance(Writable, this))
        return new Writable(options);
      if (this._writableState = new WritableState(options, this, isDuplex), options) {
        if (typeof options.write === "function")
          this._write = options.write;
        if (typeof options.writev === "function")
          this._writev = options.writev;
        if (typeof options.destroy === "function")
          this._destroy = options.destroy;
        if (typeof options.final === "function")
          this._final = options.final;
        if (typeof options.construct === "function")
          this._construct = options.construct;
        if (options.signal)
          addAbortSignal(options.signal, this);
      }
      Stream.call(this, options), destroyImpl.construct(this, () => {
        let state = this._writableState;
        if (!state.writing)
          clearBuffer(this, state);
        finishMaybe(this, state);
      });
    }
    ObjectDefineProperty(Writable, SymbolHasInstance, { __proto__: null, value: function(object) {
      if (FunctionPrototypeSymbolHasInstance(this, object))
        return true;
      if (this !== Writable)
        return false;
      return object && object._writableState instanceof WritableState;
    } });
    Writable.prototype.pipe = function() {
      errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE);
    };
    function _write(stream, chunk, encoding, cb) {
      let state = stream._writableState;
      if (typeof encoding === "function")
        cb = encoding, encoding = state.defaultEncoding;
      else {
        if (!encoding)
          encoding = state.defaultEncoding;
        else if (encoding !== "buffer" && !Buffer3.isEncoding(encoding))
          throw new ERR_UNKNOWN_ENCODING(encoding);
        if (typeof cb !== "function")
          cb = nop;
      }
      if (chunk === null)
        throw new ERR_STREAM_NULL_VALUES;
      else if (!state.objectMode)
        if (typeof chunk === "string") {
          if (state.decodeStrings !== false)
            chunk = Buffer3.from(chunk, encoding), encoding = "buffer";
        } else if (chunk instanceof Buffer3)
          encoding = "buffer";
        else if (Stream._isUint8Array(chunk))
          chunk = Stream._uint8ArrayToBuffer(chunk), encoding = "buffer";
        else
          throw new ERR_INVALID_ARG_TYPE3("chunk", ["string", "Buffer", "Uint8Array"], chunk);
      let err;
      if (state.ending)
        err = new ERR_STREAM_WRITE_AFTER_END;
      else if (state.destroyed)
        err = new ERR_STREAM_DESTROYED("write");
      if (err)
        return process2.nextTick(cb, err), errorOrDestroy(stream, err, true), err;
      return state.pendingcb++, writeOrBuffer(stream, state, chunk, encoding, cb);
    }
    Writable.prototype.write = function(chunk, encoding, cb) {
      return _write(this, chunk, encoding, cb) === true;
    };
    Writable.prototype.cork = function() {
      this._writableState.corked++;
    };
    Writable.prototype.uncork = function() {
      let state = this._writableState;
      if (state.corked) {
        if (state.corked--, !state.writing)
          clearBuffer(this, state);
      }
    };
    Writable.prototype.setDefaultEncoding = function(encoding) {
      if (typeof encoding === "string")
        encoding = StringPrototypeToLowerCase(encoding);
      if (!Buffer3.isEncoding(encoding))
        throw new ERR_UNKNOWN_ENCODING(encoding);
      return this._writableState.defaultEncoding = encoding, this;
    };
    function writeOrBuffer(stream, state, chunk, encoding, callback) {
      let len2 = state.objectMode ? 1 : chunk.length;
      state.length += len2;
      let ret = state.length < state.highWaterMark;
      if (!ret)
        state.needDrain = true;
      if (state.writing || state.corked || state.errored || !state.constructed) {
        if (state.buffered.push({ chunk, encoding, callback }), state.allBuffers && encoding !== "buffer")
          state.allBuffers = false;
        if (state.allNoop && callback !== nop)
          state.allNoop = false;
      } else
        state.writelen = len2, state.writecb = callback, state.writing = true, state.sync = true, stream._write(chunk, encoding, state.onwrite), state.sync = false;
      return ret && !state.errored && !state.destroyed;
    }
    function doWrite(stream, state, writev, len2, chunk, encoding, cb) {
      if (state.writelen = len2, state.writecb = cb, state.writing = true, state.sync = true, state.destroyed)
        state.onwrite(new ERR_STREAM_DESTROYED("write"));
      else if (writev)
        stream._writev(chunk, state.onwrite);
      else
        stream._write(chunk, encoding, state.onwrite);
      state.sync = false;
    }
    function onwriteError(stream, state, er, cb) {
      --state.pendingcb, cb(er), errorBuffer(state), errorOrDestroy(stream, er);
    }
    function onwrite(stream, er) {
      let state = stream._writableState, sync = state.sync, cb = state.writecb;
      if (typeof cb !== "function") {
        errorOrDestroy(stream, new ERR_MULTIPLE_CALLBACK);
        return;
      }
      if (state.writing = false, state.writecb = null, state.length -= state.writelen, state.writelen = 0, er) {
        if (er.stack, !state.errored)
          state.errored = er;
        if (stream._readableState && !stream._readableState.errored)
          stream._readableState.errored = er;
        if (sync)
          process2.nextTick(onwriteError, stream, state, er, cb);
        else
          onwriteError(stream, state, er, cb);
      } else {
        if (state.buffered.length > state.bufferedIndex)
          clearBuffer(stream, state);
        if (sync)
          if (state.afterWriteTickInfo !== null && state.afterWriteTickInfo.cb === cb)
            state.afterWriteTickInfo.count++;
          else
            state.afterWriteTickInfo = { count: 1, cb, stream, state }, process2.nextTick(afterWriteTick, state.afterWriteTickInfo);
        else
          afterWrite(stream, state, 1, cb);
      }
    }
    function afterWriteTick({ stream, state, count, cb }) {
      return state.afterWriteTickInfo = null, afterWrite(stream, state, count, cb);
    }
    function afterWrite(stream, state, count, cb) {
      if (!state.ending && !stream.destroyed && state.length === 0 && state.needDrain)
        state.needDrain = false, stream.emit("drain");
      while (count-- > 0)
        state.pendingcb--, cb();
      if (state.destroyed)
        errorBuffer(state);
      finishMaybe(stream, state);
    }
    function errorBuffer(state) {
      if (state.writing)
        return;
      for (let n2 = state.bufferedIndex;n2 < state.buffered.length; ++n2) {
        var _state$errored;
        let { chunk, callback } = state.buffered[n2], len2 = state.objectMode ? 1 : chunk.length;
        state.length -= len2, callback((_state$errored = state.errored) !== null && _state$errored !== undefined ? _state$errored : new ERR_STREAM_DESTROYED("write"));
      }
      let onfinishCallbacks = state[kOnFinished].splice(0);
      for (let i2 = 0;i2 < onfinishCallbacks.length; i2++) {
        var _state$errored2;
        onfinishCallbacks[i2]((_state$errored2 = state.errored) !== null && _state$errored2 !== undefined ? _state$errored2 : new ERR_STREAM_DESTROYED("end"));
      }
      resetBuffer(state);
    }
    function clearBuffer(stream, state) {
      if (state.corked || state.bufferProcessing || state.destroyed || !state.constructed)
        return;
      let { buffered, bufferedIndex, objectMode } = state, bufferedLength = buffered.length - bufferedIndex;
      if (!bufferedLength)
        return;
      let i2 = bufferedIndex;
      if (state.bufferProcessing = true, bufferedLength > 1 && stream._writev) {
        state.pendingcb -= bufferedLength - 1;
        let callback = state.allNoop ? nop : (err) => {
          for (let n2 = i2;n2 < buffered.length; ++n2)
            buffered[n2].callback(err);
        }, chunks = state.allNoop && i2 === 0 ? buffered : ArrayPrototypeSlice2(buffered, i2);
        chunks.allBuffers = state.allBuffers, doWrite(stream, state, true, state.length, chunks, "", callback), resetBuffer(state);
      } else {
        do {
          let { chunk, encoding, callback } = buffered[i2];
          buffered[i2++] = null;
          let len2 = objectMode ? 1 : chunk.length;
          doWrite(stream, state, false, len2, chunk, encoding, callback);
        } while (i2 < buffered.length && !state.writing);
        if (i2 === buffered.length)
          resetBuffer(state);
        else if (i2 > 256)
          buffered.splice(0, i2), state.bufferedIndex = 0;
        else
          state.bufferedIndex = i2;
      }
      state.bufferProcessing = false;
    }
    Writable.prototype._write = function(chunk, encoding, cb) {
      if (this._writev)
        this._writev([{ chunk, encoding }], cb);
      else
        throw new ERR_METHOD_NOT_IMPLEMENTED("_write()");
    };
    Writable.prototype._writev = null;
    Writable.prototype.end = function(chunk, encoding, cb) {
      let state = this._writableState;
      if (typeof chunk === "function")
        cb = chunk, chunk = null, encoding = null;
      else if (typeof encoding === "function")
        cb = encoding, encoding = null;
      let err;
      if (chunk !== null && chunk !== undefined) {
        let ret = _write(this, chunk, encoding);
        if (ret instanceof Error2)
          err = ret;
      }
      if (state.corked)
        state.corked = 1, this.uncork();
      if (err)
        ;
      else if (!state.errored && !state.ending)
        state.ending = true, finishMaybe(this, state, true), state.ended = true;
      else if (state.finished)
        err = new ERR_STREAM_ALREADY_FINISHED("end");
      else if (state.destroyed)
        err = new ERR_STREAM_DESTROYED("end");
      if (typeof cb === "function")
        if (err || state.finished)
          process2.nextTick(cb, err);
        else
          state[kOnFinished].push(cb);
      return this;
    };
    function needFinish(state) {
      return state.ending && !state.destroyed && state.constructed && state.length === 0 && !state.errored && state.buffered.length === 0 && !state.finished && !state.writing && !state.errorEmitted && !state.closeEmitted;
    }
    function callFinal(stream, state) {
      let called = false;
      function onFinish(err) {
        if (called) {
          errorOrDestroy(stream, err !== null && err !== undefined ? err : ERR_MULTIPLE_CALLBACK());
          return;
        }
        if (called = true, state.pendingcb--, err) {
          let onfinishCallbacks = state[kOnFinished].splice(0);
          for (let i2 = 0;i2 < onfinishCallbacks.length; i2++)
            onfinishCallbacks[i2](err);
          errorOrDestroy(stream, err, state.sync);
        } else if (needFinish(state))
          state.prefinished = true, stream.emit("prefinish"), state.pendingcb++, process2.nextTick(finish, stream, state);
      }
      state.sync = true, state.pendingcb++;
      try {
        stream._final(onFinish);
      } catch (err) {
        onFinish(err);
      }
      state.sync = false;
    }
    function prefinish(stream, state) {
      if (!state.prefinished && !state.finalCalled)
        if (typeof stream._final === "function" && !state.destroyed)
          state.finalCalled = true, callFinal(stream, state);
        else
          state.prefinished = true, stream.emit("prefinish");
    }
    function finishMaybe(stream, state, sync) {
      if (needFinish(state)) {
        if (prefinish(stream, state), state.pendingcb === 0) {
          if (sync)
            state.pendingcb++, process2.nextTick((stream2, state2) => {
              if (needFinish(state2))
                finish(stream2, state2);
              else
                state2.pendingcb--;
            }, stream, state);
          else if (needFinish(state))
            state.pendingcb++, finish(stream, state);
        }
      }
    }
    function finish(stream, state) {
      state.pendingcb--, state.finished = true;
      let onfinishCallbacks = state[kOnFinished].splice(0);
      for (let i2 = 0;i2 < onfinishCallbacks.length; i2++)
        onfinishCallbacks[i2]();
      if (stream.emit("finish"), state.autoDestroy) {
        let rState = stream._readableState;
        if (!rState || rState.autoDestroy && (rState.endEmitted || rState.readable === false))
          stream.destroy();
      }
    }
    ObjectDefineProperties(Writable.prototype, { closed: { __proto__: null, get() {
      return this._writableState ? this._writableState.closed : false;
    } }, destroyed: { __proto__: null, get() {
      return this._writableState ? this._writableState.destroyed : false;
    }, set(value) {
      if (this._writableState)
        this._writableState.destroyed = value;
    } }, writable: { __proto__: null, get() {
      let w = this._writableState;
      return !!w && w.writable !== false && !w.destroyed && !w.errored && !w.ending && !w.ended;
    }, set(val) {
      if (this._writableState)
        this._writableState.writable = !!val;
    } }, writableFinished: { __proto__: null, get() {
      return this._writableState ? this._writableState.finished : false;
    } }, writableObjectMode: { __proto__: null, get() {
      return this._writableState ? this._writableState.objectMode : false;
    } }, writableBuffer: { __proto__: null, get() {
      return this._writableState && this._writableState.getBuffer();
    } }, writableEnded: { __proto__: null, get() {
      return this._writableState ? this._writableState.ending : false;
    } }, writableNeedDrain: { __proto__: null, get() {
      let wState = this._writableState;
      if (!wState)
        return false;
      return !wState.destroyed && !wState.ending && wState.needDrain;
    } }, writableHighWaterMark: { __proto__: null, get() {
      return this._writableState && this._writableState.highWaterMark;
    } }, writableCorked: { __proto__: null, get() {
      return this._writableState ? this._writableState.corked : 0;
    } }, writableLength: { __proto__: null, get() {
      return this._writableState && this._writableState.length;
    } }, errored: { __proto__: null, enumerable: false, get() {
      return this._writableState ? this._writableState.errored : null;
    } }, writableAborted: { __proto__: null, enumerable: false, get: function() {
      return !!(this._writableState.writable !== false && (this._writableState.destroyed || this._writableState.errored) && !this._writableState.finished);
    } } });
    var destroy = destroyImpl.destroy;
    Writable.prototype.destroy = function(err, cb) {
      let state = this._writableState;
      if (!state.destroyed && (state.bufferedIndex < state.buffered.length || state[kOnFinished].length))
        process2.nextTick(errorBuffer, state);
      return destroy.call(this, err, cb), this;
    };
    Writable.prototype._undestroy = destroyImpl.undestroy;
    Writable.prototype._destroy = function(err, cb) {
      cb(err);
    };
    Writable.prototype[EE.captureRejectionSymbol] = function(err) {
      this.destroy(err);
    };
    var webStreamsAdapters;
    function lazyWebStreams() {
      if (webStreamsAdapters === undefined)
        webStreamsAdapters = {};
      return webStreamsAdapters;
    }
    Writable.fromWeb = function(writableStream, options) {
      return lazyWebStreams().newStreamWritableFromWritableStream(writableStream, options);
    };
    Writable.toWeb = function(streamWritable) {
      return lazyWebStreams().newWritableStreamFromStreamWritable(streamWritable);
    };
  });
  var require_duplexify = __commonJS2((exports2, module2) => {
    var process2 = require_process(), bufferModule = (init_buffer(), __toCommonJS(exports_buffer)), { isReadable, isWritable, isIterable, isNodeStream, isReadableNodeStream, isWritableNodeStream, isDuplexNodeStream, isReadableStream, isWritableStream } = require_utils(), eos = require_end_of_stream(), { AbortError: AbortError2, codes: { ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE3, ERR_INVALID_RETURN_VALUE } } = require_errors(), { destroyer } = require_destroy(), Duplex = require_duplex(), Readable = require_readable(), Writable = require_writable(), { createDeferredPromise } = require_util(), from2 = require_from(), Blob2 = globalThis.Blob || bufferModule.Blob, isBlob = typeof Blob2 < "u" ? function(b) {
      return b instanceof Blob2;
    } : function(b) {
      return false;
    }, AbortController2 = globalThis.AbortController || require_abort_controller().AbortController, { FunctionPrototypeCall } = require_primordials();

    class Duplexify extends Duplex {
      constructor(options) {
        super(options);
        if ((options === null || options === undefined ? undefined : options.readable) === false)
          this._readableState.readable = false, this._readableState.ended = true, this._readableState.endEmitted = true;
        if ((options === null || options === undefined ? undefined : options.writable) === false)
          this._writableState.writable = false, this._writableState.ending = true, this._writableState.ended = true, this._writableState.finished = true;
      }
    }
    module2.exports = function duplexify(body, name) {
      if (isDuplexNodeStream(body))
        return body;
      if (isReadableNodeStream(body))
        return _duplexify({ readable: body });
      if (isWritableNodeStream(body))
        return _duplexify({ writable: body });
      if (isNodeStream(body))
        return _duplexify({ writable: false, readable: false });
      if (isReadableStream(body))
        return _duplexify({ readable: Readable.fromWeb(body) });
      if (isWritableStream(body))
        return _duplexify({ writable: Writable.fromWeb(body) });
      if (typeof body === "function") {
        let { value, write: write2, final, destroy } = fromAsyncGen(body);
        if (isIterable(value))
          return from2(Duplexify, value, { objectMode: true, write: write2, final, destroy });
        let then2 = value === null || value === undefined ? undefined : value.then;
        if (typeof then2 === "function") {
          let d, promise = FunctionPrototypeCall(then2, value, (val) => {
            if (val != null)
              throw new ERR_INVALID_RETURN_VALUE("nully", "body", val);
          }, (err) => {
            destroyer(d, err);
          });
          return d = new Duplexify({ objectMode: true, readable: false, write: write2, final(cb) {
            final(async () => {
              try {
                await promise, process2.nextTick(cb, null);
              } catch (err) {
                process2.nextTick(cb, err);
              }
            });
          }, destroy });
        }
        throw new ERR_INVALID_RETURN_VALUE("Iterable, AsyncIterable or AsyncFunction", name, value);
      }
      if (isBlob(body))
        return duplexify(body.arrayBuffer());
      if (isIterable(body))
        return from2(Duplexify, body, { objectMode: true, writable: false });
      if (isReadableStream(body === null || body === undefined ? undefined : body.readable) && isWritableStream(body === null || body === undefined ? undefined : body.writable))
        return Duplexify.fromWeb(body);
      if (typeof (body === null || body === undefined ? undefined : body.writable) === "object" || typeof (body === null || body === undefined ? undefined : body.readable) === "object") {
        let readable = body !== null && body !== undefined && body.readable ? isReadableNodeStream(body === null || body === undefined ? undefined : body.readable) ? body === null || body === undefined ? undefined : body.readable : duplexify(body.readable) : undefined, writable = body !== null && body !== undefined && body.writable ? isWritableNodeStream(body === null || body === undefined ? undefined : body.writable) ? body === null || body === undefined ? undefined : body.writable : duplexify(body.writable) : undefined;
        return _duplexify({ readable, writable });
      }
      let then = body === null || body === undefined ? undefined : body.then;
      if (typeof then === "function") {
        let d;
        return FunctionPrototypeCall(then, body, (val) => {
          if (val != null)
            d.push(val);
          d.push(null);
        }, (err) => {
          destroyer(d, err);
        }), d = new Duplexify({ objectMode: true, writable: false, read() {} });
      }
      throw new ERR_INVALID_ARG_TYPE3(name, ["Blob", "ReadableStream", "WritableStream", "Stream", "Iterable", "AsyncIterable", "Function", "{ readable, writable } pair", "Promise"], body);
    };
    function fromAsyncGen(fn) {
      let { promise, resolve } = createDeferredPromise(), ac = new AbortController2, signal = ac.signal;
      return { value: fn(async function* () {
        while (true) {
          let _promise = promise;
          promise = null;
          let { chunk, done, cb } = await _promise;
          if (process2.nextTick(cb), done)
            return;
          if (signal.aborted)
            throw new AbortError2(undefined, { cause: signal.reason });
          ({ promise, resolve } = createDeferredPromise()), yield chunk;
        }
      }(), { signal }), write(chunk, encoding, cb) {
        let _resolve = resolve;
        resolve = null, _resolve({ chunk, done: false, cb });
      }, final(cb) {
        let _resolve = resolve;
        resolve = null, _resolve({ done: true, cb });
      }, destroy(err, cb) {
        ac.abort(), cb(err);
      } };
    }
    function _duplexify(pair) {
      let r2 = pair.readable && typeof pair.readable.read !== "function" ? Readable.wrap(pair.readable) : pair.readable, w = pair.writable, readable = !!isReadable(r2), writable = !!isWritable(w), ondrain, onfinish, onreadable, onclose, d;
      function onfinished(err) {
        let cb = onclose;
        if (onclose = null, cb)
          cb(err);
        else if (err)
          d.destroy(err);
      }
      if (d = new Duplexify({ readableObjectMode: !!(r2 !== null && r2 !== undefined && r2.readableObjectMode), writableObjectMode: !!(w !== null && w !== undefined && w.writableObjectMode), readable, writable }), writable)
        eos(w, (err) => {
          if (writable = false, err)
            destroyer(r2, err);
          onfinished(err);
        }), d._write = function(chunk, encoding, callback) {
          if (w.write(chunk, encoding))
            callback();
          else
            ondrain = callback;
        }, d._final = function(callback) {
          w.end(), onfinish = callback;
        }, w.on("drain", function() {
          if (ondrain) {
            let cb = ondrain;
            ondrain = null, cb();
          }
        }), w.on("finish", function() {
          if (onfinish) {
            let cb = onfinish;
            onfinish = null, cb();
          }
        });
      if (readable)
        eos(r2, (err) => {
          if (readable = false, err)
            destroyer(r2, err);
          onfinished(err);
        }), r2.on("readable", function() {
          if (onreadable) {
            let cb = onreadable;
            onreadable = null, cb();
          }
        }), r2.on("end", function() {
          d.push(null);
        }), d._read = function() {
          while (true) {
            let buf = r2.read();
            if (buf === null) {
              onreadable = d._read;
              return;
            }
            if (!d.push(buf))
              return;
          }
        };
      return d._destroy = function(err, callback) {
        if (!err && onclose !== null)
          err = new AbortError2;
        if (onreadable = null, ondrain = null, onfinish = null, onclose === null)
          callback(err);
        else
          onclose = callback, destroyer(w, err), destroyer(r2, err);
      }, d;
    }
  });
  var require_duplex = __commonJS2((exports2, module2) => {
    var { ObjectDefineProperties, ObjectGetOwnPropertyDescriptor, ObjectKeys, ObjectSetPrototypeOf } = require_primordials();
    module2.exports = Duplex;
    var Readable = require_readable(), Writable = require_writable();
    ObjectSetPrototypeOf(Duplex.prototype, Readable.prototype);
    ObjectSetPrototypeOf(Duplex, Readable);
    {
      let keys = ObjectKeys(Writable.prototype);
      for (let i2 = 0;i2 < keys.length; i2++) {
        let method = keys[i2];
        if (!Duplex.prototype[method])
          Duplex.prototype[method] = Writable.prototype[method];
      }
    }
    function Duplex(options) {
      if (!(this instanceof Duplex))
        return new Duplex(options);
      if (Readable.call(this, options), Writable.call(this, options), options) {
        if (this.allowHalfOpen = options.allowHalfOpen !== false, options.readable === false)
          this._readableState.readable = false, this._readableState.ended = true, this._readableState.endEmitted = true;
        if (options.writable === false)
          this._writableState.writable = false, this._writableState.ending = true, this._writableState.ended = true, this._writableState.finished = true;
      } else
        this.allowHalfOpen = true;
    }
    ObjectDefineProperties(Duplex.prototype, { writable: { __proto__: null, ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writable") }, writableHighWaterMark: { __proto__: null, ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableHighWaterMark") }, writableObjectMode: { __proto__: null, ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableObjectMode") }, writableBuffer: { __proto__: null, ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableBuffer") }, writableLength: { __proto__: null, ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableLength") }, writableFinished: { __proto__: null, ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableFinished") }, writableCorked: { __proto__: null, ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableCorked") }, writableEnded: { __proto__: null, ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableEnded") }, writableNeedDrain: { __proto__: null, ...ObjectGetOwnPropertyDescriptor(Writable.prototype, "writableNeedDrain") }, destroyed: { __proto__: null, get() {
      if (this._readableState === undefined || this._writableState === undefined)
        return false;
      return this._readableState.destroyed && this._writableState.destroyed;
    }, set(value) {
      if (this._readableState && this._writableState)
        this._readableState.destroyed = value, this._writableState.destroyed = value;
    } } });
    var webStreamsAdapters;
    function lazyWebStreams() {
      if (webStreamsAdapters === undefined)
        webStreamsAdapters = {};
      return webStreamsAdapters;
    }
    Duplex.fromWeb = function(pair, options) {
      return lazyWebStreams().newStreamDuplexFromReadableWritablePair(pair, options);
    };
    Duplex.toWeb = function(duplex) {
      return lazyWebStreams().newReadableWritablePairFromDuplex(duplex);
    };
    var duplexify;
    Duplex.from = function(body) {
      if (!duplexify)
        duplexify = require_duplexify();
      return duplexify(body, "body");
    };
  });
  var require_transform = __commonJS2((exports2, module2) => {
    var { ObjectSetPrototypeOf, Symbol: Symbol2 } = require_primordials();
    module2.exports = Transform;
    var { ERR_METHOD_NOT_IMPLEMENTED } = require_errors().codes, Duplex = require_duplex(), { getHighWaterMark } = require_state();
    ObjectSetPrototypeOf(Transform.prototype, Duplex.prototype);
    ObjectSetPrototypeOf(Transform, Duplex);
    var kCallback = Symbol2("kCallback");
    function Transform(options) {
      if (!(this instanceof Transform))
        return new Transform(options);
      let readableHighWaterMark = options ? getHighWaterMark(this, options, "readableHighWaterMark", true) : null;
      if (readableHighWaterMark === 0)
        options = { ...options, highWaterMark: null, readableHighWaterMark, writableHighWaterMark: options.writableHighWaterMark || 0 };
      if (Duplex.call(this, options), this._readableState.sync = false, this[kCallback] = null, options) {
        if (typeof options.transform === "function")
          this._transform = options.transform;
        if (typeof options.flush === "function")
          this._flush = options.flush;
      }
      this.on("prefinish", prefinish);
    }
    function final(cb) {
      if (typeof this._flush === "function" && !this.destroyed)
        this._flush((er, data) => {
          if (er) {
            if (cb)
              cb(er);
            else
              this.destroy(er);
            return;
          }
          if (data != null)
            this.push(data);
          if (this.push(null), cb)
            cb();
        });
      else if (this.push(null), cb)
        cb();
    }
    function prefinish() {
      if (this._final !== final)
        final.call(this);
    }
    Transform.prototype._final = final;
    Transform.prototype._transform = function(chunk, encoding, callback) {
      throw new ERR_METHOD_NOT_IMPLEMENTED("_transform()");
    };
    Transform.prototype._write = function(chunk, encoding, callback) {
      let rState = this._readableState, wState = this._writableState, length = rState.length;
      this._transform(chunk, encoding, (err, val) => {
        if (err) {
          callback(err);
          return;
        }
        if (val != null)
          this.push(val);
        if (wState.ended || length === rState.length || rState.length < rState.highWaterMark)
          callback();
        else
          this[kCallback] = callback;
      });
    };
    Transform.prototype._read = function() {
      if (this[kCallback]) {
        let callback = this[kCallback];
        this[kCallback] = null, callback();
      }
    };
  });
  var require_passthrough = __commonJS2((exports2, module2) => {
    var { ObjectSetPrototypeOf } = require_primordials();
    module2.exports = PassThrough;
    var Transform = require_transform();
    ObjectSetPrototypeOf(PassThrough.prototype, Transform.prototype);
    ObjectSetPrototypeOf(PassThrough, Transform);
    function PassThrough(options) {
      if (!(this instanceof PassThrough))
        return new PassThrough(options);
      Transform.call(this, options);
    }
    PassThrough.prototype._transform = function(chunk, encoding, cb) {
      cb(null, chunk);
    };
  });
  var require_pipeline = __commonJS2((exports2, module2) => {
    var process2 = require_process(), { ArrayIsArray, Promise: Promise2, SymbolAsyncIterator, SymbolDispose } = require_primordials(), eos = require_end_of_stream(), { once } = require_util(), destroyImpl = require_destroy(), Duplex = require_duplex(), { aggregateTwoErrors, codes: { ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE3, ERR_INVALID_RETURN_VALUE, ERR_MISSING_ARGS, ERR_STREAM_DESTROYED, ERR_STREAM_PREMATURE_CLOSE }, AbortError: AbortError2 } = require_errors(), { validateFunction, validateAbortSignal: validateAbortSignal2 } = require_validators(), { isIterable, isReadable, isReadableNodeStream, isNodeStream, isTransformStream, isWebStream, isReadableStream, isReadableFinished } = require_utils(), AbortController2 = globalThis.AbortController || require_abort_controller().AbortController, PassThrough, Readable, addAbortListener2;
    function destroyer(stream, reading, writing) {
      let finished = false;
      stream.on("close", () => {
        finished = true;
      });
      let cleanup = eos(stream, { readable: reading, writable: writing }, (err) => {
        finished = !err;
      });
      return { destroy: (err) => {
        if (finished)
          return;
        finished = true, destroyImpl.destroyer(stream, err || new ERR_STREAM_DESTROYED("pipe"));
      }, cleanup };
    }
    function popCallback(streams) {
      return validateFunction(streams[streams.length - 1], "streams[stream.length - 1]"), streams.pop();
    }
    function makeAsyncIterable(val) {
      if (isIterable(val))
        return val;
      else if (isReadableNodeStream(val))
        return fromReadable(val);
      throw new ERR_INVALID_ARG_TYPE3("val", ["Readable", "Iterable", "AsyncIterable"], val);
    }
    async function* fromReadable(val) {
      if (!Readable)
        Readable = require_readable();
      yield* Readable.prototype[SymbolAsyncIterator].call(val);
    }
    async function pumpToNode(iterable, writable, finish, { end }) {
      let error, onresolve = null, resume = (err) => {
        if (err)
          error = err;
        if (onresolve) {
          let callback = onresolve;
          onresolve = null, callback();
        }
      }, wait = () => new Promise2((resolve, reject) => {
        if (error)
          reject(error);
        else
          onresolve = () => {
            if (error)
              reject(error);
            else
              resolve();
          };
      });
      writable.on("drain", resume);
      let cleanup = eos(writable, { readable: false }, resume);
      try {
        if (writable.writableNeedDrain)
          await wait();
        for await (let chunk of iterable)
          if (!writable.write(chunk))
            await wait();
        if (end)
          writable.end(), await wait();
        finish();
      } catch (err) {
        finish(error !== err ? aggregateTwoErrors(error, err) : err);
      } finally {
        cleanup(), writable.off("drain", resume);
      }
    }
    async function pumpToWeb(readable, writable, finish, { end }) {
      if (isTransformStream(writable))
        writable = writable.writable;
      let writer = writable.getWriter();
      try {
        for await (let chunk of readable)
          await writer.ready, writer.write(chunk).catch(() => {});
        if (await writer.ready, end)
          await writer.close();
        finish();
      } catch (err) {
        try {
          await writer.abort(err), finish(err);
        } catch (err2) {
          finish(err2);
        }
      }
    }
    function pipeline(...streams) {
      return pipelineImpl(streams, once(popCallback(streams)));
    }
    function pipelineImpl(streams, callback, opts) {
      if (streams.length === 1 && ArrayIsArray(streams[0]))
        streams = streams[0];
      if (streams.length < 2)
        throw new ERR_MISSING_ARGS("streams");
      let ac = new AbortController2, signal = ac.signal, outerSignal = opts === null || opts === undefined ? undefined : opts.signal, lastStreamCleanup = [];
      validateAbortSignal2(outerSignal, "options.signal");
      function abort() {
        finishImpl(new AbortError2);
      }
      addAbortListener2 = addAbortListener2 || require_util().addAbortListener;
      let disposable;
      if (outerSignal)
        disposable = addAbortListener2(outerSignal, abort);
      let error, value, destroys = [], finishCount = 0;
      function finish(err) {
        finishImpl(err, --finishCount === 0);
      }
      function finishImpl(err, final) {
        var _disposable;
        if (err && (!error || error.code === "ERR_STREAM_PREMATURE_CLOSE"))
          error = err;
        if (!error && !final)
          return;
        while (destroys.length)
          destroys.shift()(error);
        if ((_disposable = disposable) === null || _disposable === undefined || _disposable[SymbolDispose](), ac.abort(), final) {
          if (!error)
            lastStreamCleanup.forEach((fn) => fn());
          process2.nextTick(callback, error, value);
        }
      }
      let ret;
      for (let i2 = 0;i2 < streams.length; i2++) {
        let stream = streams[i2], reading = i2 < streams.length - 1, writing = i2 > 0, end = reading || (opts === null || opts === undefined ? undefined : opts.end) !== false, isLastStream = i2 === streams.length - 1;
        if (isNodeStream(stream)) {
          let onError2 = function(err) {
            if (err && err.name !== "AbortError" && err.code !== "ERR_STREAM_PREMATURE_CLOSE")
              finish(err);
          };
          var onError = onError2;
          if (end) {
            let { destroy, cleanup } = destroyer(stream, reading, writing);
            if (destroys.push(destroy), isReadable(stream) && isLastStream)
              lastStreamCleanup.push(cleanup);
          }
          if (stream.on("error", onError2), isReadable(stream) && isLastStream)
            lastStreamCleanup.push(() => {
              stream.removeListener("error", onError2);
            });
        }
        if (i2 === 0)
          if (typeof stream === "function") {
            if (ret = stream({ signal }), !isIterable(ret))
              throw new ERR_INVALID_RETURN_VALUE("Iterable, AsyncIterable or Stream", "source", ret);
          } else if (isIterable(stream) || isReadableNodeStream(stream) || isTransformStream(stream))
            ret = stream;
          else
            ret = Duplex.from(stream);
        else if (typeof stream === "function") {
          if (isTransformStream(ret)) {
            var _ret;
            ret = makeAsyncIterable((_ret = ret) === null || _ret === undefined ? undefined : _ret.readable);
          } else
            ret = makeAsyncIterable(ret);
          if (ret = stream(ret, { signal }), reading) {
            if (!isIterable(ret, true))
              throw new ERR_INVALID_RETURN_VALUE("AsyncIterable", `transform[${i2 - 1}]`, ret);
          } else {
            var _ret2;
            if (!PassThrough)
              PassThrough = require_passthrough();
            let pt = new PassThrough({ objectMode: true }), then = (_ret2 = ret) === null || _ret2 === undefined ? undefined : _ret2.then;
            if (typeof then === "function")
              finishCount++, then.call(ret, (val) => {
                if (value = val, val != null)
                  pt.write(val);
                if (end)
                  pt.end();
                process2.nextTick(finish);
              }, (err) => {
                pt.destroy(err), process2.nextTick(finish, err);
              });
            else if (isIterable(ret, true))
              finishCount++, pumpToNode(ret, pt, finish, { end });
            else if (isReadableStream(ret) || isTransformStream(ret)) {
              let toRead = ret.readable || ret;
              finishCount++, pumpToNode(toRead, pt, finish, { end });
            } else
              throw new ERR_INVALID_RETURN_VALUE("AsyncIterable or Promise", "destination", ret);
            ret = pt;
            let { destroy, cleanup } = destroyer(ret, false, true);
            if (destroys.push(destroy), isLastStream)
              lastStreamCleanup.push(cleanup);
          }
        } else if (isNodeStream(stream)) {
          if (isReadableNodeStream(ret)) {
            finishCount += 2;
            let cleanup = pipe(ret, stream, finish, { end });
            if (isReadable(stream) && isLastStream)
              lastStreamCleanup.push(cleanup);
          } else if (isTransformStream(ret) || isReadableStream(ret)) {
            let toRead = ret.readable || ret;
            finishCount++, pumpToNode(toRead, stream, finish, { end });
          } else if (isIterable(ret))
            finishCount++, pumpToNode(ret, stream, finish, { end });
          else
            throw new ERR_INVALID_ARG_TYPE3("val", ["Readable", "Iterable", "AsyncIterable", "ReadableStream", "TransformStream"], ret);
          ret = stream;
        } else if (isWebStream(stream)) {
          if (isReadableNodeStream(ret))
            finishCount++, pumpToWeb(makeAsyncIterable(ret), stream, finish, { end });
          else if (isReadableStream(ret) || isIterable(ret))
            finishCount++, pumpToWeb(ret, stream, finish, { end });
          else if (isTransformStream(ret))
            finishCount++, pumpToWeb(ret.readable, stream, finish, { end });
          else
            throw new ERR_INVALID_ARG_TYPE3("val", ["Readable", "Iterable", "AsyncIterable", "ReadableStream", "TransformStream"], ret);
          ret = stream;
        } else
          ret = Duplex.from(stream);
      }
      if (signal !== null && signal !== undefined && signal.aborted || outerSignal !== null && outerSignal !== undefined && outerSignal.aborted)
        process2.nextTick(abort);
      return ret;
    }
    function pipe(src, dst, finish, { end }) {
      let ended = false;
      if (dst.on("close", () => {
        if (!ended)
          finish(new ERR_STREAM_PREMATURE_CLOSE);
      }), src.pipe(dst, { end: false }), end) {
        let endFn2 = function() {
          ended = true, dst.end();
        };
        var endFn = endFn2;
        if (isReadableFinished(src))
          process2.nextTick(endFn2);
        else
          src.once("end", endFn2);
      } else
        finish();
      return eos(src, { readable: true, writable: false }, (err) => {
        let rState = src._readableState;
        if (err && err.code === "ERR_STREAM_PREMATURE_CLOSE" && rState && rState.ended && !rState.errored && !rState.errorEmitted)
          src.once("end", finish).once("error", finish);
        else
          finish(err);
      }), eos(dst, { readable: false, writable: true }, finish);
    }
    module2.exports = { pipelineImpl, pipeline };
  });
  var require_compose = __commonJS2((exports2, module2) => {
    var { pipeline } = require_pipeline(), Duplex = require_duplex(), { destroyer } = require_destroy(), { isNodeStream, isReadable, isWritable, isWebStream, isTransformStream, isWritableStream, isReadableStream } = require_utils(), { AbortError: AbortError2, codes: { ERR_INVALID_ARG_VALUE, ERR_MISSING_ARGS } } = require_errors(), eos = require_end_of_stream();
    module2.exports = function(...streams) {
      if (streams.length === 0)
        throw new ERR_MISSING_ARGS("streams");
      if (streams.length === 1)
        return Duplex.from(streams[0]);
      let orgStreams = [...streams];
      if (typeof streams[0] === "function")
        streams[0] = Duplex.from(streams[0]);
      if (typeof streams[streams.length - 1] === "function") {
        let idx = streams.length - 1;
        streams[idx] = Duplex.from(streams[idx]);
      }
      for (let n2 = 0;n2 < streams.length; ++n2) {
        if (!isNodeStream(streams[n2]) && !isWebStream(streams[n2]))
          continue;
        if (n2 < streams.length - 1 && !(isReadable(streams[n2]) || isReadableStream(streams[n2]) || isTransformStream(streams[n2])))
          throw new ERR_INVALID_ARG_VALUE(`streams[${n2}]`, orgStreams[n2], "must be readable");
        if (n2 > 0 && !(isWritable(streams[n2]) || isWritableStream(streams[n2]) || isTransformStream(streams[n2])))
          throw new ERR_INVALID_ARG_VALUE(`streams[${n2}]`, orgStreams[n2], "must be writable");
      }
      let ondrain, onfinish, onreadable, onclose, d;
      function onfinished(err) {
        let cb = onclose;
        if (onclose = null, cb)
          cb(err);
        else if (err)
          d.destroy(err);
        else if (!readable && !writable)
          d.destroy();
      }
      let head = streams[0], tail = pipeline(streams, onfinished), writable = !!(isWritable(head) || isWritableStream(head) || isTransformStream(head)), readable = !!(isReadable(tail) || isReadableStream(tail) || isTransformStream(tail));
      if (d = new Duplex({ writableObjectMode: !!(head !== null && head !== undefined && head.writableObjectMode), readableObjectMode: !!(tail !== null && tail !== undefined && tail.readableObjectMode), writable, readable }), writable) {
        if (isNodeStream(head))
          d._write = function(chunk, encoding, callback) {
            if (head.write(chunk, encoding))
              callback();
            else
              ondrain = callback;
          }, d._final = function(callback) {
            head.end(), onfinish = callback;
          }, head.on("drain", function() {
            if (ondrain) {
              let cb = ondrain;
              ondrain = null, cb();
            }
          });
        else if (isWebStream(head)) {
          let writer = (isTransformStream(head) ? head.writable : head).getWriter();
          d._write = async function(chunk, encoding, callback) {
            try {
              await writer.ready, writer.write(chunk).catch(() => {}), callback();
            } catch (err) {
              callback(err);
            }
          }, d._final = async function(callback) {
            try {
              await writer.ready, writer.close().catch(() => {}), onfinish = callback;
            } catch (err) {
              callback(err);
            }
          };
        }
        let toRead = isTransformStream(tail) ? tail.readable : tail;
        eos(toRead, () => {
          if (onfinish) {
            let cb = onfinish;
            onfinish = null, cb();
          }
        });
      }
      if (readable) {
        if (isNodeStream(tail))
          tail.on("readable", function() {
            if (onreadable) {
              let cb = onreadable;
              onreadable = null, cb();
            }
          }), tail.on("end", function() {
            d.push(null);
          }), d._read = function() {
            while (true) {
              let buf = tail.read();
              if (buf === null) {
                onreadable = d._read;
                return;
              }
              if (!d.push(buf))
                return;
            }
          };
        else if (isWebStream(tail)) {
          let reader = (isTransformStream(tail) ? tail.readable : tail).getReader();
          d._read = async function() {
            while (true)
              try {
                let { value, done } = await reader.read();
                if (!d.push(value))
                  return;
                if (done) {
                  d.push(null);
                  return;
                }
              } catch {
                return;
              }
          };
        }
      }
      return d._destroy = function(err, callback) {
        if (!err && onclose !== null)
          err = new AbortError2;
        if (onreadable = null, ondrain = null, onfinish = null, onclose === null)
          callback(err);
        else if (onclose = callback, isNodeStream(tail))
          destroyer(tail, err);
      }, d;
    };
  });
  var require_operators = __commonJS2((exports2, module2) => {
    var AbortController2 = globalThis.AbortController || require_abort_controller().AbortController, { codes: { ERR_INVALID_ARG_VALUE, ERR_INVALID_ARG_TYPE: ERR_INVALID_ARG_TYPE3, ERR_MISSING_ARGS, ERR_OUT_OF_RANGE: ERR_OUT_OF_RANGE3 }, AbortError: AbortError2 } = require_errors(), { validateAbortSignal: validateAbortSignal2, validateInteger, validateObject } = require_validators(), kWeakHandler = require_primordials().Symbol("kWeak"), kResistStopPropagation = require_primordials().Symbol("kResistStopPropagation"), { finished } = require_end_of_stream(), staticCompose = require_compose(), { addAbortSignalNoValidate } = require_add_abort_signal(), { isWritable, isNodeStream } = require_utils(), { deprecate: deprecate2 } = require_util(), { ArrayPrototypePush, Boolean: Boolean2, MathFloor, Number: Number2, NumberIsNaN, Promise: Promise2, PromiseReject, PromiseResolve, PromisePrototypeThen, Symbol: Symbol2 } = require_primordials(), kEmpty = Symbol2("kEmpty"), kEof = Symbol2("kEof");
    function compose2(stream, options) {
      if (options != null)
        validateObject(options, "options");
      if ((options === null || options === undefined ? undefined : options.signal) != null)
        validateAbortSignal2(options.signal, "options.signal");
      if (isNodeStream(stream) && !isWritable(stream))
        throw new ERR_INVALID_ARG_VALUE("stream", stream, "must be writable");
      let composedStream = staticCompose(this, stream);
      if (options !== null && options !== undefined && options.signal)
        addAbortSignalNoValidate(options.signal, composedStream);
      return composedStream;
    }
    function map(fn, options) {
      if (typeof fn !== "function")
        throw new ERR_INVALID_ARG_TYPE3("fn", ["Function", "AsyncFunction"], fn);
      if (options != null)
        validateObject(options, "options");
      if ((options === null || options === undefined ? undefined : options.signal) != null)
        validateAbortSignal2(options.signal, "options.signal");
      let concurrency = 1;
      if ((options === null || options === undefined ? undefined : options.concurrency) != null)
        concurrency = MathFloor(options.concurrency);
      let highWaterMark = concurrency - 1;
      if ((options === null || options === undefined ? undefined : options.highWaterMark) != null)
        highWaterMark = MathFloor(options.highWaterMark);
      return validateInteger(concurrency, "options.concurrency", 1), validateInteger(highWaterMark, "options.highWaterMark", 0), highWaterMark += concurrency, async function* () {
        let signal = require_util().AbortSignalAny([options === null || options === undefined ? undefined : options.signal].filter(Boolean2)), stream = this, queue = [], signalOpt = { signal }, next, resume, done = false, cnt = 0;
        function onCatch() {
          done = true, afterItemProcessed();
        }
        function afterItemProcessed() {
          cnt -= 1, maybeResume();
        }
        function maybeResume() {
          if (resume && !done && cnt < concurrency && queue.length < highWaterMark)
            resume(), resume = null;
        }
        async function pump() {
          try {
            for await (let val of stream) {
              if (done)
                return;
              if (signal.aborted)
                throw new AbortError2;
              try {
                if (val = fn(val, signalOpt), val === kEmpty)
                  continue;
                val = PromiseResolve(val);
              } catch (err) {
                val = PromiseReject(err);
              }
              if (cnt += 1, PromisePrototypeThen(val, afterItemProcessed, onCatch), queue.push(val), next)
                next(), next = null;
              if (!done && (queue.length >= highWaterMark || cnt >= concurrency))
                await new Promise2((resolve) => {
                  resume = resolve;
                });
            }
            queue.push(kEof);
          } catch (err) {
            let val = PromiseReject(err);
            PromisePrototypeThen(val, afterItemProcessed, onCatch), queue.push(val);
          } finally {
            if (done = true, next)
              next(), next = null;
          }
        }
        pump();
        try {
          while (true) {
            while (queue.length > 0) {
              let val = await queue[0];
              if (val === kEof)
                return;
              if (signal.aborted)
                throw new AbortError2;
              if (val !== kEmpty)
                yield val;
              queue.shift(), maybeResume();
            }
            await new Promise2((resolve) => {
              next = resolve;
            });
          }
        } finally {
          if (done = true, resume)
            resume(), resume = null;
        }
      }.call(this);
    }
    function asIndexedPairs(options = undefined) {
      if (options != null)
        validateObject(options, "options");
      if ((options === null || options === undefined ? undefined : options.signal) != null)
        validateAbortSignal2(options.signal, "options.signal");
      return async function* () {
        let index = 0;
        for await (let val of this) {
          var _options$signal;
          if (options !== null && options !== undefined && (_options$signal = options.signal) !== null && _options$signal !== undefined && _options$signal.aborted)
            throw new AbortError2({ cause: options.signal.reason });
          yield [index++, val];
        }
      }.call(this);
    }
    async function some(fn, options = undefined) {
      for await (let unused of filter.call(this, fn, options))
        return true;
      return false;
    }
    async function every(fn, options = undefined) {
      if (typeof fn !== "function")
        throw new ERR_INVALID_ARG_TYPE3("fn", ["Function", "AsyncFunction"], fn);
      return !await some.call(this, async (...args) => {
        return !await fn(...args);
      }, options);
    }
    async function find(fn, options) {
      for await (let result of filter.call(this, fn, options))
        return result;
      return;
    }
    async function forEach(fn, options) {
      if (typeof fn !== "function")
        throw new ERR_INVALID_ARG_TYPE3("fn", ["Function", "AsyncFunction"], fn);
      async function forEachFn(value, options2) {
        return await fn(value, options2), kEmpty;
      }
      for await (let unused of map.call(this, forEachFn, options))
        ;
    }
    function filter(fn, options) {
      if (typeof fn !== "function")
        throw new ERR_INVALID_ARG_TYPE3("fn", ["Function", "AsyncFunction"], fn);
      async function filterFn(value, options2) {
        if (await fn(value, options2))
          return value;
        return kEmpty;
      }
      return map.call(this, filterFn, options);
    }

    class ReduceAwareErrMissingArgs extends ERR_MISSING_ARGS {
      constructor() {
        super("reduce");
        this.message = "Reduce of an empty stream requires an initial value";
      }
    }
    async function reduce(reducer, initialValue, options) {
      var _options$signal2;
      if (typeof reducer !== "function")
        throw new ERR_INVALID_ARG_TYPE3("reducer", ["Function", "AsyncFunction"], reducer);
      if (options != null)
        validateObject(options, "options");
      if ((options === null || options === undefined ? undefined : options.signal) != null)
        validateAbortSignal2(options.signal, "options.signal");
      let hasInitialValue = arguments.length > 1;
      if (options !== null && options !== undefined && (_options$signal2 = options.signal) !== null && _options$signal2 !== undefined && _options$signal2.aborted) {
        let err = new AbortError2(undefined, { cause: options.signal.reason });
        throw this.once("error", () => {}), await finished(this.destroy(err)), err;
      }
      let ac = new AbortController2, signal = ac.signal;
      if (options !== null && options !== undefined && options.signal) {
        let opts = { once: true, [kWeakHandler]: this, [kResistStopPropagation]: true };
        options.signal.addEventListener("abort", () => ac.abort(), opts);
      }
      let gotAnyItemFromStream = false;
      try {
        for await (let value of this) {
          var _options$signal3;
          if (gotAnyItemFromStream = true, options !== null && options !== undefined && (_options$signal3 = options.signal) !== null && _options$signal3 !== undefined && _options$signal3.aborted)
            throw new AbortError2;
          if (!hasInitialValue)
            initialValue = value, hasInitialValue = true;
          else
            initialValue = await reducer(initialValue, value, { signal });
        }
        if (!gotAnyItemFromStream && !hasInitialValue)
          throw new ReduceAwareErrMissingArgs;
      } finally {
        ac.abort();
      }
      return initialValue;
    }
    async function toArray(options) {
      if (options != null)
        validateObject(options, "options");
      if ((options === null || options === undefined ? undefined : options.signal) != null)
        validateAbortSignal2(options.signal, "options.signal");
      let result = [];
      for await (let val of this) {
        var _options$signal4;
        if (options !== null && options !== undefined && (_options$signal4 = options.signal) !== null && _options$signal4 !== undefined && _options$signal4.aborted)
          throw new AbortError2(undefined, { cause: options.signal.reason });
        ArrayPrototypePush(result, val);
      }
      return result;
    }
    function flatMap(fn, options) {
      let values = map.call(this, fn, options);
      return async function* () {
        for await (let val of values)
          yield* val;
      }.call(this);
    }
    function toIntegerOrInfinity(number) {
      if (number = Number2(number), NumberIsNaN(number))
        return 0;
      if (number < 0)
        throw new ERR_OUT_OF_RANGE3("number", ">= 0", number);
      return number;
    }
    function drop(number, options = undefined) {
      if (options != null)
        validateObject(options, "options");
      if ((options === null || options === undefined ? undefined : options.signal) != null)
        validateAbortSignal2(options.signal, "options.signal");
      return number = toIntegerOrInfinity(number), async function* () {
        var _options$signal5;
        if (options !== null && options !== undefined && (_options$signal5 = options.signal) !== null && _options$signal5 !== undefined && _options$signal5.aborted)
          throw new AbortError2;
        for await (let val of this) {
          var _options$signal6;
          if (options !== null && options !== undefined && (_options$signal6 = options.signal) !== null && _options$signal6 !== undefined && _options$signal6.aborted)
            throw new AbortError2;
          if (number-- <= 0)
            yield val;
        }
      }.call(this);
    }
    function take(number, options = undefined) {
      if (options != null)
        validateObject(options, "options");
      if ((options === null || options === undefined ? undefined : options.signal) != null)
        validateAbortSignal2(options.signal, "options.signal");
      return number = toIntegerOrInfinity(number), async function* () {
        var _options$signal7;
        if (options !== null && options !== undefined && (_options$signal7 = options.signal) !== null && _options$signal7 !== undefined && _options$signal7.aborted)
          throw new AbortError2;
        for await (let val of this) {
          var _options$signal8;
          if (options !== null && options !== undefined && (_options$signal8 = options.signal) !== null && _options$signal8 !== undefined && _options$signal8.aborted)
            throw new AbortError2;
          if (number-- > 0)
            yield val;
          if (number <= 0)
            return;
        }
      }.call(this);
    }
    module2.exports.streamReturningOperators = { asIndexedPairs: deprecate2(asIndexedPairs, "readable.asIndexedPairs will be removed in a future version."), drop, filter, flatMap, map, take, compose: compose2 };
    module2.exports.promiseReturningOperators = { every, forEach, reduce, toArray, some, find };
  });
  var require_promises = __commonJS2((exports2, module2) => {
    var { ArrayPrototypePop, Promise: Promise2 } = require_primordials(), { isIterable, isNodeStream, isWebStream } = require_utils(), { pipelineImpl: pl } = require_pipeline(), { finished } = require_end_of_stream();
    require_stream2();
    function pipeline(...streams) {
      return new Promise2((resolve, reject) => {
        let signal, end, lastArg = streams[streams.length - 1];
        if (lastArg && typeof lastArg === "object" && !isNodeStream(lastArg) && !isIterable(lastArg) && !isWebStream(lastArg)) {
          let options = ArrayPrototypePop(streams);
          signal = options.signal, end = options.end;
        }
        pl(streams, (err, value) => {
          if (err)
            reject(err);
          else
            resolve(value);
        }, { signal, end });
      });
    }
    module2.exports = { finished, pipeline };
  });
  var require_stream2 = __commonJS2((exports2, module2) => {
    var { Buffer: Buffer3 } = (init_buffer(), __toCommonJS(exports_buffer)), { ObjectDefineProperty, ObjectKeys, ReflectApply } = require_primordials(), { promisify: { custom: customPromisify } } = require_util(), { streamReturningOperators, promiseReturningOperators } = require_operators(), { codes: { ERR_ILLEGAL_CONSTRUCTOR } } = require_errors(), compose2 = require_compose(), { setDefaultHighWaterMark, getDefaultHighWaterMark } = require_state(), { pipeline } = require_pipeline(), { destroyer } = require_destroy(), eos = require_end_of_stream(), promises = require_promises(), utils = require_utils(), Stream = module2.exports = require_legacy().Stream;
    Stream.isDestroyed = utils.isDestroyed;
    Stream.isDisturbed = utils.isDisturbed;
    Stream.isErrored = utils.isErrored;
    Stream.isReadable = utils.isReadable;
    Stream.isWritable = utils.isWritable;
    Stream.Readable = require_readable();
    for (let key of ObjectKeys(streamReturningOperators)) {
      let fn = function(...args) {
        if (new.target)
          throw ERR_ILLEGAL_CONSTRUCTOR();
        return Stream.Readable.from(ReflectApply(op, this, args));
      }, op = streamReturningOperators[key];
      ObjectDefineProperty(fn, "name", { __proto__: null, value: op.name }), ObjectDefineProperty(fn, "length", { __proto__: null, value: op.length }), ObjectDefineProperty(Stream.Readable.prototype, key, { __proto__: null, value: fn, enumerable: false, configurable: true, writable: true });
    }
    for (let key of ObjectKeys(promiseReturningOperators)) {
      let fn = function(...args) {
        if (new.target)
          throw ERR_ILLEGAL_CONSTRUCTOR();
        return ReflectApply(op, this, args);
      }, op = promiseReturningOperators[key];
      ObjectDefineProperty(fn, "name", { __proto__: null, value: op.name }), ObjectDefineProperty(fn, "length", { __proto__: null, value: op.length }), ObjectDefineProperty(Stream.Readable.prototype, key, { __proto__: null, value: fn, enumerable: false, configurable: true, writable: true });
    }
    Stream.Writable = require_writable();
    Stream.Duplex = require_duplex();
    Stream.Transform = require_transform();
    Stream.PassThrough = require_passthrough();
    Stream.pipeline = pipeline;
    var { addAbortSignal } = require_add_abort_signal();
    Stream.addAbortSignal = addAbortSignal;
    Stream.finished = eos;
    Stream.destroy = destroyer;
    Stream.compose = compose2;
    Stream.setDefaultHighWaterMark = setDefaultHighWaterMark;
    Stream.getDefaultHighWaterMark = getDefaultHighWaterMark;
    ObjectDefineProperty(Stream, "promises", { __proto__: null, configurable: true, enumerable: true, get() {
      return promises;
    } });
    ObjectDefineProperty(pipeline, customPromisify, { __proto__: null, enumerable: true, get() {
      return promises.pipeline;
    } });
    ObjectDefineProperty(eos, customPromisify, { __proto__: null, enumerable: true, get() {
      return promises.finished;
    } });
    Stream.Stream = Stream;
    Stream._isUint8Array = function(value) {
      return value instanceof Uint8Array;
    };
    Stream._uint8ArrayToBuffer = function(chunk) {
      return Buffer3.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);
    };
  });
  var require_ours = __commonJS2((exports2, module2) => {
    var Stream = require_stream();
    {
      let CustomStream = require_stream2(), promises = require_promises(), originalDestroy = CustomStream.Readable.destroy;
      module2.exports = CustomStream.Readable, module2.exports._uint8ArrayToBuffer = CustomStream._uint8ArrayToBuffer, module2.exports._isUint8Array = CustomStream._isUint8Array, module2.exports.isDisturbed = CustomStream.isDisturbed, module2.exports.isErrored = CustomStream.isErrored, module2.exports.isReadable = CustomStream.isReadable, module2.exports.Readable = CustomStream.Readable, module2.exports.Writable = CustomStream.Writable, module2.exports.Duplex = CustomStream.Duplex, module2.exports.Transform = CustomStream.Transform, module2.exports.PassThrough = CustomStream.PassThrough, module2.exports.addAbortSignal = CustomStream.addAbortSignal, module2.exports.finished = CustomStream.finished, module2.exports.destroy = CustomStream.destroy, module2.exports.destroy = originalDestroy, module2.exports.pipeline = CustomStream.pipeline, module2.exports.compose = CustomStream.compose, Object.defineProperty(CustomStream, "promises", { configurable: true, enumerable: true, get() {
        return promises;
      } }), module2.exports.Stream = CustomStream.Stream;
    }
    module2.exports.default = module2.exports;
  });
  module.exports = require_ours();
});

// node:crypto
var exports_crypto = {};
__export(exports_crypto, {
  webcrypto: () => webcrypto,
  rng: () => rng2,
  randomUUID: () => randomUUID,
  randomFillSync: () => randomFillSync2,
  randomFill: () => randomFill2,
  randomBytes: () => randomBytes2,
  publicEncrypt: () => publicEncrypt2,
  publicDecrypt: () => publicDecrypt2,
  pseudoRandomBytes: () => pseudoRandomBytes2,
  prng: () => prng2,
  privateEncrypt: () => privateEncrypt2,
  privateDecrypt: () => privateDecrypt2,
  pbkdf2Sync: () => pbkdf2Sync2,
  pbkdf2: () => pbkdf22,
  listCiphers: () => listCiphers2,
  getRandomValues: () => getRandomValues,
  getHashes: () => getHashes2,
  getDiffieHellman: () => getDiffieHellman2,
  getCurves: () => getCurves,
  getCiphers: () => getCiphers2,
  default: () => crypto_default,
  createVerify: () => createVerify2,
  createSign: () => createSign2,
  createHmac: () => createHmac2,
  createHash: () => createHash2,
  createECDH: () => createECDH2,
  createDiffieHellmanGroup: () => createDiffieHellmanGroup2,
  createDiffieHellman: () => createDiffieHellman2,
  createDecipheriv: () => createDecipheriv2,
  createDecipher: () => createDecipher2,
  createCredentials: () => createCredentials2,
  createCipheriv: () => createCipheriv2,
  createCipher: () => createCipher2,
  constants: () => constants2,
  Verify: () => Verify2,
  Sign: () => Sign2,
  Hmac: () => Hmac2,
  Hash: () => Hash2,
  DiffieHellmanGroup: () => DiffieHellmanGroup2,
  DiffieHellman: () => DiffieHellman2,
  Decipheriv: () => Decipheriv2,
  Decipher: () => Decipher2,
  DEFAULT_ENCODING: () => DEFAULT_ENCODING,
  Cipheriv: () => Cipheriv2,
  Cipher: () => Cipher2
});
function getCurves() {
  return hardcoded_curves;
}
var __create2, __getProtoOf2, __defProp2, __getOwnPropNames2, __hasOwnProp2, __toESM2 = (mod, isNodeMode, target) => {
  target = mod != null ? __create2(__getProtoOf2(mod)) : {};
  let to = isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target;
  for (let key of __getOwnPropNames2(mod))
    if (!__hasOwnProp2.call(to, key))
      __defProp2(to, key, { get: () => mod[key], enumerable: true });
  return to;
}, __commonJS2 = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports), require_randombytes, require_create_hash, require_create_hmac, require_algorithms, require_precondition, require_default_encoding, require_safe_buffer, require_isarray, require_type, require_es_object_atoms, require_es_errors, require_eval, require_range, require_ref, require_syntax, require_uri, require_abs, require_floor, require_max, require_min, require_pow, require_round, require_isNaN, require_sign, require_gOPD, require_gopd, require_es_define_property, require_shams, require_has_symbols, require_Reflect_getPrototypeOf, require_Object_getPrototypeOf, require_implementation, require_function_bind, require_functionCall, require_functionApply, require_reflectApply, require_actualApply, require_call_bind_apply_helpers, require_get, require_get_proto, require_hasown, require_get_intrinsic, require_call_bound, require_is_callable, require_for_each, require_possible_typed_array_names, require_available_typed_arrays, require_define_data_property, require_has_property_descriptors, require_set_function_length, require_applyBind, require_call_bind, require_shams2, require_which_typed_array, require_is_typed_array, require_typed_array_buffer, require_to_buffer, require_to_buffer2, require_sync, require_async, require_pbkdf2, require_browserify_cipher, require_diffie_hellman, require_browserify_sign, require_package, require_bn, require_minimalistic_assert, require_utils, require_utils2, require_brorand, require_base, require_inherits_browser, require_inherits, require_short, require_mont, require_edwards, require_curve, require_utils3, require_common, require_common2, require_1, require_256, require_224, require_512, require_384, require_sha, require_ripemd, require_hmac, require_hash, require_secp256k1, require_curves, require_hmac_drbg, require_key, require_signature, require_ec, require_key2, require_signature2, require_eddsa, require_elliptic, require_bn2, require_browser, require_create_ecdh, require_bn3, require_api, require_reporter, require_buffer, require_node, require_base2, require_der, require_constants, require_der2, require_pem, require_decoders, require_der3, require_pem2, require_encoders, require_asn1, require_certificate, require_asn12, require_aesid, require_hash_base, require_md5, require_evp_bytestokey, require_browserify_aes, require_fixProc, require_parse_asn1, require_mgf, require_xor, require_bn4, require_withPublic, require_bn5, require_browserify_rsa, require_publicEncrypt, require_privateDecrypt, require_browser2, require_public_encrypt, require_browser3, require_randomfill, require_crypto_browserify, cryptoBrowserify, prng2, pseudoRandomBytes2, rng2, randomBytes2, Hash2, createHash2, Hmac2, createHmac2, getHashes2, pbkdf22, pbkdf2Sync2, Cipher2, createCipher2, Cipheriv2, createCipheriv2, Decipher2, createDecipher2, Decipheriv2, createDecipheriv2, getCiphers2, listCiphers2, DiffieHellmanGroup2, createDiffieHellmanGroup2, getDiffieHellman2, createDiffieHellman2, DiffieHellman2, createSign2, Sign2, createVerify2, Verify2, createECDH2, publicEncrypt2, privateEncrypt2, publicDecrypt2, privateDecrypt2, randomFill2, randomFillSync2, createCredentials2, constants2, DEFAULT_ENCODING = "buffer", getRandomValues = (array) => {
  return crypto.getRandomValues(array);
}, randomUUID = () => {
  return crypto.randomUUID();
}, hardcoded_curves, webcrypto, crypto_default;
var init_crypto = __esm(() => {
  __create2 = Object.create;
  ({ getPrototypeOf: __getProtoOf2, defineProperty: __defProp2, getOwnPropertyNames: __getOwnPropNames2 } = Object);
  __hasOwnProp2 = Object.prototype.hasOwnProperty;
  require_randombytes = __commonJS2((exports, module) => {
    module.exports = (init_crypto(), __toCommonJS(exports_crypto)).randomBytes;
  });
  require_create_hash = __commonJS2((exports, module) => {
    module.exports = (init_crypto(), __toCommonJS(exports_crypto)).createHash;
  });
  require_create_hmac = __commonJS2((exports, module) => {
    module.exports = (init_crypto(), __toCommonJS(exports_crypto)).createHmac;
  });
  require_algorithms = __commonJS2((exports, module) => {
    module.exports = { sha224WithRSAEncryption: { sign: "rsa", hash: "sha224", id: "302d300d06096086480165030402040500041c" }, "RSA-SHA224": { sign: "ecdsa/rsa", hash: "sha224", id: "302d300d06096086480165030402040500041c" }, sha256WithRSAEncryption: { sign: "rsa", hash: "sha256", id: "3031300d060960864801650304020105000420" }, "RSA-SHA256": { sign: "ecdsa/rsa", hash: "sha256", id: "3031300d060960864801650304020105000420" }, sha384WithRSAEncryption: { sign: "rsa", hash: "sha384", id: "3041300d060960864801650304020205000430" }, "RSA-SHA384": { sign: "ecdsa/rsa", hash: "sha384", id: "3041300d060960864801650304020205000430" }, sha512WithRSAEncryption: { sign: "rsa", hash: "sha512", id: "3051300d060960864801650304020305000440" }, "RSA-SHA512": { sign: "ecdsa/rsa", hash: "sha512", id: "3051300d060960864801650304020305000440" }, "RSA-SHA1": { sign: "rsa", hash: "sha1", id: "3021300906052b0e03021a05000414" }, "ecdsa-with-SHA1": { sign: "ecdsa", hash: "sha1", id: "" }, sha256: { sign: "ecdsa", hash: "sha256", id: "" }, sha224: { sign: "ecdsa", hash: "sha224", id: "" }, sha384: { sign: "ecdsa", hash: "sha384", id: "" }, sha512: { sign: "ecdsa", hash: "sha512", id: "" }, "DSA-SHA": { sign: "dsa", hash: "sha1", id: "" }, "DSA-SHA1": { sign: "dsa", hash: "sha1", id: "" }, DSA: { sign: "dsa", hash: "sha1", id: "" }, "DSA-WITH-SHA224": { sign: "dsa", hash: "sha224", id: "" }, "DSA-SHA224": { sign: "dsa", hash: "sha224", id: "" }, "DSA-WITH-SHA256": { sign: "dsa", hash: "sha256", id: "" }, "DSA-SHA256": { sign: "dsa", hash: "sha256", id: "" }, "DSA-WITH-SHA384": { sign: "dsa", hash: "sha384", id: "" }, "DSA-SHA384": { sign: "dsa", hash: "sha384", id: "" }, "DSA-WITH-SHA512": { sign: "dsa", hash: "sha512", id: "" }, "DSA-SHA512": { sign: "dsa", hash: "sha512", id: "" }, "DSA-RIPEMD160": { sign: "dsa", hash: "rmd160", id: "" }, ripemd160WithRSA: { sign: "rsa", hash: "rmd160", id: "3021300906052b2403020105000414" }, "RSA-RIPEMD160": { sign: "rsa", hash: "rmd160", id: "3021300906052b2403020105000414" }, md5WithRSAEncryption: { sign: "rsa", hash: "md5", id: "3020300c06082a864886f70d020505000410" }, "RSA-MD5": { sign: "rsa", hash: "md5", id: "3020300c06082a864886f70d020505000410" } };
  });
  require_precondition = __commonJS2((exports, module) => {
    var $isFinite = isFinite, MAX_ALLOC = Math.pow(2, 30) - 1;
    module.exports = function(iterations, keylen) {
      if (typeof iterations !== "number")
        throw TypeError("Iterations not a number");
      if (iterations < 0 || !$isFinite(iterations))
        throw TypeError("Bad iterations");
      if (typeof keylen !== "number")
        throw TypeError("Key length not a number");
      if (keylen < 0 || keylen > MAX_ALLOC || keylen !== keylen)
        throw TypeError("Bad key length");
    };
  });
  require_default_encoding = __commonJS2((exports, module) => {
    var defaultEncoding;
    if (globalThis.process && globalThis.process.browser)
      defaultEncoding = "utf-8";
    else if (globalThis.process && globalThis.process.version)
      pVersionMajor = parseInt(process.version.split(".")[0].slice(1), 10), defaultEncoding = pVersionMajor >= 6 ? "utf-8" : "binary";
    else
      defaultEncoding = "utf-8";
    var pVersionMajor;
    module.exports = defaultEncoding;
  });
  require_safe_buffer = __commonJS2((exports, module) => {
    /*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
    var buffer = (init_buffer(), __toCommonJS(exports_buffer)), Buffer22 = buffer.Buffer;
    function copyProps(src, dst) {
      for (var key in src)
        dst[key] = src[key];
    }
    if (Buffer22.from && Buffer22.alloc && Buffer22.allocUnsafe && Buffer22.allocUnsafeSlow)
      module.exports = buffer;
    else
      copyProps(buffer, exports), exports.Buffer = SafeBuffer;
    function SafeBuffer(arg, encodingOrOffset, length) {
      return Buffer22(arg, encodingOrOffset, length);
    }
    SafeBuffer.prototype = Object.create(Buffer22.prototype);
    copyProps(Buffer22, SafeBuffer);
    SafeBuffer.from = function(arg, encodingOrOffset, length) {
      if (typeof arg === "number")
        throw TypeError("Argument must not be a number");
      return Buffer22(arg, encodingOrOffset, length);
    };
    SafeBuffer.alloc = function(size, fill, encoding) {
      if (typeof size !== "number")
        throw TypeError("Argument must be a number");
      var buf = Buffer22(size);
      if (fill !== undefined)
        if (typeof encoding === "string")
          buf.fill(fill, encoding);
        else
          buf.fill(fill);
      else
        buf.fill(0);
      return buf;
    };
    SafeBuffer.allocUnsafe = function(size) {
      if (typeof size !== "number")
        throw TypeError("Argument must be a number");
      return Buffer22(size);
    };
    SafeBuffer.allocUnsafeSlow = function(size) {
      if (typeof size !== "number")
        throw TypeError("Argument must be a number");
      return buffer.SlowBuffer(size);
    };
  });
  require_isarray = __commonJS2((exports, module) => {
    var toString2 = {}.toString;
    module.exports = Array.isArray || function(arr) {
      return toString2.call(arr) == "[object Array]";
    };
  });
  require_type = __commonJS2((exports, module) => {
    module.exports = TypeError;
  });
  require_es_object_atoms = __commonJS2((exports, module) => {
    module.exports = Object;
  });
  require_es_errors = __commonJS2((exports, module) => {
    module.exports = Error;
  });
  require_eval = __commonJS2((exports, module) => {
    module.exports = EvalError;
  });
  require_range = __commonJS2((exports, module) => {
    module.exports = RangeError;
  });
  require_ref = __commonJS2((exports, module) => {
    module.exports = ReferenceError;
  });
  require_syntax = __commonJS2((exports, module) => {
    module.exports = SyntaxError;
  });
  require_uri = __commonJS2((exports, module) => {
    module.exports = URIError;
  });
  require_abs = __commonJS2((exports, module) => {
    module.exports = Math.abs;
  });
  require_floor = __commonJS2((exports, module) => {
    module.exports = Math.floor;
  });
  require_max = __commonJS2((exports, module) => {
    module.exports = Math.max;
  });
  require_min = __commonJS2((exports, module) => {
    module.exports = Math.min;
  });
  require_pow = __commonJS2((exports, module) => {
    module.exports = Math.pow;
  });
  require_round = __commonJS2((exports, module) => {
    module.exports = Math.round;
  });
  require_isNaN = __commonJS2((exports, module) => {
    module.exports = Number.isNaN || function(a2) {
      return a2 !== a2;
    };
  });
  require_sign = __commonJS2((exports, module) => {
    var $isNaN = require_isNaN();
    module.exports = function(number) {
      if ($isNaN(number) || number === 0)
        return number;
      return number < 0 ? -1 : 1;
    };
  });
  require_gOPD = __commonJS2((exports, module) => {
    module.exports = Object.getOwnPropertyDescriptor;
  });
  require_gopd = __commonJS2((exports, module) => {
    var $gOPD = require_gOPD();
    if ($gOPD)
      try {
        $gOPD([], "length");
      } catch (e2) {
        $gOPD = null;
      }
    module.exports = $gOPD;
  });
  require_es_define_property = __commonJS2((exports, module) => {
    var $defineProperty = Object.defineProperty || false;
    if ($defineProperty)
      try {
        $defineProperty({}, "a", { value: 1 });
      } catch (e2) {
        $defineProperty = false;
      }
    module.exports = $defineProperty;
  });
  require_shams = __commonJS2((exports, module) => {
    module.exports = function() {
      if (typeof Symbol !== "function" || typeof Object.getOwnPropertySymbols !== "function")
        return false;
      if (typeof Symbol.iterator === "symbol")
        return true;
      var obj = {}, sym = Symbol("test"), symObj = Object(sym);
      if (typeof sym === "string")
        return false;
      if (Object.prototype.toString.call(sym) !== "[object Symbol]")
        return false;
      if (Object.prototype.toString.call(symObj) !== "[object Symbol]")
        return false;
      var symVal = 42;
      obj[sym] = symVal;
      for (var _ in obj)
        return false;
      if (typeof Object.keys === "function" && Object.keys(obj).length !== 0)
        return false;
      if (typeof Object.getOwnPropertyNames === "function" && Object.getOwnPropertyNames(obj).length !== 0)
        return false;
      var syms = Object.getOwnPropertySymbols(obj);
      if (syms.length !== 1 || syms[0] !== sym)
        return false;
      if (!Object.prototype.propertyIsEnumerable.call(obj, sym))
        return false;
      if (typeof Object.getOwnPropertyDescriptor === "function") {
        var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
        if (descriptor.value !== symVal || descriptor.enumerable !== true)
          return false;
      }
      return true;
    };
  });
  require_has_symbols = __commonJS2((exports, module) => {
    var origSymbol = typeof Symbol < "u" && Symbol, hasSymbolSham = require_shams();
    module.exports = function() {
      if (typeof origSymbol !== "function")
        return false;
      if (typeof Symbol !== "function")
        return false;
      if (typeof origSymbol("foo") !== "symbol")
        return false;
      if (typeof Symbol("bar") !== "symbol")
        return false;
      return hasSymbolSham();
    };
  });
  require_Reflect_getPrototypeOf = __commonJS2((exports, module) => {
    module.exports = typeof Reflect < "u" && Reflect.getPrototypeOf || null;
  });
  require_Object_getPrototypeOf = __commonJS2((exports, module) => {
    var $Object = require_es_object_atoms();
    module.exports = $Object.getPrototypeOf || null;
  });
  require_implementation = __commonJS2((exports, module) => {
    var ERROR_MESSAGE = "Function.prototype.bind called on incompatible ", toStr = Object.prototype.toString, max = Math.max, funcType = "[object Function]", concatty = function(a2, b) {
      var arr = [];
      for (var i2 = 0;i2 < a2.length; i2 += 1)
        arr[i2] = a2[i2];
      for (var j = 0;j < b.length; j += 1)
        arr[j + a2.length] = b[j];
      return arr;
    }, slicy = function(arrLike, offset) {
      var arr = [];
      for (var i2 = offset || 0, j = 0;i2 < arrLike.length; i2 += 1, j += 1)
        arr[j] = arrLike[i2];
      return arr;
    }, joiny = function(arr, joiner) {
      var str = "";
      for (var i2 = 0;i2 < arr.length; i2 += 1)
        if (str += arr[i2], i2 + 1 < arr.length)
          str += joiner;
      return str;
    };
    module.exports = function(that) {
      var target = this;
      if (typeof target !== "function" || toStr.apply(target) !== funcType)
        throw TypeError(ERROR_MESSAGE + target);
      var args = slicy(arguments, 1), bound, binder = function() {
        if (this instanceof bound) {
          var result = target.apply(this, concatty(args, arguments));
          if (Object(result) === result)
            return result;
          return this;
        }
        return target.apply(that, concatty(args, arguments));
      }, boundLength = max(0, target.length - args.length), boundArgs = [];
      for (var i2 = 0;i2 < boundLength; i2++)
        boundArgs[i2] = "$" + i2;
      if (bound = Function("binder", "return function (" + joiny(boundArgs, ",") + "){ return binder.apply(this,arguments); }")(binder), target.prototype) {
        var Empty = function() {};
        Empty.prototype = target.prototype, bound.prototype = new Empty, Empty.prototype = null;
      }
      return bound;
    };
  });
  require_function_bind = __commonJS2((exports, module) => {
    var implementation = require_implementation();
    module.exports = Function.prototype.bind || implementation;
  });
  require_functionCall = __commonJS2((exports, module) => {
    module.exports = Function.prototype.call;
  });
  require_functionApply = __commonJS2((exports, module) => {
    module.exports = Function.prototype.apply;
  });
  require_reflectApply = __commonJS2((exports, module) => {
    module.exports = typeof Reflect < "u" && Reflect && Reflect.apply;
  });
  require_actualApply = __commonJS2((exports, module) => {
    var bind = require_function_bind(), $apply = require_functionApply(), $call = require_functionCall(), $reflectApply = require_reflectApply();
    module.exports = $reflectApply || bind.call($call, $apply);
  });
  require_call_bind_apply_helpers = __commonJS2((exports, module) => {
    var bind = require_function_bind(), $TypeError = require_type(), $call = require_functionCall(), $actualApply = require_actualApply();
    module.exports = function(args) {
      if (args.length < 1 || typeof args[0] !== "function")
        throw new $TypeError("a function is required");
      return $actualApply(bind, $call, args);
    };
  });
  require_get = __commonJS2((exports, module) => {
    var callBind = require_call_bind_apply_helpers(), gOPD = require_gopd(), hasProtoAccessor;
    try {
      hasProtoAccessor = [].__proto__ === Array.prototype;
    } catch (e2) {
      if (!e2 || typeof e2 !== "object" || !("code" in e2) || e2.code !== "ERR_PROTO_ACCESS")
        throw e2;
    }
    var desc = !!hasProtoAccessor && gOPD && gOPD(Object.prototype, "__proto__"), $Object = Object, $getPrototypeOf = $Object.getPrototypeOf;
    module.exports = desc && typeof desc.get === "function" ? callBind([desc.get]) : typeof $getPrototypeOf === "function" ? function(value) {
      return $getPrototypeOf(value == null ? value : $Object(value));
    } : false;
  });
  require_get_proto = __commonJS2((exports, module) => {
    var reflectGetProto = require_Reflect_getPrototypeOf(), originalGetProto = require_Object_getPrototypeOf(), getDunderProto = require_get();
    module.exports = reflectGetProto ? function(O) {
      return reflectGetProto(O);
    } : originalGetProto ? function(O) {
      if (!O || typeof O !== "object" && typeof O !== "function")
        throw TypeError("getProto: not an object");
      return originalGetProto(O);
    } : getDunderProto ? function(O) {
      return getDunderProto(O);
    } : null;
  });
  require_hasown = __commonJS2((exports, module) => {
    var call = Function.prototype.call, $hasOwn = Object.prototype.hasOwnProperty, bind = require_function_bind();
    module.exports = bind.call(call, $hasOwn);
  });
  require_get_intrinsic = __commonJS2((exports, module) => {
    var undefined2, $Object = require_es_object_atoms(), $Error = require_es_errors(), $EvalError = require_eval(), $RangeError = require_range(), $ReferenceError = require_ref(), $SyntaxError = require_syntax(), $TypeError = require_type(), $URIError = require_uri(), abs = require_abs(), floor = require_floor(), max = require_max(), min = require_min(), pow = require_pow(), round = require_round(), sign = require_sign(), $Function = Function, getEvalledConstructor = function(expressionSyntax) {
      try {
        return $Function('"use strict"; return (' + expressionSyntax + ").constructor;")();
      } catch (e2) {}
    }, $gOPD = require_gopd(), $defineProperty = require_es_define_property(), throwTypeError = function() {
      throw new $TypeError;
    }, ThrowTypeError = $gOPD ? function() {
      try {
        return arguments.callee, throwTypeError;
      } catch (calleeThrows) {
        try {
          return $gOPD(arguments, "callee").get;
        } catch (gOPDthrows) {
          return throwTypeError;
        }
      }
    }() : throwTypeError, hasSymbols = require_has_symbols()(), getProto = require_get_proto(), $ObjectGPO = require_Object_getPrototypeOf(), $ReflectGPO = require_Reflect_getPrototypeOf(), $apply = require_functionApply(), $call = require_functionCall(), needsEval = {}, TypedArray = typeof Uint8Array > "u" || !getProto ? undefined2 : getProto(Uint8Array), INTRINSICS = { __proto__: null, "%AggregateError%": typeof AggregateError > "u" ? undefined2 : AggregateError, "%Array%": Array, "%ArrayBuffer%": typeof ArrayBuffer > "u" ? undefined2 : ArrayBuffer, "%ArrayIteratorPrototype%": hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined2, "%AsyncFromSyncIteratorPrototype%": undefined2, "%AsyncFunction%": needsEval, "%AsyncGenerator%": needsEval, "%AsyncGeneratorFunction%": needsEval, "%AsyncIteratorPrototype%": needsEval, "%Atomics%": typeof Atomics > "u" ? undefined2 : Atomics, "%BigInt%": typeof BigInt > "u" ? undefined2 : BigInt, "%BigInt64Array%": typeof BigInt64Array > "u" ? undefined2 : BigInt64Array, "%BigUint64Array%": typeof BigUint64Array > "u" ? undefined2 : BigUint64Array, "%Boolean%": Boolean, "%DataView%": typeof DataView > "u" ? undefined2 : DataView, "%Date%": Date, "%decodeURI%": decodeURI, "%decodeURIComponent%": decodeURIComponent, "%encodeURI%": encodeURI, "%encodeURIComponent%": encodeURIComponent, "%Error%": $Error, "%eval%": eval, "%EvalError%": $EvalError, "%Float16Array%": typeof Float16Array > "u" ? undefined2 : Float16Array, "%Float32Array%": typeof Float32Array > "u" ? undefined2 : Float32Array, "%Float64Array%": typeof Float64Array > "u" ? undefined2 : Float64Array, "%FinalizationRegistry%": typeof FinalizationRegistry > "u" ? undefined2 : FinalizationRegistry, "%Function%": $Function, "%GeneratorFunction%": needsEval, "%Int8Array%": typeof Int8Array > "u" ? undefined2 : Int8Array, "%Int16Array%": typeof Int16Array > "u" ? undefined2 : Int16Array, "%Int32Array%": typeof Int32Array > "u" ? undefined2 : Int32Array, "%isFinite%": isFinite, "%isNaN%": isNaN, "%IteratorPrototype%": hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined2, "%JSON%": typeof JSON === "object" ? JSON : undefined2, "%Map%": typeof Map > "u" ? undefined2 : Map, "%MapIteratorPrototype%": typeof Map > "u" || !hasSymbols || !getProto ? undefined2 : getProto(new Map()[Symbol.iterator]()), "%Math%": Math, "%Number%": Number, "%Object%": $Object, "%Object.getOwnPropertyDescriptor%": $gOPD, "%parseFloat%": parseFloat, "%parseInt%": parseInt, "%Promise%": typeof Promise > "u" ? undefined2 : Promise, "%Proxy%": typeof Proxy > "u" ? undefined2 : Proxy, "%RangeError%": $RangeError, "%ReferenceError%": $ReferenceError, "%Reflect%": typeof Reflect > "u" ? undefined2 : Reflect, "%RegExp%": RegExp, "%Set%": typeof Set > "u" ? undefined2 : Set, "%SetIteratorPrototype%": typeof Set > "u" || !hasSymbols || !getProto ? undefined2 : getProto(new Set()[Symbol.iterator]()), "%SharedArrayBuffer%": typeof SharedArrayBuffer > "u" ? undefined2 : SharedArrayBuffer, "%String%": String, "%StringIteratorPrototype%": hasSymbols && getProto ? getProto(""[Symbol.iterator]()) : undefined2, "%Symbol%": hasSymbols ? Symbol : undefined2, "%SyntaxError%": $SyntaxError, "%ThrowTypeError%": ThrowTypeError, "%TypedArray%": TypedArray, "%TypeError%": $TypeError, "%Uint8Array%": typeof Uint8Array > "u" ? undefined2 : Uint8Array, "%Uint8ClampedArray%": typeof Uint8ClampedArray > "u" ? undefined2 : Uint8ClampedArray, "%Uint16Array%": typeof Uint16Array > "u" ? undefined2 : Uint16Array, "%Uint32Array%": typeof Uint32Array > "u" ? undefined2 : Uint32Array, "%URIError%": $URIError, "%WeakMap%": typeof WeakMap > "u" ? undefined2 : WeakMap, "%WeakRef%": typeof WeakRef > "u" ? undefined2 : WeakRef, "%WeakSet%": typeof WeakSet > "u" ? undefined2 : WeakSet, "%Function.prototype.call%": $call, "%Function.prototype.apply%": $apply, "%Object.defineProperty%": $defineProperty, "%Object.getPrototypeOf%": $ObjectGPO, "%Math.abs%": abs, "%Math.floor%": floor, "%Math.max%": max, "%Math.min%": min, "%Math.pow%": pow, "%Math.round%": round, "%Math.sign%": sign, "%Reflect.getPrototypeOf%": $ReflectGPO };
    if (getProto)
      try {
        null.error;
      } catch (e2) {
        errorProto = getProto(getProto(e2)), INTRINSICS["%Error.prototype%"] = errorProto;
      }
    var errorProto, doEval = function doEval2(name) {
      var value;
      if (name === "%AsyncFunction%")
        value = getEvalledConstructor("async function () {}");
      else if (name === "%GeneratorFunction%")
        value = getEvalledConstructor("function* () {}");
      else if (name === "%AsyncGeneratorFunction%")
        value = getEvalledConstructor("async function* () {}");
      else if (name === "%AsyncGenerator%") {
        var fn = doEval2("%AsyncGeneratorFunction%");
        if (fn)
          value = fn.prototype;
      } else if (name === "%AsyncIteratorPrototype%") {
        var gen = doEval2("%AsyncGenerator%");
        if (gen && getProto)
          value = getProto(gen.prototype);
      }
      return INTRINSICS[name] = value, value;
    }, LEGACY_ALIASES = { __proto__: null, "%ArrayBufferPrototype%": ["ArrayBuffer", "prototype"], "%ArrayPrototype%": ["Array", "prototype"], "%ArrayProto_entries%": ["Array", "prototype", "entries"], "%ArrayProto_forEach%": ["Array", "prototype", "forEach"], "%ArrayProto_keys%": ["Array", "prototype", "keys"], "%ArrayProto_values%": ["Array", "prototype", "values"], "%AsyncFunctionPrototype%": ["AsyncFunction", "prototype"], "%AsyncGenerator%": ["AsyncGeneratorFunction", "prototype"], "%AsyncGeneratorPrototype%": ["AsyncGeneratorFunction", "prototype", "prototype"], "%BooleanPrototype%": ["Boolean", "prototype"], "%DataViewPrototype%": ["DataView", "prototype"], "%DatePrototype%": ["Date", "prototype"], "%ErrorPrototype%": ["Error", "prototype"], "%EvalErrorPrototype%": ["EvalError", "prototype"], "%Float32ArrayPrototype%": ["Float32Array", "prototype"], "%Float64ArrayPrototype%": ["Float64Array", "prototype"], "%FunctionPrototype%": ["Function", "prototype"], "%Generator%": ["GeneratorFunction", "prototype"], "%GeneratorPrototype%": ["GeneratorFunction", "prototype", "prototype"], "%Int8ArrayPrototype%": ["Int8Array", "prototype"], "%Int16ArrayPrototype%": ["Int16Array", "prototype"], "%Int32ArrayPrototype%": ["Int32Array", "prototype"], "%JSONParse%": ["JSON", "parse"], "%JSONStringify%": ["JSON", "stringify"], "%MapPrototype%": ["Map", "prototype"], "%NumberPrototype%": ["Number", "prototype"], "%ObjectPrototype%": ["Object", "prototype"], "%ObjProto_toString%": ["Object", "prototype", "toString"], "%ObjProto_valueOf%": ["Object", "prototype", "valueOf"], "%PromisePrototype%": ["Promise", "prototype"], "%PromiseProto_then%": ["Promise", "prototype", "then"], "%Promise_all%": ["Promise", "all"], "%Promise_reject%": ["Promise", "reject"], "%Promise_resolve%": ["Promise", "resolve"], "%RangeErrorPrototype%": ["RangeError", "prototype"], "%ReferenceErrorPrototype%": ["ReferenceError", "prototype"], "%RegExpPrototype%": ["RegExp", "prototype"], "%SetPrototype%": ["Set", "prototype"], "%SharedArrayBufferPrototype%": ["SharedArrayBuffer", "prototype"], "%StringPrototype%": ["String", "prototype"], "%SymbolPrototype%": ["Symbol", "prototype"], "%SyntaxErrorPrototype%": ["SyntaxError", "prototype"], "%TypedArrayPrototype%": ["TypedArray", "prototype"], "%TypeErrorPrototype%": ["TypeError", "prototype"], "%Uint8ArrayPrototype%": ["Uint8Array", "prototype"], "%Uint8ClampedArrayPrototype%": ["Uint8ClampedArray", "prototype"], "%Uint16ArrayPrototype%": ["Uint16Array", "prototype"], "%Uint32ArrayPrototype%": ["Uint32Array", "prototype"], "%URIErrorPrototype%": ["URIError", "prototype"], "%WeakMapPrototype%": ["WeakMap", "prototype"], "%WeakSetPrototype%": ["WeakSet", "prototype"] }, bind = require_function_bind(), hasOwn = require_hasown(), $concat = bind.call($call, Array.prototype.concat), $spliceApply = bind.call($apply, Array.prototype.splice), $replace = bind.call($call, String.prototype.replace), $strSlice = bind.call($call, String.prototype.slice), $exec = bind.call($call, RegExp.prototype.exec), rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g, reEscapeChar = /\\(\\)?/g, stringToPath = function(string) {
      var first = $strSlice(string, 0, 1), last = $strSlice(string, -1);
      if (first === "%" && last !== "%")
        throw new $SyntaxError("invalid intrinsic syntax, expected closing `%`");
      else if (last === "%" && first !== "%")
        throw new $SyntaxError("invalid intrinsic syntax, expected opening `%`");
      var result = [];
      return $replace(string, rePropName, function(match, number, quote, subString) {
        result[result.length] = quote ? $replace(subString, reEscapeChar, "$1") : number || match;
      }), result;
    }, getBaseIntrinsic = function(name, allowMissing) {
      var intrinsicName = name, alias;
      if (hasOwn(LEGACY_ALIASES, intrinsicName))
        alias = LEGACY_ALIASES[intrinsicName], intrinsicName = "%" + alias[0] + "%";
      if (hasOwn(INTRINSICS, intrinsicName)) {
        var value = INTRINSICS[intrinsicName];
        if (value === needsEval)
          value = doEval(intrinsicName);
        if (typeof value > "u" && !allowMissing)
          throw new $TypeError("intrinsic " + name + " exists, but is not available. Please file an issue!");
        return { alias, name: intrinsicName, value };
      }
      throw new $SyntaxError("intrinsic " + name + " does not exist!");
    };
    module.exports = function(name, allowMissing) {
      if (typeof name !== "string" || name.length === 0)
        throw new $TypeError("intrinsic name must be a non-empty string");
      if (arguments.length > 1 && typeof allowMissing !== "boolean")
        throw new $TypeError('"allowMissing" argument must be a boolean');
      if ($exec(/^%?[^%]*%?$/, name) === null)
        throw new $SyntaxError("`%` may not be present anywhere but at the beginning and end of the intrinsic name");
      var parts = stringToPath(name), intrinsicBaseName = parts.length > 0 ? parts[0] : "", intrinsic = getBaseIntrinsic("%" + intrinsicBaseName + "%", allowMissing), intrinsicRealName = intrinsic.name, value = intrinsic.value, skipFurtherCaching = false, alias = intrinsic.alias;
      if (alias)
        intrinsicBaseName = alias[0], $spliceApply(parts, $concat([0, 1], alias));
      for (var i2 = 1, isOwn = true;i2 < parts.length; i2 += 1) {
        var part = parts[i2], first = $strSlice(part, 0, 1), last = $strSlice(part, -1);
        if ((first === '"' || first === "'" || first === "`" || (last === '"' || last === "'" || last === "`")) && first !== last)
          throw new $SyntaxError("property names with quotes must have matching quotes");
        if (part === "constructor" || !isOwn)
          skipFurtherCaching = true;
        if (intrinsicBaseName += "." + part, intrinsicRealName = "%" + intrinsicBaseName + "%", hasOwn(INTRINSICS, intrinsicRealName))
          value = INTRINSICS[intrinsicRealName];
        else if (value != null) {
          if (!(part in value)) {
            if (!allowMissing)
              throw new $TypeError("base intrinsic for " + name + " exists, but the property is not available.");
            return;
          }
          if ($gOPD && i2 + 1 >= parts.length) {
            var desc = $gOPD(value, part);
            if (isOwn = !!desc, isOwn && "get" in desc && !("originalValue" in desc.get))
              value = desc.get;
            else
              value = value[part];
          } else
            isOwn = hasOwn(value, part), value = value[part];
          if (isOwn && !skipFurtherCaching)
            INTRINSICS[intrinsicRealName] = value;
        }
      }
      return value;
    };
  });
  require_call_bound = __commonJS2((exports, module) => {
    var GetIntrinsic = require_get_intrinsic(), callBindBasic = require_call_bind_apply_helpers(), $indexOf = callBindBasic([GetIntrinsic("%String.prototype.indexOf%")]);
    module.exports = function(name, allowMissing) {
      var intrinsic = GetIntrinsic(name, !!allowMissing);
      if (typeof intrinsic === "function" && $indexOf(name, ".prototype.") > -1)
        return callBindBasic([intrinsic]);
      return intrinsic;
    };
  });
  require_is_callable = __commonJS2((exports, module) => {
    var fnToStr = Function.prototype.toString, reflectApply = typeof Reflect === "object" && Reflect !== null && Reflect.apply, badArrayLike, isCallableMarker;
    if (typeof reflectApply === "function" && typeof Object.defineProperty === "function")
      try {
        badArrayLike = Object.defineProperty({}, "length", { get: function() {
          throw isCallableMarker;
        } }), isCallableMarker = {}, reflectApply(function() {
          throw 42;
        }, null, badArrayLike);
      } catch (_) {
        if (_ !== isCallableMarker)
          reflectApply = null;
      }
    else
      reflectApply = null;
    var constructorRegex = /^\s*class\b/, isES6ClassFn = function(value) {
      try {
        var fnStr = fnToStr.call(value);
        return constructorRegex.test(fnStr);
      } catch (e2) {
        return false;
      }
    }, tryFunctionObject = function(value) {
      try {
        if (isES6ClassFn(value))
          return false;
        return fnToStr.call(value), true;
      } catch (e2) {
        return false;
      }
    }, toStr = Object.prototype.toString, objectClass = "[object Object]", fnClass = "[object Function]", genClass = "[object GeneratorFunction]", ddaClass = "[object HTMLAllCollection]", ddaClass2 = "[object HTML document.all class]", ddaClass3 = "[object HTMLCollection]", hasToStringTag = typeof Symbol === "function" && !!Symbol.toStringTag, isIE68 = !(0 in [,]), isDDA = function() {
      return false;
    };
    if (typeof document === "object") {
      if (all = document.all, toStr.call(all) === toStr.call(document.all))
        isDDA = function(value) {
          if ((isIE68 || !value) && (typeof value > "u" || typeof value === "object"))
            try {
              var str = toStr.call(value);
              return (str === ddaClass || str === ddaClass2 || str === ddaClass3 || str === objectClass) && value("") == null;
            } catch (e2) {}
          return false;
        };
    }
    var all;
    module.exports = reflectApply ? function(value) {
      if (isDDA(value))
        return true;
      if (!value)
        return false;
      if (typeof value !== "function" && typeof value !== "object")
        return false;
      try {
        reflectApply(value, null, badArrayLike);
      } catch (e2) {
        if (e2 !== isCallableMarker)
          return false;
      }
      return !isES6ClassFn(value) && tryFunctionObject(value);
    } : function(value) {
      if (isDDA(value))
        return true;
      if (!value)
        return false;
      if (typeof value !== "function" && typeof value !== "object")
        return false;
      if (hasToStringTag)
        return tryFunctionObject(value);
      if (isES6ClassFn(value))
        return false;
      var strClass = toStr.call(value);
      if (strClass !== fnClass && strClass !== genClass && !/^\[object HTML/.test(strClass))
        return false;
      return tryFunctionObject(value);
    };
  });
  require_for_each = __commonJS2((exports, module) => {
    var isCallable = require_is_callable(), toStr = Object.prototype.toString, hasOwnProperty2 = Object.prototype.hasOwnProperty, forEachArray = function(array, iterator, receiver) {
      for (var i2 = 0, len2 = array.length;i2 < len2; i2++)
        if (hasOwnProperty2.call(array, i2))
          if (receiver == null)
            iterator(array[i2], i2, array);
          else
            iterator.call(receiver, array[i2], i2, array);
    }, forEachString = function(string, iterator, receiver) {
      for (var i2 = 0, len2 = string.length;i2 < len2; i2++)
        if (receiver == null)
          iterator(string.charAt(i2), i2, string);
        else
          iterator.call(receiver, string.charAt(i2), i2, string);
    }, forEachObject = function(object, iterator, receiver) {
      for (var k in object)
        if (hasOwnProperty2.call(object, k))
          if (receiver == null)
            iterator(object[k], k, object);
          else
            iterator.call(receiver, object[k], k, object);
    };
    function isArray2(x) {
      return toStr.call(x) === "[object Array]";
    }
    module.exports = function(list, iterator, thisArg) {
      if (!isCallable(iterator))
        throw TypeError("iterator must be a function");
      var receiver;
      if (arguments.length >= 3)
        receiver = thisArg;
      if (isArray2(list))
        forEachArray(list, iterator, receiver);
      else if (typeof list === "string")
        forEachString(list, iterator, receiver);
      else
        forEachObject(list, iterator, receiver);
    };
  });
  require_possible_typed_array_names = __commonJS2((exports, module) => {
    module.exports = ["Float16Array", "Float32Array", "Float64Array", "Int8Array", "Int16Array", "Int32Array", "Uint8Array", "Uint8ClampedArray", "Uint16Array", "Uint32Array", "BigInt64Array", "BigUint64Array"];
  });
  require_available_typed_arrays = __commonJS2((exports, module) => {
    var possibleNames = require_possible_typed_array_names(), g = typeof globalThis > "u" ? globalThis : globalThis;
    module.exports = function() {
      var out = [];
      for (var i2 = 0;i2 < possibleNames.length; i2++)
        if (typeof g[possibleNames[i2]] === "function")
          out[out.length] = possibleNames[i2];
      return out;
    };
  });
  require_define_data_property = __commonJS2((exports, module) => {
    var $defineProperty = require_es_define_property(), $SyntaxError = require_syntax(), $TypeError = require_type(), gopd = require_gopd();
    module.exports = function(obj, property, value) {
      if (!obj || typeof obj !== "object" && typeof obj !== "function")
        throw new $TypeError("`obj` must be an object or a function`");
      if (typeof property !== "string" && typeof property !== "symbol")
        throw new $TypeError("`property` must be a string or a symbol`");
      if (arguments.length > 3 && typeof arguments[3] !== "boolean" && arguments[3] !== null)
        throw new $TypeError("`nonEnumerable`, if provided, must be a boolean or null");
      if (arguments.length > 4 && typeof arguments[4] !== "boolean" && arguments[4] !== null)
        throw new $TypeError("`nonWritable`, if provided, must be a boolean or null");
      if (arguments.length > 5 && typeof arguments[5] !== "boolean" && arguments[5] !== null)
        throw new $TypeError("`nonConfigurable`, if provided, must be a boolean or null");
      if (arguments.length > 6 && typeof arguments[6] !== "boolean")
        throw new $TypeError("`loose`, if provided, must be a boolean");
      var nonEnumerable = arguments.length > 3 ? arguments[3] : null, nonWritable = arguments.length > 4 ? arguments[4] : null, nonConfigurable = arguments.length > 5 ? arguments[5] : null, loose = arguments.length > 6 ? arguments[6] : false, desc = !!gopd && gopd(obj, property);
      if ($defineProperty)
        $defineProperty(obj, property, { configurable: nonConfigurable === null && desc ? desc.configurable : !nonConfigurable, enumerable: nonEnumerable === null && desc ? desc.enumerable : !nonEnumerable, value, writable: nonWritable === null && desc ? desc.writable : !nonWritable });
      else if (loose || !nonEnumerable && !nonWritable && !nonConfigurable)
        obj[property] = value;
      else
        throw new $SyntaxError("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.");
    };
  });
  require_has_property_descriptors = __commonJS2((exports, module) => {
    var $defineProperty = require_es_define_property(), hasPropertyDescriptors = function() {
      return !!$defineProperty;
    };
    hasPropertyDescriptors.hasArrayLengthDefineBug = function() {
      if (!$defineProperty)
        return null;
      try {
        return $defineProperty([], "length", { value: 1 }).length !== 1;
      } catch (e2) {
        return true;
      }
    };
    module.exports = hasPropertyDescriptors;
  });
  require_set_function_length = __commonJS2((exports, module) => {
    var GetIntrinsic = require_get_intrinsic(), define2 = require_define_data_property(), hasDescriptors = require_has_property_descriptors()(), gOPD = require_gopd(), $TypeError = require_type(), $floor = GetIntrinsic("%Math.floor%");
    module.exports = function(fn, length) {
      if (typeof fn !== "function")
        throw new $TypeError("`fn` is not a function");
      if (typeof length !== "number" || length < 0 || length > 4294967295 || $floor(length) !== length)
        throw new $TypeError("`length` must be a positive 32-bit integer");
      var loose = arguments.length > 2 && !!arguments[2], functionLengthIsConfigurable = true, functionLengthIsWritable = true;
      if ("length" in fn && gOPD) {
        var desc = gOPD(fn, "length");
        if (desc && !desc.configurable)
          functionLengthIsConfigurable = false;
        if (desc && !desc.writable)
          functionLengthIsWritable = false;
      }
      if (functionLengthIsConfigurable || functionLengthIsWritable || !loose)
        if (hasDescriptors)
          define2(fn, "length", length, true, true);
        else
          define2(fn, "length", length);
      return fn;
    };
  });
  require_applyBind = __commonJS2((exports, module) => {
    var bind = require_function_bind(), $apply = require_functionApply(), actualApply = require_actualApply();
    module.exports = function() {
      return actualApply(bind, $apply, arguments);
    };
  });
  require_call_bind = __commonJS2((exports, module) => {
    var setFunctionLength = require_set_function_length(), $defineProperty = require_es_define_property(), callBindBasic = require_call_bind_apply_helpers(), applyBind = require_applyBind();
    module.exports = function(originalFunction) {
      var func = callBindBasic(arguments), adjustedLength = originalFunction.length - (arguments.length - 1);
      return setFunctionLength(func, 1 + (adjustedLength > 0 ? adjustedLength : 0), true);
    };
    if ($defineProperty)
      $defineProperty(module.exports, "apply", { value: applyBind });
    else
      module.exports.apply = applyBind;
  });
  require_shams2 = __commonJS2((exports, module) => {
    var hasSymbols = require_shams();
    module.exports = function() {
      return hasSymbols() && !!Symbol.toStringTag;
    };
  });
  require_which_typed_array = __commonJS2((exports, module) => {
    var forEach = require_for_each(), availableTypedArrays = require_available_typed_arrays(), callBind = require_call_bind(), callBound = require_call_bound(), gOPD = require_gopd(), getProto = require_get_proto(), $toString = callBound("Object.prototype.toString"), hasToStringTag = require_shams2()(), g = typeof globalThis > "u" ? globalThis : globalThis, typedArrays2 = availableTypedArrays(), $slice = callBound("String.prototype.slice"), $indexOf = callBound("Array.prototype.indexOf", true) || function(array, value) {
      for (var i2 = 0;i2 < array.length; i2 += 1)
        if (array[i2] === value)
          return i2;
      return -1;
    }, cache = { __proto__: null };
    if (hasToStringTag && gOPD && getProto)
      forEach(typedArrays2, function(typedArray) {
        var arr = new g[typedArray];
        if (Symbol.toStringTag in arr && getProto) {
          var proto = getProto(arr), descriptor = gOPD(proto, Symbol.toStringTag);
          if (!descriptor && proto) {
            var superProto = getProto(proto);
            descriptor = gOPD(superProto, Symbol.toStringTag);
          }
          cache["$" + typedArray] = callBind(descriptor.get);
        }
      });
    else
      forEach(typedArrays2, function(typedArray) {
        var arr = new g[typedArray], fn = arr.slice || arr.set;
        if (fn)
          cache["$" + typedArray] = callBind(fn);
      });
    var tryTypedArrays = function(value) {
      var found = false;
      return forEach(cache, function(getter, typedArray) {
        if (!found)
          try {
            if ("$" + getter(value) === typedArray)
              found = $slice(typedArray, 1);
          } catch (e2) {}
      }), found;
    }, trySlices = function(value) {
      var found = false;
      return forEach(cache, function(getter, name) {
        if (!found)
          try {
            getter(value), found = $slice(name, 1);
          } catch (e2) {}
      }), found;
    };
    module.exports = function(value) {
      if (!value || typeof value !== "object")
        return false;
      if (!hasToStringTag) {
        var tag = $slice($toString(value), 8, -1);
        if ($indexOf(typedArrays2, tag) > -1)
          return tag;
        if (tag !== "Object")
          return false;
        return trySlices(value);
      }
      if (!gOPD)
        return null;
      return tryTypedArrays(value);
    };
  });
  require_is_typed_array = __commonJS2((exports, module) => {
    var whichTypedArray = require_which_typed_array();
    module.exports = function(value) {
      return !!whichTypedArray(value);
    };
  });
  require_typed_array_buffer = __commonJS2((exports, module) => {
    var $TypeError = require_type(), callBound = require_call_bound(), $typedArrayBuffer = callBound("TypedArray.prototype.buffer", true), isTypedArray = require_is_typed_array();
    module.exports = $typedArrayBuffer || function(x) {
      if (!isTypedArray(x))
        throw new $TypeError("Not a Typed Array");
      return x.buffer;
    };
  });
  require_to_buffer = __commonJS2((exports, module) => {
    var Buffer22 = require_safe_buffer().Buffer, isArray2 = require_isarray(), typedArrayBuffer = require_typed_array_buffer(), isView = ArrayBuffer.isView || function(obj) {
      try {
        return typedArrayBuffer(obj), true;
      } catch (e2) {
        return false;
      }
    }, useUint8Array = typeof Uint8Array < "u", useArrayBuffer = typeof ArrayBuffer < "u" && typeof Uint8Array < "u", useFromArrayBuffer = useArrayBuffer && (Buffer22.prototype instanceof Uint8Array || Buffer22.TYPED_ARRAY_SUPPORT);
    module.exports = function(data, encoding) {
      if (Buffer22.isBuffer(data)) {
        if (data.constructor && !("isBuffer" in data))
          return Buffer22.from(data);
        return data;
      }
      if (typeof data === "string")
        return Buffer22.from(data, encoding);
      if (useArrayBuffer && isView(data)) {
        if (data.byteLength === 0)
          return Buffer22.alloc(0);
        if (useFromArrayBuffer) {
          var res = Buffer22.from(data.buffer, data.byteOffset, data.byteLength);
          if (res.byteLength === data.byteLength)
            return res;
        }
        var uint83 = data instanceof Uint8Array ? data : new Uint8Array(data.buffer, data.byteOffset, data.byteLength), result = Buffer22.from(uint83);
        if (result.length === data.byteLength)
          return result;
      }
      if (useUint8Array && data instanceof Uint8Array)
        return Buffer22.from(data);
      var isArr = isArray2(data);
      if (isArr)
        for (var i2 = 0;i2 < data.length; i2 += 1) {
          var x = data[i2];
          if (typeof x !== "number" || x < 0 || x > 255 || ~~x !== x)
            throw RangeError("Array items must be numbers in the range 0-255.");
        }
      if (isArr || Buffer22.isBuffer(data) && data.constructor && typeof data.constructor.isBuffer === "function" && data.constructor.isBuffer(data))
        return Buffer22.from(data);
      throw TypeError('The "data" argument must be a string, an Array, a Buffer, a Uint8Array, or a DataView.');
    };
  });
  require_to_buffer2 = __commonJS2((exports, module) => {
    var Buffer22 = require_safe_buffer().Buffer, toBuffer = require_to_buffer(), useUint8Array = typeof Uint8Array < "u", useArrayBuffer = useUint8Array && typeof ArrayBuffer < "u", isView = useArrayBuffer && ArrayBuffer.isView;
    module.exports = function(thing, encoding, name) {
      if (typeof thing === "string" || Buffer22.isBuffer(thing) || useUint8Array && thing instanceof Uint8Array || isView && isView(thing))
        return toBuffer(thing, encoding);
      throw TypeError(name + " must be a string, a Buffer, a Uint8Array, or a DataView");
    };
  });
  require_sync = __commonJS2((exports, module) => {
    var sizes = { __proto__: null, md5: 16, sha1: 20, sha224: 28, sha256: 32, sha384: 48, sha512: 64, "sha512-256": 32, rmd160: 20, ripemd160: 20 }, mapping = { __proto__: null, "sha-1": "sha1", "sha-224": "sha224", "sha-256": "sha256", "sha-384": "sha384", "sha-512": "sha512", "ripemd-160": "ripemd160" }, createHmac = require_create_hmac(), Buffer22 = require_safe_buffer().Buffer, checkParameters = require_precondition(), defaultEncoding = require_default_encoding(), toBuffer = require_to_buffer2();
    function pbkdf2(password, salt, iterations, keylen, digest) {
      checkParameters(iterations, keylen), password = toBuffer(password, defaultEncoding, "Password"), salt = toBuffer(salt, defaultEncoding, "Salt");
      var lowerDigest = (digest || "sha1").toLowerCase(), mappedDigest = mapping[lowerDigest] || lowerDigest, size = sizes[mappedDigest];
      if (typeof size !== "number" || !size)
        throw TypeError("Digest algorithm not supported: " + digest);
      var DK = Buffer22.allocUnsafe(keylen), block1 = Buffer22.allocUnsafe(salt.length + 4);
      salt.copy(block1, 0, 0, salt.length);
      var destPos = 0, hLen = size, l2 = Math.ceil(keylen / hLen);
      for (var i2 = 1;i2 <= l2; i2++) {
        block1.writeUInt32BE(i2, salt.length);
        var T = createHmac(mappedDigest, password).update(block1).digest(), U = T;
        for (var j = 1;j < iterations; j++) {
          U = createHmac(mappedDigest, password).update(U).digest();
          for (var k = 0;k < hLen; k++)
            T[k] ^= U[k];
        }
        T.copy(DK, destPos), destPos += hLen;
      }
      return DK;
    }
    module.exports = pbkdf2;
  });
  require_async = __commonJS2((exports, module) => {
    var Buffer22 = require_safe_buffer().Buffer, checkParameters = require_precondition(), defaultEncoding = require_default_encoding(), sync = require_sync(), toBuffer = require_to_buffer2(), ZERO_BUF, subtle = globalThis.crypto && globalThis.crypto.subtle, toBrowser = { sha: "SHA-1", "sha-1": "SHA-1", sha1: "SHA-1", sha256: "SHA-256", "sha-256": "SHA-256", sha384: "SHA-384", "sha-384": "SHA-384", "sha-512": "SHA-512", sha512: "SHA-512" }, checks = [], nextTick;
    function getNextTick() {
      if (nextTick)
        return nextTick;
      if (globalThis.process && globalThis.process.nextTick)
        nextTick = globalThis.process.nextTick;
      else if (globalThis.queueMicrotask)
        nextTick = globalThis.queueMicrotask;
      else if (globalThis.setImmediate)
        nextTick = globalThis.setImmediate;
      else
        nextTick = globalThis.setTimeout;
      return nextTick;
    }
    function browserPbkdf2(password, salt, iterations, length, algo) {
      return subtle.importKey("raw", password, { name: "PBKDF2" }, false, ["deriveBits"]).then(function(key) {
        return subtle.deriveBits({ name: "PBKDF2", salt, iterations, hash: { name: algo } }, key, length << 3);
      }).then(function(res) {
        return Buffer22.from(res);
      });
    }
    function checkNative(algo) {
      if (globalThis.process && !globalThis.process.browser)
        return Promise.resolve(false);
      if (!subtle || !subtle.importKey || !subtle.deriveBits)
        return Promise.resolve(false);
      if (checks[algo] !== undefined)
        return checks[algo];
      ZERO_BUF = ZERO_BUF || Buffer22.alloc(8);
      var prom = browserPbkdf2(ZERO_BUF, ZERO_BUF, 10, 128, algo).then(function() {
        return true;
      }, function() {
        return false;
      });
      return checks[algo] = prom, prom;
    }
    function resolvePromise(promise, callback) {
      promise.then(function(out) {
        getNextTick()(function() {
          callback(null, out);
        });
      }, function(e2) {
        getNextTick()(function() {
          callback(e2);
        });
      });
    }
    module.exports = function(password, salt, iterations, keylen, digest, callback) {
      if (typeof digest === "function")
        callback = digest, digest = undefined;
      if (checkParameters(iterations, keylen), password = toBuffer(password, defaultEncoding, "Password"), salt = toBuffer(salt, defaultEncoding, "Salt"), typeof callback !== "function")
        throw Error("No callback provided to pbkdf2");
      digest = digest || "sha1";
      var algo = toBrowser[digest.toLowerCase()];
      if (!algo || typeof globalThis.Promise !== "function") {
        getNextTick()(function() {
          var out;
          try {
            out = sync(password, salt, iterations, keylen, digest);
          } catch (e2) {
            callback(e2);
            return;
          }
          callback(null, out);
        });
        return;
      }
      resolvePromise(checkNative(algo).then(function(resp) {
        if (resp)
          return browserPbkdf2(password, salt, iterations, keylen, algo);
        return sync(password, salt, iterations, keylen, digest);
      }), callback);
    };
  });
  require_pbkdf2 = __commonJS2((exports) => {
    var nativeImpl = (init_crypto(), __toCommonJS(exports_crypto)), checkParameters = require_precondition(), defaultEncoding = require_default_encoding(), toBuffer = require_to_buffer2();
    function nativePBKDF2(password, salt, iterations, keylen, digest, callback) {
      if (checkParameters(iterations, keylen), password = toBuffer(password, defaultEncoding, "Password"), salt = toBuffer(salt, defaultEncoding, "Salt"), typeof digest === "function")
        callback = digest, digest = "sha1";
      if (typeof callback !== "function")
        throw Error("No callback provided to pbkdf2");
      return nativeImpl.pbkdf2(password, salt, iterations, keylen, digest, callback);
    }
    function nativePBKDF2Sync(password, salt, iterations, keylen, digest) {
      return checkParameters(iterations, keylen), password = toBuffer(password, defaultEncoding, "Password"), salt = toBuffer(salt, defaultEncoding, "Salt"), digest = digest || "sha1", nativeImpl.pbkdf2Sync(password, salt, iterations, keylen, digest);
    }
    if (!nativeImpl.pbkdf2Sync || nativeImpl.pbkdf2Sync.toString().indexOf("keylen, digest") === -1)
      exports.pbkdf2Sync = require_sync(), exports.pbkdf2 = require_async();
    else
      exports.pbkdf2Sync = nativePBKDF2Sync, exports.pbkdf2 = nativePBKDF2;
  });
  require_browserify_cipher = __commonJS2((exports) => {
    var crypto2 = (init_crypto(), __toCommonJS(exports_crypto));
    exports.createCipher = exports.Cipher = crypto2.createCipher;
    exports.createCipheriv = exports.Cipheriv = crypto2.createCipheriv;
    exports.createDecipher = exports.Decipher = crypto2.createDecipher;
    exports.createDecipheriv = exports.Decipheriv = crypto2.createDecipheriv;
    exports.listCiphers = exports.getCiphers = crypto2.getCiphers;
  });
  require_diffie_hellman = __commonJS2((exports) => {
    var crypto2 = (init_crypto(), __toCommonJS(exports_crypto));
    exports.DiffieHellmanGroup = crypto2.DiffieHellmanGroup;
    exports.createDiffieHellmanGroup = crypto2.createDiffieHellmanGroup;
    exports.getDiffieHellman = crypto2.getDiffieHellman;
    exports.createDiffieHellman = crypto2.createDiffieHellman;
    exports.DiffieHellman = crypto2.DiffieHellman;
  });
  require_browserify_sign = __commonJS2((exports) => {
    var crypto2 = (init_crypto(), __toCommonJS(exports_crypto));
    exports.createSign = crypto2.createSign;
    exports.Sign = crypto2.Sign;
    exports.createVerify = crypto2.createVerify;
    exports.Verify = crypto2.Verify;
  });
  require_package = __commonJS2((exports, module) => {
    module.exports = { name: "elliptic", version: "6.6.1", description: "EC cryptography", main: "lib/elliptic.js", files: ["lib"], scripts: { lint: "eslint lib test", "lint:fix": "npm run lint -- --fix", unit: "istanbul test _mocha --reporter=spec test/index.js", test: "npm run lint && npm run unit", version: "grunt dist && git add dist/" }, repository: { type: "git", url: "git@github.com:indutny/elliptic" }, keywords: ["EC", "Elliptic", "curve", "Cryptography"], author: "Fedor Indutny <fedor@indutny.com>", license: "MIT", bugs: { url: "https://github.com/indutny/elliptic/issues" }, homepage: "https://github.com/indutny/elliptic", devDependencies: { brfs: "^2.0.2", coveralls: "^3.1.0", eslint: "^7.6.0", grunt: "^1.2.1", "grunt-browserify": "^5.3.0", "grunt-cli": "^1.3.2", "grunt-contrib-connect": "^3.0.0", "grunt-contrib-copy": "^1.0.0", "grunt-contrib-uglify": "^5.0.0", "grunt-mocha-istanbul": "^5.0.2", "grunt-saucelabs": "^9.0.1", istanbul: "^0.4.5", mocha: "^8.0.1" }, dependencies: { "bn.js": "^4.11.9", brorand: "^1.1.0", "hash.js": "^1.0.0", "hmac-drbg": "^1.0.1", inherits: "^2.0.4", "minimalistic-assert": "^1.0.1", "minimalistic-crypto-utils": "^1.0.1" } };
  });
  require_bn = __commonJS2((exports, module) => {
    (function(module2, exports2) {
      function assert(val, msg) {
        if (!val)
          throw Error(msg || "Assertion failed");
      }
      function inherits2(ctor, superCtor) {
        ctor.super_ = superCtor;
        var TempCtor = function() {};
        TempCtor.prototype = superCtor.prototype, ctor.prototype = new TempCtor, ctor.prototype.constructor = ctor;
      }
      function BN(number, base, endian) {
        if (BN.isBN(number))
          return number;
        if (this.negative = 0, this.words = null, this.length = 0, this.red = null, number !== null) {
          if (base === "le" || base === "be")
            endian = base, base = 10;
          this._init(number || 0, base || 10, endian || "be");
        }
      }
      if (typeof module2 === "object")
        module2.exports = BN;
      else
        exports2.BN = BN;
      BN.BN = BN, BN.wordSize = 26;
      var Buffer22;
      try {
        if (typeof window < "u" && typeof window.Buffer < "u")
          Buffer22 = window.Buffer;
        else
          Buffer22 = (init_buffer(), __toCommonJS(exports_buffer)).Buffer;
      } catch (e2) {}
      BN.isBN = function(num) {
        if (num instanceof BN)
          return true;
        return num !== null && typeof num === "object" && num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
      }, BN.max = function(left, right) {
        if (left.cmp(right) > 0)
          return left;
        return right;
      }, BN.min = function(left, right) {
        if (left.cmp(right) < 0)
          return left;
        return right;
      }, BN.prototype._init = function(number, base, endian) {
        if (typeof number === "number")
          return this._initNumber(number, base, endian);
        if (typeof number === "object")
          return this._initArray(number, base, endian);
        if (base === "hex")
          base = 16;
        assert(base === (base | 0) && base >= 2 && base <= 36), number = number.toString().replace(/\s+/g, "");
        var start = 0;
        if (number[0] === "-")
          start++, this.negative = 1;
        if (start < number.length) {
          if (base === 16)
            this._parseHex(number, start, endian);
          else if (this._parseBase(number, base, start), endian === "le")
            this._initArray(this.toArray(), base, endian);
        }
      }, BN.prototype._initNumber = function(number, base, endian) {
        if (number < 0)
          this.negative = 1, number = -number;
        if (number < 67108864)
          this.words = [number & 67108863], this.length = 1;
        else if (number < 4503599627370496)
          this.words = [number & 67108863, number / 67108864 & 67108863], this.length = 2;
        else
          assert(number < 9007199254740992), this.words = [number & 67108863, number / 67108864 & 67108863, 1], this.length = 3;
        if (endian !== "le")
          return;
        this._initArray(this.toArray(), base, endian);
      }, BN.prototype._initArray = function(number, base, endian) {
        if (assert(typeof number.length === "number"), number.length <= 0)
          return this.words = [0], this.length = 1, this;
        this.length = Math.ceil(number.length / 3), this.words = Array(this.length);
        for (var i2 = 0;i2 < this.length; i2++)
          this.words[i2] = 0;
        var j, w, off = 0;
        if (endian === "be") {
          for (i2 = number.length - 1, j = 0;i2 >= 0; i2 -= 3)
            if (w = number[i2] | number[i2 - 1] << 8 | number[i2 - 2] << 16, this.words[j] |= w << off & 67108863, this.words[j + 1] = w >>> 26 - off & 67108863, off += 24, off >= 26)
              off -= 26, j++;
        } else if (endian === "le") {
          for (i2 = 0, j = 0;i2 < number.length; i2 += 3)
            if (w = number[i2] | number[i2 + 1] << 8 | number[i2 + 2] << 16, this.words[j] |= w << off & 67108863, this.words[j + 1] = w >>> 26 - off & 67108863, off += 24, off >= 26)
              off -= 26, j++;
        }
        return this.strip();
      };
      function parseHex4Bits(string, index) {
        var c2 = string.charCodeAt(index);
        if (c2 >= 65 && c2 <= 70)
          return c2 - 55;
        else if (c2 >= 97 && c2 <= 102)
          return c2 - 87;
        else
          return c2 - 48 & 15;
      }
      function parseHexByte(string, lowerBound, index) {
        var r2 = parseHex4Bits(string, index);
        if (index - 1 >= lowerBound)
          r2 |= parseHex4Bits(string, index - 1) << 4;
        return r2;
      }
      BN.prototype._parseHex = function(number, start, endian) {
        this.length = Math.ceil((number.length - start) / 6), this.words = Array(this.length);
        for (var i2 = 0;i2 < this.length; i2++)
          this.words[i2] = 0;
        var off = 0, j = 0, w;
        if (endian === "be")
          for (i2 = number.length - 1;i2 >= start; i2 -= 2)
            if (w = parseHexByte(number, start, i2) << off, this.words[j] |= w & 67108863, off >= 18)
              off -= 18, j += 1, this.words[j] |= w >>> 26;
            else
              off += 8;
        else {
          var parseLength = number.length - start;
          for (i2 = parseLength % 2 === 0 ? start + 1 : start;i2 < number.length; i2 += 2)
            if (w = parseHexByte(number, start, i2) << off, this.words[j] |= w & 67108863, off >= 18)
              off -= 18, j += 1, this.words[j] |= w >>> 26;
            else
              off += 8;
        }
        this.strip();
      };
      function parseBase(str, start, end, mul) {
        var r2 = 0, len2 = Math.min(str.length, end);
        for (var i2 = start;i2 < len2; i2++) {
          var c2 = str.charCodeAt(i2) - 48;
          if (r2 *= mul, c2 >= 49)
            r2 += c2 - 49 + 10;
          else if (c2 >= 17)
            r2 += c2 - 17 + 10;
          else
            r2 += c2;
        }
        return r2;
      }
      BN.prototype._parseBase = function(number, base, start) {
        this.words = [0], this.length = 1;
        for (var limbLen = 0, limbPow = 1;limbPow <= 67108863; limbPow *= base)
          limbLen++;
        limbLen--, limbPow = limbPow / base | 0;
        var total = number.length - start, mod = total % limbLen, end = Math.min(total, total - mod) + start, word = 0;
        for (var i2 = start;i2 < end; i2 += limbLen)
          if (word = parseBase(number, i2, i2 + limbLen, base), this.imuln(limbPow), this.words[0] + word < 67108864)
            this.words[0] += word;
          else
            this._iaddn(word);
        if (mod !== 0) {
          var pow = 1;
          word = parseBase(number, i2, number.length, base);
          for (i2 = 0;i2 < mod; i2++)
            pow *= base;
          if (this.imuln(pow), this.words[0] + word < 67108864)
            this.words[0] += word;
          else
            this._iaddn(word);
        }
        this.strip();
      }, BN.prototype.copy = function(dest) {
        dest.words = Array(this.length);
        for (var i2 = 0;i2 < this.length; i2++)
          dest.words[i2] = this.words[i2];
        dest.length = this.length, dest.negative = this.negative, dest.red = this.red;
      }, BN.prototype.clone = function() {
        var r2 = new BN(null);
        return this.copy(r2), r2;
      }, BN.prototype._expand = function(size) {
        while (this.length < size)
          this.words[this.length++] = 0;
        return this;
      }, BN.prototype.strip = function() {
        while (this.length > 1 && this.words[this.length - 1] === 0)
          this.length--;
        return this._normSign();
      }, BN.prototype._normSign = function() {
        if (this.length === 1 && this.words[0] === 0)
          this.negative = 0;
        return this;
      }, BN.prototype.inspect = function() {
        return (this.red ? "<BN-R: " : "<BN: ") + this.toString(16) + ">";
      };
      var zeros = ["", "0", "00", "000", "0000", "00000", "000000", "0000000", "00000000", "000000000", "0000000000", "00000000000", "000000000000", "0000000000000", "00000000000000", "000000000000000", "0000000000000000", "00000000000000000", "000000000000000000", "0000000000000000000", "00000000000000000000", "000000000000000000000", "0000000000000000000000", "00000000000000000000000", "000000000000000000000000", "0000000000000000000000000"], groupSizes = [0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5], groupBases = [0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 1e7, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176];
      if (BN.prototype.toString = function(base, padding) {
        base = base || 10, padding = padding | 0 || 1;
        var out;
        if (base === 16 || base === "hex") {
          out = "";
          var off = 0, carry = 0;
          for (var i2 = 0;i2 < this.length; i2++) {
            var w = this.words[i2], word = ((w << off | carry) & 16777215).toString(16);
            if (carry = w >>> 24 - off & 16777215, off += 2, off >= 26)
              off -= 26, i2--;
            if (carry !== 0 || i2 !== this.length - 1)
              out = zeros[6 - word.length] + word + out;
            else
              out = word + out;
          }
          if (carry !== 0)
            out = carry.toString(16) + out;
          while (out.length % padding !== 0)
            out = "0" + out;
          if (this.negative !== 0)
            out = "-" + out;
          return out;
        }
        if (base === (base | 0) && base >= 2 && base <= 36) {
          var groupSize = groupSizes[base], groupBase = groupBases[base];
          out = "";
          var c2 = this.clone();
          c2.negative = 0;
          while (!c2.isZero()) {
            var r2 = c2.modn(groupBase).toString(base);
            if (c2 = c2.idivn(groupBase), !c2.isZero())
              out = zeros[groupSize - r2.length] + r2 + out;
            else
              out = r2 + out;
          }
          if (this.isZero())
            out = "0" + out;
          while (out.length % padding !== 0)
            out = "0" + out;
          if (this.negative !== 0)
            out = "-" + out;
          return out;
        }
        assert(false, "Base should be between 2 and 36");
      }, BN.prototype.toNumber = function() {
        var ret = this.words[0];
        if (this.length === 2)
          ret += this.words[1] * 67108864;
        else if (this.length === 3 && this.words[2] === 1)
          ret += 4503599627370496 + this.words[1] * 67108864;
        else if (this.length > 2)
          assert(false, "Number can only safely store up to 53 bits");
        return this.negative !== 0 ? -ret : ret;
      }, BN.prototype.toJSON = function() {
        return this.toString(16);
      }, BN.prototype.toBuffer = function(endian, length) {
        return assert(typeof Buffer22 < "u"), this.toArrayLike(Buffer22, endian, length);
      }, BN.prototype.toArray = function(endian, length) {
        return this.toArrayLike(Array, endian, length);
      }, BN.prototype.toArrayLike = function(ArrayType, endian, length) {
        var byteLength2 = this.byteLength(), reqLength = length || Math.max(1, byteLength2);
        assert(byteLength2 <= reqLength, "byte array longer than desired length"), assert(reqLength > 0, "Requested array length <= 0"), this.strip();
        var littleEndian = endian === "le", res = new ArrayType(reqLength), b, i2, q = this.clone();
        if (!littleEndian) {
          for (i2 = 0;i2 < reqLength - byteLength2; i2++)
            res[i2] = 0;
          for (i2 = 0;!q.isZero(); i2++)
            b = q.andln(255), q.iushrn(8), res[reqLength - i2 - 1] = b;
        } else {
          for (i2 = 0;!q.isZero(); i2++)
            b = q.andln(255), q.iushrn(8), res[i2] = b;
          for (;i2 < reqLength; i2++)
            res[i2] = 0;
        }
        return res;
      }, Math.clz32)
        BN.prototype._countBits = function(w) {
          return 32 - Math.clz32(w);
        };
      else
        BN.prototype._countBits = function(w) {
          var t2 = w, r2 = 0;
          if (t2 >= 4096)
            r2 += 13, t2 >>>= 13;
          if (t2 >= 64)
            r2 += 7, t2 >>>= 7;
          if (t2 >= 8)
            r2 += 4, t2 >>>= 4;
          if (t2 >= 2)
            r2 += 2, t2 >>>= 2;
          return r2 + t2;
        };
      BN.prototype._zeroBits = function(w) {
        if (w === 0)
          return 26;
        var t2 = w, r2 = 0;
        if ((t2 & 8191) === 0)
          r2 += 13, t2 >>>= 13;
        if ((t2 & 127) === 0)
          r2 += 7, t2 >>>= 7;
        if ((t2 & 15) === 0)
          r2 += 4, t2 >>>= 4;
        if ((t2 & 3) === 0)
          r2 += 2, t2 >>>= 2;
        if ((t2 & 1) === 0)
          r2++;
        return r2;
      }, BN.prototype.bitLength = function() {
        var w = this.words[this.length - 1], hi = this._countBits(w);
        return (this.length - 1) * 26 + hi;
      };
      function toBitArray(num) {
        var w = Array(num.bitLength());
        for (var bit = 0;bit < w.length; bit++) {
          var off = bit / 26 | 0, wbit = bit % 26;
          w[bit] = (num.words[off] & 1 << wbit) >>> wbit;
        }
        return w;
      }
      BN.prototype.zeroBits = function() {
        if (this.isZero())
          return 0;
        var r2 = 0;
        for (var i2 = 0;i2 < this.length; i2++) {
          var b = this._zeroBits(this.words[i2]);
          if (r2 += b, b !== 26)
            break;
        }
        return r2;
      }, BN.prototype.byteLength = function() {
        return Math.ceil(this.bitLength() / 8);
      }, BN.prototype.toTwos = function(width) {
        if (this.negative !== 0)
          return this.abs().inotn(width).iaddn(1);
        return this.clone();
      }, BN.prototype.fromTwos = function(width) {
        if (this.testn(width - 1))
          return this.notn(width).iaddn(1).ineg();
        return this.clone();
      }, BN.prototype.isNeg = function() {
        return this.negative !== 0;
      }, BN.prototype.neg = function() {
        return this.clone().ineg();
      }, BN.prototype.ineg = function() {
        if (!this.isZero())
          this.negative ^= 1;
        return this;
      }, BN.prototype.iuor = function(num) {
        while (this.length < num.length)
          this.words[this.length++] = 0;
        for (var i2 = 0;i2 < num.length; i2++)
          this.words[i2] = this.words[i2] | num.words[i2];
        return this.strip();
      }, BN.prototype.ior = function(num) {
        return assert((this.negative | num.negative) === 0), this.iuor(num);
      }, BN.prototype.or = function(num) {
        if (this.length > num.length)
          return this.clone().ior(num);
        return num.clone().ior(this);
      }, BN.prototype.uor = function(num) {
        if (this.length > num.length)
          return this.clone().iuor(num);
        return num.clone().iuor(this);
      }, BN.prototype.iuand = function(num) {
        var b;
        if (this.length > num.length)
          b = num;
        else
          b = this;
        for (var i2 = 0;i2 < b.length; i2++)
          this.words[i2] = this.words[i2] & num.words[i2];
        return this.length = b.length, this.strip();
      }, BN.prototype.iand = function(num) {
        return assert((this.negative | num.negative) === 0), this.iuand(num);
      }, BN.prototype.and = function(num) {
        if (this.length > num.length)
          return this.clone().iand(num);
        return num.clone().iand(this);
      }, BN.prototype.uand = function(num) {
        if (this.length > num.length)
          return this.clone().iuand(num);
        return num.clone().iuand(this);
      }, BN.prototype.iuxor = function(num) {
        var a2, b;
        if (this.length > num.length)
          a2 = this, b = num;
        else
          a2 = num, b = this;
        for (var i2 = 0;i2 < b.length; i2++)
          this.words[i2] = a2.words[i2] ^ b.words[i2];
        if (this !== a2)
          for (;i2 < a2.length; i2++)
            this.words[i2] = a2.words[i2];
        return this.length = a2.length, this.strip();
      }, BN.prototype.ixor = function(num) {
        return assert((this.negative | num.negative) === 0), this.iuxor(num);
      }, BN.prototype.xor = function(num) {
        if (this.length > num.length)
          return this.clone().ixor(num);
        return num.clone().ixor(this);
      }, BN.prototype.uxor = function(num) {
        if (this.length > num.length)
          return this.clone().iuxor(num);
        return num.clone().iuxor(this);
      }, BN.prototype.inotn = function(width) {
        assert(typeof width === "number" && width >= 0);
        var bytesNeeded = Math.ceil(width / 26) | 0, bitsLeft = width % 26;
        if (this._expand(bytesNeeded), bitsLeft > 0)
          bytesNeeded--;
        for (var i2 = 0;i2 < bytesNeeded; i2++)
          this.words[i2] = ~this.words[i2] & 67108863;
        if (bitsLeft > 0)
          this.words[i2] = ~this.words[i2] & 67108863 >> 26 - bitsLeft;
        return this.strip();
      }, BN.prototype.notn = function(width) {
        return this.clone().inotn(width);
      }, BN.prototype.setn = function(bit, val) {
        assert(typeof bit === "number" && bit >= 0);
        var off = bit / 26 | 0, wbit = bit % 26;
        if (this._expand(off + 1), val)
          this.words[off] = this.words[off] | 1 << wbit;
        else
          this.words[off] = this.words[off] & ~(1 << wbit);
        return this.strip();
      }, BN.prototype.iadd = function(num) {
        var r2;
        if (this.negative !== 0 && num.negative === 0)
          return this.negative = 0, r2 = this.isub(num), this.negative ^= 1, this._normSign();
        else if (this.negative === 0 && num.negative !== 0)
          return num.negative = 0, r2 = this.isub(num), num.negative = 1, r2._normSign();
        var a2, b;
        if (this.length > num.length)
          a2 = this, b = num;
        else
          a2 = num, b = this;
        var carry = 0;
        for (var i2 = 0;i2 < b.length; i2++)
          r2 = (a2.words[i2] | 0) + (b.words[i2] | 0) + carry, this.words[i2] = r2 & 67108863, carry = r2 >>> 26;
        for (;carry !== 0 && i2 < a2.length; i2++)
          r2 = (a2.words[i2] | 0) + carry, this.words[i2] = r2 & 67108863, carry = r2 >>> 26;
        if (this.length = a2.length, carry !== 0)
          this.words[this.length] = carry, this.length++;
        else if (a2 !== this)
          for (;i2 < a2.length; i2++)
            this.words[i2] = a2.words[i2];
        return this;
      }, BN.prototype.add = function(num) {
        var res;
        if (num.negative !== 0 && this.negative === 0)
          return num.negative = 0, res = this.sub(num), num.negative ^= 1, res;
        else if (num.negative === 0 && this.negative !== 0)
          return this.negative = 0, res = num.sub(this), this.negative = 1, res;
        if (this.length > num.length)
          return this.clone().iadd(num);
        return num.clone().iadd(this);
      }, BN.prototype.isub = function(num) {
        if (num.negative !== 0) {
          num.negative = 0;
          var r2 = this.iadd(num);
          return num.negative = 1, r2._normSign();
        } else if (this.negative !== 0)
          return this.negative = 0, this.iadd(num), this.negative = 1, this._normSign();
        var cmp = this.cmp(num);
        if (cmp === 0)
          return this.negative = 0, this.length = 1, this.words[0] = 0, this;
        var a2, b;
        if (cmp > 0)
          a2 = this, b = num;
        else
          a2 = num, b = this;
        var carry = 0;
        for (var i2 = 0;i2 < b.length; i2++)
          r2 = (a2.words[i2] | 0) - (b.words[i2] | 0) + carry, carry = r2 >> 26, this.words[i2] = r2 & 67108863;
        for (;carry !== 0 && i2 < a2.length; i2++)
          r2 = (a2.words[i2] | 0) + carry, carry = r2 >> 26, this.words[i2] = r2 & 67108863;
        if (carry === 0 && i2 < a2.length && a2 !== this)
          for (;i2 < a2.length; i2++)
            this.words[i2] = a2.words[i2];
        if (this.length = Math.max(this.length, i2), a2 !== this)
          this.negative = 1;
        return this.strip();
      }, BN.prototype.sub = function(num) {
        return this.clone().isub(num);
      };
      function smallMulTo(self2, num, out) {
        out.negative = num.negative ^ self2.negative;
        var len2 = self2.length + num.length | 0;
        out.length = len2, len2 = len2 - 1 | 0;
        var a2 = self2.words[0] | 0, b = num.words[0] | 0, r2 = a2 * b, lo = r2 & 67108863, carry = r2 / 67108864 | 0;
        out.words[0] = lo;
        for (var k = 1;k < len2; k++) {
          var ncarry = carry >>> 26, rword = carry & 67108863, maxJ = Math.min(k, num.length - 1);
          for (var j = Math.max(0, k - self2.length + 1);j <= maxJ; j++) {
            var i2 = k - j | 0;
            a2 = self2.words[i2] | 0, b = num.words[j] | 0, r2 = a2 * b + rword, ncarry += r2 / 67108864 | 0, rword = r2 & 67108863;
          }
          out.words[k] = rword | 0, carry = ncarry | 0;
        }
        if (carry !== 0)
          out.words[k] = carry | 0;
        else
          out.length--;
        return out.strip();
      }
      var comb10MulTo = function(self2, num, out) {
        var a2 = self2.words, b = num.words, o2 = out.words, c2 = 0, lo, mid, hi, a0 = a2[0] | 0, al0 = a0 & 8191, ah0 = a0 >>> 13, a1 = a2[1] | 0, al1 = a1 & 8191, ah1 = a1 >>> 13, a22 = a2[2] | 0, al2 = a22 & 8191, ah2 = a22 >>> 13, a3 = a2[3] | 0, al3 = a3 & 8191, ah3 = a3 >>> 13, a4 = a2[4] | 0, al4 = a4 & 8191, ah4 = a4 >>> 13, a5 = a2[5] | 0, al5 = a5 & 8191, ah5 = a5 >>> 13, a6 = a2[6] | 0, al6 = a6 & 8191, ah6 = a6 >>> 13, a7 = a2[7] | 0, al7 = a7 & 8191, ah7 = a7 >>> 13, a8 = a2[8] | 0, al8 = a8 & 8191, ah8 = a8 >>> 13, a9 = a2[9] | 0, al9 = a9 & 8191, ah9 = a9 >>> 13, b0 = b[0] | 0, bl0 = b0 & 8191, bh0 = b0 >>> 13, b1 = b[1] | 0, bl1 = b1 & 8191, bh1 = b1 >>> 13, b2 = b[2] | 0, bl2 = b2 & 8191, bh2 = b2 >>> 13, b3 = b[3] | 0, bl3 = b3 & 8191, bh3 = b3 >>> 13, b4 = b[4] | 0, bl4 = b4 & 8191, bh4 = b4 >>> 13, b5 = b[5] | 0, bl5 = b5 & 8191, bh5 = b5 >>> 13, b6 = b[6] | 0, bl6 = b6 & 8191, bh6 = b6 >>> 13, b7 = b[7] | 0, bl7 = b7 & 8191, bh7 = b7 >>> 13, b8 = b[8] | 0, bl8 = b8 & 8191, bh8 = b8 >>> 13, b9 = b[9] | 0, bl9 = b9 & 8191, bh9 = b9 >>> 13;
        out.negative = self2.negative ^ num.negative, out.length = 19, lo = Math.imul(al0, bl0), mid = Math.imul(al0, bh0), mid = mid + Math.imul(ah0, bl0) | 0, hi = Math.imul(ah0, bh0);
        var w0 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w0 >>> 26) | 0, w0 &= 67108863, lo = Math.imul(al1, bl0), mid = Math.imul(al1, bh0), mid = mid + Math.imul(ah1, bl0) | 0, hi = Math.imul(ah1, bh0), lo = lo + Math.imul(al0, bl1) | 0, mid = mid + Math.imul(al0, bh1) | 0, mid = mid + Math.imul(ah0, bl1) | 0, hi = hi + Math.imul(ah0, bh1) | 0;
        var w1 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w1 >>> 26) | 0, w1 &= 67108863, lo = Math.imul(al2, bl0), mid = Math.imul(al2, bh0), mid = mid + Math.imul(ah2, bl0) | 0, hi = Math.imul(ah2, bh0), lo = lo + Math.imul(al1, bl1) | 0, mid = mid + Math.imul(al1, bh1) | 0, mid = mid + Math.imul(ah1, bl1) | 0, hi = hi + Math.imul(ah1, bh1) | 0, lo = lo + Math.imul(al0, bl2) | 0, mid = mid + Math.imul(al0, bh2) | 0, mid = mid + Math.imul(ah0, bl2) | 0, hi = hi + Math.imul(ah0, bh2) | 0;
        var w2 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w2 >>> 26) | 0, w2 &= 67108863, lo = Math.imul(al3, bl0), mid = Math.imul(al3, bh0), mid = mid + Math.imul(ah3, bl0) | 0, hi = Math.imul(ah3, bh0), lo = lo + Math.imul(al2, bl1) | 0, mid = mid + Math.imul(al2, bh1) | 0, mid = mid + Math.imul(ah2, bl1) | 0, hi = hi + Math.imul(ah2, bh1) | 0, lo = lo + Math.imul(al1, bl2) | 0, mid = mid + Math.imul(al1, bh2) | 0, mid = mid + Math.imul(ah1, bl2) | 0, hi = hi + Math.imul(ah1, bh2) | 0, lo = lo + Math.imul(al0, bl3) | 0, mid = mid + Math.imul(al0, bh3) | 0, mid = mid + Math.imul(ah0, bl3) | 0, hi = hi + Math.imul(ah0, bh3) | 0;
        var w3 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w3 >>> 26) | 0, w3 &= 67108863, lo = Math.imul(al4, bl0), mid = Math.imul(al4, bh0), mid = mid + Math.imul(ah4, bl0) | 0, hi = Math.imul(ah4, bh0), lo = lo + Math.imul(al3, bl1) | 0, mid = mid + Math.imul(al3, bh1) | 0, mid = mid + Math.imul(ah3, bl1) | 0, hi = hi + Math.imul(ah3, bh1) | 0, lo = lo + Math.imul(al2, bl2) | 0, mid = mid + Math.imul(al2, bh2) | 0, mid = mid + Math.imul(ah2, bl2) | 0, hi = hi + Math.imul(ah2, bh2) | 0, lo = lo + Math.imul(al1, bl3) | 0, mid = mid + Math.imul(al1, bh3) | 0, mid = mid + Math.imul(ah1, bl3) | 0, hi = hi + Math.imul(ah1, bh3) | 0, lo = lo + Math.imul(al0, bl4) | 0, mid = mid + Math.imul(al0, bh4) | 0, mid = mid + Math.imul(ah0, bl4) | 0, hi = hi + Math.imul(ah0, bh4) | 0;
        var w4 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w4 >>> 26) | 0, w4 &= 67108863, lo = Math.imul(al5, bl0), mid = Math.imul(al5, bh0), mid = mid + Math.imul(ah5, bl0) | 0, hi = Math.imul(ah5, bh0), lo = lo + Math.imul(al4, bl1) | 0, mid = mid + Math.imul(al4, bh1) | 0, mid = mid + Math.imul(ah4, bl1) | 0, hi = hi + Math.imul(ah4, bh1) | 0, lo = lo + Math.imul(al3, bl2) | 0, mid = mid + Math.imul(al3, bh2) | 0, mid = mid + Math.imul(ah3, bl2) | 0, hi = hi + Math.imul(ah3, bh2) | 0, lo = lo + Math.imul(al2, bl3) | 0, mid = mid + Math.imul(al2, bh3) | 0, mid = mid + Math.imul(ah2, bl3) | 0, hi = hi + Math.imul(ah2, bh3) | 0, lo = lo + Math.imul(al1, bl4) | 0, mid = mid + Math.imul(al1, bh4) | 0, mid = mid + Math.imul(ah1, bl4) | 0, hi = hi + Math.imul(ah1, bh4) | 0, lo = lo + Math.imul(al0, bl5) | 0, mid = mid + Math.imul(al0, bh5) | 0, mid = mid + Math.imul(ah0, bl5) | 0, hi = hi + Math.imul(ah0, bh5) | 0;
        var w5 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w5 >>> 26) | 0, w5 &= 67108863, lo = Math.imul(al6, bl0), mid = Math.imul(al6, bh0), mid = mid + Math.imul(ah6, bl0) | 0, hi = Math.imul(ah6, bh0), lo = lo + Math.imul(al5, bl1) | 0, mid = mid + Math.imul(al5, bh1) | 0, mid = mid + Math.imul(ah5, bl1) | 0, hi = hi + Math.imul(ah5, bh1) | 0, lo = lo + Math.imul(al4, bl2) | 0, mid = mid + Math.imul(al4, bh2) | 0, mid = mid + Math.imul(ah4, bl2) | 0, hi = hi + Math.imul(ah4, bh2) | 0, lo = lo + Math.imul(al3, bl3) | 0, mid = mid + Math.imul(al3, bh3) | 0, mid = mid + Math.imul(ah3, bl3) | 0, hi = hi + Math.imul(ah3, bh3) | 0, lo = lo + Math.imul(al2, bl4) | 0, mid = mid + Math.imul(al2, bh4) | 0, mid = mid + Math.imul(ah2, bl4) | 0, hi = hi + Math.imul(ah2, bh4) | 0, lo = lo + Math.imul(al1, bl5) | 0, mid = mid + Math.imul(al1, bh5) | 0, mid = mid + Math.imul(ah1, bl5) | 0, hi = hi + Math.imul(ah1, bh5) | 0, lo = lo + Math.imul(al0, bl6) | 0, mid = mid + Math.imul(al0, bh6) | 0, mid = mid + Math.imul(ah0, bl6) | 0, hi = hi + Math.imul(ah0, bh6) | 0;
        var w6 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w6 >>> 26) | 0, w6 &= 67108863, lo = Math.imul(al7, bl0), mid = Math.imul(al7, bh0), mid = mid + Math.imul(ah7, bl0) | 0, hi = Math.imul(ah7, bh0), lo = lo + Math.imul(al6, bl1) | 0, mid = mid + Math.imul(al6, bh1) | 0, mid = mid + Math.imul(ah6, bl1) | 0, hi = hi + Math.imul(ah6, bh1) | 0, lo = lo + Math.imul(al5, bl2) | 0, mid = mid + Math.imul(al5, bh2) | 0, mid = mid + Math.imul(ah5, bl2) | 0, hi = hi + Math.imul(ah5, bh2) | 0, lo = lo + Math.imul(al4, bl3) | 0, mid = mid + Math.imul(al4, bh3) | 0, mid = mid + Math.imul(ah4, bl3) | 0, hi = hi + Math.imul(ah4, bh3) | 0, lo = lo + Math.imul(al3, bl4) | 0, mid = mid + Math.imul(al3, bh4) | 0, mid = mid + Math.imul(ah3, bl4) | 0, hi = hi + Math.imul(ah3, bh4) | 0, lo = lo + Math.imul(al2, bl5) | 0, mid = mid + Math.imul(al2, bh5) | 0, mid = mid + Math.imul(ah2, bl5) | 0, hi = hi + Math.imul(ah2, bh5) | 0, lo = lo + Math.imul(al1, bl6) | 0, mid = mid + Math.imul(al1, bh6) | 0, mid = mid + Math.imul(ah1, bl6) | 0, hi = hi + Math.imul(ah1, bh6) | 0, lo = lo + Math.imul(al0, bl7) | 0, mid = mid + Math.imul(al0, bh7) | 0, mid = mid + Math.imul(ah0, bl7) | 0, hi = hi + Math.imul(ah0, bh7) | 0;
        var w7 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w7 >>> 26) | 0, w7 &= 67108863, lo = Math.imul(al8, bl0), mid = Math.imul(al8, bh0), mid = mid + Math.imul(ah8, bl0) | 0, hi = Math.imul(ah8, bh0), lo = lo + Math.imul(al7, bl1) | 0, mid = mid + Math.imul(al7, bh1) | 0, mid = mid + Math.imul(ah7, bl1) | 0, hi = hi + Math.imul(ah7, bh1) | 0, lo = lo + Math.imul(al6, bl2) | 0, mid = mid + Math.imul(al6, bh2) | 0, mid = mid + Math.imul(ah6, bl2) | 0, hi = hi + Math.imul(ah6, bh2) | 0, lo = lo + Math.imul(al5, bl3) | 0, mid = mid + Math.imul(al5, bh3) | 0, mid = mid + Math.imul(ah5, bl3) | 0, hi = hi + Math.imul(ah5, bh3) | 0, lo = lo + Math.imul(al4, bl4) | 0, mid = mid + Math.imul(al4, bh4) | 0, mid = mid + Math.imul(ah4, bl4) | 0, hi = hi + Math.imul(ah4, bh4) | 0, lo = lo + Math.imul(al3, bl5) | 0, mid = mid + Math.imul(al3, bh5) | 0, mid = mid + Math.imul(ah3, bl5) | 0, hi = hi + Math.imul(ah3, bh5) | 0, lo = lo + Math.imul(al2, bl6) | 0, mid = mid + Math.imul(al2, bh6) | 0, mid = mid + Math.imul(ah2, bl6) | 0, hi = hi + Math.imul(ah2, bh6) | 0, lo = lo + Math.imul(al1, bl7) | 0, mid = mid + Math.imul(al1, bh7) | 0, mid = mid + Math.imul(ah1, bl7) | 0, hi = hi + Math.imul(ah1, bh7) | 0, lo = lo + Math.imul(al0, bl8) | 0, mid = mid + Math.imul(al0, bh8) | 0, mid = mid + Math.imul(ah0, bl8) | 0, hi = hi + Math.imul(ah0, bh8) | 0;
        var w8 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w8 >>> 26) | 0, w8 &= 67108863, lo = Math.imul(al9, bl0), mid = Math.imul(al9, bh0), mid = mid + Math.imul(ah9, bl0) | 0, hi = Math.imul(ah9, bh0), lo = lo + Math.imul(al8, bl1) | 0, mid = mid + Math.imul(al8, bh1) | 0, mid = mid + Math.imul(ah8, bl1) | 0, hi = hi + Math.imul(ah8, bh1) | 0, lo = lo + Math.imul(al7, bl2) | 0, mid = mid + Math.imul(al7, bh2) | 0, mid = mid + Math.imul(ah7, bl2) | 0, hi = hi + Math.imul(ah7, bh2) | 0, lo = lo + Math.imul(al6, bl3) | 0, mid = mid + Math.imul(al6, bh3) | 0, mid = mid + Math.imul(ah6, bl3) | 0, hi = hi + Math.imul(ah6, bh3) | 0, lo = lo + Math.imul(al5, bl4) | 0, mid = mid + Math.imul(al5, bh4) | 0, mid = mid + Math.imul(ah5, bl4) | 0, hi = hi + Math.imul(ah5, bh4) | 0, lo = lo + Math.imul(al4, bl5) | 0, mid = mid + Math.imul(al4, bh5) | 0, mid = mid + Math.imul(ah4, bl5) | 0, hi = hi + Math.imul(ah4, bh5) | 0, lo = lo + Math.imul(al3, bl6) | 0, mid = mid + Math.imul(al3, bh6) | 0, mid = mid + Math.imul(ah3, bl6) | 0, hi = hi + Math.imul(ah3, bh6) | 0, lo = lo + Math.imul(al2, bl7) | 0, mid = mid + Math.imul(al2, bh7) | 0, mid = mid + Math.imul(ah2, bl7) | 0, hi = hi + Math.imul(ah2, bh7) | 0, lo = lo + Math.imul(al1, bl8) | 0, mid = mid + Math.imul(al1, bh8) | 0, mid = mid + Math.imul(ah1, bl8) | 0, hi = hi + Math.imul(ah1, bh8) | 0, lo = lo + Math.imul(al0, bl9) | 0, mid = mid + Math.imul(al0, bh9) | 0, mid = mid + Math.imul(ah0, bl9) | 0, hi = hi + Math.imul(ah0, bh9) | 0;
        var w9 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w9 >>> 26) | 0, w9 &= 67108863, lo = Math.imul(al9, bl1), mid = Math.imul(al9, bh1), mid = mid + Math.imul(ah9, bl1) | 0, hi = Math.imul(ah9, bh1), lo = lo + Math.imul(al8, bl2) | 0, mid = mid + Math.imul(al8, bh2) | 0, mid = mid + Math.imul(ah8, bl2) | 0, hi = hi + Math.imul(ah8, bh2) | 0, lo = lo + Math.imul(al7, bl3) | 0, mid = mid + Math.imul(al7, bh3) | 0, mid = mid + Math.imul(ah7, bl3) | 0, hi = hi + Math.imul(ah7, bh3) | 0, lo = lo + Math.imul(al6, bl4) | 0, mid = mid + Math.imul(al6, bh4) | 0, mid = mid + Math.imul(ah6, bl4) | 0, hi = hi + Math.imul(ah6, bh4) | 0, lo = lo + Math.imul(al5, bl5) | 0, mid = mid + Math.imul(al5, bh5) | 0, mid = mid + Math.imul(ah5, bl5) | 0, hi = hi + Math.imul(ah5, bh5) | 0, lo = lo + Math.imul(al4, bl6) | 0, mid = mid + Math.imul(al4, bh6) | 0, mid = mid + Math.imul(ah4, bl6) | 0, hi = hi + Math.imul(ah4, bh6) | 0, lo = lo + Math.imul(al3, bl7) | 0, mid = mid + Math.imul(al3, bh7) | 0, mid = mid + Math.imul(ah3, bl7) | 0, hi = hi + Math.imul(ah3, bh7) | 0, lo = lo + Math.imul(al2, bl8) | 0, mid = mid + Math.imul(al2, bh8) | 0, mid = mid + Math.imul(ah2, bl8) | 0, hi = hi + Math.imul(ah2, bh8) | 0, lo = lo + Math.imul(al1, bl9) | 0, mid = mid + Math.imul(al1, bh9) | 0, mid = mid + Math.imul(ah1, bl9) | 0, hi = hi + Math.imul(ah1, bh9) | 0;
        var w10 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w10 >>> 26) | 0, w10 &= 67108863, lo = Math.imul(al9, bl2), mid = Math.imul(al9, bh2), mid = mid + Math.imul(ah9, bl2) | 0, hi = Math.imul(ah9, bh2), lo = lo + Math.imul(al8, bl3) | 0, mid = mid + Math.imul(al8, bh3) | 0, mid = mid + Math.imul(ah8, bl3) | 0, hi = hi + Math.imul(ah8, bh3) | 0, lo = lo + Math.imul(al7, bl4) | 0, mid = mid + Math.imul(al7, bh4) | 0, mid = mid + Math.imul(ah7, bl4) | 0, hi = hi + Math.imul(ah7, bh4) | 0, lo = lo + Math.imul(al6, bl5) | 0, mid = mid + Math.imul(al6, bh5) | 0, mid = mid + Math.imul(ah6, bl5) | 0, hi = hi + Math.imul(ah6, bh5) | 0, lo = lo + Math.imul(al5, bl6) | 0, mid = mid + Math.imul(al5, bh6) | 0, mid = mid + Math.imul(ah5, bl6) | 0, hi = hi + Math.imul(ah5, bh6) | 0, lo = lo + Math.imul(al4, bl7) | 0, mid = mid + Math.imul(al4, bh7) | 0, mid = mid + Math.imul(ah4, bl7) | 0, hi = hi + Math.imul(ah4, bh7) | 0, lo = lo + Math.imul(al3, bl8) | 0, mid = mid + Math.imul(al3, bh8) | 0, mid = mid + Math.imul(ah3, bl8) | 0, hi = hi + Math.imul(ah3, bh8) | 0, lo = lo + Math.imul(al2, bl9) | 0, mid = mid + Math.imul(al2, bh9) | 0, mid = mid + Math.imul(ah2, bl9) | 0, hi = hi + Math.imul(ah2, bh9) | 0;
        var w11 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w11 >>> 26) | 0, w11 &= 67108863, lo = Math.imul(al9, bl3), mid = Math.imul(al9, bh3), mid = mid + Math.imul(ah9, bl3) | 0, hi = Math.imul(ah9, bh3), lo = lo + Math.imul(al8, bl4) | 0, mid = mid + Math.imul(al8, bh4) | 0, mid = mid + Math.imul(ah8, bl4) | 0, hi = hi + Math.imul(ah8, bh4) | 0, lo = lo + Math.imul(al7, bl5) | 0, mid = mid + Math.imul(al7, bh5) | 0, mid = mid + Math.imul(ah7, bl5) | 0, hi = hi + Math.imul(ah7, bh5) | 0, lo = lo + Math.imul(al6, bl6) | 0, mid = mid + Math.imul(al6, bh6) | 0, mid = mid + Math.imul(ah6, bl6) | 0, hi = hi + Math.imul(ah6, bh6) | 0, lo = lo + Math.imul(al5, bl7) | 0, mid = mid + Math.imul(al5, bh7) | 0, mid = mid + Math.imul(ah5, bl7) | 0, hi = hi + Math.imul(ah5, bh7) | 0, lo = lo + Math.imul(al4, bl8) | 0, mid = mid + Math.imul(al4, bh8) | 0, mid = mid + Math.imul(ah4, bl8) | 0, hi = hi + Math.imul(ah4, bh8) | 0, lo = lo + Math.imul(al3, bl9) | 0, mid = mid + Math.imul(al3, bh9) | 0, mid = mid + Math.imul(ah3, bl9) | 0, hi = hi + Math.imul(ah3, bh9) | 0;
        var w12 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w12 >>> 26) | 0, w12 &= 67108863, lo = Math.imul(al9, bl4), mid = Math.imul(al9, bh4), mid = mid + Math.imul(ah9, bl4) | 0, hi = Math.imul(ah9, bh4), lo = lo + Math.imul(al8, bl5) | 0, mid = mid + Math.imul(al8, bh5) | 0, mid = mid + Math.imul(ah8, bl5) | 0, hi = hi + Math.imul(ah8, bh5) | 0, lo = lo + Math.imul(al7, bl6) | 0, mid = mid + Math.imul(al7, bh6) | 0, mid = mid + Math.imul(ah7, bl6) | 0, hi = hi + Math.imul(ah7, bh6) | 0, lo = lo + Math.imul(al6, bl7) | 0, mid = mid + Math.imul(al6, bh7) | 0, mid = mid + Math.imul(ah6, bl7) | 0, hi = hi + Math.imul(ah6, bh7) | 0, lo = lo + Math.imul(al5, bl8) | 0, mid = mid + Math.imul(al5, bh8) | 0, mid = mid + Math.imul(ah5, bl8) | 0, hi = hi + Math.imul(ah5, bh8) | 0, lo = lo + Math.imul(al4, bl9) | 0, mid = mid + Math.imul(al4, bh9) | 0, mid = mid + Math.imul(ah4, bl9) | 0, hi = hi + Math.imul(ah4, bh9) | 0;
        var w13 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w13 >>> 26) | 0, w13 &= 67108863, lo = Math.imul(al9, bl5), mid = Math.imul(al9, bh5), mid = mid + Math.imul(ah9, bl5) | 0, hi = Math.imul(ah9, bh5), lo = lo + Math.imul(al8, bl6) | 0, mid = mid + Math.imul(al8, bh6) | 0, mid = mid + Math.imul(ah8, bl6) | 0, hi = hi + Math.imul(ah8, bh6) | 0, lo = lo + Math.imul(al7, bl7) | 0, mid = mid + Math.imul(al7, bh7) | 0, mid = mid + Math.imul(ah7, bl7) | 0, hi = hi + Math.imul(ah7, bh7) | 0, lo = lo + Math.imul(al6, bl8) | 0, mid = mid + Math.imul(al6, bh8) | 0, mid = mid + Math.imul(ah6, bl8) | 0, hi = hi + Math.imul(ah6, bh8) | 0, lo = lo + Math.imul(al5, bl9) | 0, mid = mid + Math.imul(al5, bh9) | 0, mid = mid + Math.imul(ah5, bl9) | 0, hi = hi + Math.imul(ah5, bh9) | 0;
        var w14 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w14 >>> 26) | 0, w14 &= 67108863, lo = Math.imul(al9, bl6), mid = Math.imul(al9, bh6), mid = mid + Math.imul(ah9, bl6) | 0, hi = Math.imul(ah9, bh6), lo = lo + Math.imul(al8, bl7) | 0, mid = mid + Math.imul(al8, bh7) | 0, mid = mid + Math.imul(ah8, bl7) | 0, hi = hi + Math.imul(ah8, bh7) | 0, lo = lo + Math.imul(al7, bl8) | 0, mid = mid + Math.imul(al7, bh8) | 0, mid = mid + Math.imul(ah7, bl8) | 0, hi = hi + Math.imul(ah7, bh8) | 0, lo = lo + Math.imul(al6, bl9) | 0, mid = mid + Math.imul(al6, bh9) | 0, mid = mid + Math.imul(ah6, bl9) | 0, hi = hi + Math.imul(ah6, bh9) | 0;
        var w15 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w15 >>> 26) | 0, w15 &= 67108863, lo = Math.imul(al9, bl7), mid = Math.imul(al9, bh7), mid = mid + Math.imul(ah9, bl7) | 0, hi = Math.imul(ah9, bh7), lo = lo + Math.imul(al8, bl8) | 0, mid = mid + Math.imul(al8, bh8) | 0, mid = mid + Math.imul(ah8, bl8) | 0, hi = hi + Math.imul(ah8, bh8) | 0, lo = lo + Math.imul(al7, bl9) | 0, mid = mid + Math.imul(al7, bh9) | 0, mid = mid + Math.imul(ah7, bl9) | 0, hi = hi + Math.imul(ah7, bh9) | 0;
        var w16 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w16 >>> 26) | 0, w16 &= 67108863, lo = Math.imul(al9, bl8), mid = Math.imul(al9, bh8), mid = mid + Math.imul(ah9, bl8) | 0, hi = Math.imul(ah9, bh8), lo = lo + Math.imul(al8, bl9) | 0, mid = mid + Math.imul(al8, bh9) | 0, mid = mid + Math.imul(ah8, bl9) | 0, hi = hi + Math.imul(ah8, bh9) | 0;
        var w17 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w17 >>> 26) | 0, w17 &= 67108863, lo = Math.imul(al9, bl9), mid = Math.imul(al9, bh9), mid = mid + Math.imul(ah9, bl9) | 0, hi = Math.imul(ah9, bh9);
        var w18 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        if (c2 = (hi + (mid >>> 13) | 0) + (w18 >>> 26) | 0, w18 &= 67108863, o2[0] = w0, o2[1] = w1, o2[2] = w2, o2[3] = w3, o2[4] = w4, o2[5] = w5, o2[6] = w6, o2[7] = w7, o2[8] = w8, o2[9] = w9, o2[10] = w10, o2[11] = w11, o2[12] = w12, o2[13] = w13, o2[14] = w14, o2[15] = w15, o2[16] = w16, o2[17] = w17, o2[18] = w18, c2 !== 0)
          o2[19] = c2, out.length++;
        return out;
      };
      if (!Math.imul)
        comb10MulTo = smallMulTo;
      function bigMulTo(self2, num, out) {
        out.negative = num.negative ^ self2.negative, out.length = self2.length + num.length;
        var carry = 0, hncarry = 0;
        for (var k = 0;k < out.length - 1; k++) {
          var ncarry = hncarry;
          hncarry = 0;
          var rword = carry & 67108863, maxJ = Math.min(k, num.length - 1);
          for (var j = Math.max(0, k - self2.length + 1);j <= maxJ; j++) {
            var i2 = k - j, a2 = self2.words[i2] | 0, b = num.words[j] | 0, r2 = a2 * b, lo = r2 & 67108863;
            ncarry = ncarry + (r2 / 67108864 | 0) | 0, lo = lo + rword | 0, rword = lo & 67108863, ncarry = ncarry + (lo >>> 26) | 0, hncarry += ncarry >>> 26, ncarry &= 67108863;
          }
          out.words[k] = rword, carry = ncarry, ncarry = hncarry;
        }
        if (carry !== 0)
          out.words[k] = carry;
        else
          out.length--;
        return out.strip();
      }
      function jumboMulTo(self2, num, out) {
        var fftm = new FFTM;
        return fftm.mulp(self2, num, out);
      }
      BN.prototype.mulTo = function(num, out) {
        var res, len2 = this.length + num.length;
        if (this.length === 10 && num.length === 10)
          res = comb10MulTo(this, num, out);
        else if (len2 < 63)
          res = smallMulTo(this, num, out);
        else if (len2 < 1024)
          res = bigMulTo(this, num, out);
        else
          res = jumboMulTo(this, num, out);
        return res;
      };
      function FFTM(x, y) {
        this.x = x, this.y = y;
      }
      FFTM.prototype.makeRBT = function(N) {
        var t2 = Array(N), l2 = BN.prototype._countBits(N) - 1;
        for (var i2 = 0;i2 < N; i2++)
          t2[i2] = this.revBin(i2, l2, N);
        return t2;
      }, FFTM.prototype.revBin = function(x, l2, N) {
        if (x === 0 || x === N - 1)
          return x;
        var rb = 0;
        for (var i2 = 0;i2 < l2; i2++)
          rb |= (x & 1) << l2 - i2 - 1, x >>= 1;
        return rb;
      }, FFTM.prototype.permute = function(rbt, rws, iws, rtws, itws, N) {
        for (var i2 = 0;i2 < N; i2++)
          rtws[i2] = rws[rbt[i2]], itws[i2] = iws[rbt[i2]];
      }, FFTM.prototype.transform = function(rws, iws, rtws, itws, N, rbt) {
        this.permute(rbt, rws, iws, rtws, itws, N);
        for (var s = 1;s < N; s <<= 1) {
          var l2 = s << 1, rtwdf = Math.cos(2 * Math.PI / l2), itwdf = Math.sin(2 * Math.PI / l2);
          for (var p2 = 0;p2 < N; p2 += l2) {
            var rtwdf_ = rtwdf, itwdf_ = itwdf;
            for (var j = 0;j < s; j++) {
              var re = rtws[p2 + j], ie = itws[p2 + j], ro = rtws[p2 + j + s], io = itws[p2 + j + s], rx = rtwdf_ * ro - itwdf_ * io;
              if (io = rtwdf_ * io + itwdf_ * ro, ro = rx, rtws[p2 + j] = re + ro, itws[p2 + j] = ie + io, rtws[p2 + j + s] = re - ro, itws[p2 + j + s] = ie - io, j !== l2)
                rx = rtwdf * rtwdf_ - itwdf * itwdf_, itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_, rtwdf_ = rx;
            }
          }
        }
      }, FFTM.prototype.guessLen13b = function(n2, m) {
        var N = Math.max(m, n2) | 1, odd = N & 1, i2 = 0;
        for (N = N / 2 | 0;N; N = N >>> 1)
          i2++;
        return 1 << i2 + 1 + odd;
      }, FFTM.prototype.conjugate = function(rws, iws, N) {
        if (N <= 1)
          return;
        for (var i2 = 0;i2 < N / 2; i2++) {
          var t2 = rws[i2];
          rws[i2] = rws[N - i2 - 1], rws[N - i2 - 1] = t2, t2 = iws[i2], iws[i2] = -iws[N - i2 - 1], iws[N - i2 - 1] = -t2;
        }
      }, FFTM.prototype.normalize13b = function(ws, N) {
        var carry = 0;
        for (var i2 = 0;i2 < N / 2; i2++) {
          var w = Math.round(ws[2 * i2 + 1] / N) * 8192 + Math.round(ws[2 * i2] / N) + carry;
          if (ws[i2] = w & 67108863, w < 67108864)
            carry = 0;
          else
            carry = w / 67108864 | 0;
        }
        return ws;
      }, FFTM.prototype.convert13b = function(ws, len2, rws, N) {
        var carry = 0;
        for (var i2 = 0;i2 < len2; i2++)
          carry = carry + (ws[i2] | 0), rws[2 * i2] = carry & 8191, carry = carry >>> 13, rws[2 * i2 + 1] = carry & 8191, carry = carry >>> 13;
        for (i2 = 2 * len2;i2 < N; ++i2)
          rws[i2] = 0;
        assert(carry === 0), assert((carry & -8192) === 0);
      }, FFTM.prototype.stub = function(N) {
        var ph = Array(N);
        for (var i2 = 0;i2 < N; i2++)
          ph[i2] = 0;
        return ph;
      }, FFTM.prototype.mulp = function(x, y, out) {
        var N = 2 * this.guessLen13b(x.length, y.length), rbt = this.makeRBT(N), _ = this.stub(N), rws = Array(N), rwst = Array(N), iwst = Array(N), nrws = Array(N), nrwst = Array(N), niwst = Array(N), rmws = out.words;
        rmws.length = N, this.convert13b(x.words, x.length, rws, N), this.convert13b(y.words, y.length, nrws, N), this.transform(rws, _, rwst, iwst, N, rbt), this.transform(nrws, _, nrwst, niwst, N, rbt);
        for (var i2 = 0;i2 < N; i2++) {
          var rx = rwst[i2] * nrwst[i2] - iwst[i2] * niwst[i2];
          iwst[i2] = rwst[i2] * niwst[i2] + iwst[i2] * nrwst[i2], rwst[i2] = rx;
        }
        return this.conjugate(rwst, iwst, N), this.transform(rwst, iwst, rmws, _, N, rbt), this.conjugate(rmws, _, N), this.normalize13b(rmws, N), out.negative = x.negative ^ y.negative, out.length = x.length + y.length, out.strip();
      }, BN.prototype.mul = function(num) {
        var out = new BN(null);
        return out.words = Array(this.length + num.length), this.mulTo(num, out);
      }, BN.prototype.mulf = function(num) {
        var out = new BN(null);
        return out.words = Array(this.length + num.length), jumboMulTo(this, num, out);
      }, BN.prototype.imul = function(num) {
        return this.clone().mulTo(num, this);
      }, BN.prototype.imuln = function(num) {
        assert(typeof num === "number"), assert(num < 67108864);
        var carry = 0;
        for (var i2 = 0;i2 < this.length; i2++) {
          var w = (this.words[i2] | 0) * num, lo = (w & 67108863) + (carry & 67108863);
          carry >>= 26, carry += w / 67108864 | 0, carry += lo >>> 26, this.words[i2] = lo & 67108863;
        }
        if (carry !== 0)
          this.words[i2] = carry, this.length++;
        return this.length = num === 0 ? 1 : this.length, this;
      }, BN.prototype.muln = function(num) {
        return this.clone().imuln(num);
      }, BN.prototype.sqr = function() {
        return this.mul(this);
      }, BN.prototype.isqr = function() {
        return this.imul(this.clone());
      }, BN.prototype.pow = function(num) {
        var w = toBitArray(num);
        if (w.length === 0)
          return new BN(1);
        var res = this;
        for (var i2 = 0;i2 < w.length; i2++, res = res.sqr())
          if (w[i2] !== 0)
            break;
        if (++i2 < w.length)
          for (var q = res.sqr();i2 < w.length; i2++, q = q.sqr()) {
            if (w[i2] === 0)
              continue;
            res = res.mul(q);
          }
        return res;
      }, BN.prototype.iushln = function(bits) {
        assert(typeof bits === "number" && bits >= 0);
        var r2 = bits % 26, s = (bits - r2) / 26, carryMask = 67108863 >>> 26 - r2 << 26 - r2, i2;
        if (r2 !== 0) {
          var carry = 0;
          for (i2 = 0;i2 < this.length; i2++) {
            var newCarry = this.words[i2] & carryMask, c2 = (this.words[i2] | 0) - newCarry << r2;
            this.words[i2] = c2 | carry, carry = newCarry >>> 26 - r2;
          }
          if (carry)
            this.words[i2] = carry, this.length++;
        }
        if (s !== 0) {
          for (i2 = this.length - 1;i2 >= 0; i2--)
            this.words[i2 + s] = this.words[i2];
          for (i2 = 0;i2 < s; i2++)
            this.words[i2] = 0;
          this.length += s;
        }
        return this.strip();
      }, BN.prototype.ishln = function(bits) {
        return assert(this.negative === 0), this.iushln(bits);
      }, BN.prototype.iushrn = function(bits, hint, extended) {
        assert(typeof bits === "number" && bits >= 0);
        var h;
        if (hint)
          h = (hint - hint % 26) / 26;
        else
          h = 0;
        var r2 = bits % 26, s = Math.min((bits - r2) / 26, this.length), mask = 67108863 ^ 67108863 >>> r2 << r2, maskedWords = extended;
        if (h -= s, h = Math.max(0, h), maskedWords) {
          for (var i2 = 0;i2 < s; i2++)
            maskedWords.words[i2] = this.words[i2];
          maskedWords.length = s;
        }
        if (s === 0)
          ;
        else if (this.length > s) {
          this.length -= s;
          for (i2 = 0;i2 < this.length; i2++)
            this.words[i2] = this.words[i2 + s];
        } else
          this.words[0] = 0, this.length = 1;
        var carry = 0;
        for (i2 = this.length - 1;i2 >= 0 && (carry !== 0 || i2 >= h); i2--) {
          var word = this.words[i2] | 0;
          this.words[i2] = carry << 26 - r2 | word >>> r2, carry = word & mask;
        }
        if (maskedWords && carry !== 0)
          maskedWords.words[maskedWords.length++] = carry;
        if (this.length === 0)
          this.words[0] = 0, this.length = 1;
        return this.strip();
      }, BN.prototype.ishrn = function(bits, hint, extended) {
        return assert(this.negative === 0), this.iushrn(bits, hint, extended);
      }, BN.prototype.shln = function(bits) {
        return this.clone().ishln(bits);
      }, BN.prototype.ushln = function(bits) {
        return this.clone().iushln(bits);
      }, BN.prototype.shrn = function(bits) {
        return this.clone().ishrn(bits);
      }, BN.prototype.ushrn = function(bits) {
        return this.clone().iushrn(bits);
      }, BN.prototype.testn = function(bit) {
        assert(typeof bit === "number" && bit >= 0);
        var r2 = bit % 26, s = (bit - r2) / 26, q = 1 << r2;
        if (this.length <= s)
          return false;
        var w = this.words[s];
        return !!(w & q);
      }, BN.prototype.imaskn = function(bits) {
        assert(typeof bits === "number" && bits >= 0);
        var r2 = bits % 26, s = (bits - r2) / 26;
        if (assert(this.negative === 0, "imaskn works only with positive numbers"), this.length <= s)
          return this;
        if (r2 !== 0)
          s++;
        if (this.length = Math.min(s, this.length), r2 !== 0) {
          var mask = 67108863 ^ 67108863 >>> r2 << r2;
          this.words[this.length - 1] &= mask;
        }
        return this.strip();
      }, BN.prototype.maskn = function(bits) {
        return this.clone().imaskn(bits);
      }, BN.prototype.iaddn = function(num) {
        if (assert(typeof num === "number"), assert(num < 67108864), num < 0)
          return this.isubn(-num);
        if (this.negative !== 0) {
          if (this.length === 1 && (this.words[0] | 0) < num)
            return this.words[0] = num - (this.words[0] | 0), this.negative = 0, this;
          return this.negative = 0, this.isubn(num), this.negative = 1, this;
        }
        return this._iaddn(num);
      }, BN.prototype._iaddn = function(num) {
        this.words[0] += num;
        for (var i2 = 0;i2 < this.length && this.words[i2] >= 67108864; i2++)
          if (this.words[i2] -= 67108864, i2 === this.length - 1)
            this.words[i2 + 1] = 1;
          else
            this.words[i2 + 1]++;
        return this.length = Math.max(this.length, i2 + 1), this;
      }, BN.prototype.isubn = function(num) {
        if (assert(typeof num === "number"), assert(num < 67108864), num < 0)
          return this.iaddn(-num);
        if (this.negative !== 0)
          return this.negative = 0, this.iaddn(num), this.negative = 1, this;
        if (this.words[0] -= num, this.length === 1 && this.words[0] < 0)
          this.words[0] = -this.words[0], this.negative = 1;
        else
          for (var i2 = 0;i2 < this.length && this.words[i2] < 0; i2++)
            this.words[i2] += 67108864, this.words[i2 + 1] -= 1;
        return this.strip();
      }, BN.prototype.addn = function(num) {
        return this.clone().iaddn(num);
      }, BN.prototype.subn = function(num) {
        return this.clone().isubn(num);
      }, BN.prototype.iabs = function() {
        return this.negative = 0, this;
      }, BN.prototype.abs = function() {
        return this.clone().iabs();
      }, BN.prototype._ishlnsubmul = function(num, mul, shift) {
        var len2 = num.length + shift, i2;
        this._expand(len2);
        var w, carry = 0;
        for (i2 = 0;i2 < num.length; i2++) {
          w = (this.words[i2 + shift] | 0) + carry;
          var right = (num.words[i2] | 0) * mul;
          w -= right & 67108863, carry = (w >> 26) - (right / 67108864 | 0), this.words[i2 + shift] = w & 67108863;
        }
        for (;i2 < this.length - shift; i2++)
          w = (this.words[i2 + shift] | 0) + carry, carry = w >> 26, this.words[i2 + shift] = w & 67108863;
        if (carry === 0)
          return this.strip();
        assert(carry === -1), carry = 0;
        for (i2 = 0;i2 < this.length; i2++)
          w = -(this.words[i2] | 0) + carry, carry = w >> 26, this.words[i2] = w & 67108863;
        return this.negative = 1, this.strip();
      }, BN.prototype._wordDiv = function(num, mode) {
        var shift = this.length - num.length, a2 = this.clone(), b = num, bhi = b.words[b.length - 1] | 0, bhiBits = this._countBits(bhi);
        if (shift = 26 - bhiBits, shift !== 0)
          b = b.ushln(shift), a2.iushln(shift), bhi = b.words[b.length - 1] | 0;
        var m = a2.length - b.length, q;
        if (mode !== "mod") {
          q = new BN(null), q.length = m + 1, q.words = Array(q.length);
          for (var i2 = 0;i2 < q.length; i2++)
            q.words[i2] = 0;
        }
        var diff = a2.clone()._ishlnsubmul(b, 1, m);
        if (diff.negative === 0) {
          if (a2 = diff, q)
            q.words[m] = 1;
        }
        for (var j = m - 1;j >= 0; j--) {
          var qj = (a2.words[b.length + j] | 0) * 67108864 + (a2.words[b.length + j - 1] | 0);
          qj = Math.min(qj / bhi | 0, 67108863), a2._ishlnsubmul(b, qj, j);
          while (a2.negative !== 0)
            if (qj--, a2.negative = 0, a2._ishlnsubmul(b, 1, j), !a2.isZero())
              a2.negative ^= 1;
          if (q)
            q.words[j] = qj;
        }
        if (q)
          q.strip();
        if (a2.strip(), mode !== "div" && shift !== 0)
          a2.iushrn(shift);
        return { div: q || null, mod: a2 };
      }, BN.prototype.divmod = function(num, mode, positive) {
        if (assert(!num.isZero()), this.isZero())
          return { div: new BN(0), mod: new BN(0) };
        var div, mod, res;
        if (this.negative !== 0 && num.negative === 0) {
          if (res = this.neg().divmod(num, mode), mode !== "mod")
            div = res.div.neg();
          if (mode !== "div") {
            if (mod = res.mod.neg(), positive && mod.negative !== 0)
              mod.iadd(num);
          }
          return { div, mod };
        }
        if (this.negative === 0 && num.negative !== 0) {
          if (res = this.divmod(num.neg(), mode), mode !== "mod")
            div = res.div.neg();
          return { div, mod: res.mod };
        }
        if ((this.negative & num.negative) !== 0) {
          if (res = this.neg().divmod(num.neg(), mode), mode !== "div") {
            if (mod = res.mod.neg(), positive && mod.negative !== 0)
              mod.isub(num);
          }
          return { div: res.div, mod };
        }
        if (num.length > this.length || this.cmp(num) < 0)
          return { div: new BN(0), mod: this };
        if (num.length === 1) {
          if (mode === "div")
            return { div: this.divn(num.words[0]), mod: null };
          if (mode === "mod")
            return { div: null, mod: new BN(this.modn(num.words[0])) };
          return { div: this.divn(num.words[0]), mod: new BN(this.modn(num.words[0])) };
        }
        return this._wordDiv(num, mode);
      }, BN.prototype.div = function(num) {
        return this.divmod(num, "div", false).div;
      }, BN.prototype.mod = function(num) {
        return this.divmod(num, "mod", false).mod;
      }, BN.prototype.umod = function(num) {
        return this.divmod(num, "mod", true).mod;
      }, BN.prototype.divRound = function(num) {
        var dm = this.divmod(num);
        if (dm.mod.isZero())
          return dm.div;
        var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod, half = num.ushrn(1), r2 = num.andln(1), cmp = mod.cmp(half);
        if (cmp < 0 || r2 === 1 && cmp === 0)
          return dm.div;
        return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
      }, BN.prototype.modn = function(num) {
        assert(num <= 67108863);
        var p2 = 67108864 % num, acc = 0;
        for (var i2 = this.length - 1;i2 >= 0; i2--)
          acc = (p2 * acc + (this.words[i2] | 0)) % num;
        return acc;
      }, BN.prototype.idivn = function(num) {
        assert(num <= 67108863);
        var carry = 0;
        for (var i2 = this.length - 1;i2 >= 0; i2--) {
          var w = (this.words[i2] | 0) + carry * 67108864;
          this.words[i2] = w / num | 0, carry = w % num;
        }
        return this.strip();
      }, BN.prototype.divn = function(num) {
        return this.clone().idivn(num);
      }, BN.prototype.egcd = function(p2) {
        assert(p2.negative === 0), assert(!p2.isZero());
        var x = this, y = p2.clone();
        if (x.negative !== 0)
          x = x.umod(p2);
        else
          x = x.clone();
        var A = new BN(1), B = new BN(0), C = new BN(0), D = new BN(1), g = 0;
        while (x.isEven() && y.isEven())
          x.iushrn(1), y.iushrn(1), ++g;
        var yp = y.clone(), xp = x.clone();
        while (!x.isZero()) {
          for (var i2 = 0, im = 1;(x.words[0] & im) === 0 && i2 < 26; ++i2, im <<= 1)
            ;
          if (i2 > 0) {
            x.iushrn(i2);
            while (i2-- > 0) {
              if (A.isOdd() || B.isOdd())
                A.iadd(yp), B.isub(xp);
              A.iushrn(1), B.iushrn(1);
            }
          }
          for (var j = 0, jm = 1;(y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1)
            ;
          if (j > 0) {
            y.iushrn(j);
            while (j-- > 0) {
              if (C.isOdd() || D.isOdd())
                C.iadd(yp), D.isub(xp);
              C.iushrn(1), D.iushrn(1);
            }
          }
          if (x.cmp(y) >= 0)
            x.isub(y), A.isub(C), B.isub(D);
          else
            y.isub(x), C.isub(A), D.isub(B);
        }
        return { a: C, b: D, gcd: y.iushln(g) };
      }, BN.prototype._invmp = function(p2) {
        assert(p2.negative === 0), assert(!p2.isZero());
        var a2 = this, b = p2.clone();
        if (a2.negative !== 0)
          a2 = a2.umod(p2);
        else
          a2 = a2.clone();
        var x1 = new BN(1), x2 = new BN(0), delta = b.clone();
        while (a2.cmpn(1) > 0 && b.cmpn(1) > 0) {
          for (var i2 = 0, im = 1;(a2.words[0] & im) === 0 && i2 < 26; ++i2, im <<= 1)
            ;
          if (i2 > 0) {
            a2.iushrn(i2);
            while (i2-- > 0) {
              if (x1.isOdd())
                x1.iadd(delta);
              x1.iushrn(1);
            }
          }
          for (var j = 0, jm = 1;(b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1)
            ;
          if (j > 0) {
            b.iushrn(j);
            while (j-- > 0) {
              if (x2.isOdd())
                x2.iadd(delta);
              x2.iushrn(1);
            }
          }
          if (a2.cmp(b) >= 0)
            a2.isub(b), x1.isub(x2);
          else
            b.isub(a2), x2.isub(x1);
        }
        var res;
        if (a2.cmpn(1) === 0)
          res = x1;
        else
          res = x2;
        if (res.cmpn(0) < 0)
          res.iadd(p2);
        return res;
      }, BN.prototype.gcd = function(num) {
        if (this.isZero())
          return num.abs();
        if (num.isZero())
          return this.abs();
        var a2 = this.clone(), b = num.clone();
        a2.negative = 0, b.negative = 0;
        for (var shift = 0;a2.isEven() && b.isEven(); shift++)
          a2.iushrn(1), b.iushrn(1);
        do {
          while (a2.isEven())
            a2.iushrn(1);
          while (b.isEven())
            b.iushrn(1);
          var r2 = a2.cmp(b);
          if (r2 < 0) {
            var t2 = a2;
            a2 = b, b = t2;
          } else if (r2 === 0 || b.cmpn(1) === 0)
            break;
          a2.isub(b);
        } while (true);
        return b.iushln(shift);
      }, BN.prototype.invm = function(num) {
        return this.egcd(num).a.umod(num);
      }, BN.prototype.isEven = function() {
        return (this.words[0] & 1) === 0;
      }, BN.prototype.isOdd = function() {
        return (this.words[0] & 1) === 1;
      }, BN.prototype.andln = function(num) {
        return this.words[0] & num;
      }, BN.prototype.bincn = function(bit) {
        assert(typeof bit === "number");
        var r2 = bit % 26, s = (bit - r2) / 26, q = 1 << r2;
        if (this.length <= s)
          return this._expand(s + 1), this.words[s] |= q, this;
        var carry = q;
        for (var i2 = s;carry !== 0 && i2 < this.length; i2++) {
          var w = this.words[i2] | 0;
          w += carry, carry = w >>> 26, w &= 67108863, this.words[i2] = w;
        }
        if (carry !== 0)
          this.words[i2] = carry, this.length++;
        return this;
      }, BN.prototype.isZero = function() {
        return this.length === 1 && this.words[0] === 0;
      }, BN.prototype.cmpn = function(num) {
        var negative = num < 0;
        if (this.negative !== 0 && !negative)
          return -1;
        if (this.negative === 0 && negative)
          return 1;
        this.strip();
        var res;
        if (this.length > 1)
          res = 1;
        else {
          if (negative)
            num = -num;
          assert(num <= 67108863, "Number is too big");
          var w = this.words[0] | 0;
          res = w === num ? 0 : w < num ? -1 : 1;
        }
        if (this.negative !== 0)
          return -res | 0;
        return res;
      }, BN.prototype.cmp = function(num) {
        if (this.negative !== 0 && num.negative === 0)
          return -1;
        if (this.negative === 0 && num.negative !== 0)
          return 1;
        var res = this.ucmp(num);
        if (this.negative !== 0)
          return -res | 0;
        return res;
      }, BN.prototype.ucmp = function(num) {
        if (this.length > num.length)
          return 1;
        if (this.length < num.length)
          return -1;
        var res = 0;
        for (var i2 = this.length - 1;i2 >= 0; i2--) {
          var a2 = this.words[i2] | 0, b = num.words[i2] | 0;
          if (a2 === b)
            continue;
          if (a2 < b)
            res = -1;
          else if (a2 > b)
            res = 1;
          break;
        }
        return res;
      }, BN.prototype.gtn = function(num) {
        return this.cmpn(num) === 1;
      }, BN.prototype.gt = function(num) {
        return this.cmp(num) === 1;
      }, BN.prototype.gten = function(num) {
        return this.cmpn(num) >= 0;
      }, BN.prototype.gte = function(num) {
        return this.cmp(num) >= 0;
      }, BN.prototype.ltn = function(num) {
        return this.cmpn(num) === -1;
      }, BN.prototype.lt = function(num) {
        return this.cmp(num) === -1;
      }, BN.prototype.lten = function(num) {
        return this.cmpn(num) <= 0;
      }, BN.prototype.lte = function(num) {
        return this.cmp(num) <= 0;
      }, BN.prototype.eqn = function(num) {
        return this.cmpn(num) === 0;
      }, BN.prototype.eq = function(num) {
        return this.cmp(num) === 0;
      }, BN.red = function(num) {
        return new Red(num);
      }, BN.prototype.toRed = function(ctx) {
        return assert(!this.red, "Already a number in reduction context"), assert(this.negative === 0, "red works only with positives"), ctx.convertTo(this)._forceRed(ctx);
      }, BN.prototype.fromRed = function() {
        return assert(this.red, "fromRed works only with numbers in reduction context"), this.red.convertFrom(this);
      }, BN.prototype._forceRed = function(ctx) {
        return this.red = ctx, this;
      }, BN.prototype.forceRed = function(ctx) {
        return assert(!this.red, "Already a number in reduction context"), this._forceRed(ctx);
      }, BN.prototype.redAdd = function(num) {
        return assert(this.red, "redAdd works only with red numbers"), this.red.add(this, num);
      }, BN.prototype.redIAdd = function(num) {
        return assert(this.red, "redIAdd works only with red numbers"), this.red.iadd(this, num);
      }, BN.prototype.redSub = function(num) {
        return assert(this.red, "redSub works only with red numbers"), this.red.sub(this, num);
      }, BN.prototype.redISub = function(num) {
        return assert(this.red, "redISub works only with red numbers"), this.red.isub(this, num);
      }, BN.prototype.redShl = function(num) {
        return assert(this.red, "redShl works only with red numbers"), this.red.shl(this, num);
      }, BN.prototype.redMul = function(num) {
        return assert(this.red, "redMul works only with red numbers"), this.red._verify2(this, num), this.red.mul(this, num);
      }, BN.prototype.redIMul = function(num) {
        return assert(this.red, "redMul works only with red numbers"), this.red._verify2(this, num), this.red.imul(this, num);
      }, BN.prototype.redSqr = function() {
        return assert(this.red, "redSqr works only with red numbers"), this.red._verify1(this), this.red.sqr(this);
      }, BN.prototype.redISqr = function() {
        return assert(this.red, "redISqr works only with red numbers"), this.red._verify1(this), this.red.isqr(this);
      }, BN.prototype.redSqrt = function() {
        return assert(this.red, "redSqrt works only with red numbers"), this.red._verify1(this), this.red.sqrt(this);
      }, BN.prototype.redInvm = function() {
        return assert(this.red, "redInvm works only with red numbers"), this.red._verify1(this), this.red.invm(this);
      }, BN.prototype.redNeg = function() {
        return assert(this.red, "redNeg works only with red numbers"), this.red._verify1(this), this.red.neg(this);
      }, BN.prototype.redPow = function(num) {
        return assert(this.red && !num.red, "redPow(normalNum)"), this.red._verify1(this), this.red.pow(this, num);
      };
      var primes = { k256: null, p224: null, p192: null, p25519: null };
      function MPrime(name, p2) {
        this.name = name, this.p = new BN(p2, 16), this.n = this.p.bitLength(), this.k = new BN(1).iushln(this.n).isub(this.p), this.tmp = this._tmp();
      }
      MPrime.prototype._tmp = function() {
        var tmp = new BN(null);
        return tmp.words = Array(Math.ceil(this.n / 13)), tmp;
      }, MPrime.prototype.ireduce = function(num) {
        var r2 = num, rlen;
        do
          this.split(r2, this.tmp), r2 = this.imulK(r2), r2 = r2.iadd(this.tmp), rlen = r2.bitLength();
        while (rlen > this.n);
        var cmp = rlen < this.n ? -1 : r2.ucmp(this.p);
        if (cmp === 0)
          r2.words[0] = 0, r2.length = 1;
        else if (cmp > 0)
          r2.isub(this.p);
        else if (r2.strip !== undefined)
          r2.strip();
        else
          r2._strip();
        return r2;
      }, MPrime.prototype.split = function(input, out) {
        input.iushrn(this.n, 0, out);
      }, MPrime.prototype.imulK = function(num) {
        return num.imul(this.k);
      };
      function K256() {
        MPrime.call(this, "k256", "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f");
      }
      inherits2(K256, MPrime), K256.prototype.split = function(input, output) {
        var mask = 4194303, outLen = Math.min(input.length, 9);
        for (var i2 = 0;i2 < outLen; i2++)
          output.words[i2] = input.words[i2];
        if (output.length = outLen, input.length <= 9) {
          input.words[0] = 0, input.length = 1;
          return;
        }
        var prev = input.words[9];
        output.words[output.length++] = prev & mask;
        for (i2 = 10;i2 < input.length; i2++) {
          var next = input.words[i2] | 0;
          input.words[i2 - 10] = (next & mask) << 4 | prev >>> 22, prev = next;
        }
        if (prev >>>= 22, input.words[i2 - 10] = prev, prev === 0 && input.length > 10)
          input.length -= 10;
        else
          input.length -= 9;
      }, K256.prototype.imulK = function(num) {
        num.words[num.length] = 0, num.words[num.length + 1] = 0, num.length += 2;
        var lo = 0;
        for (var i2 = 0;i2 < num.length; i2++) {
          var w = num.words[i2] | 0;
          lo += w * 977, num.words[i2] = lo & 67108863, lo = w * 64 + (lo / 67108864 | 0);
        }
        if (num.words[num.length - 1] === 0) {
          if (num.length--, num.words[num.length - 1] === 0)
            num.length--;
        }
        return num;
      };
      function P224() {
        MPrime.call(this, "p224", "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001");
      }
      inherits2(P224, MPrime);
      function P192() {
        MPrime.call(this, "p192", "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff");
      }
      inherits2(P192, MPrime);
      function P25519() {
        MPrime.call(this, "25519", "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed");
      }
      inherits2(P25519, MPrime), P25519.prototype.imulK = function(num) {
        var carry = 0;
        for (var i2 = 0;i2 < num.length; i2++) {
          var hi = (num.words[i2] | 0) * 19 + carry, lo = hi & 67108863;
          hi >>>= 26, num.words[i2] = lo, carry = hi;
        }
        if (carry !== 0)
          num.words[num.length++] = carry;
        return num;
      }, BN._prime = function(name) {
        if (primes[name])
          return primes[name];
        var prime;
        if (name === "k256")
          prime = new K256;
        else if (name === "p224")
          prime = new P224;
        else if (name === "p192")
          prime = new P192;
        else if (name === "p25519")
          prime = new P25519;
        else
          throw Error("Unknown prime " + name);
        return primes[name] = prime, prime;
      };
      function Red(m) {
        if (typeof m === "string") {
          var prime = BN._prime(m);
          this.m = prime.p, this.prime = prime;
        } else
          assert(m.gtn(1), "modulus must be greater than 1"), this.m = m, this.prime = null;
      }
      Red.prototype._verify1 = function(a2) {
        assert(a2.negative === 0, "red works only with positives"), assert(a2.red, "red works only with red numbers");
      }, Red.prototype._verify2 = function(a2, b) {
        assert((a2.negative | b.negative) === 0, "red works only with positives"), assert(a2.red && a2.red === b.red, "red works only with red numbers");
      }, Red.prototype.imod = function(a2) {
        if (this.prime)
          return this.prime.ireduce(a2)._forceRed(this);
        return a2.umod(this.m)._forceRed(this);
      }, Red.prototype.neg = function(a2) {
        if (a2.isZero())
          return a2.clone();
        return this.m.sub(a2)._forceRed(this);
      }, Red.prototype.add = function(a2, b) {
        this._verify2(a2, b);
        var res = a2.add(b);
        if (res.cmp(this.m) >= 0)
          res.isub(this.m);
        return res._forceRed(this);
      }, Red.prototype.iadd = function(a2, b) {
        this._verify2(a2, b);
        var res = a2.iadd(b);
        if (res.cmp(this.m) >= 0)
          res.isub(this.m);
        return res;
      }, Red.prototype.sub = function(a2, b) {
        this._verify2(a2, b);
        var res = a2.sub(b);
        if (res.cmpn(0) < 0)
          res.iadd(this.m);
        return res._forceRed(this);
      }, Red.prototype.isub = function(a2, b) {
        this._verify2(a2, b);
        var res = a2.isub(b);
        if (res.cmpn(0) < 0)
          res.iadd(this.m);
        return res;
      }, Red.prototype.shl = function(a2, num) {
        return this._verify1(a2), this.imod(a2.ushln(num));
      }, Red.prototype.imul = function(a2, b) {
        return this._verify2(a2, b), this.imod(a2.imul(b));
      }, Red.prototype.mul = function(a2, b) {
        return this._verify2(a2, b), this.imod(a2.mul(b));
      }, Red.prototype.isqr = function(a2) {
        return this.imul(a2, a2.clone());
      }, Red.prototype.sqr = function(a2) {
        return this.mul(a2, a2);
      }, Red.prototype.sqrt = function(a2) {
        if (a2.isZero())
          return a2.clone();
        var mod3 = this.m.andln(3);
        if (assert(mod3 % 2 === 1), mod3 === 3) {
          var pow = this.m.add(new BN(1)).iushrn(2);
          return this.pow(a2, pow);
        }
        var q = this.m.subn(1), s = 0;
        while (!q.isZero() && q.andln(1) === 0)
          s++, q.iushrn(1);
        assert(!q.isZero());
        var one = new BN(1).toRed(this), nOne = one.redNeg(), lpow = this.m.subn(1).iushrn(1), z = this.m.bitLength();
        z = new BN(2 * z * z).toRed(this);
        while (this.pow(z, lpow).cmp(nOne) !== 0)
          z.redIAdd(nOne);
        var c2 = this.pow(z, q), r2 = this.pow(a2, q.addn(1).iushrn(1)), t2 = this.pow(a2, q), m = s;
        while (t2.cmp(one) !== 0) {
          var tmp = t2;
          for (var i2 = 0;tmp.cmp(one) !== 0; i2++)
            tmp = tmp.redSqr();
          assert(i2 < m);
          var b = this.pow(c2, new BN(1).iushln(m - i2 - 1));
          r2 = r2.redMul(b), c2 = b.redSqr(), t2 = t2.redMul(c2), m = i2;
        }
        return r2;
      }, Red.prototype.invm = function(a2) {
        var inv = a2._invmp(this.m);
        if (inv.negative !== 0)
          return inv.negative = 0, this.imod(inv).redNeg();
        else
          return this.imod(inv);
      }, Red.prototype.pow = function(a2, num) {
        if (num.isZero())
          return new BN(1).toRed(this);
        if (num.cmpn(1) === 0)
          return a2.clone();
        var windowSize = 4, wnd = Array(1 << windowSize);
        wnd[0] = new BN(1).toRed(this), wnd[1] = a2;
        for (var i2 = 2;i2 < wnd.length; i2++)
          wnd[i2] = this.mul(wnd[i2 - 1], a2);
        var res = wnd[0], current = 0, currentLen = 0, start = num.bitLength() % 26;
        if (start === 0)
          start = 26;
        for (i2 = num.length - 1;i2 >= 0; i2--) {
          var word = num.words[i2];
          for (var j = start - 1;j >= 0; j--) {
            var bit = word >> j & 1;
            if (res !== wnd[0])
              res = this.sqr(res);
            if (bit === 0 && current === 0) {
              currentLen = 0;
              continue;
            }
            if (current <<= 1, current |= bit, currentLen++, currentLen !== windowSize && (i2 !== 0 || j !== 0))
              continue;
            res = this.mul(res, wnd[current]), currentLen = 0, current = 0;
          }
          start = 26;
        }
        return res;
      }, Red.prototype.convertTo = function(num) {
        var r2 = num.umod(this.m);
        return r2 === num ? r2.clone() : r2;
      }, Red.prototype.convertFrom = function(num) {
        var res = num.clone();
        return res.red = null, res;
      }, BN.mont = function(num) {
        return new Mont(num);
      };
      function Mont(m) {
        if (Red.call(this, m), this.shift = this.m.bitLength(), this.shift % 26 !== 0)
          this.shift += 26 - this.shift % 26;
        this.r = new BN(1).iushln(this.shift), this.r2 = this.imod(this.r.sqr()), this.rinv = this.r._invmp(this.m), this.minv = this.rinv.mul(this.r).isubn(1).div(this.m), this.minv = this.minv.umod(this.r), this.minv = this.r.sub(this.minv);
      }
      inherits2(Mont, Red), Mont.prototype.convertTo = function(num) {
        return this.imod(num.ushln(this.shift));
      }, Mont.prototype.convertFrom = function(num) {
        var r2 = this.imod(num.mul(this.rinv));
        return r2.red = null, r2;
      }, Mont.prototype.imul = function(a2, b) {
        if (a2.isZero() || b.isZero())
          return a2.words[0] = 0, a2.length = 1, a2;
        var t2 = a2.imul(b), c2 = t2.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), u = t2.isub(c2).iushrn(this.shift), res = u;
        if (u.cmp(this.m) >= 0)
          res = u.isub(this.m);
        else if (u.cmpn(0) < 0)
          res = u.iadd(this.m);
        return res._forceRed(this);
      }, Mont.prototype.mul = function(a2, b) {
        if (a2.isZero() || b.isZero())
          return new BN(0)._forceRed(this);
        var t2 = a2.mul(b), c2 = t2.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), u = t2.isub(c2).iushrn(this.shift), res = u;
        if (u.cmp(this.m) >= 0)
          res = u.isub(this.m);
        else if (u.cmpn(0) < 0)
          res = u.iadd(this.m);
        return res._forceRed(this);
      }, Mont.prototype.invm = function(a2) {
        var res = this.imod(a2._invmp(this.m).mul(this.r2));
        return res._forceRed(this);
      };
    })(typeof module > "u" || module, exports);
  });
  require_minimalistic_assert = __commonJS2((exports, module) => {
    module.exports = assert;
    function assert(val, msg) {
      if (!val)
        throw Error(msg || "Assertion failed");
    }
    assert.equal = function(l2, r2, msg) {
      if (l2 != r2)
        throw Error(msg || "Assertion failed: " + l2 + " != " + r2);
    };
  });
  require_utils = __commonJS2((exports) => {
    var utils = exports;
    function toArray(msg, enc) {
      if (Array.isArray(msg))
        return msg.slice();
      if (!msg)
        return [];
      var res = [];
      if (typeof msg !== "string") {
        for (var i2 = 0;i2 < msg.length; i2++)
          res[i2] = msg[i2] | 0;
        return res;
      }
      if (enc === "hex") {
        if (msg = msg.replace(/[^a-z0-9]+/ig, ""), msg.length % 2 !== 0)
          msg = "0" + msg;
        for (var i2 = 0;i2 < msg.length; i2 += 2)
          res.push(parseInt(msg[i2] + msg[i2 + 1], 16));
      } else
        for (var i2 = 0;i2 < msg.length; i2++) {
          var c2 = msg.charCodeAt(i2), hi = c2 >> 8, lo = c2 & 255;
          if (hi)
            res.push(hi, lo);
          else
            res.push(lo);
        }
      return res;
    }
    utils.toArray = toArray;
    function zero2(word) {
      if (word.length === 1)
        return "0" + word;
      else
        return word;
    }
    utils.zero2 = zero2;
    function toHex(msg) {
      var res = "";
      for (var i2 = 0;i2 < msg.length; i2++)
        res += zero2(msg[i2].toString(16));
      return res;
    }
    utils.toHex = toHex;
    utils.encode = function(arr, enc) {
      if (enc === "hex")
        return toHex(arr);
      else
        return arr;
    };
  });
  require_utils2 = __commonJS2((exports) => {
    var utils = exports, BN = require_bn(), minAssert = require_minimalistic_assert(), minUtils = require_utils();
    utils.assert = minAssert;
    utils.toArray = minUtils.toArray;
    utils.zero2 = minUtils.zero2;
    utils.toHex = minUtils.toHex;
    utils.encode = minUtils.encode;
    function getNAF(num, w, bits) {
      var naf = Array(Math.max(num.bitLength(), bits) + 1), i2;
      for (i2 = 0;i2 < naf.length; i2 += 1)
        naf[i2] = 0;
      var ws = 1 << w + 1, k = num.clone();
      for (i2 = 0;i2 < naf.length; i2++) {
        var z, mod = k.andln(ws - 1);
        if (k.isOdd()) {
          if (mod > (ws >> 1) - 1)
            z = (ws >> 1) - mod;
          else
            z = mod;
          k.isubn(z);
        } else
          z = 0;
        naf[i2] = z, k.iushrn(1);
      }
      return naf;
    }
    utils.getNAF = getNAF;
    function getJSF(k1, k2) {
      var jsf = [[], []];
      k1 = k1.clone(), k2 = k2.clone();
      var d1 = 0, d2 = 0, m8;
      while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) {
        var m14 = k1.andln(3) + d1 & 3, m24 = k2.andln(3) + d2 & 3;
        if (m14 === 3)
          m14 = -1;
        if (m24 === 3)
          m24 = -1;
        var u1;
        if ((m14 & 1) === 0)
          u1 = 0;
        else if (m8 = k1.andln(7) + d1 & 7, (m8 === 3 || m8 === 5) && m24 === 2)
          u1 = -m14;
        else
          u1 = m14;
        jsf[0].push(u1);
        var u2;
        if ((m24 & 1) === 0)
          u2 = 0;
        else if (m8 = k2.andln(7) + d2 & 7, (m8 === 3 || m8 === 5) && m14 === 2)
          u2 = -m24;
        else
          u2 = m24;
        if (jsf[1].push(u2), 2 * d1 === u1 + 1)
          d1 = 1 - d1;
        if (2 * d2 === u2 + 1)
          d2 = 1 - d2;
        k1.iushrn(1), k2.iushrn(1);
      }
      return jsf;
    }
    utils.getJSF = getJSF;
    function cachedProperty(obj, name, computer) {
      var key = "_" + name;
      obj.prototype[name] = function() {
        return this[key] !== undefined ? this[key] : this[key] = computer.call(this);
      };
    }
    utils.cachedProperty = cachedProperty;
    function parseBytes(bytes) {
      return typeof bytes === "string" ? utils.toArray(bytes, "hex") : bytes;
    }
    utils.parseBytes = parseBytes;
    function intFromLE(bytes) {
      return new BN(bytes, "hex", "le");
    }
    utils.intFromLE = intFromLE;
  });
  require_brorand = __commonJS2((exports, module) => {
    var r2;
    module.exports = function(len2) {
      if (!r2)
        r2 = new Rand(null);
      return r2.generate(len2);
    };
    function Rand(rand) {
      this.rand = rand;
    }
    module.exports.Rand = Rand;
    Rand.prototype.generate = function(len2) {
      return this._rand(len2);
    };
    Rand.prototype._rand = function(n2) {
      if (this.rand.getBytes)
        return this.rand.getBytes(n2);
      var res = new Uint8Array(n2);
      for (var i2 = 0;i2 < res.length; i2++)
        res[i2] = this.rand.getByte();
      return res;
    };
    if (typeof self === "object") {
      if (self.crypto && self.crypto.getRandomValues)
        Rand.prototype._rand = function(n2) {
          var arr = new Uint8Array(n2);
          return self.crypto.getRandomValues(arr), arr;
        };
      else if (self.msCrypto && self.msCrypto.getRandomValues)
        Rand.prototype._rand = function(n2) {
          var arr = new Uint8Array(n2);
          return self.msCrypto.getRandomValues(arr), arr;
        };
      else if (typeof window === "object")
        Rand.prototype._rand = function() {
          throw Error("Not implemented yet");
        };
    } else
      try {
        if (crypto2 = (init_crypto(), __toCommonJS(exports_crypto)), typeof crypto2.randomBytes !== "function")
          throw Error("Not supported");
        Rand.prototype._rand = function(n2) {
          return crypto2.randomBytes(n2);
        };
      } catch (e2) {}
    var crypto2;
  });
  require_base = __commonJS2((exports, module) => {
    var BN = require_bn(), utils = require_utils2(), getNAF = utils.getNAF, getJSF = utils.getJSF, assert = utils.assert;
    function BaseCurve(type, conf) {
      this.type = type, this.p = new BN(conf.p, 16), this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p), this.zero = new BN(0).toRed(this.red), this.one = new BN(1).toRed(this.red), this.two = new BN(2).toRed(this.red), this.n = conf.n && new BN(conf.n, 16), this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed), this._wnafT1 = [, , , ,], this._wnafT2 = [, , , ,], this._wnafT3 = [, , , ,], this._wnafT4 = [, , , ,], this._bitLength = this.n ? this.n.bitLength() : 0;
      var adjustCount = this.n && this.p.div(this.n);
      if (!adjustCount || adjustCount.cmpn(100) > 0)
        this.redN = null;
      else
        this._maxwellTrick = true, this.redN = this.n.toRed(this.red);
    }
    module.exports = BaseCurve;
    BaseCurve.prototype.point = function() {
      throw Error("Not implemented");
    };
    BaseCurve.prototype.validate = function() {
      throw Error("Not implemented");
    };
    BaseCurve.prototype._fixedNafMul = function(p2, k) {
      assert(p2.precomputed);
      var doubles = p2._getDoubles(), naf = getNAF(k, 1, this._bitLength), I = (1 << doubles.step + 1) - (doubles.step % 2 === 0 ? 2 : 1);
      I /= 3;
      var repr = [], j, nafW;
      for (j = 0;j < naf.length; j += doubles.step) {
        nafW = 0;
        for (var l2 = j + doubles.step - 1;l2 >= j; l2--)
          nafW = (nafW << 1) + naf[l2];
        repr.push(nafW);
      }
      var a2 = this.jpoint(null, null, null), b = this.jpoint(null, null, null);
      for (var i2 = I;i2 > 0; i2--) {
        for (j = 0;j < repr.length; j++)
          if (nafW = repr[j], nafW === i2)
            b = b.mixedAdd(doubles.points[j]);
          else if (nafW === -i2)
            b = b.mixedAdd(doubles.points[j].neg());
        a2 = a2.add(b);
      }
      return a2.toP();
    };
    BaseCurve.prototype._wnafMul = function(p2, k) {
      var w = 4, nafPoints = p2._getNAFPoints(w);
      w = nafPoints.wnd;
      var wnd = nafPoints.points, naf = getNAF(k, w, this._bitLength), acc = this.jpoint(null, null, null);
      for (var i2 = naf.length - 1;i2 >= 0; i2--) {
        for (var l2 = 0;i2 >= 0 && naf[i2] === 0; i2--)
          l2++;
        if (i2 >= 0)
          l2++;
        if (acc = acc.dblp(l2), i2 < 0)
          break;
        var z = naf[i2];
        if (assert(z !== 0), p2.type === "affine")
          if (z > 0)
            acc = acc.mixedAdd(wnd[z - 1 >> 1]);
          else
            acc = acc.mixedAdd(wnd[-z - 1 >> 1].neg());
        else if (z > 0)
          acc = acc.add(wnd[z - 1 >> 1]);
        else
          acc = acc.add(wnd[-z - 1 >> 1].neg());
      }
      return p2.type === "affine" ? acc.toP() : acc;
    };
    BaseCurve.prototype._wnafMulAdd = function(defW, points, coeffs, len2, jacobianResult) {
      var wndWidth = this._wnafT1, wnd = this._wnafT2, naf = this._wnafT3, max = 0, i2, j, p2;
      for (i2 = 0;i2 < len2; i2++) {
        p2 = points[i2];
        var nafPoints = p2._getNAFPoints(defW);
        wndWidth[i2] = nafPoints.wnd, wnd[i2] = nafPoints.points;
      }
      for (i2 = len2 - 1;i2 >= 1; i2 -= 2) {
        var a2 = i2 - 1, b = i2;
        if (wndWidth[a2] !== 1 || wndWidth[b] !== 1) {
          naf[a2] = getNAF(coeffs[a2], wndWidth[a2], this._bitLength), naf[b] = getNAF(coeffs[b], wndWidth[b], this._bitLength), max = Math.max(naf[a2].length, max), max = Math.max(naf[b].length, max);
          continue;
        }
        var comb = [points[a2], null, null, points[b]];
        if (points[a2].y.cmp(points[b].y) === 0)
          comb[1] = points[a2].add(points[b]), comb[2] = points[a2].toJ().mixedAdd(points[b].neg());
        else if (points[a2].y.cmp(points[b].y.redNeg()) === 0)
          comb[1] = points[a2].toJ().mixedAdd(points[b]), comb[2] = points[a2].add(points[b].neg());
        else
          comb[1] = points[a2].toJ().mixedAdd(points[b]), comb[2] = points[a2].toJ().mixedAdd(points[b].neg());
        var index = [-3, -1, -5, -7, 0, 7, 5, 1, 3], jsf = getJSF(coeffs[a2], coeffs[b]);
        max = Math.max(jsf[0].length, max), naf[a2] = Array(max), naf[b] = Array(max);
        for (j = 0;j < max; j++) {
          var ja = jsf[0][j] | 0, jb = jsf[1][j] | 0;
          naf[a2][j] = index[(ja + 1) * 3 + (jb + 1)], naf[b][j] = 0, wnd[a2] = comb;
        }
      }
      var acc = this.jpoint(null, null, null), tmp = this._wnafT4;
      for (i2 = max;i2 >= 0; i2--) {
        var k = 0;
        while (i2 >= 0) {
          var zero = true;
          for (j = 0;j < len2; j++)
            if (tmp[j] = naf[j][i2] | 0, tmp[j] !== 0)
              zero = false;
          if (!zero)
            break;
          k++, i2--;
        }
        if (i2 >= 0)
          k++;
        if (acc = acc.dblp(k), i2 < 0)
          break;
        for (j = 0;j < len2; j++) {
          var z = tmp[j];
          if (z === 0)
            continue;
          else if (z > 0)
            p2 = wnd[j][z - 1 >> 1];
          else if (z < 0)
            p2 = wnd[j][-z - 1 >> 1].neg();
          if (p2.type === "affine")
            acc = acc.mixedAdd(p2);
          else
            acc = acc.add(p2);
        }
      }
      for (i2 = 0;i2 < len2; i2++)
        wnd[i2] = null;
      if (jacobianResult)
        return acc;
      else
        return acc.toP();
    };
    function BasePoint(curve, type) {
      this.curve = curve, this.type = type, this.precomputed = null;
    }
    BaseCurve.BasePoint = BasePoint;
    BasePoint.prototype.eq = function() {
      throw Error("Not implemented");
    };
    BasePoint.prototype.validate = function() {
      return this.curve.validate(this);
    };
    BaseCurve.prototype.decodePoint = function(bytes, enc) {
      bytes = utils.toArray(bytes, enc);
      var len2 = this.p.byteLength();
      if ((bytes[0] === 4 || bytes[0] === 6 || bytes[0] === 7) && bytes.length - 1 === 2 * len2) {
        if (bytes[0] === 6)
          assert(bytes[bytes.length - 1] % 2 === 0);
        else if (bytes[0] === 7)
          assert(bytes[bytes.length - 1] % 2 === 1);
        var res = this.point(bytes.slice(1, 1 + len2), bytes.slice(1 + len2, 1 + 2 * len2));
        return res;
      } else if ((bytes[0] === 2 || bytes[0] === 3) && bytes.length - 1 === len2)
        return this.pointFromX(bytes.slice(1, 1 + len2), bytes[0] === 3);
      throw Error("Unknown point format");
    };
    BasePoint.prototype.encodeCompressed = function(enc) {
      return this.encode(enc, true);
    };
    BasePoint.prototype._encode = function(compact) {
      var len2 = this.curve.p.byteLength(), x = this.getX().toArray("be", len2);
      if (compact)
        return [this.getY().isEven() ? 2 : 3].concat(x);
      return [4].concat(x, this.getY().toArray("be", len2));
    };
    BasePoint.prototype.encode = function(enc, compact) {
      return utils.encode(this._encode(compact), enc);
    };
    BasePoint.prototype.precompute = function(power) {
      if (this.precomputed)
        return this;
      var precomputed = { doubles: null, naf: null, beta: null };
      return precomputed.naf = this._getNAFPoints(8), precomputed.doubles = this._getDoubles(4, power), precomputed.beta = this._getBeta(), this.precomputed = precomputed, this;
    };
    BasePoint.prototype._hasDoubles = function(k) {
      if (!this.precomputed)
        return false;
      var doubles = this.precomputed.doubles;
      if (!doubles)
        return false;
      return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step);
    };
    BasePoint.prototype._getDoubles = function(step, power) {
      if (this.precomputed && this.precomputed.doubles)
        return this.precomputed.doubles;
      var doubles = [this], acc = this;
      for (var i2 = 0;i2 < power; i2 += step) {
        for (var j = 0;j < step; j++)
          acc = acc.dbl();
        doubles.push(acc);
      }
      return { step, points: doubles };
    };
    BasePoint.prototype._getNAFPoints = function(wnd) {
      if (this.precomputed && this.precomputed.naf)
        return this.precomputed.naf;
      var res = [this], max = (1 << wnd) - 1, dbl = max === 1 ? null : this.dbl();
      for (var i2 = 1;i2 < max; i2++)
        res[i2] = res[i2 - 1].add(dbl);
      return { wnd, points: res };
    };
    BasePoint.prototype._getBeta = function() {
      return null;
    };
    BasePoint.prototype.dblp = function(k) {
      var r2 = this;
      for (var i2 = 0;i2 < k; i2++)
        r2 = r2.dbl();
      return r2;
    };
  });
  require_inherits_browser = __commonJS2((exports, module) => {
    if (typeof Object.create === "function")
      module.exports = function(ctor, superCtor) {
        if (superCtor)
          ctor.super_ = superCtor, ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } });
      };
    else
      module.exports = function(ctor, superCtor) {
        if (superCtor) {
          ctor.super_ = superCtor;
          var TempCtor = function() {};
          TempCtor.prototype = superCtor.prototype, ctor.prototype = new TempCtor, ctor.prototype.constructor = ctor;
        }
      };
  });
  require_inherits = __commonJS2((exports, module) => {
    try {
      if (util = (init_util(), __toCommonJS(exports_util)), typeof util.inherits !== "function")
        throw "";
      module.exports = util.inherits;
    } catch (e2) {
      module.exports = require_inherits_browser();
    }
    var util;
  });
  require_short = __commonJS2((exports, module) => {
    var utils = require_utils2(), BN = require_bn(), inherits2 = require_inherits(), Base = require_base(), assert = utils.assert;
    function ShortCurve(conf) {
      Base.call(this, "short", conf), this.a = new BN(conf.a, 16).toRed(this.red), this.b = new BN(conf.b, 16).toRed(this.red), this.tinv = this.two.redInvm(), this.zeroA = this.a.fromRed().cmpn(0) === 0, this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0, this.endo = this._getEndomorphism(conf), this._endoWnafT1 = [, , , ,], this._endoWnafT2 = [, , , ,];
    }
    inherits2(ShortCurve, Base);
    module.exports = ShortCurve;
    ShortCurve.prototype._getEndomorphism = function(conf) {
      if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)
        return;
      var beta, lambda;
      if (conf.beta)
        beta = new BN(conf.beta, 16).toRed(this.red);
      else {
        var betas = this._getEndoRoots(this.p);
        beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1], beta = beta.toRed(this.red);
      }
      if (conf.lambda)
        lambda = new BN(conf.lambda, 16);
      else {
        var lambdas = this._getEndoRoots(this.n);
        if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0)
          lambda = lambdas[0];
        else
          lambda = lambdas[1], assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0);
      }
      var basis;
      if (conf.basis)
        basis = conf.basis.map(function(vec) {
          return { a: new BN(vec.a, 16), b: new BN(vec.b, 16) };
        });
      else
        basis = this._getEndoBasis(lambda);
      return { beta, lambda, basis };
    };
    ShortCurve.prototype._getEndoRoots = function(num) {
      var red = num === this.p ? this.red : BN.mont(num), tinv = new BN(2).toRed(red).redInvm(), ntinv = tinv.redNeg(), s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv), l1 = ntinv.redAdd(s).fromRed(), l2 = ntinv.redSub(s).fromRed();
      return [l1, l2];
    };
    ShortCurve.prototype._getEndoBasis = function(lambda) {
      var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2)), u = lambda, v = this.n.clone(), x1 = new BN(1), y1 = new BN(0), x2 = new BN(0), y2 = new BN(1), a0, b0, a1, b1, a2, b2, prevR, i2 = 0, r2, x;
      while (u.cmpn(0) !== 0) {
        var q = v.div(u);
        r2 = v.sub(q.mul(u)), x = x2.sub(q.mul(x1));
        var y = y2.sub(q.mul(y1));
        if (!a1 && r2.cmp(aprxSqrt) < 0)
          a0 = prevR.neg(), b0 = x1, a1 = r2.neg(), b1 = x;
        else if (a1 && ++i2 === 2)
          break;
        prevR = r2, v = u, u = r2, x2 = x1, x1 = x, y2 = y1, y1 = y;
      }
      a2 = r2.neg(), b2 = x;
      var len1 = a1.sqr().add(b1.sqr()), len2 = a2.sqr().add(b2.sqr());
      if (len2.cmp(len1) >= 0)
        a2 = a0, b2 = b0;
      if (a1.negative)
        a1 = a1.neg(), b1 = b1.neg();
      if (a2.negative)
        a2 = a2.neg(), b2 = b2.neg();
      return [{ a: a1, b: b1 }, { a: a2, b: b2 }];
    };
    ShortCurve.prototype._endoSplit = function(k) {
      var basis = this.endo.basis, v1 = basis[0], v2 = basis[1], c1 = v2.b.mul(k).divRound(this.n), c2 = v1.b.neg().mul(k).divRound(this.n), p1 = c1.mul(v1.a), p2 = c2.mul(v2.a), q1 = c1.mul(v1.b), q2 = c2.mul(v2.b), k1 = k.sub(p1).sub(p2), k2 = q1.add(q2).neg();
      return { k1, k2 };
    };
    ShortCurve.prototype.pointFromX = function(x, odd) {
      if (x = new BN(x, 16), !x.red)
        x = x.toRed(this.red);
      var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b), y = y2.redSqrt();
      if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
        throw Error("invalid point");
      var isOdd = y.fromRed().isOdd();
      if (odd && !isOdd || !odd && isOdd)
        y = y.redNeg();
      return this.point(x, y);
    };
    ShortCurve.prototype.validate = function(point) {
      if (point.inf)
        return true;
      var { x, y } = point, ax = this.a.redMul(x), rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);
      return y.redSqr().redISub(rhs).cmpn(0) === 0;
    };
    ShortCurve.prototype._endoWnafMulAdd = function(points, coeffs, jacobianResult) {
      var npoints = this._endoWnafT1, ncoeffs = this._endoWnafT2;
      for (var i2 = 0;i2 < points.length; i2++) {
        var split = this._endoSplit(coeffs[i2]), p2 = points[i2], beta = p2._getBeta();
        if (split.k1.negative)
          split.k1.ineg(), p2 = p2.neg(true);
        if (split.k2.negative)
          split.k2.ineg(), beta = beta.neg(true);
        npoints[i2 * 2] = p2, npoints[i2 * 2 + 1] = beta, ncoeffs[i2 * 2] = split.k1, ncoeffs[i2 * 2 + 1] = split.k2;
      }
      var res = this._wnafMulAdd(1, npoints, ncoeffs, i2 * 2, jacobianResult);
      for (var j = 0;j < i2 * 2; j++)
        npoints[j] = null, ncoeffs[j] = null;
      return res;
    };
    function Point2(curve, x, y, isRed) {
      if (Base.BasePoint.call(this, curve, "affine"), x === null && y === null)
        this.x = null, this.y = null, this.inf = true;
      else {
        if (this.x = new BN(x, 16), this.y = new BN(y, 16), isRed)
          this.x.forceRed(this.curve.red), this.y.forceRed(this.curve.red);
        if (!this.x.red)
          this.x = this.x.toRed(this.curve.red);
        if (!this.y.red)
          this.y = this.y.toRed(this.curve.red);
        this.inf = false;
      }
    }
    inherits2(Point2, Base.BasePoint);
    ShortCurve.prototype.point = function(x, y, isRed) {
      return new Point2(this, x, y, isRed);
    };
    ShortCurve.prototype.pointFromJSON = function(obj, red) {
      return Point2.fromJSON(this, obj, red);
    };
    Point2.prototype._getBeta = function() {
      if (!this.curve.endo)
        return;
      var pre = this.precomputed;
      if (pre && pre.beta)
        return pre.beta;
      var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y);
      if (pre) {
        var curve = this.curve, endoMul = function(p2) {
          return curve.point(p2.x.redMul(curve.endo.beta), p2.y);
        };
        pre.beta = beta, beta.precomputed = { beta: null, naf: pre.naf && { wnd: pre.naf.wnd, points: pre.naf.points.map(endoMul) }, doubles: pre.doubles && { step: pre.doubles.step, points: pre.doubles.points.map(endoMul) } };
      }
      return beta;
    };
    Point2.prototype.toJSON = function() {
      if (!this.precomputed)
        return [this.x, this.y];
      return [this.x, this.y, this.precomputed && { doubles: this.precomputed.doubles && { step: this.precomputed.doubles.step, points: this.precomputed.doubles.points.slice(1) }, naf: this.precomputed.naf && { wnd: this.precomputed.naf.wnd, points: this.precomputed.naf.points.slice(1) } }];
    };
    Point2.fromJSON = function(curve, obj, red) {
      if (typeof obj === "string")
        obj = JSON.parse(obj);
      var res = curve.point(obj[0], obj[1], red);
      if (!obj[2])
        return res;
      function obj2point(obj2) {
        return curve.point(obj2[0], obj2[1], red);
      }
      var pre = obj[2];
      return res.precomputed = { beta: null, doubles: pre.doubles && { step: pre.doubles.step, points: [res].concat(pre.doubles.points.map(obj2point)) }, naf: pre.naf && { wnd: pre.naf.wnd, points: [res].concat(pre.naf.points.map(obj2point)) } }, res;
    };
    Point2.prototype.inspect = function() {
      if (this.isInfinity())
        return "<EC Point Infinity>";
      return "<EC Point x: " + this.x.fromRed().toString(16, 2) + " y: " + this.y.fromRed().toString(16, 2) + ">";
    };
    Point2.prototype.isInfinity = function() {
      return this.inf;
    };
    Point2.prototype.add = function(p2) {
      if (this.inf)
        return p2;
      if (p2.inf)
        return this;
      if (this.eq(p2))
        return this.dbl();
      if (this.neg().eq(p2))
        return this.curve.point(null, null);
      if (this.x.cmp(p2.x) === 0)
        return this.curve.point(null, null);
      var c2 = this.y.redSub(p2.y);
      if (c2.cmpn(0) !== 0)
        c2 = c2.redMul(this.x.redSub(p2.x).redInvm());
      var nx = c2.redSqr().redISub(this.x).redISub(p2.x), ny = c2.redMul(this.x.redSub(nx)).redISub(this.y);
      return this.curve.point(nx, ny);
    };
    Point2.prototype.dbl = function() {
      if (this.inf)
        return this;
      var ys1 = this.y.redAdd(this.y);
      if (ys1.cmpn(0) === 0)
        return this.curve.point(null, null);
      var a2 = this.curve.a, x2 = this.x.redSqr(), dyinv = ys1.redInvm(), c2 = x2.redAdd(x2).redIAdd(x2).redIAdd(a2).redMul(dyinv), nx = c2.redSqr().redISub(this.x.redAdd(this.x)), ny = c2.redMul(this.x.redSub(nx)).redISub(this.y);
      return this.curve.point(nx, ny);
    };
    Point2.prototype.getX = function() {
      return this.x.fromRed();
    };
    Point2.prototype.getY = function() {
      return this.y.fromRed();
    };
    Point2.prototype.mul = function(k) {
      if (k = new BN(k, 16), this.isInfinity())
        return this;
      else if (this._hasDoubles(k))
        return this.curve._fixedNafMul(this, k);
      else if (this.curve.endo)
        return this.curve._endoWnafMulAdd([this], [k]);
      else
        return this.curve._wnafMul(this, k);
    };
    Point2.prototype.mulAdd = function(k1, p2, k2) {
      var points = [this, p2], coeffs = [k1, k2];
      if (this.curve.endo)
        return this.curve._endoWnafMulAdd(points, coeffs);
      else
        return this.curve._wnafMulAdd(1, points, coeffs, 2);
    };
    Point2.prototype.jmulAdd = function(k1, p2, k2) {
      var points = [this, p2], coeffs = [k1, k2];
      if (this.curve.endo)
        return this.curve._endoWnafMulAdd(points, coeffs, true);
      else
        return this.curve._wnafMulAdd(1, points, coeffs, 2, true);
    };
    Point2.prototype.eq = function(p2) {
      return this === p2 || this.inf === p2.inf && (this.inf || this.x.cmp(p2.x) === 0 && this.y.cmp(p2.y) === 0);
    };
    Point2.prototype.neg = function(_precompute) {
      if (this.inf)
        return this;
      var res = this.curve.point(this.x, this.y.redNeg());
      if (_precompute && this.precomputed) {
        var pre = this.precomputed, negate = function(p2) {
          return p2.neg();
        };
        res.precomputed = { naf: pre.naf && { wnd: pre.naf.wnd, points: pre.naf.points.map(negate) }, doubles: pre.doubles && { step: pre.doubles.step, points: pre.doubles.points.map(negate) } };
      }
      return res;
    };
    Point2.prototype.toJ = function() {
      if (this.inf)
        return this.curve.jpoint(null, null, null);
      var res = this.curve.jpoint(this.x, this.y, this.curve.one);
      return res;
    };
    function JPoint(curve, x, y, z) {
      if (Base.BasePoint.call(this, curve, "jacobian"), x === null && y === null && z === null)
        this.x = this.curve.one, this.y = this.curve.one, this.z = new BN(0);
      else
        this.x = new BN(x, 16), this.y = new BN(y, 16), this.z = new BN(z, 16);
      if (!this.x.red)
        this.x = this.x.toRed(this.curve.red);
      if (!this.y.red)
        this.y = this.y.toRed(this.curve.red);
      if (!this.z.red)
        this.z = this.z.toRed(this.curve.red);
      this.zOne = this.z === this.curve.one;
    }
    inherits2(JPoint, Base.BasePoint);
    ShortCurve.prototype.jpoint = function(x, y, z) {
      return new JPoint(this, x, y, z);
    };
    JPoint.prototype.toP = function() {
      if (this.isInfinity())
        return this.curve.point(null, null);
      var zinv = this.z.redInvm(), zinv2 = zinv.redSqr(), ax = this.x.redMul(zinv2), ay = this.y.redMul(zinv2).redMul(zinv);
      return this.curve.point(ax, ay);
    };
    JPoint.prototype.neg = function() {
      return this.curve.jpoint(this.x, this.y.redNeg(), this.z);
    };
    JPoint.prototype.add = function(p2) {
      if (this.isInfinity())
        return p2;
      if (p2.isInfinity())
        return this;
      var pz2 = p2.z.redSqr(), z2 = this.z.redSqr(), u1 = this.x.redMul(pz2), u2 = p2.x.redMul(z2), s1 = this.y.redMul(pz2.redMul(p2.z)), s2 = p2.y.redMul(z2.redMul(this.z)), h = u1.redSub(u2), r2 = s1.redSub(s2);
      if (h.cmpn(0) === 0)
        if (r2.cmpn(0) !== 0)
          return this.curve.jpoint(null, null, null);
        else
          return this.dbl();
      var h2 = h.redSqr(), h3 = h2.redMul(h), v = u1.redMul(h2), nx = r2.redSqr().redIAdd(h3).redISub(v).redISub(v), ny = r2.redMul(v.redISub(nx)).redISub(s1.redMul(h3)), nz = this.z.redMul(p2.z).redMul(h);
      return this.curve.jpoint(nx, ny, nz);
    };
    JPoint.prototype.mixedAdd = function(p2) {
      if (this.isInfinity())
        return p2.toJ();
      if (p2.isInfinity())
        return this;
      var z2 = this.z.redSqr(), u1 = this.x, u2 = p2.x.redMul(z2), s1 = this.y, s2 = p2.y.redMul(z2).redMul(this.z), h = u1.redSub(u2), r2 = s1.redSub(s2);
      if (h.cmpn(0) === 0)
        if (r2.cmpn(0) !== 0)
          return this.curve.jpoint(null, null, null);
        else
          return this.dbl();
      var h2 = h.redSqr(), h3 = h2.redMul(h), v = u1.redMul(h2), nx = r2.redSqr().redIAdd(h3).redISub(v).redISub(v), ny = r2.redMul(v.redISub(nx)).redISub(s1.redMul(h3)), nz = this.z.redMul(h);
      return this.curve.jpoint(nx, ny, nz);
    };
    JPoint.prototype.dblp = function(pow) {
      if (pow === 0)
        return this;
      if (this.isInfinity())
        return this;
      if (!pow)
        return this.dbl();
      var i2;
      if (this.curve.zeroA || this.curve.threeA) {
        var r2 = this;
        for (i2 = 0;i2 < pow; i2++)
          r2 = r2.dbl();
        return r2;
      }
      var a2 = this.curve.a, tinv = this.curve.tinv, jx = this.x, jy = this.y, jz = this.z, jz4 = jz.redSqr().redSqr(), jyd = jy.redAdd(jy);
      for (i2 = 0;i2 < pow; i2++) {
        var jx2 = jx.redSqr(), jyd2 = jyd.redSqr(), jyd4 = jyd2.redSqr(), c2 = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a2.redMul(jz4)), t1 = jx.redMul(jyd2), nx = c2.redSqr().redISub(t1.redAdd(t1)), t2 = t1.redISub(nx), dny = c2.redMul(t2);
        dny = dny.redIAdd(dny).redISub(jyd4);
        var nz = jyd.redMul(jz);
        if (i2 + 1 < pow)
          jz4 = jz4.redMul(jyd4);
        jx = nx, jz = nz, jyd = dny;
      }
      return this.curve.jpoint(jx, jyd.redMul(tinv), jz);
    };
    JPoint.prototype.dbl = function() {
      if (this.isInfinity())
        return this;
      if (this.curve.zeroA)
        return this._zeroDbl();
      else if (this.curve.threeA)
        return this._threeDbl();
      else
        return this._dbl();
    };
    JPoint.prototype._zeroDbl = function() {
      var nx, ny, nz;
      if (this.zOne) {
        var xx = this.x.redSqr(), yy = this.y.redSqr(), yyyy = yy.redSqr(), s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
        s = s.redIAdd(s);
        var m = xx.redAdd(xx).redIAdd(xx), t2 = m.redSqr().redISub(s).redISub(s), yyyy8 = yyyy.redIAdd(yyyy);
        yyyy8 = yyyy8.redIAdd(yyyy8), yyyy8 = yyyy8.redIAdd(yyyy8), nx = t2, ny = m.redMul(s.redISub(t2)).redISub(yyyy8), nz = this.y.redAdd(this.y);
      } else {
        var a2 = this.x.redSqr(), b = this.y.redSqr(), c2 = b.redSqr(), d = this.x.redAdd(b).redSqr().redISub(a2).redISub(c2);
        d = d.redIAdd(d);
        var e2 = a2.redAdd(a2).redIAdd(a2), f = e2.redSqr(), c8 = c2.redIAdd(c2);
        c8 = c8.redIAdd(c8), c8 = c8.redIAdd(c8), nx = f.redISub(d).redISub(d), ny = e2.redMul(d.redISub(nx)).redISub(c8), nz = this.y.redMul(this.z), nz = nz.redIAdd(nz);
      }
      return this.curve.jpoint(nx, ny, nz);
    };
    JPoint.prototype._threeDbl = function() {
      var nx, ny, nz;
      if (this.zOne) {
        var xx = this.x.redSqr(), yy = this.y.redSqr(), yyyy = yy.redSqr(), s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
        s = s.redIAdd(s);
        var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a), t2 = m.redSqr().redISub(s).redISub(s);
        nx = t2;
        var yyyy8 = yyyy.redIAdd(yyyy);
        yyyy8 = yyyy8.redIAdd(yyyy8), yyyy8 = yyyy8.redIAdd(yyyy8), ny = m.redMul(s.redISub(t2)).redISub(yyyy8), nz = this.y.redAdd(this.y);
      } else {
        var delta = this.z.redSqr(), gamma = this.y.redSqr(), beta = this.x.redMul(gamma), alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta));
        alpha = alpha.redAdd(alpha).redIAdd(alpha);
        var beta4 = beta.redIAdd(beta);
        beta4 = beta4.redIAdd(beta4);
        var beta8 = beta4.redAdd(beta4);
        nx = alpha.redSqr().redISub(beta8), nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta);
        var ggamma8 = gamma.redSqr();
        ggamma8 = ggamma8.redIAdd(ggamma8), ggamma8 = ggamma8.redIAdd(ggamma8), ggamma8 = ggamma8.redIAdd(ggamma8), ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8);
      }
      return this.curve.jpoint(nx, ny, nz);
    };
    JPoint.prototype._dbl = function() {
      var a2 = this.curve.a, jx = this.x, jy = this.y, jz = this.z, jz4 = jz.redSqr().redSqr(), jx2 = jx.redSqr(), jy2 = jy.redSqr(), c2 = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a2.redMul(jz4)), jxd4 = jx.redAdd(jx);
      jxd4 = jxd4.redIAdd(jxd4);
      var t1 = jxd4.redMul(jy2), nx = c2.redSqr().redISub(t1.redAdd(t1)), t2 = t1.redISub(nx), jyd8 = jy2.redSqr();
      jyd8 = jyd8.redIAdd(jyd8), jyd8 = jyd8.redIAdd(jyd8), jyd8 = jyd8.redIAdd(jyd8);
      var ny = c2.redMul(t2).redISub(jyd8), nz = jy.redAdd(jy).redMul(jz);
      return this.curve.jpoint(nx, ny, nz);
    };
    JPoint.prototype.trpl = function() {
      if (!this.curve.zeroA)
        return this.dbl().add(this);
      var xx = this.x.redSqr(), yy = this.y.redSqr(), zz = this.z.redSqr(), yyyy = yy.redSqr(), m = xx.redAdd(xx).redIAdd(xx), mm = m.redSqr(), e2 = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
      e2 = e2.redIAdd(e2), e2 = e2.redAdd(e2).redIAdd(e2), e2 = e2.redISub(mm);
      var ee = e2.redSqr(), t2 = yyyy.redIAdd(yyyy);
      t2 = t2.redIAdd(t2), t2 = t2.redIAdd(t2), t2 = t2.redIAdd(t2);
      var u = m.redIAdd(e2).redSqr().redISub(mm).redISub(ee).redISub(t2), yyu4 = yy.redMul(u);
      yyu4 = yyu4.redIAdd(yyu4), yyu4 = yyu4.redIAdd(yyu4);
      var nx = this.x.redMul(ee).redISub(yyu4);
      nx = nx.redIAdd(nx), nx = nx.redIAdd(nx);
      var ny = this.y.redMul(u.redMul(t2.redISub(u)).redISub(e2.redMul(ee)));
      ny = ny.redIAdd(ny), ny = ny.redIAdd(ny), ny = ny.redIAdd(ny);
      var nz = this.z.redAdd(e2).redSqr().redISub(zz).redISub(ee);
      return this.curve.jpoint(nx, ny, nz);
    };
    JPoint.prototype.mul = function(k, kbase) {
      return k = new BN(k, kbase), this.curve._wnafMul(this, k);
    };
    JPoint.prototype.eq = function(p2) {
      if (p2.type === "affine")
        return this.eq(p2.toJ());
      if (this === p2)
        return true;
      var z2 = this.z.redSqr(), pz2 = p2.z.redSqr();
      if (this.x.redMul(pz2).redISub(p2.x.redMul(z2)).cmpn(0) !== 0)
        return false;
      var z3 = z2.redMul(this.z), pz3 = pz2.redMul(p2.z);
      return this.y.redMul(pz3).redISub(p2.y.redMul(z3)).cmpn(0) === 0;
    };
    JPoint.prototype.eqXToP = function(x) {
      var zs = this.z.redSqr(), rx = x.toRed(this.curve.red).redMul(zs);
      if (this.x.cmp(rx) === 0)
        return true;
      var xc = x.clone(), t2 = this.curve.redN.redMul(zs);
      for (;; ) {
        if (xc.iadd(this.curve.n), xc.cmp(this.curve.p) >= 0)
          return false;
        if (rx.redIAdd(t2), this.x.cmp(rx) === 0)
          return true;
      }
    };
    JPoint.prototype.inspect = function() {
      if (this.isInfinity())
        return "<EC JPoint Infinity>";
      return "<EC JPoint x: " + this.x.toString(16, 2) + " y: " + this.y.toString(16, 2) + " z: " + this.z.toString(16, 2) + ">";
    };
    JPoint.prototype.isInfinity = function() {
      return this.z.cmpn(0) === 0;
    };
  });
  require_mont = __commonJS2((exports, module) => {
    var BN = require_bn(), inherits2 = require_inherits(), Base = require_base(), utils = require_utils2();
    function MontCurve(conf) {
      Base.call(this, "mont", conf), this.a = new BN(conf.a, 16).toRed(this.red), this.b = new BN(conf.b, 16).toRed(this.red), this.i4 = new BN(4).toRed(this.red).redInvm(), this.two = new BN(2).toRed(this.red), this.a24 = this.i4.redMul(this.a.redAdd(this.two));
    }
    inherits2(MontCurve, Base);
    module.exports = MontCurve;
    MontCurve.prototype.validate = function(point) {
      var x = point.normalize().x, x2 = x.redSqr(), rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x), y = rhs.redSqrt();
      return y.redSqr().cmp(rhs) === 0;
    };
    function Point2(curve, x, z) {
      if (Base.BasePoint.call(this, curve, "projective"), x === null && z === null)
        this.x = this.curve.one, this.z = this.curve.zero;
      else {
        if (this.x = new BN(x, 16), this.z = new BN(z, 16), !this.x.red)
          this.x = this.x.toRed(this.curve.red);
        if (!this.z.red)
          this.z = this.z.toRed(this.curve.red);
      }
    }
    inherits2(Point2, Base.BasePoint);
    MontCurve.prototype.decodePoint = function(bytes, enc) {
      return this.point(utils.toArray(bytes, enc), 1);
    };
    MontCurve.prototype.point = function(x, z) {
      return new Point2(this, x, z);
    };
    MontCurve.prototype.pointFromJSON = function(obj) {
      return Point2.fromJSON(this, obj);
    };
    Point2.prototype.precompute = function() {};
    Point2.prototype._encode = function() {
      return this.getX().toArray("be", this.curve.p.byteLength());
    };
    Point2.fromJSON = function(curve, obj) {
      return new Point2(curve, obj[0], obj[1] || curve.one);
    };
    Point2.prototype.inspect = function() {
      if (this.isInfinity())
        return "<EC Point Infinity>";
      return "<EC Point x: " + this.x.fromRed().toString(16, 2) + " z: " + this.z.fromRed().toString(16, 2) + ">";
    };
    Point2.prototype.isInfinity = function() {
      return this.z.cmpn(0) === 0;
    };
    Point2.prototype.dbl = function() {
      var a2 = this.x.redAdd(this.z), aa = a2.redSqr(), b = this.x.redSub(this.z), bb = b.redSqr(), c2 = aa.redSub(bb), nx = aa.redMul(bb), nz = c2.redMul(bb.redAdd(this.curve.a24.redMul(c2)));
      return this.curve.point(nx, nz);
    };
    Point2.prototype.add = function() {
      throw Error("Not supported on Montgomery curve");
    };
    Point2.prototype.diffAdd = function(p2, diff) {
      var a2 = this.x.redAdd(this.z), b = this.x.redSub(this.z), c2 = p2.x.redAdd(p2.z), d = p2.x.redSub(p2.z), da = d.redMul(a2), cb = c2.redMul(b), nx = diff.z.redMul(da.redAdd(cb).redSqr()), nz = diff.x.redMul(da.redISub(cb).redSqr());
      return this.curve.point(nx, nz);
    };
    Point2.prototype.mul = function(k) {
      var t2 = k.clone(), a2 = this, b = this.curve.point(null, null), c2 = this;
      for (var bits = [];t2.cmpn(0) !== 0; t2.iushrn(1))
        bits.push(t2.andln(1));
      for (var i2 = bits.length - 1;i2 >= 0; i2--)
        if (bits[i2] === 0)
          a2 = a2.diffAdd(b, c2), b = b.dbl();
        else
          b = a2.diffAdd(b, c2), a2 = a2.dbl();
      return b;
    };
    Point2.prototype.mulAdd = function() {
      throw Error("Not supported on Montgomery curve");
    };
    Point2.prototype.jumlAdd = function() {
      throw Error("Not supported on Montgomery curve");
    };
    Point2.prototype.eq = function(other) {
      return this.getX().cmp(other.getX()) === 0;
    };
    Point2.prototype.normalize = function() {
      return this.x = this.x.redMul(this.z.redInvm()), this.z = this.curve.one, this;
    };
    Point2.prototype.getX = function() {
      return this.normalize(), this.x.fromRed();
    };
  });
  require_edwards = __commonJS2((exports, module) => {
    var utils = require_utils2(), BN = require_bn(), inherits2 = require_inherits(), Base = require_base(), assert = utils.assert;
    function EdwardsCurve(conf) {
      this.twisted = (conf.a | 0) !== 1, this.mOneA = this.twisted && (conf.a | 0) === -1, this.extended = this.mOneA, Base.call(this, "edwards", conf), this.a = new BN(conf.a, 16).umod(this.red.m), this.a = this.a.toRed(this.red), this.c = new BN(conf.c, 16).toRed(this.red), this.c2 = this.c.redSqr(), this.d = new BN(conf.d, 16).toRed(this.red), this.dd = this.d.redAdd(this.d), assert(!this.twisted || this.c.fromRed().cmpn(1) === 0), this.oneC = (conf.c | 0) === 1;
    }
    inherits2(EdwardsCurve, Base);
    module.exports = EdwardsCurve;
    EdwardsCurve.prototype._mulA = function(num) {
      if (this.mOneA)
        return num.redNeg();
      else
        return this.a.redMul(num);
    };
    EdwardsCurve.prototype._mulC = function(num) {
      if (this.oneC)
        return num;
      else
        return this.c.redMul(num);
    };
    EdwardsCurve.prototype.jpoint = function(x, y, z, t2) {
      return this.point(x, y, z, t2);
    };
    EdwardsCurve.prototype.pointFromX = function(x, odd) {
      if (x = new BN(x, 16), !x.red)
        x = x.toRed(this.red);
      var x2 = x.redSqr(), rhs = this.c2.redSub(this.a.redMul(x2)), lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2)), y2 = rhs.redMul(lhs.redInvm()), y = y2.redSqrt();
      if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
        throw Error("invalid point");
      var isOdd = y.fromRed().isOdd();
      if (odd && !isOdd || !odd && isOdd)
        y = y.redNeg();
      return this.point(x, y);
    };
    EdwardsCurve.prototype.pointFromY = function(y, odd) {
      if (y = new BN(y, 16), !y.red)
        y = y.toRed(this.red);
      var y2 = y.redSqr(), lhs = y2.redSub(this.c2), rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a), x2 = lhs.redMul(rhs.redInvm());
      if (x2.cmp(this.zero) === 0)
        if (odd)
          throw Error("invalid point");
        else
          return this.point(this.zero, y);
      var x = x2.redSqrt();
      if (x.redSqr().redSub(x2).cmp(this.zero) !== 0)
        throw Error("invalid point");
      if (x.fromRed().isOdd() !== odd)
        x = x.redNeg();
      return this.point(x, y);
    };
    EdwardsCurve.prototype.validate = function(point) {
      if (point.isInfinity())
        return true;
      point.normalize();
      var x2 = point.x.redSqr(), y2 = point.y.redSqr(), lhs = x2.redMul(this.a).redAdd(y2), rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2)));
      return lhs.cmp(rhs) === 0;
    };
    function Point2(curve, x, y, z, t2) {
      if (Base.BasePoint.call(this, curve, "projective"), x === null && y === null && z === null)
        this.x = this.curve.zero, this.y = this.curve.one, this.z = this.curve.one, this.t = this.curve.zero, this.zOne = true;
      else {
        if (this.x = new BN(x, 16), this.y = new BN(y, 16), this.z = z ? new BN(z, 16) : this.curve.one, this.t = t2 && new BN(t2, 16), !this.x.red)
          this.x = this.x.toRed(this.curve.red);
        if (!this.y.red)
          this.y = this.y.toRed(this.curve.red);
        if (!this.z.red)
          this.z = this.z.toRed(this.curve.red);
        if (this.t && !this.t.red)
          this.t = this.t.toRed(this.curve.red);
        if (this.zOne = this.z === this.curve.one, this.curve.extended && !this.t) {
          if (this.t = this.x.redMul(this.y), !this.zOne)
            this.t = this.t.redMul(this.z.redInvm());
        }
      }
    }
    inherits2(Point2, Base.BasePoint);
    EdwardsCurve.prototype.pointFromJSON = function(obj) {
      return Point2.fromJSON(this, obj);
    };
    EdwardsCurve.prototype.point = function(x, y, z, t2) {
      return new Point2(this, x, y, z, t2);
    };
    Point2.fromJSON = function(curve, obj) {
      return new Point2(curve, obj[0], obj[1], obj[2]);
    };
    Point2.prototype.inspect = function() {
      if (this.isInfinity())
        return "<EC Point Infinity>";
      return "<EC Point x: " + this.x.fromRed().toString(16, 2) + " y: " + this.y.fromRed().toString(16, 2) + " z: " + this.z.fromRed().toString(16, 2) + ">";
    };
    Point2.prototype.isInfinity = function() {
      return this.x.cmpn(0) === 0 && (this.y.cmp(this.z) === 0 || this.zOne && this.y.cmp(this.curve.c) === 0);
    };
    Point2.prototype._extDbl = function() {
      var a2 = this.x.redSqr(), b = this.y.redSqr(), c2 = this.z.redSqr();
      c2 = c2.redIAdd(c2);
      var d = this.curve._mulA(a2), e2 = this.x.redAdd(this.y).redSqr().redISub(a2).redISub(b), g = d.redAdd(b), f = g.redSub(c2), h = d.redSub(b), nx = e2.redMul(f), ny = g.redMul(h), nt = e2.redMul(h), nz = f.redMul(g);
      return this.curve.point(nx, ny, nz, nt);
    };
    Point2.prototype._projDbl = function() {
      var b = this.x.redAdd(this.y).redSqr(), c2 = this.x.redSqr(), d = this.y.redSqr(), nx, ny, nz, e2, h, j;
      if (this.curve.twisted) {
        e2 = this.curve._mulA(c2);
        var f = e2.redAdd(d);
        if (this.zOne)
          nx = b.redSub(c2).redSub(d).redMul(f.redSub(this.curve.two)), ny = f.redMul(e2.redSub(d)), nz = f.redSqr().redSub(f).redSub(f);
        else
          h = this.z.redSqr(), j = f.redSub(h).redISub(h), nx = b.redSub(c2).redISub(d).redMul(j), ny = f.redMul(e2.redSub(d)), nz = f.redMul(j);
      } else
        e2 = c2.redAdd(d), h = this.curve._mulC(this.z).redSqr(), j = e2.redSub(h).redSub(h), nx = this.curve._mulC(b.redISub(e2)).redMul(j), ny = this.curve._mulC(e2).redMul(c2.redISub(d)), nz = e2.redMul(j);
      return this.curve.point(nx, ny, nz);
    };
    Point2.prototype.dbl = function() {
      if (this.isInfinity())
        return this;
      if (this.curve.extended)
        return this._extDbl();
      else
        return this._projDbl();
    };
    Point2.prototype._extAdd = function(p2) {
      var a2 = this.y.redSub(this.x).redMul(p2.y.redSub(p2.x)), b = this.y.redAdd(this.x).redMul(p2.y.redAdd(p2.x)), c2 = this.t.redMul(this.curve.dd).redMul(p2.t), d = this.z.redMul(p2.z.redAdd(p2.z)), e2 = b.redSub(a2), f = d.redSub(c2), g = d.redAdd(c2), h = b.redAdd(a2), nx = e2.redMul(f), ny = g.redMul(h), nt = e2.redMul(h), nz = f.redMul(g);
      return this.curve.point(nx, ny, nz, nt);
    };
    Point2.prototype._projAdd = function(p2) {
      var a2 = this.z.redMul(p2.z), b = a2.redSqr(), c2 = this.x.redMul(p2.x), d = this.y.redMul(p2.y), e2 = this.curve.d.redMul(c2).redMul(d), f = b.redSub(e2), g = b.redAdd(e2), tmp = this.x.redAdd(this.y).redMul(p2.x.redAdd(p2.y)).redISub(c2).redISub(d), nx = a2.redMul(f).redMul(tmp), ny, nz;
      if (this.curve.twisted)
        ny = a2.redMul(g).redMul(d.redSub(this.curve._mulA(c2))), nz = f.redMul(g);
      else
        ny = a2.redMul(g).redMul(d.redSub(c2)), nz = this.curve._mulC(f).redMul(g);
      return this.curve.point(nx, ny, nz);
    };
    Point2.prototype.add = function(p2) {
      if (this.isInfinity())
        return p2;
      if (p2.isInfinity())
        return this;
      if (this.curve.extended)
        return this._extAdd(p2);
      else
        return this._projAdd(p2);
    };
    Point2.prototype.mul = function(k) {
      if (this._hasDoubles(k))
        return this.curve._fixedNafMul(this, k);
      else
        return this.curve._wnafMul(this, k);
    };
    Point2.prototype.mulAdd = function(k1, p2, k2) {
      return this.curve._wnafMulAdd(1, [this, p2], [k1, k2], 2, false);
    };
    Point2.prototype.jmulAdd = function(k1, p2, k2) {
      return this.curve._wnafMulAdd(1, [this, p2], [k1, k2], 2, true);
    };
    Point2.prototype.normalize = function() {
      if (this.zOne)
        return this;
      var zi = this.z.redInvm();
      if (this.x = this.x.redMul(zi), this.y = this.y.redMul(zi), this.t)
        this.t = this.t.redMul(zi);
      return this.z = this.curve.one, this.zOne = true, this;
    };
    Point2.prototype.neg = function() {
      return this.curve.point(this.x.redNeg(), this.y, this.z, this.t && this.t.redNeg());
    };
    Point2.prototype.getX = function() {
      return this.normalize(), this.x.fromRed();
    };
    Point2.prototype.getY = function() {
      return this.normalize(), this.y.fromRed();
    };
    Point2.prototype.eq = function(other) {
      return this === other || this.getX().cmp(other.getX()) === 0 && this.getY().cmp(other.getY()) === 0;
    };
    Point2.prototype.eqXToP = function(x) {
      var rx = x.toRed(this.curve.red).redMul(this.z);
      if (this.x.cmp(rx) === 0)
        return true;
      var xc = x.clone(), t2 = this.curve.redN.redMul(this.z);
      for (;; ) {
        if (xc.iadd(this.curve.n), xc.cmp(this.curve.p) >= 0)
          return false;
        if (rx.redIAdd(t2), this.x.cmp(rx) === 0)
          return true;
      }
    };
    Point2.prototype.toP = Point2.prototype.normalize;
    Point2.prototype.mixedAdd = Point2.prototype.add;
  });
  require_curve = __commonJS2((exports) => {
    var curve = exports;
    curve.base = require_base();
    curve.short = require_short();
    curve.mont = require_mont();
    curve.edwards = require_edwards();
  });
  require_utils3 = __commonJS2((exports) => {
    var assert = require_minimalistic_assert(), inherits2 = require_inherits();
    exports.inherits = inherits2;
    function isSurrogatePair(msg, i2) {
      if ((msg.charCodeAt(i2) & 64512) !== 55296)
        return false;
      if (i2 < 0 || i2 + 1 >= msg.length)
        return false;
      return (msg.charCodeAt(i2 + 1) & 64512) === 56320;
    }
    function toArray(msg, enc) {
      if (Array.isArray(msg))
        return msg.slice();
      if (!msg)
        return [];
      var res = [];
      if (typeof msg === "string") {
        if (!enc) {
          var p2 = 0;
          for (var i2 = 0;i2 < msg.length; i2++) {
            var c2 = msg.charCodeAt(i2);
            if (c2 < 128)
              res[p2++] = c2;
            else if (c2 < 2048)
              res[p2++] = c2 >> 6 | 192, res[p2++] = c2 & 63 | 128;
            else if (isSurrogatePair(msg, i2))
              c2 = 65536 + ((c2 & 1023) << 10) + (msg.charCodeAt(++i2) & 1023), res[p2++] = c2 >> 18 | 240, res[p2++] = c2 >> 12 & 63 | 128, res[p2++] = c2 >> 6 & 63 | 128, res[p2++] = c2 & 63 | 128;
            else
              res[p2++] = c2 >> 12 | 224, res[p2++] = c2 >> 6 & 63 | 128, res[p2++] = c2 & 63 | 128;
          }
        } else if (enc === "hex") {
          if (msg = msg.replace(/[^a-z0-9]+/ig, ""), msg.length % 2 !== 0)
            msg = "0" + msg;
          for (i2 = 0;i2 < msg.length; i2 += 2)
            res.push(parseInt(msg[i2] + msg[i2 + 1], 16));
        }
      } else
        for (i2 = 0;i2 < msg.length; i2++)
          res[i2] = msg[i2] | 0;
      return res;
    }
    exports.toArray = toArray;
    function toHex(msg) {
      var res = "";
      for (var i2 = 0;i2 < msg.length; i2++)
        res += zero2(msg[i2].toString(16));
      return res;
    }
    exports.toHex = toHex;
    function htonl(w) {
      var res = w >>> 24 | w >>> 8 & 65280 | w << 8 & 16711680 | (w & 255) << 24;
      return res >>> 0;
    }
    exports.htonl = htonl;
    function toHex32(msg, endian) {
      var res = "";
      for (var i2 = 0;i2 < msg.length; i2++) {
        var w = msg[i2];
        if (endian === "little")
          w = htonl(w);
        res += zero8(w.toString(16));
      }
      return res;
    }
    exports.toHex32 = toHex32;
    function zero2(word) {
      if (word.length === 1)
        return "0" + word;
      else
        return word;
    }
    exports.zero2 = zero2;
    function zero8(word) {
      if (word.length === 7)
        return "0" + word;
      else if (word.length === 6)
        return "00" + word;
      else if (word.length === 5)
        return "000" + word;
      else if (word.length === 4)
        return "0000" + word;
      else if (word.length === 3)
        return "00000" + word;
      else if (word.length === 2)
        return "000000" + word;
      else if (word.length === 1)
        return "0000000" + word;
      else
        return word;
    }
    exports.zero8 = zero8;
    function join32(msg, start, end, endian) {
      var len2 = end - start;
      assert(len2 % 4 === 0);
      var res = Array(len2 / 4);
      for (var i2 = 0, k = start;i2 < res.length; i2++, k += 4) {
        var w;
        if (endian === "big")
          w = msg[k] << 24 | msg[k + 1] << 16 | msg[k + 2] << 8 | msg[k + 3];
        else
          w = msg[k + 3] << 24 | msg[k + 2] << 16 | msg[k + 1] << 8 | msg[k];
        res[i2] = w >>> 0;
      }
      return res;
    }
    exports.join32 = join32;
    function split32(msg, endian) {
      var res = Array(msg.length * 4);
      for (var i2 = 0, k = 0;i2 < msg.length; i2++, k += 4) {
        var m = msg[i2];
        if (endian === "big")
          res[k] = m >>> 24, res[k + 1] = m >>> 16 & 255, res[k + 2] = m >>> 8 & 255, res[k + 3] = m & 255;
        else
          res[k + 3] = m >>> 24, res[k + 2] = m >>> 16 & 255, res[k + 1] = m >>> 8 & 255, res[k] = m & 255;
      }
      return res;
    }
    exports.split32 = split32;
    function rotr32(w, b) {
      return w >>> b | w << 32 - b;
    }
    exports.rotr32 = rotr32;
    function rotl32(w, b) {
      return w << b | w >>> 32 - b;
    }
    exports.rotl32 = rotl32;
    function sum32(a2, b) {
      return a2 + b >>> 0;
    }
    exports.sum32 = sum32;
    function sum32_3(a2, b, c2) {
      return a2 + b + c2 >>> 0;
    }
    exports.sum32_3 = sum32_3;
    function sum32_4(a2, b, c2, d) {
      return a2 + b + c2 + d >>> 0;
    }
    exports.sum32_4 = sum32_4;
    function sum32_5(a2, b, c2, d, e2) {
      return a2 + b + c2 + d + e2 >>> 0;
    }
    exports.sum32_5 = sum32_5;
    function sum64(buf, pos, ah, al) {
      var bh = buf[pos], bl = buf[pos + 1], lo = al + bl >>> 0, hi = (lo < al ? 1 : 0) + ah + bh;
      buf[pos] = hi >>> 0, buf[pos + 1] = lo;
    }
    exports.sum64 = sum64;
    function sum64_hi(ah, al, bh, bl) {
      var lo = al + bl >>> 0, hi = (lo < al ? 1 : 0) + ah + bh;
      return hi >>> 0;
    }
    exports.sum64_hi = sum64_hi;
    function sum64_lo(ah, al, bh, bl) {
      var lo = al + bl;
      return lo >>> 0;
    }
    exports.sum64_lo = sum64_lo;
    function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) {
      var carry = 0, lo = al;
      lo = lo + bl >>> 0, carry += lo < al ? 1 : 0, lo = lo + cl >>> 0, carry += lo < cl ? 1 : 0, lo = lo + dl >>> 0, carry += lo < dl ? 1 : 0;
      var hi = ah + bh + ch + dh + carry;
      return hi >>> 0;
    }
    exports.sum64_4_hi = sum64_4_hi;
    function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) {
      var lo = al + bl + cl + dl;
      return lo >>> 0;
    }
    exports.sum64_4_lo = sum64_4_lo;
    function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
      var carry = 0, lo = al;
      lo = lo + bl >>> 0, carry += lo < al ? 1 : 0, lo = lo + cl >>> 0, carry += lo < cl ? 1 : 0, lo = lo + dl >>> 0, carry += lo < dl ? 1 : 0, lo = lo + el >>> 0, carry += lo < el ? 1 : 0;
      var hi = ah + bh + ch + dh + eh + carry;
      return hi >>> 0;
    }
    exports.sum64_5_hi = sum64_5_hi;
    function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
      var lo = al + bl + cl + dl + el;
      return lo >>> 0;
    }
    exports.sum64_5_lo = sum64_5_lo;
    function rotr64_hi(ah, al, num) {
      var r2 = al << 32 - num | ah >>> num;
      return r2 >>> 0;
    }
    exports.rotr64_hi = rotr64_hi;
    function rotr64_lo(ah, al, num) {
      var r2 = ah << 32 - num | al >>> num;
      return r2 >>> 0;
    }
    exports.rotr64_lo = rotr64_lo;
    function shr64_hi(ah, al, num) {
      return ah >>> num;
    }
    exports.shr64_hi = shr64_hi;
    function shr64_lo(ah, al, num) {
      var r2 = ah << 32 - num | al >>> num;
      return r2 >>> 0;
    }
    exports.shr64_lo = shr64_lo;
  });
  require_common = __commonJS2((exports) => {
    var utils = require_utils3(), assert = require_minimalistic_assert();
    function BlockHash() {
      this.pending = null, this.pendingTotal = 0, this.blockSize = this.constructor.blockSize, this.outSize = this.constructor.outSize, this.hmacStrength = this.constructor.hmacStrength, this.padLength = this.constructor.padLength / 8, this.endian = "big", this._delta8 = this.blockSize / 8, this._delta32 = this.blockSize / 32;
    }
    exports.BlockHash = BlockHash;
    BlockHash.prototype.update = function(msg, enc) {
      if (msg = utils.toArray(msg, enc), !this.pending)
        this.pending = msg;
      else
        this.pending = this.pending.concat(msg);
      if (this.pendingTotal += msg.length, this.pending.length >= this._delta8) {
        msg = this.pending;
        var r2 = msg.length % this._delta8;
        if (this.pending = msg.slice(msg.length - r2, msg.length), this.pending.length === 0)
          this.pending = null;
        msg = utils.join32(msg, 0, msg.length - r2, this.endian);
        for (var i2 = 0;i2 < msg.length; i2 += this._delta32)
          this._update(msg, i2, i2 + this._delta32);
      }
      return this;
    };
    BlockHash.prototype.digest = function(enc) {
      return this.update(this._pad()), assert(this.pending === null), this._digest(enc);
    };
    BlockHash.prototype._pad = function() {
      var len2 = this.pendingTotal, bytes = this._delta8, k = bytes - (len2 + this.padLength) % bytes, res = Array(k + this.padLength);
      res[0] = 128;
      for (var i2 = 1;i2 < k; i2++)
        res[i2] = 0;
      if (len2 <<= 3, this.endian === "big") {
        for (var t2 = 8;t2 < this.padLength; t2++)
          res[i2++] = 0;
        res[i2++] = 0, res[i2++] = 0, res[i2++] = 0, res[i2++] = 0, res[i2++] = len2 >>> 24 & 255, res[i2++] = len2 >>> 16 & 255, res[i2++] = len2 >>> 8 & 255, res[i2++] = len2 & 255;
      } else {
        res[i2++] = len2 & 255, res[i2++] = len2 >>> 8 & 255, res[i2++] = len2 >>> 16 & 255, res[i2++] = len2 >>> 24 & 255, res[i2++] = 0, res[i2++] = 0, res[i2++] = 0, res[i2++] = 0;
        for (t2 = 8;t2 < this.padLength; t2++)
          res[i2++] = 0;
      }
      return res;
    };
  });
  require_common2 = __commonJS2((exports) => {
    var utils = require_utils3(), rotr32 = utils.rotr32;
    function ft_1(s, x, y, z) {
      if (s === 0)
        return ch32(x, y, z);
      if (s === 1 || s === 3)
        return p32(x, y, z);
      if (s === 2)
        return maj32(x, y, z);
    }
    exports.ft_1 = ft_1;
    function ch32(x, y, z) {
      return x & y ^ ~x & z;
    }
    exports.ch32 = ch32;
    function maj32(x, y, z) {
      return x & y ^ x & z ^ y & z;
    }
    exports.maj32 = maj32;
    function p32(x, y, z) {
      return x ^ y ^ z;
    }
    exports.p32 = p32;
    function s0_256(x) {
      return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22);
    }
    exports.s0_256 = s0_256;
    function s1_256(x) {
      return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25);
    }
    exports.s1_256 = s1_256;
    function g0_256(x) {
      return rotr32(x, 7) ^ rotr32(x, 18) ^ x >>> 3;
    }
    exports.g0_256 = g0_256;
    function g1_256(x) {
      return rotr32(x, 17) ^ rotr32(x, 19) ^ x >>> 10;
    }
    exports.g1_256 = g1_256;
  });
  require_1 = __commonJS2((exports, module) => {
    var utils = require_utils3(), common = require_common(), shaCommon = require_common2(), rotl32 = utils.rotl32, sum32 = utils.sum32, sum32_5 = utils.sum32_5, ft_1 = shaCommon.ft_1, BlockHash = common.BlockHash, sha1_K = [1518500249, 1859775393, 2400959708, 3395469782];
    function SHA1() {
      if (!(this instanceof SHA1))
        return new SHA1;
      BlockHash.call(this), this.h = [1732584193, 4023233417, 2562383102, 271733878, 3285377520], this.W = Array(80);
    }
    utils.inherits(SHA1, BlockHash);
    module.exports = SHA1;
    SHA1.blockSize = 512;
    SHA1.outSize = 160;
    SHA1.hmacStrength = 80;
    SHA1.padLength = 64;
    SHA1.prototype._update = function(msg, start) {
      var W = this.W;
      for (var i2 = 0;i2 < 16; i2++)
        W[i2] = msg[start + i2];
      for (;i2 < W.length; i2++)
        W[i2] = rotl32(W[i2 - 3] ^ W[i2 - 8] ^ W[i2 - 14] ^ W[i2 - 16], 1);
      var a2 = this.h[0], b = this.h[1], c2 = this.h[2], d = this.h[3], e2 = this.h[4];
      for (i2 = 0;i2 < W.length; i2++) {
        var s = ~~(i2 / 20), t2 = sum32_5(rotl32(a2, 5), ft_1(s, b, c2, d), e2, W[i2], sha1_K[s]);
        e2 = d, d = c2, c2 = rotl32(b, 30), b = a2, a2 = t2;
      }
      this.h[0] = sum32(this.h[0], a2), this.h[1] = sum32(this.h[1], b), this.h[2] = sum32(this.h[2], c2), this.h[3] = sum32(this.h[3], d), this.h[4] = sum32(this.h[4], e2);
    };
    SHA1.prototype._digest = function(enc) {
      if (enc === "hex")
        return utils.toHex32(this.h, "big");
      else
        return utils.split32(this.h, "big");
    };
  });
  require_256 = __commonJS2((exports, module) => {
    var utils = require_utils3(), common = require_common(), shaCommon = require_common2(), assert = require_minimalistic_assert(), sum32 = utils.sum32, sum32_4 = utils.sum32_4, sum32_5 = utils.sum32_5, ch32 = shaCommon.ch32, maj32 = shaCommon.maj32, s0_256 = shaCommon.s0_256, s1_256 = shaCommon.s1_256, g0_256 = shaCommon.g0_256, g1_256 = shaCommon.g1_256, BlockHash = common.BlockHash, sha256_K = [1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, 2453635748, 2870763221, 3624381080, 310598401, 607225278, 1426881987, 1925078388, 2162078206, 2614888103, 3248222580, 3835390401, 4022224774, 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, 2554220882, 2821834349, 2952996808, 3210313671, 3336571891, 3584528711, 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291, 1695183700, 1986661051, 2177026350, 2456956037, 2730485921, 2820302411, 3259730800, 3345764771, 3516065817, 3600352804, 4094571909, 275423344, 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779, 1955562222, 2024104815, 2227730452, 2361852424, 2428436474, 2756734187, 3204031479, 3329325298];
    function SHA256() {
      if (!(this instanceof SHA256))
        return new SHA256;
      BlockHash.call(this), this.h = [1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225], this.k = sha256_K, this.W = Array(64);
    }
    utils.inherits(SHA256, BlockHash);
    module.exports = SHA256;
    SHA256.blockSize = 512;
    SHA256.outSize = 256;
    SHA256.hmacStrength = 192;
    SHA256.padLength = 64;
    SHA256.prototype._update = function(msg, start) {
      var W = this.W;
      for (var i2 = 0;i2 < 16; i2++)
        W[i2] = msg[start + i2];
      for (;i2 < W.length; i2++)
        W[i2] = sum32_4(g1_256(W[i2 - 2]), W[i2 - 7], g0_256(W[i2 - 15]), W[i2 - 16]);
      var a2 = this.h[0], b = this.h[1], c2 = this.h[2], d = this.h[3], e2 = this.h[4], f = this.h[5], g = this.h[6], h = this.h[7];
      assert(this.k.length === W.length);
      for (i2 = 0;i2 < W.length; i2++) {
        var T1 = sum32_5(h, s1_256(e2), ch32(e2, f, g), this.k[i2], W[i2]), T2 = sum32(s0_256(a2), maj32(a2, b, c2));
        h = g, g = f, f = e2, e2 = sum32(d, T1), d = c2, c2 = b, b = a2, a2 = sum32(T1, T2);
      }
      this.h[0] = sum32(this.h[0], a2), this.h[1] = sum32(this.h[1], b), this.h[2] = sum32(this.h[2], c2), this.h[3] = sum32(this.h[3], d), this.h[4] = sum32(this.h[4], e2), this.h[5] = sum32(this.h[5], f), this.h[6] = sum32(this.h[6], g), this.h[7] = sum32(this.h[7], h);
    };
    SHA256.prototype._digest = function(enc) {
      if (enc === "hex")
        return utils.toHex32(this.h, "big");
      else
        return utils.split32(this.h, "big");
    };
  });
  require_224 = __commonJS2((exports, module) => {
    var utils = require_utils3(), SHA256 = require_256();
    function SHA224() {
      if (!(this instanceof SHA224))
        return new SHA224;
      SHA256.call(this), this.h = [3238371032, 914150663, 812702999, 4144912697, 4290775857, 1750603025, 1694076839, 3204075428];
    }
    utils.inherits(SHA224, SHA256);
    module.exports = SHA224;
    SHA224.blockSize = 512;
    SHA224.outSize = 224;
    SHA224.hmacStrength = 192;
    SHA224.padLength = 64;
    SHA224.prototype._digest = function(enc) {
      if (enc === "hex")
        return utils.toHex32(this.h.slice(0, 7), "big");
      else
        return utils.split32(this.h.slice(0, 7), "big");
    };
  });
  require_512 = __commonJS2((exports, module) => {
    var utils = require_utils3(), common = require_common(), assert = require_minimalistic_assert(), rotr64_hi = utils.rotr64_hi, rotr64_lo = utils.rotr64_lo, shr64_hi = utils.shr64_hi, shr64_lo = utils.shr64_lo, sum64 = utils.sum64, sum64_hi = utils.sum64_hi, sum64_lo = utils.sum64_lo, sum64_4_hi = utils.sum64_4_hi, sum64_4_lo = utils.sum64_4_lo, sum64_5_hi = utils.sum64_5_hi, sum64_5_lo = utils.sum64_5_lo, BlockHash = common.BlockHash, sha512_K = [1116352408, 3609767458, 1899447441, 602891725, 3049323471, 3964484399, 3921009573, 2173295548, 961987163, 4081628472, 1508970993, 3053834265, 2453635748, 2937671579, 2870763221, 3664609560, 3624381080, 2734883394, 310598401, 1164996542, 607225278, 1323610764, 1426881987, 3590304994, 1925078388, 4068182383, 2162078206, 991336113, 2614888103, 633803317, 3248222580, 3479774868, 3835390401, 2666613458, 4022224774, 944711139, 264347078, 2341262773, 604807628, 2007800933, 770255983, 1495990901, 1249150122, 1856431235, 1555081692, 3175218132, 1996064986, 2198950837, 2554220882, 3999719339, 2821834349, 766784016, 2952996808, 2566594879, 3210313671, 3203337956, 3336571891, 1034457026, 3584528711, 2466948901, 113926993, 3758326383, 338241895, 168717936, 666307205, 1188179964, 773529912, 1546045734, 1294757372, 1522805485, 1396182291, 2643833823, 1695183700, 2343527390, 1986661051, 1014477480, 2177026350, 1206759142, 2456956037, 344077627, 2730485921, 1290863460, 2820302411, 3158454273, 3259730800, 3505952657, 3345764771, 106217008, 3516065817, 3606008344, 3600352804, 1432725776, 4094571909, 1467031594, 275423344, 851169720, 430227734, 3100823752, 506948616, 1363258195, 659060556, 3750685593, 883997877, 3785050280, 958139571, 3318307427, 1322822218, 3812723403, 1537002063, 2003034995, 1747873779, 3602036899, 1955562222, 1575990012, 2024104815, 1125592928, 2227730452, 2716904306, 2361852424, 442776044, 2428436474, 593698344, 2756734187, 3733110249, 3204031479, 2999351573, 3329325298, 3815920427, 3391569614, 3928383900, 3515267271, 566280711, 3940187606, 3454069534, 4118630271, 4000239992, 116418474, 1914138554, 174292421, 2731055270, 289380356, 3203993006, 460393269, 320620315, 685471733, 587496836, 852142971, 1086792851, 1017036298, 365543100, 1126000580, 2618297676, 1288033470, 3409855158, 1501505948, 4234509866, 1607167915, 987167468, 1816402316, 1246189591];
    function SHA512() {
      if (!(this instanceof SHA512))
        return new SHA512;
      BlockHash.call(this), this.h = [1779033703, 4089235720, 3144134277, 2227873595, 1013904242, 4271175723, 2773480762, 1595750129, 1359893119, 2917565137, 2600822924, 725511199, 528734635, 4215389547, 1541459225, 327033209], this.k = sha512_K, this.W = Array(160);
    }
    utils.inherits(SHA512, BlockHash);
    module.exports = SHA512;
    SHA512.blockSize = 1024;
    SHA512.outSize = 512;
    SHA512.hmacStrength = 192;
    SHA512.padLength = 128;
    SHA512.prototype._prepareBlock = function(msg, start) {
      var W = this.W;
      for (var i2 = 0;i2 < 32; i2++)
        W[i2] = msg[start + i2];
      for (;i2 < W.length; i2 += 2) {
        var c0_hi = g1_512_hi(W[i2 - 4], W[i2 - 3]), c0_lo = g1_512_lo(W[i2 - 4], W[i2 - 3]), c1_hi = W[i2 - 14], c1_lo = W[i2 - 13], c2_hi = g0_512_hi(W[i2 - 30], W[i2 - 29]), c2_lo = g0_512_lo(W[i2 - 30], W[i2 - 29]), c3_hi = W[i2 - 32], c3_lo = W[i2 - 31];
        W[i2] = sum64_4_hi(c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo), W[i2 + 1] = sum64_4_lo(c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo);
      }
    };
    SHA512.prototype._update = function(msg, start) {
      this._prepareBlock(msg, start);
      var W = this.W, ah = this.h[0], al = this.h[1], bh = this.h[2], bl = this.h[3], ch = this.h[4], cl = this.h[5], dh = this.h[6], dl = this.h[7], eh = this.h[8], el = this.h[9], fh = this.h[10], fl = this.h[11], gh = this.h[12], gl = this.h[13], hh = this.h[14], hl = this.h[15];
      assert(this.k.length === W.length);
      for (var i2 = 0;i2 < W.length; i2 += 2) {
        var c0_hi = hh, c0_lo = hl, c1_hi = s1_512_hi(eh, el), c1_lo = s1_512_lo(eh, el), c2_hi = ch64_hi(eh, el, fh, fl, gh, gl), c2_lo = ch64_lo(eh, el, fh, fl, gh, gl), c3_hi = this.k[i2], c3_lo = this.k[i2 + 1], c4_hi = W[i2], c4_lo = W[i2 + 1], T1_hi = sum64_5_hi(c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo, c4_hi, c4_lo), T1_lo = sum64_5_lo(c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo, c4_hi, c4_lo);
        c0_hi = s0_512_hi(ah, al), c0_lo = s0_512_lo(ah, al), c1_hi = maj64_hi(ah, al, bh, bl, ch, cl), c1_lo = maj64_lo(ah, al, bh, bl, ch, cl);
        var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo), T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo);
        hh = gh, hl = gl, gh = fh, gl = fl, fh = eh, fl = el, eh = sum64_hi(dh, dl, T1_hi, T1_lo), el = sum64_lo(dl, dl, T1_hi, T1_lo), dh = ch, dl = cl, ch = bh, cl = bl, bh = ah, bl = al, ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo), al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo);
      }
      sum64(this.h, 0, ah, al), sum64(this.h, 2, bh, bl), sum64(this.h, 4, ch, cl), sum64(this.h, 6, dh, dl), sum64(this.h, 8, eh, el), sum64(this.h, 10, fh, fl), sum64(this.h, 12, gh, gl), sum64(this.h, 14, hh, hl);
    };
    SHA512.prototype._digest = function(enc) {
      if (enc === "hex")
        return utils.toHex32(this.h, "big");
      else
        return utils.split32(this.h, "big");
    };
    function ch64_hi(xh, xl, yh, yl, zh) {
      var r2 = xh & yh ^ ~xh & zh;
      if (r2 < 0)
        r2 += 4294967296;
      return r2;
    }
    function ch64_lo(xh, xl, yh, yl, zh, zl) {
      var r2 = xl & yl ^ ~xl & zl;
      if (r2 < 0)
        r2 += 4294967296;
      return r2;
    }
    function maj64_hi(xh, xl, yh, yl, zh) {
      var r2 = xh & yh ^ xh & zh ^ yh & zh;
      if (r2 < 0)
        r2 += 4294967296;
      return r2;
    }
    function maj64_lo(xh, xl, yh, yl, zh, zl) {
      var r2 = xl & yl ^ xl & zl ^ yl & zl;
      if (r2 < 0)
        r2 += 4294967296;
      return r2;
    }
    function s0_512_hi(xh, xl) {
      var c0_hi = rotr64_hi(xh, xl, 28), c1_hi = rotr64_hi(xl, xh, 2), c2_hi = rotr64_hi(xl, xh, 7), r2 = c0_hi ^ c1_hi ^ c2_hi;
      if (r2 < 0)
        r2 += 4294967296;
      return r2;
    }
    function s0_512_lo(xh, xl) {
      var c0_lo = rotr64_lo(xh, xl, 28), c1_lo = rotr64_lo(xl, xh, 2), c2_lo = rotr64_lo(xl, xh, 7), r2 = c0_lo ^ c1_lo ^ c2_lo;
      if (r2 < 0)
        r2 += 4294967296;
      return r2;
    }
    function s1_512_hi(xh, xl) {
      var c0_hi = rotr64_hi(xh, xl, 14), c1_hi = rotr64_hi(xh, xl, 18), c2_hi = rotr64_hi(xl, xh, 9), r2 = c0_hi ^ c1_hi ^ c2_hi;
      if (r2 < 0)
        r2 += 4294967296;
      return r2;
    }
    function s1_512_lo(xh, xl) {
      var c0_lo = rotr64_lo(xh, xl, 14), c1_lo = rotr64_lo(xh, xl, 18), c2_lo = rotr64_lo(xl, xh, 9), r2 = c0_lo ^ c1_lo ^ c2_lo;
      if (r2 < 0)
        r2 += 4294967296;
      return r2;
    }
    function g0_512_hi(xh, xl) {
      var c0_hi = rotr64_hi(xh, xl, 1), c1_hi = rotr64_hi(xh, xl, 8), c2_hi = shr64_hi(xh, xl, 7), r2 = c0_hi ^ c1_hi ^ c2_hi;
      if (r2 < 0)
        r2 += 4294967296;
      return r2;
    }
    function g0_512_lo(xh, xl) {
      var c0_lo = rotr64_lo(xh, xl, 1), c1_lo = rotr64_lo(xh, xl, 8), c2_lo = shr64_lo(xh, xl, 7), r2 = c0_lo ^ c1_lo ^ c2_lo;
      if (r2 < 0)
        r2 += 4294967296;
      return r2;
    }
    function g1_512_hi(xh, xl) {
      var c0_hi = rotr64_hi(xh, xl, 19), c1_hi = rotr64_hi(xl, xh, 29), c2_hi = shr64_hi(xh, xl, 6), r2 = c0_hi ^ c1_hi ^ c2_hi;
      if (r2 < 0)
        r2 += 4294967296;
      return r2;
    }
    function g1_512_lo(xh, xl) {
      var c0_lo = rotr64_lo(xh, xl, 19), c1_lo = rotr64_lo(xl, xh, 29), c2_lo = shr64_lo(xh, xl, 6), r2 = c0_lo ^ c1_lo ^ c2_lo;
      if (r2 < 0)
        r2 += 4294967296;
      return r2;
    }
  });
  require_384 = __commonJS2((exports, module) => {
    var utils = require_utils3(), SHA512 = require_512();
    function SHA384() {
      if (!(this instanceof SHA384))
        return new SHA384;
      SHA512.call(this), this.h = [3418070365, 3238371032, 1654270250, 914150663, 2438529370, 812702999, 355462360, 4144912697, 1731405415, 4290775857, 2394180231, 1750603025, 3675008525, 1694076839, 1203062813, 3204075428];
    }
    utils.inherits(SHA384, SHA512);
    module.exports = SHA384;
    SHA384.blockSize = 1024;
    SHA384.outSize = 384;
    SHA384.hmacStrength = 192;
    SHA384.padLength = 128;
    SHA384.prototype._digest = function(enc) {
      if (enc === "hex")
        return utils.toHex32(this.h.slice(0, 12), "big");
      else
        return utils.split32(this.h.slice(0, 12), "big");
    };
  });
  require_sha = __commonJS2((exports) => {
    exports.sha1 = require_1();
    exports.sha224 = require_224();
    exports.sha256 = require_256();
    exports.sha384 = require_384();
    exports.sha512 = require_512();
  });
  require_ripemd = __commonJS2((exports) => {
    var utils = require_utils3(), common = require_common(), rotl32 = utils.rotl32, sum32 = utils.sum32, sum32_3 = utils.sum32_3, sum32_4 = utils.sum32_4, BlockHash = common.BlockHash;
    function RIPEMD160() {
      if (!(this instanceof RIPEMD160))
        return new RIPEMD160;
      BlockHash.call(this), this.h = [1732584193, 4023233417, 2562383102, 271733878, 3285377520], this.endian = "little";
    }
    utils.inherits(RIPEMD160, BlockHash);
    exports.ripemd160 = RIPEMD160;
    RIPEMD160.blockSize = 512;
    RIPEMD160.outSize = 160;
    RIPEMD160.hmacStrength = 192;
    RIPEMD160.padLength = 64;
    RIPEMD160.prototype._update = function(msg, start) {
      var A = this.h[0], B = this.h[1], C = this.h[2], D = this.h[3], E2 = this.h[4], Ah = A, Bh = B, Ch = C, Dh = D, Eh = E2;
      for (var j = 0;j < 80; j++) {
        var T = sum32(rotl32(sum32_4(A, f(j, B, C, D), msg[r2[j] + start], K(j)), s[j]), E2);
        A = E2, E2 = D, D = rotl32(C, 10), C = B, B = T, T = sum32(rotl32(sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)), sh[j]), Eh), Ah = Eh, Eh = Dh, Dh = rotl32(Ch, 10), Ch = Bh, Bh = T;
      }
      T = sum32_3(this.h[1], C, Dh), this.h[1] = sum32_3(this.h[2], D, Eh), this.h[2] = sum32_3(this.h[3], E2, Ah), this.h[3] = sum32_3(this.h[4], A, Bh), this.h[4] = sum32_3(this.h[0], B, Ch), this.h[0] = T;
    };
    RIPEMD160.prototype._digest = function(enc) {
      if (enc === "hex")
        return utils.toHex32(this.h, "little");
      else
        return utils.split32(this.h, "little");
    };
    function f(j, x, y, z) {
      if (j <= 15)
        return x ^ y ^ z;
      else if (j <= 31)
        return x & y | ~x & z;
      else if (j <= 47)
        return (x | ~y) ^ z;
      else if (j <= 63)
        return x & z | y & ~z;
      else
        return x ^ (y | ~z);
    }
    function K(j) {
      if (j <= 15)
        return 0;
      else if (j <= 31)
        return 1518500249;
      else if (j <= 47)
        return 1859775393;
      else if (j <= 63)
        return 2400959708;
      else
        return 2840853838;
    }
    function Kh(j) {
      if (j <= 15)
        return 1352829926;
      else if (j <= 31)
        return 1548603684;
      else if (j <= 47)
        return 1836072691;
      else if (j <= 63)
        return 2053994217;
      else
        return 0;
    }
    var r2 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13], rh = [5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11], s = [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6], sh = [8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11];
  });
  require_hmac = __commonJS2((exports, module) => {
    var utils = require_utils3(), assert = require_minimalistic_assert();
    function Hmac(hash, key, enc) {
      if (!(this instanceof Hmac))
        return new Hmac(hash, key, enc);
      this.Hash = hash, this.blockSize = hash.blockSize / 8, this.outSize = hash.outSize / 8, this.inner = null, this.outer = null, this._init(utils.toArray(key, enc));
    }
    module.exports = Hmac;
    Hmac.prototype._init = function(key) {
      if (key.length > this.blockSize)
        key = new this.Hash().update(key).digest();
      assert(key.length <= this.blockSize);
      for (var i2 = key.length;i2 < this.blockSize; i2++)
        key.push(0);
      for (i2 = 0;i2 < key.length; i2++)
        key[i2] ^= 54;
      this.inner = new this.Hash().update(key);
      for (i2 = 0;i2 < key.length; i2++)
        key[i2] ^= 106;
      this.outer = new this.Hash().update(key);
    };
    Hmac.prototype.update = function(msg, enc) {
      return this.inner.update(msg, enc), this;
    };
    Hmac.prototype.digest = function(enc) {
      return this.outer.update(this.inner.digest()), this.outer.digest(enc);
    };
  });
  require_hash = __commonJS2((exports) => {
    var hash = exports;
    hash.utils = require_utils3();
    hash.common = require_common();
    hash.sha = require_sha();
    hash.ripemd = require_ripemd();
    hash.hmac = require_hmac();
    hash.sha1 = hash.sha.sha1;
    hash.sha256 = hash.sha.sha256;
    hash.sha224 = hash.sha.sha224;
    hash.sha384 = hash.sha.sha384;
    hash.sha512 = hash.sha.sha512;
    hash.ripemd160 = hash.ripemd.ripemd160;
  });
  require_secp256k1 = __commonJS2((exports, module) => {
    module.exports = { doubles: { step: 4, points: [["e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a", "f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821"], ["8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508", "11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf"], ["175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739", "d3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695"], ["363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640", "4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9"], ["8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c", "4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36"], ["723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda", "96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f"], ["eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa", "5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999"], ["100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0", "cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09"], ["e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d", "9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d"], ["feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d", "e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088"], ["da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1", "9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d"], ["53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0", "5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8"], ["8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047", "10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a"], ["385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862", "283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453"], ["6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7", "7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160"], ["3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd", "56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0"], ["85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83", "7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6"], ["948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a", "53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589"], ["6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8", "bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17"], ["e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d", "4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda"], ["e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725", "7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd"], ["213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754", "4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2"], ["4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c", "17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6"], ["fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6", "6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f"], ["76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39", "c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01"], ["c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891", "893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3"], ["d895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b", "febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f"], ["b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03", "2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7"], ["e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d", "eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78"], ["a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070", "7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1"], ["90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4", "e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150"], ["8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da", "662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82"], ["e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11", "1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc"], ["8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e", "efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b"], ["e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41", "2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51"], ["b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef", "67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45"], ["d68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8", "db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120"], ["324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d", "648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84"], ["4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96", "35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d"], ["9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd", "ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d"], ["6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5", "9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8"], ["a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266", "40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8"], ["7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71", "34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac"], ["928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac", "c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f"], ["85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751", "1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962"], ["ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e", "493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907"], ["827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241", "c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec"], ["eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3", "be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d"], ["e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f", "4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414"], ["1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19", "aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd"], ["146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be", "b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0"], ["fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9", "6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811"], ["da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2", "8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1"], ["a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13", "7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c"], ["174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c", "ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73"], ["959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba", "2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd"], ["d2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151", "e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405"], ["64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073", "d99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589"], ["8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458", "38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e"], ["13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b", "69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27"], ["bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366", "d3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1"], ["8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa", "40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482"], ["8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0", "620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945"], ["dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787", "7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573"], ["f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e", "ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82"]] }, naf: { wnd: 7, points: [["f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9", "388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672"], ["2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4", "d8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6"], ["5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc", "6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da"], ["acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe", "cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37"], ["774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb", "d984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b"], ["f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8", "ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81"], ["d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e", "581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58"], ["defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34", "4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77"], ["2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c", "85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a"], ["352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5", "321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c"], ["2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f", "2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67"], ["9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714", "73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402"], ["daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729", "a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55"], ["c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db", "2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482"], ["6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4", "e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82"], ["1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5", "b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396"], ["605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479", "2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49"], ["62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d", "80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf"], ["80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f", "1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a"], ["7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb", "d0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7"], ["d528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9", "eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933"], ["49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963", "758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a"], ["77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74", "958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6"], ["f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530", "e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37"], ["463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b", "5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e"], ["f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247", "cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6"], ["caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1", "cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476"], ["2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120", "4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40"], ["7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435", "91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61"], ["754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18", "673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683"], ["e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8", "59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5"], ["186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb", "3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b"], ["df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f", "55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417"], ["5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143", "efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868"], ["290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba", "e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a"], ["af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45", "f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6"], ["766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a", "744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996"], ["59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e", "c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e"], ["f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8", "e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d"], ["7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c", "30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2"], ["948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519", "e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e"], ["7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab", "100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437"], ["3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca", "ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311"], ["d3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf", "8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4"], ["1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610", "68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575"], ["733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4", "f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d"], ["15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c", "d56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d"], ["a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940", "edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629"], ["e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980", "a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06"], ["311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3", "66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374"], ["34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf", "9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee"], ["f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63", "4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1"], ["d7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448", "fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b"], ["32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf", "5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661"], ["7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5", "8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6"], ["ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6", "8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e"], ["16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5", "5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d"], ["eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99", "f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc"], ["78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51", "f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4"], ["494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5", "42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c"], ["a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5", "204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b"], ["c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997", "4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913"], ["841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881", "73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154"], ["5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5", "39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865"], ["36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66", "d2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc"], ["336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726", "ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224"], ["8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede", "6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e"], ["1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94", "60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6"], ["85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31", "3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511"], ["29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51", "b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b"], ["a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252", "ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2"], ["4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5", "cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c"], ["d24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b", "6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3"], ["ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4", "322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d"], ["af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f", "6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700"], ["e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889", "2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4"], ["591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246", "b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196"], ["11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984", "998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4"], ["3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a", "b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257"], ["cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030", "bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13"], ["c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197", "6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096"], ["c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593", "c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38"], ["a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef", "21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f"], ["347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38", "60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448"], ["da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a", "49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a"], ["c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111", "5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4"], ["4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502", "7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437"], ["3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea", "be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7"], ["cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26", "8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d"], ["b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986", "39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a"], ["d4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e", "62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54"], ["48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4", "25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77"], ["dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda", "ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517"], ["6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859", "cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10"], ["e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f", "f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125"], ["eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c", "6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e"], ["13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942", "fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1"], ["ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a", "1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2"], ["b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80", "5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423"], ["ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d", "438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8"], ["8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1", "cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758"], ["52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63", "c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375"], ["e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352", "6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d"], ["7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193", "ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec"], ["5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00", "9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0"], ["32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58", "ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c"], ["e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7", "d3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4"], ["8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8", "c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f"], ["4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e", "67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649"], ["3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d", "cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826"], ["674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b", "299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5"], ["d32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f", "f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87"], ["30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6", "462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b"], ["be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297", "62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc"], ["93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a", "7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c"], ["b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c", "ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f"], ["d5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52", "4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a"], ["d3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb", "bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46"], ["463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065", "bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f"], ["7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917", "603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03"], ["74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9", "cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08"], ["30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3", "553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8"], ["9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57", "712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373"], ["176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66", "ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3"], ["75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8", "9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8"], ["809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721", "9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1"], ["1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180", "4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9"]] } };
  });
  require_curves = __commonJS2((exports) => {
    var curves = exports, hash = require_hash(), curve = require_curve(), utils = require_utils2(), assert = utils.assert;
    function PresetCurve(options) {
      if (options.type === "short")
        this.curve = new curve.short(options);
      else if (options.type === "edwards")
        this.curve = new curve.edwards(options);
      else
        this.curve = new curve.mont(options);
      this.g = this.curve.g, this.n = this.curve.n, this.hash = options.hash, assert(this.g.validate(), "Invalid curve"), assert(this.g.mul(this.n).isInfinity(), "Invalid curve, G*N != O");
    }
    curves.PresetCurve = PresetCurve;
    function defineCurve(name, options) {
      Object.defineProperty(curves, name, { configurable: true, enumerable: true, get: function() {
        var curve2 = new PresetCurve(options);
        return Object.defineProperty(curves, name, { configurable: true, enumerable: true, value: curve2 }), curve2;
      } });
    }
    defineCurve("p192", { type: "short", prime: "p192", p: "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff", a: "ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc", b: "64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1", n: "ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831", hash: hash.sha256, gRed: false, g: ["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012", "07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"] });
    defineCurve("p224", { type: "short", prime: "p224", p: "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001", a: "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe", b: "b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4", n: "ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d", hash: hash.sha256, gRed: false, g: ["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21", "bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"] });
    defineCurve("p256", { type: "short", prime: null, p: "ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff", a: "ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc", b: "5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b", n: "ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551", hash: hash.sha256, gRed: false, g: ["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296", "4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"] });
    defineCurve("p384", { type: "short", prime: null, p: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 ffffffff", a: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 fffffffc", b: "b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f 5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef", n: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 f4372ddf 581a0db2 48b0a77a ecec196a ccc52973", hash: hash.sha384, gRed: false, g: ["aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 5502f25d bf55296c 3a545e38 72760ab7", "3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 0a60b1ce 1d7e819d 7a431d7c 90ea0e5f"] });
    defineCurve("p521", { type: "short", prime: null, p: "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff", a: "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffc", b: "00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b 99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd 3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00", n: "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409", hash: hash.sha512, gRed: false, g: ["000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66", "00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 3fad0761 353c7086 a272c240 88be9476 9fd16650"] });
    defineCurve("curve25519", { type: "mont", prime: "p25519", p: "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed", a: "76d06", b: "1", n: "1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed", hash: hash.sha256, gRed: false, g: ["9"] });
    defineCurve("ed25519", { type: "edwards", prime: "p25519", p: "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed", a: "-1", c: "1", d: "52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3", n: "1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed", hash: hash.sha256, gRed: false, g: ["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a", "6666666666666666666666666666666666666666666666666666666666666658"] });
    var pre;
    try {
      pre = require_secp256k1();
    } catch (e2) {
      pre = undefined;
    }
    defineCurve("secp256k1", { type: "short", prime: "k256", p: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f", a: "0", b: "7", n: "ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141", h: "1", hash: hash.sha256, beta: "7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee", lambda: "5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72", basis: [{ a: "3086d221a7d46bcde86c90e49284eb15", b: "-e4437ed6010e88286f547fa90abfe4c3" }, { a: "114ca50f7a8e2f3f657c1108d9d44cfd8", b: "3086d221a7d46bcde86c90e49284eb15" }], gRed: false, g: ["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8", pre] });
  });
  require_hmac_drbg = __commonJS2((exports, module) => {
    var hash = require_hash(), utils = require_utils(), assert = require_minimalistic_assert();
    function HmacDRBG(options) {
      if (!(this instanceof HmacDRBG))
        return new HmacDRBG(options);
      this.hash = options.hash, this.predResist = !!options.predResist, this.outLen = this.hash.outSize, this.minEntropy = options.minEntropy || this.hash.hmacStrength, this._reseed = null, this.reseedInterval = null, this.K = null, this.V = null;
      var entropy = utils.toArray(options.entropy, options.entropyEnc || "hex"), nonce = utils.toArray(options.nonce, options.nonceEnc || "hex"), pers = utils.toArray(options.pers, options.persEnc || "hex");
      assert(entropy.length >= this.minEntropy / 8, "Not enough entropy. Minimum is: " + this.minEntropy + " bits"), this._init(entropy, nonce, pers);
    }
    module.exports = HmacDRBG;
    HmacDRBG.prototype._init = function(entropy, nonce, pers) {
      var seed = entropy.concat(nonce).concat(pers);
      this.K = Array(this.outLen / 8), this.V = Array(this.outLen / 8);
      for (var i2 = 0;i2 < this.V.length; i2++)
        this.K[i2] = 0, this.V[i2] = 1;
      this._update(seed), this._reseed = 1, this.reseedInterval = 281474976710656;
    };
    HmacDRBG.prototype._hmac = function() {
      return new hash.hmac(this.hash, this.K);
    };
    HmacDRBG.prototype._update = function(seed) {
      var kmac = this._hmac().update(this.V).update([0]);
      if (seed)
        kmac = kmac.update(seed);
      if (this.K = kmac.digest(), this.V = this._hmac().update(this.V).digest(), !seed)
        return;
      this.K = this._hmac().update(this.V).update([1]).update(seed).digest(), this.V = this._hmac().update(this.V).digest();
    };
    HmacDRBG.prototype.reseed = function(entropy, entropyEnc, add, addEnc) {
      if (typeof entropyEnc !== "string")
        addEnc = add, add = entropyEnc, entropyEnc = null;
      entropy = utils.toArray(entropy, entropyEnc), add = utils.toArray(add, addEnc), assert(entropy.length >= this.minEntropy / 8, "Not enough entropy. Minimum is: " + this.minEntropy + " bits"), this._update(entropy.concat(add || [])), this._reseed = 1;
    };
    HmacDRBG.prototype.generate = function(len2, enc, add, addEnc) {
      if (this._reseed > this.reseedInterval)
        throw Error("Reseed is required");
      if (typeof enc !== "string")
        addEnc = add, add = enc, enc = null;
      if (add)
        add = utils.toArray(add, addEnc || "hex"), this._update(add);
      var temp = [];
      while (temp.length < len2)
        this.V = this._hmac().update(this.V).digest(), temp = temp.concat(this.V);
      var res = temp.slice(0, len2);
      return this._update(add), this._reseed++, utils.encode(res, enc);
    };
  });
  require_key = __commonJS2((exports, module) => {
    var BN = require_bn(), utils = require_utils2(), assert = utils.assert;
    function KeyPair(ec, options) {
      if (this.ec = ec, this.priv = null, this.pub = null, options.priv)
        this._importPrivate(options.priv, options.privEnc);
      if (options.pub)
        this._importPublic(options.pub, options.pubEnc);
    }
    module.exports = KeyPair;
    KeyPair.fromPublic = function(ec, pub, enc) {
      if (pub instanceof KeyPair)
        return pub;
      return new KeyPair(ec, { pub, pubEnc: enc });
    };
    KeyPair.fromPrivate = function(ec, priv, enc) {
      if (priv instanceof KeyPair)
        return priv;
      return new KeyPair(ec, { priv, privEnc: enc });
    };
    KeyPair.prototype.validate = function() {
      var pub = this.getPublic();
      if (pub.isInfinity())
        return { result: false, reason: "Invalid public key" };
      if (!pub.validate())
        return { result: false, reason: "Public key is not a point" };
      if (!pub.mul(this.ec.curve.n).isInfinity())
        return { result: false, reason: "Public key * N != O" };
      return { result: true, reason: null };
    };
    KeyPair.prototype.getPublic = function(compact, enc) {
      if (typeof compact === "string")
        enc = compact, compact = null;
      if (!this.pub)
        this.pub = this.ec.g.mul(this.priv);
      if (!enc)
        return this.pub;
      return this.pub.encode(enc, compact);
    };
    KeyPair.prototype.getPrivate = function(enc) {
      if (enc === "hex")
        return this.priv.toString(16, 2);
      else
        return this.priv;
    };
    KeyPair.prototype._importPrivate = function(key, enc) {
      this.priv = new BN(key, enc || 16), this.priv = this.priv.umod(this.ec.curve.n);
    };
    KeyPair.prototype._importPublic = function(key, enc) {
      if (key.x || key.y) {
        if (this.ec.curve.type === "mont")
          assert(key.x, "Need x coordinate");
        else if (this.ec.curve.type === "short" || this.ec.curve.type === "edwards")
          assert(key.x && key.y, "Need both x and y coordinate");
        this.pub = this.ec.curve.point(key.x, key.y);
        return;
      }
      this.pub = this.ec.curve.decodePoint(key, enc);
    };
    KeyPair.prototype.derive = function(pub) {
      if (!pub.validate())
        assert(pub.validate(), "public point not validated");
      return pub.mul(this.priv).getX();
    };
    KeyPair.prototype.sign = function(msg, enc, options) {
      return this.ec.sign(msg, this, enc, options);
    };
    KeyPair.prototype.verify = function(msg, signature, options) {
      return this.ec.verify(msg, signature, this, undefined, options);
    };
    KeyPair.prototype.inspect = function() {
      return "<Key priv: " + (this.priv && this.priv.toString(16, 2)) + " pub: " + (this.pub && this.pub.inspect()) + " >";
    };
  });
  require_signature = __commonJS2((exports, module) => {
    var BN = require_bn(), utils = require_utils2(), assert = utils.assert;
    function Signature(options, enc) {
      if (options instanceof Signature)
        return options;
      if (this._importDER(options, enc))
        return;
      if (assert(options.r && options.s, "Signature without r or s"), this.r = new BN(options.r, 16), this.s = new BN(options.s, 16), options.recoveryParam === undefined)
        this.recoveryParam = null;
      else
        this.recoveryParam = options.recoveryParam;
    }
    module.exports = Signature;
    function Position() {
      this.place = 0;
    }
    function getLength(buf, p2) {
      var initial = buf[p2.place++];
      if (!(initial & 128))
        return initial;
      var octetLen = initial & 15;
      if (octetLen === 0 || octetLen > 4)
        return false;
      if (buf[p2.place] === 0)
        return false;
      var val = 0;
      for (var i2 = 0, off = p2.place;i2 < octetLen; i2++, off++)
        val <<= 8, val |= buf[off], val >>>= 0;
      if (val <= 127)
        return false;
      return p2.place = off, val;
    }
    function rmPadding(buf) {
      var i2 = 0, len2 = buf.length - 1;
      while (!buf[i2] && !(buf[i2 + 1] & 128) && i2 < len2)
        i2++;
      if (i2 === 0)
        return buf;
      return buf.slice(i2);
    }
    Signature.prototype._importDER = function(data, enc) {
      data = utils.toArray(data, enc);
      var p2 = new Position;
      if (data[p2.place++] !== 48)
        return false;
      var len2 = getLength(data, p2);
      if (len2 === false)
        return false;
      if (len2 + p2.place !== data.length)
        return false;
      if (data[p2.place++] !== 2)
        return false;
      var rlen = getLength(data, p2);
      if (rlen === false)
        return false;
      if ((data[p2.place] & 128) !== 0)
        return false;
      var r2 = data.slice(p2.place, rlen + p2.place);
      if (p2.place += rlen, data[p2.place++] !== 2)
        return false;
      var slen = getLength(data, p2);
      if (slen === false)
        return false;
      if (data.length !== slen + p2.place)
        return false;
      if ((data[p2.place] & 128) !== 0)
        return false;
      var s = data.slice(p2.place, slen + p2.place);
      if (r2[0] === 0)
        if (r2[1] & 128)
          r2 = r2.slice(1);
        else
          return false;
      if (s[0] === 0)
        if (s[1] & 128)
          s = s.slice(1);
        else
          return false;
      return this.r = new BN(r2), this.s = new BN(s), this.recoveryParam = null, true;
    };
    function constructLength(arr, len2) {
      if (len2 < 128) {
        arr.push(len2);
        return;
      }
      var octets = 1 + (Math.log(len2) / Math.LN2 >>> 3);
      arr.push(octets | 128);
      while (--octets)
        arr.push(len2 >>> (octets << 3) & 255);
      arr.push(len2);
    }
    Signature.prototype.toDER = function(enc) {
      var r2 = this.r.toArray(), s = this.s.toArray();
      if (r2[0] & 128)
        r2 = [0].concat(r2);
      if (s[0] & 128)
        s = [0].concat(s);
      r2 = rmPadding(r2), s = rmPadding(s);
      while (!s[0] && !(s[1] & 128))
        s = s.slice(1);
      var arr = [2];
      constructLength(arr, r2.length), arr = arr.concat(r2), arr.push(2), constructLength(arr, s.length);
      var backHalf = arr.concat(s), res = [48];
      return constructLength(res, backHalf.length), res = res.concat(backHalf), utils.encode(res, enc);
    };
  });
  require_ec = __commonJS2((exports, module) => {
    var BN = require_bn(), HmacDRBG = require_hmac_drbg(), utils = require_utils2(), curves = require_curves(), rand = require_brorand(), assert = utils.assert, KeyPair = require_key(), Signature = require_signature();
    function EC(options) {
      if (!(this instanceof EC))
        return new EC(options);
      if (typeof options === "string")
        assert(Object.prototype.hasOwnProperty.call(curves, options), "Unknown curve " + options), options = curves[options];
      if (options instanceof curves.PresetCurve)
        options = { curve: options };
      this.curve = options.curve.curve, this.n = this.curve.n, this.nh = this.n.ushrn(1), this.g = this.curve.g, this.g = options.curve.g, this.g.precompute(options.curve.n.bitLength() + 1), this.hash = options.hash || options.curve.hash;
    }
    module.exports = EC;
    EC.prototype.keyPair = function(options) {
      return new KeyPair(this, options);
    };
    EC.prototype.keyFromPrivate = function(priv, enc) {
      return KeyPair.fromPrivate(this, priv, enc);
    };
    EC.prototype.keyFromPublic = function(pub, enc) {
      return KeyPair.fromPublic(this, pub, enc);
    };
    EC.prototype.genKeyPair = function(options) {
      if (!options)
        options = {};
      var drbg = new HmacDRBG({ hash: this.hash, pers: options.pers, persEnc: options.persEnc || "utf8", entropy: options.entropy || rand(this.hash.hmacStrength), entropyEnc: options.entropy && options.entropyEnc || "utf8", nonce: this.n.toArray() }), bytes = this.n.byteLength(), ns2 = this.n.sub(new BN(2));
      for (;; ) {
        var priv = new BN(drbg.generate(bytes));
        if (priv.cmp(ns2) > 0)
          continue;
        return priv.iaddn(1), this.keyFromPrivate(priv);
      }
    };
    EC.prototype._truncateToN = function(msg, truncOnly, bitLength) {
      var byteLength2;
      if (BN.isBN(msg) || typeof msg === "number")
        msg = new BN(msg, 16), byteLength2 = msg.byteLength();
      else if (typeof msg === "object")
        byteLength2 = msg.length, msg = new BN(msg, 16);
      else {
        var str = msg.toString();
        byteLength2 = str.length + 1 >>> 1, msg = new BN(str, 16);
      }
      if (typeof bitLength !== "number")
        bitLength = byteLength2 * 8;
      var delta = bitLength - this.n.bitLength();
      if (delta > 0)
        msg = msg.ushrn(delta);
      if (!truncOnly && msg.cmp(this.n) >= 0)
        return msg.sub(this.n);
      else
        return msg;
    };
    EC.prototype.sign = function(msg, key, enc, options) {
      if (typeof enc === "object")
        options = enc, enc = null;
      if (!options)
        options = {};
      if (typeof msg !== "string" && typeof msg !== "number" && !BN.isBN(msg)) {
        assert(typeof msg === "object" && msg && typeof msg.length === "number", "Expected message to be an array-like, a hex string, or a BN instance"), assert(msg.length >>> 0 === msg.length);
        for (var i2 = 0;i2 < msg.length; i2++)
          assert((msg[i2] & 255) === msg[i2]);
      }
      key = this.keyFromPrivate(key, enc), msg = this._truncateToN(msg, false, options.msgBitLength), assert(!msg.isNeg(), "Can not sign a negative message");
      var bytes = this.n.byteLength(), bkey = key.getPrivate().toArray("be", bytes), nonce = msg.toArray("be", bytes);
      assert(new BN(nonce).eq(msg), "Can not sign message");
      var drbg = new HmacDRBG({ hash: this.hash, entropy: bkey, nonce, pers: options.pers, persEnc: options.persEnc || "utf8" }), ns1 = this.n.sub(new BN(1));
      for (var iter = 0;; iter++) {
        var k = options.k ? options.k(iter) : new BN(drbg.generate(this.n.byteLength()));
        if (k = this._truncateToN(k, true), k.cmpn(1) <= 0 || k.cmp(ns1) >= 0)
          continue;
        var kp = this.g.mul(k);
        if (kp.isInfinity())
          continue;
        var kpX = kp.getX(), r2 = kpX.umod(this.n);
        if (r2.cmpn(0) === 0)
          continue;
        var s = k.invm(this.n).mul(r2.mul(key.getPrivate()).iadd(msg));
        if (s = s.umod(this.n), s.cmpn(0) === 0)
          continue;
        var recoveryParam = (kp.getY().isOdd() ? 1 : 0) | (kpX.cmp(r2) !== 0 ? 2 : 0);
        if (options.canonical && s.cmp(this.nh) > 0)
          s = this.n.sub(s), recoveryParam ^= 1;
        return new Signature({ r: r2, s, recoveryParam });
      }
    };
    EC.prototype.verify = function(msg, signature, key, enc, options) {
      if (!options)
        options = {};
      msg = this._truncateToN(msg, false, options.msgBitLength), key = this.keyFromPublic(key, enc), signature = new Signature(signature, "hex");
      var { r: r2, s } = signature;
      if (r2.cmpn(1) < 0 || r2.cmp(this.n) >= 0)
        return false;
      if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0)
        return false;
      var sinv = s.invm(this.n), u1 = sinv.mul(msg).umod(this.n), u2 = sinv.mul(r2).umod(this.n), p2;
      if (!this.curve._maxwellTrick) {
        if (p2 = this.g.mulAdd(u1, key.getPublic(), u2), p2.isInfinity())
          return false;
        return p2.getX().umod(this.n).cmp(r2) === 0;
      }
      if (p2 = this.g.jmulAdd(u1, key.getPublic(), u2), p2.isInfinity())
        return false;
      return p2.eqXToP(r2);
    };
    EC.prototype.recoverPubKey = function(msg, signature, j, enc) {
      assert((3 & j) === j, "The recovery param is more than two bits"), signature = new Signature(signature, enc);
      var n2 = this.n, e2 = new BN(msg), r2 = signature.r, s = signature.s, isYOdd = j & 1, isSecondKey = j >> 1;
      if (r2.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey)
        throw Error("Unable to find sencond key candinate");
      if (isSecondKey)
        r2 = this.curve.pointFromX(r2.add(this.curve.n), isYOdd);
      else
        r2 = this.curve.pointFromX(r2, isYOdd);
      var rInv = signature.r.invm(n2), s1 = n2.sub(e2).mul(rInv).umod(n2), s2 = s.mul(rInv).umod(n2);
      return this.g.mulAdd(s1, r2, s2);
    };
    EC.prototype.getKeyRecoveryParam = function(e2, signature, Q, enc) {
      if (signature = new Signature(signature, enc), signature.recoveryParam !== null)
        return signature.recoveryParam;
      for (var i2 = 0;i2 < 4; i2++) {
        var Qprime;
        try {
          Qprime = this.recoverPubKey(e2, signature, i2);
        } catch (e22) {
          continue;
        }
        if (Qprime.eq(Q))
          return i2;
      }
      throw Error("Unable to find valid recovery factor");
    };
  });
  require_key2 = __commonJS2((exports, module) => {
    var utils = require_utils2(), assert = utils.assert, parseBytes = utils.parseBytes, cachedProperty = utils.cachedProperty;
    function KeyPair(eddsa, params) {
      if (this.eddsa = eddsa, this._secret = parseBytes(params.secret), eddsa.isPoint(params.pub))
        this._pub = params.pub;
      else
        this._pubBytes = parseBytes(params.pub);
    }
    KeyPair.fromPublic = function(eddsa, pub) {
      if (pub instanceof KeyPair)
        return pub;
      return new KeyPair(eddsa, { pub });
    };
    KeyPair.fromSecret = function(eddsa, secret) {
      if (secret instanceof KeyPair)
        return secret;
      return new KeyPair(eddsa, { secret });
    };
    KeyPair.prototype.secret = function() {
      return this._secret;
    };
    cachedProperty(KeyPair, "pubBytes", function() {
      return this.eddsa.encodePoint(this.pub());
    });
    cachedProperty(KeyPair, "pub", function() {
      if (this._pubBytes)
        return this.eddsa.decodePoint(this._pubBytes);
      return this.eddsa.g.mul(this.priv());
    });
    cachedProperty(KeyPair, "privBytes", function() {
      var eddsa = this.eddsa, hash = this.hash(), lastIx = eddsa.encodingLength - 1, a2 = hash.slice(0, eddsa.encodingLength);
      return a2[0] &= 248, a2[lastIx] &= 127, a2[lastIx] |= 64, a2;
    });
    cachedProperty(KeyPair, "priv", function() {
      return this.eddsa.decodeInt(this.privBytes());
    });
    cachedProperty(KeyPair, "hash", function() {
      return this.eddsa.hash().update(this.secret()).digest();
    });
    cachedProperty(KeyPair, "messagePrefix", function() {
      return this.hash().slice(this.eddsa.encodingLength);
    });
    KeyPair.prototype.sign = function(message) {
      return assert(this._secret, "KeyPair can only verify"), this.eddsa.sign(message, this);
    };
    KeyPair.prototype.verify = function(message, sig) {
      return this.eddsa.verify(message, sig, this);
    };
    KeyPair.prototype.getSecret = function(enc) {
      return assert(this._secret, "KeyPair is public only"), utils.encode(this.secret(), enc);
    };
    KeyPair.prototype.getPublic = function(enc) {
      return utils.encode(this.pubBytes(), enc);
    };
    module.exports = KeyPair;
  });
  require_signature2 = __commonJS2((exports, module) => {
    var BN = require_bn(), utils = require_utils2(), assert = utils.assert, cachedProperty = utils.cachedProperty, parseBytes = utils.parseBytes;
    function Signature(eddsa, sig) {
      if (this.eddsa = eddsa, typeof sig !== "object")
        sig = parseBytes(sig);
      if (Array.isArray(sig))
        assert(sig.length === eddsa.encodingLength * 2, "Signature has invalid size"), sig = { R: sig.slice(0, eddsa.encodingLength), S: sig.slice(eddsa.encodingLength) };
      if (assert(sig.R && sig.S, "Signature without R or S"), eddsa.isPoint(sig.R))
        this._R = sig.R;
      if (sig.S instanceof BN)
        this._S = sig.S;
      this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded, this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded;
    }
    cachedProperty(Signature, "S", function() {
      return this.eddsa.decodeInt(this.Sencoded());
    });
    cachedProperty(Signature, "R", function() {
      return this.eddsa.decodePoint(this.Rencoded());
    });
    cachedProperty(Signature, "Rencoded", function() {
      return this.eddsa.encodePoint(this.R());
    });
    cachedProperty(Signature, "Sencoded", function() {
      return this.eddsa.encodeInt(this.S());
    });
    Signature.prototype.toBytes = function() {
      return this.Rencoded().concat(this.Sencoded());
    };
    Signature.prototype.toHex = function() {
      return utils.encode(this.toBytes(), "hex").toUpperCase();
    };
    module.exports = Signature;
  });
  require_eddsa = __commonJS2((exports, module) => {
    var hash = require_hash(), curves = require_curves(), utils = require_utils2(), assert = utils.assert, parseBytes = utils.parseBytes, KeyPair = require_key2(), Signature = require_signature2();
    function EDDSA(curve) {
      if (assert(curve === "ed25519", "only tested with ed25519 so far"), !(this instanceof EDDSA))
        return new EDDSA(curve);
      curve = curves[curve].curve, this.curve = curve, this.g = curve.g, this.g.precompute(curve.n.bitLength() + 1), this.pointClass = curve.point().constructor, this.encodingLength = Math.ceil(curve.n.bitLength() / 8), this.hash = hash.sha512;
    }
    module.exports = EDDSA;
    EDDSA.prototype.sign = function(message, secret) {
      message = parseBytes(message);
      var key = this.keyFromSecret(secret), r2 = this.hashInt(key.messagePrefix(), message), R = this.g.mul(r2), Rencoded = this.encodePoint(R), s_ = this.hashInt(Rencoded, key.pubBytes(), message).mul(key.priv()), S = r2.add(s_).umod(this.curve.n);
      return this.makeSignature({ R, S, Rencoded });
    };
    EDDSA.prototype.verify = function(message, sig, pub) {
      if (message = parseBytes(message), sig = this.makeSignature(sig), sig.S().gte(sig.eddsa.curve.n) || sig.S().isNeg())
        return false;
      var key = this.keyFromPublic(pub), h = this.hashInt(sig.Rencoded(), key.pubBytes(), message), SG = this.g.mul(sig.S()), RplusAh = sig.R().add(key.pub().mul(h));
      return RplusAh.eq(SG);
    };
    EDDSA.prototype.hashInt = function() {
      var hash2 = this.hash();
      for (var i2 = 0;i2 < arguments.length; i2++)
        hash2.update(arguments[i2]);
      return utils.intFromLE(hash2.digest()).umod(this.curve.n);
    };
    EDDSA.prototype.keyFromPublic = function(pub) {
      return KeyPair.fromPublic(this, pub);
    };
    EDDSA.prototype.keyFromSecret = function(secret) {
      return KeyPair.fromSecret(this, secret);
    };
    EDDSA.prototype.makeSignature = function(sig) {
      if (sig instanceof Signature)
        return sig;
      return new Signature(this, sig);
    };
    EDDSA.prototype.encodePoint = function(point) {
      var enc = point.getY().toArray("le", this.encodingLength);
      return enc[this.encodingLength - 1] |= point.getX().isOdd() ? 128 : 0, enc;
    };
    EDDSA.prototype.decodePoint = function(bytes) {
      bytes = utils.parseBytes(bytes);
      var lastIx = bytes.length - 1, normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & -129), xIsOdd = (bytes[lastIx] & 128) !== 0, y = utils.intFromLE(normed);
      return this.curve.pointFromY(y, xIsOdd);
    };
    EDDSA.prototype.encodeInt = function(num) {
      return num.toArray("le", this.encodingLength);
    };
    EDDSA.prototype.decodeInt = function(bytes) {
      return utils.intFromLE(bytes);
    };
    EDDSA.prototype.isPoint = function(val) {
      return val instanceof this.pointClass;
    };
  });
  require_elliptic = __commonJS2((exports) => {
    var elliptic = exports;
    elliptic.version = require_package().version;
    elliptic.utils = require_utils2();
    elliptic.rand = require_brorand();
    elliptic.curve = require_curve();
    elliptic.curves = require_curves();
    elliptic.ec = require_ec();
    elliptic.eddsa = require_eddsa();
  });
  require_bn2 = __commonJS2((exports, module) => {
    (function(module2, exports2) {
      function assert(val, msg) {
        if (!val)
          throw Error(msg || "Assertion failed");
      }
      function inherits2(ctor, superCtor) {
        ctor.super_ = superCtor;
        var TempCtor = function() {};
        TempCtor.prototype = superCtor.prototype, ctor.prototype = new TempCtor, ctor.prototype.constructor = ctor;
      }
      function BN(number, base, endian) {
        if (BN.isBN(number))
          return number;
        if (this.negative = 0, this.words = null, this.length = 0, this.red = null, number !== null) {
          if (base === "le" || base === "be")
            endian = base, base = 10;
          this._init(number || 0, base || 10, endian || "be");
        }
      }
      if (typeof module2 === "object")
        module2.exports = BN;
      else
        exports2.BN = BN;
      BN.BN = BN, BN.wordSize = 26;
      var Buffer22;
      try {
        if (typeof window < "u" && typeof window.Buffer < "u")
          Buffer22 = window.Buffer;
        else
          Buffer22 = (init_buffer(), __toCommonJS(exports_buffer)).Buffer;
      } catch (e2) {}
      BN.isBN = function(num) {
        if (num instanceof BN)
          return true;
        return num !== null && typeof num === "object" && num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
      }, BN.max = function(left, right) {
        if (left.cmp(right) > 0)
          return left;
        return right;
      }, BN.min = function(left, right) {
        if (left.cmp(right) < 0)
          return left;
        return right;
      }, BN.prototype._init = function(number, base, endian) {
        if (typeof number === "number")
          return this._initNumber(number, base, endian);
        if (typeof number === "object")
          return this._initArray(number, base, endian);
        if (base === "hex")
          base = 16;
        assert(base === (base | 0) && base >= 2 && base <= 36), number = number.toString().replace(/\s+/g, "");
        var start = 0;
        if (number[0] === "-")
          start++, this.negative = 1;
        if (start < number.length) {
          if (base === 16)
            this._parseHex(number, start, endian);
          else if (this._parseBase(number, base, start), endian === "le")
            this._initArray(this.toArray(), base, endian);
        }
      }, BN.prototype._initNumber = function(number, base, endian) {
        if (number < 0)
          this.negative = 1, number = -number;
        if (number < 67108864)
          this.words = [number & 67108863], this.length = 1;
        else if (number < 4503599627370496)
          this.words = [number & 67108863, number / 67108864 & 67108863], this.length = 2;
        else
          assert(number < 9007199254740992), this.words = [number & 67108863, number / 67108864 & 67108863, 1], this.length = 3;
        if (endian !== "le")
          return;
        this._initArray(this.toArray(), base, endian);
      }, BN.prototype._initArray = function(number, base, endian) {
        if (assert(typeof number.length === "number"), number.length <= 0)
          return this.words = [0], this.length = 1, this;
        this.length = Math.ceil(number.length / 3), this.words = Array(this.length);
        for (var i2 = 0;i2 < this.length; i2++)
          this.words[i2] = 0;
        var j, w, off = 0;
        if (endian === "be") {
          for (i2 = number.length - 1, j = 0;i2 >= 0; i2 -= 3)
            if (w = number[i2] | number[i2 - 1] << 8 | number[i2 - 2] << 16, this.words[j] |= w << off & 67108863, this.words[j + 1] = w >>> 26 - off & 67108863, off += 24, off >= 26)
              off -= 26, j++;
        } else if (endian === "le") {
          for (i2 = 0, j = 0;i2 < number.length; i2 += 3)
            if (w = number[i2] | number[i2 + 1] << 8 | number[i2 + 2] << 16, this.words[j] |= w << off & 67108863, this.words[j + 1] = w >>> 26 - off & 67108863, off += 24, off >= 26)
              off -= 26, j++;
        }
        return this.strip();
      };
      function parseHex4Bits(string, index) {
        var c2 = string.charCodeAt(index);
        if (c2 >= 65 && c2 <= 70)
          return c2 - 55;
        else if (c2 >= 97 && c2 <= 102)
          return c2 - 87;
        else
          return c2 - 48 & 15;
      }
      function parseHexByte(string, lowerBound, index) {
        var r2 = parseHex4Bits(string, index);
        if (index - 1 >= lowerBound)
          r2 |= parseHex4Bits(string, index - 1) << 4;
        return r2;
      }
      BN.prototype._parseHex = function(number, start, endian) {
        this.length = Math.ceil((number.length - start) / 6), this.words = Array(this.length);
        for (var i2 = 0;i2 < this.length; i2++)
          this.words[i2] = 0;
        var off = 0, j = 0, w;
        if (endian === "be")
          for (i2 = number.length - 1;i2 >= start; i2 -= 2)
            if (w = parseHexByte(number, start, i2) << off, this.words[j] |= w & 67108863, off >= 18)
              off -= 18, j += 1, this.words[j] |= w >>> 26;
            else
              off += 8;
        else {
          var parseLength = number.length - start;
          for (i2 = parseLength % 2 === 0 ? start + 1 : start;i2 < number.length; i2 += 2)
            if (w = parseHexByte(number, start, i2) << off, this.words[j] |= w & 67108863, off >= 18)
              off -= 18, j += 1, this.words[j] |= w >>> 26;
            else
              off += 8;
        }
        this.strip();
      };
      function parseBase(str, start, end, mul) {
        var r2 = 0, len2 = Math.min(str.length, end);
        for (var i2 = start;i2 < len2; i2++) {
          var c2 = str.charCodeAt(i2) - 48;
          if (r2 *= mul, c2 >= 49)
            r2 += c2 - 49 + 10;
          else if (c2 >= 17)
            r2 += c2 - 17 + 10;
          else
            r2 += c2;
        }
        return r2;
      }
      BN.prototype._parseBase = function(number, base, start) {
        this.words = [0], this.length = 1;
        for (var limbLen = 0, limbPow = 1;limbPow <= 67108863; limbPow *= base)
          limbLen++;
        limbLen--, limbPow = limbPow / base | 0;
        var total = number.length - start, mod = total % limbLen, end = Math.min(total, total - mod) + start, word = 0;
        for (var i2 = start;i2 < end; i2 += limbLen)
          if (word = parseBase(number, i2, i2 + limbLen, base), this.imuln(limbPow), this.words[0] + word < 67108864)
            this.words[0] += word;
          else
            this._iaddn(word);
        if (mod !== 0) {
          var pow = 1;
          word = parseBase(number, i2, number.length, base);
          for (i2 = 0;i2 < mod; i2++)
            pow *= base;
          if (this.imuln(pow), this.words[0] + word < 67108864)
            this.words[0] += word;
          else
            this._iaddn(word);
        }
        this.strip();
      }, BN.prototype.copy = function(dest) {
        dest.words = Array(this.length);
        for (var i2 = 0;i2 < this.length; i2++)
          dest.words[i2] = this.words[i2];
        dest.length = this.length, dest.negative = this.negative, dest.red = this.red;
      }, BN.prototype.clone = function() {
        var r2 = new BN(null);
        return this.copy(r2), r2;
      }, BN.prototype._expand = function(size) {
        while (this.length < size)
          this.words[this.length++] = 0;
        return this;
      }, BN.prototype.strip = function() {
        while (this.length > 1 && this.words[this.length - 1] === 0)
          this.length--;
        return this._normSign();
      }, BN.prototype._normSign = function() {
        if (this.length === 1 && this.words[0] === 0)
          this.negative = 0;
        return this;
      }, BN.prototype.inspect = function() {
        return (this.red ? "<BN-R: " : "<BN: ") + this.toString(16) + ">";
      };
      var zeros = ["", "0", "00", "000", "0000", "00000", "000000", "0000000", "00000000", "000000000", "0000000000", "00000000000", "000000000000", "0000000000000", "00000000000000", "000000000000000", "0000000000000000", "00000000000000000", "000000000000000000", "0000000000000000000", "00000000000000000000", "000000000000000000000", "0000000000000000000000", "00000000000000000000000", "000000000000000000000000", "0000000000000000000000000"], groupSizes = [0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5], groupBases = [0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 1e7, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176];
      if (BN.prototype.toString = function(base, padding) {
        base = base || 10, padding = padding | 0 || 1;
        var out;
        if (base === 16 || base === "hex") {
          out = "";
          var off = 0, carry = 0;
          for (var i2 = 0;i2 < this.length; i2++) {
            var w = this.words[i2], word = ((w << off | carry) & 16777215).toString(16);
            if (carry = w >>> 24 - off & 16777215, off += 2, off >= 26)
              off -= 26, i2--;
            if (carry !== 0 || i2 !== this.length - 1)
              out = zeros[6 - word.length] + word + out;
            else
              out = word + out;
          }
          if (carry !== 0)
            out = carry.toString(16) + out;
          while (out.length % padding !== 0)
            out = "0" + out;
          if (this.negative !== 0)
            out = "-" + out;
          return out;
        }
        if (base === (base | 0) && base >= 2 && base <= 36) {
          var groupSize = groupSizes[base], groupBase = groupBases[base];
          out = "";
          var c2 = this.clone();
          c2.negative = 0;
          while (!c2.isZero()) {
            var r2 = c2.modn(groupBase).toString(base);
            if (c2 = c2.idivn(groupBase), !c2.isZero())
              out = zeros[groupSize - r2.length] + r2 + out;
            else
              out = r2 + out;
          }
          if (this.isZero())
            out = "0" + out;
          while (out.length % padding !== 0)
            out = "0" + out;
          if (this.negative !== 0)
            out = "-" + out;
          return out;
        }
        assert(false, "Base should be between 2 and 36");
      }, BN.prototype.toNumber = function() {
        var ret = this.words[0];
        if (this.length === 2)
          ret += this.words[1] * 67108864;
        else if (this.length === 3 && this.words[2] === 1)
          ret += 4503599627370496 + this.words[1] * 67108864;
        else if (this.length > 2)
          assert(false, "Number can only safely store up to 53 bits");
        return this.negative !== 0 ? -ret : ret;
      }, BN.prototype.toJSON = function() {
        return this.toString(16);
      }, BN.prototype.toBuffer = function(endian, length) {
        return assert(typeof Buffer22 < "u"), this.toArrayLike(Buffer22, endian, length);
      }, BN.prototype.toArray = function(endian, length) {
        return this.toArrayLike(Array, endian, length);
      }, BN.prototype.toArrayLike = function(ArrayType, endian, length) {
        var byteLength2 = this.byteLength(), reqLength = length || Math.max(1, byteLength2);
        assert(byteLength2 <= reqLength, "byte array longer than desired length"), assert(reqLength > 0, "Requested array length <= 0"), this.strip();
        var littleEndian = endian === "le", res = new ArrayType(reqLength), b, i2, q = this.clone();
        if (!littleEndian) {
          for (i2 = 0;i2 < reqLength - byteLength2; i2++)
            res[i2] = 0;
          for (i2 = 0;!q.isZero(); i2++)
            b = q.andln(255), q.iushrn(8), res[reqLength - i2 - 1] = b;
        } else {
          for (i2 = 0;!q.isZero(); i2++)
            b = q.andln(255), q.iushrn(8), res[i2] = b;
          for (;i2 < reqLength; i2++)
            res[i2] = 0;
        }
        return res;
      }, Math.clz32)
        BN.prototype._countBits = function(w) {
          return 32 - Math.clz32(w);
        };
      else
        BN.prototype._countBits = function(w) {
          var t2 = w, r2 = 0;
          if (t2 >= 4096)
            r2 += 13, t2 >>>= 13;
          if (t2 >= 64)
            r2 += 7, t2 >>>= 7;
          if (t2 >= 8)
            r2 += 4, t2 >>>= 4;
          if (t2 >= 2)
            r2 += 2, t2 >>>= 2;
          return r2 + t2;
        };
      BN.prototype._zeroBits = function(w) {
        if (w === 0)
          return 26;
        var t2 = w, r2 = 0;
        if ((t2 & 8191) === 0)
          r2 += 13, t2 >>>= 13;
        if ((t2 & 127) === 0)
          r2 += 7, t2 >>>= 7;
        if ((t2 & 15) === 0)
          r2 += 4, t2 >>>= 4;
        if ((t2 & 3) === 0)
          r2 += 2, t2 >>>= 2;
        if ((t2 & 1) === 0)
          r2++;
        return r2;
      }, BN.prototype.bitLength = function() {
        var w = this.words[this.length - 1], hi = this._countBits(w);
        return (this.length - 1) * 26 + hi;
      };
      function toBitArray(num) {
        var w = Array(num.bitLength());
        for (var bit = 0;bit < w.length; bit++) {
          var off = bit / 26 | 0, wbit = bit % 26;
          w[bit] = (num.words[off] & 1 << wbit) >>> wbit;
        }
        return w;
      }
      BN.prototype.zeroBits = function() {
        if (this.isZero())
          return 0;
        var r2 = 0;
        for (var i2 = 0;i2 < this.length; i2++) {
          var b = this._zeroBits(this.words[i2]);
          if (r2 += b, b !== 26)
            break;
        }
        return r2;
      }, BN.prototype.byteLength = function() {
        return Math.ceil(this.bitLength() / 8);
      }, BN.prototype.toTwos = function(width) {
        if (this.negative !== 0)
          return this.abs().inotn(width).iaddn(1);
        return this.clone();
      }, BN.prototype.fromTwos = function(width) {
        if (this.testn(width - 1))
          return this.notn(width).iaddn(1).ineg();
        return this.clone();
      }, BN.prototype.isNeg = function() {
        return this.negative !== 0;
      }, BN.prototype.neg = function() {
        return this.clone().ineg();
      }, BN.prototype.ineg = function() {
        if (!this.isZero())
          this.negative ^= 1;
        return this;
      }, BN.prototype.iuor = function(num) {
        while (this.length < num.length)
          this.words[this.length++] = 0;
        for (var i2 = 0;i2 < num.length; i2++)
          this.words[i2] = this.words[i2] | num.words[i2];
        return this.strip();
      }, BN.prototype.ior = function(num) {
        return assert((this.negative | num.negative) === 0), this.iuor(num);
      }, BN.prototype.or = function(num) {
        if (this.length > num.length)
          return this.clone().ior(num);
        return num.clone().ior(this);
      }, BN.prototype.uor = function(num) {
        if (this.length > num.length)
          return this.clone().iuor(num);
        return num.clone().iuor(this);
      }, BN.prototype.iuand = function(num) {
        var b;
        if (this.length > num.length)
          b = num;
        else
          b = this;
        for (var i2 = 0;i2 < b.length; i2++)
          this.words[i2] = this.words[i2] & num.words[i2];
        return this.length = b.length, this.strip();
      }, BN.prototype.iand = function(num) {
        return assert((this.negative | num.negative) === 0), this.iuand(num);
      }, BN.prototype.and = function(num) {
        if (this.length > num.length)
          return this.clone().iand(num);
        return num.clone().iand(this);
      }, BN.prototype.uand = function(num) {
        if (this.length > num.length)
          return this.clone().iuand(num);
        return num.clone().iuand(this);
      }, BN.prototype.iuxor = function(num) {
        var a2, b;
        if (this.length > num.length)
          a2 = this, b = num;
        else
          a2 = num, b = this;
        for (var i2 = 0;i2 < b.length; i2++)
          this.words[i2] = a2.words[i2] ^ b.words[i2];
        if (this !== a2)
          for (;i2 < a2.length; i2++)
            this.words[i2] = a2.words[i2];
        return this.length = a2.length, this.strip();
      }, BN.prototype.ixor = function(num) {
        return assert((this.negative | num.negative) === 0), this.iuxor(num);
      }, BN.prototype.xor = function(num) {
        if (this.length > num.length)
          return this.clone().ixor(num);
        return num.clone().ixor(this);
      }, BN.prototype.uxor = function(num) {
        if (this.length > num.length)
          return this.clone().iuxor(num);
        return num.clone().iuxor(this);
      }, BN.prototype.inotn = function(width) {
        assert(typeof width === "number" && width >= 0);
        var bytesNeeded = Math.ceil(width / 26) | 0, bitsLeft = width % 26;
        if (this._expand(bytesNeeded), bitsLeft > 0)
          bytesNeeded--;
        for (var i2 = 0;i2 < bytesNeeded; i2++)
          this.words[i2] = ~this.words[i2] & 67108863;
        if (bitsLeft > 0)
          this.words[i2] = ~this.words[i2] & 67108863 >> 26 - bitsLeft;
        return this.strip();
      }, BN.prototype.notn = function(width) {
        return this.clone().inotn(width);
      }, BN.prototype.setn = function(bit, val) {
        assert(typeof bit === "number" && bit >= 0);
        var off = bit / 26 | 0, wbit = bit % 26;
        if (this._expand(off + 1), val)
          this.words[off] = this.words[off] | 1 << wbit;
        else
          this.words[off] = this.words[off] & ~(1 << wbit);
        return this.strip();
      }, BN.prototype.iadd = function(num) {
        var r2;
        if (this.negative !== 0 && num.negative === 0)
          return this.negative = 0, r2 = this.isub(num), this.negative ^= 1, this._normSign();
        else if (this.negative === 0 && num.negative !== 0)
          return num.negative = 0, r2 = this.isub(num), num.negative = 1, r2._normSign();
        var a2, b;
        if (this.length > num.length)
          a2 = this, b = num;
        else
          a2 = num, b = this;
        var carry = 0;
        for (var i2 = 0;i2 < b.length; i2++)
          r2 = (a2.words[i2] | 0) + (b.words[i2] | 0) + carry, this.words[i2] = r2 & 67108863, carry = r2 >>> 26;
        for (;carry !== 0 && i2 < a2.length; i2++)
          r2 = (a2.words[i2] | 0) + carry, this.words[i2] = r2 & 67108863, carry = r2 >>> 26;
        if (this.length = a2.length, carry !== 0)
          this.words[this.length] = carry, this.length++;
        else if (a2 !== this)
          for (;i2 < a2.length; i2++)
            this.words[i2] = a2.words[i2];
        return this;
      }, BN.prototype.add = function(num) {
        var res;
        if (num.negative !== 0 && this.negative === 0)
          return num.negative = 0, res = this.sub(num), num.negative ^= 1, res;
        else if (num.negative === 0 && this.negative !== 0)
          return this.negative = 0, res = num.sub(this), this.negative = 1, res;
        if (this.length > num.length)
          return this.clone().iadd(num);
        return num.clone().iadd(this);
      }, BN.prototype.isub = function(num) {
        if (num.negative !== 0) {
          num.negative = 0;
          var r2 = this.iadd(num);
          return num.negative = 1, r2._normSign();
        } else if (this.negative !== 0)
          return this.negative = 0, this.iadd(num), this.negative = 1, this._normSign();
        var cmp = this.cmp(num);
        if (cmp === 0)
          return this.negative = 0, this.length = 1, this.words[0] = 0, this;
        var a2, b;
        if (cmp > 0)
          a2 = this, b = num;
        else
          a2 = num, b = this;
        var carry = 0;
        for (var i2 = 0;i2 < b.length; i2++)
          r2 = (a2.words[i2] | 0) - (b.words[i2] | 0) + carry, carry = r2 >> 26, this.words[i2] = r2 & 67108863;
        for (;carry !== 0 && i2 < a2.length; i2++)
          r2 = (a2.words[i2] | 0) + carry, carry = r2 >> 26, this.words[i2] = r2 & 67108863;
        if (carry === 0 && i2 < a2.length && a2 !== this)
          for (;i2 < a2.length; i2++)
            this.words[i2] = a2.words[i2];
        if (this.length = Math.max(this.length, i2), a2 !== this)
          this.negative = 1;
        return this.strip();
      }, BN.prototype.sub = function(num) {
        return this.clone().isub(num);
      };
      function smallMulTo(self2, num, out) {
        out.negative = num.negative ^ self2.negative;
        var len2 = self2.length + num.length | 0;
        out.length = len2, len2 = len2 - 1 | 0;
        var a2 = self2.words[0] | 0, b = num.words[0] | 0, r2 = a2 * b, lo = r2 & 67108863, carry = r2 / 67108864 | 0;
        out.words[0] = lo;
        for (var k = 1;k < len2; k++) {
          var ncarry = carry >>> 26, rword = carry & 67108863, maxJ = Math.min(k, num.length - 1);
          for (var j = Math.max(0, k - self2.length + 1);j <= maxJ; j++) {
            var i2 = k - j | 0;
            a2 = self2.words[i2] | 0, b = num.words[j] | 0, r2 = a2 * b + rword, ncarry += r2 / 67108864 | 0, rword = r2 & 67108863;
          }
          out.words[k] = rword | 0, carry = ncarry | 0;
        }
        if (carry !== 0)
          out.words[k] = carry | 0;
        else
          out.length--;
        return out.strip();
      }
      var comb10MulTo = function(self2, num, out) {
        var a2 = self2.words, b = num.words, o2 = out.words, c2 = 0, lo, mid, hi, a0 = a2[0] | 0, al0 = a0 & 8191, ah0 = a0 >>> 13, a1 = a2[1] | 0, al1 = a1 & 8191, ah1 = a1 >>> 13, a22 = a2[2] | 0, al2 = a22 & 8191, ah2 = a22 >>> 13, a3 = a2[3] | 0, al3 = a3 & 8191, ah3 = a3 >>> 13, a4 = a2[4] | 0, al4 = a4 & 8191, ah4 = a4 >>> 13, a5 = a2[5] | 0, al5 = a5 & 8191, ah5 = a5 >>> 13, a6 = a2[6] | 0, al6 = a6 & 8191, ah6 = a6 >>> 13, a7 = a2[7] | 0, al7 = a7 & 8191, ah7 = a7 >>> 13, a8 = a2[8] | 0, al8 = a8 & 8191, ah8 = a8 >>> 13, a9 = a2[9] | 0, al9 = a9 & 8191, ah9 = a9 >>> 13, b0 = b[0] | 0, bl0 = b0 & 8191, bh0 = b0 >>> 13, b1 = b[1] | 0, bl1 = b1 & 8191, bh1 = b1 >>> 13, b2 = b[2] | 0, bl2 = b2 & 8191, bh2 = b2 >>> 13, b3 = b[3] | 0, bl3 = b3 & 8191, bh3 = b3 >>> 13, b4 = b[4] | 0, bl4 = b4 & 8191, bh4 = b4 >>> 13, b5 = b[5] | 0, bl5 = b5 & 8191, bh5 = b5 >>> 13, b6 = b[6] | 0, bl6 = b6 & 8191, bh6 = b6 >>> 13, b7 = b[7] | 0, bl7 = b7 & 8191, bh7 = b7 >>> 13, b8 = b[8] | 0, bl8 = b8 & 8191, bh8 = b8 >>> 13, b9 = b[9] | 0, bl9 = b9 & 8191, bh9 = b9 >>> 13;
        out.negative = self2.negative ^ num.negative, out.length = 19, lo = Math.imul(al0, bl0), mid = Math.imul(al0, bh0), mid = mid + Math.imul(ah0, bl0) | 0, hi = Math.imul(ah0, bh0);
        var w0 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w0 >>> 26) | 0, w0 &= 67108863, lo = Math.imul(al1, bl0), mid = Math.imul(al1, bh0), mid = mid + Math.imul(ah1, bl0) | 0, hi = Math.imul(ah1, bh0), lo = lo + Math.imul(al0, bl1) | 0, mid = mid + Math.imul(al0, bh1) | 0, mid = mid + Math.imul(ah0, bl1) | 0, hi = hi + Math.imul(ah0, bh1) | 0;
        var w1 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w1 >>> 26) | 0, w1 &= 67108863, lo = Math.imul(al2, bl0), mid = Math.imul(al2, bh0), mid = mid + Math.imul(ah2, bl0) | 0, hi = Math.imul(ah2, bh0), lo = lo + Math.imul(al1, bl1) | 0, mid = mid + Math.imul(al1, bh1) | 0, mid = mid + Math.imul(ah1, bl1) | 0, hi = hi + Math.imul(ah1, bh1) | 0, lo = lo + Math.imul(al0, bl2) | 0, mid = mid + Math.imul(al0, bh2) | 0, mid = mid + Math.imul(ah0, bl2) | 0, hi = hi + Math.imul(ah0, bh2) | 0;
        var w2 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w2 >>> 26) | 0, w2 &= 67108863, lo = Math.imul(al3, bl0), mid = Math.imul(al3, bh0), mid = mid + Math.imul(ah3, bl0) | 0, hi = Math.imul(ah3, bh0), lo = lo + Math.imul(al2, bl1) | 0, mid = mid + Math.imul(al2, bh1) | 0, mid = mid + Math.imul(ah2, bl1) | 0, hi = hi + Math.imul(ah2, bh1) | 0, lo = lo + Math.imul(al1, bl2) | 0, mid = mid + Math.imul(al1, bh2) | 0, mid = mid + Math.imul(ah1, bl2) | 0, hi = hi + Math.imul(ah1, bh2) | 0, lo = lo + Math.imul(al0, bl3) | 0, mid = mid + Math.imul(al0, bh3) | 0, mid = mid + Math.imul(ah0, bl3) | 0, hi = hi + Math.imul(ah0, bh3) | 0;
        var w3 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w3 >>> 26) | 0, w3 &= 67108863, lo = Math.imul(al4, bl0), mid = Math.imul(al4, bh0), mid = mid + Math.imul(ah4, bl0) | 0, hi = Math.imul(ah4, bh0), lo = lo + Math.imul(al3, bl1) | 0, mid = mid + Math.imul(al3, bh1) | 0, mid = mid + Math.imul(ah3, bl1) | 0, hi = hi + Math.imul(ah3, bh1) | 0, lo = lo + Math.imul(al2, bl2) | 0, mid = mid + Math.imul(al2, bh2) | 0, mid = mid + Math.imul(ah2, bl2) | 0, hi = hi + Math.imul(ah2, bh2) | 0, lo = lo + Math.imul(al1, bl3) | 0, mid = mid + Math.imul(al1, bh3) | 0, mid = mid + Math.imul(ah1, bl3) | 0, hi = hi + Math.imul(ah1, bh3) | 0, lo = lo + Math.imul(al0, bl4) | 0, mid = mid + Math.imul(al0, bh4) | 0, mid = mid + Math.imul(ah0, bl4) | 0, hi = hi + Math.imul(ah0, bh4) | 0;
        var w4 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w4 >>> 26) | 0, w4 &= 67108863, lo = Math.imul(al5, bl0), mid = Math.imul(al5, bh0), mid = mid + Math.imul(ah5, bl0) | 0, hi = Math.imul(ah5, bh0), lo = lo + Math.imul(al4, bl1) | 0, mid = mid + Math.imul(al4, bh1) | 0, mid = mid + Math.imul(ah4, bl1) | 0, hi = hi + Math.imul(ah4, bh1) | 0, lo = lo + Math.imul(al3, bl2) | 0, mid = mid + Math.imul(al3, bh2) | 0, mid = mid + Math.imul(ah3, bl2) | 0, hi = hi + Math.imul(ah3, bh2) | 0, lo = lo + Math.imul(al2, bl3) | 0, mid = mid + Math.imul(al2, bh3) | 0, mid = mid + Math.imul(ah2, bl3) | 0, hi = hi + Math.imul(ah2, bh3) | 0, lo = lo + Math.imul(al1, bl4) | 0, mid = mid + Math.imul(al1, bh4) | 0, mid = mid + Math.imul(ah1, bl4) | 0, hi = hi + Math.imul(ah1, bh4) | 0, lo = lo + Math.imul(al0, bl5) | 0, mid = mid + Math.imul(al0, bh5) | 0, mid = mid + Math.imul(ah0, bl5) | 0, hi = hi + Math.imul(ah0, bh5) | 0;
        var w5 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w5 >>> 26) | 0, w5 &= 67108863, lo = Math.imul(al6, bl0), mid = Math.imul(al6, bh0), mid = mid + Math.imul(ah6, bl0) | 0, hi = Math.imul(ah6, bh0), lo = lo + Math.imul(al5, bl1) | 0, mid = mid + Math.imul(al5, bh1) | 0, mid = mid + Math.imul(ah5, bl1) | 0, hi = hi + Math.imul(ah5, bh1) | 0, lo = lo + Math.imul(al4, bl2) | 0, mid = mid + Math.imul(al4, bh2) | 0, mid = mid + Math.imul(ah4, bl2) | 0, hi = hi + Math.imul(ah4, bh2) | 0, lo = lo + Math.imul(al3, bl3) | 0, mid = mid + Math.imul(al3, bh3) | 0, mid = mid + Math.imul(ah3, bl3) | 0, hi = hi + Math.imul(ah3, bh3) | 0, lo = lo + Math.imul(al2, bl4) | 0, mid = mid + Math.imul(al2, bh4) | 0, mid = mid + Math.imul(ah2, bl4) | 0, hi = hi + Math.imul(ah2, bh4) | 0, lo = lo + Math.imul(al1, bl5) | 0, mid = mid + Math.imul(al1, bh5) | 0, mid = mid + Math.imul(ah1, bl5) | 0, hi = hi + Math.imul(ah1, bh5) | 0, lo = lo + Math.imul(al0, bl6) | 0, mid = mid + Math.imul(al0, bh6) | 0, mid = mid + Math.imul(ah0, bl6) | 0, hi = hi + Math.imul(ah0, bh6) | 0;
        var w6 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w6 >>> 26) | 0, w6 &= 67108863, lo = Math.imul(al7, bl0), mid = Math.imul(al7, bh0), mid = mid + Math.imul(ah7, bl0) | 0, hi = Math.imul(ah7, bh0), lo = lo + Math.imul(al6, bl1) | 0, mid = mid + Math.imul(al6, bh1) | 0, mid = mid + Math.imul(ah6, bl1) | 0, hi = hi + Math.imul(ah6, bh1) | 0, lo = lo + Math.imul(al5, bl2) | 0, mid = mid + Math.imul(al5, bh2) | 0, mid = mid + Math.imul(ah5, bl2) | 0, hi = hi + Math.imul(ah5, bh2) | 0, lo = lo + Math.imul(al4, bl3) | 0, mid = mid + Math.imul(al4, bh3) | 0, mid = mid + Math.imul(ah4, bl3) | 0, hi = hi + Math.imul(ah4, bh3) | 0, lo = lo + Math.imul(al3, bl4) | 0, mid = mid + Math.imul(al3, bh4) | 0, mid = mid + Math.imul(ah3, bl4) | 0, hi = hi + Math.imul(ah3, bh4) | 0, lo = lo + Math.imul(al2, bl5) | 0, mid = mid + Math.imul(al2, bh5) | 0, mid = mid + Math.imul(ah2, bl5) | 0, hi = hi + Math.imul(ah2, bh5) | 0, lo = lo + Math.imul(al1, bl6) | 0, mid = mid + Math.imul(al1, bh6) | 0, mid = mid + Math.imul(ah1, bl6) | 0, hi = hi + Math.imul(ah1, bh6) | 0, lo = lo + Math.imul(al0, bl7) | 0, mid = mid + Math.imul(al0, bh7) | 0, mid = mid + Math.imul(ah0, bl7) | 0, hi = hi + Math.imul(ah0, bh7) | 0;
        var w7 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w7 >>> 26) | 0, w7 &= 67108863, lo = Math.imul(al8, bl0), mid = Math.imul(al8, bh0), mid = mid + Math.imul(ah8, bl0) | 0, hi = Math.imul(ah8, bh0), lo = lo + Math.imul(al7, bl1) | 0, mid = mid + Math.imul(al7, bh1) | 0, mid = mid + Math.imul(ah7, bl1) | 0, hi = hi + Math.imul(ah7, bh1) | 0, lo = lo + Math.imul(al6, bl2) | 0, mid = mid + Math.imul(al6, bh2) | 0, mid = mid + Math.imul(ah6, bl2) | 0, hi = hi + Math.imul(ah6, bh2) | 0, lo = lo + Math.imul(al5, bl3) | 0, mid = mid + Math.imul(al5, bh3) | 0, mid = mid + Math.imul(ah5, bl3) | 0, hi = hi + Math.imul(ah5, bh3) | 0, lo = lo + Math.imul(al4, bl4) | 0, mid = mid + Math.imul(al4, bh4) | 0, mid = mid + Math.imul(ah4, bl4) | 0, hi = hi + Math.imul(ah4, bh4) | 0, lo = lo + Math.imul(al3, bl5) | 0, mid = mid + Math.imul(al3, bh5) | 0, mid = mid + Math.imul(ah3, bl5) | 0, hi = hi + Math.imul(ah3, bh5) | 0, lo = lo + Math.imul(al2, bl6) | 0, mid = mid + Math.imul(al2, bh6) | 0, mid = mid + Math.imul(ah2, bl6) | 0, hi = hi + Math.imul(ah2, bh6) | 0, lo = lo + Math.imul(al1, bl7) | 0, mid = mid + Math.imul(al1, bh7) | 0, mid = mid + Math.imul(ah1, bl7) | 0, hi = hi + Math.imul(ah1, bh7) | 0, lo = lo + Math.imul(al0, bl8) | 0, mid = mid + Math.imul(al0, bh8) | 0, mid = mid + Math.imul(ah0, bl8) | 0, hi = hi + Math.imul(ah0, bh8) | 0;
        var w8 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w8 >>> 26) | 0, w8 &= 67108863, lo = Math.imul(al9, bl0), mid = Math.imul(al9, bh0), mid = mid + Math.imul(ah9, bl0) | 0, hi = Math.imul(ah9, bh0), lo = lo + Math.imul(al8, bl1) | 0, mid = mid + Math.imul(al8, bh1) | 0, mid = mid + Math.imul(ah8, bl1) | 0, hi = hi + Math.imul(ah8, bh1) | 0, lo = lo + Math.imul(al7, bl2) | 0, mid = mid + Math.imul(al7, bh2) | 0, mid = mid + Math.imul(ah7, bl2) | 0, hi = hi + Math.imul(ah7, bh2) | 0, lo = lo + Math.imul(al6, bl3) | 0, mid = mid + Math.imul(al6, bh3) | 0, mid = mid + Math.imul(ah6, bl3) | 0, hi = hi + Math.imul(ah6, bh3) | 0, lo = lo + Math.imul(al5, bl4) | 0, mid = mid + Math.imul(al5, bh4) | 0, mid = mid + Math.imul(ah5, bl4) | 0, hi = hi + Math.imul(ah5, bh4) | 0, lo = lo + Math.imul(al4, bl5) | 0, mid = mid + Math.imul(al4, bh5) | 0, mid = mid + Math.imul(ah4, bl5) | 0, hi = hi + Math.imul(ah4, bh5) | 0, lo = lo + Math.imul(al3, bl6) | 0, mid = mid + Math.imul(al3, bh6) | 0, mid = mid + Math.imul(ah3, bl6) | 0, hi = hi + Math.imul(ah3, bh6) | 0, lo = lo + Math.imul(al2, bl7) | 0, mid = mid + Math.imul(al2, bh7) | 0, mid = mid + Math.imul(ah2, bl7) | 0, hi = hi + Math.imul(ah2, bh7) | 0, lo = lo + Math.imul(al1, bl8) | 0, mid = mid + Math.imul(al1, bh8) | 0, mid = mid + Math.imul(ah1, bl8) | 0, hi = hi + Math.imul(ah1, bh8) | 0, lo = lo + Math.imul(al0, bl9) | 0, mid = mid + Math.imul(al0, bh9) | 0, mid = mid + Math.imul(ah0, bl9) | 0, hi = hi + Math.imul(ah0, bh9) | 0;
        var w9 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w9 >>> 26) | 0, w9 &= 67108863, lo = Math.imul(al9, bl1), mid = Math.imul(al9, bh1), mid = mid + Math.imul(ah9, bl1) | 0, hi = Math.imul(ah9, bh1), lo = lo + Math.imul(al8, bl2) | 0, mid = mid + Math.imul(al8, bh2) | 0, mid = mid + Math.imul(ah8, bl2) | 0, hi = hi + Math.imul(ah8, bh2) | 0, lo = lo + Math.imul(al7, bl3) | 0, mid = mid + Math.imul(al7, bh3) | 0, mid = mid + Math.imul(ah7, bl3) | 0, hi = hi + Math.imul(ah7, bh3) | 0, lo = lo + Math.imul(al6, bl4) | 0, mid = mid + Math.imul(al6, bh4) | 0, mid = mid + Math.imul(ah6, bl4) | 0, hi = hi + Math.imul(ah6, bh4) | 0, lo = lo + Math.imul(al5, bl5) | 0, mid = mid + Math.imul(al5, bh5) | 0, mid = mid + Math.imul(ah5, bl5) | 0, hi = hi + Math.imul(ah5, bh5) | 0, lo = lo + Math.imul(al4, bl6) | 0, mid = mid + Math.imul(al4, bh6) | 0, mid = mid + Math.imul(ah4, bl6) | 0, hi = hi + Math.imul(ah4, bh6) | 0, lo = lo + Math.imul(al3, bl7) | 0, mid = mid + Math.imul(al3, bh7) | 0, mid = mid + Math.imul(ah3, bl7) | 0, hi = hi + Math.imul(ah3, bh7) | 0, lo = lo + Math.imul(al2, bl8) | 0, mid = mid + Math.imul(al2, bh8) | 0, mid = mid + Math.imul(ah2, bl8) | 0, hi = hi + Math.imul(ah2, bh8) | 0, lo = lo + Math.imul(al1, bl9) | 0, mid = mid + Math.imul(al1, bh9) | 0, mid = mid + Math.imul(ah1, bl9) | 0, hi = hi + Math.imul(ah1, bh9) | 0;
        var w10 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w10 >>> 26) | 0, w10 &= 67108863, lo = Math.imul(al9, bl2), mid = Math.imul(al9, bh2), mid = mid + Math.imul(ah9, bl2) | 0, hi = Math.imul(ah9, bh2), lo = lo + Math.imul(al8, bl3) | 0, mid = mid + Math.imul(al8, bh3) | 0, mid = mid + Math.imul(ah8, bl3) | 0, hi = hi + Math.imul(ah8, bh3) | 0, lo = lo + Math.imul(al7, bl4) | 0, mid = mid + Math.imul(al7, bh4) | 0, mid = mid + Math.imul(ah7, bl4) | 0, hi = hi + Math.imul(ah7, bh4) | 0, lo = lo + Math.imul(al6, bl5) | 0, mid = mid + Math.imul(al6, bh5) | 0, mid = mid + Math.imul(ah6, bl5) | 0, hi = hi + Math.imul(ah6, bh5) | 0, lo = lo + Math.imul(al5, bl6) | 0, mid = mid + Math.imul(al5, bh6) | 0, mid = mid + Math.imul(ah5, bl6) | 0, hi = hi + Math.imul(ah5, bh6) | 0, lo = lo + Math.imul(al4, bl7) | 0, mid = mid + Math.imul(al4, bh7) | 0, mid = mid + Math.imul(ah4, bl7) | 0, hi = hi + Math.imul(ah4, bh7) | 0, lo = lo + Math.imul(al3, bl8) | 0, mid = mid + Math.imul(al3, bh8) | 0, mid = mid + Math.imul(ah3, bl8) | 0, hi = hi + Math.imul(ah3, bh8) | 0, lo = lo + Math.imul(al2, bl9) | 0, mid = mid + Math.imul(al2, bh9) | 0, mid = mid + Math.imul(ah2, bl9) | 0, hi = hi + Math.imul(ah2, bh9) | 0;
        var w11 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w11 >>> 26) | 0, w11 &= 67108863, lo = Math.imul(al9, bl3), mid = Math.imul(al9, bh3), mid = mid + Math.imul(ah9, bl3) | 0, hi = Math.imul(ah9, bh3), lo = lo + Math.imul(al8, bl4) | 0, mid = mid + Math.imul(al8, bh4) | 0, mid = mid + Math.imul(ah8, bl4) | 0, hi = hi + Math.imul(ah8, bh4) | 0, lo = lo + Math.imul(al7, bl5) | 0, mid = mid + Math.imul(al7, bh5) | 0, mid = mid + Math.imul(ah7, bl5) | 0, hi = hi + Math.imul(ah7, bh5) | 0, lo = lo + Math.imul(al6, bl6) | 0, mid = mid + Math.imul(al6, bh6) | 0, mid = mid + Math.imul(ah6, bl6) | 0, hi = hi + Math.imul(ah6, bh6) | 0, lo = lo + Math.imul(al5, bl7) | 0, mid = mid + Math.imul(al5, bh7) | 0, mid = mid + Math.imul(ah5, bl7) | 0, hi = hi + Math.imul(ah5, bh7) | 0, lo = lo + Math.imul(al4, bl8) | 0, mid = mid + Math.imul(al4, bh8) | 0, mid = mid + Math.imul(ah4, bl8) | 0, hi = hi + Math.imul(ah4, bh8) | 0, lo = lo + Math.imul(al3, bl9) | 0, mid = mid + Math.imul(al3, bh9) | 0, mid = mid + Math.imul(ah3, bl9) | 0, hi = hi + Math.imul(ah3, bh9) | 0;
        var w12 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w12 >>> 26) | 0, w12 &= 67108863, lo = Math.imul(al9, bl4), mid = Math.imul(al9, bh4), mid = mid + Math.imul(ah9, bl4) | 0, hi = Math.imul(ah9, bh4), lo = lo + Math.imul(al8, bl5) | 0, mid = mid + Math.imul(al8, bh5) | 0, mid = mid + Math.imul(ah8, bl5) | 0, hi = hi + Math.imul(ah8, bh5) | 0, lo = lo + Math.imul(al7, bl6) | 0, mid = mid + Math.imul(al7, bh6) | 0, mid = mid + Math.imul(ah7, bl6) | 0, hi = hi + Math.imul(ah7, bh6) | 0, lo = lo + Math.imul(al6, bl7) | 0, mid = mid + Math.imul(al6, bh7) | 0, mid = mid + Math.imul(ah6, bl7) | 0, hi = hi + Math.imul(ah6, bh7) | 0, lo = lo + Math.imul(al5, bl8) | 0, mid = mid + Math.imul(al5, bh8) | 0, mid = mid + Math.imul(ah5, bl8) | 0, hi = hi + Math.imul(ah5, bh8) | 0, lo = lo + Math.imul(al4, bl9) | 0, mid = mid + Math.imul(al4, bh9) | 0, mid = mid + Math.imul(ah4, bl9) | 0, hi = hi + Math.imul(ah4, bh9) | 0;
        var w13 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w13 >>> 26) | 0, w13 &= 67108863, lo = Math.imul(al9, bl5), mid = Math.imul(al9, bh5), mid = mid + Math.imul(ah9, bl5) | 0, hi = Math.imul(ah9, bh5), lo = lo + Math.imul(al8, bl6) | 0, mid = mid + Math.imul(al8, bh6) | 0, mid = mid + Math.imul(ah8, bl6) | 0, hi = hi + Math.imul(ah8, bh6) | 0, lo = lo + Math.imul(al7, bl7) | 0, mid = mid + Math.imul(al7, bh7) | 0, mid = mid + Math.imul(ah7, bl7) | 0, hi = hi + Math.imul(ah7, bh7) | 0, lo = lo + Math.imul(al6, bl8) | 0, mid = mid + Math.imul(al6, bh8) | 0, mid = mid + Math.imul(ah6, bl8) | 0, hi = hi + Math.imul(ah6, bh8) | 0, lo = lo + Math.imul(al5, bl9) | 0, mid = mid + Math.imul(al5, bh9) | 0, mid = mid + Math.imul(ah5, bl9) | 0, hi = hi + Math.imul(ah5, bh9) | 0;
        var w14 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w14 >>> 26) | 0, w14 &= 67108863, lo = Math.imul(al9, bl6), mid = Math.imul(al9, bh6), mid = mid + Math.imul(ah9, bl6) | 0, hi = Math.imul(ah9, bh6), lo = lo + Math.imul(al8, bl7) | 0, mid = mid + Math.imul(al8, bh7) | 0, mid = mid + Math.imul(ah8, bl7) | 0, hi = hi + Math.imul(ah8, bh7) | 0, lo = lo + Math.imul(al7, bl8) | 0, mid = mid + Math.imul(al7, bh8) | 0, mid = mid + Math.imul(ah7, bl8) | 0, hi = hi + Math.imul(ah7, bh8) | 0, lo = lo + Math.imul(al6, bl9) | 0, mid = mid + Math.imul(al6, bh9) | 0, mid = mid + Math.imul(ah6, bl9) | 0, hi = hi + Math.imul(ah6, bh9) | 0;
        var w15 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w15 >>> 26) | 0, w15 &= 67108863, lo = Math.imul(al9, bl7), mid = Math.imul(al9, bh7), mid = mid + Math.imul(ah9, bl7) | 0, hi = Math.imul(ah9, bh7), lo = lo + Math.imul(al8, bl8) | 0, mid = mid + Math.imul(al8, bh8) | 0, mid = mid + Math.imul(ah8, bl8) | 0, hi = hi + Math.imul(ah8, bh8) | 0, lo = lo + Math.imul(al7, bl9) | 0, mid = mid + Math.imul(al7, bh9) | 0, mid = mid + Math.imul(ah7, bl9) | 0, hi = hi + Math.imul(ah7, bh9) | 0;
        var w16 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w16 >>> 26) | 0, w16 &= 67108863, lo = Math.imul(al9, bl8), mid = Math.imul(al9, bh8), mid = mid + Math.imul(ah9, bl8) | 0, hi = Math.imul(ah9, bh8), lo = lo + Math.imul(al8, bl9) | 0, mid = mid + Math.imul(al8, bh9) | 0, mid = mid + Math.imul(ah8, bl9) | 0, hi = hi + Math.imul(ah8, bh9) | 0;
        var w17 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w17 >>> 26) | 0, w17 &= 67108863, lo = Math.imul(al9, bl9), mid = Math.imul(al9, bh9), mid = mid + Math.imul(ah9, bl9) | 0, hi = Math.imul(ah9, bh9);
        var w18 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        if (c2 = (hi + (mid >>> 13) | 0) + (w18 >>> 26) | 0, w18 &= 67108863, o2[0] = w0, o2[1] = w1, o2[2] = w2, o2[3] = w3, o2[4] = w4, o2[5] = w5, o2[6] = w6, o2[7] = w7, o2[8] = w8, o2[9] = w9, o2[10] = w10, o2[11] = w11, o2[12] = w12, o2[13] = w13, o2[14] = w14, o2[15] = w15, o2[16] = w16, o2[17] = w17, o2[18] = w18, c2 !== 0)
          o2[19] = c2, out.length++;
        return out;
      };
      if (!Math.imul)
        comb10MulTo = smallMulTo;
      function bigMulTo(self2, num, out) {
        out.negative = num.negative ^ self2.negative, out.length = self2.length + num.length;
        var carry = 0, hncarry = 0;
        for (var k = 0;k < out.length - 1; k++) {
          var ncarry = hncarry;
          hncarry = 0;
          var rword = carry & 67108863, maxJ = Math.min(k, num.length - 1);
          for (var j = Math.max(0, k - self2.length + 1);j <= maxJ; j++) {
            var i2 = k - j, a2 = self2.words[i2] | 0, b = num.words[j] | 0, r2 = a2 * b, lo = r2 & 67108863;
            ncarry = ncarry + (r2 / 67108864 | 0) | 0, lo = lo + rword | 0, rword = lo & 67108863, ncarry = ncarry + (lo >>> 26) | 0, hncarry += ncarry >>> 26, ncarry &= 67108863;
          }
          out.words[k] = rword, carry = ncarry, ncarry = hncarry;
        }
        if (carry !== 0)
          out.words[k] = carry;
        else
          out.length--;
        return out.strip();
      }
      function jumboMulTo(self2, num, out) {
        var fftm = new FFTM;
        return fftm.mulp(self2, num, out);
      }
      BN.prototype.mulTo = function(num, out) {
        var res, len2 = this.length + num.length;
        if (this.length === 10 && num.length === 10)
          res = comb10MulTo(this, num, out);
        else if (len2 < 63)
          res = smallMulTo(this, num, out);
        else if (len2 < 1024)
          res = bigMulTo(this, num, out);
        else
          res = jumboMulTo(this, num, out);
        return res;
      };
      function FFTM(x, y) {
        this.x = x, this.y = y;
      }
      FFTM.prototype.makeRBT = function(N) {
        var t2 = Array(N), l2 = BN.prototype._countBits(N) - 1;
        for (var i2 = 0;i2 < N; i2++)
          t2[i2] = this.revBin(i2, l2, N);
        return t2;
      }, FFTM.prototype.revBin = function(x, l2, N) {
        if (x === 0 || x === N - 1)
          return x;
        var rb = 0;
        for (var i2 = 0;i2 < l2; i2++)
          rb |= (x & 1) << l2 - i2 - 1, x >>= 1;
        return rb;
      }, FFTM.prototype.permute = function(rbt, rws, iws, rtws, itws, N) {
        for (var i2 = 0;i2 < N; i2++)
          rtws[i2] = rws[rbt[i2]], itws[i2] = iws[rbt[i2]];
      }, FFTM.prototype.transform = function(rws, iws, rtws, itws, N, rbt) {
        this.permute(rbt, rws, iws, rtws, itws, N);
        for (var s = 1;s < N; s <<= 1) {
          var l2 = s << 1, rtwdf = Math.cos(2 * Math.PI / l2), itwdf = Math.sin(2 * Math.PI / l2);
          for (var p2 = 0;p2 < N; p2 += l2) {
            var rtwdf_ = rtwdf, itwdf_ = itwdf;
            for (var j = 0;j < s; j++) {
              var re = rtws[p2 + j], ie = itws[p2 + j], ro = rtws[p2 + j + s], io = itws[p2 + j + s], rx = rtwdf_ * ro - itwdf_ * io;
              if (io = rtwdf_ * io + itwdf_ * ro, ro = rx, rtws[p2 + j] = re + ro, itws[p2 + j] = ie + io, rtws[p2 + j + s] = re - ro, itws[p2 + j + s] = ie - io, j !== l2)
                rx = rtwdf * rtwdf_ - itwdf * itwdf_, itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_, rtwdf_ = rx;
            }
          }
        }
      }, FFTM.prototype.guessLen13b = function(n2, m) {
        var N = Math.max(m, n2) | 1, odd = N & 1, i2 = 0;
        for (N = N / 2 | 0;N; N = N >>> 1)
          i2++;
        return 1 << i2 + 1 + odd;
      }, FFTM.prototype.conjugate = function(rws, iws, N) {
        if (N <= 1)
          return;
        for (var i2 = 0;i2 < N / 2; i2++) {
          var t2 = rws[i2];
          rws[i2] = rws[N - i2 - 1], rws[N - i2 - 1] = t2, t2 = iws[i2], iws[i2] = -iws[N - i2 - 1], iws[N - i2 - 1] = -t2;
        }
      }, FFTM.prototype.normalize13b = function(ws, N) {
        var carry = 0;
        for (var i2 = 0;i2 < N / 2; i2++) {
          var w = Math.round(ws[2 * i2 + 1] / N) * 8192 + Math.round(ws[2 * i2] / N) + carry;
          if (ws[i2] = w & 67108863, w < 67108864)
            carry = 0;
          else
            carry = w / 67108864 | 0;
        }
        return ws;
      }, FFTM.prototype.convert13b = function(ws, len2, rws, N) {
        var carry = 0;
        for (var i2 = 0;i2 < len2; i2++)
          carry = carry + (ws[i2] | 0), rws[2 * i2] = carry & 8191, carry = carry >>> 13, rws[2 * i2 + 1] = carry & 8191, carry = carry >>> 13;
        for (i2 = 2 * len2;i2 < N; ++i2)
          rws[i2] = 0;
        assert(carry === 0), assert((carry & -8192) === 0);
      }, FFTM.prototype.stub = function(N) {
        var ph = Array(N);
        for (var i2 = 0;i2 < N; i2++)
          ph[i2] = 0;
        return ph;
      }, FFTM.prototype.mulp = function(x, y, out) {
        var N = 2 * this.guessLen13b(x.length, y.length), rbt = this.makeRBT(N), _ = this.stub(N), rws = Array(N), rwst = Array(N), iwst = Array(N), nrws = Array(N), nrwst = Array(N), niwst = Array(N), rmws = out.words;
        rmws.length = N, this.convert13b(x.words, x.length, rws, N), this.convert13b(y.words, y.length, nrws, N), this.transform(rws, _, rwst, iwst, N, rbt), this.transform(nrws, _, nrwst, niwst, N, rbt);
        for (var i2 = 0;i2 < N; i2++) {
          var rx = rwst[i2] * nrwst[i2] - iwst[i2] * niwst[i2];
          iwst[i2] = rwst[i2] * niwst[i2] + iwst[i2] * nrwst[i2], rwst[i2] = rx;
        }
        return this.conjugate(rwst, iwst, N), this.transform(rwst, iwst, rmws, _, N, rbt), this.conjugate(rmws, _, N), this.normalize13b(rmws, N), out.negative = x.negative ^ y.negative, out.length = x.length + y.length, out.strip();
      }, BN.prototype.mul = function(num) {
        var out = new BN(null);
        return out.words = Array(this.length + num.length), this.mulTo(num, out);
      }, BN.prototype.mulf = function(num) {
        var out = new BN(null);
        return out.words = Array(this.length + num.length), jumboMulTo(this, num, out);
      }, BN.prototype.imul = function(num) {
        return this.clone().mulTo(num, this);
      }, BN.prototype.imuln = function(num) {
        assert(typeof num === "number"), assert(num < 67108864);
        var carry = 0;
        for (var i2 = 0;i2 < this.length; i2++) {
          var w = (this.words[i2] | 0) * num, lo = (w & 67108863) + (carry & 67108863);
          carry >>= 26, carry += w / 67108864 | 0, carry += lo >>> 26, this.words[i2] = lo & 67108863;
        }
        if (carry !== 0)
          this.words[i2] = carry, this.length++;
        return this.length = num === 0 ? 1 : this.length, this;
      }, BN.prototype.muln = function(num) {
        return this.clone().imuln(num);
      }, BN.prototype.sqr = function() {
        return this.mul(this);
      }, BN.prototype.isqr = function() {
        return this.imul(this.clone());
      }, BN.prototype.pow = function(num) {
        var w = toBitArray(num);
        if (w.length === 0)
          return new BN(1);
        var res = this;
        for (var i2 = 0;i2 < w.length; i2++, res = res.sqr())
          if (w[i2] !== 0)
            break;
        if (++i2 < w.length)
          for (var q = res.sqr();i2 < w.length; i2++, q = q.sqr()) {
            if (w[i2] === 0)
              continue;
            res = res.mul(q);
          }
        return res;
      }, BN.prototype.iushln = function(bits) {
        assert(typeof bits === "number" && bits >= 0);
        var r2 = bits % 26, s = (bits - r2) / 26, carryMask = 67108863 >>> 26 - r2 << 26 - r2, i2;
        if (r2 !== 0) {
          var carry = 0;
          for (i2 = 0;i2 < this.length; i2++) {
            var newCarry = this.words[i2] & carryMask, c2 = (this.words[i2] | 0) - newCarry << r2;
            this.words[i2] = c2 | carry, carry = newCarry >>> 26 - r2;
          }
          if (carry)
            this.words[i2] = carry, this.length++;
        }
        if (s !== 0) {
          for (i2 = this.length - 1;i2 >= 0; i2--)
            this.words[i2 + s] = this.words[i2];
          for (i2 = 0;i2 < s; i2++)
            this.words[i2] = 0;
          this.length += s;
        }
        return this.strip();
      }, BN.prototype.ishln = function(bits) {
        return assert(this.negative === 0), this.iushln(bits);
      }, BN.prototype.iushrn = function(bits, hint, extended) {
        assert(typeof bits === "number" && bits >= 0);
        var h;
        if (hint)
          h = (hint - hint % 26) / 26;
        else
          h = 0;
        var r2 = bits % 26, s = Math.min((bits - r2) / 26, this.length), mask = 67108863 ^ 67108863 >>> r2 << r2, maskedWords = extended;
        if (h -= s, h = Math.max(0, h), maskedWords) {
          for (var i2 = 0;i2 < s; i2++)
            maskedWords.words[i2] = this.words[i2];
          maskedWords.length = s;
        }
        if (s === 0)
          ;
        else if (this.length > s) {
          this.length -= s;
          for (i2 = 0;i2 < this.length; i2++)
            this.words[i2] = this.words[i2 + s];
        } else
          this.words[0] = 0, this.length = 1;
        var carry = 0;
        for (i2 = this.length - 1;i2 >= 0 && (carry !== 0 || i2 >= h); i2--) {
          var word = this.words[i2] | 0;
          this.words[i2] = carry << 26 - r2 | word >>> r2, carry = word & mask;
        }
        if (maskedWords && carry !== 0)
          maskedWords.words[maskedWords.length++] = carry;
        if (this.length === 0)
          this.words[0] = 0, this.length = 1;
        return this.strip();
      }, BN.prototype.ishrn = function(bits, hint, extended) {
        return assert(this.negative === 0), this.iushrn(bits, hint, extended);
      }, BN.prototype.shln = function(bits) {
        return this.clone().ishln(bits);
      }, BN.prototype.ushln = function(bits) {
        return this.clone().iushln(bits);
      }, BN.prototype.shrn = function(bits) {
        return this.clone().ishrn(bits);
      }, BN.prototype.ushrn = function(bits) {
        return this.clone().iushrn(bits);
      }, BN.prototype.testn = function(bit) {
        assert(typeof bit === "number" && bit >= 0);
        var r2 = bit % 26, s = (bit - r2) / 26, q = 1 << r2;
        if (this.length <= s)
          return false;
        var w = this.words[s];
        return !!(w & q);
      }, BN.prototype.imaskn = function(bits) {
        assert(typeof bits === "number" && bits >= 0);
        var r2 = bits % 26, s = (bits - r2) / 26;
        if (assert(this.negative === 0, "imaskn works only with positive numbers"), this.length <= s)
          return this;
        if (r2 !== 0)
          s++;
        if (this.length = Math.min(s, this.length), r2 !== 0) {
          var mask = 67108863 ^ 67108863 >>> r2 << r2;
          this.words[this.length - 1] &= mask;
        }
        return this.strip();
      }, BN.prototype.maskn = function(bits) {
        return this.clone().imaskn(bits);
      }, BN.prototype.iaddn = function(num) {
        if (assert(typeof num === "number"), assert(num < 67108864), num < 0)
          return this.isubn(-num);
        if (this.negative !== 0) {
          if (this.length === 1 && (this.words[0] | 0) < num)
            return this.words[0] = num - (this.words[0] | 0), this.negative = 0, this;
          return this.negative = 0, this.isubn(num), this.negative = 1, this;
        }
        return this._iaddn(num);
      }, BN.prototype._iaddn = function(num) {
        this.words[0] += num;
        for (var i2 = 0;i2 < this.length && this.words[i2] >= 67108864; i2++)
          if (this.words[i2] -= 67108864, i2 === this.length - 1)
            this.words[i2 + 1] = 1;
          else
            this.words[i2 + 1]++;
        return this.length = Math.max(this.length, i2 + 1), this;
      }, BN.prototype.isubn = function(num) {
        if (assert(typeof num === "number"), assert(num < 67108864), num < 0)
          return this.iaddn(-num);
        if (this.negative !== 0)
          return this.negative = 0, this.iaddn(num), this.negative = 1, this;
        if (this.words[0] -= num, this.length === 1 && this.words[0] < 0)
          this.words[0] = -this.words[0], this.negative = 1;
        else
          for (var i2 = 0;i2 < this.length && this.words[i2] < 0; i2++)
            this.words[i2] += 67108864, this.words[i2 + 1] -= 1;
        return this.strip();
      }, BN.prototype.addn = function(num) {
        return this.clone().iaddn(num);
      }, BN.prototype.subn = function(num) {
        return this.clone().isubn(num);
      }, BN.prototype.iabs = function() {
        return this.negative = 0, this;
      }, BN.prototype.abs = function() {
        return this.clone().iabs();
      }, BN.prototype._ishlnsubmul = function(num, mul, shift) {
        var len2 = num.length + shift, i2;
        this._expand(len2);
        var w, carry = 0;
        for (i2 = 0;i2 < num.length; i2++) {
          w = (this.words[i2 + shift] | 0) + carry;
          var right = (num.words[i2] | 0) * mul;
          w -= right & 67108863, carry = (w >> 26) - (right / 67108864 | 0), this.words[i2 + shift] = w & 67108863;
        }
        for (;i2 < this.length - shift; i2++)
          w = (this.words[i2 + shift] | 0) + carry, carry = w >> 26, this.words[i2 + shift] = w & 67108863;
        if (carry === 0)
          return this.strip();
        assert(carry === -1), carry = 0;
        for (i2 = 0;i2 < this.length; i2++)
          w = -(this.words[i2] | 0) + carry, carry = w >> 26, this.words[i2] = w & 67108863;
        return this.negative = 1, this.strip();
      }, BN.prototype._wordDiv = function(num, mode) {
        var shift = this.length - num.length, a2 = this.clone(), b = num, bhi = b.words[b.length - 1] | 0, bhiBits = this._countBits(bhi);
        if (shift = 26 - bhiBits, shift !== 0)
          b = b.ushln(shift), a2.iushln(shift), bhi = b.words[b.length - 1] | 0;
        var m = a2.length - b.length, q;
        if (mode !== "mod") {
          q = new BN(null), q.length = m + 1, q.words = Array(q.length);
          for (var i2 = 0;i2 < q.length; i2++)
            q.words[i2] = 0;
        }
        var diff = a2.clone()._ishlnsubmul(b, 1, m);
        if (diff.negative === 0) {
          if (a2 = diff, q)
            q.words[m] = 1;
        }
        for (var j = m - 1;j >= 0; j--) {
          var qj = (a2.words[b.length + j] | 0) * 67108864 + (a2.words[b.length + j - 1] | 0);
          qj = Math.min(qj / bhi | 0, 67108863), a2._ishlnsubmul(b, qj, j);
          while (a2.negative !== 0)
            if (qj--, a2.negative = 0, a2._ishlnsubmul(b, 1, j), !a2.isZero())
              a2.negative ^= 1;
          if (q)
            q.words[j] = qj;
        }
        if (q)
          q.strip();
        if (a2.strip(), mode !== "div" && shift !== 0)
          a2.iushrn(shift);
        return { div: q || null, mod: a2 };
      }, BN.prototype.divmod = function(num, mode, positive) {
        if (assert(!num.isZero()), this.isZero())
          return { div: new BN(0), mod: new BN(0) };
        var div, mod, res;
        if (this.negative !== 0 && num.negative === 0) {
          if (res = this.neg().divmod(num, mode), mode !== "mod")
            div = res.div.neg();
          if (mode !== "div") {
            if (mod = res.mod.neg(), positive && mod.negative !== 0)
              mod.iadd(num);
          }
          return { div, mod };
        }
        if (this.negative === 0 && num.negative !== 0) {
          if (res = this.divmod(num.neg(), mode), mode !== "mod")
            div = res.div.neg();
          return { div, mod: res.mod };
        }
        if ((this.negative & num.negative) !== 0) {
          if (res = this.neg().divmod(num.neg(), mode), mode !== "div") {
            if (mod = res.mod.neg(), positive && mod.negative !== 0)
              mod.isub(num);
          }
          return { div: res.div, mod };
        }
        if (num.length > this.length || this.cmp(num) < 0)
          return { div: new BN(0), mod: this };
        if (num.length === 1) {
          if (mode === "div")
            return { div: this.divn(num.words[0]), mod: null };
          if (mode === "mod")
            return { div: null, mod: new BN(this.modn(num.words[0])) };
          return { div: this.divn(num.words[0]), mod: new BN(this.modn(num.words[0])) };
        }
        return this._wordDiv(num, mode);
      }, BN.prototype.div = function(num) {
        return this.divmod(num, "div", false).div;
      }, BN.prototype.mod = function(num) {
        return this.divmod(num, "mod", false).mod;
      }, BN.prototype.umod = function(num) {
        return this.divmod(num, "mod", true).mod;
      }, BN.prototype.divRound = function(num) {
        var dm = this.divmod(num);
        if (dm.mod.isZero())
          return dm.div;
        var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod, half = num.ushrn(1), r2 = num.andln(1), cmp = mod.cmp(half);
        if (cmp < 0 || r2 === 1 && cmp === 0)
          return dm.div;
        return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
      }, BN.prototype.modn = function(num) {
        assert(num <= 67108863);
        var p2 = 67108864 % num, acc = 0;
        for (var i2 = this.length - 1;i2 >= 0; i2--)
          acc = (p2 * acc + (this.words[i2] | 0)) % num;
        return acc;
      }, BN.prototype.idivn = function(num) {
        assert(num <= 67108863);
        var carry = 0;
        for (var i2 = this.length - 1;i2 >= 0; i2--) {
          var w = (this.words[i2] | 0) + carry * 67108864;
          this.words[i2] = w / num | 0, carry = w % num;
        }
        return this.strip();
      }, BN.prototype.divn = function(num) {
        return this.clone().idivn(num);
      }, BN.prototype.egcd = function(p2) {
        assert(p2.negative === 0), assert(!p2.isZero());
        var x = this, y = p2.clone();
        if (x.negative !== 0)
          x = x.umod(p2);
        else
          x = x.clone();
        var A = new BN(1), B = new BN(0), C = new BN(0), D = new BN(1), g = 0;
        while (x.isEven() && y.isEven())
          x.iushrn(1), y.iushrn(1), ++g;
        var yp = y.clone(), xp = x.clone();
        while (!x.isZero()) {
          for (var i2 = 0, im = 1;(x.words[0] & im) === 0 && i2 < 26; ++i2, im <<= 1)
            ;
          if (i2 > 0) {
            x.iushrn(i2);
            while (i2-- > 0) {
              if (A.isOdd() || B.isOdd())
                A.iadd(yp), B.isub(xp);
              A.iushrn(1), B.iushrn(1);
            }
          }
          for (var j = 0, jm = 1;(y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1)
            ;
          if (j > 0) {
            y.iushrn(j);
            while (j-- > 0) {
              if (C.isOdd() || D.isOdd())
                C.iadd(yp), D.isub(xp);
              C.iushrn(1), D.iushrn(1);
            }
          }
          if (x.cmp(y) >= 0)
            x.isub(y), A.isub(C), B.isub(D);
          else
            y.isub(x), C.isub(A), D.isub(B);
        }
        return { a: C, b: D, gcd: y.iushln(g) };
      }, BN.prototype._invmp = function(p2) {
        assert(p2.negative === 0), assert(!p2.isZero());
        var a2 = this, b = p2.clone();
        if (a2.negative !== 0)
          a2 = a2.umod(p2);
        else
          a2 = a2.clone();
        var x1 = new BN(1), x2 = new BN(0), delta = b.clone();
        while (a2.cmpn(1) > 0 && b.cmpn(1) > 0) {
          for (var i2 = 0, im = 1;(a2.words[0] & im) === 0 && i2 < 26; ++i2, im <<= 1)
            ;
          if (i2 > 0) {
            a2.iushrn(i2);
            while (i2-- > 0) {
              if (x1.isOdd())
                x1.iadd(delta);
              x1.iushrn(1);
            }
          }
          for (var j = 0, jm = 1;(b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1)
            ;
          if (j > 0) {
            b.iushrn(j);
            while (j-- > 0) {
              if (x2.isOdd())
                x2.iadd(delta);
              x2.iushrn(1);
            }
          }
          if (a2.cmp(b) >= 0)
            a2.isub(b), x1.isub(x2);
          else
            b.isub(a2), x2.isub(x1);
        }
        var res;
        if (a2.cmpn(1) === 0)
          res = x1;
        else
          res = x2;
        if (res.cmpn(0) < 0)
          res.iadd(p2);
        return res;
      }, BN.prototype.gcd = function(num) {
        if (this.isZero())
          return num.abs();
        if (num.isZero())
          return this.abs();
        var a2 = this.clone(), b = num.clone();
        a2.negative = 0, b.negative = 0;
        for (var shift = 0;a2.isEven() && b.isEven(); shift++)
          a2.iushrn(1), b.iushrn(1);
        do {
          while (a2.isEven())
            a2.iushrn(1);
          while (b.isEven())
            b.iushrn(1);
          var r2 = a2.cmp(b);
          if (r2 < 0) {
            var t2 = a2;
            a2 = b, b = t2;
          } else if (r2 === 0 || b.cmpn(1) === 0)
            break;
          a2.isub(b);
        } while (true);
        return b.iushln(shift);
      }, BN.prototype.invm = function(num) {
        return this.egcd(num).a.umod(num);
      }, BN.prototype.isEven = function() {
        return (this.words[0] & 1) === 0;
      }, BN.prototype.isOdd = function() {
        return (this.words[0] & 1) === 1;
      }, BN.prototype.andln = function(num) {
        return this.words[0] & num;
      }, BN.prototype.bincn = function(bit) {
        assert(typeof bit === "number");
        var r2 = bit % 26, s = (bit - r2) / 26, q = 1 << r2;
        if (this.length <= s)
          return this._expand(s + 1), this.words[s] |= q, this;
        var carry = q;
        for (var i2 = s;carry !== 0 && i2 < this.length; i2++) {
          var w = this.words[i2] | 0;
          w += carry, carry = w >>> 26, w &= 67108863, this.words[i2] = w;
        }
        if (carry !== 0)
          this.words[i2] = carry, this.length++;
        return this;
      }, BN.prototype.isZero = function() {
        return this.length === 1 && this.words[0] === 0;
      }, BN.prototype.cmpn = function(num) {
        var negative = num < 0;
        if (this.negative !== 0 && !negative)
          return -1;
        if (this.negative === 0 && negative)
          return 1;
        this.strip();
        var res;
        if (this.length > 1)
          res = 1;
        else {
          if (negative)
            num = -num;
          assert(num <= 67108863, "Number is too big");
          var w = this.words[0] | 0;
          res = w === num ? 0 : w < num ? -1 : 1;
        }
        if (this.negative !== 0)
          return -res | 0;
        return res;
      }, BN.prototype.cmp = function(num) {
        if (this.negative !== 0 && num.negative === 0)
          return -1;
        if (this.negative === 0 && num.negative !== 0)
          return 1;
        var res = this.ucmp(num);
        if (this.negative !== 0)
          return -res | 0;
        return res;
      }, BN.prototype.ucmp = function(num) {
        if (this.length > num.length)
          return 1;
        if (this.length < num.length)
          return -1;
        var res = 0;
        for (var i2 = this.length - 1;i2 >= 0; i2--) {
          var a2 = this.words[i2] | 0, b = num.words[i2] | 0;
          if (a2 === b)
            continue;
          if (a2 < b)
            res = -1;
          else if (a2 > b)
            res = 1;
          break;
        }
        return res;
      }, BN.prototype.gtn = function(num) {
        return this.cmpn(num) === 1;
      }, BN.prototype.gt = function(num) {
        return this.cmp(num) === 1;
      }, BN.prototype.gten = function(num) {
        return this.cmpn(num) >= 0;
      }, BN.prototype.gte = function(num) {
        return this.cmp(num) >= 0;
      }, BN.prototype.ltn = function(num) {
        return this.cmpn(num) === -1;
      }, BN.prototype.lt = function(num) {
        return this.cmp(num) === -1;
      }, BN.prototype.lten = function(num) {
        return this.cmpn(num) <= 0;
      }, BN.prototype.lte = function(num) {
        return this.cmp(num) <= 0;
      }, BN.prototype.eqn = function(num) {
        return this.cmpn(num) === 0;
      }, BN.prototype.eq = function(num) {
        return this.cmp(num) === 0;
      }, BN.red = function(num) {
        return new Red(num);
      }, BN.prototype.toRed = function(ctx) {
        return assert(!this.red, "Already a number in reduction context"), assert(this.negative === 0, "red works only with positives"), ctx.convertTo(this)._forceRed(ctx);
      }, BN.prototype.fromRed = function() {
        return assert(this.red, "fromRed works only with numbers in reduction context"), this.red.convertFrom(this);
      }, BN.prototype._forceRed = function(ctx) {
        return this.red = ctx, this;
      }, BN.prototype.forceRed = function(ctx) {
        return assert(!this.red, "Already a number in reduction context"), this._forceRed(ctx);
      }, BN.prototype.redAdd = function(num) {
        return assert(this.red, "redAdd works only with red numbers"), this.red.add(this, num);
      }, BN.prototype.redIAdd = function(num) {
        return assert(this.red, "redIAdd works only with red numbers"), this.red.iadd(this, num);
      }, BN.prototype.redSub = function(num) {
        return assert(this.red, "redSub works only with red numbers"), this.red.sub(this, num);
      }, BN.prototype.redISub = function(num) {
        return assert(this.red, "redISub works only with red numbers"), this.red.isub(this, num);
      }, BN.prototype.redShl = function(num) {
        return assert(this.red, "redShl works only with red numbers"), this.red.shl(this, num);
      }, BN.prototype.redMul = function(num) {
        return assert(this.red, "redMul works only with red numbers"), this.red._verify2(this, num), this.red.mul(this, num);
      }, BN.prototype.redIMul = function(num) {
        return assert(this.red, "redMul works only with red numbers"), this.red._verify2(this, num), this.red.imul(this, num);
      }, BN.prototype.redSqr = function() {
        return assert(this.red, "redSqr works only with red numbers"), this.red._verify1(this), this.red.sqr(this);
      }, BN.prototype.redISqr = function() {
        return assert(this.red, "redISqr works only with red numbers"), this.red._verify1(this), this.red.isqr(this);
      }, BN.prototype.redSqrt = function() {
        return assert(this.red, "redSqrt works only with red numbers"), this.red._verify1(this), this.red.sqrt(this);
      }, BN.prototype.redInvm = function() {
        return assert(this.red, "redInvm works only with red numbers"), this.red._verify1(this), this.red.invm(this);
      }, BN.prototype.redNeg = function() {
        return assert(this.red, "redNeg works only with red numbers"), this.red._verify1(this), this.red.neg(this);
      }, BN.prototype.redPow = function(num) {
        return assert(this.red && !num.red, "redPow(normalNum)"), this.red._verify1(this), this.red.pow(this, num);
      };
      var primes = { k256: null, p224: null, p192: null, p25519: null };
      function MPrime(name, p2) {
        this.name = name, this.p = new BN(p2, 16), this.n = this.p.bitLength(), this.k = new BN(1).iushln(this.n).isub(this.p), this.tmp = this._tmp();
      }
      MPrime.prototype._tmp = function() {
        var tmp = new BN(null);
        return tmp.words = Array(Math.ceil(this.n / 13)), tmp;
      }, MPrime.prototype.ireduce = function(num) {
        var r2 = num, rlen;
        do
          this.split(r2, this.tmp), r2 = this.imulK(r2), r2 = r2.iadd(this.tmp), rlen = r2.bitLength();
        while (rlen > this.n);
        var cmp = rlen < this.n ? -1 : r2.ucmp(this.p);
        if (cmp === 0)
          r2.words[0] = 0, r2.length = 1;
        else if (cmp > 0)
          r2.isub(this.p);
        else if (r2.strip !== undefined)
          r2.strip();
        else
          r2._strip();
        return r2;
      }, MPrime.prototype.split = function(input, out) {
        input.iushrn(this.n, 0, out);
      }, MPrime.prototype.imulK = function(num) {
        return num.imul(this.k);
      };
      function K256() {
        MPrime.call(this, "k256", "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f");
      }
      inherits2(K256, MPrime), K256.prototype.split = function(input, output) {
        var mask = 4194303, outLen = Math.min(input.length, 9);
        for (var i2 = 0;i2 < outLen; i2++)
          output.words[i2] = input.words[i2];
        if (output.length = outLen, input.length <= 9) {
          input.words[0] = 0, input.length = 1;
          return;
        }
        var prev = input.words[9];
        output.words[output.length++] = prev & mask;
        for (i2 = 10;i2 < input.length; i2++) {
          var next = input.words[i2] | 0;
          input.words[i2 - 10] = (next & mask) << 4 | prev >>> 22, prev = next;
        }
        if (prev >>>= 22, input.words[i2 - 10] = prev, prev === 0 && input.length > 10)
          input.length -= 10;
        else
          input.length -= 9;
      }, K256.prototype.imulK = function(num) {
        num.words[num.length] = 0, num.words[num.length + 1] = 0, num.length += 2;
        var lo = 0;
        for (var i2 = 0;i2 < num.length; i2++) {
          var w = num.words[i2] | 0;
          lo += w * 977, num.words[i2] = lo & 67108863, lo = w * 64 + (lo / 67108864 | 0);
        }
        if (num.words[num.length - 1] === 0) {
          if (num.length--, num.words[num.length - 1] === 0)
            num.length--;
        }
        return num;
      };
      function P224() {
        MPrime.call(this, "p224", "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001");
      }
      inherits2(P224, MPrime);
      function P192() {
        MPrime.call(this, "p192", "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff");
      }
      inherits2(P192, MPrime);
      function P25519() {
        MPrime.call(this, "25519", "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed");
      }
      inherits2(P25519, MPrime), P25519.prototype.imulK = function(num) {
        var carry = 0;
        for (var i2 = 0;i2 < num.length; i2++) {
          var hi = (num.words[i2] | 0) * 19 + carry, lo = hi & 67108863;
          hi >>>= 26, num.words[i2] = lo, carry = hi;
        }
        if (carry !== 0)
          num.words[num.length++] = carry;
        return num;
      }, BN._prime = function(name) {
        if (primes[name])
          return primes[name];
        var prime;
        if (name === "k256")
          prime = new K256;
        else if (name === "p224")
          prime = new P224;
        else if (name === "p192")
          prime = new P192;
        else if (name === "p25519")
          prime = new P25519;
        else
          throw Error("Unknown prime " + name);
        return primes[name] = prime, prime;
      };
      function Red(m) {
        if (typeof m === "string") {
          var prime = BN._prime(m);
          this.m = prime.p, this.prime = prime;
        } else
          assert(m.gtn(1), "modulus must be greater than 1"), this.m = m, this.prime = null;
      }
      Red.prototype._verify1 = function(a2) {
        assert(a2.negative === 0, "red works only with positives"), assert(a2.red, "red works only with red numbers");
      }, Red.prototype._verify2 = function(a2, b) {
        assert((a2.negative | b.negative) === 0, "red works only with positives"), assert(a2.red && a2.red === b.red, "red works only with red numbers");
      }, Red.prototype.imod = function(a2) {
        if (this.prime)
          return this.prime.ireduce(a2)._forceRed(this);
        return a2.umod(this.m)._forceRed(this);
      }, Red.prototype.neg = function(a2) {
        if (a2.isZero())
          return a2.clone();
        return this.m.sub(a2)._forceRed(this);
      }, Red.prototype.add = function(a2, b) {
        this._verify2(a2, b);
        var res = a2.add(b);
        if (res.cmp(this.m) >= 0)
          res.isub(this.m);
        return res._forceRed(this);
      }, Red.prototype.iadd = function(a2, b) {
        this._verify2(a2, b);
        var res = a2.iadd(b);
        if (res.cmp(this.m) >= 0)
          res.isub(this.m);
        return res;
      }, Red.prototype.sub = function(a2, b) {
        this._verify2(a2, b);
        var res = a2.sub(b);
        if (res.cmpn(0) < 0)
          res.iadd(this.m);
        return res._forceRed(this);
      }, Red.prototype.isub = function(a2, b) {
        this._verify2(a2, b);
        var res = a2.isub(b);
        if (res.cmpn(0) < 0)
          res.iadd(this.m);
        return res;
      }, Red.prototype.shl = function(a2, num) {
        return this._verify1(a2), this.imod(a2.ushln(num));
      }, Red.prototype.imul = function(a2, b) {
        return this._verify2(a2, b), this.imod(a2.imul(b));
      }, Red.prototype.mul = function(a2, b) {
        return this._verify2(a2, b), this.imod(a2.mul(b));
      }, Red.prototype.isqr = function(a2) {
        return this.imul(a2, a2.clone());
      }, Red.prototype.sqr = function(a2) {
        return this.mul(a2, a2);
      }, Red.prototype.sqrt = function(a2) {
        if (a2.isZero())
          return a2.clone();
        var mod3 = this.m.andln(3);
        if (assert(mod3 % 2 === 1), mod3 === 3) {
          var pow = this.m.add(new BN(1)).iushrn(2);
          return this.pow(a2, pow);
        }
        var q = this.m.subn(1), s = 0;
        while (!q.isZero() && q.andln(1) === 0)
          s++, q.iushrn(1);
        assert(!q.isZero());
        var one = new BN(1).toRed(this), nOne = one.redNeg(), lpow = this.m.subn(1).iushrn(1), z = this.m.bitLength();
        z = new BN(2 * z * z).toRed(this);
        while (this.pow(z, lpow).cmp(nOne) !== 0)
          z.redIAdd(nOne);
        var c2 = this.pow(z, q), r2 = this.pow(a2, q.addn(1).iushrn(1)), t2 = this.pow(a2, q), m = s;
        while (t2.cmp(one) !== 0) {
          var tmp = t2;
          for (var i2 = 0;tmp.cmp(one) !== 0; i2++)
            tmp = tmp.redSqr();
          assert(i2 < m);
          var b = this.pow(c2, new BN(1).iushln(m - i2 - 1));
          r2 = r2.redMul(b), c2 = b.redSqr(), t2 = t2.redMul(c2), m = i2;
        }
        return r2;
      }, Red.prototype.invm = function(a2) {
        var inv = a2._invmp(this.m);
        if (inv.negative !== 0)
          return inv.negative = 0, this.imod(inv).redNeg();
        else
          return this.imod(inv);
      }, Red.prototype.pow = function(a2, num) {
        if (num.isZero())
          return new BN(1).toRed(this);
        if (num.cmpn(1) === 0)
          return a2.clone();
        var windowSize = 4, wnd = Array(1 << windowSize);
        wnd[0] = new BN(1).toRed(this), wnd[1] = a2;
        for (var i2 = 2;i2 < wnd.length; i2++)
          wnd[i2] = this.mul(wnd[i2 - 1], a2);
        var res = wnd[0], current = 0, currentLen = 0, start = num.bitLength() % 26;
        if (start === 0)
          start = 26;
        for (i2 = num.length - 1;i2 >= 0; i2--) {
          var word = num.words[i2];
          for (var j = start - 1;j >= 0; j--) {
            var bit = word >> j & 1;
            if (res !== wnd[0])
              res = this.sqr(res);
            if (bit === 0 && current === 0) {
              currentLen = 0;
              continue;
            }
            if (current <<= 1, current |= bit, currentLen++, currentLen !== windowSize && (i2 !== 0 || j !== 0))
              continue;
            res = this.mul(res, wnd[current]), currentLen = 0, current = 0;
          }
          start = 26;
        }
        return res;
      }, Red.prototype.convertTo = function(num) {
        var r2 = num.umod(this.m);
        return r2 === num ? r2.clone() : r2;
      }, Red.prototype.convertFrom = function(num) {
        var res = num.clone();
        return res.red = null, res;
      }, BN.mont = function(num) {
        return new Mont(num);
      };
      function Mont(m) {
        if (Red.call(this, m), this.shift = this.m.bitLength(), this.shift % 26 !== 0)
          this.shift += 26 - this.shift % 26;
        this.r = new BN(1).iushln(this.shift), this.r2 = this.imod(this.r.sqr()), this.rinv = this.r._invmp(this.m), this.minv = this.rinv.mul(this.r).isubn(1).div(this.m), this.minv = this.minv.umod(this.r), this.minv = this.r.sub(this.minv);
      }
      inherits2(Mont, Red), Mont.prototype.convertTo = function(num) {
        return this.imod(num.ushln(this.shift));
      }, Mont.prototype.convertFrom = function(num) {
        var r2 = this.imod(num.mul(this.rinv));
        return r2.red = null, r2;
      }, Mont.prototype.imul = function(a2, b) {
        if (a2.isZero() || b.isZero())
          return a2.words[0] = 0, a2.length = 1, a2;
        var t2 = a2.imul(b), c2 = t2.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), u = t2.isub(c2).iushrn(this.shift), res = u;
        if (u.cmp(this.m) >= 0)
          res = u.isub(this.m);
        else if (u.cmpn(0) < 0)
          res = u.iadd(this.m);
        return res._forceRed(this);
      }, Mont.prototype.mul = function(a2, b) {
        if (a2.isZero() || b.isZero())
          return new BN(0)._forceRed(this);
        var t2 = a2.mul(b), c2 = t2.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), u = t2.isub(c2).iushrn(this.shift), res = u;
        if (u.cmp(this.m) >= 0)
          res = u.isub(this.m);
        else if (u.cmpn(0) < 0)
          res = u.iadd(this.m);
        return res._forceRed(this);
      }, Mont.prototype.invm = function(a2) {
        var res = this.imod(a2._invmp(this.m).mul(this.r2));
        return res._forceRed(this);
      };
    })(typeof module > "u" || module, exports);
  });
  require_browser = __commonJS2((exports, module) => {
    var elliptic = require_elliptic(), BN = require_bn2();
    module.exports = function(curve) {
      return new ECDH(curve);
    };
    var aliases = { secp256k1: { name: "secp256k1", byteLength: 32 }, secp224r1: { name: "p224", byteLength: 28 }, prime256v1: { name: "p256", byteLength: 32 }, prime192v1: { name: "p192", byteLength: 24 }, ed25519: { name: "ed25519", byteLength: 32 }, secp384r1: { name: "p384", byteLength: 48 }, secp521r1: { name: "p521", byteLength: 66 } };
    aliases.p224 = aliases.secp224r1;
    aliases.p256 = aliases.secp256r1 = aliases.prime256v1;
    aliases.p192 = aliases.secp192r1 = aliases.prime192v1;
    aliases.p384 = aliases.secp384r1;
    aliases.p521 = aliases.secp521r1;
    function ECDH(curve) {
      if (this.curveType = aliases[curve], !this.curveType)
        this.curveType = { name: curve };
      this.curve = new elliptic.ec(this.curveType.name), this.keys = undefined;
    }
    ECDH.prototype.generateKeys = function(enc, format2) {
      return this.keys = this.curve.genKeyPair(), this.getPublicKey(enc, format2);
    };
    ECDH.prototype.computeSecret = function(other, inenc, enc) {
      if (inenc = inenc || "utf8", !Buffer.isBuffer(other))
        other = new Buffer(other, inenc);
      var otherPub = this.curve.keyFromPublic(other).getPublic(), out = otherPub.mul(this.keys.getPrivate()).getX();
      return formatReturnValue(out, enc, this.curveType.byteLength);
    };
    ECDH.prototype.getPublicKey = function(enc, format2) {
      var key = this.keys.getPublic(format2 === "compressed", true);
      if (format2 === "hybrid")
        if (key[key.length - 1] % 2)
          key[0] = 7;
        else
          key[0] = 6;
      return formatReturnValue(key, enc);
    };
    ECDH.prototype.getPrivateKey = function(enc) {
      return formatReturnValue(this.keys.getPrivate(), enc);
    };
    ECDH.prototype.setPublicKey = function(pub, enc) {
      if (enc = enc || "utf8", !Buffer.isBuffer(pub))
        pub = new Buffer(pub, enc);
      return this.keys._importPublic(pub), this;
    };
    ECDH.prototype.setPrivateKey = function(priv, enc) {
      if (enc = enc || "utf8", !Buffer.isBuffer(priv))
        priv = new Buffer(priv, enc);
      var _priv = new BN(priv);
      return _priv = _priv.toString(16), this.keys = this.curve.genKeyPair(), this.keys._importPrivate(_priv), this;
    };
    function formatReturnValue(bn, enc, len2) {
      if (!Array.isArray(bn))
        bn = bn.toArray();
      var buf = new Buffer(bn);
      if (len2 && buf.length < len2) {
        var zeros = new Buffer(len2 - buf.length);
        zeros.fill(0), buf = Buffer.concat([zeros, buf]);
      }
      if (!enc)
        return buf;
      else
        return buf.toString(enc);
    }
  });
  require_create_ecdh = __commonJS2((exports, module) => {
    var createECDH = (init_crypto(), __toCommonJS(exports_crypto)).createECDH;
    module.exports = createECDH || require_browser();
  });
  require_bn3 = __commonJS2((exports, module) => {
    (function(module2, exports2) {
      function assert(val, msg) {
        if (!val)
          throw Error(msg || "Assertion failed");
      }
      function inherits2(ctor, superCtor) {
        ctor.super_ = superCtor;
        var TempCtor = function() {};
        TempCtor.prototype = superCtor.prototype, ctor.prototype = new TempCtor, ctor.prototype.constructor = ctor;
      }
      function BN(number, base, endian) {
        if (BN.isBN(number))
          return number;
        if (this.negative = 0, this.words = null, this.length = 0, this.red = null, number !== null) {
          if (base === "le" || base === "be")
            endian = base, base = 10;
          this._init(number || 0, base || 10, endian || "be");
        }
      }
      if (typeof module2 === "object")
        module2.exports = BN;
      else
        exports2.BN = BN;
      BN.BN = BN, BN.wordSize = 26;
      var Buffer22;
      try {
        if (typeof window < "u" && typeof window.Buffer < "u")
          Buffer22 = window.Buffer;
        else
          Buffer22 = (init_buffer(), __toCommonJS(exports_buffer)).Buffer;
      } catch (e2) {}
      BN.isBN = function(num) {
        if (num instanceof BN)
          return true;
        return num !== null && typeof num === "object" && num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
      }, BN.max = function(left, right) {
        if (left.cmp(right) > 0)
          return left;
        return right;
      }, BN.min = function(left, right) {
        if (left.cmp(right) < 0)
          return left;
        return right;
      }, BN.prototype._init = function(number, base, endian) {
        if (typeof number === "number")
          return this._initNumber(number, base, endian);
        if (typeof number === "object")
          return this._initArray(number, base, endian);
        if (base === "hex")
          base = 16;
        assert(base === (base | 0) && base >= 2 && base <= 36), number = number.toString().replace(/\s+/g, "");
        var start = 0;
        if (number[0] === "-")
          start++, this.negative = 1;
        if (start < number.length) {
          if (base === 16)
            this._parseHex(number, start, endian);
          else if (this._parseBase(number, base, start), endian === "le")
            this._initArray(this.toArray(), base, endian);
        }
      }, BN.prototype._initNumber = function(number, base, endian) {
        if (number < 0)
          this.negative = 1, number = -number;
        if (number < 67108864)
          this.words = [number & 67108863], this.length = 1;
        else if (number < 4503599627370496)
          this.words = [number & 67108863, number / 67108864 & 67108863], this.length = 2;
        else
          assert(number < 9007199254740992), this.words = [number & 67108863, number / 67108864 & 67108863, 1], this.length = 3;
        if (endian !== "le")
          return;
        this._initArray(this.toArray(), base, endian);
      }, BN.prototype._initArray = function(number, base, endian) {
        if (assert(typeof number.length === "number"), number.length <= 0)
          return this.words = [0], this.length = 1, this;
        this.length = Math.ceil(number.length / 3), this.words = Array(this.length);
        for (var i2 = 0;i2 < this.length; i2++)
          this.words[i2] = 0;
        var j, w, off = 0;
        if (endian === "be") {
          for (i2 = number.length - 1, j = 0;i2 >= 0; i2 -= 3)
            if (w = number[i2] | number[i2 - 1] << 8 | number[i2 - 2] << 16, this.words[j] |= w << off & 67108863, this.words[j + 1] = w >>> 26 - off & 67108863, off += 24, off >= 26)
              off -= 26, j++;
        } else if (endian === "le") {
          for (i2 = 0, j = 0;i2 < number.length; i2 += 3)
            if (w = number[i2] | number[i2 + 1] << 8 | number[i2 + 2] << 16, this.words[j] |= w << off & 67108863, this.words[j + 1] = w >>> 26 - off & 67108863, off += 24, off >= 26)
              off -= 26, j++;
        }
        return this.strip();
      };
      function parseHex4Bits(string, index) {
        var c2 = string.charCodeAt(index);
        if (c2 >= 65 && c2 <= 70)
          return c2 - 55;
        else if (c2 >= 97 && c2 <= 102)
          return c2 - 87;
        else
          return c2 - 48 & 15;
      }
      function parseHexByte(string, lowerBound, index) {
        var r2 = parseHex4Bits(string, index);
        if (index - 1 >= lowerBound)
          r2 |= parseHex4Bits(string, index - 1) << 4;
        return r2;
      }
      BN.prototype._parseHex = function(number, start, endian) {
        this.length = Math.ceil((number.length - start) / 6), this.words = Array(this.length);
        for (var i2 = 0;i2 < this.length; i2++)
          this.words[i2] = 0;
        var off = 0, j = 0, w;
        if (endian === "be")
          for (i2 = number.length - 1;i2 >= start; i2 -= 2)
            if (w = parseHexByte(number, start, i2) << off, this.words[j] |= w & 67108863, off >= 18)
              off -= 18, j += 1, this.words[j] |= w >>> 26;
            else
              off += 8;
        else {
          var parseLength = number.length - start;
          for (i2 = parseLength % 2 === 0 ? start + 1 : start;i2 < number.length; i2 += 2)
            if (w = parseHexByte(number, start, i2) << off, this.words[j] |= w & 67108863, off >= 18)
              off -= 18, j += 1, this.words[j] |= w >>> 26;
            else
              off += 8;
        }
        this.strip();
      };
      function parseBase(str, start, end, mul) {
        var r2 = 0, len2 = Math.min(str.length, end);
        for (var i2 = start;i2 < len2; i2++) {
          var c2 = str.charCodeAt(i2) - 48;
          if (r2 *= mul, c2 >= 49)
            r2 += c2 - 49 + 10;
          else if (c2 >= 17)
            r2 += c2 - 17 + 10;
          else
            r2 += c2;
        }
        return r2;
      }
      BN.prototype._parseBase = function(number, base, start) {
        this.words = [0], this.length = 1;
        for (var limbLen = 0, limbPow = 1;limbPow <= 67108863; limbPow *= base)
          limbLen++;
        limbLen--, limbPow = limbPow / base | 0;
        var total = number.length - start, mod = total % limbLen, end = Math.min(total, total - mod) + start, word = 0;
        for (var i2 = start;i2 < end; i2 += limbLen)
          if (word = parseBase(number, i2, i2 + limbLen, base), this.imuln(limbPow), this.words[0] + word < 67108864)
            this.words[0] += word;
          else
            this._iaddn(word);
        if (mod !== 0) {
          var pow = 1;
          word = parseBase(number, i2, number.length, base);
          for (i2 = 0;i2 < mod; i2++)
            pow *= base;
          if (this.imuln(pow), this.words[0] + word < 67108864)
            this.words[0] += word;
          else
            this._iaddn(word);
        }
        this.strip();
      }, BN.prototype.copy = function(dest) {
        dest.words = Array(this.length);
        for (var i2 = 0;i2 < this.length; i2++)
          dest.words[i2] = this.words[i2];
        dest.length = this.length, dest.negative = this.negative, dest.red = this.red;
      }, BN.prototype.clone = function() {
        var r2 = new BN(null);
        return this.copy(r2), r2;
      }, BN.prototype._expand = function(size) {
        while (this.length < size)
          this.words[this.length++] = 0;
        return this;
      }, BN.prototype.strip = function() {
        while (this.length > 1 && this.words[this.length - 1] === 0)
          this.length--;
        return this._normSign();
      }, BN.prototype._normSign = function() {
        if (this.length === 1 && this.words[0] === 0)
          this.negative = 0;
        return this;
      }, BN.prototype.inspect = function() {
        return (this.red ? "<BN-R: " : "<BN: ") + this.toString(16) + ">";
      };
      var zeros = ["", "0", "00", "000", "0000", "00000", "000000", "0000000", "00000000", "000000000", "0000000000", "00000000000", "000000000000", "0000000000000", "00000000000000", "000000000000000", "0000000000000000", "00000000000000000", "000000000000000000", "0000000000000000000", "00000000000000000000", "000000000000000000000", "0000000000000000000000", "00000000000000000000000", "000000000000000000000000", "0000000000000000000000000"], groupSizes = [0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5], groupBases = [0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 1e7, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176];
      if (BN.prototype.toString = function(base, padding) {
        base = base || 10, padding = padding | 0 || 1;
        var out;
        if (base === 16 || base === "hex") {
          out = "";
          var off = 0, carry = 0;
          for (var i2 = 0;i2 < this.length; i2++) {
            var w = this.words[i2], word = ((w << off | carry) & 16777215).toString(16);
            if (carry = w >>> 24 - off & 16777215, off += 2, off >= 26)
              off -= 26, i2--;
            if (carry !== 0 || i2 !== this.length - 1)
              out = zeros[6 - word.length] + word + out;
            else
              out = word + out;
          }
          if (carry !== 0)
            out = carry.toString(16) + out;
          while (out.length % padding !== 0)
            out = "0" + out;
          if (this.negative !== 0)
            out = "-" + out;
          return out;
        }
        if (base === (base | 0) && base >= 2 && base <= 36) {
          var groupSize = groupSizes[base], groupBase = groupBases[base];
          out = "";
          var c2 = this.clone();
          c2.negative = 0;
          while (!c2.isZero()) {
            var r2 = c2.modn(groupBase).toString(base);
            if (c2 = c2.idivn(groupBase), !c2.isZero())
              out = zeros[groupSize - r2.length] + r2 + out;
            else
              out = r2 + out;
          }
          if (this.isZero())
            out = "0" + out;
          while (out.length % padding !== 0)
            out = "0" + out;
          if (this.negative !== 0)
            out = "-" + out;
          return out;
        }
        assert(false, "Base should be between 2 and 36");
      }, BN.prototype.toNumber = function() {
        var ret = this.words[0];
        if (this.length === 2)
          ret += this.words[1] * 67108864;
        else if (this.length === 3 && this.words[2] === 1)
          ret += 4503599627370496 + this.words[1] * 67108864;
        else if (this.length > 2)
          assert(false, "Number can only safely store up to 53 bits");
        return this.negative !== 0 ? -ret : ret;
      }, BN.prototype.toJSON = function() {
        return this.toString(16);
      }, BN.prototype.toBuffer = function(endian, length) {
        return assert(typeof Buffer22 < "u"), this.toArrayLike(Buffer22, endian, length);
      }, BN.prototype.toArray = function(endian, length) {
        return this.toArrayLike(Array, endian, length);
      }, BN.prototype.toArrayLike = function(ArrayType, endian, length) {
        var byteLength2 = this.byteLength(), reqLength = length || Math.max(1, byteLength2);
        assert(byteLength2 <= reqLength, "byte array longer than desired length"), assert(reqLength > 0, "Requested array length <= 0"), this.strip();
        var littleEndian = endian === "le", res = new ArrayType(reqLength), b, i2, q = this.clone();
        if (!littleEndian) {
          for (i2 = 0;i2 < reqLength - byteLength2; i2++)
            res[i2] = 0;
          for (i2 = 0;!q.isZero(); i2++)
            b = q.andln(255), q.iushrn(8), res[reqLength - i2 - 1] = b;
        } else {
          for (i2 = 0;!q.isZero(); i2++)
            b = q.andln(255), q.iushrn(8), res[i2] = b;
          for (;i2 < reqLength; i2++)
            res[i2] = 0;
        }
        return res;
      }, Math.clz32)
        BN.prototype._countBits = function(w) {
          return 32 - Math.clz32(w);
        };
      else
        BN.prototype._countBits = function(w) {
          var t2 = w, r2 = 0;
          if (t2 >= 4096)
            r2 += 13, t2 >>>= 13;
          if (t2 >= 64)
            r2 += 7, t2 >>>= 7;
          if (t2 >= 8)
            r2 += 4, t2 >>>= 4;
          if (t2 >= 2)
            r2 += 2, t2 >>>= 2;
          return r2 + t2;
        };
      BN.prototype._zeroBits = function(w) {
        if (w === 0)
          return 26;
        var t2 = w, r2 = 0;
        if ((t2 & 8191) === 0)
          r2 += 13, t2 >>>= 13;
        if ((t2 & 127) === 0)
          r2 += 7, t2 >>>= 7;
        if ((t2 & 15) === 0)
          r2 += 4, t2 >>>= 4;
        if ((t2 & 3) === 0)
          r2 += 2, t2 >>>= 2;
        if ((t2 & 1) === 0)
          r2++;
        return r2;
      }, BN.prototype.bitLength = function() {
        var w = this.words[this.length - 1], hi = this._countBits(w);
        return (this.length - 1) * 26 + hi;
      };
      function toBitArray(num) {
        var w = Array(num.bitLength());
        for (var bit = 0;bit < w.length; bit++) {
          var off = bit / 26 | 0, wbit = bit % 26;
          w[bit] = (num.words[off] & 1 << wbit) >>> wbit;
        }
        return w;
      }
      BN.prototype.zeroBits = function() {
        if (this.isZero())
          return 0;
        var r2 = 0;
        for (var i2 = 0;i2 < this.length; i2++) {
          var b = this._zeroBits(this.words[i2]);
          if (r2 += b, b !== 26)
            break;
        }
        return r2;
      }, BN.prototype.byteLength = function() {
        return Math.ceil(this.bitLength() / 8);
      }, BN.prototype.toTwos = function(width) {
        if (this.negative !== 0)
          return this.abs().inotn(width).iaddn(1);
        return this.clone();
      }, BN.prototype.fromTwos = function(width) {
        if (this.testn(width - 1))
          return this.notn(width).iaddn(1).ineg();
        return this.clone();
      }, BN.prototype.isNeg = function() {
        return this.negative !== 0;
      }, BN.prototype.neg = function() {
        return this.clone().ineg();
      }, BN.prototype.ineg = function() {
        if (!this.isZero())
          this.negative ^= 1;
        return this;
      }, BN.prototype.iuor = function(num) {
        while (this.length < num.length)
          this.words[this.length++] = 0;
        for (var i2 = 0;i2 < num.length; i2++)
          this.words[i2] = this.words[i2] | num.words[i2];
        return this.strip();
      }, BN.prototype.ior = function(num) {
        return assert((this.negative | num.negative) === 0), this.iuor(num);
      }, BN.prototype.or = function(num) {
        if (this.length > num.length)
          return this.clone().ior(num);
        return num.clone().ior(this);
      }, BN.prototype.uor = function(num) {
        if (this.length > num.length)
          return this.clone().iuor(num);
        return num.clone().iuor(this);
      }, BN.prototype.iuand = function(num) {
        var b;
        if (this.length > num.length)
          b = num;
        else
          b = this;
        for (var i2 = 0;i2 < b.length; i2++)
          this.words[i2] = this.words[i2] & num.words[i2];
        return this.length = b.length, this.strip();
      }, BN.prototype.iand = function(num) {
        return assert((this.negative | num.negative) === 0), this.iuand(num);
      }, BN.prototype.and = function(num) {
        if (this.length > num.length)
          return this.clone().iand(num);
        return num.clone().iand(this);
      }, BN.prototype.uand = function(num) {
        if (this.length > num.length)
          return this.clone().iuand(num);
        return num.clone().iuand(this);
      }, BN.prototype.iuxor = function(num) {
        var a2, b;
        if (this.length > num.length)
          a2 = this, b = num;
        else
          a2 = num, b = this;
        for (var i2 = 0;i2 < b.length; i2++)
          this.words[i2] = a2.words[i2] ^ b.words[i2];
        if (this !== a2)
          for (;i2 < a2.length; i2++)
            this.words[i2] = a2.words[i2];
        return this.length = a2.length, this.strip();
      }, BN.prototype.ixor = function(num) {
        return assert((this.negative | num.negative) === 0), this.iuxor(num);
      }, BN.prototype.xor = function(num) {
        if (this.length > num.length)
          return this.clone().ixor(num);
        return num.clone().ixor(this);
      }, BN.prototype.uxor = function(num) {
        if (this.length > num.length)
          return this.clone().iuxor(num);
        return num.clone().iuxor(this);
      }, BN.prototype.inotn = function(width) {
        assert(typeof width === "number" && width >= 0);
        var bytesNeeded = Math.ceil(width / 26) | 0, bitsLeft = width % 26;
        if (this._expand(bytesNeeded), bitsLeft > 0)
          bytesNeeded--;
        for (var i2 = 0;i2 < bytesNeeded; i2++)
          this.words[i2] = ~this.words[i2] & 67108863;
        if (bitsLeft > 0)
          this.words[i2] = ~this.words[i2] & 67108863 >> 26 - bitsLeft;
        return this.strip();
      }, BN.prototype.notn = function(width) {
        return this.clone().inotn(width);
      }, BN.prototype.setn = function(bit, val) {
        assert(typeof bit === "number" && bit >= 0);
        var off = bit / 26 | 0, wbit = bit % 26;
        if (this._expand(off + 1), val)
          this.words[off] = this.words[off] | 1 << wbit;
        else
          this.words[off] = this.words[off] & ~(1 << wbit);
        return this.strip();
      }, BN.prototype.iadd = function(num) {
        var r2;
        if (this.negative !== 0 && num.negative === 0)
          return this.negative = 0, r2 = this.isub(num), this.negative ^= 1, this._normSign();
        else if (this.negative === 0 && num.negative !== 0)
          return num.negative = 0, r2 = this.isub(num), num.negative = 1, r2._normSign();
        var a2, b;
        if (this.length > num.length)
          a2 = this, b = num;
        else
          a2 = num, b = this;
        var carry = 0;
        for (var i2 = 0;i2 < b.length; i2++)
          r2 = (a2.words[i2] | 0) + (b.words[i2] | 0) + carry, this.words[i2] = r2 & 67108863, carry = r2 >>> 26;
        for (;carry !== 0 && i2 < a2.length; i2++)
          r2 = (a2.words[i2] | 0) + carry, this.words[i2] = r2 & 67108863, carry = r2 >>> 26;
        if (this.length = a2.length, carry !== 0)
          this.words[this.length] = carry, this.length++;
        else if (a2 !== this)
          for (;i2 < a2.length; i2++)
            this.words[i2] = a2.words[i2];
        return this;
      }, BN.prototype.add = function(num) {
        var res;
        if (num.negative !== 0 && this.negative === 0)
          return num.negative = 0, res = this.sub(num), num.negative ^= 1, res;
        else if (num.negative === 0 && this.negative !== 0)
          return this.negative = 0, res = num.sub(this), this.negative = 1, res;
        if (this.length > num.length)
          return this.clone().iadd(num);
        return num.clone().iadd(this);
      }, BN.prototype.isub = function(num) {
        if (num.negative !== 0) {
          num.negative = 0;
          var r2 = this.iadd(num);
          return num.negative = 1, r2._normSign();
        } else if (this.negative !== 0)
          return this.negative = 0, this.iadd(num), this.negative = 1, this._normSign();
        var cmp = this.cmp(num);
        if (cmp === 0)
          return this.negative = 0, this.length = 1, this.words[0] = 0, this;
        var a2, b;
        if (cmp > 0)
          a2 = this, b = num;
        else
          a2 = num, b = this;
        var carry = 0;
        for (var i2 = 0;i2 < b.length; i2++)
          r2 = (a2.words[i2] | 0) - (b.words[i2] | 0) + carry, carry = r2 >> 26, this.words[i2] = r2 & 67108863;
        for (;carry !== 0 && i2 < a2.length; i2++)
          r2 = (a2.words[i2] | 0) + carry, carry = r2 >> 26, this.words[i2] = r2 & 67108863;
        if (carry === 0 && i2 < a2.length && a2 !== this)
          for (;i2 < a2.length; i2++)
            this.words[i2] = a2.words[i2];
        if (this.length = Math.max(this.length, i2), a2 !== this)
          this.negative = 1;
        return this.strip();
      }, BN.prototype.sub = function(num) {
        return this.clone().isub(num);
      };
      function smallMulTo(self2, num, out) {
        out.negative = num.negative ^ self2.negative;
        var len2 = self2.length + num.length | 0;
        out.length = len2, len2 = len2 - 1 | 0;
        var a2 = self2.words[0] | 0, b = num.words[0] | 0, r2 = a2 * b, lo = r2 & 67108863, carry = r2 / 67108864 | 0;
        out.words[0] = lo;
        for (var k = 1;k < len2; k++) {
          var ncarry = carry >>> 26, rword = carry & 67108863, maxJ = Math.min(k, num.length - 1);
          for (var j = Math.max(0, k - self2.length + 1);j <= maxJ; j++) {
            var i2 = k - j | 0;
            a2 = self2.words[i2] | 0, b = num.words[j] | 0, r2 = a2 * b + rword, ncarry += r2 / 67108864 | 0, rword = r2 & 67108863;
          }
          out.words[k] = rword | 0, carry = ncarry | 0;
        }
        if (carry !== 0)
          out.words[k] = carry | 0;
        else
          out.length--;
        return out.strip();
      }
      var comb10MulTo = function(self2, num, out) {
        var a2 = self2.words, b = num.words, o2 = out.words, c2 = 0, lo, mid, hi, a0 = a2[0] | 0, al0 = a0 & 8191, ah0 = a0 >>> 13, a1 = a2[1] | 0, al1 = a1 & 8191, ah1 = a1 >>> 13, a22 = a2[2] | 0, al2 = a22 & 8191, ah2 = a22 >>> 13, a3 = a2[3] | 0, al3 = a3 & 8191, ah3 = a3 >>> 13, a4 = a2[4] | 0, al4 = a4 & 8191, ah4 = a4 >>> 13, a5 = a2[5] | 0, al5 = a5 & 8191, ah5 = a5 >>> 13, a6 = a2[6] | 0, al6 = a6 & 8191, ah6 = a6 >>> 13, a7 = a2[7] | 0, al7 = a7 & 8191, ah7 = a7 >>> 13, a8 = a2[8] | 0, al8 = a8 & 8191, ah8 = a8 >>> 13, a9 = a2[9] | 0, al9 = a9 & 8191, ah9 = a9 >>> 13, b0 = b[0] | 0, bl0 = b0 & 8191, bh0 = b0 >>> 13, b1 = b[1] | 0, bl1 = b1 & 8191, bh1 = b1 >>> 13, b2 = b[2] | 0, bl2 = b2 & 8191, bh2 = b2 >>> 13, b3 = b[3] | 0, bl3 = b3 & 8191, bh3 = b3 >>> 13, b4 = b[4] | 0, bl4 = b4 & 8191, bh4 = b4 >>> 13, b5 = b[5] | 0, bl5 = b5 & 8191, bh5 = b5 >>> 13, b6 = b[6] | 0, bl6 = b6 & 8191, bh6 = b6 >>> 13, b7 = b[7] | 0, bl7 = b7 & 8191, bh7 = b7 >>> 13, b8 = b[8] | 0, bl8 = b8 & 8191, bh8 = b8 >>> 13, b9 = b[9] | 0, bl9 = b9 & 8191, bh9 = b9 >>> 13;
        out.negative = self2.negative ^ num.negative, out.length = 19, lo = Math.imul(al0, bl0), mid = Math.imul(al0, bh0), mid = mid + Math.imul(ah0, bl0) | 0, hi = Math.imul(ah0, bh0);
        var w0 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w0 >>> 26) | 0, w0 &= 67108863, lo = Math.imul(al1, bl0), mid = Math.imul(al1, bh0), mid = mid + Math.imul(ah1, bl0) | 0, hi = Math.imul(ah1, bh0), lo = lo + Math.imul(al0, bl1) | 0, mid = mid + Math.imul(al0, bh1) | 0, mid = mid + Math.imul(ah0, bl1) | 0, hi = hi + Math.imul(ah0, bh1) | 0;
        var w1 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w1 >>> 26) | 0, w1 &= 67108863, lo = Math.imul(al2, bl0), mid = Math.imul(al2, bh0), mid = mid + Math.imul(ah2, bl0) | 0, hi = Math.imul(ah2, bh0), lo = lo + Math.imul(al1, bl1) | 0, mid = mid + Math.imul(al1, bh1) | 0, mid = mid + Math.imul(ah1, bl1) | 0, hi = hi + Math.imul(ah1, bh1) | 0, lo = lo + Math.imul(al0, bl2) | 0, mid = mid + Math.imul(al0, bh2) | 0, mid = mid + Math.imul(ah0, bl2) | 0, hi = hi + Math.imul(ah0, bh2) | 0;
        var w2 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w2 >>> 26) | 0, w2 &= 67108863, lo = Math.imul(al3, bl0), mid = Math.imul(al3, bh0), mid = mid + Math.imul(ah3, bl0) | 0, hi = Math.imul(ah3, bh0), lo = lo + Math.imul(al2, bl1) | 0, mid = mid + Math.imul(al2, bh1) | 0, mid = mid + Math.imul(ah2, bl1) | 0, hi = hi + Math.imul(ah2, bh1) | 0, lo = lo + Math.imul(al1, bl2) | 0, mid = mid + Math.imul(al1, bh2) | 0, mid = mid + Math.imul(ah1, bl2) | 0, hi = hi + Math.imul(ah1, bh2) | 0, lo = lo + Math.imul(al0, bl3) | 0, mid = mid + Math.imul(al0, bh3) | 0, mid = mid + Math.imul(ah0, bl3) | 0, hi = hi + Math.imul(ah0, bh3) | 0;
        var w3 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w3 >>> 26) | 0, w3 &= 67108863, lo = Math.imul(al4, bl0), mid = Math.imul(al4, bh0), mid = mid + Math.imul(ah4, bl0) | 0, hi = Math.imul(ah4, bh0), lo = lo + Math.imul(al3, bl1) | 0, mid = mid + Math.imul(al3, bh1) | 0, mid = mid + Math.imul(ah3, bl1) | 0, hi = hi + Math.imul(ah3, bh1) | 0, lo = lo + Math.imul(al2, bl2) | 0, mid = mid + Math.imul(al2, bh2) | 0, mid = mid + Math.imul(ah2, bl2) | 0, hi = hi + Math.imul(ah2, bh2) | 0, lo = lo + Math.imul(al1, bl3) | 0, mid = mid + Math.imul(al1, bh3) | 0, mid = mid + Math.imul(ah1, bl3) | 0, hi = hi + Math.imul(ah1, bh3) | 0, lo = lo + Math.imul(al0, bl4) | 0, mid = mid + Math.imul(al0, bh4) | 0, mid = mid + Math.imul(ah0, bl4) | 0, hi = hi + Math.imul(ah0, bh4) | 0;
        var w4 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w4 >>> 26) | 0, w4 &= 67108863, lo = Math.imul(al5, bl0), mid = Math.imul(al5, bh0), mid = mid + Math.imul(ah5, bl0) | 0, hi = Math.imul(ah5, bh0), lo = lo + Math.imul(al4, bl1) | 0, mid = mid + Math.imul(al4, bh1) | 0, mid = mid + Math.imul(ah4, bl1) | 0, hi = hi + Math.imul(ah4, bh1) | 0, lo = lo + Math.imul(al3, bl2) | 0, mid = mid + Math.imul(al3, bh2) | 0, mid = mid + Math.imul(ah3, bl2) | 0, hi = hi + Math.imul(ah3, bh2) | 0, lo = lo + Math.imul(al2, bl3) | 0, mid = mid + Math.imul(al2, bh3) | 0, mid = mid + Math.imul(ah2, bl3) | 0, hi = hi + Math.imul(ah2, bh3) | 0, lo = lo + Math.imul(al1, bl4) | 0, mid = mid + Math.imul(al1, bh4) | 0, mid = mid + Math.imul(ah1, bl4) | 0, hi = hi + Math.imul(ah1, bh4) | 0, lo = lo + Math.imul(al0, bl5) | 0, mid = mid + Math.imul(al0, bh5) | 0, mid = mid + Math.imul(ah0, bl5) | 0, hi = hi + Math.imul(ah0, bh5) | 0;
        var w5 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w5 >>> 26) | 0, w5 &= 67108863, lo = Math.imul(al6, bl0), mid = Math.imul(al6, bh0), mid = mid + Math.imul(ah6, bl0) | 0, hi = Math.imul(ah6, bh0), lo = lo + Math.imul(al5, bl1) | 0, mid = mid + Math.imul(al5, bh1) | 0, mid = mid + Math.imul(ah5, bl1) | 0, hi = hi + Math.imul(ah5, bh1) | 0, lo = lo + Math.imul(al4, bl2) | 0, mid = mid + Math.imul(al4, bh2) | 0, mid = mid + Math.imul(ah4, bl2) | 0, hi = hi + Math.imul(ah4, bh2) | 0, lo = lo + Math.imul(al3, bl3) | 0, mid = mid + Math.imul(al3, bh3) | 0, mid = mid + Math.imul(ah3, bl3) | 0, hi = hi + Math.imul(ah3, bh3) | 0, lo = lo + Math.imul(al2, bl4) | 0, mid = mid + Math.imul(al2, bh4) | 0, mid = mid + Math.imul(ah2, bl4) | 0, hi = hi + Math.imul(ah2, bh4) | 0, lo = lo + Math.imul(al1, bl5) | 0, mid = mid + Math.imul(al1, bh5) | 0, mid = mid + Math.imul(ah1, bl5) | 0, hi = hi + Math.imul(ah1, bh5) | 0, lo = lo + Math.imul(al0, bl6) | 0, mid = mid + Math.imul(al0, bh6) | 0, mid = mid + Math.imul(ah0, bl6) | 0, hi = hi + Math.imul(ah0, bh6) | 0;
        var w6 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w6 >>> 26) | 0, w6 &= 67108863, lo = Math.imul(al7, bl0), mid = Math.imul(al7, bh0), mid = mid + Math.imul(ah7, bl0) | 0, hi = Math.imul(ah7, bh0), lo = lo + Math.imul(al6, bl1) | 0, mid = mid + Math.imul(al6, bh1) | 0, mid = mid + Math.imul(ah6, bl1) | 0, hi = hi + Math.imul(ah6, bh1) | 0, lo = lo + Math.imul(al5, bl2) | 0, mid = mid + Math.imul(al5, bh2) | 0, mid = mid + Math.imul(ah5, bl2) | 0, hi = hi + Math.imul(ah5, bh2) | 0, lo = lo + Math.imul(al4, bl3) | 0, mid = mid + Math.imul(al4, bh3) | 0, mid = mid + Math.imul(ah4, bl3) | 0, hi = hi + Math.imul(ah4, bh3) | 0, lo = lo + Math.imul(al3, bl4) | 0, mid = mid + Math.imul(al3, bh4) | 0, mid = mid + Math.imul(ah3, bl4) | 0, hi = hi + Math.imul(ah3, bh4) | 0, lo = lo + Math.imul(al2, bl5) | 0, mid = mid + Math.imul(al2, bh5) | 0, mid = mid + Math.imul(ah2, bl5) | 0, hi = hi + Math.imul(ah2, bh5) | 0, lo = lo + Math.imul(al1, bl6) | 0, mid = mid + Math.imul(al1, bh6) | 0, mid = mid + Math.imul(ah1, bl6) | 0, hi = hi + Math.imul(ah1, bh6) | 0, lo = lo + Math.imul(al0, bl7) | 0, mid = mid + Math.imul(al0, bh7) | 0, mid = mid + Math.imul(ah0, bl7) | 0, hi = hi + Math.imul(ah0, bh7) | 0;
        var w7 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w7 >>> 26) | 0, w7 &= 67108863, lo = Math.imul(al8, bl0), mid = Math.imul(al8, bh0), mid = mid + Math.imul(ah8, bl0) | 0, hi = Math.imul(ah8, bh0), lo = lo + Math.imul(al7, bl1) | 0, mid = mid + Math.imul(al7, bh1) | 0, mid = mid + Math.imul(ah7, bl1) | 0, hi = hi + Math.imul(ah7, bh1) | 0, lo = lo + Math.imul(al6, bl2) | 0, mid = mid + Math.imul(al6, bh2) | 0, mid = mid + Math.imul(ah6, bl2) | 0, hi = hi + Math.imul(ah6, bh2) | 0, lo = lo + Math.imul(al5, bl3) | 0, mid = mid + Math.imul(al5, bh3) | 0, mid = mid + Math.imul(ah5, bl3) | 0, hi = hi + Math.imul(ah5, bh3) | 0, lo = lo + Math.imul(al4, bl4) | 0, mid = mid + Math.imul(al4, bh4) | 0, mid = mid + Math.imul(ah4, bl4) | 0, hi = hi + Math.imul(ah4, bh4) | 0, lo = lo + Math.imul(al3, bl5) | 0, mid = mid + Math.imul(al3, bh5) | 0, mid = mid + Math.imul(ah3, bl5) | 0, hi = hi + Math.imul(ah3, bh5) | 0, lo = lo + Math.imul(al2, bl6) | 0, mid = mid + Math.imul(al2, bh6) | 0, mid = mid + Math.imul(ah2, bl6) | 0, hi = hi + Math.imul(ah2, bh6) | 0, lo = lo + Math.imul(al1, bl7) | 0, mid = mid + Math.imul(al1, bh7) | 0, mid = mid + Math.imul(ah1, bl7) | 0, hi = hi + Math.imul(ah1, bh7) | 0, lo = lo + Math.imul(al0, bl8) | 0, mid = mid + Math.imul(al0, bh8) | 0, mid = mid + Math.imul(ah0, bl8) | 0, hi = hi + Math.imul(ah0, bh8) | 0;
        var w8 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w8 >>> 26) | 0, w8 &= 67108863, lo = Math.imul(al9, bl0), mid = Math.imul(al9, bh0), mid = mid + Math.imul(ah9, bl0) | 0, hi = Math.imul(ah9, bh0), lo = lo + Math.imul(al8, bl1) | 0, mid = mid + Math.imul(al8, bh1) | 0, mid = mid + Math.imul(ah8, bl1) | 0, hi = hi + Math.imul(ah8, bh1) | 0, lo = lo + Math.imul(al7, bl2) | 0, mid = mid + Math.imul(al7, bh2) | 0, mid = mid + Math.imul(ah7, bl2) | 0, hi = hi + Math.imul(ah7, bh2) | 0, lo = lo + Math.imul(al6, bl3) | 0, mid = mid + Math.imul(al6, bh3) | 0, mid = mid + Math.imul(ah6, bl3) | 0, hi = hi + Math.imul(ah6, bh3) | 0, lo = lo + Math.imul(al5, bl4) | 0, mid = mid + Math.imul(al5, bh4) | 0, mid = mid + Math.imul(ah5, bl4) | 0, hi = hi + Math.imul(ah5, bh4) | 0, lo = lo + Math.imul(al4, bl5) | 0, mid = mid + Math.imul(al4, bh5) | 0, mid = mid + Math.imul(ah4, bl5) | 0, hi = hi + Math.imul(ah4, bh5) | 0, lo = lo + Math.imul(al3, bl6) | 0, mid = mid + Math.imul(al3, bh6) | 0, mid = mid + Math.imul(ah3, bl6) | 0, hi = hi + Math.imul(ah3, bh6) | 0, lo = lo + Math.imul(al2, bl7) | 0, mid = mid + Math.imul(al2, bh7) | 0, mid = mid + Math.imul(ah2, bl7) | 0, hi = hi + Math.imul(ah2, bh7) | 0, lo = lo + Math.imul(al1, bl8) | 0, mid = mid + Math.imul(al1, bh8) | 0, mid = mid + Math.imul(ah1, bl8) | 0, hi = hi + Math.imul(ah1, bh8) | 0, lo = lo + Math.imul(al0, bl9) | 0, mid = mid + Math.imul(al0, bh9) | 0, mid = mid + Math.imul(ah0, bl9) | 0, hi = hi + Math.imul(ah0, bh9) | 0;
        var w9 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w9 >>> 26) | 0, w9 &= 67108863, lo = Math.imul(al9, bl1), mid = Math.imul(al9, bh1), mid = mid + Math.imul(ah9, bl1) | 0, hi = Math.imul(ah9, bh1), lo = lo + Math.imul(al8, bl2) | 0, mid = mid + Math.imul(al8, bh2) | 0, mid = mid + Math.imul(ah8, bl2) | 0, hi = hi + Math.imul(ah8, bh2) | 0, lo = lo + Math.imul(al7, bl3) | 0, mid = mid + Math.imul(al7, bh3) | 0, mid = mid + Math.imul(ah7, bl3) | 0, hi = hi + Math.imul(ah7, bh3) | 0, lo = lo + Math.imul(al6, bl4) | 0, mid = mid + Math.imul(al6, bh4) | 0, mid = mid + Math.imul(ah6, bl4) | 0, hi = hi + Math.imul(ah6, bh4) | 0, lo = lo + Math.imul(al5, bl5) | 0, mid = mid + Math.imul(al5, bh5) | 0, mid = mid + Math.imul(ah5, bl5) | 0, hi = hi + Math.imul(ah5, bh5) | 0, lo = lo + Math.imul(al4, bl6) | 0, mid = mid + Math.imul(al4, bh6) | 0, mid = mid + Math.imul(ah4, bl6) | 0, hi = hi + Math.imul(ah4, bh6) | 0, lo = lo + Math.imul(al3, bl7) | 0, mid = mid + Math.imul(al3, bh7) | 0, mid = mid + Math.imul(ah3, bl7) | 0, hi = hi + Math.imul(ah3, bh7) | 0, lo = lo + Math.imul(al2, bl8) | 0, mid = mid + Math.imul(al2, bh8) | 0, mid = mid + Math.imul(ah2, bl8) | 0, hi = hi + Math.imul(ah2, bh8) | 0, lo = lo + Math.imul(al1, bl9) | 0, mid = mid + Math.imul(al1, bh9) | 0, mid = mid + Math.imul(ah1, bl9) | 0, hi = hi + Math.imul(ah1, bh9) | 0;
        var w10 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w10 >>> 26) | 0, w10 &= 67108863, lo = Math.imul(al9, bl2), mid = Math.imul(al9, bh2), mid = mid + Math.imul(ah9, bl2) | 0, hi = Math.imul(ah9, bh2), lo = lo + Math.imul(al8, bl3) | 0, mid = mid + Math.imul(al8, bh3) | 0, mid = mid + Math.imul(ah8, bl3) | 0, hi = hi + Math.imul(ah8, bh3) | 0, lo = lo + Math.imul(al7, bl4) | 0, mid = mid + Math.imul(al7, bh4) | 0, mid = mid + Math.imul(ah7, bl4) | 0, hi = hi + Math.imul(ah7, bh4) | 0, lo = lo + Math.imul(al6, bl5) | 0, mid = mid + Math.imul(al6, bh5) | 0, mid = mid + Math.imul(ah6, bl5) | 0, hi = hi + Math.imul(ah6, bh5) | 0, lo = lo + Math.imul(al5, bl6) | 0, mid = mid + Math.imul(al5, bh6) | 0, mid = mid + Math.imul(ah5, bl6) | 0, hi = hi + Math.imul(ah5, bh6) | 0, lo = lo + Math.imul(al4, bl7) | 0, mid = mid + Math.imul(al4, bh7) | 0, mid = mid + Math.imul(ah4, bl7) | 0, hi = hi + Math.imul(ah4, bh7) | 0, lo = lo + Math.imul(al3, bl8) | 0, mid = mid + Math.imul(al3, bh8) | 0, mid = mid + Math.imul(ah3, bl8) | 0, hi = hi + Math.imul(ah3, bh8) | 0, lo = lo + Math.imul(al2, bl9) | 0, mid = mid + Math.imul(al2, bh9) | 0, mid = mid + Math.imul(ah2, bl9) | 0, hi = hi + Math.imul(ah2, bh9) | 0;
        var w11 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w11 >>> 26) | 0, w11 &= 67108863, lo = Math.imul(al9, bl3), mid = Math.imul(al9, bh3), mid = mid + Math.imul(ah9, bl3) | 0, hi = Math.imul(ah9, bh3), lo = lo + Math.imul(al8, bl4) | 0, mid = mid + Math.imul(al8, bh4) | 0, mid = mid + Math.imul(ah8, bl4) | 0, hi = hi + Math.imul(ah8, bh4) | 0, lo = lo + Math.imul(al7, bl5) | 0, mid = mid + Math.imul(al7, bh5) | 0, mid = mid + Math.imul(ah7, bl5) | 0, hi = hi + Math.imul(ah7, bh5) | 0, lo = lo + Math.imul(al6, bl6) | 0, mid = mid + Math.imul(al6, bh6) | 0, mid = mid + Math.imul(ah6, bl6) | 0, hi = hi + Math.imul(ah6, bh6) | 0, lo = lo + Math.imul(al5, bl7) | 0, mid = mid + Math.imul(al5, bh7) | 0, mid = mid + Math.imul(ah5, bl7) | 0, hi = hi + Math.imul(ah5, bh7) | 0, lo = lo + Math.imul(al4, bl8) | 0, mid = mid + Math.imul(al4, bh8) | 0, mid = mid + Math.imul(ah4, bl8) | 0, hi = hi + Math.imul(ah4, bh8) | 0, lo = lo + Math.imul(al3, bl9) | 0, mid = mid + Math.imul(al3, bh9) | 0, mid = mid + Math.imul(ah3, bl9) | 0, hi = hi + Math.imul(ah3, bh9) | 0;
        var w12 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w12 >>> 26) | 0, w12 &= 67108863, lo = Math.imul(al9, bl4), mid = Math.imul(al9, bh4), mid = mid + Math.imul(ah9, bl4) | 0, hi = Math.imul(ah9, bh4), lo = lo + Math.imul(al8, bl5) | 0, mid = mid + Math.imul(al8, bh5) | 0, mid = mid + Math.imul(ah8, bl5) | 0, hi = hi + Math.imul(ah8, bh5) | 0, lo = lo + Math.imul(al7, bl6) | 0, mid = mid + Math.imul(al7, bh6) | 0, mid = mid + Math.imul(ah7, bl6) | 0, hi = hi + Math.imul(ah7, bh6) | 0, lo = lo + Math.imul(al6, bl7) | 0, mid = mid + Math.imul(al6, bh7) | 0, mid = mid + Math.imul(ah6, bl7) | 0, hi = hi + Math.imul(ah6, bh7) | 0, lo = lo + Math.imul(al5, bl8) | 0, mid = mid + Math.imul(al5, bh8) | 0, mid = mid + Math.imul(ah5, bl8) | 0, hi = hi + Math.imul(ah5, bh8) | 0, lo = lo + Math.imul(al4, bl9) | 0, mid = mid + Math.imul(al4, bh9) | 0, mid = mid + Math.imul(ah4, bl9) | 0, hi = hi + Math.imul(ah4, bh9) | 0;
        var w13 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w13 >>> 26) | 0, w13 &= 67108863, lo = Math.imul(al9, bl5), mid = Math.imul(al9, bh5), mid = mid + Math.imul(ah9, bl5) | 0, hi = Math.imul(ah9, bh5), lo = lo + Math.imul(al8, bl6) | 0, mid = mid + Math.imul(al8, bh6) | 0, mid = mid + Math.imul(ah8, bl6) | 0, hi = hi + Math.imul(ah8, bh6) | 0, lo = lo + Math.imul(al7, bl7) | 0, mid = mid + Math.imul(al7, bh7) | 0, mid = mid + Math.imul(ah7, bl7) | 0, hi = hi + Math.imul(ah7, bh7) | 0, lo = lo + Math.imul(al6, bl8) | 0, mid = mid + Math.imul(al6, bh8) | 0, mid = mid + Math.imul(ah6, bl8) | 0, hi = hi + Math.imul(ah6, bh8) | 0, lo = lo + Math.imul(al5, bl9) | 0, mid = mid + Math.imul(al5, bh9) | 0, mid = mid + Math.imul(ah5, bl9) | 0, hi = hi + Math.imul(ah5, bh9) | 0;
        var w14 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w14 >>> 26) | 0, w14 &= 67108863, lo = Math.imul(al9, bl6), mid = Math.imul(al9, bh6), mid = mid + Math.imul(ah9, bl6) | 0, hi = Math.imul(ah9, bh6), lo = lo + Math.imul(al8, bl7) | 0, mid = mid + Math.imul(al8, bh7) | 0, mid = mid + Math.imul(ah8, bl7) | 0, hi = hi + Math.imul(ah8, bh7) | 0, lo = lo + Math.imul(al7, bl8) | 0, mid = mid + Math.imul(al7, bh8) | 0, mid = mid + Math.imul(ah7, bl8) | 0, hi = hi + Math.imul(ah7, bh8) | 0, lo = lo + Math.imul(al6, bl9) | 0, mid = mid + Math.imul(al6, bh9) | 0, mid = mid + Math.imul(ah6, bl9) | 0, hi = hi + Math.imul(ah6, bh9) | 0;
        var w15 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w15 >>> 26) | 0, w15 &= 67108863, lo = Math.imul(al9, bl7), mid = Math.imul(al9, bh7), mid = mid + Math.imul(ah9, bl7) | 0, hi = Math.imul(ah9, bh7), lo = lo + Math.imul(al8, bl8) | 0, mid = mid + Math.imul(al8, bh8) | 0, mid = mid + Math.imul(ah8, bl8) | 0, hi = hi + Math.imul(ah8, bh8) | 0, lo = lo + Math.imul(al7, bl9) | 0, mid = mid + Math.imul(al7, bh9) | 0, mid = mid + Math.imul(ah7, bl9) | 0, hi = hi + Math.imul(ah7, bh9) | 0;
        var w16 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w16 >>> 26) | 0, w16 &= 67108863, lo = Math.imul(al9, bl8), mid = Math.imul(al9, bh8), mid = mid + Math.imul(ah9, bl8) | 0, hi = Math.imul(ah9, bh8), lo = lo + Math.imul(al8, bl9) | 0, mid = mid + Math.imul(al8, bh9) | 0, mid = mid + Math.imul(ah8, bl9) | 0, hi = hi + Math.imul(ah8, bh9) | 0;
        var w17 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w17 >>> 26) | 0, w17 &= 67108863, lo = Math.imul(al9, bl9), mid = Math.imul(al9, bh9), mid = mid + Math.imul(ah9, bl9) | 0, hi = Math.imul(ah9, bh9);
        var w18 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        if (c2 = (hi + (mid >>> 13) | 0) + (w18 >>> 26) | 0, w18 &= 67108863, o2[0] = w0, o2[1] = w1, o2[2] = w2, o2[3] = w3, o2[4] = w4, o2[5] = w5, o2[6] = w6, o2[7] = w7, o2[8] = w8, o2[9] = w9, o2[10] = w10, o2[11] = w11, o2[12] = w12, o2[13] = w13, o2[14] = w14, o2[15] = w15, o2[16] = w16, o2[17] = w17, o2[18] = w18, c2 !== 0)
          o2[19] = c2, out.length++;
        return out;
      };
      if (!Math.imul)
        comb10MulTo = smallMulTo;
      function bigMulTo(self2, num, out) {
        out.negative = num.negative ^ self2.negative, out.length = self2.length + num.length;
        var carry = 0, hncarry = 0;
        for (var k = 0;k < out.length - 1; k++) {
          var ncarry = hncarry;
          hncarry = 0;
          var rword = carry & 67108863, maxJ = Math.min(k, num.length - 1);
          for (var j = Math.max(0, k - self2.length + 1);j <= maxJ; j++) {
            var i2 = k - j, a2 = self2.words[i2] | 0, b = num.words[j] | 0, r2 = a2 * b, lo = r2 & 67108863;
            ncarry = ncarry + (r2 / 67108864 | 0) | 0, lo = lo + rword | 0, rword = lo & 67108863, ncarry = ncarry + (lo >>> 26) | 0, hncarry += ncarry >>> 26, ncarry &= 67108863;
          }
          out.words[k] = rword, carry = ncarry, ncarry = hncarry;
        }
        if (carry !== 0)
          out.words[k] = carry;
        else
          out.length--;
        return out.strip();
      }
      function jumboMulTo(self2, num, out) {
        var fftm = new FFTM;
        return fftm.mulp(self2, num, out);
      }
      BN.prototype.mulTo = function(num, out) {
        var res, len2 = this.length + num.length;
        if (this.length === 10 && num.length === 10)
          res = comb10MulTo(this, num, out);
        else if (len2 < 63)
          res = smallMulTo(this, num, out);
        else if (len2 < 1024)
          res = bigMulTo(this, num, out);
        else
          res = jumboMulTo(this, num, out);
        return res;
      };
      function FFTM(x, y) {
        this.x = x, this.y = y;
      }
      FFTM.prototype.makeRBT = function(N) {
        var t2 = Array(N), l2 = BN.prototype._countBits(N) - 1;
        for (var i2 = 0;i2 < N; i2++)
          t2[i2] = this.revBin(i2, l2, N);
        return t2;
      }, FFTM.prototype.revBin = function(x, l2, N) {
        if (x === 0 || x === N - 1)
          return x;
        var rb = 0;
        for (var i2 = 0;i2 < l2; i2++)
          rb |= (x & 1) << l2 - i2 - 1, x >>= 1;
        return rb;
      }, FFTM.prototype.permute = function(rbt, rws, iws, rtws, itws, N) {
        for (var i2 = 0;i2 < N; i2++)
          rtws[i2] = rws[rbt[i2]], itws[i2] = iws[rbt[i2]];
      }, FFTM.prototype.transform = function(rws, iws, rtws, itws, N, rbt) {
        this.permute(rbt, rws, iws, rtws, itws, N);
        for (var s = 1;s < N; s <<= 1) {
          var l2 = s << 1, rtwdf = Math.cos(2 * Math.PI / l2), itwdf = Math.sin(2 * Math.PI / l2);
          for (var p2 = 0;p2 < N; p2 += l2) {
            var rtwdf_ = rtwdf, itwdf_ = itwdf;
            for (var j = 0;j < s; j++) {
              var re = rtws[p2 + j], ie = itws[p2 + j], ro = rtws[p2 + j + s], io = itws[p2 + j + s], rx = rtwdf_ * ro - itwdf_ * io;
              if (io = rtwdf_ * io + itwdf_ * ro, ro = rx, rtws[p2 + j] = re + ro, itws[p2 + j] = ie + io, rtws[p2 + j + s] = re - ro, itws[p2 + j + s] = ie - io, j !== l2)
                rx = rtwdf * rtwdf_ - itwdf * itwdf_, itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_, rtwdf_ = rx;
            }
          }
        }
      }, FFTM.prototype.guessLen13b = function(n2, m) {
        var N = Math.max(m, n2) | 1, odd = N & 1, i2 = 0;
        for (N = N / 2 | 0;N; N = N >>> 1)
          i2++;
        return 1 << i2 + 1 + odd;
      }, FFTM.prototype.conjugate = function(rws, iws, N) {
        if (N <= 1)
          return;
        for (var i2 = 0;i2 < N / 2; i2++) {
          var t2 = rws[i2];
          rws[i2] = rws[N - i2 - 1], rws[N - i2 - 1] = t2, t2 = iws[i2], iws[i2] = -iws[N - i2 - 1], iws[N - i2 - 1] = -t2;
        }
      }, FFTM.prototype.normalize13b = function(ws, N) {
        var carry = 0;
        for (var i2 = 0;i2 < N / 2; i2++) {
          var w = Math.round(ws[2 * i2 + 1] / N) * 8192 + Math.round(ws[2 * i2] / N) + carry;
          if (ws[i2] = w & 67108863, w < 67108864)
            carry = 0;
          else
            carry = w / 67108864 | 0;
        }
        return ws;
      }, FFTM.prototype.convert13b = function(ws, len2, rws, N) {
        var carry = 0;
        for (var i2 = 0;i2 < len2; i2++)
          carry = carry + (ws[i2] | 0), rws[2 * i2] = carry & 8191, carry = carry >>> 13, rws[2 * i2 + 1] = carry & 8191, carry = carry >>> 13;
        for (i2 = 2 * len2;i2 < N; ++i2)
          rws[i2] = 0;
        assert(carry === 0), assert((carry & -8192) === 0);
      }, FFTM.prototype.stub = function(N) {
        var ph = Array(N);
        for (var i2 = 0;i2 < N; i2++)
          ph[i2] = 0;
        return ph;
      }, FFTM.prototype.mulp = function(x, y, out) {
        var N = 2 * this.guessLen13b(x.length, y.length), rbt = this.makeRBT(N), _ = this.stub(N), rws = Array(N), rwst = Array(N), iwst = Array(N), nrws = Array(N), nrwst = Array(N), niwst = Array(N), rmws = out.words;
        rmws.length = N, this.convert13b(x.words, x.length, rws, N), this.convert13b(y.words, y.length, nrws, N), this.transform(rws, _, rwst, iwst, N, rbt), this.transform(nrws, _, nrwst, niwst, N, rbt);
        for (var i2 = 0;i2 < N; i2++) {
          var rx = rwst[i2] * nrwst[i2] - iwst[i2] * niwst[i2];
          iwst[i2] = rwst[i2] * niwst[i2] + iwst[i2] * nrwst[i2], rwst[i2] = rx;
        }
        return this.conjugate(rwst, iwst, N), this.transform(rwst, iwst, rmws, _, N, rbt), this.conjugate(rmws, _, N), this.normalize13b(rmws, N), out.negative = x.negative ^ y.negative, out.length = x.length + y.length, out.strip();
      }, BN.prototype.mul = function(num) {
        var out = new BN(null);
        return out.words = Array(this.length + num.length), this.mulTo(num, out);
      }, BN.prototype.mulf = function(num) {
        var out = new BN(null);
        return out.words = Array(this.length + num.length), jumboMulTo(this, num, out);
      }, BN.prototype.imul = function(num) {
        return this.clone().mulTo(num, this);
      }, BN.prototype.imuln = function(num) {
        assert(typeof num === "number"), assert(num < 67108864);
        var carry = 0;
        for (var i2 = 0;i2 < this.length; i2++) {
          var w = (this.words[i2] | 0) * num, lo = (w & 67108863) + (carry & 67108863);
          carry >>= 26, carry += w / 67108864 | 0, carry += lo >>> 26, this.words[i2] = lo & 67108863;
        }
        if (carry !== 0)
          this.words[i2] = carry, this.length++;
        return this.length = num === 0 ? 1 : this.length, this;
      }, BN.prototype.muln = function(num) {
        return this.clone().imuln(num);
      }, BN.prototype.sqr = function() {
        return this.mul(this);
      }, BN.prototype.isqr = function() {
        return this.imul(this.clone());
      }, BN.prototype.pow = function(num) {
        var w = toBitArray(num);
        if (w.length === 0)
          return new BN(1);
        var res = this;
        for (var i2 = 0;i2 < w.length; i2++, res = res.sqr())
          if (w[i2] !== 0)
            break;
        if (++i2 < w.length)
          for (var q = res.sqr();i2 < w.length; i2++, q = q.sqr()) {
            if (w[i2] === 0)
              continue;
            res = res.mul(q);
          }
        return res;
      }, BN.prototype.iushln = function(bits) {
        assert(typeof bits === "number" && bits >= 0);
        var r2 = bits % 26, s = (bits - r2) / 26, carryMask = 67108863 >>> 26 - r2 << 26 - r2, i2;
        if (r2 !== 0) {
          var carry = 0;
          for (i2 = 0;i2 < this.length; i2++) {
            var newCarry = this.words[i2] & carryMask, c2 = (this.words[i2] | 0) - newCarry << r2;
            this.words[i2] = c2 | carry, carry = newCarry >>> 26 - r2;
          }
          if (carry)
            this.words[i2] = carry, this.length++;
        }
        if (s !== 0) {
          for (i2 = this.length - 1;i2 >= 0; i2--)
            this.words[i2 + s] = this.words[i2];
          for (i2 = 0;i2 < s; i2++)
            this.words[i2] = 0;
          this.length += s;
        }
        return this.strip();
      }, BN.prototype.ishln = function(bits) {
        return assert(this.negative === 0), this.iushln(bits);
      }, BN.prototype.iushrn = function(bits, hint, extended) {
        assert(typeof bits === "number" && bits >= 0);
        var h;
        if (hint)
          h = (hint - hint % 26) / 26;
        else
          h = 0;
        var r2 = bits % 26, s = Math.min((bits - r2) / 26, this.length), mask = 67108863 ^ 67108863 >>> r2 << r2, maskedWords = extended;
        if (h -= s, h = Math.max(0, h), maskedWords) {
          for (var i2 = 0;i2 < s; i2++)
            maskedWords.words[i2] = this.words[i2];
          maskedWords.length = s;
        }
        if (s === 0)
          ;
        else if (this.length > s) {
          this.length -= s;
          for (i2 = 0;i2 < this.length; i2++)
            this.words[i2] = this.words[i2 + s];
        } else
          this.words[0] = 0, this.length = 1;
        var carry = 0;
        for (i2 = this.length - 1;i2 >= 0 && (carry !== 0 || i2 >= h); i2--) {
          var word = this.words[i2] | 0;
          this.words[i2] = carry << 26 - r2 | word >>> r2, carry = word & mask;
        }
        if (maskedWords && carry !== 0)
          maskedWords.words[maskedWords.length++] = carry;
        if (this.length === 0)
          this.words[0] = 0, this.length = 1;
        return this.strip();
      }, BN.prototype.ishrn = function(bits, hint, extended) {
        return assert(this.negative === 0), this.iushrn(bits, hint, extended);
      }, BN.prototype.shln = function(bits) {
        return this.clone().ishln(bits);
      }, BN.prototype.ushln = function(bits) {
        return this.clone().iushln(bits);
      }, BN.prototype.shrn = function(bits) {
        return this.clone().ishrn(bits);
      }, BN.prototype.ushrn = function(bits) {
        return this.clone().iushrn(bits);
      }, BN.prototype.testn = function(bit) {
        assert(typeof bit === "number" && bit >= 0);
        var r2 = bit % 26, s = (bit - r2) / 26, q = 1 << r2;
        if (this.length <= s)
          return false;
        var w = this.words[s];
        return !!(w & q);
      }, BN.prototype.imaskn = function(bits) {
        assert(typeof bits === "number" && bits >= 0);
        var r2 = bits % 26, s = (bits - r2) / 26;
        if (assert(this.negative === 0, "imaskn works only with positive numbers"), this.length <= s)
          return this;
        if (r2 !== 0)
          s++;
        if (this.length = Math.min(s, this.length), r2 !== 0) {
          var mask = 67108863 ^ 67108863 >>> r2 << r2;
          this.words[this.length - 1] &= mask;
        }
        return this.strip();
      }, BN.prototype.maskn = function(bits) {
        return this.clone().imaskn(bits);
      }, BN.prototype.iaddn = function(num) {
        if (assert(typeof num === "number"), assert(num < 67108864), num < 0)
          return this.isubn(-num);
        if (this.negative !== 0) {
          if (this.length === 1 && (this.words[0] | 0) < num)
            return this.words[0] = num - (this.words[0] | 0), this.negative = 0, this;
          return this.negative = 0, this.isubn(num), this.negative = 1, this;
        }
        return this._iaddn(num);
      }, BN.prototype._iaddn = function(num) {
        this.words[0] += num;
        for (var i2 = 0;i2 < this.length && this.words[i2] >= 67108864; i2++)
          if (this.words[i2] -= 67108864, i2 === this.length - 1)
            this.words[i2 + 1] = 1;
          else
            this.words[i2 + 1]++;
        return this.length = Math.max(this.length, i2 + 1), this;
      }, BN.prototype.isubn = function(num) {
        if (assert(typeof num === "number"), assert(num < 67108864), num < 0)
          return this.iaddn(-num);
        if (this.negative !== 0)
          return this.negative = 0, this.iaddn(num), this.negative = 1, this;
        if (this.words[0] -= num, this.length === 1 && this.words[0] < 0)
          this.words[0] = -this.words[0], this.negative = 1;
        else
          for (var i2 = 0;i2 < this.length && this.words[i2] < 0; i2++)
            this.words[i2] += 67108864, this.words[i2 + 1] -= 1;
        return this.strip();
      }, BN.prototype.addn = function(num) {
        return this.clone().iaddn(num);
      }, BN.prototype.subn = function(num) {
        return this.clone().isubn(num);
      }, BN.prototype.iabs = function() {
        return this.negative = 0, this;
      }, BN.prototype.abs = function() {
        return this.clone().iabs();
      }, BN.prototype._ishlnsubmul = function(num, mul, shift) {
        var len2 = num.length + shift, i2;
        this._expand(len2);
        var w, carry = 0;
        for (i2 = 0;i2 < num.length; i2++) {
          w = (this.words[i2 + shift] | 0) + carry;
          var right = (num.words[i2] | 0) * mul;
          w -= right & 67108863, carry = (w >> 26) - (right / 67108864 | 0), this.words[i2 + shift] = w & 67108863;
        }
        for (;i2 < this.length - shift; i2++)
          w = (this.words[i2 + shift] | 0) + carry, carry = w >> 26, this.words[i2 + shift] = w & 67108863;
        if (carry === 0)
          return this.strip();
        assert(carry === -1), carry = 0;
        for (i2 = 0;i2 < this.length; i2++)
          w = -(this.words[i2] | 0) + carry, carry = w >> 26, this.words[i2] = w & 67108863;
        return this.negative = 1, this.strip();
      }, BN.prototype._wordDiv = function(num, mode) {
        var shift = this.length - num.length, a2 = this.clone(), b = num, bhi = b.words[b.length - 1] | 0, bhiBits = this._countBits(bhi);
        if (shift = 26 - bhiBits, shift !== 0)
          b = b.ushln(shift), a2.iushln(shift), bhi = b.words[b.length - 1] | 0;
        var m = a2.length - b.length, q;
        if (mode !== "mod") {
          q = new BN(null), q.length = m + 1, q.words = Array(q.length);
          for (var i2 = 0;i2 < q.length; i2++)
            q.words[i2] = 0;
        }
        var diff = a2.clone()._ishlnsubmul(b, 1, m);
        if (diff.negative === 0) {
          if (a2 = diff, q)
            q.words[m] = 1;
        }
        for (var j = m - 1;j >= 0; j--) {
          var qj = (a2.words[b.length + j] | 0) * 67108864 + (a2.words[b.length + j - 1] | 0);
          qj = Math.min(qj / bhi | 0, 67108863), a2._ishlnsubmul(b, qj, j);
          while (a2.negative !== 0)
            if (qj--, a2.negative = 0, a2._ishlnsubmul(b, 1, j), !a2.isZero())
              a2.negative ^= 1;
          if (q)
            q.words[j] = qj;
        }
        if (q)
          q.strip();
        if (a2.strip(), mode !== "div" && shift !== 0)
          a2.iushrn(shift);
        return { div: q || null, mod: a2 };
      }, BN.prototype.divmod = function(num, mode, positive) {
        if (assert(!num.isZero()), this.isZero())
          return { div: new BN(0), mod: new BN(0) };
        var div, mod, res;
        if (this.negative !== 0 && num.negative === 0) {
          if (res = this.neg().divmod(num, mode), mode !== "mod")
            div = res.div.neg();
          if (mode !== "div") {
            if (mod = res.mod.neg(), positive && mod.negative !== 0)
              mod.iadd(num);
          }
          return { div, mod };
        }
        if (this.negative === 0 && num.negative !== 0) {
          if (res = this.divmod(num.neg(), mode), mode !== "mod")
            div = res.div.neg();
          return { div, mod: res.mod };
        }
        if ((this.negative & num.negative) !== 0) {
          if (res = this.neg().divmod(num.neg(), mode), mode !== "div") {
            if (mod = res.mod.neg(), positive && mod.negative !== 0)
              mod.isub(num);
          }
          return { div: res.div, mod };
        }
        if (num.length > this.length || this.cmp(num) < 0)
          return { div: new BN(0), mod: this };
        if (num.length === 1) {
          if (mode === "div")
            return { div: this.divn(num.words[0]), mod: null };
          if (mode === "mod")
            return { div: null, mod: new BN(this.modn(num.words[0])) };
          return { div: this.divn(num.words[0]), mod: new BN(this.modn(num.words[0])) };
        }
        return this._wordDiv(num, mode);
      }, BN.prototype.div = function(num) {
        return this.divmod(num, "div", false).div;
      }, BN.prototype.mod = function(num) {
        return this.divmod(num, "mod", false).mod;
      }, BN.prototype.umod = function(num) {
        return this.divmod(num, "mod", true).mod;
      }, BN.prototype.divRound = function(num) {
        var dm = this.divmod(num);
        if (dm.mod.isZero())
          return dm.div;
        var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod, half = num.ushrn(1), r2 = num.andln(1), cmp = mod.cmp(half);
        if (cmp < 0 || r2 === 1 && cmp === 0)
          return dm.div;
        return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
      }, BN.prototype.modn = function(num) {
        assert(num <= 67108863);
        var p2 = 67108864 % num, acc = 0;
        for (var i2 = this.length - 1;i2 >= 0; i2--)
          acc = (p2 * acc + (this.words[i2] | 0)) % num;
        return acc;
      }, BN.prototype.idivn = function(num) {
        assert(num <= 67108863);
        var carry = 0;
        for (var i2 = this.length - 1;i2 >= 0; i2--) {
          var w = (this.words[i2] | 0) + carry * 67108864;
          this.words[i2] = w / num | 0, carry = w % num;
        }
        return this.strip();
      }, BN.prototype.divn = function(num) {
        return this.clone().idivn(num);
      }, BN.prototype.egcd = function(p2) {
        assert(p2.negative === 0), assert(!p2.isZero());
        var x = this, y = p2.clone();
        if (x.negative !== 0)
          x = x.umod(p2);
        else
          x = x.clone();
        var A = new BN(1), B = new BN(0), C = new BN(0), D = new BN(1), g = 0;
        while (x.isEven() && y.isEven())
          x.iushrn(1), y.iushrn(1), ++g;
        var yp = y.clone(), xp = x.clone();
        while (!x.isZero()) {
          for (var i2 = 0, im = 1;(x.words[0] & im) === 0 && i2 < 26; ++i2, im <<= 1)
            ;
          if (i2 > 0) {
            x.iushrn(i2);
            while (i2-- > 0) {
              if (A.isOdd() || B.isOdd())
                A.iadd(yp), B.isub(xp);
              A.iushrn(1), B.iushrn(1);
            }
          }
          for (var j = 0, jm = 1;(y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1)
            ;
          if (j > 0) {
            y.iushrn(j);
            while (j-- > 0) {
              if (C.isOdd() || D.isOdd())
                C.iadd(yp), D.isub(xp);
              C.iushrn(1), D.iushrn(1);
            }
          }
          if (x.cmp(y) >= 0)
            x.isub(y), A.isub(C), B.isub(D);
          else
            y.isub(x), C.isub(A), D.isub(B);
        }
        return { a: C, b: D, gcd: y.iushln(g) };
      }, BN.prototype._invmp = function(p2) {
        assert(p2.negative === 0), assert(!p2.isZero());
        var a2 = this, b = p2.clone();
        if (a2.negative !== 0)
          a2 = a2.umod(p2);
        else
          a2 = a2.clone();
        var x1 = new BN(1), x2 = new BN(0), delta = b.clone();
        while (a2.cmpn(1) > 0 && b.cmpn(1) > 0) {
          for (var i2 = 0, im = 1;(a2.words[0] & im) === 0 && i2 < 26; ++i2, im <<= 1)
            ;
          if (i2 > 0) {
            a2.iushrn(i2);
            while (i2-- > 0) {
              if (x1.isOdd())
                x1.iadd(delta);
              x1.iushrn(1);
            }
          }
          for (var j = 0, jm = 1;(b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1)
            ;
          if (j > 0) {
            b.iushrn(j);
            while (j-- > 0) {
              if (x2.isOdd())
                x2.iadd(delta);
              x2.iushrn(1);
            }
          }
          if (a2.cmp(b) >= 0)
            a2.isub(b), x1.isub(x2);
          else
            b.isub(a2), x2.isub(x1);
        }
        var res;
        if (a2.cmpn(1) === 0)
          res = x1;
        else
          res = x2;
        if (res.cmpn(0) < 0)
          res.iadd(p2);
        return res;
      }, BN.prototype.gcd = function(num) {
        if (this.isZero())
          return num.abs();
        if (num.isZero())
          return this.abs();
        var a2 = this.clone(), b = num.clone();
        a2.negative = 0, b.negative = 0;
        for (var shift = 0;a2.isEven() && b.isEven(); shift++)
          a2.iushrn(1), b.iushrn(1);
        do {
          while (a2.isEven())
            a2.iushrn(1);
          while (b.isEven())
            b.iushrn(1);
          var r2 = a2.cmp(b);
          if (r2 < 0) {
            var t2 = a2;
            a2 = b, b = t2;
          } else if (r2 === 0 || b.cmpn(1) === 0)
            break;
          a2.isub(b);
        } while (true);
        return b.iushln(shift);
      }, BN.prototype.invm = function(num) {
        return this.egcd(num).a.umod(num);
      }, BN.prototype.isEven = function() {
        return (this.words[0] & 1) === 0;
      }, BN.prototype.isOdd = function() {
        return (this.words[0] & 1) === 1;
      }, BN.prototype.andln = function(num) {
        return this.words[0] & num;
      }, BN.prototype.bincn = function(bit) {
        assert(typeof bit === "number");
        var r2 = bit % 26, s = (bit - r2) / 26, q = 1 << r2;
        if (this.length <= s)
          return this._expand(s + 1), this.words[s] |= q, this;
        var carry = q;
        for (var i2 = s;carry !== 0 && i2 < this.length; i2++) {
          var w = this.words[i2] | 0;
          w += carry, carry = w >>> 26, w &= 67108863, this.words[i2] = w;
        }
        if (carry !== 0)
          this.words[i2] = carry, this.length++;
        return this;
      }, BN.prototype.isZero = function() {
        return this.length === 1 && this.words[0] === 0;
      }, BN.prototype.cmpn = function(num) {
        var negative = num < 0;
        if (this.negative !== 0 && !negative)
          return -1;
        if (this.negative === 0 && negative)
          return 1;
        this.strip();
        var res;
        if (this.length > 1)
          res = 1;
        else {
          if (negative)
            num = -num;
          assert(num <= 67108863, "Number is too big");
          var w = this.words[0] | 0;
          res = w === num ? 0 : w < num ? -1 : 1;
        }
        if (this.negative !== 0)
          return -res | 0;
        return res;
      }, BN.prototype.cmp = function(num) {
        if (this.negative !== 0 && num.negative === 0)
          return -1;
        if (this.negative === 0 && num.negative !== 0)
          return 1;
        var res = this.ucmp(num);
        if (this.negative !== 0)
          return -res | 0;
        return res;
      }, BN.prototype.ucmp = function(num) {
        if (this.length > num.length)
          return 1;
        if (this.length < num.length)
          return -1;
        var res = 0;
        for (var i2 = this.length - 1;i2 >= 0; i2--) {
          var a2 = this.words[i2] | 0, b = num.words[i2] | 0;
          if (a2 === b)
            continue;
          if (a2 < b)
            res = -1;
          else if (a2 > b)
            res = 1;
          break;
        }
        return res;
      }, BN.prototype.gtn = function(num) {
        return this.cmpn(num) === 1;
      }, BN.prototype.gt = function(num) {
        return this.cmp(num) === 1;
      }, BN.prototype.gten = function(num) {
        return this.cmpn(num) >= 0;
      }, BN.prototype.gte = function(num) {
        return this.cmp(num) >= 0;
      }, BN.prototype.ltn = function(num) {
        return this.cmpn(num) === -1;
      }, BN.prototype.lt = function(num) {
        return this.cmp(num) === -1;
      }, BN.prototype.lten = function(num) {
        return this.cmpn(num) <= 0;
      }, BN.prototype.lte = function(num) {
        return this.cmp(num) <= 0;
      }, BN.prototype.eqn = function(num) {
        return this.cmpn(num) === 0;
      }, BN.prototype.eq = function(num) {
        return this.cmp(num) === 0;
      }, BN.red = function(num) {
        return new Red(num);
      }, BN.prototype.toRed = function(ctx) {
        return assert(!this.red, "Already a number in reduction context"), assert(this.negative === 0, "red works only with positives"), ctx.convertTo(this)._forceRed(ctx);
      }, BN.prototype.fromRed = function() {
        return assert(this.red, "fromRed works only with numbers in reduction context"), this.red.convertFrom(this);
      }, BN.prototype._forceRed = function(ctx) {
        return this.red = ctx, this;
      }, BN.prototype.forceRed = function(ctx) {
        return assert(!this.red, "Already a number in reduction context"), this._forceRed(ctx);
      }, BN.prototype.redAdd = function(num) {
        return assert(this.red, "redAdd works only with red numbers"), this.red.add(this, num);
      }, BN.prototype.redIAdd = function(num) {
        return assert(this.red, "redIAdd works only with red numbers"), this.red.iadd(this, num);
      }, BN.prototype.redSub = function(num) {
        return assert(this.red, "redSub works only with red numbers"), this.red.sub(this, num);
      }, BN.prototype.redISub = function(num) {
        return assert(this.red, "redISub works only with red numbers"), this.red.isub(this, num);
      }, BN.prototype.redShl = function(num) {
        return assert(this.red, "redShl works only with red numbers"), this.red.shl(this, num);
      }, BN.prototype.redMul = function(num) {
        return assert(this.red, "redMul works only with red numbers"), this.red._verify2(this, num), this.red.mul(this, num);
      }, BN.prototype.redIMul = function(num) {
        return assert(this.red, "redMul works only with red numbers"), this.red._verify2(this, num), this.red.imul(this, num);
      }, BN.prototype.redSqr = function() {
        return assert(this.red, "redSqr works only with red numbers"), this.red._verify1(this), this.red.sqr(this);
      }, BN.prototype.redISqr = function() {
        return assert(this.red, "redISqr works only with red numbers"), this.red._verify1(this), this.red.isqr(this);
      }, BN.prototype.redSqrt = function() {
        return assert(this.red, "redSqrt works only with red numbers"), this.red._verify1(this), this.red.sqrt(this);
      }, BN.prototype.redInvm = function() {
        return assert(this.red, "redInvm works only with red numbers"), this.red._verify1(this), this.red.invm(this);
      }, BN.prototype.redNeg = function() {
        return assert(this.red, "redNeg works only with red numbers"), this.red._verify1(this), this.red.neg(this);
      }, BN.prototype.redPow = function(num) {
        return assert(this.red && !num.red, "redPow(normalNum)"), this.red._verify1(this), this.red.pow(this, num);
      };
      var primes = { k256: null, p224: null, p192: null, p25519: null };
      function MPrime(name, p2) {
        this.name = name, this.p = new BN(p2, 16), this.n = this.p.bitLength(), this.k = new BN(1).iushln(this.n).isub(this.p), this.tmp = this._tmp();
      }
      MPrime.prototype._tmp = function() {
        var tmp = new BN(null);
        return tmp.words = Array(Math.ceil(this.n / 13)), tmp;
      }, MPrime.prototype.ireduce = function(num) {
        var r2 = num, rlen;
        do
          this.split(r2, this.tmp), r2 = this.imulK(r2), r2 = r2.iadd(this.tmp), rlen = r2.bitLength();
        while (rlen > this.n);
        var cmp = rlen < this.n ? -1 : r2.ucmp(this.p);
        if (cmp === 0)
          r2.words[0] = 0, r2.length = 1;
        else if (cmp > 0)
          r2.isub(this.p);
        else if (r2.strip !== undefined)
          r2.strip();
        else
          r2._strip();
        return r2;
      }, MPrime.prototype.split = function(input, out) {
        input.iushrn(this.n, 0, out);
      }, MPrime.prototype.imulK = function(num) {
        return num.imul(this.k);
      };
      function K256() {
        MPrime.call(this, "k256", "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f");
      }
      inherits2(K256, MPrime), K256.prototype.split = function(input, output) {
        var mask = 4194303, outLen = Math.min(input.length, 9);
        for (var i2 = 0;i2 < outLen; i2++)
          output.words[i2] = input.words[i2];
        if (output.length = outLen, input.length <= 9) {
          input.words[0] = 0, input.length = 1;
          return;
        }
        var prev = input.words[9];
        output.words[output.length++] = prev & mask;
        for (i2 = 10;i2 < input.length; i2++) {
          var next = input.words[i2] | 0;
          input.words[i2 - 10] = (next & mask) << 4 | prev >>> 22, prev = next;
        }
        if (prev >>>= 22, input.words[i2 - 10] = prev, prev === 0 && input.length > 10)
          input.length -= 10;
        else
          input.length -= 9;
      }, K256.prototype.imulK = function(num) {
        num.words[num.length] = 0, num.words[num.length + 1] = 0, num.length += 2;
        var lo = 0;
        for (var i2 = 0;i2 < num.length; i2++) {
          var w = num.words[i2] | 0;
          lo += w * 977, num.words[i2] = lo & 67108863, lo = w * 64 + (lo / 67108864 | 0);
        }
        if (num.words[num.length - 1] === 0) {
          if (num.length--, num.words[num.length - 1] === 0)
            num.length--;
        }
        return num;
      };
      function P224() {
        MPrime.call(this, "p224", "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001");
      }
      inherits2(P224, MPrime);
      function P192() {
        MPrime.call(this, "p192", "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff");
      }
      inherits2(P192, MPrime);
      function P25519() {
        MPrime.call(this, "25519", "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed");
      }
      inherits2(P25519, MPrime), P25519.prototype.imulK = function(num) {
        var carry = 0;
        for (var i2 = 0;i2 < num.length; i2++) {
          var hi = (num.words[i2] | 0) * 19 + carry, lo = hi & 67108863;
          hi >>>= 26, num.words[i2] = lo, carry = hi;
        }
        if (carry !== 0)
          num.words[num.length++] = carry;
        return num;
      }, BN._prime = function(name) {
        if (primes[name])
          return primes[name];
        var prime;
        if (name === "k256")
          prime = new K256;
        else if (name === "p224")
          prime = new P224;
        else if (name === "p192")
          prime = new P192;
        else if (name === "p25519")
          prime = new P25519;
        else
          throw Error("Unknown prime " + name);
        return primes[name] = prime, prime;
      };
      function Red(m) {
        if (typeof m === "string") {
          var prime = BN._prime(m);
          this.m = prime.p, this.prime = prime;
        } else
          assert(m.gtn(1), "modulus must be greater than 1"), this.m = m, this.prime = null;
      }
      Red.prototype._verify1 = function(a2) {
        assert(a2.negative === 0, "red works only with positives"), assert(a2.red, "red works only with red numbers");
      }, Red.prototype._verify2 = function(a2, b) {
        assert((a2.negative | b.negative) === 0, "red works only with positives"), assert(a2.red && a2.red === b.red, "red works only with red numbers");
      }, Red.prototype.imod = function(a2) {
        if (this.prime)
          return this.prime.ireduce(a2)._forceRed(this);
        return a2.umod(this.m)._forceRed(this);
      }, Red.prototype.neg = function(a2) {
        if (a2.isZero())
          return a2.clone();
        return this.m.sub(a2)._forceRed(this);
      }, Red.prototype.add = function(a2, b) {
        this._verify2(a2, b);
        var res = a2.add(b);
        if (res.cmp(this.m) >= 0)
          res.isub(this.m);
        return res._forceRed(this);
      }, Red.prototype.iadd = function(a2, b) {
        this._verify2(a2, b);
        var res = a2.iadd(b);
        if (res.cmp(this.m) >= 0)
          res.isub(this.m);
        return res;
      }, Red.prototype.sub = function(a2, b) {
        this._verify2(a2, b);
        var res = a2.sub(b);
        if (res.cmpn(0) < 0)
          res.iadd(this.m);
        return res._forceRed(this);
      }, Red.prototype.isub = function(a2, b) {
        this._verify2(a2, b);
        var res = a2.isub(b);
        if (res.cmpn(0) < 0)
          res.iadd(this.m);
        return res;
      }, Red.prototype.shl = function(a2, num) {
        return this._verify1(a2), this.imod(a2.ushln(num));
      }, Red.prototype.imul = function(a2, b) {
        return this._verify2(a2, b), this.imod(a2.imul(b));
      }, Red.prototype.mul = function(a2, b) {
        return this._verify2(a2, b), this.imod(a2.mul(b));
      }, Red.prototype.isqr = function(a2) {
        return this.imul(a2, a2.clone());
      }, Red.prototype.sqr = function(a2) {
        return this.mul(a2, a2);
      }, Red.prototype.sqrt = function(a2) {
        if (a2.isZero())
          return a2.clone();
        var mod3 = this.m.andln(3);
        if (assert(mod3 % 2 === 1), mod3 === 3) {
          var pow = this.m.add(new BN(1)).iushrn(2);
          return this.pow(a2, pow);
        }
        var q = this.m.subn(1), s = 0;
        while (!q.isZero() && q.andln(1) === 0)
          s++, q.iushrn(1);
        assert(!q.isZero());
        var one = new BN(1).toRed(this), nOne = one.redNeg(), lpow = this.m.subn(1).iushrn(1), z = this.m.bitLength();
        z = new BN(2 * z * z).toRed(this);
        while (this.pow(z, lpow).cmp(nOne) !== 0)
          z.redIAdd(nOne);
        var c2 = this.pow(z, q), r2 = this.pow(a2, q.addn(1).iushrn(1)), t2 = this.pow(a2, q), m = s;
        while (t2.cmp(one) !== 0) {
          var tmp = t2;
          for (var i2 = 0;tmp.cmp(one) !== 0; i2++)
            tmp = tmp.redSqr();
          assert(i2 < m);
          var b = this.pow(c2, new BN(1).iushln(m - i2 - 1));
          r2 = r2.redMul(b), c2 = b.redSqr(), t2 = t2.redMul(c2), m = i2;
        }
        return r2;
      }, Red.prototype.invm = function(a2) {
        var inv = a2._invmp(this.m);
        if (inv.negative !== 0)
          return inv.negative = 0, this.imod(inv).redNeg();
        else
          return this.imod(inv);
      }, Red.prototype.pow = function(a2, num) {
        if (num.isZero())
          return new BN(1).toRed(this);
        if (num.cmpn(1) === 0)
          return a2.clone();
        var windowSize = 4, wnd = Array(1 << windowSize);
        wnd[0] = new BN(1).toRed(this), wnd[1] = a2;
        for (var i2 = 2;i2 < wnd.length; i2++)
          wnd[i2] = this.mul(wnd[i2 - 1], a2);
        var res = wnd[0], current = 0, currentLen = 0, start = num.bitLength() % 26;
        if (start === 0)
          start = 26;
        for (i2 = num.length - 1;i2 >= 0; i2--) {
          var word = num.words[i2];
          for (var j = start - 1;j >= 0; j--) {
            var bit = word >> j & 1;
            if (res !== wnd[0])
              res = this.sqr(res);
            if (bit === 0 && current === 0) {
              currentLen = 0;
              continue;
            }
            if (current <<= 1, current |= bit, currentLen++, currentLen !== windowSize && (i2 !== 0 || j !== 0))
              continue;
            res = this.mul(res, wnd[current]), currentLen = 0, current = 0;
          }
          start = 26;
        }
        return res;
      }, Red.prototype.convertTo = function(num) {
        var r2 = num.umod(this.m);
        return r2 === num ? r2.clone() : r2;
      }, Red.prototype.convertFrom = function(num) {
        var res = num.clone();
        return res.red = null, res;
      }, BN.mont = function(num) {
        return new Mont(num);
      };
      function Mont(m) {
        if (Red.call(this, m), this.shift = this.m.bitLength(), this.shift % 26 !== 0)
          this.shift += 26 - this.shift % 26;
        this.r = new BN(1).iushln(this.shift), this.r2 = this.imod(this.r.sqr()), this.rinv = this.r._invmp(this.m), this.minv = this.rinv.mul(this.r).isubn(1).div(this.m), this.minv = this.minv.umod(this.r), this.minv = this.r.sub(this.minv);
      }
      inherits2(Mont, Red), Mont.prototype.convertTo = function(num) {
        return this.imod(num.ushln(this.shift));
      }, Mont.prototype.convertFrom = function(num) {
        var r2 = this.imod(num.mul(this.rinv));
        return r2.red = null, r2;
      }, Mont.prototype.imul = function(a2, b) {
        if (a2.isZero() || b.isZero())
          return a2.words[0] = 0, a2.length = 1, a2;
        var t2 = a2.imul(b), c2 = t2.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), u = t2.isub(c2).iushrn(this.shift), res = u;
        if (u.cmp(this.m) >= 0)
          res = u.isub(this.m);
        else if (u.cmpn(0) < 0)
          res = u.iadd(this.m);
        return res._forceRed(this);
      }, Mont.prototype.mul = function(a2, b) {
        if (a2.isZero() || b.isZero())
          return new BN(0)._forceRed(this);
        var t2 = a2.mul(b), c2 = t2.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), u = t2.isub(c2).iushrn(this.shift), res = u;
        if (u.cmp(this.m) >= 0)
          res = u.isub(this.m);
        else if (u.cmpn(0) < 0)
          res = u.iadd(this.m);
        return res._forceRed(this);
      }, Mont.prototype.invm = function(a2) {
        var res = this.imod(a2._invmp(this.m).mul(this.r2));
        return res._forceRed(this);
      };
    })(typeof module > "u" || module, exports);
  });
  require_api = __commonJS2((exports) => {
    var asn1 = require_asn1(), inherits2 = require_inherits(), api = exports;
    api.define = function(name, body) {
      return new Entity(name, body);
    };
    function Entity(name, body) {
      this.name = name, this.body = body, this.decoders = {}, this.encoders = {};
    }
    Entity.prototype._createNamed = function(base) {
      var named;
      try {
        named = (()=>{throw new Error("Cannot require module "+"vm");})().runInThisContext("(function " + this.name + `(entity) {
  this._initNamed(entity);
})`);
      } catch (e2) {
        named = function(entity) {
          this._initNamed(entity);
        };
      }
      return inherits2(named, base), named.prototype._initNamed = function(entity) {
        base.call(this, entity);
      }, new named(this);
    };
    Entity.prototype._getDecoder = function(enc) {
      if (enc = enc || "der", !this.decoders.hasOwnProperty(enc))
        this.decoders[enc] = this._createNamed(asn1.decoders[enc]);
      return this.decoders[enc];
    };
    Entity.prototype.decode = function(data, enc, options) {
      return this._getDecoder(enc).decode(data, options);
    };
    Entity.prototype._getEncoder = function(enc) {
      if (enc = enc || "der", !this.encoders.hasOwnProperty(enc))
        this.encoders[enc] = this._createNamed(asn1.encoders[enc]);
      return this.encoders[enc];
    };
    Entity.prototype.encode = function(data, enc, reporter) {
      return this._getEncoder(enc).encode(data, reporter);
    };
  });
  require_reporter = __commonJS2((exports) => {
    var inherits2 = require_inherits();
    function Reporter(options) {
      this._reporterState = { obj: null, path: [], options: options || {}, errors: [] };
    }
    exports.Reporter = Reporter;
    Reporter.prototype.isError = function(obj) {
      return obj instanceof ReporterError;
    };
    Reporter.prototype.save = function() {
      var state = this._reporterState;
      return { obj: state.obj, pathLen: state.path.length };
    };
    Reporter.prototype.restore = function(data) {
      var state = this._reporterState;
      state.obj = data.obj, state.path = state.path.slice(0, data.pathLen);
    };
    Reporter.prototype.enterKey = function(key) {
      return this._reporterState.path.push(key);
    };
    Reporter.prototype.exitKey = function(index) {
      var state = this._reporterState;
      state.path = state.path.slice(0, index - 1);
    };
    Reporter.prototype.leaveKey = function(index, key, value) {
      var state = this._reporterState;
      if (this.exitKey(index), state.obj !== null)
        state.obj[key] = value;
    };
    Reporter.prototype.path = function() {
      return this._reporterState.path.join("/");
    };
    Reporter.prototype.enterObject = function() {
      var state = this._reporterState, prev = state.obj;
      return state.obj = {}, prev;
    };
    Reporter.prototype.leaveObject = function(prev) {
      var state = this._reporterState, now = state.obj;
      return state.obj = prev, now;
    };
    Reporter.prototype.error = function(msg) {
      var err, state = this._reporterState, inherited = msg instanceof ReporterError;
      if (inherited)
        err = msg;
      else
        err = new ReporterError(state.path.map(function(elem) {
          return "[" + JSON.stringify(elem) + "]";
        }).join(""), msg.message || msg, msg.stack);
      if (!state.options.partial)
        throw err;
      if (!inherited)
        state.errors.push(err);
      return err;
    };
    Reporter.prototype.wrapResult = function(result) {
      var state = this._reporterState;
      if (!state.options.partial)
        return result;
      return { result: this.isError(result) ? null : result, errors: state.errors };
    };
    function ReporterError(path, msg) {
      this.path = path, this.rethrow(msg);
    }
    inherits2(ReporterError, Error);
    ReporterError.prototype.rethrow = function(msg) {
      if (this.message = msg + " at: " + (this.path || "(shallow)"), Error.captureStackTrace)
        Error.captureStackTrace(this, ReporterError);
      if (!this.stack)
        try {
          throw Error(this.message);
        } catch (e2) {
          this.stack = e2.stack;
        }
      return this;
    };
  });
  require_buffer = __commonJS2((exports) => {
    var inherits2 = require_inherits(), Reporter = require_base2().Reporter, Buffer22 = (init_buffer(), __toCommonJS(exports_buffer)).Buffer;
    function DecoderBuffer(base, options) {
      if (Reporter.call(this, options), !Buffer22.isBuffer(base)) {
        this.error("Input not Buffer");
        return;
      }
      this.base = base, this.offset = 0, this.length = base.length;
    }
    inherits2(DecoderBuffer, Reporter);
    exports.DecoderBuffer = DecoderBuffer;
    DecoderBuffer.prototype.save = function() {
      return { offset: this.offset, reporter: Reporter.prototype.save.call(this) };
    };
    DecoderBuffer.prototype.restore = function(save) {
      var res = new DecoderBuffer(this.base);
      return res.offset = save.offset, res.length = this.offset, this.offset = save.offset, Reporter.prototype.restore.call(this, save.reporter), res;
    };
    DecoderBuffer.prototype.isEmpty = function() {
      return this.offset === this.length;
    };
    DecoderBuffer.prototype.readUInt8 = function(fail) {
      if (this.offset + 1 <= this.length)
        return this.base.readUInt8(this.offset++, true);
      else
        return this.error(fail || "DecoderBuffer overrun");
    };
    DecoderBuffer.prototype.skip = function(bytes, fail) {
      if (!(this.offset + bytes <= this.length))
        return this.error(fail || "DecoderBuffer overrun");
      var res = new DecoderBuffer(this.base);
      return res._reporterState = this._reporterState, res.offset = this.offset, res.length = this.offset + bytes, this.offset += bytes, res;
    };
    DecoderBuffer.prototype.raw = function(save) {
      return this.base.slice(save ? save.offset : this.offset, this.length);
    };
    function EncoderBuffer(value, reporter) {
      if (Array.isArray(value))
        this.length = 0, this.value = value.map(function(item) {
          if (!(item instanceof EncoderBuffer))
            item = new EncoderBuffer(item, reporter);
          return this.length += item.length, item;
        }, this);
      else if (typeof value === "number") {
        if (!(0 <= value && value <= 255))
          return reporter.error("non-byte EncoderBuffer value");
        this.value = value, this.length = 1;
      } else if (typeof value === "string")
        this.value = value, this.length = Buffer22.byteLength(value);
      else if (Buffer22.isBuffer(value))
        this.value = value, this.length = value.length;
      else
        return reporter.error("Unsupported type: " + typeof value);
    }
    exports.EncoderBuffer = EncoderBuffer;
    EncoderBuffer.prototype.join = function(out, offset) {
      if (!out)
        out = new Buffer22(this.length);
      if (!offset)
        offset = 0;
      if (this.length === 0)
        return out;
      if (Array.isArray(this.value))
        this.value.forEach(function(item) {
          item.join(out, offset), offset += item.length;
        });
      else {
        if (typeof this.value === "number")
          out[offset] = this.value;
        else if (typeof this.value === "string")
          out.write(this.value, offset);
        else if (Buffer22.isBuffer(this.value))
          this.value.copy(out, offset);
        offset += this.length;
      }
      return out;
    };
  });
  require_node = __commonJS2((exports, module) => {
    var Reporter = require_base2().Reporter, EncoderBuffer = require_base2().EncoderBuffer, DecoderBuffer = require_base2().DecoderBuffer, assert = require_minimalistic_assert(), tags = ["seq", "seqof", "set", "setof", "objid", "bool", "gentime", "utctime", "null_", "enum", "int", "objDesc", "bitstr", "bmpstr", "charstr", "genstr", "graphstr", "ia5str", "iso646str", "numstr", "octstr", "printstr", "t61str", "unistr", "utf8str", "videostr"], methods = ["key", "obj", "use", "optional", "explicit", "implicit", "def", "choice", "any", "contains"].concat(tags), overrided = ["_peekTag", "_decodeTag", "_use", "_decodeStr", "_decodeObjid", "_decodeTime", "_decodeNull", "_decodeInt", "_decodeBool", "_decodeList", "_encodeComposite", "_encodeStr", "_encodeObjid", "_encodeTime", "_encodeNull", "_encodeInt", "_encodeBool"];
    function Node(enc, parent) {
      var state = {};
      if (this._baseState = state, state.enc = enc, state.parent = parent || null, state.children = null, state.tag = null, state.args = null, state.reverseArgs = null, state.choice = null, state.optional = false, state.any = false, state.obj = false, state.use = null, state.useDecoder = null, state.key = null, state.default = null, state.explicit = null, state.implicit = null, state.contains = null, !state.parent)
        state.children = [], this._wrap();
    }
    module.exports = Node;
    var stateProps = ["enc", "parent", "children", "tag", "args", "reverseArgs", "choice", "optional", "any", "obj", "use", "alteredUse", "key", "default", "explicit", "implicit", "contains"];
    Node.prototype.clone = function() {
      var state = this._baseState, cstate = {};
      stateProps.forEach(function(prop) {
        cstate[prop] = state[prop];
      });
      var res = new this.constructor(cstate.parent);
      return res._baseState = cstate, res;
    };
    Node.prototype._wrap = function() {
      var state = this._baseState;
      methods.forEach(function(method) {
        this[method] = function() {
          var clone = new this.constructor(this);
          return state.children.push(clone), clone[method].apply(clone, arguments);
        };
      }, this);
    };
    Node.prototype._init = function(body) {
      var state = this._baseState;
      assert(state.parent === null), body.call(this), state.children = state.children.filter(function(child) {
        return child._baseState.parent === this;
      }, this), assert.equal(state.children.length, 1, "Root node can have only one child");
    };
    Node.prototype._useArgs = function(args) {
      var state = this._baseState, children = args.filter(function(arg) {
        return arg instanceof this.constructor;
      }, this);
      if (args = args.filter(function(arg) {
        return !(arg instanceof this.constructor);
      }, this), children.length !== 0)
        assert(state.children === null), state.children = children, children.forEach(function(child) {
          child._baseState.parent = this;
        }, this);
      if (args.length !== 0)
        assert(state.args === null), state.args = args, state.reverseArgs = args.map(function(arg) {
          if (typeof arg !== "object" || arg.constructor !== Object)
            return arg;
          var res = {};
          return Object.keys(arg).forEach(function(key) {
            if (key == (key | 0))
              key |= 0;
            var value = arg[key];
            res[value] = key;
          }), res;
        });
    };
    overrided.forEach(function(method) {
      Node.prototype[method] = function() {
        var state = this._baseState;
        throw Error(method + " not implemented for encoding: " + state.enc);
      };
    });
    tags.forEach(function(tag) {
      Node.prototype[tag] = function() {
        var state = this._baseState, args = Array.prototype.slice.call(arguments);
        return assert(state.tag === null), state.tag = tag, this._useArgs(args), this;
      };
    });
    Node.prototype.use = function(item) {
      assert(item);
      var state = this._baseState;
      return assert(state.use === null), state.use = item, this;
    };
    Node.prototype.optional = function() {
      var state = this._baseState;
      return state.optional = true, this;
    };
    Node.prototype.def = function(val) {
      var state = this._baseState;
      return assert(state.default === null), state.default = val, state.optional = true, this;
    };
    Node.prototype.explicit = function(num) {
      var state = this._baseState;
      return assert(state.explicit === null && state.implicit === null), state.explicit = num, this;
    };
    Node.prototype.implicit = function(num) {
      var state = this._baseState;
      return assert(state.explicit === null && state.implicit === null), state.implicit = num, this;
    };
    Node.prototype.obj = function() {
      var state = this._baseState, args = Array.prototype.slice.call(arguments);
      if (state.obj = true, args.length !== 0)
        this._useArgs(args);
      return this;
    };
    Node.prototype.key = function(newKey) {
      var state = this._baseState;
      return assert(state.key === null), state.key = newKey, this;
    };
    Node.prototype.any = function() {
      var state = this._baseState;
      return state.any = true, this;
    };
    Node.prototype.choice = function(obj) {
      var state = this._baseState;
      return assert(state.choice === null), state.choice = obj, this._useArgs(Object.keys(obj).map(function(key) {
        return obj[key];
      })), this;
    };
    Node.prototype.contains = function(item) {
      var state = this._baseState;
      return assert(state.use === null), state.contains = item, this;
    };
    Node.prototype._decode = function(input, options) {
      var state = this._baseState;
      if (state.parent === null)
        return input.wrapResult(state.children[0]._decode(input, options));
      var result = state.default, present = true, prevKey = null;
      if (state.key !== null)
        prevKey = input.enterKey(state.key);
      if (state.optional) {
        var tag = null;
        if (state.explicit !== null)
          tag = state.explicit;
        else if (state.implicit !== null)
          tag = state.implicit;
        else if (state.tag !== null)
          tag = state.tag;
        if (tag === null && !state.any) {
          var save = input.save();
          try {
            if (state.choice === null)
              this._decodeGeneric(state.tag, input, options);
            else
              this._decodeChoice(input, options);
            present = true;
          } catch (e2) {
            present = false;
          }
          input.restore(save);
        } else if (present = this._peekTag(input, tag, state.any), input.isError(present))
          return present;
      }
      var prevObj;
      if (state.obj && present)
        prevObj = input.enterObject();
      if (present) {
        if (state.explicit !== null) {
          var explicit = this._decodeTag(input, state.explicit);
          if (input.isError(explicit))
            return explicit;
          input = explicit;
        }
        var start = input.offset;
        if (state.use === null && state.choice === null) {
          if (state.any)
            var save = input.save();
          var body = this._decodeTag(input, state.implicit !== null ? state.implicit : state.tag, state.any);
          if (input.isError(body))
            return body;
          if (state.any)
            result = input.raw(save);
          else
            input = body;
        }
        if (options && options.track && state.tag !== null)
          options.track(input.path(), start, input.length, "tagged");
        if (options && options.track && state.tag !== null)
          options.track(input.path(), input.offset, input.length, "content");
        if (state.any)
          result = result;
        else if (state.choice === null)
          result = this._decodeGeneric(state.tag, input, options);
        else
          result = this._decodeChoice(input, options);
        if (input.isError(result))
          return result;
        if (!state.any && state.choice === null && state.children !== null)
          state.children.forEach(function(child) {
            child._decode(input, options);
          });
        if (state.contains && (state.tag === "octstr" || state.tag === "bitstr")) {
          var data = new DecoderBuffer(result);
          result = this._getUse(state.contains, input._reporterState.obj)._decode(data, options);
        }
      }
      if (state.obj && present)
        result = input.leaveObject(prevObj);
      if (state.key !== null && (result !== null || present === true))
        input.leaveKey(prevKey, state.key, result);
      else if (prevKey !== null)
        input.exitKey(prevKey);
      return result;
    };
    Node.prototype._decodeGeneric = function(tag, input, options) {
      var state = this._baseState;
      if (tag === "seq" || tag === "set")
        return null;
      if (tag === "seqof" || tag === "setof")
        return this._decodeList(input, tag, state.args[0], options);
      else if (/str$/.test(tag))
        return this._decodeStr(input, tag, options);
      else if (tag === "objid" && state.args)
        return this._decodeObjid(input, state.args[0], state.args[1], options);
      else if (tag === "objid")
        return this._decodeObjid(input, null, null, options);
      else if (tag === "gentime" || tag === "utctime")
        return this._decodeTime(input, tag, options);
      else if (tag === "null_")
        return this._decodeNull(input, options);
      else if (tag === "bool")
        return this._decodeBool(input, options);
      else if (tag === "objDesc")
        return this._decodeStr(input, tag, options);
      else if (tag === "int" || tag === "enum")
        return this._decodeInt(input, state.args && state.args[0], options);
      if (state.use !== null)
        return this._getUse(state.use, input._reporterState.obj)._decode(input, options);
      else
        return input.error("unknown tag: " + tag);
    };
    Node.prototype._getUse = function(entity, obj) {
      var state = this._baseState;
      if (state.useDecoder = this._use(entity, obj), assert(state.useDecoder._baseState.parent === null), state.useDecoder = state.useDecoder._baseState.children[0], state.implicit !== state.useDecoder._baseState.implicit)
        state.useDecoder = state.useDecoder.clone(), state.useDecoder._baseState.implicit = state.implicit;
      return state.useDecoder;
    };
    Node.prototype._decodeChoice = function(input, options) {
      var state = this._baseState, result = null, match = false;
      if (Object.keys(state.choice).some(function(key) {
        var save = input.save(), node = state.choice[key];
        try {
          var value = node._decode(input, options);
          if (input.isError(value))
            return false;
          result = { type: key, value }, match = true;
        } catch (e2) {
          return input.restore(save), false;
        }
        return true;
      }, this), !match)
        return input.error("Choice not matched");
      return result;
    };
    Node.prototype._createEncoderBuffer = function(data) {
      return new EncoderBuffer(data, this.reporter);
    };
    Node.prototype._encode = function(data, reporter, parent) {
      var state = this._baseState;
      if (state.default !== null && state.default === data)
        return;
      var result = this._encodeValue(data, reporter, parent);
      if (result === undefined)
        return;
      if (this._skipDefault(result, reporter, parent))
        return;
      return result;
    };
    Node.prototype._encodeValue = function(data, reporter, parent) {
      var state = this._baseState;
      if (state.parent === null)
        return state.children[0]._encode(data, reporter || new Reporter);
      var result = null;
      if (this.reporter = reporter, state.optional && data === undefined)
        if (state.default !== null)
          data = state.default;
        else
          return;
      var content = null, primitive = false;
      if (state.any)
        result = this._createEncoderBuffer(data);
      else if (state.choice)
        result = this._encodeChoice(data, reporter);
      else if (state.contains)
        content = this._getUse(state.contains, parent)._encode(data, reporter), primitive = true;
      else if (state.children)
        content = state.children.map(function(child2) {
          if (child2._baseState.tag === "null_")
            return child2._encode(null, reporter, data);
          if (child2._baseState.key === null)
            return reporter.error("Child should have a key");
          var prevKey = reporter.enterKey(child2._baseState.key);
          if (typeof data !== "object")
            return reporter.error("Child expected, but input is not object");
          var res = child2._encode(data[child2._baseState.key], reporter, data);
          return reporter.leaveKey(prevKey), res;
        }, this).filter(function(child2) {
          return child2;
        }), content = this._createEncoderBuffer(content);
      else if (state.tag === "seqof" || state.tag === "setof") {
        if (!(state.args && state.args.length === 1))
          return reporter.error("Too many args for : " + state.tag);
        if (!Array.isArray(data))
          return reporter.error("seqof/setof, but data is not Array");
        var child = this.clone();
        child._baseState.implicit = null, content = this._createEncoderBuffer(data.map(function(item) {
          var state2 = this._baseState;
          return this._getUse(state2.args[0], data)._encode(item, reporter);
        }, child));
      } else if (state.use !== null)
        result = this._getUse(state.use, parent)._encode(data, reporter);
      else
        content = this._encodePrimitive(state.tag, data), primitive = true;
      var result;
      if (!state.any && state.choice === null) {
        var tag = state.implicit !== null ? state.implicit : state.tag, cls = state.implicit === null ? "universal" : "context";
        if (tag === null) {
          if (state.use === null)
            reporter.error("Tag could be omitted only for .use()");
        } else if (state.use === null)
          result = this._encodeComposite(tag, primitive, cls, content);
      }
      if (state.explicit !== null)
        result = this._encodeComposite(state.explicit, false, "context", result);
      return result;
    };
    Node.prototype._encodeChoice = function(data, reporter) {
      var state = this._baseState, node = state.choice[data.type];
      if (!node)
        assert(false, data.type + " not found in " + JSON.stringify(Object.keys(state.choice)));
      return node._encode(data.value, reporter);
    };
    Node.prototype._encodePrimitive = function(tag, data) {
      var state = this._baseState;
      if (/str$/.test(tag))
        return this._encodeStr(data, tag);
      else if (tag === "objid" && state.args)
        return this._encodeObjid(data, state.reverseArgs[0], state.args[1]);
      else if (tag === "objid")
        return this._encodeObjid(data, null, null);
      else if (tag === "gentime" || tag === "utctime")
        return this._encodeTime(data, tag);
      else if (tag === "null_")
        return this._encodeNull();
      else if (tag === "int" || tag === "enum")
        return this._encodeInt(data, state.args && state.reverseArgs[0]);
      else if (tag === "bool")
        return this._encodeBool(data);
      else if (tag === "objDesc")
        return this._encodeStr(data, tag);
      else
        throw Error("Unsupported tag: " + tag);
    };
    Node.prototype._isNumstr = function(str) {
      return /^[0-9 ]*$/.test(str);
    };
    Node.prototype._isPrintstr = function(str) {
      return /^[A-Za-z0-9 '\(\)\+,\-\.\/:=\?]*$/.test(str);
    };
  });
  require_base2 = __commonJS2((exports) => {
    var base = exports;
    base.Reporter = require_reporter().Reporter;
    base.DecoderBuffer = require_buffer().DecoderBuffer;
    base.EncoderBuffer = require_buffer().EncoderBuffer;
    base.Node = require_node();
  });
  require_der = __commonJS2((exports) => {
    var constants2 = require_constants();
    exports.tagClass = { 0: "universal", 1: "application", 2: "context", 3: "private" };
    exports.tagClassByName = constants2._reverse(exports.tagClass);
    exports.tag = { 0: "end", 1: "bool", 2: "int", 3: "bitstr", 4: "octstr", 5: "null_", 6: "objid", 7: "objDesc", 8: "external", 9: "real", 10: "enum", 11: "embed", 12: "utf8str", 13: "relativeOid", 16: "seq", 17: "set", 18: "numstr", 19: "printstr", 20: "t61str", 21: "videostr", 22: "ia5str", 23: "utctime", 24: "gentime", 25: "graphstr", 26: "iso646str", 27: "genstr", 28: "unistr", 29: "charstr", 30: "bmpstr" };
    exports.tagByName = constants2._reverse(exports.tag);
  });
  require_constants = __commonJS2((exports) => {
    var constants2 = exports;
    constants2._reverse = function(map) {
      var res = {};
      return Object.keys(map).forEach(function(key) {
        if ((key | 0) == key)
          key = key | 0;
        var value = map[key];
        res[value] = key;
      }), res;
    };
    constants2.der = require_der();
  });
  require_der2 = __commonJS2((exports, module) => {
    var inherits2 = require_inherits(), asn1 = require_asn1(), base = asn1.base, bignum = asn1.bignum, der = asn1.constants.der;
    function DERDecoder(entity) {
      this.enc = "der", this.name = entity.name, this.entity = entity, this.tree = new DERNode, this.tree._init(entity.body);
    }
    module.exports = DERDecoder;
    DERDecoder.prototype.decode = function(data, options) {
      if (!(data instanceof base.DecoderBuffer))
        data = new base.DecoderBuffer(data, options);
      return this.tree._decode(data, options);
    };
    function DERNode(parent) {
      base.Node.call(this, "der", parent);
    }
    inherits2(DERNode, base.Node);
    DERNode.prototype._peekTag = function(buffer, tag, any) {
      if (buffer.isEmpty())
        return false;
      var state = buffer.save(), decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"');
      if (buffer.isError(decodedTag))
        return decodedTag;
      return buffer.restore(state), decodedTag.tag === tag || decodedTag.tagStr === tag || decodedTag.tagStr + "of" === tag || any;
    };
    DERNode.prototype._decodeTag = function(buffer, tag, any) {
      var decodedTag = derDecodeTag(buffer, 'Failed to decode tag of "' + tag + '"');
      if (buffer.isError(decodedTag))
        return decodedTag;
      var len2 = derDecodeLen(buffer, decodedTag.primitive, 'Failed to get length of "' + tag + '"');
      if (buffer.isError(len2))
        return len2;
      if (!any && decodedTag.tag !== tag && decodedTag.tagStr !== tag && decodedTag.tagStr + "of" !== tag)
        return buffer.error('Failed to match tag: "' + tag + '"');
      if (decodedTag.primitive || len2 !== null)
        return buffer.skip(len2, 'Failed to match body of: "' + tag + '"');
      var state = buffer.save(), res = this._skipUntilEnd(buffer, 'Failed to skip indefinite length body: "' + this.tag + '"');
      if (buffer.isError(res))
        return res;
      return len2 = buffer.offset - state.offset, buffer.restore(state), buffer.skip(len2, 'Failed to match body of: "' + tag + '"');
    };
    DERNode.prototype._skipUntilEnd = function(buffer, fail) {
      while (true) {
        var tag = derDecodeTag(buffer, fail);
        if (buffer.isError(tag))
          return tag;
        var len2 = derDecodeLen(buffer, tag.primitive, fail);
        if (buffer.isError(len2))
          return len2;
        var res;
        if (tag.primitive || len2 !== null)
          res = buffer.skip(len2);
        else
          res = this._skipUntilEnd(buffer, fail);
        if (buffer.isError(res))
          return res;
        if (tag.tagStr === "end")
          break;
      }
    };
    DERNode.prototype._decodeList = function(buffer, tag, decoder, options) {
      var result = [];
      while (!buffer.isEmpty()) {
        var possibleEnd = this._peekTag(buffer, "end");
        if (buffer.isError(possibleEnd))
          return possibleEnd;
        var res = decoder.decode(buffer, "der", options);
        if (buffer.isError(res) && possibleEnd)
          break;
        result.push(res);
      }
      return result;
    };
    DERNode.prototype._decodeStr = function(buffer, tag) {
      if (tag === "bitstr") {
        var unused = buffer.readUInt8();
        if (buffer.isError(unused))
          return unused;
        return { unused, data: buffer.raw() };
      } else if (tag === "bmpstr") {
        var raw = buffer.raw();
        if (raw.length % 2 === 1)
          return buffer.error("Decoding of string type: bmpstr length mismatch");
        var str = "";
        for (var i2 = 0;i2 < raw.length / 2; i2++)
          str += String.fromCharCode(raw.readUInt16BE(i2 * 2));
        return str;
      } else if (tag === "numstr") {
        var numstr = buffer.raw().toString("ascii");
        if (!this._isNumstr(numstr))
          return buffer.error("Decoding of string type: numstr unsupported characters");
        return numstr;
      } else if (tag === "octstr")
        return buffer.raw();
      else if (tag === "objDesc")
        return buffer.raw();
      else if (tag === "printstr") {
        var printstr = buffer.raw().toString("ascii");
        if (!this._isPrintstr(printstr))
          return buffer.error("Decoding of string type: printstr unsupported characters");
        return printstr;
      } else if (/str$/.test(tag))
        return buffer.raw().toString();
      else
        return buffer.error("Decoding of string type: " + tag + " unsupported");
    };
    DERNode.prototype._decodeObjid = function(buffer, values, relative) {
      var result, identifiers = [], ident = 0;
      while (!buffer.isEmpty()) {
        var subident = buffer.readUInt8();
        if (ident <<= 7, ident |= subident & 127, (subident & 128) === 0)
          identifiers.push(ident), ident = 0;
      }
      if (subident & 128)
        identifiers.push(ident);
      var first = identifiers[0] / 40 | 0, second = identifiers[0] % 40;
      if (relative)
        result = identifiers;
      else
        result = [first, second].concat(identifiers.slice(1));
      if (values) {
        var tmp = values[result.join(" ")];
        if (tmp === undefined)
          tmp = values[result.join(".")];
        if (tmp !== undefined)
          result = tmp;
      }
      return result;
    };
    DERNode.prototype._decodeTime = function(buffer, tag) {
      var str = buffer.raw().toString();
      if (tag === "gentime")
        var year = str.slice(0, 4) | 0, mon = str.slice(4, 6) | 0, day = str.slice(6, 8) | 0, hour = str.slice(8, 10) | 0, min = str.slice(10, 12) | 0, sec = str.slice(12, 14) | 0;
      else if (tag === "utctime") {
        var year = str.slice(0, 2) | 0, mon = str.slice(2, 4) | 0, day = str.slice(4, 6) | 0, hour = str.slice(6, 8) | 0, min = str.slice(8, 10) | 0, sec = str.slice(10, 12) | 0;
        if (year < 70)
          year = 2000 + year;
        else
          year = 1900 + year;
      } else
        return buffer.error("Decoding " + tag + " time is not supported yet");
      return Date.UTC(year, mon - 1, day, hour, min, sec, 0);
    };
    DERNode.prototype._decodeNull = function(buffer) {
      return null;
    };
    DERNode.prototype._decodeBool = function(buffer) {
      var res = buffer.readUInt8();
      if (buffer.isError(res))
        return res;
      else
        return res !== 0;
    };
    DERNode.prototype._decodeInt = function(buffer, values) {
      var raw = buffer.raw(), res = new bignum(raw);
      if (values)
        res = values[res.toString(10)] || res;
      return res;
    };
    DERNode.prototype._use = function(entity, obj) {
      if (typeof entity === "function")
        entity = entity(obj);
      return entity._getDecoder("der").tree;
    };
    function derDecodeTag(buf, fail) {
      var tag = buf.readUInt8(fail);
      if (buf.isError(tag))
        return tag;
      var cls = der.tagClass[tag >> 6], primitive = (tag & 32) === 0;
      if ((tag & 31) === 31) {
        var oct = tag;
        tag = 0;
        while ((oct & 128) === 128) {
          if (oct = buf.readUInt8(fail), buf.isError(oct))
            return oct;
          tag <<= 7, tag |= oct & 127;
        }
      } else
        tag &= 31;
      var tagStr = der.tag[tag];
      return { cls, primitive, tag, tagStr };
    }
    function derDecodeLen(buf, primitive, fail) {
      var len2 = buf.readUInt8(fail);
      if (buf.isError(len2))
        return len2;
      if (!primitive && len2 === 128)
        return null;
      if ((len2 & 128) === 0)
        return len2;
      var num = len2 & 127;
      if (num > 4)
        return buf.error("length octect is too long");
      len2 = 0;
      for (var i2 = 0;i2 < num; i2++) {
        len2 <<= 8;
        var j = buf.readUInt8(fail);
        if (buf.isError(j))
          return j;
        len2 |= j;
      }
      return len2;
    }
  });
  require_pem = __commonJS2((exports, module) => {
    var inherits2 = require_inherits(), Buffer22 = (init_buffer(), __toCommonJS(exports_buffer)).Buffer, DERDecoder = require_der2();
    function PEMDecoder(entity) {
      DERDecoder.call(this, entity), this.enc = "pem";
    }
    inherits2(PEMDecoder, DERDecoder);
    module.exports = PEMDecoder;
    PEMDecoder.prototype.decode = function(data, options) {
      var lines = data.toString().split(/[\r\n]+/g), label = options.label.toUpperCase(), re = /^-----(BEGIN|END) ([^-]+)-----$/, start = -1, end = -1;
      for (var i2 = 0;i2 < lines.length; i2++) {
        var match = lines[i2].match(re);
        if (match === null)
          continue;
        if (match[2] !== label)
          continue;
        if (start === -1) {
          if (match[1] !== "BEGIN")
            break;
          start = i2;
        } else {
          if (match[1] !== "END")
            break;
          end = i2;
          break;
        }
      }
      if (start === -1 || end === -1)
        throw Error("PEM section not found for: " + label);
      var base64 = lines.slice(start + 1, end).join("");
      base64.replace(/[^a-z0-9\+\/=]+/gi, "");
      var input = new Buffer22(base64, "base64");
      return DERDecoder.prototype.decode.call(this, input, options);
    };
  });
  require_decoders = __commonJS2((exports) => {
    var decoders = exports;
    decoders.der = require_der2();
    decoders.pem = require_pem();
  });
  require_der3 = __commonJS2((exports, module) => {
    var inherits2 = require_inherits(), Buffer22 = (init_buffer(), __toCommonJS(exports_buffer)).Buffer, asn1 = require_asn1(), base = asn1.base, der = asn1.constants.der;
    function DEREncoder(entity) {
      this.enc = "der", this.name = entity.name, this.entity = entity, this.tree = new DERNode, this.tree._init(entity.body);
    }
    module.exports = DEREncoder;
    DEREncoder.prototype.encode = function(data, reporter) {
      return this.tree._encode(data, reporter).join();
    };
    function DERNode(parent) {
      base.Node.call(this, "der", parent);
    }
    inherits2(DERNode, base.Node);
    DERNode.prototype._encodeComposite = function(tag, primitive, cls, content) {
      var encodedTag = encodeTag(tag, primitive, cls, this.reporter);
      if (content.length < 128) {
        var header = new Buffer22(2);
        return header[0] = encodedTag, header[1] = content.length, this._createEncoderBuffer([header, content]);
      }
      var lenOctets = 1;
      for (var i2 = content.length;i2 >= 256; i2 >>= 8)
        lenOctets++;
      var header = new Buffer22(2 + lenOctets);
      header[0] = encodedTag, header[1] = 128 | lenOctets;
      for (var i2 = 1 + lenOctets, j = content.length;j > 0; i2--, j >>= 8)
        header[i2] = j & 255;
      return this._createEncoderBuffer([header, content]);
    };
    DERNode.prototype._encodeStr = function(str, tag) {
      if (tag === "bitstr")
        return this._createEncoderBuffer([str.unused | 0, str.data]);
      else if (tag === "bmpstr") {
        var buf = new Buffer22(str.length * 2);
        for (var i2 = 0;i2 < str.length; i2++)
          buf.writeUInt16BE(str.charCodeAt(i2), i2 * 2);
        return this._createEncoderBuffer(buf);
      } else if (tag === "numstr") {
        if (!this._isNumstr(str))
          return this.reporter.error("Encoding of string type: numstr supports only digits and space");
        return this._createEncoderBuffer(str);
      } else if (tag === "printstr") {
        if (!this._isPrintstr(str))
          return this.reporter.error("Encoding of string type: printstr supports only latin upper and lower case letters, digits, space, apostrophe, left and rigth parenthesis, plus sign, comma, hyphen, dot, slash, colon, equal sign, question mark");
        return this._createEncoderBuffer(str);
      } else if (/str$/.test(tag))
        return this._createEncoderBuffer(str);
      else if (tag === "objDesc")
        return this._createEncoderBuffer(str);
      else
        return this.reporter.error("Encoding of string type: " + tag + " unsupported");
    };
    DERNode.prototype._encodeObjid = function(id, values, relative) {
      if (typeof id === "string") {
        if (!values)
          return this.reporter.error("string objid given, but no values map found");
        if (!values.hasOwnProperty(id))
          return this.reporter.error("objid not found in values map");
        id = values[id].split(/[\s\.]+/g);
        for (var i2 = 0;i2 < id.length; i2++)
          id[i2] |= 0;
      } else if (Array.isArray(id)) {
        id = id.slice();
        for (var i2 = 0;i2 < id.length; i2++)
          id[i2] |= 0;
      }
      if (!Array.isArray(id))
        return this.reporter.error("objid() should be either array or string, got: " + JSON.stringify(id));
      if (!relative) {
        if (id[1] >= 40)
          return this.reporter.error("Second objid identifier OOB");
        id.splice(0, 2, id[0] * 40 + id[1]);
      }
      var size = 0;
      for (var i2 = 0;i2 < id.length; i2++) {
        var ident = id[i2];
        for (size++;ident >= 128; ident >>= 7)
          size++;
      }
      var objid = new Buffer22(size), offset = objid.length - 1;
      for (var i2 = id.length - 1;i2 >= 0; i2--) {
        var ident = id[i2];
        objid[offset--] = ident & 127;
        while ((ident >>= 7) > 0)
          objid[offset--] = 128 | ident & 127;
      }
      return this._createEncoderBuffer(objid);
    };
    function two(num) {
      if (num < 10)
        return "0" + num;
      else
        return num;
    }
    DERNode.prototype._encodeTime = function(time, tag) {
      var str, date = new Date(time);
      if (tag === "gentime")
        str = [two(date.getFullYear()), two(date.getUTCMonth() + 1), two(date.getUTCDate()), two(date.getUTCHours()), two(date.getUTCMinutes()), two(date.getUTCSeconds()), "Z"].join("");
      else if (tag === "utctime")
        str = [two(date.getFullYear() % 100), two(date.getUTCMonth() + 1), two(date.getUTCDate()), two(date.getUTCHours()), two(date.getUTCMinutes()), two(date.getUTCSeconds()), "Z"].join("");
      else
        this.reporter.error("Encoding " + tag + " time is not supported yet");
      return this._encodeStr(str, "octstr");
    };
    DERNode.prototype._encodeNull = function() {
      return this._createEncoderBuffer("");
    };
    DERNode.prototype._encodeInt = function(num, values) {
      if (typeof num === "string") {
        if (!values)
          return this.reporter.error("String int or enum given, but no values map");
        if (!values.hasOwnProperty(num))
          return this.reporter.error("Values map doesn't contain: " + JSON.stringify(num));
        num = values[num];
      }
      if (typeof num !== "number" && !Buffer22.isBuffer(num)) {
        var numArray = num.toArray();
        if (!num.sign && numArray[0] & 128)
          numArray.unshift(0);
        num = new Buffer22(numArray);
      }
      if (Buffer22.isBuffer(num)) {
        var size = num.length;
        if (num.length === 0)
          size++;
        var out = new Buffer22(size);
        if (num.copy(out), num.length === 0)
          out[0] = 0;
        return this._createEncoderBuffer(out);
      }
      if (num < 128)
        return this._createEncoderBuffer(num);
      if (num < 256)
        return this._createEncoderBuffer([0, num]);
      var size = 1;
      for (var i2 = num;i2 >= 256; i2 >>= 8)
        size++;
      var out = Array(size);
      for (var i2 = out.length - 1;i2 >= 0; i2--)
        out[i2] = num & 255, num >>= 8;
      if (out[0] & 128)
        out.unshift(0);
      return this._createEncoderBuffer(new Buffer22(out));
    };
    DERNode.prototype._encodeBool = function(value) {
      return this._createEncoderBuffer(value ? 255 : 0);
    };
    DERNode.prototype._use = function(entity, obj) {
      if (typeof entity === "function")
        entity = entity(obj);
      return entity._getEncoder("der").tree;
    };
    DERNode.prototype._skipDefault = function(dataBuffer, reporter, parent) {
      var state = this._baseState, i2;
      if (state.default === null)
        return false;
      var data = dataBuffer.join();
      if (state.defaultBuffer === undefined)
        state.defaultBuffer = this._encodeValue(state.default, reporter, parent).join();
      if (data.length !== state.defaultBuffer.length)
        return false;
      for (i2 = 0;i2 < data.length; i2++)
        if (data[i2] !== state.defaultBuffer[i2])
          return false;
      return true;
    };
    function encodeTag(tag, primitive, cls, reporter) {
      var res;
      if (tag === "seqof")
        tag = "seq";
      else if (tag === "setof")
        tag = "set";
      if (der.tagByName.hasOwnProperty(tag))
        res = der.tagByName[tag];
      else if (typeof tag === "number" && (tag | 0) === tag)
        res = tag;
      else
        return reporter.error("Unknown tag: " + tag);
      if (res >= 31)
        return reporter.error("Multi-octet tag encoding unsupported");
      if (!primitive)
        res |= 32;
      return res |= der.tagClassByName[cls || "universal"] << 6, res;
    }
  });
  require_pem2 = __commonJS2((exports, module) => {
    var inherits2 = require_inherits(), DEREncoder = require_der3();
    function PEMEncoder(entity) {
      DEREncoder.call(this, entity), this.enc = "pem";
    }
    inherits2(PEMEncoder, DEREncoder);
    module.exports = PEMEncoder;
    PEMEncoder.prototype.encode = function(data, options) {
      var buf = DEREncoder.prototype.encode.call(this, data), p2 = buf.toString("base64"), out = ["-----BEGIN " + options.label + "-----"];
      for (var i2 = 0;i2 < p2.length; i2 += 64)
        out.push(p2.slice(i2, i2 + 64));
      return out.push("-----END " + options.label + "-----"), out.join(`
`);
    };
  });
  require_encoders = __commonJS2((exports) => {
    var encoders = exports;
    encoders.der = require_der3();
    encoders.pem = require_pem2();
  });
  require_asn1 = __commonJS2((exports) => {
    var asn1 = exports;
    asn1.bignum = require_bn3();
    asn1.define = require_api().define;
    asn1.base = require_base2();
    asn1.constants = require_constants();
    asn1.decoders = require_decoders();
    asn1.encoders = require_encoders();
  });
  require_certificate = __commonJS2((exports, module) => {
    var asn = require_asn1(), Time = asn.define("Time", function() {
      this.choice({ utcTime: this.utctime(), generalTime: this.gentime() });
    }), AttributeTypeValue = asn.define("AttributeTypeValue", function() {
      this.seq().obj(this.key("type").objid(), this.key("value").any());
    }), AlgorithmIdentifier = asn.define("AlgorithmIdentifier", function() {
      this.seq().obj(this.key("algorithm").objid(), this.key("parameters").optional(), this.key("curve").objid().optional());
    }), SubjectPublicKeyInfo = asn.define("SubjectPublicKeyInfo", function() {
      this.seq().obj(this.key("algorithm").use(AlgorithmIdentifier), this.key("subjectPublicKey").bitstr());
    }), RelativeDistinguishedName = asn.define("RelativeDistinguishedName", function() {
      this.setof(AttributeTypeValue);
    }), RDNSequence = asn.define("RDNSequence", function() {
      this.seqof(RelativeDistinguishedName);
    }), Name = asn.define("Name", function() {
      this.choice({ rdnSequence: this.use(RDNSequence) });
    }), Validity = asn.define("Validity", function() {
      this.seq().obj(this.key("notBefore").use(Time), this.key("notAfter").use(Time));
    }), Extension = asn.define("Extension", function() {
      this.seq().obj(this.key("extnID").objid(), this.key("critical").bool().def(false), this.key("extnValue").octstr());
    }), TBSCertificate = asn.define("TBSCertificate", function() {
      this.seq().obj(this.key("version").explicit(0).int().optional(), this.key("serialNumber").int(), this.key("signature").use(AlgorithmIdentifier), this.key("issuer").use(Name), this.key("validity").use(Validity), this.key("subject").use(Name), this.key("subjectPublicKeyInfo").use(SubjectPublicKeyInfo), this.key("issuerUniqueID").implicit(1).bitstr().optional(), this.key("subjectUniqueID").implicit(2).bitstr().optional(), this.key("extensions").explicit(3).seqof(Extension).optional());
    }), X509Certificate = asn.define("X509Certificate", function() {
      this.seq().obj(this.key("tbsCertificate").use(TBSCertificate), this.key("signatureAlgorithm").use(AlgorithmIdentifier), this.key("signatureValue").bitstr());
    });
    module.exports = X509Certificate;
  });
  require_asn12 = __commonJS2((exports) => {
    var asn1 = require_asn1();
    exports.certificate = require_certificate();
    var RSAPrivateKey = asn1.define("RSAPrivateKey", function() {
      this.seq().obj(this.key("version").int(), this.key("modulus").int(), this.key("publicExponent").int(), this.key("privateExponent").int(), this.key("prime1").int(), this.key("prime2").int(), this.key("exponent1").int(), this.key("exponent2").int(), this.key("coefficient").int());
    });
    exports.RSAPrivateKey = RSAPrivateKey;
    var RSAPublicKey = asn1.define("RSAPublicKey", function() {
      this.seq().obj(this.key("modulus").int(), this.key("publicExponent").int());
    });
    exports.RSAPublicKey = RSAPublicKey;
    var AlgorithmIdentifier = asn1.define("AlgorithmIdentifier", function() {
      this.seq().obj(this.key("algorithm").objid(), this.key("none").null_().optional(), this.key("curve").objid().optional(), this.key("params").seq().obj(this.key("p").int(), this.key("q").int(), this.key("g").int()).optional());
    }), PublicKey = asn1.define("SubjectPublicKeyInfo", function() {
      this.seq().obj(this.key("algorithm").use(AlgorithmIdentifier), this.key("subjectPublicKey").bitstr());
    });
    exports.PublicKey = PublicKey;
    var PrivateKeyInfo = asn1.define("PrivateKeyInfo", function() {
      this.seq().obj(this.key("version").int(), this.key("algorithm").use(AlgorithmIdentifier), this.key("subjectPrivateKey").octstr());
    });
    exports.PrivateKey = PrivateKeyInfo;
    var EncryptedPrivateKeyInfo = asn1.define("EncryptedPrivateKeyInfo", function() {
      this.seq().obj(this.key("algorithm").seq().obj(this.key("id").objid(), this.key("decrypt").seq().obj(this.key("kde").seq().obj(this.key("id").objid(), this.key("kdeparams").seq().obj(this.key("salt").octstr(), this.key("iters").int())), this.key("cipher").seq().obj(this.key("algo").objid(), this.key("iv").octstr()))), this.key("subjectPrivateKey").octstr());
    });
    exports.EncryptedPrivateKey = EncryptedPrivateKeyInfo;
    var DSAPrivateKey = asn1.define("DSAPrivateKey", function() {
      this.seq().obj(this.key("version").int(), this.key("p").int(), this.key("q").int(), this.key("g").int(), this.key("pub_key").int(), this.key("priv_key").int());
    });
    exports.DSAPrivateKey = DSAPrivateKey;
    exports.DSAparam = asn1.define("DSAparam", function() {
      this.int();
    });
    var ECParameters = asn1.define("ECParameters", function() {
      this.choice({ namedCurve: this.objid() });
    }), ECPrivateKey = asn1.define("ECPrivateKey", function() {
      this.seq().obj(this.key("version").int(), this.key("privateKey").octstr(), this.key("parameters").optional().explicit(0).use(ECParameters), this.key("publicKey").optional().explicit(1).bitstr());
    });
    exports.ECPrivateKey = ECPrivateKey;
    exports.signature = asn1.define("signature", function() {
      this.seq().obj(this.key("r").int(), this.key("s").int());
    });
  });
  require_aesid = __commonJS2((exports, module) => {
    module.exports = { "2.16.840.1.101.3.4.1.1": "aes-128-ecb", "2.16.840.1.101.3.4.1.2": "aes-128-cbc", "2.16.840.1.101.3.4.1.3": "aes-128-ofb", "2.16.840.1.101.3.4.1.4": "aes-128-cfb", "2.16.840.1.101.3.4.1.21": "aes-192-ecb", "2.16.840.1.101.3.4.1.22": "aes-192-cbc", "2.16.840.1.101.3.4.1.23": "aes-192-ofb", "2.16.840.1.101.3.4.1.24": "aes-192-cfb", "2.16.840.1.101.3.4.1.41": "aes-256-ecb", "2.16.840.1.101.3.4.1.42": "aes-256-cbc", "2.16.840.1.101.3.4.1.43": "aes-256-ofb", "2.16.840.1.101.3.4.1.44": "aes-256-cfb" };
  });
  require_hash_base = __commonJS2((exports, module) => {
    var Buffer22 = require_safe_buffer().Buffer, Transform = require_stream().Transform, inherits2 = require_inherits();
    function HashBase(blockSize) {
      Transform.call(this), this._block = Buffer22.allocUnsafe(blockSize), this._blockSize = blockSize, this._blockOffset = 0, this._length = [0, 0, 0, 0], this._finalized = false;
    }
    inherits2(HashBase, Transform);
    HashBase.prototype._transform = function(chunk, encoding, callback) {
      var error = null;
      try {
        this.update(chunk, encoding);
      } catch (err) {
        error = err;
      }
      callback(error);
    };
    HashBase.prototype._flush = function(callback) {
      var error = null;
      try {
        this.push(this.digest());
      } catch (err) {
        error = err;
      }
      callback(error);
    };
    var useUint8Array = typeof Uint8Array < "u", useArrayBuffer = typeof ArrayBuffer < "u" && typeof Uint8Array < "u" && ArrayBuffer.isView && (Buffer22.prototype instanceof Uint8Array || Buffer22.TYPED_ARRAY_SUPPORT);
    function toBuffer(data, encoding) {
      if (data instanceof Buffer22)
        return data;
      if (typeof data === "string")
        return Buffer22.from(data, encoding);
      if (useArrayBuffer && ArrayBuffer.isView(data)) {
        if (data.byteLength === 0)
          return Buffer22.alloc(0);
        var res = Buffer22.from(data.buffer, data.byteOffset, data.byteLength);
        if (res.byteLength === data.byteLength)
          return res;
      }
      if (useUint8Array && data instanceof Uint8Array)
        return Buffer22.from(data);
      if (Buffer22.isBuffer(data) && data.constructor && typeof data.constructor.isBuffer === "function" && data.constructor.isBuffer(data))
        return Buffer22.from(data);
      throw TypeError('The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView.');
    }
    HashBase.prototype.update = function(data, encoding) {
      if (this._finalized)
        throw Error("Digest already called");
      data = toBuffer(data, encoding);
      var block = this._block, offset = 0;
      while (this._blockOffset + data.length - offset >= this._blockSize) {
        for (var i2 = this._blockOffset;i2 < this._blockSize; )
          block[i2++] = data[offset++];
        this._update(), this._blockOffset = 0;
      }
      while (offset < data.length)
        block[this._blockOffset++] = data[offset++];
      for (var j = 0, carry = data.length * 8;carry > 0; ++j)
        if (this._length[j] += carry, carry = this._length[j] / 4294967296 | 0, carry > 0)
          this._length[j] -= 4294967296 * carry;
      return this;
    };
    HashBase.prototype._update = function() {
      throw Error("_update is not implemented");
    };
    HashBase.prototype.digest = function(encoding) {
      if (this._finalized)
        throw Error("Digest already called");
      this._finalized = true;
      var digest = this._digest();
      if (encoding !== undefined)
        digest = digest.toString(encoding);
      this._block.fill(0), this._blockOffset = 0;
      for (var i2 = 0;i2 < 4; ++i2)
        this._length[i2] = 0;
      return digest;
    };
    HashBase.prototype._digest = function() {
      throw Error("_digest is not implemented");
    };
    module.exports = HashBase;
  });
  require_md5 = __commonJS2((exports, module) => {
    var inherits2 = require_inherits(), HashBase = require_hash_base(), Buffer22 = require_safe_buffer().Buffer, ARRAY16 = Array(16);
    function MD5() {
      HashBase.call(this, 64), this._a = 1732584193, this._b = 4023233417, this._c = 2562383102, this._d = 271733878;
    }
    inherits2(MD5, HashBase);
    MD5.prototype._update = function() {
      var M = ARRAY16;
      for (var i2 = 0;i2 < 16; ++i2)
        M[i2] = this._block.readInt32LE(i2 * 4);
      var a2 = this._a, b = this._b, c2 = this._c, d = this._d;
      a2 = fnF(a2, b, c2, d, M[0], 3614090360, 7), d = fnF(d, a2, b, c2, M[1], 3905402710, 12), c2 = fnF(c2, d, a2, b, M[2], 606105819, 17), b = fnF(b, c2, d, a2, M[3], 3250441966, 22), a2 = fnF(a2, b, c2, d, M[4], 4118548399, 7), d = fnF(d, a2, b, c2, M[5], 1200080426, 12), c2 = fnF(c2, d, a2, b, M[6], 2821735955, 17), b = fnF(b, c2, d, a2, M[7], 4249261313, 22), a2 = fnF(a2, b, c2, d, M[8], 1770035416, 7), d = fnF(d, a2, b, c2, M[9], 2336552879, 12), c2 = fnF(c2, d, a2, b, M[10], 4294925233, 17), b = fnF(b, c2, d, a2, M[11], 2304563134, 22), a2 = fnF(a2, b, c2, d, M[12], 1804603682, 7), d = fnF(d, a2, b, c2, M[13], 4254626195, 12), c2 = fnF(c2, d, a2, b, M[14], 2792965006, 17), b = fnF(b, c2, d, a2, M[15], 1236535329, 22), a2 = fnG(a2, b, c2, d, M[1], 4129170786, 5), d = fnG(d, a2, b, c2, M[6], 3225465664, 9), c2 = fnG(c2, d, a2, b, M[11], 643717713, 14), b = fnG(b, c2, d, a2, M[0], 3921069994, 20), a2 = fnG(a2, b, c2, d, M[5], 3593408605, 5), d = fnG(d, a2, b, c2, M[10], 38016083, 9), c2 = fnG(c2, d, a2, b, M[15], 3634488961, 14), b = fnG(b, c2, d, a2, M[4], 3889429448, 20), a2 = fnG(a2, b, c2, d, M[9], 568446438, 5), d = fnG(d, a2, b, c2, M[14], 3275163606, 9), c2 = fnG(c2, d, a2, b, M[3], 4107603335, 14), b = fnG(b, c2, d, a2, M[8], 1163531501, 20), a2 = fnG(a2, b, c2, d, M[13], 2850285829, 5), d = fnG(d, a2, b, c2, M[2], 4243563512, 9), c2 = fnG(c2, d, a2, b, M[7], 1735328473, 14), b = fnG(b, c2, d, a2, M[12], 2368359562, 20), a2 = fnH(a2, b, c2, d, M[5], 4294588738, 4), d = fnH(d, a2, b, c2, M[8], 2272392833, 11), c2 = fnH(c2, d, a2, b, M[11], 1839030562, 16), b = fnH(b, c2, d, a2, M[14], 4259657740, 23), a2 = fnH(a2, b, c2, d, M[1], 2763975236, 4), d = fnH(d, a2, b, c2, M[4], 1272893353, 11), c2 = fnH(c2, d, a2, b, M[7], 4139469664, 16), b = fnH(b, c2, d, a2, M[10], 3200236656, 23), a2 = fnH(a2, b, c2, d, M[13], 681279174, 4), d = fnH(d, a2, b, c2, M[0], 3936430074, 11), c2 = fnH(c2, d, a2, b, M[3], 3572445317, 16), b = fnH(b, c2, d, a2, M[6], 76029189, 23), a2 = fnH(a2, b, c2, d, M[9], 3654602809, 4), d = fnH(d, a2, b, c2, M[12], 3873151461, 11), c2 = fnH(c2, d, a2, b, M[15], 530742520, 16), b = fnH(b, c2, d, a2, M[2], 3299628645, 23), a2 = fnI(a2, b, c2, d, M[0], 4096336452, 6), d = fnI(d, a2, b, c2, M[7], 1126891415, 10), c2 = fnI(c2, d, a2, b, M[14], 2878612391, 15), b = fnI(b, c2, d, a2, M[5], 4237533241, 21), a2 = fnI(a2, b, c2, d, M[12], 1700485571, 6), d = fnI(d, a2, b, c2, M[3], 2399980690, 10), c2 = fnI(c2, d, a2, b, M[10], 4293915773, 15), b = fnI(b, c2, d, a2, M[1], 2240044497, 21), a2 = fnI(a2, b, c2, d, M[8], 1873313359, 6), d = fnI(d, a2, b, c2, M[15], 4264355552, 10), c2 = fnI(c2, d, a2, b, M[6], 2734768916, 15), b = fnI(b, c2, d, a2, M[13], 1309151649, 21), a2 = fnI(a2, b, c2, d, M[4], 4149444226, 6), d = fnI(d, a2, b, c2, M[11], 3174756917, 10), c2 = fnI(c2, d, a2, b, M[2], 718787259, 15), b = fnI(b, c2, d, a2, M[9], 3951481745, 21), this._a = this._a + a2 | 0, this._b = this._b + b | 0, this._c = this._c + c2 | 0, this._d = this._d + d | 0;
    };
    MD5.prototype._digest = function() {
      if (this._block[this._blockOffset++] = 128, this._blockOffset > 56)
        this._block.fill(0, this._blockOffset, 64), this._update(), this._blockOffset = 0;
      this._block.fill(0, this._blockOffset, 56), this._block.writeUInt32LE(this._length[0], 56), this._block.writeUInt32LE(this._length[1], 60), this._update();
      var buffer = Buffer22.allocUnsafe(16);
      return buffer.writeInt32LE(this._a, 0), buffer.writeInt32LE(this._b, 4), buffer.writeInt32LE(this._c, 8), buffer.writeInt32LE(this._d, 12), buffer;
    };
    function rotl(x, n2) {
      return x << n2 | x >>> 32 - n2;
    }
    function fnF(a2, b, c2, d, m, k, s) {
      return rotl(a2 + (b & c2 | ~b & d) + m + k | 0, s) + b | 0;
    }
    function fnG(a2, b, c2, d, m, k, s) {
      return rotl(a2 + (b & d | c2 & ~d) + m + k | 0, s) + b | 0;
    }
    function fnH(a2, b, c2, d, m, k, s) {
      return rotl(a2 + (b ^ c2 ^ d) + m + k | 0, s) + b | 0;
    }
    function fnI(a2, b, c2, d, m, k, s) {
      return rotl(a2 + (c2 ^ (b | ~d)) + m + k | 0, s) + b | 0;
    }
    module.exports = MD5;
  });
  require_evp_bytestokey = __commonJS2((exports, module) => {
    var Buffer22 = require_safe_buffer().Buffer, MD5 = require_md5();
    function EVP_BytesToKey(password, salt, keyBits, ivLen) {
      if (!Buffer22.isBuffer(password))
        password = Buffer22.from(password, "binary");
      if (salt) {
        if (!Buffer22.isBuffer(salt))
          salt = Buffer22.from(salt, "binary");
        if (salt.length !== 8)
          throw RangeError("salt should be Buffer with 8 byte length");
      }
      var keyLen = keyBits / 8, key = Buffer22.alloc(keyLen), iv = Buffer22.alloc(ivLen || 0), tmp = Buffer22.alloc(0);
      while (keyLen > 0 || ivLen > 0) {
        var hash = new MD5;
        if (hash.update(tmp), hash.update(password), salt)
          hash.update(salt);
        tmp = hash.digest();
        var used = 0;
        if (keyLen > 0) {
          var keyStart = key.length - keyLen;
          used = Math.min(keyLen, tmp.length), tmp.copy(key, keyStart, 0, used), keyLen -= used;
        }
        if (used < tmp.length && ivLen > 0) {
          var ivStart = iv.length - ivLen, length = Math.min(ivLen, tmp.length - used);
          tmp.copy(iv, ivStart, used, used + length), ivLen -= length;
        }
      }
      return tmp.fill(0), { key, iv };
    }
    module.exports = EVP_BytesToKey;
  });
  require_browserify_aes = __commonJS2((exports) => {
    var crypto2 = (init_crypto(), __toCommonJS(exports_crypto));
    exports.createCipher = exports.Cipher = crypto2.createCipher;
    exports.createCipheriv = exports.Cipheriv = crypto2.createCipheriv;
    exports.createDecipher = exports.Decipher = crypto2.createDecipher;
    exports.createDecipheriv = exports.Decipheriv = crypto2.createDecipheriv;
    exports.listCiphers = exports.getCiphers = crypto2.getCiphers;
  });
  require_fixProc = __commonJS2((exports, module) => {
    var findProc = /Proc-Type: 4,ENCRYPTED[\n\r]+DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)[\n\r]+([0-9A-z\n\r+/=]+)[\n\r]+/m, startRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----/m, fullRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----([0-9A-z\n\r+/=]+)-----END \1-----$/m, evp = require_evp_bytestokey(), ciphers = require_browserify_aes(), Buffer22 = require_safe_buffer().Buffer;
    module.exports = function(okey, password) {
      var key = okey.toString(), match = key.match(findProc), decrypted;
      if (!match) {
        var match2 = key.match(fullRegex);
        decrypted = Buffer22.from(match2[2].replace(/[\r\n]/g, ""), "base64");
      } else {
        var suite = "aes" + match[1], iv = Buffer22.from(match[2], "hex"), cipherText = Buffer22.from(match[3].replace(/[\r\n]/g, ""), "base64"), cipherKey = evp(password, iv.slice(0, 8), parseInt(match[1], 10)).key, out = [], cipher = ciphers.createDecipheriv(suite, cipherKey, iv);
        out.push(cipher.update(cipherText)), out.push(cipher.final()), decrypted = Buffer22.concat(out);
      }
      var tag = key.match(startRegex)[1];
      return { tag, data: decrypted };
    };
  });
  require_parse_asn1 = __commonJS2((exports, module) => {
    var asn1 = require_asn12(), aesid = require_aesid(), fixProc = require_fixProc(), ciphers = require_browserify_aes(), pbkdf2Sync = require_pbkdf2().pbkdf2Sync, Buffer22 = require_safe_buffer().Buffer;
    function decrypt(data, password) {
      var salt = data.algorithm.decrypt.kde.kdeparams.salt, iters = parseInt(data.algorithm.decrypt.kde.kdeparams.iters.toString(), 10), algo = aesid[data.algorithm.decrypt.cipher.algo.join(".")], iv = data.algorithm.decrypt.cipher.iv, cipherText = data.subjectPrivateKey, keylen = parseInt(algo.split("-")[1], 10) / 8, key = pbkdf2Sync(password, salt, iters, keylen, "sha1"), cipher = ciphers.createDecipheriv(algo, key, iv), out = [];
      return out.push(cipher.update(cipherText)), out.push(cipher.final()), Buffer22.concat(out);
    }
    function parseKeys(buffer) {
      var password;
      if (typeof buffer === "object" && !Buffer22.isBuffer(buffer))
        password = buffer.passphrase, buffer = buffer.key;
      if (typeof buffer === "string")
        buffer = Buffer22.from(buffer);
      var stripped = fixProc(buffer, password), type = stripped.tag, data = stripped.data, subtype, ndata;
      switch (type) {
        case "CERTIFICATE":
          ndata = asn1.certificate.decode(data, "der").tbsCertificate.subjectPublicKeyInfo;
        case "PUBLIC KEY":
          if (!ndata)
            ndata = asn1.PublicKey.decode(data, "der");
          switch (subtype = ndata.algorithm.algorithm.join("."), subtype) {
            case "1.2.840.113549.1.1.1":
              return asn1.RSAPublicKey.decode(ndata.subjectPublicKey.data, "der");
            case "1.2.840.10045.2.1":
              return ndata.subjectPrivateKey = ndata.subjectPublicKey, { type: "ec", data: ndata };
            case "1.2.840.10040.4.1":
              return ndata.algorithm.params.pub_key = asn1.DSAparam.decode(ndata.subjectPublicKey.data, "der"), { type: "dsa", data: ndata.algorithm.params };
            default:
              throw Error("unknown key id " + subtype);
          }
        case "ENCRYPTED PRIVATE KEY":
          data = asn1.EncryptedPrivateKey.decode(data, "der"), data = decrypt(data, password);
        case "PRIVATE KEY":
          switch (ndata = asn1.PrivateKey.decode(data, "der"), subtype = ndata.algorithm.algorithm.join("."), subtype) {
            case "1.2.840.113549.1.1.1":
              return asn1.RSAPrivateKey.decode(ndata.subjectPrivateKey, "der");
            case "1.2.840.10045.2.1":
              return { curve: ndata.algorithm.curve, privateKey: asn1.ECPrivateKey.decode(ndata.subjectPrivateKey, "der").privateKey };
            case "1.2.840.10040.4.1":
              return ndata.algorithm.params.priv_key = asn1.DSAparam.decode(ndata.subjectPrivateKey, "der"), { type: "dsa", params: ndata.algorithm.params };
            default:
              throw Error("unknown key id " + subtype);
          }
        case "RSA PUBLIC KEY":
          return asn1.RSAPublicKey.decode(data, "der");
        case "RSA PRIVATE KEY":
          return asn1.RSAPrivateKey.decode(data, "der");
        case "DSA PRIVATE KEY":
          return { type: "dsa", params: asn1.DSAPrivateKey.decode(data, "der") };
        case "EC PRIVATE KEY":
          return data = asn1.ECPrivateKey.decode(data, "der"), { curve: data.parameters.value, privateKey: data.privateKey };
        default:
          throw Error("unknown key type " + type);
      }
    }
    parseKeys.signature = asn1.signature;
    module.exports = parseKeys;
  });
  require_mgf = __commonJS2((exports, module) => {
    var createHash = require_create_hash(), Buffer22 = require_safe_buffer().Buffer;
    module.exports = function(seed, len2) {
      var t2 = Buffer22.alloc(0), i2 = 0, c2;
      while (t2.length < len2)
        c2 = i2ops(i2++), t2 = Buffer22.concat([t2, createHash("sha1").update(seed).update(c2).digest()]);
      return t2.slice(0, len2);
    };
    function i2ops(c2) {
      var out = Buffer22.allocUnsafe(4);
      return out.writeUInt32BE(c2, 0), out;
    }
  });
  require_xor = __commonJS2((exports, module) => {
    module.exports = function(a2, b) {
      var len2 = a2.length, i2 = -1;
      while (++i2 < len2)
        a2[i2] ^= b[i2];
      return a2;
    };
  });
  require_bn4 = __commonJS2((exports, module) => {
    (function(module2, exports2) {
      function assert(val, msg) {
        if (!val)
          throw Error(msg || "Assertion failed");
      }
      function inherits2(ctor, superCtor) {
        ctor.super_ = superCtor;
        var TempCtor = function() {};
        TempCtor.prototype = superCtor.prototype, ctor.prototype = new TempCtor, ctor.prototype.constructor = ctor;
      }
      function BN(number, base, endian) {
        if (BN.isBN(number))
          return number;
        if (this.negative = 0, this.words = null, this.length = 0, this.red = null, number !== null) {
          if (base === "le" || base === "be")
            endian = base, base = 10;
          this._init(number || 0, base || 10, endian || "be");
        }
      }
      if (typeof module2 === "object")
        module2.exports = BN;
      else
        exports2.BN = BN;
      BN.BN = BN, BN.wordSize = 26;
      var Buffer22;
      try {
        if (typeof window < "u" && typeof window.Buffer < "u")
          Buffer22 = window.Buffer;
        else
          Buffer22 = (init_buffer(), __toCommonJS(exports_buffer)).Buffer;
      } catch (e2) {}
      BN.isBN = function(num) {
        if (num instanceof BN)
          return true;
        return num !== null && typeof num === "object" && num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
      }, BN.max = function(left, right) {
        if (left.cmp(right) > 0)
          return left;
        return right;
      }, BN.min = function(left, right) {
        if (left.cmp(right) < 0)
          return left;
        return right;
      }, BN.prototype._init = function(number, base, endian) {
        if (typeof number === "number")
          return this._initNumber(number, base, endian);
        if (typeof number === "object")
          return this._initArray(number, base, endian);
        if (base === "hex")
          base = 16;
        assert(base === (base | 0) && base >= 2 && base <= 36), number = number.toString().replace(/\s+/g, "");
        var start = 0;
        if (number[0] === "-")
          start++, this.negative = 1;
        if (start < number.length) {
          if (base === 16)
            this._parseHex(number, start, endian);
          else if (this._parseBase(number, base, start), endian === "le")
            this._initArray(this.toArray(), base, endian);
        }
      }, BN.prototype._initNumber = function(number, base, endian) {
        if (number < 0)
          this.negative = 1, number = -number;
        if (number < 67108864)
          this.words = [number & 67108863], this.length = 1;
        else if (number < 4503599627370496)
          this.words = [number & 67108863, number / 67108864 & 67108863], this.length = 2;
        else
          assert(number < 9007199254740992), this.words = [number & 67108863, number / 67108864 & 67108863, 1], this.length = 3;
        if (endian !== "le")
          return;
        this._initArray(this.toArray(), base, endian);
      }, BN.prototype._initArray = function(number, base, endian) {
        if (assert(typeof number.length === "number"), number.length <= 0)
          return this.words = [0], this.length = 1, this;
        this.length = Math.ceil(number.length / 3), this.words = Array(this.length);
        for (var i2 = 0;i2 < this.length; i2++)
          this.words[i2] = 0;
        var j, w, off = 0;
        if (endian === "be") {
          for (i2 = number.length - 1, j = 0;i2 >= 0; i2 -= 3)
            if (w = number[i2] | number[i2 - 1] << 8 | number[i2 - 2] << 16, this.words[j] |= w << off & 67108863, this.words[j + 1] = w >>> 26 - off & 67108863, off += 24, off >= 26)
              off -= 26, j++;
        } else if (endian === "le") {
          for (i2 = 0, j = 0;i2 < number.length; i2 += 3)
            if (w = number[i2] | number[i2 + 1] << 8 | number[i2 + 2] << 16, this.words[j] |= w << off & 67108863, this.words[j + 1] = w >>> 26 - off & 67108863, off += 24, off >= 26)
              off -= 26, j++;
        }
        return this.strip();
      };
      function parseHex4Bits(string, index) {
        var c2 = string.charCodeAt(index);
        if (c2 >= 65 && c2 <= 70)
          return c2 - 55;
        else if (c2 >= 97 && c2 <= 102)
          return c2 - 87;
        else
          return c2 - 48 & 15;
      }
      function parseHexByte(string, lowerBound, index) {
        var r2 = parseHex4Bits(string, index);
        if (index - 1 >= lowerBound)
          r2 |= parseHex4Bits(string, index - 1) << 4;
        return r2;
      }
      BN.prototype._parseHex = function(number, start, endian) {
        this.length = Math.ceil((number.length - start) / 6), this.words = Array(this.length);
        for (var i2 = 0;i2 < this.length; i2++)
          this.words[i2] = 0;
        var off = 0, j = 0, w;
        if (endian === "be")
          for (i2 = number.length - 1;i2 >= start; i2 -= 2)
            if (w = parseHexByte(number, start, i2) << off, this.words[j] |= w & 67108863, off >= 18)
              off -= 18, j += 1, this.words[j] |= w >>> 26;
            else
              off += 8;
        else {
          var parseLength = number.length - start;
          for (i2 = parseLength % 2 === 0 ? start + 1 : start;i2 < number.length; i2 += 2)
            if (w = parseHexByte(number, start, i2) << off, this.words[j] |= w & 67108863, off >= 18)
              off -= 18, j += 1, this.words[j] |= w >>> 26;
            else
              off += 8;
        }
        this.strip();
      };
      function parseBase(str, start, end, mul) {
        var r2 = 0, len2 = Math.min(str.length, end);
        for (var i2 = start;i2 < len2; i2++) {
          var c2 = str.charCodeAt(i2) - 48;
          if (r2 *= mul, c2 >= 49)
            r2 += c2 - 49 + 10;
          else if (c2 >= 17)
            r2 += c2 - 17 + 10;
          else
            r2 += c2;
        }
        return r2;
      }
      BN.prototype._parseBase = function(number, base, start) {
        this.words = [0], this.length = 1;
        for (var limbLen = 0, limbPow = 1;limbPow <= 67108863; limbPow *= base)
          limbLen++;
        limbLen--, limbPow = limbPow / base | 0;
        var total = number.length - start, mod = total % limbLen, end = Math.min(total, total - mod) + start, word = 0;
        for (var i2 = start;i2 < end; i2 += limbLen)
          if (word = parseBase(number, i2, i2 + limbLen, base), this.imuln(limbPow), this.words[0] + word < 67108864)
            this.words[0] += word;
          else
            this._iaddn(word);
        if (mod !== 0) {
          var pow = 1;
          word = parseBase(number, i2, number.length, base);
          for (i2 = 0;i2 < mod; i2++)
            pow *= base;
          if (this.imuln(pow), this.words[0] + word < 67108864)
            this.words[0] += word;
          else
            this._iaddn(word);
        }
        this.strip();
      }, BN.prototype.copy = function(dest) {
        dest.words = Array(this.length);
        for (var i2 = 0;i2 < this.length; i2++)
          dest.words[i2] = this.words[i2];
        dest.length = this.length, dest.negative = this.negative, dest.red = this.red;
      }, BN.prototype.clone = function() {
        var r2 = new BN(null);
        return this.copy(r2), r2;
      }, BN.prototype._expand = function(size) {
        while (this.length < size)
          this.words[this.length++] = 0;
        return this;
      }, BN.prototype.strip = function() {
        while (this.length > 1 && this.words[this.length - 1] === 0)
          this.length--;
        return this._normSign();
      }, BN.prototype._normSign = function() {
        if (this.length === 1 && this.words[0] === 0)
          this.negative = 0;
        return this;
      }, BN.prototype.inspect = function() {
        return (this.red ? "<BN-R: " : "<BN: ") + this.toString(16) + ">";
      };
      var zeros = ["", "0", "00", "000", "0000", "00000", "000000", "0000000", "00000000", "000000000", "0000000000", "00000000000", "000000000000", "0000000000000", "00000000000000", "000000000000000", "0000000000000000", "00000000000000000", "000000000000000000", "0000000000000000000", "00000000000000000000", "000000000000000000000", "0000000000000000000000", "00000000000000000000000", "000000000000000000000000", "0000000000000000000000000"], groupSizes = [0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5], groupBases = [0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 1e7, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176];
      if (BN.prototype.toString = function(base, padding) {
        base = base || 10, padding = padding | 0 || 1;
        var out;
        if (base === 16 || base === "hex") {
          out = "";
          var off = 0, carry = 0;
          for (var i2 = 0;i2 < this.length; i2++) {
            var w = this.words[i2], word = ((w << off | carry) & 16777215).toString(16);
            if (carry = w >>> 24 - off & 16777215, off += 2, off >= 26)
              off -= 26, i2--;
            if (carry !== 0 || i2 !== this.length - 1)
              out = zeros[6 - word.length] + word + out;
            else
              out = word + out;
          }
          if (carry !== 0)
            out = carry.toString(16) + out;
          while (out.length % padding !== 0)
            out = "0" + out;
          if (this.negative !== 0)
            out = "-" + out;
          return out;
        }
        if (base === (base | 0) && base >= 2 && base <= 36) {
          var groupSize = groupSizes[base], groupBase = groupBases[base];
          out = "";
          var c2 = this.clone();
          c2.negative = 0;
          while (!c2.isZero()) {
            var r2 = c2.modn(groupBase).toString(base);
            if (c2 = c2.idivn(groupBase), !c2.isZero())
              out = zeros[groupSize - r2.length] + r2 + out;
            else
              out = r2 + out;
          }
          if (this.isZero())
            out = "0" + out;
          while (out.length % padding !== 0)
            out = "0" + out;
          if (this.negative !== 0)
            out = "-" + out;
          return out;
        }
        assert(false, "Base should be between 2 and 36");
      }, BN.prototype.toNumber = function() {
        var ret = this.words[0];
        if (this.length === 2)
          ret += this.words[1] * 67108864;
        else if (this.length === 3 && this.words[2] === 1)
          ret += 4503599627370496 + this.words[1] * 67108864;
        else if (this.length > 2)
          assert(false, "Number can only safely store up to 53 bits");
        return this.negative !== 0 ? -ret : ret;
      }, BN.prototype.toJSON = function() {
        return this.toString(16);
      }, BN.prototype.toBuffer = function(endian, length) {
        return assert(typeof Buffer22 < "u"), this.toArrayLike(Buffer22, endian, length);
      }, BN.prototype.toArray = function(endian, length) {
        return this.toArrayLike(Array, endian, length);
      }, BN.prototype.toArrayLike = function(ArrayType, endian, length) {
        var byteLength2 = this.byteLength(), reqLength = length || Math.max(1, byteLength2);
        assert(byteLength2 <= reqLength, "byte array longer than desired length"), assert(reqLength > 0, "Requested array length <= 0"), this.strip();
        var littleEndian = endian === "le", res = new ArrayType(reqLength), b, i2, q = this.clone();
        if (!littleEndian) {
          for (i2 = 0;i2 < reqLength - byteLength2; i2++)
            res[i2] = 0;
          for (i2 = 0;!q.isZero(); i2++)
            b = q.andln(255), q.iushrn(8), res[reqLength - i2 - 1] = b;
        } else {
          for (i2 = 0;!q.isZero(); i2++)
            b = q.andln(255), q.iushrn(8), res[i2] = b;
          for (;i2 < reqLength; i2++)
            res[i2] = 0;
        }
        return res;
      }, Math.clz32)
        BN.prototype._countBits = function(w) {
          return 32 - Math.clz32(w);
        };
      else
        BN.prototype._countBits = function(w) {
          var t2 = w, r2 = 0;
          if (t2 >= 4096)
            r2 += 13, t2 >>>= 13;
          if (t2 >= 64)
            r2 += 7, t2 >>>= 7;
          if (t2 >= 8)
            r2 += 4, t2 >>>= 4;
          if (t2 >= 2)
            r2 += 2, t2 >>>= 2;
          return r2 + t2;
        };
      BN.prototype._zeroBits = function(w) {
        if (w === 0)
          return 26;
        var t2 = w, r2 = 0;
        if ((t2 & 8191) === 0)
          r2 += 13, t2 >>>= 13;
        if ((t2 & 127) === 0)
          r2 += 7, t2 >>>= 7;
        if ((t2 & 15) === 0)
          r2 += 4, t2 >>>= 4;
        if ((t2 & 3) === 0)
          r2 += 2, t2 >>>= 2;
        if ((t2 & 1) === 0)
          r2++;
        return r2;
      }, BN.prototype.bitLength = function() {
        var w = this.words[this.length - 1], hi = this._countBits(w);
        return (this.length - 1) * 26 + hi;
      };
      function toBitArray(num) {
        var w = Array(num.bitLength());
        for (var bit = 0;bit < w.length; bit++) {
          var off = bit / 26 | 0, wbit = bit % 26;
          w[bit] = (num.words[off] & 1 << wbit) >>> wbit;
        }
        return w;
      }
      BN.prototype.zeroBits = function() {
        if (this.isZero())
          return 0;
        var r2 = 0;
        for (var i2 = 0;i2 < this.length; i2++) {
          var b = this._zeroBits(this.words[i2]);
          if (r2 += b, b !== 26)
            break;
        }
        return r2;
      }, BN.prototype.byteLength = function() {
        return Math.ceil(this.bitLength() / 8);
      }, BN.prototype.toTwos = function(width) {
        if (this.negative !== 0)
          return this.abs().inotn(width).iaddn(1);
        return this.clone();
      }, BN.prototype.fromTwos = function(width) {
        if (this.testn(width - 1))
          return this.notn(width).iaddn(1).ineg();
        return this.clone();
      }, BN.prototype.isNeg = function() {
        return this.negative !== 0;
      }, BN.prototype.neg = function() {
        return this.clone().ineg();
      }, BN.prototype.ineg = function() {
        if (!this.isZero())
          this.negative ^= 1;
        return this;
      }, BN.prototype.iuor = function(num) {
        while (this.length < num.length)
          this.words[this.length++] = 0;
        for (var i2 = 0;i2 < num.length; i2++)
          this.words[i2] = this.words[i2] | num.words[i2];
        return this.strip();
      }, BN.prototype.ior = function(num) {
        return assert((this.negative | num.negative) === 0), this.iuor(num);
      }, BN.prototype.or = function(num) {
        if (this.length > num.length)
          return this.clone().ior(num);
        return num.clone().ior(this);
      }, BN.prototype.uor = function(num) {
        if (this.length > num.length)
          return this.clone().iuor(num);
        return num.clone().iuor(this);
      }, BN.prototype.iuand = function(num) {
        var b;
        if (this.length > num.length)
          b = num;
        else
          b = this;
        for (var i2 = 0;i2 < b.length; i2++)
          this.words[i2] = this.words[i2] & num.words[i2];
        return this.length = b.length, this.strip();
      }, BN.prototype.iand = function(num) {
        return assert((this.negative | num.negative) === 0), this.iuand(num);
      }, BN.prototype.and = function(num) {
        if (this.length > num.length)
          return this.clone().iand(num);
        return num.clone().iand(this);
      }, BN.prototype.uand = function(num) {
        if (this.length > num.length)
          return this.clone().iuand(num);
        return num.clone().iuand(this);
      }, BN.prototype.iuxor = function(num) {
        var a2, b;
        if (this.length > num.length)
          a2 = this, b = num;
        else
          a2 = num, b = this;
        for (var i2 = 0;i2 < b.length; i2++)
          this.words[i2] = a2.words[i2] ^ b.words[i2];
        if (this !== a2)
          for (;i2 < a2.length; i2++)
            this.words[i2] = a2.words[i2];
        return this.length = a2.length, this.strip();
      }, BN.prototype.ixor = function(num) {
        return assert((this.negative | num.negative) === 0), this.iuxor(num);
      }, BN.prototype.xor = function(num) {
        if (this.length > num.length)
          return this.clone().ixor(num);
        return num.clone().ixor(this);
      }, BN.prototype.uxor = function(num) {
        if (this.length > num.length)
          return this.clone().iuxor(num);
        return num.clone().iuxor(this);
      }, BN.prototype.inotn = function(width) {
        assert(typeof width === "number" && width >= 0);
        var bytesNeeded = Math.ceil(width / 26) | 0, bitsLeft = width % 26;
        if (this._expand(bytesNeeded), bitsLeft > 0)
          bytesNeeded--;
        for (var i2 = 0;i2 < bytesNeeded; i2++)
          this.words[i2] = ~this.words[i2] & 67108863;
        if (bitsLeft > 0)
          this.words[i2] = ~this.words[i2] & 67108863 >> 26 - bitsLeft;
        return this.strip();
      }, BN.prototype.notn = function(width) {
        return this.clone().inotn(width);
      }, BN.prototype.setn = function(bit, val) {
        assert(typeof bit === "number" && bit >= 0);
        var off = bit / 26 | 0, wbit = bit % 26;
        if (this._expand(off + 1), val)
          this.words[off] = this.words[off] | 1 << wbit;
        else
          this.words[off] = this.words[off] & ~(1 << wbit);
        return this.strip();
      }, BN.prototype.iadd = function(num) {
        var r2;
        if (this.negative !== 0 && num.negative === 0)
          return this.negative = 0, r2 = this.isub(num), this.negative ^= 1, this._normSign();
        else if (this.negative === 0 && num.negative !== 0)
          return num.negative = 0, r2 = this.isub(num), num.negative = 1, r2._normSign();
        var a2, b;
        if (this.length > num.length)
          a2 = this, b = num;
        else
          a2 = num, b = this;
        var carry = 0;
        for (var i2 = 0;i2 < b.length; i2++)
          r2 = (a2.words[i2] | 0) + (b.words[i2] | 0) + carry, this.words[i2] = r2 & 67108863, carry = r2 >>> 26;
        for (;carry !== 0 && i2 < a2.length; i2++)
          r2 = (a2.words[i2] | 0) + carry, this.words[i2] = r2 & 67108863, carry = r2 >>> 26;
        if (this.length = a2.length, carry !== 0)
          this.words[this.length] = carry, this.length++;
        else if (a2 !== this)
          for (;i2 < a2.length; i2++)
            this.words[i2] = a2.words[i2];
        return this;
      }, BN.prototype.add = function(num) {
        var res;
        if (num.negative !== 0 && this.negative === 0)
          return num.negative = 0, res = this.sub(num), num.negative ^= 1, res;
        else if (num.negative === 0 && this.negative !== 0)
          return this.negative = 0, res = num.sub(this), this.negative = 1, res;
        if (this.length > num.length)
          return this.clone().iadd(num);
        return num.clone().iadd(this);
      }, BN.prototype.isub = function(num) {
        if (num.negative !== 0) {
          num.negative = 0;
          var r2 = this.iadd(num);
          return num.negative = 1, r2._normSign();
        } else if (this.negative !== 0)
          return this.negative = 0, this.iadd(num), this.negative = 1, this._normSign();
        var cmp = this.cmp(num);
        if (cmp === 0)
          return this.negative = 0, this.length = 1, this.words[0] = 0, this;
        var a2, b;
        if (cmp > 0)
          a2 = this, b = num;
        else
          a2 = num, b = this;
        var carry = 0;
        for (var i2 = 0;i2 < b.length; i2++)
          r2 = (a2.words[i2] | 0) - (b.words[i2] | 0) + carry, carry = r2 >> 26, this.words[i2] = r2 & 67108863;
        for (;carry !== 0 && i2 < a2.length; i2++)
          r2 = (a2.words[i2] | 0) + carry, carry = r2 >> 26, this.words[i2] = r2 & 67108863;
        if (carry === 0 && i2 < a2.length && a2 !== this)
          for (;i2 < a2.length; i2++)
            this.words[i2] = a2.words[i2];
        if (this.length = Math.max(this.length, i2), a2 !== this)
          this.negative = 1;
        return this.strip();
      }, BN.prototype.sub = function(num) {
        return this.clone().isub(num);
      };
      function smallMulTo(self2, num, out) {
        out.negative = num.negative ^ self2.negative;
        var len2 = self2.length + num.length | 0;
        out.length = len2, len2 = len2 - 1 | 0;
        var a2 = self2.words[0] | 0, b = num.words[0] | 0, r2 = a2 * b, lo = r2 & 67108863, carry = r2 / 67108864 | 0;
        out.words[0] = lo;
        for (var k = 1;k < len2; k++) {
          var ncarry = carry >>> 26, rword = carry & 67108863, maxJ = Math.min(k, num.length - 1);
          for (var j = Math.max(0, k - self2.length + 1);j <= maxJ; j++) {
            var i2 = k - j | 0;
            a2 = self2.words[i2] | 0, b = num.words[j] | 0, r2 = a2 * b + rword, ncarry += r2 / 67108864 | 0, rword = r2 & 67108863;
          }
          out.words[k] = rword | 0, carry = ncarry | 0;
        }
        if (carry !== 0)
          out.words[k] = carry | 0;
        else
          out.length--;
        return out.strip();
      }
      var comb10MulTo = function(self2, num, out) {
        var a2 = self2.words, b = num.words, o2 = out.words, c2 = 0, lo, mid, hi, a0 = a2[0] | 0, al0 = a0 & 8191, ah0 = a0 >>> 13, a1 = a2[1] | 0, al1 = a1 & 8191, ah1 = a1 >>> 13, a22 = a2[2] | 0, al2 = a22 & 8191, ah2 = a22 >>> 13, a3 = a2[3] | 0, al3 = a3 & 8191, ah3 = a3 >>> 13, a4 = a2[4] | 0, al4 = a4 & 8191, ah4 = a4 >>> 13, a5 = a2[5] | 0, al5 = a5 & 8191, ah5 = a5 >>> 13, a6 = a2[6] | 0, al6 = a6 & 8191, ah6 = a6 >>> 13, a7 = a2[7] | 0, al7 = a7 & 8191, ah7 = a7 >>> 13, a8 = a2[8] | 0, al8 = a8 & 8191, ah8 = a8 >>> 13, a9 = a2[9] | 0, al9 = a9 & 8191, ah9 = a9 >>> 13, b0 = b[0] | 0, bl0 = b0 & 8191, bh0 = b0 >>> 13, b1 = b[1] | 0, bl1 = b1 & 8191, bh1 = b1 >>> 13, b2 = b[2] | 0, bl2 = b2 & 8191, bh2 = b2 >>> 13, b3 = b[3] | 0, bl3 = b3 & 8191, bh3 = b3 >>> 13, b4 = b[4] | 0, bl4 = b4 & 8191, bh4 = b4 >>> 13, b5 = b[5] | 0, bl5 = b5 & 8191, bh5 = b5 >>> 13, b6 = b[6] | 0, bl6 = b6 & 8191, bh6 = b6 >>> 13, b7 = b[7] | 0, bl7 = b7 & 8191, bh7 = b7 >>> 13, b8 = b[8] | 0, bl8 = b8 & 8191, bh8 = b8 >>> 13, b9 = b[9] | 0, bl9 = b9 & 8191, bh9 = b9 >>> 13;
        out.negative = self2.negative ^ num.negative, out.length = 19, lo = Math.imul(al0, bl0), mid = Math.imul(al0, bh0), mid = mid + Math.imul(ah0, bl0) | 0, hi = Math.imul(ah0, bh0);
        var w0 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w0 >>> 26) | 0, w0 &= 67108863, lo = Math.imul(al1, bl0), mid = Math.imul(al1, bh0), mid = mid + Math.imul(ah1, bl0) | 0, hi = Math.imul(ah1, bh0), lo = lo + Math.imul(al0, bl1) | 0, mid = mid + Math.imul(al0, bh1) | 0, mid = mid + Math.imul(ah0, bl1) | 0, hi = hi + Math.imul(ah0, bh1) | 0;
        var w1 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w1 >>> 26) | 0, w1 &= 67108863, lo = Math.imul(al2, bl0), mid = Math.imul(al2, bh0), mid = mid + Math.imul(ah2, bl0) | 0, hi = Math.imul(ah2, bh0), lo = lo + Math.imul(al1, bl1) | 0, mid = mid + Math.imul(al1, bh1) | 0, mid = mid + Math.imul(ah1, bl1) | 0, hi = hi + Math.imul(ah1, bh1) | 0, lo = lo + Math.imul(al0, bl2) | 0, mid = mid + Math.imul(al0, bh2) | 0, mid = mid + Math.imul(ah0, bl2) | 0, hi = hi + Math.imul(ah0, bh2) | 0;
        var w2 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w2 >>> 26) | 0, w2 &= 67108863, lo = Math.imul(al3, bl0), mid = Math.imul(al3, bh0), mid = mid + Math.imul(ah3, bl0) | 0, hi = Math.imul(ah3, bh0), lo = lo + Math.imul(al2, bl1) | 0, mid = mid + Math.imul(al2, bh1) | 0, mid = mid + Math.imul(ah2, bl1) | 0, hi = hi + Math.imul(ah2, bh1) | 0, lo = lo + Math.imul(al1, bl2) | 0, mid = mid + Math.imul(al1, bh2) | 0, mid = mid + Math.imul(ah1, bl2) | 0, hi = hi + Math.imul(ah1, bh2) | 0, lo = lo + Math.imul(al0, bl3) | 0, mid = mid + Math.imul(al0, bh3) | 0, mid = mid + Math.imul(ah0, bl3) | 0, hi = hi + Math.imul(ah0, bh3) | 0;
        var w3 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w3 >>> 26) | 0, w3 &= 67108863, lo = Math.imul(al4, bl0), mid = Math.imul(al4, bh0), mid = mid + Math.imul(ah4, bl0) | 0, hi = Math.imul(ah4, bh0), lo = lo + Math.imul(al3, bl1) | 0, mid = mid + Math.imul(al3, bh1) | 0, mid = mid + Math.imul(ah3, bl1) | 0, hi = hi + Math.imul(ah3, bh1) | 0, lo = lo + Math.imul(al2, bl2) | 0, mid = mid + Math.imul(al2, bh2) | 0, mid = mid + Math.imul(ah2, bl2) | 0, hi = hi + Math.imul(ah2, bh2) | 0, lo = lo + Math.imul(al1, bl3) | 0, mid = mid + Math.imul(al1, bh3) | 0, mid = mid + Math.imul(ah1, bl3) | 0, hi = hi + Math.imul(ah1, bh3) | 0, lo = lo + Math.imul(al0, bl4) | 0, mid = mid + Math.imul(al0, bh4) | 0, mid = mid + Math.imul(ah0, bl4) | 0, hi = hi + Math.imul(ah0, bh4) | 0;
        var w4 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w4 >>> 26) | 0, w4 &= 67108863, lo = Math.imul(al5, bl0), mid = Math.imul(al5, bh0), mid = mid + Math.imul(ah5, bl0) | 0, hi = Math.imul(ah5, bh0), lo = lo + Math.imul(al4, bl1) | 0, mid = mid + Math.imul(al4, bh1) | 0, mid = mid + Math.imul(ah4, bl1) | 0, hi = hi + Math.imul(ah4, bh1) | 0, lo = lo + Math.imul(al3, bl2) | 0, mid = mid + Math.imul(al3, bh2) | 0, mid = mid + Math.imul(ah3, bl2) | 0, hi = hi + Math.imul(ah3, bh2) | 0, lo = lo + Math.imul(al2, bl3) | 0, mid = mid + Math.imul(al2, bh3) | 0, mid = mid + Math.imul(ah2, bl3) | 0, hi = hi + Math.imul(ah2, bh3) | 0, lo = lo + Math.imul(al1, bl4) | 0, mid = mid + Math.imul(al1, bh4) | 0, mid = mid + Math.imul(ah1, bl4) | 0, hi = hi + Math.imul(ah1, bh4) | 0, lo = lo + Math.imul(al0, bl5) | 0, mid = mid + Math.imul(al0, bh5) | 0, mid = mid + Math.imul(ah0, bl5) | 0, hi = hi + Math.imul(ah0, bh5) | 0;
        var w5 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w5 >>> 26) | 0, w5 &= 67108863, lo = Math.imul(al6, bl0), mid = Math.imul(al6, bh0), mid = mid + Math.imul(ah6, bl0) | 0, hi = Math.imul(ah6, bh0), lo = lo + Math.imul(al5, bl1) | 0, mid = mid + Math.imul(al5, bh1) | 0, mid = mid + Math.imul(ah5, bl1) | 0, hi = hi + Math.imul(ah5, bh1) | 0, lo = lo + Math.imul(al4, bl2) | 0, mid = mid + Math.imul(al4, bh2) | 0, mid = mid + Math.imul(ah4, bl2) | 0, hi = hi + Math.imul(ah4, bh2) | 0, lo = lo + Math.imul(al3, bl3) | 0, mid = mid + Math.imul(al3, bh3) | 0, mid = mid + Math.imul(ah3, bl3) | 0, hi = hi + Math.imul(ah3, bh3) | 0, lo = lo + Math.imul(al2, bl4) | 0, mid = mid + Math.imul(al2, bh4) | 0, mid = mid + Math.imul(ah2, bl4) | 0, hi = hi + Math.imul(ah2, bh4) | 0, lo = lo + Math.imul(al1, bl5) | 0, mid = mid + Math.imul(al1, bh5) | 0, mid = mid + Math.imul(ah1, bl5) | 0, hi = hi + Math.imul(ah1, bh5) | 0, lo = lo + Math.imul(al0, bl6) | 0, mid = mid + Math.imul(al0, bh6) | 0, mid = mid + Math.imul(ah0, bl6) | 0, hi = hi + Math.imul(ah0, bh6) | 0;
        var w6 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w6 >>> 26) | 0, w6 &= 67108863, lo = Math.imul(al7, bl0), mid = Math.imul(al7, bh0), mid = mid + Math.imul(ah7, bl0) | 0, hi = Math.imul(ah7, bh0), lo = lo + Math.imul(al6, bl1) | 0, mid = mid + Math.imul(al6, bh1) | 0, mid = mid + Math.imul(ah6, bl1) | 0, hi = hi + Math.imul(ah6, bh1) | 0, lo = lo + Math.imul(al5, bl2) | 0, mid = mid + Math.imul(al5, bh2) | 0, mid = mid + Math.imul(ah5, bl2) | 0, hi = hi + Math.imul(ah5, bh2) | 0, lo = lo + Math.imul(al4, bl3) | 0, mid = mid + Math.imul(al4, bh3) | 0, mid = mid + Math.imul(ah4, bl3) | 0, hi = hi + Math.imul(ah4, bh3) | 0, lo = lo + Math.imul(al3, bl4) | 0, mid = mid + Math.imul(al3, bh4) | 0, mid = mid + Math.imul(ah3, bl4) | 0, hi = hi + Math.imul(ah3, bh4) | 0, lo = lo + Math.imul(al2, bl5) | 0, mid = mid + Math.imul(al2, bh5) | 0, mid = mid + Math.imul(ah2, bl5) | 0, hi = hi + Math.imul(ah2, bh5) | 0, lo = lo + Math.imul(al1, bl6) | 0, mid = mid + Math.imul(al1, bh6) | 0, mid = mid + Math.imul(ah1, bl6) | 0, hi = hi + Math.imul(ah1, bh6) | 0, lo = lo + Math.imul(al0, bl7) | 0, mid = mid + Math.imul(al0, bh7) | 0, mid = mid + Math.imul(ah0, bl7) | 0, hi = hi + Math.imul(ah0, bh7) | 0;
        var w7 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w7 >>> 26) | 0, w7 &= 67108863, lo = Math.imul(al8, bl0), mid = Math.imul(al8, bh0), mid = mid + Math.imul(ah8, bl0) | 0, hi = Math.imul(ah8, bh0), lo = lo + Math.imul(al7, bl1) | 0, mid = mid + Math.imul(al7, bh1) | 0, mid = mid + Math.imul(ah7, bl1) | 0, hi = hi + Math.imul(ah7, bh1) | 0, lo = lo + Math.imul(al6, bl2) | 0, mid = mid + Math.imul(al6, bh2) | 0, mid = mid + Math.imul(ah6, bl2) | 0, hi = hi + Math.imul(ah6, bh2) | 0, lo = lo + Math.imul(al5, bl3) | 0, mid = mid + Math.imul(al5, bh3) | 0, mid = mid + Math.imul(ah5, bl3) | 0, hi = hi + Math.imul(ah5, bh3) | 0, lo = lo + Math.imul(al4, bl4) | 0, mid = mid + Math.imul(al4, bh4) | 0, mid = mid + Math.imul(ah4, bl4) | 0, hi = hi + Math.imul(ah4, bh4) | 0, lo = lo + Math.imul(al3, bl5) | 0, mid = mid + Math.imul(al3, bh5) | 0, mid = mid + Math.imul(ah3, bl5) | 0, hi = hi + Math.imul(ah3, bh5) | 0, lo = lo + Math.imul(al2, bl6) | 0, mid = mid + Math.imul(al2, bh6) | 0, mid = mid + Math.imul(ah2, bl6) | 0, hi = hi + Math.imul(ah2, bh6) | 0, lo = lo + Math.imul(al1, bl7) | 0, mid = mid + Math.imul(al1, bh7) | 0, mid = mid + Math.imul(ah1, bl7) | 0, hi = hi + Math.imul(ah1, bh7) | 0, lo = lo + Math.imul(al0, bl8) | 0, mid = mid + Math.imul(al0, bh8) | 0, mid = mid + Math.imul(ah0, bl8) | 0, hi = hi + Math.imul(ah0, bh8) | 0;
        var w8 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w8 >>> 26) | 0, w8 &= 67108863, lo = Math.imul(al9, bl0), mid = Math.imul(al9, bh0), mid = mid + Math.imul(ah9, bl0) | 0, hi = Math.imul(ah9, bh0), lo = lo + Math.imul(al8, bl1) | 0, mid = mid + Math.imul(al8, bh1) | 0, mid = mid + Math.imul(ah8, bl1) | 0, hi = hi + Math.imul(ah8, bh1) | 0, lo = lo + Math.imul(al7, bl2) | 0, mid = mid + Math.imul(al7, bh2) | 0, mid = mid + Math.imul(ah7, bl2) | 0, hi = hi + Math.imul(ah7, bh2) | 0, lo = lo + Math.imul(al6, bl3) | 0, mid = mid + Math.imul(al6, bh3) | 0, mid = mid + Math.imul(ah6, bl3) | 0, hi = hi + Math.imul(ah6, bh3) | 0, lo = lo + Math.imul(al5, bl4) | 0, mid = mid + Math.imul(al5, bh4) | 0, mid = mid + Math.imul(ah5, bl4) | 0, hi = hi + Math.imul(ah5, bh4) | 0, lo = lo + Math.imul(al4, bl5) | 0, mid = mid + Math.imul(al4, bh5) | 0, mid = mid + Math.imul(ah4, bl5) | 0, hi = hi + Math.imul(ah4, bh5) | 0, lo = lo + Math.imul(al3, bl6) | 0, mid = mid + Math.imul(al3, bh6) | 0, mid = mid + Math.imul(ah3, bl6) | 0, hi = hi + Math.imul(ah3, bh6) | 0, lo = lo + Math.imul(al2, bl7) | 0, mid = mid + Math.imul(al2, bh7) | 0, mid = mid + Math.imul(ah2, bl7) | 0, hi = hi + Math.imul(ah2, bh7) | 0, lo = lo + Math.imul(al1, bl8) | 0, mid = mid + Math.imul(al1, bh8) | 0, mid = mid + Math.imul(ah1, bl8) | 0, hi = hi + Math.imul(ah1, bh8) | 0, lo = lo + Math.imul(al0, bl9) | 0, mid = mid + Math.imul(al0, bh9) | 0, mid = mid + Math.imul(ah0, bl9) | 0, hi = hi + Math.imul(ah0, bh9) | 0;
        var w9 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w9 >>> 26) | 0, w9 &= 67108863, lo = Math.imul(al9, bl1), mid = Math.imul(al9, bh1), mid = mid + Math.imul(ah9, bl1) | 0, hi = Math.imul(ah9, bh1), lo = lo + Math.imul(al8, bl2) | 0, mid = mid + Math.imul(al8, bh2) | 0, mid = mid + Math.imul(ah8, bl2) | 0, hi = hi + Math.imul(ah8, bh2) | 0, lo = lo + Math.imul(al7, bl3) | 0, mid = mid + Math.imul(al7, bh3) | 0, mid = mid + Math.imul(ah7, bl3) | 0, hi = hi + Math.imul(ah7, bh3) | 0, lo = lo + Math.imul(al6, bl4) | 0, mid = mid + Math.imul(al6, bh4) | 0, mid = mid + Math.imul(ah6, bl4) | 0, hi = hi + Math.imul(ah6, bh4) | 0, lo = lo + Math.imul(al5, bl5) | 0, mid = mid + Math.imul(al5, bh5) | 0, mid = mid + Math.imul(ah5, bl5) | 0, hi = hi + Math.imul(ah5, bh5) | 0, lo = lo + Math.imul(al4, bl6) | 0, mid = mid + Math.imul(al4, bh6) | 0, mid = mid + Math.imul(ah4, bl6) | 0, hi = hi + Math.imul(ah4, bh6) | 0, lo = lo + Math.imul(al3, bl7) | 0, mid = mid + Math.imul(al3, bh7) | 0, mid = mid + Math.imul(ah3, bl7) | 0, hi = hi + Math.imul(ah3, bh7) | 0, lo = lo + Math.imul(al2, bl8) | 0, mid = mid + Math.imul(al2, bh8) | 0, mid = mid + Math.imul(ah2, bl8) | 0, hi = hi + Math.imul(ah2, bh8) | 0, lo = lo + Math.imul(al1, bl9) | 0, mid = mid + Math.imul(al1, bh9) | 0, mid = mid + Math.imul(ah1, bl9) | 0, hi = hi + Math.imul(ah1, bh9) | 0;
        var w10 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w10 >>> 26) | 0, w10 &= 67108863, lo = Math.imul(al9, bl2), mid = Math.imul(al9, bh2), mid = mid + Math.imul(ah9, bl2) | 0, hi = Math.imul(ah9, bh2), lo = lo + Math.imul(al8, bl3) | 0, mid = mid + Math.imul(al8, bh3) | 0, mid = mid + Math.imul(ah8, bl3) | 0, hi = hi + Math.imul(ah8, bh3) | 0, lo = lo + Math.imul(al7, bl4) | 0, mid = mid + Math.imul(al7, bh4) | 0, mid = mid + Math.imul(ah7, bl4) | 0, hi = hi + Math.imul(ah7, bh4) | 0, lo = lo + Math.imul(al6, bl5) | 0, mid = mid + Math.imul(al6, bh5) | 0, mid = mid + Math.imul(ah6, bl5) | 0, hi = hi + Math.imul(ah6, bh5) | 0, lo = lo + Math.imul(al5, bl6) | 0, mid = mid + Math.imul(al5, bh6) | 0, mid = mid + Math.imul(ah5, bl6) | 0, hi = hi + Math.imul(ah5, bh6) | 0, lo = lo + Math.imul(al4, bl7) | 0, mid = mid + Math.imul(al4, bh7) | 0, mid = mid + Math.imul(ah4, bl7) | 0, hi = hi + Math.imul(ah4, bh7) | 0, lo = lo + Math.imul(al3, bl8) | 0, mid = mid + Math.imul(al3, bh8) | 0, mid = mid + Math.imul(ah3, bl8) | 0, hi = hi + Math.imul(ah3, bh8) | 0, lo = lo + Math.imul(al2, bl9) | 0, mid = mid + Math.imul(al2, bh9) | 0, mid = mid + Math.imul(ah2, bl9) | 0, hi = hi + Math.imul(ah2, bh9) | 0;
        var w11 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w11 >>> 26) | 0, w11 &= 67108863, lo = Math.imul(al9, bl3), mid = Math.imul(al9, bh3), mid = mid + Math.imul(ah9, bl3) | 0, hi = Math.imul(ah9, bh3), lo = lo + Math.imul(al8, bl4) | 0, mid = mid + Math.imul(al8, bh4) | 0, mid = mid + Math.imul(ah8, bl4) | 0, hi = hi + Math.imul(ah8, bh4) | 0, lo = lo + Math.imul(al7, bl5) | 0, mid = mid + Math.imul(al7, bh5) | 0, mid = mid + Math.imul(ah7, bl5) | 0, hi = hi + Math.imul(ah7, bh5) | 0, lo = lo + Math.imul(al6, bl6) | 0, mid = mid + Math.imul(al6, bh6) | 0, mid = mid + Math.imul(ah6, bl6) | 0, hi = hi + Math.imul(ah6, bh6) | 0, lo = lo + Math.imul(al5, bl7) | 0, mid = mid + Math.imul(al5, bh7) | 0, mid = mid + Math.imul(ah5, bl7) | 0, hi = hi + Math.imul(ah5, bh7) | 0, lo = lo + Math.imul(al4, bl8) | 0, mid = mid + Math.imul(al4, bh8) | 0, mid = mid + Math.imul(ah4, bl8) | 0, hi = hi + Math.imul(ah4, bh8) | 0, lo = lo + Math.imul(al3, bl9) | 0, mid = mid + Math.imul(al3, bh9) | 0, mid = mid + Math.imul(ah3, bl9) | 0, hi = hi + Math.imul(ah3, bh9) | 0;
        var w12 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w12 >>> 26) | 0, w12 &= 67108863, lo = Math.imul(al9, bl4), mid = Math.imul(al9, bh4), mid = mid + Math.imul(ah9, bl4) | 0, hi = Math.imul(ah9, bh4), lo = lo + Math.imul(al8, bl5) | 0, mid = mid + Math.imul(al8, bh5) | 0, mid = mid + Math.imul(ah8, bl5) | 0, hi = hi + Math.imul(ah8, bh5) | 0, lo = lo + Math.imul(al7, bl6) | 0, mid = mid + Math.imul(al7, bh6) | 0, mid = mid + Math.imul(ah7, bl6) | 0, hi = hi + Math.imul(ah7, bh6) | 0, lo = lo + Math.imul(al6, bl7) | 0, mid = mid + Math.imul(al6, bh7) | 0, mid = mid + Math.imul(ah6, bl7) | 0, hi = hi + Math.imul(ah6, bh7) | 0, lo = lo + Math.imul(al5, bl8) | 0, mid = mid + Math.imul(al5, bh8) | 0, mid = mid + Math.imul(ah5, bl8) | 0, hi = hi + Math.imul(ah5, bh8) | 0, lo = lo + Math.imul(al4, bl9) | 0, mid = mid + Math.imul(al4, bh9) | 0, mid = mid + Math.imul(ah4, bl9) | 0, hi = hi + Math.imul(ah4, bh9) | 0;
        var w13 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w13 >>> 26) | 0, w13 &= 67108863, lo = Math.imul(al9, bl5), mid = Math.imul(al9, bh5), mid = mid + Math.imul(ah9, bl5) | 0, hi = Math.imul(ah9, bh5), lo = lo + Math.imul(al8, bl6) | 0, mid = mid + Math.imul(al8, bh6) | 0, mid = mid + Math.imul(ah8, bl6) | 0, hi = hi + Math.imul(ah8, bh6) | 0, lo = lo + Math.imul(al7, bl7) | 0, mid = mid + Math.imul(al7, bh7) | 0, mid = mid + Math.imul(ah7, bl7) | 0, hi = hi + Math.imul(ah7, bh7) | 0, lo = lo + Math.imul(al6, bl8) | 0, mid = mid + Math.imul(al6, bh8) | 0, mid = mid + Math.imul(ah6, bl8) | 0, hi = hi + Math.imul(ah6, bh8) | 0, lo = lo + Math.imul(al5, bl9) | 0, mid = mid + Math.imul(al5, bh9) | 0, mid = mid + Math.imul(ah5, bl9) | 0, hi = hi + Math.imul(ah5, bh9) | 0;
        var w14 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w14 >>> 26) | 0, w14 &= 67108863, lo = Math.imul(al9, bl6), mid = Math.imul(al9, bh6), mid = mid + Math.imul(ah9, bl6) | 0, hi = Math.imul(ah9, bh6), lo = lo + Math.imul(al8, bl7) | 0, mid = mid + Math.imul(al8, bh7) | 0, mid = mid + Math.imul(ah8, bl7) | 0, hi = hi + Math.imul(ah8, bh7) | 0, lo = lo + Math.imul(al7, bl8) | 0, mid = mid + Math.imul(al7, bh8) | 0, mid = mid + Math.imul(ah7, bl8) | 0, hi = hi + Math.imul(ah7, bh8) | 0, lo = lo + Math.imul(al6, bl9) | 0, mid = mid + Math.imul(al6, bh9) | 0, mid = mid + Math.imul(ah6, bl9) | 0, hi = hi + Math.imul(ah6, bh9) | 0;
        var w15 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w15 >>> 26) | 0, w15 &= 67108863, lo = Math.imul(al9, bl7), mid = Math.imul(al9, bh7), mid = mid + Math.imul(ah9, bl7) | 0, hi = Math.imul(ah9, bh7), lo = lo + Math.imul(al8, bl8) | 0, mid = mid + Math.imul(al8, bh8) | 0, mid = mid + Math.imul(ah8, bl8) | 0, hi = hi + Math.imul(ah8, bh8) | 0, lo = lo + Math.imul(al7, bl9) | 0, mid = mid + Math.imul(al7, bh9) | 0, mid = mid + Math.imul(ah7, bl9) | 0, hi = hi + Math.imul(ah7, bh9) | 0;
        var w16 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w16 >>> 26) | 0, w16 &= 67108863, lo = Math.imul(al9, bl8), mid = Math.imul(al9, bh8), mid = mid + Math.imul(ah9, bl8) | 0, hi = Math.imul(ah9, bh8), lo = lo + Math.imul(al8, bl9) | 0, mid = mid + Math.imul(al8, bh9) | 0, mid = mid + Math.imul(ah8, bl9) | 0, hi = hi + Math.imul(ah8, bh9) | 0;
        var w17 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w17 >>> 26) | 0, w17 &= 67108863, lo = Math.imul(al9, bl9), mid = Math.imul(al9, bh9), mid = mid + Math.imul(ah9, bl9) | 0, hi = Math.imul(ah9, bh9);
        var w18 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        if (c2 = (hi + (mid >>> 13) | 0) + (w18 >>> 26) | 0, w18 &= 67108863, o2[0] = w0, o2[1] = w1, o2[2] = w2, o2[3] = w3, o2[4] = w4, o2[5] = w5, o2[6] = w6, o2[7] = w7, o2[8] = w8, o2[9] = w9, o2[10] = w10, o2[11] = w11, o2[12] = w12, o2[13] = w13, o2[14] = w14, o2[15] = w15, o2[16] = w16, o2[17] = w17, o2[18] = w18, c2 !== 0)
          o2[19] = c2, out.length++;
        return out;
      };
      if (!Math.imul)
        comb10MulTo = smallMulTo;
      function bigMulTo(self2, num, out) {
        out.negative = num.negative ^ self2.negative, out.length = self2.length + num.length;
        var carry = 0, hncarry = 0;
        for (var k = 0;k < out.length - 1; k++) {
          var ncarry = hncarry;
          hncarry = 0;
          var rword = carry & 67108863, maxJ = Math.min(k, num.length - 1);
          for (var j = Math.max(0, k - self2.length + 1);j <= maxJ; j++) {
            var i2 = k - j, a2 = self2.words[i2] | 0, b = num.words[j] | 0, r2 = a2 * b, lo = r2 & 67108863;
            ncarry = ncarry + (r2 / 67108864 | 0) | 0, lo = lo + rword | 0, rword = lo & 67108863, ncarry = ncarry + (lo >>> 26) | 0, hncarry += ncarry >>> 26, ncarry &= 67108863;
          }
          out.words[k] = rword, carry = ncarry, ncarry = hncarry;
        }
        if (carry !== 0)
          out.words[k] = carry;
        else
          out.length--;
        return out.strip();
      }
      function jumboMulTo(self2, num, out) {
        var fftm = new FFTM;
        return fftm.mulp(self2, num, out);
      }
      BN.prototype.mulTo = function(num, out) {
        var res, len2 = this.length + num.length;
        if (this.length === 10 && num.length === 10)
          res = comb10MulTo(this, num, out);
        else if (len2 < 63)
          res = smallMulTo(this, num, out);
        else if (len2 < 1024)
          res = bigMulTo(this, num, out);
        else
          res = jumboMulTo(this, num, out);
        return res;
      };
      function FFTM(x, y) {
        this.x = x, this.y = y;
      }
      FFTM.prototype.makeRBT = function(N) {
        var t2 = Array(N), l2 = BN.prototype._countBits(N) - 1;
        for (var i2 = 0;i2 < N; i2++)
          t2[i2] = this.revBin(i2, l2, N);
        return t2;
      }, FFTM.prototype.revBin = function(x, l2, N) {
        if (x === 0 || x === N - 1)
          return x;
        var rb = 0;
        for (var i2 = 0;i2 < l2; i2++)
          rb |= (x & 1) << l2 - i2 - 1, x >>= 1;
        return rb;
      }, FFTM.prototype.permute = function(rbt, rws, iws, rtws, itws, N) {
        for (var i2 = 0;i2 < N; i2++)
          rtws[i2] = rws[rbt[i2]], itws[i2] = iws[rbt[i2]];
      }, FFTM.prototype.transform = function(rws, iws, rtws, itws, N, rbt) {
        this.permute(rbt, rws, iws, rtws, itws, N);
        for (var s = 1;s < N; s <<= 1) {
          var l2 = s << 1, rtwdf = Math.cos(2 * Math.PI / l2), itwdf = Math.sin(2 * Math.PI / l2);
          for (var p2 = 0;p2 < N; p2 += l2) {
            var rtwdf_ = rtwdf, itwdf_ = itwdf;
            for (var j = 0;j < s; j++) {
              var re = rtws[p2 + j], ie = itws[p2 + j], ro = rtws[p2 + j + s], io = itws[p2 + j + s], rx = rtwdf_ * ro - itwdf_ * io;
              if (io = rtwdf_ * io + itwdf_ * ro, ro = rx, rtws[p2 + j] = re + ro, itws[p2 + j] = ie + io, rtws[p2 + j + s] = re - ro, itws[p2 + j + s] = ie - io, j !== l2)
                rx = rtwdf * rtwdf_ - itwdf * itwdf_, itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_, rtwdf_ = rx;
            }
          }
        }
      }, FFTM.prototype.guessLen13b = function(n2, m) {
        var N = Math.max(m, n2) | 1, odd = N & 1, i2 = 0;
        for (N = N / 2 | 0;N; N = N >>> 1)
          i2++;
        return 1 << i2 + 1 + odd;
      }, FFTM.prototype.conjugate = function(rws, iws, N) {
        if (N <= 1)
          return;
        for (var i2 = 0;i2 < N / 2; i2++) {
          var t2 = rws[i2];
          rws[i2] = rws[N - i2 - 1], rws[N - i2 - 1] = t2, t2 = iws[i2], iws[i2] = -iws[N - i2 - 1], iws[N - i2 - 1] = -t2;
        }
      }, FFTM.prototype.normalize13b = function(ws, N) {
        var carry = 0;
        for (var i2 = 0;i2 < N / 2; i2++) {
          var w = Math.round(ws[2 * i2 + 1] / N) * 8192 + Math.round(ws[2 * i2] / N) + carry;
          if (ws[i2] = w & 67108863, w < 67108864)
            carry = 0;
          else
            carry = w / 67108864 | 0;
        }
        return ws;
      }, FFTM.prototype.convert13b = function(ws, len2, rws, N) {
        var carry = 0;
        for (var i2 = 0;i2 < len2; i2++)
          carry = carry + (ws[i2] | 0), rws[2 * i2] = carry & 8191, carry = carry >>> 13, rws[2 * i2 + 1] = carry & 8191, carry = carry >>> 13;
        for (i2 = 2 * len2;i2 < N; ++i2)
          rws[i2] = 0;
        assert(carry === 0), assert((carry & -8192) === 0);
      }, FFTM.prototype.stub = function(N) {
        var ph = Array(N);
        for (var i2 = 0;i2 < N; i2++)
          ph[i2] = 0;
        return ph;
      }, FFTM.prototype.mulp = function(x, y, out) {
        var N = 2 * this.guessLen13b(x.length, y.length), rbt = this.makeRBT(N), _ = this.stub(N), rws = Array(N), rwst = Array(N), iwst = Array(N), nrws = Array(N), nrwst = Array(N), niwst = Array(N), rmws = out.words;
        rmws.length = N, this.convert13b(x.words, x.length, rws, N), this.convert13b(y.words, y.length, nrws, N), this.transform(rws, _, rwst, iwst, N, rbt), this.transform(nrws, _, nrwst, niwst, N, rbt);
        for (var i2 = 0;i2 < N; i2++) {
          var rx = rwst[i2] * nrwst[i2] - iwst[i2] * niwst[i2];
          iwst[i2] = rwst[i2] * niwst[i2] + iwst[i2] * nrwst[i2], rwst[i2] = rx;
        }
        return this.conjugate(rwst, iwst, N), this.transform(rwst, iwst, rmws, _, N, rbt), this.conjugate(rmws, _, N), this.normalize13b(rmws, N), out.negative = x.negative ^ y.negative, out.length = x.length + y.length, out.strip();
      }, BN.prototype.mul = function(num) {
        var out = new BN(null);
        return out.words = Array(this.length + num.length), this.mulTo(num, out);
      }, BN.prototype.mulf = function(num) {
        var out = new BN(null);
        return out.words = Array(this.length + num.length), jumboMulTo(this, num, out);
      }, BN.prototype.imul = function(num) {
        return this.clone().mulTo(num, this);
      }, BN.prototype.imuln = function(num) {
        assert(typeof num === "number"), assert(num < 67108864);
        var carry = 0;
        for (var i2 = 0;i2 < this.length; i2++) {
          var w = (this.words[i2] | 0) * num, lo = (w & 67108863) + (carry & 67108863);
          carry >>= 26, carry += w / 67108864 | 0, carry += lo >>> 26, this.words[i2] = lo & 67108863;
        }
        if (carry !== 0)
          this.words[i2] = carry, this.length++;
        return this.length = num === 0 ? 1 : this.length, this;
      }, BN.prototype.muln = function(num) {
        return this.clone().imuln(num);
      }, BN.prototype.sqr = function() {
        return this.mul(this);
      }, BN.prototype.isqr = function() {
        return this.imul(this.clone());
      }, BN.prototype.pow = function(num) {
        var w = toBitArray(num);
        if (w.length === 0)
          return new BN(1);
        var res = this;
        for (var i2 = 0;i2 < w.length; i2++, res = res.sqr())
          if (w[i2] !== 0)
            break;
        if (++i2 < w.length)
          for (var q = res.sqr();i2 < w.length; i2++, q = q.sqr()) {
            if (w[i2] === 0)
              continue;
            res = res.mul(q);
          }
        return res;
      }, BN.prototype.iushln = function(bits) {
        assert(typeof bits === "number" && bits >= 0);
        var r2 = bits % 26, s = (bits - r2) / 26, carryMask = 67108863 >>> 26 - r2 << 26 - r2, i2;
        if (r2 !== 0) {
          var carry = 0;
          for (i2 = 0;i2 < this.length; i2++) {
            var newCarry = this.words[i2] & carryMask, c2 = (this.words[i2] | 0) - newCarry << r2;
            this.words[i2] = c2 | carry, carry = newCarry >>> 26 - r2;
          }
          if (carry)
            this.words[i2] = carry, this.length++;
        }
        if (s !== 0) {
          for (i2 = this.length - 1;i2 >= 0; i2--)
            this.words[i2 + s] = this.words[i2];
          for (i2 = 0;i2 < s; i2++)
            this.words[i2] = 0;
          this.length += s;
        }
        return this.strip();
      }, BN.prototype.ishln = function(bits) {
        return assert(this.negative === 0), this.iushln(bits);
      }, BN.prototype.iushrn = function(bits, hint, extended) {
        assert(typeof bits === "number" && bits >= 0);
        var h;
        if (hint)
          h = (hint - hint % 26) / 26;
        else
          h = 0;
        var r2 = bits % 26, s = Math.min((bits - r2) / 26, this.length), mask = 67108863 ^ 67108863 >>> r2 << r2, maskedWords = extended;
        if (h -= s, h = Math.max(0, h), maskedWords) {
          for (var i2 = 0;i2 < s; i2++)
            maskedWords.words[i2] = this.words[i2];
          maskedWords.length = s;
        }
        if (s === 0)
          ;
        else if (this.length > s) {
          this.length -= s;
          for (i2 = 0;i2 < this.length; i2++)
            this.words[i2] = this.words[i2 + s];
        } else
          this.words[0] = 0, this.length = 1;
        var carry = 0;
        for (i2 = this.length - 1;i2 >= 0 && (carry !== 0 || i2 >= h); i2--) {
          var word = this.words[i2] | 0;
          this.words[i2] = carry << 26 - r2 | word >>> r2, carry = word & mask;
        }
        if (maskedWords && carry !== 0)
          maskedWords.words[maskedWords.length++] = carry;
        if (this.length === 0)
          this.words[0] = 0, this.length = 1;
        return this.strip();
      }, BN.prototype.ishrn = function(bits, hint, extended) {
        return assert(this.negative === 0), this.iushrn(bits, hint, extended);
      }, BN.prototype.shln = function(bits) {
        return this.clone().ishln(bits);
      }, BN.prototype.ushln = function(bits) {
        return this.clone().iushln(bits);
      }, BN.prototype.shrn = function(bits) {
        return this.clone().ishrn(bits);
      }, BN.prototype.ushrn = function(bits) {
        return this.clone().iushrn(bits);
      }, BN.prototype.testn = function(bit) {
        assert(typeof bit === "number" && bit >= 0);
        var r2 = bit % 26, s = (bit - r2) / 26, q = 1 << r2;
        if (this.length <= s)
          return false;
        var w = this.words[s];
        return !!(w & q);
      }, BN.prototype.imaskn = function(bits) {
        assert(typeof bits === "number" && bits >= 0);
        var r2 = bits % 26, s = (bits - r2) / 26;
        if (assert(this.negative === 0, "imaskn works only with positive numbers"), this.length <= s)
          return this;
        if (r2 !== 0)
          s++;
        if (this.length = Math.min(s, this.length), r2 !== 0) {
          var mask = 67108863 ^ 67108863 >>> r2 << r2;
          this.words[this.length - 1] &= mask;
        }
        return this.strip();
      }, BN.prototype.maskn = function(bits) {
        return this.clone().imaskn(bits);
      }, BN.prototype.iaddn = function(num) {
        if (assert(typeof num === "number"), assert(num < 67108864), num < 0)
          return this.isubn(-num);
        if (this.negative !== 0) {
          if (this.length === 1 && (this.words[0] | 0) < num)
            return this.words[0] = num - (this.words[0] | 0), this.negative = 0, this;
          return this.negative = 0, this.isubn(num), this.negative = 1, this;
        }
        return this._iaddn(num);
      }, BN.prototype._iaddn = function(num) {
        this.words[0] += num;
        for (var i2 = 0;i2 < this.length && this.words[i2] >= 67108864; i2++)
          if (this.words[i2] -= 67108864, i2 === this.length - 1)
            this.words[i2 + 1] = 1;
          else
            this.words[i2 + 1]++;
        return this.length = Math.max(this.length, i2 + 1), this;
      }, BN.prototype.isubn = function(num) {
        if (assert(typeof num === "number"), assert(num < 67108864), num < 0)
          return this.iaddn(-num);
        if (this.negative !== 0)
          return this.negative = 0, this.iaddn(num), this.negative = 1, this;
        if (this.words[0] -= num, this.length === 1 && this.words[0] < 0)
          this.words[0] = -this.words[0], this.negative = 1;
        else
          for (var i2 = 0;i2 < this.length && this.words[i2] < 0; i2++)
            this.words[i2] += 67108864, this.words[i2 + 1] -= 1;
        return this.strip();
      }, BN.prototype.addn = function(num) {
        return this.clone().iaddn(num);
      }, BN.prototype.subn = function(num) {
        return this.clone().isubn(num);
      }, BN.prototype.iabs = function() {
        return this.negative = 0, this;
      }, BN.prototype.abs = function() {
        return this.clone().iabs();
      }, BN.prototype._ishlnsubmul = function(num, mul, shift) {
        var len2 = num.length + shift, i2;
        this._expand(len2);
        var w, carry = 0;
        for (i2 = 0;i2 < num.length; i2++) {
          w = (this.words[i2 + shift] | 0) + carry;
          var right = (num.words[i2] | 0) * mul;
          w -= right & 67108863, carry = (w >> 26) - (right / 67108864 | 0), this.words[i2 + shift] = w & 67108863;
        }
        for (;i2 < this.length - shift; i2++)
          w = (this.words[i2 + shift] | 0) + carry, carry = w >> 26, this.words[i2 + shift] = w & 67108863;
        if (carry === 0)
          return this.strip();
        assert(carry === -1), carry = 0;
        for (i2 = 0;i2 < this.length; i2++)
          w = -(this.words[i2] | 0) + carry, carry = w >> 26, this.words[i2] = w & 67108863;
        return this.negative = 1, this.strip();
      }, BN.prototype._wordDiv = function(num, mode) {
        var shift = this.length - num.length, a2 = this.clone(), b = num, bhi = b.words[b.length - 1] | 0, bhiBits = this._countBits(bhi);
        if (shift = 26 - bhiBits, shift !== 0)
          b = b.ushln(shift), a2.iushln(shift), bhi = b.words[b.length - 1] | 0;
        var m = a2.length - b.length, q;
        if (mode !== "mod") {
          q = new BN(null), q.length = m + 1, q.words = Array(q.length);
          for (var i2 = 0;i2 < q.length; i2++)
            q.words[i2] = 0;
        }
        var diff = a2.clone()._ishlnsubmul(b, 1, m);
        if (diff.negative === 0) {
          if (a2 = diff, q)
            q.words[m] = 1;
        }
        for (var j = m - 1;j >= 0; j--) {
          var qj = (a2.words[b.length + j] | 0) * 67108864 + (a2.words[b.length + j - 1] | 0);
          qj = Math.min(qj / bhi | 0, 67108863), a2._ishlnsubmul(b, qj, j);
          while (a2.negative !== 0)
            if (qj--, a2.negative = 0, a2._ishlnsubmul(b, 1, j), !a2.isZero())
              a2.negative ^= 1;
          if (q)
            q.words[j] = qj;
        }
        if (q)
          q.strip();
        if (a2.strip(), mode !== "div" && shift !== 0)
          a2.iushrn(shift);
        return { div: q || null, mod: a2 };
      }, BN.prototype.divmod = function(num, mode, positive) {
        if (assert(!num.isZero()), this.isZero())
          return { div: new BN(0), mod: new BN(0) };
        var div, mod, res;
        if (this.negative !== 0 && num.negative === 0) {
          if (res = this.neg().divmod(num, mode), mode !== "mod")
            div = res.div.neg();
          if (mode !== "div") {
            if (mod = res.mod.neg(), positive && mod.negative !== 0)
              mod.iadd(num);
          }
          return { div, mod };
        }
        if (this.negative === 0 && num.negative !== 0) {
          if (res = this.divmod(num.neg(), mode), mode !== "mod")
            div = res.div.neg();
          return { div, mod: res.mod };
        }
        if ((this.negative & num.negative) !== 0) {
          if (res = this.neg().divmod(num.neg(), mode), mode !== "div") {
            if (mod = res.mod.neg(), positive && mod.negative !== 0)
              mod.isub(num);
          }
          return { div: res.div, mod };
        }
        if (num.length > this.length || this.cmp(num) < 0)
          return { div: new BN(0), mod: this };
        if (num.length === 1) {
          if (mode === "div")
            return { div: this.divn(num.words[0]), mod: null };
          if (mode === "mod")
            return { div: null, mod: new BN(this.modn(num.words[0])) };
          return { div: this.divn(num.words[0]), mod: new BN(this.modn(num.words[0])) };
        }
        return this._wordDiv(num, mode);
      }, BN.prototype.div = function(num) {
        return this.divmod(num, "div", false).div;
      }, BN.prototype.mod = function(num) {
        return this.divmod(num, "mod", false).mod;
      }, BN.prototype.umod = function(num) {
        return this.divmod(num, "mod", true).mod;
      }, BN.prototype.divRound = function(num) {
        var dm = this.divmod(num);
        if (dm.mod.isZero())
          return dm.div;
        var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod, half = num.ushrn(1), r2 = num.andln(1), cmp = mod.cmp(half);
        if (cmp < 0 || r2 === 1 && cmp === 0)
          return dm.div;
        return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
      }, BN.prototype.modn = function(num) {
        assert(num <= 67108863);
        var p2 = 67108864 % num, acc = 0;
        for (var i2 = this.length - 1;i2 >= 0; i2--)
          acc = (p2 * acc + (this.words[i2] | 0)) % num;
        return acc;
      }, BN.prototype.idivn = function(num) {
        assert(num <= 67108863);
        var carry = 0;
        for (var i2 = this.length - 1;i2 >= 0; i2--) {
          var w = (this.words[i2] | 0) + carry * 67108864;
          this.words[i2] = w / num | 0, carry = w % num;
        }
        return this.strip();
      }, BN.prototype.divn = function(num) {
        return this.clone().idivn(num);
      }, BN.prototype.egcd = function(p2) {
        assert(p2.negative === 0), assert(!p2.isZero());
        var x = this, y = p2.clone();
        if (x.negative !== 0)
          x = x.umod(p2);
        else
          x = x.clone();
        var A = new BN(1), B = new BN(0), C = new BN(0), D = new BN(1), g = 0;
        while (x.isEven() && y.isEven())
          x.iushrn(1), y.iushrn(1), ++g;
        var yp = y.clone(), xp = x.clone();
        while (!x.isZero()) {
          for (var i2 = 0, im = 1;(x.words[0] & im) === 0 && i2 < 26; ++i2, im <<= 1)
            ;
          if (i2 > 0) {
            x.iushrn(i2);
            while (i2-- > 0) {
              if (A.isOdd() || B.isOdd())
                A.iadd(yp), B.isub(xp);
              A.iushrn(1), B.iushrn(1);
            }
          }
          for (var j = 0, jm = 1;(y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1)
            ;
          if (j > 0) {
            y.iushrn(j);
            while (j-- > 0) {
              if (C.isOdd() || D.isOdd())
                C.iadd(yp), D.isub(xp);
              C.iushrn(1), D.iushrn(1);
            }
          }
          if (x.cmp(y) >= 0)
            x.isub(y), A.isub(C), B.isub(D);
          else
            y.isub(x), C.isub(A), D.isub(B);
        }
        return { a: C, b: D, gcd: y.iushln(g) };
      }, BN.prototype._invmp = function(p2) {
        assert(p2.negative === 0), assert(!p2.isZero());
        var a2 = this, b = p2.clone();
        if (a2.negative !== 0)
          a2 = a2.umod(p2);
        else
          a2 = a2.clone();
        var x1 = new BN(1), x2 = new BN(0), delta = b.clone();
        while (a2.cmpn(1) > 0 && b.cmpn(1) > 0) {
          for (var i2 = 0, im = 1;(a2.words[0] & im) === 0 && i2 < 26; ++i2, im <<= 1)
            ;
          if (i2 > 0) {
            a2.iushrn(i2);
            while (i2-- > 0) {
              if (x1.isOdd())
                x1.iadd(delta);
              x1.iushrn(1);
            }
          }
          for (var j = 0, jm = 1;(b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1)
            ;
          if (j > 0) {
            b.iushrn(j);
            while (j-- > 0) {
              if (x2.isOdd())
                x2.iadd(delta);
              x2.iushrn(1);
            }
          }
          if (a2.cmp(b) >= 0)
            a2.isub(b), x1.isub(x2);
          else
            b.isub(a2), x2.isub(x1);
        }
        var res;
        if (a2.cmpn(1) === 0)
          res = x1;
        else
          res = x2;
        if (res.cmpn(0) < 0)
          res.iadd(p2);
        return res;
      }, BN.prototype.gcd = function(num) {
        if (this.isZero())
          return num.abs();
        if (num.isZero())
          return this.abs();
        var a2 = this.clone(), b = num.clone();
        a2.negative = 0, b.negative = 0;
        for (var shift = 0;a2.isEven() && b.isEven(); shift++)
          a2.iushrn(1), b.iushrn(1);
        do {
          while (a2.isEven())
            a2.iushrn(1);
          while (b.isEven())
            b.iushrn(1);
          var r2 = a2.cmp(b);
          if (r2 < 0) {
            var t2 = a2;
            a2 = b, b = t2;
          } else if (r2 === 0 || b.cmpn(1) === 0)
            break;
          a2.isub(b);
        } while (true);
        return b.iushln(shift);
      }, BN.prototype.invm = function(num) {
        return this.egcd(num).a.umod(num);
      }, BN.prototype.isEven = function() {
        return (this.words[0] & 1) === 0;
      }, BN.prototype.isOdd = function() {
        return (this.words[0] & 1) === 1;
      }, BN.prototype.andln = function(num) {
        return this.words[0] & num;
      }, BN.prototype.bincn = function(bit) {
        assert(typeof bit === "number");
        var r2 = bit % 26, s = (bit - r2) / 26, q = 1 << r2;
        if (this.length <= s)
          return this._expand(s + 1), this.words[s] |= q, this;
        var carry = q;
        for (var i2 = s;carry !== 0 && i2 < this.length; i2++) {
          var w = this.words[i2] | 0;
          w += carry, carry = w >>> 26, w &= 67108863, this.words[i2] = w;
        }
        if (carry !== 0)
          this.words[i2] = carry, this.length++;
        return this;
      }, BN.prototype.isZero = function() {
        return this.length === 1 && this.words[0] === 0;
      }, BN.prototype.cmpn = function(num) {
        var negative = num < 0;
        if (this.negative !== 0 && !negative)
          return -1;
        if (this.negative === 0 && negative)
          return 1;
        this.strip();
        var res;
        if (this.length > 1)
          res = 1;
        else {
          if (negative)
            num = -num;
          assert(num <= 67108863, "Number is too big");
          var w = this.words[0] | 0;
          res = w === num ? 0 : w < num ? -1 : 1;
        }
        if (this.negative !== 0)
          return -res | 0;
        return res;
      }, BN.prototype.cmp = function(num) {
        if (this.negative !== 0 && num.negative === 0)
          return -1;
        if (this.negative === 0 && num.negative !== 0)
          return 1;
        var res = this.ucmp(num);
        if (this.negative !== 0)
          return -res | 0;
        return res;
      }, BN.prototype.ucmp = function(num) {
        if (this.length > num.length)
          return 1;
        if (this.length < num.length)
          return -1;
        var res = 0;
        for (var i2 = this.length - 1;i2 >= 0; i2--) {
          var a2 = this.words[i2] | 0, b = num.words[i2] | 0;
          if (a2 === b)
            continue;
          if (a2 < b)
            res = -1;
          else if (a2 > b)
            res = 1;
          break;
        }
        return res;
      }, BN.prototype.gtn = function(num) {
        return this.cmpn(num) === 1;
      }, BN.prototype.gt = function(num) {
        return this.cmp(num) === 1;
      }, BN.prototype.gten = function(num) {
        return this.cmpn(num) >= 0;
      }, BN.prototype.gte = function(num) {
        return this.cmp(num) >= 0;
      }, BN.prototype.ltn = function(num) {
        return this.cmpn(num) === -1;
      }, BN.prototype.lt = function(num) {
        return this.cmp(num) === -1;
      }, BN.prototype.lten = function(num) {
        return this.cmpn(num) <= 0;
      }, BN.prototype.lte = function(num) {
        return this.cmp(num) <= 0;
      }, BN.prototype.eqn = function(num) {
        return this.cmpn(num) === 0;
      }, BN.prototype.eq = function(num) {
        return this.cmp(num) === 0;
      }, BN.red = function(num) {
        return new Red(num);
      }, BN.prototype.toRed = function(ctx) {
        return assert(!this.red, "Already a number in reduction context"), assert(this.negative === 0, "red works only with positives"), ctx.convertTo(this)._forceRed(ctx);
      }, BN.prototype.fromRed = function() {
        return assert(this.red, "fromRed works only with numbers in reduction context"), this.red.convertFrom(this);
      }, BN.prototype._forceRed = function(ctx) {
        return this.red = ctx, this;
      }, BN.prototype.forceRed = function(ctx) {
        return assert(!this.red, "Already a number in reduction context"), this._forceRed(ctx);
      }, BN.prototype.redAdd = function(num) {
        return assert(this.red, "redAdd works only with red numbers"), this.red.add(this, num);
      }, BN.prototype.redIAdd = function(num) {
        return assert(this.red, "redIAdd works only with red numbers"), this.red.iadd(this, num);
      }, BN.prototype.redSub = function(num) {
        return assert(this.red, "redSub works only with red numbers"), this.red.sub(this, num);
      }, BN.prototype.redISub = function(num) {
        return assert(this.red, "redISub works only with red numbers"), this.red.isub(this, num);
      }, BN.prototype.redShl = function(num) {
        return assert(this.red, "redShl works only with red numbers"), this.red.shl(this, num);
      }, BN.prototype.redMul = function(num) {
        return assert(this.red, "redMul works only with red numbers"), this.red._verify2(this, num), this.red.mul(this, num);
      }, BN.prototype.redIMul = function(num) {
        return assert(this.red, "redMul works only with red numbers"), this.red._verify2(this, num), this.red.imul(this, num);
      }, BN.prototype.redSqr = function() {
        return assert(this.red, "redSqr works only with red numbers"), this.red._verify1(this), this.red.sqr(this);
      }, BN.prototype.redISqr = function() {
        return assert(this.red, "redISqr works only with red numbers"), this.red._verify1(this), this.red.isqr(this);
      }, BN.prototype.redSqrt = function() {
        return assert(this.red, "redSqrt works only with red numbers"), this.red._verify1(this), this.red.sqrt(this);
      }, BN.prototype.redInvm = function() {
        return assert(this.red, "redInvm works only with red numbers"), this.red._verify1(this), this.red.invm(this);
      }, BN.prototype.redNeg = function() {
        return assert(this.red, "redNeg works only with red numbers"), this.red._verify1(this), this.red.neg(this);
      }, BN.prototype.redPow = function(num) {
        return assert(this.red && !num.red, "redPow(normalNum)"), this.red._verify1(this), this.red.pow(this, num);
      };
      var primes = { k256: null, p224: null, p192: null, p25519: null };
      function MPrime(name, p2) {
        this.name = name, this.p = new BN(p2, 16), this.n = this.p.bitLength(), this.k = new BN(1).iushln(this.n).isub(this.p), this.tmp = this._tmp();
      }
      MPrime.prototype._tmp = function() {
        var tmp = new BN(null);
        return tmp.words = Array(Math.ceil(this.n / 13)), tmp;
      }, MPrime.prototype.ireduce = function(num) {
        var r2 = num, rlen;
        do
          this.split(r2, this.tmp), r2 = this.imulK(r2), r2 = r2.iadd(this.tmp), rlen = r2.bitLength();
        while (rlen > this.n);
        var cmp = rlen < this.n ? -1 : r2.ucmp(this.p);
        if (cmp === 0)
          r2.words[0] = 0, r2.length = 1;
        else if (cmp > 0)
          r2.isub(this.p);
        else if (r2.strip !== undefined)
          r2.strip();
        else
          r2._strip();
        return r2;
      }, MPrime.prototype.split = function(input, out) {
        input.iushrn(this.n, 0, out);
      }, MPrime.prototype.imulK = function(num) {
        return num.imul(this.k);
      };
      function K256() {
        MPrime.call(this, "k256", "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f");
      }
      inherits2(K256, MPrime), K256.prototype.split = function(input, output) {
        var mask = 4194303, outLen = Math.min(input.length, 9);
        for (var i2 = 0;i2 < outLen; i2++)
          output.words[i2] = input.words[i2];
        if (output.length = outLen, input.length <= 9) {
          input.words[0] = 0, input.length = 1;
          return;
        }
        var prev = input.words[9];
        output.words[output.length++] = prev & mask;
        for (i2 = 10;i2 < input.length; i2++) {
          var next = input.words[i2] | 0;
          input.words[i2 - 10] = (next & mask) << 4 | prev >>> 22, prev = next;
        }
        if (prev >>>= 22, input.words[i2 - 10] = prev, prev === 0 && input.length > 10)
          input.length -= 10;
        else
          input.length -= 9;
      }, K256.prototype.imulK = function(num) {
        num.words[num.length] = 0, num.words[num.length + 1] = 0, num.length += 2;
        var lo = 0;
        for (var i2 = 0;i2 < num.length; i2++) {
          var w = num.words[i2] | 0;
          lo += w * 977, num.words[i2] = lo & 67108863, lo = w * 64 + (lo / 67108864 | 0);
        }
        if (num.words[num.length - 1] === 0) {
          if (num.length--, num.words[num.length - 1] === 0)
            num.length--;
        }
        return num;
      };
      function P224() {
        MPrime.call(this, "p224", "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001");
      }
      inherits2(P224, MPrime);
      function P192() {
        MPrime.call(this, "p192", "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff");
      }
      inherits2(P192, MPrime);
      function P25519() {
        MPrime.call(this, "25519", "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed");
      }
      inherits2(P25519, MPrime), P25519.prototype.imulK = function(num) {
        var carry = 0;
        for (var i2 = 0;i2 < num.length; i2++) {
          var hi = (num.words[i2] | 0) * 19 + carry, lo = hi & 67108863;
          hi >>>= 26, num.words[i2] = lo, carry = hi;
        }
        if (carry !== 0)
          num.words[num.length++] = carry;
        return num;
      }, BN._prime = function(name) {
        if (primes[name])
          return primes[name];
        var prime;
        if (name === "k256")
          prime = new K256;
        else if (name === "p224")
          prime = new P224;
        else if (name === "p192")
          prime = new P192;
        else if (name === "p25519")
          prime = new P25519;
        else
          throw Error("Unknown prime " + name);
        return primes[name] = prime, prime;
      };
      function Red(m) {
        if (typeof m === "string") {
          var prime = BN._prime(m);
          this.m = prime.p, this.prime = prime;
        } else
          assert(m.gtn(1), "modulus must be greater than 1"), this.m = m, this.prime = null;
      }
      Red.prototype._verify1 = function(a2) {
        assert(a2.negative === 0, "red works only with positives"), assert(a2.red, "red works only with red numbers");
      }, Red.prototype._verify2 = function(a2, b) {
        assert((a2.negative | b.negative) === 0, "red works only with positives"), assert(a2.red && a2.red === b.red, "red works only with red numbers");
      }, Red.prototype.imod = function(a2) {
        if (this.prime)
          return this.prime.ireduce(a2)._forceRed(this);
        return a2.umod(this.m)._forceRed(this);
      }, Red.prototype.neg = function(a2) {
        if (a2.isZero())
          return a2.clone();
        return this.m.sub(a2)._forceRed(this);
      }, Red.prototype.add = function(a2, b) {
        this._verify2(a2, b);
        var res = a2.add(b);
        if (res.cmp(this.m) >= 0)
          res.isub(this.m);
        return res._forceRed(this);
      }, Red.prototype.iadd = function(a2, b) {
        this._verify2(a2, b);
        var res = a2.iadd(b);
        if (res.cmp(this.m) >= 0)
          res.isub(this.m);
        return res;
      }, Red.prototype.sub = function(a2, b) {
        this._verify2(a2, b);
        var res = a2.sub(b);
        if (res.cmpn(0) < 0)
          res.iadd(this.m);
        return res._forceRed(this);
      }, Red.prototype.isub = function(a2, b) {
        this._verify2(a2, b);
        var res = a2.isub(b);
        if (res.cmpn(0) < 0)
          res.iadd(this.m);
        return res;
      }, Red.prototype.shl = function(a2, num) {
        return this._verify1(a2), this.imod(a2.ushln(num));
      }, Red.prototype.imul = function(a2, b) {
        return this._verify2(a2, b), this.imod(a2.imul(b));
      }, Red.prototype.mul = function(a2, b) {
        return this._verify2(a2, b), this.imod(a2.mul(b));
      }, Red.prototype.isqr = function(a2) {
        return this.imul(a2, a2.clone());
      }, Red.prototype.sqr = function(a2) {
        return this.mul(a2, a2);
      }, Red.prototype.sqrt = function(a2) {
        if (a2.isZero())
          return a2.clone();
        var mod3 = this.m.andln(3);
        if (assert(mod3 % 2 === 1), mod3 === 3) {
          var pow = this.m.add(new BN(1)).iushrn(2);
          return this.pow(a2, pow);
        }
        var q = this.m.subn(1), s = 0;
        while (!q.isZero() && q.andln(1) === 0)
          s++, q.iushrn(1);
        assert(!q.isZero());
        var one = new BN(1).toRed(this), nOne = one.redNeg(), lpow = this.m.subn(1).iushrn(1), z = this.m.bitLength();
        z = new BN(2 * z * z).toRed(this);
        while (this.pow(z, lpow).cmp(nOne) !== 0)
          z.redIAdd(nOne);
        var c2 = this.pow(z, q), r2 = this.pow(a2, q.addn(1).iushrn(1)), t2 = this.pow(a2, q), m = s;
        while (t2.cmp(one) !== 0) {
          var tmp = t2;
          for (var i2 = 0;tmp.cmp(one) !== 0; i2++)
            tmp = tmp.redSqr();
          assert(i2 < m);
          var b = this.pow(c2, new BN(1).iushln(m - i2 - 1));
          r2 = r2.redMul(b), c2 = b.redSqr(), t2 = t2.redMul(c2), m = i2;
        }
        return r2;
      }, Red.prototype.invm = function(a2) {
        var inv = a2._invmp(this.m);
        if (inv.negative !== 0)
          return inv.negative = 0, this.imod(inv).redNeg();
        else
          return this.imod(inv);
      }, Red.prototype.pow = function(a2, num) {
        if (num.isZero())
          return new BN(1).toRed(this);
        if (num.cmpn(1) === 0)
          return a2.clone();
        var windowSize = 4, wnd = Array(1 << windowSize);
        wnd[0] = new BN(1).toRed(this), wnd[1] = a2;
        for (var i2 = 2;i2 < wnd.length; i2++)
          wnd[i2] = this.mul(wnd[i2 - 1], a2);
        var res = wnd[0], current = 0, currentLen = 0, start = num.bitLength() % 26;
        if (start === 0)
          start = 26;
        for (i2 = num.length - 1;i2 >= 0; i2--) {
          var word = num.words[i2];
          for (var j = start - 1;j >= 0; j--) {
            var bit = word >> j & 1;
            if (res !== wnd[0])
              res = this.sqr(res);
            if (bit === 0 && current === 0) {
              currentLen = 0;
              continue;
            }
            if (current <<= 1, current |= bit, currentLen++, currentLen !== windowSize && (i2 !== 0 || j !== 0))
              continue;
            res = this.mul(res, wnd[current]), currentLen = 0, current = 0;
          }
          start = 26;
        }
        return res;
      }, Red.prototype.convertTo = function(num) {
        var r2 = num.umod(this.m);
        return r2 === num ? r2.clone() : r2;
      }, Red.prototype.convertFrom = function(num) {
        var res = num.clone();
        return res.red = null, res;
      }, BN.mont = function(num) {
        return new Mont(num);
      };
      function Mont(m) {
        if (Red.call(this, m), this.shift = this.m.bitLength(), this.shift % 26 !== 0)
          this.shift += 26 - this.shift % 26;
        this.r = new BN(1).iushln(this.shift), this.r2 = this.imod(this.r.sqr()), this.rinv = this.r._invmp(this.m), this.minv = this.rinv.mul(this.r).isubn(1).div(this.m), this.minv = this.minv.umod(this.r), this.minv = this.r.sub(this.minv);
      }
      inherits2(Mont, Red), Mont.prototype.convertTo = function(num) {
        return this.imod(num.ushln(this.shift));
      }, Mont.prototype.convertFrom = function(num) {
        var r2 = this.imod(num.mul(this.rinv));
        return r2.red = null, r2;
      }, Mont.prototype.imul = function(a2, b) {
        if (a2.isZero() || b.isZero())
          return a2.words[0] = 0, a2.length = 1, a2;
        var t2 = a2.imul(b), c2 = t2.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), u = t2.isub(c2).iushrn(this.shift), res = u;
        if (u.cmp(this.m) >= 0)
          res = u.isub(this.m);
        else if (u.cmpn(0) < 0)
          res = u.iadd(this.m);
        return res._forceRed(this);
      }, Mont.prototype.mul = function(a2, b) {
        if (a2.isZero() || b.isZero())
          return new BN(0)._forceRed(this);
        var t2 = a2.mul(b), c2 = t2.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), u = t2.isub(c2).iushrn(this.shift), res = u;
        if (u.cmp(this.m) >= 0)
          res = u.isub(this.m);
        else if (u.cmpn(0) < 0)
          res = u.iadd(this.m);
        return res._forceRed(this);
      }, Mont.prototype.invm = function(a2) {
        var res = this.imod(a2._invmp(this.m).mul(this.r2));
        return res._forceRed(this);
      };
    })(typeof module > "u" || module, exports);
  });
  require_withPublic = __commonJS2((exports, module) => {
    var BN = require_bn4(), Buffer22 = require_safe_buffer().Buffer;
    function withPublic(paddedMsg, key) {
      return Buffer22.from(paddedMsg.toRed(BN.mont(key.modulus)).redPow(new BN(key.publicExponent)).fromRed().toArray());
    }
    module.exports = withPublic;
  });
  require_bn5 = __commonJS2((exports, module) => {
    (function(module2, exports2) {
      function assert(val, msg) {
        if (!val)
          throw Error(msg || "Assertion failed");
      }
      function inherits2(ctor, superCtor) {
        ctor.super_ = superCtor;
        var TempCtor = function() {};
        TempCtor.prototype = superCtor.prototype, ctor.prototype = new TempCtor, ctor.prototype.constructor = ctor;
      }
      function BN(number, base, endian) {
        if (BN.isBN(number))
          return number;
        if (this.negative = 0, this.words = null, this.length = 0, this.red = null, number !== null) {
          if (base === "le" || base === "be")
            endian = base, base = 10;
          this._init(number || 0, base || 10, endian || "be");
        }
      }
      if (typeof module2 === "object")
        module2.exports = BN;
      else
        exports2.BN = BN;
      BN.BN = BN, BN.wordSize = 26;
      var Buffer22;
      try {
        if (typeof window < "u" && typeof window.Buffer < "u")
          Buffer22 = window.Buffer;
        else
          Buffer22 = (init_buffer(), __toCommonJS(exports_buffer)).Buffer;
      } catch (e2) {}
      BN.isBN = function(num) {
        if (num instanceof BN)
          return true;
        return num !== null && typeof num === "object" && num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
      }, BN.max = function(left, right) {
        if (left.cmp(right) > 0)
          return left;
        return right;
      }, BN.min = function(left, right) {
        if (left.cmp(right) < 0)
          return left;
        return right;
      }, BN.prototype._init = function(number, base, endian) {
        if (typeof number === "number")
          return this._initNumber(number, base, endian);
        if (typeof number === "object")
          return this._initArray(number, base, endian);
        if (base === "hex")
          base = 16;
        assert(base === (base | 0) && base >= 2 && base <= 36), number = number.toString().replace(/\s+/g, "");
        var start = 0;
        if (number[0] === "-")
          start++, this.negative = 1;
        if (start < number.length) {
          if (base === 16)
            this._parseHex(number, start, endian);
          else if (this._parseBase(number, base, start), endian === "le")
            this._initArray(this.toArray(), base, endian);
        }
      }, BN.prototype._initNumber = function(number, base, endian) {
        if (number < 0)
          this.negative = 1, number = -number;
        if (number < 67108864)
          this.words = [number & 67108863], this.length = 1;
        else if (number < 4503599627370496)
          this.words = [number & 67108863, number / 67108864 & 67108863], this.length = 2;
        else
          assert(number < 9007199254740992), this.words = [number & 67108863, number / 67108864 & 67108863, 1], this.length = 3;
        if (endian !== "le")
          return;
        this._initArray(this.toArray(), base, endian);
      }, BN.prototype._initArray = function(number, base, endian) {
        if (assert(typeof number.length === "number"), number.length <= 0)
          return this.words = [0], this.length = 1, this;
        this.length = Math.ceil(number.length / 3), this.words = Array(this.length);
        for (var i2 = 0;i2 < this.length; i2++)
          this.words[i2] = 0;
        var j, w, off = 0;
        if (endian === "be") {
          for (i2 = number.length - 1, j = 0;i2 >= 0; i2 -= 3)
            if (w = number[i2] | number[i2 - 1] << 8 | number[i2 - 2] << 16, this.words[j] |= w << off & 67108863, this.words[j + 1] = w >>> 26 - off & 67108863, off += 24, off >= 26)
              off -= 26, j++;
        } else if (endian === "le") {
          for (i2 = 0, j = 0;i2 < number.length; i2 += 3)
            if (w = number[i2] | number[i2 + 1] << 8 | number[i2 + 2] << 16, this.words[j] |= w << off & 67108863, this.words[j + 1] = w >>> 26 - off & 67108863, off += 24, off >= 26)
              off -= 26, j++;
        }
        return this._strip();
      };
      function parseHex4Bits(string, index) {
        var c2 = string.charCodeAt(index);
        if (c2 >= 48 && c2 <= 57)
          return c2 - 48;
        else if (c2 >= 65 && c2 <= 70)
          return c2 - 55;
        else if (c2 >= 97 && c2 <= 102)
          return c2 - 87;
        else
          assert(false, "Invalid character in " + string);
      }
      function parseHexByte(string, lowerBound, index) {
        var r2 = parseHex4Bits(string, index);
        if (index - 1 >= lowerBound)
          r2 |= parseHex4Bits(string, index - 1) << 4;
        return r2;
      }
      BN.prototype._parseHex = function(number, start, endian) {
        this.length = Math.ceil((number.length - start) / 6), this.words = Array(this.length);
        for (var i2 = 0;i2 < this.length; i2++)
          this.words[i2] = 0;
        var off = 0, j = 0, w;
        if (endian === "be")
          for (i2 = number.length - 1;i2 >= start; i2 -= 2)
            if (w = parseHexByte(number, start, i2) << off, this.words[j] |= w & 67108863, off >= 18)
              off -= 18, j += 1, this.words[j] |= w >>> 26;
            else
              off += 8;
        else {
          var parseLength = number.length - start;
          for (i2 = parseLength % 2 === 0 ? start + 1 : start;i2 < number.length; i2 += 2)
            if (w = parseHexByte(number, start, i2) << off, this.words[j] |= w & 67108863, off >= 18)
              off -= 18, j += 1, this.words[j] |= w >>> 26;
            else
              off += 8;
        }
        this._strip();
      };
      function parseBase(str, start, end, mul) {
        var r2 = 0, b = 0, len2 = Math.min(str.length, end);
        for (var i2 = start;i2 < len2; i2++) {
          var c2 = str.charCodeAt(i2) - 48;
          if (r2 *= mul, c2 >= 49)
            b = c2 - 49 + 10;
          else if (c2 >= 17)
            b = c2 - 17 + 10;
          else
            b = c2;
          assert(c2 >= 0 && b < mul, "Invalid character"), r2 += b;
        }
        return r2;
      }
      BN.prototype._parseBase = function(number, base, start) {
        this.words = [0], this.length = 1;
        for (var limbLen = 0, limbPow = 1;limbPow <= 67108863; limbPow *= base)
          limbLen++;
        limbLen--, limbPow = limbPow / base | 0;
        var total = number.length - start, mod = total % limbLen, end = Math.min(total, total - mod) + start, word = 0;
        for (var i2 = start;i2 < end; i2 += limbLen)
          if (word = parseBase(number, i2, i2 + limbLen, base), this.imuln(limbPow), this.words[0] + word < 67108864)
            this.words[0] += word;
          else
            this._iaddn(word);
        if (mod !== 0) {
          var pow = 1;
          word = parseBase(number, i2, number.length, base);
          for (i2 = 0;i2 < mod; i2++)
            pow *= base;
          if (this.imuln(pow), this.words[0] + word < 67108864)
            this.words[0] += word;
          else
            this._iaddn(word);
        }
        this._strip();
      }, BN.prototype.copy = function(dest) {
        dest.words = Array(this.length);
        for (var i2 = 0;i2 < this.length; i2++)
          dest.words[i2] = this.words[i2];
        dest.length = this.length, dest.negative = this.negative, dest.red = this.red;
      };
      function move(dest, src) {
        dest.words = src.words, dest.length = src.length, dest.negative = src.negative, dest.red = src.red;
      }
      if (BN.prototype._move = function(dest) {
        move(dest, this);
      }, BN.prototype.clone = function() {
        var r2 = new BN(null);
        return this.copy(r2), r2;
      }, BN.prototype._expand = function(size) {
        while (this.length < size)
          this.words[this.length++] = 0;
        return this;
      }, BN.prototype._strip = function() {
        while (this.length > 1 && this.words[this.length - 1] === 0)
          this.length--;
        return this._normSign();
      }, BN.prototype._normSign = function() {
        if (this.length === 1 && this.words[0] === 0)
          this.negative = 0;
        return this;
      }, typeof Symbol < "u" && typeof Symbol.for === "function")
        try {
          BN.prototype[Symbol.for("nodejs.util.inspect.custom")] = inspect2;
        } catch (e2) {
          BN.prototype.inspect = inspect2;
        }
      else
        BN.prototype.inspect = inspect2;
      function inspect2() {
        return (this.red ? "<BN-R: " : "<BN: ") + this.toString(16) + ">";
      }
      var zeros = ["", "0", "00", "000", "0000", "00000", "000000", "0000000", "00000000", "000000000", "0000000000", "00000000000", "000000000000", "0000000000000", "00000000000000", "000000000000000", "0000000000000000", "00000000000000000", "000000000000000000", "0000000000000000000", "00000000000000000000", "000000000000000000000", "0000000000000000000000", "00000000000000000000000", "000000000000000000000000", "0000000000000000000000000"], groupSizes = [0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5], groupBases = [0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 1e7, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176];
      if (BN.prototype.toString = function(base, padding) {
        base = base || 10, padding = padding | 0 || 1;
        var out;
        if (base === 16 || base === "hex") {
          out = "";
          var off = 0, carry = 0;
          for (var i2 = 0;i2 < this.length; i2++) {
            var w = this.words[i2], word = ((w << off | carry) & 16777215).toString(16);
            if (carry = w >>> 24 - off & 16777215, off += 2, off >= 26)
              off -= 26, i2--;
            if (carry !== 0 || i2 !== this.length - 1)
              out = zeros[6 - word.length] + word + out;
            else
              out = word + out;
          }
          if (carry !== 0)
            out = carry.toString(16) + out;
          while (out.length % padding !== 0)
            out = "0" + out;
          if (this.negative !== 0)
            out = "-" + out;
          return out;
        }
        if (base === (base | 0) && base >= 2 && base <= 36) {
          var groupSize = groupSizes[base], groupBase = groupBases[base];
          out = "";
          var c2 = this.clone();
          c2.negative = 0;
          while (!c2.isZero()) {
            var r2 = c2.modrn(groupBase).toString(base);
            if (c2 = c2.idivn(groupBase), !c2.isZero())
              out = zeros[groupSize - r2.length] + r2 + out;
            else
              out = r2 + out;
          }
          if (this.isZero())
            out = "0" + out;
          while (out.length % padding !== 0)
            out = "0" + out;
          if (this.negative !== 0)
            out = "-" + out;
          return out;
        }
        assert(false, "Base should be between 2 and 36");
      }, BN.prototype.toNumber = function() {
        var ret = this.words[0];
        if (this.length === 2)
          ret += this.words[1] * 67108864;
        else if (this.length === 3 && this.words[2] === 1)
          ret += 4503599627370496 + this.words[1] * 67108864;
        else if (this.length > 2)
          assert(false, "Number can only safely store up to 53 bits");
        return this.negative !== 0 ? -ret : ret;
      }, BN.prototype.toJSON = function() {
        return this.toString(16, 2);
      }, Buffer22)
        BN.prototype.toBuffer = function(endian, length) {
          return this.toArrayLike(Buffer22, endian, length);
        };
      BN.prototype.toArray = function(endian, length) {
        return this.toArrayLike(Array, endian, length);
      };
      var allocate = function(ArrayType, size) {
        if (ArrayType.allocUnsafe)
          return ArrayType.allocUnsafe(size);
        return new ArrayType(size);
      };
      if (BN.prototype.toArrayLike = function(ArrayType, endian, length) {
        this._strip();
        var byteLength2 = this.byteLength(), reqLength = length || Math.max(1, byteLength2);
        assert(byteLength2 <= reqLength, "byte array longer than desired length"), assert(reqLength > 0, "Requested array length <= 0");
        var res = allocate(ArrayType, reqLength), postfix = endian === "le" ? "LE" : "BE";
        return this["_toArrayLike" + postfix](res, byteLength2), res;
      }, BN.prototype._toArrayLikeLE = function(res, byteLength2) {
        var position = 0, carry = 0;
        for (var i2 = 0, shift = 0;i2 < this.length; i2++) {
          var word = this.words[i2] << shift | carry;
          if (res[position++] = word & 255, position < res.length)
            res[position++] = word >> 8 & 255;
          if (position < res.length)
            res[position++] = word >> 16 & 255;
          if (shift === 6) {
            if (position < res.length)
              res[position++] = word >> 24 & 255;
            carry = 0, shift = 0;
          } else
            carry = word >>> 24, shift += 2;
        }
        if (position < res.length) {
          res[position++] = carry;
          while (position < res.length)
            res[position++] = 0;
        }
      }, BN.prototype._toArrayLikeBE = function(res, byteLength2) {
        var position = res.length - 1, carry = 0;
        for (var i2 = 0, shift = 0;i2 < this.length; i2++) {
          var word = this.words[i2] << shift | carry;
          if (res[position--] = word & 255, position >= 0)
            res[position--] = word >> 8 & 255;
          if (position >= 0)
            res[position--] = word >> 16 & 255;
          if (shift === 6) {
            if (position >= 0)
              res[position--] = word >> 24 & 255;
            carry = 0, shift = 0;
          } else
            carry = word >>> 24, shift += 2;
        }
        if (position >= 0) {
          res[position--] = carry;
          while (position >= 0)
            res[position--] = 0;
        }
      }, Math.clz32)
        BN.prototype._countBits = function(w) {
          return 32 - Math.clz32(w);
        };
      else
        BN.prototype._countBits = function(w) {
          var t2 = w, r2 = 0;
          if (t2 >= 4096)
            r2 += 13, t2 >>>= 13;
          if (t2 >= 64)
            r2 += 7, t2 >>>= 7;
          if (t2 >= 8)
            r2 += 4, t2 >>>= 4;
          if (t2 >= 2)
            r2 += 2, t2 >>>= 2;
          return r2 + t2;
        };
      BN.prototype._zeroBits = function(w) {
        if (w === 0)
          return 26;
        var t2 = w, r2 = 0;
        if ((t2 & 8191) === 0)
          r2 += 13, t2 >>>= 13;
        if ((t2 & 127) === 0)
          r2 += 7, t2 >>>= 7;
        if ((t2 & 15) === 0)
          r2 += 4, t2 >>>= 4;
        if ((t2 & 3) === 0)
          r2 += 2, t2 >>>= 2;
        if ((t2 & 1) === 0)
          r2++;
        return r2;
      }, BN.prototype.bitLength = function() {
        var w = this.words[this.length - 1], hi = this._countBits(w);
        return (this.length - 1) * 26 + hi;
      };
      function toBitArray(num) {
        var w = Array(num.bitLength());
        for (var bit = 0;bit < w.length; bit++) {
          var off = bit / 26 | 0, wbit = bit % 26;
          w[bit] = num.words[off] >>> wbit & 1;
        }
        return w;
      }
      BN.prototype.zeroBits = function() {
        if (this.isZero())
          return 0;
        var r2 = 0;
        for (var i2 = 0;i2 < this.length; i2++) {
          var b = this._zeroBits(this.words[i2]);
          if (r2 += b, b !== 26)
            break;
        }
        return r2;
      }, BN.prototype.byteLength = function() {
        return Math.ceil(this.bitLength() / 8);
      }, BN.prototype.toTwos = function(width) {
        if (this.negative !== 0)
          return this.abs().inotn(width).iaddn(1);
        return this.clone();
      }, BN.prototype.fromTwos = function(width) {
        if (this.testn(width - 1))
          return this.notn(width).iaddn(1).ineg();
        return this.clone();
      }, BN.prototype.isNeg = function() {
        return this.negative !== 0;
      }, BN.prototype.neg = function() {
        return this.clone().ineg();
      }, BN.prototype.ineg = function() {
        if (!this.isZero())
          this.negative ^= 1;
        return this;
      }, BN.prototype.iuor = function(num) {
        while (this.length < num.length)
          this.words[this.length++] = 0;
        for (var i2 = 0;i2 < num.length; i2++)
          this.words[i2] = this.words[i2] | num.words[i2];
        return this._strip();
      }, BN.prototype.ior = function(num) {
        return assert((this.negative | num.negative) === 0), this.iuor(num);
      }, BN.prototype.or = function(num) {
        if (this.length > num.length)
          return this.clone().ior(num);
        return num.clone().ior(this);
      }, BN.prototype.uor = function(num) {
        if (this.length > num.length)
          return this.clone().iuor(num);
        return num.clone().iuor(this);
      }, BN.prototype.iuand = function(num) {
        var b;
        if (this.length > num.length)
          b = num;
        else
          b = this;
        for (var i2 = 0;i2 < b.length; i2++)
          this.words[i2] = this.words[i2] & num.words[i2];
        return this.length = b.length, this._strip();
      }, BN.prototype.iand = function(num) {
        return assert((this.negative | num.negative) === 0), this.iuand(num);
      }, BN.prototype.and = function(num) {
        if (this.length > num.length)
          return this.clone().iand(num);
        return num.clone().iand(this);
      }, BN.prototype.uand = function(num) {
        if (this.length > num.length)
          return this.clone().iuand(num);
        return num.clone().iuand(this);
      }, BN.prototype.iuxor = function(num) {
        var a2, b;
        if (this.length > num.length)
          a2 = this, b = num;
        else
          a2 = num, b = this;
        for (var i2 = 0;i2 < b.length; i2++)
          this.words[i2] = a2.words[i2] ^ b.words[i2];
        if (this !== a2)
          for (;i2 < a2.length; i2++)
            this.words[i2] = a2.words[i2];
        return this.length = a2.length, this._strip();
      }, BN.prototype.ixor = function(num) {
        return assert((this.negative | num.negative) === 0), this.iuxor(num);
      }, BN.prototype.xor = function(num) {
        if (this.length > num.length)
          return this.clone().ixor(num);
        return num.clone().ixor(this);
      }, BN.prototype.uxor = function(num) {
        if (this.length > num.length)
          return this.clone().iuxor(num);
        return num.clone().iuxor(this);
      }, BN.prototype.inotn = function(width) {
        assert(typeof width === "number" && width >= 0);
        var bytesNeeded = Math.ceil(width / 26) | 0, bitsLeft = width % 26;
        if (this._expand(bytesNeeded), bitsLeft > 0)
          bytesNeeded--;
        for (var i2 = 0;i2 < bytesNeeded; i2++)
          this.words[i2] = ~this.words[i2] & 67108863;
        if (bitsLeft > 0)
          this.words[i2] = ~this.words[i2] & 67108863 >> 26 - bitsLeft;
        return this._strip();
      }, BN.prototype.notn = function(width) {
        return this.clone().inotn(width);
      }, BN.prototype.setn = function(bit, val) {
        assert(typeof bit === "number" && bit >= 0);
        var off = bit / 26 | 0, wbit = bit % 26;
        if (this._expand(off + 1), val)
          this.words[off] = this.words[off] | 1 << wbit;
        else
          this.words[off] = this.words[off] & ~(1 << wbit);
        return this._strip();
      }, BN.prototype.iadd = function(num) {
        var r2;
        if (this.negative !== 0 && num.negative === 0)
          return this.negative = 0, r2 = this.isub(num), this.negative ^= 1, this._normSign();
        else if (this.negative === 0 && num.negative !== 0)
          return num.negative = 0, r2 = this.isub(num), num.negative = 1, r2._normSign();
        var a2, b;
        if (this.length > num.length)
          a2 = this, b = num;
        else
          a2 = num, b = this;
        var carry = 0;
        for (var i2 = 0;i2 < b.length; i2++)
          r2 = (a2.words[i2] | 0) + (b.words[i2] | 0) + carry, this.words[i2] = r2 & 67108863, carry = r2 >>> 26;
        for (;carry !== 0 && i2 < a2.length; i2++)
          r2 = (a2.words[i2] | 0) + carry, this.words[i2] = r2 & 67108863, carry = r2 >>> 26;
        if (this.length = a2.length, carry !== 0)
          this.words[this.length] = carry, this.length++;
        else if (a2 !== this)
          for (;i2 < a2.length; i2++)
            this.words[i2] = a2.words[i2];
        return this;
      }, BN.prototype.add = function(num) {
        var res;
        if (num.negative !== 0 && this.negative === 0)
          return num.negative = 0, res = this.sub(num), num.negative ^= 1, res;
        else if (num.negative === 0 && this.negative !== 0)
          return this.negative = 0, res = num.sub(this), this.negative = 1, res;
        if (this.length > num.length)
          return this.clone().iadd(num);
        return num.clone().iadd(this);
      }, BN.prototype.isub = function(num) {
        if (num.negative !== 0) {
          num.negative = 0;
          var r2 = this.iadd(num);
          return num.negative = 1, r2._normSign();
        } else if (this.negative !== 0)
          return this.negative = 0, this.iadd(num), this.negative = 1, this._normSign();
        var cmp = this.cmp(num);
        if (cmp === 0)
          return this.negative = 0, this.length = 1, this.words[0] = 0, this;
        var a2, b;
        if (cmp > 0)
          a2 = this, b = num;
        else
          a2 = num, b = this;
        var carry = 0;
        for (var i2 = 0;i2 < b.length; i2++)
          r2 = (a2.words[i2] | 0) - (b.words[i2] | 0) + carry, carry = r2 >> 26, this.words[i2] = r2 & 67108863;
        for (;carry !== 0 && i2 < a2.length; i2++)
          r2 = (a2.words[i2] | 0) + carry, carry = r2 >> 26, this.words[i2] = r2 & 67108863;
        if (carry === 0 && i2 < a2.length && a2 !== this)
          for (;i2 < a2.length; i2++)
            this.words[i2] = a2.words[i2];
        if (this.length = Math.max(this.length, i2), a2 !== this)
          this.negative = 1;
        return this._strip();
      }, BN.prototype.sub = function(num) {
        return this.clone().isub(num);
      };
      function smallMulTo(self2, num, out) {
        out.negative = num.negative ^ self2.negative;
        var len2 = self2.length + num.length | 0;
        out.length = len2, len2 = len2 - 1 | 0;
        var a2 = self2.words[0] | 0, b = num.words[0] | 0, r2 = a2 * b, lo = r2 & 67108863, carry = r2 / 67108864 | 0;
        out.words[0] = lo;
        for (var k = 1;k < len2; k++) {
          var ncarry = carry >>> 26, rword = carry & 67108863, maxJ = Math.min(k, num.length - 1);
          for (var j = Math.max(0, k - self2.length + 1);j <= maxJ; j++) {
            var i2 = k - j | 0;
            a2 = self2.words[i2] | 0, b = num.words[j] | 0, r2 = a2 * b + rword, ncarry += r2 / 67108864 | 0, rword = r2 & 67108863;
          }
          out.words[k] = rword | 0, carry = ncarry | 0;
        }
        if (carry !== 0)
          out.words[k] = carry | 0;
        else
          out.length--;
        return out._strip();
      }
      var comb10MulTo = function(self2, num, out) {
        var a2 = self2.words, b = num.words, o2 = out.words, c2 = 0, lo, mid, hi, a0 = a2[0] | 0, al0 = a0 & 8191, ah0 = a0 >>> 13, a1 = a2[1] | 0, al1 = a1 & 8191, ah1 = a1 >>> 13, a22 = a2[2] | 0, al2 = a22 & 8191, ah2 = a22 >>> 13, a3 = a2[3] | 0, al3 = a3 & 8191, ah3 = a3 >>> 13, a4 = a2[4] | 0, al4 = a4 & 8191, ah4 = a4 >>> 13, a5 = a2[5] | 0, al5 = a5 & 8191, ah5 = a5 >>> 13, a6 = a2[6] | 0, al6 = a6 & 8191, ah6 = a6 >>> 13, a7 = a2[7] | 0, al7 = a7 & 8191, ah7 = a7 >>> 13, a8 = a2[8] | 0, al8 = a8 & 8191, ah8 = a8 >>> 13, a9 = a2[9] | 0, al9 = a9 & 8191, ah9 = a9 >>> 13, b0 = b[0] | 0, bl0 = b0 & 8191, bh0 = b0 >>> 13, b1 = b[1] | 0, bl1 = b1 & 8191, bh1 = b1 >>> 13, b2 = b[2] | 0, bl2 = b2 & 8191, bh2 = b2 >>> 13, b3 = b[3] | 0, bl3 = b3 & 8191, bh3 = b3 >>> 13, b4 = b[4] | 0, bl4 = b4 & 8191, bh4 = b4 >>> 13, b5 = b[5] | 0, bl5 = b5 & 8191, bh5 = b5 >>> 13, b6 = b[6] | 0, bl6 = b6 & 8191, bh6 = b6 >>> 13, b7 = b[7] | 0, bl7 = b7 & 8191, bh7 = b7 >>> 13, b8 = b[8] | 0, bl8 = b8 & 8191, bh8 = b8 >>> 13, b9 = b[9] | 0, bl9 = b9 & 8191, bh9 = b9 >>> 13;
        out.negative = self2.negative ^ num.negative, out.length = 19, lo = Math.imul(al0, bl0), mid = Math.imul(al0, bh0), mid = mid + Math.imul(ah0, bl0) | 0, hi = Math.imul(ah0, bh0);
        var w0 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w0 >>> 26) | 0, w0 &= 67108863, lo = Math.imul(al1, bl0), mid = Math.imul(al1, bh0), mid = mid + Math.imul(ah1, bl0) | 0, hi = Math.imul(ah1, bh0), lo = lo + Math.imul(al0, bl1) | 0, mid = mid + Math.imul(al0, bh1) | 0, mid = mid + Math.imul(ah0, bl1) | 0, hi = hi + Math.imul(ah0, bh1) | 0;
        var w1 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w1 >>> 26) | 0, w1 &= 67108863, lo = Math.imul(al2, bl0), mid = Math.imul(al2, bh0), mid = mid + Math.imul(ah2, bl0) | 0, hi = Math.imul(ah2, bh0), lo = lo + Math.imul(al1, bl1) | 0, mid = mid + Math.imul(al1, bh1) | 0, mid = mid + Math.imul(ah1, bl1) | 0, hi = hi + Math.imul(ah1, bh1) | 0, lo = lo + Math.imul(al0, bl2) | 0, mid = mid + Math.imul(al0, bh2) | 0, mid = mid + Math.imul(ah0, bl2) | 0, hi = hi + Math.imul(ah0, bh2) | 0;
        var w2 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w2 >>> 26) | 0, w2 &= 67108863, lo = Math.imul(al3, bl0), mid = Math.imul(al3, bh0), mid = mid + Math.imul(ah3, bl0) | 0, hi = Math.imul(ah3, bh0), lo = lo + Math.imul(al2, bl1) | 0, mid = mid + Math.imul(al2, bh1) | 0, mid = mid + Math.imul(ah2, bl1) | 0, hi = hi + Math.imul(ah2, bh1) | 0, lo = lo + Math.imul(al1, bl2) | 0, mid = mid + Math.imul(al1, bh2) | 0, mid = mid + Math.imul(ah1, bl2) | 0, hi = hi + Math.imul(ah1, bh2) | 0, lo = lo + Math.imul(al0, bl3) | 0, mid = mid + Math.imul(al0, bh3) | 0, mid = mid + Math.imul(ah0, bl3) | 0, hi = hi + Math.imul(ah0, bh3) | 0;
        var w3 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w3 >>> 26) | 0, w3 &= 67108863, lo = Math.imul(al4, bl0), mid = Math.imul(al4, bh0), mid = mid + Math.imul(ah4, bl0) | 0, hi = Math.imul(ah4, bh0), lo = lo + Math.imul(al3, bl1) | 0, mid = mid + Math.imul(al3, bh1) | 0, mid = mid + Math.imul(ah3, bl1) | 0, hi = hi + Math.imul(ah3, bh1) | 0, lo = lo + Math.imul(al2, bl2) | 0, mid = mid + Math.imul(al2, bh2) | 0, mid = mid + Math.imul(ah2, bl2) | 0, hi = hi + Math.imul(ah2, bh2) | 0, lo = lo + Math.imul(al1, bl3) | 0, mid = mid + Math.imul(al1, bh3) | 0, mid = mid + Math.imul(ah1, bl3) | 0, hi = hi + Math.imul(ah1, bh3) | 0, lo = lo + Math.imul(al0, bl4) | 0, mid = mid + Math.imul(al0, bh4) | 0, mid = mid + Math.imul(ah0, bl4) | 0, hi = hi + Math.imul(ah0, bh4) | 0;
        var w4 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w4 >>> 26) | 0, w4 &= 67108863, lo = Math.imul(al5, bl0), mid = Math.imul(al5, bh0), mid = mid + Math.imul(ah5, bl0) | 0, hi = Math.imul(ah5, bh0), lo = lo + Math.imul(al4, bl1) | 0, mid = mid + Math.imul(al4, bh1) | 0, mid = mid + Math.imul(ah4, bl1) | 0, hi = hi + Math.imul(ah4, bh1) | 0, lo = lo + Math.imul(al3, bl2) | 0, mid = mid + Math.imul(al3, bh2) | 0, mid = mid + Math.imul(ah3, bl2) | 0, hi = hi + Math.imul(ah3, bh2) | 0, lo = lo + Math.imul(al2, bl3) | 0, mid = mid + Math.imul(al2, bh3) | 0, mid = mid + Math.imul(ah2, bl3) | 0, hi = hi + Math.imul(ah2, bh3) | 0, lo = lo + Math.imul(al1, bl4) | 0, mid = mid + Math.imul(al1, bh4) | 0, mid = mid + Math.imul(ah1, bl4) | 0, hi = hi + Math.imul(ah1, bh4) | 0, lo = lo + Math.imul(al0, bl5) | 0, mid = mid + Math.imul(al0, bh5) | 0, mid = mid + Math.imul(ah0, bl5) | 0, hi = hi + Math.imul(ah0, bh5) | 0;
        var w5 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w5 >>> 26) | 0, w5 &= 67108863, lo = Math.imul(al6, bl0), mid = Math.imul(al6, bh0), mid = mid + Math.imul(ah6, bl0) | 0, hi = Math.imul(ah6, bh0), lo = lo + Math.imul(al5, bl1) | 0, mid = mid + Math.imul(al5, bh1) | 0, mid = mid + Math.imul(ah5, bl1) | 0, hi = hi + Math.imul(ah5, bh1) | 0, lo = lo + Math.imul(al4, bl2) | 0, mid = mid + Math.imul(al4, bh2) | 0, mid = mid + Math.imul(ah4, bl2) | 0, hi = hi + Math.imul(ah4, bh2) | 0, lo = lo + Math.imul(al3, bl3) | 0, mid = mid + Math.imul(al3, bh3) | 0, mid = mid + Math.imul(ah3, bl3) | 0, hi = hi + Math.imul(ah3, bh3) | 0, lo = lo + Math.imul(al2, bl4) | 0, mid = mid + Math.imul(al2, bh4) | 0, mid = mid + Math.imul(ah2, bl4) | 0, hi = hi + Math.imul(ah2, bh4) | 0, lo = lo + Math.imul(al1, bl5) | 0, mid = mid + Math.imul(al1, bh5) | 0, mid = mid + Math.imul(ah1, bl5) | 0, hi = hi + Math.imul(ah1, bh5) | 0, lo = lo + Math.imul(al0, bl6) | 0, mid = mid + Math.imul(al0, bh6) | 0, mid = mid + Math.imul(ah0, bl6) | 0, hi = hi + Math.imul(ah0, bh6) | 0;
        var w6 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w6 >>> 26) | 0, w6 &= 67108863, lo = Math.imul(al7, bl0), mid = Math.imul(al7, bh0), mid = mid + Math.imul(ah7, bl0) | 0, hi = Math.imul(ah7, bh0), lo = lo + Math.imul(al6, bl1) | 0, mid = mid + Math.imul(al6, bh1) | 0, mid = mid + Math.imul(ah6, bl1) | 0, hi = hi + Math.imul(ah6, bh1) | 0, lo = lo + Math.imul(al5, bl2) | 0, mid = mid + Math.imul(al5, bh2) | 0, mid = mid + Math.imul(ah5, bl2) | 0, hi = hi + Math.imul(ah5, bh2) | 0, lo = lo + Math.imul(al4, bl3) | 0, mid = mid + Math.imul(al4, bh3) | 0, mid = mid + Math.imul(ah4, bl3) | 0, hi = hi + Math.imul(ah4, bh3) | 0, lo = lo + Math.imul(al3, bl4) | 0, mid = mid + Math.imul(al3, bh4) | 0, mid = mid + Math.imul(ah3, bl4) | 0, hi = hi + Math.imul(ah3, bh4) | 0, lo = lo + Math.imul(al2, bl5) | 0, mid = mid + Math.imul(al2, bh5) | 0, mid = mid + Math.imul(ah2, bl5) | 0, hi = hi + Math.imul(ah2, bh5) | 0, lo = lo + Math.imul(al1, bl6) | 0, mid = mid + Math.imul(al1, bh6) | 0, mid = mid + Math.imul(ah1, bl6) | 0, hi = hi + Math.imul(ah1, bh6) | 0, lo = lo + Math.imul(al0, bl7) | 0, mid = mid + Math.imul(al0, bh7) | 0, mid = mid + Math.imul(ah0, bl7) | 0, hi = hi + Math.imul(ah0, bh7) | 0;
        var w7 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w7 >>> 26) | 0, w7 &= 67108863, lo = Math.imul(al8, bl0), mid = Math.imul(al8, bh0), mid = mid + Math.imul(ah8, bl0) | 0, hi = Math.imul(ah8, bh0), lo = lo + Math.imul(al7, bl1) | 0, mid = mid + Math.imul(al7, bh1) | 0, mid = mid + Math.imul(ah7, bl1) | 0, hi = hi + Math.imul(ah7, bh1) | 0, lo = lo + Math.imul(al6, bl2) | 0, mid = mid + Math.imul(al6, bh2) | 0, mid = mid + Math.imul(ah6, bl2) | 0, hi = hi + Math.imul(ah6, bh2) | 0, lo = lo + Math.imul(al5, bl3) | 0, mid = mid + Math.imul(al5, bh3) | 0, mid = mid + Math.imul(ah5, bl3) | 0, hi = hi + Math.imul(ah5, bh3) | 0, lo = lo + Math.imul(al4, bl4) | 0, mid = mid + Math.imul(al4, bh4) | 0, mid = mid + Math.imul(ah4, bl4) | 0, hi = hi + Math.imul(ah4, bh4) | 0, lo = lo + Math.imul(al3, bl5) | 0, mid = mid + Math.imul(al3, bh5) | 0, mid = mid + Math.imul(ah3, bl5) | 0, hi = hi + Math.imul(ah3, bh5) | 0, lo = lo + Math.imul(al2, bl6) | 0, mid = mid + Math.imul(al2, bh6) | 0, mid = mid + Math.imul(ah2, bl6) | 0, hi = hi + Math.imul(ah2, bh6) | 0, lo = lo + Math.imul(al1, bl7) | 0, mid = mid + Math.imul(al1, bh7) | 0, mid = mid + Math.imul(ah1, bl7) | 0, hi = hi + Math.imul(ah1, bh7) | 0, lo = lo + Math.imul(al0, bl8) | 0, mid = mid + Math.imul(al0, bh8) | 0, mid = mid + Math.imul(ah0, bl8) | 0, hi = hi + Math.imul(ah0, bh8) | 0;
        var w8 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w8 >>> 26) | 0, w8 &= 67108863, lo = Math.imul(al9, bl0), mid = Math.imul(al9, bh0), mid = mid + Math.imul(ah9, bl0) | 0, hi = Math.imul(ah9, bh0), lo = lo + Math.imul(al8, bl1) | 0, mid = mid + Math.imul(al8, bh1) | 0, mid = mid + Math.imul(ah8, bl1) | 0, hi = hi + Math.imul(ah8, bh1) | 0, lo = lo + Math.imul(al7, bl2) | 0, mid = mid + Math.imul(al7, bh2) | 0, mid = mid + Math.imul(ah7, bl2) | 0, hi = hi + Math.imul(ah7, bh2) | 0, lo = lo + Math.imul(al6, bl3) | 0, mid = mid + Math.imul(al6, bh3) | 0, mid = mid + Math.imul(ah6, bl3) | 0, hi = hi + Math.imul(ah6, bh3) | 0, lo = lo + Math.imul(al5, bl4) | 0, mid = mid + Math.imul(al5, bh4) | 0, mid = mid + Math.imul(ah5, bl4) | 0, hi = hi + Math.imul(ah5, bh4) | 0, lo = lo + Math.imul(al4, bl5) | 0, mid = mid + Math.imul(al4, bh5) | 0, mid = mid + Math.imul(ah4, bl5) | 0, hi = hi + Math.imul(ah4, bh5) | 0, lo = lo + Math.imul(al3, bl6) | 0, mid = mid + Math.imul(al3, bh6) | 0, mid = mid + Math.imul(ah3, bl6) | 0, hi = hi + Math.imul(ah3, bh6) | 0, lo = lo + Math.imul(al2, bl7) | 0, mid = mid + Math.imul(al2, bh7) | 0, mid = mid + Math.imul(ah2, bl7) | 0, hi = hi + Math.imul(ah2, bh7) | 0, lo = lo + Math.imul(al1, bl8) | 0, mid = mid + Math.imul(al1, bh8) | 0, mid = mid + Math.imul(ah1, bl8) | 0, hi = hi + Math.imul(ah1, bh8) | 0, lo = lo + Math.imul(al0, bl9) | 0, mid = mid + Math.imul(al0, bh9) | 0, mid = mid + Math.imul(ah0, bl9) | 0, hi = hi + Math.imul(ah0, bh9) | 0;
        var w9 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w9 >>> 26) | 0, w9 &= 67108863, lo = Math.imul(al9, bl1), mid = Math.imul(al9, bh1), mid = mid + Math.imul(ah9, bl1) | 0, hi = Math.imul(ah9, bh1), lo = lo + Math.imul(al8, bl2) | 0, mid = mid + Math.imul(al8, bh2) | 0, mid = mid + Math.imul(ah8, bl2) | 0, hi = hi + Math.imul(ah8, bh2) | 0, lo = lo + Math.imul(al7, bl3) | 0, mid = mid + Math.imul(al7, bh3) | 0, mid = mid + Math.imul(ah7, bl3) | 0, hi = hi + Math.imul(ah7, bh3) | 0, lo = lo + Math.imul(al6, bl4) | 0, mid = mid + Math.imul(al6, bh4) | 0, mid = mid + Math.imul(ah6, bl4) | 0, hi = hi + Math.imul(ah6, bh4) | 0, lo = lo + Math.imul(al5, bl5) | 0, mid = mid + Math.imul(al5, bh5) | 0, mid = mid + Math.imul(ah5, bl5) | 0, hi = hi + Math.imul(ah5, bh5) | 0, lo = lo + Math.imul(al4, bl6) | 0, mid = mid + Math.imul(al4, bh6) | 0, mid = mid + Math.imul(ah4, bl6) | 0, hi = hi + Math.imul(ah4, bh6) | 0, lo = lo + Math.imul(al3, bl7) | 0, mid = mid + Math.imul(al3, bh7) | 0, mid = mid + Math.imul(ah3, bl7) | 0, hi = hi + Math.imul(ah3, bh7) | 0, lo = lo + Math.imul(al2, bl8) | 0, mid = mid + Math.imul(al2, bh8) | 0, mid = mid + Math.imul(ah2, bl8) | 0, hi = hi + Math.imul(ah2, bh8) | 0, lo = lo + Math.imul(al1, bl9) | 0, mid = mid + Math.imul(al1, bh9) | 0, mid = mid + Math.imul(ah1, bl9) | 0, hi = hi + Math.imul(ah1, bh9) | 0;
        var w10 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w10 >>> 26) | 0, w10 &= 67108863, lo = Math.imul(al9, bl2), mid = Math.imul(al9, bh2), mid = mid + Math.imul(ah9, bl2) | 0, hi = Math.imul(ah9, bh2), lo = lo + Math.imul(al8, bl3) | 0, mid = mid + Math.imul(al8, bh3) | 0, mid = mid + Math.imul(ah8, bl3) | 0, hi = hi + Math.imul(ah8, bh3) | 0, lo = lo + Math.imul(al7, bl4) | 0, mid = mid + Math.imul(al7, bh4) | 0, mid = mid + Math.imul(ah7, bl4) | 0, hi = hi + Math.imul(ah7, bh4) | 0, lo = lo + Math.imul(al6, bl5) | 0, mid = mid + Math.imul(al6, bh5) | 0, mid = mid + Math.imul(ah6, bl5) | 0, hi = hi + Math.imul(ah6, bh5) | 0, lo = lo + Math.imul(al5, bl6) | 0, mid = mid + Math.imul(al5, bh6) | 0, mid = mid + Math.imul(ah5, bl6) | 0, hi = hi + Math.imul(ah5, bh6) | 0, lo = lo + Math.imul(al4, bl7) | 0, mid = mid + Math.imul(al4, bh7) | 0, mid = mid + Math.imul(ah4, bl7) | 0, hi = hi + Math.imul(ah4, bh7) | 0, lo = lo + Math.imul(al3, bl8) | 0, mid = mid + Math.imul(al3, bh8) | 0, mid = mid + Math.imul(ah3, bl8) | 0, hi = hi + Math.imul(ah3, bh8) | 0, lo = lo + Math.imul(al2, bl9) | 0, mid = mid + Math.imul(al2, bh9) | 0, mid = mid + Math.imul(ah2, bl9) | 0, hi = hi + Math.imul(ah2, bh9) | 0;
        var w11 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w11 >>> 26) | 0, w11 &= 67108863, lo = Math.imul(al9, bl3), mid = Math.imul(al9, bh3), mid = mid + Math.imul(ah9, bl3) | 0, hi = Math.imul(ah9, bh3), lo = lo + Math.imul(al8, bl4) | 0, mid = mid + Math.imul(al8, bh4) | 0, mid = mid + Math.imul(ah8, bl4) | 0, hi = hi + Math.imul(ah8, bh4) | 0, lo = lo + Math.imul(al7, bl5) | 0, mid = mid + Math.imul(al7, bh5) | 0, mid = mid + Math.imul(ah7, bl5) | 0, hi = hi + Math.imul(ah7, bh5) | 0, lo = lo + Math.imul(al6, bl6) | 0, mid = mid + Math.imul(al6, bh6) | 0, mid = mid + Math.imul(ah6, bl6) | 0, hi = hi + Math.imul(ah6, bh6) | 0, lo = lo + Math.imul(al5, bl7) | 0, mid = mid + Math.imul(al5, bh7) | 0, mid = mid + Math.imul(ah5, bl7) | 0, hi = hi + Math.imul(ah5, bh7) | 0, lo = lo + Math.imul(al4, bl8) | 0, mid = mid + Math.imul(al4, bh8) | 0, mid = mid + Math.imul(ah4, bl8) | 0, hi = hi + Math.imul(ah4, bh8) | 0, lo = lo + Math.imul(al3, bl9) | 0, mid = mid + Math.imul(al3, bh9) | 0, mid = mid + Math.imul(ah3, bl9) | 0, hi = hi + Math.imul(ah3, bh9) | 0;
        var w12 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w12 >>> 26) | 0, w12 &= 67108863, lo = Math.imul(al9, bl4), mid = Math.imul(al9, bh4), mid = mid + Math.imul(ah9, bl4) | 0, hi = Math.imul(ah9, bh4), lo = lo + Math.imul(al8, bl5) | 0, mid = mid + Math.imul(al8, bh5) | 0, mid = mid + Math.imul(ah8, bl5) | 0, hi = hi + Math.imul(ah8, bh5) | 0, lo = lo + Math.imul(al7, bl6) | 0, mid = mid + Math.imul(al7, bh6) | 0, mid = mid + Math.imul(ah7, bl6) | 0, hi = hi + Math.imul(ah7, bh6) | 0, lo = lo + Math.imul(al6, bl7) | 0, mid = mid + Math.imul(al6, bh7) | 0, mid = mid + Math.imul(ah6, bl7) | 0, hi = hi + Math.imul(ah6, bh7) | 0, lo = lo + Math.imul(al5, bl8) | 0, mid = mid + Math.imul(al5, bh8) | 0, mid = mid + Math.imul(ah5, bl8) | 0, hi = hi + Math.imul(ah5, bh8) | 0, lo = lo + Math.imul(al4, bl9) | 0, mid = mid + Math.imul(al4, bh9) | 0, mid = mid + Math.imul(ah4, bl9) | 0, hi = hi + Math.imul(ah4, bh9) | 0;
        var w13 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w13 >>> 26) | 0, w13 &= 67108863, lo = Math.imul(al9, bl5), mid = Math.imul(al9, bh5), mid = mid + Math.imul(ah9, bl5) | 0, hi = Math.imul(ah9, bh5), lo = lo + Math.imul(al8, bl6) | 0, mid = mid + Math.imul(al8, bh6) | 0, mid = mid + Math.imul(ah8, bl6) | 0, hi = hi + Math.imul(ah8, bh6) | 0, lo = lo + Math.imul(al7, bl7) | 0, mid = mid + Math.imul(al7, bh7) | 0, mid = mid + Math.imul(ah7, bl7) | 0, hi = hi + Math.imul(ah7, bh7) | 0, lo = lo + Math.imul(al6, bl8) | 0, mid = mid + Math.imul(al6, bh8) | 0, mid = mid + Math.imul(ah6, bl8) | 0, hi = hi + Math.imul(ah6, bh8) | 0, lo = lo + Math.imul(al5, bl9) | 0, mid = mid + Math.imul(al5, bh9) | 0, mid = mid + Math.imul(ah5, bl9) | 0, hi = hi + Math.imul(ah5, bh9) | 0;
        var w14 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w14 >>> 26) | 0, w14 &= 67108863, lo = Math.imul(al9, bl6), mid = Math.imul(al9, bh6), mid = mid + Math.imul(ah9, bl6) | 0, hi = Math.imul(ah9, bh6), lo = lo + Math.imul(al8, bl7) | 0, mid = mid + Math.imul(al8, bh7) | 0, mid = mid + Math.imul(ah8, bl7) | 0, hi = hi + Math.imul(ah8, bh7) | 0, lo = lo + Math.imul(al7, bl8) | 0, mid = mid + Math.imul(al7, bh8) | 0, mid = mid + Math.imul(ah7, bl8) | 0, hi = hi + Math.imul(ah7, bh8) | 0, lo = lo + Math.imul(al6, bl9) | 0, mid = mid + Math.imul(al6, bh9) | 0, mid = mid + Math.imul(ah6, bl9) | 0, hi = hi + Math.imul(ah6, bh9) | 0;
        var w15 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w15 >>> 26) | 0, w15 &= 67108863, lo = Math.imul(al9, bl7), mid = Math.imul(al9, bh7), mid = mid + Math.imul(ah9, bl7) | 0, hi = Math.imul(ah9, bh7), lo = lo + Math.imul(al8, bl8) | 0, mid = mid + Math.imul(al8, bh8) | 0, mid = mid + Math.imul(ah8, bl8) | 0, hi = hi + Math.imul(ah8, bh8) | 0, lo = lo + Math.imul(al7, bl9) | 0, mid = mid + Math.imul(al7, bh9) | 0, mid = mid + Math.imul(ah7, bl9) | 0, hi = hi + Math.imul(ah7, bh9) | 0;
        var w16 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w16 >>> 26) | 0, w16 &= 67108863, lo = Math.imul(al9, bl8), mid = Math.imul(al9, bh8), mid = mid + Math.imul(ah9, bl8) | 0, hi = Math.imul(ah9, bh8), lo = lo + Math.imul(al8, bl9) | 0, mid = mid + Math.imul(al8, bh9) | 0, mid = mid + Math.imul(ah8, bl9) | 0, hi = hi + Math.imul(ah8, bh9) | 0;
        var w17 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        c2 = (hi + (mid >>> 13) | 0) + (w17 >>> 26) | 0, w17 &= 67108863, lo = Math.imul(al9, bl9), mid = Math.imul(al9, bh9), mid = mid + Math.imul(ah9, bl9) | 0, hi = Math.imul(ah9, bh9);
        var w18 = (c2 + lo | 0) + ((mid & 8191) << 13) | 0;
        if (c2 = (hi + (mid >>> 13) | 0) + (w18 >>> 26) | 0, w18 &= 67108863, o2[0] = w0, o2[1] = w1, o2[2] = w2, o2[3] = w3, o2[4] = w4, o2[5] = w5, o2[6] = w6, o2[7] = w7, o2[8] = w8, o2[9] = w9, o2[10] = w10, o2[11] = w11, o2[12] = w12, o2[13] = w13, o2[14] = w14, o2[15] = w15, o2[16] = w16, o2[17] = w17, o2[18] = w18, c2 !== 0)
          o2[19] = c2, out.length++;
        return out;
      };
      if (!Math.imul)
        comb10MulTo = smallMulTo;
      function bigMulTo(self2, num, out) {
        out.negative = num.negative ^ self2.negative, out.length = self2.length + num.length;
        var carry = 0, hncarry = 0;
        for (var k = 0;k < out.length - 1; k++) {
          var ncarry = hncarry;
          hncarry = 0;
          var rword = carry & 67108863, maxJ = Math.min(k, num.length - 1);
          for (var j = Math.max(0, k - self2.length + 1);j <= maxJ; j++) {
            var i2 = k - j, a2 = self2.words[i2] | 0, b = num.words[j] | 0, r2 = a2 * b, lo = r2 & 67108863;
            ncarry = ncarry + (r2 / 67108864 | 0) | 0, lo = lo + rword | 0, rword = lo & 67108863, ncarry = ncarry + (lo >>> 26) | 0, hncarry += ncarry >>> 26, ncarry &= 67108863;
          }
          out.words[k] = rword, carry = ncarry, ncarry = hncarry;
        }
        if (carry !== 0)
          out.words[k] = carry;
        else
          out.length--;
        return out._strip();
      }
      function jumboMulTo(self2, num, out) {
        return bigMulTo(self2, num, out);
      }
      BN.prototype.mulTo = function(num, out) {
        var res, len2 = this.length + num.length;
        if (this.length === 10 && num.length === 10)
          res = comb10MulTo(this, num, out);
        else if (len2 < 63)
          res = smallMulTo(this, num, out);
        else if (len2 < 1024)
          res = bigMulTo(this, num, out);
        else
          res = jumboMulTo(this, num, out);
        return res;
      };
      function FFTM(x, y) {
        this.x = x, this.y = y;
      }
      FFTM.prototype.makeRBT = function(N) {
        var t2 = Array(N), l2 = BN.prototype._countBits(N) - 1;
        for (var i2 = 0;i2 < N; i2++)
          t2[i2] = this.revBin(i2, l2, N);
        return t2;
      }, FFTM.prototype.revBin = function(x, l2, N) {
        if (x === 0 || x === N - 1)
          return x;
        var rb = 0;
        for (var i2 = 0;i2 < l2; i2++)
          rb |= (x & 1) << l2 - i2 - 1, x >>= 1;
        return rb;
      }, FFTM.prototype.permute = function(rbt, rws, iws, rtws, itws, N) {
        for (var i2 = 0;i2 < N; i2++)
          rtws[i2] = rws[rbt[i2]], itws[i2] = iws[rbt[i2]];
      }, FFTM.prototype.transform = function(rws, iws, rtws, itws, N, rbt) {
        this.permute(rbt, rws, iws, rtws, itws, N);
        for (var s = 1;s < N; s <<= 1) {
          var l2 = s << 1, rtwdf = Math.cos(2 * Math.PI / l2), itwdf = Math.sin(2 * Math.PI / l2);
          for (var p2 = 0;p2 < N; p2 += l2) {
            var rtwdf_ = rtwdf, itwdf_ = itwdf;
            for (var j = 0;j < s; j++) {
              var re = rtws[p2 + j], ie = itws[p2 + j], ro = rtws[p2 + j + s], io = itws[p2 + j + s], rx = rtwdf_ * ro - itwdf_ * io;
              if (io = rtwdf_ * io + itwdf_ * ro, ro = rx, rtws[p2 + j] = re + ro, itws[p2 + j] = ie + io, rtws[p2 + j + s] = re - ro, itws[p2 + j + s] = ie - io, j !== l2)
                rx = rtwdf * rtwdf_ - itwdf * itwdf_, itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_, rtwdf_ = rx;
            }
          }
        }
      }, FFTM.prototype.guessLen13b = function(n2, m) {
        var N = Math.max(m, n2) | 1, odd = N & 1, i2 = 0;
        for (N = N / 2 | 0;N; N = N >>> 1)
          i2++;
        return 1 << i2 + 1 + odd;
      }, FFTM.prototype.conjugate = function(rws, iws, N) {
        if (N <= 1)
          return;
        for (var i2 = 0;i2 < N / 2; i2++) {
          var t2 = rws[i2];
          rws[i2] = rws[N - i2 - 1], rws[N - i2 - 1] = t2, t2 = iws[i2], iws[i2] = -iws[N - i2 - 1], iws[N - i2 - 1] = -t2;
        }
      }, FFTM.prototype.normalize13b = function(ws, N) {
        var carry = 0;
        for (var i2 = 0;i2 < N / 2; i2++) {
          var w = Math.round(ws[2 * i2 + 1] / N) * 8192 + Math.round(ws[2 * i2] / N) + carry;
          if (ws[i2] = w & 67108863, w < 67108864)
            carry = 0;
          else
            carry = w / 67108864 | 0;
        }
        return ws;
      }, FFTM.prototype.convert13b = function(ws, len2, rws, N) {
        var carry = 0;
        for (var i2 = 0;i2 < len2; i2++)
          carry = carry + (ws[i2] | 0), rws[2 * i2] = carry & 8191, carry = carry >>> 13, rws[2 * i2 + 1] = carry & 8191, carry = carry >>> 13;
        for (i2 = 2 * len2;i2 < N; ++i2)
          rws[i2] = 0;
        assert(carry === 0), assert((carry & -8192) === 0);
      }, FFTM.prototype.stub = function(N) {
        var ph = Array(N);
        for (var i2 = 0;i2 < N; i2++)
          ph[i2] = 0;
        return ph;
      }, FFTM.prototype.mulp = function(x, y, out) {
        var N = 2 * this.guessLen13b(x.length, y.length), rbt = this.makeRBT(N), _ = this.stub(N), rws = Array(N), rwst = Array(N), iwst = Array(N), nrws = Array(N), nrwst = Array(N), niwst = Array(N), rmws = out.words;
        rmws.length = N, this.convert13b(x.words, x.length, rws, N), this.convert13b(y.words, y.length, nrws, N), this.transform(rws, _, rwst, iwst, N, rbt), this.transform(nrws, _, nrwst, niwst, N, rbt);
        for (var i2 = 0;i2 < N; i2++) {
          var rx = rwst[i2] * nrwst[i2] - iwst[i2] * niwst[i2];
          iwst[i2] = rwst[i2] * niwst[i2] + iwst[i2] * nrwst[i2], rwst[i2] = rx;
        }
        return this.conjugate(rwst, iwst, N), this.transform(rwst, iwst, rmws, _, N, rbt), this.conjugate(rmws, _, N), this.normalize13b(rmws, N), out.negative = x.negative ^ y.negative, out.length = x.length + y.length, out._strip();
      }, BN.prototype.mul = function(num) {
        var out = new BN(null);
        return out.words = Array(this.length + num.length), this.mulTo(num, out);
      }, BN.prototype.mulf = function(num) {
        var out = new BN(null);
        return out.words = Array(this.length + num.length), jumboMulTo(this, num, out);
      }, BN.prototype.imul = function(num) {
        return this.clone().mulTo(num, this);
      }, BN.prototype.imuln = function(num) {
        var isNegNum = num < 0;
        if (isNegNum)
          num = -num;
        assert(typeof num === "number"), assert(num < 67108864);
        var carry = 0;
        for (var i2 = 0;i2 < this.length; i2++) {
          var w = (this.words[i2] | 0) * num, lo = (w & 67108863) + (carry & 67108863);
          carry >>= 26, carry += w / 67108864 | 0, carry += lo >>> 26, this.words[i2] = lo & 67108863;
        }
        if (carry !== 0)
          this.words[i2] = carry, this.length++;
        return this.length = num === 0 ? 1 : this.length, isNegNum ? this.ineg() : this;
      }, BN.prototype.muln = function(num) {
        return this.clone().imuln(num);
      }, BN.prototype.sqr = function() {
        return this.mul(this);
      }, BN.prototype.isqr = function() {
        return this.imul(this.clone());
      }, BN.prototype.pow = function(num) {
        var w = toBitArray(num);
        if (w.length === 0)
          return new BN(1);
        var res = this;
        for (var i2 = 0;i2 < w.length; i2++, res = res.sqr())
          if (w[i2] !== 0)
            break;
        if (++i2 < w.length)
          for (var q = res.sqr();i2 < w.length; i2++, q = q.sqr()) {
            if (w[i2] === 0)
              continue;
            res = res.mul(q);
          }
        return res;
      }, BN.prototype.iushln = function(bits) {
        assert(typeof bits === "number" && bits >= 0);
        var r2 = bits % 26, s = (bits - r2) / 26, carryMask = 67108863 >>> 26 - r2 << 26 - r2, i2;
        if (r2 !== 0) {
          var carry = 0;
          for (i2 = 0;i2 < this.length; i2++) {
            var newCarry = this.words[i2] & carryMask, c2 = (this.words[i2] | 0) - newCarry << r2;
            this.words[i2] = c2 | carry, carry = newCarry >>> 26 - r2;
          }
          if (carry)
            this.words[i2] = carry, this.length++;
        }
        if (s !== 0) {
          for (i2 = this.length - 1;i2 >= 0; i2--)
            this.words[i2 + s] = this.words[i2];
          for (i2 = 0;i2 < s; i2++)
            this.words[i2] = 0;
          this.length += s;
        }
        return this._strip();
      }, BN.prototype.ishln = function(bits) {
        return assert(this.negative === 0), this.iushln(bits);
      }, BN.prototype.iushrn = function(bits, hint, extended) {
        assert(typeof bits === "number" && bits >= 0);
        var h;
        if (hint)
          h = (hint - hint % 26) / 26;
        else
          h = 0;
        var r2 = bits % 26, s = Math.min((bits - r2) / 26, this.length), mask = 67108863 ^ 67108863 >>> r2 << r2, maskedWords = extended;
        if (h -= s, h = Math.max(0, h), maskedWords) {
          for (var i2 = 0;i2 < s; i2++)
            maskedWords.words[i2] = this.words[i2];
          maskedWords.length = s;
        }
        if (s === 0)
          ;
        else if (this.length > s) {
          this.length -= s;
          for (i2 = 0;i2 < this.length; i2++)
            this.words[i2] = this.words[i2 + s];
        } else
          this.words[0] = 0, this.length = 1;
        var carry = 0;
        for (i2 = this.length - 1;i2 >= 0 && (carry !== 0 || i2 >= h); i2--) {
          var word = this.words[i2] | 0;
          this.words[i2] = carry << 26 - r2 | word >>> r2, carry = word & mask;
        }
        if (maskedWords && carry !== 0)
          maskedWords.words[maskedWords.length++] = carry;
        if (this.length === 0)
          this.words[0] = 0, this.length = 1;
        return this._strip();
      }, BN.prototype.ishrn = function(bits, hint, extended) {
        return assert(this.negative === 0), this.iushrn(bits, hint, extended);
      }, BN.prototype.shln = function(bits) {
        return this.clone().ishln(bits);
      }, BN.prototype.ushln = function(bits) {
        return this.clone().iushln(bits);
      }, BN.prototype.shrn = function(bits) {
        return this.clone().ishrn(bits);
      }, BN.prototype.ushrn = function(bits) {
        return this.clone().iushrn(bits);
      }, BN.prototype.testn = function(bit) {
        assert(typeof bit === "number" && bit >= 0);
        var r2 = bit % 26, s = (bit - r2) / 26, q = 1 << r2;
        if (this.length <= s)
          return false;
        var w = this.words[s];
        return !!(w & q);
      }, BN.prototype.imaskn = function(bits) {
        assert(typeof bits === "number" && bits >= 0);
        var r2 = bits % 26, s = (bits - r2) / 26;
        if (assert(this.negative === 0, "imaskn works only with positive numbers"), this.length <= s)
          return this;
        if (r2 !== 0)
          s++;
        if (this.length = Math.min(s, this.length), r2 !== 0) {
          var mask = 67108863 ^ 67108863 >>> r2 << r2;
          this.words[this.length - 1] &= mask;
        }
        return this._strip();
      }, BN.prototype.maskn = function(bits) {
        return this.clone().imaskn(bits);
      }, BN.prototype.iaddn = function(num) {
        if (assert(typeof num === "number"), assert(num < 67108864), num < 0)
          return this.isubn(-num);
        if (this.negative !== 0) {
          if (this.length === 1 && (this.words[0] | 0) <= num)
            return this.words[0] = num - (this.words[0] | 0), this.negative = 0, this;
          return this.negative = 0, this.isubn(num), this.negative = 1, this;
        }
        return this._iaddn(num);
      }, BN.prototype._iaddn = function(num) {
        this.words[0] += num;
        for (var i2 = 0;i2 < this.length && this.words[i2] >= 67108864; i2++)
          if (this.words[i2] -= 67108864, i2 === this.length - 1)
            this.words[i2 + 1] = 1;
          else
            this.words[i2 + 1]++;
        return this.length = Math.max(this.length, i2 + 1), this;
      }, BN.prototype.isubn = function(num) {
        if (assert(typeof num === "number"), assert(num < 67108864), num < 0)
          return this.iaddn(-num);
        if (this.negative !== 0)
          return this.negative = 0, this.iaddn(num), this.negative = 1, this;
        if (this.words[0] -= num, this.length === 1 && this.words[0] < 0)
          this.words[0] = -this.words[0], this.negative = 1;
        else
          for (var i2 = 0;i2 < this.length && this.words[i2] < 0; i2++)
            this.words[i2] += 67108864, this.words[i2 + 1] -= 1;
        return this._strip();
      }, BN.prototype.addn = function(num) {
        return this.clone().iaddn(num);
      }, BN.prototype.subn = function(num) {
        return this.clone().isubn(num);
      }, BN.prototype.iabs = function() {
        return this.negative = 0, this;
      }, BN.prototype.abs = function() {
        return this.clone().iabs();
      }, BN.prototype._ishlnsubmul = function(num, mul, shift) {
        var len2 = num.length + shift, i2;
        this._expand(len2);
        var w, carry = 0;
        for (i2 = 0;i2 < num.length; i2++) {
          w = (this.words[i2 + shift] | 0) + carry;
          var right = (num.words[i2] | 0) * mul;
          w -= right & 67108863, carry = (w >> 26) - (right / 67108864 | 0), this.words[i2 + shift] = w & 67108863;
        }
        for (;i2 < this.length - shift; i2++)
          w = (this.words[i2 + shift] | 0) + carry, carry = w >> 26, this.words[i2 + shift] = w & 67108863;
        if (carry === 0)
          return this._strip();
        assert(carry === -1), carry = 0;
        for (i2 = 0;i2 < this.length; i2++)
          w = -(this.words[i2] | 0) + carry, carry = w >> 26, this.words[i2] = w & 67108863;
        return this.negative = 1, this._strip();
      }, BN.prototype._wordDiv = function(num, mode) {
        var shift = this.length - num.length, a2 = this.clone(), b = num, bhi = b.words[b.length - 1] | 0, bhiBits = this._countBits(bhi);
        if (shift = 26 - bhiBits, shift !== 0)
          b = b.ushln(shift), a2.iushln(shift), bhi = b.words[b.length - 1] | 0;
        var m = a2.length - b.length, q;
        if (mode !== "mod") {
          q = new BN(null), q.length = m + 1, q.words = Array(q.length);
          for (var i2 = 0;i2 < q.length; i2++)
            q.words[i2] = 0;
        }
        var diff = a2.clone()._ishlnsubmul(b, 1, m);
        if (diff.negative === 0) {
          if (a2 = diff, q)
            q.words[m] = 1;
        }
        for (var j = m - 1;j >= 0; j--) {
          var qj = (a2.words[b.length + j] | 0) * 67108864 + (a2.words[b.length + j - 1] | 0);
          qj = Math.min(qj / bhi | 0, 67108863), a2._ishlnsubmul(b, qj, j);
          while (a2.negative !== 0)
            if (qj--, a2.negative = 0, a2._ishlnsubmul(b, 1, j), !a2.isZero())
              a2.negative ^= 1;
          if (q)
            q.words[j] = qj;
        }
        if (q)
          q._strip();
        if (a2._strip(), mode !== "div" && shift !== 0)
          a2.iushrn(shift);
        return { div: q || null, mod: a2 };
      }, BN.prototype.divmod = function(num, mode, positive) {
        if (assert(!num.isZero()), this.isZero())
          return { div: new BN(0), mod: new BN(0) };
        var div, mod, res;
        if (this.negative !== 0 && num.negative === 0) {
          if (res = this.neg().divmod(num, mode), mode !== "mod")
            div = res.div.neg();
          if (mode !== "div") {
            if (mod = res.mod.neg(), positive && mod.negative !== 0)
              mod.iadd(num);
          }
          return { div, mod };
        }
        if (this.negative === 0 && num.negative !== 0) {
          if (res = this.divmod(num.neg(), mode), mode !== "mod")
            div = res.div.neg();
          return { div, mod: res.mod };
        }
        if ((this.negative & num.negative) !== 0) {
          if (res = this.neg().divmod(num.neg(), mode), mode !== "div") {
            if (mod = res.mod.neg(), positive && mod.negative !== 0)
              mod.isub(num);
          }
          return { div: res.div, mod };
        }
        if (num.length > this.length || this.cmp(num) < 0)
          return { div: new BN(0), mod: this };
        if (num.length === 1) {
          if (mode === "div")
            return { div: this.divn(num.words[0]), mod: null };
          if (mode === "mod")
            return { div: null, mod: new BN(this.modrn(num.words[0])) };
          return { div: this.divn(num.words[0]), mod: new BN(this.modrn(num.words[0])) };
        }
        return this._wordDiv(num, mode);
      }, BN.prototype.div = function(num) {
        return this.divmod(num, "div", false).div;
      }, BN.prototype.mod = function(num) {
        return this.divmod(num, "mod", false).mod;
      }, BN.prototype.umod = function(num) {
        return this.divmod(num, "mod", true).mod;
      }, BN.prototype.divRound = function(num) {
        var dm = this.divmod(num);
        if (dm.mod.isZero())
          return dm.div;
        var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod, half = num.ushrn(1), r2 = num.andln(1), cmp = mod.cmp(half);
        if (cmp < 0 || r2 === 1 && cmp === 0)
          return dm.div;
        return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
      }, BN.prototype.modrn = function(num) {
        var isNegNum = num < 0;
        if (isNegNum)
          num = -num;
        assert(num <= 67108863);
        var p2 = 67108864 % num, acc = 0;
        for (var i2 = this.length - 1;i2 >= 0; i2--)
          acc = (p2 * acc + (this.words[i2] | 0)) % num;
        return isNegNum ? -acc : acc;
      }, BN.prototype.modn = function(num) {
        return this.modrn(num);
      }, BN.prototype.idivn = function(num) {
        var isNegNum = num < 0;
        if (isNegNum)
          num = -num;
        assert(num <= 67108863);
        var carry = 0;
        for (var i2 = this.length - 1;i2 >= 0; i2--) {
          var w = (this.words[i2] | 0) + carry * 67108864;
          this.words[i2] = w / num | 0, carry = w % num;
        }
        return this._strip(), isNegNum ? this.ineg() : this;
      }, BN.prototype.divn = function(num) {
        return this.clone().idivn(num);
      }, BN.prototype.egcd = function(p2) {
        assert(p2.negative === 0), assert(!p2.isZero());
        var x = this, y = p2.clone();
        if (x.negative !== 0)
          x = x.umod(p2);
        else
          x = x.clone();
        var A = new BN(1), B = new BN(0), C = new BN(0), D = new BN(1), g = 0;
        while (x.isEven() && y.isEven())
          x.iushrn(1), y.iushrn(1), ++g;
        var yp = y.clone(), xp = x.clone();
        while (!x.isZero()) {
          for (var i2 = 0, im = 1;(x.words[0] & im) === 0 && i2 < 26; ++i2, im <<= 1)
            ;
          if (i2 > 0) {
            x.iushrn(i2);
            while (i2-- > 0) {
              if (A.isOdd() || B.isOdd())
                A.iadd(yp), B.isub(xp);
              A.iushrn(1), B.iushrn(1);
            }
          }
          for (var j = 0, jm = 1;(y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1)
            ;
          if (j > 0) {
            y.iushrn(j);
            while (j-- > 0) {
              if (C.isOdd() || D.isOdd())
                C.iadd(yp), D.isub(xp);
              C.iushrn(1), D.iushrn(1);
            }
          }
          if (x.cmp(y) >= 0)
            x.isub(y), A.isub(C), B.isub(D);
          else
            y.isub(x), C.isub(A), D.isub(B);
        }
        return { a: C, b: D, gcd: y.iushln(g) };
      }, BN.prototype._invmp = function(p2) {
        assert(p2.negative === 0), assert(!p2.isZero());
        var a2 = this, b = p2.clone();
        if (a2.negative !== 0)
          a2 = a2.umod(p2);
        else
          a2 = a2.clone();
        var x1 = new BN(1), x2 = new BN(0), delta = b.clone();
        while (a2.cmpn(1) > 0 && b.cmpn(1) > 0) {
          for (var i2 = 0, im = 1;(a2.words[0] & im) === 0 && i2 < 26; ++i2, im <<= 1)
            ;
          if (i2 > 0) {
            a2.iushrn(i2);
            while (i2-- > 0) {
              if (x1.isOdd())
                x1.iadd(delta);
              x1.iushrn(1);
            }
          }
          for (var j = 0, jm = 1;(b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1)
            ;
          if (j > 0) {
            b.iushrn(j);
            while (j-- > 0) {
              if (x2.isOdd())
                x2.iadd(delta);
              x2.iushrn(1);
            }
          }
          if (a2.cmp(b) >= 0)
            a2.isub(b), x1.isub(x2);
          else
            b.isub(a2), x2.isub(x1);
        }
        var res;
        if (a2.cmpn(1) === 0)
          res = x1;
        else
          res = x2;
        if (res.cmpn(0) < 0)
          res.iadd(p2);
        return res;
      }, BN.prototype.gcd = function(num) {
        if (this.isZero())
          return num.abs();
        if (num.isZero())
          return this.abs();
        var a2 = this.clone(), b = num.clone();
        a2.negative = 0, b.negative = 0;
        for (var shift = 0;a2.isEven() && b.isEven(); shift++)
          a2.iushrn(1), b.iushrn(1);
        do {
          while (a2.isEven())
            a2.iushrn(1);
          while (b.isEven())
            b.iushrn(1);
          var r2 = a2.cmp(b);
          if (r2 < 0) {
            var t2 = a2;
            a2 = b, b = t2;
          } else if (r2 === 0 || b.cmpn(1) === 0)
            break;
          a2.isub(b);
        } while (true);
        return b.iushln(shift);
      }, BN.prototype.invm = function(num) {
        return this.egcd(num).a.umod(num);
      }, BN.prototype.isEven = function() {
        return (this.words[0] & 1) === 0;
      }, BN.prototype.isOdd = function() {
        return (this.words[0] & 1) === 1;
      }, BN.prototype.andln = function(num) {
        return this.words[0] & num;
      }, BN.prototype.bincn = function(bit) {
        assert(typeof bit === "number");
        var r2 = bit % 26, s = (bit - r2) / 26, q = 1 << r2;
        if (this.length <= s)
          return this._expand(s + 1), this.words[s] |= q, this;
        var carry = q;
        for (var i2 = s;carry !== 0 && i2 < this.length; i2++) {
          var w = this.words[i2] | 0;
          w += carry, carry = w >>> 26, w &= 67108863, this.words[i2] = w;
        }
        if (carry !== 0)
          this.words[i2] = carry, this.length++;
        return this;
      }, BN.prototype.isZero = function() {
        return this.length === 1 && this.words[0] === 0;
      }, BN.prototype.cmpn = function(num) {
        var negative = num < 0;
        if (this.negative !== 0 && !negative)
          return -1;
        if (this.negative === 0 && negative)
          return 1;
        this._strip();
        var res;
        if (this.length > 1)
          res = 1;
        else {
          if (negative)
            num = -num;
          assert(num <= 67108863, "Number is too big");
          var w = this.words[0] | 0;
          res = w === num ? 0 : w < num ? -1 : 1;
        }
        if (this.negative !== 0)
          return -res | 0;
        return res;
      }, BN.prototype.cmp = function(num) {
        if (this.negative !== 0 && num.negative === 0)
          return -1;
        if (this.negative === 0 && num.negative !== 0)
          return 1;
        var res = this.ucmp(num);
        if (this.negative !== 0)
          return -res | 0;
        return res;
      }, BN.prototype.ucmp = function(num) {
        if (this.length > num.length)
          return 1;
        if (this.length < num.length)
          return -1;
        var res = 0;
        for (var i2 = this.length - 1;i2 >= 0; i2--) {
          var a2 = this.words[i2] | 0, b = num.words[i2] | 0;
          if (a2 === b)
            continue;
          if (a2 < b)
            res = -1;
          else if (a2 > b)
            res = 1;
          break;
        }
        return res;
      }, BN.prototype.gtn = function(num) {
        return this.cmpn(num) === 1;
      }, BN.prototype.gt = function(num) {
        return this.cmp(num) === 1;
      }, BN.prototype.gten = function(num) {
        return this.cmpn(num) >= 0;
      }, BN.prototype.gte = function(num) {
        return this.cmp(num) >= 0;
      }, BN.prototype.ltn = function(num) {
        return this.cmpn(num) === -1;
      }, BN.prototype.lt = function(num) {
        return this.cmp(num) === -1;
      }, BN.prototype.lten = function(num) {
        return this.cmpn(num) <= 0;
      }, BN.prototype.lte = function(num) {
        return this.cmp(num) <= 0;
      }, BN.prototype.eqn = function(num) {
        return this.cmpn(num) === 0;
      }, BN.prototype.eq = function(num) {
        return this.cmp(num) === 0;
      }, BN.red = function(num) {
        return new Red(num);
      }, BN.prototype.toRed = function(ctx) {
        return assert(!this.red, "Already a number in reduction context"), assert(this.negative === 0, "red works only with positives"), ctx.convertTo(this)._forceRed(ctx);
      }, BN.prototype.fromRed = function() {
        return assert(this.red, "fromRed works only with numbers in reduction context"), this.red.convertFrom(this);
      }, BN.prototype._forceRed = function(ctx) {
        return this.red = ctx, this;
      }, BN.prototype.forceRed = function(ctx) {
        return assert(!this.red, "Already a number in reduction context"), this._forceRed(ctx);
      }, BN.prototype.redAdd = function(num) {
        return assert(this.red, "redAdd works only with red numbers"), this.red.add(this, num);
      }, BN.prototype.redIAdd = function(num) {
        return assert(this.red, "redIAdd works only with red numbers"), this.red.iadd(this, num);
      }, BN.prototype.redSub = function(num) {
        return assert(this.red, "redSub works only with red numbers"), this.red.sub(this, num);
      }, BN.prototype.redISub = function(num) {
        return assert(this.red, "redISub works only with red numbers"), this.red.isub(this, num);
      }, BN.prototype.redShl = function(num) {
        return assert(this.red, "redShl works only with red numbers"), this.red.shl(this, num);
      }, BN.prototype.redMul = function(num) {
        return assert(this.red, "redMul works only with red numbers"), this.red._verify2(this, num), this.red.mul(this, num);
      }, BN.prototype.redIMul = function(num) {
        return assert(this.red, "redMul works only with red numbers"), this.red._verify2(this, num), this.red.imul(this, num);
      }, BN.prototype.redSqr = function() {
        return assert(this.red, "redSqr works only with red numbers"), this.red._verify1(this), this.red.sqr(this);
      }, BN.prototype.redISqr = function() {
        return assert(this.red, "redISqr works only with red numbers"), this.red._verify1(this), this.red.isqr(this);
      }, BN.prototype.redSqrt = function() {
        return assert(this.red, "redSqrt works only with red numbers"), this.red._verify1(this), this.red.sqrt(this);
      }, BN.prototype.redInvm = function() {
        return assert(this.red, "redInvm works only with red numbers"), this.red._verify1(this), this.red.invm(this);
      }, BN.prototype.redNeg = function() {
        return assert(this.red, "redNeg works only with red numbers"), this.red._verify1(this), this.red.neg(this);
      }, BN.prototype.redPow = function(num) {
        return assert(this.red && !num.red, "redPow(normalNum)"), this.red._verify1(this), this.red.pow(this, num);
      };
      var primes = { k256: null, p224: null, p192: null, p25519: null };
      function MPrime(name, p2) {
        this.name = name, this.p = new BN(p2, 16), this.n = this.p.bitLength(), this.k = new BN(1).iushln(this.n).isub(this.p), this.tmp = this._tmp();
      }
      MPrime.prototype._tmp = function() {
        var tmp = new BN(null);
        return tmp.words = Array(Math.ceil(this.n / 13)), tmp;
      }, MPrime.prototype.ireduce = function(num) {
        var r2 = num, rlen;
        do
          this.split(r2, this.tmp), r2 = this.imulK(r2), r2 = r2.iadd(this.tmp), rlen = r2.bitLength();
        while (rlen > this.n);
        var cmp = rlen < this.n ? -1 : r2.ucmp(this.p);
        if (cmp === 0)
          r2.words[0] = 0, r2.length = 1;
        else if (cmp > 0)
          r2.isub(this.p);
        else if (r2.strip !== undefined)
          r2.strip();
        else
          r2._strip();
        return r2;
      }, MPrime.prototype.split = function(input, out) {
        input.iushrn(this.n, 0, out);
      }, MPrime.prototype.imulK = function(num) {
        return num.imul(this.k);
      };
      function K256() {
        MPrime.call(this, "k256", "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f");
      }
      inherits2(K256, MPrime), K256.prototype.split = function(input, output) {
        var mask = 4194303, outLen = Math.min(input.length, 9);
        for (var i2 = 0;i2 < outLen; i2++)
          output.words[i2] = input.words[i2];
        if (output.length = outLen, input.length <= 9) {
          input.words[0] = 0, input.length = 1;
          return;
        }
        var prev = input.words[9];
        output.words[output.length++] = prev & mask;
        for (i2 = 10;i2 < input.length; i2++) {
          var next = input.words[i2] | 0;
          input.words[i2 - 10] = (next & mask) << 4 | prev >>> 22, prev = next;
        }
        if (prev >>>= 22, input.words[i2 - 10] = prev, prev === 0 && input.length > 10)
          input.length -= 10;
        else
          input.length -= 9;
      }, K256.prototype.imulK = function(num) {
        num.words[num.length] = 0, num.words[num.length + 1] = 0, num.length += 2;
        var lo = 0;
        for (var i2 = 0;i2 < num.length; i2++) {
          var w = num.words[i2] | 0;
          lo += w * 977, num.words[i2] = lo & 67108863, lo = w * 64 + (lo / 67108864 | 0);
        }
        if (num.words[num.length - 1] === 0) {
          if (num.length--, num.words[num.length - 1] === 0)
            num.length--;
        }
        return num;
      };
      function P224() {
        MPrime.call(this, "p224", "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001");
      }
      inherits2(P224, MPrime);
      function P192() {
        MPrime.call(this, "p192", "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff");
      }
      inherits2(P192, MPrime);
      function P25519() {
        MPrime.call(this, "25519", "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed");
      }
      inherits2(P25519, MPrime), P25519.prototype.imulK = function(num) {
        var carry = 0;
        for (var i2 = 0;i2 < num.length; i2++) {
          var hi = (num.words[i2] | 0) * 19 + carry, lo = hi & 67108863;
          hi >>>= 26, num.words[i2] = lo, carry = hi;
        }
        if (carry !== 0)
          num.words[num.length++] = carry;
        return num;
      }, BN._prime = function(name) {
        if (primes[name])
          return primes[name];
        var prime;
        if (name === "k256")
          prime = new K256;
        else if (name === "p224")
          prime = new P224;
        else if (name === "p192")
          prime = new P192;
        else if (name === "p25519")
          prime = new P25519;
        else
          throw Error("Unknown prime " + name);
        return primes[name] = prime, prime;
      };
      function Red(m) {
        if (typeof m === "string") {
          var prime = BN._prime(m);
          this.m = prime.p, this.prime = prime;
        } else
          assert(m.gtn(1), "modulus must be greater than 1"), this.m = m, this.prime = null;
      }
      Red.prototype._verify1 = function(a2) {
        assert(a2.negative === 0, "red works only with positives"), assert(a2.red, "red works only with red numbers");
      }, Red.prototype._verify2 = function(a2, b) {
        assert((a2.negative | b.negative) === 0, "red works only with positives"), assert(a2.red && a2.red === b.red, "red works only with red numbers");
      }, Red.prototype.imod = function(a2) {
        if (this.prime)
          return this.prime.ireduce(a2)._forceRed(this);
        return move(a2, a2.umod(this.m)._forceRed(this)), a2;
      }, Red.prototype.neg = function(a2) {
        if (a2.isZero())
          return a2.clone();
        return this.m.sub(a2)._forceRed(this);
      }, Red.prototype.add = function(a2, b) {
        this._verify2(a2, b);
        var res = a2.add(b);
        if (res.cmp(this.m) >= 0)
          res.isub(this.m);
        return res._forceRed(this);
      }, Red.prototype.iadd = function(a2, b) {
        this._verify2(a2, b);
        var res = a2.iadd(b);
        if (res.cmp(this.m) >= 0)
          res.isub(this.m);
        return res;
      }, Red.prototype.sub = function(a2, b) {
        this._verify2(a2, b);
        var res = a2.sub(b);
        if (res.cmpn(0) < 0)
          res.iadd(this.m);
        return res._forceRed(this);
      }, Red.prototype.isub = function(a2, b) {
        this._verify2(a2, b);
        var res = a2.isub(b);
        if (res.cmpn(0) < 0)
          res.iadd(this.m);
        return res;
      }, Red.prototype.shl = function(a2, num) {
        return this._verify1(a2), this.imod(a2.ushln(num));
      }, Red.prototype.imul = function(a2, b) {
        return this._verify2(a2, b), this.imod(a2.imul(b));
      }, Red.prototype.mul = function(a2, b) {
        return this._verify2(a2, b), this.imod(a2.mul(b));
      }, Red.prototype.isqr = function(a2) {
        return this.imul(a2, a2.clone());
      }, Red.prototype.sqr = function(a2) {
        return this.mul(a2, a2);
      }, Red.prototype.sqrt = function(a2) {
        if (a2.isZero())
          return a2.clone();
        var mod3 = this.m.andln(3);
        if (assert(mod3 % 2 === 1), mod3 === 3) {
          var pow = this.m.add(new BN(1)).iushrn(2);
          return this.pow(a2, pow);
        }
        var q = this.m.subn(1), s = 0;
        while (!q.isZero() && q.andln(1) === 0)
          s++, q.iushrn(1);
        assert(!q.isZero());
        var one = new BN(1).toRed(this), nOne = one.redNeg(), lpow = this.m.subn(1).iushrn(1), z = this.m.bitLength();
        z = new BN(2 * z * z).toRed(this);
        while (this.pow(z, lpow).cmp(nOne) !== 0)
          z.redIAdd(nOne);
        var c2 = this.pow(z, q), r2 = this.pow(a2, q.addn(1).iushrn(1)), t2 = this.pow(a2, q), m = s;
        while (t2.cmp(one) !== 0) {
          var tmp = t2;
          for (var i2 = 0;tmp.cmp(one) !== 0; i2++)
            tmp = tmp.redSqr();
          assert(i2 < m);
          var b = this.pow(c2, new BN(1).iushln(m - i2 - 1));
          r2 = r2.redMul(b), c2 = b.redSqr(), t2 = t2.redMul(c2), m = i2;
        }
        return r2;
      }, Red.prototype.invm = function(a2) {
        var inv = a2._invmp(this.m);
        if (inv.negative !== 0)
          return inv.negative = 0, this.imod(inv).redNeg();
        else
          return this.imod(inv);
      }, Red.prototype.pow = function(a2, num) {
        if (num.isZero())
          return new BN(1).toRed(this);
        if (num.cmpn(1) === 0)
          return a2.clone();
        var windowSize = 4, wnd = Array(1 << windowSize);
        wnd[0] = new BN(1).toRed(this), wnd[1] = a2;
        for (var i2 = 2;i2 < wnd.length; i2++)
          wnd[i2] = this.mul(wnd[i2 - 1], a2);
        var res = wnd[0], current = 0, currentLen = 0, start = num.bitLength() % 26;
        if (start === 0)
          start = 26;
        for (i2 = num.length - 1;i2 >= 0; i2--) {
          var word = num.words[i2];
          for (var j = start - 1;j >= 0; j--) {
            var bit = word >> j & 1;
            if (res !== wnd[0])
              res = this.sqr(res);
            if (bit === 0 && current === 0) {
              currentLen = 0;
              continue;
            }
            if (current <<= 1, current |= bit, currentLen++, currentLen !== windowSize && (i2 !== 0 || j !== 0))
              continue;
            res = this.mul(res, wnd[current]), currentLen = 0, current = 0;
          }
          start = 26;
        }
        return res;
      }, Red.prototype.convertTo = function(num) {
        var r2 = num.umod(this.m);
        return r2 === num ? r2.clone() : r2;
      }, Red.prototype.convertFrom = function(num) {
        var res = num.clone();
        return res.red = null, res;
      }, BN.mont = function(num) {
        return new Mont(num);
      };
      function Mont(m) {
        if (Red.call(this, m), this.shift = this.m.bitLength(), this.shift % 26 !== 0)
          this.shift += 26 - this.shift % 26;
        this.r = new BN(1).iushln(this.shift), this.r2 = this.imod(this.r.sqr()), this.rinv = this.r._invmp(this.m), this.minv = this.rinv.mul(this.r).isubn(1).div(this.m), this.minv = this.minv.umod(this.r), this.minv = this.r.sub(this.minv);
      }
      inherits2(Mont, Red), Mont.prototype.convertTo = function(num) {
        return this.imod(num.ushln(this.shift));
      }, Mont.prototype.convertFrom = function(num) {
        var r2 = this.imod(num.mul(this.rinv));
        return r2.red = null, r2;
      }, Mont.prototype.imul = function(a2, b) {
        if (a2.isZero() || b.isZero())
          return a2.words[0] = 0, a2.length = 1, a2;
        var t2 = a2.imul(b), c2 = t2.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), u = t2.isub(c2).iushrn(this.shift), res = u;
        if (u.cmp(this.m) >= 0)
          res = u.isub(this.m);
        else if (u.cmpn(0) < 0)
          res = u.iadd(this.m);
        return res._forceRed(this);
      }, Mont.prototype.mul = function(a2, b) {
        if (a2.isZero() || b.isZero())
          return new BN(0)._forceRed(this);
        var t2 = a2.mul(b), c2 = t2.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), u = t2.isub(c2).iushrn(this.shift), res = u;
        if (u.cmp(this.m) >= 0)
          res = u.isub(this.m);
        else if (u.cmpn(0) < 0)
          res = u.iadd(this.m);
        return res._forceRed(this);
      }, Mont.prototype.invm = function(a2) {
        var res = this.imod(a2._invmp(this.m).mul(this.r2));
        return res._forceRed(this);
      };
    })(typeof module > "u" || module, exports);
  });
  require_browserify_rsa = __commonJS2((exports, module) => {
    var BN = require_bn5(), randomBytes = require_randombytes(), Buffer22 = require_safe_buffer().Buffer;
    function getr(priv) {
      var len2 = priv.modulus.byteLength(), r2;
      do
        r2 = new BN(randomBytes(len2));
      while (r2.cmp(priv.modulus) >= 0 || !r2.umod(priv.prime1) || !r2.umod(priv.prime2));
      return r2;
    }
    function blind(priv) {
      var r2 = getr(priv), blinder = r2.toRed(BN.mont(priv.modulus)).redPow(new BN(priv.publicExponent)).fromRed();
      return { blinder, unblinder: r2.invm(priv.modulus) };
    }
    function crt(msg, priv) {
      var blinds = blind(priv), len2 = priv.modulus.byteLength(), blinded = new BN(msg).mul(blinds.blinder).umod(priv.modulus), c1 = blinded.toRed(BN.mont(priv.prime1)), c2 = blinded.toRed(BN.mont(priv.prime2)), qinv = priv.coefficient, p2 = priv.prime1, q = priv.prime2, m1 = c1.redPow(priv.exponent1).fromRed(), m2 = c2.redPow(priv.exponent2).fromRed(), h = m1.isub(m2).imul(qinv).umod(p2).imul(q);
      return m2.iadd(h).imul(blinds.unblinder).umod(priv.modulus).toArrayLike(Buffer22, "be", len2);
    }
    crt.getr = getr;
    module.exports = crt;
  });
  require_publicEncrypt = __commonJS2((exports, module) => {
    var parseKeys = require_parse_asn1(), randomBytes = require_randombytes(), createHash = require_create_hash(), mgf = require_mgf(), xor = require_xor(), BN = require_bn4(), withPublic = require_withPublic(), crt = require_browserify_rsa(), Buffer22 = require_safe_buffer().Buffer;
    module.exports = function(publicKey, msg, reverse) {
      var padding;
      if (publicKey.padding)
        padding = publicKey.padding;
      else if (reverse)
        padding = 1;
      else
        padding = 4;
      var key = parseKeys(publicKey), paddedMsg;
      if (padding === 4)
        paddedMsg = oaep(key, msg);
      else if (padding === 1)
        paddedMsg = pkcs1(key, msg, reverse);
      else if (padding === 3) {
        if (paddedMsg = new BN(msg), paddedMsg.cmp(key.modulus) >= 0)
          throw Error("data too long for modulus");
      } else
        throw Error("unknown padding");
      if (reverse)
        return crt(paddedMsg, key);
      else
        return withPublic(paddedMsg, key);
    };
    function oaep(key, msg) {
      var k = key.modulus.byteLength(), mLen = msg.length, iHash = createHash("sha1").update(Buffer22.alloc(0)).digest(), hLen = iHash.length, hLen2 = 2 * hLen;
      if (mLen > k - hLen2 - 2)
        throw Error("message too long");
      var ps = Buffer22.alloc(k - mLen - hLen2 - 2), dblen = k - hLen - 1, seed = randomBytes(hLen), maskedDb = xor(Buffer22.concat([iHash, ps, Buffer22.alloc(1, 1), msg], dblen), mgf(seed, dblen)), maskedSeed = xor(seed, mgf(maskedDb, hLen));
      return new BN(Buffer22.concat([Buffer22.alloc(1), maskedSeed, maskedDb], k));
    }
    function pkcs1(key, msg, reverse) {
      var mLen = msg.length, k = key.modulus.byteLength();
      if (mLen > k - 11)
        throw Error("message too long");
      var ps;
      if (reverse)
        ps = Buffer22.alloc(k - mLen - 3, 255);
      else
        ps = nonZero(k - mLen - 3);
      return new BN(Buffer22.concat([Buffer22.from([0, reverse ? 1 : 2]), ps, Buffer22.alloc(1), msg], k));
    }
    function nonZero(len2) {
      var out = Buffer22.allocUnsafe(len2), i2 = 0, cache = randomBytes(len2 * 2), cur = 0, num;
      while (i2 < len2) {
        if (cur === cache.length)
          cache = randomBytes(len2 * 2), cur = 0;
        if (num = cache[cur++], num)
          out[i2++] = num;
      }
      return out;
    }
  });
  require_privateDecrypt = __commonJS2((exports, module) => {
    var parseKeys = require_parse_asn1(), mgf = require_mgf(), xor = require_xor(), BN = require_bn4(), crt = require_browserify_rsa(), createHash = require_create_hash(), withPublic = require_withPublic(), Buffer22 = require_safe_buffer().Buffer;
    module.exports = function(privateKey, enc, reverse) {
      var padding;
      if (privateKey.padding)
        padding = privateKey.padding;
      else if (reverse)
        padding = 1;
      else
        padding = 4;
      var key = parseKeys(privateKey), k = key.modulus.byteLength();
      if (enc.length > k || new BN(enc).cmp(key.modulus) >= 0)
        throw Error("decryption error");
      var msg;
      if (reverse)
        msg = withPublic(new BN(enc), key);
      else
        msg = crt(enc, key);
      var zBuffer = Buffer22.alloc(k - msg.length);
      if (msg = Buffer22.concat([zBuffer, msg], k), padding === 4)
        return oaep(key, msg);
      else if (padding === 1)
        return pkcs1(key, msg, reverse);
      else if (padding === 3)
        return msg;
      else
        throw Error("unknown padding");
    };
    function oaep(key, msg) {
      var k = key.modulus.byteLength(), iHash = createHash("sha1").update(Buffer22.alloc(0)).digest(), hLen = iHash.length;
      if (msg[0] !== 0)
        throw Error("decryption error");
      var maskedSeed = msg.slice(1, hLen + 1), maskedDb = msg.slice(hLen + 1), seed = xor(maskedSeed, mgf(maskedDb, hLen)), db = xor(maskedDb, mgf(seed, k - hLen - 1));
      if (compare(iHash, db.slice(0, hLen)))
        throw Error("decryption error");
      var i2 = hLen;
      while (db[i2] === 0)
        i2++;
      if (db[i2++] !== 1)
        throw Error("decryption error");
      return db.slice(i2);
    }
    function pkcs1(key, msg, reverse) {
      var p1 = msg.slice(0, 2), i2 = 2, status = 0;
      while (msg[i2++] !== 0)
        if (i2 >= msg.length) {
          status++;
          break;
        }
      var ps = msg.slice(2, i2 - 1);
      if (p1.toString("hex") !== "0002" && !reverse || p1.toString("hex") !== "0001" && reverse)
        status++;
      if (ps.length < 8)
        status++;
      if (status)
        throw Error("decryption error");
      return msg.slice(i2);
    }
    function compare(a2, b) {
      a2 = Buffer22.from(a2), b = Buffer22.from(b);
      var dif = 0, len2 = a2.length;
      if (a2.length !== b.length)
        dif++, len2 = Math.min(a2.length, b.length);
      var i2 = -1;
      while (++i2 < len2)
        dif += a2[i2] ^ b[i2];
      return dif;
    }
  });
  require_browser2 = __commonJS2((exports) => {
    exports.publicEncrypt = require_publicEncrypt();
    exports.privateDecrypt = require_privateDecrypt();
    exports.privateEncrypt = function(key, buf) {
      return exports.publicEncrypt(key, buf, true);
    };
    exports.publicDecrypt = function(key, buf) {
      return exports.privateDecrypt(key, buf, true);
    };
  });
  require_public_encrypt = __commonJS2((exports) => {
    var crypto2 = (init_crypto(), __toCommonJS(exports_crypto));
    if (typeof crypto2.publicEncrypt !== "function")
      crypto2 = require_browser2();
    exports.publicEncrypt = crypto2.publicEncrypt;
    exports.privateDecrypt = crypto2.privateDecrypt;
    if (typeof crypto2.privateEncrypt !== "function")
      exports.privateEncrypt = require_browser2().privateEncrypt;
    else
      exports.privateEncrypt = crypto2.privateEncrypt;
    if (typeof crypto2.publicDecrypt !== "function")
      exports.publicDecrypt = require_browser2().publicDecrypt;
    else
      exports.publicDecrypt = crypto2.publicDecrypt;
  });
  require_browser3 = __commonJS2((exports) => {
    var safeBuffer = require_safe_buffer(), randombytes = require_randombytes(), Buffer22 = safeBuffer.Buffer, kBufferMaxLength = safeBuffer.kMaxLength, crypto2 = globalThis.crypto || globalThis.msCrypto, kMaxUint32 = Math.pow(2, 32) - 1;
    function assertOffset(offset, length) {
      if (typeof offset !== "number" || offset !== offset)
        throw TypeError("offset must be a number");
      if (offset > kMaxUint32 || offset < 0)
        throw TypeError("offset must be a uint32");
      if (offset > kBufferMaxLength || offset > length)
        throw RangeError("offset out of range");
    }
    function assertSize2(size, offset, length) {
      if (typeof size !== "number" || size !== size)
        throw TypeError("size must be a number");
      if (size > kMaxUint32 || size < 0)
        throw TypeError("size must be a uint32");
      if (size + offset > length || size > kBufferMaxLength)
        throw RangeError("buffer too small");
    }
    crypto2 && crypto2.getRandomValues, exports.randomFill = randomFill, exports.randomFillSync = randomFillSync;
    function randomFill(buf, offset, size, cb) {
      if (!Buffer22.isBuffer(buf) && !(buf instanceof globalThis.Uint8Array))
        throw TypeError('"buf" argument must be a Buffer or Uint8Array');
      if (typeof offset === "function")
        cb = offset, offset = 0, size = buf.length;
      else if (typeof size === "function")
        cb = size, size = buf.length - offset;
      else if (typeof cb !== "function")
        throw TypeError('"cb" argument must be a function');
      return assertOffset(offset, buf.length), assertSize2(size, offset, buf.length), actualFill(buf, offset, size, cb);
    }
    function actualFill(buf, offset, size, cb) {
      if (false)
        var ourBuf, uint;
      if (cb) {
        randombytes(size, function(err, bytes2) {
          if (err)
            return cb(err);
          bytes2.copy(buf, offset), cb(null, buf);
        });
        return;
      }
      var bytes = randombytes(size);
      return bytes.copy(buf, offset), buf;
    }
    function randomFillSync(buf, offset, size) {
      if (typeof offset > "u")
        offset = 0;
      if (!Buffer22.isBuffer(buf) && !(buf instanceof globalThis.Uint8Array))
        throw TypeError('"buf" argument must be a Buffer or Uint8Array');
      if (assertOffset(offset, buf.length), size === undefined)
        size = buf.length - offset;
      return assertSize2(size, offset, buf.length), actualFill(buf, offset, size);
    }
  });
  require_randomfill = __commonJS2((exports, module) => {
    var crypto2 = (init_crypto(), __toCommonJS(exports_crypto));
    if (typeof crypto2.randomFill === "function" && typeof crypto2.randomFillSync === "function")
      exports.randomFill = crypto2.randomFill, exports.randomFillSync = crypto2.randomFillSync;
    else
      module.exports = require_browser3();
  });
  require_crypto_browserify = __commonJS2((exports) => {
    exports.randomBytes = exports.rng = exports.pseudoRandomBytes = exports.prng = require_randombytes();
    exports.createHash = exports.Hash = require_create_hash();
    exports.createHmac = exports.Hmac = require_create_hmac();
    var algos = require_algorithms(), algoKeys = Object.keys(algos), hashes = ["sha1", "sha224", "sha256", "sha384", "sha512", "md5", "rmd160"].concat(algoKeys);
    exports.getHashes = function() {
      return hashes;
    };
    var p2 = require_pbkdf2();
    exports.pbkdf2 = p2.pbkdf2;
    exports.pbkdf2Sync = p2.pbkdf2Sync;
    var aes = require_browserify_cipher();
    exports.Cipher = aes.Cipher;
    exports.createCipher = aes.createCipher;
    exports.Cipheriv = aes.Cipheriv;
    exports.createCipheriv = aes.createCipheriv;
    exports.Decipher = aes.Decipher;
    exports.createDecipher = aes.createDecipher;
    exports.Decipheriv = aes.Decipheriv;
    exports.createDecipheriv = aes.createDecipheriv;
    exports.getCiphers = aes.getCiphers;
    exports.listCiphers = aes.listCiphers;
    var dh = require_diffie_hellman();
    exports.DiffieHellmanGroup = dh.DiffieHellmanGroup;
    exports.createDiffieHellmanGroup = dh.createDiffieHellmanGroup;
    exports.getDiffieHellman = dh.getDiffieHellman;
    exports.createDiffieHellman = dh.createDiffieHellman;
    exports.DiffieHellman = dh.DiffieHellman;
    var sign = require_browserify_sign();
    exports.createSign = sign.createSign;
    exports.Sign = sign.Sign;
    exports.createVerify = sign.createVerify;
    exports.Verify = sign.Verify;
    exports.createECDH = require_create_ecdh();
    var publicEncrypt = require_public_encrypt();
    exports.publicEncrypt = publicEncrypt.publicEncrypt;
    exports.privateEncrypt = publicEncrypt.privateEncrypt;
    exports.publicDecrypt = publicEncrypt.publicDecrypt;
    exports.privateDecrypt = publicEncrypt.privateDecrypt;
    var rf = require_randomfill();
    exports.randomFill = rf.randomFill;
    exports.randomFillSync = rf.randomFillSync;
    exports.createCredentials = function() {
      throw Error(`sorry, createCredentials is not implemented yet
we accept pull requests
https://github.com/browserify/crypto-browserify`);
    };
    exports.constants = { DH_CHECK_P_NOT_SAFE_PRIME: 2, DH_CHECK_P_NOT_PRIME: 1, DH_UNABLE_TO_CHECK_GENERATOR: 4, DH_NOT_SUITABLE_GENERATOR: 8, NPN_ENABLED: 1, ALPN_ENABLED: 1, RSA_PKCS1_PADDING: 1, RSA_SSLV23_PADDING: 2, RSA_NO_PADDING: 3, RSA_PKCS1_OAEP_PADDING: 4, RSA_X931_PADDING: 5, RSA_PKCS1_PSS_PADDING: 6, POINT_CONVERSION_COMPRESSED: 2, POINT_CONVERSION_UNCOMPRESSED: 4, POINT_CONVERSION_HYBRID: 6 };
  });
  cryptoBrowserify = __toESM2(require_crypto_browserify(), 1);
  prng2 = cryptoBrowserify.prng;
  pseudoRandomBytes2 = cryptoBrowserify.pseudoRandomBytes;
  rng2 = cryptoBrowserify.rng;
  randomBytes2 = cryptoBrowserify.randomBytes;
  Hash2 = cryptoBrowserify.Hash;
  createHash2 = cryptoBrowserify.createHash;
  Hmac2 = cryptoBrowserify.Hmac;
  createHmac2 = cryptoBrowserify.createHmac;
  getHashes2 = cryptoBrowserify.getHashes;
  pbkdf22 = cryptoBrowserify.pbkdf2;
  pbkdf2Sync2 = cryptoBrowserify.pbkdf2Sync;
  Cipher2 = cryptoBrowserify.Cipher;
  createCipher2 = cryptoBrowserify.createCipher;
  Cipheriv2 = cryptoBrowserify.Cipheriv;
  createCipheriv2 = cryptoBrowserify.createCipheriv;
  Decipher2 = cryptoBrowserify.Decipher;
  createDecipher2 = cryptoBrowserify.createDecipher;
  Decipheriv2 = cryptoBrowserify.Decipheriv;
  createDecipheriv2 = cryptoBrowserify.createDecipheriv;
  getCiphers2 = cryptoBrowserify.getCiphers;
  listCiphers2 = cryptoBrowserify.listCiphers;
  DiffieHellmanGroup2 = cryptoBrowserify.DiffieHellmanGroup;
  createDiffieHellmanGroup2 = cryptoBrowserify.createDiffieHellmanGroup;
  getDiffieHellman2 = cryptoBrowserify.getDiffieHellman;
  createDiffieHellman2 = cryptoBrowserify.createDiffieHellman;
  DiffieHellman2 = cryptoBrowserify.DiffieHellman;
  createSign2 = cryptoBrowserify.createSign;
  Sign2 = cryptoBrowserify.Sign;
  createVerify2 = cryptoBrowserify.createVerify;
  Verify2 = cryptoBrowserify.Verify;
  createECDH2 = cryptoBrowserify.createECDH;
  publicEncrypt2 = cryptoBrowserify.publicEncrypt;
  privateEncrypt2 = cryptoBrowserify.privateEncrypt;
  publicDecrypt2 = cryptoBrowserify.publicDecrypt;
  privateDecrypt2 = cryptoBrowserify.privateDecrypt;
  randomFill2 = cryptoBrowserify.randomFill;
  randomFillSync2 = cryptoBrowserify.randomFillSync;
  createCredentials2 = cryptoBrowserify.createCredentials;
  constants2 = cryptoBrowserify.constants;
  hardcoded_curves = ["p192", "p224", "p256", "p384", "p521", "curve25519", "ed25519", "secp256k1", "secp224r1", "prime256v1", "prime192v1", "ed25519", "secp384r1", "secp521r1"];
  webcrypto = crypto;
  crypto_default = crypto;
});

// node_modules/object-hash/index.js
var require_object_hash = __commonJS((exports, module) => {
  var crypto2 = (init_crypto(), __toCommonJS(exports_crypto));
  exports = module.exports = objectHash;
  function objectHash(object, options) {
    options = applyDefaults(object, options);
    return hash(object, options);
  }
  exports.sha1 = function(object) {
    return objectHash(object);
  };
  exports.keys = function(object) {
    return objectHash(object, { excludeValues: true, algorithm: "sha1", encoding: "hex" });
  };
  exports.MD5 = function(object) {
    return objectHash(object, { algorithm: "md5", encoding: "hex" });
  };
  exports.keysMD5 = function(object) {
    return objectHash(object, { algorithm: "md5", encoding: "hex", excludeValues: true });
  };
  var hashes = crypto2.getHashes ? crypto2.getHashes().slice() : ["sha1", "md5"];
  hashes.push("passthrough");
  var encodings = ["buffer", "hex", "binary", "base64"];
  function applyDefaults(object, sourceOptions) {
    sourceOptions = sourceOptions || {};
    var options = {};
    options.algorithm = sourceOptions.algorithm || "sha1";
    options.encoding = sourceOptions.encoding || "hex";
    options.excludeValues = sourceOptions.excludeValues ? true : false;
    options.algorithm = options.algorithm.toLowerCase();
    options.encoding = options.encoding.toLowerCase();
    options.ignoreUnknown = sourceOptions.ignoreUnknown !== true ? false : true;
    options.respectType = sourceOptions.respectType === false ? false : true;
    options.respectFunctionNames = sourceOptions.respectFunctionNames === false ? false : true;
    options.respectFunctionProperties = sourceOptions.respectFunctionProperties === false ? false : true;
    options.unorderedArrays = sourceOptions.unorderedArrays !== true ? false : true;
    options.unorderedSets = sourceOptions.unorderedSets === false ? false : true;
    options.unorderedObjects = sourceOptions.unorderedObjects === false ? false : true;
    options.replacer = sourceOptions.replacer || undefined;
    options.excludeKeys = sourceOptions.excludeKeys || undefined;
    if (typeof object === "undefined") {
      throw new Error("Object argument required.");
    }
    for (var i2 = 0;i2 < hashes.length; ++i2) {
      if (hashes[i2].toLowerCase() === options.algorithm.toLowerCase()) {
        options.algorithm = hashes[i2];
      }
    }
    if (hashes.indexOf(options.algorithm) === -1) {
      throw new Error('Algorithm "' + options.algorithm + '"  not supported. ' + "supported values: " + hashes.join(", "));
    }
    if (encodings.indexOf(options.encoding) === -1 && options.algorithm !== "passthrough") {
      throw new Error('Encoding "' + options.encoding + '"  not supported. ' + "supported values: " + encodings.join(", "));
    }
    return options;
  }
  function isNativeFunction(f) {
    if (typeof f !== "function") {
      return false;
    }
    var exp = /^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i;
    return exp.exec(Function.prototype.toString.call(f)) != null;
  }
  function hash(object, options) {
    var hashingStream;
    if (options.algorithm !== "passthrough") {
      hashingStream = crypto2.createHash(options.algorithm);
    } else {
      hashingStream = new PassThrough;
    }
    if (typeof hashingStream.write === "undefined") {
      hashingStream.write = hashingStream.update;
      hashingStream.end = hashingStream.update;
    }
    var hasher = typeHasher(options, hashingStream);
    hasher.dispatch(object);
    if (!hashingStream.update) {
      hashingStream.end("");
    }
    if (hashingStream.digest) {
      return hashingStream.digest(options.encoding === "buffer" ? undefined : options.encoding);
    }
    var buf = hashingStream.read();
    if (options.encoding === "buffer") {
      return buf;
    }
    return buf.toString(options.encoding);
  }
  exports.writeToStream = function(object, options, stream) {
    if (typeof stream === "undefined") {
      stream = options;
      options = {};
    }
    options = applyDefaults(object, options);
    return typeHasher(options, stream).dispatch(object);
  };
  function typeHasher(options, writeTo, context) {
    context = context || [];
    var write2 = function(str) {
      if (writeTo.update) {
        return writeTo.update(str, "utf8");
      } else {
        return writeTo.write(str, "utf8");
      }
    };
    return {
      dispatch: function(value) {
        if (options.replacer) {
          value = options.replacer(value);
        }
        var type = typeof value;
        if (value === null) {
          type = "null";
        }
        return this["_" + type](value);
      },
      _object: function(object) {
        var pattern = /\[object (.*)\]/i;
        var objString = Object.prototype.toString.call(object);
        var objType = pattern.exec(objString);
        if (!objType) {
          objType = "unknown:[" + objString + "]";
        } else {
          objType = objType[1];
        }
        objType = objType.toLowerCase();
        var objectNumber = null;
        if ((objectNumber = context.indexOf(object)) >= 0) {
          return this.dispatch("[CIRCULAR:" + objectNumber + "]");
        } else {
          context.push(object);
        }
        if (typeof Buffer !== "undefined" && Buffer.isBuffer && Buffer.isBuffer(object)) {
          write2("buffer:");
          return write2(object);
        }
        if (objType !== "object" && objType !== "function" && objType !== "asyncfunction") {
          if (this["_" + objType]) {
            this["_" + objType](object);
          } else if (options.ignoreUnknown) {
            return write2("[" + objType + "]");
          } else {
            throw new Error('Unknown object type "' + objType + '"');
          }
        } else {
          var keys = Object.keys(object);
          if (options.unorderedObjects) {
            keys = keys.sort();
          }
          if (options.respectType !== false && !isNativeFunction(object)) {
            keys.splice(0, 0, "prototype", "__proto__", "constructor");
          }
          if (options.excludeKeys) {
            keys = keys.filter(function(key) {
              return !options.excludeKeys(key);
            });
          }
          write2("object:" + keys.length + ":");
          var self2 = this;
          return keys.forEach(function(key) {
            self2.dispatch(key);
            write2(":");
            if (!options.excludeValues) {
              self2.dispatch(object[key]);
            }
            write2(",");
          });
        }
      },
      _array: function(arr, unordered) {
        unordered = typeof unordered !== "undefined" ? unordered : options.unorderedArrays !== false;
        var self2 = this;
        write2("array:" + arr.length + ":");
        if (!unordered || arr.length <= 1) {
          return arr.forEach(function(entry) {
            return self2.dispatch(entry);
          });
        }
        var contextAdditions = [];
        var entries = arr.map(function(entry) {
          var strm = new PassThrough;
          var localContext = context.slice();
          var hasher = typeHasher(options, strm, localContext);
          hasher.dispatch(entry);
          contextAdditions = contextAdditions.concat(localContext.slice(context.length));
          return strm.read().toString();
        });
        context = context.concat(contextAdditions);
        entries.sort();
        return this._array(entries, false);
      },
      _date: function(date) {
        return write2("date:" + date.toJSON());
      },
      _symbol: function(sym) {
        return write2("symbol:" + sym.toString());
      },
      _error: function(err) {
        return write2("error:" + err.toString());
      },
      _boolean: function(bool) {
        return write2("bool:" + bool.toString());
      },
      _string: function(string) {
        write2("string:" + string.length + ":");
        write2(string.toString());
      },
      _function: function(fn) {
        write2("fn:");
        if (isNativeFunction(fn)) {
          this.dispatch("[native]");
        } else {
          this.dispatch(fn.toString());
        }
        if (options.respectFunctionNames !== false) {
          this.dispatch("function-name:" + String(fn.name));
        }
        if (options.respectFunctionProperties) {
          this._object(fn);
        }
      },
      _number: function(number) {
        return write2("number:" + number.toString());
      },
      _xml: function(xml) {
        return write2("xml:" + xml.toString());
      },
      _null: function() {
        return write2("Null");
      },
      _undefined: function() {
        return write2("Undefined");
      },
      _regexp: function(regex) {
        return write2("regex:" + regex.toString());
      },
      _uint8array: function(arr) {
        write2("uint8array:");
        return this.dispatch(Array.prototype.slice.call(arr));
      },
      _uint8clampedarray: function(arr) {
        write2("uint8clampedarray:");
        return this.dispatch(Array.prototype.slice.call(arr));
      },
      _int8array: function(arr) {
        write2("int8array:");
        return this.dispatch(Array.prototype.slice.call(arr));
      },
      _uint16array: function(arr) {
        write2("uint16array:");
        return this.dispatch(Array.prototype.slice.call(arr));
      },
      _int16array: function(arr) {
        write2("int16array:");
        return this.dispatch(Array.prototype.slice.call(arr));
      },
      _uint32array: function(arr) {
        write2("uint32array:");
        return this.dispatch(Array.prototype.slice.call(arr));
      },
      _int32array: function(arr) {
        write2("int32array:");
        return this.dispatch(Array.prototype.slice.call(arr));
      },
      _float32array: function(arr) {
        write2("float32array:");
        return this.dispatch(Array.prototype.slice.call(arr));
      },
      _float64array: function(arr) {
        write2("float64array:");
        return this.dispatch(Array.prototype.slice.call(arr));
      },
      _arraybuffer: function(arr) {
        write2("arraybuffer:");
        return this.dispatch(new Uint8Array(arr));
      },
      _url: function(url) {
        return write2("url:" + url.toString(), "utf8");
      },
      _map: function(map) {
        write2("map:");
        var arr = Array.from(map);
        return this._array(arr, options.unorderedSets !== false);
      },
      _set: function(set) {
        write2("set:");
        var arr = Array.from(set);
        return this._array(arr, options.unorderedSets !== false);
      },
      _file: function(file) {
        write2("file:");
        return this.dispatch([file.name, file.size, file.type, file.lastModfied]);
      },
      _blob: function() {
        if (options.ignoreUnknown) {
          return write2("[blob]");
        }
        throw Error(`Hashing Blob objects is currently not supported
` + `(see https://github.com/puleos/object-hash/issues/26)
` + `Use "options.replacer" or "options.ignoreUnknown"
`);
      },
      _domwindow: function() {
        return write2("domwindow");
      },
      _bigint: function(number) {
        return write2("bigint:" + number.toString());
      },
      _process: function() {
        return write2("process");
      },
      _timer: function() {
        return write2("timer");
      },
      _pipe: function() {
        return write2("pipe");
      },
      _tcp: function() {
        return write2("tcp");
      },
      _udp: function() {
        return write2("udp");
      },
      _tty: function() {
        return write2("tty");
      },
      _statwatcher: function() {
        return write2("statwatcher");
      },
      _securecontext: function() {
        return write2("securecontext");
      },
      _connection: function() {
        return write2("connection");
      },
      _zlib: function() {
        return write2("zlib");
      },
      _context: function() {
        return write2("context");
      },
      _nodescript: function() {
        return write2("nodescript");
      },
      _httpparser: function() {
        return write2("httpparser");
      },
      _dataview: function() {
        return write2("dataview");
      },
      _signal: function() {
        return write2("signal");
      },
      _fsevent: function() {
        return write2("fsevent");
      },
      _tlswrap: function() {
        return write2("tlswrap");
      }
    };
  }
  function PassThrough() {
    return {
      buf: "",
      write: function(b) {
        this.buf += b;
      },
      end: function(b) {
        this.buf += b;
      },
      read: function() {
        return this.buf;
      }
    };
  }
});

// index.circuit.tsx
import { Fragment } from "react";

// node_modules/@tscircuit/capacity-autorouter/dist/chunk-G3PMV62Z.js
var e = Object.create;
var t = Object.defineProperty;
var r = Object.getOwnPropertyDescriptor;
var o = Object.getOwnPropertyNames;
var n = Object.getPrototypeOf;
var p = Object.prototype.hasOwnProperty;
var a = (e2, t2) => function() {
  return t2 || (0, e2[o(e2)[0]])((t2 = { exports: {} }).exports, t2), t2.exports;
};
var c = (e2, r2) => {
  for (var o2 in r2)
    t(e2, o2, { get: r2[o2], enumerable: true });
};
var l = (a2, c2, l2) => (l2 = a2 != null ? e(n(a2)) : {}, ((e2, n2, a3, c3) => {
  if (n2 && typeof n2 == "object" || typeof n2 == "function")
    for (let l3 of o(n2))
      p.call(e2, l3) || l3 === a3 || t(e2, l3, { get: () => n2[l3], enumerable: !(c3 = r(n2, l3)) || c3.enumerable });
  return e2;
})(!c2 && a2 && a2.__esModule ? l2 : t(l2, "default", { value: a2, enumerable: true }), a2));

// node_modules/@tscircuit/solver-utils/dist/chunk-FCNBEO2E.js
function webWorkerEndpoint(target) {
  return {
    postMessage: (message) => target.postMessage(message),
    onMessage: (listener) => {
      const handler = (event) => listener(event.data);
      target.addEventListener("message", handler);
      return () => target.removeEventListener("message", handler);
    }
  };
}
function cloneSolverData(value) {
  return new Promise((resolve, reject) => {
    const channel = new MessageChannel;
    const close = () => {
      channel.port1.close();
      channel.port2.close();
    };
    channel.port2.onmessage = (event) => {
      close();
      resolve(event.data);
    };
    channel.port2.onmessageerror = () => {
      close();
      reject(new Error("Could not deserialize solver data"));
    };
    try {
      channel.port1.postMessage(value);
    } catch (error) {
      close();
      reject(error);
    }
  });
}
function getRegisteredSolverName(Solver) {
  if (!Object.hasOwn(Solver, "solverName") || typeof Solver.solverName !== "string" || Solver.solverName.trim().length === 0) {
    throw new Error("Solver must define its own non-empty static solverName");
  }
  return Solver.solverName;
}
var SOLVER_RUNTIME_PROTOCOL = 1;
function serializeSolverError(error) {
  if (error instanceof Error) {
    return { name: error.name, message: error.message, stack: error.stack };
  }
  return { name: "Error", message: String(error) };
}
function deserializeSolverError(error) {
  const result = new Error(error.message);
  result.name = error.name;
  result.stack = error.stack;
  return result;
}
var constructors = /* @__PURE__ */ new Map;
var SolverRuntime = class _SolverRuntime {
  options;
  slots = [];
  jobs = /* @__PURE__ */ new Set;
  queue = [];
  initialization;
  termination;
  stopped;
  nextId = 0;
  constructor(options = {}) {
    if (!Number.isInteger(options.workerCount ?? 1) || (options.workerCount ?? 1) < 1) {
      throw new Error("workerCount must be a positive integer");
    }
    if (!Number.isFinite(options.startupTimeoutMs ?? 1e4) || (options.startupTimeoutMs ?? 1e4) <= 0) {
      throw new Error("startupTimeoutMs must be positive and finite");
    }
    this.options = options;
  }
  static registerSolver(Solver) {
    const name = getRegisteredSolverName(Solver);
    const existing = constructors.get(name);
    if (existing && existing !== Solver) {
      throw new Error('Solver "' + name + '" is already registered');
    }
    constructors.set(name, Solver);
  }
  static listen(endpoint = webWorkerEndpoint(globalThis)) {
    const runtime = new _SolverRuntime;
    const removeListener = endpoint.onMessage((message) => {
      const request = message;
      if (request?.solverRuntime !== SOLVER_RUNTIME_PROTOCOL)
        return;
      if (request.type === "hello") {
        endpoint.postMessage({
          solverRuntime: SOLVER_RUNTIME_PROTOCOL,
          type: "ready",
          names: Array.from(constructors.keys())
        });
        return;
      }
      if (request.type !== "execute")
        return;
      runtime.executeAsync(request.name, request.input).then((output) => {
        try {
          endpoint.postMessage({
            solverRuntime: SOLVER_RUNTIME_PROTOCOL,
            type: "output",
            id: request.id,
            output
          });
        } catch (error) {
          endpoint.postMessage({
            solverRuntime: SOLVER_RUNTIME_PROTOCOL,
            type: "error",
            id: request.id,
            error: serializeSolverError(error)
          });
        }
      }, (error) => endpoint.postMessage({
        solverRuntime: SOLVER_RUNTIME_PROTOCOL,
        type: "error",
        id: request.id,
        error: serializeSolverError(error)
      }));
    });
    return () => {
      removeListener();
      runtime.dispose();
    };
  }
  executeAsync(solver, input) {
    if (this.stopped)
      return Promise.reject(this.stopped);
    let name;
    try {
      name = typeof solver === "string" ? solver : getRegisteredSolverName(solver);
      const registered = constructors.get(name);
      if (typeof solver !== "string" && registered && registered !== solver) {
        throw new Error('Solver "' + name + '" is registered with a different constructor');
      }
    } catch (error) {
      return Promise.reject(error);
    }
    const snapshot = cloneSolverData(input);
    return new Promise((resolve, reject) => {
      const job = {
        id: this.nextId++,
        name,
        input: undefined,
        resolve,
        reject
      };
      this.jobs.add(job);
      snapshot.then(async (value) => {
        job.input = value;
        try {
          await this.initialize();
          if (!this.jobs.has(job))
            return;
          if (this.slots.some((slot) => slot.names.has(name))) {
            this.queue.push(job);
            this.dispatch();
          } else if (this.options.requireWorker) {
            throw new Error('No worker registered solver "' + name + '"');
          } else {
            const output = await this.executeInline(name, value);
            this.finish(job, undefined, output);
          }
        } catch (error) {
          this.finish(job, error instanceof Error ? error : new Error(String(error)));
        }
      }, (error) => {
        this.finish(job, error instanceof Error ? error : new Error(String(error)));
      });
    });
  }
  async executeInline(name, input) {
    const Solver = constructors.get(name);
    if (!Solver)
      throw new Error('Unknown solver "' + name + '"');
    const solver = new Solver(input);
    if (solver.solveAsync) {
      await solver.solveAsync(this);
    } else {
      solver.solve();
    }
    if (solver.failed) {
      throw new Error(solver.error || 'Solver "' + name + '" failed');
    }
    return cloneSolverData(solver.getOutput());
  }
  initialize() {
    if (!this.initialization) {
      this.initialization = this.startWorkers();
    }
    return this.initialization;
  }
  async startWorkers() {
    if (!this.options.createWorker)
      return;
    try {
      await Promise.all(Array.from({ length: this.options.workerCount ?? 1 }, () => this.startWorker()));
    } catch (error) {
      const failure = error instanceof Error ? error : new Error(String(error));
      await this.terminateWorkers();
      if (this.stopped)
        throw this.stopped;
      if (this.options.startupFailure === "serial" && !this.options.requireWorker) {
        if (this.options.onDiagnostic)
          this.options.onDiagnostic(failure);
        else
          console.warn("SolverRuntime: worker startup failed; using serial execution", failure);
      } else {
        this.stop(failure);
        throw failure;
      }
    }
  }
  async startWorker() {
    if (this.stopped)
      return Promise.reject(this.stopped);
    const worker = this.options.createWorker();
    const slot = {
      worker,
      names: /* @__PURE__ */ new Set,
      job: null,
      removeListeners: []
    };
    this.slots.push(slot);
    return new Promise((resolve, reject) => {
      let ready = false;
      const timer = setTimeout(() => {
        reject(new Error("Solver worker startup timed out"));
      }, this.options.startupTimeoutMs ?? 1e4);
      slot.removeListeners.push(() => {
        clearTimeout(timer);
        if (!ready)
          reject(this.stopped ?? new Error("Solver worker startup interrupted"));
      });
      slot.removeListeners.push(worker.onError((error) => {
        if (!ready) {
          clearTimeout(timer);
          reject(error);
        } else {
          this.stop(error);
          this.terminateAfterFailure();
        }
      }));
      slot.removeListeners.push(worker.onMessage((message) => {
        const response = message;
        if (response?.solverRuntime !== SOLVER_RUNTIME_PROTOCOL)
          return;
        if (!ready && response.type === "ready" && Array.isArray(response.names)) {
          ready = true;
          clearTimeout(timer);
          slot.names = new Set(response.names);
          resolve();
        } else if (ready && slot.job && (response.type === "output" || response.type === "error") && response.id === slot.job.id) {
          const job = slot.job;
          slot.job = null;
          if (response.type === "error") {
            this.finish(job, deserializeSolverError(response.error));
          } else {
            this.finish(job, undefined, response.output);
          }
          this.dispatch();
        } else {
          const error = new Error("Invalid solver worker protocol response");
          clearTimeout(timer);
          reject(error);
          this.stop(error);
          this.terminateAfterFailure();
        }
      }));
      try {
        worker.postMessage({
          solverRuntime: SOLVER_RUNTIME_PROTOCOL,
          type: "hello"
        });
      } catch (error) {
        clearTimeout(timer);
        reject(error);
      }
    });
  }
  dispatch() {
    if (this.stopped)
      return;
    for (const slot of this.slots) {
      if (slot.job)
        continue;
      const index = this.queue.findIndex((job2) => slot.names.has(job2.name));
      if (index === -1)
        continue;
      const job = this.queue.splice(index, 1)[0];
      slot.job = job;
      try {
        slot.worker.postMessage({
          solverRuntime: SOLVER_RUNTIME_PROTOCOL,
          type: "execute",
          id: job.id,
          name: job.name,
          input: job.input
        });
      } catch (error) {
        slot.job = null;
        this.finish(job, error instanceof Error ? error : new Error(String(error)));
        this.dispatch();
      }
    }
  }
  finish(job, error, output) {
    if (!this.jobs.delete(job))
      return;
    if (error)
      job.reject(error);
    else
      job.resolve(output);
  }
  stop(error) {
    this.stopped = error;
    this.queue = [];
    for (const job of this.jobs)
      this.finish(job, error);
  }
  async terminateWorkers() {
    if (this.termination)
      return this.termination;
    const slots = this.slots.splice(0);
    for (const slot of slots) {
      for (const remove of slot.removeListeners)
        remove();
    }
    this.termination = Promise.allSettled(slots.map(async (slot) => {
      await slot.worker.terminate();
    })).then((results) => {
      const failures = results.filter((result) => result.status === "rejected");
      if (failures.length) {
        throw new AggregateError(failures.map((result) => result.reason), "Could not terminate solver workers");
      }
    });
    return this.termination;
  }
  terminateAfterFailure() {
    this.terminateWorkers().catch((error) => {
      if (this.options.onDiagnostic)
        this.options.onDiagnostic(error);
      else
        console.error("SolverRuntime: worker cleanup failed", error);
    });
  }
  async dispose() {
    this.stop(new Error("Solver runtime disposed"));
    await this.terminateWorkers();
  }
};

// node_modules/@tscircuit/alphabet/dist/index.js
var svgAlphabet = {
  "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"
};
var lineAlphabet = {};
for (const letter in svgAlphabet) {
  lineAlphabet[letter] = [];
  const segs = svgAlphabet[letter].split("M").slice(1).map((seg) => seg.split("L").map((pr) => pr.trim().split(" ").map(parseFloat)));
  for (const seg of segs) {
    for (let i = 0;i < seg.length - 1; i++) {
      lineAlphabet[letter].push({
        x1: seg[i][0],
        y1: 1 - seg[i][1],
        x2: seg[i + 1][0],
        y2: 1 - seg[i + 1][1]
      });
    }
  }
}

// node_modules/iobuffer/lib/text.js
var encoder = new TextEncoder;

// node_modules/iobuffer/lib/iobuffer.js
var defaultByteLength = 1024 * 8;
var hostBigEndian = (() => {
  const array = new Uint8Array(4);
  const view = new Uint32Array(array.buffer);
  return !((view[0] = 1) & array[0]);
})();
var 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
};

// node_modules/fast-png/lib/helpers/crc.js
var crcTable = [];
for (let n2 = 0;n2 < 256; n2++) {
  let c2 = n2;
  for (let k = 0;k < 8; k++) {
    if (c2 & 1) {
      c2 = 3988292384 ^ c2 >>> 1;
    } else {
      c2 = c2 >>> 1;
    }
  }
  crcTable[n2] = c2;
}

// node_modules/fast-png/lib/helpers/decode_interlace_adam7.js
var uint16 = new Uint16Array([255]);
var uint8 = new Uint8Array(uint16.buffer);
var osIsLittleEndian = uint8[0] === 255;

// node_modules/fast-png/lib/helpers/decode_interlace_null.js
var uint162 = new Uint16Array([255]);
var uint82 = new Uint8Array(uint162.buffer);
var osIsLittleEndian2 = uint82[0] === 255;
var empty = new Uint8Array(0);

// node_modules/fast-png/lib/helpers/signature.js
var pngSignature = Uint8Array.of(137, 80, 78, 71, 13, 10, 26, 10);

// node_modules/fast-png/lib/helpers/text.js
var latin1Decoder = new TextDecoder("latin1");
// node_modules/svgson/dist/svgson.esm.js
var import_deep_rename_keys = __toESM(require_deep_rename_keys(), 1);
var import_xml_reader = __toESM(require_reader(), 1);

// node_modules/graphics-debug/dist/chunk-OB4CGOL3.js
function setStepOfAllObjects(graphics, step) {
  if (graphics.points) {
    for (const p2 of graphics.points) {
      p2.step = step;
    }
  }
  if (graphics.lines) {
    for (const line of graphics.lines) {
      line.step = step;
    }
  }
  if (graphics.infiniteLines) {
    for (const infiniteLine of graphics.infiniteLines) {
      infiniteLine.step = step;
    }
  }
  if (graphics.polygons) {
    for (const polygon of graphics.polygons) {
      polygon.step = step;
    }
  }
  if (graphics.rects) {
    for (const rect of graphics.rects) {
      rect.step = step;
    }
  }
  if (graphics.circles) {
    for (const circle of graphics.circles) {
      circle.step = step;
    }
  }
  if (graphics.texts) {
    for (const text of graphics.texts) {
      text.step = step;
    }
  }
  return graphics;
}

// node_modules/@tscircuit/solver-utils/dist/index.js
var BaseSolver = class {
  MAX_ITERATIONS = 1e5;
  solved = false;
  failed = false;
  iterations = 0;
  progress = 0;
  error = null;
  activeSubSolver;
  failedSubSolvers;
  timeToSolve;
  stats = {};
  _setupDone = false;
  getSolverName() {
    return this.constructor.name;
  }
  setup() {
    if (this._setupDone)
      return;
    this._setup();
    this._setupDone = true;
  }
  _setup() {}
  step() {
    if (!this._setupDone) {
      this.setup();
    }
    if (this.solved)
      return;
    if (this.failed)
      return;
    this.iterations++;
    try {
      this._step();
    } catch (e2) {
      this.error = `${this.getSolverName()} error: ${e2}`;
      this.failed = true;
      throw e2;
    }
    if (!this.solved && this.iterations >= this.MAX_ITERATIONS) {
      this.tryFinalAcceptance();
    }
    if (!this.solved && this.iterations >= this.MAX_ITERATIONS) {
      this.error = `${this.getSolverName()} ran out of iterations`;
      this.failed = true;
    }
    if ("computeProgress" in this) {
      this.progress = this.computeProgress();
    }
  }
  _step() {}
  getConstructorParams() {
    throw new Error("getConstructorParams not implemented");
  }
  getOutput() {
    return null;
  }
  solve() {
    const startTime = Date.now();
    while (!this.solved && !this.failed) {
      this.step();
    }
    const endTime = Date.now();
    this.timeToSolve = endTime - startTime;
  }
  visualize() {
    return {
      lines: [],
      points: [],
      rects: [],
      circles: []
    };
  }
  tryFinalAcceptance() {}
  preview() {
    return {
      lines: [],
      points: [],
      rects: [],
      circles: []
    };
  }
};
function definePipelineStep(solverName, solverClass, getConstructorParams, opts = {}) {
  return {
    solverName,
    solverClass,
    getConstructorParams,
    onSolved: opts.onSolved
  };
}
var BasePipelineSolver = class extends BaseSolver {
  startTimeOfStage = {};
  endTimeOfStage = {};
  timeSpentOnStage = {};
  firstIterationOfStage = {};
  currentPipelineStageIndex = 0;
  inputProblem;
  pipelineOutputs = {};
  constructor(inputProblem) {
    super();
    this.inputProblem = inputProblem;
    this.MAX_ITERATIONS = 1e6;
  }
  _step() {
    const pipelineStageDef = this.pipelineDef[this.currentPipelineStageIndex];
    if (!pipelineStageDef) {
      this.solved = true;
      return;
    }
    if (this.activeSubSolver) {
      this.activeSubSolver.step();
      if (this.activeSubSolver.solved) {
        this.endTimeOfStage[pipelineStageDef.solverName] = performance.now();
        this.timeSpentOnStage[pipelineStageDef.solverName] = this.endTimeOfStage[pipelineStageDef.solverName] - this.startTimeOfStage[pipelineStageDef.solverName];
        const output = this.activeSubSolver.getOutput();
        if (output !== null) {
          this.pipelineOutputs[pipelineStageDef.solverName] = output;
        }
        pipelineStageDef.onSolved?.(this);
        this.activeSubSolver = null;
        this.currentPipelineStageIndex++;
      } else if (this.activeSubSolver.failed) {
        this.error = this.activeSubSolver?.error;
        this.failed = true;
        this.activeSubSolver = null;
      }
      return;
    }
    const constructorParams = pipelineStageDef.getConstructorParams(this);
    this.activeSubSolver = new pipelineStageDef.solverClass(...constructorParams);
    this[pipelineStageDef.solverName] = this.activeSubSolver;
    this.timeSpentOnStage[pipelineStageDef.solverName] = 0;
    this.startTimeOfStage[pipelineStageDef.solverName] = performance.now();
    this.firstIterationOfStage[pipelineStageDef.solverName] = this.iterations;
  }
  solveUntilStage(stageName) {
    while (this.getCurrentStageName().toLowerCase() !== stageName.toLowerCase()) {
      this.step();
      if (this.failed || this.solved)
        break;
    }
  }
  getCurrentStageName() {
    return this.pipelineDef[this.currentPipelineStageIndex]?.solverName ?? "none";
  }
  getStageProgress() {
    const totalStages = this.pipelineDef.length;
    if (totalStages === 0)
      return 1;
    const currentStageProgress = this.activeSubSolver?.progress ?? 0;
    return (this.currentPipelineStageIndex + currentStageProgress) / totalStages;
  }
  getStageStats() {
    const stats = {};
    for (const stage of this.pipelineDef) {
      const timeSpent = this.timeSpentOnStage[stage.solverName] || 0;
      const firstIteration = this.firstIterationOfStage[stage.solverName] || 0;
      const currentIteration = this.iterations;
      const iterations = stage.solverName === this.getCurrentStageName() ? currentIteration - firstIteration : 0;
      const completed = this.currentPipelineStageIndex > this.pipelineDef.findIndex((s) => s.solverName === stage.solverName);
      stats[stage.solverName] = {
        timeSpent,
        iterations,
        completed
      };
    }
    return stats;
  }
  initialVisualize() {
    return null;
  }
  finalVisualize() {
    return null;
  }
  visualize() {
    if (!this.solved && this.activeSubSolver) {
      return this.activeSubSolver.visualize();
    }
    let stageStepOffset = 0;
    const initialVisualization = this.initialVisualize();
    if (initialVisualization) {
      setStepOfAllObjects(initialVisualization, 0);
      stageStepOffset = 1;
    }
    let finalVisualization = null;
    if (this.solved) {
      finalVisualization = this.finalVisualize();
    }
    const visualizations = [initialVisualization].filter(Boolean).concat(this.pipelineDef.map((stage, stageIndex) => {
      const solver = this[stage.solverName];
      const viz = solver?.visualize();
      if (!viz)
        return null;
      setStepOfAllObjects(viz, stageIndex + stageStepOffset);
      return viz;
    }).filter(Boolean));
    if (visualizations.length === 0) {
      return { points: [], rects: [], lines: [], circles: [], texts: [] };
    }
    if (this.solved && finalVisualization) {
      setStepOfAllObjects(finalVisualization, visualizations.length + stageStepOffset + 1);
      visualizations.push(finalVisualization);
    }
    if (visualizations.length === 1) {
      return visualizations[0];
    }
    return {
      points: visualizations.flatMap((v) => v.points || []),
      rects: visualizations.flatMap((v) => v.rects || []),
      lines: visualizations.flatMap((v) => v.lines || []),
      circles: visualizations.flatMap((v) => v.circles || []),
      texts: visualizations.flatMap((v) => v.texts || [])
    };
  }
  preview() {
    if (this.activeSubSolver) {
      return this.activeSubSolver.preview();
    }
    return super.preview();
  }
  computeProgress() {
    return this.getStageProgress();
  }
  getStageOutput(stageOutput) {
    return this.pipelineOutputs[stageOutput];
  }
  getAllOutputs() {
    return { ...this.pipelineOutputs };
  }
  hasStageOutput(stageName) {
    return stageName in this.pipelineOutputs;
  }
  getSolver(stageName) {
    return this[stageName];
  }
};

// node_modules/@tscircuit/capacity-autorouter/dist/index.js
var import_object_hash = __toESM(require_object_hash(), 1);
var import_object_hash2 = __toESM(require_object_hash(), 1);
var import_object_hash3 = __toESM(require_object_hash(), 1);
var o2 = a({ "node_modules/is-buffer/index.js"(e2, t2) {
  function n2(e3) {
    return !!e3.constructor && typeof e3.constructor.isBuffer == "function" && e3.constructor.isBuffer(e3);
  }
  t2.exports = function(e3) {
    return e3 != null && (n2(e3) || function(e4) {
      return typeof e4.readFloatLE == "function" && typeof e4.slice == "function" && n2(e4.slice(0, 0));
    }(e3) || !!e3._isBuffer);
  };
} });
var i2 = a({ "node_modules/kind-of/index.js"(e2, t2) {
  var n2 = o2(), i3 = Object.prototype.toString;
  t2.exports = function(e3) {
    if (e3 === undefined)
      return "undefined";
    if (e3 === null)
      return "null";
    if (e3 === true || e3 === false || e3 instanceof Boolean)
      return "boolean";
    if (typeof e3 == "string" || e3 instanceof String)
      return "string";
    if (typeof e3 == "number" || e3 instanceof Number)
      return "number";
    if (typeof e3 == "function" || e3 instanceof Function)
      return "function";
    if (Array.isArray !== undefined && Array.isArray(e3))
      return "array";
    if (e3 instanceof RegExp)
      return "regexp";
    if (e3 instanceof Date)
      return "date";
    var t3 = i3.call(e3);
    return t3 === "[object RegExp]" ? "regexp" : t3 === "[object Date]" ? "date" : t3 === "[object Arguments]" ? "arguments" : t3 === "[object Error]" ? "error" : n2(e3) ? "buffer" : t3 === "[object Set]" ? "set" : t3 === "[object WeakSet]" ? "weakset" : t3 === "[object Map]" ? "map" : t3 === "[object WeakMap]" ? "weakmap" : t3 === "[object Symbol]" ? "symbol" : t3 === "[object Int8Array]" ? "int8array" : t3 === "[object Uint8Array]" ? "uint8array" : t3 === "[object Uint8ClampedArray]" ? "uint8clampedarray" : t3 === "[object Int16Array]" ? "int16array" : t3 === "[object Uint16Array]" ? "uint16array" : t3 === "[object Int32Array]" ? "int32array" : t3 === "[object Uint32Array]" ? "uint32array" : t3 === "[object Float32Array]" ? "float32array" : t3 === "[object Float64Array]" ? "float64array" : "object";
  };
} });
var r2 = a({ "node_modules/rename-keys/index.js"(e2, t2) {
  (function() {
    function e3(e4, t3) {
      if (typeof t3 != "function")
        return e4;
      var n2 = {};
      for (var o3 in e4)
        Object.prototype.hasOwnProperty.call(e4, o3) && (n2[t3(o3, e4[o3]) || o3] = e4[o3]);
      return n2;
    }
    t2 !== undefined && t2.exports ? t2.exports = e3 : typeof define == "function" && define.amd ? define([], function() {
      return e3;
    }) : window.rename = e3;
  })();
} });
var s = a({ "node_modules/deep-rename-keys/index.js"(e2, t2) {
  var n2 = i2(), o3 = r2();
  t2.exports = function e3(t3, i3) {
    var r3 = n2(t3);
    if (r3 !== "object" && r3 !== "array")
      throw new Error("expected an object");
    var s2 = [];
    for (var a2 in r3 === "object" && (t3 = o3(t3, i3), s2 = {}), t3)
      if (t3.hasOwnProperty(a2)) {
        var c2 = t3[a2];
        n2(c2) === "object" || n2(c2) === "array" ? s2[a2] = e3(c2, i3) : s2[a2] = c2;
      }
    return s2;
  };
} });
var a2 = a({ "node_modules/xml-reader/node_modules/eventemitter3/index.js"(e2, t2) {
  var n2 = Object.prototype.hasOwnProperty, o3 = "~";
  function i3() {}
  function r3(e3, t3, n3) {
    this.fn = e3, this.context = t3, this.once = n3 || false;
  }
  function s2() {
    this._events = new i3, this._eventsCount = 0;
  }
  Object.create && (i3.prototype = Object.create(null), new i3().__proto__ || (o3 = false)), s2.prototype.eventNames = function() {
    var e3, t3, i4 = [];
    if (this._eventsCount === 0)
      return i4;
    for (t3 in e3 = this._events)
      n2.call(e3, t3) && i4.push(o3 ? t3.slice(1) : t3);
    return Object.getOwnPropertySymbols ? i4.concat(Object.getOwnPropertySymbols(e3)) : i4;
  }, s2.prototype.listeners = function(e3, t3) {
    var n3 = o3 ? o3 + e3 : e3, i4 = this._events[n3];
    if (t3)
      return !!i4;
    if (!i4)
      return [];
    if (i4.fn)
      return [i4.fn];
    for (var r4 = 0, s3 = i4.length, a3 = new Array(s3);r4 < s3; r4++)
      a3[r4] = i4[r4].fn;
    return a3;
  }, s2.prototype.emit = function(e3, t3, n3, i4, r4, s3) {
    var a3 = o3 ? o3 + e3 : e3;
    if (!this._events[a3])
      return false;
    var c2, l2, h = this._events[a3], d = arguments.length;
    if (h.fn) {
      switch (h.once && this.removeListener(e3, h.fn, undefined, true), d) {
        case 1:
          return h.fn.call(h.context), true;
        case 2:
          return h.fn.call(h.context, t3), true;
        case 3:
          return h.fn.call(h.context, t3, n3), true;
        case 4:
          return h.fn.call(h.context, t3, n3, i4), true;
        case 5:
          return h.fn.call(h.context, t3, n3, i4, r4), true;
        case 6:
          return h.fn.call(h.context, t3, n3, i4, r4, s3), true;
      }
      for (l2 = 1, c2 = new Array(d - 1);l2 < d; l2++)
        c2[l2 - 1] = arguments[l2];
      h.fn.apply(h.context, c2);
    } else {
      var u, p2 = h.length;
      for (l2 = 0;l2 < p2; l2++)
        switch (h[l2].once && this.removeListener(e3, h[l2].fn, undefined, true), d) {
          case 1:
            h[l2].fn.call(h[l2].context);
            break;
          case 2:
            h[l2].fn.call(h[l2].context, t3);
            break;
          case 3:
            h[l2].fn.call(h[l2].context, t3, n3);
            break;
          case 4:
            h[l2].fn.call(h[l2].context, t3, n3, i4);
            break;
          default:
            if (!c2)
              for (u = 1, c2 = new Array(d - 1);u < d; u++)
                c2[u - 1] = arguments[u];
            h[l2].fn.apply(h[l2].context, c2);
        }
    }
    return true;
  }, s2.prototype.on = function(e3, t3, n3) {
    var i4 = new r3(t3, n3 || this), s3 = o3 ? o3 + e3 : e3;
    return this._events[s3] ? this._events[s3].fn ? this._events[s3] = [this._events[s3], i4] : this._events[s3].push(i4) : (this._events[s3] = i4, this._eventsCount++), this;
  }, s2.prototype.once = function(e3, t3, n3) {
    var i4 = new r3(t3, n3 || this, true), s3 = o3 ? o3 + e3 : e3;
    return this._events[s3] ? this._events[s3].fn ? this._events[s3] = [this._events[s3], i4] : this._events[s3].push(i4) : (this._events[s3] = i4, this._eventsCount++), this;
  }, s2.prototype.removeListener = function(e3, t3, n3, r4) {
    var s3 = o3 ? o3 + e3 : e3;
    if (!this._events[s3])
      return this;
    if (!t3)
      return --this._eventsCount === 0 ? this._events = new i3 : delete this._events[s3], this;
    var a3 = this._events[s3];
    if (a3.fn)
      a3.fn !== t3 || r4 && !a3.once || n3 && a3.context !== n3 || (--this._eventsCount === 0 ? this._events = new i3 : delete this._events[s3]);
    else {
      for (var c2 = 0, l2 = [], h = a3.length;c2 < h; c2++)
        (a3[c2].fn !== t3 || r4 && !a3[c2].once || n3 && a3[c2].context !== n3) && l2.push(a3[c2]);
      l2.length ? this._events[s3] = l2.length === 1 ? l2[0] : l2 : --this._eventsCount === 0 ? this._events = new i3 : delete this._events[s3];
    }
    return this;
  }, s2.prototype.removeAllListeners = function(e3) {
    var t3;
    return e3 ? (t3 = o3 ? o3 + e3 : e3, this._events[t3] && (--this._eventsCount === 0 ? this._events = new i3 : delete this._events[t3])) : (this._events = new i3, this._eventsCount = 0), this;
  }, s2.prototype.off = s2.prototype.removeListener, s2.prototype.addListener = s2.prototype.on, s2.prototype.setMaxListeners = function() {
    return this;
  }, s2.prefixed = o3, s2.EventEmitter = s2, t2 !== undefined && (t2.exports = s2);
} });
var c2 = a({ "node_modules/xml-lexer/node_modules/eventemitter3/index.js"(e2, t2) {
  var n2 = Object.prototype.hasOwnProperty, o3 = "~";
  function i3() {}
  function r3(e3, t3, n3) {
    this.fn = e3, this.context = t3, this.once = n3 || false;
  }
  function s2() {
    this._events = new i3, this._eventsCount = 0;
  }
  Object.create && (i3.prototype = Object.create(null), new i3().__proto__ || (o3 = false)), s2.prototype.eventNames = function() {
    var e3, t3, i4 = [];
    if (this._eventsCount === 0)
      return i4;
    for (t3 in e3 = this._events)
      n2.call(e3, t3) && i4.push(o3 ? t3.slice(1) : t3);
    return Object.getOwnPropertySymbols ? i4.concat(Object.getOwnPropertySymbols(e3)) : i4;
  }, s2.prototype.listeners = function(e3, t3) {
    var n3 = o3 ? o3 + e3 : e3, i4 = this._events[n3];
    if (t3)
      return !!i4;
    if (!i4)
      return [];
    if (i4.fn)
      return [i4.fn];
    for (var r4 = 0, s3 = i4.length, a3 = new Array(s3);r4 < s3; r4++)
      a3[r4] = i4[r4].fn;
    return a3;
  }, s2.prototype.emit = function(e3, t3, n3, i4, r4, s3) {
    var a3 = o3 ? o3 + e3 : e3;
    if (!this._events[a3])
      return false;
    var c3, l2, h = this._events[a3], d = arguments.length;
    if (h.fn) {
      switch (h.once && this.removeListener(e3, h.fn, undefined, true), d) {
        case 1:
          return h.fn.call(h.context), true;
        case 2:
          return h.fn.call(h.context, t3), true;
        case 3:
          return h.fn.call(h.context, t3, n3), true;
        case 4:
          return h.fn.call(h.context, t3, n3, i4), true;
        case 5:
          return h.fn.call(h.context, t3, n3, i4, r4), true;
        case 6:
          return h.fn.call(h.context, t3, n3, i4, r4, s3), true;
      }
      for (l2 = 1, c3 = new Array(d - 1);l2 < d; l2++)
        c3[l2 - 1] = arguments[l2];
      h.fn.apply(h.context, c3);
    } else {
      var u, p2 = h.length;
      for (l2 = 0;l2 < p2; l2++)
        switch (h[l2].once && this.removeListener(e3, h[l2].fn, undefined, true), d) {
          case 1:
            h[l2].fn.call(h[l2].context);
            break;
          case 2:
            h[l2].fn.call(h[l2].context, t3);
            break;
          case 3:
            h[l2].fn.call(h[l2].context, t3, n3);
            break;
          case 4:
            h[l2].fn.call(h[l2].context, t3, n3, i4);
            break;
          default:
            if (!c3)
              for (u = 1, c3 = new Array(d - 1);u < d; u++)
                c3[u - 1] = arguments[u];
            h[l2].fn.apply(h[l2].context, c3);
        }
    }
    return true;
  }, s2.prototype.on = function(e3, t3, n3) {
    var i4 = new r3(t3, n3 || this), s3 = o3 ? o3 + e3 : e3;
    return this._events[s3] ? this._events[s3].fn ? this._events[s3] = [this._events[s3], i4] : this._events[s3].push(i4) : (this._events[s3] = i4, this._eventsCount++), this;
  }, s2.prototype.once = function(e3, t3, n3) {
    var i4 = new r3(t3, n3 || this, true), s3 = o3 ? o3 + e3 : e3;
    return this._events[s3] ? this._events[s3].fn ? this._events[s3] = [this._events[s3], i4] : this._events[s3].push(i4) : (this._events[s3] = i4, this._eventsCount++), this;
  }, s2.prototype.removeListener = function(e3, t3, n3, r4) {
    var s3 = o3 ? o3 + e3 : e3;
    if (!this._events[s3])
      return this;
    if (!t3)
      return --this._eventsCount === 0 ? this._events = new i3 : delete this._events[s3], this;
    var a3 = this._events[s3];
    if (a3.fn)
      a3.fn !== t3 || r4 && !a3.once || n3 && a3.context !== n3 || (--this._eventsCount === 0 ? this._events = new i3 : delete this._events[s3]);
    else {
      for (var c3 = 0, l2 = [], h = a3.length;c3 < h; c3++)
        (a3[c3].fn !== t3 || r4 && !a3[c3].once || n3 && a3[c3].context !== n3) && l2.push(a3[c3]);
      l2.length ? this._events[s3] = l2.length === 1 ? l2[0] : l2 : --this._eventsCount === 0 ? this._events = new i3 : delete this._events[s3];
    }
    return this;
  }, s2.prototype.removeAllListeners = function(e3) {
    var t3;
    return e3 ? (t3 = o3 ? o3 + e3 : e3, this._events[t3] && (--this._eventsCount === 0 ? this._events = new i3 : delete this._events[t3])) : (this._events = new i3, this._eventsCount = 0), this;
  }, s2.prototype.off = s2.prototype.removeListener, s2.prototype.addListener = s2.prototype.on, s2.prototype.setMaxListeners = function() {
    return this;
  }, s2.prefixed = o3, s2.EventEmitter = s2, t2 !== undefined && (t2.exports = s2);
} });
var l2 = a({ "node_modules/xml-lexer/dist/lexer.js"(e2, t2) {
  function n2(e3, t3, n3) {
    return t3 in e3 ? Object.defineProperty(e3, t3, { value: n3, enumerable: true, configurable: true, writable: true }) : e3[t3] = n3, e3;
  }
  var o3 = c2(), i3 = function() {}, r3 = { 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" }, s2 = { 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" }, l3 = { " ": s2.space, "\t": s2.space, "\n": s2.space, "\r": s2.space, "<": s2.lt, ">": s2.gt, '"': s2.quote, "'": s2.quote, "=": s2.equal, "/": s2.slash };
  t2.exports = { State: r3, Action: s2, Type: a3, create: function(e3) {
    var t3, c3, h, d, u, p2, m, g, f, _;
    e3 = Object.assign({ debug: false }, e3);
    var y = new o3, b = r3.data, x = "", v = "", I = "", S = "", C = "", P = "", M = function(t4, n3) {
      if (v[0] !== "?" && v[0] !== "!") {
        var o4 = { type: t4, value: n3 };
        e3.debug && console.log("emit:", o4), y.emit("data", o4);
      }
    };
    y.stateMachine = (n2(_ = {}, r3.data, (n2(t3 = {}, s2.lt, function() {
      x.trim() && M(a3.text, x), v = "", C = false, b = r3.tagBegin;
    }), n2(t3, s2.char, function(e4) {
      x += e4;
    }), t3)), n2(_, r3.cdata, n2({}, s2.char, function(e4) {
      (x += e4).substr(-3) === "]]>" && (M(a3.text, x.slice(0, -3)), x = "", b = r3.data);
    })), n2(_, r3.tagBegin, (n2(c3 = {}, s2.space, i3), n2(c3, s2.char, function(e4) {
      v = e4, b = r3.tagName;
    }), n2(c3, s2.slash, function() {
      v = "", C = true;
    }), c3)), n2(_, r3.tagName, (n2(h = {}, s2.space, function() {
      C ? b = r3.tagEnd : (b = r3.attributeNameStart, M(a3.openTag, v));
    }), n2(h, s2.gt, function() {
      M(C ? a3.closeTag : a3.openTag, v), x = "", b = r3.data;
    }), n2(h, s2.slash, function() {
      b = r3.tagEnd, M(a3.openTag, v);
    }), n2(h, s2.char, function(e4) {
      (v += e4) === "![CDATA[" && (b = r3.cdata, x = "", v = "");
    }), h)), n2(_, r3.tagEnd, (n2(d = {}, s2.gt, function() {
      M(a3.closeTag, v), x = "", b = r3.data;
    }), n2(d, s2.char, i3), d)), n2(_, r3.attributeNameStart, (n2(u = {}, s2.char, function(e4) {
      I = e4, b = r3.attributeName;
    }), n2(u, s2.gt, function() {
      x = "", b = r3.data;
    }), n2(u, s2.space, i3), n2(u, s2.slash, function() {
      C = true, b = r3.tagEnd;
    }), u)), n2(_, r3.attributeName, (n2(p2 = {}, s2.space, function() {
      b = r3.attributeNameEnd;
    }), n2(p2, s2.equal, function() {
      M(a3.attributeName, I), b = r3.attributeValueBegin;
    }), n2(p2, s2.gt, function() {
      S = "", M(a3.attributeName, I), M(a3.attributeValue, S), x = "", b = r3.data;
    }), n2(p2, s2.slash, function() {
      C = true, S = "", M(a3.attributeName, I), M(a3.attributeValue, S), b = r3.tagEnd;
    }), n2(p2, s2.char, function(e4) {
      I += e4;
    }), p2)), n2(_, r3.attributeNameEnd, (n2(m = {}, s2.space, i3), n2(m, s2.equal, function() {
      M(a3.attributeName, I), b = r3.attributeValueBegin;
    }), n2(m, s2.gt, function() {
      S = "", M(a3.attributeName, I), M(a3.attributeValue, S), x = "", b = r3.data;
    }), n2(m, s2.char, function(e4) {
      S = "", M(a3.attributeName, I), M(a3.attributeValue, S), I = e4, b = r3.attributeName;
    }), m)), n2(_, r3.attributeValueBegin, (n2(g = {}, s2.space, i3), n2(g, s2.quote, function(e4) {
      P = e4, S = "", b = r3.attributeValue;
    }), n2(g, s2.gt, function() {
      M(a3.attributeValue, S = ""), x = "", b = r3.data;
    }), n2(g, s2.char, function(e4) {
      P = "", S = e4, b = r3.attributeValue;
    }), g)), n2(_, r3.attributeValue, (n2(f = {}, s2.space, function(e4) {
      P ? S += e4 : (M(a3.attributeValue, S), b = r3.attributeNameStart);
    }), n2(f, s2.quote, function(e4) {
      P === e4 ? (M(a3.attributeValue, S), b = r3.attributeNameStart) : S += e4;
    }), n2(f, s2.gt, function(e4) {
      P ? S += e4 : (M(a3.attributeValue, S), x = "", b = r3.data);
    }), n2(f, s2.slash, function(e4) {
      P ? S += e4 : (M(a3.attributeValue, S), C = true, b = r3.tagEnd);
    }), n2(f, s2.char, function(e4) {
      S += e4;
    }), f)), _);
    var w = function(t4) {
      e3.debug && console.log(b, t4);
      var n3 = y.stateMachine[b], o4 = n3[function(e4) {
        return l3[e4] || s2.char;
      }(t4)] || n3[s2.error] || n3[s2.char];
      o4(t4);
    };
    return y.write = function(e4) {
      for (var t4 = e4.length, n3 = 0;n3 < t4; n3++)
        w(e4[n3]);
    }, y;
  } };
} });
var h = a({ "node_modules/xml-reader/dist/reader.js"(e2, t2) {
  var n2 = a2(), o3 = l2(), i3 = o3.Type, r3 = { element: "element", text: "text" }, s2 = function(e3) {
    return Object.assign({ name: "", type: r3.element, value: "", parent: null, attributes: {}, children: [] }, e3);
  }, c3 = function(e3) {
    e3 = Object.assign({ stream: false, parentNodes: true, doneEvent: "done", tagPrefix: "tag:", emitTopLevelOnly: false, debug: false }, e3);
    var t3 = undefined, a3 = undefined, c4 = undefined, l3 = undefined, h2 = new n2, d = function(n3) {
      switch (n3.type) {
        case i3.openTag:
          if (c4 === null)
            (c4 = a3).name = n3.value;
          else {
            var o4 = s2({ name: n3.value, parent: c4 });
            c4.children.push(o4), c4 = o4;
          }
          break;
        case i3.closeTag:
          var d2 = c4.parent;
          if (e3.parentNodes || (c4.parent = null), c4.name !== n3.value)
            break;
          e3.stream && d2 === a3 && (a3.children = [], c4.parent = null), e3.emitTopLevelOnly && d2 !== a3 || (h2.emit(e3.tagPrefix + c4.name, c4), h2.emit("tag", c4.name, c4)), c4 === a3 && (t3.removeAllListeners("data"), h2.emit(e3.doneEvent, c4), a3 = null), c4 = d2;
          break;
        case i3.text:
          c4 && c4.children.push(s2({ type: r3.text, value: n3.value, parent: e3.parentNodes ? c4 : null }));
          break;
        case i3.attributeName:
          l3 = n3.value, c4.attributes[l3] = "";
          break;
        case i3.attributeValue:
          c4.attributes[l3] = n3.value;
      }
    };
    return h2.reset = function() {
      (t3 = o3.create({ debug: e3.debug })).on("data", d), a3 = s2(), c4 = null, l3 = "", h2.parse = t3.write;
    }, h2.reset(), h2;
  };
  t2.exports = { parseSync: function(e3, t3) {
    t3 = Object.assign({}, t3, { stream: false, tagPrefix: ":" });
    var n3 = c3(t3), o4 = undefined;
    return n3.on("done", function(e4) {
      o4 = e4;
    }), n3.parse(e3), o4;
  }, create: c3, NodeType: r3 };
} });
var d = a({ "node_modules/binary-search-bounds/search-bounds.js"(e2, t2) {
  function n2(e3, t3, n3, o4, i4) {
    for (var r4 = i4 + 1;o4 <= i4; ) {
      var s3 = o4 + i4 >>> 1, a4 = e3[s3];
      (n3 !== undefined ? n3(a4, t3) : a4 - t3) >= 0 ? (r4 = s3, i4 = s3 - 1) : o4 = s3 + 1;
    }
    return r4;
  }
  function o3(e3, t3, n3, o4, i4) {
    for (var r4 = i4 + 1;o4 <= i4; ) {
      var s3 = o4 + i4 >>> 1, a4 = e3[s3];
      (n3 !== undefined ? n3(a4, t3) : a4 - t3) > 0 ? (r4 = s3, i4 = s3 - 1) : o4 = s3 + 1;
    }
    return r4;
  }
  function i3(e3, t3, n3, o4, i4) {
    for (var r4 = o4 - 1;o4 <= i4; ) {
      var s3 = o4 + i4 >>> 1, a4 = e3[s3];
      (n3 !== undefined ? n3(a4, t3) : a4 - t3) < 0 ? (r4 = s3, o4 = s3 + 1) : i4 = s3 - 1;
    }
    return r4;
  }
  function r3(e3, t3, n3, o4, i4) {
    for (var r4 = o4 - 1;o4 <= i4; ) {
      var s3 = o4 + i4 >>> 1, a4 = e3[s3];
      (n3 !== undefined ? n3(a4, t3) : a4 - t3) <= 0 ? (r4 = s3, o4 = s3 + 1) : i4 = s3 - 1;
    }
    return r4;
  }
  function s2(e3, t3, n3, o4, i4) {
    for (;o4 <= i4; ) {
      var r4 = o4 + i4 >>> 1, s3 = e3[r4], a4 = n3 !== undefined ? n3(s3, t3) : s3 - t3;
      if (a4 === 0)
        return r4;
      a4 <= 0 ? o4 = r4 + 1 : i4 = r4 - 1;
    }
    return -1;
  }
  function a3(e3, t3, n3, o4, i4, r4) {
    return typeof n3 == "function" ? r4(e3, t3, n3, o4 === undefined ? 0 : 0 | o4, i4 === undefined ? e3.length - 1 : 0 | i4) : r4(e3, t3, undefined, n3 === undefined ? 0 : 0 | n3, o4 === undefined ? e3.length - 1 : 0 | o4);
  }
  t2.exports = { ge: function(e3, t3, o4, i4, r4) {
    return a3(e3, t3, o4, i4, r4, n2);
  }, gt: function(e3, t3, n3, i4, r4) {
    return a3(e3, t3, n3, i4, r4, o3);
  }, lt: function(e3, t3, n3, o4, r4) {
    return a3(e3, t3, n3, o4, r4, i3);
  }, le: function(e3, t3, n3, o4, i4) {
    return a3(e3, t3, n3, o4, i4, r3);
  }, eq: function(e3, t3, n3, o4, i4) {
    return a3(e3, t3, n3, o4, i4, s2);
  } };
} });
var u = a({ "node_modules/two-product/two-product.js"(e2, t2) {
  t2.exports = function(e3, t3, o3) {
    var i3 = e3 * t3, r3 = n2 * e3, s2 = r3 - (r3 - e3), a3 = e3 - s2, c3 = n2 * t3, l3 = c3 - (c3 - t3), h2 = t3 - l3, d2 = a3 * h2 - (i3 - s2 * l3 - a3 * l3 - s2 * h2);
    if (o3)
      return o3[0] = d2, o3[1] = i3, o3;
    return [d2, i3];
  };
  var n2 = +(Math.pow(2, 27) + 1);
} });
var p2 = a({ "node_modules/robust-sum/robust-sum.js"(e2, t2) {
  t2.exports = function(e3, t3) {
    var n2 = 0 | e3.length, o3 = 0 | t3.length;
    if (n2 === 1 && o3 === 1)
      return function(e4, t4) {
        var n3 = e4 + t4, o4 = n3 - e4, i4 = n3 - o4, r4 = t4 - o4, s3 = e4 - i4, a4 = s3 + r4;
        if (a4)
          return [a4, n3];
        return [n3];
      }(e3[0], t3[0]);
    var i3, r3, s2 = new Array(n2 + o3), a3 = 0, c3 = 0, l3 = 0, h2 = Math.abs, d2 = e3[c3], u2 = h2(d2), p3 = t3[l3], m = h2(p3);
    u2 < m ? (r3 = d2, (c3 += 1) < n2 && (u2 = h2(d2 = e3[c3]))) : (r3 = p3, (l3 += 1) < o3 && (m = h2(p3 = t3[l3])));
    c3 < n2 && u2 < m || l3 >= o3 ? (i3 = d2, (c3 += 1) < n2 && (u2 = h2(d2 = e3[c3]))) : (i3 = p3, (l3 += 1) < o3 && (m = h2(p3 = t3[l3])));
    var g, f, _ = i3 + r3, y = _ - i3, b = r3 - y, x = b, v = _;
    for (;c3 < n2 && l3 < o3; )
      u2 < m ? (i3 = d2, (c3 += 1) < n2 && (u2 = h2(d2 = e3[c3]))) : (i3 = p3, (l3 += 1) < o3 && (m = h2(p3 = t3[l3]))), (b = (r3 = x) - (y = (_ = i3 + r3) - i3)) && (s2[a3++] = b), x = v - ((g = v + _) - (f = g - v)) + (_ - f), v = g;
    for (;c3 < n2; )
      (b = (r3 = x) - (y = (_ = (i3 = d2) + r3) - i3)) && (s2[a3++] = b), x = v - ((g = v + _) - (f = g - v)) + (_ - f), v = g, (c3 += 1) < n2 && (d2 = e3[c3]);
    for (;l3 < o3; )
      (b = (r3 = x) - (y = (_ = (i3 = p3) + r3) - i3)) && (s2[a3++] = b), x = v - ((g = v + _) - (f = g - v)) + (_ - f), v = g, (l3 += 1) < o3 && (p3 = t3[l3]);
    x && (s2[a3++] = x);
    v && (s2[a3++] = v);
    a3 || (s2[a3++] = 0);
    return s2.length = a3, s2;
  };
} });
var m = a({ "node_modules/two-sum/two-sum.js"(e2, t2) {
  t2.exports = function(e3, t3, n2) {
    var o3 = e3 + t3, i3 = o3 - e3, r3 = t3 - i3, s2 = e3 - (o3 - i3);
    if (n2)
      return n2[0] = s2 + r3, n2[1] = o3, n2;
    return [s2 + r3, o3];
  };
} });
var g = a({ "node_modules/robust-scale/robust-scale.js"(e2, t2) {
  var n2 = u(), o3 = m();
  t2.exports = function(e3, t3) {
    var i3 = e3.length;
    if (i3 === 1) {
      var r3 = n2(e3[0], t3);
      return r3[0] ? r3 : [r3[1]];
    }
    var s2 = new Array(2 * i3), a3 = [0.1, 0.1], c3 = [0.1, 0.1], l3 = 0;
    n2(e3[0], t3, a3), a3[0] && (s2[l3++] = a3[0]);
    for (var h2 = 1;h2 < i3; ++h2) {
      n2(e3[h2], t3, c3);
      var d2 = a3[1];
      o3(d2, c3[0], a3), a3[0] && (s2[l3++] = a3[0]);
      var u2 = c3[1], p3 = a3[1], m2 = u2 + p3, g2 = p3 - (m2 - u2);
      a3[1] = m2, g2 && (s2[l3++] = g2);
    }
    a3[1] && (s2[l3++] = a3[1]);
    l3 === 0 && (s2[l3++] = 0);
    return s2.length = l3, s2;
  };
} });
var f = a({ "node_modules/robust-subtract/robust-diff.js"(e2, t2) {
  t2.exports = function(e3, t3) {
    var n2 = 0 | e3.length, o3 = 0 | t3.length;
    if (n2 === 1 && o3 === 1)
      return function(e4, t4) {
        var n3 = e4 + t4, o4 = n3 - e4, i4 = n3 - o4, r4 = t4 - o4, s3 = e4 - i4, a4 = s3 + r4;
        if (a4)
          return [a4, n3];
        return [n3];
      }(e3[0], -t3[0]);
    var i3, r3, s2 = new Array(n2 + o3), a3 = 0, c3 = 0, l3 = 0, h2 = Math.abs, d2 = e3[c3], u2 = h2(d2), p3 = -t3[l3], m2 = h2(p3);
    u2 < m2 ? (r3 = d2, (c3 += 1) < n2 && (u2 = h2(d2 = e3[c3]))) : (r3 = p3, (l3 += 1) < o3 && (m2 = h2(p3 = -t3[l3])));
    c3 < n2 && u2 < m2 || l3 >= o3 ? (i3 = d2, (c3 += 1) < n2 && (u2 = h2(d2 = e3[c3]))) : (i3 = p3, (l3 += 1) < o3 && (m2 = h2(p3 = -t3[l3])));
    var g2, f2, _ = i3 + r3, y = _ - i3, b = r3 - y, x = b, v = _;
    for (;c3 < n2 && l3 < o3; )
      u2 < m2 ? (i3 = d2, (c3 += 1) < n2 && (u2 = h2(d2 = e3[c3]))) : (i3 = p3, (l3 += 1) < o3 && (m2 = h2(p3 = -t3[l3]))), (b = (r3 = x) - (y = (_ = i3 + r3) - i3)) && (s2[a3++] = b), x = v - ((g2 = v + _) - (f2 = g2 - v)) + (_ - f2), v = g2;
    for (;c3 < n2; )
      (b = (r3 = x) - (y = (_ = (i3 = d2) + r3) - i3)) && (s2[a3++] = b), x = v - ((g2 = v + _) - (f2 = g2 - v)) + (_ - f2), v = g2, (c3 += 1) < n2 && (d2 = e3[c3]);
    for (;l3 < o3; )
      (b = (r3 = x) - (y = (_ = (i3 = p3) + r3) - i3)) && (s2[a3++] = b), x = v - ((g2 = v + _) - (f2 = g2 - v)) + (_ - f2), v = g2, (l3 += 1) < o3 && (p3 = -t3[l3]);
    x && (s2[a3++] = x);
    v && (s2[a3++] = v);
    a3 || (s2[a3++] = 0);
    return s2.length = a3, s2;
  };
} });
var _ = a({ "node_modules/robust-orientation/orientation.js"(e2, t2) {
  var n2 = u(), o3 = p2(), i3 = g(), r3 = f();
  function s2(e3, t3, n3, o4) {
    return function(n4, i4, r4) {
      var s3 = e3(e3(t3(i4[1], r4[0]), t3(-r4[1], i4[0])), e3(t3(n4[1], i4[0]), t3(-i4[1], n4[0]))), a4 = e3(t3(n4[1], r4[0]), t3(-r4[1], n4[0])), c4 = o4(s3, a4);
      return c4[c4.length - 1];
    };
  }
  function a3(e3, t3, n3, o4) {
    return function(i4, r4, s3, a4) {
      var c4 = e3(e3(n3(e3(t3(s3[1], a4[0]), t3(-a4[1], s3[0])), r4[2]), e3(n3(e3(t3(r4[1], a4[0]), t3(-a4[1], r4[0])), -s3[2]), n3(e3(t3(r4[1], s3[0]), t3(-s3[1], r4[0])), a4[2]))), e3(n3(e3(t3(r4[1], a4[0]), t3(-a4[1], r4[0])), i4[2]), e3(n3(e3(t3(i4[1], a4[0]), t3(-a4[1], i4[0])), -r4[2]), n3(e3(t3(i4[1], r4[0]), t3(-r4[1], i4[0])), a4[2])))), l4 = e3(e3(n3(e3(t3(s3[1], a4[0]), t3(-a4[1], s3[0])), i4[2]), e3(n3(e3(t3(i4[1], a4[0]), t3(-a4[1], i4[0])), -s3[2]), n3(e3(t3(i4[1], s3[0]), t3(-s3[1], i4[0])), a4[2]))), e3(n3(e3(t3(r4[1], s3[0]), t3(-s3[1], r4[0])), i4[2]), e3(n3(e3(t3(i4[1], s3[0]), t3(-s3[1], i4[0])), -r4[2]), n3(e3(t3(i4[1], r4[0]), t3(-r4[1], i4[0])), s3[2])))), h3 = o4(c4, l4);
      return h3[h3.length - 1];
    };
  }
  function c3(e3, t3, n3, o4) {
    return function(i4, r4, s3, a4, c4) {
      var l4 = e3(e3(e3(n3(e3(n3(e3(t3(a4[1], c4[0]), t3(-c4[1], a4[0])), s3[2]), e3(n3(e3(t3(s3[1], c4[0]), t3(-c4[1], s3[0])), -a4[2]), n3(e3(t3(s3[1], a4[0]), t3(-a4[1], s3[0])), c4[2]))), r4[3]), e3(n3(e3(n3(e3(t3(a4[1], c4[0]), t3(-c4[1], a4[0])), r4[2]), e3(n3(e3(t3(r4[1], c4[0]), t3(-c4[1], r4[0])), -a4[2]), n3(e3(t3(r4[1], a4[0]), t3(-a4[1], r4[0])), c4[2]))), -s3[3]), n3(e3(n3(e3(t3(s3[1], c4[0]), t3(-c4[1], s3[0])), r4[2]), e3(n3(e3(t3(r4[1], c4[0]), t3(-c4[1], r4[0])), -s3[2]), n3(e3(t3(r4[1], s3[0]), t3(-s3[1], r4[0])), c4[2]))), a4[3]))), e3(n3(e3(n3(e3(t3(s3[1], a4[0]), t3(-a4[1], s3[0])), r4[2]), e3(n3(e3(t3(r4[1], a4[0]), t3(-a4[1], r4[0])), -s3[2]), n3(e3(t3(r4[1], s3[0]), t3(-s3[1], r4[0])), a4[2]))), -c4[3]), e3(n3(e3(n3(e3(t3(a4[1], c4[0]), t3(-c4[1], a4[0])), r4[2]), e3(n3(e3(t3(r4[1], c4[0]), t3(-c4[1], r4[0])), -a4[2]), n3(e3(t3(r4[1], a4[0]), t3(-a4[1], r4[0])), c4[2]))), i4[3]), n3(e3(n3(e3(t3(a4[1], c4[0]), t3(-c4[1], a4[0])), i4[2]), e3(n3(e3(t3(i4[1], c4[0]), t3(-c4[1], i4[0])), -a4[2]), n3(e3(t3(i4[1], a4[0]), t3(-a4[1], i4[0])), c4[2]))), -r4[3])))), e3(e3(n3(e3(n3(e3(t3(r4[1], c4[0]), t3(-c4[1], r4[0])), i4[2]), e3(n3(e3(t3(i4[1], c4[0]), t3(-c4[1], i4[0])), -r4[2]), n3(e3(t3(i4[1], r4[0]), t3(-r4[1], i4[0])), c4[2]))), a4[3]), e3(n3(e3(n3(e3(t3(r4[1], a4[0]), t3(-a4[1], r4[0])), i4[2]), e3(n3(e3(t3(i4[1], a4[0]), t3(-a4[1], i4[0])), -r4[2]), n3(e3(t3(i4[1], r4[0]), t3(-r4[1], i4[0])), a4[2]))), -c4[3]), n3(e3(n3(e3(t3(s3[1], a4[0]), t3(-a4[1], s3[0])), r4[2]), e3(n3(e3(t3(r4[1], a4[0]), t3(-a4[1], r4[0])), -s3[2]), n3(e3(t3(r4[1], s3[0]), t3(-s3[1], r4[0])), a4[2]))), i4[3]))), e3(n3(e3(n3(e3(t3(s3[1], a4[0]), t3(-a4[1], s3[0])), i4[2]), e3(n3(e3(t3(i4[1], a4[0]), t3(-a4[1], i4[0])), -s3[2]), n3(e3(t3(i4[1], s3[0]), t3(-s3[1], i4[0])), a4[2]))), -r4[3]), e3(n3(e3(n3(e3(t3(r4[1], a4[0]), t3(-a4[1], r4[0])), i4[2]), e3(n3(e3(t3(i4[1], a4[0]), t3(-a4[1], i4[0])), -r4[2]), n3(e3(t3(i4[1], r4[0]), t3(-r4[1], i4[0])), a4[2]))), s3[3]), n3(e3(n3(e3(t3(r4[1], s3[0]), t3(-s3[1], r4[0])), i4[2]), e3(n3(e3(t3(i4[1], s3[0]), t3(-s3[1], i4[0])), -r4[2]), n3(e3(t3(i4[1], r4[0]), t3(-r4[1], i4[0])), s3[2]))), -a4[3]))))), h3 = e3(e3(e3(n3(e3(n3(e3(t3(a4[1], c4[0]), t3(-c4[1], a4[0])), s3[2]), e3(n3(e3(t3(s3[1], c4[0]), t3(-c4[1], s3[0])), -a4[2]), n3(e3(t3(s3[1], a4[0]), t3(-a4[1], s3[0])), c4[2]))), i4[3]), n3(e3(n3(e3(t3(a4[1], c4[0]), t3(-c4[1], a4[0])), i4[2]), e3(n3(e3(t3(i4[1], c4[0]), t3(-c4[1], i4[0])), -a4[2]), n3(e3(t3(i4[1], a4[0]), t3(-a4[1], i4[0])), c4[2]))), -s3[3])), e3(n3(e3(n3(e3(t3(s3[1], c4[0]), t3(-c4[1], s3[0])), i4[2]), e3(n3(e3(t3(i4[1], c4[0]), t3(-c4[1], i4[0])), -s3[2]), n3(e3(t3(i4[1], s3[0]), t3(-s3[1], i4[0])), c4[2]))), a4[3]), n3(e3(n3(e3(t3(s3[1], a4[0]), t3(-a4[1], s3[0])), i4[2]), e3(n3(e3(t3(i4[1], a4[0]), t3(-a4[1], i4[0])), -s3[2]), n3(e3(t3(i4[1], s3[0]), t3(-s3[1], i4[0])), a4[2]))), -c4[3]))), e3(e3(n3(e3(n3(e3(t3(s3[1], c4[0]), t3(-c4[1], s3[0])), r4[2]), e3(n3(e3(t3(r4[1], c4[0]), t3(-c4[1], r4[0])), -s3[2]), n3(e3(t3(r4[1], s3[0]), t3(-s3[1], r4[0])), c4[2]))), i4[3]), n3(e3(n3(e3(t3(s3[1], c4[0]), t3(-c4[1], s3[0])), i4[2]), e3(n3(e3(t3(i4[1], c4[0]), t3(-c4[1], i4[0])), -s3[2]), n3(e3(t3(i4[1], s3[0]), t3(-s3[1], i4[0])), c4[2]))), -r4[3])), e3(n3(e3(n3(e3(t3(r4[1], c4[0]), t3(-c4[1], r4[0])), i4[2]), e3(n3(e3(t3(i4[1], c4[0]), t3(-c4[1], i4[0])), -r4[2]), n3(e3(t3(i4[1], r4[0]), t3(-r4[1], i4[0])), c4[2]))), s3[3]), n3(e3(n3(e3(t3(r4[1], s3[0]), t3(-s3[1], r4[0])), i4[2]), e3(n3(e3(t3(i4[1], s3[0]), t3(-s3[1], i4[0])), -r4[2]), n3(e3(t3(i4[1], r4[0]), t3(-r4[1], i4[0])), s3[2]))), -c4[3])))), d3 = o4(l4, h3);
      return d3[d3.length - 1];
    };
  }
  function l3(e3) {
    return (e3 === 3 ? s2 : e3 === 4 ? a3 : c3)(o3, n2, i3, r3);
  }
  var h2 = l3(3), d2 = l3(4), m2 = [function() {
    return 0;
  }, function() {
    return 0;
  }, function(e3, t3) {
    return t3[0] - e3[0];
  }, function(e3, t3, n3) {
    var o4, i4 = (e3[1] - n3[1]) * (t3[0] - n3[0]), r4 = (e3[0] - n3[0]) * (t3[1] - n3[1]), s3 = i4 - r4;
    if (i4 > 0) {
      if (r4 <= 0)
        return s3;
      o4 = i4 + r4;
    } else {
      if (!(i4 < 0))
        return s3;
      if (r4 >= 0)
        return s3;
      o4 = -(i4 + r4);
    }
    var a4 = 0.00000000000000033306690738754716 * o4;
    return s3 >= a4 || s3 <= -a4 ? s3 : h2(e3, t3, n3);
  }, function(e3, t3, n3, o4) {
    var i4 = e3[0] - o4[0], r4 = t3[0] - o4[0], s3 = n3[0] - o4[0], a4 = e3[1] - o4[1], c4 = t3[1] - o4[1], l4 = n3[1] - o4[1], h3 = e3[2] - o4[2], u2 = t3[2] - o4[2], p3 = n3[2] - o4[2], m3 = r4 * l4, g2 = s3 * c4, f2 = s3 * a4, _3 = i4 * l4, y2 = i4 * c4, b = r4 * a4, x = h3 * (m3 - g2) + u2 * (f2 - _3) + p3 * (y2 - b), v = 0.0000000000000007771561172376103 * ((Math.abs(m3) + Math.abs(g2)) * Math.abs(h3) + (Math.abs(f2) + Math.abs(_3)) * Math.abs(u2) + (Math.abs(y2) + Math.abs(b)) * Math.abs(p3));
    return x > v || -x > v ? x : d2(e3, t3, n3, o4);
  }];
  function _2(e3) {
    var t3 = m2[e3.length];
    return t3 || (t3 = m2[e3.length] = l3(e3.length)), t3.apply(undefined, e3);
  }
  function y(e3, t3, n3, o4, i4, r4, s3) {
    return function(t4, n4, a4, c4, l4) {
      switch (arguments.length) {
        case 0:
        case 1:
          return 0;
        case 2:
          return o4(t4, n4);
        case 3:
          return i4(t4, n4, a4);
        case 4:
          return r4(t4, n4, a4, c4);
        case 5:
          return s3(t4, n4, a4, c4, l4);
      }
      for (var h3 = new Array(arguments.length), d3 = 0;d3 < arguments.length; ++d3)
        h3[d3] = arguments[d3];
      return e3(h3);
    };
  }
  (function() {
    for (;m2.length <= 5; )
      m2.push(l3(m2.length));
    t2.exports = y.apply(undefined, [_2].concat(m2));
    for (var e3 = 0;e3 <= 5; ++e3)
      t2.exports[e3] = m2[e3];
  })();
} });
var y = a({ "node_modules/cdt2d/lib/monotone.js"(e2, t2) {
  var n2 = d(), o3 = _()[3];
  function i3(e3, t3, n3, o4, i4) {
    this.a = e3, this.b = t3, this.idx = n3, this.lowerIds = o4, this.upperIds = i4;
  }
  function r3(e3, t3, n3, o4) {
    this.a = e3, this.b = t3, this.type = n3, this.idx = o4;
  }
  function s2(e3, t3) {
    var n3 = e3.a[0] - t3.a[0] || e3.a[1] - t3.a[1] || e3.type - t3.type;
    return n3 || (e3.type !== 0 && (n3 = o3(e3.a, e3.b, t3.b)) ? n3 : e3.idx - t3.idx);
  }
  function a3(e3, t3) {
    return o3(e3.a, e3.b, t3);
  }
  function c3(e3, t3, i4, r4, s3) {
    for (var c4 = n2.lt(t3, r4, a3), l4 = n2.gt(t3, r4, a3), h3 = c4;h3 < l4; ++h3) {
      for (var d2 = t3[h3], u3 = d2.lowerIds, p3 = u3.length;p3 > 1 && o3(i4[u3[p3 - 2]], i4[u3[p3 - 1]], r4) > 0; )
        e3.push([u3[p3 - 1], u3[p3 - 2], s3]), p3 -= 1;
      u3.length = p3, u3.push(s3);
      var m2 = d2.upperIds;
      for (p3 = m2.length;p3 > 1 && o3(i4[m2[p3 - 2]], i4[m2[p3 - 1]], r4) < 0; )
        e3.push([m2[p3 - 2], m2[p3 - 1], s3]), p3 -= 1;
      m2.length = p3, m2.push(s3);
    }
  }
  function l3(e3, t3) {
    var n3;
    return (n3 = e3.a[0] < t3.a[0] ? o3(e3.a, e3.b, t3.a) : o3(t3.b, t3.a, e3.a)) ? n3 : (n3 = t3.b[0] < e3.b[0] ? o3(e3.a, e3.b, t3.b) : o3(t3.b, t3.a, e3.b)) || e3.idx - t3.idx;
  }
  function h2(e3, t3, o4) {
    var r4 = n2.le(e3, o4, l3), s3 = e3[r4], a4 = s3.upperIds, c4 = a4[a4.length - 1];
    s3.upperIds = [c4], e3.splice(r4 + 1, 0, new i3(o4.a, o4.b, o4.idx, [c4], a4));
  }
  function u2(e3, t3, o4) {
    var i4 = o4.a;
    o4.a = o4.b, o4.b = i4;
    var r4 = n2.eq(e3, o4, l3), s3 = e3[r4];
    e3[r4 - 1].upperIds = s3.upperIds, e3.splice(r4, 1);
  }
  t2.exports = function(e3, t3) {
    for (var n3 = e3.length, o4 = t3.length, a4 = [], l4 = 0;l4 < n3; ++l4)
      a4.push(new r3(e3[l4], null, 0, l4));
    for (l4 = 0;l4 < o4; ++l4) {
      var d2 = t3[l4], p3 = e3[d2[0]], m2 = e3[d2[1]];
      p3[0] < m2[0] ? a4.push(new r3(p3, m2, 2, l4), new r3(m2, p3, 1, l4)) : p3[0] > m2[0] && a4.push(new r3(m2, p3, 2, l4), new r3(p3, m2, 1, l4));
    }
    a4.sort(s2);
    for (var g2 = a4[0].a[0] - (1 + Math.abs(a4[0].a[0])) * Math.pow(2, -52), f2 = [new i3([g2, 1], [g2, 0], -1, [], [], [], [])], _2 = [], y2 = (l4 = 0, a4.length);l4 < y2; ++l4) {
      var b = a4[l4], x = b.type;
      x === 0 ? c3(_2, f2, e3, b.a, b.idx) : x === 2 ? h2(f2, e3, b) : u2(f2, e3, b);
    }
    return _2;
  };
} });
var b = a({ "node_modules/cdt2d/lib/triangulation.js"(e2, t2) {
  var n2 = d();
  function o3(e3, t3) {
    this.stars = e3, this.edges = t3;
  }
  t2.exports = function(e3, t3) {
    for (var n3 = new Array(e3), i4 = 0;i4 < e3; ++i4)
      n3[i4] = [];
    return new o3(n3, t3);
  };
  var i3 = o3.prototype;
  function r3(e3, t3, n3) {
    for (var o4 = 1, i4 = e3.length;o4 < i4; o4 += 2)
      if (e3[o4 - 1] === t3 && e3[o4] === n3)
        return e3[o4 - 1] = e3[i4 - 2], e3[o4] = e3[i4 - 1], void (e3.length = i4 - 2);
  }
  i3.isConstraint = function() {
    var e3 = [0, 0];
    function t3(e4, t4) {
      return e4[0] - t4[0] || e4[1] - t4[1];
    }
    return function(o4, i4) {
      return e3[0] = Math.min(o4, i4), e3[1] = Math.max(o4, i4), n2.eq(this.edges, e3, t3) >= 0;
    };
  }(), i3.removeTriangle = function(e3, t3, n3) {
    var o4 = this.stars;
    r3(o4[e3], t3, n3), r3(o4[t3], n3, e3), r3(o4[n3], e3, t3);
  }, i3.addTriangle = function(e3, t3, n3) {
    var o4 = this.stars;
    o4[e3].push(t3, n3), o4[t3].push(n3, e3), o4[n3].push(e3, t3);
  }, i3.opposite = function(e3, t3) {
    for (var n3 = this.stars[t3], o4 = 1, i4 = n3.length;o4 < i4; o4 += 2)
      if (n3[o4] === e3)
        return n3[o4 - 1];
    return -1;
  }, i3.flip = function(e3, t3) {
    var n3 = this.opposite(e3, t3), o4 = this.opposite(t3, e3);
    this.removeTriangle(e3, t3, n3), this.removeTriangle(t3, e3, o4), this.addTriangle(e3, o4, n3), this.addTriangle(t3, n3, o4);
  }, i3.edges = function() {
    for (var e3 = this.stars, t3 = [], n3 = 0, o4 = e3.length;n3 < o4; ++n3)
      for (var i4 = e3[n3], r4 = 0, s2 = i4.length;r4 < s2; r4 += 2)
        t3.push([i4[r4], i4[r4 + 1]]);
    return t3;
  }, i3.cells = function() {
    for (var e3 = this.stars, t3 = [], n3 = 0, o4 = e3.length;n3 < o4; ++n3)
      for (var i4 = e3[n3], r4 = 0, s2 = i4.length;r4 < s2; r4 += 2) {
        var a3 = i4[r4], c3 = i4[r4 + 1];
        n3 < Math.min(a3, c3) && t3.push([n3, a3, c3]);
      }
    return t3;
  };
} });
var x = a({ "node_modules/robust-in-sphere/in-sphere.js"(e2, t2) {
  var n2 = u(), o3 = p2(), i3 = f(), r3 = g();
  function s2(e3) {
    return (e3 === 3 ? a3 : e3 === 4 ? c3 : e3 === 5 ? l3 : h2)(o3, i3, n2, r3);
  }
  function a3(e3, t3, n3, o4) {
    return function(i4, r4, s3) {
      var a4 = n3(i4[0], i4[0]), c4 = o4(a4, r4[0]), l4 = o4(a4, s3[0]), h3 = n3(r4[0], r4[0]), d3 = o4(h3, i4[0]), u2 = o4(h3, s3[0]), p3 = n3(s3[0], s3[0]), m3 = o4(p3, i4[0]), g2 = o4(p3, r4[0]), f2 = e3(t3(g2, u2), t3(d3, c4)), _3 = t3(m3, l4), y2 = t3(f2, _3);
      return y2[y2.length - 1];
    };
  }
  function c3(e3, t3, n3, o4) {
    return function(i4, r4, s3, a4) {
      var c4 = e3(n3(i4[0], i4[0]), n3(i4[1], i4[1])), l4 = o4(c4, r4[0]), h3 = o4(c4, s3[0]), d3 = o4(c4, a4[0]), u2 = e3(n3(r4[0], r4[0]), n3(r4[1], r4[1])), p3 = o4(u2, i4[0]), m3 = o4(u2, s3[0]), g2 = o4(u2, a4[0]), f2 = e3(n3(s3[0], s3[0]), n3(s3[1], s3[1])), _3 = o4(f2, i4[0]), y2 = o4(f2, r4[0]), b2 = o4(f2, a4[0]), x2 = e3(n3(a4[0], a4[0]), n3(a4[1], a4[1])), v = o4(x2, i4[0]), I = o4(x2, r4[0]), S = o4(x2, s3[0]), C = e3(e3(o4(t3(S, b2), r4[1]), e3(o4(t3(I, g2), -s3[1]), o4(t3(y2, m3), a4[1]))), e3(o4(t3(I, g2), i4[1]), e3(o4(t3(v, d3), -r4[1]), o4(t3(p3, l4), a4[1])))), P = e3(e3(o4(t3(S, b2), i4[1]), e3(o4(t3(v, d3), -s3[1]), o4(t3(_3, h3), a4[1]))), e3(o4(t3(y2, m3), i4[1]), e3(o4(t3(_3, h3), -r4[1]), o4(t3(p3, l4), s3[1])))), M = t3(C, P);
      return M[M.length - 1];
    };
  }
  function l3(e3, t3, n3, o4) {
    return function(i4, r4, s3, a4, c4) {
      var l4 = e3(n3(i4[0], i4[0]), e3(n3(i4[1], i4[1]), n3(i4[2], i4[2]))), h3 = o4(l4, r4[0]), d3 = o4(l4, s3[0]), u2 = o4(l4, a4[0]), p3 = o4(l4, c4[0]), m3 = e3(n3(r4[0], r4[0]), e3(n3(r4[1], r4[1]), n3(r4[2], r4[2]))), g2 = o4(m3, i4[0]), f2 = o4(m3, s3[0]), _3 = o4(m3, a4[0]), y2 = o4(m3, c4[0]), b2 = e3(n3(s3[0], s3[0]), e3(n3(s3[1], s3[1]), n3(s3[2], s3[2]))), x2 = o4(b2, i4[0]), v = o4(b2, r4[0]), I = o4(b2, a4[0]), S = o4(b2, c4[0]), C = e3(n3(a4[0], a4[0]), e3(n3(a4[1], a4[1]), n3(a4[2], a4[2]))), P = o4(C, i4[0]), M = o4(C, r4[0]), w = o4(C, s3[0]), N = o4(C, c4[0]), R = e3(n3(c4[0], c4[0]), e3(n3(c4[1], c4[1]), n3(c4[2], c4[2]))), T = o4(R, i4[0]), E2 = o4(R, r4[0]), A = o4(R, s3[0]), O = o4(R, a4[0]), k = e3(e3(e3(o4(e3(o4(t3(O, N), s3[1]), e3(o4(t3(A, S), -a4[1]), o4(t3(w, I), c4[1]))), r4[2]), e3(o4(e3(o4(t3(O, N), r4[1]), e3(o4(t3(E2, y2), -a4[1]), o4(t3(M, _3), c4[1]))), -s3[2]), o4(e3(o4(t3(A, S), r4[1]), e3(o4(t3(E2, y2), -s3[1]), o4(t3(v, f2), c4[1]))), a4[2]))), e3(o4(e3(o4(t3(w, I), r4[1]), e3(o4(t3(M, _3), -s3[1]), o4(t3(v, f2), a4[1]))), -c4[2]), e3(o4(e3(o4(t3(O, N), r4[1]), e3(o4(t3(E2, y2), -a4[1]), o4(t3(M, _3), c4[1]))), i4[2]), o4(e3(o4(t3(O, N), i4[1]), e3(o4(t3(T, p3), -a4[1]), o4(t3(P, u2), c4[1]))), -r4[2])))), e3(e3(o4(e3(o4(t3(E2, y2), i4[1]), e3(o4(t3(T, p3), -r4[1]), o4(t3(g2, h3), c4[1]))), a4[2]), e3(o4(e3(o4(t3(M, _3), i4[1]), e3(o4(t3(P, u2), -r4[1]), o4(t3(g2, h3), a4[1]))), -c4[2]), o4(e3(o4(t3(w, I), r4[1]), e3(o4(t3(M, _3), -s3[1]), o4(t3(v, f2), a4[1]))), i4[2]))), e3(o4(e3(o4(t3(w, I), i4[1]), e3(o4(t3(P, u2), -s3[1]), o4(t3(x2, d3), a4[1]))), -r4[2]), e3(o4(e3(o4(t3(M, _3), i4[1]), e3(o4(t3(P, u2), -r4[1]), o4(t3(g2, h3), a4[1]))), s3[2]), o4(e3(o4(t3(v, f2), i4[1]), e3(o4(t3(x2, d3), -r4[1]), o4(t3(g2, h3), s3[1]))), -a4[2]))))), D = e3(e3(e3(o4(e3(o4(t3(O, N), s3[1]), e3(o4(t3(A, S), -a4[1]), o4(t3(w, I), c4[1]))), i4[2]), o4(e3(o4(t3(O, N), i4[1]), e3(o4(t3(T, p3), -a4[1]), o4(t3(P, u2), c4[1]))), -s3[2])), e3(o4(e3(o4(t3(A, S), i4[1]), e3(o4(t3(T, p3), -s3[1]), o4(t3(x2, d3), c4[1]))), a4[2]), o4(e3(o4(t3(w, I), i4[1]), e3(o4(t3(P, u2), -s3[1]), o4(t3(x2, d3), a4[1]))), -c4[2]))), e3(e3(o4(e3(o4(t3(A, S), r4[1]), e3(o4(t3(E2, y2), -s3[1]), o4(t3(v, f2), c4[1]))), i4[2]), o4(e3(o4(t3(A, S), i4[1]), e3(o4(t3(T, p3), -s3[1]), o4(t3(x2, d3), c4[1]))), -r4[2])), e3(o4(e3(o4(t3(E2, y2), i4[1]), e3(o4(t3(T, p3), -r4[1]), o4(t3(g2, h3), c4[1]))), s3[2]), o4(e3(o4(t3(v, f2), i4[1]), e3(o4(t3(x2, d3), -r4[1]), o4(t3(g2, h3), s3[1]))), -c4[2])))), L = t3(k, D);
      return L[L.length - 1];
    };
  }
  function h2(e3, t3, n3, o4) {
    return function(i4, r4, s3, a4, c4, l4) {
      var h3 = e3(e3(n3(i4[0], i4[0]), n3(i4[1], i4[1])), e3(n3(i4[2], i4[2]), n3(i4[3], i4[3]))), d3 = o4(h3, r4[0]), u2 = o4(h3, s3[0]), p3 = o4(h3, a4[0]), m3 = o4(h3, c4[0]), g2 = o4(h3, l4[0]), f2 = e3(e3(n3(r4[0], r4[0]), n3(r4[1], r4[1])), e3(n3(r4[2], r4[2]), n3(r4[3], r4[3]))), _3 = o4(f2, i4[0]), y2 = o4(f2, s3[0]), b2 = o4(f2, a4[0]), x2 = o4(f2, c4[0]), v = o4(f2, l4[0]), I = e3(e3(n3(s3[0], s3[0]), n3(s3[1], s3[1])), e3(n3(s3[2], s3[2]), n3(s3[3], s3[3]))), S = o4(I, i4[0]), C = o4(I, r4[0]), P = o4(I, a4[0]), M = o4(I, c4[0]), w = o4(I, l4[0]), N = e3(e3(n3(a4[0], a4[0]), n3(a4[1], a4[1])), e3(n3(a4[2], a4[2]), n3(a4[3], a4[3]))), R = o4(N, i4[0]), T = o4(N, r4[0]), E2 = o4(N, s3[0]), A = o4(N, c4[0]), O = o4(N, l4[0]), k = e3(e3(n3(c4[0], c4[0]), n3(c4[1], c4[1])), e3(n3(c4[2], c4[2]), n3(c4[3], c4[3]))), D = o4(k, i4[0]), L = o4(k, r4[0]), z = o4(k, s3[0]), B = o4(k, a4[0]), F = o4(k, l4[0]), j = e3(e3(n3(l4[0], l4[0]), n3(l4[1], l4[1])), e3(n3(l4[2], l4[2]), n3(l4[3], l4[3]))), $ = o4(j, i4[0]), Y = o4(j, r4[0]), X = o4(j, s3[0]), H = o4(j, a4[0]), V = o4(j, c4[0]), W = e3(e3(e3(o4(e3(e3(o4(e3(o4(t3(V, F), a4[1]), e3(o4(t3(H, O), -c4[1]), o4(t3(B, A), l4[1]))), s3[2]), o4(e3(o4(t3(V, F), s3[1]), e3(o4(t3(X, w), -c4[1]), o4(t3(z, M), l4[1]))), -a4[2])), e3(o4(e3(o4(t3(H, O), s3[1]), e3(o4(t3(X, w), -a4[1]), o4(t3(E2, P), l4[1]))), c4[2]), o4(e3(o4(t3(B, A), s3[1]), e3(o4(t3(z, M), -a4[1]), o4(t3(E2, P), c4[1]))), -l4[2]))), r4[3]), e3(o4(e3(e3(o4(e3(o4(t3(V, F), a4[1]), e3(o4(t3(H, O), -c4[1]), o4(t3(B, A), l4[1]))), r4[2]), o4(e3(o4(t3(V, F), r4[1]), e3(o4(t3(Y, v), -c4[1]), o4(t3(L, x2), l4[1]))), -a4[2])), e3(o4(e3(o4(t3(H, O), r4[1]), e3(o4(t3(Y, v), -a4[1]), o4(t3(T, b2), l4[1]))), c4[2]), o4(e3(o4(t3(B, A), r4[1]), e3(o4(t3(L, x2), -a4[1]), o4(t3(T, b2), c4[1]))), -l4[2]))), -s3[3]), o4(e3(e3(o4(e3(o4(t3(V, F), s3[1]), e3(o4(t3(X, w), -c4[1]), o4(t3(z, M), l4[1]))), r4[2]), o4(e3(o4(t3(V, F), r4[1]), e3(o4(t3(Y, v), -c4[1]), o4(t3(L, x2), l4[1]))), -s3[2])), e3(o4(e3(o4(t3(X, w), r4[1]), e3(o4(t3(Y, v), -s3[1]), o4(t3(C, y2), l4[1]))), c4[2]), o4(e3(o4(t3(z, M), r4[1]), e3(o4(t3(L, x2), -s3[1]), o4(t3(C, y2), c4[1]))), -l4[2]))), a4[3]))), e3(e3(o4(e3(e3(o4(e3(o4(t3(H, O), s3[1]), e3(o4(t3(X, w), -a4[1]), o4(t3(E2, P), l4[1]))), r4[2]), o4(e3(o4(t3(H, O), r4[1]), e3(o4(t3(Y, v), -a4[1]), o4(t3(T, b2), l4[1]))), -s3[2])), e3(o4(e3(o4(t3(X, w), r4[1]), e3(o4(t3(Y, v), -s3[1]), o4(t3(C, y2), l4[1]))), a4[2]), o4(e3(o4(t3(E2, P), r4[1]), e3(o4(t3(T, b2), -s3[1]), o4(t3(C, y2), a4[1]))), -l4[2]))), -c4[3]), o4(e3(e3(o4(e3(o4(t3(B, A), s3[1]), e3(o4(t3(z, M), -a4[1]), o4(t3(E2, P), c4[1]))), r4[2]), o4(e3(o4(t3(B, A), r4[1]), e3(o4(t3(L, x2), -a4[1]), o4(t3(T, b2), c4[1]))), -s3[2])), e3(o4(e3(o4(t3(z, M), r4[1]), e3(o4(t3(L, x2), -s3[1]), o4(t3(C, y2), c4[1]))), a4[2]), o4(e3(o4(t3(E2, P), r4[1]), e3(o4(t3(T, b2), -s3[1]), o4(t3(C, y2), a4[1]))), -c4[2]))), l4[3])), e3(o4(e3(e3(o4(e3(o4(t3(V, F), a4[1]), e3(o4(t3(H, O), -c4[1]), o4(t3(B, A), l4[1]))), r4[2]), o4(e3(o4(t3(V, F), r4[1]), e3(o4(t3(Y, v), -c4[1]), o4(t3(L, x2), l4[1]))), -a4[2])), e3(o4(e3(o4(t3(H, O), r4[1]), e3(o4(t3(Y, v), -a4[1]), o4(t3(T, b2), l4[1]))), c4[2]), o4(e3(o4(t3(B, A), r4[1]), e3(o4(t3(L, x2), -a4[1]), o4(t3(T, b2), c4[1]))), -l4[2]))), i4[3]), o4(e3(e3(o4(e3(o4(t3(V, F), a4[1]), e3(o4(t3(H, O), -c4[1]), o4(t3(B, A), l4[1]))), i4[2]), o4(e3(o4(t3(V, F), i4[1]), e3(o4(t3($, g2), -c4[1]), o4(t3(D, m3), l4[1]))), -a4[2])), e3(o4(e3(o4(t3(H, O), i4[1]), e3(o4(t3($, g2), -a4[1]), o4(t3(R, p3), l4[1]))), c4[2]), o4(e3(o4(t3(B, A), i4[1]), e3(o4(t3(D, m3), -a4[1]), o4(t3(R, p3), c4[1]))), -l4[2]))), -r4[3])))), e3(e3(e3(o4(e3(e3(o4(e3(o4(t3(V, F), r4[1]), e3(o4(t3(Y, v), -c4[1]), o4(t3(L, x2), l4[1]))), i4[2]), o4(e3(o4(t3(V, F), i4[1]), e3(o4(t3($, g2), -c4[1]), o4(t3(D, m3), l4[1]))), -r4[2])), e3(o4(e3(o4(t3(Y, v), i4[1]), e3(o4(t3($, g2), -r4[1]), o4(t3(_3, d3), l4[1]))), c4[2]), o4(e3(o4(t3(L, x2), i4[1]), e3(o4(t3(D, m3), -r4[1]), o4(t3(_3, d3), c4[1]))), -l4[2]))), a4[3]), o4(e3(e3(o4(e3(o4(t3(H, O), r4[1]), e3(o4(t3(Y, v), -a4[1]), o4(t3(T, b2), l4[1]))), i4[2]), o4(e3(o4(t3(H, O), i4[1]), e3(o4(t3($, g2), -a4[1]), o4(t3(R, p3), l4[1]))), -r4[2])), e3(o4(e3(o4(t3(Y, v), i4[1]), e3(o4(t3($, g2), -r4[1]), o4(t3(_3, d3), l4[1]))), a4[2]), o4(e3(o4(t3(T, b2), i4[1]), e3(o4(t3(R, p3), -r4[1]), o4(t3(_3, d3), a4[1]))), -l4[2]))), -c4[3])), e3(o4(e3(e3(o4(e3(o4(t3(B, A), r4[1]), e3(o4(t3(L, x2), -a4[1]), o4(t3(T, b2), c4[1]))), i4[2]), o4(e3(o4(t3(B, A), i4[1]), e3(o4(t3(D, m3), -a4[1]), o4(t3(R, p3), c4[1]))), -r4[2])), e3(o4(e3(o4(t3(L, x2), i4[1]), e3(o4(t3(D, m3), -r4[1]), o4(t3(_3, d3), c4[1]))), a4[2]), o4(e3(o4(t3(T, b2), i4[1]), e3(o4(t3(R, p3), -r4[1]), o4(t3(_3, d3), a4[1]))), -c4[2]))), l4[3]), o4(e3(e3(o4(e3(o4(t3(H, O), s3[1]), e3(o4(t3(X, w), -a4[1]), o4(t3(E2, P), l4[1]))), r4[2]), o4(e3(o4(t3(H, O), r4[1]), e3(o4(t3(Y, v), -a4[1]), o4(t3(T, b2), l4[1]))), -s3[2])), e3(o4(e3(o4(t3(X, w), r4[1]), e3(o4(t3(Y, v), -s3[1]), o4(t3(C, y2), l4[1]))), a4[2]), o4(e3(o4(t3(E2, P), r4[1]), e3(o4(t3(T, b2), -s3[1]), o4(t3(C, y2), a4[1]))), -l4[2]))), i4[3]))), e3(e3(o4(e3(e3(o4(e3(o4(t3(H, O), s3[1]), e3(o4(t3(X, w), -a4[1]), o4(t3(E2, P), l4[1]))), i4[2]), o4(e3(o4(t3(H, O), i4[1]), e3(o4(t3($, g2), -a4[1]), o4(t3(R, p3), l4[1]))), -s3[2])), e3(o4(e3(o4(t3(X, w), i4[1]), e3(o4(t3($, g2), -s3[1]), o4(t3(S, u2), l4[1]))), a4[2]), o4(e3(o4(t3(E2, P), i4[1]), e3(o4(t3(R, p3), -s3[1]), o4(t3(S, u2), a4[1]))), -l4[2]))), -r4[3]), o4(e3(e3(o4(e3(o4(t3(H, O), r4[1]), e3(o4(t3(Y, v), -a4[1]), o4(t3(T, b2), l4[1]))), i4[2]), o4(e3(o4(t3(H, O), i4[1]), e3(o4(t3($, g2), -a4[1]), o4(t3(R, p3), l4[1]))), -r4[2])), e3(o4(e3(o4(t3(Y, v), i4[1]), e3(o4(t3($, g2), -r4[1]), o4(t3(_3, d3), l4[1]))), a4[2]), o4(e3(o4(t3(T, b2), i4[1]), e3(o4(t3(R, p3), -r4[1]), o4(t3(_3, d3), a4[1]))), -l4[2]))), s3[3])), e3(o4(e3(e3(o4(e3(o4(t3(X, w), r4[1]), e3(o4(t3(Y, v), -s3[1]), o4(t3(C, y2), l4[1]))), i4[2]), o4(e3(o4(t3(X, w), i4[1]), e3(o4(t3($, g2), -s3[1]), o4(t3(S, u2), l4[1]))), -r4[2])), e3(o4(e3(o4(t3(Y, v), i4[1]), e3(o4(t3($, g2), -r4[1]), o4(t3(_3, d3), l4[1]))), s3[2]), o4(e3(o4(t3(C, y2), i4[1]), e3(o4(t3(S, u2), -r4[1]), o4(t3(_3, d3), s3[1]))), -l4[2]))), -a4[3]), o4(e3(e3(o4(e3(o4(t3(E2, P), r4[1]), e3(o4(t3(T, b2), -s3[1]), o4(t3(C, y2), a4[1]))), i4[2]), o4(e3(o4(t3(E2, P), i4[1]), e3(o4(t3(R, p3), -s3[1]), o4(t3(S, u2), a4[1]))), -r4[2])), e3(o4(e3(o4(t3(T, b2), i4[1]), e3(o4(t3(R, p3), -r4[1]), o4(t3(_3, d3), a4[1]))), s3[2]), o4(e3(o4(t3(C, y2), i4[1]), e3(o4(t3(S, u2), -r4[1]), o4(t3(_3, d3), s3[1]))), -a4[2]))), l4[3]))))), G = e3(e3(e3(o4(e3(e3(o4(e3(o4(t3(V, F), a4[1]), e3(o4(t3(H, O), -c4[1]), o4(t3(B, A), l4[1]))), s3[2]), o4(e3(o4(t3(V, F), s3[1]), e3(o4(t3(X, w), -c4[1]), o4(t3(z, M), l4[1]))), -a4[2])), e3(o4(e3(o4(t3(H, O), s3[1]), e3(o4(t3(X, w), -a4[1]), o4(t3(E2, P), l4[1]))), c4[2]), o4(e3(o4(t3(B, A), s3[1]), e3(o4(t3(z, M), -a4[1]), o4(t3(E2, P), c4[1]))), -l4[2]))), i4[3]), e3(o4(e3(e3(o4(e3(o4(t3(V, F), a4[1]), e3(o4(t3(H, O), -c4[1]), o4(t3(B, A), l4[1]))), i4[2]), o4(e3(o4(t3(V, F), i4[1]), e3(o4(t3($, g2), -c4[1]), o4(t3(D, m3), l4[1]))), -a4[2])), e3(o4(e3(o4(t3(H, O), i4[1]), e3(o4(t3($, g2), -a4[1]), o4(t3(R, p3), l4[1]))), c4[2]), o4(e3(o4(t3(B, A), i4[1]), e3(o4(t3(D, m3), -a4[1]), o4(t3(R, p3), c4[1]))), -l4[2]))), -s3[3]), o4(e3(e3(o4(e3(o4(t3(V, F), s3[1]), e3(o4(t3(X, w), -c4[1]), o4(t3(z, M), l4[1]))), i4[2]), o4(e3(o4(t3(V, F), i4[1]), e3(o4(t3($, g2), -c4[1]), o4(t3(D, m3), l4[1]))), -s3[2])), e3(o4(e3(o4(t3(X, w), i4[1]), e3(o4(t3($, g2), -s3[1]), o4(t3(S, u2), l4[1]))), c4[2]), o4(e3(o4(t3(z, M), i4[1]), e3(o4(t3(D, m3), -s3[1]), o4(t3(S, u2), c4[1]))), -l4[2]))), a4[3]))), e3(e3(o4(e3(e3(o4(e3(o4(t3(H, O), s3[1]), e3(o4(t3(X, w), -a4[1]), o4(t3(E2, P), l4[1]))), i4[2]), o4(e3(o4(t3(H, O), i4[1]), e3(o4(t3($, g2), -a4[1]), o4(t3(R, p3), l4[1]))), -s3[2])), e3(o4(e3(o4(t3(X, w), i4[1]), e3(o4(t3($, g2), -s3[1]), o4(t3(S, u2), l4[1]))), a4[2]), o4(e3(o4(t3(E2, P), i4[1]), e3(o4(t3(R, p3), -s3[1]), o4(t3(S, u2), a4[1]))), -l4[2]))), -c4[3]), o4(e3(e3(o4(e3(o4(t3(B, A), s3[1]), e3(o4(t3(z, M), -a4[1]), o4(t3(E2, P), c4[1]))), i4[2]), o4(e3(o4(t3(B, A), i4[1]), e3(o4(t3(D, m3), -a4[1]), o4(t3(R, p3), c4[1]))), -s3[2])), e3(o4(e3(o4(t3(z, M), i4[1]), e3(o4(t3(D, m3), -s3[1]), o4(t3(S, u2), c4[1]))), a4[2]), o4(e3(o4(t3(E2, P), i4[1]), e3(o4(t3(R, p3), -s3[1]), o4(t3(S, u2), a4[1]))), -c4[2]))), l4[3])), e3(o4(e3(e3(o4(e3(o4(t3(V, F), s3[1]), e3(o4(t3(X, w), -c4[1]), o4(t3(z, M), l4[1]))), r4[2]), o4(e3(o4(t3(V, F), r4[1]), e3(o4(t3(Y, v), -c4[1]), o4(t3(L, x2), l4[1]))), -s3[2])), e3(o4(e3(o4(t3(X, w), r4[1]), e3(o4(t3(Y, v), -s3[1]), o4(t3(C, y2), l4[1]))), c4[2]), o4(e3(o4(t3(z, M), r4[1]), e3(o4(t3(L, x2), -s3[1]), o4(t3(C, y2), c4[1]))), -l4[2]))), i4[3]), o4(e3(e3(o4(e3(o4(t3(V, F), s3[1]), e3(o4(t3(X, w), -c4[1]), o4(t3(z, M), l4[1]))), i4[2]), o4(e3(o4(t3(V, F), i4[1]), e3(o4(t3($, g2), -c4[1]), o4(t3(D, m3), l4[1]))), -s3[2])), e3(o4(e3(o4(t3(X, w), i4[1]), e3(o4(t3($, g2), -s3[1]), o4(t3(S, u2), l4[1]))), c4[2]), o4(e3(o4(t3(z, M), i4[1]), e3(o4(t3(D, m3), -s3[1]), o4(t3(S, u2), c4[1]))), -l4[2]))), -r4[3])))), e3(e3(e3(o4(e3(e3(o4(e3(o4(t3(V, F), r4[1]), e3(o4(t3(Y, v), -c4[1]), o4(t3(L, x2), l4[1]))), i4[2]), o4(e3(o4(t3(V, F), i4[1]), e3(o4(t3($, g2), -c4[1]), o4(t3(D, m3), l4[1]))), -r4[2])), e3(o4(e3(o4(t3(Y, v), i4[1]), e3(o4(t3($, g2), -r4[1]), o4(t3(_3, d3), l4[1]))), c4[2]), o4(e3(o4(t3(L, x2), i4[1]), e3(o4(t3(D, m3), -r4[1]), o4(t3(_3, d3), c4[1]))), -l4[2]))), s3[3]), o4(e3(e3(o4(e3(o4(t3(X, w), r4[1]), e3(o4(t3(Y, v), -s3[1]), o4(t3(C, y2), l4[1]))), i4[2]), o4(e3(o4(t3(X, w), i4[1]), e3(o4(t3($, g2), -s3[1]), o4(t3(S, u2), l4[1]))), -r4[2])), e3(o4(e3(o4(t3(Y, v), i4[1]), e3(o4(t3($, g2), -r4[1]), o4(t3(_3, d3), l4[1]))), s3[2]), o4(e3(o4(t3(C, y2), i4[1]), e3(o4(t3(S, u2), -r4[1]), o4(t3(_3, d3), s3[1]))), -l4[2]))), -c4[3])), e3(o4(e3(e3(o4(e3(o4(t3(z, M), r4[1]), e3(o4(t3(L, x2), -s3[1]), o4(t3(C, y2), c4[1]))), i4[2]), o4(e3(o4(t3(z, M), i4[1]), e3(o4(t3(D, m3), -s3[1]), o4(t3(S, u2), c4[1]))), -r4[2])), e3(o4(e3(o4(t3(L, x2), i4[1]), e3(o4(t3(D, m3), -r4[1]), o4(t3(_3, d3), c4[1]))), s3[2]), o4(e3(o4(t3(C, y2), i4[1]), e3(o4(t3(S, u2), -r4[1]), o4(t3(_3, d3), s3[1]))), -c4[2]))), l4[3]), o4(e3(e3(o4(e3(o4(t3(B, A), s3[1]), e3(o4(t3(z, M), -a4[1]), o4(t3(E2, P), c4[1]))), r4[2]), o4(e3(o4(t3(B, A), r4[1]), e3(o4(t3(L, x2), -a4[1]), o4(t3(T, b2), c4[1]))), -s3[2])), e3(o4(e3(o4(t3(z, M), r4[1]), e3(o4(t3(L, x2), -s3[1]), o4(t3(C, y2), c4[1]))), a4[2]), o4(e3(o4(t3(E2, P), r4[1]), e3(o4(t3(T, b2), -s3[1]), o4(t3(C, y2), a4[1]))), -c4[2]))), i4[3]))), e3(e3(o4(e3(e3(o4(e3(o4(t3(B, A), s3[1]), e3(o4(t3(z, M), -a4[1]), o4(t3(E2, P), c4[1]))), i4[2]), o4(e3(o4(t3(B, A), i4[1]), e3(o4(t3(D, m3), -a4[1]), o4(t3(R, p3), c4[1]))), -s3[2])), e3(o4(e3(o4(t3(z, M), i4[1]), e3(o4(t3(D, m3), -s3[1]), o4(t3(S, u2), c4[1]))), a4[2]), o4(e3(o4(t3(E2, P), i4[1]), e3(o4(t3(R, p3), -s3[1]), o4(t3(S, u2), a4[1]))), -c4[2]))), -r4[3]), o4(e3(e3(o4(e3(o4(t3(B, A), r4[1]), e3(o4(t3(L, x2), -a4[1]), o4(t3(T, b2), c4[1]))), i4[2]), o4(e3(o4(t3(B, A), i4[1]), e3(o4(t3(D, m3), -a4[1]), o4(t3(R, p3), c4[1]))), -r4[2])), e3(o4(e3(o4(t3(L, x2), i4[1]), e3(o4(t3(D, m3), -r4[1]), o4(t3(_3, d3), c4[1]))), a4[2]), o4(e3(o4(t3(T, b2), i4[1]), e3(o4(t3(R, p3), -r4[1]), o4(t3(_3, d3), a4[1]))), -c4[2]))), s3[3])), e3(o4(e3(e3(o4(e3(o4(t3(z, M), r4[1]), e3(o4(t3(L, x2), -s3[1]), o4(t3(C, y2), c4[1]))), i4[2]), o4(e3(o4(t3(z, M), i4[1]), e3(o4(t3(D, m3), -s3[1]), o4(t3(S, u2), c4[1]))), -r4[2])), e3(o4(e3(o4(t3(L, x2), i4[1]), e3(o4(t3(D, m3), -r4[1]), o4(t3(_3, d3), c4[1]))), s3[2]), o4(e3(o4(t3(C, y2), i4[1]), e3(o4(t3(S, u2), -r4[1]), o4(t3(_3, d3), s3[1]))), -c4[2]))), -a4[3]), o4(e3(e3(o4(e3(o4(t3(E2, P), r4[1]), e3(o4(t3(T, b2), -s3[1]), o4(t3(C, y2), a4[1]))), i4[2]), o4(e3(o4(t3(E2, P), i4[1]), e3(o4(t3(R, p3), -s3[1]), o4(t3(S, u2), a4[1]))), -r4[2])), e3(o4(e3(o4(t3(T, b2), i4[1]), e3(o4(t3(R, p3), -r4[1]), o4(t3(_3, d3), a4[1]))), s3[2]), o4(e3(o4(t3(C, y2), i4[1]), e3(o4(t3(S, u2), -r4[1]), o4(t3(_3, d3), s3[1]))), -a4[2]))), c4[3]))))), U = t3(W, G);
      return U[U.length - 1];
    };
  }
  var d2 = [function() {
    return 0;
  }, function() {
    return 0;
  }, function() {
    return 0;
  }];
  function m2(e3) {
    var t3 = d2[e3.length];
    return t3 || (t3 = d2[e3.length] = s2(e3.length)), t3.apply(undefined, e3);
  }
  function _2(e3, t3, n3, o4, i4, r4, s3, a4) {
    return function(t4, n4, c4, l4, h3, d3) {
      switch (arguments.length) {
        case 0:
        case 1:
          return 0;
        case 2:
          return o4(t4, n4);
        case 3:
          return i4(t4, n4, c4);
        case 4:
          return r4(t4, n4, c4, l4);
        case 5:
          return s3(t4, n4, c4, l4, h3);
        case 6:
          return a4(t4, n4, c4, l4, h3, d3);
      }
      for (var u2 = new Array(arguments.length), p3 = 0;p3 < arguments.length; ++p3)
        u2[p3] = arguments[p3];
      return e3(u2);
    };
  }
  (function() {
    for (;d2.length <= 6; )
      d2.push(s2(d2.length));
    t2.exports = _2.apply(undefined, [m2].concat(d2));
    for (var e3 = 0;e3 <= 6; ++e3)
      t2.exports[e3] = d2[e3];
  })();
} });
var v = a({ "node_modules/cdt2d/lib/delaunay.js"(e2, t2) {
  var n2 = x()[4];
  d();
  function o3(e3, t3, o4, i3, r3, s2) {
    var a3 = t3.opposite(i3, r3);
    if (!(a3 < 0)) {
      if (r3 < i3) {
        var c3 = i3;
        i3 = r3, r3 = c3, c3 = s2, s2 = a3, a3 = c3;
      }
      t3.isConstraint(i3, r3) || n2(e3[i3], e3[r3], e3[s2], e3[a3]) < 0 && o4.push(i3, r3);
    }
  }
  t2.exports = function(e3, t3) {
    for (var i3 = [], r3 = e3.length, s2 = t3.stars, a3 = 0;a3 < r3; ++a3)
      for (var c3 = s2[a3], l3 = 1;l3 < c3.length; l3 += 2) {
        if (!((p3 = c3[l3]) < a3) && !t3.isConstraint(a3, p3)) {
          for (var h2 = c3[l3 - 1], d2 = -1, u2 = 1;u2 < c3.length; u2 += 2)
            if (c3[u2 - 1] === p3) {
              d2 = c3[u2];
              break;
            }
          d2 < 0 || n2(e3[a3], e3[p3], e3[h2], e3[d2]) < 0 && i3.push(a3, p3);
        }
      }
    for (;i3.length > 0; ) {
      for (var p3 = i3.pop(), m2 = (h2 = -1, d2 = -1, c3 = s2[a3 = i3.pop()], 1);m2 < c3.length; m2 += 2) {
        var g2 = c3[m2 - 1], f2 = c3[m2];
        g2 === p3 ? d2 = f2 : f2 === p3 && (h2 = g2);
      }
      h2 < 0 || d2 < 0 || (n2(e3[a3], e3[p3], e3[h2], e3[d2]) >= 0 || (t3.flip(a3, p3), o3(e3, t3, i3, h2, a3, d2), o3(e3, t3, i3, a3, d2, h2), o3(e3, t3, i3, d2, p3, h2), o3(e3, t3, i3, p3, h2, d2)));
    }
  };
} });
var I = a({ "node_modules/cdt2d/lib/filter.js"(e2, t2) {
  var n2 = d();
  function o3(e3, t3, n3, o4, i4, r3, s2) {
    this.cells = e3, this.neighbor = t3, this.flags = o4, this.constraint = n3, this.active = i4, this.next = r3, this.boundary = s2;
  }
  function i3(e3, t3) {
    return e3[0] - t3[0] || e3[1] - t3[1] || e3[2] - t3[2];
  }
  t2.exports = function(e3, t3, n3) {
    var r3 = function(e4, t4) {
      for (var n4 = e4.cells(), r4 = n4.length, s3 = 0;s3 < r4; ++s3) {
        var a4 = (_3 = n4[s3])[0], c4 = _3[1], l4 = _3[2];
        c4 < l4 ? c4 < a4 && (_3[0] = c4, _3[1] = l4, _3[2] = a4) : l4 < a4 && (_3[0] = l4, _3[1] = a4, _3[2] = c4);
      }
      n4.sort(i3);
      var h3 = new Array(r4);
      for (s3 = 0;s3 < h3.length; ++s3)
        h3[s3] = 0;
      var d3 = [], u3 = [], p4 = new Array(3 * r4), m3 = new Array(3 * r4), g3 = null;
      t4 && (g3 = []);
      var f3 = new o3(n4, p4, m3, h3, d3, u3, g3);
      for (s3 = 0;s3 < r4; ++s3)
        for (var _3 = n4[s3], y2 = 0;y2 < 3; ++y2) {
          a4 = _3[y2], c4 = _3[(y2 + 1) % 3];
          var b2 = p4[3 * s3 + y2] = f3.locate(c4, a4, e4.opposite(c4, a4)), x2 = m3[3 * s3 + y2] = e4.isConstraint(a4, c4);
          b2 < 0 && (x2 ? u3.push(s3) : (d3.push(s3), h3[s3] = 1), t4 && g3.push([c4, a4, -1]));
        }
      return f3;
    }(e3, n3);
    if (t3 === 0)
      return n3 ? r3.cells.concat(r3.boundary) : r3.cells;
    var s2 = 1, a3 = r3.active, c3 = r3.next, l3 = r3.flags, h2 = r3.cells, d2 = r3.constraint, u2 = r3.neighbor;
    for (;a3.length > 0 || c3.length > 0; ) {
      for (;a3.length > 0; ) {
        var p3 = a3.pop();
        if (l3[p3] !== -s2) {
          l3[p3] = s2;
          h2[p3];
          for (var m2 = 0;m2 < 3; ++m2) {
            var g2 = u2[3 * p3 + m2];
            g2 >= 0 && l3[g2] === 0 && (d2[3 * p3 + m2] ? c3.push(g2) : (a3.push(g2), l3[g2] = s2));
          }
        }
      }
      var f2 = c3;
      c3 = a3, a3 = f2, c3.length = 0, s2 = -s2;
    }
    var _2 = function(e4, t4, n4) {
      for (var o4 = 0, i4 = 0;i4 < e4.length; ++i4)
        t4[i4] === n4 && (e4[o4++] = e4[i4]);
      return e4.length = o4, e4;
    }(h2, l3, t3);
    if (n3)
      return _2.concat(r3.boundary);
    return _2;
  }, o3.prototype.locate = function() {
    var e3 = [0, 0, 0];
    return function(t3, o4, r3) {
      var s2 = t3, a3 = o4, c3 = r3;
      return o4 < r3 ? o4 < t3 && (s2 = o4, a3 = r3, c3 = t3) : r3 < t3 && (s2 = r3, a3 = t3, c3 = o4), s2 < 0 ? -1 : (e3[0] = s2, e3[1] = a3, e3[2] = c3, n2.eq(this.cells, e3, i3));
    };
  }();
} });
var S = a({ "node_modules/cdt2d/cdt2d.js"(e2, t2) {
  var n2 = y(), o3 = b(), i3 = v(), r3 = I();
  function s2(e3) {
    return [Math.min(e3[0], e3[1]), Math.max(e3[0], e3[1])];
  }
  function a3(e3, t3) {
    return e3[0] - t3[0] || e3[1] - t3[1];
  }
  function c3(e3, t3, n3) {
    return t3 in e3 ? e3[t3] : n3;
  }
  t2.exports = function(e3, t3, l3) {
    Array.isArray(t3) ? (l3 = l3 || {}, t3 = t3 || []) : (l3 = t3 || {}, t3 = []);
    var h2 = !!c3(l3, "delaunay", true), d2 = !!c3(l3, "interior", true), u2 = !!c3(l3, "exterior", true), p3 = !!c3(l3, "infinity", false);
    if (!d2 && !u2 || e3.length === 0)
      return [];
    var m2 = n2(e3, t3);
    if (h2 || d2 !== u2 || p3) {
      for (var g2 = o3(e3.length, function(e4) {
        return e4.map(s2).sort(a3);
      }(t3)), f2 = 0;f2 < m2.length; ++f2) {
        var _2 = m2[f2];
        g2.addTriangle(_2[0], _2[1], _2[2]);
      }
      return h2 && i3(e3, g2), u2 ? d2 ? p3 ? r3(g2, 0, p3) : g2.cells() : r3(g2, 1, p3) : r3(g2, -1);
    }
    return m2;
  };
} });
var R = class {
  constructor(e2 = 1 / 0, t2 = Float64Array, n2 = Uint32Array) {
    const o3 = e2 !== 1 / 0;
    this.ids = o3 ? new n2(e2) : [], this.values = o3 ? new t2(e2) : [], this.capacity = e2, this.length = 0;
  }
  clear() {
    this.length = 0;
  }
  push(e2, t2) {
    if (this.length === this.capacity)
      throw new RangeError("Queue is at capacity.");
    let n2 = this.length++;
    for (;n2 > 0; ) {
      const e3 = n2 - 1 >> 1, o3 = this.values[e3];
      if (t2 >= o3)
        break;
      this.ids[n2] = this.ids[e3], this.values[n2] = o3, n2 = e3;
    }
    this.ids[n2] = e2, this.values[n2] = t2;
  }
  pop() {
    if (this.length === 0)
      return;
    const e2 = this.ids, t2 = this.values, n2 = e2[0], o3 = --this.length;
    if (o3 > 0) {
      const n3 = e2[o3], i3 = t2[o3];
      let r3 = 0;
      const s2 = o3 >> 1;
      for (;r3 < s2; ) {
        const n4 = 1 + (r3 << 1), s3 = n4 + 1, a3 = n4 + (+(s3 < o3) & +(t2[s3] < t2[n4]));
        if (t2[a3] >= i3)
          break;
        e2[r3] = e2[a3], t2[r3] = t2[a3], r3 = a3;
      }
      e2[r3] = n3, t2[r3] = i3;
    }
    return n2;
  }
  peek() {
    return this.length > 0 ? this.ids[0] : undefined;
  }
  peekValue() {
    return this.length > 0 ? this.values[0] : undefined;
  }
  shrink() {
    Array.isArray(this.ids) && (this.ids.length = this.length), Array.isArray(this.values) && (this.values.length = this.length);
  }
};
var T = [Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array];
var E2 = class e2 {
  static from(t2, n2 = 0) {
    if (n2 % 8 != 0)
      throw new Error("byteOffset must be 8-byte aligned.");
    if (!t2 || t2.byteLength === undefined || "buffer" in t2)
      throw new Error("Data must be an instance of ArrayBuffer or SharedArrayBuffer.");
    const [o3, i3] = new Uint8Array(t2, n2 + 0, 2);
    if (o3 !== 251)
      throw new Error("Data does not appear to be in a Flatbush format.");
    const r3 = i3 >> 4;
    if (r3 !== 3)
      throw new Error(`Got v${r3} data when expected v3.`);
    const s2 = T[15 & i3];
    if (!s2)
      throw new Error("Unrecognized array type.");
    const [a3] = new Uint16Array(t2, n2 + 2, 1), [c3] = new Uint32Array(t2, n2 + 4, 1);
    return new e2(c3, a3, s2, undefined, t2, n2);
  }
  constructor(e3, t2 = 16, n2 = Float64Array, o3 = ArrayBuffer, i3, r3 = 0) {
    if (e3 === undefined)
      throw new Error("Missing required argument: numItems.");
    if (isNaN(e3) || e3 <= 0)
      throw new Error(`Unexpected numItems value: ${e3}.`);
    this.numItems = +e3, this.nodeSize = Math.min(Math.max(+t2, 2), 65535), this.byteOffset = r3;
    let s2 = e3, a3 = s2;
    this._levelBounds = [4 * s2];
    do {
      s2 = Math.ceil(s2 / this.nodeSize), a3 += s2, this._levelBounds.push(4 * a3);
    } while (s2 !== 1);
    this.ArrayType = n2, this.IndexArrayType = a3 < 16384 ? Uint16Array : Uint32Array;
    const c3 = T.indexOf(n2), l3 = 4 * a3 * n2.BYTES_PER_ELEMENT;
    if (c3 < 0)
      throw new Error(`Unexpected typed array class: ${n2}.`);
    const h2 = n2, d2 = this.IndexArrayType;
    if (i3)
      this.data = i3, this._boxes = new h2(i3, r3 + 8, 4 * a3), this._indices = new d2(i3, r3 + 8 + l3, a3), this._pos = 4 * a3, 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 {
      const t3 = this.data = new o3(8 + l3 + a3 * this.IndexArrayType.BYTES_PER_ELEMENT);
      this._boxes = new h2(t3, 8, 4 * a3), this._indices = new d2(t3, 8 + l3, a3), this._pos = 0, this.minX = 1 / 0, this.minY = 1 / 0, this.maxX = -1 / 0, this.maxY = -1 / 0, new Uint8Array(t3, 0, 2).set([251, 48 + c3]), new Uint16Array(t3, 2, 1)[0] = this.nodeSize, new Uint32Array(t3, 4, 1)[0] = e3;
    }
    this._queue = new R;
  }
  add(e3, t2, n2 = e3, o3 = t2) {
    const i3 = this._pos, r3 = i3 >> 2, s2 = this._boxes;
    return this._indices[r3] = r3, s2[i3] = e3, s2[i3 + 1] = t2, s2[i3 + 2] = n2, s2[i3 + 3] = o3, this._pos = i3 + 4, e3 < this.minX && (this.minX = e3), t2 < this.minY && (this.minY = t2), n2 > this.maxX && (this.maxX = n2), o3 > this.maxY && (this.maxY = o3), r3;
  }
  finish() {
    if (this._pos >> 2 !== this.numItems)
      throw new Error(`Added ${this._pos >> 2} items when expected ${this.numItems}.`);
    const e3 = this._boxes;
    if (this.numItems <= this.nodeSize)
      return e3[this._pos++] = this.minX, e3[this._pos++] = this.minY, e3[this._pos++] = this.maxX, void (e3[this._pos++] = this.maxY);
    const { numItems: t2, minX: n2, minY: o3, nodeSize: i3, _indices: r3, _levelBounds: s2 } = this, a3 = this.maxX - n2 || 1, c3 = this.maxY - o3 || 1, l3 = new Int32Array(t2), h2 = 65535 / a3, d2 = 65535 / c3;
    for (let i4 = 0, r4 = 0;i4 < t2; i4++) {
      const t3 = e3[r4++], s3 = e3[r4++], a4 = h2 * ((t3 + e3[r4++]) / 2 - n2) | 0, c4 = d2 * ((s3 + e3[r4++]) / 2 - o3) | 0;
      l3[i4] = k(a4, c4);
    }
    (function(e4, t3, n3, o4, i4, r4) {
      const s3 = [o4, i4];
      for (;s3.length; ) {
        const o5 = s3.pop() || 0, i5 = s3.pop() || 0;
        if (o5 - i5 <= r4 && Math.floor(i5 / r4) >= Math.floor(o5 / r4))
          continue;
        const a4 = e4[i5], c4 = e4[i5 + o5 >> 1], l4 = e4[o5], h3 = a4 > c4 != a4 > l4 ? a4 : c4 < a4 != c4 < l4 ? c4 : l4;
        let d3 = i5 - 1, u3 = o5 + 1;
        for (;; ) {
          do {
            d3++;
          } while (e4[d3] < h3);
          do {
            u3--;
          } while (e4[u3] > h3);
          if (d3 >= u3)
            break;
          O(e4, t3, n3, d3, u3);
        }
        s3.push(i5, u3, u3 + 1, o5);
      }
    })(l3, e3, r3, 0, t2 - 1, i3);
    let u2 = 4 * t2;
    for (let t3 = 0, n3 = 0;t3 < s2.length - 1; t3++) {
      const o4 = s2[t3];
      for (;n3 < o4; ) {
        const t4 = n3;
        let s3 = e3[n3++], a4 = e3[n3++], c4 = e3[n3++], l4 = e3[n3++];
        for (let t5 = 1;t5 < i3 && n3 < o4; t5++)
          s3 = Math.min(s3, e3[n3++]), a4 = Math.min(a4, e3[n3++]), c4 = Math.max(c4, e3[n3++]), l4 = Math.max(l4, e3[n3++]);
        r3[u2 >> 2] = t4, e3[u2++] = s3, e3[u2++] = a4, e3[u2++] = c4, e3[u2++] = l4;
      }
    }
    this._pos = u2;
  }
  search(e3, t2, n2, o3, i3) {
    if (this._pos !== this._boxes.length)
      throw new Error("Data not yet indexed - call index.finish().");
    const { _boxes: r3, _levelBounds: s2, _indices: a3, nodeSize: c3 } = this, l3 = 4 * this.numItems;
    let h2 = r3.length - 4, d2 = s2.length - 1;
    const u2 = [], p3 = [];
    let m2 = false;
    for (;h2 !== undefined; ) {
      const g2 = Math.min(h2 + 4 * c3, s2[d2]), f2 = h2 >= l3;
      if (m2)
        this._collectContained(h2, g2, d2, l3, p3, i3);
      else
        for (let s3 = h2;s3 < g2; s3 += 4) {
          const c4 = r3[s3];
          if (n2 < c4)
            continue;
          const l4 = r3[s3 + 1];
          if (o3 < l4)
            continue;
          const h3 = r3[s3 + 2];
          if (e3 > h3)
            continue;
          const m3 = r3[s3 + 3];
          if (t2 > m3)
            continue;
          const g3 = 0 | a3[s3 >> 2];
          if (f2) {
            const i4 = +(e3 <= c4 && t2 <= l4 && n2 >= h3 && o3 >= m3);
            u2.push(g3 | i4, d2 - 1);
          } else
            (i3 === undefined || i3(g3, c4, l4, h3, m3)) && p3.push(g3);
        }
      d2 = u2.pop(), h2 = u2.pop(), h2 !== undefined && (m2 = !(1 & ~h2), h2 &= -2);
    }
    return p3;
  }
  _collectContained(e3, t2, n2, o3, i3, r3) {
    const s2 = this._boxes, a3 = this._indices;
    let c3 = e3;
    for (let e4 = n2;e4 > 0; e4--)
      c3 = a3[c3 >> 2];
    const l3 = Math.min(c3 + (t2 - e3) * this.nodeSize ** n2, o3);
    if (r3 === undefined)
      for (;c3 < l3; c3 += 4)
        i3.push(0 | a3[c3 >> 2]);
    else
      for (;c3 < l3; c3 += 4) {
        const e4 = 0 | a3[c3 >> 2];
        r3(e4, s2[c3], s2[c3 + 1], s2[c3 + 2], s2[c3 + 3]) && i3.push(e4);
      }
  }
  collides(e3, t2, n2, o3, i3) {
    if (this._pos !== this._boxes.length)
      throw new Error("Data not yet indexed - call index.finish().");
    const { _boxes: r3, _levelBounds: s2, _indices: a3, nodeSize: c3 } = this, l3 = 4 * this.numItems;
    let h2 = r3.length - 4, d2 = s2.length - 1;
    const u2 = [];
    for (;h2 !== undefined; ) {
      const p3 = Math.min(h2 + 4 * c3, s2[d2]), m2 = h2 >= l3;
      for (let s3 = h2;s3 < p3; s3 += 4) {
        const c4 = r3[s3];
        if (n2 < c4)
          continue;
        const l4 = r3[s3 + 1];
        if (o3 < l4)
          continue;
        const h3 = r3[s3 + 2];
        if (e3 > h3)
          continue;
        const p4 = r3[s3 + 3];
        if (t2 > p4)
          continue;
        const g2 = 0 | a3[s3 >> 2];
        if (m2)
          u2.push(g2, d2 - 1);
        else if (i3 === undefined || i3(g2, c4, l4, h3, p4))
          return true;
      }
      d2 = u2.pop(), h2 = u2.pop();
    }
    return false;
  }
  neighbors(e3, t2, n2 = 1 / 0, o3 = 1 / 0, i3) {
    if (this._pos !== this._boxes.length)
      throw new Error("Data not yet indexed - call index.finish().");
    const { _boxes: r3, _levelBounds: s2, _indices: a3, _queue: c3, nodeSize: l3 } = this, h2 = 4 * this.numItems, d2 = 4 * l3, u2 = [], p3 = n2 === 1;
    let m2 = o3 * o3;
    for (c3.push(r3.length - 4 << 1, 0);c3.length; ) {
      const o4 = c3.ids[0];
      if (1 & o4) {
        if (c3.pop(), u2.push(o4 >> 1), u2.length === n2)
          break;
        continue;
      }
      c3.pop();
      const l4 = o4 >> 1, g2 = l4 < h2, f2 = Math.min(l4 + d2, A(l4, s2));
      for (let n3 = l4;n3 < f2; n3 += 4) {
        const o5 = r3[n3], s3 = r3[n3 + 1], l5 = r3[n3 + 2], h3 = r3[n3 + 3], d3 = Math.max(Math.max(o5 - e3, e3 - l5), 0), u3 = Math.max(Math.max(s3 - t2, t2 - h3), 0), f3 = d3 * d3 + u3 * u3;
        if (f3 > m2)
          continue;
        const _2 = 0 | a3[n3 >> 2];
        g2 ? (i3 === undefined || i3(_2)) && (c3.push(_2 << 1 | 1, f3), p3 && f3 < m2 && (m2 = f3)) : c3.push(_2 << 1, f3);
      }
    }
    return c3.clear(), u2;
  }
};
function A(e3, t2) {
  let n2 = 0, o3 = t2.length - 1;
  for (;n2 < o3; ) {
    const i3 = n2 + o3 >> 1;
    t2[i3] > e3 ? o3 = i3 : n2 = i3 + 1;
  }
  return t2[n2];
}
function O(e3, t2, n2, o3, i3) {
  const r3 = e3[o3];
  e3[o3] = e3[i3], e3[i3] = r3;
  const s2 = 4 * o3, a3 = 4 * i3, c3 = t2[s2], l3 = t2[s2 + 1], h2 = t2[s2 + 2], d2 = t2[s2 + 3];
  t2[s2] = t2[a3], t2[s2 + 1] = t2[a3 + 1], t2[s2 + 2] = t2[a3 + 2], t2[s2 + 3] = t2[a3 + 3], t2[a3] = c3, t2[a3 + 1] = l3, t2[a3 + 2] = h2, t2[a3 + 3] = d2;
  const u2 = n2[o3];
  n2[o3] = n2[i3], n2[i3] = u2;
}
function k(e3, t2) {
  let n2 = e3 ^ t2, o3 = 65535 ^ n2, i3 = 65535 ^ (e3 | t2), r3 = e3 & (65535 ^ t2), s2 = n2 | o3 >> 1, a3 = n2 >> 1 ^ n2, c3 = i3 ^ i3 >> 1 ^ o3 & r3 >> 1, l3 = r3 ^ n2 & i3 >> 1 ^ r3 >> 1;
  return n2 = s2 & s2 >> 2 ^ a3 & a3 >> 2, o3 = s2 & a3 >> 2 ^ a3 & (s2 ^ a3) >> 2, i3 = c3 ^ s2 & c3 >> 2 ^ a3 & l3 >> 2, r3 = l3 ^ a3 & c3 >> 2 ^ (s2 ^ a3) & l3 >> 2, s2 = n2 & n2 >> 4 ^ o3 & o3 >> 4, a3 = n2 & o3 >> 4 ^ o3 & (n2 ^ o3) >> 4, c3 = i3 ^ n2 & i3 >> 4 ^ o3 & r3 >> 4, l3 = r3 ^ o3 & i3 >> 4 ^ (n2 ^ o3) & r3 >> 4, i3 = c3 ^ s2 & c3 >> 8 ^ a3 & l3 >> 8, r3 = l3 ^ a3 & c3 >> 8 ^ (s2 ^ a3) & l3 >> 8, i3 ^= i3 >> 1, r3 ^= r3 >> 1, n2 = e3 ^ t2, o3 = r3 | 65535 ^ (n2 | i3), n2 = 16711935 & (n2 | n2 << 8), n2 = 252645135 & (n2 | n2 << 4), n2 = 858993459 & (n2 | n2 << 2), n2 = 1431655765 & (n2 | n2 << 1), o3 = 16711935 & (o3 | o3 << 8), o3 = 252645135 & (o3 | o3 << 4), o3 = 858993459 & (o3 | o3 << 2), o3 = 1431655765 & (o3 | o3 << 1), ((o3 << 1 | n2) >>> 0) - 2147483648;
}
var D = 0.0001;
var L = [{ facingDirection: "x-", dx: -1, dy: 0, startX: -0.5, startY: 0.5, endX: -0.5, endY: -0.5 }, { facingDirection: "x+", dx: 1, dy: 0, startX: 0.5, startY: 0.5, endX: 0.5, endY: -0.5 }, { facingDirection: "y-", dx: 0, dy: -1, startX: -0.5, startY: -0.5, endX: 0.5, endY: -0.5 }, { facingDirection: "y+", dx: 0, dy: 1, startX: 0.5, startY: 0.5, endX: -0.5, endY: 0.5 }];
var z = { "x-": L.find((e3) => e3.facingDirection === "x-"), "x+": L.find((e3) => e3.facingDirection === "x+"), "y-": L.find((e3) => e3.facingDirection === "y-"), "y+": L.find((e3) => e3.facingDirection === "y+") };
var B = { "x-": { x: -1, y: 0 }, "x+": { x: 1, y: 0 }, "y-": { x: 0, y: -1 }, "y+": { x: 0, y: 1 } };
var F = (e3, t2) => {
  const { dir: n2, amt: o3 } = t2, i3 = B[n2];
  return e3.map((e4) => ({ x: e4.x + i3.x * o3, y: e4.y + i3.y * o3 }));
};
var j = 0.0001;
function $(e3) {
  const t2 = [];
  for (const n2 of e3)
    for (const e4 of L) {
      let o3 = { x: n2.center.x + n2.width * e4.startX, y: n2.center.y + n2.height * e4.startY }, i3 = { x: n2.center.x + n2.width * e4.endX, y: n2.center.y + n2.height * e4.endY };
      o3.x > i3.x && ([o3, i3] = [i3, o3]), Math.abs(o3.x - i3.x) < j && o3.y > i3.y && ([o3, i3] = [i3, o3]);
      for (const r3 of n2.availableZ)
        t2.push({ parent: n2, start: o3, end: i3, facingDirection: e4.facingDirection, z: r3 });
    }
  return t2;
}
var Y = class extends BaseSolver {
  constructor(e3) {
    super(), this.input = e3;
    const t2 = this.input.targetMeshNodes ?? this.input.allMeshNodes, n2 = new Set(t2.map((e4) => e4.capacityMeshNodeId)), o3 = this.input.allMeshNodes.filter((e4) => !n2.has(e4.capacityMeshNodeId));
    this.unprocessedEdges = $(t2), this.allEdges = [...this.unprocessedEdges, ...$(o3)], this.edgeSpatialIndex = new E2(this.allEdges.length);
    for (const e4 of this.allEdges)
      this.edgeSpatialIndex.add(e4.start.x, e4.start.y, e4.end.x, e4.end.y);
    this.edgeSpatialIndex.finish();
  }
  allEdges;
  unprocessedEdges = [];
  segmentsWithAdjacentEmptySpace = [];
  edgeSpatialIndex;
  lastCandidateEdge = null;
  lastOverlappingEdges = null;
  lastUncoveredSegments = null;
  _step() {
    if (this.unprocessedEdges.length === 0)
      return this.solved = true, this.lastCandidateEdge = null, this.lastOverlappingEdges = null, void (this.lastUncoveredSegments = null);
    const e3 = this.unprocessedEdges.shift();
    this.lastCandidateEdge = e3;
    const t2 = this.edgeSpatialIndex.search(e3.start.x - j, e3.start.y - j, e3.end.x + j, e3.end.y + j).map((e4) => this.allEdges[e4]).filter((t3) => t3.z === e3.z);
    this.lastOverlappingEdges = t2;
    const n2 = function(e4, t3) {
      const n3 = Math.abs(e4.start.y - e4.end.y) < D, o3 = Math.abs(e4.start.x - e4.end.x) < D;
      if (!n3 && !o3)
        return [];
      const i3 = n3 ? "x" : "y", r3 = n3 ? "y" : "x", s2 = e4.start[r3], a3 = e4.start[i3], c3 = e4.end[i3], l3 = Math.min(a3, c3), h2 = Math.max(a3, c3), d2 = (e5) => Math.max(l3, Math.min(h2, e5)), u2 = [];
      for (const n4 of t3) {
        if (n4 === e4)
          continue;
        const t4 = Math.abs(n4.start.y - n4.end.y) < D, o4 = Math.abs(n4.start.x - n4.end.x) < D;
        if (i3 === "x" && !t4)
          continue;
        if (i3 === "y" && !o4)
          continue;
        if (Math.abs(n4.start[r3] - s2) > D)
          continue;
        const a4 = Math.min(n4.start[i3], n4.end[i3]), c4 = Math.max(n4.start[i3], n4.end[i3]), l4 = d2(a4), h3 = d2(c4);
        h3 - l4 > D && u2.push({ s: l4, e: h3 });
      }
      if (u2.length === 0)
        return [{ ...e4, start: { ...e4.start }, end: { ...e4.end } }];
      u2.sort((e5, t4) => e5.s - t4.s);
      const p3 = [];
      for (const e5 of u2) {
        const t4 = p3[p3.length - 1];
        !t4 || e5.s > t4.e + D ? p3.push({ ...e5 }) : t4.e = Math.max(t4.e, e5.e);
      }
      const m2 = [];
      let g2 = l3;
      for (const e5 of p3)
        if (e5.s > g2 + D && m2.push({ s: g2, e: e5.s }), g2 = Math.max(g2, e5.e), g2 >= h2 - D)
          break;
      return h2 > g2 + D && m2.push({ s: g2, e: h2 }), m2.length === 0 ? [] : m2.filter((e5) => e5.e - e5.s > D).map((t4) => {
        const n4 = i3 === "x" ? { x: t4.s, y: s2 } : { x: s2, y: t4.s }, o4 = i3 === "x" ? { x: t4.e, y: s2 } : { x: s2, y: t4.e };
        return { parent: e4.parent, facingDirection: e4.facingDirection, start: n4, end: o4, z: e4.z };
      });
    }(e3, t2);
    this.lastUncoveredSegments = n2, this.segmentsWithAdjacentEmptySpace.push(...n2);
  }
  getOutput() {
    return { segmentsWithAdjacentEmptySpace: this.segmentsWithAdjacentEmptySpace };
  }
  visualize() {
    const e3 = { title: "FindSegmentsWithAdjacentEmptySpace", coordinateSystem: "cartesian", rects: [], points: [], lines: [], circles: [], infiniteLines: [], polygons: [], arrows: [], texts: [] };
    for (const t2 of this.input.allMeshNodes)
      e3.rects.push({ center: t2.center, width: t2.width, height: t2.height, stroke: "rgba(0, 0, 0, 0.1)" });
    for (const t2 of this.unprocessedEdges)
      e3.lines.push({ points: F([t2.start, t2.end], { dir: t2.facingDirection, amt: -0.1 }), strokeColor: "rgba(0, 0, 255, 0.5)", strokeDash: "5 5" });
    for (const t2 of this.segmentsWithAdjacentEmptySpace)
      e3.lines.push({ points: [t2.start, t2.end], strokeColor: "rgba(0,255,0, 0.5)" });
    if (this.lastCandidateEdge && e3.lines.push({ points: [this.lastCandidateEdge.start, this.lastCandidateEdge.end], strokeColor: "blue" }), this.lastOverlappingEdges)
      for (const t2 of this.lastOverlappingEdges)
        e3.lines.push({ points: F([t2.start, t2.end], { dir: t2.facingDirection, amt: 0.05 }), strokeColor: "red", strokeDash: "2 2" });
    if (this.lastUncoveredSegments)
      for (const t2 of this.lastUncoveredSegments)
        e3.lines.push({ points: F([t2.start, t2.end], { dir: t2.facingDirection, amt: -0.05 }), strokeColor: "green", strokeDash: "2 2" });
    return e3;
  }
};
function H(e3, t2, n2 = 0, o3 = e3.length - 1, i3 = W) {
  for (;o3 > n2; ) {
    if (o3 - n2 > 600) {
      const r4 = o3 - n2 + 1, s3 = t2 - n2 + 1, a4 = Math.log(r4), c3 = 0.5 * Math.exp(2 * a4 / 3), l3 = 0.5 * Math.sqrt(a4 * c3 * (r4 - c3) / r4) * (s3 - r4 / 2 < 0 ? -1 : 1);
      H(e3, t2, Math.max(n2, Math.floor(t2 - s3 * c3 / r4 + l3)), Math.min(o3, Math.floor(t2 + (r4 - s3) * c3 / r4 + l3)), i3);
    }
    const r3 = e3[t2];
    let s2 = n2, a3 = o3;
    for (V(e3, n2, t2), i3(e3[o3], r3) > 0 && V(e3, n2, o3);s2 < a3; ) {
      for (V(e3, s2, a3), s2++, a3--;i3(e3[s2], r3) < 0; )
        s2++;
      for (;i3(e3[a3], r3) > 0; )
        a3--;
    }
    i3(e3[n2], r3) === 0 ? V(e3, n2, a3) : (a3++, V(e3, a3, o3)), a3 <= t2 && (n2 = a3 + 1), t2 <= a3 && (o3 = a3 - 1);
  }
}
function V(e3, t2, n2) {
  const o3 = e3[t2];
  e3[t2] = e3[n2], e3[n2] = o3;
}
function W(e3, t2) {
  return e3 < t2 ? -1 : e3 > t2 ? 1 : 0;
}
var G = class {
  constructor(e3 = 9) {
    this._maxEntries = Math.max(4, e3), this._minEntries = Math.max(2, Math.ceil(0.4 * this._maxEntries)), this.clear();
  }
  all() {
    return this._all(this.data, []);
  }
  search(e3) {
    let t2 = this.data;
    const n2 = [];
    if (!re(e3, t2))
      return n2;
    const o3 = this.toBBox, i3 = [];
    for (;t2; ) {
      for (let r3 = 0;r3 < t2.children.length; r3++) {
        const s2 = t2.children[r3], a3 = t2.leaf ? o3(s2) : s2;
        re(e3, a3) && (t2.leaf ? n2.push(s2) : ie(e3, a3) ? this._all(s2, n2) : i3.push(s2));
      }
      t2 = i3.pop();
    }
    return n2;
  }
  collides(e3) {
    let t2 = this.data;
    if (!re(e3, t2))
      return false;
    const n2 = [];
    for (;t2; ) {
      for (let o3 = 0;o3 < t2.children.length; o3++) {
        const i3 = t2.children[o3], r3 = t2.leaf ? this.toBBox(i3) : i3;
        if (re(e3, r3)) {
          if (t2.leaf || ie(e3, r3))
            return true;
          n2.push(i3);
        }
      }
      t2 = n2.pop();
    }
    return false;
  }
  load(e3) {
    if (!e3 || !e3.length)
      return this;
    if (e3.length < this._minEntries) {
      for (let t3 = 0;t3 < e3.length; t3++)
        this.insert(e3[t3]);
      return this;
    }
    let t2 = this._build(e3.slice(), 0, e3.length - 1, 0);
    if (this.data.children.length)
      if (this.data.height === t2.height)
        this._splitRoot(this.data, t2);
      else {
        if (this.data.height < t2.height) {
          const e4 = this.data;
          this.data = t2, t2 = e4;
        }
        this._insert(t2, this.data.height - t2.height - 1, true);
      }
    else
      this.data = t2;
    return this;
  }
  insert(e3) {
    return e3 && this._insert(e3, this.data.height - 1), this;
  }
  clear() {
    return this.data = se([]), this;
  }
  remove(e3, t2) {
    if (!e3)
      return this;
    let n2 = this.data;
    const o3 = this.toBBox(e3), i3 = [], r3 = [];
    let s2, a3, c3;
    for (;n2 || i3.length; ) {
      if (n2 || (n2 = i3.pop(), a3 = i3[i3.length - 1], s2 = r3.pop(), c3 = true), n2.leaf) {
        const o4 = U(e3, n2.children, t2);
        if (o4 !== -1)
          return n2.children.splice(o4, 1), i3.push(n2), this._condense(i3), this;
      }
      c3 || n2.leaf || !ie(n2, o3) ? a3 ? (s2++, n2 = a3.children[s2], c3 = false) : n2 = null : (i3.push(n2), r3.push(s2), s2 = 0, a3 = n2, n2 = n2.children[0]);
    }
    return this;
  }
  toBBox(e3) {
    return e3;
  }
  compareMinX(e3, t2) {
    return e3.minX - t2.minX;
  }
  compareMinY(e3, t2) {
    return e3.minY - t2.minY;
  }
  toJSON() {
    return this.data;
  }
  fromJSON(e3) {
    return this.data = e3, this;
  }
  _all(e3, t2) {
    const n2 = [];
    for (;e3; )
      e3.leaf ? t2.push(...e3.children) : n2.push(...e3.children), e3 = n2.pop();
    return t2;
  }
  _build(e3, t2, n2, o3) {
    const i3 = n2 - t2 + 1;
    let r3, s2 = this._maxEntries;
    if (i3 <= s2)
      return r3 = se(e3.slice(t2, n2 + 1)), Z(r3, this.toBBox), r3;
    o3 || (o3 = Math.ceil(Math.log(i3) / Math.log(s2)), s2 = Math.ceil(i3 / Math.pow(s2, o3 - 1))), r3 = se([]), r3.leaf = false, r3.height = o3;
    const a3 = Math.ceil(i3 / s2), c3 = a3 * Math.ceil(Math.sqrt(s2));
    ae(e3, t2, n2, c3, this.compareMinX);
    for (let i4 = t2;i4 <= n2; i4 += c3) {
      const t3 = Math.min(i4 + c3 - 1, n2);
      ae(e3, i4, t3, a3, this.compareMinY);
      for (let n3 = i4;n3 <= t3; n3 += a3) {
        const i5 = Math.min(n3 + a3 - 1, t3);
        r3.children.push(this._build(e3, n3, i5, o3 - 1));
      }
    }
    return Z(r3, this.toBBox), r3;
  }
  _chooseSubtree(e3, t2, n2, o3) {
    for (;o3.push(t2), !t2.leaf && o3.length - 1 !== n2; ) {
      let n3, o4 = 1 / 0, i3 = 1 / 0;
      for (let r3 = 0;r3 < t2.children.length; r3++) {
        const s2 = t2.children[r3], a3 = ee(s2), c3 = ne(e3, s2) - a3;
        c3 < i3 ? (i3 = c3, o4 = a3 < o4 ? a3 : o4, n3 = s2) : c3 === i3 && a3 < o4 && (o4 = a3, n3 = s2);
      }
      t2 = n3 || t2.children[0];
    }
    return t2;
  }
  _insert(e3, t2, n2) {
    const o3 = n2 ? e3 : this.toBBox(e3), i3 = [], r3 = this._chooseSubtree(o3, this.data, t2, i3);
    for (r3.children.push(e3), J(r3, o3);t2 >= 0 && i3[t2].children.length > this._maxEntries; )
      this._split(i3, t2), t2--;
    this._adjustParentBBoxes(o3, i3, t2);
  }
  _split(e3, t2) {
    const n2 = e3[t2], o3 = n2.children.length, i3 = this._minEntries;
    this._chooseSplitAxis(n2, i3, o3);
    const r3 = this._chooseSplitIndex(n2, i3, o3), s2 = se(n2.children.splice(r3, n2.children.length - r3));
    s2.height = n2.height, s2.leaf = n2.leaf, Z(n2, this.toBBox), Z(s2, this.toBBox), t2 ? e3[t2 - 1].children.push(s2) : this._splitRoot(n2, s2);
  }
  _splitRoot(e3, t2) {
    this.data = se([e3, t2]), this.data.height = e3.height + 1, this.data.leaf = false, Z(this.data, this.toBBox);
  }
  _chooseSplitIndex(e3, t2, n2) {
    let o3, i3 = 1 / 0, r3 = 1 / 0;
    for (let s2 = t2;s2 <= n2 - t2; s2++) {
      const t3 = q(e3, 0, s2, this.toBBox), a3 = q(e3, s2, n2, this.toBBox), c3 = oe(t3, a3), l3 = ee(t3) + ee(a3);
      c3 < i3 ? (i3 = c3, o3 = s2, r3 = l3 < r3 ? l3 : r3) : c3 === i3 && l3 < r3 && (r3 = l3, o3 = s2);
    }
    return o3 || n2 - t2;
  }
  _chooseSplitAxis(e3, t2, n2) {
    const o3 = e3.leaf ? this.compareMinX : Q, i3 = e3.leaf ? this.compareMinY : K;
    this._allDistMargin(e3, t2, n2, o3) < this._allDistMargin(e3, t2, n2, i3) && e3.children.sort(o3);
  }
  _allDistMargin(e3, t2, n2, o3) {
    e3.children.sort(o3);
    const i3 = this.toBBox, r3 = q(e3, 0, t2, i3), s2 = q(e3, n2 - t2, n2, i3);
    let a3 = te(r3) + te(s2);
    for (let o4 = t2;o4 < n2 - t2; o4++) {
      const t3 = e3.children[o4];
      J(r3, e3.leaf ? i3(t3) : t3), a3 += te(r3);
    }
    for (let o4 = n2 - t2 - 1;o4 >= t2; o4--) {
      const t3 = e3.children[o4];
      J(s2, e3.leaf ? i3(t3) : t3), a3 += te(s2);
    }
    return a3;
  }
  _adjustParentBBoxes(e3, t2, n2) {
    for (let o3 = n2;o3 >= 0; o3--)
      J(t2[o3], e3);
  }
  _condense(e3) {
    for (let t2, n2 = e3.length - 1;n2 >= 0; n2--)
      e3[n2].children.length === 0 ? n2 > 0 ? (t2 = e3[n2 - 1].children, t2.splice(t2.indexOf(e3[n2]), 1)) : this.clear() : Z(e3[n2], this.toBBox);
  }
};
function U(e3, t2, n2) {
  if (!n2)
    return t2.indexOf(e3);
  for (let o3 = 0;o3 < t2.length; o3++)
    if (n2(e3, t2[o3]))
      return o3;
  return -1;
}
function Z(e3, t2) {
  q(e3, 0, e3.children.length, t2, e3);
}
function q(e3, t2, n2, o3, i3) {
  i3 || (i3 = se(null)), i3.minX = 1 / 0, i3.minY = 1 / 0, i3.maxX = -1 / 0, i3.maxY = -1 / 0;
  for (let r3 = t2;r3 < n2; r3++) {
    const t3 = e3.children[r3];
    J(i3, e3.leaf ? o3(t3) : t3);
  }
  return i3;
}
function J(e3, t2) {
  return e3.minX = Math.min(e3.minX, t2.minX), e3.minY = Math.min(e3.minY, t2.minY), e3.maxX = Math.max(e3.maxX, t2.maxX), e3.maxY = Math.max(e3.maxY, t2.maxY), e3;
}
function Q(e3, t2) {
  return e3.minX - t2.minX;
}
function K(e3, t2) {
  return e3.minY - t2.minY;
}
function ee(e3) {
  return (e3.maxX - e3.minX) * (e3.maxY - e3.minY);
}
function te(e3) {
  return e3.maxX - e3.minX + (e3.maxY - e3.minY);
}
function ne(e3, t2) {
  return (Math.max(t2.maxX, e3.maxX) - Math.min(t2.minX, e3.minX)) * (Math.max(t2.maxY, e3.maxY) - Math.min(t2.minY, e3.minY));
}
function oe(e3, t2) {
  const n2 = Math.max(e3.minX, t2.minX), o3 = Math.max(e3.minY, t2.minY), i3 = Math.min(e3.maxX, t2.maxX), r3 = Math.min(e3.maxY, t2.maxY);
  return Math.max(0, i3 - n2) * Math.max(0, r3 - o3);
}
function ie(e3, t2) {
  return e3.minX <= t2.minX && e3.minY <= t2.minY && t2.maxX <= e3.maxX && t2.maxY <= e3.maxY;
}
function re(e3, t2) {
  return t2.minX <= e3.maxX && t2.minY <= e3.maxY && t2.maxX >= e3.minX && t2.maxY >= e3.minY;
}
function se(e3) {
  return { children: e3, height: 1, leaf: true, minX: 1 / 0, minY: 1 / 0, maxX: -1 / 0, maxY: -1 / 0 };
}
function ae(e3, t2, n2, o3, i3) {
  const r3 = [t2, n2];
  for (;r3.length; ) {
    if ((n2 = r3.pop()) - (t2 = r3.pop()) <= o3)
      continue;
    const s2 = t2 + Math.ceil((n2 - t2) / o3 / 2) * o3;
    H(e3, s2, t2, n2, i3), r3.push(t2, s2, s2, n2);
  }
}
var ce = (e3) => ({ minX: Math.min(...e3.map((e4) => e4.x)), minY: Math.min(...e3.map((e4) => e4.y)), maxX: Math.max(...e3.map((e4) => e4.x)), maxY: Math.max(...e3.map((e4) => e4.y)) });
function le([e3, t2], [n2, o3], { lineThickness: i3 = 0 } = {}) {
  if (i3 === 0)
    return he(e3, t2, n2, o3);
  const r3 = function(e4, t3, n3, o4) {
    if (e4.x === t3.x && e4.y === t3.y)
      return pe(e4, n3, o4);
    if (n3.x === o4.x && n3.y === o4.y)
      return pe(n3, e4, t3);
    if (he(e4, t3, n3, o4))
      return 0;
    const i4 = [pe(e4, n3, o4), pe(t3, n3, o4), pe(n3, e4, t3), pe(o4, e4, t3)];
    return Math.min(...i4);
  }(e3, t2, n2, o3);
  return r3 <= i3;
}
function he(e3, t2, n2, o3) {
  const i3 = de(e3, t2, n2), r3 = de(e3, t2, o3), s2 = de(n2, o3, e3), a3 = de(n2, o3, t2);
  return i3 !== r3 && s2 !== a3 || (!(i3 !== 0 || !ue(e3, n2, t2)) || (!(r3 !== 0 || !ue(e3, o3, t2)) || (!(s2 !== 0 || !ue(n2, e3, o3)) || !(a3 !== 0 || !ue(n2, t2, o3)))));
}
function de(e3, t2, n2) {
  const o3 = (t2.y - e3.y) * (n2.x - t2.x) - (t2.x - e3.x) * (n2.y - t2.y);
  return o3 === 0 ? 0 : o3 > 0 ? 1 : 2;
}
function ue(e3, t2, n2) {
  return t2.x <= Math.max(e3.x, n2.x) && t2.x >= Math.min(e3.x, n2.x) && t2.y <= Math.max(e3.y, n2.y) && t2.y >= Math.min(e3.y, n2.y);
}
function pe(e3, t2, n2) {
  const o3 = (n2.x - t2.x) ** 2 + (n2.y - t2.y) ** 2;
  if (o3 === 0)
    return me(e3, t2);
  let i3 = ((e3.x - t2.x) * (n2.x - t2.x) + (e3.y - t2.y) * (n2.y - t2.y)) / o3;
  i3 = Math.max(0, Math.min(1, i3));
  return me(e3, { x: t2.x + i3 * (n2.x - t2.x), y: t2.y + i3 * (n2.y - t2.y) });
}
function me(e3, t2) {
  const n2 = e3.x - t2.x, o3 = e3.y - t2.y;
  return Math.sqrt(n2 * n2 + o3 * o3);
}
function ge(e3, t2, n2, o3) {
  const i3 = t2.x - e3.x, r3 = t2.y - e3.y, s2 = o3.x - n2.x, a3 = o3.y - n2.y, c3 = e3.x - n2.x, l3 = e3.y - n2.y, h2 = i3 * a3 - r3 * s2;
  if (Math.abs(h2) < 0.0000000001)
    return null;
  const d2 = (l3 * s2 - c3 * a3) / h2, u2 = (i3 * l3 - r3 * c3) / h2, p3 = 0.000000001;
  if (d2 >= -0.000000001 && d2 <= 1 + p3 && u2 >= -0.000000001 && u2 <= 1 + p3) {
    return { x: e3.x + d2 * i3, y: e3.y + d2 * r3 };
  }
  return null;
}
var fe = (e3) => {
  if ("minX" in e3)
    return e3;
  const t2 = e3.width / 2, n2 = e3.height / 2;
  return { minX: e3.center.x - t2, minY: e3.center.y - n2, maxX: e3.center.x + t2, maxY: e3.center.y + n2 };
};
var _e = (e3) => [{ x: e3.minX, y: e3.minY }, { x: e3.maxX, y: e3.minY }, { x: e3.maxX, y: e3.maxY }, { x: e3.minX, y: e3.maxY }];
var ye = (e3) => {
  const t2 = [];
  for (let n2 = 0;n2 < e3.length; n2++) {
    const o3 = e3[n2], i3 = e3[(n2 + 1) % e3.length];
    t2.push([o3, i3]);
  }
  return t2;
};
var be = (e3, t2, n2) => {
  const o3 = (e3.y - t2.y) * (n2.x - t2.x) - (e3.x - t2.x) * (n2.y - t2.y);
  if (Math.abs(o3) > 0.000000001)
    return false;
  const i3 = (e3.x - t2.x) * (n2.x - t2.x) + (e3.y - t2.y) * (n2.y - t2.y);
  if (i3 < 0)
    return false;
  const r3 = (n2.x - t2.x) ** 2 + (n2.y - t2.y) ** 2;
  return r3 !== 0 && !(i3 > r3);
};
var xe = (e3, t2) => e3.x >= t2.minX && e3.x <= t2.maxX && e3.y >= t2.minY && e3.y <= t2.maxY;
var ve = (e3, t2) => {
  if (t2.length < 3)
    return false;
  const n2 = ye(t2);
  for (const [t3, o4] of n2)
    if (be(e3, t3, o4))
      return true;
  let o3 = false;
  for (let n3 = 0, i3 = t2.length - 1;n3 < t2.length; i3 = n3++) {
    const r3 = t2[n3].x, s2 = t2[n3].y, a3 = t2[i3].x, c3 = t2[i3].y;
    s2 > e3.y != c3 > e3.y && e3.x < (a3 - r3) * (e3.y - s2) / (c3 - s2) + r3 && (o3 = !o3);
  }
  return o3;
};
var Ie = (e3, t2) => {
  const n2 = _e(e3), o3 = [[n2[0], n2[1]], [n2[1], n2[2]], [n2[2], n2[3]], [n2[3], n2[0]]], i3 = ye(t2);
  for (const [e4, t3] of i3)
    for (const [n3, i4] of o3)
      if (he(e4, t3, n3, i4))
        return true;
  return false;
};
var Se = (e3, t2) => ((e4, t3) => !(t3.length < 3) && (!!t3.some((t4) => xe(t4, e4)) || (!!_e(e4).some((e5) => ve(e5, t3)) || Ie(e4, t3))))(fe(e3), t2);
var Ce = (e3, t2) => ((e4, t3) => !(t3.length < 3) && (!!_e(e4).every((e5) => ve(e5, t3)) && !Ie(e4, t3)))(fe(e3), t2);
function Pe(e3) {
  const t2 = e3.width / 2, n2 = e3.height / 2;
  return { minX: e3.center.x - t2, maxX: e3.center.x + t2, minY: e3.center.y - n2, maxY: e3.center.y + n2 };
}
function Me(e3, t2, n2) {
  return Math.max(t2, Math.min(n2, e3));
}
function we(e3, t2, n2, o3) {
  if (e3.x === t2.x && e3.y === t2.y)
    return pe(e3, n2, o3);
  if (n2.x === o3.x && n2.y === o3.y)
    return pe(n2, e3, t2);
  if (he(e3, t2, n2, o3))
    return 0;
  const i3 = [pe(e3, n2, o3), pe(t2, n2, o3), pe(n2, e3, t2), pe(o3, e3, t2)];
  return Math.min(...i3);
}
function Ne(e3, t2, n2) {
  const o3 = { x: n2.minX, y: n2.minY }, i3 = { x: n2.maxX, y: n2.minY }, r3 = { x: n2.minX, y: n2.maxY }, s2 = { x: n2.maxX, y: n2.maxY };
  if (he(e3, t2, o3, i3) || he(e3, t2, i3, s2) || he(e3, t2, s2, r3) || he(e3, t2, r3, o3))
    return 0;
  if (e3.x >= n2.minX && e3.x <= n2.maxX && e3.y >= n2.minY && e3.y <= n2.maxY && t2.x >= n2.minX && t2.x <= n2.maxX && t2.y >= n2.minY && t2.y <= n2.maxY)
    return 0;
  const a3 = [pe(o3, e3, t2), pe(i3, e3, t2), pe(r3, e3, t2), pe(s2, e3, t2)];
  if (e3.x >= n2.minX && e3.x <= n2.maxX && e3.y >= n2.minY && e3.y <= n2.maxY)
    return 0;
  if (t2.x >= n2.minX && t2.x <= n2.maxX && t2.y >= n2.minY && t2.y <= n2.maxY)
    return 0;
  if (e3.x < n2.minX || e3.x > n2.maxX || e3.y < n2.minY || e3.y > n2.maxY) {
    const t3 = Me(e3.x, n2.minX, n2.maxX), o4 = Me(e3.y, n2.minY, n2.maxY);
    a3.push(me(e3, { x: t3, y: o4 }));
  }
  if (t2.x < n2.minX || t2.x > n2.maxX || t2.y < n2.minY || t2.y > n2.maxY) {
    const e4 = Me(t2.x, n2.minX, n2.maxX), o4 = Me(t2.y, n2.minY, n2.maxY);
    a3.push(me(t2, { x: e4, y: o4 }));
  }
  return Math.min(...a3);
}
function Re(e3, t2, n2) {
  const o3 = n2.width / 2, i3 = n2.height / 2;
  return Ne(e3, t2, { minX: n2.center.x - o3, maxX: n2.center.x + o3, minY: n2.center.y - i3, maxY: n2.center.y + i3 });
}
function Te(e3, t2, n2) {
  const o3 = { x: n2.x, y: n2.y };
  if (e3.x === t2.x && e3.y === t2.y)
    return Math.max(0, me(e3, o3) - n2.radius);
  const i3 = t2.x - e3.x, r3 = t2.y - e3.y, s2 = o3.x - e3.x, a3 = o3.y - e3.y, c3 = i3 * i3 + r3 * r3, l3 = Math.max(0, Math.min(1, (i3 * s2 + r3 * a3) / c3)), h2 = me({ x: e3.x + l3 * i3, y: e3.y + l3 * r3 }, o3);
  return Math.max(0, h2 - n2.radius);
}
function Ee(e3, t2, n2) {
  const o3 = n2.x - t2.x, i3 = n2.y - t2.y, r3 = o3 * o3 + i3 * i3;
  if (r3 === 0)
    return { x: t2.x, y: t2.y };
  let s2 = ((e3.x - t2.x) * o3 + (e3.y - t2.y) * i3) / r3;
  s2 = Math.max(0, Math.min(1, s2));
  return { x: t2.x + s2 * o3, y: t2.y + s2 * i3 };
}
var Ae = (e3, t2) => {
  const n2 = t2.x - e3.x, o3 = t2.y - e3.y, i3 = Math.sqrt(n2 ** 2 + o3 ** 2);
  return { x: n2 / i3, y: o3 / i3 };
};
function Oe(e3, t2) {
  const n2 = t2.width / 2, o3 = t2.height / 2, i3 = t2.center.x - n2, r3 = t2.center.x + n2, s2 = t2.center.y - o3, a3 = t2.center.y + o3;
  if (e3.x >= i3 && e3.x <= r3 && e3.y >= s2 && e3.y <= a3)
    return 0;
  return me(e3, { x: Me(e3.x, i3, r3), y: Me(e3.y, s2, a3) });
}
function ke(e3, t2) {
  return { x: (e3.x + t2.x) / 2, y: (e3.y + t2.y) / 2 };
}
var De = (e3, t2) => !(e3.maxX < t2.minX || t2.maxX < e3.minX || e3.maxY < t2.minY || t2.maxY < e3.minY);
var Le = (e3) => {
  const { center: t2, width: n2, height: o3 } = e3, i3 = n2 / 2, r3 = o3 / 2;
  return { minX: t2.x - i3, maxX: t2.x + i3, minY: t2.y - r3, maxY: t2.y + r3 };
};
var ze = 0.0001;
var Be = class extends BaseSolver {
  constructor(e3) {
    super(), this.input = e3, this.input.bounds && ((e4) => {
      const { minX: t2, maxX: n2, minY: o3, maxY: i3 } = e4;
      if (![t2, n2, o3, i3].every(Number.isFinite))
        throw new Error(`ExpandEdgesToEmptySpaceSolver bounds must be finite, got ${JSON.stringify(e4)}`);
      if (t2 > n2 || o3 > i3)
        throw new Error(`ExpandEdgesToEmptySpaceSolver bounds must satisfy minX <= maxX and minY <= maxY, got ${JSON.stringify(e4)}`);
    })(this.input.bounds), this.unprocessedSegments = [...this.input.segmentsWithAdjacentEmptySpace], this.rectSpatialIndex = new G, this.rectSpatialIndex.load(this.input.boardVoid?.boardVoidRects.map((e4, t2) => ({ capacityMeshNodeId: `void-rect-${t2}`, center: { x: e4.x + e4.width / 2, y: e4.y + e4.height / 2 }, width: e4.width, height: e4.height, availableZ: Array.from({ length: this.input.boardVoid?.layerCount || 0 }, (e5, t3) => t3), layer: "void", minX: e4.x, minY: e4.y, maxX: e4.x + e4.width, maxY: e4.y + e4.height })) || []), this.rectSpatialIndex.load(this.input.inputMeshNodes.map((e4) => ({ ...e4, minX: e4.center.x - e4.width / 2, minY: e4.center.y - e4.height / 2, maxX: e4.center.x + e4.width / 2, maxY: e4.center.y + e4.height / 2 })));
  }
  unprocessedSegments = [];
  expandedSegments = [];
  lastSegment = null;
  lastSearchBounds = null;
  lastCollidingNodes = null;
  lastSearchCorner1 = null;
  lastSearchCorner2 = null;
  lastExpandedSegment = null;
  rectSpatialIndex;
  _step() {
    if (this.unprocessedSegments.length === 0)
      return void (this.solved = true);
    const e3 = this.unprocessedSegments.shift();
    this.lastSegment = e3;
    const t2 = this.input.bounds;
    let n2 = e3;
    if (t2) {
      const o4 = ((e4, t3) => {
        const n3 = { ...e4.start }, o5 = { ...e4.end };
        if (z[e4.facingDirection].dx !== 0) {
          if (n3.x < t3.minX || n3.x > t3.maxX)
            return null;
          n3.y = Math.max(t3.minY, Math.min(t3.maxY, n3.y)), o5.y = Math.max(t3.minY, Math.min(t3.maxY, o5.y));
        } else {
          if (n3.y < t3.minY || n3.y > t3.maxY)
            return null;
          n3.x = Math.max(t3.minX, Math.min(t3.maxX, n3.x)), o5.x = Math.max(t3.minX, Math.min(t3.maxX, o5.x));
        }
        return { ...e4, start: n3, end: o5 };
      })(e3, t2);
      if (!o4)
        return;
      n2 = o4, this.lastSegment = o4;
    }
    const { dx: o3, dy: i3 } = z[n2.facingDirection], r3 = n2.end.x - n2.start.x, s2 = n2.end.y - n2.start.y, a3 = Math.sqrt(r3 ** 2 + s2 ** 2);
    if (a3 < ze)
      return;
    const c3 = r3 / a3, l3 = s2 / a3, h2 = t2 ? ((e4, t3) => {
      switch (e4.facingDirection) {
        case "x+":
          return t3.maxX - e4.start.x;
        case "x-":
          return e4.start.x - t3.minX;
        case "y+":
          return t3.maxY - e4.start.y;
        case "y-":
          return e4.start.y - t3.minY;
      }
    })(n2, t2) : 1 / 0;
    if (h2 < ze)
      return;
    const d2 = { x: n2.start.x + o3 * ze + c3 * ze * 10, y: n2.start.y + i3 * ze + l3 * ze * 10 }, u2 = { x: n2.end.x + o3 * ze - c3 * ze * 10, y: n2.end.y + i3 * ze - l3 * ze * 10 };
    this.lastSearchCorner1 = d2, this.lastSearchCorner2 = u2;
    let p3 = [];
    for (let e4 = 1;t2 || e4 < 1000; e4 *= 4) {
      const t3 = Math.min(e4, h2), r4 = ce([d2, u2, { x: d2.x + o3 * t3, y: d2.y + i3 * t3 }, { x: u2.x + o3 * t3, y: u2.y + i3 * t3 }]);
      if (this.lastSearchBounds = r4, p3 = this.rectSpatialIndex.search(r4).filter((e5) => e5.availableZ.includes(n2.z)).filter((e5) => e5.capacityMeshNodeId !== n2.parent.capacityMeshNodeId), p3.length > 0)
        break;
      if (e4 >= h2)
        break;
    }
    if (p3.length === 0 && !t2)
      return;
    this.lastCollidingNodes = p3;
    let m2 = h2;
    for (const e4 of p3) {
      const t3 = Re(n2.start, n2.end, e4);
      t3 < m2 && (m2 = t3);
    }
    const g2 = m2, f2 = ce([n2.start, n2.end, { x: n2.start.x + o3 * g2, y: n2.start.y + i3 * g2 }, { x: n2.end.x + o3 * g2, y: n2.end.y + i3 * g2 }]), _2 = { x: (f2.minX + f2.maxX) / 2, y: (f2.minY + f2.maxY) / 2 }, y2 = f2.maxX - f2.minX, b2 = f2.maxY - f2.minY, x2 = { segment: n2, newNode: { capacityMeshNodeId: `new-${n2.parent.capacityMeshNodeId}-${this.expandedSegments.length}`, center: _2, width: y2, height: b2, availableZ: [n2.z], layer: n2.parent.layer } };
    this.lastExpandedSegment = x2, y2 < ze || b2 < ze || (this.expandedSegments.push(x2), this.rectSpatialIndex.insert({ ...x2.newNode, ...f2 }));
  }
  getOutput() {
    return { expandedSegments: this.expandedSegments };
  }
  visualize() {
    const e3 = { title: "ExpandEdgesToEmptySpace", coordinateSystem: "cartesian", rects: [], points: [], lines: [], circles: [], infiniteLines: [], polygons: [], arrows: [], texts: [] };
    for (const t2 of this.input.inputMeshNodes)
      e3.rects.push({ center: t2.center, width: t2.width, height: t2.height, stroke: "rgba(0, 0, 0, 0.1)", layer: `z${t2.availableZ.join(",")}`, label: [`node ${t2.capacityMeshNodeId}`, `z:${t2.availableZ.join(",")}`].join(`
`) });
    for (const { newNode: t2 } of this.expandedSegments)
      e3.rects.push({ center: t2.center, width: t2.width, height: t2.height, fill: "green", label: `expandedSegment (z=${t2.availableZ.join(",")})`, layer: `z${t2.availableZ.join(",")}` });
    if (this.lastSegment && e3.lines.push({ points: [this.lastSegment.start, this.lastSegment.end], strokeColor: "rgba(0, 0, 255, 0.5)" }), this.lastSearchBounds && e3.rects.push({ center: { x: (this.lastSearchBounds.minX + this.lastSearchBounds.maxX) / 2, y: (this.lastSearchBounds.minY + this.lastSearchBounds.maxY) / 2 }, width: this.lastSearchBounds.maxX - this.lastSearchBounds.minX, height: this.lastSearchBounds.maxY - this.lastSearchBounds.minY, fill: "rgba(0, 0, 255, 0.25)" }), this.lastSearchCorner1 && this.lastSearchCorner2 && (e3.points.push({ x: this.lastSearchCorner1.x, y: this.lastSearchCorner1.y, color: "rgba(0, 0, 255, 0.5)", label: ["searchCorner1", `z=${this.lastSegment?.z}`].join(`
`) }), e3.points.push({ x: this.lastSearchCorner2.x, y: this.lastSearchCorner2.y, color: "rgba(0, 0, 255, 0.5)", label: ["searchCorner2", `z=${this.lastSegment?.z}`].join(`
`) })), this.lastExpandedSegment && e3.rects.push({ center: this.lastExpandedSegment.newNode.center, width: this.lastExpandedSegment.newNode.width, height: this.lastExpandedSegment.newNode.height, fill: "purple", label: `expandedSegment (z=${this.lastExpandedSegment.segment.z})` }), this.lastCollidingNodes)
      for (const t2 of this.lastCollidingNodes)
        e3.rects.push({ center: t2.center, width: t2.width, height: t2.height, fill: "rgba(255, 0, 0, 0.5)" });
    return e3;
  }
};
var Fe = class extends BasePipelineSolver {
  findSegmentsWithAdjacentEmptySpaceSolver;
  expandEdgesToEmptySpaceSolver;
  outputNodes = [];
  passExpandedCounts = [];
  currentPassNodes = [];
  currentTargetNodes = [];
  currentPassIndex = 0;
  expandedNodeIds = new Set;
  maxGapFillPasses = 1;
  pipelineDef = [definePipelineStep("findSegmentsWithAdjacentEmptySpaceSolver", Y, (e3) => [{ allMeshNodes: e3.currentPassNodes, targetMeshNodes: e3.currentTargetNodes }], { onSolved: () => {} }), definePipelineStep("expandEdgesToEmptySpaceSolver", Be, (e3) => [{ inputMeshNodes: e3.currentPassNodes, segmentsWithAdjacentEmptySpace: e3.findSegmentsWithAdjacentEmptySpaceSolver.getOutput().segmentsWithAdjacentEmptySpace, boardVoid: e3.inputProblem.boardVoid, bounds: e3.inputProblem.bounds }], { onSolved: (e3) => {
    e3.completePass();
  } })];
  _setup() {
    this.outputNodes = [...this.inputProblem.meshNodes], this.currentPassNodes = [...this.inputProblem.meshNodes], this.currentTargetNodes = [...this.inputProblem.meshNodes], this.passExpandedCounts = [], this.currentPassIndex = 0, this.expandedNodeIds.clear();
    const e3 = this.inputProblem.maxGapFillPasses;
    this.maxGapFillPasses = Number.isFinite(e3) ? Math.max(1, Math.floor(e3)) : 1;
  }
  completePass() {
    const e3 = (this.expandEdgesToEmptySpaceSolver?.getOutput().expandedSegments ?? []).map((e4) => e4.newNode);
    for (const t2 of e3)
      this.expandedNodeIds.add(t2.capacityMeshNodeId);
    this.passExpandedCounts.push(e3.length), this.currentPassNodes = [...this.currentPassNodes, ...e3], this.currentTargetNodes = e3, this.outputNodes = this.currentPassNodes, e3.length === 0 || this.currentPassIndex + 1 >= this.maxGapFillPasses || (this.currentPassIndex += 1, this.currentPipelineStageIndex = -1);
  }
  getOutput() {
    return { outputNodes: this.outputNodes.length ? this.outputNodes : this.inputProblem.meshNodes };
  }
  initialVisualize() {
    const e3 = { title: "GapFillSolverPipeline - Initial", coordinateSystem: "cartesian", rects: [], points: [], lines: [], circles: [], infiniteLines: [], polygons: [], arrows: [], texts: [] };
    for (const t2 of this.inputProblem.meshNodes)
      e3.rects.push({ center: t2.center, width: t2.width, height: t2.height, stroke: "rgba(0, 0, 0, 0.3)", fill: "rgba(100, 100, 100, 0.1)", layer: `z${t2.availableZ.join(",")}`, label: [`node ${t2.capacityMeshNodeId}`, `z:${t2.availableZ.join(",")}`].join(`
`) });
    return e3;
  }
  finalVisualize() {
    const e3 = { title: "GapFillSolverPipeline - Final", coordinateSystem: "cartesian", rects: [], points: [], lines: [], circles: [], infiniteLines: [], polygons: [], arrows: [], texts: [] }, { outputNodes: t2 } = this.getOutput();
    for (const n2 of t2) {
      const t3 = this.expandedNodeIds.has(n2.capacityMeshNodeId);
      e3.rects.push({ center: n2.center, width: n2.width, height: n2.height, stroke: t3 ? "rgba(0, 128, 0, 0.8)" : "rgba(0, 0, 0, 0.3)", fill: t3 ? "rgba(0, 200, 0, 0.3)" : "rgba(100, 100, 100, 0.1)", layer: `z${n2.availableZ.join(",")}`, label: [`${t3 ? "[expanded] " : ""}node ${n2.capacityMeshNodeId}`, `z:${n2.availableZ.join(",")}`].join(`
`) });
    }
    return e3;
  }
};
function $e(e3) {
  const t2 = e3.toLowerCase();
  if (t2 === "top")
    return -1e6;
  if (t2 === "bottom")
    return 1e6;
  const n2 = /^inner(\d+)$/i.exec(t2);
  return n2 ? parseInt(n2[1], 10) || 0 : 100 + t2.charCodeAt(0);
}
function Ye(e3) {
  const t2 = function(e4) {
    return Array.from(new Set(e4)).sort((e5, t3) => {
      const n3 = $e(e5), o4 = $e(t3);
      return n3 !== o4 ? n3 - o4 : e5.localeCompare(t3);
    });
  }((e3.obstacles ?? []).flatMap((e4) => e4.layers ?? [])), n2 = Math.max(1, e3.layerCount || t2.length || 1), o3 = Array.from({ length: n2 }, (e4, t3) => t3 === 0 ? "top" : t3 === n2 - 1 ? "bottom" : `inner${t3}`), i3 = [], r3 = new Set, s2 = (e4) => {
    const t3 = e4.toLowerCase();
    r3.has(t3) || (r3.add(t3), i3.push(e4));
  };
  o3.forEach(s2), t2.forEach(s2);
  const a3 = i3.slice(0, n2), c3 = new Map;
  return a3.forEach((e4, t3) => c3.set(e4.toLowerCase(), t3)), i3.slice(a3.length).forEach((e4) => {
    const t3 = e4.toLowerCase();
    c3.set(t3, ((e5) => {
      if (a3.length <= 1)
        return 0;
      if (e5 === "top")
        return 0;
      if (e5 === "bottom")
        return a3.length - 1;
      const t4 = /^inner(\d+)$/i.exec(e5);
      if (t4) {
        if (a3.length <= 2)
          return a3.length - 1;
        const e6 = parseInt(t4[1], 10), n3 = a3.length - 2;
        return Math.min(n3, Math.max(1, Number.isFinite(e6) ? e6 : 1));
      }
      return 0;
    })(t3));
  }), { layerNames: a3, zIndexByName: c3 };
}
function Xe(e3, t2) {
  if (e3.zLayers?.length)
    return Array.from(new Set(e3.zLayers)).sort((e4, t3) => e4 - t3);
  const n2 = (e3.layers ?? []).map((e4) => t2.get(e4.toLowerCase())).filter((e4) => typeof e4 == "number");
  return Array.from(new Set(n2)).sort((e4, t3) => e4 - t3);
}
function He(e3) {
  const { width: t2, height: n2 } = e3;
  return typeof t2 != "number" || typeof n2 != "number" ? null : { x: e3.center.x - t2 / 2, y: e3.center.y - n2 / 2, width: t2, height: n2 };
}
var Ve = (e3) => {
  const t2 = [{ fill: "#dbeafe", stroke: "#3b82f6" }, { fill: "#fef3c7", stroke: "#f59e0b" }, { fill: "#d1fae5", stroke: "#10b981" }, { fill: "#e9d5ff", stroke: "#a855f7" }, { fill: "#fed7aa", stroke: "#f97316" }, { fill: "#fecaca", stroke: "#ef4444" }];
  return t2[Math.min(...e3) % t2.length];
};
var We = 0.000000001;
var Ge = (e3, t2) => e3 > t2 + We;
var Ue = (e3, t2) => e3 > t2 - We;
var Ze = (e3, t2) => e3 < t2 - We;
var qe = (e3, t2) => e3 < t2 + We;
function Je(e3, t2) {
  return !(e3.x + e3.width <= t2.x + We || t2.x + t2.width <= e3.x + We || e3.y + e3.height <= t2.y + We || t2.y + t2.height <= e3.y + We);
}
function Qe(e3, t2) {
  const n2 = t2.x, o3 = t2.x + t2.width, i3 = t2.y, r3 = t2.y + t2.height;
  if (e3.x >= n2 && e3.x <= o3 && e3.y >= i3 && e3.y <= r3)
    return Math.min(e3.x - n2, o3 - e3.x, e3.y - i3, r3 - e3.y);
  const s2 = e3.x < n2 ? n2 - e3.x : e3.x > o3 ? e3.x - o3 : 0, a3 = e3.y < i3 ? i3 - e3.y : e3.y > r3 ? e3.y - r3 : 0;
  return s2 === 0 ? a3 : a3 === 0 ? s2 : Math.hypot(s2, a3);
}
function Ke(e3, t2) {
  const n2 = Math.max(e3[0], t2[0]), o3 = Math.min(e3[1], t2[1]);
  return o3 > n2 + We ? [n2, o3] : null;
}
function et(e3, t2) {
  if (!Je(e3, t2))
    return [e3];
  const n2 = Ke([e3.x, e3.x + e3.width], [t2.x, t2.x + t2.width]), o3 = Ke([e3.y, e3.y + e3.height], [t2.y, t2.y + t2.height]);
  if (!n2 || !o3)
    return [e3];
  const [i3, r3] = n2, [s2, a3] = o3, c3 = [];
  i3 > e3.x + We && c3.push({ x: e3.x, y: e3.y, width: i3 - e3.x, height: e3.height }), e3.x + e3.width > r3 + We && c3.push({ x: r3, y: e3.y, width: e3.x + e3.width - r3, height: e3.height });
  const l3 = Math.max(0, r3 - i3);
  return l3 > We && s2 > e3.y + We && c3.push({ x: i3, y: e3.y, width: l3, height: s2 - e3.y }), l3 > We && e3.y + e3.height > a3 + We && c3.push({ x: i3, y: a3, width: l3, height: e3.y + e3.height - a3 }), c3.filter((e4) => e4.width > We && e4.height > We);
}
var tt = (e3, t2) => !t2 || t2 <= 0 ? e3 : { x: e3.x - t2, y: e3.y - t2, width: e3.width + 2 * t2, height: e3.height + 2 * t2 };
var nt = (e3) => ({ x: e3.center.x - e3.width / 2, y: e3.center.y - e3.height / 2, width: e3.width, height: e3.height });
var ot = (e3) => e3.width * e3.height;
var it = (e3) => ({ ...e3, center: { ...e3.center }, availableZ: [...e3.availableZ] });
var rt = (e3, t2, n2) => ({ ...e3, capacityMeshNodeId: n2, center: { x: t2.x + t2.width / 2, y: t2.y + t2.height / 2 }, width: t2.width, height: t2.height, availableZ: [...e3.availableZ], layer: `z${e3.availableZ.join(",")}` });
var st = (e3) => !e3._containsObstacle && !e3._containsTarget;
var at = (e3, t2) => e3.availableZ.length === 1 && e3.availableZ[0] === t2;
var ct = (e3, t2) => Math.abs(e3.x - t2.x) <= We && Math.abs(e3.y - t2.y) <= We && Math.abs(e3.width - t2.width) <= We && Math.abs(e3.height - t2.height) <= We;
var lt = (e3, t2) => {
  let n2 = [e3];
  for (const e4 of t2) {
    if (n2.length === 0)
      return n2;
    const t3 = [];
    for (const o3 of n2)
      t3.push(...et(o3, e4));
    n2 = t3;
  }
  return n2;
};
var ht = (e3, t2) => lt(e3, t2).length === 0;
var dt = class extends BaseSolver {
  constructor(e3) {
    super(), this.input = e3;
  }
  outputNodes = [];
  promotedNodeIds = new Set;
  residualNodeIds = new Set;
  _setup() {
    this.outputNodes = this.input.meshNodes.map(it), this.promotedNodeIds.clear(), this.residualNodeIds.clear();
  }
  _step() {
    this.outputNodes = this.processOuterLayerContainmentMerges(), this.solved = true;
  }
  processOuterLayerContainmentMerges() {
    const e3 = this.input.simpleRouteJson, t2 = Math.max(1, e3.layerCount || 1);
    if (t2 < 3)
      return this.input.meshNodes.map(it);
    const n2 = t2 - 1, o3 = Math.max(e3.minViaDiameter ?? 0, e3.minTraceWidth || 0), i3 = this.input.meshNodes.map(it), r3 = this.buildObstaclesByLayer(t2);
    if (!r3.slice(1, -1).some((e4) => e4.some((e5) => e5.obstacle.isCopperPour)))
      return i3;
    const s2 = i3.filter((e4) => st(e4) && (at(e4, 0) || at(e4, n2))), a3 = i3.filter((e4) => !st(e4)), c3 = a3.filter((e4) => e4.availableZ.includes(0) || e4.availableZ.includes(n2)).map(nt), l3 = new Map;
    l3.set(0, i3.filter((e4) => st(e4) && e4.availableZ.includes(0))), l3.set(n2, i3.filter((e4) => st(e4) && e4.availableZ.includes(n2)));
    const h2 = [], d2 = [], u2 = s2.filter((e4) => e4.width + We >= o3 && e4.height + We >= o3).sort((e4, t3) => ot(nt(t3)) - ot(nt(e4)));
    for (const e4 of u2) {
      const t3 = e4.availableZ[0], i4 = t3 === 0 ? n2 : 0, s3 = nt(e4);
      if (c3.some((e5) => Je(e5, s3)))
        continue;
      const a4 = (l3.get(i4) ?? []).filter((e5) => Je(s3, nt(e5))), u3 = a4[0]?.availableZ;
      if (!u3)
        continue;
      if (d2.some((e5) => Je(s3, e5)))
        continue;
      if (!this.isTransitCompatibleAcrossIntermediateLayers({ rect: s3, fromZ: t3, toZ: i4, obstaclesByLayer: r3 }))
        continue;
      if (!ht(s3, a4.map(nt)))
        continue;
      const p4 = a4.every((e5) => e5.availableZ.length === u3.length && e5.availableZ.every((e6) => u3.includes(e6))) ? [{ rect: s3, availableZ: u3 }] : a4.map((e5) => {
        const t4 = nt(e5), n3 = Math.max(s3.x, t4.x), o4 = Math.max(s3.y, t4.y);
        return { rect: { x: n3, y: o4, width: Math.min(s3.x + s3.width, t4.x + t4.width) - n3, height: Math.min(s3.y + s3.height, t4.y + t4.height) - o4 }, availableZ: e5.availableZ };
      });
      for (const [n3, i5] of p4.entries()) {
        if (i5.rect.width + We < o3 || i5.rect.height + We < o3)
          continue;
        const r4 = [...new Set([t3, ...i5.availableZ])].sort((e5, t4) => e5 - t4), s4 = n3 === 0 ? e4.capacityMeshNodeId : `${e4.capacityMeshNodeId}-outer-support-${n3}`;
        h2.push(rt({ ...e4, availableZ: r4 }, i5.rect, s4)), d2.push(i5.rect), this.promotedNodeIds.add(s4);
      }
    }
    if (h2.length === 0)
      return i3;
    let p3 = 0;
    const m2 = [];
    for (const e4 of i3.filter(st)) {
      const t3 = nt(e4);
      if (e4.availableZ.filter((e5) => e5 === 0 || e5 === n2).length === 0) {
        m2.push(e4);
        continue;
      }
      const o4 = lt(t3, d2);
      if (o4.length === 1 && ct(o4[0], t3))
        m2.push(e4);
      else
        for (const t4 of o4) {
          const n3 = rt(e4, t4, `${e4.capacityMeshNodeId}-outer-merge-${p3++}`);
          m2.push(n3), this.residualNodeIds.add(n3.capacityMeshNodeId);
        }
    }
    return [...a3, ...h2, ...m2];
  }
  buildObstaclesByLayer(e3) {
    const t2 = Array.from({ length: e3 }, () => []);
    for (const n2 of this.input.simpleRouteJson.obstacles ?? []) {
      const o3 = He(n2);
      if (!o3)
        continue;
      const i3 = tt(o3, this.input.obstacleClearance ?? 0), r3 = Xe(n2, this.input.zIndexByName);
      for (const o4 of r3)
        o4 < 0 || o4 >= e3 || t2[o4].push({ obstacle: n2, rect: i3 });
    }
    return t2;
  }
  isTransitCompatibleAcrossIntermediateLayers(e3) {
    const { rect: t2, fromZ: n2, toZ: o3, obstaclesByLayer: i3 } = e3, r3 = Math.min(n2, o3), s2 = Math.max(n2, o3);
    if (s2 - r3 < 2)
      return false;
    let a3 = false;
    for (let e4 = r3 + 1;e4 < s2; e4++) {
      const n3 = (i3[e4] ?? []).filter((e5) => Je(e5.rect, t2));
      if (n3.length === 0)
        continue;
      if (n3.some((e5) => !e5.obstacle.isCopperPour))
        return false;
      if (!ht(t2, n3.map((e5) => e5.rect)))
        return false;
      a3 = true;
    }
    return a3;
  }
  getOutput() {
    return { outputNodes: this.outputNodes };
  }
  visualize() {
    return { title: "OuterLayerContainmentMergeSolver", coordinateSystem: "cartesian", rects: this.outputNodes.map((e3) => {
      const t2 = Ve(e3.availableZ), n2 = this.promotedNodeIds.has(e3.capacityMeshNodeId), o3 = this.residualNodeIds.has(e3.capacityMeshNodeId);
      return { center: e3.center, width: e3.width, height: e3.height, stroke: n2 ? "rgba(22, 163, 74, 0.95)" : o3 ? "rgba(37, 99, 235, 0.95)" : t2.stroke, fill: e3._containsObstacle ? "rgba(239, 68, 68, 0.35)" : n2 ? "rgba(34, 197, 94, 0.28)" : o3 ? "rgba(59, 130, 246, 0.18)" : t2.fill, layer: `z${e3.availableZ.join(",")}`, label: [`node ${e3.capacityMeshNodeId}`, `z:${e3.availableZ.join(",")}`].join(`
`) };
    }), points: [], lines: [], texts: [] };
  }
};
var gt = 0.000000001;
var ft = (e3) => Math.abs(e3.rect.x + e3.rect.width / 2 - e3.startX) < gt && Math.abs(e3.rect.y + e3.rect.height / 2 - e3.startY) < gt && Math.abs(e3.rect.width - e3.initialW) < gt && Math.abs(e3.rect.height - e3.initialH) < gt;
var _t = ({ rect: e3, bounds: t2 }) => ({ x: e3.x, y: e3.y, width: t2.x + t2.width - e3.x, height: e3.height });
var yt = ({ rect: e3, bounds: t2 }) => ({ x: e3.x, y: e3.y, width: e3.width, height: t2.y + t2.height - e3.y });
var bt = ({ rect: e3, bounds: t2 }) => ({ x: t2.x, y: e3.y, width: e3.x - t2.x, height: e3.height });
var xt = ({ rect: e3, bounds: t2 }) => ({ x: e3.x, y: t2.y, width: e3.width, height: e3.y - t2.y });
var vt = (e3, t2 = 0.000001) => Math.round(e3 / t2) * t2;
var It = (e3) => ({ x: vt(e3.x), y: vt(e3.y), width: vt(e3.width), height: vt(e3.height) });
function St(e3) {
  const { r: t2, bounds: n2, blockers: o3, maxAspect: i3 } = e3;
  let r3 = n2.x + n2.width - t2.x;
  for (const e4 of o3) {
    if (t2.y + t2.height > e4.y + We && e4.y + e4.height > t2.y + We) {
      if (Ue(e4.x, t2.x + t2.width))
        r3 = Math.min(r3, e4.x - t2.x);
      else if (e4.x + e4.width > t2.x + t2.width - We && e4.x < t2.x + t2.width + We)
        return 0;
    }
  }
  let s2 = Math.max(0, r3 - t2.width);
  if (s2 <= 0)
    return 0;
  if (i3 != null) {
    const { width: e4, height: n3 } = t2;
    e4 >= n3 && (s2 = Math.min(s2, i3 * n3 - e4));
  }
  return Math.max(0, s2);
}
function Ct(e3) {
  const { r: t2, bounds: n2, blockers: o3, maxAspect: i3 } = e3;
  let r3 = n2.y + n2.height - t2.y;
  for (const e4 of o3) {
    if (t2.x + t2.width > e4.x + We && e4.x + e4.width > t2.x + We) {
      if (Ue(e4.y, t2.y + t2.height))
        r3 = Math.min(r3, e4.y - t2.y);
      else if (e4.y + e4.height > t2.y + t2.height - We && e4.y < t2.y + t2.height + We)
        return 0;
    }
  }
  let s2 = Math.max(0, r3 - t2.height);
  if (s2 <= 0)
    return 0;
  if (i3 != null) {
    const { width: e4, height: n3 } = t2;
    n3 >= e4 && (s2 = Math.min(s2, i3 * e4 - n3));
  }
  return Math.max(0, s2);
}
function Pt(e3) {
  const { r: t2, bounds: n2, blockers: o3, maxAspect: i3 } = e3;
  let r3 = n2.x;
  for (const e4 of o3) {
    if (t2.y + t2.height > e4.y + We && e4.y + e4.height > t2.y + We) {
      if (qe(e4.x + e4.width, t2.x))
        r3 = Math.max(r3, e4.x + e4.width);
      else if (e4.x < t2.x + We && e4.x + e4.width > t2.x - We)
        return 0;
    }
  }
  let s2 = Math.max(0, t2.x - r3);
  if (s2 <= 0)
    return 0;
  if (i3 != null) {
    const { width: e4, height: n3 } = t2;
    e4 >= n3 && (s2 = Math.min(s2, i3 * n3 - e4));
  }
  return Math.max(0, s2);
}
function Mt(e3) {
  const { r: t2, bounds: n2, blockers: o3, maxAspect: i3 } = e3;
  let r3 = n2.y;
  for (const e4 of o3) {
    if (t2.x + t2.width > e4.x + We && e4.x + e4.width > t2.x + We) {
      if (qe(e4.y + e4.height, t2.y))
        r3 = Math.max(r3, e4.y + e4.height);
      else if (e4.y < t2.y + We && e4.y + e4.height > t2.y - We)
        return 0;
    }
  }
  let s2 = Math.max(0, t2.y - r3);
  if (s2 <= 0)
    return 0;
  if (i3 != null) {
    const { width: e4, height: n3 } = t2;
    n3 >= e4 && (s2 = Math.min(s2, i3 * e4 - n3));
  }
  return Math.max(0, s2);
}
var wt = (e3) => {
  const { rect: t2, seen: n2, blockers: o3 } = e3;
  n2.has(t2) || (n2.add(t2), o3.push(t2));
};
function Nt(e3) {
  const { startX: t2, startY: n2, gridSize: o3, bounds: i3, obsticalIndexByLayer: r3, placedIndexByLayer: s2, initialCellRatio: a3, maxAspectRatio: c3, minReq: l3 } = e3, h2 = Math.max(0.000000001, o3 * a3), d2 = Math.max(h2, l3.width), u2 = Math.max(h2, l3.height), p3 = [], m2 = new Set, g2 = s2.length, f2 = [], _2 = (o4) => {
    const a4 = ((e4) => {
      const { bounds: t3, rect: n3 } = e4, o5 = Math.max(t3.x, n3.x), i4 = Math.max(t3.y, n3.y), r4 = Math.min(t3.x + t3.width, n3.x + n3.width), s3 = Math.min(t3.y + t3.height, n3.y + n3.height);
      return r4 <= o5 + We || s3 <= i4 + We ? null : { minX: o5, minY: i4, maxX: r4, maxY: s3 };
    })({ bounds: i3, rect: o4 });
    if (a4) {
      for (const e4 of f2)
        if (e4.minX <= a4.minX && e4.minY <= a4.minY && e4.maxX >= a4.maxX && e4.maxY >= a4.maxY)
          return;
      for (const o5 of e3.zLayers) {
        const e4 = r3[o5];
        if (e4)
          for (const t3 of e4.search(a4))
            wt({ rect: t3, seen: m2, blockers: p3 });
        const i4 = s2[o5];
        if (i4)
          for (const e5 of i4.search(a4)) {
            e5.zLayers.length >= g2 && (ft({ rect: e5, startX: t2, startY: n2, initialW: d2, initialH: u2 }) || wt({ rect: e5, seen: m2, blockers: p3 }));
          }
      }
      for (let e4 = f2.length - 1;e4 >= 0; e4--) {
        const t3 = f2[e4];
        a4.minX <= t3.minX && a4.minY <= t3.minY && a4.maxX >= t3.maxX && a4.maxY >= t3.maxY && f2.splice(e4, 1);
      }
      f2.push(a4);
    }
  }, y2 = [{ ox: 0, oy: 0 }, { ox: -d2, oy: 0 }, { ox: 0, oy: -u2 }, { ox: -d2, oy: -u2 }, { ox: -d2 / 2, oy: -u2 / 2 }];
  let b2 = null, x2 = 0;
  e:
    for (const e4 of y2) {
      let o4 = { x: t2 + e4.ox, y: n2 + e4.oy, width: d2, height: u2 };
      if (_2(o4), Ze(o4.x, i3.x) || Ze(o4.y, i3.y) || Ge(o4.x + o4.width, i3.x + i3.width) || Ge(o4.y + o4.height, i3.y + i3.height))
        continue;
      for (const e5 of p3)
        if (Je(o4, e5))
          continue e;
      const r4 = 0.000001, s3 = 1000;
      let a4 = true, h3 = 0;
      for (;a4 && h3 < s3; ) {
        h3++, a4 = false;
        const e5 = { bounds: i3, blockers: p3, maxAspect: c3 };
        _2(_t({ rect: o4, bounds: i3 }));
        const t3 = St({ ...e5, r: o4 });
        t3 > r4 && (o4 = { ...o4, width: o4.width + t3 }, _2(o4), a4 = true), _2(yt({ rect: o4, bounds: i3 }));
        const n3 = Ct({ ...e5, r: o4 });
        n3 > r4 && (o4 = { ...o4, height: o4.height + n3 }, _2(o4), a4 = true), _2(bt({ rect: o4, bounds: i3 }));
        const s4 = Pt({ ...e5, r: o4 });
        s4 > r4 && (o4 = { x: o4.x - s4, y: o4.y, width: o4.width + s4, height: o4.height }, _2(o4), a4 = true), _2(xt({ rect: o4, bounds: i3 }));
        const l4 = Mt({ ...e5, r: o4 });
        l4 > r4 && (o4 = { x: o4.x, y: o4.y - l4, width: o4.width, height: o4.height + l4 }, _2(o4), a4 = true);
      }
      if (o4.width + We >= l3.width && o4.height + We >= l3.height) {
        const e5 = o4.width * o4.height;
        e5 > x2 && (b2 = It(o4), x2 = e5);
      }
    }
  return b2;
}
function Rt(e3) {
  const t2 = Math.max(e3.width, e3.height);
  return [t2 / 8, t2 / 16, t2 / 32];
}
function Tt(e3) {
  const t2 = { minX: e3.point.x, minY: e3.point.y, maxX: e3.point.x, maxY: e3.point.y };
  for (let n2 = 0;n2 < e3.layerCount; n2++) {
    const o3 = e3.obstacleIndexByLayer[n2], i3 = !!o3 && o3.collides(t2), r3 = e3.placedIndexByLayer[n2], s2 = !!r3 && r3.collides(t2);
    if (!i3 && !s2)
      return false;
  }
  return true;
}
function Et(e3) {
  const { x: t2, y: n2, z: o3, layerCount: i3, minSpan: r3, maxSpan: s2, obstacleIndexByLayer: a3, additionalBlockersByLayer: c3 } = e3, l3 = (e4) => {
    const o4 = { minX: t2, minY: n2, maxX: t2, maxY: n2 }, i4 = a3[e4];
    if (i4 && i4.collides(o4))
      return false;
    return !(c3?.[e4] ?? []).some((e5) => {
      return (i5 = { x: t2, y: n2 }).x >= (o5 = e5).x - We && i5.x <= o5.x + o5.width + We && i5.y >= o5.y - We && i5.y <= o5.y + o5.height + We;
      var o5, i5;
    });
  };
  let h2 = o3, d2 = o3;
  for (;h2 - 1 >= 0 && l3(h2 - 1); )
    h2--;
  for (;d2 + 1 < i3 && l3(d2 + 1); )
    d2++;
  if (typeof s2 == "number") {
    const e4 = ((e5, t3, n3) => Math.max(t3, Math.min(n3, e5)))(s2, 1, i3);
    for (;d2 - h2 + 1 > e4; )
      o3 - h2 > d2 - o3 ? h2++ : d2--;
  }
  const u2 = [];
  for (let e4 = h2;e4 <= d2; e4++)
    u2.push(e4);
  return u2.length >= r3 ? u2 : [];
}
var At = (e3, t2 = 0.000001) => Math.round(e3 / t2) * t2;
var Ot = (e3, t2 = 0.000001) => Math.round(e3 / t2) * t2;
var kt = (e3) => ("minX" in e3) ? { x: e3.minX, y: e3.minY, width: e3.maxX - e3.minX, height: e3.maxY - e3.minY } : e3;
function Dt(e3) {
  const { segment: t2, coveringIntervals: n2, hasReversedIntervals: o3, minSegmentLength: i3 } = e3, r3 = Ot(t2.lineStart), s2 = Ot(t2.lineEnd), a3 = Ot(t2.clipStart), c3 = Ot(t2.clipEnd);
  let l3 = [];
  if (o3 || a3 > c3)
    l3 = n2.filter((e4) => e4.sourceIndex !== t2.sourceIndex).map((e4) => {
      const t3 = Math.max(a3, e4.start), n3 = Math.min(c3, e4.end);
      return { start: Math.min(t3, n3), end: Math.max(t3, n3) };
    }).filter((e4) => e4.end > e4.start + We).sort((e4, t3) => e4.start - t3.start);
  else {
    let e4 = 1 / 0, o4 = -1 / 0;
    for (const i4 of n2) {
      if (i4.sourceIndex === t2.sourceIndex)
        continue;
      const n3 = Math.max(a3, i4.start), r4 = Math.min(c3, i4.end);
      r4 < n3 ? i4.end < a3 ? e4 = Math.min(e4, r4) : o4 = Math.max(o4, n3) : r4 > n3 + We && l3.push({ start: n3, end: r4 });
    }
    a3 > e4 + We && l3.unshift({ start: e4, end: a3 }), o4 > c3 + We && l3.push({ start: c3, end: o4 });
  }
  if (l3.length === 0) {
    return [{ start: r3, end: s2, center: (r3 + s2) / 2 }];
  }
  const h2 = [], d2 = l3[0].start;
  let u2 = l3[0].end;
  d2 > r3 + We && d2 - r3 >= i3 && h2.push({ start: r3, end: d2, center: (r3 + d2) / 2 });
  for (let e4 = 1;e4 < l3.length; e4++) {
    const t3 = l3[e4];
    t3.start <= u2 + We ? u2 = Math.max(u2, t3.end) : (t3.start - u2 >= i3 && h2.push({ start: u2, end: t3.start, center: (u2 + t3.start) / 2 }), u2 = t3.end);
  }
  return u2 < s2 - We && s2 - u2 >= i3 && h2.push({ start: u2, end: s2, center: (u2 + s2) / 2 }), h2;
}
function Lt(e3) {
  const { bounds: t2, minSize: n2, layerCount: o3, obstacleIndexByLayer: i3, placedIndexByLayer: r3, hardPlacedByLayer: s2 } = e3, a3 = [], c3 = Math.max(0.15 * n2, 3 * We);
  let l3 = 0;
  const h2 = new Map, d2 = Array.from({ length: o3 }, (e4, t3) => [...i3[t3]?.all() ?? [], ...s2[t3] ?? []].map(kt)), u2 = d2.map((e4) => {
    if (e4.length === 0)
      return null;
    const t3 = new E2(e4.length);
    for (const n3 of e4) {
      const e5 = n3.x + n3.width, o4 = n3.y + n3.height;
      t3.add(Math.min(n3.x, e5), Math.min(n3.y, o4), Math.max(n3.x, e5), Math.max(n3.y, o4));
    }
    return t3.finish(), t3;
  });
  function p3(e4) {
    const n3 = Ot(e4.x), s3 = Ot(e4.y), { z: a4 } = e4, c4 = n3, l4 = s3;
    if (c4 < t2.x + We || l4 < t2.y + We || c4 > t2.x + t2.width - We || l4 > t2.y + t2.height - We)
      return;
    const d3 = ((e5) => `${e5.z}|${e5.x.toFixed(6)}|${e5.y.toFixed(6)}`)({ x: c4, y: l4, z: a4 }), u3 = h2.get(d3);
    u3 && (u3.order < e4.order || u3.order === e4.order && u3.pointOrder <= e4.pointOrder) || function(e5) {
      return Tt({ layerCount: o3, obstacleIndexByLayer: i3, placedIndexByLayer: r3, point: e5 });
    }({ x: c4, y: l4 }) || h2.set(d3, { x: c4, y: l4, z: a4, order: e4.order, pointOrder: e4.pointOrder });
  }
  for (let e4 = 0;e4 < o3; e4++) {
    const o4 = (d2[e4] ?? []).map((e5) => ({ x: Ot(e5.x), y: Ot(e5.y), width: Ot(e5.width), height: Ot(e5.height) })), i4 = o4.length > 0 ? new E2(o4.length) : null;
    if (i4) {
      for (const e5 of o4)
        i4.add(e5.x, e5.y, e5.x + e5.width, e5.y + e5.height);
      i4.finish();
    }
    const r4 = new Map, s3 = new Map, a4 = (e5) => {
      const t3 = e5.vertical ? r4 : s3, n3 = t3.get(e5.coordinate);
      n3 ? n3.push(e5.edgeOrdinal) : t3.set(e5.coordinate, [e5.edgeOrdinal]);
    }, h3 = l3;
    let u3 = 0;
    const m3 = [{ x: t2.x + c3, y: t2.y + c3 }, { x: t2.x + t2.width - c3, y: t2.y + c3 }, { x: t2.x + c3, y: t2.y + t2.height - c3 }, { x: t2.x + t2.width - c3, y: t2.y + t2.height - c3 }];
    for (const t3 of m3)
      p3({ ...t3, z: e4, order: h3 + u3++, pointOrder: 0 });
    const g2 = u3;
    for (const e5 of [t2.y + c3, t2.y + t2.height - c3])
      a4({ vertical: false, coordinate: e5, edgeOrdinal: u3++ });
    for (const e5 of [t2.x + c3, t2.x + t2.width - c3])
      a4({ vertical: true, coordinate: e5, edgeOrdinal: u3++ });
    const f2 = u3;
    for (let e5 = 0;e5 < o4.length; e5++) {
      const n3 = o4[e5];
      for (const e6 of [n3.x - c3, n3.x + n3.width + c3]) {
        const n4 = u3++;
        e6 > t2.x + We && e6 < t2.x + t2.width - We && a4({ vertical: true, coordinate: e6, edgeOrdinal: n4 });
      }
      for (const e6 of [n3.y - c3, n3.y + n3.height + c3]) {
        const n4 = u3++;
        e6 > t2.y + We && e6 < t2.y + t2.height - We && a4({ vertical: false, coordinate: e6, edgeOrdinal: n4 });
      }
    }
    l3 = h3 + u3;
    for (const a5 of [true, false]) {
      const l4 = a5 ? r4 : s3;
      for (const [r5, s4] of l4) {
        const l5 = i4 ? a5 ? i4.search(r5, -1 / 0, r5, 1 / 0) : i4.search(-1 / 0, r5, 1 / 0, r5) : [], d3 = [];
        let u4 = false;
        for (const e5 of l5) {
          const t3 = o4[e5];
          if (a5 ? t3.x > r5 || t3.x + t3.width < r5 : t3.y > r5 || t3.y + t3.height < r5)
            continue;
          const n3 = Ot(a5 ? t3.y : t3.x), i5 = Ot(a5 ? t3.y + t3.height : t3.x + t3.width);
          d3.push({ start: n3, end: i5, sourceIndex: e5 }), i5 < n3 && (u4 = true);
        }
        d3.sort((e5, t3) => e5.start - t3.start);
        for (const i5 of s4) {
          const r6 = i5 < f2, s5 = i5 - f2, l6 = r6 ? undefined : Math.floor(s5 / 4), m4 = r6 ? t2 : o4[l6], _2 = r6 ? i5 === g2 || i5 === g2 + 2 : s5 % 4 == 0 || s5 % 4 == 2, y2 = a5 ? m4.x : m4.y, b2 = a5 ? m4.width : m4.height, x2 = r6 ? _2 ? y2 + c3 : y2 + b2 - c3 : _2 ? y2 - c3 : y2 + b2 + c3, v2 = a5 ? m4.y : m4.x, I2 = a5 ? m4.y + m4.height : m4.x + m4.width, S2 = Dt({ segment: { lineStart: r6 ? v2 + c3 : v2, lineEnd: r6 ? I2 - c3 : I2, clipStart: v2, clipEnd: I2, sourceIndex: l6 }, coveringIntervals: d3, hasReversedIntervals: u4, minSegmentLength: 0.5 * n2 });
          let C = 0;
          for (const t3 of S2) {
            const o5 = (t4) => p3({ ...a5 ? { x: x2, y: t4, z: e4 } : { x: t4, y: x2, z: e4 }, order: h3 + i5, pointOrder: C++ }), s6 = t3.end - t3.start;
            if (r6) {
              if (s6 < n2)
                continue;
              o5(t3.center), s6 > 1.5 * n2 && (o5(t3.start + 0.4 * n2), o5(t3.end - 0.4 * n2));
            } else
              o5(t3.center);
          }
        }
      }
    }
  }
  const m2 = [...h2.values()].sort((e4, t3) => e4.order - t3.order || e4.pointOrder - t3.pointOrder);
  for (const { x: e4, y: n3, z: r4 } of m2) {
    const c4 = d2[r4] ?? [];
    let l4 = Qe({ x: e4, y: n3 }, t2);
    const h3 = u2[r4];
    if (h3) {
      const t3 = h3.neighbors(e4, n3, 1)[0];
      l4 = Math.min(l4, Qe({ x: e4, y: n3 }, c4[t3]));
      const o4 = h3.search(e4 - l4, n3 - l4, e4 + l4, n3 + l4);
      for (const t4 of o4)
        l4 = Math.min(l4, Qe({ x: e4, y: n3 }, c4[t4]));
    }
    const p4 = Ot(l4), m3 = Et({ x: e4, y: n3, z: r4, layerCount: o3, minSpan: 1, maxSpan: undefined, obstacleIndexByLayer: i3, additionalBlockersByLayer: s2 });
    a3.push({ x: e4, y: n3, z: r4, distance: p4, zSpanLen: m3.length, isEdgeSeed: true });
  }
  return a3.sort((e4, t3) => t3.zSpanLen - e4.zSpanLen || t3.distance - e4.distance || e4.z - t3.z || e4.x - t3.x || e4.y - t3.y), a3;
}
var zt = (e3, t2) => ({ ...e3, minX: e3.x, minY: e3.y, maxX: e3.x + e3.width, maxY: e3.y + e3.height, zLayers: t2.zLayers });
function Bt(e3, t2) {
  const n2 = e3.placed[t2], { rect: o3, zLayers: i3 } = n2, r3 = e3.layerCount, s2 = [], a3 = [];
  for (let n3 = 0;n3 < e3.placed.length; n3++) {
    if (n3 === t2)
      continue;
    const c4 = e3.placed[n3];
    if (c4.zLayers.length >= r3)
      continue;
    if (!Je(c4.rect, o3))
      continue;
    const l3 = c4.zLayers.filter((e4) => i3.includes(e4));
    if (l3.length === 0)
      continue;
    const h2 = et(c4.rect, o3);
    s2.push(n3);
    const d2 = c4.zLayers.filter((e4) => !i3.includes(e4));
    d2.length > 0 && a3.push({ rect: c4.rect, zLayers: d2 });
    const u2 = Math.min(e3.options.minSingle.width, e3.options.minMulti.width), p3 = Math.min(e3.options.minSingle.height, e3.options.minMulti.height);
    for (const e4 of h2)
      e4.width + We >= u2 && e4.height + We >= p3 && a3.push({ rect: e4, zLayers: l3.slice() });
  }
  const c3 = (e4, t3) => e4.minX === t3.minX && e4.minY === t3.minY && e4.maxX === t3.maxX && e4.maxY === t3.maxY;
  s2.sort((e4, t3) => t3 - e4).forEach((t3) => {
    const n3 = e3.placed.splice(t3, 1)[0];
    if (e3.placedIndexByLayer)
      for (const t4 of n3.zLayers) {
        const o4 = e3.placedIndexByLayer[t4];
        o4 && o4.remove(zt(n3.rect, { zLayers: n3.zLayers }), c3);
      }
  });
  for (const t3 of a3) {
    e3.placed.push(t3);
    for (const n3 of t3.zLayers)
      if (e3.placedIndexByLayer) {
        const o4 = e3.placedIndexByLayer[n3];
        o4 && o4.insert(zt(t3.rect, { zLayers: t3.zLayers.slice() }));
      }
  }
}
var Ft = class extends BaseSolver {
  constructor(e3) {
    super(), this.input = e3;
  }
  srj;
  layerNames;
  layerCount;
  bounds;
  options;
  boardVoidRects;
  gridIndex;
  candidates;
  placed;
  placedIndexByLayer;
  hardPlacedByLayer;
  expansionIndex;
  edgeAnalysisDone;
  totalSeedsThisGrid;
  consumedSeedsThisGrid;
  _setup() {
    const e3 = this.input.simpleRouteJson, t2 = this.input.gridOptions ?? {}, n2 = this.input.layerNames && this.input.zIndexByName, { layerNames: o3, zIndexByName: i3 } = n2 ? { layerNames: this.input.layerNames, zIndexByName: this.input.zIndexByName } : Ye({ obstacles: e3.obstacles, layerCount: e3.layerCount }), r3 = Math.max(1, o3.length, e3.layerCount || 1), s2 = { x: e3.bounds.minX, y: e3.bounds.minY, width: e3.bounds.maxX - e3.bounds.minX, height: e3.bounds.maxY - e3.bounds.minY }, a3 = Math.max(0.01, e3.minTraceWidth || 0.15), c3 = { ...{ gridSizes: [], initialCellRatio: 0.2, maxAspectRatio: 3, minSingle: { width: 2 * a3, height: 2 * a3 }, minMulti: { width: 4 * a3, height: 4 * a3, minLayers: Math.min(2, Math.max(1, e3.layerCount || 1)) }, preferMultiLayer: true, maxMultiLayerSpan: undefined }, ...t2, gridSizes: t2.gridSizes ?? Rt(s2) };
    this.srj = e3, this.layerNames = o3, this.layerCount = r3, this.bounds = s2, this.options = c3, this.boardVoidRects = this.input.boardVoidRects, this.gridIndex = 0, this.candidates = [], this.placed = [], this.placedIndexByLayer = Array.from({ length: r3 }, () => new G), this.hardPlacedByLayer = Array.from({ length: r3 }, () => []), this.expansionIndex = 0, this.edgeAnalysisDone = false, this.totalSeedsThisGrid = 0, this.consumedSeedsThisGrid = 0, this.stats = { gridIndex: this.gridIndex };
  }
  _step() {
    this._stepGrid(), this.stats.gridIndex = this.gridIndex, this.stats.placed = this.placed.length;
  }
  _stepGrid() {
    const { gridSizes: e3, initialCellRatio: t2, maxAspectRatio: n2, minSingle: o3, minMulti: i3, preferMultiLayer: r3, maxMultiLayerSpan: s2 } = this.options, a3 = e3[this.gridIndex];
    if (this.candidates.length === 0 && this.consumedSeedsThisGrid === 0 && (this.candidates = function(e4) {
      const { bounds: t3, gridSize: n3, layerCount: o4, obstacleIndexByLayer: i4, placedIndexByLayer: r4, hardPlacedByLayer: s3 } = e4, a4 = new Map, c4 = Array.from({ length: o4 }, (e5, t4) => [...i4[t4]?.all() ?? [], ...s3[t4] ?? []]);
      for (let e5 = t3.x;e5 < t3.x + t3.width; e5 += n3)
        for (let l5 = t3.y;l5 < t3.y + t3.height; l5 += n3) {
          if (Math.abs(e5 - t3.x) < We || Math.abs(l5 - t3.y) < We || e5 > t3.x + t3.width - n3 - We || l5 > t3.y + t3.height - n3 - We)
            continue;
          if (Tt({ layerCount: o4, obstacleIndexByLayer: i4, placedIndexByLayer: r4, point: { x: e5, y: l5 } }))
            continue;
          let h3 = [], d3 = 0;
          for (let t4 = 0;t4 < o4; t4++) {
            const n4 = Et({ x: e5, y: l5, z: t4, layerCount: o4, minSpan: 1, maxSpan: undefined, obstacleIndexByLayer: i4, additionalBlockersByLayer: s3 });
            n4.length > h3.length && (h3 = n4, d3 = t4);
          }
          const u2 = h3.length ? h3[Math.floor(h3.length / 2)] : d3, p3 = c4[u2] ?? [];
          let m2 = Qe({ x: e5, y: l5 }, t3);
          for (const t4 of p3)
            m2 = Math.min(m2, Qe({ x: e5, y: l5 }, t4));
          const g2 = At(m2), f2 = `${e5.toFixed(6)}|${l5.toFixed(6)}`, _2 = { x: e5, y: l5, z: u2, distance: g2, zSpanLen: h3.length }, y2 = a4.get(f2);
          (!y2 || _2.zSpanLen > (y2.zSpanLen ?? 0) || _2.zSpanLen === y2.zSpanLen && _2.distance > y2.distance) && a4.set(f2, _2);
        }
      const l4 = Array.from(a4.values());
      return l4.sort((e5, t4) => t4.zSpanLen - e5.zSpanLen || t4.distance - e5.distance || e5.z - t4.z || e5.x - t4.x || e5.y - t4.y), l4;
    }({ bounds: this.bounds, gridSize: a3, layerCount: this.layerCount, hardPlacedByLayer: this.hardPlacedByLayer, obstacleIndexByLayer: this.input.obstacleIndexByLayer, placedIndexByLayer: this.placedIndexByLayer }), this.totalSeedsThisGrid = this.candidates.length, this.consumedSeedsThisGrid = 0), this.consumedSeedsThisGrid >= this.candidates.length) {
      if (this.gridIndex + 1 < e3.length)
        return this.gridIndex += 1, this.candidates = [], this.totalSeedsThisGrid = 0, void (this.consumedSeedsThisGrid = 0);
      if (!this.edgeAnalysisDone) {
        const e4 = Math.min(o3.width, o3.height);
        return this.candidates = Lt({ bounds: this.bounds, minSize: e4, layerCount: this.layerCount, obstacleIndexByLayer: this.input.obstacleIndexByLayer, placedIndexByLayer: this.placedIndexByLayer, hardPlacedByLayer: this.hardPlacedByLayer }), this.edgeAnalysisDone = true, this.totalSeedsThisGrid = this.candidates.length, void (this.consumedSeedsThisGrid = 0);
      }
      return this.candidates = [], this.solved = true, void (this.expansionIndex = 0);
    }
    const c3 = this.candidates[this.consumedSeedsThisGrid++];
    if (Tt({ layerCount: this.layerCount, obstacleIndexByLayer: this.input.obstacleIndexByLayer, placedIndexByLayer: this.placedIndexByLayer, point: { x: c3.x, y: c3.y } }))
      return;
    const l3 = Et({ x: c3.x, y: c3.y, z: c3.z, layerCount: this.layerCount, minSpan: i3.minLayers, maxSpan: s2, obstacleIndexByLayer: this.input.obstacleIndexByLayer, additionalBlockersByLayer: this.hardPlacedByLayer }), h2 = [];
    l3.length >= i3.minLayers && h2.push({ kind: "multi", layers: l3, minReq: { width: i3.width, height: i3.height } }), h2.push({ kind: "single", layers: [c3.z], minReq: { width: o3.width, height: o3.height } });
    const d2 = r3 ? h2 : h2.reverse();
    for (const e4 of d2) {
      const o4 = Nt({ startX: c3.x, startY: c3.y, gridSize: a3, bounds: this.bounds, obsticalIndexByLayer: this.input.obstacleIndexByLayer, placedIndexByLayer: this.placedIndexByLayer, initialCellRatio: t2, maxAspectRatio: n2, minReq: e4.minReq, zLayers: e4.layers });
      if (!o4)
        continue;
      const i4 = { rect: o4, zLayers: [...e4.layers] }, r4 = this.placed.push(i4) - 1;
      for (const t3 of e4.layers) {
        const e5 = this.placedIndexByLayer[t3];
        e5 && e5.insert(zt(o4, { zLayers: i4.zLayers }));
      }
      if (Bt({ layerCount: this.layerCount, placed: this.placed, options: this.options, placedIndexByLayer: this.placedIndexByLayer }, r4), i4.zLayers.length >= this.layerCount)
        for (const e5 of i4.zLayers)
          this.hardPlacedByLayer[e5].push(i4.rect);
      return;
    }
  }
  computeProgress() {
    if (this.solved)
      return 1;
    const e3 = this.options.gridSizes.length, t2 = this.gridIndex / (e3 + 1), n2 = Math.max(1, this.totalSeedsThisGrid), o3 = n2 ? this.consumedSeedsThisGrid / n2 : 1;
    return Math.min(0.999, t2 + o3 * (1 / (e3 + 1)));
  }
  getOutput() {
    return { layerNames: this.layerNames, layerCount: this.layerCount, bounds: this.bounds, options: this.options, boardVoidRects: this.boardVoidRects, gridIndex: this.gridIndex, candidates: this.candidates, placed: this.placed, expansionIndex: this.expansionIndex, edgeAnalysisDone: this.edgeAnalysisDone, totalSeedsThisGrid: this.totalSeedsThisGrid, consumedSeedsThisGrid: this.consumedSeedsThisGrid, obstacles: this.srj.obstacles, obstacleClearance: this.input.obstacleClearance };
  }
  visualize() {
    const e3 = [], t2 = [], n2 = [], o3 = this.srj ?? this.input.simpleRouteJson, i3 = o3.bounds.minX, r3 = o3.bounds.maxX, s2 = o3.bounds.minY, a3 = o3.bounds.maxY;
    o3.outline && o3.outline.length > 1 ? n2.push({ points: [...o3.outline, o3.outline[0]], strokeColor: "#111827", strokeWidth: 0.01, label: "outline" }) : e3.push({ center: { x: (i3 + r3) / 2, y: (s2 + a3) / 2 }, width: r3 - i3, height: a3 - s2, fill: "none", stroke: "#111827", label: "board" });
    for (const t3 of o3.obstacles ?? [])
      t3.type !== "rect" && t3.type !== "oval" || e3.push({ center: { x: t3.center.x, y: t3.center.y }, width: t3.width, height: t3.height, fill: "#fee2e2", stroke: "#ef4444", layer: "obstacle", label: "obstacle" });
    if (this.boardVoidRects) {
      let t3 = null;
      if (o3.outline && o3.outline.length > 0) {
        const e4 = o3.outline.map((e5) => e5.x), n3 = o3.outline.map((e5) => e5.y), i4 = Math.min(...e4), r4 = Math.min(...n3);
        t3 = { x: i4, y: r4, width: Math.max(...e4) - i4, height: Math.max(...n3) - r4 };
      }
      for (const n3 of this.boardVoidRects)
        t3 && !Je(n3, t3) || e3.push({ center: { x: n3.x + n3.width / 2, y: n3.y + n3.height / 2 }, width: n3.width, height: n3.height, fill: "rgba(0, 0, 0, 0.5)", stroke: "none", label: "void" });
    }
    if (this.candidates?.length)
      for (const e4 of this.candidates)
        t2.push({ x: e4.x, y: e4.y, label: `z:${e4.z}` });
    if (this.placed?.length)
      for (const t3 of this.placed) {
        const n3 = Ve(t3.zLayers);
        e3.push({ center: { x: t3.rect.x + t3.rect.width / 2, y: t3.rect.y + t3.rect.height / 2 }, width: t3.rect.width, height: t3.rect.height, fill: n3.fill, stroke: n3.stroke, layer: `z${t3.zLayers.join(",")}`, label: `free
z:${t3.zLayers.join(",")}` });
      }
    return { title: "RectDiff Grid", coordinateSystem: "cartesian", rects: e3, points: t2, lines: n2 };
  }
};
var $t = (e3, t2) => e3.minX === t2.minX && e3.minY === t2.minY && e3.maxX === t2.maxX && e3.maxY === t2.maxY;
var Yt = class extends BaseSolver {
  constructor(e3) {
    super(), this.input = e3;
  }
  placedIndexByLayer = [];
  _meshNodes = [];
  _setup() {
    this.stats = { gridIndex: this.input.gridIndex }, this.placedIndexByLayer = Array.from({ length: this.input.layerCount }, () => new G);
    for (const e3 of this.input.placed)
      for (const t2 of e3.zLayers) {
        const n2 = this.placedIndexByLayer[t2];
        n2 && n2.insert(zt(e3.rect, { zLayers: e3.zLayers }));
      }
  }
  _step() {
    this.solved || (this._stepExpansion(), this.stats.gridIndex = this.input.gridIndex, this.stats.placed = this.input.placed.length, this.input.expansionIndex >= this.input.placed.length && this.finalizeIfNeeded());
  }
  _stepExpansion() {
    if (this.input.expansionIndex >= this.input.placed.length)
      return;
    const e3 = this.input.expansionIndex, t2 = this.input.placed[e3], n2 = this.input.options.gridSizes[this.input.options.gridSizes.length - 1], o3 = t2.rect, i3 = Nt({ startX: t2.rect.x + t2.rect.width / 2, startY: t2.rect.y + t2.rect.height / 2, gridSize: n2, bounds: this.input.bounds, obsticalIndexByLayer: this.input.obstacleIndexByLayer, placedIndexByLayer: this.placedIndexByLayer, initialCellRatio: 0, maxAspectRatio: null, minReq: { width: t2.rect.width, height: t2.rect.height }, zLayers: t2.zLayers });
    if (i3) {
      this.input.placed[e3] = { rect: i3, zLayers: t2.zLayers };
      for (const e4 of t2.zLayers) {
        const n3 = this.placedIndexByLayer[e4];
        n3 && (n3.remove(zt(o3, { zLayers: t2.zLayers }), $t), n3.insert(zt(i3, { zLayers: t2.zLayers })));
      }
      Bt({ layerCount: this.input.layerCount, placed: this.input.placed, options: this.input.options, placedIndexByLayer: this.placedIndexByLayer }, e3);
    }
    this.input.expansionIndex += 1;
  }
  finalizeIfNeeded() {
    if (this.solved)
      return;
    const e3 = function(e4) {
      const t2 = e4.placed.map((e5) => ({ minX: e5.rect.x, minY: e5.rect.y, maxX: e5.rect.x + e5.rect.width, maxY: e5.rect.y + e5.rect.height, zLayers: [...e5.zLayers].sort((e6, t3) => e6 - t3) }));
      for (const n2 of e4.obstacles ?? []) {
        const o3 = He(n2);
        if (!o3)
          continue;
        const i3 = e4.obstacleClearance ? { x: o3.x - e4.obstacleClearance, y: o3.y - e4.obstacleClearance, width: o3.width + 2 * e4.obstacleClearance, height: o3.height + 2 * e4.obstacleClearance } : o3, r3 = n2.zLayers?.length && n2.zLayers.length > 0 ? n2.zLayers : Xe(n2, e4.zIndexByName);
        t2.push({ minX: i3.x, minY: i3.y, maxX: i3.x + i3.width, maxY: i3.y + i3.height, zLayers: [...new Set(r3)].sort((e5, t3) => e5 - t3), isObstacle: true, connectedTo: [...n2.connectedTo] });
      }
      return t2;
    }({ placed: this.input.placed, obstacles: this.input.obstacles, zIndexByName: this.input.zIndexByName, boardVoidRects: this.input.boardVoidRects, obstacleClearance: this.input.obstacleClearance });
    this._meshNodes = function(e4) {
      let t2 = 0;
      const n2 = [];
      for (const o3 of e4) {
        const e5 = Math.max(0, o3.maxX - o3.minX), i3 = Math.max(0, o3.maxY - o3.minY);
        e5 <= 0 || i3 <= 0 || o3.zLayers.length === 0 || n2.push({ capacityMeshNodeId: "cmn_" + t2++, center: { x: (o3.minX + o3.maxX) / 2, y: (o3.minY + o3.maxY) / 2 }, width: e5, height: i3, layer: "top", availableZ: o3.zLayers.slice(), _containsObstacle: o3.isObstacle, _containsTarget: o3.isObstacle, ...o3.connectedTo?.length ? { _connectedTo: [...o3.connectedTo] } : {} });
      }
      return n2;
    }(e3), this.solved = true;
  }
  computeProgress() {
    if (this.solved)
      return 1;
    const e3 = this.input.options.gridSizes.length, t2 = e3 / (e3 + 1), n2 = Math.max(1, this.input.placed.length), o3 = n2 ? this.input.expansionIndex / n2 : 1;
    return Math.min(0.999, t2 + o3 * (1 / (e3 + 1)));
  }
  getOutput() {
    if (this.solved)
      return { meshNodes: this._meshNodes };
    return { meshNodes: this.input.placed.map((e3, t2) => ({ capacityMeshNodeId: `expand-preview-${t2}`, center: { x: e3.rect.x + e3.rect.width / 2, y: e3.rect.y + e3.rect.height / 2 }, width: e3.rect.width, height: e3.rect.height, availableZ: e3.zLayers.slice(), layer: `z${e3.zLayers.join(",")}` })) };
  }
  visualize() {
    const e3 = [];
    for (const t2 of this.input.placed ?? [])
      e3.push({ center: { x: t2.rect.x + t2.rect.width / 2, y: t2.rect.y + t2.rect.height / 2 }, width: t2.rect.width, height: t2.rect.height, stroke: "rgba(37, 99, 235, 0.9)", fill: "rgba(191, 219, 254, 0.5)", layer: `z${t2.zLayers.join(",")}`, label: `expanded
z:${t2.zLayers.join(",")}` });
    return { title: "RectDiff Expansion", coordinateSystem: "cartesian", rects: e3, points: [], lines: [] };
  }
};
var Xt = class extends BasePipelineSolver {
  rectDiffSeedingSolver;
  rectDiffExpansionSolver;
  obstacleIndexByLayer;
  layerNames;
  zIndexByName;
  constructor(e3) {
    super(e3);
    const { obstacleIndexByLayer: t2, layerNames: n2, zIndexByName: o3 } = ((e4) => {
      const { srj: t3, boardVoidRects: n3, obstacleClearance: o4 } = e4, { layerNames: i3, zIndexByName: r3 } = Ye({ obstacles: t3.obstacles, layerCount: t3.layerCount }), s2 = Math.max(1, i3.length, t3.layerCount || 1), a3 = (t3.bounds.minX, t3.bounds.minY, t3.bounds.maxX, t3.bounds.minX, t3.bounds.maxY, t3.bounds.minY, Array.from({ length: s2 }, () => new G)), c3 = (e5, t4) => {
        const n4 = { ...e5, minX: e5.x, minY: e5.y, maxX: e5.x + e5.width, maxY: e5.y + e5.height, zLayers: [t4] };
        a3[t4]?.insert(n4);
      };
      if (t3.outline && t3.outline.length > 2)
        for (const e5 of n3 ?? [])
          for (let t4 = 0;t4 < s2; t4++)
            c3(e5, t4);
      for (const e5 of t3.obstacles ?? []) {
        const t4 = He(e5);
        if (!t4)
          continue;
        const n4 = tt(t4, o4 ?? 0), i4 = Xe(e5, r3), a4 = i4.filter((e6) => e6 < 0 || e6 >= s2);
        if (a4.length)
          throw new Error(`RectDiff: obstacle uses z-layer indices ${a4.join(",")} outside 0-${s2 - 1}`);
        e5.zLayers && e5.zLayers.length !== 0 || !i4.length || (e5.zLayers = i4);
        for (const e6 of i4)
          c3(n4, e6);
      }
      return { obstacleIndexByLayer: a3, layerNames: i3, zIndexByName: r3 };
    })({ srj: { bounds: e3.bounds, obstacles: e3.obstacles, connections: e3.connections, outline: e3.outline?.outline, layerCount: e3.layerCount, minTraceWidth: e3.minTraceWidth }, boardVoidRects: e3.boardVoidRects, obstacleClearance: e3.obstacleClearance });
    this.obstacleIndexByLayer = t2, this.layerNames = e3.layerNames ?? n2, this.zIndexByName = e3.zIndexByName ?? o3;
  }
  pipelineDef = [definePipelineStep("rectDiffSeedingSolver", Ft, (e3) => [{ simpleRouteJson: { bounds: e3.inputProblem.bounds, obstacles: e3.inputProblem.obstacles, connections: e3.inputProblem.connections, outline: e3.inputProblem.outline?.outline, layerCount: e3.inputProblem.layerCount, minTraceWidth: e3.inputProblem.minTraceWidth }, gridOptions: e3.inputProblem.gridOptions, obstacleIndexByLayer: e3.obstacleIndexByLayer, boardVoidRects: e3.inputProblem.boardVoidRects, layerNames: e3.layerNames, zIndexByName: e3.zIndexByName, obstacleClearance: e3.inputProblem.obstacleClearance }]), definePipelineStep("rectDiffExpansionSolver", Yt, (e3) => {
    const t2 = e3.rectDiffSeedingSolver?.getOutput();
    if (!t2)
      throw new Error("RectDiffSeedingSolver did not produce output");
    return [{ layerNames: t2.layerNames ?? [], boardVoidRects: e3.inputProblem.boardVoidRects ?? [], layerCount: e3.inputProblem.layerCount, bounds: t2.bounds, candidates: t2.candidates, consumedSeedsThisGrid: t2.placed.length, totalSeedsThisGrid: t2.candidates.length, placed: t2.placed, edgeAnalysisDone: t2.edgeAnalysisDone, gridIndex: t2.gridIndex, expansionIndex: t2.expansionIndex, obstacleIndexByLayer: e3.obstacleIndexByLayer, options: t2.options, zIndexByName: e3.zIndexByName, layerNamesCanonical: e3.layerNames, obstacles: e3.inputProblem.obstacles, obstacleClearance: e3.inputProblem.obstacleClearance }];
  })];
  getConstructorParams() {
    return [this.inputProblem];
  }
  getOutput() {
    if (this.rectDiffExpansionSolver)
      return this.rectDiffExpansionSolver.getOutput();
    if (this.rectDiffSeedingSolver) {
      return { meshNodes: this.rectDiffSeedingSolver.getOutput().placed.map((e3, t2) => ({ capacityMeshNodeId: `grid-${t2}`, center: { x: e3.rect.x + e3.rect.width / 2, y: e3.rect.y + e3.rect.height / 2 }, width: e3.rect.width, height: e3.rect.height, availableZ: e3.zLayers, layer: `z${e3.zLayers.join(",")}` })) };
    }
    return { meshNodes: [] };
  }
  visualize() {
    return this.rectDiffExpansionSolver ? this.rectDiffExpansionSolver.visualize() : this.rectDiffSeedingSolver ? this.rectDiffSeedingSolver.visualize() : { title: "RectDiff Grid Pipeline", coordinateSystem: "cartesian", rects: [], points: [], lines: [] };
  }
};
function Ht(e3, t2) {
  return Array.isArray(t2) ? [e3.a * t2[0] + e3.c * t2[1] + e3.e, e3.b * t2[0] + e3.d * t2[1] + e3.f] : { x: e3.a * t2.x + e3.c * t2.y + e3.e, y: e3.b * t2.x + e3.d * t2.y + e3.f };
}
function Vt(e3) {
  const { a: t2, b: n2, c: o3, d: i3, e: r3, f: s2 } = e3, a3 = t2 * i3 - n2 * o3;
  return { a: i3 / a3, b: n2 / -a3, c: o3 / -a3, d: t2 / a3, e: (i3 * r3 - o3 * s2) / -a3, f: (n2 * r3 - t2 * s2) / a3 };
}
function Wt(e3) {
  return e3 === undefined;
}
function Gt(e3, t2 = 0) {
  return { a: 1, c: 0, e: e3, b: 0, d: 1, f: t2 };
}
function Ut(...e3) {
  const t2 = (e4, t3) => ({ a: e4.a * t3.a + e4.c * t3.b, c: e4.a * t3.c + e4.c * t3.d, e: e4.a * t3.e + e4.c * t3.f + e4.e, b: e4.b * t3.a + e4.d * t3.b, d: e4.b * t3.c + e4.d * t3.d, f: e4.b * t3.e + e4.d * t3.f + e4.f });
  switch ((e3 = Array.isArray(e3[0]) ? e3[0] : e3).length) {
    case 0:
      throw new Error("no matrices provided");
    case 1:
      return e3[0];
    case 2:
      return t2(e3[0], e3[1]);
    default: {
      const [n2, o3, ...i3] = e3;
      return Ut(t2(n2, o3), ...i3);
    }
  }
}
function Zt(...e3) {
  return Ut(...e3);
}
var { cos: qt, sin: Jt, PI: Qt } = Math;
function Kt(e3, t2, n2) {
  const o3 = qt(e3), i3 = Jt(e3), r3 = { a: o3, c: -i3, e: 0, b: i3, d: o3, f: 0 };
  return Wt(t2) || Wt(n2) ? r3 : Ut([Gt(t2, n2), r3, Gt(-t2, -n2)]);
}
function en(e3, t2 = undefined, n2 = undefined) {
  return Kt(e3 * Qt / 180, t2, n2);
}
var nn = (l(s()), l(h()), new TextEncoder, (() => {
  const e3 = new Uint8Array(4);
  new Uint32Array(e3.buffer)[0] = 1, e3[0];
})(), globalThis.Int8Array, globalThis.Uint8Array, globalThis.Int16Array, globalThis.Uint16Array, globalThis.Int32Array, globalThis.Uint32Array, globalThis.BigUint64Array, globalThis.BigInt64Array, globalThis.Float32Array, globalThis.Float64Array, []);
for (let e3 = 0;e3 < 256; e3++) {
  let t2 = e3;
  for (let e4 = 0;e4 < 8; e4++)
    1 & t2 ? t2 = 3988292384 ^ t2 >>> 1 : t2 >>>= 1;
  nn[e3] = t2;
}
var on = new Uint16Array([255]);
var rn = (new Uint8Array(on.buffer)[0], new Uint16Array([255]));
new Uint8Array(rn.buffer)[0], new Uint8Array(0), Uint8Array.of(137, 80, 78, 71, 13, 10, 26, 10), new TextDecoder("latin1");
function sn() {
  return sn = Object.assign ? Object.assign.bind() : function(e3) {
    for (var t2 = 1;t2 < arguments.length; t2++) {
      var n2 = arguments[t2];
      for (var o3 in n2)
        ({}).hasOwnProperty.call(n2, o3) && (e3[o3] = n2[o3]);
    }
    return e3;
  }, sn.apply(null, arguments);
}
function an(e3, t2) {
  return (an = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function(e4, t3) {
    return e4.__proto__ = t3, e4;
  })(e3, t2);
}
function cn(e3) {
  return (cn = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function(e4) {
    return e4.__proto__ || Object.getPrototypeOf(e4);
  })(e3);
}
function ln() {
  try {
    var e3 = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
  } catch (e4) {}
  return (ln = function() {
    return !!e3;
  })();
}
function hn(e3) {
  var t2 = typeof Map == "function" ? new Map : undefined;
  return hn = function(e4) {
    if (e4 === null || !function(e5) {
      try {
        return Function.toString.call(e5).indexOf("[native code]") !== -1;
      } catch (t3) {
        return typeof e5 == "function";
      }
    }(e4))
      return e4;
    if (typeof e4 != "function")
      throw new TypeError("Super expression must either be null or a function");
    if (t2 !== undefined) {
      if (t2.has(e4))
        return t2.get(e4);
      t2.set(e4, n2);
    }
    function n2() {
      return function(e5, t3, n3) {
        if (ln())
          return Reflect.construct.apply(null, arguments);
        var o3 = [null];
        o3.push.apply(o3, t3);
        var i3 = new (e5.bind.apply(e5, o3));
        return n3 && an(i3, n3.prototype), i3;
      }(e4, arguments, cn(this).constructor);
    }
    return n2.prototype = Object.create(e4.prototype, { constructor: { value: n2, enumerable: false, writable: true, configurable: true } }), an(n2, e4);
  }, hn(e3);
}
var dn = { 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 }).

`, 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 }).

`, 3: `Passed an incorrect argument to a color function, please pass a string representation of a color.

`, 4: `Couldn't generate valid rgb string from %s, it returned %s.

`, 5: `Couldn't parse the color string. Please provide the color as a string in hex, rgb, rgba, hsl or hsla notation.

`, 6: `Passed invalid arguments to rgb, please pass multiple numbers e.g. rgb(255, 205, 100) or an object e.g. rgb({ red: 255, green: 205, blue: 100 }).

`, 7: `Passed invalid arguments to rgba, please pass multiple numbers e.g. rgb(255, 205, 100, 0.75) or an object e.g. rgb({ red: 255, green: 205, blue: 100, alpha: 0.75 }).

`, 8: `Passed invalid argument to toColorString, please pass a RgbColor, RgbaColor, HslColor or HslaColor object.

`, 9: `Please provide a number of steps to the modularScale helper.

`, 10: `Please pass a number or one of the predefined scales to the modularScale helper as the ratio.

`, 11: `Invalid value passed as base to modularScale, expected number or em string but got "%s"

`, 12: `Expected a string ending in "px" or a number passed as the first argument to %s(), got "%s" instead.

`, 13: `Expected a string ending in "px" or a number passed as the second argument to %s(), got "%s" instead.

`, 14: `Passed invalid pixel value ("%s") to %s(), please pass a value like "12px" or 12.

`, 15: `Passed invalid base value ("%s") to %s(), please pass a value like "12px" or 12.

`, 16: `You must provide a template to this method.

`, 17: `You passed an unsupported selector state to this method.

`, 18: `minScreen and maxScreen must be provided as stringified numbers with the same units.

`, 19: `fromSize and toSize must be provided as stringified numbers with the same units.

`, 20: `expects either an array of objects or a single object with the properties prop, fromSize, and toSize.

`, 21: "expects the objects in the first argument array to have the properties `prop`, `fromSize`, and `toSize`.\n\n", 22: "expects the first argument object to have the properties `prop`, `fromSize`, and `toSize`.\n\n", 23: `fontFace expects a name of a font-family.

`, 24: `fontFace expects either the path to the font file(s) or a name of a local copy.

`, 25: `fontFace expects localFonts to be an array.

`, 26: `fontFace expects fileFormats to be an array.

`, 27: `radialGradient requries at least 2 color-stops to properly render.

`, 28: `Please supply a filename to retinaImage() as the first argument.

`, 29: `Passed invalid argument to triangle, please pass correct pointingDirection e.g. 'right'.

`, 30: "Passed an invalid value to `height` or `width`. Please provide a pixel based unit.\n\n", 31: `The animation shorthand only takes 8 arguments. See the specification for more information: http://mdn.io/animation

`, 32: `To pass multiple animations please supply them in arrays, e.g. animation(['rotate', '2s'], ['move', '1s'])
To pass a single animation please supply them in simple values, e.g. animation('rotate', '2s')

`, 33: `The animation shorthand arrays can only have 8 elements. See the specification for more information: http://mdn.io/animation

`, 34: `borderRadius expects a radius value as a string or number as the second argument.

`, 35: `borderRadius expects one of "top", "bottom", "left" or "right" as the first argument.

`, 36: `Property must be a string value.

`, 37: `Syntax Error at %s.

`, 38: `Formula contains a function that needs parentheses at %s.

`, 39: `Formula is missing closing parenthesis at %s.

`, 40: `Formula has too many closing parentheses at %s.

`, 41: `All values in a formula must have the same unit or be unitless.

`, 42: `Please provide a number of steps to the modularScale helper.

`, 43: `Please pass a number or one of the predefined scales to the modularScale helper as the ratio.

`, 44: `Invalid value passed as base to modularScale, expected number or em/rem string but got %s.

`, 45: `Passed invalid argument to hslToColorString, please pass a HslColor or HslaColor object.

`, 46: `Passed invalid argument to rgbToColorString, please pass a RgbColor or RgbaColor object.

`, 47: `minScreen and maxScreen must be provided as stringified numbers with the same units.

`, 48: `fromSize and toSize must be provided as stringified numbers with the same units.

`, 49: `Expects either an array of objects or a single object with the properties prop, fromSize, and toSize.

`, 50: `Expects the objects in the first argument array to have the properties prop, fromSize, and toSize.

`, 51: `Expects the first argument object to have the properties prop, fromSize, and toSize.

`, 52: `fontFace expects either the path to the font file(s) or a name of a local copy.

`, 53: `fontFace expects localFonts to be an array.

`, 54: `fontFace expects fileFormats to be an array.

`, 55: `fontFace expects a name of a font-family.

`, 56: `linearGradient requries at least 2 color-stops to properly render.

`, 57: `radialGradient requries at least 2 color-stops to properly render.

`, 58: `Please supply a filename to retinaImage() as the first argument.

`, 59: `Passed invalid argument to triangle, please pass correct pointingDirection e.g. 'right'.

`, 60: "Passed an invalid value to `height` or `width`. Please provide a pixel based unit.\n\n", 61: `Property must be a string value.

`, 62: `borderRadius expects a radius value as a string or number as the second argument.

`, 63: `borderRadius expects one of "top", "bottom", "left" or "right" as the first argument.

`, 64: `The animation shorthand only takes 8 arguments. See the specification for more information: http://mdn.io/animation.

`, 65: `To pass multiple animations please supply them in arrays, e.g. animation(['rotate', '2s'], ['move', '1s'])\\nTo pass a single animation please supply them in simple values, e.g. animation('rotate', '2s').

`, 66: `The animation shorthand arrays can only have 8 elements. See the specification for more information: http://mdn.io/animation.

`, 67: `You must provide a template to this method.

`, 68: `You passed an unsupported selector state to this method.

`, 69: `Expected a string ending in "px" or a number passed as the first argument to %s(), got %s instead.

`, 70: `Expected a string ending in "px" or a number passed as the second argument to %s(), got %s instead.

`, 71: `Passed invalid pixel value %s to %s(), please pass a value like "12px" or 12.

`, 72: `Passed invalid base value %s to %s(), please pass a value like "12px" or 12.

`, 73: `Please provide a valid CSS variable.

`, 74: `CSS variable not found and no default was provided.

`, 75: `important requires a valid style object, got a %s instead.

`, 76: `fromSize and toSize must be provided as stringified numbers with the same units as minScreen and maxScreen.

`, 77: `remToPx expects a value in "rem" but you provided it in "%s".

`, 78: `base must be set in "px" or "%" but you set it in "%s".
` };
function un() {
  for (var e3 = arguments.length, t2 = new Array(e3), n2 = 0;n2 < e3; n2++)
    t2[n2] = arguments[n2];
  var o3, i3 = t2[0], r3 = [];
  for (o3 = 1;o3 < t2.length; o3 += 1)
    r3.push(t2[o3]);
  return r3.forEach(function(e4) {
    i3 = i3.replace(/%[a-z]/, e4);
  }), i3;
}
var pn = function(e3) {
  var t2, n2;
  function o3(t3) {
    var n3;
    if (false)
      ;
    else {
      for (var o4 = arguments.length, i3 = new Array(o4 > 1 ? o4 - 1 : 0), r3 = 1;r3 < o4; r3++)
        i3[r3 - 1] = arguments[r3];
      n3 = e3.call(this, un.apply(undefined, [dn[t3]].concat(i3))) || this;
    }
    return function(e4) {
      if (e4 === undefined)
        throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
      return e4;
    }(n3);
  }
  return n2 = e3, (t2 = o3).prototype = Object.create(n2.prototype), t2.prototype.constructor = t2, an(t2, n2), o3;
}(hn(Error));
function mn(e3, t2) {
  return e3.substr(-t2.length) === t2;
}
var gn = /^([+-]?(?:\d+|\d*\.\d+))([a-z]*|%)$/;
function fn(e3) {
  return typeof e3 != "string" ? e3 : e3.match(gn) ? parseFloat(e3) : e3;
}
var _n = function(e3) {
  return function(t2, n2) {
    n2 === undefined && (n2 = "16px");
    var o3 = t2, i3 = n2;
    if (typeof t2 == "string") {
      if (!mn(t2, "px"))
        throw new pn(69, e3, t2);
      o3 = fn(t2);
    }
    if (typeof n2 == "string") {
      if (!mn(n2, "px"))
        throw new pn(70, e3, n2);
      i3 = fn(n2);
    }
    if (typeof o3 == "string")
      throw new pn(71, t2, e3);
    if (typeof i3 == "string")
      throw new pn(72, n2, e3);
    return "" + o3 / i3 + e3;
  };
};
_n("em"), _n("rem");
function yn(e3) {
  return Math.round(255 * e3);
}
function bn(e3, t2, n2) {
  return yn(e3) + "," + yn(t2) + "," + yn(n2);
}
function xn(e3, t2, n2, o3) {
  if (o3 === undefined && (o3 = bn), t2 === 0)
    return o3(n2, n2, n2);
  var i3 = (e3 % 360 + 360) % 360 / 60, r3 = (1 - Math.abs(2 * n2 - 1)) * t2, s2 = r3 * (1 - Math.abs(i3 % 2 - 1)), a3 = 0, c3 = 0, l3 = 0;
  i3 >= 0 && i3 < 1 ? (a3 = r3, c3 = s2) : i3 >= 1 && i3 < 2 ? (a3 = s2, c3 = r3) : i3 >= 2 && i3 < 3 ? (c3 = r3, l3 = s2) : i3 >= 3 && i3 < 4 ? (c3 = s2, l3 = r3) : i3 >= 4 && i3 < 5 ? (a3 = s2, l3 = r3) : i3 >= 5 && i3 < 6 && (a3 = r3, l3 = s2);
  var h2 = n2 - r3 / 2;
  return o3(a3 + h2, c3 + h2, l3 + h2);
}
var vn = { aliceblue: "f0f8ff", antiquewhite: "faebd7", aqua: "00ffff", aquamarine: "7fffd4", azure: "f0ffff", beige: "f5f5dc", bisque: "ffe4c4", black: "000", blanchedalmond: "ffebcd", blue: "0000ff", blueviolet: "8a2be2", brown: "a52a2a", burlywood: "deb887", cadetblue: "5f9ea0", chartreuse: "7fff00", chocolate: "d2691e", coral: "ff7f50", cornflowerblue: "6495ed", cornsilk: "fff8dc", crimson: "dc143c", cyan: "00ffff", darkblue: "00008b", darkcyan: "008b8b", darkgoldenrod: "b8860b", darkgray: "a9a9a9", darkgreen: "006400", darkgrey: "a9a9a9", darkkhaki: "bdb76b", darkmagenta: "8b008b", darkolivegreen: "556b2f", darkorange: "ff8c00", darkorchid: "9932cc", darkred: "8b0000", darksalmon: "e9967a", darkseagreen: "8fbc8f", darkslateblue: "483d8b", darkslategray: "2f4f4f", darkslategrey: "2f4f4f", darkturquoise: "00ced1", darkviolet: "9400d3", deeppink: "ff1493", deepskyblue: "00bfff", dimgray: "696969", dimgrey: "696969", dodgerblue: "1e90ff", firebrick: "b22222", floralwhite: "fffaf0", forestgreen: "228b22", fuchsia: "ff00ff", gainsboro: "dcdcdc", ghostwhite: "f8f8ff", gold: "ffd700", goldenrod: "daa520", gray: "808080", green: "008000", greenyellow: "adff2f", grey: "808080", honeydew: "f0fff0", hotpink: "ff69b4", indianred: "cd5c5c", indigo: "4b0082", ivory: "fffff0", khaki: "f0e68c", lavender: "e6e6fa", lavenderblush: "fff0f5", lawngreen: "7cfc00", lemonchiffon: "fffacd", lightblue: "add8e6", lightcoral: "f08080", lightcyan: "e0ffff", lightgoldenrodyellow: "fafad2", lightgray: "d3d3d3", lightgreen: "90ee90", lightgrey: "d3d3d3", lightpink: "ffb6c1", lightsalmon: "ffa07a", lightseagreen: "20b2aa", lightskyblue: "87cefa", lightslategray: "789", lightslategrey: "789", lightsteelblue: "b0c4de", lightyellow: "ffffe0", lime: "0f0", limegreen: "32cd32", linen: "faf0e6", magenta: "f0f", maroon: "800000", mediumaquamarine: "66cdaa", mediumblue: "0000cd", mediumorchid: "ba55d3", mediumpurple: "9370db", mediumseagreen: "3cb371", mediumslateblue: "7b68ee", mediumspringgreen: "00fa9a", mediumturquoise: "48d1cc", mediumvioletred: "c71585", midnightblue: "191970", mintcream: "f5fffa", mistyrose: "ffe4e1", moccasin: "ffe4b5", navajowhite: "ffdead", navy: "000080", oldlace: "fdf5e6", olive: "808000", olivedrab: "6b8e23", orange: "ffa500", orangered: "ff4500", orchid: "da70d6", palegoldenrod: "eee8aa", palegreen: "98fb98", paleturquoise: "afeeee", palevioletred: "db7093", papayawhip: "ffefd5", peachpuff: "ffdab9", peru: "cd853f", pink: "ffc0cb", plum: "dda0dd", powderblue: "b0e0e6", purple: "800080", rebeccapurple: "639", red: "f00", rosybrown: "bc8f8f", royalblue: "4169e1", saddlebrown: "8b4513", salmon: "fa8072", sandybrown: "f4a460", seagreen: "2e8b57", seashell: "fff5ee", sienna: "a0522d", silver: "c0c0c0", skyblue: "87ceeb", slateblue: "6a5acd", slategray: "708090", slategrey: "708090", snow: "fffafa", springgreen: "00ff7f", steelblue: "4682b4", tan: "d2b48c", teal: "008080", thistle: "d8bfd8", tomato: "ff6347", turquoise: "40e0d0", violet: "ee82ee", wheat: "f5deb3", white: "fff", whitesmoke: "f5f5f5", yellow: "ff0", yellowgreen: "9acd32" };
var In = /^#[a-fA-F0-9]{6}$/;
var Sn = /^#[a-fA-F0-9]{8}$/;
var Cn = /^#[a-fA-F0-9]{3}$/;
var Pn = /^#[a-fA-F0-9]{4}$/;
var Mn = /^rgb\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*\)$/i;
var wn = /^rgb(?:a)?\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i;
var Nn = /^hsl\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i;
var Rn = /^hsl(?:a)?\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i;
function Tn(e3) {
  if (typeof e3 != "string")
    throw new pn(3);
  var t2 = function(e4) {
    if (typeof e4 != "string")
      return e4;
    var t3 = e4.toLowerCase();
    return vn[t3] ? "#" + vn[t3] : e4;
  }(e3);
  if (t2.match(In))
    return { red: parseInt("" + t2[1] + t2[2], 16), green: parseInt("" + t2[3] + t2[4], 16), blue: parseInt("" + t2[5] + t2[6], 16) };
  if (t2.match(Sn)) {
    var n2 = parseFloat((parseInt("" + t2[7] + t2[8], 16) / 255).toFixed(2));
    return { red: parseInt("" + t2[1] + t2[2], 16), green: parseInt("" + t2[3] + t2[4], 16), blue: parseInt("" + t2[5] + t2[6], 16), alpha: n2 };
  }
  if (t2.match(Cn))
    return { red: parseInt("" + t2[1] + t2[1], 16), green: parseInt("" + t2[2] + t2[2], 16), blue: parseInt("" + t2[3] + t2[3], 16) };
  if (t2.match(Pn)) {
    var o3 = parseFloat((parseInt("" + t2[4] + t2[4], 16) / 255).toFixed(2));
    return { red: parseInt("" + t2[1] + t2[1], 16), green: parseInt("" + t2[2] + t2[2], 16), blue: parseInt("" + t2[3] + t2[3], 16), alpha: o3 };
  }
  var i3 = Mn.exec(t2);
  if (i3)
    return { red: parseInt("" + i3[1], 10), green: parseInt("" + i3[2], 10), blue: parseInt("" + i3[3], 10) };
  var r3 = wn.exec(t2.substring(0, 50));
  if (r3)
    return { red: parseInt("" + r3[1], 10), green: parseInt("" + r3[2], 10), blue: parseInt("" + r3[3], 10), alpha: parseFloat("" + r3[4]) > 1 ? parseFloat("" + r3[4]) / 100 : parseFloat("" + r3[4]) };
  var s2 = Nn.exec(t2);
  if (s2) {
    var a3 = "rgb(" + xn(parseInt("" + s2[1], 10), parseInt("" + s2[2], 10) / 100, parseInt("" + s2[3], 10) / 100) + ")", c3 = Mn.exec(a3);
    if (!c3)
      throw new pn(4, t2, a3);
    return { red: parseInt("" + c3[1], 10), green: parseInt("" + c3[2], 10), blue: parseInt("" + c3[3], 10) };
  }
  var l3 = Rn.exec(t2.substring(0, 50));
  if (l3) {
    var h2 = "rgb(" + xn(parseInt("" + l3[1], 10), parseInt("" + l3[2], 10) / 100, parseInt("" + l3[3], 10) / 100) + ")", d2 = Mn.exec(h2);
    if (!d2)
      throw new pn(4, t2, h2);
    return { red: parseInt("" + d2[1], 10), green: parseInt("" + d2[2], 10), blue: parseInt("" + d2[3], 10), alpha: parseFloat("" + l3[4]) > 1 ? parseFloat("" + l3[4]) / 100 : parseFloat("" + l3[4]) };
  }
  throw new pn(5);
}
function En(e3) {
  return function(e4) {
    var t2, n2 = e4.red / 255, o3 = e4.green / 255, i3 = e4.blue / 255, r3 = Math.max(n2, o3, i3), s2 = Math.min(n2, o3, i3), a3 = (r3 + s2) / 2;
    if (r3 === s2)
      return e4.alpha !== undefined ? { hue: 0, saturation: 0, lightness: a3, alpha: e4.alpha } : { hue: 0, saturation: 0, lightness: a3 };
    var c3 = r3 - s2, l3 = a3 > 0.5 ? c3 / (2 - r3 - s2) : c3 / (r3 + s2);
    switch (r3) {
      case n2:
        t2 = (o3 - i3) / c3 + (o3 < i3 ? 6 : 0);
        break;
      case o3:
        t2 = (i3 - n2) / c3 + 2;
        break;
      default:
        t2 = (n2 - o3) / c3 + 4;
    }
    return t2 *= 60, e4.alpha !== undefined ? { hue: t2, saturation: l3, lightness: a3, alpha: e4.alpha } : { hue: t2, saturation: l3, lightness: a3 };
  }(Tn(e3));
}
var An = function(e3) {
  return e3.length === 7 && e3[1] === e3[2] && e3[3] === e3[4] && e3[5] === e3[6] ? "#" + e3[1] + e3[3] + e3[5] : e3;
};
function On(e3) {
  var t2 = e3.toString(16);
  return t2.length === 1 ? "0" + t2 : t2;
}
function kn(e3) {
  return On(Math.round(255 * e3));
}
function Dn(e3, t2, n2) {
  return An("#" + kn(e3) + kn(t2) + kn(n2));
}
function Ln(e3, t2, n2) {
  return xn(e3, t2, n2, Dn);
}
function zn(e3, t2, n2) {
  if (typeof e3 == "number" && typeof t2 == "number" && typeof n2 == "number")
    return An("#" + On(e3) + On(t2) + On(n2));
  if (typeof e3 == "object" && t2 === undefined && n2 === undefined)
    return An("#" + On(e3.red) + On(e3.green) + On(e3.blue));
  throw new pn(6);
}
function Bn(e3, t2, n2, o3) {
  if (typeof e3 == "string" && typeof t2 == "number") {
    var i3 = Tn(e3);
    return "rgba(" + i3.red + "," + i3.green + "," + i3.blue + "," + t2 + ")";
  }
  if (typeof e3 == "number" && typeof t2 == "number" && typeof n2 == "number" && typeof o3 == "number")
    return o3 >= 1 ? zn(e3, t2, n2) : "rgba(" + e3 + "," + t2 + "," + n2 + "," + o3 + ")";
  if (typeof e3 == "object" && t2 === undefined && n2 === undefined && o3 === undefined)
    return e3.alpha >= 1 ? zn(e3.red, e3.green, e3.blue) : "rgba(" + e3.red + "," + e3.green + "," + e3.blue + "," + e3.alpha + ")";
  throw new pn(7);
}
function Fn(e3) {
  if (typeof e3 != "object")
    throw new pn(8);
  if (function(e4) {
    return typeof e4.red == "number" && typeof e4.green == "number" && typeof e4.blue == "number" && typeof e4.alpha == "number";
  }(e3))
    return Bn(e3);
  if (function(e4) {
    return typeof e4.red == "number" && typeof e4.green == "number" && typeof e4.blue == "number" && (typeof e4.alpha != "number" || e4.alpha === undefined);
  }(e3))
    return zn(e3);
  if (function(e4) {
    return typeof e4.hue == "number" && typeof e4.saturation == "number" && typeof e4.lightness == "number" && typeof e4.alpha == "number";
  }(e3))
    return function(e4, t2, n2, o3) {
      if (typeof e4 == "number" && typeof t2 == "number" && typeof n2 == "number" && typeof o3 == "number")
        return o3 >= 1 ? Ln(e4, t2, n2) : "rgba(" + xn(e4, t2, n2) + "," + o3 + ")";
      if (typeof e4 == "object" && t2 === undefined && n2 === undefined && o3 === undefined)
        return e4.alpha >= 1 ? Ln(e4.hue, e4.saturation, e4.lightness) : "rgba(" + xn(e4.hue, e4.saturation, e4.lightness) + "," + e4.alpha + ")";
      throw new pn(2);
    }(e3);
  if (function(e4) {
    return typeof e4.hue == "number" && typeof e4.saturation == "number" && typeof e4.lightness == "number" && (typeof e4.alpha != "number" || e4.alpha === undefined);
  }(e3))
    return function(e4, t2, n2) {
      if (typeof e4 == "number" && typeof t2 == "number" && typeof n2 == "number")
        return Ln(e4, t2, n2);
      if (typeof e4 == "object" && t2 === undefined && n2 === undefined)
        return Ln(e4.hue, e4.saturation, e4.lightness);
      throw new pn(1);
    }(e3);
  throw new pn(8);
}
function jn(e3, t2, n2) {
  return function() {
    var o3 = n2.concat(Array.prototype.slice.call(arguments));
    return o3.length >= t2 ? e3.apply(this, o3) : jn(e3, t2, o3);
  };
}
function $n(e3) {
  return jn(e3, e3.length, []);
}
$n(function(e3, t2) {
  if (t2 === "transparent")
    return t2;
  var n2 = En(t2);
  return Fn(sn({}, n2, { hue: n2.hue + parseFloat(e3) }));
});
function Yn(e3, t2, n2) {
  return Math.max(e3, Math.min(t2, n2));
}
$n(function(e3, t2) {
  if (t2 === "transparent")
    return t2;
  var n2 = En(t2);
  return Fn(sn({}, n2, { lightness: Yn(0, 1, n2.lightness - parseFloat(e3)) }));
});
$n(function(e3, t2) {
  if (t2 === "transparent")
    return t2;
  var n2 = En(t2);
  return Fn(sn({}, n2, { saturation: Yn(0, 1, n2.saturation - parseFloat(e3)) }));
});
$n(function(e3, t2) {
  if (t2 === "transparent")
    return t2;
  var n2 = En(t2);
  return Fn(sn({}, n2, { lightness: Yn(0, 1, n2.lightness + parseFloat(e3)) }));
});
var Xn = $n(function(e3, t2, n2) {
  if (t2 === "transparent")
    return n2;
  if (n2 === "transparent")
    return t2;
  if (e3 === 0)
    return n2;
  var o3 = Tn(t2), i3 = sn({}, o3, { alpha: typeof o3.alpha == "number" ? o3.alpha : 1 }), r3 = Tn(n2), s2 = sn({}, r3, { alpha: typeof r3.alpha == "number" ? r3.alpha : 1 }), a3 = i3.alpha - s2.alpha, c3 = 2 * parseFloat(e3) - 1, l3 = ((c3 * a3 === -1 ? c3 : c3 + a3) / (1 + c3 * a3) + 1) / 2, h2 = 1 - l3;
  return Bn({ red: Math.floor(i3.red * l3 + s2.red * h2), green: Math.floor(i3.green * l3 + s2.green * h2), blue: Math.floor(i3.blue * l3 + s2.blue * h2), alpha: i3.alpha * parseFloat(e3) + s2.alpha * (1 - parseFloat(e3)) });
});
$n(function(e3, t2) {
  if (t2 === "transparent")
    return t2;
  var n2 = Tn(t2);
  return Bn(sn({}, n2, { alpha: Yn(0, 1, (100 * (typeof n2.alpha == "number" ? n2.alpha : 1) + 100 * parseFloat(e3)) / 100) }));
});
$n(function(e3, t2) {
  if (t2 === "transparent")
    return t2;
  var n2 = En(t2);
  return Fn(sn({}, n2, { saturation: Yn(0, 1, n2.saturation + parseFloat(e3)) }));
});
$n(function(e3, t2) {
  return t2 === "transparent" ? t2 : Fn(sn({}, En(t2), { hue: parseFloat(e3) }));
});
$n(function(e3, t2) {
  return t2 === "transparent" ? t2 : Fn(sn({}, En(t2), { lightness: parseFloat(e3) }));
});
$n(function(e3, t2) {
  return t2 === "transparent" ? t2 : Fn(sn({}, En(t2), { saturation: parseFloat(e3) }));
});
$n(function(e3, t2) {
  return t2 === "transparent" ? t2 : Xn(parseFloat(e3), "rgb(0, 0, 0)", t2);
});
$n(function(e3, t2) {
  return t2 === "transparent" ? t2 : Xn(parseFloat(e3), "rgb(255, 255, 255)", t2);
});
var Hn = $n(function(e3, t2) {
  if (t2 === "transparent")
    return t2;
  var n2 = Tn(t2);
  return Bn(sn({}, n2, { alpha: Yn(0, 1, +(100 * (typeof n2.alpha == "number" ? n2.alpha : 1) - 100 * parseFloat(e3)).toFixed(2) / 100) }));
});
var Vn = { 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" };
var Wn = {};
for (const e3 in Vn) {
  Wn[e3] = [];
  const t2 = Vn[e3].split("M").slice(1).map((e4) => e4.split("L").map((e5) => e5.trim().split(" ").map(parseFloat)));
  for (const n2 of t2)
    for (let t3 = 0;t3 < n2.length - 1; t3++)
      Wn[e3].push({ x1: n2[t3][0], y1: 1 - n2[t3][1], x2: n2[t3 + 1][0], y2: 1 - n2[t3 + 1][1] });
}
var Gn = (e3, t2) => ({ ...e3, rects: [...e3.rects ?? [], ...t2.rects ?? []], points: [...e3.points ?? [], ...t2.points ?? []], lines: [...e3.lines ?? [], ...t2.lines ?? []], infiniteLines: [...e3.infiniteLines ?? [], ...t2.infiniteLines ?? []], polygons: [...e3.polygons ?? [], ...t2.polygons ?? []], circles: [...e3.circles ?? [], ...t2.circles ?? []], arrows: [...e3.arrows ?? [], ...t2.arrows ?? []], texts: [...e3.texts ?? [], ...t2.texts ?? []] });
var Un = (e3) => {
  const { srj: t2, clearance: n2 } = e3, o3 = n2 ?? 0;
  if (o3 <= 0)
    return { title: "Obstacle Clearance", coordinateSystem: "cartesian", rects: [] };
  const i3 = [];
  for (const e4 of t2.obstacles ?? []) {
    if (e4.type !== "rect" && e4.type !== "oval")
      continue;
    const t3 = { x: e4.center.x - e4.width / 2 - o3, y: e4.center.y - e4.height / 2 - o3, width: e4.width + 2 * o3, height: e4.height + 2 * o3 };
    i3.push({ center: { x: t3.x + t3.width / 2, y: t3.y + t3.height / 2 }, width: t3.width, height: t3.height, stroke: "rgba(202, 138, 4, 0.9)", fill: "rgba(234, 179, 8, 0.15)", layer: "obstacle-clearance", label: `clearance
z:${(e4.zLayers ?? []).join(",") || "all"}` });
  }
  return { title: "Obstacle Clearance", coordinateSystem: "cartesian", rects: i3 };
};
function Zn(e3) {
  const t2 = Array.from(e3).sort((e4, t3) => e4 - t3), n2 = [];
  for (const e4 of t2) {
    const t3 = n2.at(-1);
    (t3 === undefined || e4 - t3 > We) && n2.push(e4);
  }
  return n2;
}
function qn(e3, t2, n2 = {}) {
  if (!t2 || t2.length < 3)
    return [];
  const o3 = t2.length > 120, i3 = o3 ? function(e4, t3) {
    const n3 = (e5) => Math.round(e5 / t3) * t3, o4 = new Set, i4 = [];
    for (const t4 of e4) {
      const e5 = n3(t4.x), r4 = n3(t4.y), s3 = `${e5},${r4}`;
      o4.has(s3) || (o4.add(s3), i4.push({ x: e5, y: r4 }));
    }
    return i4;
  }(t2, Math.max(e3.width, e3.height) / 120) : t2, r3 = new Set([e3.x, e3.x + e3.width]), s2 = new Set([e3.y, e3.y + e3.height]);
  for (const e4 of i3)
    r3.add(e4.x), s2.add(e4.y);
  (function({ polygon: e4, xs: t3, ys: n3, minGridSize: o4 }) {
    const i4 = [];
    let r4 = 0;
    for (let t4 = 0;t4 < e4.length; t4++) {
      const n4 = e4[t4], o5 = e4[(t4 + 1) % e4.length], s4 = Math.abs(o5.x - n4.x), a4 = Math.abs(o5.y - n4.y);
      if (s4 <= We || a4 <= We)
        continue;
      const c4 = Math.max(s4, a4);
      i4.push({ start: n4, end: o5, span: c4 }), r4 += c4;
    }
    if (i4.length === 0)
      return;
    const s3 = Math.max(o4, r4 / 256);
    for (const { start: e5, end: o5, span: r5 } of i4) {
      const i5 = Math.max(1, Math.ceil(r5 / s3));
      for (let r6 = 1;r6 < i5; r6++) {
        const s4 = r6 / i5;
        t3.add(e5.x + (o5.x - e5.x) * s4), n3.add(e5.y + (o5.y - e5.y) * s4);
      }
    }
  })({ polygon: i3, xs: r3, ys: s2, minGridSize: Math.max(We, n2.minGridSize ?? Math.max(e3.width, e3.height) / 256) });
  const a3 = Zn(r3), c3 = Zn(s2), l3 = [];
  for (let n3 = 0;n3 < a3.length - 1; n3++)
    for (let i4 = 0;i4 < c3.length - 1; i4++) {
      const r4 = a3[n3], s3 = a3[n3 + 1], h3 = c3[i4], d3 = c3[i4 + 1], u3 = (r4 + s3) / 2, p3 = (h3 + d3) / 2;
      if (u3 >= e3.x && u3 <= e3.x + e3.width && p3 >= e3.y && p3 <= e3.y + e3.height) {
        (o3 ? [{ x: u3, y: p3 }] : [{ x: u3, y: p3 }, { x: r4, y: h3 }, { x: s3, y: h3 }, { x: r4, y: d3 }, { x: s3, y: d3 }]).every((e4) => ve(e4, t2)) || l3.push({ x: r4, y: h3, width: s3 - r4, height: d3 - h3 });
      }
    }
  const h2 = [];
  l3.sort((e4, t3) => Math.abs(e4.y - t3.y) > We ? e4.y - t3.y : e4.x - t3.x);
  let d2 = null;
  for (const e4 of l3) {
    if (!d2) {
      d2 = e4;
      continue;
    }
    const t3 = Math.abs(d2.y - e4.y) < We, n3 = Math.abs(d2.height - e4.height) < We, o4 = Math.abs(d2.x + d2.width - e4.x) < We;
    t3 && n3 && o4 ? d2.width += e4.width : (h2.push(d2), d2 = e4);
  }
  d2 && h2.push(d2), h2.sort((e4, t3) => Math.abs(e4.x - t3.x) > We ? e4.x - t3.x : e4.y - t3.y);
  const u2 = [];
  d2 = null;
  for (const e4 of h2) {
    if (!d2) {
      d2 = e4;
      continue;
    }
    const t3 = Math.abs(d2.x - e4.x) < We, n3 = Math.abs(d2.width - e4.width) < We, o4 = Math.abs(d2.y + d2.height - e4.y) < We;
    t3 && n3 && o4 ? d2.height += e4.height : (u2.push(d2), d2 = e4);
  }
  return d2 && u2.push(d2), u2;
}
var Jn = class extends BasePipelineSolver {
  rectDiffGridSolverPipeline;
  gapFillSolver;
  outerLayerContainmentMergeSolver;
  boardVoidRects;
  zIndexByName;
  layerNames;
  pipelineDef = [definePipelineStep("rectDiffGridSolverPipeline", Xt, (e3) => [{ bounds: e3.inputProblem.simpleRouteJson.bounds, obstacles: e3.inputProblem.simpleRouteJson.obstacles, connections: e3.inputProblem.simpleRouteJson.connections, outline: e3.inputProblem.simpleRouteJson.outline ? { outline: e3.inputProblem.simpleRouteJson.outline } : undefined, layerCount: e3.inputProblem.simpleRouteJson.layerCount, gridOptions: e3.inputProblem.gridOptions, boardVoidRects: e3.boardVoidRects, layerNames: e3.layerNames, zIndexByName: e3.zIndexByName, minTraceWidth: e3.inputProblem.simpleRouteJson.minTraceWidth, obstacleClearance: e3.inputProblem.obstacleClearance }]), definePipelineStep("gapFillSolver", Fe, (e3) => [{ meshNodes: e3.rectDiffGridSolverPipeline?.getOutput().meshNodes ?? [], bounds: e3.inputProblem.simpleRouteJson.bounds, boardVoid: { boardVoidRects: e3.boardVoidRects || [], layerCount: e3.inputProblem.simpleRouteJson.layerCount || 0 }, maxGapFillPasses: e3.inputProblem.maxGapFillPasses }]), definePipelineStep("outerLayerContainmentMergeSolver", dt, (e3) => [{ meshNodes: e3.gapFillSolver?.getOutput().outputNodes ?? e3.rectDiffGridSolverPipeline?.getOutput().meshNodes ?? [], simpleRouteJson: e3.inputProblem.simpleRouteJson, zIndexByName: e3.zIndexByName ?? new Map, obstacleClearance: e3.inputProblem.obstacleClearance }])];
  _setup() {
    const { zIndexByName: e3, layerNames: t2 } = Ye({ obstacles: this.inputProblem.simpleRouteJson.obstacles, layerCount: this.inputProblem.simpleRouteJson.layerCount });
    if (this.zIndexByName = e3, this.layerNames = t2, this.inputProblem.simpleRouteJson.outline) {
      const e4 = Math.max(0, this.inputProblem.simpleRouteJson.minBoardEdgeClearance ?? 0);
      this.boardVoidRects = qn({ x: this.inputProblem.simpleRouteJson.bounds.minX - e4, y: this.inputProblem.simpleRouteJson.bounds.minY - e4, width: this.inputProblem.simpleRouteJson.bounds.maxX - this.inputProblem.simpleRouteJson.bounds.minX + 2 * e4, height: this.inputProblem.simpleRouteJson.bounds.maxY - this.inputProblem.simpleRouteJson.bounds.minY + 2 * e4 }, this.inputProblem.simpleRouteJson.outline ?? [], { minGridSize: this.inputProblem.simpleRouteJson.minTraceWidth }).map((t3) => tt(t3, e4));
    }
  }
  getConstructorParams() {
    return [this.inputProblem];
  }
  getOutput() {
    const e3 = this.outerLayerContainmentMergeSolver?.getOutput();
    if (e3)
      return { meshNodes: e3.outputNodes };
    const t2 = this.gapFillSolver?.getOutput();
    return t2 ? { meshNodes: t2.outputNodes } : this.rectDiffGridSolverPipeline ? this.rectDiffGridSolverPipeline.getOutput() : { meshNodes: [] };
  }
  initialVisualize() {
    const e3 = function(e4, t3 = "RectDiff") {
      const n3 = [], o3 = [], i3 = e4.bounds.minX, r3 = e4.bounds.maxX, s2 = e4.bounds.minY, a3 = e4.bounds.maxY;
      e4.outline && e4.outline.length > 1 ? o3.push({ points: [...e4.outline, e4.outline[0]], strokeColor: "#111827", strokeWidth: 0.01, label: "outline" }) : n3.push({ center: { x: (i3 + r3) / 2, y: (s2 + a3) / 2 }, width: r3 - i3, height: a3 - s2, fill: "none", stroke: "#111827", label: "board" });
      for (const t4 of e4.obstacles ?? [])
        if (t4.type === "rect" || t4.type === "oval") {
          const e5 = (t4.zLayers ?? []).join(",") || "all";
          n3.push({ center: { x: t4.center.x, y: t4.center.y }, width: t4.width, height: t4.height, fill: "#fee2e2", stroke: "#ef4444", layer: "obstacle", label: `obstacle
z:${e5}` });
        }
      return { title: t3, coordinateSystem: "cartesian", rects: n3, points: [], lines: o3 };
    }(this.inputProblem.simpleRouteJson, "RectDiffPipeline - Initial"), t2 = Un({ srj: this.inputProblem.simpleRouteJson, clearance: this.inputProblem.obstacleClearance }), n2 = { title: "Initial Nodes", coordinateSystem: "cartesian", rects: (this.rectDiffGridSolverPipeline?.getOutput().meshNodes ?? []).map((e4) => ({ center: e4.center, width: e4.width, height: e4.height, stroke: "rgba(0, 0, 0, 0.3)", fill: "rgba(100, 100, 100, 0.1)", layer: `z${e4.availableZ.join(",")}`, label: [`node ${e4.capacityMeshNodeId}`, `z:${e4.availableZ.join(",")}`].join(`
`) })) };
    return Gn(Gn(e3, t2), n2);
  }
  finalVisualize() {
    return (({ srj: e3, meshNodes: t2, obstacleClearance: n2 }) => {
      const o3 = (({ srj: e4 }) => ({ title: "SimpleRoute Outline", coordinateSystem: "cartesian", lines: e4.outline && e4.outline.length > 1 ? [{ points: [...e4.outline, e4.outline[0]], strokeColor: "#111827", strokeWidth: 0.1, label: "outline" }] : [{ points: [{ x: e4.bounds.minX, y: e4.bounds.minY }, { x: e4.bounds.maxX, y: e4.bounds.minY }, { x: e4.bounds.maxX, y: e4.bounds.maxY }, { x: e4.bounds.minX, y: e4.bounds.maxY }, { x: e4.bounds.minX, y: e4.bounds.minY }], strokeColor: "#111827", strokeWidth: 0.1, label: "bounds" }] }))({ srj: e3 }), i3 = Un({ srj: e3, clearance: n2 }), r3 = t2.map((e4) => ({ center: e4.center, width: e4.width, height: e4.height, stroke: Ve(e4.availableZ).stroke, fill: e4._containsObstacle ? "#fca5a5" : Ve(e4.availableZ).fill, layer: `z${e4.availableZ.join(",")}`, label: `node ${e4.capacityMeshNodeId}
z:${e4.availableZ.join(",")}` }));
      return Gn(Gn({ title: "RectDiffPipeline - Final", coordinateSystem: "cartesian", rects: r3, lines: [], points: [], texts: [] }, o3), i3);
    })({ srj: this.inputProblem.simpleRouteJson, meshNodes: this.getOutput().meshNodes, obstacleClearance: this.inputProblem.obstacleClearance });
  }
};
var Qn = class {
  cacheHitsByPrefix = {};
  cacheMissesByPrefix = {};
  isSyncCache = true;
  cacheHits = 0;
  cacheMisses = 0;
  cache = new Map;
  getCachedSolutionSync(e3) {
    const t2 = this.cache.get(e3);
    if (t2 !== undefined) {
      this.cacheHits++;
      const n2 = e3.split(":")[0];
      return this.cacheHitsByPrefix[n2] = (this.cacheHitsByPrefix[n2] || 0) + 1, structuredClone(t2);
    }
    {
      this.cacheMisses++;
      const t3 = e3.split(":")[0];
      return void (this.cacheMissesByPrefix[t3] = (this.cacheMissesByPrefix[t3] || 0) + 1);
    }
  }
  async getCachedSolution(e3) {
    return this.getCachedSolutionSync(e3);
  }
  setCachedSolutionSync(e3, t2) {
    this.cache.set(e3, structuredClone(t2));
  }
  async setCachedSolution(e3, t2) {
    this.setCachedSolutionSync(e3, t2);
  }
  clearCache() {
    this.cache.clear(), this.cacheHits = 0, this.cacheMisses = 0, this.cacheHitsByPrefix = {}, this.cacheMissesByPrefix = {};
  }
  getAllCacheKeys() {
    return Array.from(this.cache.keys());
  }
};
var Kn = "tscircuit_autorouter_cache_";
var eo = class {
  isSyncCache = true;
  cacheHits = 0;
  cacheMisses = 0;
  cacheHitsByPrefix = {};
  cacheMissesByPrefix = {};
  constructor() {}
  getKey(e3) {
    return `${Kn}${e3}`;
  }
  getCachedSolutionSync(e3) {
    if (typeof localStorage == "undefined")
      return;
    const t2 = this.getKey(e3);
    try {
      const n2 = localStorage.getItem(t2);
      if (n2 !== null) {
        const t3 = JSON.parse(n2);
        this.cacheHits++;
        const o3 = e3.split(":")[0];
        return this.cacheHitsByPrefix[o3] = (this.cacheHitsByPrefix[o3] || 0) + 1, t3;
      }
      {
        this.cacheMisses++;
        const t3 = e3.split(":")[0];
        return void (this.cacheMissesByPrefix[t3] = (this.cacheMissesByPrefix[t3] || 0) + 1);
      }
    } catch (n2) {
      console.error(`Error getting cached solution sync for ${t2}:`, n2), this.cacheMisses++;
      const o3 = e3.split(":")[0];
      return void (this.cacheMissesByPrefix[o3] = (this.cacheMissesByPrefix[o3] || 0) + 1);
    }
  }
  async getCachedSolution(e3) {
    return this.getCachedSolutionSync(e3);
  }
  setCachedSolutionSync(e3, t2) {
    if (typeof localStorage == "undefined")
      return;
    const n2 = this.getKey(e3);
    try {
      const e4 = JSON.stringify(t2);
      localStorage.setItem(n2, e4);
    } catch (e4) {
      console.error(`Error setting cached solution sync for ${n2}:`, e4), e4 instanceof DOMException && (e4.name === "QuotaExceededError" || e4.name === "NS_ERROR_DOM_QUOTA_REACHED") && console.warn(`LocalStorage quota exceeded. Failed to cache solution for ${n2}. Consider clearing the cache.`);
    }
  }
  async setCachedSolution(e3, t2) {
    this.setCachedSolutionSync(e3, t2);
  }
  clearCache() {
    if (typeof localStorage != "undefined")
      try {
        const e3 = [];
        for (let t2 = 0;t2 < localStorage.length; t2++) {
          const n2 = localStorage.key(t2);
          n2?.startsWith(Kn) && e3.push(n2);
        }
        e3.forEach((e4) => localStorage.removeItem(e4)), console.log(`Cleared ${e3.length} items from LocalStorage cache.`);
      } catch (e3) {
        console.error("Error clearing LocalStorage cache:", e3);
      } finally {
        this.cacheHits = 0, this.cacheMisses = 0, this.cacheHitsByPrefix = {}, this.cacheMissesByPrefix = {};
      }
  }
  getAllCacheKeys() {
    const e3 = [];
    for (let t2 = 0;t2 < 1e4; t2++) {
      const n2 = localStorage.key(t2);
      if (!n2)
        break;
      n2.includes(Kn) && e3.push(n2);
    }
    return e3;
  }
};
function to() {
  return globalThis.TSCIRCUIT_AUTOROUTER_LOCAL_STORAGE_CACHE || oo(), globalThis.TSCIRCUIT_AUTOROUTER_LOCAL_STORAGE_CACHE;
}
function no() {
  return globalThis.TSCIRCUIT_AUTOROUTER_IN_MEMORY_CACHE || oo(), globalThis.TSCIRCUIT_AUTOROUTER_IN_MEMORY_CACHE;
}
function oo() {
  globalThis.TSCIRCUIT_AUTOROUTER_LOCAL_STORAGE_CACHE ??= new eo, globalThis.TSCIRCUIT_AUTOROUTER_IN_MEMORY_CACHE ??= new Qn;
}
function ro(e3) {
  const t2 = { minX: e3.center.x - e3.width / 2, maxX: e3.center.x + e3.width / 2, minY: e3.center.y - e3.height / 2, maxY: e3.center.y + e3.height / 2 };
  for (const n2 of e3.portPoints)
    n2.x < t2.minX && (t2.minX = n2.x), n2.x > t2.maxX && (t2.maxX = n2.x), n2.y < t2.minY && (t2.minY = n2.y), n2.y > t2.maxY && (t2.maxY = n2.y);
  return t2;
}
var so = (e3, t2) => e3 <= t2 ? [e3, t2] : [t2, e3];
var ao = (e3) => `${e3[0]}|${e3[1]}`;
var co = ({ portPointId: e3, currentNodeId: t2, inputNodes: n2, connectionNodeIdsByPortPointId: o3 }) => {
  let i3 = e3 ? o3?.get(e3) : undefined;
  if (e3 && !o3)
    for (const t3 of n2) {
      const n3 = t3.portPoints.find((t4) => t4.portPointId === e3);
      if (n3?.connectionNodeIds) {
        i3 = n3.connectionNodeIds;
        break;
      }
    }
  if (!i3 || i3.length !== 2)
    return [t2, t2];
  const [r3, s2] = i3;
  return r3 && s2 ? so(r3, s2) : [t2, t2];
};
var lo = 0.000001;
var ho = (e3, t2) => Math.abs(e3 - t2) <= lo;
var uo = ({ nodeAId: e3, nodeBId: t2, nodeBounds: n2 }) => {
  if (e3 === t2)
    return null;
  const o3 = n2.get(e3), i3 = n2.get(t2);
  if (!o3 || !i3)
    return null;
  const r3 = so(e3, t2), s2 = ao(r3);
  if (ho(o3.maxX, i3.minX) || ho(i3.maxX, o3.minX)) {
    const n3 = Math.max(o3.minY, i3.minY), a3 = Math.min(o3.maxY, i3.maxY), c3 = a3 - n3;
    if (c3 > lo) {
      const l3 = ho(o3.maxX, i3.minX) ? o3.maxX : o3.minX;
      return { ownerNodeIds: r3, ownerPairKey: s2, orientation: "vertical", x1: l3, y1: n3, x2: l3, y2: a3, center: { x: l3, y: (n3 + a3) / 2 }, length: c3, nodeSideByOwnerId: ho(o3.maxX, i3.minX) ? { [e3]: "right", [t2]: "left" } : { [e3]: "left", [t2]: "right" } };
    }
  }
  if (ho(o3.maxY, i3.minY) || ho(i3.maxY, o3.minY)) {
    const n3 = Math.max(o3.minX, i3.minX), a3 = Math.min(o3.maxX, i3.maxX), c3 = a3 - n3;
    if (c3 > lo) {
      const l3 = ho(o3.maxY, i3.minY) ? o3.maxY : o3.minY;
      return { ownerNodeIds: r3, ownerPairKey: s2, orientation: "horizontal", x1: n3, y1: l3, x2: a3, y2: l3, center: { x: (n3 + a3) / 2, y: l3 }, length: c3, nodeSideByOwnerId: ho(o3.maxY, i3.minY) ? { [e3]: "top", [t2]: "bottom" } : { [e3]: "bottom", [t2]: "top" } };
    }
  }
  return null;
};
var po = ({ portPoint: e3, ownerNodeIds: t2, inputNodes: n2 }) => {
  for (const o3 of t2) {
    const t3 = n2.find((e4) => e4.capacityMeshNodeId === o3);
    if (t3?._containsTarget)
      return true;
    const i3 = t3?.portPoints.find((t4) => t4.portPointId === e3.portPointId);
    if (i3?.connectionNodeIds?.some((e4) => n2.find((t4) => t4.capacityMeshNodeId === e4)?._containsTarget))
      return true;
  }
  return false;
};
var mo = (e3, t2) => e3 === "top" ? 0 : e3 === "bottom" ? t2 - 1 : parseInt(e3.slice(5));
function go(e3, t2) {
  return [...new Set(e3)].filter((e4) => Number.isInteger(e4) && e4 >= 0 && e4 < t2).sort((e4, t3) => e4 - t3);
}
function fo(e3, t2) {
  return go(e3.map((e4) => mo(e4, t2)), t2);
}
var _o = 0.000001;
var yo = ({ sharedEdge: e3, obstacles: t2, z: n2, layerCount: o3 }) => {
  for (const i3 of t2) {
    const t3 = i3.zLayers ?? (o3 === undefined ? undefined : i3.layers.map((e4) => mo(e4, o3)));
    if (n2 !== undefined && t3 && !t3.includes(n2))
      continue;
    const r3 = i3.center.x - i3.width / 2, s2 = i3.center.x + i3.width / 2, a3 = i3.center.y - i3.height / 2, c3 = i3.center.y + i3.height / 2;
    if (e3.orientation !== "vertical") {
      if (Math.abs(e3.y1 - a3) < _o || Math.abs(e3.y1 - c3) < _o) {
        const t4 = Math.max(e3.x1, r3);
        if (Math.min(e3.x2, s2) - t4 > _o)
          return true;
      }
    } else if (Math.abs(e3.x1 - r3) < _o || Math.abs(e3.x1 - s2) < _o) {
      const t4 = Math.max(e3.y1, a3);
      if (Math.min(e3.y2, c3) - t4 > _o)
        return true;
    }
  }
  return false;
};
var bo = class extends BaseSolver {
  constructor(e3) {
    super(), this.input = e3;
    for (const t3 of e3.nodeWithPortPoints)
      this.mapOfNodeIdToBounds.set(t3.capacityMeshNodeId, e3.useLayerAwareGeometry ? { minX: t3.center.x - t3.width / 2, maxX: t3.center.x + t3.width / 2, minY: t3.center.y - t3.height / 2, maxY: t3.center.y + t3.height / 2 } : ro(t3));
    const t2 = new Map, n2 = ((e4) => {
      const t3 = new Map;
      for (const n3 of e4) {
        const e5 = new Set;
        for (const o3 of n3.portPoints) {
          const n4 = o3.portPointId;
          n4 && !e5.has(n4) && (e5.add(n4), !t3.has(n4) && o3.connectionNodeIds && t3.set(n4, o3.connectionNodeIds));
        }
      }
      return t3;
    })(e3.inputNodesWithPortPoints);
    for (const o3 of e3.nodeWithPortPoints)
      for (const i3 of o3.portPoints) {
        if (!i3.portPointId)
          continue;
        const r3 = co({ portPointId: i3.portPointId, currentNodeId: o3.capacityMeshNodeId, inputNodes: e3.inputNodesWithPortPoints, connectionNodeIdsByPortPointId: n2 }), s2 = ao(r3), a3 = this.mapOfOwnerPairToPortPoints.get(s2) ?? [];
        a3.some((e4) => e4.portPointId && e4.portPointId === i3.portPointId) || a3.push({ ...i3, ownerNodeIds: r3, ownerPairKey: s2 }), this.mapOfOwnerPairToPortPoints.set(s2, a3), t2.set(s2, r3);
      }
    this.mapOfOwnerPairToSharedEdge = (({ ownerPairs: e4, nodeBounds: t3 }) => {
      const n3 = new Map;
      for (const o3 of e4) {
        const [e5, i3] = o3;
        if (e5 === i3)
          continue;
        const r3 = uo({ nodeAId: e5, nodeBId: i3, nodeBounds: t3 });
        r3 && n3.set(ao(o3), r3);
      }
      return n3;
    })({ ownerPairs: Array.from(t2.values()), nodeBounds: this.mapOfNodeIdToBounds }), this.ownerPairsToProcess = Array.from(this.mapOfOwnerPairToSharedEdge.keys()), this.ownerPairsToProcess.sort((e4, t3) => {
      const n3 = this.mapOfOwnerPairToSharedEdge.get(e4), o3 = this.mapOfOwnerPairToSharedEdge.get(t3);
      return n3.center.x - o3.center.x || n3.center.y - o3.center.y;
    });
  }
  getSolverName() {
    return "UniformPortDistributionSolver";
  }
  mapOfNodeIdToBounds = new Map;
  mapOfOwnerPairToPortPoints = new Map;
  mapOfOwnerPairToSharedEdge = new Map;
  ownerPairsToProcess = [];
  currentOwnerPairBeingProcessed = null;
  redistributedNodes = [];
  step() {
    if (this.ownerPairsToProcess.length === 0)
      return this.rebuildNodes(), void (this.solved = true);
    this.currentOwnerPairBeingProcessed = this.ownerPairsToProcess.shift();
    const e3 = this.currentOwnerPairBeingProcessed, t2 = this.mapOfOwnerPairToSharedEdge.get(e3);
    if (!t2)
      return;
    const n2 = this.mapOfOwnerPairToPortPoints.get(e3) ?? [], o3 = yo({ sharedEdge: t2, obstacles: this.input.obstacles });
    if (!this.input.useLayerAwareGeometry && o3)
      return;
    const i3 = new Map;
    for (const e4 of n2)
      i3.set(e4.z, (i3.get(e4.z) ?? 0) + 1);
    const r3 = [];
    for (const e4 of n2)
      this.input.preserveSolitaryPorts && o3 && i3.get(e4.z) === 1 || yo({ sharedEdge: t2, obstacles: this.input.obstacles, z: this.input.useLayerAwareGeometry ? e4.z : undefined, layerCount: this.input.layerCount }) || po({ portPoint: e4, ownerNodeIds: e4.ownerNodeIds, inputNodes: this.input.inputNodesWithPortPoints }) || r3.push(e4);
    const s2 = (({ sharedEdge: e4, portPoints: t3 }) => {
      if (t3.length === 0)
        return [];
      const n3 = new Map;
      for (const e5 of t3) {
        const t4 = e5.z ?? 0, o5 = n3.get(t4) ?? [];
        o5.push(e5), n3.set(t4, o5);
      }
      const o4 = [], i4 = Array.from(n3.keys()).sort((e5, t4) => e5 - t4);
      for (const t4 of i4) {
        const i5 = n3.get(t4), r4 = i5.length;
        i5.sort((t5, n4) => e4.orientation === "horizontal" ? t5.x - n4.x : t5.y - n4.y);
        for (let t5 = 0;t5 < r4; t5++) {
          const n4 = (2 * t5 + 1) / (2 * r4), s3 = e4.orientation === "horizontal" ? e4.x1 + e4.length * n4 : e4.x1, a3 = e4.orientation === "horizontal" ? e4.y1 : e4.y1 + e4.length * n4;
          o4.push({ ...i5[t5], x: s3, y: a3 });
        }
      }
      return o4;
    })({ sharedEdge: t2, portPoints: r3 });
    this.mapOfOwnerPairToPortPoints.set(e3, s2);
  }
  rebuildNodes() {
    const e3 = new Map;
    for (const t3 of this.mapOfOwnerPairToPortPoints.values())
      for (const n2 of t3)
        n2.portPointId && e3.set(n2.portPointId, { x: n2.x, y: n2.y });
    const t2 = (t3) => {
      if (t3.portPointId && e3.has(t3.portPointId)) {
        const n2 = e3.get(t3.portPointId);
        return { ...t3, x: n2.x, y: n2.y };
      }
      return t3;
    };
    this.redistributedNodes = this.input.nodeWithPortPoints.map((e4) => ({ ...e4, portPoints: e4.portPoints.map(t2), portPointsInPairs: e4.portPointsInPairs?.map(([e5, n2]) => [t2(e5), t2(n2)]) }));
  }
  getOutput = () => this.redistributedNodes;
  visualize() {
    return (({ obstacles: e3, nodeWithPortPoints: t2, mapOfOwnerPairToPortPoints: n2, mapOfOwnerPairToSharedEdge: o3, ownerPairsToProcess: i3, currentOwnerPairBeingProcessed: r3, mapOfNodeIdToBounds: s2 }) => {
      const a3 = e3.filter((e4) => !e4.isCopperPour).map((e4) => ({ ...e4, fill: "#ec000070" })), c3 = [], l3 = [], h2 = new Map, d2 = new Map, u2 = new Map, p3 = (e4) => e4.portPointId ? h2.get(e4.portPointId) ?? { x: e4.x, y: e4.y } : { x: e4.x, y: e4.y };
      for (const e4 of t2)
        for (const t3 of e4.portPoints)
          t3.portPointId && (h2.set(t3.portPointId, { x: t3.x, y: t3.y }), d2.set(t3.portPointId, t3.z ?? 0));
      for (const e4 of n2.values())
        for (const t3 of e4)
          t3.portPointId && (h2.set(t3.portPointId, { x: t3.x, y: t3.y }), d2.set(t3.portPointId, t3.z ?? 0), u2.set(t3.portPointId, `${t3.ownerNodeIds[0]}&${t3.ownerNodeIds[1]}`));
      t2.forEach((e4) => {
        const t3 = s2.get(e4.capacityMeshNodeId);
        if (t3) {
          const n3 = (t3.minX + t3.maxX) / 2, o4 = (t3.minY + t3.maxY) / 2, i4 = t3.maxX - t3.minX, r4 = t3.maxY - t3.minY;
          a3.push({ center: { x: n3, y: o4 }, width: i4, height: r4, fill: "#00000030", label: `${e4.capacityMeshNodeId}` });
        }
        e4.portPoints.forEach((t4) => {
          if (!t4.portPointId)
            return;
          const n3 = h2.get(t4.portPointId), o4 = d2.get(t4.portPointId) ?? 0, i4 = u2.get(t4.portPointId) ?? `${e4.capacityMeshNodeId}&${e4.capacityMeshNodeId}`;
          c3.push({ x: n3.x, y: n3.y, label: `z:${o4}
o:${i4}` }), e4.portPointsInPairs?.length || e4.portPoints.forEach((e5) => {
            if (e5.portPointId && t4 !== e5 && t4.connectionName === e5.connectionName) {
              const t5 = h2.get(e5.portPointId);
              l3.push({ points: [n3, t5], strokeColor: "#fff822c9" });
            }
          });
        }), e4.portPointsInPairs?.forEach(([e5, t4]) => {
          l3.push({ points: [p3(e5), p3(t4)], strokeColor: "#fff822c9" });
        });
      });
      for (const e4 of i3) {
        const t3 = o3.get(e4);
        t3 && l3.push({ points: [{ x: t3.x1, y: t3.y1 }, { x: t3.x2, y: t3.y2 }], strokeColor: "orange", strokeWidth: 0.01 });
      }
      if (r3) {
        const e4 = o3.get(r3);
        e4 && (l3.push({ points: [{ x: e4.x1, y: e4.y1 }, { x: e4.x2, y: e4.y2 }], strokeColor: "red", strokeWidth: 0.03 }), c3.push({ x: e4.center.x, y: e4.center.y, label: e4.ownerPairKey }));
      }
      for (const e4 of o3.values())
        l3.push({ points: [{ x: e4.x1, y: e4.y1 }, { x: e4.x2, y: e4.y2 }], strokeColor: "#33b5ff80", strokeWidth: 0.006 });
      return { rects: a3, lines: l3, points: c3 };
    })({ obstacles: this.input.obstacles, nodeWithPortPoints: this.input.nodeWithPortPoints, mapOfOwnerPairToPortPoints: this.mapOfOwnerPairToPortPoints, mapOfOwnerPairToSharedEdge: this.mapOfOwnerPairToSharedEdge, ownerPairsToProcess: this.ownerPairsToProcess, currentOwnerPairBeingProcessed: this.currentOwnerPairBeingProcessed, mapOfNodeIdToBounds: this.mapOfNodeIdToBounds });
  }
};
var xo = (e3, t2, n2) => e3.connectedTo.some((e4) => e4 === t2.connectionName || e4 === t2.rootConnectionName || (n2?.areIdsConnected(t2.connectionName, e4) ?? false) || t2.rootConnectionName !== undefined && (n2?.areIdsConnected(t2.rootConnectionName, e4) ?? false));
function vo(e3) {
  return !("layers" in e3) && typeof e3.layer == "string";
}
function Io(e3) {
  return So(e3)[0];
}
function So(e3) {
  if (function(e4) {
    return !("layer" in e4) && Array.isArray(e4.layers);
  }(e3))
    return e3.layers;
  if (vo(e3))
    return [e3.layer];
  throw new Error("Connection point must specify either layer or layers, never both");
}
var Co = (e3, t2) => {
  if (e3 === 1 && t2 === 1)
    return "inner1";
  if (e3 < 0 || e3 >= t2)
    throw new Error(`Invalid z "${e3}" for layer count: ${t2}`);
  return e3 === 0 ? "top" : e3 === t2 - 1 ? "bottom" : `inner${e3}`;
};
var Po = (e3, t2) => !!e3 && !!t2 && Math.abs(e3.x - t2.x) <= 0.000000000001 && Math.abs(e3.y - t2.y) <= 0.000000000001;
var Mo = (e3, t2) => Oe(e3, t2) <= 0.000001;
var wo = (e3, t2, n2, o3) => t2.toNextSegmentType === "through_obstacle" || (o3.connectedMultilayerObstacles ? o3.connectedMultilayerObstacles.some((e4) => Mo(t2, e4) && Mo(n2, e4)) : o3.obstacles?.some((i3) => ((e4) => (e4.__zLayers?.length ?? e4.layers?.length ?? 0) > 1)(i3) && Mo(t2, i3) && Mo(n2, i3) && xo(i3, e3, o3.connMap)) ?? false);
var No = ({ endpoint: e3, endpointLayer: t2, connectionPoints: n2, tolerance: o3 }) => {
  let i3;
  for (const r3 of n2) {
    if (!vo(r3) || !r3.terminalVia)
      continue;
    if (r3.layer !== t2)
      continue;
    const n3 = me(r3, e3);
    n3 > o3 || (!i3 || n3 < i3.distance) && (i3 = { point: r3, distance: n3 });
  }
  return i3?.point;
};
var Ro = (e3, t2, n2 = {}) => {
  const o3 = [];
  if (e3.route.length === 0)
    return o3;
  let i3 = [], r3 = e3.route[0].z;
  for (let s3 = 0;s3 < e3.route.length; s3++) {
    const a3 = e3.route[s3];
    if (a3.z !== r3) {
      const s4 = i3[i3.length - 1], c3 = Co(r3, t2);
      for (const t3 of i3)
        o3.push({ route_type: "wire", x: t3.x, y: t3.y, width: t3.traceThickness ?? e3.traceThickness, layer: c3 });
      const l3 = Co(a3.z, t2);
      if (s4 && wo(e3, s4, a3, n2))
        o3.push({ route_type: "through_obstacle", start: { x: s4.x, y: s4.y }, end: { x: a3.x, y: a3.y }, from_layer: c3, to_layer: l3, width: s4.traceThickness ?? e3.traceThickness, ...s4.toNextSegmentCircuitJsonMetadata ? { circuitJsonMetadata: s4.toNextSegmentCircuitJsonMetadata } : {} });
      else {
        e3.vias.some((e4) => Math.abs(e4.x - a3.x) < 0.001 && Math.abs(e4.y - a3.y) < 0.001) && o3.push({ route_type: "via", x: a3.x, y: a3.y, from_layer: c3, to_layer: l3, via_diameter: e3.viaDiameter, ...n2.defaultViaHoleDiameter !== undefined ? { via_hole_diameter: n2.defaultViaHoleDiameter } : {} });
      }
      i3 = [a3], r3 = a3.z;
    } else
      Po(i3[i3.length - 1], a3) || i3.push(a3);
  }
  const s2 = Co(r3, t2);
  for (const t3 of i3)
    o3.push({ route_type: "wire", x: t3.x, y: t3.y, width: t3.traceThickness ?? e3.traceThickness, layer: s2 });
  if (e3.jumpers && e3.jumpers.length > 0) {
    const n3 = Co(e3.route[0]?.z ?? 0, t2);
    for (const t3 of e3.jumpers)
      o3.push({ route_type: "jumper", start: t3.start, end: t3.end, footprint: t3.footprint, layer: n3 });
  }
  return (({ route: e4, hdRoute: t3, layerCount: n3, connectionPoints: o4 = [], tolerance: i4 = 0.25, defaultViaHoleDiameter: r4 }) => {
    if (e4.length === 0 || t3.route.length === 0 || !o4.length)
      return e4;
    if (!o4.some((e5) => vo(e5) && e5.terminalVia))
      return e4;
    const s3 = e4.filter((e5) => e5.route_type !== "jumper"), a3 = e4.filter((e5) => e5.route_type === "jumper");
    if (s3.length === 0)
      return e4;
    const c3 = t3.route[0], l3 = t3.route[t3.route.length - 1], h2 = Co(c3.z, n3), d2 = Co(l3.z, n3), u2 = No({ endpoint: c3, endpointLayer: h2, connectionPoints: o4, tolerance: i4 }), p3 = No({ endpoint: l3, endpointLayer: d2, connectionPoints: o4, tolerance: i4 }), m2 = [], g2 = [], f2 = s3[0], _2 = s3[s3.length - 1], y2 = c3.traceThickness ?? t3.traceThickness, b2 = l3.traceThickness ?? t3.traceThickness;
    return u2?.terminalVia && (m2.push({ route_type: "via", x: u2.x, y: u2.y, from_layer: u2.layer, to_layer: u2.terminalVia.toLayer, via_diameter: u2.terminalVia.viaDiameter ?? t3.viaDiameter, ...r4 !== undefined ? { via_hole_diameter: r4 } : {} }), f2?.route_type === "wire" && f2.layer === u2.layer && Po(f2, u2) || m2.push({ route_type: "wire", x: u2.x, y: u2.y, width: y2, layer: u2.layer })), p3?.terminalVia && (_2?.route_type === "wire" && _2.layer === p3.layer && Po(_2, p3) || g2.push({ route_type: "wire", x: p3.x, y: p3.y, width: b2, layer: p3.layer }), g2.push({ route_type: "via", x: p3.x, y: p3.y, from_layer: p3.layer, to_layer: p3.terminalVia.toLayer, via_diameter: p3.terminalVia.viaDiameter ?? t3.viaDiameter, ...r4 !== undefined ? { via_hole_diameter: r4 } : {} })), [...m2, ...s3, ...g2, ...a3];
  })({ route: o3, hdRoute: e3, layerCount: t2, connectionPoints: n2.connectionPoints, tolerance: n2.terminalViaAttachTolerance, defaultViaHoleDiameter: n2.defaultViaHoleDiameter });
};
var To = ["blue", "orange", "purple", "cyan", "magenta", "yellowgreen", "darkgoldenrod", "deeppink"];
var Eo = (e3, t2) => {
  const n2 = {};
  for (let o3 = 0;o3 < e3.connections.length; o3++) {
    const i3 = e3.connections[o3], r3 = t2?.getNetConnectedToId(i3.name);
    r3 && !n2[r3] && (n2[r3] = `hsl(${300 * o3 / e3.connections.length}, 100%, 50%)`), n2[i3.name] = (r3 ? n2[r3] : null) ?? `hsl(${340 * o3 / e3.connections.length}, 100%, 50%)`;
  }
  return n2;
};
var Ao = (e3, t2) => {
  try {
    return Hn(t2, e3);
  } catch (t3) {
    return console.error(t3), e3;
  }
};
var Oo = (e3, t2 = 1) => {
  if (!e3)
    return "rgba(0, 0, 0, 0.5)";
  const n2 = 300 * e3.split("").reduce((e4, t3) => e4 + t3.charCodeAt(0), 0) / e3.length % 360;
  return t2 < 1 ? `hsla(${n2}, 100%, 50%, ${t2})` : `hsl(${n2}, 100%, 50%)`;
};
var ko = (e3) => {
  const t2 = new Set;
  return e3.filter((e4) => !t2.has(e4) && (t2.add(e4), true));
};
var Do = (e3, t2, n2) => {
  if (!t2)
    return;
  const o3 = e3.get(t2);
  o3 ? o3.includes(n2) || o3.push(n2) : e3.set(t2, [n2]);
};
var Lo = (e3) => {
  const t2 = new Map;
  for (const n2 of e3.connections) {
    const e4 = n2.__rootConnectionNames ?? [n2.name];
    for (const o3 of e4) {
      Do(t2, n2.name, o3), Do(t2, o3, o3), Do(t2, n2.__netConnectionName, o3);
      for (const e5 of n2.pointsToConnect)
        Do(t2, e5.pointId, o3), Do(t2, e5.pcb_port_id, o3);
    }
  }
  return (e4) => ((e5, t3 = []) => {
    const n2 = ko(t3).join(", ");
    return e5.layers.map((e6) => n2 ? `${e6}
${n2}` : e6).join(`
`);
  })(e4, ((e5, t3) => ko([...e5.connectedTo.flatMap((e6) => t3.get(e6) ?? []), ...(e5.offBoardConnectsTo ?? []).flatMap((e6) => t3.get(e6) ?? [])]))(e4, t2));
};
var zo = (e3, t2) => `z${fo(e3, t2).join(",")}`;
var Bo = (e3, t2) => zo(So(e3), t2);
var Fo = (e3, t2) => e3.__zLayers && e3.__zLayers.length > 0 ? go(e3.__zLayers, t2) : fo(e3.layers, t2);
var jo = (e3, t2) => `z${Fo(e3, t2).join(",")}`;
var $o = (...e3) => e3.find((e4) => typeof e4 == "number" && Number.isFinite(e4));
var Yo = (e3) => {
  const t2 = $o(e3.min_via_hole_diameter, e3.minViaHoleDiameter), n2 = $o(e3.min_via_pad_diameter, e3.minViaPadDiameter, e3.minViaDiameter), o3 = Math.max(n2 ?? e3.minViaDiameter ?? 0.3, t2 ?? 0);
  return { padDiameter: o3, holeDiameter: t2 ?? 0.5 * o3 };
};
var Xo = { "0603": { length: 1.65, width: 0.95, padLength: 0.8, padWidth: 0.95 }, 1206: { length: 3.2, width: 1.6, padLength: 0.6, padWidth: 1.6 }, "1206x4_pair": { length: 2.7, width: 0.5, padLength: 0.8, padWidth: 0.5 } };
var Ho = { top: "red", bottom: "blue", inner1: "green", inner2: "yellow", inner3: "orange", inner4: "purple", inner5: "cyan", inner6: "magenta", inner7: "lime", inner8: "brown" };
function Vo(e3) {
  if (Object.hasOwn(Ho, e3))
    return Ho[e3];
  const t2 = /^inner([1-9]\d*)$/.exec(e3);
  if (t2) {
    return `hsl(${137 * Number(t2[1]) % 360}, 70%, 45%)`;
  }
  throw new Error(`No visualization color for layer "${e3}"`);
}
var Wo = (e3, t2 = {}) => {
  const n2 = [], o3 = [], i3 = [], r3 = [], s2 = Eo(e3), a3 = t2.traceColorMode ?? "layer", c3 = e3.layerCount, l3 = Yo(e3), h2 = Lo(e3);
  if (e3.connections)
    for (const t3 of e3.connections)
      for (const e4 of t3.pointsToConnect) {
        const n3 = So(e4), o4 = t3.__rootConnectionNames ?? [t3.name];
        i3.push({ x: e4.x, y: e4.y, color: s2[t3.name], layer: Bo(e4, c3), label: [t3.name, o4.join(", "), n3.join(",")].join(`
`) });
      }
  if (e3.traces)
    for (const t3 of e3.traces) {
      let i4 = e3.minTraceWidth;
      const h3 = t3.route.filter((e4) => e4.route_type === "jumper"), d2 = (e4, t4) => {
        const n3 = 0.01;
        for (const o4 of h3) {
          const i5 = Math.abs(e4.x - o4.start.x) < n3 && Math.abs(e4.y - o4.start.y) < n3 && Math.abs(t4.x - o4.end.x) < n3 && Math.abs(t4.y - o4.end.y) < n3, r4 = Math.abs(e4.x - o4.end.x) < n3 && Math.abs(e4.y - o4.end.y) < n3 && Math.abs(t4.x - o4.start.x) < n3 && Math.abs(t4.y - o4.start.y) < n3;
          if (i5 || r4)
            return true;
        }
        return false;
      };
      for (const e4 of t3.route)
        if (e4.route_type === "via") {
          const n3 = mo(e4.from_layer, c3), i5 = mo(e4.to_layer, c3), r4 = (e4.via_diameter ?? l3.padDiameter) / 2, h4 = Array.from({ length: Math.abs(i5 - n3) + 1 }, (e5, t4) => Math.min(n3, i5) + t4);
          o3.push({ center: { x: e4.x, y: e4.y }, radius: r4, fill: a3 === "net" ? s2[t3.connection_name] : "blue", stroke: "none", layer: `z${h4.join(",")}` });
        } else if (e4.route_type === "through_obstacle") {
          const o4 = s2[t3.connection_name] ?? "purple";
          n2.push({ points: [e4.start, e4.end], strokeColor: Ao(o4, 0.35), strokeWidth: e4.width, strokeDash: [0.1, 0.1], layer: zo([e4.from_layer, e4.to_layer], c3), label: `${t3.connection_name} through_obstacle` });
        }
      let u2;
      for (let e4 = 0;e4 < t3.route.length - 1; e4++) {
        const o4 = t3.route[e4], l4 = t3.route[e4 + 1];
        if (o4.route_type === "jumper") {
          u2 = undefined;
          const e5 = s2[t3.connection_name] ?? "rgba(255, 165, 0, 0.8)", i5 = o4.footprint, a4 = Xo[i5 === "1206x4_pair" ? "1206x4_pair" : "0603"] ?? Xo["0603"], l5 = o4.end.x - o4.start.x, h4 = o4.end.y - o4.start.y, d3 = Math.abs(l5) > Math.abs(h4), p3 = d3 ? a4.padLength : a4.padWidth, m2 = d3 ? a4.padWidth : a4.padLength;
          r3.push({ center: o4.start, width: p3, height: m2, fill: Ao(e5, 0.5), stroke: "rgba(0, 0, 0, 0.5)", layer: zo([o4.layer], c3) }), r3.push({ center: o4.end, width: p3, height: m2, fill: Ao(e5, 0.5), stroke: "rgba(0, 0, 0, 0.5)", layer: zo([o4.layer], c3) }), n2.push({ points: [o4.start, o4.end], strokeColor: "rgba(100, 100, 100, 0.8)", strokeWidth: 0.3 * a4.padWidth, layer: zo([o4.layer], c3) });
        } else if (o4.route_type === "wire" && l4.route_type === "wire" && l4.layer === o4.layer) {
          if (d2({ x: o4.x, y: o4.y }, { x: l4.x, y: l4.y })) {
            u2 = undefined;
            continue;
          }
          i4 = o4.width;
          const e5 = o4.layer === "top", r4 = a3 === "net" ? s2[t3.connection_name] : Vo(o4.layer), h4 = `z${mo(o4.layer, c3)}`;
          if (u2 && u2.layer === h4 && u2.strokeWidth === i4) {
            u2.points.push({ x: l4.x, y: l4.y });
            continue;
          }
          u2 = { points: [{ x: o4.x, y: o4.y }, { x: l4.x, y: l4.y }], layer: h4, strokeWidth: i4, strokeColor: e5 ? r4 : Ao(r4, 0.5), ...a3 === "net" ? { label: t3.connection_name } : {}, ...e5 ? {} : { strokeDash: [0.2, 0.2] } }, n2.push(u2);
        } else
          u2 = undefined;
      }
    }
  for (const t3 of e3.obstacles) {
    if (t3.isCopperPour)
      continue;
    const e4 = Fo(t3, c3);
    if (e4.length === 0)
      throw new Error(`Cannot visualize obstacle "${t3.obstacleId ?? "unknown"}" without a valid layer: layers=${t3.layers.join(",")}, __zLayers=${t3.__zLayers?.join(",") ?? "unset"}, layerCount=${c3}`);
    const n3 = Vo((e4.length === 1 ? Co(e4[0], c3) : null) === "bottom" ? "bottom" : "top"), o4 = 0.5 ** e4.length;
    r3.push({ center: t3.center, width: t3.width, height: t3.height, ccwRotationDegrees: t3.ccwRotationDegrees, fill: Ao(n3, o4), layer: jo(t3, c3), label: h2(t3) });
  }
  if (e3.jumpers)
    for (const t3 of e3.jumpers)
      for (const e4 of t3.pads)
        r3.push({ center: e4.center, width: e4.width, height: e4.height, ccwRotationDegrees: e4.ccwRotationDegrees, fill: "rgba(255, 165, 0, 0.3)", stroke: "rgba(255, 165, 0, 0.8)", layer: jo(e4, c3) });
  return { rects: r3, circles: o3, lines: n2, points: i3 };
};
function Go(e3) {
  let t2 = e3;
  for (;t2.parent !== null; )
    t2 = t2.parent;
  let n2 = e3;
  for (;n2.parent !== null && n2.parent !== t2; ) {
    const e4 = n2.parent;
    n2.parent = t2, n2 = e4;
  }
  return t2;
}
function Uo(e3, t2) {
  const n2 = t2.rootByNodeId.get(e3);
  return n2 === undefined ? function(e4, t3) {
    const n3 = { nodeId: e4, nextMember: null }, o3 = { parent: null, networkId: "connectivity_net" + t3.nextNetworkNumber++, firstMember: n3, lastMember: n3 };
    return t3.rootByNodeId.set(e4, o3), o3;
  }(e3, t2) : Go(n2);
}
function Zo({ targetRoot: e3, sourceRoot: t2 }) {
  e3.lastMember.nextMember = t2.firstMember, e3.lastMember = t2.lastMember, t2.parent = e3;
}
function qo(e3) {
  const t2 = [];
  let n2 = e3.firstMember;
  for (;n2 !== null; )
    t2.push(n2.nodeId), n2 = n2.nextMember;
  return t2;
}
var Jo = class {
  netMap;
  idToNetMap;
  constructor(e3) {
    this.netMap = e3, this.idToNetMap = {};
    for (const [t2, n2] of Object.entries(e3))
      for (const e4 of n2)
        this.idToNetMap[e4] = t2;
  }
  addConnections(e3) {
    for (const t2 of e3) {
      const e4 = new Set;
      for (const n3 of t2) {
        const t3 = this.idToNetMap[n3];
        t3 && e4.add(t3);
      }
      let n2;
      if (e4.size === 0)
        n2 = `connectivity_net${Object.keys(this.netMap).length}`, this.netMap[n2] = [];
      else if (e4.size === 1)
        n2 = e4.values().next().value ?? `connectivity_net${Object.keys(this.netMap).length}`;
      else {
        n2 = e4.values().next().value ?? `connectivity_net${Object.keys(this.netMap).length}`;
        for (const t3 of e4)
          if (t3 !== n2) {
            this.netMap[n2].push(...this.netMap[t3]), this.netMap[t3] = this.netMap[n2];
            for (const e5 of this.netMap[n2])
              this.idToNetMap[e5] = n2;
          }
      }
      for (const e5 of t2)
        this.idToNetMap[e5] !== n2 && this.netMap[n2].push(e5), this.idToNetMap[e5] = n2;
    }
  }
  getIdsConnectedToNet(e3) {
    return this.netMap[e3] || [];
  }
  getNetConnectedToId(e3) {
    return this.idToNetMap[e3];
  }
  areIdsConnected(e3, t2) {
    if (e3 === t2)
      return true;
    const n2 = this.getNetConnectedToId(e3);
    if (!n2)
      return false;
    const o3 = this.getNetConnectedToId(t2);
    return !!o3 && (n2 === o3 || o3 === e3 || o3 === e3);
  }
  areAllIdsConnected(e3) {
    const t2 = this.getNetConnectedToId(e3[0]);
    for (const n2 of e3) {
      const e4 = this.getNetConnectedToId(n2);
      if (e4 === undefined)
        return false;
      if (e4 !== t2)
        return false;
    }
    return true;
  }
};
var Qo = (e3) => {
  const t2 = [];
  for (const n3 of e3)
    if (n3.type === "source_trace")
      t2.push([n3.source_trace_id, ...n3.connected_source_port_ids ?? [], ...n3.connected_source_net_ids ?? []].filter(Boolean));
    else if (n3.type === "pcb_port") {
      const { pcb_port_id: e4, source_port_id: o3 } = n3;
      o3 && e4 && t2.push([o3, e4]);
    } else if (n3.type === "pcb_smtpad") {
      const { pcb_smtpad_id: e4, pcb_port_id: o3 } = n3;
      o3 && e4 && t2.push([e4, o3]);
    } else if (n3.type === "pcb_plated_hole") {
      const { pcb_plated_hole_id: e4, pcb_port_id: o3 } = n3;
      o3 && e4 && t2.push([e4, o3]);
    } else if (n3.type === "pcb_trace") {
      const { pcb_trace_id: e4, source_trace_id: o3 } = n3, i3 = Array.isArray(n3.route) ? n3.route.filter((e5) => e5 && e5.route_type === "wire") : [];
      if (o3 && e4 && t2.push([e4, o3]), Array.isArray(i3)) {
        const n4 = i3.find((e5) => e5?.start_pcb_port_id)?.start_pcb_port_id, o4 = i3.find((e5) => e5?.end_pcb_port_id)?.end_pcb_port_id;
        n4 && e4 && t2.push([n4, e4]), e4 && o4 && t2.push([e4, o4]);
      }
    } else if (n3.type === "pcb_via") {
      const { pcb_via_id: e4, pcb_trace_id: o3, source_trace_id: i3, source_net_id: r3 } = n3, s2 = [...n3.pcb_port_ids ?? [], o3, i3, r3].filter((e5) => Boolean(e5));
      e4 && s2.length > 0 && t2.push([e4, ...s2]);
    } else if (n3.type === "source_component" && n3.internally_connected_source_port_ids)
      for (const e4 of n3.internally_connected_source_port_ids)
        t2.push(e4);
  const n2 = function(e4) {
    const t3 = { rootByNodeId: new Map, nextNetworkNumber: 0 };
    for (const n4 of e4) {
      let e5 = null;
      for (const o3 of n4) {
        const n5 = Uo(o3, t3);
        e5 !== null ? (e5 = Go(e5), n5 !== e5 && Zo({ targetRoot: e5, sourceRoot: n5 })) : e5 = n5;
      }
    }
    const n3 = {};
    for (const e5 of t3.rootByNodeId.values())
      e5.parent === null && (n3[e5.networkId] = qo(e5));
    return n3;
  }(t2);
  return new Jo(n2);
};
var Ko = (e3) => `${Math.round(100 * e3.x)},${Math.round(100 * e3.y)}`;
var ei = (e3) => {
  const t2 = new Jo({});
  for (const n2 of e3.connections) {
    for (const e4 of n2.__rootConnectionNames ?? [])
      t2.addConnections([[n2.name, e4]]);
    n2.__netConnectionName && t2.addConnections([[n2.name, n2.__netConnectionName]]);
    for (const o3 of n2.pointsToConnect)
      t2.addConnections([[n2.name, `${Ko(o3)}:${So(o3).map((t3) => mo(t3, e3.layerCount)).sort().join("-")}`]]), "pcb_port_id" in o3 && o3.pcb_port_id && t2.addConnections([[n2.name, o3.pcb_port_id]]), o3.pointId && t2.addConnections([[n2.name, o3.pointId]]);
  }
  for (const n2 of e3.obstacles) {
    const o3 = n2.offBoardConnectsTo ?? [], i3 = Array.from(new Set([n2.obstacleId, ...n2.connectedTo, ...o3, `${Ko(n2.center)}:${n2.layers.map((t3) => mo(t3, e3.layerCount)).sort().join("-")}`].filter(Boolean)));
    i3.length > 0 && t2.addConnections([i3]);
  }
  for (const n2 of e3.traces ?? []) {
    const e4 = Array.from(new Set([n2.pcb_trace_id, n2.connection_name, ...n2.connectsTo ?? []].filter(Boolean)));
    e4.length > 0 && t2.addConnections([e4]);
  }
  return t2;
};
var ti = (e3) => {
  const t2 = new Jo({});
  for (const n2 of e3.connections) {
    const e4 = n2.externallyConnectedPointIds ?? [];
    t2.addConnections(e4);
  }
  for (const n2 of e3.traces ?? []) {
    const e4 = n2.connectsTo ?? [];
    e4.length !== 0 && t2.addConnections([[n2.pcb_trace_id, ...e4]]);
  }
  return t2;
};
var ni = class {
  MAX_ITERATIONS = 1000;
  solved = false;
  failed = false;
  iterations = 0;
  progress = 0;
  error = null;
  activeSubSolver;
  failedSubSolvers;
  timeToSolve;
  stats = {};
  pendingEffects;
  cacheHit;
  cacheKey;
  cacheToSolveSpaceTransform;
  getSolverName() {
    return this.constructor.name;
  }
  step() {
    if (!this.solved && !this.failed) {
      this.iterations++;
      try {
        this._step();
      } catch (e3) {
        throw this.error = `${this.getSolverName()} error: ${e3}`, console.error(this.error), this.failed = true, e3;
      }
      !this.solved && this.iterations > this.MAX_ITERATIONS && this.tryFinalAcceptance(), !this.solved && this.iterations > this.MAX_ITERATIONS && (this.error = `${this.getSolverName()} ran out of iterations (MAX_ITERATIONS=${this.MAX_ITERATIONS})`, this.failed = true), "computeProgress" in this && (this.progress = this.computeProgress());
    }
  }
  _step() {}
  getConstructorParams() {
    throw new Error("getConstructorParams not implemented");
  }
  solve() {
    const e3 = Date.now();
    for (;!this.solved && !this.failed; )
      this.step();
    const t2 = Date.now();
    this.timeToSolve = t2 - e3;
  }
  visualize() {
    return { lines: [], points: [], rects: [], circles: [] };
  }
  tryFinalAcceptance() {}
  preview() {
    return { lines: [], points: [], rects: [], circles: [] };
  }
};
function oi(e3) {
  const t2 = new Map;
  for (const n2 of e3)
    for (const e4 of n2.nodeIds)
      t2.set(e4, [...t2.get(e4) ?? [], n2]);
  return t2;
}
var ii = class extends ni {
  getSolverName() {
    return "AvailableSegmentPointSolver";
  }
  nodes;
  edges;
  traceWidth;
  obstacleMargin;
  minPortSpacing;
  nodeMap;
  nodeEdgeMap;
  sharedEdgeSegments = [];
  edgeSegmentMap = new Map;
  portPointMap = new Map;
  colorMap;
  shouldReturnCrampedPortPoints;
  constructor({ nodes: e3, edges: t2, traceWidth: n2, obstacleMargin: o3, colorMap: i3, shouldReturnCrampedPortPoints: r3 }) {
    super(), this.nodes = e3, this.edges = t2, this.traceWidth = n2, this.obstacleMargin = o3 ?? 0.15, this.shouldReturnCrampedPortPoints = r3, this.minPortSpacing = this.traceWidth + this.obstacleMargin, this.colorMap = i3 ?? {}, this.nodeMap = new Map(e3.map((e4) => [e4.capacityMeshNodeId, e4])), this.nodeEdgeMap = oi(t2), this.MAX_ITERATIONS = 1;
  }
  _step() {
    this.computeAllSharedEdgeSegments(), this.solved = true;
  }
  computeAllSharedEdgeSegments() {
    for (const e3 of this.edges) {
      const [t2, n2] = e3.nodeIds, o3 = this.nodeMap.get(t2), i3 = this.nodeMap.get(n2);
      if (!o3 || !i3)
        continue;
      const r3 = this.computeSharedEdgeSegment(e3, o3, i3);
      if (r3) {
        this.sharedEdgeSegments.push(r3), this.edgeSegmentMap.set(e3.capacityMeshEdgeId, r3);
        for (const e4 of r3.portPoints)
          this.portPointMap.set(e4.segmentPortPointId, e4);
      }
    }
  }
  computeSharedEdgeSegment(e3, t2, n2) {
    const o3 = this.findOverlappingSegment(t2, n2);
    if (!o3)
      return null;
    const i3 = t2.availableZ.filter((e4) => n2.availableZ.includes(e4));
    if (i3.length === 0)
      return null;
    const r3 = Math.sqrt((o3.end.x - o3.start.x) ** 2 + (o3.end.y - o3.start.y) ** 2), s2 = Boolean(t2._isNarrowQfpPadGap || n2._isNarrowQfpPadGap), a3 = 3 * this.minPortSpacing / 4, c3 = Math.max(0, r3 - 2 * a3);
    if (c3 <= 0 && !t2._containsTarget && !n2._containsTarget) {
      if (!this.shouldReturnCrampedPortPoints)
        return null;
      const r4 = [];
      for (const s3 of i3)
        r4.push({ segmentPortPointId: `${e3.capacityMeshEdgeId}_pp0_z${s3}_cramped`, x: (o3.start.x + o3.end.x) / 2, y: (o3.start.y + o3.end.y) / 2, availableZ: [s3], nodeIds: [t2.capacityMeshNodeId, n2.capacityMeshNodeId], edgeId: e3.capacityMeshEdgeId, connectionName: null, distToCentermostPortOnZ: 0, cramped: true });
      return { edgeId: e3.capacityMeshEdgeId, nodeIds: [t2.capacityMeshNodeId, n2.capacityMeshNodeId], start: o3.start, end: o3.end, availableZ: i3, portPoints: r4 };
    }
    let l3 = Math.max(1, Math.floor(c3 / this.minPortSpacing) + 1);
    if (t2._offBoardConnectionId || n2._offBoardConnectionId) {
      if (t2._offBoardConnectionId && !n2._offBoardConnectionId) {
        if (this.shouldSkipOffBoardPortPoint(t2, n2))
          return null;
      } else if (n2._offBoardConnectionId && !t2._offBoardConnectionId && this.shouldSkipOffBoardPortPoint(n2, t2))
        return null;
      l3 = 1;
    }
    const h2 = [], d2 = o3.end.x - o3.start.x, u2 = o3.end.y - o3.start.y, p3 = (o3.start.x + o3.end.x) / 2, m2 = (o3.start.y + o3.end.y) / 2;
    l3 > 5 && (l3 = 5 + Math.floor(l3 / 4));
    const g2 = [];
    for (let e4 = 0;e4 < l3; e4++) {
      let t3;
      t3 = r3 === 0 || l3 === 1 ? 0.5 : (a3 + c3 * e4 / (l3 - 1)) / r3;
      const n3 = o3.start.x + d2 * t3, i4 = o3.start.y + u2 * t3, s3 = Math.sqrt((n3 - p3) ** 2 + (i4 - m2) ** 2);
      g2.push({ x: n3, y: i4, distToCenter: s3 });
    }
    const f2 = g2.reduce((e4, t3) => t3.distToCenter < e4.distToCenter ? t3 : e4);
    for (let o4 = 0;o4 < l3; o4++) {
      const { x: r4, y: a4 } = g2[o4], c4 = Math.sqrt((r4 - f2.x) ** 2 + (a4 - f2.y) ** 2);
      for (const l4 of i3) {
        const i4 = { segmentPortPointId: `${e3.capacityMeshEdgeId}_pp${o4}_z${l4}`, x: r4, y: a4, availableZ: [l4], nodeIds: [t2.capacityMeshNodeId, n2.capacityMeshNodeId], edgeId: e3.capacityMeshEdgeId, connectionName: null, distToCentermostPortOnZ: c4, cramped: s2 };
        h2.push(i4);
      }
    }
    return { edgeId: e3.capacityMeshEdgeId, nodeIds: [t2.capacityMeshNodeId, n2.capacityMeshNodeId], start: o3.start, end: o3.end, availableZ: i3, portPoints: h2 };
  }
  shouldSkipOffBoardPortPoint(e3, t2) {
    const n2 = this.nodeEdgeMap.get(t2.capacityMeshNodeId) ?? [];
    for (const o3 of n2) {
      const n3 = o3.nodeIds[0] === t2.capacityMeshNodeId ? o3.nodeIds[1] : o3.nodeIds[0];
      if (n3 === e3.capacityMeshNodeId)
        continue;
      const i3 = this.nodeMap.get(n3);
      if (i3?._offBoardConnectionId !== e3._offBoardConnectionId)
        continue;
      if (this.nodes.filter((t3) => t3._offBoardConnectionId === e3._offBoardConnectionId).length !== 2)
        continue;
      const r3 = { x: (e3.center.x + i3.center.x) / 2, y: (e3.center.y + i3.center.y) / 2 };
      if (r3.x >= t2.center.x - t2.width / 2 && r3.x <= t2.center.x + t2.width / 2 && r3.y >= t2.center.y - t2.height / 2 && r3.y <= t2.center.y + t2.height / 2)
        return true;
    }
    return false;
  }
  findOverlappingSegment(e3, t2) {
    const n2 = { start: Math.max(e3.center.x - e3.width / 2, t2.center.x - t2.width / 2), end: Math.min(e3.center.x + e3.width / 2, t2.center.x + t2.width / 2) }, o3 = { start: Math.max(e3.center.y - e3.height / 2, t2.center.y - t2.height / 2), end: Math.min(e3.center.y + e3.height / 2, t2.center.y + t2.height / 2) }, i3 = n2.end - n2.start, r3 = o3.end - o3.start;
    if (i3 < -0.0001 || r3 < -0.0001)
      return null;
    if (i3 < r3) {
      const e4 = (n2.start + n2.end) / 2;
      return { start: { x: e4, y: o3.start }, end: { x: e4, y: o3.end } };
    }
    {
      const e4 = (o3.start + o3.end) / 2;
      return { start: { x: n2.start, y: e4 }, end: { x: n2.end, y: e4 } };
    }
  }
  getAvailablePortPointsBetweenNodes(e3, t2) {
    const n2 = this.edges.find((n3) => n3.nodeIds[0] === e3 && n3.nodeIds[1] === t2 || n3.nodeIds[0] === t2 && n3.nodeIds[1] === e3);
    if (!n2)
      return [];
    const o3 = this.edgeSegmentMap.get(n2.capacityMeshEdgeId);
    return o3 ? o3.portPoints.filter((e4) => e4.connectionName === null) : [];
  }
  getPortPointsForEdge(e3, t2) {
    const n2 = this.edges.find((n3) => n3.nodeIds[0] === e3 && n3.nodeIds[1] === t2 || n3.nodeIds[0] === t2 && n3.nodeIds[1] === e3);
    if (!n2)
      return [];
    const o3 = this.edgeSegmentMap.get(n2.capacityMeshEdgeId);
    return o3?.portPoints ?? [];
  }
  assignPortPoint(e3, t2, n2) {
    const o3 = this.portPointMap.get(e3);
    return !!o3 && (o3.connectionName === null && (o3.connectionName = t2, o3.rootConnectionName = n2, true));
  }
  releasePortPoint(e3) {
    const t2 = this.portPointMap.get(e3);
    return !!t2 && (t2.connectionName = null, t2.rootConnectionName = undefined, true);
  }
  getAvailablePortCountForEdge(e3, t2) {
    return this.getAvailablePortPointsBetweenNodes(e3, t2).length;
  }
  getOutput() {
    return this.sharedEdgeSegments;
  }
  visualize() {
    const e3 = { lines: [], points: [], rects: [], circles: [] };
    for (const t2 of this.sharedEdgeSegments) {
      e3.lines.push({ points: [t2.start, t2.end], strokeColor: "rgba(100, 100, 100, 0.5)" });
      for (const n2 of t2.portPoints) {
        const t3 = n2.connectionName ? this.colorMap[n2.connectionName] ?? "blue" : "rgba(0, 200, 0, 0.7)";
        n2.cramped ? e3.rects.push({ center: { x: n2.x, y: n2.y }, width: 0.1, height: 0.1, fill: t3, layer: `z${n2.availableZ.join(",")}`, label: `cramped ${n2.segmentPortPointId}` }) : e3.circles.push({ center: { x: n2.x, y: n2.y }, radius: this.traceWidth / 2, fill: t3, layer: `z${n2.availableZ.join(",")}`, label: [n2.segmentPortPointId, n2.connectionName, n2.availableZ.join(","), `cd: ${n2.distToCentermostPortOnZ}`, `connects: ${n2.nodeIds.join(",")}`].filter(Boolean).join(`
`) });
      }
    }
    return e3;
  }
};
function ri(e3, t2) {
  const n2 = e3.center.x - e3.width / 2, o3 = e3.center.x + e3.width / 2, i3 = e3.center.y - e3.height / 2, r3 = e3.center.y + e3.height / 2, s2 = t2.center.x - t2.width / 2, a3 = t2.center.x + t2.width / 2, c3 = t2.center.y - t2.height / 2, l3 = t2.center.y + t2.height / 2, h2 = 0.001, d2 = (Math.abs(o3 - s2) < h2 || Math.abs(n2 - a3) < h2) && Math.min(r3, l3) - Math.max(i3, c3) >= h2, u2 = (Math.abs(r3 - c3) < h2 || Math.abs(i3 - l3) < h2) && Math.min(o3, a3) - Math.max(n2, s2) >= h2;
  return d2 || u2;
}
var si = 0.000000001;
function ai(e3) {
  return Le({ center: e3.center, width: e3.width, height: e3.height });
}
function ci(e3, t2) {
  const n2 = { minX: Math.max(e3.minX, t2.minX), maxX: Math.min(e3.maxX, t2.maxX), minY: Math.max(e3.minY, t2.minY), maxY: Math.min(e3.maxY, t2.maxY) };
  return li(n2) ? n2 : null;
}
function li(e3) {
  const t2 = e3.maxX - e3.minX, n2 = e3.maxY - e3.minY, o3 = Number.isFinite(t2) && t2 > si, i3 = Number.isFinite(n2) && n2 > si;
  return o3 && i3;
}
var hi = class extends ni {
  constructor(e3) {
    super(), this.nodes = e3, this.edges = [];
  }
  getSolverName() {
    return "CapacityMeshEdgeSolver";
  }
  edges;
  nodeMap;
  getNextCapacityMeshEdgeId() {
    return `ce${this.edges.length}`;
  }
  _step() {
    this.edges = [];
    for (let e3 = 0;e3 < this.nodes.length; e3++)
      for (let t2 = e3 + 1;t2 < this.nodes.length; t2++) {
        !(this.nodes[e3]._strawNode && this.nodes[t2]._strawNode && this.nodes[e3]._strawParentCapacityMeshNodeId === this.nodes[t2]._strawParentCapacityMeshNodeId) && ri(this.nodes[e3], this.nodes[t2]) && this.doNodesHaveSharedLayer(this.nodes[e3], this.nodes[t2]) && this.edges.push({ capacityMeshEdgeId: this.getNextCapacityMeshEdgeId(), nodeIds: [this.nodes[e3].capacityMeshNodeId, this.nodes[t2].capacityMeshNodeId] });
      }
    this.handleTargetNodes(), this.solved = true;
  }
  handleTargetNodes() {
    const e3 = this.nodes.filter((e4) => e4._containsTarget);
    for (let t3 = 0;t3 < e3.length; t3++)
      for (let n2 = t3 + 1;n2 < e3.length; n2++) {
        const o3 = e3[t3], i3 = e3[n2];
        this.doNodesHaveSharedLayer(o3, i3) && (this.doNodesTouchOrOverlap(o3, i3) && (this.hasEdgeBetween(o3, i3) || this.edges.push({ capacityMeshEdgeId: this.getNextCapacityMeshEdgeId(), nodeIds: [o3.capacityMeshNodeId, i3.capacityMeshNodeId] })));
      }
    const t2 = function({ nodes: e4, edges: t3 }) {
      const n2 = new Map(e4.map((e5) => [e5.capacityMeshNodeId, e5])), o3 = new Map;
      for (const t4 of e4)
        o3.set(t4.capacityMeshNodeId, []);
      for (const e5 of t3) {
        const t4 = n2.get(e5.nodeIds[0]), i4 = n2.get(e5.nodeIds[1]);
        if (t4._containsTarget && i4._containsTarget) {
          const e6 = ci(ai(t4), ai(i4));
          if (!ri(t4, i4) && !e6)
            continue;
        }
        o3.get(t4.capacityMeshNodeId).push(i4), o3.get(i4.capacityMeshNodeId).push(t4);
      }
      const i3 = new Set, r3 = [];
      for (const t4 of e4)
        t4._containsTarget && t4._targetConnectionName && o3.get(t4.capacityMeshNodeId).some((e5) => !e5._containsObstacle && !e5._containsTarget) && (i3.add(t4.capacityMeshNodeId), r3.push(t4));
      for (;r3.length; ) {
        const e5 = r3.pop();
        for (const t4 of o3.get(e5.capacityMeshNodeId))
          t4._containsTarget && t4._targetConnectionName === e5._targetConnectionName && !i3.has(t4.capacityMeshNodeId) && (i3.add(t4.capacityMeshNodeId), r3.push(t4));
      }
      return i3;
    }({ nodes: this.nodes, edges: this.edges });
    for (const n2 of e3)
      if (n2._containsObstacle && n2._targetConnectionName && !t2.has(n2.capacityMeshNodeId))
        throw new Error(`Target obstacle region "${n2.capacityMeshNodeId}" for connection "${n2._targetConnectionName}" has no bordering routing edge`);
  }
  doNodesHaveSharedLayer(e3, t2) {
    return e3.availableZ.some((e4) => t2.availableZ.includes(e4));
  }
  hasEdgeBetween(e3, t2) {
    return this.edges.some((n2) => n2.nodeIds.includes(e3.capacityMeshNodeId) && n2.nodeIds.includes(t2.capacityMeshNodeId));
  }
  doNodesTouchOrOverlap(e3, t2) {
    const n2 = 0.001, o3 = e3.center.x - e3.width / 2, i3 = e3.center.x + e3.width / 2, r3 = e3.center.y - e3.height / 2, s2 = e3.center.y + e3.height / 2, a3 = t2.center.x - t2.width / 2, c3 = t2.center.x + t2.width / 2, l3 = t2.center.y - t2.height / 2, h2 = t2.center.y + t2.height / 2;
    return o3 <= c3 + n2 && i3 + n2 >= a3 && r3 <= h2 + n2 && s2 + n2 >= l3;
  }
  visualize() {
    const e3 = new Map;
    for (const t3 of this.edges)
      for (const n2 of t3.nodeIds)
        e3.set(n2, 1 + (e3.get(n2) ?? 0));
    const t2 = { lines: [], points: [], rects: this.nodes.map((t3) => {
      const n2 = Math.min(...t3.availableZ);
      return { width: Math.max(t3.width - 2, 0.8 * t3.width), height: Math.max(t3.height - 2, 0.8 * t3.height), center: { x: t3.center.x + n2 * t3.width * 0.05, y: t3.center.y - n2 * t3.width * 0.05 }, fill: t3._containsObstacle ? "rgba(255,0,0,0.1)" : { "0,1": "rgba(0,0,0,0.1)", 0: "rgba(0,200,200, 0.1)", 1: "rgba(0,0,200, 0.1)" }[t3.availableZ.join(",")] ?? "rgba(0,200,200,0.1)", label: [t3.capacityMeshNodeId, `availableZ: ${t3.availableZ.join(",")}`, `target? ${t3._containsTarget ?? false}`, `obs? ${t3._containsObstacle ?? false}`, `conn: ${e3.get(t3.capacityMeshNodeId) ?? 0}`].join(`
`), layer: `z${t3.availableZ.join(",")}` };
    }), circles: [] };
    if (!this.nodeMap) {
      this.nodeMap = new Map;
      for (const e4 of this.nodes)
        this.nodeMap.set(e4.capacityMeshNodeId, e4);
    }
    for (const e4 of this.edges) {
      const n2 = this.nodeMap.get(e4.nodeIds[0]), o3 = this.nodeMap.get(e4.nodeIds[1]);
      if (n2?.center && o3?.center) {
        const e5 = Math.min(...n2.availableZ), i3 = Math.min(...o3.availableZ), r3 = { x: n2.center.x + e5 * n2.width * 0.05, y: n2.center.y - e5 * n2.width * 0.05 }, s2 = { x: o3.center.x + i3 * o3.width * 0.05, y: o3.center.y - i3 * o3.width * 0.05 }, a3 = Array.from(new Set([...n2.availableZ, ...o3.availableZ])).sort();
        t2.lines.push({ layer: `z${a3.join(",")}`, points: [r3, s2], strokeDash: n2.availableZ.join(",") === o3.availableZ.join(",") ? undefined : "10 5" });
      }
    }
    return t2;
  }
};
var di = class {
  constructor(e3) {
    this.nodes = e3, this.buckets = new Map;
    for (const t2 of e3) {
      const e4 = t2.center.x - t2.width / 2, n2 = t2.center.y - t2.height / 2, o3 = t2.center.x + t2.width / 2, i3 = t2.center.y + t2.height / 2, r3 = Math.floor(e4 / this.CELL_SIZE), s2 = Math.floor(o3 / this.CELL_SIZE), a3 = Math.floor(n2 / this.CELL_SIZE), c3 = Math.floor(i3 / this.CELL_SIZE);
      for (let e5 = r3;e5 <= s2; e5++)
        for (let n3 = a3;n3 <= c3; n3++) {
          const o4 = `${e5}x${n3}`, i4 = this.buckets.get(o4);
          i4 ? i4.push(t2) : this.buckets.set(o4, [t2]);
        }
    }
  }
  buckets;
  CELL_SIZE = 0.4;
  getBucketKey(e3, t2) {
    return `${Math.floor(e3 / this.CELL_SIZE)}x${Math.floor(t2 / this.CELL_SIZE)}`;
  }
  getNodesInArea(e3, t2, n2, o3) {
    const i3 = [], r3 = new Set, s2 = e3 - n2 / 2, a3 = t2 - o3 / 2, c3 = e3 + n2 / 2, l3 = t2 + o3 / 2, h2 = Math.floor(s2 / this.CELL_SIZE), d2 = Math.floor(c3 / this.CELL_SIZE), u2 = Math.floor(a3 / this.CELL_SIZE), p3 = Math.floor(l3 / this.CELL_SIZE);
    for (let e4 = h2;e4 <= d2; e4++)
      for (let t3 = u2;t3 <= p3; t3++) {
        const n3 = `${e4}x${t3}`, o4 = this.buckets.get(n3) || [];
        for (const e5 of o4)
          r3.has(e5.capacityMeshNodeId) || (r3.add(e5.capacityMeshNodeId), i3.push(e5));
      }
    return i3;
  }
};
var ui = class extends hi {
  constructor(e3) {
    super(e3), this.nodes = e3, this.MAX_ITERATIONS = 1e7, this.nodeTree = new di(this.nodes), this.currentNodeIndex = 0, this.edgeSet = new Set;
  }
  getSolverName() {
    return "CapacityMeshEdgeSolver2_NodeTreeOptimization";
  }
  nodeTree;
  currentNodeIndex;
  edgeSet;
  _step() {
    if (this.currentNodeIndex >= this.nodes.length)
      return this.handleTargetNodes(), void (this.solved = true);
    const e3 = this.nodes[this.currentNodeIndex], t2 = this.nodeTree.getNodesInArea(e3.center.x, e3.center.y, 2 * e3.width, 2 * e3.height);
    for (const n2 of t2) {
      if (!ri(e3, n2))
        continue;
      const t3 = e3._strawNode && n2._strawNode && e3._strawParentCapacityMeshNodeId === n2._strawParentCapacityMeshNodeId;
      e3.capacityMeshNodeId === n2.capacityMeshNodeId || t3 || !this.doNodesHaveSharedLayer(e3, n2) || this.edgeSet.has(`${e3.capacityMeshNodeId}-${n2.capacityMeshNodeId}`) || (this.edgeSet.add(`${e3.capacityMeshNodeId}-${n2.capacityMeshNodeId}`), this.edgeSet.add(`${n2.capacityMeshNodeId}-${e3.capacityMeshNodeId}`), this.edges.push({ capacityMeshEdgeId: this.getNextCapacityMeshEdgeId(), nodeIds: [e3.capacityMeshNodeId, n2.capacityMeshNodeId] }));
    }
    this.currentNodeIndex++;
  }
};
var pi = (...e3) => {
  const t2 = { points: [], lines: [], circles: [], rects: [], polygons: [], infiniteLines: [], arrows: [], texts: [] };
  return e3.forEach((e4, n2) => {
    e4 && (e4.lines && (t2.lines = [...t2.lines || [], ...e4.lines.map((e5) => ({ ...e5, step: n2 }))]), e4.points && (t2.points = [...t2.points || [], ...e4.points.map((e5) => ({ ...e5, step: n2 }))]), e4.circles && (t2.circles = [...t2.circles || [], ...e4.circles.map((e5) => ({ ...e5, step: n2 }))]), e4.rects && (t2.rects = [...t2.rects || [], ...e4.rects.map((e5) => ({ ...e5, step: n2 }))]), e4.polygons && (t2.polygons = [...t2.polygons || [], ...e4.polygons.map((e5) => ({ ...e5, step: n2 }))]), e4.infiniteLines && (t2.infiniteLines = [...t2.infiniteLines || [], ...e4.infiniteLines.map((e5) => ({ ...e5, step: n2 }))]), e4.arrows && (t2.arrows = [...t2.arrows || [], ...e4.arrows.map((e5) => ({ ...e5, step: n2 }))]), e4.texts && (t2.texts = [...t2.texts || [], ...e4.texts.map((e5) => ({ ...e5, step: n2 }))]));
  }), t2;
};
function mi(e3, t2, n2) {
  const o3 = [];
  let i3 = null;
  for (let r3 = 0;r3 < e3.length; r3++) {
    const s2 = e3[r3];
    i3 ? i3.z === s2.z ? i3.points.push({ x: s2.x, y: s2.y }) : (o3.push(i3), i3 = { points: [{ x: s2.x, y: s2.y }], z: s2.z, connectionName: t2, color: n2 }) : i3 = { points: [{ x: s2.x, y: s2.y }], z: s2.z, connectionName: t2, color: n2 }, r3 === e3.length - 1 && i3 && o3.push(i3);
  }
  return o3;
}
function gi(e3, t2) {
  return { x: e3.a * t2.x + e3.b * t2.y + e3.c, y: e3.d * t2.x + e3.e * t2.y + e3.f };
}
var _i = (e3, t2, n2) => {
  const [o3, i3] = e3;
  if (o3 === i3)
    return;
  const r3 = ((e4, t3) => {
    const n3 = e4.portPointId ?? `${e4.connectionName}:${e4.x}:${e4.y}:${e4.z}`, o4 = t3.portPointId ?? `${t3.connectionName}:${t3.x}:${t3.y}:${t3.z}`;
    return n3 < o4 ? `${n3}|${o4}` : `${o4}|${n3}`;
  })(o3, i3);
  t2.has(r3) || (t2.add(r3), n2.push(e3));
};
var yi = (e3, t2, n2) => {
  for (let o3 = 0;o3 < e3.length - 1; o3++)
    _i([e3[o3], e3[o3 + 1]], t2, n2);
};
var bi = (e3) => {
  const t2 = [], n2 = new Set, o3 = ((e4) => {
    const t3 = new Map;
    for (const n3 of e4)
      n3.portPointId && t3.set(n3.portPointId, n3);
    return t3;
  })(e3);
  for (const i4 of e3) {
    if (i4.prevPortPointId) {
      const e4 = o3.get(i4.prevPortPointId);
      e4 && e4.connectionName === i4.connectionName && _i([e4, i4], n2, t2);
    }
    if (i4.nextPortPointId) {
      const e4 = o3.get(i4.nextPortPointId);
      e4 && e4.connectionName === i4.connectionName && _i([i4, e4], n2, t2);
    }
  }
  if (t2.length === 0)
    return yi(e3, n2, t2), t2;
  const i3 = ((e4) => {
    const t3 = new Set;
    for (const [n3, o4] of e4)
      n3.portPointId && t3.add(n3.portPointId), o4.portPointId && t3.add(o4.portPointId);
    return t3;
  })(t2), r3 = e3.filter((e4) => !e4.portPointId || !i3.has(e4.portPointId));
  return yi(r3, n2, t2), t2;
};
function xi(e3, t2, n2) {
  return Math.max(t2, Math.min(n2, e3));
}
function vi(e3) {
  const t2 = e3.planeSize * e3.layers, n2 = e3.connectionCount, o3 = Math.sqrt(n2), i3 = Math.max(1, e3.maxIterations), r3 = xi(Math.round(t2 * (8 + 1.2 * o3)), 150000, 12000000), s2 = xi(Math.round(r3 * e3.effort), 150000, 12000000), a3 = xi(Math.round(0.2 * i3), 150000, 2000000);
  return { maxIterationsIters: Math.max(1, Math.min(i3, Math.max(a3, s2))), baseSearchBudgetIters: xi(Math.round(t2 * (10 + 0.8 * o3) * e3.effort), 50000, 4000000) };
}
function Ii(e3, t2) {
  for (let n2 = e3;n2; n2 = n2.prev)
    if (n2.id === t2)
      return true;
  return false;
}
var Si = class {
  f = [];
  seq = [];
  id = [];
  n = 0;
  push(e3, t2, n2) {
    let o3 = this.n++;
    for (;o3 > 0; ) {
      const n3 = o3 - 1 >> 1, i3 = this.f[n3], r3 = this.seq[n3];
      if (i3 !== e3 ? i3 < e3 : r3 < t2)
        break;
      this.f[o3] = i3, this.seq[o3] = r3, this.id[o3] = this.id[n3], o3 = n3;
    }
    this.f[o3] = e3, this.seq[o3] = t2, this.id[o3] = n2;
  }
  pop() {
    const e3 = 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)), e3;
  }
  get size() {
    return this.n;
  }
  clear() {
    this.n = 0;
  }
  siftDown(e3) {
    const t2 = this.f[e3], n2 = this.seq[e3], o3 = this.id[e3];
    for (;; ) {
      const o4 = 2 * e3 + 1, i3 = o4 + 1;
      if (o4 >= this.n)
        break;
      let r3 = o4;
      i3 < this.n && !this.less(o4, i3) && (r3 = i3);
      const s2 = this.f[r3];
      if (t2 !== s2 ? t2 < s2 : n2 < this.seq[r3])
        break;
      this.f[e3] = s2, this.seq[e3] = this.seq[r3], this.id[e3] = this.id[r3], e3 = r3;
    }
    this.f[e3] = t2, this.seq[e3] = n2, this.id[e3] = o3;
  }
  less(e3, t2) {
    const n2 = this.f[e3], o3 = this.f[t2];
    return n2 !== o3 ? n2 < o3 : this.seq[e3] < this.seq[t2];
  }
};
var Ci = [-1, -1, -1, 0, 0, 1, 1, 1];
var Pi = [-1, 0, 1, -1, 1, -1, 0, 1];
var Mi = class extends BaseSolver {
  getSolverName() {
    return "HighDensitySolverA01";
  }
  nodeWithPortPoints;
  cellSizeMm;
  viaDiameter;
  MAX_RIPS;
  maxCellCount;
  traceThickness;
  traceMargin;
  viaMinDistFromBorder;
  showPenaltyMap;
  showUsedCellMap;
  effort;
  stepMultiplier;
  hyperParameters;
  initialPenaltyFn;
  useExactViaTraceClearance = false;
  ripHistoryCostMultiplier = 0;
  rows;
  cols;
  layers;
  gridOrigin;
  gridToBoundsTransform;
  availableZ;
  zToLayer;
  layerToZ;
  connNameToId;
  connIdToName;
  connIdToRootNet;
  overlapFriendlyRootNets;
  planeSize;
  usedCellsFlat;
  portOwnerFlat;
  usedDiagFlat;
  penalty2d;
  visitedStamp;
  bestQueuedCost;
  sharedCrossRootPortCells;
  stamp = 0;
  viaOccupantScanOffsetsDr;
  viaOccupantScanOffsetsDc;
  viaOccupantScanOffsetsLen;
  viaOwnersByCell;
  viaCenterIndicesByConn;
  viaTraceClearanceMm;
  outputCellStepX;
  outputCellStepY;
  minViaRow;
  maxViaRow;
  minViaCol;
  maxViaCol;
  usedIndicesByConn;
  usedDiagIndicesByConn;
  unsolvedSegs;
  solvedRoutes;
  activeConnSeg = null;
  activeConnId = -1;
  crossLayerSearch = false;
  nodePool;
  heap;
  seqCounter = 0;
  _viaOccs = [];
  viaOccupantsByCell = new Map;
  ripCount;
  totalRipEvents = 0;
  searchIterations = 0;
  consecutiveSkips = 0;
  penaltyCap;
  baseSearchBudgetIters;
  _moveCost = 0;
  _moveRipped = null;
  get unsolvedConnections() {
    return this.unsolvedSegs;
  }
  get solvedConnectionsMap() {
    return this.solvedRoutes;
  }
  get activeConnection() {
    if (!this.activeConnSeg)
      return null;
    const e3 = this.activeConnSeg;
    return { connectionName: this.connIdToName[e3.connId] ?? "", start: { row: e3.startRow, col: e3.startCol, z: e3.startZ, x: 0, y: 0 }, end: { row: e3.endRow, col: e3.endCol, z: e3.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) };
  }
  constructor(e3) {
    super(), this.nodeWithPortPoints = e3.nodeWithPortPoints, this.cellSizeMm = e3.cellSizeMm, this.viaDiameter = e3.viaDiameter, this.maxCellCount = e3.maxCellCount, this.traceThickness = e3.traceThickness ?? 0.1, this.traceMargin = e3.traceMargin ?? 0.15, this.viaMinDistFromBorder = e3.viaMinDistFromBorder ?? 0.15, this.showPenaltyMap = e3.showPenaltyMap ?? false, this.showUsedCellMap = e3.showUsedCellMap ?? false, this.effort = e3.effort ?? 1, this.stepMultiplier = Math.max(1, Math.floor(e3.stepMultiplier ?? 1)), this.hyperParameters = { shuffleSeed: 0, ripCost: 10, ripTracePenalty: 0.5, ripViaPenalty: 0.75, viaBaseCost: 0.1, greedyMultiplier: 1.5, ...e3.hyperParameters }, this.MAX_ITERATIONS = 1e8, this.MAX_RIPS = 200, this.initialPenaltyFn = e3.initialPenaltyFn;
  }
  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() {
    const { nodeWithPortPoints: e3, cellSizeMm: t2 } = this, { width: n2, height: o3, center: i3 } = e3;
    this.availableZ = e3.availableZ ?? [...new Set(e3.portPoints.map((e4) => e4.z))].sort((e4, t3) => e4 - t3), this.rows = Math.floor(o3 / t2), this.cols = Math.floor(n2 / t2), this.layers = this.availableZ.length, this.planeSize = this.rows * this.cols;
    const r3 = this.layers * this.planeSize;
    if (this.maxCellCount !== undefined && r3 > this.maxCellCount)
      return this.error = `Cell count ${r3} exceeds maxCellCount ${this.maxCellCount}`, void (this.failed = true);
    const s2 = 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 e4 = 0;e4 < this.availableZ.length; e4++) {
      const t3 = this.availableZ[e4];
      this.zToLayer.set(t3, e4), this.layerToZ.set(e4, t3);
    }
    if (this.gridOrigin = { x: i3.x - n2 / 2, y: i3.y - o3 / 2 }, this.gridToBoundsTransform = function(e4) {
      const { originX: t3, originY: n3, rows: o4, cols: i4, cellSizeMm: r4, width: s3, height: a4 } = e4;
      let c4, l4, h2, d2;
      return i4 > 1 ? (c4 = s3 / ((i4 - 1) * r4), l4 = t3 * (1 - c4) - 0.5 * r4 * c4) : (c4 = 1, l4 = t3 + s3 / 2 - (t3 + 0.5 * r4)), o4 > 1 ? (h2 = a4 / ((o4 - 1) * r4), d2 = n3 * (1 - h2) - 0.5 * r4 * h2) : (h2 = 1, d2 = n3 + a4 / 2 - (n3 + 0.5 * r4)), { a: c4, b: 0, c: l4, d: 0, e: h2, f: d2 };
    }({ originX: this.gridOrigin.x, originY: this.gridOrigin.y, rows: this.rows, cols: this.cols, cellSizeMm: t2, width: n2, height: o3 }), this.outputCellStepX = this.cols > 1 ? n2 / (this.cols - 1) : n2, this.outputCellStepY = this.rows > 1 ? o3 / (this.rows - 1) : o3, this.connNameToId = new Map, this.connIdToName = [], this.connIdToRootNet = [], this.overlapFriendlyRootNets = new Set, this.penalty2d = new Float64Array(this.planeSize), this.initialPenaltyFn)
      for (let e4 = 0;e4 < this.rows; e4++) {
        const n3 = e4 * this.cols;
        for (let o4 = 0;o4 < this.cols; o4++) {
          const i4 = this.gridOrigin.x + (o4 + 0.5) * t2, r4 = this.gridOrigin.y + (e4 + 0.5) * t2, s3 = (o4 + 0.5) / this.cols, a4 = (e4 + 0.5) / this.rows;
          this.penalty2d[n3 + o4] = this.initialPenaltyFn({ x: i4, y: r4, px: s3, py: a4, row: e4, col: o4 });
        }
      }
    this.usedCellsFlat = new Int32Array(r3).fill(-1), this.portOwnerFlat = new Int32Array(r3).fill(-1), this.usedDiagFlat = new Int32Array(s2).fill(-1), this.visitedStamp = new Uint32Array(r3), this.bestQueuedCost = new Float64Array(r3), this.stamp = 0;
    const a3 = function(e4) {
      const t3 = e4.radiusMm / e4.cellSizeMm, n3 = Math.round(t3), o4 = Math.abs(t3 - n3) <= 0.000000001 ? n3 : Math.ceil(t3), i4 = o4 * o4, r4 = [], s3 = [];
      for (let e5 = -o4;e5 <= o4; e5++)
        for (let t4 = -o4;t4 <= o4; t4++)
          e5 * e5 + t4 * t4 <= i4 && (r4.push(e5), s3.push(t4));
      return { rowOffsets: new Int32Array(r4), columnOffsets: new Int32Array(s3), length: r4.length };
    }({ radiusMm: this.viaDiameter / 2, cellSizeMm: t2 });
    if (this.viaOccupantScanOffsetsLen = a3.length, this.viaOccupantScanOffsetsDr = a3.rowOffsets, this.viaOccupantScanOffsetsDc = a3.columnOffsets, this.viaOwnersByCell = new Map, this.viaCenterIndicesByConn = [], this.viaTraceClearanceMm = this.viaDiameter / 2 + this.traceThickness / 2, this.viaMinDistFromBorder > 0) {
      const e4 = Math.ceil(this.viaMinDistFromBorder / t2);
      this.minViaRow = e4, this.maxViaRow = this.rows - 1 - e4, this.minViaCol = e4, this.maxViaCol = this.cols - 1 - e4;
    } 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;
    const c3 = new Map;
    for (const e4 of this.nodeWithPortPoints.portPoints) {
      const t3 = this.connNameToId.get(e4.connectionName);
      if (t3 === undefined)
        continue;
      const n3 = this.pointToCell(e4), o4 = (n3.z * this.rows + n3.row) * this.cols + n3.col, i4 = this.connIdToRootNet[t3], r4 = c3.get(o4);
      r4 === undefined ? c3.set(o4, i4) : r4 !== i4 && this.sharedCrossRootPortCells.add(o4);
      const s3 = this.portOwnerFlat[o4];
      this.portOwnerFlat[o4] = s3 === -1 || s3 === t3 ? t3 : -2;
    }
    this.solvedRoutes = new Map, this.usedIndicesByConn = [], this.usedDiagIndicesByConn = [], this.ripCount = [], this.consecutiveSkips = 0, this.penaltyCap = 0.5 * this.hyperParameters.ripCost, this.shuffleConnections();
    const l3 = vi({ planeSize: this.planeSize, layers: this.layers, connectionCount: this.unsolvedSegs.length, effort: this.effort, maxIterations: this.MAX_ITERATIONS });
    this.baseSearchBudgetIters = l3.baseSearchBudgetIters, this.MAX_ITERATIONS = l3.maxIterationsIters, this.activeConnSeg = null, this.activeConnId = -1, this.nodePool = [], this.heap = new Si, this.seqCounter = 0;
  }
  _step() {
    for (let e3 = 0;e3 < this.stepMultiplier; e3++) {
      if (this.solved || this.failed)
        return;
      this.stepOnce();
    }
  }
  stepOnce() {
    if (!this.activeConnSeg) {
      if (this.unsolvedSegs.length === 0)
        return void (this.solved = true);
      const e4 = this.unsolvedSegs.shift();
      this.activeConnSeg = e4, this.activeConnId = e4.connId, this.crossLayerSearch = e4.startZ !== e4.endZ, this.viaOccupantsByCell.clear(), this.nodePool = [], this.heap.clear(), this.bestQueuedCost.fill(Number.NaN), this.seqCounter = 0, this.searchIterations = 0, this.nextStamp();
      const t3 = this.computeH(e4.startZ, e4.startRow, e4.startCol, e4.endZ, e4.endRow, e4.endCol) * this.hyperParameters.greedyMultiplier;
      this.nodePool.push({ z: e4.startZ, row: e4.startRow, col: e4.startCol, g: 0, parentIdx: -1, ripped: null });
      const n3 = (e4.startZ * this.rows + e4.startRow) * this.cols + e4.startCol;
      return this.bestQueuedCost[n3] = t3, void this.heap.push(t3, this.seqCounter++, 0);
    }
    this.searchIterations++;
    const e3 = this.ripCount[this.activeConnId] ?? 0, t2 = Math.round(this.baseSearchBudgetIters * (1 + 0.25 * Math.min(e3, 10)));
    if (this.searchIterations > t2) {
      const e4 = this.penalty2d;
      for (let t3 = 0;t3 < e4.length; t3++)
        e4[t3] = 0.9 * e4[t3];
      return this.unsolvedSegs.push(this.activeConnSeg), this.activeConnSeg = null, this.activeConnId = -1, this.heap.clear(), this.nodePool = [], this.consecutiveSkips++, void (this.consecutiveSkips >= 3 * this.unsolvedSegs.length && (this.error = `Convergence failure: ${this.unsolvedSegs.length} connections stuck`, this.failed = true));
    }
    if (this.heap.size === 0)
      return this.error = `No path found for ${this.connIdToName[this.activeConnId]}`, void (this.failed = true);
    const n2 = this.heap.pop();
    if (n2 === -1)
      return;
    const o3 = this.nodePool[n2], { z: i3, row: r3, col: s2, g: a3, ripped: c3 } = o3, l3 = (i3 * this.rows + r3) * this.cols + s2;
    if (this.visitedStamp[l3] === this.stamp)
      return;
    this.visitedStamp[l3] = this.stamp;
    const h2 = this.activeConnSeg;
    if (i3 === h2.endZ && r3 === h2.endRow && s2 === h2.endCol)
      return this.finalizeRoute(n2), this.activeConnSeg = null, void (this.activeConnId = -1);
    const { endZ: d2, endRow: u2, endCol: p3 } = h2, m2 = this.activeConnId, g2 = this.rows, f2 = this.cols, _2 = (this.cellSizeMm, this.visitedStamp), y2 = this.stamp;
    for (let e4 = 0;e4 < 8; e4++) {
      const t3 = r3 + Ci[e4], o4 = s2 + Pi[e4];
      if (t3 < 0 || t3 >= g2 || o4 < 0 || o4 >= f2)
        continue;
      const l4 = (i3 * g2 + t3) * f2 + o4;
      if (_2[l4] === y2)
        continue;
      if (this.computeMoveCostAndRips(m2, i3, r3, s2, i3, t3, o4, c3), this._moveCost < 0)
        continue;
      const h3 = a3 + this._moveCost, b2 = h3 + this.computeH(i3, t3, o4, d2, u2, p3) * this.hyperParameters.greedyMultiplier;
      if (b2 >= this.bestQueuedCost[l4]) {
        this.heap.push(b2, this.seqCounter++, -1);
        continue;
      }
      this.bestQueuedCost[l4] = b2;
      const x2 = this.nodePool.length;
      this.nodePool.push({ z: i3, row: t3, col: o4, g: h3, parentIdx: n2, ripped: this._moveRipped }), this.heap.push(b2, this.seqCounter++, x2);
    }
    if (r3 >= this.minViaRow && r3 <= this.maxViaRow && s2 >= this.minViaCol && s2 <= this.maxViaCol)
      for (let e4 = 0;e4 < this.layers; e4++) {
        if (e4 === i3)
          continue;
        const t3 = (e4 * g2 + r3) * f2 + s2;
        if (_2[t3] === y2)
          continue;
        if (this.computeMoveCostAndRips(m2, i3, r3, s2, e4, r3, s2, c3), this._moveCost < 0)
          continue;
        const o4 = a3 + this._moveCost, l4 = o4 + this.computeH(e4, r3, s2, d2, u2, p3) * this.hyperParameters.greedyMultiplier;
        if (l4 >= this.bestQueuedCost[t3]) {
          this.heap.push(l4, this.seqCounter++, -1);
          continue;
        }
        this.bestQueuedCost[t3] = l4;
        const h3 = this.nodePool.length;
        this.nodePool.push({ z: e4, row: r3, col: s2, g: o4, parentIdx: n2, ripped: this._moveRipped }), this.heap.push(l4, this.seqCounter++, h3);
      }
  }
  getRipCost(e3) {
    return this.hyperParameters.ripCost * (1 + this.ripHistoryCostMultiplier * (this.ripCount[e3] ?? 0));
  }
  computeMoveCostAndRips(e3, t2, n2, o3, i3, r3, s2, a3) {
    let c3 = 0, l3 = a3;
    const h2 = this.cols;
    if (t2 !== i3) {
      c3 += this.hyperParameters.viaBaseCost, c3 += Math.min(this.penalty2d[r3 * h2 + s2], this.penaltyCap);
      const t3 = (i3 * this.rows + r3) * h2 + s2, n3 = this.portOwnerFlat[t3];
      if (n3 >= 0 && n3 !== e3) {
        const t4 = this.connIdToRootNet[n3] === this.connIdToRootNet[e3] && this.overlapFriendlyRootNets.has(this.connIdToRootNet[e3]), o5 = this.activeConnSeg, a4 = !!o5 && i3 === o5.endZ && r3 === o5.endRow && s2 === o5.endCol;
        if (!t4 && !a4)
          return this._moveCost = -1, void (this._moveRipped = l3);
      }
      this.fillViaOccupants(r3, s2, e3);
      const o4 = this._viaOccs;
      for (let e4 = 0;e4 < o4.length; e4++) {
        const t4 = o4[e4];
        Ii(l3, t4) || (c3 += this.getRipCost(t4), l3 = { id: t4, prev: l3 }), c3 += this.hyperParameters.ripViaPenalty;
      }
    } else {
      const t3 = n2 > r3 ? n2 - r3 : r3 - n2, a4 = o3 > s2 ? o3 - s2 : s2 - o3;
      c3 += (t3 + a4 > 1 ? Math.SQRT2 : 1) * this.cellSizeMm, c3 += Math.min(this.penalty2d[r3 * h2 + s2], this.penaltyCap);
      const d2 = (i3 * this.rows + r3) * h2 + s2, u2 = this.portOwnerFlat[d2];
      if (u2 >= 0 && u2 !== e3) {
        const t4 = this.connIdToRootNet[u2] === this.connIdToRootNet[e3] && this.overlapFriendlyRootNets.has(this.connIdToRootNet[e3]), n3 = this.activeConnSeg, o4 = !!n3 && i3 === n3.endZ && r3 === n3.endRow && s2 === n3.endCol;
        if (!t4 && !o4)
          return this._moveCost = -1, void (this._moveRipped = l3);
      }
      const p3 = this.usedCellsFlat[d2];
      if (p3 >= 0 && p3 !== e3) {
        this.connIdToRootNet[p3] === this.connIdToRootNet[e3] && this.overlapFriendlyRootNets.has(this.connIdToRootNet[e3]) || (Ii(l3, p3) || (c3 += this.getRipCost(p3), l3 = { id: p3, prev: l3 }), c3 += this.hyperParameters.ripTracePenalty);
      }
      if (this.viaOwnersByCell.size > 0) {
        this.fillTraceSegmentViaOccupants(n2, o3, r3, s2, e3);
        const t4 = this._viaOccs;
        for (let e4 = 0;e4 < t4.length; e4++) {
          const n3 = t4[e4];
          Ii(l3, n3) || (c3 += this.getRipCost(n3), l3 = { id: n3, prev: l3 }), c3 += this.hyperParameters.ripViaPenalty;
        }
      }
      if (t3 === 1 && a4 === 1) {
        const t4 = n2 < r3 ? n2 : r3, a5 = o3 < s2 ? o3 : s2, c4 = 1 ^ (n2 < r3 && o3 < s2 || n2 > r3 && o3 > s2 ? 0 : 1), h3 = this.cols - 1, d3 = 2 * ((i3 * (this.rows - 1) + t4) * h3 + a5), u3 = this.usedDiagFlat[d3 + c4];
        if (u3 >= 0 && u3 !== e3) {
          if (!(this.connIdToRootNet[u3] === this.connIdToRootNet[e3] && this.overlapFriendlyRootNets.has(this.connIdToRootNet[e3])))
            return this._moveCost = -1, void (this._moveRipped = l3);
        }
      }
    }
    this._moveCost = c3, this._moveRipped = l3;
  }
  fillViaOccupants(e3, t2, n2) {
    const o3 = this._viaOccs;
    o3.length = 0;
    const i3 = e3 * this.cols + t2, r3 = this.viaOccupantsByCell.get(i3);
    if (r3) {
      for (const e4 of r3)
        o3.push(e4);
      return;
    }
    const s2 = this.rows, a3 = this.cols, c3 = this.viaOccupantScanOffsetsDr, l3 = this.viaOccupantScanOffsetsDc, h2 = this.viaOccupantScanOffsetsLen, d2 = this.usedCellsFlat;
    for (let i4 = 0;i4 < this.layers; i4++) {
      const r4 = i4 * this.planeSize;
      for (let i5 = 0;i5 < h2; i5++) {
        const h3 = e3 + c3[i5], u2 = t2 + l3[i5];
        if (h3 < 0 || u2 < 0 || h3 >= s2 || u2 >= a3)
          continue;
        const p3 = d2[r4 + h3 * a3 + u2];
        if (p3 === -1 || p3 === n2)
          continue;
        if (this.connIdToRootNet[p3] === this.connIdToRootNet[n2] && this.overlapFriendlyRootNets.has(this.connIdToRootNet[n2]))
          continue;
        let m2 = false;
        for (let e4 = 0;e4 < o3.length; e4++)
          if (o3[e4] === p3) {
            m2 = true;
            break;
          }
        m2 || o3.push(p3);
      }
    }
    this.viaOccupantsByCell.set(i3, o3.slice());
  }
  fillTraceSegmentViaOccupants(e3, t2, n2, o3, i3) {
    const r3 = this._viaOccs;
    r3.length = 0;
    const s2 = Math.min(e3, n2), a3 = Math.max(e3, n2), c3 = Math.min(t2, o3), l3 = Math.max(t2, o3), h2 = this.viaTraceClearanceMm / this.outputCellStepY, d2 = this.viaTraceClearanceMm / this.outputCellStepX, u2 = (o3 - t2) * this.outputCellStepX, p3 = (n2 - e3) * this.outputCellStepY, m2 = u2 * u2 + p3 * p3, g2 = this.viaTraceClearanceMm * this.viaTraceClearanceMm;
    for (const [n3, o4] of this.viaOwnersByCell) {
      const f2 = Math.floor(n3 / this.cols), _2 = n3 - f2 * this.cols;
      if (f2 < s2 - h2 || f2 > a3 + h2 || _2 < c3 - d2 || _2 > l3 + d2)
        continue;
      const y2 = (_2 - t2) * this.outputCellStepX, b2 = (f2 - e3) * this.outputCellStepY, x2 = m2 === 0 ? 0 : Math.max(0, Math.min(1, (y2 * u2 + b2 * p3) / m2)), v2 = y2 - u2 * x2, I2 = b2 - p3 * x2;
      if (!(v2 * v2 + I2 * I2 >= g2))
        for (const e4 of o4) {
          if (e4 === i3)
            continue;
          this.connIdToRootNet[e4] === this.connIdToRootNet[i3] && this.overlapFriendlyRootNets.has(this.connIdToRootNet[i3]) || (r3.includes(e4) || r3.push(e4));
        }
    }
  }
  shouldSkipFixedPortHalo(e3, t2) {
    const n2 = this.portOwnerFlat[e3];
    if (n2 === t2)
      return false;
    if (n2 === -2)
      return true;
    if (n2 < 0)
      return false;
    return !(this.connIdToRootNet[n2] === this.connIdToRootNet[t2] && this.overlapFriendlyRootNets.has(this.connIdToRootNet[t2]));
  }
  nextStamp() {
    this.stamp = this.stamp + 1 >>> 0, this.stamp === 0 && (this.visitedStamp.fill(0), this.stamp = 1);
  }
  computeH(e3, t2, n2, o3, i3, r3) {
    const s2 = Math.abs(t2 - i3) + Math.abs(n2 - r3);
    if (e3 === o3)
      return s2 * this.cellSizeMm;
    if (!this.crossLayerSearch)
      return s2 * this.cellSizeMm + this.hyperParameters.viaBaseCost;
    const a3 = Math.max(this.minViaRow, Math.min(this.maxViaRow, t2)), c3 = Math.max(this.minViaCol, Math.min(this.maxViaCol, n2)), l3 = Math.max(this.minViaRow, Math.min(this.maxViaRow, i3)), h2 = Math.max(this.minViaCol, Math.min(this.maxViaCol, r3)), d2 = Math.abs(t2 - a3) + Math.abs(n2 - c3) + Math.abs(a3 - i3) + Math.abs(c3 - r3), u2 = Math.abs(t2 - l3) + Math.abs(n2 - h2) + Math.abs(l3 - i3) + Math.abs(h2 - r3);
    return Math.max(Math.min(d2, u2), s2) * this.cellSizeMm + this.hyperParameters.viaBaseCost;
  }
  internConn(e3, t2) {
    const n2 = this.connNameToId.get(e3);
    if (n2 !== undefined)
      return n2;
    const o3 = this.connIdToName.length;
    var i3;
    return this.connIdToName.push(e3), this.connIdToRootNet.push((i3 = e3, t2 ?? i3.replace(/_mst\d+$/, ""))), this.connNameToId.set(e3, o3), o3;
  }
  buildConnectionSegs() {
    const e3 = new Map;
    for (const t3 of this.nodeWithPortPoints.portPoints) {
      const n3 = t3.connectionName;
      e3.has(n3) || e3.set(n3, { points: [], rootConnectionName: t3.rootConnectionName }), e3.get(n3).points.push(t3);
    }
    const t2 = [], n2 = new Set;
    for (const [o3, i3] of e3) {
      const e4 = i3.points, r3 = bi(e4);
      if (r3.length === 0)
        continue;
      const s2 = this.internConn(o3, i3.rootConnectionName);
      for (const [e5, a3] of r3) {
        const r4 = this.pointToCell(e5), c3 = this.pointToCell(a3), l3 = `${r4.z}:${r4.row}:${r4.col}`, h2 = `${c3.z}:${c3.row}:${c3.col}`, d2 = l3 < h2 ? `${l3}|${h2}` : `${h2}|${l3}`, u2 = i3.rootConnectionName ?? o3, p3 = `${u2}|${d2}`;
        n2.has(p3) ? this.overlapFriendlyRootNets.add(u2) : (n2.add(p3), t2.push({ connId: s2, startZ: r4.z, startRow: r4.row, startCol: r4.col, startPoint: e5, endZ: c3.z, endRow: c3.row, endCol: c3.col, endPoint: a3 }));
      }
    }
    return t2;
  }
  pointToCell(e3) {
    const t2 = Math.max(0, Math.min(this.cols - 1, Math.round((e3.x - this.gridOrigin.x) / this.cellSizeMm - 0.5))), n2 = Math.max(0, Math.min(this.rows - 1, Math.round((e3.y - this.gridOrigin.y) / this.cellSizeMm - 0.5)));
    return { z: this.zToLayer.get(e3.z) ?? 0, row: n2, col: t2 };
  }
  shuffleConnections() {
    const e3 = this.unsolvedSegs;
    let t2 = this.hyperParameters.shuffleSeed;
    const n2 = () => (t2 = 1664525 * t2 + 1013904223 & 4294967295, (t2 >>> 0) / 4294967295);
    for (let t3 = e3.length - 1;t3 > 0; t3--) {
      const o3 = Math.floor(n2() * (t3 + 1)), i3 = e3[t3];
      e3[t3] = e3[o3], e3[o3] = i3;
    }
  }
  finalizeRoute(e3) {
    this.consecutiveSkips = Math.max(0, this.consecutiveSkips - 1);
    const t2 = [];
    let n2 = e3;
    for (;n2 >= 0; ) {
      const e4 = this.nodePool[n2];
      t2.push({ z: e4.z, row: e4.row, col: e4.col }), n2 = e4.parentIdx;
    }
    for (t2.reverse();t2.length > 1; ) {
      const e4 = t2[0], n3 = (e4.z * this.rows + e4.row) * this.cols + e4.col;
      if (!this.sharedCrossRootPortCells.has(n3))
        break;
      t2.shift();
    }
    for (;t2.length > 1; ) {
      const e4 = t2[t2.length - 1], n3 = (e4.z * this.rows + e4.row) * this.cols + e4.col;
      if (!this.sharedCrossRootPortCells.has(n3))
        break;
      t2.pop();
    }
    const o3 = [];
    for (let e4 = 1;e4 < t2.length; e4++)
      t2[e4].z !== t2[e4 - 1].z && o3.push({ row: t2[e4].row, col: t2[e4].col });
    const i3 = t2[0], r3 = t2[t2.length - 1], s2 = this.activeConnId, a3 = [];
    for (let t3 = this.nodePool[e3].ripped;t3; t3 = t3.prev)
      a3.push(t3.id);
    for (let e4 = 0;e4 < a3.length; e4++)
      if (this.ripTrace(a3[e4]), this.failed)
        return;
    const c3 = Math.ceil(this.traceMargin / this.cellSizeMm), l3 = [], h2 = this.rows, d2 = this.cols, u2 = this.usedCellsFlat;
    for (let e4 = 0;e4 < t2.length; e4++) {
      const n3 = t2[e4];
      for (let e5 = -c3;e5 <= c3; e5++)
        for (let t3 = -c3;t3 <= c3; t3++) {
          const o4 = n3.row + e5, i4 = n3.col + t3;
          if (o4 < 0 || o4 >= h2 || i4 < 0 || i4 >= d2)
            continue;
          const r4 = (n3.z * h2 + o4) * d2 + i4;
          if ((o4 !== n3.row || i4 !== n3.col) && this.shouldSkipFixedPortHalo(r4, s2))
            continue;
          const a4 = u2[r4], c4 = this.connIdToRootNet[a4] === this.connIdToRootNet[s2] && this.overlapFriendlyRootNets.has(this.connIdToRootNet[s2]);
          (a4 === -1 || a4 === s2 || c4) && (u2[r4] = s2, l3.push(r4));
        }
    }
    const p3 = [], m2 = this.viaOccupantScanOffsetsDr, g2 = this.viaOccupantScanOffsetsDc, f2 = this.viaOccupantScanOffsetsLen;
    for (let e4 = 0;e4 < o3.length; e4++) {
      const t3 = o3[e4];
      for (let e5 = 0;e5 < this.layers; e5++) {
        const n3 = e5 * this.planeSize;
        for (let e6 = 0;e6 < f2; e6++) {
          const o4 = t3.row + m2[e6], i4 = t3.col + g2[e6];
          if (o4 < 0 || o4 >= h2 || i4 < 0 || i4 >= d2)
            continue;
          const r4 = n3 + o4 * d2 + i4;
          if ((o4 !== t3.row || i4 !== t3.col) && this.shouldSkipFixedPortHalo(r4, s2))
            continue;
          const a4 = u2[r4], c4 = this.connIdToRootNet[a4] === this.connIdToRootNet[s2] && this.overlapFriendlyRootNets.has(this.connIdToRootNet[s2]);
          if (a4 !== -1 && a4 !== s2 && !c4) {
            let e7 = false;
            for (let t4 = 0;t4 < p3.length; t4++)
              if (p3[t4] === a4) {
                e7 = true;
                break;
              }
            e7 || p3.push(a4);
          }
          u2[r4] = s2, l3.push(r4);
        }
      }
    }
    const _2 = [], y2 = this.cols - 1;
    for (let e4 = 1;e4 < t2.length; e4++) {
      const n3 = t2[e4 - 1], o4 = t2[e4];
      if (n3.z !== o4.z)
        continue;
      const i4 = n3.row > o4.row ? n3.row - o4.row : o4.row - n3.row, r4 = n3.col > o4.col ? n3.col - o4.col : o4.col - n3.col;
      if (i4 !== 1 || r4 !== 1)
        continue;
      const a4 = n3.row < o4.row ? n3.row : o4.row, c4 = n3.col < o4.col ? n3.col : o4.col, l4 = n3.row < o4.row && n3.col < o4.col || n3.row > o4.row && n3.col > o4.col ? 0 : 1, h3 = 1 ^ l4, d3 = 2 * ((n3.z * (this.rows - 1) + a4) * y2 + c4), u3 = d3 + h3, p4 = this.usedDiagFlat[u3], m3 = this.connIdToRootNet[p4] === this.connIdToRootNet[s2] && this.overlapFriendlyRootNets.has(this.connIdToRootNet[s2]);
      if (p4 !== -1 && p4 !== s2 && !m3)
        continue;
      const g3 = d3 + l4;
      this.usedDiagFlat[g3] = s2, _2.push(g3);
    }
    for (;this.usedIndicesByConn.length <= s2; )
      this.usedIndicesByConn.push([]);
    const b2 = this.usedIndicesByConn[s2] ?? [];
    for (b2.push(...l3), this.usedIndicesByConn[s2] = b2;this.usedDiagIndicesByConn.length <= s2; )
      this.usedDiagIndicesByConn.push([]);
    const x2 = this.usedDiagIndicesByConn[s2] ?? [];
    x2.push(..._2), this.usedDiagIndicesByConn[s2] = x2;
    const v2 = this.solvedRoutes.get(s2) ?? [];
    if (v2.push({ connId: s2, startZ: i3.z, startRow: i3.row, startCol: i3.col, startPoint: this.activeConnSeg.startPoint, endZ: r3.z, endRow: r3.row, endCol: r3.col, endPoint: this.activeConnSeg.endPoint, cells: t2, viaCells: o3 }), this.solvedRoutes.set(s2, v2), this.useExactViaTraceClearance) {
      for (;this.viaCenterIndicesByConn.length <= s2; )
        this.viaCenterIndicesByConn.push([]);
      const e4 = this.viaCenterIndicesByConn[s2] ?? [];
      for (const t3 of o3) {
        const n3 = t3.row * this.cols + t3.col, o4 = this.viaOwnersByCell.get(n3) ?? new Set;
        o4.has(s2) || (o4.add(s2), e4.push(n3)), this.viaOwnersByCell.set(n3, o4);
      }
      this.viaCenterIndicesByConn[s2] = e4;
    }
    for (let e4 = 0;e4 < p3.length; e4++)
      if (this.ripTrace(p3[e4]), this.failed)
        return;
    if (a3.length > 0 || p3.length > 0) {
      const e4 = this.penalty2d, t3 = this.penaltyCap;
      if (this.totalRipEvents > 50)
        for (let t4 = 0;t4 < e4.length; t4++)
          e4[t4] = 0.99 * e4[t4];
      else
        for (let n3 = 0;n3 < e4.length; n3++)
          e4[n3] > t3 && (e4[n3] = 0.5 * e4[n3]);
    }
  }
  ripTrace(e3) {
    for (;this.ripCount.length <= e3; )
      this.ripCount.push(0);
    if (this.ripCount[e3]++, this.totalRipEvents++, this.totalRipEvents >= this.MAX_RIPS)
      return this.error = `Convergence failure: exceeded MAX_RIPS ${this.MAX_RIPS}`, void (this.failed = true);
    const t2 = this.solvedRoutes.get(e3) ?? [];
    if (t2.length > 0) {
      const e4 = this.cols;
      for (const n3 of t2) {
        for (let t3 = 0;t3 < n3.cells.length; t3++) {
          const o4 = n3.cells[t3], i4 = o4.row * e4 + o4.col;
          this.penalty2d[i4] = this.penalty2d[i4] + this.hyperParameters.ripTracePenalty;
        }
        for (let t3 = 0;t3 < n3.viaCells.length; t3++) {
          const o4 = n3.viaCells[t3], i4 = o4.row * e4 + o4.col;
          this.penalty2d[i4] = this.penalty2d[i4] + this.hyperParameters.ripViaPenalty;
        }
      }
    }
    const n2 = this.usedIndicesByConn[e3];
    if (n2) {
      const t3 = this.usedCellsFlat;
      for (let o4 = 0;o4 < n2.length; o4++) {
        const i4 = n2[o4];
        t3[i4] === e3 && (t3[i4] = -1);
      }
      this.usedIndicesByConn[e3] = [];
    }
    const o3 = this.usedDiagIndicesByConn[e3];
    if (o3) {
      const t3 = this.usedDiagFlat;
      for (let n3 = 0;n3 < o3.length; n3++) {
        const i4 = o3[n3];
        t3[i4] === e3 && (t3[i4] = -1);
      }
      this.usedDiagIndicesByConn[e3] = [];
    }
    const i3 = this.viaCenterIndicesByConn[e3];
    if (i3) {
      for (const t3 of i3) {
        const n3 = this.viaOwnersByCell.get(t3);
        n3 && (n3.delete(e3), n3.size === 0 && this.viaOwnersByCell.delete(t3));
      }
      this.viaCenterIndicesByConn[e3] = [];
    }
    if (t2.length > 0) {
      this.solvedRoutes.delete(e3);
      for (const n3 of t2)
        this.unsolvedSegs.push({ connId: e3, startZ: n3.startZ, startRow: n3.startRow, startCol: n3.startCol, startPoint: n3.startPoint, endZ: n3.endZ, endRow: n3.endRow, endCol: n3.endCol, endPoint: n3.endPoint });
    }
  }
  visualize() {
    const e3 = ["red", "blue", "orange", "green"], t2 = [], n2 = [], o3 = [], i3 = [], { width: r3, height: s2, center: a3 } = this.nodeWithPortPoints;
    i3.push({ center: { x: a3.x, y: a3.y }, width: r3, height: s2, stroke: "gray" });
    const c3 = this.gridToBoundsTransform;
    if (this.showPenaltyMap && this.penalty2d) {
      let e4 = 0;
      for (let t3 = 0;t3 < this.penalty2d.length; t3++)
        this.penalty2d[t3] > e4 && (e4 = this.penalty2d[t3]);
      if (e4 > 0)
        for (let t3 = 0;t3 < this.rows; t3++)
          for (let n3 = 0;n3 < this.cols; n3++) {
            const o4 = this.penalty2d[t3 * this.cols + n3];
            if (o4 <= 0)
              continue;
            const r4 = Math.min(0.6, o4 / e4 * 0.6), s3 = gi(c3, { x: this.gridOrigin.x + (n3 + 0.5) * this.cellSizeMm, y: this.gridOrigin.y + (t3 + 0.5) * this.cellSizeMm });
            i3.push({ center: s3, width: this.cellSizeMm * c3.a, height: this.cellSizeMm * c3.e, fill: `rgba(255,165,0,${r4.toFixed(3)})` });
          }
    }
    if (this.showUsedCellMap && this.usedCellsFlat)
      for (let e4 = 0;e4 < this.layers; e4++)
        for (let t3 = 0;t3 < this.rows; t3++)
          for (let n3 = 0;n3 < this.cols; n3++) {
            if (this.usedCellsFlat[(e4 * this.rows + t3) * this.cols + n3] === -1)
              continue;
            const o4 = gi(c3, { x: this.gridOrigin.x + (n3 + 0.5) * this.cellSizeMm, y: this.gridOrigin.y + (t3 + 0.5) * this.cellSizeMm });
            i3.push({ center: o4, width: this.cellSizeMm * c3.a, height: this.cellSizeMm * c3.e, fill: "rgba(0,0,255,0.5)" });
          }
    for (const n3 of this.nodeWithPortPoints.portPoints)
      t2.push({ x: n3.x, y: n3.y, color: e3[n3.z] ?? "gray", label: n3.connectionName });
    const l3 = ["rgba(255,0,0,0.75)", "rgba(0,0,255,0.75)", "rgba(255,165,0,0.75)", "rgba(0,128,0,0.75)"], h2 = this.getOutput();
    for (const e4 of h2) {
      if (e4.route.length < 2)
        continue;
      let t3 = 0;
      for (let o4 = 1;o4 < e4.route.length; o4++) {
        const i4 = e4.route[o4 - 1];
        e4.route[o4].z !== i4.z && (o4 - t3 >= 2 && n2.push({ points: e4.route.slice(t3, o4).map((e5) => ({ x: e5.x, y: e5.y })), strokeColor: l3[i4.z] ?? "rgba(128,128,128,0.75)", strokeWidth: this.traceThickness }), t3 = o4);
      }
      if (e4.route.length - t3 >= 2) {
        const o4 = e4.route[t3].z;
        n2.push({ points: e4.route.slice(t3).map((e5) => ({ x: e5.x, y: e5.y })), strokeColor: l3[o4] ?? "rgba(128,128,128,0.75)", strokeWidth: this.traceThickness });
      }
    }
    for (const e4 of h2)
      for (const t3 of e4.vias)
        o3.push({ center: { x: t3.x, y: t3.y }, radius: this.viaDiameter / 2, fill: "rgba(0,0,0,0.3)", stroke: "black" });
    if (this.activeConnSeg && this.visitedStamp) {
      const e4 = this.stamp;
      for (let n3 = 0;n3 < this.layers; n3++)
        for (let o4 = 0;o4 < this.rows; o4++)
          for (let i4 = 0;i4 < this.cols; i4++) {
            if (this.visitedStamp[(n3 * this.rows + o4) * this.cols + i4] !== e4)
              continue;
            const r4 = gi(c3, { x: this.gridOrigin.x + (i4 + 0.5) * this.cellSizeMm, y: this.gridOrigin.y + (o4 + 0.5) * this.cellSizeMm });
            t2.push({ x: r4.x, y: r4.y, color: "rgba(0,0,255,0.2)" });
          }
    }
    return { points: t2, lines: n2, circles: o3, rects: i3, coordinateSystem: "cartesian", title: `HighDensityA01 [${this.solvedRoutes?.size ?? 0} solved, ${this.unsolvedSegs?.length ?? 0} remaining]` };
  }
  getOutput() {
    const e3 = this.gridToBoundsTransform, t2 = [];
    for (const [n2, o3] of this.solvedRoutes ?? []) {
      const i3 = this.connIdToName[n2];
      for (const r3 of o3) {
        const o4 = r3.cells.map((t3) => {
          const n3 = this.gridOrigin.x + (t3.col + 0.5) * this.cellSizeMm, o5 = this.gridOrigin.y + (t3.row + 0.5) * this.cellSizeMm, i4 = gi(e3, { x: n3, y: o5 });
          return { x: i4.x, y: i4.y, z: this.layerToZ.get(t3.z) ?? t3.z };
        });
        o4.length > 0 && (o4[0] = { ...r3.startPoint }, o4.length > 1 && (o4[o4.length - 1] = { ...r3.endPoint })), t2.push({ connectionName: i3, rootConnectionName: this.connIdToRootNet[n2], regionId: this.nodeWithPortPoints.capacityMeshNodeId, traceThickness: this.traceThickness, viaDiameter: this.viaDiameter, route: o4, vias: r3.viaCells.map((t3) => {
          const n3 = this.gridOrigin.x + (t3.col + 0.5) * this.cellSizeMm, o5 = this.gridOrigin.y + (t3.row + 0.5) * this.cellSizeMm;
          return gi(e3, { x: n3, y: o5 });
        }) });
      }
    }
    return t2;
  }
};
var Ri = ["left", "top", "right", "bottom", "middle"];
var Ti = class {
  f = new Float64Array(1024);
  seq = new Uint32Array(1024);
  id = new Int32Array(1024);
  n = 0;
  push(e3, t2, n2) {
    this.ensureCapacity(this.n + 1);
    let o3 = this.n++;
    for (this.f[o3] = e3, this.seq[o3] = t2, this.id[o3] = n2;o3 > 0; ) {
      const e4 = o3 - 1 >> 1;
      if (this.less(e4, o3))
        break;
      this.swap(o3, e4), o3 = e4;
    }
  }
  pop() {
    const e3 = 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)), e3;
  }
  get size() {
    return this.n;
  }
  clear() {
    this.n = 0;
  }
  ensureCapacity(e3) {
    if (e3 <= this.f.length)
      return;
    let t2 = this.f.length;
    for (;t2 < e3; )
      t2 *= 2;
    const n2 = new Float64Array(t2);
    n2.set(this.f), this.f = n2;
    const o3 = new Uint32Array(t2);
    o3.set(this.seq), this.seq = o3;
    const i3 = new Int32Array(t2);
    i3.set(this.id), this.id = i3;
  }
  siftDown(e3) {
    for (;; ) {
      const t2 = 2 * e3 + 1, n2 = t2 + 1;
      if (t2 >= this.n)
        return;
      let o3 = t2;
      if (n2 < this.n && !this.less(t2, n2) && (o3 = n2), this.less(e3, o3))
        return;
      this.swap(e3, o3), e3 = o3;
    }
  }
  less(e3, t2) {
    const n2 = this.f[e3], o3 = this.f[t2];
    return n2 !== o3 ? n2 < o3 : this.seq[e3] < this.seq[t2];
  }
  swap(e3, t2) {
    const n2 = this.f[e3];
    this.f[e3] = this.f[t2], this.f[t2] = n2;
    const o3 = this.seq[e3];
    this.seq[e3] = this.seq[t2], this.seq[t2] = o3;
    const i3 = this.id[e3];
    this.id[e3] = this.id[t2], this.id[t2] = i3;
  }
};
var Ei = class {
  z = new Int32Array(1024);
  cellId = new Int32Array(1024);
  g = new Float64Array(1024);
  parent = new Int32Array(1024);
  ripHead = new Int32Array(1024).fill(-1);
  ripCount = new Int32Array(1024);
  length = 0;
  clear() {
    this.length = 0;
  }
  push(e3, t2, n2, o3, i3, r3) {
    this.ensureCapacity(this.length + 1);
    const s2 = this.length++;
    return this.z[s2] = e3, this.cellId[s2] = t2, this.g[s2] = n2, this.parent[s2] = o3, this.ripHead[s2] = i3, this.ripCount[s2] = r3, s2;
  }
  ensureCapacity(e3) {
    if (e3 <= this.z.length)
      return;
    let t2 = this.z.length;
    for (;t2 < e3; )
      t2 *= 2;
    const n2 = new Int32Array(t2);
    n2.set(this.z), this.z = n2;
    const o3 = new Int32Array(t2);
    o3.set(this.cellId), this.cellId = o3;
    const i3 = new Float64Array(t2);
    i3.set(this.g), this.g = i3;
    const r3 = new Int32Array(t2);
    r3.set(this.parent), this.parent = r3;
    const s2 = new Int32Array(t2);
    s2.fill(-1), s2.set(this.ripHead.subarray(0, this.length)), this.ripHead = s2;
    const a3 = new Int32Array(t2);
    a3.set(this.ripCount.subarray(0, this.length)), this.ripCount = a3;
  }
};
var Ai = class {
  connId = new Int32Array(1024);
  prev = new Int32Array(1024).fill(-1);
  length = 0;
  clear() {
    this.length = 0;
  }
  append(e3, t2) {
    this.ensureCapacity(this.length + 1);
    const n2 = this.length++;
    return this.connId[n2] = t2, this.prev[n2] = e3, n2;
  }
  contains(e3, t2) {
    for (let n2 = e3;n2 >= 0; n2 = this.prev[n2])
      if (this.connId[n2] === t2)
        return true;
    return false;
  }
  collect(e3, t2) {
    t2.length = 0;
    for (let n2 = e3;n2 >= 0; n2 = this.prev[n2])
      t2.push(this.connId[n2]);
  }
  ensureCapacity(e3) {
    if (e3 <= this.connId.length)
      return;
    let t2 = this.connId.length;
    for (;t2 < e3; )
      t2 *= 2;
    const n2 = new Int32Array(t2);
    n2.set(this.connId), this.connId = n2;
    const o3 = new Int32Array(t2);
    o3.fill(-1), o3.set(this.prev.subarray(0, this.length)), this.prev = o3;
  }
};
function Oi(e3, t2, n2) {
  return Math.max(t2, Math.min(n2, e3));
}
function ki(e3, t2) {
  for (let n2 = 0;n2 < e3.length; n2++)
    if (e3[n2] === t2)
      return;
  e3.push(t2);
}
function Di(e3, t2) {
  for (let n2 = 0;n2 < e3.length; n2++)
    if (e3[n2].cellId === t2.cellId)
      return;
  e3.push(t2);
}
function Li(e3, t2, n2, o3, i3, r3, s2) {
  const a3 = e3 - Oi(e3, o3, r3), c3 = t2 - Oi(t2, i3, s2);
  return a3 * a3 + c3 * c3 <= n2 * n2;
}
var zi = class extends BaseSolver {
  getSolverName() {
    return "HighDensitySolverA03";
  }
  nodeWithPortPoints;
  highResolutionCellSize;
  highResolutionCellThickness;
  lowResolutionCellSize;
  viaDiameter;
  MAX_RIPS;
  maxCellCount;
  traceThickness;
  traceMargin;
  viaMinDistFromBorder;
  showPenaltyMap;
  showUsedCellMap;
  effort;
  enableDiagonalMoves;
  stepMultiplier;
  hyperParameters;
  initialPenaltyFn;
  boundsMinX;
  boundsMaxX;
  boundsMinY;
  boundsMaxY;
  gridToBoundsTransform;
  availableZ;
  zToLayer;
  layerToZ;
  layers;
  fineRows;
  fineCols;
  lowScale;
  bandRows;
  bandCols;
  regions;
  planeSize;
  cellCenterX;
  cellCenterY;
  cellMinX;
  cellMinY;
  cellMaxX;
  cellMaxY;
  cellWidth;
  cellHeight;
  cellRegion;
  cellRow;
  cellCol;
  viaAllowed;
  neighborOffset;
  neighborIds;
  neighborCosts;
  usedCellsFlat;
  sharedCellsFlat;
  portOwnerFlat;
  penalty2d;
  ripStateBuckets;
  visitedStamp;
  bestGStamp;
  bestGValue;
  visitedFlatStamp;
  sharedCrossRootPortFlat;
  stamp = 0;
  connNameToId;
  connIdToName;
  connIdToRootNet;
  overlapFriendlyRootNets;
  usedIndicesByConn;
  unsolvedSegs;
  solvedRoutes;
  activeConnSeg = null;
  activeConnId = -1;
  nodePool;
  heap;
  ripChain;
  seqCounter = 0;
  _viaOccs = [];
  viaOccupantsByCell = new Map;
  _cellOccs = [];
  _rippedIds = [];
  ripCount;
  totalRipEvents = 0;
  searchIterations = 0;
  consecutiveSkips = 0;
  penaltyCap;
  baseSearchBudgetIters;
  _moveCost = 0;
  _moveRippedHead = -1;
  _moveRipCount = 0;
  traceKeepoutRadius;
  viaKeepoutRadius;
  get unsolvedConnections() {
    return this.unsolvedSegs;
  }
  get solvedConnectionsMap() {
    const e3 = new Map;
    for (let t2 = 0;t2 < this.solvedRoutes.length; t2++) {
      const n2 = this.getSolvedRoutesForConn(t2);
      n2.length > 0 && e3.set(t2, n2);
    }
    return e3;
  }
  get activeConnection() {
    if (!this.activeConnSeg)
      return null;
    const e3 = this.activeConnSeg.startCellId, t2 = this.activeConnSeg.endCellId;
    return { connectionName: this.connIdToName[this.activeConnSeg.connId] ?? "", start: { cellId: e3, region: Ri[this.cellRegion[e3]], row: this.cellRow[e3], col: this.cellCol[e3], x: this.cellCenterX[e3], y: this.cellCenterY[e3], z: this.activeConnSeg.startZ }, end: { cellId: t2, region: Ri[this.cellRegion[t2]], row: this.cellRow[t2], col: this.cellCol[t2], x: this.cellCenterX[t2], y: this.cellCenterY[t2], 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((e3) => [e3.name, e3.rows * e3.cols])) : {} };
  }
  constructor(e3) {
    super(), this.nodeWithPortPoints = e3.nodeWithPortPoints, this.highResolutionCellSize = e3.highResolutionCellSize ?? 0.1, this.highResolutionCellThickness = Math.max(1, Math.floor(e3.highResolutionCellThickness ?? 8)), this.lowResolutionCellSize = e3.lowResolutionCellSize ?? 0.4, this.viaDiameter = e3.viaDiameter, this.maxCellCount = e3.maxCellCount, this.traceThickness = e3.traceThickness ?? 0.1, this.traceMargin = e3.traceMargin ?? 0.15, this.viaMinDistFromBorder = e3.viaMinDistFromBorder ?? 0.15, this.showPenaltyMap = e3.showPenaltyMap ?? false, this.showUsedCellMap = e3.showUsedCellMap ?? false, this.effort = e3.effort ?? 1, this.enableDiagonalMoves = e3.enableDiagonalMoves ?? false, this.stepMultiplier = Math.max(1, Math.floor(e3.stepMultiplier ?? 1)), this.hyperParameters = { shuffleSeed: 0, ripCost: 8, ripTracePenalty: 0.5, ripViaPenalty: 0.75, viaBaseCost: 0.1, greedyMultiplier: 1.5, ...e3.hyperParameters }, this.MAX_ITERATIONS = 1e8, this.MAX_RIPS = 200, this.initialPenaltyFn = e3.initialPenaltyFn;
  }
  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, enableDiagonalMoves: this.enableDiagonalMoves, hyperParameters: this.hyperParameters, initialPenaltyFn: this.initialPenaltyFn }];
  }
  _setup() {
    const { nodeWithPortPoints: e3 } = this, { width: t2, height: n2, center: o3 } = e3, i3 = this.lowResolutionCellSize / this.highResolutionCellSize, r3 = Math.round(i3);
    if (!Number.isFinite(i3) || i3 <= 0 || Math.abs(i3 - r3) > 0.000000001)
      return this.error = "lowResolutionCellSize must be a positive integer multiple of highResolutionCellSize", void (this.failed = true);
    this.lowScale = Math.max(1, r3), this.availableZ = e3.availableZ ?? [...new Set(e3.portPoints.map((e4) => e4.z))].sort((e4, t3) => e4 - t3), this.layers = this.availableZ.length, this.zToLayer = new Map, this.layerToZ = new Map;
    for (let e4 = 0;e4 < this.availableZ.length; e4++) {
      const t3 = this.availableZ[e4];
      this.zToLayer.set(t3, e4), this.layerToZ.set(e4, t3);
    }
    this.boundsMinX = o3.x - t2 / 2, this.boundsMaxX = o3.x + t2 / 2, this.boundsMinY = o3.y - n2 / 2, this.boundsMaxY = o3.y + n2 / 2, this.traceKeepoutRadius = this.traceMargin + this.traceThickness / 2, this.viaKeepoutRadius = this.viaDiameter / 2 + this.traceKeepoutRadius, this.buildFiveRegionGrid(t2, n2), this.gridToBoundsTransform = this.computeGridToBoundsTransform();
    const s2 = this.layers * this.planeSize;
    if (this.maxCellCount !== undefined && s2 > this.maxCellCount)
      return this.error = `Cell count ${s2} exceeds maxCellCount ${this.maxCellCount}`, void (this.failed = true);
    this.connNameToId = new Map, this.connIdToName = [], this.connIdToRootNet = [], this.overlapFriendlyRootNets = new Set, this.unsolvedSegs = this.buildConnectionSegs(), this.penalty2d = new Float64Array(this.planeSize);
    const a3 = t2 > 0 ? 1 / t2 : 0, c3 = n2 > 0 ? 1 / n2 : 0;
    for (let e4 = 0;e4 < this.planeSize; e4++) {
      let t3 = 0;
      this.initialPenaltyFn && (t3 += this.initialPenaltyFn({ x: this.cellCenterX[e4], y: this.cellCenterY[e4], px: (this.cellCenterX[e4] - this.boundsMinX) * a3, py: (this.cellCenterY[e4] - this.boundsMinY) * c3, cellId: e4, region: Ri[this.cellRegion[e4]], row: this.cellRow[e4], col: this.cellCol[e4] })), this.penalty2d[e4] = t3;
    }
    this.usedCellsFlat = new Int32Array(s2).fill(-1), this.sharedCellsFlat = Array.from({ length: s2 }, () => {}), this.portOwnerFlat = new Int32Array(s2).fill(-1), this.sharedCrossRootPortFlat = new Uint8Array(s2), this.ripStateBuckets = 1;
    const l3 = s2;
    this.visitedStamp = new Uint32Array(l3), this.bestGStamp = new Uint32Array(l3), this.bestGValue = new Float64Array(l3), this.visitedFlatStamp = new Uint32Array(s2), this.stamp = 0;
    const h2 = new Map;
    for (const e4 of this.nodeWithPortPoints.portPoints) {
      const t3 = this.connNameToId.get(e4.connectionName);
      if (t3 === undefined)
        continue;
      const n3 = this.pointToCell(e4), o4 = n3.z * this.planeSize + n3.cellId, i4 = this.connIdToRootNet[t3], r4 = h2.get(o4);
      r4 === undefined ? h2.set(o4, i4) : r4 !== i4 && (this.sharedCrossRootPortFlat[o4] = 1);
      const s3 = this.portOwnerFlat[o4];
      this.portOwnerFlat[o4] = s3 === -1 || s3 === t3 ? t3 : -2;
    }
    this.solvedRoutes = [], this.usedIndicesByConn = [], this.ripCount = [], this.consecutiveSkips = 0, this.penaltyCap = 0.5 * this.hyperParameters.ripCost, this.shuffleConnections();
    const d2 = vi({ planeSize: this.planeSize, layers: this.layers, connectionCount: this.unsolvedSegs.length, effort: this.effort, maxIterations: this.MAX_ITERATIONS });
    this.baseSearchBudgetIters = d2.baseSearchBudgetIters, this.MAX_ITERATIONS = d2.maxIterationsIters, this.activeConnSeg = null, this.activeConnId = -1, this.nodePool = new Ei, this.heap = new Ti, this.ripChain = new Ai, this.seqCounter = 0;
  }
  _step() {
    for (let e3 = 0;e3 < this.stepMultiplier; e3++) {
      if (this.solved || this.failed)
        return;
      this.stepOnce();
    }
  }
  buildFiveRegionGrid(e3, t2) {
    this.fineCols = Math.max(1, Math.ceil(e3 / this.highResolutionCellSize)), this.fineRows = Math.max(1, Math.ceil(t2 / this.highResolutionCellSize)), this.bandCols = Math.min(this.highResolutionCellThickness, Math.floor(this.fineCols / 2)), this.bandRows = Math.min(this.highResolutionCellThickness, Math.floor(this.fineRows / 2));
    const n2 = Math.max(0, this.fineCols - 2 * this.bandCols), o3 = Math.max(0, this.fineRows - 2 * this.bandRows), i3 = n2, r3 = n2;
    this.regions = [{ id: 0, name: "left", fineOriginRow: 0, fineOriginCol: 0, fineRows: this.fineRows, fineCols: this.bandCols, cellScale: 1, rows: this.fineRows, cols: this.bandCols, offset: 0 }, { id: 1, name: "top", fineOriginRow: 0, fineOriginCol: this.bandCols, fineRows: this.bandRows, fineCols: i3, cellScale: 1, rows: this.bandRows, cols: i3, offset: 0 }, { id: 2, 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: 3, name: "bottom", fineOriginRow: this.fineRows - this.bandRows, fineOriginCol: this.bandCols, fineRows: this.bandRows, fineCols: r3, cellScale: 1, rows: this.bandRows, cols: r3, offset: 0 }, { id: 4, name: "middle", fineOriginRow: this.bandRows, fineOriginCol: this.bandCols, fineRows: o3, fineCols: n2, cellScale: this.lowScale, rows: o3 > 0 ? Math.ceil(o3 / this.lowScale) : 0, cols: n2 > 0 ? Math.ceil(n2 / this.lowScale) : 0, offset: 0 }];
    let s2 = 0;
    for (let e4 = 0;e4 < this.regions.length; e4++)
      this.regions[e4].offset = s2, s2 += this.regions[e4].rows * this.regions[e4].cols;
    this.planeSize = s2, 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 e4 = 0;e4 < this.regions.length; e4++) {
      const t3 = this.regions[e4];
      for (let e5 = 0;e5 < t3.rows; e5++) {
        const n3 = t3.fineOriginRow + e5 * t3.cellScale, o4 = Math.min(t3.fineOriginRow + t3.fineRows, n3 + t3.cellScale), i4 = this.boundsMinY + n3 * this.highResolutionCellSize, r4 = Math.min(this.boundsMaxY, this.boundsMinY + o4 * this.highResolutionCellSize);
        for (let n4 = 0;n4 < t3.cols; n4++) {
          const o5 = t3.fineOriginCol + n4 * t3.cellScale, s3 = Math.min(t3.fineOriginCol + t3.fineCols, o5 + t3.cellScale), a4 = this.boundsMinX + o5 * this.highResolutionCellSize, c4 = Math.min(this.boundsMaxX, this.boundsMinX + s3 * this.highResolutionCellSize), l4 = this.cellIdFor(t3.id, e5, n4);
          this.cellCenterX[l4] = (a4 + c4) / 2, this.cellCenterY[l4] = (i4 + r4) / 2, this.cellMinX[l4] = a4, this.cellMinY[l4] = i4, this.cellMaxX[l4] = c4, this.cellMaxY[l4] = r4, this.cellWidth[l4] = c4 - a4, this.cellHeight[l4] = r4 - i4, this.cellRegion[l4] = t3.id, this.cellRow[l4] = e5, this.cellCol[l4] = n4;
          const h3 = Math.min(this.cellCenterX[l4] - this.boundsMinX, this.boundsMaxX - this.cellCenterX[l4], this.cellCenterY[l4] - this.boundsMinY, this.boundsMaxY - this.cellCenterY[l4]);
          this.viaAllowed[l4] = h3 >= this.viaMinDistFromBorder ? 1 : 0;
        }
      }
    }
    const a3 = Array.from({ length: this.planeSize }, () => []), c3 = (e4, t3) => {
      if (e4 === t3 || e4 < 0 || t3 < 0)
        return;
      const n3 = this.cellCenterX[e4] - this.cellCenterX[t3], o4 = this.cellCenterY[e4] - this.cellCenterY[t3], i4 = Math.hypot(n3, o4);
      Di(a3[e4], { cellId: t3, cost: i4 }), Di(a3[t3], { cellId: e4, cost: i4 });
    };
    for (let e4 = 0;e4 < this.regions.length; e4++) {
      const t3 = this.regions[e4];
      for (let e5 = 0;e5 < t3.rows; e5++)
        for (let n3 = 0;n3 < t3.cols; n3++) {
          const o4 = this.cellIdFor(t3.id, e5, n3);
          e5 + 1 < t3.rows && c3(o4, this.cellIdFor(t3.id, e5 + 1, n3)), n3 + 1 < t3.cols && c3(o4, this.cellIdFor(t3.id, e5, n3 + 1)), this.enableDiagonalMoves && e5 + 1 < t3.rows && (n3 + 1 < t3.cols && c3(o4, this.cellIdFor(t3.id, e5 + 1, n3 + 1)), n3 > 0 && c3(o4, this.cellIdFor(t3.id, e5 + 1, n3 - 1)));
        }
    }
    const l3 = this.regions[0], h2 = this.regions[1], d2 = this.regions[2], u2 = this.regions[3], p3 = this.regions[4], m2 = l3.rows > 0 && l3.cols > 0, g2 = h2.rows > 0 && h2.cols > 0, f2 = d2.rows > 0 && d2.cols > 0, _2 = u2.rows > 0 && u2.cols > 0, y2 = p3.rows > 0 && p3.cols > 0;
    if (m2 && g2)
      for (let e4 = 0;e4 < this.bandRows; e4++)
        c3(this.cellIdFor(0, e4, l3.cols - 1), this.cellIdFor(1, e4, 0));
    if (g2 && f2)
      for (let e4 = 0;e4 < this.bandRows; e4++)
        c3(this.cellIdFor(1, e4, h2.cols - 1), this.cellIdFor(2, e4, 0));
    if (m2 && _2)
      for (let e4 = this.fineRows - this.bandRows;e4 < this.fineRows; e4++)
        c3(this.cellIdFor(0, e4, l3.cols - 1), this.cellIdFor(3, e4 - (this.fineRows - this.bandRows), 0));
    if (_2 && f2)
      for (let e4 = this.fineRows - this.bandRows;e4 < this.fineRows; e4++)
        c3(this.cellIdFor(3, e4 - (this.fineRows - this.bandRows), u2.cols - 1), this.cellIdFor(2, e4, 0));
    if (m2 && y2)
      for (let e4 = this.bandRows;e4 < this.fineRows - this.bandRows; e4++)
        c3(this.cellIdFor(0, e4, l3.cols - 1), this.cellIdFor(4, Math.floor((e4 - this.bandRows) / this.lowScale), 0));
    if (f2 && y2)
      for (let e4 = this.bandRows;e4 < this.fineRows - this.bandRows; e4++)
        c3(this.cellIdFor(4, Math.floor((e4 - this.bandRows) / this.lowScale), p3.cols - 1), this.cellIdFor(2, e4, 0));
    if (g2 && y2)
      for (let e4 = this.bandCols;e4 < this.fineCols - this.bandCols; e4++)
        c3(this.cellIdFor(1, h2.rows - 1, e4 - this.bandCols), this.cellIdFor(4, 0, Math.floor((e4 - this.bandCols) / this.lowScale)));
    if (_2 && y2)
      for (let e4 = this.bandCols;e4 < this.fineCols - this.bandCols; e4++)
        c3(this.cellIdFor(4, p3.rows - 1, Math.floor((e4 - this.bandCols) / this.lowScale)), this.cellIdFor(3, 0, e4 - this.bandCols));
    if (!y2 && !g2 && !_2 && m2 && f2)
      for (let e4 = 0;e4 < Math.min(l3.rows, d2.rows); e4++)
        c3(this.cellIdFor(0, e4, l3.cols - 1), this.cellIdFor(2, e4, 0));
    if (!y2 && !m2 && !f2 && g2 && _2)
      for (let e4 = 0;e4 < Math.min(h2.cols, u2.cols); e4++)
        c3(this.cellIdFor(1, h2.rows - 1, e4), this.cellIdFor(3, 0, e4));
    const b2 = this.flattenNeighborLists(a3);
    this.neighborOffset = b2.offset, this.neighborIds = b2.ids, this.neighborCosts = b2.costs;
  }
  cellIdFor(e3, t2, n2) {
    const o3 = this.regions[e3];
    return o3.offset + t2 * o3.cols + n2;
  }
  stepOnce() {
    if (!this.activeConnSeg) {
      if (this.unsolvedSegs.length === 0)
        return void (this.solved = true);
      const e4 = this.unsolvedSegs.shift();
      this.activeConnSeg = e4, this.activeConnId = e4.connId, this.viaOccupantsByCell.clear(), this.nodePool.clear(), this.ripChain.clear(), this.heap.clear(), this.seqCounter = 0, this.searchIterations = 0, this.nextStamp();
      const t3 = this.computeH(e4.startZ, e4.startCellId, e4.endZ, e4.endCellId) * this.hyperParameters.greedyMultiplier, n3 = this.nodePool.push(e4.startZ, e4.startCellId, 0, -1, -1, 0), o4 = e4.startZ * this.planeSize + e4.startCellId, i4 = this.getSearchStateIdx(o4, 0);
      return this.bestGStamp[i4] = this.stamp, this.bestGValue[i4] = 0, void this.heap.push(t3, this.seqCounter++, n3);
    }
    this.searchIterations++;
    const e3 = this.ripCount[this.activeConnId] ?? 0, t2 = Math.round(this.baseSearchBudgetIters * (1 + 0.25 * Math.min(e3, 10)));
    if (this.searchIterations > t2) {
      const e4 = this.penalty2d;
      for (let t3 = 0;t3 < e4.length; t3++)
        e4[t3] = 0.9 * e4[t3];
      return this.unsolvedSegs.push(this.activeConnSeg), this.activeConnSeg = null, this.activeConnId = -1, this.heap.clear(), this.nodePool.clear(), this.consecutiveSkips++, void (this.consecutiveSkips >= Math.max(3, 3 * this.unsolvedSegs.length) && (this.error = `Convergence failure: ${this.unsolvedSegs.length} connections stuck`, this.failed = true));
    }
    if (this.heap.size === 0)
      return this.error = `No path found for ${this.connIdToName[this.activeConnId]}`, void (this.failed = true);
    const n2 = this.heap.pop(), o3 = this.nodePool.z[n2], i3 = this.nodePool.cellId[n2], r3 = this.nodePool.g[n2], s2 = this.nodePool.ripHead[n2], a3 = this.nodePool.ripCount[n2], c3 = o3 * this.planeSize + i3, l3 = this.getSearchStateIdx(c3, a3);
    if (this.visitedStamp[l3] === this.stamp)
      return;
    this.visitedStamp[l3] = this.stamp, this.visitedFlatStamp[c3] = this.stamp;
    const h2 = this.activeConnSeg;
    if (o3 === h2.endZ && i3 === h2.endCellId)
      return this.finalizeRoute(n2), this.activeConnSeg = null, void (this.activeConnId = -1);
    const d2 = this.visitedStamp, u2 = this.stamp, p3 = this.activeConnId, m2 = h2.endZ, g2 = h2.endCellId, f2 = this.neighborOffset[i3], _2 = this.neighborOffset[i3 + 1];
    for (let e4 = f2;e4 < _2; e4++) {
      const t3 = this.neighborIds[e4], i4 = o3 * this.planeSize + t3;
      if (this.computeMoveCostAndRips(p3, o3, t3, false, s2, a3, this.neighborCosts[e4]), this._moveCost < 0)
        continue;
      const c4 = this.getSearchStateIdx(i4, this._moveRipCount);
      if (d2[c4] === u2)
        continue;
      const l4 = r3 + this._moveCost;
      if (this.bestGStamp[c4] === u2 && l4 >= this.bestGValue[c4])
        continue;
      this.bestGStamp[c4] = u2, this.bestGValue[c4] = l4;
      const h3 = l4 + this.computeH(o3, t3, m2, g2) * this.hyperParameters.greedyMultiplier, f3 = this.nodePool.push(o3, t3, l4, n2, this._moveRippedHead, this._moveRipCount);
      this.heap.push(h3, this.seqCounter++, f3);
    }
    if (this.viaAllowed[i3])
      for (let e4 = 0;e4 < this.layers; e4++) {
        if (e4 === o3)
          continue;
        const t3 = e4 * this.planeSize + i3;
        if (this.computeMoveCostAndRips(p3, e4, i3, true, s2, a3, 0), this._moveCost < 0)
          continue;
        const c4 = this.getSearchStateIdx(t3, this._moveRipCount);
        if (d2[c4] === u2)
          continue;
        const l4 = r3 + this._moveCost;
        if (this.bestGStamp[c4] === u2 && l4 >= this.bestGValue[c4])
          continue;
        this.bestGStamp[c4] = u2, this.bestGValue[c4] = l4;
        const h3 = l4 + this.computeH(e4, i3, m2, g2) * this.hyperParameters.greedyMultiplier, f3 = this.nodePool.push(e4, i3, l4, n2, this._moveRippedHead, this._moveRipCount);
        this.heap.push(h3, this.seqCounter++, f3);
      }
  }
  computeMoveCostAndRips(e3, t2, n2, o3, i3, r3, s2) {
    let a3 = 0, c3 = i3, l3 = r3;
    const h2 = t2 * this.planeSize + n2;
    if (o3) {
      a3 += this.hyperParameters.viaBaseCost, a3 += Math.min(this.penalty2d[n2], this.penaltyCap);
      const o4 = this.portOwnerFlat[h2], i4 = this.allowSharedUse(e3, o4), r4 = this.activeConnSeg, s3 = !!r4 && t2 === r4.endZ && n2 === r4.endCellId;
      if (o4 >= 0 && o4 !== e3 && !i4 && !s3)
        return this._moveCost = -1, void (this._moveRippedHead = c3);
      this.fillViaOccupants(n2, e3);
      const d2 = this._viaOccs;
      for (let e4 = 0;e4 < d2.length; e4++) {
        const t3 = d2[e4];
        this.ripChain.contains(c3, t3) || (a3 += this.hyperParameters.ripCost, c3 = this.ripChain.append(c3, t3), l3++), a3 += this.hyperParameters.ripViaPenalty;
      }
    } else {
      a3 += s2, a3 += Math.min(this.penalty2d[n2], this.penaltyCap);
      const o4 = this.portOwnerFlat[h2], i4 = this.allowSharedUse(e3, o4), r4 = this.activeConnSeg, d2 = !!r4 && t2 === r4.endZ && n2 === r4.endCellId;
      if (o4 >= 0 && o4 !== e3 && !i4 && !d2)
        return this._moveCost = -1, void (this._moveRippedHead = c3);
      this.fillTraceOccupants(h2, e3, this._cellOccs);
      for (let e4 = 0;e4 < this._cellOccs.length; e4++) {
        const t3 = this._cellOccs[e4];
        this.ripChain.contains(c3, t3) || (a3 += this.hyperParameters.ripCost, c3 = this.ripChain.append(c3, t3), l3++), a3 += this.hyperParameters.ripTracePenalty;
      }
    }
    this._moveCost = a3, this._moveRippedHead = c3, this._moveRipCount = l3;
  }
  fillViaOccupants(e3, t2) {
    const n2 = this._viaOccs;
    n2.length = 0;
    const o3 = this.viaOccupantsByCell.get(e3);
    if (o3) {
      for (const e4 of o3)
        n2.push(e4);
      return;
    }
    const i3 = this.cellCenterX[e3], r3 = this.cellCenterY[e3];
    this.forEachCellNearCircle(i3, r3, this.viaKeepoutRadius, (e4) => {
      if (Li(i3, r3, this.viaKeepoutRadius, this.cellMinX[e4], this.cellMinY[e4], this.cellMaxX[e4], this.cellMaxY[e4]))
        for (let o4 = 0;o4 < this.layers; o4++)
          this.pushFlatOccupants(o4 * this.planeSize + e4, t2, n2);
    }), this.viaOccupantsByCell.set(e3, n2.slice());
  }
  fillTraceOccupants(e3, t2, n2) {
    n2.length = 0, this.pushFlatOccupants(e3, t2, n2);
  }
  pushFlatOccupants(e3, t2, n2) {
    const o3 = this.usedCellsFlat[e3];
    o3 === -1 || o3 === t2 || this.allowSharedUse(t2, o3) || ki(n2, o3);
    const i3 = this.sharedCellsFlat[e3];
    if (i3)
      for (let e4 = 0;e4 < i3.length; e4++) {
        const o4 = i3[e4];
        o4 !== t2 && (this.allowSharedUse(t2, o4) || ki(n2, o4));
      }
  }
  addSharedOccupant(e3, t2) {
    if (this.usedCellsFlat[e3] === t2)
      return;
    let n2 = this.sharedCellsFlat[e3];
    n2 || (n2 = [], this.sharedCellsFlat[e3] = n2), ki(n2, t2);
  }
  replaceOccupants(e3, t2) {
    this.usedCellsFlat[e3] = t2, this.sharedCellsFlat[e3] = undefined;
  }
  removeOccupant(e3, t2) {
    const n2 = this.sharedCellsFlat[e3];
    if (this.usedCellsFlat[e3] === t2)
      return void (n2 && n2.length > 0 ? (this.usedCellsFlat[e3] = n2.pop(), n2.length === 0 && (this.sharedCellsFlat[e3] = undefined)) : this.usedCellsFlat[e3] = -1);
    if (!n2)
      return;
    const o3 = n2.indexOf(t2);
    o3 !== -1 && (n2.splice(o3, 1), n2.length === 0 && (this.sharedCellsFlat[e3] = undefined));
  }
  allowSharedUse(e3, t2) {
    if (t2 < 0)
      return false;
    return this.connIdToRootNet[t2] === this.connIdToRootNet[e3];
  }
  shouldSkipFixedPortHalo(e3, t2) {
    const n2 = this.portOwnerFlat[e3];
    return n2 !== t2 && (n2 === -2 || !(n2 < 0) && !this.allowSharedUse(t2, n2));
  }
  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(e3, t2) {
    return e3;
  }
  computeH(e3, t2, n2, o3) {
    const i3 = Math.hypot(this.cellCenterX[t2] - this.cellCenterX[o3], this.cellCenterY[t2] - this.cellCenterY[o3]);
    return e3 === n2 ? i3 : i3 + this.hyperParameters.viaBaseCost;
  }
  internConn(e3, t2) {
    const n2 = this.connNameToId.get(e3);
    if (n2 !== undefined)
      return n2;
    const o3 = this.connIdToName.length;
    var i3;
    return this.connIdToName.push(e3), this.connIdToRootNet.push((i3 = e3, t2 ?? i3.replace(/_mst\d+$/, ""))), this.connNameToId.set(e3, o3), o3;
  }
  buildConnectionSegs() {
    const e3 = new Map;
    for (const t3 of this.nodeWithPortPoints.portPoints) {
      const n3 = t3.connectionName;
      e3.has(n3) || e3.set(n3, { points: [], rootConnectionName: t3.rootConnectionName }), e3.get(n3).points.push(t3);
    }
    const t2 = [], n2 = new Set;
    for (const [o3, i3] of e3) {
      const e4 = i3.points, r3 = bi(e4);
      if (r3.length === 0)
        continue;
      const s2 = this.internConn(o3, i3.rootConnectionName);
      for (const [e5, a3] of r3) {
        const r4 = this.pointToCell(e5), c3 = this.pointToCell(a3), l3 = `${r4.z}:${r4.cellId}`, h2 = `${c3.z}:${c3.cellId}`, d2 = l3 < h2 ? `${l3}|${h2}` : `${h2}|${l3}`, u2 = i3.rootConnectionName ?? o3, p3 = `${u2}|${d2}`;
        n2.has(p3) ? this.overlapFriendlyRootNets.add(u2) : (n2.add(p3), t2.push({ connId: s2, startZ: r4.z, startCellId: r4.cellId, startPoint: e5, endZ: c3.z, endCellId: c3.cellId, endPoint: a3 }));
      }
    }
    return t2;
  }
  pointToCell(e3) {
    const t2 = Oi(Math.floor((e3.x - this.boundsMinX) / this.highResolutionCellSize), 0, this.fineCols - 1), n2 = Oi(Math.floor((e3.y - this.boundsMinY) / this.highResolutionCellSize), 0, this.fineRows - 1);
    let o3 = 4;
    t2 < this.bandCols ? o3 = 0 : t2 >= this.fineCols - this.bandCols ? o3 = 2 : n2 < this.bandRows ? o3 = 1 : n2 >= this.fineRows - this.bandRows && (o3 = 3);
    const i3 = this.regions[o3], r3 = n2 - i3.fineOriginRow, s2 = t2 - i3.fineOriginCol, a3 = Oi(Math.floor(r3 / i3.cellScale), 0, Math.max(0, i3.rows - 1)), c3 = Oi(Math.floor(s2 / i3.cellScale), 0, Math.max(0, i3.cols - 1));
    return { z: this.zToLayer.get(e3.z) ?? 0, cellId: this.cellIdFor(o3, a3, c3) };
  }
  shuffleConnections() {
    const e3 = this.unsolvedSegs;
    let t2 = this.hyperParameters.shuffleSeed >>> 0;
    const n2 = () => (t2 = Math.imul(t2, 1664525) + 1013904223 >>> 0, t2 / 4294967295);
    for (let t3 = e3.length - 1;t3 > 0; t3--) {
      const o3 = Math.floor(n2() * (t3 + 1)), i3 = e3[t3];
      e3[t3] = e3[o3], e3[o3] = i3;
    }
  }
  finalizeRoute(e3) {
    this.consecutiveSkips = Math.max(0, this.consecutiveSkips - 1);
    const t2 = [];
    let n2 = e3;
    for (;n2 >= 0; ) {
      const e4 = this.nodePool.z[n2], o4 = this.nodePool.cellId[n2];
      t2.push(e4 * this.planeSize + o4), n2 = this.nodePool.parent[n2];
    }
    for (t2.reverse();t2.length > 1 && this.sharedCrossRootPortFlat[t2[0]]; )
      t2.shift();
    for (;t2.length > 1 && this.sharedCrossRootPortFlat[t2[t2.length - 1]]; )
      t2.pop();
    const o3 = this.extractViaCellIds(t2), i3 = this.activeConnId;
    this.ripChain.collect(this.nodePool.ripHead[e3], this._rippedIds);
    for (let e4 = 0;e4 < this._rippedIds.length; e4++)
      if (this.ripTrace(this._rippedIds[e4]), this.failed)
        return;
    const r3 = [];
    for (let e4 = 0;e4 < t2.length; e4++) {
      const n3 = t2[e4], o4 = Math.floor(n3 / this.planeSize), s3 = n3 - o4 * this.planeSize;
      this.markTraceFootprint(i3, o4, s3, r3);
    }
    const s2 = [];
    for (let e4 = 0;e4 < o3.length; e4++)
      this.markViaFootprint(i3, o3[e4], r3, s2);
    for (;this.usedIndicesByConn.length <= i3; )
      this.usedIndicesByConn.push(undefined);
    const a3 = this.usedIndicesByConn[i3] ?? [];
    for (a3.push(...r3), this.usedIndicesByConn[i3] = a3;this.solvedRoutes.length <= i3; )
      this.solvedRoutes.push(undefined);
    const c3 = this.solvedRoutes[i3] ?? [];
    c3.push({ connId: i3, states: Int32Array.from(t2), viaCellIds: Int32Array.from(o3), startPoint: this.activeConnSeg.startPoint, endPoint: this.activeConnSeg.endPoint }), this.solvedRoutes[i3] = c3;
    for (let e4 = 0;e4 < s2.length; e4++)
      if (this.ripTrace(s2[e4]), this.failed)
        return;
    if (this._rippedIds.length > 0 || s2.length > 0) {
      const e4 = this.penalty2d, t3 = this.penaltyCap;
      if (this.totalRipEvents > 50)
        for (let t4 = 0;t4 < e4.length; t4++)
          e4[t4] = 0.99 * e4[t4];
      else
        for (let n3 = 0;n3 < e4.length; n3++)
          e4[n3] > t3 && (e4[n3] = 0.5 * e4[n3]);
    }
  }
  extractViaCellIds(e3) {
    const t2 = [];
    for (let n2 = 1;n2 < e3.length; n2++) {
      const o3 = e3[n2 - 1], i3 = e3[n2], r3 = Math.floor(o3 / this.planeSize), s2 = Math.floor(i3 / this.planeSize);
      r3 !== s2 && t2.push(i3 - s2 * this.planeSize);
    }
    return t2;
  }
  markTraceFootprint(e3, t2, n2, o3) {
    const i3 = this.cellCenterX[n2], r3 = this.cellCenterY[n2];
    this.forEachCellNearCircle(i3, r3, this.traceKeepoutRadius, (s2) => {
      if (!Li(i3, r3, this.traceKeepoutRadius, this.cellMinX[s2], this.cellMinY[s2], this.cellMaxX[s2], this.cellMaxY[s2]))
        return;
      const a3 = t2 * this.planeSize + s2;
      if (s2 !== n2 && this.shouldSkipFixedPortHalo(a3, e3))
        return;
      const c3 = this.usedCellsFlat[a3], l3 = this.allowSharedUse(e3, c3);
      (c3 === -1 || c3 === e3 || l3) && (c3 !== -1 && c3 !== e3 ? this.addSharedOccupant(a3, e3) : this.usedCellsFlat[a3] = e3, o3.push(a3));
    });
  }
  markViaFootprint(e3, t2, n2, o3) {
    const i3 = this.cellCenterX[t2], r3 = this.cellCenterY[t2];
    this.forEachCellNearCircle(i3, r3, this.viaKeepoutRadius, (s2) => {
      if (Li(i3, r3, this.viaKeepoutRadius, this.cellMinX[s2], this.cellMinY[s2], this.cellMaxX[s2], this.cellMaxY[s2]))
        for (let i4 = 0;i4 < this.layers; i4++) {
          const r4 = i4 * this.planeSize + s2;
          if (s2 !== t2 && this.shouldSkipFixedPortHalo(r4, e3))
            continue;
          if (this.fillTraceOccupants(r4, e3, this._cellOccs), this._cellOccs.length > 0) {
            for (let e4 = 0;e4 < this._cellOccs.length; e4++)
              ki(o3, this._cellOccs[e4]);
            this.replaceOccupants(r4, e3), n2.push(r4);
            continue;
          }
          const a3 = this.usedCellsFlat[r4];
          a3 !== -1 && a3 !== e3 ? this.addSharedOccupant(r4, e3) : this.usedCellsFlat[r4] = e3, n2.push(r4);
        }
    });
  }
  forEachCellNearCircle(e3, t2, n2, o3) {
    const i3 = Oi(Math.floor((e3 - n2 - this.boundsMinX) / this.highResolutionCellSize), 0, this.fineCols - 1), r3 = Oi(Math.floor((e3 + n2 - this.boundsMinX) / this.highResolutionCellSize), 0, this.fineCols - 1), s2 = Oi(Math.floor((t2 - n2 - this.boundsMinY) / this.highResolutionCellSize), 0, this.fineRows - 1), a3 = Oi(Math.floor((t2 + n2 - this.boundsMinY) / this.highResolutionCellSize), 0, this.fineRows - 1);
    for (let e4 = 0;e4 < this.regions.length; e4++) {
      const t3 = this.regions[e4];
      if (t3.rows === 0 || t3.cols === 0)
        continue;
      const n3 = Math.max(s2, t3.fineOriginRow), c3 = Math.min(a3, t3.fineOriginRow + t3.fineRows - 1), l3 = Math.max(i3, t3.fineOriginCol), h2 = Math.min(r3, t3.fineOriginCol + t3.fineCols - 1);
      if (n3 > c3)
        continue;
      if (l3 > h2)
        continue;
      const d2 = Math.floor((n3 - t3.fineOriginRow) / t3.cellScale), u2 = Math.floor((c3 - t3.fineOriginRow) / t3.cellScale), p3 = Math.floor((l3 - t3.fineOriginCol) / t3.cellScale), m2 = Math.floor((h2 - t3.fineOriginCol) / t3.cellScale);
      for (let e5 = d2;e5 <= u2; e5++)
        for (let n4 = p3;n4 <= m2; n4++)
          o3(this.cellIdFor(t3.id, e5, n4));
    }
  }
  ripTrace(e3) {
    for (;this.ripCount.length <= e3; )
      this.ripCount.push(0);
    if (this.ripCount[e3]++, this.totalRipEvents++, this.totalRipEvents >= this.MAX_RIPS)
      return this.error = `Convergence failure: exceeded MAX_RIPS ${this.MAX_RIPS}`, void (this.failed = true);
    const t2 = this.getSolvedRoutesForConn(e3);
    if (t2.length > 0)
      for (const e4 of t2) {
        for (let t3 = 0;t3 < e4.states.length; t3++) {
          const n3 = e4.states[t3] % this.planeSize;
          this.penalty2d[n3] = this.penalty2d[n3] + this.hyperParameters.ripTracePenalty;
        }
        for (let t3 = 0;t3 < e4.viaCellIds.length; t3++) {
          const n3 = e4.viaCellIds[t3];
          this.penalty2d[n3] = this.penalty2d[n3] + this.hyperParameters.ripViaPenalty;
        }
      }
    const n2 = this.usedIndicesByConn[e3];
    if (n2) {
      for (let t3 = 0;t3 < n2.length; t3++)
        this.removeOccupant(n2[t3], e3);
      this.usedIndicesByConn[e3] = undefined;
    }
    if (t2.length > 0) {
      this.solvedRoutes[e3] = undefined;
      for (const n3 of t2) {
        const t3 = n3.states[0], o3 = n3.states[n3.states.length - 1], i3 = Math.floor(t3 / this.planeSize), r3 = Math.floor(o3 / this.planeSize);
        this.unsolvedSegs.push({ connId: e3, startZ: i3, startCellId: t3 - i3 * this.planeSize, startPoint: n3.startPoint, endZ: r3, endCellId: o3 - r3 * this.planeSize, endPoint: n3.endPoint });
      }
    }
  }
  flattenNeighborLists(e3) {
    const t2 = new Int32Array(e3.length + 1);
    let n2 = 0;
    for (let o4 = 0;o4 < e3.length; o4++)
      t2[o4] = n2, n2 += e3[o4].length;
    t2[e3.length] = n2;
    const o3 = new Int32Array(n2), i3 = new Float32Array(n2);
    let r3 = 0;
    for (let t3 = 0;t3 < e3.length; t3++) {
      const n3 = e3[t3];
      for (let e4 = 0;e4 < n3.length; e4++) {
        const t4 = n3[e4];
        o3[r3] = t4.cellId, i3[r3] = t4.cost, r3++;
      }
    }
    return { offset: t2, ids: o3, costs: i3 };
  }
  visualize() {
    const e3 = ["red", "blue", "orange", "green"], t2 = this.gridToBoundsTransform, n2 = [], o3 = [], i3 = [], r3 = [];
    if (r3.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 e4 = 0;
      for (let t3 = 0;t3 < this.penalty2d.length; t3++)
        this.penalty2d[t3] > e4 && (e4 = this.penalty2d[t3]);
      if (e4 > 0)
        for (let n3 = 0;n3 < this.planeSize; n3++) {
          const o4 = this.penalty2d[n3];
          if (o4 <= 0)
            continue;
          const i4 = gi(t2, { x: this.cellCenterX[n3], y: this.cellCenterY[n3] }), s3 = Math.min(0.6, o4 / e4 * 0.6);
          r3.push({ center: i4, width: this.cellWidth[n3] * t2.a, height: this.cellHeight[n3] * t2.e, fill: `rgba(255,165,0,${s3.toFixed(3)})` });
        }
    }
    if (this.showUsedCellMap && this.usedCellsFlat)
      for (let e4 = 0;e4 < this.layers; e4++) {
        const n3 = e4 * this.planeSize;
        for (let e5 = 0;e5 < this.planeSize; e5++) {
          if (this.usedCellsFlat[n3 + e5] === -1)
            continue;
          const o4 = gi(t2, { x: this.cellCenterX[e5], y: this.cellCenterY[e5] });
          r3.push({ center: o4, width: this.cellWidth[e5] * t2.a, height: this.cellHeight[e5] * t2.e, fill: "rgba(0,0,255,0.5)" });
        }
      }
    for (const t3 of this.nodeWithPortPoints.portPoints)
      n2.push({ x: t3.x, y: t3.y, color: e3[t3.z] ?? "gray", label: t3.connectionName });
    const s2 = ["rgba(255,0,0,0.75)", "rgba(0,0,255,0.75)", "rgba(255,165,0,0.75)", "rgba(0,128,0,0.75)"], a3 = this.getOutput();
    for (const e4 of a3) {
      if (e4.route.length < 2)
        continue;
      let t3 = 0;
      for (let n3 = 1;n3 < e4.route.length; n3++) {
        const i4 = e4.route[n3 - 1];
        e4.route[n3].z !== i4.z && (n3 - t3 >= 2 && o3.push({ points: e4.route.slice(t3, n3).map((e5) => ({ x: e5.x, y: e5.y })), strokeColor: s2[i4.z] ?? "rgba(128,128,128,0.75)", strokeWidth: this.traceThickness }), t3 = n3);
      }
      if (e4.route.length - t3 >= 2) {
        const n3 = e4.route[t3].z;
        o3.push({ points: e4.route.slice(t3).map((e5) => ({ x: e5.x, y: e5.y })), strokeColor: s2[n3] ?? "rgba(128,128,128,0.75)", strokeWidth: this.traceThickness });
      }
    }
    for (const e4 of a3)
      for (const t3 of e4.vias)
        i3.push({ center: { x: t3.x, y: t3.y }, radius: this.viaDiameter / 2, fill: "rgba(0,0,0,0.3)", stroke: "black" });
    if (this.activeConnSeg && this.visitedFlatStamp) {
      const e4 = this.stamp;
      for (let o4 = 0;o4 < this.layers; o4++) {
        const i4 = o4 * this.planeSize;
        for (let o5 = 0;o5 < this.planeSize; o5++) {
          if (this.visitedFlatStamp[i4 + o5] !== e4)
            continue;
          const r4 = gi(t2, { x: this.cellCenterX[o5], y: this.cellCenterY[o5] });
          n2.push({ x: r4.x, y: r4.y, color: "rgba(0,0,255,0.2)" });
        }
      }
    }
    return { points: n2, lines: o3, circles: i3, rects: r3, coordinateSystem: "cartesian", title: `${this.getSolverName()} [${this.getSolvedRouteCount()} solved, ${this.unsolvedSegs?.length ?? 0} remaining]` };
  }
  getOutput() {
    const e3 = this.gridToBoundsTransform, t2 = [];
    for (let n2 = 0;n2 < this.solvedRoutes.length; n2++) {
      const o3 = this.getSolvedRoutesForConn(n2);
      if (o3.length === 0)
        continue;
      const i3 = this.connIdToName[n2];
      for (const r3 of o3) {
        const o4 = Array.from(r3.states, (t3) => {
          const n3 = Math.floor(t3 / this.planeSize), o5 = t3 - n3 * this.planeSize, i4 = gi(e3, { x: this.cellCenterX[o5], y: this.cellCenterY[o5] });
          return { x: i4.x, y: i4.y, z: this.layerToZ.get(n3) ?? n3 };
        });
        o4.length === 1 ? (o4[0] = { ...r3.startPoint }, o4.push({ ...r3.endPoint })) : o4.length > 1 && (o4[0] = { ...r3.startPoint }, o4[o4.length - 1] = { ...r3.endPoint }), t2.push({ connectionName: i3, rootConnectionName: this.connIdToRootNet[n2], regionId: this.nodeWithPortPoints.capacityMeshNodeId, traceThickness: this.traceThickness, viaDiameter: this.viaDiameter, route: o4, vias: Array.from(r3.viaCellIds, (t3) => gi(e3, { x: this.cellCenterX[t3], y: this.cellCenterY[t3] })) });
      }
    }
    return t2;
  }
  getSolvedRoutesForConn(e3) {
    const t2 = this.solvedRoutes[e3];
    return t2 ? Array.isArray(t2) ? t2 : [t2] : [];
  }
  getSolvedRouteCount() {
    let e3 = 0;
    for (let t2 = 0;t2 < this.solvedRoutes.length; t2++)
      e3 += this.getSolvedRoutesForConn(t2).length;
    return e3;
  }
  computeGridToBoundsTransform() {
    let e3 = 1 / 0, t2 = -1 / 0, n2 = 1 / 0, o3 = -1 / 0;
    for (let i4 = 0;i4 < this.planeSize; i4++) {
      const r4 = this.cellCenterX[i4], s3 = this.cellCenterY[i4];
      r4 < e3 && (e3 = r4), r4 > t2 && (t2 = r4), s3 < n2 && (n2 = s3), s3 > o3 && (o3 = s3);
    }
    const i3 = t2 - e3, r3 = o3 - n2, s2 = this.boundsMaxX - this.boundsMinX, a3 = this.boundsMaxY - this.boundsMinY, c3 = i3 > 0 ? s2 / i3 : 1, l3 = r3 > 0 ? a3 / r3 : 1;
    return { a: c3, b: 0, c: i3 > 0 ? this.boundsMinX - c3 * e3 : (this.boundsMinX + this.boundsMaxX) / 2 - e3, d: 0, e: l3, f: r3 > 0 ? this.boundsMinY - l3 * n2 : (this.boundsMinY + this.boundsMaxY) / 2 - n2 };
  }
};
var Hi;
var Vi = class {
  begin;
  run;
  copyParents;
  constructor(e3, t2, n2, o3, i3) {
    const r3 = e3 * t2, s2 = r3 * n2, a3 = new Float64Array(s2), c3 = new Int32Array(s2), l3 = new Uint32Array(s2), h2 = new Int32Array(s2), d2 = new Uint8Array(s2);
    let u2, p3, m2, g2, f2, _2, y2, b2, x2 = 0, v2 = 0, I2 = 0, S2 = 1024, C = new Float64Array(S2), P = new Int32Array(S2), M = new Uint32Array(S2);
    for (let n3 = 0;n3 < s2; n3++) {
      const o4 = n3 % r3, i4 = o4 % e3, s3 = Math.floor(o4 / e3), a4 = Math.floor(n3 / r3);
      h2[n3] = o4, d2[n3] = Number(i4 > 0) | Number(i4 + 1 < e3) << 1 | Number(s3 > 0) << 2 | Number(s3 + 1 < t2) << 3 | a4 % 2 << 4;
    }
    function w(e4, t3) {
      let n3 = I2++;
      for (;n3 > 0; ) {
        const e5 = n3 - 1 >> 1;
        if (C[e5] <= t3)
          break;
        C[n3] = C[e5], P[n3] = P[e5], M[n3] = M[e5], n3 = e5;
      }
      C[n3] = t3, P[n3] = e4, l3[e4] = l3[e4] + 1 >>> 0, M[n3] = l3[e4];
    }
    let N = 0, R2 = 0;
    function T2() {
      N = P[0], R2 = M[0];
      const e4 = --I2;
      if (!e4)
        return;
      const t3 = P[e4], n3 = M[e4], o4 = C[e4];
      let i4 = 0;
      for (;2 * i4 + 1 < I2; ) {
        let e5 = 2 * i4 + 1;
        if (e5 + 1 < I2 && C[e5 + 1] < C[e5] && e5++, o4 <= C[e5])
          break;
        C[i4] = C[e5], P[i4] = P[e5], M[i4] = M[e5], i4 = e5;
      }
      C[i4] = o4, P[i4] = t3, M[i4] = n3;
    }
    function E3(e4, t3, n3, o4, i4, r4) {
      const s3 = r4 + t3;
      if (s3 >= a3[e4])
        return;
      if (m2[e4] && e4 !== x2)
        return;
      if (n3 && g2[o4])
        return;
      const l4 = n3 ? p3[o4] : u2[e4], h3 = n3 ? _2[o4] : f2[e4], d3 = s3 + v2 * l4 + h3;
      d3 >= a3[e4] || (a3[e4] = d3, c3[e4] = i4, w(e4, d3 + y2[e4]));
    }
    this.begin = (e4, t3, n3, o4) => {
      ({ traceCost: u2, viaCost: p3, fixed: m2, fixedVia: g2, history: f2, viaHistory: _2, viaAllowed: b2 } = e4), y2 = e4.heuristicCost, x2 = n3, v2 = o4, I2 = 0, a3.fill(1 / 0), c3.fill(-1), l3.fill(0), a3[t3] = 0, w(t3, y2[t3]);
    }, this.run = (t3, s3) => {
      let c4 = 0, u3 = 0;
      for (;u3 < t3; ) {
        if (c4 >= s3)
          return { status: 3, expansions: c4 };
        if (!I2)
          return { status: 2, expansions: c4 };
        if (I2 + 4 + n2 > S2) {
          S2 *= 2;
          const e4 = new Float64Array(S2), t5 = new Int32Array(S2), n3 = new Uint32Array(S2);
          e4.set(C), t5.set(P), n3.set(M), C = e4, P = t5, M = n3;
          continue;
        }
        T2(), u3++;
        const t4 = N;
        if (R2 !== l3[t4])
          continue;
        const p4 = a3[t4];
        if (c4++, t4 === x2)
          return { status: 1, expansions: c4 };
        const m3 = h2[t4], g3 = d2[t4], f3 = o3 * (16 & g3 ? 1.05 : 1), _3 = i3 * (16 & g3 ? 1 : 1.05);
        if (1 & g3 && E3(t4 - 1, f3, false, 0, t4, p4), 2 & g3 && E3(t4 + 1, f3, false, 0, t4, p4), 4 & g3 && E3(t4 - e3, _3, false, 0, t4, p4), 8 & g3 && E3(t4 + e3, _3, false, 0, t4, p4), b2[m3])
          for (let e4 = 0;e4 < n2; e4++) {
            const n3 = e4 * r3 + m3;
            n3 !== t4 && E3(n3, 0.8, true, m3, t4, p4);
          }
      }
      return { status: 0, expansions: c4 };
    }, this.copyParents = (e4) => e4.set(c3);
  }
};
var Wi = class {
  exports;
  offsets = [];
  states;
  heapCapacity = 1024;
  constructor(e3, t2, n2, o3, i3) {
    Hi ??= new WebAssembly.Module(Uint8Array.from(atob("AGFzbQEAAAABHwVgB39/f3x8f38AYAF/AGAAAX9gA39/fABgAn9/AX8DBwYAAQICAwQFAwEAAgYPAn8BQYCABAt/AEGAgQQLB2kIBm1lbW9yeQIACWNvbmZpZ3VyZQAAEXNldF9oZWFwX2NhcGFjaXR5AAEOZ2V0X2V4cGFuc2lvbnMAAghnZXRfcG9wcwADDGJlZ2luX3NlYXJjaAAEA3J1bgAFC19faGVhcF9iYXNlAwEK0h8G8wcEBX8FewR/BHtBACEHQQAgAjYChICEgABBACAANgKAgISAAEEAIAY2AqCAhIAAQQAgASAAbCIINgKIgISAAEEAIAggAmwiCTYCjICEgABBACADOQOQgISAAEEAIAQ5A5iAhIAAQQAgBSgCBDYCqICEgABBACAFKAIINgKsgISAAEEAIAUoAgw2ArCAhIAAQQAgBSgCEDYCtICEgABBACAFKAIUNgK4gISAAEEAIAUoAgA2AqSAhIAAQQAgBSgCGDYCvICEgABBACAFKAIcNgLAgISAAEEAIAUoAiA2AsSAhIAAQQAgBSgCJDYCyICEgABBACAFKAIoIgo2AsyAhIAAQQAgBSgCLCILNgLQgISAAEEAIAUoAjA2AtSAhIAAQQAgBSgCNDYC2ICEgAACQCAJQQFIDQACQCAJQQhJDQAgCyACIAFsIABsQQJ0IgVqIgIgCksgCiAFaiIFIAtLcQ0AIApBhICEgABJIAVBgICEgABLcQ0AIAtBhICEgABJIAJBgICEgABLcQ0AIAH9ESEMIAD9ESENIAj9ESEOQQD9CQKAgISAACEP/QwAAAAAAQAAAAIAAAADAAAAIRAgCiEFIAshAiAJQfz///8HcSIHIQYDQCAFIBAgEP0bACAO/RsAbSIR/REgEP0bASAO/RsBbSIS/RwBIBD9GwIgDv0bAm0iE/0cAiAQ/RsDIA79GwNtIhT9HAMgDv21Af2xASIV/QsCACACIBX9GwAgDf0bAG39ESAV/RsBIA39GwFt/RwBIBX9GwIgDf0bAm39HAIgFf0bAyAN/RsDbf0cAyIW/QwAAAAAAAAAAAAAAAAAAAAAIhf9O/0MBAAAAAQAAAAEAAAABAAAACIY/U4gFSAWIA39tQH9sQEiFSAX/Tj9sQEgEUECb/0RIBJBAm/9HAEgE0ECb/0cAiAUQQJv/RwDQQT9qwH9UCAV/QwBAAAAAQAAAAEAAAABAAAAIhf9rgEgD/05/QwCAAAAAgAAAAIAAAACAAAA/U79UCAWIBf9rgEgDP05/QwIAAAACAAAAAgAAAAIAAAA/U79UP0LAgAgBUEQaiEFIAJBEGohAiAQIBj9rgEhECAGQXxqIgYNAAsgCSAHRg0BC0EAIAFrIRMgCiAHQQJ0IgJqIQUgCyACaiECQQAgCGshFANAIAUgByAUIAcgCG0iBmxqIhE2AgAgAkEEQQAgESAAbSIRQQBKGyAHIAAgEyAGbCARa2wiEmpBAEdyIAZBAm9BBHRyQQJBACAHQQFqIgYgEmpBACgCgICEgABIG3JBCEEAIBFBAWogAUgbcjYCACAFQQRqIQUgAkEEaiECIAYhByAJIAZHDQALCwsNAEEAIAA2AqCAhIAACwsAQQAoAtyAhIAACwsAQQAoAuCAhIAAC4gFAQl/QQAgAjkD6ICEgABBACABNgLkgISAAEEAKALUgISAACEDQQAoAsSAhIAAIQQCQEEAKAKMgISAACIFQQFIDQBBACgCyICEgAAhBkEAIQcCQCAFQQRJDQBBACEHIAMgBmtBCEkNACAEIQEgBiEIIAMhCSAFQf7///8HcSIHIQoDQCAIQn83AgAgAf0MAAAAAAAA8H8AAAAAAADwf/0LAwAgCUIANwIAIAFBEGohASAIQQhqIQggCUEIaiEJIApBfmoiCg0ACyAFIAdGDQELIAchCwJAIAUgB2tBA3EiCkUNACAHIApqIQsgBCAHQQN0aiEBIAYgB0ECdCIJaiEIIAMgCWohCQNAIAhBfzYCACABQoCAgICAgID4/wA3AwAgCUEANgIAIAFBCGohASAIQQRqIQggCUEEaiEJIApBf2oiCg0ACwsgByAFa0F8Sw0AIAtBAnQhByAFIAtrIQUgBCALQQN0aiEBIAMhCgNAIAYgB2oiCEF/NgIAIAogB2oiCUEANgIAIAhBBGpBfzYCACAJQQRqQQA2AgAgCEEIakF/NgIAIAlBCGpBADYCACAIQQxqQX82AgAgAUKAgICAgICA+P8ANwMAIAFBCGpCgICAgICAgPj/ADcDACABQRBqQoCAgICAgID4/wA3AwAgAUEYakKAgICAgICA+P8ANwMAIAlBDGpBADYCACABQSBqIQEgBkEQaiEGIApBEGohCiAFQXxqIgUNAAsLQQBBATYC8ICEgAAgBCAAQQN0IghqQgA3AwAgAyAAQQJ0aiIBIAEoAgBBAWoiCTYCAEEAKALYgISAACIBQQAoAryAhIAAIAhqKwMAOQMAIAEgCTYCDCABIAA2AggLqhIMC38BfAN/AnwNfwF+AXwDfwJ8AX8BfAN/QQAhAkEAQQA2AuCAhIAAQQBBADYC3ICEgAACQCAAQQFIDQBBACgChICEgAAiA0EEaiEEQQAoAriAhIAAIQVBACgCqICEgAAhBkEAKAKwgISAACEHQQAoAoiAhIAAIQhBACgCwICEgAAhCUEAKAKAgISAACEKQQAoAryAhIAAIQtBACgCyICEgAAhDEEAKwPogISAACENQQAoArSAhIAAIQ5BACgCpICEgAAhD0EAKAKsgISAACEQQQArA5iAhIAAIRFBACsDkICEgAAhEkEAKALQgISAACETQQAoAsyAhIAAIRRBACgC5ICEgAAhFUEAKALEgISAACEWQQAoAtSAhIAAIRdBACgC2ICEgAAhGEEAKAKggISAACEZQQAoAvCAhIAAIRpBACEbQQAhHANAAkAgHCABSA0AQQMPCwJAIBoNAEECDwsCQCAaIARqIBlMDQBBBA8LQQAgGkF/aiIdNgLwgISAACAYKAIMIR4gGCgCCCEfAkAgHUUNACAYIB1BBHRqIgIpAwghICACKwMAISFBACECAkAgGkEDSA0AQQAhIkEBISNBACEkA0ACQAJAICRBAmoiJCAdSA0AICMhAgwBCyAjIQIgGCAkQQR0aisDACAYICNBBHRqKwMAY0UNACAkIQILAkAgISAYIAJBBHRqIiMrAwBlRQ0AICIhAgwCCyAYICJBBHRqICP9AAMA/QsDACACISIgAkEBdCIkQQFyIiMgHUgNAAsLIBggAkEEdGoiAiAgNwMIIAIgITkDAAtBACAbQQFqIhs2AuCAhIAAAkACQCAeIBcgH0ECdCIjaigCAEYNACAdIRoMAQtBASECQQAgHEEBaiIcNgLcgISAACAfIBVGDQIgFiAfQQN0aisDACEhIBJEzczMzMzM8D9EAAAAAAAA8D8gEyAjaigCACICQRBxIiIboiElIBQgI2ooAgAhIwJAAkAgAkEBcQ0AIB0hGgwBCwJAICEgJaAiJiAWIB9Bf2oiHkEDdCIkaiInKwMAIihmRQ0AIB0hGgwBCwJAIB4gFUYNACAQIB5qLQAAQf8BcUUNACAdIRoMAQsCQCAOICRqKwMAICYgDSAPIB5BAXRqLwEAuKKgoCImIChmRQ0AIB0hGgwBCyAMIB5BAnQiKWogHzYCACAnICY5AwBBACAaNgLwgISAACAmIAsgJGorAwCgISYCQCAaQQJIDQADQCAYIB1Bf2pBAXYiJEEEdGoiJysDACAmZQ0BIBggHUEEdGogJ/0AAwD9CwMAICQhHSAkDQALQQAhHQsgFyApaiIkICQoAgBBAWoiJDYCACAYIB1BBHRqIh0gJjkDACAdICQ2AgwgHSAeNgIIC0QAAAAAAADwP0TNzMzMzMzwPyAiGyEmAkACQCACQQJxDQAgGiEdDAELAkAgISAloCIlIBYgH0EBaiIeQQN0IiJqIh0rAwAiKGZFDQAgGiEdDAELAkAgHiAVRg0AIBAgHmotAABB/wFxRQ0AIBohHQwBCwJAIA4gImorAwAgJSANIA8gHkEBdGovAQC4oqCgIiUgKGZFDQAgGiEdDAELIAwgHkECdCInaiAfNgIAIB0gJTkDAEEAIBpBAWoiHTYC8ICEgAAgJSALICJqKwMAoCElAkAgGkEBSA0AA0AgGCAaQX9qQQF2IiJBBHRqIiQrAwAgJWUNASAYIBpBBHRqICT9AAMA/QsDACAiIRogIg0AC0EAIRoLIBcgJ2oiIiAiKAIAQQFqIiI2AgAgGCAaQQR0aiIaICU5AwAgGiAiNgIMIBogHjYCCAsgESAmoiElAkACQCACQQRxDQAgHSEiDAELAkAgISAloCImIBYgHyAKayIeQQN0IhpqIiIrAwAiKGZFDQAgHSEiDAELAkAgHiAVRg0AIBAgHmotAABB/wFxRQ0AIB0hIgwBCwJAIA4gGmorAwAgJiANIA8gHkEBdGovAQC4oqCgIiYgKGZFDQAgHSEiDAELIAwgHkECdCInaiAfNgIAICIgJjkDAEEAIB1BAWoiIjYC8ICEgAAgJiALIBpqKwMAoCEmAkAgHUEBSA0AA0AgGCAdQX9qQQF2IhpBBHRqIiQrAwAgJmUNASAYIB1BBHRqICT9AAMA/QsDACAaIR0gGg0AC0EAIR0LIBcgJ2oiGiAaKAIAQQFqIho2AgAgGCAdQQR0aiIdICY5AwAgHSAaNgIMIB0gHjYCCAsCQAJAIAJBCHENACAiIRoMAQsCQCAhICWgIiUgFiAKIB9qIiRBA3QiAmoiHSsDACImZkUNACAiIRoMAQsCQCAkIBVGDQAgECAkai0AAEH/AXFFDQAgIiEaDAELAkAgDiACaisDACAlIA0gDyAkQQF0ai8BALiioKAiJSAmZkUNACAiIRoMAQsgDCAkQQJ0Ih5qIB82AgAgHSAlOQMAQQAgIkEBaiIaNgLwgISAACAlIAsgAmorAwCgISUCQCAiQQFIDQADQCAYICJBf2pBAXYiAkEEdGoiHSsDACAlZQ0BIBggIkEEdGogHf0AAwD9CwMAIAIhIiACDQALQQAhIgsgFyAeaiICIAIoAgBBAWoiHTYCACAYICJBBHRqIgIgJTkDACACIB02AgwgAiAkNgIICyAJICNqLQAARQ0AIANBAUgNACAHICNqIR4gIUSamZmZmZnpP6AhISAFICNBA3RqIScgBiAjQQF0aiEpQQAhAgNAAkAgCCACbCAjaiIdIB9GDQAgISAWIB1BA3QiImoiJCsDACIlZg0AAkAgHSAVRg0AIBAgHWotAABB/wFxDQELIB4tAAANACAnKwMAICEgDSApLwEAuKKgoCImICVmDQAgDCAdQQJ0IipqIB82AgAgJCAmOQMAQQAgGkEBaiIrNgLwgISAACAmIAsgImorAwCgISUCQCAaQQFIDQADQCAYIBpBf2pBAXYiIkEEdGoiJCsDACAlZQ0BIBggGkEEdGogJP0AAwD9CwMAICIhGiAiDQALQQAhGgsgFyAqaiIiICIoAgBBAWoiIjYCACAYIBpBBHRqIhogJTkDACAaICI2AgwgGiAdNgIIICshGgsgAkEBaiICIANHDQALCyAbIABHDQALQQAhAgsgAgsAdQRuYW1lAAwLa2VybmVsLndhc20BTAYACWNvbmZpZ3VyZQERc2V0X2hlYXBfY2FwYWNpdHkCDmdldF9leHBhbnNpb25zAwhnZXRfcG9wcwQMYmVnaW5fc2VhcmNoBQNydW4HEgEAD19fc3RhY2tfcG9pbnRlcgAvCXByb2R1Y2VycwEMcHJvY2Vzc2VkLWJ5AQ5Ib21lYnJldyBjbGFuZwYyMi4xLjgAnQEPdGFyZ2V0X2ZlYXR1cmVzCSsLYnVsay1tZW1vcnkrD2J1bGstbWVtb3J5LW9wdCsWY2FsbC1pbmRpcmVjdC1vdmVybG9uZysKbXVsdGl2YWx1ZSsPbXV0YWJsZS1nbG9iYWxzKxNub250cmFwcGluZy1mcHRvaW50Kw9yZWZlcmVuY2UtdHlwZXMrCHNpZ24tZXh0KwdzaW1kMTI4"), (e4) => e4.charCodeAt(0))), this.exports = new WebAssembly.Instance(Hi).exports;
    const r3 = e3 * t2;
    this.states = r3 * n2;
    let s2 = Number(this.exports.__heap_base.value);
    const a3 = s2;
    s2 += 56;
    for (const e4 of [2 * this.states, 2 * r3, this.states, r3, 8 * this.states, 8 * r3, 8 * this.states, r3, 8 * this.states, 4 * this.states, 4 * this.states, 4 * this.states, 4 * this.states, 16 * this.heapCapacity])
      s2 = 8 * Math.ceil(s2 / 8), this.offsets.push(s2), s2 += e4;
    this.ensureMemory(s2), new Int32Array(this.exports.memory.buffer, a3, 14).set(this.offsets), this.exports.configure(e3, t2, n2, o3, i3, a3, this.heapCapacity);
  }
  ensureMemory(e3) {
    const t2 = this.exports.memory;
    e3 > t2.buffer.byteLength && t2.grow(Math.ceil((e3 - t2.buffer.byteLength) / 65536));
  }
  begin(e3, t2, n2, o3) {
    const i3 = new Uint8Array(this.exports.memory.buffer), r3 = [e3.traceCost, e3.viaCost, e3.fixed, e3.fixedVia, e3.history, e3.viaHistory, e3.heuristicCost, e3.viaAllowed];
    for (let e4 = 0;e4 < r3.length; e4++) {
      const t3 = r3[e4];
      i3.set(new Uint8Array(t3.buffer, t3.byteOffset, t3.byteLength), this.offsets[e4]);
    }
    this.exports.begin_search(t2, n2, o3);
  }
  run(e3, t2) {
    let n2 = 0, o3 = 0, i3 = Math.ceil(e3);
    for (;i3 > 0; )
      if (o3 = this.exports.run(Math.min(i3, 1e6), Math.min(Math.ceil(t2 - n2), 2147483647)), i3 -= this.exports.get_pops(), n2 += this.exports.get_expansions(), o3 === 4)
        this.heapCapacity *= 2, this.ensureMemory(this.offsets[13] + 16 * this.heapCapacity), this.exports.set_heap_capacity(this.heapCapacity);
      else if (o3 !== 0)
        break;
    return { status: o3, expansions: n2 };
  }
  copyParents(e3) {
    e3.set(new Int32Array(this.exports.memory.buffer, this.offsets[9], this.states));
  }
};
var Ui = (e3, t2, n2) => {
  const [o3, i3] = e3;
  if (o3 === i3)
    return;
  const r3 = ((e4, t3) => {
    const n3 = e4.portPointId ?? `${e4.connectionName}:${e4.x}:${e4.y}:${e4.z}`, o4 = t3.portPointId ?? `${t3.connectionName}:${t3.x}:${t3.y}:${t3.z}`;
    return n3 < o4 ? `${n3}|${o4}` : `${o4}|${n3}`;
  })(o3, i3);
  t2.has(r3) || (t2.add(r3), n2.push(e3));
};
var Zi = (e3, t2, n2) => {
  for (let o3 = 0;o3 < e3.length - 1; o3++)
    Ui([e3[o3], e3[o3 + 1]], t2, n2);
};
var qi = (e3) => {
  const t2 = [], n2 = new Set, o3 = ((e4) => {
    const t3 = new Map;
    for (const n3 of e4)
      n3.portPointId && t3.set(n3.portPointId, n3);
    return t3;
  })(e3);
  for (const i4 of e3) {
    if (i4.prevPortPointId) {
      const e4 = o3.get(i4.prevPortPointId);
      e4 && e4.connectionName === i4.connectionName && Ui([e4, i4], n2, t2);
    }
    if (i4.nextPortPointId) {
      const e4 = o3.get(i4.nextPortPointId);
      e4 && e4.connectionName === i4.connectionName && Ui([i4, e4], n2, t2);
    }
  }
  if (t2.length === 0)
    return Zi(e3, n2, t2), t2;
  const i3 = ((e4) => {
    const t3 = new Set;
    for (const [n3, o4] of e4)
      n3.portPointId && t3.add(n3.portPointId), o4.portPointId && t3.add(o4.portPointId);
    return t3;
  })(t2), r3 = e3.filter((e4) => !e4.portPointId || !i3.has(e4.portPointId));
  return Zi(r3, n2, t2), t2;
};
var Ji = 0.000000001;
var Qi = 0.01;
var Ki = 0.000001;
function er(e3, t2, n2) {
  return (t2.x - e3.x) * (n2.y - e3.y) - (t2.y - e3.y) * (n2.x - e3.x);
}
function tr(e3, t2, n2, o3) {
  const i3 = er(n2, o3, e3), r3 = er(n2, o3, t2), s2 = er(e3, t2, n2), a3 = er(e3, t2, o3);
  if ((i3 > Ji && r3 < -0.000000001 || i3 < -0.000000001 && r3 > Ji) && (s2 > Ji && a3 < -0.000000001 || s2 < -0.000000001 && a3 > Ji)) {
    const n3 = i3 / (i3 - r3);
    return { x: e3.x + n3 * (t2.x - e3.x), y: e3.y + n3 * (t2.y - e3.y) };
  }
  return null;
}
function nr(e3, t2) {
  const n2 = [];
  for (let o3 = 0;o3 < e3.route.length - 1; o3++) {
    const i3 = e3.route[o3], r3 = e3.route[o3 + 1];
    i3.z === t2 && r3.z === t2 && n2.push([{ x: i3.x, y: i3.y }, { x: r3.x, y: r3.y }]);
  }
  return n2;
}
function or(e3, t2) {
  return e3.route.filter((e4) => e4.z === t2).map((e4) => ({ x: e4.x, y: e4.y }));
}
function ir(e3, t2) {
  return Math.hypot(e3.x - t2.x, e3.y - t2.y);
}
function rr(e3, t2, n2 = 0.01) {
  return Math.abs(e3.x - t2.x) < n2 && Math.abs(e3.y - t2.y) < n2;
}
function sr(e3, t2, n2) {
  const o3 = new Set, i3 = [e3.route[0], e3.route[e3.route.length - 1]];
  for (const e4 of i3)
    e4 && e4.z === t2 && e4.portPointId && rr(e4, n2) && o3.add(e4.portPointId);
  return o3;
}
function ar(e3, t2, n2, o3) {
  const i3 = sr(e3, n2, o3);
  if (i3.size === 0)
    return false;
  const r3 = sr(t2, n2, o3);
  if (r3.size === 0)
    return false;
  for (const e4 of i3)
    if (r3.has(e4))
      return true;
  return false;
}
function cr(e3, t2, n2, o3) {
  const i3 = [t2.a, t2.b], r3 = [o3.a, o3.b];
  for (const o4 of i3)
    for (const i4 of r3)
      if (rr(o4, i4) && ar(e3, n2, t2.z, o4))
        return true;
  return false;
}
function lr(e3, t2, n2) {
  const o3 = n2.x - t2.x, i3 = n2.y - t2.y, r3 = o3 * o3 + i3 * i3;
  if (r3 <= Ji)
    return ir(e3, t2);
  const s2 = e3.x - t2.x, a3 = e3.y - t2.y, c3 = Math.max(0, Math.min(1, (s2 * o3 + a3 * i3) / r3));
  const l3 = t2.x + o3 * c3, h2 = t2.y + i3 * c3;
  return Math.hypot(e3.x - l3, e3.y - h2);
}
function hr(e3, t2, n2, o3) {
  return tr(e3, t2, n2, o3) ? 0 : Math.min(lr(e3, n2, o3), lr(t2, n2, o3), lr(n2, e3, t2), lr(o3, e3, t2));
}
function dr(e3) {
  return e3.rootConnectionName ?? e3.connectionName.replace(/_mst\d+$/, "");
}
function ur(e3, t2) {
  e3.push(t2);
}
function pr(e3) {
  const t2 = function(e4) {
    const t3 = [], n3 = new Set;
    for (const t4 of e4)
      for (const e5 of t4.route)
        n3.add(e5.z);
    for (const o3 of n3) {
      const n4 = e4.map((e5) => ({ points: or(e5, o3), segments: nr(e5, o3), root: dr(e5) }));
      for (let i3 = 0;i3 < e4.length; i3++) {
        const r3 = e4[i3], { points: s2, segments: a3, root: c3 } = n4[i3];
        for (let l3 = i3 + 1;l3 < e4.length; l3++) {
          const i4 = e4[l3], { points: h2, segments: d2, root: u2 } = n4[l3];
          if (c3 === u2)
            continue;
          const p3 = new Set;
          for (const e5 of s2)
            for (const n5 of h2)
              if (rr(e5, n5)) {
                if (ar(r3, i4, o3, e5))
                  continue;
                const n6 = `${e5.x.toFixed(2)},${e5.y.toFixed(2)}`;
                if (p3.has(n6))
                  continue;
                p3.add(n6), t3.push({ trace1: r3.connectionName, trace2: i4.connectionName, z: o3, point: e5, type: "shared_point" });
              }
          for (const [e5, n5] of a3)
            for (const [s3, a4] of d2) {
              const c4 = tr(e5, n5, s3, a4);
              c4 && t3.push({ trace1: r3.connectionName, trace2: i4.connectionName, z: o3, point: c4, type: "crossing", seg1: [e5, n5], seg2: [s3, a4] });
            }
        }
      }
    }
    return t3;
  }(e3).map((e4) => ({ trace1: e4.trace1, trace2: e4.trace2, type: e4.type, z: e4.z, point: e4.point, seg1: e4.seg1, seg2: e4.seg2, distance: 0, requiredDistance: 0 })), n2 = e3.map((e4) => {
    const t3 = function(e5) {
      const t4 = [];
      for (let n4 = 0;n4 < e5.route.length - 1; n4++) {
        const o4 = e5.route[n4], i4 = e5.route[n4 + 1];
        o4.z === i4.z && t4.push({ minX: Math.min(o4.x, i4.x), maxX: Math.max(o4.x, i4.x), minY: Math.min(o4.y, i4.y), maxY: Math.max(o4.y, i4.y), z: o4.z, a: { x: o4.x, y: o4.y }, b: { x: i4.x, y: i4.y } });
      }
      return t4;
    }(e4), n3 = new Set, o3 = new Map, i3 = new Map;
    for (const t4 of e4.route) {
      n3.add(t4.z);
      const e5 = o3.get(t4.z) ?? [];
      e5.push({ x: t4.x, y: t4.y }), o3.set(t4.z, e5);
    }
    for (const e5 of t3) {
      const t4 = i3.get(e5.z) ?? [];
      t4.push(e5), i3.set(e5.z, t4);
    }
    return { route: e4, rootNet: dr(e4), pointsByLayer: o3, segmentsByLayer: i3, segments: t3, vias: e4.vias.map((e5) => ({ x: e5.x, y: e5.y })), traceRadius: e4.traceThickness / 2, viaRadius: e4.viaDiameter / 2, zLayers: n3 };
  });
  for (let e4 = 0;e4 < n2.length; e4++) {
    const o3 = n2[e4];
    for (let i3 = e4 + 1;i3 < n2.length; i3++) {
      const e5 = n2[i3];
      if (o3.rootNet === e5.rootNet)
        continue;
      const r3 = new Set([...o3.zLayers.values(), ...e5.zLayers.values()]);
      for (const n3 of r3) {
        const i4 = o3.segmentsByLayer.get(n3) ?? [], r4 = e5.segmentsByLayer.get(n3) ?? [], s3 = o3.pointsByLayer.get(n3) ?? [], a3 = e5.pointsByLayer.get(n3) ?? [], c3 = o3.traceRadius + e5.traceRadius;
        for (const s4 of i4)
          for (const i5 of r4) {
            if (s4.minX - i5.maxX >= c3 || i5.minX - s4.maxX >= c3 || s4.minY - i5.maxY >= c3 || i5.minY - s4.maxY >= c3)
              continue;
            const r5 = hr(s4.a, s4.b, i5.a, i5.b);
            r5 + Ki >= c3 || (r5 <= Qi && cr(o3.route, s4, e5.route, i5) || ur(t2, { trace1: o3.route.connectionName, trace2: e5.route.connectionName, type: r5 <= Qi ? "shared_point" : "trace_clearance", z: n3, distance: r5, requiredDistance: c3, seg1: [s4.a, s4.b], seg2: [i5.a, i5.b] }));
          }
        for (const i5 of s3)
          for (const r5 of a3) {
            if (Math.abs(i5.x - r5.x) >= c3 || Math.abs(i5.y - r5.y) >= c3)
              continue;
            const s4 = ir(i5, r5);
            s4 + Ki >= c3 || (s4 <= Qi && ar(o3.route, e5.route, n3, i5) || ur(t2, { trace1: o3.route.connectionName, trace2: e5.route.connectionName, type: s4 <= Qi ? "shared_point" : "trace_clearance", z: n3, distance: s4, requiredDistance: c3, point: i5, point2: r5 }));
          }
      }
      const s2 = o3.viaRadius + e5.viaRadius;
      for (const n3 of o3.vias)
        for (const i4 of e5.vias) {
          if (Math.abs(n3.x - i4.x) >= s2 || Math.abs(n3.y - i4.y) >= s2)
            continue;
          const r4 = ir(n3, i4);
          r4 + Ki >= s2 || ur(t2, { trace1: o3.route.connectionName, trace2: e5.route.connectionName, type: "via_via_clearance", z: null, distance: r4, requiredDistance: s2, point: n3, point2: i4 });
        }
      for (const n3 of o3.vias) {
        const i4 = o3.viaRadius + e5.traceRadius;
        for (const r4 of e5.segments) {
          if (n3.x - r4.maxX >= i4 || r4.minX - n3.x >= i4 || n3.y - r4.maxY >= i4 || r4.minY - n3.y >= i4)
            continue;
          const s3 = lr(n3, r4.a, r4.b);
          s3 + Ki >= i4 || ur(t2, { trace1: o3.route.connectionName, trace2: e5.route.connectionName, type: "via_trace_clearance", z: r4.z, distance: s3, requiredDistance: i4, point: n3, seg2: [r4.a, r4.b] });
        }
      }
      for (const n3 of e5.vias) {
        const i4 = e5.viaRadius + o3.traceRadius;
        for (const r4 of o3.segments) {
          if (n3.x - r4.maxX >= i4 || r4.minX - n3.x >= i4 || n3.y - r4.maxY >= i4 || r4.minY - n3.y >= i4)
            continue;
          const s3 = lr(n3, r4.a, r4.b);
          s3 + Ki >= i4 || ur(t2, { trace1: o3.route.connectionName, trace2: e5.route.connectionName, type: "via_trace_clearance", z: r4.z, distance: s3, requiredDistance: i4, point: n3, seg1: [r4.a, r4.b] });
        }
      }
    }
  }
  return t2;
}
var mr = class extends BaseSolver {
  nodeWithPortPoints;
  props;
  traceThickness;
  traceMargin;
  viaDiameter;
  hyperParameters;
  phase = "routing";
  round = 0;
  routingIterations = 0;
  routedCount = 0;
  conflictCount = 0;
  rerouteCount = 0;
  bestConflictCount = 1 / 0;
  broadNegotiations = 0;
  stagnantRounds = 0;
  violations = [];
  connections = [];
  activeConnectionIndex = -1;
  rows = 0;
  cols = 0;
  plane = 0;
  layers = [];
  pitchX = 0;
  pitchY = 0;
  left = 0;
  bottom = 0;
  routes = new Map;
  pairCache = new WeakMap;
  queue = [];
  traceCost;
  viaCost;
  fixed;
  fixedVia;
  history;
  viaHistory;
  parent;
  searchKernel;
  heuristicCost;
  heuristicCache = new Map;
  viaAllowed;
  goal = 0;
  presentCost = 0.5;
  randomState = 1;
  constructor(e3) {
    super(), this.props = e3, this.nodeWithPortPoints = e3.nodeWithPortPoints, this.traceThickness = e3.traceThickness ?? 0.1, this.traceMargin = e3.traceMargin ?? 0.1, this.viaDiameter = e3.viaDiameter ?? 0.3, this.hyperParameters = { shuffleSeed: 0, greedyMultiplier: 1.1, ...e3.hyperParameters };
    for (const t2 of [e3.cellSizeMm ?? 0.1, this.traceThickness, this.viaDiameter, e3.stepMultiplier ?? 1000, e3.maxRounds ?? 200, e3.maxSearchIterations ?? 50000000, this.hyperParameters.greedyMultiplier])
      if (!Number.isFinite(t2) || t2 <= 0)
        throw new Error("A13 dimensions and search limits must be positive and finite");
    if (!Number.isFinite(this.traceMargin) || this.traceMargin < 0)
      throw new Error("traceMargin must be nonnegative");
    this.MAX_ITERATIONS = 1e8;
  }
  getSolverName() {
    return "HighDensitySolverA13";
  }
  getConstructorParams() {
    return [{ ...this.props }];
  }
  _setup() {
    const e3 = this.nodeWithPortPoints;
    if (e3.width <= 0 || e3.height <= 0)
      throw new Error("Node dimensions must be positive");
    this.cols = Math.ceil(e3.width / (this.props.cellSizeMm ?? 0.1)) + 1, this.rows = Math.ceil(e3.height / (this.props.cellSizeMm ?? 0.1)) + 1, this.pitchX = e3.width / (this.cols - 1), this.pitchY = e3.height / (this.rows - 1), this.left = e3.center.x - e3.width / 2, this.bottom = e3.center.y - e3.height / 2, this.layers = e3.availableZ ?? [...new Set(e3.portPoints.map((e4) => e4.z))].sort((e4, t3) => e4 - t3), this.plane = this.rows * this.cols;
    const t2 = this.plane * this.layers.length;
    if (t2 > 2000000)
      throw new Error("A13 grid exceeds two million states");
    this.traceCost = new Uint16Array(t2), this.viaCost = new Uint16Array(this.plane), this.fixed = new Uint8Array(t2), this.fixedVia = new Uint8Array(this.plane), this.history = new Float64Array(t2), this.viaHistory = new Float64Array(this.plane), this.heuristicCost = new Float64Array(t2), this.viaAllowed = new Uint8Array(this.plane);
    const n2 = Math.max(this.viaDiameter / 2, this.props.viaMinDistFromBorder ?? this.viaDiameter / 2);
    for (let t3 = 0;t3 < this.plane; t3++) {
      const o4 = this.point(t3);
      o4.x - this.left >= n2 && this.left + e3.width - o4.x >= n2 && o4.y - this.bottom >= n2 && this.bottom + e3.height - o4.y >= n2 && (this.viaAllowed[t3] = 1);
    }
    this.parent = new Int32Array(t2);
    const o3 = this.props.searchBackend === "wasm" ? Wi : Vi;
    this.searchKernel = new o3(this.cols, this.rows, this.layers.length, this.pitchX, this.pitchY);
    const i3 = new Map;
    for (const t3 of e3.portPoints) {
      if (!this.layers.includes(t3.z))
        throw new Error("Port is on an unavailable layer");
      const e4 = i3.get(t3.connectionName) ?? [];
      e4.push(t3), i3.set(t3.connectionName, e4);
    }
    for (const e4 of i3.values())
      for (const [t3, n3] of qi(e4))
        this.connections.push({ start: t3, end: n3, root: t3.rootConnectionName ?? t3.connectionName.replace(/_mst\d+$/, "") });
    this.randomState = this.hyperParameters.shuffleSeed + 1 >>> 0, this.queue = this.shuffle(this.connections.map((e4, t3) => t3));
  }
  shuffle(e3) {
    for (let t2 = e3.length - 1;t2 > 0; t2--) {
      this.randomState = Math.imul(this.randomState, 1664525) + 1013904223 >>> 0;
      const n2 = this.randomState % (t2 + 1);
      [e3[t2], e3[n2]] = [e3[n2], e3[t2]];
    }
    return e3;
  }
  index(e3) {
    const t2 = Math.max(0, Math.min(this.cols - 1, Math.round((e3.x - this.left) / this.pitchX))), n2 = Math.max(0, Math.min(this.rows - 1, Math.round((e3.y - this.bottom) / this.pitchY)));
    return this.layers.indexOf(e3.z) * this.plane + n2 * this.cols + t2;
  }
  point(e3) {
    const t2 = e3 % this.plane;
    return { x: this.left + t2 % this.cols * this.pitchX, y: this.bottom + Math.floor(t2 / this.cols) * this.pitchY, z: this.layers[Math.floor(e3 / this.plane)] };
  }
  capsule(e3, t2, n2, o3) {
    const i3 = Math.max(0, Math.floor((Math.min(e3.x, t2.x) - n2 - this.left) / this.pitchX)), r3 = Math.min(this.cols - 1, Math.ceil((Math.max(e3.x, t2.x) + n2 - this.left) / this.pitchX)), s2 = Math.max(0, Math.floor((Math.min(e3.y, t2.y) - n2 - this.bottom) / this.pitchY)), a3 = Math.min(this.rows - 1, Math.ceil((Math.max(e3.y, t2.y) + n2 - this.bottom) / this.pitchY)), c3 = t2.x - e3.x, l3 = t2.y - e3.y, h2 = c3 * c3 + l3 * l3;
    for (let t3 = s2;t3 <= a3; t3++)
      for (let s3 = i3;s3 <= r3; s3++) {
        const i4 = this.left + s3 * this.pitchX, r4 = this.bottom + t3 * this.pitchY, a4 = h2 ? Math.max(0, Math.min(1, ((i4 - e3.x) * c3 + (r4 - e3.y) * l3) / h2)) : 0;
        (i4 - e3.x - a4 * c3) ** 2 + (r4 - e3.y - a4 * l3) ** 2 < n2 * n2 - 0.000000000001 && o3(t3 * this.cols + s3);
      }
  }
  prepareSearch(e3) {
    this.activeConnectionIndex = e3;
    const t2 = this.connections[e3];
    this.traceCost.fill(0), this.viaCost.fill(0), this.fixed.fill(0), this.fixedVia.fill(0);
    for (const [e4, n3] of this.routes)
      if (this.connections[e4].root !== t2.root) {
        for (const e5 of n3.traceFootprint)
          this.traceCost[e5]++;
        for (const e5 of n3.viaFootprint)
          this.viaCost[e5]++;
      }
    for (const e4 of this.connections)
      if (e4.root !== t2.root)
        for (const t3 of [e4.start, e4.end])
          this.capsule(t3, t3, this.traceThickness + this.traceMargin, (e5) => {
            this.fixed[this.layers.indexOf(t3.z) * this.plane + e5] = 1;
          }), this.capsule(t3, t3, (this.traceThickness + this.viaDiameter) / 2 + this.traceMargin, (e5) => {
            this.fixedVia[e5] = 1;
          });
    const n2 = this.index(t2.start);
    this.goal = this.index(t2.end);
    const o3 = this.point(this.goal), i3 = this.heuristicCache.get(this.goal);
    if (i3)
      this.heuristicCost = i3;
    else {
      this.heuristicCost = new Float64Array(this.parent.length);
      for (let e5 = 0;e5 < this.layers.length; e5++)
        for (let t3 = 0;t3 < this.rows; t3++) {
          const n3 = Math.abs(this.bottom + t3 * this.pitchY - o3.y);
          for (let i4 = 0;i4 < this.cols; i4++)
            this.heuristicCost[e5 * this.plane + t3 * this.cols + i4] = (Math.abs(this.left + i4 * this.pitchX - o3.x) + n3 + (this.layers[e5] === o3.z ? 0 : 0.8)) * this.hyperParameters.greedyMultiplier;
        }
      const e4 = Math.floor(8388608 / this.heuristicCost.byteLength);
      e4 > 0 && (this.heuristicCache.size >= e4 && this.heuristicCache.delete(this.heuristicCache.keys().next().value), this.heuristicCache.set(this.goal, this.heuristicCost));
    }
    this.searchKernel.begin({ traceCost: this.traceCost, viaCost: this.viaCost, fixed: this.fixed, fixedVia: this.fixedVia, history: this.history, viaHistory: this.viaHistory, heuristicCost: this.heuristicCost, viaAllowed: this.viaAllowed }, n2, this.goal, this.presentCost);
  }
  _step() {
    if (this.phase === "negotiating")
      return void this.negotiate();
    if (this.activeConnectionIndex < 0) {
      const e4 = this.queue.shift();
      if (e4 === undefined)
        return void (this.phase = "negotiating");
      this.prepareSearch(e4);
    }
    const { status: e3, expansions: t2 } = this.searchKernel.run(this.props.stepMultiplier ?? 1000, (this.props.maxSearchIterations ?? 50000000) - this.routingIterations);
    this.routingIterations += t2, e3 === 1 ? (this.searchKernel.copyParents(this.parent), this.commit(this.goal)) : e3 === 2 ? (this.failed = true, this.error = `No path between fixed terminals of ${this.connections[this.activeConnectionIndex].start.connectionName}`) : e3 === 3 && (this.failed = true, this.error = "A13 exhausted its search budget");
  }
  commit(e3) {
    const t2 = this.activeConnectionIndex, n2 = this.connections[t2], o3 = [];
    for (let t3 = e3;t3 !== -1; t3 = this.parent[t3])
      o3.push(t3);
    o3.reverse();
    const i3 = [{ ...n2.start }, ...o3.map((e4) => this.point(e4)), { ...n2.end }], r3 = [];
    for (const e4 of i3) {
      const t3 = r3.at(-1), n3 = r3.at(-2);
      t3 && t3.x === e4.x && t3.y === e4.y && t3.z === e4.z || (n3 && t3 && n3.z === e4.z && t3.z === e4.z && (t3.x - n3.x) * (e4.y - t3.y) === (t3.y - n3.y) * (e4.x - t3.x) && r3.pop(), r3.push(e4));
    }
    r3[0] = { ...n2.start }, r3[r3.length - 1] = { ...n2.end };
    const s2 = [], a3 = [];
    for (let e4 = 1;e4 < o3.length; e4++)
      if (Math.floor(o3[e4] / this.plane) !== Math.floor(o3[e4 - 1] / this.plane)) {
        const t3 = this.point(o3[e4]);
        s2.push({ x: t3.x, y: t3.y }), a3.push(o3[e4] % this.plane);
      }
    const c3 = { connectionName: n2.start.connectionName, rootConnectionName: n2.root, regionId: this.nodeWithPortPoints.capacityMeshNodeId, traceThickness: this.traceThickness, viaDiameter: this.viaDiameter, route: r3, vias: s2 }, l3 = new Set, h2 = new Set, d2 = new Set;
    for (let e4 = 1;e4 < r3.length; e4++) {
      const t3 = r3[e4 - 1], n3 = r3[e4];
      t3.z === n3.z && (this.capsule(t3, n3, 0.00001, (e5) => d2.add(this.layers.indexOf(t3.z) * this.plane + e5)), this.capsule(t3, n3, this.traceThickness + this.traceMargin, (e5) => l3.add(this.layers.indexOf(t3.z) * this.plane + e5)), this.capsule(t3, n3, (this.traceThickness + this.viaDiameter) / 2 + this.traceMargin, (e5) => h2.add(e5)));
    }
    for (const e4 of s2)
      this.capsule(e4, e4, (this.viaDiameter + this.traceThickness) / 2 + this.traceMargin, (e5) => {
        for (let t3 = 0;t3 < this.layers.length; t3++)
          l3.add(t3 * this.plane + e5);
      }), this.capsule(e4, e4, this.viaDiameter + this.traceMargin, (e5) => h2.add(e5));
    this.routes.has(t2) && this.rerouteCount++, this.routes.set(t2, { output: c3, clearanceOutput: { ...c3, traceThickness: c3.traceThickness + this.traceMargin, viaDiameter: c3.viaDiameter + this.traceMargin }, traceFootprint: [...l3], traceFootprintSet: l3, viaFootprint: [...h2], viaFootprintSet: h2, cells: [...d2], viaCells: a3 }), this.routedCount = this.routes.size, this.activeConnectionIndex = -1;
  }
  getPair(e3, t2) {
    let n2 = this.pairCache.get(e3);
    n2 || (n2 = new WeakMap, this.pairCache.set(e3, n2));
    let o3 = n2.get(t2);
    return o3 || (o3 = { cells: [...e3.cells.filter((e4) => t2.traceFootprintSet.has(e4)), ...t2.cells.filter((t3) => e3.traceFootprintSet.has(t3))], vias: [...e3.viaCells.filter((e4) => t2.viaFootprintSet.has(e4)), ...t2.viaCells.filter((t3) => e3.viaFootprintSet.has(t3))], violations: pr([e3.clearanceOutput, t2.clearanceOutput]) }, n2.set(t2, o3)), o3;
  }
  negotiate() {
    this.round++;
    const e3 = new Set, t2 = new Set, n2 = new Set;
    for (const [o4, i4] of this.routes)
      for (const [r4, s2] of this.routes) {
        if (r4 <= o4 || this.connections[o4].root === this.connections[r4].root)
          continue;
        const a3 = this.getPair(i4, s2);
        if (a3.cells.length || a3.vias.length) {
          e3.add(o4), e3.add(r4);
          for (const e4 of a3.cells)
            t2.add(e4);
          for (const e4 of a3.vias)
            n2.add(e4);
        }
      }
    const o3 = [...this.routes.entries()].sort(([e4], [t3]) => e4 - t3), i3 = new Map;
    for (const [, e4] of o3)
      for (const t3 of e4.output.route)
        i3.has(t3.z) || i3.set(t3.z, []);
    const r3 = [];
    for (let e4 = 0;e4 < o3.length; e4++)
      for (let t3 = e4 + 1;t3 < o3.length; t3++) {
        const [n3, s2] = o3[e4], [a3, c3] = o3[t3];
        if (this.connections[n3].root !== this.connections[a3].root)
          for (const e5 of this.getPair(s2, c3).violations)
            e5.requiredDistance === 0 ? i3.get(e5.z).push(e5) : r3.push(e5);
      }
    this.violations = [...i3.values()].flat().concat(r3);
    for (const o4 of this.violations) {
      for (let t3 = 0;t3 < this.connections.length; t3++)
        [o4.trace1, o4.trace2].includes(this.connections[t3].start.connectionName) && e3.add(t3);
      for (const e4 of [o4.point, o4.point2])
        if (e4) {
          const i4 = this.index({ ...e4, z: this.layers[0] }) % this.plane;
          n2.add(i4), o4.z !== null && t2.add(this.layers.indexOf(o4.z) * this.plane + i4);
        }
    }
    if (this.conflictCount = e3.size, this.stagnantRounds = this.conflictCount < this.bestConflictCount ? 0 : this.stagnantRounds + 1, this.bestConflictCount = Math.min(this.bestConflictCount, this.conflictCount), this.stats = { round: this.round, conflictedRoutes: this.conflictCount, geometryViolations: this.violations.length, reroutes: this.rerouteCount, searchExpansions: this.routingIterations }, !this.violations.length && this.routes.size === this.connections.length)
      return this.solved = true, this.stats.conflictedRoutes = 0, this.conflictCount = 0, this.bestConflictCount = 0, void (this.phase = "complete");
    if (this.round >= (this.props.maxRounds ?? 200))
      return this.failed = true, void (this.error = `Negotiation exhausted ${this.round} rounds (${this.conflictCount} conflicted routes)`);
    for (const e4 of t2)
      this.history[e4] += 0.15;
    for (const e4 of n2)
      this.viaHistory[e4] += 0.15;
    this.presentCost = Math.min(20, 1.08 * this.presentCost), this.stagnantRounds >= 8 ? (this.queue = this.shuffle(this.connections.map((e4, t3) => t3)), this.presentCost = Math.max(0.5, this.presentCost / 2), this.stagnantRounds = 0, this.broadNegotiations++) : this.queue = this.shuffle([...e3]), this.phase = "routing";
  }
  getOutput() {
    return [...this.routes.entries()].sort(([e3], [t2]) => e3 - t2).map(([, e3]) => e3.output);
  }
  visualize() {
    const e3 = this.nodeWithPortPoints, t2 = { title: `A13 negotiated congestion · round ${this.round} · ${this.conflictCount} conflicted routes`, rects: [{ center: e3.center, width: e3.width, height: e3.height, stroke: "#475569", fill: "transparent" }], points: e3.portPoints.map((e4) => ({ ...e4, color: e4.z === 0 ? "red" : "blue", layer: `z${e4.z}`, label: e4.connectionName })), lines: [], circles: [] };
    for (const e4 of this.getOutput()) {
      for (let n2 = 1;n2 < e4.route.length; n2++) {
        const o3 = e4.route[n2 - 1], i3 = e4.route[n2];
        o3.z === i3.z && t2.lines.push({ points: [o3, i3], strokeColor: o3.z === 0 ? "#ef4444" : "#3b82f6", strokeWidth: this.traceThickness, layer: `z${o3.z}` });
      }
      for (const n2 of e4.vias)
        t2.circles.push({ center: n2, radius: this.viaDiameter / 2, fill: "#cbd5e1", stroke: "#334155", layer: `z${this.layers.join(",")}` });
    }
    for (const e4 of this.violations.slice(0, 50))
      e4.point && t2.circles.push({ center: e4.point, radius: 0.2, stroke: "#f59e0b", fill: "transparent" });
    return t2;
  }
};
var fr = (e3) => ({ minX: Math.min(e3[0].x, e3[1].x), maxX: Math.max(e3[0].x, e3[1].x), minY: Math.min(e3[0].y, e3[1].y), maxY: Math.max(e3[0].y, e3[1].y) });
function _r(e3, t2) {
  const n2 = e3.x - t2.x, o3 = e3.y - t2.y;
  return n2 * n2 + o3 * o3;
}
function yr(e3, t2, n2) {
  const o3 = _r(t2, n2);
  if (o3 === 0)
    return _r(e3, t2);
  let i3 = ((e3.x - t2.x) * (n2.x - t2.x) + (e3.y - t2.y) * (n2.y - t2.y)) / o3;
  i3 = Math.max(0, Math.min(1, i3));
  return _r(e3, { x: t2.x + i3 * (n2.x - t2.x), y: t2.y + i3 * (n2.y - t2.y) });
}
function br(e3, t2, n2, o3) {
  if (he(e3, t2, n2, o3))
    return 0;
  const i3 = { x: e3.x, y: e3.y }, r3 = { x: t2.x, y: t2.y }, s2 = { x: n2.x, y: n2.y }, a3 = { x: o3.x, y: o3.y };
  return Math.min(yr(i3, s2, a3), yr(r3, s2, a3), yr(s2, i3, r3), yr(a3, i3, r3));
}
var xr = class {
  segmentBuckets;
  viaBuckets;
  CELL_SIZE;
  maximumCopperRadius = 0;
  constructor(e3, t2 = 1) {
    this.segmentBuckets = new Map, this.viaBuckets = new Map, this.CELL_SIZE = t2;
    for (const t3 of e3)
      if (t3 && t3.connectionName) {
        if (this.maximumCopperRadius = Math.max(this.maximumCopperRadius, t3.traceThickness / 2, t3.viaDiameter / 2), t3.route && t3.route.length >= 2)
          for (let e4 = 0;e4 < t3.route.length - 1; e4++) {
            const n2 = t3.route[e4], o3 = t3.route[e4 + 1];
            if (n2.x === o3.x && n2.y === o3.y)
              continue;
            if (n2.insideJumperPad && o3.insideJumperPad)
              continue;
            const i3 = [n2, o3], r3 = fr(i3), s2 = { segmentId: `${t3.connectionName}-seg-${e4}`, segment: i3, parentRoute: t3 }, a3 = Math.floor(r3.minX / this.CELL_SIZE), c3 = Math.floor((r3.maxX + 0.000000001) / this.CELL_SIZE), l3 = Math.floor(r3.minY / this.CELL_SIZE), h2 = Math.floor((r3.maxY + 0.000000001) / this.CELL_SIZE);
            for (let e5 = a3;e5 <= c3; e5++)
              for (let t4 = l3;t4 <= h2; t4++) {
                const n3 = `${e5}x${t4}`;
                let o4 = this.segmentBuckets.get(n3);
                o4 || (o4 = [], this.segmentBuckets.set(n3, o4)), o4.push(s2);
              }
          }
        if (t3.vias && t3.vias.length > 0)
          for (let e4 = 0;e4 < t3.vias.length; e4++) {
            const n2 = t3.vias[e4];
            if (n2 == null)
              continue;
            const o3 = { viaId: `${t3.connectionName}-via-${e4}`, x: n2.x, y: n2.y, parentRoute: t3 }, i3 = `${Math.floor(n2.x / this.CELL_SIZE)}x${Math.floor(n2.y / this.CELL_SIZE)}`;
            let r3 = this.viaBuckets.get(i3);
            r3 || (r3 = [], this.viaBuckets.set(i3, r3)), r3.push(o3);
          }
      } else
        console.warn("Skipping route with missing data:", t3);
  }
  getConflictingRoutesForSegment(e3, t2, n2) {
    const o3 = fr([e3, t2]), i3 = n2 + this.maximumCopperRadius, r3 = o3.minX - i3, s2 = o3.minY - i3, a3 = o3.maxX + i3, c3 = o3.maxY + i3, l3 = Math.floor(r3 / this.CELL_SIZE), h2 = Math.floor((a3 + 0.000000001) / this.CELL_SIZE), d2 = Math.floor(s2 / this.CELL_SIZE), u2 = Math.floor((c3 + 0.000000001) / this.CELL_SIZE), p3 = new Map, m2 = new Set, g2 = new Set, f2 = { x: e3.x, y: e3.y }, _2 = { x: t2.x, y: t2.y };
    for (let o4 = l3;o4 <= h2; o4++)
      for (let i4 = d2;i4 <= u2; i4++) {
        const r4 = `${o4}x${i4}`, s3 = this.segmentBuckets.get(r4);
        if (s3)
          for (const o5 of s3) {
            if (m2.has(o5.segmentId))
              continue;
            m2.add(o5.segmentId);
            const i5 = o5.parentRoute, [r5, s4] = o5.segment;
            if (e3.z !== t2.z || r5.z !== s4.z || r5.z !== e3.z)
              continue;
            const a5 = n2 + i5.traceThickness / 2, c4 = a5 * a5, l4 = br(e3, t2, r5, s4);
            if (l4 < c4) {
              const e4 = i5.connectionName, t3 = p3.get(e4);
              (!t3 || l4 < t3.minDistSq) && p3.set(e4, { route: i5, minDistSq: l4 });
            }
          }
        const a4 = this.viaBuckets.get(r4);
        if (a4)
          for (const e4 of a4) {
            if (g2.has(e4.viaId))
              continue;
            g2.add(e4.viaId);
            const t3 = e4.parentRoute, o5 = { x: e4.x, y: e4.y }, i5 = n2 + t3.viaDiameter / 2, r5 = i5 * i5, s4 = yr(o5, f2, _2);
            if (s4 < r5) {
              const e5 = t3.connectionName, n3 = p3.get(e5);
              (!n3 || s4 < n3.minDistSq) && p3.set(e5, { route: t3, minDistSq: s4 });
            }
          }
      }
    const y2 = [];
    for (const e4 of p3.values())
      y2.push({ conflictingRoute: e4.route, distance: Math.sqrt(e4.minDistSq) });
    return y2;
  }
  removeRoute(e3) {
    for (const [t2, n2] of this.segmentBuckets) {
      const o3 = n2.filter((t3) => t3.parentRoute.connectionName !== e3);
      o3.length === 0 ? this.segmentBuckets.delete(t2) : o3.length !== n2.length && this.segmentBuckets.set(t2, o3);
    }
    for (const [t2, n2] of this.viaBuckets) {
      const o3 = n2.filter((t3) => t3.parentRoute.connectionName !== e3);
      o3.length === 0 ? this.viaBuckets.delete(t2) : o3.length !== n2.length && this.viaBuckets.set(t2, o3);
    }
  }
  addRoute(e3) {
    if (!e3 || !e3.connectionName)
      return void console.warn("Skipping route with missing data:", e3);
    this.maximumCopperRadius = Math.max(this.maximumCopperRadius, e3.traceThickness / 2, e3.viaDiameter / 2);
    if (e3.route && e3.route.length >= 2)
      for (let t2 = 0;t2 < e3.route.length - 1; t2++) {
        const n2 = e3.route[t2], o3 = e3.route[t2 + 1];
        if (n2.x === o3.x && n2.y === o3.y)
          continue;
        if (n2.insideJumperPad && o3.insideJumperPad)
          continue;
        const i3 = [n2, o3], r3 = fr(i3), s2 = { segmentId: `${e3.connectionName}-seg-${t2}`, segment: i3, parentRoute: e3 }, a3 = Math.floor(r3.minX / this.CELL_SIZE), c3 = Math.floor((r3.maxX + 0.000000001) / this.CELL_SIZE), l3 = Math.floor(r3.minY / this.CELL_SIZE), h2 = Math.floor((r3.maxY + 0.000000001) / this.CELL_SIZE);
        for (let e4 = a3;e4 <= c3; e4++)
          for (let t3 = l3;t3 <= h2; t3++) {
            const n3 = `${e4}x${t3}`;
            let o4 = this.segmentBuckets.get(n3);
            o4 || (o4 = [], this.segmentBuckets.set(n3, o4)), o4.push(s2);
          }
      }
    if (e3.vias && e3.vias.length > 0)
      for (let t2 = 0;t2 < e3.vias.length; t2++) {
        const n2 = e3.vias[t2];
        if (n2 == null)
          continue;
        const o3 = { viaId: `${e3.connectionName}-via-${t2}`, x: n2.x, y: n2.y, parentRoute: e3 }, i3 = `${Math.floor(n2.x / this.CELL_SIZE)}x${Math.floor(n2.y / this.CELL_SIZE)}`;
        let r3 = this.viaBuckets.get(i3);
        r3 || (r3 = [], this.viaBuckets.set(i3, r3)), r3.push(o3);
      }
  }
  getConflictingRoutesNearPoint(e3, t2) {
    const n2 = t2 + this.maximumCopperRadius, o3 = e3.x - n2, i3 = e3.y - n2, r3 = e3.x + n2, s2 = e3.y + n2, a3 = Math.floor(o3 / this.CELL_SIZE), c3 = Math.floor((r3 + 0.000000001) / this.CELL_SIZE), l3 = Math.floor(i3 / this.CELL_SIZE), h2 = Math.floor((s2 + 0.000000001) / this.CELL_SIZE), d2 = new Map, u2 = new Set, p3 = new Set;
    for (let n3 = a3;n3 <= c3; n3++)
      for (let o4 = l3;o4 <= h2; o4++) {
        const i4 = `${n3}x${o4}`, r4 = this.segmentBuckets.get(i4);
        if (r4)
          for (const n4 of r4) {
            if (u2.has(n4.segmentId))
              continue;
            u2.add(n4.segmentId);
            const o5 = n4.segment[0], i5 = n4.segment[1];
            if (o5.z !== i5.z || o5.z !== e3.z)
              continue;
            const r5 = n4.parentRoute, s4 = { x: n4.segment[0].x, y: n4.segment[0].y }, a4 = { x: n4.segment[1].x, y: n4.segment[1].y }, c4 = t2 + r5.traceThickness / 2, l4 = c4 * c4, h3 = yr(e3, s4, a4);
            if (h3 < l4) {
              const e4 = r5.connectionName, t3 = d2.get(e4);
              (!t3 || h3 < t3.minDistSq) && d2.set(e4, { route: r5, minDistSq: h3 });
            }
          }
        const s3 = this.viaBuckets.get(i4);
        if (s3)
          for (const n4 of s3) {
            if (p3.has(n4.viaId))
              continue;
            p3.add(n4.viaId);
            const o5 = n4.parentRoute, i5 = { x: n4.x, y: n4.y }, r5 = t2 + o5.viaDiameter / 2, s4 = r5 * r5, a4 = _r(e3, i5);
            if (a4 < s4) {
              const e4 = o5.connectionName, t3 = d2.get(e4);
              (!t3 || a4 < t3.minDistSq) && d2.set(e4, { route: o5, minDistSq: a4 });
            }
          }
      }
    const m2 = [];
    for (const e4 of d2.values())
      m2.push({ conflictingRoute: e4.route, distance: Math.sqrt(e4.minDistSq) });
    return m2;
  }
};
function vr(e3) {
  let t2 = e3;
  for (let e4 = 0;e4 < 10; e4++)
    t2 = 16807 * t2 % 2147483647;
  let n2 = t2;
  t2 = (69069 * e3 + 1) % 2147483647;
  for (let e4 = 0;e4 < 10; e4++)
    t2 = 48271 * t2 % 2147483647;
  let o3 = t2;
  return () => {
    let e4 = n2;
    n2 = o3, e4 ^= e4 << 23, e4 ^= e4 >>> 17, e4 ^= o3, e4 ^= o3 >>> 26, o3 = e4;
    const t3 = (n2 + o3) / 4294967296;
    return t3 - Math.floor(t3);
  };
}
var Ir = { 1: [[0]], 2: [[0, 1], [1, 0]], 3: [[0, 1, 2], [2, 0, 1], [1, 0, 2], [0, 2, 1], [1, 2, 0], [2, 1, 0]], 4: [[0, 1, 2, 3], [2, 0, 1, 3], [1, 3, 2, 0], [3, 0, 1, 2], [0, 2, 1, 3], [2, 1, 3, 0], [3, 0, 2, 1], [1, 2, 0, 3], [3, 1, 0, 2], [0, 3, 2, 1], [2, 3, 0, 1], [2, 3, 1, 0], [1, 2, 3, 0], [3, 1, 2, 0], [0, 1, 3, 2], [0, 2, 3, 1], [0, 3, 1, 2], [1, 0, 2, 3], [1, 0, 3, 2], [1, 3, 0, 2], [2, 0, 3, 1], [2, 1, 0, 3], [3, 2, 0, 1], [3, 2, 1, 0]] };
function Sr(e3, t2) {
  if (t2 === 0)
    return e3;
  if (e3.length === 0)
    return e3;
  if (e3.length <= 4) {
    const n3 = Ir[e3.length];
    return n3[t2 % n3.length].map((t3) => e3[t3]);
  }
  const n2 = vr(t2), o3 = e3.slice();
  for (let e4 = 0;e4 < o3.length; e4++) {
    const t3 = Math.floor(n2() * o3.length), i3 = Math.floor(n2() * (e4 + 1));
    [o3[t3], o3[i3]] = [o3[i3], o3[t3]];
  }
  return o3;
}
var Cr = class {
  heap = [];
  costs = [];
  constructor(e3) {
    this.heap = [];
    for (const t2 of e3)
      this.enqueue(t2);
  }
  dequeue() {
    if (this.heap.length === 0)
      return null;
    const e3 = this.heap[0];
    return this.heap[0] = this.heap[this.heap.length - 1], this.heap.pop(), this.costs[0] = this.costs[this.costs.length - 1], this.costs.pop(), this.heapifyDown(), e3;
  }
  peek() {
    return this.heap.length === 0 ? null : this.heap[0];
  }
  enqueue(e3) {
    this.heap.push(e3), this.costs.push(e3.f), this.heapifyUp();
  }
  heapifyUp() {
    let e3 = this.heap.length - 1;
    const t2 = this.heap[e3];
    for (;e3 > 0; ) {
      const n2 = Math.floor((e3 - 1) / 2), o3 = this.heap[n2];
      if (this.costs[n2] <= t2.f)
        break;
      this.costs[e3] = this.costs[n2], this.heap[e3] = o3, e3 = n2;
    }
    this.heap[e3] = t2, this.costs[e3] = t2.f;
  }
  heapifyDown() {
    let e3 = 0;
    const t2 = this.heap.length, n2 = this.heap[e3];
    if (n2) {
      for (;; ) {
        const o3 = 2 * e3 + 1;
        if (o3 >= t2)
          break;
        const i3 = o3 + 1;
        let r3 = o3;
        if (i3 < t2 && this.costs[i3] < this.costs[o3] && (r3 = i3), n2.f < this.costs[r3])
          break;
        this.heap[e3] = this.heap[r3], this.costs[e3] = this.costs[r3], e3 = r3;
      }
      this.heap[e3] = n2, this.costs[e3] = n2.f;
    }
  }
  getTopN(e3) {
    return [...this.heap].sort((e4, t2) => e4.f - t2.f).slice(0, e3);
  }
};
var Pr = (e3, t2, n2 = []) => [e3, t2 ? `rootConnectionName: ${t2}` : undefined, ...n2].filter(Boolean).join(`
`);
var Mr = class extends ni {
  getSolverName() {
    return "SingleHighDensityRouteSolver";
  }
  obstacleRoutes;
  bounds;
  boundsSize;
  boundsCenter;
  A;
  B;
  straightLineDistance;
  viaDiameter;
  traceThickness;
  obstacleMargin;
  layerCount;
  availableZ;
  minCellSize = 0.05;
  cellStep = 0.05;
  GREEDY_MULTIPLER = 1.1;
  numRoutes;
  VIA_PENALTY_FACTOR = 0.3;
  CELL_SIZE_FACTOR;
  NEARBY_SEGMENT_CLEARANCE;
  exploredNodes;
  viasInPathByNode = new WeakMap;
  gridMinXIndex;
  gridMinYIndex;
  gridWidth;
  gridHeight;
  candidates;
  connectionName;
  rootConnectionName;
  regionId;
  solvedPath = null;
  futureConnections;
  hyperParameters;
  connMap;
  obstacleSegments = [];
  obstacleSegmentIndex = null;
  obstacleSegmentsByLayer = new Map;
  obstacleSegmentIndexByLayer = new Map;
  obstacleVias = [];
  obstacleViaIndex = null;
  freePlanarObstaclePoints = new Map;
  cachedPlanarTraceProximity;
  cachedPlanarViaProximity;
  debug_exploredNodesOrdered;
  debug_nodesTooCloseToObstacle;
  debug_nodePathToParentIntersectsObstacle;
  debugEnabled;
  initialNodeGridOffset;
  constructor(e3) {
    super(), this.bounds = e3.bounds, this.connMap = e3.connMap, this.hyperParameters = e3.hyperParameters ?? {}, this.CELL_SIZE_FACTOR = this.hyperParameters.CELL_SIZE_FACTOR ?? 1, this.boundsSize = { width: this.bounds.maxX - this.bounds.minX, height: this.bounds.maxY - this.bounds.minY }, this.boundsCenter = { x: (this.bounds.minX + this.bounds.maxX) / 2, y: (this.bounds.minY + this.bounds.maxY) / 2 }, this.connectionName = e3.connectionName, this.rootConnectionName = e3.rootConnectionName, this.regionId = e3.regionId, this.obstacleRoutes = e3.obstacleRoutes, this.A = e3.A, this.B = e3.B, this.viaDiameter = e3.viaDiameter ?? 0.3, this.traceThickness = e3.traceThickness ?? 0.15, this.obstacleMargin = e3.obstacleMargin ?? 0.15, this.layerCount = e3.layerCount ?? 2, this.availableZ = e3.availableZ && e3.availableZ.length > 0 ? [...new Set(e3.availableZ)].sort((e4, t3) => e4 - t3) : Array.from({ length: this.layerCount }, (e4, t3) => t3), this.exploredNodes = new Set, this.straightLineDistance = me(this.A, this.B), this.futureConnections = e3.futureConnections ?? [], this.NEARBY_SEGMENT_CLEARANCE = e3.nearbySegmentClearance ?? 0.15, this.debugEnabled = e3.captureSearchDebug ?? true, this.MAX_ITERATIONS = 1e4, this.debug_exploredNodesOrdered = [], this.debug_nodesTooCloseToObstacle = new Set, this.debug_nodePathToParentIntersectsObstacle = new Set, this.numRoutes = this.obstacleRoutes.length + this.futureConnections.length, this.buildObstacleIndexes();
    const t2 = Math.ceil(5 * (this.numRoutes + 1));
    let n2 = this.boundsSize.width / this.cellStep, o3 = this.boundsSize.height / this.cellStep;
    for (;n2 * o3 > t2 ** 2 && !(2 * this.cellStep > e3.minDistBetweenEnteringPoints); )
      this.cellStep *= 2, n2 = this.boundsSize.width / this.cellStep, o3 = this.boundsSize.height / this.cellStep;
    this.cellStep *= this.CELL_SIZE_FACTOR, this.gridMinXIndex = Math.round(this.bounds.minX / this.cellStep) - 1, this.gridMinYIndex = Math.round(this.bounds.minY / this.cellStep) - 1;
    const i3 = Math.round(this.bounds.maxX / this.cellStep) + 1, r3 = Math.round(this.bounds.maxY / this.cellStep) + 1;
    this.gridWidth = i3 - this.gridMinXIndex + 1, this.gridHeight = r3 - this.gridMinYIndex + 1;
    const s2 = Math.abs(this.A.x - this.bounds.minX) < 0.001 && Math.abs(this.B.x - this.bounds.minX) < 0.001 || Math.abs(this.A.x - this.bounds.maxX) < 0.001 && Math.abs(this.B.x - this.bounds.maxX) < 0.001 || Math.abs(this.A.y - this.bounds.minY) < 0.001 && Math.abs(this.B.y - this.bounds.minY) < 0.001 || Math.abs(this.A.y - this.bounds.maxY) < 0.001 && Math.abs(this.B.y - this.bounds.maxY) < 0.001;
    this.futureConnections && this.futureConnections.length === 0 && this.obstacleRoutes.length === 0 && !s2 && this.handleSimpleCases();
    const a3 = { x: Math.round(e3.A.x / (this.cellStep / 2)) * (this.cellStep / 2), y: Math.round(e3.A.y / (this.cellStep / 2)) * (this.cellStep / 2) };
    this.initialNodeGridOffset = { x: a3.x - Math.round(e3.A.x / this.cellStep) * this.cellStep, y: a3.y - Math.round(e3.A.y / this.cellStep) * this.cellStep };
    const c3 = { ...e3.A, z: e3.A.z ?? 0, g: 0, h: 0, f: 0, parent: null }, l3 = { ...e3.A, ...a3, z: e3.A.z ?? 0, g: 0, h: 0, f: 0, parent: c3 }, h2 = (Math.abs(l3.x - e3.A.x) > 0.000000001 || Math.abs(l3.y - e3.A.y) > 0.000000001) && (this.isNodeTooCloseToObstacle(l3) || this.isNodeTooCloseToEdge(l3, false) || this.doesPathToParentIntersectObstacle(l3));
    this.candidates = new Cr([h2 ? c3 : l3]);
  }
  handleSimpleCases() {
    this.solved = true;
    const { A: e3, B: t2 } = this, n2 = e3.z === t2.z ? [e3, t2] : [e3, { ...this.boundsCenter, z: this.A.z }, { ...this.boundsCenter, z: t2.z }, t2];
    this.solvedPath = { connectionName: this.connectionName, rootConnectionName: this.rootConnectionName, regionId: this.regionId, route: n2, traceThickness: this.traceThickness, viaDiameter: this.viaDiameter, vias: this.A.z === this.B.z ? [] : [this.boundsCenter] };
  }
  get viaPenaltyDistance() {
    return this.cellStep + this.straightLineDistance * this.VIA_PENALTY_FACTOR;
  }
  isNodeTooCloseToObstacle(e3, t2, n2, o3) {
    if (t2 ??= this.obstacleMargin, n2 && e3.parent) {
      const n3 = this.getViasInNodePath(e3.parent);
      for (const o4 of n3)
        if (me(e3, o4) < this.viaDiameter / 2 + t2)
          return true;
    }
    const i3 = this.traceThickness + t2, r3 = this.viaDiameter / 2 + this.traceThickness / 2 + t2, s2 = !n2 && this.gridWidth !== undefined && (!o3 || o3.pointQueryProximity === i3) && (this.obstacleViaIndex !== null || this.obstacleSegmentIndexByLayer.has(e3.z)) ? o3?.pointKey ?? this.getNodeKey(e3) : undefined;
    if (s2 !== undefined) {
      this.cachedPlanarTraceProximity === i3 && this.cachedPlanarViaProximity === r3 || (this.freePlanarObstaclePoints.clear(), this.cachedPlanarTraceProximity = i3, this.cachedPlanarViaProximity = r3);
      const t3 = this.freePlanarObstaclePoints.get(s2);
      if (t3 && t3.x === e3.x && t3.y === e3.y && t3.z === e3.z)
        return false;
    }
    const a3 = o3?.segments ?? (n2 ? this.obstacleSegments : this.obstacleSegmentsByLayer.get(e3.z)), c3 = o3?.segmentIds ?? (n2 ? this.obstacleSegmentIndex : this.obstacleSegmentIndexByLayer.get(e3.z))?.search(e3.x - i3, e3.y - i3, e3.x + i3, e3.y + i3) ?? [], l3 = o3?.segmentBounds;
    if (a3)
      for (const t3 of c3) {
        const r4 = a3[t3];
        if (r4 && !r4.connectedToCurrentConnection && ((n2 || r4.z === e3.z) && !(l3 && (l3.maxX < r4.minX || l3.maxY < r4.minY || l3.minX > r4.maxX || l3.minY > r4.maxY) || o3 && (e3.x + i3 < r4.minX || e3.y + i3 < r4.minY || e3.x - i3 > r4.maxX || e3.y - i3 > r4.maxY) || !(Math.sqrt(Tr(e3, r4.A, r4.deltaX, r4.deltaY, r4.lengthSquared)) < i3))))
          return true;
      }
    if (this.obstacleViaIndex) {
      const t3 = this.obstacleViaIndex.search(e3.x - r3, e3.y - r3, e3.x + r3, e3.y + r3);
      for (const n3 of t3) {
        const t4 = this.obstacleVias[n3];
        if (t4 && me(e3, t4) < r3)
          return true;
      }
    }
    return s2 !== undefined && this.freePlanarObstaclePoints.set(s2, { x: e3.x, y: e3.y, z: e3.z }), false;
  }
  isNodeTooCloseToEdge(e3, t2) {
    const n2 = t2 ? this.viaDiameter / 2 + this.obstacleMargin / 2 : this.obstacleMargin / 2, o3 = e3.x < this.bounds.minX + n2 || e3.x > this.bounds.maxX - n2 || e3.y < this.bounds.minY + n2 || e3.y > this.bounds.maxY - n2;
    return !(o3 && !t2 && (me(e3, this.B) < 2 * n2 || me(e3, this.A) < 2 * n2)) && o3;
  }
  doesPathToParentIntersectObstacle(e3, t2) {
    const n2 = e3.parent;
    if (!n2)
      return false;
    const o3 = t2?.segments ?? this.obstacleSegmentsByLayer.get(e3.z);
    if (!o3)
      return false;
    const i3 = e3.z === n2.z && this.obstacleSegments.length > 0 ? this.NEARBY_SEGMENT_CLEARANCE : 0, r3 = Math.min(e3.x, n2.x), s2 = Math.max(e3.x, n2.x), a3 = Math.min(e3.y, n2.y), c3 = Math.max(e3.y, n2.y), l3 = t2?.segmentIds ?? this.obstacleSegmentIndexByLayer.get(e3.z)?.search(r3 - i3, a3 - i3, s2 + i3, c3 + i3) ?? [], h2 = t2?.segmentBounds, d2 = n2.x - e3.x, u2 = n2.y - e3.y, p3 = d2 ** 2 + u2 ** 2;
    for (const m2 of l3) {
      const l4 = o3[m2];
      if (l4 && !l4.connectedToCurrentConnection && (l4.z === e3.z && !(h2 && (h2.maxX < l4.minX || h2.maxY < l4.minY || h2.minX > l4.maxX || h2.minY > l4.maxY) || t2 && (s2 + i3 < l4.minX || c3 + i3 < l4.minY || r3 - i3 > l4.maxX || a3 - i3 > l4.maxY)))) {
        if (he(e3, n2, l4.A, l4.B))
          return true;
        if (i3 > 0 && Rr(e3, n2, d2, u2, p3, l4) < i3)
          return true;
      }
    }
    return false;
  }
  getPlanarObstacleQuery(e3, t2, n2) {
    const o3 = e3.parent;
    if (!o3)
      return;
    const i3 = t2 ? undefined : this.obstacleSegmentIndexByLayer.get(e3.z), r3 = t2?.segments ?? this.obstacleSegmentsByLayer.get(e3.z);
    if (!r3 || !t2 && !i3)
      return;
    const s2 = this.traceThickness + this.obstacleMargin, a3 = e3.z === o3.z && this.obstacleSegments.length > 0 ? this.NEARBY_SEGMENT_CLEARANCE : 0, c3 = Math.min(e3.x - s2, o3.x - a3), l3 = Math.min(e3.y - s2, o3.y - a3), h2 = Math.max(e3.x + s2, o3.x + a3), d2 = Math.max(e3.y + s2, o3.y + a3);
    if (t2) {
      const e4 = t2.segmentBounds ??= { minX: c3, minY: l3, maxX: h2, maxY: d2 };
      return e4.minX = c3, e4.minY = l3, e4.maxX = h2, e4.maxY = d2, t2.pointQueryProximity = s2, t2.pointKey = n2, t2;
    }
    return { segments: r3, segmentIds: i3.search(c3, l3, h2, d2), pointQueryProximity: s2, pointKey: n2 };
  }
  getPlanarNeighborObstacleQuery(e3) {
    const t2 = this.obstacleSegmentIndexByLayer.get(e3.z), n2 = this.obstacleSegmentsByLayer.get(e3.z);
    if (!t2 || !n2)
      return;
    const o3 = this.traceThickness + this.obstacleMargin, i3 = this.obstacleSegments.length > 0 ? this.NEARBY_SEGMENT_CLEARANCE : 0, { minX: r3, minY: s2, maxX: a3, maxY: c3 } = this.bounds, l3 = Nr(e3.x - this.cellStep, r3, a3), h2 = Nr(e3.y - this.cellStep, s2, c3), d2 = Nr(e3.x + this.cellStep, r3, a3), u2 = Nr(e3.y + this.cellStep, s2, c3);
    return { segments: n2, segmentIds: t2.search(Math.min(l3 - o3, e3.x - i3), Math.min(h2 - o3, e3.y - i3), Math.max(d2 + o3, e3.x + i3), Math.max(u2 + o3, e3.y + i3)) };
  }
  buildObstacleIndexes() {
    if (this.freePlanarObstaclePoints.clear(), this.obstacleRoutes.length === 0)
      return this.obstacleSegmentIndex = null, this.obstacleSegmentsByLayer.clear(), this.obstacleSegmentIndexByLayer.clear(), void (this.obstacleViaIndex = null);
    const e3 = [], t2 = [];
    for (const n2 of this.obstacleRoutes) {
      const o3 = this.connMap?.areIdsConnected?.(this.connectionName, n2.connectionName) ?? false;
      for (const t3 of wr(n2)) {
        const n3 = t3.B.x - t3.A.x, i3 = t3.B.y - t3.A.y;
        e3.push({ ...t3, deltaX: n3, deltaY: i3, lengthSquared: n3 ** 2 + i3 ** 2, minX: Math.min(t3.A.x, t3.B.x), minY: Math.min(t3.A.y, t3.B.y), maxX: Math.max(t3.A.x, t3.B.x), maxY: Math.max(t3.A.y, t3.B.y), connectedToCurrentConnection: o3 });
      }
      for (const e4 of n2.vias)
        t2.push(e4);
    }
    if (this.obstacleSegments = e3, this.obstacleVias = t2, this.obstacleSegmentsByLayer.clear(), this.obstacleSegmentIndexByLayer.clear(), e3.length > 0) {
      const t3 = new E2(e3.length);
      for (const n2 of e3)
        t3.add(n2.minX, n2.minY, n2.maxX, n2.maxY);
      t3.finish(), this.obstacleSegmentIndex = t3;
      for (const t4 of e3) {
        if (t4.connectedToCurrentConnection)
          continue;
        const e4 = this.obstacleSegmentsByLayer.get(t4.z);
        e4 ? e4.push(t4) : this.obstacleSegmentsByLayer.set(t4.z, [t4]);
      }
      for (const [e4, t4] of this.obstacleSegmentsByLayer) {
        const n2 = new E2(t4.length);
        for (const e5 of t4)
          n2.add(e5.minX, e5.minY, e5.maxX, e5.maxY);
        n2.finish(), this.obstacleSegmentIndexByLayer.set(e4, n2);
      }
    } else
      this.obstacleSegmentIndex = null;
    if (t2.length > 0) {
      const e4 = new E2(t2.length);
      for (const n2 of t2)
        e4.add(n2.x, n2.y, n2.x, n2.y);
      e4.finish(), this.obstacleViaIndex = e4;
    } else
      this.obstacleViaIndex = null;
  }
  computeH(e3) {
    return me(e3, this.B) + (e3.z !== this.B.z ? this.viaPenaltyDistance : 0);
  }
  computeG(e3) {
    return (e3.parent?.g ?? 0) + (e3.z === e3.parent?.z ? 0 : this.viaPenaltyDistance) + me(e3, e3.parent);
  }
  computeF(e3, t2) {
    return e3 + t2 * this.GREEDY_MULTIPLER;
  }
  setNodeCosts(e3) {
    e3.g = this.computeG(e3), e3.h = this.computeH(e3), e3.f = this.computeF(e3.g, e3.h);
  }
  getNodeKey(e3) {
    const t2 = Math.round(e3.x / this.cellStep) - this.gridMinXIndex, n2 = Math.round(e3.y / this.cellStep) - this.gridMinYIndex;
    return (e3.z * this.gridHeight + n2) * this.gridWidth + t2;
  }
  getNeighbors(e3) {
    const t2 = [];
    let n2, o3 = false;
    const { maxX: i3, minX: r3, maxY: s2, minY: a3 } = this.bounds, c3 = Nr(e3.y - this.cellStep, a3, s2), l3 = Nr(e3.y, a3, s2), h2 = Nr(e3.y + this.cellStep, a3, s2), d2 = Math.round(c3 / this.cellStep) - this.gridMinYIndex, u2 = Math.round(l3 / this.cellStep) - this.gridMinYIndex, p3 = Math.round(h2 / this.cellStep) - this.gridMinYIndex;
    for (let s3 = -1;s3 <= 1; s3++) {
      const a4 = Nr(e3.x + s3 * this.cellStep, r3, i3), m2 = Math.round(a4 / this.cellStep) - this.gridMinXIndex;
      for (let i4 = -1;i4 <= 1; i4++) {
        if (s3 === 0 && i4 === 0)
          continue;
        const r4 = i4 < 0 ? c3 : i4 === 0 ? l3 : h2, g2 = i4 < 0 ? d2 : i4 === 0 ? u2 : p3, f2 = (e3.z * this.gridHeight + g2) * this.gridWidth + m2;
        if (this.exploredNodes.has(f2))
          continue;
        const _2 = { x: a4, y: r4, z: e3.z, g: e3.g, h: e3.h, f: e3.f, parent: e3 };
        o3 || (n2 = this.getPlanarNeighborObstacleQuery(e3), o3 = true);
        const y2 = this.getPlanarObstacleQuery(_2, n2, f2);
        this.isNodeTooCloseToObstacle(_2, undefined, false, y2) ? (this.debugEnabled && this.debug_nodesTooCloseToObstacle.add(f2), this.exploredNodes.add(f2)) : this.isNodeTooCloseToEdge(_2, false) ? this.exploredNodes.add(f2) : this.doesPathToParentIntersectObstacle(_2, y2) ? (this.debugEnabled && this.debug_nodePathToParentIntersectsObstacle.add(f2), this.exploredNodes.add(f2)) : (this.setNodeCosts(_2), t2.push(_2));
      }
    }
    for (const n3 of this.availableZ) {
      if (n3 === e3.z)
        continue;
      const o4 = { x: e3.x, y: e3.y, z: n3, g: e3.g, h: e3.h, f: e3.f, parent: e3 };
      this.exploredNodes.has(this.getNodeKey(o4)) || this.isNodeTooCloseToEdge(o4, true) || this.isNodeTooCloseToObstacle(o4, this.viaDiameter / 2 + this.obstacleMargin / 2, true) || (this.setNodeCosts(o4), t2.push(o4));
    }
    return t2;
  }
  getNodePath(e3) {
    const t2 = [];
    for (;e3; )
      t2.push(e3), e3 = e3.parent;
    return t2;
  }
  getViasInNodePath(e3) {
    const t2 = this.viasInPathByNode.get(e3);
    if (t2)
      return t2;
    const n2 = e3.parent, o3 = n2 ? this.getViasInNodePath(n2) : [], i3 = n2 && e3.z !== n2.z ? [{ x: e3.x, y: e3.y }, ...o3] : o3;
    return this.viasInPathByNode.set(e3, i3), i3;
  }
  setSolvedPath(e3) {
    const t2 = this.getNodePath(e3);
    t2.reverse();
    const n2 = [];
    for (let e4 = 0;e4 < t2.length - 1; e4++)
      t2[e4].z !== t2[e4 + 1].z && n2.push({ x: t2[e4].x, y: t2[e4].y });
    this.solvedPath = { connectionName: this.connectionName, rootConnectionName: this.rootConnectionName, regionId: this.regionId, traceThickness: this.traceThickness, viaDiameter: this.viaDiameter, route: t2.map((e4) => ({ x: e4.x, y: e4.y, z: e4.z })).concat([this.B]), vias: n2 };
  }
  computeProgress(e3, t2, n2) {
    if (t2 === undefined || n2 === undefined)
      return Number.NaN;
    n2 || (t2 += this.viaPenaltyDistance);
    const o3 = 1 - t2 / this.straightLineDistance;
    return Math.max(this.progress || 0, 2 / Math.PI * Math.atan(0.112 * o3 / (1 - o3)));
  }
  _step() {
    let e3 = this.candidates.dequeue(), t2 = e3 ? this.getNodeKey(e3) : undefined;
    for (;e3 && t2 && this.exploredNodes.has(t2); )
      e3 = this.candidates.dequeue(), t2 = e3 ? this.getNodeKey(e3) : undefined;
    if (!e3 || !t2)
      return this.failed = true, void (this.error = "Ran out of candidate nodes to explore");
    this.exploredNodes.add(t2), this.debugEnabled && this.debug_exploredNodesOrdered.push({ key: t2, x: Math.round(e3.x / this.cellStep) * this.cellStep + this.initialNodeGridOffset.x, y: Math.round(e3.y / this.cellStep) * this.cellStep + this.initialNodeGridOffset.y, z: e3.z });
    const n2 = me(e3, this.B);
    if (this.progress = this.computeProgress(e3, n2, e3.z === this.B.z), n2 <= this.cellStep * Math.SQRT2 && e3.z === this.B.z && !this.doesPathToParentIntersectObstacle({ ...e3, parent: e3, x: this.B.x, y: this.B.y }))
      return this.solved = true, void this.setSolvedPath(e3);
    const o3 = this.getNeighbors(e3);
    for (const e4 of o3)
      this.candidates.enqueue(e4);
  }
  visualize() {
    const e3 = { lines: [], points: [], rects: [], circles: [] };
    e3.points.push({ x: this.A.x, y: this.A.y, label: Pr(this.connectionName, this.rootConnectionName, ["Input A", `z: ${this.A.z}`]), color: "orange" }), e3.points.push({ x: this.B.x, y: this.B.y, label: Pr(this.connectionName, this.rootConnectionName, ["Input B", `z: ${this.B.z}`]), color: "orange" }), e3.lines.push({ points: [this.A, this.B], strokeColor: "rgba(255, 0, 0, 0.5)", label: Pr(this.connectionName, this.rootConnectionName, ["Direct Input Connection"]) });
    for (let t2 = 0;t2 < this.obstacleRoutes.length; t2++) {
      const n2 = this.obstacleRoutes[t2];
      for (let o3 = 0;o3 < n2.route.length - 1; o3++) {
        const i3 = n2.route[o3].z;
        e3.lines.push({ points: [n2.route[o3], n2.route[o3 + 1]], strokeColor: i3 === 0 ? "rgba(255, 0, 0, 0.75)" : "rgba(255, 128, 0, 0.25)", strokeWidth: n2.traceThickness, label: Pr(n2.connectionName, n2.rootConnectionName, ["Obstacle Route"]), layer: `obstacle${t2.toString()}` });
      }
    }
    for (let t2 = 0;t2 < this.debug_exploredNodesOrdered.length; t2++) {
      const { key: n2, x: o3, y: i3, z: r3 } = this.debug_exploredNodesOrdered[t2];
      this.debug_nodesTooCloseToObstacle.has(n2) || (this.debug_nodePathToParentIntersectsObstacle.has(n2) || e3.rects.push({ center: { x: o3 + r3 * this.cellStep / 20, y: i3 + r3 * this.cellStep / 20 }, fill: r3 === 0 ? `rgba(255,0,255,${0.3 - t2 / this.debug_exploredNodesOrdered.length * 0.2})` : `rgba(0,0,255,${0.3 - t2 / this.debug_exploredNodesOrdered.length * 0.2})`, width: 0.9 * this.cellStep, height: 0.9 * this.cellStep, label: `Explored (z=${r3})` }));
    }
    if (this.candidates.peek()) {
      const t2 = this.candidates.peek();
      e3.rects.push({ center: { x: t2.x + t2.z * this.cellStep / 20, y: t2.y + t2.z * this.cellStep / 20 }, fill: "rgba(0, 255, 0, 0.8)", width: 0.9 * this.cellStep, height: 0.9 * this.cellStep, label: `Next (z=${t2.z})` });
    }
    for (const t2 of this.obstacleRoutes)
      for (const n2 of t2.vias)
        e3.circles.push({ center: { x: n2.x, y: n2.y }, radius: this.viaDiameter / 2, fill: "rgba(255, 0, 0, 0.5)", label: "Via" });
    if (this.solvedPath) {
      e3.lines.push({ points: this.solvedPath.route, strokeColor: "green", label: Pr(this.solvedPath.connectionName, this.solvedPath.rootConnectionName, ["Solved Route"]) });
      for (const t2 of this.solvedPath.vias)
        e3.circles.push({ center: t2, radius: this.viaDiameter / 2, fill: "green", label: Pr(this.solvedPath.connectionName, this.solvedPath.rootConnectionName, ["Via"]) });
    }
    return e3;
  }
};
function wr(e3) {
  const t2 = [];
  for (let n2 = 0;n2 < e3.route.length - 1; n2++)
    e3.route[n2].z === e3.route[n2 + 1].z && t2.push({ z: e3.route[n2].z, A: e3.route[n2], B: e3.route[n2 + 1] });
  return t2;
}
function Nr(e3, t2, n2) {
  return Math.max(t2, Math.min(e3, n2));
}
function Rr(e3, t2, n2, o3, i3, r3) {
  return Math.sqrt(Math.min(Tr(e3, r3.A, r3.deltaX, r3.deltaY, r3.lengthSquared), Tr(t2, r3.A, r3.deltaX, r3.deltaY, r3.lengthSquared), Tr(r3.A, e3, n2, o3, i3), Tr(r3.B, e3, n2, o3, i3)));
}
function Tr(e3, t2, n2, o3, i3) {
  if (i3 === 0) {
    const n3 = e3.x - t2.x, o4 = e3.y - t2.y;
    return n3 * n3 + o4 * o4;
  }
  const r3 = Math.max(0, Math.min(1, ((e3.x - t2.x) * n2 + (e3.y - t2.y) * o3) / i3)), s2 = t2.x + r3 * n2, a3 = t2.y + r3 * o3, c3 = e3.x - s2, l3 = e3.y - a3;
  return c3 * c3 + l3 * l3;
}
var Er = class extends Mr {
  FUTURE_CONNECTION_PROX_TRACE_PENALTY_FACTOR = 2;
  FUTURE_CONNECTION_PROX_VIA_PENALTY_FACTOR = 1;
  FUTURE_CONNECTION_PROXIMITY_VD = 10;
  MISALIGNED_DIST_PENALTY_FACTOR = 5;
  VIA_PENALTY_FACTOR_2 = 1;
  FLIP_TRACE_ALIGNMENT_DIRECTION = false;
  FUTURE_CONNECTION_VIA_TRACE_CLEARANCE = 0.1;
  futureConnectionPoints;
  futureConnectionSegmentsCache = null;
  closestFuturePointCacheCoordinates = new Float64Array(1024);
  closestFuturePointCacheIndices = new Int32Array(256).fill(-2);
  cachedFutureConnectionPoints;
  cachedFutureConnectionPointCount = 0;
  constructor(e3) {
    super({ ...e3, nearbySegmentClearance: e3.nearbySegmentClearance ?? (e3.traceThickness ?? 0.15) / 2 + (e3.obstacleMargin ?? 0.15) });
    for (const t3 in e3.hyperParameters)
      this[t3] = e3.hyperParameters[t3];
    const t2 = this.boundsSize.width / this.viaDiameter, n2 = Math.max(1, this.numRoutes);
    this.VIA_PENALTY_FACTOR = t2 / n2 * 0.3 * this.VIA_PENALTY_FACTOR_2, this.futureConnectionPoints = this.futureConnections.flatMap((e4) => e4.points);
  }
  getClosestFutureConnectionPoint(e3) {
    this.cachedFutureConnectionPoints === this.futureConnectionPoints && this.cachedFutureConnectionPointCount === this.futureConnectionPoints.length || (this.closestFuturePointCacheIndices.fill(-2), this.cachedFutureConnectionPoints = this.futureConnectionPoints, this.cachedFutureConnectionPointCount = this.futureConnectionPoints.length);
    const t2 = this.getNodeKey(e3), n2 = Number.isSafeInteger(t2) ? Math.abs(t2 % 256) : -1, o3 = 4 * n2, i3 = this.viaPenaltyDistance, r3 = this.closestFuturePointCacheIndices[n2];
    if (n2 >= 0 && r3 >= -1 && this.closestFuturePointCacheCoordinates[o3] === e3.x && this.closestFuturePointCacheCoordinates[o3 + 1] === e3.y && this.closestFuturePointCacheCoordinates[o3 + 2] === e3.z && this.closestFuturePointCacheCoordinates[o3 + 3] === i3)
      return r3 === -1 ? null : this.futureConnectionPoints[r3];
    let s2 = 1 / 0, a3 = null, c3 = -1, l3 = 0;
    for (const t3 of this.futureConnectionPoints) {
      const n3 = me(e3, t3) + (e3.z !== t3.z ? this.viaPenaltyDistance : 0);
      n3 < s2 && (s2 = n3, a3 = t3, c3 = l3), l3++;
    }
    return n2 >= 0 && (this.closestFuturePointCacheCoordinates[o3] = e3.x, this.closestFuturePointCacheCoordinates[o3 + 1] = e3.y, this.closestFuturePointCacheCoordinates[o3 + 2] = e3.z, this.closestFuturePointCacheCoordinates[o3 + 3] = i3, this.closestFuturePointCacheIndices[n2] = c3), a3;
  }
  getFutureConnectionSegments() {
    if (this.futureConnectionSegmentsCache)
      return this.futureConnectionSegmentsCache;
    const e3 = [];
    for (const t2 of this.futureConnections) {
      if (t2.connectionName === this.connectionName || (this.connMap?.areIdsConnected?.(this.connectionName, t2.connectionName) ?? false))
        continue;
      const [n2, ...o3] = t2.points;
      if (n2)
        for (const i3 of o3)
          Math.abs(n2.x - i3.x) < 0.000000001 && Math.abs(n2.y - i3.y) < 0.000000001 || e3.push({ connectionName: t2.connectionName, start: n2, end: i3 });
    }
    return this.futureConnectionSegmentsCache = e3, e3;
  }
  isViaTooCloseToFutureConnectionTrace(e3) {
    const t2 = this.viaDiameter / 2 + this.traceThickness / 2 + this.FUTURE_CONNECTION_VIA_TRACE_CLEARANCE;
    for (const n2 of this.getFutureConnectionSegments())
      if (pe(e3, n2.start, n2.end) < t2)
        return true;
    return false;
  }
  isNodeTooCloseToObstacle(e3, t2, n2, o3) {
    return !!super.isNodeTooCloseToObstacle(e3, t2, n2, o3) || !(!n2 || !this.isViaTooCloseToFutureConnectionTrace(e3));
  }
  diminishCloseToGoal(e3) {
    const t2 = me(e3, this.B);
    return 1 - Math.exp(-t2 / this.straightLineDistance * 5);
  }
  getFutureConnectionPenalty(e3, t2) {
    let n2 = 0;
    const o3 = this.getClosestFutureConnectionPoint(e3), i3 = me(e3, this.B);
    if (o3) {
      const r3 = me(e3, o3);
      if (i3 <= r3)
        return 0;
      const s2 = r3 / (this.viaDiameter * this.FUTURE_CONNECTION_PROXIMITY_VD);
      n2 = (t2 ? this.straightLineDistance * this.FUTURE_CONNECTION_PROX_VIA_PENALTY_FACTOR : this.straightLineDistance * this.FUTURE_CONNECTION_PROX_TRACE_PENALTY_FACTOR) * Math.exp(5 * -s2);
    }
    return n2;
  }
  computeH(e3) {
    const t2 = me(e3, this.B) ** 1.6;
    this.straightLineDistance;
    return t2 + (e3.z !== this.B.z ? this.viaPenaltyDistance : 0) + this.getFutureConnectionPenalty(e3, e3.z !== e3.parent?.z);
  }
  computeG(e3) {
    const t2 = Math.abs(e3.x - e3.parent.x), n2 = Math.abs(e3.y - e3.parent.y), o3 = Math.sqrt(t2 ** 2 + n2 ** 2), i3 = e3.z % 2 == 0, r3 = this.FLIP_TRACE_ALIGNMENT_DIRECTION ? i3 ? t2 : n2 : i3 ? n2 : t2;
    return (e3.parent?.g ?? 0) + (e3.z === e3.parent?.z ? 0 : this.viaPenaltyDistance) + o3 + r3 * this.MISALIGNED_DIST_PENALTY_FACTOR + this.getFutureConnectionPenalty(e3, e3.z !== e3.parent?.z);
  }
  setNodeCosts(e3) {
    const t2 = Math.abs(e3.x - e3.parent.x), n2 = Math.abs(e3.y - e3.parent.y), o3 = Math.sqrt(t2 ** 2 + n2 ** 2), i3 = e3.z % 2 == 0, r3 = this.FLIP_TRACE_ALIGNMENT_DIRECTION ? i3 ? t2 : n2 : i3 ? n2 : t2, s2 = (e3.parent?.g ?? 0) + (e3.z === e3.parent?.z ? 0 : this.viaPenaltyDistance) + o3 + r3 * this.MISALIGNED_DIST_PENALTY_FACTOR, a3 = me(e3, this.B) ** 1.6 + (e3.z !== this.B.z ? this.viaPenaltyDistance : 0), c3 = this.getFutureConnectionPenalty(e3, e3.z !== e3.parent?.z);
    e3.g = s2 + c3, e3.h = a3 + c3, e3.f = this.computeF(e3.g, e3.h);
  }
};
var Ar = (e3) => {
  let t2 = 1 / 0;
  const n2 = e3.portPoints;
  for (let e4 = 0;e4 < n2.length; e4++)
    for (let o3 = e4 + 1;o3 < n2.length; o3++) {
      const i3 = n2[e4], r3 = n2[o3];
      if (i3.z !== r3.z)
        continue;
      if (i3.rootConnectionName && i3.rootConnectionName === r3.rootConnectionName)
        continue;
      const s2 = Math.sqrt((i3.x - r3.x) ** 2 + (i3.y - r3.y) ** 2);
      t2 = Math.min(t2, s2);
    }
  return t2 === 1 / 0 ? 0 : t2;
};
var Or = (e3) => {
  const t2 = new Map, n2 = new Map, o3 = new Map;
  for (const { connectionName: i3, rootConnectionName: r3, x: s2, y: a3, z: c3 } of e3.portPoints) {
    r3 && n2.set(i3, r3);
    let e4 = t2.get(i3), l3 = o3.get(i3);
    e4 && l3 || (e4 = [], l3 = new Set, t2.set(i3, e4), o3.set(i3, l3));
    const h2 = c3 ?? 0, d2 = `${s2.toFixed(6)},${a3.toFixed(6)},${h2}`;
    l3.has(d2) || (l3.add(d2), e4.push({ x: s2, y: a3, z: h2 }));
  }
  return { connectionPointsByName: t2, rootConnectionNameByConnectionName: n2, minDistBetweenEnteringPoints: Ar(e3) };
};
var kr = (e3, t2, n2 = []) => [e3, t2 ? `rootConnectionName: ${t2}` : undefined, ...n2].filter(Boolean).join(`
`);
var Dr = (e3) => `${e3.x.toFixed(6)},${e3.y.toFixed(6)},${e3.z}`;
var Lr = class extends ni {
  getSolverName() {
    return "IntraNodeRouteSolver";
  }
  nodeWithPortPoints;
  colorMap;
  unsolvedConnections;
  originalConnectionPointsByName;
  rootConnectionNameByConnectionName;
  totalConnections;
  solvedRoutes;
  failedSubSolvers;
  hyperParameters;
  minDistBetweenEnteringPoints;
  viaDiameter;
  traceWidth;
  obstacleMargin;
  captureSearchDebug;
  rerouteAttemptsByConnection;
  POSTROUTE_VIA_TRACE_CLEARANCE = 0.1;
  MAX_POSTROUTE_REPAIR_ATTEMPTS = 2;
  activeSubSolver = null;
  connMap;
  get failedSolvers() {
    return this.failedSubSolvers;
  }
  get activeSolver() {
    return this.activeSubSolver;
  }
  constructor(e3) {
    const { nodeWithPortPoints: t2, colorMap: n2 } = e3;
    super(), this.nodeWithPortPoints = t2, this.colorMap = n2 ?? {}, this.solvedRoutes = [], this.hyperParameters = e3.hyperParameters ?? {}, this.failedSubSolvers = [], this.connMap = e3.connMap, this.viaDiameter = e3.viaDiameter ?? 0.3, this.traceWidth = e3.traceWidth ?? 0.15, this.obstacleMargin = e3.obstacleMargin ?? 0.15, this.captureSearchDebug = e3.captureSearchDebug ?? true;
    const o3 = e3.precomputedIntraNodeRouteParams ?? Or(t2);
    this.rootConnectionNameByConnectionName = new Map(o3.rootConnectionNameByConnectionName), this.originalConnectionPointsByName = new Map(Array.from(o3.connectionPointsByName.entries()).map(([e4, t3]) => [e4, t3.map((e5) => ({ ...e5 }))])), this.unsolvedConnections = Array.from(this.originalConnectionPointsByName.entries().map(([e4, t3]) => ({ connectionName: e4, rootConnectionName: this.rootConnectionNameByConnectionName.get(e4), points: [...t3] }))), this.rerouteAttemptsByConnection = new Map, this.hyperParameters.SHUFFLE_SEED && (this.unsolvedConnections = Sr(this.unsolvedConnections, this.hyperParameters.SHUFFLE_SEED ?? 0), this.unsolvedConnections = this.unsolvedConnections.map(({ points: e4, ...t3 }, n3) => ({ ...t3, points: Sr(e4, 7117 * n3 + (this.hyperParameters.SHUFFLE_SEED ?? 0)) }))), this.totalConnections = this.unsolvedConnections.length, this.MAX_ITERATIONS = 1000 * this.totalConnections ** 1.5, this.minDistBetweenEnteringPoints = o3.minDistBetweenEnteringPoints;
  }
  computeProgress() {
    return (this.solvedRoutes.length + (this.activeSubSolver?.progress || 0)) / this.totalConnections;
  }
  getSingleRouteSolverOpts(e3) {
    const { connectionName: t2, rootConnectionName: n2, points: o3 } = e3;
    return { connectionName: t2, rootConnectionName: n2, regionId: this.nodeWithPortPoints.capacityMeshNodeId, minDistBetweenEnteringPoints: this.minDistBetweenEnteringPoints, bounds: ro(this.nodeWithPortPoints), A: { x: o3[0].x, y: o3[0].y, z: o3[0].z }, B: { x: o3[o3.length - 1].x, y: o3[o3.length - 1].y, z: o3[o3.length - 1].z }, obstacleRoutes: this.connMap ? this.solvedRoutes.filter((e4) => !this.connMap.areIdsConnected(e4.connectionName, t2)) : this.solvedRoutes, futureConnections: this.unsolvedConnections, layerCount: this.nodeWithPortPoints.portPoints.reduce((e4, t3) => Math.max(e4, (t3.z ?? 0) + 1), 2), availableZ: this.nodeWithPortPoints.availableZ && this.nodeWithPortPoints.availableZ.length > 0 ? this.nodeWithPortPoints.availableZ : [...new Set(this.nodeWithPortPoints.portPoints.map((e4) => e4.z ?? 0))].sort((e4, t3) => e4 - t3), hyperParameters: this.hyperParameters, connMap: this.connMap, viaDiameter: this.viaDiameter, traceThickness: this.traceWidth, obstacleMargin: this.obstacleMargin, captureSearchDebug: this.captureSearchDebug };
  }
  trySolveSamePointLayerChange(e3) {
    const t2 = this.getSingleRouteSolverOpts(e3), n2 = new Er(t2), { A: o3, B: i3 } = t2, r3 = { x: o3.x, y: o3.y };
    if (!zr(n2, r3, o3, i3))
      return false;
    const s2 = [{ x: o3.x, y: o3.y, z: o3.z }, { ...r3, z: o3.z }, { ...r3, z: i3.z }, { x: i3.x, y: i3.y, z: i3.z }].filter((e4, t3, n3) => t3 === 0 || Math.abs(e4.x - n3[t3 - 1].x) > 0.000001 || Math.abs(e4.y - n3[t3 - 1].y) > 0.000001 || e4.z !== n3[t3 - 1].z);
    return this.solvedRoutes.push({ connectionName: e3.connectionName, rootConnectionName: e3.rootConnectionName, regionId: this.nodeWithPortPoints.capacityMeshNodeId, traceThickness: this.traceWidth, viaDiameter: this.viaDiameter, route: s2, vias: [{ x: r3.x, y: r3.y }] }), true;
  }
  queueExtraBranchesForMultiPointConnection(e3) {
    const [t2, ...n2] = ((e4) => {
      const t3 = new Set, n3 = [];
      for (const o3 of e4) {
        const e5 = Dr(o3);
        t3.has(e5) || (t3.add(e5), n3.push(o3));
      }
      return n3;
    })(e3.points);
    if (!t2 || n2.length <= 1)
      return false;
    for (const o3 of n2)
      this.unsolvedConnections.push({ connectionName: e3.connectionName, rootConnectionName: e3.rootConnectionName, points: [t2, o3] });
    return true;
  }
  getAvailableZLayers() {
    return this.nodeWithPortPoints.availableZ && this.nodeWithPortPoints.availableZ.length > 0 ? [...new Set(this.nodeWithPortPoints.availableZ)].sort((e3, t2) => e3 - t2) : [...new Set(this.nodeWithPortPoints.portPoints.map((e3) => e3.z ?? 0))].sort((e3, t2) => e3 - t2);
  }
  getFirstSolvedViaTraceConflict() {
    if (this.solvedRoutes.length < 2)
      return null;
    const e3 = new xr(this.solvedRoutes), t2 = this.getAvailableZLayers();
    for (const n2 of this.solvedRoutes) {
      const o3 = n2.viaDiameter / 2 + this.POSTROUTE_VIA_TRACE_CLEARANCE;
      for (const i3 of n2.vias)
        for (const r3 of t2) {
          const t3 = e3.getConflictingRoutesNearPoint({ x: i3.x, y: i3.y, z: r3 }, o3).filter(({ conflictingRoute: e4 }) => e4.connectionName !== n2.connectionName && !this.connMap?.areIdsConnected(n2.connectionName, e4.connectionName));
          if (t3.length > 0)
            return { route: n2, via: i3, conflictingRoute: t3[0].conflictingRoute };
        }
    }
    return null;
  }
  queueConnectionForPostrouteRepair(e3) {
    const t2 = this.originalConnectionPointsByName.get(e3);
    return !(!t2 || t2.length < 2) && (this.solvedRoutes = this.solvedRoutes.filter((t3) => t3.connectionName !== e3), this.unsolvedConnections.push({ connectionName: e3, rootConnectionName: this.rootConnectionNameByConnectionName.get(e3), points: t2.map((e4) => ({ ...e4 })) }), this.rerouteAttemptsByConnection.set(e3, (this.rerouteAttemptsByConnection.get(e3) ?? 0) + 1), true);
  }
  _step() {
    if (this.activeSubSolver) {
      if (this.activeSubSolver.step(), this.progress = this.computeProgress(), this.activeSubSolver.solved)
        this.solvedRoutes.push(this.activeSubSolver.solvedPath), this.activeSubSolver = null;
      else if (this.activeSubSolver.failed) {
        const e4 = this.activeSubSolver;
        this.activeSubSolver = null, this.error = e4.error, this.captureSearchDebug && this.failedSubSolvers.push(e4), this.failed = true;
      }
      return;
    }
    const e3 = this.unsolvedConnections.pop();
    if (this.progress = this.computeProgress(), !e3) {
      const e4 = this.getFirstSolvedViaTraceConflict();
      if (e4) {
        if ((this.rerouteAttemptsByConnection.get(e4.route.connectionName) ?? 0) >= this.MAX_POSTROUTE_REPAIR_ATTEMPTS)
          return this.error = ["Post-route via/trace clearance repair exceeded retry budget", `route: ${e4.route.connectionName}`, `conflicts with: ${e4.conflictingRoute.connectionName}`, `via: (${e4.via.x.toFixed(3)}, ${e4.via.y.toFixed(3)})`].join(`
`), void (this.failed = true);
        if (this.queueConnectionForPostrouteRepair(e4.route.connectionName))
          return void (this.progress = this.computeProgress());
      }
      return void (this.solved = this.failedSubSolvers.length === 0);
    }
    if (e3.points.length !== 1 && !(e3.points.length > 2 && this.queueExtraBranchesForMultiPointConnection(e3))) {
      if (e3.points.length === 2) {
        const [t2, n2] = e3.points, o3 = Math.abs(t2.x - n2.x) < 0.000001, i3 = Math.abs(t2.y - n2.y) < 0.000001;
        if (o3 && i3 && t2.z === n2.z)
          return;
        if (o3 && i3 && t2.z !== n2.z && this.trySolveSamePointLayerChange(e3))
          return;
      }
      this.activeSubSolver = new Er(this.getSingleRouteSolverOpts(e3));
    }
  }
  visualize() {
    const e3 = { lines: [], points: [], rects: [], circles: [] };
    for (const t3 of this.nodeWithPortPoints.portPoints)
      e3.points.push({ x: t3.x, y: t3.y, label: kr(t3.connectionName, t3.rootConnectionName, [`layer: ${t3.z}`]), color: this.colorMap[t3.connectionName] ?? "blue" });
    for (let t3 = 0;t3 < this.solvedRoutes.length; t3++) {
      const n3 = this.solvedRoutes[t3];
      if (n3.route.length > 0) {
        const o4 = this.colorMap[n3.connectionName] ?? "blue", i4 = n3.rootConnectionName ?? this.rootConnectionNameByConnectionName.get(n3.connectionName);
        for (let r4 = 0;r4 < n3.route.length - 1; r4++) {
          const s2 = n3.route[r4], a3 = n3.route[r4 + 1];
          e3.lines.push({ points: [s2, a3], label: kr(n3.connectionName, i4, [`layer: ${s2.z}`]), strokeColor: s2.z === 0 ? Ao(o4, 0.2) : Ao(o4, 0.8), layer: `route-layer-${s2.z}`, step: t3, strokeWidth: n3.traceThickness });
        }
        for (const r4 of n3.vias)
          e3.circles.push({ center: { x: r4.x, y: r4.y }, radius: n3.viaDiameter / 2, fill: Ao(o4, 0.5), layer: "via", step: t3, label: kr(n3.connectionName, i4, ["via"]) });
      }
    }
    const t2 = ro(this.nodeWithPortPoints), { minX: n2, minY: o3, maxX: i3, maxY: r3 } = t2;
    return e3.lines.push({ points: [{ x: n2, y: o3 }, { x: i3, y: o3 }, { x: i3, y: r3 }, { x: n2, y: r3 }, { x: n2, y: o3 }], strokeColor: "rgba(255, 0, 0, 0.25)", strokeDash: "4 4", layer: "border" }), e3;
  }
};
var zr = (e3, t2, n2, o3) => {
  const i3 = { x: t2.x, y: t2.y, z: n2.z, parent: { x: n2.x, y: n2.y, z: n2.z, g: 0, h: 0, f: 0, parent: null }, g: 0, h: 0, f: 0 };
  return !e3.isNodeTooCloseToObstacle(i3, e3.viaDiameter / 2 + e3.obstacleMargin / 2, true) && !e3.isNodeTooCloseToEdge(i3, true);
};
var Br = (e3) => Math.round(200 * e3) / 200;
var Fr = (e3) => typeof structuredClone == "function" ? structuredClone(e3) : JSON.parse(JSON.stringify(e3));
oo();
var jr = class extends Lr {
  getSolverName() {
    return "CachedIntraNodeRouteSolver";
  }
  cacheProvider;
  cacheHit = false;
  hasAttemptedToUseCache = false;
  initialUnsolvedConnections;
  constructor(e3) {
    super(e3), this.cacheProvider = e3.cacheProvider === undefined ? no() : e3.cacheProvider, this.initialUnsolvedConnections = this.unsolvedConnections.map((e4) => ({ ...e4, points: e4.points.map((e5) => ({ ...e5 })) })), (this.solved || this.failed) && this.cacheProvider && !this.cacheHit && this.saveToCacheSync();
  }
  _step() {
    if (!this.hasAttemptedToUseCache && this.cacheProvider && this.attemptToUseCacheSync())
      return;
    const e3 = this.solved, t2 = this.failed;
    super._step(), !this.cacheProvider || this.cacheHit || !this.solved && !this.failed || e3 || t2 || this.saveToCacheSync();
  }
  computeCacheKeyAndTransform() {
    const e3 = this.nodeWithPortPoints.center, t2 = this.initialUnsolvedConnections.map(({ connectionName: t3, rootConnectionName: n3, points: o4 }) => ({ connectionName: t3, rootConnectionName: n3, points: o4.map((n4) => ({ connectionName: t3, x: Br(n4.x - e3.x), y: Br(n4.y - e3.y), z: n4.z ?? 0 })) })), n2 = [...this.nodeWithPortPoints.portPoints].sort((e4, t3) => e4.connectionName !== t3.connectionName ? e4.connectionName.localeCompare(t3.connectionName) : (e4.portPointId ?? "") !== (t3.portPointId ?? "") ? (e4.portPointId ?? "").localeCompare(t3.portPointId ?? "") : e4.x !== t3.x ? e4.x - t3.x : e4.y !== t3.y ? e4.y - t3.y : (e4.z ?? 0) - (t3.z ?? 0)).map((t3) => ({ connectionName: t3.connectionName, rootConnectionName: t3.rootConnectionName, portPointId: t3.portPointId, prevPortPointId: t3.prevPortPointId, nextPortPointId: t3.nextPortPointId, x: Br(t3.x - e3.x), y: Br(t3.y - e3.y), z: t3.z ?? 0 })), o3 = Object.fromEntries(Object.entries(this.hyperParameters ?? {}).filter(([, e4]) => e4 !== undefined).sort(([e4], [t3]) => e4.localeCompare(t3))), i3 = this.connMap ? this.initialUnsolvedConnections.map(({ connectionName: e4 }) => ({ connectionName: e4, connectedIds: [...new Set(this.connMap.getIdsConnectedToNet(e4) ?? [])].sort() })) : undefined, r3 = { cacheSchemaVersion: 6, node: { width: Br(this.nodeWithPortPoints.width), height: Br(this.nodeWithPortPoints.height), center: { x: Br(this.nodeWithPortPoints.center.x), y: Br(this.nodeWithPortPoints.center.y) }, availableZ: this.nodeWithPortPoints.availableZ ? [...this.nodeWithPortPoints.availableZ].sort() : undefined, portPoints: n2 }, normalizedConnections: t2, normalizedHyperParameters: o3, minDistBetweenEnteringPoints: Br(this.minDistBetweenEnteringPoints), traceWidth: Br(this.traceWidth), viaDiameter: Br(this.viaDiameter), obstacleMargin: Br(this.obstacleMargin), normalizedConnMap: i3 }, s2 = JSON.stringify(r3, (e4, t3) => typeof t3 != "number" || Number.isFinite(t3) ? typeof t3 == "string" && (t3 === "u:" || t3.startsWith("n:") || t3.startsWith("s:")) ? `s:${t3}` : t3 === undefined ? "u:" : t3 : `n:${t3.toString()}`), a3 = `intranode-solver:${import_object_hash.default(s2)}`, c3 = {};
    return this.cacheKey = a3, this.cacheToSolveSpaceTransform = c3, { cacheKey: a3, cacheToSolveSpaceTransform: c3 };
  }
  applyCachedSolution(e3) {
    e3.success ? (this.solvedRoutes = Fr(e3.solvedRoutes), this.solved = true, this.failed = false) : (this.solvedRoutes = [], this.failedSubSolvers = [], this.solved = false, this.failed = true, this.error = e3.error ?? this.error), this.unsolvedConnections = [], this.activeSubSolver = null, this.cacheHit = true, this.progress = 1;
  }
  attemptToUseCacheSync() {
    if (this.hasAttemptedToUseCache = true, !this.cacheProvider?.isSyncCache)
      return false;
    if (!this.cacheKey)
      try {
        this.computeCacheKeyAndTransform();
      } catch (e3) {
        return console.error("Error computing cache key:", e3), false;
      }
    if (!this.cacheKey)
      return console.error("Failed to compute cache key."), false;
    try {
      const e3 = this.cacheProvider.getCachedSolutionSync(this.cacheKey);
      if (e3 != null)
        return this.applyCachedSolution(e3), true;
    } catch (e3) {
      console.error("Error attempting to use cache:", e3);
    }
    return false;
  }
  saveToCacheSync() {
    if (!this.cacheProvider?.isSyncCache)
      return;
    if (!this.cacheKey)
      try {
        this.computeCacheKeyAndTransform();
      } catch (e4) {
        return void console.error("Error computing cache key during save:", e4);
      }
    if (!this.cacheKey)
      return void console.error("Failed to compute cache key before saving.");
    const e3 = this.failed ? { success: false, error: this.error ?? undefined } : { success: true, solvedRoutes: Fr(this.solvedRoutes) };
    try {
      this.cacheProvider.setCachedSolutionSync(this.cacheKey, e3);
    } catch (e4) {
      console.error("Error saving solution to cache:", e4);
    }
  }
};
function $r(e3, t2) {
  const n2 = [];
  for (let o3 = e3.length - 1;o3 >= 0; o3--) {
    t2("priorityDecompositionGroups");
    const i3 = e3[o3];
    if (i3.points.length < 2)
      return null;
    let r3 = i3.points;
    for (const e4 of r3)
      if (t2("priorityDecompositionPoints"), !Number.isFinite(e4.x) || !Number.isFinite(e4.y) || !Number.isSafeInteger(e4.z))
        return null;
    if (r3.length > 2) {
      const e4 = new Set, n3 = [];
      for (const o4 of i3.points) {
        t2("priorityDecompositionDedupes");
        const i4 = `${o4.x.toFixed(6)},${o4.y.toFixed(6)},${o4.z}`;
        e4.has(i4) || (e4.add(i4), n3.push(o4));
      }
      if (r3 = n3, r3.length < 3)
        return null;
    }
    for (let e4 = r3.length - 1;e4 >= 1; e4--) {
      t2("priorityDecompositionBranches");
      const o4 = r3[0], s2 = r3[e4];
      if (Math.abs(o4.x - s2.x) < 0.000001 && Math.abs(o4.y - s2.y) < 0.000001 && (o4.z === s2.z || o4.x !== s2.x || o4.y !== s2.y))
        return null;
      n2.push({ connectionName: i3.connectionName, rootConnectionName: i3.rootConnectionName, points: [{ ...o4 }, { ...s2 }] });
    }
  }
  return n2.length >= 2 ? n2 : null;
}
var Yr = (e3) => (e3 % 360 + 360) % 360;
var Xr = (e3, t2) => {
  const { ccwRotationDegrees: n2, ...o3 } = e3, i3 = ((e4) => {
    const t3 = Yr(e4), n3 = [0, 90, 180, 270];
    for (const e5 of n3)
      if (Math.min(Math.abs(t3 - e5), 360 - Math.abs(t3 - e5)) <= 0.01)
        return e5;
    return null;
  })(t2);
  return i3 === 90 || i3 === 270 ? { ...o3, width: e3.height, height: e3.width } : o3;
};
var Hr = (e3, t2) => {
  if (So(e3).length > 0 && !So(e3).some((e4) => t2.layers.includes(e4)))
    return false;
  const n2 = Ht(en(-(t2.ccwRotationDegrees ?? 0)), { x: e3.x - t2.center.x, y: e3.y - t2.center.y }), o3 = { x: t2.center.x + n2.x, y: t2.center.y + n2.y };
  return xe(o3, Le(t2));
};
var Vr = (e3, t2) => {
  const { minX: n2, maxX: o3, minY: i3, maxY: r3 } = Le(t2);
  return { x: Math.max(n2, Math.min(o3, e3.x)), y: Math.max(i3, Math.min(r3, e3.y)) };
};
var Wr = (e3, t2) => e3.obstacleId ?? `${e3.componentId ?? "obstacle"}_${t2}`;
function Gr(e3, t2 = 2) {
  const { center: n2, width: o3, height: i3, rotation: r3 } = e3, s2 = [], a3 = Math.max(1, Math.ceil(t2)), c3 = r3 * Math.PI / 180, l3 = Math.cos(c3), h2 = Math.sin(c3);
  if (o3 >= i3) {
    const e4 = o3 / a3;
    for (let t3 = 0;t3 < a3; t3++) {
      const o4 = (t3 - a3 / 2 + 0.5) * e4, r4 = o4 * l3, c4 = o4 * h2, d2 = Math.abs(e4 * l3) + Math.abs(i3 * h2), u2 = Math.abs(e4 * h2) + Math.abs(i3 * l3);
      s2.push({ center: { x: n2.x + r4, y: n2.y + c4 }, width: d2, height: u2 });
    }
  } else {
    const e4 = i3 / a3;
    for (let t3 = 0;t3 < a3; t3++) {
      const i4 = (t3 - a3 / 2 + 0.5) * e4, r4 = -i4 * h2, c4 = i4 * l3, d2 = Math.abs(o3 * l3) + Math.abs(e4 * h2), u2 = Math.abs(o3 * h2) + Math.abs(e4 * l3);
      s2.push({ center: { x: n2.x + r4, y: n2.y + c4 }, width: d2, height: u2 });
    }
  }
  return s2;
}
var Ur = (e3) => {
  if (e3.type === "oval")
    return Ur({ ...e3, type: "rect" });
  const t2 = e3.ccwRotationDegrees;
  if (typeof t2 != "number" || !Number.isFinite(t2))
    return [e3];
  if (((e4) => {
    const t3 = Yr(e4);
    return [0, 90, 180, 270].some((e5) => Math.min(Math.abs(t3 - e5), 360 - Math.abs(t3 - e5)) <= 0.01);
  })(t2))
    return [Xr(e3, t2)];
  const { ccwRotationDegrees: n2, ...o3 } = e3, i3 = { center: e3.center, width: e3.width, height: e3.height, rotation: t2 }, r3 = ((e4) => {
    const t3 = Math.max(e4.width, e4.height), n3 = Math.min(e4.width, e4.height);
    return e4.obstacleId?.startsWith("trace_obstacle_") ? Math.max(2, Math.ceil(t3 / 0.75)) : n3 <= 0 ? 2 : t3 / n3 < 2 || n3 >= 0.9 ? null : Math.max(2, Math.ceil(t3 / 0.75));
  })(e3), s2 = e3.connectedTo.length > 0 && !e3.obstacleId?.startsWith("trace_obstacle_"), a3 = e3.isNonPlatedHole || s2 ? ((e4) => {
    const t3 = e4.rotation * Math.PI / 180, n3 = Math.cos(t3), o4 = Math.sin(t3), i4 = [-1, 1].flatMap((t4) => [-1, 1].map((i5) => {
      const r5 = t4 * (e4.width / 2), s4 = i5 * (e4.height / 2);
      return { x: e4.center.x + r5 * n3 - s4 * o4, y: e4.center.y + r5 * o4 + s4 * n3 };
    })), r4 = [i4[0], i4[2], i4[3], i4[1]], s3 = Math.min(...r4.map((e5) => e5.x)), a4 = Math.max(...r4.map((e5) => e5.x)), c4 = Math.min(...r4.map((e5) => e5.y)), l3 = Math.max(...r4.map((e5) => e5.y)), h2 = a4 - s3 <= l3 - c4 ? "x" : "y", d2 = h2 === "x" ? s3 : c4, u2 = h2 === "x" ? a4 : l3, p3 = Math.max(1, Math.ceil((u2 - d2) / 0.4)), m2 = (u2 - d2) / p3, g2 = (e5, t4, n4) => {
      const o5 = [], i5 = (e6) => e6[h2];
      for (let r5 = 0;r5 < e5.length; r5++) {
        const s4 = e5[r5], a5 = e5[(r5 + 1) % e5.length], c5 = i5(s4), l4 = i5(a5), h3 = n4 ? c5 >= t4 : c5 <= t4, d3 = n4 ? l4 >= t4 : l4 <= t4;
        if (h3 && o5.push(s4), h3 === d3)
          continue;
        const u3 = (t4 - c5) / (l4 - c5);
        o5.push({ x: s4.x + (a5.x - s4.x) * u3, y: s4.y + (a5.y - s4.y) * u3 });
      }
      return o5;
    }, f2 = [];
    for (let e5 = 0;e5 < p3; e5++) {
      const t4 = d2 + e5 * m2, n4 = e5 === p3 - 1 ? u2 : t4 + m2, o5 = g2(g2(r4, t4, true), n4, false);
      if (o5.length === 0)
        continue;
      const i5 = Math.min(...o5.map((e6) => e6.x)), s4 = Math.max(...o5.map((e6) => e6.x)), a5 = Math.min(...o5.map((e6) => e6.y)), c5 = Math.max(...o5.map((e6) => e6.y));
      f2.push({ center: { x: (i5 + s4) / 2, y: (a5 + c5) / 2 }, width: s4 - i5, height: c5 - a5 });
    }
    return f2;
  })(i3) : r3 === null ? ((e4, t3) => {
    const { center: n3, width: o4, height: i4, rotation: r4 } = e4, s3 = Math.max(1, Math.ceil(o4 / t3)), a4 = Math.max(1, Math.ceil(i4 / t3)), c4 = o4 / s3, l3 = i4 / a4, h2 = r4 * Math.PI / 180, d2 = Math.cos(h2), u2 = Math.sin(h2), p3 = [];
    for (let e5 = 0;e5 < s3; e5++) {
      const t4 = (e5 - s3 / 2 + 0.5) * c4;
      for (let e6 = 0;e6 < a4; e6++) {
        const o5 = (e6 - a4 / 2 + 0.5) * l3;
        p3.push({ center: { x: n3.x + t4 * d2 - o5 * u2, y: n3.y + t4 * u2 + o5 * d2 }, width: Math.abs(c4 * d2) + Math.abs(l3 * u2), height: Math.abs(c4 * u2) + Math.abs(l3 * d2) });
      }
    }
    return p3;
  })(i3, ((e4) => e4.obstacleId?.startsWith("trace_obstacle_") ? 0.75 : 0.4)(e3)) : Gr(i3, r3), c3 = e3.connectedTo.length > 0 ? a3.reduce((t3, n3, o4) => {
    const i4 = a3[t3], r4 = (i4.center.x - e3.center.x) ** 2 + (i4.center.y - e3.center.y) ** 2;
    return (n3.center.x - e3.center.x) ** 2 + (n3.center.y - e3.center.y) ** 2 < r4 ? o4 : t3;
  }, 0) : -1;
  return a3.map((e4, t3) => ({ ...o3, obstacleId: t3 === c3 ? o3.obstacleId : o3.obstacleId ? `${o3.obstacleId}_approx_${t3}` : undefined, connectedTo: o3.connectedTo, center: e4.center, width: e4.width, height: e4.height }));
};
var Zr = (e3) => {
  const t2 = new Map, n2 = new Map, o3 = new Map;
  for (const [i4, r3] of e3.obstacles.entries()) {
    const e4 = Ur(r3), s2 = Wr(r3, i4);
    n2.set(s2, e4), o3.set(s2, r3);
    for (const n3 of e4) {
      const e5 = [n3.center.x.toFixed(6), n3.center.y.toFixed(6), n3.width.toFixed(6), n3.height.toFixed(6), n3.layers.join(","), n3.isNonPlatedHole ? "hole" : ""].join(":"), o4 = t2.get(e5);
      o4 ? o4.connectedTo = [...new Set([...o4.connectedTo, ...n3.connectedTo])] : t2.set(e5, n3);
    }
  }
  const i3 = e3.connections.map((e4) => ({ ...e4, pointsToConnect: e4.pointsToConnect.map((e5) => {
    const t3 = ((e6) => [e6.pointId, e6.pcb_port_id].filter((e7) => Boolean(e7)))(e5);
    if (t3.length === 0)
      return e5;
    for (const [i4, r3] of o3) {
      if (!t3.some((e6) => r3.connectedTo.includes(e6)))
        continue;
      if (!Hr(e5, r3))
        continue;
      const o4 = n2.get(i4) ?? [];
      if (o4.length === 0)
        continue;
      if (o4.some((t4) => Hr(e5, t4)))
        return e5;
      let s2 = o4[0], a3 = Number.POSITIVE_INFINITY;
      for (const t4 of o4) {
        const n3 = me(Vr(e5, t4), e5);
        n3 < a3 && (a3 = n3, s2 = t4);
      }
      return { ...e5, ...Vr(e5, s2) };
    }
    return e5;
  }) }));
  return { ...e3, connections: i3, obstacles: [...t2.values()] };
};
function qr(e3, t2, n2, o3) {
  if (he(e3, t2, n2, o3))
    return 0;
  const i3 = Jr(e3, n2, o3), r3 = Jr(t2, n2, o3), s2 = Jr(n2, e3, t2), a3 = Jr(o3, e3, t2);
  return Math.min(i3, r3, s2, a3);
}
function Jr(e3, t2, n2) {
  const o3 = { x: n2.x - t2.x, y: n2.y - t2.y }, i3 = Qr({ x: e3.x - t2.x, y: e3.y - t2.y }, o3);
  if (i3 <= 0)
    return Kr(e3, t2);
  const r3 = Qr(o3, o3);
  if (r3 <= i3)
    return Kr(e3, n2);
  const s2 = i3 / r3;
  return Kr(e3, { x: t2.x + s2 * o3.x, y: t2.y + s2 * o3.y });
}
function Qr(e3, t2) {
  return e3.x * t2.x + e3.y * t2.y;
}
function Kr(e3, t2) {
  const n2 = t2.x - e3.x, o3 = t2.y - e3.y;
  return Math.sqrt(n2 * n2 + o3 * o3);
}
var es = 0.000001;
var ts = ({ hdRoute: e3, start: t2, end: n2 }) => {
  if (Math.abs(t2.x - n2.x) <= es && Math.abs(t2.y - n2.y) <= es)
    return "colocated";
  const o3 = e3.vias.some((e4) => Math.abs(e4.x - t2.x) <= es && Math.abs(e4.y - t2.y) <= es), i3 = e3.vias.some((e4) => Math.abs(e4.x - n2.x) <= es && Math.abs(e4.y - n2.y) <= es);
  if (!o3 && !i3)
    throw new Error(`Pipeline9 route "${e3.connectionName}" changes layers from z=${t2.z} to z=${n2.z} without an explicit via`);
  if (o3 === i3)
    throw new Error(`Pipeline9 route "${e3.connectionName}" has an ambiguous layer transition between (${t2.x}, ${t2.y}) and (${n2.x}, ${n2.y})`);
  return o3 ? "start" : "end";
};
var ns = new WeakMap;
var os = (e3, { layerCount: t2, allowBlindAndBuriedVias: n2 }) => {
  const o3 = `${t2}:${n2 === true}`, i3 = ns.get(e3)?.get(o3);
  if (i3)
    return i3;
  const r3 = [], s2 = [];
  for (let o4 = 1;o4 < e3.route.length; o4++) {
    const i4 = e3.route[o4 - 1], a4 = e3.route[o4], c4 = Math.hypot(a4.x - i4.x, a4.y - i4.y), l3 = Math.max(i4.traceThickness ?? e3.traceThickness, a4.traceThickness ?? e3.traceThickness);
    if (i4.z !== a4.z && i4.toNextSegmentType === "through_obstacle") {
      const t3 = Math.min(i4.z, a4.z), n3 = Math.max(i4.z, a4.z);
      if (c4 <= 0.000000001) {
        const o5 = e3.vias.some((e4) => Math.hypot(e4.x - a4.x, e4.y - a4.y) <= 0.000000001);
        s2.push({ center: { x: a4.x, y: a4.y }, minZ: t3, maxZ: n3, diameter: o5 ? e3.viaDiameter : l3 });
        continue;
      }
      for (let e4 = t3;e4 <= n3; e4++)
        r3.push({ start: { ...i4, z: e4 }, end: { ...a4, z: e4 }, z: e4, width: l3 });
      continue;
    }
    const h2 = i4.z === a4.z ? undefined : ts({ hdRoute: e3, start: i4, end: a4 }), d2 = h2 === "start" ? a4.z : i4.z;
    if (c4 > 0.000000001 && r3.push({ start: i4.z === d2 ? i4 : { ...i4, z: d2 }, end: a4.z === d2 ? a4 : { ...a4, z: d2 }, z: d2, width: l3 }), i4.z === a4.z)
      continue;
    const u2 = h2 === "start" ? i4 : a4;
    Co(i4.z, t2), Co(a4.z, t2), s2.push({ center: { x: u2.x, y: u2.y }, minZ: n2 ? Math.min(i4.z, a4.z) : 0, maxZ: n2 ? Math.max(i4.z, a4.z) : t2 - 1, diameter: e3.viaDiameter });
  }
  const a3 = { wireSegments: r3, viaSpans: s2 }, c3 = ns.get(e3) ?? new Map;
  return c3.set(o3, a3), ns.set(e3, c3), a3;
};
var is = (e3, t2, n2) => {
  const o3 = e3.end.x - e3.start.x, i3 = e3.end.y - e3.start.y, r3 = Math.hypot(o3, i3), s2 = { x: (e3.start.x + e3.end.x) / 2, y: (e3.start.y + e3.end.y) / 2 };
  return Math.abs(o3) <= 0.000000001 || Math.abs(i3) <= 0.000000001 ? [{ center: s2, width: Math.abs(o3) > Math.abs(i3) ? r3 : e3.width, height: Math.abs(o3) > Math.abs(i3) ? e3.width : r3 }] : Gr({ center: s2, width: r3, height: e3.width, rotation: 180 * Math.atan2(i3, o3) / Math.PI }, Math.max(n2, Math.ceil(r3 / t2)));
};
var rs = ({ fixedObstacleRoutes: e3, layerCount: t2, allowBlindAndBuriedVias: n2 }) => e3.flatMap((e4, o3) => {
  const i3 = [e4.connectionName, e4.rootConnectionName].filter((e5) => typeof e5 == "string"), r3 = os(e4, { layerCount: t2, allowBlindAndBuriedVias: n2 });
  return [...r3.wireSegments.flatMap((e5, n3) => is(e5, 0.75, 2).map((r4, s2) => ({ obstacleId: `pipeline9_fixed_obstacle_${o3}_wire_${n3}_${s2}`, type: "rect", layers: [Co(e5.z, t2)], center: r4.center, width: r4.width, height: r4.height, connectedTo: i3 }))), ...r3.viaSpans.map((e5, n3) => ({ obstacleId: `pipeline9_fixed_obstacle_${o3}_via_${n3}`, type: "rect", layers: Array.from({ length: e5.maxZ - e5.minZ + 1 }, (n4, o4) => Co(e5.minZ + o4, t2)), center: e5.center, width: e5.diameter, height: e5.diameter, connectedTo: i3 }))];
});
var ss = (e3, t2, n2) => {
  const o3 = [e3.connectionName, e3.rootConnectionName].filter((e4) => typeof e4 == "string"), i3 = [t2.connectionName, t2.rootConnectionName].filter((e4) => typeof e4 == "string");
  return o3.some((e4) => i3.some((t3) => e4 === t3 || n2.areIdsConnected(e4, t3)));
};
var as = (e3, t2) => e3.minX <= t2.maxX && e3.maxX >= t2.minX && e3.minY <= t2.maxY && e3.maxY >= t2.minY;
var cs = ({ left: e3, right: t2, clearance: n2, leftBounds: o3, layerCount: i3, allowBlindAndBuriedVias: r3 }) => {
  const s2 = { layerCount: i3, allowBlindAndBuriedVias: r3 }, a3 = os(e3, s2), c3 = os(t2, s2), l3 = o3 ? a3.wireSegments.filter((e4) => ((e5, t3) => {
    const n3 = { minX: Math.min(e5.start.x, e5.end.x) - e5.width / 2, maxX: Math.max(e5.start.x, e5.end.x) + e5.width / 2, minY: Math.min(e5.start.y, e5.end.y) - e5.width / 2, maxY: Math.max(e5.start.y, e5.end.y) + e5.width / 2 };
    return as(n3, t3);
  })(e4, o3)) : a3.wireSegments, h2 = o3 ? a3.viaSpans.filter((e4) => ((e5, t3) => {
    const n3 = { minX: e5.center.x - e5.diameter / 2, maxX: e5.center.x + e5.diameter / 2, minY: e5.center.y - e5.diameter / 2, maxY: e5.center.y + e5.diameter / 2 };
    return as(n3, t3);
  })(e4, o3)) : a3.viaSpans;
  for (const e4 of l3) {
    for (const t3 of c3.wireSegments) {
      if (e4.z !== t3.z)
        continue;
      const o4 = e4.width / 2 + t3.width / 2 + n2;
      if (qr(e4.start, e4.end, t3.start, t3.end) < o4)
        return true;
    }
    for (const t3 of c3.viaSpans) {
      if (e4.z < t3.minZ || e4.z > t3.maxZ)
        continue;
      const o4 = e4.width / 2 + t3.diameter / 2 + n2;
      if (qr(e4.start, e4.end, t3.center, t3.center) < o4)
        return true;
    }
  }
  for (const e4 of h2) {
    for (const t3 of c3.wireSegments) {
      if (t3.z < e4.minZ || t3.z > e4.maxZ)
        continue;
      const o4 = e4.diameter / 2 + t3.width / 2 + n2;
      if (qr(e4.center, e4.center, t3.start, t3.end) < o4)
        return true;
    }
    for (const t3 of c3.viaSpans) {
      if (e4.minZ > t3.maxZ || t3.minZ > e4.maxZ)
        continue;
      const o4 = e4.diameter / 2 + t3.diameter / 2 + n2;
      if (Math.hypot(e4.center.x - t3.center.x, e4.center.y - t3.center.y) < o4)
        return true;
    }
  }
  return false;
};
function ls(e3, t2, n2, o3) {
  if (o3("priorityBranchProposals"), t2 === n2 || e3.ancestors[t2].has(n2) || e3.ancestors[n2].has(t2))
    return null;
  const i3 = e3.ancestors.map((e4) => (o3("priorityClosureCopies", e4.size + 1), new Set(e4))), r3 = e3.witnesses.slice();
  o3("priorityWitnessSlotsCopied", r3.length);
  const s2 = [...i3[t2], t2];
  for (let e4 = 0;e4 < i3.length; e4++)
    if (o3("priorityDescendantTests"), e4 === n2 || i3[e4].has(n2)) {
      for (const t3 of s2)
        o3("priorityClosureInsertions"), i3[e4].add(t3);
      r3[e4] && o3("priorityWitnessesInvalidated"), r3[e4] = undefined;
    }
  return { ancestors: i3, witnesses: r3 };
}
var hs = class extends Error {
};
var ds = class e3 extends Lr {
  static detailedWorkDiagnostics = false;
  detailedWorkDiagnosticsEnabled = e3.detailedWorkDiagnostics;
  priorityDiagnostics = {};
  familySize;
  coordinateScale;
  terminalRecorded = false;
  aggregate;
  tasks = [];
  owner = [];
  board = { layerCount: 2 };
  stack = [];
  visited = new Set;
  current;
  currentTask = -1;
  nativeTaskOptions;
  todo = [];
  pairLeft = 0;
  pairRight = 1;
  finalTask = 0;
  readyToValidate = false;
  expectedNativeCandidateAllowance;
  nativeCandidateIterationLimit;
  viaHoleDiameter;
  minimumHoleGap;
  nativeBounds = { minX: 0, maxX: 0, minY: 0, maxY: 0 };
  allowedLayers = [];
  regionId = "";
  constructor(e4) {
    if (super(e4), this.aggregate = e4.priorityDiagnostics, this.coordinateScale = e4.priorityCoordinateScale ?? 1, !Number.isFinite(this.coordinateScale) || this.coordinateScale <= 0)
      throw new Error("Invalid priority coordinate scale");
    if (this.familySize = e4.priorityFamilySize, !Number.isSafeInteger(this.familySize) || this.familySize < 1)
      throw new Error("Invalid priority family allocation");
    this.nativeCandidateIterationLimit = this.MAX_ITERATIONS, this.expectedNativeCandidateAllowance = Math.floor(this.MAX_ITERATIONS) + 1;
    const t2 = this.familySize * this.expectedNativeCandidateAllowance;
    if (!Number.isSafeInteger(t2))
      throw new Error("Unsafe priority family work allocation");
    if (this.MAX_ITERATIONS = t2 - 1, this.viaHoleDiameter = e4.viaHoleDiameter ?? this.viaDiameter, this.minimumHoleGap = e4.minViaHoleEdgeToViaHoleEdgeClearance ?? 0.1, !Number.isFinite(this.viaHoleDiameter) || this.viaHoleDiameter <= 0 || !Number.isFinite(this.minimumHoleGap) || this.minimumHoleGap < 0)
      throw new Error("Invalid priority drill geometry");
    for (const [e5, t3] of Object.entries({ priorityInstances: 1, priorityRemovedNativeCandidates: this.familySize, priorityAllocatedWorkUnits: this.MAX_ITERATIONS, priorityDetailedInstances: Number(this.detailedWorkDiagnosticsEnabled), priorityCoordinateScaleSum: this.coordinateScale, priorityScaledInstances: Number(this.coordinateScale !== 1) }))
      this.priorityDiagnostics[e5] = t3, this.aggregate && (this.aggregate[e5] = (this.aggregate[e5] ?? 0) + t3);
    try {
      if (this.charge("priorityOwnedContextSnapshots", 3 + Object.keys(this.hyperParameters).length), this.nativeBounds = { ...ro(this.nodeWithPortPoints) }, this.regionId = this.nodeWithPortPoints.capacityMeshNodeId, this.hyperParameters = Object.freeze({ ...this.hyperParameters }), this.nodeWithPortPoints.availableZ?.length)
        this.charge("priorityAllowedLayerCopies", this.nodeWithPortPoints.availableZ.length), this.allowedLayers = [...this.nodeWithPortPoints.availableZ];
      else {
        const e5 = new Set;
        for (const t4 of this.nodeWithPortPoints.portPoints)
          this.charge("priorityAllowedLayerVisits"), e5.add(t4.z ?? 0);
        this.allowedLayers = [...e5].sort((e6, t4) => (this.charge("priorityAllowedLayerComparisons"), e6 - t4));
      }
      this.charge("priorityEligibilityUpperBound", this.unsolvedConnections.reduce((e5, t4) => e5 + 2 + 3 * t4.points.length, 0));
      const t3 = $r(this.unsolvedConnections, this.charge);
      if (!t3)
        throw new Error("Priority DAG requires nondegenerate native star tasks");
      this.tasks = t3, this.charge("priorityLayerExtentUpperBound", 2 * this.tasks.length), this.board = { layerCount: e4.layerCount ?? Math.max(2, ...this.tasks.flatMap((e5) => e5.points.map((e6) => e6.z + 1))), allowBlindAndBuriedVias: e4.allowBlindAndBuriedVias }, this.owner = this.tasks.map((e5) => {
        this.charge("priorityOwnerLookups");
        const t4 = this.connMap?.getNetConnectedToId(e5.connectionName);
        if (t4 === undefined)
          return JSON.stringify(["literal", e5.connectionName]);
        const n2 = this.connMap.netMap[t4];
        if (!Array.isArray(n2))
          throw new Error("Missing indexed priority owner members");
        let o3 = false;
        for (const t5 of n2)
          if (this.charge("priorityOwnerMemberVisits"), t5 === e5.connectionName) {
            o3 = true;
            break;
          }
        if (!o3)
          throw new Error(`Stale indexed priority owner for ${e5.connectionName}`);
        return JSON.stringify(["registered", t4]);
      }), this.charge("priorityInitialStateSlots", 3 * this.tasks.length + 1), this.stack.push({ ancestors: this.tasks.map(() => new Set), witnesses: this.tasks.map(() => {}) });
    } catch (e5) {
      if (!(e5 instanceof hs))
        throw e5;
      this.unknown("owned setup exhausted aggregate family work allowance");
    }
  }
  record(e4, t2 = 1) {
    this.detailedWorkDiagnosticsEnabled && (this.priorityDiagnostics[e4] = (this.priorityDiagnostics[e4] ?? 0) + t2, this.aggregate && (this.aggregate[e4] = (this.aggregate[e4] ?? 0) + t2));
  }
  charge = (e4, t2 = 1) => {
    if (!Number.isSafeInteger(t2) || t2 < 0)
      throw new Error("Invalid priority work charge");
    if (this.iterations + t2 > this.MAX_ITERATIONS)
      throw new hs;
    this.iterations += t2, this.record(e4, t2), this.record("priorityWorkUnits", t2);
  };
  unknown(e4) {
    this.failed = true, this.error = `Priority DAG candidate UNKNOWN: ${e4}`, this.recordTerminal(false);
  }
  recordTerminal(e4) {
    if (this.terminalRecorded)
      throw new Error("Duplicate priority terminal accounting");
    this.terminalRecorded = true;
    for (const [t2, n2] of Object.entries({ priorityCompletedCandidates: 1, prioritySolvedCandidates: Number(e4), priorityUnknownCandidates: Number(!e4), priorityCompletedWorkUnits: this.iterations }))
      this.priorityDiagnostics[t2] = (this.priorityDiagnostics[t2] ?? 0) + n2, this.aggregate && (this.aggregate[t2] = (this.aggregate[t2] ?? 0) + n2);
  }
  acceptState(e4) {
    this.charge("priorityStateSelections");
    for (let t2 = 0;t2 < this.tasks.length; t2++) {
      const n2 = e4.witnesses[t2];
      if (n2) {
        if (this.charge("priorityRetainedContextChecks", this.tasks.length), n2.ancestors.length !== e4.ancestors[t2].size || n2.ancestors.some(([n3, o3]) => !e4.ancestors[t2].has(n3) || e4.witnesses[n3] !== o3))
          throw new Error("Stale retained priority witness");
        this.record("priorityWitnessesRetained");
      }
    }
    this.current = e4, this.todo = this.tasks.map((e5, t2) => t2).filter((t2) => !e4.witnesses[t2]).sort((t2, n2) => (this.charge("priorityTopologicalComparisons"), e4.ancestors[t2].size - e4.ancestors[n2].size || t2 - n2)), this.pairLeft = 0, this.pairRight = 1, this.finalTask = 0, this.readyToValidate = false;
  }
  getOptions(e4, t2) {
    const n2 = t2.ancestors[e4], o3 = [], i3 = [];
    for (let r3 = 0;r3 < this.tasks.length; r3++)
      if (this.charge("priorityContextEntries"), n2.has(r3)) {
        const n3 = t2.witnesses[r3];
        if (!n3)
          throw new Error("Missing higher-priority physical witness");
        this.owner[r3] !== this.owner[e4] && o3.push(n3.route);
      } else
        r3 !== e4 && i3.push(this.tasks[r3]);
    return { ...this.tasks[e4], A: this.tasks[e4].points[0], B: this.tasks[e4].points[1], regionId: this.regionId, obstacleRoutes: o3, futureConnections: i3, bounds: this.nativeBounds, minDistBetweenEnteringPoints: this.minDistBetweenEnteringPoints, layerCount: this.board.layerCount, availableZ: this.allowedLayers, hyperParameters: this.hyperParameters, connMap: this.connMap, viaDiameter: this.viaDiameter, traceThickness: this.traceWidth, obstacleMargin: this.obstacleMargin, captureSearchDebug: this.captureSearchDebug };
  }
  getSingleRouteSolverOpts(e4) {
    if (e4 !== this.tasks[this.currentTask] || !this.nativeTaskOptions)
      throw new Error("Unknown priority native helper context");
    return this.nativeTaskOptions;
  }
  startTask(e4, t2) {
    const n2 = this.getOptions(e4, t2), o3 = 1 + n2.obstacleRoutes.reduce((e5, t3) => e5 + t3.route.length + t3.vias.length, 0) + (n2.futureConnections ?? []).reduce((e5, t3) => e5 + t3.points.length, 0);
    if (this.currentTask = e4, n2.A.x === n2.B.x && n2.A.y === n2.B.y && n2.A.z !== n2.B.z) {
      let i3;
      this.charge("priorityEndpointViaSetupPrimitives", o3), this.charge("priorityEndpointViaGuardUpperBound", 2), this.record("priorityEndpointViaAttempts"), this.nativeTaskOptions = n2;
      try {
        i3 = super.trySolveSamePointLayerChange(this.tasks[e4]);
      } finally {
        this.nativeTaskOptions = undefined;
      }
      if (i3) {
        const n3 = this.solvedRoutes.pop();
        if (!n3 || this.solvedRoutes.length !== 0)
          throw new Error("Invalid native endpoint-via temporary witness");
        return this.storeRoute(n3, t2, e4), void this.record("priorityEndpointViaAccepted");
      }
    }
    this.charge("priorityNativeSetupPrimitives", o3), this.activeSubSolver = new Er(n2), this.record("priorityNativeSearches");
  }
  storeRoute(e4, t2, n2) {
    this.charge("priorityWitnessCopies", 1 + e4.route.length + e4.vias.length + t2.ancestors[n2].size);
    const o3 = this.tasks[n2], i3 = e4.route[0], r3 = e4.route.at(-1);
    if (e4.connectionName !== o3.connectionName || e4.rootConnectionName !== o3.rootConnectionName || e4.regionId !== this.regionId || e4.traceThickness !== this.traceWidth || e4.viaDiameter !== this.viaDiameter || !i3 || !r3 || i3.x !== o3.points[0].x || i3.y !== o3.points[0].y || i3.z !== o3.points[0].z || r3.x !== o3.points[1].x || r3.y !== o3.points[1].y || r3.z !== o3.points[1].z)
      throw new Error("Invalid priority native route identity");
    const s2 = { ...e4, route: e4.route.map((e5) => Object.freeze({ ...e5 })), vias: e4.vias.map((e5) => Object.freeze({ ...e5 })) };
    Object.freeze(s2.route), Object.freeze(s2.vias), Object.freeze(s2), t2.witnesses[n2] = { route: s2, ancestors: [...t2.ancestors[n2]].map((e5) => {
      const n3 = t2.witnesses[e5];
      if (!n3)
        throw new Error("Missing priority route context");
      return [e5, n3];
    }) };
  }
  pairConflict(e4, t2, n2) {
    this.charge("priorityPairChecks");
    const o3 = n2.witnesses[e4]?.route, i3 = n2.witnesses[t2]?.route;
    if (!o3 || !i3)
      throw new Error("Missing priority pair witness");
    for (const n3 of o3.vias)
      for (const o4 of i3.vias) {
        this.charge("priorityDrillPairChecks");
        const i4 = Math.hypot(n3.x - o4.x, n3.y - o4.y);
        if ((i4 !== 0 || this.owner[e4] !== this.owner[t2]) && i4 < this.viaHoleDiameter + this.minimumHoleGap)
          return true;
      }
    if (this.owner[e4] === this.owner[t2])
      return false;
    this.charge("priorityGeometrySetupUpperBound", o3.route.length + o3.vias.length + i3.route.length + i3.vias.length);
    const r3 = os(o3, this.board), s2 = os(i3, this.board);
    return this.charge("priorityPairPrimitiveUpperBound", (r3.wireSegments.length + r3.viaSpans.length) * (s2.wireSegments.length + s2.viaSpans.length)), cs({ left: o3, right: i3, clearance: this.obstacleMargin, ...this.board });
  }
  branch(e4, t2, n2) {
    this.record("priorityObservedConflicts");
    for (const [o3, i3] of [[t2, e4], [e4, t2]]) {
      const e5 = ls(n2, o3, i3, this.charge);
      if (!e5) {
        this.record("priorityCyclicOrExistingBranches");
        continue;
      }
      this.charge("priorityStateKeyEntries", this.tasks.length ** 2);
      const t3 = e5.ancestors.map((e6) => [...e6].sort((e7, t4) => e7 - t4).join(",")).join(";");
      this.visited.has(t3) ? this.record("priorityDuplicateStates") : (this.visited.add(t3), this.stack.push(e5), this.record("priorityStatesQueued"));
    }
    this.current = undefined;
  }
  validateRoute(e4, t2) {
    const n2 = t2.witnesses[e4];
    if (!n2)
      throw new Error("Missing final priority route");
    for (let e5 = 0;e5 < n2.route.vias.length; e5++)
      for (let t3 = e5 + 1;t3 < n2.route.vias.length; t3++) {
        this.charge("priorityFinalDrillPairs");
        const o4 = n2.route.vias[e5], i4 = n2.route.vias[t3], r4 = Math.hypot(o4.x - i4.x, o4.y - i4.y);
        if (r4 > 0 && r4 < this.viaHoleDiameter + this.minimumHoleGap)
          return false;
      }
    const o3 = this.getOptions(e4, t2);
    this.charge("priorityValidationSetupPrimitives", 1 + o3.obstacleRoutes.reduce((e5, t3) => e5 + t3.route.length + t3.vias.length, 0) + (o3.futureConnections ?? []).reduce((e5, t3) => e5 + t3.points.length, 0));
    const i3 = new Er(o3);
    let r3 = null;
    for (let e5 = 0;e5 < n2.route.route.length; e5++) {
      this.charge("priorityWitnessVertices");
      const t3 = n2.route.route[e5];
      if (!Number.isFinite(t3.x) || !Number.isFinite(t3.y) || !Number.isSafeInteger(t3.z))
        throw new Error("Nonfinite priority route");
      const s2 = { ...t3, g: 0, h: 0, f: 0, parent: r3 };
      if (r3)
        if (s2.z !== r3.z) {
          if (this.charge("priorityFinalViaChecks"), i3.isNodeTooCloseToObstacle(s2, this.viaDiameter / 2 + this.obstacleMargin / 2, true) || i3.isNodeTooCloseToEdge(s2, true))
            return false;
        } else {
          if (this.charge("priorityFinalSegmentChecks"), i3.doesPathToParentIntersectObstacle(s2))
            return false;
          const t4 = s2.x === o3.A.x && s2.y === o3.A.y && s2.z === o3.A.z;
          if (e5 < n2.route.route.length - 1 && !t4 && (this.charge("priorityFinalPointChecks"), i3.isNodeTooCloseToObstacle(s2) || i3.isNodeTooCloseToEdge(s2, false)))
            return false;
        }
      r3 = s2;
    }
    return true;
  }
  _step() {
    this.iterations--;
    try {
      if (this.charge("priorityDispatches"), this.activeSubSolver) {
        if (this.charge("priorityNativeSteps"), this.activeSubSolver.step(), this.activeSubSolver.failed)
          this.record("priorityUnknownLowLevelSearches"), this.record("priorityStatesAbandonedLowLevel"), this.activeSubSolver = null, this.current = undefined;
        else if (this.activeSubSolver.solved) {
          if (!this.current || !this.activeSubSolver.solvedPath)
            throw new Error("Missing completed priority plan");
          this.storeRoute(this.activeSubSolver.solvedPath, this.current, this.currentTask), this.activeSubSolver = null;
        }
        return;
      }
      if (!this.current) {
        const e5 = this.stack.pop();
        if (!e5)
          return void this.unknown("bounded priority policy exhausted; no physical impossibility proven");
        this.acceptState(e5);
      }
      const e4 = this.current, t2 = this.todo.shift();
      if (t2 !== undefined)
        return void this.startTask(t2, e4);
      if (!this.readyToValidate) {
        if (this.pairLeft < this.tasks.length - 1) {
          const t3 = this.pairLeft, n2 = this.pairRight;
          return this.pairConflict(t3, n2, e4) ? void this.branch(t3, n2, e4) : (this.pairRight++, void (this.pairRight === this.tasks.length && (this.pairLeft++, this.pairRight = this.pairLeft + 1)));
        }
        this.readyToValidate = true;
      }
      if (this.finalTask < this.tasks.length)
        return void (this.validateRoute(this.finalTask++, e4) || (this.record("priorityRejectedFinalWitnesses"), this.current = undefined));
      this.charge("priorityOutputCopies", e4.witnesses.reduce((e5, t3) => e5 + 1 + t3.route.route.length + t3.route.vias.length, 0)), this.solvedRoutes = e4.witnesses.map((e5) => ({ ...e5.route, route: e5.route.route.map((e6) => ({ ...e6 })), vias: e5.route.vias.map((e6) => ({ ...e6 })) })), this.solved = true, this.recordTerminal(true);
    } catch (e4) {
      if (!(e4 instanceof hs))
        throw e4;
      this.unknown("aggregate family work allowance exhausted");
    }
    this.progress = this.current ? this.current.witnesses.filter(Boolean).length / this.tasks.length : 0;
  }
  computeProgress() {
    if (this.solved)
      return 1;
    const e4 = this.current;
    return e4 ? Math.min(0.99, e4.witnesses.filter(Boolean).length / this.tasks.length) : 0;
  }
};
var us = (e4, t2) => {
  const n2 = {};
  return e4.portPoints.forEach((t3, o3) => {
    n2[t3.connectionName] = `hsl(${360 * o3 / e4.portPoints.length}, 100%, 50%)`;
  }), n2;
};
var ps = class extends ni {
  getSolverName() {
    return "ViaPossibilitiesSolver2";
  }
  bounds;
  maxViaCount;
  portPairMap;
  colorMap;
  nodeWidth;
  availableZ;
  hyperParameters;
  VIA_INTERSECTION_BUFFER_DISTANCE = 0.05;
  PLACEHOLDER_WALL_BUFFER_DISTANCE = 0.1;
  NEW_HEAD_WALL_BUFFER_DISTANCE = 0.05;
  viaDiameter;
  unprocessedConnections;
  completedPaths = new Map;
  placeholderPaths = new Map;
  currentHead;
  currentConnectionName;
  currentPath;
  currentViaCount;
  constructor({ nodeWithPortPoints: e4, colorMap: t2, hyperParameters: n2, viaDiameter: o3 }) {
    super(), this.MAX_ITERATIONS = 1e5, this.colorMap = t2 ?? us(e4), this.maxViaCount = 5, this.bounds = ro(e4), this.nodeWidth = this.bounds.maxX - this.bounds.minX, this.portPairMap = ((e5) => {
      const t3 = new Map;
      return e5.portPoints.forEach((e6) => {
        t3.has(e6.connectionName) ? t3.get(e6.connectionName).end = e6 : t3.set(e6.connectionName, { start: e6, end: null, connectionName: e6.connectionName });
      }), t3;
    })(e4), this.stats.solutionsFound = 0, this.availableZ = e4.availableZ ?? [0, 1], this.hyperParameters = n2 ?? { SHUFFLE_SEED: 0 }, this.viaDiameter = o3 ?? 0.3, this.unprocessedConnections = Array.from(this.portPairMap.keys()).sort(), n2?.SHUFFLE_SEED && (this.unprocessedConnections = Sr(this.unprocessedConnections, n2.SHUFFLE_SEED));
    for (const [e5, { start: t3, end: n3 }] of this.portPairMap.entries())
      if (t3.z === n3.z) {
        const o4 = Math.abs(t3.x - n3.x) < 0.000000001, i4 = Math.abs(t3.y - n3.y) < 0.000000001;
        o4 || i4 ? this.placeholderPaths.set(e5, [t3, this._padByPlaceholderWallBuffer(t3), this._padByPlaceholderWallBuffer(n3), n3]) : this.placeholderPaths.set(e5, [t3, n3]);
      } else {
        const o4 = (t3.x + n3.x) / 2, i4 = (t3.y + n3.y) / 2, r3 = this._padByPlaceholderWallBuffer({ x: o4, y: i4, z: t3.z }), s2 = this._padByPlaceholderWallBuffer({ x: o4, y: i4, z: n3.z });
        this.placeholderPaths.set(e5, [t3, this._padByPlaceholderWallBuffer(t3), r3, s2, this._padByPlaceholderWallBuffer(n3), n3]);
      }
    this.currentConnectionName = this.unprocessedConnections.pop();
    const i3 = this.portPairMap.get(this.currentConnectionName).start;
    this.currentHead = this._padByNewHeadWallBuffer(i3), this.currentPath = [i3, this.currentHead], this.currentViaCount = 0, this.placeholderPaths.delete(this.currentConnectionName);
  }
  _padByNewHeadWallBuffer(e4) {
    return { x: Me(e4.x, this.bounds.minX + this.NEW_HEAD_WALL_BUFFER_DISTANCE, this.bounds.maxX - this.NEW_HEAD_WALL_BUFFER_DISTANCE), y: Me(e4.y, this.bounds.minY + this.NEW_HEAD_WALL_BUFFER_DISTANCE, this.bounds.maxY - this.NEW_HEAD_WALL_BUFFER_DISTANCE), z: e4.z };
  }
  _padByPlaceholderWallBuffer(e4) {
    return { x: Me(e4.x, this.bounds.minX + this.PLACEHOLDER_WALL_BUFFER_DISTANCE, this.bounds.maxX - this.PLACEHOLDER_WALL_BUFFER_DISTANCE), y: Me(e4.y, this.bounds.minY + this.PLACEHOLDER_WALL_BUFFER_DISTANCE, this.bounds.maxY - this.PLACEHOLDER_WALL_BUFFER_DISTANCE), z: e4.z };
  }
  _step() {
    if (this.solved)
      return;
    const e4 = this.portPairMap.get(this.currentConnectionName).end, t2 = [this.currentHead, e4];
    let n2 = null, o3 = null;
    const i3 = (e5) => {
      for (const i4 of e5.values())
        for (let e6 = 0;e6 < i4.length - 1; e6++) {
          const r4 = [i4[e6], i4[e6 + 1]];
          if (r4[0].x === r4[1].x && r4[0].y === r4[1].y)
            continue;
          if (r4[0].z !== this.currentHead.z)
            continue;
          const s2 = ge(t2[0], t2[1], r4[0], r4[1]);
          if (s2) {
            const e7 = me(this.currentHead, s2);
            if (e7 < 0.000001)
              continue;
            (!n2 || e7 < n2.dist) && (n2 = { point: s2, dist: e7 }, o3 = r4[0].z);
          }
        }
    };
    i3(this.completedPaths), i3(this.placeholderPaths);
    const r3 = this.currentHead.z !== e4.z;
    if ((n2 || r3) && (this.currentViaCount++, this.currentViaCount >= this.maxViaCount))
      return this.failed = true, void (this.error = `Exceeded max via count of ${this.maxViaCount}`);
    if (n2) {
      let e5;
      const t3 = n2.dist;
      if (t3 <= this.VIA_INTERSECTION_BUFFER_DISTANCE + 0.000001)
        e5 = ke(this.currentHead, n2.point);
      else {
        const o4 = n2.point, i5 = o4.x - this.currentHead.x, r5 = o4.y - this.currentHead.y, s3 = (t3 - this.VIA_INTERSECTION_BUFFER_DISTANCE) / t3;
        e5 = { x: this.currentHead.x + i5 * s3, y: this.currentHead.y + r5 * s3 };
      }
      const i4 = this.availableZ.find((e6) => e6 !== o3);
      if (i4 === undefined)
        return this.error = "Could not determine next Z level for via placement!", void (this.failed = true);
      const r4 = { ...e5, z: this.currentHead.z }, s2 = { ...e5, z: i4 };
      this.currentPath.push(r4, s2), this.currentHead = s2;
    } else if (r3) {
      let t3;
      const n3 = me(this.currentHead, e4);
      if (n3 < this.VIA_INTERSECTION_BUFFER_DISTANCE)
        t3 = ke(this.currentHead, e4);
      else {
        const o5 = e4.x - this.currentHead.x, i5 = e4.y - this.currentHead.y, r5 = (n3 - this.VIA_INTERSECTION_BUFFER_DISTANCE) / n3;
        t3 = { x: this.currentHead.x + o5 * r5, y: this.currentHead.y + i5 * r5 };
      }
      const o4 = e4.z, i4 = { ...t3, z: this.currentHead.z }, r4 = { ...t3, z: o4 };
      this.currentPath.push(i4, r4), this.currentHead = r4;
    } else if (this.currentPath.push(e4), this.completedPaths.set(this.currentConnectionName, this.currentPath), this.unprocessedConnections.length === 0)
      this.solved = true, this.stats.solutionsFound = 1;
    else {
      this.currentConnectionName = this.unprocessedConnections.pop();
      const { start: e5 } = this.portPairMap.get(this.currentConnectionName);
      this.currentHead = this._padByNewHeadWallBuffer(e5), this.currentPath = [e5, this.currentHead], this.currentViaCount = 0, this.placeholderPaths.delete(this.currentConnectionName);
    }
  }
  visualize() {
    const e4 = { points: [], lines: [], circles: [], rects: [], title: "Via Possibilities Solver State", coordinateSystem: "cartesian" }, t2 = this.colorMap;
    e4.lines.push({ points: [{ x: this.bounds.minX, y: this.bounds.minY }, { x: this.bounds.maxX, y: this.bounds.minY }, { x: this.bounds.maxX, y: this.bounds.maxY }, { x: this.bounds.minX, y: this.bounds.maxY }, { x: this.bounds.minX, y: this.bounds.minY }], strokeColor: "gray", strokeWidth: 0.01 });
    for (const [t3, { start: n3, end: o3 }] of this.portPairMap.entries()) {
      const i3 = this.colorMap[t3] ?? "black";
      e4.points.push({ x: n3.x, y: n3.y, color: i3, label: `Port: ${t3} Start (z${n3.z})` }), e4.points.push({ x: o3.x, y: o3.y, color: i3, label: `Port: ${t3} End (z${o3.z})` });
    }
    const n2 = (n3, o3) => {
      for (const [i3, r3] of n3.entries()) {
        const n4 = t2[i3] ?? "black";
        for (let t3 = 0;t3 < r3.length - 1; t3++) {
          const s2 = r3[t3], a3 = r3[t3 + 1];
          s2.x === a3.x && s2.y === a3.y && s2.z !== a3.z ? e4.circles.push({ center: { x: s2.x, y: s2.y }, radius: this.viaDiameter / 2, fill: Ao(n4, 0.5), label: `${o3}: ${i3} Via (z${s2.z}->z${a3.z})` }) : e4.lines.push({ points: [s2, a3], strokeColor: Ao(n4, 0.5), strokeDash: s2.z === 0 ? undefined : [0.1, 0.1], strokeWidth: 0.1, label: `${o3}: ${i3} (z${s2.z})` });
        }
      }
    };
    if (n2(this.placeholderPaths, "Placeholder"), n2(this.completedPaths, "Completed"), this.currentPath && this.currentPath.length > 0) {
      const n3 = t2[this.currentConnectionName] ?? "orange";
      for (let t3 = 0;t3 < this.currentPath.length - 1; t3++) {
        const o3 = this.currentPath[t3], i3 = this.currentPath[t3 + 1];
        o3.x === i3.x && o3.y === i3.y && o3.z !== i3.z ? e4.circles.push({ center: { x: o3.x, y: o3.y }, radius: this.viaDiameter / 2, fill: Ao(n3, 0.5), label: `Current: ${this.currentConnectionName} Via (z${o3.z}->z${i3.z})` }) : e4.lines.push({ points: [o3, i3], strokeColor: Ao(n3, 0.5), strokeWidth: 0.15, strokeDash: "2,2", label: `Current: ${this.currentConnectionName} (z${o3.z})` });
      }
      e4.points.push({ x: this.currentHead.x, y: this.currentHead.y, color: "green", label: `Current Head: ${this.currentConnectionName} (z${this.currentHead.z})` });
    }
    return e4;
  }
};
var ms = (e4) => Math.round(1e4 * e4);
var gs = (e4) => {
  let t2 = 0, n2 = [];
  const o3 = [];
  for (const t3 of e4.portPoints) {
    if (n2.some((e5) => e5.connectionName === t3.connectionName))
      continue;
    if (o3.some((e5) => e5.connectionName === t3.connectionName))
      continue;
    const i4 = { connectionName: t3.connectionName, z: t3.z, points: [{ x: ms(t3.x), y: ms(t3.y), z: t3.z }] };
    for (const n3 of e4.portPoints)
      t3.connectionName === n3.connectionName && (t3.x === n3.x && t3.y === n3.y || i4.points.push({ x: ms(n3.x), y: ms(n3.y), z: n3.z }));
    i4.points.some((e5) => e5.z !== i4.z) ? o3.push(i4) : n2.push(i4);
  }
  n2 = n2.filter((e5) => e5.points.length > 1);
  for (let e5 = 0;e5 < n2.length; e5++)
    for (let o4 = e5 + 1;o4 < n2.length; o4++) {
      const i4 = n2[e5], r3 = n2[o4];
      i4.z === r3.z && he(i4.points[0], i4.points[1], r3.points[0], r3.points[1]) && t2++;
    }
  let i3 = 0;
  for (let e5 = 0;e5 < o3.length; e5++)
    for (let t3 = e5 + 1;t3 < o3.length; t3++) {
      const n3 = o3[e5], r3 = o3[t3];
      he(n3.points[0], n3.points[1], r3.points[0], r3.points[1]) && i3++;
    }
  return { numSameLayerCrossings: t2, numEntryExitLayerChanges: o3.length, numTransitionPairCrossings: i3 };
};
var fs = (e4) => {
  const { start: t2, end: n2, segmentsPerPolyline: o3, viaPositions: i3, viaCount: r3, availableZ: s2 } = e4, a3 = function(e5, t3) {
    const n3 = new Array(e5).fill(0);
    if (t3 === 0)
      return n3;
    if (t3 === e5)
      return n3.fill(1);
    if (t3 <= e5 / 2) {
      const o4 = Math.floor(e5 / t3), i4 = Math.floor((e5 - (o4 * (t3 - 1) + 1)) / 2);
      for (let e6 = 0;e6 < t3; e6++)
        n3[i4 + e6 * o4] = 1;
    } else {
      const o4 = e5 - t3, i4 = Math.floor(e5 / o4), r4 = Math.floor((e5 - (i4 * (o4 - 1) + 1)) / 2);
      n3.fill(1);
      for (let e6 = 0;e6 < o4; e6++)
        n3[r4 + e6 * i4] = 0;
    }
    return n3;
  }(o3, r3), c3 = a3.map(() => null);
  let l3 = 0, h2 = t2.z1;
  const d2 = s2.indexOf(t2.z1);
  for (let e5 = 0;e5 < a3.length; e5++)
    if (a3[e5] === 1) {
      const t3 = s2[(d2 + l3 + 1) % s2.length];
      c3[e5] = { ...i3[l3], z1: h2, z2: t3 }, h2 = t3, l3++;
    }
  let u2 = t2;
  for (let e5 = 0;e5 < c3.length; e5++) {
    if (c3[e5]) {
      u2 = c3[e5];
      continue;
    }
    let t3 = n2, o4 = c3.length;
    for (let n3 = e5 + 1;n3 < c3.length; n3++)
      if (c3[n3]) {
        t3 = c3[n3], o4 = n3;
        break;
      }
    const i4 = o4 - e5, r4 = t3.x - u2.x, s3 = t3.y - u2.y;
    for (let t4 = 1 / (i4 + 1), n3 = 0;e5 + n3 !== o4; t4 += 1 / (i4 + 1), n3++)
      c3[e5 + n3] = { x: u2.x + r4 * t4, y: u2.y + s3 * t4, z1: u2.z2, z2: u2.z2 };
  }
  return c3;
};
var _s = 0.000000001;
function ys(e4, t2) {
  return Math.abs(e4 - t2) < _s;
}
function bs(e4) {
  return `${Math.round(e4.x / _s)}:${Math.round(e4.y / _s)}`;
}
function xs(e4, t2, n2, o3) {
  return e4 * o3 - t2 * n2;
}
function vs(e4, t2, n2, o3) {
  const i3 = { x: t2.x - e4.x, y: t2.y - e4.y }, r3 = { x: o3.x - n2.x, y: o3.y - n2.y }, s2 = xs(i3.x, i3.y, r3.x, r3.y), a3 = { x: n2.x - e4.x, y: n2.y - e4.y };
  if (ys(s2, 0))
    return null;
  const c3 = xs(a3.x, a3.y, r3.x, r3.y) / s2, l3 = xs(a3.x, a3.y, i3.x, i3.y) / s2;
  return c3 >= -0.000000001 && c3 <= 1 + _s && l3 >= -0.000000001 && l3 <= 1 + _s ? { x: e4.x + c3 * i3.x, y: e4.y + c3 * i3.y } : null;
}
function Is(e4, t2, n2) {
  return ys(Math.hypot(e4.x - t2.x, e4.y - t2.y) + Math.hypot(e4.x - n2.x, e4.y - n2.y), Math.hypot(t2.x - n2.x, t2.y - n2.y));
}
function Ss(e4, t2) {
  const n2 = [], o3 = new Map;
  for (const t3 of e4) {
    const e5 = [t3.start, ...t3.mPoints, t3.end];
    for (let i5 = 0;i5 < e5.length - 1; i5++) {
      const r4 = e5[i5], s3 = e5[i5 + 1], a4 = r4.z2;
      if (n2.push({ start: { x: r4.x, y: r4.y }, end: { x: s3.x, y: s3.y }, connectionName: t3.connectionName, layer: a4 }), r4.z1 !== r4.z2) {
        const e6 = bs(r4);
        o3.has(e6) || o3.set(e6, { point: r4, connectionName: t3.connectionName });
      }
    }
    const i4 = e5[e5.length - 1];
    if (i4.z1 !== i4.z2) {
      const e6 = bs(i4);
      o3.has(e6) || o3.set(e6, { point: i4, connectionName: t3.connectionName });
    }
  }
  const i3 = [{ start: { x: t2.minX, y: t2.minY }, end: { x: t2.maxX, y: t2.minY }, connectionName: null, layer: 0 }, { start: { x: t2.maxX, y: t2.minY }, end: { x: t2.maxX, y: t2.maxY }, connectionName: null, layer: 0 }, { start: { x: t2.maxX, y: t2.maxY }, end: { x: t2.minX, y: t2.maxY }, connectionName: null, layer: 0 }, { start: { x: t2.minX, y: t2.maxY }, end: { x: t2.minX, y: t2.minY }, connectionName: null, layer: 0 }];
  n2.push(...i3);
  const r3 = new Map;
  let s2 = 0;
  function a3(e5, t3) {
    const n3 = bs(e5);
    let i4 = r3.get(n3);
    if (!i4) {
      const t4 = o3.has(n3);
      i4 = { id: s2++, x: e5.x, y: e5.y, isVia: t4, connectionNames: new Set, outgoingEdges: [] }, r3.set(n3, i4), t4 && o3.get(n3) && i4.connectionNames.add(o3.get(n3).connectionName);
    }
    return t3 && i4.connectionNames.add(t3), i4;
  }
  for (const e5 of n2)
    a3(e5.start, e5.connectionName), a3(e5.end, e5.connectionName);
  const c3 = new Map;
  for (const e5 of n2)
    c3.set(e5, []);
  for (let e5 = 0;e5 < n2.length; e5++)
    for (let t3 = e5 + 1;t3 < n2.length; t3++) {
      if (n2[e5].layer !== n2[t3].layer)
        continue;
      const o4 = vs(n2[e5].start, n2[e5].end, n2[t3].start, n2[t3].end);
      o4 && (a3(o4), Is(o4, n2[e5].start, n2[e5].end) && c3.get(n2[e5]).push(o4), Is(o4, n2[t3].start, n2[t3].end) && c3.get(n2[t3]).push(o4));
    }
  const l3 = [];
  let h2 = 0;
  for (const e5 of n2) {
    const t3 = [e5.start, ...c3.get(e5), e5.end];
    t3.sort((t4, n4) => {
      const o4 = e5.end.x - e5.start.x, i4 = e5.end.y - e5.start.y;
      return Math.abs(o4) > Math.abs(i4) ? (t4.x - e5.start.x) / o4 - (n4.x - e5.start.x) / o4 : Math.abs(i4) < _s ? 0 : (t4.y - e5.start.y) / i4 - (n4.y - e5.start.y) / i4;
    });
    const n3 = [];
    if (t3.length > 0) {
      n3.push(t3[0]);
      for (let e6 = 1;e6 < t3.length; e6++)
        ys(t3[e6].x, t3[e6 - 1].x) && ys(t3[e6].y, t3[e6 - 1].y) || n3.push(t3[e6]);
    }
    for (let t4 = 0;t4 < n3.length - 1; t4++) {
      const o4 = n3[t4], i4 = n3[t4 + 1], r4 = a3(o4, e5.connectionName), s3 = a3(i4, e5.connectionName);
      if (r4 === s3)
        continue;
      const c4 = { id: h2++, origin: r4, twin: null, next: null, face: null, connectionName: e5.connectionName, layer: e5.layer, visited: false }, d3 = { id: h2++, origin: s3, twin: c4, next: null, face: null, connectionName: e5.connectionName, layer: e5.layer, visited: false };
      c4.twin = d3, l3.push(c4, d3), r4.outgoingEdges.push(c4), s3.outgoingEdges.push(d3);
    }
  }
  for (const e5 of r3.values()) {
    e5.outgoingEdges.sort((t4, n3) => {
      const o4 = t4.twin.origin, i4 = n3.twin.origin;
      return Math.atan2(o4.y - e5.y, o4.x - e5.x) - Math.atan2(i4.y - e5.y, i4.x - e5.x);
    });
    const t3 = e5.outgoingEdges.length;
    for (let n3 = 0;n3 < t3; n3++) {
      const o4 = e5.outgoingEdges[n3], i4 = e5.outgoingEdges[(n3 - 1 + t3) % t3];
      o4.twin && (o4.twin.next = i4);
    }
  }
  const d2 = [];
  let u2 = 0, p3 = null, m2 = -1 / 0;
  for (const e5 of l3) {
    if (e5.visited)
      continue;
    const t3 = { id: u2++, outerComponent: e5, innerComponents: [], isOuterFace: false };
    d2.push(t3);
    let n3 = e5;
    const o4 = [], i4 = [], r4 = new Set;
    let s3 = 0;
    do {
      if (!n3 || n3.visited) {
        console.warn("Face traversal encountered visited edge or null, breaking loop.", t3.id), o4.length = 0;
        break;
      }
      n3.visited = true, n3.face = t3, o4.push(n3), i4.push(n3.origin), n3.connectionName !== null && r4.add(n3.connectionName);
      const e6 = n3.origin, a4 = n3.twin.origin;
      s3 += e6.x * a4.y - a4.x * e6.y, n3 = n3.next;
    } while (n3 !== e5 && n3 !== null);
    if (n3 === e5) {
      if (s3 = 0.5 * Math.abs(s3), s3 > m2 && (m2 = s3, p3 && (p3.isOuterFace = false), p3 = t3, t3.isOuterFace = true), !t3.isOuterFace && o4.length > 0) {
        if ([...r4].filter((e6) => e6 !== null).length > 1) {
          let e6 = false;
          for (const t4 of i4)
            if (t4.isVia) {
              e6 = true;
              break;
            }
          if (!e6)
            return true;
        }
      }
    } else
      console.warn(`Face ${t3.id} did not close properly.`), d2.pop(), u2--;
  }
  return false;
}
var Cs = (e4) => {
  if (e4.length === 0)
    return [[]];
  const t2 = [];
  for (let n2 = 0;n2 < e4.length; n2++) {
    const o3 = e4[n2], i3 = [...e4.slice(0, n2), ...e4.slice(n2 + 1)], r3 = Cs(i3);
    for (const e5 of r3)
      t2.push([o3, ...e5]);
  }
  return t2;
};
var Ps = 0.000000001;
function Ms(e4, t2, n2 = 0.000000001) {
  return Math.abs(e4 - t2) < n2;
}
function ws(e4, t2, n2, o3) {
  return e4 * o3 - t2 * n2;
}
function Ns(e4, t2, n2, o3) {
  const i3 = { x: t2.x - e4.x, y: t2.y - e4.y }, r3 = { x: o3.x - n2.x, y: o3.y - n2.y }, s2 = ws(i3.x, i3.y, r3.x, r3.y);
  if (Ms(s2, 0))
    return null;
  const a3 = { x: n2.x - e4.x, y: n2.y - e4.y }, c3 = ws(a3.x, a3.y, r3.x, r3.y) / s2, l3 = ws(a3.x, a3.y, i3.x, i3.y) / s2;
  return c3 < -0.000000001 || c3 > 1 + Ps || l3 < -0.000000001 || l3 > 1 + Ps ? null : { x: e4.x + c3 * i3.x, y: e4.y + c3 * i3.y };
}
function Rs(e4) {
  let t2 = 0;
  for (let n2 = 0, o3 = e4.length;n2 < o3; ++n2) {
    const i3 = (n2 + 1) % o3;
    t2 += e4[n2].x * e4[i3].y - e4[i3].x * e4[n2].y;
  }
  return 0.5 * t2;
}
function Ts(e4) {
  let t2 = 0, n2 = 0, o3 = 0;
  for (let i3 = 0, r3 = e4.length;i3 < r3; ++i3) {
    const s2 = (i3 + 1) % r3, a3 = e4[i3].x * e4[s2].y - e4[s2].x * e4[i3].y;
    t2 += a3, n2 += (e4[i3].x + e4[s2].x) * a3, o3 += (e4[i3].y + e4[s2].y) * a3;
  }
  return t2 *= 0.5, Ms(t2, 0) ? null : (n2 /= 6 * t2, o3 /= 6 * t2, { x: n2, y: o3 });
}
var Es = class {
  x;
  y;
  out;
  connectionNames;
  constructor(e4, t2) {
    this.x = e4, this.y = t2, this.out = [], this.connectionNames = new Set;
  }
};
var As = class {
  orig;
  dest;
  twin;
  next;
  visited;
  constructor(e4, t2) {
    this.orig = e4, this.dest = t2, this.twin = null, this.next = null, this.visited = false;
  }
};
function Os(e4, t2) {
  const n2 = [...t2, ...[{ start: { x: e4.minX, y: e4.minY }, end: { x: e4.maxX, y: e4.minY } }, { start: { x: e4.maxX, y: e4.minY }, end: { x: e4.maxX, y: e4.maxY } }, { start: { x: e4.maxX, y: e4.maxY }, end: { x: e4.minX, y: e4.maxY } }, { start: { x: e4.minX, y: e4.maxY }, end: { x: e4.minX, y: e4.minY } }]], o3 = n2.map(() => []);
  for (let e5 = 0;e5 < n2.length; ++e5) {
    const t3 = n2[e5];
    o3[e5].push(t3.start, t3.end);
  }
  for (let e5 = 0;e5 < n2.length; ++e5)
    for (let t3 = e5 + 1;t3 < n2.length; ++t3) {
      const i4 = Ns(n2[e5].start, n2[e5].end, n2[t3].start, n2[t3].end);
      i4 && (o3[e5].push(i4), o3[t3].push(i4));
    }
  const i3 = new Map, r3 = [];
  function s2(e5) {
    const t3 = function(e6, t4 = 0.000000001) {
      return `${Math.round(e6.x / t4)}:${Math.round(e6.y / t4)}`;
    }(e5);
    if (!i3.has(t3)) {
      const n3 = r3.length;
      return i3.set(t3, n3), r3.push(new Es(e5.x, e5.y)), n3;
    }
    return i3.get(t3);
  }
  const a3 = [];
  for (let e5 = 0;e5 < n2.length; ++e5) {
    const t3 = n2[e5], i4 = o3[e5].slice();
    i4.sort((e6, n3) => {
      const o4 = t3.end.x - t3.start.x, i5 = t3.end.y - t3.start.y;
      return (Ms(Math.abs(o4), 0) ? (e6.y - t3.start.y) / i5 : (e6.x - t3.start.x) / o4) - (Ms(Math.abs(o4), 0) ? (n3.y - t3.start.y) / i5 : (n3.x - t3.start.x) / o4);
    });
    for (let e6 = 0;e6 < i4.length - 1; ++e6) {
      const n3 = i4[e6], o4 = i4[e6 + 1], c4 = s2(n3), l4 = s2(o4);
      c4 !== l4 && (a3.push([c4, l4]), t3.connectionName && (r3[c4].connectionNames.add(t3.connectionName), r3[l4].connectionNames.add(t3.connectionName)));
    }
  }
  const c3 = [];
  for (const [e5, t3] of a3) {
    const n3 = new As(e5, t3), o4 = new As(t3, e5);
    n3.twin = c3.length + 1, o4.twin = c3.length;
    const i4 = c3.length;
    c3.push(n3, o4), r3[e5].out.push(i4), r3[t3].out.push(i4 + 1);
  }
  for (let e5 = 0;e5 < r3.length; ++e5) {
    const t3 = r3[e5];
    t3.out.sort((e6, n4) => {
      const o4 = c3[e6], i4 = c3[n4], s3 = r3[o4.dest], a4 = r3[i4.dest];
      return Math.atan2(s3.y - t3.y, s3.x - t3.x) - Math.atan2(a4.y - t3.y, a4.x - t3.x);
    });
    const n3 = t3.out.length;
    for (let e6 = 0;e6 < n3; ++e6) {
      const o4 = t3.out[e6], i4 = t3.out[(e6 - 1 + n3) % n3], r4 = c3[o4];
      r4.twin !== null && (c3[r4.twin].next = i4);
    }
  }
  const l3 = [], h2 = [];
  for (let e5 = 0;e5 < c3.length; ++e5) {
    if (c3[e5].visited)
      continue;
    let t3 = e5;
    const n3 = [], o4 = [];
    do {
      if (t3 === null)
        break;
      const e6 = c3[t3];
      e6.visited = true, n3.push(r3[e6.orig]), o4.push(t3), t3 = e6.next;
    } while (t3 !== null && t3 !== e5 && !c3[t3].visited);
    if (n3.length < 3)
      continue;
    if (Rs(n3) > Ps) {
      const e6 = Ts(n3);
      e6 && (l3.push(e6), h2.push({ vertices: n3.map((e7) => ({ x: e7.x, y: e7.y, connectionNames: e7.connectionNames.size > 0 ? e7.connectionNames : undefined })), centroid: e6 }));
    }
  }
  return { centroids: l3, faces: h2, allVertices: r3 };
}
function ks(e4, t2) {
  if (e4 > t2)
    throw new Error("oneCount cannot be greater than length");
  if (e4 < 0 || t2 < 0)
    throw new Error("oneCount and length must be non-negative");
  const n2 = [];
  return function e5(o3, i3, r3) {
    r3 !== t2 ? (o3[r3] = 0, e5(o3, i3, r3 + 1), i3 > 0 && (o3[r3] = 1, e5(o3, i3 - 1, r3 + 1))) : i3 === 0 && n2.push([...o3]);
  }(Array(t2).fill(0), e4, 0), n2;
}
var Ds = class extends ni {
  getSolverName() {
    return "MultiHeadPolyLineIntraNodeSolver";
  }
  nodeWithPortPoints;
  colorMap;
  hyperParameters;
  connMap;
  candidates;
  bounds;
  solvedRoutes = [];
  unsolvedConnections = [];
  SEGMENTS_PER_POLYLINE;
  cellSize;
  MAX_CANDIDATES = 50000;
  viaDiameter = 0.3;
  obstacleMargin = 0.1;
  traceWidth = 0.15;
  availableZ = [];
  uniqueConnections = 0;
  BOUNDARY_PADDING;
  lastCandidate = null;
  maxViaCount;
  minViaCount;
  phase = "setup";
  progress = 0;
  constructor(e4) {
    super(), this.MAX_ITERATIONS = 1e4, this.nodeWithPortPoints = e4.nodeWithPortPoints, this.colorMap = e4.colorMap ?? us(e4.nodeWithPortPoints), this.hyperParameters = e4.hyperParameters ?? {}, this.SEGMENTS_PER_POLYLINE = e4.hyperParameters?.SEGMENTS_PER_POLYLINE ?? 3, this.BOUNDARY_PADDING = e4.hyperParameters?.BOUNDARY_PADDING ?? 0.05, this.connMap = e4.connMap, this.viaDiameter = e4.viaDiameter ?? this.viaDiameter, this.cellSize = this.nodeWithPortPoints.width / 1024, this.candidates = [], this.availableZ = this.nodeWithPortPoints.availableZ ?? [0, 1], this.bounds = { minX: this.nodeWithPortPoints.center.x - this.nodeWithPortPoints.width / 2, maxX: this.nodeWithPortPoints.center.x + this.nodeWithPortPoints.width / 2, minY: this.nodeWithPortPoints.center.y - this.nodeWithPortPoints.height / 2, maxY: this.nodeWithPortPoints.center.y + this.nodeWithPortPoints.height / 2 };
    const t2 = this.nodeWithPortPoints.width * this.nodeWithPortPoints.height, n2 = (this.viaDiameter + 2 * this.obstacleMargin + this.traceWidth / 2) ** 2, o3 = new Set(this.nodeWithPortPoints.portPoints.map((e5) => e5.connectionName)).size;
    this.uniqueConnections = o3;
    const { numSameLayerCrossings: i3, numEntryExitLayerChanges: r3 } = gs(this.nodeWithPortPoints);
    if (this.minViaCount = 2 * i3 + r3, this.maxViaCount = Math.min(Math.floor(t2 / n2), Math.ceil(1.5 * o3)), this.minViaCount > this.SEGMENTS_PER_POLYLINE * (o3 / 2))
      return this.failed = true, void (this.error = `Not possible to solve problem with given SEGMENTS_PER_POLYLINE (${this.SEGMENTS_PER_POLYLINE}), atleast ${this.minViaCount} vias are required`);
    this.maxViaCount > this.SEGMENTS_PER_POLYLINE && (this.maxViaCount = this.SEGMENTS_PER_POLYLINE), this.maxViaCount < this.minViaCount && (this.maxViaCount = this.minViaCount);
  }
  computeMinGapBtwPolyLines(e4) {
    const t2 = [], n2 = [], o3 = [];
    for (let t3 = 0;t3 < e4.length; t3++) {
      const i3 = e4[t3], r3 = [i3.start, ...i3.mPoints, i3.end], s2 = new Map(this.availableZ.map((e5) => [e5, []]));
      for (let e5 = 0;e5 < r3.length - 1; e5++) {
        const t4 = [r3[e5], r3[e5 + 1]], n3 = t4[0].z2;
        s2.has(n3) || s2.set(n3, []), s2.get(n3).push(t4);
      }
      n2.push(s2), o3.push(r3.filter((e5) => e5.z1 !== e5.z2));
    }
    for (let i3 = 0;i3 < e4.length; i3++) {
      const r3 = n2[i3], s2 = o3[i3];
      for (let a3 = i3 + 1;a3 < e4.length; a3++) {
        if (this.connMap?.areIdsConnected(e4[i3].connectionName, e4[a3].connectionName))
          continue;
        const c3 = n2[a3], l3 = o3[a3];
        let h2 = 1;
        for (const e5 of this.availableZ) {
          const t3 = r3.get(e5) ?? [], n3 = c3.get(e5) ?? [];
          for (const e6 of t3)
            for (const t4 of n3)
              h2 = Math.min(h2, we(e6[0], e6[1], t4[0], t4[1]) - this.traceWidth);
          for (const e6 of s2)
            for (const t4 of n3)
              h2 = Math.min(h2, pe(e6, t4[0], t4[1]) - this.traceWidth / 2 - this.viaDiameter / 2);
          for (const e6 of l3)
            for (const n4 of t3)
              h2 = Math.min(h2, pe(e6, n4[0], n4[1]) - this.traceWidth / 2 - this.viaDiameter / 2);
          for (const e6 of s2)
            for (const t4 of l3)
              h2 = Math.min(h2, me(e6, t4) - this.viaDiameter);
        }
        t2.push(h2);
      }
    }
    return t2;
  }
  insertCandidate(e4) {
    let t2 = 0, n2 = this.candidates.length - 1;
    for (;t2 <= n2; ) {
      const o3 = Math.floor((t2 + n2) / 2);
      this.candidates[o3].f < e4.f ? t2 = o3 + 1 : n2 = o3 - 1;
    }
    this.candidates.splice(t2, 0, e4);
  }
  setupInitialPolyLines() {
    const e4 = new Map;
    this.nodeWithPortPoints.portPoints.forEach((t3) => {
      e4.has(t3.connectionName) ? e4.get(t3.connectionName).end = { ...t3, z1: t3.z ?? 0, z2: t3.z ?? 0 } : e4.set(t3.connectionName, { start: { ...t3, z1: t3.z ?? 0, z2: t3.z ?? 0 }, end: null });
    });
    for (const [t3, n3] of e4.entries())
      n3.end === null && e4.delete(t3);
    if (e4.size === 0)
      return this.failed = true, void (this.error = "No port pairs found, can't solve");
    const t2 = Array.from(e4.entries()), n2 = ((e5, t3, n3, o4) => {
      const i4 = [];
      for (const [, n4] of e5) {
        const e6 = n4.start.z1 !== n4.end.z1, o5 = [];
        for (let n5 = 0;n5 <= t3; n5++) {
          const t4 = n5 % 2 != 0;
          e6 && t4 ? o5.push(n5) : e6 || t4 || o5.push(n5);
        }
        i4.push(o5);
      }
      if (i4.length === 0)
        return [[]];
      let r3 = ((e6) => {
        if (!e6 || e6.length === 0)
          return [[]];
        let t4 = [[]];
        for (const n4 of e6) {
          const e7 = [];
          for (const o5 of t4)
            for (const t5 of n4)
              e7.push([...o5, t5]);
          t4 = e7;
        }
        return t4;
      })(i4).filter((e6) => {
        for (let t4 = 0;t4 < e6.length; t4++)
          if (e6.reduce((e7, t5) => e7 + t5, 0) < o4)
            return false;
        return true;
      });
      return r3 = r3.filter((t4) => {
        for (let n4 = 0;n4 < e5.length; n4++) {
          const [, o5] = e5[n4];
          if (o5.start.z1 !== o5.start.z2 && t4[n4] === 0)
            return false;
        }
        return true;
      }), r3 = r3.filter((t4) => {
        for (let n4 = 0;n4 < e5.length; n4++) {
          const [, o5] = e5[n4];
          if (e5[n4][1].start.z1 === e5[n4][1].start.z2)
            for (let i5 = n4 + 1;i5 < e5.length; i5++) {
              if (e5[i5][1].start.z1 !== e5[i5][1].start.z2)
                continue;
              const [, r4] = e5[i5];
              if (o5.start.z1 === o5.end.z1 && r4.start.z1 === r4.end.z1 && o5.start.z1 === r4.start.z1 && he(o5.start, o5.end, r4.start, r4.end) && t4[n4] + t4[i5] < 2)
                return false;
            }
        }
        return true;
      }), r3 = r3.filter((e6) => !(e6.reduce((e7, t4) => e7 + t4, 0) > n3)), r3;
    })(t2, this.SEGMENTS_PER_POLYLINE, this.maxViaCount, this.minViaCount), o3 = ((e5) => {
      const { bounds: t3, portPairsEntries: n3, viaCountVariants: o4 } = e5, { centroids: i4 } = Os(t3, n3.map(([e6, t4]) => t4)), r3 = [];
      for (const e6 of o4) {
        const n4 = e6.reduce((e7, t4) => e7 + t4, 0);
        let o5 = i4;
        if (i4.length < n4) {
          o5 = [];
          const e7 = Math.ceil(Math.sqrt(n4)), i5 = e7;
          for (let n5 = 0;n5 < e7; n5++)
            for (let r4 = 0;r4 < i5; r4++)
              o5.push({ x: t3.minX + (r4 + 1) / (i5 + 1) * (t3.maxX - t3.minX), y: t3.minY + (n5 + 1) / (e7 + 1) * (t3.maxY - t3.minY) });
        }
        const s2 = ks(n4, o5.length);
        for (const t4 of s2) {
          const n5 = [];
          for (let e7 = 0;e7 < t4.length; e7++)
            t4[e7] === 1 && n5.push(o5[e7]);
          r3.push({ viaPositions: n5, viaCountVariant: e6 });
        }
      }
      return r3;
    })({ portPairsEntries: t2, viaCountVariants: n2, bounds: this.bounds }), i3 = [];
    for (const { viaCountVariant: e5, viaPositions: t3 } of o3) {
      const n3 = Cs(t3);
      for (const t4 of n3)
        i3.push({ viaCountVariant: e5, viaPositions: t4 });
    }
    for (const { viaPositions: e5, viaCountVariant: n3 } of i3) {
      const o4 = [];
      let i4 = 0;
      for (let r4 = 0;r4 < t2.length; r4++) {
        const [s3, a4] = t2[r4], c3 = n3[r4], l3 = e5.slice(i4, i4 + c3), h2 = fs({ start: a4.start, end: a4.end, segmentsPerPolyline: this.SEGMENTS_PER_POLYLINE, viaPositions: l3, viaCount: c3, availableZ: this.availableZ });
        i4 += c3, o4.push({ connectionName: s3, start: a4.start, end: a4.end, mPoints: h2 });
      }
      if (Ss(o4, this.bounds))
        continue;
      const r3 = this.computeMinGapBtwPolyLines(o4), s2 = this.computeH({ minGaps: r3, forces: [] }), a3 = { polyLines: o4, g: 0, h: s2, f: s2, viaCount: n3.reduce((e6, t3) => e6 + t3, 0), minGaps: r3 };
      if (this.checkIfSolved(a3))
        return void (this.candidates = [a3]);
      if (this.candidates.push(a3), this.candidates.length > this.MAX_CANDIDATES)
        return;
    }
    this.candidates.sort((e5, t3) => e5.f - t3.f);
  }
  computeG(e4, t2) {
    return t2.g + 0.000005 + 0.000005 * t2.viaCount * 100;
  }
  computeH(e4) {
    let t2 = 0;
    for (const n2 of e4.forces ?? [])
      for (const e5 of n2)
        for (const n3 of e5.values())
          t2 += n3.fx * n3.fx + n3.fy * n3.fy;
    return t2;
  }
  getNeighbors(e4) {
    const { polyLines: t2 } = e4, n2 = t2.length, o3 = 0.02, i3 = 0.008, r3 = 0.000001, s2 = Array.from({ length: n2 }, (e5, n3) => Array.from({ length: t2[n3].mPoints.length }, () => new Map)), a3 = (e5, n3, o4, i4, r4) => {
      if (n3 > 0 && n3 < t2[e5].mPoints.length + 1) {
        const t3 = n3 - 1, a4 = s2[e5][t3], c4 = a4.get(o4) || { fx: 0, fy: 0 };
        a4.set(o4, { fx: c4.fx + i4, fy: c4.fy + r4 });
      }
    };
    for (let e5 = 0;e5 < n2; e5++)
      for (let i4 = e5 + 1;i4 < n2; i4++) {
        const n3 = t2[e5], s3 = t2[i4], c4 = [n3.start, ...n3.mPoints, n3.end], l4 = [s3.start, ...s3.mPoints, s3.end], h3 = [], d3 = [];
        for (let e6 = 0;e6 < c4.length - 1; e6++)
          h3.push({ p1: c4[e6], p2: c4[e6 + 1], layer: c4[e6].z2, p1Idx: e6, p2Idx: e6 + 1 });
        c4.forEach((e6, t3) => {
          e6.z1 !== e6.z2 && d3.push({ point: e6, layers: [e6.z1, e6.z2], index: t3 });
        });
        const u3 = [], p3 = [];
        for (let e6 = 0;e6 < l4.length - 1; e6++)
          u3.push({ p1: l4[e6], p2: l4[e6 + 1], layer: l4[e6].z2, p1Idx: e6, p2Idx: e6 + 1 });
        l4.forEach((e6, t3) => {
          e6.z1 !== e6.z2 && p3.push({ point: e6, layers: [e6.z1, e6.z2], index: t3 });
        });
        for (const t3 of h3)
          for (const n4 of u3)
            if (t3.layer === n4.layer) {
              if (we(t3.p1, t3.p2, n4.p1, n4.p2) < r3)
                continue;
              const o4 = { x: (t3.p1.x + t3.p2.x) / 2, y: (t3.p1.y + t3.p2.y) / 2 }, s4 = { x: (n4.p1.x + n4.p2.x) / 2, y: (n4.p1.y + n4.p2.y) / 2 }, c5 = o4.x - s4.x, l5 = o4.y - s4.y, h4 = c5 * c5 + l5 * l5;
              if (h4 > r3) {
                const o5 = Math.sqrt(h4), s5 = (Math.exp(-6 * o5), `seg:${i4}:${n4.p1Idx}:${n4.p2Idx}`), c6 = `seg:${e5}:${t3.p1Idx}:${t3.p2Idx}`, l6 = (e6, t4, n5, o6, i5, s6, c7) => {
                  const l7 = Ee(e6, n5.p1, n5.p2), h5 = e6.x - l7.x, d4 = e6.y - l7.y, u4 = h5 * h5 + d4 * d4;
                  if (u4 <= r3)
                    return;
                  const p4 = Math.sqrt(u4), m2 = 0.02 * Math.exp(-6 * p4), g2 = h5 / p4 * m2, f2 = d4 / p4 * m2;
                  a3(o6, t4, s6, g2, f2), a3(i5, n5.p1Idx, c7, -g2 / 2, -f2 / 2), a3(i5, n5.p2Idx, c7, -g2 / 2, -f2 / 2);
                };
                l6(t3.p1, t3.p1Idx, n4, e5, i4, s5, c6), l6(t3.p2, t3.p2Idx, n4, e5, i4, s5, c6), l6(n4.p1, n4.p1Idx, t3, i4, e5, c6, s5), l6(n4.p2, n4.p2Idx, t3, i4, e5, c6, s5);
              }
            }
        for (const t3 of d3)
          for (const n4 of u3)
            if (t3.layers.includes(n4.layer)) {
              const s4 = Ee(t3.point, n4.p1, n4.p2), c5 = t3.point.x - s4.x, l5 = t3.point.y - s4.y, h4 = c5 * c5 + l5 * l5;
              if (h4 > r3) {
                const s5 = Math.sqrt(h4);
                let d4 = 2, u4 = s5;
                s5 < this.viaDiameter / 2 ? (d4 *= 4, u4 = Math.max(r3, s5)) : u4 = Math.max(r3, s5 - this.viaDiameter / 2);
                const p4 = d4 * o3 * Math.exp(-6 * u4), m2 = c5 / s5 * p4, g2 = l5 / s5 * p4, f2 = `seg:${i4}:${n4.p1Idx}:${n4.p2Idx}`;
                a3(e5, t3.index, f2, m2, g2);
                const _2 = `via:${e5}:${t3.index}`;
                a3(i4, n4.p1Idx, _2, -m2 / 2, -g2 / 2), a3(i4, n4.p2Idx, _2, -m2 / 2, -g2 / 2);
              }
            }
        for (const t3 of p3)
          for (const n4 of h3)
            if (t3.layers.includes(n4.layer)) {
              const s4 = Ee(t3.point, n4.p1, n4.p2), c5 = t3.point.x - s4.x, l5 = t3.point.y - s4.y, h4 = c5 * c5 + l5 * l5;
              if (h4 > r3) {
                const s5 = Math.sqrt(h4);
                let d4 = 2, u4 = s5;
                s5 < this.viaDiameter / 2 ? (d4 *= 4, u4 = Math.max(r3, s5)) : u4 = Math.max(r3, s5 - this.viaDiameter / 2);
                const p4 = d4 * o3 * Math.exp(-6 * u4), m2 = c5 / s5 * p4, g2 = l5 / s5 * p4, f2 = `seg:${e5}:${n4.p1Idx}:${n4.p2Idx}`;
                a3(i4, t3.index, f2, m2, g2);
                const _2 = `via:${i4}:${t3.index}`;
                a3(e5, n4.p1Idx, _2, -m2 / 2, -g2 / 2), a3(e5, n4.p2Idx, _2, -m2 / 2, -g2 / 2);
              }
            }
        for (const t3 of d3)
          for (const n4 of p3) {
            if (t3.layers.filter((e6) => n4.layers.includes(e6)).length > 0) {
              const s4 = t3.point.x - n4.point.x, c5 = t3.point.y - n4.point.y, l5 = s4 * s4 + c5 * c5;
              if (l5 > r3) {
                const h4 = Math.sqrt(l5);
                let d4 = 2, u4 = h4;
                h4 < this.viaDiameter ? (d4 *= 4, u4 = Math.max(r3, h4)) : u4 = Math.max(r3, h4 - this.viaDiameter);
                const p4 = d4 * o3 * Math.exp(-6 * u4), m2 = s4 / h4 * p4, g2 = c5 / h4 * p4, f2 = `via:${i4}:${n4.index}`, _2 = `via:${e5}:${t3.index}`;
                a3(e5, t3.index, f2, m2, g2), a3(i4, n4.index, _2, -m2, -g2);
              }
            }
          }
      }
    for (let e5 = 0;e5 < n2; e5++) {
      const n3 = t2[e5], i4 = [n3.start, ...n3.mPoints, n3.end], s3 = [];
      if (i4.forEach((e6, t3) => {
        e6.z1 !== e6.z2 && s3.push({ point: e6, layers: [e6.z1, e6.z2], index: t3 });
      }), !(s3.length < 2))
        for (let t3 = 0;t3 < s3.length; t3++)
          for (let n4 = t3 + 1;n4 < s3.length; n4++) {
            const i5 = s3[t3], c4 = s3[n4], l4 = i5.point.x - c4.point.x, h3 = i5.point.y - c4.point.y, d3 = l4 * l4 + h3 * h3;
            if (d3 > r3) {
              const t4 = Math.sqrt(d3);
              let n5 = 2, s4 = t4;
              t4 < this.viaDiameter ? (n5 *= 4, s4 = Math.max(r3, t4)) : s4 = Math.max(r3, t4 - this.viaDiameter);
              const u3 = n5 * o3 * Math.exp(-6 * s4), p3 = l4 / t4 * u3, m2 = h3 / t4 * u3, g2 = `via:${e5}:${c4.index}`, f2 = `via:${e5}:${i5.index}`;
              a3(e5, i5.index, g2, p3, m2), a3(e5, c4.index, f2, -p3, -m2);
            }
          }
    }
    const c3 = t2.map((e5) => ({ ...e5, mPoints: e5.mPoints.map((e6) => ({ ...e6 })) }));
    let l3 = false;
    for (let e5 = 0;e5 < n2; e5++)
      for (let t3 = 0;t3 < c3[e5].mPoints.length; t3++) {
        const n3 = c3[e5].mPoints[t3], o4 = s2[e5][t3], a4 = { fx: 0, fy: 0 };
        for (const e6 of o4.values())
          a4.fx += e6.fx, a4.fy += e6.fy;
        const h3 = n3.z1 !== n3.z2;
        let d3 = n3.x + a4.fx, u3 = n3.y + a4.fy;
        if (h3) {
          const e6 = this.viaDiameter / 2;
          let t4 = 0, o5 = 0;
          const r4 = this.viaDiameter / 2 + this.BOUNDARY_PADDING, s3 = this.bounds.minX + r4, c4 = this.bounds.maxX - r4, l4 = this.bounds.minY + r4, h4 = this.bounds.maxY - r4, p3 = s3 + e6 - n3.x, m2 = n3.x - (c4 - e6), g2 = l4 + e6 - n3.y, f2 = n3.y - (h4 - e6);
          p3 > 0 ? t4 = i3 * (Math.exp(p3 / (2 * this.obstacleMargin)) - 1) : m2 > 0 && (t4 = -0.008 * (Math.exp(m2 / (2 * this.obstacleMargin)) - 1)), g2 > 0 ? o5 = i3 * (Math.exp(g2 / (2 * this.obstacleMargin)) - 1) : f2 > 0 && (o5 = -0.008 * (Math.exp(f2 / (2 * this.obstacleMargin)) - 1)), a4.fx += t4, a4.fy += o5, d3 = n3.x + a4.fx, u3 = n3.y + a4.fy;
        } else {
          const e6 = this.traceWidth / 2 + this.BOUNDARY_PADDING;
          d3 = Math.max(this.bounds.minX + e6, Math.min(this.bounds.maxX - e6, d3)), u3 = Math.max(this.bounds.minY + e6, Math.min(this.bounds.maxY - e6, u3));
        }
        Math.abs(a4.fx) < r3 && Math.abs(a4.fy) < r3 || (Math.abs(n3.x - d3) > r3 || Math.abs(n3.y - u3) > r3) && (n3.x = d3, n3.y = u3, l3 = true);
      }
    if (!l3)
      return [];
    const h2 = this.computeMinGapBtwPolyLines(c3), d2 = this.computeG(c3, e4), u2 = this.computeH({ minGaps: h2, forces: s2 });
    return [{ polyLines: c3, g: d2, h: u2, f: Math.round(5 * d2) / 5 + u2, minGaps: h2, forces: s2, viaCount: e4.viaCount }];
  }
  checkIfSolved(e4) {
    const t2 = e4.minGaps.every((e5) => e5 >= this.obstacleMargin), n2 = e4.polyLines.every((e5) => e5.mPoints.every((e6) => {
      const t3 = (e6.z1 !== e6.z2 ? this.viaDiameter / 2 : this.traceWidth / 2) + this.BOUNDARY_PADDING;
      return ((e7, t4, n3 = 0) => e7.x >= t4.minX + n3 && e7.x <= t4.maxX - n3 && e7.y >= t4.minY + n3 && e7.y <= t4.maxY - n3)(e6, this.bounds, t3);
    }));
    return t2 && n2;
  }
  tryFinalAcceptance() {
    const e4 = this.hyperParameters?.MINIMUM_FINAL_ACCEPTANCE_GAP ?? undefined;
    if (e4 === undefined || this.lastCandidate === null || this.lastCandidate.minGaps.length === 0)
      return;
    return Math.min(...this.lastCandidate.minGaps) >= e4 ? (this.solved = true, void this._setSolvedRoutes()) : undefined;
  }
  _step() {
    if (this.phase === "setup")
      return this.setupInitialPolyLines(), void (this.phase = "solving");
    const e4 = this.candidates.shift();
    if (!e4) {
      if (this.tryFinalAcceptance(), this.solved)
        return;
      return this.failed = true, void (this.error = "No candidates left");
    }
    if (this.lastCandidate = e4, this.checkIfSolved(e4))
      return this.solved = true, void this._setSolvedRoutes();
    if (!e4)
      return void (this.failed = true);
    const t2 = this.getNeighbors(e4);
    for (const e5 of t2)
      this.insertCandidate(e5);
  }
  visualize() {
    const e4 = { points: [], lines: [], rects: [], circles: [], coordinateSystem: "cartesian", title: "MultiHeadPolyLineIntraNodeSolver Visualization" };
    e4.lines.push({ points: [{ x: this.bounds.minX, y: this.bounds.minY }, { x: this.bounds.maxX, y: this.bounds.minY }, { x: this.bounds.maxX, y: this.bounds.maxY }, { x: this.bounds.minX, y: this.bounds.maxY }, { x: this.bounds.minX, y: this.bounds.minY }], strokeColor: "gray" });
    const t2 = this.lastCandidate ?? this.candidates[0];
    if (t2?.hasClosedSameLayerFace) {
      const t3 = 0.1 * (this.bounds.maxX - this.bounds.minX), n2 = 0.1 * (this.bounds.maxY - this.bounds.minY);
      e4.rects.push({ center: { x: this.bounds.maxX + 0.6 * t3, y: this.bounds.maxY + 0.6 * n2 }, width: t3, height: n2, fill: "red", label: "HAS CLOSED FACE" });
    }
    for (const t3 of this.nodeWithPortPoints.portPoints)
      e4.points.push({ x: t3.x, y: t3.y, label: `${t3.connectionName} (Port z=${t3.z ?? 0})`, color: this.colorMap[t3.connectionName] ?? "blue" });
    return t2 && t2.polyLines.forEach((n2, o3) => {
      const i3 = this.colorMap[n2.connectionName] ?? "purple", r3 = [n2.start, ...n2.mPoints, n2.end];
      for (let t3 = 0;t3 < r3.length - 1; t3++) {
        const o4 = r3[t3], s2 = r3[t3 + 1], a3 = o4.z2, c3 = a3 === 0, l3 = c3 ? i3 : Ao(i3, 0.5);
        e4.lines.push({ points: [o4, s2], strokeColor: l3, strokeWidth: this.traceWidth, strokeDash: c3 ? undefined : [0.15, 0.15], label: `${n2.connectionName} segment (z=${a3})` });
      }
      r3.forEach((s2, a3) => {
        const c3 = s2.z1 !== s2.z2, l3 = s2.z1, h2 = a3 > 0 && a3 < r3.length - 1;
        let d2 = "", u2 = "";
        if (h2) {
          const i4 = a3 - 1, r4 = t2.forces?.[o3]?.[i4];
          if (r4 && r4.size > 0) {
            const o4 = { fx: 0, fy: 0 };
            r4.forEach((r5, a4) => {
              if (o4.fx += r5.fx, o4.fy += r5.fy, Math.abs(r5.fx) > 0.000001 || Math.abs(r5.fy) > 0.000001) {
                const o5 = a4.split(":"), c4 = o5[0], l4 = parseInt(o5[1], 10), h3 = t2.polyLines[l4], d3 = this.colorMap[h3.connectionName] ?? "gray", u3 = 20, p3 = { x: s2.x + r5.fx * u3, y: s2.y + r5.fy * u3 };
                let m2 = h3.connectionName;
                if (c4 === "via") {
                  m2 += ` Via ${parseInt(o5[2], 10)}`;
                } else if (c4 === "seg") {
                  m2 += ` Seg ${parseInt(o5[2], 10)}-${parseInt(o5[3], 10)}`;
                }
                e4.lines.push({ points: [s2, p3], strokeColor: d3, strokeWidth: 0.02, strokeDash: "2,2", label: `Force by ${m2} on ${n2.connectionName} mPoint ${i4}` });
              }
            }), (Math.abs(o4.fx) > 0.000001 || Math.abs(o4.fy) > 0.000001) && (u2 = `
Net Force: (${o4.fx.toFixed(3)}, ${o4.fy.toFixed(3)})`);
          }
        }
        if (c3)
          d2 = `Via (${n2.connectionName} z=${s2.z1} -> z=${s2.z2})${u2}`, e4.circles.push({ center: s2, radius: this.viaDiameter / 2, fill: Ao(i3, 0.5), label: d2 });
        else if (h2) {
          const t3 = l3 === 0 ? i3 : Ao(i3, 0.5);
          d2 = `mPoint (${n2.connectionName} z=${l3})${u2}`, e4.circles.push({ center: s2, radius: this.cellSize / 8, fill: t3, label: d2 });
        }
      });
    }), e4;
  }
  _setSolvedRoutes() {
    if (!this.solved || !this.lastCandidate)
      return [];
    const e4 = [];
    for (const t2 of this.lastCandidate.polyLines) {
      const n2 = [], o3 = [], i3 = [t2.start, ...t2.mPoints, t2.end];
      for (let e5 = 0;e5 < i3.length; e5++) {
        const t3 = i3[e5];
        n2.push({ x: t3.x, y: t3.y, z: t3.z1 }), t3.z1 !== t3.z2 && (o3.push({ x: t3.x, y: t3.y }), n2.push({ x: t3.x, y: t3.y, z: t3.z2 }));
      }
      e4.push({ connectionName: t2.connectionName, regionId: this.nodeWithPortPoints.capacityMeshNodeId, traceThickness: this.traceWidth, viaDiameter: this.viaDiameter, route: n2, vias: o3 });
    }
    this.solvedRoutes = e4;
  }
};
var Ls = class extends Ds {
  forceWorkspace = { netForces: [], geometry: [] };
  prepareForceWorkspace(e4) {
    const { netForces: t2, geometry: n2 } = this.forceWorkspace;
    t2.length = e4.length, n2.length = e4.length;
    for (let o3 = 0;o3 < e4.length; o3++) {
      const i3 = e4[o3];
      let r3 = t2[o3];
      r3 || (r3 = [], t2[o3] = r3), r3.length = i3.mPoints.length;
      for (let e5 = 0;e5 < r3.length; e5++) {
        const t3 = r3[e5];
        t3 ? (t3.fx = 0, t3.fy = 0) : r3[e5] = { fx: 0, fy: 0 };
      }
      let s2 = n2[o3];
      s2 || (s2 = { segments: [], vias: [] }, n2[o3] = s2);
      const { segments: a3, vias: c3 } = s2, l3 = i3.mPoints.length + 1;
      a3.length = l3;
      let h2 = 0;
      for (let e5 = 0;e5 <= l3; e5++) {
        const t3 = e5 === 0 ? i3.start : e5 === l3 ? i3.end : i3.mPoints[e5 - 1];
        if (e5 < l3) {
          const n3 = e5 + 1 === l3 ? i3.end : i3.mPoints[e5], o4 = n3.x - t3.x, s3 = n3.y - t3.y;
          let c4 = a3[e5];
          c4 ? (c4.p1 = t3, c4.p2 = n3, c4.deltaX = o4, c4.deltaY = s3, c4.lengthSquared = o4 * o4 + s3 * s3, c4.layer = t3.z2, c4.p1Idx = e5, c4.p2Idx = e5 + 1, c4.p1Force = r3[e5 - 1], c4.p2Force = r3[e5], c4.lastTargetLine = -1, c4.lastEndpointIndex = -1, c4.lastFx = 0, c4.lastFy = 0, c4.lastForceActive = false) : (c4 = { p1: t3, p2: n3, deltaX: o4, deltaY: s3, lengthSquared: o4 * o4 + s3 * s3, layer: t3.z2, p1Idx: e5, p2Idx: e5 + 1, p1Force: r3[e5 - 1], p2Force: r3[e5], lastTargetLine: -1, lastEndpointIndex: -1, lastFx: 0, lastFy: 0, lastForceActive: false }, a3[e5] = c4);
        }
        if (t3.z1 !== t3.z2) {
          let n3 = c3[h2];
          n3 ? (n3.point = t3, n3.layers[0] = t3.z1, n3.layers[1] = t3.z2, n3.index = e5, n3.force = r3[e5 - 1]) : (n3 = { point: t3, layers: [t3.z1, t3.z2], index: e5, force: r3[e5 - 1] }, c3[h2] = n3), h2++;
        }
      }
      c3.length = h2;
    }
    return this.forceWorkspace;
  }
  getSolverName() {
    return "MultiHeadPolyLineIntraNodeSolver2";
  }
  computeG(e4, t2) {
    return t2.g + 0.000005 + 0.000005 * t2.viaCount * 100;
  }
  computeH(e4) {
    const { minGaps: t2 } = e4;
    let n2 = 0;
    for (const e5 of t2)
      e5 < 0 && (n2 += this.obstacleMargin), e5 < this.obstacleMargin && (n2 += this.obstacleMargin - e5);
    return 0.011 * n2;
  }
  _step() {
    if (this.phase === "setup")
      return this.setupInitialPolyLines(), void (this.phase = "solving");
    const e4 = this.candidates.shift();
    if (!e4) {
      if (this.tryFinalAcceptance(), this.solved)
        return;
      return void (this.failed = true);
    }
    if (this.lastCandidate = e4, this.checkIfSolved(e4))
      return this.solved = true, void this._setSolvedRoutes();
    let t2 = false, n2 = 0;
    const o3 = e4.magForceApplied === undefined ? 1 : 10;
    for (let i3 = 0;i3 < o3; i3++) {
      const o4 = this.applyForcesToPolyLines(e4.polyLines);
      if (n2 += o4.magForceApplied, t2 = o4.lastStepMoved, !o4.lastStepMoved)
        break;
    }
    if (e4.magForceApplied = n2, e4.minGaps = this.computeMinGapBtwPolyLines(e4.polyLines), this.checkIfSolved(e4))
      return this.solved = true, void this._setSolvedRoutes();
    e4.g = this.computeG(e4.polyLines, e4), e4.h = this.computeH(e4), e4.f = e4.g + e4.h, t2 && this.insertCandidate(e4);
  }
  applyForcesToPolyLines(e4) {
    let t2 = 0;
    const n2 = e4.length, o3 = 0.02, i3 = 0.008, r3 = 0.000001, { netForces: s2, geometry: a3 } = this.prepareForceWorkspace(e4), c3 = (e5, t3, n3, o4, i4) => {
      let s3, a4;
      if (n3.lastTargetLine === o4 && n3.lastEndpointIndex === t3) {
        if (!n3.lastForceActive)
          return;
        s3 = n3.lastFx, a4 = n3.lastFy;
      } else {
        let i5 = n3.p1.x, c4 = n3.p1.y;
        if (n3.lengthSquared !== 0) {
          const t4 = Math.max(0, Math.min(1, ((e5.x - n3.p1.x) * n3.deltaX + (e5.y - n3.p1.y) * n3.deltaY) / n3.lengthSquared));
          i5 += t4 * n3.deltaX, c4 += t4 * n3.deltaY;
        }
        const l4 = e5.x - i5, h2 = e5.y - c4, d2 = l4 * l4 + h2 * h2;
        if (n3.lastTargetLine = o4, n3.lastEndpointIndex = t3, d2 <= r3)
          return void (n3.lastForceActive = false);
        const u2 = Math.sqrt(d2), p3 = 0.02 * Math.exp(-6 * u2);
        s3 = l4 / u2 * p3, a4 = h2 / u2 * p3, n3.lastFx = s3, n3.lastFy = a4, n3.lastForceActive = true;
      }
      i4 && (i4.fx += s3, i4.fy += a4), n3.p1Force && (n3.p1Force.fx += -s3 / 2, n3.p1Force.fy += -a4 / 2), n3.p2Force && (n3.p2Force.fx += -s3 / 2, n3.p2Force.fy += -a4 / 2);
    };
    for (let e5 = 0;e5 < n2; e5++)
      for (let t3 = e5 + 1;t3 < n2; t3++) {
        const { segments: n3, vias: i4 } = a3[e5], { segments: s3, vias: l4 } = a3[t3];
        for (const o4 of n3)
          for (const n4 of s3)
            o4.layer === n4.layer && (c3(o4.p1, o4.p1Idx, n4, e5, o4.p1Force), c3(o4.p2, o4.p2Idx, n4, e5, o4.p2Force), c3(n4.p1, n4.p1Idx, o4, t3, n4.p1Force), c3(n4.p2, n4.p2Idx, o4, t3, n4.p2Force));
        for (const e6 of i4)
          for (const t4 of s3)
            if (e6.layers.includes(t4.layer)) {
              const n4 = Ee(e6.point, t4.p1, t4.p2), i5 = e6.point.x - n4.x, s4 = e6.point.y - n4.y, a4 = i5 * i5 + s4 * s4;
              if (a4 > r3) {
                const n5 = Math.sqrt(a4);
                let c4 = 2, l5 = n5;
                n5 < this.viaDiameter / 2 ? (c4 *= 4, l5 = Math.max(r3, n5)) : l5 = Math.max(r3, n5 - this.viaDiameter / 2);
                const h2 = c4 * o3 * Math.exp(-6 * l5), d2 = i5 / n5 * h2, u2 = s4 / n5 * h2;
                e6.force && (e6.force.fx += d2, e6.force.fy += u2), t4.p1Force && (t4.p1Force.fx += -d2 / 2, t4.p1Force.fy += -u2 / 2), t4.p2Force && (t4.p2Force.fx += -d2 / 2, t4.p2Force.fy += -u2 / 2);
              }
            }
        for (const e6 of l4)
          for (const t4 of n3)
            if (e6.layers.includes(t4.layer)) {
              const n4 = Ee(e6.point, t4.p1, t4.p2), i5 = e6.point.x - n4.x, s4 = e6.point.y - n4.y, a4 = i5 * i5 + s4 * s4;
              if (a4 > r3) {
                const n5 = Math.sqrt(a4);
                let c4 = 2, l5 = n5;
                n5 < this.viaDiameter / 2 ? (c4 *= 4, l5 = Math.max(r3, n5)) : l5 = Math.max(r3, n5 - this.viaDiameter / 2);
                const h2 = c4 * o3 * Math.exp(-6 * l5), d2 = i5 / n5 * h2, u2 = s4 / n5 * h2;
                e6.force && (e6.force.fx += d2, e6.force.fy += u2), t4.p1Force && (t4.p1Force.fx += -d2 / 2, t4.p1Force.fy += -u2 / 2), t4.p2Force && (t4.p2Force.fx += -d2 / 2, t4.p2Force.fy += -u2 / 2);
              }
            }
        for (const e6 of i4)
          for (const t4 of l4) {
            if (e6.layers.filter((e7) => t4.layers.includes(e7)).length > 0) {
              const n4 = e6.point.x - t4.point.x, i5 = e6.point.y - t4.point.y, s4 = n4 * n4 + i5 * i5;
              if (s4 > r3) {
                const a4 = Math.sqrt(s4);
                let c4 = 2, l5 = a4;
                a4 < this.viaDiameter ? (c4 *= 4, l5 = Math.max(r3, a4)) : l5 = Math.max(r3, a4 - this.viaDiameter);
                const h2 = c4 * o3 * Math.exp(-6 * l5), d2 = n4 / a4 * h2, u2 = i5 / a4 * h2;
                e6.force && (e6.force.fx += d2, e6.force.fy += u2), t4.force && (t4.force.fx += -d2, t4.force.fy += -u2);
              }
            }
          }
      }
    for (let e5 = 0;e5 < n2; e5++) {
      const { vias: t3 } = a3[e5];
      if (!(t3.length < 2))
        for (let e6 = 0;e6 < t3.length; e6++)
          for (let n3 = e6 + 1;n3 < t3.length; n3++) {
            const i4 = t3[e6], s3 = t3[n3], a4 = i4.point.x - s3.point.x, c4 = i4.point.y - s3.point.y, l4 = a4 * a4 + c4 * c4;
            if (l4 > r3) {
              const e7 = Math.sqrt(l4);
              let t4 = 2, n4 = e7;
              e7 < this.viaDiameter ? (t4 *= 4, n4 = Math.max(r3, e7)) : n4 = Math.max(r3, e7 - this.viaDiameter);
              const h2 = t4 * o3 * Math.exp(-6 * n4), d2 = a4 / e7 * h2, u2 = c4 / e7 * h2;
              i4.force && (i4.force.fx += d2, i4.force.fy += u2), s3.force && (s3.force.fx += -d2, s3.force.fy += -u2);
            }
          }
    }
    let l3 = false;
    for (let o4 = 0;o4 < n2; o4++)
      for (let n3 = 0;n3 < e4[o4].mPoints.length; n3++) {
        const a4 = e4[o4].mPoints[n3], c4 = s2[o4][n3], h2 = a4.z1 !== a4.z2;
        let { fx: d2, fy: u2 } = c4, p3 = a4.x + d2, m2 = a4.y + u2;
        if (h2) {
          const e5 = this.viaDiameter / 2;
          let t3 = 0, n4 = 0;
          const o5 = this.viaDiameter / 2 + this.BOUNDARY_PADDING, r4 = this.bounds.minX + o5, s3 = this.bounds.maxX - o5, c5 = this.bounds.minY + o5, l4 = this.bounds.maxY - o5, h3 = r4 + e5 - a4.x, g2 = a4.x - (s3 - e5), f2 = c5 + e5 - a4.y, _2 = a4.y - (l4 - e5);
          h3 > 0 ? t3 = i3 * (Math.exp(h3 / (2 * this.obstacleMargin)) - 1) : g2 > 0 && (t3 = -0.008 * (Math.exp(g2 / (2 * this.obstacleMargin)) - 1)), f2 > 0 ? n4 = i3 * (Math.exp(f2 / (2 * this.obstacleMargin)) - 1) : _2 > 0 && (n4 = -0.008 * (Math.exp(_2 / (2 * this.obstacleMargin)) - 1)), d2 += t3, u2 += n4, p3 = a4.x + d2, m2 = a4.y + u2;
        } else {
          const e5 = this.traceWidth / 2 + this.BOUNDARY_PADDING;
          p3 = Math.max(this.bounds.minX + e5, Math.min(this.bounds.maxX - e5, p3)), m2 = Math.max(this.bounds.minY + e5, Math.min(this.bounds.maxY - e5, m2));
        }
        if (Math.abs(d2) < r3 && Math.abs(u2) < r3)
          continue;
        t2 += Math.sqrt(d2 * d2 + u2 * u2), (Math.abs(a4.x - p3) > r3 || Math.abs(a4.y - m2) > r3) && (a4.x = p3, a4.y = m2, l3 = true);
      }
    return { lastStepMoved: l3, magForceApplied: t2 };
  }
};
var zs = (e4) => e4.flatMap((e5) => `${e5.connectionName}-${e5.mPoints.map((e6) => `${e6.x.toFixed(2)},${e6.y.toFixed(2)},${e6.z1},${e6.z2}`)}`).sort().join("|");
var Bs = class extends Ls {
  getSolverName() {
    return "MultiHeadPolyLineIntraNodeSolver3";
  }
  constructor(e4) {
    super(e4), this.MAX_ITERATIONS = 1000;
  }
  createInitialCandidateFromSeed(e4, t2) {
    const n2 = new ps({ nodeWithPortPoints: this.nodeWithPortPoints, colorMap: this.colorMap, hyperParameters: { SHUFFLE_SEED: e4 }, viaDiameter: this.viaDiameter });
    if (n2.solve(), n2.failed || !n2.solved)
      return this.failed = true, this.error = `ViaPossibilitiesSolver2 failed with: ${n2.error}`, null;
    const o3 = [];
    let i3 = 0;
    for (const [e5, t3] of n2.completedPaths.entries()) {
      if (t3.length < 2) {
        console.warn(`Skipping connection "${e5}" due to insufficient points (${t3.length}) in ViaPossibilitiesSolver2 path.`);
        continue;
      }
      const n3 = t3[0], r4 = t3[t3.length - 1], s3 = t3.slice(1, -1), a4 = [];
      let c3 = 0, l3 = n3.z;
      for (let e6 = 0;e6 < s3.length; e6++) {
        const t4 = s3[e6], n4 = e6 + 1 < s3.length ? s3[e6 + 1] : r4, o4 = l3, i4 = e6 + 1 < s3.length && t4.x === n4.x && t4.y === n4.y && t4.z !== n4.z ? n4.z : t4.z;
        a4.push({ x: t4.x, y: t4.y, z1: o4, z2: i4 }), o4 !== i4 ? (c3++, e6++, l3 = i4) : l3 = t4.z;
      }
      i3 += c3;
      const h2 = this.SEGMENTS_PER_POLYLINE;
      let d2 = a4.length + 1;
      for (;d2 < h2; ) {
        let t4 = -1, o4 = -1, i4 = null, s4 = null;
        const c4 = [{ ...n3, z1: n3.z, z2: n3.z, connectionName: e5 }, ...a4, { ...r4, z1: r4.z, z2: r4.z, connectionName: e5 }];
        for (let e6 = 0;e6 < c4.length - 1; e6++) {
          const n4 = c4[e6], r5 = c4[e6 + 1];
          if (n4.x === r5.x && n4.y === r5.y)
            continue;
          const a5 = me(n4, r5);
          a5 > t4 && (t4 = a5, o4 = e6, i4 = n4, s4 = r5);
        }
        if (o4 === -1 || !i4 || !s4) {
          console.warn(`Could not find longest segment for ${e5} while trying to reach ${h2} segments.`);
          break;
        }
        const l4 = (i4.x + s4.x) / 2, u2 = (i4.y + s4.y) / 2, p3 = i4.z2, m2 = { x: l4, y: u2, z1: p3, z2: p3 };
        a4.splice(o4, 0, m2), d2++;
      }
      o3.push({ connectionName: e5, start: { ...n3, z1: n3.z, z2: n3.z }, end: { ...r4, z1: r4.z, z2: r4.z }, mPoints: a4 });
    }
    if (o3.length === 0)
      return this.failed = true, this.error = "No valid polylines generated from ViaPossibilitiesSolver2.", console.error(this.error), null;
    if (t2?.has(zs(o3)))
      return null;
    const r3 = this.computeMinGapBtwPolyLines(o3), s2 = this.computeH({ minGaps: r3, forces: [] }), a3 = { polyLines: o3, g: 0, h: s2, f: 0 + s2, viaCount: i3, minGaps: r3 };
    return a3.g = this.computeG(o3, a3), a3.f = a3.g + a3.h, a3;
  }
  setupInitialPolyLines() {
    this.candidates = [];
    const e4 = Math.min(2000, function(e5) {
      if (!Number.isInteger(e5) || e5 < 0)
        throw new RangeError("n must be a non-negative integer");
      let t3 = 1;
      for (let n3 = 2;n3 <= e5; n3++)
        t3 *= n3;
      return t3;
    }(this.uniqueConnections)), t2 = new Set, n2 = this.createInitialCandidateFromSeed === Fs && this.computeMinGapBtwPolyLines === js && this.computeH === $s && this.computeG === Ys;
    for (let o3 = 0;o3 < e4; o3++) {
      const e5 = n2 ? this.createInitialCandidateFromSeed(o3, t2) : this.createInitialCandidateFromSeed(o3);
      if (!e5)
        continue;
      const i3 = zs(e5.polyLines);
      t2.has(i3) || (t2.add(i3), this.candidates.push(e5));
    }
    this.candidates.sort((e5, t3) => e5.f - t3.f);
  }
};
var Fs = Bs.prototype.createInitialCandidateFromSeed;
var js = Ds.prototype.computeMinGapBtwPolyLines;
var $s = Ls.prototype.computeH;
var Ys = Ls.prototype.computeG;
var Xs = (e4) => e4.portPointId ?? `${e4.connectionName}:${e4.x}:${e4.y}:${e4.z}`;
var Hs = (e4, t2) => {
  const [n2, o3] = e4;
  if (n2 === o3)
    return false;
  const i3 = ((e5) => {
    const [t3, n3] = e5, o4 = Xs(t3), i4 = Xs(n3);
    return o4 < i4 ? `${o4}|${i4}` : `${i4}|${o4}`;
  })(e4);
  return !t2.seenPairKeys.has(i3) && (t2.seenPairKeys.add(i3), t2.pairs.push(e4), true);
};
var Vs = (e4, t2) => {
  for (let n2 = 0;n2 < e4.length - 1; n2++)
    Hs([e4[n2], e4[n2 + 1]], t2);
};
var Ws = (e4) => {
  const t2 = [], n2 = new Set, o3 = new Map(e4.filter((e5) => typeof e5.portPointId == "string").map((e5) => [e5.portPointId, e5])), i3 = { pairs: t2, seenPairKeys: n2 };
  for (const t3 of e4) {
    if (t3.prevPortPointId) {
      const e5 = o3.get(t3.prevPortPointId);
      e5 && e5.connectionName === t3.connectionName && Hs([e5, t3], i3);
    }
    if (t3.nextPortPointId) {
      const e5 = o3.get(t3.nextPortPointId);
      e5 && e5.connectionName === t3.connectionName && Hs([t3, e5], i3);
    }
  }
  if (t2.length === 0)
    return Vs(e4, i3), t2;
  const r3 = new Set(t2.flatMap(([e5, t3]) => [e5.portPointId, t3.portPointId]).filter(Boolean)), s2 = e4.filter((e5) => !e5.portPointId || !r3.has(e5.portPointId));
  return Vs(s2, i3), t2;
};
var Gs = 0.000001;
var Us = 0.02;
var Zs = (e4) => `${e4.x.toFixed(6)},${e4.y.toFixed(6)}`;
var qs = (e4, t2) => Math.abs(e4.x - t2.x) < Gs && Math.abs(e4.y - t2.y) < Gs;
var Js = (e4) => ({ minX: e4.center.x - e4.width / 2, maxX: e4.center.x + e4.width / 2, minY: e4.center.y - e4.height / 2, maxY: e4.center.y + e4.height / 2 });
var Qs = (e4, t2) => e4.x >= t2.minX - Gs && e4.x <= t2.maxX + Gs && e4.y >= t2.minY - Gs && e4.y <= t2.maxY + Gs;
var Ks = (e4, t2, n2) => {
  for (const o3 of n2)
    if (!qs(o3, e4) && !qs(o3, t2) && pe(o3, e4, t2) < 0.0001)
      return true;
  return false;
};
var ea = (e4, t2, n2) => {
  for (const o3 of n2)
    if (!(qs(e4, o3.A) || qs(e4, o3.B) || qs(t2, o3.A) || qs(t2, o3.B)) && he(e4, t2, o3.A, o3.B))
      return true;
  return false;
};
var ta = (e4, t2) => {
  const n2 = [];
  for (const o3 of e4) {
    const e5 = o3.rootConnectionName ?? o3.connectionName;
    if (e5 !== t2)
      for (let t3 = 0;t3 < o3.route.length - 1; t3++) {
        const i3 = o3.route[t3], r3 = o3.route[t3 + 1];
        i3.z === r3.z && n2.push({ A: { x: i3.x, y: i3.y }, B: { x: r3.x, y: r3.y }, rootConnectionName: e5 });
      }
  }
  return n2;
};
var na = (e4, t2) => e4.portPoints.filter((e5) => (e5.rootConnectionName ?? e5.connectionName) !== t2).map((e5) => ({ x: e5.x, y: e5.y }));
function* oa(e4, t2 = e4.length) {
  if (t2 <= 1)
    yield e4.slice();
  else
    for (let n2 = 0;n2 < t2; n2++)
      [e4[n2], e4[t2 - 1]] = [e4[t2 - 1], e4[n2]], yield* oa(e4, t2 - 1), [e4[n2], e4[t2 - 1]] = [e4[t2 - 1], e4[n2]];
}
var ia = ({ A: e4, B: t2, bounds: n2, obstacleSegments: o3, foreignPorts: i3 }) => {
  const r3 = [{ x: e4.x, y: e4.y }, { x: t2.x, y: t2.y }, { x: (n2.minX + n2.maxX) / 2, y: (n2.minY + n2.maxY) / 2 }, { x: n2.minX, y: n2.minY }, { x: n2.maxX, y: n2.minY }, { x: n2.maxX, y: n2.maxY }, { x: n2.minX, y: n2.maxY }], s2 = [...o3.flatMap((e5) => [e5.A, e5.B]), ...i3, { x: e4.x, y: e4.y }, { x: t2.x, y: t2.y }];
  for (const e5 of s2)
    for (const t3 of [-0.02, 0, Us])
      for (const o4 of [-0.02, 0, Us]) {
        const i4 = { x: e5.x + t3, y: e5.y + o4 };
        Qs(i4, n2) && r3.push(i4);
      }
  const a3 = ((e5) => {
    const t3 = new Set, n3 = [];
    for (const o4 of e5) {
      const e6 = Zs(o4);
      t3.has(e6) || (t3.add(e6), n3.push(o4));
    }
    return n3;
  })(r3), c3 = Zs(e4), l3 = Zs(t2), h2 = new Map(a3.map((e5) => [Zs(e5), e5])), d2 = new Map, u2 = new Map, p3 = new Set;
  for (const e5 of a3) {
    const t3 = Zs(e5);
    d2.set(t3, t3 === c3 ? 0 : 1 / 0), u2.set(t3, null), p3.add(t3);
  }
  for (;p3.size > 0; ) {
    let e5 = null, t3 = 1 / 0;
    for (const n4 of p3) {
      const o4 = d2.get(n4) ?? 1 / 0;
      (o4 < t3 - Gs || Math.abs(o4 - t3) <= Gs && (e5 === null || n4 < e5)) && (t3 = o4, e5 = n4);
    }
    if (!e5 || t3 === 1 / 0)
      break;
    if (p3.delete(e5), e5 === l3)
      break;
    const n3 = h2.get(e5);
    for (const r4 of p3) {
      const s3 = h2.get(r4);
      if (qs(n3, s3))
        continue;
      if (ea(n3, s3, o3))
        continue;
      if (Ks(n3, s3, i3))
        continue;
      const a4 = t3 + me(n3, s3), c4 = d2.get(r4) ?? 1 / 0, l4 = u2.get(r4);
      (a4 < c4 - Gs || Math.abs(a4 - c4) <= Gs && (l4 == null || e5 < l4)) && (d2.set(r4, a4), u2.set(r4, e5));
    }
  }
  if ((d2.get(l3) ?? 1 / 0) === 1 / 0)
    return null;
  const m2 = [];
  let g2 = l3;
  for (;g2; )
    m2.push(h2.get(g2)), g2 = u2.get(g2) ?? null;
  return m2.reverse(), m2.map((t3) => ({ x: t3.x, y: t3.y, z: e4.z }));
};
var ra = class extends ni {
  getSolverName() {
    return "SingleLayerNoDifferentRootIntersectionsIntraNodeSolver";
  }
  nodeWithPortPoints;
  traceWidth;
  viaDiameter;
  solvedRoutes = [];
  constructor(e4) {
    super(), this.nodeWithPortPoints = e4.nodeWithPortPoints, this.traceWidth = e4.traceWidth ?? 0.15, this.viaDiameter = e4.viaDiameter ?? 0.3, this.MAX_ITERATIONS = 1;
  }
  static isApplicable(e4) {
    const t2 = ((e5) => e5.availableZ?.length ? [...new Set(e5.availableZ)].sort((e6, t3) => e6 - t3) : [...new Set(e5.portPoints.map((e6) => e6.z ?? 0))].sort((e6, t3) => e6 - t3))(e4);
    if (t2.length !== 1)
      return false;
    if (e4.portPoints.length > 12)
      return false;
    const n2 = Js(e4);
    if (e4.portPoints.some((e5) => ((e6, t3) => Math.abs(e6.y - t3.minY) < 0.001 ? "top" : Math.abs(e6.x - t3.maxX) < 0.001 ? "right" : Math.abs(e6.y - t3.maxY) < 0.001 ? "bottom" : Math.abs(e6.x - t3.minX) < 0.001 ? "left" : null)(e5, n2) === null))
      return false;
    const o3 = new Map;
    for (const t3 of e4.portPoints)
      o3.set(t3.connectionName, (o3.get(t3.connectionName) ?? 0) + 1);
    return [...o3.values()].some((e5) => e5 > 2);
  }
  buildTaskGroups() {
    const e4 = new Map;
    for (const t2 of this.nodeWithPortPoints.portPoints) {
      const n2 = e4.get(t2.connectionName) ?? [];
      n2.push(t2), e4.set(t2.connectionName, n2);
    }
    return e4;
  }
  trySolveNode() {
    const e4 = Js(this.nodeWithPortPoints), t2 = this.buildTaskGroups(), n2 = Array.from(t2.entries()).flatMap(([e5, t3]) => Ws(t3).map(([t4, n3]) => ({ connectionName: e5, rootConnectionName: t4.rootConnectionName ?? n3.rootConnectionName ?? e5, A: t4, B: n3 }))), o3 = n2.length <= 6 ? oa(n2.slice()) : [n2];
    for (const t3 of o3) {
      const n3 = [];
      let o4 = false;
      for (const i3 of t3) {
        const t4 = ta(n3, i3.rootConnectionName), r3 = na(this.nodeWithPortPoints, i3.rootConnectionName), s2 = ia({ A: i3.A, B: i3.B, bounds: e4, obstacleSegments: t4, foreignPorts: r3 });
        if (!s2 || s2.length < 2) {
          o4 = true;
          break;
        }
        n3.push({ connectionName: i3.connectionName, rootConnectionName: i3.rootConnectionName, regionId: this.nodeWithPortPoints.capacityMeshNodeId, traceThickness: this.traceWidth, viaDiameter: this.viaDiameter, route: s2, vias: [] });
      }
      if (!o4)
        return n3;
    }
    return null;
  }
  _step() {
    const e4 = this.trySolveNode();
    if (!e4)
      return this.failed = true, void (this.error = "Failed to find a single-layer route set without different-root intersections");
    this.solvedRoutes = e4, this.stats = { routeCount: e4.length, distinctRoots: new Set(e4.map((e5) => e5.rootConnectionName ?? e5.connectionName)).size }, this.solved = true;
  }
  visualize() {
    return { lines: this.solvedRoutes.map((e4) => ({ points: e4.route, strokeColor: "cyan", strokeWidth: e4.traceThickness, label: `${e4.connectionName}
root: ${e4.rootConnectionName ?? e4.connectionName}` })), points: this.nodeWithPortPoints.portPoints.map((e4) => ({ x: e4.x, y: e4.y, color: "blue", label: `${e4.connectionName}
root: ${e4.rootConnectionName ?? e4.connectionName}` })), rects: [], circles: [] };
  }
};
var sa = (e4) => e4.min <= e4.max ? Me(e4.value, e4.min, e4.max) : e4.value;
var aa = class extends ni {
  getSolverName() {
    return "SingleTransitionIntraNodeSolver";
  }
  nodeWithPortPoints;
  routes;
  viaDiameter;
  traceThickness;
  obstacleMargin;
  solvedRoutes = [];
  bounds;
  constructor(e4) {
    if (super(), this.nodeWithPortPoints = e4.nodeWithPortPoints, this.viaDiameter = e4?.viaDiameter ?? 0.3, this.traceThickness = e4?.traceThickness ?? 0.15, this.obstacleMargin = e4?.obstacleMargin ?? 0.1, this.routes = this.extractRoutesFromNode(), this.bounds = this.calculateBounds(), this.routes.length !== 1)
      return this.failed = true, void (this.error = `Expected 1 route, but got ${this.routes.length}`);
    const t2 = this.routes[0];
    if (t2.A.z === undefined || t2.B.z === undefined)
      return this.failed = true, void (this.error = "Route points should have predefined z values");
    if (t2.A.z === t2.B.z)
      return this.failed = true, void (this.error = "Only one route provided, but it has no transition");
    const n2 = this.viaDiameter / 2 + this.obstacleMargin, o3 = { x: sa({ value: (t2.A.x + t2.B.x) / 2, min: this.bounds.minX + n2, max: this.bounds.maxX - n2 }), y: sa({ value: (t2.A.y + t2.B.y) / 2, min: this.bounds.minY + n2, max: this.bounds.maxY - n2 }) };
    this.solvedRoutes.push(this.createTransitionRoute({ start: t2.A, end: t2.B, via: o3, connectionName: t2.connectionName })), this.solved = true;
  }
  extractRoutesFromNode() {
    const e4 = [], t2 = this.nodeWithPortPoints.portPoints, n2 = new Map;
    for (const e5 of t2) {
      const { connectionName: t3 } = e5;
      n2.has(t3) || n2.set(t3, []), n2.get(t3).push(e5);
    }
    for (const [t3, o3] of n2.entries())
      for (const [n3, i3] of Ws(o3))
        e4.push({ A: { ...n3 }, B: { ...i3 }, connectionName: t3 });
    return e4;
  }
  calculateBounds() {
    return { minX: this.nodeWithPortPoints.center.x - this.nodeWithPortPoints.width / 2, maxX: this.nodeWithPortPoints.center.x + this.nodeWithPortPoints.width / 2, minY: this.nodeWithPortPoints.center.y - this.nodeWithPortPoints.height / 2, maxY: this.nodeWithPortPoints.center.y + this.nodeWithPortPoints.height / 2 };
  }
  createTransitionRoute(e4) {
    const { start: t2, end: n2, via: o3, connectionName: i3 } = e4, r3 = [{ x: t2.x, y: t2.y, z: t2.z }, { x: o3.x, y: o3.y, z: t2.z }, { x: o3.x, y: o3.y, z: n2.z }, { x: n2.x, y: n2.y, z: n2.z }];
    return { connectionName: i3, regionId: this.nodeWithPortPoints.capacityMeshNodeId, route: r3, traceThickness: this.traceThickness, viaDiameter: this.viaDiameter, vias: [o3] };
  }
  _step() {
    this.solved = true;
  }
  visualize() {
    const e4 = { lines: [], points: [], rects: [], circles: [] };
    if (e4.rects.push({ center: { x: (this.bounds.minX + this.bounds.maxX) / 2, y: (this.bounds.minY + this.bounds.maxY) / 2 }, width: this.bounds.maxX - this.bounds.minX, height: this.bounds.maxY - this.bounds.minY, stroke: "rgba(0, 0, 0, 0.5)", fill: "rgba(240, 240, 240, 0.1)", label: "PCB Bounds" }), this.routes.length > 0)
      for (const t2 of this.routes)
        e4.points.push({ x: t2.A.x, y: t2.A.y, label: `${t2.connectionName} start (z=${t2.A.z})`, color: "orange" }), e4.points.push({ x: t2.B.x, y: t2.B.y, label: `${t2.connectionName} end (z=${t2.B.z})`, color: "orange" }), e4.lines.push({ points: [t2.A, t2.B], strokeColor: "rgba(255, 0, 0, 0.5)", label: `${t2.connectionName} direct` });
    for (let t2 = 0;t2 < this.solvedRoutes.length; t2++) {
      const n2 = this.solvedRoutes[t2], o3 = "rgba(0, 255, 0, 0.75)";
      for (let t3 = 0;t3 < n2.route.length - 1; t3++) {
        const i3 = n2.route[t3], r3 = n2.route[t3 + 1];
        e4.lines.push({ points: [i3, r3], strokeColor: o3, strokeDash: i3.z !== n2.route[0].z ? [0.2, 0.2] : undefined, strokeWidth: n2.traceThickness, label: `${n2.connectionName} z=${i3.z}` });
      }
      for (const t3 of n2.vias)
        e4.circles.push({ center: t3, radius: this.viaDiameter / 2, fill: "rgba(0, 0, 255, 0.8)", stroke: "black", label: "Solved Via" }), e4.circles.push({ center: t3, radius: this.viaDiameter / 2 + this.obstacleMargin, fill: "rgba(0, 0, 255, 0.3)", stroke: "black", label: "Via Margin" });
    }
    return e4;
  }
};
var ca = (e4, t2 = 2) => {
  const n2 = Array.from({ length: t2 }, (e5, t3) => t3);
  return e4.map((e5) => {
    const o3 = go(e5.__zLayers ?? (e5.layers ? fo(e5.layers, t2) : undefined) ?? n2, t2);
    return { ...e5, __zLayers: o3.length > 0 ? o3 : n2 };
  });
};
var la = 0.000001;
var ha = (e4) => {
  const { point: t2, obstacle: n2 } = e4, o3 = n2.width / 2 + la, i3 = n2.height / 2 + la;
  return Math.abs(t2.x - n2.center.x) <= o3 && Math.abs(t2.y - n2.center.y) <= i3;
};
var da = class e4 extends ni {
  getSolverName() {
    return "SingleTransitionThroughObstacleIntraNodeSolver";
  }
  nodeWithPortPoints;
  routes;
  obstacles;
  viaDiameter;
  traceThickness;
  connMap;
  solvedRoutes = [];
  constructor(e5) {
    if (super(), this.nodeWithPortPoints = e5.nodeWithPortPoints, this.obstacles = ca(e5.obstacles ?? [], e5.layerCount ?? 2), this.connMap = e5.connMap, this.viaDiameter = e5.viaDiameter ?? 0.3, this.traceThickness = e5.traceThickness ?? 0.15, this.routes = this.extractRoutesFromNode(), this.routes.length === 0)
      return this.failed = true, void (this.error = "Expected at least 1 route");
    if (this.routes.some((e6) => e6.A.z === undefined || e6.B.z === undefined))
      return this.failed = true, void (this.error = "Route points should have predefined z values");
    if (!this.routes.some((e6) => e6.A.z !== e6.B.z))
      return this.failed = true, void (this.error = "No route transitions through an obstacle");
    const t2 = this.routes.map((e6) => this.getContainingThroughObstacle(e6));
    if (t2.some((e6) => !e6))
      return this.failed = true, void (this.error = "No same-net multilayer obstacle contains every route");
    this.solvedRoutes.push(...this.routes.map((e6, n2) => ({ connectionName: e6.connectionName, rootConnectionName: e6.rootConnectionName, regionId: this.nodeWithPortPoints.capacityMeshNodeId, route: [{ x: e6.A.x, y: e6.A.y, z: e6.A.z, ...e6.A.z !== e6.B.z ? { toNextSegmentType: "through_obstacle", ...t2[n2].circuitJsonMetadata ? { toNextSegmentCircuitJsonMetadata: t2[n2].circuitJsonMetadata } : {} } : {} }, { x: e6.B.x, y: e6.B.y, z: e6.B.z }], traceThickness: this.traceThickness, viaDiameter: this.viaDiameter, vias: [] }))), this.solved = true;
  }
  static isApplicable(t2) {
    return new e4(t2).solved;
  }
  extractRoutesFromNode() {
    const e5 = [], t2 = new Map;
    for (const e6 of this.nodeWithPortPoints.portPoints) {
      const { connectionName: n2 } = e6;
      t2.has(n2) || t2.set(n2, []), t2.get(n2).push(e6);
    }
    for (const [n2, o3] of t2.entries())
      for (const [t3, i3] of Ws(o3))
        e5.push({ A: { ...t3 }, B: { ...i3 }, connectionName: n2, rootConnectionName: t3.rootConnectionName ?? i3.rootConnectionName });
    return e5;
  }
  getContainingThroughObstacle(e5) {
    const t2 = e5.A.z, n2 = e5.B.z;
    return t2 === undefined || n2 === undefined ? null : this.obstacles.find((o3) => {
      return !(o3.__zLayers.length < 2) && (!(!o3.__zLayers.includes(t2) || !o3.__zLayers.includes(n2)) && (!!(i3 = { obstacle: o3, connectionName: e5.connectionName, connMap: this.connMap }).obstacle.connectedTo.some((e6) => e6 === i3.connectionName || (i3.connMap?.areIdsConnected(i3.connectionName, e6) ?? false)) && (ha({ point: e5.A, obstacle: o3 }) && ha({ point: e5.B, obstacle: o3 }))));
      var i3;
    }) ?? null;
  }
  _step() {
    this.solved = true;
  }
  visualize() {
    const e5 = { lines: [], points: [], rects: [], circles: [] };
    for (const t2 of this.obstacles)
      e5.rects.push({ center: t2.center, width: t2.width, height: t2.height, fill: "rgba(128, 0, 128, 0.2)", stroke: "rgba(128, 0, 128, 0.6)", label: `through obstacle candidate
z: ${t2.__zLayers.join(",")}` });
    for (const t2 of this.solvedRoutes) {
      e5.lines.push({ points: t2.route, strokeColor: "rgba(0, 180, 0, 0.8)", strokeDash: "4, 3", strokeWidth: t2.traceThickness, label: `${t2.connectionName} through_obstacle` });
      for (const n2 of t2.route)
        e5.points.push({ x: n2.x, y: n2.y, color: "green", label: `${t2.connectionName}
z: ${n2.z}` });
    }
    return e5;
  }
};
var ua = 0.000001;
var pa = ({ value: e5, min: t2, max: n2 }) => e5 >= t2 && e5 <= n2;
var ma = ({ value: e5, target: t2, epsilon: n2 }) => Math.abs(e5 - t2) <= n2;
var ga = ({ point: e5, bounds: t2, epsilon: n2 = 0.000001 }) => {
  if (![e5.x, e5.y, t2.minX, t2.maxX, t2.minY, t2.maxY].every((e6) => (({ value: e7 }) => Number.isFinite(e7))({ value: e6 })))
    return "outside";
  if (e5.x < t2.minX - n2 || e5.x > t2.maxX + n2 || e5.y < t2.minY - n2 || e5.y > t2.maxY + n2)
    return "outside";
  const o3 = ma({ value: e5.x, target: t2.minX, epsilon: n2 }), i3 = ma({ value: e5.x, target: t2.maxX, epsilon: n2 }), r3 = ma({ value: e5.y, target: t2.minY, epsilon: n2 }), s2 = ma({ value: e5.y, target: t2.maxY, epsilon: n2 }), a3 = o3 || i3, c3 = r3 || s2;
  if (a3 && c3)
    return "on-boundary";
  const l3 = pa({ value: e5.y, min: t2.minY, max: t2.maxY }), h2 = pa({ value: e5.x, min: t2.minX, max: t2.maxX });
  return a3 && l3 || c3 && h2 ? "on-boundary" : "inside";
};
function fa(e5, t2, n2, o3, i3) {
  const r3 = { x: (e5.x + t2.x + n2.x) / 3, y: (e5.y + t2.y + n2.y) / 3 }, s2 = (e6, t3) => Math.sqrt((t3.x - e6.x) ** 2 + (t3.y - e6.y) ** 2), a3 = (r4) => {
    const a4 = s2(r4, e5), c4 = s2(r4, t2), l4 = s2(r4, n2), h3 = r4.x >= i3.minX && r4.x <= i3.maxX && r4.y >= i3.minY && r4.y <= i3.maxY;
    return a4 >= o3 && c4 >= o3 && l4 >= o3 && h3;
  };
  if (a3(r3))
    return r3;
  const c3 = (e6, t3, n3) => {
    const o4 = e6.x - t3.x, i4 = e6.y - t3.y, r4 = Math.sqrt(o4 * o4 + i4 * i4);
    return r4 < 0.0000000001 ? { x: t3.x + n3, y: t3.y } : { x: t3.x + o4 / r4 * n3, y: t3.y + i4 / r4 * n3 };
  }, l3 = (e6, t3, n3) => {
    const o4 = t3.x - e6.x, i4 = t3.y - e6.y, r4 = Math.sqrt(o4 * o4 + i4 * i4);
    if (r4 > 2 * n3 - 0.0000000001 || r4 < 0.0000000001)
      return [];
    const a4 = r4 * r4 / (2 * r4), c4 = Math.sqrt(Math.max(0, n3 * n3 - a4 * a4)), l4 = e6.x + o4 * a4 / r4, h3 = e6.y + i4 * a4 / r4, d3 = { x: l4 + c4 * i4 / r4, y: h3 - c4 * o4 / r4 }, u3 = { x: l4 - c4 * i4 / r4, y: h3 + c4 * o4 / r4 }, p4 = [], m3 = 0.000001;
    return Math.abs(s2(d3, e6) - n3) < m3 && Math.abs(s2(d3, t3) - n3) < m3 && p4.push(d3), Math.abs(s2(u3, e6) - n3) < m3 && Math.abs(s2(u3, t3) - n3) < m3 && p4.push(u3), p4;
  }, h2 = [c3(r3, e5, o3), c3(r3, t2, o3), c3(r3, n2, o3), ...l3(e5, t2, o3), ...l3(t2, n2, o3), ...l3(n2, e5, o3)], d2 = h2.filter(a3);
  if (d2.length > 0) {
    const e6 = d2.filter((e7) => !((e8) => {
      const t3 = 0.000001;
      return Math.abs(e8.x - i3.minX) < t3 || Math.abs(e8.x - i3.maxX) < t3 || Math.abs(e8.y - i3.minY) < t3 || Math.abs(e8.y - i3.maxY) < t3;
    })(e7));
    if (e6.length > 0)
      return e6.sort((e7, t3) => s2(e7, r3) - s2(t3, r3)), e6[0];
  }
  let u2 = null, p3 = 1 / 0;
  for (let e6 = i3.minX + 1;e6 < i3.maxX; e6 += 5)
    for (let t3 = i3.minY + 1;t3 < i3.maxY; t3 += 5) {
      const n3 = { x: e6, y: t3 };
      if (a3(n3)) {
        const e7 = s2(n3, r3);
        e7 < p3 && (p3 = e7, u2 = n3);
      }
    }
  if (u2 !== null)
    return u2;
  const m2 = [];
  for (let e6 = 0;e6 <= 100; e6++) {
    const t3 = e6 / 100;
    m2.push({ x: i3.minX + t3 * (i3.maxX - i3.minX), y: i3.minY }), m2.push({ x: i3.maxX, y: i3.minY + t3 * (i3.maxY - i3.minY) }), m2.push({ x: i3.maxX - t3 * (i3.maxX - i3.minX), y: i3.maxY }), m2.push({ x: i3.minX, y: i3.maxY - t3 * (i3.maxY - i3.minY) });
  }
  const g2 = m2.filter(a3);
  if (g2.length > 0)
    return g2.sort((e6, t3) => s2(e6, r3) - s2(t3, r3)), g2[0];
  let f2 = 1 / 0, _2 = { x: i3.minX, y: i3.minY };
  for (const r4 of [...h2, ...m2])
    if (r4.x >= i3.minX && r4.x <= i3.maxX && r4.y >= i3.minY && r4.y <= i3.maxY) {
      const i4 = Math.max(0, o3 - s2(r4, e5)) + Math.max(0, o3 - s2(r4, t2)) + Math.max(0, o3 - s2(r4, n2));
      i4 < f2 && (f2 = i4, _2 = r4);
    }
  return _2;
}
function _a(e5, t2, n2) {
  const o3 = ya(t2, e5, n2.center, n2.radius), i3 = ya(e5, t2, n2.center, n2.radius), r3 = ba(o3, t2), s2 = ba(e5, i3), a3 = 0.000001;
  let c3;
  if (r3 > a3 && s2 > a3) {
    c3 = { x: (o3.x + i3.x) / 2, y: (o3.y + i3.y) / 2 };
    const r4 = ba(o3, c3), s3 = ba(i3, c3);
    if (Math.abs(r4 - s3) > 0.5 * Math.min(r4, s3)) {
      const n3 = ba(e5, o3), r5 = ba(t2, i3), s4 = n3 + r5;
      if (s4 > a3) {
        const e6 = r5 / s4, t3 = n3 / s4;
        c3 = { x: o3.x * e6 + i3.x * t3, y: o3.y * e6 + i3.y * t3 };
      }
    }
    const l3 = ba(c3, n2.center);
    if (l3 < 1.05 * n2.radius) {
      const e6 = { x: (c3.x - n2.center.x) / l3, y: (c3.y - n2.center.y) / l3 };
      c3 = { x: n2.center.x + e6.x * n2.radius * 1.2, y: n2.center.y + e6.y * n2.radius * 1.2 };
    }
  } else {
    const o4 = { x: (e5.x + t2.x) / 2, y: (e5.y + t2.y) / 2 }, i4 = ba(o4, n2.center);
    if (i4 < 1.1 * n2.radius) {
      const e6 = { x: (o4.x - n2.center.x) / i4, y: (o4.y - n2.center.y) / i4 };
      c3 = { x: n2.center.x + e6.x * n2.radius * 1.2, y: n2.center.y + e6.y * n2.radius * 1.2 };
    } else
      c3 = o4;
  }
  return { B: o3, D: i3, E: c3 };
}
function ya(e5, t2, n2, o3) {
  const i3 = [n2.x - e5.x, n2.y - e5.y], r3 = Math.sqrt(i3[0] * i3[0] + i3[1] * i3[1]);
  if (r3 <= o3) {
    if (r3 < 0.00000001) {
      const i4 = [t2.x - e5.x, t2.y - e5.y], r4 = Math.sqrt(i4[0] * i4[0] + i4[1] * i4[1]);
      return r4 < 0.00000001 ? { x: n2.x + o3, y: n2.y } : { x: n2.x + i4[0] / r4 * o3, y: n2.y + i4[1] / r4 * o3 };
    }
    const s3 = [i3[0] / r3, i3[1] / r3];
    return { x: n2.x - s3[0] * o3, y: n2.y - s3[1] * o3 };
  }
  const s2 = [t2.x - e5.x, t2.y - e5.y], a3 = Math.sqrt(r3 * r3 - o3 * o3), c3 = [i3[0] / r3, i3[1] / r3], l3 = [-c3[1], c3[0]], h2 = [c3[1], -c3[0]], d2 = s2[0] * l3[0] + s2[1] * l3[1] > s2[0] * h2[0] + s2[1] * h2[1] ? l3 : h2, u2 = o3 / r3, p3 = a3 / r3, m2 = [c3[0] * p3 + d2[0] * u2, c3[1] * p3 + d2[1] * u2];
  return { x: e5.x + a3 * m2[0], y: e5.y + a3 * m2[1] };
}
function ba(e5, t2) {
  const n2 = t2.x - e5.x, o3 = t2.y - e5.y;
  return Math.sqrt(n2 * n2 + o3 * o3);
}
var xa = 0.000000001;
function va(e5, t2, n2, o3 = "cw") {
  const i3 = Ia(e5, n2), r3 = Ia(t2, n2);
  return Math.abs(r3 - i3) < xa ? { left: 0, top: 0, right: 0, bottom: 0 } : function(e6, t3, n3, o4) {
    const i4 = n3.maxX - n3.minX, r4 = n3.maxY - n3.minY;
    if (i4 < xa && r4 < xa)
      return { left: 0, top: 0, right: 0, bottom: 0 };
    const s2 = 2 * (i4 + r4);
    if (s2 < xa)
      return { left: 0, top: 0, right: 0, bottom: 0 };
    const a3 = i4 / s2 * (2 * Math.PI), c3 = (i4 + r4) / s2 * (2 * Math.PI), l3 = (i4 + i4 + r4) / s2 * (2 * Math.PI), h2 = 2 * Math.PI, d2 = [{ name: "top", start: 0, end: a3, length: i4 }, { name: "right", start: a3, end: c3, length: r4 }, { name: "bottom", start: c3, end: l3, length: i4 }, { name: "left", start: l3, end: h2, length: r4 }], u2 = { left: 0, top: 0, right: 0, bottom: 0 }, p3 = (e7, t4, n4, o5, i5) => {
      const r5 = t4 > 2 * Math.PI - xa ? 2 * Math.PI : t4;
      if (r5 <= e7 + xa)
        return 0;
      if (i5) {
        const t5 = Math.max(e7, n4), i6 = Math.min(r5, 2 * Math.PI), s3 = Math.max(0, i6 - t5), a4 = Math.max(e7, 0), c4 = Math.min(r5, o5);
        return s3 + Math.max(0, c4 - a4);
      }
      {
        const t5 = Math.max(e7, n4), i6 = Math.min(r5, o5);
        return Math.max(0, i6 - t5);
      }
    };
    for (const n4 of d2) {
      const i5 = n4.end - n4.start;
      if (i5 < xa || n4.length < xa)
        continue;
      let r5 = 0;
      if (o4 === "cw") {
        const o5 = e6 > t3 + xa;
        r5 = p3(n4.start, n4.end, e6, t3, o5);
      } else {
        const o5 = t3 > e6 + xa;
        r5 = p3(n4.start, n4.end, t3, e6, o5);
      }
      if (r5 > xa) {
        const e7 = r5 / i5;
        u2[n4.name] += Math.max(0, Number.isFinite(e7) ? e7 : 0);
      }
    }
    for (const e7 in u2)
      u2[e7] = Math.max(0, Math.min(1, u2[e7]));
    return u2;
  }(i3, r3, n2, o3);
}
function Ia(e5, t2) {
  const n2 = t2.maxX - t2.minX, o3 = t2.maxY - t2.minY;
  if (n2 < xa && o3 < xa)
    return 0;
  const i3 = 2 * (n2 + o3);
  if (i3 < xa)
    return 0;
  let r3 = 0;
  if (Math.abs(e5.y - t2.maxY) <= ua && e5.x >= t2.minX - ua && e5.x <= t2.maxX + ua)
    r3 = Math.max(0, Math.min(n2, e5.x - t2.minX));
  else if (Math.abs(e5.x - t2.maxX) <= ua && e5.y >= t2.minY - ua && e5.y <= t2.maxY + ua)
    r3 = n2 + Math.max(0, Math.min(o3, t2.maxY - e5.y));
  else if (Math.abs(e5.y - t2.minY) <= ua && e5.x >= t2.minX - ua && e5.x <= t2.maxX + ua)
    r3 = n2 + o3 + Math.max(0, Math.min(n2, t2.maxX - e5.x));
  else {
    if (!(Math.abs(e5.x - t2.minX) <= ua && e5.y >= t2.minY - ua && e5.y <= t2.maxY + ua))
      throw new Error(`Point (${e5.x}, ${e5.y}) does not lie on the boundary defined by ${JSON.stringify(t2)}`);
    r3 = n2 + o3 + n2 + Math.max(0, Math.min(o3, e5.y - t2.minY));
  }
  return r3 = Math.max(0, Math.min(i3, r3)), i3 > xa ? r3 / i3 * (2 * Math.PI) : 0;
}
function Sa(e5, t2, n2, o3) {
  return function({ angleA: e6, angleB: t3, angleC: n3 }) {
    const o4 = Math.cos(e6), i3 = Math.sin(e6), r3 = Math.cos(t3), s2 = Math.sin(t3), a3 = Math.cos(n3);
    return (r3 - o4) * (Math.sin(n3) - i3) - (s2 - i3) * (a3 - o4) < 0 ? "ccw" : "cw";
  }({ angleA: Ia(e5, o3), angleB: Ia(t2, o3), angleC: Ia(n2, o3) });
}
var Ca = class extends ni {
  getSolverName() {
    return "SingleTransitionCrossingRouteSolver";
  }
  nodeWithPortPoints;
  routes;
  viaDiameter;
  traceThickness;
  obstacleMargin;
  layerCount = 2;
  debugViaPositions;
  solvedRoutes = [];
  bounds;
  constructor(e5) {
    if (super(), this.nodeWithPortPoints = e5.nodeWithPortPoints, this.viaDiameter = e5?.viaDiameter ?? 0.3, this.traceThickness = e5?.traceThickness ?? 0.15, this.obstacleMargin = e5?.obstacleMargin ?? 0.1, this.layerCount = e5?.layerCount ?? 2, this.debugViaPositions = [], this.routes = this.extractRoutesFromNode(), this.bounds = this.calculateBounds(), this.routes.length !== 2)
      return this.failed = true, void (this.error = `Expected 2 routes, but got ${this.routes.length}`);
    const t2 = this.routes.flatMap((e6) => [e6.A, e6.B]).map((e6) => this.getPortPointBoundsPosition(e6));
    if (t2.includes("outside"))
      return this.failed = true, void (this.error = "Invalid route input: SingleTransitionCrossingRouteSolver received port point(s) outside node bounds");
    if (t2.includes("inside"))
      return void (this.failed = true);
    this.routes = this.routes.map((e6) => ({ ...e6, A: this.snapPortPointToBounds(e6.A), B: this.snapPortPointToBounds(e6.B) }));
    const [n2, o3] = this.routes, i3 = n2.A.z !== n2.B.z, r3 = o3.A.z !== o3.B.z;
    return i3 && r3 || !i3 && !r3 ? (this.failed = true, void (this.error = "Exactly one route must have a layer transition")) : undefined;
  }
  extractRoutesFromNode() {
    const e5 = [], t2 = this.nodeWithPortPoints.portPoints, n2 = new Map;
    for (const e6 of t2) {
      const { connectionName: t3 } = e6;
      n2.has(t3) || n2.set(t3, []), n2.get(t3)?.push(e6);
    }
    for (const [t3, o3] of n2.entries())
      o3.length === 2 && e5.push({ A: { ...o3[0], z: o3[0].z ?? 0 }, B: { ...o3[1], z: o3[1].z ?? 0 }, connectionName: t3 });
    return e5;
  }
  calculateBounds() {
    return { minX: this.nodeWithPortPoints.center.x - this.nodeWithPortPoints.width / 2, maxX: this.nodeWithPortPoints.center.x + this.nodeWithPortPoints.width / 2, minY: this.nodeWithPortPoints.center.y - this.nodeWithPortPoints.height / 2, maxY: this.nodeWithPortPoints.center.y + this.nodeWithPortPoints.height / 2 };
  }
  getPortPointBoundsPosition(e5) {
    return ga({ point: e5, bounds: this.bounds });
  }
  snapPortPointToBounds(e5) {
    const t2 = Me(e5.x, this.bounds.minX, this.bounds.maxX), n2 = Me(e5.y, this.bounds.minY, this.bounds.maxY);
    return [{ distance: Math.abs(e5.y - this.bounds.maxY), point: { ...e5, x: t2, y: this.bounds.maxY } }, { distance: Math.abs(e5.x - this.bounds.maxX), point: { ...e5, x: this.bounds.maxX, y: n2 } }, { distance: Math.abs(e5.y - this.bounds.minY), point: { ...e5, x: t2, y: this.bounds.minY } }, { distance: Math.abs(e5.x - this.bounds.minX), point: { ...e5, x: this.bounds.minX, y: n2 } }].reduce((e6, t3) => t3.distance < e6.distance ? t3 : e6).point;
  }
  doRoutesCross(e5, t2) {
    return he(e5.A, e5.B, t2.A, t2.B);
  }
  calculateViaPosition(e5, t2) {
    const n2 = t2.A.z, o3 = e5.A.z !== n2 ? e5.A : e5.B, i3 = 2 * this.obstacleMargin + this.viaDiameter / 2 + this.traceThickness, r3 = this.obstacleMargin + this.viaDiameter / 2, s2 = t2.A, a3 = o3, c3 = t2.B, l3 = Sa(s2, a3, c3, this.bounds), h2 = function(e6, t3, n3, o4, i4) {
      const r4 = va(e6, t3, o4, i4), s3 = va(t3, n3, o4, i4), a4 = { left: Math.min(1, r4.left + s3.left), top: Math.min(1, r4.top + s3.top), right: Math.min(1, r4.right + s3.right), bottom: Math.min(1, r4.bottom + s3.bottom) };
      for (const e7 in a4)
        Math.abs(a4[e7]) < xa && (a4[e7] = 0);
      return a4;
    }(s2, a3, c3, this.bounds, l3), d2 = { minX: this.bounds.minX + (h2.left > 0.5 ? i3 : r3), minY: this.bounds.minY + (h2.bottom > 0.5 ? i3 : r3), maxX: this.bounds.maxX - (h2.right > 0.5 ? i3 : r3), maxY: this.bounds.maxY - (h2.top > 0.5 ? i3 : r3) };
    return d2.maxY < d2.minY && (d2.minY = (d2.minY + d2.maxY) / 2, d2.maxY = d2.minY), d2.maxX < d2.minX && (d2.minX = (d2.minX + d2.maxX) / 2, d2.maxX = d2.minX), fa(s2, a3, c3, i3, d2);
  }
  createTransitionRoute(e5, t2, n2, o3) {
    const i3 = [{ x: e5.x, y: e5.y, z: e5.z ?? 0 }, { x: n2.x, y: n2.y, z: e5.z ?? 0 }, { x: n2.x, y: n2.y, z: t2.z ?? 0 }, { x: t2.x, y: t2.y, z: t2.z ?? 0 }];
    return { connectionName: o3, regionId: this.nodeWithPortPoints.capacityMeshNodeId, route: i3, traceThickness: this.traceThickness, viaDiameter: this.viaDiameter, vias: [n2] };
  }
  createFlatRoute(e5, t2, n2, o3, i3, r3) {
    o3.z, e5.z;
    const s2 = this.viaDiameter / 2 + this.traceThickness / 2 + this.obstacleMargin, a3 = ((e6, t3, n3, o4) => {
      const i4 = n3.x - e6.x, r4 = n3.y - e6.y;
      return ((e7, t4) => ({ x: (e7.x + t4.x) / 2, y: (e7.y + t4.y) / 2 }))({ x: e6.x + i4 * t3, y: e6.y + r4 * t3 }, { x: n3.x - i4 * o4, y: n3.y - r4 * o4 });
    })(n2, this.viaDiameter, o3.z !== e5.z ? o3 : i3, this.traceThickness), c3 = { center: { x: n2.x, y: n2.y }, radius: s2 }, l3 = _a(e5, a3, c3).E, h2 = _a(a3, t2, c3).E, d2 = _a(e5, l3, c3).E, u2 = _a(l3, a3, c3).E, p3 = _a(a3, h2, c3).E, m2 = _a(h2, t2, c3).E, g2 = _a(u2, p3, c3).E;
    return { connectionName: r3, regionId: this.nodeWithPortPoints.capacityMeshNodeId, route: [{ x: e5.x, y: e5.y, z: e5.z ?? 0 }, { x: d2.x, y: d2.y, z: e5.z ?? 0 }, { x: l3.x, y: l3.y, z: e5.z ?? 0 }, { x: u2.x, y: u2.y, z: e5.z ?? 0 }, { x: g2.x, y: g2.y, z: e5.z ?? 0 }, { x: p3.x, y: p3.y, z: e5.z ?? 0 }, { x: h2.x, y: h2.y, z: e5.z ?? 0 }, { x: m2.x, y: m2.y, z: e5.z ?? 0 }, { x: t2.x, y: t2.y, z: t2.z ?? 0 }], traceThickness: this.traceThickness, viaDiameter: this.viaDiameter, vias: [] };
  }
  trySolve() {
    const [e5, t2] = this.routes, n2 = e5.A.z !== e5.B.z, o3 = n2 ? e5 : t2, i3 = n2 ? t2 : e5, r3 = this.calculateViaPosition(o3, i3);
    if (!r3)
      return false;
    this.debugViaPositions.push({ via: r3 });
    const s2 = this.createTransitionRoute(o3.A, o3.B, r3, o3.connectionName), a3 = this.createFlatRoute(i3.A, i3.B, r3, o3.A, o3.B, i3.connectionName);
    return this.solvedRoutes.push(s2, a3), true;
  }
  _step() {
    if (!this.doRoutesCross(this.routes[0], this.routes[1]))
      return this.failed = true, void (this.error = "Can only solve routes that have a single transition crossing");
    this.trySolve() ? this.solved = true : (this.failed = true, this.error = "Failed to find a valid via position and route path");
  }
  visualize() {
    const e5 = { lines: [], points: [], rects: [], circles: [] };
    e5.rects.push({ center: { x: (this.bounds.minX + this.bounds.maxX) / 2, y: (this.bounds.minY + this.bounds.maxY) / 2 }, width: this.bounds.maxX - this.bounds.minX, height: this.bounds.maxY - this.bounds.minY, stroke: "rgba(0, 0, 0, 0.5)", fill: "rgba(240, 240, 240, 0.1)", label: "PCB Bounds" });
    for (const t2 of this.routes)
      e5.points.push({ x: t2.A.x, y: t2.A.y, label: `${t2.connectionName} start (z=${t2.A.z})`, color: "orange" }), e5.points.push({ x: t2.B.x, y: t2.B.y, label: `${t2.connectionName} end (z=${t2.B.z})`, color: "orange" }), e5.lines.push({ points: [t2.A, t2.B], strokeColor: "rgba(255, 0, 0, 0.5)", label: `${t2.connectionName} direct` });
    for (let t2 = 0;t2 < this.debugViaPositions.length; t2++) {
      const { via: n2 } = this.debugViaPositions[t2];
      e5.circles.push({ center: n2, radius: this.viaDiameter / 2, fill: "rgba(255, 165, 0, 0.7)", stroke: "rgba(0, 0, 0, 0.5)", label: `Computed Via (attempt ${t2 + 1})` });
      const o3 = this.viaDiameter / 2 + this.obstacleMargin;
      e5.circles.push({ center: n2, radius: o3, stroke: "rgba(255, 165, 0, 0.7)", fill: "rgba(0, 0, 0, 0)", label: "Safety Margin" });
    }
    for (let t2 = 0;t2 < this.solvedRoutes.length; t2++) {
      const n2 = this.solvedRoutes[t2], o3 = t2 % 2 == 0 ? "rgba(0, 255, 0, 0.75)" : "rgba(255, 0, 255, 0.75)";
      for (let t3 = 0;t3 < n2.route.length - 1; t3++) {
        const i3 = n2.route[t3], r3 = n2.route[t3 + 1];
        e5.lines.push({ points: [i3, r3], strokeColor: o3, strokeDash: i3.z !== n2.route[0].z ? [0.2, 0.2] : undefined, strokeWidth: n2.traceThickness, label: `${n2.connectionName} z=${i3.z}` });
      }
      for (const t3 of n2.vias)
        e5.circles.push({ center: t3, radius: this.viaDiameter / 2, fill: "rgba(0, 0, 255, 0.8)", stroke: "black", label: "Solved Via" }), e5.circles.push({ center: t3, radius: this.viaDiameter / 2 + this.obstacleMargin, fill: "rgba(0, 0, 255, 0.3)", stroke: "black", label: "Via Margin" });
    }
    return e5;
  }
  getSolvedRoutes() {
    return this.solvedRoutes;
  }
};
function Pa({ A: e5, B: t2, C: n2, D: o3, E: i3, F: r3, radius: s2, margin: a3, subdivisions: c3 = 0 }) {
  const l3 = (e6, t3) => ({ x: (e6.x + t3.x) / 2, y: (e6.y + t3.y) / 2 }), h2 = (e6, t3, n3) => {
    const o4 = t3.x - e6.x, i4 = t3.y - e6.y, r4 = Math.sqrt(o4 * o4 + i4 * i4), s3 = o4 / r4, a4 = i4 / r4, c4 = -a4, l4 = s3;
    return { midpoint: { x: (e6.x + t3.x) / 2, y: (e6.y + t3.y) / 2 }, A_Opp: { x: e6.x - s3 * n3, y: e6.y - a4 * n3 }, A_Right: { x: e6.x + c4 * n3, y: e6.y + l4 * n3 }, A_Left: { x: e6.x - c4 * n3, y: e6.y - l4 * n3 }, B_Opp: { x: t3.x + s3 * n3, y: t3.y + a4 * n3 }, B_Right: { x: t3.x + c4 * n3, y: t3.y + l4 * n3 }, B_Left: { x: t3.x - c4 * n3, y: t3.y - l4 * n3 } };
  }, d2 = (e6, t3) => {
    const n3 = me(e6, t3.start), o4 = me(e6, t3.end), i4 = me(t3.start, t3.end);
    return Math.abs(n3 + o4 - i4) < 0.0001;
  }, u2 = (e6, t3) => {
    const { start: n3, end: o4 } = e6, { start: i4, end: r4 } = t3;
    if (d2(n3, t3) || d2(o4, t3) || d2(i4, e6) || d2(r4, e6))
      return true;
    const s3 = o4.x - n3.x, a4 = o4.y - n3.y, c4 = r4.x - i4.x, l4 = r4.y - i4.y, h3 = s3 * l4 - a4 * c4;
    if (Math.abs(h3) < 0.0001)
      return false;
    const u3 = i4.x - n3.x, p4 = i4.y - n3.y, m3 = (u3 * l4 - p4 * c4) / h3, g3 = (u3 * a4 - p4 * s3) / h3;
    return m3 > 0 && m3 < 1 && g3 > 0 && g3 < 1;
  }, p3 = (e6, t3) => {
    const n3 = [];
    for (let t4 = 0;t4 < e6.length - 1; t4++)
      n3.push({ start: e6[t4], end: e6[t4 + 1] });
    const o4 = [];
    for (let e7 = 0;e7 < t3.length - 1; e7++)
      o4.push({ start: t3[e7], end: t3[e7 + 1] });
    for (const e7 of n3)
      for (const t4 of o4)
        if (u2(e7, t4))
          return true;
    return false;
  }, m2 = (e6) => {
    let t3 = 0;
    for (let n3 = 1;n3 < e6.length; n3++) {
      const o4 = e6[n3].x - e6[n3 - 1].x, i4 = e6[n3].y - e6[n3 - 1].y;
      t3 += Math.sqrt(o4 * o4 + i4 * i4);
    }
    return t3;
  }, g2 = (e6, t3) => {
    const { start: n3, end: o4 } = e6, i4 = o4.x - n3.x, r4 = o4.y - n3.y, s3 = i4 * i4 + r4 * r4;
    if (s3 === 0)
      return { ...n3, t: 0 };
    const a4 = Math.max(0, Math.min(1, ((t3.x - n3.x) * i4 + (t3.y - n3.y) * r4) / s3));
    return { x: n3.x + a4 * i4, y: n3.y + a4 * r4, t: a4 };
  }, f2 = (t3, n3, o4) => {
    const i4 = g2(t3, n3);
    if (me(i4, n3) >= o4)
      return i4;
    const r4 = i4.x - n3.x, s3 = i4.y - n3.y, a4 = Math.sqrt(r4 * r4 + s3 * s3);
    if (a4 === 0) {
      const r5 = t3.end.x - t3.start.x, s4 = t3.end.y - t3.start.y, a5 = Math.sqrt(r5 * r5 + s4 * s4);
      return { x: n3.x + o4 * r5 / a5, y: n3.y + o4 * s4 / a5, t: i4.t, isSpecial: true, specialType: n3 === e5 ? "A" : "B" };
    }
    return { x: n3.x + o4 * r4 / a4, y: n3.y + o4 * s3 / a4, t: i4.t, isSpecial: true, specialType: n3 === e5 ? "A" : "B" };
  }, _2 = h2(e5, t2, s2), y2 = h2(e5, t2, s2 + a3), b2 = (e6, t3, n3, o4, i4) => {
    const r4 = e6.points;
    if (r4.length < 2)
      return r4;
    const a4 = n3 + o4, c4 = [r4[0]];
    for (let e7 = 0;e7 < r4.length - 1; e7++) {
      const n4 = { start: r4[e7], end: r4[e7 + 1] };
      if (pe(t3, n4.start, n4.end) < a4) {
        const e8 = g2(n4, t3), o5 = e8.x - t3.x, i5 = e8.y - t3.y, r5 = Math.sqrt(o5 * o5 + i5 * i5);
        let l4 = null;
        if (r5 > 0.000001)
          l4 = { x: t3.x + a4 * o5 / r5, y: t3.y + a4 * i5 / r5 };
        else {
          const e9 = n4.end.x - n4.start.x, o6 = n4.end.y - n4.start.y, i6 = Math.sqrt(e9 * e9 + o6 * o6);
          i6 > 0.000001 && (l4 = { x: t3.x + a4 * e9 / i6, y: t3.y + a4 * o6 / i6 });
        }
        l4 && me(n4.start, l4) > s2 / 10 && c4.push(l4);
      }
      me(c4[c4.length - 1], n4.end) > s2 / 10 && c4.push(n4.end);
    }
    if (c4.length > 1) {
      const e7 = [c4[0]];
      for (let t4 = 1;t4 < c4.length; t4++)
        me(e7[e7.length - 1], c4[t4]) > s2 / 10 && e7.push(c4[t4]);
      return e7;
    }
    return c4;
  }, x2 = (() => {
    const e6 = [[n2, _2.B_Left, _2.B_Opp, _2.B_Right, l3(_2.midpoint, l3(_2.B_Right, _2.A_Right)), l3(_2.midpoint, l3(_2.A_Left, _2.B_Left)), _2.A_Left, _2.A_Opp, _2.A_Right, o3], [n2, _2.B_Right, _2.B_Opp, _2.B_Left, l3(_2.midpoint, l3(_2.A_Left, _2.B_Left)), l3(_2.midpoint, l3(_2.A_Right, _2.B_Right)), _2.A_Right, _2.A_Opp, _2.A_Left, o3], [o3, _2.B_Left, _2.B_Opp, _2.B_Right, l3(_2.midpoint, l3(_2.A_Right, _2.B_Right)), l3(_2.midpoint, l3(_2.A_Left, _2.B_Left)), _2.A_Left, _2.A_Opp, _2.A_Right, n2], [o3, _2.B_Right, _2.B_Opp, _2.B_Left, l3(_2.midpoint, l3(_2.A_Left, _2.B_Left)), l3(_2.midpoint, l3(_2.A_Right, _2.B_Right)), _2.A_Right, _2.A_Opp, _2.A_Left, n2]], t3 = [];
    for (let n3 = 0;n3 < e6.length; n3++) {
      const o4 = e6[n3], i5 = { start: o4[0], end: o4[1] }, r5 = { start: o4[o4.length - 2], end: o4[o4.length - 1] }, s4 = { start: o4[3], end: o4[4] };
      u2(i5, r5) || u2(i5, s4) || u2(r5, s4) || t3.push({ index: n3 + 1, path: o4, length: m2(o4) });
    }
    if (t3.length === 0)
      return { index: 0, path: [] };
    const i4 = t3.sort((e7, t4) => e7.length - t4.length)[0], r4 = [...i4.path], s3 = r4[0], a4 = me(s3, r4[2]), c4 = me(s3, r4[3]), h3 = a4 < c4 ? 2 : 3;
    (a4 < me(s3, r4[1]) || c4 < me(s3, r4[1])) && r4.splice(1, h3 - 1);
    const d3 = r4[r4.length - 1], p4 = me(d3, r4[r4.length - 3]), g3 = me(d3, r4[r4.length - 4]), f3 = p4 < g3 ? r4.length - 3 : r4.length - 4;
    return (p4 < me(d3, r4[r4.length - 2]) || g3 < me(d3, r4[r4.length - 2])) && r4.splice(f3 + 1, r4.length - f3 - 2), { index: i4.index, path: r4, startsAt: r4[0] === n2 ? "C" : "D", goesTo: r4[r4.length - 1] === n2 ? "C" : "D" };
  })(), v2 = c3 > 0 ? ((n3, o4) => {
    if (n3.length < 2)
      return n3;
    const i4 = [n3[0]];
    for (let r4 = 0;r4 < n3.length - 1; r4++) {
      const a4 = { start: n3[r4], end: n3[r4 + 1] }, c4 = { x: (a4.start.x + a4.end.x) / 2, y: (a4.start.y + a4.end.y) / 2 }, l4 = me(c4, e5), h3 = me(c4, t2);
      if ((l4 <= s2 || h3 <= s2) && Math.abs(l4 - h3) > 0.0001) {
        const n4 = g2(a4, e5), r5 = g2(a4, t2), c5 = me(n4, e5), l5 = me(r5, t2) < s2, h4 = c5 < s2 ? f2(a4, e5, s2) : null, d3 = l5 ? f2(a4, t2, s2) : null;
        let u3 = [];
        if (me(a4.start, a4.end) > s2 / 2 && o4 > 0)
          for (let n5 = 1;n5 <= o4; n5++) {
            const i5 = n5 / (o4 + 1), r6 = { x: a4.start.x + i5 * (a4.end.x - a4.start.x), y: a4.start.y + i5 * (a4.end.y - a4.start.y), t: i5, isSpecial: false }, c6 = me(r6, e5), l6 = me(r6, t2);
            c6 < s2 || l6 < s2 || (h4 && Math.abs(r6.t - h4.t) < 0.1 || d3 && Math.abs(r6.t - d3.t) < 0.1 || u3.push(r6));
          }
        if (h4 && u3.push(h4), d3 && u3.push(d3), u3.sort((e6, t3) => e6.t - t3.t), u3.length > 1) {
          const e6 = [u3[0]];
          for (let t3 = 1;t3 < u3.length; t3++) {
            const n5 = e6[e6.length - 1], o5 = u3[t3];
            me(n5, o5) > s2 / 10 && e6.push(o5);
          }
          u3 = e6;
        }
        u3.forEach((e6) => i4.push(e6));
      }
      i4.push(n3[r4 + 1]);
    }
    if (i4.length > 1) {
      const e6 = [i4[0]];
      for (let t3 = 1;t3 < i4.length; t3++) {
        const n4 = e6[e6.length - 1], o5 = i4[t3];
        me(n4, o5) > s2 / 10 && e6.push(o5);
      }
      return e6;
    }
    return i4;
  })(x2.path, c3) : x2.path;
  let I2 = (() => {
    if (x2.path.length === 0)
      return null;
    const n3 = (() => {
      const n4 = l3(_2.A_Right, _2.B_Right), o5 = l3(_2.B_Left, _2.A_Left);
      return [{ startsAt: "E", goesTo: "B", points: [i3, t2] }, { startsAt: "E", goesTo: "A", points: [i3, e5] }, { startsAt: "F", goesTo: "B", points: [r3, t2] }, { startsAt: "F", goesTo: "A", points: [r3, e5] }, { startsAt: "E", goesTo: "B", points: [i3, n4, t2] }, { startsAt: "E", goesTo: "A", points: [i3, n4, e5] }, { startsAt: "F", goesTo: "B", points: [r3, n4, t2] }, { startsAt: "F", goesTo: "A", points: [r3, n4, e5] }, { startsAt: "E", goesTo: "B", points: [i3, o5, t2] }, { startsAt: "E", goesTo: "A", points: [i3, o5, e5] }, { startsAt: "F", goesTo: "B", points: [r3, o5, t2] }, { startsAt: "F", goesTo: "A", points: [r3, o5, e5] }, { startsAt: "E", goesTo: "B", points: [i3, y2.A_Right, n4, t2] }, { startsAt: "F", goesTo: "B", points: [r3, y2.B_Right, n4, t2] }, { startsAt: "E", goesTo: "A", points: [i3, y2.B_Left, o5, e5] }, { startsAt: "F", goesTo: "A", points: [r3, y2.A_Left, o5, e5] }, { startsAt: "E", goesTo: "B", points: [i3, y2.A_Left, o5, t2] }, { startsAt: "E", goesTo: "A", points: [i3, y2.B_Right, n4, e5] }, { startsAt: "E", goesTo: "B", points: [i3, y2.A_Opp, y2.A_Right, n4, t2] }, { startsAt: "E", goesTo: "A", points: [i3, y2.B_Opp, y2.B_Left, o5, e5] }, { startsAt: "F", goesTo: "B", points: [r3, y2.A_Opp, y2.A_Left, o5, t2] }, { startsAt: "F", goesTo: "A", points: [r3, y2.B_Opp, y2.B_Right, n4, e5] }, { startsAt: "F", goesTo: "A", points: [r3, y2.B_Opp, y2.B_Left, o5, e5] }, { startsAt: "E", goesTo: "B", points: [i3, y2.A_Opp, y2.A_Left, o5, t2] }, { startsAt: "E", goesTo: "A", points: [i3, y2.B_Opp, y2.B_Right, n4, e5] }, { startsAt: "E", goesTo: "B", points: [i3, y2.A_Left, y2.A_Opp, y2.A_Right, n4, t2] }, { startsAt: "E", goesTo: "A", points: [i3, y2.B_Right, y2.B_Opp, y2.B_Left, o5, e5] }, { startsAt: "F", goesTo: "B", points: [r3, y2.A_Right, y2.A_Opp, y2.A_Left, o5, t2] }, { startsAt: "F", goesTo: "A", points: [r3, y2.B_Left, y2.B_Opp, y2.B_Right, n4, e5] }, { startsAt: "F", goesTo: "A", points: [r3, y2.B_Right, y2.B_Opp, y2.B_Left, o5, e5] }, { startsAt: "E", goesTo: "B", points: [i3, y2.A_Right, y2.A_Opp, y2.A_Left, o5, t2] }, { startsAt: "E", goesTo: "A", points: [i3, y2.B_Left, y2.B_Opp, y2.B_Right, n4, e5] }].map((e6, t3) => ({ ...e6, index: t3 }));
    })(), o4 = n3.filter((e6) => e6.startsAt === "E"), s3 = n3.filter((e6) => e6.startsAt === "F"), a4 = [], c4 = [];
    for (const e6 of o4)
      if (!p3(e6.points, x2.path)) {
        a4.push(e6);
        break;
      }
    for (const e6 of s3)
      if (!p3(e6.points, x2.path)) {
        c4.push(e6);
        break;
      }
    return a4.length === 0 || c4.length === 0 ? null : { line1: a4[0], line2: c4[0] };
  })();
  if (I2) {
    const n3 = I2.line1.goesTo === "A" ? t2 : e5, o4 = I2.line2.goesTo === "A" ? t2 : e5, i4 = b2(I2.line1, n3, s2, a3), r4 = b2(I2.line2, o4, s2, a3);
    I2 = { line1: { ...I2.line1, points: i4 }, line2: { ...I2.line2, points: r4 } };
  }
  return { jPair: I2, optimalPath: { startsAt: x2.startsAt, goesTo: x2.goesTo, points: v2 } };
}
var Ma = class extends ni {
  getSolverName() {
    return "TwoCrossingRoutesHighDensitySolver";
  }
  nodeWithPortPoints;
  routes;
  viaDiameter;
  traceThickness;
  obstacleMargin;
  layerCount = 2;
  debugViaPositions;
  escapeLayer = 1;
  solvedRoutes = [];
  bounds;
  constructor(e5) {
    if (super(), this.nodeWithPortPoints = e5.nodeWithPortPoints, this.viaDiameter = e5?.viaDiameter ?? 0.3, this.traceThickness = e5?.traceThickness ?? 0.15, this.obstacleMargin = e5?.obstacleMargin ?? 0.1, this.layerCount = e5?.layerCount ?? 2, this.debugViaPositions = [], this.routes = this.extractRoutesFromNode(), this.bounds = this.calculateBounds(), this.routes.length !== 2)
      return this.failed = true, void (this.error = `Expected 2 routes, but got ${this.routes.length}`);
    const [t2, n2] = this.routes;
    if (!(t2.startPort.z === t2.endPort.z))
      return this.failed = true, void (this.error = "Route A must start and end on the same layer");
    if (!(n2.startPort.z === n2.endPort.z))
      return this.failed = true, void (this.error = "Route B must start and end on the same layer");
    if (!(t2.startPort.z === n2.startPort.z))
      return this.failed = true, void (this.error = "Both routes must be on the same layer");
    t2.startPort.z === 0 ? this.escapeLayer = 1 : this.escapeLayer = 0;
  }
  extractRoutesFromNode() {
    const e5 = [], t2 = this.nodeWithPortPoints.portPoints, n2 = new Map;
    for (const e6 of t2) {
      const { connectionName: t3 } = e6;
      n2.has(t3) || n2.set(t3, []), n2.get(t3)?.push(e6);
    }
    for (const [t3, o3] of n2.entries())
      o3.length === 2 && e5.push({ startPort: { ...o3[0], z: o3[0].z ?? 0 }, endPort: { ...o3[1], z: o3[1].z ?? 0 }, connectionName: t3 });
    return e5;
  }
  calculateBounds() {
    return { minX: this.nodeWithPortPoints.center.x - this.nodeWithPortPoints.width / 2, maxX: this.nodeWithPortPoints.center.x + this.nodeWithPortPoints.width / 2, minY: this.nodeWithPortPoints.center.y - this.nodeWithPortPoints.height / 2, maxY: this.nodeWithPortPoints.center.y + this.nodeWithPortPoints.height / 2 };
  }
  doRoutesCross(e5, t2) {
    return he(e5.startPort, e5.endPort, t2.startPort, t2.endPort);
  }
  calculateViaPositions(e5, t2) {
    const n2 = this.bounds.maxX - this.bounds.minX, o3 = this.bounds.maxY - this.bounds.minY, i3 = this.bounds.minX, r3 = this.bounds.minY, s2 = { width: n2 - 2 * this.obstacleMargin - this.viaDiameter, height: o3 - 2 * this.obstacleMargin - this.viaDiameter, x: i3 + this.obstacleMargin + this.viaDiameter / 2, y: r3 + this.obstacleMargin + this.viaDiameter / 2 }, a3 = this.viaDiameter + this.obstacleMargin, c3 = t2.startPort, l3 = t2.endPort, h2 = [{ x: s2.x, y: s2.y }, { x: s2.x + s2.width, y: s2.y }, { x: s2.x + s2.width, y: s2.y + s2.height }, { x: s2.x, y: s2.y + s2.height }], d2 = (e6, t3) => me(e6, t3), u2 = [];
    h2.forEach((e6, t3) => {
      d2(e6, c3) >= a3 && d2(e6, l3) >= a3 && u2.push({ ...e6, type: "corner", index: t3 });
    });
    const p3 = [{ p1: h2[0], p2: h2[1] }, { p1: h2[1], p2: h2[2] }, { p1: h2[2], p2: h2[3] }, { p1: h2[3], p2: h2[0] }];
    if ([c3, l3].forEach((e6, t3) => {
      p3.forEach((n3, o4) => {
        ((e7, t4) => {
          const { x: n4, y: o5, r: i4 } = e7, r4 = t4.p1.x, s3 = t4.p1.y, a4 = t4.p2.x, c4 = t4.p2.y;
          if (Math.abs(a4 - r4) < 0.001) {
            const e8 = r4, t5 = i4 * i4 - (e8 - n4) ** 2;
            if (t5 < 0)
              return [];
            if (Math.abs(t5) < 0.001) {
              const t6 = o5;
              return t6 >= Math.min(s3, c4) && t6 <= Math.max(s3, c4) ? [{ x: e8, y: t6 }] : [];
            }
            const a5 = o5 + Math.sqrt(t5), l5 = o5 - Math.sqrt(t5), h4 = [];
            return a5 >= Math.min(s3, c4) && a5 <= Math.max(s3, c4) && h4.push({ x: e8, y: a5 }), l5 >= Math.min(s3, c4) && l5 <= Math.max(s3, c4) && h4.push({ x: e8, y: l5 }), h4;
          }
          const l4 = (c4 - s3) / (a4 - r4), h3 = s3 - l4 * r4, d3 = 1 + l4 * l4, u3 = 2 * (l4 * h3 - l4 * o5 - n4), p4 = u3 * u3 - 4 * d3 * (n4 * n4 + (h3 - o5) * (h3 - o5) - i4 * i4);
          if (p4 < 0)
            return [];
          if (Math.abs(p4) < 0.001) {
            const e8 = -u3 / (2 * d3), t5 = l4 * e8 + h3;
            return e8 >= Math.min(r4, a4) && e8 <= Math.max(r4, a4) && t5 >= Math.min(s3, c4) && t5 <= Math.max(s3, c4) ? [{ x: e8, y: t5 }] : [];
          }
          const m3 = (-u3 + Math.sqrt(p4)) / (2 * d3), g3 = (-u3 - Math.sqrt(p4)) / (2 * d3), f3 = l4 * m3 + h3, _3 = l4 * g3 + h3, y3 = [];
          return m3 >= Math.min(r4, a4) && m3 <= Math.max(r4, a4) && f3 >= Math.min(s3, c4) && f3 <= Math.max(s3, c4) && y3.push({ x: m3, y: f3 }), g3 >= Math.min(r4, a4) && g3 <= Math.max(r4, a4) && _3 >= Math.min(s3, c4) && _3 <= Math.max(s3, c4) && y3.push({ x: g3, y: _3 }), y3;
        })({ ...e6, r: a3 }, n3).forEach((e7) => {
          d2(e7, t3 === 0 ? l3 : c3) >= a3 && u2.push({ ...e7, type: "intersection", circle: t3, edge: o4 });
        });
      });
    }), u2.length < 2) {
      const e6 = 0.8 * a3;
      if (h2.forEach((t3, n3) => {
        d2(t3, c3) >= e6 && d2(t3, l3) >= e6 && !u2.some((e7) => e7.x === t3.x && e7.y === t3.y) && u2.push({ ...t3, type: "relaxed_corner", index: n3 });
      }), u2.length < 2) {
        const e7 = [...h2].sort((e8, t3) => {
          const n3 = Math.min(d2(e8, c3), d2(e8, l3));
          return Math.min(d2(t3, c3), d2(t3, l3)) - n3;
        });
        for (const t3 of e7)
          if (!u2.some((e8) => e8.x === t3.x && e8.y === t3.y) && (u2.push({ ...t3, type: "forced_corner" }), u2.length >= 2))
            break;
      }
    }
    if (u2.length < 2)
      return null;
    let m2 = 0, g2 = [u2[0], u2[u2.length > 1 ? 1 : 0]];
    for (let e6 = 0;e6 < u2.length; e6++)
      for (let t3 = e6 + 1;t3 < u2.length; t3++) {
        const n3 = d2(u2[e6], u2[t3]);
        n3 > m2 && (m2 = n3, g2 = [u2[e6], u2[t3]]);
      }
    let f2 = { x: g2[0].x, y: g2[0].y }, _2 = { x: g2[1].x, y: g2[1].y };
    const y2 = me(f2, e5.startPort);
    return me(_2, e5.startPort) < y2 && ([f2, _2] = [_2, f2]), { via1: f2, via2: _2 };
  }
  trySolveAOverB(e5, t2, n2 = false) {
    const o3 = n2 ? this.calculateViaPositions(e5, t2) : this.calculateViaPositions(t2, e5);
    if (!o3)
      return false;
    this.debugViaPositions.push(o3);
    const { via1: i3, via2: r3 } = this.pushViasFromEndpoints(this.moveViasAsCloseAsPossible(o3));
    this.debugViaPositions.push({ via1: i3, via2: r3 });
    const { jPair: s2, optimalPath: a3 } = Pa({ A: i3, B: r3, C: e5.startPort, D: e5.endPort, E: t2.startPort, F: t2.endPort, radius: this.viaDiameter / 2 + this.obstacleMargin + this.traceThickness / 2 * 1.5, margin: 2 * this.obstacleMargin + this.traceThickness / 2 * 1.5, subdivisions: 1 });
    if (!s2)
      return false;
    const c3 = { connectionName: e5.connectionName, regionId: this.nodeWithPortPoints.capacityMeshNodeId, route: a3.points.map((t3) => ({ x: t3.x, y: t3.y, z: e5.startPort.z ?? 0 })), traceThickness: this.traceThickness, viaDiameter: this.viaDiameter, vias: [] };
    s2.line2.points.reverse();
    const l3 = { connectionName: t2.connectionName, regionId: this.nodeWithPortPoints.capacityMeshNodeId, route: [...s2.line1.points.map((e6) => ({ x: e6.x, y: e6.y, z: t2.startPort.z ?? 0 })), { ...s2.line1.points[s2.line1.points.length - 1], z: this.escapeLayer }, { ...s2.line2.points[0], z: this.escapeLayer }, ...s2.line2.points.map((e6) => ({ x: e6.x, y: e6.y, z: t2.startPort.z ?? 0 }))], traceThickness: this.traceThickness, viaDiameter: this.viaDiameter, vias: [i3, r3] };
    return this.solvedRoutes.push(c3, l3), true;
  }
  pushViasFromEndpoints(e5) {
    const t2 = { ...e5.via1 }, n2 = { ...e5.via2 }, o3 = [this.routes[0].startPort, this.routes[0].endPort, this.routes[1].startPort, this.routes[1].endPort], i3 = this.getMinDistanceBetweenViaCenters(), r3 = this.viaDiameter / 2 + 2 * this.traceThickness + 2 * this.obstacleMargin;
    for (let e6 = 0;e6 < 10; e6++) {
      let s3 = false, a3 = false;
      const c3 = 0.9 ** e6;
      for (const e7 of o3) {
        const o4 = me(t2, e7);
        if (o4 < r3) {
          const n3 = (r3 - o4) * c3, i5 = t2.x - e7.x, a4 = t2.y - e7.y, l4 = Math.sqrt(i5 * i5 + a4 * a4);
          l4 > 0.000001 && (t2.x += i5 / l4 * n3, t2.y += a4 / l4 * n3, s3 = true);
        }
        const i4 = me(n2, e7);
        if (i4 < r3) {
          const t3 = (r3 - i4) * c3, o5 = n2.x - e7.x, s4 = n2.y - e7.y, l4 = Math.sqrt(o5 * o5 + s4 * s4);
          l4 > 0.000001 && (n2.x += o5 / l4 * t3, n2.y += s4 / l4 * t3, a3 = true);
        }
      }
      const l3 = me(t2, n2);
      if (l3 < i3) {
        const e7 = (i3 - l3) / 2, o4 = n2.x - t2.x, r4 = n2.y - t2.y, c4 = Math.sqrt(o4 * o4 + r4 * r4);
        c4 > 0.000001 ? (t2.x -= o4 / c4 * e7, t2.y -= r4 / c4 * e7, n2.x += o4 / c4 * e7, n2.y += r4 / c4 * e7, s3 = true, a3 = true) : (t2.x -= e7, n2.x += e7, s3 = true, a3 = true);
      }
      if (!s3 && !a3)
        break;
    }
    const s2 = me(t2, n2);
    if (s2 < i3) {
      const e6 = (i3 - s2) / 2, o4 = n2.x - t2.x, r4 = n2.y - t2.y, a3 = Math.sqrt(o4 * o4 + r4 * r4);
      a3 > 0.000001 ? (t2.x -= o4 / a3 * e6, t2.y -= r4 / a3 * e6, n2.x += o4 / a3 * e6, n2.y += r4 / a3 * e6) : (t2.x -= e6, n2.x += e6);
    }
    return { via1: t2, via2: n2 };
  }
  getMinDistanceBetweenViaCenters() {
    return this.viaDiameter + this.traceThickness + 2 * this.obstacleMargin;
  }
  moveViasAsCloseAsPossible(e5) {
    const { via1: t2, via2: n2 } = e5, o3 = this.getMinDistanceBetweenViaCenters(), i3 = me(t2, n2);
    if (i3 <= o3)
      return e5;
    const r3 = n2.x - t2.x, s2 = n2.y - t2.y, a3 = Math.sqrt(r3 * r3 + s2 * s2), c3 = r3 / a3, l3 = s2 / a3, h2 = (t2.x, n2.x, t2.y, n2.y, (i3 - o3) / 2);
    return { via1: { x: t2.x + c3 * h2, y: t2.y + l3 * h2 }, via2: { x: n2.x - c3 * h2, y: n2.y - l3 * h2 } };
  }
  handleRoutesDontCross() {
    const [e5, t2] = this.routes, n2 = { connectionName: e5.connectionName, regionId: this.nodeWithPortPoints.capacityMeshNodeId, route: [{ x: e5.startPort.x, y: e5.startPort.y, z: e5.startPort.z ?? 0 }, { x: e5.endPort.x, y: e5.endPort.y, z: e5.endPort.z ?? 0 }], traceThickness: this.traceThickness, viaDiameter: this.viaDiameter, vias: [] }, o3 = { connectionName: t2.connectionName, regionId: this.nodeWithPortPoints.capacityMeshNodeId, route: [{ x: t2.startPort.x, y: t2.startPort.y, z: t2.startPort.z ?? 0 }, { x: t2.endPort.x, y: t2.endPort.y, z: t2.endPort.z ?? 0 }], traceThickness: this.traceThickness, viaDiameter: this.viaDiameter, vias: [] };
    this.solvedRoutes.push(n2, o3), this.solved = true;
  }
  _step() {
    if (this.routes.length !== 2)
      return void (this.failed = true);
    const [e5, t2] = this.routes;
    this.doRoutesCross(e5, t2) ? this.trySolveAOverB(e5, t2) || this.trySolveAOverB(t2, e5) || this.trySolveAOverB(e5, t2, true) || this.trySolveAOverB(t2, e5, true) ? this.solved = true : (this.failed = true, this.error = "All crossover strategies failed") : this.handleRoutesDontCross();
  }
  visualize() {
    const e5 = { lines: [], points: [], rects: [], circles: [] };
    e5.rects.push({ center: { x: (this.bounds.minX + this.bounds.maxX) / 2, y: (this.bounds.minY + this.bounds.maxY) / 2 }, width: this.bounds.maxX - this.bounds.minX, height: this.bounds.maxY - this.bounds.minY, stroke: "rgba(0, 0, 0, 0.5)", fill: "rgba(240, 240, 240, 0.1)" });
    for (const [t2, n2] of [["Route A", this.routes[0]], ["Route B", this.routes[1]]])
      e5.points.push({ x: n2.startPort.x, y: n2.startPort.y, label: `${t2}
${n2.connectionName} start`, color: "orange" }), e5.points.push({ x: n2.endPort.x, y: n2.endPort.y, label: `${t2}
${n2.connectionName} end`, color: "orange" }), e5.lines.push({ points: [n2.startPort, n2.endPort], strokeColor: "rgba(255, 0, 0, 0.5)", label: `${t2}
${n2.connectionName} direct` });
    for (let t2 = 0;t2 < this.debugViaPositions.length; t2++) {
      const { via1: n2, via2: o3 } = this.debugViaPositions[t2], i3 = ["rgba(255, 165, 0, 0.3)", "rgba(128, 0, 128, 0.3)"], r3 = i3[t2 % i3.length];
      e5.circles.push({ center: n2, radius: this.viaDiameter / 2, fill: r3, stroke: "rgba(0, 0, 0, 0.3)", label: `Computed Via A (attempt ${t2 + 1})` }), e5.circles.push({ center: o3, radius: this.viaDiameter / 2, fill: r3, stroke: "rgba(0, 0, 0, 0.3)", label: `Computed Via B (attempt ${t2 + 1})` });
      const s2 = this.viaDiameter / 2 + this.obstacleMargin;
      e5.circles.push({ center: n2, radius: s2, stroke: r3, fill: "rgba(0, 0, 0, 0)", label: `Debug Via 1 Safety Margin (attempt ${t2 + 1})` }), e5.circles.push({ center: o3, radius: s2, stroke: r3, fill: "rgba(0, 0, 0, 0)", label: `Debug Via 2 Safety Margin (attempt ${t2 + 1})` }), e5.lines.push({ points: [this.routes[t2 % 2].startPort, n2, o3, this.routes[t2 % 2].endPort], strokeColor: `${r3.substring(0, r3.lastIndexOf(","))}, 0.3)`, strokeDash: [5, 5], label: `Potential Route (attempt ${t2 + 1})` });
    }
    for (let t2 = 0;t2 < this.solvedRoutes.length; t2++) {
      const n2 = this.solvedRoutes[t2], o3 = t2 % 2 == 0 ? "rgba(0, 255, 0, 0.75)" : "rgba(255, 0, 255, 0.75)";
      for (let t3 = 0;t3 < n2.route.length - 1; t3++) {
        const i3 = n2.route[t3], r3 = n2.route[t3 + 1];
        e5.lines.push({ points: [i3, r3], strokeColor: o3, strokeDash: i3.z === 1 ? [0.2, 0.2] : undefined, strokeWidth: n2.traceThickness, label: `${n2.connectionName} z=${i3.z}` }), i3._label && e5.points.push({ x: i3.x, y: i3.y, label: i3._label });
      }
      for (const t3 of n2.vias)
        e5.circles.push({ center: t3, radius: this.viaDiameter / 2, fill: "rgba(0, 0, 255, 0.8)", stroke: "black", label: "Solved Via" }), e5.circles.push({ center: t3, radius: this.viaDiameter / 2 + this.obstacleMargin, fill: "rgba(0, 0, 255, 0.3)", stroke: "black", label: "Solved Via Margin" });
    }
    return e5;
  }
  getSolvedRoutes() {
    return this.solvedRoutes;
  }
};
var wa = class extends ni {
  getSolverName() {
    return "HyperParameterSupervisorSolver";
  }
  GREEDY_MULTIPLIER = 1.2;
  MIN_SUBSTEPS = 1;
  supervisedSolvers;
  winningSolver;
  getHyperParameterDefs() {
    throw new Error("Not implemented");
  }
  getCombinationDefs() {
    return null;
  }
  getHyperParameterCombinations(e5) {
    e5 || (e5 = this.getHyperParameterDefs());
    const t2 = [];
    if (e5.length === 0)
      return [{}];
    const [n2, ...o3] = e5, i3 = this.getHyperParameterCombinations(o3);
    return n2.possibleValues.forEach((e6) => {
      i3.forEach((n3) => {
        t2.push({ ...n3, ...e6 });
      });
    }), t2;
  }
  initializeSolvers() {
    const e5 = this.getHyperParameterDefs(), t2 = this.getCombinationDefs() ?? [e5.map((e6) => e6.name)];
    this.supervisedSolvers = [];
    for (const n2 of t2) {
      const t3 = this.getHyperParameterCombinations(e5.filter((e6) => n2.includes(e6.name)));
      for (const e6 of t3) {
        const t4 = this.generateSolver(e6), n3 = this.computeG(t4);
        this.supervisedSolvers.push({ hyperParameters: e6, solver: t4, h: 0, g: n3, f: n3 });
      }
    }
  }
  generateSolver(e5) {
    throw new Error("Not implemented");
  }
  computeG(e5) {
    return e5.iterations / e5.MAX_ITERATIONS;
  }
  computeH(e5) {
    return 1 - (e5.progress || 0);
  }
  computeF(e5, t2) {
    return e5 + t2 * this.GREEDY_MULTIPLIER;
  }
  getSupervisedSolverWithBestFitness() {
    let e5 = 1 / 0, t2 = null;
    for (const n2 of this.supervisedSolvers ?? []) {
      if (n2.solver.solved)
        return n2;
      if (n2.solver.failed)
        continue;
      const o3 = n2.f;
      o3 < e5 && (e5 = o3, t2 = n2);
    }
    return t2;
  }
  getFailureMessage() {
    return `All solvers failed in hyper solver. Example failures: ${this.supervisedSolvers?.sort((e5, t2) => t2.f - e5.f)?.slice(0, 5).map((e5) => e5.solver.error).join(", ")}`;
  }
  _step() {
    this.supervisedSolvers || this.initializeSolvers();
    const e5 = this.getSupervisedSolverWithBestFitness();
    if (!e5)
      return this.failed = true, void (this.error = this.getFailureMessage());
    for (let t2 = 0;t2 < this.MIN_SUBSTEPS; t2++)
      e5.solver.step();
    this.activeSubSolver = e5.solver, e5.g = this.computeG(e5.solver), e5.h = this.computeH(e5.solver), e5.f = this.computeF(e5.g, e5.h), e5.solver.solved && (this.solved = true, this.winningSolver = e5.solver, this.onSolve?.(e5));
  }
  onSolve(e5) {}
  visualize() {
    const e5 = this.getSupervisedSolverWithBestFitness();
    let t2 = { lines: [], circles: [], points: [], rects: [] };
    return e5 && (t2 = e5.solver.visualize()), t2;
  }
};
function Na(e5, t2, n2) {
  const o3 = t2.z !== n2.z && e5.allowBlindAndBuriedVias !== true;
  return { minZ: o3 ? 0 : Math.min(t2.z, n2.z), maxZ: o3 ? e5.layerCount - 1 : Math.max(t2.z, n2.z) };
}
var Ra = class {
  values = [];
  positions;
  densePositions;
  reusableEntries = true;
  constructor(e5) {
    if (e5 === undefined)
      this.positions = new Map;
    else {
      if (!Number.isSafeInteger(e5) || e5 <= 0)
        throw new Error("repair04: dense path queue requires a positive grid size");
      this.densePositions = new Int32Array(e5);
    }
  }
  get length() {
    return this.values.length;
  }
  push(e5) {
    this.reusableEntries = false;
    const t2 = e5.id, n2 = this.densePositions, o3 = n2 ? n2[t2] === 0 ? undefined : n2[t2] - 1 : this.positions.get(t2);
    this.insert(e5, o3);
  }
  pushValues(e5, t2, n2) {
    const o3 = this.densePositions, i3 = o3 ? o3[e5] === 0 ? undefined : o3[e5] - 1 : this.positions.get(e5), r3 = i3 === undefined ? undefined : this.values[i3];
    if (r3 && n2 > r3.priority)
      throw new Error("repair04: queued path priorities may only decrease");
    const s2 = this.reusableEntries && r3 ? r3 : { id: e5, cost: t2, priority: n2 };
    s2.id = e5, s2.cost = t2, s2.priority = n2, this.insert(s2, i3);
  }
  insert(e5, t2) {
    const n2 = this.densePositions;
    if (t2 === undefined)
      t2 = this.values.length, this.values.push(e5);
    else if (e5.priority > this.values[t2].priority)
      throw new Error("repair04: queued path priorities may only decrease");
    for (;t2 > 0; ) {
      const o3 = Math.floor((t2 - 1) / 2), i3 = this.values[o3];
      if (i3.priority <= e5.priority)
        break;
      this.values[t2] = i3, n2 ? n2[i3.id] = t2 + 1 : this.positions.set(i3.id, t2), t2 = o3;
    }
    this.values[t2] = e5, n2 ? n2[e5.id] = t2 + 1 : this.positions.set(e5.id, t2);
  }
  pop() {
    const e5 = this.values[0];
    if (!e5)
      throw new Error("repair04: cannot pop an empty path queue");
    const t2 = this.values.pop(), n2 = this.densePositions;
    if (n2 ? n2[e5.id] = 0 : this.positions.delete(e5.id), this.values.length) {
      let e6 = 0;
      for (;2 * e6 + 1 < this.values.length; ) {
        let o3 = 2 * e6 + 1;
        o3 + 1 < this.values.length && this.values[o3 + 1].priority < this.values[o3].priority && o3++;
        const i3 = this.values[o3];
        if (i3.priority >= t2.priority)
          break;
        this.values[e6] = i3, n2 ? n2[i3.id] = e6 + 1 : this.positions.set(i3.id, e6), e6 = o3;
      }
      this.values[e6] = t2, n2 ? n2[t2.id] = e6 + 1 : this.positions.set(t2.id, e6);
    } else
      this.reusableEntries = true;
    return e5;
  }
};
var Ta = (e5, t2) => {
  const n2 = [];
  for (let o3 = 0;o3 < e5.route.length; o3 += 1) {
    const i3 = e5.route[o3];
    if (i3.route_type !== "via") {
      n2.push(structuredClone(i3));
      continue;
    }
    const r3 = n2[n2.length - 1], s2 = e5.route[o3 + 1], a3 = r3?.route_type === "wire" ? r3.width : s2?.route_type === "wire" ? s2.width : t2, c3 = s2?.route_type === "wire" ? s2.width : a3;
    r3?.route_type === "wire" && r3.x === i3.x && r3.y === i3.y && r3.layer === i3.from_layer || n2.push({ route_type: "wire", x: i3.x, y: i3.y, layer: i3.from_layer, width: a3 }), n2.push(structuredClone(i3)), s2?.route_type === "wire" && s2.x === i3.x && s2.y === i3.y && s2.layer === i3.to_layer || n2.push({ route_type: "wire", x: i3.x, y: i3.y, layer: i3.to_layer, width: c3 });
  }
  return { ...structuredClone(e5), route: n2 };
};
function Ea(e5, t2, n2) {
  return Math.max(n2 ? 0 : t2, e5.defaultObstacleMargin ?? 0, e5.minViaEdgeToPadEdgeClearance ?? 0);
}
var Aa = 0.00000001;
var Oa = (e5, t2, n2 = 0) => e5.x >= t2.minX + n2 - Aa && e5.x <= t2.maxX - n2 + Aa && e5.y >= t2.minY + n2 - Aa && e5.y <= t2.maxY - n2 + Aa;
var ka = (e5, t2, n2) => {
  let o3 = 0, i3 = 1;
  for (const [r3, s2, a3, c3] of [[e5.x, t2.x - e5.x, n2.minX, n2.maxX], [e5.y, t2.y - e5.y, n2.minY, n2.maxY]]) {
    if (r3 === undefined || s2 === undefined || a3 === undefined || c3 === undefined)
      throw new Error("Invalid segment clipping axis");
    if (Math.abs(s2) <= Aa) {
      if (r3 < a3 - Aa || r3 > c3 + Aa)
        return;
      continue;
    }
    const e6 = (a3 - r3) / s2, t3 = (c3 - r3) / s2;
    if (o3 = Math.max(o3, Math.min(e6, t3)), i3 = Math.min(i3, Math.max(e6, t3)), i3 < o3 - Aa)
      return;
  }
  return [Math.max(0, o3), Math.min(1, i3)];
};
var Da = (e5, t2, n2) => {
  if (n2 <= Aa)
    return structuredClone(e5);
  if (n2 >= 0.99999999)
    return structuredClone(t2);
  const o3 = { ...structuredClone(e5), x: e5.x + (t2.x - e5.x) * n2, y: e5.y + (t2.y - e5.y) * n2 };
  return delete o3.pcb_port_id, o3;
};
var La = (e5, t2) => Math.abs(e5.x - t2.x) <= Aa && Math.abs(e5.y - t2.y) <= Aa && e5.z === t2.z;
var za = (e5) => Array.isArray(e5) ? `[${e5.map(za).join(",")}]` : e5 !== null && typeof e5 == "object" ? `{${Object.keys(e5).filter((t2) => e5[t2] !== undefined).sort().map((t2) => `${JSON.stringify(t2)}:${za(e5[t2])}`).join(",")}}` : JSON.stringify(e5) ?? "undefined";
var Ba = (e5, t2, n2) => {
  if (e5.route.length === 1)
    return structuredClone(e5.route);
  const o3 = (t3) => {
    const n3 = Math.min(Math.floor(t3), e5.route.length - 2);
    return Da(e5.route[n3], e5.route[n3 + 1], t3 - n3);
  }, i3 = [o3(t2)];
  for (let o4 = Math.floor(t2) + 1;o4 < n2 - Aa; o4 += 1)
    i3.push(structuredClone(e5.route[o4]));
  return n2 > t2 + Aa && i3.push(o3(n2)), i3;
};
var Fa = (e5, t2, n2) => {
  const o3 = Ba(e5, t2, n2), i3 = Object.fromEntries(Object.entries(e5).filter(([e6]) => e6 !== "route" && e6 !== "vias")), r3 = e5.vias.filter((e6) => o3.some((t3) => Math.hypot(t3.x - e6.x, t3.y - e6.y) <= Aa));
  return za({ metadata: i3, points: o3, vias: r3 });
};
var Ya = {};
c(Ya, { all_layers: () => iu, any_circuit_element: () => _g, any_soup_element: () => yg, any_source_component: () => Zd, asset: () => Gh, base_circuit_json_error: () => ld, battery_capacity: () => Bh, brep_shape: () => Gu, cadModelDefaultDirectionMap: () => Km, cad_component: () => eg, cad_model_axis_directions: () => Qm, cad_model_formats: () => Jm, capacitance: () => Mh, circuit_json_footprint_load_error: () => Cm, current: () => Ah, distance: () => Eh, duration_ms: () => Oh, experiment_type: () => hg, external_footprint_load_error: () => Sm, frequency: () => Th, getZodPrefixedIdWithDefault: () => Hh, inductance: () => wh, kicadAt: () => Uh, kicadEffects: () => qh, kicadFont: () => Zh, kicadFootprintAttributes: () => Kh, kicadFootprintMetadata: () => nd, kicadFootprintModel: () => td, kicadFootprintPad: () => ed, kicadFootprintProperties: () => Qh, kicadProperty: () => Jh, kicadSymbolEffects: () => rd, kicadSymbolMetadata: () => cd, kicadSymbolPinNames: () => id, kicadSymbolPinNumbers: () => od, kicadSymbolProperties: () => ad, kicadSymbolProperty: () => sd, layer_ref: () => su, layer_string: () => ru, length: () => Rh, manufacturing_drc_properties: () => Ju, ms: () => Dh, ninePointAnchor: () => Vh, pcbRenderLayer: () => Wh, pcb_autorouting_error: () => Mm, pcb_board: () => Vp, pcb_breakout_point: () => Em, pcb_component: () => Qu, pcb_component_invalid_layer_error: () => Ym, pcb_component_not_on_board_edge_error: () => $m, pcb_component_outside_board_error: () => jm, pcb_connector_not_in_accessible_orientation_warning: () => Rm, pcb_copper_pour: () => Fm, pcb_copper_pour_brep: () => zm, pcb_copper_pour_polygon: () => Bm, pcb_copper_pour_rect: () => Lm, pcb_copper_text: () => Kp, pcb_courtyard_circle: () => qm, pcb_courtyard_outline: () => Um, pcb_courtyard_overlap_error: () => mm, pcb_courtyard_polygon: () => Zm, pcb_courtyard_rect: () => Gm, pcb_cutout: () => vm, pcb_cutout_circle: () => ym, pcb_cutout_path: () => xm, pcb_cutout_polygon: () => bm, pcb_cutout_rect: () => _m, pcb_fabrication_note_dimension: () => am, pcb_fabrication_note_path: () => rm, pcb_fabrication_note_rect: () => sm, pcb_fabrication_note_text: () => im, pcb_footprint_overlap_error: () => pm, pcb_ground_plane: () => Am, pcb_ground_plane_region: () => Om, pcb_group: () => Pm, pcb_hole: () => dp, pcb_hole_circle_or_square_shape: () => ip, pcb_hole_circle_shape: () => ep, pcb_hole_oval_shape: () => sp, pcb_hole_pill_shape: () => cp, pcb_hole_rect_shape: () => np, pcb_hole_rotated_pill_shape: () => hp, pcb_keepout: () => gm, pcb_manual_edit_conflict_warning: () => wm, pcb_missing_footprint_error: () => Im, pcb_net: () => Xp, pcb_note_dimension: () => um, pcb_note_line: () => dm, pcb_note_path: () => hm, pcb_note_rect: () => lm, pcb_note_text: () => cm, pcb_pad_pad_clearance_error: () => Vm, pcb_pad_trace_clearance_error: () => Wm, pcb_panel: () => Wp, pcb_panelization_placement_error: () => Up, pcb_placement_error: () => Gp, pcb_plated_hole: () => yp, pcb_port: () => bp, pcb_port_not_connected_error: () => Yp, pcb_port_not_matched_error: () => $p, pcb_route_hint: () => Uu, pcb_route_hints: () => Zu, pcb_silkscreen_circle: () => tm, pcb_silkscreen_line: () => qp, pcb_silkscreen_oval: () => nm, pcb_silkscreen_path: () => Jp, pcb_silkscreen_pill: () => om, pcb_silkscreen_rect: () => em, pcb_silkscreen_text: () => Qp, pcb_smtpad: () => Mp, pcb_smtpad_pill: () => Sp, pcb_solder_paste: () => Ap, pcb_text: () => Op, pcb_thermal_spoke: () => km, pcb_trace: () => zp, pcb_trace_error: () => Fp, pcb_trace_hint: () => Zp, pcb_trace_missing_error: () => jp, pcb_trace_route_point: () => Lp, pcb_trace_route_point_via: () => Dp, pcb_trace_route_point_wire: () => kp, pcb_trace_warning: () => Bp, pcb_via: () => Hp, pcb_via_clearance_error: () => Xm, pcb_via_trace_clearance_error: () => Hm, point: () => Fh, point3: () => $h, point_with_bulge: () => Vu, port_arrangement: () => bu, position: () => jh, position3: () => Yh, resistance: () => Ph, ring: () => Wu, rotation: () => zh, route_hint_point: () => qu, schematic_arc: () => Mu, schematic_box: () => mu, schematic_circle: () => Pu, schematic_component: () => xu, schematic_component_port_arrangement_by_sides: () => yu, schematic_component_port_arrangement_by_size: () => _u, schematic_debug_line: () => Lu, schematic_debug_object: () => Bu, schematic_debug_object_base: () => ku, schematic_debug_point: () => zu, schematic_debug_rect: () => Du, schematic_error: () => Au, schematic_group: () => $u, schematic_layout_error: () => Ou, schematic_line: () => Su, schematic_manual_edit_conflict_warning: () => ju, schematic_net_label: () => Eu, schematic_path: () => gu, schematic_pin_styles: () => fu, schematic_port: () => Tu, schematic_rect: () => Cu, schematic_sheet: () => Hu, schematic_symbol: () => Iu, schematic_table: () => Yu, schematic_table_cell: () => Xu, schematic_text: () => Ru, schematic_trace: () => wu, schematic_voltage_probe: () => Fu, simulation_ac_current_source: () => cg, simulation_ac_voltage_source: () => ig, simulation_current_source: () => lg, simulation_dc_current_source: () => ag, simulation_dc_voltage_source: () => og, simulation_experiment: () => dg, simulation_op_amp: () => fg, simulation_switch: () => pg, simulation_transient_voltage_graph: () => ug, simulation_unknown_experiment_error: () => gg, simulation_voltage_probe: () => mg, simulation_voltage_source: () => rg, size: () => Xh, source_ambiguous_port_reference: () => nu, source_board: () => tu, source_component_base: () => dd, source_component_internal_connection: () => Jd, source_component_pins_underspecified_warning: () => du, source_failed_to_create_component_error: () => Fd, source_group: () => Kd, source_i2c_misconfigured_error: () => Gd, source_interconnect: () => Wd, source_invalid_component_property_error: () => jd, source_manually_placed_via: () => cu, source_missing_manufacturer_part_number_warning: () => Hd, source_missing_property_error: () => Bd, source_net: () => eu, source_no_ground_pin_defined_warning: () => hu, source_no_power_pin_defined_warning: () => lu, source_pcb_ground_plane: () => ou, source_pin_attributes: () => vd, source_pin_missing_trace_warning: () => Xd, source_pin_must_be_connected_error: () => uu, source_port: () => qd, source_project_metadata: () => zd, source_property_ignored_warning: () => Yd, source_simple_battery: () => Sd, source_simple_capacitor: () => ud, source_simple_chip: () => yd, source_simple_connector: () => Rd, source_simple_crystal: () => wd, source_simple_current_source: () => xd, source_simple_diode: () => md, source_simple_fiducial: () => gd, source_simple_ground: () => _d, source_simple_inductor: () => Cd, source_simple_led: () => fd, source_simple_mosfet: () => kd, source_simple_op_amp: () => Dd, source_simple_pin_header: () => Nd, source_simple_pinout: () => Td, source_simple_potentiometer: () => Md, source_simple_power_source: () => bd, source_simple_push_button: () => Pd, source_simple_resistor: () => pd, source_simple_resonator: () => Ed, source_simple_switch: () => Ld, source_simple_test_point: () => Od, source_simple_transistor: () => Ad, source_simple_voltage_probe: () => Vd, source_simple_voltage_source: () => Ud, source_trace: () => Qd, source_trace_not_connected_error: () => $d, supplier_footprint_mismatch_warning: () => Tm, supplier_name: () => hd, time: () => kh, timestamp: () => Lh, unknown_error_finding_part: () => pu, visible_layer: () => au, voltage: () => Nh, wave_shape: () => tg });
var Xa;
var Ha;
var Va;
var Wa = {};
c(Wa, { BRAND: () => Ml, DIRTY: () => lc, EMPTY_PATH: () => oc, INVALID: () => cc, NEVER: () => xh, OK: () => hc, ParseStatus: () => ac, Schema: () => bc, ZodAny: () => Jc, ZodArray: () => tl, ZodBigInt: () => Vc, ZodBoolean: () => Wc, ZodBranded: () => wl, ZodCatch: () => Cl, ZodDate: () => Gc, ZodDefault: () => Sl, ZodDiscriminatedUnion: () => sl, ZodEffects: () => xl, ZodEnum: () => _l, ZodError: () => Ja, ZodFirstPartyTypeKind: () => Al, ZodFunction: () => pl, ZodIntersection: () => cl, ZodIssueCode: () => Za, ZodLazy: () => ml, ZodLiteral: () => gl, ZodMap: () => dl, ZodNaN: () => Pl, ZodNativeEnum: () => yl, ZodNever: () => Kc, ZodNull: () => qc, ZodNullable: () => Il, ZodNumber: () => Hc, ZodObject: () => ol, ZodOptional: () => vl, ZodParsedType: () => Ga, ZodPipeline: () => Nl, ZodPromise: () => bl, ZodReadonly: () => Rl, ZodRecord: () => hl, ZodSchema: () => bc, ZodSet: () => ul, ZodString: () => Yc, ZodSymbol: () => Uc, ZodTransformer: () => xl, ZodTuple: () => ll, ZodType: () => bc, ZodUndefined: () => Zc, ZodUnion: () => il, ZodUnknown: () => Qc, ZodVoid: () => el, addIssueToContext: () => ic, any: () => Vl, array: () => Zl, bigint: () => Fl, boolean: () => jl, coerce: () => bh, custom: () => El, date: () => $l, datetimeRegex: () => Bc, defaultErrorMap: () => Qa, discriminatedUnion: () => Kl, effect: () => dh, enum: () => ch, function: () => rh, getErrorMap: () => tc, getParsedType: () => Ua, instanceof: () => Dl, intersection: () => eh, isAborted: () => dc, isAsync: () => mc, isDirty: () => uc, isValid: () => pc, late: () => kl, lazy: () => sh, literal: () => ah, makeIssue: () => nc, map: () => oh, nan: () => Bl, nativeEnum: () => lh, never: () => Gl, null: () => Hl, nullable: () => ph, number: () => zl, object: () => ql, objectUtil: () => Va, oboolean: () => yh, onumber: () => _h, optional: () => uh, ostring: () => fh, pipeline: () => gh, preprocess: () => mh, promise: () => hh, quotelessJson: () => qa, record: () => nh, set: () => ih, setErrorMap: () => ec, strictObject: () => Jl, string: () => Ll, symbol: () => Yl, transformer: () => dh, tuple: () => th, undefined: () => Xl, union: () => Ql, unknown: () => Wl, util: () => Xa, void: () => Ul }), (Ha = Xa || (Xa = {})).assertEqual = (e5) => {}, Ha.assertIs = function(e5) {}, Ha.assertNever = function(e5) {
  throw new Error;
}, Ha.arrayToEnum = (e5) => {
  const t2 = {};
  for (const n2 of e5)
    t2[n2] = n2;
  return t2;
}, Ha.getValidEnumValues = (e5) => {
  const t2 = Ha.objectKeys(e5).filter((t3) => typeof e5[e5[t3]] != "number"), n2 = {};
  for (const o3 of t2)
    n2[o3] = e5[o3];
  return Ha.objectValues(n2);
}, Ha.objectValues = (e5) => Ha.objectKeys(e5).map(function(t2) {
  return e5[t2];
}), Ha.objectKeys = typeof Object.keys == "function" ? (e5) => Object.keys(e5) : (e5) => {
  const t2 = [];
  for (const n2 in e5)
    Object.prototype.hasOwnProperty.call(e5, n2) && t2.push(n2);
  return t2;
}, Ha.find = (e5, t2) => {
  for (const n2 of e5)
    if (t2(n2))
      return n2;
}, Ha.isInteger = typeof Number.isInteger == "function" ? (e5) => Number.isInteger(e5) : (e5) => typeof e5 == "number" && Number.isFinite(e5) && Math.floor(e5) === e5, Ha.joinValues = function(e5, t2 = " | ") {
  return e5.map((e6) => typeof e6 == "string" ? `'${e6}'` : e6).join(t2);
}, Ha.jsonStringifyReplacer = (e5, t2) => typeof t2 == "bigint" ? t2.toString() : t2, (Va || (Va = {})).mergeShapes = (e5, t2) => ({ ...e5, ...t2 });
var Ga = Xa.arrayToEnum(["string", "nan", "number", "integer", "float", "boolean", "date", "bigint", "symbol", "function", "undefined", "null", "array", "object", "unknown", "promise", "void", "never", "map", "set"]);
var Ua = (e5) => {
  switch (typeof e5) {
    case "undefined":
      return Ga.undefined;
    case "string":
      return Ga.string;
    case "number":
      return Number.isNaN(e5) ? Ga.nan : Ga.number;
    case "boolean":
      return Ga.boolean;
    case "function":
      return Ga.function;
    case "bigint":
      return Ga.bigint;
    case "symbol":
      return Ga.symbol;
    case "object":
      return Array.isArray(e5) ? Ga.array : e5 === null ? Ga.null : e5.then && typeof e5.then == "function" && e5.catch && typeof e5.catch == "function" ? Ga.promise : typeof Map != "undefined" && e5 instanceof Map ? Ga.map : typeof Set != "undefined" && e5 instanceof Set ? Ga.set : typeof Date != "undefined" && e5 instanceof Date ? Ga.date : Ga.object;
    default:
      return Ga.unknown;
  }
};
var Za = Xa.arrayToEnum(["invalid_type", "invalid_literal", "custom", "invalid_union", "invalid_union_discriminator", "invalid_enum_value", "unrecognized_keys", "invalid_arguments", "invalid_return_type", "invalid_date", "invalid_string", "too_small", "too_big", "invalid_intersection_types", "not_multiple_of", "not_finite"]);
var qa = (e5) => JSON.stringify(e5, null, 2).replace(/"([^"]+)":/g, "$1:");
var Ja = class e5 extends Error {
  get errors() {
    return this.issues;
  }
  constructor(e6) {
    super(), this.issues = [], this.addIssue = (e7) => {
      this.issues = [...this.issues, e7];
    }, this.addIssues = (e7 = []) => {
      this.issues = [...this.issues, ...e7];
    };
    const t2 = new.target.prototype;
    Object.setPrototypeOf ? Object.setPrototypeOf(this, t2) : this.__proto__ = t2, this.name = "ZodError", this.issues = e6;
  }
  format(e6) {
    const t2 = e6 || function(e7) {
      return e7.message;
    }, n2 = { _errors: [] }, o3 = (e7) => {
      for (const i3 of e7.issues)
        if (i3.code === "invalid_union")
          i3.unionErrors.map(o3);
        else if (i3.code === "invalid_return_type")
          o3(i3.returnTypeError);
        else if (i3.code === "invalid_arguments")
          o3(i3.argumentsError);
        else if (i3.path.length === 0)
          n2._errors.push(t2(i3));
        else {
          let e8 = n2, o4 = 0;
          for (;o4 < i3.path.length; ) {
            const n3 = i3.path[o4];
            o4 === i3.path.length - 1 ? (e8[n3] = e8[n3] || { _errors: [] }, e8[n3]._errors.push(t2(i3))) : e8[n3] = e8[n3] || { _errors: [] }, e8 = e8[n3], o4++;
          }
        }
    };
    return o3(this), n2;
  }
  static assert(t2) {
    if (!(t2 instanceof e5))
      throw new Error(`Not a ZodError: ${t2}`);
  }
  toString() {
    return this.message;
  }
  get message() {
    return JSON.stringify(this.issues, Xa.jsonStringifyReplacer, 2);
  }
  get isEmpty() {
    return this.issues.length === 0;
  }
  flatten(e6 = (e7) => e7.message) {
    const t2 = {}, n2 = [];
    for (const o3 of this.issues)
      if (o3.path.length > 0) {
        const n3 = o3.path[0];
        t2[n3] = t2[n3] || [], t2[n3].push(e6(o3));
      } else
        n2.push(e6(o3));
    return { formErrors: n2, fieldErrors: t2 };
  }
  get formErrors() {
    return this.flatten();
  }
};
Ja.create = (e6) => new Ja(e6);
var Qa = (e6, t2) => {
  let n2;
  switch (e6.code) {
    case Za.invalid_type:
      n2 = e6.received === Ga.undefined ? "Required" : `Expected ${e6.expected}, received ${e6.received}`;
      break;
    case Za.invalid_literal:
      n2 = `Invalid literal value, expected ${JSON.stringify(e6.expected, Xa.jsonStringifyReplacer)}`;
      break;
    case Za.unrecognized_keys:
      n2 = `Unrecognized key(s) in object: ${Xa.joinValues(e6.keys, ", ")}`;
      break;
    case Za.invalid_union:
      n2 = "Invalid input";
      break;
    case Za.invalid_union_discriminator:
      n2 = `Invalid discriminator value. Expected ${Xa.joinValues(e6.options)}`;
      break;
    case Za.invalid_enum_value:
      n2 = `Invalid enum value. Expected ${Xa.joinValues(e6.options)}, received '${e6.received}'`;
      break;
    case Za.invalid_arguments:
      n2 = "Invalid function arguments";
      break;
    case Za.invalid_return_type:
      n2 = "Invalid function return type";
      break;
    case Za.invalid_date:
      n2 = "Invalid date";
      break;
    case Za.invalid_string:
      typeof e6.validation == "object" ? "includes" in e6.validation ? (n2 = `Invalid input: must include "${e6.validation.includes}"`, typeof e6.validation.position == "number" && (n2 = `${n2} at one or more positions greater than or equal to ${e6.validation.position}`)) : ("startsWith" in e6.validation) ? n2 = `Invalid input: must start with "${e6.validation.startsWith}"` : ("endsWith" in e6.validation) ? n2 = `Invalid input: must end with "${e6.validation.endsWith}"` : Xa.assertNever(e6.validation) : n2 = e6.validation !== "regex" ? `Invalid ${e6.validation}` : "Invalid";
      break;
    case Za.too_small:
      n2 = e6.type === "array" ? `Array must contain ${e6.exact ? "exactly" : e6.inclusive ? "at least" : "more than"} ${e6.minimum} element(s)` : e6.type === "string" ? `String must contain ${e6.exact ? "exactly" : e6.inclusive ? "at least" : "over"} ${e6.minimum} character(s)` : e6.type === "number" || e6.type === "bigint" ? `Number must be ${e6.exact ? "exactly equal to " : e6.inclusive ? "greater than or equal to " : "greater than "}${e6.minimum}` : e6.type === "date" ? `Date must be ${e6.exact ? "exactly equal to " : e6.inclusive ? "greater than or equal to " : "greater than "}${new Date(Number(e6.minimum))}` : "Invalid input";
      break;
    case Za.too_big:
      n2 = e6.type === "array" ? `Array must contain ${e6.exact ? "exactly" : e6.inclusive ? "at most" : "less than"} ${e6.maximum} element(s)` : e6.type === "string" ? `String must contain ${e6.exact ? "exactly" : e6.inclusive ? "at most" : "under"} ${e6.maximum} character(s)` : e6.type === "number" ? `Number must be ${e6.exact ? "exactly" : e6.inclusive ? "less than or equal to" : "less than"} ${e6.maximum}` : e6.type === "bigint" ? `BigInt must be ${e6.exact ? "exactly" : e6.inclusive ? "less than or equal to" : "less than"} ${e6.maximum}` : e6.type === "date" ? `Date must be ${e6.exact ? "exactly" : e6.inclusive ? "smaller than or equal to" : "smaller than"} ${new Date(Number(e6.maximum))}` : "Invalid input";
      break;
    case Za.custom:
      n2 = "Invalid input";
      break;
    case Za.invalid_intersection_types:
      n2 = "Intersection results could not be merged";
      break;
    case Za.not_multiple_of:
      n2 = `Number must be a multiple of ${e6.multipleOf}`;
      break;
    case Za.not_finite:
      n2 = "Number must be finite";
      break;
    default:
      n2 = t2.defaultError, Xa.assertNever(e6);
  }
  return { message: n2 };
};
var Ka = Qa;
function ec(e6) {
  Ka = e6;
}
function tc() {
  return Ka;
}
var nc = (e6) => {
  const { data: t2, path: n2, errorMaps: o3, issueData: i3 } = e6, r3 = [...n2, ...i3.path || []], s2 = { ...i3, path: r3 };
  if (i3.message !== undefined)
    return { ...i3, path: r3, message: i3.message };
  let a3 = "";
  const c3 = o3.filter((e7) => !!e7).slice().reverse();
  for (const e7 of c3)
    a3 = e7(s2, { data: t2, defaultError: a3 }).message;
  return { ...i3, path: r3, message: a3 };
};
var oc = [];
function ic(e6, t2) {
  const n2 = tc(), o3 = nc({ issueData: t2, data: e6.data, path: e6.path, errorMaps: [e6.common.contextualErrorMap, e6.schemaErrorMap, n2, n2 === Qa ? undefined : Qa].filter((e7) => !!e7) });
  e6.common.issues.push(o3);
}
var rc;
var sc;
var ac = class e6 {
  constructor() {
    this.value = "valid";
  }
  dirty() {
    this.value === "valid" && (this.value = "dirty");
  }
  abort() {
    this.value !== "aborted" && (this.value = "aborted");
  }
  static mergeArray(e7, t2) {
    const n2 = [];
    for (const o3 of t2) {
      if (o3.status === "aborted")
        return cc;
      o3.status === "dirty" && e7.dirty(), n2.push(o3.value);
    }
    return { status: e7.value, value: n2 };
  }
  static async mergeObjectAsync(t2, n2) {
    const o3 = [];
    for (const e7 of n2) {
      const t3 = await e7.key, n3 = await e7.value;
      o3.push({ key: t3, value: n3 });
    }
    return e6.mergeObjectSync(t2, o3);
  }
  static mergeObjectSync(e7, t2) {
    const n2 = {};
    for (const o3 of t2) {
      const { key: t3, value: i3 } = o3;
      if (t3.status === "aborted")
        return cc;
      if (i3.status === "aborted")
        return cc;
      t3.status === "dirty" && e7.dirty(), i3.status === "dirty" && e7.dirty(), t3.value === "__proto__" || i3.value === undefined && !o3.alwaysSet || (n2[t3.value] = i3.value);
    }
    return { status: e7.value, value: n2 };
  }
};
var cc = Object.freeze({ status: "aborted" });
var lc = (e7) => ({ status: "dirty", value: e7 });
var hc = (e7) => ({ status: "valid", value: e7 });
var dc = (e7) => e7.status === "aborted";
var uc = (e7) => e7.status === "dirty";
var pc = (e7) => e7.status === "valid";
var mc = (e7) => typeof Promise != "undefined" && e7 instanceof Promise;
(sc = rc || (rc = {})).errToObj = (e7) => typeof e7 == "string" ? { message: e7 } : e7 || {}, sc.toString = (e7) => typeof e7 == "string" ? e7 : e7?.message;
var gc = class {
  constructor(e7, t2, n2, o3) {
    this._cachedPath = [], this.parent = e7, this.data = t2, this._path = n2, this._key = o3;
  }
  get path() {
    return this._cachedPath.length || (Array.isArray(this._key) ? this._cachedPath.push(...this._path, ...this._key) : this._cachedPath.push(...this._path, this._key)), this._cachedPath;
  }
};
var fc = (e7, t2) => {
  if (pc(t2))
    return { success: true, data: t2.value };
  if (!e7.common.issues.length)
    throw new Error("Validation failed but no issues detected.");
  return { success: false, get error() {
    if (this._error)
      return this._error;
    const t3 = new Ja(e7.common.issues);
    return this._error = t3, this._error;
  } };
};
function _c(e7) {
  if (!e7)
    return {};
  const { errorMap: t2, invalid_type_error: n2, required_error: o3, description: i3 } = e7;
  if (t2 && (n2 || o3))
    throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
  if (t2)
    return { errorMap: t2, description: i3 };
  return { errorMap: (t3, i4) => {
    const { message: r3 } = e7;
    return t3.code === "invalid_enum_value" ? { message: r3 ?? i4.defaultError } : i4.data === undefined ? { message: r3 ?? o3 ?? i4.defaultError } : t3.code !== "invalid_type" ? { message: i4.defaultError } : { message: r3 ?? n2 ?? i4.defaultError };
  }, description: i3 };
}
var yc;
var bc = class {
  get description() {
    return this._def.description;
  }
  _getType(e7) {
    return Ua(e7.data);
  }
  _getOrReturnCtx(e7, t2) {
    return t2 || { common: e7.parent.common, data: e7.data, parsedType: Ua(e7.data), schemaErrorMap: this._def.errorMap, path: e7.path, parent: e7.parent };
  }
  _processInputParams(e7) {
    return { status: new ac, ctx: { common: e7.parent.common, data: e7.data, parsedType: Ua(e7.data), schemaErrorMap: this._def.errorMap, path: e7.path, parent: e7.parent } };
  }
  _parseSync(e7) {
    const t2 = this._parse(e7);
    if (mc(t2))
      throw new Error("Synchronous parse encountered promise.");
    return t2;
  }
  _parseAsync(e7) {
    const t2 = this._parse(e7);
    return Promise.resolve(t2);
  }
  parse(e7, t2) {
    const n2 = this.safeParse(e7, t2);
    if (n2.success)
      return n2.data;
    throw n2.error;
  }
  safeParse(e7, t2) {
    const n2 = { common: { issues: [], async: t2?.async ?? false, contextualErrorMap: t2?.errorMap }, path: t2?.path || [], schemaErrorMap: this._def.errorMap, parent: null, data: e7, parsedType: Ua(e7) }, o3 = this._parseSync({ data: e7, path: n2.path, parent: n2 });
    return fc(n2, o3);
  }
  "~validate"(e7) {
    const t2 = { common: { issues: [], async: !!this["~standard"].async }, path: [], schemaErrorMap: this._def.errorMap, parent: null, data: e7, parsedType: Ua(e7) };
    if (!this["~standard"].async)
      try {
        const n2 = this._parseSync({ data: e7, path: [], parent: t2 });
        return pc(n2) ? { value: n2.value } : { issues: t2.common.issues };
      } catch (e8) {
        e8?.message?.toLowerCase()?.includes("encountered") && (this["~standard"].async = true), t2.common = { issues: [], async: true };
      }
    return this._parseAsync({ data: e7, path: [], parent: t2 }).then((e8) => pc(e8) ? { value: e8.value } : { issues: t2.common.issues });
  }
  async parseAsync(e7, t2) {
    const n2 = await this.safeParseAsync(e7, t2);
    if (n2.success)
      return n2.data;
    throw n2.error;
  }
  async safeParseAsync(e7, t2) {
    const n2 = { common: { issues: [], contextualErrorMap: t2?.errorMap, async: true }, path: t2?.path || [], schemaErrorMap: this._def.errorMap, parent: null, data: e7, parsedType: Ua(e7) }, o3 = this._parse({ data: e7, path: n2.path, parent: n2 }), i3 = await (mc(o3) ? o3 : Promise.resolve(o3));
    return fc(n2, i3);
  }
  refine(e7, t2) {
    const n2 = (e8) => typeof t2 == "string" || t2 === undefined ? { message: t2 } : typeof t2 == "function" ? t2(e8) : t2;
    return this._refinement((t3, o3) => {
      const i3 = e7(t3), r3 = () => o3.addIssue({ code: Za.custom, ...n2(t3) });
      return typeof Promise != "undefined" && i3 instanceof Promise ? i3.then((e8) => !!e8 || (r3(), false)) : !!i3 || (r3(), false);
    });
  }
  refinement(e7, t2) {
    return this._refinement((n2, o3) => !!e7(n2) || (o3.addIssue(typeof t2 == "function" ? t2(n2, o3) : t2), false));
  }
  _refinement(e7) {
    return new xl({ schema: this, typeName: Al.ZodEffects, effect: { type: "refinement", refinement: e7 } });
  }
  superRefine(e7) {
    return this._refinement(e7);
  }
  constructor(e7) {
    this.spa = this.safeParseAsync, this._def = e7, this.parse = this.parse.bind(this), this.safeParse = this.safeParse.bind(this), this.parseAsync = this.parseAsync.bind(this), this.safeParseAsync = this.safeParseAsync.bind(this), this.spa = this.spa.bind(this), this.refine = this.refine.bind(this), this.refinement = this.refinement.bind(this), this.superRefine = this.superRefine.bind(this), this.optional = this.optional.bind(this), this.nullable = this.nullable.bind(this), this.nullish = this.nullish.bind(this), this.array = this.array.bind(this), this.promise = this.promise.bind(this), this.or = this.or.bind(this), this.and = this.and.bind(this), this.transform = this.transform.bind(this), this.brand = this.brand.bind(this), this.default = this.default.bind(this), this.catch = this.catch.bind(this), this.describe = this.describe.bind(this), this.pipe = this.pipe.bind(this), this.readonly = this.readonly.bind(this), this.isNullable = this.isNullable.bind(this), this.isOptional = this.isOptional.bind(this), this["~standard"] = { version: 1, vendor: "zod", validate: (e8) => this["~validate"](e8) };
  }
  optional() {
    return vl.create(this, this._def);
  }
  nullable() {
    return Il.create(this, this._def);
  }
  nullish() {
    return this.nullable().optional();
  }
  array() {
    return tl.create(this);
  }
  promise() {
    return bl.create(this, this._def);
  }
  or(e7) {
    return il.create([this, e7], this._def);
  }
  and(e7) {
    return cl.create(this, e7, this._def);
  }
  transform(e7) {
    return new xl({ ..._c(this._def), schema: this, typeName: Al.ZodEffects, effect: { type: "transform", transform: e7 } });
  }
  default(e7) {
    const t2 = typeof e7 == "function" ? e7 : () => e7;
    return new Sl({ ..._c(this._def), innerType: this, defaultValue: t2, typeName: Al.ZodDefault });
  }
  brand() {
    return new wl({ typeName: Al.ZodBranded, type: this, ..._c(this._def) });
  }
  catch(e7) {
    const t2 = typeof e7 == "function" ? e7 : () => e7;
    return new Cl({ ..._c(this._def), innerType: this, catchValue: t2, typeName: Al.ZodCatch });
  }
  describe(e7) {
    return new (0, this.constructor)({ ...this._def, description: e7 });
  }
  pipe(e7) {
    return Nl.create(this, e7);
  }
  readonly() {
    return Rl.create(this);
  }
  isOptional() {
    return this.safeParse(undefined).success;
  }
  isNullable() {
    return this.safeParse(null).success;
  }
};
var xc = /^c[^\s-]{8,}$/i;
var vc = /^[0-9a-z]+$/;
var Ic = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
var Sc = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
var Cc = /^[a-z0-9_-]{21}$/i;
var Pc = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
var Mc = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
var wc = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
var Nc = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
var Rc = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
var Tc = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
var Ec = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
var Ac = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
var Oc = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
var kc = "((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))";
var Dc = new RegExp(`^${kc}$`);
function Lc(e7) {
  let t2 = "[0-5]\\d";
  e7.precision ? t2 = `${t2}\\.\\d{${e7.precision}}` : e7.precision == null && (t2 = `${t2}(\\.\\d+)?`);
  return `([01]\\d|2[0-3]):[0-5]\\d(:${t2})${e7.precision ? "+" : "?"}`;
}
function zc(e7) {
  return new RegExp(`^${Lc(e7)}$`);
}
function Bc(e7) {
  let t2 = `${kc}T${Lc(e7)}`;
  const n2 = [];
  return n2.push(e7.local ? "Z?" : "Z"), e7.offset && n2.push("([+-]\\d{2}:?\\d{2})"), t2 = `${t2}(${n2.join("|")})`, new RegExp(`^${t2}$`);
}
function Fc(e7, t2) {
  return !(t2 !== "v4" && t2 || !Nc.test(e7)) || !(t2 !== "v6" && t2 || !Tc.test(e7));
}
function jc(e7, t2) {
  if (!Pc.test(e7))
    return false;
  try {
    const [n2] = e7.split(".");
    if (!n2)
      return false;
    const o3 = n2.replace(/-/g, "+").replace(/_/g, "/").padEnd(n2.length + (4 - n2.length % 4) % 4, "="), i3 = JSON.parse(atob(o3));
    return typeof i3 == "object" && i3 !== null && ((!("typ" in i3) || i3?.typ === "JWT") && (!!i3.alg && (!t2 || i3.alg === t2)));
  } catch {
    return false;
  }
}
function $c(e7, t2) {
  return !(t2 !== "v4" && t2 || !Rc.test(e7)) || !(t2 !== "v6" && t2 || !Ec.test(e7));
}
var Yc = class e7 extends bc {
  _parse(e8) {
    this._def.coerce && (e8.data = String(e8.data));
    if (this._getType(e8) !== Ga.string) {
      const t3 = this._getOrReturnCtx(e8);
      return ic(t3, { code: Za.invalid_type, expected: Ga.string, received: t3.parsedType }), cc;
    }
    const t2 = new ac;
    let n2;
    for (const o3 of this._def.checks)
      if (o3.kind === "min")
        e8.data.length < o3.value && (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { code: Za.too_small, minimum: o3.value, type: "string", inclusive: true, exact: false, message: o3.message }), t2.dirty());
      else if (o3.kind === "max")
        e8.data.length > o3.value && (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { code: Za.too_big, maximum: o3.value, type: "string", inclusive: true, exact: false, message: o3.message }), t2.dirty());
      else if (o3.kind === "length") {
        const i3 = e8.data.length > o3.value, r3 = e8.data.length < o3.value;
        (i3 || r3) && (n2 = this._getOrReturnCtx(e8, n2), i3 ? ic(n2, { code: Za.too_big, maximum: o3.value, type: "string", inclusive: true, exact: true, message: o3.message }) : r3 && ic(n2, { code: Za.too_small, minimum: o3.value, type: "string", inclusive: true, exact: true, message: o3.message }), t2.dirty());
      } else if (o3.kind === "email")
        wc.test(e8.data) || (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { validation: "email", code: Za.invalid_string, message: o3.message }), t2.dirty());
      else if (o3.kind === "emoji")
        yc || (yc = new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u")), yc.test(e8.data) || (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { validation: "emoji", code: Za.invalid_string, message: o3.message }), t2.dirty());
      else if (o3.kind === "uuid")
        Sc.test(e8.data) || (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { validation: "uuid", code: Za.invalid_string, message: o3.message }), t2.dirty());
      else if (o3.kind === "nanoid")
        Cc.test(e8.data) || (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { validation: "nanoid", code: Za.invalid_string, message: o3.message }), t2.dirty());
      else if (o3.kind === "cuid")
        xc.test(e8.data) || (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { validation: "cuid", code: Za.invalid_string, message: o3.message }), t2.dirty());
      else if (o3.kind === "cuid2")
        vc.test(e8.data) || (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { validation: "cuid2", code: Za.invalid_string, message: o3.message }), t2.dirty());
      else if (o3.kind === "ulid")
        Ic.test(e8.data) || (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { validation: "ulid", code: Za.invalid_string, message: o3.message }), t2.dirty());
      else if (o3.kind === "url")
        try {
          new URL(e8.data);
        } catch {
          n2 = this._getOrReturnCtx(e8, n2), ic(n2, { validation: "url", code: Za.invalid_string, message: o3.message }), t2.dirty();
        }
      else if (o3.kind === "regex") {
        o3.regex.lastIndex = 0;
        o3.regex.test(e8.data) || (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { validation: "regex", code: Za.invalid_string, message: o3.message }), t2.dirty());
      } else if (o3.kind === "trim")
        e8.data = e8.data.trim();
      else if (o3.kind === "includes")
        e8.data.includes(o3.value, o3.position) || (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { code: Za.invalid_string, validation: { includes: o3.value, position: o3.position }, message: o3.message }), t2.dirty());
      else if (o3.kind === "toLowerCase")
        e8.data = e8.data.toLowerCase();
      else if (o3.kind === "toUpperCase")
        e8.data = e8.data.toUpperCase();
      else if (o3.kind === "startsWith")
        e8.data.startsWith(o3.value) || (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { code: Za.invalid_string, validation: { startsWith: o3.value }, message: o3.message }), t2.dirty());
      else if (o3.kind === "endsWith")
        e8.data.endsWith(o3.value) || (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { code: Za.invalid_string, validation: { endsWith: o3.value }, message: o3.message }), t2.dirty());
      else if (o3.kind === "datetime") {
        Bc(o3).test(e8.data) || (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { code: Za.invalid_string, validation: "datetime", message: o3.message }), t2.dirty());
      } else if (o3.kind === "date") {
        Dc.test(e8.data) || (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { code: Za.invalid_string, validation: "date", message: o3.message }), t2.dirty());
      } else if (o3.kind === "time") {
        zc(o3).test(e8.data) || (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { code: Za.invalid_string, validation: "time", message: o3.message }), t2.dirty());
      } else
        o3.kind === "duration" ? Mc.test(e8.data) || (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { validation: "duration", code: Za.invalid_string, message: o3.message }), t2.dirty()) : o3.kind === "ip" ? Fc(e8.data, o3.version) || (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { validation: "ip", code: Za.invalid_string, message: o3.message }), t2.dirty()) : o3.kind === "jwt" ? jc(e8.data, o3.alg) || (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { validation: "jwt", code: Za.invalid_string, message: o3.message }), t2.dirty()) : o3.kind === "cidr" ? $c(e8.data, o3.version) || (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { validation: "cidr", code: Za.invalid_string, message: o3.message }), t2.dirty()) : o3.kind === "base64" ? Ac.test(e8.data) || (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { validation: "base64", code: Za.invalid_string, message: o3.message }), t2.dirty()) : o3.kind === "base64url" ? Oc.test(e8.data) || (n2 = this._getOrReturnCtx(e8, n2), ic(n2, { validation: "base64url", code: Za.invalid_string, message: o3.message }), t2.dirty()) : Xa.assertNever(o3);
    return { status: t2.value, value: e8.data };
  }
  _regex(e8, t2, n2) {
    return this.refinement((t3) => e8.test(t3), { validation: t2, code: Za.invalid_string, ...rc.errToObj(n2) });
  }
  _addCheck(t2) {
    return new e7({ ...this._def, checks: [...this._def.checks, t2] });
  }
  email(e8) {
    return this._addCheck({ kind: "email", ...rc.errToObj(e8) });
  }
  url(e8) {
    return this._addCheck({ kind: "url", ...rc.errToObj(e8) });
  }
  emoji(e8) {
    return this._addCheck({ kind: "emoji", ...rc.errToObj(e8) });
  }
  uuid(e8) {
    return this._addCheck({ kind: "uuid", ...rc.errToObj(e8) });
  }
  nanoid(e8) {
    return this._addCheck({ kind: "nanoid", ...rc.errToObj(e8) });
  }
  cuid(e8) {
    return this._addCheck({ kind: "cuid", ...rc.errToObj(e8) });
  }
  cuid2(e8) {
    return this._addCheck({ kind: "cuid2", ...rc.errToObj(e8) });
  }
  ulid(e8) {
    return this._addCheck({ kind: "ulid", ...rc.errToObj(e8) });
  }
  base64(e8) {
    return this._addCheck({ kind: "base64", ...rc.errToObj(e8) });
  }
  base64url(e8) {
    return this._addCheck({ kind: "base64url", ...rc.errToObj(e8) });
  }
  jwt(e8) {
    return this._addCheck({ kind: "jwt", ...rc.errToObj(e8) });
  }
  ip(e8) {
    return this._addCheck({ kind: "ip", ...rc.errToObj(e8) });
  }
  cidr(e8) {
    return this._addCheck({ kind: "cidr", ...rc.errToObj(e8) });
  }
  datetime(e8) {
    return typeof e8 == "string" ? this._addCheck({ kind: "datetime", precision: null, offset: false, local: false, message: e8 }) : this._addCheck({ kind: "datetime", precision: e8?.precision === undefined ? null : e8?.precision, offset: e8?.offset ?? false, local: e8?.local ?? false, ...rc.errToObj(e8?.message) });
  }
  date(e8) {
    return this._addCheck({ kind: "date", message: e8 });
  }
  time(e8) {
    return typeof e8 == "string" ? this._addCheck({ kind: "time", precision: null, message: e8 }) : this._addCheck({ kind: "time", precision: e8?.precision === undefined ? null : e8?.precision, ...rc.errToObj(e8?.message) });
  }
  duration(e8) {
    return this._addCheck({ kind: "duration", ...rc.errToObj(e8) });
  }
  regex(e8, t2) {
    return this._addCheck({ kind: "regex", regex: e8, ...rc.errToObj(t2) });
  }
  includes(e8, t2) {
    return this._addCheck({ kind: "includes", value: e8, position: t2?.position, ...rc.errToObj(t2?.message) });
  }
  startsWith(e8, t2) {
    return this._addCheck({ kind: "startsWith", value: e8, ...rc.errToObj(t2) });
  }
  endsWith(e8, t2) {
    return this._addCheck({ kind: "endsWith", value: e8, ...rc.errToObj(t2) });
  }
  min(e8, t2) {
    return this._addCheck({ kind: "min", value: e8, ...rc.errToObj(t2) });
  }
  max(e8, t2) {
    return this._addCheck({ kind: "max", value: e8, ...rc.errToObj(t2) });
  }
  length(e8, t2) {
    return this._addCheck({ kind: "length", value: e8, ...rc.errToObj(t2) });
  }
  nonempty(e8) {
    return this.min(1, rc.errToObj(e8));
  }
  trim() {
    return new e7({ ...this._def, checks: [...this._def.checks, { kind: "trim" }] });
  }
  toLowerCase() {
    return new e7({ ...this._def, checks: [...this._def.checks, { kind: "toLowerCase" }] });
  }
  toUpperCase() {
    return new e7({ ...this._def, checks: [...this._def.checks, { kind: "toUpperCase" }] });
  }
  get isDatetime() {
    return !!this._def.checks.find((e8) => e8.kind === "datetime");
  }
  get isDate() {
    return !!this._def.checks.find((e8) => e8.kind === "date");
  }
  get isTime() {
    return !!this._def.checks.find((e8) => e8.kind === "time");
  }
  get isDuration() {
    return !!this._def.checks.find((e8) => e8.kind === "duration");
  }
  get isEmail() {
    return !!this._def.checks.find((e8) => e8.kind === "email");
  }
  get isURL() {
    return !!this._def.checks.find((e8) => e8.kind === "url");
  }
  get isEmoji() {
    return !!this._def.checks.find((e8) => e8.kind === "emoji");
  }
  get isUUID() {
    return !!this._def.checks.find((e8) => e8.kind === "uuid");
  }
  get isNANOID() {
    return !!this._def.checks.find((e8) => e8.kind === "nanoid");
  }
  get isCUID() {
    return !!this._def.checks.find((e8) => e8.kind === "cuid");
  }
  get isCUID2() {
    return !!this._def.checks.find((e8) => e8.kind === "cuid2");
  }
  get isULID() {
    return !!this._def.checks.find((e8) => e8.kind === "ulid");
  }
  get isIP() {
    return !!this._def.checks.find((e8) => e8.kind === "ip");
  }
  get isCIDR() {
    return !!this._def.checks.find((e8) => e8.kind === "cidr");
  }
  get isBase64() {
    return !!this._def.checks.find((e8) => e8.kind === "base64");
  }
  get isBase64url() {
    return !!this._def.checks.find((e8) => e8.kind === "base64url");
  }
  get minLength() {
    let e8 = null;
    for (const t2 of this._def.checks)
      t2.kind === "min" && (e8 === null || t2.value > e8) && (e8 = t2.value);
    return e8;
  }
  get maxLength() {
    let e8 = null;
    for (const t2 of this._def.checks)
      t2.kind === "max" && (e8 === null || t2.value < e8) && (e8 = t2.value);
    return e8;
  }
};
function Xc(e8, t2) {
  const n2 = (e8.toString().split(".")[1] || "").length, o3 = (t2.toString().split(".")[1] || "").length, i3 = n2 > o3 ? n2 : o3;
  return Number.parseInt(e8.toFixed(i3).replace(".", "")) % Number.parseInt(t2.toFixed(i3).replace(".", "")) / 10 ** i3;
}
Yc.create = (e8) => new Yc({ checks: [], typeName: Al.ZodString, coerce: e8?.coerce ?? false, ..._c(e8) });
var Hc = class e8 extends bc {
  constructor() {
    super(...arguments), this.min = this.gte, this.max = this.lte, this.step = this.multipleOf;
  }
  _parse(e9) {
    this._def.coerce && (e9.data = Number(e9.data));
    if (this._getType(e9) !== Ga.number) {
      const t3 = this._getOrReturnCtx(e9);
      return ic(t3, { code: Za.invalid_type, expected: Ga.number, received: t3.parsedType }), cc;
    }
    let t2;
    const n2 = new ac;
    for (const o3 of this._def.checks)
      if (o3.kind === "int")
        Xa.isInteger(e9.data) || (t2 = this._getOrReturnCtx(e9, t2), ic(t2, { code: Za.invalid_type, expected: "integer", received: "float", message: o3.message }), n2.dirty());
      else if (o3.kind === "min") {
        (o3.inclusive ? e9.data < o3.value : e9.data <= o3.value) && (t2 = this._getOrReturnCtx(e9, t2), ic(t2, { code: Za.too_small, minimum: o3.value, type: "number", inclusive: o3.inclusive, exact: false, message: o3.message }), n2.dirty());
      } else if (o3.kind === "max") {
        (o3.inclusive ? e9.data > o3.value : e9.data >= o3.value) && (t2 = this._getOrReturnCtx(e9, t2), ic(t2, { code: Za.too_big, maximum: o3.value, type: "number", inclusive: o3.inclusive, exact: false, message: o3.message }), n2.dirty());
      } else
        o3.kind === "multipleOf" ? Xc(e9.data, o3.value) !== 0 && (t2 = this._getOrReturnCtx(e9, t2), ic(t2, { code: Za.not_multiple_of, multipleOf: o3.value, message: o3.message }), n2.dirty()) : o3.kind === "finite" ? Number.isFinite(e9.data) || (t2 = this._getOrReturnCtx(e9, t2), ic(t2, { code: Za.not_finite, message: o3.message }), n2.dirty()) : Xa.assertNever(o3);
    return { status: n2.value, value: e9.data };
  }
  gte(e9, t2) {
    return this.setLimit("min", e9, true, rc.toString(t2));
  }
  gt(e9, t2) {
    return this.setLimit("min", e9, false, rc.toString(t2));
  }
  lte(e9, t2) {
    return this.setLimit("max", e9, true, rc.toString(t2));
  }
  lt(e9, t2) {
    return this.setLimit("max", e9, false, rc.toString(t2));
  }
  setLimit(t2, n2, o3, i3) {
    return new e8({ ...this._def, checks: [...this._def.checks, { kind: t2, value: n2, inclusive: o3, message: rc.toString(i3) }] });
  }
  _addCheck(t2) {
    return new e8({ ...this._def, checks: [...this._def.checks, t2] });
  }
  int(e9) {
    return this._addCheck({ kind: "int", message: rc.toString(e9) });
  }
  positive(e9) {
    return this._addCheck({ kind: "min", value: 0, inclusive: false, message: rc.toString(e9) });
  }
  negative(e9) {
    return this._addCheck({ kind: "max", value: 0, inclusive: false, message: rc.toString(e9) });
  }
  nonpositive(e9) {
    return this._addCheck({ kind: "max", value: 0, inclusive: true, message: rc.toString(e9) });
  }
  nonnegative(e9) {
    return this._addCheck({ kind: "min", value: 0, inclusive: true, message: rc.toString(e9) });
  }
  multipleOf(e9, t2) {
    return this._addCheck({ kind: "multipleOf", value: e9, message: rc.toString(t2) });
  }
  finite(e9) {
    return this._addCheck({ kind: "finite", message: rc.toString(e9) });
  }
  safe(e9) {
    return this._addCheck({ kind: "min", inclusive: true, value: Number.MIN_SAFE_INTEGER, message: rc.toString(e9) })._addCheck({ kind: "max", inclusive: true, value: Number.MAX_SAFE_INTEGER, message: rc.toString(e9) });
  }
  get minValue() {
    let e9 = null;
    for (const t2 of this._def.checks)
      t2.kind === "min" && (e9 === null || t2.value > e9) && (e9 = t2.value);
    return e9;
  }
  get maxValue() {
    let e9 = null;
    for (const t2 of this._def.checks)
      t2.kind === "max" && (e9 === null || t2.value < e9) && (e9 = t2.value);
    return e9;
  }
  get isInt() {
    return !!this._def.checks.find((e9) => e9.kind === "int" || e9.kind === "multipleOf" && Xa.isInteger(e9.value));
  }
  get isFinite() {
    let e9 = null, t2 = null;
    for (const n2 of this._def.checks) {
      if (n2.kind === "finite" || n2.kind === "int" || n2.kind === "multipleOf")
        return true;
      n2.kind === "min" ? (t2 === null || n2.value > t2) && (t2 = n2.value) : n2.kind === "max" && (e9 === null || n2.value < e9) && (e9 = n2.value);
    }
    return Number.isFinite(t2) && Number.isFinite(e9);
  }
};
Hc.create = (e9) => new Hc({ checks: [], typeName: Al.ZodNumber, coerce: e9?.coerce || false, ..._c(e9) });
var Vc = class e9 extends bc {
  constructor() {
    super(...arguments), this.min = this.gte, this.max = this.lte;
  }
  _parse(e10) {
    if (this._def.coerce)
      try {
        e10.data = BigInt(e10.data);
      } catch {
        return this._getInvalidInput(e10);
      }
    if (this._getType(e10) !== Ga.bigint)
      return this._getInvalidInput(e10);
    let t2;
    const n2 = new ac;
    for (const o3 of this._def.checks)
      if (o3.kind === "min") {
        (o3.inclusive ? e10.data < o3.value : e10.data <= o3.value) && (t2 = this._getOrReturnCtx(e10, t2), ic(t2, { code: Za.too_small, type: "bigint", minimum: o3.value, inclusive: o3.inclusive, message: o3.message }), n2.dirty());
      } else if (o3.kind === "max") {
        (o3.inclusive ? e10.data > o3.value : e10.data >= o3.value) && (t2 = this._getOrReturnCtx(e10, t2), ic(t2, { code: Za.too_big, type: "bigint", maximum: o3.value, inclusive: o3.inclusive, message: o3.message }), n2.dirty());
      } else
        o3.kind === "multipleOf" ? e10.data % o3.value !== BigInt(0) && (t2 = this._getOrReturnCtx(e10, t2), ic(t2, { code: Za.not_multiple_of, multipleOf: o3.value, message: o3.message }), n2.dirty()) : Xa.assertNever(o3);
    return { status: n2.value, value: e10.data };
  }
  _getInvalidInput(e10) {
    const t2 = this._getOrReturnCtx(e10);
    return ic(t2, { code: Za.invalid_type, expected: Ga.bigint, received: t2.parsedType }), cc;
  }
  gte(e10, t2) {
    return this.setLimit("min", e10, true, rc.toString(t2));
  }
  gt(e10, t2) {
    return this.setLimit("min", e10, false, rc.toString(t2));
  }
  lte(e10, t2) {
    return this.setLimit("max", e10, true, rc.toString(t2));
  }
  lt(e10, t2) {
    return this.setLimit("max", e10, false, rc.toString(t2));
  }
  setLimit(t2, n2, o3, i3) {
    return new e9({ ...this._def, checks: [...this._def.checks, { kind: t2, value: n2, inclusive: o3, message: rc.toString(i3) }] });
  }
  _addCheck(t2) {
    return new e9({ ...this._def, checks: [...this._def.checks, t2] });
  }
  positive(e10) {
    return this._addCheck({ kind: "min", value: BigInt(0), inclusive: false, message: rc.toString(e10) });
  }
  negative(e10) {
    return this._addCheck({ kind: "max", value: BigInt(0), inclusive: false, message: rc.toString(e10) });
  }
  nonpositive(e10) {
    return this._addCheck({ kind: "max", value: BigInt(0), inclusive: true, message: rc.toString(e10) });
  }
  nonnegative(e10) {
    return this._addCheck({ kind: "min", value: BigInt(0), inclusive: true, message: rc.toString(e10) });
  }
  multipleOf(e10, t2) {
    return this._addCheck({ kind: "multipleOf", value: e10, message: rc.toString(t2) });
  }
  get minValue() {
    let e10 = null;
    for (const t2 of this._def.checks)
      t2.kind === "min" && (e10 === null || t2.value > e10) && (e10 = t2.value);
    return e10;
  }
  get maxValue() {
    let e10 = null;
    for (const t2 of this._def.checks)
      t2.kind === "max" && (e10 === null || t2.value < e10) && (e10 = t2.value);
    return e10;
  }
};
Vc.create = (e10) => new Vc({ checks: [], typeName: Al.ZodBigInt, coerce: e10?.coerce ?? false, ..._c(e10) });
var Wc = class extends bc {
  _parse(e10) {
    this._def.coerce && (e10.data = Boolean(e10.data));
    if (this._getType(e10) !== Ga.boolean) {
      const t2 = this._getOrReturnCtx(e10);
      return ic(t2, { code: Za.invalid_type, expected: Ga.boolean, received: t2.parsedType }), cc;
    }
    return hc(e10.data);
  }
};
Wc.create = (e10) => new Wc({ typeName: Al.ZodBoolean, coerce: e10?.coerce || false, ..._c(e10) });
var Gc = class e10 extends bc {
  _parse(e11) {
    this._def.coerce && (e11.data = new Date(e11.data));
    if (this._getType(e11) !== Ga.date) {
      const t3 = this._getOrReturnCtx(e11);
      return ic(t3, { code: Za.invalid_type, expected: Ga.date, received: t3.parsedType }), cc;
    }
    if (Number.isNaN(e11.data.getTime())) {
      return ic(this._getOrReturnCtx(e11), { code: Za.invalid_date }), cc;
    }
    const t2 = new ac;
    let n2;
    for (const o3 of this._def.checks)
      o3.kind === "min" ? e11.data.getTime() < o3.value && (n2 = this._getOrReturnCtx(e11, n2), ic(n2, { code: Za.too_small, message: o3.message, inclusive: true, exact: false, minimum: o3.value, type: "date" }), t2.dirty()) : o3.kind === "max" ? e11.data.getTime() > o3.value && (n2 = this._getOrReturnCtx(e11, n2), ic(n2, { code: Za.too_big, message: o3.message, inclusive: true, exact: false, maximum: o3.value, type: "date" }), t2.dirty()) : Xa.assertNever(o3);
    return { status: t2.value, value: new Date(e11.data.getTime()) };
  }
  _addCheck(t2) {
    return new e10({ ...this._def, checks: [...this._def.checks, t2] });
  }
  min(e11, t2) {
    return this._addCheck({ kind: "min", value: e11.getTime(), message: rc.toString(t2) });
  }
  max(e11, t2) {
    return this._addCheck({ kind: "max", value: e11.getTime(), message: rc.toString(t2) });
  }
  get minDate() {
    let e11 = null;
    for (const t2 of this._def.checks)
      t2.kind === "min" && (e11 === null || t2.value > e11) && (e11 = t2.value);
    return e11 != null ? new Date(e11) : null;
  }
  get maxDate() {
    let e11 = null;
    for (const t2 of this._def.checks)
      t2.kind === "max" && (e11 === null || t2.value < e11) && (e11 = t2.value);
    return e11 != null ? new Date(e11) : null;
  }
};
Gc.create = (e11) => new Gc({ checks: [], coerce: e11?.coerce || false, typeName: Al.ZodDate, ..._c(e11) });
var Uc = class extends bc {
  _parse(e11) {
    if (this._getType(e11) !== Ga.symbol) {
      const t2 = this._getOrReturnCtx(e11);
      return ic(t2, { code: Za.invalid_type, expected: Ga.symbol, received: t2.parsedType }), cc;
    }
    return hc(e11.data);
  }
};
Uc.create = (e11) => new Uc({ typeName: Al.ZodSymbol, ..._c(e11) });
var Zc = class extends bc {
  _parse(e11) {
    if (this._getType(e11) !== Ga.undefined) {
      const t2 = this._getOrReturnCtx(e11);
      return ic(t2, { code: Za.invalid_type, expected: Ga.undefined, received: t2.parsedType }), cc;
    }
    return hc(e11.data);
  }
};
Zc.create = (e11) => new Zc({ typeName: Al.ZodUndefined, ..._c(e11) });
var qc = class extends bc {
  _parse(e11) {
    if (this._getType(e11) !== Ga.null) {
      const t2 = this._getOrReturnCtx(e11);
      return ic(t2, { code: Za.invalid_type, expected: Ga.null, received: t2.parsedType }), cc;
    }
    return hc(e11.data);
  }
};
qc.create = (e11) => new qc({ typeName: Al.ZodNull, ..._c(e11) });
var Jc = class extends bc {
  constructor() {
    super(...arguments), this._any = true;
  }
  _parse(e11) {
    return hc(e11.data);
  }
};
Jc.create = (e11) => new Jc({ typeName: Al.ZodAny, ..._c(e11) });
var Qc = class extends bc {
  constructor() {
    super(...arguments), this._unknown = true;
  }
  _parse(e11) {
    return hc(e11.data);
  }
};
Qc.create = (e11) => new Qc({ typeName: Al.ZodUnknown, ..._c(e11) });
var Kc = class extends bc {
  _parse(e11) {
    const t2 = this._getOrReturnCtx(e11);
    return ic(t2, { code: Za.invalid_type, expected: Ga.never, received: t2.parsedType }), cc;
  }
};
Kc.create = (e11) => new Kc({ typeName: Al.ZodNever, ..._c(e11) });
var el = class extends bc {
  _parse(e11) {
    if (this._getType(e11) !== Ga.undefined) {
      const t2 = this._getOrReturnCtx(e11);
      return ic(t2, { code: Za.invalid_type, expected: Ga.void, received: t2.parsedType }), cc;
    }
    return hc(e11.data);
  }
};
el.create = (e11) => new el({ typeName: Al.ZodVoid, ..._c(e11) });
var tl = class e11 extends bc {
  _parse(e12) {
    const { ctx: t2, status: n2 } = this._processInputParams(e12), o3 = this._def;
    if (t2.parsedType !== Ga.array)
      return ic(t2, { code: Za.invalid_type, expected: Ga.array, received: t2.parsedType }), cc;
    if (o3.exactLength !== null) {
      const e13 = t2.data.length > o3.exactLength.value, i4 = t2.data.length < o3.exactLength.value;
      (e13 || i4) && (ic(t2, { code: e13 ? Za.too_big : Za.too_small, minimum: i4 ? o3.exactLength.value : undefined, maximum: e13 ? o3.exactLength.value : undefined, type: "array", inclusive: true, exact: true, message: o3.exactLength.message }), n2.dirty());
    }
    if (o3.minLength !== null && t2.data.length < o3.minLength.value && (ic(t2, { code: Za.too_small, minimum: o3.minLength.value, type: "array", inclusive: true, exact: false, message: o3.minLength.message }), n2.dirty()), o3.maxLength !== null && t2.data.length > o3.maxLength.value && (ic(t2, { code: Za.too_big, maximum: o3.maxLength.value, type: "array", inclusive: true, exact: false, message: o3.maxLength.message }), n2.dirty()), t2.common.async)
      return Promise.all([...t2.data].map((e13, n3) => o3.type._parseAsync(new gc(t2, e13, t2.path, n3)))).then((e13) => ac.mergeArray(n2, e13));
    const i3 = [...t2.data].map((e13, n3) => o3.type._parseSync(new gc(t2, e13, t2.path, n3)));
    return ac.mergeArray(n2, i3);
  }
  get element() {
    return this._def.type;
  }
  min(t2, n2) {
    return new e11({ ...this._def, minLength: { value: t2, message: rc.toString(n2) } });
  }
  max(t2, n2) {
    return new e11({ ...this._def, maxLength: { value: t2, message: rc.toString(n2) } });
  }
  length(t2, n2) {
    return new e11({ ...this._def, exactLength: { value: t2, message: rc.toString(n2) } });
  }
  nonempty(e12) {
    return this.min(1, e12);
  }
};
function nl(e12) {
  if (e12 instanceof ol) {
    const t2 = {};
    for (const n2 in e12.shape) {
      const o3 = e12.shape[n2];
      t2[n2] = vl.create(nl(o3));
    }
    return new ol({ ...e12._def, shape: () => t2 });
  }
  return e12 instanceof tl ? new tl({ ...e12._def, type: nl(e12.element) }) : e12 instanceof vl ? vl.create(nl(e12.unwrap())) : e12 instanceof Il ? Il.create(nl(e12.unwrap())) : e12 instanceof ll ? ll.create(e12.items.map((e13) => nl(e13))) : e12;
}
tl.create = (e12, t2) => new tl({ type: e12, minLength: null, maxLength: null, exactLength: null, typeName: Al.ZodArray, ..._c(t2) });
var ol = class e12 extends bc {
  constructor() {
    super(...arguments), this._cached = null, this.nonstrict = this.passthrough, this.augment = this.extend;
  }
  _getCached() {
    if (this._cached !== null)
      return this._cached;
    const e13 = this._def.shape(), t2 = Xa.objectKeys(e13);
    return this._cached = { shape: e13, keys: t2 }, this._cached;
  }
  _parse(e13) {
    if (this._getType(e13) !== Ga.object) {
      const t3 = this._getOrReturnCtx(e13);
      return ic(t3, { code: Za.invalid_type, expected: Ga.object, received: t3.parsedType }), cc;
    }
    const { status: t2, ctx: n2 } = this._processInputParams(e13), { shape: o3, keys: i3 } = this._getCached(), r3 = [];
    if (!(this._def.catchall instanceof Kc && this._def.unknownKeys === "strip"))
      for (const e14 in n2.data)
        i3.includes(e14) || r3.push(e14);
    const s2 = [];
    for (const e14 of i3) {
      const t3 = o3[e14], i4 = n2.data[e14];
      s2.push({ key: { status: "valid", value: e14 }, value: t3._parse(new gc(n2, i4, n2.path, e14)), alwaysSet: e14 in n2.data });
    }
    if (this._def.catchall instanceof Kc) {
      const e14 = this._def.unknownKeys;
      if (e14 === "passthrough")
        for (const e15 of r3)
          s2.push({ key: { status: "valid", value: e15 }, value: { status: "valid", value: n2.data[e15] } });
      else if (e14 === "strict")
        r3.length > 0 && (ic(n2, { code: Za.unrecognized_keys, keys: r3 }), t2.dirty());
      else if (e14 !== "strip")
        throw new Error("Internal ZodObject error: invalid unknownKeys value.");
    } else {
      const e14 = this._def.catchall;
      for (const t3 of r3) {
        const o4 = n2.data[t3];
        s2.push({ key: { status: "valid", value: t3 }, value: e14._parse(new gc(n2, o4, n2.path, t3)), alwaysSet: t3 in n2.data });
      }
    }
    return n2.common.async ? Promise.resolve().then(async () => {
      const e14 = [];
      for (const t3 of s2) {
        const n3 = await t3.key, o4 = await t3.value;
        e14.push({ key: n3, value: o4, alwaysSet: t3.alwaysSet });
      }
      return e14;
    }).then((e14) => ac.mergeObjectSync(t2, e14)) : ac.mergeObjectSync(t2, s2);
  }
  get shape() {
    return this._def.shape();
  }
  strict(t2) {
    return rc.errToObj, new e12({ ...this._def, unknownKeys: "strict", ...t2 !== undefined ? { errorMap: (e13, n2) => {
      const o3 = this._def.errorMap?.(e13, n2).message ?? n2.defaultError;
      return e13.code === "unrecognized_keys" ? { message: rc.errToObj(t2).message ?? o3 } : { message: o3 };
    } } : {} });
  }
  strip() {
    return new e12({ ...this._def, unknownKeys: "strip" });
  }
  passthrough() {
    return new e12({ ...this._def, unknownKeys: "passthrough" });
  }
  extend(t2) {
    return new e12({ ...this._def, shape: () => ({ ...this._def.shape(), ...t2 }) });
  }
  merge(t2) {
    return new e12({ unknownKeys: t2._def.unknownKeys, catchall: t2._def.catchall, shape: () => ({ ...this._def.shape(), ...t2._def.shape() }), typeName: Al.ZodObject });
  }
  setKey(e13, t2) {
    return this.augment({ [e13]: t2 });
  }
  catchall(t2) {
    return new e12({ ...this._def, catchall: t2 });
  }
  pick(t2) {
    const n2 = {};
    for (const e13 of Xa.objectKeys(t2))
      t2[e13] && this.shape[e13] && (n2[e13] = this.shape[e13]);
    return new e12({ ...this._def, shape: () => n2 });
  }
  omit(t2) {
    const n2 = {};
    for (const e13 of Xa.objectKeys(this.shape))
      t2[e13] || (n2[e13] = this.shape[e13]);
    return new e12({ ...this._def, shape: () => n2 });
  }
  deepPartial() {
    return nl(this);
  }
  partial(t2) {
    const n2 = {};
    for (const e13 of Xa.objectKeys(this.shape)) {
      const o3 = this.shape[e13];
      t2 && !t2[e13] ? n2[e13] = o3 : n2[e13] = o3.optional();
    }
    return new e12({ ...this._def, shape: () => n2 });
  }
  required(t2) {
    const n2 = {};
    for (const e13 of Xa.objectKeys(this.shape))
      if (t2 && !t2[e13])
        n2[e13] = this.shape[e13];
      else {
        let t3 = this.shape[e13];
        for (;t3 instanceof vl; )
          t3 = t3._def.innerType;
        n2[e13] = t3;
      }
    return new e12({ ...this._def, shape: () => n2 });
  }
  keyof() {
    return fl(Xa.objectKeys(this.shape));
  }
};
ol.create = (e13, t2) => new ol({ shape: () => e13, unknownKeys: "strip", catchall: Kc.create(), typeName: Al.ZodObject, ..._c(t2) }), ol.strictCreate = (e13, t2) => new ol({ shape: () => e13, unknownKeys: "strict", catchall: Kc.create(), typeName: Al.ZodObject, ..._c(t2) }), ol.lazycreate = (e13, t2) => new ol({ shape: e13, unknownKeys: "strip", catchall: Kc.create(), typeName: Al.ZodObject, ..._c(t2) });
var il = class extends bc {
  _parse(e13) {
    const { ctx: t2 } = this._processInputParams(e13), n2 = this._def.options;
    if (t2.common.async)
      return Promise.all(n2.map(async (e14) => {
        const n3 = { ...t2, common: { ...t2.common, issues: [] }, parent: null };
        return { result: await e14._parseAsync({ data: t2.data, path: t2.path, parent: n3 }), ctx: n3 };
      })).then(function(e14) {
        for (const t3 of e14)
          if (t3.result.status === "valid")
            return t3.result;
        for (const n4 of e14)
          if (n4.result.status === "dirty")
            return t2.common.issues.push(...n4.ctx.common.issues), n4.result;
        const n3 = e14.map((e15) => new Ja(e15.ctx.common.issues));
        return ic(t2, { code: Za.invalid_union, unionErrors: n3 }), cc;
      });
    {
      let e14;
      const o3 = [];
      for (const i4 of n2) {
        const n3 = { ...t2, common: { ...t2.common, issues: [] }, parent: null }, r3 = i4._parseSync({ data: t2.data, path: t2.path, parent: n3 });
        if (r3.status === "valid")
          return r3;
        r3.status !== "dirty" || e14 || (e14 = { result: r3, ctx: n3 }), n3.common.issues.length && o3.push(n3.common.issues);
      }
      if (e14)
        return t2.common.issues.push(...e14.ctx.common.issues), e14.result;
      const i3 = o3.map((e15) => new Ja(e15));
      return ic(t2, { code: Za.invalid_union, unionErrors: i3 }), cc;
    }
  }
  get options() {
    return this._def.options;
  }
};
il.create = (e13, t2) => new il({ options: e13, typeName: Al.ZodUnion, ..._c(t2) });
var rl = (e13) => e13 instanceof ml ? rl(e13.schema) : e13 instanceof xl ? rl(e13.innerType()) : e13 instanceof gl ? [e13.value] : e13 instanceof _l ? e13.options : e13 instanceof yl ? Xa.objectValues(e13.enum) : e13 instanceof Sl ? rl(e13._def.innerType) : e13 instanceof Zc ? [undefined] : e13 instanceof qc ? [null] : e13 instanceof vl ? [undefined, ...rl(e13.unwrap())] : e13 instanceof Il ? [null, ...rl(e13.unwrap())] : e13 instanceof wl || e13 instanceof Rl ? rl(e13.unwrap()) : e13 instanceof Cl ? rl(e13._def.innerType) : [];
var sl = class e13 extends bc {
  _parse(e14) {
    const { ctx: t2 } = this._processInputParams(e14);
    if (t2.parsedType !== Ga.object)
      return ic(t2, { code: Za.invalid_type, expected: Ga.object, received: t2.parsedType }), cc;
    const n2 = this.discriminator, o3 = t2.data[n2], i3 = this.optionsMap.get(o3);
    return i3 ? t2.common.async ? i3._parseAsync({ data: t2.data, path: t2.path, parent: t2 }) : i3._parseSync({ data: t2.data, path: t2.path, parent: t2 }) : (ic(t2, { code: Za.invalid_union_discriminator, options: Array.from(this.optionsMap.keys()), path: [n2] }), cc);
  }
  get discriminator() {
    return this._def.discriminator;
  }
  get options() {
    return this._def.options;
  }
  get optionsMap() {
    return this._def.optionsMap;
  }
  static create(t2, n2, o3) {
    const i3 = new Map;
    for (const e14 of n2) {
      const n3 = rl(e14.shape[t2]);
      if (!n3.length)
        throw new Error(`A discriminator value for key \`${t2}\` could not be extracted from all schema options`);
      for (const o4 of n3) {
        if (i3.has(o4))
          throw new Error(`Discriminator property ${String(t2)} has duplicate value ${String(o4)}`);
        i3.set(o4, e14);
      }
    }
    return new e13({ typeName: Al.ZodDiscriminatedUnion, discriminator: t2, options: n2, optionsMap: i3, ..._c(o3) });
  }
};
function al(e14, t2) {
  const n2 = Ua(e14), o3 = Ua(t2);
  if (e14 === t2)
    return { valid: true, data: e14 };
  if (n2 === Ga.object && o3 === Ga.object) {
    const n3 = Xa.objectKeys(t2), o4 = Xa.objectKeys(e14).filter((e15) => n3.indexOf(e15) !== -1), i3 = { ...e14, ...t2 };
    for (const n4 of o4) {
      const o5 = al(e14[n4], t2[n4]);
      if (!o5.valid)
        return { valid: false };
      i3[n4] = o5.data;
    }
    return { valid: true, data: i3 };
  }
  if (n2 === Ga.array && o3 === Ga.array) {
    if (e14.length !== t2.length)
      return { valid: false };
    const n3 = [];
    for (let o4 = 0;o4 < e14.length; o4++) {
      const i3 = al(e14[o4], t2[o4]);
      if (!i3.valid)
        return { valid: false };
      n3.push(i3.data);
    }
    return { valid: true, data: n3 };
  }
  return n2 === Ga.date && o3 === Ga.date && +e14 === +t2 ? { valid: true, data: e14 } : { valid: false };
}
var cl = class extends bc {
  _parse(e14) {
    const { status: t2, ctx: n2 } = this._processInputParams(e14), o3 = (e15, o4) => {
      if (dc(e15) || dc(o4))
        return cc;
      const i3 = al(e15.value, o4.value);
      return i3.valid ? ((uc(e15) || uc(o4)) && t2.dirty(), { status: t2.value, value: i3.data }) : (ic(n2, { code: Za.invalid_intersection_types }), cc);
    };
    return n2.common.async ? Promise.all([this._def.left._parseAsync({ data: n2.data, path: n2.path, parent: n2 }), this._def.right._parseAsync({ data: n2.data, path: n2.path, parent: n2 })]).then(([e15, t3]) => o3(e15, t3)) : o3(this._def.left._parseSync({ data: n2.data, path: n2.path, parent: n2 }), this._def.right._parseSync({ data: n2.data, path: n2.path, parent: n2 }));
  }
};
cl.create = (e14, t2, n2) => new cl({ left: e14, right: t2, typeName: Al.ZodIntersection, ..._c(n2) });
var ll = class e14 extends bc {
  _parse(e15) {
    const { status: t2, ctx: n2 } = this._processInputParams(e15);
    if (n2.parsedType !== Ga.array)
      return ic(n2, { code: Za.invalid_type, expected: Ga.array, received: n2.parsedType }), cc;
    if (n2.data.length < this._def.items.length)
      return ic(n2, { code: Za.too_small, minimum: this._def.items.length, inclusive: true, exact: false, type: "array" }), cc;
    !this._def.rest && n2.data.length > this._def.items.length && (ic(n2, { code: Za.too_big, maximum: this._def.items.length, inclusive: true, exact: false, type: "array" }), t2.dirty());
    const o3 = [...n2.data].map((e16, t3) => {
      const o4 = this._def.items[t3] || this._def.rest;
      return o4 ? o4._parse(new gc(n2, e16, n2.path, t3)) : null;
    }).filter((e16) => !!e16);
    return n2.common.async ? Promise.all(o3).then((e16) => ac.mergeArray(t2, e16)) : ac.mergeArray(t2, o3);
  }
  get items() {
    return this._def.items;
  }
  rest(t2) {
    return new e14({ ...this._def, rest: t2 });
  }
};
ll.create = (e15, t2) => {
  if (!Array.isArray(e15))
    throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
  return new ll({ items: e15, typeName: Al.ZodTuple, rest: null, ..._c(t2) });
};
var hl = class e15 extends bc {
  get keySchema() {
    return this._def.keyType;
  }
  get valueSchema() {
    return this._def.valueType;
  }
  _parse(e16) {
    const { status: t2, ctx: n2 } = this._processInputParams(e16);
    if (n2.parsedType !== Ga.object)
      return ic(n2, { code: Za.invalid_type, expected: Ga.object, received: n2.parsedType }), cc;
    const o3 = [], i3 = this._def.keyType, r3 = this._def.valueType;
    for (const e17 in n2.data)
      o3.push({ key: i3._parse(new gc(n2, e17, n2.path, e17)), value: r3._parse(new gc(n2, n2.data[e17], n2.path, e17)), alwaysSet: e17 in n2.data });
    return n2.common.async ? ac.mergeObjectAsync(t2, o3) : ac.mergeObjectSync(t2, o3);
  }
  get element() {
    return this._def.valueType;
  }
  static create(t2, n2, o3) {
    return new e15(n2 instanceof bc ? { keyType: t2, valueType: n2, typeName: Al.ZodRecord, ..._c(o3) } : { keyType: Yc.create(), valueType: t2, typeName: Al.ZodRecord, ..._c(n2) });
  }
};
var dl = class extends bc {
  get keySchema() {
    return this._def.keyType;
  }
  get valueSchema() {
    return this._def.valueType;
  }
  _parse(e16) {
    const { status: t2, ctx: n2 } = this._processInputParams(e16);
    if (n2.parsedType !== Ga.map)
      return ic(n2, { code: Za.invalid_type, expected: Ga.map, received: n2.parsedType }), cc;
    const o3 = this._def.keyType, i3 = this._def.valueType, r3 = [...n2.data.entries()].map(([e17, t3], r4) => ({ key: o3._parse(new gc(n2, e17, n2.path, [r4, "key"])), value: i3._parse(new gc(n2, t3, n2.path, [r4, "value"])) }));
    if (n2.common.async) {
      const e17 = new Map;
      return Promise.resolve().then(async () => {
        for (const n3 of r3) {
          const o4 = await n3.key, i4 = await n3.value;
          if (o4.status === "aborted" || i4.status === "aborted")
            return cc;
          o4.status !== "dirty" && i4.status !== "dirty" || t2.dirty(), e17.set(o4.value, i4.value);
        }
        return { status: t2.value, value: e17 };
      });
    }
    {
      const e17 = new Map;
      for (const n3 of r3) {
        const { key: o4, value: i4 } = n3;
        if (o4.status === "aborted" || i4.status === "aborted")
          return cc;
        o4.status !== "dirty" && i4.status !== "dirty" || t2.dirty(), e17.set(o4.value, i4.value);
      }
      return { status: t2.value, value: e17 };
    }
  }
};
dl.create = (e16, t2, n2) => new dl({ valueType: t2, keyType: e16, typeName: Al.ZodMap, ..._c(n2) });
var ul = class e16 extends bc {
  _parse(e17) {
    const { status: t2, ctx: n2 } = this._processInputParams(e17);
    if (n2.parsedType !== Ga.set)
      return ic(n2, { code: Za.invalid_type, expected: Ga.set, received: n2.parsedType }), cc;
    const o3 = this._def;
    o3.minSize !== null && n2.data.size < o3.minSize.value && (ic(n2, { code: Za.too_small, minimum: o3.minSize.value, type: "set", inclusive: true, exact: false, message: o3.minSize.message }), t2.dirty()), o3.maxSize !== null && n2.data.size > o3.maxSize.value && (ic(n2, { code: Za.too_big, maximum: o3.maxSize.value, type: "set", inclusive: true, exact: false, message: o3.maxSize.message }), t2.dirty());
    const i3 = this._def.valueType;
    function r3(e18) {
      const n3 = new Set;
      for (const o4 of e18) {
        if (o4.status === "aborted")
          return cc;
        o4.status === "dirty" && t2.dirty(), n3.add(o4.value);
      }
      return { status: t2.value, value: n3 };
    }
    const s2 = [...n2.data.values()].map((e18, t3) => i3._parse(new gc(n2, e18, n2.path, t3)));
    return n2.common.async ? Promise.all(s2).then((e18) => r3(e18)) : r3(s2);
  }
  min(t2, n2) {
    return new e16({ ...this._def, minSize: { value: t2, message: rc.toString(n2) } });
  }
  max(t2, n2) {
    return new e16({ ...this._def, maxSize: { value: t2, message: rc.toString(n2) } });
  }
  size(e17, t2) {
    return this.min(e17, t2).max(e17, t2);
  }
  nonempty(e17) {
    return this.min(1, e17);
  }
};
ul.create = (e17, t2) => new ul({ valueType: e17, minSize: null, maxSize: null, typeName: Al.ZodSet, ..._c(t2) });
var pl = class e17 extends bc {
  constructor() {
    super(...arguments), this.validate = this.implement;
  }
  _parse(e18) {
    const { ctx: t2 } = this._processInputParams(e18);
    if (t2.parsedType !== Ga.function)
      return ic(t2, { code: Za.invalid_type, expected: Ga.function, received: t2.parsedType }), cc;
    function n2(e19, n3) {
      return nc({ data: e19, path: t2.path, errorMaps: [t2.common.contextualErrorMap, t2.schemaErrorMap, tc(), Qa].filter((e20) => !!e20), issueData: { code: Za.invalid_arguments, argumentsError: n3 } });
    }
    function o3(e19, n3) {
      return nc({ data: e19, path: t2.path, errorMaps: [t2.common.contextualErrorMap, t2.schemaErrorMap, tc(), Qa].filter((e20) => !!e20), issueData: { code: Za.invalid_return_type, returnTypeError: n3 } });
    }
    const i3 = { errorMap: t2.common.contextualErrorMap }, r3 = t2.data;
    if (this._def.returns instanceof bl) {
      const e19 = this;
      return hc(async function(...t3) {
        const s2 = new Ja([]), a3 = await e19._def.args.parseAsync(t3, i3).catch((e20) => {
          throw s2.addIssue(n2(t3, e20)), s2;
        }), c3 = await Reflect.apply(r3, this, a3);
        return await e19._def.returns._def.type.parseAsync(c3, i3).catch((e20) => {
          throw s2.addIssue(o3(c3, e20)), s2;
        });
      });
    }
    {
      const e19 = this;
      return hc(function(...t3) {
        const s2 = e19._def.args.safeParse(t3, i3);
        if (!s2.success)
          throw new Ja([n2(t3, s2.error)]);
        const a3 = Reflect.apply(r3, this, s2.data), c3 = e19._def.returns.safeParse(a3, i3);
        if (!c3.success)
          throw new Ja([o3(a3, c3.error)]);
        return c3.data;
      });
    }
  }
  parameters() {
    return this._def.args;
  }
  returnType() {
    return this._def.returns;
  }
  args(...t2) {
    return new e17({ ...this._def, args: ll.create(t2).rest(Qc.create()) });
  }
  returns(t2) {
    return new e17({ ...this._def, returns: t2 });
  }
  implement(e18) {
    return this.parse(e18);
  }
  strictImplement(e18) {
    return this.parse(e18);
  }
  static create(t2, n2, o3) {
    return new e17({ args: t2 || ll.create([]).rest(Qc.create()), returns: n2 || Qc.create(), typeName: Al.ZodFunction, ..._c(o3) });
  }
};
var ml = class extends bc {
  get schema() {
    return this._def.getter();
  }
  _parse(e18) {
    const { ctx: t2 } = this._processInputParams(e18);
    return this._def.getter()._parse({ data: t2.data, path: t2.path, parent: t2 });
  }
};
ml.create = (e18, t2) => new ml({ getter: e18, typeName: Al.ZodLazy, ..._c(t2) });
var gl = class extends bc {
  _parse(e18) {
    if (e18.data !== this._def.value) {
      const t2 = this._getOrReturnCtx(e18);
      return ic(t2, { received: t2.data, code: Za.invalid_literal, expected: this._def.value }), cc;
    }
    return { status: "valid", value: e18.data };
  }
  get value() {
    return this._def.value;
  }
};
function fl(e18, t2) {
  return new _l({ values: e18, typeName: Al.ZodEnum, ..._c(t2) });
}
gl.create = (e18, t2) => new gl({ value: e18, typeName: Al.ZodLiteral, ..._c(t2) });
var _l = class e18 extends bc {
  _parse(e19) {
    if (typeof e19.data != "string") {
      const t2 = this._getOrReturnCtx(e19), n2 = this._def.values;
      return ic(t2, { expected: Xa.joinValues(n2), received: t2.parsedType, code: Za.invalid_type }), cc;
    }
    if (this._cache || (this._cache = new Set(this._def.values)), !this._cache.has(e19.data)) {
      const t2 = this._getOrReturnCtx(e19), n2 = this._def.values;
      return ic(t2, { received: t2.data, code: Za.invalid_enum_value, options: n2 }), cc;
    }
    return hc(e19.data);
  }
  get options() {
    return this._def.values;
  }
  get enum() {
    const e19 = {};
    for (const t2 of this._def.values)
      e19[t2] = t2;
    return e19;
  }
  get Values() {
    const e19 = {};
    for (const t2 of this._def.values)
      e19[t2] = t2;
    return e19;
  }
  get Enum() {
    const e19 = {};
    for (const t2 of this._def.values)
      e19[t2] = t2;
    return e19;
  }
  extract(t2, n2 = this._def) {
    return e18.create(t2, { ...this._def, ...n2 });
  }
  exclude(t2, n2 = this._def) {
    return e18.create(this.options.filter((e19) => !t2.includes(e19)), { ...this._def, ...n2 });
  }
};
_l.create = fl;
var yl = class extends bc {
  _parse(e19) {
    const t2 = Xa.getValidEnumValues(this._def.values), n2 = this._getOrReturnCtx(e19);
    if (n2.parsedType !== Ga.string && n2.parsedType !== Ga.number) {
      const e20 = Xa.objectValues(t2);
      return ic(n2, { expected: Xa.joinValues(e20), received: n2.parsedType, code: Za.invalid_type }), cc;
    }
    if (this._cache || (this._cache = new Set(Xa.getValidEnumValues(this._def.values))), !this._cache.has(e19.data)) {
      const e20 = Xa.objectValues(t2);
      return ic(n2, { received: n2.data, code: Za.invalid_enum_value, options: e20 }), cc;
    }
    return hc(e19.data);
  }
  get enum() {
    return this._def.values;
  }
};
yl.create = (e19, t2) => new yl({ values: e19, typeName: Al.ZodNativeEnum, ..._c(t2) });
var bl = class extends bc {
  unwrap() {
    return this._def.type;
  }
  _parse(e19) {
    const { ctx: t2 } = this._processInputParams(e19);
    if (t2.parsedType !== Ga.promise && t2.common.async === false)
      return ic(t2, { code: Za.invalid_type, expected: Ga.promise, received: t2.parsedType }), cc;
    const n2 = t2.parsedType === Ga.promise ? t2.data : Promise.resolve(t2.data);
    return hc(n2.then((e20) => this._def.type.parseAsync(e20, { path: t2.path, errorMap: t2.common.contextualErrorMap })));
  }
};
bl.create = (e19, t2) => new bl({ type: e19, typeName: Al.ZodPromise, ..._c(t2) });
var xl = class extends bc {
  innerType() {
    return this._def.schema;
  }
  sourceType() {
    return this._def.schema._def.typeName === Al.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
  }
  _parse(e19) {
    const { status: t2, ctx: n2 } = this._processInputParams(e19), o3 = this._def.effect || null, i3 = { addIssue: (e20) => {
      ic(n2, e20), e20.fatal ? t2.abort() : t2.dirty();
    }, get path() {
      return n2.path;
    } };
    if (i3.addIssue = i3.addIssue.bind(i3), o3.type === "preprocess") {
      const e20 = o3.transform(n2.data, i3);
      if (n2.common.async)
        return Promise.resolve(e20).then(async (e21) => {
          if (t2.value === "aborted")
            return cc;
          const o4 = await this._def.schema._parseAsync({ data: e21, path: n2.path, parent: n2 });
          return o4.status === "aborted" ? cc : o4.status === "dirty" || t2.value === "dirty" ? lc(o4.value) : o4;
        });
      {
        if (t2.value === "aborted")
          return cc;
        const o4 = this._def.schema._parseSync({ data: e20, path: n2.path, parent: n2 });
        return o4.status === "aborted" ? cc : o4.status === "dirty" || t2.value === "dirty" ? lc(o4.value) : o4;
      }
    }
    if (o3.type === "refinement") {
      const e20 = (e21) => {
        const t3 = o3.refinement(e21, i3);
        if (n2.common.async)
          return Promise.resolve(t3);
        if (t3 instanceof Promise)
          throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
        return e21;
      };
      if (n2.common.async === false) {
        const o4 = this._def.schema._parseSync({ data: n2.data, path: n2.path, parent: n2 });
        return o4.status === "aborted" ? cc : (o4.status === "dirty" && t2.dirty(), e20(o4.value), { status: t2.value, value: o4.value });
      }
      return this._def.schema._parseAsync({ data: n2.data, path: n2.path, parent: n2 }).then((n3) => n3.status === "aborted" ? cc : (n3.status === "dirty" && t2.dirty(), e20(n3.value).then(() => ({ status: t2.value, value: n3.value }))));
    }
    if (o3.type === "transform") {
      if (n2.common.async === false) {
        const e20 = this._def.schema._parseSync({ data: n2.data, path: n2.path, parent: n2 });
        if (!pc(e20))
          return cc;
        const r3 = o3.transform(e20.value, i3);
        if (r3 instanceof Promise)
          throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");
        return { status: t2.value, value: r3 };
      }
      return this._def.schema._parseAsync({ data: n2.data, path: n2.path, parent: n2 }).then((e20) => pc(e20) ? Promise.resolve(o3.transform(e20.value, i3)).then((e21) => ({ status: t2.value, value: e21 })) : cc);
    }
    Xa.assertNever(o3);
  }
};
xl.create = (e19, t2, n2) => new xl({ schema: e19, typeName: Al.ZodEffects, effect: t2, ..._c(n2) }), xl.createWithPreprocess = (e19, t2, n2) => new xl({ schema: t2, effect: { type: "preprocess", transform: e19 }, typeName: Al.ZodEffects, ..._c(n2) });
var vl = class extends bc {
  _parse(e19) {
    return this._getType(e19) === Ga.undefined ? hc(undefined) : this._def.innerType._parse(e19);
  }
  unwrap() {
    return this._def.innerType;
  }
};
vl.create = (e19, t2) => new vl({ innerType: e19, typeName: Al.ZodOptional, ..._c(t2) });
var Il = class extends bc {
  _parse(e19) {
    return this._getType(e19) === Ga.null ? hc(null) : this._def.innerType._parse(e19);
  }
  unwrap() {
    return this._def.innerType;
  }
};
Il.create = (e19, t2) => new Il({ innerType: e19, typeName: Al.ZodNullable, ..._c(t2) });
var Sl = class extends bc {
  _parse(e19) {
    const { ctx: t2 } = this._processInputParams(e19);
    let n2 = t2.data;
    return t2.parsedType === Ga.undefined && (n2 = this._def.defaultValue()), this._def.innerType._parse({ data: n2, path: t2.path, parent: t2 });
  }
  removeDefault() {
    return this._def.innerType;
  }
};
Sl.create = (e19, t2) => new Sl({ innerType: e19, typeName: Al.ZodDefault, defaultValue: typeof t2.default == "function" ? t2.default : () => t2.default, ..._c(t2) });
var Cl = class extends bc {
  _parse(e19) {
    const { ctx: t2 } = this._processInputParams(e19), n2 = { ...t2, common: { ...t2.common, issues: [] } }, o3 = this._def.innerType._parse({ data: n2.data, path: n2.path, parent: { ...n2 } });
    return mc(o3) ? o3.then((e20) => ({ status: "valid", value: e20.status === "valid" ? e20.value : this._def.catchValue({ get error() {
      return new Ja(n2.common.issues);
    }, input: n2.data }) })) : { status: "valid", value: o3.status === "valid" ? o3.value : this._def.catchValue({ get error() {
      return new Ja(n2.common.issues);
    }, input: n2.data }) };
  }
  removeCatch() {
    return this._def.innerType;
  }
};
Cl.create = (e19, t2) => new Cl({ innerType: e19, typeName: Al.ZodCatch, catchValue: typeof t2.catch == "function" ? t2.catch : () => t2.catch, ..._c(t2) });
var Pl = class extends bc {
  _parse(e19) {
    if (this._getType(e19) !== Ga.nan) {
      const t2 = this._getOrReturnCtx(e19);
      return ic(t2, { code: Za.invalid_type, expected: Ga.nan, received: t2.parsedType }), cc;
    }
    return { status: "valid", value: e19.data };
  }
};
Pl.create = (e19) => new Pl({ typeName: Al.ZodNaN, ..._c(e19) });
var Ml = Symbol("zod_brand");
var wl = class extends bc {
  _parse(e19) {
    const { ctx: t2 } = this._processInputParams(e19), n2 = t2.data;
    return this._def.type._parse({ data: n2, path: t2.path, parent: t2 });
  }
  unwrap() {
    return this._def.type;
  }
};
var Nl = class e19 extends bc {
  _parse(e20) {
    const { status: t2, ctx: n2 } = this._processInputParams(e20);
    if (n2.common.async) {
      return (async () => {
        const e21 = await this._def.in._parseAsync({ data: n2.data, path: n2.path, parent: n2 });
        return e21.status === "aborted" ? cc : e21.status === "dirty" ? (t2.dirty(), lc(e21.value)) : this._def.out._parseAsync({ data: e21.value, path: n2.path, parent: n2 });
      })();
    }
    {
      const e21 = this._def.in._parseSync({ data: n2.data, path: n2.path, parent: n2 });
      return e21.status === "aborted" ? cc : e21.status === "dirty" ? (t2.dirty(), { status: "dirty", value: e21.value }) : this._def.out._parseSync({ data: e21.value, path: n2.path, parent: n2 });
    }
  }
  static create(t2, n2) {
    return new e19({ in: t2, out: n2, typeName: Al.ZodPipeline });
  }
};
var Rl = class extends bc {
  _parse(e20) {
    const t2 = this._def.innerType._parse(e20), n2 = (e21) => (pc(e21) && (e21.value = Object.freeze(e21.value)), e21);
    return mc(t2) ? t2.then((e21) => n2(e21)) : n2(t2);
  }
  unwrap() {
    return this._def.innerType;
  }
};
function Tl(e20, t2) {
  const n2 = typeof e20 == "function" ? e20(t2) : typeof e20 == "string" ? { message: e20 } : e20;
  return typeof n2 == "string" ? { message: n2 } : n2;
}
function El(e20, t2 = {}, n2) {
  return e20 ? Jc.create().superRefine((o3, i3) => {
    const r3 = e20(o3);
    if (r3 instanceof Promise)
      return r3.then((e21) => {
        if (!e21) {
          const e22 = Tl(t2, o3), r4 = e22.fatal ?? n2 ?? true;
          i3.addIssue({ code: "custom", ...e22, fatal: r4 });
        }
      });
    if (!r3) {
      const e21 = Tl(t2, o3), r4 = e21.fatal ?? n2 ?? true;
      i3.addIssue({ code: "custom", ...e21, fatal: r4 });
    }
  }) : Jc.create();
}
Rl.create = (e20, t2) => new Rl({ innerType: e20, typeName: Al.ZodReadonly, ..._c(t2) });
var Al;
var Ol;
var kl = { object: ol.lazycreate };
(Ol = Al || (Al = {})).ZodString = "ZodString", Ol.ZodNumber = "ZodNumber", Ol.ZodNaN = "ZodNaN", Ol.ZodBigInt = "ZodBigInt", Ol.ZodBoolean = "ZodBoolean", Ol.ZodDate = "ZodDate", Ol.ZodSymbol = "ZodSymbol", Ol.ZodUndefined = "ZodUndefined", Ol.ZodNull = "ZodNull", Ol.ZodAny = "ZodAny", Ol.ZodUnknown = "ZodUnknown", Ol.ZodNever = "ZodNever", Ol.ZodVoid = "ZodVoid", Ol.ZodArray = "ZodArray", Ol.ZodObject = "ZodObject", Ol.ZodUnion = "ZodUnion", Ol.ZodDiscriminatedUnion = "ZodDiscriminatedUnion", Ol.ZodIntersection = "ZodIntersection", Ol.ZodTuple = "ZodTuple", Ol.ZodRecord = "ZodRecord", Ol.ZodMap = "ZodMap", Ol.ZodSet = "ZodSet", Ol.ZodFunction = "ZodFunction", Ol.ZodLazy = "ZodLazy", Ol.ZodLiteral = "ZodLiteral", Ol.ZodEnum = "ZodEnum", Ol.ZodEffects = "ZodEffects", Ol.ZodNativeEnum = "ZodNativeEnum", Ol.ZodOptional = "ZodOptional", Ol.ZodNullable = "ZodNullable", Ol.ZodDefault = "ZodDefault", Ol.ZodCatch = "ZodCatch", Ol.ZodPromise = "ZodPromise", Ol.ZodBranded = "ZodBranded", Ol.ZodPipeline = "ZodPipeline", Ol.ZodReadonly = "ZodReadonly";
var Dl = (e20, t2 = { message: `Input not instance of ${e20.name}` }) => El((t3) => t3 instanceof e20, t2);
var Ll = Yc.create;
var zl = Hc.create;
var Bl = Pl.create;
var Fl = Vc.create;
var jl = Wc.create;
var $l = Gc.create;
var Yl = Uc.create;
var Xl = Zc.create;
var Hl = qc.create;
var Vl = Jc.create;
var Wl = Qc.create;
var Gl = Kc.create;
var Ul = el.create;
var Zl = tl.create;
var ql = ol.create;
var Jl = ol.strictCreate;
var Ql = il.create;
var Kl = sl.create;
var eh = cl.create;
var th = ll.create;
var nh = hl.create;
var oh = dl.create;
var ih = ul.create;
var rh = pl.create;
var sh = ml.create;
var ah = gl.create;
var ch = _l.create;
var lh = yl.create;
var hh = bl.create;
var dh = xl.create;
var uh = vl.create;
var ph = Il.create;
var mh = xl.createWithPreprocess;
var gh = Nl.create;
var fh = () => Ll().optional();
var _h = () => zl().optional();
var yh = () => jl().optional();
var bh = { string: (e20) => Yc.create({ ...e20, coerce: true }), number: (e20) => Hc.create({ ...e20, coerce: true }), boolean: (e20) => Wc.create({ ...e20, coerce: true }), bigint: (e20) => Vc.create({ ...e20, coerce: true }), date: (e20) => Gc.create({ ...e20, coerce: true }) };
var xh = cc;
var vh = { Hz: { baseUnit: "Hz", variants: { MHz: 1e6, kHz: 1000, Hz: 1 } }, g: { baseUnit: "g", variants: { kg: 1000, g: 1 } }, "Ω": { baseUnit: "Ω", variants: { "mΩ": 0.001, "Ω": 1, "kΩ": 1000, "KΩ": 1000, kohm: 1000, "MΩ": 1e6, "GΩ": 1e9, "TΩ": 1000000000000 } }, V: { baseUnit: "V", variants: { mV: 0.001, V: 1, kV: 1000, KV: 1000, MV: 1e6, GV: 1e9, TV: 1000000000000 } }, A: { baseUnit: "A", variants: { "µA": 0.000001, mA: 0.001, ma: 0.001, A: 1, kA: 1000, MA: 1e6 } }, F: { baseUnit: "F", variants: { pF: 0.000000000001, nF: 0.000000001, "µF": 0.000001, uF: 0.000001, mF: 0.001, F: 1 } }, ml: { baseUnit: "ml", variants: { ml: 1, mL: 1, l: 1000, L: 1000 } }, deg: { baseUnit: "deg", variants: { rad: 180 / Math.PI } }, ms: { baseUnit: "ms", variants: { fs: 0.000000000001, ps: 0.000000001, ns: 0.000001, us: 0.001, "µs": 0.001, ms: 1, s: 1000 } }, mm: { baseUnit: "mm", variants: { nm: 0.000001, "µm": 0.001, um: 0.001, mm: 1, cm: 10, dm: 100, m: 1000, km: 1e6, in: 25.4, ft: 304.8, IN: 25.4, FT: 304.8, yd: 914.4, mi: 1609344, mil: 0.0254 } } };
var Ih = new Set;
for (const [e20, t2] of Object.entries(vh)) {
  Ih.add(e20);
  for (const e21 of Object.keys(t2.variants))
    Ih.add(e21);
}
var Sh = { tera: 1000000000000, T: 1000000000000, giga: 1e9, G: 1e9, mega: 1e6, M: 1e6, kilo: 1000, k: 1000, deci: 0.1, d: 0.1, centi: 0.01, c: 0.01, milli: 0.001, m: 0.001, micro: 0.000001, u: 0.000001, "µ": 0.000001, nano: 0.000000001, n: 0.000000001, pico: 0.000000000001, p: 0.000000000001 };
function Ch(e20) {
  if (e20 == null)
    return { parsedUnit: null, unitOfValue: null, value: null };
  if (typeof e20 == "string" && e20.match(/^-?[\d\.]+$/))
    return { value: Number.parseFloat(e20), parsedUnit: null, unitOfValue: null };
  if (typeof e20 == "number")
    return { value: e20, parsedUnit: null, unitOfValue: null };
  if (typeof e20 == "object" && "x" in e20 && "y" in e20) {
    const { parsedUnit: t3, unitOfValue: n3 } = Ch(e20.x), o4 = Ch(e20.x), i4 = Ch(e20.y);
    return o4.value === null || i4.value === null ? { parsedUnit: null, unitOfValue: null, value: null } : { parsedUnit: t3, unitOfValue: n3, value: { x: o4.value, y: i4.value } };
  }
  const t2 = e20.toString().split("").reverse().join(""), n2 = t2.match(/[^\d\s]+/)?.[0];
  if (!n2)
    throw new Error(`Could not determine unit: "${e20}"`);
  const o3 = n2.split("").reverse().join(""), i3 = e20.slice(0, -o3.length);
  if (o3 in Sh && !Ih.has(o3)) {
    const e21 = Sh[o3];
    return { parsedUnit: null, unitOfValue: null, value: Number.parseFloat(i3) * e21 };
  }
  const { baseUnit: r3, conversionFactor: s2 } = function(e21) {
    for (const [t3, n3] of Object.entries(vh))
      if (e21 in n3.variants)
        return { baseUnit: n3.baseUnit, conversionFactor: n3.variants[e21] };
    return { baseUnit: e21, conversionFactor: 1 };
  }(o3);
  return { parsedUnit: o3, unitOfValue: r3, value: s2 * Number.parseFloat(i3) };
}
var Ph = Wa.string().or(Wa.number()).transform((e20) => Ch(e20).value);
var Mh = Wa.string().or(Wa.number()).transform((e20) => Ch(e20).value).transform((e20) => Number.parseFloat(e20.toPrecision(12)));
var wh = Wa.string().or(Wa.number()).transform((e20) => Ch(e20).value);
var Nh = Wa.string().or(Wa.number()).transform((e20) => Ch(e20).value);
var Rh = Wa.string().or(Wa.number()).transform((e20) => Ch(e20).value);
var Th = Wa.string().or(Wa.number()).transform((e20) => Ch(e20).value);
var Eh = Rh;
var Ah = Wa.string().or(Wa.number()).transform((e20) => Ch(e20).value);
var Oh = Wa.string().or(Wa.number()).transform((e20) => Ch(e20).value);
var kh = Oh;
var Dh = Oh;
var Lh = Wa.string().datetime();
var zh = Wa.string().or(Wa.number()).transform((e20) => typeof e20 == "number" ? e20 : e20.endsWith("deg") ? Number.parseFloat(e20.split("deg")[0]) : e20.endsWith("rad") ? 180 * Number.parseFloat(e20.split("rad")[0]) / Math.PI : Number.parseFloat(e20));
var Bh = Wa.number().or(Wa.string().endsWith("mAh")).transform((e20) => {
  if (typeof e20 == "string") {
    const t2 = e20.replace("mAh", ""), n2 = Number.parseFloat(t2);
    if (Number.isNaN(n2))
      throw new Error("Invalid capacity");
    return n2;
  }
  return e20;
}).describe("Battery capacity in mAh");
var Fh = Wa.object({ x: Eh, y: Eh });
var jh = Fh;
var $h = Wa.object({ x: Eh, y: Eh, z: Eh });
var Yh = $h;
var Xh = Wa.object({ width: Wa.number(), height: Wa.number() });
var Hh = (e20) => Wa.string().optional().default(() => `${e20}_${((e21) => {
  const t2 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  return Array.from({ length: e21 }, () => t2[Math.floor(62 * Math.random())]).join("");
})(10)}`);
var Vh = Wa.enum(["top_left", "top_center", "top_right", "center_left", "center", "center_right", "bottom_left", "bottom_center", "bottom_right"]);
var Wh = Wa.enum(["top_silkscreen", "bottom_silkscreen", "top_copper", "bottom_copper", "top_soldermask", "bottom_soldermask", "top_fabrication_note", "bottom_fabrication_note", "top_user_note", "bottom_user_note", "top_courtyard", "bottom_courtyard", "inner1_copper", "inner2_copper", "inner3_copper", "inner4_copper", "inner5_copper", "inner6_copper", "edge_cuts", "drill"]);
var Gh = Wa.object({ project_relative_path: Wa.string(), url: Wa.string(), mimetype: Wa.string() });
var Uh = Fh.extend({ rotation: zh.optional() });
var Zh = Wa.object({ size: Fh.optional(), thickness: Eh.optional() });
var qh = Wa.object({ font: Zh.optional() });
var Jh = Wa.object({ value: Wa.string(), at: Uh.optional(), layer: Wa.string().optional(), uuid: Wa.string().optional(), hide: Wa.boolean().optional(), effects: qh.optional() });
var Qh = Wa.object({ Reference: Jh.optional(), Value: Jh.optional(), Datasheet: Jh.optional(), Description: Jh.optional() });
var Kh = Wa.object({ through_hole: Wa.boolean().optional(), smd: Wa.boolean().optional(), exclude_from_pos_files: Wa.boolean().optional(), exclude_from_bom: Wa.boolean().optional() });
var ed = Wa.object({ name: Wa.string(), type: Wa.string(), shape: Wa.string().optional(), at: Uh.optional(), size: Fh.optional(), drill: Eh.optional(), layers: Wa.array(Wa.string()).optional(), removeUnusedLayers: Wa.boolean().optional(), uuid: Wa.string().optional() });
var td = Wa.object({ path: Wa.string(), offset: $h.optional(), scale: $h.optional(), rotate: $h.optional() });
var nd = Wa.object({ footprintName: Wa.string().optional(), version: Wa.union([Wa.number(), Wa.string()]).optional(), generator: Wa.string().optional(), generatorVersion: Wa.union([Wa.number(), Wa.string()]).optional(), layer: Wa.string().optional(), properties: Qh.optional(), attributes: Kh.optional(), pads: Wa.array(ed).optional(), embeddedFonts: Wa.boolean().optional(), model: td.optional() });
var od = Wa.object({ hide: Wa.boolean().optional() });
var id = Wa.object({ offset: Eh.optional(), hide: Wa.boolean().optional() });
var rd = Wa.object({ font: Zh.optional(), justify: Wa.union([Wa.string(), Wa.array(Wa.string())]).optional(), hide: Wa.boolean().optional() });
var sd = Wa.object({ value: Wa.string(), id: Wa.union([Wa.number(), Wa.string()]).optional(), at: Uh.optional(), effects: rd.optional() });
var ad = Wa.object({ Reference: sd.optional(), Value: sd.optional(), Footprint: sd.optional(), Datasheet: sd.optional(), Description: sd.optional(), ki_keywords: sd.optional(), ki_fp_filters: sd.optional() });
var cd = Wa.object({ symbolName: Wa.string().optional(), extends: Wa.string().optional(), pinNumbers: od.optional(), pinNames: id.optional(), excludeFromSim: Wa.boolean().optional(), inBom: Wa.boolean().optional(), onBoard: Wa.boolean().optional(), properties: ad.optional(), embeddedFonts: Wa.boolean().optional() });
var ld = Wa.object({ error_type: Wa.string(), message: Wa.string(), is_fatal: Wa.boolean().optional() });
var hd = Wa.enum(["jlcpcb", "macrofab", "pcbway", "digikey", "mouser", "lcsc"]);
var dd = Wa.object({ type: Wa.literal("source_component"), ftype: Wa.string().optional(), source_component_id: Wa.string(), name: Wa.string(), manufacturer_part_number: Wa.string().optional(), supplier_part_numbers: Wa.record(hd, Wa.array(Wa.string())).optional(), display_value: Wa.string().optional(), display_name: Wa.string().optional(), are_pins_interchangeable: Wa.boolean().optional(), internally_connected_source_port_ids: Wa.array(Wa.array(Wa.string())).optional(), source_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() });
var ud = dd.extend({ ftype: Wa.literal("simple_capacitor"), capacitance: Mh, max_voltage_rating: Nh.optional(), display_capacitance: Wa.string().optional(), max_decoupling_trace_length: Eh.optional() });
var pd = dd.extend({ ftype: Wa.literal("simple_resistor"), resistance: Ph, display_resistance: Wa.string().optional() });
var md = dd.extend({ ftype: Wa.literal("simple_diode") });
var gd = dd.extend({ ftype: Wa.literal("simple_fiducial") });
var fd = md.extend({ ftype: Wa.literal("simple_led"), color: Wa.string().optional(), wavelength: Wa.string().optional() });
var _d = dd.extend({ ftype: Wa.literal("simple_ground") });
var yd = dd.extend({ ftype: Wa.literal("simple_chip") });
var bd = dd.extend({ ftype: Wa.literal("simple_power_source"), voltage: Nh });
var xd = dd.extend({ ftype: Wa.literal("simple_current_source"), current: Ah, frequency: Th.optional(), peak_to_peak_current: Ah.optional(), wave_shape: Wa.enum(["sine", "square", "triangle", "sawtooth", "dc"]).optional().default("dc"), phase: Wa.number().optional(), duty_cycle: Wa.number().min(0).max(1).optional() });
var vd = Wa.object({ must_be_connected: Wa.boolean().optional(), provides_power: Wa.boolean().optional(), requires_power: Wa.boolean().optional(), provides_ground: Wa.boolean().optional(), requires_ground: Wa.boolean().optional(), provides_voltage: Wa.union([Wa.string(), Wa.number()]).optional(), requires_voltage: Wa.union([Wa.string(), Wa.number()]).optional(), do_not_connect: Wa.boolean().optional(), include_in_board_pinout: Wa.boolean().optional(), can_use_internal_pullup: Wa.boolean().optional(), is_using_internal_pullup: Wa.boolean().optional(), needs_external_pullup: Wa.boolean().optional(), can_use_internal_pulldown: Wa.boolean().optional(), is_using_internal_pulldown: Wa.boolean().optional(), needs_external_pulldown: Wa.boolean().optional(), can_use_open_drain: Wa.boolean().optional(), is_using_open_drain: Wa.boolean().optional(), can_use_push_pull: Wa.boolean().optional(), is_using_push_pull: Wa.boolean().optional(), should_have_decoupling_capacitor: Wa.boolean().optional(), recommended_decoupling_capacitor_capacitance: Wa.union([Wa.string(), Wa.number()]).optional(), is_configured_for_i2c_sda: Wa.boolean().optional(), is_configured_for_i2c_scl: Wa.boolean().optional(), is_configured_for_spi_mosi: Wa.boolean().optional(), is_configured_for_spi_miso: Wa.boolean().optional(), is_configured_for_spi_sck: Wa.boolean().optional(), is_configured_for_spi_cs: Wa.boolean().optional(), is_configured_for_uart_tx: Wa.boolean().optional(), is_configured_for_uart_rx: Wa.boolean().optional(), supports_i2c_sda: Wa.boolean().optional(), supports_i2c_scl: Wa.boolean().optional(), supports_spi_mosi: Wa.boolean().optional(), supports_spi_miso: Wa.boolean().optional(), supports_spi_sck: Wa.boolean().optional(), supports_spi_cs: Wa.boolean().optional(), supports_uart_tx: Wa.boolean().optional(), supports_uart_rx: Wa.boolean().optional() });
var Id = dd.extend({ ftype: Wa.literal("simple_fuse"), current_rating_amps: Wa.number().describe("Nominal current in amps the fuse is rated for"), voltage_rating_volts: Wa.number().describe("Voltage rating in volts, e.g. ±5V would be 5") });
var Sd = dd.extend({ ftype: Wa.literal("simple_battery"), capacity: Bh });
var Cd = dd.extend({ ftype: Wa.literal("simple_inductor"), inductance: wh, display_inductance: Wa.string().optional(), max_current_rating: Wa.number().optional() });
var Pd = dd.extend({ ftype: Wa.literal("simple_push_button") });
var Md = dd.extend({ ftype: Wa.literal("simple_potentiometer"), max_resistance: Ph, display_max_resistance: Wa.string().optional() });
var wd = dd.extend({ ftype: Wa.literal("simple_crystal"), frequency: Wa.number().describe("Frequency in Hz"), load_capacitance: Wa.number().optional().describe("Load capacitance in pF"), pin_variant: Wa.enum(["two_pin", "four_pin"]).optional() });
var Nd = dd.extend({ ftype: Wa.literal("simple_pin_header"), pin_count: Wa.number(), gender: Wa.enum(["male", "female"]).optional().default("male") });
var Rd = dd.extend({ ftype: Wa.literal("simple_connector"), standard: Wa.enum(["usb_c", "m2"]).optional() });
var Td = dd.extend({ ftype: Wa.literal("simple_pinout") });
var Ed = dd.extend({ ftype: Wa.literal("simple_resonator"), load_capacitance: Mh, equivalent_series_resistance: Ph.optional(), frequency: Th });
var Ad = dd.extend({ ftype: Wa.literal("simple_transistor"), transistor_type: Wa.enum(["npn", "pnp"]) });
var Od = dd.extend({ ftype: Wa.literal("simple_test_point"), footprint_variant: Wa.enum(["pad", "through_hole"]).optional(), pad_shape: Wa.enum(["rect", "circle"]).optional(), pad_diameter: Wa.union([Wa.number(), Wa.string()]).optional(), hole_diameter: Wa.union([Wa.number(), Wa.string()]).optional(), width: Wa.union([Wa.number(), Wa.string()]).optional(), height: Wa.union([Wa.number(), Wa.string()]).optional() });
var kd = dd.extend({ ftype: Wa.literal("simple_mosfet"), channel_type: Wa.enum(["n", "p"]), mosfet_mode: Wa.enum(["enhancement", "depletion"]) });
var Dd = dd.extend({ ftype: Wa.literal("simple_op_amp") });
var Ld = dd.extend({ ftype: Wa.literal("simple_switch") });
var zd = Wa.object({ type: Wa.literal("source_project_metadata"), name: Wa.string().optional(), software_used_string: Wa.string().optional(), project_url: Wa.string().optional(), created_at: Lh.optional() });
var Bd = ld.extend({ type: Wa.literal("source_missing_property_error"), source_missing_property_error_id: Hh("source_missing_property_error"), source_component_id: Wa.string(), property_name: Wa.string(), subcircuit_id: Wa.string().optional(), error_type: Wa.literal("source_missing_property_error").default("source_missing_property_error") }).describe("The source code is missing a property");
var Fd = ld.extend({ type: Wa.literal("source_failed_to_create_component_error"), source_failed_to_create_component_error_id: Hh("source_failed_to_create_component_error"), error_type: Wa.literal("source_failed_to_create_component_error").default("source_failed_to_create_component_error"), component_name: Wa.string().optional(), subcircuit_id: Wa.string().optional(), parent_source_component_id: Wa.string().optional(), pcb_center: Wa.object({ x: Wa.number().optional(), y: Wa.number().optional() }).optional(), schematic_center: Wa.object({ x: Wa.number().optional(), y: Wa.number().optional() }).optional() }).describe("Error emitted when a component fails to be constructed");
var jd = ld.extend({ type: Wa.literal("source_invalid_component_property_error"), source_invalid_component_property_error_id: Hh("source_invalid_component_property_error"), source_component_id: Wa.string(), property_name: Wa.string(), property_value: Wa.unknown().optional(), expected_format: Wa.string().optional(), subcircuit_id: Wa.string().optional(), error_type: Wa.literal("source_invalid_component_property_error").default("source_invalid_component_property_error") }).describe("The source component property is invalid");
var $d = ld.extend({ type: Wa.literal("source_trace_not_connected_error"), source_trace_not_connected_error_id: Hh("source_trace_not_connected_error"), error_type: Wa.literal("source_trace_not_connected_error").default("source_trace_not_connected_error"), subcircuit_id: Wa.string().optional(), source_group_id: Wa.string().optional(), source_trace_id: Wa.string().optional(), connected_source_port_ids: Wa.array(Wa.string()).optional(), selectors_not_found: Wa.array(Wa.string()).optional() }).describe("Occurs when a source trace selector does not match any ports");
var Yd = Wa.object({ type: Wa.literal("source_property_ignored_warning"), source_property_ignored_warning_id: Hh("source_property_ignored_warning"), source_component_id: Wa.string(), property_name: Wa.string(), subcircuit_id: Wa.string().optional(), error_type: Wa.literal("source_property_ignored_warning").default("source_property_ignored_warning"), message: Wa.string() }).describe("The source property was ignored");
var Xd = Wa.object({ type: Wa.literal("source_pin_missing_trace_warning"), source_pin_missing_trace_warning_id: Hh("source_pin_missing_trace_warning"), warning_type: Wa.literal("source_pin_missing_trace_warning").default("source_pin_missing_trace_warning"), message: Wa.string(), source_component_id: Wa.string(), source_port_id: Wa.string(), subcircuit_id: Wa.string().optional() }).describe("Warning emitted when a source component pin is missing a trace connection");
var Hd = Wa.object({ type: Wa.literal("source_missing_manufacturer_part_number_warning"), source_missing_manufacturer_part_number_warning_id: Hh("source_missing_manufacturer_part_number_warning"), warning_type: Wa.literal("source_missing_manufacturer_part_number_warning").default("source_missing_manufacturer_part_number_warning"), message: Wa.string(), source_component_id: Wa.string(), standard: Wa.string(), subcircuit_id: Wa.string().optional() }).describe("Warning emitted when a standard connector is missing manufacturer part number");
var Vd = dd.extend({ ftype: Wa.literal("simple_voltage_probe") });
var Wd = dd.extend({ ftype: Wa.literal("interconnect") });
var Gd = ld.extend({ type: Wa.literal("source_i2c_misconfigured_error"), source_i2c_misconfigured_error_id: Hh("source_i2c_misconfigured_error"), error_type: Wa.literal("source_i2c_misconfigured_error").default("source_i2c_misconfigured_error"), source_port_ids: Wa.array(Wa.string()) }).describe("Error emitted when incompatible I2C pins (e.g. SDA and SCL) are connected to the same net");
var Ud = dd.extend({ ftype: Wa.literal("simple_voltage_source"), voltage: Nh, frequency: Th.optional(), peak_to_peak_voltage: Nh.optional(), wave_shape: Wa.enum(["sinewave", "square", "triangle", "sawtooth"]).optional(), phase: zh.optional(), duty_cycle: Wa.number().optional().describe("Duty cycle as a fraction (0 to 1)") });
var Zd = Wa.union([pd, ud, md, gd, fd, _d, yd, bd, xd, Sd, Cd, Pd, Md, wd, Nd, Rd, Td, Ed, Ld, Ad, Od, kd, Dd, Id, Vd, Wd, Ud, zd, Bd, jd, Fd, $d, Yd, Xd, Hd, Gd]);
var qd = Wa.object({ type: Wa.literal("source_port"), pin_number: Wa.number().optional(), port_hints: Wa.array(Wa.string()).optional(), name: Wa.string(), source_port_id: Wa.string(), source_component_id: Wa.string().optional(), source_group_id: Wa.string().optional(), most_frequently_referenced_by_name: Wa.string().optional(), subcircuit_id: Wa.string().optional(), subcircuit_connectivity_map_key: Wa.string().optional() }).merge(vd);
var Jd = Wa.object({ type: Wa.literal("source_component_internal_connection"), source_component_internal_connection_id: Wa.string(), source_component_id: Wa.string(), source_port_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() });
var Qd = Wa.object({ type: Wa.literal("source_trace"), source_trace_id: Wa.string(), connected_source_port_ids: Wa.array(Wa.string()), connected_source_net_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional(), subcircuit_connectivity_map_key: Wa.string().optional(), max_length: Wa.number().optional(), min_trace_thickness: Wa.number().optional(), display_name: Wa.string().optional() });
var Kd = Wa.object({ type: Wa.literal("source_group"), source_group_id: Wa.string(), subcircuit_id: Wa.string().optional(), parent_subcircuit_id: Wa.string().optional(), parent_source_group_id: Wa.string().optional(), is_subcircuit: Wa.boolean().optional(), show_as_schematic_box: Wa.boolean().optional(), name: Wa.string().optional(), was_automatically_named: Wa.boolean().optional() });
var eu = Wa.object({ type: Wa.literal("source_net"), source_net_id: Wa.string(), name: Wa.string(), member_source_group_ids: Wa.array(Wa.string()), is_power: Wa.boolean().optional(), is_ground: Wa.boolean().optional(), is_digital_signal: Wa.boolean().optional(), is_analog_signal: Wa.boolean().optional(), is_positive_voltage_source: Wa.boolean().optional(), trace_width: Wa.number().optional(), subcircuit_id: Wa.string().optional(), subcircuit_connectivity_map_key: Wa.string().optional() });
var tu = Wa.object({ type: Wa.literal("source_board"), source_board_id: Wa.string(), source_group_id: Wa.string(), title: Wa.string().optional() }).describe("Defines a board in the source domain");
var nu = ld.extend({ type: Wa.literal("source_ambiguous_port_reference"), source_ambiguous_port_reference_id: Hh("source_ambiguous_port_reference"), error_type: Wa.literal("source_ambiguous_port_reference").default("source_ambiguous_port_reference"), source_port_id: Wa.string().optional(), source_component_id: Wa.string().optional() }).describe("Error emitted when a port hint matches multiple non-overlapping pads, making the port reference ambiguous");
var ou = Wa.object({ type: Wa.literal("source_pcb_ground_plane"), source_pcb_ground_plane_id: Wa.string(), source_group_id: Wa.string(), source_net_id: Wa.string(), subcircuit_id: Wa.string().optional() }).describe("Defines a ground plane in the source domain");
var iu = ["top", "bottom", "inner1", "inner2", "inner3", "inner4", "inner5", "inner6"];
var ru = Wa.enum(iu);
var su = ru.or(Wa.object({ name: ru })).transform((e20) => typeof e20 == "string" ? e20 : e20.name);
var au = Wa.enum(["top", "bottom"]);
var cu = Wa.object({ type: Wa.literal("source_manually_placed_via"), source_manually_placed_via_id: Wa.string(), source_group_id: Wa.string(), source_net_id: Wa.string(), subcircuit_id: Wa.string().optional(), source_trace_id: Wa.string().optional() }).describe("Defines a via that is manually placed in the source domain");
var lu = Wa.object({ type: Wa.literal("source_no_power_pin_defined_warning"), source_no_power_pin_defined_warning_id: Hh("source_no_power_pin_defined_warning"), warning_type: Wa.literal("source_no_power_pin_defined_warning").default("source_no_power_pin_defined_warning"), message: Wa.string(), source_component_id: Wa.string(), source_port_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe("Warning emitted when a chip has no source ports with requires_power=true");
var hu = Wa.object({ type: Wa.literal("source_no_ground_pin_defined_warning"), source_no_ground_pin_defined_warning_id: Hh("source_no_ground_pin_defined_warning"), warning_type: Wa.literal("source_no_ground_pin_defined_warning").default("source_no_ground_pin_defined_warning"), message: Wa.string(), source_component_id: Wa.string(), source_port_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe("Warning emitted when a chip has no source ports marked as ground pins");
var du = Wa.object({ type: Wa.literal("source_component_pins_underspecified_warning"), source_component_pins_underspecified_warning_id: Hh("source_component_pins_underspecified_warning"), warning_type: Wa.literal("source_component_pins_underspecified_warning").default("source_component_pins_underspecified_warning"), message: Wa.string(), source_component_id: Wa.string(), source_port_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe("Warning emitted when all ports on a source component are underspecified");
var uu = ld.extend({ type: Wa.literal("source_pin_must_be_connected_error"), source_pin_must_be_connected_error_id: Hh("source_pin_must_be_connected_error"), error_type: Wa.literal("source_pin_must_be_connected_error").default("source_pin_must_be_connected_error"), source_component_id: Wa.string(), source_port_id: Wa.string(), subcircuit_id: Wa.string().optional() }).describe("Error emitted when a pin with mustBeConnected attribute is not connected to any trace");
var pu = ld.extend({ type: Wa.literal("unknown_error_finding_part"), unknown_error_finding_part_id: Hh("unknown_error_finding_part"), error_type: Wa.literal("unknown_error_finding_part").default("unknown_error_finding_part"), source_component_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe("Error emitted when an unexpected error occurs while finding a part");
var mu = Wa.object({ type: Wa.literal("schematic_box"), schematic_component_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), width: Eh, height: Eh, is_dashed: Wa.boolean().default(false), x: Eh, y: Eh, subcircuit_id: Wa.string().optional() }).describe("Draws a box on the schematic");
var gu = Wa.object({ type: Wa.literal("schematic_path"), schematic_path_id: Hh("schematic_path"), schematic_component_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), fill_color: Wa.string().optional(), is_filled: Wa.boolean().optional(), stroke_width: Eh.nullable().optional(), stroke_color: Wa.string().optional(), points: Wa.array(Fh), subcircuit_id: Wa.string().optional() });
var fu = Wa.record(Wa.object({ left_margin: Rh.optional(), right_margin: Rh.optional(), top_margin: Rh.optional(), bottom_margin: Rh.optional() }));
var _u = Wa.object({ left_size: Wa.number(), right_size: Wa.number(), top_size: Wa.number().optional(), bottom_size: Wa.number().optional() });
var yu = Wa.object({ left_side: Wa.object({ pins: Wa.array(Wa.number()), direction: Wa.enum(["top-to-bottom", "bottom-to-top"]).optional() }).optional(), right_side: Wa.object({ pins: Wa.array(Wa.number()), direction: Wa.enum(["top-to-bottom", "bottom-to-top"]).optional() }).optional(), top_side: Wa.object({ pins: Wa.array(Wa.number()), direction: Wa.enum(["left-to-right", "right-to-left"]).optional() }).optional(), bottom_side: Wa.object({ pins: Wa.array(Wa.number()), direction: Wa.enum(["left-to-right", "right-to-left"]).optional() }).optional() });
var bu = Wa.union([_u, yu]);
var xu = Wa.object({ type: Wa.literal("schematic_component"), size: Xh, center: Fh, source_component_id: Wa.string().optional(), schematic_component_id: Wa.string(), schematic_symbol_id: Wa.string().optional(), pin_spacing: Rh.optional(), pin_styles: fu.optional(), box_width: Rh.optional(), symbol_name: Wa.string().optional(), port_arrangement: bu.optional(), port_labels: Wa.record(Wa.string()).optional(), symbol_display_value: Wa.string().optional(), subcircuit_id: Wa.string().optional(), schematic_group_id: Wa.string().optional(), is_schematic_group: Wa.boolean().optional(), source_group_id: Wa.string().optional(), is_box_with_pins: Wa.boolean().optional().default(true) });
var vu = Wa.object({ kicad_symbol: cd.optional() }).catchall(Wa.unknown());
var Iu = Wa.object({ type: Wa.literal("schematic_symbol"), schematic_symbol_id: Wa.string(), name: Wa.string().optional(), metadata: vu.optional() }).describe("Defines a named schematic symbol that can be referenced by components.");
var Su = Wa.object({ type: Wa.literal("schematic_line"), schematic_line_id: Hh("schematic_line"), schematic_component_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), x1: Eh, y1: Eh, x2: Eh, y2: Eh, stroke_width: Eh.nullable().optional(), color: Wa.string().default("#000000"), is_dashed: Wa.boolean().default(false), subcircuit_id: Wa.string().optional() }).describe("Draws a styled line on the schematic");
var Cu = Wa.object({ type: Wa.literal("schematic_rect"), schematic_rect_id: Hh("schematic_rect"), schematic_component_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), center: Fh, width: Eh, height: Eh, rotation: zh.default(0), stroke_width: Eh.nullable().optional(), color: Wa.string().default("#000000"), is_filled: Wa.boolean().default(false), fill_color: Wa.string().optional(), is_dashed: Wa.boolean().default(false), subcircuit_id: Wa.string().optional() }).describe("Draws a styled rectangle on the schematic");
var Pu = Wa.object({ type: Wa.literal("schematic_circle"), schematic_circle_id: Hh("schematic_circle"), schematic_component_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), center: Fh, radius: Eh, stroke_width: Eh.nullable().optional(), color: Wa.string().default("#000000"), is_filled: Wa.boolean().default(false), fill_color: Wa.string().optional(), is_dashed: Wa.boolean().default(false), subcircuit_id: Wa.string().optional() }).describe("Draws a styled circle on the schematic");
var Mu = Wa.object({ type: Wa.literal("schematic_arc"), schematic_arc_id: Hh("schematic_arc"), schematic_component_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), center: Fh, radius: Eh, start_angle_degrees: zh, end_angle_degrees: zh, direction: Wa.enum(["clockwise", "counterclockwise"]).default("counterclockwise"), stroke_width: Eh.nullable().optional(), color: Wa.string().default("#000000"), is_dashed: Wa.boolean().default(false), subcircuit_id: Wa.string().optional() }).describe("Draws a styled arc on the schematic");
var wu = Wa.object({ type: Wa.literal("schematic_trace"), schematic_trace_id: Wa.string(), source_trace_id: Wa.string().optional(), junctions: Wa.array(Wa.object({ x: Wa.number(), y: Wa.number() })), edges: Wa.array(Wa.object({ from: Wa.object({ x: Wa.number(), y: Wa.number() }), to: Wa.object({ x: Wa.number(), y: Wa.number() }), is_crossing: Wa.boolean().optional(), from_schematic_port_id: Wa.string().optional(), to_schematic_port_id: Wa.string().optional() })), subcircuit_id: Wa.string().optional(), subcircuit_connectivity_map_key: Wa.string().optional() });
var Nu = Wa.enum(["center", "left", "right", "top", "bottom"]);
var Ru = Wa.object({ type: Wa.literal("schematic_text"), schematic_component_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), schematic_text_id: Wa.string(), text: Wa.string(), font_size: Wa.number().default(0.18), position: Wa.object({ x: Eh, y: Eh }), rotation: Wa.number().default(0), anchor: Wa.union([Nu.describe("legacy"), Vh]).default("center"), color: Wa.string().default("#000000"), subcircuit_id: Wa.string().optional() });
var Tu = Wa.object({ type: Wa.literal("schematic_port"), schematic_port_id: Wa.string(), source_port_id: Wa.string(), schematic_component_id: Wa.string().optional(), center: Fh, facing_direction: Wa.enum(["up", "down", "left", "right"]).optional(), distance_from_component_edge: Wa.number().optional(), side_of_component: Wa.enum(["top", "bottom", "left", "right"]).optional(), true_ccw_index: Wa.number().optional(), pin_number: Wa.number().optional(), display_pin_label: Wa.string().optional(), subcircuit_id: Wa.string().optional(), is_connected: Wa.boolean().optional(), has_input_arrow: Wa.boolean().optional(), has_output_arrow: Wa.boolean().optional(), is_drawn_with_inversion_circle: Wa.boolean().optional() }).describe("Defines a port on a schematic component");
var Eu = Wa.object({ type: Wa.literal("schematic_net_label"), schematic_net_label_id: Hh("schematic_net_label"), schematic_trace_id: Wa.string().optional(), source_trace_id: Wa.string().optional(), source_net_id: Wa.string(), center: Fh, anchor_position: Fh.optional(), anchor_side: Wa.enum(["top", "bottom", "left", "right"]), text: Wa.string(), symbol_name: Wa.string().optional(), is_movable: Wa.boolean().optional(), subcircuit_id: Wa.string().optional() });
var Au = ld.extend({ type: Wa.literal("schematic_error"), schematic_error_id: Wa.string(), error_type: Wa.literal("schematic_port_not_found").default("schematic_port_not_found"), subcircuit_id: Wa.string().optional() }).describe("Defines a schematic error on the schematic");
var Ou = ld.extend({ type: Wa.literal("schematic_layout_error"), schematic_layout_error_id: Hh("schematic_layout_error"), error_type: Wa.literal("schematic_layout_error").default("schematic_layout_error"), source_group_id: Wa.string(), schematic_group_id: Wa.string(), subcircuit_id: Wa.string().optional() }).describe("Error emitted when schematic layout fails for a group");
var ku = Wa.object({ type: Wa.literal("schematic_debug_object"), label: Wa.string().optional(), subcircuit_id: Wa.string().optional() });
var Du = ku.extend({ shape: Wa.literal("rect"), center: Fh, size: Xh });
var Lu = ku.extend({ shape: Wa.literal("line"), start: Fh, end: Fh });
var zu = ku.extend({ shape: Wa.literal("point"), center: Fh });
var Bu = Wa.discriminatedUnion("shape", [Du, Lu, zu]);
var Fu = Wa.object({ type: Wa.literal("schematic_voltage_probe"), schematic_voltage_probe_id: Wa.string(), source_component_id: Wa.string().optional(), name: Wa.string().optional(), position: Fh, schematic_trace_id: Wa.string(), voltage: Nh.optional(), subcircuit_id: Wa.string().optional(), color: Wa.string().optional(), label_alignment: Vh.optional() }).describe("Defines a voltage probe measurement point on a schematic trace");
var ju = Wa.object({ type: Wa.literal("schematic_manual_edit_conflict_warning"), schematic_manual_edit_conflict_warning_id: Hh("schematic_manual_edit_conflict_warning"), warning_type: Wa.literal("schematic_manual_edit_conflict_warning").default("schematic_manual_edit_conflict_warning"), message: Wa.string(), schematic_component_id: Wa.string(), schematic_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), source_component_id: Wa.string() }).describe("Warning emitted when a component has both manual placement and explicit schX/schY coordinates");
var $u = Wa.object({ type: Wa.literal("schematic_group"), schematic_group_id: Hh("schematic_group"), source_group_id: Wa.string(), is_subcircuit: Wa.boolean().optional(), subcircuit_id: Wa.string().optional(), width: Rh, height: Rh, center: Fh, schematic_component_ids: Wa.array(Wa.string()), show_as_schematic_box: Wa.boolean().optional(), name: Wa.string().optional(), description: Wa.string().optional() }).describe("Defines a group of components on the schematic");
var Yu = Wa.object({ type: Wa.literal("schematic_table"), schematic_table_id: Hh("schematic_table"), anchor_position: Fh, column_widths: Wa.array(Eh), row_heights: Wa.array(Eh), cell_padding: Eh.optional(), border_width: Eh.optional(), subcircuit_id: Wa.string().optional(), schematic_component_id: Wa.string().optional(), anchor: Vh.optional() }).describe("Defines a table on the schematic");
var Xu = Wa.object({ type: Wa.literal("schematic_table_cell"), schematic_table_cell_id: Hh("schematic_table_cell"), schematic_table_id: Wa.string(), start_row_index: Wa.number(), end_row_index: Wa.number(), start_column_index: Wa.number(), end_column_index: Wa.number(), text: Wa.string().optional(), center: Fh, width: Eh, height: Eh, horizontal_align: Wa.enum(["left", "center", "right"]).optional(), vertical_align: Wa.enum(["top", "middle", "bottom"]).optional(), font_size: Eh.optional(), subcircuit_id: Wa.string().optional() }).describe("Defines a cell within a schematic_table");
var Hu = Wa.object({ type: Wa.literal("schematic_sheet"), schematic_sheet_id: Hh("schematic_sheet"), name: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe("Defines a schematic sheet or page that components can be placed on");
var Vu = Wa.object({ x: Eh, y: Eh, bulge: Wa.number().optional() });
var Wu = Wa.object({ vertices: Wa.array(Vu) });
var Gu = Wa.object({ outer_ring: Wu, inner_rings: Wa.array(Wu).default([]) });
var Uu = Wa.object({ x: Eh, y: Eh, via: Wa.boolean().optional(), via_to_layer: su.optional() });
var Zu = Wa.array(Uu);
var qu = Wa.object({ x: Eh, y: Eh, via: Wa.boolean().optional(), to_layer: su.optional(), trace_width: Eh.optional() });
var Ju = Wa.object({ min_trace_width: Rh.optional(), min_board_edge_clearance: Rh.optional(), min_via_hole_edge_to_via_hole_edge_clearance: Rh.optional(), min_plated_hole_drill_edge_to_drill_edge_clearance: Rh.optional(), min_trace_to_pad_edge_clearance: Rh.optional(), min_pad_edge_to_pad_edge_clearance: Rh.optional(), min_same_net_trace_edge_to_trace_edge_clearance: Rh.optional(), min_different_net_trace_edge_to_trace_edge_clearance: Rh.optional(), min_via_hole_diameter: Rh.optional(), min_via_pad_diameter: Rh.optional() });
var Qu = Wa.object({ type: Wa.literal("pcb_component"), pcb_component_id: Hh("pcb_component"), source_component_id: Wa.string(), center: Fh, layer: su, rotation: zh, display_offset_x: Wa.string().optional().describe("How to display the x offset for this part, usually corresponding with how the user specified it"), display_offset_y: Wa.string().optional().describe("How to display the y offset for this part, usually corresponding with how the user specified it"), width: Rh, height: Rh, do_not_place: Wa.boolean().optional(), is_allowed_to_be_off_board: Wa.boolean().optional(), subcircuit_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), position_mode: Wa.enum(["packed", "relative_to_group_anchor", "relative_to_another_component", "none"]).optional(), anchor_position: Fh.optional(), anchor_alignment: Vh.optional(), positioned_relative_to_pcb_group_id: Wa.string().optional(), positioned_relative_to_pcb_board_id: Wa.string().optional(), cable_insertion_center: Fh.optional(), insertion_direction: Wa.enum(["from_above", "from_left", "from_right", "from_front", "from_back"]).optional(), metadata: Wa.object({ kicad_footprint: nd.optional() }).optional(), obstructs_within_bounds: Wa.boolean().default(true).describe("Does this component take up all the space within its bounds on a layer. This is generally true except for when separated pin headers are being represented by a single component (in which case, chips can be placed between the pin headers) or for tall modules where chips fit underneath") }).describe("Defines a component on the PCB");
var Ku = Wa.object({ type: Wa.literal("pcb_hole"), pcb_hole_id: Hh("pcb_hole"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), pcb_component_id: Wa.string().optional(), hole_shape: Wa.literal("circle"), hole_diameter: Wa.number(), x: Eh, y: Eh, is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });
var ep = Ku.describe("Defines a circular hole on the PCB");
var tp = Wa.object({ type: Wa.literal("pcb_hole"), pcb_hole_id: Hh("pcb_hole"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), pcb_component_id: Wa.string().optional(), hole_shape: Wa.literal("rect"), hole_width: Wa.number(), hole_height: Wa.number(), x: Eh, y: Eh, is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });
var np = tp.describe("Defines a rectangular (square-capable) hole on the PCB. Use equal width/height for square.");
var op = Wa.object({ type: Wa.literal("pcb_hole"), pcb_hole_id: Hh("pcb_hole"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), pcb_component_id: Wa.string().optional(), hole_shape: Wa.enum(["circle", "square"]), hole_diameter: Wa.number(), x: Eh, y: Eh, is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });
var ip = op.describe("Defines a circular or square hole on the PCB");
var rp = Wa.object({ type: Wa.literal("pcb_hole"), pcb_hole_id: Hh("pcb_hole"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), pcb_component_id: Wa.string().optional(), hole_shape: Wa.literal("oval"), hole_width: Wa.number(), hole_height: Wa.number(), x: Eh, y: Eh, is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });
var sp = rp.describe("Defines an oval hole on the PCB");
var ap = Wa.object({ type: Wa.literal("pcb_hole"), pcb_hole_id: Hh("pcb_hole"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), pcb_component_id: Wa.string().optional(), hole_shape: Wa.literal("pill"), hole_width: Wa.number(), hole_height: Wa.number(), x: Eh, y: Eh, is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });
var cp = ap.describe("Defines a pill-shaped hole on the PCB");
var lp = Wa.object({ type: Wa.literal("pcb_hole"), pcb_hole_id: Hh("pcb_hole"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), pcb_component_id: Wa.string().optional(), hole_shape: Wa.literal("rotated_pill"), hole_width: Wa.number(), hole_height: Wa.number(), x: Eh, y: Eh, ccw_rotation: zh, is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });
var hp = lp.describe("Defines a rotated pill-shaped hole on the PCB");
var dp = op.or(rp).or(ap).or(lp).or(Ku).or(tp);
var up = Wa.object({ type: Wa.literal("pcb_plated_hole"), shape: Wa.literal("circle"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), outer_diameter: Wa.number(), hole_diameter: Wa.number(), is_covered_with_solder_mask: Wa.boolean().optional(), x: Eh, y: Eh, layers: Wa.array(su), port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), pcb_plated_hole_id: Hh("pcb_plated_hole"), soldermask_margin: Wa.number().optional() });
var pp = Wa.object({ type: Wa.literal("pcb_plated_hole"), shape: Wa.enum(["oval", "pill"]), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), outer_width: Wa.number(), outer_height: Wa.number(), hole_width: Wa.number(), hole_height: Wa.number(), is_covered_with_solder_mask: Wa.boolean().optional(), x: Eh, y: Eh, ccw_rotation: zh, layers: Wa.array(su), port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), pcb_plated_hole_id: Hh("pcb_plated_hole"), soldermask_margin: Wa.number().optional() });
var mp = Wa.object({ type: Wa.literal("pcb_plated_hole"), shape: Wa.literal("circular_hole_with_rect_pad"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), hole_shape: Wa.literal("circle"), pad_shape: Wa.literal("rect"), hole_diameter: Wa.number(), rect_pad_width: Wa.number(), rect_pad_height: Wa.number(), rect_border_radius: Wa.number().optional(), hole_offset_x: Eh.default(0), hole_offset_y: Eh.default(0), is_covered_with_solder_mask: Wa.boolean().optional(), x: Eh, y: Eh, layers: Wa.array(su), port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), pcb_plated_hole_id: Hh("pcb_plated_hole"), soldermask_margin: Wa.number().optional(), rect_ccw_rotation: zh.optional() });
var gp = Wa.object({ type: Wa.literal("pcb_plated_hole"), shape: Wa.literal("pill_hole_with_rect_pad"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), hole_shape: Wa.literal("pill"), pad_shape: Wa.literal("rect"), hole_width: Wa.number(), hole_height: Wa.number(), rect_pad_width: Wa.number(), rect_pad_height: Wa.number(), rect_border_radius: Wa.number().optional(), hole_offset_x: Eh.default(0), hole_offset_y: Eh.default(0), is_covered_with_solder_mask: Wa.boolean().optional(), x: Eh, y: Eh, layers: Wa.array(su), port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), pcb_plated_hole_id: Hh("pcb_plated_hole"), soldermask_margin: Wa.number().optional() });
var fp = Wa.object({ type: Wa.literal("pcb_plated_hole"), shape: Wa.literal("rotated_pill_hole_with_rect_pad"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), hole_shape: Wa.literal("rotated_pill"), pad_shape: Wa.literal("rect"), hole_width: Wa.number(), hole_height: Wa.number(), hole_ccw_rotation: zh, rect_pad_width: Wa.number(), rect_pad_height: Wa.number(), rect_border_radius: Wa.number().optional(), rect_ccw_rotation: zh, hole_offset_x: Eh.default(0), hole_offset_y: Eh.default(0), is_covered_with_solder_mask: Wa.boolean().optional(), x: Eh, y: Eh, layers: Wa.array(su), port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), pcb_plated_hole_id: Hh("pcb_plated_hole"), soldermask_margin: Wa.number().optional() });
var _p = Wa.object({ type: Wa.literal("pcb_plated_hole"), shape: Wa.literal("hole_with_polygon_pad"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), hole_shape: Wa.enum(["circle", "oval", "pill", "rotated_pill"]), hole_diameter: Wa.number().optional(), hole_width: Wa.number().optional(), hole_height: Wa.number().optional(), pad_outline: Wa.array(Wa.object({ x: Eh, y: Eh })).min(3), hole_offset_x: Eh.default(0), hole_offset_y: Eh.default(0), is_covered_with_solder_mask: Wa.boolean().optional(), x: Eh, y: Eh, layers: Wa.array(su), port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), pcb_plated_hole_id: Hh("pcb_plated_hole"), soldermask_margin: Wa.number().optional(), ccw_rotation: zh.optional() });
var yp = Wa.union([up, pp, mp, gp, fp, _p]);
var bp = Wa.object({ type: Wa.literal("pcb_port"), pcb_port_id: Hh("pcb_port"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), source_port_id: Wa.string(), pcb_component_id: Wa.string().optional(), x: Eh, y: Eh, layers: Wa.array(su), is_board_pinout: Wa.boolean().optional() }).describe("Defines a port on the PCB");
var xp = Wa.object({ type: Wa.literal("pcb_smtpad"), shape: Wa.literal("circle"), pcb_smtpad_id: Hh("pcb_smtpad"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: Eh, y: Eh, radius: Wa.number(), layer: su, port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });
var vp = Wa.object({ type: Wa.literal("pcb_smtpad"), shape: Wa.literal("rect"), pcb_smtpad_id: Hh("pcb_smtpad"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: Eh, y: Eh, width: Wa.number(), height: Wa.number(), rect_border_radius: Wa.number().optional(), corner_radius: Wa.number().optional(), layer: su, port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional(), soldermask_margin_left: Wa.number().optional(), soldermask_margin_top: Wa.number().optional(), soldermask_margin_right: Wa.number().optional(), soldermask_margin_bottom: Wa.number().optional() });
var Ip = Wa.object({ type: Wa.literal("pcb_smtpad"), shape: Wa.literal("rotated_rect"), pcb_smtpad_id: Hh("pcb_smtpad"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: Eh, y: Eh, width: Wa.number(), height: Wa.number(), rect_border_radius: Wa.number().optional(), corner_radius: Wa.number().optional(), ccw_rotation: zh, layer: su, port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional(), soldermask_margin_left: Wa.number().optional(), soldermask_margin_top: Wa.number().optional(), soldermask_margin_right: Wa.number().optional(), soldermask_margin_bottom: Wa.number().optional() });
var Sp = Wa.object({ type: Wa.literal("pcb_smtpad"), shape: Wa.literal("pill"), pcb_smtpad_id: Hh("pcb_smtpad"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: Eh, y: Eh, width: Wa.number(), height: Wa.number(), radius: Wa.number(), layer: su, port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });
var Cp = Wa.object({ type: Wa.literal("pcb_smtpad"), shape: Wa.literal("rotated_pill"), pcb_smtpad_id: Hh("pcb_smtpad"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: Eh, y: Eh, width: Wa.number(), height: Wa.number(), radius: Wa.number(), ccw_rotation: zh, layer: su, port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });
var Pp = Wa.object({ type: Wa.literal("pcb_smtpad"), shape: Wa.literal("polygon"), pcb_smtpad_id: Hh("pcb_smtpad"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), points: Wa.array(Fh), layer: su, port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });
var Mp = Wa.discriminatedUnion("shape", [xp, vp, Ip, Cp, Sp, Pp]).describe("Defines an SMT pad on the PCB");
var wp = Wa.object({ type: Wa.literal("pcb_solder_paste"), shape: Wa.literal("circle"), pcb_solder_paste_id: Hh("pcb_solder_paste"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: Eh, y: Eh, radius: Wa.number(), layer: su, pcb_component_id: Wa.string().optional(), pcb_smtpad_id: Wa.string().optional() });
var Np = Wa.object({ type: Wa.literal("pcb_solder_paste"), shape: Wa.literal("rect"), pcb_solder_paste_id: Hh("pcb_solder_paste"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: Eh, y: Eh, width: Wa.number(), height: Wa.number(), layer: su, pcb_component_id: Wa.string().optional(), pcb_smtpad_id: Wa.string().optional() });
var Rp = Wa.object({ type: Wa.literal("pcb_solder_paste"), shape: Wa.literal("pill"), pcb_solder_paste_id: Hh("pcb_solder_paste"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: Eh, y: Eh, width: Wa.number(), height: Wa.number(), radius: Wa.number(), layer: su, pcb_component_id: Wa.string().optional(), pcb_smtpad_id: Wa.string().optional() });
var Tp = Wa.object({ type: Wa.literal("pcb_solder_paste"), shape: Wa.literal("rotated_rect"), pcb_solder_paste_id: Hh("pcb_solder_paste"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: Eh, y: Eh, width: Wa.number(), height: Wa.number(), ccw_rotation: Eh, layer: su, pcb_component_id: Wa.string().optional(), pcb_smtpad_id: Wa.string().optional() });
var Ep = Wa.object({ type: Wa.literal("pcb_solder_paste"), shape: Wa.literal("oval"), pcb_solder_paste_id: Hh("pcb_solder_paste"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: Eh, y: Eh, width: Wa.number(), height: Wa.number(), layer: su, pcb_component_id: Wa.string().optional(), pcb_smtpad_id: Wa.string().optional() });
var Ap = Wa.union([wp, Np, Rp, Tp, Ep]).describe("Defines solderpaste on the PCB");
var Op = Wa.object({ type: Wa.literal("pcb_text"), pcb_text_id: Hh("pcb_text"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), text: Wa.string(), center: Fh, layer: su, width: Rh, height: Rh, lines: Wa.number(), align: Wa.enum(["bottom-left"]) }).describe("Defines text on the PCB");
var kp = Wa.object({ route_type: Wa.literal("wire"), x: Eh, y: Eh, width: Eh, copper_pour_id: Wa.string().optional(), is_inside_copper_pour: Wa.boolean().optional(), start_pcb_port_id: Wa.string().optional(), end_pcb_port_id: Wa.string().optional(), layer: su });
var Dp = Wa.object({ route_type: Wa.literal("via"), x: Eh, y: Eh, copper_pour_id: Wa.string().optional(), is_inside_copper_pour: Wa.boolean().optional(), hole_diameter: Eh.optional(), outer_diameter: Eh.optional(), from_layer: su, to_layer: su });
var Lp = Wa.union([kp, Dp]);
var zp = Wa.object({ type: Wa.literal("pcb_trace"), source_trace_id: Wa.string().optional(), pcb_component_id: Wa.string().optional(), pcb_trace_id: Hh("pcb_trace"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), route_thickness_mode: Wa.enum(["constant", "interpolated"]).default("constant").optional(), route_order_index: Wa.number().optional(), should_round_corners: Wa.boolean().optional(), trace_length: Wa.number().optional(), highlight_color: Wa.string().optional(), route: Wa.array(Lp) }).describe("Defines a trace on the PCB");
var Bp = Wa.object({ type: Wa.literal("pcb_trace_warning"), pcb_trace_warning_id: Hh("pcb_trace_warning"), warning_type: Wa.literal("pcb_trace_warning").default("pcb_trace_warning"), message: Wa.string(), center: Fh.optional(), pcb_trace_id: Wa.string(), source_trace_id: Wa.string(), pcb_component_ids: Wa.array(Wa.string()), pcb_port_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe("Defines a trace warning on the PCB");
var Fp = ld.extend({ type: Wa.literal("pcb_trace_error"), pcb_trace_error_id: Hh("pcb_trace_error"), error_type: Wa.literal("pcb_trace_error").default("pcb_trace_error"), center: Fh.optional(), pcb_trace_id: Wa.string(), source_trace_id: Wa.string(), pcb_component_ids: Wa.array(Wa.string()), pcb_port_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe("Defines a trace error on the PCB");
var jp = ld.extend({ type: Wa.literal("pcb_trace_missing_error"), pcb_trace_missing_error_id: Hh("pcb_trace_missing_error"), error_type: Wa.literal("pcb_trace_missing_error").default("pcb_trace_missing_error"), center: Fh.optional(), source_trace_id: Wa.string(), pcb_component_ids: Wa.array(Wa.string()), pcb_port_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe("Defines an error when a source trace has no corresponding PCB trace");
var $p = ld.extend({ type: Wa.literal("pcb_port_not_matched_error"), pcb_error_id: Hh("pcb_error"), error_type: Wa.literal("pcb_port_not_matched_error").default("pcb_port_not_matched_error"), pcb_component_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe("Defines a trace error on the PCB where a port is not matched");
var Yp = ld.extend({ type: Wa.literal("pcb_port_not_connected_error"), pcb_port_not_connected_error_id: Hh("pcb_port_not_connected_error"), error_type: Wa.literal("pcb_port_not_connected_error").default("pcb_port_not_connected_error"), pcb_port_ids: Wa.array(Wa.string()), pcb_component_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe("Defines an error when a pcb port is not connected to any trace");
var Xp = Wa.object({ type: Wa.literal("pcb_net"), pcb_net_id: Hh("pcb_net"), source_net_id: Wa.string().optional(), highlight_color: Wa.string().optional() }).describe("Defines a net on the PCB");
var Hp = Wa.object({ type: Wa.literal("pcb_via"), pcb_via_id: Hh("pcb_via"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), subcircuit_connectivity_map_key: Wa.string().optional(), x: Eh, y: Eh, outer_diameter: Eh.default("0.6mm"), hole_diameter: Eh.default("0.25mm"), from_layer: su.optional(), to_layer: su.optional(), layers: Wa.array(su), pcb_trace_id: Wa.string().optional(), net_is_assignable: Wa.boolean().optional(), net_assigned: Wa.boolean().optional(), is_tented: Wa.boolean().optional() }).describe("Defines a via on the PCB");
var Vp = Wa.object({ type: Wa.literal("pcb_board"), pcb_board_id: Hh("pcb_board"), pcb_panel_id: Wa.string().optional(), carrier_pcb_board_id: Wa.string().optional(), is_subcircuit: Wa.boolean().optional(), subcircuit_id: Wa.string().optional(), is_mounted_to_carrier_board: Wa.boolean().optional(), width: Rh.optional(), height: Rh.optional(), center: Fh, display_offset_x: Wa.string().optional().describe("How to display the x offset for this board, usually corresponding with how the user specified it"), display_offset_y: Wa.string().optional().describe("How to display the y offset for this board, usually corresponding with how the user specified it"), thickness: Rh.optional().default(1.4), num_layers: Wa.number().optional().default(4), outline: Wa.array(Fh).optional(), shape: Wa.enum(["rect", "polygon"]).optional(), material: Wa.enum(["fr4", "fr1"]).default("fr4"), anchor_position: Fh.optional(), anchor_alignment: Vh.optional(), position_mode: Wa.enum(["relative_to_panel_anchor", "none"]).optional() }).merge(Ju).describe("Defines the board outline of the PCB");
var Wp = Wa.object({ type: Wa.literal("pcb_panel"), pcb_panel_id: Hh("pcb_panel"), width: Rh, height: Rh, center: Fh, thickness: Rh.optional().default(1.4), covered_with_solder_mask: Wa.boolean().optional().default(true) }).describe("Defines a PCB panel that can contain multiple boards");
var Gp = ld.extend({ type: Wa.literal("pcb_placement_error"), pcb_placement_error_id: Hh("pcb_placement_error"), error_type: Wa.literal("pcb_placement_error").default("pcb_placement_error"), subcircuit_id: Wa.string().optional() }).describe("Defines a placement error on the PCB");
var Up = ld.extend({ type: Wa.literal("pcb_panelization_placement_error"), pcb_panelization_placement_error_id: Hh("pcb_panelization_placement_error"), error_type: Wa.literal("pcb_panelization_placement_error").default("pcb_panelization_placement_error"), pcb_panel_id: Wa.string().optional(), pcb_board_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe("Defines a panelization placement error on the PCB");
var Zp = Wa.object({ type: Wa.literal("pcb_trace_hint"), pcb_trace_hint_id: Hh("pcb_trace_hint"), pcb_port_id: Wa.string(), pcb_component_id: Wa.string(), route: Wa.array(qu), subcircuit_id: Wa.string().optional() }).describe("A hint that can be used during generation of a PCB trace");
var qp = Wa.object({ type: Wa.literal("pcb_silkscreen_line"), pcb_silkscreen_line_id: Hh("pcb_silkscreen_line"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), stroke_width: Eh.default("0.1mm"), x1: Eh, y1: Eh, x2: Eh, y2: Eh, layer: au }).describe("Defines a silkscreen line on the PCB");
var Jp = Wa.object({ type: Wa.literal("pcb_silkscreen_path"), pcb_silkscreen_path_id: Hh("pcb_silkscreen_path"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), layer: au, route: Wa.array(Fh), stroke_width: Rh }).describe("Defines a silkscreen path on the PCB");
var Qp = Wa.object({ type: Wa.literal("pcb_silkscreen_text"), pcb_silkscreen_text_id: Hh("pcb_silkscreen_text"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), font: Wa.literal("tscircuit2024").default("tscircuit2024"), font_size: Eh.default("0.2mm"), pcb_component_id: Wa.string(), text: Wa.string(), is_knockout: Wa.boolean().default(false).optional(), knockout_padding: Wa.object({ left: Rh, top: Rh, bottom: Rh, right: Rh }).default({ left: "0.2mm", top: "0.2mm", bottom: "0.2mm", right: "0.2mm" }).optional(), ccw_rotation: Wa.number().optional(), layer: su, is_mirrored: Wa.boolean().default(false).optional(), anchor_position: Fh.default({ x: 0, y: 0 }), anchor_alignment: Vh.default("center") }).describe("Defines silkscreen text on the PCB");
var Kp = Wa.object({ type: Wa.literal("pcb_copper_text"), pcb_copper_text_id: Hh("pcb_copper_text"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), font: Wa.literal("tscircuit2024").default("tscircuit2024"), font_size: Eh.default("0.2mm"), pcb_component_id: Wa.string(), text: Wa.string(), is_knockout: Wa.boolean().default(false).optional(), knockout_padding: Wa.object({ left: Rh, top: Rh, bottom: Rh, right: Rh }).default({ left: "0.2mm", top: "0.2mm", bottom: "0.2mm", right: "0.2mm" }).optional(), ccw_rotation: Wa.number().optional(), layer: su, is_mirrored: Wa.boolean().default(false).optional(), anchor_position: Fh.default({ x: 0, y: 0 }), anchor_alignment: Vh.default("center") }).describe("Defines copper text on the PCB");
var em = Wa.object({ type: Wa.literal("pcb_silkscreen_rect"), pcb_silkscreen_rect_id: Hh("pcb_silkscreen_rect"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: Fh, width: Rh, height: Rh, layer: su, stroke_width: Rh.default("1mm"), corner_radius: Rh.optional(), is_filled: Wa.boolean().default(true).optional(), has_stroke: Wa.boolean().optional(), is_stroke_dashed: Wa.boolean().optional(), ccw_rotation: Wa.number().optional() }).describe("Defines a silkscreen rect on the PCB");
var tm = Wa.object({ type: Wa.literal("pcb_silkscreen_circle"), pcb_silkscreen_circle_id: Hh("pcb_silkscreen_circle"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: Fh, radius: Rh, layer: au, stroke_width: Rh.default("1mm"), is_filled: Wa.boolean().optional() }).describe("Defines a silkscreen circle on the PCB");
var nm = Wa.object({ type: Wa.literal("pcb_silkscreen_oval"), pcb_silkscreen_oval_id: Hh("pcb_silkscreen_oval"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: Fh, radius_x: Eh, radius_y: Eh, layer: au, ccw_rotation: zh.optional() }).describe("Defines a silkscreen oval on the PCB");
var om = Wa.object({ type: Wa.literal("pcb_silkscreen_pill"), pcb_silkscreen_pill_id: Hh("pcb_silkscreen_pill"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: Fh, width: Rh, height: Rh, layer: su, ccw_rotation: Wa.number().optional() }).describe("Defines a silkscreen pill on the PCB");
var im = Wa.object({ type: Wa.literal("pcb_fabrication_note_text"), pcb_fabrication_note_text_id: Hh("pcb_fabrication_note_text"), subcircuit_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), font: Wa.literal("tscircuit2024").default("tscircuit2024"), font_size: Eh.default("1mm"), pcb_component_id: Wa.string(), text: Wa.string(), layer: au, anchor_position: Fh.default({ x: 0, y: 0 }), anchor_alignment: Wa.enum(["center", "top_left", "top_right", "bottom_left", "bottom_right"]).default("center"), color: Wa.string().optional() }).describe("Defines a fabrication note in text on the PCB, useful for leaving notes for assemblers or fabricators");
var rm = Wa.object({ type: Wa.literal("pcb_fabrication_note_path"), pcb_fabrication_note_path_id: Hh("pcb_fabrication_note_path"), pcb_component_id: Wa.string(), subcircuit_id: Wa.string().optional(), layer: su, route: Wa.array(Fh), stroke_width: Rh, color: Wa.string().optional() }).describe("Defines a fabrication path on the PCB for fabricators or assemblers");
var sm = Wa.object({ type: Wa.literal("pcb_fabrication_note_rect"), pcb_fabrication_note_rect_id: Hh("pcb_fabrication_note_rect"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: Fh, width: Rh, height: Rh, layer: au, stroke_width: Rh.default("0.1mm"), corner_radius: Rh.optional(), is_filled: Wa.boolean().optional(), has_stroke: Wa.boolean().optional(), is_stroke_dashed: Wa.boolean().optional(), color: Wa.string().optional() }).describe("Defines a fabrication note rectangle on the PCB");
var am = Wa.object({ type: Wa.literal("pcb_fabrication_note_dimension"), pcb_fabrication_note_dimension_id: Hh("pcb_fabrication_note_dimension"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), layer: au, from: Fh, to: Fh, text: Wa.string().optional(), text_ccw_rotation: Wa.number().optional(), offset: Rh.optional(), offset_distance: Rh.optional(), offset_direction: Wa.object({ x: Wa.number(), y: Wa.number() }).optional(), font: Wa.literal("tscircuit2024").default("tscircuit2024"), font_size: Rh.default("1mm"), color: Wa.string().optional(), arrow_size: Rh.default("1mm") }).describe("Defines a measurement annotation within PCB fabrication notes");
var cm = Wa.object({ type: Wa.literal("pcb_note_text"), pcb_note_text_id: Hh("pcb_note_text"), pcb_component_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), name: Wa.string().optional(), font: Wa.literal("tscircuit2024").default("tscircuit2024"), font_size: Eh.default("1mm"), text: Wa.string().optional(), anchor_position: Fh.default({ x: 0, y: 0 }), anchor_alignment: Wa.enum(["center", "top_left", "top_right", "bottom_left", "bottom_right"]).default("center"), layer: au.default("top"), is_mirrored_from_top_view: Wa.boolean().optional(), color: Wa.string().optional() }).describe("Defines a documentation note in text on the PCB");
var lm = Wa.object({ type: Wa.literal("pcb_note_rect"), pcb_note_rect_id: Hh("pcb_note_rect"), pcb_component_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), name: Wa.string().optional(), text: Wa.string().optional(), center: Fh, width: Rh, height: Rh, layer: au.default("top"), stroke_width: Rh.default("0.1mm"), corner_radius: Rh.optional(), is_filled: Wa.boolean().optional(), has_stroke: Wa.boolean().optional(), is_stroke_dashed: Wa.boolean().optional(), color: Wa.string().optional() }).describe("Defines a rectangular documentation note on the PCB");
var hm = Wa.object({ type: Wa.literal("pcb_note_path"), pcb_note_path_id: Hh("pcb_note_path"), pcb_component_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), name: Wa.string().optional(), text: Wa.string().optional(), route: Wa.array(Fh), layer: au.default("top"), stroke_width: Rh.default("0.1mm"), color: Wa.string().optional() }).describe("Defines a polyline documentation note on the PCB");
var dm = Wa.object({ type: Wa.literal("pcb_note_line"), pcb_note_line_id: Hh("pcb_note_line"), pcb_component_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), name: Wa.string().optional(), text: Wa.string().optional(), x1: Eh, y1: Eh, x2: Eh, y2: Eh, layer: au.default("top"), stroke_width: Eh.default("0.1mm"), color: Wa.string().optional(), is_dashed: Wa.boolean().optional() }).describe("Defines a straight documentation note line on the PCB");
var um = Wa.object({ type: Wa.literal("pcb_note_dimension"), pcb_note_dimension_id: Hh("pcb_note_dimension"), pcb_component_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), name: Wa.string().optional(), from: Fh, to: Fh, text: Wa.string().optional(), text_ccw_rotation: Wa.number().optional(), offset_distance: Rh.optional(), offset_direction: Wa.object({ x: Wa.number(), y: Wa.number() }).optional(), font: Wa.literal("tscircuit2024").default("tscircuit2024"), font_size: Rh.default("1mm"), layer: au.default("top"), color: Wa.string().optional(), arrow_size: Rh.default("1mm") }).describe("Defines a measurement annotation within PCB documentation notes");
var pm = ld.extend({ type: Wa.literal("pcb_footprint_overlap_error"), pcb_error_id: Hh("pcb_error"), error_type: Wa.literal("pcb_footprint_overlap_error").default("pcb_footprint_overlap_error"), pcb_smtpad_ids: Wa.array(Wa.string()).optional(), pcb_plated_hole_ids: Wa.array(Wa.string()).optional(), pcb_hole_ids: Wa.array(Wa.string()).optional(), pcb_keepout_ids: Wa.array(Wa.string()).optional() }).describe("Error emitted when a pcb footprint overlaps with another element");
var mm = ld.extend({ type: Wa.literal("pcb_courtyard_overlap_error"), pcb_error_id: Hh("pcb_error"), error_type: Wa.literal("pcb_courtyard_overlap_error").default("pcb_courtyard_overlap_error"), pcb_component_ids: Wa.tuple([Wa.string(), Wa.string()]) }).describe("Error emitted when the courtyard (CrtYd) of one PCB component overlaps with the courtyard of another");
var gm = Wa.object({ type: Wa.literal("pcb_keepout"), shape: Wa.literal("rect"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: Fh, width: Eh, height: Eh, pcb_keepout_id: Wa.string(), layers: Wa.array(Wa.string()), description: Wa.string().optional() }).or(Wa.object({ type: Wa.literal("pcb_keepout"), shape: Wa.literal("circle"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: Fh, radius: Eh, pcb_keepout_id: Wa.string(), layers: Wa.array(Wa.string()), description: Wa.string().optional() }));
var fm = Wa.object({ type: Wa.literal("pcb_cutout"), pcb_cutout_id: Hh("pcb_cutout"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), pcb_board_id: Wa.string().optional(), pcb_panel_id: Wa.string().optional() });
var _m = fm.extend({ shape: Wa.literal("rect"), center: Fh, width: Rh, height: Rh, rotation: zh.optional(), corner_radius: Rh.optional() });
var ym = fm.extend({ shape: Wa.literal("circle"), center: Fh, radius: Rh });
var bm = fm.extend({ shape: Wa.literal("polygon"), points: Wa.array(Fh) });
var xm = fm.extend({ shape: Wa.literal("path"), route: Wa.array(Fh), slot_width: Rh, slot_length: Rh.optional(), space_between_slots: Rh.optional(), slot_corner_radius: Rh.optional() });
var vm = Wa.discriminatedUnion("shape", [_m, ym, bm, xm]).describe("Defines a cutout on the PCB, removing board material.");
var Im = ld.extend({ type: Wa.literal("pcb_missing_footprint_error"), pcb_missing_footprint_error_id: Hh("pcb_missing_footprint_error"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), error_type: Wa.literal("pcb_missing_footprint_error").default("pcb_missing_footprint_error"), source_component_id: Wa.string() }).describe("Defines a missing footprint error on the PCB");
var Sm = ld.extend({ type: Wa.literal("external_footprint_load_error"), external_footprint_load_error_id: Hh("external_footprint_load_error"), pcb_component_id: Wa.string(), source_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), footprinter_string: Wa.string().optional(), error_type: Wa.literal("external_footprint_load_error").default("external_footprint_load_error") }).describe("Defines an error when an external footprint fails to load");
var Cm = ld.extend({ type: Wa.literal("circuit_json_footprint_load_error"), circuit_json_footprint_load_error_id: Hh("circuit_json_footprint_load_error"), pcb_component_id: Wa.string(), source_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), error_type: Wa.literal("circuit_json_footprint_load_error").default("circuit_json_footprint_load_error"), circuit_json: Wa.array(Wa.any()).optional() }).describe("Defines an error when a circuit JSON footprint fails to load");
var Pm = Wa.object({ type: Wa.literal("pcb_group"), pcb_group_id: Hh("pcb_group"), source_group_id: Wa.string(), is_subcircuit: Wa.boolean().optional(), subcircuit_id: Wa.string().optional(), width: Rh.optional(), height: Rh.optional(), center: Fh, display_offset_x: Wa.string().optional().describe("How to display the x offset for this group, usually corresponding with how the user specified it"), display_offset_y: Wa.string().optional().describe("How to display the y offset for this group, usually corresponding with how the user specified it"), outline: Wa.array(Fh).optional(), anchor_position: Fh.optional(), anchor_alignment: Vh.default("center"), position_mode: Wa.enum(["packed", "relative_to_group_anchor", "none"]).optional(), positioned_relative_to_pcb_group_id: Wa.string().optional(), positioned_relative_to_pcb_board_id: Wa.string().optional(), pcb_component_ids: Wa.array(Wa.string()), child_layout_mode: Wa.enum(["packed", "none"]).optional(), name: Wa.string().optional(), description: Wa.string().optional(), layout_mode: Wa.string().optional(), autorouter_configuration: Wa.object({ trace_clearance: Rh }).optional(), autorouter_used_string: Wa.string().optional() }).describe("Defines a group of components on the PCB");
var Mm = ld.extend({ type: Wa.literal("pcb_autorouting_error"), pcb_error_id: Hh("pcb_autorouting_error"), error_type: Wa.literal("pcb_autorouting_error").default("pcb_autorouting_error"), subcircuit_id: Wa.string().optional() }).describe("The autorouting has failed to route a portion of the board");
var wm = Wa.object({ type: Wa.literal("pcb_manual_edit_conflict_warning"), pcb_manual_edit_conflict_warning_id: Hh("pcb_manual_edit_conflict_warning"), warning_type: Wa.literal("pcb_manual_edit_conflict_warning").default("pcb_manual_edit_conflict_warning"), message: Wa.string(), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), source_component_id: Wa.string() }).describe("Warning emitted when a component has both manual placement and explicit pcbX/pcbY coordinates");
var Nm = Wa.enum(["x-", "x+", "y+", "y-"]);
var Rm = Wa.object({ type: Wa.literal("pcb_connector_not_in_accessible_orientation_warning"), pcb_connector_not_in_accessible_orientation_warning_id: Hh("pcb_connector_not_in_accessible_orientation_warning"), warning_type: Wa.literal("pcb_connector_not_in_accessible_orientation_warning").default("pcb_connector_not_in_accessible_orientation_warning"), message: Wa.string(), pcb_component_id: Wa.string(), source_component_id: Wa.string().optional(), pcb_board_id: Wa.string().optional(), facing_direction: Nm, recommended_facing_direction: Nm, subcircuit_id: Wa.string().optional() }).describe("Warning emitted when a connector PCB component is facing inward toward the board and should be reoriented to an outward-facing direction");
var Tm = Wa.object({ type: Wa.literal("supplier_footprint_mismatch_warning"), supplier_footprint_mismatch_warning_id: Hh("supplier_footprint_mismatch_warning"), warning_type: Wa.literal("supplier_footprint_mismatch_warning").default("supplier_footprint_mismatch_warning"), message: Wa.string(), source_component_id: Wa.string(), pcb_component_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), supplier_name: hd.optional(), supplier_part_number: Wa.string().optional(), supplier_footprint_url: Wa.string().optional(), footprint_copper_intersection_over_union: Wa.number() }).describe("Warning emitted when a supplier part footprint does not match the expected footprint");
var Em = Wa.object({ type: Wa.literal("pcb_breakout_point"), pcb_breakout_point_id: Hh("pcb_breakout_point"), pcb_group_id: Wa.string(), subcircuit_id: Wa.string().optional(), source_trace_id: Wa.string().optional(), source_port_id: Wa.string().optional(), source_net_id: Wa.string().optional(), x: Eh, y: Eh }).describe("Defines a routing target within a pcb_group for a source_trace or source_net");
var Am = Wa.object({ type: Wa.literal("pcb_ground_plane"), pcb_ground_plane_id: Hh("pcb_ground_plane"), source_pcb_ground_plane_id: Wa.string(), source_net_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe("Defines a ground plane on the PCB");
var Om = Wa.object({ type: Wa.literal("pcb_ground_plane_region"), pcb_ground_plane_region_id: Hh("pcb_ground_plane_region"), pcb_ground_plane_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), layer: su, points: Wa.array(Fh) }).describe("Defines a polygon region of a ground plane");
var km = Wa.object({ type: Wa.literal("pcb_thermal_spoke"), pcb_thermal_spoke_id: Hh("pcb_thermal_spoke"), pcb_ground_plane_id: Wa.string(), shape: Wa.string(), spoke_count: Wa.number(), spoke_thickness: Eh, spoke_inner_diameter: Eh, spoke_outer_diameter: Eh, pcb_plated_hole_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe("Pattern for connecting a ground plane to a plated hole");
var Dm = Wa.object({ type: Wa.literal("pcb_copper_pour"), pcb_copper_pour_id: Hh("pcb_copper_pour"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), layer: su, source_net_id: Wa.string().optional(), covered_with_solder_mask: Wa.boolean().optional().default(true) });
var Lm = Dm.extend({ shape: Wa.literal("rect"), center: Fh, width: Rh, height: Rh, rotation: zh.optional() });
var zm = Dm.extend({ shape: Wa.literal("brep"), brep_shape: Gu });
var Bm = Dm.extend({ shape: Wa.literal("polygon"), points: Wa.array(Fh) });
var Fm = Wa.discriminatedUnion("shape", [Lm, zm, Bm]).describe("Defines a copper pour on the PCB.");
var jm = ld.extend({ type: Wa.literal("pcb_component_outside_board_error"), pcb_component_outside_board_error_id: Hh("pcb_component_outside_board_error"), error_type: Wa.literal("pcb_component_outside_board_error").default("pcb_component_outside_board_error"), pcb_component_id: Wa.string(), pcb_board_id: Wa.string(), component_center: Fh, component_bounds: Wa.object({ min_x: Wa.number(), max_x: Wa.number(), min_y: Wa.number(), max_y: Wa.number() }), subcircuit_id: Wa.string().optional(), source_component_id: Wa.string().optional() }).describe("Error emitted when a PCB component is placed outside the board boundaries");
var $m = ld.extend({ type: Wa.literal("pcb_component_not_on_board_edge_error"), pcb_component_not_on_board_edge_error_id: Hh("pcb_component_not_on_board_edge_error"), error_type: Wa.literal("pcb_component_not_on_board_edge_error").default("pcb_component_not_on_board_edge_error"), pcb_component_id: Wa.string(), pcb_board_id: Wa.string(), component_center: Fh, pad_to_nearest_board_edge_distance: Wa.number(), source_component_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe("Error emitted when a component that must be placed on the board edge is centered away from the edge");
var Ym = ld.extend({ type: Wa.literal("pcb_component_invalid_layer_error"), pcb_component_invalid_layer_error_id: Hh("pcb_component_invalid_layer_error"), error_type: Wa.literal("pcb_component_invalid_layer_error").default("pcb_component_invalid_layer_error"), pcb_component_id: Wa.string().optional(), source_component_id: Wa.string(), layer: su, subcircuit_id: Wa.string().optional() }).describe("Error emitted when a component is placed on an invalid layer (components can only be on 'top' or 'bottom' layers)");
var Xm = ld.extend({ type: Wa.literal("pcb_via_clearance_error"), pcb_error_id: Hh("pcb_error"), error_type: Wa.literal("pcb_via_clearance_error").default("pcb_via_clearance_error"), pcb_via_ids: Wa.array(Wa.string()).min(2), minimum_clearance: Eh.optional(), actual_clearance: Eh.optional(), pcb_center: Wa.object({ x: Wa.number().optional(), y: Wa.number().optional() }).optional(), subcircuit_id: Wa.string().optional() }).describe("Error emitted when vias are closer than the allowed clearance");
var Hm = ld.extend({ type: Wa.literal("pcb_via_trace_clearance_error"), pcb_via_trace_clearance_error_id: Hh("pcb_via_trace_clearance_error"), error_type: Wa.literal("pcb_via_trace_clearance_error").default("pcb_via_trace_clearance_error"), pcb_via_id: Wa.string(), pcb_trace_id: Wa.string(), minimum_clearance: Eh.optional(), actual_clearance: Eh.optional(), center: Wa.object({ x: Wa.number().optional(), y: Wa.number().optional() }).optional(), subcircuit_id: Wa.string().optional() }).describe("Error emitted when a via and trace are closer than the allowed clearance");
var Vm = ld.extend({ type: Wa.literal("pcb_pad_pad_clearance_error"), pcb_pad_pad_clearance_error_id: Hh("pcb_pad_pad_clearance_error"), error_type: Wa.literal("pcb_pad_pad_clearance_error").default("pcb_pad_pad_clearance_error"), pcb_pad_ids: Wa.array(Wa.string()).min(2), minimum_clearance: Eh.optional(), actual_clearance: Eh.optional(), center: Wa.object({ x: Wa.number().optional(), y: Wa.number().optional() }).optional(), subcircuit_id: Wa.string().optional() }).describe("Error emitted when pads are closer than the allowed clearance");
var Wm = ld.extend({ type: Wa.literal("pcb_pad_trace_clearance_error"), pcb_pad_trace_clearance_error_id: Hh("pcb_pad_trace_clearance_error"), error_type: Wa.literal("pcb_pad_trace_clearance_error").default("pcb_pad_trace_clearance_error"), pcb_pad_id: Wa.string(), pcb_trace_id: Wa.string(), minimum_clearance: Eh.optional(), actual_clearance: Eh.optional(), center: Wa.object({ x: Wa.number().optional(), y: Wa.number().optional() }).optional(), subcircuit_id: Wa.string().optional() }).describe("Error emitted when a pad and trace are closer than allowed clearance");
var Gm = Wa.object({ type: Wa.literal("pcb_courtyard_rect"), pcb_courtyard_rect_id: Hh("pcb_courtyard_rect"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: Fh, width: Rh, height: Rh, layer: au, ccw_rotation: zh.optional(), color: Wa.string().optional() }).describe("Defines a courtyard rectangle on the PCB");
var Um = Wa.object({ type: Wa.literal("pcb_courtyard_outline"), pcb_courtyard_outline_id: Hh("pcb_courtyard_outline"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), layer: au, outline: Wa.array(Fh).min(2) }).describe("Defines a courtyard outline on the PCB");
var Zm = Wa.object({ type: Wa.literal("pcb_courtyard_polygon"), pcb_courtyard_polygon_id: Hh("pcb_courtyard_polygon"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), layer: au, points: Wa.array(Fh).min(3), color: Wa.string().optional() }).describe("Defines a courtyard polygon on the PCB");
var qm = Wa.object({ type: Wa.literal("pcb_courtyard_circle"), pcb_courtyard_circle_id: Hh("pcb_courtyard_circle"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: Fh, radius: Rh, layer: au, color: Wa.string().optional() }).describe("Defines a courtyard circle on the PCB");
var Jm = ["obj", "stl", "3mf", "gltf", "glb", "step", "wrl"];
var Qm = ["x+", "x-", "y+", "y-", "z+", "z-"];
var Km = { obj: "z+", stl: "z+", "3mf": "z+", gltf: "y+", glb: "y+", step: "z+", wrl: "y+" };
var eg = Wa.object({ type: Wa.literal("cad_component"), cad_component_id: Wa.string(), pcb_component_id: Wa.string(), source_component_id: Wa.string(), position: $h, rotation: $h.optional(), size: $h.optional(), layer: su.optional(), subcircuit_id: Wa.string().optional(), footprinter_string: Wa.string().optional(), model_obj_url: Wa.string().optional(), model_stl_url: Wa.string().optional(), model_3mf_url: Wa.string().optional(), model_gltf_url: Wa.string().optional(), model_glb_url: Wa.string().optional(), model_step_url: Wa.string().optional(), model_wrl_url: Wa.string().optional(), model_asset: Gh.optional(), model_unit_to_mm_scale_factor: Wa.number().optional(), model_board_normal_direction: Wa.enum(Qm).optional().describe(`The direction in the model's coordinate space that is considered "up" or "coming out of the board surface"`), model_origin_position: $h.optional(), model_origin_alignment: Wa.enum(["unknown", "center", "center_of_component_on_board_surface", "bottom_center_of_component"]).optional(), model_object_fit: Wa.enum(["contain_within_bounds", "fill_bounds"]).optional().default("contain_within_bounds"), model_jscad: Wa.any().optional(), show_as_translucent_model: Wa.boolean().optional(), anchor_alignment: Wa.enum(["center", "center_of_component_on_board_surface"]).optional().default("center") }).describe("Defines a component on the PCB");
var tg = Wa.enum(["sinewave", "square", "triangle", "sawtooth"]);
var ng = Wa.union([Wa.string(), Wa.number()]).transform((e20) => typeof e20 == "string" ? e20.endsWith("%") ? parseFloat(e20.slice(0, -1)) / 100 : parseFloat(e20) : e20).pipe(Wa.number().min(0, "Duty cycle must be non-negative").max(1, "Duty cycle cannot be greater than 100%"));
var og = Wa.object({ type: Wa.literal("simulation_voltage_source"), simulation_voltage_source_id: Hh("simulation_voltage_source"), is_dc_source: Wa.literal(true).optional().default(true), positive_source_port_id: Wa.string().optional(), negative_source_port_id: Wa.string().optional(), positive_source_net_id: Wa.string().optional(), negative_source_net_id: Wa.string().optional(), voltage: Nh }).describe("Defines a DC voltage source for simulation");
var ig = Wa.object({ type: Wa.literal("simulation_voltage_source"), simulation_voltage_source_id: Hh("simulation_voltage_source"), is_dc_source: Wa.literal(false), terminal1_source_port_id: Wa.string().optional(), terminal2_source_port_id: Wa.string().optional(), terminal1_source_net_id: Wa.string().optional(), terminal2_source_net_id: Wa.string().optional(), voltage: Nh.optional(), frequency: Th.optional(), peak_to_peak_voltage: Nh.optional(), wave_shape: tg.optional(), phase: zh.optional(), duty_cycle: ng.optional() }).describe("Defines an AC voltage source for simulation");
var rg = Wa.union([og, ig]).describe("Defines a voltage source for simulation");
var sg = Wa.union([Wa.string(), Wa.number()]).transform((e20) => typeof e20 == "string" ? e20.endsWith("%") ? parseFloat(e20.slice(0, -1)) / 100 : parseFloat(e20) : e20).pipe(Wa.number().min(0, "Duty cycle must be non-negative").max(1, "Duty cycle cannot be greater than 100%"));
var ag = Wa.object({ type: Wa.literal("simulation_current_source"), simulation_current_source_id: Hh("simulation_current_source"), is_dc_source: Wa.literal(true).optional().default(true), positive_source_port_id: Wa.string().optional(), negative_source_port_id: Wa.string().optional(), positive_source_net_id: Wa.string().optional(), negative_source_net_id: Wa.string().optional(), current: Ah }).describe("Defines a DC current source for simulation");
var cg = Wa.object({ type: Wa.literal("simulation_current_source"), simulation_current_source_id: Hh("simulation_current_source"), is_dc_source: Wa.literal(false), terminal1_source_port_id: Wa.string().optional(), terminal2_source_port_id: Wa.string().optional(), terminal1_source_net_id: Wa.string().optional(), terminal2_source_net_id: Wa.string().optional(), current: Ah.optional(), frequency: Th.optional(), peak_to_peak_current: Ah.optional(), wave_shape: tg.optional(), phase: zh.optional(), duty_cycle: sg.optional() }).describe("Defines an AC current source for simulation");
var lg = Wa.union([ag, cg]).describe("Defines a current source for simulation");
var hg = Wa.union([Wa.literal("spice_dc_sweep"), Wa.literal("spice_dc_operating_point"), Wa.literal("spice_transient_analysis"), Wa.literal("spice_ac_analysis")]);
var dg = Wa.object({ type: Wa.literal("simulation_experiment"), simulation_experiment_id: Hh("simulation_experiment"), name: Wa.string(), experiment_type: hg, time_per_step: Oh.optional(), start_time_ms: Dh.optional(), end_time_ms: Dh.optional() }).describe("Defines a simulation experiment configuration");
var ug = Wa.object({ type: Wa.literal("simulation_transient_voltage_graph"), simulation_transient_voltage_graph_id: Hh("simulation_transient_voltage_graph"), simulation_experiment_id: Wa.string(), timestamps_ms: Wa.array(Wa.number()).optional(), voltage_levels: Wa.array(Wa.number()), source_component_id: Wa.string().optional(), subcircuit_connectivity_map_key: Wa.string().optional(), time_per_step: Oh, start_time_ms: Dh, end_time_ms: Dh, name: Wa.string().optional(), color: Wa.string().optional() }).describe("Stores voltage measurements over time for a simulation");
var pg = Wa.object({ type: Wa.literal("simulation_switch"), simulation_switch_id: Hh("simulation_switch"), source_component_id: Wa.string().optional(), closes_at: Dh.optional(), opens_at: Dh.optional(), starts_closed: Wa.boolean().optional(), switching_frequency: Th.optional() }).describe("Defines a switch for simulation timing control");
var mg = Wa.object({ type: Wa.literal("simulation_voltage_probe"), simulation_voltage_probe_id: Hh("simulation_voltage_probe"), source_component_id: Wa.string().optional(), name: Wa.string().optional(), signal_input_source_port_id: Wa.string().optional(), signal_input_source_net_id: Wa.string().optional(), reference_input_source_port_id: Wa.string().optional(), reference_input_source_net_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), color: Wa.string().optional() }).describe("Defines a voltage probe for simulation. If a reference input is not provided, it measures against ground. If a reference input is provided, it measures the differential voltage between two points.").superRefine((e20, t2) => {
  if (e20.reference_input_source_port_id || e20.reference_input_source_net_id) {
    const n2 = !!e20.signal_input_source_port_id || !!e20.reference_input_source_port_id, o3 = !!e20.signal_input_source_net_id || !!e20.reference_input_source_net_id;
    n2 && o3 ? t2.addIssue({ code: Wa.ZodIssueCode.custom, message: "Cannot mix port and net connections in a differential probe." }) : n2 ? e20.signal_input_source_port_id && e20.reference_input_source_port_id || t2.addIssue({ code: Wa.ZodIssueCode.custom, message: "Differential port probe requires both signal_input_source_port_id and reference_input_source_port_id." }) : o3 && (e20.signal_input_source_net_id && e20.reference_input_source_net_id || t2.addIssue({ code: Wa.ZodIssueCode.custom, message: "Differential net probe requires both signal_input_source_net_id and reference_input_source_net_id." }));
  } else
    !!e20.signal_input_source_port_id == !!e20.signal_input_source_net_id && t2.addIssue({ code: Wa.ZodIssueCode.custom, message: "A voltage probe must have exactly one of signal_input_source_port_id or signal_input_source_net_id." });
});
var gg = ld.extend({ type: Wa.literal("simulation_unknown_experiment_error"), simulation_unknown_experiment_error_id: Hh("simulation_unknown_experiment_error"), error_type: Wa.literal("simulation_unknown_experiment_error").default("simulation_unknown_experiment_error"), simulation_experiment_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe("An unknown error occurred during the simulation experiment.");
var fg = Wa.object({ type: Wa.literal("simulation_op_amp"), simulation_op_amp_id: Hh("simulation_op_amp"), source_component_id: Wa.string().optional(), inverting_input_source_port_id: Wa.string(), non_inverting_input_source_port_id: Wa.string(), output_source_port_id: Wa.string(), positive_supply_source_port_id: Wa.string(), negative_supply_source_port_id: Wa.string() }).describe("Defines a simple ideal operational amplifier for simulation");
var _g = Wa.union([Qd, qd, Jd, Zd, eu, Kd, yd, ud, md, fd, pd, bd, Sd, Cd, Nd, Td, Ed, Ld, Ad, Od, kd, Dd, Md, Pd, ou, cu, tu, zd, jd, $d, Xd, Hd, lu, hu, du, uu, pu, Gd, nu, Qu, dp, Im, Sm, Cm, wm, Rm, Tm, yp, gm, bp, Xp, Op, zp, Bp, Hp, Mp, Ap, Vp, Wp, Pm, Zp, qp, Jp, Qp, om, Kp, em, tm, nm, Fp, jp, Gp, Up, $p, Yp, Xm, Hm, Vm, Wm, rm, im, sm, am, cm, lm, hm, dm, um, Mm, pm, mm, Em, vm, Am, Om, km, Fm, jm, $m, Ym, Gm, Um, Zm, qm, mu, Ru, Su, Cu, Pu, Mu, xu, Iu, Tu, wu, gu, Au, Ou, Eu, Bu, Fu, ju, $u, Hu, Yu, Xu, eg, rg, lg, dg, ug, pg, mg, gg, fg]);
var yg = _g;
function bg(e20, t2, n2) {
  if (!t2 || !n2)
    return;
  let o3 = e20.get(t2);
  o3 || (o3 = new Set, e20.set(t2, o3)), o3.add(n2);
  let i3 = e20.get(n2);
  i3 || (i3 = new Set, e20.set(n2, i3)), i3.add(t2);
}
var xg = (e20, t2 = {}) => {
  const n2 = e20;
  let o3 = n2._internal_store;
  if (!o3) {
    o3 = { counts: {}, editCount: 0 }, n2._internal_store = o3;
    for (const e21 of n2) {
      const t3 = e21.type, n3 = e21[`${t3}_id`];
      if (!n3)
        continue;
      const i4 = Number.parseInt(n3.split("_").pop());
      Number.isNaN(i4) || (o3.counts[t3] = Math.max(o3.counts[t3] ?? 0, i4));
    }
  }
  const i3 = new Proxy({}, { get: (e21, r3) => {
    if (r3 === "toArray")
      return () => (n2.editCount = o3.editCount, n2);
    if (r3 === "editCount")
      return o3.editCount;
    if (r3 === "subtree")
      return (e22) => xg(function(e23, t3) {
        if (!t3.subcircuit_id && !t3.source_group_id)
          return [...e23];
        let n3 = t3;
        if (t3.subcircuit_id) {
          const o5 = new Set([t3.subcircuit_id]), i5 = new Map, r5 = new Map;
          for (const t4 of e23)
            if (t4.type === "source_group") {
              const { source_group_id: e24, subcircuit_id: n4 } = t4;
              n4 && r5.set(e24, n4);
              const o6 = t4.parent_source_group_id;
              o6 && (i5.has(o6) || i5.set(o6, []), i5.get(o6).push(e24));
            }
          let s4;
          for (const [e24, n4] of r5)
            if (n4 === t3.subcircuit_id) {
              s4 = e24;
              break;
            }
          if (s4) {
            const e24 = (t4) => {
              const n4 = i5.get(t4) || [];
              for (const t5 of n4) {
                const n5 = r5.get(t5);
                n5 && o5.add(n5), e24(t5);
              }
            };
            e24(s4), n3 = { ...t3, subcircuit_ids: Array.from(o5) };
          }
        }
        const o4 = new Map;
        for (const t4 of e23) {
          const e24 = t4[`${t4.type}_id`];
          typeof e24 == "string" && o4.set(e24, t4);
        }
        const i4 = new Map;
        for (const t4 of e23) {
          const e24 = Object.entries(t4);
          for (const [n4, r5] of e24)
            if (n4 !== "parent_source_group_id") {
              if (n4.endsWith("_id") && typeof r5 == "string")
                bg(i4, t4, o4.get(r5));
              else if (n4.endsWith("_ids") && Array.isArray(r5))
                for (const e25 of r5)
                  typeof e25 == "string" && bg(i4, t4, o4.get(e25));
            }
        }
        const r4 = [], s3 = new Set;
        for (const t4 of e23) {
          let e24 = false;
          (n3.subcircuit_id && ("subcircuit_id" in t4) && t4.subcircuit_id === n3.subcircuit_id || n3.subcircuit_ids && ("subcircuit_id" in t4) && t4.subcircuit_id && n3.subcircuit_ids.includes(t4.subcircuit_id) || n3.source_group_id && ("source_group_id" in t4) && t4.source_group_id === n3.source_group_id || n3.source_group_id && ("member_source_group_ids" in t4) && Array.isArray(t4.member_source_group_ids) && t4.member_source_group_ids.includes(n3.source_group_id)) && (e24 = true), e24 && (r4.push(t4), s3.add(t4));
        }
        for (;r4.length > 0; ) {
          const e24 = r4.shift(), t4 = i4.get(e24);
          if (t4)
            for (const e25 of t4)
              s3.has(e25) || (s3.add(e25), r4.push(e25));
        }
        return e23.filter((e24) => s3.has(e24));
      }(n2, e22), t2);
    if (r3 === "insert")
      return (e22) => {
        const i4 = e22.type;
        if (!i4)
          throw new Error("insert requires an element with a type");
        o3.counts[i4] ??= -1, o3.counts[i4]++;
        const r4 = o3.counts[i4], s3 = { ...e22, type: i4, [`${i4}_id`]: `${i4}_${r4}` };
        if (t2.validateInserts) {
          (Ya[i4] ?? yg).parse(s3);
        }
        return n2.push(s3), o3.editCount++, s3;
      };
    if (r3 === "insertAll")
      return (e22) => e22.map((e23) => i3.insert(e23));
    const s2 = r3;
    return { get: (e22) => n2.find((t3) => t3.type === s2 && t3[`${s2}_id`] === e22), getUsing: (e22) => {
      const t3 = Object.keys(e22);
      if (t3.length !== 1)
        throw new Error("getUsing requires exactly one key, e.g. { pcb_component_id }");
      const o4 = t3[0], i4 = o4.replace("_id", ""), r4 = n2.find((t4) => t4.type === i4 && t4[o4] === e22[o4]);
      return r4 ? n2.find((e23) => e23.type === s2 && e23[`${s2}_id`] === r4[`${s2}_id`]) : null;
    }, getWhere: (e22) => {
      const t3 = Object.keys(e22);
      return n2.find((n3) => n3.type === s2 && t3.every((t4) => n3[t4] === e22[t4]));
    }, list: (e22) => {
      const t3 = e22 ? Object.keys(e22) : [];
      return n2.filter((n3) => n3.type === s2 && t3.every((t4) => n3[t4] === e22[t4]));
    }, insert: (e22) => {
      o3.counts[s2] ??= -1, o3.counts[s2]++;
      const i4 = o3.counts[s2], r4 = { type: s2, [`${s2}_id`]: `${s2}_${i4}`, ...e22 };
      if (t2.validateInserts) {
        (Ya[s2] ?? yg).parse(r4);
      }
      return n2.push(r4), o3.editCount++, r4;
    }, delete: (e22) => {
      const t3 = n2.find((t4) => t4[`${s2}_id`] === e22);
      t3 && (n2.splice(n2.indexOf(t3), 1), o3.editCount++);
    }, update: (e22, t3) => {
      const i4 = n2.find((t4) => t4.type === s2 && t4[`${s2}_id`] === e22);
      return i4 ? (Object.assign(i4, t3), o3.editCount++, i4) : null;
    }, select: (e22) => {
      if (s2 === "source_component")
        return n2.find((t3) => t3.type === "source_component" && t3.name === e22.replace(/\./g, ""));
      if (s2 === "pcb_port" || s2 === "source_port" || s2 === "schematic_port") {
        const [t3, o4] = e22.replace(/\./g, "").split(/[\s\>]+/), i4 = n2.find((e23) => e23.type === "source_component" && e23.name === t3);
        if (!i4)
          return null;
        const r4 = n2.find((e23) => e23.type === "source_port" && e23.source_component_id === i4.source_component_id && (e23.name === o4 || (e23.port_hints ?? []).includes(o4)));
        if (!r4)
          return null;
        if (s2 === "source_port")
          return r4;
        if (s2 === "pcb_port")
          return n2.find((e23) => e23.type === "pcb_port" && e23.source_port_id === r4.source_port_id);
        if (s2 === "schematic_port")
          return n2.find((e23) => e23.type === "schematic_port" && e23.source_port_id === r4.source_port_id);
      }
    } };
  } });
  return i3;
};
function vg(e20) {
  const t2 = e20.type;
  return `${t2}:${e20[`${t2}_id`]}`;
}
xg.unparsed = xg;
var Ig = (e20, t2 = {}) => {
  let n2 = e20._internal_store_indexed;
  if (!n2) {
    n2 = { counts: {}, editCount: 0, indexes: {} };
    for (const t3 of e20) {
      const e21 = t3.type, o4 = t3[`${e21}_id`];
      if (!o4)
        continue;
      const i4 = Number.parseInt(o4.split("_").pop() || "");
      Number.isNaN(i4) || (n2.counts[e21] = Math.max(n2.counts[e21] ?? 0, i4));
    }
    const o3 = t2.indexConfig || {}, i3 = n2.indexes;
    if (o3.byId && (i3.byId = new Map), o3.byType && (i3.byType = new Map), o3.byRelation && (i3.byRelation = new Map), o3.bySubcircuit && (i3.bySubcircuit = new Map), o3.byCustomField && o3.byCustomField.length > 0) {
      i3.byCustomField = new Map;
      for (const e21 of o3.byCustomField)
        i3.byCustomField.set(e21, new Map);
    }
    for (const t3 of e20) {
      if (o3.byId) {
        const e21 = vg(t3);
        i3.byId.set(e21, t3);
      }
      if (o3.byType) {
        const e21 = i3.byType.get(t3.type) || [];
        e21.push(t3), i3.byType.set(t3.type, e21);
      }
      if (o3.byRelation) {
        const e21 = Object.entries(t3);
        for (const [n3, o4] of e21)
          if (n3.endsWith("_id") && n3 !== `${t3.type}_id` && typeof o4 == "string") {
            const e22 = i3.byRelation.get(n3) || new Map, r3 = e22.get(o4) || [];
            r3.push(t3), e22.set(o4, r3), i3.byRelation.set(n3, e22);
          }
      }
      if (o3.bySubcircuit && "subcircuit_id" in t3) {
        const e21 = t3.subcircuit_id;
        if (e21 && typeof e21 == "string") {
          const n3 = i3.bySubcircuit.get(e21) || [];
          n3.push(t3), i3.bySubcircuit.set(e21, n3);
        }
      }
      if (o3.byCustomField && i3.byCustomField) {
        for (const e21 of o3.byCustomField)
          if (e21 in t3) {
            const n3 = t3[e21];
            if (n3 !== undefined && (typeof n3 == "string" || typeof n3 == "number")) {
              const o4 = String(n3), r3 = i3.byCustomField.get(e21), s2 = r3.get(o4) || [];
              s2.push(t3), r3.set(o4, s2);
            }
          }
      }
    }
    e20._internal_store_indexed = n2;
  }
  return new Proxy({}, { get: (o3, i3) => {
    if (i3 === "toArray")
      return () => (e20.editCount = n2.editCount, e20);
    if (i3 === "editCount")
      return n2.editCount;
    const r3 = i3;
    return { get: (o4) => {
      const i4 = t2.indexConfig || {};
      if (i4.byId && n2.indexes.byId)
        return n2.indexes.byId.get(`${r3}:${o4}`) || null;
      if (i4.byType && n2.indexes.byType) {
        return (n2.indexes.byType.get(r3) || []).find((e21) => e21[`${r3}_id`] === o4) || null;
      }
      return e20.find((e21) => e21.type === r3 && e21[`${r3}_id`] === o4) || null;
    }, getUsing: (o4) => {
      const i4 = t2.indexConfig || {}, s2 = Object.keys(o4);
      if (s2.length !== 1)
        throw new Error("getUsing requires exactly one key, e.g. { pcb_component_id }");
      const a3 = s2[0], c3 = a3.replace("_id", "");
      if (i4.byRelation && n2.indexes.byRelation) {
        const t3 = n2.indexes.byRelation.get(a3);
        if (t3) {
          const s3 = (t3.get(o4[a3]) || []).find((e21) => e21.type === c3);
          if (!s3)
            return null;
          const l4 = s3[`${r3}_id`];
          if (i4.byId && n2.indexes.byId)
            return n2.indexes.byId.get(`${r3}:${l4}`) || null;
          if (i4.byType && n2.indexes.byType) {
            return (n2.indexes.byType.get(r3) || []).find((e21) => e21[`${r3}_id`] === l4) || null;
          }
          return e20.find((e21) => e21.type === r3 && e21[`${r3}_id`] === l4) || null;
        }
      }
      const l3 = e20.find((e21) => e21.type === c3 && e21[a3] === o4[a3]);
      return l3 && e20.find((e21) => e21.type === r3 && e21[`${r3}_id`] === l3[`${r3}_id`]) || null;
    }, getWhere: (o4) => {
      const i4 = t2.indexConfig || {}, s2 = Object.keys(o4);
      if (s2.length === 1 && i4.byCustomField && n2.indexes.byCustomField) {
        const e21 = s2[0], t3 = n2.indexes.byCustomField.get(e21);
        if (t3) {
          const n3 = String(o4[e21]);
          return (t3.get(n3) || []).find((e22) => e22.type === r3) || null;
        }
      }
      if ("subcircuit_id" in o4 && i4.bySubcircuit && n2.indexes.bySubcircuit) {
        const e21 = o4.subcircuit_id;
        return (n2.indexes.bySubcircuit.get(e21) || []).find((e22) => e22.type === r3 && s2.every((t3) => e22[t3] === o4[t3])) || null;
      }
      if (i4.byType && n2.indexes.byType) {
        return (n2.indexes.byType.get(r3) || []).find((e21) => s2.every((t3) => e21[t3] === o4[t3])) || null;
      }
      return e20.find((e21) => e21.type === r3 && s2.every((t3) => e21[t3] === o4[t3])) || null;
    }, list: (o4) => {
      const i4 = t2.indexConfig || {}, s2 = o4 ? Object.keys(o4) : [];
      if (s2.length === 0 && i4.byType && n2.indexes.byType)
        return n2.indexes.byType.get(r3) || [];
      if (s2.length === 1 && s2[0] === "subcircuit_id" && i4.bySubcircuit && n2.indexes.bySubcircuit) {
        const e21 = o4.subcircuit_id;
        return (n2.indexes.bySubcircuit.get(e21) || []).filter((e22) => e22.type === r3);
      }
      let a3;
      return a3 = i4.byType && n2.indexes.byType ? n2.indexes.byType.get(r3) || [] : e20.filter((e21) => e21.type === r3), s2.length > 0 ? a3.filter((e21) => s2.every((t3) => e21[t3] === o4[t3])) : a3;
    }, insert: (o4) => {
      n2.counts[r3] ??= -1, n2.counts[r3]++;
      const i4 = n2.counts[r3], s2 = { type: r3, [`${r3}_id`]: `${r3}_${i4}`, ...o4 };
      if (t2.validateInserts) {
        (Ya[r3] ?? yg).parse(s2);
      }
      e20.push(s2), n2.editCount++;
      const a3 = t2.indexConfig || {};
      if (a3.byId && n2.indexes.byId) {
        const e21 = vg(s2);
        n2.indexes.byId.set(e21, s2);
      }
      if (a3.byType && n2.indexes.byType) {
        const e21 = n2.indexes.byType.get(r3) || [];
        e21.push(s2), n2.indexes.byType.set(r3, e21);
      }
      if (a3.byRelation && n2.indexes.byRelation) {
        const e21 = Object.entries(s2);
        for (const [t3, o5] of e21)
          if (t3.endsWith("_id") && t3 !== `${s2.type}_id` && typeof o5 == "string") {
            const e22 = n2.indexes.byRelation.get(t3) || new Map, i5 = e22.get(o5) || [];
            i5.push(s2), e22.set(o5, i5), n2.indexes.byRelation.set(t3, e22);
          }
      }
      if (a3.bySubcircuit && n2.indexes.bySubcircuit && "subcircuit_id" in s2) {
        const e21 = s2.subcircuit_id;
        if (e21 && typeof e21 == "string") {
          const t3 = n2.indexes.bySubcircuit.get(e21) || [];
          t3.push(s2), n2.indexes.bySubcircuit.set(e21, t3);
        }
      }
      if (a3.byCustomField && n2.indexes.byCustomField) {
        for (const e21 of a3.byCustomField)
          if (e21 in s2) {
            const t3 = s2[e21];
            if (t3 !== undefined && (typeof t3 == "string" || typeof t3 == "number")) {
              const o5 = String(t3), i5 = n2.indexes.byCustomField.get(e21), r4 = i5.get(o5) || [];
              r4.push(s2), i5.set(o5, r4);
            }
          }
      }
      return s2;
    }, delete: (o4) => {
      const i4 = t2.indexConfig || {};
      let s2;
      if (i4.byId && n2.indexes.byId)
        s2 = n2.indexes.byId.get(`${r3}:${o4}`);
      else if (i4.byType && n2.indexes.byType) {
        const e21 = n2.indexes.byType.get(r3) || [];
        s2 = e21.find((e22) => e22[`${r3}_id`] === o4);
      } else
        s2 = e20.find((e21) => e21[`${r3}_id`] === o4);
      if (!s2)
        return;
      const a3 = e20.indexOf(s2);
      if (a3 >= 0 && (e20.splice(a3, 1), n2.editCount++), i4.byId && n2.indexes.byId) {
        const e21 = vg(s2);
        n2.indexes.byId.delete(e21);
      }
      if (i4.byType && n2.indexes.byType) {
        const e21 = (n2.indexes.byType.get(r3) || []).filter((e22) => e22[`${r3}_id`] !== o4);
        n2.indexes.byType.set(r3, e21);
      }
      if (i4.byRelation && n2.indexes.byRelation)
        for (const [e21, t3] of n2.indexes.byRelation.entries())
          for (const [e22, n3] of t3.entries()) {
            const o5 = n3.filter((e23) => e23 !== s2);
            o5.length === 0 ? t3.delete(e22) : t3.set(e22, o5);
          }
      if (i4.bySubcircuit && n2.indexes.bySubcircuit && "subcircuit_id" in s2) {
        const e21 = s2.subcircuit_id;
        if (e21) {
          const t3 = (n2.indexes.bySubcircuit.get(e21) || []).filter((e22) => e22 !== s2);
          t3.length === 0 ? n2.indexes.bySubcircuit.delete(e21) : n2.indexes.bySubcircuit.set(e21, t3);
        }
      }
      if (i4.byCustomField && n2.indexes.byCustomField)
        for (const e21 of n2.indexes.byCustomField.values())
          for (const [t3, n3] of e21.entries()) {
            const o5 = n3.filter((e22) => e22 !== s2);
            o5.length === 0 ? e21.delete(t3) : e21.set(t3, o5);
          }
    }, update: (o4, i4) => {
      const s2 = t2.indexConfig || {};
      let a3;
      if (s2.byId && n2.indexes.byId)
        a3 = n2.indexes.byId.get(`${r3}:${o4}`);
      else if (s2.byType && n2.indexes.byType) {
        const e21 = n2.indexes.byType.get(r3) || [];
        a3 = e21.find((e22) => e22[`${r3}_id`] === o4);
      } else
        a3 = e20.find((e21) => e21.type === r3 && e21[`${r3}_id`] === o4);
      if (!a3)
        return null;
      if (s2.byRelation && n2.indexes.byRelation) {
        const e21 = Object.entries(a3);
        for (const [t3, o5] of e21)
          if (t3.endsWith("_id") && t3 !== `${a3.type}_id` && typeof o5 == "string" && t3 in i4 && i4[t3] !== o5) {
            const e22 = n2.indexes.byRelation.get(t3);
            if (e22) {
              const t4 = (e22.get(o5) || []).filter((e23) => e23 !== a3);
              t4.length === 0 ? e22.delete(o5) : e22.set(o5, t4);
            }
          }
      }
      if (s2.bySubcircuit && n2.indexes.bySubcircuit && "subcircuit_id" in a3 && "subcircuit_id" in i4) {
        const e21 = a3.subcircuit_id;
        if (e21 !== i4.subcircuit_id) {
          const t3 = (n2.indexes.bySubcircuit.get(e21) || []).filter((e22) => e22 !== a3);
          t3.length === 0 ? n2.indexes.bySubcircuit.delete(e21) : n2.indexes.bySubcircuit.set(e21, t3);
        }
      }
      if (s2.byCustomField && n2.indexes.byCustomField) {
        for (const e21 of s2.byCustomField)
          if (e21 in a3 && e21 in i4 && a3[e21] !== i4[e21]) {
            const t3 = n2.indexes.byCustomField.get(e21);
            if (t3) {
              const n3 = String(a3[e21]), o5 = (t3.get(n3) || []).filter((e22) => e22 !== a3);
              o5.length === 0 ? t3.delete(n3) : t3.set(n3, o5);
            }
          }
      }
      if (Object.assign(a3, i4), n2.editCount++, s2.byRelation && n2.indexes.byRelation) {
        const e21 = Object.entries(a3);
        for (const [t3, o5] of e21)
          if (t3.endsWith("_id") && t3 !== `${a3.type}_id` && typeof o5 == "string" && t3 in i4) {
            const e22 = n2.indexes.byRelation.get(t3) || new Map, i5 = e22.get(o5) || [];
            i5.includes(a3) || (i5.push(a3), e22.set(o5, i5), n2.indexes.byRelation.set(t3, e22));
          }
      }
      if (s2.bySubcircuit && n2.indexes.bySubcircuit && "subcircuit_id" in a3 && "subcircuit_id" in i4) {
        const e21 = a3.subcircuit_id;
        if (e21 && typeof e21 == "string") {
          const t3 = n2.indexes.bySubcircuit.get(e21) || [];
          t3.includes(a3) || (t3.push(a3), n2.indexes.bySubcircuit.set(e21, t3));
        }
      }
      if (s2.byCustomField && n2.indexes.byCustomField) {
        for (const e21 of s2.byCustomField)
          if (e21 in a3 && e21 in i4) {
            const t3 = a3[e21];
            if (t3 !== undefined && (typeof t3 == "string" || typeof t3 == "number")) {
              const o5 = String(t3), i5 = n2.indexes.byCustomField.get(e21), r4 = i5.get(o5) || [];
              r4.includes(a3) || (r4.push(a3), i5.set(o5, r4));
            }
          }
      }
      return a3;
    }, select: (t3) => {
      if (r3 === "source_component")
        return e20.find((e21) => e21.type === "source_component" && e21.name === t3.replace(/\./g, "")) || null;
      if (r3 === "pcb_port" || r3 === "source_port" || r3 === "schematic_port") {
        const [n3, o4] = t3.replace(/\./g, "").split(/[\s\>]+/), i4 = e20.find((e21) => e21.type === "source_component" && e21.name === n3);
        if (!i4)
          return null;
        const s2 = e20.find((e21) => e21.type === "source_port" && e21.source_component_id === i4.source_component_id && (e21.name === o4 || (e21.port_hints ?? []).includes(o4)));
        if (!s2)
          return null;
        if (r3 === "source_port")
          return s2;
        if (r3 === "pcb_port")
          return e20.find((e21) => e21.type === "pcb_port" && e21.source_port_id === s2.source_port_id) || null;
        if (r3 === "schematic_port")
          return e20.find((e21) => e21.type === "schematic_port" && e21.source_port_id === s2.source_port_id) || null;
      }
      return null;
    } };
  } });
};
Ig.unparsed = Ig;
var Sg = true;
var Cg = { CCW: -1, CW: 1, NOT_ORIENTABLE: 0 };
var Pg = 2 * Math.PI;
var Mg = Object.freeze({ __proto__: null, BOUNDARY: 2, CCW: Sg, CONTAINS: 3, CW: false, END_VERTEX: 2, INSIDE: 1, INTERLACE: 4, NOT_VERTEX: 0, ORIENTATION: Cg, OUTSIDE: 0, OVERLAP_OPPOSITE: 2, OVERLAP_SAME: 1, PIx2: Pg, START_VERTEX: 1 });
var wg = 0.000001;
function Ng(e20) {
  wg = e20;
}
function Rg() {
  return wg;
}
function Tg(e20) {
  return e20 < wg && e20 > -wg;
}
function Eg(e20, t2) {
  return e20 - t2 < wg && e20 - t2 > -wg;
}
function Ag(e20, t2) {
  return e20 - t2 > wg;
}
function Og(e20, t2) {
  return e20 - t2 < -wg;
}
var kg = { Utils: Object.freeze({ __proto__: null, DECIMALS: 3, EQ: Eg, EQ_0: Tg, GE: function(e20, t2) {
  return e20 - t2 > -wg;
}, GT: Ag, LE: function(e20, t2) {
  return e20 - t2 < wg;
}, LT: Og, getTolerance: Rg, setTolerance: Ng }), Errors: undefined, Matrix: undefined, Planar_set: undefined, Point: undefined, Vector: undefined, Line: undefined, Circle: undefined, Segment: undefined, Arc: undefined, Box: undefined, Edge: undefined, Face: undefined, Ray: undefined, Ray_shooting: undefined, Multiline: undefined, Polygon: undefined, Distance: undefined, Inversion: undefined };
for (let e20 in Mg)
  kg[e20] = Mg[e20];
Object.defineProperty(kg, "DP_TOL", { get: function() {
  return Rg();
}, set: function(e20) {
  Ng(e20);
} });
var Dg = class {
  static get ILLEGAL_PARAMETERS() {
    return new ReferenceError("Illegal Parameters");
  }
  static get ZERO_DIVISION() {
    return new Error("Zero division");
  }
  static get UNRESOLVED_BOUNDARY_CONFLICT() {
    return new Error("Unresolved boundary conflict in boolean operation");
  }
  static get INFINITE_LOOP() {
    return new Error("Infinite loop");
  }
  static get CANNOT_COMPLETE_BOOLEAN_OPERATION() {
    return new Error("Cannot complete boolean operation");
  }
  static get CANNOT_INVOKE_ABSTRACT_METHOD() {
    return new Error("Abstract method cannot be invoked");
  }
  static get OPERATION_IS_NOT_SUPPORTED() {
    return new Error("Operation is not supported");
  }
  static get UNSUPPORTED_SHAPE_TYPE() {
    return new Error("Unsupported shape type");
  }
};
kg.Errors = Dg;
var Lg = class {
  constructor(e20, t2) {
    this.first = e20, this.last = t2 || this.first;
  }
  [Symbol.iterator]() {
    let e20;
    return { next: () => (e20 = e20 ? e20.next : this.first, { value: e20, done: e20 === undefined }) };
  }
  get size() {
    let e20 = 0;
    for (let t2 of this)
      e20++;
    return e20;
  }
  toArray(e20 = undefined, t2 = undefined) {
    let n2 = [], o3 = e20 || this.first, i3 = t2 || this.last, r3 = o3;
    if (r3 === undefined)
      return n2;
    do {
      n2.push(r3), r3 = r3.next;
    } while (r3 !== i3.next);
    return n2;
  }
  append(e20) {
    return this.isEmpty() ? this.first = e20 : (e20.prev = this.last, this.last.next = e20), this.last = e20, this.last.next = undefined, this.first.prev = undefined, this;
  }
  insert(e20, t2) {
    if (this.isEmpty())
      this.first = e20, this.last = e20;
    else if (t2 == null)
      e20.next = this.first, this.first.prev = e20, this.first = e20;
    else {
      let n2 = t2.next;
      t2.next = e20, n2 && (n2.prev = e20), e20.prev = t2, e20.next = n2, this.last === t2 && (this.last = e20);
    }
    return this.last.next = undefined, this.first.prev = undefined, this;
  }
  remove(e20) {
    return e20 === this.first && e20 === this.last ? (this.first = undefined, this.last = undefined) : (e20.prev && (e20.prev.next = e20.next), e20.next && (e20.next.prev = e20.prev), e20 === this.first && (this.first = e20.next), e20 === this.last && (this.last = e20.prev)), this;
  }
  isEmpty() {
    return this.first === undefined;
  }
  static testInfiniteLoop(e20) {
    let t2 = e20, n2 = e20;
    do {
      if (t2 != e20 && t2 === n2)
        throw Dg.INFINITE_LOOP;
      t2 = t2.next, n2 = n2.next.next;
    } while (t2 != e20);
  }
};
var zg = { stroke: "black" };
var Bg = class {
  constructor(e20 = zg) {
    for (const t2 in e20)
      this[t2] = e20[t2];
    this.stroke = e20.stroke ?? zg.stroke;
  }
  toAttributesString() {
    return Object.keys(this).reduce((e20, t2) => e20 + (this[t2] !== undefined ? this.toAttrString(t2, this[t2]) : ""), "");
  }
  toAttrString(e20, t2) {
    const n2 = e20 === "className" ? "class" : this.convertCamelToKebabCase(e20);
    return t2 === null ? `${n2} ` : `${n2}="${t2.toString()}" `;
  }
  convertCamelToKebabCase(e20) {
    return e20.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g).join("-").toLowerCase();
  }
};
function Fg(e20) {
  return new Bg(e20).toAttributesString();
}
function jg(e20, t2) {
  let n2 = [], [o3, i3, r3] = e20.standard, [s2, a3, c3] = t2.standard, l3 = o3 * a3 - i3 * s2, h2 = r3 * a3 - i3 * c3, d2 = o3 * c3 - r3 * s2;
  if (!kg.Utils.EQ_0(l3)) {
    let e21, t3;
    i3 === 0 ? (e21 = r3 / o3, t3 = d2 / l3) : a3 === 0 ? (e21 = c3 / s2, t3 = d2 / l3) : o3 === 0 ? (e21 = h2 / l3, t3 = r3 / i3) : s2 === 0 ? (e21 = h2 / l3, t3 = c3 / a3) : (e21 = h2 / l3, t3 = d2 / l3), n2.push(new kg.Point(e21, t3));
  }
  return n2;
}
function $g(e20, t2) {
  let n2 = [], o3 = t2.pc.projectionOn(e20), i3 = t2.pc.distanceTo(o3)[0];
  if (kg.Utils.EQ(i3, t2.r))
    n2.push(o3);
  else if (kg.Utils.LT(i3, t2.r)) {
    let r3, s2, a3 = Math.sqrt(t2.r * t2.r - i3 * i3);
    r3 = e20.norm.rotate90CCW().multiply(a3), s2 = o3.translate(r3), n2.push(s2), r3 = e20.norm.rotate90CW().multiply(a3), s2 = o3.translate(r3), n2.push(s2);
  }
  return n2;
}
function Yg(e20, t2) {
  let n2 = [];
  for (let o3 of t2.toSegments()) {
    let t3 = Hg(o3, e20);
    for (let e21 of t3)
      hf(e21, n2) || n2.push(e21);
  }
  return n2;
}
function Xg(e20, t2) {
  let n2 = [];
  if (Yg(e20, t2.box).length === 0)
    return n2;
  let o3 = $g(e20, new kg.Circle(t2.pc, t2.r));
  for (let e21 of o3)
    e21.on(t2) && n2.push(e21);
  return n2;
}
function Hg(e20, t2) {
  let n2 = [];
  return e20.ps.on(t2) && n2.push(e20.ps), e20.pe.on(t2) && !e20.isZeroLength() && n2.push(e20.pe), n2.length > 0 || e20.isZeroLength() || e20.ps.leftTo(t2) && e20.pe.leftTo(t2) || !e20.ps.leftTo(t2) && !e20.pe.leftTo(t2) ? n2 : jg(new kg.Line(e20.ps, e20.pe), t2);
}
function Vg(e20, t2) {
  let n2 = [];
  if (e20.isZeroLength())
    return e20.ps.on(t2) && n2.push(e20.ps), n2;
  if (t2.isZeroLength())
    return t2.ps.on(e20) && n2.push(t2.ps), n2;
  let o3 = new kg.Line(e20.ps, e20.pe), i3 = new kg.Line(t2.ps, t2.pe);
  if (o3.incidentTo(i3))
    e20.ps.on(t2) && n2.push(e20.ps), e20.pe.on(t2) && n2.push(e20.pe), !t2.ps.on(e20) || t2.ps.equalTo(e20.ps) || t2.ps.equalTo(e20.pe) || n2.push(t2.ps), !t2.pe.on(e20) || t2.pe.equalTo(e20.ps) || t2.pe.equalTo(e20.pe) || n2.push(t2.pe);
  else if (o3.parallelTo(i3)) {
    const o4 = new kg.Vector(e20.ps, e20.pe), i4 = new kg.Vector(t2.ps, t2.pe), r3 = new kg.Vector(e20.ps, t2.ps), s2 = o4.cross(i4);
    if (!kg.Utils.EQ_0(s2)) {
      const a3 = r3.cross(i4) / s2, c3 = r3.cross(o4) / s2;
      kg.Utils.GE(a3, 0) && kg.Utils.LE(a3, 1) && kg.Utils.GE(c3, 0) && kg.Utils.LE(c3, 1) && n2.push(Wg(e20.ps.translate(o4.multiply(a3)), e20, t2));
    }
  } else {
    let r3 = jg(o3, i3);
    r3.length > 0 && Gg(r3[0], e20) && Gg(r3[0], t2) && n2.push(Wg(r3[0], e20, t2));
  }
  return n2;
}
function Wg(e20, t2, n2) {
  for (const o3 of [t2.ps, t2.pe, n2.ps, n2.pe])
    if (e20.equalTo(o3))
      return o3;
  return e20;
}
function Gg(e20, t2) {
  const n2 = t2.box;
  return kg.Utils.LE(e20.x, n2.xmax) && kg.Utils.GE(e20.x, n2.xmin) && kg.Utils.LE(e20.y, n2.ymax) && kg.Utils.GE(e20.y, n2.ymin);
}
function Ug(e20, t2) {
  let n2 = [];
  if (e20.isZeroLength()) {
    let [o4, i3] = e20.ps.distanceTo(t2.pc);
    return kg.Utils.EQ(o4, t2.r) && n2.push(e20.ps), n2;
  }
  let o3 = $g(new kg.Line(e20.ps, e20.pe), t2);
  for (let t3 of o3)
    t3.on(e20) && n2.push(t3);
  return n2;
}
function Zg(e20, t2) {
  let n2 = [];
  if (e20.isZeroLength())
    return e20.ps.on(t2) && n2.push(e20.ps), n2;
  let o3 = $g(new kg.Line(e20.ps, e20.pe), new kg.Circle(t2.pc, t2.r));
  for (let i3 of o3)
    i3.on(e20) && i3.on(t2) && n2.push(i3);
  return n2;
}
function qg(e20, t2) {
  let n2 = [], o3 = new kg.Vector(e20.pc, t2.pc), i3 = e20.r, r3 = t2.r;
  if (kg.Utils.EQ_0(i3) || kg.Utils.EQ_0(r3))
    return n2;
  if (kg.Utils.EQ_0(o3.x) && kg.Utils.EQ_0(o3.y) && kg.Utils.EQ(i3, r3))
    return n2.push(e20.pc.translate(-i3, 0)), n2;
  let s2, a3 = e20.pc.distanceTo(t2.pc)[0];
  if (kg.Utils.GT(a3, i3 + r3))
    return n2;
  if (kg.Utils.LT(a3, Math.abs(i3 - r3)))
    return n2;
  if (o3.x /= a3, o3.y /= a3, kg.Utils.EQ(a3, i3 + r3) || kg.Utils.EQ(a3, Math.abs(i3 - r3)))
    return s2 = e20.pc.translate(i3 * o3.x, i3 * o3.y), n2.push(s2), n2;
  let c3 = i3 * i3 / (2 * a3) - r3 * r3 / (2 * a3) + a3 / 2, l3 = e20.pc.translate(c3 * o3.x, c3 * o3.y), h2 = Math.sqrt(i3 * i3 - c3 * c3);
  return s2 = l3.translate(o3.rotate90CCW().multiply(h2)), n2.push(s2), s2 = l3.translate(o3.rotate90CW().multiply(h2)), n2.push(s2), n2;
}
function Jg(e20, t2) {
  let n2 = [];
  if (e20.pc.equalTo(t2.pc) && kg.Utils.EQ(e20.r, t2.r)) {
    let o4;
    return o4 = e20.start, o4.on(t2) && n2.push(o4), o4 = e20.end, o4.on(t2) && n2.push(o4), o4 = t2.start, o4.on(e20) && n2.push(o4), o4 = t2.end, o4.on(e20) && n2.push(o4), n2;
  }
  let o3 = new kg.Circle(e20.pc, e20.r), i3 = new kg.Circle(t2.pc, t2.r), r3 = o3.intersect(i3);
  for (let o4 of r3)
    o4.on(e20) && o4.on(t2) && n2.push(o4);
  return n2;
}
function Qg(e20, t2) {
  let n2 = [];
  if (t2.pc.equalTo(e20.pc) && kg.Utils.EQ(t2.r, e20.r))
    return n2.push(e20.start), n2.push(e20.end), n2;
  let o3 = qg(t2, new kg.Circle(e20.pc, e20.r));
  for (let t3 of o3)
    t3.on(e20) && n2.push(t3);
  return n2;
}
function Kg(e20, t2) {
  return e20.isSegment ? Vg(e20.shape, t2) : Zg(t2, e20.shape);
}
function ef(e20, t2) {
  return e20.isSegment ? Zg(e20.shape, t2) : Jg(e20.shape, t2);
}
function tf(e20, t2) {
  return e20.isSegment ? Hg(e20.shape, t2) : Xg(t2, e20.shape);
}
function nf(e20, t2) {
  return e20.isSegment ? Ug(e20.shape, t2) : Qg(e20.shape, t2);
}
function of(e20, t2) {
  let n2 = [];
  for (let o3 of t2.edges)
    for (let t3 of Kg(o3, e20))
      n2.push(t3);
  return n2;
}
function rf(e20, t2) {
  let n2 = [];
  for (let o3 of t2.edges)
    for (let t3 of ef(o3, e20))
      n2.push(t3);
  return n2;
}
function sf(e20, t2) {
  let n2 = [];
  if (t2.isEmpty())
    return n2;
  for (let o3 of t2.edges)
    for (let t3 of tf(o3, e20))
      hf(t3, n2) || n2.push(t3);
  return e20.sortPoints(n2);
}
function af(e20, t2) {
  let n2 = [];
  if (t2.isEmpty())
    return n2;
  for (let o3 of t2.edges)
    for (let t3 of nf(o3, e20))
      n2.push(t3);
  return n2;
}
function cf(e20, t2) {
  return e20.isSegment ? Kg(t2, e20.shape) : e20.isArc ? ef(t2, e20.shape) : e20.isLine ? tf(t2, e20.shape) : e20.isRay ? (n2 = t2, o3 = e20.shape, n2.isSegment ? uf(o3, n2.shape) : pf(o3, n2.shape)) : [];
  var n2, o3;
}
function lf(e20, t2) {
  let n2 = [];
  if (t2.isEmpty() || e20.shape.box.not_intersect(t2.box))
    return n2;
  let o3 = t2.edges.search(e20.shape.box);
  for (let t3 of o3)
    n2 = [...n2, ...cf(e20, t3)];
  return n2;
}
function hf(e20, t2) {
  return t2.some((t3) => t3.equalTo(e20));
}
function df(e20) {
  return new kg.Line(e20.start, e20.norm);
}
function uf(e20, t2) {
  return Hg(t2, df(e20)).filter((t3) => e20.contains(t3));
}
function pf(e20, t2) {
  return Xg(df(e20), t2).filter((t3) => e20.contains(t3));
}
function mf(e20, t2) {
  return $g(df(e20), t2).filter((t3) => e20.contains(t3));
}
function gf(e20, t2) {
  return jg(df(e20), t2).filter((t3) => e20.contains(t3));
}
function ff(e20, t2) {
  return sf(df(e20), t2).filter((t3) => e20.contains(t3));
}
function _f(e20, t2) {
  if (e20.intersect && e20.intersect instanceof Function)
    return e20.intersect(t2);
  throw Dg.UNSUPPORTED_SHAPE_TYPE;
}
function yf(e20, t2) {
  let n2 = [];
  for (let o3 of t2)
    n2 = [...n2, ..._f(e20, o3.shape)];
  return n2;
}
var bf = class e20 extends Lg {
  constructor(...e21) {
    if (super(), this.isInfinite = false, e21.length === 1 && e21[0] instanceof Array && e21[0].length > 0) {
      const t2 = e21[0], n2 = t2.length, o3 = (e22) => e22 instanceof kg.Segment || e22 instanceof kg.Arc || e22 instanceof kg.Ray, i3 = (e22) => e22 instanceof kg.Segment || e22 instanceof kg.Arc;
      if (!(n2 === 1 && ((e22) => e22 instanceof kg.Segment || e22 instanceof kg.Arc || e22 instanceof kg.Ray || e22 instanceof kg.Line)(t2[0]) || n2 > 1 && o3(t2[0]) && o3(t2[n2 - 1]) && t2.slice(1, n2 - 1).every(i3)))
        throw kg.Errors.ILLEGAL_PARAMETERS;
      this.isInfinite = t2.some((e22) => e22 instanceof kg.Ray || e22 instanceof kg.Line);
      for (let e22 of t2) {
        let t3 = new kg.Edge(e22);
        this.append(t3);
      }
      this.setArcLength();
    }
  }
  get edges() {
    return [...this];
  }
  get box() {
    return this.edges.reduce((e21, t2) => e21.merge(t2.box), new kg.Box);
  }
  get vertices() {
    let e21 = this.edges.map((e22) => e22.start);
    return e21.push(this.last.end), e21;
  }
  get length() {
    if (this.isEmpty())
      return 0;
    if (this.isInfinite)
      return Number.POSITIVE_INFINITY;
    let e21 = 0;
    for (let t2 of this)
      e21 += t2.length;
    return e21;
  }
  clone() {
    return new e20(this.toShapes());
  }
  setArcLength() {
    for (let e21 of this)
      this.setOneEdgeArcLength(e21);
  }
  setOneEdgeArcLength(e21) {
    e21 === this.first ? e21.arc_length = 0 : e21.arc_length = e21.prev.arc_length + e21.prev.length;
  }
  pointAtLength(e21) {
    if (e21 > this.length || e21 < 0)
      return null;
    if (this.isInfinite)
      return null;
    let t2 = null;
    for (let n2 of this)
      if (e21 >= n2.arc_length && (n2 === this.last || e21 < n2.next.arc_length)) {
        t2 = n2.pointAtLength(e21 - n2.arc_length);
        break;
      }
    return t2;
  }
  addVertex(e21, t2) {
    let n2 = t2.shape.split(e21);
    if (n2[0] === null)
      return t2.prev;
    if (n2[1] === null)
      return t2;
    let o3 = new kg.Edge(n2[0]), i3 = t2.prev;
    return this.insert(o3, i3), t2.shape = n2[1], o3;
  }
  getChain(e21, t2) {
    let n2 = [];
    for (let o3 = e21;o3 !== t2.next; o3 = o3.next)
      n2.push(o3);
    return n2;
  }
  split(e21) {
    for (let t2 of e21) {
      let e22 = this.findEdgeByPoint(t2);
      this.addVertex(t2, e22);
    }
    return this;
  }
  findEdgeByPoint(e21) {
    let t2;
    for (let n2 of this)
      if (n2.shape.contains(e21)) {
        t2 = n2;
        break;
      }
    return t2;
  }
  distanceTo(e21) {
    if (e21 instanceof kg.Point) {
      const [t2, n2] = kg.Distance.shape2multiline(e21, this);
      return [t2, n2.reverse()];
    }
    if (e21 instanceof kg.Line) {
      const [t2, n2] = kg.Distance.shape2multiline(e21, this);
      return [t2, n2.reverse()];
    }
    if (e21 instanceof kg.Circle) {
      const [t2, n2] = kg.Distance.shape2multiline(e21, this);
      return [t2, n2.reverse()];
    }
    if (e21 instanceof kg.Segment) {
      const [t2, n2] = kg.Distance.shape2multiline(e21, this);
      return [t2, n2.reverse()];
    }
    if (e21 instanceof kg.Arc) {
      const [t2, n2] = kg.Distance.shape2multiline(e21, this);
      return [t2, n2.reverse()];
    }
    if (e21 instanceof kg.Box) {
      const [t2, n2] = kg.Distance.shape2multiline(new kg.Polygon(e21), this);
      return [t2, n2.reverse()];
    }
    if (e21 instanceof kg.Multiline)
      return kg.Distance.multiline2multiline(this, e21);
    throw kg.Errors.UNSUPPORTED_SHAPE_TYPE;
  }
  intersect(e21) {
    return e21 instanceof kg.Multiline ? function(e22, t2) {
      let n2 = [];
      for (let o3 of e22)
        for (let e23 of t2)
          n2 = [...n2, ..._f(o3.shape, e23.shape)];
      return n2;
    }(this, e21) : yf(e21, this);
  }
  contains(e21) {
    if (e21 instanceof kg.Point)
      return this.edges.some((t2) => t2.shape.contains(e21));
    throw kg.Errors.UNSUPPORTED_SHAPE_TYPE;
  }
  translate(t2) {
    return new e20(this.edges.map((e21) => e21.shape.translate(t2)));
  }
  rotate(t2 = 0, n2 = new kg.Point) {
    return new e20(this.edges.map((e21) => e21.shape.rotate(t2, n2)));
  }
  transform(t2 = new kg.Matrix) {
    return new e20(this.edges.map((e21) => e21.shape.transform(t2)));
  }
  toShapes() {
    return this.edges.map((e21) => e21.shape.clone());
  }
  toJSON() {
    return this.edges.map((e21) => e21.toJSON());
  }
  svgPoints() {
    return this.vertices.map((e21) => `${e21.x},${e21.y}`).join(" ");
  }
  dpath() {
    let e21 = `M${this.first.start.x},${this.first.start.y}`;
    for (let t2 of this)
      e21 += t2.svg();
    return e21;
  }
  svg(e21 = {}) {
    let t2 = `
<path ${Fg({ fill: "none", ...e21 })} d="`;
    t2 += `
M${this.first.start.x},${this.first.start.y}`;
    for (let e22 of this)
      t2 += e22.svg();
    return t2 += `" >
</path>`, t2;
  }
};
kg.Multiline = bf;
function xf(e21, t2, n2) {
  let o3 = n2.length, i3 = e21.shape.split(t2);
  if (i3.length === 0)
    return;
  let r3 = 0;
  r3 = i3[0] === null ? 0 : i3[1] === null ? e21.shape.length : i3[0].length;
  let s2, a3 = 0;
  Eg(r3, 0) && (a3 |= 1), Eg(r3, e21.shape.length) && (a3 |= 2), s2 = r3 === 1 / 0 ? i3[0].coord(t2) : 2 & a3 && e21.next && e21.next.arc_length === 0 ? 0 : e21.arc_length + r3, n2.push({ id: o3, pt: t2, arc_length: s2, edge_before: e21, edge_after: undefined, face: e21.face, is_vertex: a3 });
}
function vf(e21) {
  e21.int_points1_sorted = If(e21.int_points1), e21.int_points2_sorted = If(e21.int_points2);
}
function If(e21) {
  let t2 = new Map, n2 = 0;
  for (let o3 of e21)
    t2.has(o3.face) || (t2.set(o3.face, n2), n2++);
  for (let n3 of e21)
    n3.faceId = t2.get(n3.face);
  return e21.slice().sort(Sf);
}
function Sf(e21, t2) {
  return e21.faceId < t2.faceId ? -1 : e21.faceId > t2.faceId ? 1 : e21.arc_length < t2.arc_length ? -1 : e21.arc_length > t2.arc_length ? 1 : 0;
}
function Cf(e21) {
  if (e21.int_points1.length < 2)
    return;
  let t2, n2, o3, i3, r3 = false;
  for (let s2 = 0;s2 < e21.int_points1_sorted.length; s2++)
    if (e21.int_points1_sorted[s2].id !== -1) {
      t2 = e21.int_points1_sorted[s2], n2 = e21.int_points2[t2.id];
      for (let a3 = s2 + 1;a3 < e21.int_points1_sorted.length && (o3 = e21.int_points1_sorted[a3], Eg(o3.arc_length, t2.arc_length)); a3++)
        o3.id !== -1 && (i3 = e21.int_points2[o3.id], i3.id !== -1 && o3.edge_before === t2.edge_before && o3.edge_after === t2.edge_after && i3.edge_before === n2.edge_before && i3.edge_after === n2.edge_after && (o3.id = -1, i3.id = -1, r3 = true));
    }
  n2 = e21.int_points2_sorted[0], t2 = e21.int_points1[n2.id];
  for (let o4 = 1;o4 < e21.int_points2_sorted.length; o4++) {
    let i4 = e21.int_points2_sorted[o4];
    if (i4.id === -1)
      continue;
    if (n2.id === -1 || !Eg(i4.arc_length, n2.arc_length)) {
      n2 = i4, t2 = e21.int_points1[n2.id];
      continue;
    }
    let s2 = e21.int_points1[i4.id];
    s2.edge_before === t2.edge_before && s2.edge_after === t2.edge_after && i4.edge_before === n2.edge_before && i4.edge_after === n2.edge_after && (s2.id = -1, i4.id = -1, r3 = true);
  }
  r3 && (e21.int_points1 = e21.int_points1.filter((e22) => e22.id >= 0), e21.int_points2 = e21.int_points2.filter((e22) => e22.id >= 0), e21.int_points1.forEach((e22, t3) => e22.id = t3), e21.int_points2.forEach((e22, t3) => e22.id = t3));
}
function Pf(e21) {
  for (let t2 of e21)
    t2.edge_before && (t2.edge_before.bvStart = undefined, t2.edge_before.bvEnd = undefined, t2.edge_before.bv = undefined, t2.edge_before.overlap = undefined), t2.edge_after && (t2.edge_after.bvStart = undefined, t2.edge_after.bvEnd = undefined, t2.edge_after.bv = undefined, t2.edge_after.overlap = undefined);
  for (let t2 of e21)
    t2.edge_before && (t2.edge_before.bvEnd = 2), t2.edge_after && (t2.edge_after.bvStart = 2);
}
function Mf(e21, t2) {
  for (let n2 of e21)
    n2.edge_before && n2.edge_before.setInclusion(t2), n2.edge_after && n2.edge_after.setInclusion(t2);
}
function wf(e21, t2, n2) {
  let o3, i3, r3 = 1;
  if (e21.length === 1)
    return 1;
  o3 = e21[t2];
  for (let s2 = t2 + 1;s2 < e21.length && o3.face === n2 && (i3 = e21[s2], i3.pt.equalTo(o3.pt) && i3.edge_before === o3.edge_before && i3.edge_after === o3.edge_after); s2++)
    r3++;
  return r3;
}
function Nf(e21, t2) {
  if (t2) {
    for (let n2 of t2) {
      let t3 = n2.edge_before;
      if (n2.is_vertex = 0, t3.shape.start && t3.shape.start.equalTo(n2.pt) && (n2.is_vertex |= 1), t3.shape.end && t3.shape.end.equalTo(n2.pt) && (n2.is_vertex |= 2), 1 & n2.is_vertex) {
        n2.edge_before = t3.prev, t3.prev && (n2.is_vertex = 2);
        continue;
      }
      if (2 & n2.is_vertex)
        continue;
      let o3 = e21.addVertex(n2.pt, t3);
      n2.edge_before = o3;
    }
    for (let n2 of t2)
      n2.edge_before ? n2.edge_after = n2.edge_before.next : e21 instanceof bf && 1 & n2.is_vertex && (n2.edge_after = e21.first);
  }
}
function Rf(e21, t2, n2) {
  const o3 = e21.edge_before, i3 = t2.edge_after, r3 = n2.length;
  o3.next = n2[0], n2[0].prev = o3, n2[r3 - 1].next = i3, i3.prev = n2[r3 - 1];
}
kg.multiline = (...e21) => new kg.Multiline(...e21);
var { INSIDE: Tf, OUTSIDE: Ef, BOUNDARY: Af, OVERLAP_SAME: Of, OVERLAP_OPPOSITE: kf } = Mg;
var { NOT_VERTEX: Df, START_VERTEX: Lf, END_VERTEX: zf } = Mg;
function Bf(e21, t2) {
  let n2 = t2.clone().reverse(), [o3, i3] = Hf(e21, n2, 3, true);
  return o3;
}
function Ff(e21, t2) {
  let [n2, o3] = Hf(e21, t2, 2, true);
  return n2;
}
function jf(e21, t2) {
  let [n2, o3] = Hf(e21, t2, 2, false), i3 = [];
  for (let e22 of n2.faces)
    i3 = [...i3, ...[...e22.edges].map((e23) => e23.shape)];
  let r3 = [];
  for (let e22 of o3.faces)
    r3 = [...r3, ...[...e22.edges].map((e23) => e23.shape)];
  return [i3, r3];
}
function $f(e21, t2) {
  let [n2, o3] = Hf(e21, t2, 3, false), i3 = [];
  for (let e22 of n2.faces)
    i3 = [...i3, ...[...e22.edges].map((e23) => e23.shape)];
  return i3;
}
function Yf(e21, t2) {
  let n2 = e21.clone(), o3 = t2.clone(), i3 = Vf(n2, o3);
  return vf(i3), Nf(n2, i3.int_points1_sorted), Nf(o3, i3.int_points2_sorted), Cf(i3), vf(i3), [i3.int_points1_sorted.map((e22) => e22.pt), i3.int_points2_sorted.map((e22) => e22.pt)];
}
function Xf(e21, t2, n2, o3) {
  let i3 = Wf(e21, n2.int_points1), r3 = Wf(t2, n2.int_points2);
  for (Gf(i3, t2), Gf(r3, e21), Pf(n2.int_points1), Pf(n2.int_points2), Mf(n2.int_points1, t2), Mf(n2.int_points2, e21);Uf(e21, t2, n2.int_points1, n2.int_points1_sorted, n2.int_points2, n2); )
    ;
  (function(e22) {
    let t3, n3, o4, i4 = e22.int_points1.length;
    for (let r4 = 0;r4 < i4; r4++) {
      let s2 = e22.int_points1_sorted[r4];
      s2.face !== t3 && (n3 = r4, t3 = s2.face);
      let a3, c3 = r4, l3 = wf(e22.int_points1_sorted, r4, t3);
      a3 = c3 + l3 < i4 && e22.int_points1_sorted[c3 + l3].face === t3 ? c3 + l3 : n3;
      let h2 = wf(e22.int_points1_sorted, a3, t3);
      o4 = null;
      for (let n4 = a3;n4 < a3 + h2; n4++) {
        let i5 = e22.int_points1_sorted[n4];
        if (i5.face === t3 && e22.int_points2[i5.id].face === e22.int_points2[s2.id].face) {
          o4 = i5;
          break;
        }
      }
      if (o4 === null)
        continue;
      let d2 = s2.edge_after, u2 = o4.edge_before;
      if (d2.bv !== 2 || u2.bv !== 2)
        continue;
      if (d2 !== u2)
        continue;
      let p3 = e22.int_points2[s2.id], m2 = e22.int_points2[o4.id], g2 = p3.edge_after, f2 = m2.edge_before;
      g2.bv === 2 && f2.bv === 2 && g2 === f2 || (p3 = e22.int_points2[o4.id], m2 = e22.int_points2[s2.id], g2 = p3.edge_after, f2 = m2.edge_before), g2.bv === 2 && f2.bv === 2 && g2 === f2 && d2.setOverlap(g2);
    }
  })(n2), Zf(e21, o3, n2.int_points1_sorted, true), Zf(t2, o3, n2.int_points2_sorted, false), Qf(e21, i3, o3, true), Qf(t2, r3, o3, false);
}
function Hf(e21, t2, n2, o3) {
  let i3 = e21.clone(), r3 = t2.clone(), s2 = Vf(i3, r3);
  return vf(s2), Nf(i3, s2.int_points1_sorted), Nf(r3, s2.int_points2_sorted), Cf(s2), vf(s2), Xf(i3, r3, s2, n2), o3 && function(e22, t3, n3) {
    (function(e23, t4, n4, o4) {
      for (let n5 of t4.faces) {
        for (let t5 of n5)
          e23.edges.add(t5);
        o4.find((e24) => e24.face === n5) === undefined && e23.addFace(n5.first, n5.last);
      }
    })(e22, t3, 0, n3.int_points2), function(e23, t4, n4) {
      if (n4.int_points1.length !== 0)
        for (let e24 = 0;e24 < n4.int_points1.length; e24++) {
          let t5 = n4.int_points1[e24], o4 = n4.int_points2[e24];
          if (t5.edge_before !== undefined && t5.edge_after === undefined && o4.edge_before === undefined && o4.edge_after !== undefined && (t5.edge_before.next = o4.edge_after, o4.edge_after.prev = t5.edge_before, t5.edge_after = o4.edge_after, o4.edge_before = t5.edge_before), o4.edge_before !== undefined && o4.edge_after === undefined && t5.edge_before === undefined && t5.edge_after !== undefined && (o4.edge_before.next = t5.edge_after, t5.edge_after.prev = o4.edge_before, o4.edge_after = t5.edge_after, t5.edge_before = o4.edge_before), t5.edge_before !== undefined && t5.edge_after === undefined)
            for (let e25 of n4.int_points1_sorted)
              e25 !== t5 && e25.edge_before === undefined && e25.edge_after !== undefined && e25.pt.equalTo(t5.pt) && (t5.edge_before.next = e25.edge_after, e25.edge_after.prev = t5.edge_before, t5.edge_after = e25.edge_after, e25.edge_before = t5.edge_before);
          if (o4.edge_before !== undefined && o4.edge_after === undefined)
            for (let e25 of n4.int_points2_sorted)
              e25 !== o4 && e25.edge_before === undefined && e25.edge_after !== undefined && e25.pt.equalTo(o4.pt) && (o4.edge_before.next = e25.edge_after, e25.edge_after.prev = o4.edge_before, o4.edge_after = e25.edge_after, e25.edge_before = o4.edge_before);
        }
    }(0, 0, n3), qf(e22, n3.int_points1), qf(t3, n3.int_points2), Jf(e22, n3.int_points1, n3.int_points2), Jf(e22, n3.int_points2, n3.int_points1), Kf(e22), Kf(t3);
  }(i3, r3, s2), [i3, r3];
}
function Vf(e21, t2) {
  let n2 = { int_points1: [], int_points2: [] };
  for (let o3 of e21.edges) {
    let e22 = t2.edges.search(o3.box);
    for (let t3 of e22) {
      let e23 = o3.shape.intersect(t3.shape);
      for (let i3 of e23)
        xf(o3, i3, n2.int_points1), xf(t3, i3, n2.int_points2);
    }
  }
  return n2;
}
function Wf(e21, t2) {
  let n2 = [];
  for (let o3 of e21.faces)
    t2.find((e22) => e22.face === o3) || n2.push(o3);
  return n2;
}
function Gf(e21, t2) {
  for (let n2 of e21)
    n2.first.bv = n2.first.bvStart = n2.first.bvEnd = undefined, n2.first.setInclusion(t2);
}
function Uf(e21, t2, n2, o3, i3, r3) {
  let s2, a3, c3, l3 = o3.length, h2 = false;
  for (let d2 = 0;d2 < l3; d2++) {
    let u2 = o3[d2];
    u2.face !== s2 && (a3 = d2, s2 = u2.face);
    let p3, m2 = d2, g2 = wf(o3, d2, s2);
    p3 = m2 + g2 < l3 && o3[m2 + g2].face === s2 ? m2 + g2 : a3;
    let f2 = wf(o3, p3, s2);
    c3 = null;
    for (let e22 = p3;e22 < p3 + f2; e22++) {
      let t3 = o3[e22];
      if (t3.face === s2 && i3[t3.id].face === i3[u2.id].face) {
        c3 = t3;
        break;
      }
    }
    if (c3 === null)
      continue;
    let _2 = u2.edge_after, y2 = c3.edge_before;
    if (_2.bv !== Af || y2.bv == Af)
      if (_2.bv == Af || y2.bv !== Af) {
        if (_2.bv === Af && y2.bv === Af && _2 != y2 || _2.bv === Tf && y2.bv === Ef || _2.bv === Ef && y2.bv === Tf) {
          let e22 = _2.next;
          for (;e22 != y2; )
            e22.bvStart = undefined, e22.bvEnd = undefined, e22.bv = undefined, e22.setInclusion(t2), e22 = e22.next;
        }
        if (_2.bv === Af && y2.bv === Af && _2 != y2) {
          let e22, t3 = _2.next;
          for (;t3 != y2; ) {
            if (t3.bv != Af) {
              if (e22 === undefined)
                e22 = t3.bv;
              else if (t3.bv != e22)
                throw Dg.UNRESOLVED_BOUNDARY_CONFLICT;
            }
            t3 = t3.next;
          }
          e22 != null && (_2.bv = e22, y2.bv = e22);
          continue;
        }
        if (_2.bv === Tf && y2.bv === Ef || _2.bv === Ef && y2.bv === Tf) {
          let o4 = _2;
          for (;o4 != y2; ) {
            if (o4.bvStart === _2.bv && o4.bvEnd === y2.bv) {
              let [s3, a4] = o4.shape.distanceTo(t2);
              if (s3 < 10 * kg.DP_TOL) {
                xf(o4, a4.ps, n2);
                let s4 = n2[n2.length - 1];
                if (s4.is_vertex & Lf)
                  s4.edge_after = o4, s4.edge_before = o4.prev, o4.bvStart = Af, o4.bv = undefined, o4.setInclusion(t2);
                else if (s4.is_vertex & zf)
                  s4.edge_after = o4.next, o4.bvEnd = Af, o4.bv = undefined, o4.setInclusion(t2);
                else {
                  let e22 = t2.addVertex(s4.pt, o4);
                  s4.edge_before = e22, s4.edge_after = e22.next, e22.setInclusion(t2), e22.next.bvStart = Af, e22.next.bvEnd = undefined, e22.next.bv = undefined, e22.next.setInclusion(t2);
                }
                let c4 = t2.findEdgeByPoint(a4.pe);
                xf(c4, a4.pe, i3);
                let l4 = i3[i3.length - 1];
                if (l4.is_vertex & Lf)
                  l4.edge_after = c4, l4.edge_before = c4.prev;
                else if (l4.is_vertex & zf)
                  l4.edge_after = c4.next;
                else {
                  let n3 = i3.find((e22) => e22.edge_after === c4), o5 = t2.addVertex(l4.pt, c4);
                  l4.edge_before = o5, l4.edge_after = o5.next, n3 && (n3.edge_after = o5), o5.bvStart = undefined, o5.bvEnd = Af, o5.bv = undefined, o5.setInclusion(e21), o5.next.bvStart = Af, o5.next.bvEnd = undefined, o5.next.bv = undefined, o5.next.setInclusion(e21);
                }
                vf(r3), h2 = true;
                break;
              }
            }
            o4 = o4.next;
          }
          if (h2)
            break;
          throw Dg.UNRESOLVED_BOUNDARY_CONFLICT;
        }
      } else
        y2.bv = _2.bv;
    else
      _2.bv = y2.bv;
  }
  return h2;
}
function Zf(e21, t2, n2, o3) {
  if (!n2)
    return;
  let i3, r3, s2, a3;
  for (let c3 = 0;c3 < n2.length; c3++) {
    if (s2 = n2[c3], s2.face !== i3 && (r3 = c3, i3 = s2.face), i3.isEmpty())
      continue;
    let l3, h2 = c3, d2 = wf(n2, c3, i3);
    l3 = h2 + d2 < n2.length && n2[h2 + d2].face === s2.face ? h2 + d2 : r3, a3 = n2[l3];
    let u2 = l3, p3 = wf(n2, u2, i3), m2 = s2.edge_after, g2 = a3.edge_before;
    if (m2.bv === Tf && g2.bv === Tf && t2 === 1 || m2.bv === Ef && g2.bv === Ef && t2 === 2 || (m2.bv === Ef || g2.bv === Ef) && t2 === 3 && !o3 || (m2.bv === Tf || g2.bv === Tf) && t2 === 3 && o3 || m2.bv === Af && g2.bv === Af && m2.overlap & Of && o3 || m2.bv === Af && g2.bv === Af && m2.overlap & kf) {
      e21.removeChain(i3, m2, g2);
      for (let e22 = h2;e22 < h2 + d2; e22++)
        n2[e22].edge_after = undefined;
      for (let e22 = u2;e22 < u2 + p3; e22++)
        n2[e22].edge_before = undefined;
    }
    c3 += d2 - 1;
  }
}
function qf(e21, t2) {
  for (let n2 of t2)
    e21.faces.delete(n2.face), n2.face = undefined, n2.edge_before && (n2.edge_before.face = undefined), n2.edge_after && (n2.edge_after.face = undefined);
}
function Jf(e21, t2, n2) {
  for (let o3 of t2) {
    if (o3.edge_before === undefined || o3.edge_after === undefined)
      continue;
    if (o3.face)
      continue;
    if (o3.edge_after.face || o3.edge_before.face)
      continue;
    let { edge_after: i3, edge_before: r3 } = o3;
    try {
      Lg.testInfiniteLoop(i3);
    } catch (e22) {
      throw Dg.CANNOT_COMPLETE_BOOLEAN_OPERATION;
    }
    let s2 = e21.addFace(i3, r3);
    for (let e22 of t2)
      e22.edge_before && e22.edge_after && e22.edge_before.face === s2 && e22.edge_after.face === s2 && (e22.face = s2);
    for (let e22 of n2)
      e22.edge_before && e22.edge_after && e22.edge_before.face === s2 && e22.edge_after.face === s2 && (e22.face = s2);
  }
}
function Qf(e21, t2, n2, o3) {
  for (let i3 of t2) {
    let t3 = i3.first.bv;
    (n2 === 1 && t3 === Tf || n2 === 3 && t3 === Tf && o3 || n2 === 3 && t3 === Ef && !o3 || n2 === 2 && t3 === Ef) && e21.deleteFace(i3);
  }
}
function Kf(e21) {
  const t2 = [];
  for (const n2 of e21.edges)
    n2.face && e21.faces.has(n2.face) || t2.push(n2);
  for (const n2 of t2)
    e21.edges.delete(n2);
}
var e_ = Object.freeze({ __proto__: null, BOOLEAN_INTERSECT: 2, BOOLEAN_SUBTRACT: 3, BOOLEAN_UNION: 1, calculateIntersections: Yf, innerClip: jf, intersect: Ff, outerClip: $f, removeNotRelevantChains: Zf, removeOldFaces: qf, restoreFaces: Jf, subtract: Bf, unify: function(e21, t2) {
  let [n2, o3] = Hf(e21, t2, 1, true);
  return n2;
} });
var t_ = RegExp("T.F..FFF.|T.F...F..");
var n_ = RegExp("T........|.T.......|...T.....|....T....");
var o_ = RegExp("FT.......|F..T.....|F...T....");
var i_ = RegExp("T.F..F...");
var r_ = RegExp("T.F..F...|.TF..F...|..FT.F...|..F.TF...");
var s_ = class {
  constructor() {
    this.m = new Array(9).fill(undefined);
  }
  get I2I() {
    return this.m[0];
  }
  set I2I(e21) {
    this.m[0] = e21;
  }
  get I2B() {
    return this.m[1];
  }
  set I2B(e21) {
    this.m[1] = e21;
  }
  get I2E() {
    return this.m[2];
  }
  set I2E(e21) {
    this.m[2] = e21;
  }
  get B2I() {
    return this.m[3];
  }
  set B2I(e21) {
    this.m[3] = e21;
  }
  get B2B() {
    return this.m[4];
  }
  set B2B(e21) {
    this.m[4] = e21;
  }
  get B2E() {
    return this.m[5];
  }
  set B2E(e21) {
    this.m[5] = e21;
  }
  get E2I() {
    return this.m[6];
  }
  set E2I(e21) {
    this.m[6] = e21;
  }
  get E2B() {
    return this.m[7];
  }
  set E2B(e21) {
    this.m[7] = e21;
  }
  get E2E() {
    return this.m[8];
  }
  set E2E(e21) {
    this.m[8] = e21;
  }
  toString() {
    return this.m.map((e21) => e21 instanceof Array && e21.length > 0 ? "T" : e21 instanceof Array && e21.length === 0 ? "F" : "*").join("");
  }
  equal() {
    return t_.test(this.toString());
  }
  intersect() {
    return n_.test(this.toString());
  }
  touch() {
    return o_.test(this.toString());
  }
  inside() {
    return i_.test(this.toString());
  }
  covered() {
    return r_.test(this.toString());
  }
};
function a_(e21, t2) {
  let n2, o3 = new kg.Ray(t2), i3 = new kg.Line(o3.pt, o3.norm);
  const r3 = new kg.Box(o3.box.xmin - kg.DP_TOL, o3.box.ymin - kg.DP_TOL, o3.box.xmax + kg.DP_TOL, o3.box.ymax + kg.DP_TOL);
  if (e21.box.not_intersect(r3))
    return kg.OUTSIDE;
  let s2 = e21.edges.search(r3);
  if (s2.length === 0)
    return kg.OUTSIDE;
  for (let e22 of s2)
    if (e22.shape.contains(t2))
      return kg.BOUNDARY;
  let a3 = [...e21.faces], c3 = [];
  for (let e22 of s2)
    for (let n3 of o3.intersect(e22.shape)) {
      if (n3.equalTo(t2))
        return kg.BOUNDARY;
      c3.push({ pt: n3, edge: e22, face_index: a3.indexOf(e22.face) });
    }
  c3.sort((e22, t3) => Og(e22.pt.x, t3.pt.x) ? -1 : Ag(e22.pt.x, t3.pt.x) ? 1 : e22.face_index < t3.face_index ? -1 : e22.face_index > t3.face_index ? 1 : e22.edge.arc_length < t3.edge.arc_length ? -1 : e22.edge.arc_length > t3.edge.arc_length ? 1 : 0);
  let l3 = 0;
  for (let e22 = 0;e22 < c3.length; e22++) {
    let t3 = c3[e22];
    if (t3.pt.equalTo(t3.edge.shape.start)) {
      if (e22 > 0 && t3.pt.equalTo(c3[e22 - 1].pt) && t3.face_index === c3[e22 - 1].face_index && t3.edge.prev === c3[e22 - 1].edge)
        continue;
      let n3 = t3.edge.prev;
      for (;Tg(n3.length); )
        n3 = n3.prev;
      let o4 = n3.shape.tangentInEnd(), r4 = t3.pt.translate(o4), s3 = t3.edge.shape.tangentInStart(), a4 = t3.pt.translate(s3), h2 = r4.leftTo(i3), d2 = a4.leftTo(i3);
      (h2 && !d2 || !h2 && d2) && l3++;
    } else if (t3.pt.equalTo(t3.edge.shape.end)) {
      if (e22 > 0 && t3.pt.equalTo(c3[e22 - 1].pt) && t3.face_index === c3[e22 - 1].face_index && t3.edge.next === c3[e22 - 1].edge)
        continue;
      let n3 = t3.edge.next;
      for (;Tg(n3.length); )
        n3 = n3.next;
      let o4 = n3.shape.tangentInStart(), r4 = t3.pt.translate(o4), s3 = t3.edge.shape.tangentInEnd(), a4 = t3.pt.translate(s3), h2 = r4.leftTo(i3), d2 = a4.leftTo(i3);
      (h2 && !d2 || !h2 && d2) && l3++;
    } else if (t3.edge.shape instanceof kg.Segment)
      l3++;
    else {
      let e23 = t3.edge.shape.box;
      Eg(t3.pt.y, e23.ymin) || Eg(t3.pt.y, e23.ymax) || l3++;
    }
  }
  return n2 = l3 % 2 == 1 ? 1 : 0, n2;
}
function c_(e21, t2) {
  return u_(e21, t2).intersect();
}
function l_(e21, t2) {
  return u_(e21, t2).inside();
}
function h_(e21, t2) {
  return u_(e21, t2).covered();
}
function d_(e21, t2) {
  return h_(t2, e21);
}
function u_(e21, t2) {
  return e21 instanceof kg.Line && t2 instanceof kg.Line ? function(e22, t3) {
    let n2 = new s_, o3 = jg(e22, t3);
    o3.length === 0 ? e22.contains(t3.pt) && t3.contains(e22.pt) ? (n2.I2I = [e22], n2.I2E = [], n2.E2I = []) : (n2.I2I = [], n2.I2E = [e22], n2.E2I = [t3]) : (n2.I2I = o3, n2.I2E = e22.split(o3), n2.E2I = t3.split(o3));
    return n2;
  }(e21, t2) : e21 instanceof kg.Line && t2 instanceof kg.Circle ? function(e22, t3) {
    let n2 = new s_, o3 = $g(e22, t3);
    if (o3.length === 0)
      n2.I2I = [], n2.I2B = [], n2.I2E = [e22], n2.E2I = [t3];
    else if (o3.length === 1)
      n2.I2I = [], n2.I2B = o3, n2.I2E = e22.split(o3), n2.E2I = [t3];
    else {
      let i3 = new bf([e22]), r3 = e22.sortPoints(o3);
      i3.split(r3);
      let s2 = i3.toShapes();
      n2.I2I = [s2[1]], n2.I2B = r3, n2.I2E = [s2[0], s2[2]], n2.E2I = new kg.Polygon([t3.toArc()]).cutWithLine(e22);
    }
    return n2;
  }(e21, t2) : e21 instanceof kg.Line && t2 instanceof kg.Box ? function(e22, t3) {
    let n2 = new s_, o3 = Yg(e22, t3);
    if (o3.length === 0)
      n2.I2I = [], n2.I2B = [], n2.I2E = [e22], n2.E2I = [t3];
    else if (o3.length === 1)
      n2.I2I = [], n2.I2B = o3, n2.I2E = e22.split(o3), n2.E2I = [t3];
    else {
      let i3 = new bf([e22]), r3 = e22.sortPoints(o3);
      i3.split(r3);
      let s2 = i3.toShapes();
      t3.toSegments().some((e23) => e23.contains(o3[0]) && e23.contains(o3[1])) ? (n2.I2I = [], n2.I2B = [s2[1]], n2.I2E = [s2[0], s2[2]], n2.E2I = [t3]) : (n2.I2I = [s2[1]], n2.I2B = r3, n2.I2E = [s2[0], s2[2]], n2.E2I = new kg.Polygon(t3.toSegments()).cutWithLine(e22));
    }
    return n2;
  }(e21, t2) : e21 instanceof kg.Line && t2 instanceof kg.Polygon ? function(e22, t3) {
    let n2 = new s_, o3 = sf(e22, t3), i3 = new bf([e22]), r3 = o3.length > 0 ? o3.slice() : e22.sortPoints(o3);
    return i3.split(r3), [...i3].forEach((e23) => e23.setInclusion(t3)), n2.I2I = [...i3].filter((e23) => e23.bv === kg.INSIDE).map((e23) => e23.shape), n2.I2B = [...i3].slice(1).map((e23) => e23.bv === kg.BOUNDARY ? e23.shape : e23.shape.start), n2.I2E = [...i3].filter((e23) => e23.bv === kg.OUTSIDE).map((e23) => e23.shape), n2.E2I = t3.cutWithLine(e22), n2;
  }(e21, t2) : (e21 instanceof kg.Segment || e21 instanceof kg.Arc) && t2 instanceof kg.Polygon ? p_(e21, t2) : (e21 instanceof kg.Segment || e21 instanceof kg.Arc) && (t2 instanceof kg.Circle || t2 instanceof kg.Box) ? p_(e21, new kg.Polygon(t2)) : e21 instanceof kg.Polygon && t2 instanceof kg.Polygon ? m_(e21, t2) : (e21 instanceof kg.Circle || e21 instanceof kg.Box) && (t2 instanceof kg.Circle || t2 instanceof kg.Box) ? m_(new kg.Polygon(e21), new kg.Polygon(t2)) : (e21 instanceof kg.Circle || e21 instanceof kg.Box) && t2 instanceof kg.Polygon ? m_(new kg.Polygon(e21), t2) : e21 instanceof kg.Polygon && (t2 instanceof kg.Circle || t2 instanceof kg.Box) ? m_(e21, new kg.Polygon(t2)) : undefined;
}
function p_(e21, t2) {
  let n2 = new s_, o3 = function(e22, t3) {
    return e22 instanceof kg.Line ? sf(e22, t3) : e22 instanceof kg.Segment ? of(e22, t3) : e22 instanceof kg.Arc ? rf(e22, t3) : [];
  }(e21, t2), i3 = o3.length > 0 ? o3.slice() : e21.sortPoints(o3), r3 = new bf([e21]);
  r3.split(i3), [...r3].forEach((e22) => e22.setInclusion(t2)), n2.I2I = [...r3].filter((e22) => e22.bv === kg.INSIDE).map((e22) => e22.shape), n2.I2B = [...r3].slice(1).map((e22) => e22.bv === kg.BOUNDARY ? e22.shape : e22.shape.start), n2.I2E = [...r3].filter((e22) => e22.bv === kg.OUTSIDE).map((e22) => e22.shape), n2.B2I = [], n2.B2B = [], n2.B2E = [];
  for (let o4 of [e21.start, e21.end])
    switch (a_(t2, o4)) {
      case kg.INSIDE:
        n2.B2I.push(o4);
        break;
      case kg.BOUNDARY:
        n2.B2B.push(o4);
        break;
      case kg.OUTSIDE:
        n2.B2E.push(o4);
    }
  return n2;
}
function m_(e21, t2) {
  let n2 = new s_, [o3, i3] = Yf(e21, t2), r3 = Ff(e21, t2), s2 = Bf(e21, t2), a3 = Bf(t2, e21), [c3, l3] = jf(e21, t2), h2 = $f(e21, t2), d2 = $f(t2, e21);
  return n2.I2I = r3.isEmpty() ? [] : [r3], n2.I2B = l3, n2.I2E = s2.isEmpty() ? [] : [s2], n2.B2I = c3, n2.B2B = o3, n2.B2E = h2, n2.E2I = a3.isEmpty() ? [] : [a3], n2.E2B = d2, n2;
}
var g_ = Object.freeze({ __proto__: null, contain: function(e21, t2) {
  return l_(t2, e21);
}, cover: d_, covered: h_, disjoint: function(e21, t2) {
  return !c_(e21, t2);
}, equal: function(e21, t2) {
  return u_(e21, t2).equal();
}, inside: l_, intersect: c_, relate: u_, touch: function(e21, t2) {
  return u_(e21, t2).touch();
} });
var f_ = class e21 {
  constructor(e22 = 1, t2 = 0, n2 = 0, o3 = 1, i3 = 0, r3 = 0) {
    this.a = e22, this.b = t2, this.c = n2, this.d = o3, this.tx = i3, this.ty = r3;
  }
  fromMatrix3x3(t2) {
    const [n2, o3, i3] = t2[0], [r3, s2, a3] = t2[1];
    return new e21(n2, r3, o3, s2, i3, a3);
  }
  toMatrix3x3() {
    return [[this.a, this.c, this.tx], [this.b, this.d, this.ty], [0, 0, 1]];
  }
  clone() {
    return new e21(this.a, this.b, this.c, this.d, this.tx, this.ty);
  }
  transform(e22) {
    return [e22[0] * this.a + e22[1] * this.c + this.tx, e22[0] * this.b + e22[1] * this.d + this.ty];
  }
  multiply(t2) {
    return new e21(this.a * t2.a + this.c * t2.b, this.b * t2.a + this.d * t2.b, this.a * t2.c + this.c * t2.d, this.b * t2.c + this.d * t2.d, this.a * t2.tx + this.c * t2.ty + this.tx, this.b * t2.tx + this.d * t2.ty + this.ty);
  }
  translate(...t2) {
    let n2, o3;
    if (t2.length != 1 || isNaN(t2[0].x) || isNaN(t2[0].y)) {
      if (t2.length !== 2 || typeof t2[0] != "number" || typeof t2[1] != "number")
        throw Dg.ILLEGAL_PARAMETERS;
      n2 = t2[0], o3 = t2[1];
    } else
      n2 = t2[0].x, o3 = t2[0].y;
    return this.multiply(new e21(1, 0, 0, 1, n2, o3));
  }
  rotate(t2, n2 = 0, o3 = 0) {
    let i3 = Math.cos(t2), r3 = Math.sin(t2);
    return this.translate(n2, o3).multiply(new e21(i3, r3, -r3, i3, 0, 0)).translate(-n2, -o3);
  }
  scale(t2, n2) {
    return this.multiply(new e21(t2, 0, 0, n2, 0, 0));
  }
  equalTo(e22) {
    return !!kg.Utils.EQ(this.tx, e22.tx) && (!!kg.Utils.EQ(this.ty, e22.ty) && (!!kg.Utils.EQ(this.a, e22.a) && (!!kg.Utils.EQ(this.b, e22.b) && (!!kg.Utils.EQ(this.c, e22.c) && !!kg.Utils.EQ(this.d, e22.d)))));
  }
};
kg.Matrix = f_;
kg.matrix = (...e22) => new kg.Matrix(...e22);
var __ = class {
  constructor(e22, t2) {
    this.low = e22, this.high = t2;
  }
  get max() {
    return this.clone();
  }
  less_than(e22) {
    return this.low < e22.low || this.low === e22.low && this.high < e22.high;
  }
  equal_to(e22) {
    return this.low === e22.low && this.high === e22.high;
  }
  intersect(e22) {
    return !this.not_intersect(e22);
  }
  not_intersect(e22) {
    return this.high < e22.low || e22.high < this.low;
  }
  merge(e22) {
    const t2 = this.low === undefined ? e22.low : this.low < e22.low ? this.low : e22.low, n2 = this.high === undefined ? e22.high : this.high > e22.high ? this.high : e22.high, o3 = this.clone();
    return o3.low = t2, o3.high = n2, o3;
  }
  output() {
    return [this.low, this.high];
  }
  comparable_less_than(e22, t2) {
    return e22 < t2;
  }
};
var y_ = class e22 extends __ {
  clone() {
    return new e22(this.low, this.high);
  }
};
var b_ = class {
  constructor(e23, t2, n2 = null, o3 = null, i3 = null, r3 = 0) {
    if (this.left = n2, this.right = o3, this.parent = i3, this.color = r3, this.item = { key: undefined, values: [] }, t2 !== undefined && this.item.values.push(t2), e23 !== undefined)
      if (Array.isArray(e23)) {
        const [t3, n3] = e23;
        if (!Number.isNaN(t3) && !Number.isNaN(n3)) {
          let e24 = t3, o4 = n3;
          e24 > o4 && ([e24, o4] = [o4, e24]), this.item.key = new y_(e24, o4);
        }
      } else
        this.item.key = e23;
    this.max = this.item.key ? this.item.key.max : undefined;
  }
  isNil() {
    return this.item.key === undefined && this.item.values.length === 0 && this.left === null && this.right === null && this.color === 0;
  }
  requireKey() {
    if (!this.item.key)
      throw new Error("Node key is undefined (nil/sentinel). Operation is not applicable.");
    return this.item.key;
  }
  less_than(e23) {
    const t2 = this.requireKey(), n2 = e23.requireKey();
    return t2.less_than(n2);
  }
  _value_equal(e23) {
    const t2 = this.item.values[0], n2 = e23.item.values[0];
    return t2 && n2 && t2.equal_to ? t2.equal_to(n2) : t2 === n2;
  }
  equal_to(e23) {
    const t2 = this.requireKey(), n2 = e23.requireKey();
    return t2.equal_to(n2);
  }
  intersect(e23) {
    const t2 = this.requireKey(), n2 = e23.requireKey();
    return t2.intersect(n2);
  }
  copy_data(e23) {
    this.item.key = e23.item.key, this.item.values = e23.item.values.slice();
  }
  update_max() {
    this.max = this.item.key ? this.item.key.max : undefined, this.right && this.right.max && (this.max = this.max ? this.max.merge(this.right.max) : this.right.max), this.left && this.left.max && (this.max = this.max ? this.max.merge(this.left.max) : this.left.max);
  }
  not_intersect_left_subtree(e23) {
    if (!this.left)
      return true;
    const t2 = this.left.max ? this.left.max.high : this.left.item.key.high, n2 = this.requireKey(), o3 = e23.requireKey();
    return n2.comparable_less_than(t2, o3.low);
  }
  not_intersect_right_subtree(e23) {
    if (!this.right)
      return true;
    const t2 = this.right.max ? this.right.max.low : this.right.item.key.low, n2 = this.requireKey(), o3 = e23.requireKey();
    return n2.comparable_less_than(o3.high, t2);
  }
};
var x_ = class e23 {
  constructor() {
    this.root = null, this.nil_node = new b_;
  }
  get size() {
    let e24 = 0;
    return this.tree_walk(this.root, (t2) => e24 += t2.item.values.length), e24;
  }
  get keys() {
    const e24 = [];
    return this.tree_walk(this.root, (t2) => e24.push(t2.item.key.output())), e24;
  }
  get values() {
    const e24 = [];
    return this.tree_walk(this.root, (t2) => {
      for (const n2 of t2.item.values)
        e24.push(n2);
    }), e24;
  }
  get items() {
    const e24 = [];
    return this.tree_walk(this.root, (t2) => {
      const n2 = t2.item.key.output();
      for (const o3 of t2.item.values)
        e24.push({ key: n2, value: o3 });
    }), e24;
  }
  isEmpty() {
    return this.root == null || this.root === this.nil_node;
  }
  clear() {
    this.root = null;
  }
  insert(e24, t2 = e24) {
    if (e24 === undefined)
      return;
    const n2 = this.tree_search(this.root, new b_(e24));
    if (n2)
      return n2.item.values.push(t2), n2;
    const o3 = new b_(e24, t2, this.nil_node, this.nil_node, null, 1);
    return this.tree_insert(o3), this.recalc_max(o3), o3;
  }
  exist(e24, t2 = e24) {
    const n2 = this.tree_search(this.root, new b_(e24));
    return !!n2 && (arguments.length < 2 || t2 === e24 || n2.item.values.some((e25) => e25 && e25.equal_to ? e25.equal_to(t2) : e25 === t2));
  }
  remove(e24, t2 = e24) {
    const n2 = this.tree_search(this.root, new b_(e24));
    if (!n2)
      return;
    if (arguments.length < 2)
      return this.tree_delete(n2), n2;
    const o3 = n2.item.values.findIndex((e25) => e25 && e25.equal_to ? e25.equal_to(t2) : e25 === t2);
    return o3 >= 0 ? (n2.item.values.splice(o3, 1), n2.item.values.length === 0 && this.tree_delete(n2), n2) : undefined;
  }
  search(e24, t2 = (e25, t3) => e25 === t3 ? t3.output() : e25) {
    const n2 = new b_(e24), o3 = [];
    this.tree_search_interval(this.root, n2, o3);
    const i3 = [];
    for (const e25 of o3)
      for (const n3 of e25.item.values)
        i3.push(t2(n3, e25.item.key));
    return i3;
  }
  intersect_any(e24) {
    const t2 = new b_(e24);
    return this.tree_find_any_interval(this.root, t2);
  }
  forEach(e24) {
    this.tree_walk(this.root, (t2) => {
      for (const n2 of t2.item.values)
        e24(t2.item.key, n2);
    });
  }
  map(t2) {
    const n2 = new e23;
    return this.tree_walk(this.root, (e24) => {
      for (const o3 of e24.item.values)
        n2.insert(e24.item.key, t2(o3, e24.item.key));
    }), n2;
  }
  *iterate(e24, t2 = (e25, t3) => e25 === t3 ? t3.output() : e25) {
    let n2 = null;
    for (e24 ? n2 = this.tree_search_nearest_forward(this.root, new b_(e24)) : this.root && (n2 = this.local_minimum(this.root));n2; ) {
      for (const e25 of n2.item.values)
        yield t2(e25, n2.item.key);
      n2 = this.tree_successor(n2);
    }
  }
  recalc_max(e24) {
    let t2 = e24;
    for (;t2.parent != null; )
      t2.parent.update_max(), t2 = t2.parent;
  }
  tree_insert(e24) {
    let t2 = this.root, n2 = null;
    if (this.root == null || this.root === this.nil_node)
      this.root = e24;
    else {
      for (;t2 !== this.nil_node; )
        n2 = t2, t2 = e24.less_than(t2) ? t2.left : t2.right;
      e24.parent = n2, e24.less_than(n2) ? n2.left = e24 : n2.right = e24;
    }
    this.insert_fixup(e24);
  }
  insert_fixup(e24) {
    let t2, n2;
    for (t2 = e24;t2 !== this.root && t2.parent.color === 1; )
      t2.parent === t2.parent.parent.left ? (n2 = t2.parent.parent.right, n2.color === 1 ? (t2.parent.color = 0, n2.color = 0, t2.parent.parent.color = 1, t2 = t2.parent.parent) : (t2 === t2.parent.right && (t2 = t2.parent, this.rotate_left(t2)), t2.parent.color = 0, t2.parent.parent.color = 1, this.rotate_right(t2.parent.parent))) : (n2 = t2.parent.parent.left, n2.color === 1 ? (t2.parent.color = 0, n2.color = 0, t2.parent.parent.color = 1, t2 = t2.parent.parent) : (t2 === t2.parent.left && (t2 = t2.parent, this.rotate_right(t2)), t2.parent.color = 0, t2.parent.parent.color = 1, this.rotate_left(t2.parent.parent)));
    this.root.color = 0;
  }
  tree_delete(e24) {
    let t2, n2;
    t2 = e24.left === this.nil_node || e24.right === this.nil_node ? e24 : this.tree_successor(e24), n2 = t2.left !== this.nil_node ? t2.left : t2.right, n2.parent = t2.parent, t2 === this.root ? this.root = n2 : (t2 === t2.parent.left ? t2.parent.left = n2 : t2.parent.right = n2, t2.parent.update_max()), this.recalc_max(n2), t2 !== e24 && (e24.copy_data(t2), e24.update_max(), this.recalc_max(e24)), t2.color === 0 && this.delete_fixup(n2);
  }
  delete_fixup(e24) {
    let t2, n2 = e24;
    for (;n2 !== this.root && n2.parent != null && n2.color === 0; )
      n2 === n2.parent.left ? (t2 = n2.parent.right, t2.color === 1 && (t2.color = 0, n2.parent.color = 1, this.rotate_left(n2.parent), t2 = n2.parent.right), t2.left.color === 0 && t2.right.color === 0 ? (t2.color = 1, n2 = n2.parent) : (t2.right.color === 0 && (t2.color = 1, t2.left.color = 0, this.rotate_right(t2), t2 = n2.parent.right), t2.color = n2.parent.color, n2.parent.color = 0, t2.right.color = 0, this.rotate_left(n2.parent), n2 = this.root)) : (t2 = n2.parent.left, t2.color === 1 && (t2.color = 0, n2.parent.color = 1, this.rotate_right(n2.parent), t2 = n2.parent.left), t2.left.color === 0 && t2.right.color === 0 ? (t2.color = 1, n2 = n2.parent) : (t2.left.color === 0 && (t2.color = 1, t2.right.color = 0, this.rotate_left(t2), t2 = n2.parent.left), t2.color = n2.parent.color, n2.parent.color = 0, t2.left.color = 0, this.rotate_right(n2.parent), n2 = this.root));
    n2.color = 0;
  }
  tree_search(e24, t2) {
    if (e24 != null && e24 !== this.nil_node)
      return t2.equal_to(e24) ? e24 : t2.less_than(e24) ? this.tree_search(e24.left, t2) : this.tree_search(e24.right, t2);
  }
  tree_search_nearest_forward(e24, t2) {
    let n2 = null, o3 = e24;
    for (;o3 && o3 !== this.nil_node; )
      o3.less_than(t2) ? o3.intersect(t2) ? (n2 = o3, o3 = o3.left) : o3 = o3.right : (n2 && !o3.less_than(n2) || (n2 = o3), o3 = o3.left);
    return n2 || null;
  }
  tree_search_interval(e24, t2, n2) {
    e24 != null && e24 !== this.nil_node && (e24.left === this.nil_node || e24.not_intersect_left_subtree(t2) || this.tree_search_interval(e24.left, t2, n2), e24.intersect(t2) && n2.push(e24), e24.right === this.nil_node || e24.not_intersect_right_subtree(t2) || this.tree_search_interval(e24.right, t2, n2));
  }
  tree_find_any_interval(e24, t2) {
    let n2 = false;
    return e24 != null && e24 !== this.nil_node && (e24.left === this.nil_node || e24.not_intersect_left_subtree(t2) || (n2 = this.tree_find_any_interval(e24.left, t2)), n2 || (n2 = e24.intersect(t2)), n2 || e24.right === this.nil_node || e24.not_intersect_right_subtree(t2) || (n2 = this.tree_find_any_interval(e24.right, t2))), n2;
  }
  local_minimum(e24) {
    let t2 = e24;
    for (;t2.left != null && t2.left !== this.nil_node; )
      t2 = t2.left;
    return t2;
  }
  local_maximum(e24) {
    let t2 = e24;
    for (;t2.right != null && t2.right !== this.nil_node; )
      t2 = t2.right;
    return t2;
  }
  tree_successor(e24) {
    let t2, n2, o3;
    if (e24.right !== this.nil_node)
      t2 = this.local_minimum(e24.right);
    else {
      for (n2 = e24, o3 = e24.parent;o3 != null && o3.right === n2; )
        n2 = o3, o3 = o3.parent;
      t2 = o3;
    }
    return t2;
  }
  rotate_left(e24) {
    const t2 = e24.right;
    e24.right = t2.left, t2.left !== this.nil_node && (t2.left.parent = e24), t2.parent = e24.parent, e24 === this.root ? this.root = t2 : e24 === e24.parent.left ? e24.parent.left = t2 : e24.parent.right = t2, t2.left = e24, e24.parent = t2, e24 !== null && e24 !== this.nil_node && e24.update_max(), t2 != null && t2 !== this.nil_node && t2.update_max();
  }
  rotate_right(e24) {
    const t2 = e24.left;
    e24.left = t2.right, t2.right !== this.nil_node && (t2.right.parent = e24), t2.parent = e24.parent, e24 === this.root ? this.root = t2 : e24 === e24.parent.left ? e24.parent.left = t2 : e24.parent.right = t2, t2.right = e24, e24.parent = t2, e24 !== null && e24 !== this.nil_node && e24.update_max(), t2 != null && t2 !== this.nil_node && t2.update_max();
  }
  tree_walk(e24, t2) {
    e24 != null && e24 !== this.nil_node && (this.tree_walk(e24.left, t2), t2(e24), this.tree_walk(e24.right, t2));
  }
  testRedBlackProperty() {
    let e24 = true;
    return this.tree_walk(this.root, function(t2) {
      t2.color === 1 && (t2.left.color === 0 && t2.right.color === 0 || (e24 = false));
    }), e24;
  }
  testBlackHeightProperty(e24) {
    let t2 = 0, n2 = 0, o3 = 0;
    if (e24.color === 0 && t2++, n2 = e24.left !== this.nil_node ? this.testBlackHeightProperty(e24.left) : 1, o3 = e24.right !== this.nil_node ? this.testBlackHeightProperty(e24.right) : 1, n2 !== o3)
      throw new Error("Red-black height property violated");
    return t2 += n2, t2;
  }
};
var v_ = class extends Set {
  constructor(e24) {
    super(e24), this.index = new x_, this.forEach((e25) => this.index.insert(e25));
  }
  add(e24) {
    let t2 = this.size;
    const { key: n2, value: o3 } = e24, i3 = n2 || e24.box, r3 = o3 || e24;
    return super.add(r3), this.size > t2 && this.index.insert(i3, r3), this;
  }
  delete(e24) {
    const { key: t2, value: n2 } = e24, o3 = t2 || e24.box, i3 = n2 || e24;
    let r3 = super.delete(i3);
    return r3 && this.index.remove(o3, i3), r3;
  }
  clear() {
    super.clear(), this.index = new x_;
  }
  search(e24) {
    return this.index.search(e24);
  }
  hit(e24) {
    let t2 = new kg.Box(e24.x - 1, e24.y - 1, e24.x + 1, e24.y + 1);
    return this.index.search(t2).filter((t3) => e24.on(t3));
  }
  svg() {
    return [...this].reduce((e24, t2) => e24 + t2.svg(), "");
  }
};
kg.PlanarSet = v_;
var I_ = class {
  get name() {
    throw Dg.CANNOT_INVOKE_ABSTRACT_METHOD;
  }
  get box() {
    throw Dg.CANNOT_INVOKE_ABSTRACT_METHOD;
  }
  clone() {
    throw Dg.CANNOT_INVOKE_ABSTRACT_METHOD;
  }
  translate(...e24) {
    return this.transform(new f_().translate(...e24));
  }
  rotate(e24, t2 = new kg.Point) {
    return this.transform(new f_().rotate(e24, t2.x, t2.y));
  }
  scale(e24, t2) {
    return this.transform(new f_().scale(e24, t2));
  }
  transform(...e24) {
    throw Dg.CANNOT_INVOKE_ABSTRACT_METHOD;
  }
  toJSON() {
    return Object.assign({}, this, { name: this.name });
  }
  svg(e24 = {}) {
    throw Dg.CANNOT_INVOKE_ABSTRACT_METHOD;
  }
};
var S_ = class e24 extends I_ {
  constructor(...e25) {
    if (super(), this.x = 0, this.y = 0, e25.length !== 0) {
      if (e25.length === 1 && e25[0] instanceof Array && e25[0].length === 2) {
        let t2 = e25[0];
        if (typeof t2[0] == "number" && typeof t2[1] == "number")
          return this.x = t2[0], void (this.y = t2[1]);
      }
      if (e25.length === 1 && e25[0] instanceof Object && e25[0].name === "point") {
        let { x: t2, y: n2 } = e25[0];
        return this.x = t2, void (this.y = n2);
      }
      if (e25.length === 2 && typeof e25[0] == "number" && typeof e25[1] == "number")
        return this.x = e25[0], void (this.y = e25[1]);
      throw Dg.ILLEGAL_PARAMETERS;
    }
  }
  get box() {
    return new kg.Box(this.x, this.y, this.x, this.y);
  }
  clone() {
    return new kg.Point(this.x, this.y);
  }
  get vertices() {
    return [this.clone()];
  }
  equalTo(e25) {
    return kg.Utils.EQ(this.x, e25.x) && kg.Utils.EQ(this.y, e25.y);
  }
  lessThan(e25) {
    return !!kg.Utils.LT(this.y, e25.y) || !(!kg.Utils.EQ(this.y, e25.y) || !kg.Utils.LT(this.x, e25.x));
  }
  transform(e25) {
    return new kg.Point(e25.transform([this.x, this.y]));
  }
  projectionOn(e25) {
    if (this.equalTo(e25.pt))
      return this.clone();
    let t2 = new kg.Vector(this, e25.pt);
    if (kg.Utils.EQ_0(t2.cross(e25.norm)))
      return e25.pt.clone();
    let n2 = t2.dot(e25.norm), o3 = e25.norm.multiply(n2);
    return this.translate(o3);
  }
  leftTo(e25) {
    let t2 = new kg.Vector(e25.pt, this);
    return kg.Utils.GT(t2.dot(e25.norm), 0);
  }
  distanceTo(t2) {
    if (t2 instanceof e24) {
      let e25 = t2.x - this.x, n2 = t2.y - this.y;
      return [Math.sqrt(e25 * e25 + n2 * n2), new kg.Segment(this, t2)];
    }
    return t2 instanceof kg.Line ? kg.Distance.point2line(this, t2) : t2 instanceof kg.Circle ? kg.Distance.point2circle(this, t2) : t2 instanceof kg.Segment ? kg.Distance.point2segment(this, t2) : t2 instanceof kg.Arc ? kg.Distance.point2arc(this, t2) : t2 instanceof kg.Box ? kg.Distance.point2polygon(this, new kg.Polygon(t2)) : t2 instanceof kg.Polygon ? kg.Distance.point2polygon(this, t2) : t2 instanceof kg.PlanarSet ? kg.Distance.shape2planarSet(this, t2) : t2 instanceof kg.Multiline ? kg.Distance.shape2multiline(this, t2) : undefined;
  }
  on(e25) {
    if (e25 instanceof kg.Point)
      return this.equalTo(e25);
    if (e25.contains && e25.contains instanceof Function)
      return e25.contains(this);
    throw kg.Errors.UNSUPPORTED_SHAPE_TYPE;
  }
  get name() {
    return "point";
  }
  svg(e25 = {}) {
    const t2 = e25.r ?? 3;
    return `
<circle cx="${this.x}" cy="${this.y}" r="${t2}"
            ${Fg({ fill: "red", ...e25 })} />`;
  }
};
kg.Point = S_;
var C_ = (...e25) => new kg.Point(...e25);
kg.point = C_;
var P_ = class extends I_ {
  constructor(...e25) {
    if (super(), this.x = 0, this.y = 0, e25.length !== 0) {
      if (e25.length === 1 && e25[0] instanceof Array && e25[0].length === 2) {
        let t2 = e25[0];
        if (typeof t2[0] == "number" && typeof t2[1] == "number")
          return this.x = t2[0], void (this.y = t2[1]);
      }
      if (e25.length === 1 && e25[0] instanceof Object && e25[0].name === "vector") {
        let { x: t2, y: n2 } = e25[0];
        return this.x = t2, void (this.y = n2);
      }
      if (e25.length === 1 && e25[0] instanceof Object && e25[0].name === "segment") {
        let { start: t2, end: n2 } = e25[0];
        return this.x = n2.x - t2.x, void (this.y = n2.y - t2.y);
      }
      if (e25.length === 2) {
        let t2 = e25[0], n2 = e25[1];
        if (typeof t2 == "number" && typeof n2 == "number")
          return this.x = t2, void (this.y = n2);
        if (t2 instanceof kg.Point && n2 instanceof kg.Point)
          return this.x = n2.x - t2.x, void (this.y = n2.y - t2.y);
      }
      throw Dg.ILLEGAL_PARAMETERS;
    }
  }
  clone() {
    return new kg.Vector(this.x, this.y);
  }
  get slope() {
    let e25 = Math.atan2(this.y, this.x);
    return e25 < 0 && (e25 = 2 * Math.PI + e25), e25;
  }
  get length() {
    return Math.sqrt(this.dot(this));
  }
  isZeroLength() {
    return kg.Utils.EQ_0(this.length);
  }
  equalTo(e25) {
    return kg.Utils.EQ(this.x, e25.x) && kg.Utils.EQ(this.y, e25.y);
  }
  multiply(e25) {
    return new kg.Vector(e25 * this.x, e25 * this.y);
  }
  dot(e25) {
    return this.x * e25.x + this.y * e25.y;
  }
  cross(e25) {
    return this.x * e25.y - this.y * e25.x;
  }
  normalize() {
    if (this.isZeroLength())
      throw Dg.ZERO_DIVISION;
    return new kg.Vector(this.x / this.length, this.y / this.length);
  }
  rotate(e25, t2 = new kg.Point) {
    if (t2.x === 0 && t2.y === 0)
      return this.transform(new f_().rotate(e25));
    throw Dg.OPERATION_IS_NOT_SUPPORTED;
  }
  transform(e25) {
    return new kg.Vector(e25.transform([this.x, this.y]));
  }
  rotate90CCW() {
    return new kg.Vector(-this.y, this.x);
  }
  rotate90CW() {
    return new kg.Vector(this.y, -this.x);
  }
  invert() {
    return new kg.Vector(-this.x, -this.y);
  }
  add(e25) {
    return new kg.Vector(this.x + e25.x, this.y + e25.y);
  }
  subtract(e25) {
    return new kg.Vector(this.x - e25.x, this.y - e25.y);
  }
  angleTo(e25) {
    let t2 = this.normalize(), n2 = e25.normalize(), o3 = Math.atan2(t2.cross(n2), t2.dot(n2));
    return o3 < 0 && (o3 += 2 * Math.PI), o3;
  }
  projectionOn(e25) {
    let t2 = e25.normalize(), n2 = this.dot(t2);
    return t2.multiply(n2);
  }
  get name() {
    return "vector";
  }
};
kg.Vector = P_;
var M_ = (...e25) => new kg.Vector(...e25);
kg.vector = M_;
var w_ = class e25 extends I_ {
  constructor(...e26) {
    if (super(), this.ps = new kg.Point, this.pe = new kg.Point, e26.length !== 0) {
      if (e26.length === 1 && e26[0] instanceof Array && e26[0].length === 4) {
        let t2 = e26[0];
        return this.ps = new kg.Point(t2[0], t2[1]), void (this.pe = new kg.Point(t2[2], t2[3]));
      }
      if (e26.length === 1 && e26[0] instanceof Object && e26[0].name === "segment") {
        let { ps: t2, pe: n2 } = e26[0];
        return this.ps = new kg.Point(t2.x, t2.y), void (this.pe = new kg.Point(n2.x, n2.y));
      }
      if (!(e26.length === 1 && e26[0] instanceof kg.Point)) {
        if (e26.length === 2 && e26[0] instanceof kg.Point && e26[1] instanceof kg.Point)
          return this.ps = e26[0].clone(), void (this.pe = e26[1].clone());
        if (e26.length === 4)
          return this.ps = new kg.Point(e26[0], e26[1]), void (this.pe = new kg.Point(e26[2], e26[3]));
        throw Dg.ILLEGAL_PARAMETERS;
      }
      this.ps = e26[0].clone();
    }
  }
  clone() {
    return new kg.Segment(this.start, this.end);
  }
  get start() {
    return this.ps;
  }
  get end() {
    return this.pe;
  }
  get vertices() {
    return [this.ps.clone(), this.pe.clone()];
  }
  get length() {
    return this.start.distanceTo(this.end)[0];
  }
  get slope() {
    return new kg.Vector(this.start, this.end).slope;
  }
  get box() {
    return new kg.Box(Math.min(this.start.x, this.end.x), Math.min(this.start.y, this.end.y), Math.max(this.start.x, this.end.x), Math.max(this.start.y, this.end.y));
  }
  equalTo(e26) {
    return this.ps.equalTo(e26.ps) && this.pe.equalTo(e26.pe);
  }
  contains(e26) {
    return kg.Utils.EQ_0(this.distanceToPoint(e26));
  }
  intersect(e26) {
    return e26 instanceof kg.Point ? this.contains(e26) ? [e26] : [] : e26 instanceof kg.Line ? Hg(this, e26) : e26 instanceof kg.Ray ? uf(e26, this) : e26 instanceof kg.Segment ? Vg(this, e26) : e26 instanceof kg.Circle ? Ug(this, e26) : e26 instanceof kg.Box ? function(e27, t2) {
      let n2 = [];
      for (let o3 of t2.toSegments()) {
        let t3 = Vg(o3, e27);
        for (let e28 of t3)
          n2.push(e28);
      }
      return n2;
    }(this, e26) : e26 instanceof kg.Arc ? Zg(this, e26) : e26 instanceof kg.Polygon ? of(this, e26) : e26 instanceof kg.Multiline ? yf(this, e26) : undefined;
  }
  distanceTo(e26) {
    if (e26 instanceof kg.Point) {
      let [t2, n2] = kg.Distance.point2segment(e26, this);
      return n2 = n2.reverse(), [t2, n2];
    }
    if (e26 instanceof kg.Circle) {
      let [t2, n2] = kg.Distance.segment2circle(this, e26);
      return [t2, n2];
    }
    if (e26 instanceof kg.Line) {
      let [t2, n2] = kg.Distance.segment2line(this, e26);
      return [t2, n2];
    }
    if (e26 instanceof kg.Segment) {
      let [t2, n2] = kg.Distance.segment2segment(this, e26);
      return [t2, n2];
    }
    if (e26 instanceof kg.Arc) {
      let [t2, n2] = kg.Distance.segment2arc(this, e26);
      return [t2, n2];
    }
    if (e26 instanceof kg.Box) {
      let [t2, n2] = kg.Distance.shape2polygon(this, new kg.Polygon(e26));
      return [t2, n2];
    }
    if (e26 instanceof kg.Polygon) {
      let [t2, n2] = kg.Distance.shape2polygon(this, e26);
      return [t2, n2];
    }
    if (e26 instanceof kg.PlanarSet) {
      let [t2, n2] = kg.Distance.shape2planarSet(this, e26);
      return [t2, n2];
    }
    if (e26 instanceof kg.Multiline)
      return kg.Distance.shape2multiline(this, e26);
  }
  tangentInStart() {
    return new kg.Vector(this.start, this.end).normalize();
  }
  tangentInEnd() {
    return new kg.Vector(this.end, this.start).normalize();
  }
  reverse() {
    return new e25(this.end, this.start);
  }
  split(e26) {
    return this.start.equalTo(e26) ? [null, this.clone()] : this.end.equalTo(e26) ? [this.clone(), null] : [new kg.Segment(this.start, e26), new kg.Segment(e26, this.end)];
  }
  middle() {
    return new kg.Point((this.start.x + this.end.x) / 2, (this.start.y + this.end.y) / 2);
  }
  pointAtLength(e26) {
    if (e26 > this.length || e26 < 0)
      return null;
    if (e26 == 0)
      return this.start;
    if (e26 == this.length)
      return this.end;
    let t2 = e26 / this.length;
    return new kg.Point((this.end.x - this.start.x) * t2 + this.start.x, (this.end.y - this.start.y) * t2 + this.start.y);
  }
  distanceToPoint(e26) {
    let [t2, ...n2] = kg.Distance.point2segment(e26, this);
    return t2;
  }
  definiteIntegral(e26 = 0) {
    return (this.end.x - this.start.x) * (this.start.y - e26 + (this.end.y - e26)) / 2;
  }
  transform(t2 = new kg.Matrix) {
    return new e25(this.ps.transform(t2), this.pe.transform(t2));
  }
  isZeroLength() {
    return this.ps.equalTo(this.pe);
  }
  sortPoints(e26) {
    return new kg.Line(this.start, this.end).sortPoints(e26);
  }
  get name() {
    return "segment";
  }
  svg(e26 = {}) {
    return `
<line x1="${this.start.x}" y1="${this.start.y}" x2="${this.end.x}" y2="${this.end.y}" ${Fg(e26)} />`;
  }
};
kg.Segment = w_;
var N_ = (...e26) => new kg.Segment(...e26);
kg.segment = N_;
var { vector: R_ } = kg;
kg.Line = class e26 extends I_ {
  constructor(...t2) {
    if (super(), this.pt = new kg.Point, this.norm = new kg.Vector(0, 1), t2.length !== 0) {
      if (t2.length === 1 && t2[0] instanceof Object && t2[0].name === "line") {
        let { pt: e27, norm: n2 } = t2[0];
        return this.pt = new kg.Point(e27), void (this.norm = new kg.Vector(n2));
      }
      if (t2.length === 2) {
        let n2 = t2[0], o3 = t2[1];
        if (n2 instanceof kg.Point && o3 instanceof kg.Point)
          return this.pt = n2, this.norm = e26.points2norm(n2, o3), void (this.norm.dot(R_(this.pt.x, this.pt.y)) >= 0 && this.norm.invert());
        if (n2 instanceof kg.Point && o3 instanceof kg.Vector) {
          if (kg.Utils.EQ_0(o3.x) && kg.Utils.EQ_0(o3.y))
            throw Dg.ILLEGAL_PARAMETERS;
          return this.pt = n2.clone(), this.norm = o3.clone(), this.norm = this.norm.normalize(), void (this.norm.dot(R_(this.pt.x, this.pt.y)) >= 0 && this.norm.invert());
        }
        if (n2 instanceof kg.Vector && o3 instanceof kg.Point) {
          if (kg.Utils.EQ_0(n2.x) && kg.Utils.EQ_0(n2.y))
            throw Dg.ILLEGAL_PARAMETERS;
          return this.pt = o3.clone(), this.norm = n2.clone(), this.norm = this.norm.normalize(), void (this.norm.dot(R_(this.pt.x, this.pt.y)) >= 0 && this.norm.invert());
        }
      }
      throw Dg.ILLEGAL_PARAMETERS;
    }
  }
  clone() {
    return new kg.Line(this.pt, this.norm);
  }
  get start() {}
  get end() {}
  get length() {
    return Number.POSITIVE_INFINITY;
  }
  get box() {
    return new kg.Box(Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY);
  }
  get middle() {}
  get slope() {
    return new kg.Vector(this.norm.y, -this.norm.x).slope;
  }
  get standard() {
    return [this.norm.x, this.norm.y, this.norm.dot(R_(this.pt.x, this.pt.y))];
  }
  parallelTo(e27) {
    return kg.Utils.EQ_0(this.norm.cross(e27.norm));
  }
  incidentTo(e27) {
    return this.parallelTo(e27) && this.pt.on(e27);
  }
  contains(e27) {
    if (this.pt.equalTo(e27))
      return true;
    let t2 = new kg.Vector(this.pt, e27);
    return kg.Utils.EQ_0(this.norm.dot(t2));
  }
  coord(e27) {
    return R_(e27.x, e27.y).cross(this.norm);
  }
  intersect(e27) {
    return e27 instanceof kg.Point ? this.contains(e27) ? [e27] : [] : e27 instanceof kg.Line ? jg(this, e27) : e27 instanceof kg.Ray ? gf(e27, this) : e27 instanceof kg.Circle ? $g(this, e27) : e27 instanceof kg.Box ? Yg(this, e27) : e27 instanceof kg.Segment ? Hg(e27, this) : e27 instanceof kg.Arc ? Xg(this, e27) : e27 instanceof kg.Polygon ? sf(this, e27) : e27 instanceof kg.Multiline ? yf(this, e27) : undefined;
  }
  distanceTo(e27) {
    if (e27 instanceof kg.Point) {
      let [t2, n2] = kg.Distance.point2line(e27, this);
      return n2 = n2.reverse(), [t2, n2];
    }
    if (e27 instanceof kg.Circle) {
      let [t2, n2] = kg.Distance.circle2line(e27, this);
      return n2 = n2.reverse(), [t2, n2];
    }
    if (e27 instanceof kg.Segment) {
      let [t2, n2] = kg.Distance.segment2line(e27, this);
      return [t2, n2.reverse()];
    }
    if (e27 instanceof kg.Arc) {
      let [t2, n2] = kg.Distance.arc2line(e27, this);
      return [t2, n2.reverse()];
    }
    if (e27 instanceof kg.Box) {
      let [t2, n2] = kg.Distance.shape2polygon(this, new kg.Polygon(e27));
      return [t2, n2];
    }
    if (e27 instanceof kg.Polygon) {
      let [t2, n2] = kg.Distance.shape2polygon(this, e27);
      return [t2, n2];
    }
  }
  split(e27) {
    if (e27 instanceof kg.Point)
      return [new kg.Ray(e27, this.norm), new kg.Ray(e27, this.norm)];
    {
      let t2 = new kg.Multiline([this]), n2 = this.sortPoints(e27);
      return t2.split(n2), t2.toShapes();
    }
  }
  rotate(e27, t2 = new kg.Point) {
    return new kg.Line(this.pt.rotate(e27, t2), this.norm.rotate(e27));
  }
  transform(e27) {
    return new kg.Line(this.pt.transform(e27), this.norm.clone());
  }
  sortPoints(e27) {
    return e27.slice().sort((e28, t2) => this.coord(e28) < this.coord(t2) ? -1 : this.coord(e28) > this.coord(t2) ? 1 : 0);
  }
  get name() {
    return "line";
  }
  svg(e27, t2 = {}) {
    let n2 = Yg(this, e27);
    if (n2.length === 0)
      return "";
    let o3 = n2[0], i3 = n2.length === 2 ? n2[1] : n2.find((e28) => !e28.equalTo(o3));
    return i3 === undefined && (i3 = o3), new kg.Segment(o3, i3).svg(t2);
  }
  static points2norm(e27, t2) {
    if (e27.equalTo(t2))
      throw Dg.ILLEGAL_PARAMETERS;
    return new kg.Vector(e27, t2).normalize().rotate90CCW();
  }
};
var T_ = (...e27) => new kg.Line(...e27);
kg.line = T_;
var E_ = class extends I_ {
  constructor(...e27) {
    if (super(), this.pc = new kg.Point, this.r = 1, e27.length === 1 && e27[0] instanceof Object && e27[0].name === "circle") {
      let { pc: t2, r: n2 } = e27[0];
      this.pc = new kg.Point(t2), this.r = n2;
    } else {
      let [t2, n2] = [...e27];
      t2 && t2 instanceof kg.Point && (this.pc = t2.clone()), n2 !== undefined && (this.r = n2);
    }
  }
  clone() {
    return new kg.Circle(this.pc.clone(), this.r);
  }
  get center() {
    return this.pc;
  }
  get box() {
    return new kg.Box(this.pc.x - this.r, this.pc.y - this.r, this.pc.x + this.r, this.pc.y + this.r);
  }
  contains(e27) {
    return e27 instanceof kg.Point ? kg.Utils.LE(e27.distanceTo(this.center)[0], this.r) : e27 instanceof kg.Segment ? kg.Utils.LE(e27.start.distanceTo(this.center)[0], this.r) && kg.Utils.LE(e27.end.distanceTo(this.center)[0], this.r) : e27 instanceof kg.Arc ? this.intersect(e27).length === 0 && kg.Utils.LE(e27.start.distanceTo(this.center)[0], this.r) && kg.Utils.LE(e27.end.distanceTo(this.center)[0], this.r) : e27 instanceof kg.Circle ? this.intersect(e27).length === 0 && kg.Utils.LE(e27.r, this.r) && kg.Utils.LE(e27.center.distanceTo(this.center)[0], this.r) : undefined;
  }
  toArc(e27 = true) {
    return new kg.Arc(this.center, this.r, Math.PI, -Math.PI, e27);
  }
  scale(e27, t2) {
    if (e27 !== t2)
      throw Dg.OPERATION_IS_NOT_SUPPORTED;
    if (this.pc.x !== 0 || this.pc.y !== 0)
      throw Dg.OPERATION_IS_NOT_SUPPORTED;
    return new kg.Circle(this.pc, this.r * e27);
  }
  transform(e27 = new kg.Matrix) {
    return new kg.Circle(this.pc.transform(e27), this.r);
  }
  intersect(e27) {
    return e27 instanceof kg.Point ? this.contains(e27) ? [e27] : [] : e27 instanceof kg.Line ? $g(e27, this) : e27 instanceof kg.Ray ? mf(e27, this) : e27 instanceof kg.Segment ? Ug(e27, this) : e27 instanceof kg.Circle ? qg(e27, this) : e27 instanceof kg.Box ? function(e28, t2) {
      let n2 = [];
      for (let o3 of t2.toSegments()) {
        let t3 = Ug(o3, e28);
        for (let e29 of t3)
          n2.push(e29);
      }
      return n2;
    }(this, e27) : e27 instanceof kg.Arc ? Qg(e27, this) : e27 instanceof kg.Polygon ? af(this, e27) : e27 instanceof kg.Multiline ? yf(this, e27) : undefined;
  }
  distanceTo(e27) {
    if (e27 instanceof kg.Point) {
      let [t2, n2] = kg.Distance.point2circle(e27, this);
      return n2 = n2.reverse(), [t2, n2];
    }
    if (e27 instanceof kg.Circle) {
      let [t2, n2] = kg.Distance.circle2circle(this, e27);
      return [t2, n2];
    }
    if (e27 instanceof kg.Line) {
      let [t2, n2] = kg.Distance.circle2line(this, e27);
      return [t2, n2];
    }
    if (e27 instanceof kg.Segment) {
      let [t2, n2] = kg.Distance.segment2circle(e27, this);
      return n2 = n2.reverse(), [t2, n2];
    }
    if (e27 instanceof kg.Arc) {
      let [t2, n2] = kg.Distance.arc2circle(e27, this);
      return n2 = n2.reverse(), [t2, n2];
    }
    if (e27 instanceof kg.Box) {
      let [t2, n2] = kg.Distance.shape2polygon(this, new kg.Polygon(e27));
      return [t2, n2];
    }
    if (e27 instanceof kg.Polygon) {
      let [t2, n2] = kg.Distance.shape2polygon(this, e27);
      return [t2, n2];
    }
    if (e27 instanceof kg.PlanarSet) {
      let [t2, n2] = kg.Distance.shape2planarSet(this, e27);
      return [t2, n2];
    }
    if (e27 instanceof kg.Multiline) {
      let [t2, n2] = kg.Distance.shape2multiline(this, e27);
      return [t2, n2];
    }
  }
  get name() {
    return "circle";
  }
  svg(e27 = {}) {
    return `
<circle cx="${this.pc.x}" cy="${this.pc.y}" r="${this.r}"
                ${Fg({ fill: "none", ...e27 })} />`;
  }
};
kg.Circle = E_;
kg.circle = (...e27) => new kg.Circle(...e27);
var A_ = class extends I_ {
  constructor(...e27) {
    if (super(), this.pc = new kg.Point, this.r = 1, this.startAngle = 0, this.endAngle = 2 * Math.PI, this.counterClockwise = true, e27.length !== 0)
      if (e27.length === 1 && e27[0] instanceof Object && e27[0].name === "arc") {
        let { pc: t2, r: n2, startAngle: o3, endAngle: i3, counterClockwise: r3 } = e27[0];
        this.pc = new kg.Point(t2.x, t2.y), this.r = n2, this.startAngle = o3, this.endAngle = i3, this.counterClockwise = r3;
      } else {
        let [t2, n2, o3, i3, r3] = [...e27];
        t2 && t2 instanceof kg.Point && (this.pc = t2.clone()), n2 !== undefined && (this.r = n2), o3 !== undefined && (this.startAngle = o3), i3 !== undefined && (this.endAngle = i3), r3 !== undefined && (this.counterClockwise = r3);
      }
  }
  clone() {
    return new kg.Arc(this.pc.clone(), this.r, this.startAngle, this.endAngle, this.counterClockwise);
  }
  get sweep() {
    let e27 = this.startAngle, t2 = this.endAngle;
    if (kg.Utils.EQ(Math.abs(e27 - t2), kg.PIx2))
      return kg.PIx2;
    Math.abs(e27) > kg.PIx2 && (e27 -= Math.trunc(e27 / kg.PIx2) * kg.PIx2), e27 < 0 && (e27 += kg.PIx2), Math.abs(t2) > kg.PIx2 && (t2 -= Math.trunc(t2 / kg.PIx2) * kg.PIx2), t2 < 0 && (t2 += kg.PIx2);
    let n2 = this.counterClockwise ? t2 - e27 : e27 - t2;
    return n2 < 0 && (n2 += kg.PIx2), n2;
  }
  get start() {
    return new kg.Point(this.pc.x + this.r, this.pc.y).rotate(this.startAngle, this.pc);
  }
  get end() {
    return new kg.Point(this.pc.x + this.r, this.pc.y).rotate(this.endAngle, this.pc);
  }
  get center() {
    return this.pc.clone();
  }
  get vertices() {
    return [this.start.clone(), this.end.clone()];
  }
  get length() {
    return Math.abs(this.sweep * this.r);
  }
  get box() {
    let e27 = this.breakToFunctional().reduce((e28, t2) => e28.merge(t2.start.box), new kg.Box);
    return e27 = e27.merge(this.end.box), e27;
  }
  contains(e27) {
    if (!kg.Utils.EQ(this.pc.distanceTo(e27)[0], this.r))
      return false;
    if (e27.equalTo(this.start))
      return true;
    let t2 = new kg.Vector(this.pc, e27).slope, n2 = new kg.Arc(this.pc, this.r, this.startAngle, t2, this.counterClockwise);
    return kg.Utils.LE(n2.length, this.length);
  }
  split(e27) {
    if (this.start.equalTo(e27))
      return [null, this.clone()];
    if (this.end.equalTo(e27))
      return [this.clone(), null];
    let t2 = new kg.Vector(this.pc, e27).slope;
    return [new kg.Arc(this.pc, this.r, this.startAngle, t2, this.counterClockwise), new kg.Arc(this.pc, this.r, t2, this.endAngle, this.counterClockwise)];
  }
  middle() {
    let e27 = this.counterClockwise ? this.startAngle + this.sweep / 2 : this.startAngle - this.sweep / 2;
    return new kg.Arc(this.pc, this.r, this.startAngle, e27, this.counterClockwise).end;
  }
  pointAtLength(e27) {
    if (e27 > this.length || e27 < 0)
      return null;
    if (e27 === 0)
      return this.start;
    if (e27 === this.length)
      return this.end;
    let t2 = e27 / this.length, n2 = this.counterClockwise ? this.startAngle + this.sweep * t2 : this.startAngle - this.sweep * t2;
    return new kg.Arc(this.pc, this.r, this.startAngle, n2, this.counterClockwise).end;
  }
  chordHeight() {
    return (1 - Math.cos(Math.abs(this.sweep / 2))) * this.r;
  }
  intersect(e27) {
    return e27 instanceof kg.Point ? this.contains(e27) ? [e27] : [] : e27 instanceof kg.Line ? Xg(e27, this) : e27 instanceof kg.Ray ? pf(e27, this) : e27 instanceof kg.Circle ? Qg(this, e27) : e27 instanceof kg.Segment ? Zg(e27, this) : e27 instanceof kg.Box ? function(e28, t2) {
      let n2 = [];
      for (let o3 of t2.toSegments()) {
        let t3 = Zg(o3, e28);
        for (let e29 of t3)
          n2.push(e29);
      }
      return n2;
    }(this, e27) : e27 instanceof kg.Arc ? Jg(this, e27) : e27 instanceof kg.Polygon ? rf(this, e27) : e27 instanceof kg.Multiline ? yf(this, e27) : undefined;
  }
  distanceTo(e27) {
    if (e27 instanceof kg.Point) {
      let [t2, n2] = kg.Distance.point2arc(e27, this);
      return n2 = n2.reverse(), [t2, n2];
    }
    if (e27 instanceof kg.Circle) {
      let [t2, n2] = kg.Distance.arc2circle(this, e27);
      return [t2, n2];
    }
    if (e27 instanceof kg.Line) {
      let [t2, n2] = kg.Distance.arc2line(this, e27);
      return [t2, n2];
    }
    if (e27 instanceof kg.Segment) {
      let [t2, n2] = kg.Distance.segment2arc(e27, this);
      return n2 = n2.reverse(), [t2, n2];
    }
    if (e27 instanceof kg.Arc) {
      let [t2, n2] = kg.Distance.arc2arc(this, e27);
      return [t2, n2];
    }
    if (e27 instanceof kg.Box) {
      let [t2, n2] = kg.Distance.shape2polygon(this, new kg.Polygon(e27));
      return [t2, n2];
    }
    if (e27 instanceof kg.Polygon) {
      let [t2, n2] = kg.Distance.shape2polygon(this, e27);
      return [t2, n2];
    }
    if (e27 instanceof kg.PlanarSet) {
      let [t2, n2] = kg.Distance.shape2planarSet(this, e27);
      return [t2, n2];
    }
    if (e27 instanceof kg.Multiline)
      return kg.Distance.shape2multiline(this, e27);
  }
  breakToFunctional() {
    let e27 = [], t2 = [0, Math.PI / 2, Math.PI, 3 * Math.PI / 2], n2 = this.startAngle, o3 = this.endAngle;
    kg.Utils.EQ(Math.abs(n2 - o3), kg.PIx2) && (o3 = n2), Math.abs(n2) > kg.PIx2 && (n2 -= Math.trunc(n2 / kg.PIx2) * kg.PIx2), n2 < 0 && (n2 += kg.PIx2), Math.abs(o3) > kg.PIx2 && (o3 -= Math.trunc(o3 / kg.PIx2) * kg.PIx2), o3 < 0 && (o3 += kg.PIx2);
    let i3, r3, s2, a3 = n2;
    this.counterClockwise ? (r3 = Math.ceil(n2 / (Math.PI / 2)) % 4, s2 = 1) : (r3 = Math.floor(n2 / (Math.PI / 2)) % 4, s2 = -1);
    for (let o4 = 0, c3 = r3;o4 < 4; o4++, c3 = (c3 + s2 + 4) % 4) {
      if (i3 = t2[c3], i3 === a3)
        continue;
      let o5 = this.counterClockwise ? i3 - n2 : n2 - i3;
      if (o5 < 0 && (o5 += kg.PIx2), o5 > this.sweep)
        break;
      e27.push(new kg.Arc(this.pc, this.r, a3, i3, this.counterClockwise)), a3 = i3;
    }
    return e27.length === 0 ? (e27.push(this), e27) : (i3 = o3, a3 !== i3 && e27.push(new kg.Arc(this.pc, this.r, a3, i3, this.counterClockwise)), e27);
  }
  tangentInStart() {
    let e27 = new kg.Vector(this.pc, this.start), t2 = this.counterClockwise ? Math.PI / 2 : -Math.PI / 2;
    return e27.rotate(t2).normalize();
  }
  tangentInEnd() {
    let e27 = new kg.Vector(this.pc, this.end), t2 = this.counterClockwise ? -Math.PI / 2 : Math.PI / 2;
    return e27.rotate(t2).normalize();
  }
  reverse() {
    return new kg.Arc(this.pc, this.r, this.endAngle, this.startAngle, !this.counterClockwise);
  }
  transform(e27 = new kg.Matrix) {
    let t2 = this.start.transform(e27), n2 = this.end.transform(e27), o3 = this.pc.transform(e27), i3 = this.counterClockwise;
    return e27.a * e27.d < 0 && (i3 = !i3), kg.Arc.arcSE(o3, t2, n2, i3);
  }
  static arcSE(e27, t2, n2, o3) {
    let { vector: i3 } = kg, r3 = i3(e27, t2).slope, s2 = i3(e27, n2).slope;
    kg.Utils.EQ(r3, s2) && (s2 += 2 * Math.PI, o3 = true);
    let a3 = i3(e27, t2).length;
    return new kg.Arc(e27, a3, r3, s2, o3);
  }
  definiteIntegral(e27 = 0) {
    return this.breakToFunctional().reduce((t2, n2) => t2 + n2.circularSegmentDefiniteIntegral(e27), 0);
  }
  circularSegmentDefiniteIntegral(e27) {
    let t2 = new kg.Segment(this.start, this.end).definiteIntegral(e27), n2 = kg.Utils.EQ(this.sweep, kg.PIx2) ? 0 : this.circularSegmentArea();
    return this.counterClockwise ? t2 - n2 : t2 + n2;
  }
  circularSegmentArea() {
    return 0.5 * this.r * this.r * (this.sweep - Math.sin(this.sweep));
  }
  sortPoints(e27) {
    let { vector: t2 } = kg;
    return e27.slice().sort((e28, n2) => {
      let o3 = t2(this.pc, e28).slope, i3 = t2(this.pc, n2).slope;
      return o3 < i3 ? -1 : o3 > i3 ? 1 : 0;
    });
  }
  get name() {
    return "arc";
  }
  svg(e27 = {}) {
    let t2 = this.sweep <= Math.PI ? "0" : "1", n2 = this.counterClockwise ? "1" : "0";
    if (kg.Utils.EQ(this.sweep, 2 * Math.PI)) {
      return new kg.Circle(this.pc, this.r).svg(e27);
    }
    return `
<path d="M${this.start.x},${this.start.y}
                             A${this.r},${this.r} 0 ${t2},${n2} ${this.end.x},${this.end.y}"
                    ${Fg({ fill: "none", ...e27 })} />`;
  }
};
kg.Arc = A_;
kg.arc = (...e27) => new kg.Arc(...e27);
var O_ = class e27 extends I_ {
  constructor(e28 = undefined, t2 = undefined, n2 = undefined, o3 = undefined) {
    super(), this.xmin = e28, this.ymin = t2, this.xmax = n2, this.ymax = o3;
  }
  clone() {
    return new e27(this.xmin, this.ymin, this.xmax, this.ymax);
  }
  get low() {
    return new kg.Point(this.xmin, this.ymin);
  }
  get high() {
    return new kg.Point(this.xmax, this.ymax);
  }
  get max() {
    return this.clone();
  }
  get center() {
    return new kg.Point((this.xmin + this.xmax) / 2, (this.ymin + this.ymax) / 2);
  }
  get width() {
    return Math.abs(this.xmax - this.xmin);
  }
  get height() {
    return Math.abs(this.ymax - this.ymin);
  }
  get box() {
    return this.clone();
  }
  not_intersect(e28) {
    return this.xmax < e28.xmin || this.xmin > e28.xmax || this.ymax < e28.ymin || this.ymin > e28.ymax;
  }
  intersect(e28) {
    return !this.not_intersect(e28);
  }
  merge(t2) {
    return new e27(this.xmin === undefined ? t2.xmin : Math.min(this.xmin, t2.xmin), this.ymin === undefined ? t2.ymin : Math.min(this.ymin, t2.ymin), this.xmax === undefined ? t2.xmax : Math.max(this.xmax, t2.xmax), this.ymax === undefined ? t2.ymax : Math.max(this.ymax, t2.ymax));
  }
  less_than(e28) {
    return !!this.low.lessThan(e28.low) || !(!this.low.equalTo(e28.low) || !this.high.lessThan(e28.high));
  }
  equal_to(e28) {
    return this.low.equalTo(e28.low) && this.high.equalTo(e28.high);
  }
  output() {
    return this.clone();
  }
  comparable_less_than(e28, t2) {
    return e28.lessThan(t2);
  }
  set(e28, t2, n2, o3) {
    this.xmin = e28, this.ymin = t2, this.xmax = n2, this.ymax = o3;
  }
  extend(t2) {
    return t2 <= 0 ? this.clone() : new e27(this.xmin - t2, this.ymin - t2, this.xmax + t2, this.ymax + t2);
  }
  toPoints() {
    return [new kg.Point(this.xmin, this.ymin), new kg.Point(this.xmax, this.ymin), new kg.Point(this.xmax, this.ymax), new kg.Point(this.xmin, this.ymax)];
  }
  toSegments() {
    let e28 = this.toPoints();
    return [new kg.Segment(e28[0], e28[1]), new kg.Segment(e28[1], e28[2]), new kg.Segment(e28[2], e28[3]), new kg.Segment(e28[3], e28[0])];
  }
  rotate(e28, t2 = new kg.Point) {
    throw Dg.OPERATION_IS_NOT_SUPPORTED;
  }
  transform(t2 = new kg.Matrix) {
    return this.toPoints().map((e28) => e28.transform(t2)).reduce((e28, t3) => e28.merge(t3.box), new e27);
  }
  contains(e28) {
    return e28 instanceof kg.Point ? e28.x >= this.xmin && e28.x <= this.xmax && e28.y >= this.ymin && e28.y <= this.ymax : e28 instanceof kg.Segment ? e28.vertices.every((e29) => this.contains(e29)) : e28 instanceof kg.Box ? e28.toSegments().every((e29) => this.contains(e29)) : e28 instanceof kg.Circle ? this.contains(e28.box) : e28 instanceof kg.Arc ? e28.vertices.every((e29) => this.contains(e29)) && this.toSegments().every((t2) => Zg(t2, e28).length === 0) : !(e28 instanceof kg.Line || e28 instanceof kg.Ray) && (e28 instanceof kg.Multiline ? e28.toShapes().every((e29) => this.contains(e29)) : e28 instanceof kg.Polygon ? this.contains(e28.box) : undefined);
  }
  distanceTo(e28) {
    const t2 = this.toSegments().map((t3) => t3.distanceTo(e28));
    let n2 = [Number.MAX_SAFE_INTEGER, null];
    return t2.forEach((e29) => {
      e29[0] < n2[0] && (n2 = e29);
    }), n2;
  }
  get name() {
    return "box";
  }
  svg(e28 = {}) {
    const t2 = this.xmax - this.xmin, n2 = this.ymax - this.ymin;
    return `
<rect x="${this.xmin}" y="${this.ymin}" width="${t2}" height="${n2}"
                ${Fg({ fill: "none", ...e28 })} />`;
  }
};
kg.Box = O_;
kg.box = (...e28) => new kg.Box(...e28);
kg.Edge = class {
  constructor(e28) {
    this.shape = e28, this.next = undefined, this.prev = undefined, this.face = undefined, this.arc_length = 0, this.bvStart = undefined, this.bvEnd = undefined, this.bv = undefined, this.overlap = undefined;
  }
  get start() {
    return this.shape.start;
  }
  get end() {
    return this.shape.end;
  }
  get length() {
    return this.shape.length;
  }
  get box() {
    return this.shape.box;
  }
  get isSegment() {
    return this.shape instanceof kg.Segment;
  }
  get isArc() {
    return this.shape instanceof kg.Arc;
  }
  get isLine() {
    return this.shape instanceof kg.Line;
  }
  get isRay() {
    return this.shape instanceof kg.Ray;
  }
  middle() {
    return this.shape.middle();
  }
  pointAtLength(e28) {
    return this.shape.pointAtLength(e28);
  }
  contains(e28) {
    return this.shape.contains(e28);
  }
  setInclusion(e28) {
    if (this.bv !== undefined)
      return this.bv;
    if (this.shape instanceof kg.Line || this.shape instanceof kg.Ray)
      return this.bv = kg.OUTSIDE, this.bv;
    if (this.bvStart === undefined && (this.bvStart = a_(e28, this.start)), this.bvEnd === undefined && (this.bvEnd = a_(e28, this.end)), this.bvStart === kg.OUTSIDE || this.bvEnd == kg.OUTSIDE)
      this.bv = kg.OUTSIDE;
    else if (this.bvStart === kg.INSIDE || this.bvEnd == kg.INSIDE)
      this.bv = kg.INSIDE;
    else {
      let t2 = a_(e28, this.middle());
      this.bv = t2;
    }
    return this.bv;
  }
  setOverlap(e28) {
    let t2, n2 = this.shape, o3 = e28.shape;
    n2 instanceof kg.Segment && o3 instanceof kg.Segment ? n2.start.equalTo(o3.start) && n2.end.equalTo(o3.end) ? t2 = kg.OVERLAP_SAME : n2.start.equalTo(o3.end) && n2.end.equalTo(o3.start) && (t2 = kg.OVERLAP_OPPOSITE) : (n2 instanceof kg.Arc && o3 instanceof kg.Arc || n2 instanceof kg.Segment && o3 instanceof kg.Arc || n2 instanceof kg.Arc && o3 instanceof kg.Segment) && (n2.start.equalTo(o3.start) && n2.end.equalTo(o3.end) && n2.middle().equalTo(o3.middle()) ? t2 = kg.OVERLAP_SAME : n2.start.equalTo(o3.end) && n2.end.equalTo(o3.start) && n2.middle().equalTo(o3.middle()) && (t2 = kg.OVERLAP_OPPOSITE)), this.overlap === undefined && (this.overlap = t2), e28.overlap === undefined && (e28.overlap = t2);
  }
  svg() {
    if (this.shape instanceof kg.Segment)
      return ` L${this.shape.end.x},${this.shape.end.y}`;
    if (this.shape instanceof kg.Arc) {
      let e28, t2 = this.shape, n2 = t2.counterClockwise ? "1" : "0";
      if (kg.Utils.EQ(t2.sweep, 2 * Math.PI)) {
        let o3 = t2.counterClockwise ? 1 : -1, i3 = new kg.Arc(t2.pc, t2.r, t2.startAngle, t2.startAngle + o3 * Math.PI, t2.counterClockwise), r3 = new kg.Arc(t2.pc, t2.r, t2.startAngle + o3 * Math.PI, t2.endAngle, t2.counterClockwise);
        return e28 = "0", ` A${i3.r},${i3.r} 0 ${e28},${n2} ${i3.end.x},${i3.end.y}
                    A${r3.r},${r3.r} 0 ${e28},${n2} ${r3.end.x},${r3.end.y}`;
      }
      return e28 = t2.sweep <= Math.PI ? "0" : "1", ` A${t2.r},${t2.r} 0 ${e28},${n2} ${t2.end.x},${t2.end.y}`;
    }
  }
  toJSON() {
    return this.shape.toJSON();
  }
};
var k_ = class extends Lg {
  constructor(e28, t2) {
    super(e28, t2), this.setCircularLinks();
  }
  setCircularLinks() {
    this.isEmpty() || (this.last.next = this.first, this.first.prev = this.last);
  }
  [Symbol.iterator]() {
    let e28;
    return { next: () => {
      let t2 = e28 || this.first, n2 = !this.first || !!e28 && e28 === this.first;
      return e28 = t2 ? t2.next : undefined, { value: t2, done: n2 };
    } };
  }
  append(e28) {
    return super.append(e28), this.setCircularLinks(), this;
  }
  insert(e28, t2) {
    return super.insert(e28, t2), this.setCircularLinks(), this;
  }
  remove(e28) {
    return super.remove(e28), this;
  }
};
kg.Face = class e28 extends k_ {
  constructor(t2, ...n2) {
    if (super(), this._box = undefined, this._orientation = undefined, n2.length !== 0) {
      if (n2.length === 1) {
        if (n2[0] instanceof Array) {
          let o3 = n2[0];
          if (o3.length === 0)
            return;
          if (o3.every((e29) => e29 instanceof kg.Point)) {
            let n3 = e28.points2segments(o3);
            this.shapes2face(t2.edges, n3);
          } else if (o3.every((e29) => e29 instanceof Array && e29.length === 2)) {
            let n3 = o3.map((e29) => new kg.Point(e29[0], e29[1])), i3 = e28.points2segments(n3);
            this.shapes2face(t2.edges, i3);
          } else if (o3.every((e29) => e29 instanceof kg.Segment || e29 instanceof kg.Arc))
            this.shapes2face(t2.edges, o3);
          else if (o3.every((e29) => e29.name === "segment" || e29.name === "arc")) {
            let e29 = [];
            for (let t3 of o3) {
              let n3;
              n3 = t3.name === "segment" ? new kg.Segment(t3) : new kg.Arc(t3), e29.push(n3);
            }
            this.shapes2face(t2.edges, e29);
          }
        } else if (n2[0] instanceof e28) {
          let e29 = n2[0];
          this.first = e29.first, this.last = e29.last;
          for (let n3 of e29)
            t2.edges.add(n3);
        } else if (n2[0] instanceof kg.Circle)
          this.shapes2face(t2.edges, [n2[0].toArc(Sg)]);
        else if (n2[0] instanceof kg.Box) {
          let e29 = n2[0];
          this.shapes2face(t2.edges, [new kg.Segment(new kg.Point(e29.xmin, e29.ymin), new kg.Point(e29.xmax, e29.ymin)), new kg.Segment(new kg.Point(e29.xmax, e29.ymin), new kg.Point(e29.xmax, e29.ymax)), new kg.Segment(new kg.Point(e29.xmax, e29.ymax), new kg.Point(e29.xmin, e29.ymax)), new kg.Segment(new kg.Point(e29.xmin, e29.ymax), new kg.Point(e29.xmin, e29.ymin))]);
        }
      }
      n2.length === 2 && n2[0] instanceof kg.Edge && n2[1] instanceof kg.Edge && (this.first = n2[0], this.last = n2[1], this.last.next = this.first, this.first.prev = this.last, this.setArcLength());
    }
  }
  get edges() {
    return this.toArray();
  }
  get vertices() {
    return this.edges.map((e29) => e29.shape.start.clone());
  }
  get shapes() {
    return this.edges.map((e29) => e29.shape.clone());
  }
  get box() {
    if (this._box === undefined) {
      let e29 = new kg.Box;
      for (let t2 of this)
        e29 = e29.merge(t2.box);
      this._box = e29;
    }
    return this._box;
  }
  get perimeter() {
    return this.last.arc_length + this.last.length;
  }
  pointAtLength(e29) {
    if (e29 > this.perimeter || e29 < 0)
      return null;
    let t2 = null;
    for (let n2 of this)
      if (e29 >= n2.arc_length && (n2 === this.last || e29 < n2.next.arc_length)) {
        t2 = n2.pointAtLength(e29 - n2.arc_length);
        break;
      }
    return t2;
  }
  static points2segments(e29) {
    let t2 = [];
    for (let n2 = 0;n2 < e29.length; n2++)
      e29[n2].equalTo(e29[(n2 + 1) % e29.length]) || t2.push(new kg.Segment(e29[n2], e29[(n2 + 1) % e29.length]));
    return t2;
  }
  shapes2face(e29, t2) {
    for (let n2 of t2) {
      let t3 = new kg.Edge(n2);
      this.append(t3), e29.add(t3);
    }
  }
  append(e29) {
    return super.append(e29), this.setOneEdgeArcLength(e29), e29.face = this, this;
  }
  insert(e29, t2) {
    return super.insert(e29, t2), this.setOneEdgeArcLength(e29), e29.face = this, this;
  }
  remove(e29) {
    return super.remove(e29), this.setArcLength(), this;
  }
  merge_with_next_edge(e29) {
    return e29.shape.end.x = e29.next.shape.end.x, e29.shape.end.y = e29.next.shape.end.y, this.remove(e29.next), this;
  }
  reverse() {
    let e29 = [], t2 = this.last;
    do {
      t2.shape = t2.shape.reverse(), e29.push(t2), t2 = t2.prev;
    } while (t2 !== this.last);
    this.first = undefined, this.last = undefined;
    for (let t3 of e29)
      this.first === undefined ? (t3.prev = t3, t3.next = t3, this.first = t3, this.last = t3) : (t3.prev = this.last, this.last.next = t3, this.last = t3, this.last.next = this.first, this.first.prev = this.last), this.setOneEdgeArcLength(t3);
    this._orientation !== undefined && (this._orientation = undefined, this._orientation = this.orientation());
  }
  setArcLength() {
    for (let e29 of this)
      this.setOneEdgeArcLength(e29), e29.face = this;
  }
  setOneEdgeArcLength(e29) {
    e29 === this.first ? e29.arc_length = 0 : e29.arc_length = e29.prev.arc_length + e29.prev.length;
  }
  area() {
    return Math.abs(this.signedArea());
  }
  signedArea() {
    let e29 = 0, t2 = this.box.ymin;
    for (let n2 of this)
      e29 += n2.shape.definiteIntegral(t2);
    return e29;
  }
  orientation() {
    if (this._orientation === undefined) {
      let e29 = this.signedArea();
      kg.Utils.EQ_0(e29) ? this._orientation = Cg.NOT_ORIENTABLE : kg.Utils.LT(e29, 0) ? this._orientation = Cg.CCW : this._orientation = Cg.CW;
    }
    return this._orientation;
  }
  isSimple(t2) {
    return e28.getSelfIntersections(this, t2, true).length === 0;
  }
  static getSelfIntersections(e29, t2, n2 = false) {
    let o3 = [];
    for (let i3 of e29) {
      let r3 = t2.search(i3.box);
      for (let t3 of r3) {
        if (i3 === t3)
          continue;
        if (t3.face !== e29)
          continue;
        if (i3.shape instanceof kg.Segment && t3.shape instanceof kg.Segment && (i3.next === t3 || i3.prev === t3))
          continue;
        let r4 = i3.shape.intersect(t3.shape);
        for (let e30 of r4)
          if ((!e30.equalTo(i3.start) || !e30.equalTo(t3.end) || t3 !== i3.prev) && (!e30.equalTo(i3.end) || !e30.equalTo(t3.start) || t3 !== i3.next) && (o3.push(e30), n2))
            break;
        if (o3.length > 0 && n2)
          break;
      }
      if (o3.length > 0 && n2)
        break;
    }
    return o3;
  }
  findEdgeByPoint(e29) {
    let t2;
    for (let n2 of this)
      if (!e29.equalTo(n2.shape.start) && (e29.equalTo(n2.shape.end) || n2.shape.contains(e29))) {
        t2 = n2;
        break;
      }
    return t2;
  }
  toPolygon() {
    return new kg.Polygon(this.shapes);
  }
  toJSON() {
    return this.edges.map((e29) => e29.toJSON());
  }
  svg() {
    let e29 = `M${this.first.start.x},${this.first.start.y}`;
    for (let t2 of this)
      e29 += t2.svg();
    return e29 += " z", e29;
  }
};
kg.Ray = class e29 extends I_ {
  constructor(...e30) {
    if (super(), this.pt = new kg.Point, this.norm = new kg.Vector(0, 1), e30.length !== 0 && (e30.length >= 1 && e30[0] instanceof kg.Point && (this.pt = e30[0].clone()), e30.length !== 1)) {
      if (!(e30.length === 2 && e30[1] instanceof kg.Vector))
        throw Dg.ILLEGAL_PARAMETERS;
      this.norm = e30[1].clone();
    }
  }
  clone() {
    return new e29(this.pt, this.norm);
  }
  get slope() {
    return new kg.Vector(this.norm.y, -this.norm.x).slope;
  }
  get box() {
    let e30 = this.slope;
    return new kg.Box(e30 > Math.PI / 2 && e30 < 3 * Math.PI / 2 ? Number.NEGATIVE_INFINITY : this.pt.x, e30 >= 0 && e30 <= Math.PI ? this.pt.y : Number.NEGATIVE_INFINITY, e30 >= Math.PI / 2 && e30 <= 3 * Math.PI / 2 ? this.pt.x : Number.POSITIVE_INFINITY, e30 >= Math.PI && e30 <= 2 * Math.PI || e30 === 0 ? this.pt.y : Number.POSITIVE_INFINITY);
  }
  get start() {
    return this.pt;
  }
  get end() {}
  get length() {
    return Number.POSITIVE_INFINITY;
  }
  contains(e30) {
    if (this.pt.equalTo(e30))
      return true;
    let t2 = new kg.Vector(this.pt, e30);
    return kg.Utils.EQ_0(this.norm.dot(t2)) && kg.Utils.GE(t2.cross(this.norm), 0);
  }
  coord(e30) {
    return M_(e30.x, e30.y).cross(this.norm);
  }
  split(e30) {
    return this.contains(e30) ? this.pt.equalTo(e30) ? [this] : [new kg.Segment(this.pt, e30), new kg.Ray(e30, this.norm)] : [];
  }
  intersect(e30) {
    return e30 instanceof kg.Point ? this.contains(e30) ? [e30] : [] : e30 instanceof kg.Segment ? uf(this, e30) : e30 instanceof kg.Arc ? pf(this, e30) : e30 instanceof kg.Line ? gf(this, e30) : e30 instanceof kg.Ray ? (n2 = e30, jg(df(t2 = this), df(n2)).filter((e31) => t2.contains(e31)).filter((e31) => n2.contains(e31))) : e30 instanceof kg.Circle ? mf(this, e30) : e30 instanceof kg.Box ? (i3 = e30, Yg(df(o3 = this), i3).filter((e31) => o3.contains(e31))) : e30 instanceof kg.Polygon ? ff(this, e30) : e30 instanceof kg.Multiline ? yf(this, e30) : undefined;
    var t2, n2, o3, i3;
  }
  rotate(e30, t2 = new kg.Point) {
    return new kg.Ray(this.pt.rotate(e30, t2), this.norm.rotate(e30));
  }
  transform(e30) {
    return new kg.Ray(this.pt.transform(e30), this.norm.clone());
  }
  get name() {
    return "ray";
  }
  svg(e30, t2 = {}) {
    let n2 = Yg(new kg.Line(this.pt, this.norm), e30);
    return n2 = n2.filter((e31) => this.contains(e31)), n2.length === 0 || n2.length === 2 ? "" : new kg.Segment(this.pt, n2[0]).svg(t2);
  }
};
kg.ray = (...e30) => new kg.Ray(...e30);
var D_ = class e30 {
  constructor() {
    this.faces = new kg.PlanarSet, this.edges = new kg.PlanarSet;
    let e31 = [...arguments];
    if (e31.length === 1 && (e31[0] instanceof Array && e31[0].length > 0 || e31[0] instanceof kg.Circle || e31[0] instanceof kg.Box)) {
      let t2 = e31[0];
      if (e31[0] instanceof Array && e31[0].every((e32) => e32 instanceof Array))
        if (t2.every((e32) => e32 instanceof Array && e32.length === 2 && typeof e32[0] == "number" && typeof e32[1] == "number"))
          this.faces.add(new kg.Face(this, t2));
        else
          for (let e32 of t2)
            if (e32 instanceof Array && e32[0] instanceof Array && e32[0].every((e33) => e33 instanceof Array && e33.length === 2 && typeof e33[0] == "number" && typeof e33[1] == "number"))
              for (let t3 of e32)
                this.faces.add(new kg.Face(this, t3));
            else
              this.faces.add(new kg.Face(this, e32));
      else
        this.faces.add(new kg.Face(this, t2));
    }
  }
  get box() {
    return [...this.faces].reduce((e31, t2) => e31.merge(t2.box), new kg.Box);
  }
  get vertices() {
    return [...this.faces].flatMap((e31) => e31.vertices);
  }
  clone() {
    let t2 = new e30;
    for (let e31 of this.faces)
      t2.addFace(e31.shapes);
    return t2;
  }
  createFromArray(t2) {
    const n2 = new e30;
    return t2.forEach((e31) => [...e31.faces].forEach((e32) => n2.addFace(e32.shapes))), n2;
  }
  isEmpty() {
    return this.edges.size === 0 || this.faces.size === 0;
  }
  isValid() {
    let e31 = true;
    for (let t2 of this.faces)
      if (!t2.isSimple(this.edges)) {
        e31 = false;
        break;
      }
    return e31;
  }
  area() {
    let e31 = [...this.faces].reduce((e32, t2) => e32 + t2.signedArea(), 0);
    return Math.abs(e31);
  }
  addFace(...e31) {
    let t2 = new kg.Face(this, ...e31);
    return this.faces.add(t2), t2;
  }
  deleteFace(e31) {
    for (let t2 of e31)
      this.edges.delete(t2);
    return this.faces.delete(e31);
  }
  recreateFaces() {
    this.faces.clear();
    for (let e32 of this.edges)
      e32.face = null;
    let e31, t2 = true;
    for (;t2; ) {
      t2 = false;
      for (let n2 of this.edges)
        if (n2.face === null) {
          e31 = n2, t2 = true;
          break;
        }
      if (t2) {
        let t3 = e31;
        do {
          t3 = t3.next;
        } while (t3.next !== e31);
        this.addFace(e31, t3);
      }
    }
  }
  removeChain(e31, t2, n2) {
    if (n2.next !== t2) {
      for (let o3 = t2;o3 !== n2.next; o3 = o3.next)
        if (e31.remove(o3), this.edges.delete(o3), e31.isEmpty()) {
          this.deleteFace(e31);
          break;
        }
    } else
      this.deleteFace(e31);
  }
  addVertex(e31, t2) {
    let n2 = t2.shape.split(e31);
    if (n2[0] === null)
      return t2.prev;
    if (n2[1] === null)
      return t2;
    let o3 = new kg.Edge(n2[0]), i3 = t2.prev;
    return t2.face.insert(o3, i3), this.edges.delete(t2), this.edges.add(o3), t2.shape = n2[1], this.edges.add(t2), o3;
  }
  removeEndVertex(e31) {
    const t2 = e31.next;
    t2 !== e31 && (e31.face.merge_with_next_edge(e31), this.edges.delete(t2));
  }
  cut(e31) {
    const t2 = this.splitToIslands().flatMap((t3) => t3._cutSingleIsland(e31)).filter((e32) => e32.isValid() && e32.isEmpty() === false);
    return this.createFromArray(t2);
  }
  _cutSingleIsland(e31) {
    let t2 = this.clone();
    const n2 = e31.clone();
    let o3, i3, r3 = { int_points1: [], int_points2: [], int_points1_sorted: [], int_points2_sorted: [] };
    for (let e32 of n2.edges)
      for (let n3 of t2.edges) {
        let t3 = cf(e32, n3);
        for (let o4 of t3)
          xf(e32, o4, r3.int_points1), xf(n3, o4, r3.int_points2);
      }
    if (r3.int_points1.length === 0)
      return t2;
    r3.int_points1_sorted = If(r3.int_points1), r3.int_points2_sorted = If(r3.int_points2), Nf(n2, r3.int_points1_sorted), Nf(t2, r3.int_points2_sorted), Cf(r3), r3.int_points1_sorted = If(r3.int_points1), r3.int_points2_sorted = If(r3.int_points2), Pf(r3.int_points1), Mf(r3.int_points1, t2);
    for (let e32 of r3.int_points1_sorted)
      e32.edge_before && e32.edge_after && e32.edge_before.bv === e32.edge_after.bv && (r3.int_points2[e32.id] = -1, e32.id = -1);
    if (r3.int_points1 = r3.int_points1.filter((e32) => e32.id >= 0), r3.int_points2 = r3.int_points2.filter((e32) => e32.id >= 0), r3.int_points1.forEach((e32, t3) => {
      e32.id = t3;
    }), r3.int_points2.forEach((e32, t3) => {
      e32.id = t3;
    }), r3.int_points1.length === 0)
      return t2;
    r3.int_points1_sorted = If(r3.int_points1), r3.int_points2_sorted = If(r3.int_points2);
    for (let e32 = 1;e32 < r3.int_points1_sorted.length; e32++)
      if (i3 = r3.int_points1_sorted[e32], o3 = r3.int_points1_sorted[e32 - 1], i3.edge_before && i3.edge_before.bv === 1) {
        let e33 = o3.edge_after, s2 = i3.edge_before, a3 = n2.getChain(e33, s2);
        Rf(r3.int_points2[o3.id], r3.int_points2[i3.id], a3), a3.forEach((e34) => t2.edges.add(e34)), a3 = a3.reverse().map((e34) => new kg.Edge(e34.shape.reverse()));
        for (let e34 = 0;e34 < a3.length - 1; e34++)
          a3[e34].next = a3[e34 + 1], a3[e34 + 1].prev = a3[e34];
        Rf(r3.int_points2[i3.id], r3.int_points2[o3.id], a3), a3.forEach((e34) => t2.edges.add(e34));
      }
    return t2.recreateFaces(), t2;
  }
  cutWithLine(e31) {
    let t2 = new bf([e31]);
    return this.cut(t2);
  }
  findEdgeByPoint(e31) {
    let t2;
    for (let n2 of this.faces)
      if (t2 = n2.findEdgeByPoint(e31), t2 !== undefined)
        break;
    return t2;
  }
  splitToIslands() {
    if (this.isEmpty())
      return [];
    let e31 = this.toArray();
    e31.sort((e32, t3) => t3.area() - e32.area());
    let t2 = [...e31[0].faces][0].orientation(), n2 = e31.filter((e32) => [...e32.faces][0].orientation() === t2);
    for (let o3 of e31) {
      let e32 = [...o3.faces][0];
      if (e32.orientation() !== t2) {
        for (let t3 of n2)
          if (e32.shapes.every((e33) => t3.contains(e33))) {
            t3.addFace(e32.shapes);
            break;
          }
      }
    }
    return n2;
  }
  rearrange() {
    if (this.faces.size <= 1)
      return this.clone();
    const t2 = this.splitToIslands(), n2 = new e30;
    return t2.forEach((e31) => {
      e31.faces.forEach((e32) => n2.addFace(e32.shapes));
    }), n2;
  }
  orientation() {
    return this.isEmpty() ? Cg.NOT_ORIENTABLE : [...this.faces][0].orientation();
  }
  isOuter(e31) {
    return e31.orientation() === this.orientation();
  }
  isMultiPolygon() {
    let e31 = 0;
    return this.faces.forEach((t2) => {
      this.isOuter(t2) && e31++;
    }), e31 > 1;
  }
  reverse() {
    for (let e31 of this.faces)
      e31.reverse();
    return this;
  }
  contains(e31) {
    if (e31 instanceof kg.Point) {
      let t2 = a_(this, e31);
      return t2 === 1 || t2 === 2;
    }
    return d_(this, e31);
  }
  distanceTo(e31) {
    if (e31 instanceof kg.Point) {
      let [t2, n2] = kg.Distance.point2polygon(e31, this);
      return n2 = n2.reverse(), [t2, n2];
    }
    if (e31 instanceof kg.Circle || e31 instanceof kg.Line || e31 instanceof kg.Segment || e31 instanceof kg.Arc) {
      let [t2, n2] = kg.Distance.shape2polygon(e31, this);
      return n2 = n2.reverse(), [t2, n2];
    }
    if (e31 instanceof kg.Box)
      return this.distanceTo(new kg.Polygon(e31));
    if (e31 instanceof kg.Polygon) {
      let t2, n2, o3 = [Number.POSITIVE_INFINITY, new kg.Segment];
      for (let i3 of this.edges) {
        let r3 = o3[0];
        [t2, n2] = kg.Distance.shape2planarSet(i3.shape, e31.edges, r3), kg.Utils.LT(t2, r3) && (o3 = [t2, n2]);
      }
      return o3;
    }
  }
  intersect(e31) {
    return e31 instanceof kg.Point ? this.contains(e31) ? [e31] : [] : e31 instanceof kg.Line ? sf(e31, this) : e31 instanceof kg.Ray ? ff(e31, this) : e31 instanceof kg.Circle ? af(e31, this) : e31 instanceof kg.Segment ? of(e31, this) : e31 instanceof kg.Arc ? rf(e31, this) : e31 instanceof kg.Polygon ? function(e32, t2) {
      let n2 = [];
      if (e32.isEmpty() || t2.isEmpty())
        return n2;
      if (e32.box.not_intersect(t2.box))
        return n2;
      for (let o3 of e32.edges)
        n2 = [...n2, ...lf(o3, t2)];
      return n2;
    }(e31, this) : e31 instanceof kg.Multiline ? function(e32, t2) {
      let n2 = [];
      if (t2.isEmpty() || e32.size === 0)
        return n2;
      for (let o3 of e32)
        n2 = [...n2, ...lf(o3, t2)];
      return n2;
    }(e31, this) : undefined;
  }
  translate(t2) {
    let n2 = new e30;
    for (let e31 of this.faces)
      n2.addFace(e31.shapes.map((e32) => e32.translate(t2)));
    return n2;
  }
  rotate(t2 = 0, n2 = new kg.Point) {
    let o3 = new e30;
    for (let e31 of this.faces)
      o3.addFace(e31.shapes.map((e32) => e32.rotate(t2, n2)));
    return o3;
  }
  scale(t2, n2) {
    let o3 = new e30;
    for (let e31 of this.faces)
      o3.addFace(e31.shapes.map((e32) => e32.scale(t2, n2)));
    return o3;
  }
  transform(t2 = new kg.Matrix) {
    let n2 = new e30;
    for (let e31 of this.faces)
      n2.addFace(e31.shapes.map((e32) => e32.transform(t2)));
    return n2;
  }
  toJSON() {
    return [...this.faces].map((e31) => e31.toJSON());
  }
  toArray() {
    return [...this.faces].map((e31) => e31.toPolygon());
  }
  dpath() {
    return [...this.faces].reduce((e31, t2) => e31 + t2.svg(), "");
  }
  svg(e31 = {}) {
    let t2 = `
<path ${Fg({ fillRule: "evenodd", fill: "lightcyan", ...e31 })} d="`;
    for (let e32 of this.faces)
      t2 += `
${e32.svg()}`;
    return t2 += `" >
</path>`, t2;
  }
};
kg.Polygon = D_;
kg.polygon = (...e31) => new kg.Polygon(...e31);
var { Circle: L_, Line: z_, Point: B_, Vector: F_, Utils: j_ } = kg;
kg.Inversion = class e31 {
  constructor(e32) {
    this.circle = e32;
  }
  get inversion_circle() {
    return this.circle;
  }
  static inversePoint(e32, t2) {
    const n2 = new F_(e32.pc, t2), o3 = e32.r * e32.r, i3 = n2.dot(n2);
    return j_.EQ_0(i3) ? new B_(Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY) : e32.pc.translate(n2.multiply(o3 / i3));
  }
  static inverseCircle(e32, t2) {
    const n2 = e32.pc.distanceTo(t2.pc)[0];
    if (j_.EQ(n2, t2.r)) {
      let n3 = e32.r * e32.r / (2 * t2.r), o3 = new F_(e32.pc, t2.pc);
      o3 = o3.normalize();
      let i3 = e32.pc.translate(o3.multiply(n3));
      return new z_(i3, o3);
    }
    {
      let n3 = new F_(e32.pc, t2.pc), o3 = e32.r * e32.r / (n3.dot(n3) - t2.r * t2.r), i3 = e32.pc.translate(n3.multiply(o3)), r3 = Math.abs(o3) * t2.r;
      return new L_(i3, r3);
    }
  }
  static inverseLine(e32, t2) {
    const [n2, o3] = e32.pc.distanceTo(t2);
    if (j_.EQ_0(n2))
      return t2.clone();
    {
      let t3 = e32.r * e32.r / (2 * n2), i3 = new F_(e32.pc, o3.end);
      return i3 = i3.multiply(t3 / n2), new L_(e32.pc.translate(i3), t3);
    }
  }
  inverse(t2) {
    return t2 instanceof B_ ? e31.inversePoint(this.circle, t2) : t2 instanceof L_ ? e31.inverseCircle(this.circle, t2) : t2 instanceof z_ ? e31.inverseLine(this.circle, t2) : undefined;
  }
};
kg.inversion = (e32) => new kg.Inversion(e32);
kg.Distance = class e32 {
  static point2point(e33, t2) {
    return e33.distanceTo(t2);
  }
  static point2line(e33, t2) {
    let n2 = e33.projectionOn(t2);
    return [new kg.Vector(e33, n2).length, new kg.Segment(e33, n2)];
  }
  static point2circle(e33, t2) {
    let [n2, o3] = e33.distanceTo(t2.center);
    if (kg.Utils.EQ_0(n2))
      return [t2.r, new kg.Segment(e33, t2.toArc().start)];
    {
      let o4 = Math.abs(n2 - t2.r), i3 = new kg.Vector(t2.pc, e33).normalize().multiply(t2.r), r3 = t2.pc.translate(i3);
      return [o4, new kg.Segment(e33, r3)];
    }
  }
  static point2segment(t2, n2) {
    if (n2.start.equalTo(n2.end))
      return e32.point2point(t2, n2.start);
    let o3, i3, r3 = new kg.Vector(n2.start, n2.end), s2 = new kg.Vector(n2.start, t2), a3 = new kg.Vector(n2.end, t2), c3 = r3.dot(s2), l3 = -r3.dot(a3);
    if (kg.Utils.GE(c3, 0) && kg.Utils.GE(l3, 0)) {
      let e33 = n2.tangentInStart();
      return o3 = Math.abs(e33.cross(s2)), i3 = n2.start.translate(e33.multiply(e33.dot(s2))), [o3, new kg.Segment(t2, i3)];
    }
    return c3 < 0 ? t2.distanceTo(n2.start) : t2.distanceTo(n2.end);
  }
  static point2arc(t2, n2) {
    let o3, i3, r3 = new kg.Circle(n2.pc, n2.r), s2 = [];
    return [o3, i3] = e32.point2circle(t2, r3), i3.end.on(n2) && s2.push(e32.point2circle(t2, r3)), s2.push(e32.point2point(t2, n2.start)), s2.push(e32.point2point(t2, n2.end)), e32.sort(s2), s2[0];
  }
  static point2edge(t2, n2) {
    return n2.shape instanceof kg.Segment ? e32.point2segment(t2, n2.shape) : e32.point2arc(t2, n2.shape);
  }
  static segment2line(t2, n2) {
    let o3 = t2.intersect(n2);
    if (o3.length > 0)
      return [0, new kg.Segment(o3[0], o3[0])];
    let i3 = [];
    return i3.push(e32.point2line(t2.start, n2)), i3.push(e32.point2line(t2.end, n2)), e32.sort(i3), i3[0];
  }
  static segment2segment(t2, n2) {
    let o3 = Vg(t2, n2);
    if (o3.length > 0)
      return [0, new kg.Segment(o3[0], o3[0])];
    let i3, r3, s2 = [];
    return [i3, r3] = e32.point2segment(n2.start, t2), s2.push([i3, r3.reverse()]), [i3, r3] = e32.point2segment(n2.end, t2), s2.push([i3, r3.reverse()]), s2.push(e32.point2segment(t2.start, n2)), s2.push(e32.point2segment(t2.end, n2)), e32.sort(s2), s2[0];
  }
  static segment2circle(t2, n2) {
    let o3 = t2.intersect(n2);
    if (o3.length > 0)
      return [0, new kg.Segment(o3[0], o3[0])];
    let i3 = new kg.Line(t2.ps, t2.pe), [r3, s2] = e32.point2line(n2.center, i3);
    if (kg.Utils.GE(r3, n2.r) && s2.end.on(t2))
      return e32.point2circle(s2.end, n2);
    {
      let [o4, i4] = e32.point2circle(t2.start, n2), [r4, s3] = e32.point2circle(t2.end, n2);
      return kg.Utils.LT(o4, r4) ? [o4, i4] : [r4, s3];
    }
  }
  static segment2arc(t2, n2) {
    let o3 = t2.intersect(n2);
    if (o3.length > 0)
      return [0, new kg.Segment(o3[0], o3[0])];
    let i3 = new kg.Line(t2.ps, t2.pe), r3 = new kg.Circle(n2.pc, n2.r), [s2, a3] = e32.point2line(r3.center, i3);
    if (kg.Utils.GE(s2, r3.r) && a3.end.on(t2)) {
      let [t3, o4] = e32.point2circle(a3.end, r3);
      if (o4.end.on(n2))
        return [t3, o4];
    }
    let c3, l3, h2 = [];
    return h2.push(e32.point2arc(t2.start, n2)), h2.push(e32.point2arc(t2.end, n2)), [c3, l3] = e32.point2segment(n2.start, t2), h2.push([c3, l3.reverse()]), [c3, l3] = e32.point2segment(n2.end, t2), h2.push([c3, l3.reverse()]), e32.sort(h2), h2[0];
  }
  static circle2circle(t2, n2) {
    let o3 = t2.intersect(n2);
    if (o3.length > 0)
      return [0, new kg.Segment(o3[0], o3[0])];
    if (t2.center.equalTo(n2.center)) {
      let o4 = t2.toArc(), i3 = n2.toArc();
      return e32.point2point(o4.start, i3.start);
    }
    {
      let o4 = new kg.Line(t2.center, n2.center), i3 = o4.intersect(t2), r3 = o4.intersect(n2), s2 = [];
      return s2.push(e32.point2point(i3[0], r3[0])), s2.push(e32.point2point(i3[0], r3[1])), s2.push(e32.point2point(i3[1], r3[0])), s2.push(e32.point2point(i3[1], r3[1])), e32.sort(s2), s2[0];
    }
  }
  static circle2line(t2, n2) {
    let o3 = t2.intersect(n2);
    if (o3.length > 0)
      return [0, new kg.Segment(o3[0], o3[0])];
    let [i3, r3] = e32.point2line(t2.center, n2), [s2, a3] = e32.point2circle(r3.end, t2);
    return a3 = a3.reverse(), [s2, a3];
  }
  static arc2line(t2, n2) {
    let o3 = n2.intersect(t2);
    if (o3.length > 0)
      return [0, new kg.Segment(o3[0], o3[0])];
    let i3 = new kg.Circle(t2.center, t2.r), [r3, s2] = e32.point2line(i3.center, n2);
    if (!kg.Utils.GE(r3, i3.r)) {
      let o4 = [];
      return o4.push(e32.point2line(t2.start, n2)), o4.push(e32.point2line(t2.end, n2)), e32.sort(o4), o4[0];
    }
    {
      let [n3, o4] = e32.point2circle(s2.end, i3);
      if (o4.end.on(t2))
        return [n3, o4];
    }
  }
  static arc2circle(t2, n2) {
    let o3 = t2.intersect(n2);
    if (o3.length > 0)
      return [0, new kg.Segment(o3[0], o3[0])];
    let i3 = new kg.Circle(t2.center, t2.r), [r3, s2] = e32.circle2circle(i3, n2);
    if (s2.start.on(t2))
      return [r3, s2];
    {
      let o4 = [];
      return o4.push(e32.point2circle(t2.start, n2)), o4.push(e32.point2circle(t2.end, n2)), e32.sort(o4), o4[0];
    }
  }
  static arc2arc(t2, n2) {
    let o3 = t2.intersect(n2);
    if (o3.length > 0)
      return [0, new kg.Segment(o3[0], o3[0])];
    let i3 = new kg.Circle(t2.center, t2.r), r3 = new kg.Circle(n2.center, n2.r), [s2, a3] = e32.circle2circle(i3, r3);
    if (a3.start.on(t2) && a3.end.on(n2))
      return [s2, a3];
    {
      let o4, i4, r4 = [];
      return [o4, i4] = e32.point2arc(t2.start, n2), i4.end.on(n2) && r4.push([o4, i4]), [o4, i4] = e32.point2arc(t2.end, n2), i4.end.on(n2) && r4.push([o4, i4]), [o4, i4] = e32.point2arc(n2.start, t2), i4.end.on(t2) && r4.push([o4, i4.reverse()]), [o4, i4] = e32.point2arc(n2.end, t2), i4.end.on(t2) && r4.push([o4, i4.reverse()]), [o4, i4] = e32.point2point(t2.start, n2.start), r4.push([o4, i4]), [o4, i4] = e32.point2point(t2.start, n2.end), r4.push([o4, i4]), [o4, i4] = e32.point2point(t2.end, n2.start), r4.push([o4, i4]), [o4, i4] = e32.point2point(t2.end, n2.end), r4.push([o4, i4]), e32.sort(r4), r4[0];
    }
  }
  static point2polygon(t2, n2) {
    let o3 = [Number.POSITIVE_INFINITY, new kg.Segment];
    for (let i3 of n2.edges) {
      let [n3, r3] = e32.point2edge(t2, i3);
      kg.Utils.LT(n3, o3[0]) && (o3 = [n3, r3]);
    }
    return o3;
  }
  static shape2polygon(e33, t2) {
    let n2 = [Number.POSITIVE_INFINITY, new kg.Segment];
    for (let o3 of t2.edges) {
      let [t3, i3] = e33.distanceTo(o3.shape);
      kg.Utils.LT(t3, n2[0]) && (n2 = [t3, i3]);
    }
    return n2;
  }
  static polygon2polygon(e33, t2) {
    let n2 = [Number.POSITIVE_INFINITY, new kg.Segment];
    for (let o3 of e33.edges)
      for (let e34 of t2.edges) {
        let [t3, i3] = o3.shape.distanceTo(e34.shape);
        kg.Utils.LT(t3, n2[0]) && (n2 = [t3, i3]);
      }
    return n2;
  }
  static box2box_minmax(e33, t2) {
    let n2 = Math.max(Math.max(e33.xmin - t2.xmax, 0), Math.max(t2.xmin - e33.xmax, 0)), o3 = Math.max(Math.max(e33.ymin - t2.ymax, 0), Math.max(t2.ymin - e33.ymax, 0)), i3 = n2 * n2 + o3 * o3, r3 = e33.merge(t2), s2 = r3.xmax - r3.xmin, a3 = r3.ymax - r3.ymin;
    return [i3, s2 * s2 + a3 * a3];
  }
  static minmax_tree_process_level(t2, n2, o3, i3) {
    let r3, s2;
    for (let a4 of n2) {
      [r3, s2] = e32.box2box_minmax(t2.box, a4.item.key);
      for (let e33 of a4.item.values)
        e33 instanceof kg.Edge ? i3.insert([r3, s2], e33.shape) : i3.insert([r3, s2], e33);
      kg.Utils.LT(s2, o3) && (o3 = s2);
    }
    if (n2.length === 0)
      return o3;
    let a3 = [...n2.map((e33) => e33.left.isNil() ? undefined : e33.left).filter((e33) => e33 !== undefined), ...n2.map((e33) => e33.right.isNil() ? undefined : e33.right).filter((e33) => e33 !== undefined)].filter((n3) => {
      let [i4, r4] = e32.box2box_minmax(t2.box, n3.max);
      return kg.Utils.LE(i4, o3);
    });
    return o3 = e32.minmax_tree_process_level(t2, a3, o3, i3);
  }
  static minmax_tree(t2, n2, o3) {
    let i3 = new x_, r3 = [n2.index.root], s2 = o3 < Number.POSITIVE_INFINITY ? o3 * o3 : Number.POSITIVE_INFINITY;
    return s2 = e32.minmax_tree_process_level(t2, r3, s2, i3), i3;
  }
  static minmax_tree_calc_distance(t2, n2, o3) {
    let i3, r3;
    if (n2 != null && !n2.isNil()) {
      if ([i3, r3] = e32.minmax_tree_calc_distance(t2, n2.left, o3), r3)
        return [i3, r3];
      if (kg.Utils.LT(i3[0], Math.sqrt(n2.item.key.low)))
        return [i3, true];
      let [s2, a3] = e32.distanceToArray(t2, n2.item.values);
      return kg.Utils.LT(s2, i3[0]) && (i3 = [s2, a3]), [i3, r3] = e32.minmax_tree_calc_distance(t2, n2.right, i3), [i3, r3];
    }
    return [o3, false];
  }
  static shape2planarSet(t2, n2, o3 = Number.POSITIVE_INFINITY) {
    let i3 = [o3, new kg.Segment], r3 = false;
    if (n2 instanceof kg.PlanarSet) {
      let s2 = e32.minmax_tree(t2, n2, o3);
      [i3, r3] = e32.minmax_tree_calc_distance(t2, s2.root, i3);
    }
    return i3;
  }
  static sort(e33) {
    e33.sort((e34, t2) => kg.Utils.LT(e34[0], t2[0]) ? -1 : kg.Utils.GT(e34[0], t2[0]) ? 1 : 0);
  }
  static distance(e33, t2) {
    return e33.distanceTo(t2);
  }
  static distanceToArray(e33, t2) {
    let n2 = [Number.POSITIVE_INFINITY, new kg.Segment];
    for (let o3 of t2) {
      let [t3, i3] = e33.distanceTo(o3);
      kg.Utils.LT(t3, n2[0]) && (n2 = [t3, i3]);
    }
    return n2;
  }
  static shape2multiline(t2, n2) {
    let o3 = [Number.POSITIVE_INFINITY, new kg.Segment];
    for (let i3 of n2) {
      let [n3, r3] = e32.distance(t2, i3.shape);
      kg.Utils.LT(n3, o3[0]) && (o3 = [n3, r3]);
    }
    return o3;
  }
  static multiline2multiline(t2, n2) {
    let o3 = [Number.POSITIVE_INFINITY, new kg.Segment];
    for (let i3 of t2)
      for (let t3 of n2) {
        let [n3, r3] = e32.distance(i3.shape, t3.shape);
        kg.Utils.LT(n3, o3[0]) && (o3 = [n3, r3]);
      }
    return o3;
  }
};
var { Multiline: $_, Point: Y_, Segment: X_, Polygon: H_ } = kg;
function V_(e33) {
  const t2 = [];
  let n2 = 0, o3 = 0;
  for (let i3 = 0;i3 < e33.length; i3++) {
    if (e33[i3] === "(" && n2++, e33[i3] === ")" && n2--, n2 < 0)
      throw kg.Errors.ILLEGAL_PARAMETERS;
    e33[i3] === "," && n2 === 0 && (t2.push(e33.slice(o3, i3).trim()), o3 = i3 + 1);
  }
  if (n2 !== 0)
    throw kg.Errors.ILLEGAL_PARAMETERS;
  return t2.push(e33.slice(o3).trim()), t2;
}
function W_(e33) {
  if ((e33 = e33.trim()) === "EMPTY")
    throw new Error("Empty geometry not supported");
  if (!e33.startsWith("(") || !e33.endsWith(")"))
    throw kg.Errors.ILLEGAL_PARAMETERS;
  return e33.slice(1, -1).trim();
}
function G_(e33) {
  if ((e33 = e33.trim()) === "EMPTY")
    throw new Error("Empty geometry not supported");
  return new Y_(e33.split(/\s+/).map(Number));
}
function U_(e33) {
  const t2 = V_(e33).map(G_);
  let n2 = [];
  for (let e34 = 0;e34 < t2.length - 1; e34++)
    n2.push(new X_(t2[e34], t2[e34 + 1]));
  return new $_(n2);
}
function Z_(e33) {
  const t2 = new H_;
  if (e33.trim() === "EMPTY")
    return t2;
  let n2;
  return V_(W_(e33)).forEach((e34, o3) => {
    const i3 = V_(W_(e34)).map(G_), r3 = t2.addFace(i3);
    o3 === 0 ? n2 = r3.orientation() : r3.orientation() === n2 && r3.reverse();
  }), t2;
}
function q_(e33) {
  return e33.split(`
`).map((e34) => e34.match(/\(([^)]+)\)/)[1]).map(G_);
}
function J_(e33) {
  return e33.split(`
`).map((e34) => e34.match(/\(([^)]+)\)/)[1]).map(U_).reduce((e34, t2) => [...e34, ...t2], []);
}
function Q_(e33) {
  return e33.split(`
`)?.every((e34) => e34.includes("POINT"));
}
function K_(e33) {
  return e33.split(`
`)?.every((e34) => e34.includes("LINESTRING"));
}
kg.isWktString = function(e34) {
  return e34.startsWith("POINT") || Q_(e34) || e34.startsWith("LINESTRING") || K_(e34) || e34.startsWith("MULTILINESTRING") || e34.startsWith("POLYGON") || e34.startsWith("MULTIPOINT") || e34.startsWith("MULTIPOLYGON") || e34.startsWith("GEOMETRYCOLLECTION");
}, kg.parseWKT = function e33(t2) {
  const n2 = t2.trim().split(`
`);
  if (n2.length > 1) {
    if (n2.every((e34) => /^\s*POINT\s*\([^()]*\)\s*$/.test(e34)))
      return q_(t2.trim());
    if (n2.every((e34) => /^\s*LINESTRING\s*\([^()]*\)\s*$/.test(e34)))
      return J_(t2.trim());
  }
  const o3 = t2.trim().match(/^(POINT|MULTIPOINT|LINESTRING|MULTILINESTRING|POLYGON|MULTIPOLYGON|GEOMETRYCOLLECTION)\s*(EMPTY|\([\s\S]*\))$/);
  if (o3) {
    const [, t3, n3] = o3;
    if (n3 === "EMPTY") {
      if (t3 === "POLYGON")
        return new H_;
      throw new Error("Empty geometry not supported");
    }
    const i3 = W_(n3);
    switch (t3) {
      case "POINT":
        return G_(i3);
      case "MULTIPOINT":
        return V_(i3).map((e34) => G_(e34.startsWith("(") ? W_(e34) : e34));
      case "LINESTRING":
        return U_(i3);
      case "MULTILINESTRING":
        return V_(i3).map((e34) => U_(W_(e34)));
      case "POLYGON":
        return Z_(n3);
      case "MULTIPOLYGON":
        return function(e34) {
          const t4 = new H_;
          return V_(e34).map(Z_).forEach((e35) => {
            e35.faces.forEach((e36) => t4.addFace([...e36.shapes]));
          }), t4;
        }(i3);
      case "GEOMETRYCOLLECTION":
        return V_(i3).map(e33).reduce((e34, t4) => e34.concat(t4), []);
    }
  } else {
    if (Q_(t2))
      return q_(t2);
    if (K_(t2))
      return J_(t2);
  }
  return [];
}, kg.BooleanOperations = e_, kg.Relations = g_;
var ey = [0, 1, -1, 2, -2, 3, -3, 4];
var ty = (ey.flatMap((e34) => ey.map((t2) => [e34, t2])).sort(([e34, t2], [n2, o3]) => Math.abs(e34) + Math.abs(t2) - Math.abs(n2) - Math.abs(o3)).length, [0.2, 0.4, 0.8, 1.2].flatMap((e34) => [0.2, 0.3, 0.45, 0.6].flatMap((t2) => [-1, 1].map((n2) => ({ halfSpan: e34, offset: t2, directionSign: n2 })))).flatMap((e34) => [0, 1].map((t2) => ({ kind: "segment", routeSide: t2, ...e34 }))));
[1, -1].flatMap((e34) => [1, -1].flatMap((t2) => [false, true].flatMap((n2) => [0, 1].map((o3) => ({ routeSide: o3, normalDirectionSign: e34, tangentDirectionSign: t2, reverseEndpointOffsets: n2 }))))), [0, 1].map((e34) => ({ kind: "displacementChain", routeSide: e34 })), [-1, 1].flatMap((e34) => [0, 1].map((t2) => ({ kind: "segment", routeSide: t2, halfSpan: 0.4, offset: 1.2, directionSign: e34 }))), [-1, 1].flatMap((e34) => [0, 1].map((t2) => ({ kind: "span", routeSide: t2, spanExpansion: 3, offset: 1.8, directionSign: e34 }))), [{ dx: -2.4, dy: -0.4 }, { dx: -2.4, dy: 0.4 }, { dx: 2.4, dy: -0.4 }, { dx: 2.4, dy: 0.4 }, { dx: -0.4, dy: -2.4 }, { dx: -0.4, dy: 2.4 }, { dx: 0.4, dy: -2.4 }, { dx: 0.4, dy: 2.4 }].flatMap((e34) => [0, 1].map((t2) => ({ kind: "waypoint", routeSide: t2, spanExpansion: 2, ...e34 }))), [{ dx: -0.17, dy: 0 }, { dx: 0.17, dy: 0 }, { dx: 0, dy: -0.17 }, { dx: 0, dy: 0.17 }].flatMap((e34) => [0, 1].map((t2) => ({ kind: "waypoint", routeSide: t2, spanExpansion: 0, ...e34 })));
function ny(e34) {
  if (e34.isNonPlatedHole && e34.shape === "circle")
    return { type: "oval", a: { x: 0, y: 0 }, b: { x: 0, y: 0 }, radius: e34.width / 2 };
  if (e34.type === "rect")
    return { type: "rect", bounds: { minX: -e34.width / 2, maxX: e34.width / 2, minY: -e34.height / 2, maxY: e34.height / 2 } };
  if (e34.type !== "oval")
    throw new Error("repair04 found an unsupported obstacle shape");
  const t2 = Math.abs(e34.width - e34.height) / 2, n2 = e34.width >= e34.height ? t2 : 0, o3 = e34.height > e34.width ? t2 : 0;
  return { type: "oval", a: { x: -n2, y: -o3 }, b: { x: n2, y: o3 }, radius: Math.min(e34.width, e34.height) / 2 };
}
function oy(e34, t2, n2) {
  return n2.type === "rect" ? Ne(e34, t2, n2.bounds) : Math.max(0, we(e34, t2, n2.a, n2.b) - n2.radius);
}
var iy = (e34, t2) => {
  const n2 = new Map, o3 = (e35) => {
    const t3 = n2.get(e35);
    if (t3 === undefined)
      return n2.set(e35, e35), e35;
    if (t3 === e35)
      return e35;
    const i4 = o3(t3);
    return n2.set(e35, i4), i4;
  }, i3 = (e35) => {
    const t3 = e35.filter((e36) => typeof e36 == "string" && e36.length > 0);
    if (t3.length === 0)
      return;
    const i4 = o3(t3[0]);
    for (const e36 of t3)
      n2.set(o3(e36), i4);
  };
  for (const t3 of e34.connections) {
    const e35 = t3;
    i3([e35.name, e35.rootConnectionName, e35.netConnectionName, e35.__netConnectionName, ...e35.mergedConnectionNames ?? [], ...e35.__rootConnectionNames ?? [], ...e35.pointsToConnect.flatMap((e36) => [e36.pointId, e36.pcb_port_id])]);
  }
  for (const t3 of e34.obstacles)
    i3(t3.connectedTo);
  for (const e35 of t2)
    i3([e35.connectionName, e35.rootConnectionName]);
  for (const e35 of n2.keys())
    n2.set(e35, o3(e35));
  return n2;
};
var ry = (e34, t2) => {
  const n2 = e34.__zLayers;
  if (n2)
    return new Set(n2);
  if (e34.zLayers)
    return new Set(e34.zLayers);
  const o3 = new Set;
  for (const n3 of e34.layers) {
    const e35 = n3 === "top" ? 0 : n3 === "bottom" ? t2 - 1 : /^inner\d+$/.test(n3) ? Number(n3.slice(5)) : -1;
    if (e35 < 0 || e35 >= t2)
      throw new Error(`repair04 obstacle has an unknown layer: ${n3}`);
    o3.add(e35);
  }
  return o3;
};
var sy = ({ srj: e34, routes: t2, traceClearance: n2 = 0.1, viaClearance: o3 = 0.1 }) => {
  let i3;
  const r3 = new Map, s2 = [];
  let a3 = false;
  return (c3) => {
    const l3 = i3 ??= iy(e34, t2), h2 = new Map, d2 = a3 ? s2 : function* (t3) {
      for (let i4 = 0;i4 < e34.obstacles.length; i4++) {
        if (r3.has(i4)) {
          const e35 = r3.get(i4);
          e35 && (yield e35);
          continue;
        }
        const a4 = e34.obstacles[i4], c4 = a4.connectedTo.some((e35) => /^(pcb_smtpad_|pcb_plated_hole_|pcb_port_)/.test(e35)), l4 = Math.abs((a4.ccwRotationDegrees ?? 0) % 180) > 0.00000001, h3 = a4.type === "rect" && a4.layers.length > 1 && Math.abs(a4.width - a4.height) < 0.001;
        if (c4 && !l4 && !h3) {
          r3.set(i4, null);
          continue;
        }
        if (![a4.center.x, a4.center.y, a4.width, a4.height, a4.ccwRotationDegrees ?? 0].every(Number.isFinite) || a4.width < 0 || a4.height < 0)
          throw new Error("repair04 fixed obstacle geometry must be finite and nonnegative");
        const d3 = ry(a4, e34.layerCount), u2 = new Set(a4.connectedTo.map((e35) => t3.get(e35) ?? e35)), p3 = ny(a4), m2 = (a4.ccwRotationDegrees ?? 0) * Math.PI / 180, g2 = Math.cos(m2), f2 = Math.sin(m2), _2 = Math.hypot(a4.width, a4.height) / 2, y2 = (e35) => {
          const t4 = e35.x - a4.center.x, n3 = e35.y - a4.center.y;
          return { x: t4 * g2 + n3 * f2, y: -t4 * f2 + n3 * g2 };
        }, b2 = (e35, t4, n3) => Math.max(e35.x, t4.x) + n3 < a4.center.x - _2 || Math.min(e35.x, t4.x) - n3 > a4.center.x + _2 || Math.max(e35.y, t4.y) + n3 < a4.center.y - _2 || Math.min(e35.y, t4.y) - n3 > a4.center.y + _2, x2 = a4.obstacleId?.startsWith("repair04_board_edge_") === true, v2 = x2 ? 0 : a4.isNonPlatedHole && e34.minTraceToHoleEdgeClearance !== undefined ? e34.minTraceToHoleEdgeClearance : Math.max(n2, e34.defaultObstacleMargin ?? 0, e34.minTraceToPadEdgeClearance ?? 0), I2 = x2 ? 0 : Math.max(o3, e34.defaultObstacleMargin ?? 0, e34.minViaEdgeToPadEdgeClearance ?? 0), S2 = { obstacleIndex: i4, obstacle: a4, zLayers: d3, obstacleNets: u2, shape: p3, toLocal: y2, separated: b2, wireGap: v2, viaGap: I2 };
        r3.set(i4, S2), s2.push(S2), yield S2;
      }
      a3 = true;
    }(l3);
    for (const { obstacleIndex: t3, obstacle: n3, zLayers: o4, obstacleNets: i4, shape: r4, toLocal: s3, separated: a4, wireGap: u2, viaGap: p3 } of d2)
      for (let d3 = 0;d3 < c3.length; d3 += 1) {
        const m2 = c3[d3];
        if (!(m2.route.length < 2) && ![m2.connectionName, m2.rootConnectionName].some((e35) => e35 !== undefined && i4.has(l3.get(e35) ?? e35)))
          for (let i5 = 1;i5 < m2.route.length; i5 += 1) {
            const c4 = m2.route[i5 - 1], l4 = m2.route[i5];
            if (c4.toNextSegmentType === "through_obstacle")
              continue;
            if (c4.z !== l4.z) {
              const n4 = Na(e34, c4, l4);
              if (!Array.from(o4).some((e35) => e35 >= n4.minZ && e35 <= n4.maxZ))
                continue;
              if (Math.abs(c4.x - l4.x) > 0.00000001 || Math.abs(c4.y - l4.y) > 0.00000001)
                throw new Error("repair04 found a non-colocated via transition");
              if (a4(c4, c4, m2.viaDiameter / 2 + p3 + 0.00000001))
                continue;
              const i6 = s3(c4), u3 = oy(i6, i6, r4), g3 = m2.viaDiameter / 2 + p3 - u3;
              if (g3 <= 0.00000001)
                continue;
              const f3 = `fixed-obstacle:${d3}:${t3}:via`;
              (h2.get(f3)?.severity ?? -1 / 0) < g3 && h2.set(f3, { key: f3, center: { x: c4.x, y: c4.y }, routeIndex: d3, obstacleIndex: t3, kind: "via", severity: g3 });
              continue;
            }
            if (!o4.has(c4.z))
              continue;
            const g2 = Math.max(c4.traceThickness ?? m2.traceThickness, l4.traceThickness ?? m2.traceThickness) / 2;
            if (a4(c4, l4, g2 + u2 + 0.00000001))
              continue;
            const f2 = g2 + u2 - oy(s3(c4), s3(l4), r4);
            if (f2 <= 0.00000001)
              continue;
            const _2 = `fixed-obstacle:${d3}:${t3}:wire`;
            (h2.get(_2)?.severity ?? -1 / 0) < f2 && h2.set(_2, { key: _2, center: Ee(n3.center, c4, l4), routeIndex: d3, obstacleIndex: t3, kind: "wire", severity: f2 });
          }
      }
    return Array.from(h2.values());
  };
};
var ay = (e34) => sy(e34)(e34.routes);
var cy = (e34, t2) => {
  const n2 = [];
  for (let o3 = 1;o3 < e34.route.length; o3++) {
    const i3 = e34.route[o3 - 1], r3 = e34.route[o3];
    if (i3.z === r3.z || i3.toNextSegmentType === "through_obstacle")
      continue;
    if (i3.x !== r3.x || i3.y !== r3.y || ![i3.x, i3.y, i3.z, r3.z, e34.viaDiameter].every(Number.isFinite) || !Number.isInteger(i3.z) || !Number.isInteger(r3.z) || Math.min(i3.z, r3.z) < 0 || Math.max(i3.z, r3.z) >= t2 || e34.viaDiameter <= 0)
      throw new Error("repair04 new-via guard requires valid colocated vias");
    const s2 = o3 - 1, a3 = [i3.z, r3.z];
    let c3 = Math.min(i3.z, r3.z), l3 = Math.max(i3.z, r3.z);
    for (;o3 + 1 < e34.route.length && e34.route[o3].toNextSegmentType !== "through_obstacle"; ) {
      const n3 = e34.route[o3 + 1];
      if (n3.x !== r3.x || n3.y !== r3.y)
        break;
      if (!Number.isInteger(n3.z) || n3.z < 0 || n3.z >= t2)
        throw new Error("repair04 new-via guard found an invalid layer span");
      n3.z !== a3.at(-1) && a3.push(n3.z), c3 = Math.min(c3, n3.z), l3 = Math.max(l3, n3.z), o3++;
    }
    n2.push({ pointIndices: Array.from({ length: o3 - s2 + 1 }, (e35, t3) => s2 + t3), layerSequence: a3, x: r3.x, y: r3.y, minZ: c3, maxZ: l3, diameter: e34.viaDiameter, identity: JSON.stringify([r3.x, r3.y, c3, l3, e34.viaDiameter]) });
  }
  return n2;
};
var ly = (e34) => (({ srj: e35, viaClearance: t2 = 0.1 }) => {
  const n2 = new Map, o3 = new Map, i3 = [t2, e35.defaultObstacleMargin ?? 0, e35.minViaEdgeToPadEdgeClearance ?? 0], r3 = Math.max(...i3), s2 = Ea(e35, t2, true);
  let a3, c3 = [];
  const l3 = (t3) => {
    const i4 = o3.get(t3.identity);
    if (i4)
      return i4;
    const s3 = [], a4 = Na(e35, { z: t3.minZ }, { z: t3.maxZ });
    for (let o4 = 0;o4 < e35.obstacles.length; o4++) {
      const i5 = e35.obstacles[o4];
      let c4 = n2.get(o4);
      if (!c4) {
        const t4 = i5.__zLayers ?? i5.zLayers ?? i5.layers.map((t5) => t5 === "top" ? 0 : t5 === "bottom" ? e35.layerCount - 1 : /^inner\d+$/.test(t5) ? Number(t5.slice(5)) : -1);
        if (t4.some((t5) => !Number.isInteger(t5) || t5 < 0 || t5 >= e35.layerCount))
          throw new Error("repair04 new-via guard found an unknown obstacle layer");
        c4 = { zs: t4 }, n2.set(o4, c4);
      }
      if (!c4.zs.some((e36) => e36 >= a4.minZ && e36 <= a4.maxZ))
        continue;
      if (!c4.geometry) {
        if (![i5.center.x, i5.center.y, i5.width, i5.height, i5.ccwRotationDegrees ?? 0].every(Number.isFinite) || i5.width < 0 || i5.height < 0)
          throw new Error("repair04 new-via guard found invalid obstacle geometry");
        const e36 = (i5.ccwRotationDegrees ?? 0) * Math.PI / 180;
        c4.geometry = { x: i5.center.x, y: i5.center.y, cosine: Math.cos(e36), sine: Math.sin(e36), extent: Math.hypot(i5.width, i5.height) / 2, shape: ny(i5) };
      }
      const l4 = c4.geometry, h2 = l4.extent + t3.diameter / 2 + r3 + 0.00000001;
      if (Math.abs(t3.x - l4.x) > h2 || Math.abs(t3.y - l4.y) > h2)
        continue;
      const d2 = t3.x - l4.x, u2 = t3.y - l4.y, p3 = { x: d2 * l4.cosine + u2 * l4.sine, y: -d2 * l4.sine + u2 * l4.cosine }, m2 = oy(p3, p3, l4.shape), g2 = t3.diameter / 2 + r3 - m2;
      g2 <= 0.00000001 || s3.push({ obstacleIndex: o4, severity: g2 });
    }
    return o3.set(t3.identity, s3), s3;
  };
  return ({ previousRoutes: t3, routes: n3, includeExistingVias: o4 = [] }) => {
    if (t3.length !== n3.length)
      throw new Error("repair04 new-via guard requires matching route ordering");
    if (i3.some((e36) => !Number.isFinite(e36) || e36 < 0))
      throw new Error("repair04 new-via guard requires nonnegative finite margins");
    const h2 = [];
    a3 && c3.length === n3.length && !c3.some((e36, t4) => e36.connectionName !== n3[t4].connectionName || e36.rootConnectionName !== n3[t4].rootConnectionName) || (a3 = iy(e35, n3), c3 = n3.map((e36) => ({ connectionName: e36.connectionName, rootConnectionName: e36.rootConnectionName })));
    for (let i4 = 0;i4 < n3.length; i4++) {
      const c4 = n3[i4], d2 = t3[i4], u2 = a3.get(c4.connectionName) ?? c4.connectionName, p3 = (t4) => l3(t4).flatMap((t5) => {
        const n4 = e35.obstacles[t5.obstacleIndex].connectedTo.some((e36) => (a3.get(e36) ?? e36) === u2), o5 = t5.severity - (n4 ? r3 - s2 : 0);
        return o5 > 0.00000001 ? [{ obstacleIndex: t5.obstacleIndex, severity: o5 }] : [];
      }), m2 = cy(d2, e35.layerCount), g2 = c4.connectionName === d2.connectionName && c4.rootConnectionName === d2.rootConnectionName, f2 = new Set(g2 ? m2.map((e36) => e36.identity) : []), _2 = cy(c4, e35.layerCount), y2 = g2 && c4.route.length === d2.route.length && c4.route.every((e36, t4) => {
        const n4 = d2.route[t4];
        return (!(t4 === 0 || t4 === c4.route.length - 1 || e36.pcb_port_id || e36.insideJumperPad || e36.toNextSegmentType) || e36.x === n4.x && e36.y === n4.y) && e36.z === n4.z && e36.pcb_port_id === n4.pcb_port_id && e36.toNextSegmentType === n4.toNextSegmentType && e36.insideJumperPad === n4.insideJumperPad;
      }) && _2.length === m2.length && new Set(_2.map((e36) => e36.identity)).size === _2.length && _2.every((e36, t4) => {
        const n4 = m2[t4];
        return e36.diameter === n4.diameter && e36.pointIndices.length === n4.pointIndices.length && e36.pointIndices.every((e37, t5) => e37 === n4.pointIndices[t5]) && e36.layerSequence.length === n4.layerSequence.length && e36.layerSequence.every((e37, t5) => e37 === n4.layerSequence[t5]) && !m2.some((n5, o5) => o5 !== t4 && n5.identity === e36.identity);
      });
      for (let e36 = 0;e36 < _2.length; e36++) {
        const t4 = _2[e36];
        if (f2.has(t4.identity) && !o4.some((t5) => t5.routeIndex === i4 && t5.viaIndex === e36))
          continue;
        const n4 = y2 && !o4.some((t5) => t5.routeIndex === i4 && t5.viaIndex === e36) ? new Map(p3(m2[e36]).map((e37) => [e37.obstacleIndex, e37.severity])) : undefined;
        for (const o5 of p3(t4)) {
          const r4 = n4?.get(o5.obstacleIndex);
          r4 !== undefined && o5.severity <= r4 + 0.00000001 || h2.push({ key: `new-via-pad:${i4}:${o5.obstacleIndex}:${e36}`, routeIndex: i4, obstacleIndex: o5.obstacleIndex, center: { x: t4.x, y: t4.y }, kind: "via", severity: o5.severity });
        }
      }
    }
    return h2;
  };
})(e34)(e34);
var hy = (e34, t2, n2) => {
  if (n2 <= Aa)
    return structuredClone(e34);
  if (n2 >= 0.99999999)
    return structuredClone(t2);
  const o3 = { ...structuredClone(e34), x: e34.x + (t2.x - e34.x) * n2, y: e34.y + (t2.y - e34.y) * n2 };
  return delete o3.start_pcb_port_id, delete o3.end_pcb_port_id, o3;
};
var dy = [Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array];
var uy = class e34 {
  static from(t2, n2 = 0) {
    if (n2 % 8 != 0)
      throw new Error("byteOffset must be 8-byte aligned.");
    if (!t2 || t2.byteLength === undefined || "buffer" in t2)
      throw new Error("Data must be an instance of ArrayBuffer or SharedArrayBuffer.");
    const [o3, i3] = new Uint8Array(t2, n2 + 0, 2);
    if (o3 !== 251)
      throw new Error("Data does not appear to be in a Flatbush format.");
    const r3 = i3 >> 4;
    if (r3 !== 3)
      throw new Error(`Got v${r3} data when expected v3.`);
    const s2 = dy[15 & i3];
    if (!s2)
      throw new Error("Unrecognized array type.");
    const [a3] = new Uint16Array(t2, n2 + 2, 1), [c3] = new Uint32Array(t2, n2 + 4, 1);
    return new e34(c3, a3, s2, undefined, t2, n2);
  }
  constructor(e35, t2 = 16, n2 = Float64Array, o3 = ArrayBuffer, i3, r3 = 0) {
    if (e35 === undefined)
      throw new Error("Missing required argument: numItems.");
    if (isNaN(e35) || e35 <= 0)
      throw new Error(`Unexpected numItems value: ${e35}.`);
    this.numItems = +e35, this.nodeSize = Math.min(Math.max(+t2, 2), 65535), this.byteOffset = r3;
    let s2 = e35, a3 = s2;
    this._levelBounds = [4 * s2];
    do {
      s2 = Math.ceil(s2 / this.nodeSize), a3 += s2, this._levelBounds.push(4 * a3);
    } while (s2 !== 1);
    this.ArrayType = n2, this.IndexArrayType = a3 < 16384 ? Uint16Array : Uint32Array;
    const c3 = dy.indexOf(n2), l3 = 4 * a3 * n2.BYTES_PER_ELEMENT;
    if (c3 < 0)
      throw new Error(`Unexpected typed array class: ${n2}.`);
    const h2 = n2, d2 = this.IndexArrayType;
    if (i3)
      this.data = i3, this._boxes = new h2(i3, r3 + 8, 4 * a3), this._indices = new d2(i3, r3 + 8 + l3, a3), this._pos = 4 * a3, 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 {
      const n3 = this.data = new o3(8 + l3 + a3 * this.IndexArrayType.BYTES_PER_ELEMENT);
      this._boxes = new h2(n3, 8, 4 * a3), this._indices = new d2(n3, 8 + l3, a3), this._pos = 0, this.minX = 1 / 0, this.minY = 1 / 0, this.maxX = -1 / 0, this.maxY = -1 / 0, new Uint8Array(n3, 0, 2).set([251, 48 + c3]), new Uint16Array(n3, 2, 1)[0] = t2, new Uint32Array(n3, 4, 1)[0] = e35;
    }
    this._queue = new R;
  }
  add(e35, t2, n2 = e35, o3 = t2) {
    const i3 = this._pos, r3 = i3 >> 2, s2 = this._boxes;
    return this._indices[r3] = r3, s2[i3] = e35, s2[i3 + 1] = t2, s2[i3 + 2] = n2, s2[i3 + 3] = o3, this._pos = i3 + 4, e35 < this.minX && (this.minX = e35), t2 < this.minY && (this.minY = t2), n2 > this.maxX && (this.maxX = n2), o3 > this.maxY && (this.maxY = o3), r3;
  }
  finish() {
    if (this._pos >> 2 !== this.numItems)
      throw new Error(`Added ${this._pos >> 2} items when expected ${this.numItems}.`);
    const e35 = this._boxes;
    if (this.numItems <= this.nodeSize)
      return e35[this._pos++] = this.minX, e35[this._pos++] = this.minY, e35[this._pos++] = this.maxX, void (e35[this._pos++] = this.maxY);
    const { numItems: t2, minX: n2, minY: o3, nodeSize: i3, _indices: r3, _levelBounds: s2 } = this, a3 = this.maxX - n2 || 1, c3 = this.maxY - o3 || 1, l3 = new Int32Array(t2), h2 = 65535 / a3, d2 = 65535 / c3;
    for (let i4 = 0, r4 = 0;i4 < t2; i4++) {
      const t3 = e35[r4++], s3 = e35[r4++], a4 = h2 * ((t3 + e35[r4++]) / 2 - n2) | 0, c4 = d2 * ((s3 + e35[r4++]) / 2 - o3) | 0;
      l3[i4] = gy(a4, c4);
    }
    (function(e36, t3, n3, o4, i4, r4) {
      const s3 = [o4, i4];
      for (;s3.length; ) {
        const o5 = s3.pop() || 0, i5 = s3.pop() || 0;
        if (o5 - i5 <= r4 && Math.floor(i5 / r4) >= Math.floor(o5 / r4))
          continue;
        const a4 = e36[i5], c4 = e36[i5 + o5 >> 1], l4 = e36[o5], h3 = a4 > c4 != a4 > l4 ? a4 : c4 < a4 != c4 < l4 ? c4 : l4;
        let d3 = i5 - 1, u3 = o5 + 1;
        for (;; ) {
          do {
            d3++;
          } while (e36[d3] < h3);
          do {
            u3--;
          } while (e36[u3] > h3);
          if (d3 >= u3)
            break;
          my(e36, t3, n3, d3, u3);
        }
        s3.push(i5, u3, u3 + 1, o5);
      }
    })(l3, e35, r3, 0, t2 - 1, i3);
    let u2 = 4 * t2;
    for (let t3 = 0, n3 = 0;t3 < s2.length - 1; t3++) {
      const o4 = s2[t3];
      for (;n3 < o4; ) {
        const t4 = n3;
        let s3 = e35[n3++], a4 = e35[n3++], c4 = e35[n3++], l4 = e35[n3++];
        for (let t5 = 1;t5 < i3 && n3 < o4; t5++)
          s3 = Math.min(s3, e35[n3++]), a4 = Math.min(a4, e35[n3++]), c4 = Math.max(c4, e35[n3++]), l4 = Math.max(l4, e35[n3++]);
        r3[u2 >> 2] = t4, e35[u2++] = s3, e35[u2++] = a4, e35[u2++] = c4, e35[u2++] = l4;
      }
    }
    this._pos = u2;
  }
  search(e35, t2, n2, o3, i3) {
    if (this._pos !== this._boxes.length)
      throw new Error("Data not yet indexed - call index.finish().");
    const { _boxes: r3, _levelBounds: s2, _indices: a3, nodeSize: c3 } = this, l3 = 4 * this.numItems;
    let h2 = r3.length - 4, d2 = s2.length - 1;
    const u2 = [], p3 = [];
    let m2 = false;
    for (;h2 !== undefined; ) {
      const g2 = Math.min(h2 + 4 * c3, s2[d2]), f2 = h2 >= l3;
      if (m2)
        this._collectContained(h2, g2, d2, l3, p3, i3);
      else
        for (let s3 = h2;s3 < g2; s3 += 4) {
          const c4 = r3[s3];
          if (n2 < c4)
            continue;
          const l4 = r3[s3 + 1];
          if (o3 < l4)
            continue;
          const h3 = r3[s3 + 2];
          if (e35 > h3)
            continue;
          const m3 = r3[s3 + 3];
          if (t2 > m3)
            continue;
          const g3 = 0 | a3[s3 >> 2];
          if (f2) {
            const i4 = +(e35 <= c4 && t2 <= l4 && n2 >= h3 && o3 >= m3);
            u2.push(g3 | i4, d2 - 1);
          } else
            (i3 === undefined || i3(g3, c4, l4, h3, m3)) && p3.push(g3);
        }
      d2 = u2.pop(), h2 = u2.pop(), h2 !== undefined && (m2 = !(1 & ~h2), h2 &= -2);
    }
    return p3;
  }
  _collectContained(e35, t2, n2, o3, i3, r3) {
    const s2 = this._boxes, a3 = this._indices;
    let c3 = e35;
    for (let e36 = n2;e36 > 0; e36--)
      c3 = a3[c3 >> 2];
    const l3 = Math.min(c3 + (t2 - e35) * this.nodeSize ** n2, o3);
    if (r3 === undefined)
      for (;c3 < l3; c3 += 4)
        i3.push(0 | a3[c3 >> 2]);
    else
      for (;c3 < l3; c3 += 4) {
        const e36 = 0 | a3[c3 >> 2];
        r3(e36, s2[c3], s2[c3 + 1], s2[c3 + 2], s2[c3 + 3]) && i3.push(e36);
      }
  }
  neighbors(e35, t2, n2 = 1 / 0, o3 = 1 / 0, i3) {
    if (this._pos !== this._boxes.length)
      throw new Error("Data not yet indexed - call index.finish().");
    const { _boxes: r3, _levelBounds: s2, _indices: a3, _queue: c3, nodeSize: l3 } = this, h2 = 4 * this.numItems, d2 = 4 * l3, u2 = [], p3 = n2 === 1;
    let m2 = o3 * o3;
    for (c3.push(r3.length - 4 << 1, 0);c3.length; ) {
      const o4 = c3.ids[0];
      if (1 & o4) {
        if (c3.pop(), u2.push(o4 >> 1), u2.length === n2)
          break;
        continue;
      }
      c3.pop();
      const l4 = o4 >> 1, g2 = l4 < h2, f2 = Math.min(l4 + d2, py(l4, s2));
      for (let n3 = l4;n3 < f2; n3 += 4) {
        const o5 = r3[n3], s3 = r3[n3 + 1], l5 = r3[n3 + 2], h3 = r3[n3 + 3], d3 = Math.max(Math.max(o5 - e35, e35 - l5), 0), u3 = Math.max(Math.max(s3 - t2, t2 - h3), 0), f3 = d3 * d3 + u3 * u3;
        if (f3 > m2)
          continue;
        const _2 = 0 | a3[n3 >> 2];
        g2 ? (i3 === undefined || i3(_2)) && (c3.push(_2 << 1 | 1, f3), p3 && f3 < m2 && (m2 = f3)) : c3.push(_2 << 1, f3);
      }
    }
    return c3.clear(), u2;
  }
};
function py(e35, t2) {
  let n2 = 0, o3 = t2.length - 1;
  for (;n2 < o3; ) {
    const i3 = n2 + o3 >> 1;
    t2[i3] > e35 ? o3 = i3 : n2 = i3 + 1;
  }
  return t2[n2];
}
function my(e35, t2, n2, o3, i3) {
  const r3 = e35[o3];
  e35[o3] = e35[i3], e35[i3] = r3;
  const s2 = 4 * o3, a3 = 4 * i3, c3 = t2[s2], l3 = t2[s2 + 1], h2 = t2[s2 + 2], d2 = t2[s2 + 3];
  t2[s2] = t2[a3], t2[s2 + 1] = t2[a3 + 1], t2[s2 + 2] = t2[a3 + 2], t2[s2 + 3] = t2[a3 + 3], t2[a3] = c3, t2[a3 + 1] = l3, t2[a3 + 2] = h2, t2[a3 + 3] = d2;
  const u2 = n2[o3];
  n2[o3] = n2[i3], n2[i3] = u2;
}
function gy(e35, t2) {
  let n2 = e35 ^ t2, o3 = 65535 ^ n2, i3 = 65535 ^ (e35 | t2), r3 = e35 & (65535 ^ t2), s2 = n2 | o3 >> 1, a3 = n2 >> 1 ^ n2, c3 = i3 ^ i3 >> 1 ^ o3 & r3 >> 1, l3 = r3 ^ n2 & i3 >> 1 ^ r3 >> 1;
  return n2 = s2 & s2 >> 2 ^ a3 & a3 >> 2, o3 = s2 & a3 >> 2 ^ a3 & (s2 ^ a3) >> 2, i3 = c3 ^ s2 & c3 >> 2 ^ a3 & l3 >> 2, r3 = l3 ^ a3 & c3 >> 2 ^ (s2 ^ a3) & l3 >> 2, s2 = n2 & n2 >> 4 ^ o3 & o3 >> 4, a3 = n2 & o3 >> 4 ^ o3 & (n2 ^ o3) >> 4, c3 = i3 ^ n2 & i3 >> 4 ^ o3 & r3 >> 4, l3 = r3 ^ o3 & i3 >> 4 ^ (n2 ^ o3) & r3 >> 4, i3 = c3 ^ s2 & c3 >> 8 ^ a3 & l3 >> 8, r3 = l3 ^ a3 & c3 >> 8 ^ (s2 ^ a3) & l3 >> 8, i3 ^= i3 >> 1, r3 ^= r3 >> 1, n2 = e35 ^ t2, o3 = r3 | 65535 ^ (n2 | i3), n2 = 16711935 & (n2 | n2 << 8), n2 = 252645135 & (n2 | n2 << 4), n2 = 858993459 & (n2 | n2 << 2), n2 = 1431655765 & (n2 | n2 << 1), o3 = 16711935 & (o3 | o3 << 8), o3 = 252645135 & (o3 | o3 << 4), o3 = 858993459 & (o3 | o3 << 2), o3 = 1431655765 & (o3 | o3 << 1), ((o3 << 1 | n2) >>> 0) - 2147483648;
}
var fy = (e35, t2) => {
  const n2 = e35.end.x - e35.start.x, o3 = e35.end.y - e35.start.y, i3 = t2.end.x - t2.start.x, r3 = t2.end.y - t2.start.y, s2 = t2.start.x - e35.start.x, a3 = t2.start.y - e35.start.y, c3 = n2 * r3 - o3 * i3, l3 = (e36, t3) => ({ x: e36.start.x + (e36.end.x - e36.start.x) * t3, y: e36.start.y + (e36.end.y - e36.start.y) * t3 }), h2 = (e36, t3) => {
    const n3 = t3.end.x - t3.start.x, o4 = t3.end.y - t3.start.y, i4 = n3 * n3 + o4 * o4, r4 = i4 > 0.00000000000000010000000000000001 ? Math.max(0, Math.min(1, ((e36.x - t3.start.x) * n3 + (e36.y - t3.start.y) * o4) / i4)) : 0;
    return l3(t3, r4);
  };
  if (Math.abs(c3) > Aa) {
    const t3 = (s2 * r3 - a3 * i3) / c3, h3 = (s2 * o3 - a3 * n2) / c3;
    if (t3 >= 0 && t3 <= 1 && h3 >= 0 && h3 <= 1) {
      const n3 = l3(e35, t3);
      return [n3, n3];
    }
  } else {
    const i4 = n2 * n2 + o3 * o3;
    if (i4 > 0.00000000000000010000000000000001) {
      const r4 = (s2 * n2 + a3 * o3) / i4, c4 = ((t2.end.x - e35.start.x) * n2 + (t2.end.y - e35.start.y) * o3) / i4, d3 = Math.max(0, Math.min(r4, c4)), u2 = Math.min(1, Math.max(r4, c4));
      if (d3 <= u2) {
        const n3 = l3(e35, (d3 + u2) / 2);
        return [n3, h2(n3, t2)];
      }
    }
  }
  const d2 = [[e35.start, h2(e35.start, t2)], [e35.end, h2(e35.end, t2)], [h2(t2.start, e35), t2.start], [h2(t2.end, e35), t2.end]];
  return d2.sort((e36, t3) => Math.hypot(e36[0].x - e36[1].x, e36[0].y - e36[1].y) - Math.hypot(t3[0].x - t3[1].x, t3[0].y - t3[1].y)), d2[0];
};
var _y = (e35, t2) => {
  const n2 = e35 === "top" ? 0 : e35 === "bottom" ? t2 - 1 : /^inner\d+$/.test(e35) ? Number(e35.slice(5)) : -1;
  if (!Number.isInteger(n2) || n2 < 0 || n2 >= t2)
    throw new Error(`repair04 preload has an unknown layer: ${e35}`);
  return n2;
};
var yy = (e35, t2, n2) => {
  const o3 = ((e36, t3) => {
    const n3 = new Map, o4 = (e37) => {
      const t4 = n3.get(e37);
      if (t4 === undefined || t4 === e37)
        return e37;
      const i5 = o4(t4);
      return n3.set(e37, i5), i5;
    }, i4 = (e37) => {
      const t4 = e37.filter((e38) => typeof e38 == "string" && e38.length > 0);
      if (t4.length === 0)
        return;
      const i5 = o4(t4[0]);
      for (const e38 of t4)
        n3.set(o4(e38), i5);
    };
    for (const t4 of e36.connections) {
      const e37 = t4;
      i4([e37.name, e37.rootConnectionName, e37.netConnectionName, e37.__netConnectionName, ...e37.mergedConnectionNames ?? [], ...e37.__rootConnectionNames ?? []]);
    }
    for (const e37 of t3)
      i4([e37.connectionName, e37.rootConnectionName]);
    for (const t4 of e36.traces ?? [])
      i4([t4.connection_name, ...t4.connectsTo ?? []]);
    return o4;
  })(e35, t2), i3 = t2.map((e36, t3) => t3), r3 = (e36) => {
    const t3 = i3[e36];
    if (t3 === e36)
      return e36;
    const n3 = r3(t3);
    return i3[e36] = n3, n3;
  }, s2 = new Map, a3 = new Map;
  for (let t3 = 0;t3 < e35.obstacles.length; t3 += 1)
    for (const n3 of e35.obstacles[t3].connectedTo) {
      const e36 = a3.get(n3) ?? [];
      e36.push(t3), a3.set(n3, e36);
    }
  for (let n3 = 0;n3 < t2.length; n3 += 1) {
    const c4 = t2[n3];
    for (const t3 of [c4.route[0], c4.route.at(-1)]) {
      if (!t3)
        continue;
      const l4 = o3(c4.connectionName), h3 = [JSON.stringify([l4, "point", t3.x, t3.y, t3.z])], d3 = t3.pcb_port_id ? a3.get(t3.pcb_port_id) ?? [] : [];
      for (const n4 of d3) {
        const o4 = e35.obstacles[n4];
        if (!(o4.zLayers ?? o4.layers.map((t4) => _y(t4, e35.layerCount))).includes(t3.z))
          continue;
        const i4 = (o4.ccwRotationDegrees ?? 0) * Math.PI / 180, r4 = t3.x - o4.center.x, s3 = t3.y - o4.center.y, a4 = { x: r4 * Math.cos(i4) + s3 * Math.sin(i4), y: -r4 * Math.sin(i4) + s3 * Math.cos(i4) };
        oy(a4, a4, ny(o4)) > Aa || h3.push(JSON.stringify([l4, "pad", n4]));
      }
      for (const e36 of h3) {
        const t4 = s2.get(e36);
        t4 === undefined ? s2.set(e36, n3) : i3[r3(n3)] = r3(t4);
      }
    }
  }
  const c3 = (e36, t3) => !(!e36.startsWith("route:") || !t3.startsWith("route:")) && r3(Number(e36.slice(6))) === r3(Number(t3.slice(6))), l3 = [], h2 = [], d2 = [], u2 = t2.map(() => ({ segmentTimes: new Map, viaPositions: [] })), p3 = (e36) => {
    if (Oa(e36, n2)) {
      d2.push(e36);
      for (let t3 = e36.minZ;t3 <= e36.maxZ; t3 += 1)
        l3.push({ x: e36.x, y: e36.y, z: t3, radius: e36.radius, net: e36.net, source: e36.source, ...e36.routeIndex !== undefined ? { viaOwner: e36.routeIndex } : {} });
    }
  };
  for (let e36 = 0;e36 < t2.length; e36 += 1) {
    const i4 = t2[e36], r4 = o3(i4.connectionName), s3 = `route:${e36}`;
    for (let t3 = 0;t3 < i4.route.length; t3 += 1) {
      const o4 = i4.route[t3];
      if ((t3 === 0 || t3 === i4.route.length - 1 || o4.pcb_port_id) && Oa(o4, n2) && l3.push({ x: o4.x, y: o4.y, z: o4.z, radius: (o4.traceThickness ?? i4.traceThickness) / 2, net: r4, source: s3 }), t3 === 0)
        continue;
      const a4 = i4.route[t3 - 1];
      a4.toNextSegmentType !== "through_obstacle" && (a4.z === o4.z ? h2.push({ start: a4, end: o4, z: o4.z, radius: Math.max(a4.traceThickness ?? i4.traceThickness, o4.traceThickness ?? i4.traceThickness) / 2, net: r4, source: s3, routeIndex: e36, segmentIndex: t3 - 1 }) : p3({ x: o4.x, y: o4.y, minZ: Math.min(a4.z, o4.z), maxZ: Math.max(a4.z, o4.z), radius: i4.viaDiameter / 2, net: r4, source: s3, routeIndex: e36 }));
    }
  }
  for (let t3 = 0;t3 < (e35.traces ?? []).length; t3 += 1) {
    const i4 = Ta(e35.traces[t3], e35.minTraceWidth), r4 = o3(i4.connection_name), s3 = `fixed:${t3}`;
    for (let t4 = 0;t4 < i4.route.length; t4 += 1) {
      const o4 = i4.route[t4], a4 = i4.route[t4 - 1];
      if (o4.route_type === "wire") {
        const c4 = _y(o4.layer, e35.layerCount);
        (t4 === 0 || t4 === i4.route.length - 1 || o4.start_pcb_port_id || o4.end_pcb_port_id) && Oa(o4, n2) && l3.push({ x: o4.x, y: o4.y, z: c4, radius: o4.width / 2, net: r4, source: s3 }), a4?.route_type === "wire" && a4.layer === o4.layer && h2.push({ start: a4, end: o4, z: c4, radius: Math.max(a4.width, o4.width) / 2, net: r4, source: s3 });
      } else if (o4.route_type === "via") {
        const t5 = _y(o4.from_layer, e35.layerCount), n3 = _y(o4.to_layer, e35.layerCount);
        p3({ x: o4.x, y: o4.y, minZ: Math.min(t5, n3), maxZ: Math.max(t5, n3), radius: (o4.via_diameter ?? e35.minViaDiameter ?? 0.3) / 2, net: r4, source: s3 });
      }
    }
  }
  const m2 = new Map;
  for (const e36 of l3) {
    const t3 = JSON.stringify([e36.net, e36.z]), n3 = m2.get(t3) ?? [];
    n3.push(e36), m2.set(t3, n3);
  }
  const g2 = new Map;
  for (const [e36, t3] of m2) {
    const n3 = new uy(t3.length);
    for (const e37 of t3) {
      const t4 = e37.radius + Aa;
      n3.add(e37.x - t4, e37.y - t4, e37.x + t4, e37.y + t4);
    }
    n3.finish(), g2.set(e36, n3);
  }
  const f2 = (e36, t3, n3) => {
    const o4 = JSON.stringify([e36, t3]), i4 = m2.get(o4);
    return i4 ? g2.get(o4).search(n3.minX, n3.minY, n3.maxX, n3.maxY).sort((e37, t4) => e37 - t4).map((e37) => i4[e37]) : [];
  }, _2 = (e36, t3) => {
    if (e36 === undefined)
      return;
    const n3 = u2[e36].viaPositions;
    n3.some((e37) => Math.hypot(e37.x - t3.x, e37.y - t3.y) <= Aa) || n3.push({ x: t3.x, y: t3.y });
  };
  for (const e36 of h2) {
    if (!ka(e36.start, e36.end, n2))
      continue;
    const t3 = e36.end.x - e36.start.x, o4 = e36.end.y - e36.start.y, i4 = t3 * t3 + o4 * o4;
    if (i4 <= 0.00000000000000010000000000000001)
      continue;
    const r4 = e36.radius + Aa;
    for (const s3 of f2(e36.net, e36.z, { minX: Math.min(e36.start.x, e36.end.x) - r4, minY: Math.min(e36.start.y, e36.end.y) - r4, maxX: Math.max(e36.start.x, e36.end.x) + r4, maxY: Math.max(e36.start.y, e36.end.y) + r4 })) {
      if (s3.source === e36.source || c3(s3.source, e36.source))
        continue;
      const r5 = Math.max(0, Math.min(1, ((s3.x - e36.start.x) * t3 + (s3.y - e36.start.y) * o4) / i4)), a4 = { x: e36.start.x + t3 * r5, y: e36.start.y + o4 * r5 };
      if (Oa(a4, n2) && !(Math.hypot(a4.x - s3.x, a4.y - s3.y) > e36.radius + s3.radius + Aa)) {
        if (e36.routeIndex !== undefined && e36.segmentIndex !== undefined) {
          const t4 = u2[e36.routeIndex].segmentTimes.get(e36.segmentIndex) ?? [];
          t4.some((e37) => Math.abs(e37 - r5) <= Aa) || t4.push(r5), u2[e36.routeIndex].segmentTimes.set(e36.segmentIndex, t4);
        }
        _2(s3.viaOwner, s3);
      }
    }
  }
  for (const e36 of d2) {
    const t3 = e36.radius + Aa;
    for (let n3 = e36.minZ;n3 <= e36.maxZ; n3 += 1)
      for (const o4 of f2(e36.net, n3, { minX: e36.x - t3, minY: e36.y - t3, maxX: e36.x + t3, maxY: e36.y + t3 }))
        o4.source === e36.source || c3(o4.source, e36.source) || Math.hypot(e36.x - o4.x, e36.y - o4.y) > e36.radius + o4.radius + Aa || (_2(e36.routeIndex, e36), _2(o4.viaOwner, o4));
  }
  return ((e36, t3, n3, o4) => {
    const i4 = new Map, r4 = new Set, s3 = [], a4 = (e37, t4) => {
      if (e37.routeIndex === undefined || e37.segmentIndex === undefined)
        return;
      const o5 = e37.end.x - e37.start.x, i5 = e37.end.y - e37.start.y, r5 = o5 * o5 + i5 * i5;
      if (r5 <= 0.00000000000000010000000000000001)
        return;
      const s4 = Math.max(0, Math.min(1, ((t4.x - e37.start.x) * o5 + (t4.y - e37.start.y) * i5) / r5)), a5 = n3[e37.routeIndex].segmentTimes.get(e37.segmentIndex) ?? [];
      a5.some((e38) => Math.abs(e38 - s4) <= Aa) || a5.push(s4), n3[e37.routeIndex].segmentTimes.set(e37.segmentIndex, a5);
    };
    for (const n4 of e36) {
      const e37 = ka(n4.start, n4.end, t3);
      if (!e37 || e37[1] - e37[0] <= Aa)
        continue;
      const c4 = (e38) => ({ x: n4.start.x + (n4.end.x - n4.start.x) * e38, y: n4.start.y + (n4.end.y - n4.start.y) * e38 }), l4 = { ...n4, start: c4(e37[0]), end: c4(e37[1]) }, h3 = s3.length;
      s3.push({ original: n4, clipped: l4 });
      const d3 = Math.floor((Math.min(l4.start.x, l4.end.x) - l4.radius) / 2), u3 = Math.floor((Math.max(l4.start.x, l4.end.x) + l4.radius) / 2), p4 = Math.floor((Math.min(l4.start.y, l4.end.y) - l4.radius) / 2), m3 = Math.floor((Math.max(l4.start.y, l4.end.y) + l4.radius) / 2);
      for (let e38 = d3;e38 <= u3; e38 += 1)
        for (let t4 = p4;t4 <= m3; t4 += 1) {
          const c5 = JSON.stringify([l4.net, l4.z, e38, t4]), d4 = i4.get(c5) ?? [];
          for (const e39 of d4) {
            const t5 = s3[e39];
            if (t5.original.source === n4.source || o4(t5.original.source, n4.source) || t5.original.routeIndex === undefined && n4.routeIndex === undefined)
              continue;
            const i5 = `${e39}:${h3}`;
            if (r4.has(i5))
              continue;
            r4.add(i5);
            const [c6, d5] = fy(l4, t5.clipped);
            Math.hypot(c6.x - d5.x, c6.y - d5.y) > l4.radius + t5.clipped.radius + Aa || (a4(n4, c6), a4(t5.original, d5));
          }
          d4.push(h3), i4.set(c5, d4);
        }
    }
  })(h2, n2, u2, c3), u2;
};
var by = (e35, t2) => ({ minX: e35.minX - t2, maxX: e35.maxX + t2, minY: e35.minY - t2, maxY: e35.maxY + t2 });
var xy = (e35, t2, n2, o3) => {
  const i3 = [];
  let r3;
  const s2 = e35.route, a3 = (e36) => e36 === 0 || e36 === s2.length - 1 || s2[e36]?.pcb_port_id !== undefined, c3 = () => {
    r3 !== undefined && r3.points.length > 0 && (r3.locks[0] = true, r3.locks[r3.points.length - 1] = true, i3.push(r3)), r3 = undefined;
  };
  if (s2.length === 1 && s2[0] && Oa(s2[0], t2))
    return [{ points: structuredClone(s2), locks: [true], start: { segmentIndex: 0, t: 0 }, end: { segmentIndex: 0, t: 0 } }];
  for (let i4 = 0;i4 < s2.length - 1; i4 += 1) {
    const l3 = s2[i4], h2 = s2[i4 + 1];
    if (!l3 || !h2)
      throw new Error("repair04 found a missing route point");
    if (![l3.x, l3.y, l3.z, h2.x, h2.y, h2.z].every(Number.isFinite))
      throw new Error("repair04 route coordinates must be finite");
    if (l3.z !== h2.z && !La({ x: l3.x, y: l3.y }, { x: h2.x, y: h2.y }) && l3.toNextSegmentType !== "through_obstacle")
      throw new Error("repair04 requires colocated points at a via transition");
    const d2 = ka(l3, h2, t2);
    if (!d2) {
      c3();
      continue;
    }
    const [u2, p3] = d2;
    if (p3 - u2 <= Aa && !La(l3, h2)) {
      c3();
      continue;
    }
    const m2 = ka(l3, h2, n2), g2 = [u2, p3], f2 = o3.segmentTimes.get(i4) ?? [];
    for (const e36 of f2)
      e36 >= u2 - Aa && e36 <= p3 + Aa && g2.push(Math.max(u2, Math.min(p3, e36)));
    if (m2 && l3.z === h2.z)
      for (const e36 of m2)
        e36 > u2 + Aa && e36 < p3 - Aa && g2.push(e36);
    g2.sort((e36, t3) => e36 - t3);
    const _2 = g2.filter((e36, t3) => t3 === 0 || Math.abs(e36 - g2[t3 - 1]) > Aa), y2 = Da(l3, h2, u2);
    r3 && !La(r3.points[r3.points.length - 1], y2) && c3(), r3 || (r3 = { points: [], locks: [], start: { segmentIndex: i4, t: u2 }, end: { segmentIndex: i4, t: p3 } });
    for (const t3 of _2) {
      const s3 = Da(l3, h2, t3), c4 = t3 <= Aa ? i4 : t3 >= 0.99999999 ? i4 + 1 : undefined, d3 = !Oa(s3, n2, 0.00000004) || f2.some((e36) => Math.abs(e36 - t3) <= Aa) || o3.viaPositions.some((e36) => Math.hypot(e36.x - s3.x, e36.y - s3.y) <= Aa) || c4 !== undefined && a3(c4) || l3.toNextSegmentType === "through_obstacle" || s3.toNextSegmentType === "through_obstacle" || l3.insideJumperPad === true || h2.insideJumperPad === true || (e35.jumpers ?? []).some((e36) => La(s3, { ...e36.start, z: s3.z }) || La(s3, { ...e36.end, z: s3.z })), u3 = r3.points[r3.points.length - 1];
      u3 && u3.x === s3.x && u3.y === s3.y && u3.z === s3.z ? r3.locks[r3.locks.length - 1] = r3.locks[r3.locks.length - 1] || d3 : (r3.points.push(s3), r3.locks.push(d3));
    }
    r3.end = { segmentIndex: i4, t: p3 }, p3 < 0.99999999 && c3();
  }
  c3();
  for (const e36 of i3)
    for (let t3 = 1;t3 < e36.points.length; t3 += 1) {
      const n3 = e36.points[t3 - 1], o4 = e36.points[t3];
      if (n3.z !== o4.z && (e36.locks[t3 - 1] || e36.locks[t3])) {
        let n4 = t3 - 1, i4 = t3;
        for (;n4 > 0 && La({ x: e36.points[n4 - 1].x, y: e36.points[n4 - 1].y }, { x: o4.x, y: o4.y }); )
          n4 -= 1;
        for (;i4 + 1 < e36.points.length && La({ x: e36.points[i4 + 1].x, y: e36.points[i4 + 1].y }, { x: o4.x, y: o4.y }); )
          i4 += 1;
        for (let t4 = n4;t4 <= i4; t4 += 1)
          e36.locks[t4] = true;
      }
    }
  return i3;
};
var vy = (e35, t2) => {
  const n2 = e35.bounds, o3 = e35.outline && e35.outline.length >= 3 ? e35.outline : [{ x: n2.minX, y: n2.minY }, { x: n2.maxX, y: n2.minY }, { x: n2.maxX, y: n2.maxY }, { x: n2.minX, y: n2.maxY }], i3 = [];
  for (let n3 = 0;n3 < o3.length; n3 += 1) {
    const r3 = o3[n3], s2 = o3[(n3 + 1) % o3.length], a3 = ka(r3, s2, t2);
    if (!a3)
      continue;
    const c3 = s2.x - r3.x, l3 = s2.y - r3.y, h2 = Math.hypot(c3, l3);
    if (h2 <= Aa)
      continue;
    const d2 = (a3[0] + a3[1]) / 2;
    i3.push({ obstacleId: `repair04_board_edge_${n3}`, type: "rect", center: { x: r3.x + c3 * d2, y: r3.y + l3 * d2 }, width: h2 * (a3[1] - a3[0]), height: Math.max(2 * (e35.minBoardEdgeClearance ?? 0), Aa), ccwRotationDegrees: 180 * Math.atan2(l3, c3) / Math.PI, layers: Array.from({ length: e35.layerCount }, (t3, n4) => n4 === 0 ? "top" : n4 === e35.layerCount - 1 ? "bottom" : `inner${n4}`), zLayers: Array.from({ length: e35.layerCount }, (e36, t3) => t3), connectedTo: [] });
  }
  return i3;
};
var Iy = ({ srj: e35, routes: t2, bounds: n2, boundaryMargin: o3 = 0.5, clearanceHalo: i3 }) => {
  if (((e36) => {
    if (!Object.values(e36).every(Number.isFinite))
      throw new Error("repair04 bounds must contain finite coordinates");
    if (e36.maxX - e36.minX < 9.99999999 || e36.maxY - e36.minY < 9.99999999)
      throw new Error("repair04 requires bounds at least 10 mm by 10 mm");
  })(n2), !Number.isFinite(o3) || o3 < 0 || i3 !== undefined && (!Number.isFinite(i3) || i3 < 0))
    throw new Error("repair04 collar and halo must be finite and nonnegative");
  const r3 = Math.max(e35.defaultObstacleMargin ?? 0.2, e35.minTraceToPadEdgeClearance ?? 0, e35.minTraceToHoleEdgeClearance ?? 0, e35.minViaEdgeToPadEdgeClearance ?? 0);
  let s2 = Math.max(e35.minTraceWidth, e35.minViaDiameter ?? 0);
  for (const e36 of t2) {
    s2 = Math.max(s2, e36.traceThickness, e36.viaDiameter);
    for (const t3 of e36.route)
      s2 = Math.max(s2, t3.traceThickness ?? 0);
  }
  for (const t3 of e35.traces ?? [])
    for (const n3 of t3.route)
      n3.route_type === "wire" && (s2 = Math.max(s2, n3.width)), n3.route_type === "via" && (s2 = Math.max(s2, n3.via_diameter ?? e35.minViaDiameter ?? 0.3));
  if (!Number.isFinite(s2) || s2 <= 0)
    throw new Error("repair04 requires finite positive copper widths");
  const a3 = Math.max(o3, s2 + r3);
  if (2 * a3 >= Math.min(n2.maxX - n2.minX, n2.maxY - n2.minY))
    throw new Error("repair04 bounds are too small for their required copper safety collar");
  const c3 = by(n2, Math.max(i3 ?? a3, r3 + s2)), l3 = by(n2, -a3), h2 = yy(e35, t2, c3), d2 = ((e36, t3, n3) => {
    const o4 = [];
    for (const i4 of e36) {
      const e37 = Ta(i4, n3), r4 = [];
      let s3 = [];
      const a4 = () => {
        s3.length > 0 && r4.push(s3), s3 = [];
      }, c4 = (e38) => {
        za(s3[s3.length - 1]) !== za(e38) && s3.push(structuredClone(e38));
      };
      for (let n4 = 0;n4 < e37.route.length; n4 += 1) {
        const o5 = e37.route[n4], i5 = e37.route[n4 - 1];
        if (o5.route_type === "wire" && i5?.route_type === "wire" && o5.layer === i5.layer) {
          const e38 = ka(i5, o5, t3);
          if (!e38) {
            a4();
            continue;
          }
          const n5 = hy(i5, o5, e38[0]), r5 = hy(i5, o5, e38[1]), l4 = s3[s3.length - 1];
          l4?.route_type === "wire" && (l4.layer !== n5.layer || Math.hypot(l4.x - n5.x, l4.y - n5.y) > Aa) && a4(), c4(n5), c4(r5), e38[1] < 0.99999999 && a4();
        } else if (o5.route_type === "via") {
          if (!Oa(o5, t3)) {
            a4();
            continue;
          }
          if (i5?.route_type !== "wire")
            throw new Error("repair04 normalized preload via has no incoming wire");
          c4(i5), c4(o5);
          const r5 = e37.route[n4 + 1];
          if (r5?.route_type !== "wire")
            throw new Error("repair04 normalized preload via has no outgoing wire");
          c4(r5);
        } else if (o5.route_type === "wire")
          Oa(o5, t3) && c4(o5);
        else if ("start" in o5 && "end" in o5) {
          const e38 = ka(o5.start, o5.end, t3);
          if (!e38) {
            a4();
            continue;
          }
          const n5 = (e39) => ({ x: o5.start.x + (o5.end.x - o5.start.x) * e39, y: o5.start.y + (o5.end.y - o5.start.y) * e39 });
          c4({ ...structuredClone(o5), start: n5(e38[0]), end: n5(e38[1]) }), e38[1] < 0.99999999 && a4();
        }
      }
      a4();
      for (let e38 = 0;e38 < r4.length; e38 += 1)
        o4.push({ ...structuredClone(i4), pcb_trace_id: r4.length === 1 ? i4.pcb_trace_id : `${i4.pcb_trace_id}__repair04_fixed_${e38}`, route: r4[e38] });
    }
    return o4;
  })(e35.traces ?? [], c3, e35.minTraceWidth), u2 = [], p3 = [], m2 = [];
  for (let e36 = 0;e36 < t2.length; e36 += 1) {
    const n3 = t2[e36];
    for (const t3 of xy(n3, c3, l3, h2[e36])) {
      const o4 = { ...structuredClone(Object.fromEntries(Object.entries(n3).filter(([e37]) => e37 !== "route" && e37 !== "vias" && e37 !== "jumpers"))), connectionName: n3.connectionName, traceThickness: n3.traceThickness, viaDiameter: n3.viaDiameter, route: t3.points, vias: n3.vias.filter((e37) => t3.points.some((t4) => Math.abs(t4.x - e37.x) <= Aa && Math.abs(t4.y - e37.y) <= Aa)).map((e37) => structuredClone(e37)), ...n3.jumpers !== undefined ? { jumpers: n3.jumpers.filter((e37) => ka(e37.start, e37.end, c3) !== undefined).map((e37) => structuredClone(e37)) } : {} };
      u2.push(o4), p3.push(t3.locks), m2.push({ sourceRouteIndex: e36, start: t3.start, end: t3.end, sourceGeometryKey: Fa(n3, t3.start.segmentIndex + t3.start.t, t3.end.segmentIndex + t3.end.t), originalFragment: structuredClone(o4) });
    }
  }
  const g2 = new Set([...u2.flatMap((e36) => [e36.connectionName, ...e36.rootConnectionName ? [e36.rootConnectionName] : []]), ...d2.map((e36) => e36.connection_name)]), f2 = e35.connections.filter((e36) => g2.has(e36.name) || e36.pointsToConnect.some((e37) => Oa(e37, c3))).map((e36) => ({ ...structuredClone(Object.fromEntries(Object.entries(e36).filter(([e37]) => e37 !== "pointsToConnect"))), name: e36.name, pointsToConnect: e36.pointsToConnect.filter((e37) => Oa(e37, c3)).map((e37) => structuredClone(e37)) }));
  for (let t3 = 0;t3 < u2.length; t3 += 1) {
    const n3 = u2[t3];
    let o4 = f2.find((e36) => e36.name === n3.connectionName);
    o4 || (o4 = { name: n3.connectionName, ...n3.rootConnectionName ? { rootConnectionName: n3.rootConnectionName } : {}, pointsToConnect: [] }, f2.push(o4));
    for (const [i4, r4] of [["start", n3.route[0]], ["end", n3.route[n3.route.length - 1]]]) {
      if (!r4)
        continue;
      const n4 = r4.z === 0 ? "top" : r4.z === e35.layerCount - 1 ? "bottom" : `inner${r4.z}`;
      o4.pointsToConnect.some((e36) => Math.abs(e36.x - r4.x) <= Aa && Math.abs(e36.y - r4.y) <= Aa && ("layer" in e36 ? e36.layer === n4 : e36.layers.includes(n4))) || o4.pointsToConnect.push({ x: r4.x, y: r4.y, layer: n4, pointId: `repair04_${t3}_${i4}`, ...r4.pcb_port_id ? { pcb_port_id: r4.pcb_port_id } : {} });
    }
  }
  const _2 = { ...Object.fromEntries(Object.entries(e35).filter(([e36, t3]) => e36 !== "sourceCircuitJson" && e36 !== "sourceKicadPcb" && (typeof t3 == "number" || typeof t3 == "boolean" || typeof t3 == "string"))), layerCount: e35.layerCount, minTraceWidth: e35.minTraceWidth, bounds: structuredClone(c3), obstacles: [...e35.obstacles.filter((e36) => ((e37, t3) => {
    const n3 = (e37.ccwRotationDegrees ?? 0) * Math.PI / 180, o4 = (Math.abs(e37.width * Math.cos(n3)) + Math.abs(e37.height * Math.sin(n3))) / 2, i4 = (Math.abs(e37.width * Math.sin(n3)) + Math.abs(e37.height * Math.cos(n3))) / 2;
    return e37.center.x + o4 >= t3.minX && e37.center.x - o4 <= t3.maxX && e37.center.y + i4 >= t3.minY && e37.center.y - i4 <= t3.maxY;
  })(e36, c3)).map((e36) => structuredClone(e36)), ...vy(e35, c3)], connections: f2, ...e35.traces !== undefined ? { traces: d2 } : {}, ...e35.allowJumpers !== undefined ? { allowJumpers: e35.allowJumpers } : {}, ...e35.availableJumperTypes ? { availableJumperTypes: structuredClone(e35.availableJumperTypes) } : {} };
  return { srj: _2, routes: u2, bounds: structuredClone(n2), contextBounds: c3, mutableBounds: l3, boundaryMargin: a3, lockedPointIndices: p3, routeMappings: m2 };
};
var Sy = (e35) => za(Object.fromEntries(Object.entries(e35).filter(([e36]) => e36 !== "route" && e36 !== "vias")));
var Cy = (e35, t2) => {
  const n2 = [];
  for (let o3 = 1;o3 < e35.route.length; o3 += 1) {
    const i3 = e35.route[o3 - 1], r3 = e35.route[o3], s2 = ka(i3, r3, t2), a3 = s2 ? [...s2[0] > Aa ? [[0, s2[0]]] : [], ...s2[1] < 0.99999999 ? [[s2[1], 1]] : []] : [[0, 1]];
    s2 && !Oa(Da(i3, r3, 0.5), t2, 0.00000004) && a3.length === 0 && a3.push([0, 1]);
    for (const [e36, t3] of a3)
      n2.push(za([Da(i3, r3, e36), Da(i3, r3, t3)]));
  }
  return n2;
};
var Py = (e35, t2, n2, o3, i3, r3) => {
  if (Sy(e35) !== Sy(t2))
    throw new Error("repair04 merge rejected changed net, width, jumper, or route metadata");
  if (n2.length !== e35.route.length)
    throw new Error("repair04 merge received an invalid lock mask");
  if (t2.route.length === 0)
    throw new Error("repair04 merge rejected an empty replacement route");
  if (za(e35.route[0]) !== za(t2.route[0]) || za(e35.route[e35.route.length - 1]) !== za(t2.route[t2.route.length - 1]))
    throw new Error("repair04 merge rejected a moved fragment endpoint");
  let s2 = 0;
  for (let o4 = 0;o4 < e35.route.length; o4 += 1) {
    if (!n2[o4])
      continue;
    const i4 = za(e35.route[o4]);
    for (;s2 < t2.route.length && za(t2.route[s2]) !== i4; )
      s2 += 1;
    if (s2 === t2.route.length)
      throw new Error("repair04 merge rejected a moved or removed locked point");
    s2 += 1;
  }
  if (za(Cy(e35, o3)) !== za(Cy(t2, o3)))
    throw new Error("repair04 merge rejected modified geometry in the fixed boundary collar");
  for (let n3 = 1;n3 < e35.route.length; n3 += 1) {
    const o4 = e35.route[n3 - 1], i4 = e35.route[n3];
    if (!(o4.toNextSegmentType === "through_obstacle" || o4.insideJumperPad === true || i4.insideJumperPad === true || (e35.jumpers ?? []).some((e36) => La(o4, { ...e36.start, z: o4.z }) && La(i4, { ...e36.end, z: i4.z }) || La(o4, { ...e36.end, z: o4.z }) && La(i4, { ...e36.start, z: i4.z }))))
      continue;
    const r4 = za([o4, i4]);
    if (!t2.route.some((e36, n4) => n4 + 1 < t2.route.length && za([e36, t2.route[n4 + 1]]) === r4))
      throw new Error("repair04 merge rejected a changed atomic jumper or through-obstacle span");
  }
  for (const n3 of t2.route) {
    if (![n3.x, n3.y, n3.z].every(Number.isFinite) || !Number.isInteger(n3.z) || n3.z < 0 || n3.z >= r3 || !Oa(n3, i3))
      throw new Error("repair04 merge rejected invalid or out-of-region geometry");
    if ((n3.pcb_port_id !== undefined || n3.insideJumperPad === true || n3.toNextSegmentCircuitJsonMetadata !== undefined) && !e35.route.some((e36) => za(e36) === za(n3)))
      throw new Error("repair04 merge rejected invented or moved terminal/circuit metadata");
    if (n3.traceThickness !== undefined && (!Number.isFinite(n3.traceThickness) || n3.traceThickness <= 0 || n3.traceThickness > Math.max(e35.traceThickness, ...e35.route.map((e36) => e36.traceThickness ?? 0)) + Aa))
      throw new Error("repair04 merge rejected increased per-point copper width");
  }
  for (let n3 = 1;n3 < t2.route.length; n3 += 1) {
    const o4 = t2.route[n3 - 1], i4 = t2.route[n3];
    if (o4.toNextSegmentType === "through_obstacle" && !e35.route.some((t3, n4) => n4 + 1 < e35.route.length && za([t3, e35.route[n4 + 1]]) === za([o4, i4])))
      throw new Error("repair04 merge rejected an invented through-obstacle span");
    if (o4.z !== i4.z && o4.toNextSegmentType !== "through_obstacle" && (Math.abs(o4.x - i4.x) > Aa || Math.abs(o4.y - i4.y) > Aa || !t2.vias.some((e36) => Math.abs(e36.x - o4.x) <= Aa && Math.abs(e36.y - o4.y) <= Aa)))
      throw new Error("repair04 merge rejected a disconnected or missing via");
  }
  for (const n3 of t2.vias) {
    if (!(Number.isFinite(n3.x) && Number.isFinite(n3.y) && Oa(n3, i3) && t2.route.some((e36) => Math.abs(e36.x - n3.x) <= Aa && Math.abs(e36.y - n3.y) <= Aa)))
      throw new Error("repair04 merge rejected an invalid via position");
    if (!Oa(n3, o3, 0.00000004) && !e35.vias.some((e36) => za(e36) === za(n3)))
      throw new Error("repair04 merge rejected a new via in the boundary collar");
  }
  for (const n3 of e35.vias)
    if (!Oa(n3, o3, 0.00000004) && !t2.vias.some((e36) => za(e36) === za(n3)))
      throw new Error("repair04 merge rejected a changed via in the boundary collar");
};
var My = (e35, t2) => {
  for (const n2 of t2) {
    const t3 = e35[e35.length - 1];
    t3 && La(t3, n2) && za(t3) === za(n2) || e35.push(structuredClone(n2));
  }
};
var wy = (e35, t2, n2) => {
  const o3 = new Set(t2.route.map(za)), i3 = new Set(n2.flatMap((e36) => e36.originalFragment.route.map(za)).filter((e36) => !o3.has(e36))), r3 = [];
  for (const t3 of e35)
    for (r3.push(t3);r3.length >= 3; ) {
      const e36 = r3[r3.length - 3], t4 = r3[r3.length - 2], n3 = r3[r3.length - 1];
      if (!i3.has(za(t4)))
        break;
      if (e36.z !== t4.z || t4.z !== n3.z && e36.toNextSegmentType !== "through_obstacle")
        break;
      if (e36.toNextSegmentType !== t4.toNextSegmentType || e36.insideJumperPad !== t4.insideJumperPad || e36.traceThickness !== t4.traceThickness || za(e36.toNextSegmentCircuitJsonMetadata) !== za(t4.toNextSegmentCircuitJsonMetadata))
        break;
      const o4 = n3.x - e36.x, s2 = n3.y - e36.y, a3 = o4 * o4 + s2 * s2;
      if (a3 <= 0.00000000000000010000000000000001)
        break;
      const c3 = (t4.x - e36.x) * s2 - (t4.y - e36.y) * o4, l3 = ((t4.x - e36.x) * o4 + (t4.y - e36.y) * s2) / a3;
      if (Math.abs(c3) > Aa * Math.sqrt(a3) || l3 < 0 || l3 > 1)
        break;
      r3.splice(r3.length - 2, 1);
    }
  return r3;
};
var Ny = (e35) => {
  if (!Number.isInteger(e35.segmentIndex) || e35.segmentIndex < 0 || !Number.isFinite(e35.t) || e35.t < 0 || e35.t > 1)
    throw new Error("repair04 merge received invalid fragment provenance");
  return e35.segmentIndex + e35.t;
};
var Ry = (e35, t2) => {
  const n2 = Math.max(Math.abs(e35), Math.abs(t2));
  if (n2 === 0 || n2 === Number.POSITIVE_INFINITY)
    return n2;
  const o3 = e35 / n2, i3 = t2 / n2;
  return n2 * Math.sqrt(o3 * o3 + i3 * i3);
};
function Ty(e35, t2, n2) {
  return e35.minX - n2 - Aa > t2.maxX || e35.maxX + n2 + Aa < t2.minX || e35.minY - n2 - Aa > t2.maxY || e35.maxY + n2 + Aa < t2.minY;
}
function Ey({ route: e35, mutableBounds: t2 }) {
  const n2 = e35.vias.filter((n3) => !Oa(n3, t2, 0.00000004) && e35.route.some((e36) => Math.abs(e36.x - n3.x) <= Aa && Math.abs(e36.y - n3.y) <= Aa)).map((e36) => structuredClone(e36));
  for (let t3 = 1;t3 < e35.route.length; t3++) {
    const o3 = e35.route[t3 - 1], i3 = e35.route[t3];
    if (o3.z !== i3.z && o3.toNextSegmentType !== "through_obstacle") {
      if (o3.x !== i3.x || o3.y !== i3.y)
        throw new Error("repair04: a layer transition must have coincident endpoints");
      n2.some((e36) => e36.x === i3.x && e36.y === i3.y) || n2.push({ x: i3.x, y: i3.y });
    }
  }
  return n2;
}
var Ay = class {
  constructor(e35) {
    this.srj = e35;
  }
  boardParents;
  createNetResolver(e35) {
    const t2 = new Map(this.boardParents), n2 = (e36) => {
      const o4 = t2.get(e36);
      if (o4 === undefined || o4 === e36)
        return e36;
      const i3 = n2(o4);
      return t2.set(e36, i3), i3;
    }, o3 = (e36) => {
      const o4 = e36.filter((e37) => Boolean(e37));
      if (!o4.length)
        return;
      const i3 = n2(o4[0]);
      for (const e37 of o4)
        t2.set(n2(e37), i3);
    };
    if (!this.boardParents) {
      for (const e36 of this.srj.connections) {
        const t3 = e36;
        o3([t3.name, t3.rootConnectionName, t3.netConnectionName, t3.__netConnectionName, ...t3.mergedConnectionNames ?? [], ...t3.__rootConnectionNames ?? [], ...t3.pointsToConnect.flatMap((e37) => [e37.pcb_port_id, e37.pointId])]);
      }
      for (const e36 of this.srj.obstacles)
        o3(e36.connectedTo);
      this.boardParents = new Map(t2);
    }
    for (const t3 of e35)
      o3([t3.connectionName, t3.rootConnectionName]);
    return n2;
  }
};
var Dy = (e35, t2, n2) => {
  const o3 = n2.x - t2.x, i3 = n2.y - t2.y, r3 = o3 ** 2 + i3 ** 2;
  if (r3 === 0) {
    const n3 = e35.x - t2.x, o4 = e35.y - t2.y;
    return n3 * n3 + o4 * o4;
  }
  const s2 = Math.max(0, Math.min(1, ((e35.x - t2.x) * o3 + (e35.y - t2.y) * i3) / r3)), a3 = e35.x - (t2.x + s2 * o3), c3 = e35.y - (t2.y + s2 * i3);
  return a3 * a3 + c3 * c3;
};
var Ly = (e35, t2, n2, o3) => e35.x === t2.x && e35.y === t2.y ? Math.sqrt(Dy(e35, n2, o3)) : n2.x === o3.x && n2.y === o3.y ? Math.sqrt(Dy(n2, e35, t2)) : he(e35, t2, n2, o3) ? 0 : Math.sqrt(Math.min(Dy(e35, n2, o3), Dy(t2, n2, o3), Dy(n2, e35, t2), Dy(o3, e35, t2)));
var zy = class extends BaseSolver {
  constructor(e35, t2) {
    super(), this.connectivity = t2, this.input = e35, this.stats = e35.stats ?? { nodesPopped: 0, completionReason: "no-path" }, this.MAX_ITERATIONS = Math.ceil((e35.maxNodes ?? 30000) / 128) + Math.ceil(e35.srj.obstacles.length / 128) + Math.ceil(e35.routes.length / 32) + Math.ceil((e35.srj.traces?.length ?? 0) / 32) + e35.srj.obstacles.length * e35.srj.layerCount + e35.routes.reduce((e36, t3) => e36 + t3.route.length, 0) + (e35.srj.traces ?? []).reduce((e36, t3) => e36 + t3.route.length, 0) + 32;
  }
  input;
  stats;
  phase = "initialize";
  cursor = 0;
  barrierCount = 0;
  output;
  prepareObstacle;
  prepareRoute;
  prepareTrace;
  indexBarrier;
  seedSearch;
  searchBatch;
  finish(e35) {
    this.output = e35, this.phase = "finished", this.solved = true, this.progress = 1, this.prepareObstacle = undefined, this.prepareRoute = undefined, this.prepareTrace = undefined, this.indexBarrier = undefined, this.seedSearch = undefined, this.searchBatch = undefined;
  }
  _step() {
    if (this.phase === "initialize")
      return void this.initialize();
    if (this.phase === "seed")
      return void this.seedSearch();
    if (this.phase === "search")
      return this.searchBatch(), void (this.solved || (this.progress = Math.min(0.99, this.stats.nodesPopped / (this.input.maxNodes ?? 30000))));
    const e35 = this.cursor;
    if (this.phase === "obstacles") {
      const t2 = this.input.srj.obstacles;
      for (;this.cursor < Math.min(e35 + 128, t2.length); this.cursor++)
        this.prepareObstacle(t2[this.cursor]);
      return void (this.cursor === t2.length && (this.phase = "routes", this.cursor = 0));
    }
    if (this.phase !== "routes") {
      if (this.phase === "traces") {
        const t2 = this.input.srj.traces ?? [];
        for (;this.cursor < Math.min(e35 + 32, t2.length); this.cursor++)
          this.prepareTrace(t2[this.cursor]);
        return void (this.cursor === t2.length && (this.phase = "index", this.cursor = 0));
      }
      if (this.phase !== "index")
        throw new Error("repair04: clearance path stepped after completion");
      for (;this.cursor < Math.min(e35 + 128, this.barrierCount); this.cursor++)
        this.indexBarrier(this.cursor);
      this.cursor === this.barrierCount && (this.phase = "seed");
    } else {
      for (;this.cursor < Math.min(e35 + 32, this.input.routes.length); this.cursor++)
        this.prepareRoute(this.input.routes[this.cursor]);
      this.cursor === this.input.routes.length && (this.phase = "traces", this.cursor = 0);
    }
  }
  initialize() {
    const e35 = this.input, { srj: t2, routes: n2, routeIndex: o3, start: i3, end: r3, bounds: s2, traceThickness: a3 } = e35, c3 = e35.heuristicWeight ?? 1;
    if (!Number.isFinite(c3) || c3 < 1)
      throw new Error("repair04: heuristic weight must be finite and at least one");
    const l3 = (t3, n3) => {
      const o4 = e35.getAdditionalEdgeCost?.(t3, n3) ?? 0;
      if (Number.isNaN(o4) || o4 < 0)
        throw new Error("repair04: additional edge costs must be nonnegative");
      return o4;
    };
    if (e35.maxNodes !== undefined && (!Number.isSafeInteger(e35.maxNodes) || e35.maxNodes < 1))
      throw new Error("repair04: maxNodes must be a positive safe integer");
    if (this.stats && (this.stats.nodesPopped = 0, this.stats.completionReason = "no-path"), e35.allowLayerChanges === false && i3.z !== r3.z)
      return void this.finish(null);
    const h2 = n2[o3], d2 = e35.viaHoleDiameter ?? h2.viaDiameter;
    if (!Number.isFinite(d2) || d2 <= 0 || d2 > h2.viaDiameter)
      throw new Error("repair04: via hole diameter must be positive and fit the copper");
    const u2 = d2 + e35.viaClearance, p3 = (e36, t3) => {
      for (let n3 = t3;n3; n3 = n3.previous)
        if ((e36.x !== n3.x || e36.y !== n3.y) && Math.hypot(e36.x - n3.x, e36.y - n3.y) + Aa < u2)
          return false;
      return true;
    }, m2 = (e36) => {
      let t3;
      for (let n3 = 1;n3 < e36.length; n3++) {
        const o4 = e36[n3 - 1], i4 = e36[n3];
        if (o4.z !== i4.z && o4.toNextSegmentType !== "through_obstacle") {
          if (!p3(o4, t3))
            return false;
          o4.x === t3?.x && o4.y === t3?.y || (t3 = { x: o4.x, y: o4.y, previous: t3 });
        }
      }
      return true;
    }, g2 = (this.connectivity ?? new Ay(t2)).createNetResolver(n2), f2 = g2(h2.connectionName), _2 = (e36) => e36 === "top" ? 0 : e36 === "bottom" ? t2.layerCount - 1 : Number(e36.slice(5)), y2 = [s2.minX, s2.maxX, s2.minY, s2.maxY, i3.x, i3.y, r3.x, r3.y, a3, h2.viaDiameter, e35.traceClearance, e35.viaClearance, t2.defaultObstacleMargin ?? 0, t2.minTraceToPadEdgeClearance ?? 0, t2.minTraceToHoleEdgeClearance ?? 0, t2.minViaEdgeToPadEdgeClearance ?? 0].every((e36) => Number.isFinite(e36) && Math.abs(e36) <= 1e4), b2 = [], x2 = (e36, n3, o4, i4, r4 = false, s3 = false, a4 = false) => {
      const c4 = i4 ? Math.hypot(i4.width, i4.height) / 2 : o4, l4 = i4 ? Math.cos(i4.rotation) : 1, h3 = i4 ? Math.sin(i4.rotation) : 0, d3 = { minX: Math.min(e36.x, n3.x) - c4, maxX: Math.max(e36.x, n3.x) + c4, minY: Math.min(e36.y, n3.y) - c4, maxY: Math.max(e36.y, n3.y) + c4 }, u3 = i4 && y2 ? ((e37, t3, n4, o5, i5, r5) => {
        if (e37.x !== t3.x || e37.y !== t3.y || !Number.isFinite(n4.rotation) || n4.width <= 0 || n4.height <= 0 || ![e37.x, e37.y, n4.width, n4.height, r5.minX, r5.maxX, r5.minY, r5.maxY].every((e38) => Number.isFinite(e38) && Math.abs(e38) <= 1e4))
          return r5;
        const s4 = o5 * o5 + i5 * i5;
        if (!Number.isFinite(s4) || Math.abs(s4 - 1) > 0.000000000001)
          return r5;
        const a5 = n4.width / 2, c5 = n4.height / 2, l5 = (Math.abs(o5) * a5 + Math.abs(i5) * c5) / s4 + 0.00000001, h4 = (Math.abs(i5) * a5 + Math.abs(o5) * c5) / s4 + 0.00000001, d4 = { minX: e37.x - l5, maxX: e37.x + l5, minY: e37.y - h4, maxY: e37.y + h4 };
        return d4.minX < r5.minX || d4.maxX > r5.maxX || d4.minY < r5.minY || d4.maxY > r5.maxY ? r5 : d4;
      })(e36, n3, i4, l4, h3, d3) : d3;
      b2.push({ a: e36, b: n3, radius: o4, rect: i4, viaOnly: r4, pad: s3, isNonPlatedHole: a4, rectCos: l4, rectSin: h3, rectBounds: i4 ? { minX: -i4.width / 2, maxX: i4.width / 2, minY: -i4.height / 2, maxY: i4.height / 2 } : undefined, visitedQuery: 0, ...u3, ...Na(t2, e36, n3) });
    };
    this.prepareObstacle = (e36) => {
      const t3 = e36.connectedTo.some((e37) => g2(e37) === f2), n3 = e36.__zLayers ?? e36.zLayers ?? e36.layers.map(_2), o4 = e36.isNonPlatedHole && e36.shape === "circle" || e36.type === "oval" && e36.width === e36.height && e36.ccwRotationDegrees === undefined && n3.length > 1;
      for (const i4 of n3) {
        const n4 = { ...e36.center, z: i4 };
        x2(n4, n4, o4 ? e36.width / 2 : 0, o4 ? undefined : { width: e36.width, height: e36.height, rotation: (e36.ccwRotationDegrees ?? 0) * Math.PI / 180 }, t3, o4, e36.isNonPlatedHole);
      }
      this.barrierCount = b2.length;
    }, this.prepareRoute = (e36) => {
      if (g2(e36.connectionName) !== f2) {
        for (let t3 = 1;t3 < e36.route.length; t3++) {
          const n3 = e36.route[t3 - 1], o4 = e36.route[t3];
          n3.toNextSegmentType !== "through_obstacle" && x2(n3, o4, n3.z !== o4.z ? e36.viaDiameter / 2 : Math.max(n3.traceThickness ?? e36.traceThickness, o4.traceThickness ?? e36.traceThickness) / 2);
        }
        this.barrierCount = b2.length;
      }
    }, this.prepareTrace = (e36) => {
      if (g2(e36.connection_name) === f2)
        return;
      const n3 = Ta(e36, t2.minTraceWidth);
      for (let e37 = 1;e37 < n3.route.length; e37++) {
        const t3 = n3.route[e37 - 1], o4 = n3.route[e37];
        t3.route_type === "wire" && o4.route_type === "wire" && t3.layer === o4.layer && x2({ x: t3.x, y: t3.y, z: _2(t3.layer) }, { x: o4.x, y: o4.y, z: _2(o4.layer) }, Math.max(t3.width, o4.width) / 2), o4.route_type === "via" && x2({ x: o4.x, y: o4.y, z: _2(o4.from_layer) }, { x: o4.x, y: o4.y, z: _2(o4.to_layer) }, (o4.via_diameter ?? h2.viaDiameter) / 2);
      }
      this.barrierCount = b2.length;
    };
    const v2 = new Map, I2 = Math.max(h2.viaDiameter, a3) / 2 + Math.max(e35.traceClearance, e35.viaClearance, t2.defaultObstacleMargin ?? 0, t2.minTraceToPadEdgeClearance ?? 0, t2.minTraceToHoleEdgeClearance ?? 0, t2.minViaEdgeToPadEdgeClearance ?? 0) + 0.00001;
    this.indexBarrier = (e36) => {
      const t3 = b2[e36];
      for (let e37 = Math.floor(Math.max(t3.minX, s2.minX - I2));e37 <= Math.floor(Math.min(t3.maxX, s2.maxX + I2)); e37++) {
        let n3 = v2.get(e37);
        for (let o4 = Math.floor(Math.max(t3.minY, s2.minY - I2));o4 <= Math.floor(Math.min(t3.maxY, s2.maxY + I2)); o4++) {
          n3 || (n3 = new Map, v2.set(e37, n3));
          const i4 = n3.get(o4);
          i4 ? i4.push(t3) : n3.set(o4, [t3]);
        }
      }
    };
    let S2 = 0;
    const C = { x: 0, y: 0 }, P = { x: 0, y: 0 }, M = (n3, o4) => {
      const i4 = n3.z !== o4.z, r4 = i4 ? h2.viaDiameter / 2 : a3 / 2, s3 = Math.max(i4 ? e35.viaClearance : e35.traceClearance, t2.defaultObstacleMargin ?? 0, i4 ? t2.minViaEdgeToPadEdgeClearance ?? 0 : t2.minTraceToPadEdgeClearance ?? 0), c4 = r4 + Math.max(s3, t2.minTraceToHoleEdgeClearance ?? 0) + 0.00001, l4 = ++S2, d3 = Math.min(n3.x, o4.x), u3 = Math.max(n3.x, o4.x), p4 = Math.min(n3.y, o4.y), m3 = Math.max(n3.y, o4.y), { minZ: g3, maxZ: f3 } = Na(t2, n3, o4);
      for (let a4 = Math.floor(d3 - c4);a4 <= Math.floor(u3 + c4); a4++) {
        const h3 = v2.get(a4);
        if (h3)
          for (let a5 = Math.floor(p4 - c4);a5 <= Math.floor(m3 + c4); a5++) {
            const c5 = h3.get(a5);
            if (c5)
              for (const a6 of c5) {
                if (a6.viaOnly && !i4)
                  continue;
                if (a6.visitedQuery === l4)
                  continue;
                if (a6.visitedQuery = l4, a6.maxZ < g3 || a6.minZ > f3)
                  continue;
                const c6 = r4 + (a6.isNonPlatedHole && !i4 && t2.minTraceToHoleEdgeClearance !== undefined ? t2.minTraceToHoleEdgeClearance : a6.viaOnly ? Ea(t2, e35.viaClearance, true) : a6.rect || a6.pad ? s3 : i4 && a6.minZ !== a6.maxZ ? e35.viaClearance : e35.traceClearance);
                if (u3 + c6 < a6.minX || d3 - c6 > a6.maxX || m3 + c6 < a6.minY || p4 - c6 > a6.maxY)
                  continue;
                let h4;
                if (a6.rect ? (C.x = (n3.x - a6.a.x) * a6.rectCos + (n3.y - a6.a.y) * a6.rectSin, C.y = -(n3.x - a6.a.x) * a6.rectSin + (n3.y - a6.a.y) * a6.rectCos, P.x = (o4.x - a6.a.x) * a6.rectCos + (o4.y - a6.a.y) * a6.rectSin, P.y = -(o4.x - a6.a.x) * a6.rectSin + (o4.y - a6.a.y) * a6.rectCos, h4 = Ne(C, P, a6.rectBounds)) : h4 = Ly(n3, o4, a6.a, a6.b) - a6.radius, h4 + Aa < c6)
                  return false;
              }
          }
      }
      return true;
    };
    this.seedSearch = () => {
      if (!M(i3, i3) || !M(r3, r3))
        return void this.finish(null);
      if (e35.existingPath) {
        const t3 = e35.existingPath, n4 = t3[0], o5 = t3.at(-1);
        if (!n4 || !o5 || n4.x !== i3.x || n4.y !== i3.y || n4.z !== i3.z || o5.x !== r3.x || o5.y !== r3.y || o5.z !== r3.z)
          throw new Error("repair04: existing clearance path must match its anchors");
        if (t3.some((e36, n5) => {
          const o6 = t3[n5 - 1];
          return Boolean(o6 && o6.z !== e36.z && (o6.x !== e36.x || o6.y !== e36.y));
        }))
          throw new Error("repair04: existing clearance path has a non-colocated layer transition");
        if (m2(t3) && (e35.allowLayerChanges !== false || t3.every((e36) => e36.z === i3.z)) && t3.slice(1).every((e36, n5) => M(t3[n5], e36) && l3(t3[n5], e36) === 0))
          return this.stats && (this.stats.completionReason = "found"), void this.finish(t3.map((e36) => ({ ...e36 })));
      }
      const n3 = e35.gridSize ?? 0.1;
      if (!Number.isFinite(n3) || n3 <= 0)
        throw new Error("repair04: clearance grid size must be positive and finite");
      const o4 = Math.floor((s2.maxX - s2.minX) / n3), h3 = Math.floor((s2.maxY - s2.minY) / n3), d3 = (e36) => ({ x: s2.minX + (e36 % o4 + 0.5) * n3, y: s2.minY + (Math.floor(e36 / o4) % h3 + 0.5) * n3, z: Math.floor(e36 / (o4 * h3)), traceThickness: a3 }), u3 = (e36, t3, n4) => (n4 * h3 + t3) * o4 + e36, g3 = (e36) => Math.hypot(e36.x - r3.x, e36.y - r3.y) + (e36.z === r3.z ? 0 : 1), f3 = o4 * h3 * t2.layerCount, _3 = o4 > 0 && h3 > 0 && Number.isSafeInteger(t2.layerCount) && Number.isSafeInteger(f3) && f3 > 0 && f3 <= 1e6 && Number.isInteger(i3.z) && i3.z >= 0 && i3.z < t2.layerCount, y3 = new Ra(_3 ? f3 : undefined), b3 = _3 ? new Float64Array(f3).fill(1 / 0) : undefined, x3 = _3 ? new Int32Array(f3) : undefined, v3 = new Map, I3 = new Map, S3 = new Map, C2 = (N = i3, u3(Math.max(0, Math.min(o4 - 1, Math.floor((N.x - s2.minX) / n3))), Math.max(0, Math.min(h3 - 1, Math.floor((N.y - s2.minY) / n3))), N.z)), P2 = C2 % o4, w = Math.floor(C2 / o4) % h3;
      var N;
      for (let e36 = -2;e36 <= 2; e36++)
        for (let t3 = -2;t3 <= 2; t3++) {
          const n4 = P2 + e36, r4 = w + t3;
          if (n4 < 0 || n4 >= o4 || r4 < 0 || r4 >= h3)
            continue;
          const s3 = u3(n4, r4, i3.z), a4 = d3(s3);
          if (!M(i3, a4))
            continue;
          const p4 = Math.hypot(a4.x - i3.x, a4.y - i3.y) + l3(i3, a4);
          Number.isFinite(p4) && (b3 ? b3[s3] = p4 : v3.set(s3, p4), x3 ? x3[s3] = -1 : I3.set(s3, -1), y3.pushValues(s3, p4, p4 + c3 * g3(a4)));
        }
      const R2 = o4 * h3 * t2.layerCount, T2 = o4 > 0 && h3 > 0 && Number.isSafeInteger(t2.layerCount) && Number.isSafeInteger(R2) && R2 > 0 && Number.isSafeInteger(R2 * R2 - 1) && Number.isInteger(i3.z) && i3.z >= 0 && i3.z < t2.layerCount, E3 = _3 && c3 > 1 ? new Uint8Array(f3) : undefined, A2 = !_3 && c3 > 1 ? new Set : undefined, O2 = new Map, k2 = _3 && o4 >= 3 ? new Uint8Array(f3) : undefined, D2 = new Map, L2 = _3 ? new Uint8Array(o4 * h3) : undefined;
      let z2 = 0;
      this.searchBatch = () => {
        const s3 = Math.min(z2 + 128, e35.maxNodes ?? 30000);
        for (;y3.length && z2 < s3; ) {
          const s4 = y3.pop();
          if (z2++, this.stats && (this.stats.nodesPopped = z2), s4.cost !== (b3 ? b3[s4.id] : v3.get(s4.id)))
            continue;
          E3 ? E3[s4.id] = 1 : A2?.add(s4.id);
          const a4 = d3(s4.id), f4 = S3.get(s4.id);
          if (a4.z === r3.z && Math.hypot(a4.x - r3.x, a4.y - r3.y) < 3 * n3 && M(a4, r3) && Number.isFinite(l3(a4, r3))) {
            const t3 = [r3];
            for (let e36 = s4.id;e36 !== -1; e36 = x3 ? x3[e36] : I3.get(e36))
              t3.push(d3(e36));
            t3.push(i3);
            const n4 = t3.reverse(), o5 = [i3], a5 = [0];
            for (let t4 = 1;e35.getAdditionalEdgeCost && t4 < n4.length; t4++) {
              const e36 = n4[t4 - 1], o6 = n4[t4];
              a5.push(a5[t4 - 1] + (e36.z === o6.z ? Math.hypot(e36.x - o6.x, e36.y - o6.y) : 1) + l3(e36, o6));
            }
            let c4 = 0;
            for (let t4 = 1;t4 < n4.length; ) {
              let i4 = t4;
              if (n4[t4].z === o5.at(-1).z)
                for (let r4 = t4 + 1;r4 < n4.length && n4[r4].z === n4[t4].z; r4++)
                  M(o5.at(-1), n4[r4]) && (!e35.getAdditionalEdgeCost || Math.hypot(n4[r4].x - n4[c4].x, n4[r4].y - n4[c4].y) + l3(n4[c4], n4[r4]) <= a5[r4] - a5[c4] + Aa) && (i4 = r4);
              o5.push(n4[i4]), c4 = i4, t4 = i4 + 1;
            }
            if (!m2(o5))
              throw new Error("repair04: search generated conflicting drill sites");
            return this.stats && (this.stats.completionReason = "found"), void this.finish(o5);
          }
          const _4 = s4.id % o4, C3 = Math.floor(s4.id / o4) % h3, P3 = [];
          for (let e36 = -1;e36 <= 1; e36++)
            for (let t3 = -1;t3 <= 1; t3++)
              e36 === 0 && t3 === 0 || _4 + e36 < 0 || _4 + e36 >= o4 || C3 + t3 < 0 || C3 + t3 >= h3 || P3.push(u3(_4 + e36, C3 + t3, a4.z));
          if (e35.allowLayerChanges !== false && p3(a4, f4))
            for (let e36 = 0;e36 < t2.layerCount; e36++)
              e36 !== a4.z && P3.push(u3(_4, C3, e36));
          for (const e36 of P3) {
            if (E3 ? E3[e36] === 1 : A2?.has(e36))
              continue;
            const n4 = d3(e36), i4 = s4.cost + (a4.z === n4.z ? Math.hypot(a4.x - n4.x, a4.y - n4.y) : 1), r4 = b3 ? b3[e36] : v3.get(e36) ?? 1 / 0;
            if (i4 >= r4)
              continue;
            const u4 = Math.min(s4.id, e36), p4 = Math.max(s4.id, e36), m3 = T2 && a4.z !== n4.z && t2.allowBlindAndBuriedVias !== true ? s4.id % (o4 * h3) : undefined;
            let _5;
            if (k2 && a4.z === n4.z) {
              const e37 = p4 - u4, t3 = e37 === 1 ? 0 : e37 === o4 - 1 ? 2 : e37 === o4 ? 4 : 6, i5 = k2[u4] >> t3 & 3;
              i5 === 0 ? (_5 = M(a4, n4), k2[u4] = k2[u4] | (_5 ? 2 : 1) << t3) : _5 = i5 === 2;
            } else if (L2 && m3 !== undefined) {
              const e37 = L2[m3];
              e37 === 0 ? (_5 = M(a4, n4), L2[m3] = _5 ? 2 : 1) : _5 = e37 === 2;
            } else {
              const e37 = T2 ? u4 * R2 + p4 : `${u4},${p4}`;
              _5 = m3 === undefined ? O2.get(e37) : D2.get(m3), _5 === undefined && (_5 = M(a4, n4), m3 === undefined ? O2.set(e37, _5) : D2.set(m3, _5));
            }
            if (!_5)
              continue;
            const C4 = i4 + l3(a4, n4);
            C4 >= r4 || (a4.z === n4.z || a4.x === f4?.x && a4.y === f4?.y ? f4 ? S3.set(e36, f4) : S3.delete(e36) : S3.set(e36, { x: a4.x, y: a4.y, previous: f4 }), b3 ? b3[e36] = C4 : v3.set(e36, C4), x3 ? x3[e36] = s4.id : I3.set(e36, s4.id), y3.pushValues(e36, C4, C4 + c3 * g3(n4)));
          }
        }
        y3.length && z2 < (e35.maxNodes ?? 30000) || (this.stats.completionReason = y3.length ? "node-limit" : "no-path", this.finish(null));
      }, this.phase = "search";
    }, this.phase = "obstacles";
  }
  getOutput() {
    if (!this.solved || this.failed || this.output === undefined)
      throw new Error("repair04: clearance path output requested before completion");
    return this.output;
  }
  isSearchPrepared() {
    return this.phase === "search";
  }
  getResult() {
    return this.getOutput();
  }
};
function Fy(e35) {
  let t2;
  return { ...e35.pathInput, stats: { nodesPopped: 0, completionReason: "no-path" }, getAdditionalEdgeCost: (n2, o3) => (t2 ??= function(e36) {
    const { pathInput: t3, coppers: n3, selectedOwner: o4, weights: i3 } = e36, r3 = t3.routes[t3.routeIndex], s2 = (e37) => {
      if (!e37.length)
        return;
      const t4 = new uy(e37.length);
      for (const n4 of e37)
        t4.add(n4.minX - n4.radius - Aa, n4.minY - n4.radius - Aa, n4.maxX + n4.radius + Aa, n4.maxY + n4.radius + Aa);
      return t4.finish(), { index: t4, copper: e37, cellCandidates: new Map, queryStamps: new Uint32Array(e37.length) };
    }, a3 = s2(n3), c3 = new Map;
    for (let e37 = 0;e37 < t3.srj.layerCount; e37++)
      c3.set(e37, s2(n3.filter((t4) => t4.minZ <= e37 && t4.maxZ >= e37)));
    const l3 = [];
    let h2 = 0;
    const d2 = (e37, n4) => {
      const i4 = e37.z !== n4.z, s3 = Math.min(e37.x, n4.x), d3 = Math.max(e37.x, n4.x), u3 = Math.min(e37.y, n4.y), p4 = Math.max(e37.y, n4.y), m2 = (i4 ? r3.viaDiameter : r3.traceThickness) / 2 + Math.max(t3.traceClearance, t3.viaClearance), g2 = [], f2 = Na(t3.srj, e37, n4), _2 = i4 ? a3 : c3.get(e37.z), y2 = s3 - m2 - Aa, b2 = u3 - m2 - Aa, x2 = d3 + m2 + Aa, v2 = p4 + m2 + Aa, I2 = Math.floor(y2), S2 = Math.floor(x2), C = Math.floor(b2), P = Math.floor(v2);
      if (h2 === 4294967295) {
        a3?.queryStamps.fill(0);
        for (const e38 of c3.values())
          e38?.queryStamps.fill(0);
        h2 = 0;
      }
      const M = ++h2;
      let w;
      if (_2 && (S2 - I2 + 1) * (P - C + 1) <= 16 && Number.isSafeInteger(I2) && Number.isSafeInteger(S2) && Number.isSafeInteger(C) && Number.isSafeInteger(P)) {
        l3.length = 0;
        for (let e38 = I2;e38 <= S2; e38++) {
          let t4 = _2.cellCandidates.get(e38);
          t4 || (t4 = new Map, _2.cellCandidates.set(e38, t4));
          for (let n5 = C;n5 <= P; n5++) {
            let o5 = t4.get(n5);
            o5 || (o5 = _2.index.search(e38, n5, e38 + 1, n5 + 1), t4.set(n5, o5));
            for (const e39 of o5) {
              const t5 = _2.copper[e39];
              _2.queryStamps[e39] !== M && (_2.queryStamps[e39] = M, x2 < t5.minX - t5.radius - Aa || v2 < t5.minY - t5.radius - Aa || y2 > t5.maxX + t5.radius + Aa || b2 > t5.maxY + t5.radius + Aa || l3.push(e39));
            }
          }
        }
        w = l3;
      } else
        w = _2?.index.search(y2, b2, x2, v2) ?? [];
      for (const a4 of w) {
        const c4 = _2.copper[a4], l4 = i4 && c4.minZ !== c4.maxZ, h3 = c4.minZ <= f2.maxZ && c4.maxZ >= f2.minZ;
        if (!h3 && !l4)
          continue;
        if (c4.immutable && !l4)
          continue;
        if (c4.owner === o4 && (!l4 || e37.x === c4.a.x && e37.y === c4.a.y))
          continue;
        const m3 = (i4 ? r3.viaDiameter : r3.traceThickness) / 2 + (l4 ? t3.viaClearance : t3.traceClearance) + c4.radius, y3 = (t3.viaHoleDiameter ?? r3.viaDiameter) / 2 + (t3.viaHoleDiameter ?? 2 * c4.radius) / 2 + t3.viaClearance, b3 = l4 ? h3 && c4.owner !== o4 ? Math.max(m3, y3) : y3 : m3;
        if (s3 - b3 - Aa > c4.maxX || d3 + b3 + Aa < c4.minX || u3 - b3 - Aa > c4.maxY || p4 + b3 + Aa < c4.minY)
          continue;
        const x3 = Ly(e37, n4, c4.a, c4.b);
        x3 < b3 - Aa && g2.push({ copper: c4, ratio: (b3 - x3) / (b3 * b3) });
      }
      const N = Math.floor(s3 - m2), R2 = Math.floor(u3 - m2);
      return g2.sort((e38, t4) => {
        const n5 = Math.max(N, e38.copper.cellX) - Math.max(N, t4.copper.cellX);
        return n5 !== 0 ? n5 : Math.max(R2, e38.copper.cellY) - Math.max(R2, t4.copper.cellY) || e38.copper.index - t4.copper.index;
      }), g2;
    }, u2 = (e37, n4) => {
      const r4 = (e37.x + n4.x) / 2, s3 = (e37.y + n4.y) / 2;
      if (r4 <= t3.bounds.minX + 0.00000004 || r4 >= t3.bounds.maxX - 0.00000004 || s3 <= t3.bounds.minY + 0.00000004 || s3 >= t3.bounds.maxY - 0.00000004)
        return 1 / 0;
      const a4 = new Map;
      for (const { copper: t4, ratio: r5 } of d2(e37, n4)) {
        if (t4.owner === o4 || t4.immutable)
          return 1 / 0;
        a4.set(t4.owner, Math.max(a4.get(t4.owner) ?? 0, r5 * i3[t4.spanIndex]));
      }
      let c4 = 0;
      for (const e38 of a4.values())
        c4 += e38;
      return (e37.z === n4.z ? Math.hypot(e37.x - n4.x, e37.y - n4.y) : 1) * c4;
    }, p3 = new Map;
    return { getAdditionalEdgeCost: (e37, n4) => {
      if (e37.z === n4.z || t3.srj.allowBlindAndBuriedVias === true || e37.x !== n4.x || e37.y !== n4.y)
        return u2(e37, n4);
      let o5 = p3.get(e37.x);
      const i4 = o5?.get(e37.y);
      if (i4 !== undefined)
        return i4;
      const r4 = u2(e37, n4);
      return o5 || (o5 = new Map, p3.set(e37.x, o5)), o5.set(e37.y, r4), r4;
    }, query: d2 };
  }(e35), t2.getAdditionalEdgeCost(n2, o3)) };
}
function jy(e35, t2) {
  return new zy(Fy(e35), t2);
}
var $y = class extends BaseSolver {
  input;
  forward;
  reverse;
  stats = { nodesPopped: 0, completionReason: "no-path" };
  phase = "prepare-forward";
  output;
  laneErrors = [];
  originalErrors = [];
  constructor(e35) {
    if (super(), e35.reverseMaxNodes !== undefined && (!Number.isSafeInteger(e35.reverseMaxNodes) || e35.reverseMaxNodes < 1))
      throw new Error("repair04: reverse node budget must be positive");
    this.input = e35, this.forward = jy(e35.task, e35.connectivity), this.activeSubSolver = this.forward;
    const t2 = e35.task.pathInput.maxNodes ?? 30000, n2 = this.forward.MAX_ITERATIONS + Math.ceil((e35.reverseMaxNodes ?? t2) / 128) - Math.ceil(t2 / 128);
    this.MAX_ITERATIONS = this.forward.MAX_ITERATIONS + n2 + 8;
  }
  getLaneStats() {
    return [this.forward, ...this.reverse ? [this.reverse] : []].map((e35) => ({ ...e35.stats }));
  }
  getLastLaneErrors() {
    return this.laneErrors.map((e35) => e35 ? { ...e35 } : undefined);
  }
  stepLane(e35, t2) {
    try {
      e35.step();
    } catch (e36) {
      this.originalErrors[t2] = { error: e36 }, this.laneErrors[t2] = e36 instanceof Error ? { name: e36.name, message: e36.message } : { name: "Error", message: String(e36) };
    }
  }
  throwLaneError() {
    const e35 = this.originalErrors.find((e36) => e36 !== undefined);
    if (e35)
      throw e35.error;
  }
  updateStats() {
    this.stats.nodesPopped = this.forward.stats.nodesPopped + (this.reverse?.stats.nodesPopped ?? 0), this.solved || (this.progress = Math.min(0.99, this.stats.nodesPopped / ((this.input.task.pathInput.maxNodes ?? 30000) + (this.reverse ? this.input.reverseMaxNodes : 0))));
  }
  finish(e35, t2 = false) {
    this.output = t2 && e35 ? e35.slice().reverse() : e35, this.stats.completionReason = e35 ? "found" : this.getLaneStats().some((e36) => e36.completionReason === "node-limit") ? "node-limit" : "no-path", this.solved = true, this.progress = 1, this.activeSubSolver = null;
  }
  checkFailure() {
    const e35 = [this.forward, this.reverse].find((e36) => Boolean(e36?.failed));
    return !!e35 && (this.failed = true, this.error = e35.error, true);
  }
  _step() {
    if (this.laneErrors = [], this.originalErrors = [], this.phase === "prepare-forward") {
      if (this.stepLane(this.forward, 0), this.updateStats(), this.throwLaneError(), this.checkFailure())
        return;
      if (this.forward.solved)
        return void this.finish(this.forward.getOutput());
      if (!this.forward.isSearchPrepared())
        return;
      return this.input.reverseMaxNodes === undefined ? void (this.phase = "search") : void (this.phase = "search-forward");
    }
    if (this.phase === "search-forward") {
      if (this.stepLane(this.forward, 0), this.updateStats(), this.throwLaneError(), this.checkFailure())
        return;
      if (this.forward.solved)
        return void this.finish(this.forward.getOutput());
      if (this.forward.stats.nodesPopped < 1024)
        return;
      const { task: e35 } = this.input;
      return this.reverse = jy({ ...e35, pathInput: { ...e35.pathInput, start: e35.pathInput.end, end: e35.pathInput.start, existingPath: e35.pathInput.existingPath?.slice().reverse(), maxNodes: this.input.reverseMaxNodes } }, this.input.connectivity), this.activeSubSolver = this.reverse, void (this.phase = "prepare-reverse");
    }
    if (this.phase === "prepare-reverse") {
      if (this.stepLane(this.reverse, 1), this.updateStats(), this.throwLaneError(), this.checkFailure())
        return;
      return this.reverse.solved && this.reverse.getOutput() ? void this.finish(this.reverse.getOutput(), true) : void ((this.reverse.solved || this.reverse.isSearchPrepared()) && (this.phase = "search", this.activeSubSolver = this.forward));
    }
    this.forward.solved || this.forward.failed || this.stepLane(this.forward, 0), !this.reverse || this.reverse.solved || this.reverse.failed || this.stepLane(this.reverse, 1), this.updateStats(), this.throwLaneError(), this.checkFailure() || (this.forward.solved && this.forward.getOutput() ? this.finish(this.forward.getOutput()) : this.reverse?.solved && this.reverse.getOutput() ? this.finish(this.reverse.getOutput(), true) : !this.forward.solved || this.reverse && !this.reverse.solved || this.finish(null));
  }
  getOutput() {
    if (!this.solved || this.failed || this.output === undefined)
      throw new Error("repair04: paired clearance output requested too early");
    return this.output;
  }
};
function Yy({ route: e35, points: t2, mutableBounds: n2 }) {
  const o3 = { ...e35, route: t2 };
  return { ...o3, vias: Ey({ route: o3, mutableBounds: n2 }) };
}
var Xy = class extends BaseSolver {
  input;
  phase = "initialize";
  routeCursor = 0;
  copperCursor = 0;
  spanCount = 0;
  output;
  pathSolver;
  prepareRoute;
  finishSetup;
  selectSpan;
  prepareCopper;
  startPath;
  applyPath;
  updateWorkStats;
  constructor(e35) {
    super(), this.input = e35, this.stats = { pathSearchNodes: 0, pathSearchCalls: 0, unresolvedSpanCount: 0 }, this.MAX_ITERATIONS = Math.ceil(e35.maxPathSearchNodes / 128) + e35.maxPathSearchCalls * (e35.routes.reduce((e36, t2) => e36 + t2.route.length, 0) + e35.srj.obstacles.length * e35.srj.layerCount + 128) + e35.routes.length + 32;
  }
  _step() {
    if (this.phase !== "initialize") {
      if (this.phase === "spans") {
        const e35 = Math.min(this.routeCursor + 32, this.input.routes.length);
        for (;this.routeCursor < e35; this.routeCursor++)
          this.prepareRoute(this.routeCursor);
        return void (this.routeCursor === this.input.routes.length && (this.phase = "setup"));
      }
      if (this.phase !== "setup") {
        if (this.phase === "select")
          return this.selectSpan(), void this.updateWorkStats();
        if (this.phase === "coppers") {
          const e35 = Math.min(this.copperCursor + 32, this.spanCount);
          for (;this.copperCursor < e35; this.copperCursor++)
            this.prepareCopper(this.copperCursor);
          return void (this.copperCursor === this.spanCount && (this.phase = "start-path"));
        }
        if (this.phase !== "start-path") {
          if (this.phase === "path") {
            const e35 = this.pathSolver;
            if (!e35)
              throw new Error("repair04: negotiated search child is missing");
            return e35.step(), e35.failed ? (this.failed = true, this.error = e35.error) : e35.solved && (this.activeSubSolver = null, this.phase = "apply-path"), void this.updateWorkStats();
          }
          if (this.phase === "apply-path") {
            const e35 = this.pathSolver;
            if (!e35)
              throw new Error("repair04: completed negotiated search child is missing");
            return this.applyPath(e35.getOutput()), this.applyPath = undefined, void this.updateWorkStats();
          }
          throw new Error("repair04: negotiated clearance stepped after completion");
        }
        this.startPath();
      } else
        this.finishSetup();
    } else
      this.initialize();
  }
  initialize() {
    const e35 = this.input, t2 = new Ay(e35.srj);
    if (e35.searchDirectionCount !== undefined && e35.searchDirectionCount !== 1 && e35.searchDirectionCount !== 2)
      throw new Error("repair04: search direction count must be one or two");
    for (const t3 of [e35.maxPathSearchNodes, e35.maxPathSearchCalls])
      if (!Number.isSafeInteger(t3) || t3 < 0)
        throw new Error("repair04: negotiated work budgets must be nonnegative integers");
    if (e35.maxPathSearchNodesPerCall !== undefined && (!Number.isSafeInteger(e35.maxPathSearchNodesPerCall) || e35.maxPathSearchNodesPerCall < 1))
      throw new Error("repair04: per-path work budget must be a positive integer");
    if (e35.pathHeuristicWeight !== undefined && (!Number.isFinite(e35.pathHeuristicWeight) || e35.pathHeuristicWeight < 1))
      throw new Error("repair04: heuristic weight must be finite and at least one");
    if (e35.pathGridSizeScale !== undefined && (!Number.isFinite(e35.pathGridSizeScale) || e35.pathGridSizeScale <= 0))
      throw new Error("repair04: path grid scale must be positive and finite");
    if (e35.viaHoleDiameter !== undefined && (!Number.isFinite(e35.viaHoleDiameter) || e35.viaHoleDiameter <= 0 || e35.routes.some((t3) => e35.viaHoleDiameter > t3.viaDiameter)))
      throw new Error("repair04: via hole diameter must be positive and fit the copper");
    const n2 = (t3) => t3.x >= e35.bounds.minX - Aa && t3.x <= e35.bounds.maxX + Aa && t3.y >= e35.bounds.minY - Aa && t3.y <= e35.bounds.maxY + Aa, o3 = [], i3 = e35.routes.map(() => []);
    this.prepareRoute = (t3) => {
      const r3 = e35.routes[t3], s2 = r3.route, a3 = s2.flatMap((n3, o4) => {
        const i4 = s2[o4 - 1], a4 = s2[o4 + 1], c3 = n3.traceThickness ?? r3.traceThickness, l3 = i4 && (i4.traceThickness ?? r3.traceThickness) !== c3 || a4 && (a4.traceThickness ?? r3.traceThickness) !== c3, h2 = i4 && i4.z !== n3.z && (!e35.allowLayerChanges || e35.isLocked(t3, o4) || e35.isLocked(t3, o4 - 1)) || a4 && a4.z !== n3.z && (!e35.allowLayerChanges || e35.isLocked(t3, o4) || e35.isLocked(t3, o4 + 1));
        return o4 === 0 || o4 === s2.length - 1 || e35.isLocked(t3, o4) || n3.pcb_port_id || n3.toNextSegmentType || n3.insideJumperPad || l3 || h2 ? [o4] : [];
      });
      for (let c3 = 1;c3 < a3.length; c3++) {
        const l3 = s2.slice(a3[c3 - 1], a3[c3] + 1), h2 = l3[0].traceThickness ?? r3.traceThickness, d2 = l3.slice(1).every((t4, n3) => {
          const o4 = l3[n3], i4 = (o4.x + t4.x) / 2, r4 = (o4.y + t4.y) / 2;
          return i4 > e35.bounds.minX + 0.00000004 && i4 < e35.bounds.maxX - 0.00000004 && r4 > e35.bounds.minY + 0.00000004 && r4 < e35.bounds.maxY - 0.00000004;
        }), u2 = l3.slice(1).every((n3, o4) => {
          const i4 = l3[o4], r4 = a3[c3 - 1] + o4;
          return i4.z === n3.z || !e35.isLocked(t3, r4) && !e35.isLocked(t3, r4 + 1);
        }), p3 = l3.every(n2) && d2 && u2 && !r3.jumpers?.length && l3.every((e36) => !e36.toNextSegmentType && !e36.insideJumperPad && (e36.traceThickness ?? r3.traceThickness) === h2) && (e35.allowLayerChanges || l3.every((e36) => e36.z === l3[0].z));
        i3[t3].push(o3.length), o3.push({ routeIndex: t3, mutable: Boolean(p3), route: Yy({ route: { ...r3, traceThickness: h2 }, points: l3, mutableBounds: e35.bounds }) });
      }
    }, this.finishSetup = () => {
      const n3 = o3.map((e36) => e36.route), r3 = o3.filter((e36) => !e36.mutable).map((e36) => e36.route), s2 = iy(e35.srj, e35.routes), a3 = (e36) => s2.get(e36.connectionName) ?? e36.connectionName, c3 = new Set;
      for (const e36 of o3)
        for (const t3 of [e36.route.route[0], e36.route.route.at(-1)]) {
          const n4 = t3.traceThickness ?? e36.route.traceThickness, o4 = `${a3(e36.route)}|${t3.x}|${t3.y}|${t3.z}|${n4}`;
          if (c3.has(o4))
            continue;
          c3.add(o4);
          const i4 = { x: t3.x, y: t3.y, z: t3.z };
          r3.push({ ...e36.route, traceThickness: n4, route: [i4, i4], vias: [] });
        }
      const l3 = o3.map(({ route: e36 }) => {
        let t3 = 0;
        for (let n4 = 1;n4 < e36.route.length; n4++) {
          const o4 = e36.route[n4 - 1], i4 = e36.route[n4];
          t3 += o4.z === i4.z ? Math.hypot(o4.x - i4.x, o4.y - i4.y) : 1;
        }
        return t3;
      }), h2 = new Set, d2 = new Set(e35.dirtyRouteIndices), u2 = [], p3 = new Set, m2 = (e36) => {
        p3.has(e36) || h2.has(e36) || !o3[e36].mutable || (p3.add(e36), u2.push(e36));
      };
      o3.forEach((e36, t3) => {
        d2.has(e36.routeIndex) && m2(t3);
      });
      let g2 = 0, f2 = 0, _2 = 0;
      this.spanCount = o3.length, this.updateWorkStats = () => {
        this.stats = { pathSearchNodes: g2 + (this.pathSolver?.stats.nodesPopped ?? 0), pathSearchCalls: f2, unresolvedSpanCount: p3.size + h2.size }, this.progress = this.solved ? 1 : Math.min(0.99, Math.max(this.stats.pathSearchNodes / Math.max(1, e35.maxPathSearchNodes), f2 / Math.max(1, e35.maxPathSearchCalls)));
      }, this.selectSpan = () => {
        if (!(_2 < u2.length && g2 < e35.maxPathSearchNodes && f2 < e35.maxPathSearchCalls))
          return this.output = { routes: e35.routes.map((t3, o4) => {
            if (!i3[o4].length)
              return t3;
            return Yy({ route: t3, points: i3[o4].flatMap((e36, t4) => t4 === 0 ? n3[e36].route : n3[e36].route.slice(1)), mutableBounds: e35.bounds });
          }), pathSearchNodes: g2, pathSearchCalls: f2, unresolvedSpanCount: p3.size + h2.size }, this.solved = true, void (this.phase = "finished");
        const s3 = u2[_2++];
        p3.delete(s3);
        const c4 = n3[s3], d3 = a3(c4), y2 = [];
        this.copperCursor = 0, this.prepareCopper = (t3) => {
          if (t3 === s3)
            return;
          const i4 = n3[t3], r4 = a3(i4);
          for (let n4 = 1;n4 < i4.route.length; n4++) {
            const s4 = i4.route[n4 - 1], a4 = i4.route[n4];
            if (s4.toNextSegmentType === "through_obstacle")
              continue;
            const c5 = !o3[t3].mutable || h2.has(t3);
            if (s4.z === a4.z && (r4 === d3 || c5))
              continue;
            const l4 = (s4.z !== a4.z ? i4.viaDiameter : Math.max(s4.traceThickness ?? i4.traceThickness, a4.traceThickness ?? i4.traceThickness)) / 2, u3 = { a: s4, b: a4, radius: l4, minX: Math.min(s4.x, a4.x), maxX: Math.max(s4.x, a4.x), minY: Math.min(s4.y, a4.y), maxY: Math.max(s4.y, a4.y), ...Na(e35.srj, s4, a4), spanIndex: t3, owner: r4, index: y2.length, cellX: Math.floor(Math.min(s4.x, a4.x) - l4), cellY: Math.floor(Math.min(s4.y, a4.y) - l4), immutable: c5, visitedQuery: 0 };
            y2.push(u3);
          }
        }, this.startPath = () => {
          const o4 = (e36) => {
            if (!e36.length)
              return;
            const t3 = new uy(e36.length);
            for (const n4 of e36)
              t3.add(n4.minX - n4.radius - Aa, n4.minY - n4.radius - Aa, n4.maxX + n4.radius + Aa, n4.maxY + n4.radius + Aa);
            return t3.finish(), { index: t3, copper: e36, cellCandidates: new Map };
          }, i4 = o4(y2), a4 = new Map;
          for (let t3 = 0;t3 < e35.srj.layerCount; t3++)
            a4.set(t3, o4(y2.filter((e36) => e36.minZ <= t3 && e36.maxZ >= t3)));
          const u3 = [];
          let p4 = 0;
          const _3 = (t3, n4) => {
            const o5 = t3.z !== n4.z, r4 = Math.min(t3.x, n4.x), s4 = Math.max(t3.x, n4.x), l4 = Math.min(t3.y, n4.y), h3 = Math.max(t3.y, n4.y), m3 = (o5 ? c4.viaDiameter : c4.traceThickness) / 2 + Math.max(e35.traceClearance, e35.viaClearance), g3 = [], f3 = Na(e35.srj, t3, n4), _4 = o5 ? i4 : a4.get(t3.z), y3 = r4 - m3 - Aa, b3 = l4 - m3 - Aa, x3 = s4 + m3 + Aa, v3 = h3 + m3 + Aa, I3 = Math.floor(y3), S3 = Math.floor(x3), C2 = Math.floor(b3), P = Math.floor(v3), M = ++p4;
            let w;
            if (_4 && (S3 - I3 + 1) * (P - C2 + 1) <= 16 && Number.isSafeInteger(I3) && Number.isSafeInteger(S3) && Number.isSafeInteger(C2) && Number.isSafeInteger(P)) {
              u3.length = 0;
              for (let e36 = I3;e36 <= S3; e36++) {
                let t4 = _4.cellCandidates.get(e36);
                t4 || (t4 = new Map, _4.cellCandidates.set(e36, t4));
                for (let n5 = C2;n5 <= P; n5++) {
                  let o6 = t4.get(n5);
                  o6 || (o6 = _4.index.search(e36, n5, e36 + 1, n5 + 1), t4.set(n5, o6));
                  for (const e37 of o6) {
                    const t5 = _4.copper[e37];
                    t5.visitedQuery !== M && (t5.visitedQuery = M, x3 < t5.minX - t5.radius - Aa || v3 < t5.minY - t5.radius - Aa || y3 > t5.maxX + t5.radius + Aa || b3 > t5.maxY + t5.radius + Aa || u3.push(e37));
                  }
                }
              }
              w = u3;
            } else
              w = _4?.index.search(y3, b3, x3, v3) ?? [];
            for (const i5 of w) {
              const a5 = _4.copper[i5], u4 = o5 && a5.minZ !== a5.maxZ, p5 = a5.minZ <= f3.maxZ && a5.maxZ >= f3.minZ;
              if (!p5 && !u4)
                continue;
              if (a5.immutable && !u4)
                continue;
              if (a5.owner === d3 && (!u4 || t3.x === a5.a.x && t3.y === a5.a.y))
                continue;
              const m4 = (o5 ? c4.viaDiameter : c4.traceThickness) / 2 + (u4 ? e35.viaClearance : e35.traceClearance) + a5.radius, y4 = (e35.viaHoleDiameter ?? c4.viaDiameter) / 2 + (e35.viaHoleDiameter ?? 2 * a5.radius) / 2 + e35.viaClearance, b4 = u4 ? p5 && a5.owner !== d3 ? Math.max(m4, y4) : y4 : m4;
              if (r4 - b4 - Aa > a5.maxX || s4 + b4 + Aa < a5.minX || l4 - b4 - Aa > a5.maxY || h3 + b4 + Aa < a5.minY)
                continue;
              const x4 = Ly(t3, n4, a5.a, a5.b);
              x4 < b4 - Aa && g3.push({ copper: a5, ratio: (b4 - x4) / (b4 * b4) });
            }
            const N = Math.floor(r4 - m3), R2 = Math.floor(l4 - m3);
            return g3.sort((e36, t4) => {
              const n5 = Math.max(N, e36.copper.cellX) - Math.max(N, t4.copper.cellX);
              if (n5 !== 0)
                return n5;
              return Math.max(R2, e36.copper.cellY) - Math.max(R2, t4.copper.cellY) || e36.copper.index - t4.copper.index;
            }), g3;
          }, b2 = (t3, n4) => {
            const o5 = (t3.x + n4.x) / 2, i5 = (t3.y + n4.y) / 2;
            if (o5 <= e35.bounds.minX + 0.00000004 || o5 >= e35.bounds.maxX - 0.00000004 || i5 <= e35.bounds.minY + 0.00000004 || i5 >= e35.bounds.maxY - 0.00000004)
              return 1 / 0;
            const r4 = new Map;
            for (const { copper: e36, ratio: o6 } of _3(t3, n4)) {
              if (e36.owner === d3 || e36.immutable)
                return 1 / 0;
              r4.set(e36.owner, Math.max(r4.get(e36.owner) ?? 0, o6 * l3[e36.spanIndex]));
            }
            let s4 = 0;
            for (const e36 of r4.values())
              s4 += e36;
            return (t3.z === n4.z ? Math.hypot(t3.x - n4.x, t3.y - n4.y) : 1) * s4;
          }, x2 = new Map, v2 = { nodesPopped: 0, completionReason: "no-path" }, I2 = { srj: e35.srj, routes: [...r3, c4], routeIndex: r3.length, start: c4.route[0], end: c4.route.at(-1), bounds: e35.bounds, traceThickness: c4.traceThickness, traceClearance: e35.traceClearance, viaClearance: e35.viaClearance, gridSize: Math.min(0.1, c4.traceThickness * (e35.pathGridSizeScale ?? 1) / 2), allowLayerChanges: e35.allowLayerChanges, maxNodes: Math.min(e35.maxPathSearchNodesPerCall ?? e35.maxPathSearchNodes, e35.maxPathSearchNodes - g2), heuristicWeight: e35.pathHeuristicWeight, existingPath: c4.route, viaHoleDiameter: e35.viaHoleDiameter }, S2 = Math.min(e35.maxPathSearchNodesPerCall ?? e35.maxPathSearchNodes, e35.maxPathSearchNodes - g2 - I2.maxNodes), C = e35.searchDirectionCount === 2 ? new $y({ task: { pathInput: I2, coppers: y2, selectedOwner: d3, weights: l3 }, connectivity: t2, reverseMaxNodes: e35.maxPathSearchCalls - f2 >= 2 && S2 > 0 ? S2 : undefined }) : new zy({ ...I2, stats: v2, getAdditionalEdgeCost: (t3, n4) => {
            if (t3.z === n4.z || e35.srj.allowBlindAndBuriedVias === true || t3.x !== n4.x || t3.y !== n4.y)
              return b2(t3, n4);
            let o5 = x2.get(t3.x);
            const i5 = o5?.get(t3.y);
            if (i5 !== undefined)
              return i5;
            const r4 = b2(t3, n4);
            return o5 || (o5 = new Map, x2.set(t3.x, o5)), o5.set(t3.y, r4), r4;
          } }, t2);
          this.pathSolver = C, this.activeSubSolver = C, this.MAX_ITERATIONS = Math.max(this.MAX_ITERATIONS, this.iterations + C.MAX_ITERATIONS + 3), this.phase = "path", this.applyPath = (t3) => {
            const o5 = C instanceof $y ? C.getLaneStats() : [v2];
            f2 += o5.length;
            for (const t4 of o5)
              g2 += t4.nodesPopped, e35.onSearch?.(t4);
            if (!t3)
              return h2.add(s3), r3.push(c4), this.phase = "select", void (this.pathSolver = undefined);
            n3[s3] = Yy({ route: c4, points: t3, mutableBounds: e35.bounds });
            const i5 = new Set;
            for (let e36 = 1;e36 < t3.length; e36++)
              for (const { copper: n4 } of _3(t3[e36 - 1], t3[e36]))
                i5.add(n4.spanIndex);
            for (const e36 of [...i5].sort((e37, t4) => e37 - t4))
              l3[e36]++, m2(e36);
            i5.size && (l3[s3]++, m2(s3)), this.phase = "select", this.pathSolver = undefined;
          };
        }, this.phase = "coppers";
      }, this.phase = "select", this.updateWorkStats();
    }, this.phase = "spans";
  }
  getOutput() {
    if (!this.solved || this.failed || !this.output)
      throw new Error("repair04: negotiated clearance output requested before completion");
    return this.output;
  }
  getResult() {
    return this.getOutput();
  }
};
var Vy = 256;
var Wy = 0.25;
function Gy(e35, t2, n2, o3) {
  const i3 = t2.x - e35.x, r3 = t2.y - e35.y, s2 = o3.x - n2.x, a3 = o3.y - n2.y, c3 = e35.x - n2.x, l3 = e35.y - n2.y, h2 = i3 * i3 + r3 * r3, d2 = i3 * s2 + r3 * a3, u2 = s2 * s2 + a3 * a3, p3 = i3 * c3 + r3 * l3, m2 = s2 * c3 + a3 * l3, g2 = h2 * u2 - d2 * d2;
  let f2 = g2 > 0.000000000000001 ? Math.max(0, Math.min(1, (d2 * m2 - u2 * p3) / g2)) : 0;
  u2 < 0.000000000000001 && (f2 = h2 > 0.000000000000001 ? Math.max(0, Math.min(1, -p3 / h2)) : 0);
  let _2 = u2 > 0.000000000000001 ? (d2 * f2 + m2) / u2 : 0;
  _2 < 0 ? (_2 = 0, f2 = h2 > 0.000000000000001 ? Math.max(0, Math.min(1, -p3 / h2)) : 0) : _2 > 1 && (_2 = 1, f2 = h2 > 0.000000000000001 ? Math.max(0, Math.min(1, (d2 - p3) / h2)) : 0);
  const y2 = e35.x + f2 * i3 - n2.x - _2 * s2, b2 = e35.y + f2 * r3 - n2.y - _2 * a3;
  return { s: f2, t: _2, x: y2, y: b2, distance: Ry(y2, b2) };
}
function Uy(e35, t2) {
  let n2 = { x: 0, y: 0, depth: 1 / 0 };
  for (let o3 = 0;o3 < t2.length; o3++) {
    const i3 = t2[o3], r3 = t2[(o3 + 1) % t2.length], s2 = r3.x - i3.x, a3 = r3.y - i3.y, c3 = Ry(s2, a3), l3 = a3 / c3, h2 = -s2 / c3, d2 = -((e35.x - i3.x) * l3 + (e35.y - i3.y) * h2);
    if (d2 < 0)
      return null;
    d2 < n2.depth && (n2 = { x: l3, y: h2, depth: d2 });
  }
  return n2;
}
var Zy = class extends BaseSolver {
  input;
  phase = "geometry";
  routes = [];
  nets = new Map;
  vertices = new Map;
  segments = [];
  pairs = [];
  padContacts = [];
  viaPadConstraints = new Map;
  traceClearance = 0.1;
  viaClearance = 0.1;
  pairOuterIndex = 0;
  pairInnerIndex = 1;
  obstacleIndex = 0;
  sweepIndex = 0;
  sweepPairIndex = 0;
  sweepPadIndex = 0;
  preparedPairCount = 0;
  projectedConstraintCount = 0;
  constructor(e35) {
    super(), this.input = e35, this.MAX_ITERATIONS = 1024;
  }
  prepareGeometry() {
    const e35 = this.input, t2 = structuredClone(e35.routes), n2 = iy(e35.srj, t2), o3 = e35.traceClearance ?? 0.1, i3 = e35.viaClearance ?? 0.1, r3 = { minX: e35.bounds.minX + e35.boundaryMargin, maxX: e35.bounds.maxX - e35.boundaryMargin, minY: e35.bounds.minY + e35.boundaryMargin, maxY: e35.bounds.maxY - e35.boundaryMargin }, s2 = yy(e35.srj, t2, e35.bounds), a3 = new Map, c3 = t2.map((t3, o4) => t3.route.map((i4, c4) => {
      const l4 = `${n2.get(t3.connectionName)}:${i4.x}:${i4.y}`;
      let h3 = a3.get(l4);
      return h3 || (h3 = { x: i4.x, y: i4.y, original: { x: i4.x, y: i4.y }, locked: false, radius: 0, revision: 0, bounds: r3, points: [] }, a3.set(l4, h3)), h3.points.push(i4), h3.locked ||= Boolean(e35.lockedPointIndices[o4][c4] || s2[o4].segmentTimes.has(c4) || s2[o4].segmentTimes.has(c4 - 1) || s2[o4].viaPositions.some((e36) => Math.hypot(e36.x - i4.x, e36.y - i4.y) <= Aa) || c4 === 0 || c4 === t3.route.length - 1 || i4.pcb_port_id || i4.insideJumperPad || i4.toNextSegmentType || i4.x <= r3.minX || i4.x >= r3.maxX || i4.y <= r3.minY || i4.y >= r3.maxY), h3;
    })), l3 = [];
    for (let o4 = 0;o4 < t2.length; o4++) {
      const i4 = t2[o4];
      for (let t3 = 1;t3 < i4.route.length; t3++) {
        const r4 = i4.route[t3 - 1], s3 = i4.route[t3];
        if (r4.toNextSegmentType || r4.insideJumperPad || s3.insideJumperPad)
          continue;
        const a4 = c3[o4][t3 - 1], h3 = c3[o4][t3], d3 = r4.z !== s3.z;
        d3 && e35.allowViaMovement !== true && (a4.locked = h3.locked = true), l3.push({ a: a4, b: h3, initialBounds: { minX: Math.min(a4.x, h3.x), maxX: Math.max(a4.x, h3.x), minY: Math.min(a4.y, h3.y), maxY: Math.max(a4.y, h3.y) }, ...Na(e35.srj, r4, s3), radius: d3 ? i4.viaDiameter / 2 : Math.max(r4.traceThickness ?? i4.traceThickness, s3.traceThickness ?? i4.traceThickness) / 2, net: n2.get(i4.connectionName), routeIndex: o4, via: d3 });
      }
    }
    for (const e36 of l3)
      e36.a.radius = Math.max(e36.a.radius, e36.radius), e36.b.radius = Math.max(e36.b.radius, e36.radius);
    if (e35.boardEdgeClearance !== undefined) {
      const t3 = e35.srj.bounds;
      for (const n3 of a3.values()) {
        const o4 = n3.radius + e35.boardEdgeClearance;
        n3.bounds = { minX: Math.max(r3.minX, Math.min(n3.original.x, t3.minX + o4)), maxX: Math.min(r3.maxX, Math.max(n3.original.x, t3.maxX - o4)), minY: Math.max(r3.minY, Math.min(n3.original.y, t3.minY + o4)), maxY: Math.min(r3.maxY, Math.max(n3.original.y, t3.maxY - o4)) };
      }
    }
    this.routes = t2, this.nets = n2, this.vertices = a3, this.segments = l3, this.traceClearance = o3, this.viaClearance = i3;
    const h2 = l3.length * (l3.length - 1) / 2, d2 = l3.length * e35.srj.obstacles.length;
    this.MAX_ITERATIONS = this.iterations + Math.ceil(h2 / 4096) + Math.ceil(e35.srj.obstacles.length / 16) + Vy * Math.max(1, Math.ceil((h2 + d2) / 4096)) + 4, this.phase = "pairs";
  }
  preparePairs() {
    let e35 = 0;
    for (;e35 < 4096 && this.pairOuterIndex < this.segments.length; ) {
      if (this.pairInnerIndex >= this.segments.length) {
        this.pairOuterIndex++, this.pairInnerIndex = this.pairOuterIndex + 1;
        continue;
      }
      const t2 = this.segments[this.pairOuterIndex], n2 = this.segments[this.pairInnerIndex++];
      if (e35++, this.preparedPairCount++, t2.net === n2.net || t2.maxZ < n2.minZ || n2.maxZ < t2.minZ)
        continue;
      const o3 = t2.radius + n2.radius + Math.max(this.traceClearance, this.viaClearance) + 2 * Math.SQRT2 * Wy;
      Ty(t2.initialBounds, n2.initialBounds, o3) || Ly(t2.a, t2.b, n2.a, n2.b) <= o3 && this.pairs.push({ a: t2, b: n2, revisions: [-1, -1, -1, -1], contact: null });
    }
    this.pairOuterIndex >= this.segments.length && (this.phase = "obstacles"), this.stats = { ...this.stats, preparedPairCount: this.preparedPairCount, pairCount: this.pairs.length, lastPreparedPairBatchCount: e35 };
  }
  prepareObstacles() {
    const { input: e35, nets: t2, segments: n2, traceClearance: o3, viaClearance: i3, padContacts: r3, viaPadConstraints: s2 } = this;
    let a3 = 0;
    for (;a3 < 16 && this.obstacleIndex < e35.srj.obstacles.length; ) {
      const c3 = e35.srj.obstacles[this.obstacleIndex++];
      a3++;
      const l3 = (c3.ccwRotationDegrees ?? 0) * Math.PI / 180, h2 = Math.cos(l3), d2 = Math.sin(l3), u2 = new Set(c3.connectedTo.map((e36) => t2.get(e36) ?? e36)), p3 = c3.__zLayers ?? c3.zLayers ?? c3.layers.map((t3) => t3 === "top" ? 0 : t3 === "bottom" ? e35.srj.layerCount - 1 : Number(t3.slice(5))), m2 = [[-1, -1], [1, -1], [1, 1], [-1, 1]].map(([e36, t3]) => ({ x: c3.center.x + h2 * e36 * c3.width / 2 - d2 * t3 * c3.height / 2, y: c3.center.y + d2 * e36 * c3.width / 2 + h2 * t3 * c3.height / 2 })), g2 = { minX: Math.min(...m2.map((e36) => e36.x)), maxX: Math.max(...m2.map((e36) => e36.x)), minY: Math.min(...m2.map((e36) => e36.y)), maxY: Math.max(...m2.map((e36) => e36.y)) };
      for (const t3 of n2) {
        if (!t3.via && u2.has(t3.net) || !p3.some((e36) => e36 >= t3.minZ && e36 <= t3.maxZ))
          continue;
        const n3 = t3.radius + Math.max(o3, i3, e35.srj.defaultObstacleMargin ?? 0, e35.srj.minTraceToPadEdgeClearance ?? 0, e35.srj.minTraceToHoleEdgeClearance ?? 0, e35.srj.minViaEdgeToPadEdgeClearance ?? 0) + Math.SQRT2 * Wy;
        if (Ty(t3.initialBounds, g2, n3))
          continue;
        if (Math.min(...m2.map((e36, n4) => Ly(t3.a, t3.b, e36, m2[(n4 + 1) % 4]))) > n3)
          continue;
        const a4 = t3.radius + (t3.via ? Ea(e35.srj, i3, u2.has(t3.net)) : c3.isNonPlatedHole && e35.srj.minTraceToHoleEdgeClearance !== undefined ? e35.srj.minTraceToHoleEdgeClearance : Math.max(o3, e35.srj.defaultObstacleMargin ?? 0, e35.srj.minTraceToPadEdgeClearance ?? 0));
        if (r3.push({ segment: t3, corners: m2, bounds: g2, required: a4, revisions: [-1, -1], projectionRevisions: [-1, -1], contact: null }), t3.via) {
          const e36 = { center: c3.center, cosine: h2, sine: d2, shape: ny(c3), clearance: a4 }, n4 = t3.a.original.x - c3.center.x, o4 = t3.a.original.y - c3.center.y, i4 = { x: n4 * h2 + o4 * d2, y: -n4 * d2 + o4 * h2 };
          e36.clearance = Math.min(e36.clearance, oy(i4, i4, e36.shape));
          for (const n5 of new Set([t3.a, t3.b])) {
            const t4 = s2.get(n5);
            t4 ? t4.push(e36) : s2.set(n5, [e36]);
          }
        }
      }
    }
    this.stats = { ...this.stats, preparedObstacleCount: this.obstacleIndex, padContactCount: this.padContacts.length, lastPreparedObstacleBatchCount: a3 }, this.obstacleIndex === e35.srj.obstacles.length && (this.MAX_ITERATIONS = this.iterations + Vy * Math.max(1, Math.ceil((this.pairs.length + this.padContacts.length) / 4096)) + 2, this.phase = "sweeps");
  }
  project(e35, t2, n2, o3, i3) {
    const r3 = this.viaPadConstraints, s2 = [], a3 = [];
    for (const [t3, n3] of e35) {
      if (t3.locked)
        continue;
      const e36 = s2.indexOf(t3);
      e36 === -1 ? (s2.push(t3), a3.push(0 + n3)) : a3[e36] = a3[e36] + n3;
    }
    let c3 = 0;
    for (const e36 of a3)
      c3 += e36 * e36;
    if (c3 < 0.000000000000001)
      return;
    const l3 = Math.min(0.05, 0.7 * o3) / c3;
    for (let e36 = 0;e36 < s2.length; e36++) {
      const o4 = s2[e36], c4 = a3[e36];
      let h2 = Math.max(o4.bounds.minX, o4.original.x - Wy, Math.min(o4.bounds.maxX, o4.original.x + Wy, o4.x + t2 * l3 * c4)), d2 = Math.max(o4.bounds.minY, o4.original.y - Wy, Math.min(o4.bounds.maxY, o4.original.y + Wy, o4.y + n2 * l3 * c4));
      const u2 = r3.get(o4);
      if (u2?.some((e37) => this.getViaPadDistance({ x: h2, y: d2 }, e37) < e37.clearance)) {
        if (!i3)
          continue;
        const e37 = this.constrainViaDisplacement(o4, { x: h2, y: d2 }, u2);
        h2 = e37.x, d2 = e37.y;
      }
      u2?.some((e37) => this.getViaPadDistance({ x: h2, y: d2 }, e37) < e37.clearance) || (o4.x === h2 && o4.y === d2 || o4.revision++, o4.x = h2, o4.y = d2);
    }
  }
  getViaPadDistance(e35, t2) {
    const n2 = e35.x - t2.center.x, o3 = e35.y - t2.center.y, i3 = { x: n2 * t2.cosine + o3 * t2.sine, y: -n2 * t2.sine + o3 * t2.cosine };
    return oy(i3, i3, t2.shape);
  }
  constrainViaDisplacement(e35, t2, n2) {
    const o3 = t2.x - e35.x, i3 = t2.y - e35.y, r3 = [];
    for (const o4 of n2) {
      if (this.getViaPadDistance(t2, o4) >= o4.clearance)
        continue;
      const n3 = e35.x - o4.center.x, i4 = e35.y - o4.center.y, s3 = { x: n3 * o4.cosine + i4 * o4.sine, y: -n3 * o4.sine + i4 * o4.cosine };
      let a4;
      if (o4.shape.type === "rect") {
        const e36 = o4.shape.bounds;
        a4 = { x: Math.max(e36.minX, Math.min(e36.maxX, s3.x)), y: Math.max(e36.minY, Math.min(e36.maxY, s3.y)) };
      } else {
        const { a: e36, b: t3 } = o4.shape, n4 = t3.x - e36.x, i5 = t3.y - e36.y, r4 = n4 * n4 + i5 * i5, c4 = r4 > 0 ? Math.max(0, Math.min(1, ((s3.x - e36.x) * n4 + (s3.y - e36.y) * i5) / r4)) : 0;
        a4 = { x: e36.x + c4 * n4, y: e36.y + c4 * i5 };
      }
      const c3 = s3.x - a4.x, l3 = s3.y - a4.y, h2 = { x: c3 * o4.cosine - l3 * o4.sine, y: c3 * o4.sine + l3 * o4.cosine };
      h2.x * h2.x + h2.y * h2.y > 0.00000000000000000001 && r3.push(h2);
    }
    let s2 = { x: 0, y: 0 }, a3 = o3 * o3 + i3 * i3;
    for (const t3 of r3) {
      const n3 = o3 * t3.x + i3 * t3.y, c3 = t3.x * t3.x + t3.y * t3.y, l3 = this.shortenDisplacement(e35, { x: o3 - t3.x * n3 / c3, y: i3 - t3.y * n3 / c3 });
      if (r3.some((e36) => l3.x * e36.x + l3.y * e36.y < -0.000000000000001))
        continue;
      const h2 = (l3.x - o3) ** 2 + (l3.y - i3) ** 2;
      h2 < a3 && (s2 = l3, a3 = h2);
    }
    return this.compensateTangentRounding(e35, s2, n2, r3);
  }
  shortenDisplacement(e35, t2) {
    const n2 = Math.max(e35.bounds.minX, e35.original.x - Wy), o3 = Math.min(e35.bounds.maxX, e35.original.x + Wy), i3 = Math.max(e35.bounds.minY, e35.original.y - Wy), r3 = Math.min(e35.bounds.maxY, e35.original.y + Wy);
    let s2 = 1;
    return t2.x > 0 && (s2 = Math.min(s2, (o3 - e35.x) / t2.x)), t2.x < 0 && (s2 = Math.min(s2, (n2 - e35.x) / t2.x)), t2.y > 0 && (s2 = Math.min(s2, (r3 - e35.y) / t2.y)), t2.y < 0 && (s2 = Math.min(s2, (i3 - e35.y) / t2.y)), { x: Math.max(n2, Math.min(o3, e35.x + t2.x * s2)) - e35.x, y: Math.max(i3, Math.min(r3, e35.y + t2.y * s2)) - e35.y };
  }
  compensateTangentRounding(e35, t2, n2, o3) {
    const i3 = { x: e35.x + t2.x, y: e35.y + t2.y }, r3 = n2.reduce((e36, t3) => Math.max(e36, Math.abs(t3.center.x), Math.abs(t3.center.y), t3.clearance), Math.max(1, Math.abs(e35.x), Math.abs(e35.y), Math.abs(i3.x), Math.abs(i3.y))), s2 = 32 * Number.EPSILON * r3, a3 = n2.map((e36) => this.getViaPadDistance(i3, e36));
    if (a3.every((e36, t3) => e36 >= n2[t3].clearance) || a3.some((e36, t3) => e36 < n2[t3].clearance - s2))
      return i3;
    const c3 = o3.map((e36) => {
      const t3 = Math.hypot(e36.x, e36.y);
      return { x: e36.x / t3, y: e36.y / t3 };
    }), l3 = { x: 0, y: 0 };
    for (const e36 of c3)
      for (const t3 of [e36, { x: -e36.y, y: e36.x }, { x: e36.y, y: -e36.x }])
        c3.some((e37) => t3.x * e37.x + t3.y * e37.y < -0.000000000000001) || (l3.x += t3.x, l3.y += t3.y);
    const h2 = Math.hypot(l3.x, l3.y);
    if (h2 < 0.000000000000001)
      return i3;
    const d2 = this.shortenDisplacement(e35, { x: t2.x + l3.x * s2 / h2, y: t2.y + l3.y * s2 / h2 }), u2 = { x: e35.x + d2.x, y: e35.y + d2.y };
    return n2.every((e36) => this.getViaPadDistance(u2, e36) >= e36.clearance) ? u2 : i3;
  }
  projectPair(e35) {
    const { a: t2, b: n2, revisions: o3 } = e35;
    if (t2.a.locked && t2.b.locked && n2.a.locked && n2.b.locked)
      return;
    if (t2.a.revision === o3[0] && t2.b.revision === o3[1] && n2.a.revision === o3[2] && n2.b.revision === o3[3])
      return;
    o3[0] = t2.a.revision, o3[1] = t2.b.revision, o3[2] = n2.a.revision, o3[3] = n2.b.revision;
    const i3 = t2.radius + n2.radius + (t2.via && n2.via ? this.viaClearance : this.traceClearance);
    if (Ty({ minX: Math.min(t2.a.x, t2.b.x), maxX: Math.max(t2.a.x, t2.b.x), minY: Math.min(t2.a.y, t2.b.y), maxY: Math.max(t2.a.y, t2.b.y) }, { minX: Math.min(n2.a.x, n2.b.x), maxX: Math.max(n2.a.x, n2.b.x), minY: Math.min(n2.a.y, n2.b.y), maxY: Math.max(n2.a.y, n2.b.y) }, i3))
      return void (e35.contact = null);
    const r3 = e35.contact = Gy(t2.a, t2.b, n2.a, n2.b);
    r3.distance >= i3 || r3.distance < 0.0000000001 || this.project([[t2.a, 1 - r3.s], [t2.b, r3.s], [n2.a, r3.t - 1], [n2.b, -r3.t]], r3.x / r3.distance, r3.y / r3.distance, i3 - r3.distance, t2.via && n2.via);
  }
  projectPad(e35) {
    const { segment: t2, corners: n2, required: o3 } = e35;
    if (t2.a.locked && t2.b.locked)
      return;
    if (t2.a.revision === e35.projectionRevisions[0] && t2.b.revision === e35.projectionRevisions[1])
      return;
    e35.projectionRevisions[0] = t2.a.revision, e35.projectionRevisions[1] = t2.b.revision;
    if (Ty({ minX: Math.min(t2.a.x, t2.b.x), maxX: Math.max(t2.a.x, t2.b.x), minY: Math.min(t2.a.y, t2.b.y), maxY: Math.max(t2.a.y, t2.b.y) }, e35.bounds, o3))
      return;
    const i3 = t2.a === t2.b ? 1 : 2;
    for (let e36 = 0;e36 < i3; e36++) {
      const i4 = e36 === 0 ? t2.a : t2.b, r4 = Uy(i4, n2);
      r4 && this.project([[i4, 1]], r4.x, r4.y, o3 + r4.depth, false);
    }
    if (t2.a.revision !== e35.revisions[0] || t2.b.revision !== e35.revisions[1]) {
      let o4 = Gy(t2.a, t2.b, n2[0], n2[1]);
      for (let e36 = 1;e36 < n2.length; e36++) {
        const i4 = Gy(t2.a, t2.b, n2[e36], n2[(e36 + 1) % n2.length]);
        o4 = o4.distance < i4.distance ? o4 : i4;
      }
      e35.contact = o4, e35.revisions[0] = t2.a.revision, e35.revisions[1] = t2.b.revision;
    }
    const r3 = e35.contact;
    r3.distance < 0.0000000001 || r3.distance >= o3 || this.project([[t2.a, 1 - r3.s], [t2.b, r3.s]], r3.x / r3.distance, r3.y / r3.distance, o3 - r3.distance, false);
  }
  stepSweep() {
    let e35 = 0;
    for (;e35 < 4096 && this.sweepPairIndex < this.pairs.length; )
      this.projectPair(this.pairs[this.sweepPairIndex++]), e35++;
    for (;e35 < 4096 && this.sweepPairIndex === this.pairs.length && this.sweepPadIndex < this.padContacts.length; )
      this.projectPad(this.padContacts[this.sweepPadIndex++]), e35++;
    this.projectedConstraintCount += e35, this.sweepPairIndex === this.pairs.length && this.sweepPadIndex === this.padContacts.length && (this.sweepIndex++, this.sweepPairIndex = 0, this.sweepPadIndex = 0, this.sweepIndex === Vy && (this.phase = "finalize")), this.progress = this.sweepIndex / 257, this.stats = { ...this.stats, sweepCount: this.sweepIndex, projectedConstraintCount: this.projectedConstraintCount, lastProjectedConstraintBatchCount: e35 };
  }
  finalizeRoutes() {
    const { vertices: e35, routes: t2 } = this;
    for (const t3 of e35.values())
      for (const e36 of t3.points)
        e36.x = t3.x, e36.y = t3.y;
    for (const e36 of t2) {
      e36.vias = [];
      for (let t3 = 1;t3 < e36.route.length; t3++) {
        const n2 = e36.route[t3 - 1], o3 = e36.route[t3];
        n2.z === o3.z || n2.toNextSegmentType === "through_obstacle" || e36.vias.some((e37) => e37.x === o3.x && e37.y === o3.y) || e36.vias.push({ x: o3.x, y: o3.y });
      }
    }
    this.solved = true, this.progress = 1;
  }
  _step() {
    switch (this.phase) {
      case "geometry":
        return this.prepareGeometry();
      case "pairs":
        return this.preparePairs();
      case "obstacles":
        return this.prepareObstacles();
      case "sweeps":
        return this.stepSweep();
      case "finalize":
        return this.finalizeRoutes();
    }
  }
  getOutput() {
    if (!this.solved || this.failed)
      throw new Error("Trace clearance projection is not complete");
    return this.routes;
  }
  getResult() {
    return this.getOutput();
  }
};
var qy = (e35) => {
  const t2 = Qo(e35), n2 = e35.filter((e36) => e36.type === "pcb_via" && typeof e36.pcb_trace_id == "string").map((e36) => [e36.pcb_via_id, e36.pcb_trace_id]);
  return t2.addConnections(n2), t2;
};
var Qy = (e35, t2) => e35 === 0 ? "top" : e35 === t2 - 1 ? "bottom" : `inner${e35}`;
var Ky = (e35, t2) => {
  if (e35.layers !== undefined)
    return e35.layers;
  if (!Number.isInteger(t2) || t2 < 1)
    throw new Error(`Invalid board layer count: ${t2}`);
  const n2 = Array.from({ length: t2 }, (e36, n3) => Qy(n3, t2)), o3 = n2.findIndex((t3) => t3 === e35.from_layer), i3 = n2.findIndex((t3) => t3 === e35.to_layer);
  if (o3 < 0 || i3 < 0)
    throw new Error(`Via span ${e35.from_layer} -> ${e35.to_layer} is outside the board`);
  return n2.slice(Math.min(o3, i3), Math.max(o3, i3) + 1);
};
var eb = ({ via: e35, layerCount: t2, allowBlindAndBuriedVias: n2 = false }) => {
  const o3 = n2 ? e35 : { from_layer: "top", to_layer: Qy(t2 - 1, t2) };
  return Ky(o3, t2);
};
var tb = 0.005;
var nb = 0.000001;
var ob = (e35, t2) => ({ minX: e35.minX - t2, minY: e35.minY - t2, maxX: e35.maxX + t2, maxY: e35.maxY + t2 });
var ib = (e35) => ob({ minX: Math.min(e35.start.x, e35.end.x), minY: Math.min(e35.start.y, e35.end.y), maxX: Math.max(e35.start.x, e35.end.x), maxY: Math.max(e35.start.y, e35.end.y) }, e35.width / 2);
var rb = (e35) => {
  const t2 = e35.diameter / 2;
  return { minX: e35.x - t2, minY: e35.y - t2, maxX: e35.x + t2, maxY: e35.y + t2 };
};
var sb = (e35) => {
  return ((e36) => {
    if (e36.length === 0)
      return null;
    let t3 = e36[0].x, n2 = e36[0].y, o3 = e36[0].x, i3 = e36[0].y;
    for (let r3 = 1;r3 < e36.length; r3++) {
      const s2 = e36[r3];
      s2.x < t3 && (t3 = s2.x), s2.y < n2 && (n2 = s2.y), s2.x > o3 && (o3 = s2.x), s2.y > i3 && (i3 = s2.y);
    }
    return { minX: t3, minY: n2, maxX: o3, maxY: i3 };
  })((t2 = e35.localToWorld, [{ x: -e35.width / 2, y: -e35.height / 2 }, { x: e35.width / 2, y: -e35.height / 2 }, { x: e35.width / 2, y: e35.height / 2 }, { x: -e35.width / 2, y: e35.height / 2 }].map((e36) => Ht(t2, e36))));
  var t2;
};
var ab = (e35) => ({ minX: -e35.width / 2, minY: -e35.height / 2, maxX: e35.width / 2, maxY: e35.height / 2 });
var cb = class {
  constructor(e35) {
    this.cellSize = e35;
  }
  cells = new Map;
  itemIds = new Map;
  rowItems = [];
  visitedGenerations = new Uint32Array(0);
  queryGeneration = 0;
  registerItem(e35) {
    const t2 = this.itemIds.get(e35);
    if (t2 !== undefined)
      return t2;
    const n2 = this.rowItems.length;
    if (n2 >= this.visitedGenerations.length) {
      const e36 = new Uint32Array(this.visitedGenerations.length === 0 ? 16 : 2 * this.visitedGenerations.length);
      e36.set(this.visitedGenerations), this.visitedGenerations = e36;
    }
    return this.itemIds.set(e35, n2), this.rowItems.push(e35 === 0 ? 0 : e35), n2;
  }
  insert(e35, t2) {
    const n2 = Math.floor(t2.minX / this.cellSize), o3 = Math.floor(t2.maxX / this.cellSize), i3 = Math.floor(t2.minY / this.cellSize), r3 = Math.floor(t2.maxY / this.cellSize);
    let s2;
    for (let t3 = n2;t3 <= o3; t3 += 1) {
      let n3 = this.cells.get(t3);
      !n3 && i3 <= r3 && (n3 = new Map, this.cells.set(t3, n3));
      for (let t4 = i3;t4 <= r3; t4 += 1) {
        const o4 = n3.get(t4);
        s2 === undefined && (s2 = this.registerItem(e35)), o4 ? o4.push(s2) : n3.set(t4, [s2]);
      }
    }
  }
  query(e35) {
    const t2 = Math.floor(e35.minX / this.cellSize), n2 = Math.floor(e35.maxX / this.cellSize), o3 = Math.floor(e35.minY / this.cellSize), i3 = Math.floor(e35.maxY / this.cellSize);
    let r3 = this.queryGeneration + 1;
    r3 > 4294967295 && (this.visitedGenerations.fill(0), r3 = 1), this.queryGeneration = r3;
    const s2 = [];
    for (let e36 = t2;e36 <= n2; e36 += 1) {
      const t3 = this.cells.get(e36);
      if (!(!t3 && o3 >= -9007199254740991 && i3 <= 9007199254740991))
        for (let e37 = o3;e37 <= i3; e37 += 1) {
          const n3 = t3?.get(e37);
          if (n3)
            for (const e38 of n3)
              this.visitedGenerations[e38] !== r3 && (this.visitedGenerations[e38] = r3, s2.push(this.rowItems[e38]));
        }
    }
    return s2;
  }
};
var lb = (e35, t2) => {
  const n2 = ge(e35.start, e35.end, t2.start, t2.end);
  if (n2)
    return n2;
  const o3 = [{ left: e35.start, right: Ee(e35.start, t2.start, t2.end) }, { left: e35.end, right: Ee(e35.end, t2.start, t2.end) }, { left: Ee(t2.start, e35.start, e35.end), right: t2.start }, { left: Ee(t2.end, e35.start, e35.end), right: t2.end }];
  let i3 = { left: e35.start, right: t2.start }, r3 = Number.POSITIVE_INFINITY;
  for (const e36 of o3) {
    const t3 = Math.hypot(e36.left.x - e36.right.x, e36.left.y - e36.right.y);
    t3 < r3 && (i3 = e36, r3 = t3);
  }
  return { x: (i3.left.x + i3.right.x) / 2, y: (i3.left.y + i3.right.y) / 2 };
};
var hb = (e35, t2) => {
  const n2 = Ee(t2, e35.start, e35.end);
  return { x: (n2.x + t2.x) / 2, y: (n2.y + t2.y) / 2 };
};
var db = (e35, t2) => {
  const n2 = Ee({ x: (t2.minX + t2.maxX) / 2, y: (t2.minY + t2.maxY) / 2 }, e35.start, e35.end), o3 = Math.max(t2.minX, Math.min(t2.maxX, n2.x)), i3 = Math.max(t2.minY, Math.min(t2.maxY, n2.y));
  return { x: (n2.x + o3) / 2, y: (n2.y + i3) / 2 };
};
var ub = (e35) => {
  const t2 = new Set;
  for (const n2 of e35.route)
    n2.route_type === "wire" && (n2.start_pcb_port_id && t2.add(n2.start_pcb_port_id), n2.end_pcb_port_id && t2.add(n2.end_pcb_port_id));
  return [...t2];
};
var pb = (e35, t2, n2) => n2 < 0 ? `PCB trace ${e35} overlaps with ${t2} (accidental contact)` : `PCB trace ${e35} is too close to ${t2} (gap: ${n2.toFixed(3)}mm)`;
var mb = class {
  constructor(e35, t2 = {}) {
    this.srj = e35;
    const n2 = t2.queryResultCacheBudget ?? 8000000;
    if (!Number.isSafeInteger(n2) || n2 < 0)
      throw new Error("queryResultCacheBudget must be a nonnegative safe integer");
    if (this.primitiveKeyBudget = Math.floor(n2 / 4), this.queryResultBudget = n2 - this.primitiveKeyBudget, this.traceClearance = t2.traceClearance ?? 0.1, this.viaClearance = Math.max(t2.viaClearance ?? 0.1, 0.1), this.viaToPadClearance = t2.viaToPadClearance ?? this.srj.minViaEdgeToPadEdgeClearance ?? 0.1, this.connMap = t2.connMap, this.includeTraceViaOwnerMetadata = t2.includeTraceViaOwnerMetadata ?? false, this.cellSize = t2.spatialCellSize ?? this.getDefaultSpatialCellSize(), !Number.isFinite(this.traceClearance) || this.traceClearance < 0)
      throw new Error("traceClearance must be a non-negative finite number");
    if (!Number.isFinite(this.viaClearance))
      throw new Error("viaClearance must be a finite number");
    if (!Number.isFinite(this.viaToPadClearance) || this.viaToPadClearance < 0)
      throw new Error("viaToPadClearance must be a non-negative finite number");
    if (!Number.isFinite(this.cellSize) || this.cellSize <= 0)
      throw new Error("spatialCellSize must be a positive finite number");
    this.compileConnectionAliases(), this.obstacles = this.compileStaticObstacles(), this.obstacles.forEach((e36, t3) => this.staticObstacleIds.set(e36, t3)), this.indexStaticObstacles();
  }
  traceClearance;
  viaClearance;
  viaToPadClearance;
  cellSize;
  connMap;
  includeTraceViaOwnerMetadata;
  canonicalNetByAlias = new Map;
  connMapNetByCanonicalNet = new Map;
  obstacles;
  queryResultBudget;
  primitiveKeyBudget;
  primitiveIdsByKey = new Map;
  primitiveEvictionCursor = this.primitiveIdsByKey.entries();
  primitiveKeyUnits = 0;
  nextPrimitiveId = 0;
  staticObstacleIds = new WeakMap;
  queryResultCache = new Map;
  queryEvictionCursor = this.queryResultCache.entries();
  queryResultUnits = 0;
  cachedConnectivityKey;
  obstacleIndexesByLayer = new Map;
  lastRunStats = { traceCount: 0, segmentCount: 0, viaCount: 0, obstacleCount: 0, broadPhaseCandidateCount: 0, exactCheckCount: 0 };
  getDefaultSpatialCellSize() {
    const e35 = Math.max(0, this.srj.bounds.maxX - this.srj.bounds.minX), t2 = Math.max(0, this.srj.bounds.maxY - this.srj.bounds.minY);
    return Math.max(0.25, Math.max(e35, t2) / 64, (this.srj.minViaDiameter ?? 0.3) + Math.max(this.traceClearance, this.viaToPadClearance));
  }
  compileConnectionAliases() {
    const e35 = new Map;
    for (const t2 of this.srj.connections) {
      const n2 = t2.netConnectionName ?? t2.rootConnectionName ?? t2.name, o3 = [t2.name, t2.rootConnectionName, t2.netConnectionName, ...t2.mergedConnectionNames ?? [], ...t2.pointsToConnect.flatMap((e36) => [e36.pointId, e36.pcb_port_id])];
      for (const t3 of o3) {
        if (!t3)
          continue;
        this.canonicalNetByAlias.set(t3, n2);
        const o4 = this.connMap?.getNetConnectedToId(t3);
        if (!o4)
          continue;
        let i3 = e35.get(n2);
        i3 || (i3 = new Set, e35.set(n2, i3)), i3.add(o4);
      }
      this.canonicalNetByAlias.set(n2, n2);
    }
    for (const [t2, n2] of e35)
      n2.size === 1 && this.connMapNetByCanonicalNet.set(t2, n2.values().next().value);
  }
  resolveNetId(e35) {
    const t2 = this.connMap?.getNetConnectedToId(e35);
    if (t2)
      return t2;
    const n2 = this.canonicalNetByAlias.get(e35);
    return n2 ? this.connMapNetByCanonicalNet.get(n2) ?? n2 : e35;
  }
  areConnected(e35, t2) {
    return e35 === t2 || (!!this.connMap?.areIdsConnected(e35, t2) || this.resolveNetId(e35) === this.resolveNetId(t2));
  }
  compileStaticObstacles() {
    const e35 = [], t2 = new Set, n2 = new Set;
    for (const o3 of this.srj.obstacles) {
      if (o3.layers.length === 0)
        continue;
      const i3 = o3.connectedTo.find((e36) => e36.startsWith("pcb_smtpad_")), r3 = o3.connectedTo.find((e36) => e36.startsWith("pcb_plated_hole_")), s2 = o3.connectedTo.find((e36) => e36.startsWith("pcb_port_"));
      if (!i3 && !r3 && !s2)
        continue;
      const a3 = o3.layers.length > 1, c3 = a3 ? "pcb_plated_hole" : "pcb_smtpad", l3 = a3 ? r3 ?? `pcb_plated_hole_${o3.center.x.toFixed(3)}_${o3.center.y.toFixed(3)}` : i3 ?? `pcb_smtpad_${o3.center.x.toFixed(3)}_${o3.center.y.toFixed(3)}`, h2 = a3 ? n2 : t2;
      if (h2.has(l3))
        continue;
      h2.add(l3);
      const d2 = typeof o3.ccwRotationDegrees == "number" && Number.isFinite(o3.ccwRotationDegrees), u2 = Zt(Gt(o3.center.x, o3.center.y), en(d2 ? o3.ccwRotationDegrees : 0)), p3 = o3.shape === "circle" || !d2 && a3 && Math.abs(o3.width - o3.height) < 0.001;
      e35.push({ kind: "obstacle", obstacleType: c3, obstacleId: l3, shape: o3.shape, connectedTo: o3.connectedTo, x: o3.center.x, y: o3.center.y, width: o3.width, height: o3.height, localToWorld: u2, worldToLocal: Vt(u2), ...p3 ? { radius: Math.max(o3.width, o3.height) / 2 } : {}, layers: o3.layers, ...s2 ? { pcbPortId: s2 } : {} });
    }
    return e35;
  }
  indexStaticObstacles() {
    for (const e35 of this.obstacles) {
      const t2 = ob(sb(e35), Math.max(this.traceClearance, this.viaToPadClearance));
      for (const n2 of e35.layers) {
        let o3 = this.obstacleIndexesByLayer.get(n2);
        o3 || (o3 = new cb(this.cellSize), this.obstacleIndexesByLayer.set(n2, o3)), o3.insert(e35, t2);
      }
    }
  }
  collectDynamicGeometry(e35) {
    const t2 = [], n2 = [], o3 = new Set;
    for (const i3 of e35) {
      const e36 = this.resolveNetId(i3.connection_name), r3 = ub(i3), s2 = this.queryResultBudget ? JSON.stringify([i3.pcb_trace_id, e36, r3]) : undefined;
      for (let n3 = 0;n3 < i3.route.length - 1; n3 += 1) {
        const o4 = i3.route[n3], a3 = i3.route[n3 + 1];
        o4?.route_type === "wire" && a3?.route_type === "wire" && o4.layer === a3.layer && (Math.abs(o4.x - a3.x) <= nb && Math.abs(o4.y - a3.y) <= nb || t2.push({ kind: "trace_segment", order: t2.length, traceId: i3.pcb_trace_id, netId: e36, start: { x: o4.x, y: o4.y }, end: { x: a3.x, y: a3.y }, width: gb(o4, a3), layer: o4.layer, pcbPortIds: r3, primitiveId: s2 === undefined ? undefined : this.getPrimitiveId(["trace", s2, o4.x, o4.y, a3.x, a3.y, gb(o4, a3), o4.layer]) }));
      }
      for (const t3 of i3.route) {
        if (t3.route_type !== "via")
          continue;
        const r4 = `${t3.x},${t3.y},${t3.from_layer},${t3.to_layer}`;
        if (o3.has(r4))
          continue;
        o3.add(r4);
        const s3 = `via_${n2.length}`, a3 = t3.via_diameter ?? this.srj.minViaDiameter ?? 0.3, c3 = t3.via_hole_diameter ?? this.srj.min_via_hole_diameter ?? this.srj.minViaHoleDiameter ?? a3 / 2, l3 = eb({ via: t3, layerCount: this.srj.layerCount, allowBlindAndBuriedVias: this.srj.allowBlindAndBuriedVias });
        n2.push({ kind: "via", order: n2.length, viaId: s3, traceId: i3.pcb_trace_id, netId: e36, x: t3.x, y: t3.y, diameter: a3, holeDiameter: c3, layers: l3, primitiveId: this.queryResultBudget ? this.getPrimitiveId(["via", s3, i3.pcb_trace_id, e36, t3.x, t3.y, a3, c3, l3]) : undefined });
      }
    }
    return { segments: t2, vias: n2 };
  }
  buildDynamicIndexes(e35, t2) {
    const n2 = new Map, o3 = (e36, t3, o4) => {
      let i3 = n2.get(e36);
      i3 || (i3 = new cb(this.cellSize), n2.set(e36, i3)), i3.insert(t3, ob(o4, this.traceClearance));
    };
    for (const t3 of e35)
      o3(t3.layer, t3, ib(t3));
    for (const e36 of t2)
      for (const t3 of e36.layers)
        o3(t3, e36, rb(e36));
    return n2;
  }
  obstacleSharesNet(e35, t2) {
    return t2.connectedTo.some((t3) => this.areConnected(e35, t3));
  }
  getPrimitiveId(e35) {
    if (!this.primitiveKeyBudget)
      return;
    const t2 = JSON.stringify(e35.map((e36) => typeof e36 != "number" ? e36 : Object.is(e36, -0) ? "-0" : Number.isNaN(e36) ? "NaN" : e36 === 1 / 0 ? "+Infinity" : e36 === -1 / 0 ? "-Infinity" : e36)), n2 = this.primitiveIdsByKey.get(t2);
    if (n2)
      return n2.id;
    const o3 = t2.length + 64;
    if (o3 > this.primitiveKeyBudget || this.nextPrimitiveId >= Number.MAX_SAFE_INTEGER)
      return;
    for (;this.primitiveKeyUnits + o3 > this.primitiveKeyBudget; ) {
      const [e36, t3] = this.primitiveEvictionCursor.next().value;
      this.primitiveKeyUnits -= t3.units, this.primitiveIdsByKey.delete(e36);
    }
    const i3 = this.nextPrimitiveId++;
    return this.primitiveIdsByKey.set(t2, { id: i3, units: o3 }), this.primitiveKeyUnits += o3, i3;
  }
  getQueryCacheKey(e35, t2) {
    if (this.queryResultBudget && !t2.some((e36) => e36 === undefined))
      return `${e35}:${t2.join(",")}`;
  }
  runCachedQuery(e35, t2) {
    const n2 = e35 === undefined ? undefined : this.queryResultCache.get(e35);
    if (n2)
      return this.lastRunStats.exactCheckCount += n2.exactCheckCount, this.lastRunStats.broadPhaseCandidateCount += n2.broadPhaseCandidateCount, n2.errors.length ? structuredClone(n2.errors) : [];
    const o3 = this.lastRunStats.exactCheckCount, i3 = this.lastRunStats.broadPhaseCandidateCount, r3 = t2();
    if (e35 === undefined)
      return r3;
    const s2 = e35.length + (r3.length ? JSON.stringify(r3).length : 0) + 64 * r3.length + 64;
    if (s2 > this.queryResultBudget)
      return r3;
    for (;this.queryResultUnits + s2 > this.queryResultBudget; ) {
      const [e36, t3] = this.queryEvictionCursor.next().value;
      this.queryResultUnits -= t3.units, this.queryResultCache.delete(e36);
    }
    return this.queryResultCache.set(e35, { errors: r3.length ? structuredClone(r3) : [], exactCheckCount: this.lastRunStats.exactCheckCount - o3, broadPhaseCandidateCount: this.lastRunStats.broadPhaseCandidateCount - i3, units: s2 }), this.queryResultUnits += s2, r3;
  }
  checkTraceQuery(e35, t2, n2) {
    let o3;
    if (this.lastRunStats.broadPhaseCandidateCount += t2.length + n2.length, this.queryResultBudget) {
      const i3 = [e35.primitiveId];
      for (const n3 of t2)
        n3.kind === "trace_segment" && n3.order <= e35.order || i3.push(n3.primitiveId);
      i3.push(-1);
      for (const e36 of n2)
        i3.push(this.staticObstacleIds.get(e36));
      o3 = this.getQueryCacheKey("trace", i3);
    }
    return this.runCachedQuery(o3, () => {
      const o4 = [];
      for (const n3 of t2) {
        if (n3.kind === "trace_segment" && n3.order <= e35.order)
          continue;
        const t3 = n3.kind === "trace_segment" ? this.checkTracePair(e35, n3) : this.checkTraceVia(e35, n3);
        t3 && o4.push(t3);
      }
      for (const t3 of n2) {
        const n3 = this.checkTraceObstacle(e35, t3);
        n3 && o4.push(n3);
      }
      return o4;
    });
  }
  checkTracePair(e35, t2) {
    if (this.areConnected(e35.netId, t2.netId))
      return;
    this.lastRunStats.exactCheckCount += 1;
    const n2 = we(e35.start, e35.end, t2.start, t2.end) - e35.width / 2 - t2.width / 2;
    if (n2 > this.traceClearance - tb)
      return;
    const o3 = `overlap_${e35.traceId}_${t2.traceId}`;
    return { type: "pcb_trace_error", error_type: "pcb_trace_error", message: pb(e35.traceId, `PCB trace ${t2.traceId}`, n2), pcb_trace_id: e35.traceId, source_trace_id: "", pcb_trace_error_id: o3, minimum_clearance: this.traceClearance, actual_clearance: n2, pcb_component_ids: [], pcb_port_ids: [...new Set([...e35.pcbPortIds, ...t2.pcbPortIds])], center: lb(e35, t2) };
  }
  checkTraceVia(e35, t2) {
    if (this.areConnected(e35.netId, t2.netId))
      return;
    this.lastRunStats.exactCheckCount += 1;
    const n2 = Te(e35.start, e35.end, { x: t2.x, y: t2.y, radius: t2.diameter / 2 }) - e35.width / 2;
    if (n2 > this.traceClearance - tb)
      return;
    const o3 = `overlap_${e35.traceId}_${t2.viaId}`;
    return { type: "pcb_trace_error", error_type: "pcb_trace_error", message: pb(e35.traceId, `pcb_via "${t2.viaId}"`, n2), pcb_trace_id: e35.traceId, ...this.includeTraceViaOwnerMetadata ? { pcb_trace_ids: [e35.traceId, t2.traceId], pcb_via_id: t2.viaId, pcb_via_ids: [t2.viaId] } : {}, source_trace_id: "", pcb_trace_error_id: o3, minimum_clearance: this.traceClearance, actual_clearance: n2, pcb_component_ids: [], pcb_port_ids: e35.pcbPortIds, center: hb(e35, t2) };
  }
  checkTraceObstacle(e35, t2) {
    if (this.obstacleSharesNet(e35.netId, t2))
      return;
    this.lastRunStats.exactCheckCount += 1;
    const n2 = ab(t2), o3 = { ...e35, start: Ht(t2.worldToLocal, e35.start), end: Ht(t2.worldToLocal, e35.end) }, i3 = (t2.radius === undefined ? Ne(o3.start, o3.end, n2) : Te(e35.start, e35.end, { x: t2.x, y: t2.y, radius: t2.radius })) - e35.width / 2;
    if (i3 + tb >= this.traceClearance)
      return;
    const r3 = `overlap_${e35.traceId}_${t2.obstacleId}`;
    return { type: "pcb_trace_error", error_type: "pcb_trace_error", message: pb(e35.traceId, `${t2.obstacleType} "${t2.obstacleId}"`, i3), pcb_trace_id: e35.traceId, source_trace_id: "", pcb_trace_error_id: r3, minimum_clearance: this.traceClearance, actual_clearance: i3, pcb_component_ids: [], pcb_port_ids: [...new Set([...e35.pcbPortIds, ...t2.pcbPortId ? [t2.pcbPortId] : []])], center: t2.radius === undefined ? Ht(t2.localToWorld, db(o3, n2)) : hb(e35, t2) };
  }
  checkViaObstacle(e35, t2) {
    const n2 = this.obstacleSharesNet(e35.netId, t2);
    if (n2 && this.srj.allowViaInPad !== false)
      return;
    this.lastRunStats.exactCheckCount += 1;
    const o3 = ab(t2), i3 = Ht(t2.worldToLocal, e35), r3 = n2 && t2.shape === "circle" ? Math.min(t2.width, t2.height) / 2 : t2.radius, s2 = r3 === undefined ? Math.hypot(Math.max(o3.minX - i3.x, 0, i3.x - o3.maxX), Math.max(o3.minY - i3.y, 0, i3.y - o3.maxY)) : Math.hypot(e35.x - t2.x, e35.y - t2.y) - r3, a3 = n2 ? e35.holeDiameter : e35.diameter, c3 = n2 ? 0 : this.viaToPadClearance, l3 = s2 - a3 / 2;
    if (l3 + (n2 ? nb : tb) >= c3)
      return;
    const h2 = n2 ? "pcb_placement_error" : "pcb_pad_pad_clearance_error", d2 = `via_pad_clearance_${e35.viaId}_${t2.obstacleId}`, u2 = { x: (e35.x + t2.x) / 2, y: (e35.y + t2.y) / 2 };
    return { type: h2, error_type: h2, [`${h2}_id`]: d2, message: `pcb_via "${e35.viaId}" and ${t2.obstacleType} "${t2.obstacleId}" are too close (gap: ${l3.toFixed(3)}mm)`, pcb_trace_id: e35.traceId, pcb_pad_ids: [e35.viaId, t2.obstacleId], pcb_via_ids: [e35.viaId], minimum_clearance: c3, actual_clearance: l3, center: u2 };
  }
  checkViaPairs(e35) {
    const t2 = this.queryResultBudget ? this.getQueryCacheKey("via-pairs", e35.map((e36) => e36.primitiveId)) : undefined;
    return this.runCachedQuery(t2, () => this.computeViaPairs(e35));
  }
  computeViaPairs(e35) {
    if (e35.length < 2)
      return [];
    const t2 = [], n2 = new cb(this.cellSize);
    for (const t3 of e35)
      n2.insert(t3, ob(rb(t3), this.viaClearance));
    for (const o3 of e35)
      for (const e36 of n2.query(rb(o3))) {
        if (this.lastRunStats.broadPhaseCandidateCount += 1, e36.order <= o3.order)
          continue;
        this.lastRunStats.exactCheckCount += 1;
        const n3 = Math.hypot(o3.x - e36.x, o3.y - e36.y);
        if (n3 <= nb)
          continue;
        const i3 = n3 - o3.diameter / 2 - e36.diameter / 2;
        if (i3 + tb >= this.viaClearance)
          continue;
        const r3 = this.areConnected(o3.netId, e36.netId), s2 = [o3.viaId, e36.viaId].sort().join("_"), a3 = { x: (o3.x + e36.x) / 2, y: (o3.y + e36.y) / 2 };
        t2.push({ type: "pcb_via_clearance_error", error_type: "pcb_via_clearance_error", pcb_error_id: `${r3 ? "same_net" : "different_net"}_vias_close_${s2}`, message: `Vias ${o3.viaId} and ${e36.viaId}${r3 ? "" : " from different nets"} are too close together (gap: ${i3.toFixed(3)}mm)`, pcb_via_ids: [o3.viaId, e36.viaId], ...this.includeTraceViaOwnerMetadata ? { pcb_trace_ids: [o3.traceId, e36.traceId] } : {}, pcb_via_pair_net_relation: r3 ? "same_net" : "different_net", minimum_clearance: this.viaClearance, actual_clearance: i3, pcb_center: a3, center: a3 });
      }
    return t2;
  }
  checkViaPadQuery(e35) {
    const t2 = this.getQueryCacheKey("via-pad", [e35.primitiveId]);
    return this.runCachedQuery(t2, () => {
      const t3 = [], n2 = new Set;
      for (const o3 of e35.layers) {
        const i3 = this.obstacleIndexesByLayer.get(o3)?.query(rb(e35)) ?? [];
        for (const o4 of i3) {
          if (n2.has(o4))
            continue;
          n2.add(o4), this.lastRunStats.broadPhaseCandidateCount += 1;
          const i4 = this.checkViaObstacle(e35, o4);
          i4 && t3.push(i4);
        }
      }
      return t3;
    });
  }
  evaluate(e35) {
    return this.evaluateInternal(e35, true);
  }
  evaluateLegacy(e35) {
    return this.evaluateInternal(e35, false);
  }
  evaluateInternal(e35, t2) {
    if (this.queryResultBudget) {
      const e36 = JSON.stringify([this.connMap?.idToNetMap, this.obstacles.map((e37) => e37.connectedTo)]);
      e36 !== this.cachedConnectivityKey && (this.queryResultCache.clear(), this.queryEvictionCursor = this.queryResultCache.entries(), this.queryResultUnits = 0, this.cachedConnectivityKey = e36);
    }
    const { segments: n2, vias: o3 } = this.collectDynamicGeometry(e35), i3 = this.buildDynamicIndexes(n2, o3), r3 = [], s2 = [];
    this.lastRunStats = { traceCount: e35.length, segmentCount: n2.length, viaCount: o3.length, obstacleCount: this.obstacles.length, broadPhaseCandidateCount: 0, exactCheckCount: 0 };
    for (const e36 of n2) {
      const t3 = ib(e36), n3 = i3.get(e36.layer)?.query(t3) ?? [], o4 = this.obstacleIndexesByLayer.get(e36.layer)?.query(t3) ?? [];
      r3.push(...this.checkTraceQuery(e36, n3, o4));
    }
    const a3 = this.checkViaPairs(o3);
    if (t2)
      for (const e36 of o3)
        s2.push(...this.checkViaPadQuery(e36));
    const c3 = new Map;
    for (const e36 of r3) {
      const t3 = String(e36.pcb_trace_error_id), n3 = c3.get(t3), o4 = Number(e36.actual_clearance);
      if (!n3) {
        c3.set(t3, { ...e36, first_contact_center: e36.center, first_contact_message: e36.message, first_actual_clearance: o4, worst_contact_center: e36.center, worst_contact_message: e36.message, worst_actual_clearance: o4 });
        continue;
      }
      const i4 = Number(n3.worst_actual_clearance);
      (o4 < i4 || !Number.isFinite(i4)) && (n3.worst_contact_center = e36.center, n3.worst_contact_message = e36.message, n3.worst_actual_clearance = o4);
    }
    const l3 = [...c3.values()].map((e36) => ({ ...e36, center: typeof e36.worst_contact_center == "object" ? e36.worst_contact_center : e36.center, message: typeof e36.worst_contact_message == "string" ? e36.worst_contact_message : e36.message, actual_clearance: typeof e36.worst_actual_clearance == "number" ? e36.worst_actual_clearance : e36.actual_clearance }));
    l3.push(...s2), l3.push(...a3);
    const h2 = l3.filter((e36) => e36.center);
    return { errors: l3, errorsWithCenters: h2, locationAwareErrors: h2 };
  }
};
var gb = (e35, t2) => e35.width ?? t2.width ?? 0.1;
var fb = [1, 1.75, -1];
var _b = [1, 1.75, -1];
var yb = 8 / 3;
var bb = 0.000001;
var xb = 0.001;
var vb = 0.14;
var Ib = 0.035;
var Sb = 0.015;
var Cb = (e35) => e35.minTraceToPadEdgeClearance ?? 0.16;
var Pb = (e35) => e35.minViaEdgeToPadEdgeClearance ?? 0.1;
var Mb = (e35) => Math.max(48, Math.round(48 * Math.max(1, e35)));
var wb = (e35) => e35 >= 2 ? fb : _b;
var Nb = class {
  netMap;
  idToNetMap;
  constructor(e35) {
    this.netMap = e35, this.idToNetMap = {};
    for (const [t2, n2] of Object.entries(e35))
      for (const e36 of n2)
        this.idToNetMap[e36] = t2;
  }
  addConnections(e35) {
    for (const t2 of e35) {
      const e36 = new Set;
      for (const n3 of t2) {
        const t3 = this.idToNetMap[n3];
        t3 && e36.add(t3);
      }
      let n2;
      if (e36.size === 0)
        n2 = `connectivity_net${Object.keys(this.netMap).length}`, this.netMap[n2] = [];
      else if (e36.size === 1)
        n2 = e36.values().next().value ?? `connectivity_net${Object.keys(this.netMap).length}`;
      else {
        n2 = e36.values().next().value ?? `connectivity_net${Object.keys(this.netMap).length}`;
        for (const t3 of e36)
          if (t3 !== n2) {
            this.netMap[n2].push(...this.netMap[t3]), this.netMap[t3] = this.netMap[n2];
            for (const e37 of this.netMap[n2])
              this.idToNetMap[e37] = n2;
          }
      }
      for (const e37 of t2)
        this.netMap[n2].includes(e37) || this.netMap[n2].push(e37), this.idToNetMap[e37] = n2;
    }
  }
  getIdsConnectedToNet(e35) {
    return this.netMap[e35] || [];
  }
  getNetConnectedToId(e35) {
    return this.idToNetMap[e35];
  }
  areIdsConnected(e35, t2) {
    if (e35 === t2)
      return true;
    const n2 = this.getNetConnectedToId(e35);
    if (!n2)
      return false;
    const o3 = this.getNetConnectedToId(t2);
    return !!o3 && (n2 === o3 || o3 === e35 || o3 === e35);
  }
  areAllIdsConnected(e35) {
    const t2 = this.getNetConnectedToId(e35[0]);
    for (const n2 of e35) {
      const e36 = this.getNetConnectedToId(n2);
      if (e36 === undefined)
        return false;
      if (e36 !== t2)
        return false;
    }
    return true;
  }
};
var Rb = (e35) => {
  const t2 = [];
  for (const n3 of e35)
    if (n3.type === "source_trace")
      t2.push([n3.source_trace_id, ...n3.connected_source_port_ids ?? [], ...n3.connected_source_net_ids ?? []].filter(Boolean));
    else if (n3.type === "pcb_port") {
      const { pcb_port_id: e36, source_port_id: o3 } = n3;
      o3 && e36 && t2.push([o3, e36]);
    } else if (n3.type === "pcb_smtpad") {
      const { pcb_smtpad_id: e36, pcb_port_id: o3 } = n3;
      o3 && e36 && t2.push([e36, o3]);
    } else if (n3.type === "pcb_plated_hole") {
      const { pcb_plated_hole_id: e36, pcb_port_id: o3 } = n3;
      o3 && e36 && t2.push([e36, o3]);
    } else if (n3.type === "pcb_trace") {
      const { pcb_trace_id: e36, source_trace_id: o3 } = n3, i3 = Array.isArray(n3.route) ? n3.route.filter((e37) => e37 && e37.route_type === "wire") : [];
      if (o3 && e36 && t2.push([e36, o3]), Array.isArray(i3)) {
        const n4 = i3.find((e37) => e37?.start_pcb_port_id)?.start_pcb_port_id, o4 = i3.find((e37) => e37?.end_pcb_port_id)?.end_pcb_port_id;
        n4 && e36 && o4 && t2.push([n4, e36, o4]);
      }
    } else if (n3.type === "pcb_via") {
      const { pcb_via_id: e36, pcb_trace_id: o3 } = n3;
      o3 && e36 && t2.push([e36, o3]);
    } else if (n3.type === "source_component" && n3.internally_connected_source_port_ids)
      for (const e36 of n3.internally_connected_source_port_ids)
        t2.push(e36);
  const n2 = function(e36) {
    const t3 = new Map;
    let n3 = 0;
    function o3(e37) {
      for (const [, n4] of t3)
        if (n4.has(e37))
          return n4;
      const o4 = new Set;
      return t3.set("connectivity_net" + n3++, o4), o4;
    }
    for (const n4 of e36) {
      let e37 = null;
      for (const i3 of n4) {
        if (e37) {
          if (!e37.has(i3)) {
            const n5 = o3(i3);
            if (n5 !== e37) {
              for (const t4 of n5)
                e37.add(t4);
              t3.delete(Array.from(t3.entries()).find(([, e38]) => e38 === n5)[0]);
            }
          }
        } else
          e37 = o3(i3);
        e37.add(i3);
      }
    }
    return Object.fromEntries(Array.from(t3.entries()).map(([e37, t4]) => [e37, Array.from(t4)]));
  }(t2);
  return new Nb(n2);
};
var Tb = {};
c(Tb, { all_layers: () => mv, any_circuit_element: () => wC, any_soup_element: () => NC, any_source_component: () => rv, asset: () => ox, base_circuit_json_error: () => bx, battery_capacity: () => Ub, brep_shape: () => oI, cadModelDefaultDirectionMap: () => lC, cad_component: () => hC, cad_model_axis_directions: () => cC, cad_model_formats: () => aC, capacitance: () => Lb, circuit_json_footprint_load_error: () => kS, current: () => Yb, distance: () => $b, duration_ms: () => Xb, experiment_type: () => xC, external_footprint_load_error: () => OS, frequency: () => jb, getZodPrefixedIdWithDefault: () => ex, inductance: () => zb, kicadAt: () => ix, kicadEffects: () => sx, kicadFont: () => rx, kicadFootprintAttributes: () => lx, kicadFootprintMetadata: () => ux, kicadFootprintModel: () => dx, kicadFootprintPad: () => hx, kicadFootprintProperties: () => cx, kicadProperty: () => ax, kicadSymbolEffects: () => gx, kicadSymbolMetadata: () => yx, kicadSymbolPinNames: () => mx, kicadSymbolPinNumbers: () => px, kicadSymbolProperties: () => _x, kicadSymbolProperty: () => fx, layer_ref: () => fv, layer_string: () => gv, length: () => Fb, manufacturing_drc_properties: () => aI, ms: () => Vb, ninePointAnchor: () => tx, pcbRenderLayer: () => nx, pcb_autorouting_error: () => LS, pcb_board: () => tS, pcb_breakout_point: () => $S, pcb_component: () => cI, pcb_component_invalid_layer_error: () => QS, pcb_component_not_on_board_edge_error: () => JS, pcb_component_outside_board_error: () => qS, pcb_connector_not_in_accessible_orientation_warning: () => FS, pcb_copper_pour: () => ZS, pcb_copper_pour_brep: () => GS, pcb_copper_pour_polygon: () => US, pcb_copper_pour_rect: () => WS, pcb_copper_text: () => lS, pcb_courtyard_circle: () => sC, pcb_courtyard_outline: () => iC, pcb_courtyard_overlap_error: () => CS, pcb_courtyard_polygon: () => rC, pcb_courtyard_rect: () => oC, pcb_cutout: () => ES, pcb_cutout_circle: () => NS, pcb_cutout_path: () => TS, pcb_cutout_polygon: () => RS, pcb_cutout_rect: () => wS, pcb_fabrication_note_dimension: () => _S, pcb_fabrication_note_path: () => gS, pcb_fabrication_note_rect: () => fS, pcb_fabrication_note_text: () => mS, pcb_footprint_overlap_error: () => SS, pcb_ground_plane: () => YS, pcb_ground_plane_region: () => XS, pcb_group: () => DS, pcb_hole: () => vI, pcb_hole_circle_or_square_shape: () => mI, pcb_hole_circle_shape: () => hI, pcb_hole_oval_shape: () => fI, pcb_hole_pill_shape: () => yI, pcb_hole_rect_shape: () => uI, pcb_hole_rotated_pill_shape: () => xI, pcb_keepout: () => PS, pcb_manual_edit_conflict_warning: () => zS, pcb_missing_footprint_error: () => AS, pcb_net: () => KI, pcb_note_dimension: () => IS, pcb_note_line: () => vS, pcb_note_path: () => xS, pcb_note_rect: () => bS, pcb_note_text: () => yS, pcb_pad_pad_clearance_error: () => tC, pcb_pad_trace_clearance_error: () => nC, pcb_panel: () => nS, pcb_panelization_placement_error: () => iS, pcb_placement_error: () => oS, pcb_plated_hole: () => NI, pcb_port: () => RI, pcb_port_not_connected_error: () => QI, pcb_port_not_matched_error: () => JI, pcb_route_hint: () => iI, pcb_route_hints: () => rI, pcb_silkscreen_circle: () => dS, pcb_silkscreen_line: () => sS, pcb_silkscreen_oval: () => uS, pcb_silkscreen_path: () => aS, pcb_silkscreen_pill: () => pS, pcb_silkscreen_rect: () => hS, pcb_silkscreen_text: () => cS, pcb_smtpad: () => LI, pcb_smtpad_pill: () => OI, pcb_solder_paste: () => YI, pcb_text: () => XI, pcb_thermal_spoke: () => HS, pcb_trace: () => GI, pcb_trace_error: () => ZI, pcb_trace_hint: () => rS, pcb_trace_missing_error: () => qI, pcb_trace_route_point: () => WI, pcb_trace_route_point_via: () => VI, pcb_trace_route_point_wire: () => HI, pcb_trace_warning: () => UI, pcb_via: () => eS, pcb_via_clearance_error: () => KS, pcb_via_trace_clearance_error: () => eC, point: () => Zb, point3: () => Jb, point_with_bulge: () => tI, port_arrangement: () => Rv, position: () => qb, position3: () => Qb, resistance: () => Db, ring: () => nI, rotation: () => Gb, route_hint_point: () => sI, schematic_arc: () => Lv, schematic_box: () => Cv, schematic_circle: () => Dv, schematic_component: () => Tv, schematic_component_port_arrangement_by_sides: () => Nv, schematic_component_port_arrangement_by_size: () => wv, schematic_debug_line: () => Wv, schematic_debug_object: () => Uv, schematic_debug_object_base: () => Hv, schematic_debug_point: () => Gv, schematic_debug_rect: () => Vv, schematic_error: () => Yv, schematic_group: () => Jv, schematic_layout_error: () => Xv, schematic_line: () => Ov, schematic_manual_edit_conflict_warning: () => qv, schematic_net_label: () => $v, schematic_path: () => Pv, schematic_pin_styles: () => Mv, schematic_port: () => jv, schematic_rect: () => kv, schematic_sheet: () => eI, schematic_symbol: () => Av, schematic_table: () => Qv, schematic_table_cell: () => Kv, schematic_text: () => Fv, schematic_trace: () => zv, schematic_voltage_probe: () => Zv, simulation_ac_current_source: () => yC, simulation_ac_voltage_source: () => mC, simulation_current_source: () => bC, simulation_dc_current_source: () => _C, simulation_dc_voltage_source: () => pC, simulation_experiment: () => vC, simulation_op_amp: () => MC, simulation_switch: () => SC, simulation_transient_voltage_graph: () => IC, simulation_unknown_experiment_error: () => PC, simulation_voltage_probe: () => CC, simulation_voltage_source: () => gC, size: () => Kb, source_ambiguous_port_reference: () => uv, source_board: () => dv, source_component_base: () => vx, source_component_internal_connection: () => av, source_component_pins_underspecified_warning: () => vv, source_failed_to_create_component_error: () => Zx, source_group: () => lv, source_i2c_misconfigured_error: () => ov, source_interconnect: () => nv, source_invalid_component_property_error: () => qx, source_manually_placed_via: () => yv, source_missing_manufacturer_part_number_warning: () => ev, source_missing_property_error: () => Ux, source_net: () => hv, source_no_ground_pin_defined_warning: () => xv, source_no_power_pin_defined_warning: () => bv, source_pcb_ground_plane: () => pv, source_pin_attributes: () => Ex, source_pin_missing_trace_warning: () => Kx, source_pin_must_be_connected_error: () => Iv, source_port: () => sv, source_project_metadata: () => Gx, source_property_ignored_warning: () => Qx, source_simple_battery: () => Ox, source_simple_capacitor: () => Ix, source_simple_chip: () => Nx, source_simple_connector: () => Fx, source_simple_crystal: () => zx, source_simple_current_source: () => Tx, source_simple_diode: () => Cx, source_simple_fiducial: () => Px, source_simple_ground: () => wx, source_simple_inductor: () => kx, source_simple_led: () => Mx, source_simple_mosfet: () => Hx, source_simple_op_amp: () => Vx, source_simple_pin_header: () => Bx, source_simple_pinout: () => jx, source_simple_potentiometer: () => Lx, source_simple_power_source: () => Rx, source_simple_push_button: () => Dx, source_simple_resistor: () => Sx, source_simple_resonator: () => $x, source_simple_switch: () => Wx, source_simple_test_point: () => Xx, source_simple_transistor: () => Yx, source_simple_voltage_probe: () => tv, source_simple_voltage_source: () => iv, source_trace: () => cv, source_trace_not_connected_error: () => Jx, supplier_footprint_mismatch_warning: () => jS, supplier_name: () => xx, time: () => Hb, timestamp: () => Wb, unknown_error_finding_part: () => Sv, visible_layer: () => _v, voltage: () => Bb, wave_shape: () => dC });
var Eb = { Hz: { baseUnit: "Hz", variants: { MHz: 1e6, kHz: 1000, Hz: 1 } }, g: { baseUnit: "g", variants: { kg: 1000, g: 1 } }, "Ω": { baseUnit: "Ω", variants: { "mΩ": 0.001, "Ω": 1, "kΩ": 1000, "KΩ": 1000, kohm: 1000, "MΩ": 1e6, "GΩ": 1e9, "TΩ": 1000000000000 } }, V: { baseUnit: "V", variants: { mV: 0.001, V: 1, kV: 1000, KV: 1000, MV: 1e6, GV: 1e9, TV: 1000000000000 } }, A: { baseUnit: "A", variants: { "µA": 0.000001, mA: 0.001, ma: 0.001, A: 1, kA: 1000, MA: 1e6 } }, F: { baseUnit: "F", variants: { pF: 0.000000000001, nF: 0.000000001, "µF": 0.000001, uF: 0.000001, mF: 0.001, F: 1 } }, ml: { baseUnit: "ml", variants: { ml: 1, mL: 1, l: 1000, L: 1000 } }, deg: { baseUnit: "deg", variants: { rad: 180 / Math.PI } }, ms: { baseUnit: "ms", variants: { fs: 0.000000000001, ps: 0.000000001, ns: 0.000001, us: 0.001, "µs": 0.001, ms: 1, s: 1000 } }, mm: { baseUnit: "mm", variants: { nm: 0.000001, "µm": 0.001, um: 0.001, mm: 1, cm: 10, dm: 100, m: 1000, km: 1e6, in: 25.4, ft: 304.8, IN: 25.4, FT: 304.8, yd: 914.4, mi: 1609344, mil: 0.0254 } } };
var Ab = new Set;
for (const [e35, t2] of Object.entries(Eb)) {
  Ab.add(e35);
  for (const e36 of Object.keys(t2.variants))
    Ab.add(e36);
}
var Ob = { tera: 1000000000000, T: 1000000000000, giga: 1e9, G: 1e9, mega: 1e6, M: 1e6, kilo: 1000, k: 1000, deci: 0.1, d: 0.1, centi: 0.01, c: 0.01, milli: 0.001, m: 0.001, micro: 0.000001, u: 0.000001, "µ": 0.000001, nano: 0.000000001, n: 0.000000001, pico: 0.000000000001, p: 0.000000000001 };
function kb(e35) {
  if (e35 == null)
    return { parsedUnit: null, unitOfValue: null, value: null };
  if (typeof e35 == "string" && e35.match(/^-?[\d\.]+$/))
    return { value: Number.parseFloat(e35), parsedUnit: null, unitOfValue: null };
  if (typeof e35 == "number")
    return { value: e35, parsedUnit: null, unitOfValue: null };
  if (typeof e35 == "object" && "x" in e35 && "y" in e35) {
    const { parsedUnit: t3, unitOfValue: n3 } = kb(e35.x), o4 = kb(e35.x), i4 = kb(e35.y);
    return o4.value === null || i4.value === null ? { parsedUnit: null, unitOfValue: null, value: null } : { parsedUnit: t3, unitOfValue: n3, value: { x: o4.value, y: i4.value } };
  }
  const t2 = e35.toString().split("").reverse().join(""), n2 = t2.match(/[^\d\s]+/)?.[0];
  if (!n2)
    throw new Error(`Could not determine unit: "${e35}"`);
  const o3 = n2.split("").reverse().join(""), i3 = e35.slice(0, -o3.length);
  if (o3 in Ob && !Ab.has(o3)) {
    const e36 = Ob[o3];
    return { parsedUnit: null, unitOfValue: null, value: Number.parseFloat(i3) * e36 };
  }
  const { baseUnit: r3, conversionFactor: s2 } = function(e36) {
    for (const [t3, n3] of Object.entries(Eb))
      if (e36 in n3.variants)
        return { baseUnit: n3.baseUnit, conversionFactor: n3.variants[e36] };
    return { baseUnit: e36, conversionFactor: 1 };
  }(o3);
  return { parsedUnit: o3, unitOfValue: r3, value: s2 * Number.parseFloat(i3) };
}
var Db = Wa.string().or(Wa.number()).transform((e35) => kb(e35).value);
var Lb = Wa.string().or(Wa.number()).transform((e35) => kb(e35).value).transform((e35) => Number.parseFloat(e35.toPrecision(12)));
var zb = Wa.string().or(Wa.number()).transform((e35) => kb(e35).value);
var Bb = Wa.string().or(Wa.number()).transform((e35) => kb(e35).value);
var Fb = Wa.string().or(Wa.number()).transform((e35) => kb(e35).value);
var jb = Wa.string().or(Wa.number()).transform((e35) => kb(e35).value);
var $b = Fb;
var Yb = Wa.string().or(Wa.number()).transform((e35) => kb(e35).value);
var Xb = Wa.string().or(Wa.number()).transform((e35) => kb(e35).value);
var Hb = Xb;
var Vb = Xb;
var Wb = Wa.string().datetime();
var Gb = Wa.string().or(Wa.number()).transform((e35) => typeof e35 == "number" ? e35 : e35.endsWith("deg") ? Number.parseFloat(e35.split("deg")[0]) : e35.endsWith("rad") ? 180 * Number.parseFloat(e35.split("rad")[0]) / Math.PI : Number.parseFloat(e35));
var Ub = Wa.number().or(Wa.string().endsWith("mAh")).transform((e35) => {
  if (typeof e35 == "string") {
    const t2 = e35.replace("mAh", ""), n2 = Number.parseFloat(t2);
    if (Number.isNaN(n2))
      throw new Error("Invalid capacity");
    return n2;
  }
  return e35;
}).describe("Battery capacity in mAh");
var Zb = Wa.object({ x: $b, y: $b });
var qb = Zb;
var Jb = Wa.object({ x: $b, y: $b, z: $b });
var Qb = Jb;
var Kb = Wa.object({ width: Wa.number(), height: Wa.number() });
var ex = (e35) => Wa.string().optional().default(() => `${e35}_${((e36) => {
  const t2 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  return Array.from({ length: e36 }, () => t2[Math.floor(62 * Math.random())]).join("");
})(10)}`);
var tx = Wa.enum(["top_left", "top_center", "top_right", "center_left", "center", "center_right", "bottom_left", "bottom_center", "bottom_right"]);
var nx = Wa.enum(["top_silkscreen", "bottom_silkscreen", "top_copper", "bottom_copper", "top_soldermask", "bottom_soldermask", "top_fabrication_note", "bottom_fabrication_note", "top_user_note", "bottom_user_note", "top_courtyard", "bottom_courtyard", "inner1_copper", "inner2_copper", "inner3_copper", "inner4_copper", "inner5_copper", "inner6_copper", "edge_cuts", "drill"]);
var ox = Wa.object({ project_relative_path: Wa.string(), url: Wa.string(), mimetype: Wa.string() });
var ix = Zb.extend({ rotation: Gb.optional() });
var rx = Wa.object({ size: Zb.optional(), thickness: $b.optional() });
var sx = Wa.object({ font: rx.optional() });
var ax = Wa.object({ value: Wa.string(), at: ix.optional(), layer: Wa.string().optional(), uuid: Wa.string().optional(), hide: Wa.boolean().optional(), effects: sx.optional() });
var cx = Wa.object({ Reference: ax.optional(), Value: ax.optional(), Datasheet: ax.optional(), Description: ax.optional() });
var lx = Wa.object({ through_hole: Wa.boolean().optional(), smd: Wa.boolean().optional(), exclude_from_pos_files: Wa.boolean().optional(), exclude_from_bom: Wa.boolean().optional() });
var hx = Wa.object({ name: Wa.string(), type: Wa.string(), shape: Wa.string().optional(), at: ix.optional(), size: Zb.optional(), drill: $b.optional(), layers: Wa.array(Wa.string()).optional(), removeUnusedLayers: Wa.boolean().optional(), uuid: Wa.string().optional() });
var dx = Wa.object({ path: Wa.string(), offset: Jb.optional(), scale: Jb.optional(), rotate: Jb.optional() });
var ux = Wa.object({ footprintName: Wa.string().optional(), version: Wa.union([Wa.number(), Wa.string()]).optional(), generator: Wa.string().optional(), generatorVersion: Wa.union([Wa.number(), Wa.string()]).optional(), layer: Wa.string().optional(), properties: cx.optional(), attributes: lx.optional(), pads: Wa.array(hx).optional(), embeddedFonts: Wa.boolean().optional(), model: dx.optional() });
var px = Wa.object({ hide: Wa.boolean().optional() });
var mx = Wa.object({ offset: $b.optional(), hide: Wa.boolean().optional() });
var gx = Wa.object({ font: rx.optional(), justify: Wa.union([Wa.string(), Wa.array(Wa.string())]).optional(), hide: Wa.boolean().optional() });
var fx = Wa.object({ value: Wa.string(), id: Wa.union([Wa.number(), Wa.string()]).optional(), at: ix.optional(), effects: gx.optional() });
var _x = Wa.object({ Reference: fx.optional(), Value: fx.optional(), Footprint: fx.optional(), Datasheet: fx.optional(), Description: fx.optional(), ki_keywords: fx.optional(), ki_fp_filters: fx.optional() });
var yx = Wa.object({ symbolName: Wa.string().optional(), extends: Wa.string().optional(), pinNumbers: px.optional(), pinNames: mx.optional(), excludeFromSim: Wa.boolean().optional(), inBom: Wa.boolean().optional(), onBoard: Wa.boolean().optional(), properties: _x.optional(), embeddedFonts: Wa.boolean().optional() });
var bx = Wa.object({ error_type: Wa.string(), message: Wa.string(), is_fatal: Wa.boolean().optional() });
var xx = Wa.enum(["jlcpcb", "macrofab", "pcbway", "digikey", "mouser", "lcsc"]);
var vx = Wa.object({ type: Wa.literal("source_component"), ftype: Wa.string().optional(), source_component_id: Wa.string(), name: Wa.string(), manufacturer_part_number: Wa.string().optional(), supplier_part_numbers: Wa.record(xx, Wa.array(Wa.string())).optional(), display_value: Wa.string().optional(), display_name: Wa.string().optional(), are_pins_interchangeable: Wa.boolean().optional(), internally_connected_source_port_ids: Wa.array(Wa.array(Wa.string())).optional(), source_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() });
var Ix = vx.extend({ ftype: Wa.literal("simple_capacitor"), capacitance: Lb, max_voltage_rating: Bb.optional(), display_capacitance: Wa.string().optional(), max_decoupling_trace_length: $b.optional() });
var Sx = vx.extend({ ftype: Wa.literal("simple_resistor"), resistance: Db, display_resistance: Wa.string().optional() });
var Cx = vx.extend({ ftype: Wa.literal("simple_diode") });
var Px = vx.extend({ ftype: Wa.literal("simple_fiducial") });
var Mx = Cx.extend({ ftype: Wa.literal("simple_led"), color: Wa.string().optional(), wavelength: Wa.string().optional() });
var wx = vx.extend({ ftype: Wa.literal("simple_ground") });
var Nx = vx.extend({ ftype: Wa.literal("simple_chip") });
var Rx = vx.extend({ ftype: Wa.literal("simple_power_source"), voltage: Bb });
var Tx = vx.extend({ ftype: Wa.literal("simple_current_source"), current: Yb, frequency: jb.optional(), peak_to_peak_current: Yb.optional(), wave_shape: Wa.enum(["sine", "square", "triangle", "sawtooth", "dc"]).optional().default("dc"), phase: Wa.number().optional(), duty_cycle: Wa.number().min(0).max(1).optional() });
var Ex = Wa.object({ must_be_connected: Wa.boolean().optional(), provides_power: Wa.boolean().optional(), requires_power: Wa.boolean().optional(), provides_ground: Wa.boolean().optional(), requires_ground: Wa.boolean().optional(), provides_voltage: Wa.union([Wa.string(), Wa.number()]).optional(), requires_voltage: Wa.union([Wa.string(), Wa.number()]).optional(), do_not_connect: Wa.boolean().optional(), include_in_board_pinout: Wa.boolean().optional(), can_use_internal_pullup: Wa.boolean().optional(), is_using_internal_pullup: Wa.boolean().optional(), needs_external_pullup: Wa.boolean().optional(), can_use_internal_pulldown: Wa.boolean().optional(), is_using_internal_pulldown: Wa.boolean().optional(), needs_external_pulldown: Wa.boolean().optional(), can_use_open_drain: Wa.boolean().optional(), is_using_open_drain: Wa.boolean().optional(), can_use_push_pull: Wa.boolean().optional(), is_using_push_pull: Wa.boolean().optional(), should_have_decoupling_capacitor: Wa.boolean().optional(), recommended_decoupling_capacitor_capacitance: Wa.union([Wa.string(), Wa.number()]).optional(), is_configured_for_i2c_sda: Wa.boolean().optional(), is_configured_for_i2c_scl: Wa.boolean().optional(), is_configured_for_spi_mosi: Wa.boolean().optional(), is_configured_for_spi_miso: Wa.boolean().optional(), is_configured_for_spi_sck: Wa.boolean().optional(), is_configured_for_spi_cs: Wa.boolean().optional(), is_configured_for_uart_tx: Wa.boolean().optional(), is_configured_for_uart_rx: Wa.boolean().optional(), supports_i2c_sda: Wa.boolean().optional(), supports_i2c_scl: Wa.boolean().optional(), supports_spi_mosi: Wa.boolean().optional(), supports_spi_miso: Wa.boolean().optional(), supports_spi_sck: Wa.boolean().optional(), supports_spi_cs: Wa.boolean().optional(), supports_uart_tx: Wa.boolean().optional(), supports_uart_rx: Wa.boolean().optional() });
var Ax = vx.extend({ ftype: Wa.literal("simple_fuse"), current_rating_amps: Wa.number().describe("Nominal current in amps the fuse is rated for"), voltage_rating_volts: Wa.number().describe("Voltage rating in volts, e.g. ±5V would be 5") });
var Ox = vx.extend({ ftype: Wa.literal("simple_battery"), capacity: Ub });
var kx = vx.extend({ ftype: Wa.literal("simple_inductor"), inductance: zb, display_inductance: Wa.string().optional(), max_current_rating: Wa.number().optional() });
var Dx = vx.extend({ ftype: Wa.literal("simple_push_button") });
var Lx = vx.extend({ ftype: Wa.literal("simple_potentiometer"), max_resistance: Db, display_max_resistance: Wa.string().optional() });
var zx = vx.extend({ ftype: Wa.literal("simple_crystal"), frequency: Wa.number().describe("Frequency in Hz"), load_capacitance: Wa.number().optional().describe("Load capacitance in pF"), pin_variant: Wa.enum(["two_pin", "four_pin"]).optional() });
var Bx = vx.extend({ ftype: Wa.literal("simple_pin_header"), pin_count: Wa.number(), gender: Wa.enum(["male", "female"]).optional().default("male") });
var Fx = vx.extend({ ftype: Wa.literal("simple_connector"), standard: Wa.enum(["usb_c", "m2"]).optional() });
var jx = vx.extend({ ftype: Wa.literal("simple_pinout") });
var $x = vx.extend({ ftype: Wa.literal("simple_resonator"), load_capacitance: Lb, equivalent_series_resistance: Db.optional(), frequency: jb });
var Yx = vx.extend({ ftype: Wa.literal("simple_transistor"), transistor_type: Wa.enum(["npn", "pnp"]) });
var Xx = vx.extend({ ftype: Wa.literal("simple_test_point"), footprint_variant: Wa.enum(["pad", "through_hole"]).optional(), pad_shape: Wa.enum(["rect", "circle"]).optional(), pad_diameter: Wa.union([Wa.number(), Wa.string()]).optional(), hole_diameter: Wa.union([Wa.number(), Wa.string()]).optional(), width: Wa.union([Wa.number(), Wa.string()]).optional(), height: Wa.union([Wa.number(), Wa.string()]).optional() });
var Hx = vx.extend({ ftype: Wa.literal("simple_mosfet"), channel_type: Wa.enum(["n", "p"]), mosfet_mode: Wa.enum(["enhancement", "depletion"]) });
var Vx = vx.extend({ ftype: Wa.literal("simple_op_amp") });
var Wx = vx.extend({ ftype: Wa.literal("simple_switch") });
var Gx = Wa.object({ type: Wa.literal("source_project_metadata"), name: Wa.string().optional(), software_used_string: Wa.string().optional(), project_url: Wa.string().optional(), created_at: Wb.optional() });
var Ux = bx.extend({ type: Wa.literal("source_missing_property_error"), source_missing_property_error_id: ex("source_missing_property_error"), source_component_id: Wa.string(), property_name: Wa.string(), subcircuit_id: Wa.string().optional(), error_type: Wa.literal("source_missing_property_error").default("source_missing_property_error") }).describe("The source code is missing a property");
var Zx = bx.extend({ type: Wa.literal("source_failed_to_create_component_error"), source_failed_to_create_component_error_id: ex("source_failed_to_create_component_error"), error_type: Wa.literal("source_failed_to_create_component_error").default("source_failed_to_create_component_error"), component_name: Wa.string().optional(), subcircuit_id: Wa.string().optional(), parent_source_component_id: Wa.string().optional(), pcb_center: Wa.object({ x: Wa.number().optional(), y: Wa.number().optional() }).optional(), schematic_center: Wa.object({ x: Wa.number().optional(), y: Wa.number().optional() }).optional() }).describe("Error emitted when a component fails to be constructed");
var qx = bx.extend({ type: Wa.literal("source_invalid_component_property_error"), source_invalid_component_property_error_id: ex("source_invalid_component_property_error"), source_component_id: Wa.string(), property_name: Wa.string(), property_value: Wa.unknown().optional(), expected_format: Wa.string().optional(), subcircuit_id: Wa.string().optional(), error_type: Wa.literal("source_invalid_component_property_error").default("source_invalid_component_property_error") }).describe("The source component property is invalid");
var Jx = bx.extend({ type: Wa.literal("source_trace_not_connected_error"), source_trace_not_connected_error_id: ex("source_trace_not_connected_error"), error_type: Wa.literal("source_trace_not_connected_error").default("source_trace_not_connected_error"), subcircuit_id: Wa.string().optional(), source_group_id: Wa.string().optional(), source_trace_id: Wa.string().optional(), connected_source_port_ids: Wa.array(Wa.string()).optional(), selectors_not_found: Wa.array(Wa.string()).optional() }).describe("Occurs when a source trace selector does not match any ports");
var Qx = Wa.object({ type: Wa.literal("source_property_ignored_warning"), source_property_ignored_warning_id: ex("source_property_ignored_warning"), source_component_id: Wa.string(), property_name: Wa.string(), subcircuit_id: Wa.string().optional(), error_type: Wa.literal("source_property_ignored_warning").default("source_property_ignored_warning"), message: Wa.string() }).describe("The source property was ignored");
var Kx = Wa.object({ type: Wa.literal("source_pin_missing_trace_warning"), source_pin_missing_trace_warning_id: ex("source_pin_missing_trace_warning"), warning_type: Wa.literal("source_pin_missing_trace_warning").default("source_pin_missing_trace_warning"), message: Wa.string(), source_component_id: Wa.string(), source_port_id: Wa.string(), subcircuit_id: Wa.string().optional() }).describe("Warning emitted when a source component pin is missing a trace connection");
var ev = Wa.object({ type: Wa.literal("source_missing_manufacturer_part_number_warning"), source_missing_manufacturer_part_number_warning_id: ex("source_missing_manufacturer_part_number_warning"), warning_type: Wa.literal("source_missing_manufacturer_part_number_warning").default("source_missing_manufacturer_part_number_warning"), message: Wa.string(), source_component_id: Wa.string(), standard: Wa.string(), subcircuit_id: Wa.string().optional() }).describe("Warning emitted when a standard connector is missing manufacturer part number");
var tv = vx.extend({ ftype: Wa.literal("simple_voltage_probe") });
var nv = vx.extend({ ftype: Wa.literal("interconnect") });
var ov = bx.extend({ type: Wa.literal("source_i2c_misconfigured_error"), source_i2c_misconfigured_error_id: ex("source_i2c_misconfigured_error"), error_type: Wa.literal("source_i2c_misconfigured_error").default("source_i2c_misconfigured_error"), source_port_ids: Wa.array(Wa.string()) }).describe("Error emitted when incompatible I2C pins (e.g. SDA and SCL) are connected to the same net");
var iv = vx.extend({ ftype: Wa.literal("simple_voltage_source"), voltage: Bb, frequency: jb.optional(), peak_to_peak_voltage: Bb.optional(), wave_shape: Wa.enum(["sinewave", "square", "triangle", "sawtooth"]).optional(), phase: Gb.optional(), duty_cycle: Wa.number().optional().describe("Duty cycle as a fraction (0 to 1)") });
var rv = Wa.union([Sx, Ix, Cx, Px, Mx, wx, Nx, Rx, Tx, Ox, kx, Dx, Lx, zx, Bx, Fx, jx, $x, Wx, Yx, Xx, Hx, Vx, Ax, tv, nv, iv, Gx, Ux, qx, Zx, Jx, Qx, Kx, ev, ov]);
var sv = Wa.object({ type: Wa.literal("source_port"), pin_number: Wa.number().optional(), port_hints: Wa.array(Wa.string()).optional(), name: Wa.string(), source_port_id: Wa.string(), source_component_id: Wa.string().optional(), source_group_id: Wa.string().optional(), most_frequently_referenced_by_name: Wa.string().optional(), subcircuit_id: Wa.string().optional(), subcircuit_connectivity_map_key: Wa.string().optional() }).merge(Ex);
var av = Wa.object({ type: Wa.literal("source_component_internal_connection"), source_component_internal_connection_id: Wa.string(), source_component_id: Wa.string(), source_port_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() });
var cv = Wa.object({ type: Wa.literal("source_trace"), source_trace_id: Wa.string(), connected_source_port_ids: Wa.array(Wa.string()), connected_source_net_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional(), subcircuit_connectivity_map_key: Wa.string().optional(), max_length: Wa.number().optional(), min_trace_thickness: Wa.number().optional(), display_name: Wa.string().optional() });
var lv = Wa.object({ type: Wa.literal("source_group"), source_group_id: Wa.string(), subcircuit_id: Wa.string().optional(), parent_subcircuit_id: Wa.string().optional(), parent_source_group_id: Wa.string().optional(), is_subcircuit: Wa.boolean().optional(), show_as_schematic_box: Wa.boolean().optional(), name: Wa.string().optional(), was_automatically_named: Wa.boolean().optional() });
var hv = Wa.object({ type: Wa.literal("source_net"), source_net_id: Wa.string(), name: Wa.string(), member_source_group_ids: Wa.array(Wa.string()), is_power: Wa.boolean().optional(), is_ground: Wa.boolean().optional(), is_digital_signal: Wa.boolean().optional(), is_analog_signal: Wa.boolean().optional(), is_positive_voltage_source: Wa.boolean().optional(), trace_width: Wa.number().optional(), subcircuit_id: Wa.string().optional(), subcircuit_connectivity_map_key: Wa.string().optional() });
var dv = Wa.object({ type: Wa.literal("source_board"), source_board_id: Wa.string(), source_group_id: Wa.string(), title: Wa.string().optional() }).describe("Defines a board in the source domain");
var uv = bx.extend({ type: Wa.literal("source_ambiguous_port_reference"), source_ambiguous_port_reference_id: ex("source_ambiguous_port_reference"), error_type: Wa.literal("source_ambiguous_port_reference").default("source_ambiguous_port_reference"), source_port_id: Wa.string().optional(), source_component_id: Wa.string().optional() }).describe("Error emitted when a port hint matches multiple non-overlapping pads, making the port reference ambiguous");
var pv = Wa.object({ type: Wa.literal("source_pcb_ground_plane"), source_pcb_ground_plane_id: Wa.string(), source_group_id: Wa.string(), source_net_id: Wa.string(), subcircuit_id: Wa.string().optional() }).describe("Defines a ground plane in the source domain");
var mv = ["top", "bottom", "inner1", "inner2", "inner3", "inner4", "inner5", "inner6"];
var gv = Wa.enum(mv);
var fv = gv.or(Wa.object({ name: gv })).transform((e35) => typeof e35 == "string" ? e35 : e35.name);
var _v = Wa.enum(["top", "bottom"]);
var yv = Wa.object({ type: Wa.literal("source_manually_placed_via"), source_manually_placed_via_id: Wa.string(), source_group_id: Wa.string(), source_net_id: Wa.string(), subcircuit_id: Wa.string().optional(), source_trace_id: Wa.string().optional() }).describe("Defines a via that is manually placed in the source domain");
var bv = Wa.object({ type: Wa.literal("source_no_power_pin_defined_warning"), source_no_power_pin_defined_warning_id: ex("source_no_power_pin_defined_warning"), warning_type: Wa.literal("source_no_power_pin_defined_warning").default("source_no_power_pin_defined_warning"), message: Wa.string(), source_component_id: Wa.string(), source_port_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe("Warning emitted when a chip has no source ports with requires_power=true");
var xv = Wa.object({ type: Wa.literal("source_no_ground_pin_defined_warning"), source_no_ground_pin_defined_warning_id: ex("source_no_ground_pin_defined_warning"), warning_type: Wa.literal("source_no_ground_pin_defined_warning").default("source_no_ground_pin_defined_warning"), message: Wa.string(), source_component_id: Wa.string(), source_port_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe("Warning emitted when a chip has no source ports marked as ground pins");
var vv = Wa.object({ type: Wa.literal("source_component_pins_underspecified_warning"), source_component_pins_underspecified_warning_id: ex("source_component_pins_underspecified_warning"), warning_type: Wa.literal("source_component_pins_underspecified_warning").default("source_component_pins_underspecified_warning"), message: Wa.string(), source_component_id: Wa.string(), source_port_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe("Warning emitted when all ports on a source component are underspecified");
var Iv = bx.extend({ type: Wa.literal("source_pin_must_be_connected_error"), source_pin_must_be_connected_error_id: ex("source_pin_must_be_connected_error"), error_type: Wa.literal("source_pin_must_be_connected_error").default("source_pin_must_be_connected_error"), source_component_id: Wa.string(), source_port_id: Wa.string(), subcircuit_id: Wa.string().optional() }).describe("Error emitted when a pin with mustBeConnected attribute is not connected to any trace");
var Sv = bx.extend({ type: Wa.literal("unknown_error_finding_part"), unknown_error_finding_part_id: ex("unknown_error_finding_part"), error_type: Wa.literal("unknown_error_finding_part").default("unknown_error_finding_part"), source_component_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe("Error emitted when an unexpected error occurs while finding a part");
var Cv = Wa.object({ type: Wa.literal("schematic_box"), schematic_component_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), width: $b, height: $b, is_dashed: Wa.boolean().default(false), x: $b, y: $b, subcircuit_id: Wa.string().optional() }).describe("Draws a box on the schematic");
var Pv = Wa.object({ type: Wa.literal("schematic_path"), schematic_path_id: ex("schematic_path"), schematic_component_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), fill_color: Wa.string().optional(), is_filled: Wa.boolean().optional(), stroke_width: $b.nullable().optional(), stroke_color: Wa.string().optional(), points: Wa.array(Zb), subcircuit_id: Wa.string().optional() });
var Mv = Wa.record(Wa.object({ left_margin: Fb.optional(), right_margin: Fb.optional(), top_margin: Fb.optional(), bottom_margin: Fb.optional() }));
var wv = Wa.object({ left_size: Wa.number(), right_size: Wa.number(), top_size: Wa.number().optional(), bottom_size: Wa.number().optional() });
var Nv = Wa.object({ left_side: Wa.object({ pins: Wa.array(Wa.number()), direction: Wa.enum(["top-to-bottom", "bottom-to-top"]).optional() }).optional(), right_side: Wa.object({ pins: Wa.array(Wa.number()), direction: Wa.enum(["top-to-bottom", "bottom-to-top"]).optional() }).optional(), top_side: Wa.object({ pins: Wa.array(Wa.number()), direction: Wa.enum(["left-to-right", "right-to-left"]).optional() }).optional(), bottom_side: Wa.object({ pins: Wa.array(Wa.number()), direction: Wa.enum(["left-to-right", "right-to-left"]).optional() }).optional() });
var Rv = Wa.union([wv, Nv]);
var Tv = Wa.object({ type: Wa.literal("schematic_component"), size: Kb, center: Zb, source_component_id: Wa.string().optional(), schematic_component_id: Wa.string(), schematic_symbol_id: Wa.string().optional(), pin_spacing: Fb.optional(), pin_styles: Mv.optional(), box_width: Fb.optional(), symbol_name: Wa.string().optional(), port_arrangement: Rv.optional(), port_labels: Wa.record(Wa.string()).optional(), symbol_display_value: Wa.string().optional(), subcircuit_id: Wa.string().optional(), schematic_group_id: Wa.string().optional(), is_schematic_group: Wa.boolean().optional(), source_group_id: Wa.string().optional(), is_box_with_pins: Wa.boolean().optional().default(true) });
var Ev = Wa.object({ kicad_symbol: yx.optional() }).catchall(Wa.unknown());
var Av = Wa.object({ type: Wa.literal("schematic_symbol"), schematic_symbol_id: Wa.string(), name: Wa.string().optional(), metadata: Ev.optional() }).describe("Defines a named schematic symbol that can be referenced by components.");
var Ov = Wa.object({ type: Wa.literal("schematic_line"), schematic_line_id: ex("schematic_line"), schematic_component_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), x1: $b, y1: $b, x2: $b, y2: $b, stroke_width: $b.nullable().optional(), color: Wa.string().default("#000000"), is_dashed: Wa.boolean().default(false), subcircuit_id: Wa.string().optional() }).describe("Draws a styled line on the schematic");
var kv = Wa.object({ type: Wa.literal("schematic_rect"), schematic_rect_id: ex("schematic_rect"), schematic_component_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), center: Zb, width: $b, height: $b, rotation: Gb.default(0), stroke_width: $b.nullable().optional(), color: Wa.string().default("#000000"), is_filled: Wa.boolean().default(false), fill_color: Wa.string().optional(), is_dashed: Wa.boolean().default(false), subcircuit_id: Wa.string().optional() }).describe("Draws a styled rectangle on the schematic");
var Dv = Wa.object({ type: Wa.literal("schematic_circle"), schematic_circle_id: ex("schematic_circle"), schematic_component_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), center: Zb, radius: $b, stroke_width: $b.nullable().optional(), color: Wa.string().default("#000000"), is_filled: Wa.boolean().default(false), fill_color: Wa.string().optional(), is_dashed: Wa.boolean().default(false), subcircuit_id: Wa.string().optional() }).describe("Draws a styled circle on the schematic");
var Lv = Wa.object({ type: Wa.literal("schematic_arc"), schematic_arc_id: ex("schematic_arc"), schematic_component_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), center: Zb, radius: $b, start_angle_degrees: Gb, end_angle_degrees: Gb, direction: Wa.enum(["clockwise", "counterclockwise"]).default("counterclockwise"), stroke_width: $b.nullable().optional(), color: Wa.string().default("#000000"), is_dashed: Wa.boolean().default(false), subcircuit_id: Wa.string().optional() }).describe("Draws a styled arc on the schematic");
var zv = Wa.object({ type: Wa.literal("schematic_trace"), schematic_trace_id: Wa.string(), source_trace_id: Wa.string().optional(), junctions: Wa.array(Wa.object({ x: Wa.number(), y: Wa.number() })), edges: Wa.array(Wa.object({ from: Wa.object({ x: Wa.number(), y: Wa.number() }), to: Wa.object({ x: Wa.number(), y: Wa.number() }), is_crossing: Wa.boolean().optional(), from_schematic_port_id: Wa.string().optional(), to_schematic_port_id: Wa.string().optional() })), subcircuit_id: Wa.string().optional(), subcircuit_connectivity_map_key: Wa.string().optional() });
var Bv = Wa.enum(["center", "left", "right", "top", "bottom"]);
var Fv = Wa.object({ type: Wa.literal("schematic_text"), schematic_component_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), schematic_text_id: Wa.string(), text: Wa.string(), font_size: Wa.number().default(0.18), position: Wa.object({ x: $b, y: $b }), rotation: Wa.number().default(0), anchor: Wa.union([Bv.describe("legacy"), tx]).default("center"), color: Wa.string().default("#000000"), subcircuit_id: Wa.string().optional() });
var jv = Wa.object({ type: Wa.literal("schematic_port"), schematic_port_id: Wa.string(), source_port_id: Wa.string(), schematic_component_id: Wa.string().optional(), center: Zb, facing_direction: Wa.enum(["up", "down", "left", "right"]).optional(), distance_from_component_edge: Wa.number().optional(), side_of_component: Wa.enum(["top", "bottom", "left", "right"]).optional(), true_ccw_index: Wa.number().optional(), pin_number: Wa.number().optional(), display_pin_label: Wa.string().optional(), subcircuit_id: Wa.string().optional(), is_connected: Wa.boolean().optional(), has_input_arrow: Wa.boolean().optional(), has_output_arrow: Wa.boolean().optional(), is_drawn_with_inversion_circle: Wa.boolean().optional() }).describe("Defines a port on a schematic component");
var $v = Wa.object({ type: Wa.literal("schematic_net_label"), schematic_net_label_id: ex("schematic_net_label"), schematic_trace_id: Wa.string().optional(), source_trace_id: Wa.string().optional(), source_net_id: Wa.string(), center: Zb, anchor_position: Zb.optional(), anchor_side: Wa.enum(["top", "bottom", "left", "right"]), text: Wa.string(), symbol_name: Wa.string().optional(), is_movable: Wa.boolean().optional(), subcircuit_id: Wa.string().optional() });
var Yv = bx.extend({ type: Wa.literal("schematic_error"), schematic_error_id: Wa.string(), error_type: Wa.literal("schematic_port_not_found").default("schematic_port_not_found"), subcircuit_id: Wa.string().optional() }).describe("Defines a schematic error on the schematic");
var Xv = bx.extend({ type: Wa.literal("schematic_layout_error"), schematic_layout_error_id: ex("schematic_layout_error"), error_type: Wa.literal("schematic_layout_error").default("schematic_layout_error"), source_group_id: Wa.string(), schematic_group_id: Wa.string(), subcircuit_id: Wa.string().optional() }).describe("Error emitted when schematic layout fails for a group");
var Hv = Wa.object({ type: Wa.literal("schematic_debug_object"), label: Wa.string().optional(), subcircuit_id: Wa.string().optional() });
var Vv = Hv.extend({ shape: Wa.literal("rect"), center: Zb, size: Kb });
var Wv = Hv.extend({ shape: Wa.literal("line"), start: Zb, end: Zb });
var Gv = Hv.extend({ shape: Wa.literal("point"), center: Zb });
var Uv = Wa.discriminatedUnion("shape", [Vv, Wv, Gv]);
var Zv = Wa.object({ type: Wa.literal("schematic_voltage_probe"), schematic_voltage_probe_id: Wa.string(), source_component_id: Wa.string().optional(), name: Wa.string().optional(), position: Zb, schematic_trace_id: Wa.string(), voltage: Bb.optional(), subcircuit_id: Wa.string().optional(), color: Wa.string().optional(), label_alignment: tx.optional() }).describe("Defines a voltage probe measurement point on a schematic trace");
var qv = Wa.object({ type: Wa.literal("schematic_manual_edit_conflict_warning"), schematic_manual_edit_conflict_warning_id: ex("schematic_manual_edit_conflict_warning"), warning_type: Wa.literal("schematic_manual_edit_conflict_warning").default("schematic_manual_edit_conflict_warning"), message: Wa.string(), schematic_component_id: Wa.string(), schematic_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), source_component_id: Wa.string() }).describe("Warning emitted when a component has both manual placement and explicit schX/schY coordinates");
var Jv = Wa.object({ type: Wa.literal("schematic_group"), schematic_group_id: ex("schematic_group"), source_group_id: Wa.string(), is_subcircuit: Wa.boolean().optional(), subcircuit_id: Wa.string().optional(), width: Fb, height: Fb, center: Zb, schematic_component_ids: Wa.array(Wa.string()), show_as_schematic_box: Wa.boolean().optional(), name: Wa.string().optional(), description: Wa.string().optional() }).describe("Defines a group of components on the schematic");
var Qv = Wa.object({ type: Wa.literal("schematic_table"), schematic_table_id: ex("schematic_table"), anchor_position: Zb, column_widths: Wa.array($b), row_heights: Wa.array($b), cell_padding: $b.optional(), border_width: $b.optional(), subcircuit_id: Wa.string().optional(), schematic_component_id: Wa.string().optional(), anchor: tx.optional() }).describe("Defines a table on the schematic");
var Kv = Wa.object({ type: Wa.literal("schematic_table_cell"), schematic_table_cell_id: ex("schematic_table_cell"), schematic_table_id: Wa.string(), start_row_index: Wa.number(), end_row_index: Wa.number(), start_column_index: Wa.number(), end_column_index: Wa.number(), text: Wa.string().optional(), center: Zb, width: $b, height: $b, horizontal_align: Wa.enum(["left", "center", "right"]).optional(), vertical_align: Wa.enum(["top", "middle", "bottom"]).optional(), font_size: $b.optional(), subcircuit_id: Wa.string().optional() }).describe("Defines a cell within a schematic_table");
var eI = Wa.object({ type: Wa.literal("schematic_sheet"), schematic_sheet_id: ex("schematic_sheet"), name: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe("Defines a schematic sheet or page that components can be placed on");
var tI = Wa.object({ x: $b, y: $b, bulge: Wa.number().optional() });
var nI = Wa.object({ vertices: Wa.array(tI) });
var oI = Wa.object({ outer_ring: nI, inner_rings: Wa.array(nI).default([]) });
var iI = Wa.object({ x: $b, y: $b, via: Wa.boolean().optional(), via_to_layer: fv.optional() });
var rI = Wa.array(iI);
var sI = Wa.object({ x: $b, y: $b, via: Wa.boolean().optional(), to_layer: fv.optional(), trace_width: $b.optional() });
var aI = Wa.object({ min_trace_width: Fb.optional(), min_board_edge_clearance: Fb.optional(), min_via_hole_edge_to_via_hole_edge_clearance: Fb.optional(), min_plated_hole_drill_edge_to_drill_edge_clearance: Fb.optional(), min_trace_to_pad_edge_clearance: Fb.optional(), min_pad_edge_to_pad_edge_clearance: Fb.optional(), min_same_net_trace_edge_to_trace_edge_clearance: Fb.optional(), min_different_net_trace_edge_to_trace_edge_clearance: Fb.optional(), min_via_hole_diameter: Fb.optional(), min_via_pad_diameter: Fb.optional() });
var cI = Wa.object({ type: Wa.literal("pcb_component"), pcb_component_id: ex("pcb_component"), source_component_id: Wa.string(), center: Zb, layer: fv, rotation: Gb, display_offset_x: Wa.string().optional().describe("How to display the x offset for this part, usually corresponding with how the user specified it"), display_offset_y: Wa.string().optional().describe("How to display the y offset for this part, usually corresponding with how the user specified it"), width: Fb, height: Fb, do_not_place: Wa.boolean().optional(), is_allowed_to_be_off_board: Wa.boolean().optional(), subcircuit_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), position_mode: Wa.enum(["packed", "relative_to_group_anchor", "relative_to_another_component", "none"]).optional(), anchor_position: Zb.optional(), anchor_alignment: tx.optional(), positioned_relative_to_pcb_group_id: Wa.string().optional(), positioned_relative_to_pcb_board_id: Wa.string().optional(), cable_insertion_center: Zb.optional(), insertion_direction: Wa.enum(["from_above", "from_left", "from_right", "from_front", "from_back"]).optional(), metadata: Wa.object({ kicad_footprint: ux.optional() }).optional(), obstructs_within_bounds: Wa.boolean().default(true).describe("Does this component take up all the space within its bounds on a layer. This is generally true except for when separated pin headers are being represented by a single component (in which case, chips can be placed between the pin headers) or for tall modules where chips fit underneath") }).describe("Defines a component on the PCB");
var lI = Wa.object({ type: Wa.literal("pcb_hole"), pcb_hole_id: ex("pcb_hole"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), pcb_component_id: Wa.string().optional(), hole_shape: Wa.literal("circle"), hole_diameter: Wa.number(), x: $b, y: $b, is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });
var hI = lI.describe("Defines a circular hole on the PCB");
var dI = Wa.object({ type: Wa.literal("pcb_hole"), pcb_hole_id: ex("pcb_hole"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), pcb_component_id: Wa.string().optional(), hole_shape: Wa.literal("rect"), hole_width: Wa.number(), hole_height: Wa.number(), x: $b, y: $b, is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });
var uI = dI.describe("Defines a rectangular (square-capable) hole on the PCB. Use equal width/height for square.");
var pI = Wa.object({ type: Wa.literal("pcb_hole"), pcb_hole_id: ex("pcb_hole"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), pcb_component_id: Wa.string().optional(), hole_shape: Wa.enum(["circle", "square"]), hole_diameter: Wa.number(), x: $b, y: $b, is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });
var mI = pI.describe("Defines a circular or square hole on the PCB");
var gI = Wa.object({ type: Wa.literal("pcb_hole"), pcb_hole_id: ex("pcb_hole"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), pcb_component_id: Wa.string().optional(), hole_shape: Wa.literal("oval"), hole_width: Wa.number(), hole_height: Wa.number(), x: $b, y: $b, is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });
var fI = gI.describe("Defines an oval hole on the PCB");
var _I = Wa.object({ type: Wa.literal("pcb_hole"), pcb_hole_id: ex("pcb_hole"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), pcb_component_id: Wa.string().optional(), hole_shape: Wa.literal("pill"), hole_width: Wa.number(), hole_height: Wa.number(), x: $b, y: $b, is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });
var yI = _I.describe("Defines a pill-shaped hole on the PCB");
var bI = Wa.object({ type: Wa.literal("pcb_hole"), pcb_hole_id: ex("pcb_hole"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), pcb_component_id: Wa.string().optional(), hole_shape: Wa.literal("rotated_pill"), hole_width: Wa.number(), hole_height: Wa.number(), x: $b, y: $b, ccw_rotation: Gb, is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });
var xI = bI.describe("Defines a rotated pill-shaped hole on the PCB");
var vI = pI.or(gI).or(_I).or(bI).or(lI).or(dI);
var II = Wa.object({ type: Wa.literal("pcb_plated_hole"), shape: Wa.literal("circle"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), outer_diameter: Wa.number(), hole_diameter: Wa.number(), is_covered_with_solder_mask: Wa.boolean().optional(), x: $b, y: $b, layers: Wa.array(fv), port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), pcb_plated_hole_id: ex("pcb_plated_hole"), soldermask_margin: Wa.number().optional() });
var SI = Wa.object({ type: Wa.literal("pcb_plated_hole"), shape: Wa.enum(["oval", "pill"]), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), outer_width: Wa.number(), outer_height: Wa.number(), hole_width: Wa.number(), hole_height: Wa.number(), is_covered_with_solder_mask: Wa.boolean().optional(), x: $b, y: $b, ccw_rotation: Gb, layers: Wa.array(fv), port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), pcb_plated_hole_id: ex("pcb_plated_hole"), soldermask_margin: Wa.number().optional() });
var CI = Wa.object({ type: Wa.literal("pcb_plated_hole"), shape: Wa.literal("circular_hole_with_rect_pad"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), hole_shape: Wa.literal("circle"), pad_shape: Wa.literal("rect"), hole_diameter: Wa.number(), rect_pad_width: Wa.number(), rect_pad_height: Wa.number(), rect_border_radius: Wa.number().optional(), hole_offset_x: $b.default(0), hole_offset_y: $b.default(0), is_covered_with_solder_mask: Wa.boolean().optional(), x: $b, y: $b, layers: Wa.array(fv), port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), pcb_plated_hole_id: ex("pcb_plated_hole"), soldermask_margin: Wa.number().optional(), rect_ccw_rotation: Gb.optional() });
var PI = Wa.object({ type: Wa.literal("pcb_plated_hole"), shape: Wa.literal("pill_hole_with_rect_pad"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), hole_shape: Wa.literal("pill"), pad_shape: Wa.literal("rect"), hole_width: Wa.number(), hole_height: Wa.number(), rect_pad_width: Wa.number(), rect_pad_height: Wa.number(), rect_border_radius: Wa.number().optional(), hole_offset_x: $b.default(0), hole_offset_y: $b.default(0), is_covered_with_solder_mask: Wa.boolean().optional(), x: $b, y: $b, layers: Wa.array(fv), port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), pcb_plated_hole_id: ex("pcb_plated_hole"), soldermask_margin: Wa.number().optional() });
var MI = Wa.object({ type: Wa.literal("pcb_plated_hole"), shape: Wa.literal("rotated_pill_hole_with_rect_pad"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), hole_shape: Wa.literal("rotated_pill"), pad_shape: Wa.literal("rect"), hole_width: Wa.number(), hole_height: Wa.number(), hole_ccw_rotation: Gb, rect_pad_width: Wa.number(), rect_pad_height: Wa.number(), rect_border_radius: Wa.number().optional(), rect_ccw_rotation: Gb, hole_offset_x: $b.default(0), hole_offset_y: $b.default(0), is_covered_with_solder_mask: Wa.boolean().optional(), x: $b, y: $b, layers: Wa.array(fv), port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), pcb_plated_hole_id: ex("pcb_plated_hole"), soldermask_margin: Wa.number().optional() });
var wI = Wa.object({ type: Wa.literal("pcb_plated_hole"), shape: Wa.literal("hole_with_polygon_pad"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), hole_shape: Wa.enum(["circle", "oval", "pill", "rotated_pill"]), hole_diameter: Wa.number().optional(), hole_width: Wa.number().optional(), hole_height: Wa.number().optional(), pad_outline: Wa.array(Wa.object({ x: $b, y: $b })).min(3), hole_offset_x: $b.default(0), hole_offset_y: $b.default(0), is_covered_with_solder_mask: Wa.boolean().optional(), x: $b, y: $b, layers: Wa.array(fv), port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), pcb_plated_hole_id: ex("pcb_plated_hole"), soldermask_margin: Wa.number().optional(), ccw_rotation: Gb.optional() });
var NI = Wa.union([II, SI, CI, PI, MI, wI]);
var RI = Wa.object({ type: Wa.literal("pcb_port"), pcb_port_id: ex("pcb_port"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), source_port_id: Wa.string(), pcb_component_id: Wa.string().optional(), x: $b, y: $b, layers: Wa.array(fv), is_board_pinout: Wa.boolean().optional() }).describe("Defines a port on the PCB");
var TI = Wa.object({ type: Wa.literal("pcb_smtpad"), shape: Wa.literal("circle"), pcb_smtpad_id: ex("pcb_smtpad"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: $b, y: $b, radius: Wa.number(), layer: fv, port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });
var EI = Wa.object({ type: Wa.literal("pcb_smtpad"), shape: Wa.literal("rect"), pcb_smtpad_id: ex("pcb_smtpad"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: $b, y: $b, width: Wa.number(), height: Wa.number(), rect_border_radius: Wa.number().optional(), corner_radius: Wa.number().optional(), layer: fv, port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional(), soldermask_margin_left: Wa.number().optional(), soldermask_margin_top: Wa.number().optional(), soldermask_margin_right: Wa.number().optional(), soldermask_margin_bottom: Wa.number().optional() });
var AI = Wa.object({ type: Wa.literal("pcb_smtpad"), shape: Wa.literal("rotated_rect"), pcb_smtpad_id: ex("pcb_smtpad"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: $b, y: $b, width: Wa.number(), height: Wa.number(), rect_border_radius: Wa.number().optional(), corner_radius: Wa.number().optional(), ccw_rotation: Gb, layer: fv, port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional(), soldermask_margin_left: Wa.number().optional(), soldermask_margin_top: Wa.number().optional(), soldermask_margin_right: Wa.number().optional(), soldermask_margin_bottom: Wa.number().optional() });
var OI = Wa.object({ type: Wa.literal("pcb_smtpad"), shape: Wa.literal("pill"), pcb_smtpad_id: ex("pcb_smtpad"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: $b, y: $b, width: Wa.number(), height: Wa.number(), radius: Wa.number(), layer: fv, port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });
var kI = Wa.object({ type: Wa.literal("pcb_smtpad"), shape: Wa.literal("rotated_pill"), pcb_smtpad_id: ex("pcb_smtpad"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: $b, y: $b, width: Wa.number(), height: Wa.number(), radius: Wa.number(), ccw_rotation: Gb, layer: fv, port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });
var DI = Wa.object({ type: Wa.literal("pcb_smtpad"), shape: Wa.literal("polygon"), pcb_smtpad_id: ex("pcb_smtpad"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), points: Wa.array(Zb), layer: fv, port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });
var LI = Wa.discriminatedUnion("shape", [TI, EI, AI, kI, OI, DI]).describe("Defines an SMT pad on the PCB");
var zI = Wa.object({ type: Wa.literal("pcb_solder_paste"), shape: Wa.literal("circle"), pcb_solder_paste_id: ex("pcb_solder_paste"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: $b, y: $b, radius: Wa.number(), layer: fv, pcb_component_id: Wa.string().optional(), pcb_smtpad_id: Wa.string().optional() });
var BI = Wa.object({ type: Wa.literal("pcb_solder_paste"), shape: Wa.literal("rect"), pcb_solder_paste_id: ex("pcb_solder_paste"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: $b, y: $b, width: Wa.number(), height: Wa.number(), layer: fv, pcb_component_id: Wa.string().optional(), pcb_smtpad_id: Wa.string().optional() });
var FI = Wa.object({ type: Wa.literal("pcb_solder_paste"), shape: Wa.literal("pill"), pcb_solder_paste_id: ex("pcb_solder_paste"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: $b, y: $b, width: Wa.number(), height: Wa.number(), radius: Wa.number(), layer: fv, pcb_component_id: Wa.string().optional(), pcb_smtpad_id: Wa.string().optional() });
var jI = Wa.object({ type: Wa.literal("pcb_solder_paste"), shape: Wa.literal("rotated_rect"), pcb_solder_paste_id: ex("pcb_solder_paste"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: $b, y: $b, width: Wa.number(), height: Wa.number(), ccw_rotation: $b, layer: fv, pcb_component_id: Wa.string().optional(), pcb_smtpad_id: Wa.string().optional() });
var $I = Wa.object({ type: Wa.literal("pcb_solder_paste"), shape: Wa.literal("oval"), pcb_solder_paste_id: ex("pcb_solder_paste"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: $b, y: $b, width: Wa.number(), height: Wa.number(), layer: fv, pcb_component_id: Wa.string().optional(), pcb_smtpad_id: Wa.string().optional() });
var YI = Wa.union([zI, BI, FI, jI, $I]).describe("Defines solderpaste on the PCB");
var XI = Wa.object({ type: Wa.literal("pcb_text"), pcb_text_id: ex("pcb_text"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), text: Wa.string(), center: Zb, layer: fv, width: Fb, height: Fb, lines: Wa.number(), align: Wa.enum(["bottom-left"]) }).describe("Defines text on the PCB");
var HI = Wa.object({ route_type: Wa.literal("wire"), x: $b, y: $b, width: $b, copper_pour_id: Wa.string().optional(), is_inside_copper_pour: Wa.boolean().optional(), start_pcb_port_id: Wa.string().optional(), end_pcb_port_id: Wa.string().optional(), layer: fv });
var VI = Wa.object({ route_type: Wa.literal("via"), x: $b, y: $b, copper_pour_id: Wa.string().optional(), is_inside_copper_pour: Wa.boolean().optional(), hole_diameter: $b.optional(), outer_diameter: $b.optional(), from_layer: fv, to_layer: fv });
var WI = Wa.union([HI, VI]);
var GI = Wa.object({ type: Wa.literal("pcb_trace"), source_trace_id: Wa.string().optional(), pcb_component_id: Wa.string().optional(), pcb_trace_id: ex("pcb_trace"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), route_thickness_mode: Wa.enum(["constant", "interpolated"]).default("constant").optional(), route_order_index: Wa.number().optional(), should_round_corners: Wa.boolean().optional(), trace_length: Wa.number().optional(), highlight_color: Wa.string().optional(), route: Wa.array(WI) }).describe("Defines a trace on the PCB");
var UI = Wa.object({ type: Wa.literal("pcb_trace_warning"), pcb_trace_warning_id: ex("pcb_trace_warning"), warning_type: Wa.literal("pcb_trace_warning").default("pcb_trace_warning"), message: Wa.string(), center: Zb.optional(), pcb_trace_id: Wa.string(), source_trace_id: Wa.string(), pcb_component_ids: Wa.array(Wa.string()), pcb_port_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe("Defines a trace warning on the PCB");
var ZI = bx.extend({ type: Wa.literal("pcb_trace_error"), pcb_trace_error_id: ex("pcb_trace_error"), error_type: Wa.literal("pcb_trace_error").default("pcb_trace_error"), center: Zb.optional(), pcb_trace_id: Wa.string(), source_trace_id: Wa.string(), pcb_component_ids: Wa.array(Wa.string()), pcb_port_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe("Defines a trace error on the PCB");
var qI = bx.extend({ type: Wa.literal("pcb_trace_missing_error"), pcb_trace_missing_error_id: ex("pcb_trace_missing_error"), error_type: Wa.literal("pcb_trace_missing_error").default("pcb_trace_missing_error"), center: Zb.optional(), source_trace_id: Wa.string(), pcb_component_ids: Wa.array(Wa.string()), pcb_port_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe("Defines an error when a source trace has no corresponding PCB trace");
var JI = bx.extend({ type: Wa.literal("pcb_port_not_matched_error"), pcb_error_id: ex("pcb_error"), error_type: Wa.literal("pcb_port_not_matched_error").default("pcb_port_not_matched_error"), pcb_component_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe("Defines a trace error on the PCB where a port is not matched");
var QI = bx.extend({ type: Wa.literal("pcb_port_not_connected_error"), pcb_port_not_connected_error_id: ex("pcb_port_not_connected_error"), error_type: Wa.literal("pcb_port_not_connected_error").default("pcb_port_not_connected_error"), pcb_port_ids: Wa.array(Wa.string()), pcb_component_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe("Defines an error when a pcb port is not connected to any trace");
var KI = Wa.object({ type: Wa.literal("pcb_net"), pcb_net_id: ex("pcb_net"), source_net_id: Wa.string().optional(), highlight_color: Wa.string().optional() }).describe("Defines a net on the PCB");
var eS = Wa.object({ type: Wa.literal("pcb_via"), pcb_via_id: ex("pcb_via"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), subcircuit_connectivity_map_key: Wa.string().optional(), x: $b, y: $b, outer_diameter: $b.default("0.6mm"), hole_diameter: $b.default("0.25mm"), from_layer: fv.optional(), to_layer: fv.optional(), layers: Wa.array(fv), pcb_trace_id: Wa.string().optional(), net_is_assignable: Wa.boolean().optional(), net_assigned: Wa.boolean().optional(), is_tented: Wa.boolean().optional() }).describe("Defines a via on the PCB");
var tS = Wa.object({ type: Wa.literal("pcb_board"), pcb_board_id: ex("pcb_board"), pcb_panel_id: Wa.string().optional(), carrier_pcb_board_id: Wa.string().optional(), is_subcircuit: Wa.boolean().optional(), subcircuit_id: Wa.string().optional(), is_mounted_to_carrier_board: Wa.boolean().optional(), width: Fb.optional(), height: Fb.optional(), center: Zb, display_offset_x: Wa.string().optional().describe("How to display the x offset for this board, usually corresponding with how the user specified it"), display_offset_y: Wa.string().optional().describe("How to display the y offset for this board, usually corresponding with how the user specified it"), thickness: Fb.optional().default(1.4), num_layers: Wa.number().optional().default(4), outline: Wa.array(Zb).optional(), shape: Wa.enum(["rect", "polygon"]).optional(), material: Wa.enum(["fr4", "fr1"]).default("fr4"), anchor_position: Zb.optional(), anchor_alignment: tx.optional(), position_mode: Wa.enum(["relative_to_panel_anchor", "none"]).optional() }).merge(aI).describe("Defines the board outline of the PCB");
var nS = Wa.object({ type: Wa.literal("pcb_panel"), pcb_panel_id: ex("pcb_panel"), width: Fb, height: Fb, center: Zb, thickness: Fb.optional().default(1.4), covered_with_solder_mask: Wa.boolean().optional().default(true) }).describe("Defines a PCB panel that can contain multiple boards");
var oS = bx.extend({ type: Wa.literal("pcb_placement_error"), pcb_placement_error_id: ex("pcb_placement_error"), error_type: Wa.literal("pcb_placement_error").default("pcb_placement_error"), subcircuit_id: Wa.string().optional() }).describe("Defines a placement error on the PCB");
var iS = bx.extend({ type: Wa.literal("pcb_panelization_placement_error"), pcb_panelization_placement_error_id: ex("pcb_panelization_placement_error"), error_type: Wa.literal("pcb_panelization_placement_error").default("pcb_panelization_placement_error"), pcb_panel_id: Wa.string().optional(), pcb_board_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe("Defines a panelization placement error on the PCB");
var rS = Wa.object({ type: Wa.literal("pcb_trace_hint"), pcb_trace_hint_id: ex("pcb_trace_hint"), pcb_port_id: Wa.string(), pcb_component_id: Wa.string(), route: Wa.array(sI), subcircuit_id: Wa.string().optional() }).describe("A hint that can be used during generation of a PCB trace");
var sS = Wa.object({ type: Wa.literal("pcb_silkscreen_line"), pcb_silkscreen_line_id: ex("pcb_silkscreen_line"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), stroke_width: $b.default("0.1mm"), x1: $b, y1: $b, x2: $b, y2: $b, layer: _v }).describe("Defines a silkscreen line on the PCB");
var aS = Wa.object({ type: Wa.literal("pcb_silkscreen_path"), pcb_silkscreen_path_id: ex("pcb_silkscreen_path"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), layer: _v, route: Wa.array(Zb), stroke_width: Fb }).describe("Defines a silkscreen path on the PCB");
var cS = Wa.object({ type: Wa.literal("pcb_silkscreen_text"), pcb_silkscreen_text_id: ex("pcb_silkscreen_text"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), font: Wa.literal("tscircuit2024").default("tscircuit2024"), font_size: $b.default("0.2mm"), pcb_component_id: Wa.string(), text: Wa.string(), is_knockout: Wa.boolean().default(false).optional(), knockout_padding: Wa.object({ left: Fb, top: Fb, bottom: Fb, right: Fb }).default({ left: "0.2mm", top: "0.2mm", bottom: "0.2mm", right: "0.2mm" }).optional(), ccw_rotation: Wa.number().optional(), layer: fv, is_mirrored: Wa.boolean().default(false).optional(), anchor_position: Zb.default({ x: 0, y: 0 }), anchor_alignment: tx.default("center") }).describe("Defines silkscreen text on the PCB");
var lS = Wa.object({ type: Wa.literal("pcb_copper_text"), pcb_copper_text_id: ex("pcb_copper_text"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), font: Wa.literal("tscircuit2024").default("tscircuit2024"), font_size: $b.default("0.2mm"), pcb_component_id: Wa.string(), text: Wa.string(), is_knockout: Wa.boolean().default(false).optional(), knockout_padding: Wa.object({ left: Fb, top: Fb, bottom: Fb, right: Fb }).default({ left: "0.2mm", top: "0.2mm", bottom: "0.2mm", right: "0.2mm" }).optional(), ccw_rotation: Wa.number().optional(), layer: fv, is_mirrored: Wa.boolean().default(false).optional(), anchor_position: Zb.default({ x: 0, y: 0 }), anchor_alignment: tx.default("center") }).describe("Defines copper text on the PCB");
var hS = Wa.object({ type: Wa.literal("pcb_silkscreen_rect"), pcb_silkscreen_rect_id: ex("pcb_silkscreen_rect"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: Zb, width: Fb, height: Fb, layer: fv, stroke_width: Fb.default("1mm"), corner_radius: Fb.optional(), is_filled: Wa.boolean().default(true).optional(), has_stroke: Wa.boolean().optional(), is_stroke_dashed: Wa.boolean().optional(), ccw_rotation: Wa.number().optional() }).describe("Defines a silkscreen rect on the PCB");
var dS = Wa.object({ type: Wa.literal("pcb_silkscreen_circle"), pcb_silkscreen_circle_id: ex("pcb_silkscreen_circle"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: Zb, radius: Fb, layer: _v, stroke_width: Fb.default("1mm"), is_filled: Wa.boolean().optional() }).describe("Defines a silkscreen circle on the PCB");
var uS = Wa.object({ type: Wa.literal("pcb_silkscreen_oval"), pcb_silkscreen_oval_id: ex("pcb_silkscreen_oval"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: Zb, radius_x: $b, radius_y: $b, layer: _v, ccw_rotation: Gb.optional() }).describe("Defines a silkscreen oval on the PCB");
var pS = Wa.object({ type: Wa.literal("pcb_silkscreen_pill"), pcb_silkscreen_pill_id: ex("pcb_silkscreen_pill"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: Zb, width: Fb, height: Fb, layer: fv, ccw_rotation: Wa.number().optional() }).describe("Defines a silkscreen pill on the PCB");
var mS = Wa.object({ type: Wa.literal("pcb_fabrication_note_text"), pcb_fabrication_note_text_id: ex("pcb_fabrication_note_text"), subcircuit_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), font: Wa.literal("tscircuit2024").default("tscircuit2024"), font_size: $b.default("1mm"), pcb_component_id: Wa.string(), text: Wa.string(), layer: _v, anchor_position: Zb.default({ x: 0, y: 0 }), anchor_alignment: Wa.enum(["center", "top_left", "top_right", "bottom_left", "bottom_right"]).default("center"), color: Wa.string().optional() }).describe("Defines a fabrication note in text on the PCB, useful for leaving notes for assemblers or fabricators");
var gS = Wa.object({ type: Wa.literal("pcb_fabrication_note_path"), pcb_fabrication_note_path_id: ex("pcb_fabrication_note_path"), pcb_component_id: Wa.string(), subcircuit_id: Wa.string().optional(), layer: fv, route: Wa.array(Zb), stroke_width: Fb, color: Wa.string().optional() }).describe("Defines a fabrication path on the PCB for fabricators or assemblers");
var fS = Wa.object({ type: Wa.literal("pcb_fabrication_note_rect"), pcb_fabrication_note_rect_id: ex("pcb_fabrication_note_rect"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: Zb, width: Fb, height: Fb, layer: _v, stroke_width: Fb.default("0.1mm"), corner_radius: Fb.optional(), is_filled: Wa.boolean().optional(), has_stroke: Wa.boolean().optional(), is_stroke_dashed: Wa.boolean().optional(), color: Wa.string().optional() }).describe("Defines a fabrication note rectangle on the PCB");
var _S = Wa.object({ type: Wa.literal("pcb_fabrication_note_dimension"), pcb_fabrication_note_dimension_id: ex("pcb_fabrication_note_dimension"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), layer: _v, from: Zb, to: Zb, text: Wa.string().optional(), text_ccw_rotation: Wa.number().optional(), offset: Fb.optional(), offset_distance: Fb.optional(), offset_direction: Wa.object({ x: Wa.number(), y: Wa.number() }).optional(), font: Wa.literal("tscircuit2024").default("tscircuit2024"), font_size: Fb.default("1mm"), color: Wa.string().optional(), arrow_size: Fb.default("1mm") }).describe("Defines a measurement annotation within PCB fabrication notes");
var yS = Wa.object({ type: Wa.literal("pcb_note_text"), pcb_note_text_id: ex("pcb_note_text"), pcb_component_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), name: Wa.string().optional(), font: Wa.literal("tscircuit2024").default("tscircuit2024"), font_size: $b.default("1mm"), text: Wa.string().optional(), anchor_position: Zb.default({ x: 0, y: 0 }), anchor_alignment: Wa.enum(["center", "top_left", "top_right", "bottom_left", "bottom_right"]).default("center"), layer: _v.default("top"), is_mirrored_from_top_view: Wa.boolean().optional(), color: Wa.string().optional() }).describe("Defines a documentation note in text on the PCB");
var bS = Wa.object({ type: Wa.literal("pcb_note_rect"), pcb_note_rect_id: ex("pcb_note_rect"), pcb_component_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), name: Wa.string().optional(), text: Wa.string().optional(), center: Zb, width: Fb, height: Fb, layer: _v.default("top"), stroke_width: Fb.default("0.1mm"), corner_radius: Fb.optional(), is_filled: Wa.boolean().optional(), has_stroke: Wa.boolean().optional(), is_stroke_dashed: Wa.boolean().optional(), color: Wa.string().optional() }).describe("Defines a rectangular documentation note on the PCB");
var xS = Wa.object({ type: Wa.literal("pcb_note_path"), pcb_note_path_id: ex("pcb_note_path"), pcb_component_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), name: Wa.string().optional(), text: Wa.string().optional(), route: Wa.array(Zb), layer: _v.default("top"), stroke_width: Fb.default("0.1mm"), color: Wa.string().optional() }).describe("Defines a polyline documentation note on the PCB");
var vS = Wa.object({ type: Wa.literal("pcb_note_line"), pcb_note_line_id: ex("pcb_note_line"), pcb_component_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), name: Wa.string().optional(), text: Wa.string().optional(), x1: $b, y1: $b, x2: $b, y2: $b, layer: _v.default("top"), stroke_width: $b.default("0.1mm"), color: Wa.string().optional(), is_dashed: Wa.boolean().optional() }).describe("Defines a straight documentation note line on the PCB");
var IS = Wa.object({ type: Wa.literal("pcb_note_dimension"), pcb_note_dimension_id: ex("pcb_note_dimension"), pcb_component_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), name: Wa.string().optional(), from: Zb, to: Zb, text: Wa.string().optional(), text_ccw_rotation: Wa.number().optional(), offset_distance: Fb.optional(), offset_direction: Wa.object({ x: Wa.number(), y: Wa.number() }).optional(), font: Wa.literal("tscircuit2024").default("tscircuit2024"), font_size: Fb.default("1mm"), layer: _v.default("top"), color: Wa.string().optional(), arrow_size: Fb.default("1mm") }).describe("Defines a measurement annotation within PCB documentation notes");
var SS = bx.extend({ type: Wa.literal("pcb_footprint_overlap_error"), pcb_error_id: ex("pcb_error"), error_type: Wa.literal("pcb_footprint_overlap_error").default("pcb_footprint_overlap_error"), pcb_smtpad_ids: Wa.array(Wa.string()).optional(), pcb_plated_hole_ids: Wa.array(Wa.string()).optional(), pcb_hole_ids: Wa.array(Wa.string()).optional(), pcb_keepout_ids: Wa.array(Wa.string()).optional() }).describe("Error emitted when a pcb footprint overlaps with another element");
var CS = bx.extend({ type: Wa.literal("pcb_courtyard_overlap_error"), pcb_error_id: ex("pcb_error"), error_type: Wa.literal("pcb_courtyard_overlap_error").default("pcb_courtyard_overlap_error"), pcb_component_ids: Wa.tuple([Wa.string(), Wa.string()]) }).describe("Error emitted when the courtyard (CrtYd) of one PCB component overlaps with the courtyard of another");
var PS = Wa.object({ type: Wa.literal("pcb_keepout"), shape: Wa.literal("rect"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: Zb, width: $b, height: $b, pcb_keepout_id: Wa.string(), layers: Wa.array(Wa.string()), description: Wa.string().optional() }).or(Wa.object({ type: Wa.literal("pcb_keepout"), shape: Wa.literal("circle"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: Zb, radius: $b, pcb_keepout_id: Wa.string(), layers: Wa.array(Wa.string()), description: Wa.string().optional() }));
var MS = Wa.object({ type: Wa.literal("pcb_cutout"), pcb_cutout_id: ex("pcb_cutout"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), pcb_board_id: Wa.string().optional(), pcb_panel_id: Wa.string().optional() });
var wS = MS.extend({ shape: Wa.literal("rect"), center: Zb, width: Fb, height: Fb, rotation: Gb.optional(), corner_radius: Fb.optional() });
var NS = MS.extend({ shape: Wa.literal("circle"), center: Zb, radius: Fb });
var RS = MS.extend({ shape: Wa.literal("polygon"), points: Wa.array(Zb) });
var TS = MS.extend({ shape: Wa.literal("path"), route: Wa.array(Zb), slot_width: Fb, slot_length: Fb.optional(), space_between_slots: Fb.optional(), slot_corner_radius: Fb.optional() });
var ES = Wa.discriminatedUnion("shape", [wS, NS, RS, TS]).describe("Defines a cutout on the PCB, removing board material.");
var AS = bx.extend({ type: Wa.literal("pcb_missing_footprint_error"), pcb_missing_footprint_error_id: ex("pcb_missing_footprint_error"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), error_type: Wa.literal("pcb_missing_footprint_error").default("pcb_missing_footprint_error"), source_component_id: Wa.string() }).describe("Defines a missing footprint error on the PCB");
var OS = bx.extend({ type: Wa.literal("external_footprint_load_error"), external_footprint_load_error_id: ex("external_footprint_load_error"), pcb_component_id: Wa.string(), source_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), footprinter_string: Wa.string().optional(), error_type: Wa.literal("external_footprint_load_error").default("external_footprint_load_error") }).describe("Defines an error when an external footprint fails to load");
var kS = bx.extend({ type: Wa.literal("circuit_json_footprint_load_error"), circuit_json_footprint_load_error_id: ex("circuit_json_footprint_load_error"), pcb_component_id: Wa.string(), source_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), error_type: Wa.literal("circuit_json_footprint_load_error").default("circuit_json_footprint_load_error"), circuit_json: Wa.array(Wa.any()).optional() }).describe("Defines an error when a circuit JSON footprint fails to load");
var DS = Wa.object({ type: Wa.literal("pcb_group"), pcb_group_id: ex("pcb_group"), source_group_id: Wa.string(), is_subcircuit: Wa.boolean().optional(), subcircuit_id: Wa.string().optional(), width: Fb.optional(), height: Fb.optional(), center: Zb, display_offset_x: Wa.string().optional().describe("How to display the x offset for this group, usually corresponding with how the user specified it"), display_offset_y: Wa.string().optional().describe("How to display the y offset for this group, usually corresponding with how the user specified it"), outline: Wa.array(Zb).optional(), anchor_position: Zb.optional(), anchor_alignment: tx.default("center"), position_mode: Wa.enum(["packed", "relative_to_group_anchor", "none"]).optional(), positioned_relative_to_pcb_group_id: Wa.string().optional(), positioned_relative_to_pcb_board_id: Wa.string().optional(), pcb_component_ids: Wa.array(Wa.string()), child_layout_mode: Wa.enum(["packed", "none"]).optional(), name: Wa.string().optional(), description: Wa.string().optional(), layout_mode: Wa.string().optional(), autorouter_configuration: Wa.object({ trace_clearance: Fb }).optional(), autorouter_used_string: Wa.string().optional() }).describe("Defines a group of components on the PCB");
var LS = bx.extend({ type: Wa.literal("pcb_autorouting_error"), pcb_error_id: ex("pcb_autorouting_error"), error_type: Wa.literal("pcb_autorouting_error").default("pcb_autorouting_error"), subcircuit_id: Wa.string().optional() }).describe("The autorouting has failed to route a portion of the board");
var zS = Wa.object({ type: Wa.literal("pcb_manual_edit_conflict_warning"), pcb_manual_edit_conflict_warning_id: ex("pcb_manual_edit_conflict_warning"), warning_type: Wa.literal("pcb_manual_edit_conflict_warning").default("pcb_manual_edit_conflict_warning"), message: Wa.string(), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), source_component_id: Wa.string() }).describe("Warning emitted when a component has both manual placement and explicit pcbX/pcbY coordinates");
var BS = Wa.enum(["x-", "x+", "y+", "y-"]);
var FS = Wa.object({ type: Wa.literal("pcb_connector_not_in_accessible_orientation_warning"), pcb_connector_not_in_accessible_orientation_warning_id: ex("pcb_connector_not_in_accessible_orientation_warning"), warning_type: Wa.literal("pcb_connector_not_in_accessible_orientation_warning").default("pcb_connector_not_in_accessible_orientation_warning"), message: Wa.string(), pcb_component_id: Wa.string(), source_component_id: Wa.string().optional(), pcb_board_id: Wa.string().optional(), facing_direction: BS, recommended_facing_direction: BS, subcircuit_id: Wa.string().optional() }).describe("Warning emitted when a connector PCB component is facing inward toward the board and should be reoriented to an outward-facing direction");
var jS = Wa.object({ type: Wa.literal("supplier_footprint_mismatch_warning"), supplier_footprint_mismatch_warning_id: ex("supplier_footprint_mismatch_warning"), warning_type: Wa.literal("supplier_footprint_mismatch_warning").default("supplier_footprint_mismatch_warning"), message: Wa.string(), source_component_id: Wa.string(), pcb_component_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), supplier_name: xx.optional(), supplier_part_number: Wa.string().optional(), supplier_footprint_url: Wa.string().optional(), footprint_copper_intersection_over_union: Wa.number() }).describe("Warning emitted when a supplier part footprint does not match the expected footprint");
var $S = Wa.object({ type: Wa.literal("pcb_breakout_point"), pcb_breakout_point_id: ex("pcb_breakout_point"), pcb_group_id: Wa.string(), subcircuit_id: Wa.string().optional(), source_trace_id: Wa.string().optional(), source_port_id: Wa.string().optional(), source_net_id: Wa.string().optional(), x: $b, y: $b }).describe("Defines a routing target within a pcb_group for a source_trace or source_net");
var YS = Wa.object({ type: Wa.literal("pcb_ground_plane"), pcb_ground_plane_id: ex("pcb_ground_plane"), source_pcb_ground_plane_id: Wa.string(), source_net_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe("Defines a ground plane on the PCB");
var XS = Wa.object({ type: Wa.literal("pcb_ground_plane_region"), pcb_ground_plane_region_id: ex("pcb_ground_plane_region"), pcb_ground_plane_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), layer: fv, points: Wa.array(Zb) }).describe("Defines a polygon region of a ground plane");
var HS = Wa.object({ type: Wa.literal("pcb_thermal_spoke"), pcb_thermal_spoke_id: ex("pcb_thermal_spoke"), pcb_ground_plane_id: Wa.string(), shape: Wa.string(), spoke_count: Wa.number(), spoke_thickness: $b, spoke_inner_diameter: $b, spoke_outer_diameter: $b, pcb_plated_hole_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe("Pattern for connecting a ground plane to a plated hole");
var VS = Wa.object({ type: Wa.literal("pcb_copper_pour"), pcb_copper_pour_id: ex("pcb_copper_pour"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), layer: fv, source_net_id: Wa.string().optional(), covered_with_solder_mask: Wa.boolean().optional().default(true) });
var WS = VS.extend({ shape: Wa.literal("rect"), center: Zb, width: Fb, height: Fb, rotation: Gb.optional() });
var GS = VS.extend({ shape: Wa.literal("brep"), brep_shape: oI });
var US = VS.extend({ shape: Wa.literal("polygon"), points: Wa.array(Zb) });
var ZS = Wa.discriminatedUnion("shape", [WS, GS, US]).describe("Defines a copper pour on the PCB.");
var qS = bx.extend({ type: Wa.literal("pcb_component_outside_board_error"), pcb_component_outside_board_error_id: ex("pcb_component_outside_board_error"), error_type: Wa.literal("pcb_component_outside_board_error").default("pcb_component_outside_board_error"), pcb_component_id: Wa.string(), pcb_board_id: Wa.string(), component_center: Zb, component_bounds: Wa.object({ min_x: Wa.number(), max_x: Wa.number(), min_y: Wa.number(), max_y: Wa.number() }), subcircuit_id: Wa.string().optional(), source_component_id: Wa.string().optional() }).describe("Error emitted when a PCB component is placed outside the board boundaries");
var JS = bx.extend({ type: Wa.literal("pcb_component_not_on_board_edge_error"), pcb_component_not_on_board_edge_error_id: ex("pcb_component_not_on_board_edge_error"), error_type: Wa.literal("pcb_component_not_on_board_edge_error").default("pcb_component_not_on_board_edge_error"), pcb_component_id: Wa.string(), pcb_board_id: Wa.string(), component_center: Zb, pad_to_nearest_board_edge_distance: Wa.number(), source_component_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe("Error emitted when a component that must be placed on the board edge is centered away from the edge");
var QS = bx.extend({ type: Wa.literal("pcb_component_invalid_layer_error"), pcb_component_invalid_layer_error_id: ex("pcb_component_invalid_layer_error"), error_type: Wa.literal("pcb_component_invalid_layer_error").default("pcb_component_invalid_layer_error"), pcb_component_id: Wa.string().optional(), source_component_id: Wa.string(), layer: fv, subcircuit_id: Wa.string().optional() }).describe("Error emitted when a component is placed on an invalid layer (components can only be on 'top' or 'bottom' layers)");
var KS = bx.extend({ type: Wa.literal("pcb_via_clearance_error"), pcb_error_id: ex("pcb_error"), error_type: Wa.literal("pcb_via_clearance_error").default("pcb_via_clearance_error"), pcb_via_ids: Wa.array(Wa.string()).min(2), minimum_clearance: $b.optional(), actual_clearance: $b.optional(), pcb_center: Wa.object({ x: Wa.number().optional(), y: Wa.number().optional() }).optional(), subcircuit_id: Wa.string().optional() }).describe("Error emitted when vias are closer than the allowed clearance");
var eC = bx.extend({ type: Wa.literal("pcb_via_trace_clearance_error"), pcb_via_trace_clearance_error_id: ex("pcb_via_trace_clearance_error"), error_type: Wa.literal("pcb_via_trace_clearance_error").default("pcb_via_trace_clearance_error"), pcb_via_id: Wa.string(), pcb_trace_id: Wa.string(), minimum_clearance: $b.optional(), actual_clearance: $b.optional(), center: Wa.object({ x: Wa.number().optional(), y: Wa.number().optional() }).optional(), subcircuit_id: Wa.string().optional() }).describe("Error emitted when a via and trace are closer than the allowed clearance");
var tC = bx.extend({ type: Wa.literal("pcb_pad_pad_clearance_error"), pcb_pad_pad_clearance_error_id: ex("pcb_pad_pad_clearance_error"), error_type: Wa.literal("pcb_pad_pad_clearance_error").default("pcb_pad_pad_clearance_error"), pcb_pad_ids: Wa.array(Wa.string()).min(2), minimum_clearance: $b.optional(), actual_clearance: $b.optional(), center: Wa.object({ x: Wa.number().optional(), y: Wa.number().optional() }).optional(), subcircuit_id: Wa.string().optional() }).describe("Error emitted when pads are closer than the allowed clearance");
var nC = bx.extend({ type: Wa.literal("pcb_pad_trace_clearance_error"), pcb_pad_trace_clearance_error_id: ex("pcb_pad_trace_clearance_error"), error_type: Wa.literal("pcb_pad_trace_clearance_error").default("pcb_pad_trace_clearance_error"), pcb_pad_id: Wa.string(), pcb_trace_id: Wa.string(), minimum_clearance: $b.optional(), actual_clearance: $b.optional(), center: Wa.object({ x: Wa.number().optional(), y: Wa.number().optional() }).optional(), subcircuit_id: Wa.string().optional() }).describe("Error emitted when a pad and trace are closer than allowed clearance");
var oC = Wa.object({ type: Wa.literal("pcb_courtyard_rect"), pcb_courtyard_rect_id: ex("pcb_courtyard_rect"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: Zb, width: Fb, height: Fb, layer: _v, ccw_rotation: Gb.optional(), color: Wa.string().optional() }).describe("Defines a courtyard rectangle on the PCB");
var iC = Wa.object({ type: Wa.literal("pcb_courtyard_outline"), pcb_courtyard_outline_id: ex("pcb_courtyard_outline"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), layer: _v, outline: Wa.array(Zb).min(2) }).describe("Defines a courtyard outline on the PCB");
var rC = Wa.object({ type: Wa.literal("pcb_courtyard_polygon"), pcb_courtyard_polygon_id: ex("pcb_courtyard_polygon"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), layer: _v, points: Wa.array(Zb).min(3), color: Wa.string().optional() }).describe("Defines a courtyard polygon on the PCB");
var sC = Wa.object({ type: Wa.literal("pcb_courtyard_circle"), pcb_courtyard_circle_id: ex("pcb_courtyard_circle"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: Zb, radius: Fb, layer: _v, color: Wa.string().optional() }).describe("Defines a courtyard circle on the PCB");
var aC = ["obj", "stl", "3mf", "gltf", "glb", "step", "wrl"];
var cC = ["x+", "x-", "y+", "y-", "z+", "z-"];
var lC = { obj: "z+", stl: "z+", "3mf": "z+", gltf: "y+", glb: "y+", step: "z+", wrl: "y+" };
var hC = Wa.object({ type: Wa.literal("cad_component"), cad_component_id: Wa.string(), pcb_component_id: Wa.string(), source_component_id: Wa.string(), position: Jb, rotation: Jb.optional(), size: Jb.optional(), layer: fv.optional(), subcircuit_id: Wa.string().optional(), footprinter_string: Wa.string().optional(), model_obj_url: Wa.string().optional(), model_stl_url: Wa.string().optional(), model_3mf_url: Wa.string().optional(), model_gltf_url: Wa.string().optional(), model_glb_url: Wa.string().optional(), model_step_url: Wa.string().optional(), model_wrl_url: Wa.string().optional(), model_asset: ox.optional(), model_unit_to_mm_scale_factor: Wa.number().optional(), model_board_normal_direction: Wa.enum(cC).optional().describe(`The direction in the model's coordinate space that is considered "up" or "coming out of the board surface"`), model_origin_position: Jb.optional(), model_origin_alignment: Wa.enum(["unknown", "center", "center_of_component_on_board_surface", "bottom_center_of_component"]).optional(), model_object_fit: Wa.enum(["contain_within_bounds", "fill_bounds"]).optional().default("contain_within_bounds"), model_jscad: Wa.any().optional(), show_as_translucent_model: Wa.boolean().optional(), anchor_alignment: Wa.enum(["center", "center_of_component_on_board_surface"]).optional().default("center") }).describe("Defines a component on the PCB");
var dC = Wa.enum(["sinewave", "square", "triangle", "sawtooth"]);
var uC = Wa.union([Wa.string(), Wa.number()]).transform((e35) => typeof e35 == "string" ? e35.endsWith("%") ? parseFloat(e35.slice(0, -1)) / 100 : parseFloat(e35) : e35).pipe(Wa.number().min(0, "Duty cycle must be non-negative").max(1, "Duty cycle cannot be greater than 100%"));
var pC = Wa.object({ type: Wa.literal("simulation_voltage_source"), simulation_voltage_source_id: ex("simulation_voltage_source"), is_dc_source: Wa.literal(true).optional().default(true), positive_source_port_id: Wa.string().optional(), negative_source_port_id: Wa.string().optional(), positive_source_net_id: Wa.string().optional(), negative_source_net_id: Wa.string().optional(), voltage: Bb }).describe("Defines a DC voltage source for simulation");
var mC = Wa.object({ type: Wa.literal("simulation_voltage_source"), simulation_voltage_source_id: ex("simulation_voltage_source"), is_dc_source: Wa.literal(false), terminal1_source_port_id: Wa.string().optional(), terminal2_source_port_id: Wa.string().optional(), terminal1_source_net_id: Wa.string().optional(), terminal2_source_net_id: Wa.string().optional(), voltage: Bb.optional(), frequency: jb.optional(), peak_to_peak_voltage: Bb.optional(), wave_shape: dC.optional(), phase: Gb.optional(), duty_cycle: uC.optional() }).describe("Defines an AC voltage source for simulation");
var gC = Wa.union([pC, mC]).describe("Defines a voltage source for simulation");
var fC = Wa.union([Wa.string(), Wa.number()]).transform((e35) => typeof e35 == "string" ? e35.endsWith("%") ? parseFloat(e35.slice(0, -1)) / 100 : parseFloat(e35) : e35).pipe(Wa.number().min(0, "Duty cycle must be non-negative").max(1, "Duty cycle cannot be greater than 100%"));
var _C = Wa.object({ type: Wa.literal("simulation_current_source"), simulation_current_source_id: ex("simulation_current_source"), is_dc_source: Wa.literal(true).optional().default(true), positive_source_port_id: Wa.string().optional(), negative_source_port_id: Wa.string().optional(), positive_source_net_id: Wa.string().optional(), negative_source_net_id: Wa.string().optional(), current: Yb }).describe("Defines a DC current source for simulation");
var yC = Wa.object({ type: Wa.literal("simulation_current_source"), simulation_current_source_id: ex("simulation_current_source"), is_dc_source: Wa.literal(false), terminal1_source_port_id: Wa.string().optional(), terminal2_source_port_id: Wa.string().optional(), terminal1_source_net_id: Wa.string().optional(), terminal2_source_net_id: Wa.string().optional(), current: Yb.optional(), frequency: jb.optional(), peak_to_peak_current: Yb.optional(), wave_shape: dC.optional(), phase: Gb.optional(), duty_cycle: fC.optional() }).describe("Defines an AC current source for simulation");
var bC = Wa.union([_C, yC]).describe("Defines a current source for simulation");
var xC = Wa.union([Wa.literal("spice_dc_sweep"), Wa.literal("spice_dc_operating_point"), Wa.literal("spice_transient_analysis"), Wa.literal("spice_ac_analysis")]);
var vC = Wa.object({ type: Wa.literal("simulation_experiment"), simulation_experiment_id: ex("simulation_experiment"), name: Wa.string(), experiment_type: xC, time_per_step: Xb.optional(), start_time_ms: Vb.optional(), end_time_ms: Vb.optional() }).describe("Defines a simulation experiment configuration");
var IC = Wa.object({ type: Wa.literal("simulation_transient_voltage_graph"), simulation_transient_voltage_graph_id: ex("simulation_transient_voltage_graph"), simulation_experiment_id: Wa.string(), timestamps_ms: Wa.array(Wa.number()).optional(), voltage_levels: Wa.array(Wa.number()), source_component_id: Wa.string().optional(), subcircuit_connectivity_map_key: Wa.string().optional(), time_per_step: Xb, start_time_ms: Vb, end_time_ms: Vb, name: Wa.string().optional(), color: Wa.string().optional() }).describe("Stores voltage measurements over time for a simulation");
var SC = Wa.object({ type: Wa.literal("simulation_switch"), simulation_switch_id: ex("simulation_switch"), source_component_id: Wa.string().optional(), closes_at: Vb.optional(), opens_at: Vb.optional(), starts_closed: Wa.boolean().optional(), switching_frequency: jb.optional() }).describe("Defines a switch for simulation timing control");
var CC = Wa.object({ type: Wa.literal("simulation_voltage_probe"), simulation_voltage_probe_id: ex("simulation_voltage_probe"), source_component_id: Wa.string().optional(), name: Wa.string().optional(), signal_input_source_port_id: Wa.string().optional(), signal_input_source_net_id: Wa.string().optional(), reference_input_source_port_id: Wa.string().optional(), reference_input_source_net_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), color: Wa.string().optional() }).describe("Defines a voltage probe for simulation. If a reference input is not provided, it measures against ground. If a reference input is provided, it measures the differential voltage between two points.").superRefine((e35, t2) => {
  if (e35.reference_input_source_port_id || e35.reference_input_source_net_id) {
    const n2 = !!e35.signal_input_source_port_id || !!e35.reference_input_source_port_id, o3 = !!e35.signal_input_source_net_id || !!e35.reference_input_source_net_id;
    n2 && o3 ? t2.addIssue({ code: Wa.ZodIssueCode.custom, message: "Cannot mix port and net connections in a differential probe." }) : n2 ? e35.signal_input_source_port_id && e35.reference_input_source_port_id || t2.addIssue({ code: Wa.ZodIssueCode.custom, message: "Differential port probe requires both signal_input_source_port_id and reference_input_source_port_id." }) : o3 && (e35.signal_input_source_net_id && e35.reference_input_source_net_id || t2.addIssue({ code: Wa.ZodIssueCode.custom, message: "Differential net probe requires both signal_input_source_net_id and reference_input_source_net_id." }));
  } else
    !!e35.signal_input_source_port_id == !!e35.signal_input_source_net_id && t2.addIssue({ code: Wa.ZodIssueCode.custom, message: "A voltage probe must have exactly one of signal_input_source_port_id or signal_input_source_net_id." });
});
var PC = bx.extend({ type: Wa.literal("simulation_unknown_experiment_error"), simulation_unknown_experiment_error_id: ex("simulation_unknown_experiment_error"), error_type: Wa.literal("simulation_unknown_experiment_error").default("simulation_unknown_experiment_error"), simulation_experiment_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe("An unknown error occurred during the simulation experiment.");
var MC = Wa.object({ type: Wa.literal("simulation_op_amp"), simulation_op_amp_id: ex("simulation_op_amp"), source_component_id: Wa.string().optional(), inverting_input_source_port_id: Wa.string(), non_inverting_input_source_port_id: Wa.string(), output_source_port_id: Wa.string(), positive_supply_source_port_id: Wa.string(), negative_supply_source_port_id: Wa.string() }).describe("Defines a simple ideal operational amplifier for simulation");
var wC = Wa.union([cv, sv, av, rv, hv, lv, Nx, Ix, Cx, Mx, Sx, Rx, Ox, kx, Bx, jx, $x, Wx, Yx, Xx, Hx, Vx, Lx, Dx, pv, yv, dv, Gx, qx, Jx, Kx, ev, bv, xv, vv, Iv, Sv, ov, uv, cI, vI, AS, OS, kS, zS, FS, jS, NI, PS, RI, KI, XI, GI, UI, eS, LI, YI, tS, nS, DS, rS, sS, aS, cS, pS, lS, hS, dS, uS, ZI, qI, oS, iS, JI, QI, KS, eC, tC, nC, gS, mS, fS, _S, yS, bS, xS, vS, IS, LS, SS, CS, $S, ES, YS, XS, HS, ZS, qS, JS, QS, oC, iC, rC, sC, Cv, Fv, Ov, kv, Dv, Lv, Tv, Av, jv, zv, Pv, Yv, Xv, $v, Uv, Zv, qv, Jv, eI, Qv, Kv, hC, gC, bC, vC, IC, SC, CC, PC, MC]);
var NC = wC;
function RC(e35, t2, n2) {
  if (!t2 || !n2)
    return;
  let o3 = e35.get(t2);
  o3 || (o3 = new Set, e35.set(t2, o3)), o3.add(n2);
  let i3 = e35.get(n2);
  i3 || (i3 = new Set, e35.set(n2, i3)), i3.add(t2);
}
var TC = (e35, t2 = {}) => {
  const n2 = e35;
  let o3 = n2._internal_store;
  if (!o3) {
    o3 = { counts: {}, editCount: 0 }, n2._internal_store = o3;
    for (const e36 of n2) {
      const t3 = e36.type, n3 = e36[`${t3}_id`];
      if (!n3)
        continue;
      const i4 = Number.parseInt(n3.split("_").pop());
      Number.isNaN(i4) || (o3.counts[t3] = Math.max(o3.counts[t3] ?? 0, i4));
    }
  }
  const i3 = new Proxy({}, { get: (e36, r3) => {
    if (r3 === "toArray")
      return () => (n2.editCount = o3.editCount, n2);
    if (r3 === "editCount")
      return o3.editCount;
    if (r3 === "subtree")
      return (e37) => TC(function(e38, t3) {
        if (!t3.subcircuit_id && !t3.source_group_id)
          return [...e38];
        let n3 = t3;
        if (t3.subcircuit_id) {
          const o5 = new Set([t3.subcircuit_id]), i5 = new Map, r5 = new Map;
          for (const t4 of e38)
            if (t4.type === "source_group") {
              const { source_group_id: e39, subcircuit_id: n4 } = t4;
              n4 && r5.set(e39, n4);
              const o6 = t4.parent_source_group_id;
              o6 && (i5.has(o6) || i5.set(o6, []), i5.get(o6).push(e39));
            }
          let s4;
          for (const [e39, n4] of r5)
            if (n4 === t3.subcircuit_id) {
              s4 = e39;
              break;
            }
          if (s4) {
            const e39 = (t4) => {
              const n4 = i5.get(t4) || [];
              for (const t5 of n4) {
                const n5 = r5.get(t5);
                n5 && o5.add(n5), e39(t5);
              }
            };
            e39(s4), n3 = { ...t3, subcircuit_ids: Array.from(o5) };
          }
        }
        const o4 = new Map;
        for (const t4 of e38) {
          const e39 = t4[`${t4.type}_id`];
          typeof e39 == "string" && o4.set(e39, t4);
        }
        const i4 = new Map;
        for (const t4 of e38) {
          const e39 = Object.entries(t4);
          for (const [n4, r5] of e39)
            if (n4 !== "parent_source_group_id") {
              if (n4.endsWith("_id") && typeof r5 == "string")
                RC(i4, t4, o4.get(r5));
              else if (n4.endsWith("_ids") && Array.isArray(r5))
                for (const e40 of r5)
                  typeof e40 == "string" && RC(i4, t4, o4.get(e40));
            }
        }
        const r4 = [], s3 = new Set;
        for (const t4 of e38) {
          let e39 = false;
          (n3.subcircuit_id && ("subcircuit_id" in t4) && t4.subcircuit_id === n3.subcircuit_id || n3.subcircuit_ids && ("subcircuit_id" in t4) && t4.subcircuit_id && n3.subcircuit_ids.includes(t4.subcircuit_id) || n3.source_group_id && ("source_group_id" in t4) && t4.source_group_id === n3.source_group_id || n3.source_group_id && ("member_source_group_ids" in t4) && Array.isArray(t4.member_source_group_ids) && t4.member_source_group_ids.includes(n3.source_group_id)) && (e39 = true), e39 && (r4.push(t4), s3.add(t4));
        }
        for (;r4.length > 0; ) {
          const e39 = r4.shift(), t4 = i4.get(e39);
          if (t4)
            for (const e40 of t4)
              s3.has(e40) || (s3.add(e40), r4.push(e40));
        }
        return e38.filter((e39) => s3.has(e39));
      }(n2, e37), t2);
    if (r3 === "insert")
      return (e37) => {
        const i4 = e37.type;
        if (!i4)
          throw new Error("insert requires an element with a type");
        o3.counts[i4] ??= -1, o3.counts[i4]++;
        const r4 = o3.counts[i4], s3 = { ...e37, type: i4, [`${i4}_id`]: `${i4}_${r4}` };
        if (t2.validateInserts) {
          (Tb[i4] ?? NC).parse(s3);
        }
        return n2.push(s3), o3.editCount++, s3;
      };
    if (r3 === "insertAll")
      return (e37) => e37.map((e38) => i3.insert(e38));
    const s2 = r3;
    return { get: (e37) => n2.find((t3) => t3.type === s2 && t3[`${s2}_id`] === e37), getUsing: (e37) => {
      const t3 = Object.keys(e37);
      if (t3.length !== 1)
        throw new Error("getUsing requires exactly one key, e.g. { pcb_component_id }");
      const o4 = t3[0], i4 = o4.replace("_id", ""), r4 = n2.find((t4) => t4.type === i4 && t4[o4] === e37[o4]);
      return r4 ? n2.find((e38) => e38.type === s2 && e38[`${s2}_id`] === r4[`${s2}_id`]) : null;
    }, getWhere: (e37) => {
      const t3 = Object.keys(e37);
      return n2.find((n3) => n3.type === s2 && t3.every((t4) => n3[t4] === e37[t4]));
    }, list: (e37) => {
      const t3 = e37 ? Object.keys(e37) : [];
      return n2.filter((n3) => n3.type === s2 && t3.every((t4) => n3[t4] === e37[t4]));
    }, insert: (e37) => {
      o3.counts[s2] ??= -1, o3.counts[s2]++;
      const i4 = o3.counts[s2], r4 = { type: s2, [`${s2}_id`]: `${s2}_${i4}`, ...e37 };
      if (t2.validateInserts) {
        (Tb[s2] ?? NC).parse(r4);
      }
      return n2.push(r4), o3.editCount++, r4;
    }, delete: (e37) => {
      const t3 = n2.find((t4) => t4[`${s2}_id`] === e37);
      t3 && (n2.splice(n2.indexOf(t3), 1), o3.editCount++);
    }, update: (e37, t3) => {
      const i4 = n2.find((t4) => t4.type === s2 && t4[`${s2}_id`] === e37);
      return i4 ? (Object.assign(i4, t3), o3.editCount++, i4) : null;
    }, select: (e37) => {
      if (s2 === "source_component")
        return n2.find((t3) => t3.type === "source_component" && t3.name === e37.replace(/\./g, ""));
      if (s2 === "pcb_port" || s2 === "source_port" || s2 === "schematic_port") {
        const [t3, o4] = e37.replace(/\./g, "").split(/[\s\>]+/), i4 = n2.find((e38) => e38.type === "source_component" && e38.name === t3);
        if (!i4)
          return null;
        const r4 = n2.find((e38) => e38.type === "source_port" && e38.source_component_id === i4.source_component_id && (e38.name === o4 || (e38.port_hints ?? []).includes(o4)));
        if (!r4)
          return null;
        if (s2 === "source_port")
          return r4;
        if (s2 === "pcb_port")
          return n2.find((e38) => e38.type === "pcb_port" && e38.source_port_id === r4.source_port_id);
        if (s2 === "schematic_port")
          return n2.find((e38) => e38.type === "schematic_port" && e38.source_port_id === r4.source_port_id);
      }
    } };
  } });
  return i3;
};
TC.unparsed = TC;
var EC = TC;
function AC(e35) {
  const t2 = e35.type;
  return `${t2}:${e35[`${t2}_id`]}`;
}
var OC = (e35, t2 = {}) => {
  let n2 = e35._internal_store_indexed;
  if (!n2) {
    n2 = { counts: {}, editCount: 0, indexes: {} };
    for (const t3 of e35) {
      const e36 = t3.type, o4 = t3[`${e36}_id`];
      if (!o4)
        continue;
      const i4 = Number.parseInt(o4.split("_").pop() || "");
      Number.isNaN(i4) || (n2.counts[e36] = Math.max(n2.counts[e36] ?? 0, i4));
    }
    const o3 = t2.indexConfig || {}, i3 = n2.indexes;
    if (o3.byId && (i3.byId = new Map), o3.byType && (i3.byType = new Map), o3.byRelation && (i3.byRelation = new Map), o3.bySubcircuit && (i3.bySubcircuit = new Map), o3.byCustomField && o3.byCustomField.length > 0) {
      i3.byCustomField = new Map;
      for (const e36 of o3.byCustomField)
        i3.byCustomField.set(e36, new Map);
    }
    for (const t3 of e35) {
      if (o3.byId) {
        const e36 = AC(t3);
        i3.byId.set(e36, t3);
      }
      if (o3.byType) {
        const e36 = i3.byType.get(t3.type) || [];
        e36.push(t3), i3.byType.set(t3.type, e36);
      }
      if (o3.byRelation) {
        const e36 = Object.entries(t3);
        for (const [n3, o4] of e36)
          if (n3.endsWith("_id") && n3 !== `${t3.type}_id` && typeof o4 == "string") {
            const e37 = i3.byRelation.get(n3) || new Map, r3 = e37.get(o4) || [];
            r3.push(t3), e37.set(o4, r3), i3.byRelation.set(n3, e37);
          }
      }
      if (o3.bySubcircuit && "subcircuit_id" in t3) {
        const e36 = t3.subcircuit_id;
        if (e36 && typeof e36 == "string") {
          const n3 = i3.bySubcircuit.get(e36) || [];
          n3.push(t3), i3.bySubcircuit.set(e36, n3);
        }
      }
      if (o3.byCustomField && i3.byCustomField) {
        for (const e36 of o3.byCustomField)
          if (e36 in t3) {
            const n3 = t3[e36];
            if (n3 !== undefined && (typeof n3 == "string" || typeof n3 == "number")) {
              const o4 = String(n3), r3 = i3.byCustomField.get(e36), s2 = r3.get(o4) || [];
              s2.push(t3), r3.set(o4, s2);
            }
          }
      }
    }
    e35._internal_store_indexed = n2;
  }
  return new Proxy({}, { get: (o3, i3) => {
    if (i3 === "toArray")
      return () => (e35.editCount = n2.editCount, e35);
    if (i3 === "editCount")
      return n2.editCount;
    const r3 = i3;
    return { get: (o4) => {
      const i4 = t2.indexConfig || {};
      if (i4.byId && n2.indexes.byId)
        return n2.indexes.byId.get(`${r3}:${o4}`) || null;
      if (i4.byType && n2.indexes.byType) {
        return (n2.indexes.byType.get(r3) || []).find((e36) => e36[`${r3}_id`] === o4) || null;
      }
      return e35.find((e36) => e36.type === r3 && e36[`${r3}_id`] === o4) || null;
    }, getUsing: (o4) => {
      const i4 = t2.indexConfig || {}, s2 = Object.keys(o4);
      if (s2.length !== 1)
        throw new Error("getUsing requires exactly one key, e.g. { pcb_component_id }");
      const a3 = s2[0], c3 = a3.replace("_id", "");
      if (i4.byRelation && n2.indexes.byRelation) {
        const t3 = n2.indexes.byRelation.get(a3);
        if (t3) {
          const s3 = (t3.get(o4[a3]) || []).find((e36) => e36.type === c3);
          if (!s3)
            return null;
          const l4 = s3[`${r3}_id`];
          if (i4.byId && n2.indexes.byId)
            return n2.indexes.byId.get(`${r3}:${l4}`) || null;
          if (i4.byType && n2.indexes.byType) {
            return (n2.indexes.byType.get(r3) || []).find((e36) => e36[`${r3}_id`] === l4) || null;
          }
          return e35.find((e36) => e36.type === r3 && e36[`${r3}_id`] === l4) || null;
        }
      }
      const l3 = e35.find((e36) => e36.type === c3 && e36[a3] === o4[a3]);
      return l3 && e35.find((e36) => e36.type === r3 && e36[`${r3}_id`] === l3[`${r3}_id`]) || null;
    }, getWhere: (o4) => {
      const i4 = t2.indexConfig || {}, s2 = Object.keys(o4);
      if (s2.length === 1 && i4.byCustomField && n2.indexes.byCustomField) {
        const e36 = s2[0], t3 = n2.indexes.byCustomField.get(e36);
        if (t3) {
          const n3 = String(o4[e36]);
          return (t3.get(n3) || []).find((e37) => e37.type === r3) || null;
        }
      }
      if ("subcircuit_id" in o4 && i4.bySubcircuit && n2.indexes.bySubcircuit) {
        const e36 = o4.subcircuit_id;
        return (n2.indexes.bySubcircuit.get(e36) || []).find((e37) => e37.type === r3 && s2.every((t3) => e37[t3] === o4[t3])) || null;
      }
      if (i4.byType && n2.indexes.byType) {
        return (n2.indexes.byType.get(r3) || []).find((e36) => s2.every((t3) => e36[t3] === o4[t3])) || null;
      }
      return e35.find((e36) => e36.type === r3 && s2.every((t3) => e36[t3] === o4[t3])) || null;
    }, list: (o4) => {
      const i4 = t2.indexConfig || {}, s2 = o4 ? Object.keys(o4) : [];
      if (s2.length === 0 && i4.byType && n2.indexes.byType)
        return n2.indexes.byType.get(r3) || [];
      if (s2.length === 1 && s2[0] === "subcircuit_id" && i4.bySubcircuit && n2.indexes.bySubcircuit) {
        const e36 = o4.subcircuit_id;
        return (n2.indexes.bySubcircuit.get(e36) || []).filter((e37) => e37.type === r3);
      }
      let a3;
      return a3 = i4.byType && n2.indexes.byType ? n2.indexes.byType.get(r3) || [] : e35.filter((e36) => e36.type === r3), s2.length > 0 ? a3.filter((e36) => s2.every((t3) => e36[t3] === o4[t3])) : a3;
    }, insert: (o4) => {
      n2.counts[r3] ??= -1, n2.counts[r3]++;
      const i4 = n2.counts[r3], s2 = { type: r3, [`${r3}_id`]: `${r3}_${i4}`, ...o4 };
      if (t2.validateInserts) {
        (Tb[r3] ?? NC).parse(s2);
      }
      e35.push(s2), n2.editCount++;
      const a3 = t2.indexConfig || {};
      if (a3.byId && n2.indexes.byId) {
        const e36 = AC(s2);
        n2.indexes.byId.set(e36, s2);
      }
      if (a3.byType && n2.indexes.byType) {
        const e36 = n2.indexes.byType.get(r3) || [];
        e36.push(s2), n2.indexes.byType.set(r3, e36);
      }
      if (a3.byRelation && n2.indexes.byRelation) {
        const e36 = Object.entries(s2);
        for (const [t3, o5] of e36)
          if (t3.endsWith("_id") && t3 !== `${s2.type}_id` && typeof o5 == "string") {
            const e37 = n2.indexes.byRelation.get(t3) || new Map, i5 = e37.get(o5) || [];
            i5.push(s2), e37.set(o5, i5), n2.indexes.byRelation.set(t3, e37);
          }
      }
      if (a3.bySubcircuit && n2.indexes.bySubcircuit && "subcircuit_id" in s2) {
        const e36 = s2.subcircuit_id;
        if (e36 && typeof e36 == "string") {
          const t3 = n2.indexes.bySubcircuit.get(e36) || [];
          t3.push(s2), n2.indexes.bySubcircuit.set(e36, t3);
        }
      }
      if (a3.byCustomField && n2.indexes.byCustomField) {
        for (const e36 of a3.byCustomField)
          if (e36 in s2) {
            const t3 = s2[e36];
            if (t3 !== undefined && (typeof t3 == "string" || typeof t3 == "number")) {
              const o5 = String(t3), i5 = n2.indexes.byCustomField.get(e36), r4 = i5.get(o5) || [];
              r4.push(s2), i5.set(o5, r4);
            }
          }
      }
      return s2;
    }, delete: (o4) => {
      const i4 = t2.indexConfig || {};
      let s2;
      if (i4.byId && n2.indexes.byId)
        s2 = n2.indexes.byId.get(`${r3}:${o4}`);
      else if (i4.byType && n2.indexes.byType) {
        const e36 = n2.indexes.byType.get(r3) || [];
        s2 = e36.find((e37) => e37[`${r3}_id`] === o4);
      } else
        s2 = e35.find((e36) => e36[`${r3}_id`] === o4);
      if (!s2)
        return;
      const a3 = e35.indexOf(s2);
      if (a3 >= 0 && (e35.splice(a3, 1), n2.editCount++), i4.byId && n2.indexes.byId) {
        const e36 = AC(s2);
        n2.indexes.byId.delete(e36);
      }
      if (i4.byType && n2.indexes.byType) {
        const e36 = (n2.indexes.byType.get(r3) || []).filter((e37) => e37[`${r3}_id`] !== o4);
        n2.indexes.byType.set(r3, e36);
      }
      if (i4.byRelation && n2.indexes.byRelation)
        for (const [e36, t3] of n2.indexes.byRelation.entries())
          for (const [e37, n3] of t3.entries()) {
            const o5 = n3.filter((e38) => e38 !== s2);
            o5.length === 0 ? t3.delete(e37) : t3.set(e37, o5);
          }
      if (i4.bySubcircuit && n2.indexes.bySubcircuit && "subcircuit_id" in s2) {
        const e36 = s2.subcircuit_id;
        if (e36) {
          const t3 = (n2.indexes.bySubcircuit.get(e36) || []).filter((e37) => e37 !== s2);
          t3.length === 0 ? n2.indexes.bySubcircuit.delete(e36) : n2.indexes.bySubcircuit.set(e36, t3);
        }
      }
      if (i4.byCustomField && n2.indexes.byCustomField)
        for (const e36 of n2.indexes.byCustomField.values())
          for (const [t3, n3] of e36.entries()) {
            const o5 = n3.filter((e37) => e37 !== s2);
            o5.length === 0 ? e36.delete(t3) : e36.set(t3, o5);
          }
    }, update: (o4, i4) => {
      const s2 = t2.indexConfig || {};
      let a3;
      if (s2.byId && n2.indexes.byId)
        a3 = n2.indexes.byId.get(`${r3}:${o4}`);
      else if (s2.byType && n2.indexes.byType) {
        const e36 = n2.indexes.byType.get(r3) || [];
        a3 = e36.find((e37) => e37[`${r3}_id`] === o4);
      } else
        a3 = e35.find((e36) => e36.type === r3 && e36[`${r3}_id`] === o4);
      if (!a3)
        return null;
      if (s2.byRelation && n2.indexes.byRelation) {
        const e36 = Object.entries(a3);
        for (const [t3, o5] of e36)
          if (t3.endsWith("_id") && t3 !== `${a3.type}_id` && typeof o5 == "string" && t3 in i4 && i4[t3] !== o5) {
            const e37 = n2.indexes.byRelation.get(t3);
            if (e37) {
              const t4 = (e37.get(o5) || []).filter((e38) => e38 !== a3);
              t4.length === 0 ? e37.delete(o5) : e37.set(o5, t4);
            }
          }
      }
      if (s2.bySubcircuit && n2.indexes.bySubcircuit && "subcircuit_id" in a3 && "subcircuit_id" in i4) {
        const e36 = a3.subcircuit_id;
        if (e36 !== i4.subcircuit_id) {
          const t3 = (n2.indexes.bySubcircuit.get(e36) || []).filter((e37) => e37 !== a3);
          t3.length === 0 ? n2.indexes.bySubcircuit.delete(e36) : n2.indexes.bySubcircuit.set(e36, t3);
        }
      }
      if (s2.byCustomField && n2.indexes.byCustomField) {
        for (const e36 of s2.byCustomField)
          if (e36 in a3 && e36 in i4 && a3[e36] !== i4[e36]) {
            const t3 = n2.indexes.byCustomField.get(e36);
            if (t3) {
              const n3 = String(a3[e36]), o5 = (t3.get(n3) || []).filter((e37) => e37 !== a3);
              o5.length === 0 ? t3.delete(n3) : t3.set(n3, o5);
            }
          }
      }
      if (Object.assign(a3, i4), n2.editCount++, s2.byRelation && n2.indexes.byRelation) {
        const e36 = Object.entries(a3);
        for (const [t3, o5] of e36)
          if (t3.endsWith("_id") && t3 !== `${a3.type}_id` && typeof o5 == "string" && t3 in i4) {
            const e37 = n2.indexes.byRelation.get(t3) || new Map, i5 = e37.get(o5) || [];
            i5.includes(a3) || (i5.push(a3), e37.set(o5, i5), n2.indexes.byRelation.set(t3, e37));
          }
      }
      if (s2.bySubcircuit && n2.indexes.bySubcircuit && "subcircuit_id" in a3 && "subcircuit_id" in i4) {
        const e36 = a3.subcircuit_id;
        if (e36 && typeof e36 == "string") {
          const t3 = n2.indexes.bySubcircuit.get(e36) || [];
          t3.includes(a3) || (t3.push(a3), n2.indexes.bySubcircuit.set(e36, t3));
        }
      }
      if (s2.byCustomField && n2.indexes.byCustomField) {
        for (const e36 of s2.byCustomField)
          if (e36 in a3 && e36 in i4) {
            const t3 = a3[e36];
            if (t3 !== undefined && (typeof t3 == "string" || typeof t3 == "number")) {
              const o5 = String(t3), i5 = n2.indexes.byCustomField.get(e36), r4 = i5.get(o5) || [];
              r4.includes(a3) || (r4.push(a3), i5.set(o5, r4));
            }
          }
      }
      return a3;
    }, select: (t3) => {
      if (r3 === "source_component")
        return e35.find((e36) => e36.type === "source_component" && e36.name === t3.replace(/\./g, "")) || null;
      if (r3 === "pcb_port" || r3 === "source_port" || r3 === "schematic_port") {
        const [n3, o4] = t3.replace(/\./g, "").split(/[\s\>]+/), i4 = e35.find((e36) => e36.type === "source_component" && e36.name === n3);
        if (!i4)
          return null;
        const s2 = e35.find((e36) => e36.type === "source_port" && e36.source_component_id === i4.source_component_id && (e36.name === o4 || (e36.port_hints ?? []).includes(o4)));
        if (!s2)
          return null;
        if (r3 === "source_port")
          return s2;
        if (r3 === "pcb_port")
          return e35.find((e36) => e36.type === "pcb_port" && e36.source_port_id === s2.source_port_id) || null;
        if (r3 === "schematic_port")
          return e35.find((e36) => e36.type === "schematic_port" && e36.source_port_id === s2.source_port_id) || null;
      }
      return null;
    } };
  } });
};
OC.unparsed = OC;
var kC = (e35) => e35[`${e35.type}_id`];
function DC(e35, t2) {
  const n2 = TC(e35).pcb_trace.get(t2);
  if (!n2)
    return `trace[${t2}]`;
  const o3 = n2.route.flatMap((e36) => [e36.start_pcb_port_id, e36.end_pcb_port_id]).filter(Boolean);
  if (o3.length === 0)
    return `trace[${t2}]`;
  return `trace[${o3.map((t3) => {
    const n3 = function(t4) {
      const n4 = TC(e35).pcb_port.get(t4);
      if (!n4)
        return null;
      const o4 = n4.pcb_component_id ? TC(e35).pcb_component.get(n4.pcb_component_id) : undefined;
      if (!o4)
        return null;
      const i3 = TC(e35).source_component.get(o4.source_component_id);
      if (!i3)
        return null;
      const r3 = TC(e35).source_port.get(n4.source_port_id), s2 = r3?.port_hints ? r3.port_hints[1] : "";
      return { componentName: i3.name, portHint: s2 };
    }(t3);
    return n3 ? `.${n3.componentName} > port.${n3.portHint}` : `port[${t3}]`;
  }).join(", ")}]`;
}
var LC = (e35, t2) => {
  const n2 = TC(e35).pcb_port.get(t2);
  if (!n2)
    return `pcb_port[#${t2}]`;
  const o3 = n2.pcb_component_id ? TC(e35).pcb_component.get(n2.pcb_component_id) : undefined;
  if (!o3)
    return `pcb_port[#${t2}]`;
  const i3 = TC(e35).source_component.get(o3.source_component_id);
  if (!i3)
    return `pcb_port[#${t2}]`;
  const r3 = TC(e35).source_port.get(n2.source_port_id);
  if (!r3)
    return `pcb_port[#${t2}]`;
  let s2;
  return s2 = r3?.port_hints && r3.port_hints.length > 0 || r3.port_hints && r3.port_hints.length > 0 ? r3.port_hints[0] : t2, `pcb_port[.${i3.name} > .${s2}]`;
};
var zC = (e35, t2) => {
  if (typeof t2 == "string") {
    const n2 = ((e36, t3) => e36.find((e37) => kC(e37) === t3) ?? null)(e35, t2);
    return zC(e35, n2);
  }
  switch (t2.type) {
    case "pcb_port":
      return LC(e35, t2.pcb_port_id);
    case "pcb_smtpad":
      return function(e36, t3) {
        const n2 = TC(e36).pcb_smtpad.get(t3);
        return n2 && n2.pcb_port_id ? LC(e36, n2.pcb_port_id) : `smtpad[${t3}]`;
      }(e35, t2.pcb_smtpad_id);
    case "pcb_trace":
      return DC(e35, t2.pcb_trace_id);
    case "source_component":
      return `source_component[${t2.name}]`;
    default:
      return `${t2.type}[#${kC(t2)}]`;
  }
};
var BC = (e35, t2) => ({ minX: Math.min(e35.minX, t2.minX), minY: Math.min(e35.minY, t2.minY), maxX: Math.max(e35.maxX, t2.maxX), maxY: Math.max(e35.maxY, t2.maxY) });
var FC = (e35, t2, n2) => {
  const o3 = n2 / 2;
  return { minX: e35 - o3, minY: t2 - o3, maxX: e35 + o3, maxY: t2 + o3 };
};
var jC = (e35, t2, n2, o3, i3) => {
  const r3 = n2 / 2, s2 = o3 / 2, a3 = i3 * Math.PI / 180, c3 = Math.cos(a3), l3 = Math.sin(a3), h2 = [{ x: -r3, y: -s2 }, { x: r3, y: -s2 }, { x: r3, y: s2 }, { x: -r3, y: s2 }].map((n3) => ({ x: e35 + n3.x * c3 - n3.y * l3, y: t2 + n3.x * l3 + n3.y * c3 }));
  return { minX: Math.min(...h2.map((e36) => e36.x)), minY: Math.min(...h2.map((e36) => e36.y)), maxX: Math.max(...h2.map((e36) => e36.x)), maxY: Math.max(...h2.map((e36) => e36.y)) };
};
var $C = (e35) => e35[`${e35.type}_id`];
function YC(e35, t2, n2, o3) {
  return Math.sqrt((n2 - e35) ** 2 + (o3 - t2) ** 2);
}
var XC = class {
  buckets;
  objectsById;
  getBounds;
  getId;
  CELL_SIZE = 0.4;
  constructor({ objects: e35, getBounds: t2, getId: n2, CELL_SIZE: o3 }) {
    this.buckets = new Map, this.objectsById = new Map, this.getBounds = t2, this.getId = n2 ?? (() => this._getNextId()), this.CELL_SIZE = o3 ?? this.CELL_SIZE;
    for (const t3 of e35)
      this.addObject(t3);
  }
  _idCounter = 0;
  _getNextId() {
    return "" + this._idCounter++;
  }
  addObject(e35) {
    const t2 = this.getBounds(e35), n2 = this.getId(e35), o3 = { ...e35, spatialIndexId: n2 };
    this.objectsById.set(n2, o3);
    const i3 = Math.floor(t2.minX / this.CELL_SIZE), r3 = Math.floor(t2.minY / this.CELL_SIZE), s2 = Math.floor(t2.maxX / this.CELL_SIZE), a3 = Math.floor(t2.maxY / this.CELL_SIZE);
    for (let e36 = i3;e36 <= s2; e36++)
      for (let t3 = r3;t3 <= a3; t3++) {
        const n3 = `${e36}x${t3}`, i4 = this.buckets.get(n3);
        i4 ? i4.push(o3) : this.buckets.set(n3, [o3]);
      }
  }
  removeObject(e35) {
    const t2 = this.objectsById.get(e35);
    if (!t2)
      return false;
    this.objectsById.delete(e35);
    const n2 = this.getBounds(t2), o3 = Math.floor(n2.minX / this.CELL_SIZE), i3 = Math.floor(n2.minY / this.CELL_SIZE), r3 = Math.floor(n2.maxX / this.CELL_SIZE), s2 = Math.floor(n2.maxY / this.CELL_SIZE);
    for (let t3 = o3;t3 <= r3; t3++)
      for (let n3 = i3;n3 <= s2; n3++) {
        const o4 = `${t3}x${n3}`, i4 = this.buckets.get(o4);
        if (i4) {
          const t4 = i4.findIndex((t5) => t5.spatialIndexId === e35);
          t4 !== -1 && (i4.splice(t4, 1), i4.length === 0 && this.buckets.delete(o4));
        }
      }
    return true;
  }
  getBucketKey(e35, t2) {
    return `${Math.floor(e35 / this.CELL_SIZE)}x${Math.floor(t2 / this.CELL_SIZE)}`;
  }
  getObjectsInBounds(e35, t2 = 0) {
    const n2 = [], o3 = new Set, i3 = Math.floor((e35.minX - t2) / this.CELL_SIZE), r3 = Math.floor((e35.minY - t2) / this.CELL_SIZE), s2 = Math.floor((e35.maxX + t2) / this.CELL_SIZE), a3 = Math.floor((e35.maxY + t2) / this.CELL_SIZE);
    for (let e36 = i3;e36 <= s2; e36++)
      for (let t3 = r3;t3 <= a3; t3++) {
        const i4 = `${e36}x${t3}`, r4 = this.buckets.get(i4) || [];
        for (const e37 of r4) {
          const t4 = e37.spatialIndexId;
          o3.has(t4) || (o3.add(t4), n2.push(e37));
        }
      }
    return n2;
  }
};
var HC = 0.1;
var VC = 0.1;
var WC = HC;
var GC = HC;
var UC = 0.005;
function ZC(e35) {
  return e35.type === "pcb_trace_segment" || e35.type === "pcb_smtpad" ? [e35.layer] : e35.type === "pcb_plated_hole" ? Array.isArray(e35.layers) ? e35.layers : [...mv] : e35.type === "pcb_hole" ? [...mv] : e35.type === "pcb_via" ? Array.isArray(e35.layers) ? e35.layers : [...mv] : e35.type === "pcb_keepout" && Array.isArray(e35.layers) ? e35.layers : [];
}
var qC = (e35, t2) => {
  const n2 = { x: e35.x1, y: e35.y1 }, o3 = { x: e35.x2, y: e35.y2 }, i3 = t2.minX, r3 = t2.minY, s2 = t2.maxX, a3 = t2.maxY;
  if (n2.x === o3.x && n2.y === o3.y) {
    const e36 = Math.max(i3, Math.min(s2, n2.x)), t3 = Math.max(r3, Math.min(a3, n2.y));
    return e36 === n2.x && t3 === n2.y ? { x: n2.x, y: n2.y } : { x: e36, y: t3 };
  }
  const c3 = o3.x - n2.x, l3 = o3.y - n2.y, h2 = c3 !== 0 ? (i3 - n2.x) / c3 : Number.NEGATIVE_INFINITY, d2 = c3 !== 0 ? (s2 - n2.x) / c3 : Number.POSITIVE_INFINITY, u2 = l3 !== 0 ? (r3 - n2.y) / l3 : Number.NEGATIVE_INFINITY, p3 = l3 !== 0 ? (a3 - n2.y) / l3 : Number.POSITIVE_INFINITY, m2 = Math.max(Math.min(h2, d2), Math.min(u2, p3)), g2 = Math.min(Math.max(h2, d2), Math.max(u2, p3));
  if (m2 <= g2 && g2 >= 0 && m2 <= 1) {
    const e36 = Math.max(0, Math.min(1, m2));
    return { x: n2.x + e36 * c3, y: n2.y + e36 * l3 };
  }
  const f2 = { x: Math.max(i3, Math.min(s2, n2.x)), y: Math.max(r3, Math.min(a3, n2.y)) }, _2 = { x: Math.max(i3, Math.min(s2, o3.x)), y: Math.max(r3, Math.min(a3, o3.y)) }, y2 = (f2.x - n2.x) ** 2 + (f2.y - n2.y) ** 2, b2 = (_2.x - o3.x) ** 2 + (_2.y - o3.y) ** 2, x2 = [{ start: { x: i3, y: r3 }, end: { x: s2, y: r3 } }, { start: { x: s2, y: r3 }, end: { x: s2, y: a3 } }, { start: { x: s2, y: a3 }, end: { x: i3, y: a3 } }, { start: { x: i3, y: a3 }, end: { x: i3, y: r3 } }];
  let v2 = Math.min(y2, b2), I2 = y2 <= b2 ? f2 : _2;
  const S2 = (e36, t3, n3) => Math.max(t3, Math.min(n3, e36));
  for (const e36 of x2) {
    const t3 = { x: o3.x - n2.x, y: o3.y - n2.y }, i4 = { x: e36.end.x - e36.start.x, y: e36.end.y - e36.start.y }, r4 = { x: n2.x - e36.start.x, y: n2.y - e36.start.y }, s3 = t3.x * t3.x + t3.y * t3.y, a4 = t3.x * i4.x + t3.y * i4.y, c4 = t3.x * r4.x + t3.y * r4.y, l4 = i4.x * i4.x + i4.y * i4.y, h3 = i4.x * r4.x + i4.y * r4.y, d3 = s3 * l4 - a4 * a4;
    if (Math.abs(d3) < 0.0000000001)
      continue;
    let u3 = (a4 * h3 - l4 * c4) / d3, p4 = (s3 * h3 - a4 * c4) / d3;
    u3 = S2(u3, 0, 1), p4 = S2(p4, 0, 1);
    const m3 = { x: n2.x + u3 * t3.x, y: n2.y + u3 * t3.y }, g3 = { x: e36.start.x + p4 * i4.x, y: e36.start.y + p4 * i4.y }, f3 = m3.x - g3.x, _3 = m3.y - g3.y, y3 = f3 * f3 + _3 * _3;
    y3 < v2 && (v2 = y3, I2 = { x: (m3.x + g3.x) / 2, y: (m3.y + g3.y) / 2 });
  }
  return I2;
};
var JC = (e35, t2) => {
  const n2 = { x: e35.x1, y: e35.y1 }, o3 = { x: e35.x2, y: e35.y2 }, i3 = { x: t2.x1, y: t2.y1 }, r3 = { x: t2.x2, y: t2.y2 }, s2 = { x: o3.x - n2.x, y: o3.y - n2.y }, a3 = { x: r3.x - i3.x, y: r3.y - i3.y }, c3 = s2.x * s2.x + s2.y * s2.y, l3 = a3.x * a3.x + a3.y * a3.y;
  if (c3 === 0 || l3 === 0) {
    if (c3 === 0 && l3 === 0)
      return { x: (n2.x + i3.x) / 2, y: (n2.y + i3.y) / 2 };
    if (c3 === 0) {
      const e37 = KC(((n2.x - i3.x) * a3.x + (n2.y - i3.y) * a3.y) / l3, 0, 1), t4 = { x: i3.x + e37 * a3.x, y: i3.y + e37 * a3.y };
      return { x: (n2.x + t4.x) / 2, y: (n2.y + t4.y) / 2 };
    }
    const e36 = KC(((i3.x - n2.x) * s2.x + (i3.y - n2.y) * s2.y) / c3, 0, 1), t3 = { x: n2.x + e36 * s2.x, y: n2.y + e36 * s2.y };
    return { x: (t3.x + i3.x) / 2, y: (t3.y + i3.y) / 2 };
  }
  const h2 = n2.x - i3.x, d2 = n2.y - i3.y, u2 = s2.x * s2.x + s2.y * s2.y, p3 = s2.x * a3.x + s2.y * a3.y, m2 = s2.x * h2 + s2.y * d2, g2 = a3.x * a3.x + a3.y * a3.y, f2 = a3.x * h2 + a3.y * d2, _2 = u2 * g2 - p3 * p3;
  if (_2 < 0.0000000001)
    return QC(n2, o3, i3, r3, s2, a3, c3, l3);
  let y2 = (p3 * f2 - g2 * m2) / _2, b2 = (u2 * f2 - p3 * m2) / _2;
  y2 = KC(y2, 0, 1), b2 = KC(b2, 0, 1), b2 = (y2 * p3 + f2) / g2, b2 = KC(b2, 0, 1), y2 = (b2 * p3 - m2) / u2, y2 = KC(y2, 0, 1);
  const x2 = n2.x + y2 * s2.x, v2 = n2.y + y2 * s2.y, I2 = i3.x + b2 * a3.x, S2 = i3.y + b2 * a3.y, C = x2 - I2, P = v2 - S2;
  Math.sqrt(C * C + P * P);
  return { x: (x2 + I2) / 2, y: (v2 + S2) / 2 };
};
var QC = (e35, t2, n2, o3, i3, r3, s2, a3) => {
  let c3 = ((n2.x - e35.x) * i3.x + (n2.y - e35.y) * i3.y) / s2;
  c3 = KC(c3, 0, 1);
  const l3 = { x: e35.x + c3 * i3.x, y: e35.y + c3 * i3.y };
  let h2 = ((o3.x - e35.x) * i3.x + (o3.y - e35.y) * i3.y) / s2;
  h2 = KC(h2, 0, 1);
  const d2 = { x: e35.x + h2 * i3.x, y: e35.y + h2 * i3.y };
  let u2 = ((e35.x - n2.x) * r3.x + (e35.y - n2.y) * r3.y) / a3;
  u2 = KC(u2, 0, 1);
  const p3 = { x: n2.x + u2 * r3.x, y: n2.y + u2 * r3.y };
  let m2 = ((t2.x - n2.x) * r3.x + (t2.y - n2.y) * r3.y) / a3;
  m2 = KC(m2, 0, 1);
  const g2 = { x: n2.x + m2 * r3.x, y: n2.y + m2 * r3.y }, f2 = [{ pointA: l3, pointB: n2, distance: Math.sqrt((l3.x - n2.x) ** 2 + (l3.y - n2.y) ** 2) }, { pointA: d2, pointB: o3, distance: Math.sqrt((d2.x - o3.x) ** 2 + (d2.y - o3.y) ** 2) }, { pointA: e35, pointB: p3, distance: Math.sqrt((e35.x - p3.x) ** 2 + (e35.y - p3.y) ** 2) }, { pointA: t2, pointB: g2, distance: Math.sqrt((t2.x - g2.x) ** 2 + (t2.y - g2.y) ** 2) }].reduce((e36, t3) => t3.distance < e36.distance ? t3 : e36);
  return { x: (f2.pointA.x + f2.pointB.x) / 2, y: (f2.pointA.y + f2.pointB.y) / 2 };
};
var KC = (e35, t2, n2) => Math.max(t2, Math.min(n2, e35));
var eP = (e35) => e35.type === "pcb_trace_segment" ? { minX: Math.min(e35.x1, e35.x2), minY: Math.min(e35.y1, e35.y2), maxX: Math.max(e35.x1, e35.x2), maxY: Math.max(e35.y1, e35.y2) } : ((e36) => {
  let { POSITIVE_INFINITY: t2, POSITIVE_INFINITY: n2, NEGATIVE_INFINITY: o3, NEGATIVE_INFINITY: i3 } = Number;
  for (const r3 of e36) {
    if (!r3.type.startsWith("pcb_"))
      continue;
    if (r3.type === "pcb_smtpad" && r3.shape === "polygon" && Array.isArray(r3.points)) {
      for (const e38 of r3.points)
        t2 = Math.min(t2, e38.x), n2 = Math.min(n2, e38.y), o3 = Math.max(o3, e38.x), i3 = Math.max(i3, e38.y);
      continue;
    }
    if (r3.type === "pcb_hole" && r3.hole_shape === "circle") {
      const e38 = FC(r3.x, r3.y, r3.hole_diameter);
      t2 = Math.min(t2, e38.minX), n2 = Math.min(n2, e38.minY), o3 = Math.max(o3, e38.maxX), i3 = Math.max(i3, e38.maxY);
      continue;
    }
    if (r3.type === "pcb_plated_hole") {
      let e38;
      if ("outer_diameter" in r3 && typeof r3.outer_diameter == "number" ? e38 = FC(r3.x, r3.y, r3.outer_diameter) : ("hole_diameter" in r3) && typeof r3.hole_diameter == "number" && (e38 = FC(r3.x, r3.y, r3.hole_diameter)), "rect_pad_width" in r3 && typeof r3.rect_pad_width == "number" && "rect_pad_height" in r3 && typeof r3.rect_pad_height == "number") {
        const t3 = jC(r3.x, r3.y, r3.rect_pad_width, r3.rect_pad_height, "rect_ccw_rotation" in r3 ? r3.rect_ccw_rotation ?? 0 : 0);
        e38 = e38 ? BC(e38, t3) : t3;
      }
      if ("hole_diameter" in r3 && typeof r3.hole_diameter == "number") {
        const t3 = FC(r3.x + ("hole_offset_x" in r3 ? r3.hole_offset_x ?? 0 : 0), r3.y + ("hole_offset_y" in r3 ? r3.hole_offset_y ?? 0 : 0), r3.hole_diameter);
        e38 = e38 ? BC(e38, t3) : t3;
      }
      if (e38) {
        t2 = Math.min(t2, e38.minX), n2 = Math.min(n2, e38.minY), o3 = Math.max(o3, e38.maxX), i3 = Math.max(i3, e38.maxY);
        continue;
      }
    }
    let e37, s2, a3, c3;
    if ("x" in r3 && "y" in r3 && (e37 = Number(r3.x), s2 = Number(r3.y)), "outer_diameter" in r3 && (a3 = Number(r3.outer_diameter), c3 = Number(r3.outer_diameter)), "width" in r3 && (a3 = Number(r3.width)), "height" in r3 && (c3 = Number(r3.height)), "center" in r3 && (e37 = r3.center.x, s2 = r3.center.y), e37 !== undefined && s2 !== undefined)
      t2 = Math.min(t2, e37), n2 = Math.min(n2, s2), o3 = Math.max(o3, e37), i3 = Math.max(i3, s2), a3 !== undefined && c3 !== undefined && (t2 = Math.min(t2, e37 - a3 / 2), n2 = Math.min(n2, s2 - c3 / 2), o3 = Math.max(o3, e37 + a3 / 2), i3 = Math.max(i3, s2 + c3 / 2)), "radius" in r3 && (t2 = Math.min(t2, e37 - r3.radius), n2 = Math.min(n2, s2 - r3.radius), o3 = Math.max(o3, e37 + r3.radius), i3 = Math.max(i3, s2 + r3.radius));
    else if (r3.type === "pcb_trace")
      for (const e38 of r3.route)
        t2 = Math.min(t2, e38.x), n2 = Math.min(n2, e38.y), o3 = Math.max(o3, e38.x), i3 = Math.max(i3, e38.y);
    else if (r3.type === "pcb_courtyard_outline")
      for (const e38 of r3.outline)
        t2 = Math.min(t2, e38.x), n2 = Math.min(n2, e38.y), o3 = Math.max(o3, e38.x), i3 = Math.max(i3, e38.y);
    else if (r3.type === "pcb_courtyard_polygon")
      for (const e38 of r3.points)
        t2 = Math.min(t2, e38.x), n2 = Math.min(n2, e38.y), o3 = Math.max(o3, e38.x), i3 = Math.max(i3, e38.y);
  }
  return { minX: t2, minY: n2, maxX: o3, maxY: i3 };
})([e35]);
function tP(e35) {
  const t2 = new Set;
  for (const n2 of e35.route)
    n2.route_type === "wire" && (n2.start_pcb_port_id && t2.add(n2.start_pcb_port_id), n2.end_pcb_port_id && t2.add(n2.end_pcb_port_id));
  return Array.from(t2);
}
function nP(e35) {
  const t2 = new Set;
  for (const n2 of e35)
    for (const e36 of tP(n2))
      t2.add(e36);
  return Array.from(t2);
}
var oP = (e35) => {
  if (e35.type === "pcb_via")
    return e35.outer_diameter / 2;
  if (e35.type === "pcb_plated_hole" && e35.shape === "circle")
    return e35.outer_diameter / 2;
  if (e35.type === "pcb_hole" && e35.hole_shape === "circle")
    return e35.hole_diameter / 2;
  if (e35.type === "pcb_smtpad" && e35.shape === "circle")
    return e35.radius;
  throw new Error(`Could not determine radius of element: ${JSON.stringify(e35)}`);
};
function iP(e35, { connMap: t2, minClearance: n2 = 0.1 } = {}) {
  const o3 = [];
  ((e36) => {
    const t3 = e36.filter((e37) => e37.type === "pcb_port"), n3 = e36.filter((e37) => e37.type === "pcb_smtpad"), o4 = e36.filter((e37) => e37.type === "pcb_trace");
    function i4(e37, o5 = {}) {
      const i5 = o5.traceWidth || 0, r4 = t3.find((t4) => YC(t4.x, t4.y, e37.x, e37.y) < 0.01);
      if (r4)
        return r4.pcb_port_id;
      if (o5.isFirstOrLastPoint) {
        const t4 = n3.find((t5) => t5.shape === "rect" ? Math.abs(e37.x - t5.x) < t5.width / 2 + i5 / 2 && Math.abs(e37.y - t5.y) < t5.height / 2 + i5 / 2 : t5.shape === "circle" ? YC(e37.x, e37.y, t5.x, t5.y) < t5.radius : undefined);
        if (t4)
          return t4.pcb_port_id ?? null;
      }
      return null;
    }
    for (const e37 of o4)
      for (let t4 = 0;t4 < e37.route.length; t4++) {
        const n4 = e37.route[t4], o5 = t4 === 0 || t4 === e37.route.length - 1;
        if (n4.route_type === "wire") {
          if (!n4.start_pcb_port_id && t4 === 0) {
            const e38 = i4(n4, { isFirstOrLastPoint: o5, traceWidth: n4.width });
            e38 && (n4.start_pcb_port_id = e38);
          }
          if (!n4.end_pcb_port_id && t4 === e37.route.length - 1) {
            const e38 = i4(n4, { isFirstOrLastPoint: o5, traceWidth: n4.width });
            e38 && (n4.end_pcb_port_id = e38);
          }
        }
      }
  })(e35), t2 ??= Rb(e35);
  const i3 = EC(e35).pcb_trace.list().flatMap((e36) => {
    const t3 = [];
    for (let n3 = 0;n3 < e36.route.length - 1; n3++) {
      const o4 = e36.route[n3], i4 = e36.route[n3 + 1];
      o4.route_type === "wire" && (i4.route_type === "wire" && o4.layer === i4.layer && t3.push({ type: "pcb_trace_segment", pcb_trace_id: e36.pcb_trace_id, _pcbTrace: e36, thickness: "width" in o4 ? o4.width : ("width" in i4) ? i4.width : VC, layer: o4.layer, x1: o4.x, y1: o4.y, x2: i4.x, y2: i4.y }));
    }
    return t3;
  }), r3 = EC(e35).pcb_smtpad.list(), s2 = EC(e35).pcb_plated_hole.list(), a3 = EC(e35).pcb_hole.list(), c3 = EC(e35).pcb_via.list(), l3 = EC(e35).pcb_keepout.list(), h2 = [...i3, ...r3, ...s2, ...a3, ...c3, ...l3], d2 = new XC({ objects: h2, getBounds: eP }), u2 = (t3) => zC(e35, t3), p3 = (e36, t3, n3) => n3 < 0 ? `PCB trace ${e36} overlaps with ${t3} (accidental contact)` : `PCB trace ${e36} is too close to ${t3} (gap: ${n3.toFixed(3)}mm)`, m2 = new Set;
  for (const e36 of i3) {
    const i4 = n2, r4 = eP(e36), s3 = d2.getObjectsInBounds(r4, i4 + e36.thickness / 2);
    if (e36.x1 !== e36.x2 || e36.y1 !== e36.y2)
      for (const r5 of s3) {
        if (!ZC(r5).includes(e36.layer))
          continue;
        if (r5.type === "pcb_trace_segment") {
          const i5 = r5;
          if (e36.layer !== i5.layer)
            continue;
          if (t2.areIdsConnected(e36.pcb_trace_id, i5.pcb_trace_id))
            continue;
          const s5 = we({ x: e36.x1, y: e36.y1 }, { x: e36.x2, y: e36.y2 }, { x: i5.x1, y: i5.y1 }, { x: i5.x2, y: i5.y2 }) - e36.thickness / 2 - i5.thickness / 2;
          if (s5 > n2 - UC)
            continue;
          const a5 = `overlap_${e36.pcb_trace_id}_${i5.pcb_trace_id}`, c4 = `overlap_${i5.pcb_trace_id}_${e36.pcb_trace_id}`;
          if (m2.has(a5))
            continue;
          if (m2.has(c4))
            continue;
          m2.add(a5), o3.push({ type: "pcb_trace_error", error_type: "pcb_trace_error", message: p3(u2(e36.pcb_trace_id), u2(i5.pcb_trace_id), s5), pcb_trace_id: e36.pcb_trace_id, source_trace_id: "", pcb_trace_error_id: a5, pcb_component_ids: [], center: JC(e36, i5), pcb_port_ids: nP([e36._pcbTrace, i5._pcbTrace]) });
          continue;
        }
        const s4 = $C(r5);
        if (t2.areIdsConnected(e36.pcb_trace_id, "pcb_trace_id" in r5 ? r5.pcb_trace_id : s4))
          continue;
        if (r5.type === "pcb_via" || r5.type === "pcb_plated_hole" && r5.shape === "circle" || r5.type === "pcb_hole" || r5.type === "pcb_smtpad" && r5.shape === "circle") {
          const t3 = oP(r5), i5 = Te({ x: e36.x1, y: e36.y1 }, { x: e36.x2, y: e36.y2 }, { x: r5.x, y: r5.y, radius: t3 }) - e36.thickness / 2;
          if (i5 > n2 - UC)
            continue;
          const a5 = `overlap_${e36.pcb_trace_id}_${s4}`;
          if (m2.has(a5))
            continue;
          m2.add(a5), o3.push({ type: "pcb_trace_error", error_type: "pcb_trace_error", message: p3(u2(e36.pcb_trace_id), `${r5.type} "${u2($C(r5))}"`, i5), pcb_trace_id: e36.pcb_trace_id, center: qC(e36, eP(r5)), source_trace_id: "", pcb_trace_error_id: a5, pcb_component_ids: ["pcb_component_id" in r5 ? r5.pcb_component_id : undefined].filter(Boolean), pcb_port_ids: [...nP([e36._pcbTrace]), "pcb_port_id" in r5 ? r5.pcb_port_id : undefined].filter(Boolean) });
        }
        const a4 = Ne({ x: e36.x1, y: e36.y1 }, { x: e36.x2, y: e36.y2 }, eP(r5)) - e36.thickness / 2;
        if (a4 + UC < i4) {
          const t3 = `overlap_${e36.pcb_trace_id}_${s4}`;
          if (m2.has(t3))
            continue;
          m2.add(t3), o3.push({ type: "pcb_trace_error", error_type: "pcb_trace_error", message: p3(u2(e36.pcb_trace_id), `${r5.type} "${u2($C(r5))}"`, a4), pcb_trace_id: e36.pcb_trace_id, source_trace_id: "", pcb_trace_error_id: t3, pcb_component_ids: ["pcb_component_id" in r5 ? r5.pcb_component_id : undefined].filter(Boolean), center: qC(e36, eP(r5)), pcb_port_ids: [...nP([e36._pcbTrace]), "pcb_port_id" in r5 ? r5.pcb_port_id : undefined].filter(Boolean) });
        }
      }
  }
  return o3;
}
function rP(e35, t2) {
  return Math.hypot(e35.x - t2.x, e35.y - t2.y);
}
function sP(e35, t2) {
  return rP(e35, t2) <= UC;
}
function aP(e35, { connMap: t2, minClearance: n2 = WC } = {}) {
  const o3 = e35.filter((e36) => e36.type === "pcb_via");
  if (o3.length < 2)
    return [];
  t2 ??= Rb(e35);
  const i3 = [], r3 = new Set;
  for (let s2 = 0;s2 < o3.length; s2++)
    for (let a3 = s2 + 1;a3 < o3.length; a3++) {
      const c3 = o3[s2], l3 = o3[a3];
      if (sP(c3, l3))
        continue;
      if (!t2.areIdsConnected(c3.pcb_via_id, l3.pcb_via_id))
        continue;
      const h2 = rP(c3, l3) - c3.outer_diameter / 2 - l3.outer_diameter / 2;
      if (h2 + UC >= n2)
        continue;
      const d2 = [c3.pcb_via_id, l3.pcb_via_id].sort().join("_");
      r3.has(d2) || (r3.add(d2), i3.push({ type: "pcb_via_clearance_error", pcb_error_id: `same_net_vias_close_${d2}`, message: `Vias ${zC(e35, c3.pcb_via_id)} and ${zC(e35, l3.pcb_via_id)} are too close together (gap: ${h2.toFixed(3)}mm)`, error_type: "pcb_via_clearance_error", pcb_via_ids: [c3.pcb_via_id, l3.pcb_via_id], minimum_clearance: n2, actual_clearance: h2, pcb_center: { x: (c3.x + l3.x) / 2, y: (c3.y + l3.y) / 2 } }));
    }
  return i3;
}
function cP(e35, { connMap: t2, minClearance: n2 = GC } = {}) {
  const o3 = e35.filter((e36) => e36.type === "pcb_via");
  if (o3.length < 2)
    return [];
  t2 ??= Rb(e35);
  const i3 = [], r3 = new Set;
  for (let s2 = 0;s2 < o3.length; s2++)
    for (let a3 = s2 + 1;a3 < o3.length; a3++) {
      const c3 = o3[s2], l3 = o3[a3];
      if (sP(c3, l3))
        continue;
      if (t2.areIdsConnected(c3.pcb_via_id, l3.pcb_via_id))
        continue;
      const h2 = rP(c3, l3) - c3.outer_diameter / 2 - l3.outer_diameter / 2;
      if (h2 + UC >= n2)
        continue;
      const d2 = [c3.pcb_via_id, l3.pcb_via_id].sort().join("_");
      r3.has(d2) || (r3.add(d2), i3.push({ type: "pcb_via_clearance_error", pcb_error_id: `different_net_vias_close_${d2}`, message: `Vias ${zC(e35, c3.pcb_via_id)} and ${zC(e35, l3.pcb_via_id)} from different nets are too close together (gap: ${h2.toFixed(3)}mm)`, error_type: "pcb_via_clearance_error", pcb_via_ids: [c3.pcb_via_id, l3.pcb_via_id], minimum_clearance: n2, actual_clearance: h2, pcb_center: { x: (c3.x + l3.x) / 2, y: (c3.y + l3.y) / 2 } }));
    }
  return i3;
}
var lP = (e35) => ({ minSpacing: e35, minClearance: e35 });
var hP = { traceClearance: 0.1, viaClearance: 0.1 };
var dP = (e35) => ((e36) => ("layer" in e36))(e35) ? [e35.layer] : e35.layers;
function uP(e35, t2, n2) {
  let o3, i3 = Number.POSITIVE_INFINITY;
  for (const r3 of t2) {
    const t3 = n2.get(r3);
    if (!t3)
      continue;
    const s2 = Math.hypot(t3.x - e35.x, t3.y - e35.y);
    s2 < i3 && (i3 = s2, o3 = r3);
  }
  return o3 ?? t2[0];
}
function pP(e35) {
  const t2 = [], n2 = new Set, o3 = new Set, i3 = function(e36) {
    const t3 = new Map;
    for (const n3 of e36.connections)
      for (const e37 of n3.pointsToConnect)
        e37.pcb_port_id && t3.set(e37.pcb_port_id, { x: e37.x, y: e37.y });
    return t3;
  }(e35);
  for (const r3 of e35.obstacles) {
    const e36 = r3.connectedTo, s2 = e36.find((e37) => e37.startsWith("pcb_smtpad_")), a3 = e36.find((e37) => e37.startsWith("pcb_plated_hole_")), c3 = e36.filter((e37) => e37.startsWith("pcb_port_")), l3 = uP(r3.center, c3, i3);
    if (!s2 && !a3 && !l3)
      continue;
    const h2 = r3.layers;
    if (h2.length === 0)
      continue;
    const { width: d2, height: u2 } = r3, p3 = r3.center.x, m2 = r3.center.y, g2 = r3.ccwRotationDegrees, f2 = typeof g2 == "number" && Number.isFinite(g2);
    if (h2.length > 1) {
      const e37 = a3 ?? `pcb_plated_hole_${p3.toFixed(3)}_${m2.toFixed(3)}`;
      if (o3.has(e37))
        continue;
      if (o3.add(e37), f2) {
        const n3 = Math.max(0.5 * Math.min(d2, u2), 0.1);
        t2.push({ type: "pcb_plated_hole", pcb_plated_hole_id: e37, shape: "rotated_pill_hole_with_rect_pad", hole_shape: "rotated_pill", pad_shape: "rect", hole_width: n3, hole_height: n3, hole_ccw_rotation: g2, rect_pad_width: d2, rect_pad_height: u2, rect_ccw_rotation: g2, hole_offset_x: 0, hole_offset_y: 0, x: p3, y: m2, layers: h2, ...l3 ? { pcb_port_id: l3 } : {} });
        continue;
      }
      if (Math.abs(d2 - u2) < 0.001) {
        t2.push({ type: "pcb_plated_hole", pcb_plated_hole_id: e37, shape: "circle", outer_diameter: Math.max(d2, u2), hole_diameter: Math.max(0.5 * Math.min(d2, u2), 0.1), x: p3, y: m2, layers: h2, ...l3 ? { pcb_port_id: l3 } : {} });
        continue;
      }
      t2.push({ type: "pcb_plated_hole", pcb_plated_hole_id: e37, shape: "circular_hole_with_rect_pad", hole_shape: "circle", hole_diameter: Math.max(0.5 * Math.min(d2, u2), 0.1), rect_pad_width: d2, rect_pad_height: u2, hole_offset_x: 0, hole_offset_y: 0, x: p3, y: m2, layers: h2, ...l3 ? { pcb_port_id: l3 } : {} });
      continue;
    }
    const _2 = s2 ?? `pcb_smtpad_${p3.toFixed(3)}_${m2.toFixed(3)}`;
    n2.has(_2) || (n2.add(_2), f2 ? t2.push({ type: "pcb_smtpad", pcb_smtpad_id: _2, layer: h2[0], shape: "rotated_rect", x: p3, y: m2, width: d2, height: u2, ccw_rotation: g2, ...l3 ? { pcb_port_id: l3 } : {} }) : t2.push({ type: "pcb_smtpad", pcb_smtpad_id: _2, layer: h2[0], shape: "rect", width: d2, height: u2, x: p3, y: m2, ...l3 ? { pcb_port_id: l3 } : {} }));
  }
  return t2;
}
function mP(e35, t2, n2 = 0.1, o3 = e35.minViaDiameter ?? 0.3) {
  const i3 = [];
  i3.push(...function(e36, t3) {
    const n3 = [];
    return e36.connections.forEach((o4) => {
      const i4 = o4.pointsToConnect.filter((e37) => e37.pcb_port_id).map((e37) => e37.pcb_port_id).filter(Boolean), r4 = o4.netConnectionName || o4.rootConnectionName || o4.name, s2 = [], a3 = t3.find((e37) => (e37.connection_name ?? e37.connectionName) === o4.name);
      if (a3) {
        const t4 = (e37) => ("route_type" in e37) && e37.route_type === "jumper" ? e37.start : ("x" in e37) && ("y" in e37) ? { x: e37.x, y: e37.y } : { x: 0, y: 0 }, n4 = [t4(a3.route[0]), t4(a3.route[a3.route.length - 1])];
        for (const t5 of n4)
          for (const n5 of e36.obstacles)
            Oe(t5, n5) <= 0 && s2.push(n5);
      }
      const c3 = n3.find((e37) => e37.type === "source_trace" && e37.source_trace_id === r4);
      if (c3) {
        const e37 = c3;
        e37.connected_source_port_ids = [...new Set([...e37.connected_source_port_ids, ...i4])];
      } else
        n3.push({ type: "source_trace", source_trace_id: r4, connected_source_port_ids: i4.concat(s2.flatMap((e37) => [`obstacle_${e37.center.x.toFixed(3)}_${e37.center.y.toFixed(3)}_${e37.layers.join(".")}`, ...e37.connectedTo])), connected_source_net_ids: [] });
    }), n3;
  }(e35, t2)), i3.push(...function(e36) {
    const t3 = new Map;
    return e36.connections.forEach((e37) => {
      e37.pointsToConnect.forEach((e38) => {
        e38.pcb_port_id && t3.set(e38.pcb_port_id, { type: "pcb_port", pcb_port_id: e38.pcb_port_id, source_port_id: e38.pcb_port_id, x: e38.x, y: e38.y, layers: dP(e38) });
      });
    }), Array.from(t3.values());
  }(e35)), i3.push(...pP(e35)), i3.push(...function({ routes: e36, layerCount: t3, minViaDiameter: n3 = 0.3, allowBlindAndBuriedVias: o4 = false }) {
    const i4 = [], r4 = new Set;
    return e36.length > 0 && ("type" in e36[0] && e36[0].type === "pcb_trace" ? e36.forEach((e37) => {
      e37.route.forEach((s2) => {
        if (s2.route_type === "via") {
          const a3 = s2.via_diameter ?? n3, c3 = `${s2.x},${s2.y},${s2.from_layer},${s2.to_layer}`;
          r4.has(c3) || (i4.push({ type: "pcb_via", pcb_via_id: `via_${i4.length}`, pcb_trace_id: e37.pcb_trace_id, x: s2.x, y: s2.y, outer_diameter: a3, hole_diameter: 0.5 * a3, layers: eb({ via: s2, layerCount: t3, allowBlindAndBuriedVias: o4 }) }), r4.add(c3));
        }
      });
    }) : e36.forEach((e37, s2) => {
      const a3 = `trace_${s2}`, c3 = e37.viaDiameter ?? n3;
      for (let n4 = 1;n4 < e37.route.length; n4++) {
        const s3 = e37.route[n4 - 1], l3 = e37.route[n4];
        if (s3.z !== l3.z && Math.abs(s3.x - l3.x) < 0.01 && Math.abs(s3.y - l3.y) < 0.01) {
          const e38 = Qy(s3.z, t3), n5 = Qy(l3.z, t3), h2 = `${l3.x},${l3.y},${e38},${n5}`;
          r4.has(h2) || (i4.push({ type: "pcb_via", pcb_via_id: `via_${i4.length}`, pcb_trace_id: a3, x: l3.x, y: l3.y, outer_diameter: c3, hole_diameter: 0.5 * c3, layers: eb({ via: { from_layer: e38, to_layer: n5 }, layerCount: t3, allowBlindAndBuriedVias: o4 }) }), r4.add(h2));
        }
      }
    })), i4;
  }({ routes: t2, layerCount: e35.layerCount, minViaDiameter: o3, allowBlindAndBuriedVias: e35.allowBlindAndBuriedVias }));
  const r3 = new Map;
  return e35.connections.forEach((e36) => {
    r3.set(e36.name, e36.netConnectionName || e36.rootConnectionName || e36.name);
  }), t2.length > 0 && ("type" in t2[0] && t2[0].type === "pcb_trace" ? t2.forEach((e36) => {
    const t3 = e36.connection_name;
    i3.push(function(e37, t4) {
      return { type: "pcb_trace", pcb_trace_id: e37.pcb_trace_id, source_trace_id: t4, route: e37.route.map((e38) => e38.route_type === "wire" ? { route_type: "wire", x: e38.x, y: e38.y, width: e38.width, layer: e38.layer, start_pcb_port_id: e38.start_pcb_port_id, end_pcb_port_id: e38.end_pcb_port_id } : e38.route_type === "via" ? { route_type: "via", x: e38.x, y: e38.y, from_layer: e38.from_layer, to_layer: e38.to_layer } : null).filter((e38) => e38 !== null) };
    }(e36, r3.get(t3) || t3));
  }) : t2.forEach((t3, o4) => {
    const s2 = t3.connectionName, a3 = function(e36, t4, n3, o5 = 0.1, i4) {
      const r4 = [];
      if (!e36.jumpers || e36.jumpers.length === 0)
        return [{ type: "pcb_trace", pcb_trace_id: t4, source_trace_id: n3, route: e36.route.map((t5, n4) => {
          const r5 = n4 === 0, s4 = n4 === e36.route.length - 1;
          return { route_type: "wire", x: t5.x, y: t5.y, width: o5, layer: Qy(t5.z, i4), ...r5 && t5.pcb_port_id ? { start_pcb_port_id: t5.pcb_port_id } : {}, ...s4 && t5.pcb_port_id ? { end_pcb_port_id: t5.pcb_port_id } : {} };
        }) }];
      const s3 = [];
      for (const t5 of e36.jumpers) {
        let n4 = -1, o6 = -1;
        for (let i5 = 0;i5 < e36.route.length; i5++) {
          const r5 = e36.route[i5];
          Math.abs(r5.x - t5.start.x) < 0.01 && Math.abs(r5.y - t5.start.y) < 0.01 && (n4 = i5), Math.abs(r5.x - t5.end.x) < 0.01 && Math.abs(r5.y - t5.end.y) < 0.01 && (o6 = i5);
        }
        n4 !== -1 && o6 !== -1 && (n4 > o6 && ([n4, o6] = [o6, n4]), s3.push({ startIdx: n4, endIdx: o6 }));
      }
      s3.sort((e37, t5) => e37.startIdx - t5.startIdx);
      let a4 = 0, c3 = 0;
      for (const { startIdx: l3, endIdx: h2 } of s3) {
        if (l3 >= a4) {
          const s4 = e36.route.slice(a4, l3 + 1);
          s4.length > 0 && (r4.push({ type: "pcb_trace", pcb_trace_id: `${t4}_${c3}`, source_trace_id: n3, route: s4.map((e37, t5) => {
            const n4 = t5 === 0 && a4 === 0;
            return { route_type: "wire", x: e37.x, y: e37.y, width: o5, layer: Qy(e37.z, i4), ...n4 && e37.pcb_port_id ? { start_pcb_port_id: e37.pcb_port_id } : {} };
          }) }), c3++);
        }
        a4 = h2;
      }
      if (a4 < e36.route.length) {
        const s4 = e36.route.slice(a4);
        if (s4.length > 0) {
          const e37 = true;
          r4.push({ type: "pcb_trace", pcb_trace_id: `${t4}_${c3}`, source_trace_id: n3, route: s4.map((t5, n4) => {
            const r5 = e37 && n4 === s4.length - 1;
            return { route_type: "wire", x: t5.x, y: t5.y, width: o5, layer: Qy(t5.z, i4), ...r5 && t5.pcb_port_id ? { end_pcb_port_id: t5.pcb_port_id } : {} };
          }) });
        }
      }
      return r4;
    }(t3, `trace_${o4}`, r3.get(s2) || s2, n2, e35.layerCount);
    i3.push(...a3);
  })), i3;
}
var gP = (e35) => e35.rootConnectionName ?? e35.connectionName;
var fP = (e35, t2) => {
  if (e35 && t2)
    return e35.getNetConnectedToId(t2);
};
var _P = (e35, t2) => t2 ? { ...e35, connections: e35.connections.map((e36) => {
  const n2 = fP(t2, e36.name) ?? fP(t2, e36.rootConnectionName) ?? e36.netConnectionName;
  return n2 ? { ...e36, netConnectionName: n2 } : e36;
}), obstacles: e35.obstacles.map((e36) => {
  const n2 = new Set(e36.connectedTo);
  for (const o3 of e36.connectedTo) {
    const e37 = fP(t2, o3);
    e37 && n2.add(e37);
  }
  return { ...e36, connectedTo: [...n2] };
}) } : e35;
var yP = (e35, t2, n2) => {
  if (!t2)
    return false;
  if (e35 === t2)
    return true;
  const o3 = n2?.getNetConnectedToId(e35), i3 = n2?.getNetConnectedToId(t2);
  return !(!o3 || !(o3 === i3 || e35 && o3 === t2)) || !(!i3 || i3 !== e35);
};
var bP = (e35, t2, n2) => t2.connectedTo?.some((t3) => yP(e35, t3, n2)) ?? false;
var xP = (e35, t2, n2) => Math.max(t2, Math.min(e35, n2));
var vP = (e35, t2) => {
  e35.x = xP(e35.x, t2.minX, t2.maxX), e35.y = xP(e35.y, t2.minY, t2.maxY);
};
var IP = (e35, t2) => ({ minX: e35.minX - t2, minY: e35.minY - t2, maxX: e35.maxX + t2, maxY: e35.maxY + t2 });
var SP = (e35, t2) => ({ minCellX: Math.floor(e35.minX / t2), maxCellX: Math.floor(e35.maxX / t2), minCellY: Math.floor(e35.minY / t2), maxCellY: Math.floor(e35.maxY / t2) });
var CP = (e35, t2) => `${e35}:${t2}`;
var PP = new WeakMap;
var MP = (e35, t2, n2) => {
  const o3 = new Map, i3 = Math.ceil(e35.length / 32);
  PP.set(o3, { bits: new Uint32Array(i3), wordGenerations: new Uint32Array(i3), generation: 0 });
  for (let i4 = 0;i4 < e35.length; i4 += 1) {
    const r3 = e35[i4];
    if (!r3)
      continue;
    const s2 = SP(t2(r3), n2);
    for (let e36 = s2.minCellX;e36 <= s2.maxCellX; e36 += 1)
      for (let t3 = s2.minCellY;t3 <= s2.maxCellY; t3 += 1) {
        const n3 = CP(e36, t3), r4 = o3.get(n3);
        r4 ? r4.push(i4) : o3.set(n3, [i4]);
      }
  }
  return o3;
};
var wP = (e35, t2, n2) => {
  let o3 = PP.get(e35);
  o3 || (o3 = { bits: new Uint32Array(0), wordGenerations: new Uint32Array(0), generation: 0 }, PP.set(e35, o3)), o3.generation += 1, o3.generation > 4294967295 && (o3.wordGenerations.fill(0), o3.generation = 1);
  const i3 = o3.generation, r3 = SP(t2, n2);
  let s2 = 1 / 0, a3 = -1;
  for (let t3 = r3.minCellX;t3 <= r3.maxCellX; t3 += 1)
    for (let n3 = r3.minCellY;n3 <= r3.maxCellY; n3 += 1) {
      const r4 = e35.get(CP(t3, n3));
      if (r4)
        for (const e36 of r4) {
          const t4 = e36 >>> 5;
          if (t4 >= o3.bits.length) {
            const e37 = Math.max(t4 + 1, 2 * o3.bits.length), n4 = new Uint32Array(e37);
            n4.set(o3.bits);
            const i4 = new Uint32Array(e37);
            i4.set(o3.wordGenerations), o3.bits = n4, o3.wordGenerations = i4;
          }
          o3.wordGenerations[t4] !== i3 && (o3.wordGenerations[t4] = i3, o3.bits[t4] = 0), o3.bits[t4] = o3.bits[t4] | 1 << (31 & e36), t4 < s2 && (s2 = t4), t4 > a3 && (a3 = t4);
        }
    }
  const c3 = [];
  for (let e36 = s2;e36 <= a3; e36 += 1) {
    if (o3.wordGenerations[e36] !== i3)
      continue;
    let t3 = o3.bits[e36];
    for (;t3 !== 0; ) {
      const n3 = 31 - Math.clz32(t3 & -t3);
      c3.push(32 * e36 + n3), t3 &= t3 - 1;
    }
  }
  return c3;
};
var NP = 0.000001;
var RP = (e35, t2, n2) => {
  if (e35.length === 0)
    return [];
  const o3 = n2?.traceThickness ?? 0.1, i3 = e35[0], r3 = e35.at(-1), s2 = (e36) => {
    if (e36.pcb_port_id)
      return e36.pcb_port_id;
    const o4 = Qy(e36.z, t2);
    return n2?.connectionPoints?.find((t3) => {
      return t3.pcb_port_id && (n3 = t3, i4 = e36, Math.abs(n3.x - i4.x) <= NP && Math.abs(n3.y - i4.y) <= NP) && dP(t3).includes(o4);
      var n3, i4;
    })?.pcb_port_id;
  }, a3 = s2(i3), c3 = s2(r3), l3 = [{ route_type: "wire", x: i3.x, y: i3.y, width: o3, layer: Qy(i3.z, t2), ...a3 ? { start_pcb_port_id: a3 } : {}, ...e35.length === 1 && c3 ? { end_pcb_port_id: c3 } : {} }];
  for (let i4 = 1;i4 < e35.length; i4 += 1) {
    const r4 = e35[i4 - 1], s3 = e35[i4];
    r4 && s3 && (r4.toNextSegmentType === "through_obstacle" || r4.z === s3.z || r4.x !== s3.x || r4.y !== s3.y ? l3.push({ route_type: "wire", x: s3.x, y: s3.y, width: o3, layer: Qy(s3.z, t2), ...i4 === e35.length - 1 && c3 ? { end_pcb_port_id: c3 } : {} }) : l3.push({ route_type: "via", x: s3.x, y: s3.y, from_layer: Qy(r4.z, t2), to_layer: Qy(s3.z, t2), ...n2?.viaDiameter ? { via_diameter: n2.viaDiameter } : {} }));
  }
  return l3;
};
var TP = 1048576;
var EP = (e35) => ({ ...e35, route: e35.route.map((e36) => ({ ...e36 })), vias: e35.vias.map((e36) => ({ ...e36 })) });
var AP = (e35) => e35.map(EP);
var OP = (e35, t2) => {
  const n2 = new Set(t2);
  return e35.map((e36, t3) => n2.has(t3) ? EP(e36) : e36);
};
var kP = (e35, t2) => Math.abs(e35.x - t2.x) <= xb && Math.abs(e35.y - t2.y) <= xb;
var DP = ["pcb_smtpad", "pcb_plated_hole", "pcb_hole", "pcb_keepout"];
var LP = (e35) => typeof e35.type == "string" ? e35.type : typeof e35.error_type == "string" ? e35.error_type : undefined;
var zP = (e35) => {
  if (LP(e35) === "pcb_pad_trace_clearance_error")
    return true;
  const t2 = typeof e35.message == "string" ? e35.message.toLowerCase() : "";
  return (t2.includes("pcb_trace") || t2.includes("pcb trace")) && DP.some((e36) => t2.includes(e36));
};
var BP = (e35, t2, n2 = true) => {
  const o3 = [], i3 = new Map, r3 = new Map, s2 = new Map;
  for (let e36 = 0;e36 < t2.length; e36 += 1) {
    const n3 = t2[e36];
    if (!n3)
      continue;
    const o4 = s2.get(n3.connectionName);
    o4 ? o4.push({ route: n3, routeIndex: e36 }) : s2.set(n3.connectionName, [{ route: n3, routeIndex: e36 }]);
  }
  for (const t3 of e35.connections) {
    const a3 = s2.get(t3.name) ?? [];
    for (let s3 = 0;s3 < a3.length; s3 += 1) {
      const c3 = a3[s3];
      if (!c3)
        continue;
      const l3 = `${t3.name}_${s3}`;
      n2 && o3.push({ type: "pcb_trace", pcb_trace_id: l3, connection_name: t3.netConnectionName ?? t3.rootConnectionName ?? t3.name, route: RP(c3.route.route, e35.layerCount, { traceThickness: c3.route.traceThickness ?? t3.nominalTraceWidth ?? e35.nominalTraceWidth ?? e35.minTraceWidth, viaDiameter: c3.route.viaDiameter ?? e35.minViaDiameter, connectionPoints: t3.pointsToConnect }) }), i3.set(l3, c3.routeIndex), r3.set(l3, t3.name);
    }
  }
  return { traces: o3, traceRouteIndexById: i3, traceConnectionNameById: r3 };
};
var FP = (e35) => {
  const t2 = typeof e35.message == "string" ? e35.message : "", n2 = t2.match(/gap: (-?\d+(?:\.\d+)?)mm/), o3 = t2.match(/required: (-?\d+(?:\.\d+)?)mm/);
  if (n2 && o3) {
    const e36 = Number.parseFloat(n2[1]), t3 = Number.parseFloat(o3[1]);
    if (Number.isFinite(e36) && Number.isFinite(t3))
      return Math.max(0, t3 - e36);
  }
  if (n2) {
    const e36 = Number.parseFloat(n2[1]), t3 = hP.traceClearance ?? 0.1;
    if (Number.isFinite(e36))
      return Math.max(0, t3 - e36);
  }
  return 1;
};
var jP = { projectEngineError: (e35) => ({ ...e35, center: typeof e35.first_contact_center == "object" ? e35.first_contact_center : e35.center, message: typeof e35.first_contact_message == "string" ? e35.first_contact_message : e35.message, actual_clearance: typeof e35.first_actual_clearance == "number" ? e35.first_actual_clearance : e35.actual_clearance }), getErrorSeverity: FP };
var $P = { projectEngineError: (e35) => e35, getErrorSeverity: (e35) => {
  const t2 = Number(e35.minimum_clearance), n2 = Number(e35.worst_actual_clearance);
  return Number.isFinite(t2) && Number.isFinite(n2) ? Math.max(0, t2 - n2) : FP(e35);
} };
var YP = (e35, t2 = FP) => e35.reduce((e36, n2) => e36 + t2(n2), 0);
var XP = (e35, t2, n2, o3, i3, r3 = jP) => {
  const s2 = n2?.inputMode === "routes-only";
  let a3 = i3 && !n2 || s2 ? e35 : _P(e35, o3), { traces: c3, traceRouteIndexById: l3, traceConnectionNameById: h2 } = BP(a3, t2, !s2);
  const d2 = n2?.({ srj: a3, routes: t2, traces: c3 });
  if (d2) {
    const e36 = Array.isArray(d2) ? d2 : d2.errors, t3 = Array.isArray(d2) ? d2 : d2.errorsWithCenters ?? d2.errors;
    return { rawErrors: e36, errors: t3, count: e36.length, issueScore: YP(t3, r3.getErrorSeverity), legacyIssueScore: YP(t3.filter((e37) => !uw(e37)), r3.getErrorSeverity), traceRouteIndexById: l3, traceConnectionNameById: h2 };
  }
  if (s2) {
    a3 = _P(e35, o3);
    const n3 = BP(a3, t2);
    c3 = n3.traces, l3 = n3.traceRouteIndexById, h2 = n3.traceConnectionNameById;
  }
  const u2 = i3?.evaluate(c3) ?? ((e36, t3 = {}) => {
    const n3 = Math.max(t3.viaClearance ?? 0.1, 0.1), o4 = [...iP(e36, lP(t3.traceClearance)), ...aP(e36, lP(n3)), ...cP(e36, lP(n3))], i4 = e36.filter((e37) => e37.type === "pcb_via"), r4 = new Map(i4.map((e37) => [e37.pcb_via_id, e37])), s3 = o4.map((e37) => {
      if ("center" in e37 && e37.center)
        return e37;
      if ("pcb_center" in e37 && e37.pcb_center)
        return { ...e37, center: e37.pcb_center };
      if ("pcb_via_ids" in e37 && Array.isArray(e37.pcb_via_ids)) {
        const [t4, n4] = e37.pcb_via_ids;
        if (typeof t4 != "string" || typeof n4 != "string")
          return e37;
        const o5 = r4.get(t4), i5 = r4.get(n4);
        if (o5 && i5)
          return { ...e37, center: { x: (o5.x + i5.x) / 2, y: (o5.y + i5.y) / 2 } };
      }
      if ("pcb_error_id" in e37 && typeof e37.pcb_error_id == "string" && (e37.pcb_error_id.startsWith("same_net_vias_close_") || e37.pcb_error_id.startsWith("different_net_vias_close_"))) {
        const t4 = e37.pcb_error_id.replace("same_net_vias_close_", "").replace("different_net_vias_close_", "").split("_").filter(Boolean);
        if (t4.length === 2) {
          const n4 = t4[0], o5 = t4[1];
          if (!n4 || !o5)
            return e37;
          const i5 = r4.get(n4), s4 = r4.get(o5);
          if (i5 && s4)
            return { ...e37, center: { x: (i5.x + s4.x) / 2, y: (i5.y + s4.y) / 2 } };
        }
      }
      return e37;
    }), a4 = s3.filter((e37) => Boolean(e37.center));
    return { errors: o4, errorsWithCenters: s3, locationAwareErrors: a4 };
  })(mP(a3, c3, a3.minTraceWidth, a3.minViaDiameter), { ...hP, traceClearance: a3.minTraceToPadEdgeClearance ?? hP.traceClearance, viaClearance: a3.minTraceToPadEdgeClearance ?? hP.viaClearance }), p3 = u2.errors, m2 = (u2.errorsWithCenters.length > 0 ? u2.errorsWithCenters : u2.errors).map((e36) => r3.projectEngineError(e36));
  return { rawErrors: p3, errors: m2, count: p3.length, issueScore: YP(m2, r3.getErrorSeverity), legacyIssueScore: YP(m2.filter((e36) => !uw(e36)), r3.getErrorSeverity), traceRouteIndexById: l3, traceConnectionNameById: h2 };
};
var HP = (e35, t2, n2, o3, i3) => XP(e35, t2, n2, o3, i3, jP);
var VP = (e35, t2, n2, o3, i3) => XP(e35, t2, n2, o3, i3, $P);
var WP = (e35, t2) => {
  const n2 = [];
  for (let o3 = 0;o3 < e35.length; o3 += 1) {
    const i3 = e35[o3];
    if (!i3)
      continue;
    let r3;
    for (let e36 = 0;e36 < i3.route.length - 1; e36 += 1) {
      const s2 = i3.route[e36], a3 = i3.route[e36 + 1];
      if (!s2 || !a3)
        continue;
      if (s2.z === a3.z || !kP(s2, a3))
        continue;
      const c3 = r3 ??= new Set, l3 = [e36, e36 + 1];
      for (let t3 = e36 - 1;t3 >= 0; t3 -= 1) {
        const e37 = i3.route[t3];
        if (!e37 || !kP(e37, s2))
          break;
        l3.push(t3);
      }
      for (let t3 = e36 + 2;t3 < i3.route.length; t3 += 1) {
        const e37 = i3.route[t3];
        if (!e37 || !kP(e37, s2))
          break;
        l3.push(t3);
      }
      const h2 = l3;
      if (h2.some((e37) => c3.has(e37)))
        continue;
      for (const e37 of h2)
        c3.add(e37);
      const d2 = h2.filter((e37) => e37 === 0 || e37 === i3.route.length - 1), u2 = d2.some((e37) => Boolean(i3.route[e37]?.pcb_port_id));
      let p3 = 0, m2 = t2.layerCount - 1;
      if (t2.allowBlindAndBuriedVias) {
        const e37 = h2.map((e38) => i3.route[e38].z);
        p3 = Math.min(...e37), m2 = Math.max(...e37);
      }
      n2.push({ routeIndex: o3, rootConnectionName: gP(i3), pointIndexes: h2, zLayers: Array.from({ length: m2 - p3 + 1 }, (e37, t3) => p3 + t3), x: s2.x, y: s2.y, radius: (i3.viaDiameter ?? t2.minViaDiameter ?? 0.3) / 2, movable: d2.length === 0, canCanonicalize: d2.length === 0 || !u2 });
    }
  }
  return n2;
};
var GP = (e35, t2) => {
  const n2 = [];
  for (let o3 = 0;o3 < e35.route.length - 1; o3 += 1) {
    const i3 = e35.route[o3], r3 = e35.route[o3 + 1];
    i3 && r3 && (i3.z !== r3.z || kP(i3, r3) || n2.push({ routeIndex: t2, rootConnectionName: gP(e35), startIndex: o3, endIndex: o3 + 1, start: i3, end: r3, z: i3.z, radius: (e35.traceThickness ?? 0.1) / 2 }));
  }
  return n2;
};
var UP = (e35) => e35.flatMap((e36, t2) => GP(e36, t2));
var ZP = (e35) => ({ minX: e35.x, minY: e35.y, maxX: e35.x, maxY: e35.y });
var qP = (e35) => ({ minX: Math.min(e35.start.x, e35.end.x), minY: Math.min(e35.start.y, e35.end.y), maxX: Math.max(e35.start.x, e35.end.x), maxY: Math.max(e35.start.y, e35.end.y) });
var JP = (e35) => ({ minX: e35.center.x - e35.width / 2, minY: e35.center.y - e35.height / 2, maxX: e35.center.x + e35.width / 2, maxY: e35.center.y + e35.height / 2 });
var QP = (e35, t2) => {
  if (e35.zLayers && e35.zLayers.length > 0)
    return e35.zLayers;
  const n2 = Array.from({ length: t2 }, (e36, t3) => t3).filter((n3) => e35.layers.includes(Qy(n3, t2)));
  return n2.length > 0 ? n2 : Array.from({ length: t2 }, (e36, t3) => t3);
};
var KP = (e35, t2, n2) => {
  const o3 = t2.reduce((e36, t3) => Math.max(e36, t3.radius), (e35.minViaDiameter ?? 0.3) / 2), i3 = n2.reduce((e36, t3) => Math.max(e36, t3.radius), e35.minTraceWidth / 2), r3 = (hP.traceClearance ?? 0.1) + Sb;
  return Math.max(2 * o3 + 0.2 + Sb, o3 + i3 + r3, 2 * i3 + r3, i3 + Cb(e35) + Sb, o3 + Pb(e35) + Sb);
};
var eM = (e35, t2, n2) => {
  const o3 = n2.x - t2.x, i3 = n2.y - t2.y, r3 = o3 * o3 + i3 * i3;
  if (r3 <= bb)
    return { x: t2.x, y: t2.y, t: 0 };
  const s2 = xP(((e35.x - t2.x) * o3 + (e35.y - t2.y) * i3) / r3, 0, 1);
  return { x: t2.x + o3 * s2, y: t2.y + i3 * s2, t: s2 };
};
var tM = (e35, t2) => eM(e35, t2.start, t2.end);
var nM = (e35, t2) => {
  if (t2.shape === "circle") {
    const n3 = Math.hypot(e35.x - t2.center.x, e35.y - t2.center.y);
    return Math.max(0, n3 - t2.width / 2);
  }
  const n2 = t2.width / 2, o3 = t2.height / 2, i3 = Math.max(Math.abs(e35.x - t2.center.x) - n2, 0), r3 = Math.max(Math.abs(e35.y - t2.center.y) - o3, 0);
  return Math.hypot(i3, r3);
};
var oM = (e35, t2) => e35.x >= t2.center.x - t2.width / 2 - xb && e35.x <= t2.center.x + t2.width / 2 + xb && e35.y >= t2.center.y - t2.height / 2 - xb && e35.y <= t2.center.y + t2.height / 2 + xb;
var iM = (e35, t2, n2, o3) => e35.obstacles.find((i3) => bP(gP(t2), i3, o3) && QP(i3, e35.layerCount).includes(n2.z) && oM(n2, i3));
var rM = (e35, t2, n2 = 0.6, o3) => {
  let i3;
  for (const r3 of e35.obstacles) {
    const e36 = nM(t2, r3);
    e36 > n2 || (o3 && !o3(r3) || (!i3 || e36 < i3.distance) && (i3 = { obstacle: r3, distance: e36 }));
  }
  return i3?.obstacle;
};
var sM = (e35, t2, n2) => {
  if (t2.shape === "circle") {
    const o4 = e35.x - t2.center.x, i4 = e35.y - t2.center.y, r4 = Math.hypot(o4, i4), s3 = n2 + t2.width / 2 - r4;
    if (s3 <= 0)
      return;
    let a4 = { x: 1, y: 0 };
    return r4 > bb && (a4 = { x: o4 / r4, y: i4 / r4 }), { direction: a4, penetration: s3 };
  }
  const o3 = t2.width / 2, i3 = t2.height / 2, r3 = xP(e35.x, t2.center.x - o3, t2.center.x + o3), s2 = xP(e35.y, t2.center.y - i3, t2.center.y + i3);
  let a3 = e35.x - r3, c3 = e35.y - s2, l3 = Math.hypot(a3, c3);
  if (l3 <= bb) {
    o3 - Math.abs(e35.x - t2.center.x) < i3 - Math.abs(e35.y - t2.center.y) ? (a3 = e35.x >= t2.center.x ? 1 : -1, c3 = 0, l3 = 0) : (a3 = 0, c3 = e35.y >= t2.center.y ? 1 : -1, l3 = 0);
  }
  const h2 = n2 - l3;
  if (h2 <= 0)
    return;
  const d2 = Math.hypot(a3, c3);
  return { direction: { x: d2 > bb ? a3 / d2 : 1, y: d2 > bb ? c3 / d2 : 0 }, penetration: h2 };
};
var aM = (e35, t2, n2, o3) => {
  const i3 = t2.message;
  if (typeof i3 != "string" || !i3.includes("pcb_"))
    return n2;
  const r3 = Array.isArray(t2.pcb_pad_ids) ? t2.pcb_pad_ids.filter((e36) => typeof e36 == "string") : [], s2 = e35.obstacles.find((e36) => r3.some((t3) => e36.connectedTo.includes(t3)) && (o3?.(e36) ?? true));
  return s2 ? s2.center : rM(e35, n2, 0.6, o3)?.center ?? n2;
};
var cM = (e35, t2) => {
  const n2 = e35.route[t2];
  if (!n2)
    return [];
  const o3 = [t2];
  for (let i3 = t2 - 1;i3 >= 0; i3 -= 1) {
    const t3 = e35.route[i3];
    if (!t3 || !kP(t3, n2))
      break;
    o3.push(i3);
  }
  for (let i3 = t2 + 1;i3 < e35.route.length; i3 += 1) {
    const t3 = e35.route[i3];
    if (!t3 || !kP(t3, n2))
      break;
    o3.push(i3);
  }
  return [...new Set(o3)];
};
var lM = (e35, t2) => {
  if (t2 <= 0 || t2 >= e35.route.length - 1)
    return;
  const n2 = cM(e35, t2);
  return n2.includes(0) || n2.includes(e35.route.length - 1) ? undefined : n2;
};
var hM = (e35, t2) => e35.x >= t2.minX - xb && e35.x <= t2.maxX + xb && e35.y >= t2.minY - xb && e35.y <= t2.maxY + xb;
var dM = (e35, t2) => Math.min(e35.x - t2.minX, t2.maxX - e35.x, e35.y - t2.minY, t2.maxY - e35.y);
var uM = (e35, t2, n2) => {
  const o3 = n2.x - t2.x, i3 = n2.y - t2.y, r3 = e35.x - t2.x, s2 = o3 * (e35.y - t2.y) - i3 * r3;
  if (Math.abs(s2) > xb)
    return false;
  const a3 = Math.min(t2.x, n2.x) - xb, c3 = Math.max(t2.x, n2.x) + xb, l3 = Math.min(t2.y, n2.y) - xb, h2 = Math.max(t2.y, n2.y) + xb;
  return e35.x >= a3 && e35.x <= c3 && e35.y >= l3 && e35.y <= h2;
};
var pM = (e35, t2) => {
  if (t2.length < 3)
    return true;
  for (let n3 = 0;n3 < t2.length; n3 += 1) {
    const o3 = t2[n3], i3 = t2[(n3 + 1) % t2.length];
    if (o3 && i3 && uM(e35, o3, i3))
      return true;
  }
  let n2 = false;
  for (let o3 = 0, i3 = t2.length - 1;o3 < t2.length; i3 = o3, o3 += 1) {
    const r3 = t2[o3], s2 = t2[i3];
    if (!r3 || !s2)
      continue;
    r3.y > e35.y != s2.y > e35.y && e35.x < (s2.x - r3.x) * (e35.y - r3.y) / (s2.y - r3.y) + r3.x && (n2 = !n2);
  }
  return n2;
};
var mM = (e35, t2) => {
  const n2 = Math.hypot(e35, t2);
  if (!(n2 <= bb))
    return { x: e35 / n2, y: t2 / n2 };
};
var gM = (e35, t2) => e35.outline && e35.outline.length >= 3 ? ((e36, t3) => {
  const n2 = pM(e36, t3);
  let o3;
  for (let n3 = 0;n3 < t3.length; n3 += 1) {
    const i4 = t3[n3], r4 = t3[(n3 + 1) % t3.length];
    if (!i4 || !r4)
      continue;
    const s3 = eM(e36, i4, r4), a4 = Math.hypot(e36.x - s3.x, e36.y - s3.y);
    (!o3 || a4 < o3.distance) && (o3 = { projection: s3, start: i4, end: r4, distance: a4 });
  }
  if (!o3)
    return;
  const i3 = mM(n2 ? e36.x - o3.projection.x : o3.projection.x - e36.x, n2 ? e36.y - o3.projection.y : o3.projection.y - e36.y);
  if (i3)
    return i3;
  const r3 = o3.end.x - o3.start.x, s2 = o3.end.y - o3.start.y, a3 = Math.hypot(r3, s2);
  if (a3 <= bb)
    return;
  const c3 = ((e37) => {
    let t4 = 0;
    for (let n3 = 0;n3 < e37.length; n3 += 1) {
      const o4 = e37[n3], i4 = e37[(n3 + 1) % e37.length];
      o4 && i4 && (t4 += o4.x * i4.y - i4.x * o4.y);
    }
    return t4 / 2;
  })(t3) >= 0;
  return { x: c3 ? -s2 / a3 : s2 / a3, y: c3 ? r3 / a3 : -r3 / a3 };
})(t2, e35.outline) : ((e36, t3) => {
  const n2 = e36.x - t3.minX, o3 = t3.maxX - e36.x, i3 = e36.y - t3.minY, r3 = t3.maxY - e36.y, s2 = Math.min(n2, o3, i3, r3);
  let a3 = 0, c3 = 0;
  return n2 <= s2 + xb && (a3 += 1), o3 <= s2 + xb && (a3 -= 1), i3 <= s2 + xb && (c3 += 1), r3 <= s2 + xb && (c3 -= 1), mM(a3, c3);
})(t2, e35.bounds);
var fM = (e35, t2) => e35.outline && e35.outline.length >= 3 ? pM(t2, e35.outline) : hM(t2, e35.bounds);
var _M = (e35, t2) => {
  if (e35.outline && e35.outline.length >= 3) {
    const n2 = ((e36, t3) => {
      let n3 = Number.POSITIVE_INFINITY;
      for (let o3 = 0;o3 < t3.length; o3 += 1) {
        const i3 = t3[o3], r3 = t3[(o3 + 1) % t3.length];
        i3 && r3 && (n3 = Math.min(n3, pe(e36, i3, r3)));
      }
      return n3;
    })(t2, e35.outline);
    return pM(t2, e35.outline) ? n2 : -n2;
  }
  return dM(t2, e35.bounds);
};
var yM = (e35, t2, n2) => {
  if (Math.abs(t2.x - n2.x) <= xb && Math.abs(t2.y - n2.y) <= xb)
    return Math.min(_M(e35, t2), _M(e35, n2));
  if (e35.outline && e35.outline.length >= 3) {
    if (!pM(t2, e35.outline) || !pM(n2, e35.outline))
      return Math.min(_M(e35, t2), _M(e35, n2));
    let o3 = Number.POSITIVE_INFINITY;
    for (let i3 = 0;i3 < e35.outline.length; i3 += 1) {
      const r3 = e35.outline[i3], s2 = e35.outline[(i3 + 1) % e35.outline.length];
      r3 && s2 && (o3 = Math.min(o3, we(t2, n2, r3, s2)));
    }
    return o3;
  }
  return hM(t2, e35.bounds) && hM(n2, e35.bounds) ? Math.min(dM(t2, e35.bounds), dM(n2, e35.bounds)) : Math.min(_M(e35, t2), _M(e35, n2));
};
var bM = (e35, t2) => t2 + Math.max(0.16, e35.defaultObstacleMargin ?? 0, hP.traceClearance ?? 0.1);
var xM = (e35, t2, n2) => t2 < e35 - xb && Math.min(e35, t2) <= n2 + xb;
var vM = (e35, t2, n2, o3, i3) => {
  const r3 = e35 * n2.x + t2 * n2.y, s2 = -Math.max(0, o3 - i3);
  if (r3 >= s2 - xb)
    return { x: e35, y: t2 };
  const a3 = s2 - r3;
  return { x: e35 + n2.x * a3, y: t2 + n2.y * a3 };
};
var IM = (e35, t2, n2, o3, i3) => {
  const r3 = gM(e35, t2);
  return r3 ? vM(n2, o3, r3, _M(e35, t2), bM(e35, i3)) : { x: n2, y: o3 };
};
var SM = (e35, t2, n2, o3) => {
  const i3 = [...new Set(n2)].sort((e36, t3) => e36 - t3);
  if (i3.length === 0)
    return Number.POSITIVE_INFINITY;
  const r3 = new Set(i3), s2 = (e36) => o3?.get(e36) ?? t2.route[e36];
  let a3 = Number.POSITIVE_INFINITY;
  for (const t3 of i3) {
    const n3 = s2(t3);
    n3 && (a3 = Math.min(a3, _M(e35, n3)));
  }
  for (let n3 = 0;n3 < t2.route.length - 1; n3 += 1) {
    if (!r3.has(n3) && !r3.has(n3 + 1))
      continue;
    const t3 = s2(n3), o4 = s2(n3 + 1);
    t3 && o4 && (a3 = Math.min(a3, yM(e35, t3, o4)));
  }
  return a3;
};
var CM = (e35, t2, n2, o3, i3, r3) => {
  const s2 = [...new Set(n2)].sort((e36, t3) => e36 - t3);
  if (s2.length === 0)
    return;
  const a3 = ((e36, t3, n3, o4, i4, r4) => {
    const s3 = [...new Set(n3)].sort((e37, t4) => e37 - t4);
    let a4 = { x: o4, y: i4 };
    const c4 = bM(e36, r4);
    for (let n4 = 0;n4 < Math.max(1, s3.length); n4 += 1) {
      let n5 = false;
      for (const o5 of s3) {
        const i5 = t3.route[o5];
        if (!i5)
          continue;
        const r5 = gM(e36, i5);
        if (!r5)
          continue;
        const s4 = vM(a4.x, a4.y, r5, _M(e36, i5), c4);
        (Math.abs(s4.x - a4.x) > bb || Math.abs(s4.y - a4.y) > bb) && (a4 = s4, n5 = true);
      }
      if (!n5)
        break;
    }
    return a4;
  })(e35, t2, s2, o3, i3, r3);
  if (Math.abs(a3.x) <= bb && Math.abs(a3.y) <= bb)
    return;
  const c3 = new Map;
  for (const e36 of s2) {
    const n3 = t2.route[e36];
    if (!n3)
      continue;
    const o4 = { x: n3.x + a3.x, y: n3.y + a3.y };
    c3.set(e36, o4);
  }
  const l3 = SM(e35, t2, s2), h2 = SM(e35, t2, s2, c3);
  if (h2 < r3 - xb)
    return;
  const d2 = bM(e35, r3);
  return xM(l3, h2, d2) ? undefined : a3;
};
var PM = (e35, t2, n2, o3, i3, r3, s2) => {
  const a3 = e35[t2];
  if (!a3)
    return false;
  const c3 = lM(a3, n2);
  if (!c3)
    return false;
  const l3 = CM(r3, a3, c3, o3, i3, s2);
  if (!l3)
    return false;
  let h2 = false;
  for (const e36 of c3) {
    const t3 = a3.route[e36];
    t3 && (t3.x += l3.x, t3.y += l3.y, vP(t3, r3.bounds), h2 = true);
  }
  return h2;
};
var MM = (e35, t2, n2, o3, i3, r3) => lM(t2, n2) ?? ((e36, t3, n3, o4, i4, r4) => {
  const s2 = t3.route[n3];
  if (!s2 || s2.pcb_port_id || n3 !== 0 && n3 !== t3.route.length - 1)
    return;
  const a3 = iM(e36, t3, s2, r4);
  if (!a3)
    return;
  const c3 = { ...s2, x: s2.x + o4, y: s2.y + i4 };
  return fM(e36, c3) && oM(c3, a3) ? cM(t3, n3) : undefined;
})(e35, t2, n2, o3, i3, r3);
var wM = (e35, t2, n2, o3, i3, r3) => {
  const s2 = CM(i3, e35, t2, n2, o3, r3);
  if (!s2)
    return false;
  let a3 = false;
  for (const n3 of t2) {
    const t3 = e35.route[n3];
    t3 && (t3.x += s2.x, t3.y += s2.y, vP(t3, i3.bounds), a3 = true);
  }
  return a3;
};
var NM = (e35, t2, n2, o3, i3, r3) => {
  const s2 = t2.route[n2];
  if (!s2)
    return false;
  if (s2.pcb_port_id)
    return false;
  const a3 = iM(e35, t2, s2, r3);
  return !!a3 && oM({ ...s2, x: s2.x + o3, y: s2.y + i3 }, a3);
};
var RM = (e35, t2, n2, o3) => {
  const i3 = t2.route[n2];
  if (i3 && !i3.pcb_port_id)
    return iM(e35, t2, i3, o3);
};
var TM = (e35, t2, n2, o3, i3, r3, s2) => {
  const a3 = e35[t2];
  if (!a3 || a3.route.length === 0)
    return false;
  const c3 = ((e36, t3, n3, o4, i4) => {
    let { NEGATIVE_INFINITY: r4, POSITIVE_INFINITY: s3, NEGATIVE_INFINITY: a4, POSITIVE_INFINITY: c4 } = Number;
    for (const n4 of [0, t3.route.length - 1]) {
      const o5 = t3.route[n4], l4 = RM(e36, t3, n4, i4);
      if (!o5 || !l4)
        return;
      r4 = Math.max(r4, l4.center.x - l4.width / 2 - o5.x), s3 = Math.min(s3, l4.center.x + l4.width / 2 - o5.x), a4 = Math.max(a4, l4.center.y - l4.height / 2 - o5.y), c4 = Math.min(c4, l4.center.y + l4.height / 2 - o5.y);
    }
    if (!(r4 > s3 || a4 > c4))
      return { x: xP(n3, r4, s3), y: xP(o4, a4, c4) };
  })(i3, a3, n2, o3, s2);
  if (!c3)
    return false;
  const l3 = a3.route.map((e36, t3) => t3), h2 = CM(i3, a3, l3, c3.x, c3.y, r3);
  if (!h2)
    return false;
  const d2 = a3.route.length - 1;
  if (!NM(i3, a3, 0, h2.x, h2.y, s2) || !NM(i3, a3, d2, h2.x, h2.y, s2))
    return false;
  let u2 = false;
  for (const e36 of a3.route)
    e36.x += h2.x, e36.y += h2.y, vP(e36, i3.bounds), u2 = true;
  return u2;
};
var EM = (e35, t2, n2) => {
  const o3 = t2.x - e35.x, i3 = t2.y - e35.y, r3 = n2.x - t2.x, s2 = n2.y - t2.y;
  return Math.abs(o3 * s2 - i3 * r3) <= xb;
};
var AM = (e35, t2) => {
  if (e35.z !== t2.z)
    return false;
  const n2 = t2.end.x - t2.start.x, o3 = t2.end.y - t2.start.y, i3 = e35.x - t2.start.x, r3 = e35.y - t2.start.y;
  return Math.abs(n2 * r3 - o3 * i3) <= xb;
};
var OM = (e35, t2) => {
  const n2 = ((e36, t3) => {
    const n3 = t3.end.x - t3.start.x, o4 = t3.end.y - t3.start.y, i3 = Math.max(xb, 0.12 * (e36.traceThickness ?? 0.1)), r3 = Math.abs(o4) <= i3, s2 = Math.abs(n3) <= i3;
    let { startIndex: a3, endIndex: c3 } = t3;
    if (r3 || s2) {
      const n4 = r3 ? (t3.start.y + t3.end.y) / 2 : (t3.start.x + t3.end.x) / 2;
      for (;a3 > 0; ) {
        const o5 = e36.route[a3 - 1];
        if (!o5 || o5.z !== t3.z || Math.abs((r3 ? o5.y : o5.x) - n4) > i3)
          break;
        a3 -= 1;
      }
      for (;c3 < e36.route.length - 1; ) {
        const o5 = e36.route[c3 + 1];
        if (!o5 || o5.z !== t3.z || Math.abs((r3 ? o5.y : o5.x) - n4) > i3)
          break;
        c3 += 1;
      }
      return Array.from({ length: c3 - a3 + 1 }, (e37, t4) => a3 + t4);
    }
    for (;a3 > 0; ) {
      const n4 = e36.route[a3 - 1], o5 = e36.route[a3], i4 = e36.route[a3 + 1];
      if (!(n4 && o5 && i4 && n4.z === t3.z && AM(n4, t3) && EM(n4, o5, i4)))
        break;
      a3 -= 1;
    }
    for (;c3 < e36.route.length - 1; ) {
      const n4 = e36.route[c3 - 1], o5 = e36.route[c3], i4 = e36.route[c3 + 1];
      if (!(n4 && o5 && i4 && i4.z === t3.z && AM(i4, t3) && EM(n4, o5, i4)))
        break;
      c3 += 1;
    }
    return Array.from({ length: c3 - a3 + 1 }, (e37, t4) => a3 + t4);
  })(e35, t2);
  if (n2.length <= 2)
    return;
  const o3 = [];
  for (const t3 of n2) {
    const n3 = lM(e35, t3);
    if (!n3)
      return;
    o3.push(...n3);
  }
  return [...new Set(o3)];
};
var kM = (e35, t2) => t2 > 0 && t2 < e35.route.length - 1 && !((e36, t3) => {
  const n2 = e36.route[t3];
  if (!n2)
    return false;
  const o3 = e36.route[t3 - 1], i3 = e36.route[t3 + 1];
  return o3 && o3.z !== n2.z && kP(o3, n2) || i3 && i3.z !== n2.z && kP(i3, n2);
})(e35, t2);
var DM = (e35, t2, n2) => {
  const o3 = e35.route[t2.startIndex], i3 = e35.route[t2.endIndex];
  return !(!o3 || !i3) && (o3.z === t2.z && i3.z === t2.z && (!!((e36, t3) => qP(e36).maxX >= t3.minX - xb && qP(e36).minX <= t3.maxX + xb && qP(e36).maxY >= t3.minY - xb && qP(e36).minY <= t3.maxY + xb)(t2, n2) && (kM(e35, t2.startIndex) || kM(e35, t2.endIndex))));
};
var LM = (e35, t2, n2, o3, i3, r3, s2) => {
  const a3 = e35[t2.routeIndex];
  if (!a3)
    return false;
  const c3 = ((e36, t3, n3, o4) => {
    const i4 = IP(JP(n3), o4);
    let { startIndex: r4, startIndex: s3 } = t3;
    for (;r4 > 0; ) {
      const n4 = { ...t3, startIndex: r4 - 1, endIndex: r4, start: e36.route[r4 - 1], end: e36.route[r4] };
      if (!e36.route[r4 - 1] || !DM(e36, n4, i4))
        break;
      r4 -= 1;
    }
    for (;s3 < e36.route.length - 2; ) {
      const n4 = { ...t3, startIndex: s3 + 1, endIndex: s3 + 2, start: e36.route[s3 + 1], end: e36.route[s3 + 2] };
      if (!e36.route[s3 + 2] || !DM(e36, n4, i4))
        break;
      s3 += 1;
    }
    const a4 = [];
    for (let t4 = r4;t4 <= s3 + 1; t4 += 1)
      kM(e36, t4) && a4.push(t4);
    return [...new Set(a4)];
  })(a3, t2, n2, o3);
  return !(c3.length <= 2) && wM(a3, c3, i3, r3, s2, t2.radius);
};
var zM = (e35, t2) => {
  const n2 = tM(t2, e35), o3 = n2.x - t2.x, i3 = n2.y - t2.y, r3 = Math.hypot(o3, i3), s2 = e35.end.x - e35.start.x, a3 = e35.end.y - e35.start.y, c3 = Math.hypot(s2, a3), l3 = e35.routeIndex % 2 == 0 ? 1 : -1;
  return { projection: n2, direction: r3 > bb ? { x: o3 / r3, y: i3 / r3 } : c3 > bb ? { x: -a3 / c3 * l3, y: s2 / c3 * l3 } : { x: 1, y: 0 } };
};
var BM = (e35, t2, n2, o3, i3) => {
  const r3 = e35[t2.routeIndex];
  if (!r3)
    return false;
  const s2 = IM(i3, t2, n2, o3, t2.radius);
  if (Math.abs(s2.x) <= bb && Math.abs(s2.y) <= bb)
    return false;
  const a3 = { x: t2.x + s2.x, y: t2.y + s2.y }, c3 = _M(i3, t2), l3 = _M(i3, a3);
  if (l3 < t2.radius - xb)
    return false;
  const h2 = bM(i3, t2.radius);
  if (xM(c3, l3, h2))
    return false;
  t2.x += s2.x, t2.y += s2.y, vP(t2, i3.bounds);
  for (const e36 of t2.pointIndexes) {
    const n3 = r3.route[e36];
    n3 && (n3.x = t2.x, n3.y = t2.y);
  }
  return true;
};
var FM = ({ routes: e35, via: t2, srj: n2 }) => {
  if (!Number.isInteger(t2.routeIndex))
    return [];
  const o3 = e35[t2.routeIndex];
  if (!o3 || t2.routeIndex < 0 || t2.routeIndex >= e35.length)
    return [];
  const i3 = WP([o3], n2), r3 = i3.find((e36) => e36.pointIndexes.some((e37) => t2.pointIndexes.includes(e37)));
  if (!r3)
    return [];
  const s2 = [];
  for (let o4 = 0;o4 < e35.length; o4 += 1) {
    const a3 = e35[o4];
    if (!a3 || gP(a3) !== r3.rootConnectionName)
      continue;
    const c3 = o4 === t2.routeIndex ? i3 : WP([a3], n2);
    for (const e36 of c3)
      e36.routeIndex = o4, e36.rootConnectionName === r3.rootConnectionName && Math.hypot(e36.x - r3.x, e36.y - r3.y) <= xb && s2.push(e36);
  }
  return s2;
};
var jM = (e35, t2, n2, o3, i3) => t2.movable && FM({ routes: e35, via: t2, srj: i3 }).length <= 1 && BM(e35, t2, n2, o3, i3);
var $M = (e35, t2, n2, o3, i3 = 1) => {
  const { projection: r3, direction: s2 } = zM(t2, n2), a3 = vb * i3, c3 = 1 - r3.t, l3 = r3.t, h2 = PM(e35, t2.routeIndex, t2.startIndex, s2.x * a3 * c3, s2.y * a3 * c3, o3, t2.radius), d2 = PM(e35, t2.routeIndex, t2.endIndex, s2.x * a3 * l3, s2.y * a3 * l3, o3, t2.radius);
  return !(!h2 && !d2) || ((e36, t3, n3, o4, i4) => {
    const r4 = e36[t3.routeIndex];
    if (!r4)
      return false;
    const { projection: s3, direction: a4 } = zM(t3, n3), c4 = IM(o4, s3, a4.x * vb * i4, a4.y * vb * i4, t3.radius);
    if (Math.abs(c4.x) <= bb && Math.abs(c4.y) <= bb)
      return false;
    const l4 = { ...r4.route[t3.startIndex], x: s3.x + c4.x, y: s3.y + c4.y };
    if (vP(l4, o4.bounds), pe(l4, t3.start, t3.end) <= xb)
      return false;
    const h3 = r4.route[t3.startIndex], d3 = r4.route[t3.endIndex];
    if (!h3 || !d3)
      return false;
    const u2 = yM(o4, h3, d3), p3 = Math.min(_M(o4, l4), yM(o4, h3, l4), yM(o4, l4, d3));
    if (p3 < t3.radius - xb)
      return false;
    const m2 = bM(o4, t3.radius);
    return !xM(u2, p3, m2) && (r4.route.splice(t3.endIndex, 0, l4), true);
  })(e35, t2, n2, o3, i3);
};
var YM = (e35, t2, n2, o3, i3, r3 = 1) => {
  const s2 = t2.radius + Cb(o3) + Sb, a3 = tw(t2, n2, s2);
  if (!a3)
    return false;
  const c3 = Math.min(0.3 * Math.abs(r3), a3.penetration + Sb), l3 = a3.direction.x * c3, h2 = a3.direction.y * c3, d2 = e35[t2.routeIndex];
  if (!d2)
    return false;
  const u2 = !((e36) => {
    for (let t3 = 0;t3 < e36.route.length - 1; t3 += 1) {
      const n3 = e36.route[t3], o4 = e36.route[t3 + 1];
      if (n3 && o4 && n3.z !== o4.z && kP(n3, o4))
        return true;
    }
    return false;
  })(d2);
  if (u2 && TM(e35, t2.routeIndex, l3, h2, o3, t2.radius, i3))
    return true;
  const p3 = LM(e35, t2, n2, s2, l3, h2, o3) || ((e36, t3, n3, o4, i4) => {
    const r4 = e36[t3.routeIndex];
    if (!r4)
      return false;
    const s3 = OM(r4, t3);
    return !!s3 && wM(r4, s3, n3, o4, i4, t3.radius);
  })(e35, t2, l3, h2, o3) || ((e36, t3, n3, o4, i4, r4) => {
    const s3 = e36[t3.routeIndex];
    if (!s3)
      return false;
    const a4 = MM(i4, s3, t3.startIndex, n3, o4, r4), c4 = MM(i4, s3, t3.endIndex, n3, o4, r4);
    if (!a4 || !c4)
      return false;
    const l4 = [...new Set([...a4, ...c4])], h3 = CM(i4, s3, l4, n3, o4, t3.radius);
    if (!h3)
      return false;
    let d3 = false;
    for (const e37 of l4) {
      const t4 = s3.route[e37];
      t4 && (t4.x += h3.x, t4.y += h3.y, vP(t4, i4.bounds), d3 = true);
    }
    return d3;
  })(e35, t2, l3, h2, o3, i3);
  if (p3)
    return true;
  if (!u2 && TM(e35, t2.routeIndex, l3, h2, o3, t2.radius, i3))
    return true;
  const m2 = n2.width / 2, g2 = n2.height / 2, f2 = (Math.abs(a3.direction.y) >= Math.abs(a3.direction.x) ? [{ ...d2.route[t2.startIndex], x: n2.center.x - m2 - s2, y: n2.center.y + a3.direction.y * (g2 + s2) }, { ...d2.route[t2.startIndex], x: n2.center.x + m2 + s2, y: n2.center.y + a3.direction.y * (g2 + s2) }] : [{ ...d2.route[t2.startIndex], x: n2.center.x + a3.direction.x * (m2 + s2), y: n2.center.y - g2 - s2 }, { ...d2.route[t2.startIndex], x: n2.center.x + a3.direction.x * (m2 + s2), y: n2.center.y + g2 + s2 }]).map((e36) => {
    const { t: n3 } = tM(e36, t2), i4 = { x: t2.start.x + (t2.end.x - t2.start.x) * n3, y: t2.start.y + (t2.end.y - t2.start.y) * n3 }, r4 = IM(o3, i4, e36.x - i4.x, e36.y - i4.y, t2.radius);
    return e36.x = i4.x + r4.x, e36.y = i4.y + r4.y, vP(e36, o3.bounds), { point: e36, t: n3, moved: Math.abs(r4.x) > bb || Math.abs(r4.y) > bb, awayFromObstacleMotion: r4.x * a3.direction.x + r4.y * a3.direction.y };
  }).sort((e36, t3) => e36.t - t3.t);
  if (!f2.some(({ moved: e36 }) => e36))
    return false;
  if (!f2.some(({ awayFromObstacleMotion: e36 }) => e36 > xb))
    return false;
  const _2 = f2.map(({ point: e36 }) => e36);
  if (_2.every((e36) => pe(e36, t2.start, t2.end) <= xb))
    return false;
  if (_2.some((e36) => !fM(o3, e36)))
    return false;
  const y2 = d2.route[t2.startIndex], b2 = d2.route[t2.endIndex], x2 = _2[0], v2 = _2[1];
  if (!(y2 && b2 && x2 && v2))
    return false;
  const I2 = yM(o3, y2, b2), S2 = Math.min(_M(o3, x2), _M(o3, v2), yM(o3, y2, x2), yM(o3, x2, v2), yM(o3, v2, b2));
  if (S2 < t2.radius - xb)
    return false;
  const C = bM(o3, t2.radius);
  return !xM(I2, S2, C) && (d2.route.splice(t2.endIndex, 0, ..._2), true);
};
var XM = (e35, t2, n2) => {
  let o3;
  for (const i3 of e35) {
    if (n2 !== undefined && i3.routeIndex !== n2)
      continue;
    const e36 = tM(t2, i3), r3 = Math.hypot(e36.x - t2.x, e36.y - t2.y);
    (!o3 || r3 < o3.distance) && (o3 = { segment: i3, distance: r3 });
  }
  return o3?.segment;
};
var HM = (e35, t2, n2) => {
  let o3;
  for (const i3 of e35) {
    if (n2 !== undefined && i3.routeIndex !== n2)
      continue;
    const e36 = Math.hypot(i3.x - t2.x, i3.y - t2.y);
    (!o3 || e36 < o3.distance) && (o3 = { via: i3, distance: e36 });
  }
  return o3?.via;
};
var VM = (e35, t2) => {
  const n2 = e35.map((e36) => ({ via: e36, distance: Math.hypot(e36.x - t2.x, e36.y - t2.y) })).sort((e36, t3) => e36.distance - t3.distance).slice(0, 2).map(({ via: e36 }) => e36);
  return n2.length === 2 ? n2 : undefined;
};
var WM = (e35, t2, n2, o3) => {
  const i3 = t2.x - n2.x, r3 = t2.y - n2.y, s2 = Math.hypot(i3, r3);
  return jM(e35, t2, (s2 > bb ? i3 / s2 : 1) * vb, (s2 > bb ? r3 / s2 : 0) * vb, o3);
};
var GM = (e35, t2) => {
  const n2 = tM(e35.start, t2), o3 = tM(e35.end, t2), i3 = tM(t2.start, e35), r3 = tM(t2.end, e35), s2 = [{ leftT: 0, rightT: n2.t, leftPoint: e35.start, rightPoint: n2 }, { leftT: 1, rightT: o3.t, leftPoint: e35.end, rightPoint: o3 }, { leftT: i3.t, rightT: 0, leftPoint: i3, rightPoint: t2.start }, { leftT: r3.t, rightT: 1, leftPoint: r3, rightPoint: t2.end }];
  let a3 = s2[0], c3 = Math.hypot(a3.leftPoint.x - a3.rightPoint.x, a3.leftPoint.y - a3.rightPoint.y);
  for (let e36 = 1;e36 < s2.length; e36 += 1) {
    const t3 = s2[e36], n3 = Math.hypot(t3.leftPoint.x - t3.rightPoint.x, t3.leftPoint.y - t3.rightPoint.y);
    n3 < c3 && (a3 = t3, c3 = n3);
  }
  return a3;
};
var UM = (e35, t2, n2, o3, i3, r3) => {
  const s2 = xP(r3, 0, 1), a3 = 1 - s2, c3 = s2, l3 = PM(e35, t2.routeIndex, t2.startIndex, n2 * a3, o3 * a3, i3, t2.radius), h2 = PM(e35, t2.routeIndex, t2.endIndex, n2 * c3, o3 * c3, i3, t2.radius);
  return l3 || h2;
};
var ZM = (e35, t2, n2, o3, i3, r3 = 0.035, s2 = false, a3) => {
  if (!s2 && (a3 ? a3.routesShareNet(t2, n2) : yP(t2.rootConnectionName, n2.rootConnectionName, i3)))
    return false;
  const c3 = t2.radius + n2.radius + 0.2 + Sb, l3 = t2.x - n2.x, h2 = t2.y - n2.y, d2 = Math.hypot(l3, h2), u2 = c3 - d2;
  if (u2 <= 0)
    return false;
  const p3 = 1.618 * (97 * t2.routeIndex + 13 * n2.routeIndex), m2 = d2 > bb ? l3 / d2 : Math.cos(p3), g2 = d2 > bb ? h2 / d2 : Math.sin(p3), f2 = Number(t2.movable) + Number(n2.movable);
  if (f2 === 0)
    return false;
  const _2 = Math.min(r3, u2 / f2), y2 = jM(e35, t2, m2 * _2, g2 * _2, o3), b2 = jM(e35, n2, -m2 * _2, -g2 * _2, o3);
  return y2 || b2;
};
var qM = (e35, t2, n2, o3, i3) => {
  if (!yP(t2.rootConnectionName, n2.rootConnectionName, i3))
    return false;
  const [r3, s2] = t2.canCanonicalize ? n2.canCanonicalize && t2.routeIndex <= n2.routeIndex ? [t2, n2] : [n2, t2] : [t2, n2];
  return ((e36, t3, n3, o4) => {
    if (!n3.canCanonicalize)
      return false;
    const i4 = t3.x - n3.x, r4 = t3.y - n3.y;
    if (!n3.movable && Math.hypot(i4, r4) > n3.radius + xb)
      return false;
    const s3 = e36[n3.routeIndex];
    if (!s3)
      return false;
    const a3 = { x: n3.x, y: n3.y }, c3 = n3.pointIndexes.map((e37) => {
      const t4 = s3.route[e37];
      return t4 ? { pointIndex: e37, x: t4.x, y: t4.y } : undefined;
    });
    if (BM(e36, n3, i4, r4, o4) && kP(n3, t3))
      return true;
    n3.x = a3.x, n3.y = a3.y;
    for (const e37 of c3) {
      if (!e37)
        continue;
      const t4 = s3.route[e37.pointIndex];
      t4 && (t4.x = e37.x, t4.y = e37.y);
    }
    return false;
  })(e35, r3, s2, o3);
};
var JM = (e35, t2, n2, o3, i3, r3 = 0.035, s2 = 2, a3 = false, c3) => {
  if (c3 ? c3.routesShareNet(t2, n2) : yP(t2.rootConnectionName, n2.rootConnectionName, i3))
    return false;
  const l3 = tM(t2, n2), h2 = t2.x - l3.x, d2 = t2.y - l3.y, u2 = Math.hypot(h2, d2), p3 = t2.radius + n2.radius + (hP.traceClearance ?? 0.1) + Sb - u2;
  if (p3 <= 0)
    return false;
  const m2 = n2.end.x - n2.start.x, g2 = n2.end.y - n2.start.y, f2 = Math.hypot(m2, g2), _2 = t2.routeIndex % 2 == 0 ? 1 : -1, y2 = u2 > bb ? h2 / u2 : f2 > bb ? -g2 / f2 * _2 : 1, b2 = u2 > bb ? d2 / u2 : f2 > bb ? m2 / f2 * _2 : 0, x2 = Math.min(r3, p3 / s2), v2 = a3 ? ((e36, t3, n3, o4, i4) => {
    const r4 = FM({ routes: e36, via: t3, srj: i4 });
    if (r4.length === 0 || r4.some((t4) => !t4.movable || e36[t4.routeIndex] === undefined))
      return false;
    const s3 = r4.reduce((e37, t4) => t4.radius > e37.radius ? t4 : e37);
    if (!BM(e36, s3, n3, o4, i4))
      return false;
    for (const t4 of r4) {
      if (t4 === s3)
        continue;
      t4.x = s3.x, t4.y = s3.y;
      const n4 = e36[t4.routeIndex];
      for (const e37 of t4.pointIndexes) {
        const t5 = n4.route[e37];
        t5 && (t5.x = s3.x, t5.y = s3.y);
      }
    }
    return true;
  })(e35, t2, y2 * x2, b2 * x2, o3) : jM(e35, t2, y2 * x2, b2 * x2, o3), I2 = UM(e35, n2, -y2 * x2, -b2 * x2, o3, l3.t);
  return v2 || I2;
};
var QM = (e35, t2, n2, o3, i3, r3) => {
  if (t2.z !== n2.z || (r3 ? r3.routesShareNet(t2, n2) : yP(t2.rootConnectionName, n2.rootConnectionName, i3)))
    return false;
  const s2 = GM(t2, n2), a3 = s2.leftPoint.x - s2.rightPoint.x, c3 = s2.leftPoint.y - s2.rightPoint.y, l3 = Math.hypot(a3, c3), h2 = t2.radius + n2.radius + (hP.traceClearance ?? 0.1) + Sb - l3;
  if (h2 <= 0)
    return false;
  const d2 = t2.end.x - t2.start.x, u2 = t2.end.y - t2.start.y, p3 = Math.hypot(d2, u2), m2 = (t2.routeIndex + n2.routeIndex) % 2 == 0 ? 1 : -1, g2 = l3 > bb ? a3 / l3 : p3 > bb ? -u2 / p3 * m2 : 1, f2 = l3 > bb ? c3 / l3 : p3 > bb ? d2 / p3 * m2 : 0, _2 = Math.min(Ib, h2 / 2), y2 = UM(e35, t2, g2 * _2, f2 * _2, o3, s2.leftT), b2 = UM(e35, n2, -g2 * _2, -f2 * _2, o3, s2.rightT);
  return y2 || b2;
};
var KM = (e35, t2, n2) => QP(e35, n2).includes(t2.z);
var ew = (e35, t2, n2, o3, i3) => {
  const r3 = t2[n2];
  if (!r3)
    return;
  const s2 = GP(r3, n2);
  if (s2.length === 0)
    return;
  const a3 = gP(r3), c3 = XM(s2, o3);
  if (!c3)
    return;
  const l3 = rM(e35, o3, 0.6, (t3) => !bP(a3, t3, i3) && KM(t3, c3, e35.layerCount));
  if (l3)
    return { obstacle: l3, segment: c3 };
  const h2 = rM(e35, o3, 0.6, (t3) => !bP(a3, t3, i3) && s2.some((n3) => KM(t3, n3, e35.layerCount)));
  if (!h2)
    return;
  const d2 = XM(s2.filter((t3) => KM(h2, t3, e35.layerCount)), o3);
  return d2 ? { obstacle: h2, segment: d2 } : undefined;
};
var tw = (e35, t2, n2) => {
  const o3 = t2.width / 2, i3 = t2.height / 2, r3 = [{ x: t2.center.x - o3, y: t2.center.y - i3 }, { x: t2.center.x + o3, y: t2.center.y - i3 }, { x: t2.center.x + o3, y: t2.center.y + i3 }, { x: t2.center.x - o3, y: t2.center.y + i3 }], s2 = [t2.center, ...r3].map((t3) => tM(t3, e35)), a3 = [{ point: e35.start, t: 0 }, { point: e35.end, t: 1 }, { point: { x: (e35.start.x + e35.end.x) / 2, y: (e35.start.y + e35.end.y) / 2 }, t: 0.5 }, ...s2.map((e36) => ({ point: { x: e36.x, y: e36.y }, t: e36.t }))];
  let c3;
  const l3 = Math.hypot(e35.end.x - e35.start.x, e35.end.y - e35.start.y);
  for (const o4 of a3) {
    const i4 = sM(o4.point, t2, n2);
    if (!i4)
      continue;
    const r4 = l3 > bb ? Math.abs(((e35.end.x - e35.start.x) * i4.direction.y - (e35.end.y - e35.start.y) * i4.direction.x) / l3) : 0;
    (!c3 || i4.penetration > c3.penetration + bb || Math.abs(i4.penetration - c3.penetration) <= bb && r4 > c3.normality) && (c3 = { ...i4, normality: r4, t: o4.t });
  }
  return c3;
};
var nw = (e35, t2, n2, o3 = false, i3) => {
  let r3 = false;
  const s2 = WP(t2, e35), a3 = UP(t2), c3 = KP(e35, s2, a3), l3 = Math.max(1, 2 * c3), h2 = MP(s2, ZP, l3), d2 = MP(a3, qP, l3);
  for (let a4 = 0;a4 < s2.length; a4 += 1) {
    const d3 = s2[a4];
    if (!d3)
      continue;
    const u2 = wP(h2, IP(ZP(d3), c3), l3);
    for (const c4 of u2) {
      if (c4 <= a4)
        continue;
      const l4 = s2[c4];
      l4 && (r3 = ZM(t2, d3, l4, e35, n2, Ib, o3, i3) || r3);
    }
  }
  for (let o4 = 0;o4 < s2.length; o4 += 1) {
    const h3 = s2[o4];
    if (!h3)
      continue;
    const u2 = wP(d2, IP(ZP(h3), c3), l3);
    for (const o5 of u2) {
      const s3 = a3[o5];
      s3 && (r3 = JM(t2, h3, s3, e35, n2, Ib, 2, false, i3) || r3);
    }
  }
  for (let o4 = 0;o4 < a3.length; o4 += 1) {
    const s3 = a3[o4];
    if (!s3)
      continue;
    const h3 = wP(d2, IP(qP(s3), c3), l3);
    for (const c4 of h3) {
      if (c4 <= o4)
        continue;
      const l4 = a3[c4];
      l4 && (r3 = QM(t2, s3, l4, e35, n2, i3) || r3);
    }
  }
  return ((e36, t3, n3, o4, i4, r4, s3, a4, c4) => {
    let l4 = false;
    const h3 = Cb(e36), d3 = o4.reduce((e37, t4) => Math.max(e37, t4.radius), 0) + h3 + Sb, u2 = Pb(e36), p3 = n3.reduce((e37, t4) => Math.max(e37, t4.radius), 0) + u2 + Sb;
    for (const m2 of e36.obstacles) {
      if (m2.isCopperPour)
        continue;
      const g2 = JP(m2), f2 = c4?.forObstacle(m2), _2 = wP(i4, IP(g2, p3), s3);
      for (const o5 of _2) {
        const i5 = n3[o5];
        if (!i5)
          continue;
        if (f2 ? f2(i5) : bP(i5.rootConnectionName, m2, a4))
          continue;
        const r5 = sM(i5, m2, i5.radius + u2 + Sb);
        if (!r5)
          continue;
        const s4 = Math.min(Ib, r5.penetration);
        l4 = jM(t3, i5, r5.direction.x * s4, r5.direction.y * s4, e36) || l4;
      }
      const y2 = wP(r4, IP(g2, d3), s3);
      for (const n4 of y2) {
        const i5 = o4[n4];
        if (!i5)
          continue;
        if ((f2 ? f2(i5) : bP(i5.rootConnectionName, m2, a4)) || !KM(m2, i5, e36.layerCount))
          continue;
        const r5 = tw(i5, m2, i5.radius + h3 + Sb);
        if (!r5)
          continue;
        const s4 = Math.min(Ib, r5.penetration);
        l4 = UM(t3, i5, r5.direction.x * s4, r5.direction.y * s4, e36, r5.t) || l4;
      }
    }
    return l4;
  })(e35, t2, s2, a3, h2, d2, l3, n2, i3) || r3;
};
var ow = (e35, t2, n2, o3 = 1, i3, r3 = false, s2 = true) => {
  const a3 = AP(t2), c3 = ((e36, t3, n3) => {
    const o4 = e36 * e36 <= TP ? new Uint8Array(e36 * e36) : undefined, i4 = e36 * t3 <= TP, r4 = new WeakMap;
    return { routesShareNet: (t4, i5) => {
      const r5 = t4.routeIndex * e36 + i5.routeIndex, s3 = o4?.[r5];
      if (s3)
        return s3 === 2;
      const a4 = yP(t4.rootConnectionName, i5.rootConnectionName, n3);
      return o4 && (o4[r5] = a4 ? 2 : 1), a4;
    }, forObstacle: (t4) => {
      let o5 = r4.get(t4);
      if (o5)
        return o5;
      const s3 = i4 ? new Uint8Array(e36) : undefined;
      return o5 = (e37) => {
        const o6 = s3?.[e37.routeIndex];
        if (o6)
          return o6 === 2;
        const i5 = bP(e37.rootConnectionName, t4, n3);
        return s3 && (s3[e37.routeIndex] = i5 ? 2 : 1), i5;
      }, r4.set(t4, o5), o5;
    } };
  })(a3.length, e35.obstacles.length, i3), l3 = Math.max(2, Math.round(12 * Math.max(1, n2) * o3));
  let h2 = false;
  for (let t3 = 0;t3 < l3; t3 += 1) {
    if (!nw(e35, a3, i3, r3, c3))
      break;
    h2 = true;
  }
  return h2 && s2 && ((e36, t3, n3, o4) => {
    let i4 = false;
    const r4 = WP(t3, e36), s3 = UP(t3), a4 = KP(e36, r4, s3), c4 = Math.max(1, 2 * a4), l4 = MP(s3, qP, c4);
    for (const h3 of r4) {
      const r5 = wP(l4, IP(ZP(h3), a4), c4);
      for (const a5 of r5) {
        const r6 = s3[a5];
        r6 && (i4 = JM(t3, h3, r6, e36, n3, Ib, 1.75, false, o4) || i4);
      }
    }
  })(e35, a3, i3, c3), h2 ? sw(a3) : t2;
};
var iw = (e35) => {
  const t2 = [];
  for (let n2 = 0;n2 < e35.route.length - 1; n2 += 1) {
    const o3 = e35.route[n2], i3 = e35.route[n2 + 1];
    if (!o3 || !i3)
      continue;
    if (o3.toNextSegmentType === "through_obstacle")
      continue;
    if (o3.z === i3.z || !kP(o3, i3))
      continue;
    const r3 = { x: o3.x, y: o3.y }, s2 = t2.at(-1);
    s2 && kP(s2, r3) || t2.push(r3);
  }
  return t2;
};
var rw = (e35) => ({ ...e35, vias: iw(e35) });
var sw = (e35) => e35.map(rw);
var aw = (e35, t2) => {
  const n2 = new Set(t2);
  return e35.map((e36, t3) => n2.has(t3) ? rw(e36) : e36);
};
var cw = (e35) => {
  const t2 = e35.pcb_trace_id;
  if (typeof t2 != "string")
    return;
  const n2 = t2.match(/^trace_(\d+)/);
  return n2 ? Number.parseInt(n2[1], 10) : undefined;
};
var lw = (e35) => {
  const t2 = e35.center ?? e35.pcb_center;
  if (!t2 || typeof t2 != "object")
    return;
  const n2 = t2;
  return typeof n2.x == "number" && typeof n2.y == "number" ? { x: n2.x, y: n2.y } : undefined;
};
var hw = (e35, t2 = true) => e35.errors.filter((e36) => ((e37) => LP(e37) === "pcb_via_clearance_error" || Array.isArray(e37.pcb_via_ids))(e36) && (t2 || !uw(e36))).length;
var dw = (e35) => LP(e35) === "pcb_placement_error" && Array.isArray(e35.pcb_via_ids) && e35.pcb_via_ids.length === 1 && Array.isArray(e35.pcb_pad_ids);
var uw = (e35) => LP(e35) === "pcb_pad_pad_clearance_error" && Array.isArray(e35.pcb_via_ids) && e35.pcb_via_ids.length === 1;
var pw = (e35) => {
  const t2 = Object.entries(e35).filter(([e36, t3]) => e36 !== "source_trace_id" && (e36.endsWith("_id") || e36.endsWith("_ids")) && t3 !== undefined && t3 !== "").sort(([e36], [t3]) => e36.localeCompare(t3)), n2 = typeof e35.message == "string" ? e35.message.replace(/-?\d+\.\d+/g, "#") : "";
  return JSON.stringify([LP(e35), t2, n2]);
};
var mw = (e35) => Math.max(e35.errors.filter((e36) => !uw(e36)).length, e35.count - e35.errors.filter(uw).length);
var gw = (e35) => {
  const t2 = mw(e35);
  return t2 > 0 ? t2 : e35.count;
};
var fw = (e35) => {
  if (mw(e35) === 0)
    return e35.issueScore;
  const t2 = e35.errors.filter((e36) => !uw(e36));
  return e35.errors.some(uw) ? YP(t2) : e35.legacyIssueScore ?? YP(t2);
};
var _w = (e35, t2) => {
  const n2 = e35.pcb_trace_id;
  if (typeof n2 != "string" || n2.length === 0)
    return;
  const o3 = [e35.pcb_pad_id, e35.pcb_smtpad_id, e35.pcb_plated_hole_id, e35.pcb_hole_id, e35.pcb_keepout_id, e35.pcb_obstacle_id].find((e36) => typeof e36 == "string" && e36.length > 0), i3 = e35.worst_contact_message ?? e35.message, r3 = typeof i3 == "string" ? i3.match(/\b(?:pcb_smtpad|pcb_plated_hole|pcb_hole|pcb_keepout)\s+"([^"]+)"/)?.[1] : undefined, s2 = o3 ?? r3?.match(/\[#([^\]]+)\]/)?.[1] ?? r3;
  if (!s2)
    return;
  const a3 = t2.traceConnectionNameById?.get(n2);
  return JSON.stringify([a3 === undefined ? "trace" : "connection", a3 ?? n2, s2]);
};
var yw = (e35) => {
  const t2 = [], n2 = e35.rawErrors ? e35.rawErrors.concat(e35.errors) : e35.errors;
  for (const o3 of n2) {
    if (!_w(o3, e35) && !zP(o3))
      continue;
    const n3 = o3.worst_actual_clearance ?? o3.actual_clearance, i3 = o3.worst_contact_message ?? o3.message;
    (typeof n3 == "number" && Number.isFinite(n3) ? n3 < -0.001 : typeof i3 == "string" && i3.includes("(accidental contact)")) && t2.push(o3);
  }
  return t2;
};
var bw = (e35) => new Set(yw(e35).map((t2) => _w(t2, e35) ?? Symbol("unidentified trace-obstacle contact")));
var xw = (e35, t2) => {
  const n2 = bw(e35);
  if (n2.size === 0)
    return false;
  const o3 = bw(t2);
  return [...n2].some((e36) => !o3.has(e36));
};
var vw = (e35, t2) => {
  if (e35.errors.filter(dw).length > t2.errors.filter(dw).length)
    return false;
  const n2 = mw(e35), o3 = mw(t2);
  return n2 !== o3 ? n2 < o3 : !(n2 > 0) && e35.count < t2.count;
};
var Iw = (e35) => {
  const t2 = e35.filter(dw);
  if (t2.length > 0)
    return t2;
  const n2 = e35.filter((e36) => !uw(e36));
  return n2.length > 0 ? n2 : e35;
};
var Sw = (e35, t2) => {
  const n2 = e35.pcb_trace_id;
  return typeof n2 == "string" ? t2.get(n2) ?? cw(e35) : cw(e35);
};
var Cw = (e35, t2, n2, o3, i3) => {
  const r3 = n2.pcb_port_id;
  if (!r3)
    return false;
  const s2 = (i3 ?? t2.viaDiameter) / 2;
  return e35.obstacles.some((i4) => {
    const a3 = QP(i4, e35.layerCount);
    return !(a3.length !== 1 || a3[0] !== n2.z || !i4.connectedTo.includes(r3) || n2.x - s2 < i4.center.x - i4.width / 2 - bb || n2.x + s2 > i4.center.x + i4.width / 2 + bb || n2.y - s2 < i4.center.y - i4.height / 2 - bb || n2.y + s2 > i4.center.y + i4.height / 2 + bb) && (bP(gP(t2), i4, o3) || bP(t2.connectionName, i4, o3));
  });
};
var Pw = [0, 1, -1, 2, -2, 3, -3, 4];
var Mw = Pw.flatMap((e35) => Pw.map((t2) => [e35, t2])).sort(([e35, t2], [n2, o3]) => Math.abs(e35) + Math.abs(t2) - Math.abs(n2) - Math.abs(o3));
var ww = Mw.length;
var Nw = (e35, t2) => {
  const n2 = t2 * Math.PI / 4, o3 = Math.cos(n2), i3 = Math.sin(n2);
  return { x: e35.x * o3 - e35.y * i3, y: e35.x * i3 + e35.y * o3 };
};
var Rw = (e35, t2, n2) => e35.x - t2 >= n2.minX - bb && e35.x + t2 <= n2.maxX + bb && e35.y - t2 >= n2.minY - bb && e35.y + t2 <= n2.maxY + bb;
var Tw = (e35, t2) => {
  const n2 = e35.at(-1);
  n2 && n2.x === t2.x && n2.y === t2.y && n2.z === t2.z && n2.pcb_port_id === t2.pcb_port_id || e35.push(t2);
};
var Ew = (e35, t2, n2, o3, i3, r3, s2, a3 = 0) => {
  const c3 = LP(n2);
  if (c3 !== "pcb_pad_trace_clearance_error" && c3 !== "pcb_trace_error")
    return false;
  if (i3 < 0 || i3 >= e35.layerCount)
    return false;
  const l3 = t2[o3];
  if (!l3 || l3.route.length < 2)
    return false;
  const h2 = l3.route.map((e36) => ({ ...e36 })), d2 = h2[0], u2 = h2.at(-1);
  if (!d2 || !u2)
    return false;
  const p3 = lw(n2);
  if (!p3)
    return false;
  const m2 = zP(n2), g2 = m2 ? ew(e35, t2, o3, p3, s2) : undefined, f2 = m2 ? g2?.segment : XM(GP(l3, o3), p3);
  if (!f2 || f2.z === i3)
    return false;
  let { startIndex: _2, endIndex: y2 } = f2;
  const b2 = r3 === "full" ? h2.length : r3;
  for (let e36 = 0;e36 < b2; e36 += 1) {
    let e37 = false;
    const t3 = h2[_2 - 1];
    t3?.z === f2.z && (_2 -= 1, e37 = true);
    const n3 = h2[y2 + 1];
    if (n3?.z === f2.z && (y2 += 1, e37 = true), !e37)
      break;
  }
  const x2 = _2 === 0 && d2.pcb_port_id, v2 = y2 === h2.length - 1 && u2.pcb_port_id, I2 = l3.viaDiameter / 2, S2 = Mw[a3 % ww], C = (t3) => {
    const n3 = t3 === "start" ? d2 : u2, o4 = ((e36, t4, n4, o5) => {
      const i5 = n4.pcb_port_id;
      if (i5)
        return e36.obstacles.find((r5) => {
          const s3 = QP(r5, e36.layerCount);
          return !(s3.length !== 1 || s3[0] !== n4.z || !r5.connectedTo.includes(i5) || !oM(n4, r5)) && (bP(gP(t4), r5, o5) || bP(t4.connectionName, r5, o5));
        });
    })(e35, l3, n3, s2), i4 = ((e36, t4) => {
      const n4 = t4 === "start" ? e36[0] : e36.at(-1);
      if (!n4)
        return;
      const o5 = t4 === "start" ? Array.from({ length: e36.length - 1 }, (e37, t5) => t5 + 1) : Array.from({ length: e36.length - 1 }, (t5, n5) => e36.length - n5 - 2);
      for (const t5 of o5) {
        const o6 = e36[t5];
        if (!o6)
          continue;
        const i5 = o6.x - n4.x, r5 = o6.y - n4.y, s3 = Math.hypot(i5, r5);
        if (!(s3 <= bb))
          return { x: i5 / s3, y: r5 / s3 };
      }
    })(h2, t3);
    if (!o4 || !i4)
      return;
    const r4 = t3 === "start" ? S2[0] : S2[1], a4 = I2 + Pb(e35) + bb, c4 = (({ endpoint: e36, pad: t4, direction: n4, requiredDistance: o5 }) => {
      let i5 = 0, r5 = Math.hypot(t4.width, t4.height) + 2 * o5;
      const s3 = (t5) => ({ x: e36.x + n4.x * t5, y: e36.y + n4.y * t5 });
      if (!(nM(s3(r5), t4) < o5)) {
        for (;r5 - i5 > bb; ) {
          const e37 = (i5 + r5) / 2;
          nM(s3(e37), t4) >= o5 ? r5 = e37 : i5 = e37;
        }
        return s3(r5);
      }
    })({ endpoint: n3, pad: o4, direction: Nw(i4, r4), requiredDistance: a4 });
    return !c4 || !Rw(c4, I2, e35.bounds) || nM(c4, o4) + bb < a4 ? undefined : c4;
  }, P = x2 ? C("start") : undefined, M = v2 ? C("end") : undefined;
  if (x2 && !P || v2 && !M)
    return false;
  const w = [];
  for (let e36 = 0;e36 < _2; e36 += 1)
    Tw(w, h2[e36]);
  const N = h2[_2], R2 = h2[_2 - 1], T2 = R2?.x === N.x && R2.y === N.y, E3 = h2[y2], A2 = h2[y2 + 1], O2 = A2?.x === E3.x && A2.y === E3.y;
  x2 ? (Tw(w, d2), Tw(w, { ...d2, ...P, pcb_port_id: undefined }), Tw(w, { ...d2, ...P, z: i3, pcb_port_id: undefined })) : (T2 || Tw(w, { ...N, pcb_port_id: undefined }), Tw(w, { ...N, z: i3, pcb_port_id: undefined }));
  const k2 = v2 ? y2 - 1 : y2;
  for (let e36 = _2 + 1;e36 <= k2; e36 += 1)
    Tw(w, { ...h2[e36], z: i3, pcb_port_id: undefined });
  v2 ? (Tw(w, { ...u2, ...M, z: i3, pcb_port_id: undefined }), Tw(w, { ...u2, ...M, pcb_port_id: undefined }), Tw(w, u2)) : O2 || Tw(w, { ...E3, pcb_port_id: undefined });
  for (let e36 = y2 + 1;e36 < h2.length; e36 += 1)
    Tw(w, h2[e36]);
  for (let e36 = 1;e36 < w.length - 1; e36 += 1)
    w[e36].pcb_port_id = undefined;
  return l3.route = w, true;
};
var Aw = (e35, t2, n2, o3, i3, r3, s2) => {
  const a3 = LP(n2);
  if (a3 !== "pcb_pad_trace_clearance_error" && a3 !== "pcb_trace_error")
    return false;
  if (i3 < 0 || i3 >= e35.layerCount)
    return false;
  const c3 = Sw(n2, o3);
  if (c3 === undefined)
    return false;
  const l3 = t2[c3];
  if (!l3 || l3.route.length < 2)
    return false;
  const h2 = l3.route[0], d2 = l3.route.at(-1);
  if (!h2 || !d2 || h2.z !== d2.z || i3 === h2.z)
    return false;
  if (l3.route.some((e36) => e36.z !== h2.z))
    return false;
  if (!h2.pcb_port_id || !d2.pcb_port_id)
    return false;
  if (!Cw(e35, l3, h2, r3, s2) || !Cw(e35, l3, d2, r3, s2))
    return false;
  const u2 = l3.route.map((e36) => ({ ...e36 }));
  return l3.route = [u2[0], { ...u2[0], z: i3, pcb_port_id: undefined }, ...u2.slice(1, -1).map((e36) => ({ ...e36, z: i3 })), { ...u2.at(-1), z: i3, pcb_port_id: undefined }, u2.at(-1)], true;
};
var Ow = (e35, t2, n2, o3, i3, r3, s2) => {
  if (LP(n2) !== "pcb_pad_trace_clearance_error")
    return false;
  const a3 = Sw(n2, o3);
  if (a3 === undefined)
    return false;
  const c3 = t2[a3];
  if (!c3 || c3.route.length < 4)
    return false;
  const l3 = c3.route.map((e36) => ({ ...e36 }));
  if (i3 === "start") {
    const t3 = l3[0];
    if (!Cw(e35, c3, t3, r3, s2))
      return false;
    let n3 = -1;
    for (let e36 = 1;e36 < l3.length; e36 += 1)
      if (l3[e36].z !== t3.z) {
        n3 = e36;
        break;
      }
    if (n3 <= 0)
      return false;
    const o4 = n3 - 1;
    if (!kP(l3[o4], l3[n3]))
      return false;
    let i4 = n3;
    for (;i4 + 1 < l3.length && kP(l3[n3], l3[i4 + 1]); )
      i4 += 1;
    const a4 = l3[i4].z, h3 = l3.slice(o4, i4 + 1).map((e36) => e36.z);
    return c3.route = [t3, ...h3.slice(1).map((e36) => ({ ...t3, z: e36, pcb_port_id: undefined })), ...l3.slice(1, o4 + 1).map((e36) => ({ ...e36, z: a4 })), ...l3.slice(i4 + 1)], true;
  }
  const h2 = l3.at(-1);
  if (!Cw(e35, c3, h2, r3, s2))
    return false;
  let d2 = -1;
  for (let e36 = l3.length - 2;e36 >= 0; e36 -= 1)
    if (l3[e36].z !== h2.z) {
      d2 = e36;
      break;
    }
  if (d2 < 0 || d2 >= l3.length - 1)
    return false;
  const u2 = d2 + 1;
  if (!kP(l3[d2], l3[u2]))
    return false;
  let p3 = d2;
  for (;p3 - 1 >= 0 && kP(l3[d2], l3[p3 - 1]); )
    p3 -= 1;
  const m2 = l3[p3].z, g2 = l3.slice(p3, u2 + 1).map((e36) => e36.z);
  return c3.route = [...l3.slice(0, p3 + 1), ...l3.slice(u2 + 1, -1).map((e36) => ({ ...e36, z: m2 })), { ...h2, z: m2, pcb_port_id: undefined }, ...g2.slice(1, -1).map((e36) => ({ ...h2, z: e36, pcb_port_id: undefined })), h2], true;
};
var kw = (e35, t2) => {
  const n2 = e35.pcb_trace_id;
  if (typeof n2 != "string")
    return;
  if (Array.isArray(e35.pcb_via_ids) && e35.pcb_via_ids.length > 0)
    return;
  const o3 = Array.isArray(e35.pcb_trace_ids) ? e35.pcb_trace_ids.filter((e36) => typeof e36 == "string") : [], i3 = e35.pcb_trace_error_id, r3 = `overlap_${n2}_`, s2 = typeof i3 == "string" && i3.startsWith(r3) ? i3.slice(r3.length) : undefined, a3 = [n2, ...o3, ...s2 ? [s2] : []], c3 = [...new Set(a3.map((e36) => t2.get(e36)).filter((e36) => e36 !== undefined))];
  return c3.length >= 2 ? [c3[0], c3[1]] : undefined;
};
var Dw = (e35, t2, n2, o3, i3) => {
  if (LP(n2) !== "pcb_trace_error")
    return;
  const r3 = kw(n2, o3);
  if (!r3)
    return;
  const s2 = n2.worst_contact_center ?? n2.center;
  if (!s2 || typeof s2 != "object")
    return;
  const a3 = s2;
  if (typeof a3.x != "number" || typeof a3.y != "number")
    return;
  const c3 = { x: a3.x, y: a3.y }, l3 = UP(t2), h2 = XM(l3, c3, r3[0]), d2 = XM(l3, c3, r3[1]);
  if (!h2 || !d2 || h2.z !== d2.z)
    return;
  const u2 = GM(h2, d2), p3 = u2.leftPoint.x - u2.rightPoint.x, m2 = u2.leftPoint.y - u2.rightPoint.y, g2 = Math.hypot(p3, m2), f2 = Number(n2.minimum_clearance), _2 = Number.isFinite(f2) ? f2 : hP.traceClearance ?? 0.1, y2 = h2.radius + d2.radius + _2 - g2;
  if (y2 <= bb)
    return;
  const b2 = i3 === 0 ? h2 : d2, x2 = i3 === 0 ? u2.leftT : u2.rightT, v2 = (1 - x2) ** 2 + x2 ** 2;
  if (v2 <= bb)
    return;
  const I2 = y2 / v2, S2 = i3 === 0 ? u2.leftPoint : u2.rightPoint, C = i3 === 0 ? u2.rightPoint : u2.leftPoint, P = i3 === 0 ? 1 : -1, M = b2.end.x - b2.start.x, w = b2.end.y - b2.start.y, N = Math.hypot(M, w), R2 = (b2.routeIndex + (i3 === 0 ? d2.routeIndex : h2.routeIndex)) % 2 == 0 ? 1 : -1, T2 = g2 > bb ? (S2.x - C.x) / g2 : N > bb ? -w / N * R2 * P : P, E3 = g2 > bb ? (S2.y - C.y) / g2 : N > bb ? M / N * R2 * P : 0;
  return UM(t2, b2, T2 * I2, E3 * I2, e35, x2) ? { movedRouteIndex: b2.routeIndex } : undefined;
};
var Lw = (e35) => {
  const { srj: t2, via: n2, segment: o3, initialTarget: i3, requiredTraceDistance: r3, requiredObstacleDistance: s2, connMap: a3 } = e35, c3 = t2.obstacles.filter((e36) => !e36.isCopperPour && !bP(n2.rootConnectionName, e36, a3) && QP(e36, t2.layerCount).some((e37) => n2.zLayers.includes(e37))), l3 = c3.filter((e36) => Boolean(sM(i3, e36, s2))), h2 = [i3, ...l3.flatMap((e36) => ((e37) => {
    const { point: t3, obstacle: n3, requiredDistance: o4 } = e37, i4 = n3.center.x - n3.width / 2, r4 = n3.center.x + n3.width / 2, s3 = n3.center.y - n3.height / 2, a4 = n3.center.y + n3.height / 2, c4 = Math.max(i4 - t3.x, t3.x - r4, 0), l4 = Math.max(s3 - t3.y, t3.y - a4, 0), h3 = [];
    if (c4 < o4) {
      const e38 = Math.sqrt(o4 * o4 - c4 * c4);
      h3.push({ x: t3.x, y: s3 - e38 - bb }, { x: t3.x, y: a4 + e38 + bb });
    }
    if (l4 < o4) {
      const e38 = Math.sqrt(o4 * o4 - l4 * l4);
      h3.push({ x: i4 - e38 - bb, y: t3.y }, { x: r4 + e38 + bb, y: t3.y });
    }
    return h3;
  })({ point: i3, obstacle: e36, requiredDistance: s2 }))];
  return h2.filter((e36) => {
    if (!Rw(e36, n2.radius, t2.bounds))
      return false;
    const i4 = tM(e36, o3);
    return !(Math.hypot(e36.x - i4.x, e36.y - i4.y) < r3 - bb) && c3.every((t3) => nM(e36, t3) >= s2 - bb);
  }).sort((e36, t3) => Math.hypot(e36.x - n2.x, e36.y - n2.y) - Math.hypot(t3.x - n2.x, t3.y - n2.y))[0];
};
var zw = (e35, t2, n2, o3, i3, r3) => {
  if (LP(n2) !== "pcb_trace_error")
    return false;
  const s2 = typeof n2.pcb_trace_error_id == "string" ? n2.pcb_trace_error_id.toLowerCase() : "", a3 = typeof n2.message == "string" ? n2.message.toLowerCase() : "";
  if (!(typeof n2.pcb_via_id == "string" || Array.isArray(n2.pcb_via_ids) || s2.includes("_via_") || a3.includes("via")))
    return false;
  if (Sw(n2, o3) !== i3)
    return false;
  if (kw(n2, o3))
    return false;
  const c3 = n2.worst_contact_center ?? n2.center;
  if (!c3 || typeof c3 != "object")
    return false;
  const l3 = c3;
  if (typeof l3.x != "number" || typeof l3.y != "number")
    return false;
  const h2 = { x: l3.x, y: l3.y }, d2 = XM(UP(t2), h2, i3), u2 = HM(WP(t2, e35), h2);
  if (!d2 || !u2 || !u2.movable || yP(u2.rootConnectionName, d2.rootConnectionName, r3))
    return false;
  const p3 = tM(u2, d2), m2 = u2.x - p3.x, g2 = u2.y - p3.y, f2 = Math.hypot(m2, g2), _2 = Number(n2.minimum_clearance), y2 = Number.isFinite(_2) ? _2 : hP.traceClearance ?? 0.1, b2 = u2.radius + d2.radius + y2 - f2;
  if (b2 <= bb)
    return false;
  const x2 = d2.end.x - d2.start.x, v2 = d2.end.y - d2.start.y, I2 = Math.hypot(x2, v2), S2 = u2.routeIndex % 2 == 0 ? 1 : -1, C = f2 > bb ? m2 / f2 : I2 > bb ? -v2 / I2 * S2 : 1, P = f2 > bb ? g2 / f2 : I2 > bb ? x2 / I2 * S2 : 0, M = u2.radius + d2.radius + y2 + Sb, w = u2.radius + Pb(e35) + Sb, N = { x: u2.x + C * (b2 + Sb), y: u2.y + P * (b2 + Sb) }, R2 = Lw({ srj: e35, via: u2, segment: d2, initialTarget: N, requiredTraceDistance: M, requiredObstacleDistance: w, connMap: r3 });
  return !!R2 && jM(t2, u2, R2.x - u2.x, R2.y - u2.y, e35);
};
var Bw = (e35, t2, n2) => {
  if (LP(t2) !== "pcb_trace_error")
    return;
  const o3 = lw(t2), i3 = e35[n2];
  if (!o3 || !i3)
    return;
  const r3 = XM(GP(i3, n2), o3);
  return r3 ? { center: o3, route: i3, segment: r3 } : undefined;
};
var Fw = (e35, t2, n2, o3) => {
  const i3 = Bw(e35, t2, n2);
  if (!i3)
    return;
  const { route: r3, segment: s2 } = i3, a3 = Math.max(0, s2.startIndex - o3), c3 = Math.min(r3.route.length - 1, s2.endIndex + o3), l3 = r3.route.slice(a3, c3 + 1), h2 = l3[0], d2 = l3.at(-1);
  return h2 && d2 && !l3.some((e36) => e36.z !== h2.z) && h2.z === d2.z ? { route: r3, spanStartIndex: a3, spanEndIndex: c3, start: h2, end: d2 } : undefined;
};
var jw = (e35, t2, n2, o3, i3, r3, s2 = 0, a3, c3) => {
  if (r3 < 0 || r3 >= e35.layerCount)
    return false;
  const l3 = kw(n2, o3);
  if (!l3)
    return false;
  const h2 = l3[i3], d2 = Bw(t2, n2, h2);
  if (!d2 || d2.segment.z === r3)
    return false;
  const { route: u2, segment: p3 } = d2;
  let { startIndex: m2, endIndex: g2 } = p3;
  for (let e36 = 0;e36 < s2; e36 += 1) {
    const e37 = u2.route[m2 - 1];
    e37?.z === p3.z && (m2 -= 1);
    const t3 = u2.route[g2 + 1];
    t3?.z === p3.z && (g2 += 1);
  }
  if (m2 === 0 && u2.route[0]?.pcb_port_id && !Cw(e35, u2, u2.route[0], a3, c3) || g2 === u2.route.length - 1 && u2.route.at(-1)?.pcb_port_id && !Cw(e35, u2, u2.route.at(-1), a3, c3))
    return false;
  const f2 = u2.route[m2], _2 = u2.route[g2];
  if (!f2 || !_2 || f2.z !== _2.z)
    return false;
  const y2 = u2.route.slice(m2, g2 + 1).map((e36) => ({ ...e36, z: r3, pcb_port_id: undefined }));
  return u2.route.splice(m2, g2 - m2 + 1, { ...f2 }, ...y2, { ..._2 }), true;
};
var $w = (e35, t2, n2, o3, i3, r3) => {
  if (o3 <= 0 || i3 <= 0)
    return false;
  const s2 = Bw(e35, t2, n2);
  if (!s2)
    return false;
  const { center: a3, route: c3, segment: l3 } = s2, h2 = l3.end.x - l3.start.x, d2 = l3.end.y - l3.start.y, u2 = Math.hypot(h2, d2);
  if (u2 <= bb)
    return false;
  const p3 = tM(a3, l3), m2 = xP(p3.t - o3 / u2, 0.02, 0.98), g2 = xP(p3.t + o3 / u2, 0.02, 0.98);
  if (m2 >= g2)
    return false;
  const f2 = (e36) => ({ x: l3.start.x + h2 * e36, y: l3.start.y + d2 * e36, z: l3.z }), _2 = f2(m2), y2 = f2(g2), b2 = -d2 / u2 * r3, x2 = h2 / u2 * r3, v2 = c3.route[l3.startIndex], I2 = c3.route[l3.endIndex];
  return c3.route.splice(l3.startIndex, 2, { ...v2 }, _2, { ..._2, x: _2.x + b2 * i3, y: _2.y + x2 * i3 }, { ...y2, x: y2.x + b2 * i3, y: y2.y + x2 * i3 }, y2, { ...I2 }), true;
};
var Yw = (e35, t2, n2, o3, i3, r3, s2, a3 = false) => {
  if (!Number.isInteger(i3) || i3 < 0 || i3 >= e35.layerCount)
    return false;
  const c3 = lw(n2), l3 = t2[o3], h2 = l3?.route[0], d2 = l3?.route.at(-1);
  if (!l3 || !c3 || !h2 || !d2 || h2.z !== d2.z || h2.z === i3 || l3.jumpers?.length || l3.route.some((e36) => e36.z !== h2.z || e36.toNextSegmentType === "through_obstacle"))
    return false;
  const u2 = d2.x - h2.x, p3 = d2.y - h2.y, m2 = Math.hypot(u2, p3);
  if (m2 <= bb || m2 > 8)
    return false;
  const g2 = u2 / m2, f2 = p3 / m2, _2 = f2 * r3, y2 = -g2 * r3, b2 = (e36) => (e36.x - c3.x) * g2 + (e36.y - c3.y) * f2, x2 = (e36, t3, n3) => ({ x: c3.x + g2 * e36 + _2 * t3, y: c3.y + f2 * e36 + y2 * t3, z: n3 }), v2 = (l3.viaDiameter ?? e35.minViaDiameter ?? 0.3) + (e35.minTraceToPadEdgeClearance ?? hP.traceClearance ?? 0.1), I2 = (a3 ? 1.25 : -0.75) * v2, S2 = (a3 ? -0.75 : 1.25) * v2, C = b2(h2) + 0.5 * v2 * s2, P = b2(d2) + v2 * s2, M = x2(C, I2, h2.z), w = x2(P, S2, h2.z), N = x2(C, 2 * v2, i3), R2 = x2(P, 2 * v2, i3), T2 = [{ ...h2 }, M, { ...M, z: i3 }, N, R2, { ...w, z: i3 }, w, { ...d2 }], E3 = e35.minBoardEdgeClearance ?? 0, A2 = (l3.viaDiameter ?? e35.minViaDiameter ?? 0.3) / 2, O2 = l3.traceThickness / 2;
  if ([M, w].some((t3) => _M(e35, t3) + xb < A2 + E3))
    return false;
  for (let t3 = 0;t3 < T2.length - 1; t3 += 1) {
    const n3 = T2[t3], o4 = T2[t3 + 1];
    if (n3.z === o4.z && yM(e35, n3, o4) + xb < O2 + E3)
      return false;
  }
  return l3.route.splice(0, l3.route.length, ...T2), true;
};
var Xw = (e35, t2, n2, o3, i3, r3, s2) => {
  if (!Number.isInteger(i3) || i3 < 1 || r3 <= 0)
    return false;
  const a3 = Fw(t2, n2, o3, i3);
  if (!a3)
    return false;
  const { route: c3, spanStartIndex: l3, spanEndIndex: h2, start: d2, end: u2 } = a3, p3 = u2.x - d2.x, m2 = u2.y - d2.y, g2 = Math.hypot(p3, m2);
  if (g2 <= bb)
    return false;
  const f2 = -m2 / g2 * s2 * r3, _2 = p3 / g2 * s2 * r3, y2 = { ...d2, x: d2.x + f2, y: d2.y + _2, pcb_port_id: undefined }, b2 = { ...u2, x: u2.x + f2, y: u2.y + _2, pcb_port_id: undefined };
  return !(!hM(y2, e35.bounds) || !hM(b2, e35.bounds)) && (c3.route.splice(l3, h2 - l3 + 1, { ...d2 }, y2, b2, { ...u2 }), true);
};
var Hw = (e35, t2, n2, o3, i3, r3) => {
  if (!Number.isInteger(i3) || i3 < 0)
    return false;
  const s2 = Fw(t2, n2, o3, i3);
  if (!s2)
    return false;
  const { route: a3, spanStartIndex: c3, spanEndIndex: l3, start: h2, end: d2 } = s2;
  return !(Math.hypot(r3.x - h2.x, r3.y - h2.y) <= bb || Math.hypot(r3.x - d2.x, r3.y - d2.y) <= bb || !hM(r3, e35.bounds)) && (a3.route.splice(c3, l3 - c3 + 1, { ...h2 }, { x: r3.x, y: r3.y, z: h2.z }, { ...d2 }), true);
};
var Vw = (e35, t2, n2, o3, i3, r3) => {
  if (r3) {
    if (e35.errors.filter(dw).length > r3.errors.filter(dw).length)
      return false;
    const t3 = mw(e35), n3 = mw(r3);
    if (t3 !== n3)
      return t3 < n3;
  }
  const s2 = gw(e35), a3 = fw(e35);
  return s2 < n2 || s2 === n2 && a3 < o3 || s2 === n2 && t2 < i3;
};
var Ww = (e35, t2, n2, o3, i3, r3, s2 = true, a3 = false, c3 = true, l3 = false) => {
  let h2 = false, d2 = WP(t2, e35), u2 = UP(t2);
  for (const p3 of n2) {
    const n3 = lw(p3);
    if (!n3)
      continue;
    let m2 = n3;
    const g2 = p3.pcb_via_ids, f2 = LP(p3) === "pcb_via_clearance_error", _2 = uw(p3), y2 = Array.isArray(g2) && g2.length > 0, b2 = !f2 && !_2 && !Array.isArray(p3.pcb_pad_ids) && y2 && (typeof p3.pcb_trace_id == "string" || Array.isArray(p3.pcb_trace_ids)), x2 = l3 && b2;
    if (y2 && !b2) {
      m2 = aM(e35, p3, n3);
      const c4 = Sw(p3, o3), l4 = g2.length > 1 ? VM(d2, n3) : undefined;
      if (l4) {
        const n4 = a3 && LP(p3) === "pcb_via_clearance_error" && p3.pcb_via_pair_net_relation === "same_net", o4 = s2 && LP(p3) === "pcb_via_clearance_error";
        h2 = (n4 ? qM(t2, l4[0], l4[1], e35, r3) : ZM(t2, l4[0], l4[1], e35, r3, 0.16 * Math.abs(i3), o4)) || h2;
      } else {
        const o4 = HM(d2, n3, c4);
        if (o4)
          if (dw(p3) && typeof p3.minimum_clearance == "number" && typeof p3.actual_clearance == "number") {
            const n4 = o4.x - m2.x, r4 = o4.y - m2.y, s3 = Math.hypot(n4, r4), a4 = Math.min(vb, p3.minimum_clearance - p3.actual_clearance + bb) * i3;
            h2 = jM(t2, o4, (s3 > bb ? n4 / s3 : 1) * a4, (s3 > bb ? r4 / s3 : 0) * a4, e35) || h2;
          } else
            h2 = WM(t2, o4, m2, e35) || h2;
      }
      continue;
    }
    const v2 = p3.pcb_trace_id, I2 = Sw(p3, o3);
    if (x2 && I2 === undefined)
      continue;
    const S2 = Array.isArray(p3.pcb_trace_ids) ? p3.pcb_trace_ids.filter((e36) => typeof e36 == "string") : [];
    if (x2 && typeof v2 == "string" && I2 !== undefined && S2.includes(v2) && S2.some((e36) => e36 !== v2 && !o3.has(e36))) {
      const o4 = HM(d2, n3, I2);
      if (o4) {
        h2 = WM(t2, o4, n3, e35) || h2;
        continue;
      }
    }
    const C = s2 && !b2 ? kw(p3, o3) : undefined;
    if (C) {
      const o4 = XM(u2, n3, C[0]), i4 = XM(u2, n3, C[1]);
      if (o4 && i4 && QM(t2, o4, i4, e35, r3)) {
        h2 = true;
        continue;
      }
    }
    const P = zP(p3), M = P && I2 !== undefined ? ew(e35, t2, I2, n3, r3) : undefined, w = P ? M?.segment : XM(u2, n3, I2);
    if (w) {
      const o4 = P ? M?.obstacle : rM(e35, n3);
      if (P && !o4)
        continue;
      m2 = P ? o4?.center ?? n3 : aM(e35, p3, n3);
      const s3 = x2 ? undefined : HM(d2, n3), a4 = LP(p3) === "pcb_via_trace_clearance_error", l4 = typeof p3.pcb_trace_error_id == "string" ? p3.pcb_trace_error_id.toLowerCase() : "", g3 = typeof p3.message == "string" ? p3.message.toLowerCase() : "", f3 = a4 || typeof p3.pcb_via_id == "string" || Array.isArray(p3.pcb_via_ids) || l4.includes("_via_") || g3.includes("via"), _3 = Array.isArray(p3.pcb_port_ids) && p3.pcb_port_ids.length > 0;
      if (s3 && !yP(s3.rootConnectionName, w.rootConnectionName, r3) && (a4 || Math.hypot(s3.x - n3.x, s3.y - n3.y) < 0.45)) {
        if (JM(t2, s3, w, e35, r3, 0.3 * Math.abs(i3), 1, c3) && (h2 = true, f3 && !_3))
          continue;
      }
      const y3 = o4 !== undefined && (P || !bP(w.rootConnectionName, o4, r3) && KM(o4, w, e35.layerCount)), b3 = t2[w.routeIndex].route.length, v3 = y3 ? YM(t2, w, o4, e35, r3, i3) : $M(t2, w, m2, e35, i3);
      t2[w.routeIndex].route.length !== b3 && (d2 = WP(t2, e35), u2 = UP(t2)), h2 = v3 || h2;
    }
    const N = x2 ? undefined : HM(d2, n3);
    N && Math.hypot(N.x - n3.x, N.y - n3.y) < 0.35 && (h2 = WM(t2, N, m2, e35) || h2);
  }
  return h2;
};
var Gw = 0.000001;
var Uw = 0.006;
var Zw = [1, 0.5, 0.25, 0.1, 0.05, 0.025];
var qw = (e35, t2) => (t2.traceThickness ?? e35.minTraceWidth) / 2;
var Jw = (e35) => e35.minTraceToPadEdgeClearance ?? 0.1;
var Qw = (e35, t2) => t2.viaDiameter ?? e35.minViaDiameter ?? 0.3;
var Kw = (e35, t2) => me(e35, t2) < Gw;
var eN = (e35) => {
  const t2 = [], n2 = (e36) => {
    t2.some((t3) => Kw(t3, e36)) || t2.push({ x: e36.x, y: e36.y });
  };
  for (const t3 of e35.vias)
    n2(t3);
  for (let t3 = 0;t3 < e35.route.length - 1; t3 += 1) {
    const o3 = e35.route[t3], i3 = e35.route[t3 + 1];
    o3 && i3 && o3.z !== i3.z && (Kw(o3, i3) && n2(o3));
  }
  return t2;
};
var tN = (e35) => me({ x: 0, y: 0 }, e35) < Gw ? { x: 0, y: 0 } : Ae({ x: 0, y: 0 }, e35);
var nN = (e35, t2) => {
  if (e35.zLayers && e35.zLayers.length > 0)
    return e35.zLayers;
  const n2 = Array.from({ length: t2 }, (e36, t3) => t3).filter((n3) => e35.layers.includes(Qy(n3, t2)));
  return n2.length > 0 ? n2 : Array.from({ length: t2 }, (e36, t3) => t3);
};
var oN = (e35, t2, n2) => yP(gP(e35), gP(t2), n2) || yP(gP(e35), t2.connectionName, n2) || yP(e35.connectionName, gP(t2), n2) || yP(e35.connectionName, t2.connectionName, n2);
var iN = (e35, t2, n2) => bP(gP(e35), t2, n2) || bP(e35.connectionName, t2, n2);
var rN = (e35, t2, n2, o3) => !n2.pcb_port_id && e35.obstacles.some((i3) => iN(t2, i3, o3) && nN(i3, e35.layerCount).includes(n2.z) && ((e36, t3) => e36.x >= t3.center.x - t3.width / 2 - Gw && e36.x <= t3.center.x + t3.width / 2 + Gw && e36.y >= t3.center.y - t3.height / 2 - Gw && e36.y <= t3.center.y + t3.height / 2 + Gw)(n2, i3));
var sN = (e35, t2, n2, o3, i3) => {
  if (!((e36, t3) => e36.zLayers.includes(t3))(i3, n2.z))
    return Number.POSITIVE_INFINITY;
  const r3 = qw(e35, t2);
  return i3.kind === "pad" ? Re(n2, o3, i3.obstacle) - (Jw(e35) + r3 + Uw) : pe(i3.center, n2, o3) - (Jw(e35) + r3 + i3.diameter / 2 + Uw);
};
var aN = (e35, t2, n2) => {
  const o3 = n2.kind === "pad" ? n2.obstacle.center : n2.center, i3 = Ee(o3, e35, t2);
  let r3 = tN({ x: i3.x - o3.x, y: i3.y - o3.y });
  if (Math.abs(r3.x) < Gw && Math.abs(r3.y) < Gw) {
    const n3 = t2.x - e35.x, i4 = t2.y - e35.y, s2 = ke(e35, t2), a3 = tN({ x: -i4, y: n3 }), c3 = { x: -a3.x, y: -a3.y };
    r3 = me({ x: s2.x + a3.x, y: s2.y + a3.y }, o3) >= me({ x: s2.x + c3.x, y: s2.y + c3.y }, o3) ? a3 : c3;
  }
  return r3;
};
var cN = (e35, t2, n2, o3) => {
  if (n2 <= 0 || n2 >= t2.route.length - 1) {
    const i4 = t2.route[n2];
    return !i4 || !rN(e35, t2, i4, o3);
  }
  const i3 = t2.route[n2];
  if (!i3 || i3.insideJumperPad)
    return true;
  const r3 = t2.route[n2 - 1], s2 = t2.route[n2 + 1];
  return !(!r3 || r3.z === i3.z) || (!(!s2 || s2.z === i3.z) || t2.vias.some((e36) => Kw(e36, i3)));
};
var lN = (e35, t2, n2) => {
  let o3 = 0;
  for (let i3 = 0;i3 < t2.route.length - 1; i3 += 1) {
    const r3 = t2.route[i3], s2 = t2.route[i3 + 1];
    if (r3 && s2 && r3.z === s2.z && !Kw(r3, s2))
      for (const i4 of n2) {
        const n3 = sN(e35, t2, r3, s2, i4);
        if (!(n3 >= 0) && (o3 += n3 * n3, i4.kind === "pad")) {
          if (Re(r3, s2, i4.obstacle) < Gw) {
            o3 += 0.01 / (pe(i4.obstacle.center, r3, s2) + 0.01);
          }
        }
      }
  }
  return o3;
};
var hN = (e35, t2, n2, o3) => {
  let i3 = 0;
  for (let r3 = 0;r3 < t2.route.length - 1; r3 += 1) {
    const s2 = t2.route[r3], a3 = t2.route[r3 + 1];
    if (s2 && a3 && s2.z === a3.z && !Kw(s2, a3)) {
      for (const r4 of n2)
        if (!oN(t2, r4, o3)) {
          for (let n3 = 0;n3 < r4.route.length - 1; n3 += 1) {
            const o4 = r4.route[n3], c3 = r4.route[n3 + 1];
            if (!o4 || !c3 || o4.z !== s2.z || c3.z !== s2.z || Kw(o4, c3))
              continue;
            const l3 = we(s2, a3, o4, c3) - qw(e35, t2) - qw(e35, r4), h2 = Jw(e35) + Uw - l3;
            h2 > 0 && (i3 += h2 * h2);
          }
          for (const n3 of eN(r4)) {
            const o4 = pe(n3, s2, a3) - qw(e35, t2) - Qw(e35, r4) / 2, c3 = Jw(e35) + Uw - o4;
            c3 > 0 && (i3 += c3 * c3);
          }
        }
    }
  }
  return i3;
};
var dN = (e35, t2, n2, o3, i3) => {
  const r3 = t2.route.map(() => ({ x: 0, y: 0 }));
  for (let s2 = 0;s2 < t2.route.length - 1; s2 += 1) {
    const a3 = t2.route[s2], c3 = t2.route[s2 + 1];
    if (a3 && c3 && a3.z === c3.z && !Kw(a3, c3)) {
      for (const o4 of n2) {
        const n3 = sN(e35, t2, a3, c3, o4);
        if (n3 >= 0)
          continue;
        const l3 = aN(a3, c3, o4);
        if (Math.abs(l3.x) < Gw && Math.abs(l3.y) < Gw)
          continue;
        const h2 = !cN(e35, t2, s2, i3), d2 = !cN(e35, t2, s2 + 1, i3);
        if (!h2 && !d2)
          continue;
        const u2 = -n3, p3 = h2 && d2 ? 0.5 : h2 ? 1 : 0, m2 = h2 && d2 ? 0.5 : d2 ? 1 : 0;
        r3[s2].x += l3.x * u2 * p3, r3[s2].y += l3.y * u2 * p3, r3[s2 + 1].x += l3.x * u2 * m2, r3[s2 + 1].y += l3.y * u2 * m2;
      }
      for (const n3 of o3)
        if (!oN(t2, n3, i3))
          for (let o4 = 0;o4 < n3.route.length - 1; o4 += 1) {
            const l3 = n3.route[o4], h2 = n3.route[o4 + 1];
            if (!l3 || !h2 || l3.z !== a3.z || h2.z !== a3.z || Kw(l3, h2))
              continue;
            const d2 = we(a3, c3, l3, h2) - qw(e35, t2) - qw(e35, n3), u2 = e35.minTraceToPadEdgeClearance + Uw - d2;
            if (u2 <= 0)
              continue;
            const p3 = ke(a3, c3), m2 = Ee(p3, l3, h2);
            let g2 = tN({ x: p3.x - m2.x, y: p3.y - m2.y });
            if (Math.abs(g2.x) < Gw && Math.abs(g2.y) < Gw) {
              const e36 = c3.x - a3.x, t3 = c3.y - a3.y;
              g2 = tN({ x: -t3, y: e36 });
            }
            const f2 = !cN(e35, t2, s2, i3), _2 = !cN(e35, t2, s2 + 1, i3);
            if (!f2 && !_2)
              continue;
            const y2 = f2 && _2 ? 0.5 : f2 ? 1 : 0, b2 = f2 && _2 ? 0.5 : _2 ? 1 : 0;
            r3[s2].x += g2.x * u2 * y2, r3[s2].y += g2.y * u2 * y2, r3[s2 + 1].x += g2.x * u2 * b2, r3[s2 + 1].y += g2.y * u2 * b2;
          }
    }
  }
  return r3;
};
var uN = (e35, t2, n2, o3, i3) => ({ ...t2, route: t2.route.map((r3, s2) => {
  if (cN(e35, t2, s2, i3))
    return { ...r3 };
  const a3 = ((e36, t3) => {
    const n3 = me({ x: 0, y: 0 }, e36);
    if (n3 <= t3 || n3 < Gw)
      return e36;
    const o4 = t3 / n3;
    return { x: e36.x * o4, y: e36.y * o4 };
  })(n2[s2] ?? { x: 0, y: 0 }, 0.5);
  return { ...r3, x: r3.x + a3.x * o3, y: r3.y + a3.y * o3 };
}), vias: t2.vias.map((e36) => ({ ...e36 })), jumpers: t2.jumpers ? [...t2.jumpers] : undefined });
var pN = (e35, t2) => t2.route.every((t3) => t3.x >= e35.bounds.minX - Gw && t3.x <= e35.bounds.maxX + Gw && t3.y >= e35.bounds.minY - Gw && t3.y <= e35.bounds.maxY + Gw);
var mN = (e35, t2, n2, o3, i3) => {
  const r3 = ((e36, t3, n3, o4) => {
    const i4 = [];
    for (const t4 of e36.obstacles)
      t4.isCopperPour || iN(n3, t4, o4) || i4.push({ kind: "pad", obstacle: t4, zLayers: nN(t4, e36.layerCount) });
    const r4 = Array.from({ length: e36.layerCount }, (e37, t4) => t4);
    for (const s3 of t3)
      if (s3 !== n3 && !oN(n3, s3, o4))
        for (const t4 of eN(s3))
          i4.push({ kind: "via", center: { x: t4.x, y: t4.y }, diameter: Qw(e36, s3), zLayers: r4, connectionName: s3.connectionName, rootConnectionName: s3.rootConnectionName });
    return i4;
  })(e35, t2, n2, i3), s2 = t2.filter((e36, t3) => t3 !== o3 && e36 !== n2);
  let a3 = n2, c3 = lN(e35, a3, r3) + hN(e35, a3, s2, i3);
  for (let t3 = 0;t3 < 160 && !(c3 <= Gw); t3 += 1) {
    const t4 = dN(e35, a3, r3, s2, i3);
    if (t4.every((e36) => me(e36, { x: 0, y: 0 }) < 0.000000001))
      break;
    let n3 = null, o4 = c3;
    for (const l3 of Zw) {
      const h2 = uN(e35, a3, t4, l3, i3), d2 = lN(e35, h2, r3) + hN(e35, h2, s2, i3);
      if (d2 < c3 - 0.000001 && pN(e35, h2)) {
        n3 = h2, o4 = d2;
        break;
      }
    }
    if (!n3)
      break;
    a3 = n3, c3 = o4;
  }
  return a3;
};
var gN = 0.000001;
var fN = [1, 0.5, 0.25, 0.1, 0.05, 0.025];
var _N = (e35, t2) => e35.some((e36) => t2.includes(e36));
var yN = (e35, t2, n2, o3) => (bP(e35.rootConnectionName, n2, o3) || bP(t2.connectionName, n2, o3)) && nM(e35, n2) <= gN;
var bN = (e35, t2, n2, o3) => {
  const i3 = [], r3 = t2[n2.routeIndex];
  if (!r3)
    return i3;
  for (const t3 of e35.obstacles) {
    if (t3.isCopperPour || yN(n2, r3, t3, o3))
      continue;
    const s2 = QP(t3, e35.layerCount);
    _N(n2.zLayers, s2) && i3.push({ obstacle: t3 });
  }
  return i3;
};
var xN = (e35, t2, n2) => nM(t2, n2.obstacle) - (t2.radius + e35.minViaEdgeToPadEdgeClearance + 0.006);
var vN = (e35, t2, n2, o3) => WP(t2, e35).filter((e36) => e36.routeIndex === n2).reduce((n3, i3) => n3 + ((e36, t3, n4, o4) => {
  let i4 = 0;
  for (const r3 of bN(e36, t3, n4, o4)) {
    const t4 = xN(e36, n4, r3);
    !(t4 >= 0) && (i4 += t4 * t4, nM(n4, r3.obstacle) < gN) && (i4 += 0.01 / (me(n4, r3.obstacle.center) + 0.01));
  }
  return i4;
})(e35, t2, i3, o3), 0);
var IN = (e35, t2, n2, o3) => {
  const i3 = t2[n2];
  if (!i3)
    return [];
  const r3 = i3.route.map(() => ({ x: 0, y: 0 })), s2 = WP(t2, e35).filter((e36) => e36.routeIndex === n2);
  for (const n3 of s2)
    if (n3.movable)
      for (const i4 of bN(e35, t2, n3, o3)) {
        const t3 = n3.radius + e35.minViaEdgeToPadEdgeClearance + 0.006, o4 = sM(n3, i4.obstacle, t3);
        if (o4)
          for (const e36 of n3.pointIndexes)
            r3[e36].x += o4.direction.x * o4.penetration, r3[e36].y += o4.direction.y * o4.penetration;
      }
  return r3;
};
var SN = (e35, t2, n2, o3) => {
  const i3 = new Set(WP([t2], e35).flatMap((e36) => e36.movable ? e36.pointIndexes : []));
  return { ...t2, route: t2.route.map((e36, t3) => {
    if (!i3.has(t3))
      return { ...e36 };
    const r3 = ((e37, t4) => {
      const n3 = me({ x: 0, y: 0 }, e37);
      if (n3 <= t4 || n3 < gN)
        return e37;
      const o4 = t4 / n3;
      return { x: e37.x * o4, y: e37.y * o4 };
    })(n2[t3] ?? { x: 0, y: 0 }, 0.5);
    return { ...e36, x: e36.x + r3.x * o3, y: e36.y + r3.y * o3 };
  }), vias: t2.vias.map((e36) => ({ ...e36 })), jumpers: t2.jumpers ? [...t2.jumpers] : undefined };
};
var CN = (e35, t2) => t2.route.every((t3) => t3.x >= e35.bounds.minX - gN && t3.x <= e35.bounds.maxX + gN && t3.y >= e35.bounds.minY - gN && t3.y <= e35.bounds.maxY + gN);
var PN = (e35, t2, n2, o3, i3) => {
  let r3 = n2, s2 = vN(e35, t2, o3, i3);
  for (let n3 = 0;n3 < 160 && !(s2 <= gN); n3 += 1) {
    const n4 = IN(e35, t2, o3, i3);
    if (n4.every((e36) => me(e36, { x: 0, y: 0 }) < 0.000000001))
      break;
    let a3 = null, c3 = s2;
    for (const l3 of fN) {
      const h2 = SN(e35, r3, n4, l3), d2 = [...t2];
      d2[o3] = h2;
      const u2 = vN(e35, d2, o3, i3);
      if (u2 < s2 - 0.000001 && CN(e35, h2)) {
        a3 = h2, c3 = u2;
        break;
      }
    }
    if (!a3)
      break;
    t2[o3] = a3, r3 = a3, s2 = c3;
  }
  return r3;
};
var MN = ({ routes: e35, snapshot: t2, inputSnapshot: n2, checkpointRoutes: o3, peerConnectionNames: i3 }) => {
  const r3 = ((e36, t3) => {
    const n3 = bw(t3), o4 = new Set;
    for (const t4 of yw(e36)) {
      const i4 = _w(t4, e36);
      if (!i4)
        return;
      if (n3.has(i4))
        continue;
      const r4 = t4.pcb_trace_id, s3 = typeof r4 == "string" ? e36.traceConnectionNameById?.get(r4) : undefined;
      if (s3 === undefined)
        return;
      o4.add(s3);
    }
    return o4;
  })(t2, n2);
  if (!r3)
    return;
  if (r3.size === 0)
    for (const e36 of i3 ?? [])
      r3.add(e36);
  if (!r3?.size)
    return;
  const s2 = new Map;
  for (const e36 of o3) {
    if (!r3.has(e36.connectionName))
      continue;
    const t3 = s2.get(e36.connectionName);
    t3 ? t3.push(e36) : s2.set(e36.connectionName, [e36]);
  }
  if (s2.size !== r3.size)
    return;
  const a3 = new Set, c3 = [];
  for (const t3 of e35)
    r3.has(t3.connectionName) ? a3.has(t3.connectionName) || (a3.add(t3.connectionName), c3.push(...s2.get(t3.connectionName))) : c3.push(t3);
  return a3.size === r3.size ? { routes: c3, restoredConnectionCount: a3.size, restoredConnectionNames: a3 } : undefined;
};
var wN = (e35, t2) => e35.connectionName === t2.connectionName && e35.rootConnectionName === t2.rootConnectionName && e35.traceThickness === t2.traceThickness && e35.route.length === t2.route.length && e35.route.every((e36, n2) => {
  const o3 = t2.route[n2];
  return e36.x === o3.x && e36.y === o3.y && e36.z === o3.z && e36.toNextSegmentType === o3.toNextSegmentType;
});
var NN = (e35, t2, n2) => {
  if (t2.start.z !== n2.start.z || t2.net === n2.net || t2.bounds.maxX <= n2.bounds.minX || n2.bounds.maxX <= t2.bounds.minX || t2.bounds.maxY <= n2.bounds.minY || n2.bounds.maxY <= t2.bounds.minY)
    return;
  const o3 = t2.connectionName < n2.connectionName ? [t2.connectionName, n2.connectionName] : [n2.connectionName, t2.connectionName], i3 = JSON.stringify(o3);
  if (e35.has(i3))
    return;
  we(t2.start, t2.end, n2.start, n2.end) - t2.radius - n2.radius < -0.000000001 && e35.set(i3, o3);
};
var RN = class {
  connectivity;
  inputContacts;
  cellSize;
  constructor({ srj: e35, inputRoutes: t2, connMap: n2 }) {
    this.cellSize = Math.max(1, (e35.bounds.maxX - e35.bounds.minX) / 64, (e35.bounds.maxY - e35.bounds.minY) / 64), this.connectivity = new Nb({}), this.connectivity.addConnections([...Object.entries(n2?.netMap ?? {}).map(([e36, t3]) => [e36, ...t3]), ...e35.connections.map((e36) => [e36.name, e36.rootConnectionName, e36.netConnectionName, ...e36.mergedConnectionNames ?? [], ...e36.pointsToConnect.flatMap((e37) => [e37.pointId, e37.pcb_port_id])].filter((e37) => typeof e37 == "string" && e37.length > 0)), ...t2.map((e36) => [e36.connectionName, e36.rootConnectionName ?? e36.connectionName])]), this.inputContacts = this.collectContacts(t2);
  }
  getNewContactConnectionNames(e35) {
    const t2 = new Set;
    for (const n2 of this.getNewContactPairs(e35))
      t2.add(n2[0]), t2.add(n2[1]);
    return t2;
  }
  getNewContactPairs(e35) {
    return [...this.collectContacts(e35)].filter(([e36]) => !this.inputContacts.has(e36)).map(([, e36]) => e36);
  }
  hasContactPair(e35, t2) {
    const n2 = e35.filter((e36) => e36.connectionName === t2[0] || e36.connectionName === t2[1]);
    return this.collectContacts(n2).has(JSON.stringify(t2));
  }
  preserveClearedContacts(e35) {
    const t2 = this.collectContacts(e35);
    for (const e36 of this.inputContacts.keys())
      t2.has(e36) || this.inputContacts.delete(e36);
  }
  prepareCandidateCheck(e35) {
    const t2 = structuredClone(e35), n2 = this.collectContacts(t2), o3 = [...this.collectSegments(t2).values()].flat(), i3 = MP(o3, (e36) => e36.bounds, this.cellSize);
    return (e36) => {
      if (e36.length !== t2.length)
        return this.getNewContactPairs(e36);
      const r3 = new Set;
      for (let n3 = 0;n3 < e36.length; n3++) {
        const o4 = t2[n3], i4 = e36[n3];
        wN(o4, i4) || (r3.add(o4.connectionName), r3.add(i4.connectionName));
      }
      if (r3.size > e36.length / 4)
        return this.getNewContactPairs(e36);
      const s2 = new Map([...n2].filter(([, e37]) => !r3.has(e37[0]) && !r3.has(e37[1]))), a3 = [...this.collectSegments(e36.filter((e37) => r3.has(e37.connectionName))).values()].flat();
      for (let e37 = 0;e37 < a3.length; e37++) {
        const t3 = a3[e37];
        for (const e38 of wP(i3, t3.bounds, this.cellSize)) {
          const n3 = o3[e38];
          r3.has(n3.connectionName) || NN(s2, t3, n3);
        }
        for (let n3 = e37 + 1;n3 < a3.length; n3++)
          NN(s2, t3, a3[n3]);
      }
      return [...s2].filter(([e37]) => !this.inputContacts.has(e37)).map(([, e37]) => e37);
    };
  }
  collectSegments(e35) {
    const t2 = new Map;
    for (const n2 of e35) {
      const e36 = this.connectivity.getNetConnectedToId(n2.connectionName) ?? n2.rootConnectionName ?? n2.connectionName, o3 = n2.traceThickness / 2;
      for (let i3 = 1;i3 < n2.route.length; i3++) {
        const r3 = n2.route[i3 - 1], s2 = n2.route[i3];
        if (r3.z !== s2.z || r3.toNextSegmentType === "through_obstacle")
          continue;
        let a3 = t2.get(r3.z);
        a3 || (a3 = [], t2.set(r3.z, a3)), a3.push({ connectionName: n2.connectionName, net: e36, start: r3, end: s2, radius: o3, bounds: { minX: Math.min(r3.x, s2.x) - o3, minY: Math.min(r3.y, s2.y) - o3, maxX: Math.max(r3.x, s2.x) + o3, maxY: Math.max(r3.y, s2.y) + o3 } });
      }
    }
    return t2;
  }
  collectContacts(e35) {
    const t2 = new Map;
    for (const n2 of this.collectSegments(e35).values()) {
      const e36 = MP(n2, (e37) => e37.bounds, this.cellSize);
      for (let o3 = 0;o3 < n2.length; o3++) {
        const i3 = n2[o3];
        for (const r3 of wP(e36, i3.bounds, this.cellSize))
          r3 <= o3 || NN(t2, i3, n2[r3]);
      }
    }
    return t2;
  }
};
var TN = [0.2, 0.4, 0.8, 1.2].flatMap((e35) => [0.2, 0.3, 0.45, 0.6].flatMap((t2) => [-1, 1].map((n2) => ({ halfSpan: e35, offset: t2, directionSign: n2 })))).flatMap((e35) => [0, 1].map((t2) => ({ kind: "segment", routeSide: t2, ...e35 })));
var EN = [1, -1].flatMap((e35) => [1, -1].flatMap((t2) => [false, true].flatMap((n2) => [0, 1].map((o3) => ({ routeSide: o3, normalDirectionSign: e35, tangentDirectionSign: t2, reverseEndpointOffsets: n2 })))));
var AN = [...[0, 1].map((e35) => ({ kind: "displacementChain", routeSide: e35 })), ...[-1, 1].flatMap((e35) => [0, 1].map((t2) => ({ kind: "segment", routeSide: t2, halfSpan: 0.4, offset: 1.2, directionSign: e35 }))), ...[-1, 1].flatMap((e35) => [0, 1].map((t2) => ({ kind: "span", routeSide: t2, spanExpansion: 3, offset: 1.8, directionSign: e35 }))), ...[{ dx: -2.4, dy: -0.4 }, { dx: -2.4, dy: 0.4 }, { dx: 2.4, dy: -0.4 }, { dx: 2.4, dy: 0.4 }, { dx: -0.4, dy: -2.4 }, { dx: -0.4, dy: 2.4 }, { dx: 0.4, dy: -2.4 }, { dx: 0.4, dy: 2.4 }].flatMap((e35) => [0, 1].map((t2) => ({ kind: "waypoint", routeSide: t2, spanExpansion: 2, ...e35 }))), ...[{ dx: -0.17, dy: 0 }, { dx: 0.17, dy: 0 }, { dx: 0, dy: -0.17 }, { dx: 0, dy: 0.17 }].flatMap((e35) => [0, 1].map((t2) => ({ kind: "waypoint", routeSide: t2, spanExpansion: 0, ...e35 }))), ...TN];
var ON = [0, 1, 2];
var kN = class extends BaseSolver {
  srj;
  inputHdRoutes;
  guardedInputHdRoutes;
  connMap;
  effort;
  drcEvaluator;
  referenceDrcEvaluator;
  autoroutingDrcEngine;
  viaHoleDiameter;
  configuredMaxIterations;
  enableBroadFallback;
  enableLargeBoardBroadFallback;
  enableTargetedErrorSweep;
  enablePostSolveClearanceRelaxation;
  enableSafeTraceLayerMoves;
  enableViaInPadLayerMoves;
  enableTraceViaOwnerTargeting;
  deferTraceContactGuard;
  outputHdRoutes;
  deferTraceObstacleOverlapGuard = false;
  initialDrcIssueCount;
  initialRepairDrcIssueCount;
  initialLowCountErrorsHaveMovableTraces = false;
  broadForceAccepted = false;
  targetedForceAccepted = false;
  candidateAttempts = 0;
  viaInPadCandidateAttempts = 0;
  viaInPadCandidatesAccepted = 0;
  padTopologyErrorCursor = 0;
  safeTraceLayerCursorByErrorId = new Map;
  traceLayerCorridorCursorByErrorId = new Map;
  tracePairDetourCursorByErrorId = new Map;
  errorCursor = 0;
  stalledIterations = 0;
  bestDrcIssueCountSeen;
  bestDrcIssueScoreSeen;
  lastDrcCountImprovementCheckIteration = 0;
  drcCountPlateauChecks = 0;
  largeBoardBroadFallbackMisses = 0;
  outputSnapshot;
  overlapSafeCheckpoint;
  traceObstacleRepairRolledBack = false;
  traceObstacleConnectionsRestored = 0;
  traceContactGuard;
  peerTraceRepairRolledBack = false;
  overlapRestorationChecks = 0;
  legacyCleanCheckpoint;
  viaPadRepairRolledBack = false;
  referenceInputDrcIssueCount;
  referenceCandidateDrcIssueCount;
  referenceCandidateRolledBack = false;
  referenceInputSnapshot;
  inputSnapshot;
  constructor(e35) {
    if (super(), this.srj = e35.srj, this.inputHdRoutes = e35.hdRoutes, this.guardedInputHdRoutes = sw(AP(e35.hdRoutes)), this.connMap = e35.connMap, this.effort = e35.effort ?? 1, this.drcEvaluator = e35.drcEvaluator, this.referenceDrcEvaluator = e35.referenceDrcEvaluator, this.autoroutingDrcEngine = e35.autoroutingDrcEngine ?? (e35.drcEvaluator ? undefined : new mb(e35.srj, { connMap: e35.connMap, traceClearance: e35.srj.minTraceToPadEdgeClearance ?? hP.traceClearance, viaClearance: e35.srj.minTraceToPadEdgeClearance ?? hP.viaClearance, includeTraceViaOwnerMetadata: e35.enableTraceViaOwnerTargeting ?? false })), e35.viaHoleDiameter !== undefined && (!Number.isFinite(e35.viaHoleDiameter) || e35.viaHoleDiameter <= 0))
      throw new Error("viaHoleDiameter must be a positive finite number");
    this.viaHoleDiameter = e35.viaHoleDiameter, this.configuredMaxIterations = e35.maxIterations, this.enableBroadFallback = e35.enableBroadFallback ?? true, this.enableLargeBoardBroadFallback = e35.enableLargeBoardBroadFallback ?? true, this.enableTargetedErrorSweep = e35.enableTargetedErrorSweep ?? false, this.enablePostSolveClearanceRelaxation = e35.enablePostSolveClearanceRelaxation ?? true, this.enableSafeTraceLayerMoves = e35.enableSafeTraceLayerMoves ?? false, this.enableViaInPadLayerMoves = e35.enableViaInPadLayerMoves ?? false, this.enableTraceViaOwnerTargeting = e35.enableTraceViaOwnerTargeting ?? false, this.deferTraceContactGuard = e35.deferTraceContactGuard ?? false, this.outputHdRoutes = e35.hdRoutes, this.referenceDrcEvaluator && (this.referenceInputSnapshot = this.getReferenceDrcSnapshot(this.inputHdRoutes)), this.MAX_ITERATIONS = this.configuredMaxIterations ?? Mb(this.effort);
  }
  getConstructorParams() {
    return [{ srj: this.srj, hdRoutes: this.inputHdRoutes, connMap: this.connMap, effort: this.effort, drcEvaluator: this.drcEvaluator, referenceDrcEvaluator: this.referenceDrcEvaluator, autoroutingDrcEngine: this.autoroutingDrcEngine, viaHoleDiameter: this.viaHoleDiameter, maxIterations: this.configuredMaxIterations, enableBroadFallback: this.enableBroadFallback, enableLargeBoardBroadFallback: this.enableLargeBoardBroadFallback, enableTargetedErrorSweep: this.enableTargetedErrorSweep, enablePostSolveClearanceRelaxation: this.enablePostSolveClearanceRelaxation, enableSafeTraceLayerMoves: this.enableSafeTraceLayerMoves, enableViaInPadLayerMoves: this.enableViaInPadLayerMoves, enableTraceViaOwnerTargeting: this.enableTraceViaOwnerTargeting, deferTraceContactGuard: this.deferTraceContactGuard }];
  }
  updateStats(e35) {
    this.stats = { initialDrcIssueCount: this.initialDrcIssueCount ?? e35.count, finalDrcIssueCount: e35.count, globalDrcForceImproveMaxIterations: this.MAX_ITERATIONS, globalDrcForceImproveBroadForceAccepted: this.broadForceAccepted, globalDrcForceImproveTargetedForceAccepted: this.targetedForceAccepted, globalDrcForceImproveCandidateAttempts: this.candidateAttempts, globalDrcForceImproveViaInPadCandidateAttempts: this.viaInPadCandidateAttempts, globalDrcForceImproveViaInPadCandidatesAccepted: this.viaInPadCandidatesAccepted, globalDrcForceImproveStalledIterations: this.stalledIterations, globalDrcForceImproveBestDrcIssueCountSeen: this.bestDrcIssueCountSeen ?? e35.count, globalDrcForceImproveBestDrcIssueScoreSeen: this.bestDrcIssueScoreSeen ?? e35.issueScore, globalDrcForceImproveDrcCountPlateauChecks: this.drcCountPlateauChecks, globalDrcForceImproveLargeBoardBroadFallbackMisses: this.largeBoardBroadFallbackMisses, globalDrcForceImproveViaPadRepairRolledBack: this.viaPadRepairRolledBack, globalDrcForceImproveTraceObstacleRepairRolledBack: this.traceObstacleRepairRolledBack, globalDrcForceImproveTraceObstacleConnectionsRestored: this.traceObstacleConnectionsRestored, globalDrcForceImprovePeerTraceRepairRolledBack: this.peerTraceRepairRolledBack, globalDrcForceImproveOverlapRestorationChecks: this.overlapRestorationChecks, globalDrcForceImproveReferenceInputDrcIssueCount: this.referenceInputDrcIssueCount, globalDrcForceImproveReferenceCandidateDrcIssueCount: this.referenceCandidateDrcIssueCount, globalDrcForceImproveReferenceCandidateRolledBack: this.referenceCandidateRolledBack };
  }
  finishAtLegacyCleanCheckpoint() {
    const e35 = this.legacyCleanCheckpoint;
    return !!e35 && (this.outputHdRoutes = e35.routes, this.outputSnapshot = e35.snapshot, this.viaPadRepairRolledBack = true, this.updateStats(e35.snapshot), this.solved = true, true);
  }
  increaseMaxIterationsForDrcIssueCount(e35) {
    this.configuredMaxIterations === undefined ? this.MAX_ITERATIONS = Math.max(this.MAX_ITERATIONS, ((e36, t2) => Math.max(Mb(t2), Math.ceil(e36 * yb * Math.max(1, t2))))(e35, this.effort), ((e36, t2) => e36 > 120 && t2 > 0 ? 192 : 48)(this.inputHdRoutes.length, e35)) : this.MAX_ITERATIONS = this.configuredMaxIterations;
  }
  getSnapshot(e35) {
    return (this.initialLowCountErrorsHaveMovableTraces ? VP : HP)(this.srj, e35, this.drcEvaluator, this.connMap, this.autoroutingDrcEngine);
  }
  getReferenceDrcSnapshot(e35) {
    const t2 = { traces: [], srj: this.srj, routes: e35, hdRoutes: e35 }, n2 = this.referenceDrcEvaluator?.getCachedResult?.(t2);
    if (n2) {
      const e36 = Array.isArray(n2) ? n2 : n2.errors;
      return { errors: e36, count: e36.length };
    }
    return HP(this.srj, e35, this.referenceDrcEvaluator, this.connMap, this.autoroutingDrcEngine);
  }
  getViaIssueCount(e35) {
    return hw(e35, false);
  }
  getRepairIssueCount(e35) {
    return gw(e35);
  }
  getRepairIssueScore(e35) {
    return fw(e35);
  }
  getNewPeerContactConnectionNames(e35) {
    return this.deferTraceContactGuard ? new Set : (this.traceContactGuard ??= new RN({ srj: this.srj, inputRoutes: this.guardedInputHdRoutes, connMap: this.connMap }), this.traceContactGuard.getNewContactConnectionNames(e35));
  }
  rememberOverlapSafeRoutes(e35, t2) {
    if (this.deferTraceObstacleOverlapGuard)
      return;
    const n2 = this.overlapSafeCheckpoint;
    n2 && !Vw(t2, this.getViaIssueCount(t2), this.getRepairIssueCount(n2.snapshot), this.getRepairIssueScore(n2.snapshot), this.getViaIssueCount(n2.snapshot), n2.snapshot) || this.inputSnapshot && xw(t2, this.inputSnapshot) || this.getNewPeerContactConnectionNames(e35).size > 0 || (this.overlapSafeCheckpoint = { routes: sw(AP(e35)), snapshot: t2 });
  }
  acceptSolvedRoutes(e35, t2) {
    this.rememberOverlapSafeRoutes(e35, t2);
    const n2 = this.enablePostSolveClearanceRelaxation ? ((e36, t3, n3) => {
      if (e36.minTraceToPadEdgeClearance === undefined || e36.minTraceToPadEdgeClearance <= 0)
        return t3;
      let o4 = false;
      const i4 = AP(t3);
      for (let t4 = 0;t4 < 4; t4 += 1)
        for (let t5 = 0;t5 < i4.length; t5 += 1) {
          const r4 = i4[t5];
          if (!r4)
            continue;
          const s3 = mN(e36, i4, r4, t5, n3);
          s3 !== r4 && (i4[t5] = s3, o4 = true);
        }
      return o4 ? i4 : t3;
    })(this.srj, e35, this.connMap) : e35, o3 = this.enablePostSolveClearanceRelaxation ? ((e36, t3, n3) => {
      if (e36.minViaEdgeToPadEdgeClearance === undefined || e36.minViaEdgeToPadEdgeClearance <= 0)
        return t3;
      let o4 = false;
      const i4 = AP(t3);
      for (let t4 = 0;t4 < 4; t4 += 1)
        for (let t5 = 0;t5 < i4.length; t5 += 1) {
          const r4 = i4[t5];
          if (!r4)
            continue;
          const s3 = PN(e36, i4, r4, t5, n3);
          s3 !== r4 && (i4[t5] = s3, o4 = true);
        }
      return o4 ? sw(i4) : t3;
    })(this.srj, n2, this.connMap) : e35, i3 = o3 === e35 ? t2 : this.getSnapshot(o3), r3 = i3.count < t2.count || i3.count === t2.count && i3.issueScore <= t2.issueScore;
    let s2 = r3 ? o3 : e35, a3 = r3 ? i3 : t2;
    const c3 = this.inputSnapshot ?? this.getSnapshot(this.guardedInputHdRoutes);
    let l3 = this.deferTraceObstacleOverlapGuard ? new Set : this.getNewPeerContactConnectionNames(s2);
    if (!this.deferTraceObstacleOverlapGuard && (xw(a3, c3) || l3.size > 0)) {
      this.peerTraceRepairRolledBack = l3.size > 0;
      const e36 = new Set, t3 = l3.size > 0 ? 2 : 1;
      for (let n3 = 0;n3 < t3; n3++) {
        const t4 = MN({ routes: s2, snapshot: a3, inputSnapshot: c3, checkpointRoutes: this.overlapSafeCheckpoint?.routes ?? this.guardedInputHdRoutes, peerConnectionNames: l3 });
        if (!t4)
          break;
        for (const n5 of t4.restoredConnectionNames)
          e36.add(n5);
        const n4 = this.getSnapshot(t4.routes);
        if (this.overlapRestorationChecks++, this.rememberOverlapSafeRoutes(t4.routes, n4), this.overlapSafeCheckpoint?.snapshot === n4) {
          this.traceObstacleConnectionsRestored = e36.size;
          break;
        }
        if (s2 = t4.routes, a3 = n4, l3 = this.getNewPeerContactConnectionNames(s2), !xw(a3, c3) && l3.size === 0)
          break;
      }
      s2 = this.overlapSafeCheckpoint?.routes ?? this.guardedInputHdRoutes, a3 = this.overlapSafeCheckpoint?.snapshot ?? c3, this.traceObstacleRepairRolledBack = true;
    }
    if (this.referenceDrcEvaluator) {
      const e36 = this.referenceInputSnapshot, t3 = this.getReferenceDrcSnapshot(s2);
      this.referenceInputDrcIssueCount = e36.count, this.referenceCandidateDrcIssueCount = t3.count, t3.count > e36.count && (s2 = this.guardedInputHdRoutes, a3 = c3, this.referenceCandidateRolledBack = true, this.traceObstacleConnectionsRestored = 0);
    }
    this.outputHdRoutes = s2, this.outputSnapshot = a3, this.stalledIterations = 0, this.updateStats(a3), this.solved = true;
  }
  updateDrcCountPlateauState(e35) {
    const t2 = this.getRepairIssueCount(e35), n2 = this.getRepairIssueScore(e35);
    this.bestDrcIssueCountSeen ??= t2, this.bestDrcIssueScoreSeen ??= n2;
    const o3 = this.initialRepairDrcIssueCount ?? t2, i3 = this.inputHdRoutes.length > 120 && o3 > 0;
    if ((o3 >= 20 || i3) && this.iterations < 192)
      return (t2 < this.bestDrcIssueCountSeen || t2 === this.bestDrcIssueCountSeen && n2 < this.bestDrcIssueScoreSeen) && (this.bestDrcIssueCountSeen = t2, this.bestDrcIssueScoreSeen = n2), void (i3 && this.largeBoardBroadFallbackMisses >= 2 && (this.solved = true));
    const r3 = ((e36) => e36 >= 20 ? 8 : e36 <= 2 ? 1 : 2)(o3);
    if (!(this.iterations - this.lastDrcCountImprovementCheckIteration < r3)) {
      if (this.lastDrcCountImprovementCheckIteration = this.iterations, t2 < this.bestDrcIssueCountSeen || t2 === this.bestDrcIssueCountSeen && n2 < this.bestDrcIssueScoreSeen)
        return this.bestDrcIssueCountSeen = t2, this.bestDrcIssueScoreSeen = n2, void (this.drcCountPlateauChecks = 0);
      this.drcCountPlateauChecks += 1, this.drcCountPlateauChecks >= 2 && (this.solved = true);
    }
  }
  _step() {
    let e35 = this.outputHdRoutes, t2 = this.outputSnapshot ?? this.getSnapshot(e35);
    const n2 = mw(t2);
    if (this.legacyCleanCheckpoint && n2 > 0)
      return void this.finishAtLegacyCleanCheckpoint();
    if (this.legacyCleanCheckpoint || n2 !== 0 || !t2.errors.some(uw) || !this.deferTraceObstacleOverlapGuard && (this.getNewPeerContactConnectionNames(e35).size !== 0 || this.inputSnapshot && xw(t2, this.inputSnapshot)) || (this.legacyCleanCheckpoint = { routes: sw(AP(e35)), snapshot: t2 }), this.initialDrcIssueCount === undefined) {
      this.inputSnapshot = t2, this.initialDrcIssueCount = t2.count, this.initialRepairDrcIssueCount = this.getRepairIssueCount(t2);
      const n3 = Iw(t2.errors);
      this.initialLowCountErrorsHaveMovableTraces = this.initialRepairDrcIssueCount > 0 && this.initialRepairDrcIssueCount <= 3 && n3.every((e36) => Sw(e36, t2.traceRouteIndexById) !== undefined), this.initialLowCountErrorsHaveMovableTraces && (t2 = this.getSnapshot(e35)), this.bestDrcIssueCountSeen = this.getRepairIssueCount(t2), this.bestDrcIssueScoreSeen = this.getRepairIssueScore(t2), this.increaseMaxIterationsForDrcIssueCount(this.getRepairIssueCount(t2));
    }
    if (this.rememberOverlapSafeRoutes(e35, t2), t2.count === 0)
      return void this.acceptSolvedRoutes(e35, t2);
    let o3 = this.getRepairIssueCount(t2), i3 = this.getRepairIssueScore(t2), r3 = this.getViaIssueCount(t2);
    const s2 = t2.errors.filter((e36) => Boolean(lw(e36)));
    if (s2.length === 0)
      return void this.acceptSolvedRoutes(e35, t2);
    const a3 = (c3 = this.effort, Math.max(1, Math.round(3 * Math.max(1, c3))));
    var c3;
    let l3 = 0, h2 = 0, d2 = false, u2 = false, p3 = false;
    const m2 = Iw(s2), g2 = this.enableTargetedErrorSweep ? m2.find((e36) => e36.type === "pcb_via_clearance_error" && e36.pcb_via_pair_net_relation === "same_net") : undefined, f2 = this.enableTargetedErrorSweep && (this.iterations - 1) % 8 == 0, _2 = g2 ?? (f2 ? m2.find((e36) => e36.type === "pcb_via_clearance_error") : undefined), y2 = _2 ? [_2, ...m2.filter((e36) => e36 !== _2)] : m2, b2 = Math.min(y2.length, Math.max(1, Math.ceil(this.effort))), x2 = _2 ? 0 : this.errorCursor % y2.length, v2 = this.enableTargetedErrorSweep ? ((e36, t3) => {
      const n3 = Math.max(2, Math.round(12 * Math.max(1, t3)));
      return e36.filter((e37) => LP(e37) === "pcb_trace_error").slice(0, n3);
    })(s2, this.effort) : [], I2 = o3 <= 1 || this.initialLowCountErrorsHaveMovableTraces, S2 = !this.initialLowCountErrorsHaveMovableTraces && o3 <= 8 && this.srj.layerCount > 1, C = _2 ? [] : s2.filter((e36) => e36.type === "pcb_pad_trace_clearance_error" || (this.enableSafeTraceLayerMoves || I2 || S2) && e36.type === "pcb_trace_error"), P = C.map((e36, t3) => C[(this.padTopologyErrorCursor + t3) % C.length]);
    for (const n3 of this.enableSafeTraceLayerMoves || this.enableViaInPadLayerMoves ? P : []) {
      const s3 = !this.enableSafeTraceLayerMoves || h2 >= a3, c4 = !this.enableViaInPadLayerMoves || l3 >= a3;
      if (u2 || s3 && c4)
        break;
      let p4;
      this.padTopologyErrorCursor = (C.indexOf(n3) + 1) % C.length;
      const m3 = typeof n3.pcb_trace_error_id == "string" ? n3.pcb_trace_error_id : typeof n3.pcb_trace_id == "string" ? n3.pcb_trace_id : undefined, g3 = Sw(n3, t2.traceRouteIndexById), f3 = kw(n3, t2.traceRouteIndexById);
      if (this.enableSafeTraceLayerMoves && g3 !== undefined) {
        const o4 = f3 ?? [g3], i4 = o4.length * this.srj.layerCount * ON.length, s4 = o4.length * this.srj.layerCount * ww, c5 = i4 + s4, l4 = zP(n3), d3 = l4 ? 0 : i4, u3 = l4 ? s4 : 0;
        let _4 = m3 ? this.safeTraceLayerCursorByErrorId.get(m3) ?? 0 : 0, y3 = 0;
        for (;h2 < a3 && y3 < c5; ) {
          const i5 = _4;
          _4 = (_4 + 1) % c5, y3 += 1;
          const a4 = i5 >= d3 && i5 < d3 + s4, l5 = i5 - (a4 ? d3 : u3), m4 = l5 % o4.length, g4 = Math.floor(l5 / o4.length), f4 = g4 % this.srj.layerCount, b3 = a4 ? "full" : ON[Math.floor(g4 / this.srj.layerCount) % ON.length], x3 = a4 ? Math.floor(g4 / this.srj.layerCount) : 0, v3 = o4[m4], I3 = OP(e35, [v3]);
          if (!Ew(this.srj, I3, n3, v3, f4, b3, this.connMap, x3))
            continue;
          const S3 = aw(I3, [v3]);
          h2 += 1, this.candidateAttempts += 1;
          const C2 = this.getSnapshot(S3), P2 = this.getViaIssueCount(C2), M2 = p4?.snapshot ?? t2;
          P2 <= (p4?.viaIssueCount ?? r3) && vw(C2, M2) && (p4 = { routes: S3, snapshot: C2, viaIssueCount: P2, usesViaInPad: false });
        }
        m3 && this.safeTraceLayerCursorByErrorId.set(m3, _4);
      }
      if (this.enableSafeTraceLayerMoves && S2 && m3 && f3) {
        let o4 = this.traceLayerCorridorCursorByErrorId.get(m3) ?? 0, i4 = 0;
        for (;l3 < a3 && i4 < EN.length; ) {
          const s4 = EN[o4 % EN.length];
          o4 += 1, i4 += 1;
          const a4 = f3[s4.routeSide], c5 = e35[a4]?.route[0]?.z;
          if (c5 === undefined)
            continue;
          const h3 = (c5 + 1) % this.srj.layerCount, d3 = OP(e35, [a4]);
          if (!Yw(this.srj, d3, n3, a4, h3, s4.normalDirectionSign, s4.tangentDirectionSign, s4.reverseEndpointOffsets))
            continue;
          const u3 = aw(d3, [a4]);
          l3 += 1, this.candidateAttempts += 1;
          const m4 = this.getSnapshot(u3), g4 = this.getViaIssueCount(m4), _4 = p4?.snapshot ?? t2;
          g4 <= (p4?.viaIssueCount ?? r3) && vw(m4, _4) && (p4 = { routes: u3, snapshot: m4, viaIssueCount: g4, usesViaInPad: false });
        }
        this.traceLayerCorridorCursorByErrorId.set(m3, o4);
      }
      if (this.enableSafeTraceLayerMoves && I2 && m3 && (this.initialLowCountErrorsHaveMovableTraces && (f3 || g3 !== undefined) || !this.initialLowCountErrorsHaveMovableTraces && f3)) {
        const s4 = this.initialLowCountErrorsHaveMovableTraces ? AN : TN, c5 = f3 ?? [g3];
        let h3 = this.tracePairDetourCursorByErrorId.get(m3) ?? 0, u3 = 0;
        for (;l3 < a3 && u3 < s4.length; ) {
          const m4 = s4[h3 % s4.length];
          h3 += 1, u3 += 1;
          const g4 = c5[m4.routeSide];
          if (g4 === undefined)
            continue;
          const f4 = this.initialLowCountErrorsHaveMovableTraces && n3.worst_contact_center ? { ...n3, center: n3.worst_contact_center, message: n3.worst_contact_message ?? n3.message, actual_clearance: n3.worst_actual_clearance ?? n3.actual_clearance } : n3;
          if (m4.kind === "displacementChain") {
            const n4 = AP(e35), s5 = Dw(this.srj, n4, f4, t2.traceRouteIndexById, m4.routeSide);
            if (!s5)
              continue;
            d2 = true, l3 += 1, this.candidateAttempts += 1;
            let c6 = sw(n4), h4 = this.getSnapshot(c6), u4 = this.getViaIssueCount(h4), g5 = this.getRepairIssueCount(h4);
            if (g5 > 0 && g5 <= 3 && l3 < a3) {
              const e36 = AP(c6);
              let t3 = false;
              for (const n5 of h4.errors)
                t3 = zw(this.srj, e36, n5, h4.traceRouteIndexById, s5.movedRouteIndex, this.connMap) || t3;
              if (t3) {
                l3 += 1, this.candidateAttempts += 1;
                const t4 = sw(e36), n5 = this.getSnapshot(t4), o4 = this.getViaIssueCount(n5);
                Vw(n5, o4, g5, this.getRepairIssueScore(h4), u4, h4) && (c6 = t4, h4 = n5, u4 = o4, g5 = this.getRepairIssueCount(h4));
              }
            }
            const _5 = p4 ? this.getRepairIssueCount(p4.snapshot) : o3, y4 = p4 ? this.getRepairIssueScore(p4.snapshot) : i3;
            if (Vw(h4, u4, _5, y4, p4?.viaIssueCount ?? r3, p4?.snapshot ?? t2) && (p4 = { routes: c6, snapshot: h4, viaIssueCount: u4, usesViaInPad: false }), g5 === 0)
              break;
            continue;
          }
          const _4 = OP(e35, [g4]);
          if (!(m4.kind === "segment" ? $w(_4, f4, g4, m4.halfSpan, m4.offset, m4.directionSign) : m4.kind === "span" ? Xw(this.srj, _4, f4, g4, m4.spanExpansion, m4.offset, m4.directionSign) : Hw(this.srj, _4, f4, g4, m4.spanExpansion, { x: f4.center.x + m4.dx, y: f4.center.y + m4.dy })))
            continue;
          const y3 = aw(_4, [g4]);
          d2 = true, l3 += 1, this.candidateAttempts += 1;
          const b3 = this.getSnapshot(y3), x3 = this.getViaIssueCount(b3), v3 = p4 ? this.getRepairIssueCount(p4.snapshot) : o3, I3 = p4 ? this.getRepairIssueScore(p4.snapshot) : i3, S3 = p4?.viaIssueCount ?? r3;
          (this.initialLowCountErrorsHaveMovableTraces ? Vw(b3, x3, v3, I3, S3, p4?.snapshot ?? t2) : x3 <= S3 && vw(b3, p4?.snapshot ?? t2)) && (p4 = { routes: y3, snapshot: b3, viaIssueCount: x3, usesViaInPad: false });
        }
        this.tracePairDetourCursorByErrorId.set(m3, h3);
      }
      for (const s4 of this.enableViaInPadLayerMoves ? ["start", "end"] : []) {
        if (l3 >= a3)
          break;
        if (g3 === undefined)
          break;
        const c5 = OP(e35, [g3]);
        if (!Ow(this.srj, c5, n3, t2.traceRouteIndexById, s4, this.connMap, this.viaHoleDiameter))
          continue;
        const h3 = aw(c5, [g3]);
        this.viaInPadCandidateAttempts += 1, l3 += 1, this.candidateAttempts += 1;
        const d3 = this.getSnapshot(h3), u3 = this.getViaIssueCount(d3), m4 = p4 ? this.getRepairIssueCount(p4.snapshot) : o3, f4 = p4 ? this.getRepairIssueScore(p4.snapshot) : i3;
        Vw(d3, u3, m4, f4, p4?.viaIssueCount ?? r3, p4?.snapshot ?? t2) && (p4 = { routes: h3, snapshot: d3, viaIssueCount: u3, usesViaInPad: true });
      }
      const _3 = this.enableViaInPadLayerMoves ? this.srj.layerCount : 0;
      for (let s4 = 0;s4 < _3 && !(l3 >= a3) && g3 !== undefined; s4 += 1) {
        const a4 = OP(e35, [g3]);
        if (!Aw(this.srj, a4, n3, t2.traceRouteIndexById, s4, this.connMap, this.viaHoleDiameter))
          continue;
        const c5 = aw(a4, [g3]);
        this.viaInPadCandidateAttempts += 1, l3 += 1, this.candidateAttempts += 1;
        const h3 = this.getSnapshot(c5), d3 = this.getViaIssueCount(h3), u3 = p4 ? this.getRepairIssueCount(p4.snapshot) : o3, m4 = p4 ? this.getRepairIssueScore(p4.snapshot) : i3;
        Vw(h3, d3, u3, m4, p4?.viaIssueCount ?? r3, p4?.snapshot ?? t2) && (p4 = { routes: c5, snapshot: h3, viaIssueCount: d3, usesViaInPad: true });
      }
      if (this.enableViaInPadLayerMoves && I2 && f3) {
        const s4 = this.iterations % 2 == 0 ? [0, 1] : [1, 0], c5 = this.iterations % 3;
        for (const h3 of s4)
          for (let s5 = 0;s5 < this.srj.layerCount && !(l3 >= a3); s5 += 1) {
            const a4 = f3[h3], d3 = OP(e35, [a4]);
            if (!jw(this.srj, d3, n3, t2.traceRouteIndexById, h3, s5, c5, this.connMap, this.viaHoleDiameter))
              continue;
            const u3 = aw(d3, [a4]);
            this.viaInPadCandidateAttempts += 1, l3 += 1, this.candidateAttempts += 1;
            const m4 = this.getSnapshot(u3), g4 = this.getViaIssueCount(m4), _4 = p4 ? this.getRepairIssueCount(p4.snapshot) : o3, y3 = p4 ? this.getRepairIssueScore(p4.snapshot) : i3;
            Vw(m4, g4, _4, y3, p4?.viaIssueCount ?? r3, p4?.snapshot ?? t2) && (p4 = { routes: u3, snapshot: m4, viaIssueCount: g4, usesViaInPad: true });
          }
      }
      p4 && (e35 = p4.routes, t2 = p4.snapshot, o3 = this.getRepairIssueCount(t2), i3 = this.getRepairIssueScore(t2), r3 = p4.viaIssueCount, this.targetedForceAccepted = true, p4.usesViaInPad && (this.viaInPadCandidatesAccepted += 1), u2 = true);
    }
    if (!u2 && v2.length >= 2) {
      const n3 = AP(e35);
      let s3 = false;
      for (const e36 of v2)
        s3 = Ww(this.srj, n3, [e36], t2.traceRouteIndexById, 1, this.connMap, true, this.enableTargetedErrorSweep, false, this.enableTraceViaOwnerTargeting) || s3;
      if (s3) {
        const s4 = sw(n3);
        l3 += 1, this.candidateAttempts += 1;
        const a4 = this.getSnapshot(s4), c4 = this.getViaIssueCount(a4);
        if (Vw(a4, c4, o3, i3, r3, t2) && (e35 = s4, t2 = a4, o3 = this.getRepairIssueCount(a4), i3 = this.getRepairIssueScore(a4), r3 = c4, this.targetedForceAccepted = true, u2 = true, a4.count === 0))
          return void this.acceptSolvedRoutes(e35, t2);
      }
    }
    for (let n3 = 0;n3 < b2 && l3 < a3 && !u2; n3 += 1) {
      const s3 = (x2 + n3) % y2.length, c4 = y2[s3];
      if (!c4)
        continue;
      this.errorCursor = (s3 + 1) % y2.length;
      const h3 = o3 === 1;
      for (const n4 of wb(this.effort)) {
        if (l3 >= a3)
          break;
        const s4 = AP(e35);
        if (!Ww(this.srj, s4, [c4], t2.traceRouteIndexById, n4, this.connMap, true, this.enableTargetedErrorSweep, h3, this.enableTraceViaOwnerTargeting))
          continue;
        const d3 = sw(s4);
        l3 += 1, this.candidateAttempts += 1;
        const p4 = this.getSnapshot(d3), m3 = this.getViaIssueCount(p4);
        if (Vw(p4, m3, o3, i3, r3, t2)) {
          if (e35 = d3, t2 = p4, o3 = this.getRepairIssueCount(p4), i3 = this.getRepairIssueScore(p4), r3 = m3, this.targetedForceAccepted = true, u2 = true, p4.count === 0)
            return void this.acceptSolvedRoutes(e35, t2);
          break;
        }
      }
      if (u2)
        break;
    }
    const M = e35.length <= 120, w = (N = s2.length, Math.max(16, Math.min(64, 2 * N)));
    var N;
    const R2 = this.enableLargeBoardBroadFallback && this.MAX_ITERATIONS >= 192 && !M && this.stalledIterations > 0 && this.stalledIterations % w === 0;
    if (this.enableBroadFallback && !u2 && (M || this.effort >= 2 && this.stalledIterations >= 2 || R2)) {
      p3 = R2;
      for (const n3 of [1, 2]) {
        const s3 = ow(this.srj, e35, this.effort, n3, this.connMap, this.drcEvaluator === undefined, false);
        if (s3 === e35)
          continue;
        const a4 = this.getSnapshot(s3), c4 = this.getViaIssueCount(a4);
        if (Vw(a4, c4, o3, i3, r3, t2) && (e35 = s3, t2 = a4, o3 = this.getRepairIssueCount(a4), i3 = this.getRepairIssueScore(a4), r3 = c4, this.broadForceAccepted = true, u2 = true, a4.count === 0))
          return void this.acceptSolvedRoutes(e35, t2);
      }
    }
    u2 ? this.largeBoardBroadFallbackMisses = 0 : p3 && (this.largeBoardBroadFallbackMisses += 1), this.outputHdRoutes = e35, this.outputSnapshot = t2, this.stalledIterations = u2 ? 0 : this.stalledIterations + 1, d2 || this.updateDrcCountPlateauState(t2), this.updateStats(t2), (this.solved || o3 === 0) && this.acceptSolvedRoutes(e35, t2);
  }
  tryFinalAcceptance() {
    const e35 = this.outputSnapshot ?? this.getSnapshot(this.outputHdRoutes);
    this.legacyCleanCheckpoint && mw(e35) > 0 && this.finishAtLegacyCleanCheckpoint() || this.acceptSolvedRoutes(this.outputHdRoutes, e35);
  }
  getOutput() {
    return this.outputHdRoutes;
  }
  visualize() {
    return super.visualize();
  }
  preview() {
    return this.visualize();
  }
};
var DN = class extends kN {
  deferTraceObstacleOverlapGuard = true;
};
var LN = class extends BaseSolver {
  params;
  inputHdRoutes;
  guardedInputHdRoutes;
  broadMaxIterations;
  broadPassMultiplier;
  autoroutingDrcEngine;
  legacyDrcEvaluator;
  outputHdRoutes;
  phase = "start";
  inputSnapshot;
  baselineSolver;
  baselineSnapshot;
  broadInputSnapshot;
  broadSnapshot;
  broadSolver;
  preBroadCandidate;
  safeTraceLayerInputRoutes;
  safeTraceLayerInputSnapshot;
  safeTraceLayerSolver;
  safeTraceLayerPhaseAccepted = false;
  mixedSafeTraceLayerSolver;
  mixedSafeTraceLayerPhaseAccepted = false;
  legacySafeTraceLayerRoutes;
  legacySafeTraceLayerSnapshot;
  legacySafeTraceLayerSelectedSolver;
  viaInPadSolver;
  portfolioSelectedSolver;
  outputVisualizationSolver;
  overlapSafeCheckpoint;
  traceObstacleRepairRolledBack = false;
  traceObstacleConnectionsRestored = 0;
  traceContactGuard;
  peerTraceRepairRolledBack = false;
  overlapRestorationChecks = 0;
  stoppedForTraceContacts = false;
  referenceInputDrcIssueCount;
  referenceCandidateDrcIssueCount;
  referenceCandidateRolledBack = false;
  mixedReferenceInputDrcIssueCount;
  mixedReferenceCandidateDrcIssueCount;
  referenceInputSnapshot;
  constructor(e35) {
    if (super(), !Number.isFinite(e35.broadPassMultiplier))
      throw new Error("broadPassMultiplier must be a finite number");
    if (e35.broadPassMultiplier <= 0)
      throw new Error("broadPassMultiplier must be greater than zero");
    if (!Number.isInteger(e35.broadMaxIterations))
      throw new Error("broadMaxIterations must be an integer");
    if (e35.broadMaxIterations <= 0)
      throw new Error("broadMaxIterations must be greater than zero");
    if (e35.viaInPadMaxIterations !== undefined && !Number.isInteger(e35.viaInPadMaxIterations))
      throw new Error("viaInPadMaxIterations must be an integer");
    if (e35.viaInPadMaxIterations !== undefined && e35.viaInPadMaxIterations <= 0)
      throw new Error("viaInPadMaxIterations must be greater than zero");
    this.autoroutingDrcEngine = e35.autoroutingDrcEngine ?? (e35.drcEvaluator ? undefined : new mb(e35.srj, { connMap: e35.connMap, traceClearance: e35.srj.minTraceToPadEdgeClearance ?? hP.traceClearance, viaClearance: e35.srj.minTraceToPadEdgeClearance ?? hP.viaClearance, includeTraceViaOwnerMetadata: e35.enableTraceViaOwnerTargeting ?? false })), this.legacyDrcEvaluator = (t2) => {
      const n2 = e35.drcEvaluator?.evaluateLegacy ?? e35.drcEvaluator, o3 = n2 ? n2(t2) : this.autoroutingDrcEngine.evaluateLegacy(t2.traces), i3 = Array.isArray(o3) ? o3 : o3.errors, r3 = Array.isArray(o3) ? o3 : o3.errorsWithCenters ?? o3.errors;
      return { errors: i3.filter((e36) => !uw(e36)), errorsWithCenters: r3.filter((e36) => !uw(e36)) };
    }, Object.defineProperty(this.legacyDrcEvaluator, "inputMode", { get: () => (e35.drcEvaluator?.evaluateLegacy ?? e35.drcEvaluator)?.inputMode }), this.params = { ...e35, autoroutingDrcEngine: this.autoroutingDrcEngine }, this.inputHdRoutes = e35.hdRoutes, this.guardedInputHdRoutes = sw(AP(e35.hdRoutes)), this.broadMaxIterations = e35.broadMaxIterations, this.broadPassMultiplier = e35.broadPassMultiplier, this.outputHdRoutes = e35.hdRoutes, this.params.referenceDrcEvaluator && (this.referenceInputSnapshot = this.getReferenceDrcSnapshot(this.inputHdRoutes));
  }
  getConstructorParams() {
    return [{ ...this.params, hdRoutes: this.inputHdRoutes }];
  }
  stepBranch(e35, t2) {
    if (this.activeSubSolver = e35, e35.step(), e35.failed)
      throw new Error(`${t2} DRC repair branch failed: ${e35.error}`);
  }
  getReferenceDrcSnapshot(e35) {
    const t2 = { traces: [], srj: this.params.srj, routes: e35, hdRoutes: e35 }, n2 = this.params.referenceDrcEvaluator?.getCachedResult?.(t2);
    if (n2) {
      const e36 = Array.isArray(n2) ? n2 : n2.errors;
      return { errors: e36, count: e36.length };
    }
    return HP(this.params.srj, e35, this.params.referenceDrcEvaluator, this.params.connMap, this.autoroutingDrcEngine);
  }
  getNewPeerContactConnectionNames(e35) {
    return this.params.deferTraceContactGuard ? new Set : (this.traceContactGuard ??= new RN({ srj: this.params.srj, inputRoutes: this.guardedInputHdRoutes, connMap: this.params.connMap }), this.traceContactGuard.getNewContactConnectionNames(e35));
  }
  rememberOverlapSafeCandidate({ routes: e35, snapshot: t2, solver: n2, safeTraceLayerPhaseAccepted: o3 }) {
    this.overlapSafeCheckpoint && !vw(t2, this.overlapSafeCheckpoint.snapshot) || xw(t2, this.inputSnapshot) || this.getNewPeerContactConnectionNames(e35).size > 0 || (this.overlapSafeCheckpoint = { routes: sw(AP(e35)), snapshot: t2, solver: n2, safeTraceLayerPhaseAccepted: o3 });
  }
  finishWithOutput(e35, t2, n2) {
    let o3 = e35, i3 = t2;
    this.rememberOverlapSafeCandidate({ routes: e35, snapshot: t2, solver: n2, safeTraceLayerPhaseAccepted: this.safeTraceLayerPhaseAccepted });
    let r3 = this.getNewPeerContactConnectionNames(e35);
    if (xw(t2, this.inputSnapshot) || r3.size > 0) {
      this.peerTraceRepairRolledBack = r3.size > 0;
      const e36 = new Set, t3 = r3.size > 0 ? 2 : 1;
      for (let s3 = 0;s3 < t3; s3++) {
        const t4 = MN({ routes: o3, snapshot: i3, inputSnapshot: this.inputSnapshot, checkpointRoutes: this.overlapSafeCheckpoint.routes, peerConnectionNames: r3 });
        if (!t4)
          break;
        for (const n3 of t4.restoredConnectionNames)
          e36.add(n3);
        const s4 = HP(this.params.srj, t4.routes, this.phase === "viaInPad" ? this.params.viaInPadDrcEvaluator ?? this.params.drcEvaluator : this.params.drcEvaluator, this.params.connMap, this.autoroutingDrcEngine);
        if (this.overlapRestorationChecks++, this.rememberOverlapSafeCandidate({ routes: t4.routes, snapshot: s4, solver: n2, safeTraceLayerPhaseAccepted: this.safeTraceLayerPhaseAccepted }), this.overlapSafeCheckpoint.snapshot === s4) {
          this.traceObstacleConnectionsRestored = e36.size;
          break;
        }
        if (o3 = t4.routes, i3 = s4, r3 = this.getNewPeerContactConnectionNames(o3), !xw(i3, this.inputSnapshot) && r3.size === 0)
          break;
      }
      const s2 = this.overlapSafeCheckpoint;
      o3 = s2.routes, i3 = s2.snapshot, n2 = s2.solver, this.portfolioSelectedSolver = s2.solver, this.safeTraceLayerPhaseAccepted = s2.safeTraceLayerPhaseAccepted, this.mixedSafeTraceLayerPhaseAccepted = s2.solver !== undefined && s2.solver === this.mixedSafeTraceLayerSolver, this.traceObstacleRepairRolledBack = true;
    }
    if (this.params.referenceDrcEvaluator) {
      const e36 = this.referenceInputSnapshot, t3 = this.getReferenceDrcSnapshot(o3);
      this.referenceInputDrcIssueCount = e36.count, this.referenceCandidateDrcIssueCount = t3.count, (t3.count > e36.count || t3.count === e36.count && ((e37, t4) => {
        const n3 = new Set(t4.map(pw));
        return e37.some((e38) => !n3.has(pw(e38)));
      })(t3.errors, e36.errors)) && (o3 = this.guardedInputHdRoutes, i3 = this.inputSnapshot, this.referenceCandidateRolledBack = true, this.traceObstacleConnectionsRestored = 0);
    }
    this.outputHdRoutes = o3, this.activeSubSolver = null, this.phase = "done", this.progress = 1, this.stats = { ...this.portfolioSelectedSolver?.stats ?? {}, ...n2?.stats ?? {}, finalDrcIssueCount: i3.count, drcBranchPortfolioInitialDrcIssueCount: this.inputSnapshot?.count ?? t2.count, drcBranchPortfolioBaselineDrcIssueCount: this.baselineSnapshot?.count ?? t2.count, drcBranchPortfolioBroadInitialDrcIssueCount: this.broadInputSnapshot?.count, drcBranchPortfolioBroadFinalDrcIssueCount: this.broadSnapshot?.count, drcBranchPortfolioBroadMaxIterations: this.broadMaxIterations, drcBranchPortfolioBroadBranchAttempted: Boolean(this.broadSolver), drcBranchPortfolioBroadBranchAccepted: this.portfolioSelectedSolver !== undefined && this.portfolioSelectedSolver === this.broadSolver, drcBranchPortfolioSafeTraceLayerPhaseAttempted: Boolean(this.safeTraceLayerSolver), drcBranchPortfolioSafeTraceLayerPhaseAccepted: this.safeTraceLayerPhaseAccepted, drcBranchPortfolioMixedSafeTraceLayerPhaseAttempted: Boolean(this.mixedSafeTraceLayerSolver), drcBranchPortfolioMixedSafeTraceLayerPhaseAccepted: this.mixedSafeTraceLayerPhaseAccepted, drcBranchPortfolioViaInPadPhaseAttempted: Boolean(this.viaInPadSolver), drcBranchPortfolioViaInPadMaxIterations: this.params.viaInPadMaxIterations, drcBranchPortfolioFinalNonViaPadDrcIssueCount: mw(i3), drcBranchPortfolioReferenceInputDrcIssueCount: this.referenceInputDrcIssueCount, drcBranchPortfolioReferenceCandidateDrcIssueCount: this.referenceCandidateDrcIssueCount, drcBranchPortfolioReferenceCandidateRolledBack: this.referenceCandidateRolledBack, drcBranchPortfolioTraceObstacleRepairRolledBack: this.traceObstacleRepairRolledBack, drcBranchPortfolioTraceObstacleConnectionsRestored: this.traceObstacleConnectionsRestored, drcBranchPortfolioPeerTraceRepairRolledBack: this.peerTraceRepairRolledBack, drcBranchPortfolioOverlapRestorationChecks: this.overlapRestorationChecks, drcBranchPortfolioStoppedForTraceContacts: this.stoppedForTraceContacts, drcBranchPortfolioMixedReferenceInputDrcIssueCount: this.mixedReferenceInputDrcIssueCount, drcBranchPortfolioMixedReferenceCandidateDrcIssueCount: this.mixedReferenceCandidateDrcIssueCount }, this.solved = true;
  }
  startBaselineBranch() {
    this.baselineSolver = new DN({ ...this.params, hdRoutes: this.inputHdRoutes, drcEvaluator: this.legacyDrcEvaluator, referenceDrcEvaluator: undefined, enableSafeTraceLayerMoves: false, enableViaInPadLayerMoves: false }), this.activeSubSolver = this.baselineSolver, this.phase = "baseline";
  }
  startSafeTraceLayerPhase(e35, t2, n2) {
    this.portfolioSelectedSolver = n2, this.rememberOverlapSafeCandidate({ routes: e35, snapshot: t2, solver: n2, safeTraceLayerPhaseAccepted: false }), this.params.enableSafeTraceLayerMoves ? (this.safeTraceLayerInputRoutes = e35, this.safeTraceLayerInputSnapshot = t2, this.safeTraceLayerSolver = new DN({ ...this.params, hdRoutes: e35, drcEvaluator: this.legacyDrcEvaluator, referenceDrcEvaluator: undefined, maxIterations: this.params.viaInPadMaxIterations ?? this.params.maxIterations, enableLargeBoardBroadFallback: false, enableTargetedErrorSweep: false, enablePostSolveClearanceRelaxation: false, enableSafeTraceLayerMoves: true, enableViaInPadLayerMoves: false }), this.activeSubSolver = this.safeTraceLayerSolver, this.phase = "safeTraceLayer") : this.startViaInPadPhase(e35, t2, n2);
  }
  startViaInPadPhase(e35, t2, n2) {
    this.portfolioSelectedSolver = n2, this.rememberOverlapSafeCandidate({ routes: e35, snapshot: t2, solver: n2, safeTraceLayerPhaseAccepted: this.safeTraceLayerPhaseAccepted });
    const o3 = this.params.enableViaInPadLayerMoves && this.params.viaInPadDrcEvaluator !== undefined;
    t2.errors.some(uw) || o3 ? (this.viaInPadSolver = new DN({ ...this.params, hdRoutes: e35, drcEvaluator: this.params.viaInPadDrcEvaluator ?? this.params.drcEvaluator, maxIterations: this.params.viaInPadMaxIterations ?? this.params.maxIterations, enableLargeBoardBroadFallback: false, enableTargetedErrorSweep: false, enablePostSolveClearanceRelaxation: false, enableSafeTraceLayerMoves: false, enableViaInPadLayerMoves: this.params.enableViaInPadLayerMoves }), this.activeSubSolver = this.viaInPadSolver, this.phase = "viaInPad") : this.finishWithOutput(e35, t2, n2);
  }
  startMixedSafeTraceLayerPhase(e35, t2, n2) {
    if (this.params.prioritizeMultipleTraceContactRepair && this.params.deferTraceContactGuard && (this.traceContactGuard ??= new RN({ srj: this.params.srj, inputRoutes: this.guardedInputHdRoutes, connMap: this.params.connMap }), this.traceContactGuard.getNewContactPairs(e35).length > 1))
      return this.stoppedForTraceContacts = true, void this.finishWithOutput(e35, t2, n2);
    this.legacySafeTraceLayerRoutes = e35, this.legacySafeTraceLayerSnapshot = t2, this.legacySafeTraceLayerSelectedSolver = n2, this.mixedSafeTraceLayerSolver = new DN({ ...this.params, hdRoutes: this.safeTraceLayerInputRoutes, drcEvaluator: this.params.drcEvaluator, referenceDrcEvaluator: undefined, maxIterations: this.params.viaInPadMaxIterations ?? this.params.maxIterations, enableLargeBoardBroadFallback: false, enableTargetedErrorSweep: false, enablePostSolveClearanceRelaxation: false, enableSafeTraceLayerMoves: true, enableViaInPadLayerMoves: false }), this.activeSubSolver = this.mixedSafeTraceLayerSolver, this.phase = "mixedSafeTraceLayer";
  }
  startBroadBranch() {
    const e35 = ow(this.params.srj, this.inputHdRoutes, this.params.effort ?? 1, this.broadPassMultiplier, this.params.connMap);
    this.broadInputSnapshot = HP(this.params.srj, e35, this.params.drcEvaluator, this.params.connMap, this.autoroutingDrcEngine), vw(this.broadInputSnapshot, this.baselineSnapshot) ? (this.broadSolver = new DN({ ...this.params, hdRoutes: e35, drcEvaluator: this.legacyDrcEvaluator, referenceDrcEvaluator: undefined, maxIterations: this.broadMaxIterations, enableSafeTraceLayerMoves: false, enableViaInPadLayerMoves: false }), this.activeSubSolver = this.broadSolver, this.phase = "broad") : this.startSafeTraceLayerPhase(this.baselineSolver.getOutput(), this.baselineSnapshot, this.baselineSolver);
  }
  _step() {
    if (this.phase === "start")
      return this.inputSnapshot = HP(this.params.srj, this.inputHdRoutes, this.params.drcEvaluator, this.params.connMap, this.autoroutingDrcEngine), this.overlapSafeCheckpoint = { routes: this.guardedInputHdRoutes, snapshot: this.inputSnapshot, safeTraceLayerPhaseAccepted: false }, mw(this.inputSnapshot) === 0 ? void this.startViaInPadPhase(this.inputHdRoutes, this.inputSnapshot) : void this.startBaselineBranch();
    if (this.phase === "baseline") {
      if (this.stepBranch(this.baselineSolver, "baseline"), !this.baselineSolver.solved)
        return;
      const e35 = this.baselineSolver.getOutput();
      return this.baselineSnapshot = HP(this.params.srj, e35, this.params.drcEvaluator, this.params.connMap, this.autoroutingDrcEngine), this.rememberOverlapSafeCandidate({ routes: e35, snapshot: this.baselineSnapshot, solver: this.baselineSolver, safeTraceLayerPhaseAccepted: false }), mw(this.baselineSnapshot) === 0 ? void this.startViaInPadPhase(e35, this.baselineSnapshot, this.baselineSolver) : void (this.params.enableSafeTraceLayerMoves && this.baselineSnapshot.count <= 3 ? this.startSafeTraceLayerPhase(e35, this.baselineSnapshot, this.baselineSolver) : this.startBroadBranch());
    }
    if (this.phase === "broad") {
      if (this.stepBranch(this.broadSolver, "broad"), !this.broadSolver.solved)
        return;
      const e35 = this.broadSolver.getOutput();
      return this.broadSnapshot = HP(this.params.srj, e35, this.params.drcEvaluator, this.params.connMap, this.autoroutingDrcEngine), vw(this.broadSnapshot, this.baselineSnapshot) ? void this.startSafeTraceLayerPhase(e35, this.broadSnapshot, this.broadSolver) : void this.startSafeTraceLayerPhase(this.baselineSolver.getOutput(), this.baselineSnapshot, this.baselineSolver);
    }
    if (this.phase === "safeTraceLayer") {
      if (this.stepBranch(this.safeTraceLayerSolver, "safe trace-layer"), !this.safeTraceLayerSolver.solved)
        return;
      const e35 = this.safeTraceLayerSolver.getOutput(), t2 = HP(this.params.srj, e35, this.params.drcEvaluator, this.params.connMap, this.autoroutingDrcEngine), n2 = hw(this.safeTraceLayerInputSnapshot), o3 = hw(t2);
      this.safeTraceLayerPhaseAccepted = o3 <= n2 && Vw(t2, o3, this.safeTraceLayerInputSnapshot.count, this.safeTraceLayerInputSnapshot.issueScore, n2);
      let i3 = this.safeTraceLayerPhaseAccepted ? e35 : this.safeTraceLayerInputRoutes, r3 = this.safeTraceLayerPhaseAccepted ? t2 : this.safeTraceLayerInputSnapshot, s2 = this.safeTraceLayerPhaseAccepted ? this.safeTraceLayerSolver : this.portfolioSelectedSolver;
      return this.rememberOverlapSafeCandidate({ routes: i3, snapshot: r3, solver: s2, safeTraceLayerPhaseAccepted: this.safeTraceLayerPhaseAccepted }), this.preBroadCandidate && !vw(r3, this.preBroadCandidate.snapshot) && (i3 = this.preBroadCandidate.routes, r3 = this.preBroadCandidate.snapshot, s2 = this.preBroadCandidate.solver, this.safeTraceLayerPhaseAccepted = this.preBroadCandidate.safeTraceLayerPhaseAccepted), r3.count > 0 && !this.broadInputSnapshot ? (this.preBroadCandidate = { routes: i3, snapshot: r3, solver: s2, safeTraceLayerPhaseAccepted: this.safeTraceLayerPhaseAccepted }, void this.startBroadBranch()) : mw(r3) > 0 && this.safeTraceLayerInputSnapshot.errors.some(uw) ? void this.startMixedSafeTraceLayerPhase(i3, r3, s2) : void this.startViaInPadPhase(i3, r3, s2);
    }
    if (this.phase === "mixedSafeTraceLayer") {
      if (this.stepBranch(this.mixedSafeTraceLayerSolver, "mixed safe trace-layer"), !this.mixedSafeTraceLayerSolver.solved)
        return;
      const e35 = this.mixedSafeTraceLayerSolver.getOutput(), t2 = HP(this.params.srj, e35, this.params.drcEvaluator, this.params.connMap, this.autoroutingDrcEngine), n2 = mw(t2) <= mw(this.legacySafeTraceLayerSnapshot);
      let o3 = true;
      if (this.params.referenceDrcEvaluator) {
        const t3 = this.getReferenceDrcSnapshot(this.legacySafeTraceLayerRoutes), n3 = this.getReferenceDrcSnapshot(e35);
        this.mixedReferenceInputDrcIssueCount = t3.count, this.mixedReferenceCandidateDrcIssueCount = n3.count, o3 = n3.count <= t3.count;
      }
      return this.mixedSafeTraceLayerPhaseAccepted = n2 && o3, void this.startViaInPadPhase(this.mixedSafeTraceLayerPhaseAccepted ? e35 : this.legacySafeTraceLayerRoutes, this.mixedSafeTraceLayerPhaseAccepted ? t2 : this.legacySafeTraceLayerSnapshot, this.mixedSafeTraceLayerPhaseAccepted ? this.mixedSafeTraceLayerSolver : this.legacySafeTraceLayerSelectedSolver);
    }
    if (this.phase === "viaInPad") {
      if (this.stepBranch(this.viaInPadSolver, "via-in-pad"), !this.viaInPadSolver.solved)
        return;
      const e35 = this.viaInPadSolver.getOutput(), t2 = HP(this.params.srj, e35, this.params.viaInPadDrcEvaluator ?? this.params.drcEvaluator, this.params.connMap, this.autoroutingDrcEngine);
      this.finishWithOutput(e35, t2, this.viaInPadSolver);
    }
  }
  getOutput() {
    return this.outputHdRoutes;
  }
  visualize() {
    return this.activeSubSolver ? this.activeSubSolver.visualize() : this.solved ? (this.outputVisualizationSolver || (this.outputVisualizationSolver = new kN({ ...this.params, hdRoutes: this.inputHdRoutes, referenceDrcEvaluator: undefined }), this.outputVisualizationSolver.outputHdRoutes = this.outputHdRoutes, this.outputVisualizationSolver.stats = this.stats, this.outputVisualizationSolver.solved = true, this.outputVisualizationSolver.progress = 1), this.outputVisualizationSolver.visualize()) : super.visualize();
  }
  preview() {
    return this.activeSubSolver?.preview() ?? this.visualize();
  }
};
var zN = (e35, t2, n2) => {
  const o3 = n2.x - t2.x, i3 = n2.y - t2.y, r3 = o3 * o3 + i3 * i3;
  return r3 === 0 ? 0 : Math.max(0, Math.min(1, ((e35.x - t2.x) * o3 + (e35.y - t2.y) * i3) / r3));
};
var BN = (e35, t2, n2) => ({ x: e35.x + (t2.x - e35.x) * n2, y: e35.y + (t2.y - e35.y) * n2, z: e35.z });
var FN = (e35, t2, n2, o3) => {
  const i3 = t2.x - e35.x, r3 = t2.y - e35.y, s2 = o3.x - n2.x, a3 = o3.y - n2.y, c3 = i3 * a3 - r3 * s2;
  if (Math.abs(c3) > 0.000000000001) {
    const t3 = ((n2.x - e35.x) * a3 - (n2.y - e35.y) * s2) / c3, o4 = ((n2.x - e35.x) * r3 - (n2.y - e35.y) * i3) / c3;
    if (t3 >= 0 && t3 <= 1 && o4 >= 0 && o4 <= 1)
      return [t3, o4];
  }
  const l3 = [[0, zN(e35, n2, o3)], [1, zN(t2, n2, o3)], [zN(n2, e35, t2), 0], [zN(o3, e35, t2), 1]];
  let h2 = l3[0], d2 = 1 / 0;
  for (const i4 of l3) {
    const r4 = BN(e35, t2, i4[0]), s3 = BN(n2, o3, i4[1]), a4 = Math.hypot(r4.x - s3.x, r4.y - s3.y);
    a4 < d2 && (h2 = i4, d2 = a4);
  }
  return h2;
};
var jN = (e35, t2) => {
  const n2 = [];
  for (let o3 = 1;o3 < e35.route.length; o3++) {
    const i3 = e35.route[o3 - 1], r3 = e35.route[o3];
    if (i3.z === r3.z && i3.toNextSegmentType !== "through_obstacle")
      for (let s2 = 1;s2 < t2.route.length; s2++) {
        const a3 = t2.route[s2 - 1], c3 = t2.route[s2];
        if (a3.z !== c3.z || i3.z !== a3.z || a3.toNextSegmentType === "through_obstacle")
          continue;
        if (we(i3, r3, a3, c3) >= (e35.traceThickness + t2.traceThickness) / 2 - 0.000000001)
          continue;
        const [l3, h2] = FN(i3, r3, a3, c3);
        n2.push({ indexes: [o3, s2], positions: [o3 - 1 + l3, s2 - 1 + h2] });
      }
  }
  return n2;
};
var $N = (e35, t2, n2, o3) => {
  const i3 = Math.min(Math.floor(t2), e35.route.length - 2);
  let r3 = BN(e35.route[i3], e35.route[i3 + 1], t2 - i3), s2 = n2 < 0 ? i3 : i3 + 1;
  for (;s2 >= 0 && s2 < e35.route.length; ) {
    const t3 = e35.route[s2], i4 = n2 < 0 ? t3 : e35.route[s2 - 1];
    if (r3.z !== t3.z || i4.toNextSegmentType === "through_obstacle")
      return;
    const a3 = Math.hypot(t3.x - r3.x, t3.y - r3.y);
    if (a3 >= o3 && a3 > 0) {
      if (Math.abs(a3 - o3) <= 0.000000001 && t3.pcb_port_id)
        return;
      return { index: n2 < 0 ? s2 : s2 - 1, point: BN(r3, t3, o3 / a3) };
    }
    o3 -= a3, r3 = t3, s2 += n2;
  }
};
var YN = (e35) => e35.reduce((e36, t2) => e36 + t2.vias.length, 0);
var XN = (e35, t2) => e35.snapshot.count < t2.snapshot.count || e35.snapshot.count === t2.snapshot.count && e35.snapshot.issueScore < t2.snapshot.issueScore - 0.00000001;
var HN = class extends BaseSolver {
  params;
  guard;
  phase = "start";
  inputSnapshot;
  targetDrcCount = 1 / 0;
  current;
  best;
  proposals;
  candidateContactCheck;
  pairs = [];
  affectedConnections = new Set;
  refineSolver;
  candidateChecks = 0;
  geometryChecks = 0;
  contactRounds = 0;
  viaRounds = 0;
  simplificationRounds = 0;
  outputHdRoutes;
  constructor(e35) {
    super(), this.params = e35, this.guard = new RN({ srj: e35.srj, inputRoutes: e35.inputHdRoutes, connMap: e35.connMap }), this.outputHdRoutes = e35.inputHdRoutes, this.MAX_ITERATIONS = 20000;
  }
  snapshot(e35) {
    return HP(this.params.srj, e35, this.params.drcEvaluator, this.params.connMap, this.params.autoroutingDrcEngine);
  }
  startContactRound() {
    this.guard.preserveClearedContacts(this.current.routes), this.pairs = this.guard.getNewContactPairs(this.current.routes), this.pairs.length !== 0 ? this.contactRounds++ >= 4 || this.geometryChecks >= 2048 || this.candidateChecks >= 256 ? this.finish() : (this.best = undefined, this.candidateContactCheck = this.guard.prepareCandidateCheck(this.current.routes), this.proposals = function* ({ srj: e35, routes: t2, pair: n2, connMap: o3, viaHoleDiameter: i3 }) {
      const r3 = t2.flatMap((e36, t3) => e36.connectionName === n2[0] ? [t3] : []), s2 = t2.flatMap((e36, t3) => e36.connectionName === n2[1] ? [t3] : []);
      for (const n3 of r3)
        for (const r4 of s2) {
          const s3 = [n3, r4], a3 = t2[n3], c3 = t2[r4], l3 = jN(a3, c3);
          if (l3.length === 0)
            continue;
          for (const n4 of [0, 1]) {
            const o4 = s3[n4], i4 = t2[o4], r5 = t2[s3[1 - n4]];
            for (const s4 of [-1, 1])
              for (const h4 of [0.001, 0.1])
                for (const d2 of [0, 1]) {
                  const u2 = OP(t2, [o4]);
                  for (const e36 of l3) {
                    const t3 = e36.indexes[n4], l4 = e36.indexes[1 - n4], p3 = r5.route[l4 - 1], m2 = r5.route[l4], g2 = m2.x - p3.x, f2 = m2.y - p3.y, _2 = Math.hypot(g2, f2);
                    if (_2 <= 0.000000001)
                      continue;
                    const y2 = -f2 / _2 * s4, b2 = g2 / _2 * s4, x2 = (a3.traceThickness + c3.traceThickness) / 2 + h4;
                    for (let e37 = Math.max(1, t3 - 1 - d2);e37 <= Math.min(i4.route.length - 2, t3 + d2); e37++) {
                      const t4 = u2[o4].route[e37], n5 = i4.route[e37 - 1], r6 = i4.route[e37 + 1];
                      if (t4.z !== p3.z || t4.pcb_port_id || n5.z !== t4.z || r6.z !== t4.z || n5.toNextSegmentType === "through_obstacle" || t4.toNextSegmentType === "through_obstacle")
                        continue;
                      const s5 = x2 - ((t4.x - p3.x) * y2 + (t4.y - p3.y) * b2);
                      s5 > 0 && (t4.x += s5 * y2, t4.y += s5 * b2);
                    }
                  }
                  u2[o4].route.every((t3) => t3.x >= e35.bounds.minX && t3.x <= e35.bounds.maxX && t3.y >= e35.bounds.minY && t3.y <= e35.bounds.maxY) && (yield aw(u2, [o4]));
                }
            const h3 = [[Math.min(...l3.map((e36) => e36.positions[n4])), Math.max(...l3.map((e36) => e36.positions[n4]))], [Math.min(...l3.map((e36) => e36.indexes[n4])) - 1, Math.max(...l3.map((e36) => e36.indexes[n4]))]];
            for (const [n5, r6] of h3) {
              const s4 = i4.route[Math.floor(n5)].z, a4 = [0.15, 0.3, 0.6, 1, 2];
              for (const c4 of a4)
                for (const l4 of a4)
                  for (let a5 = 0;a5 < e35.layerCount; a5++) {
                    if (a5 === s4)
                      continue;
                    const e36 = $N(i4, n5, -1, c4), h4 = $N(i4, r6, 1, l4);
                    if (!e36 || !h4 || e36.index > h4.index)
                      continue;
                    const d2 = i4.route.slice(e36.index + 1, h4.index + 1);
                    if (d2.some((e37) => e37.z !== s4 || e37.pcb_port_id || e37.toNextSegmentType === "through_obstacle"))
                      continue;
                    const u2 = OP(t2, [o4]);
                    u2[o4].route = [...i4.route.slice(0, e36.index + 1), e36.point, { ...e36.point, z: a5 }, ...d2.map((e37) => ({ ...e37, z: a5 })), { ...h4.point, z: a5 }, h4.point, ...i4.route.slice(h4.index + 1)], yield aw(u2, [o4]);
                  }
            }
          }
          const h2 = new Map([["peer_left", n3], ["peer_right", r4]]);
          for (const n4 of l3) {
            const r5 = { type: "pcb_trace_error", pcb_trace_id: "peer_left", pcb_trace_ids: ["peer_left", "peer_right"], center: BN(a3.route[n4.indexes[0] - 1], a3.route[n4.indexes[0]], n4.positions[0] - n4.indexes[0] + 1), minimum_clearance: 0.1 };
            for (const n5 of [0, 1])
              for (let a4 = 0;a4 < e35.layerCount; a4++)
                for (const c4 of [0, 1, 2, 4]) {
                  const l4 = OP(t2, [s3[n5]]);
                  jw(e35, l4, r5, h2, n5, a4, c4, o3, i3) && (yield aw(l4, [s3[n5]]));
                }
          }
        }
    }({ ...this.params, routes: this.current.routes, pair: this.pairs[0] }), this.phase = "contacts") : this.startRefinement();
  }
  startRefinement() {
    this.current.snapshot.count <= this.targetDrcCount || xw(this.current.snapshot, this.inputSnapshot) ? this.finish() : (this.refineSolver = new LN({ ...this.params, hdRoutes: this.current.routes, maxIterations: 1, viaInPadMaxIterations: Math.min(24, this.params.viaInPadMaxIterations ?? 8), broadMaxIterations: 4, enableSafeTraceLayerMoves: false, prioritizeMultipleTraceContactRepair: false, enableBroadFallback: false, enableLargeBoardBroadFallback: false, enablePostSolveClearanceRelaxation: false, deferTraceContactGuard: false, referenceDrcEvaluator: undefined }), this.activeSubSolver = this.refineSolver, this.phase = "refine");
  }
  startViaRound() {
    this.guard.preserveClearedContacts(this.current.routes), this.current.snapshot.count <= this.targetDrcCount || this.viaRounds++ >= 4 || this.candidateChecks >= 768 ? this.finish() : (this.best = this.current, this.candidateContactCheck = this.guard.prepareCandidateCheck(this.current.routes), this.proposals = function* ({ srj: e35, routes: t2, previousRoutes: n2, affectedConnections: o3 }) {
      const i3 = new Set(n2.flatMap((e36) => e36.vias.map((t3) => `${e36.connectionName}:${t3.x},${t3.y}`)));
      let r3 = 0;
      for (const [n3, s2] of t2.entries())
        if (o3.has(s2.connectionName))
          for (let o4 = 1;o4 < s2.route.length; o4++) {
            const a3 = s2.route[o4 - 1], c3 = s2.route[o4];
            if (a3.z === c3.z || a3.x !== c3.x || a3.y !== c3.y || i3.has(`${s2.connectionName}:${c3.x},${c3.y}`))
              continue;
            let l3 = o4 - 1, h2 = o4;
            for (;l3 > 0 && s2.route[l3 - 1].x === c3.x && s2.route[l3 - 1].y === c3.y; )
              l3--;
            for (;h2 + 1 < s2.route.length && s2.route[h2 + 1].x === c3.x && s2.route[h2 + 1].y === c3.y; )
              h2++;
            if (o4 = h2, l3 !== 0 && h2 !== s2.route.length - 1 && s2.route[l3 - 1].toNextSegmentType !== "through_obstacle" && !s2.route.slice(l3, h2 + 1).some((e36) => e36.pcb_port_id || e36.toNextSegmentType === "through_obstacle")) {
              if (++r3 > 8)
                return;
              for (const o5 of [0.05, 0.1, 0.4])
                for (let i4 = 0;i4 < 8; i4++) {
                  const r4 = c3.x + Math.cos(i4 * Math.PI / 4) * o5, a4 = c3.y + Math.sin(i4 * Math.PI / 4) * o5, d2 = s2.viaDiameter / 2, u2 = e35.bounds;
                  if (r4 - d2 < u2.minX || r4 + d2 > u2.maxX || a4 - d2 < u2.minY || a4 + d2 > u2.maxY)
                    continue;
                  const p3 = OP(t2, [n3]);
                  for (let e36 = l3;e36 <= h2; e36++)
                    p3[n3].route[e36].x = r4, p3[n3].route[e36].y = a4;
                  yield aw(p3, [n3]);
                }
            }
          }
    }({ srj: this.params.srj, routes: this.current.routes, previousRoutes: this.params.hdRoutes, affectedConnections: this.affectedConnections }), this.phase = "vias");
  }
  finish() {
    const e35 = this.current;
    if (e35 && e35.snapshot.count <= this.inputSnapshot.count && this.guard.getNewContactPairs(e35.routes).length === 0 && !xw(e35.snapshot, this.inputSnapshot)) {
      if (this.phase !== "simplify" && YN(e35.routes) > YN(this.params.hdRoutes))
        return void this.startSimplificationRound();
      this.outputHdRoutes = e35.routes;
    }
    this.stats = { traceContactRepairCandidateChecks: this.candidateChecks, traceContactRepairGeometryChecks: this.geometryChecks, traceContactRepairContactRounds: this.contactRounds, traceContactRepairViaRounds: this.viaRounds, traceContactRepairSimplificationRounds: this.simplificationRounds, traceContactRepairAccepted: this.outputHdRoutes !== this.params.inputHdRoutes }, this.activeSubSolver = null, this.phase = "done", this.progress = 1, this.solved = true;
  }
  startSimplificationRound() {
    this.phase = "simplify", this.guard.preserveClearedContacts(this.current.routes), YN(this.current.routes) <= YN(this.params.hdRoutes) || this.simplificationRounds++ >= 4 ? this.finish() : (this.proposals = function* (e35) {
      for (let t2 = 0;t2 < e35.length; t2++) {
        const n2 = e35[t2], o3 = n2.route.flatMap((e36, t3) => t3 > 0 && e36.z !== n2.route[t3 - 1].z ? [t3] : []);
        for (let i3 = 0;i3 + 1 < o3.length; i3++) {
          const r3 = o3[i3], s2 = o3[i3 + 1], a3 = n2.route[r3 - 1].z;
          if (n2.route[s2].z === a3 && !n2.route.slice(r3 - 1, s2 + 1).some((e36) => e36.toNextSegmentType === "through_obstacle") && !n2.route.slice(r3, s2).some((e36) => e36.pcb_port_id))
            for (const n3 of ["chord", "flatten"]) {
              const o4 = OP(e35, [t2]), i4 = o4[t2];
              if (n3 === "chord")
                i4.route.splice(r3, s2 - r3);
              else
                for (let e36 = r3;e36 < s2; e36++)
                  i4.route[e36].z = a3;
              i4.route = i4.route.filter((e36, t3, n4) => {
                const o5 = n4[t3 - 1];
                return !o5 || e36.pcb_port_id || e36.toNextSegmentType || o5.toNextSegmentType || e36.insideJumperPad !== o5.insideJumperPad || e36.x !== o5.x || e36.y !== o5.y || e36.z !== o5.z;
              }), yield aw(o4, [t2]);
            }
        }
      }
    }(this.current.routes), this.candidateContactCheck = this.guard.prepareCandidateCheck(this.current.routes));
  }
  _step() {
    if (this.phase === "start")
      return this.inputSnapshot = this.snapshot(this.params.inputHdRoutes), this.current = { routes: this.params.hdRoutes, snapshot: this.snapshot(this.params.hdRoutes) }, this.targetDrcCount = this.current.snapshot.count, this.affectedConnections = this.guard.getNewContactConnectionNames(this.current.routes), void this.startContactRound();
    if (this.phase === "refine") {
      const e36 = this.refineSolver;
      if (e36.step(), e36.failed)
        throw new Error(`Peer contact refinement failed: ${e36.error}`);
      if (!e36.solved)
        return;
      const t3 = e36.getOutput(), n3 = { routes: t3, snapshot: this.snapshot(t3) };
      return XN(n3, this.current) && this.guard.getNewContactPairs(t3).length === 0 && !xw(n3.snapshot, this.inputSnapshot) && (this.current = n3), this.activeSubSolver = null, void this.startViaRound();
    }
    if (this.phase === "simplify") {
      const e36 = this.proposals.next();
      if (e36.done || this.geometryChecks >= 4096 || this.candidateChecks >= 768)
        return void this.finish();
      const t3 = e36.value;
      if (this.geometryChecks++, this.candidateContactCheck(t3).length > 0)
        return;
      this.candidateChecks++;
      const n3 = this.snapshot(t3);
      if (n3.count > this.current.snapshot.count || xw(n3, this.inputSnapshot) || YN(t3) >= YN(this.current.routes))
        return;
      return this.current = { routes: t3, snapshot: n3 }, void this.startSimplificationRound();
    }
    if (this.phase !== "contacts" && this.phase !== "vias")
      return;
    const e35 = this.proposals.next();
    if (e35.done || this.geometryChecks >= 4096 || this.candidateChecks >= 768) {
      if (this.phase === "contacts") {
        if (!this.best)
          return void this.finish();
        this.current = this.best, this.startContactRound();
      } else
        this.best !== this.current ? (this.current = this.best, this.startViaRound()) : this.finish();
      return;
    }
    const t2 = e35.value;
    if (this.geometryChecks++, this.phase === "contacts" && this.guard.hasContactPair(t2, this.pairs[0]))
      return;
    const n2 = this.candidateContactCheck(t2);
    if (this.phase === "contacts") {
      if (n2.length >= this.pairs.length || n2.some((e36) => e36[0] === this.pairs[0][0] && e36[1] === this.pairs[0][1] || !this.pairs.some((t3) => t3[0] === e36[0] && t3[1] === e36[1])))
        return;
    } else if (n2.length > 0)
      return;
    this.candidateChecks++;
    const o3 = { routes: t2, snapshot: this.snapshot(t2) };
    xw(o3.snapshot, this.inputSnapshot) || (this.best && !XN(o3, this.best) || (this.best = o3), this.phase === "contacts" && this.best.snapshot.count <= this.current.snapshot.count && YN(this.best.routes) <= YN(this.current.routes) && (this.current = this.best, this.startContactRound()));
  }
  getOutput() {
    return this.outputHdRoutes;
  }
};
function VN(e35) {
  if (!e35.connections.some((e36) => e36.pointsToConnect.some((e37) => !e37.pcb_port_id && e37.pointId)))
    return e35;
  const t2 = new Map;
  for (const n3 of e35.obstacles) {
    const e36 = n3.circuitJsonMetadata;
    if (!e36?.source_component_name || !e36.source_port_name || e36.pcb_via_id || n3.isNonPlatedHole)
      continue;
    const o4 = new Set([n3.obstacleId, `${e36.source_component_name}.${e36.source_port_name}`, ...n3.connectedTo]);
    for (const e37 of o4) {
      if (!e37)
        continue;
      const o5 = t2.get(e37);
      o5 ? o5.push(n3) : t2.set(e37, [n3]);
    }
  }
  if (t2.size === 0)
    return e35;
  let n2 = false;
  const o3 = { ...e35, connections: e35.connections.map((e36) => ({ ...e36, pointsToConnect: e36.pointsToConnect.map((o4) => {
    if (o4.pcb_port_id || !o4.pointId)
      return o4;
    const i3 = So(o4);
    return [o4.pointId, o4.port_selector, e36.name, e36.__netConnectionName, ...e36.__rootConnectionNames ?? []].some((e37) => e37 && t2.get(e37)?.some((e38) => Math.hypot(o4.x - e38.center.x, o4.y - e38.center.y) < 0.000001 && i3.some((t3) => e38.layers.includes(t3)))) ? (n2 = true, { ...o4, pcb_port_id: o4.pointId }) : o4;
  }) })) };
  return n2 ? o3 : e35;
}
var WN = (e35) => e35.circuitJsonMetadata ?? {};
var GN = ({ connections: e35, obstacles: t2 }) => new Set([...e35.flatMap((e36) => e36.pointsToConnect.flatMap((e37) => e37.pcb_port_id ? [e37.pcb_port_id] : [])), ...t2.flatMap((e36) => {
  const t3 = WN(e36).pcb_port_id;
  return t3 ? [t3] : [];
})]);
var UN = (e35) => e35.__netConnectionName ?? e35.__rootConnectionNames?.[0] ?? e35.name;
var ZN = (e35) => Array.from(new Set([e35.name, e35.__netConnectionName, ...e35.__rootConnectionNames ?? [], ...e35.pointsToConnect.flatMap((e36) => [e36.pointId, e36.pcb_port_id])])).filter((e36) => Boolean(e36));
var qN = (e35, t2) => {
  const n2 = new Map, o3 = new Set, i3 = new Map;
  for (const r3 of e35) {
    const e36 = UN(r3);
    for (const t3 of ZN(r3)) {
      const i4 = n2.get(t3);
      i4 && i4 !== e36 ? (n2.delete(t3), o3.add(t3)) : o3.has(t3) || n2.set(t3, e36);
    }
    const s2 = t2.getNetConnectedToId(r3.name);
    if (!s2)
      continue;
    const a3 = s2, c3 = i3.get(a3) ?? new Set;
    c3.add(e36), i3.set(a3, c3);
  }
  return { connMap: t2, circuitJsonSourceTraceIdBySrjDeclaredConnectionReference: n2, circuitJsonSourceTraceIdsByConnectivityNetId: i3 };
};
var JN = (e35, t2) => {
  const n2 = e35.circuitJsonSourceTraceIdBySrjDeclaredConnectionReference.get(t2);
  if (n2)
    return n2;
  const o3 = e35.connMap.getNetConnectedToId(t2);
  if (!o3)
    return;
  const i3 = e35.circuitJsonSourceTraceIdsByConnectivityNetId.get(o3);
  return i3?.size === 1 ? i3.values().next().value : undefined;
};
function QN(e35, t2, n2 = e35, o3) {
  const i3 = [], r3 = n2 === e35 ? e35.connections : [...e35.connections, ...n2.connections], s2 = n2 === e35 ? e35.obstacles : n2.obstacles, a3 = qN(r3, o3 ?? ei(n2 === e35 ? e35 : { ...n2, connections: r3 })), c3 = GN({ connections: r3, obstacles: s2 });
  if (r3.forEach((e36) => {
    const n3 = e36.pointsToConnect.map((e37) => e37.pcb_port_id).filter((e37) => Boolean(e37)), o4 = new Set(n3), r4 = (e37) => ((e38) => Array.from(new Set(e38.flatMap((e39) => e39.connectedTo))))(e37).filter((e38) => !o4.has(e38)), c4 = e36.pointsToConnect.map((e37) => e37.pointId).filter((e37) => Boolean(e37)), l3 = JN(a3, e36.name) ?? UN(e36), h2 = new Set(ZN(e36)), d2 = [], u2 = t2.find((t3) => (t3.connection_name ?? t3.connectionName) === e36.name);
    if (u2) {
      const e37 = (e38) => ("route_type" in e38) && e38.route_type === "jumper" ? e38.start : ("x" in e38) && ("y" in e38) ? { x: e38.x, y: e38.y } : { x: 0, y: 0 }, t3 = [e37(u2.route[0]), e37(u2.route[u2.route.length - 1])];
      for (const e38 of t3)
        for (const t4 of s2)
          Oe(e38, t4) <= 0 && (n3.length === 0 || t4.netIsAssignable || t4.connectedTo.some((e39) => h2.has(e39))) && d2.push(t4);
    }
    const p3 = i3.find((e37) => e37.type === "source_trace" && e37.source_trace_id === l3);
    if (p3) {
      const e37 = p3;
      e37.connected_source_port_ids = [...new Set([...e37.connected_source_port_ids, ...n3])], e37.connected_source_net_ids = [...new Set([...e37.connected_source_net_ids ?? [], ...c4, ...r4(d2)])];
    } else
      i3.push({ type: "source_trace", source_trace_id: l3, connected_source_port_ids: n3, connected_source_net_ids: r4(d2).concat(c4) });
  }), t2[0] && "type" in t2[0]) {
    const e36 = new Map(r3.map((e37) => [e37.name, e37]));
    for (const n3 of t2) {
      const t3 = [...new Set((n3.connectsTo ?? []).filter((e37) => c3.has(e37)))], o4 = new Set(t3), r4 = [...new Set((n3.connectsTo ?? []).filter((e37) => !o4.has(e37)))];
      if (t3.length === 0 && r4.length === 0)
        continue;
      const s3 = e36.get(n3.connection_name), l3 = JN(a3, n3.connection_name) ?? n3.connectsTo?.map((e37) => JN(a3, e37)).find((e37) => e37 !== undefined) ?? (s3 ? UN(s3) : n3.connection_name), h2 = i3.find((e37) => e37.type === "source_trace" && e37.source_trace_id === l3);
      h2?.type !== "source_trace" ? i3.push({ type: "source_trace", source_trace_id: l3, connected_source_port_ids: t3, connected_source_net_ids: r4 }) : (h2.connected_source_port_ids = [...new Set([...h2.connected_source_port_ids, ...t3])], h2.connected_source_net_ids = [...new Set([...h2.connected_source_net_ids ?? [], ...r4])]);
    }
  }
  return i3;
}
function KN(e35, t2, n2) {
  let o3, i3 = Number.POSITIVE_INFINITY;
  for (const r3 of t2) {
    const t3 = n2.get(r3);
    if (!t3)
      continue;
    const s2 = Math.hypot(t3.x - e35.x, t3.y - e35.y);
    s2 < i3 && (i3 = s2, o3 = r3);
  }
  return o3 ?? t2[0];
}
var eR = new Set(["top", "bottom", "inner1", "inner2", "inner3", "inner4", "inner5", "inner6", "inner7", "inner8"]);
var tR = (e35) => eR.has(e35);
function nR(e35, t2, n2, o3) {
  const i3 = JSON.stringify([t2.center.x, t2.center.y, t2.width, t2.height, t2.ccwRotationDegrees ?? 0, [...t2.layers].sort()]), r3 = o3.get(e35) ?? new Set;
  if (r3.has(i3))
    return;
  const s2 = r3.size === 0 ? e35 : `${e35}_fragment_${n2}`;
  return r3.add(i3), o3.set(e35, r3), s2;
}
function oR(e35) {
  const t2 = [], n2 = new Map, o3 = new Map, i3 = function(e36) {
    const t3 = new Map;
    for (const n3 of e36.connections)
      for (const e37 of n3.pointsToConnect)
        e37.pcb_port_id && t3.set(e37.pcb_port_id, { x: e37.x, y: e37.y });
    return t3;
  }(e35), r3 = GN(e35);
  for (const [s2, a3] of e35.obstacles.entries()) {
    if (a3.isNonPlatedHole) {
      const e36 = { type: "pcb_hole", pcb_hole_id: a3.obstacleId ?? `pcb_hole_${s2}`, x: a3.center.x, y: a3.center.y };
      if (a3.shape === "circle")
        t2.push({ ...e36, hole_shape: "circle", hole_diameter: a3.width });
      else {
        const n3 = a3.ccwRotationDegrees ?? 0;
        if (n3 % 90 != 0)
          throw new Error(`Cannot represent rotated rectangular hole ${e36.pcb_hole_id} in Circuit JSON`);
        const o4 = n3 % 180 != 0;
        t2.push({ ...e36, hole_shape: "rect", hole_width: o4 ? a3.height : a3.width, hole_height: o4 ? a3.width : a3.height });
      }
      continue;
    }
    const c3 = a3.connectedTo, l3 = WN(a3);
    if (l3.pcb_via_id || a3.isCopperPour)
      continue;
    const { source_component_name: h2, source_port_name: d2 } = l3, u2 = h2 && d2 ? a3.obstacleId ?? `${h2}.${d2}` : undefined, p3 = l3.pcb_smtpad_id ?? u2, m2 = l3.pcb_plated_hole_id, g2 = [...new Set([...l3.pcb_port_id ? [l3.pcb_port_id] : [], ...c3.filter((e36) => r3.has(e36))])];
    if (g2.length === 0) {
      for (const t3 of e35.connections)
        if (a3.netIsAssignable || ZN(t3).some((e36) => c3.includes(e36)))
          for (const e36 of t3.pointsToConnect)
            e36.pcb_port_id && Math.hypot(e36.x - a3.center.x, e36.y - a3.center.y) < 0.000001 && g2.push(e36.pcb_port_id);
    }
    const f2 = l3.pcb_port_id && i3.has(l3.pcb_port_id) ? l3.pcb_port_id : KN(a3.center, g2, i3);
    if (!p3 && !m2 && !f2)
      continue;
    const _2 = a3.layers.filter(tR);
    if (_2.length === 0)
      continue;
    const { width: y2, height: b2 } = a3, x2 = a3.center.x, v2 = a3.center.y, I2 = a3.ccwRotationDegrees;
    if (Boolean(m2) || _2.length > 1) {
      const e36 = nR(m2 ?? `pcb_plated_hole_${x2.toFixed(3)}_${v2.toFixed(3)}`, a3, s2, o3);
      if (e36 === undefined)
        continue;
      if (typeof I2 == "number" && Number.isFinite(I2)) {
        const n3 = Math.max(0.5 * Math.min(y2, b2), 0.1);
        t2.push({ type: "pcb_plated_hole", pcb_plated_hole_id: e36, shape: "rotated_pill_hole_with_rect_pad", hole_shape: "rotated_pill", pad_shape: "rect", hole_width: n3, hole_height: n3, hole_ccw_rotation: I2, rect_pad_width: y2, rect_pad_height: b2, rect_ccw_rotation: I2, hole_offset_x: 0, hole_offset_y: 0, x: x2, y: v2, layers: _2, ...f2 ? { pcb_port_id: f2 } : {} });
        continue;
      }
      if (Math.abs(y2 - b2) < 0.001) {
        t2.push({ type: "pcb_plated_hole", pcb_plated_hole_id: e36, shape: "circle", outer_diameter: Math.max(y2, b2), hole_diameter: Math.max(0.5 * Math.min(y2, b2), 0.1), x: x2, y: v2, layers: _2, ...f2 ? { pcb_port_id: f2 } : {} });
        continue;
      }
      t2.push({ type: "pcb_plated_hole", pcb_plated_hole_id: e36, shape: "circular_hole_with_rect_pad", hole_shape: "circle", hole_diameter: Math.max(0.5 * Math.min(y2, b2), 0.1), rect_pad_width: y2, rect_pad_height: b2, hole_offset_x: 0, hole_offset_y: 0, x: x2, y: v2, layers: _2, ...f2 ? { pcb_port_id: f2 } : {} });
      continue;
    }
    const S2 = nR(p3 ?? `pcb_smtpad_${x2.toFixed(3)}_${v2.toFixed(3)}`, a3, s2, n2);
    S2 !== undefined && (a3.shape !== "circle" ? typeof I2 == "number" && Number.isFinite(I2) ? t2.push({ type: "pcb_smtpad", pcb_smtpad_id: S2, layer: _2[0], shape: "rotated_rect", x: x2, y: v2, width: y2, height: b2, ccw_rotation: I2, ...f2 ? { pcb_port_id: f2 } : {} }) : t2.push({ type: "pcb_smtpad", pcb_smtpad_id: S2, layer: _2[0], shape: "rect", width: y2, height: b2, x: x2, y: v2, ...f2 ? { pcb_port_id: f2 } : {} }) : t2.push({ type: "pcb_smtpad", pcb_smtpad_id: S2, layer: _2[0], shape: "circle", radius: y2 / 2, x: x2, y: v2, ...f2 ? { pcb_port_id: f2 } : {} }));
  }
  return t2;
}
function iR(e35, t2, n2) {
  if (n2 && e35.layers !== undefined)
    return e35.layers;
  const o3 = n2 ? e35 : { from_layer: "top", to_layer: Co(t2 - 1, t2) };
  return Ky(o3, t2);
}
function rR(e35) {
  const { minX: t2, maxX: n2, minY: o3, maxY: i3 } = e35.bounds;
  return { type: "pcb_board", pcb_board_id: "__autorouting_board__", thickness: 1.6, num_layers: e35.layerCount, center: { x: (t2 + n2) / 2, y: (o3 + i3) / 2 }, width: n2 - t2, height: i3 - o3, ...e35.outline ? { outline: e35.outline, shape: "polygon" } : { shape: "rect" }, material: "fr4", min_trace_to_hole_edge_clearance: e35.minTraceToHoleEdgeClearance, min_pad_edge_to_pad_edge_clearance: e35.minPadEdgeToPadEdgeClearance, ...e35.minBoardEdgeClearance !== undefined ? { min_board_edge_clearance: e35.minBoardEdgeClearance } : {} };
}
function sR(e35, t2, n2 = {}) {
  const { minTraceWidth: o3 = 0.1, minViaDiameter: i3, minViaHoleDiameter: r3, originalSrj: s2, includeOriginalConnections: a3 = false } = n2, c3 = VN(e35), l3 = s2 ? VN(s2) : undefined, h2 = Yo(c3), d2 = i3 ?? h2.padDiameter, u2 = c3.min_via_hole_diameter ?? c3.minViaHoleDiameter, p3 = r3 ?? u2 ?? (i3 !== undefined ? 0.5 * d2 : h2.holeDiameter), m2 = [];
  m2.push(...QN(c3, t2, a3 && l3 ? l3 : c3, n2.connectivityMaps?.source)), m2.push(...function(e36) {
    const t3 = new Map;
    return e36.connections.forEach((e37) => {
      e37.pointsToConnect.forEach((e38) => {
        e38.pcb_port_id && t3.set(e38.pcb_port_id, { type: "pcb_port", pcb_port_id: e38.pcb_port_id, source_port_id: e38.pcb_port_id, x: e38.x, y: e38.y, layers: So(e38) });
      });
    }), Array.from(t3.values());
  }(a3 && l3 ? l3 : c3)), m2.push(...oR(l3 ?? c3)), m2.push(...function(e36, t3, n3 = 0.3, o4 = 0.5 * n3, i4 = false) {
    const r4 = [], s3 = new Set;
    return e36.length > 0 && ("type" in e36[0] && e36[0].type === "pcb_trace" ? e36.forEach((e37) => {
      e37.route.forEach((a4) => {
        if (a4.route_type === "via") {
          if (!tR(a4.from_layer) || !tR(a4.to_layer))
            return;
          const c4 = a4.via_diameter ?? n3, l4 = a4.via_hole_diameter ?? o4, h3 = `${a4.x},${a4.y},${a4.from_layer},${a4.to_layer}`;
          s3.has(h3) || (r4.push({ type: "pcb_via", pcb_via_id: `via_${r4.length}`, pcb_trace_id: e37.pcb_trace_id, x: a4.x, y: a4.y, outer_diameter: c4, hole_diameter: l4, layers: iR(a4, t3, i4) }), s3.add(h3));
        }
      });
    }) : e36.forEach((e37, a4) => {
      const c4 = `trace_${a4}`, l4 = e37.viaDiameter ?? n3, h3 = o4;
      for (let n4 = 1;n4 < e37.route.length; n4++) {
        const o5 = e37.route[n4 - 1], a5 = e37.route[n4];
        if (o5.z !== a5.z && Math.abs(o5.x - a5.x) < 0.01 && Math.abs(o5.y - a5.y) < 0.01) {
          const e38 = Co(o5.z, t3), n5 = Co(a5.z, t3), d3 = `${a5.x},${a5.y},${e38},${n5}`;
          s3.has(d3) || (r4.push({ type: "pcb_via", pcb_via_id: `via_${r4.length}`, pcb_trace_id: c4, x: a5.x, y: a5.y, outer_diameter: l4, hole_diameter: h3, layers: iR({ from_layer: e38, to_layer: n5 }, t3, i4) }), s3.add(d3));
        }
      }
    })), r4;
  }(t2, c3.layerCount, d2, p3, (l3 ?? c3).allowBlindAndBuriedVias === true));
  const g2 = new Set(c3.connections.flatMap(ZN)), f2 = qN(a3 && l3 ? [...c3.connections, ...l3.connections.filter((e36) => !g2.has(e36.name))] : c3.connections, n2.connectivityMaps?.route ?? ei(c3));
  return t2.length > 0 && ("type" in t2[0] && t2[0].type === "pcb_trace" ? t2.forEach((e36) => {
    const t3 = JN(f2, e36.connection_name) ?? e36.connectsTo?.map((e37) => JN(f2, e37)).find((e37) => Boolean(e37)) ?? e36.connection_name;
    m2.push(function(e37, t4) {
      return { type: "pcb_trace", pcb_trace_id: e37.pcb_trace_id, source_trace_id: t4, route: e37.route.map((e38) => {
        if (e38.route_type === "wire") {
          if (!tR(e38.layer))
            return null;
          const t5 = "start_pcb_port_id" in e38 && typeof e38.start_pcb_port_id == "string" ? e38.start_pcb_port_id : undefined, n3 = "end_pcb_port_id" in e38 && typeof e38.end_pcb_port_id == "string" ? e38.end_pcb_port_id : undefined;
          return { route_type: "wire", x: e38.x, y: e38.y, width: e38.width, layer: e38.layer, ...t5 ? { start_pcb_port_id: t5 } : {}, ...n3 ? { end_pcb_port_id: n3 } : {} };
        }
        return e38.route_type === "via" && tR(e38.from_layer) && tR(e38.to_layer) ? { route_type: "via", x: e38.x, y: e38.y, from_layer: e38.from_layer, to_layer: e38.to_layer } : null;
      }).filter((e38) => e38 !== null) };
    }(e36, t3));
  }) : t2.forEach((e36, t3) => {
    const n3 = function(e37, t4, n4, o4, i4 = 0.1) {
      const r4 = [];
      if (!e37.jumpers || e37.jumpers.length === 0)
        return [{ type: "pcb_trace", pcb_trace_id: t4, source_trace_id: n4, route: e37.route.map((t5, n5) => {
          const r5 = n5 === 0, s4 = n5 === e37.route.length - 1;
          return { route_type: "wire", x: t5.x, y: t5.y, width: t5.traceThickness ?? i4, layer: Co(t5.z, o4), ...r5 && t5.pcb_port_id ? { start_pcb_port_id: t5.pcb_port_id } : {}, ...s4 && t5.pcb_port_id ? { end_pcb_port_id: t5.pcb_port_id } : {} };
        }) }];
      const s3 = [];
      for (const t5 of e37.jumpers) {
        let n5 = -1, o5 = -1;
        for (let i5 = 0;i5 < e37.route.length; i5++) {
          const r5 = e37.route[i5];
          Math.abs(r5.x - t5.start.x) < 0.01 && Math.abs(r5.y - t5.start.y) < 0.01 && (n5 = i5), Math.abs(r5.x - t5.end.x) < 0.01 && Math.abs(r5.y - t5.end.y) < 0.01 && (o5 = i5);
        }
        n5 !== -1 && o5 !== -1 && (n5 > o5 && ([n5, o5] = [o5, n5]), s3.push({ startIdx: n5, endIdx: o5 }));
      }
      s3.sort((e38, t5) => e38.startIdx - t5.startIdx);
      let a4 = 0, c4 = 0;
      for (const { startIdx: l4, endIdx: h3 } of s3) {
        if (l4 >= a4) {
          const s4 = e37.route.slice(a4, l4 + 1);
          s4.length > 0 && (r4.push({ type: "pcb_trace", pcb_trace_id: `${t4}_${c4}`, source_trace_id: n4, route: s4.map((e38, t5) => {
            const n5 = t5 === 0 && a4 === 0;
            return { route_type: "wire", x: e38.x, y: e38.y, width: e38.traceThickness ?? i4, layer: Co(e38.z, o4), ...n5 && e38.pcb_port_id ? { start_pcb_port_id: e38.pcb_port_id } : {} };
          }) }), c4++);
        }
        a4 = h3;
      }
      if (a4 < e37.route.length) {
        const s4 = e37.route.slice(a4);
        if (s4.length > 0) {
          const e38 = true;
          r4.push({ type: "pcb_trace", pcb_trace_id: `${t4}_${c4}`, source_trace_id: n4, route: s4.map((t5, n5) => {
            const r5 = e38 && n5 === s4.length - 1;
            return { route_type: "wire", x: t5.x, y: t5.y, width: t5.traceThickness ?? i4, layer: Co(t5.z, o4), ...r5 && t5.pcb_port_id ? { end_pcb_port_id: t5.pcb_port_id } : {} };
          }) });
        }
      }
      return r4;
    }(e36, `trace_${t3}`, JN(f2, e36.connectionName) ?? e36.connectionName, c3.layerCount, o3);
    m2.push(...n3);
  })), m2;
}
var aR = (e35) => {
  const t2 = e35.filter((e36) => e36.type === "pcb_port"), n2 = e35.filter((e36) => e36.type === "pcb_smtpad"), o3 = e35.filter((e36) => e36.type === "pcb_trace");
  for (const e36 of o3)
    for (const [o4, i3] of e36.route.entries()) {
      if (i3.route_type !== "wire")
        continue;
      const r3 = o4 === 0 && !i3.start_pcb_port_id, s2 = o4 === e36.route.length - 1 && !i3.end_pcb_port_id;
      if (!r3 && !s2)
        continue;
      const a3 = t2.find((e37) => e37.layers.includes(i3.layer) && Math.hypot(e37.x - i3.x, e37.y - i3.y) < 0.01);
      let c3 = a3?.pcb_port_id;
      if (!c3) {
        const e37 = n2.find((e38) => {
          if (e38.layer !== i3.layer)
            return false;
          if (e38.shape === "rect") {
            const t3 = (i3.width || 0) / 2;
            return Math.abs(i3.x - e38.x) < e38.width / 2 + t3 && Math.abs(i3.y - e38.y) < e38.height / 2 + t3;
          }
          return e38.shape === "circle" && Math.hypot(i3.x - e38.x, i3.y - e38.y) < e38.radius;
        });
        c3 = e37?.pcb_port_id;
      }
      c3 && (r3 && (i3.start_pcb_port_id = c3), s2 && (i3.end_pcb_port_id = c3));
    }
};
var cR = new WeakMap;
var lR = (e35, t2 = {}) => {
  const n2 = t2.board ?? e35.find((e36) => e36.type === "pcb_board");
  if (!n2)
    return [];
  let o3 = cR.get(n2);
  if (!o3) {
    let e36;
    if (n2.outline?.length)
      e36 = n2.outline;
    else {
      if (!n2.center || typeof n2.width != "number" || typeof n2.height != "number")
        return [];
      e36 = [{ x: n2.center.x - n2.width / 2, y: n2.center.y - n2.height / 2 }, { x: n2.center.x + n2.width / 2, y: n2.center.y - n2.height / 2 }, { x: n2.center.x + n2.width / 2, y: n2.center.y + n2.height / 2 }, { x: n2.center.x - n2.width / 2, y: n2.center.y + n2.height / 2 }];
    }
    o3 = e36.map((t3, n3) => ({ start: t3, end: e36[(n3 + 1) % e36.length] })), cR.set(n2, o3);
  }
  const i3 = t2.margin ?? n2.min_board_edge_clearance ?? 0.2, r3 = [];
  for (const t3 of e35)
    if (t3.type === "pcb_trace")
      for (let e36 = 0;e36 < t3.route.length - 1; e36++) {
        const n3 = t3.route[e36], s2 = t3.route[e36 + 1];
        if (n3.route_type !== "wire" || s2.route_type !== "wire")
          continue;
        const a3 = n3.width ?? s2.width ?? 0.1;
        let c3 = Number.POSITIVE_INFINITY;
        for (const e37 of o3)
          c3 = Math.min(c3, we(n3, s2, e37.start, e37.end));
        const l3 = a3 / 2 + i3;
        c3 < l3 && r3.push({ type: "pcb_trace_error", error_type: "pcb_trace_error", pcb_trace_error_id: `trace_too_close_to_board_${t3.pcb_trace_id}_segment_${e36}`, message: `Trace too close to board edge (${c3.toFixed(3)}mm < ${l3.toFixed(3)}mm required, margin: ${i3}mm)`, pcb_trace_id: t3.pcb_trace_id, source_trace_id: t3.source_trace_id || "", center: { x: (n3.x + s2.x) / 2, y: (n3.y + s2.y) / 2 }, pcb_component_ids: [], pcb_port_ids: [] });
      }
  return r3;
};
var hR = 0.1;
var dR = 0.1;
var uR = {};
c(uR, { all_layers: () => fE, any_circuit_element: () => vL, any_soup_element: () => IL, any_source_component: () => aE, asset: () => qR, base_circuit_json_error: () => uT, battery_capacity: () => kR, brep_shape: () => vA, cadModelDefaultDirectionMap: () => fD, cad_cable: () => xD, cad_collision_error: () => yD, cad_component: () => _D, cad_model_axis_directions: () => gD, cad_model_formats: () => mD, cad_reference_surface: () => CD, capacitance: () => IR, circle_shape: () => YR, circuit_json_footprint_load_error: () => zk, current: () => NR, distance: () => wR, duration_ms: () => RR, experiment_type: () => LD, external_footprint_load_error: () => Lk, frequency: () => MR, getRotationBetweenPcbPin1Locations: () => wA, getSimulationReturnCurrentGridJsonSchema: () => _L, getZodPrefixedIdWithDefault: () => GR, inductance: () => SR, insertionDirectionToCanonical: () => IA, insertionDirectionToVector: () => SA, insertion_direction: () => CA, kicadAt: () => JR, kicadEffects: () => KR, kicadFont: () => QR, kicadFootprintAttributes: () => nT, kicadFootprintMetadata: () => rT, kicadFootprintModel: () => iT, kicadFootprintPad: () => oT, kicadFootprintProperties: () => tT, kicadProperty: () => eT, kicadSymbolEffects: () => cT, kicadSymbolMetadata: () => dT, kicadSymbolPinNames: () => aT, kicadSymbolPinNumbers: () => sT, kicadSymbolProperties: () => hT, kicadSymbolProperty: () => lT, layer_ref: () => yE, layer_string: () => _E, length: () => PR, manufacturing_drc_properties: () => EA, ms: () => ER, ninePointAnchor: () => UR, parseAndConvertSiUnit: () => bR, pcbRenderLayer: () => ZR, pcb_autorouting_error: () => Fk, pcb_bend: () => GO, pcb_board: () => VO, pcb_breakout_point: () => Gk, pcb_bus_length_skew_error: () => AO, pcb_bus_routing_constraint_error: () => LO, pcb_bus_routing_constraint_warning: () => BO, pcb_component: () => AA, pcb_component_invalid_layer_error: () => iD, pcb_component_missing_courtyard_warning: () => Hk, pcb_component_not_on_board_edge_error: () => oD, pcb_component_outside_board_error: () => nD, pcb_connector_not_in_accessible_orientation_warning: () => Xk, pcb_copper_pour: () => tD, pcb_copper_pour_brep: () => Kk, pcb_copper_pour_polygon: () => eD, pcb_copper_pour_rect: () => Qk, pcb_copper_text: () => ck, pcb_courtyard_circle: () => uD, pcb_courtyard_outline: () => hD, pcb_courtyard_overlap_error: () => Pk, pcb_courtyard_pill: () => pD, pcb_courtyard_polygon: () => dD, pcb_courtyard_rect: () => lD, pcb_cutout: () => kk, pcb_cutout_circle: () => Ek, pcb_cutout_path: () => Ok, pcb_cutout_polygon: () => Ak, pcb_cutout_rect: () => Tk, pcb_debug_line: () => DA, pcb_debug_object: () => zA, pcb_debug_object_base: () => OA, pcb_debug_point: () => LA, pcb_debug_rect: () => kA, pcb_fabrication_note_dimension: () => yk, pcb_fabrication_note_path: () => fk, pcb_fabrication_note_rect: () => _k, pcb_fabrication_note_text: () => gk, pcb_fabricator_extra_charge_warning: () => Wk, pcb_footprint_overlap_error: () => Ck, pcb_ground_plane: () => Uk, pcb_ground_plane_region: () => Zk, pcb_group: () => Bk, pcb_hole: () => qA, pcb_hole_circle_or_square_shape: () => XA, pcb_hole_circle_shape: () => FA, pcb_hole_oval_shape: () => VA, pcb_hole_pill_shape: () => GA, pcb_hole_rect_shape: () => $A, pcb_hole_rotated_pill_shape: () => ZA, pcb_keepout: () => wk, pcb_keepout_outline: () => Mk, pcb_keepout_overlap_warning: () => Nk, pcb_manual_edit_conflict_warning: () => $k, pcb_missing_footprint_error: () => Dk, pcb_net: () => XO, pcb_note_dimension: () => Sk, pcb_note_line: () => Ik, pcb_note_path: () => vk, pcb_note_rect: () => xk, pcb_note_text: () => bk, pcb_packing_error: () => nk, pcb_pad_pad_clearance_error: () => aD, pcb_pad_trace_clearance_error: () => cD, pcb_panel: () => ek, pcb_panelization_placement_error: () => ok, pcb_pin1_location: () => PA, pcb_placement_error: () => tk, pcb_plated_hole: () => oO, pcb_port: () => iO, pcb_port_not_connected_error: () => YO, pcb_port_not_matched_error: () => $O, pcb_preflight_routing_error: () => jk, pcb_route_hint: () => NA, pcb_route_hints: () => RA, pcb_silkscreen_circle: () => hk, pcb_silkscreen_graphic: () => pk, pcb_silkscreen_graphic_brep: () => uk, pcb_silkscreen_line: () => rk, pcb_silkscreen_oval: () => dk, pcb_silkscreen_path: () => sk, pcb_silkscreen_pill: () => mk, pcb_silkscreen_rect: () => lk, pcb_silkscreen_text: () => ak, pcb_smtpad: () => dO, pcb_smtpad_pill: () => cO, pcb_solder_paste: () => bO, pcb_soldermask_opening: () => vO, pcb_stiffener: () => KO, pcb_stiffener_polygon: () => QO, pcb_stiffener_rect: () => JO, pcb_text: () => IO, pcb_thermal_spoke: () => qk, pcb_trace: () => NO, pcb_trace_error: () => FO, pcb_trace_hint: () => ik, pcb_trace_missing_error: () => jO, pcb_trace_route_point: () => wO, pcb_trace_route_point_through_pad: () => MO, pcb_trace_route_point_via: () => PO, pcb_trace_route_point_wire: () => CO, pcb_trace_style_warning: () => TO, pcb_trace_too_long_error: () => EO, pcb_trace_too_long_warning: () => OO, pcb_trace_too_many_vias_warning: () => kO, pcb_trace_warning: () => RO, pcb_via: () => HO, pcb_via_clearance_error: () => rD, pcb_via_trace_clearance_error: () => sD, point: () => DR, point3: () => zR, point_with_bulge: () => bA, polygon_shape: () => VR, port_arrangement: () => BE, position: () => LR, position3: () => BR, rect_shape: () => XR, resistance: () => vR, ring: () => xA, rotated_rect_shape: () => HR, rotation: () => OR, route_hint_point: () => TA, schematic_arc: () => VE, schematic_box: () => OE, schematic_circle: () => HE, schematic_component: () => FE, schematic_component_overlap_warning: () => aA, schematic_component_port_arrangement_by_sides: () => zE, schematic_component_port_arrangement_by_size: () => LE, schematic_component_styling_warning: () => cA, schematic_debug_line: () => nA, schematic_debug_object: () => iA, schematic_debug_object_base: () => eA, schematic_debug_point: () => oA, schematic_debug_rect: () => tA, schematic_element_outside_sheet_warning: () => hA, schematic_error: () => QE, schematic_graphic: () => uA, schematic_group: () => pA, schematic_layout_error: () => KE, schematic_line: () => YE, schematic_manual_edit_conflict_warning: () => sA, schematic_missing_sheet_warning: () => yA, schematic_net_label: () => JE, schematic_path: () => kE, schematic_pin_styles: () => DE, schematic_port: () => qE, schematic_rect: () => XE, schematic_sheet: () => _A, schematic_sheet_size: () => fA, schematic_sheet_styling_warning: () => lA, schematic_symbol: () => $E, schematic_table: () => mA, schematic_table_cell: () => gA, schematic_text: () => ZE, schematic_text_part: () => UE, schematic_trace: () => WE, schematic_voltage_probe: () => rA, simulation_ac_current_source: () => AD, simulation_ac_sweep_current_graph: () => tL, simulation_ac_sweep_voltage_graph: () => eL, simulation_ac_voltage_source: () => ND, simulation_complex_sample: () => KD, simulation_current_probe: () => HD, simulation_current_source: () => OD, simulation_dc_current_source: () => ED, simulation_dc_operating_point_current: () => qD, simulation_dc_operating_point_voltage: () => ZD, simulation_dc_sweep_current_graph: () => QD, simulation_dc_sweep_unit: () => kD, simulation_dc_sweep_voltage_graph: () => JD, simulation_dc_voltage_source: () => wD, simulation_experiment: () => BD, simulation_op_amp: () => nL, simulation_oscilloscope_trace: () => rL, simulation_parameter_sweep: () => UD, simulation_parameter_sweep_coordinate: () => FD, simulation_parameter_type: () => WD, simulation_parameter_unit: () => DD, simulation_pcb_return_current_field: () => mL, simulation_pcb_return_current_heatmap: () => yL, simulation_pcb_return_current_marker: () => xL, simulation_pcb_return_current_result: () => hL, simulation_return_current_contact: () => aL, simulation_return_current_excitation: () => lL, simulation_return_current_field_asset: () => uL, simulation_return_current_grid_json: () => fL, simulation_return_current_image_asset: () => pL, simulation_spice_subcircuit: () => oL, simulation_switch: () => YD, simulation_terminal_port: () => cL, simulation_transient_current_graph: () => $D, simulation_transient_voltage_graph: () => jD, simulation_unknown_experiment_error: () => VD, simulation_voltage_probe: () => XD, simulation_voltage_source: () => RD, size: () => FR, source_ambiguous_port_reference: () => mE, source_board: () => pE, source_bus: () => EE, source_component_availability_warning: () => tE, source_component_base: () => mT, source_component_internal_connection: () => lE, source_component_misconfigured_error: () => rE, source_component_pins_underspecified_warning: () => CE, source_confusing_net_name_warning: () => NE, source_failed_to_create_component_error: () => UT, source_group: () => dE, source_i2c_misconfigured_error: () => iE, source_interconnect: () => oE, source_invalid_component_property_error: () => ZT, source_manually_placed_via: () => xE, source_missing_manufacturer_part_number_warning: () => KT, source_missing_property_error: () => GT, source_motor: () => CT, source_net: () => uE, source_no_ground_pin_defined_warning: () => SE, source_no_power_pin_defined_warning: () => IE, source_part_not_found_warning: () => wE, source_pcb_ground_plane: () => gE, source_pin_attributes: () => TT, source_pin_missing_trace_warning: () => QT, source_pin_must_be_connected_error: () => PE, source_port: () => cE, source_printed_part: () => IT, source_project_metadata: () => WT, source_property_ignored_warning: () => JT, source_refdes_convention_warning: () => eE, source_runtime_error: () => AE, source_simple_ammeter: () => NT, source_simple_battery: () => ET, source_simple_capacitor: () => gT, source_simple_chip: () => vT, source_simple_connector: () => BT, source_simple_connector_standards: () => zT, source_simple_crystal: () => DT, source_simple_current_source: () => MT, source_simple_diode: () => _T, source_simple_fiducial: () => yT, source_simple_fuse: () => wT, source_simple_ground: () => xT, source_simple_inductor: () => AT, source_simple_led: () => bT, source_simple_mosfet: () => XT, source_simple_op_amp: () => HT, source_simple_pin_header: () => LT, source_simple_pinout: () => FT, source_simple_potentiometer: () => kT, source_simple_power_source: () => PT, source_simple_push_button: () => OT, source_simple_resistor: () => fT, source_simple_resonator: () => jT, source_simple_switch: () => VT, source_simple_test_point: () => YT, source_simple_transistor: () => $T, source_simple_voltage_probe: () => nE, source_simple_voltage_source: () => sE, source_subassembly: () => ST, source_trace: () => hE, source_trace_not_connected_error: () => qT, source_unnamed_trace_warning: () => vE, spice_simulation_options: () => zD, standard_shape: () => WR, supplier_footprint_mismatch_warning: () => Vk, supplier_name: () => pT, time: () => TR, timestamp: () => AR, unknown_error_finding_part: () => ME, visible_layer: () => bE, voltage: () => CR, wave_shape: () => PD });
var pR = (e35) => {
  const t2 = Math.round(1000 * e35) / 1000;
  return `${Number(t2.toFixed(3))}mm`;
};
var mR = new Map([["T", 1000000000000], ["G", 1e9], ["M", 1e6], ["K", 1000], ["k", 1000], ["", 1], ["m", 0.001], ["µ", 0.000001], ["μ", 0.000001], ["u", 0.000001], ["n", 0.000000001], ["p", 0.000000000001], ["f", 0.000000000000001]]);
var gR = [...mR.keys()];
function fR(e35) {
  return mR.get(e35);
}
var _R = { Hz: { baseUnit: "Hz", variants: { MHz: 1e6, kHz: 1000, Hz: 1 } }, g: { baseUnit: "g", variants: { kg: 1000, g: 1 } }, "Ω": { baseUnit: "Ω", variants: { "mΩ": 0.001, mohm: 0.001, mOhm: 0.001, milliohm: 0.001, "Ω": 1, ohm: 1, Ohm: 1, "kΩ": 1000, "KΩ": 1000, kohm: 1000, kOhm: 1000, KOhm: 1000, Kohm: 1000, "MΩ": 1e6, Mohm: 1e6, MOhm: 1e6, megohm: 1e6, Megohm: 1e6, "GΩ": 1e9, Gohm: 1e9, GOhm: 1e9, "TΩ": 1000000000000, Tohm: 1000000000000, TOhm: 1000000000000 } }, V: { baseUnit: "V", variants: { mV: 0.001, V: 1, kV: 1000, KV: 1000, MV: 1e6, GV: 1e9, TV: 1000000000000 } }, A: { baseUnit: "A", variants: { "µA": 0.000001, "μA": 0.000001, mA: 0.001, ma: 0.001, A: 1, kA: 1000, MA: 1e6 } }, F: { baseUnit: "F", variants: { pF: 0.000000000001, nF: 0.000000001, "µF": 0.000001, "μF": 0.000001, uF: 0.000001, mF: 0.001, F: 1, kF: 1000, KF: 1000, MF: 1e6 } }, H: { baseUnit: "H", variants: { pH: 0.000000000001, nH: 0.000000001, "µH": 0.000001, "μH": 0.000001, uH: 0.000001, mH: 0.001, H: 1, kH: 1000, KH: 1000, MH: 1e6 } }, ml: { baseUnit: "ml", variants: { ml: 1, mL: 1, l: 1000, L: 1000 } }, deg: { baseUnit: "deg", variants: { rad: 180 / Math.PI } }, ms: { baseUnit: "ms", variants: { fs: 0.000000000001, ps: 0.000000001, ns: 0.000001, us: 0.001, "µs": 0.001, "μs": 0.001, ms: 1, s: 1000 } }, mm: { baseUnit: "mm", variants: { nm: 0.000001, "µm": 0.001, "μm": 0.001, um: 0.001, mm: 1, cm: 10, dm: 100, m: 1000, km: 1e6, in: 25.4, ft: 304.8, IN: 25.4, FT: 304.8, yd: 914.4, mi: 1609344, mil: 0.0254 } } };
var yR = new Set;
for (const [e35, t2] of Object.entries(_R)) {
  yR.add(e35);
  for (const e36 of Object.keys(t2.variants))
    yR.add(e36);
}
function bR(e35, t2) {
  if (e35 == null)
    return { parsedUnit: null, unitOfValue: null, value: null };
  if (typeof e35 == "string" && e35.match(/^-?[\d.]+$/))
    return { value: Number.parseFloat(e35), parsedUnit: null, unitOfValue: null };
  if (typeof e35 == "number")
    return { value: e35, parsedUnit: null, unitOfValue: null };
  if (typeof e35 == "object" && "x" in e35 && "y" in e35) {
    const n3 = bR(e35.x, t2), o4 = bR(e35.x, t2), i4 = bR(e35.y, t2);
    return o4.value === null || i4.value === null ? { parsedUnit: null, unitOfValue: null, value: null } : { parsedUnit: n3.parsedUnit, unitOfValue: n3.unitOfValue, value: { x: o4.value, y: i4.value } };
  }
  const n2 = e35.toString().split("").reverse().join(""), o3 = n2.match(/[^\d\s]+/)?.[0];
  if (!o3)
    throw new Error(`Could not determine unit: "${e35}"`);
  const i3 = o3.split("").reverse().join(""), r3 = e35.slice(0, -i3.length), s2 = fR(i3);
  if (t2 && s2 != null)
    return { parsedUnit: null, unitOfValue: t2, value: Number.parseFloat(r3) * s2 };
  if (s2 != null && !yR.has(i3))
    return { parsedUnit: null, unitOfValue: null, value: Number.parseFloat(r3) * s2 };
  const { baseUnit: a3, conversionFactor: c3 } = function(e36) {
    for (const t3 of Object.values(_R)) {
      if (e36 in t3.variants)
        return { baseUnit: t3.baseUnit, conversionFactor: t3.variants[e36] };
      for (const [n3, o4] of Object.entries(t3.variants)) {
        if (!e36.endsWith(n3))
          continue;
        const i4 = fR(e36.slice(0, -n3.length));
        if (i4 != null)
          return { baseUnit: t3.baseUnit, conversionFactor: i4 * o4 };
      }
    }
    return { baseUnit: e36, conversionFactor: 1 };
  }(i3);
  return { parsedUnit: i3, unitOfValue: a3, value: c3 * Number.parseFloat(r3) };
}
var xR = gR.filter((e35) => e35 !== "").sort((e35, t2) => t2.length - e35.length).map((e35) => e35.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|");
var vR = (new RegExp(`^([+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?)(?:(${xR}))?$`), Wa.string().or(Wa.number()).transform((e35) => bR(e35, "Ω").value));
var IR = Wa.string().or(Wa.number()).transform((e35) => bR(e35, "F").value).transform((e35) => Number.parseFloat(e35.toPrecision(12)));
var SR = Wa.string().or(Wa.number()).transform((e35) => bR(e35, "H").value);
var CR = Wa.string().or(Wa.number()).transform((e35) => bR(e35, "V").value);
var PR = Wa.string().or(Wa.number()).transform((e35) => bR(e35).value);
var MR = Wa.string().or(Wa.number()).transform((e35) => bR(e35, "Hz").value);
var wR = PR;
var NR = Wa.string().or(Wa.number()).transform((e35) => bR(e35, "A").value);
var RR = Wa.string().or(Wa.number()).transform((e35) => bR(e35).value);
var TR = RR;
var ER = RR;
var AR = Wa.string().datetime();
var OR = Wa.string().or(Wa.number()).transform((e35) => typeof e35 == "number" ? e35 : e35.endsWith("deg") ? Number.parseFloat(e35.split("deg")[0]) : e35.endsWith("rad") ? 180 * Number.parseFloat(e35.split("rad")[0]) / Math.PI : Number.parseFloat(e35));
var kR = Wa.number().or(Wa.string().endsWith("mAh")).transform((e35) => {
  if (typeof e35 == "string") {
    const t2 = e35.replace("mAh", ""), n2 = Number.parseFloat(t2);
    if (Number.isNaN(n2))
      throw new Error("Invalid capacity");
    return n2;
  }
  return e35;
}).describe("Battery capacity in mAh");
var DR = Wa.object({ x: wR, y: wR });
var LR = DR;
var zR = Wa.object({ x: wR, y: wR, z: wR });
var BR = zR;
var FR = Wa.object({ width: Wa.number(), height: Wa.number() });
var jR = wR.pipe(Wa.number().finite());
var $R = wR.pipe(Wa.number().finite().positive());
var YR = Wa.object({ shape: Wa.literal("circle"), x: jR, y: jR, radius: $R }).strict();
var XR = Wa.object({ shape: Wa.literal("rect"), x: jR, y: jR, width: $R, height: $R }).strict();
var HR = XR.extend({ shape: Wa.literal("rotated_rect"), ccw_rotation: OR.pipe(Wa.number().finite()) });
var VR = Wa.object({ shape: Wa.literal("polygon"), points: Wa.array(DR.extend({ x: jR, y: jR })).min(3).refine((e35) => {
  const t2 = e35.reduce((t3, n2, o3) => {
    const i3 = e35[(o3 + 1) % e35.length];
    return t3 + n2.x * i3.y - i3.x * n2.y;
  }, 0);
  return Number.isFinite(t2) && t2 !== 0;
}, "Polygon boundary must enclose a nonzero area") }).strict();
var WR = Wa.discriminatedUnion("shape", [YR, XR, HR, VR]);
var GR = (e35) => Wa.string().optional().default(() => `${e35}_${((e36) => {
  const t2 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  return Array.from({ length: e36 }, () => t2[Math.floor(62 * Math.random())]).join("");
})(10)}`);
var UR = Wa.enum(["top_left", "top_center", "top_right", "center_left", "center", "center_right", "bottom_left", "bottom_center", "bottom_right"]);
var ZR = Wa.enum(["top_silkscreen", "bottom_silkscreen", "top_copper", "bottom_copper", "top_soldermask", "bottom_soldermask", "top_fabrication_note", "bottom_fabrication_note", "top_user_note", "bottom_user_note", "top_courtyard", "bottom_courtyard", "inner1_copper", "inner2_copper", "inner3_copper", "inner4_copper", "inner5_copper", "inner6_copper", "inner7_copper", "inner8_copper", "edge_cuts", "drill"]);
var qR = Wa.object({ project_relative_path: Wa.string(), url: Wa.string(), mimetype: Wa.string() });
var JR = DR.extend({ rotation: OR.optional() });
var QR = Wa.object({ size: DR.optional(), thickness: wR.optional() });
var KR = Wa.object({ font: QR.optional() });
var eT = Wa.object({ value: Wa.string(), at: JR.optional(), layer: Wa.string().optional(), uuid: Wa.string().optional(), hide: Wa.boolean().optional(), effects: KR.optional() });
var tT = Wa.object({ Reference: eT.optional(), Value: eT.optional(), Datasheet: eT.optional(), Description: eT.optional() });
var nT = Wa.object({ through_hole: Wa.boolean().optional(), smd: Wa.boolean().optional(), exclude_from_pos_files: Wa.boolean().optional(), exclude_from_bom: Wa.boolean().optional() });
var oT = Wa.object({ name: Wa.string(), type: Wa.string(), shape: Wa.string().optional(), at: JR.optional(), size: DR.optional(), drill: wR.optional(), layers: Wa.array(Wa.string()).optional(), removeUnusedLayers: Wa.boolean().optional(), uuid: Wa.string().optional() });
var iT = Wa.object({ path: Wa.string(), offset: zR.optional(), scale: zR.optional(), rotate: zR.optional() });
var rT = Wa.object({ footprintName: Wa.string().optional(), version: Wa.union([Wa.number(), Wa.string()]).optional(), generator: Wa.string().optional(), generatorVersion: Wa.union([Wa.number(), Wa.string()]).optional(), layer: Wa.string().optional(), properties: tT.optional(), attributes: nT.optional(), pads: Wa.array(oT).optional(), embeddedFonts: Wa.boolean().optional(), model: iT.optional() });
var sT = Wa.object({ hide: Wa.boolean().optional() });
var aT = Wa.object({ offset: wR.optional(), hide: Wa.boolean().optional() });
var cT = Wa.object({ font: QR.optional(), justify: Wa.union([Wa.string(), Wa.array(Wa.string())]).optional(), hide: Wa.boolean().optional() });
var lT = Wa.object({ value: Wa.string(), id: Wa.union([Wa.number(), Wa.string()]).optional(), at: JR.optional(), effects: cT.optional() });
var hT = Wa.object({ Reference: lT.optional(), Value: lT.optional(), Footprint: lT.optional(), Datasheet: lT.optional(), Description: lT.optional(), ki_keywords: lT.optional(), ki_fp_filters: lT.optional() });
var dT = Wa.object({ symbolName: Wa.string().optional(), extends: Wa.string().optional(), pinNumbers: sT.optional(), pinNames: aT.optional(), excludeFromSim: Wa.boolean().optional(), inBom: Wa.boolean().optional(), onBoard: Wa.boolean().optional(), properties: hT.optional(), embeddedFonts: Wa.boolean().optional() });
var uT = Wa.object({ error_type: Wa.string(), message: Wa.string(), is_fatal: Wa.boolean().optional() });
var pT = Wa.enum(["jlcpcb", "macrofab", "pcbway", "digikey", "mouser", "lcsc"]);
var mT = Wa.object({ type: Wa.literal("source_component"), ftype: Wa.string().optional(), source_component_id: Wa.string(), name: Wa.string(), manufacturer_part_number: Wa.string().optional(), supplier_part_numbers: Wa.record(pT, Wa.array(Wa.string())).optional(), display_value: Wa.string().optional(), display_name: Wa.string().optional(), are_pins_interchangeable: Wa.boolean().optional(), internally_connected_source_port_ids: Wa.array(Wa.array(Wa.string())).optional(), source_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() });
var gT = mT.extend({ ftype: Wa.literal("simple_capacitor"), capacitance: IR, max_voltage_rating: CR.optional(), display_capacitance: Wa.string().optional(), max_decoupling_trace_length: wR.optional() });
var fT = mT.extend({ ftype: Wa.literal("simple_resistor"), resistance: vR, display_resistance: Wa.string().optional() });
var _T = mT.extend({ ftype: Wa.literal("simple_diode") });
var yT = mT.extend({ ftype: Wa.literal("simple_fiducial") });
var bT = _T.extend({ ftype: Wa.literal("simple_led"), color: Wa.string().optional(), wavelength: Wa.string().optional() });
var xT = mT.extend({ ftype: Wa.literal("simple_ground") });
var vT = mT.extend({ ftype: Wa.literal("simple_chip") });
var IT = mT.extend({ ftype: Wa.literal("printedpart"), material: Wa.enum(["pla", "petg", "nylon"]).optional(), color: Wa.string().trim().min(1).optional() });
var ST = mT.extend({ ftype: Wa.literal("subassembly") });
var CT = mT.extend({ ftype: Wa.literal("motor") });
var PT = mT.extend({ ftype: Wa.literal("simple_power_source"), voltage: CR });
var MT = mT.extend({ ftype: Wa.literal("simple_current_source"), current: NR, frequency: MR.optional(), peak_to_peak_current: NR.optional(), wave_shape: Wa.enum(["sine", "square", "triangle", "sawtooth", "dc"]).optional().default("dc"), phase: Wa.number().optional(), duty_cycle: Wa.number().min(0).max(1).optional() });
var wT = mT.extend({ ftype: Wa.literal("simple_fuse"), current_rating_amps: Wa.number().describe("Nominal current in amps the fuse is rated for"), voltage_rating_volts: Wa.number().describe("Voltage rating in volts, e.g. ±5V would be 5") });
var NT = mT.extend({ ftype: Wa.literal("simple_ammeter") });
var RT = Wa.union([Wa.number(), Wa.string().trim().regex(/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?\s*(?:[fpnumkKMGTµμ]?V?|V)?$/, "Expected a scalar voltage, optionally with SI units")]).pipe(CR).pipe(Wa.number().finite());
var TT = Wa.object({ is_input: Wa.boolean().optional(), is_output: Wa.boolean().optional(), is_bidirectional: Wa.boolean().optional(), is_passive: Wa.boolean().optional(), can_use_tri_state: Wa.boolean().optional(), is_using_tri_state: Wa.boolean().optional(), can_use_open_collector: Wa.boolean().optional(), is_using_open_collector: Wa.boolean().optional(), can_use_open_emitter: Wa.boolean().optional(), is_using_open_emitter: Wa.boolean().optional(), is_gpio: Wa.boolean().optional(), highlight_color: Wa.string().optional(), must_be_connected: Wa.boolean().optional(), provides_power: Wa.boolean().optional(), requires_power: Wa.boolean().optional(), provides_ground: Wa.boolean().optional(), requires_ground: Wa.boolean().optional(), provides_voltage: RT.optional(), requires_voltage: RT.optional(), required_voltage_tolerance: Wa.number().finite().min(0).max(1).optional(), do_not_connect: Wa.boolean().optional(), include_in_board_pinout: Wa.boolean().optional(), can_use_internal_pullup: Wa.boolean().optional(), is_using_internal_pullup: Wa.boolean().optional(), needs_external_pullup: Wa.boolean().optional(), can_use_internal_pulldown: Wa.boolean().optional(), is_using_internal_pulldown: Wa.boolean().optional(), needs_external_pulldown: Wa.boolean().optional(), can_use_open_drain: Wa.boolean().optional(), is_using_open_drain: Wa.boolean().optional(), can_use_push_pull: Wa.boolean().optional(), is_using_push_pull: Wa.boolean().optional(), should_have_decoupling_capacitor: Wa.boolean().optional(), recommended_decoupling_capacitor_capacitance: Wa.union([Wa.string(), Wa.number()]).optional(), is_configured_for_i2c_sda: Wa.boolean().optional(), is_configured_for_i2c_scl: Wa.boolean().optional(), is_configured_for_spi_mosi: Wa.boolean().optional(), is_configured_for_spi_miso: Wa.boolean().optional(), is_configured_for_spi_sck: Wa.boolean().optional(), is_configured_for_spi_cs: Wa.boolean().optional(), is_configured_for_uart_tx: Wa.boolean().optional(), is_configured_for_uart_rx: Wa.boolean().optional(), supports_i2c_sda: Wa.boolean().optional(), supports_i2c_scl: Wa.boolean().optional(), supports_spi_mosi: Wa.boolean().optional(), supports_spi_miso: Wa.boolean().optional(), supports_spi_sck: Wa.boolean().optional(), supports_spi_cs: Wa.boolean().optional(), supports_uart_tx: Wa.boolean().optional(), supports_uart_rx: Wa.boolean().optional() });
var ET = mT.extend({ ftype: Wa.literal("simple_battery"), capacity: kR });
var AT = mT.extend({ ftype: Wa.literal("simple_inductor"), inductance: SR, display_inductance: Wa.string().optional(), max_current_rating: Wa.number().optional() });
var OT = mT.extend({ ftype: Wa.literal("simple_push_button") });
var kT = mT.extend({ ftype: Wa.literal("simple_potentiometer"), max_resistance: vR, display_max_resistance: Wa.string().optional() });
var DT = mT.extend({ ftype: Wa.literal("simple_crystal"), frequency: Wa.number().describe("Frequency in Hz"), load_capacitance: Wa.number().optional().describe("Load capacitance in pF"), pin_variant: Wa.enum(["two_pin", "four_pin"]).optional() });
var LT = mT.extend({ ftype: Wa.literal("simple_pin_header"), pin_count: Wa.number(), gender: Wa.enum(["male", "female"]).optional().default("male") });
var zT = ["usb_c", "m2", "jst_sh", "jst_gh", "jst_zh", "jst_ph", "jst_xh", "jst_vh"];
var BT = mT.extend({ ftype: Wa.literal("simple_connector"), standard: Wa.enum(zT).optional(), pin_count: Wa.number().int().positive().optional() });
var FT = mT.extend({ ftype: Wa.literal("simple_pinout") });
var jT = mT.extend({ ftype: Wa.literal("simple_resonator"), load_capacitance: IR, equivalent_series_resistance: vR.optional(), frequency: MR });
var $T = mT.extend({ ftype: Wa.literal("simple_transistor"), transistor_type: Wa.enum(["npn", "pnp"]) });
var YT = mT.extend({ ftype: Wa.literal("simple_test_point"), footprint_variant: Wa.enum(["pad", "through_hole"]).optional(), pad_shape: Wa.enum(["rect", "circle"]).optional(), pad_diameter: Wa.union([Wa.number(), Wa.string()]).optional(), hole_diameter: Wa.union([Wa.number(), Wa.string()]).optional(), width: Wa.union([Wa.number(), Wa.string()]).optional(), height: Wa.union([Wa.number(), Wa.string()]).optional() });
var XT = mT.extend({ ftype: Wa.literal("simple_mosfet"), channel_type: Wa.enum(["n", "p"]), mosfet_mode: Wa.enum(["enhancement", "depletion"]) });
var HT = mT.extend({ ftype: Wa.literal("simple_op_amp") });
var VT = mT.extend({ ftype: Wa.literal("simple_switch") });
var WT = Wa.object({ type: Wa.literal("source_project_metadata"), name: Wa.string().optional(), software_used_string: Wa.string().optional(), project_url: Wa.string().optional(), source_filesystem_md5_hash: Wa.string().optional(), created_at: AR.optional() });
var GT = uT.extend({ type: Wa.literal("source_missing_property_error"), source_missing_property_error_id: GR("source_missing_property_error"), source_component_id: Wa.string(), property_name: Wa.string(), subcircuit_id: Wa.string().optional(), error_type: Wa.literal("source_missing_property_error").default("source_missing_property_error") }).describe("The source code is missing a property");
var UT = uT.extend({ type: Wa.literal("source_failed_to_create_component_error"), source_failed_to_create_component_error_id: GR("source_failed_to_create_component_error"), error_type: Wa.literal("source_failed_to_create_component_error").default("source_failed_to_create_component_error"), component_name: Wa.string().optional(), subcircuit_id: Wa.string().optional(), parent_source_component_id: Wa.string().optional(), pcb_center: Wa.object({ x: Wa.number().optional(), y: Wa.number().optional() }).optional(), schematic_center: Wa.object({ x: Wa.number().optional(), y: Wa.number().optional() }).optional() }).describe("Error emitted when a component fails to be constructed");
var ZT = uT.extend({ type: Wa.literal("source_invalid_component_property_error"), source_invalid_component_property_error_id: GR("source_invalid_component_property_error"), source_component_id: Wa.string(), property_name: Wa.string(), property_value: Wa.unknown().optional(), expected_format: Wa.string().optional(), subcircuit_id: Wa.string().optional(), error_type: Wa.literal("source_invalid_component_property_error").default("source_invalid_component_property_error") }).describe("The source component property is invalid");
var qT = uT.extend({ type: Wa.literal("source_trace_not_connected_error"), source_trace_not_connected_error_id: GR("source_trace_not_connected_error"), error_type: Wa.literal("source_trace_not_connected_error").default("source_trace_not_connected_error"), subcircuit_id: Wa.string().optional(), source_group_id: Wa.string().optional(), source_trace_id: Wa.string().optional(), connected_source_port_ids: Wa.array(Wa.string()).optional(), selectors_not_found: Wa.array(Wa.string()).optional() }).describe("Occurs when a source trace selector does not match any ports");
var JT = Wa.object({ type: Wa.literal("source_property_ignored_warning"), source_property_ignored_warning_id: GR("source_property_ignored_warning"), source_component_id: Wa.string(), property_name: Wa.string(), subcircuit_id: Wa.string().optional(), error_type: Wa.literal("source_property_ignored_warning").default("source_property_ignored_warning"), message: Wa.string() }).describe("The source property was ignored");
var QT = Wa.object({ type: Wa.literal("source_pin_missing_trace_warning"), source_pin_missing_trace_warning_id: GR("source_pin_missing_trace_warning"), warning_type: Wa.literal("source_pin_missing_trace_warning").default("source_pin_missing_trace_warning"), message: Wa.string(), source_component_id: Wa.string(), source_port_id: Wa.string(), subcircuit_id: Wa.string().optional() }).describe("Warning emitted when a source component pin is missing a trace connection");
var KT = Wa.object({ type: Wa.literal("source_missing_manufacturer_part_number_warning"), source_missing_manufacturer_part_number_warning_id: GR("source_missing_manufacturer_part_number_warning"), warning_type: Wa.literal("source_missing_manufacturer_part_number_warning").default("source_missing_manufacturer_part_number_warning"), message: Wa.string(), source_component_id: Wa.string(), standard: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe("Warning emitted when a source component is missing its manufacturer part number");
var eE = Wa.object({ type: Wa.literal("source_refdes_convention_warning"), source_refdes_convention_warning_id: GR("source_refdes_convention_warning"), warning_type: Wa.literal("source_refdes_convention_warning").default("source_refdes_convention_warning"), message: Wa.string(), source_component_id: Wa.string(), refdes: Wa.string(), source_component_ftype: Wa.string(), expected_prefixes: Wa.array(Wa.string()), actual_prefix: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe("Warning emitted when a source component reference designator does not match the component type convention");
var tE = Wa.object({ type: Wa.literal("source_component_availability_warning"), source_component_availability_warning_id: GR("source_component_availability_warning"), warning_type: Wa.literal("source_component_availability_warning").default("source_component_availability_warning"), message: Wa.string(), source_component_id: Wa.string(), subcircuit_id: Wa.string().optional(), supplier_name: pT, supplier_part_numbers: Wa.array(Wa.string()).nonempty() }).describe("Warning emitted when no supplier alternative can be confirmed in stock. Availability may be unknown or change over time.");
var nE = mT.extend({ ftype: Wa.literal("simple_voltage_probe") });
var oE = mT.extend({ ftype: Wa.literal("interconnect") });
var iE = uT.extend({ type: Wa.literal("source_i2c_misconfigured_error"), source_i2c_misconfigured_error_id: GR("source_i2c_misconfigured_error"), error_type: Wa.literal("source_i2c_misconfigured_error").default("source_i2c_misconfigured_error"), source_port_ids: Wa.array(Wa.string()) }).describe("Error emitted when incompatible I2C pins (e.g. SDA and SCL) are connected to the same net");
var rE = uT.extend({ type: Wa.literal("source_component_misconfigured_error"), source_component_misconfigured_error_id: GR("source_component_misconfigured_error"), error_type: Wa.literal("source_component_misconfigured_error").default("source_component_misconfigured_error"), source_component_ids: Wa.array(Wa.string()), source_port_ids: Wa.array(Wa.string()).optional() }).describe("Error emitted when one or more source components have an invalid or conflicting configuration");
var sE = mT.extend({ ftype: Wa.literal("simple_voltage_source"), voltage: CR, frequency: MR.optional(), peak_to_peak_voltage: CR.optional(), wave_shape: Wa.enum(["sinewave", "square", "triangle", "sawtooth"]).optional(), phase: OR.optional(), duty_cycle: Wa.number().optional().describe("Duty cycle as a fraction (0 to 1)"), pulse_delay: ER.optional(), rise_time: ER.optional(), fall_time: ER.optional(), pulse_width: ER.optional(), period: ER.optional() });
var aE = Wa.union([fT, gT, _T, yT, bT, xT, vT, IT, ST, CT, PT, MT, NT, ET, AT, OT, kT, DT, LT, BT, FT, jT, VT, $T, YT, XT, HT, wT, nE, oE, sE, WT, GT, ZT, UT, qT, JT, QT, KT, eE, tE, iE, rE]);
var cE = Wa.object({ type: Wa.literal("source_port"), pin_number: Wa.number().optional(), port_hints: Wa.array(Wa.string()).optional(), name: Wa.string(), source_port_id: Wa.string(), source_component_id: Wa.string().optional(), source_group_id: Wa.string().optional(), most_frequently_referenced_by_name: Wa.string().optional(), subcircuit_id: Wa.string().optional(), subcircuit_connectivity_map_key: Wa.string().optional() }).merge(TT);
var lE = Wa.object({ type: Wa.literal("source_component_internal_connection"), source_component_internal_connection_id: Wa.string(), source_component_id: Wa.string(), source_port_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() });
var hE = Wa.object({ type: Wa.literal("source_trace"), source_trace_id: Wa.string(), connected_source_port_ids: Wa.array(Wa.string()), connected_source_net_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional(), subcircuit_connectivity_map_key: Wa.string().optional(), max_length: Wa.number().optional(), max_via_count: Wa.number().int().nonnegative().optional(), name: Wa.string().optional(), min_trace_thickness: Wa.number().optional(), display_name: Wa.string().optional() });
var dE = Wa.object({ type: Wa.literal("source_group"), source_group_id: Wa.string(), subcircuit_id: Wa.string().optional(), parent_subcircuit_id: Wa.string().optional(), parent_source_group_id: Wa.string().optional(), is_subcircuit: Wa.boolean().optional(), show_as_schematic_box: Wa.boolean().optional(), name: Wa.string().optional(), was_automatically_named: Wa.boolean().optional() });
var uE = Wa.object({ type: Wa.literal("source_net"), source_net_id: Wa.string(), name: Wa.string(), member_source_group_ids: Wa.array(Wa.string()), is_power: Wa.boolean().optional(), is_ground: Wa.boolean().optional(), is_digital_signal: Wa.boolean().optional(), is_analog_signal: Wa.boolean().optional(), is_positive_voltage_source: Wa.boolean().optional(), trace_width: Wa.number().optional(), subcircuit_id: Wa.string().optional(), subcircuit_connectivity_map_key: Wa.string().optional() });
var pE = Wa.object({ type: Wa.literal("source_board"), source_board_id: Wa.string(), source_group_id: Wa.string(), title: Wa.string().optional() }).describe("Defines a board in the source domain");
var mE = uT.extend({ type: Wa.literal("source_ambiguous_port_reference"), source_ambiguous_port_reference_id: GR("source_ambiguous_port_reference"), error_type: Wa.literal("source_ambiguous_port_reference").default("source_ambiguous_port_reference"), source_port_id: Wa.string().optional(), source_component_id: Wa.string().optional() }).describe("Error emitted when a port hint matches multiple non-overlapping pads, making the port reference ambiguous");
var gE = Wa.object({ type: Wa.literal("source_pcb_ground_plane"), source_pcb_ground_plane_id: Wa.string(), source_group_id: Wa.string(), source_net_id: Wa.string(), subcircuit_id: Wa.string().optional() }).describe("Defines a ground plane in the source domain");
var fE = ["top", "bottom", "inner1", "inner2", "inner3", "inner4", "inner5", "inner6", "inner7", "inner8"];
var _E = Wa.enum(fE);
var yE = _E.or(Wa.object({ name: _E })).transform((e35) => typeof e35 == "string" ? e35 : e35.name);
var bE = Wa.enum(["top", "bottom"]);
var xE = Wa.object({ type: Wa.literal("source_manually_placed_via"), source_manually_placed_via_id: Wa.string(), source_group_id: Wa.string(), source_net_id: Wa.string().min(1).optional(), subcircuit_id: Wa.string().optional(), source_trace_id: Wa.string().optional() }).describe("Defines a via that is manually placed in the source domain");
var vE = Wa.object({ type: Wa.literal("source_unnamed_trace_warning"), source_unnamed_trace_warning_id: GR("source_unnamed_trace_warning"), warning_type: Wa.literal("source_unnamed_trace_warning").default("source_unnamed_trace_warning"), message: Wa.string(), source_trace_id: Wa.string(), subcircuit_id: Wa.string().optional() }).describe("Warning emitted when a source trace is missing a name");
var IE = Wa.object({ type: Wa.literal("source_no_power_pin_defined_warning"), source_no_power_pin_defined_warning_id: GR("source_no_power_pin_defined_warning"), warning_type: Wa.literal("source_no_power_pin_defined_warning").default("source_no_power_pin_defined_warning"), message: Wa.string(), source_component_id: Wa.string(), source_port_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe("Warning emitted when a chip has no source ports with requires_power=true");
var SE = Wa.object({ type: Wa.literal("source_no_ground_pin_defined_warning"), source_no_ground_pin_defined_warning_id: GR("source_no_ground_pin_defined_warning"), warning_type: Wa.literal("source_no_ground_pin_defined_warning").default("source_no_ground_pin_defined_warning"), message: Wa.string(), source_component_id: Wa.string(), source_port_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe("Warning emitted when a chip has no source ports marked as ground pins");
var CE = Wa.object({ type: Wa.literal("source_component_pins_underspecified_warning"), source_component_pins_underspecified_warning_id: GR("source_component_pins_underspecified_warning"), warning_type: Wa.literal("source_component_pins_underspecified_warning").default("source_component_pins_underspecified_warning"), message: Wa.string(), source_component_id: Wa.string(), source_port_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe("Warning emitted when all ports on a source component are underspecified");
var PE = uT.extend({ type: Wa.literal("source_pin_must_be_connected_error"), source_pin_must_be_connected_error_id: GR("source_pin_must_be_connected_error"), error_type: Wa.literal("source_pin_must_be_connected_error").default("source_pin_must_be_connected_error"), source_component_id: Wa.string(), source_port_id: Wa.string(), subcircuit_id: Wa.string().optional() }).describe("Error emitted when a pin with mustBeConnected attribute is not connected to any trace");
var ME = uT.extend({ type: Wa.literal("unknown_error_finding_part"), unknown_error_finding_part_id: GR("unknown_error_finding_part"), error_type: Wa.literal("unknown_error_finding_part").default("unknown_error_finding_part"), source_component_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe("Error emitted when an unexpected error occurs while finding a part");
var wE = Wa.object({ type: Wa.literal("source_part_not_found_warning"), source_part_not_found_warning_id: GR("source_part_not_found_warning"), warning_type: Wa.literal("source_part_not_found_warning").default("source_part_not_found_warning"), message: Wa.string(), source_component_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), supplier_name: pT.optional(), manufacturer_part_number: Wa.string().optional(), supplier_part_number: Wa.string().optional(), part_name: Wa.string().optional() }).describe("Warning emitted when a requested part can not be found");
var NE = Wa.object({ type: Wa.literal("source_confusing_net_name_warning"), source_confusing_net_name_warning_id: GR("source_confusing_net_name_warning"), warning_type: Wa.literal("source_confusing_net_name_warning").default("source_confusing_net_name_warning"), message: Wa.string(), source_net_ids: Wa.array(Wa.string()).min(2), net_name: Wa.string(), subcircuit_id: Wa.string().optional() }).describe("Warning emitted when electrically disconnected source nets share a name");
var RE = Wa.union([Wa.number().nonnegative().finite(), Wa.object({ reference: Wa.literal("longest_manhattan"), source_trace_ids: Wa.array(Wa.string()).min(1).optional(), offset: Wa.number().finite().optional() })]);
var TE = Wa.union([Wa.number().positive().finite(), Wa.object({ width_multiplier: Wa.number().positive().finite() })]);
var EE = Wa.object({ type: Wa.literal("source_bus"), source_bus_id: Wa.string(), name: Wa.string().optional(), source_trace_ids: Wa.array(Wa.string()).min(1), max_length_skew: Wa.number().nonnegative().finite().optional(), target_impedance: Wa.number().positive().finite().optional(), target_differential_impedance: Wa.number().positive().finite().optional(), differential_pair: Wa.object({ positive_source_trace_id: Wa.string(), negative_source_trace_id: Wa.string(), trace_gap: Wa.number().positive().finite().optional(), max_uncoupled_length: Wa.number().nonnegative().finite().optional() }).optional(), length_match_source_trace_ids: Wa.array(Wa.string()).min(1).optional(), min_length: RE.optional(), max_length: RE.optional(), target_length: RE.optional(), length_tolerance: Wa.number().nonnegative().finite().optional(), pcb_trace_spacing: TE.optional(), pcb_spacing_to_other_signals: TE.optional(), target_impedance_min: Wa.number().positive().finite().optional(), target_impedance_max: Wa.number().positive().finite().optional(), target_differential_impedance_min: Wa.number().positive().finite().optional(), target_differential_impedance_max: Wa.number().positive().finite().optional(), subcircuit_id: Wa.string().optional() });
var AE = uT.pick({ message: true, error_type: true }).extend({ type: Wa.literal("source_runtime_error"), source_runtime_error_id: GR("source_runtime_error"), error_type: Wa.literal("source_runtime_error").default("source_runtime_error"), phase_name: Wa.string().optional() }).describe("An unexpected runtime failure while generating or validating a circuit");
var OE = Wa.object({ type: Wa.literal("schematic_box"), schematic_sheet_id: Wa.string().optional(), schematic_component_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), width: wR, height: wR, is_dashed: Wa.boolean().default(false), x: wR, y: wR, subcircuit_id: Wa.string().optional() }).describe("Draws a box on the schematic");
var kE = Wa.object({ type: Wa.literal("schematic_path"), schematic_path_id: GR("schematic_path"), schematic_sheet_id: Wa.string().optional(), schematic_component_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), fill_color: Wa.string().optional(), is_filled: Wa.boolean().optional(), is_dashed: Wa.boolean().default(false), stroke_width: wR.nullable().optional(), stroke_color: Wa.string().optional(), dash_length: wR.optional(), dash_gap: wR.optional(), points: Wa.array(DR), subcircuit_id: Wa.string().optional() });
var DE = Wa.record(Wa.object({ left_margin: PR.optional(), right_margin: PR.optional(), top_margin: PR.optional(), bottom_margin: PR.optional() }));
var LE = Wa.object({ left_size: Wa.number(), right_size: Wa.number(), top_size: Wa.number().optional(), bottom_size: Wa.number().optional() });
var zE = Wa.object({ left_side: Wa.object({ pins: Wa.array(Wa.number()), direction: Wa.enum(["top-to-bottom", "bottom-to-top"]).optional() }).optional(), right_side: Wa.object({ pins: Wa.array(Wa.number()), direction: Wa.enum(["top-to-bottom", "bottom-to-top"]).optional() }).optional(), top_side: Wa.object({ pins: Wa.array(Wa.number()), direction: Wa.enum(["left-to-right", "right-to-left"]).optional() }).optional(), bottom_side: Wa.object({ pins: Wa.array(Wa.number()), direction: Wa.enum(["left-to-right", "right-to-left"]).optional() }).optional() });
var BE = Wa.union([LE, zE]);
var FE = Wa.object({ type: Wa.literal("schematic_component"), size: FR, center: DR, source_component_id: Wa.string().optional(), schematic_component_id: Wa.string(), schematic_sheet_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), pin_spacing: PR.optional(), pin_styles: DE.optional(), box_width: PR.optional(), symbol_name: Wa.string().optional(), port_arrangement: BE.optional(), port_labels: Wa.record(Wa.string()).optional(), symbol_display_value: Wa.string().optional(), subcircuit_id: Wa.string().optional(), schematic_group_id: Wa.string().optional(), is_schematic_group: Wa.boolean().optional(), source_group_id: Wa.string().optional(), is_box_with_pins: Wa.boolean().optional().default(true) });
var jE = Wa.object({ kicad_symbol: dT.optional() }).catchall(Wa.unknown());
var $E = Wa.object({ type: Wa.literal("schematic_symbol"), schematic_symbol_id: Wa.string(), name: Wa.string().optional(), metadata: jE.optional() }).describe("Defines a named schematic symbol that can be referenced by components.");
var YE = Wa.object({ type: Wa.literal("schematic_line"), schematic_line_id: GR("schematic_line"), schematic_sheet_id: Wa.string().optional(), schematic_component_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), x1: wR, y1: wR, x2: wR, y2: wR, stroke_width: wR.nullable().optional(), color: Wa.string().default("#000000"), is_dashed: Wa.boolean().default(false), dash_length: wR.optional(), dash_gap: wR.optional(), subcircuit_id: Wa.string().optional() }).describe("Draws a styled line on the schematic");
var XE = Wa.object({ type: Wa.literal("schematic_rect"), schematic_rect_id: GR("schematic_rect"), schematic_sheet_id: Wa.string().optional(), schematic_component_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), center: DR, width: wR, height: wR, rotation: OR.default(0), stroke_width: wR.nullable().optional(), color: Wa.string().default("#000000"), is_filled: Wa.boolean().default(false), fill_color: Wa.string().optional(), is_dashed: Wa.boolean().default(false), subcircuit_id: Wa.string().optional() }).describe("Draws a styled rectangle on the schematic");
var HE = Wa.object({ type: Wa.literal("schematic_circle"), schematic_circle_id: GR("schematic_circle"), schematic_sheet_id: Wa.string().optional(), schematic_component_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), center: DR, radius: wR, stroke_width: wR.nullable().optional(), color: Wa.string().default("#000000"), is_filled: Wa.boolean().default(false), fill_color: Wa.string().optional(), is_dashed: Wa.boolean().default(false), subcircuit_id: Wa.string().optional() }).describe("Draws a styled circle on the schematic");
var VE = Wa.object({ type: Wa.literal("schematic_arc"), schematic_arc_id: GR("schematic_arc"), schematic_sheet_id: Wa.string().optional(), schematic_component_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), center: DR, radius: wR, start_angle_degrees: OR, end_angle_degrees: OR, direction: Wa.enum(["clockwise", "counterclockwise"]).default("counterclockwise"), stroke_width: wR.nullable().optional(), color: Wa.string().default("#000000"), is_dashed: Wa.boolean().default(false), subcircuit_id: Wa.string().optional() }).describe("Draws a styled arc on the schematic");
var WE = Wa.object({ type: Wa.literal("schematic_trace"), schematic_trace_id: Wa.string(), schematic_sheet_id: Wa.string().optional(), source_trace_id: Wa.string().optional(), junctions: Wa.array(Wa.object({ x: Wa.number(), y: Wa.number() })), edges: Wa.array(Wa.object({ from: Wa.object({ x: Wa.number(), y: Wa.number() }), to: Wa.object({ x: Wa.number(), y: Wa.number() }), is_crossing: Wa.boolean().optional(), from_schematic_port_id: Wa.string().optional(), to_schematic_port_id: Wa.string().optional() })), subcircuit_id: Wa.string().optional(), subcircuit_connectivity_map_key: Wa.string().optional() });
var GE = Wa.enum(["center", "left", "right", "top", "bottom"]);
var UE = Wa.object({ text: Wa.string(), is_overlined: Wa.boolean().optional() });
var ZE = Wa.object({ type: Wa.literal("schematic_text"), schematic_sheet_id: Wa.string().optional(), schematic_component_id: Wa.string().optional(), schematic_symbol_id: Wa.string().optional(), schematic_text_id: Wa.string(), source_trace_id: Wa.string().optional(), text: Wa.string(), text_parts: Wa.array(UE).min(1).optional(), display_superscript: Wa.string().optional(), font_size: Wa.number().default(0.18), position: Wa.object({ x: wR, y: wR }), rotation: Wa.number().default(0), anchor: Wa.union([GE.describe("legacy"), UR]).default("center"), color: Wa.string().default("#000000"), subcircuit_id: Wa.string().optional() });
var qE = Wa.object({ type: Wa.literal("schematic_port"), schematic_port_id: Wa.string(), source_port_id: Wa.string(), schematic_sheet_id: Wa.string().optional(), schematic_component_id: Wa.string().optional(), center: DR, facing_direction: Wa.enum(["up", "down", "left", "right"]).optional(), distance_from_component_edge: Wa.number().optional(), side_of_component: Wa.enum(["top", "bottom", "left", "right"]).optional(), true_ccw_index: Wa.number().optional(), pin_number: Wa.number().optional(), display_pin_label: Wa.string().optional(), display_pin_label_text_parts: Wa.array(UE).min(1).optional(), display_pin_label_font_size: Wa.number().positive().finite().optional(), subcircuit_id: Wa.string().optional(), is_connected: Wa.boolean().optional(), is_internal_circuit_port: Wa.boolean().optional(), is_overlapping_internal_circuit_port: Wa.boolean().optional(), has_input_arrow: Wa.boolean().optional(), has_output_arrow: Wa.boolean().optional(), is_drawn_with_inversion_circle: Wa.boolean().optional() }).describe("Defines a port on a schematic component");
var JE = Wa.object({ type: Wa.literal("schematic_net_label"), schematic_net_label_id: GR("schematic_net_label"), schematic_sheet_id: Wa.string().optional(), schematic_trace_id: Wa.string().optional(), source_trace_id: Wa.string().optional(), source_net_id: Wa.string(), center: DR, anchor_position: DR.optional(), anchor_side: Wa.enum(["top", "bottom", "left", "right"]), text: Wa.string(), display_superscript: Wa.string().optional(), symbol_name: Wa.string().optional(), is_movable: Wa.boolean().optional(), subcircuit_id: Wa.string().optional() });
var QE = uT.extend({ type: Wa.literal("schematic_error"), schematic_error_id: Wa.string(), error_type: Wa.literal("schematic_port_not_found").default("schematic_port_not_found"), subcircuit_id: Wa.string().optional() }).describe("Defines a schematic error on the schematic");
var KE = uT.extend({ type: Wa.literal("schematic_layout_error"), schematic_layout_error_id: GR("schematic_layout_error"), error_type: Wa.literal("schematic_layout_error").default("schematic_layout_error"), source_group_id: Wa.string(), schematic_group_id: Wa.string(), subcircuit_id: Wa.string().optional() }).describe("Error emitted when schematic layout fails for a group");
var eA = Wa.object({ type: Wa.literal("schematic_debug_object"), label: Wa.string().optional(), subcircuit_id: Wa.string().optional() });
var tA = eA.extend({ shape: Wa.literal("rect"), center: DR, size: FR });
var nA = eA.extend({ shape: Wa.literal("line"), start: DR, end: DR });
var oA = eA.extend({ shape: Wa.literal("point"), center: DR });
var iA = Wa.discriminatedUnion("shape", [tA, nA, oA]);
var rA = Wa.object({ type: Wa.literal("schematic_voltage_probe"), schematic_voltage_probe_id: Wa.string(), schematic_sheet_id: Wa.string().optional(), source_component_id: Wa.string().optional(), name: Wa.string().optional(), position: DR, schematic_trace_id: Wa.string(), voltage: CR.optional(), subcircuit_id: Wa.string().optional(), color: Wa.string().optional(), label_alignment: UR.optional() }).describe("Defines a voltage probe measurement point on a schematic trace");
var sA = Wa.object({ type: Wa.literal("schematic_manual_edit_conflict_warning"), schematic_manual_edit_conflict_warning_id: GR("schematic_manual_edit_conflict_warning"), warning_type: Wa.literal("schematic_manual_edit_conflict_warning").default("schematic_manual_edit_conflict_warning"), message: Wa.string(), schematic_component_id: Wa.string(), schematic_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), source_component_id: Wa.string() }).describe("Warning emitted when a component has both manual placement and explicit schX/schY coordinates");
var aA = Wa.object({ type: Wa.literal("schematic_component_overlap_warning"), schematic_component_overlap_warning_id: GR("schematic_component_overlap_warning"), warning_type: Wa.literal("schematic_component_overlap_warning").default("schematic_component_overlap_warning"), message: Wa.string(), schematic_component_ids: Wa.tuple([Wa.string(), Wa.string()]), schematic_sheet_id: Wa.string().optional() }).describe("Warning emitted when the rendered bounds of two schematic components overlap");
var cA = Wa.object({ type: Wa.literal("schematic_component_styling_warning"), schematic_component_styling_warning_id: GR("schematic_component_styling_warning"), warning_type: Wa.literal("schematic_component_styling_warning").default("schematic_component_styling_warning"), message: Wa.string(), schematic_component_id: Wa.string(), styling_issue_type: Wa.string(), schematic_port_ids: Wa.array(Wa.string()).optional(), source_component_id: Wa.string().optional(), schematic_sheet_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe("Warning emitted when a schematic component has a visual styling issue");
var lA = Wa.object({ type: Wa.literal("schematic_sheet_styling_warning"), schematic_sheet_styling_warning_id: GR("schematic_sheet_styling_warning"), warning_type: Wa.literal("schematic_sheet_styling_warning").default("schematic_sheet_styling_warning"), message: Wa.string(), schematic_sheet_id: Wa.string(), styling_issue_type: Wa.literal("non_default_sheet_size"), subcircuit_id: Wa.string().optional() }).describe("Style warning emitted when a schematic sheet uses a non-default size");
var hA = Wa.object({ type: Wa.literal("schematic_element_outside_sheet_warning"), schematic_element_outside_sheet_warning_id: GR("schematic_element_outside_sheet_warning"), warning_type: Wa.literal("schematic_element_outside_sheet_warning").default("schematic_element_outside_sheet_warning"), message: Wa.string(), schematic_sheet_id: Wa.string(), schematic_element_type: Wa.enum(["schematic_component", "schematic_net_label", "schematic_trace"]), schematic_element_id: Wa.string() }).describe("Warning emitted when a schematic component, net label, or trace extends outside its schematic sheet");
var dA = wR.pipe(Wa.number().positive().finite());
var uA = Wa.object({ type: Wa.literal("schematic_graphic"), schematic_graphic_id: GR("schematic_graphic"), schematic_sheet_id: Wa.string().optional(), asset: qR.optional(), svg_content: Wa.string().optional(), width: dA.optional(), height: dA.optional() }).describe("References a graphic asset or inline SVG content with optional centered layout bounds on a schematic sheet").superRefine(({ asset: e35, svg_content: t2 }, n2) => {
  e35 === undefined && t2 === undefined && n2.addIssue({ code: Wa.ZodIssueCode.custom, message: "At least one of asset or svg_content is required" });
});
var pA = Wa.object({ type: Wa.literal("schematic_group"), schematic_group_id: GR("schematic_group"), schematic_sheet_id: Wa.string().optional(), source_group_id: Wa.string(), is_subcircuit: Wa.boolean().optional(), subcircuit_id: Wa.string().optional(), width: PR, height: PR, center: DR, schematic_component_ids: Wa.array(Wa.string()), show_as_schematic_box: Wa.boolean().optional(), name: Wa.string().optional(), description: Wa.string().optional() }).describe("Defines a group of components on the schematic");
var mA = Wa.object({ type: Wa.literal("schematic_table"), schematic_table_id: GR("schematic_table"), schematic_sheet_id: Wa.string().optional(), anchor_position: DR, column_widths: Wa.array(wR), row_heights: Wa.array(wR), cell_padding: wR.optional(), border_width: wR.optional(), subcircuit_id: Wa.string().optional(), schematic_component_id: Wa.string().optional(), anchor: UR.optional() }).describe("Defines a table on the schematic");
var gA = Wa.object({ type: Wa.literal("schematic_table_cell"), schematic_table_cell_id: GR("schematic_table_cell"), schematic_sheet_id: Wa.string().optional(), schematic_table_id: Wa.string(), start_row_index: Wa.number(), end_row_index: Wa.number(), start_column_index: Wa.number(), end_column_index: Wa.number(), text: Wa.string().optional(), center: DR, width: wR, height: wR, horizontal_align: Wa.enum(["left", "center", "right"]).optional(), vertical_align: Wa.enum(["top", "middle", "bottom"]).optional(), font_size: wR.optional(), subcircuit_id: Wa.string().optional() }).describe("Defines a cell within a schematic_table");
var fA = Wa.enum(["a4", "ansi_b"]);
var _A = Wa.object({ type: Wa.literal("schematic_sheet"), schematic_sheet_id: GR("schematic_sheet"), name: Wa.string().optional(), sheet_index: Wa.number().optional(), sheet_size: fA.optional(), sheet_width: Wa.number().positive().optional(), sheet_height: Wa.number().positive().optional(), subcircuit_id: Wa.string().optional(), outline_color: Wa.string().optional() }).describe("Defines a schematic sheet or page that components can be placed on");
var yA = Wa.object({ type: Wa.literal("schematic_missing_sheet_warning"), schematic_missing_sheet_warning_id: GR("schematic_missing_sheet_warning"), warning_type: Wa.literal("schematic_missing_sheet_warning").default("schematic_missing_sheet_warning"), message: Wa.string() }).describe("Circuit-wide warning emitted when a schematic has no schematic sheet. Display as a banner without attaching it to a component or drawing a target outline or leader line.");
var bA = Wa.object({ x: wR, y: wR, bulge: Wa.number().optional() });
var xA = Wa.object({ vertices: Wa.array(bA) });
var vA = Wa.object({ outer_ring: xA, inner_rings: Wa.array(xA).default([]) });
var IA = { from_left: "from_left", from_right: "from_right", from_top: "from_top", from_bottom: "from_bottom", from_above: "from_above", from_below: "from_below", from_x_neg: "from_left", from_x_pos: "from_right", from_y_pos: "from_top", from_y_neg: "from_bottom", from_z_pos: "from_above", from_z_neg: "from_below", from_front: "from_top", from_back: "from_bottom" };
var SA = { from_left: { x: -1, y: 0, z: 0 }, from_right: { x: 1, y: 0, z: 0 }, from_top: { x: 0, y: 1, z: 0 }, from_bottom: { x: 0, y: -1, z: 0 }, from_above: { x: 0, y: 0, z: 1 }, from_below: { x: 0, y: 0, z: -1 } };
var CA = Wa.enum(["from_left", "from_right", "from_top", "from_bottom", "from_above", "from_below", "from_x_neg", "from_x_pos", "from_y_pos", "from_y_neg", "from_z_pos", "from_z_neg", "from_front", "from_back"]).transform((e35) => IA[e35]).describe('The side exposing the receptacle where the cable or mating part is attached, following the 2D PCB diagram convention, not a 3D viewport frame. In project coordinate space, "from_top" is +Y, "from_bottom" -Y, "from_left" -X, "from_right" +X, "from_above" +Z and "from_below" -Z. A receptacle on the +Y edge is "from_top" even though the plug moves in -Y as it seats. Cartesian spellings such as "from_y_pos" are accepted and normalized to the named values, as are the deprecated "from_front" (now "from_top") and "from_back" (now "from_bottom").');
var PA = Wa.enum(["leftside_top", "leftside_bottom", "rightside_top", "rightside_bottom", "topside_left", "topside_right", "bottomside_left", "bottomside_right"]);
var MA = [["leftside_top", "bottomside_left", "rightside_bottom", "topside_right"], ["leftside_bottom", "bottomside_right", "rightside_top", "topside_left"]];
var wA = (e35, t2) => {
  for (const n2 of MA) {
    const o3 = n2.indexOf(e35), i3 = n2.indexOf(t2);
    if (o3 !== -1 && i3 !== -1)
      return (i3 - o3 + n2.length) % n2.length * 90;
  }
  return null;
};
var NA = Wa.object({ x: wR, y: wR, via: Wa.boolean().optional(), via_to_layer: yE.optional() });
var RA = Wa.array(NA);
var TA = Wa.object({ x: wR, y: wR, via: Wa.boolean().optional(), to_layer: yE.optional(), trace_width: wR.optional() });
var EA = Wa.object({ min_trace_width: PR.optional(), min_board_edge_clearance: PR.optional(), min_via_hole_edge_to_via_hole_edge_clearance: PR.optional(), min_plated_hole_drill_edge_to_drill_edge_clearance: PR.optional(), min_trace_to_pad_edge_clearance: PR.optional(), min_trace_to_hole_edge_clearance: PR.optional().describe("Minimum distance from a trace copper edge to a non-plated hole edge, in mm. No default is applied when omitted."), min_pad_edge_to_pad_edge_clearance: PR.optional(), min_same_net_trace_edge_to_trace_edge_clearance: PR.optional(), min_different_net_trace_edge_to_trace_edge_clearance: PR.optional(), min_via_edge_to_pad_edge_clearance: PR.optional(), min_via_hole_diameter: PR.optional(), min_via_pad_diameter: PR.optional() });
var AA = Wa.object({ type: Wa.literal("pcb_component"), pcb_component_id: GR("pcb_component"), source_component_id: Wa.string(), center: DR, layer: yE, rotation: OR, display_offset_x: Wa.string().optional().describe("How to display the x offset for this part, usually corresponding with how the user specified it"), display_offset_y: Wa.string().optional().describe("How to display the y offset for this part, usually corresponding with how the user specified it"), width: PR, height: PR, do_not_place: Wa.boolean().optional(), is_allowed_to_be_off_board: Wa.boolean().optional(), subcircuit_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), position_mode: Wa.enum(["packed", "relative_to_group_anchor", "relative_to_another_component", "none"]).optional(), anchor_position: DR.optional(), anchor_alignment: UR.optional(), positioned_relative_to_pcb_group_id: Wa.string().optional(), positioned_relative_to_pcb_board_id: Wa.string().optional(), cable_insertion_center: DR.optional(), insertion_direction: CA.optional(), pin1_location: PA.optional().describe("Location of pin 1 on the unrotated, top-view component footprint"), supplier_pin1_location_map: Wa.record(pT, PA).optional().describe("Pin 1 location for each supplier's unrotated, top-view footprint"), metadata: Wa.object({ kicad_footprint: rT.optional() }).optional(), obstructs_within_bounds: Wa.boolean().default(true).describe("Does this component take up all the space within its bounds on a layer. This is generally true except for when separated pin headers are being represented by a single component (in which case, chips can be placed between the pin headers) or for tall modules where chips fit underneath") }).describe("Defines a component on the PCB");
var OA = Wa.object({ type: Wa.literal("pcb_debug_object"), pcb_debug_object_id: GR("pcb_debug_object"), label: Wa.string().optional(), subcircuit_id: Wa.string().optional() });
var kA = OA.extend({ shape: Wa.literal("rect"), center: DR, size: FR });
var DA = OA.extend({ shape: Wa.literal("line"), start: DR, end: DR });
var LA = OA.extend({ shape: Wa.literal("point"), center: DR });
var zA = Wa.discriminatedUnion("shape", [kA, DA, LA]);
var BA = Wa.object({ type: Wa.literal("pcb_hole"), pcb_hole_id: GR("pcb_hole"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), pcb_component_id: Wa.string().optional(), hole_shape: Wa.literal("circle"), hole_diameter: Wa.number(), x: wR, y: wR, is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });
var FA = BA.describe("Defines a circular hole on the PCB");
var jA = Wa.object({ type: Wa.literal("pcb_hole"), pcb_hole_id: GR("pcb_hole"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), pcb_component_id: Wa.string().optional(), hole_shape: Wa.literal("rect"), hole_width: Wa.number(), hole_height: Wa.number(), x: wR, y: wR, is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });
var $A = jA.describe("Defines a rectangular (square-capable) hole on the PCB. Use equal width/height for square.");
var YA = Wa.object({ type: Wa.literal("pcb_hole"), pcb_hole_id: GR("pcb_hole"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), pcb_component_id: Wa.string().optional(), hole_shape: Wa.enum(["circle", "square"]), hole_diameter: Wa.number(), x: wR, y: wR, is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });
var XA = YA.describe("Defines a circular or square hole on the PCB");
var HA = Wa.object({ type: Wa.literal("pcb_hole"), pcb_hole_id: GR("pcb_hole"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), pcb_component_id: Wa.string().optional(), hole_shape: Wa.literal("oval"), hole_width: Wa.number(), hole_height: Wa.number(), x: wR, y: wR, is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });
var VA = HA.describe("Defines an oval hole on the PCB");
var WA = Wa.object({ type: Wa.literal("pcb_hole"), pcb_hole_id: GR("pcb_hole"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), pcb_component_id: Wa.string().optional(), hole_shape: Wa.literal("pill"), hole_width: Wa.number(), hole_height: Wa.number(), x: wR, y: wR, is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });
var GA = WA.describe("Defines a pill-shaped hole on the PCB");
var UA = Wa.object({ type: Wa.literal("pcb_hole"), pcb_hole_id: GR("pcb_hole"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), pcb_component_id: Wa.string().optional(), hole_shape: Wa.literal("rotated_pill"), hole_width: Wa.number(), hole_height: Wa.number(), x: wR, y: wR, ccw_rotation: OR, is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional() });
var ZA = UA.describe("Defines a rotated pill-shaped hole on the PCB");
var qA = YA.or(HA).or(WA).or(UA).or(BA).or(jA);
var JA = Wa.object({ type: Wa.literal("pcb_plated_hole"), shape: Wa.literal("circle"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), outer_diameter: Wa.number(), hole_diameter: Wa.number(), is_covered_with_solder_mask: Wa.boolean().optional(), x: wR, y: wR, layers: Wa.array(yE), port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), pcb_plated_hole_id: GR("pcb_plated_hole"), soldermask_margin: Wa.number().optional() });
var QA = Wa.object({ type: Wa.literal("pcb_plated_hole"), shape: Wa.enum(["oval", "pill"]), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), outer_width: Wa.number(), outer_height: Wa.number(), hole_width: Wa.number(), hole_height: Wa.number(), is_covered_with_solder_mask: Wa.boolean().optional(), x: wR, y: wR, ccw_rotation: OR, layers: Wa.array(yE), port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), pcb_plated_hole_id: GR("pcb_plated_hole"), soldermask_margin: Wa.number().optional() });
var KA = Wa.object({ type: Wa.literal("pcb_plated_hole"), shape: Wa.literal("circular_hole_with_rect_pad"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), hole_shape: Wa.literal("circle"), pad_shape: Wa.literal("rect"), hole_diameter: Wa.number(), rect_pad_width: Wa.number(), rect_pad_height: Wa.number(), rect_border_radius: Wa.number().optional(), hole_offset_x: wR.default(0), hole_offset_y: wR.default(0), is_covered_with_solder_mask: Wa.boolean().optional(), x: wR, y: wR, layers: Wa.array(yE), port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), pcb_plated_hole_id: GR("pcb_plated_hole"), soldermask_margin: Wa.number().optional(), rect_ccw_rotation: OR.optional() });
var eO = Wa.object({ type: Wa.literal("pcb_plated_hole"), shape: Wa.literal("pill_hole_with_rect_pad"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), hole_shape: Wa.literal("pill"), pad_shape: Wa.literal("rect"), hole_width: Wa.number(), hole_height: Wa.number(), rect_pad_width: Wa.number(), rect_pad_height: Wa.number(), rect_border_radius: Wa.number().optional(), hole_offset_x: wR.default(0), hole_offset_y: wR.default(0), is_covered_with_solder_mask: Wa.boolean().optional(), x: wR, y: wR, layers: Wa.array(yE), port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), pcb_plated_hole_id: GR("pcb_plated_hole"), soldermask_margin: Wa.number().optional() });
var tO = Wa.object({ type: Wa.literal("pcb_plated_hole"), shape: Wa.literal("rotated_pill_hole_with_rect_pad"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), hole_shape: Wa.literal("rotated_pill"), pad_shape: Wa.literal("rect"), hole_width: Wa.number(), hole_height: Wa.number(), hole_ccw_rotation: OR, rect_pad_width: Wa.number(), rect_pad_height: Wa.number(), rect_border_radius: Wa.number().optional(), rect_ccw_rotation: OR, hole_offset_x: wR.default(0), hole_offset_y: wR.default(0), is_covered_with_solder_mask: Wa.boolean().optional(), x: wR, y: wR, layers: Wa.array(yE), port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), pcb_plated_hole_id: GR("pcb_plated_hole"), soldermask_margin: Wa.number().optional() });
var nO = Wa.object({ type: Wa.literal("pcb_plated_hole"), shape: Wa.literal("hole_with_polygon_pad"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), hole_shape: Wa.enum(["circle", "oval", "pill", "rotated_pill"]), hole_diameter: Wa.number().optional(), hole_width: Wa.number().optional(), hole_height: Wa.number().optional(), pad_outline: Wa.array(Wa.object({ x: wR, y: wR })).min(3), hole_offset_x: wR.default(0), hole_offset_y: wR.default(0), is_covered_with_solder_mask: Wa.boolean().optional(), x: wR, y: wR, layers: Wa.array(yE), port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), pcb_plated_hole_id: GR("pcb_plated_hole"), soldermask_margin: Wa.number().optional(), ccw_rotation: OR.optional() });
var oO = Wa.union([JA, QA, KA, eO, tO, nO]);
var iO = Wa.object({ type: Wa.literal("pcb_port"), pcb_port_id: GR("pcb_port"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), source_port_id: Wa.string(), pcb_component_id: Wa.string().optional(), x: wR, y: wR, layers: Wa.array(yE), is_board_pinout: Wa.boolean().optional() }).describe("Defines a port on the PCB");
var rO = Wa.object({ type: Wa.literal("pcb_smtpad"), shape: Wa.literal("circle"), pcb_smtpad_id: GR("pcb_smtpad"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: wR, y: wR, radius: Wa.number(), layer: yE, port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional(), solderpaste_margin: Wa.number().optional() });
var sO = Wa.object({ type: Wa.literal("pcb_smtpad"), shape: Wa.literal("rect"), pcb_smtpad_id: GR("pcb_smtpad"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: wR, y: wR, width: Wa.number(), height: Wa.number(), rect_border_radius: Wa.number().optional(), corner_radius: Wa.number().optional(), layer: yE, port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional(), soldermask_margin_left: Wa.number().optional(), soldermask_margin_top: Wa.number().optional(), soldermask_margin_right: Wa.number().optional(), soldermask_margin_bottom: Wa.number().optional(), solderpaste_margin: Wa.number().optional() });
var aO = Wa.object({ type: Wa.literal("pcb_smtpad"), shape: Wa.literal("rotated_rect"), pcb_smtpad_id: GR("pcb_smtpad"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: wR, y: wR, width: Wa.number(), height: Wa.number(), rect_border_radius: Wa.number().optional(), corner_radius: Wa.number().optional(), ccw_rotation: OR, layer: yE, port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional(), soldermask_margin_left: Wa.number().optional(), soldermask_margin_top: Wa.number().optional(), soldermask_margin_right: Wa.number().optional(), soldermask_margin_bottom: Wa.number().optional(), solderpaste_margin: Wa.number().optional() });
var cO = Wa.object({ type: Wa.literal("pcb_smtpad"), shape: Wa.literal("pill"), pcb_smtpad_id: GR("pcb_smtpad"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: wR, y: wR, width: Wa.number(), height: Wa.number(), radius: Wa.number(), layer: yE, port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional(), solderpaste_margin: Wa.number().optional() });
var lO = Wa.object({ type: Wa.literal("pcb_smtpad"), shape: Wa.literal("rotated_pill"), pcb_smtpad_id: GR("pcb_smtpad"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: wR, y: wR, width: Wa.number(), height: Wa.number(), radius: Wa.number(), ccw_rotation: OR, layer: yE, port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional(), solderpaste_margin: Wa.number().optional() });
var hO = Wa.object({ type: Wa.literal("pcb_smtpad"), shape: Wa.literal("polygon"), pcb_smtpad_id: GR("pcb_smtpad"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), points: Wa.array(DR), layer: yE, port_hints: Wa.array(Wa.string()).optional(), pcb_component_id: Wa.string().optional(), pcb_port_id: Wa.string().optional(), is_covered_with_solder_mask: Wa.boolean().optional(), soldermask_margin: Wa.number().optional(), solderpaste_margin: Wa.number().optional() });
var dO = Wa.discriminatedUnion("shape", [rO, sO, aO, lO, cO, hO]).describe("Defines an SMT pad on the PCB");
var uO = Wa.object({ type: Wa.literal("pcb_solder_paste"), shape: Wa.literal("circle"), pcb_solder_paste_id: GR("pcb_solder_paste"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: wR, y: wR, radius: Wa.number(), layer: yE, pcb_component_id: Wa.string().optional(), pcb_smtpad_id: Wa.string().optional() });
var pO = Wa.object({ type: Wa.literal("pcb_solder_paste"), shape: Wa.literal("rect"), pcb_solder_paste_id: GR("pcb_solder_paste"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: wR, y: wR, width: Wa.number(), height: Wa.number(), layer: yE, pcb_component_id: Wa.string().optional(), pcb_smtpad_id: Wa.string().optional() });
var mO = Wa.object({ type: Wa.literal("pcb_solder_paste"), shape: Wa.literal("pill"), pcb_solder_paste_id: GR("pcb_solder_paste"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: wR, y: wR, width: Wa.number(), height: Wa.number(), radius: Wa.number(), layer: yE, pcb_component_id: Wa.string().optional(), pcb_smtpad_id: Wa.string().optional() });
var gO = Wa.object({ type: Wa.literal("pcb_solder_paste"), shape: Wa.literal("rotated_rect"), pcb_solder_paste_id: GR("pcb_solder_paste"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: wR, y: wR, width: Wa.number(), height: Wa.number(), ccw_rotation: wR, layer: yE, pcb_component_id: Wa.string().optional(), pcb_smtpad_id: Wa.string().optional() });
var fO = Wa.object({ type: Wa.literal("pcb_solder_paste"), shape: Wa.literal("rotated_pill"), pcb_solder_paste_id: GR("pcb_solder_paste"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: wR, y: wR, width: Wa.number(), height: Wa.number(), radius: Wa.number(), ccw_rotation: OR, layer: yE, pcb_component_id: Wa.string().optional(), pcb_smtpad_id: Wa.string().optional() });
var _O = Wa.object({ type: Wa.literal("pcb_solder_paste"), shape: Wa.literal("oval"), pcb_solder_paste_id: GR("pcb_solder_paste"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), x: wR, y: wR, width: Wa.number(), height: Wa.number(), layer: yE, pcb_component_id: Wa.string().optional(), pcb_smtpad_id: Wa.string().optional() });
var yO = VR.extend({ type: Wa.literal("pcb_solder_paste"), pcb_solder_paste_id: GR("pcb_solder_paste"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), holes: Wa.array(VR.shape.points).optional(), layer: yE, pcb_component_id: Wa.string().optional(), pcb_smtpad_id: Wa.string().optional() });
var bO = Wa.union([uO, pO, mO, gO, fO, _O, yO]).describe("Defines solderpaste on the PCB");
var xO = Wa.object({ type: Wa.literal("pcb_soldermask_opening"), pcb_soldermask_opening_id: GR("pcb_soldermask_opening"), layer: yE.pipe(bE), pcb_component_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() });
var vO = Wa.discriminatedUnion("shape", [YR.extend(xO.shape), XR.extend(xO.shape), HR.extend(xO.shape), VR.extend(xO.shape)]).describe("An explicit opening in top or bottom solder mask or flex coverlay, independent of pads. Removes mask without adding copper or solder paste.");
var IO = Wa.object({ type: Wa.literal("pcb_text"), pcb_text_id: GR("pcb_text"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), text: Wa.string(), center: DR, layer: yE, width: PR, height: PR, lines: Wa.number(), align: Wa.enum(["bottom-left"]) }).describe("Defines text on the PCB");
var SO = wR.pipe(Wa.number().finite().positive());
var CO = Wa.object({ route_type: Wa.literal("wire"), x: wR, y: wR, width: wR, start_width: SO.optional(), end_width: SO.optional(), width_interpolation_mode: Wa.enum(["linear", "quadratic"]).optional(), copper_pour_id: Wa.string().optional(), is_inside_copper_pour: Wa.boolean().optional(), start_pcb_port_id: Wa.string().optional(), end_pcb_port_id: Wa.string().optional(), layer: yE }).superRefine((e35, t2) => {
  const n2 = [e35.start_width, e35.end_width, e35.width_interpolation_mode].filter((e36) => e36 !== undefined).length;
  n2 !== 0 && (n2 !== 3 && t2.addIssue({ code: Wa.ZodIssueCode.custom, message: "Wire taper requires start_width, end_width and width_interpolation_mode together" }), e35.width !== e35.start_width && t2.addIssue({ code: Wa.ZodIssueCode.custom, path: ["start_width"], message: "start_width must equal width" }), Number.isFinite(e35.x) && Number.isFinite(e35.y) || t2.addIssue({ code: Wa.ZodIssueCode.custom, message: "Tapered wire coordinates must be finite" }));
});
var PO = Wa.object({ route_type: Wa.literal("via"), x: wR, y: wR, copper_pour_id: Wa.string().optional(), is_inside_copper_pour: Wa.boolean().optional(), hole_diameter: wR.optional(), outer_diameter: wR.optional(), tented_on_top: Wa.boolean().optional(), tented_on_bottom: Wa.boolean().optional(), from_layer: yE, to_layer: yE });
var MO = Wa.object({ route_type: Wa.literal("through_pad"), start: DR, end: DR, width: wR, start_layer: yE, end_layer: yE, pcb_smtpad_id: Wa.string().optional(), pcb_plated_hole_id: Wa.string().optional() });
var wO = Wa.union([CO, PO, MO]);
var NO = Wa.object({ type: Wa.literal("pcb_trace"), source_trace_id: Wa.string().optional(), pcb_component_id: Wa.string().optional(), pcb_trace_id: GR("pcb_trace"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), route_thickness_mode: Wa.enum(["constant", "interpolated"]).default("constant").optional(), route_order_index: Wa.number().optional(), should_round_corners: Wa.boolean().optional(), trace_length: Wa.number().optional(), is_antenna_trace: Wa.boolean().optional(), highlight_color: Wa.string().optional(), route: Wa.array(wO).superRefine((e35, t2) => {
  for (const [n2, o3] of e35.entries()) {
    if (o3.route_type !== "wire" || o3.width_interpolation_mode === undefined)
      continue;
    const i3 = e35[n2 + 1], r3 = i3?.route_type === "through_pad" ? i3.start : i3, s2 = i3?.route_type === "wire" ? i3.layer : i3?.route_type === "via" ? i3.from_layer : i3?.start_layer, a3 = r3 ? Math.hypot(r3.x - o3.x, r3.y - o3.y) : NaN;
    (!Number.isFinite(a3) || a3 <= 0 || s2 !== o3.layer) && t2.addIssue({ code: Wa.ZodIssueCode.custom, path: [n2], message: "Tapered wire must lead to a distinct finite next point on the same layer" });
  }
}) }).describe("Defines a trace on the PCB");
var RO = Wa.object({ type: Wa.literal("pcb_trace_warning"), pcb_trace_warning_id: GR("pcb_trace_warning"), warning_type: Wa.literal("pcb_trace_warning").default("pcb_trace_warning"), message: Wa.string(), center: DR.optional(), pcb_trace_id: Wa.string(), source_trace_id: Wa.string(), pcb_component_ids: Wa.array(Wa.string()), pcb_port_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe("Defines a trace warning on the PCB");
var TO = Wa.object({ type: Wa.literal("pcb_trace_style_warning"), pcb_trace_style_warning_id: GR("pcb_trace_style_warning"), warning_type: Wa.literal("pcb_trace_style_warning").default("pcb_trace_style_warning"), message: Wa.string(), styling_issue_type: Wa.literal("long_segment_at_odd_angle"), pcb_trace_id: Wa.string(), source_trace_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), layer: yE, start_route_index: Wa.number().int().nonnegative(), end_route_index: Wa.number().int().nonnegative(), segment_start: DR, segment_end: DR, center: DR, segment_length: wR, minimum_segment_length: wR, angle_degrees: Wa.number().min(0).lt(360), nearest_allowed_angle_degrees: Wa.number().min(0).lt(360).multipleOf(45), angle_deviation_degrees: Wa.number().min(0).max(22.5), angle_tolerance_degrees: Wa.number().min(0).lt(22.5) }).describe("Warning for a long PCB trace segment whose direction deviates from a multiple of 45 degrees");
var EO = Wa.object({ type: Wa.literal("pcb_trace_too_long_error"), pcb_trace_too_long_error_id: GR("pcb_trace_too_long_error"), error_type: Wa.literal("pcb_trace_too_long_error").default("pcb_trace_too_long_error"), message: Wa.string(), pcb_trace_id: Wa.string(), source_net_id: Wa.string().optional(), source_trace_id: Wa.string().optional(), actual_trace_length: wR, maximum_trace_length: wR, subcircuit_id: Wa.string().optional() }).describe("Error emitted when a PCB trace is longer than its maximum allowed length");
var AO = uT.extend({ type: Wa.literal("pcb_bus_length_skew_error"), pcb_bus_length_skew_error_id: GR("pcb_bus_length_skew_error"), error_type: Wa.literal("pcb_bus_length_skew_error").default("pcb_bus_length_skew_error"), source_bus_id: Wa.string(), source_trace_ids: Wa.array(Wa.string()), pcb_trace_ids: Wa.array(Wa.string()), actual_length_skew: Wa.number().nonnegative().finite(), maximum_length_skew: Wa.number().nonnegative().finite(), subcircuit_id: Wa.string().optional() });
var OO = Wa.object({ type: Wa.literal("pcb_trace_too_long_warning"), pcb_trace_too_long_warning_id: GR("pcb_trace_too_long_warning"), warning_type: Wa.literal("pcb_trace_too_long_warning").default("pcb_trace_too_long_warning"), message: Wa.string(), pcb_trace_id: Wa.string(), source_net_id: Wa.string().optional(), source_trace_id: Wa.string().optional(), actual_trace_length: wR, maximum_trace_length: wR, subcircuit_id: Wa.string().optional() }).describe("Warning emitted when a PCB trace is longer than its maximum allowed length");
var kO = Wa.object({ type: Wa.literal("pcb_trace_too_many_vias_warning"), pcb_trace_too_many_vias_warning_id: GR("pcb_trace_too_many_vias_warning"), warning_type: Wa.literal("pcb_trace_too_many_vias_warning").default("pcb_trace_too_many_vias_warning"), message: Wa.string(), pcb_trace_id: Wa.string(), source_net_id: Wa.string().optional(), source_trace_id: Wa.string().optional(), actual_via_count: Wa.number().int().nonnegative(), maximum_via_count: Wa.number().int().nonnegative(), subcircuit_id: Wa.string().optional() }).describe("Warning emitted when a PCB trace has more vias than its maximum allowed count");
var DO = uT.extend({ type: Wa.literal("pcb_bus_routing_constraint_error"), pcb_bus_routing_constraint_error_id: GR("pcb_bus_routing_constraint_error"), error_type: Wa.literal("pcb_bus_routing_constraint_error").default("pcb_bus_routing_constraint_error"), source_bus_id: Wa.string(), source_trace_ids: Wa.array(Wa.string()).min(1), pcb_trace_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() });
var LO = Wa.discriminatedUnion("routing_rule", [DO.extend({ routing_rule: Wa.literal("length_skew"), actual_length_skew: Wa.number().nonnegative().finite(), maximum_length_skew: Wa.number().nonnegative().finite() }), DO.extend({ routing_rule: Wa.literal("min_length"), actual_trace_length: Wa.number().nonnegative().finite(), minimum_trace_length: Wa.number().finite() }), DO.extend({ routing_rule: Wa.literal("max_length"), actual_trace_length: Wa.number().nonnegative().finite(), maximum_trace_length: Wa.number().finite() }), DO.extend({ routing_rule: Wa.literal("target_length"), actual_trace_length: Wa.number().nonnegative().finite(), target_trace_length: Wa.number().finite(), length_tolerance: Wa.number().nonnegative().finite() }), DO.extend({ routing_rule: Wa.literal("pcb_trace_spacing"), other_pcb_trace_id: Wa.string(), other_source_trace_id: Wa.string().optional(), actual_centerline_spacing: Wa.number().nonnegative().finite(), minimum_centerline_spacing: Wa.number().positive().finite() }), DO.extend({ routing_rule: Wa.literal("pcb_spacing_to_other_signals"), other_pcb_trace_id: Wa.string(), other_source_trace_id: Wa.string().optional(), actual_centerline_spacing: Wa.number().nonnegative().finite(), minimum_centerline_spacing: Wa.number().positive().finite() }), DO.extend({ routing_rule: Wa.literal("impedance_target"), target_impedance: Wa.number().positive().finite(), minimum_impedance: Wa.number().positive().finite().optional(), maximum_impedance: Wa.number().positive().finite().optional() })]).superRefine((e35, t2) => {
  e35.routing_rule === "impedance_target" && (e35.minimum_impedance === undefined && e35.maximum_impedance === undefined && t2.addIssue({ code: Wa.ZodIssueCode.custom, path: ["minimum_impedance"], message: "Provide an impedance bound" }), e35.minimum_impedance !== undefined && e35.maximum_impedance !== undefined && e35.minimum_impedance > e35.maximum_impedance && t2.addIssue({ code: Wa.ZodIssueCode.custom, path: ["maximum_impedance"], message: "Impedance bounds must be ordered" }));
}).describe("A declared bus or differential-pair routing constraint is violated.");
var zO = Wa.object({ type: Wa.literal("pcb_bus_routing_constraint_warning"), pcb_bus_routing_constraint_warning_id: GR("pcb_bus_routing_constraint_warning"), warning_type: Wa.literal("pcb_bus_routing_constraint_warning").default("pcb_bus_routing_constraint_warning"), source_bus_id: Wa.string(), source_trace_ids: Wa.array(Wa.string()).min(1), pcb_trace_ids: Wa.array(Wa.string()), message: Wa.string(), subcircuit_id: Wa.string().optional() }).describe("A declared bus or pair constraint could not be verified; this is not a pass.");
var BO = Wa.discriminatedUnion("routing_rule", [zO.extend({ routing_rule: Wa.literal("route_geometry") }), zO.extend({ routing_rule: Wa.literal("reference_geometry") }), zO.extend({ routing_rule: Wa.literal("spacing_geometry") }), zO.extend({ routing_rule: Wa.literal("target_length") }), zO.extend({ routing_rule: Wa.literal("physical_impedance") })]);
var FO = uT.extend({ type: Wa.literal("pcb_trace_error"), pcb_trace_error_id: GR("pcb_trace_error"), error_type: Wa.literal("pcb_trace_error").default("pcb_trace_error"), center: DR.optional(), pcb_trace_id: Wa.string(), source_trace_id: Wa.string(), pcb_component_ids: Wa.array(Wa.string()), pcb_port_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe("Defines a trace error on the PCB");
var jO = uT.extend({ type: Wa.literal("pcb_trace_missing_error"), pcb_trace_missing_error_id: GR("pcb_trace_missing_error"), error_type: Wa.literal("pcb_trace_missing_error").default("pcb_trace_missing_error"), center: DR.optional(), source_trace_id: Wa.string(), pcb_component_ids: Wa.array(Wa.string()), pcb_port_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe("Defines an error when a source trace has no corresponding PCB trace");
var $O = uT.extend({ type: Wa.literal("pcb_port_not_matched_error"), pcb_error_id: GR("pcb_error"), error_type: Wa.literal("pcb_port_not_matched_error").default("pcb_port_not_matched_error"), pcb_component_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe("Defines a trace error on the PCB where a port is not matched");
var YO = uT.extend({ type: Wa.literal("pcb_port_not_connected_error"), pcb_port_not_connected_error_id: GR("pcb_port_not_connected_error"), error_type: Wa.literal("pcb_port_not_connected_error").default("pcb_port_not_connected_error"), pcb_port_ids: Wa.array(Wa.string()), pcb_component_ids: Wa.array(Wa.string()), subcircuit_id: Wa.string().optional() }).describe("Defines an error when a pcb port is not connected to any trace");
var XO = Wa.object({ type: Wa.literal("pcb_net"), pcb_net_id: GR("pcb_net"), source_net_id: Wa.string().optional(), highlight_color: Wa.string().optional() }).describe("Defines a net on the PCB");
var HO = Wa.object({ type: Wa.literal("pcb_via"), pcb_via_id: GR("pcb_via"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), subcircuit_connectivity_map_key: Wa.string().optional(), x: wR, y: wR, outer_diameter: wR.default("0.6mm"), hole_diameter: wR.default("0.25mm"), topmost_drill_layer: yE.optional(), bottommost_drill_layer: yE.optional(), through_hole: Wa.boolean().optional(), from_layer: yE.optional(), to_layer: yE.optional(), layers: Wa.array(yE), pcb_port_ids: Wa.array(Wa.string()).optional(), pcb_trace_id: Wa.string().optional(), source_trace_id: Wa.string().optional(), source_net_id: Wa.string().min(1).optional(), net_is_assignable: Wa.boolean().optional(), net_assigned: Wa.boolean().optional(), is_tented: Wa.boolean().optional(), tented_on_top: Wa.boolean().optional(), tented_on_bottom: Wa.boolean().optional() }).transform(({ is_tented: e35, ...t2 }) => (e35 !== undefined && (t2.tented_on_top ??= e35, t2.tented_on_bottom ??= e35), t2)).describe("Defines a via on the PCB");
var VO = Wa.object({ type: Wa.literal("pcb_board"), pcb_board_id: GR("pcb_board"), pcb_panel_id: Wa.string().optional(), carrier_pcb_board_id: Wa.string().optional(), is_subcircuit: Wa.boolean().optional(), subcircuit_id: Wa.string().optional(), is_mounted_to_carrier_board: Wa.boolean().optional(), is_via_in_pad_allowed: Wa.boolean().optional(), default_via_tented_on_top: Wa.boolean().optional(), default_via_tented_on_bottom: Wa.boolean().optional(), default_via_plugged: Wa.boolean().optional(), width: PR.optional(), height: PR.optional(), center: DR, display_offset_x: Wa.string().optional().describe("How to display the x offset for this board, usually corresponding with how the user specified it"), display_offset_y: Wa.string().optional().describe("How to display the y offset for this board, usually corresponding with how the user specified it"), thickness: PR.optional().default(1.4), num_layers: Wa.number().optional().default(4), allow_blind_and_buried_vias: Wa.boolean().optional().describe("Whether autorouters may generate blind and buried vias. False restricts newly generated vias to the full board stack."), outline: Wa.array(DR).optional(), shape: Wa.enum(["rect", "polygon"]).optional(), material: Wa.enum(["fr4", "fr1", "flex"]).default("fr4"), solder_mask_color: Wa.string().optional(), silkscreen_color: Wa.string().optional(), anchor_position: DR.optional(), anchor_alignment: UR.optional(), position_mode: Wa.enum(["relative_to_panel_anchor", "none"]).optional() }).merge(EA).describe("Defines the board outline of the PCB");
var WO = DR.extend({ x: PR.pipe(Wa.number().finite()), y: PR.pipe(Wa.number().finite()) });
var GO = Wa.object({ type: Wa.literal("pcb_bend"), pcb_bend_id: GR("pcb_bend"), pcb_board_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), name: Wa.string().optional(), start: WO, end: WO, bend_angle: OR.pipe(Wa.number().finite()), bend_radius: PR.pipe(Wa.number().finite().positive()), bend_side: Wa.enum(["left", "right"]) }).refine(({ start: e35, end: t2 }) => e35.x !== t2.x || e35.y !== t2.y, { message: "Bend centerline endpoints must be distinct", path: ["end"] }).describe("Defines a finite-radius bend on a flat PCB for runtime CAD folding");
var UO = PR.pipe(Wa.number().finite().positive());
var ZO = DR.extend({ x: PR.pipe(Wa.number().finite()), y: PR.pipe(Wa.number().finite()) });
var qO = Wa.object({ type: Wa.literal("pcb_stiffener"), pcb_stiffener_id: GR("pcb_stiffener"), pcb_board_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), name: Wa.string().optional(), layer: Wa.enum(["top", "bottom"]), material: Wa.enum(["fr4", "polyimide", "stainless_steel", "aluminum"]), thickness: UO, adhesive_thickness: PR.pipe(Wa.number().finite().nonnegative()).optional() });
var JO = qO.extend({ shape: Wa.literal("rect"), center: ZO, rotation: OR.pipe(Wa.number().finite()).optional(), width: UO, height: UO, outline: Wa.never().optional() });
var QO = qO.extend({ shape: Wa.literal("polygon"), outline: Wa.array(ZO).min(3).refine((e35) => {
  const t2 = e35.reduce((t3, n2, o3) => {
    const i3 = e35[(o3 + 1) % e35.length];
    return t3 + n2.x * i3.y - i3.x * n2.y;
  }, 0);
  return Number.isFinite(t2) && t2 !== 0;
}, "Stiffener outline must enclose a nonzero area"), center: Wa.never().optional(), rotation: Wa.never().optional(), width: Wa.never().optional(), height: Wa.never().optional() });
var KO = Wa.discriminatedUnion("shape", [JO, QO]).describe("Defines bonded mechanical PCB reinforcement without adding copper layers");
var ek = Wa.object({ type: Wa.literal("pcb_panel"), pcb_panel_id: GR("pcb_panel"), width: PR, height: PR, center: DR, thickness: PR.optional().default(1.4), covered_with_solder_mask: Wa.boolean().optional().default(true) }).describe("Defines a PCB panel that can contain multiple boards");
var tk = uT.extend({ type: Wa.literal("pcb_placement_error"), pcb_placement_error_id: GR("pcb_placement_error"), error_type: Wa.literal("pcb_placement_error").default("pcb_placement_error"), subcircuit_id: Wa.string().optional() }).describe("Defines a placement error on the PCB");
var nk = uT.extend({ type: Wa.literal("pcb_packing_error"), pcb_packing_error_id: GR("pcb_packing_error"), error_type: Wa.literal("pcb_packing_error").default("pcb_packing_error"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe("Defines a failure to pack PCB components within layout bounds");
var ok = uT.extend({ type: Wa.literal("pcb_panelization_placement_error"), pcb_panelization_placement_error_id: GR("pcb_panelization_placement_error"), error_type: Wa.literal("pcb_panelization_placement_error").default("pcb_panelization_placement_error"), pcb_panel_id: Wa.string().optional(), pcb_board_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe("Defines a panelization placement error on the PCB");
var ik = Wa.object({ type: Wa.literal("pcb_trace_hint"), pcb_trace_hint_id: GR("pcb_trace_hint"), pcb_port_id: Wa.string(), pcb_component_id: Wa.string(), route: Wa.array(TA), subcircuit_id: Wa.string().optional() }).describe("A hint that can be used during generation of a PCB trace");
var rk = Wa.object({ type: Wa.literal("pcb_silkscreen_line"), pcb_silkscreen_line_id: GR("pcb_silkscreen_line"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), stroke_width: wR.default("0.1mm"), x1: wR, y1: wR, x2: wR, y2: wR, layer: bE }).describe("Defines a silkscreen line on the PCB");
var sk = Wa.object({ type: Wa.literal("pcb_silkscreen_path"), pcb_silkscreen_path_id: GR("pcb_silkscreen_path"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), layer: bE, route: Wa.array(DR), stroke_width: PR }).describe("Defines a silkscreen path on the PCB");
var ak = Wa.object({ type: Wa.literal("pcb_silkscreen_text"), pcb_silkscreen_text_id: GR("pcb_silkscreen_text"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), font: Wa.literal("tscircuit2024").default("tscircuit2024"), font_size: wR.default("0.2mm"), pcb_component_id: Wa.string(), text: Wa.string(), is_knockout: Wa.boolean().default(false).optional(), knockout_padding: Wa.object({ left: PR, top: PR, bottom: PR, right: PR }).default({ left: "0.2mm", top: "0.2mm", bottom: "0.2mm", right: "0.2mm" }).optional(), ccw_rotation: Wa.number().optional(), layer: yE, is_mirrored: Wa.boolean().default(false).optional(), anchor_position: DR.default({ x: 0, y: 0 }), anchor_alignment: UR.default("center") }).describe("Defines silkscreen text on the PCB");
var ck = Wa.object({ type: Wa.literal("pcb_copper_text"), pcb_copper_text_id: GR("pcb_copper_text"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), font: Wa.literal("tscircuit2024").default("tscircuit2024"), font_size: wR.default("0.2mm"), pcb_component_id: Wa.string(), text: Wa.string(), is_knockout: Wa.boolean().default(false).optional(), knockout_padding: Wa.object({ left: PR, top: PR, bottom: PR, right: PR }).default({ left: "0.2mm", top: "0.2mm", bottom: "0.2mm", right: "0.2mm" }).optional(), ccw_rotation: Wa.number().optional(), layer: yE, is_mirrored: Wa.boolean().default(false).optional(), anchor_position: DR.default({ x: 0, y: 0 }), anchor_alignment: UR.default("center") }).describe("Defines copper text on the PCB");
var lk = Wa.object({ type: Wa.literal("pcb_silkscreen_rect"), pcb_silkscreen_rect_id: GR("pcb_silkscreen_rect"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: DR, width: PR, height: PR, layer: yE, stroke_width: PR.default("1mm"), corner_radius: PR.optional(), is_filled: Wa.boolean().default(true).optional(), has_stroke: Wa.boolean().optional(), is_stroke_dashed: Wa.boolean().optional(), ccw_rotation: Wa.number().optional() }).describe("Defines a silkscreen rect on the PCB");
var hk = Wa.object({ type: Wa.literal("pcb_silkscreen_circle"), pcb_silkscreen_circle_id: GR("pcb_silkscreen_circle"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: DR, radius: PR, layer: bE, stroke_width: PR.default("1mm"), is_filled: Wa.boolean().optional() }).describe("Defines a silkscreen circle on the PCB");
var dk = Wa.object({ type: Wa.literal("pcb_silkscreen_oval"), pcb_silkscreen_oval_id: GR("pcb_silkscreen_oval"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: DR, radius_x: wR, radius_y: wR, layer: bE, ccw_rotation: OR.optional() }).describe("Defines a silkscreen oval on the PCB");
var uk = Wa.object({ type: Wa.literal("pcb_silkscreen_graphic"), pcb_silkscreen_graphic_id: GR("pcb_silkscreen_graphic"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), layer: bE, image_asset: qR.optional() }).extend({ shape: Wa.literal("brep"), brep_shape: vA }).describe("Defines a BRep silkscreen graphic on the PCB");
var pk = Wa.discriminatedUnion("shape", [uk]).describe("Defines a silkscreen graphic on the PCB");
var mk = Wa.object({ type: Wa.literal("pcb_silkscreen_pill"), pcb_silkscreen_pill_id: GR("pcb_silkscreen_pill"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: DR, width: PR, height: PR, layer: yE, ccw_rotation: Wa.number().optional() }).describe("Defines a silkscreen pill on the PCB");
var gk = Wa.object({ type: Wa.literal("pcb_fabrication_note_text"), pcb_fabrication_note_text_id: GR("pcb_fabrication_note_text"), subcircuit_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), font: Wa.literal("tscircuit2024").default("tscircuit2024"), font_size: wR.default("1mm"), pcb_component_id: Wa.string(), text: Wa.string(), ccw_rotation: Wa.number().optional(), layer: bE, anchor_position: DR.default({ x: 0, y: 0 }), anchor_alignment: Wa.enum(["center", "top_left", "top_right", "bottom_left", "bottom_right"]).default("center"), color: Wa.string().optional() }).describe("Defines a fabrication note in text on the PCB, useful for leaving notes for assemblers or fabricators");
var fk = Wa.object({ type: Wa.literal("pcb_fabrication_note_path"), pcb_fabrication_note_path_id: GR("pcb_fabrication_note_path"), pcb_component_id: Wa.string(), subcircuit_id: Wa.string().optional(), layer: yE, route: Wa.array(DR), stroke_width: PR, color: Wa.string().optional(), is_filled: Wa.boolean().optional(), has_stroke: Wa.boolean().optional() }).describe("Defines a fabrication path on the PCB for fabricators or assemblers");
var _k = Wa.object({ type: Wa.literal("pcb_fabrication_note_rect"), pcb_fabrication_note_rect_id: GR("pcb_fabrication_note_rect"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: DR, width: PR, height: PR, layer: bE, stroke_width: PR.default("0.1mm"), corner_radius: PR.optional(), is_filled: Wa.boolean().optional(), has_stroke: Wa.boolean().optional(), is_stroke_dashed: Wa.boolean().optional(), color: Wa.string().optional() }).describe("Defines a fabrication note rectangle on the PCB");
var yk = Wa.object({ type: Wa.literal("pcb_fabrication_note_dimension"), pcb_fabrication_note_dimension_id: GR("pcb_fabrication_note_dimension"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), layer: bE, from: DR, to: DR, text: Wa.string().optional(), text_ccw_rotation: Wa.number().optional(), offset: PR.optional(), offset_distance: PR.optional(), offset_direction: Wa.object({ x: Wa.number(), y: Wa.number() }).optional(), font: Wa.literal("tscircuit2024").default("tscircuit2024"), font_size: PR.default("1mm"), color: Wa.string().optional(), arrow_size: PR.default("1mm") }).describe("Defines a measurement annotation within PCB fabrication notes");
var bk = Wa.object({ type: Wa.literal("pcb_note_text"), pcb_note_text_id: GR("pcb_note_text"), pcb_component_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), name: Wa.string().optional(), font: Wa.literal("tscircuit2024").default("tscircuit2024"), font_size: wR.default("1mm"), text: Wa.string().optional(), anchor_position: DR.default({ x: 0, y: 0 }), anchor_alignment: Wa.enum(["center", "top_left", "top_right", "bottom_left", "bottom_right"]).default("center"), layer: bE.default("top"), is_mirrored_from_top_view: Wa.boolean().optional(), color: Wa.string().optional() }).describe("Defines a documentation note in text on the PCB");
var xk = Wa.object({ type: Wa.literal("pcb_note_rect"), pcb_note_rect_id: GR("pcb_note_rect"), pcb_component_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), name: Wa.string().optional(), text: Wa.string().optional(), center: DR, width: PR, height: PR, layer: bE.default("top"), stroke_width: PR.default("0.1mm"), corner_radius: PR.optional(), is_filled: Wa.boolean().optional(), has_stroke: Wa.boolean().optional(), is_stroke_dashed: Wa.boolean().optional(), color: Wa.string().optional() }).describe("Defines a rectangular documentation note on the PCB");
var vk = Wa.object({ type: Wa.literal("pcb_note_path"), pcb_note_path_id: GR("pcb_note_path"), pcb_component_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), name: Wa.string().optional(), text: Wa.string().optional(), route: Wa.array(DR), layer: bE.default("top"), stroke_width: PR.default("0.1mm"), color: Wa.string().optional() }).describe("Defines a polyline documentation note on the PCB");
var Ik = Wa.object({ type: Wa.literal("pcb_note_line"), pcb_note_line_id: GR("pcb_note_line"), pcb_component_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), name: Wa.string().optional(), text: Wa.string().optional(), x1: wR, y1: wR, x2: wR, y2: wR, layer: bE.default("top"), stroke_width: wR.default("0.1mm"), color: Wa.string().optional(), is_dashed: Wa.boolean().optional() }).describe("Defines a straight documentation note line on the PCB");
var Sk = Wa.object({ type: Wa.literal("pcb_note_dimension"), pcb_note_dimension_id: GR("pcb_note_dimension"), pcb_component_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), name: Wa.string().optional(), from: DR, to: DR, text: Wa.string().optional(), text_ccw_rotation: Wa.number().optional(), offset_distance: PR.optional(), offset_direction: Wa.object({ x: Wa.number(), y: Wa.number() }).optional(), font: Wa.literal("tscircuit2024").default("tscircuit2024"), font_size: PR.default("1mm"), layer: bE.default("top"), color: Wa.string().optional(), arrow_size: PR.default("1mm") }).describe("Defines a measurement annotation within PCB documentation notes");
var Ck = uT.extend({ type: Wa.literal("pcb_footprint_overlap_error"), pcb_error_id: GR("pcb_error"), error_type: Wa.literal("pcb_footprint_overlap_error").default("pcb_footprint_overlap_error"), pcb_smtpad_ids: Wa.array(Wa.string()).optional(), pcb_plated_hole_ids: Wa.array(Wa.string()).optional(), pcb_hole_ids: Wa.array(Wa.string()).optional(), pcb_keepout_ids: Wa.array(Wa.string()).optional() }).describe("Error emitted when a pcb footprint overlaps with another element");
var Pk = uT.extend({ type: Wa.literal("pcb_courtyard_overlap_error"), pcb_error_id: GR("pcb_error"), error_type: Wa.literal("pcb_courtyard_overlap_error").default("pcb_courtyard_overlap_error"), pcb_component_ids: Wa.tuple([Wa.string(), Wa.string()]) }).describe("Error emitted when the courtyard (CrtYd) of one PCB component overlaps with the courtyard of another");
var Mk = Wa.object({ type: Wa.literal("pcb_keepout"), shape: Wa.literal("outline"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), outline: Wa.array(DR).min(2), stroke_width: PR, pcb_keepout_id: Wa.string(), layers: Wa.array(Wa.string()), description: Wa.string().optional(), excluded_pcb_component_ids: Wa.array(Wa.string()).optional(), warning_only: Wa.boolean().optional(), allow_traces: Wa.boolean().optional(), allow_placements: Wa.boolean().optional() });
var wk = Wa.object({ type: Wa.literal("pcb_keepout"), shape: Wa.literal("rect"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: DR, width: wR, height: wR, pcb_keepout_id: Wa.string(), layers: Wa.array(Wa.string()), description: Wa.string().optional(), excluded_pcb_component_ids: Wa.array(Wa.string()).optional(), warning_only: Wa.boolean().optional(), allow_traces: Wa.boolean().optional(), allow_placements: Wa.boolean().optional() }).or(Wa.object({ type: Wa.literal("pcb_keepout"), shape: Wa.literal("circle"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: DR, radius: wR, pcb_keepout_id: Wa.string(), layers: Wa.array(Wa.string()), description: Wa.string().optional(), excluded_pcb_component_ids: Wa.array(Wa.string()).optional(), warning_only: Wa.boolean().optional(), allow_traces: Wa.boolean().optional(), allow_placements: Wa.boolean().optional() })).or(Mk);
var Nk = Wa.object({ type: Wa.literal("pcb_keepout_overlap_warning"), pcb_keepout_overlap_warning_id: GR("pcb_keepout_overlap_warning"), warning_type: Wa.literal("pcb_keepout_overlap_warning").default("pcb_keepout_overlap_warning"), message: Wa.string(), pcb_keepout_id: Wa.string(), pcb_component_ids: Wa.array(Wa.string()).optional(), pcb_trace_ids: Wa.array(Wa.string()).optional(), pcb_smtpad_ids: Wa.array(Wa.string()).optional(), pcb_plated_hole_ids: Wa.array(Wa.string()).optional(), pcb_via_ids: Wa.array(Wa.string()).optional(), center: DR.optional(), subcircuit_id: Wa.string().optional() }).describe("Warning emitted when copper overlaps a PCB keepout with warning_only enabled");
var Rk = Wa.object({ type: Wa.literal("pcb_cutout"), pcb_cutout_id: GR("pcb_cutout"), pcb_component_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), pcb_board_id: Wa.string().optional(), pcb_panel_id: Wa.string().optional() });
var Tk = Rk.extend({ shape: Wa.literal("rect"), center: DR, width: PR, height: PR, rotation: OR.optional(), corner_radius: PR.optional() });
var Ek = Rk.extend({ shape: Wa.literal("circle"), center: DR, radius: PR });
var Ak = Rk.extend({ shape: Wa.literal("polygon"), points: Wa.array(DR) });
var Ok = Rk.extend({ shape: Wa.literal("path"), route: Wa.array(DR), slot_width: PR, slot_length: PR.optional(), space_between_slots: PR.optional(), slot_corner_radius: PR.optional() });
var kk = Wa.discriminatedUnion("shape", [Tk, Ek, Ak, Ok]).describe("Defines a cutout on the PCB, removing board material.");
var Dk = uT.extend({ type: Wa.literal("pcb_missing_footprint_error"), pcb_missing_footprint_error_id: GR("pcb_missing_footprint_error"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), error_type: Wa.literal("pcb_missing_footprint_error").default("pcb_missing_footprint_error"), source_component_id: Wa.string() }).describe("Defines a missing footprint error on the PCB");
var Lk = uT.extend({ type: Wa.literal("external_footprint_load_error"), external_footprint_load_error_id: GR("external_footprint_load_error"), pcb_component_id: Wa.string(), source_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), footprinter_string: Wa.string().optional(), error_type: Wa.literal("external_footprint_load_error").default("external_footprint_load_error") }).describe("Defines an error when an external footprint fails to load");
var zk = uT.extend({ type: Wa.literal("circuit_json_footprint_load_error"), circuit_json_footprint_load_error_id: GR("circuit_json_footprint_load_error"), pcb_component_id: Wa.string(), source_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), error_type: Wa.literal("circuit_json_footprint_load_error").default("circuit_json_footprint_load_error"), circuit_json: Wa.array(Wa.any()).optional() }).describe("Defines an error when a circuit JSON footprint fails to load");
var Bk = Wa.object({ type: Wa.literal("pcb_group"), pcb_group_id: GR("pcb_group"), source_group_id: Wa.string(), is_subcircuit: Wa.boolean().optional(), subcircuit_id: Wa.string().optional(), width: PR.optional(), height: PR.optional(), center: DR, display_offset_x: Wa.string().optional().describe("How to display the x offset for this group, usually corresponding with how the user specified it"), display_offset_y: Wa.string().optional().describe("How to display the y offset for this group, usually corresponding with how the user specified it"), outline: Wa.array(DR).optional(), anchor_position: DR.optional(), anchor_alignment: UR.default("center"), position_mode: Wa.enum(["packed", "relative_to_group_anchor", "none"]).optional(), positioned_relative_to_pcb_group_id: Wa.string().optional(), positioned_relative_to_pcb_board_id: Wa.string().optional(), pcb_component_ids: Wa.array(Wa.string()), child_layout_mode: Wa.enum(["packed", "none"]).optional(), name: Wa.string().optional(), description: Wa.string().optional(), layout_mode: Wa.string().optional(), autorouter_configuration: Wa.object({ trace_clearance: PR }).optional(), autorouter_used_string: Wa.string().optional() }).describe("Defines a group of components on the PCB");
var Fk = uT.extend({ type: Wa.literal("pcb_autorouting_error"), pcb_error_id: GR("pcb_autorouting_error"), error_type: Wa.literal("pcb_autorouting_error").default("pcb_autorouting_error"), subcircuit_id: Wa.string().optional() }).describe("The autorouting has failed to route a portion of the board");
var jk = uT.extend({ type: Wa.literal("pcb_preflight_routing_error"), pcb_preflight_routing_error_id: GR("pcb_preflight_routing_error"), error_type: Wa.literal("pcb_preflight_routing_error").default("pcb_preflight_routing_error"), error_code: Wa.string(), subcircuit_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), routing_phase_index: Wa.number().int().optional(), phase_name: Wa.string().optional(), source_trace_ids: Wa.array(Wa.string()).optional(), pcb_component_ids: Wa.array(Wa.string()).optional(), pcb_port_ids: Wa.array(Wa.string()).optional(), related_error_ids: Wa.array(Wa.string()).optional(), measurements: Wa.record(Wa.number().finite()).optional() });
var $k = Wa.object({ type: Wa.literal("pcb_manual_edit_conflict_warning"), pcb_manual_edit_conflict_warning_id: GR("pcb_manual_edit_conflict_warning"), warning_type: Wa.literal("pcb_manual_edit_conflict_warning").default("pcb_manual_edit_conflict_warning"), message: Wa.string(), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), source_component_id: Wa.string() }).describe("Warning emitted when a component has both manual placement and explicit pcbX/pcbY coordinates");
var Yk = Wa.enum(["x-", "x+", "y+", "y-"]);
var Xk = Wa.object({ type: Wa.literal("pcb_connector_not_in_accessible_orientation_warning"), pcb_connector_not_in_accessible_orientation_warning_id: GR("pcb_connector_not_in_accessible_orientation_warning"), warning_type: Wa.literal("pcb_connector_not_in_accessible_orientation_warning").default("pcb_connector_not_in_accessible_orientation_warning"), message: Wa.string(), pcb_component_id: Wa.string(), source_component_id: Wa.string().optional(), pcb_board_id: Wa.string().optional(), facing_direction: Yk, recommended_facing_direction: Yk, subcircuit_id: Wa.string().optional() }).describe("Warning emitted when a connector PCB component is facing inward toward the board and should be reoriented to an outward-facing direction");
var Hk = Wa.object({ type: Wa.literal("pcb_component_missing_courtyard_warning"), pcb_component_missing_courtyard_warning_id: GR("pcb_component_missing_courtyard_warning"), warning_type: Wa.literal("pcb_component_missing_courtyard_warning").default("pcb_component_missing_courtyard_warning"), message: Wa.string(), pcb_component_id: Wa.string(), source_component_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe("Warning emitted when a PCB component has no courtyard geometry");
var Vk = Wa.object({ type: Wa.literal("supplier_footprint_mismatch_warning"), supplier_footprint_mismatch_warning_id: GR("supplier_footprint_mismatch_warning"), warning_type: Wa.literal("supplier_footprint_mismatch_warning").default("supplier_footprint_mismatch_warning"), message: Wa.string(), source_component_id: Wa.string(), pcb_component_id: Wa.string().optional(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), supplier_name: pT.optional(), supplier_part_number: Wa.string().optional(), supplier_footprint_url: Wa.string().optional(), footprint_copper_intersection_over_union: Wa.number() }).describe("Warning emitted when a supplier part footprint does not match the expected footprint");
var Wk = Wa.object({ type: Wa.literal("pcb_fabricator_extra_charge_warning"), pcb_fabricator_extra_charge_warning_id: GR("pcb_fabricator_extra_charge_warning"), warning_type: Wa.literal("pcb_fabricator_extra_charge_warning").default("pcb_fabricator_extra_charge_warning"), message: Wa.string(), fabricator_preset: Wa.string(), pcb_board_id: Wa.string().optional(), pcb_via_ids: Wa.array(Wa.string()).optional(), subcircuit_id: Wa.string().optional() }).describe("Warning that a design feature incurs an extra charge for the selected fabricator preset, such as via hole diameters below 0.3 mm with JLCPCB economy or standard presets.");
var Gk = Wa.object({ type: Wa.literal("pcb_breakout_point"), pcb_breakout_point_id: GR("pcb_breakout_point"), pcb_group_id: Wa.string(), subcircuit_id: Wa.string().optional(), source_trace_id: Wa.string().optional(), source_port_id: Wa.string().optional(), source_net_id: Wa.string().optional(), layer: yE.optional(), x: wR, y: wR }).describe("Defines a routing target within a pcb_group for a source_trace or source_net");
var Uk = Wa.object({ type: Wa.literal("pcb_ground_plane"), pcb_ground_plane_id: GR("pcb_ground_plane"), source_pcb_ground_plane_id: Wa.string(), source_net_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe("Defines a ground plane on the PCB");
var Zk = Wa.object({ type: Wa.literal("pcb_ground_plane_region"), pcb_ground_plane_region_id: GR("pcb_ground_plane_region"), pcb_ground_plane_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), layer: yE, points: Wa.array(DR) }).describe("Defines a polygon region of a ground plane");
var qk = Wa.object({ type: Wa.literal("pcb_thermal_spoke"), pcb_thermal_spoke_id: GR("pcb_thermal_spoke"), pcb_ground_plane_id: Wa.string(), shape: Wa.string(), spoke_count: Wa.number(), spoke_thickness: wR, spoke_inner_diameter: wR, spoke_outer_diameter: wR, pcb_plated_hole_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe("Pattern for connecting a ground plane to a plated hole");
var Jk = Wa.object({ type: Wa.literal("pcb_copper_pour"), pcb_copper_pour_id: GR("pcb_copper_pour"), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), layer: yE, source_net_id: Wa.string().optional(), covered_with_solder_mask: Wa.boolean().optional().default(true) });
var Qk = Jk.extend({ shape: Wa.literal("rect"), center: DR, width: PR, height: PR, rotation: OR.optional() });
var Kk = Jk.extend({ shape: Wa.literal("brep"), brep_shape: vA });
var eD = Jk.extend({ shape: Wa.literal("polygon"), points: Wa.array(DR) });
var tD = Wa.discriminatedUnion("shape", [Qk, Kk, eD]).describe("Defines a copper pour on the PCB.");
var nD = uT.extend({ type: Wa.literal("pcb_component_outside_board_error"), pcb_component_outside_board_error_id: GR("pcb_component_outside_board_error"), error_type: Wa.literal("pcb_component_outside_board_error").default("pcb_component_outside_board_error"), pcb_component_id: Wa.string(), pcb_board_id: Wa.string(), component_center: DR, component_bounds: Wa.object({ min_x: Wa.number(), max_x: Wa.number(), min_y: Wa.number(), max_y: Wa.number() }), subcircuit_id: Wa.string().optional(), source_component_id: Wa.string().optional() }).describe("Error emitted when a PCB component is placed outside the board boundaries");
var oD = uT.extend({ type: Wa.literal("pcb_component_not_on_board_edge_error"), pcb_component_not_on_board_edge_error_id: GR("pcb_component_not_on_board_edge_error"), error_type: Wa.literal("pcb_component_not_on_board_edge_error").default("pcb_component_not_on_board_edge_error"), pcb_component_id: Wa.string(), pcb_board_id: Wa.string(), component_center: DR, pad_to_nearest_board_edge_distance: Wa.number(), source_component_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe("Error emitted when a component that must be placed on the board edge is centered away from the edge");
var iD = uT.extend({ type: Wa.literal("pcb_component_invalid_layer_error"), pcb_component_invalid_layer_error_id: GR("pcb_component_invalid_layer_error"), error_type: Wa.literal("pcb_component_invalid_layer_error").default("pcb_component_invalid_layer_error"), pcb_component_id: Wa.string().optional(), source_component_id: Wa.string(), layer: yE, subcircuit_id: Wa.string().optional() }).describe("Error emitted when a component is placed on an invalid layer (components can only be on 'top' or 'bottom' layers)");
var rD = uT.extend({ type: Wa.literal("pcb_via_clearance_error"), pcb_error_id: GR("pcb_error"), error_type: Wa.literal("pcb_via_clearance_error").default("pcb_via_clearance_error"), pcb_via_ids: Wa.array(Wa.string()).min(2), minimum_clearance: wR.optional(), actual_clearance: wR.optional(), pcb_center: Wa.object({ x: Wa.number().optional(), y: Wa.number().optional() }).optional(), subcircuit_id: Wa.string().optional() }).describe("Error emitted when vias are closer than the allowed clearance");
var sD = uT.extend({ type: Wa.literal("pcb_via_trace_clearance_error"), pcb_via_trace_clearance_error_id: GR("pcb_via_trace_clearance_error"), error_type: Wa.literal("pcb_via_trace_clearance_error").default("pcb_via_trace_clearance_error"), pcb_via_id: Wa.string(), pcb_trace_id: Wa.string(), minimum_clearance: wR.optional(), actual_clearance: wR.optional(), center: Wa.object({ x: Wa.number().optional(), y: Wa.number().optional() }).optional(), subcircuit_id: Wa.string().optional() }).describe("Error emitted when a via and trace are closer than the allowed clearance");
var aD = uT.extend({ type: Wa.literal("pcb_pad_pad_clearance_error"), pcb_pad_pad_clearance_error_id: GR("pcb_pad_pad_clearance_error"), error_type: Wa.literal("pcb_pad_pad_clearance_error").default("pcb_pad_pad_clearance_error"), pcb_pad_ids: Wa.array(Wa.string()).min(2), minimum_clearance: wR.optional(), actual_clearance: wR.optional(), center: Wa.object({ x: Wa.number().optional(), y: Wa.number().optional() }).optional(), subcircuit_id: Wa.string().optional() }).describe("Error emitted when pads are closer than the allowed clearance");
var cD = uT.extend({ type: Wa.literal("pcb_pad_trace_clearance_error"), pcb_pad_trace_clearance_error_id: GR("pcb_pad_trace_clearance_error"), error_type: Wa.literal("pcb_pad_trace_clearance_error").default("pcb_pad_trace_clearance_error"), pcb_pad_id: Wa.string(), pcb_trace_id: Wa.string(), minimum_clearance: wR.optional(), actual_clearance: wR.optional(), center: Wa.object({ x: Wa.number().optional(), y: Wa.number().optional() }).optional(), subcircuit_id: Wa.string().optional() }).describe("Error emitted when a pad and trace are closer than allowed clearance");
var lD = Wa.object({ type: Wa.literal("pcb_courtyard_rect"), pcb_courtyard_rect_id: GR("pcb_courtyard_rect"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: DR, width: PR, height: PR, layer: bE, ccw_rotation: OR.optional(), color: Wa.string().optional() }).describe("Defines a courtyard rectangle on the PCB");
var hD = Wa.object({ type: Wa.literal("pcb_courtyard_outline"), pcb_courtyard_outline_id: GR("pcb_courtyard_outline"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), layer: bE, outline: Wa.array(DR).min(2) }).describe("Defines a courtyard outline on the PCB");
var dD = Wa.object({ type: Wa.literal("pcb_courtyard_polygon"), pcb_courtyard_polygon_id: GR("pcb_courtyard_polygon"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), layer: bE, points: Wa.array(DR).min(3), color: Wa.string().optional() }).describe("Defines a courtyard polygon on the PCB");
var uD = Wa.object({ type: Wa.literal("pcb_courtyard_circle"), pcb_courtyard_circle_id: GR("pcb_courtyard_circle"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: DR, radius: PR, layer: bE, color: Wa.string().optional() }).describe("Defines a courtyard circle on the PCB");
var pD = Wa.object({ type: Wa.literal("pcb_courtyard_pill"), pcb_courtyard_pill_id: GR("pcb_courtyard_pill"), pcb_component_id: Wa.string(), pcb_group_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), center: DR, width: PR, height: PR, radius: PR, layer: bE, color: Wa.string().optional() }).describe("Defines a courtyard pill on the PCB");
var mD = ["obj", "stl", "3mf", "gltf", "glb", "step", "wrl"];
var gD = ["x+", "x-", "y+", "y-", "z+", "z-"];
var fD = { obj: "z+", stl: "z+", "3mf": "z+", gltf: "y+", glb: "y+", step: "z+", wrl: "y+" };
var _D = Wa.object({ type: Wa.literal("cad_component"), cad_component_id: Wa.string(), pcb_component_id: Wa.string().optional().describe("Optional PCB component reference; omit for CAD geometry without a PCB component"), source_component_id: Wa.string(), position: zR, rotation: zR.optional(), is_on_folded_board: Wa.boolean().optional().describe("True when position and rotation describe the assembled folded board pose. False or omitted means the flat board pose. PCB records remain flat; pcb_component_id identifies the flat mount and owning board for reversible transforms."), size: zR.optional(), layer: yE.optional(), subcircuit_id: Wa.string().optional(), footprinter_string: Wa.string().optional(), model_obj_url: Wa.string().optional(), model_stl_url: Wa.string().optional(), model_3mf_url: Wa.string().optional(), model_gltf_url: Wa.string().optional(), model_glb_url: Wa.string().optional(), model_step_url: Wa.string().optional(), model_wrl_url: Wa.string().optional(), model_asset: qR.optional(), model_unit_to_mm_scale_factor: Wa.number().optional(), model_board_normal_direction: Wa.enum(gD).optional().describe(`The direction in the model's coordinate space that is considered "up" or "coming out of the board surface"`), model_origin_position: zR.optional(), model_origin_alignment: Wa.enum(["unknown", "center", "center_of_component_on_board_surface", "bottom_center_of_component"]).optional(), model_object_fit: Wa.enum(["contain_within_bounds", "fill_bounds"]).optional().default("contain_within_bounds"), model_jscad: Wa.any().optional(), color: Wa.string().trim().min(1).optional().describe("Explicit color override for CAD geometry, including authored JSCAD material colors. Omit to preserve model materials."), show_as_translucent_model: Wa.boolean().optional(), show_as_bounding_box: Wa.boolean().optional(), show_hidden_edges: Wa.boolean().optional(), anchor_alignment: Wa.enum(["center", "center_of_component_on_board_surface"]).optional().default("center") }).describe("Defines CAD geometry, optionally associated with a PCB component");
var yD = uT.extend({ type: Wa.literal("cad_collision_error"), cad_collision_error_id: GR("cad_collision_error"), error_type: Wa.literal("cad_collision_error").default("cad_collision_error"), cad_component_ids: Wa.array(Wa.string()).min(1), pcb_component_ids: Wa.array(Wa.string()).optional(), source_component_ids: Wa.array(Wa.string()).min(1), intersection_area_mm2: Wa.number().finite().nonnegative(), threshold_area_mm2: Wa.number().finite().nonnegative() }).describe("An aperture-bearing part intersects the finished enclosure. The intersection_area_mm2 is the union silhouette area of the solid intersection projected along the aperture face normal, in the right-handed Circuit JSON world frame (+X right, +Y top, +Z above). It is an area in square millimetres, not intersection volume or surface area. This indicates possible aperture misplacement, insufficient size/depth, or body clearance problems; it does not prove which cause applies.");
var bD = zR.refine((e35) => [e35.x, e35.y, e35.z].every(Number.isFinite), "Connector pin 1 positions must be finite").describe("Resolved pin 1 position at the connector mating face, in right-handed circuit world, millimeters: +X right, +Y top, +Z above. An absolute point, not a direction. Computed by the circuit producer from endpoint geometry. Together with the endpoint path tangent, fixes connector roll and identifies its pin 1 side; renderers must not infer it from footprints.");
var xD = Wa.object({ type: Wa.literal("cad_cable"), cad_cable_id: Wa.string(), name: Wa.string().min(1), from_source_component_id: Wa.string(), to_source_component_id: Wa.string(), from_connector_pin1_position: bD.optional(), to_connector_pin1_position: bD.optional(), cableprinter_string: Wa.string().min(1).describe('Physical cable definition, e.g. "usb_c" or "jst_ph_pins6". Independent of the route.'), path: Wa.array(zR).min(2).refine((e35) => e35.every((t2, n2) => [t2.x, t2.y, t2.z].every(Number.isFinite) && (n2 === 0 || Math.hypot(t2.x - e35[n2 - 1].x, t2.y - e35[n2 - 1].y, t2.z - e35[n2 - 1].z) > 0.00000001)), "Cable paths require finite, distinct consecutive points").describe("Resolved cable centerline points in right-handed circuit world, millimeters: +X right, +Y top, +Z above. First/last samples are connector wire exits; their tangents point into/out of the cable. Includes routing/slack; renderers must not recompute the path.") }).describe("A physical assembly cable with a resolved 3D route. Several cables are independent cad_cable records, each with its own endpoints, definition and path. Does not imply electrical pin mapping.");
var vD = 0.000001;
var ID = Wa.object({ x: Wa.number().finite(), y: Wa.number().finite(), z: Wa.number().finite() }).refine((e35) => Math.abs(Math.hypot(e35.x, e35.y, e35.z) - 1) <= vD, "Reference surface directions must be unit vectors");
var SD = wR.pipe(Wa.number().finite().positive());
var CD = Wa.object({ type: Wa.literal("cad_reference_surface"), cad_reference_surface_id: Wa.string().min(1), source_component_id: Wa.string().min(1).describe("Owning assembly part's source component ID. The part may have no CAD geometry."), name: Wa.string().trim().min(1).describe("Reference name, unique within the owning part, e.g. shade in STEM.shade."), shape: Wa.literal("rect"), center: zR.refine((e35) => [e35.x, e35.y, e35.z].every(Number.isFinite), "Reference surface centers must be finite").describe("Resolved surface center in right-handed circuit-world XYZ, millimeters: +X right, +Y top, +Z above. An absolute point after assembly placement."), normal: ID.describe("Outward unit normal in circuit-world XYZ. Dimensionless direction; transform with the part's rotation, without translation."), x_axis: ID.describe("In-plane unit X direction in circuit-world XYZ, perpendicular to normal. The second tangent is normal cross x_axis, giving a right-handed frame."), width: SD.optional().describe("Rectangular extent along x_axis in millimeters. Supply together with height. Omission leaves the surface's display size unspecified."), height: SD.optional().describe("Rectangular extent along normal cross x_axis in millimeters. Supply together with width."), subcircuit_id: Wa.string().optional() }).superRefine((e35, t2) => {
  e35.width === undefined != (e35.height === undefined) && t2.addIssue({ code: Wa.ZodIssueCode.custom, path: ["width"], message: "Provide width and height together" });
  const { normal: n2, x_axis: o3 } = e35;
  Math.abs(n2.x * o3.x + n2.y * o3.y + n2.z * o3.z) > vD && t2.addIssue({ code: Wa.ZodIssueCode.custom, path: ["x_axis"], message: "x_axis must be perpendicular to normal" });
}).describe("A named assembly mounting surface with a resolved world-space frame. Reference geometry for optional visualization; does not add solid material or electrical connectivity. The producer resolves part placement independently of CAD-model offsets; renderers consume the world frame without reapplying the owning model's transform.");
var PD = Wa.enum(["sinewave", "square", "triangle", "sawtooth"]);
var MD = Wa.union([Wa.string(), Wa.number()]).transform((e35) => typeof e35 == "string" ? e35.endsWith("%") ? parseFloat(e35.slice(0, -1)) / 100 : parseFloat(e35) : e35).pipe(Wa.number().min(0, "Duty cycle must be non-negative").max(1, "Duty cycle cannot be greater than 100%"));
var wD = Wa.object({ type: Wa.literal("simulation_voltage_source"), simulation_voltage_source_id: GR("simulation_voltage_source"), is_dc_source: Wa.literal(true).optional().default(true), positive_source_port_id: Wa.string().optional(), negative_source_port_id: Wa.string().optional(), positive_source_net_id: Wa.string().optional(), negative_source_net_id: Wa.string().optional(), voltage: CR, ac_magnitude: CR.optional(), ac_phase: OR.optional() }).describe("Defines a DC voltage source for simulation");
var ND = Wa.object({ type: Wa.literal("simulation_voltage_source"), simulation_voltage_source_id: GR("simulation_voltage_source"), is_dc_source: Wa.literal(false), terminal1_source_port_id: Wa.string().optional(), terminal2_source_port_id: Wa.string().optional(), terminal1_source_net_id: Wa.string().optional(), terminal2_source_net_id: Wa.string().optional(), voltage: CR.optional(), frequency: MR.optional(), peak_to_peak_voltage: CR.optional(), wave_shape: PD.optional(), phase: OR.optional(), duty_cycle: MD.optional(), pulse_delay: ER.optional(), rise_time: ER.optional(), fall_time: ER.optional(), pulse_width: ER.optional(), period: ER.optional(), ac_magnitude: CR.optional(), ac_phase: OR.optional() }).describe("Defines an AC voltage source for simulation");
var RD = Wa.union([wD, ND]).describe("Defines a voltage source for simulation");
var TD = Wa.union([Wa.string(), Wa.number()]).transform((e35) => typeof e35 == "string" ? e35.endsWith("%") ? parseFloat(e35.slice(0, -1)) / 100 : parseFloat(e35) : e35).pipe(Wa.number().min(0, "Duty cycle must be non-negative").max(1, "Duty cycle cannot be greater than 100%"));
var ED = Wa.object({ type: Wa.literal("simulation_current_source"), simulation_current_source_id: GR("simulation_current_source"), is_dc_source: Wa.literal(true).optional().default(true), positive_source_port_id: Wa.string().optional(), negative_source_port_id: Wa.string().optional(), positive_source_net_id: Wa.string().optional(), negative_source_net_id: Wa.string().optional(), current: NR, ac_magnitude: NR.optional(), ac_phase: OR.optional() }).describe("Defines a DC current source for simulation");
var AD = Wa.object({ type: Wa.literal("simulation_current_source"), simulation_current_source_id: GR("simulation_current_source"), is_dc_source: Wa.literal(false), terminal1_source_port_id: Wa.string().optional(), terminal2_source_port_id: Wa.string().optional(), terminal1_source_net_id: Wa.string().optional(), terminal2_source_net_id: Wa.string().optional(), current: NR.optional(), frequency: MR.optional(), peak_to_peak_current: NR.optional(), wave_shape: PD.optional(), phase: OR.optional(), duty_cycle: TD.optional(), ac_magnitude: NR.optional(), ac_phase: OR.optional() }).describe("Defines an AC current source for simulation");
var OD = Wa.union([ED, AD]).describe("Defines a current source for simulation");
var kD = Wa.custom((e35) => e35 === "V" || e35 === "A");
var DD = Wa.custom((e35) => e35 === "Ω" || e35 === "F" || e35 === "H" || e35 === "V" || e35 === "A");
var LD = Wa.union([Wa.literal("spice_dc_sweep"), Wa.literal("spice_dc_operating_point"), Wa.literal("spice_transient_analysis"), Wa.literal("spice_ac_analysis"), Wa.literal("pcb_return_current")]);
var zD = Wa.object({ method: Wa.enum(["trap", "gear"]).optional(), reltol: Wa.union([Wa.number(), Wa.string()]).optional(), abstol: Wa.union([Wa.number(), Wa.string()]).optional(), vntol: Wa.union([Wa.number(), Wa.string()]).optional() }).describe("SPICE solver options for a simulation experiment");
var BD = Wa.object({ type: Wa.literal("simulation_experiment"), simulation_experiment_id: GR("simulation_experiment"), name: Wa.string(), experiment_type: LD, time_per_step: RR.optional(), start_time_ms: ER.optional(), end_time_ms: ER.optional(), spice_options: zD.optional(), dc_sweep_voltage_source_id: Wa.string().optional(), dc_sweep_current_source_id: Wa.string().optional(), dc_sweep_start: Wa.number().optional(), dc_sweep_stop: Wa.number().optional(), dc_sweep_step: Wa.number().refine((e35) => e35 !== 0).optional(), dc_sweep_unit: kD.optional(), ac_sweep_type: Wa.enum(["linear", "decade", "octave"]).optional(), ac_samples_per_interval: Wa.number().int().positive().optional(), ac_sample_count: Wa.number().int().positive().optional(), ac_start_frequency_hz: Wa.number().positive().optional(), ac_stop_frequency_hz: Wa.number().positive().optional() }).superRefine((e35, t2) => {
  if (e35.experiment_type === "spice_dc_sweep") {
    const n2 = ["dc_sweep_start", "dc_sweep_stop", "dc_sweep_step", "dc_sweep_unit"];
    for (const o3 of n2)
      e35[o3] === undefined && t2.addIssue({ code: Wa.ZodIssueCode.custom, path: [o3], message: `${o3} is required for a DC sweep` });
    e35.dc_sweep_voltage_source_id !== undefined === (e35.dc_sweep_current_source_id !== undefined) && t2.addIssue({ code: Wa.ZodIssueCode.custom, path: ["dc_sweep_voltage_source_id"], message: "Exactly one DC sweep voltage or current source ID is required" });
  }
  e35.experiment_type === "spice_ac_analysis" && (e35.ac_sweep_type === undefined && t2.addIssue({ code: Wa.ZodIssueCode.custom, path: ["ac_sweep_type"], message: "ac_sweep_type is required for an AC analysis" }), e35.ac_start_frequency_hz === undefined && t2.addIssue({ code: Wa.ZodIssueCode.custom, path: ["ac_start_frequency_hz"], message: "ac_start_frequency_hz is required for an AC analysis" }), e35.ac_stop_frequency_hz === undefined && t2.addIssue({ code: Wa.ZodIssueCode.custom, path: ["ac_stop_frequency_hz"], message: "ac_stop_frequency_hz is required for an AC analysis" }), e35.ac_sweep_type === "linear" && e35.ac_sample_count === undefined && t2.addIssue({ code: Wa.ZodIssueCode.custom, path: ["ac_sample_count"], message: "ac_sample_count is required for a linear AC analysis" }), e35.ac_sweep_type !== "decade" && e35.ac_sweep_type !== "octave" || e35.ac_samples_per_interval !== undefined || t2.addIssue({ code: Wa.ZodIssueCode.custom, path: ["ac_samples_per_interval"], message: "ac_samples_per_interval is required for decade and octave AC analyses" }));
}).describe("Defines a simulation experiment configuration");
var FD = Wa.object({ simulation_parameter_sweep_id: Wa.string(), sweep_index: Wa.number().int().nonnegative(), parameter_value: Wa.number(), parameter_unit: DD });
var jD = Wa.object({ type: Wa.literal("simulation_transient_voltage_graph"), simulation_transient_voltage_graph_id: GR("simulation_transient_voltage_graph"), simulation_experiment_id: Wa.string(), simulation_parameter_sweep_coordinate: FD.optional(), timestamps_ms: Wa.array(Wa.number()).optional(), voltage_levels: Wa.array(Wa.number()), source_component_id: Wa.string().optional(), subcircuit_connectivity_map_key: Wa.string().optional(), time_per_step: RR, start_time_ms: ER, end_time_ms: ER, name: Wa.string().optional(), color: Wa.string().optional() }).describe("Stores voltage measurements over time for a simulation");
var $D = Wa.object({ type: Wa.literal("simulation_transient_current_graph"), simulation_transient_current_graph_id: GR("simulation_transient_current_graph"), simulation_experiment_id: Wa.string(), simulation_parameter_sweep_coordinate: FD.optional(), timestamps_ms: Wa.array(Wa.number()).optional(), current_levels: Wa.array(Wa.number()), source_component_id: Wa.string().optional(), subcircuit_connectivity_map_key: Wa.string().optional(), time_per_step: RR, start_time_ms: ER, end_time_ms: ER, name: Wa.string().optional(), color: Wa.string().optional() }).describe("Stores current measurements over time for a simulation");
var YD = Wa.object({ type: Wa.literal("simulation_switch"), simulation_switch_id: GR("simulation_switch"), source_component_id: Wa.string().optional(), closes_at: ER.optional(), opens_at: ER.optional(), starts_closed: Wa.boolean().optional(), switching_frequency: MR.optional() }).describe("Defines a switch for simulation timing control");
var XD = Wa.object({ type: Wa.literal("simulation_voltage_probe"), simulation_voltage_probe_id: GR("simulation_voltage_probe"), source_component_id: Wa.string().optional(), name: Wa.string().optional(), signal_input_source_port_id: Wa.string().optional(), signal_input_source_net_id: Wa.string().optional(), reference_input_source_port_id: Wa.string().optional(), reference_input_source_net_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), color: Wa.string().optional() }).describe("Defines a voltage probe for simulation. If a reference input is not provided, it measures against ground. If a reference input is provided, it measures the differential voltage between two points.").superRefine((e35, t2) => {
  if (e35.reference_input_source_port_id || e35.reference_input_source_net_id) {
    const n2 = !!e35.signal_input_source_port_id || !!e35.reference_input_source_port_id, o3 = !!e35.signal_input_source_net_id || !!e35.reference_input_source_net_id;
    n2 && o3 ? t2.addIssue({ code: Wa.ZodIssueCode.custom, message: "Cannot mix port and net connections in a differential probe." }) : n2 ? e35.signal_input_source_port_id && e35.reference_input_source_port_id || t2.addIssue({ code: Wa.ZodIssueCode.custom, message: "Differential port probe requires both signal_input_source_port_id and reference_input_source_port_id." }) : o3 && (e35.signal_input_source_net_id && e35.reference_input_source_net_id || t2.addIssue({ code: Wa.ZodIssueCode.custom, message: "Differential net probe requires both signal_input_source_net_id and reference_input_source_net_id." }));
  } else
    !!e35.signal_input_source_port_id == !!e35.signal_input_source_net_id && t2.addIssue({ code: Wa.ZodIssueCode.custom, message: "A voltage probe must have exactly one of signal_input_source_port_id or signal_input_source_net_id." });
});
var HD = Wa.object({ type: Wa.literal("simulation_current_probe"), simulation_current_probe_id: GR("simulation_current_probe"), source_component_id: Wa.string().optional(), name: Wa.string().optional(), positive_source_port_id: Wa.string().optional(), negative_source_port_id: Wa.string().optional(), positive_source_net_id: Wa.string().optional(), negative_source_net_id: Wa.string().optional(), subcircuit_id: Wa.string().optional(), color: Wa.string().optional() }).describe("Defines a current probe for simulation. It measures current flowing from the positive endpoint to the negative endpoint.").superRefine((e35, t2) => {
  const n2 = !!e35.positive_source_port_id, o3 = !!e35.negative_source_port_id, i3 = !!e35.positive_source_net_id, r3 = !!e35.negative_source_net_id, s2 = n2 || o3, a3 = i3 || r3;
  s2 && a3 ? t2.addIssue({ code: Wa.ZodIssueCode.custom, message: "Cannot mix port and net connections in a current probe." }) : s2 ? n2 && o3 || t2.addIssue({ code: Wa.ZodIssueCode.custom, message: "Current probe using source ports requires both positive_source_port_id and negative_source_port_id." }) : a3 ? i3 && r3 || t2.addIssue({ code: Wa.ZodIssueCode.custom, message: "Current probe using source nets requires both positive_source_net_id and negative_source_net_id." }) : t2.addIssue({ code: Wa.ZodIssueCode.custom, message: "A current probe must have either positive/negative source port ids or positive/negative source net ids." });
});
var VD = uT.extend({ type: Wa.literal("simulation_unknown_experiment_error"), simulation_unknown_experiment_error_id: GR("simulation_unknown_experiment_error"), error_type: Wa.literal("simulation_unknown_experiment_error").default("simulation_unknown_experiment_error"), simulation_experiment_id: Wa.string().optional(), subcircuit_id: Wa.string().optional() }).describe("An unknown error occurred during the simulation experiment.");
var WD = Wa.enum(["resistance", "capacitance", "inductance", "voltage", "current"]);
var GD = Wa.object({ type: Wa.literal("simulation_parameter_sweep"), simulation_parameter_sweep_id: GR("simulation_parameter_sweep"), simulation_experiment_id: Wa.string(), name: Wa.string().optional(), parameter_values: Wa.array(Wa.number()).min(1), parameter_unit: DD });
var UD = Wa.discriminatedUnion("parameter_type", [GD.extend({ parameter_type: Wa.literal("resistance"), resistor_source_component_id: Wa.string() }), GD.extend({ parameter_type: Wa.literal("capacitance"), capacitor_source_component_id: Wa.string() }), GD.extend({ parameter_type: Wa.literal("inductance"), inductor_source_component_id: Wa.string() }), GD.extend({ parameter_type: Wa.literal("voltage"), source_net_id: Wa.string() }), GD.extend({ parameter_type: Wa.literal("current"), current_source_component_id: Wa.string() })]).describe("Repeats a simulation experiment over component parameter values");
var ZD = Wa.object({ type: Wa.literal("simulation_dc_operating_point_voltage"), simulation_dc_operating_point_voltage_id: GR("simulation_dc_operating_point_voltage"), simulation_experiment_id: Wa.string(), simulation_parameter_sweep_coordinate: FD.optional(), simulation_voltage_probe_id: Wa.string(), voltage: Wa.number(), name: Wa.string().optional(), color: Wa.string().optional() });
var qD = Wa.object({ type: Wa.literal("simulation_dc_operating_point_current"), simulation_dc_operating_point_current_id: GR("simulation_dc_operating_point_current"), simulation_experiment_id: Wa.string(), simulation_parameter_sweep_coordinate: FD.optional(), simulation_current_probe_id: Wa.string(), current: Wa.number(), name: Wa.string().optional(), color: Wa.string().optional() });
var JD = Wa.object({ type: Wa.literal("simulation_dc_sweep_voltage_graph"), simulation_dc_sweep_voltage_graph_id: GR("simulation_dc_sweep_voltage_graph"), simulation_experiment_id: Wa.string(), simulation_parameter_sweep_coordinate: FD.optional(), simulation_voltage_probe_id: Wa.string(), sweep_values: Wa.array(Wa.number()), sweep_unit: kD, voltage_levels: Wa.array(Wa.number()), name: Wa.string().optional(), color: Wa.string().optional() }).refine((e35) => e35.sweep_values.length === e35.voltage_levels.length, { message: "sweep_values and voltage_levels must have the same length" });
var QD = Wa.object({ type: Wa.literal("simulation_dc_sweep_current_graph"), simulation_dc_sweep_current_graph_id: GR("simulation_dc_sweep_current_graph"), simulation_experiment_id: Wa.string(), simulation_parameter_sweep_coordinate: FD.optional(), simulation_current_probe_id: Wa.string(), sweep_values: Wa.array(Wa.number()), sweep_unit: kD, current_levels: Wa.array(Wa.number()), name: Wa.string().optional(), color: Wa.string().optional() }).refine((e35) => e35.sweep_values.length === e35.current_levels.length, { message: "sweep_values and current_levels must have the same length" });
var KD = Wa.object({ re: Wa.number(), im: Wa.number() });
var eL = Wa.object({ type: Wa.literal("simulation_ac_sweep_voltage_graph"), simulation_ac_sweep_voltage_graph_id: GR("simulation_ac_sweep_voltage_graph"), simulation_experiment_id: Wa.string(), simulation_parameter_sweep_coordinate: FD.optional(), simulation_voltage_probe_id: Wa.string(), frequencies_hz: Wa.array(Wa.number()), complex_voltages: Wa.array(KD), name: Wa.string().optional(), color: Wa.string().optional() }).refine((e35) => e35.frequencies_hz.length === e35.complex_voltages.length, { message: "frequencies_hz and complex_voltages must have the same length" });
var tL = Wa.object({ type: Wa.literal("simulation_ac_sweep_current_graph"), simulation_ac_sweep_current_graph_id: GR("simulation_ac_sweep_current_graph"), simulation_experiment_id: Wa.string(), simulation_parameter_sweep_coordinate: FD.optional(), simulation_current_probe_id: Wa.string(), frequencies_hz: Wa.array(Wa.number()), complex_currents: Wa.array(KD), name: Wa.string().optional(), color: Wa.string().optional() }).refine((e35) => e35.frequencies_hz.length === e35.complex_currents.length, { message: "frequencies_hz and complex_currents must have the same length" });
var nL = Wa.object({ type: Wa.literal("simulation_op_amp"), simulation_op_amp_id: GR("simulation_op_amp"), source_component_id: Wa.string().optional(), inverting_input_source_port_id: Wa.string(), non_inverting_input_source_port_id: Wa.string(), output_source_port_id: Wa.string(), positive_supply_source_port_id: Wa.string(), negative_supply_source_port_id: Wa.string() }).describe("Defines a simple ideal operational amplifier for simulation");
var oL = Wa.object({ type: Wa.literal("simulation_spice_subcircuit"), simulation_spice_subcircuit_id: GR("simulation_spice_subcircuit"), source_component_id: Wa.string(), spice_pin_to_source_port_map: Wa.record(Wa.string(), Wa.string()), subcircuit_source: Wa.string() }).describe("Defines a custom SPICE subcircuit model for simulation");
var iL = (e35) => e35 !== undefined;
var rL = Wa.object({ type: Wa.literal("simulation_oscilloscope_trace"), simulation_oscilloscope_trace_id: GR("simulation_oscilloscope_trace"), simulation_transient_voltage_graph_id: Wa.string().optional(), simulation_transient_current_graph_id: Wa.string().optional(), simulation_voltage_probe_id: Wa.string().optional(), simulation_current_probe_id: Wa.string().optional(), display_name: Wa.string().optional(), color: Wa.string().optional(), display_center_value: Wa.number().optional(), display_center_offset_divs: Wa.number().optional(), volts_per_div: Wa.number().positive().optional(), amps_per_div: Wa.number().positive().optional() }).describe("Defines how a simulation measurement is rendered as an oscilloscope-style trace.").superRefine((e35, t2) => {
  const n2 = [e35.simulation_transient_voltage_graph_id, e35.simulation_voltage_probe_id].filter(iL).length, o3 = [e35.simulation_transient_current_graph_id, e35.simulation_current_probe_id].filter(iL).length;
  n2 + o3 !== 1 && t2.addIssue({ code: Wa.ZodIssueCode.custom, message: "An oscilloscope trace must reference exactly one voltage graph, current graph, voltage probe, or current probe." }), n2 > 0 && e35.amps_per_div !== undefined && t2.addIssue({ code: Wa.ZodIssueCode.custom, message: "Voltage oscilloscope traces must use volts_per_div, not amps_per_div." }), o3 > 0 && e35.volts_per_div !== undefined && t2.addIssue({ code: Wa.ZodIssueCode.custom, message: "Current oscilloscope traces must use amps_per_div, not volts_per_div." });
});
var sL = Wa.object({ x: Wa.number().finite(), y: Wa.number().finite(), layer: yE });
var aL = Wa.discriminatedUnion("contact_type", [sL.extend({ contact_type: Wa.literal("pcb_port"), pcb_port_id: Wa.string().min(1) }), sL.extend({ contact_type: Wa.literal("pcb_via"), pcb_via_id: Wa.string().min(1) }), sL.extend({ contact_type: Wa.literal("pcb_copper_pour"), pcb_copper_pour_id: Wa.string().min(1) })]).describe("Identifies the reference conductor at a return-current contact");
var cL = Wa.object({ signal_pcb_port_id: Wa.string().min(1), reference_pcb_port_id: Wa.string().min(1).optional(), reference_layer: yE, resistance: Wa.number().finite().positive() }).describe("A two-terminal return-current excitation port with resistance in ohms");
var lL = Wa.object({ type: Wa.literal("simulation_return_current_excitation"), simulation_return_current_excitation_id: GR("simulation_return_current_excitation"), simulation_experiment_id: Wa.string().min(1), pcb_trace_id: Wa.string().min(1), ground_source_net_id: Wa.string().min(1), current: Wa.number().finite(), return_source: aL, return_sink: aL, source_port: cL.optional(), load_port: cL.optional() }).describe("Excites a signal trace with signed current in amperes, peak for AC; return_source is near the load and return_sink near the driver for positive current");
var hL = Wa.object({ type: Wa.literal("simulation_pcb_return_current_result"), simulation_pcb_return_current_result_id: GR("simulation_pcb_return_current_result"), simulation_experiment_id: Wa.string().min(1), pcb_board_id: Wa.string().min(1), simulation_return_current_excitation_ids: Wa.array(Wa.string().min(1)).min(1).refine((e35) => new Set(e35).size === e35.length, "Excitation IDs must be unique"), frequency_hz: Wa.number().finite().positive().optional() }).describe("A PCB return-current result at one frequency, or a frequency-independent result when frequency_hz is absent");
function dL(e35) {
  return qR.extend({ project_relative_path: Wa.string().min(1), url: Wa.string().url() }).superRefine((t2, n2) => {
    if (e35.includes(t2.mimetype) || n2.addIssue({ code: Wa.ZodIssueCode.custom, path: ["mimetype"], message: `Expected one of: ${e35.join(", ")}` }), t2.url.startsWith("data:")) {
      const e36 = /^data:([^;,]*)(?:;[^,]*)?,/i.exec(t2.url)?.[1];
      e36?.toLowerCase() !== t2.mimetype && n2.addIssue({ code: Wa.ZodIssueCode.custom, path: ["url"], message: "Data URL media type must match asset.mimetype" });
    }
  });
}
var uL = dL(["application/json", "application/gzip"]);
var pL = dL(["image/png", "image/webp"]);
var mL = Wa.object({ type: Wa.literal("simulation_pcb_return_current_field"), simulation_pcb_return_current_field_id: GR("simulation_pcb_return_current_field"), simulation_pcb_return_current_result_id: Wa.string().min(1), layer: yE, source_net_id: Wa.string().min(1), field_type: Wa.enum(["real", "complex_phasor"]), min_x: Wa.number().finite(), min_y: Wa.number().finite(), columns: Wa.number().int().positive().safe(), rows: Wa.number().int().positive().safe(), cell_width: Wa.number().finite().positive(), cell_height: Wa.number().finite().positive(), copper_thickness: Wa.number().finite().positive(), data_format: Wa.literal("simulation_return_current_grid_json_v1"), field_asset: uL }).superRefine((e35, t2) => {
  Number.isSafeInteger(e35.columns * e35.rows) || t2.addIssue({ code: Wa.ZodIssueCode.custom, path: ["columns"], message: "The grid cell count must be a safe integer" });
}).describe("A sampled sheet-current field in A/mm, using plain or gzipped JSON Asset URLs; dimensions are PCB millimeters");
var gL = Wa.array(Wa.number().finite().nullable()).min(1);
var fL = Wa.discriminatedUnion("field_type", [Wa.object({ field_type: Wa.literal("real"), sheet_current_x: gL, sheet_current_y: gL }), Wa.object({ field_type: Wa.literal("complex_phasor"), sheet_current_x_real: gL, sheet_current_x_imag: gL, sheet_current_y_real: gL, sheet_current_y_imag: gL })]).superRefine((e35, t2) => {
  const n2 = e35.field_type === "real" ? [e35.sheet_current_x, e35.sheet_current_y] : [e35.sheet_current_x_real, e35.sheet_current_x_imag, e35.sheet_current_y_real, e35.sheet_current_y_imag], o3 = n2[0];
  if (n2.some((e36) => e36.length !== o3.length))
    t2.addIssue({ code: Wa.ZodIssueCode.custom, message: "Current channels must have equal lengths" });
  else
    for (let e36 = 0;e36 < o3.length; e36++) {
      const i3 = o3[e36] === null;
      if (n2.some((t3) => t3[e36] === null !== i3))
        return void t2.addIssue({ code: Wa.ZodIssueCode.custom, message: `Cell ${e36} must be null in every channel or finite in every channel` });
    }
}).describe("Decoded real or complex sheet-current arrays with a shared conductor mask");
function _L(e35) {
  const t2 = e35.columns * e35.rows;
  if (!Number.isSafeInteger(e35.columns) || e35.columns <= 0 || !Number.isSafeInteger(e35.rows) || e35.rows <= 0 || !Number.isSafeInteger(t2))
    throw new Error("Grid dimensions must be positive safe integers");
  return fL.superRefine((n2, o3) => {
    n2.field_type !== e35.field_type && o3.addIssue({ code: Wa.ZodIssueCode.custom, path: ["field_type"], message: "Decoded field_type must match the parent field" });
    (n2.field_type === "real" ? n2.sheet_current_x : n2.sheet_current_x_real).length !== t2 && o3.addIssue({ code: Wa.ZodIssueCode.custom, message: `Each current channel must have ${t2} entries (columns * rows)` });
  });
}
var yL = Wa.object({ type: Wa.literal("simulation_pcb_return_current_heatmap"), simulation_pcb_return_current_heatmap_id: GR("simulation_pcb_return_current_heatmap"), simulation_pcb_return_current_result_id: Wa.string().min(1), layer: yE, source_net_id: Wa.string().min(1), min_x: Wa.number().finite(), min_y: Wa.number().finite(), max_x: Wa.number().finite(), max_y: Wa.number().finite(), image_asset: pL }).superRefine((e35, t2) => {
  for (const n2 of ["x", "y"])
    e35[`max_${n2}`] <= e35[`min_${n2}`] && t2.addIssue({ code: Wa.ZodIssueCode.custom, path: [`max_${n2}`], message: "Heatmap bounds must have positive width and height" });
}).describe("A transparent PNG/WebP current-density overlay in A/mm²; the top-left pixel maps to (min_x, max_y)");
var bL = Wa.object({ type: Wa.literal("simulation_pcb_return_current_marker"), simulation_pcb_return_current_marker_id: GR("simulation_pcb_return_current_marker"), simulation_pcb_return_current_result_id: Wa.string().min(1), role: Wa.enum(["signal_source", "signal_load", "return_source", "return_sink", "signal_transition", "return_transition"]), label: Wa.string().optional(), label_x: Wa.number().finite().optional(), label_y: Wa.number().finite().optional() });
var xL = Wa.discriminatedUnion("target_type", [bL.extend({ target_type: Wa.literal("pcb_port"), pcb_port_id: Wa.string().min(1), layer: yE }), bL.extend({ target_type: Wa.literal("pcb_via"), pcb_via_id: Wa.string().min(1), from_layer: yE, to_layer: yE })]).superRefine((e35, t2) => {
  e35.label_x === undefined != (e35.label_y === undefined) && t2.addIssue({ code: Wa.ZodIssueCode.custom, path: ["label_x"], message: "label_x and label_y must be provided together" }), e35.target_type === "pcb_via" && e35.from_layer === e35.to_layer && t2.addIssue({ code: Wa.ZodIssueCode.custom, path: ["to_layer"], message: "A via transition must connect distinct layers" });
}).describe("A signal/return port or via highlight; markers do not assert measured via-transfer currents");
var vL = Wa.union([AE, hE, EE, cE, lE, aE, uE, dE, vT, gT, _T, bT, fT, PT, ET, AT, LT, FT, jT, VT, $T, YT, XT, HT, kT, OT, gE, xE, pE, WT, ZT, qT, QT, vE, NE, KT, tE, eE, IE, SE, CE, PE, ME, wE, iE, rE, mE, AA, zA, qA, Dk, Lk, zk, $k, Xk, Hk, Vk, Wk, oO, wk, Nk, iO, XO, IO, NO, RO, TO, OO, EO, AO, kO, HO, dO, bO, vO, VO, GO, KO, ek, Bk, ik, rk, sk, ak, mk, ck, lk, hk, dk, pk, LO, BO, FO, jO, tk, nk, ok, $O, YO, rD, sD, aD, cD, fk, gk, _k, yk, bk, xk, vk, Ik, Sk, Fk, jk, Ck, Pk, Gk, kk, Uk, Zk, qk, tD, nD, oD, iD, lD, hD, dD, uD, pD, OE, ZE, YE, XE, HE, VE, FE, $E, qE, WE, kE, QE, KE, JE, iA, rA, sA, aA, cA, lA, yA, hA, uA, pA, _A, mA, gA, _D, xD, CD, yD, RD, OD, BD, lL, hL, mL, yL, xL, jD, $D, ZD, qD, JD, QD, eL, tL, UD, YD, XD, HD, rL, VD, nL, oL]);
var IL = vL;
function SL(e35, t2, n2) {
  if (!t2 || !n2)
    return;
  let o3 = e35.get(t2);
  o3 || (o3 = new Set, e35.set(t2, o3)), o3.add(n2);
  let i3 = e35.get(n2);
  i3 || (i3 = new Set, e35.set(n2, i3)), i3.add(t2);
}
var CL = (e35, t2 = {}) => {
  const n2 = e35;
  let o3 = n2._internal_store;
  if (!o3) {
    o3 = { counts: {}, editCount: 0 }, n2._internal_store = o3;
    for (const e36 of n2) {
      const t3 = e36.type, n3 = e36[`${t3}_id`];
      if (!n3)
        continue;
      const i4 = Number.parseInt(n3.split("_").pop());
      Number.isNaN(i4) || (o3.counts[t3] = Math.max(o3.counts[t3] ?? 0, i4));
    }
  }
  const i3 = new Proxy({}, { get: (e36, r3) => {
    if (r3 === "toArray")
      return () => (n2.editCount = o3.editCount, n2);
    if (r3 === "editCount")
      return o3.editCount;
    if (r3 === "subtree")
      return (e37) => CL(function(e38, t3) {
        if (!t3.subcircuit_id && !t3.source_group_id)
          return [...e38];
        let n3 = t3;
        if (t3.subcircuit_id) {
          const o5 = new Set([t3.subcircuit_id]), i5 = new Map, r5 = new Map;
          for (const t4 of e38)
            if (t4.type === "source_group") {
              const { source_group_id: e39, subcircuit_id: n4 } = t4;
              n4 && r5.set(e39, n4);
              const o6 = t4.parent_source_group_id;
              o6 && (i5.has(o6) || i5.set(o6, []), i5.get(o6).push(e39));
            }
          let s4;
          for (const [e39, n4] of r5)
            if (n4 === t3.subcircuit_id) {
              s4 = e39;
              break;
            }
          if (s4) {
            const e39 = (t4) => {
              const n4 = i5.get(t4) || [];
              for (const t5 of n4) {
                const n5 = r5.get(t5);
                n5 && o5.add(n5), e39(t5);
              }
            };
            e39(s4), n3 = { ...t3, subcircuit_ids: Array.from(o5) };
          }
        }
        const o4 = new Map;
        for (const t4 of e38) {
          const e39 = t4[`${t4.type}_id`];
          typeof e39 == "string" && o4.set(e39, t4);
        }
        const i4 = new Map;
        for (const t4 of e38) {
          const e39 = Object.entries(t4);
          for (const [n4, r5] of e39)
            if (n4 !== "parent_source_group_id") {
              if (n4.endsWith("_id") && typeof r5 == "string")
                SL(i4, t4, o4.get(r5));
              else if (n4.endsWith("_ids") && Array.isArray(r5))
                for (const e40 of r5)
                  typeof e40 == "string" && SL(i4, t4, o4.get(e40));
            }
        }
        const r4 = [], s3 = new Set;
        for (const t4 of e38) {
          let e39 = false;
          (n3.subcircuit_id && ("subcircuit_id" in t4) && t4.subcircuit_id === n3.subcircuit_id || n3.subcircuit_ids && ("subcircuit_id" in t4) && t4.subcircuit_id && n3.subcircuit_ids.includes(t4.subcircuit_id) || n3.source_group_id && ("source_group_id" in t4) && t4.source_group_id === n3.source_group_id || n3.source_group_id && ("member_source_group_ids" in t4) && Array.isArray(t4.member_source_group_ids) && t4.member_source_group_ids.includes(n3.source_group_id)) && (e39 = true), e39 && (r4.push(t4), s3.add(t4));
        }
        for (;r4.length > 0; ) {
          const e39 = r4.shift(), t4 = i4.get(e39);
          if (t4)
            for (const e40 of t4)
              s3.has(e40) || (s3.add(e40), r4.push(e40));
        }
        return e38.filter((e39) => s3.has(e39));
      }(n2, e37), t2);
    if (r3 === "insert")
      return (e37) => {
        const i4 = e37.type;
        if (!i4)
          throw new Error("insert requires an element with a type");
        o3.counts[i4] ??= -1, o3.counts[i4]++;
        const r4 = o3.counts[i4], s3 = { ...e37, type: i4, [`${i4}_id`]: `${i4}_${r4}` };
        if (t2.validateInserts) {
          (uR[i4] ?? IL).parse(s3);
        }
        return n2.push(s3), o3.editCount++, s3;
      };
    if (r3 === "insertAll")
      return (e37) => e37.map((e38) => i3.insert(e38));
    const s2 = r3;
    return { get: (e37) => n2.find((t3) => t3.type === s2 && t3[`${s2}_id`] === e37), getUsing: (e37) => {
      const t3 = Object.keys(e37);
      if (t3.length !== 1)
        throw new Error("getUsing requires exactly one key, e.g. { pcb_component_id }");
      const o4 = t3[0], i4 = o4.replace("_id", ""), r4 = n2.find((t4) => t4.type === i4 && t4[o4] === e37[o4]);
      return r4 ? n2.find((e38) => e38.type === s2 && e38[`${s2}_id`] === r4[`${s2}_id`]) : null;
    }, getWhere: (e37) => {
      const t3 = Object.keys(e37);
      return n2.find((n3) => n3.type === s2 && t3.every((t4) => n3[t4] === e37[t4]));
    }, list: (e37) => {
      const t3 = e37 ? Object.keys(e37) : [];
      return n2.filter((n3) => n3.type === s2 && t3.every((t4) => n3[t4] === e37[t4]));
    }, insert: (e37) => {
      o3.counts[s2] ??= -1, o3.counts[s2]++;
      const i4 = o3.counts[s2], r4 = { type: s2, [`${s2}_id`]: `${s2}_${i4}`, ...e37 };
      if (t2.validateInserts) {
        (uR[s2] ?? IL).parse(r4);
      }
      return n2.push(r4), o3.editCount++, r4;
    }, delete: (e37) => {
      const t3 = n2.find((t4) => t4[`${s2}_id`] === e37);
      t3 && (n2.splice(n2.indexOf(t3), 1), o3.editCount++);
    }, update: (e37, t3) => {
      const i4 = n2.find((t4) => t4.type === s2 && t4[`${s2}_id`] === e37);
      return i4 ? (Object.assign(i4, t3), o3.editCount++, i4) : null;
    }, select: (e37) => {
      if (s2 === "source_component")
        return n2.find((t3) => t3.type === "source_component" && t3.name === e37.replace(/\./g, ""));
      if (s2 === "pcb_port" || s2 === "source_port" || s2 === "schematic_port") {
        const [t3, o4] = e37.replace(/\./g, "").split(/[\s\>]+/), i4 = n2.find((e38) => e38.type === "source_component" && e38.name === t3);
        if (!i4)
          return null;
        const r4 = n2.find((e38) => e38.type === "source_port" && e38.source_component_id === i4.source_component_id && (e38.name === o4 || (e38.port_hints ?? []).includes(o4)));
        if (!r4)
          return null;
        if (s2 === "source_port")
          return r4;
        if (s2 === "pcb_port")
          return n2.find((e38) => e38.type === "pcb_port" && e38.source_port_id === r4.source_port_id);
        if (s2 === "schematic_port")
          return n2.find((e38) => e38.type === "schematic_port" && e38.source_port_id === r4.source_port_id);
      }
    } };
  } });
  return i3;
};
function PL(e35) {
  const t2 = e35.type;
  return `${t2}:${e35[`${t2}_id`]}`;
}
CL.unparsed = CL;
var ML = (e35, t2 = {}) => {
  let n2 = e35._internal_store_indexed;
  if (!n2) {
    n2 = { counts: {}, editCount: 0, indexes: {} };
    for (const t3 of e35) {
      const e36 = t3.type, o4 = t3[`${e36}_id`];
      if (!o4)
        continue;
      const i4 = Number.parseInt(o4.split("_").pop() || "");
      Number.isNaN(i4) || (n2.counts[e36] = Math.max(n2.counts[e36] ?? 0, i4));
    }
    const o3 = t2.indexConfig || {}, i3 = n2.indexes;
    if (o3.byId && (i3.byId = new Map), o3.byType && (i3.byType = new Map), o3.byRelation && (i3.byRelation = new Map), o3.bySubcircuit && (i3.bySubcircuit = new Map), o3.byCustomField && o3.byCustomField.length > 0) {
      i3.byCustomField = new Map;
      for (const e36 of o3.byCustomField)
        i3.byCustomField.set(e36, new Map);
    }
    for (const t3 of e35) {
      if (o3.byId) {
        const e36 = PL(t3);
        i3.byId.set(e36, t3);
      }
      if (o3.byType) {
        const e36 = i3.byType.get(t3.type) || [];
        e36.push(t3), i3.byType.set(t3.type, e36);
      }
      if (o3.byRelation) {
        const e36 = Object.entries(t3);
        for (const [n3, o4] of e36)
          if (n3.endsWith("_id") && n3 !== `${t3.type}_id` && typeof o4 == "string") {
            const e37 = i3.byRelation.get(n3) || new Map, r3 = e37.get(o4) || [];
            r3.push(t3), e37.set(o4, r3), i3.byRelation.set(n3, e37);
          }
      }
      if (o3.bySubcircuit && "subcircuit_id" in t3) {
        const e36 = t3.subcircuit_id;
        if (e36 && typeof e36 == "string") {
          const n3 = i3.bySubcircuit.get(e36) || [];
          n3.push(t3), i3.bySubcircuit.set(e36, n3);
        }
      }
      if (o3.byCustomField && i3.byCustomField) {
        for (const e36 of o3.byCustomField)
          if (e36 in t3) {
            const n3 = t3[e36];
            if (n3 !== undefined && (typeof n3 == "string" || typeof n3 == "number")) {
              const o4 = String(n3), r3 = i3.byCustomField.get(e36), s2 = r3.get(o4) || [];
              s2.push(t3), r3.set(o4, s2);
            }
          }
      }
    }
    e35._internal_store_indexed = n2;
  }
  return new Proxy({}, { get: (o3, i3) => {
    if (i3 === "toArray")
      return () => (e35.editCount = n2.editCount, e35);
    if (i3 === "editCount")
      return n2.editCount;
    const r3 = i3;
    return { get: (o4) => {
      const i4 = t2.indexConfig || {};
      if (i4.byId && n2.indexes.byId)
        return n2.indexes.byId.get(`${r3}:${o4}`) || null;
      if (i4.byType && n2.indexes.byType) {
        return (n2.indexes.byType.get(r3) || []).find((e36) => e36[`${r3}_id`] === o4) || null;
      }
      return e35.find((e36) => e36.type === r3 && e36[`${r3}_id`] === o4) || null;
    }, getUsing: (o4) => {
      const i4 = t2.indexConfig || {}, s2 = Object.keys(o4);
      if (s2.length !== 1)
        throw new Error("getUsing requires exactly one key, e.g. { pcb_component_id }");
      const a3 = s2[0], c3 = a3.replace("_id", "");
      if (i4.byRelation && n2.indexes.byRelation) {
        const t3 = n2.indexes.byRelation.get(a3);
        if (t3) {
          const s3 = (t3.get(o4[a3]) || []).find((e36) => e36.type === c3);
          if (!s3)
            return null;
          const l4 = s3[`${r3}_id`];
          if (i4.byId && n2.indexes.byId)
            return n2.indexes.byId.get(`${r3}:${l4}`) || null;
          if (i4.byType && n2.indexes.byType) {
            return (n2.indexes.byType.get(r3) || []).find((e36) => e36[`${r3}_id`] === l4) || null;
          }
          return e35.find((e36) => e36.type === r3 && e36[`${r3}_id`] === l4) || null;
        }
      }
      const l3 = e35.find((e36) => e36.type === c3 && e36[a3] === o4[a3]);
      return l3 && e35.find((e36) => e36.type === r3 && e36[`${r3}_id`] === l3[`${r3}_id`]) || null;
    }, getWhere: (o4) => {
      const i4 = t2.indexConfig || {}, s2 = Object.keys(o4);
      if (s2.length === 1 && i4.byCustomField && n2.indexes.byCustomField) {
        const e36 = s2[0], t3 = n2.indexes.byCustomField.get(e36);
        if (t3) {
          const n3 = String(o4[e36]);
          return (t3.get(n3) || []).find((e37) => e37.type === r3) || null;
        }
      }
      if ("subcircuit_id" in o4 && i4.bySubcircuit && n2.indexes.bySubcircuit) {
        const e36 = o4.subcircuit_id;
        return (n2.indexes.bySubcircuit.get(e36) || []).find((e37) => e37.type === r3 && s2.every((t3) => e37[t3] === o4[t3])) || null;
      }
      if (i4.byType && n2.indexes.byType) {
        return (n2.indexes.byType.get(r3) || []).find((e36) => s2.every((t3) => e36[t3] === o4[t3])) || null;
      }
      return e35.find((e36) => e36.type === r3 && s2.every((t3) => e36[t3] === o4[t3])) || null;
    }, list: (o4) => {
      const i4 = t2.indexConfig || {}, s2 = o4 ? Object.keys(o4) : [];
      if (s2.length === 0 && i4.byType && n2.indexes.byType)
        return n2.indexes.byType.get(r3) || [];
      if (s2.length === 1 && s2[0] === "subcircuit_id" && i4.bySubcircuit && n2.indexes.bySubcircuit) {
        const e36 = o4.subcircuit_id;
        return (n2.indexes.bySubcircuit.get(e36) || []).filter((e37) => e37.type === r3);
      }
      let a3;
      return a3 = i4.byType && n2.indexes.byType ? n2.indexes.byType.get(r3) || [] : e35.filter((e36) => e36.type === r3), s2.length > 0 ? a3.filter((e36) => s2.every((t3) => e36[t3] === o4[t3])) : a3;
    }, insert: (o4) => {
      n2.counts[r3] ??= -1, n2.counts[r3]++;
      const i4 = n2.counts[r3], s2 = { type: r3, [`${r3}_id`]: `${r3}_${i4}`, ...o4 };
      if (t2.validateInserts) {
        (uR[r3] ?? IL).parse(s2);
      }
      e35.push(s2), n2.editCount++;
      const a3 = t2.indexConfig || {};
      if (a3.byId && n2.indexes.byId) {
        const e36 = PL(s2);
        n2.indexes.byId.set(e36, s2);
      }
      if (a3.byType && n2.indexes.byType) {
        const e36 = n2.indexes.byType.get(r3) || [];
        e36.push(s2), n2.indexes.byType.set(r3, e36);
      }
      if (a3.byRelation && n2.indexes.byRelation) {
        const e36 = Object.entries(s2);
        for (const [t3, o5] of e36)
          if (t3.endsWith("_id") && t3 !== `${s2.type}_id` && typeof o5 == "string") {
            const e37 = n2.indexes.byRelation.get(t3) || new Map, i5 = e37.get(o5) || [];
            i5.push(s2), e37.set(o5, i5), n2.indexes.byRelation.set(t3, e37);
          }
      }
      if (a3.bySubcircuit && n2.indexes.bySubcircuit && "subcircuit_id" in s2) {
        const e36 = s2.subcircuit_id;
        if (e36 && typeof e36 == "string") {
          const t3 = n2.indexes.bySubcircuit.get(e36) || [];
          t3.push(s2), n2.indexes.bySubcircuit.set(e36, t3);
        }
      }
      if (a3.byCustomField && n2.indexes.byCustomField) {
        for (const e36 of a3.byCustomField)
          if (e36 in s2) {
            const t3 = s2[e36];
            if (t3 !== undefined && (typeof t3 == "string" || typeof t3 == "number")) {
              const o5 = String(t3), i5 = n2.indexes.byCustomField.get(e36), r4 = i5.get(o5) || [];
              r4.push(s2), i5.set(o5, r4);
            }
          }
      }
      return s2;
    }, delete: (o4) => {
      const i4 = t2.indexConfig || {};
      let s2;
      if (i4.byId && n2.indexes.byId)
        s2 = n2.indexes.byId.get(`${r3}:${o4}`);
      else if (i4.byType && n2.indexes.byType) {
        const e36 = n2.indexes.byType.get(r3) || [];
        s2 = e36.find((e37) => e37[`${r3}_id`] === o4);
      } else
        s2 = e35.find((e36) => e36[`${r3}_id`] === o4);
      if (!s2)
        return;
      const a3 = e35.indexOf(s2);
      if (a3 >= 0 && (e35.splice(a3, 1), n2.editCount++), i4.byId && n2.indexes.byId) {
        const e36 = PL(s2);
        n2.indexes.byId.delete(e36);
      }
      if (i4.byType && n2.indexes.byType) {
        const e36 = (n2.indexes.byType.get(r3) || []).filter((e37) => e37[`${r3}_id`] !== o4);
        n2.indexes.byType.set(r3, e36);
      }
      if (i4.byRelation && n2.indexes.byRelation)
        for (const [e36, t3] of n2.indexes.byRelation.entries())
          for (const [e37, n3] of t3.entries()) {
            const o5 = n3.filter((e38) => e38 !== s2);
            o5.length === 0 ? t3.delete(e37) : t3.set(e37, o5);
          }
      if (i4.bySubcircuit && n2.indexes.bySubcircuit && "subcircuit_id" in s2) {
        const e36 = s2.subcircuit_id;
        if (e36) {
          const t3 = (n2.indexes.bySubcircuit.get(e36) || []).filter((e37) => e37 !== s2);
          t3.length === 0 ? n2.indexes.bySubcircuit.delete(e36) : n2.indexes.bySubcircuit.set(e36, t3);
        }
      }
      if (i4.byCustomField && n2.indexes.byCustomField)
        for (const e36 of n2.indexes.byCustomField.values())
          for (const [t3, n3] of e36.entries()) {
            const o5 = n3.filter((e37) => e37 !== s2);
            o5.length === 0 ? e36.delete(t3) : e36.set(t3, o5);
          }
    }, update: (o4, i4) => {
      const s2 = t2.indexConfig || {};
      let a3;
      if (s2.byId && n2.indexes.byId)
        a3 = n2.indexes.byId.get(`${r3}:${o4}`);
      else if (s2.byType && n2.indexes.byType) {
        const e36 = n2.indexes.byType.get(r3) || [];
        a3 = e36.find((e37) => e37[`${r3}_id`] === o4);
      } else
        a3 = e35.find((e36) => e36.type === r3 && e36[`${r3}_id`] === o4);
      if (!a3)
        return null;
      if (s2.byRelation && n2.indexes.byRelation) {
        const e36 = Object.entries(a3);
        for (const [t3, o5] of e36)
          if (t3.endsWith("_id") && t3 !== `${a3.type}_id` && typeof o5 == "string" && t3 in i4 && i4[t3] !== o5) {
            const e37 = n2.indexes.byRelation.get(t3);
            if (e37) {
              const t4 = (e37.get(o5) || []).filter((e38) => e38 !== a3);
              t4.length === 0 ? e37.delete(o5) : e37.set(o5, t4);
            }
          }
      }
      if (s2.bySubcircuit && n2.indexes.bySubcircuit && "subcircuit_id" in a3 && "subcircuit_id" in i4) {
        const e36 = a3.subcircuit_id;
        if (e36 !== i4.subcircuit_id) {
          const t3 = (n2.indexes.bySubcircuit.get(e36) || []).filter((e37) => e37 !== a3);
          t3.length === 0 ? n2.indexes.bySubcircuit.delete(e36) : n2.indexes.bySubcircuit.set(e36, t3);
        }
      }
      if (s2.byCustomField && n2.indexes.byCustomField) {
        for (const e36 of s2.byCustomField)
          if (e36 in a3 && e36 in i4 && a3[e36] !== i4[e36]) {
            const t3 = n2.indexes.byCustomField.get(e36);
            if (t3) {
              const n3 = String(a3[e36]), o5 = (t3.get(n3) || []).filter((e37) => e37 !== a3);
              o5.length === 0 ? t3.delete(n3) : t3.set(n3, o5);
            }
          }
      }
      if (Object.assign(a3, i4), n2.editCount++, s2.byRelation && n2.indexes.byRelation) {
        const e36 = Object.entries(a3);
        for (const [t3, o5] of e36)
          if (t3.endsWith("_id") && t3 !== `${a3.type}_id` && typeof o5 == "string" && t3 in i4) {
            const e37 = n2.indexes.byRelation.get(t3) || new Map, i5 = e37.get(o5) || [];
            i5.includes(a3) || (i5.push(a3), e37.set(o5, i5), n2.indexes.byRelation.set(t3, e37));
          }
      }
      if (s2.bySubcircuit && n2.indexes.bySubcircuit && "subcircuit_id" in a3 && "subcircuit_id" in i4) {
        const e36 = a3.subcircuit_id;
        if (e36 && typeof e36 == "string") {
          const t3 = n2.indexes.bySubcircuit.get(e36) || [];
          t3.includes(a3) || (t3.push(a3), n2.indexes.bySubcircuit.set(e36, t3));
        }
      }
      if (s2.byCustomField && n2.indexes.byCustomField) {
        for (const e36 of s2.byCustomField)
          if (e36 in a3 && e36 in i4) {
            const t3 = a3[e36];
            if (t3 !== undefined && (typeof t3 == "string" || typeof t3 == "number")) {
              const o5 = String(t3), i5 = n2.indexes.byCustomField.get(e36), r4 = i5.get(o5) || [];
              r4.includes(a3) || (r4.push(a3), i5.set(o5, r4));
            }
          }
      }
      return a3;
    }, select: (t3) => {
      if (r3 === "source_component")
        return e35.find((e36) => e36.type === "source_component" && e36.name === t3.replace(/\./g, "")) || null;
      if (r3 === "pcb_port" || r3 === "source_port" || r3 === "schematic_port") {
        const [n3, o4] = t3.replace(/\./g, "").split(/[\s\>]+/), i4 = e35.find((e36) => e36.type === "source_component" && e36.name === n3);
        if (!i4)
          return null;
        const s2 = e35.find((e36) => e36.type === "source_port" && e36.source_component_id === i4.source_component_id && (e36.name === o4 || (e36.port_hints ?? []).includes(o4)));
        if (!s2)
          return null;
        if (r3 === "source_port")
          return s2;
        if (r3 === "pcb_port")
          return e35.find((e36) => e36.type === "pcb_port" && e36.source_port_id === s2.source_port_id) || null;
        if (r3 === "schematic_port")
          return e35.find((e36) => e36.type === "schematic_port" && e36.source_port_id === s2.source_port_id) || null;
      }
      return null;
    } };
  } });
};
ML.unparsed = ML;
var wL = (e35) => e35[`${e35.type}_id`];
var NL = (e35, t2) => {
  const n2 = CL(e35).pcb_port.get(t2);
  if (!n2)
    return `pcb_port[#${t2}]`;
  const o3 = n2.pcb_component_id ? CL(e35).pcb_component.get(n2.pcb_component_id) : undefined;
  if (!o3)
    return `pcb_port[#${t2}]`;
  const i3 = CL(e35).source_component.get(o3.source_component_id);
  if (!i3)
    return `pcb_port[#${t2}]`;
  const r3 = CL(e35).source_port.get(n2.source_port_id);
  if (!r3)
    return `pcb_port[#${t2}]`;
  let s2;
  return s2 = r3?.port_hints && r3.port_hints.length > 0 || r3.port_hints && r3.port_hints.length > 0 ? r3.port_hints[0] : t2, `pcb_port[.${i3.name} > .${s2}]`;
};
function RL(e35, t2) {
  const n2 = CL(e35).pcb_trace.get(t2);
  if (!n2)
    return `trace[${t2}]`;
  const o3 = n2.route.flatMap((e36) => [e36.start_pcb_port_id, e36.end_pcb_port_id]).filter(Boolean);
  if (o3.length === 0)
    return `trace[${t2}]`;
  return `trace[${o3.map((t3) => {
    const n3 = function(t4) {
      const n4 = CL(e35).pcb_port.get(t4);
      if (!n4)
        return null;
      const o4 = n4.pcb_component_id ? CL(e35).pcb_component.get(n4.pcb_component_id) : undefined;
      if (!o4)
        return null;
      const i3 = CL(e35).source_component.get(o4.source_component_id);
      if (!i3)
        return null;
      const r3 = CL(e35).source_port.get(n4.source_port_id), s2 = r3?.port_hints ? r3.port_hints[1] : "";
      return { componentName: i3.name, portHint: s2 };
    }(t3);
    return n3 ? `.${n3.componentName} > port.${n3.portHint}` : `port[${t3}]`;
  }).join(", ")}]`;
}
var TL = (e35, t2) => {
  if (typeof t2 == "string") {
    const n2 = ((e36, t3) => e36.find((e37) => wL(e37) === t3) ?? null)(e35, t2);
    return TL(e35, n2);
  }
  switch (t2.type) {
    case "pcb_port":
      return NL(e35, t2.pcb_port_id);
    case "pcb_smtpad":
      return function(e36, t3) {
        const n2 = CL(e36).pcb_smtpad.get(t3);
        return n2 && n2.pcb_port_id ? NL(e36, n2.pcb_port_id) : `smtpad[${t3}]`;
      }(e35, t2.pcb_smtpad_id);
    case "pcb_trace":
      return RL(e35, t2.pcb_trace_id);
    case "source_component":
      return `source_component[${t2.name}]`;
    default:
      return `${t2.type}[#${wL(t2)}]`;
  }
};
var EL = (e35, t2) => ({ minX: Math.min(e35.minX, t2.minX), minY: Math.min(e35.minY, t2.minY), maxX: Math.max(e35.maxX, t2.maxX), maxY: Math.max(e35.maxY, t2.maxY) });
var AL = (e35, t2, n2) => {
  const o3 = n2 / 2;
  return { minX: e35 - o3, minY: t2 - o3, maxX: e35 + o3, maxY: t2 + o3 };
};
var OL = (e35, t2, n2, o3, i3) => {
  const r3 = n2 / 2, s2 = o3 / 2, a3 = i3 * Math.PI / 180, c3 = Math.cos(a3), l3 = Math.sin(a3), h2 = [{ x: -r3, y: -s2 }, { x: r3, y: -s2 }, { x: r3, y: s2 }, { x: -r3, y: s2 }].map((n3) => ({ x: e35 + n3.x * c3 - n3.y * l3, y: t2 + n3.x * l3 + n3.y * c3 }));
  return { minX: Math.min(...h2.map((e36) => e36.x)), minY: Math.min(...h2.map((e36) => e36.y)), maxX: Math.max(...h2.map((e36) => e36.x)), maxY: Math.max(...h2.map((e36) => e36.y)) };
};
var kL = (e35, t2, n2, o3, i3) => {
  const r3 = n2 / 2, s2 = o3 / 2, a3 = i3 * Math.PI / 180, c3 = Math.cos(a3), l3 = Math.sin(a3), h2 = Math.hypot(r3 * c3, s2 * l3), d2 = Math.hypot(r3 * l3, s2 * c3);
  return { minX: e35 - h2, minY: t2 - d2, maxX: e35 + h2, maxY: t2 + d2 };
};
var DL = (e35, t2, n2, o3, i3) => {
  const r3 = Math.min(n2, o3) / 2, s2 = Math.max(n2, o3) / 2 - r3, a3 = i3 * Math.PI / 180, c3 = n2 >= o3 ? { x: s2, y: 0 } : { x: 0, y: s2 }, l3 = { x: c3.x * Math.cos(a3) - c3.y * Math.sin(a3), y: c3.x * Math.sin(a3) + c3.y * Math.cos(a3) }, h2 = Math.abs(l3.x) + r3, d2 = Math.abs(l3.y) + r3;
  return { minX: e35 - h2, minY: t2 - d2, maxX: e35 + h2, maxY: t2 + d2 };
};
var LL = (e35) => e35.length === 0 ? null : { minX: Math.min(...e35.map((e36) => e36.x)), minY: Math.min(...e35.map((e36) => e36.y)), maxX: Math.max(...e35.map((e36) => e36.x)), maxY: Math.max(...e35.map((e36) => e36.y)) };
var zL = (e35) => Array.isArray(e35) ? e35.flatMap((e36) => {
  if (!e36 || typeof e36 != "object")
    return [];
  if ("x" in e36 && "y" in e36 && typeof e36.x == "number" && typeof e36.y == "number")
    return [{ x: e36.x, y: e36.y }];
  if ("start" in e36 && "end" in e36) {
    return [e36.start, e36.end].filter((e37) => Boolean(e37 && typeof e37 == "object" && "x" in e37 && "y" in e37 && typeof e37.x == "number" && typeof e37.y == "number"));
  }
  return [];
}) : [];
var BL = (e35) => {
  if (!e35.type.startsWith("pcb_"))
    return null;
  if (e35.type === "pcb_smtpad" && e35.shape === "polygon" && Array.isArray(e35.points))
    return LL(e35.points);
  if (e35.type === "pcb_hole" && e35.hole_shape === "circle")
    return AL(e35.x, e35.y, e35.hole_diameter);
  if (e35.type === "pcb_plated_hole") {
    let t3;
    if ("outer_diameter" in e35 && typeof e35.outer_diameter == "number" ? t3 = AL(e35.x, e35.y, e35.outer_diameter) : ("hole_diameter" in e35) && typeof e35.hole_diameter == "number" && (t3 = AL(e35.x, e35.y, e35.hole_diameter)), (e35.shape === "oval" || e35.shape === "pill") && typeof e35.outer_width == "number" && typeof e35.outer_height == "number") {
      t3 = (e35.shape === "pill" ? DL : kL)(e35.x, e35.y, e35.outer_width, e35.outer_height, e35.ccw_rotation ?? 0);
    }
    if ("rect_pad_width" in e35 && typeof e35.rect_pad_width == "number" && "rect_pad_height" in e35 && typeof e35.rect_pad_height == "number") {
      const n3 = OL(e35.x, e35.y, e35.rect_pad_width, e35.rect_pad_height, "rect_ccw_rotation" in e35 ? e35.rect_ccw_rotation ?? 0 : 0);
      t3 = t3 ? EL(t3, n3) : n3;
    }
    if ("hole_diameter" in e35 && typeof e35.hole_diameter == "number") {
      const n3 = AL(e35.x + ("hole_offset_x" in e35 ? e35.hole_offset_x ?? 0 : 0), e35.y + ("hole_offset_y" in e35 ? e35.hole_offset_y ?? 0 : 0), e35.hole_diameter);
      t3 = t3 ? EL(t3, n3) : n3;
    }
    if (t3)
      return t3;
  }
  const t2 = e35, n2 = LL(zL(t2.route));
  if (n2)
    return n2;
  const o3 = LL(zL(t2.outline));
  if (o3)
    return o3;
  const i3 = LL(zL(t2.points));
  if (i3)
    return i3;
  let r3, s2, a3, c3;
  "x" in e35 && "y" in e35 && (r3 = Number(e35.x), s2 = Number(e35.y)), "outer_diameter" in e35 && (a3 = Number(e35.outer_diameter), c3 = Number(e35.outer_diameter)), "width" in e35 && (a3 = Number(e35.width)), "height" in e35 && (c3 = Number(e35.height)), "center" in e35 && e35.center && typeof e35.center == "object" && "x" in e35.center && "y" in e35.center && (r3 = Number(e35.center.x), s2 = Number(e35.center.y));
  let l3 = 0;
  if ("rotation" in e35 && typeof e35.rotation == "number" && (l3 = e35.rotation), "ccw_rotation" in e35 && typeof e35.ccw_rotation == "number" && (l3 = e35.ccw_rotation), r3 !== undefined && s2 !== undefined)
    return a3 !== undefined && c3 !== undefined ? l3 ? OL(r3, s2, a3, c3, l3) : { minX: r3 - a3 / 2, minY: s2 - c3 / 2, maxX: r3 + a3 / 2, maxY: s2 + c3 / 2 } : ("radius" in e35) && typeof e35.radius == "number" ? AL(r3, s2, 2 * e35.radius) : { minX: r3, minY: s2, maxX: r3, maxY: s2 };
  const h2 = [t2.anchor_position, t2.position].filter((e36) => Boolean(e36 && typeof e36 == "object" && "x" in e36 && "y" in e36 && typeof e36.x == "number" && typeof e36.y == "number")).at(0);
  return h2 ? { minX: h2.x, minY: h2.y, maxX: h2.x, maxY: h2.y } : null;
};
var FL = (e35) => {
  let t2 = { minX: Number.POSITIVE_INFINITY, minY: Number.POSITIVE_INFINITY, maxX: Number.NEGATIVE_INFINITY, maxY: Number.NEGATIVE_INFINITY };
  for (const n2 of e35) {
    const e36 = BL(n2);
    e36 && (t2 = EL(t2, e36));
  }
  return t2;
};
var jL = (e35) => e35[`${e35.type}_id`];
var $L = 0.000000001;
var YL = (e35, t2, n2) => {
  const o3 = n2.x - t2.x, i3 = n2.y - t2.y, r3 = o3 * o3 + i3 * i3;
  if (r3 <= $L)
    return ((e36, t3) => Math.hypot(e36.x - t3.x, e36.y - t3.y))(e35, t2);
  const s2 = (a3 = ((e35.x - t2.x) * o3 + (e35.y - t2.y) * i3) / r3, c3 = 0, l3 = 1, Math.max(c3, Math.min(l3, a3)));
  var a3, c3, l3;
  return Math.hypot(e35.x - (t2.x + s2 * o3), e35.y - (t2.y + s2 * i3));
};
var XL = (e35, t2, n2) => !(Math.abs(((e36, t3, n3) => (t3.x - e36.x) * (n3.y - e36.y) - (t3.y - e36.y) * (n3.x - e36.x))(t2, n2, e35)) > $L) && (e35.x >= Math.min(t2.x, n2.x) - $L && e35.x <= Math.max(t2.x, n2.x) + $L && e35.y >= Math.min(t2.y, n2.y) - $L && e35.y <= Math.max(t2.y, n2.y) + $L);
var HL = (e35) => {
  const t2 = [];
  if (e35.points.length < 2)
    return t2;
  for (let n2 = 0;n2 < e35.points.length; n2 += 1) {
    const o3 = e35.points[n2], i3 = e35.points[(n2 + 1) % e35.points.length];
    o3 && i3 && t2.push([o3, i3]);
  }
  return t2;
};
var VL = (e35, t2) => Math.max(0, Math.hypot(e35.x - t2.x, e35.y - t2.y) - e35.radius - t2.radius);
var WL = (e35, t2) => {
  if (t2.points.length < 3)
    return Number.POSITIVE_INFINITY;
  if (((e36, t3) => {
    for (const [n4, o3] of HL(t3))
      if (XL(e36, n4, o3))
        return true;
    let n3 = false;
    for (let o3 = 0, i3 = t3.points.length - 1;o3 < t3.points.length; i3 = o3++) {
      const r3 = t3.points[o3], s2 = t3.points[i3];
      r3 && s2 && (r3.y > e36.y != s2.y > e36.y && e36.x < (s2.x - r3.x) * (e36.y - r3.y) / (s2.y - r3.y) + r3.x && (n3 = !n3));
    }
    return n3;
  })({ x: e35.x, y: e35.y }, t2))
    return 0;
  let n2 = Number.POSITIVE_INFINITY;
  for (const [o3, i3] of HL(t2))
    n2 = Math.min(n2, YL({ x: e35.x, y: e35.y }, o3, i3));
  return Math.max(0, n2 - e35.radius);
};
var GL = (Object.keys({ leftside_top: { side: "leftside", alignment: "top" }, leftside_bottom: { side: "leftside", alignment: "bottom" }, rightside_top: { side: "rightside", alignment: "top" }, rightside_bottom: { side: "rightside", alignment: "bottom" }, topside_left: { side: "topside", alignment: "left" }, topside_right: { side: "topside", alignment: "right" }, bottomside_left: { side: "bottomside", alignment: "left" }, bottomside_right: { side: "bottomside", alignment: "right" } }), (e35, t2, n2 = 0) => {
  const { a: o3, b: i3, c: r3, d: s2, e: a3, f: c3 } = Zt(Gt(t2.x, t2.y), Kt(n2 * Math.PI / 180));
  return e35.transform(new f_(o3, i3, r3, s2, a3, c3));
});
var UL = (e35) => e35.orientation() === Cg.CCW ? e35 : e35.reverse();
var ZL = (e35, t2) => UL(new D_(new E_(new S_(e35.x, e35.y), t2)));
var qL = (e35, t2, n2, o3 = 0, i3 = 0) => {
  const r3 = t2 / 2, s2 = n2 / 2, a3 = Math.max(0, Math.min(o3, r3, s2));
  if (a3 === 0)
    return GL(UL(new D_(new O_(-r3, -s2, r3, s2))), e35, i3);
  const c3 = [new A_(new S_(r3 - a3, -s2 + a3), a3, -Math.PI / 2, 0, true), new A_(new S_(r3 - a3, s2 - a3), a3, 0, Math.PI / 2, true), new A_(new S_(-r3 + a3, s2 - a3), a3, Math.PI / 2, Math.PI, true), new A_(new S_(-r3 + a3, -s2 + a3), a3, Math.PI, 1.5 * Math.PI, true)], l3 = [];
  for (let e36 = 0;e36 < c3.length; e36++) {
    const t3 = c3[e36], n3 = c3[(e36 + 1) % c3.length];
    l3.push(t3), t3.end.distanceTo(n3.start)[0] > 0.000000000001 && l3.push(new w_(t3.end, n3.start));
  }
  return GL(UL(new D_(l3)), e35, i3);
};
var JL = (e35, t2) => {
  for (const n2 of t2.reverse().faces)
    e35.addFace(n2.shapes);
  return e35;
};
var QL = (e35, t2 = 0) => {
  if (e35.shape === "circle")
    return ((e36, t3, n3) => JL(ZL(e36, t3 / 2), ZL(e36, n3 / 2)))(e35, e35.outer_diameter, e35.hole_diameter);
  if ("outer_width" in e35)
    return JL(qL(e35, e35.outer_width, e35.outer_height, Math.min(e35.outer_width, e35.outer_height) / 2, e35.ccw_rotation), qL(e35, e35.hole_width, e35.hole_height, Math.min(e35.hole_width, e35.hole_height) / 2, e35.ccw_rotation));
  const n2 = { x: e35.x + e35.hole_offset_x, y: e35.y + e35.hole_offset_y }, o3 = e35.shape === "hole_with_polygon_pad" ? GL(UL(new D_(e35.pad_outline.map((e36) => new S_(e36.x, e36.y)))), e35, e35.ccw_rotation ?? t2) : qL(e35, e35.rect_pad_width, e35.rect_pad_height, e35.rect_border_radius, "rect_ccw_rotation" in e35 ? e35.rect_ccw_rotation : 0);
  if (e35.shape === "circular_hole_with_rect_pad" || e35.shape === "hole_with_polygon_pad" && e35.hole_shape === "circle") {
    if (e35.hole_diameter === undefined)
      throw new Error("Circular plated hole requires hole_diameter");
    return JL(o3, ZL(n2, e35.hole_diameter / 2));
  }
  if (!("hole_width" in e35) || e35.hole_width === undefined || e35.hole_height === undefined)
    throw new Error("Slotted plated hole requires hole_width and hole_height");
  return JL(o3, qL(n2, e35.hole_width, e35.hole_height, Math.min(e35.hole_width, e35.hole_height) / 2, "hole_ccw_rotation" in e35 ? e35.hole_ccw_rotation : e35.shape === "hole_with_polygon_pad" ? e35.ccw_rotation ?? t2 : 0));
};
var KL = (e35, t2, n2, o3 = n2) => {
  const i3 = Math.hypot(t2.x - e35.x, t2.y - e35.y), r3 = n2 / 2, s2 = o3 / 2;
  if (i3 <= Math.abs(s2 - r3))
    return ZL(r3 >= s2 ? e35 : t2, Math.max(r3, s2));
  const a3 = Math.atan2(t2.y - e35.y, t2.x - e35.x), c3 = Math.acos((r3 - s2) / i3), l3 = new A_(new S_(e35.x, e35.y), r3, a3 + c3, a3 - c3, true), h2 = new A_(new S_(t2.x, t2.y), s2, a3 - c3, a3 + c3, true);
  return UL(new D_([l3, new w_(l3.end, h2.start), h2, new w_(h2.end, l3.start)]));
};
var ez = (e35, t2, n2 = 0.0000001) => e35.vertices.some((e36) => t2.contains(e36)) || t2.vertices.some((t3) => e35.contains(t3)) || e35.distanceTo(t2)[0] <= n2;
var tz = (e35, t2) => {
  for (const n2 of e35)
    if (n2 && n2 !== t2 && !(t2.length > 0 && n2.includes(t2)) && !/\b(?:pcb|source|schematic|subcircuit)_[a-z0-9_]+\b/i.test(n2))
      return n2;
  return "";
};
var nz = (e35, t2) => {
  const n2 = e35.find((e36) => e36.type === "pcb_port" && e36.pcb_port_id === t2);
  if (n2?.type !== "pcb_port")
    return "unnamed port";
  const o3 = e35.find((e36) => e36.type === "source_port" && e36.source_port_id === n2.source_port_id);
  if (o3?.type !== "source_port")
    return "unnamed port";
  const i3 = e35.find((e36) => e36.type === "source_component" && e36.source_component_id === o3.source_component_id), r3 = i3?.type === "source_component" ? tz([i3.name], i3.source_component_id) : "", s2 = tz([o3.name, o3.pin_number?.toString(), o3.port_hints?.[0]], o3.source_port_id);
  return r3 && s2 ? `${r3}.${s2}` : s2 || "unnamed port";
};
var oz = (e35, t2) => {
  const n2 = e35.find((e36) => e36.type === "pcb_trace" && e36.pcb_trace_id === t2);
  if (n2?.type !== "pcb_trace")
    return "unnamed trace";
  const o3 = e35.find((e36) => e36.type === "source_trace" && e36.source_trace_id === n2.source_trace_id);
  if (o3?.type === "source_trace")
    return ((e36, t3) => {
      const n3 = tz([t3.display_name], t3.source_trace_id);
      if (n3)
        return n3;
      const o4 = [];
      for (const n4 of t3.connected_source_port_ids ?? []) {
        const t4 = e36.find((e37) => e37.type === "pcb_port" && e37.source_port_id === n4);
        if (t4?.type === "pcb_port") {
          const n5 = nz(e36, t4.pcb_port_id);
          n5 !== "unnamed port" && o4.push(n5);
        } else {
          const t5 = e36.find((e37) => e37.type === "source_port" && e37.source_port_id === n4);
          if (t5?.type !== "source_port")
            continue;
          const i4 = e36.find((e37) => e37.type === "source_component" && e37.source_component_id === t5.source_component_id), r3 = i4?.type === "source_component" ? tz([i4.name], i4.source_component_id) : "", s2 = tz([t5.name, t5.pin_number?.toString(), t5.port_hints?.[0]], t5.source_port_id);
          r3 && s2 ? o4.push(`${r3}.${s2}`) : s2 && o4.push(s2);
        }
        if (o4.length === 2)
          return `${o4[0]} to ${o4[1]}`;
      }
      return o4.length === 1 ? `trace connected to ${o4[0]}` : "unnamed trace";
    })(e35, o3);
  const i3 = Array.from(new Set(n2.route.flatMap((e36) => e36.route_type === "wire" ? [e36.start_pcb_port_id, e36.end_pcb_port_id].filter((e37) => Boolean(e37)) : []))).map((t3) => nz(e35, t3)).filter((e36) => e36 !== "unnamed port");
  return i3.length >= 2 ? `${i3[0]} to ${i3[1]}` : i3.length === 1 ? `trace connected to ${i3[0]}` : "unnamed trace";
};
var iz = (e35, t2) => {
  const n2 = e35.find((e36) => jL(e36) === t2);
  if (!n2)
    return "unnamed element";
  if (n2.type === "pcb_component" || n2.type === "schematic_component") {
    const t3 = e35.find((e36) => e36.type === "source_component" && e36.source_component_id === n2.source_component_id);
    if (t3?.type === "source_component")
      return tz([t3.name], t3.source_component_id) || "unnamed component";
  }
  if ((n2.type === "pcb_smtpad" || n2.type === "pcb_plated_hole") && n2.pcb_port_id) {
    const t3 = nz(e35, n2.pcb_port_id);
    if (t3 !== "unnamed port")
      return t3;
  }
  if (n2.type === "pcb_trace")
    return oz(e35, t2);
  const o3 = { pcb_smtpad: "SMD pad", pcb_plated_hole: "through-hole pad", pcb_via: "via", pcb_hole: "hole", pcb_bend: "bend", pcb_stiffener: "stiffener", pcb_keepout: "keepout", pcb_cutout: "cutout", pcb_copper_pour: "copper pour" }[n2.type] ?? n2.type.replace(/^(pcb|source|schematic)_/, "").replaceAll("_", " ");
  return tz(["name" in n2 ? n2.name : undefined, "description" in n2 ? n2.description : undefined, TL(e35, t2)], t2) || `unnamed ${o3}`;
};
var rz = (e35, t2, n2 = {}) => {
  const o3 = e35.find((e36) => e36.type === "pcb_board"), i3 = Math.max(n2.viaClearance ?? 0.1, 0.1), r3 = o3?.min_pad_edge_to_pad_edge_clearance ?? 0.1, s2 = e35.filter((e36) => e36.type === "pcb_via").map((e36, t3) => ({ minX: e36.x - Math.max(e36.hole_diameter, e36.outer_diameter) / 2, minY: e36.y - Math.max(e36.hole_diameter, e36.outer_diameter) / 2, maxX: e36.x + Math.max(e36.hole_diameter, e36.outer_diameter) / 2, maxY: e36.y + Math.max(e36.hole_diameter, e36.outer_diameter) / 2, via: e36, order: t3 })), a3 = new G;
  a3.load(s2);
  const c3 = [], l3 = [], h2 = new Set, d2 = Math.max(i3, r3);
  for (const n3 of s2) {
    const o4 = a3.search({ minX: n3.minX - d2, minY: n3.minY - d2, maxX: n3.maxX + d2, maxY: n3.maxY + d2 }).sort((e36, t3) => e36.order - t3.order);
    for (const s3 of o4) {
      if (s3.order <= n3.order)
        continue;
      const o5 = n3.via, a4 = s3.via, d3 = Math.hypot(o5.x - a4.x, o5.y - a4.y), u2 = t2.areIdsConnected(o5.pcb_via_id, a4.pcb_via_id);
      if (u2 && d3 <= 0.005)
        continue;
      let p3 = d3 - o5.hole_diameter / 2 - a4.hole_diameter / 2, m2 = i3;
      if (p3 + 0.005 >= m2) {
        if (u2 || !o5.layers.some((e36) => a4.layers.includes(e36)))
          continue;
        if (p3 = d3 - o5.outer_diameter / 2 - a4.outer_diameter / 2, m2 = r3, p3 >= 0 && p3 + 0.005 >= m2)
          continue;
      }
      const g2 = [o5.pcb_via_id, a4.pcb_via_id].sort().join("_");
      if (h2.has(g2))
        continue;
      h2.add(g2);
      const f2 = { x: (o5.x + a4.x) / 2, y: (o5.y + a4.y) / 2 }, _2 = { type: "pcb_via_clearance_error", error_type: "pcb_via_clearance_error", pcb_error_id: `${u2 ? "same_net" : "different_net"}_vias_close_${g2}`, message: `Vias ${iz(e35, o5.pcb_via_id)} and ${iz(e35, a4.pcb_via_id)}${u2 ? "" : " from different nets"} are too close together (gap: ${p3.toFixed(3)}mm)`, pcb_via_ids: [o5.pcb_via_id, a4.pcb_via_id], minimum_clearance: m2, actual_clearance: p3, pcb_center: f2 };
      u2 ? c3.push(_2) : l3.push(_2);
    }
  }
  return [...c3, ...l3];
};
var sz = 0.005;
var az = (e35, t2) => {
  const n2 = e35.type === "pcb_via" ? e35.pcb_via_id : e35.type === "pcb_smtpad" ? e35.pcb_smtpad_id : e35.type === "pcb_hole" ? e35.pcb_hole_id : e35.pcb_plated_hole_id, o3 = e35.type === "pcb_smtpad" ? [e35.layer] : e35.type === "pcb_hole" ? [...fE] : e35.layers, i3 = FL([e35]);
  if (e35.type === "pcb_smtpad" && e35.shape === "polygon")
    return { id: n2, order: t2, layers: o3, element: e35, clearanceBounds: i3, minX: Math.min(...e35.points.map((e36) => e36.x)), minY: Math.min(...e35.points.map((e36) => e36.y)), maxX: Math.max(...e35.points.map((e36) => e36.x)), maxY: Math.max(...e35.points.map((e36) => e36.y)), shape: { kind: "polygon", points: e35.points } };
  if (e35.type === "pcb_via" || (e35.type === "pcb_hole" ? e35.hole_shape === "circle" : e35.shape === "circle")) {
    const r4 = e35.type === "pcb_via" ? e35.outer_diameter / 2 : e35.type === "pcb_hole" && e35.hole_shape === "circle" ? e35.hole_diameter / 2 : e35.type === "pcb_smtpad" && e35.shape === "circle" ? e35.radius : e35.outer_diameter / 2;
    return { id: n2, order: t2, layers: o3, element: e35, clearanceBounds: i3, minX: e35.x - r4, minY: e35.y - r4, maxX: e35.x + r4, maxY: e35.y + r4, shape: { kind: "circle", center: { x: e35.x, y: e35.y }, radius: r4 } };
  }
  let r3, s2, a3, c3 = 0, l3 = false;
  if (e35.type !== "pcb_smtpad" || e35.shape !== "rect" && e35.shape !== "rotated_rect")
    if (e35.type !== "pcb_smtpad" || e35.shape !== "pill" && e35.shape !== "rotated_pill")
      if (e35.type !== "pcb_plated_hole" || e35.shape !== "oval" && e35.shape !== "pill")
        if (e35.type === "pcb_hole")
          r3 = "hole_width" in e35 ? e35.hole_width : e35.hole_diameter, s2 = "hole_height" in e35 ? e35.hole_height : e35.hole_diameter, a3 = e35.hole_shape === "rotated_pill" ? e35.ccw_rotation : 0, l3 = e35.hole_shape === "pill" || e35.hole_shape === "rotated_pill", c3 = l3 ? Math.min(r3, s2) / 2 : 0;
        else {
          if (e35.type !== "pcb_plated_hole" || !("rect_pad_width" in e35) || !("rect_pad_height" in e35))
            throw new Error(`Unsupported autorouting DRC obstacle shape: ${e35.type}`);
          r3 = e35.rect_pad_width, s2 = e35.rect_pad_height, a3 = "rect_ccw_rotation" in e35 && typeof e35.rect_ccw_rotation == "number" ? e35.rect_ccw_rotation : 0;
        }
      else
        r3 = e35.outer_width, s2 = e35.outer_height, c3 = Math.min(r3, s2) / 2, a3 = e35.ccw_rotation, l3 = true;
    else
      r3 = e35.width, s2 = e35.height, c3 = e35.radius, a3 = e35.shape === "rotated_pill" ? e35.ccw_rotation : 0, l3 = true;
  else
    r3 = e35.width, s2 = e35.height, a3 = e35.shape === "rotated_rect" ? e35.ccw_rotation : 0, c3 = Math.max(0, Math.min(e35.corner_radius ?? 0, r3 / 2, s2 / 2)), l3 = c3 > 0 && c3 === Math.min(r3, s2) / 2;
  const h2 = a3 * Math.PI / 180, d2 = Math.cos(h2), u2 = Math.sin(h2), p3 = [{ x: -r3 / 2, y: -s2 / 2 }, { x: r3 / 2, y: -s2 / 2 }, { x: r3 / 2, y: s2 / 2 }, { x: -r3 / 2, y: s2 / 2 }].map((t3) => ({ x: e35.x + (t3.x * d2 - t3.y * u2), y: e35.y + (t3.x * u2 + t3.y * d2) }));
  let m2, g2;
  if (l3) {
    const t3 = Math.max(Math.max(r3, s2) / 2 - c3, 0), n3 = r3 >= s2 ? t3 * d2 : -t3 * u2, o4 = r3 >= s2 ? t3 * u2 : t3 * d2;
    m2 = { kind: "capsule", start: { x: e35.x - n3, y: e35.y - o4 }, end: { x: e35.x + n3, y: e35.y + o4 }, radius: c3 };
  } else {
    m2 = { kind: "polygon", points: c3 === 0 ? p3 : [{ x: -r3 / 2 + c3, y: -s2 / 2 + c3 }, { x: r3 / 2 - c3, y: -s2 / 2 + c3 }, { x: r3 / 2 - c3, y: s2 / 2 - c3 }, { x: -r3 / 2 + c3, y: s2 / 2 - c3 }].map((t3) => ({ x: e35.x + t3.x * d2 - t3.y * u2, y: e35.y + t3.x * u2 + t3.y * d2 })), radius: c3 };
  }
  if (e35.type === "pcb_hole") {
    if (e35.hole_shape === "oval")
      if (Math.abs(r3 - s2) < 0.000000001)
        g2 = new D_(new E_(new S_(0, 0), r3 / 2));
      else {
        const e36 = Math.max(16, Math.ceil(Math.PI / Math.acos(Math.max(-1, 1 - 0.000001 / (Math.max(r3, s2) / 2)))));
        g2 = new D_(Array.from({ length: e36 }, (t3, n3) => new S_(r3 / 2 * Math.cos(2 * n3 * Math.PI / e36), s2 / 2 * Math.sin(2 * n3 * Math.PI / e36))));
      }
    else if (l3) {
      const e36 = [new S_(r3 / 2 - c3, -s2 / 2 + c3), new S_(r3 / 2 - c3, s2 / 2 - c3), new S_(-r3 / 2 + c3, s2 / 2 - c3), new S_(-r3 / 2 + c3, -s2 / 2 + c3)], t3 = [];
      for (let n3 = 0;n3 < 4; n3++) {
        const o4 = -Math.PI / 2 + n3 * Math.PI / 2, i4 = new A_(e36[n3], c3, o4, o4 + Math.PI / 2, true), r4 = e36[(n3 + 1) % 4], s3 = new S_(r4.x + c3 * Math.cos(o4 + Math.PI / 2), r4.y + c3 * Math.sin(o4 + Math.PI / 2));
        t3.push(i4), i4.end.distanceTo(s3)[0] > 0.000000001 && t3.push(new w_(i4.end, s3));
      }
      g2 = new D_, g2.addFace(t3);
    } else
      g2 = new D_([new S_(-r3 / 2, -s2 / 2), new S_(r3 / 2, -s2 / 2), new S_(r3 / 2, s2 / 2), new S_(-r3 / 2, s2 / 2)]);
    g2 = g2.rotate(a3 * Math.PI / 180).translate(new P_(e35.x, e35.y));
  }
  const f2 = p3, _2 = g2 ? { minX: g2.box.xmin, minY: g2.box.ymin, maxX: g2.box.xmax, maxY: g2.box.ymax } : m2.kind === "capsule" ? { minX: Math.min(m2.start.x, m2.end.x) - m2.radius, minY: Math.min(m2.start.y, m2.end.y) - m2.radius, maxX: Math.max(m2.start.x, m2.end.x) + m2.radius, maxY: Math.max(m2.start.y, m2.end.y) + m2.radius } : { minX: Math.min(...f2.map((e36) => e36.x)), minY: Math.min(...f2.map((e36) => e36.y)), maxX: Math.max(...f2.map((e36) => e36.x)), maxY: Math.max(...f2.map((e36) => e36.y)) };
  return { id: n2, order: t2, layers: o3, element: e35, clearanceBounds: i3, holePolygon: g2, ..._2, shape: m2 };
};
var cz = (e35, t2, n2, o3) => {
  const i3 = ge(e35, t2, n2, o3);
  if (i3)
    return { distance: 0, tracePoint: i3, obstaclePoint: i3 };
  const r3 = [{ tracePoint: e35, obstaclePoint: Ee(e35, n2, o3) }, { tracePoint: t2, obstaclePoint: Ee(t2, n2, o3) }, { tracePoint: Ee(n2, e35, t2), obstaclePoint: n2 }, { tracePoint: Ee(o3, e35, t2), obstaclePoint: o3 }];
  let s2 = r3[0], a3 = Number.POSITIVE_INFINITY;
  for (const e36 of r3) {
    const t3 = (e36.tracePoint.x - e36.obstaclePoint.x) ** 2 + (e36.tracePoint.y - e36.obstaclePoint.y) ** 2;
    t3 < a3 && (s2 = e36, a3 = t3);
  }
  return { ...s2, distance: we(e35, t2, n2, o3) };
};
var lz = (e35, t2, n2, o3) => {
  const i3 = n2 / 2;
  if (o3.element.type === "pcb_hole") {
    const n3 = o3.element;
    if (n3.hole_shape === "circle")
      return { gap: pe(n3, e35, t2) - n3.hole_diameter / 2 - i3, center: Ee(n3, e35, t2) };
    if (!o3.holePolygon)
      throw new Error(`Missing compiled hole geometry for ${o3.id}`);
    const r4 = new S_(e35.x, e35.y), s3 = new S_(t2.x, t2.y), [a4, c4] = o3.holePolygon.distanceTo(new w_(r4, s3));
    return { gap: (o3.holePolygon.contains(r4) || o3.holePolygon.contains(s3) ? 0 : a4) - i3, center: { x: c4.end.x, y: c4.end.y } };
  }
  let r3, s2, a3, c3 = 0;
  if (o3.shape.kind === "circle")
    c3 = o3.shape.radius, s2 = o3.shape.center, r3 = Ee(s2, e35, t2), a3 = Te(e35, t2, { ...s2, radius: c3 });
  else if (o3.shape.kind === "capsule") {
    const n3 = cz(e35, t2, o3.shape.start, o3.shape.end);
    r3 = n3.tracePoint, s2 = n3.obstaclePoint, c3 = o3.shape.radius, a3 = n3.distance - c3;
  } else {
    const n3 = o3.shape.points;
    if (c3 = o3.shape.radius ?? 0, n3.length < 3)
      return { gap: 1 / 0, center: e35 };
    const i4 = n3.flatMap((o4, i5) => {
      const r4 = ge(e35, t2, o4, n3[(i5 + 1) % n3.length]);
      return r4 ? [r4] : [];
    });
    if (i4.length > 0) {
      const n4 = t2.x - e35.x, o4 = t2.y - e35.y;
      i4.sort((t3, i5) => (t3.x - e35.x) * n4 + (t3.y - e35.y) * o4 - ((i5.x - e35.x) * n4 + (i5.y - e35.y) * o4)), r3 = s2 = i4[0], a3 = 0;
    } else if (ve(e35, n3) || ve(t2, n3))
      r3 = s2 = { x: (e35.x + t2.x) / 2, y: (e35.y + t2.y) / 2 }, a3 = 0;
    else {
      let o4 = cz(e35, t2, n3[0], n3[1]);
      for (let i5 = 1;i5 < n3.length; i5++) {
        const r4 = cz(e35, t2, n3[i5], n3[(i5 + 1) % n3.length]);
        r4.distance < o4.distance && (o4 = r4);
      }
      r3 = o4.tracePoint, s2 = o4.obstaclePoint, a3 = o4.distance;
    }
    a3 -= c3;
  }
  const l3 = s2.x - r3.x, h2 = s2.y - r3.y, d2 = Math.hypot(l3, h2), u2 = d2 === 0 ? 0 : l3 / d2, p3 = d2 === 0 ? 0 : h2 / d2;
  if (d2 > 0 && d2 <= i3 + c3) {
    const e36 = (Math.max(-i3, d2 - c3) + Math.min(i3, d2 + c3)) / 2;
    return { gap: a3 - i3, center: { x: r3.x + u2 * e36, y: r3.y + p3 * e36 } };
  }
  return { gap: a3 - i3, center: { x: (r3.x + u2 * i3 + (s2.x - u2 * c3)) / 2, y: (r3.y + p3 * i3 + (s2.y - p3 * c3)) / 2 } };
};
var hz = (e35, t2) => {
  const n2 = e35.start, o3 = t2.start, i3 = e35.end.x - n2.x, r3 = e35.end.y - n2.y, s2 = t2.end.x - o3.x, a3 = t2.end.y - o3.y, c3 = i3 * i3 + r3 * r3, l3 = s2 * s2 + a3 * a3;
  if (c3 === 0 || l3 === 0) {
    const i4 = c3 === 0 ? n2 : Ee(o3, n2, e35.end), r4 = l3 === 0 ? o3 : Ee(n2, o3, t2.end);
    return { x: (i4.x + r4.x) / 2, y: (i4.y + r4.y) / 2 };
  }
  const h2 = n2.x - o3.x, d2 = n2.y - o3.y, u2 = i3 * s2 + r3 * a3, p3 = i3 * h2 + r3 * d2, m2 = s2 * h2 + a3 * d2, g2 = c3 * l3 - u2 * u2;
  if (g2 < 0.0000000001) {
    const i4 = [{ pointA: Ee(o3, n2, e35.end), pointB: o3 }, { pointA: Ee(t2.end, n2, e35.end), pointB: t2.end }, { pointA: n2, pointB: Ee(n2, o3, t2.end) }, { pointA: e35.end, pointB: Ee(e35.end, o3, t2.end) }];
    let r4 = i4[0], s3 = Number.POSITIVE_INFINITY;
    for (const e36 of i4) {
      const t3 = Math.sqrt((e36.pointA.x - e36.pointB.x) ** 2 + (e36.pointA.y - e36.pointB.y) ** 2);
      t3 < s3 && (r4 = e36, s3 = t3);
    }
    return { x: (r4.pointA.x + r4.pointB.x) / 2, y: (r4.pointA.y + r4.pointB.y) / 2 };
  }
  let f2 = Math.max(0, Math.min(1, (u2 * m2 - l3 * p3) / g2)), _2 = Math.max(0, Math.min(1, (f2 * u2 + m2) / l3));
  return f2 = Math.max(0, Math.min(1, (_2 * u2 - p3) / c3)), { x: (n2.x + f2 * i3 + (o3.x + _2 * s2)) / 2, y: (n2.y + f2 * r3 + (o3.y + _2 * a3)) / 2 };
};
var dz = (e35, t2 = {}) => {
  const n2 = e35.filter((e36) => e36.type === "pcb_smtpad" || e36.type === "pcb_plated_hole" || e36.type === "pcb_hole").sort((e36, t3) => {
    const n3 = { pcb_smtpad: 0, pcb_plated_hole: 1, pcb_hole: 2 };
    return n3[e36.type] - n3[t3.type];
  }).map(az), o3 = new G;
  o3.load(n2);
  const i3 = new G;
  i3.load(n2.filter((e36) => e36.element.type !== "pcb_hole").map((e36) => ({ ...e36, ...e36.clearanceBounds })));
  const r3 = new G;
  return r3.load(n2.filter((e36) => e36.element.type === "pcb_hole")), (e36, s2) => {
    const a3 = e36.find((e37) => e37.type === "pcb_board"), c3 = t2.traceClearance ?? a3?.min_trace_to_pad_edge_clearance ?? 0.1, l3 = t2.holeClearance ?? a3?.min_trace_to_hole_edge_clearance ?? 0.2;
    if (!Number.isFinite(l3) || l3 < 0)
      throw new Error("Trace-to-hole clearance must be finite and non-negative");
    const h2 = e36.filter((e37) => e37.type === "pcb_trace"), d2 = [];
    for (const [e37, t3] of h2.entries()) {
      const n3 = Array.from(new Set(t3.route.flatMap((e38) => e38.route_type === "wire" ? [e38.start_pcb_port_id, e38.end_pcb_port_id].filter((e39) => Boolean(e39)) : [])));
      for (let o4 = 0;o4 < t3.route.length - 1; o4++) {
        const i4 = t3.route[o4], r4 = t3.route[o4 + 1];
        if (i4.route_type !== "wire" && i4.route_type !== "via" || r4.route_type !== "wire" && r4.route_type !== "via")
          continue;
        const s3 = i4.route_type === "wire" ? i4 : r4;
        s3.route_type === "wire" && (i4.route_type === "wire" && r4.route_type === "wire" && i4.layer !== r4.layer || d2.push({ start: i4, end: r4, trace: t3, traceOrder: e37, portIds: n3, width: Math.max(i4.route_type === "wire" ? i4.width ?? 0.1 : 0, r4.route_type === "wire" ? r4.width ?? 0.1 : 0), typedWidth: i4.route_type === "wire" && r4.route_type === "wire" ? i4.width ?? r4.width ?? 0.1 : undefined, layer: s3.layer, order: d2.length, minX: Math.min(i4.x, r4.x), minY: Math.min(i4.y, r4.y), maxX: Math.max(i4.x, r4.x), maxY: Math.max(i4.y, r4.y) }));
      }
    }
    const u2 = e36.filter((e37) => e37.type === "pcb_via").map((e37, t3) => az(e37, n2.length + t3)), p3 = new G;
    p3.load([...d2, ...u2]);
    const m2 = d2.filter((e37) => e37.typedWidth !== undefined), g2 = new G;
    g2.load(m2);
    const f2 = m2.reduce((e37, t3) => Math.max(e37, t3.typedWidth / 2), 0), _2 = new Map, y2 = (e37, t3, n3) => {
      const o4 = Math.floor((e37.minX - t3) / 0.4), i4 = Math.floor((e37.minY - t3) / 0.4), r4 = Math.floor((e37.maxX + t3) / 0.4), s3 = Math.floor((e37.maxY + t3) / 0.4), a4 = { minX: 0.4 * o4, minY: 0.4 * i4, maxX: 0.4 * (r4 + 1), maxY: 0.4 * (s3 + 1) };
      return n3.flatMap((e38) => e38.search(a4)).filter((e38) => Math.floor(e38.minX / 0.4) <= r4 && Math.floor(e38.maxX / 0.4) >= o4 && Math.floor(e38.minY / 0.4) <= s3 && Math.floor(e38.maxY / 0.4) >= i4).sort((e38, t4) => Math.max(o4, Math.floor(e38.minX / 0.4)) - Math.max(o4, Math.floor(t4.minX / 0.4)) || Math.max(i4, Math.floor(e38.minY / 0.4)) - Math.max(i4, Math.floor(t4.minY / 0.4)) || e38.order + ("trace" in e38 ? 0 : d2.length) - (t4.order + ("trace" in t4 ? 0 : d2.length)));
    };
    for (const t3 of d2) {
      const { start: n3, end: i4, trace: r4, width: a4, portIds: l4 } = t3;
      if (n3.x !== i4.x || n3.y !== i4.y)
        for (const h3 of y2(t3, c3 + a4 / 2, [p3, o3])) {
          const o4 = "trace" in h3 ? h3.trace.pcb_trace_id : h3.id;
          if (!("trace" in h3 ? [h3.layer] : h3.layers).includes(t3.layer))
            continue;
          const d3 = "trace" in h3 ? o4 : ("pcb_trace_id" in h3.element) ? h3.element.pcb_trace_id : o4;
          if (s2.areIdsConnected(r4.pcb_trace_id, d3))
            continue;
          const u3 = `${r4.pcb_trace_id}_${o4}`;
          if (_2.has(u3) || "trace" in h3 && _2.has(`${o4}_${r4.pcb_trace_id}`))
            continue;
          const p4 = "trace" in h3 ? { gap: we(n3, i4, h3.start, h3.end) - a4 / 2 - h3.width / 2, center: hz(t3, h3) } : lz(n3, i4, a4, h3);
          if ("trace" in h3 ? p4.gap > c3 - sz : p4.gap > 0)
            continue;
          const m3 = iz(e36, r4.pcb_trace_id), g3 = "trace" in h3 ? iz(e36, o4) : `${h3.element.type} "${iz(e36, o4)}"`, f3 = !("trace" in h3) && h3.element.type === "pcb_hole";
          _2.set(u3, { type: "pcb_trace_error", error_type: "pcb_trace_error", message: p4.gap <= 0 ? `PCB trace ${m3} overlaps with ${g3} (accidental contact)` : `PCB trace ${m3} is too close to ${g3} (gap: ${p4.gap.toFixed(3)}mm)`, pcb_trace_id: r4.pcb_trace_id, source_trace_id: f3 ? r4.source_trace_id ?? "" : "", pcb_trace_error_id: `overlap_${u3}`, pcb_component_ids: !("trace" in h3) && "pcb_component_id" in h3.element && h3.element.pcb_component_id ? [h3.element.pcb_component_id] : [], pcb_port_ids: "trace" in h3 ? Array.from(new Set([...l4, ...h3.portIds])) : [...l4, ..."pcb_port_id" in h3.element && h3.element.pcb_port_id ? [h3.element.pcb_port_id] : []], center: p4.center });
        }
    }
    const b2 = new Map, x2 = new Set, v2 = (t3, n3) => {
      if (!n3.layers.includes(t3.layer) || s2.areIdsConnected(t3.trace.pcb_trace_id, n3.id))
        return;
      const o4 = `${n3.id}_${t3.trace.pcb_trace_id}`, { gap: i4, center: r4 } = lz(t3.start, t3.end, t3.typedWidth, n3);
      if (i4 <= 0)
        return b2.delete(o4), void x2.add(o4);
      if (x2.has(o4) || i4 + sz >= c3 || (b2.get(o4)?.gap ?? 1 / 0) <= i4)
        return;
      const a4 = n3.element.type === "pcb_via", l4 = a4 ? "pcb_via_trace_clearance_error" : "pcb_pad_trace_clearance_error";
      b2.set(o4, { gap: i4, error: { type: l4, error_type: l4, [a4 ? "pcb_via_trace_clearance_error_id" : "pcb_pad_trace_clearance_error_id"]: `${a4 ? "via" : "pad"}_trace_clearance_${o4}`, [a4 ? "pcb_via_id" : "pcb_pad_id"]: n3.id, pcb_trace_id: t3.trace.pcb_trace_id, minimum_clearance: c3, actual_clearance: i4, message: `${a4 ? "Via" : "Pad"} ${iz(e36, n3.id)} and trace ${iz(e36, t3.trace.pcb_trace_id)} are too close (clearance: ${pR(i4)}, minimum: ${pR(c3)})`, center: r4 } });
    };
    for (const e37 of u2) {
      const t3 = c3 + f2 + sz, n3 = g2.search({ minX: e37.minX - t3, minY: e37.minY - t3, maxX: e37.maxX + t3, maxY: e37.maxY + t3 }).sort((e38, t4) => e38.order - t4.order);
      for (const t4 of n3)
        v2(t4, e37);
    }
    for (const e37 of m2)
      for (const t3 of y2(e37, c3 + e37.typedWidth / 2, [i3])) {
        if ("trace" in t3)
          throw new Error("Unexpected trace in pad index");
        v2(e37, t3);
      }
    const I2 = new Map, S2 = new Set;
    for (const t3 of d2)
      for (const n3 of y2(t3, l3 + t3.width / 2, [r3])) {
        if ("trace" in n3 || n3.element.type !== "pcb_hole")
          throw new Error("Unexpected geometry in hole index");
        const { gap: o4, center: i4 } = lz(t3.start, t3.end, t3.width, n3), r4 = `${t3.trace.pcb_trace_id}_${n3.id}`;
        o4 <= 0 ? (I2.delete(r4), S2.add(r4)) : S2.has(r4) || o4 + 0.000001 >= l3 || (I2.get(r4)?.gap ?? 1 / 0) <= o4 || I2.set(r4, { gap: o4, error: { type: "pcb_trace_error", error_type: "pcb_trace_error", pcb_trace_error_id: `overlap_${r4}`, pcb_trace_id: t3.trace.pcb_trace_id, source_trace_id: t3.trace.source_trace_id ?? "", pcb_component_ids: n3.element.pcb_component_id ? [n3.element.pcb_component_id] : [], pcb_port_ids: [], center: i4, message: `Trace ${oz(e36, t3.trace.pcb_trace_id)} is too close to non-plated hole ${iz(e36, n3.id)} (gap: ${o4.toFixed(6)}mm, required: ${l3}mm)` } });
      }
    const C = Array.from(b2.values(), ({ error: e37 }) => e37);
    return { traceErrors: [..._2.values()], viaErrors: C.filter((e37) => e37.type === "pcb_via_trace_clearance_error"), padErrors: C.filter((e37) => e37.type === "pcb_pad_trace_clearance_error"), holeErrors: Array.from(I2.values(), ({ error: e37 }) => e37) };
  };
};
var uz = (e35, t2 = {}) => {
  const n2 = e35.find((e36) => e36.type === "pcb_board"), o3 = t2.minClearance ?? n2?.min_pad_edge_to_pad_edge_clearance ?? 0.1, i3 = e35.filter((e36) => e36.type === "pcb_smtpad" || e36.type === "pcb_plated_hole").sort((e36, t3) => Number(e36.type === "pcb_plated_hole") - Number(t3.type === "pcb_plated_hole")), r3 = new G;
  return r3.load(i3.map((e36, t3) => {
    const n3 = az(e36, t3);
    return { ...n3, ...n3.clearanceBounds };
  })), (e36, n3) => {
    const i4 = [];
    for (const s2 of e36) {
      if (s2.type !== "pcb_via")
        continue;
      const a3 = FL([s2]), c3 = Math.floor((a3.minX - o3) / 0.4), l3 = Math.floor((a3.minY - o3) / 0.4), h2 = Math.floor((a3.maxX + o3) / 0.4), d2 = Math.floor((a3.maxY + o3) / 0.4), u2 = r3.search({ minX: 0.4 * c3, minY: 0.4 * l3, maxX: 0.4 * (h2 + 1), maxY: 0.4 * (d2 + 1) }).filter((e37) => Math.floor(e37.minX / 0.4) <= h2 && Math.floor(e37.maxX / 0.4) >= c3 && Math.floor(e37.minY / 0.4) <= d2 && Math.floor(e37.maxY / 0.4) >= l3).sort((e37, t3) => Math.max(c3, Math.floor(e37.minX / 0.4)) - Math.max(c3, Math.floor(t3.minX / 0.4)) || Math.max(l3, Math.floor(e37.minY / 0.4)) - Math.max(l3, Math.floor(t3.minY / 0.4)) || e37.order - t3.order);
      for (const r4 of u2) {
        if (!s2.layers.some((e37) => r4.layers.includes(e37)))
          continue;
        const c4 = n3.areIdsConnected(s2.pcb_via_id, r4.id);
        if (c4 && t2.allowViaInPad !== false)
          continue;
        let l4 = o3, h3 = 0.005, d3 = s2.outer_diameter, u3 = "pcb_pad_pad_clearance_error";
        c4 && (l4 = 0, h3 = 0.000001, d3 = s2.hole_diameter, u3 = "pcb_placement_error");
        const p3 = { kind: "circle", x: (a3.minX + a3.maxX) / 2, y: (a3.minY + a3.maxY) / 2, radius: Math.min(a3.maxX - a3.minX, a3.maxY - a3.minY) / 2 };
        let m2 = r4.shape.kind === "circle" ? VL(p3, { kind: "circle", x: (r4.clearanceBounds.minX + r4.clearanceBounds.maxX) / 2, y: (r4.clearanceBounds.minY + r4.clearanceBounds.maxY) / 2, radius: Math.min(r4.clearanceBounds.maxX - r4.clearanceBounds.minX, r4.clearanceBounds.maxY - r4.clearanceBounds.minY) / 2 }) : r4.shape.kind === "capsule" ? Te(r4.shape.start, r4.shape.end, p3) - r4.shape.radius : WL(p3, { kind: "polygon", points: r4.shape.points }) - (r4.shape.radius ?? 0);
        if (c4 && (m2 = lz(s2, s2, d3, r4).gap), m2 + h3 >= l4)
          continue;
        let g2 = lz(s2, s2, d3, r4).center;
        c4 && (g2 = { x: (r4.minX + r4.maxX) / 2, y: (r4.minY + r4.maxY) / 2 }), i4.push({ type: u3, error_type: u3, [`${u3}_id`]: `via_pad_clearance_${s2.pcb_via_id}_${r4.id}`, message: `Via ${iz(e36, s2.pcb_via_id)} and pad ${iz(e36, r4.id)} are too close (clearance: ${pR(m2)}, minimum: ${pR(l4)})`, pcb_pad_ids: [s2.pcb_via_id, r4.id], minimum_clearance: l4, actual_clearance: m2, center: g2, pcb_via_ids: [s2.pcb_via_id], ...typeof s2.pcb_trace_id == "string" ? { pcb_trace_id: s2.pcb_trace_id } : {} });
      }
    }
    return i4;
  };
};
var pz = Symbol("originalPortPoint");
var mz = class extends mr {
  constructor(e35) {
    const t2 = e35.nodeWithPortPoints, n2 = (e35.traceThickness ?? 0.1) / 2 + (e35.traceMargin ?? 0.1), o3 = t2.width > 2 * n2 && t2.height > 2 * n2, i3 = t2.center.x - t2.width / 2 + n2, r3 = t2.center.x + t2.width / 2 - n2, s2 = t2.center.y - t2.height / 2 + n2, a3 = t2.center.y + t2.height / 2 - n2, c3 = t2.portPoints.map((e36) => ({ ...e36, x: Math.max(i3, Math.min(r3, e36.x)), y: Math.max(s2, Math.min(a3, e36.y)), [pz]: e36 })), l3 = new Map;
    let h2 = false;
    for (const e36 of c3) {
      const t3 = `${e36.x},${e36.y},${e36.z}`, n3 = l3.get(t3), o4 = e36[pz];
      !n3 || n3.x === o4.x && n3.y === o4.y || (h2 = true), l3.set(t3, o4);
    }
    super({ ...e35, nodeWithPortPoints: o3 ? { ...t2, width: t2.width - 2 * n2, height: t2.height - 2 * n2, portPoints: c3 } : t2 }), h2 && (this.failed = true, this.error = "Boundary clearance collapses distinct terminals"), o3 || (this.failed = true, this.error = "Node has no interior after copper boundary clearance");
  }
  getOutput() {
    return super.getOutput().map((e35) => {
      const t2 = e35.route[0], n2 = e35.route[e35.route.length - 1];
      if (!t2[pz] || !n2[pz])
        throw new Error("A13 route lost its original terminal metadata");
      return { ...e35, route: [{ ...t2[pz] }, ...e35.route, { ...n2[pz] }] };
    });
  }
};
var gz = class extends mz {
  constructor(e35) {
    super(e35), this.validationParams = e35;
  }
  _step() {
    if (super._step(), !this.solved)
      return;
    const e35 = this.getOutput(), { connMap: t2, layerCount: n2 } = this.validationParams, o3 = this.nodeWithPortPoints, i3 = e35.flatMap((e36) => e36.route), r3 = Math.max(this.traceThickness, this.viaDiameter) / 2 + Math.max(this.traceMargin, 0.1) + 0.000001, s2 = Math.min(...i3.map((e36) => e36.x)) - r3, a3 = Math.max(...i3.map((e36) => e36.x)) + r3, c3 = Math.min(...i3.map((e36) => e36.y)) - r3, l3 = Math.max(...i3.map((e36) => e36.y)) + r3, h2 = this.validationParams.obstacles.filter((e36) => {
      const t3 = Math.hypot(e36.width, e36.height) / 2;
      return e36.center.x + t3 >= s2 && e36.center.x - t3 <= a3 && e36.center.y + t3 >= c3 && e36.center.y - t3 <= l3;
    });
    this.stats.boardObstaclesChecked = h2.length;
    const { connectedRouteNamesByObstacle: d2, connectedObstaclesByRoute: u2 } = (({ obstacles: e36, routes: t3, connMap: n3 }) => {
      const o4 = e36.map(() => []), i4 = t3.map(() => []);
      for (let r4 = 0;r4 < e36.length; r4++) {
        const s3 = e36[r4], a4 = { ...s3, connectedTo: [...new Set(s3.connectedTo)] };
        for (let e37 = 0;e37 < t3.length; e37++) {
          const c4 = t3[e37];
          xo(a4, c4, n3) && (o4[r4].push(c4.connectionName), i4[e37].push(s3));
        }
      }
      return { connectedRouteNamesByObstacle: o4, connectedObstaclesByRoute: i4 };
    })({ obstacles: h2, routes: e35, connMap: t2 }), p3 = { layerCount: n2, minTraceWidth: this.traceThickness, minViaDiameter: this.viaDiameter, bounds: { minX: o3.center.x - o3.width / 2, maxX: o3.center.x + o3.width / 2, minY: o3.center.y - o3.height / 2, maxY: o3.center.y + o3.height / 2 }, ...this.validationParams.boardGeometry, obstacles: h2.map((e36, t3) => ({ ...e36, connectedTo: [...e36.connectedTo, ...d2[t3]] })), connections: e35.map((e36, t3) => ({ name: e36.connectionName, rootConnectionName: e36.rootConnectionName, __netConnectionName: e36.rootConnectionName ?? e36.connectionName, pointsToConnect: [...[e36.route[0], e36.route.at(-1)].map((e37) => ({ x: e37.x, y: e37.y, layer: Co(e37.z, n2) })), ...u2[t3].flatMap((e37) => {
      const t4 = e37.circuitJsonMetadata?.pcb_port_id;
      return t4 ? [{ ...e37.center, layer: Co(0, n2), pcb_port_id: t4 }] : [];
    })] })) }, m2 = sR(p3, e35.map((e36, t3) => ({ type: "pcb_trace", pcb_trace_id: `${e36.connectionName}_${t3}`, connection_name: e36.connectionName, route: Ro(e36, n2) })));
    this.validationParams.boardGeometry && m2.push(rR(p3));
    const g2 = qy(m2);
    aR(m2);
    const f2 = dz(m2, { traceClearance: this.traceMargin })(m2, g2), _2 = [...f2.traceErrors, ...lR(m2), ...f2.viaErrors, ...f2.padErrors, ...f2.holeErrors, ...uz(m2)(m2, g2), ...rz(m2, g2, { viaClearance: this.traceMargin })], y2 = ay({ srj: { ...p3, traces: undefined }, routes: e35 });
    this.stats.boardDrcIssueCount = _2.length + y2.length, (_2.length > 0 || y2.length > 0) && (this.solved = false, this.failed = true, this.error = `A13 candidate fails board copper validation: ${_2[0]?.message ?? "fixed obstacle clearance violation"}`);
  }
};
var fz = (e35) => `${e35.x.toFixed(6)},${e35.y.toFixed(6)},${e35.z}`;
var _z = (e35) => [e35.route[0], e35.route[e35.route.length - 1]];
var yz = (e35, t2, n2) => {
  const o3 = new Map, i3 = (e36, t3) => {
    o3.has(e36) || o3.set(e36, new Set), o3.has(t3) || o3.set(t3, new Set), o3.get(e36).add(t3), o3.get(t3).add(e36);
  };
  for (const n3 of e35)
    if (n3.connectionName === t2 && n3.route.length !== 0) {
      if (n3.route.length === 1) {
        const e36 = fz(n3.route[0]);
        o3.has(e36) || o3.set(e36, new Set);
        continue;
      }
      for (let e36 = 0;e36 < n3.route.length - 1; e36++)
        i3(fz(n3.route[e36]), fz(n3.route[e36 + 1]));
    }
  const r3 = new Set([n2]), s2 = [n2];
  for (;s2.length > 0; ) {
    const e36 = s2.pop();
    for (const t3 of o3.get(e36) ?? [])
      r3.has(t3) || (r3.add(t3), s2.push(t3));
  }
  return r3;
};
var bz = Array.from({ length: 6 }, (e35, t2) => t2);
var xz = class extends wa {
  getSolverName() {
    return "PortfolioSingleIntraNodeSolver";
  }
  constructorParams;
  solvedRoutes = [];
  nodeWithPortPoints;
  connMap;
  effort;
  adaptiveSearchExpanded = false;
  negotiatedSearchStarted = false;
  enableNegotiatedSearch;
  gridSearchSegmentWork;
  gridSearchWorkScale;
  rejectOverlappingTerminals;
  precomputedIntraNodeRouteParams;
  nodeSegmentCount;
  totalCandidateWork = 0;
  dynamicExpansionWorkBudget = 1;
  candidateWorkBySolver = new WeakMap;
  getSolvedSegmentCount(e35) {
    const t2 = e35.solvedConnectionsMap;
    if (!(t2 instanceof Map))
      return null;
    let n2 = 0;
    for (const e36 of t2.values())
      Array.isArray(e36) && (n2 += e36.length);
    return n2;
  }
  getNodeSegmentCount() {
    return this.nodeSegmentCount ??= Math.max(1, this.nodeWithPortPoints.portPointsInPairs?.length ?? new Set(this.nodeWithPortPoints.portPoints.map((e35) => e35.connectionName)).size), this.nodeSegmentCount;
  }
  getCandidateProgress(e35) {
    if (e35 instanceof mr) {
      if (e35.solved)
        return 1;
      const t3 = e35.connections.length;
      if (t3 === 0)
        return 0;
      const n2 = e35.routedCount / t3, o3 = Math.max(0, (e35.routedCount - e35.conflictCount) / t3);
      return Math.min(0.99, (n2 + o3) / 2);
    }
    const t2 = this.getSolvedSegmentCount(e35);
    return t2 !== null ? Math.min(1, t2 / this.getNodeSegmentCount()) : Math.max(0, Math.min(1, e35.progress || 0));
  }
  constructor(e35) {
    if (super(), this.nodeWithPortPoints = e35.nodeWithPortPoints, this.connMap = e35.connMap, this.constructorParams = e35, this.effort = e35.effort ?? 1, this.gridSearchSegmentWork = e35.gridSearchSegmentWork ?? 1e4, this.gridSearchWorkScale = e35.gridSearchWorkScale ?? 1, this.rejectOverlappingTerminals = e35.rejectOverlappingTerminals ?? false, this.enableNegotiatedSearch = e35.enableNegotiatedSearch ?? false, this.MAX_ITERATIONS = 20000000 * this.effort, this.GREEDY_MULTIPLIER = 5, this.MIN_SUBSTEPS = 100, this.rejectOverlappingTerminals) {
      const t2 = this.nodeWithPortPoints.portPoints, n2 = e35.traceWidth ?? 0.15;
      for (let e36 = 0;e36 < t2.length; e36++)
        for (let o3 = e36 + 1;o3 < t2.length; o3++) {
          const i3 = t2[e36], r3 = t2[o3];
          if (i3.z === r3.z && (i3.rootConnectionName ?? i3.connectionName) !== (r3.rootConnectionName ?? r3.connectionName) && !this.connMap?.areIdsConnected(i3.connectionName, r3.connectionName) && Math.hypot(i3.x - r3.x, i3.y - r3.y) < n2 - 0.000001)
            return this.failed = true, void (this.error = "Unrelated route terminals overlap at the requested trace width");
        }
    }
  }
  getGridSearchIterationBudget() {
    const e35 = this.nodeWithPortPoints, t2 = e35.availableZ?.length ?? new Set(e35.portPoints.map((e36) => e36.z)).size, n2 = Math.floor(e35.width / 0.1) * Math.floor(e35.height / 0.1) * t2, o3 = t2 > 2 ? this.gridSearchWorkScale : 1;
    return Math.round(o3 * Math.max(150000, (t2 <= 2 ? 1e4 : this.gridSearchSegmentWork) * this.getNodeSegmentCount() ** 2, Math.round(n2 * (8 + 1.2 * Math.sqrt(this.getNodeSegmentCount())) * this.effort)));
  }
  getCombinationDefs() {
    return [["throughObstacle"], ["singleLayerNoDifferentRootIntersections"], ["multiHeadPolyLine"], ["majorCombinations", "orderings6", "cellSizeFactor"], ["noVias"], ["orderings50"], ["flipTraceAlignmentDirection", "orderings6"], ["closedFormSingleTrace"], ["highDensityA01"], ["highDensityA03"], ...this.enableNegotiatedSearch ? [["highDensityA13"]] : []];
  }
  getHyperParameterDefs() {
    let e35 = false;
    if (this.constructorParams.priorityDagSearch) {
      this.precomputedIntraNodeRouteParams ??= Or(this.nodeWithPortPoints);
      const t2 = [...this.precomputedIntraNodeRouteParams.connectionPointsByName.entries()].map(([e36, t3]) => ({ connectionName: e36, rootConnectionName: this.precomputedIntraNodeRouteParams.rootConnectionNameByConnectionName.get(e36), points: t3 }));
      let n2 = 0;
      const o3 = ds.detailedWorkDiagnostics;
      e35 = $r(t2, (e36, t3 = 1) => {
        o3 && (n2 += t3);
      }) !== null;
      const i3 = this.constructorParams.priorityDiagnostics;
      o3 && i3 && (i3.priorityEligibilityCalls = (i3.priorityEligibilityCalls ?? 0) + 1, i3.priorityEligibilityObservedWork = (i3.priorityEligibilityObservedWork ?? 0) + n2, e35 || (i3.priorityIneligiblePreflightWork = (i3.priorityIneligiblePreflightWork ?? 0) + n2));
    }
    return [{ name: "singleLayerNoDifferentRootIntersections", possibleValues: [{ SINGLE_LAYER_NO_DIFFERENT_ROOT_INTERSECTIONS: true }] }, { name: "majorCombinations", possibleValues: [{ FUTURE_CONNECTION_PROX_TRACE_PENALTY_FACTOR: 2, FUTURE_CONNECTION_PROX_VIA_PENALTY_FACTOR: 1, FUTURE_CONNECTION_PROXIMITY_VD: 10, MISALIGNED_DIST_PENALTY_FACTOR: 5 }, { FUTURE_CONNECTION_PROX_TRACE_PENALTY_FACTOR: 1, FUTURE_CONNECTION_PROX_VIA_PENALTY_FACTOR: 0.5, FUTURE_CONNECTION_PROXIMITY_VD: 5, MISALIGNED_DIST_PENALTY_FACTOR: 2 }, { FUTURE_CONNECTION_PROX_TRACE_PENALTY_FACTOR: 10, FUTURE_CONNECTION_PROX_VIA_PENALTY_FACTOR: 1, FUTURE_CONNECTION_PROXIMITY_VD: 5, MISALIGNED_DIST_PENALTY_FACTOR: 10, VIA_PENALTY_FACTOR_2: 1 }] }, { name: "orderings6", possibleValues: e35 ? [{ SHUFFLE_SEED: 0, PRIORITY_DAG_FAMILY_SIZE: 6 }] : bz.map((e36) => ({ SHUFFLE_SEED: e36 })) }, { name: "cellSizeFactor", possibleValues: [{ CELL_SIZE_FACTOR: 0.5 }, { CELL_SIZE_FACTOR: 1 }] }, { name: "flipTraceAlignmentDirection", possibleValues: [{ FLIP_TRACE_ALIGNMENT_DIRECTION: true }] }, { name: "noVias", possibleValues: [{ CELL_SIZE_FACTOR: 2, VIA_PENALTY_FACTOR_2: 10 }] }, { name: "orderings50", possibleValues: e35 ? [{ SHUFFLE_SEED: 0, PRIORITY_DAG_FAMILY_SIZE: 20 }] : Array.from({ length: 20 }, (e36, t2) => ({ SHUFFLE_SEED: 100 + t2 })) }, { name: "throughObstacle", possibleValues: [{ THROUGH_OBSTACLE: true }] }, { name: "closedFormSingleTrace", possibleValues: [{ CLOSED_FORM_SINGLE_TRANSITION: true }] }, { name: "multiHeadPolyLine", possibleValues: [{ MULTI_HEAD_POLYLINE_SOLVER: true, SEGMENTS_PER_POLYLINE: 6, BOUNDARY_PADDING: 0.05 }, { MULTI_HEAD_POLYLINE_SOLVER: true, SEGMENTS_PER_POLYLINE: 6, BOUNDARY_PADDING: -0.05, ITERATION_PENALTY: 1e4, MINIMUM_FINAL_ACCEPTANCE_GAP: 0.001 }] }, { name: "highDensityA01", possibleValues: [{ HIGH_DENSITY_A01: true, SHUFFLE_SEED: bz[0] }] }, { name: "highDensityA03", possibleValues: [{ HIGH_DENSITY_A03: true }] }, { name: "highDensityA13", possibleValues: [{ HIGH_DENSITY_A13: true, SHUFFLE_SEED: 0 }] }];
  }
  initializeCandidateBudget(e35) {
    if (e35 instanceof mr)
      return;
    const t2 = e35.setup;
    typeof t2 == "function" && t2.call(e35), (e35 instanceof Mi || e35 instanceof zi) && (e35.MAX_ITERATIONS = Math.min(e35.MAX_ITERATIONS, this.getGridSearchIterationBudget()));
  }
  refreshDynamicIterationLimit() {
    this.totalCandidateWork = 0, this.dynamicExpansionWorkBudget = 1;
    const e35 = (this.supervisedSolvers ?? []).reduce((e36, { solver: t2 }) => {
      if (t2 instanceof mr || (this.totalCandidateWork += t2.iterations, this.dynamicExpansionWorkBudget = Math.max(this.dynamicExpansionWorkBudget, t2 instanceof ds ? t2.nativeCandidateIterationLimit : t2.MAX_ITERATIONS), this.candidateWorkBySolver.set(t2, { iterations: t2.iterations, maxIterations: t2.MAX_ITERATIONS })), t2.solved || t2.failed)
        return e36;
      const n2 = Math.max(0, t2.MAX_ITERATIONS - t2.iterations + 1);
      return e36 + Math.ceil(n2 / this.MIN_SUBSTEPS);
    }, 0);
    this.MAX_ITERATIONS = Math.max(this.iterations + 1, this.iterations + e35), this.stats.dynamicSupervisorIterationLimit = this.MAX_ITERATIONS;
  }
  initialA01Orderings = new Set;
  initializeSolvers() {
    super.initializeSolvers();
    for (const { solver: e35, hyperParameters: t2 } of this.supervisedSolvers ?? [])
      this.initializeCandidateBudget(e35), t2.HIGH_DENSITY_A01 && this.initialA01Orderings.add(JSON.stringify(e35.unsolvedConnections));
    this.refreshDynamicIterationLimit(), this.stats.dynamicExpansionWorkBudget = this.dynamicExpansionWorkBudget;
  }
  addSupervisedCandidate(e35) {
    const t2 = this.generateSolver(e35);
    if (this.initializeCandidateBudget(t2), e35.HIGH_DENSITY_A01) {
      const e36 = JSON.stringify(t2.unsolvedConnections);
      if (this.initialA01Orderings.has(e36))
        return;
      this.initialA01Orderings.add(e36);
    }
    const n2 = this.computeG(t2);
    this.supervisedSolvers.push({ hyperParameters: e35, solver: t2, h: 0, g: n2, f: n2 });
  }
  expandAdaptiveSearch() {
    if (!this.adaptiveSearchExpanded) {
      this.adaptiveSearchExpanded = true;
      for (const e35 of bz.slice(1))
        this.addSupervisedCandidate({ HIGH_DENSITY_A01: true, SHUFFLE_SEED: e35 });
      this.refreshDynamicIterationLimit(), this.stats.adaptiveSearchExpanded = true, this.stats.adaptiveSearchExpandedAtIteration = this.iterations, this.stats.candidateWorkAtExpansion = this.totalCandidateWork, this.stats.bestProgressAtExpansion = Math.max(0, ...(this.supervisedSolvers ?? []).map(({ solver: e35 }) => this.getCandidateProgress(e35)));
    }
  }
  shouldExpandPortfolio() {
    if (this.adaptiveSearchExpanded)
      return false;
    const e35 = this.dynamicExpansionWorkBudget;
    return this.stats.dynamicExpansionWorkBudget = e35, this.totalCandidateWork >= e35;
  }
  _step() {
    this.supervisedSolvers || this.initializeSolvers(), this.adaptiveSearchExpanded || this.getSupervisedSolverWithBestFitness() || this.expandAdaptiveSearch(), super._step(), !this.negotiatedSearchStarted && this.activeSubSolver instanceof mr && (this.negotiatedSearchStarted = true, this.stats.negotiatedSearchStartedAtIteration = this.iterations), this.solved || this.failed || !this.shouldExpandPortfolio() || this.expandAdaptiveSearch();
  }
  computeG(e35) {
    if (e35 instanceof mr)
      return e35.routingIterations / 1e6;
    const t2 = this.candidateWorkBySolver.get(e35);
    if (t2 && (this.totalCandidateWork += e35.iterations - t2.iterations, t2.iterations = e35.iterations, t2.maxIterations !== e35.MAX_ITERATIONS)) {
      t2.maxIterations = e35.MAX_ITERATIONS, this.dynamicExpansionWorkBudget = 1;
      for (const { solver: e36 } of this.supervisedSolvers ?? [])
        e36 instanceof mr || (this.dynamicExpansionWorkBudget = Math.max(this.dynamicExpansionWorkBudget, e36 instanceof ds ? e36.nativeCandidateIterationLimit : e36.MAX_ITERATIONS));
    }
    return e35 instanceof Mi || e35 instanceof zi || e35 instanceof mr ? e35.iterations / 1e6 : e35?.hyperParameters?.MULTI_HEAD_POLYLINE_SOLVER ? 1000 + ((e35.hyperParameters?.ITERATION_PENALTY ?? 0) + e35.iterations) / 1e4 + 1e4 * (e35.hyperParameters.SEGMENTS_PER_POLYLINE - 3) : e35.iterations / 1e4;
  }
  computeH(e35) {
    return e35 instanceof mr || this.adaptiveSearchExpanded ? 1 - this.getCandidateProgress(e35) : 1 - (e35.progress || 0);
  }
  generateSolver(e35) {
    if (this.precomputedIntraNodeRouteParams ??= Or(this.nodeWithPortPoints), e35.SINGLE_LAYER_NO_DIFFERENT_ROOT_INTERSECTIONS) {
      if (!ra.isApplicable(this.nodeWithPortPoints)) {
        const e36 = new Lr({ nodeWithPortPoints: this.nodeWithPortPoints, connMap: this.connMap, traceWidth: this.constructorParams.traceWidth, viaDiameter: this.constructorParams.viaDiameter, obstacleMargin: this.constructorParams.obstacleMargin, precomputedIntraNodeRouteParams: this.precomputedIntraNodeRouteParams });
        return e36.failed = true, e36.error = "Single-layer no-different-root-intersection solver not applicable", e36;
      }
      return new ra({ nodeWithPortPoints: this.nodeWithPortPoints, traceWidth: this.constructorParams.traceWidth, viaDiameter: this.constructorParams.viaDiameter });
    }
    if (e35.HIGH_DENSITY_A13) {
      const t2 = Math.max(1, Math.round(50000000 * this.effort)), n2 = new gz({ obstacles: this.constructorParams.obstacles ?? [], boardGeometry: this.constructorParams.boardGeometry, connMap: this.connMap, layerCount: this.constructorParams.layerCount ?? 2, nodeWithPortPoints: this.nodeWithPortPoints, cellSizeMm: 0.1, viaDiameter: this.constructorParams.viaDiameter ?? 0.3, viaMinDistFromBorder: (this.constructorParams.viaDiameter ?? 0.3) / 2, traceThickness: this.constructorParams.traceWidth ?? 0.15, traceMargin: 0.1, stepMultiplier: 1000, maxSearchIterations: t2, maxRounds: Math.max(1, Math.round(200 * this.effort)), hyperParameters: { shuffleSeed: e35.SHUFFLE_SEED ?? 0 } });
      return n2.MAX_ITERATIONS = 2 * t2, n2;
    }
    if (e35.HIGH_DENSITY_A01) {
      return new Mi({ nodeWithPortPoints: this.nodeWithPortPoints, cellSizeMm: 0.1, viaDiameter: this.constructorParams.viaDiameter ?? 0.3, viaMinDistFromBorder: (this.constructorParams.viaDiameter ?? 0.3) / 2, traceMargin: 0.1, traceThickness: this.constructorParams.traceWidth ?? 0.15, effort: this.effort, hyperParameters: { shuffleSeed: e35.SHUFFLE_SEED ?? 0 } });
    }
    if (e35.HIGH_DENSITY_A03) {
      return new zi({ nodeWithPortPoints: this.nodeWithPortPoints, highResolutionCellSize: 0.1, highResolutionCellThickness: 8, lowResolutionCellSize: 0.4, viaDiameter: this.constructorParams.viaDiameter ?? 0.3, viaMinDistFromBorder: (this.constructorParams.viaDiameter ?? 0.3) / 2, traceMargin: 0.1, traceThickness: 0.1, effort: this.effort, hyperParameters: e35 });
    }
    return e35.CLOSED_FORM_TWO_TRACE_SAME_LAYER ? new Ma({ nodeWithPortPoints: this.nodeWithPortPoints, viaDiameter: this.constructorParams.viaDiameter }) : e35.CLOSED_FORM_TWO_TRACE_TRANSITION_CROSSING ? new Ca({ nodeWithPortPoints: this.nodeWithPortPoints, viaDiameter: this.constructorParams.viaDiameter }) : e35.CLOSED_FORM_SINGLE_TRANSITION ? new aa({ nodeWithPortPoints: this.nodeWithPortPoints, viaDiameter: this.constructorParams.viaDiameter }) : e35.THROUGH_OBSTACLE ? new da({ nodeWithPortPoints: this.nodeWithPortPoints, obstacles: this.constructorParams.obstacles, connMap: this.connMap, layerCount: this.constructorParams.layerCount, viaDiameter: this.constructorParams.viaDiameter, traceThickness: this.constructorParams.traceWidth }) : e35.MULTI_HEAD_POLYLINE_SOLVER ? new Bs({ nodeWithPortPoints: this.nodeWithPortPoints, connMap: this.connMap, hyperParameters: e35, viaDiameter: this.constructorParams.viaDiameter }) : e35.PRIORITY_DAG_FAMILY_SIZE ? new ds({ ...this.constructorParams, hyperParameters: e35, priorityFamilySize: e35.PRIORITY_DAG_FAMILY_SIZE, precomputedIntraNodeRouteParams: this.precomputedIntraNodeRouteParams }) : new jr({ ...this.constructorParams, hyperParameters: e35, precomputedIntraNodeRouteParams: this.precomputedIntraNodeRouteParams });
  }
  onSolve(e35) {
    let t2;
    t2 = e35.solver instanceof Mi || e35.solver instanceof zi || e35.solver instanceof mr ? e35.solver.getOutput() : e35.solver.solvedRoutes;
    const n2 = t2.map((e36) => {
      const t3 = this.nodeWithPortPoints.portPoints.find((t4) => t4.connectionName === e36.connectionName);
      return t3?.rootConnectionName ? { ...e36, rootConnectionName: t3.rootConnectionName } : e36;
    });
    this.solvedRoutes = ((e36, t3) => {
      const n3 = [...e36], o3 = new Map;
      for (const e37 of t3.portPoints) {
        const t4 = o3.get(e37.connectionName) ?? [];
        t4.push(e37), o3.set(e37.connectionName, t4);
      }
      for (const [e37, t4] of o3) {
        if (t4.length <= 1)
          continue;
        const o4 = t4[0]?.rootConnectionName ?? e37, i3 = new Set(t4.map(fz));
        let r3 = yz(n3, e37, fz(t4[0]));
        for (const s2 of t4.slice(1)) {
          const a3 = fz(s2);
          if (r3.has(a3))
            continue;
          const c3 = n3.find((t5) => {
            if ((t5.rootConnectionName ?? t5.connectionName) !== o4)
              return false;
            if (t5.connectionName === e37)
              return false;
            const [n4, s3] = _z(t5);
            if (!n4 || !s3)
              return false;
            const c4 = fz(n4), l3 = fz(s3);
            return r3.has(c4) && l3 === a3 || r3.has(l3) && c4 === a3 || i3.has(c4) && i3.has(l3) && (c4 === a3 || l3 === a3);
          });
          c3 && (n3.push({ ...c3, connectionName: e37, rootConnectionName: o4, route: c3.route.map((t5) => ({ ...t5, connectionName: e37, rootConnectionName: o4 })), vias: c3.vias.map((e38) => ({ ...e38 })), jumpers: c3.jumpers?.map((e38) => ({ ...e38, start: { ...e38.start }, end: { ...e38.end } })) }), r3 = yz(n3, e37, fz(t4[0])));
        }
      }
      return n3;
    })(n2, this.nodeWithPortPoints);
  }
};
function vz(e35, t2, n2, o3, i3) {
  const r3 = n2 - t2, s2 = i3 - o3, a3 = 0.000001;
  if (Math.abs(e35.y - i3) < a3)
    return e35.x - t2;
  if (Math.abs(e35.x - n2) < a3)
    return r3 + (i3 - e35.y);
  if (Math.abs(e35.y - o3) < a3)
    return r3 + s2 + (n2 - e35.x);
  if (Math.abs(e35.x - t2) < a3)
    return 2 * r3 + s2 + (e35.y - o3);
  const c3 = Math.abs(e35.y - i3), l3 = Math.abs(e35.x - n2), h2 = Math.abs(e35.y - o3), d2 = Math.abs(e35.x - t2), u2 = Math.min(c3, l3, h2, d2);
  return u2 === c3 ? Math.max(0, Math.min(r3, e35.x - t2)) : u2 === l3 ? r3 + Math.max(0, Math.min(s2, i3 - e35.y)) : u2 === h2 ? r3 + s2 + Math.max(0, Math.min(r3, n2 - e35.x)) : 2 * r3 + s2 + Math.max(0, Math.min(s2, e35.y - o3));
}
function Iz(e35, t2, n2 = 0.000001) {
  return Math.abs(e35 - t2) < n2;
}
function Sz(e35) {
  if (e35.length < 2)
    return 0;
  const t2 = e35.map(([e36, t3]) => e36 < t3 ? [e36, t3] : [t3, e36]);
  let n2 = 0;
  for (let e36 = 0;e36 < t2.length; e36++) {
    const [o3, i3] = t2[e36];
    for (let r3 = e36 + 1;r3 < t2.length; r3++) {
      const [e37, s2] = t2[r3];
      Iz(o3, e37) || Iz(o3, s2) || Iz(i3, e37) || Iz(i3, s2) || (o3 < e37 && e37 < i3 && i3 < s2 || e37 < o3 && o3 < s2 && s2 < i3) && n2++;
    }
  }
  return n2;
}
var Cz = (e35) => {
  const t2 = e35.center.x - e35.width / 2, n2 = e35.center.x + e35.width / 2, o3 = e35.center.y - e35.height / 2, i3 = e35.center.y + e35.height / 2, r3 = new Map;
  for (const t3 of e35.portPoints) {
    const e36 = r3.get(t3.connectionName) ?? [];
    e36.some((e37) => e37.x === t3.x && e37.y === t3.y && e37.z === t3.z) || e36.push({ x: t3.x, y: t3.y, z: t3.z }), r3.set(t3.connectionName, e36);
  }
  const s2 = new Map, a3 = [];
  let c3 = 0;
  for (const [e36, l4] of r3) {
    if (l4.length < 2)
      continue;
    const e37 = l4[0], r4 = l4[1], h2 = vz(e37, t2, n2, o3, i3), d2 = vz(r4, t2, n2, o3, i3);
    if (e37.z === r4.z) {
      const t3 = e37.z, n3 = s2.get(t3) ?? [];
      n3.push([h2, d2]), s2.set(t3, n3);
    } else
      c3++, a3.push([h2, d2]);
  }
  let l3 = 0;
  for (const [e36, t3] of s2)
    l3 += Sz(t3);
  return { numSameLayerCrossings: l3, numEntryExitLayerChanges: c3, numTransitionPairCrossings: Sz(a3) };
};
var Pz = (e35) => e35.availableZ?.length ? [...new Set(e35.availableZ)].sort((e36, t2) => e36 - t2) : [...new Set(e35.portPoints.map((e36) => e36.z ?? 0))].sort((e36, t2) => e36 - t2);
var Mz = (e35) => Pz(e35).length === 1 && Cz(e35).numSameLayerCrossings > 0;
var wz = (e35, t2, n2) => {
  const o3 = new Map, [i3] = Pz(e35);
  for (const t3 of e35.portPoints)
    o3.set(t3.connectionName, [...o3.get(t3.connectionName) ?? [], t3]);
  return Array.from(o3.entries()).flatMap(([o4, r3]) => {
    if (r3.length < 2)
      return [];
    const s2 = r3[0], a3 = r3[r3.length - 1];
    return [{ connectionName: o4, rootConnectionName: s2.rootConnectionName, regionId: e35.capacityMeshNodeId, traceThickness: t2, viaDiameter: n2, route: [{ x: s2.x, y: s2.y, z: i3 ?? s2.z ?? 0 }, { x: a3.x, y: a3.y, z: i3 ?? a3.z ?? 0 }], vias: [] }];
  });
};
var Nz = wz;
var Rz = (e35, t2, n2) => ({ ...e35, x: t2.x + (e35.x - t2.x) * n2, y: t2.y + (e35.y - t2.y) * n2 });
var Tz = (e35, t2, n2) => Rz(e35, t2, n2);
var Ez = ["#dc2626", "#2563eb", "#16a34a", "#ca8a04", "#9333ea", "#0891b2"];
var Az = (e35, t2, n2 = []) => [e35, t2 ? `rootConnectionName: ${t2}` : undefined, ...n2].filter(Boolean).join(`
`);
var Oz = class extends ni {
  getSolverName() {
    return "GrowShrinkHighDensityIntraNodeSolver";
  }
  constructorParams;
  nodeWithPortPoints;
  solvedRoutes = [];
  failedSolvers = [];
  activeSubSolver = null;
  winningSolver;
  scaleFactor = 1;
  growthAttempts = 0;
  maxGrowthAttempts;
  minimumGrowthAttempts;
  constructor(e35) {
    super(), this.constructorParams = e35, this.nodeWithPortPoints = e35.nodeWithPortPoints;
    const t2 = Math.min(this.nodeWithPortPoints.width, this.nodeWithPortPoints.height), n2 = t2 > 0 ? Math.max(0, Math.ceil(Math.log2((e35.viaDiameter ?? 0.3) / t2))) : 0;
    let o3 = Number.POSITIVE_INFINITY;
    const i3 = this.nodeWithPortPoints.portPoints;
    for (let e36 = 0;e36 < i3.length; e36++)
      for (let t3 = e36 + 1;t3 < i3.length; t3++) {
        const n3 = i3[e36], r4 = i3[t3];
        if (n3.z !== r4.z || (n3.rootConnectionName ?? n3.connectionName) === (r4.rootConnectionName ?? r4.connectionName))
          continue;
        const s3 = Math.hypot(n3.x - r4.x, n3.y - r4.y);
        s3 > 0.000000001 && (o3 = Math.min(o3, s3));
      }
    const r3 = Math.max(0, Math.ceil(Math.log2((e35.traceWidth ?? 0.15) / o3))), s2 = Math.max(n2, r3);
    if (this.maxGrowthAttempts = e35.maxGrowthAttempts ?? 3 + s2, this.minimumGrowthAttempts = Math.min(e35.maxGrowthAttempts ?? 3 + n2, Math.max(n2, 0, r3 - 1)), this.MAX_ITERATIONS = 20000000 * (e35.effort ?? 1) * (this.maxGrowthAttempts + 1), Mz(this.nodeWithPortPoints)) {
      if (!e35.fallbackToInvalidGeometryOnFailure)
        return this.failed = true, this.progress = 1, void (this.error = "GrowShrinkHighDensityIntraNodeSolver cannot route an impossible single-layer crossing");
      this.solvedRoutes = Nz(this.nodeWithPortPoints, e35.traceWidth ?? 0.15, e35.viaDiameter ?? 0.3), this.solved = true, this.progress = 1, this.stats = { invalidGeometryFallback: true, reason: "single-layer node has same-layer crossings" };
    }
  }
  getConstructorParams() {
    return this.constructorParams;
  }
  createActiveSubSolver() {
    const { growShrinkSolutionValidator: e35, ...t2 } = this.constructorParams;
    var n2, o3;
    this.activeSubSolver = new xz({ ...t2, priorityCoordinateScale: (t2.priorityCoordinateScale ?? 1) * this.scaleFactor, enableNegotiatedSearch: this.scaleFactor === 1 && (t2.enableNegotiatedSearch ?? true), nodeWithPortPoints: (n2 = this.nodeWithPortPoints, o3 = this.scaleFactor, { ...n2, width: n2.width * o3, height: n2.height * o3, portPoints: n2.portPoints.map((e36) => Tz(e36, n2.center, o3)), portPointsInPairs: n2.portPointsInPairs?.map(([e36, t3]) => [Tz(e36, n2.center, o3), Tz(t3, n2.center, o3)]) }) }), this.constructorParams.maxInnerIterationsPerGrowthAttempt && (this.activeSubSolver.MAX_ITERATIONS = this.constructorParams.maxInnerIterationsPerGrowthAttempt);
  }
  acceptSolution(e35) {
    const t2 = this.scaleFactor === 1 ? e35.solvedRoutes : e35.solvedRoutes.map((e36) => ((e37, t3, n2) => ({ ...e37, route: e37.route.map((e38) => Rz(e38, t3, n2)), vias: e37.vias.map((e38) => Rz(e38, t3, n2)), jumpers: e37.jumpers?.map((e38) => ({ ...e38, start: Rz(e38.start, t3, n2), end: Rz(e38.end, t3, n2) })) }))(e36, this.nodeWithPortPoints.center, 1 / this.scaleFactor));
    return this.constructorParams.growShrinkSolutionValidator && !this.constructorParams.growShrinkSolutionValidator(t2) ? (e35.solved = false, e35.failed = true, e35.error = "High-density scale solution rejected by validator", false) : (this.winningSolver = e35, this.error = null, this.solvedRoutes = t2, this.solved = true, this.failed = false, true);
  }
  computeProgress() {
    return Math.min(0.99, (this.growthAttempts + (this.activeSubSolver?.progress ?? 0)) / (this.maxGrowthAttempts + 1));
  }
  _step() {
    if (this.activeSubSolver || this.createActiveSubSolver(), this.activeSubSolver.step(), this.activeSubSolver.solved && this.acceptSolution(this.activeSubSolver))
      this.activeSubSolver = null;
    else if (this.activeSubSolver.failed) {
      if (this.failedSolvers.push(this.activeSubSolver), this.error = this.activeSubSolver.error, this.activeSubSolver = null, this.growthAttempts >= this.maxGrowthAttempts)
        return this.constructorParams.fallbackToInvalidGeometryOnFailure ? (this.solvedRoutes = wz(this.nodeWithPortPoints, this.constructorParams.traceWidth ?? 0.15, this.constructorParams.viaDiameter ?? 0.3), this.solved = true, this.failed = false, this.progress = 1, this.stats = { ...this.stats, invalidGeometryFallback: true, reason: "growth attempts exhausted", lastError: this.error }, void (this.error = null)) : (this.failed = true, void (this.error = `GrowShrinkHighDensityIntraNodeSolver failed after resizing to ${this.scaleFactor}x. Last error: ${this.error}`));
      this.growthAttempts = Math.max(this.growthAttempts + 1, this.minimumGrowthAttempts), this.scaleFactor = 2 ** this.growthAttempts;
    }
  }
  visualize() {
    const e35 = this.activeSubSolver?.visualize() ?? this.winningSolver?.visualize();
    return e35 || (this.solvedRoutes.length > 0 ? { title: this.stats.invalidGeometryFallback ? "Invalid same-layer crossing geometry" : "Grow/shrink high density routes", lines: this.solvedRoutes.flatMap((e36, t2) => e36.route.slice(0, -1).map((n2, o3) => ({ points: [n2, e36.route[o3 + 1]], strokeColor: Ez[t2 % Ez.length], strokeWidth: e36.traceThickness, layer: `z${n2.z}`, label: Az(e36.connectionName, e36.rootConnectionName, [`z${n2.z}`, this.stats.invalidGeometryFallback ? "invalid fallback route" : undefined].filter(Boolean)) }))), points: this.nodeWithPortPoints.portPoints.map((e36) => ({ x: e36.x, y: e36.y, color: Ez[Math.max(0, this.solvedRoutes.findIndex((t2) => t2.connectionName === e36.connectionName)) % Ez.length], label: Az(e36.connectionName, e36.rootConnectionName, [`z${e36.z}`]) })), rects: [{ center: this.nodeWithPortPoints.center, width: this.nodeWithPortPoints.width, height: this.nodeWithPortPoints.height, fill: this.stats.invalidGeometryFallback ? "rgba(245, 158, 11, 0.12)" : "rgba(14, 165, 233, 0.08)", stroke: this.stats.invalidGeometryFallback ? "rgba(217, 119, 6, 0.8)" : "rgba(14, 165, 233, 0.55)", label: [this.nodeWithPortPoints.capacityMeshNodeId, this.stats.reason].filter(Boolean).join(`
`) }], circles: [] } : e35 ?? { lines: [], points: [], rects: [], circles: [] });
  }
};
var kz = (e35, t2, n2 = []) => [e35, t2 ? `rootConnectionName: ${t2}` : undefined, ...n2].filter(Boolean).join(`
`);
var Dz = class extends ni {
  getSolverName() {
    return "HighDensitySolver";
  }
  unsolvedNodePortPoints;
  routes;
  colorMap;
  defaultViaDiameter = 0.3;
  defaultTraceThickness = 0.15;
  viaDiameter;
  traceWidth;
  obstacleMargin;
  effort;
  obstacles;
  layerCount;
  useGrowShrinkHighDensityIntraNodeSolver;
  enableNegotiatedSearch;
  gridSearchSegmentWork;
  gridSearchWorkScale;
  rejectOverlappingTerminals;
  boardGeometry;
  preserveTerminalPcbPortIds;
  growShrinkMaxInnerIterationsPerGrowthAttempt;
  growShrinkFallbackToInvalidGeometryOnFailure;
  growShrinkSolutionValidator;
  captureSearchDebug;
  benchmarkDiagnosticCounters;
  priorityDagOptions;
  failedSolvers;
  activeSubSolver = null;
  connMap;
  nodePfById;
  nodeSolveMetadataById;
  constructor({ nodePortPoints: e35, colorMap: t2, connMap: n2, viaDiameter: o3, traceWidth: i3, obstacleMargin: r3, effort: s2, nodePfById: a3, obstacles: c3, layerCount: l3, useGrowShrinkHighDensityIntraNodeSolver: h2, enableNegotiatedSearch: d2 = false, gridSearchSegmentWork: u2 = 1e4, gridSearchWorkScale: p3 = 1, rejectOverlappingTerminals: m2 = false, boardGeometry: g2, preserveTerminalPcbPortIds: f2, growShrinkMaxInnerIterationsPerGrowthAttempt: _2, growShrinkFallbackToInvalidGeometryOnFailure: y2, growShrinkSolutionValidator: b2, captureSearchDebug: x2, priorityDagSearch: v2 = false, priorityDiagnostics: I2, viaHoleDiameter: S2, minViaHoleEdgeToViaHoleEdgeClearance: C, allowBlindAndBuriedVias: P }) {
    super(), this.unsolvedNodePortPoints = e35, this.colorMap = t2 ?? {}, this.connMap = n2, this.routes = [], this.failedSolvers = [], this.effort = s2 ?? 1, this.viaDiameter = o3 ?? this.defaultViaDiameter, this.traceWidth = i3 ?? this.defaultTraceThickness, this.obstacleMargin = r3 ?? 0.15, this.obstacles = c3 ?? [], this.layerCount = l3 ?? 2, this.enableNegotiatedSearch = d2, this.gridSearchSegmentWork = u2, this.gridSearchWorkScale = p3, this.rejectOverlappingTerminals = m2, this.boardGeometry = g2, this.useGrowShrinkHighDensityIntraNodeSolver = h2 ?? false, this.preserveTerminalPcbPortIds = f2 ?? false, this.growShrinkMaxInnerIterationsPerGrowthAttempt = _2, this.growShrinkFallbackToInvalidGeometryOnFailure = y2 ?? false, this.growShrinkSolutionValidator = b2, this.captureSearchDebug = x2 ?? true, this.benchmarkDiagnosticCounters = I2 ?? {}, this.priorityDagOptions = { priorityDagSearch: v2, viaHoleDiameter: S2, minViaHoleEdgeToViaHoleEdgeClearance: C, allowBlindAndBuriedVias: P }, this.MAX_ITERATIONS = 1e7 * this.effort * (this.useGrowShrinkHighDensityIntraNodeSolver ? 4 : 1), this.nodePfById = a3 instanceof Map ? new Map(a3) : new Map(Object.entries(a3 ?? {})), this.nodeSolveMetadataById = new Map, this.stats = { solverNodeCount: {}, difficultNodePfs: {}, highDensityResizeCount: 0 };
  }
  getSolvedNodeSolverType(e35) {
    return e35 instanceof Oz && e35.winningSolver ? this.getSolvedNodeSolverType(e35.winningSolver) : e35 instanceof xz && e35.winningSolver ? this.getConcreteSolverTypeName(e35.winningSolver) : this.getConcreteSolverTypeName(e35);
  }
  recordNodeSolveMetadata(e35, t2) {
    const n2 = e35.nodeWithPortPoints, o3 = this.nodePfById.get(n2.capacityMeshNodeId) ?? null;
    this.nodeSolveMetadataById.set(n2.capacityMeshNodeId, { node: n2, status: t2, solverType: this.getSolvedNodeSolverType(e35), iterations: e35.iterations, routeCount: e35.solvedRoutes.length, nodePf: o3, error: e35.error ?? undefined });
  }
  createNodeMarkerLabel(e35, t2) {
    return ["hd_node_marker", `node: ${e35}`, `status: ${t2.status}`, `solver: ${t2.solverType}`, `iterations: ${t2.iterations}`, `routes: ${t2.routeCount}`, `nodePf: ${t2.nodePf ?? "n/a"}`, `portPoints: ${t2.node.portPoints.length}`, ...t2.error ? [`error: ${t2.error}`] : []].join(`
`);
  }
  getConcreteSolverTypeName(e35) {
    if (e35 instanceof jr) {
      const t2 = this.getIntraNodeStrategyName(e35.hyperParameters);
      return e35.cacheHit ? `${t2} [cached]` : t2;
    }
    return e35 instanceof Lr ? this.getIntraNodeStrategyName(e35.hyperParameters) : e35.getSolverName();
  }
  getIntraNodeStrategyName(e35) {
    return e35?.PRIORITY_DAG_FAMILY_SIZE ? "PriorityDagIntraNodeSolver" : e35?.MULTI_HEAD_POLYLINE_SOLVER ? "MultiHeadPolyLineIntraNodeSolver3" : e35?.SINGLE_LAYER_NO_DIFFERENT_ROOT_INTERSECTIONS ? "SingleLayerNoDifferentRootIntersectionsIntraNodeSolver" : e35?.CLOSED_FORM_SINGLE_TRANSITION ? "SingleTransitionIntraNodeSolver" : e35?.CLOSED_FORM_TWO_TRACE_SAME_LAYER ? "TwoCrossingRoutesHighDensitySolver" : e35?.CLOSED_FORM_TWO_TRACE_TRANSITION_CROSSING ? "SingleTransitionCrossingRouteSolver" : e35?.HIGH_DENSITY_A01 ? "HighDensitySolverA01" : e35?.HIGH_DENSITY_A03 ? "HighDensitySolverA03" : "SingleHighDensityRouteSolver6_VertHorzLayer_FutureCost";
  }
  recordSolvedNodeStats(e35, t2) {
    const n2 = this.getSolvedNodeSolverType(e35), o3 = this.stats.solverNodeCount, i3 = this.stats.difficultNodePfs;
    o3[n2] = (o3[n2] ?? 0) + 1;
    const r3 = this.nodePfById.get(t2.capacityMeshNodeId) ?? null;
    r3 !== null && r3 > 0.05 && (i3[n2] || (i3[n2] = []), i3[n2].push(r3));
  }
  recordResizeStats(e35) {
    e35 instanceof Oz && (this.stats.highDensityResizeCount = (this.stats.highDensityResizeCount ?? 0) + e35.growthAttempts);
  }
  getSolvedRoutesWithTerminalPcbPortIds(e35) {
    const t2 = e35.nodeWithPortPoints.portPoints.filter((e36) => e36.pcb_port_id !== undefined);
    if (t2.length === 0)
      return e35.solvedRoutes;
    const n2 = (e36, n3) => {
      const o3 = t2.filter((t3) => t3.connectionName === e36.connectionName && t3.x === n3.x && t3.y === n3.y && t3.z === n3.z);
      if (o3.length > 1)
        throw new Error(`HighDensitySolver found multiple PCB terminals at an endpoint of "${e36.connectionName}"`);
      const i3 = o3[0];
      if (i3?.pcb_port_id)
        return i3.pcb_port_id;
    };
    return e35.solvedRoutes.map((e36) => ({ ...e36, startPcbPortId: e36.route[0] ? n2(e36, e36.route[0]) : undefined, endPcbPortId: e36.route.length > 1 ? n2(e36, e36.route[e36.route.length - 1]) : undefined }));
  }
  _step() {
    if (this.updateCacheStats(), this.activeSubSolver)
      return this.activeSubSolver.step(), this.activeSubSolver.solved ? (this.routes.push(...this.preserveTerminalPcbPortIds ? this.getSolvedRoutesWithTerminalPcbPortIds(this.activeSubSolver) : this.activeSubSolver.solvedRoutes), this.recordNodeSolveMetadata(this.activeSubSolver, "solved"), this.recordSolvedNodeStats(this.activeSubSolver, this.activeSubSolver.nodeWithPortPoints), this.recordResizeStats(this.activeSubSolver), this.activeSubSolver = null) : this.activeSubSolver.failed && (this.recordNodeSolveMetadata(this.activeSubSolver, "failed"), this.recordResizeStats(this.activeSubSolver), this.failedSolvers.push(this.activeSubSolver), this.activeSubSolver = null), void this.updateCacheStats();
    if (this.unsolvedNodePortPoints.length === 0)
      return this.failedSolvers.length > 0 ? (this.solved = false, this.failed = true, this.error = `Failed to solve ${this.failedSolvers.length} nodes, ${this.failedSolvers.slice(0, 5).map((e36) => e36.nodeWithPortPoints.capacityMeshNodeId)}. err0: ${this.failedSolvers[0].error}.`, void this.updateCacheStats()) : (this.solved = true, void this.updateCacheStats());
    const e35 = { nodeWithPortPoints: this.unsolvedNodePortPoints.pop(), ...this.priorityDagOptions, priorityDiagnostics: this.benchmarkDiagnosticCounters, enableNegotiatedSearch: this.enableNegotiatedSearch, gridSearchSegmentWork: this.gridSearchSegmentWork, gridSearchWorkScale: this.gridSearchWorkScale, rejectOverlappingTerminals: this.rejectOverlappingTerminals, boardGeometry: this.boardGeometry, colorMap: this.colorMap, connMap: this.connMap, viaDiameter: this.viaDiameter, traceWidth: this.traceWidth, obstacleMargin: this.obstacleMargin, effort: this.effort, obstacles: this.obstacles, layerCount: this.layerCount, maxInnerIterationsPerGrowthAttempt: this.growShrinkMaxInnerIterationsPerGrowthAttempt, fallbackToInvalidGeometryOnFailure: this.growShrinkFallbackToInvalidGeometryOnFailure, growShrinkSolutionValidator: this.growShrinkSolutionValidator, captureSearchDebug: this.captureSearchDebug };
    this.activeSubSolver = this.useGrowShrinkHighDensityIntraNodeSolver ? new Oz(e35) : new xz(e35), this.updateCacheStats();
  }
  updateCacheStats() {
    const e35 = no();
    this.stats.intraNodeCacheHits = e35.cacheHits, this.stats.intraNodeCacheMisses = e35.cacheMisses;
  }
  visualize() {
    let e35 = { lines: [], points: [], rects: [], circles: [] };
    for (const t2 of this.routes) {
      const n2 = mi(t2.route, t2.connectionName, this.colorMap[t2.connectionName]);
      for (const o3 of n2)
        e35.lines.push({ points: o3.points, label: kz(t2.connectionName, t2.rootConnectionName), strokeColor: o3.z === 0 ? o3.color : Ao(o3.color, 0.5), layer: `z${o3.z}`, strokeWidth: t2.traceThickness, strokeDash: o3.z !== 0 ? [0.1, 0.3] : undefined });
      for (const n3 of t2.vias)
        e35.circles.push({ center: n3, layer: "z0,1", radius: t2.viaDiameter / 2, fill: this.colorMap[t2.connectionName], label: kz(t2.connectionName, t2.rootConnectionName, ["via"]) });
    }
    if (this.solved || this.failed)
      for (const [t2, n2] of this.nodeSolveMetadataById) {
        const o3 = n2.node.center.x - n2.node.width / 2, i3 = n2.node.center.x + n2.node.width / 2, r3 = n2.node.center.y - n2.node.height / 2, s2 = n2.node.center.y + n2.node.height / 2, a3 = this.createNodeMarkerLabel(t2, n2), c3 = n2.status === "solved" ? "blue" : "red";
        if (e35.lines.push({ points: [{ x: o3, y: r3 }, { x: i3, y: r3 }], layer: "hd_node_boundaries", strokeColor: c3, strokeDash: "6, 4", strokeWidth: 0.03, label: a3 }, { points: [{ x: i3, y: r3 }, { x: i3, y: s2 }], layer: "hd_node_boundaries", strokeColor: c3, strokeDash: "6, 4", strokeWidth: 0.03, label: a3 }, { points: [{ x: i3, y: s2 }, { x: o3, y: s2 }], layer: "hd_node_boundaries", strokeColor: c3, strokeDash: "6, 4", strokeWidth: 0.03, label: a3 }, { points: [{ x: o3, y: s2 }, { x: o3, y: r3 }], layer: "hd_node_boundaries", strokeColor: c3, strokeDash: "6, 4", strokeWidth: 0.03, label: a3 }), n2.status === "solved")
          e35.points.push({ x: n2.node.center.x, y: n2.node.center.y, color: c3, layer: "hd_node_markers", label: a3 });
        else {
          e35.lines.push({ points: [{ x: 0, y: 0 }, { x: n2.node.center.x, y: n2.node.center.y }], layer: "hd_failed_node_guides", strokeColor: "red", strokeDash: "8, 6", strokeWidth: 0.05, label: a3 });
          const t3 = Math.max(0.1 * n2.node.width, 0.12), o4 = Math.max(0.1 * n2.node.height, 0.12);
          e35.rects.push({ center: n2.node.center, layer: "hd_node_markers", width: t3, height: o4, fill: "red", label: a3 });
        }
      }
    return this.activeSubSolver && (e35 = pi(e35, this.activeSubSolver.visualize())), e35;
  }
};
function Lz(e35, t2) {
  const n2 = [], o3 = t2.filter((e36) => e36._containsTarget), i3 = new Map;
  for (const r3 of e35.connections) {
    const e36 = [];
    for (const n3 of r3.pointsToConnect) {
      let i4 = t2[0], r4 = Number.MAX_VALUE;
      for (const e37 of o3) {
        const t3 = Math.sqrt((e37.center.x - n3.x) ** 2 + (e37.center.y - n3.y) ** 2);
        t3 < r4 && (r4 = t3, i4 = e37);
      }
      e36.push(i4);
    }
    if (e36.length < 2)
      throw new Error(`Not enough nodes for connection "${r3.name}", only ${e36.length} found`);
    i3.set(r3.name, e36.map((e37) => e37.capacityMeshNodeId)), n2.push({ connection: r3, nodeIds: [e36[0].capacityMeshNodeId, e36[e36.length - 1].capacityMeshNodeId], straightLineDistance: me(e36[0].center, e36[e36.length - 1].center) });
  }
  return { unshuffledConnectionsWithResults: n2, connectionNameToGoalNodeIds: i3 };
}
function zz(e35, t2) {
  const n2 = new Map(t2.map((e36) => [e36.capacityMeshNodeId, e36])), o3 = t2.map((e36) => (e36.width + e36.height) / 2).filter((e36) => Number.isFinite(e36) && e36 > 0), i3 = o3.length > 0 ? o3.reduce((e36, t3) => e36 + t3, 0) / o3.length : 1, r3 = t2.filter((e36) => e36._offBoardConnectionId), s2 = new Map, a3 = new Map, c3 = new Map;
  for (const e36 of t2)
    a3.set(e36.capacityMeshNodeId, []), c3.set(e36.capacityMeshNodeId, []);
  for (const e36 of t2)
    for (const t3 of e36.portPoints) {
      s2.set(t3.portPointId, t3);
      for (const e37 of t3.connectionNodeIds) {
        const n3 = a3.get(e37);
        n3 && !n3.some((e38) => e38.portPointId === t3.portPointId) && n3.push(t3);
      }
    }
  const { unshuffledConnectionsWithResults: l3, connectionNameToGoalNodeIds: h2 } = Lz(e35, t2);
  return { nodeMap: n2, avgNodePitch: i3, offBoardNodes: r3, portPointMap: s2, nodePortPointsMap: a3, nodeAssignedPortPoints: c3, unshuffledConnectionsWithResults: l3, connectionNameToGoalNodeIds: h2 };
}
var Bz = (e35, t2 = 1, n2 = {}) => {
  const o3 = n2.viaDiameter ?? 0.3, i3 = "width" in e35 ? e35.width : e35, r3 = n2.obstacleMargin ?? 0.2, s2 = "height" in e35 && typeof e35.height == "number" ? e35.height : i3;
  if (!Number.isFinite(i3) || !Number.isFinite(s2))
    return 0;
  if (i3 <= 0 || s2 <= 0)
    return 0;
  const a3 = Math.min(i3, s2) / (o3 + r3), c3 = (Math.sqrt(i3 * s2) * Math.min(1.2, Math.max(0.85, a3 ** 0.05)) / (o3 / 2 + r3) / 2) ** 1.1 * t2;
  return Number.isFinite(c3) ? e35.availableZ?.length === 1 && c3 > 1 ? 1 : c3 : 0;
};
var Fz = (e35, t2 = 0.5, n2 = 16) => {
  let o3 = 0, i3 = e35;
  for (;o3 < n2; ) {
    if (Bz({ width: i3 }) <= t2)
      break;
    i3 /= 2, o3++;
  }
  return Math.max(1, o3);
};
var jz = (e35, t2, n2, o3) => {
  if (e35?._containsTarget)
    return 0;
  if ((e35.availableZ?.length ?? 2) === 1 && (t2 > 0 || n2 > 0 || o3 > 0))
    return 1;
  const i3 = ((0.82 * t2 + 0.41 * n2 + 0.2 * o3) / 2) ** 1.1;
  if (!Number.isFinite(i3))
    return 1;
  const r3 = Bz(e35);
  if (!Number.isFinite(r3) || r3 <= 0)
    return i3 > 0 ? 1 : 0;
  const s2 = i3 / r3;
  if (Number.isNaN(s2))
    throw new Error("calculateNodeProbabilityOfFailure returned NaN");
  return Number.isFinite(s2) ? s2 : i3 > 0 ? 1 : 0;
};
function $z(e35, t2, n2) {
  let o3 = 0;
  const i3 = n2?.NODE_MAX_PF ?? 0.99999;
  for (const n3 of e35) {
    const e36 = t2.get(n3.capacityMeshNodeId);
    if (!e36)
      continue;
    if (e36._containsTarget)
      continue;
    const r3 = Cz(n3), s2 = Math.min(jz(e36, r3.numSameLayerCrossings, r3.numEntryExitLayerChanges, r3.numTransitionPairCrossings), i3);
    o3 += Math.log(1 - s2);
  }
  return o3;
}
function Yz(e35, t2) {
  if (t2._containsTarget)
    return 0;
  const n2 = Cz(e35);
  return jz(t2, n2.numSameLayerCrossings, n2.numEntryExitLayerChanges, n2.numTransitionPairCrossings);
}
function Xz(e35, t2, n2, o3, i3) {
  const r3 = n2 - t2, s2 = i3 - o3, a3 = 0.000001;
  if (Math.abs(e35.y - i3) < a3)
    return e35.x - t2;
  if (Math.abs(e35.x - n2) < a3)
    return r3 + (i3 - e35.y);
  if (Math.abs(e35.y - o3) < a3)
    return r3 + s2 + (n2 - e35.x);
  if (Math.abs(e35.x - t2) < a3)
    return 2 * r3 + s2 + (e35.y - o3);
  const c3 = Math.abs(e35.y - i3), l3 = Math.abs(e35.x - n2), h2 = Math.abs(e35.y - o3), d2 = Math.abs(e35.x - t2), u2 = Math.min(c3, l3, h2, d2);
  return u2 === c3 ? Math.max(0, Math.min(r3, e35.x - t2)) : u2 === l3 ? r3 + Math.max(0, Math.min(s2, i3 - e35.y)) : u2 === h2 ? r3 + s2 + Math.max(0, Math.min(r3, n2 - e35.x)) : 2 * r3 + s2 + Math.max(0, Math.min(s2, e35.y - o3));
}
var Hz = 1.6 * 3.2;
var Vz = (e35, t2) => {
  const n2 = Math.ceil(t2 / 2), o3 = Math.min(e35.width, e35.height), i3 = Math.max(e35.width, e35.height), r3 = (Math.floor(o3 / 1.6) + 0.1) * (Math.floor(i3 / 3.2) + 0.1) / Hz;
  return Math.min(1, n2 / r3);
};
function Wz(e35, t2, n2, o3) {
  const i3 = t2.x - n2 / 2, r3 = t2.x + n2 / 2, s2 = t2.y - o3 / 2, a3 = t2.y + o3 / 2, c3 = Math.abs(e35.y - a3), l3 = Math.abs(e35.x - r3), h2 = Math.abs(e35.y - s2), d2 = Math.abs(e35.x - i3), u2 = Math.min(c3, l3, h2, d2);
  return u2 > 0.001 ? "interior" : u2 === c3 ? "top" : u2 === l3 ? "right" : u2 === h2 ? "bottom" : "left";
}
function Gz(e35, t2, n2, o3, i3) {
  const r3 = Wz(e35, n2, o3, i3), s2 = Wz(t2, n2, o3, i3);
  return r3 !== "interior" && r3 === s2;
}
function Uz(e35, t2, n2, o3, i3) {
  const r3 = Wz(e35, n2, o3, i3);
  let s2;
  if (r3 === "top" || r3 === "bottom") {
    const n3 = o3;
    s2 = Math.abs(t2.x - e35.x) / n3;
  } else {
    const n3 = i3;
    s2 = Math.abs(t2.y - e35.y) / n3;
  }
  s2 = Math.min(1, Math.max(0, s2));
  const a3 = (e35.x + t2.x) / 2, c3 = (e35.y + t2.y) / 2;
  return { x: a3 + (n2.x - a3) * s2, y: c3 + (n2.y - c3) * s2 };
}
function Zz(e35) {
  return "computeNodePf" in e35 && typeof e35.computeNodePf == "function";
}
function qz(e35) {
  const t2 = { lines: [], points: [], rects: [], circles: [] };
  for (const n3 of e35.inputNodes) {
    let o3 = 0, i3 = 0, r3 = { numSameLayerCrossings: 0, numEntryExitLayerChanges: 0, numTransitionPairCrossings: 0 }, s2 = 0;
    if (Zz(e35)) {
      o3 = e35.computeNodePf(n3), i3 = e35.nodeMemoryPfMap.get(n3.capacityMeshNodeId) ?? 0;
      const t3 = e35.buildNodeWithPortPointsForCrossing(n3);
      r3 = Cz(t3);
      const a4 = new Set, c4 = e35.nodeAssignedPortPoints.get(n3.capacityMeshNodeId) ?? [];
      for (const e36 of c4)
        e36.connectionName && a4.add(e36.connectionName);
      s2 = a4.size;
    } else {
      o3 = e35.nodePfMap.get(n3.capacityMeshNodeId) ?? 0;
      const t3 = e35.nodeAssignedPortPoints.get(n3.capacityMeshNodeId) ?? [], i4 = { capacityMeshNodeId: n3.capacityMeshNodeId, center: n3.center, width: n3.width, height: n3.height, portPoints: t3, availableZ: n3.availableZ };
      r3 = Cz(i4);
      const a4 = new Set;
      for (const e36 of t3)
        e36.connectionName && a4.add(e36.connectionName);
      s2 = a4.size;
    }
    const a3 = Math.min(255, Math.floor(512 * o3)), c3 = Math.max(0, 255 - Math.floor(512 * o3));
    let l3 = `rgba(${a3}, ${c3}, ${c3}, ${o3 < 0.001 ? "0.1" : "0.3"})`;
    n3._containsObstacle && (l3 = "rgba(255, 0, 0, 0.3)"), n3._offBoardConnectedCapacityMeshNodeIds?.length && (l3 = "rgba(255, 165, 0, 0.3)"), t2.rects.push({ center: n3.center, width: n3.width - 0.2, height: n3.height - 0.2, layer: `z${n3.availableZ.join(",")}`, fill: l3, label: `${n3.capacityMeshNodeId}
pf: ${o3.toFixed(3)}, memPf: ${i3.toFixed(3)}
C#: ${s2}
xSame: ${r3.numSameLayerCrossings}, xLC: ${r3.numEntryExitLayerChanges}, xTransition: ${r3.numTransitionPairCrossings}
obCmid: ${n3._offBoardConnectedCapacityMeshNodeIds?.join(",")}
obs: ${n3._containsObstacle ? "yes" : "no"}` });
  }
  if (Zz(e35))
    for (const [n3, o3] of e35.portPointMap) {
      const i3 = e35.assignedPortPoints.get(n3), r3 = i3 ? e35.colorMap[i3.connectionName] ?? "blue" : "rgba(150, 150, 150, 0.5)";
      t2.circles.push({ center: { x: o3.x, y: o3.y }, radius: 0.05, fill: r3, layer: `z${o3.z}`, label: [n3, `conn: ${i3?.connectionName}`, `cd: ${o3.distToCentermostPortOnZ}`, `connects: ${o3.connectionNodeIds.join(",")}`, `rootConn: ${i3?.rootConnectionName}`].filter(Boolean).join(`
`) });
    }
  const n2 = Zz(e35) ? e35.connectionsWithResults : e35.connectionResults;
  for (const o3 of n2) {
    if (!o3.path)
      continue;
    const n3 = o3.connection, i3 = e35.colorMap[n3.name] ?? "blue", r3 = [];
    for (const e36 of o3.path)
      r3.push({ x: e36.point.x, y: e36.point.y, z: e36.z, nodeId: e36.currentNodeId });
    for (let n4 = 0;n4 < r3.length - 1; n4++) {
      const o4 = r3[n4], s2 = r3[n4 + 1], a3 = o4.z === s2.z, c3 = o4.z;
      let l3;
      l3 = a3 ? c3 === 0 ? undefined : "10 5" : "3 3 10";
      const h2 = o4.nodeId ? e35.nodeMap.get(o4.nodeId) : null;
      if (h2 && Gz(o4, s2, h2.center, h2.width, h2.height)) {
        const e36 = Uz(o4, s2, h2.center, h2.width, h2.height);
        t2.lines.push({ points: [{ x: o4.x, y: o4.y }, { x: e36.x, y: e36.y }], strokeColor: i3, strokeDash: l3 }), t2.lines.push({ points: [{ x: e36.x, y: e36.y }, { x: s2.x, y: s2.y }], strokeColor: i3, strokeDash: l3 });
      } else
        t2.lines.push({ points: [{ x: o4.x, y: o4.y }, { x: s2.x, y: s2.y }], strokeColor: i3, strokeDash: l3 });
    }
  }
  if (Zz(e35) && !e35.solved && e35.candidates && e35.candidates.length > 0) {
    const n3 = e35.currentConnection, o3 = n3 ? e35.colorMap[n3.connection.name] ?? "blue" : "blue";
    if (n3) {
      const [i4, r3] = n3.nodeIds, s2 = e35.nodeMap.get(i4), a3 = e35.nodeMap.get(r3), c3 = n3.connection.pointsToConnect[0], l3 = n3.connection.pointsToConnect[n3.connection.pointsToConnect.length - 1];
      if (s2 && a3) {
        const e36 = c3 ? { x: c3.x, y: c3.y } : s2.center, i5 = l3 ? { x: l3.x, y: l3.y } : a3.center;
        t2.lines.push({ points: [e36, i5], strokeColor: Ao(o3, 0.5), strokeDash: "5 5" }), t2.points.push({ x: e36.x, y: e36.y, color: o3, label: [`Start: ${n3.connection.name}`, `${n3.connection.__rootConnectionNames?.[0]}`].join(`
`) }), t2.points.push({ x: i5.x, y: i5.y, color: o3, label: [`End: ${n3.connection.name}`, `${n3.connection.__rootConnectionNames?.[0]}`].join(`
`) }), t2.circles.push({ center: i5, radius: 0.08, stroke: o3, label: `Goal: ${n3.connection.name}` });
      }
    }
    const i3 = [...e35.candidates].sort((e36, t3) => e36.f - t3.f).slice(0, 1);
    for (const r3 of i3) {
      const i4 = [];
      let s2 = r3;
      for (;s2; )
        i4.unshift({ x: s2.point.x, y: s2.point.y, z: s2.z, lastMoveWasOffBoard: s2.lastMoveWasOffBoard, nodeId: s2.currentNodeId }), s2 = s2.prevCandidate;
      for (let n4 = 0;n4 < i4.length - 1; n4++) {
        const r4 = i4[n4], s3 = i4[n4 + 1], a3 = r4.z === s3.z, c3 = r4.z;
        let l3;
        l3 = s3.lastMoveWasOffBoard ? "2 2" : a3 ? c3 === 0 ? undefined : "10 5" : "3 3 10";
        const h2 = r4.nodeId ? e35.nodeMap.get(r4.nodeId) : null, d2 = 0.02 * r4.z;
        if (h2 && Gz(r4, s3, h2.center, h2.width, h2.height)) {
          const e36 = Uz(r4, s3, h2.center, h2.width, h2.height);
          t2.lines.push({ points: [{ x: r4.x + d2, y: r4.y + d2 }, { x: e36.x + d2, y: e36.y + d2 }], strokeColor: Ao(o3, 0.25), strokeDash: l3 }), t2.lines.push({ points: [{ x: e36.x + d2, y: e36.y + d2 }, { x: s3.x + d2, y: s3.y + d2 }], strokeColor: Ao(o3, 0.25), strokeDash: l3 });
        } else
          t2.lines.push({ points: [{ x: r4.x + d2, y: r4.y + d2 }, { x: s3.x + d2, y: s3.y + d2 }], strokeColor: Ao(o3, 0.25), strokeDash: l3 });
      }
      if (i4.length >= 1) {
        const s3 = i4[i4.length - 1];
        let a3 = 0, c3 = 0, l3 = 0, h2 = 0, d2 = 0, u2 = 0;
        const p3 = e35.nodeMap.get(r3.prevCandidate?.currentNodeId);
        if (p3 && r3.prevCandidate && r3.portPoint && n3) {
          const t3 = n3.connection.name, o4 = { x: r3.prevCandidate.point.x, y: r3.prevCandidate.point.y, z: r3.prevCandidate.z, connectionName: t3 }, i5 = { x: r3.portPoint.x, y: r3.portPoint.y, z: r3.portPoint.z, connectionName: t3 }, s4 = e35.buildNodeWithPortPointsForCrossing(p3, [o4, i5]), m3 = gs(s4);
          l3 = m3.numSameLayerCrossings, h2 = m3.numTransitionPairCrossings, d2 = m3.numEntryExitLayerChanges;
          const g3 = e35.capacityMeshNodeMap.get(p3.capacityMeshNodeId);
          g3 && (c3 = e35.JUMPER_PF_FN_ENABLED && p3.availableZ.length === 1 ? Vz(g3, l3) : jz(g3, l3, d2, h2), a3 = c3 ** 2 * e35.NODE_PF_FACTOR), u2 = r3.prevCandidate.g > 0 ? r3.g - r3.prevCandidate.g : r3.g;
        }
        if (!n3)
          continue;
        const [m2, g2] = n3.nodeIds, f2 = e35.nodeMap.get(g2), _2 = f2 ? Math.sqrt((s3.x - f2.center.x) ** 2 + (s3.y - f2.center.y) ** 2) : 0, y2 = e35.avgNodePitch > 0 ? _2 / e35.avgNodePitch : 0, b2 = y2 * e35.BASE_CANDIDATE_COST, x2 = e35.nodeMemoryPfMap.get(r3.currentNodeId) ?? 0, v2 = -Math.log(1 - x2) * e35.MEMORY_PF_FACTOR;
        t2.circles.push({ center: s3, radius: 0.03, fill: Ao(o3, 0.25), layer: `z${r3.z}`, label: [`f: ${r3.f.toFixed(2)}`, `g: ${r3.g.toFixed(2)} (nodeDelta: ${u2.toFixed(2)})`, `h: ${r3.h.toFixed(2)}`, `  dist: ${_2.toFixed(2)}`, `  estHops: ${y2.toFixed(1)}`, `  estStepCost: ${b2.toFixed(2)}`, `  memRiskCost: ${v2.toFixed(2)}`, `z: ${r3.z}`, `node: ${r3.currentNodeId}`, `Cost(Pf): ${a3.toFixed(3)}`, `Pf: ${c3.toFixed(3)}`, `xSame: ${l3}, xTrans: ${h2}, xLC: ${d2}`, `routeOffBoard=${e35.currentConnectionShouldRouteOffBoard}`, `offBoardTouched=${r3.hasTouchedOffBoardNode ?? false}`, `lastMoveWasOffBoard=${r3.lastMoveWasOffBoard ?? false}`].join(`
`) });
      }
    }
  }
  return t2;
}
function Jz(e35, t2, n2) {
  let o3 = 0;
  const i3 = n2?.NODE_MAX_PF ?? 0.99999;
  for (const n3 of e35) {
    const e36 = t2.get(n3.capacityMeshNodeId);
    if (!e36)
      continue;
    if (e36._containsTarget)
      continue;
    const r3 = Cz(n3), s2 = Math.min(Vz(e36, r3.numSameLayerCrossings), i3);
    o3 += Math.log(1 - s2);
  }
  return o3;
}
var Qz = class extends ni {
  constructor(e35) {
    super(), this.input = e35;
    const { simpleRouteJson: t2, capacityMeshNodes: n2, inputNodes: o3, colorMap: i3, nodeMemoryPfMap: r3, hyperParameters: s2, precomputedInitialParams: a3, fixedRoutes: c3 } = e35;
    if (this.input = structuredClone(e35), this.MAX_ITERATIONS = 1e8, this.simpleRouteJson = t2, this.inputNodes = o3, this.colorMap = i3 ?? {}, this.capacityMeshNodeMap = new Map(n2.map((e36) => [e36.capacityMeshNodeId, e36])), this.nodeMemoryPfMap = r3 ?? new Map, this.hyperParameters = s2 ?? {}, a3) {
      this.nodeMap = a3.nodeMap, this.avgNodePitch = a3.avgNodePitch, this.offBoardNodes = a3.offBoardNodes, this.portPointMap = a3.portPointMap, this.nodePortPointsMap = a3.nodePortPointsMap, this.connectionNameToGoalNodeIds = a3.connectionNameToGoalNodeIds;
      const { nodeAssignedPortPoints: e36 } = function(e37) {
        const t3 = new Map;
        for (const [n3, o4] of e37.nodeAssignedPortPoints)
          t3.set(n3, [...o4]);
        return { nodeAssignedPortPoints: t3 };
      }(a3);
      this.nodeAssignedPortPoints = e36, this.connectionsWithResults = Sr(structuredClone(a3.unshuffledConnectionsWithResults), this.hyperParameters.SHUFFLE_SEED ?? 0);
    } else {
      this.nodeMap = new Map(o3.map((e37) => [e37.capacityMeshNodeId, e37]));
      const e36 = o3.map((e37) => (e37.width + e37.height) / 2).filter((e37) => Number.isFinite(e37) && e37 > 0);
      this.avgNodePitch = e36.length > 0 ? e36.reduce((e37, t4) => e37 + t4, 0) / e36.length : 1, this.offBoardNodes = o3.filter((e37) => e37._offBoardConnectionId), this.portPointMap = new Map, this.nodePortPointsMap = new Map;
      for (const e37 of o3)
        this.nodePortPointsMap.set(e37.capacityMeshNodeId, []), this.nodeAssignedPortPoints.set(e37.capacityMeshNodeId, []);
      for (const e37 of o3)
        for (const t4 of e37.portPoints) {
          this.portPointMap.set(t4.portPointId, t4);
          for (const e38 of t4.connectionNodeIds) {
            const n4 = this.nodePortPointsMap.get(e38);
            n4 && !n4.some((e39) => e39.portPointId === t4.portPointId) && n4.push(t4);
          }
        }
      const { connectionsWithResults: t3, connectionNameToGoalNodeIds: n3 } = this.getConnectionsWithNodes();
      this.connectionsWithResults = t3, this.connectionNameToGoalNodeIds = n3;
    }
    if (c3 && c3.length > 0) {
      for (const e36 of c3)
        if (this.connectionsWithResults.push(e36), e36.portPoints)
          for (const t3 of e36.portPoints)
            t3.portPointId && this.assignedPortPoints.set(t3.portPointId, { connectionName: t3.connectionName, rootConnectionName: t3.rootConnectionName });
    }
    for (const e36 of this.connectionsWithResults)
      e36.path ? this.processedConnectionQueue.push(e36) : this.unprocessedConnectionQueue.push(e36);
    this.totalConnectionCount = this.connectionsWithResults.length;
  }
  getSolverName() {
    return "PortPointPathingSolver";
  }
  hyperParameters;
  simpleRouteJson;
  inputNodes;
  nodeMap;
  nodePortPointsMap;
  portPointMap;
  connectionsWithResults = [];
  failedConnection = null;
  assignedPortPoints = new Map;
  nodeAssignedPortPoints = new Map;
  PORT_POINT_REUSE_FACTOR = 1000;
  BASE_COST_FOR_NOT_GOING_OFF_BOARD = 100;
  get NODE_PF_FACTOR() {
    return this.hyperParameters.NODE_PF_FACTOR ?? 50;
  }
  get RANDOM_WALK_DISTANCE() {
    return this.hyperParameters.RANDOM_WALK_DISTANCE ?? 0;
  }
  get MEMORY_PF_FACTOR() {
    return this.hyperParameters.MEMORY_PF_FACTOR ?? 0;
  }
  get CENTER_OFFSET_FOCUS_SHIFT() {
    return this.hyperParameters.CENTER_OFFSET_FOCUS_SHIFT ?? 0;
  }
  get RANDOM_COST_MAGNITUDE() {
    return this.hyperParameters.RANDOM_COST_MAGNITUDE ?? 0;
  }
  get BASE_CANDIDATE_COST() {
    return this.hyperParameters.BASE_CANDIDATE_COST ?? 0;
  }
  get NODE_PF_MAX_PENALTY() {
    return this.hyperParameters.NODE_PF_MAX_PENALTY ?? 1e4;
  }
  get FORCE_CENTER_FIRST() {
    return this.hyperParameters.FORCE_CENTER_FIRST ?? true;
  }
  get FORCE_OFF_BOARD_FREQUENCY() {
    return this.offBoardNodes.length === 0 ? 0 : this.hyperParameters.FORCE_OFF_BOARD_FREQUENCY ?? 0;
  }
  get FORCE_OFF_BOARD_SEED() {
    return this.hyperParameters.FORCE_OFF_BOARD_SEED ?? 0;
  }
  get NODE_MAX_PF() {
    return Math.min(0.99999, 1 - Math.exp(-this.NODE_PF_MAX_PENALTY));
  }
  get CENTER_OFFSET_DIST_PENALTY_FACTOR() {
    return this.hyperParameters.CENTER_OFFSET_DIST_PENALTY_FACTOR ?? 0;
  }
  get STRAIGHT_LINE_DEVIATION_PENALTY_FACTOR() {
    return this.hyperParameters.STRAIGHT_LINE_DEVIATION_PENALTY_FACTOR ?? 0;
  }
  colorMap;
  get GREEDY_MULTIPLIER() {
    return this.hyperParameters.GREEDY_MULTIPLIER ?? 1.3;
  }
  MAX_CANDIDATES_IN_MEMORY = 5000;
  get MAX_ITERATIONS_PER_PATH() {
    return this.hyperParameters.MAX_ITERATIONS_PER_PATH ?? 1e4;
  }
  ITERATIONS_PER_MM_FOR_PATH = 30;
  BASE_ITERATIONS_PER_PATH = 1e4;
  get RIPPING_ENABLED() {
    return this.hyperParameters.RIPPING_ENABLED ?? false;
  }
  get RIPPING_PF_THRESHOLD() {
    const e35 = this.hyperParameters.START_RIPPING_PF_THRESHOLD, t2 = this.hyperParameters.END_RIPPING_PF_THRESHOLD;
    if (e35 !== undefined && t2 !== undefined) {
      const n2 = this.MAX_RIPS;
      return e35 + (n2 > 0 ? this.totalRipCount / n2 : 0) * (t2 - e35);
    }
    return this.hyperParameters.RIPPING_PF_THRESHOLD ?? 0.3;
  }
  get MAX_RIPS() {
    return this.hyperParameters.MAX_RIPS ?? 100;
  }
  get RANDOM_RIP_FRACTION() {
    return this.hyperParameters.RANDOM_RIP_FRACTION ?? 0;
  }
  get JUMPER_PF_FN_ENABLED() {
    return this.hyperParameters.JUMPER_PF_FN_ENABLED ?? false;
  }
  jumpersPerMmSquared = 0.1;
  testedRipConnections = new Map;
  totalRipCount = 0;
  get MIN_ALLOWED_BOARD_SCORE() {
    return this.hyperParameters.MIN_ALLOWED_BOARD_SCORE ?? -1e4;
  }
  nodeMemoryPfMap;
  unprocessedConnectionQueue = [];
  processedConnectionQueue = [];
  currentConnection = null;
  totalConnectionCount = 0;
  currentPathIterations = 0;
  candidates;
  visitedPortPoints;
  connectionNameToGoalNodeIds;
  capacityMeshNodeMap;
  avgNodePitch;
  currentConnectionShouldRouteOffBoard = false;
  activeCandidateStraightLineDistance;
  offBoardNodes = [];
  baseNodeCostCache = new Map;
  getConstructorParams() {
    return this.input;
  }
  clearCostCaches() {
    this.baseNodeCostCache.clear();
  }
  clampPf(e35) {
    return Number.isFinite(e35) ? Math.min(Math.max(e35, 0), 0.999999) : 0.999999;
  }
  pfToFailureCost(e35) {
    const t2 = this.clampPf(e35);
    return t2 >= this.NODE_MAX_PF ? this.NODE_PF_MAX_PENALTY : -Math.log(1 - t2);
  }
  getBaseNodeFailureCost(e35) {
    const t2 = this.baseNodeCostCache.get(e35);
    if (t2 != null)
      return t2;
    const n2 = this.nodeMap.get(e35);
    if (!n2)
      return 0;
    const o3 = this.computeNodePf(n2), i3 = this.pfToFailureCost(o3);
    return this.baseNodeCostCache.set(e35, i3), i3;
  }
  computeBoardScore() {
    const e35 = this.getNodesWithPortPoints();
    return this.JUMPER_PF_FN_ENABLED ? Jz(e35, this.capacityMeshNodeMap) : $z(e35, this.capacityMeshNodeMap);
  }
  getMaxIterationsForCurrentPath() {
    const e35 = this.activeCandidateStraightLineDistance ?? 0;
    return Math.min(this.BASE_ITERATIONS_PER_PATH + this.ITERATIONS_PER_MM_FOR_PATH * e35, this.MAX_ITERATIONS_PER_PATH);
  }
  getNodeDeltaFailureCostForSegment(e35, t2, n2) {
    const o3 = this.nodeMap.get(e35);
    if (!o3)
      return 0;
    const i3 = this.getBaseNodeFailureCost(e35), r3 = this.computeNodePf(o3, [t2, n2]), s2 = this.pfToFailureCost(r3), a3 = Math.max(0, s2 - i3);
    return r3 >= this.NODE_MAX_PF ? this.NODE_PF_MAX_PENALTY : a3 * this.NODE_PF_FACTOR;
  }
  getConnectionsWithNodes() {
    const { unshuffledConnectionsWithResults: e35, connectionNameToGoalNodeIds: t2 } = Lz(this.simpleRouteJson, this.inputNodes);
    return { connectionsWithResults: Sr(e35, this.hyperParameters.SHUFFLE_SEED ?? 0), connectionNameToGoalNodeIds: t2 };
  }
  buildNodeWithPortPointsForCrossing(e35, t2) {
    const n2 = this.nodeAssignedPortPoints.get(e35.capacityMeshNodeId) ?? [], o3 = t2 ? [...n2, ...t2] : n2;
    return { capacityMeshNodeId: e35.capacityMeshNodeId, center: e35.center, width: e35.width, height: e35.height, portPoints: o3, availableZ: e35.availableZ };
  }
  computeNodePf(e35, t2) {
    if (e35._containsTarget)
      return 0;
    const n2 = this.buildNodeWithPortPointsForCrossing(e35, t2), o3 = Cz(n2);
    return this.JUMPER_PF_FN_ENABLED && e35.availableZ.length === 1 ? Vz(this.capacityMeshNodeMap.get(e35.capacityMeshNodeId), o3.numSameLayerCrossings) : jz(this.capacityMeshNodeMap.get(e35.capacityMeshNodeId), o3.numSameLayerCrossings, o3.numEntryExitLayerChanges, o3.numTransitionPairCrossings);
  }
  getPortPointReusePenalty(e35, t2) {
    const n2 = this.assignedPortPoints.get(e35);
    return n2 ? t2 === n2.rootConnectionName ? 0 : this.PORT_POINT_REUSE_FACTOR : 0;
  }
  getOtherNodeId(e35, t2) {
    const [n2, o3] = e35.connectionNodeIds;
    return n2 === t2 ? o3 : o3 === t2 ? n2 : null;
  }
  computeG(e35, t2, n2, o3, i3) {
    const { currentNodeId: r3, point: s2 } = e35, a3 = { x: s2.x, y: s2.y, z: e35.z, connectionName: o3, rootConnectionName: i3 }, c3 = { x: t2.x, y: t2.y, z: t2.z, connectionName: o3, rootConnectionName: i3 }, l3 = this.getNodeDeltaFailureCostForSegment(r3, a3, c3);
    return e35.g + l3;
  }
  computeGToEndTarget(e35, t2, n2, o3) {
    const i3 = e35.currentNodeId, r3 = { x: e35.point.x, y: e35.point.y, z: e35.z, connectionName: n2, rootConnectionName: o3 }, s2 = { x: t2.x, y: t2.y, z: e35.z, connectionName: n2, rootConnectionName: o3 }, a3 = this.getNodeDeltaFailureCostForSegment(i3, r3, s2);
    return e35.g + a3;
  }
  computeDistanceToNearestOffBoardNode(e35) {
    if (this.offBoardNodes.length === 0)
      return 1 / 0;
    let t2 = 1 / 0;
    for (const n2 of this.offBoardNodes) {
      const o3 = me(e35, n2.center);
      o3 < t2 && (t2 = o3);
    }
    return t2;
  }
  computeH(e35, t2, n2, o3, i3, r3) {
    if (this.RANDOM_WALK_DISTANCE > 0 && i3 < this.RANDOM_WALK_DISTANCE)
      return 0;
    if (this.currentConnectionShouldRouteOffBoard && !r3)
      return this.BASE_COST_FOR_NOT_GOING_OFF_BOARD + this.computeDistanceToNearestOffBoardNode(e35);
    const s2 = this.nodeMap.get(n2);
    if (!s2)
      return 0;
    const a3 = me(e35, s2.center), c3 = this.avgNodePitch > 0 ? a3 / this.avgNodePitch : 0, l3 = this.clampPf(this.nodeMemoryPfMap.get(t2) ?? 0), h2 = this.pfToFailureCost(l3) * this.MEMORY_PF_FACTOR, d2 = c3 * this.BASE_CANDIDATE_COST, u2 = this.CENTER_OFFSET_DIST_PENALTY_FACTOR * e35.distToCentermostPortOnZ ** 2;
    let p3 = 0;
    if (this.STRAIGHT_LINE_DEVIATION_PENALTY_FACTOR > 0 && this.currentConnection) {
      const t3 = pe(e35, this.currentConnection.connection.pointsToConnect[0], this.currentConnection.connection.pointsToConnect[1]);
      p3 = this.STRAIGHT_LINE_DEVIATION_PENALTY_FACTOR * t3;
    }
    return a3 + d2 + h2 + u2 + p3;
  }
  getVisitedPortPointKey(e35, t2) {
    return this.currentConnectionShouldRouteOffBoard && t2 ? `${e35}:touched_off_board` : e35;
  }
  getAvailableExitPortPoints(e35, t2) {
    const n2 = this.currentConnection?.connection.__rootConnectionNames?.[0], o3 = this.nodePortPointsMap.get(e35) ?? [], i3 = [];
    for (const e36 of o3) {
      const o4 = this.getVisitedPortPointKey(e36.portPointId, t2);
      if (this.visitedPortPoints?.has(o4))
        continue;
      const r3 = this.assignedPortPoints.get(e36.portPointId);
      r3 && r3?.rootConnectionName !== n2 || i3.push(e36);
    }
    return i3;
  }
  getAvailableExitPortPointsWithOmissions(e35, t2, n2) {
    const o3 = this.nodePortPointsMap.get(e35) ?? [], i3 = this.currentConnection?.connection.__rootConnectionNames?.[0], r3 = new Map;
    for (const t3 of o3) {
      const o4 = this.getVisitedPortPointKey(t3.portPointId, n2);
      if (this.visitedPortPoints?.has(o4))
        continue;
      const i4 = this.getOtherNodeId(t3, e35);
      if (!i4)
        continue;
      this.nodeMap.get(i4);
      const s3 = `${i4}|${t3.z}`, a3 = r3.get(s3) ?? [];
      a3.push(t3), r3.set(s3, a3);
    }
    const s2 = [];
    for (const [, e36] of r3) {
      e36.sort((e37, t4) => e37.distToCentermostPortOnZ - t4.distToCentermostPortOnZ);
      const t3 = e36[0];
      if (!t3)
        continue;
      const n3 = this.assignedPortPoints.get(t3.portPointId), o4 = n3 && n3.rootConnectionName === i3;
      if (!n3 || o4) {
        s2.push(t3);
        continue;
      }
      const r4 = [...e36].sort((e37, t4) => e37.x !== t4.x ? e37.x - t4.x : e37.y - t4.y), a3 = [];
      let c3 = [];
      for (const e37 of r4) {
        const t4 = this.assignedPortPoints.get(e37.portPointId);
        !t4 || t4.rootConnectionName === i3 ? c3.push(e37) : c3.length > 0 && (a3.push(c3), c3 = []);
      }
      c3.length > 0 && a3.push(c3);
      for (const e37 of a3) {
        const t4 = Math.floor(e37.length / 2);
        s2.push(e37[t4]);
      }
    }
    return s2;
  }
  getAvailableExitPortPointsForOffboardConnection(e35, t2) {
    const n2 = this.nodeMap.get(e35);
    if (!n2)
      return [];
    const o3 = this.currentConnection?.connection.__rootConnectionNames?.[0], i3 = [];
    for (const r3 of n2?._offBoardConnectedCapacityMeshNodeIds ?? []) {
      if (r3 === e35)
        continue;
      if (!this.nodeMap.get(r3))
        continue;
      const n3 = this.nodePortPointsMap.get(r3) ?? [];
      for (const e36 of n3) {
        const n4 = this.getVisitedPortPointKey(e36.portPointId, t2);
        if (this.visitedPortPoints?.has(n4))
          continue;
        const s2 = this.assignedPortPoints.get(e36.portPointId);
        s2 && s2.rootConnectionName !== o3 || i3.push({ ...e36, throughNodeId: r3 });
      }
    }
    return i3;
  }
  canTravelThroughObstacle(e35, t2, n2) {
    const o3 = this.connectionNameToGoalNodeIds.get(t2);
    return o3?.includes(e35.capacityMeshNodeId) || Boolean(e35._offBoardConnectionId);
  }
  isAtEndGoal(e35, t2) {
    return e35 === t2;
  }
  getBacktrackedPath(e35) {
    const t2 = [];
    let n2 = e35;
    for (;n2; ) {
      if (n2.lastMoveWasOffBoard && n2.throughNodeId) {
        const e36 = this.nodeMap.get(n2.throughNodeId), o3 = n2.prevCandidate ? this.nodeMap.get(n2.prevCandidate.currentNodeId) : null;
        t2.push(n2), e36 && t2.push({ prevCandidate: null, portPoint: null, currentNodeId: n2.throughNodeId, point: e36.center, z: n2.z, f: 0, g: 0, h: 0, distanceTraveled: 0 }), o3 && o3._offBoardConnectionId && t2.push({ prevCandidate: null, portPoint: null, currentNodeId: n2.prevCandidate.currentNodeId, point: o3.center, z: n2.z, f: 0, g: 0, h: 0, distanceTraveled: 0 });
      } else
        t2.push(n2);
      n2 = n2.prevCandidate;
    }
    return t2.reverse();
  }
  assignPortPointsForPath(e35, t2, n2) {
    const o3 = [];
    for (let i4 = 0;i4 < e35.length; i4++) {
      const r4 = e35[i4];
      if (!r4.portPoint) {
        const s4 = i4 === 0, a4 = i4 === e35.length - 1;
        if (!s4 && !a4) {
          const e36 = { x: r4.point.x, y: r4.point.y, z: r4.z, connectionName: t2, rootConnectionName: n2 };
          o3.push(e36);
          const i5 = this.nodeAssignedPortPoints.get(r4.currentNodeId) ?? [];
          i5.push(e36), this.nodeAssignedPortPoints.set(r4.currentNodeId, i5);
        }
        continue;
      }
      const s3 = r4.portPoint;
      this.assignedPortPoints.set(s3.portPointId, { connectionName: t2, rootConnectionName: n2 });
      const a3 = { portPointId: s3.portPointId, x: s3.x, y: s3.y, z: s3.z, connectionName: t2, rootConnectionName: n2, prevPortPointId: s3.prevPortPointId, nextPortPointId: s3.nextPortPointId };
      o3.push(a3);
      for (const e36 of s3.connectionNodeIds) {
        const t3 = this.nodeAssignedPortPoints.get(e36) ?? [];
        t3.push(a3), this.nodeAssignedPortPoints.set(e36, t3);
      }
    }
    const i3 = o3.map((e36) => e36.portPointId).filter((e36) => Boolean(e36));
    let r3 = 0;
    for (const e36 of o3)
      e36.portPointId && (e36.prevPortPointId = i3[r3 - 1], e36.nextPortPointId = i3[r3 + 1], r3 += 1);
    const s2 = Array.from(new Set(e35.map((e36) => e36.currentNodeId)));
    for (const e36 of s2) {
      const o4 = this.nodeMap.get(e36);
      if (o4 && o4._offBoardConnectionId)
        for (const e37 of o4?._offBoardConnectedCapacityMeshNodeIds ?? []) {
          const o5 = this.nodePortPointsMap.get(e37) ?? [];
          for (const e38 of o5)
            this.assignedPortPoints.set(e38.portPointId, { connectionName: t2, rootConnectionName: n2 });
        }
    }
    return o3;
  }
  addTargetPointsToNodes(e35, t2) {
    const n2 = e35[0], o3 = e35[e35.length - 1], i3 = t2.pointsToConnect[0], r3 = t2.pointsToConnect[t2.pointsToConnect.length - 1];
    if (n2 && i3) {
      const e36 = this.nodeAssignedPortPoints.get(n2.currentNodeId) ?? [];
      e36.push({ x: i3.x, y: i3.y, z: n2.z, connectionName: t2.name, rootConnectionName: t2.__rootConnectionNames?.[0] }), this.nodeAssignedPortPoints.set(n2.currentNodeId, e36);
    }
    if (o3 && r3) {
      const e36 = this.nodeAssignedPortPoints.get(o3.currentNodeId) ?? [];
      e36.push({ x: r3.x, y: r3.y, z: o3.z, connectionName: t2.name, rootConnectionName: t2.__rootConnectionNames?.[0] }), this.nodeAssignedPortPoints.set(o3.currentNodeId, e36);
    }
  }
  isPortPointInPathChain(e35, t2) {
    let n2 = e35;
    for (;n2; ) {
      if (n2.portPoint?.portPointId === t2)
        return true;
      n2 = n2.prevCandidate;
    }
    return false;
  }
  isNodeInPathChain(e35, t2) {
    let n2 = e35;
    for (;n2; ) {
      if (n2.currentNodeId === t2)
        return true;
      n2 = n2.prevCandidate;
    }
    return false;
  }
  _step() {
    if (this.currentConnection || (this.currentConnection = this.unprocessedConnectionQueue.shift() ?? null), !this.currentConnection) {
      const e36 = this.computeBoardScore();
      return this.stats = { boardScore: e36, totalRipCount: this.totalRipCount }, e36 < this.MIN_ALLOWED_BOARD_SCORE ? (this.failedConnection = null, this.failed = true, void (this.error = `Board score ${e36.toFixed(2)} is less than MIN_ALLOWED_BOARD_SCORE ${this.MIN_ALLOWED_BOARD_SCORE.toFixed(2)}`)) : void (this.solved = true);
    }
    const e35 = this.currentConnection;
    this.activeCandidateStraightLineDistance = e35.straightLineDistance, this.currentPathIterations++;
    const t2 = this.getMaxIterationsForCurrentPath();
    if (this.currentPathIterations > t2)
      return this.failedConnection = e35, this.processedConnectionQueue.push(e35), this.currentConnection = null, this.candidates = null, this.visitedPortPoints = null, this.currentPathIterations = 0, this.failed = true, void (this.error = `Exceeded max iterations for path (${t2}) on connection ${e35.connection.name}`);
    const [n2, o3] = e35.nodeIds, i3 = this.nodeMap.get(n2), r3 = this.nodeMap.get(o3);
    if (!i3 || !r3)
      return this.processedConnectionQueue.push(e35), this.currentConnection = null, void (this.currentPathIterations = 0);
    const s2 = e35.connection.name, a3 = e35.connection.__rootConnectionNames?.[0], c3 = e35.connection.pointsToConnect[0];
    if (!this.candidates) {
      if (this.clearCostCaches(), this.FORCE_OFF_BOARD_FREQUENCY > 0) {
        const e36 = vr(17 * (this.hyperParameters.SHUFFLE_SEED ?? 0) + this.FORCE_OFF_BOARD_SEED + this.processedConnectionQueue.length);
        this.currentConnectionShouldRouteOffBoard = e36() < this.FORCE_OFF_BOARD_FREQUENCY;
      } else
        this.currentConnectionShouldRouteOffBoard = false;
      this.candidates = [], this.visitedPortPoints = new Set;
      for (const e36 of i3.availableZ) {
        const t3 = c3 ? { x: c3.x, y: c3.y } : i3.center, r4 = { portPointId: `start:${n2}:${e36}`, x: t3.x, y: t3.y, z: e36, connectionNodeIds: [n2, n2], distToCentermostPortOnZ: 0 }, s3 = this.computeH(r4, n2, o3, e36, 0, false), a4 = 0 + s3 * this.GREEDY_MULTIPLIER;
        this.candidates.push({ prevCandidate: null, portPoint: null, currentNodeId: n2, point: t3, z: e36, f: a4, g: 0, h: s3, distanceTraveled: 0, hasTouchedOffBoardNode: false });
      }
    }
    this.candidates.sort((e36, t3) => e36.f - t3.f);
    let l3, h2 = this.candidates.shift();
    for (;h2?.portPoint && this.visitedPortPoints; ) {
      const e36 = this.getVisitedPortPointKey(h2.portPoint.portPointId, h2.hasTouchedOffBoardNode);
      if (!this.visitedPortPoints.has(e36))
        break;
      h2 = this.candidates.shift();
    }
    if (this.candidates.length > this.MAX_CANDIDATES_IN_MEMORY && this.candidates.splice(this.MAX_CANDIDATES_IN_MEMORY, this.candidates.length - this.MAX_CANDIDATES_IN_MEMORY), !h2)
      return this.error = `Ran out of candidates on connection ${s2}`, this.failedConnection = e35, this.processedConnectionQueue.push(e35), this.currentConnection = null, this.candidates = null, this.visitedPortPoints = null, this.currentPathIterations = 0, void (this.failed = true);
    if (h2.portPoint && this.visitedPortPoints) {
      const e36 = this.getVisitedPortPointKey(h2.portPoint.portPointId, h2.hasTouchedOffBoardNode);
      this.visitedPortPoints.add(e36);
    }
    if (this.isAtEndGoal(h2.currentNodeId, o3)) {
      const t3 = e35.connection.pointsToConnect[e35.connection.pointsToConnect.length - 1], n3 = t3 ? { x: t3.x, y: t3.y } : r3.center, i4 = this.computeGToEndTarget(h2, n3, s2, a3), c4 = { prevCandidate: h2, portPoint: null, currentNodeId: o3, point: n3, z: h2.z, g: i4, h: 0, f: i4, distanceTraveled: h2.distanceTraveled + me(h2.point, n3) }, l4 = this.getBacktrackedPath(c4);
      return e35.path = l4, e35.portPoints = this.assignPortPointsForPath(l4, s2, a3), this.addTargetPointsToNodes(l4, e35.connection), this.clearCostCaches(), this.RIPPING_ENABLED && this.processRippingForPath(l4, s2), this.processedConnectionQueue.push(e35), this.currentConnection = null, this.progress = this.processedConnectionQueue.length / this.totalConnectionCount, this.candidates = null, this.visitedPortPoints = null, void (this.currentPathIterations = 0);
    }
    const d2 = this.nodeMap.get(h2.currentNodeId);
    l3 = d2?._offBoardConnectionId ? this.getAvailableExitPortPointsForOffboardConnection(h2.currentNodeId, h2.hasTouchedOffBoardNode) : this.FORCE_CENTER_FIRST ? this.getAvailableExitPortPointsWithOmissions(h2.currentNodeId, o3, h2.hasTouchedOffBoardNode) : this.getAvailableExitPortPoints(h2.currentNodeId, h2.hasTouchedOffBoardNode);
    for (const e36 of l3) {
      if (this.isPortPointInPathChain(h2, e36.portPointId))
        continue;
      if (this.visitedPortPoints?.has(e36.portPointId))
        continue;
      const t3 = this.getOtherNodeId(e36, e36.throughNodeId ?? h2.currentNodeId);
      if (!t3)
        continue;
      if (this.isNodeInPathChain(h2, t3))
        continue;
      const n3 = "throughNodeId" in e36 ? e36.throughNodeId : undefined, i4 = n3 ? this.nodeMap.get(n3) : null, r4 = this.nodeMap.get(t3);
      if (!r4)
        continue;
      if (r4._containsObstacle && !this.canTravelThroughObstacle(r4, s2, a3))
        continue;
      const c4 = this.computeG(h2, e36, t3, s2, a3);
      if (!this.RIPPING_ENABLED && c4 > -this.MIN_ALLOWED_BOARD_SCORE)
        continue;
      const l4 = h2.distanceTraveled + me(h2.point, e36), u2 = h2.hasTouchedOffBoardNode || Boolean(r4._offBoardConnectionId), p3 = this.computeH(e36, t3, o3, e36.z, l4, u2), m2 = c4 + p3 * this.GREEDY_MULTIPLIER, g2 = Boolean(d2?._offBoardConnectionId) && Boolean(i4?._offBoardConnectionId);
      this.candidates.push({ prevCandidate: h2, portPoint: e36, currentNodeId: t3, point: { x: e36.x, y: e36.y }, z: e36.z, f: m2, g: c4, h: p3, distanceTraveled: l4, lastMoveWasOffBoard: g2, throughNodeId: g2 ? n3 : undefined, hasTouchedOffBoardNode: u2 || Boolean(r4._offBoardConnectionId) || Boolean(d2?._offBoardConnectionId) });
    }
  }
  getNodesWithPortPoints() {
    const e35 = [];
    for (const t2 of this.inputNodes) {
      const n2 = this.nodeAssignedPortPoints.get(t2.capacityMeshNodeId) ?? [];
      n2.length > 0 && e35.push({ capacityMeshNodeId: t2.capacityMeshNodeId, center: t2.center, width: t2.width, height: t2.height, portPoints: n2, availableZ: t2.availableZ });
    }
    return e35;
  }
  getConnectionsInNode(e35, t2) {
    const n2 = [], o3 = new Set;
    for (const i3 of this.connectionsWithResults)
      if (i3.path && i3.connection.name !== t2 && !o3.has(i3.connection.name)) {
        for (const t3 of i3.path)
          if (t3.currentNodeId === e35) {
            n2.push(i3), o3.add(i3.connection.name);
            break;
          }
      }
    return n2;
  }
  computeNodePfWithoutConnection(e35, t2) {
    if (e35._containsTarget)
      return { pf: 0, totalCrossings: 0 };
    const n2 = (this.nodeAssignedPortPoints.get(e35.capacityMeshNodeId) ?? []).filter((e36) => e36.connectionName !== t2), o3 = { capacityMeshNodeId: e35.capacityMeshNodeId, center: e35.center, width: e35.width, height: e35.height, portPoints: n2, availableZ: e35.availableZ }, i3 = Cz(o3), r3 = i3.numSameLayerCrossings + i3.numEntryExitLayerChanges + i3.numTransitionPairCrossings;
    return { pf: jz(this.capacityMeshNodeMap.get(e35.capacityMeshNodeId), i3.numSameLayerCrossings, i3.numEntryExitLayerChanges, i3.numTransitionPairCrossings), totalCrossings: r3 };
  }
  computeNodeCrossings(e35) {
    if (e35._containsTarget)
      return 0;
    const t2 = this.buildNodeWithPortPointsForCrossing(e35), n2 = Cz(t2);
    return n2.numSameLayerCrossings + n2.numEntryExitLayerChanges + n2.numTransitionPairCrossings;
  }
  ripConnection(e35) {
    const t2 = e35.connection.name;
    for (const [e36, n2] of this.assignedPortPoints.entries())
      n2.connectionName === t2 && this.assignedPortPoints.delete(e36);
    for (const [e36, n2] of this.nodeAssignedPortPoints.entries()) {
      const o3 = n2.filter((e37) => e37.connectionName !== t2);
      this.nodeAssignedPortPoints.set(e36, o3);
    }
    e35.path = undefined, e35.portPoints = undefined;
  }
  requeueConnection(e35) {
    this.totalRipCount++;
    const t2 = this.processedConnectionQueue.indexOf(e35);
    if (t2 !== -1)
      return this.processedConnectionQueue.splice(t2, 1), this.unprocessedConnectionQueue.push(e35), true;
    const n2 = this.unprocessedConnectionQueue.indexOf(e35);
    return n2 !== -1 && (this.unprocessedConnectionQueue.splice(n2, 1), this.unprocessedConnectionQueue.unshift(e35)), true;
  }
  processRippingForPath(e35, t2) {
    const n2 = Array.from(new Set(e35.map((e36) => e36.currentNodeId)));
    let o3 = false;
    for (const e36 of n2) {
      if (this.totalRipCount > this.MAX_RIPS)
        break;
      const n3 = this.nodeMap.get(e36);
      if (!n3)
        continue;
      let i3 = this.computeNodePf(n3);
      if (i3 <= this.RIPPING_PF_THRESHOLD)
        continue;
      this.testedRipConnections.has(e36) || this.testedRipConnections.set(e36, new Set);
      const r3 = this.testedRipConnections.get(e36), s2 = Sr(this.getConnectionsInNode(e36, t2), (this.hyperParameters.SHUFFLE_SEED ?? 0) + this.processedConnectionQueue.length);
      for (const e37 of s2) {
        if (i3 <= this.RIPPING_PF_THRESHOLD)
          break;
        const t3 = e37.connection.name;
        r3.add(t3);
        const { pf: s3 } = this.computeNodePfWithoutConnection(n3, t3);
        this.ripConnection(e37);
        if (!this.requeueConnection(e37))
          return;
        i3 = s3, o3 = true, this.clearCostCaches();
      }
    }
    o3 && this.RANDOM_RIP_FRACTION > 0 && this.processRandomRipping(t2);
  }
  processRandomRipping(e35) {
    const t2 = this.processedConnectionQueue.filter((t3) => t3.path !== undefined && t3.connection.name !== e35);
    if (t2.length === 0)
      return;
    const n2 = Math.max(1, Math.floor(this.RANDOM_RIP_FRACTION * t2.length)), o3 = Sr(t2, (this.hyperParameters.SHUFFLE_SEED ?? 0) + this.totalRipCount + this.processedConnectionQueue.length);
    for (let e36 = 0;e36 < n2 && e36 < o3.length && !(this.totalRipCount > this.MAX_RIPS); e36++) {
      const t3 = o3[e36];
      this.ripConnection(t3);
      if (!this.requeueConnection(t3))
        return;
      this.clearCostCaches();
    }
  }
  visualize() {
    let e35 = {};
    if (this.failed) {
      const t2 = this.failedConnection?.connection.pointsToConnect[0], n2 = this.failedConnection?.connection.pointsToConnect[1];
      t2 && n2 && (e35 = { lines: [{ points: [t2, n2], label: `Failed Connection ${this.failedConnection?.connection.name}`, strokeWidth: 1, strokeColor: "red", strokeDash: [2, 2] }] });
    }
    return Gn(qz(this), e35);
  }
};
var Kz = class extends wa {
  getSolverName() {
    return "HyperPortPointPathingSolver";
  }
  params;
  precomputedInitialParams;
  constructor(e35) {
    super(), this.params = e35, this.MAX_ITERATIONS = 1e8, this.GREEDY_MULTIPLIER = 1.2, this.MIN_SUBSTEPS = 50, this.precomputedInitialParams = e35.precomputedInitialParams ?? zz(e35.simpleRouteJson, e35.inputNodes);
  }
  getHyperParameterDefs() {
    const e35 = this.params.numShuffleSeeds ?? 50;
    return [{ name: "SHUFFLE_SEED", possibleValues: Array.from({ length: e35 }, (e36, t2) => ({ SHUFFLE_SEED: t2 + 1700 * (this.params.hyperParameters?.SHUFFLE_SEED ?? 0) })) }];
  }
  getCombinationDefs() {
    return [["SHUFFLE_SEED"]];
  }
  generateSolver(e35) {
    return new Qz({ simpleRouteJson: this.params.simpleRouteJson, capacityMeshNodes: this.params.capacityMeshNodes, inputNodes: this.params.inputNodes, colorMap: this.params.colorMap, nodeMemoryPfMap: this.params.nodeMemoryPfMap, hyperParameters: { ...this.params.hyperParameters, ...e35, MIN_ALLOWED_BOARD_SCORE: this.params.minAllowedBoardScore ?? e35.MIN_ALLOWED_BOARD_SCORE ?? this.params.hyperParameters?.MIN_ALLOWED_BOARD_SCORE }, precomputedInitialParams: this.precomputedInitialParams, fixedRoutes: this.params.fixedRoutes });
  }
  computeG(e35) {
    return -e35.computeBoardScore();
  }
  computeH(e35) {
    const t2 = e35.progress || 0;
    if (t2 < 0.1)
      return 0;
    return -(e35.computeBoardScore() / t2) * (1 - t2);
  }
  getNodesWithPortPoints() {
    if (this.winningSolver)
      return this.winningSolver.getNodesWithPortPoints();
    const e35 = this.getSupervisedSolverWithBestFitness();
    return e35 ? e35.solver.getNodesWithPortPoints() : [];
  }
  get connectionsWithResults() {
    if (this.winningSolver)
      return this.winningSolver.connectionsWithResults;
    const e35 = this.getSupervisedSolverWithBestFitness();
    return e35 ? e35.solver.connectionsWithResults : [];
  }
  get inputNodes() {
    if (this.winningSolver)
      return this.winningSolver.inputNodes;
    const e35 = this.getSupervisedSolverWithBestFitness();
    return e35 ? e35.solver.inputNodes : this.params.inputNodes;
  }
  get nodeMap() {
    if (this.winningSolver)
      return this.winningSolver.nodeMap;
    const e35 = this.getSupervisedSolverWithBestFitness();
    return e35 ? e35.solver.nodeMap : new Map(this.params.inputNodes.map((e36) => [e36.capacityMeshNodeId, e36]));
  }
  get assignedPortPoints() {
    if (this.winningSolver)
      return this.winningSolver.assignedPortPoints;
    const e35 = this.getSupervisedSolverWithBestFitness();
    return e35 ? e35.solver.assignedPortPoints : new Map;
  }
  get nodeAssignedPortPoints() {
    if (this.winningSolver)
      return this.winningSolver.nodeAssignedPortPoints;
    const e35 = this.getSupervisedSolverWithBestFitness();
    return e35 ? e35.solver.nodeAssignedPortPoints : new Map;
  }
  computeNodePf(e35) {
    if (this.winningSolver)
      return this.winningSolver.computeNodePf(e35);
    const t2 = this.getSupervisedSolverWithBestFitness();
    return t2 ? t2.solver.computeNodePf(e35) : null;
  }
  computeBoardScore() {
    if (this.winningSolver)
      return this.winningSolver.computeBoardScore();
    const e35 = this.getSupervisedSolverWithBestFitness();
    return e35 ? e35.solver.computeBoardScore() : 0;
  }
  onSolve(e35) {
    this.stats = { ...e35.solver.stats, winningHyperParameters: this.winningSolver?.hyperParameters };
  }
  visualize() {
    return this.winningSolver ? this.winningSolver.visualize() : super.visualize();
  }
};
function eB(e35) {
  let t2 = e35;
  return () => {
    t2 += 1831565813;
    let e36 = t2;
    return e36 = Math.imul(e36 ^ e36 >>> 15, 1 | e36), e36 ^= e36 + Math.imul(e36 ^ e36 >>> 7, 61 | e36), ((e36 ^ e36 >>> 14) >>> 0) / 4294967296;
  };
}
var tB = [{ SHUFFLE_SEED: 100, NODE_PF_FACTOR: 100, NODE_PF_MAX_PENALTY: 100, MEMORY_PF_FACTOR: 0, EXPANSION_DEGREES: 10, FORCE_CENTER_FIRST: true, FORCE_OFF_BOARD_FREQUENCY: 0, CENTER_OFFSET_DIST_PENALTY_FACTOR: 0 }];
var nB = class extends ni {
  getSolverName() {
    return "MultiSectionPortPointOptimizer";
  }
  simpleRouteJson;
  inputNodes;
  capacityMeshNodes;
  capacityMeshEdges;
  colorMap;
  nodeMap;
  capacityMeshNodeMap;
  connectionResults;
  assignedPortPoints;
  nodeAssignedPortPoints;
  sections = [];
  activeSubSolver = null;
  currentSection = null;
  sectionScoreBeforeOptimization = 0;
  currentSectionCenterNodeId = null;
  currentScheduleIndex = 0;
  nodePfMap = new Map;
  attemptsToFixNode = new Map;
  sectionAttempts = 0;
  MAX_ATTEMPTS_PER_NODE = 100;
  MAX_SECTION_ATTEMPTS = 15;
  ACCEPTABLE_PF = 0.05;
  FRACTION_TO_REPLACE = 0.2;
  JUMPER_PF_FN_ENABLED = false;
  SHUFFLE_SEEDS_PER_SECTION = null;
  ALWAYS_RIP_INTERSECTIONS = true;
  effort = 1;
  HYPERPARAMETER_SCHEDULE = tB;
  constructor(e35) {
    super(), this.MAX_ITERATIONS = 1e6, this.simpleRouteJson = e35.simpleRouteJson, this.inputNodes = e35.inputNodes, this.capacityMeshNodes = e35.capacityMeshNodes, this.capacityMeshEdges = e35.capacityMeshEdges, this.colorMap = e35.colorMap ?? {}, this.effort = e35.effort ?? 1, e35.FRACTION_TO_REPLACE !== undefined && (this.FRACTION_TO_REPLACE = e35.FRACTION_TO_REPLACE), e35.ALWAYS_RIP_INTERSECTIONS !== undefined && (this.ALWAYS_RIP_INTERSECTIONS = e35.ALWAYS_RIP_INTERSECTIONS), e35.MAX_ATTEMPTS_PER_NODE !== undefined && (this.MAX_ATTEMPTS_PER_NODE = e35.MAX_ATTEMPTS_PER_NODE), e35.MAX_SECTION_ATTEMPTS !== undefined && (this.MAX_SECTION_ATTEMPTS = e35.MAX_SECTION_ATTEMPTS), e35.HYPERPARAMETER_SCHEDULE !== undefined && (this.HYPERPARAMETER_SCHEDULE = e35.HYPERPARAMETER_SCHEDULE), this.JUMPER_PF_FN_ENABLED = e35.JUMPER_PF_FN_ENABLED ?? this.JUMPER_PF_FN_ENABLED, this.SHUFFLE_SEEDS_PER_SECTION = e35.SHUFFLE_SEEDS_PER_SECTION, this.nodeMap = new Map(e35.inputNodes.map((e36) => [e36.capacityMeshNodeId, e36])), this.capacityMeshNodeMap = new Map(e35.capacityMeshNodes.map((e36) => [e36.capacityMeshNodeId, e36])), this.connectionResults = [...e35.initialConnectionResults], this.assignedPortPoints = new Map(e35.initialAssignedPortPoints), this.nodeAssignedPortPoints = new Map(e35.initialNodeAssignedPortPoints), this.nodePfMap = this.computeInitialPfMap();
    const t2 = this.computeBoardScore();
    this.stats.successfulOptimizations = 0, this.stats.failedOptimizations = 0, this.stats.nodesExamined = 0, this.stats.sectionAttempts = 0, this.stats.sectionScores = {}, this.stats.initialBoardScore = t2, this.stats.currentBoardScore = t2, this.stats.errors = 0;
  }
  computeInitialPfMap() {
    const e35 = new Map;
    for (const t2 of this.capacityMeshNodes) {
      const n2 = this.nodeAssignedPortPoints.get(t2.capacityMeshNodeId) ?? [];
      if (n2.length === 0)
        continue;
      const o3 = { capacityMeshNodeId: t2.capacityMeshNodeId, center: t2.center, width: t2.width, height: t2.height, portPoints: n2, availableZ: t2.availableZ }, i3 = this.JUMPER_PF_FN_ENABLED && t2.availableZ.length === 1 ? Vz(t2, Cz(o3).numSameLayerCrossings) : Yz(o3, t2);
      e35.set(t2.capacityMeshNodeId, i3);
    }
    return e35;
  }
  computeBoardScore() {
    const e35 = this.getNodesWithPortPoints();
    return this.computeScoreForNodes(e35);
  }
  computeScoreForNodes(e35) {
    return this.JUMPER_PF_FN_ENABLED ? Jz(e35, this.capacityMeshNodeMap) : $z(e35, this.capacityMeshNodeMap);
  }
  recomputePfForNodes(e35) {
    for (const t2 of e35) {
      const e36 = this.capacityMeshNodeMap.get(t2);
      if (!e36)
        continue;
      const n2 = this.nodeAssignedPortPoints.get(t2) ?? [];
      if (n2.length === 0) {
        this.nodePfMap.set(t2, 0);
        continue;
      }
      const o3 = { capacityMeshNodeId: t2, center: e36.center, width: e36.width, height: e36.height, portPoints: n2, availableZ: e36.availableZ }, i3 = this.JUMPER_PF_FN_ENABLED && e36.availableZ.length === 1 ? Vz(e36, Cz(o3).numSameLayerCrossings) : Yz(o3, e36);
      this.nodePfMap.set(t2, i3);
    }
  }
  getCreatePortPointSectionInput() {
    return { inputNodes: this.inputNodes, capacityMeshNodes: this.capacityMeshNodes, capacityMeshEdges: this.capacityMeshEdges, nodeMap: this.nodeMap, connectionResults: this.connectionResults };
  }
  createSection(e35) {
    return function(e36, t2) {
      const { inputNodes: n2, capacityMeshNodes: o3, capacityMeshEdges: i3, connectionResults: r3 } = e36, { centerOfSectionCapacityNodeId: s2, expansionDegrees: a3 } = t2, c3 = new Map;
      for (const e37 of i3) {
        const [t3, n3] = e37.nodeIds;
        c3.has(t3) || c3.set(t3, new Set), c3.has(n3) || c3.set(n3, new Set), c3.get(t3).add(n3), c3.get(n3).add(t3);
      }
      const l3 = new Set, h2 = new Set, d2 = [];
      for (d2.push({ nodeId: s2, depth: 0 }), h2.add(s2);d2.length > 0; ) {
        const { nodeId: e37, depth: t3 } = d2.shift();
        if (l3.add(e37), t3 < a3) {
          const n3 = c3.get(e37) ?? new Set;
          for (const e38 of n3)
            h2.has(e38) || (h2.add(e38), d2.push({ nodeId: e38, depth: t3 + 1 }));
        }
      }
      const u2 = n2.filter((e37) => l3.has(e37.capacityMeshNodeId)), p3 = o3.filter((e37) => l3.has(e37.capacityMeshNodeId)), m2 = [], g2 = [];
      for (const e37 of i3) {
        const [t3, n3] = e37.nodeIds, o4 = l3.has(t3), i4 = l3.has(n3);
        o4 && i4 ? m2.push(e37) : (o4 || i4) && g2.push(e37);
      }
      const f2 = u2.map((e37) => {
        const t3 = e37.portPoints.filter((e38) => {
          const [t4, n3] = e38.connectionNodeIds, o4 = l3.has(t4), i4 = l3.has(n3);
          return o4 || i4;
        });
        return { ...e37, portPoints: t3 };
      }), _2 = function(e37, t3) {
        const n3 = [];
        for (const o4 of e37) {
          if (!o4.path || o4.path.length === 0)
            continue;
          const e38 = o4.connection.name, i4 = o4.connection.__rootConnectionNames?.[0], r4 = [];
          for (let e39 = 0;e39 < o4.path.length; e39++) {
            const n4 = o4.path[e39];
            t3.has(n4.currentNodeId) && r4.push(e39);
          }
          if (r4.length === 0)
            continue;
          const s3 = r4[0], a4 = r4[r4.length - 1];
          let c4 = s3, l4 = a4;
          if (s3 > 0) {
            const e39 = o4.path[0].currentNodeId;
            (o4.nodeIds[0] === e39 || o4.nodeIds[1] === e39) && (c4 = 0);
          }
          if (a4 < o4.path.length - 1) {
            const e39 = o4.path.length - 1, t4 = o4.path[e39].currentNodeId;
            (o4.nodeIds[0] === t4 || o4.nodeIds[1] === t4) && (l4 = e39);
          }
          const h3 = o4.path.slice(c4, l4 + 1), d3 = c4 > 0, u3 = l4 < o4.path.length - 1;
          n3.push({ connectionName: e38, rootConnectionName: i4, points: h3.map((e39) => ({ x: e39.point.x, y: e39.point.y, z: e39.z, nodeId: e39.currentNodeId, portPointId: e39.portPoint?.portPointId })), originalStartIndex: c4, originalEndIndex: l4, hasEntryFromOutside: d3, hasExitToOutside: u3 });
        }
        return n3;
      }(r3 ?? [], l3);
      return { centerNodeId: s2, expansionDegrees: a3, nodeIds: l3, inputNodes: f2, capacityMeshNodes: p3, internalEdges: m2, boundaryEdges: g2, sectionPaths: _2 };
    }(this.getCreatePortPointSectionInput(), e35);
  }
  getSectionNodesWithPortPoints(e35) {
    const t2 = [];
    for (const n2 of e35.nodeIds) {
      const e36 = this.nodeMap.get(n2), o3 = this.capacityMeshNodeMap.get(n2);
      if (!e36 || !o3)
        continue;
      const i3 = this.nodeAssignedPortPoints.get(n2) ?? [];
      i3.length > 0 && t2.push({ capacityMeshNodeId: n2, center: e36.center, width: e36.width, height: e36.height, portPoints: i3, availableZ: e36.availableZ });
    }
    return t2;
  }
  getNodesWithPortPoints() {
    const e35 = [];
    for (const t2 of this.inputNodes) {
      const n2 = this.nodeAssignedPortPoints.get(t2.capacityMeshNodeId) ?? [];
      n2.length > 0 && e35.push({ capacityMeshNodeId: t2.capacityMeshNodeId, center: t2.center, width: t2.width, height: t2.height, portPoints: n2, availableZ: t2.availableZ });
    }
    return e35;
  }
  findHighestPfNode() {
    let e35 = null, t2 = 0;
    for (const [n2, o3] of this.nodePfMap.entries()) {
      o3 * (1 - (this.attemptsToFixNode.get(n2) ?? 0) / this.MAX_ATTEMPTS_PER_NODE) ** 2 > t2 && (t2 = o3, e35 = n2);
    }
    return !e35 || t2 < this.ACCEPTABLE_PF ? null : e35;
  }
  currentSectionCutPathInfo = new Map;
  currentSectionKeptPortPoints = new Map;
  currentSectionFixedRoutes = [];
  determineConnectionsToRip(e35, t2) {
    const n2 = 31337 * this.sectionAttempts, o3 = eB(n2);
    if (this.FRACTION_TO_REPLACE >= 1)
      return new Set(t2);
    const i3 = function(e36, t3) {
      const n3 = eB(t3), o4 = [...e36];
      for (let e37 = o4.length - 1;e37 > 0; e37--) {
        const t4 = Math.floor(n3() * (e37 + 1));
        [o4[e37], o4[t4]] = [o4[t4], o4[e37]];
      }
      return o4;
    }(t2, n2), r3 = Math.max(1, Math.ceil(i3.length * this.FRACTION_TO_REPLACE)), s2 = new Set(i3.slice(0, r3));
    if (this.ALWAYS_RIP_INTERSECTIONS) {
      const n3 = function(e36) {
        const { section: t3, nodePfMap: n4, capacityMeshNodeMap: o4, nodeAssignedPortPoints: i4, acceptablePf: r4 } = e36, s3 = [];
        for (const e37 of t3.nodeIds) {
          if ((n4.get(e37) ?? 0) <= r4)
            continue;
          const t4 = o4.get(e37);
          if (!t4)
            continue;
          const a3 = i4.get(e37) ?? [];
          if (a3.length < 2)
            continue;
          const c3 = t4.center.x - t4.width / 2, l3 = t4.center.x + t4.width / 2, h2 = t4.center.y - t4.height / 2, d2 = t4.center.y + t4.height / 2, u2 = new Map;
          for (const e38 of a3) {
            const t5 = u2.get(e38.connectionName) ?? [];
            t5.some((t6) => t6.x === e38.x && t6.y === e38.y && t6.z === e38.z) || t5.push({ x: e38.x, y: e38.y, z: e38.z }), u2.set(e38.connectionName, t5);
          }
          const p3 = new Map;
          for (const [e38, t5] of u2) {
            if (t5.length < 2)
              continue;
            const n5 = t5[0], o5 = t5[1];
            if (n5.z !== o5.z)
              continue;
            const i5 = Xz(n5, c3, l3, h2, d2), r5 = Xz(o5, c3, l3, h2, d2), s4 = n5.z, a4 = p3.get(s4) ?? [];
            a4.push({ connectionName: e38, t1: i5, t2: r5 }), p3.set(s4, a4);
          }
          const m2 = 0.000001;
          for (const [, e38] of p3) {
            const t5 = e38.map((e39) => ({ connectionName: e39.connectionName, a: Math.min(e39.t1, e39.t2), b: Math.max(e39.t1, e39.t2) }));
            for (let e39 = 0;e39 < t5.length; e39++) {
              const { connectionName: n5, a: o5, b: i5 } = t5[e39];
              for (let r5 = e39 + 1;r5 < t5.length; r5++) {
                const { connectionName: e40, a: a4, b: c4 } = t5[r5];
                Math.abs(o5 - a4) < m2 || Math.abs(o5 - c4) < m2 || Math.abs(i5 - a4) < m2 || Math.abs(i5 - c4) < m2 || (o5 < a4 && a4 < i5 && i5 < c4 || a4 < o5 && o5 < c4 && c4 < i5) && s3.push([n5, e40]);
              }
            }
          }
        }
        return s3;
      }({ section: e35, nodePfMap: this.nodePfMap, capacityMeshNodeMap: this.capacityMeshNodeMap, nodeAssignedPortPoints: this.nodeAssignedPortPoints, acceptablePf: this.ACCEPTABLE_PF });
      for (const [e36, i4] of n3) {
        if (s2.has(e36) || s2.has(i4))
          continue;
        const n4 = t2.includes(e36), r4 = t2.includes(i4);
        if (n4 && r4) {
          const t3 = o3() < 0.5;
          s2.add(t3 ? e36 : i4);
        } else
          n4 ? s2.add(e36) : r4 && s2.add(i4);
      }
    }
    return this.stats.lastRipCount = s2.size, s2;
  }
  createSectionSimpleRouteJson(e35) {
    const t2 = [];
    this.currentSectionCutPathInfo.clear(), this.currentSectionKeptPortPoints.clear(), this.currentSectionFixedRoutes = [];
    const n2 = [], o3 = [];
    for (const t3 of this.connectionResults) {
      if (!t3.path || t3.path.length === 0)
        continue;
      const [i4, r4] = t3.nodeIds, s3 = e35.nodeIds.has(i4), a3 = e35.nodeIds.has(r4);
      s3 && a3 && (o3.push(t3), n2.push(t3.connection.name));
    }
    const i3 = [];
    for (const t3 of e35.sectionPaths) {
      if (!t3.hasEntryFromOutside && !t3.hasExitToOutside)
        continue;
      if (t3.points.length < 2)
        continue;
      const e36 = this.connectionResults.find((e37) => e37.connection.name === t3.connectionName);
      e36 && (i3.push({ sectionPath: t3, originalResult: e36 }), n2.includes(t3.connectionName) || n2.push(t3.connectionName));
    }
    const r3 = this.determineConnectionsToRip(e35, n2);
    for (const e36 of o3)
      r3.has(e36.connection.name) && t2.push(e36.connection);
    for (const { sectionPath: e36, originalResult: n3 } of i3) {
      if (!r3.has(e36.connectionName))
        continue;
      const o4 = `__cut__${e36.connectionName}__${e36.originalStartIndex}`;
      this.colorMap[o4] = this.colorMap[e36.connectionName];
      const i4 = e36.points[0], s3 = e36.points[e36.points.length - 1], a3 = { name: o4, __rootConnectionNames: [e36.rootConnectionName ?? e36.connectionName], pointsToConnect: [{ x: i4.x, y: i4.y, layers: [`layer${i4.z + 1}`] }, { x: s3.x, y: s3.y, layers: [`layer${s3.z + 1}`] }] };
      t2.push(a3), this.currentSectionCutPathInfo.set(o4, { sectionPath: e36, originalConnectionResult: n3 });
    }
    const s2 = new Set(n2.filter((e36) => !r3.has(e36)));
    if (s2.size > 0) {
      for (const t3 of e35.nodeIds) {
        const e36 = (this.nodeAssignedPortPoints.get(t3) ?? []).filter((e37) => s2.has(e37.connectionName));
        e36.length > 0 && this.currentSectionKeptPortPoints.set(t3, e36);
      }
      for (const e36 of o3)
        s2.has(e36.connection.name) && this.currentSectionFixedRoutes.push(e36);
      for (const { sectionPath: e36, originalResult: t3 } of i3)
        if (s2.has(e36.connectionName)) {
          const n3 = { connection: { name: e36.connectionName, __rootConnectionNames: e36.rootConnectionName ? [e36.rootConnectionName] : undefined, pointsToConnect: t3.connection.pointsToConnect }, path: e36.points.map((e37) => ({ prevCandidate: null, portPoint: null, currentNodeId: e37.nodeId, point: { x: e37.x, y: e37.y }, z: e37.z, f: 0, g: 0, h: 0, distanceTraveled: 0 })), portPoints: e36.points.map((t4) => ({ portPointId: t4.portPointId, x: t4.x, y: t4.y, z: t4.z, connectionName: e36.connectionName, rootConnectionName: e36.rootConnectionName })), nodeIds: t3.nodeIds, straightLineDistance: t3.straightLineDistance };
          this.currentSectionFixedRoutes.push(n3);
        }
    }
    return { ...this.simpleRouteJson, connections: t2 };
  }
  prepareSectionInputNodesForCutPaths(e35) {
    const t2 = new Set;
    for (const [, e36] of this.currentSectionCutPathInfo.entries()) {
      const { sectionPath: n2 } = e36;
      if (n2.points.length === 0)
        continue;
      const o3 = n2.points[0].nodeId;
      t2.add(o3);
      const i3 = n2.points[n2.points.length - 1].nodeId;
      t2.add(i3);
    }
    return e35.inputNodes.map((e36) => t2.has(e36.capacityMeshNodeId) ? { ...e36, _containsTarget: true } : e36);
  }
  getHyperParametersForScheduleIndex(e35, t2) {
    const n2 = this.HYPERPARAMETER_SCHEDULE[e35];
    return { ...n2, SHUFFLE_SEED: (n2.SHUFFLE_SEED ?? 0) + 17 * t2 };
  }
  createSectionSolver(e35) {
    const t2 = this.createSectionSimpleRouteJson(e35), n2 = this.prepareSectionInputNodesForCutPaths(e35), o3 = zz(t2, n2);
    for (const [e36, t3] of this.currentSectionKeptPortPoints) {
      const n3 = o3.nodeAssignedPortPoints.get(e36) ?? [];
      o3.nodeAssignedPortPoints.set(e36, [...n3, ...t3]);
    }
    return new Kz({ simpleRouteJson: t2, inputNodes: n2, capacityMeshNodes: e35.capacityMeshNodes, colorMap: this.colorMap, nodeMemoryPfMap: this.nodePfMap, numShuffleSeeds: this.SHUFFLE_SEEDS_PER_SECTION ?? 2 * t2.connections.length * this.effort, hyperParameters: { ...this.getHyperParametersForScheduleIndex(this.currentScheduleIndex, this.sectionAttempts) }, precomputedInitialParams: o3, fixedRoutes: this.currentSectionFixedRoutes });
  }
  reattachSection(e35, t2, n2, o3) {
    const i3 = [], r3 = [];
    for (const e36 of t2)
      e36.connection.name.startsWith("__cut__") ? r3.push(e36) : i3.push(e36);
    const s2 = new Set(i3.map((e36) => e36.connection.name));
    this.connectionResults = this.connectionResults.filter((e36) => !s2.has(e36.connection.name)), this.connectionResults.push(...i3);
    for (const [t3, n3] of this.nodeAssignedPortPoints.entries()) {
      if (!e35.nodeIds.has(t3))
        continue;
      const o4 = n3.filter((e36) => !s2.has(e36.connectionName));
      this.nodeAssignedPortPoints.set(t3, o4);
    }
    for (const [e36, t3] of this.assignedPortPoints.entries())
      s2.has(t3.connectionName) && this.assignedPortPoints.delete(e36);
    for (const t3 of r3) {
      const n3 = this.currentSectionCutPathInfo.get(t3.connection.name);
      if (!n3 || !t3.path)
        continue;
      const { sectionPath: o4, originalConnectionResult: i4 } = n3, r4 = i4.path;
      if (!r4)
        continue;
      const s3 = o4.connectionName;
      for (const [t4, n4] of this.nodeAssignedPortPoints.entries()) {
        const o5 = n4.filter((n5) => n5.connectionName !== s3 || !e35.nodeIds.has(t4));
        this.nodeAssignedPortPoints.set(t4, o5);
      }
      const a3 = r4.slice(0, o4.originalStartIndex), c3 = r4.slice(o4.originalEndIndex + 1), l3 = [];
      let h2 = a3.length > 0 ? a3[a3.length - 1] : null;
      for (const e36 of t3.path) {
        const t4 = { ...e36, prevCandidate: h2 };
        l3.push(t4), h2 = t4;
      }
      if (c3.length > 0 && l3.length > 0 && (c3[0] = { ...c3[0], prevCandidate: l3[l3.length - 1] }), i4.path = [...a3, ...l3, ...c3], t3.portPoints)
        for (const n4 of t3.portPoints) {
          const t4 = { ...n4, connectionName: s3, rootConnectionName: o4.rootConnectionName ?? s3 };
          for (const o5 of e35.inputNodes)
            for (const e36 of o5.portPoints)
              if (Math.abs(e36.x - n4.x) < 0.001 && Math.abs(e36.y - n4.y) < 0.001 && e36.z === n4.z) {
                for (const n5 of e36.connectionNodeIds) {
                  const e37 = this.nodeAssignedPortPoints.get(n5) ?? [];
                  e37.push(t4), this.nodeAssignedPortPoints.set(n5, e37);
                }
                break;
              }
        }
    }
    for (const [e36, t3] of n2.entries())
      t3.connectionName.startsWith("__cut__") || this.assignedPortPoints.set(e36, t3);
    for (const [e36, t3] of o3.entries()) {
      const n3 = t3.filter((e37) => !e37.connectionName.startsWith("__cut__"));
      if (n3.length > 0) {
        const t4 = this.nodeAssignedPortPoints.get(e36) ?? [];
        this.nodeAssignedPortPoints.set(e36, [...t4, ...n3]);
      }
    }
  }
  _step() {
    if (this.activeSubSolver) {
      if (this.activeSubSolver.step(), this.activeSubSolver.solved || this.activeSubSolver.failed) {
        if (this.activeSubSolver.failed) {
          if (this.currentScheduleIndex++, this.activeSubSolver.error && this.stats.errors++, this.currentScheduleIndex < this.HYPERPARAMETER_SCHEDULE.length && this.currentSectionCenterNodeId) {
            const e37 = this.HYPERPARAMETER_SCHEDULE[this.currentScheduleIndex];
            this.currentSection = this.createSection({ centerOfSectionCapacityNodeId: this.currentSectionCenterNodeId, expansionDegrees: e37.EXPANSION_DEGREES }), this.activeSubSolver = this.createSectionSolver(this.currentSection);
          } else
            this.stats.failedOptimizations++, this.activeSubSolver = null, this.currentSection = null, this.currentSectionCenterNodeId = null, this.currentScheduleIndex = 0;
          return;
        }
        const e36 = this.activeSubSolver.getNodesWithPortPoints().map((e37) => ({ ...e37, portPoints: e37.portPoints.map((e38) => {
          if (e38.connectionName.startsWith("__cut__")) {
            const t4 = e38.connectionName.slice(7), n4 = t4.lastIndexOf("__"), o4 = n4 >= 0 ? t4.slice(0, n4) : t4;
            return { ...e38, connectionName: o4 };
          }
          return e38;
        }) })), t3 = new Set;
        for (const n4 of e36)
          for (const e37 of n4.portPoints)
            t3.add(e37.connectionName);
        const n3 = this.getSectionNodesWithPortPoints(this.currentSection).map((e37) => ({ ...e37, portPoints: e37.portPoints.filter((e38) => t3.has(e38.connectionName)) })).filter((e37) => e37.portPoints.length > 0), o3 = this.computeScoreForNodes(n3), i3 = this.computeScoreForNodes(e36), r3 = `attempt${this.sectionAttempts}`;
        if (this.stats.lastSectionScore = i3, i3 > o3) {
          const e37 = this.stats.currentBoardScore;
          this.stats.lastBoardScore = e37;
          const t4 = [...this.connectionResults], n4 = new Map(this.assignedPortPoints), o4 = new Map(Array.from(this.nodeAssignedPortPoints.entries()).map(([e38, t5]) => [e38, [...t5]]));
          this.reattachSection(this.currentSection, this.activeSubSolver.connectionsWithResults, this.activeSubSolver.assignedPortPoints, this.activeSubSolver.nodeAssignedPortPoints), this.recomputePfForNodes(this.currentSection.nodeIds);
          const i4 = this.computeBoardScore();
          this.stats.sectionScores[r3] = i4, i4 > e37 ? (this.stats.successfulOptimizations++, this.stats.currentBoardScore = i4) : (this.connectionResults = t4, this.assignedPortPoints = n4, this.nodeAssignedPortPoints = o4, this.recomputePfForNodes(this.currentSection.nodeIds), this.stats.failedOptimizations++), this.activeSubSolver = null, this.currentSection = null, this.currentSectionCenterNodeId = null, this.currentScheduleIndex = 0;
        } else if (this.currentScheduleIndex++, this.currentScheduleIndex < this.HYPERPARAMETER_SCHEDULE.length && this.currentSectionCenterNodeId) {
          const e37 = this.HYPERPARAMETER_SCHEDULE[this.currentScheduleIndex];
          this.currentSection = this.createSection({ centerOfSectionCapacityNodeId: this.currentSectionCenterNodeId, expansionDegrees: e37.EXPANSION_DEGREES }), this.activeSubSolver = this.createSectionSolver(this.currentSection);
        } else
          this.stats.failedOptimizations++, this.activeSubSolver = null, this.currentSection = null, this.currentSectionCenterNodeId = null, this.currentScheduleIndex = 0;
      }
      return;
    }
    if (this.sectionAttempts >= this.MAX_SECTION_ATTEMPTS)
      return void (this.solved = true);
    const e35 = this.findHighestPfNode();
    if (!e35)
      return void (this.solved = true);
    this.sectionAttempts++, this.stats.sectionAttempts = this.sectionAttempts, this.stats.nodesExamined++, this.attemptsToFixNode.set(e35, (this.attemptsToFixNode.get(e35) ?? 0) + 1), this.currentSectionCenterNodeId = e35, this.currentScheduleIndex = 0;
    const t2 = this.HYPERPARAMETER_SCHEDULE[this.currentScheduleIndex];
    this.currentSection = this.createSection({ centerOfSectionCapacityNodeId: e35, expansionDegrees: t2.EXPANSION_DEGREES });
    const n2 = this.getSectionNodesWithPortPoints(this.currentSection);
    this.sectionScoreBeforeOptimization = this.computeScoreForNodes(n2);
    if (this.createSectionSimpleRouteJson(this.currentSection).connections.length === 0)
      return this.currentSection = null, void (this.currentSectionCenterNodeId = null);
    this.activeSubSolver = this.createSectionSolver(this.currentSection);
  }
  computeProgress() {
    return this.sectionAttempts / this.MAX_SECTION_ATTEMPTS;
  }
  visualize() {
    return this.solved ? qz(this) : this.activeSubSolver ? this.activeSubSolver.visualize() : this.currentSection ? function(e35, t2) {
      const n2 = { lines: [], points: [], rects: [], circles: [] };
      for (const t3 of e35.inputNodes) {
        const o3 = t3.capacityMeshNodeId === e35.centerNodeId, i3 = o3 ? "rgba(0, 200, 0, 0.3)" : "rgba(200, 200, 200, 0.3)";
        n2.rects.push({ center: t3.center, width: 0.9 * t3.width, height: 0.9 * t3.height, layer: `z${t3.availableZ.join(",")}`, fill: i3, label: `${t3.capacityMeshNodeId}${o3 ? " (CENTER)" : ""}` });
      }
      for (const t3 of e35.inputNodes)
        for (const e36 of t3.portPoints) {
          const t4 = "rgba(150, 150, 150, 0.5)";
          n2.circles.push({ center: { x: e36.x, y: e36.y }, radius: 0.05, fill: t4, layer: `z${e36.z}`, label: [e36.portPointId, `cd: ${e36.distToCentermostPortOnZ}`, `connects: ${e36.connectionNodeIds.join(",")}`].filter(Boolean).join(`
`) });
        }
      for (const o3 of e35.sectionPaths) {
        const e36 = t2?.[o3.connectionName] ?? "blue";
        for (let t3 = 0;t3 < o3.points.length - 1; t3++) {
          const i3 = o3.points[t3], r3 = o3.points[t3 + 1], s2 = i3.z === r3.z, a3 = i3.z;
          let c3;
          c3 = s2 ? a3 === 0 ? "5 5" : "10 5" : "3 3 10", n2.lines.push({ points: [{ x: i3.x, y: i3.y }, { x: r3.x, y: r3.y }], strokeColor: e36, strokeDash: c3 });
        }
      }
      return n2;
    }(this.currentSection, this.colorMap) : qz(this);
  }
};
var oB = class {
  parent = {};
  constructor(e35) {
    for (const t2 of e35)
      this.parent[t2] = t2;
  }
  find(e35) {
    return this.parent[e35] === e35 ? e35 : this.parent[e35] = this.find(this.parent[e35]);
  }
  union(e35, t2) {
    const n2 = this.find(e35), o3 = this.find(t2);
    n2 !== o3 && (this.parent[o3] = n2);
  }
  getGroup(e35) {
    const t2 = this.find(e35), n2 = [];
    for (const e36 in this.parent)
      this.find(e36) === t2 && n2.push(e36);
    return n2;
  }
};
var iB = class {
  point;
  left = null;
  right = null;
  constructor(e35) {
    this.point = e35;
  }
};
var rB = class {
  root = null;
  constructor(e35) {
    e35.length > 0 && (this.root = this.buildTree(e35, 0));
  }
  buildTree(e35, t2) {
    const n2 = t2 % 2 == 0 ? "x" : "y";
    e35.sort((e36, t3) => e36[n2] - t3[n2]);
    const o3 = Math.floor(e35.length / 2), i3 = new iB(e35[o3]);
    return o3 > 0 && (i3.left = this.buildTree(e35.slice(0, o3), t2 + 1)), o3 < e35.length - 1 && (i3.right = this.buildTree(e35.slice(o3 + 1), t2 + 1)), i3;
  }
  findNearestNeighbor(e35) {
    if (!this.root)
      throw new Error("Tree is empty");
    const t2 = this.root.point, n2 = this.distance(e35, t2);
    return this.nearestNeighborSearch(this.root, e35, 0, t2, n2), t2;
  }
  nearestNeighborSearch(e35, t2, n2, o3, i3) {
    if (!e35)
      return o3;
    const r3 = n2 % 2 ? "x" : "y", s2 = this.distance(t2, e35.point);
    s2 < i3 && (o3 = e35.point, i3 = s2);
    const a3 = t2[r3] - e35.point[r3], c3 = a3 <= 0 ? e35.left : e35.right, l3 = a3 <= 0 ? e35.right : e35.left;
    return o3 = this.nearestNeighborSearch(c3, t2, n2 + 1, o3, i3), i3 = this.distance(t2, o3), Math.abs(a3) < i3 && (o3 = this.nearestNeighborSearch(l3, t2, n2 + 1, o3, i3)), o3;
  }
  findKNearestNeighbors(e35, t2) {
    if (!this.root)
      return [];
    const n2 = [];
    return this.kNearestNeighborSearch(this.root, e35, 0, n2, t2), n2.sort((e36, t3) => e36.distance - t3.distance).slice(0, t2).map((e36) => e36.point);
  }
  kNearestNeighborSearch(e35, t2, n2, o3, i3) {
    if (!e35)
      return;
    const r3 = n2 % 2 ? "x" : "y", s2 = this.distance(t2, e35.point);
    o3.push({ point: e35.point, distance: s2 });
    const a3 = t2[r3] - e35.point[r3], c3 = a3 <= 0 ? e35.left : e35.right, l3 = a3 <= 0 ? e35.right : e35.left;
    this.kNearestNeighborSearch(c3, t2, n2 + 1, o3, i3);
    let h2 = 1 / 0;
    o3.length >= i3 && (o3.sort((e36, t3) => e36.distance - t3.distance), h2 = o3[i3 - 1]?.distance || 1 / 0), (Math.abs(a3) < h2 || o3.length < i3) && this.kNearestNeighborSearch(l3, t2, n2 + 1, o3, i3);
  }
  distance(e35, t2) {
    return Math.sqrt((e35.x - t2.x) ** 2 + (e35.y - t2.y) ** 2);
  }
};
var sB = class {
  parent = new Map;
  rank = new Map;
  componentCount;
  constructor(e35) {
    for (const t2 of e35) {
      const e36 = this.pointToKey(t2);
      this.parent.set(e36, e36), this.rank.set(e36, 0);
    }
    this.componentCount = this.parent.size;
  }
  pointToKey(e35) {
    return `${e35.x},${e35.y}`;
  }
  find(e35) {
    const t2 = this.pointToKey(e35);
    if (!this.parent.has(t2))
      throw new Error(`Point ${t2} not found in DisjointSet`);
    let n2 = t2;
    for (;n2 !== this.parent.get(n2); )
      n2 = this.parent.get(n2);
    let o3 = t2;
    for (;o3 !== n2; ) {
      const e36 = this.parent.get(o3);
      this.parent.set(o3, n2), o3 = e36;
    }
    return n2;
  }
  union(e35, t2) {
    const n2 = this.find(e35), o3 = this.find(t2);
    if (n2 === o3)
      return false;
    const i3 = this.rank.get(n2) || 0, r3 = this.rank.get(o3) || 0;
    return i3 < r3 ? this.parent.set(n2, o3) : i3 > r3 ? this.parent.set(o3, n2) : (this.parent.set(o3, n2), this.rank.set(n2, i3 + 1)), this.componentCount -= 1, true;
  }
};
function aB(e35, t2 = {}) {
  if (e35.length <= 1)
    return [];
  const n2 = [...e35], o3 = new rB(n2);
  let i3 = Math.min(10, e35.length - 1);
  for (;; ) {
    const r3 = [];
    for (const e36 of n2) {
      const t3 = o3.findKNearestNeighbors(e36, i3 + 1);
      for (const n3 of t3) {
        if (e36.x === n3.x && e36.y === n3.y)
          continue;
        const t4 = Math.sqrt((e36.x - n3.x) ** 2 + (e36.y - n3.y) ** 2);
        r3.push({ from: e36, to: n3, weight: t4 });
      }
    }
    t2.extraEdges && r3.push(...t2.extraEdges), r3.sort((e36, t3) => e36.weight - t3.weight);
    const s2 = new sB(n2), a3 = [];
    for (const e36 of r3)
      if (s2.union(e36.from, e36.to) && (a3.push(e36), a3.length === n2.length - 1))
        break;
    if (s2.componentCount === 1)
      return a3;
    i3 = Math.min(2 * i3, e35.length - 1);
  }
}
var cB = (e35, t2) => {
  const n2 = new Map;
  for (const o4 of e35.pointsToConnect) {
    if (!o4.pointId)
      continue;
    const e36 = t2.getNetConnectedToId(o4.pointId);
    if (!e36)
      continue;
    const i3 = n2.get(e36) ?? [];
    i3.push(o4), n2.set(e36, i3);
  }
  const o3 = [];
  for (const e36 of n2.values()) {
    const t3 = e36[0];
    if (t3)
      for (const n3 of e36.slice(1))
        o3.push({ from: t3, to: n3, weight: 0 });
  }
  return o3;
};
var lB = (e35, t2) => ({ zeroWeightEdges: cB(e35, t2), arePointsConnected: (e36, n2) => Boolean(e36.pointId && n2.pointId && ((e37, t3, n3) => {
  const o3 = e37.getNetConnectedToId(t3);
  return !!o3 && o3 === e37.getNetConnectedToId(n3);
})(t2, e36.pointId, n2.pointId)) });
function hB(e35) {
  if (e35.pointId)
    return e35.pointId;
  const t2 = [...So(e35)].sort().join("-");
  return `${e35.x.toFixed(4)},${e35.y.toFixed(4)},${t2}`;
}
function dB(e35) {
  if (e35.length === 0)
    return [];
  const t2 = e35.map((e36, t3) => `conn_${t3}`), n2 = new oB(t2), o3 = new Map;
  e35.forEach((e36, t3) => {
    const n3 = `conn_${t3}`;
    e36.pointsToConnect.forEach((e37) => {
      const t4 = hB(e37);
      o3.has(t4) || o3.set(t4, []), o3.get(t4).push(n3);
    });
  });
  for (const e36 of o3.values())
    if (e36.length > 1) {
      const t3 = e36[0];
      for (let o4 = 1;o4 < e36.length; o4++)
        n2.union(t3, e36[o4]);
    }
  const i3 = new Map;
  e35.forEach((e36, t3) => {
    const o4 = `conn_${t3}`, r4 = n2.find(o4);
    i3.has(r4) || i3.set(r4, []), i3.get(r4).push(e36);
  });
  const r3 = [];
  for (const e36 of i3.values()) {
    if (e36.length === 1) {
      r3.push(e36[0]);
      continue;
    }
    const t3 = new Map, n3 = new Set;
    let o4 = false;
    const i4 = [], s2 = new Set;
    let a3;
    e36.forEach((e37) => {
      e37.pointsToConnect.forEach((e38) => t3.set(hB(e38), e38));
      const r4 = e37.__rootConnectionNames;
      if (r4 && r4.length > 0)
        for (const e38 of r4)
          n3.add(e38);
      else
        n3.add(e37.name);
      e37.isOffBoard && (o4 = true), e37.externallyConnectedPointIds && i4.push(...e37.externallyConnectedPointIds), e37.__netConnectionName && s2.add(e37.__netConnectionName), a3 === undefined && e37.nominalTraceWidth !== undefined && (a3 = e37.nominalTraceWidth);
    });
    const c3 = { name: e36.map((e37) => e37.name).join("__"), pointsToConnect: Array.from(t3.values()), isOffBoard: o4, externallyConnectedPointIds: i4.length > 0 ? i4 : undefined, __netConnectionName: s2.size > 0 ? Array.from(s2).join("__") : undefined, __rootConnectionNames: Array.from(n3), nominalTraceWidth: a3 };
    r3.push(c3);
  }
  return r3;
}
var uB = class extends ni {
  constructor(e35, t2 = {}, n2) {
    super(), this.ogSrj = e35, this.colorMap = t2;
    const o3 = new Map;
    for (const t3 of e35.buses ?? [])
      if (t3.traceWidth !== undefined)
        for (const e36 of t3.connectionNames)
          o3.set(e36, Math.max(o3.get(e36) ?? 0, t3.traceWidth));
    const i3 = e35.connections.map((e36) => {
      const t3 = o3.get(e36.name);
      return t3 === undefined ? e36 : { ...e36, nominalTraceWidth: Math.max(e36.nominalTraceWidth ?? 0, t3) };
    });
    this.unprocessedConnections = dB(i3), this.newConnections = [], this.initiallyConnectedMap = n2;
  }
  getSolverName() {
    return "NetToPointPairsSolver";
  }
  unprocessedConnections;
  newConnections;
  initiallyConnectedMap;
  _step() {
    if (this.unprocessedConnections.length === 0)
      return void (this.solved = true);
    const e35 = this.unprocessedConnections.pop(), { zeroWeightEdges: t2, arePointsConnected: n2 } = lB(e35, this.initiallyConnectedMap);
    if (e35.pointsToConnect.length === 2) {
      const [t3, o4] = e35.pointsToConnect;
      if (t3 && o4 && n2(t3, o4))
        return;
      return void this.newConnections.push({ ...e35, __rootConnectionNames: e35.__rootConnectionNames ?? [e35.name] });
    }
    const o3 = aB(e35.pointsToConnect, { extraEdges: t2 });
    let i3 = 0;
    for (const t3 of o3)
      n2(t3.from, t3.to) || this.newConnections.push({ ...e35, pointsToConnect: [t3.from, t3.to], name: `${e35.name}_mst${i3++}`, __rootConnectionNames: e35.__rootConnectionNames ?? [e35.name], __netConnectionName: e35.__netConnectionName });
  }
  getNewSimpleRouteJson() {
    return { ...structuredClone(this.ogSrj), connections: structuredClone(this.newConnections) };
  }
  visualize() {
    const e35 = { lines: [], points: [], rects: [], circles: [], coordinateSystem: "cartesian", title: "Net To Point Pairs Visualization" };
    return this.unprocessedConnections.forEach((t2) => {
      t2.pointsToConnect.forEach((t3) => {
        e35.points.push({ x: t3.x, y: t3.y, color: "red", label: t3.pcb_port_id ?? t3.pointId });
      });
      const n2 = t2.pointsToConnect.length ** 2, o3 = vr(0), i3 = new Set;
      for (let r3 = 0;r3 < Math.max(n2, 2 * t2.pointsToConnect.length); r3++) {
        const n3 = Math.floor(o3() * t2.pointsToConnect.length), r4 = Math.floor(o3() * t2.pointsToConnect.length);
        i3.has(`${n3}-${r4}`) || (i3.add(`${n3}-${r4}`), e35.lines.push({ points: [t2.pointsToConnect[n3], t2.pointsToConnect[r4]], strokeColor: "rgba(255,0,0,0.25)", label: t2.name }));
      }
    }), this.newConnections.forEach((t2) => {
      const n2 = this.colorMap?.[t2.name] || "blue";
      t2.pointsToConnect.forEach((t3) => {
        e35.points.push({ x: t3.x, y: t3.y, color: n2, label: t3.pcb_port_id ?? t3.pointId });
      });
      for (let o3 = 0;o3 < t2.pointsToConnect.length - 1; o3++)
        for (let i3 = o3 + 1;i3 < t2.pointsToConnect.length; i3++)
          e35.lines.push({ points: [t2.pointsToConnect[o3], t2.pointsToConnect[i3]], strokeColor: n2, label: t2.name });
    }), e35;
  }
};
var pB = class extends uB {
  constructor(e35, t2 = {}, n2) {
    const o3 = e35.connections.flatMap((e36) => e36.pointsToConnect), i3 = new Map;
    for (const e36 of o3)
      e36.pointId && i3.set(e36.pointId, e36);
    const r3 = o3.map((e36) => e36.pointId).filter((e36) => !!e36), s2 = new oB(r3), a3 = [];
    for (const t3 of e35.connections)
      t3.isOffBoard ? t3.pointsToConnect.length >= 2 && t3.pointsToConnect[0].pointId && t3.pointsToConnect[1].pointId && s2.union(t3.pointsToConnect[0].pointId, t3.pointsToConnect[1].pointId) : a3.push(t3);
    super({ ...e35, connections: a3 }, t2, n2), this.ogSrj = e35, this.colorMap = t2, this.connectionPointDsu = s2, this.connectionPointMap = i3, this.ogSrj = e35;
  }
  getSolverName() {
    return "NetToPointPairsSolver2_OffBoardConnection";
  }
  connectionPointDsu;
  connectionPointMap;
  _findBestConnectionPointsFromDisjointSets(e35, t2) {
    if (!e35.pointId || !t2.pointId)
      return { pointsToConnect: [e35, t2] };
    const n2 = this.connectionPointDsu.getGroup(e35.pointId).map((e36) => this.connectionPointMap.get(e36)), o3 = this.connectionPointDsu.getGroup(t2.pointId).map((e36) => this.connectionPointMap.get(e36));
    let i3 = e35, r3 = t2, s2 = 1 / 0;
    for (const e36 of n2)
      for (const t3 of o3) {
        const n3 = Math.sqrt(Math.pow(e36.x - t3.x, 2) + Math.pow(e36.y - t3.y, 2));
        n3 < s2 && (s2 = n3, i3 = e36, r3 = t3);
      }
    return { pointsToConnect: [i3, r3] };
  }
  _step() {
    if (this.unprocessedConnections.length === 0)
      return void (this.solved = true);
    const e35 = this.unprocessedConnections.pop(), { zeroWeightEdges: t2, arePointsConnected: n2 } = lB(e35, this.initiallyConnectedMap);
    if (e35.pointsToConnect.length === 2) {
      const [t3, o4] = e35.pointsToConnect;
      if (t3 && o4 && n2(t3, o4))
        return;
      const i4 = this._findBestConnectionPointsFromDisjointSets(e35.pointsToConnect[0], e35.pointsToConnect[1]);
      return void this.newConnections.push({ ...e35, pointsToConnect: i4.pointsToConnect, __rootConnectionNames: e35.__rootConnectionNames ?? [e35.name] });
    }
    const o3 = aB(e35.pointsToConnect, { extraEdges: t2 });
    let i3 = 0;
    for (const t3 of o3) {
      if (n2(t3.from, t3.to))
        continue;
      const o4 = this._findBestConnectionPointsFromDisjointSets(t3.from, t3.to);
      this.newConnections.push({ ...e35, pointsToConnect: o4.pointsToConnect, name: `${e35.name}_mst${i3++}`, __rootConnectionNames: e35.__rootConnectionNames ?? [e35.name], __netConnectionName: e35.__netConnectionName });
    }
  }
};
var mB = class {
  netMap;
  idToNetMap;
  constructor(e35) {
    this.netMap = e35, this.idToNetMap = {};
    for (const [t2, n2] of Object.entries(e35))
      for (const e36 of n2)
        this.idToNetMap[e36] = t2;
  }
  addConnections(e35) {
    for (const t2 of e35) {
      const e36 = new Set;
      for (const n3 of t2) {
        const t3 = this.idToNetMap[n3];
        t3 && e36.add(t3);
      }
      let n2;
      if (e36.size === 0)
        n2 = `connectivity_net${Object.keys(this.netMap).length}`, this.netMap[n2] = [];
      else if (e36.size === 1)
        n2 = e36.values().next().value ?? `connectivity_net${Object.keys(this.netMap).length}`;
      else {
        n2 = e36.values().next().value ?? `connectivity_net${Object.keys(this.netMap).length}`;
        for (const t3 of e36)
          if (t3 !== n2) {
            const e37 = this.netMap[n2], o3 = this.netMap[t3];
            if (e37 && o3) {
              e37.push(...o3), this.netMap[t3] = e37;
              for (const t4 of e37)
                this.idToNetMap[t4] = n2;
            }
          }
      }
      for (const e37 of t2) {
        const t3 = this.netMap[n2];
        t3 && !t3.includes(e37) && t3.push(e37), this.idToNetMap[e37] = n2;
      }
    }
  }
  getIdsConnectedToNet(e35) {
    return this.netMap[e35] || [];
  }
  getNetConnectedToId(e35) {
    return this.idToNetMap[e35];
  }
  areIdsConnected(e35, t2) {
    if (e35 === t2)
      return true;
    const n2 = this.getNetConnectedToId(e35);
    if (!n2)
      return false;
    const o3 = this.getNetConnectedToId(t2);
    return !!o3 && (n2 === o3 || o3 === e35 || o3 === e35);
  }
  areAllIdsConnected(e35) {
    if (e35.length === 0)
      return true;
    const t2 = this.getNetConnectedToId(e35[0]);
    if (!t2)
      return false;
    for (const n2 of e35) {
      const e36 = this.getNetConnectedToId(n2);
      if (e36 === undefined)
        return false;
      if (e36 !== t2)
        return false;
    }
    return true;
  }
};
function gB(e35, t2 = {}) {
  const n2 = [], o3 = [], i3 = t2.color ?? "gray", r3 = t2.label, s2 = Xo[e35.footprint] ?? Xo["0603"], a3 = e35.end.x - e35.start.x, c3 = e35.end.y - e35.start.y, l3 = Math.abs(a3) > Math.abs(c3), h2 = l3 ? s2.padLength : s2.padWidth, d2 = l3 ? s2.padWidth : s2.padLength;
  return n2.push({ center: e35.start, width: h2, height: d2, fill: Ao(i3, 0.5), stroke: "rgba(0, 0, 0, 0.5)", layer: "jumper", label: r3 ? `${r3} (start)` : undefined }), n2.push({ center: e35.end, width: h2, height: d2, fill: Ao(i3, 0.5), stroke: "rgba(0, 0, 0, 0.5)", layer: "jumper", label: r3 ? `${r3} (end)` : undefined }), o3.push({ points: [e35.start, e35.end], strokeColor: "rgba(100, 100, 100, 0.8)", strokeWidth: 0.3 * s2.padWidth, layer: "jumper-body" }), { rects: n2, lines: o3 };
}
function fB(e35, t2 = {}) {
  const n2 = { rects: [], lines: [] };
  for (const o3 of e35) {
    const { rects: e36, lines: i3 } = gB(o3, t2);
    n2.rects.push(...e36), n2.lines.push(...i3);
  }
  return n2;
}
var _B = 1e5;
var yB = 0.001;
var bB = class extends ni {
  getSolverName() {
    return "SingleHighDensityRouteStitchSolver";
  }
  mergedHdRoute;
  remainingHdRoutes;
  start;
  end;
  colorMap;
  constructor(e35) {
    if (super(), this.remainingHdRoutes = [...e35.hdRoutes], this.colorMap = e35.colorMap ?? {}, e35.hdRoutes.length === 0) {
      this.start = e35.start, this.end = e35.end;
      const t3 = [{ x: e35.start.x, y: e35.start.y, z: e35.start.z }], n3 = [];
      return e35.start.z !== e35.end.z && (t3.push({ x: e35.start.x, y: e35.start.y, z: e35.end.z }), n3.push({ x: e35.start.x, y: e35.start.y })), t3.push({ x: e35.end.x, y: e35.end.y, z: e35.end.z }), this.mergedHdRoute = { connectionName: e35.connectionName, rootConnectionName: e35.hdRoutes[0]?.rootConnectionName, route: t3, vias: n3, jumpers: [], viaDiameter: e35.defaultViaDiameter ?? 0.3, traceThickness: e35.defaultTraceThickness ?? 0.15 }, void (this.solved = true);
    }
    let t2 = 1 / 0, n2 = e35.hdRoutes[0], o3 = "start-to-end";
    for (const i4 of e35.hdRoutes) {
      const r4 = i4.route[0], s3 = i4.route[i4.route.length - 1], a3 = me(e35.start, r4), c3 = me(e35.start, s3), l3 = me(e35.end, r4), h2 = me(e35.end, s3), d2 = Math.min(a3, c3, l3, h2);
      d2 < t2 && (t2 = d2, n2 = i4, o3 = Math.min(l3, h2) < Math.min(a3, c3) ? "end-to-start" : "start-to-end");
    }
    o3 === "start-to-end" ? (this.start = e35.start, this.end = e35.end) : (this.start = e35.end, this.end = e35.start);
    const i3 = n2.route[0], r3 = n2.route[n2.route.length - 1], s2 = me(this.start, i3) <= me(this.start, r3) ? i3 : r3;
    this.mergedHdRoute = { connectionName: e35.connectionName, rootConnectionName: n2.rootConnectionName, route: [{ x: this.start.x, y: this.start.y, z: s2.z }], vias: [], jumpers: [], viaDiameter: n2.viaDiameter, traceThickness: n2.traceThickness };
  }
  getDisjointedRoute() {
    for (const e35 of this.remainingHdRoutes) {
      if ([e35.route[0], e35.route[e35.route.length - 1]].some((t2) => !this.remainingHdRoutes.some((n2) => {
        if (n2 === e35)
          return false;
        return [n2.route[0], n2.route[n2.route.length - 1]].some((e36) => e36.z === t2.z && me(t2, e36) < 0.001);
      })))
        return { firstRoute: e35 };
    }
    return { firstRoute: this.remainingHdRoutes[0] };
  }
  _step() {
    if (this.remainingHdRoutes.length === 0) {
      const e36 = this.mergedHdRoute.route[this.mergedHdRoute.route.length - 1];
      return this.mergedHdRoute.route.push({ x: this.end.x, y: this.end.y, z: e36.z }), void (this.solved = true);
    }
    const e35 = this.mergedHdRoute.route[this.mergedHdRoute.route.length - 1];
    let t2 = -1, n2 = "first", o3 = 1 / 0;
    for (let i4 = 0;i4 < this.remainingHdRoutes.length; i4++) {
      const r4 = this.remainingHdRoutes[i4], s2 = r4.route[0], a3 = r4.route[r4.route.length - 1], c3 = me(e35, s2), l3 = me(e35, a3);
      let h2 = 1 / 0;
      h2 = e35.z === s2.z ? c3 < yB ? c3 : _B + c3 : c3 < yB ? 1000 + c3 : _B + c3, h2 < o3 && (o3 = h2, t2 = i4, n2 = "first");
      let d2 = 1 / 0;
      d2 = e35.z === a3.z ? l3 < yB ? l3 : _B + l3 : l3 < yB ? 1000 + l3 : _B + l3, d2 < o3 && (o3 = d2, t2 = i4, n2 = "last");
    }
    if (t2 === -1)
      return void (this.remainingHdRoutes = []);
    const i3 = this.remainingHdRoutes[t2];
    let r3;
    this.remainingHdRoutes.splice(t2, 1), r3 = n2 === "first" ? i3.route : [...i3.route].reverse(), me(e35, r3[0]) < yB && e35.z === r3[0].z ? this.mergedHdRoute.route.push(...r3.slice(1)) : this.mergedHdRoute.route.push(...r3), this.mergedHdRoute.vias.push(...i3.vias), i3.jumpers && this.mergedHdRoute.jumpers.push(...i3.jumpers);
  }
  visualize() {
    const e35 = { points: [], lines: [], circles: [], rects: [], title: "Single High Density Route Stitch Solver" };
    if (e35.points?.push({ x: this.start.x, y: this.start.y, color: "green", label: "Start" }, { x: this.end.x, y: this.end.y, color: "red", label: "End" }), this.mergedHdRoute && this.mergedHdRoute.route.length > 1) {
      e35.lines?.push({ points: this.mergedHdRoute.route.map((e36) => ({ x: e36.x, y: e36.y })), strokeColor: "green" });
      for (const t2 of this.mergedHdRoute.route)
        e35.points?.push({ x: t2.x, y: t2.y, color: "green" });
      for (const t2 of this.mergedHdRoute.vias)
        e35.circles?.push({ center: { x: t2.x, y: t2.y }, radius: this.mergedHdRoute.viaDiameter / 2, fill: "green" });
      if (this.mergedHdRoute.jumpers && this.mergedHdRoute.jumpers.length > 0) {
        const t2 = fB(this.mergedHdRoute.jumpers, { color: "green", label: this.mergedHdRoute.connectionName });
        e35.rects.push(...t2.rects ?? []), e35.lines.push(...t2.lines ?? []);
      }
    }
    for (const [t2, n2] of this.remainingHdRoutes.entries()) {
      const o3 = this.colorMap[n2.connectionName] ?? "gray";
      e35.lines?.push({ points: n2.route.map((e36) => ({ x: e36.x, y: e36.y })), strokeColor: o3 });
      for (let i3 = 0;i3 < n2.route.length; i3++) {
        const r3 = n2.route[i3];
        e35.points?.push({ x: r3.x + (t2 % 2 - 0.5) / 500 + (i3 % 8 - 4) / 1000, y: r3.y + (t2 % 2 - 0.5) / 500 + (i3 % 8 - 4) / 1000, color: o3, label: `Route ${n2.connectionName} ${r3 === n2.route[0] ? "First" : r3 === n2.route[n2.route.length - 1] ? "Last" : ""}` });
      }
      for (const t3 of n2.vias)
        e35.circles?.push({ center: { x: t3.x, y: t3.y }, radius: n2.viaDiameter / 2, fill: o3 });
      if (n2.jumpers && n2.jumpers.length > 0) {
        const t3 = fB(n2.jumpers, { color: o3, label: n2.connectionName });
        e35.rects.push(...t3.rects ?? []), e35.lines.push(...t3.lines ?? []);
      }
    }
    return e35;
  }
};
var xB = (e35) => `${Math.round(100 * e35.x)},${Math.round(100 * e35.y)},${Math.round(100 * e35.z)}`;
var vB = (e35) => ({ startHash: xB(e35.route[0]), endHash: xB(e35.route[e35.route.length - 1]) });
var IB = class extends ni {
  getSolverName() {
    return "MultipleHighDensityRouteStitchSolver";
  }
  unsolvedRoutes;
  activeSolver = null;
  mergedHdRoutes = [];
  colorMap = {};
  defaultTraceThickness;
  defaultViaDiameter;
  getClosestEndpointHash(e35, t2) {
    let n2 = null, o3 = 1 / 0;
    for (const i3 of e35) {
      const e36 = [i3.route[0], i3.route[i3.route.length - 1]];
      for (const i4 of e36) {
        const e37 = me(t2, i4);
        e37 < o3 && (o3 = e37, n2 = xB(i4));
      }
    }
    return n2;
  }
  selectRoutesAlongEndpointPath(e35, t2, n2) {
    if (e35.length <= 2)
      return e35;
    const o3 = this.getClosestEndpointHash(e35, t2), i3 = this.getClosestEndpointHash(e35, n2);
    if (!o3 || !i3 || o3 === i3)
      return e35;
    const r3 = new Map;
    for (let t3 = 0;t3 < e35.length; t3++) {
      const { startHash: n3, endHash: o4 } = vB(e35[t3]), i4 = r3.get(n3) ?? [];
      i4.push({ nextHash: o4, routeIndex: t3 }), r3.set(n3, i4);
      const s3 = r3.get(o4) ?? [];
      s3.push({ nextHash: n3, routeIndex: t3 }), r3.set(o4, s3);
    }
    const s2 = [o3], a3 = new Set([o3]), c3 = new Map;
    for (;s2.length > 0; ) {
      const e36 = s2.shift();
      if (e36 === i3)
        break;
      for (const t3 of r3.get(e36) ?? [])
        a3.has(t3.nextHash) || (a3.add(t3.nextHash), c3.set(t3.nextHash, { prevHash: e36, routeIndex: t3.routeIndex }), s2.push(t3.nextHash));
    }
    if (!a3.has(i3))
      return e35;
    const l3 = new Set;
    let h2 = i3;
    for (;h2 !== o3; ) {
      const t3 = c3.get(h2);
      if (!t3)
        return e35;
      l3.add(t3.routeIndex), h2 = t3.prevHash;
    }
    if (l3.size === 0)
      return e35;
    return e35.filter((e36, t3) => l3.has(t3));
  }
  constructor(e35) {
    super(), this.colorMap = e35.colorMap ?? {};
    const t2 = e35.hdRoutes[0];
    this.defaultTraceThickness = t2?.traceThickness ?? 0.15, this.defaultViaDiameter = t2?.viaDiameter ?? e35.defaultViaDiameter ?? 0.3;
    const n2 = new mB({}), o3 = [], i3 = new Map;
    for (let t3 = 0;t3 < e35.hdRoutes.length; t3++) {
      const n3 = e35.hdRoutes[t3], i4 = n3.route[0], r4 = n3.route[n3.route.length - 1];
      o3.push([`route_island_${t3}`, `${n3.connectionName}:${xB(i4)}`, `${n3.connectionName}:${xB(r4)}`]);
    }
    n2.addConnections(o3);
    for (const e36 of o3)
      for (const t3 of e36.slice(1))
        i3.set(t3, (i3.get(t3) ?? 0) + 1);
    this.unsolvedRoutes = [];
    const r3 = Array.from(new Set(Object.values(n2.idToNetMap)));
    for (const t3 of r3) {
      const o4 = n2.getIdsConnectedToNet(t3), r4 = e35.hdRoutes.filter((e36, t4) => o4.includes(`route_island_${t4}`));
      if (r4.length === 0)
        continue;
      const s3 = e35.connections.find((e36) => e36.name === r4[0].connectionName), a3 = r4.flatMap((e36) => [e36.route[0], e36.route[e36.route.length - 1]]), c3 = [];
      for (const e36 of a3) {
        const t4 = `${r4[0].connectionName}:${xB(e36)}`;
        i3.get(t4) === 1 && c3.push(e36);
      }
      if (c3.length === 0) {
        console.log("no possible endpoints, can't stitch");
        continue;
      }
      let l3, h2;
      c3.length !== 2 ? (l3 = { ...s3.pointsToConnect[0], z: mo(Io(s3.pointsToConnect[0]), e35.layerCount) }, h2 = { ...s3.pointsToConnect[1], z: mo(Io(s3.pointsToConnect[1]), e35.layerCount) }) : (l3 = c3[0], h2 = c3[1], me(l3, s3.pointsToConnect[1]) < me(h2, s3.pointsToConnect[0]) && ([l3, h2] = [h2, l3]));
      const d2 = this.selectRoutesAlongEndpointPath(r4, l3, h2);
      this.unsolvedRoutes.push({ connectionName: r4[0].connectionName, hdRoutes: d2, start: l3, end: h2 });
    }
    const s2 = new Map;
    for (const e36 of this.unsolvedRoutes) {
      const t3 = s2.get(e36.connectionName);
      t3 ? t3.push(e36) : s2.set(e36.connectionName, [e36]);
    }
    this.unsolvedRoutes = Array.from(s2.entries()).flatMap(([t3, n3]) => {
      if (!n3.some((e36) => e36.hdRoutes.some((e37) => e37.route.length < 2)))
        return n3;
      const o4 = e35.connections.find((e36) => e36.name === t3);
      if (!o4)
        return n3;
      const i4 = { ...o4.pointsToConnect[0], z: mo(Io(o4.pointsToConnect[0]), e35.layerCount) }, r4 = { ...o4.pointsToConnect[1], z: mo(Io(o4.pointsToConnect[1]), e35.layerCount) }, s3 = n3.flatMap((e36) => e36.hdRoutes);
      return [{ connectionName: t3, hdRoutes: this.selectRoutesAlongEndpointPath(s3, i4, r4), start: i4, end: r4 }];
    }), this.MAX_ITERATIONS = 1e5;
  }
  _step() {
    if (this.activeSolver)
      return this.activeSolver.step(), void (this.activeSolver.solved ? (this.activeSolver instanceof bB && this.mergedHdRoutes.push(this.activeSolver.mergedHdRoute), this.activeSolver = null) : this.activeSolver.failed && (this.failed = true, this.error = this.activeSolver.error));
    const e35 = this.unsolvedRoutes.pop();
    e35 ? this.activeSolver = new bB({ connectionName: e35.connectionName, hdRoutes: e35.hdRoutes, start: e35.start, end: e35.end, colorMap: this.colorMap, defaultTraceThickness: this.defaultTraceThickness, defaultViaDiameter: this.defaultViaDiameter }) : this.solved = true;
  }
  visualize() {
    const e35 = { points: [], lines: [], circles: [], rects: [], title: "Multiple High Density Route Stitch Solver" };
    if (this.activeSolver) {
      const t2 = this.activeSolver.visualize();
      t2.points?.length && e35.points?.push(...t2.points), t2.lines?.length && e35.lines?.push(...t2.lines), t2.circles?.length && e35.circles?.push(...t2.circles), t2.rects?.length && (e35.rects || (e35.rects = []), e35.rects.push(...t2.rects));
    }
    for (const [t2, n2] of this.mergedHdRoutes.entries()) {
      const o3 = this.colorMap[n2.connectionName] ?? `hsl(120, 100%, ${40 + 10 * t2 % 40}%)`;
      for (let t3 = 0;t3 < n2.route.length - 1; t3++) {
        const i3 = n2.route[t3], r3 = n2.route[t3 + 1], s2 = i3.z !== 0 ? Ao(o3, 0.5) : o3;
        e35.lines?.push({ points: [{ x: i3.x, y: i3.y }, { x: r3.x, y: r3.y }], strokeColor: s2, strokeWidth: n2.traceThickness });
      }
      for (const t3 of n2.route) {
        const n3 = t3.z !== 0 ? Ao(o3, 0.5) : o3;
        e35.points?.push({ x: t3.x, y: t3.y, color: n3 });
      }
      for (const t3 of n2.vias)
        e35.circles?.push({ center: { x: t3.x, y: t3.y }, radius: n2.viaDiameter / 2, fill: o3 });
      if (n2.jumpers && n2.jumpers.length > 0) {
        const t3 = fB(n2.jumpers, { color: o3, label: n2.connectionName });
        e35.rects.push(...t3.rects ?? []), e35.lines.push(...t3.lines ?? []);
      }
    }
    for (const t2 of this.unsolvedRoutes) {
      const n2 = this.colorMap[t2.connectionName] ?? "gray";
      e35.points?.push({ x: t2.start.x, y: t2.start.y, color: n2, label: `${t2.connectionName} Start (z=${t2.start.z})` }, { x: t2.end.x, y: t2.end.y, color: n2, label: `${t2.connectionName} End (z=${t2.end.z})` }), e35.lines?.push({ points: [{ x: t2.start.x, y: t2.start.y }, { x: t2.end.x, y: t2.end.y }], strokeColor: n2, strokeDash: "2 2" });
      for (const o3 of t2.hdRoutes) {
        o3.route.length > 1 && e35.lines?.push({ points: o3.route.map((e36) => ({ x: e36.x, y: e36.y })), strokeColor: Ao(n2, 0.5), strokeDash: "10 5" });
        for (const t3 of o3.vias)
          e35.circles?.push({ center: { x: t3.x, y: t3.y }, radius: o3.viaDiameter / 2, fill: n2 });
        if (o3.jumpers && o3.jumpers.length > 0) {
          const t3 = fB(o3.jumpers, { color: n2, label: o3.connectionName });
          e35.rects.push(...t3.rects ?? []), e35.lines.push(...t3.lines ?? []);
        }
      }
    }
    return e35;
  }
};
var SB = class {
  MAX_ITERATIONS = 1000;
  solved = false;
  failed = false;
  iterations = 0;
  progress = 0;
  error = null;
  activeSubSolver;
  failedSubSolvers;
  timeToSolve;
  stats = {};
  pendingEffects;
  cacheHit;
  cacheKey;
  cacheToSolveSpaceTransform;
  getSolverName() {
    return this.constructor.name;
  }
  step() {
    if (!this.solved && !this.failed) {
      this.iterations++;
      try {
        this._step();
      } catch (e35) {
        throw this.error = `${this.getSolverName()} error: ${e35}`, console.error(this.error), this.failed = true, e35;
      }
      !this.solved && this.iterations > this.MAX_ITERATIONS && this.tryFinalAcceptance(), !this.solved && this.iterations > this.MAX_ITERATIONS && (this.error = `${this.getSolverName()} ran out of iterations (MAX_ITERATIONS=${this.MAX_ITERATIONS})`, this.failed = true), "computeProgress" in this && (this.progress = this.computeProgress());
    }
  }
  _step() {}
  getConstructorParams() {
    throw new Error("getConstructorParams not implemented");
  }
  solve() {
    const e35 = Date.now();
    for (;!this.solved && !this.failed; )
      this.step();
    const t2 = Date.now();
    this.timeToSolve = t2 - e35;
  }
  visualize() {
    return { lines: [], points: [], rects: [], circles: [] };
  }
  tryFinalAcceptance() {}
  preview() {
    return { lines: [], points: [], rects: [], circles: [] };
  }
};
var CB = class {
  tree;
  constructor(e35 = 9) {
    this.tree = new G(e35);
  }
  insert(e35, t2, n2, o3, i3) {
    this.tree.insert({ minX: t2, minY: n2, maxX: o3, maxY: i3, data: e35 });
  }
  bulkLoad(e35) {
    const t2 = e35.map(({ item: e36, minX: t3, minY: n2, maxX: o3, maxY: i3 }) => ({ minX: t3, minY: n2, maxX: o3, maxY: i3, data: e36 }));
    this.tree.load(t2);
  }
  search(e35, t2, n2, o3) {
    return this.tree.search({ minX: e35, minY: t2, maxX: n2, maxY: o3 }).map((e36) => e36.data);
  }
  clear() {
    this.tree.clear();
  }
};
var PB = [Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array];
var MB = class e35 {
  static from(t2, n2 = 0) {
    if (n2 % 8 != 0)
      throw new Error("byteOffset must be 8-byte aligned.");
    if (!t2 || t2.byteLength === undefined || "buffer" in t2)
      throw new Error("Data must be an instance of ArrayBuffer or SharedArrayBuffer.");
    const [o3, i3] = new Uint8Array(t2, n2 + 0, 2);
    if (o3 !== 251)
      throw new Error("Data does not appear to be in a Flatbush format.");
    const r3 = i3 >> 4;
    if (r3 !== 3)
      throw new Error(`Got v${r3} data when expected v3.`);
    const s2 = PB[15 & i3];
    if (!s2)
      throw new Error("Unrecognized array type.");
    const [a3] = new Uint16Array(t2, n2 + 2, 1), [c3] = new Uint32Array(t2, n2 + 4, 1);
    return new e35(c3, a3, s2, undefined, t2, n2);
  }
  constructor(e36, t2 = 16, n2 = Float64Array, o3 = ArrayBuffer, i3, r3 = 0) {
    if (e36 === undefined)
      throw new Error("Missing required argument: numItems.");
    if (isNaN(e36) || e36 <= 0)
      throw new Error(`Unexpected numItems value: ${e36}.`);
    this.numItems = +e36, this.nodeSize = Math.min(Math.max(+t2, 2), 65535), this.byteOffset = r3;
    let s2 = e36, a3 = s2;
    this._levelBounds = [4 * s2];
    do {
      s2 = Math.ceil(s2 / this.nodeSize), a3 += s2, this._levelBounds.push(4 * a3);
    } while (s2 !== 1);
    this.ArrayType = n2, this.IndexArrayType = a3 < 16384 ? Uint16Array : Uint32Array;
    const c3 = PB.indexOf(n2), l3 = 4 * a3 * n2.BYTES_PER_ELEMENT;
    if (c3 < 0)
      throw new Error(`Unexpected typed array class: ${n2}.`);
    const h2 = n2, d2 = this.IndexArrayType;
    if (i3)
      this.data = i3, this._boxes = new h2(i3, r3 + 8, 4 * a3), this._indices = new d2(i3, r3 + 8 + l3, a3), this._pos = 4 * a3, 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 {
      const n3 = this.data = new o3(8 + l3 + a3 * this.IndexArrayType.BYTES_PER_ELEMENT);
      this._boxes = new h2(n3, 8, 4 * a3), this._indices = new d2(n3, 8 + l3, a3), this._pos = 0, this.minX = 1 / 0, this.minY = 1 / 0, this.maxX = -1 / 0, this.maxY = -1 / 0, new Uint8Array(n3, 0, 2).set([251, 48 + c3]), new Uint16Array(n3, 2, 1)[0] = t2, new Uint32Array(n3, 4, 1)[0] = e36;
    }
    this._queue = new R;
  }
  add(e36, t2, n2 = e36, o3 = t2) {
    const i3 = this._pos, r3 = i3 >> 2, s2 = this._boxes;
    return this._indices[r3] = r3, s2[i3] = e36, s2[i3 + 1] = t2, s2[i3 + 2] = n2, s2[i3 + 3] = o3, this._pos = i3 + 4, e36 < this.minX && (this.minX = e36), t2 < this.minY && (this.minY = t2), n2 > this.maxX && (this.maxX = n2), o3 > this.maxY && (this.maxY = o3), r3;
  }
  finish() {
    if (this._pos >> 2 !== this.numItems)
      throw new Error(`Added ${this._pos >> 2} items when expected ${this.numItems}.`);
    const e36 = this._boxes;
    if (this.numItems <= this.nodeSize)
      return e36[this._pos++] = this.minX, e36[this._pos++] = this.minY, e36[this._pos++] = this.maxX, void (e36[this._pos++] = this.maxY);
    const { numItems: t2, minX: n2, minY: o3, nodeSize: i3, _indices: r3, _levelBounds: s2 } = this, a3 = this.maxX - n2 || 1, c3 = this.maxY - o3 || 1, l3 = new Int32Array(t2), h2 = 65535 / a3, d2 = 65535 / c3;
    for (let i4 = 0, r4 = 0;i4 < t2; i4++) {
      const t3 = e36[r4++], s3 = e36[r4++], a4 = h2 * ((t3 + e36[r4++]) / 2 - n2) | 0, c4 = d2 * ((s3 + e36[r4++]) / 2 - o3) | 0;
      l3[i4] = RB(a4, c4);
    }
    (function(e37, t3, n3, o4, i4, r4) {
      const s3 = [o4, i4];
      for (;s3.length; ) {
        const o5 = s3.pop() || 0, i5 = s3.pop() || 0;
        if (o5 - i5 <= r4 && Math.floor(i5 / r4) >= Math.floor(o5 / r4))
          continue;
        const a4 = e37[i5], c4 = e37[i5 + o5 >> 1], l4 = e37[o5], h3 = a4 > c4 != a4 > l4 ? a4 : c4 < a4 != c4 < l4 ? c4 : l4;
        let d3 = i5 - 1, u3 = o5 + 1;
        for (;; ) {
          do {
            d3++;
          } while (e37[d3] < h3);
          do {
            u3--;
          } while (e37[u3] > h3);
          if (d3 >= u3)
            break;
          NB(e37, t3, n3, d3, u3);
        }
        s3.push(i5, u3, u3 + 1, o5);
      }
    })(l3, e36, r3, 0, t2 - 1, i3);
    let u2 = 4 * t2;
    for (let t3 = 0, n3 = 0;t3 < s2.length - 1; t3++) {
      const o4 = s2[t3];
      for (;n3 < o4; ) {
        const t4 = n3;
        let s3 = e36[n3++], a4 = e36[n3++], c4 = e36[n3++], l4 = e36[n3++];
        for (let t5 = 1;t5 < i3 && n3 < o4; t5++)
          s3 = Math.min(s3, e36[n3++]), a4 = Math.min(a4, e36[n3++]), c4 = Math.max(c4, e36[n3++]), l4 = Math.max(l4, e36[n3++]);
        r3[u2 >> 2] = t4, e36[u2++] = s3, e36[u2++] = a4, e36[u2++] = c4, e36[u2++] = l4;
      }
    }
    this._pos = u2;
  }
  search(e36, t2, n2, o3, i3) {
    if (this._pos !== this._boxes.length)
      throw new Error("Data not yet indexed - call index.finish().");
    const { _boxes: r3, _levelBounds: s2, _indices: a3, nodeSize: c3 } = this, l3 = 4 * this.numItems;
    let h2 = r3.length - 4, d2 = s2.length - 1;
    const u2 = [], p3 = [];
    let m2 = false;
    for (;h2 !== undefined; ) {
      const g2 = Math.min(h2 + 4 * c3, s2[d2]), f2 = h2 >= l3;
      if (m2)
        this._collectContained(h2, g2, d2, l3, p3, i3);
      else
        for (let s3 = h2;s3 < g2; s3 += 4) {
          const c4 = r3[s3];
          if (n2 < c4)
            continue;
          const l4 = r3[s3 + 1];
          if (o3 < l4)
            continue;
          const h3 = r3[s3 + 2];
          if (e36 > h3)
            continue;
          const m3 = r3[s3 + 3];
          if (t2 > m3)
            continue;
          const g3 = 0 | a3[s3 >> 2];
          if (f2) {
            const i4 = +(e36 <= c4 && t2 <= l4 && n2 >= h3 && o3 >= m3);
            u2.push(g3 | i4, d2 - 1);
          } else
            (i3 === undefined || i3(g3, c4, l4, h3, m3)) && p3.push(g3);
        }
      d2 = u2.pop(), h2 = u2.pop(), h2 !== undefined && (m2 = !(1 & ~h2), h2 &= -2);
    }
    return p3;
  }
  _collectContained(e36, t2, n2, o3, i3, r3) {
    const s2 = this._boxes, a3 = this._indices;
    let c3 = e36;
    for (let e37 = n2;e37 > 0; e37--)
      c3 = a3[c3 >> 2];
    const l3 = Math.min(c3 + (t2 - e36) * this.nodeSize ** n2, o3);
    if (r3 === undefined)
      for (;c3 < l3; c3 += 4)
        i3.push(0 | a3[c3 >> 2]);
    else
      for (;c3 < l3; c3 += 4) {
        const e37 = 0 | a3[c3 >> 2];
        r3(e37, s2[c3], s2[c3 + 1], s2[c3 + 2], s2[c3 + 3]) && i3.push(e37);
      }
  }
  neighbors(e36, t2, n2 = 1 / 0, o3 = 1 / 0, i3) {
    if (this._pos !== this._boxes.length)
      throw new Error("Data not yet indexed - call index.finish().");
    const { _boxes: r3, _levelBounds: s2, _indices: a3, _queue: c3, nodeSize: l3 } = this, h2 = 4 * this.numItems, d2 = 4 * l3, u2 = [], p3 = n2 === 1;
    let m2 = o3 * o3;
    for (c3.push(r3.length - 4 << 1, 0);c3.length; ) {
      const o4 = c3.ids[0];
      if (1 & o4) {
        if (c3.pop(), u2.push(o4 >> 1), u2.length === n2)
          break;
        continue;
      }
      c3.pop();
      const l4 = o4 >> 1, g2 = l4 < h2, f2 = Math.min(l4 + d2, wB(l4, s2));
      for (let n3 = l4;n3 < f2; n3 += 4) {
        const o5 = r3[n3], s3 = r3[n3 + 1], l5 = r3[n3 + 2], h3 = r3[n3 + 3], d3 = Math.max(Math.max(o5 - e36, e36 - l5), 0), u3 = Math.max(Math.max(s3 - t2, t2 - h3), 0), f3 = d3 * d3 + u3 * u3;
        if (f3 > m2)
          continue;
        const _2 = 0 | a3[n3 >> 2];
        g2 ? (i3 === undefined || i3(_2)) && (c3.push(_2 << 1 | 1, f3), p3 && f3 < m2 && (m2 = f3)) : c3.push(_2 << 1, f3);
      }
    }
    return c3.clear(), u2;
  }
};
function wB(e36, t2) {
  let n2 = 0, o3 = t2.length - 1;
  for (;n2 < o3; ) {
    const i3 = n2 + o3 >> 1;
    t2[i3] > e36 ? o3 = i3 : n2 = i3 + 1;
  }
  return t2[n2];
}
function NB(e36, t2, n2, o3, i3) {
  const r3 = e36[o3];
  e36[o3] = e36[i3], e36[i3] = r3;
  const s2 = 4 * o3, a3 = 4 * i3, c3 = t2[s2], l3 = t2[s2 + 1], h2 = t2[s2 + 2], d2 = t2[s2 + 3];
  t2[s2] = t2[a3], t2[s2 + 1] = t2[a3 + 1], t2[s2 + 2] = t2[a3 + 2], t2[s2 + 3] = t2[a3 + 3], t2[a3] = c3, t2[a3 + 1] = l3, t2[a3 + 2] = h2, t2[a3 + 3] = d2;
  const u2 = n2[o3];
  n2[o3] = n2[i3], n2[i3] = u2;
}
function RB(e36, t2) {
  let n2 = e36 ^ t2, o3 = 65535 ^ n2, i3 = 65535 ^ (e36 | t2), r3 = e36 & (65535 ^ t2), s2 = n2 | o3 >> 1, a3 = n2 >> 1 ^ n2, c3 = i3 ^ i3 >> 1 ^ o3 & r3 >> 1, l3 = r3 ^ n2 & i3 >> 1 ^ r3 >> 1;
  return n2 = s2 & s2 >> 2 ^ a3 & a3 >> 2, o3 = s2 & a3 >> 2 ^ a3 & (s2 ^ a3) >> 2, i3 = c3 ^ s2 & c3 >> 2 ^ a3 & l3 >> 2, r3 = l3 ^ a3 & c3 >> 2 ^ (s2 ^ a3) & l3 >> 2, s2 = n2 & n2 >> 4 ^ o3 & o3 >> 4, a3 = n2 & o3 >> 4 ^ o3 & (n2 ^ o3) >> 4, c3 = i3 ^ n2 & i3 >> 4 ^ o3 & r3 >> 4, l3 = r3 ^ o3 & i3 >> 4 ^ (n2 ^ o3) & r3 >> 4, i3 = c3 ^ s2 & c3 >> 8 ^ a3 & l3 >> 8, r3 = l3 ^ a3 & c3 >> 8 ^ (s2 ^ a3) & l3 >> 8, i3 ^= i3 >> 1, r3 ^= r3 >> 1, n2 = e36 ^ t2, o3 = r3 | 65535 ^ (n2 | i3), n2 = 16711935 & (n2 | n2 << 8), n2 = 252645135 & (n2 | n2 << 4), n2 = 858993459 & (n2 | n2 << 2), n2 = 1431655765 & (n2 | n2 << 1), o3 = 16711935 & (o3 | o3 << 8), o3 = 252645135 & (o3 | o3 << 4), o3 = 858993459 & (o3 | o3 << 2), o3 = 1431655765 & (o3 | o3 << 1), ((o3 << 1 | n2) >>> 0) - 2147483648;
}
var TB = class {
  index;
  items = [];
  currentIndex = 0;
  capacity;
  constructor(e36) {
    this.capacity = Math.max(1, e36), this.index = new MB(this.capacity);
  }
  insert(e36, t2, n2, o3, i3) {
    if (this.currentIndex >= this.index.numItems)
      throw new Error("Exceeded initial capacity");
    this.items[this.currentIndex] = e36, this.index.add(t2, n2, o3, i3), this.currentIndex++;
  }
  finish() {
    this.index.finish();
  }
  search(e36, t2, n2, o3) {
    return this.index.search(e36, t2, n2, o3).map((e37) => this.items[e37] || null).filter(Boolean);
  }
  clear() {
    this.items = [], this.currentIndex = 0, this.index = new MB(this.capacity);
  }
};
var EB = class {
  idx;
  storage = [];
  constructor(e36 = "native", t2 = []) {
    e36 === "flatbush" ? t2.length === 0 ? (this.idx = new CB, e36 = "rbush") : this.idx = new TB(t2.length) : this.idx = e36 === "rbush" ? new CB : new class {
      shi = new AB(t2);
      insert(e37) {}
      search(e37, t3, n2, o3) {
        const i3 = (e37 + n2) / 2, r3 = (t3 + o3) / 2, s2 = n2 - e37, a3 = o3 - t3;
        return this.shi.getNodesInArea(i3, r3, s2, a3);
      }
      clear() {}
    }, t2.forEach((e37) => this.insert(e37)), e36 === "flatbush" && t2.length > 0 && this.idx.finish?.();
  }
  insert(e36) {
    this.storage.push(e36), this.idx.insert(e36, e36.center.x - e36.width / 2, e36.center.y - e36.height / 2, e36.center.x + e36.width / 2, e36.center.y + e36.height / 2);
  }
  search(e36) {
    return this.idx.search(e36.minX, e36.minY, e36.maxX, e36.maxY);
  }
  searchArea(e36, t2, n2, o3) {
    return this.search({ minX: e36 - n2 / 2, minY: t2 - o3 / 2, maxX: e36 + n2 / 2, maxY: t2 + o3 / 2 });
  }
};
var AB = class {
  constructor(e36) {
    this.obstacles = e36, this.buckets = new Map;
    for (let t2 = 0;t2 < e36.length; t2++) {
      const n2 = e36[t2], o3 = n2.center.x - n2.width / 2, i3 = n2.center.y - n2.height / 2, r3 = n2.center.x + n2.width / 2, s2 = n2.center.y + n2.height / 2;
      for (let e37 = o3;e37 <= r3; e37 += this.CELL_SIZE)
        for (let o4 = i3;o4 <= s2; o4 += this.CELL_SIZE) {
          const i4 = this.getBucketKey(e37, o4), r4 = this.buckets.get(i4);
          r4 ? r4.push([n2, t2]) : this.buckets.set(i4, [[n2, t2]]);
        }
    }
  }
  buckets;
  CELL_SIZE = 0.4;
  getBucketKey(e36, t2) {
    return `${Math.floor(e36 / this.CELL_SIZE)}x${Math.floor(t2 / this.CELL_SIZE)}`;
  }
  getNodesInArea(e36, t2, n2, o3) {
    const i3 = [], r3 = new Set, s2 = t2 - o3 / 2, a3 = e36 + n2 / 2, c3 = t2 + o3 / 2;
    for (let t3 = e36 - n2 / 2;t3 <= a3; t3 += this.CELL_SIZE)
      for (let e37 = s2;e37 <= c3; e37 += this.CELL_SIZE) {
        const n3 = this.getBucketKey(t3, e37), o4 = this.buckets.get(n3) || [];
        for (const e38 of o4)
          r3.has(e38[1]) || (r3.add(e38[1]), i3.push(e38[0]));
      }
    return i3;
  }
};
var OB = (e36) => ({ minX: Math.min(e36[0].x, e36[1].x), maxX: Math.max(e36[0].x, e36[1].x), minY: Math.min(e36[0].y, e36[1].y), maxY: Math.max(e36[0].y, e36[1].y) });
function kB(e36, t2) {
  const n2 = e36.x - t2.x, o3 = e36.y - t2.y;
  return n2 * n2 + o3 * o3;
}
function DB(e36, t2, n2) {
  const o3 = kB(t2, n2);
  if (o3 === 0)
    return kB(e36, t2);
  let i3 = ((e36.x - t2.x) * (n2.x - t2.x) + (e36.y - t2.y) * (n2.y - t2.y)) / o3;
  i3 = Math.max(0, Math.min(1, i3));
  return kB(e36, { x: t2.x + i3 * (n2.x - t2.x), y: t2.y + i3 * (n2.y - t2.y) });
}
function LB(e36, t2, n2, o3) {
  if (he(e36, t2, n2, o3))
    return 0;
  const i3 = { x: e36.x, y: e36.y }, r3 = { x: t2.x, y: t2.y }, s2 = { x: n2.x, y: n2.y }, a3 = { x: o3.x, y: o3.y };
  return Math.min(DB(i3, s2, a3), DB(r3, s2, a3), DB(s2, i3, r3), DB(a3, i3, r3));
}
var zB = class {
  segmentBuckets;
  viaBuckets;
  CELL_SIZE;
  maximumCopperRadius = 0;
  constructor(e36, t2 = 1) {
    this.segmentBuckets = new Map, this.viaBuckets = new Map, this.CELL_SIZE = t2;
    for (const t3 of e36)
      if (t3 && t3.connectionName) {
        if (this.maximumCopperRadius = Math.max(this.maximumCopperRadius, t3.traceThickness / 2, t3.viaDiameter / 2), t3.route && t3.route.length >= 2)
          for (let e37 = 0;e37 < t3.route.length - 1; e37++) {
            const n2 = t3.route[e37], o3 = t3.route[e37 + 1];
            if (n2.x === o3.x && n2.y === o3.y)
              continue;
            if (n2.insideJumperPad && o3.insideJumperPad)
              continue;
            const i3 = [n2, o3], r3 = OB(i3), s2 = { segmentId: `${t3.connectionName}-seg-${e37}`, segment: i3, parentRoute: t3 }, a3 = Math.floor(r3.minX / this.CELL_SIZE), c3 = Math.floor((r3.maxX + 0.000000001) / this.CELL_SIZE), l3 = Math.floor(r3.minY / this.CELL_SIZE), h2 = Math.floor((r3.maxY + 0.000000001) / this.CELL_SIZE);
            for (let e38 = a3;e38 <= c3; e38++)
              for (let t4 = l3;t4 <= h2; t4++) {
                const n3 = `${e38}x${t4}`;
                let o4 = this.segmentBuckets.get(n3);
                o4 || (o4 = [], this.segmentBuckets.set(n3, o4)), o4.push(s2);
              }
          }
        if (t3.vias && t3.vias.length > 0)
          for (let e37 = 0;e37 < t3.vias.length; e37++) {
            const n2 = t3.vias[e37];
            if (n2 == null)
              continue;
            const o3 = { viaId: `${t3.connectionName}-via-${e37}`, x: n2.x, y: n2.y, parentRoute: t3 }, i3 = `${Math.floor(n2.x / this.CELL_SIZE)}x${Math.floor(n2.y / this.CELL_SIZE)}`;
            let r3 = this.viaBuckets.get(i3);
            r3 || (r3 = [], this.viaBuckets.set(i3, r3)), r3.push(o3);
          }
      } else
        console.warn("Skipping route with missing data:", t3);
  }
  hasConflictingRoutesForSegment(e36, t2, n2, o3, i3) {
    const r3 = OB([e36, t2]), s2 = n2 + this.maximumCopperRadius, a3 = Math.floor((r3.minX - s2) / this.CELL_SIZE), c3 = Math.floor((r3.maxX + s2 + 0.000000001) / this.CELL_SIZE), l3 = Math.floor((r3.minY - s2) / this.CELL_SIZE), h2 = Math.floor((r3.maxY + s2 + 0.000000001) / this.CELL_SIZE), d2 = new Set, u2 = new Set;
    for (let r4 = a3;r4 <= c3; r4++)
      for (let s3 = l3;s3 <= h2; s3++) {
        const a4 = `${r4}x${s3}`, c4 = this.segmentBuckets.get(a4);
        if (c4)
          for (const r5 of c4) {
            const s4 = r5.parentRoute, [a5, c5] = r5.segment;
            if (e36.z !== t2.z || a5.z !== c5.z || a5.z !== e36.z || o3(s4) || d2.has(r5.segmentId))
              continue;
            d2.add(r5.segmentId);
            const l5 = n2 + s4.traceThickness / 2, h3 = LB(e36, t2, a5, c5);
            if (h3 < l5 * l5 && (!i3 || Math.sqrt(h3) < i3(s4)))
              return true;
          }
        const l4 = this.viaBuckets.get(a4);
        if (l4)
          for (const r5 of l4) {
            const s4 = r5.parentRoute;
            if (o3(s4) || u2.has(r5.viaId))
              continue;
            u2.add(r5.viaId);
            const a5 = n2 + s4.viaDiameter / 2, c5 = DB(r5, e36, t2);
            if (c5 < a5 * a5 && (!i3 || Math.sqrt(c5) < i3(s4)))
              return true;
          }
      }
    return false;
  }
  getConflictingRoutesForSegment(e36, t2, n2, o3) {
    const i3 = OB([e36, t2]), r3 = n2 + this.maximumCopperRadius, s2 = i3.minX - r3, a3 = i3.minY - r3, c3 = i3.maxX + r3, l3 = i3.maxY + r3, h2 = Math.floor(s2 / this.CELL_SIZE), d2 = Math.floor((c3 + 0.000000001) / this.CELL_SIZE), u2 = Math.floor(a3 / this.CELL_SIZE), p3 = Math.floor((l3 + 0.000000001) / this.CELL_SIZE), m2 = new Map, g2 = new Set, f2 = new Set, _2 = { x: e36.x, y: e36.y }, y2 = { x: t2.x, y: t2.y };
    for (let i4 = h2;i4 <= d2; i4++)
      for (let r4 = u2;r4 <= p3; r4++) {
        const s3 = `${i4}x${r4}`, a4 = this.segmentBuckets.get(s3);
        if (a4)
          for (const i5 of a4) {
            if (g2.has(i5.segmentId))
              continue;
            g2.add(i5.segmentId);
            const r5 = i5.parentRoute, [s4, a5] = i5.segment;
            if (e36.z !== t2.z || s4.z !== a5.z || s4.z !== e36.z)
              continue;
            if (o3?.(r5))
              continue;
            const c5 = n2 + r5.traceThickness / 2, l4 = c5 * c5, h3 = LB(e36, t2, s4, a5);
            if (h3 < l4) {
              const e37 = r5.connectionName, t3 = m2.get(e37);
              (!t3 || h3 < t3.minDistSq) && m2.set(e37, { route: r5, minDistSq: h3 });
            }
          }
        const c4 = this.viaBuckets.get(s3);
        if (c4)
          for (const e37 of c4) {
            if (f2.has(e37.viaId))
              continue;
            f2.add(e37.viaId);
            const t3 = e37.parentRoute;
            if (o3?.(t3))
              continue;
            const i5 = { x: e37.x, y: e37.y }, r5 = n2 + t3.viaDiameter / 2, s4 = r5 * r5, a5 = DB(i5, _2, y2);
            if (a5 < s4) {
              const e38 = t3.connectionName, n3 = m2.get(e38);
              (!n3 || a5 < n3.minDistSq) && m2.set(e38, { route: t3, minDistSq: a5 });
            }
          }
      }
    const b2 = [];
    for (const e37 of m2.values())
      b2.push({ conflictingRoute: e37.route, distance: Math.sqrt(e37.minDistSq) });
    return b2;
  }
  removeRoute(e36) {
    for (const [t2, n2] of this.segmentBuckets) {
      const o3 = n2.filter((t3) => t3.parentRoute.connectionName !== e36);
      o3.length === 0 ? this.segmentBuckets.delete(t2) : o3.length !== n2.length && this.segmentBuckets.set(t2, o3);
    }
    for (const [t2, n2] of this.viaBuckets) {
      const o3 = n2.filter((t3) => t3.parentRoute.connectionName !== e36);
      o3.length === 0 ? this.viaBuckets.delete(t2) : o3.length !== n2.length && this.viaBuckets.set(t2, o3);
    }
  }
  addRoute(e36) {
    if (!e36 || !e36.connectionName)
      return void console.warn("Skipping route with missing data:", e36);
    this.maximumCopperRadius = Math.max(this.maximumCopperRadius, e36.traceThickness / 2, e36.viaDiameter / 2);
    if (e36.route && e36.route.length >= 2)
      for (let t2 = 0;t2 < e36.route.length - 1; t2++) {
        const n2 = e36.route[t2], o3 = e36.route[t2 + 1];
        if (n2.x === o3.x && n2.y === o3.y)
          continue;
        if (n2.insideJumperPad && o3.insideJumperPad)
          continue;
        const i3 = [n2, o3], r3 = OB(i3), s2 = { segmentId: `${e36.connectionName}-seg-${t2}`, segment: i3, parentRoute: e36 }, a3 = Math.floor(r3.minX / this.CELL_SIZE), c3 = Math.floor((r3.maxX + 0.000000001) / this.CELL_SIZE), l3 = Math.floor(r3.minY / this.CELL_SIZE), h2 = Math.floor((r3.maxY + 0.000000001) / this.CELL_SIZE);
        for (let e37 = a3;e37 <= c3; e37++)
          for (let t3 = l3;t3 <= h2; t3++) {
            const n3 = `${e37}x${t3}`;
            let o4 = this.segmentBuckets.get(n3);
            o4 || (o4 = [], this.segmentBuckets.set(n3, o4)), o4.push(s2);
          }
      }
    if (e36.vias && e36.vias.length > 0)
      for (let t2 = 0;t2 < e36.vias.length; t2++) {
        const n2 = e36.vias[t2];
        if (n2 == null)
          continue;
        const o3 = { viaId: `${e36.connectionName}-via-${t2}`, x: n2.x, y: n2.y, parentRoute: e36 }, i3 = `${Math.floor(n2.x / this.CELL_SIZE)}x${Math.floor(n2.y / this.CELL_SIZE)}`;
        let r3 = this.viaBuckets.get(i3);
        r3 || (r3 = [], this.viaBuckets.set(i3, r3)), r3.push(o3);
      }
  }
  getConflictingRoutesNearPoint(e36, t2, n2) {
    const o3 = t2 + this.maximumCopperRadius, i3 = e36.x - o3, r3 = e36.y - o3, s2 = e36.x + o3, a3 = e36.y + o3, c3 = Math.floor(i3 / this.CELL_SIZE), l3 = Math.floor((s2 + 0.000000001) / this.CELL_SIZE), h2 = Math.floor(r3 / this.CELL_SIZE), d2 = Math.floor((a3 + 0.000000001) / this.CELL_SIZE), u2 = new Map, p3 = new Set, m2 = new Set;
    for (let n3 = c3;n3 <= l3; n3++)
      for (let o4 = h2;o4 <= d2; o4++) {
        const i4 = `${n3}x${o4}`, r4 = this.segmentBuckets.get(i4);
        if (r4)
          for (const n4 of r4) {
            if (p3.has(n4.segmentId))
              continue;
            p3.add(n4.segmentId);
            const o5 = n4.segment[0], i5 = n4.segment[1];
            if (o5.z !== i5.z || o5.z !== e36.z)
              continue;
            const r5 = n4.parentRoute, s4 = { x: n4.segment[0].x, y: n4.segment[0].y }, a4 = { x: n4.segment[1].x, y: n4.segment[1].y }, c4 = t2 + r5.traceThickness / 2, l4 = c4 * c4, h3 = DB(e36, s4, a4);
            if (h3 < l4) {
              const e37 = r5.connectionName, t3 = u2.get(e37);
              (!t3 || h3 < t3.minDistSq) && u2.set(e37, { route: r5, minDistSq: h3 });
            }
          }
        const s3 = this.viaBuckets.get(i4);
        if (s3)
          for (const n4 of s3) {
            if (m2.has(n4.viaId))
              continue;
            m2.add(n4.viaId);
            const o5 = n4.parentRoute, i5 = { x: n4.x, y: n4.y }, r5 = t2 + o5.viaDiameter / 2, s4 = r5 * r5, a4 = kB(e36, i5);
            if (a4 < s4) {
              const e37 = o5.connectionName, t3 = u2.get(e37);
              (!t3 || a4 < t3.minDistSq) && u2.set(e37, { route: o5, minDistSq: a4 });
            }
          }
      }
    const g2 = [];
    for (const e37 of u2.values())
      g2.push({ conflictingRoute: e37.route, distance: Math.sqrt(e37.minDistSq) });
    return g2;
  }
};
var BB = (e36, t2) => {
  const n2 = [], o3 = Math.abs(t2.x - e36.x), i3 = Math.abs(t2.y - e36.y), r3 = t2.x > e36.x ? 1 : -1, s2 = t2.y > e36.y ? 1 : -1, a3 = { x: t2.x - r3 * Math.abs(t2.y - e36.y), y: e36.y };
  (a3.x - e36.x) * r3 >= 0 && (a3.x - t2.x) * r3 <= 0 && n2.push([e36, a3, t2]);
  const c3 = { x: e36.x, y: t2.y - s2 * Math.abs(t2.x - e36.x) };
  (c3.y - e36.y) * s2 >= 0 && (c3.y - t2.y) * s2 <= 0 && n2.push([e36, c3, t2]);
  const l3 = Math.min(o3, i3), h2 = { x: e36.x + r3 * l3, y: e36.y + s2 * l3 };
  return (h2.x - e36.x) * r3 >= 0 && (h2.x - t2.x) * r3 <= 0 && (h2.y - e36.y) * s2 >= 0 && (h2.y - t2.y) * s2 <= 0 && n2.push([e36, h2, t2]), n2;
};
var FB = (e36, t2) => {
  const n2 = Math.max(Math.abs(e36), Math.abs(t2));
  if (n2 === 0 || n2 === Number.POSITIVE_INFINITY)
    return n2;
  const o3 = e36 / n2, i3 = t2 / n2;
  return n2 * Math.sqrt(o3 * o3 + i3 * i3);
};
function jB(e36, t2, n2, o3) {
  if (he(e36, t2, n2, o3))
    return 0;
  const i3 = $B(e36, n2, o3), r3 = $B(t2, n2, o3), s2 = $B(n2, e36, t2), a3 = $B(o3, e36, t2);
  return Math.min(i3, r3, s2, a3);
}
function $B(e36, t2, n2) {
  const o3 = { x: n2.x - t2.x, y: n2.y - t2.y }, i3 = YB({ x: e36.x - t2.x, y: e36.y - t2.y }, o3);
  if (i3 <= 0)
    return XB(e36, t2);
  const r3 = YB(o3, o3);
  if (r3 <= i3)
    return XB(e36, n2);
  const s2 = i3 / r3;
  return XB(e36, { x: t2.x + s2 * o3.x, y: t2.y + s2 * o3.y });
}
function YB(e36, t2) {
  return e36.x * t2.x + e36.y * t2.y;
}
function XB(e36, t2) {
  const n2 = t2.x - e36.x, o3 = t2.y - e36.y;
  return Math.sqrt(n2 * n2 + o3 * o3);
}
var HB = 0.000001;
var VB = (e36, t2, n2) => pe(e36, t2, n2) <= HB;
var WB = (e36, t2) => Math.abs(e36.x - t2.x) <= HB && Math.abs(e36.y - t2.y) <= HB;
var GB = (e36, t2) => {
  if (!t2 || t2.length < 3)
    return false;
  for (let n3 = 0;n3 < t2.length; n3++) {
    const o3 = t2[n3], i3 = t2[(n3 + 1) % t2.length];
    if (VB(e36, o3, i3))
      return true;
  }
  let n2 = false;
  for (let o3 = 0, i3 = t2.length - 1;o3 < t2.length; i3 = o3++) {
    const r3 = t2[o3], s2 = t2[i3];
    r3.y > e36.y != s2.y > e36.y && e36.x < (s2.x - r3.x) * (e36.y - r3.y) / (s2.y - r3.y) + r3.x && (n2 = !n2);
  }
  return n2;
};
var UB = ({ start: e36, end: t2, polygon: n2, margin: o3 = 0.2 }) => {
  if (!n2 || n2.length < 3)
    return false;
  const i3 = GB(e36, n2), r3 = GB(t2, n2);
  if (!i3 || !r3)
    return true;
  for (let i4 = 0;i4 < n2.length; i4++) {
    const r4 = n2[i4], s2 = n2[(i4 + 1) % n2.length], a3 = VB(e36, r4, s2), c3 = VB(t2, r4, s2);
    if (a3 && c3)
      continue;
    if (!he(e36, t2, r4, s2)) {
      if (!a3 && !c3) {
        if (jB(e36, t2, r4, s2) < o3 - HB)
          return true;
      }
      continue;
    }
    const l3 = ge(e36, t2, r4, s2);
    if ((!l3 || !(a3 && WB(l3, e36) || c3 && WB(l3, t2))) && (!l3 || !WB(l3, e36) && !WB(l3, t2)))
      return true;
  }
  return false;
};
var ZB = (e36) => {
  const t2 = [], n2 = e36.route;
  if (n2.length === 0)
    return [];
  let o3 = { startIndex: 0, endIndex: -1, z: n2[0].z, points: [n2[0]] };
  for (let e37 = 1;e37 < n2.length; e37++)
    n2[e37].z === o3.z ? o3.points.push(n2[e37]) : (o3.endIndex = e37 - 1, t2.push(o3), o3 = { startIndex: e37, endIndex: -1, z: n2[e37].z, points: [n2[e37]] });
  return o3.endIndex = n2.length - 1, t2.push(o3), t2;
};
var qB = ({ endpointX: e36, endpointY: t2, targetZ: n2, endpointPcbPortId: o3, terminalLayerIndicesByPcbPortId: i3, obstacleSHI: r3, route: s2, connMap: a3 }) => {
  const c3 = o3 ? i3?.get(o3) : undefined;
  if (c3 && !c3.has(n2))
    return false;
  const l3 = [s2.connectionName, s2.rootConnectionName].filter((e37) => e37 !== undefined), h2 = r3.searchArea(e36, t2, 2, 2).filter((n3) => {
    if (!l3.some((e37) => n3.connectedTo.some((t3) => t3 === e37 || a3.areIdsConnected(e37, t3))))
      return false;
    const o4 = n3.width / 2 + 0.05, i4 = n3.height / 2 + 0.05, r4 = Math.abs(e36 - n3.center.x) <= o4, s3 = Math.abs(t2 - n3.center.y) <= i4;
    return r4 && s3;
  });
  return h2.length > 0 && h2.some((e37) => e37.__zLayers?.includes(n2));
};
var JB = ({ currentSection: e36, targetZ: t2, route: n2, hdRouteSHI: o3, obstacleSHI: i3, connMap: r3, defaultTraceThickness: s2, obstacleMargin: a3, traceMargin: c3, shouldCheckStaticGeometryForSegment: l3 }) => {
  const h2 = n2.traceThickness ?? s2, d2 = c3 ?? 0, u2 = [n2.connectionName, n2.rootConnectionName].filter((e37) => e37 !== undefined);
  for (let n3 = 0;n3 < e36.points.length - 1; n3++) {
    const c4 = { ...e36.points[n3], z: t2 }, p3 = { ...e36.points[n3 + 1], z: t2 }, m2 = o3.getConflictingRoutesForSegment(c4, p3, h2 / 2 + d2);
    for (const { conflictingRoute: e37, distance: t3 } of m2) {
      const n4 = [e37.connectionName, e37.rootConnectionName].filter((e38) => e38 !== undefined);
      if (u2.some((e38) => n4.some((t4) => t4 === e38 || r3.areIdsConnected(t4, e38))))
        continue;
      const o4 = e37.traceThickness ?? s2;
      if (t3 < h2 / 2 + (d2 > 0 ? Math.max(o4 / 2, e37.viaDiameter / 2) : o4 / 2) + d2)
        return false;
    }
    if (l3?.(c4, p3) === false)
      continue;
    const g2 = { centerX: (c4.x + p3.x) / 2, centerY: (c4.y + p3.y) / 2, width: Math.abs(c4.x - p3.x), height: Math.abs(c4.y - p3.y) }, f2 = h2 / 2 + a3, _2 = i3.searchArea(g2.centerX, g2.centerY, g2.width + 2 * f2, g2.height + 2 * f2);
    for (const e37 of _2) {
      if (u2.some((t3) => e37.connectedTo.some((e38) => e38 === t3 || r3.areIdsConnected(e38, t3))))
        continue;
      if (e37.__zLayers?.includes(t2)) {
        if (Math.abs(c4.x - e37.center.x) < 0.01 && Math.abs(c4.y - e37.center.y) < 0.01 || Math.abs(p3.x - e37.center.x) < 0.01 && Math.abs(p3.y - e37.center.y) < 0.01)
          continue;
      }
      if (Re(c4, p3, e37) < f2)
        return false;
    }
  }
  return true;
};
var QB = ({ targetZ: e36, route: t2, hdRouteSHI: n2, obstacleSHI: o3, connMap: i3, defaultTraceThickness: r3, obstacleMargin: s2, traceMargin: a3, useNumericSegmentKeys: c3 }) => {
  const l3 = t2.traceThickness ?? r3, h2 = l3 / 2 + a3, d2 = l3 / 2 + s2, u2 = t2.connectionName, p3 = t2.rootConnectionName, m2 = new Map, g2 = new WeakMap, f2 = new WeakMap, _2 = c3 ? new Map : undefined;
  let y2 = 0;
  const b2 = (e37) => {
    let t3 = _2.get(e37.x);
    t3 || (t3 = new Map, _2.set(e37.x, t3));
    let n3 = t3.get(e37.y);
    return n3 === undefined && (n3 = y2++, t3.set(e37.y, n3)), n3;
  }, x2 = (e37, t3) => {
    if (c3) {
      const n3 = b2(e37), o4 = b2(t3), i4 = Math.max(n3, o4);
      return i4 * (i4 + 1) / 2 + Math.min(n3, o4);
    }
    return e37.x < t3.x || e37.x === t3.x && e37.y <= t3.y ? `${e37.x}:${e37.y}|${t3.x}:${t3.y}` : `${t3.x}:${t3.y}|${e37.x}:${e37.y}`;
  }, v2 = (e37) => e37 === u2 || i3.areIdsConnected(e37, u2) || p3 !== undefined && (e37 === p3 || i3.areIdsConnected(e37, p3)), I2 = (e37) => {
    let t3 = f2.get(e37);
    return t3 === undefined && (t3 = v2(e37.connectionName) || e37.rootConnectionName !== undefined && v2(e37.rootConnectionName), f2.set(e37, t3)), t3;
  }, S2 = (e37) => l3 / 2 + Math.max((e37.traceThickness ?? r3) / 2, e37.viaDiameter / 2) + a3;
  return (t3, i4) => {
    const r4 = t3.length - 1;
    for (let s3 = 0;s3 < r4; s3++) {
      const r5 = s3 - 1, a4 = i4 === 0 ? s3 : s3 === 0 ? i4 : r5 >= i4 ? r5 + 1 : r5, c4 = t3[a4], l4 = t3[a4 + 1], u3 = x2(c4, l4), p4 = m2.get(u3);
      if (p4 !== undefined) {
        if (!p4)
          return false;
        continue;
      }
      const f3 = c4.z === e36 ? c4 : { ...c4, z: e36 }, _3 = l4.z === e36 ? l4 : { ...l4, z: e36 }, y3 = { centerX: (f3.x + _3.x) / 2, centerY: (f3.y + _3.y) / 2, width: Math.abs(f3.x - _3.x), height: Math.abs(f3.y - _3.y) }, b3 = o3.searchArea(y3.centerX, y3.centerY, y3.width + 2 * d2, y3.height + 2 * d2);
      for (const t4 of b3) {
        let n3 = g2.get(t4);
        if (n3 === undefined && (n3 = t4.connectedTo.some(v2), g2.set(t4, n3)), n3)
          continue;
        if (t4.__zLayers?.includes(e36)) {
          if (Math.abs(f3.x - t4.center.x) < 0.01 && Math.abs(f3.y - t4.center.y) < 0.01 || Math.abs(_3.x - t4.center.x) < 0.01 && Math.abs(_3.y - t4.center.y) < 0.01)
            continue;
        }
        if (Re(f3, _3, t4) < d2)
          return m2.set(u3, false), false;
      }
      if (n2.hasConflictingRoutesForSegment(f3, _3, h2, I2, S2))
        return m2.set(u3, false), false;
      m2.set(u3, true);
    }
    return true;
  };
};
var KB = class extends SB {
  getSolverName() {
    return "SingleRouteUselessViaRemovalSolver";
  }
  obstacleSHI;
  hdRouteSHI;
  unsimplifiedRoute;
  connMap;
  outline;
  terminalLayerIndicesByPcbPortId;
  routeSections;
  currentSectionIndex;
  sameNetRouteCache = new WeakMap;
  detourContexts = new WeakMap;
  TRACE_THICKNESS = 0.15;
  OBSTACLE_MARGIN = 0.1;
  GEOMETRY_SHORTCUT_TRACE_MARGIN = 0.1;
  GEOMETRY_SHORTCUT_OBSTACLE_MARGIN = 0.15;
  MAX_GEOMETRY_SHORTCUT_ADDED_LENGTH = 4;
  ENABLE_GEOMETRY_SHORTCUTS = true;
  ENABLE_OBSTACLE_DETOUR_SHORTCUTS = false;
  ENABLE_ROUTED_TRACE_DETOURS = false;
  PRESERVE_ROUTE_ENDPOINTS = false;
  geometryShortcutsApplied = 0;
  multilayerSectionsCollapsed = 0;
  obstacleDetourCandidatesValidated = 0;
  constructor(e36) {
    super(), this.currentSectionIndex = 0, this.obstacleSHI = e36.obstacleSHI, this.hdRouteSHI = e36.hdRouteSHI, this.unsimplifiedRoute = e36.unsimplifiedRoute, this.connMap = e36.connMap, this.outline = e36.outline, this.terminalLayerIndicesByPcbPortId = e36.terminalLayerIndicesByPcbPortId, this.GEOMETRY_SHORTCUT_TRACE_MARGIN = e36.geometryShortcutTraceMargin ?? this.GEOMETRY_SHORTCUT_TRACE_MARGIN, this.GEOMETRY_SHORTCUT_OBSTACLE_MARGIN = e36.geometryShortcutObstacleMargin ?? this.GEOMETRY_SHORTCUT_OBSTACLE_MARGIN, this.ENABLE_GEOMETRY_SHORTCUTS = e36.enableGeometryShortcuts ?? true, this.ENABLE_OBSTACLE_DETOUR_SHORTCUTS = e36.enableObstacleDetourShortcuts ?? false, this.ENABLE_ROUTED_TRACE_DETOURS = e36.enableRoutedTraceDetours ?? false, this.PRESERVE_ROUTE_ENDPOINTS = e36.preserveRouteEndpoints ?? false, this.routeSections = ZB(this.unsimplifiedRoute);
  }
  getPathLength(e36) {
    let t2 = 0;
    for (let n2 = 1;n2 < e36.length; n2++)
      t2 += FB(e36[n2].x - e36[n2 - 1].x, e36[n2].y - e36[n2 - 1].y);
    return t2;
  }
  normalizeShortcutPath(e36, t2, n2) {
    const o3 = e36.filter((t3, n3) => {
      const o4 = e36[n3 - 1];
      return !o4 || t3.x !== o4.x || t3.y !== o4.y;
    });
    return o3.map((e37, i3) => i3 === 0 ? { ...t2 } : i3 === o3.length - 1 ? { ...n2 } : { x: e37.x, y: e37.y, z: t2.z });
  }
  shortcutCrossesOutline(e36) {
    if (!this.outline || this.outline.length < 3)
      return false;
    for (let t2 = 1;t2 < e36.length; t2++)
      if (UB({ start: e36[t2 - 1], end: e36[t2], polygon: this.outline }))
        return true;
    return false;
  }
  isRouteOnSameNet(e36) {
    const t2 = this.sameNetRouteCache.get(e36);
    if (t2 !== undefined)
      return t2;
    const n2 = [this.unsimplifiedRoute.connectionName, this.unsimplifiedRoute.rootConnectionName].filter((e37) => e37 !== undefined), o3 = [e36.connectionName, e36.rootConnectionName].filter((e37) => e37 !== undefined), i3 = n2.some((e37) => o3.some((t3) => e37 === t3 || this.connMap.areIdsConnected(e37, t3)));
    return this.sameNetRouteCache.set(e36, i3), i3;
  }
  getObstacleDetourContext(e36, t2, n2) {
    const o3 = this.ENABLE_ROUTED_TRACE_DETOURS ? this.detourContexts.get(e36)?.get(t2) : undefined;
    if (o3?.targetZ === n2)
      return o3;
    const i3 = this.unsimplifiedRoute.traceThickness ?? this.TRACE_THICKNESS, r3 = i3 / 2 + this.GEOMETRY_SHORTCUT_OBSTACLE_MARGIN + 0.000001, s2 = this.MAX_GEOMETRY_SHORTCUT_ADDED_LENGTH / 2 + r3, a3 = Math.min(e36.x, t2.x) - s2, c3 = Math.max(e36.x, t2.x) + s2, l3 = Math.min(e36.y, t2.y) - s2, h2 = Math.max(e36.y, t2.y) + s2, d2 = this.obstacleSHI.search({ minX: a3, minY: l3, maxX: c3, maxY: h2 }).filter((e37) => e37.__zLayers?.includes(n2)), u2 = this.ENABLE_ROUTED_TRACE_DETOURS ? this.hdRouteSHI.getConflictingRoutesForSegment({ ...e36, z: n2 }, { ...t2, z: n2 }, i3 / 2 + this.GEOMETRY_SHORTCUT_TRACE_MARGIN, (e37) => this.isRouteOnSameNet(e37)) : [], p3 = [], m2 = new Set, g2 = new Set;
    for (const e37 of d2)
      m2.add(e37.center.x - e37.width / 2 - r3), m2.add(e37.center.x + e37.width / 2 + r3), g2.add(e37.center.y - e37.height / 2 - r3), g2.add(e37.center.y + e37.height / 2 + r3);
    for (const { conflictingRoute: e37 } of u2) {
      const t3 = e37.route.filter((e38) => e38.z === n2 && e38.x >= a3 && e38.x <= c3 && e38.y >= l3 && e38.y <= h2);
      if (t3.length === 0)
        continue;
      const o4 = i3 / 2 + Math.max(e37.traceThickness / 2, e37.viaDiameter / 2) + this.GEOMETRY_SHORTCUT_TRACE_MARGIN + 0.000001;
      m2.add(Math.min(...t3.map((e38) => e38.x)) - o4), m2.add(Math.max(...t3.map((e38) => e38.x)) + o4), g2.add(Math.min(...t3.map((e38) => e38.y)) - o4), g2.add(Math.max(...t3.map((e38) => e38.y)) + o4);
      {
        const e38 = Math.min(...t3.map((e39) => e39.x)) - o4, n3 = Math.max(...t3.map((e39) => e39.x)) + o4, i4 = Math.min(...t3.map((e39) => e39.y)) - o4, r4 = Math.max(...t3.map((e39) => e39.y)) + o4;
        p3.push({ x: e38, y: i4 }, { x: e38, y: r4 }, { x: n3, y: i4 }, { x: n3, y: r4 });
      }
    }
    const f2 = { targetZ: n2, traceCorners: p3, corridorXs: m2, corridorYs: g2 };
    if (this.ENABLE_ROUTED_TRACE_DETOURS) {
      const n3 = this.detourContexts.get(e36) ?? new WeakMap;
      n3.set(t2, f2), this.detourContexts.set(e36, n3);
    }
    return f2;
  }
  getObstacleDetourPaths(e36, t2, n2, o3, i3 = false, r3) {
    const { traceCorners: s2, corridorXs: a3, corridorYs: c3 } = this.getObstacleDetourContext(e36, t2, n2), l3 = [], h2 = new Set, d2 = (n3) => {
      let i4 = 0;
      for (let e37 = 1;e37 < n3.length; e37++)
        i4 += FB(n3[e37].x - n3[e37 - 1].x, n3[e37].y - n3[e37 - 1].y);
      if (i4 > o3)
        return;
      if (r3) {
        let t3 = 0, o4 = -1;
        for (let e37 = 0;e37 < n3.length - 1; e37++) {
          const i5 = n3[e37 + 1].x - n3[e37].x, r4 = n3[e37 + 1].y - n3[e37].y, s4 = i5 * i5 + r4 * r4;
          s4 > o4 && (t3 = e37, o4 = s4);
        }
        if (!r3([{ ...n3[t3], z: e36.z }, { ...n3[t3 + 1], z: e36.z }], 0))
          return;
      }
      const s3 = this.normalizeShortcutPath(n3, e36, t2);
      let a4 = 0, c4 = -1;
      for (let e37 = 0;e37 < s3.length - 1; e37++) {
        const t3 = s3[e37 + 1].x - s3[e37].x, n4 = s3[e37 + 1].y - s3[e37].y, o4 = t3 * t3 + n4 * n4;
        o4 > c4 && (a4 = e37, c4 = o4);
      }
      const d3 = s3.map((e37) => `${e37.x}:${e37.y}`).join("|");
      h2.has(d3) || (h2.add(d3), l3.push({ path: s3, length: i4, longestSegmentIndex: a4 }));
    };
    if (i3) {
      for (const n3 of s2)
        for (const o4 of BB(e36, n3))
          for (const e37 of BB(n3, t2))
            d2([...o4, ...e37.slice(1)]);
      return l3;
    }
    for (const n3 of c3)
      d2([e36, { x: e36.x, y: n3 }, { x: t2.x, y: n3 }, t2]);
    for (const n3 of a3)
      d2([e36, { x: n3, y: e36.y }, { x: n3, y: t2.y }, t2]);
    return l3;
  }
  getDirectGeometryShortcut(e36, t2, n2) {
    let o3 = null;
    const i3 = QB({ targetZ: e36.z, route: this.unsimplifiedRoute, hdRouteSHI: this.hdRouteSHI, obstacleSHI: this.obstacleSHI, connMap: this.connMap, defaultTraceThickness: this.TRACE_THICKNESS, obstacleMargin: this.GEOMETRY_SHORTCUT_OBSTACLE_MARGIN, traceMargin: this.GEOMETRY_SHORTCUT_TRACE_MARGIN, useNumericSegmentKeys: true });
    for (let r3 = 0;r3 < e36.points.length; r3++) {
      const s2 = e36.points[r3];
      for (let a3 = 0;a3 < n2.points.length; a3++) {
        const c3 = n2.points[a3], l3 = [...e36.points.slice(r3), ...t2.points, ...n2.points.slice(0, a3 + 1)];
        if (!l3.some((e37) => e37.insideJumperPad || e37.toNextSegmentType))
          for (const e37 of BB(s2, c3)) {
            const t3 = this.normalizeShortcutPath(e37, s2, c3), n3 = this.getPathLength(l3) - this.getPathLength(t3);
            if (n3 < -0.000001)
              continue;
            i3(t3, 0) && !this.shortcutCrossesOutline(t3) && ((!o3 || n3 > o3.savedLength) && (o3 = { path: t3, previousPointIndex: r3, nextPointIndex: a3, savedLength: n3 }));
          }
      }
    }
    return o3;
  }
  getObstacleDetourShortcut(e36, t2, n2, o3 = false) {
    const i3 = e36.points.length - 1, r3 = [];
    for (let e37 = 0;e37 <= i3; e37++)
      r3.push([e37, 0]);
    for (let e37 = 1;e37 < n2.points.length; e37++)
      r3.push([i3, e37]);
    const s2 = this.ENABLE_ROUTED_TRACE_DETOURS ? QB({ targetZ: e36.z, route: this.unsimplifiedRoute, hdRouteSHI: this.hdRouteSHI, obstacleSHI: this.obstacleSHI, connMap: this.connMap, defaultTraceThickness: this.TRACE_THICKNESS, obstacleMargin: this.GEOMETRY_SHORTCUT_OBSTACLE_MARGIN, traceMargin: this.GEOMETRY_SHORTCUT_TRACE_MARGIN, useNumericSegmentKeys: true }) : undefined, a3 = [];
    for (const [i4, c4] of r3) {
      const r4 = e36.points[i4], l4 = n2.points[c4], h3 = [...e36.points.slice(i4), ...t2.points, ...n2.points.slice(0, c4 + 1)];
      if (h3.some((e37) => e37.insideJumperPad || e37.toNextSegmentType))
        continue;
      const d2 = this.getPathLength(h3);
      for (const { path: t3, length: n3, longestSegmentIndex: h4 } of this.getObstacleDetourPaths(r4, l4, e36.z, d2 + this.MAX_GEOMETRY_SHORTCUT_ADDED_LENGTH + 0.000001, o3, s2)) {
        const e37 = d2 - n3;
        e37 < -this.MAX_GEOMETRY_SHORTCUT_ADDED_LENGTH - 0.000001 || a3.push({ path: t3, previousPointIndex: i4, nextPointIndex: c4, savedLength: e37, validationFirstSegmentIndex: h4 });
      }
    }
    a3.sort((e37, t3) => t3.savedLength - e37.savedLength);
    let c3 = 0;
    const l3 = a3.length >= 256, h2 = s2 ?? QB({ targetZ: e36.z, route: this.unsimplifiedRoute, hdRouteSHI: this.hdRouteSHI, obstacleSHI: this.obstacleSHI, connMap: this.connMap, defaultTraceThickness: this.TRACE_THICKNESS, obstacleMargin: this.GEOMETRY_SHORTCUT_OBSTACLE_MARGIN, traceMargin: this.GEOMETRY_SHORTCUT_TRACE_MARGIN, useNumericSegmentKeys: l3 });
    for (const e37 of a3) {
      c3++;
      const { path: t3 } = e37;
      if (h2(t3, e37.validationFirstSegmentIndex ?? 0) && !this.shortcutCrossesOutline(t3))
        return this.obstacleDetourCandidatesValidated += c3, this.stats.obstacleDetourCandidatesValidated = this.obstacleDetourCandidatesValidated, e37;
    }
    return this.obstacleDetourCandidatesValidated += c3, this.stats.obstacleDetourCandidatesValidated = this.obstacleDetourCandidatesValidated, null;
  }
  findGeometryShortcut(e36, t2, n2) {
    if (this.detourContexts = new WeakMap, this.unsimplifiedRoute.jumpers?.length)
      return null;
    if (this.ENABLE_GEOMETRY_SHORTCUTS) {
      const o4 = this.getDirectGeometryShortcut(e36, t2, n2);
      if (o4)
        return o4;
    }
    if (!this.ENABLE_OBSTACLE_DETOUR_SHORTCUTS)
      return null;
    const o3 = this.getObstacleDetourShortcut(e36, t2, n2);
    return o3 || !this.ENABLE_ROUTED_TRACE_DETOURS ? o3 : this.getObstacleDetourShortcut(e36, t2, n2, true);
  }
  applyGeometryShortcut(e36) {
    const t2 = this.routeSections[this.currentSectionIndex - 1], n2 = this.routeSections[this.currentSectionIndex + 1], o3 = [...t2.points.slice(0, e36.previousPointIndex), ...e36.path, ...n2.points.slice(e36.nextPointIndex + 1)].filter((e37, t3, n3) => {
      const o4 = n3[t3 - 1];
      return !o4 || e37.x !== o4.x || e37.y !== o4.y || e37.z !== o4.z;
    });
    this.routeSections.splice(this.currentSectionIndex - 1, 3, { startIndex: t2.startIndex, endIndex: n2.endIndex, z: t2.z, points: o3 }), this.geometryShortcutsApplied++, this.stats.geometryShortcutsApplied = this.geometryShortcutsApplied, this.stats.viasRemovedByGeometryShortcuts = 2 * this.geometryShortcutsApplied, this.currentSectionIndex = Math.max(0, this.currentSectionIndex - 1);
  }
  findMultilayerSectionCollapse(e36, t2, n2) {
    if (e36.z === n2.z || this.unsimplifiedRoute.jumpers?.length)
      return null;
    const o3 = e36.points[e36.points.length - 1];
    if (o3?.insideJumperPad || o3?.toNextSegmentType || t2.points.some((e37) => e37.insideJumperPad || e37.toNextSegmentType))
      return null;
    const i3 = [{ targetZ: e36.z, mergeWith: "previous" }, { targetZ: n2.z, mergeWith: "next" }];
    for (const e37 of i3)
      if (e37.targetZ !== t2.z && JB({ currentSection: t2, targetZ: e37.targetZ, route: this.unsimplifiedRoute, hdRouteSHI: this.hdRouteSHI, obstacleSHI: this.obstacleSHI, connMap: this.connMap, defaultTraceThickness: this.TRACE_THICKNESS, obstacleMargin: this.GEOMETRY_SHORTCUT_OBSTACLE_MARGIN, traceMargin: this.GEOMETRY_SHORTCUT_TRACE_MARGIN }))
        return e37;
    return null;
  }
  applyMultilayerSectionCollapse(e36) {
    const t2 = this.routeSections[this.currentSectionIndex - 1], n2 = this.routeSections[this.currentSectionIndex], o3 = this.routeSections[this.currentSectionIndex + 1], i3 = n2.points.map((t3) => ({ ...t3, z: e36.targetZ })), r3 = (e37) => e37.filter((t3, n3) => {
      const o4 = e37[n3 - 1];
      return !o4 || t3.x !== o4.x || t3.y !== o4.y || t3.z !== o4.z;
    });
    e36.mergeWith === "previous" ? this.routeSections.splice(this.currentSectionIndex - 1, 2, { startIndex: t2.startIndex, endIndex: n2.endIndex, z: e36.targetZ, points: r3([...t2.points, ...i3]) }) : this.routeSections.splice(this.currentSectionIndex, 2, { startIndex: n2.startIndex, endIndex: o3.endIndex, z: e36.targetZ, points: r3([...i3, ...o3.points]) }), this.multilayerSectionsCollapsed++, this.stats.multilayerSectionsCollapsed = this.multilayerSectionsCollapsed, this.stats.viasRemovedByMultilayerSectionCollapses = this.multilayerSectionsCollapsed, this.currentSectionIndex = Math.max(0, this.currentSectionIndex - 1);
  }
  _step() {
    if (this.currentSectionIndex >= this.routeSections.length)
      return void (this.solved = true);
    if (this.currentSectionIndex === 0 && this.routeSections.length > 1) {
      const e37 = this.routeSections[0], t3 = this.routeSections[1];
      if (!this.PRESERVE_ROUTE_ENDPOINTS && e37.z !== t3.z) {
        const n3 = t3.z, o4 = e37.points[0];
        if (qB({ endpointX: o4.x, endpointY: o4.y, targetZ: n3, endpointPcbPortId: this.unsimplifiedRoute.startPcbPortId, terminalLayerIndicesByPcbPortId: this.terminalLayerIndicesByPcbPortId, obstacleSHI: this.obstacleSHI, route: this.unsimplifiedRoute, connMap: this.connMap }) && JB({ currentSection: e37, targetZ: n3, route: this.unsimplifiedRoute, hdRouteSHI: this.hdRouteSHI, obstacleSHI: this.obstacleSHI, connMap: this.connMap, defaultTraceThickness: this.TRACE_THICKNESS, obstacleMargin: this.OBSTACLE_MARGIN }))
          return e37.z = n3, e37.points = e37.points.map((e38) => ({ ...e38, z: n3 })), void (this.currentSectionIndex = 2);
      }
      return void this.currentSectionIndex++;
    }
    if (this.currentSectionIndex === this.routeSections.length - 1) {
      if (!this.PRESERVE_ROUTE_ENDPOINTS && this.routeSections.length >= 2) {
        const e37 = this.routeSections[this.routeSections.length - 1], t3 = this.routeSections[this.routeSections.length - 2];
        if (e37.z !== t3.z) {
          const n3 = t3.z, o4 = e37.points[e37.points.length - 1];
          qB({ endpointX: o4.x, endpointY: o4.y, targetZ: n3, endpointPcbPortId: this.unsimplifiedRoute.endPcbPortId, terminalLayerIndicesByPcbPortId: this.terminalLayerIndicesByPcbPortId, obstacleSHI: this.obstacleSHI, route: this.unsimplifiedRoute, connMap: this.connMap }) && JB({ currentSection: e37, targetZ: n3, route: this.unsimplifiedRoute, hdRouteSHI: this.hdRouteSHI, obstacleSHI: this.obstacleSHI, connMap: this.connMap, defaultTraceThickness: this.TRACE_THICKNESS, obstacleMargin: this.OBSTACLE_MARGIN }) && (e37.z = n3, e37.points = e37.points.map((e38) => ({ ...e38, z: n3 })));
        }
      }
      return void (this.solved = true);
    }
    const e36 = this.routeSections[this.currentSectionIndex - 1], t2 = this.routeSections[this.currentSectionIndex], n2 = this.routeSections[this.currentSectionIndex + 1];
    if (e36.z !== n2.z) {
      const o4 = this.findMultilayerSectionCollapse(e36, t2, n2);
      return o4 ? void this.applyMultilayerSectionCollapse(o4) : void this.currentSectionIndex++;
    }
    const o3 = e36.z;
    if (JB({ currentSection: t2, targetZ: o3, route: this.unsimplifiedRoute, hdRouteSHI: this.hdRouteSHI, obstacleSHI: this.obstacleSHI, connMap: this.connMap, defaultTraceThickness: this.TRACE_THICKNESS, obstacleMargin: this.OBSTACLE_MARGIN }))
      return t2.z = o3, t2.points = t2.points.map((e37) => ({ ...e37, z: o3 })), void (this.currentSectionIndex += 2);
    const i3 = this.findGeometryShortcut(e36, t2, n2);
    i3 ? this.applyGeometryShortcut(i3) : this.currentSectionIndex++;
  }
  getConstructorParams() {
    return { obstacleSHI: this.obstacleSHI, hdRouteSHI: this.hdRouteSHI, unsimplifiedRoute: this.unsimplifiedRoute, connMap: this.connMap, outline: this.outline, geometryShortcutTraceMargin: this.GEOMETRY_SHORTCUT_TRACE_MARGIN, geometryShortcutObstacleMargin: this.GEOMETRY_SHORTCUT_OBSTACLE_MARGIN, enableGeometryShortcuts: this.ENABLE_GEOMETRY_SHORTCUTS, enableObstacleDetourShortcuts: this.ENABLE_OBSTACLE_DETOUR_SHORTCUTS, enableRoutedTraceDetours: this.ENABLE_ROUTED_TRACE_DETOURS, preserveRouteEndpoints: this.PRESERVE_ROUTE_ENDPOINTS, terminalLayerIndicesByPcbPortId: this.terminalLayerIndicesByPcbPortId };
  }
  getOptimizedHdRoute() {
    const e36 = this.routeSections.flatMap((e37) => e37.points), t2 = [];
    for (let n2 = 0;n2 < e36.length - 1; n2++)
      e36[n2].z !== e36[n2 + 1].z && t2.push({ x: e36[n2].x, y: e36[n2].y });
    return { connectionName: this.unsimplifiedRoute.connectionName, rootConnectionName: this.unsimplifiedRoute.rootConnectionName, startPcbPortId: this.unsimplifiedRoute.startPcbPortId, endPcbPortId: this.unsimplifiedRoute.endPcbPortId, route: e36, traceThickness: this.unsimplifiedRoute.traceThickness, vias: t2, viaDiameter: this.unsimplifiedRoute.viaDiameter, jumpers: this.unsimplifiedRoute.jumpers };
  }
  visualize() {
    const e36 = { circles: [], lines: [], points: [], rects: [], coordinateSystem: "cartesian", title: "Single Route Useless Via Removal Solver" };
    for (let t2 = 0;t2 < this.routeSections.length; t2++) {
      const n2 = this.routeSections[t2];
      e36.lines.push({ points: n2.points, strokeWidth: this.TRACE_THICKNESS, strokeColor: t2 === this.currentSectionIndex ? "orange" : n2.z === 0 ? "red" : "blue" });
    }
    return e36;
  }
};
var eF = (e36, t2) => {
  try {
    return Hn(t2, e36);
  } catch (t3) {
    return console.error(t3), e36;
  }
};
var tF = { "0603": { length: 1.65, width: 0.95, padLength: 0.8, padWidth: 0.95 }, 1206: { length: 3.2, width: 1.6, padLength: 0.6, padWidth: 1.6 }, "1206x4_pair": { length: 2.7, width: 0.5, padLength: 0.8, padWidth: 0.5 } };
function nF(e36, t2 = {}) {
  const n2 = [], o3 = [], i3 = t2.color ?? "gray", r3 = t2.label, s2 = tF[e36.footprint] ?? tF["0603"], a3 = e36.end.x - e36.start.x, c3 = e36.end.y - e36.start.y, l3 = Math.abs(a3) > Math.abs(c3), h2 = l3 ? s2.padLength : s2.padWidth, d2 = l3 ? s2.padWidth : s2.padLength;
  return n2.push({ center: e36.start, width: h2, height: d2, fill: eF(i3, 0.5), stroke: "rgba(0, 0, 0, 0.5)", layer: "jumper", label: r3 ? `${r3} (start)` : undefined }), n2.push({ center: e36.end, width: h2, height: d2, fill: eF(i3, 0.5), stroke: "rgba(0, 0, 0, 0.5)", layer: "jumper", label: r3 ? `${r3} (end)` : undefined }), o3.push({ points: [e36.start, e36.end], strokeColor: "rgba(100, 100, 100, 0.8)", strokeWidth: 0.3 * s2.padWidth, layer: "jumper-body" }), { rects: n2, lines: o3 };
}
function oF(e36, t2 = {}) {
  const n2 = { rects: [], lines: [] };
  for (const o3 of e36) {
    const { rects: e37, lines: i3 } = nF(o3, t2);
    n2.rects.push(...e37), n2.lines.push(...i3);
  }
  return n2;
}
function iF(e36, t2) {
  return [...new Set(e36)].filter((e37) => Number.isInteger(e37) && e37 >= 0 && e37 < t2).sort((e37, t3) => e37 - t3);
}
function rF(e36, t2) {
  return iF(e36.map((e37) => ((e38, t3) => e38 === "top" ? 0 : e38 === "bottom" ? t3 - 1 : parseInt(e38.slice(5)))(e37, t2)), t2);
}
var sF = (e36, t2 = 2) => {
  const n2 = Array.from({ length: t2 }, (e37, t3) => t3);
  return e36.map((e37) => {
    const o3 = iF(e37.__zLayers ?? (e37.layers ? rF(e37.layers, t2) : undefined) ?? n2, t2);
    return { ...e37, __zLayers: o3.length > 0 ? o3 : n2 };
  });
};
var aF = class extends SB {
  constructor(e36) {
    super(), this.input = e36, this.input = { ...e36, obstacles: sF(e36.obstacles, e36.layerCount) }, this.MAX_ITERATIONS = 1e6, this.unsimplifiedHdRoutes = e36.unsimplifiedHdRoutes, this.optimizedHdRoutes = [], this.unprocessedRoutes = [...e36.unsimplifiedHdRoutes], this.obstacleSHI = new EB("flatbush", this.input.obstacles), this.hdRouteSHI = new zB([...this.unsimplifiedHdRoutes, ...e36.otherHdRoutes ?? []]);
  }
  getSolverName() {
    return "UselessViaRemovalSolver";
  }
  unsimplifiedHdRoutes;
  optimizedHdRoutes;
  unprocessedRoutes;
  activeSubSolver = null;
  obstacleSHI = null;
  hdRouteSHI = null;
  _step() {
    if (this.activeSubSolver) {
      if (this.activeSubSolver.step(), this.activeSubSolver.solved) {
        const e37 = this.activeSubSolver.getOptimizedHdRoute();
        this.hdRouteSHI.removeRoute(e37.connectionName), this.hdRouteSHI.addRoute(e37), this.optimizedHdRoutes.push(e37), this.activeSubSolver = null;
      } else
        (this.activeSubSolver.failed || this.activeSubSolver.error) && (this.error = this.activeSubSolver.error, this.failed = true);
      return;
    }
    const e36 = this.unprocessedRoutes.shift();
    e36 ? this.activeSubSolver = new KB({ hdRouteSHI: this.hdRouteSHI, obstacleSHI: this.obstacleSHI, unsimplifiedRoute: e36, connMap: this.input.connMap, outline: this.input.outline, geometryShortcutTraceMargin: this.input.geometryShortcutTraceMargin, geometryShortcutObstacleMargin: this.input.geometryShortcutObstacleMargin, enableGeometryShortcuts: this.input.enableGeometryShortcuts, enableObstacleDetourShortcuts: this.input.enableObstacleDetourShortcuts, enableRoutedTraceDetours: this.input.enableRoutedTraceDetours, preserveRouteEndpoints: this.input.preserveRouteEndpoints, terminalLayerIndicesByPcbPortId: this.input.terminalLayerIndicesByPcbPortId }) : this.solved = true;
  }
  getOptimizedHdRoutes() {
    return this.optimizedHdRoutes;
  }
  visualize() {
    const e36 = { lines: [], points: [], rects: [], circles: [], coordinateSystem: "cartesian", title: "Useless Via Removal Solver" };
    for (const t2 of this.input.obstacles) {
      let n2 = "rgba(128, 128, 128, 0.2)";
      const o3 = t2.__zLayers?.includes(0), i3 = t2.__zLayers?.includes(1);
      o3 && i3 ? n2 = "rgba(128, 0, 128, 0.2)" : o3 ? n2 = "rgba(255, 0, 0, 0.2)" : i3 && (n2 = "rgba(0, 0, 255, 0.2)"), e36.rects.push({ center: t2.center, width: t2.width, height: t2.height, fill: n2, label: `Obstacle (Z: ${t2.__zLayers?.join(", ")})` });
    }
    for (const t2 of this.optimizedHdRoutes) {
      if (t2.route.length === 0)
        continue;
      const n2 = this.input.colorMap[t2.connectionName] || "#888888";
      for (let n3 = 0;n3 < t2.route.length - 1; n3++) {
        const o3 = t2.route[n3], i3 = t2.route[n3 + 1];
        o3.z === i3.z && e36.lines.push({ points: [{ x: o3.x, y: o3.y }, { x: i3.x, y: i3.y }], strokeColor: o3.z === 0 ? "red" : "blue", strokeWidth: t2.traceThickness, label: `${t2.connectionName} (z=${o3.z})` });
      }
      for (const n3 of t2.vias)
        e36.circles.push({ center: { x: n3.x, y: n3.y }, radius: t2.viaDiameter / 2, fill: "rgba(255, 0, 255, 0.5)", label: `${t2.connectionName} via` });
      if (t2.jumpers && t2.jumpers.length > 0) {
        const o3 = oF(t2.jumpers, { color: n2, label: t2.connectionName });
        e36.rects.push(...o3.rects ?? []), e36.lines.push(...o3.lines ?? []);
      }
    }
    return this.activeSubSolver && e36.lines.push(...this.activeSubSolver.visualize().lines ?? []), e36;
  }
};
var cF = class {
  netMap;
  idToNetMap;
  constructor(e36) {
    this.netMap = e36, this.idToNetMap = {};
    for (const [t2, n2] of Object.entries(e36))
      for (const e37 of n2)
        this.idToNetMap[e37] = t2;
  }
  addConnections(e36) {
    for (const t2 of e36) {
      const e37 = new Set;
      for (const n3 of t2) {
        const t3 = this.idToNetMap[n3];
        t3 && e37.add(t3);
      }
      let n2;
      if (e37.size === 0)
        n2 = `connectivity_net${Object.keys(this.netMap).length}`, this.netMap[n2] = [];
      else if (e37.size === 1)
        n2 = e37.values().next().value ?? `connectivity_net${Object.keys(this.netMap).length}`;
      else {
        n2 = e37.values().next().value ?? `connectivity_net${Object.keys(this.netMap).length}`;
        for (const t3 of e37)
          if (t3 !== n2) {
            this.netMap[n2].push(...this.netMap[t3]), this.netMap[t3] = this.netMap[n2];
            for (const e38 of this.netMap[n2])
              this.idToNetMap[e38] = n2;
          }
      }
      for (const e38 of t2)
        this.netMap[n2].includes(e38) || this.netMap[n2].push(e38), this.idToNetMap[e38] = n2;
    }
  }
  getIdsConnectedToNet(e36) {
    return this.netMap[e36] || [];
  }
  getNetConnectedToId(e36) {
    return this.idToNetMap[e36];
  }
  areIdsConnected(e36, t2) {
    if (e36 === t2)
      return true;
    const n2 = this.getNetConnectedToId(e36);
    if (!n2)
      return false;
    const o3 = this.getNetConnectedToId(t2);
    return !!o3 && (n2 === o3 || o3 === e36 || o3 === e36);
  }
  areAllIdsConnected(e36) {
    const t2 = this.getNetConnectedToId(e36[0]);
    for (const n2 of e36) {
      const e37 = this.getNetConnectedToId(n2);
      if (e37 === undefined)
        return false;
      if (e37 !== t2)
        return false;
    }
    return true;
  }
};
var lF = class extends SB {
  getSolverName() {
    return "SingleSimplifiedPathSolver";
  }
  newRoute;
  newVias;
  headIndex = 0;
  tailIndex = 0;
  inputRoute;
  otherHdRoutes;
  obstacles;
  connMap;
  colorMap;
  outline;
  minBoardEdgeClearance;
  constructor(e36) {
    super(), this.inputRoute = e36.inputRoute, this.otherHdRoutes = e36.otherHdRoutes, this.obstacles = e36.obstacles, this.connMap = e36.connMap, this.colorMap = e36.colorMap, this.outline = e36.outline, this.minBoardEdgeClearance = e36.minBoardEdgeClearance ?? 0.2, this.newRoute = [this.inputRoute.route[0]], this.newVias = [];
  }
  getConstructorParams() {
    return { inputRoute: this.inputRoute, otherHdRoutes: this.otherHdRoutes, obstacles: this.obstacles, connMap: this.connMap.netMap, colorMap: this.colorMap, outline: this.outline, minBoardEdgeClearance: this.minBoardEdgeClearance };
  }
  get simplifiedRoute() {
    return { connectionName: this.inputRoute.connectionName, rootConnectionName: this.inputRoute.rootConnectionName, startPcbPortId: this.inputRoute.startPcbPortId, endPcbPortId: this.inputRoute.endPcbPortId, traceThickness: this.inputRoute.traceThickness, viaDiameter: this.inputRoute.viaDiameter, route: this.newRoute, vias: this.newVias, jumpers: this.inputRoute.jumpers };
  }
  isValidPath(e36) {
    throw new Error("Not implemented");
  }
  _step() {
    throw new Error("Not implemented");
  }
  getVisualsForNewRouteAndObstacles() {
    const e36 = { lines: [], points: [], circles: [], rects: [], coordinateSystem: "cartesian", title: "Simplified Path Solver" };
    for (let t2 = 0;t2 < this.inputRoute.route.length - 1; t2++)
      e36.lines.push({ points: [{ x: this.inputRoute.route[t2].x, y: this.inputRoute.route[t2].y }, { x: this.inputRoute.route[t2 + 1].x, y: this.inputRoute.route[t2 + 1].y }], strokeColor: "rgba(255, 0, 0, 0.8)", strokeDash: this.inputRoute.route[t2].z === 1 ? "5, 5" : undefined, layer: `z${this.inputRoute.route[t2].z.toString()}` });
    for (let t2 = 0;t2 < this.newRoute.length; t2++)
      t2 < this.newRoute.length - 1 && e36.lines.push({ points: [{ x: this.newRoute[t2].x, y: this.newRoute[t2].y }, { x: this.newRoute[t2 + 1].x, y: this.newRoute[t2 + 1].y }], strokeWidth: 0.15, strokeColor: "rgba(0, 255, 0, 0.8)", strokeDash: this.newRoute[t2].z === 1 ? [0.4, 0.4] : undefined, layer: `z${this.newRoute[t2].z.toString()}` }), e36.points.push({ x: this.newRoute[t2].x, y: this.newRoute[t2].y, color: "rgba(0, 255, 0, 0.8)", label: `z: ${this.newRoute[t2].z}`, layer: `z${this.newRoute[t2].z.toString()}` });
    for (const t2 of this.newVias)
      e36.circles.push({ center: t2, radius: this.inputRoute.viaDiameter / 2, fill: "rgba(0, 0, 255, 0.5)" });
    for (const t2 of this.obstacles)
      e36.rects.push({ center: t2.center, width: t2.width, height: t2.height, fill: t2.layers?.includes("top") ? "rgba(255, 0, 0, 0.3)" : t2.layers?.includes("bottom") ? "rgba(0, 0, 255, 0.3)" : "rgba(128, 128, 128, 0.3)" });
    for (const t2 of this.otherHdRoutes)
      for (let n2 = 0;n2 < t2.route.length - 1; n2++)
        e36.lines.push({ points: [{ x: t2.route[n2].x, y: t2.route[n2].y }, { x: t2.route[n2 + 1].x, y: t2.route[n2 + 1].y }], strokeWidth: 0.15, strokeColor: t2.route[n2].z === 0 ? "rgba(255, 0, 255, 0.5)" : t2.route[n2].z === 1 ? "rgba(128, 0, 128, 0.5)" : "rgba(0, 0, 255, 0.5)", layer: `z${t2.route[n2].z.toString()}` });
    if ("filteredObstaclePathSegments" in this) {
      const t2 = this.filteredObstaclePathSegments;
      for (const [n2, o3] of t2)
        e36.lines.push({ points: [n2, o3] });
    }
    return e36;
  }
};
var hF = (e36) => ({ minX: Math.min(e36[0].x, e36[1].x), maxX: Math.max(e36[0].x, e36[1].x), minY: Math.min(e36[0].y, e36[1].y), maxY: Math.max(e36[0].y, e36[1].y) });
var dF = class {
  constructor(e36, t2 = 0.4) {
    this.segments = e36, this.buckets = new Map, this.SEGMENT_MARGIN = t2;
    const n2 = new Map;
    for (const t3 of e36) {
      const e37 = this.getSegmentKey(t3);
      if (n2.has(e37))
        continue;
      n2.set(e37, t3);
      const o3 = hF(t3), i3 = Math.floor(o3.minX / this.CELL_SIZE), r3 = Math.floor(o3.maxX / this.CELL_SIZE), s2 = Math.floor(o3.minY / this.CELL_SIZE), a3 = Math.floor(o3.maxY / this.CELL_SIZE);
      for (let n3 = i3;n3 <= r3; n3++)
        for (let o4 = s2;o4 <= a3; o4++) {
          const i4 = `${n3}x${o4}`, r4 = this.buckets.get(i4), s3 = [t3[0], t3[1], e37];
          r4 ? r4.push(s3) : this.buckets.set(i4, [s3]);
        }
    }
  }
  buckets;
  CELL_SIZE = 0.4;
  SEGMENT_MARGIN;
  getBucketKey(e36, t2) {
    return `${Math.floor(e36 / this.CELL_SIZE)}x${Math.floor(t2 / this.CELL_SIZE)}`;
  }
  getSegmentKey(e36) {
    return `${e36[0].x}-${e36[0].y}-${e36[0].z}-${e36[1].x}-${e36[1].y}-${e36[1].z}`;
  }
  getSegmentsThatCouldIntersect(e36, t2) {
    const n2 = [], o3 = new Set, i3 = Math.min(e36.x, t2.x) - this.SEGMENT_MARGIN, r3 = Math.min(e36.y, t2.y) - this.SEGMENT_MARGIN, s2 = Math.max(e36.x, t2.x) + this.SEGMENT_MARGIN, a3 = Math.max(e36.y, t2.y) + this.SEGMENT_MARGIN, c3 = Math.floor(i3 / this.CELL_SIZE), l3 = Math.floor(s2 / this.CELL_SIZE), h2 = Math.floor(r3 / this.CELL_SIZE), d2 = Math.floor(a3 / this.CELL_SIZE);
    for (let e37 = c3;e37 <= l3; e37++)
      for (let t3 = h2;t3 <= d2; t3++) {
        const i4 = `${e37}x${t3}`, r4 = this.buckets.get(i4);
        if (r4)
          for (const e38 of r4) {
            const t4 = e38[2];
            o3.has(t4) || (o3.add(t4), n2.push(e38));
          }
      }
    return n2;
  }
};
var uF = class extends lF {
  pathSegments = [];
  totalPathLength = 0;
  headDistanceAlongPath = 0;
  tailDistanceAlongPath = 0;
  minStepSize = 0.25;
  lastValidPath = null;
  lastValidPathHeadDistance = 0;
  STEP_SIZE_REDUCTION_FACTOR = 0.25;
  maxStepSize = 4;
  currentStepSize = this.maxStepSize;
  lastHeadMoveDistance = 0;
  cachedValidPathSegments;
  filteredObstacles = [];
  filteredObstaclePathSegments = [];
  traceThicknessByObstacleSegmentId = new Map;
  filteredVias = [];
  filteredJumperPads = [];
  jumperPadPointIndices = new Set;
  segmentTree;
  OBSTACLE_MARGIN = 0.1;
  TRACE_THICKNESS = 0.15;
  useTraceWidthAwareClearance = false;
  clearanceTraceThickness = this.TRACE_THICKNESS;
  TAIL_JUMP_RATIO = 0.8;
  isSameNetRoute(e36) {
    const t2 = [this.inputRoute.connectionName, this.inputRoute.rootConnectionName].filter((e37) => e37 !== undefined), n2 = [e36.connectionName, e36.rootConnectionName].filter((e37) => e37 !== undefined);
    return t2.some((e37) => n2.some((t3) => e37 === t3 || this.connMap.areIdsConnected(e37, t3)));
  }
  constructor(e36) {
    if (super(e36), this.cachedValidPathSegments = new Set, this.useTraceWidthAwareClearance = e36.useTraceWidthAwareClearance ?? false, this.clearanceTraceThickness = this.useTraceWidthAwareClearance ? this.inputRoute.traceThickness : this.TRACE_THICKNESS, this.inputRoute.route.length <= 1)
      return this.newRoute = [...this.inputRoute.route], void (this.solved = true);
    const t2 = this.inputRoute.route.reduce((e37, t3) => (e37.minX = Math.min(e37.minX, t3.x), e37.maxX = Math.max(e37.maxX, t3.x), e37.minY = Math.min(e37.minY, t3.y), e37.maxY = Math.max(e37.maxY, t3.y), e37), { minX: 1 / 0, maxX: -1 / 0, minY: 1 / 0, maxY: -1 / 0 }), n2 = this.useTraceWidthAwareClearance ? Math.max(0, ...this.otherHdRoutes.flatMap((e37) => [e37.traceThickness, ...e37.route.map((t3) => t3.traceThickness ?? e37.traceThickness)])) : this.TRACE_THICKNESS, o3 = this.useTraceWidthAwareClearance ? this.OBSTACLE_MARGIN + this.clearanceTraceThickness / 2 + n2 / 2 : this.OBSTACLE_MARGIN + this.TRACE_THICKNESS, i3 = { center: { x: (t2.minX + t2.maxX) / 2, y: (t2.minY + t2.maxY) / 2 }, width: t2.maxX - t2.minX, height: t2.maxY - t2.minY }, r3 = this.OBSTACLE_MARGIN + this.clearanceTraceThickness / 2, s2 = e36.geometryQuery ? e36.geometryQuery.index.getCandidateObstacles({ minX: i3.center.x - i3.width / 2, minY: i3.center.y - i3.height / 2, maxX: i3.center.x + i3.width / 2, maxY: i3.center.y + i3.height / 2 }, r3) : this.obstacles, a3 = e36.geometryQuery ? e36.geometryQuery.index.getCandidateRoutes(t2, Math.max(o3, r3), e36.geometryQuery.routeIndex) : this.otherHdRoutes;
    this.filteredObstacles = s2.filter((e37) => !e37.connectedTo.some((e38) => this.connMap.areIdsConnected(this.inputRoute.connectionName, e38))).filter((e37) => {
      if (e37.connectedTo.some((e38) => this.connMap.areIdsConnected(this.inputRoute.connectionName, e38)))
        return false;
      return function(e38, t3) {
        const n3 = Pe(e38), o4 = Pe(t3), i4 = Math.max(n3.minX - o4.maxX, o4.minX - n3.maxX, 0), r4 = Math.max(n3.minY - o4.maxY, o4.minY - n3.maxY, 0);
        return Math.hypot(i4, r4);
      }(i3, e37) < this.OBSTACLE_MARGIN + this.clearanceTraceThickness / 2;
    }), this.filteredObstaclePathSegments = a3.flatMap((e37) => {
      if (this.isSameNetRoute(e37))
        return [];
      const n3 = e37.route, i4 = [];
      for (let r4 = 0;r4 < n3.length - 1; r4++) {
        const s3 = n3[r4], a4 = n3[r4 + 1];
        if (Ne(s3, a4, t2) <= o3) {
          i4.push([s3, a4]);
          const t3 = `${s3.x}-${s3.y}-${s3.z}-${a4.x}-${a4.y}-${a4.z}`;
          if (this.useTraceWidthAwareClearance) {
            const n4 = Math.max(s3.traceThickness ?? e37.traceThickness, a4.traceThickness ?? e37.traceThickness);
            this.traceThicknessByObstacleSegmentId.set(t3, Math.max(this.traceThicknessByObstacleSegmentId.get(t3) ?? 0, n4));
          }
        }
      }
      return i4;
    }), this.segmentTree = this.useTraceWidthAwareClearance ? new dF(this.filteredObstaclePathSegments, o3) : new dF(this.filteredObstaclePathSegments), this.filteredVias = a3.flatMap((e37) => {
      if (this.isSameNetRoute(e37))
        return [];
      const n3 = e37.vias, o4 = [];
      for (const i4 of n3) {
        const n4 = this.OBSTACLE_MARGIN + this.clearanceTraceThickness / 2 + e37.viaDiameter / 2, r4 = i4.x - n4, s3 = i4.x + n4, a4 = i4.y - n4, c4 = i4.y + n4;
        r4 <= t2.maxX && s3 >= t2.minX && a4 <= t2.maxY && c4 >= t2.minY && o4.push({ ...i4, diameter: e37.viaDiameter });
      }
      return o4;
    });
    const c3 = (e37, n3) => {
      const o4 = [];
      for (const i4 of e37) {
        const e38 = tF[i4.footprint] ?? tF["0603"], r4 = i4.end.x - i4.start.x, s3 = i4.end.y - i4.start.y, a4 = Math.abs(r4) > Math.abs(s3), c4 = a4 ? e38.padLength : e38.padWidth, l3 = a4 ? e38.padWidth : e38.padLength, h2 = this.OBSTACLE_MARGIN + this.clearanceTraceThickness / 2;
        i4.start.x - c4 / 2 - h2 <= t2.maxX && i4.start.x + c4 / 2 + h2 >= t2.minX && i4.start.y - l3 / 2 - h2 <= t2.maxY && i4.start.y + l3 / 2 + h2 >= t2.minY && o4.push({ center: i4.start, width: c4, height: l3, connectionName: n3 }), i4.end.x - c4 / 2 - h2 <= t2.maxX && i4.end.x + c4 / 2 + h2 >= t2.minX && i4.end.y - l3 / 2 - h2 <= t2.maxY && i4.end.y + l3 / 2 + h2 >= t2.minY && o4.push({ center: i4.end, width: c4, height: l3, connectionName: n3 });
      }
      return o4;
    };
    if (this.filteredJumperPads = a3.flatMap((e37) => this.isSameNetRoute(e37) ? [] : c3(e37.jumpers ?? [], e37.connectionName)), this.inputRoute.jumpers && this.inputRoute.jumpers.length > 0) {
      this.filteredJumperPads.push(...c3(this.inputRoute.jumpers, this.inputRoute.connectionName));
      for (const e37 of this.inputRoute.jumpers)
        for (let t3 = 0;t3 < this.inputRoute.route.length; t3++) {
          const n3 = this.inputRoute.route[t3];
          (Math.abs(n3.x - e37.start.x) < 0.01 && Math.abs(n3.y - e37.start.y) < 0.01 || Math.abs(n3.x - e37.end.x) < 0.01 && Math.abs(n3.y - e37.end.y) < 0.01) && this.jumperPadPointIndices.add(t3);
        }
    }
    this.computePathSegments(), this.MAX_ITERATIONS = Math.max(this.MAX_ITERATIONS, 6 * (Math.ceil(this.totalPathLength / this.minStepSize) + this.pathSegments.length));
  }
  computePathSegments() {
    let e36 = 0;
    for (let t2 = 0;t2 < this.inputRoute.route.length - 1; t2++) {
      const n2 = this.inputRoute.route[t2], o3 = this.inputRoute.route[t2 + 1], i3 = Math.sqrt((o3.x - n2.x) ** 2 + (o3.y - n2.y) ** 2) + t2 / 1e4;
      this.pathSegments.push({ start: n2, end: o3, length: i3, startDistance: e36, endDistance: e36 + i3 }), e36 += i3;
    }
    this.totalPathLength = e36;
  }
  arePointsEqual(e36, t2) {
    return e36.x === t2.x && e36.y === t2.y && e36.z === t2.z;
  }
  getPointAtDistance(e36) {
    e36 = Math.max(0, Math.min(e36, this.totalPathLength));
    const t2 = this.pathSegments.find((t3) => e36 >= t3.startDistance && e36 <= t3.endDistance);
    if (!t2)
      return this.inputRoute.route[this.inputRoute.route.length - 1];
    const n2 = (e36 - t2.startDistance) / t2.length;
    return { x: t2.start.x + n2 * (t2.end.x - t2.start.x), y: t2.start.y + n2 * (t2.end.y - t2.start.y), z: n2 < 0.5 ? t2.start.z : t2.end.z };
  }
  getNearestIndexForDistance(e36) {
    if (e36 <= 0)
      return 0;
    if (e36 >= this.totalPathLength)
      return this.inputRoute.route.length - 1;
    const t2 = this.pathSegments.findIndex((t3) => e36 >= t3.startDistance && e36 <= t3.endDistance);
    if (t2 === -1)
      return 0;
    const n2 = this.pathSegments[t2], o3 = (n2.startDistance + n2.endDistance) / 2;
    return e36 > o3 ? t2 + 1 : t2;
  }
  isValidPathSegment(e36, t2) {
    for (const n3 of this.filteredObstacles) {
      if (!n3.__zLayers?.includes(e36.z))
        continue;
      if (Re(e36, t2, n3) < this.OBSTACLE_MARGIN + this.clearanceTraceThickness / 2)
        return false;
    }
    const n2 = this.segmentTree.getSegmentsThatCouldIntersect(e36, t2);
    for (const [o3, i3, r3] of n2)
      if (o3.z === e36.z && i3.z === e36.z) {
        const n3 = jB({ x: e36.x, y: e36.y }, { x: t2.x, y: t2.y }, { x: o3.x, y: o3.y }, { x: i3.x, y: i3.y });
        if (!this.useTraceWidthAwareClearance) {
          if (n3 < this.OBSTACLE_MARGIN + this.TRACE_THICKNESS)
            return false;
          continue;
        }
        const s2 = this.traceThicknessByObstacleSegmentId.get(r3);
        if (s2 === undefined)
          throw new Error(`Missing trace thickness for segment "${r3}"`);
        if (n3 < this.OBSTACLE_MARGIN + this.clearanceTraceThickness / 2 + s2 / 2)
          return false;
      }
    for (const n3 of this.filteredVias)
      if (pe(n3, e36, t2) < this.OBSTACLE_MARGIN + n3.diameter / 2 + this.clearanceTraceThickness / 2)
        return false;
    for (const n3 of this.filteredJumperPads) {
      if (Re(e36, t2, n3) < this.OBSTACLE_MARGIN + this.clearanceTraceThickness / 2)
        return false;
    }
    if (this.outline && this.outline.length >= 3) {
      if (UB({ start: { x: e36.x, y: e36.y }, end: { x: t2.x, y: t2.y }, polygon: this.outline, margin: this.minBoardEdgeClearance + this.inputRoute.traceThickness / 2 }))
        return false;
    }
    return true;
  }
  isValidPath(e36) {
    if (e36.length < 2)
      return true;
    for (let t2 = 0;t2 < e36.length - 1; t2++)
      if (e36[t2].z !== e36[t2 + 1].z)
        return false;
    for (let t2 = 0;t2 < e36.length - 1; t2++)
      if (!this.isValidPathSegment(e36[t2], e36[t2 + 1]))
        return false;
    return true;
  }
  find45DegreePath(e36, t2) {
    if (this.arePointsEqual(e36, t2))
      return [e36];
    if (e36.z !== t2.z)
      return null;
    const n2 = BB({ x: e36.x, y: e36.y }, { x: t2.x, y: t2.y });
    for (const t3 of n2) {
      const n3 = t3.map((t4) => ({ x: t4.x, y: t4.y, z: e36.z }));
      if (this.isValidPath(n3))
        return n3;
    }
    return null;
  }
  addPathToResult(e36) {
    if (e36.length !== 0) {
      for (let t2 = 0;t2 < e36.length; t2++)
        t2 === 0 && this.newRoute.length > 0 && this.arePointsEqual(this.newRoute[this.newRoute.length - 1], e36[t2]) || this.newRoute.push(e36[t2]);
      this.currentStepSize = this.maxStepSize;
    }
  }
  appendOriginalRouteSlice(e36, t2) {
    const n2 = this.pathSegments.findIndex((t3) => e36 >= t3.startDistance && e36 <= t3.endDistance);
    if (n2 === -1)
      throw new Error(`Could not find path segment containing distance ${e36}`);
    for (let e37 = n2 + 1;e37 <= t2 && e37 < this.inputRoute.route.length; e37++) {
      const t3 = this.inputRoute.route[e37], n3 = this.newRoute[this.newRoute.length - 1];
      n3 && this.arePointsEqual(n3, t3) || this.newRoute.push({ ...t3 });
    }
  }
  moveHead(e36) {
    this.lastHeadMoveDistance = e36, this.headDistanceAlongPath = Math.min(this.headDistanceAlongPath + e36, this.totalPathLength);
  }
  stepBackAndReduceStepSize() {
    this.headDistanceAlongPath = Math.max(this.tailDistanceAlongPath, this.headDistanceAlongPath - this.lastHeadMoveDistance), this.currentStepSize = Math.max(this.minStepSize, this.currentStepSize * this.STEP_SIZE_REDUCTION_FACTOR);
  }
  _step() {
    const e36 = this.tailDistanceAlongPath >= this.totalPathLength, t2 = this.headDistanceAlongPath >= this.totalPathLength;
    if (e36) {
      const e37 = this.inputRoute.route[this.inputRoute.route.length - 1];
      return this.newRoute.length !== 0 && this.arePointsEqual(this.newRoute[this.newRoute.length - 1], e37) || this.newRoute.push(e37), void (this.solved = true);
    }
    if (t2) {
      const e37 = this.getPointAtDistance(this.tailDistanceAlongPath), t3 = this.inputRoute.route[this.inputRoute.route.length - 1], n3 = this.find45DegreePath(e37, t3);
      if (n3)
        return this.addPathToResult(n3), void (this.solved = true);
      const o4 = this.lastValidPath ? this.lastValidPathHeadDistance : this.tailDistanceAlongPath;
      this.lastValidPath && (this.addPathToResult(this.lastValidPath), this.lastValidPath = null);
      this.getNearestIndexForDistance(o4);
      return this.appendOriginalRouteSlice(o4, this.inputRoute.route.length - 1), this.tailDistanceAlongPath = this.totalPathLength, this.headDistanceAlongPath = this.totalPathLength, void (this.solved = true);
    }
    this.moveHead(this.currentStepSize);
    const n2 = this.getPointAtDistance(this.tailDistanceAlongPath), o3 = this.getPointAtDistance(this.headDistanceAlongPath), i3 = this.getNearestIndexForDistance(this.tailDistanceAlongPath), r3 = this.getNearestIndexForDistance(this.headDistanceAlongPath);
    let s2 = false, a3 = -1;
    for (let e37 = i3;e37 < r3; e37++)
      if (e37 + 1 < this.inputRoute.route.length && this.inputRoute.route[e37].z !== this.inputRoute.route[e37 + 1].z) {
        s2 = true;
        const t3 = e37;
        a3 = this.pathSegments[t3].startDistance;
        break;
      }
    if (s2 && this.lastHeadMoveDistance > this.minStepSize)
      return void this.stepBackAndReduceStepSize();
    let c3 = false, l3 = -1, h2 = -1;
    for (let e37 = i3 + 1;e37 <= r3; e37++)
      if (this.jumperPadPointIndices.has(e37)) {
        c3 = true, l3 = e37, h2 = e37 > 0 && e37 - 1 < this.pathSegments.length ? this.pathSegments[e37 - 1].endDistance : this.pathSegments[0]?.startDistance ?? 0;
        break;
      }
    if (c3 && this.lastHeadMoveDistance > this.minStepSize)
      return void this.stepBackAndReduceStepSize();
    if (c3 && l3 >= 0) {
      const e37 = this.inputRoute.route[l3];
      this.lastValidPath && (this.addPathToResult(this.lastValidPath), this.lastValidPath = null);
      const t3 = this.newRoute[this.newRoute.length - 1];
      return t3 && t3.x === e37.x && t3.y === e37.y || this.newRoute.push({ x: e37.x, y: e37.y, z: e37.z }), this.currentStepSize = this.maxStepSize, this.tailDistanceAlongPath = h2, this.headDistanceAlongPath = this.tailDistanceAlongPath, this.lastValidPath = null, void (this.lastValidPathHeadDistance = this.tailDistanceAlongPath);
    }
    if (s2 && a3 > 0) {
      const e37 = this.lastValidPath ? this.lastValidPathHeadDistance : this.tailDistanceAlongPath, t3 = this.getNearestIndexForDistance(a3) + 1, n3 = this.inputRoute.route[t3], o4 = { x: n3.x, y: n3.y };
      this.lastValidPath && (this.addPathToResult(this.lastValidPath), this.lastValidPath = null);
      const i4 = this.newRoute[this.newRoute.length - 1], r4 = { x: o4.x, y: o4.y, z: i4.z };
      if (!this.arePointsEqual(i4, r4)) {
        const n4 = this.find45DegreePath(i4, r4);
        n4 ? this.addPathToResult(n4) : this.appendOriginalRouteSlice(e37, t3 - 1);
      }
      this.newVias.push(o4), this.newRoute.push({ x: o4.x, y: o4.y, z: n3.z }), this.currentStepSize = this.maxStepSize;
      const s3 = this.pathSegments.findIndex((e38) => e38.start === n3);
      if (s3 !== -1)
        this.tailDistanceAlongPath = this.pathSegments[s3].startDistance, this.headDistanceAlongPath = this.tailDistanceAlongPath, this.lastValidPath = null, this.lastValidPathHeadDistance = this.tailDistanceAlongPath;
      else if (t3 < this.inputRoute.route.length) {
        if (t3 === this.inputRoute.route.length - 1)
          return void (this.solved = true);
        console.warn("Fallback used for tailDistanceAlongPath after layer change");
        const e38 = this.pathSegments.find((e39) => e39.start === this.inputRoute.route[t3]);
        e38 ? (this.tailDistanceAlongPath = e38.startDistance, this.headDistanceAlongPath = this.tailDistanceAlongPath, this.lastValidPath = null, this.lastValidPathHeadDistance = this.tailDistanceAlongPath) : (console.error(`[${this.inputRoute.connectionName}] Could not find segment start after layer change. Path might be incomplete.
            Index sought: ${t3}, Point: (${this.inputRoute.route[t3].x.toFixed(3)}, ${this.inputRoute.route[t3].y.toFixed(3)}, z=${this.inputRoute.route[t3].z})
            Route Length: ${this.inputRoute.route.length}, Path Segments: ${this.pathSegments.length}`), this.solved = true);
      } else
        console.warn("Layer change occurred at the end of the path."), this.solved = true;
      return;
    }
    const d2 = this.find45DegreePath(n2, o3);
    if (!d2 && this.lastHeadMoveDistance > this.minStepSize)
      this.stepBackAndReduceStepSize();
    else {
      if (!d2 && !this.lastValidPath) {
        const e37 = this.getPointAtDistance(this.tailDistanceAlongPath);
        this.tailDistanceAlongPath += this.minStepSize, this.moveHead(this.minStepSize);
        let t3 = this.getNearestIndexForDistance(this.tailDistanceAlongPath);
        for (let e38 = i3;e38 < t3; e38++)
          if (this.inputRoute.route[e38].z !== this.inputRoute.route[e38 + 1].z) {
            t3 = e38;
            break;
          }
        const n3 = this.inputRoute.route[t3], o4 = this.inputRoute.route[this.inputRoute.route.length - 1];
        return void (this.arePointsEqual(e37, n3) || this.arePointsEqual(n3, o4) || (this.newRoute.push(n3), this.tailDistanceAlongPath = t3 === 0 ? 0 : this.pathSegments[t3 - 1].endDistance));
      }
      if (d2)
        return this.lastValidPath = d2, void (this.lastValidPathHeadDistance = this.headDistanceAlongPath);
      this.lastValidPath && (this.addPathToResult(this.lastValidPath), this.lastValidPath = null, this.tailDistanceAlongPath = this.lastValidPathHeadDistance, this.moveHead(this.minStepSize));
    }
  }
  visualize() {
    const e36 = this.getVisualsForNewRouteAndObstacles(), t2 = this.getPointAtDistance(this.tailDistanceAlongPath), n2 = this.getPointAtDistance(this.headDistanceAlongPath);
    e36.points.push({ x: t2.x, y: t2.y, color: "yellow", label: ["Tail", `z: ${t2.z}`].join(`
`) }), e36.points.push({ x: n2.x, y: n2.y, color: "orange", label: ["Head", `z: ${n2.z}`].join(`
`) });
    const o3 = this.getPointAtDistance(this.headDistanceAlongPath + this.currentStepSize);
    e36.points.push({ x: o3.x, y: o3.y, color: "red", label: ["Tentative Head", `z: ${o3.z}`].join(`
`) });
    let i3 = 0;
    for (;i3 < this.totalPathLength; ) {
      const t3 = this.getPointAtDistance(i3);
      e36.circles.push({ center: { x: t3.x, y: t3.y }, radius: 0.05, fill: "rgba(100, 100, 100, 0.5)" }), i3 += this.totalPathLength / 20;
    }
    if (this.lastValidPath && this.lastValidPath.length > 1)
      for (let t3 = 0;t3 < this.lastValidPath.length - 1; t3++)
        e36.lines.push({ points: [{ x: this.lastValidPath[t3].x, y: this.lastValidPath[t3].y }, { x: this.lastValidPath[t3 + 1].x, y: this.lastValidPath[t3 + 1].y }], strokeColor: "rgba(0, 255, 255, 0.9)", strokeDash: "3, 3" });
    return e36;
  }
};
var pF = class extends uF {
  vertexIndex = 0;
  constructor(e36) {
    super(e36), this.newRoute = this.inputRoute.route.slice(0, 1).map((e37) => ({ ...e37 })), this.newVias = this.inputRoute.vias.map((e37) => ({ ...e37 }));
  }
  getSolverName() {
    return "VertexShortcutPathSolver";
  }
  _step() {
    const e36 = this.inputRoute.route, t2 = e36[this.vertexIndex];
    if (this.vertexIndex >= e36.length - 1)
      return void (this.solved = true);
    let n2 = this.vertexIndex + 1;
    const o3 = [0];
    for (let t3 = this.vertexIndex;t3 < e36.length - 1; t3++) {
      const i3 = e36[t3], r3 = e36[t3 + 1];
      if (i3.z !== r3.z || i3.toNextSegmentType || i3.traceThickness !== r3.traceThickness || i3.traceThickness !== undefined && i3.traceThickness !== this.inputRoute.traceThickness || i3.insideJumperPad || r3.insideJumperPad)
        break;
      if (o3.push(o3.at(-1) + Math.hypot(r3.x - i3.x, r3.y - i3.y)), n2 = t3 + 1, r3.pcb_port_id || this.jumperPadPointIndices.has(n2))
        break;
    }
    for (let i3 = n2;i3 > this.vertexIndex + 1; i3--) {
      const n3 = e36[i3], r3 = o3[i3 - this.vertexIndex];
      for (const e37 of BB(t2, n3)) {
        const o4 = e37.filter((t3, n4) => n4 === 0 || t3.x !== e37[n4 - 1].x || t3.y !== e37[n4 - 1].y).map((e38) => ({ ...e38, z: t2.z, traceThickness: t2.traceThickness })), s2 = o4.reduce((e38, t3, n4) => n4 === 0 ? e38 : e38 + Math.hypot(t3.x - o4[n4 - 1].x, t3.y - o4[n4 - 1].y), 0);
        if (!(o4.length < 2 || s2 > r3 + 0.000000001 || s2 >= r3 - 0.000000001 && o4.length >= i3 - this.vertexIndex + 1) && this.isValidPath(o4))
          return o4[o4.length - 1] = { ...n3 }, this.newRoute.push(...o4.slice(1)), void (this.vertexIndex = i3);
      }
    }
    this.vertexIndex++, this.newRoute.push({ ...e36[this.vertexIndex] });
  }
};
var mF = new Float64Array(1);
var gF = new BigUint64Array(mF.buffer);
function fF(e36, t2) {
  return Number.isFinite(e36) ? e36 === 0 ? t2 ? Number.MIN_VALUE : -Number.MIN_VALUE : (mF[0] = e36, gF[0] += e36 > 0 === t2 ? 1n : -1n, mF[0]) : e36;
}
function _F(e36, t2, n2 = t2) {
  const o3 = fF(t2, true), i3 = fF(n2, true);
  return { minX: fF(fF(e36.minX, false) - o3, false), minY: fF(fF(e36.minY, false) - i3, false), maxX: fF(fF(e36.maxX, true) + o3, true), maxY: fF(fF(e36.maxY, true) + i3, true) };
}
function yF(e36, t2, n2) {
  const o3 = { minX: 1 / 0, minY: 1 / 0, maxX: -1 / 0, maxY: -1 / 0 };
  for (const t3 of e36.route)
    o3.minX = Math.min(o3.minX, t3.x), o3.minY = Math.min(o3.minY, t3.y), o3.maxX = Math.max(o3.maxX, t3.x), o3.maxY = Math.max(o3.maxY, t3.y);
  for (const t3 of e36.vias) {
    const n3 = _F({ minX: t3.x, minY: t3.y, maxX: t3.x, maxY: t3.y }, Math.abs(e36.viaDiameter / 2));
    o3.minX = Math.min(o3.minX, n3.minX), o3.minY = Math.min(o3.minY, n3.minY), o3.maxX = Math.max(o3.maxX, n3.maxX), o3.maxY = Math.max(o3.maxY, n3.maxY);
  }
  for (const t3 of e36.jumpers ?? []) {
    const e37 = tF[t3.footprint] ?? tF["0603"], n3 = Math.abs(t3.end.x - t3.start.x) > Math.abs(t3.end.y - t3.start.y), i3 = (n3 ? e37.padLength : e37.padWidth) / 2, r3 = (n3 ? e37.padWidth : e37.padLength) / 2;
    for (const e38 of [t3.start, t3.end]) {
      const t4 = _F({ minX: e38.x, minY: e38.y, maxX: e38.x, maxY: e38.y }, i3, r3);
      o3.minX = Math.min(o3.minX, t4.minX), o3.minY = Math.min(o3.minY, t4.minY), o3.maxX = Math.max(o3.maxX, t4.maxX), o3.maxY = Math.max(o3.maxY, t4.maxY);
    }
  }
  if (e36.route.length !== 0 || e36.vias.length !== 0 || e36.jumpers?.length)
    return [o3.minX, o3.minY, o3.maxX, o3.maxY].every(Number.isFinite) ? { ..._F(o3, 0), route: e36, routeIndex: t2, immutable: n2 } : { minX: -1 / 0, minY: -1 / 0, maxX: 1 / 0, maxY: 1 / 0, route: e36, routeIndex: t2, immutable: n2 };
}
var bF = class {
  constructor(e36, t2, n2) {
    this.obstacles = n2, this.mutableRoutes = e36.map((e37, t3) => yF(e37, t3, false));
    const o3 = t2.map((e37, t3) => yF(e37, t3, true)).concat(this.mutableRoutes).filter((e37) => e37 !== undefined);
    this.routeIndex.load(o3);
    const i3 = n2.map((e37, t3) => {
      const n3 = { minX: e37.center.x - e37.width / 2, minY: e37.center.y - e37.height / 2, maxX: e37.center.x + e37.width / 2, maxY: e37.center.y + e37.height / 2 };
      return Object.values(n3).every(Number.isFinite) ? this.indexedObstacleIds.push(t3) : this.unindexedObstacleIds.push(t3), n3;
    });
    if (this.indexedObstacleIds.length > 0) {
      this.obstacleIndex = new MB(this.indexedObstacleIds.length);
      for (const e37 of this.indexedObstacleIds) {
        const t3 = i3[e37];
        this.obstacleIndex.add(t3.minX, t3.minY, t3.maxX, t3.maxY);
      }
      this.obstacleIndex.finish();
    }
  }
  routeIndex = new G;
  mutableRoutes;
  obstacleIndex;
  indexedObstacleIds = [];
  unindexedObstacleIds = [];
  getCandidateObstacles(e36, t2) {
    if (!Number.isFinite(t2) || !Object.values(e36).every(Number.isFinite))
      return [...this.obstacles];
    const n2 = _F(e36, Math.max(0, t2));
    return (this.obstacleIndex ? this.obstacleIndex.search(n2.minX, n2.minY, n2.maxX, n2.maxY).map((e37) => this.indexedObstacleIds[e37]) : []).concat(this.unindexedObstacleIds).sort((e37, t3) => e37 - t3).map((e37) => this.obstacles[e37]);
  }
  getCandidateRoutes(e36, t2, n2) {
    return (Number.isFinite(t2) && Object.values(e36).every(Number.isFinite) ? this.routeIndex.search(_F(e36, Math.max(0, t2))) : this.routeIndex.all()).filter((e37) => e37.immutable || e37.routeIndex !== n2).sort((e37, t3) => (e37.immutable ? 0 : e37.routeIndex > n2 ? 1 : 2) - (t3.immutable ? 0 : t3.routeIndex > n2 ? 1 : 2) || e37.routeIndex - t3.routeIndex).map((e37) => e37.route);
  }
  replaceRoute(e36, t2) {
    if (!Number.isInteger(e36) || e36 < 0 || e36 >= this.mutableRoutes.length)
      throw new Error(`Cannot replace path simplification route ${e36}`);
    const n2 = this.mutableRoutes[e36];
    n2 && this.routeIndex.remove(n2);
    const o3 = yF(t2, e36, false);
    this.mutableRoutes[e36] = o3, o3 && this.routeIndex.insert(o3);
  }
};
var xF = class extends SB {
  getSolverName() {
    return "MultiSimplifiedPathSolver";
  }
  simplifiedHdRoutes;
  currentUnsimplifiedHdRouteIndex = 0;
  activeSubSolver = null;
  unsimplifiedHdRoutes;
  otherHdRoutes;
  obstacles;
  connMap;
  colorMap;
  outline;
  minBoardEdgeClearance;
  defaultViaDiameter;
  useTraceWidthAwareClearance;
  enableVertexShortcuts;
  geometryIndex;
  constructor(e36) {
    super(), this.MAX_ITERATIONS = 1e8, this.unsimplifiedHdRoutes = e36.unsimplifiedHdRoutes, this.otherHdRoutes = e36.otherHdRoutes ?? [];
    const t2 = Math.max(2, ...[...e36.unsimplifiedHdRoutes, ...this.otherHdRoutes].flatMap((e37) => e37.route.map((e38) => e38.z + 1))) || 2;
    this.obstacles = sF(e36.obstacles, t2), this.connMap = e36.connMap || new cF({}), this.colorMap = e36.colorMap || {}, this.outline = e36.outline, this.minBoardEdgeClearance = e36.minBoardEdgeClearance ?? 0.2, this.defaultViaDiameter = e36.defaultViaDiameter ?? 0.3, this.useTraceWidthAwareClearance = e36.useTraceWidthAwareClearance ?? false, this.enableVertexShortcuts = e36.enableVertexShortcuts ?? false, this.geometryIndex = new bF(this.unsimplifiedHdRoutes, this.otherHdRoutes, this.obstacles), this.simplifiedHdRoutes = [];
  }
  _step() {
    const e36 = this.unsimplifiedHdRoutes[this.currentUnsimplifiedHdRouteIndex];
    if (!this.activeSubSolver)
      return e36 ? (this.activeSubSolver = new uF({ inputRoute: e36, otherHdRoutes: this.otherHdRoutes.concat(this.unsimplifiedHdRoutes.slice(this.currentUnsimplifiedHdRouteIndex + 1).concat(this.simplifiedHdRoutes)), obstacles: this.obstacles, connMap: this.connMap, colorMap: this.colorMap, outline: this.outline, minBoardEdgeClearance: this.minBoardEdgeClearance, useTraceWidthAwareClearance: this.useTraceWidthAwareClearance, geometryQuery: { index: this.geometryIndex, routeIndex: this.currentUnsimplifiedHdRouteIndex } }), void this.currentUnsimplifiedHdRouteIndex++) : void (this.solved = true);
    if (this.activeSubSolver.step(), this.activeSubSolver.failed)
      return this.failed = true, void (this.error = this.activeSubSolver.error);
    if (this.activeSubSolver.solved) {
      if (this.enableVertexShortcuts && !(this.activeSubSolver instanceof pF))
        return void (this.activeSubSolver = new pF({ inputRoute: this.activeSubSolver.simplifiedRoute, otherHdRoutes: this.activeSubSolver.otherHdRoutes, obstacles: this.obstacles, connMap: this.connMap, colorMap: this.colorMap, outline: this.outline, minBoardEdgeClearance: this.minBoardEdgeClearance, useTraceWidthAwareClearance: this.useTraceWidthAwareClearance, geometryQuery: { index: this.geometryIndex, routeIndex: this.currentUnsimplifiedHdRouteIndex - 1 } }));
      const e37 = this.activeSubSolver.simplifiedRoute;
      this.geometryIndex.replaceRoute(this.currentUnsimplifiedHdRouteIndex - 1, e37), this.simplifiedHdRoutes.push(e37), this.activeSubSolver = null;
    }
  }
  visualize() {
    if (this.activeSubSolver)
      return this.activeSubSolver.visualize();
    const e36 = { lines: [], points: [], circles: [], rects: [], coordinateSystem: "cartesian", title: "Multi Simplified Path Solver" };
    for (const t2 of this.unsimplifiedHdRoutes)
      if (!this.simplifiedHdRoutes.some((e37) => e37.connectionName === t2.connectionName)) {
        for (let n2 = 0;n2 < t2.route.length - 1; n2++)
          e36.lines.push({ points: [{ x: t2.route[n2].x, y: t2.route[n2].y }, { x: t2.route[n2 + 1].x, y: t2.route[n2 + 1].y }], strokeColor: t2.route[n2].z === 1 ? "rgba(0, 0, 255, 0.4)" : "rgba(255, 0, 0, 0.4)", strokeWidth: 0.15, strokeDash: t2.route[n2].z === 1 ? [0.5, 0.5] : undefined });
        for (const n2 of t2.vias || [])
          e36.circles.push({ center: n2, radius: (t2.viaDiameter ?? this.defaultViaDiameter) / 2, fill: "rgba(0, 0, 255, 0.4)" });
      }
    for (const t2 of this.simplifiedHdRoutes) {
      const n2 = this.colorMap?.[t2.connectionName] || "rgba(128, 128, 128, 0.8)";
      for (let o3 = 0;o3 < t2.route.length - 1; o3++)
        e36.lines.push({ points: [{ x: t2.route[o3].x, y: t2.route[o3].y }, { x: t2.route[o3 + 1].x, y: t2.route[o3 + 1].y }], strokeWidth: 0.15, strokeColor: n2, strokeDash: t2.route[o3].z === 1 ? [0.5, 0.5] : undefined, step: 1 });
      for (const n3 of t2.vias || [])
        e36.circles.push({ center: n3, radius: t2.viaDiameter / 2, fill: "rgba(0, 0, 255, 0.5)", step: 1 });
    }
    for (const t2 of this.unsimplifiedHdRoutes) {
      for (let n2 = 0;n2 < t2.route.length - 1; n2++)
        e36.lines.push({ points: [{ x: t2.route[n2].x, y: t2.route[n2].y }, { x: t2.route[n2 + 1].x, y: t2.route[n2 + 1].y }], strokeWidth: 0.15, strokeColor: "rgba(255, 0, 0, 0.2)", strokeDash: [0.5, 0.5], step: 0, layer: `z${t2.route[n2].z.toString()}` });
      for (const n2 of t2.vias)
        e36.circles.push({ center: { x: n2.x, y: n2.y }, radius: t2.viaDiameter / 2, fill: "rgba(255, 0, 0, 0.2)", step: 0 });
    }
    for (const t2 of this.obstacles)
      e36.rects.push({ center: t2.center, width: t2.width, height: t2.height, fill: t2.layers?.includes("top") ? "rgba(255, 0, 0, 0.3)" : t2.layers?.includes("bottom") ? "rgba(0, 0, 255, 0.3)" : "rgba(128, 128, 128, 0.3)" });
    if (this.currentUnsimplifiedHdRouteIndex < this.unsimplifiedHdRoutes.length) {
      const t2 = this.unsimplifiedHdRoutes[this.currentUnsimplifiedHdRouteIndex];
      t2.route.length > 0 && e36.circles.push({ center: { x: t2.route[0].x, y: t2.route[0].y }, radius: 0.2, fill: "yellow", label: "Current" });
    }
    return e36;
  }
};
var vF = (e36, t2) => {
  for (let n2 = 0;n2 < e36.route.length - 1; n2++) {
    const o3 = e36.route[n2], i3 = e36.route[n2 + 1];
    if (o3.z === i3.z || o3.x !== t2.x || o3.y !== t2.y || i3.x !== t2.x || i3.y !== t2.y)
      continue;
    let r3 = n2;
    for (;r3 > 0 && e36.route[r3 - 1].x === t2.x && e36.route[r3 - 1].y === t2.y; )
      r3--;
    let s2 = n2 + 1;
    for (;s2 < e36.route.length - 1 && e36.route[s2 + 1].x === t2.x && e36.route[s2 + 1].y === t2.y; )
      s2++;
    if (r3 === 0 || s2 === e36.route.length - 1)
      return true;
  }
  return false;
};
var IF = (e36, t2, n2) => n2?.get(t2.connectionName) ?? e36.idToNetMap[t2.connectionName] ?? (t2.rootConnectionName ? e36.idToNetMap[t2.rootConnectionName] : undefined);
var SF = (e36, t2, n2) => {
  for (const o3 of t2.connectedTo) {
    if (o3 === n2.net)
      return true;
    if (e36.idToNetMap[o3] === n2.net)
      return true;
    if (e36.areIdsConnected(o3, n2.net))
      return true;
  }
  return false;
};
var CF = (e36, t2, n2) => {
  const o3 = n2.mergedViaHdRoutes[e36.routeIndex];
  if (!o3)
    throw new Error(`SameNetViaMergerSolver could not find route for via at index ${e36.routeIndex}`);
  const i3 = new Set;
  for (let t3 = 1;t3 < o3.route.length; t3++) {
    const n3 = o3.route[t3 - 1], r3 = o3.route[t3];
    n3.z !== r3.z && (n3.x === e36.x && n3.y === e36.y && r3.x === e36.x && r3.y === e36.y && (i3.add(n3.z), i3.add(r3.z)));
  }
  if (i3.size === 0)
    throw new Error(`SameNetViaMergerSolver could not find transition layers for via at (${e36.x}, ${e36.y})`);
  for (const r3 of i3) {
    const i4 = o3.traceThickness, s2 = { x: e36.x, y: e36.y, z: r3 }, a3 = { x: t2.x, y: t2.y, z: r3 };
    if (s2.x === a3.x && s2.y === a3.y)
      continue;
    const c3 = n2.hdRouteSHI.getConflictingRoutesForSegment(s2, a3, i4 / 2);
    for (const { conflictingRoute: t3, distance: r4 } of c3) {
      if (t3.connectionName === o3.connectionName)
        continue;
      if (IF(n2.connMap, t3, n2.netByConnectionName) === e36.net)
        continue;
      if (r4 < i4 / 2 + t3.traceThickness / 2)
        return false;
    }
    const l3 = { centerX: (s2.x + a3.x) / 2, centerY: (s2.y + a3.y) / 2, width: Math.abs(s2.x - a3.x), height: Math.abs(s2.y - a3.y) }, h2 = i4 / 2 + 0.1, d2 = n2.obstacleSHI.searchArea(l3.centerX, l3.centerY, l3.width + 2 * h2, l3.height + 2 * h2);
    for (const t3 of d2) {
      if (!t3.__zLayers)
        throw new Error(`SameNetViaMergerSolver found obstacle without zLayers near via at (${e36.x}, ${e36.y})`);
      if (t3.__zLayers.includes(r3) && (!SF(n2.connMap, t3, e36) && Re(s2, a3, t3) < h2))
        return false;
    }
  }
  return true;
};
var PF = class extends SB {
  constructor(e36) {
    if (super(), this.input = e36, !e36.connMap)
      throw new Error("SameNetViaMergerSolver requires connMap");
    this.input = { ...e36, obstacles: sF(e36.obstacles, e36.layerCount) }, this.MAX_ITERATIONS = 1e6, this.inputHdRoutes = this.input.inputHdRoutes, this.mergedViaHdRoutes = structuredClone(this.inputHdRoutes);
    for (const e37 of this.mergedViaHdRoutes)
      this.dedupeRouteVias(e37);
    this.unprocessedRoutes = [...this.input.inputHdRoutes], this.colorMap = this.input.colorMap, this.outline = this.input.outline, this.obstacles = this.input.obstacles, this.obstacleSHI = new EB("flatbush", this.input.obstacles), this.hdRouteSHI = this.createHdRouteSpatialIndex(), this.vias = [], this.offendingVias = [], this.connMap = e36.connMap, this.netByConnectionName = e36.netByConnectionName, this.viasByNet = new Map, this.rebuildVias();
  }
  getSolverName() {
    return "SameNetViaMergerSolver";
  }
  inputHdRoutes;
  mergedViaHdRoutes;
  unprocessedRoutes;
  vias;
  offendingVias;
  currentViaRoutes = [];
  connMap;
  colorMap;
  outline;
  obstacles;
  viasByNet;
  netByConnectionName;
  obstacleSHI;
  hdRouteSHI;
  createHdRouteSpatialIndex() {
    return new zB([...this.mergedViaHdRoutes, ...this.input.otherHdRoutes ?? []]);
  }
  rebuildVias() {
    this.vias = [], this.viasByNet = new Map;
    const e36 = (e37, t2, n2) => {
      if (e37.vias.length === 0)
        return;
      const o3 = n2 ? ((e38, t3, n3) => {
        const o4 = IF(e38, t3, n3);
        if (!o4)
          throw new Error(`SameNetViaMergerSolver could not find net for route "${t3.connectionName}"`);
        return o4;
      })(this.connMap, e37, this.netByConnectionName) : IF(this.connMap, e37, this.netByConnectionName);
      if (o3)
        for (let i3 = 0;i3 < e37.vias.length; i3++) {
          const r3 = e37.vias[i3], s2 = [...new Set(e37.route.map((e38) => e38.z))];
          if (s2.length === 0)
            throw new Error(`SameNetViaMergerSolver found via on route "${e37.connectionName}" with no route points`);
          const a3 = { x: r3.x, y: r3.y, diameter: e37.viaDiameter, net: o3, layers: s2, routeIndex: t2, mutable: n2 && !(this.input.preserveRouteEndpoints && vF(e37, r3)) };
          this.vias.push(a3);
          const c3 = this.viasByNet.get(a3.net);
          c3 ? c3.push(a3) : this.viasByNet.set(a3.net, [a3]);
        }
    };
    for (let t2 = 0;t2 < this.mergedViaHdRoutes.length; t2++)
      e36(this.mergedViaHdRoutes[t2], t2, true);
    for (let t2 = 0;t2 < (this.input.otherHdRoutes?.length ?? 0); t2++)
      e36(this.input.otherHdRoutes[t2], this.mergedViaHdRoutes.length + t2, false);
  }
  getViaLocationKey(e36) {
    return [e36.net, e36.x, e36.y].join(":");
  }
  dedupeRouteVias(e36) {
    const t2 = new Set;
    e36.vias = e36.vias.filter((e37) => {
      const n2 = `${e37.x}:${e37.y}`;
      return !t2.has(n2) && (t2.add(n2), true);
    });
  }
  getOffendingViaGroupsBatch() {
    const e36 = [], t2 = new Set, n2 = [];
    for (const e37 of this.viasByNet.values()) {
      if (e37.length < 2)
        continue;
      const t3 = Math.max(0.000001, ...e37.map((e38) => e38.diameter)), o3 = new Map, i3 = new Map;
      for (let n3 = 0;n3 < e37.length; n3++) {
        const r3 = e37[n3], s2 = this.getViaLocationKey(r3), a3 = i3.get(s2);
        a3 ? a3.push(r3) : i3.set(s2, [r3]);
        const c3 = `${Math.floor(r3.x / t3)}:${Math.floor(r3.y / t3)}`, l3 = o3.get(c3);
        l3 ? l3.push(n3) : o3.set(c3, [n3]);
      }
      for (let r3 = 0;r3 < e37.length; r3++) {
        const s2 = e37[r3], a3 = Math.floor(s2.x / t3), c3 = Math.floor(s2.y / t3), l3 = Math.ceil(2.5), h2 = [];
        for (let t4 = -l3;t4 <= l3; t4++)
          for (let n3 = -l3;n3 <= l3; n3++) {
            const i4 = o3.get(`${a3 + t4}:${c3 + n3}`);
            if (i4)
              for (const t5 of i4) {
                if (t5 === r3)
                  continue;
                const n4 = e37[t5];
                if (!n4.mutable)
                  continue;
                const o4 = s2.x - n4.x, i5 = s2.y - n4.y, a4 = o4 * o4 + i5 * i5, c4 = s2.diameter / 2 + n4.diameter / 2, l4 = 2.5 * c4;
                a4 !== 0 && ((a4 <= c4 * c4 || a4 <= l4 * l4 && CF(n4, s2, { connMap: this.connMap, mergedViaHdRoutes: this.mergedViaHdRoutes, hdRouteSHI: this.hdRouteSHI, obstacleSHI: this.obstacleSHI, netByConnectionName: this.netByConnectionName })) && h2.push(n4));
              }
          }
        const d2 = new Set(h2), u2 = h2.filter((e38) => e38.x === s2.x && e38.y === s2.y || i3.get(this.getViaLocationKey(e38)).every((e39) => e39.mutable && d2.has(e39)));
        u2.length > 0 && n2.push({ keep: s2, remove: u2 });
      }
    }
    n2.sort((e37, t3) => t3.remove.length !== e37.remove.length ? t3.remove.length - e37.remove.length : e37.keep.mutable !== t3.keep.mutable ? e37.keep.mutable ? 1 : -1 : t3.keep.layers.length !== e37.keep.layers.length ? t3.keep.layers.length - e37.keep.layers.length : e37.keep.routeIndex - t3.keep.routeIndex);
    for (const o3 of n2) {
      const n3 = this.getViaLocationKey(o3.keep);
      if (t2.has(n3))
        continue;
      const i3 = o3.remove.filter((e37) => !t2.has(this.getViaLocationKey(e37)));
      if (i3.length !== 0) {
        e36.push({ keep: o3.keep, remove: i3 }), t2.add(n3);
        for (const e37 of i3)
          t2.add(this.getViaLocationKey(e37));
      }
    }
    return e36;
  }
  moveViaTo(e36, t2, n2 = true) {
    if (!e36.mutable)
      throw new Error("SameNetViaMergerSolver cannot mutate an immutable via anchor");
    const o3 = this.mergedViaHdRoutes[e36.routeIndex];
    if (!o3)
      throw new Error(`SameNetViaMergerSolver could not find route for via at index ${e36.routeIndex}`);
    const i3 = o3.route, r3 = new Set;
    let s2 = false;
    for (let t3 = i3.length - 1;t3 >= 1; t3--) {
      const n3 = i3[t3 - 1], o4 = i3[t3];
      if (n3.z === o4.z)
        continue;
      if (n3.x !== e36.x || n3.y !== e36.y)
        continue;
      if (o4.x !== e36.x || o4.y !== e36.y)
        continue;
      let s3 = t3 - 1;
      for (;s3 > 0 && i3[s3 - 1].x === e36.x && i3[s3 - 1].y === e36.y; )
        s3--;
      let a3 = t3;
      for (;a3 < i3.length - 1 && i3[a3 + 1].x === e36.x && i3[a3 + 1].y === e36.y; )
        a3++;
      for (let e37 = s3;e37 <= a3; e37++)
        r3.add(e37);
    }
    if (r3.size === 0)
      throw new Error(`SameNetViaMergerSolver could not find route transition for via at (${e36.x}, ${e36.y}) on route "${o3.connectionName}"`);
    for (const e37 of r3) {
      const n3 = i3[e37];
      i3[e37] = { ...n3, x: t2.x, y: t2.y };
    }
    if (o3.vias = o3.vias.map((n3) => n3.x !== e36.x || n3.y !== e36.y ? n3 : (s2 = true, { x: t2.x, y: t2.y })), !s2)
      throw new Error(`SameNetViaMergerSolver could not find via at (${e36.x}, ${e36.y}) on route "${o3.connectionName}"`);
    this.dedupeRouteVias(o3), n2 && this.rebuildVias();
  }
  _step() {
    const e36 = this.getOffendingViaGroupsBatch();
    if (e36.length === 0)
      return void (this.solved = true);
    let t2 = 0;
    for (const n2 of e36)
      for (const e37 of n2.remove)
        this.moveViaTo(e37, n2.keep, false), t2++;
    this.rebuildVias(), this.hdRouteSHI = this.createHdRouteSpatialIndex(), this.stats.mergedViaGroups = e36.length, this.stats.mergedViaCount = t2;
  }
  getMergedViaHdRoutes() {
    return this.mergedViaHdRoutes;
  }
  visualize() {
    const e36 = { lines: [], points: [], rects: [], circles: [], coordinateSystem: "cartesian", title: "Same Net Via Merger Solver" };
    for (const t2 of this.input.obstacles) {
      if (!t2.__zLayers)
        throw new Error("SameNetViaMergerSolver found obstacle without zLayers while visualizing");
      let n2 = "rgba(128, 128, 128, 0.2)";
      const o3 = t2.__zLayers.includes(0), i3 = t2.__zLayers.includes(1);
      o3 && i3 ? n2 = "rgba(128, 0, 128, 0.2)" : o3 ? n2 = "rgba(255, 0, 0, 0.2)" : i3 && (n2 = "rgba(0, 0, 255, 0.2)"), e36.rects.push({ center: t2.center, width: t2.width, height: t2.height, fill: n2, label: `Obstacle (Z: ${t2.__zLayers?.join(", ")})` });
    }
    for (const t2 of this.mergedViaHdRoutes) {
      if (t2.route.length === 0)
        continue;
      const n2 = this.input.colorMap[t2.connectionName];
      if (!n2)
        throw new Error(`SameNetViaMergerSolver could not find color for route "${t2.connectionName}"`);
      for (let n3 = 0;n3 < t2.route.length - 1; n3++) {
        const o3 = t2.route[n3], i3 = t2.route[n3 + 1];
        o3.z === i3.z && e36.lines.push({ points: [{ x: o3.x, y: o3.y }, { x: i3.x, y: i3.y }], strokeColor: o3.z === 0 ? "rgba(255, 0, 0, 0.5)" : "rgba(0, 0, 255, 0.5)", strokeWidth: t2.traceThickness, label: `${t2.connectionName} (z=${o3.z})` });
      }
      for (const n3 of t2.vias)
        e36.circles.push({ center: { x: n3.x, y: n3.y }, radius: t2.viaDiameter / 2, fill: "rgba(255, 0, 255, 0.5)", label: `${t2.connectionName} via` });
      if (t2.jumpers && t2.jumpers.length > 0) {
        const o3 = oF(t2.jumpers, { color: n2, label: t2.connectionName });
        if (!o3.rects || !o3.lines)
          throw new Error(`SameNetViaMergerSolver expected jumper graphics for route "${t2.connectionName}"`);
        e36.rects.push(...o3.rects), e36.lines.push(...o3.lines);
      }
    }
    return e36;
  }
};
var MF = { getConflictingRoutesForSegment: () => [], getConflictingRoutesNearPoint: () => [] };
var wF = 0.000001;
var NF = (e36, t2) => {
  const n2 = `${e36.x}:${e36.y}:${e36.z}`, o3 = `${t2.x}:${t2.y}:${t2.z}`;
  return n2 < o3 ? `${n2}|${o3}` : `${o3}|${n2}`;
};
var RF = (e36) => {
  const t2 = new Set;
  for (let n2 = 1;n2 < e36.route.length; n2++) {
    const o3 = e36.route[n2 - 1], i3 = e36.route[n2];
    o3.z === i3.z && t2.add(NF(o3, i3));
  }
  return t2;
};
var TF = (e36) => e36.filter((t2, n2) => {
  const o3 = e36[n2 - 1];
  return !o3 || t2.x !== o3.x || t2.y !== o3.y || t2.z !== o3.z;
});
var EF = (e36) => {
  const t2 = [], n2 = new Set;
  for (let o3 = 1;o3 < e36.length; o3++) {
    const i3 = e36[o3 - 1], r3 = e36[o3];
    if (i3.z === r3.z)
      continue;
    if (i3.toNextSegmentType === "through_obstacle")
      continue;
    if (i3.x !== r3.x || i3.y !== r3.y)
      throw new Error(`CrossingViaReductionSolver found a layer transition without a via at route point ${o3}`);
    const s2 = `${r3.x}:${r3.y}`;
    n2.has(s2) || (n2.add(s2), t2.push({ x: r3.x, y: r3.y }));
  }
  return t2;
};
var AF = (e36) => {
  const t2 = [e36.connectionName];
  return e36.rootConnectionName && t2.push(e36.rootConnectionName), t2;
};
var OF = (e36, t2, n2) => {
  const o3 = AF(e36), i3 = AF(t2);
  return o3.some((e37) => i3.some((t3) => e37 === t3 || n2.areIdsConnected(e37, t3)));
};
var kF = (e36, t2, n2) => {
  const o3 = AF(t2);
  return e36.connectedTo.some((e37) => o3.some((t3) => e37 === t3 || n2.areIdsConnected(e37, t3)));
};
var DF = (e36) => {
  let t2 = 0;
  for (let n2 = 1;n2 < e36.length; n2++)
    t2 += Math.hypot(e36[n2].x - e36[n2 - 1].x, e36[n2].y - e36[n2 - 1].y);
  return t2;
};
var LF = (e36, t2) => {
  const n2 = DF(e36);
  if (t2 <= wF || t2 >= n2 - wF)
    return null;
  let o3 = 0;
  for (let n3 = 1;n3 < e36.length; n3++) {
    const i3 = e36[n3 - 1], r3 = e36[n3], s2 = Math.hypot(r3.x - i3.x, r3.y - i3.y);
    if (o3 + s2 < t2 - wF) {
      o3 += s2;
      continue;
    }
    const a3 = t2 - o3;
    if (a3 <= wF)
      return { prefix: e36.slice(0, n3).map((e37) => ({ ...e37 })), suffix: e36.slice(n3 - 1).map((e37) => ({ ...e37 })), point: { ...i3 } };
    if (s2 - a3 <= wF)
      return { prefix: e36.slice(0, n3 + 1).map((e37) => ({ ...e37 })), suffix: e36.slice(n3).map((e37) => ({ ...e37 })), point: { ...r3 } };
    const c3 = a3 / s2, l3 = { x: i3.x + (r3.x - i3.x) * c3, y: i3.y + (r3.y - i3.y) * c3, z: i3.z };
    return { prefix: [...e36.slice(0, n3), l3].map((e37) => ({ ...e37 })), suffix: [l3, ...e36.slice(n3)].map((e37) => ({ ...e37 })), point: l3 };
  }
  return null;
};
var zF = (e36, t2, n2, o3) => {
  const i3 = ge(e36, t2, n2, o3);
  if (!i3)
    return null;
  const r3 = Math.hypot(i3.x - e36.x, i3.y - e36.y), s2 = Math.hypot(i3.x - t2.x, i3.y - t2.y), a3 = Math.hypot(i3.x - n2.x, i3.y - n2.y), c3 = Math.hypot(i3.x - o3.x, i3.y - o3.y);
  return Math.min(r3, s2, a3, c3) <= wF ? null : r3;
};
var BF = (e36) => e36.points.some((e37) => e37.insideJumperPad || e37.toNextSegmentType);
var FF = ({ sections: e36, sectionIndex: t2, side: n2 }) => {
  const o3 = e36[t2], i3 = n2 === "start" ? e36[t2 - 1] : e36[t2 + 1];
  if (!i3)
    return null;
  const r3 = n2 === "start" ? o3.points[0] : o3.points.at(-1), s2 = n2 === "start" ? i3.points.at(-1) : i3.points[0];
  return r3.x !== s2.x || r3.y !== s2.y ? null : i3.z;
};
var jF = ({ sections: e36, sectionIndex: t2, targetZ: n2, side: o3 }) => FF({ sections: e36, sectionIndex: t2, side: o3 }) === n2;
var $F = ({ baseIndexes: e36, otherCandidateRoutes: t2, ignoredConnectionNames: n2, originalRouteSegmentKeys: o3 }) => {
  const i3 = new zB([...t2]);
  return { getConflictingRoutesForSegment: (t3, r3, s2) => {
    const a3 = o3.has(NF(t3, r3));
    return [...a3 ? [] : e36.mutableRoutes.getConflictingRoutesForSegment(t3, r3, s2).filter(({ conflictingRoute: e37 }) => !n2.has(e37.connectionName)), ...a3 ? [] : e36.immutableRoutes?.getConflictingRoutesForSegment(t3, r3, s2) ?? [], ...i3.getConflictingRoutesForSegment(t3, r3, s2)];
  }, getConflictingRoutesNearPoint: (t3, o4) => [...e36.mutableRoutes.getConflictingRoutesNearPoint(t3, o4).filter(({ conflictingRoute: e37 }) => !n2.has(e37.connectionName)), ...e36.immutableRoutes?.getConflictingRoutesNearPoint(t3, o4) ?? [], ...i3.getConflictingRoutesNearPoint(t3, o4)] };
};
var YF = class extends SB {
  input;
  obstacleSHI;
  traceMargin;
  obstacleMargin;
  reducedHdRoutes;
  getSolverName() {
    return "CrossingViaReductionSolver";
  }
  constructor(e36) {
    super(), this.input = { ...e36, obstacles: sF(e36.obstacles, e36.layerCount) }, this.traceMargin = e36.traceMargin ?? 0.1, this.obstacleMargin = e36.obstacleMargin ?? 0.15, this.reducedHdRoutes = structuredClone([...e36.inputHdRoutes]), this.obstacleSHI = new EB("flatbush", [...this.input.obstacles]), this.MAX_ITERATIONS = 1e6;
  }
  collapseDetourSection({ route: e36, section: t2, targetZ: n2 }) {
    const o3 = t2.points.map((e37) => ({ ...e37, z: n2 })), i3 = TF([...e36.route.slice(0, t2.startIndex).map((e37) => ({ ...e37 })), ...o3, ...e36.route.slice(t2.endIndex + 1).map((e37) => ({ ...e37 }))]);
    return { ...e36, route: i3, vias: EF(i3) };
  }
  relocateTransitionVia({ route: e36, section: t2, targetZ: n2, side: o3, newViaDistance: i3 }) {
    const r3 = LF(t2.points, i3);
    if (!r3)
      return null;
    const s2 = o3 === "start" ? n2 : t2.z, a3 = o3 === "start" ? t2.z : n2, c3 = [...r3.prefix.map((e37) => ({ ...e37, z: s2 })), ...r3.suffix.map((e37) => ({ ...e37, z: a3 }))], l3 = TF([...e36.route.slice(0, t2.startIndex).map((e37) => ({ ...e37 })), ...c3, ...e36.route.slice(t2.endIndex + 1).map((e37) => ({ ...e37 }))]);
    return { route: { ...e36, route: l3, vias: EF(l3) }, relocatedVia: { x: r3.point.x, y: r3.point.y } };
  }
  relocateTransitionVias({ route: e36, sections: t2, crossingGroups: n2, detourZ: o3, detourTraceThickness: i3 }) {
    const r3 = new Map;
    for (const e37 of n2) {
      const t3 = r3.get(e37.transitionSectionIndex) ?? [];
      t3.push(e37), r3.set(e37.transitionSectionIndex, t3);
    }
    const s2 = [], a3 = [], c3 = e36.viaDiameter / 2 + i3 / 2 + this.traceMargin + wF;
    for (const [e37, n3] of r3) {
      if (n3.length !== 1)
        return null;
      const i4 = t2[e37], r4 = n3[0];
      if (!jF({ sections: t2, sectionIndex: e37, targetZ: o3, side: r4.side }))
        return null;
      const l4 = r4.side === "start" ? Math.max(...r4.crossingDistances) + c3 : Math.min(...r4.crossingDistances) - c3, h2 = LF(i4.points, l4);
      if (!h2)
        return null;
      const d2 = r4.side === "start" ? o3 : i4.z, u2 = r4.side === "start" ? i4.z : o3;
      s2.push({ section: i4, points: [...h2.prefix.map((e38) => ({ ...e38, z: d2 })), ...h2.suffix.map((e38) => ({ ...e38, z: u2 }))] }), a3.push({ x: h2.point.x, y: h2.point.y });
    }
    let l3 = e36.route.map((e37) => ({ ...e37 }));
    for (const e37 of s2.sort((e38, t3) => t3.section.startIndex - e38.section.startIndex))
      l3 = [...l3.slice(0, e37.section.startIndex), ...e37.points, ...l3.slice(e37.section.endIndex + 1)];
    return l3 = TF(l3), { route: { ...e36, route: l3, vias: EF(l3) }, relocatedVias: a3 };
  }
  routeIsClear(e36, t2, n2) {
    for (const o3 of ZB(e36)) {
      for (let t3 = 1;t3 < o3.points.length; t3++) {
        const i3 = o3.points[t3 - 1], r3 = o3.points[t3];
        if (!n2.has(NF(i3, r3)) && this.input.outline && UB({ start: i3, end: r3, polygon: [...this.input.outline], margin: e36.traceThickness / 2 }))
          return false;
      }
      if (!JB({ currentSection: o3, targetZ: o3.z, route: e36, hdRouteSHI: t2, obstacleSHI: this.obstacleSHI, connMap: this.input.connMap, defaultTraceThickness: e36.traceThickness, obstacleMargin: this.obstacleMargin, traceMargin: this.traceMargin, shouldCheckStaticGeometryForSegment: (e37, t3) => !n2.has(NF(e37, t3)) }))
        return false;
    }
    return true;
  }
  relocatedViaIsClear(e36, t2, n2) {
    const o3 = e36.viaDiameter / 2;
    for (let i4 = 0;i4 < this.input.layerCount; i4++) {
      if (n2.getConflictingRoutesNearPoint({ ...t2, z: i4 }, o3 + this.traceMargin).some(({ conflictingRoute: t3 }) => !OF(e36, t3, this.input.connMap)))
        return false;
    }
    const i3 = o3 + this.obstacleMargin, r3 = this.obstacleSHI.searchArea(t2.x, t2.y, 2 * i3, 2 * i3);
    for (const n3 of r3)
      if (!kF(n3, e36, this.input.connMap) && Re(t2, t2, n3) < i3)
        return false;
    if (this.input.outline)
      for (let e37 = 0;e37 < this.input.outline.length; e37++) {
        if (pe(t2, this.input.outline[e37], this.input.outline[(e37 + 1) % this.input.outline.length]) < o3 + this.traceMargin)
          return false;
      }
    return true;
  }
  changedSectionsAreStaticallyClear(e36, t2) {
    for (const n2 of ZB(e36)) {
      if (n2.points.some((e37, o3) => {
        const i3 = n2.points[o3 - 1];
        return i3 !== undefined && !t2.has(NF(i3, e37));
      })) {
        if (this.input.outline) {
          for (let t3 = 1;t3 < n2.points.length; t3++)
            if (UB({ start: n2.points[t3 - 1], end: n2.points[t3], polygon: [...this.input.outline], margin: e36.traceThickness / 2 }))
              return false;
        }
        if (!JB({ currentSection: n2, targetZ: n2.z, route: e36, hdRouteSHI: MF, obstacleSHI: this.obstacleSHI, connMap: this.input.connMap, defaultTraceThickness: e36.traceThickness, obstacleMargin: Math.min(this.obstacleMargin, 0.1), traceMargin: this.traceMargin }))
          return false;
      }
    }
    return true;
  }
  candidateIsClear(e36, t2) {
    const n2 = [{ routeIndex: e36.detourRouteIndex, route: e36.detourRoute }, ...e36.transitionUpdates], o3 = new Set(n2.map(({ routeIndex: e37 }) => this.reducedHdRoutes[e37].connectionName)), i3 = RF(this.reducedHdRoutes[e36.detourRouteIndex]), r3 = $F({ baseIndexes: t2, otherCandidateRoutes: e36.transitionUpdates.map(({ route: e37 }) => e37), ignoredConnectionNames: o3, originalRouteSegmentKeys: i3 });
    if (this.stats.candidateClearanceChecks = (this.stats.candidateClearanceChecks ?? 0) + 1, !this.routeIsClear(e36.detourRoute, r3, i3))
      return false;
    for (const i4 of e36.transitionUpdates) {
      const e37 = RF(this.reducedHdRoutes[i4.routeIndex]), r4 = $F({ baseIndexes: t2, otherCandidateRoutes: n2.filter(({ routeIndex: e38 }) => e38 !== i4.routeIndex).map(({ route: e38 }) => e38), ignoredConnectionNames: o3, originalRouteSegmentKeys: e37 });
      if (!this.routeIsClear(i4.route, r4, e37) || i4.relocatedVias.some((e38) => !this.relocatedViaIsClear(i4.route, e38, r4)))
        return false;
    }
    return this.changedSectionsAreStaticallyClear(e36.detourRoute, i3);
  }
  candidateRoutesHaveNoExternalCopperConflicts(e36, t2) {
    const n2 = [e36.detourRoute, ...e36.transitionUpdates.map(({ route: e37 }) => e37)], o3 = new Set(n2.map(({ connectionName: e37 }) => e37)), i3 = [t2.mutableRoutes, ...t2.immutableRoutes ? [t2.immutableRoutes] : []];
    for (const e37 of n2)
      for (const t3 of ZB(e37))
        for (let n3 = 1;n3 < t3.points.length; n3++) {
          const r3 = t3.points[n3 - 1], s2 = t3.points[n3];
          for (const t4 of i3) {
            if (t4.getConflictingRoutesForSegment(r3, s2, e37.traceThickness / 2 + this.traceMargin).some(({ conflictingRoute: t5 }) => !o3.has(t5.connectionName) && !OF(e37, t5, this.input.connMap)))
              return false;
          }
        }
    return true;
  }
  buildTransitionSegmentIndex(e36, t2) {
    const n2 = [];
    for (let o4 = 0;o4 < this.reducedHdRoutes.length; o4++) {
      if (this.reducedHdRoutes[o4].jumpers?.length)
        continue;
      const i3 = e36[o4];
      for (let e37 = 0;e37 < i3.length; e37++) {
        const r3 = i3[e37];
        if (!BF(r3))
          for (const s2 of ["start", "end"]) {
            const a3 = FF({ sections: i3, sectionIndex: e37, side: s2 });
            if (a3 === null || a3 === r3.z)
              continue;
            if (!t2.has(`${r3.z}:${a3}`))
              continue;
            let c3 = 0;
            for (let t3 = 1;t3 < r3.points.length; t3++) {
              const i4 = r3.points[t3 - 1], l3 = r3.points[t3], h2 = Math.hypot(l3.x - i4.x, l3.y - i4.y);
              h2 > wF && n2.push({ routeIndex: o4, sectionIndex: e37, side: s2, adjacentZ: a3, start: i4, end: l3, distanceFromSectionStart: c3 }), c3 += h2;
            }
          }
      }
    }
    if (this.stats.transitionSegmentsIndexed = (this.stats.transitionSegmentsIndexed ?? 0) + n2.length, n2.length === 0)
      return null;
    const o3 = new TB(n2.length);
    for (const e37 of n2)
      o3.insert(e37, Math.min(e37.start.x, e37.end.x), Math.min(e37.start.y, e37.end.y), Math.max(e37.start.x, e37.end.x), Math.max(e37.start.y, e37.end.y));
    return o3.finish(), o3;
  }
  getIndexedCrossingGroups({ detourRouteIndex: e36, detourSection: t2, targetZ: n2, transitionSegmentIndex: o3 }) {
    const i3 = new Map;
    for (let r3 = 1;r3 < t2.points.length; r3++) {
      const s2 = t2.points[r3 - 1], a3 = t2.points[r3];
      if (Math.hypot(a3.x - s2.x, a3.y - s2.y) <= wF)
        continue;
      this.stats.indexedDetourSegmentQueries = (this.stats.indexedDetourSegmentQueries ?? 0) + 1;
      const c3 = o3.search(Math.min(s2.x, a3.x) - wF, Math.min(s2.y, a3.y) - wF, Math.max(s2.x, a3.x) + wF, Math.max(s2.y, a3.y) + wF);
      for (const o4 of c3) {
        if (o4.routeIndex === e36 || o4.start.z !== n2 || o4.adjacentZ !== t2.z)
          continue;
        this.stats.exactSegmentIntersectionChecks = (this.stats.exactSegmentIntersectionChecks ?? 0) + 1;
        const r4 = zF(o4.start, o4.end, s2, a3);
        if (r4 === null)
          continue;
        const c4 = `${o4.routeIndex}:${o4.sectionIndex}:${o4.side}`;
        let l3 = i3.get(c4);
        l3 || (l3 = { transitionRouteIndex: o4.routeIndex, transitionSectionIndex: o4.sectionIndex, side: o4.side, crossingDistances: [] }, i3.set(c4, l3)), l3.crossingDistances.push(o4.distanceFromSectionStart + r4);
      }
    }
    return [...i3.values()].sort((e37, t3) => e37.transitionRouteIndex !== t3.transitionRouteIndex ? e37.transitionRouteIndex - t3.transitionRouteIndex : e37.transitionSectionIndex !== t3.transitionSectionIndex ? e37.transitionSectionIndex - t3.transitionSectionIndex : e37.side === t3.side ? 0 : e37.side === "start" ? -1 : 1);
  }
  tryCreateCandidate({ detourRouteIndex: e36, detourSection: t2, targetZ: n2, transitionRouteIndex: o3, transitionSection: i3, transitionSections: r3, transitionSectionIndex: s2, side: a3, crossingDistances: c3, baseClearanceIndexes: l3 }) {
    if (!jF({ sections: r3, sectionIndex: s2, targetZ: t2.z, side: a3 }))
      return null;
    const h2 = this.reducedHdRoutes[e36], d2 = this.reducedHdRoutes[o3];
    if (c3.length === 0)
      return null;
    const u2 = d2.viaDiameter / 2 + h2.traceThickness / 2 + this.traceMargin + wF, p3 = a3 === "start" ? Math.max(...c3) + u2 : Math.min(...c3) - u2, m2 = this.relocateTransitionVia({ route: d2, section: i3, targetZ: t2.z, side: a3, newViaDistance: p3 });
    if (!m2)
      return null;
    const g2 = this.collapseDetourSection({ route: h2, section: t2, targetZ: n2 });
    if (h2.vias.length + d2.vias.length - g2.vias.length - m2.route.vias.length !== 2)
      return null;
    const f2 = { detourRouteIndex: e36, detourRoute: g2, transitionUpdates: [{ routeIndex: o3, route: m2.route, relocatedVias: [m2.relocatedVia] }] };
    return this.candidateIsClear(f2, l3) ? f2 : null;
  }
  tryCreateMultiCrossingCandidate({ detourRouteIndex: e36, detourSection: t2, targetZ: n2, crossingGroups: o3, sectionsByRoute: i3, baseClearanceIndexes: r3 }) {
    if (o3.length < 2)
      return null;
    const s2 = this.reducedHdRoutes[e36], a3 = [], c3 = new Map;
    for (const e37 of o3) {
      const t3 = c3.get(e37.transitionRouteIndex) ?? [];
      t3.push(e37), c3.set(e37.transitionRouteIndex, t3);
    }
    for (const [e37, n3] of c3) {
      const o4 = this.reducedHdRoutes[e37], r4 = this.relocateTransitionVias({ route: o4, sections: i3[e37], crossingGroups: n3, detourZ: t2.z, detourTraceThickness: s2.traceThickness });
      if (!r4)
        return null;
      a3.push({ routeIndex: e37, route: r4.route, relocatedVias: r4.relocatedVias });
    }
    const l3 = this.collapseDetourSection({ route: s2, section: t2, targetZ: n2 });
    if (s2.vias.length + [...c3.keys()].reduce((e37, t3) => e37 + this.reducedHdRoutes[t3].vias.length, 0) - (l3.vias.length + a3.reduce((e37, { route: t3 }) => e37 + t3.vias.length, 0)) !== 2)
      return null;
    this.stats.multiCrossingCandidates = (this.stats.multiCrossingCandidates ?? 0) + 1;
    const h2 = { detourRouteIndex: e36, detourRoute: l3, transitionUpdates: a3 };
    return this.candidateIsClear(h2, r3) ? this.candidateRoutesHaveNoExternalCopperConflicts(h2, r3) ? (this.stats.multiCrossingReductions = (this.stats.multiCrossingReductions ?? 0) + 1, this.stats.transitionRoutesMovedByMultiCrossingReductions = (this.stats.transitionRoutesMovedByMultiCrossingReductions ?? 0) + a3.length, h2) : (this.stats.multiCrossingPreexistingConflictRejections = (this.stats.multiCrossingPreexistingConflictRejections ?? 0) + 1, null) : null;
  }
  findCrossingReduction() {
    const e36 = this.reducedHdRoutes.map((e37) => ZB(e37)), t2 = [], n2 = new Set;
    for (let o4 = 0;o4 < this.reducedHdRoutes.length; o4++) {
      if (this.reducedHdRoutes[o4].jumpers?.length)
        continue;
      const i4 = e36[o4];
      for (let e37 = 1;e37 < i4.length - 1; e37++) {
        const r3 = i4[e37 - 1], s2 = i4[e37], a3 = i4[e37 + 1];
        r3.z !== a3.z || r3.z === s2.z || BF(s2) || (t2.push({ routeIndex: o4, section: s2, targetZ: r3.z }), n2.add(`${r3.z}:${s2.z}`));
      }
    }
    if (t2.length === 0)
      return null;
    const o3 = this.buildTransitionSegmentIndex(e36, n2);
    if (!o3)
      return null;
    let i3 = null;
    for (const n3 of t2) {
      const { routeIndex: t3, section: r3 } = n3, s2 = this.reducedHdRoutes[t3], a3 = this.getIndexedCrossingGroups({ detourRouteIndex: t3, detourSection: r3, targetZ: n3.targetZ, transitionSegmentIndex: o3 }).filter(({ transitionRouteIndex: e37 }) => {
        const t4 = this.reducedHdRoutes[e37];
        return !t4.jumpers?.length && !OF(s2, t4, this.input.connMap);
      }), c3 = new Map;
      for (const e37 of a3) {
        const t4 = `${e37.transitionRouteIndex}:${e37.transitionSectionIndex}`, n4 = c3.get(t4) ?? [];
        n4.push(e37), c3.set(t4, n4);
      }
      if (c3.size > 1) {
        i3 ??= { mutableRoutes: new zB(this.reducedHdRoutes), immutableRoutes: this.input.otherHdRoutes?.length ? new zB([...this.input.otherHdRoutes]) : null };
        let o4 = [{ groups: [], movement: 0 }];
        const a4 = (t4) => {
          const n4 = this.reducedHdRoutes[t4.transitionRouteIndex], o5 = e36[t4.transitionRouteIndex][t4.transitionSectionIndex], i4 = n4.viaDiameter / 2 + s2.traceThickness / 2 + this.traceMargin + wF, r4 = t4.side === "start" ? Math.max(...t4.crossingDistances) + i4 : Math.min(...t4.crossingDistances) - i4;
          return t4.side === "start" ? r4 : DF(o5.points) - r4;
        };
        for (const e37 of c3.values()) {
          const t4 = e37.map((e38) => ({ group: e38, movement: a4(e38) })).sort((e38, t5) => e38.movement - t5.movement);
          o4 = o4.flatMap((e38) => t4.map((t5) => ({ groups: [...e38.groups, t5.group], movement: e38.movement + t5.movement }))).sort((e38, t5) => e38.movement - t5.movement).slice(0, 4);
        }
        for (const s3 of o4) {
          const o5 = this.tryCreateMultiCrossingCandidate({ detourRouteIndex: t3, detourSection: r3, targetZ: n3.targetZ, crossingGroups: s3.groups, sectionsByRoute: e36, baseClearanceIndexes: i3 });
          if (o5)
            return o5;
        }
        continue;
      }
      const l3 = c3.values().next().value ?? [];
      for (const o4 of l3) {
        const s3 = o4.transitionRouteIndex, a4 = e36[s3], c4 = a4[o4.transitionSectionIndex];
        i3 ??= { mutableRoutes: new zB(this.reducedHdRoutes), immutableRoutes: this.input.otherHdRoutes?.length ? new zB([...this.input.otherHdRoutes]) : null };
        const l4 = this.tryCreateCandidate({ detourRouteIndex: t3, detourSection: r3, targetZ: n3.targetZ, transitionRouteIndex: s3, transitionSection: c4, transitionSections: a4, transitionSectionIndex: o4.transitionSectionIndex, side: o4.side, crossingDistances: o4.crossingDistances, baseClearanceIndexes: i3 });
        if (l4)
          return l4;
      }
    }
    return null;
  }
  _step() {
    const e36 = this.findCrossingReduction();
    if (e36) {
      this.reducedHdRoutes[e36.detourRouteIndex] = e36.detourRoute;
      for (const t2 of e36.transitionUpdates)
        this.reducedHdRoutes[t2.routeIndex] = t2.route;
      this.stats.crossingViaReductions = (this.stats.crossingViaReductions ?? 0) + 1, this.stats.viasRemovedByCrossingReductions = (this.stats.viasRemovedByCrossingReductions ?? 0) + 2;
    } else
      this.solved = true;
  }
  getReducedHdRoutes() {
    return this.reducedHdRoutes;
  }
  visualize() {
    const e36 = { lines: [], circles: [], rects: [], coordinateSystem: "cartesian", title: "Crossing Via Reduction Solver" };
    for (const t2 of this.input.obstacles)
      e36.rects.push({ center: t2.center, width: t2.width, height: t2.height, fill: "rgba(128, 128, 128, 0.2)" });
    for (const t2 of this.reducedHdRoutes) {
      for (let n2 = 1;n2 < t2.route.length; n2++) {
        const o3 = t2.route[n2 - 1], i3 = t2.route[n2];
        o3.z === i3.z && e36.lines.push({ points: [o3, i3], strokeColor: o3.z === 0 ? "#d32f2f" : "#3367a8", strokeWidth: t2.traceThickness, label: `${t2.connectionName} (z=${o3.z})` });
      }
      for (const n2 of t2.vias)
        e36.circles.push({ center: n2, radius: t2.viaDiameter / 2, fill: "#ff20d6", label: `${t2.connectionName} via` });
    }
    return e36;
  }
};
var XF = 0.000001;
var HF = (e36, t2) => Math.abs(e36.x - t2.center.x) <= t2.width / 2 + XF && Math.abs(e36.y - t2.center.y) <= t2.height / 2 + XF;
var VF = (e36) => (e36.__zLayers?.length ?? e36.layers?.length ?? 0) > 1;
var WF = class extends SB {
  constructor(e36) {
    if (super(), this.simplificationConfig = e36, this.simplificationConfig = { ...e36, obstacles: sF(e36.obstacles, e36.layerCount) }, this.hdRoutes = this.markThroughObstacleSegments(e36.hdRoutes), e36.preserveRouteEndpoints) {
      const t2 = new Map;
      for (const n2 of e36.hdRoutes) {
        const e37 = n2.route[0], o3 = n2.route.at(-1);
        if (!e37 || !o3)
          throw new Error(`TraceSimplificationSolver cannot preserve endpoints for empty route "${n2.connectionName}"`);
        if (t2.has(n2.connectionName))
          throw new Error(`TraceSimplificationSolver cannot preserve endpoints for duplicate route "${n2.connectionName}"`);
        t2.set(n2.connectionName, { start: { ...e37 }, end: { ...o3 } });
      }
      this.preservedRouteEndpoints = t2;
    }
    this.MAX_ITERATIONS = 1e8;
  }
  getSolverName() {
    return "TraceSimplificationSolver";
  }
  hdRoutes = [];
  preservedRouteEndpoints;
  simplificationPipelineLoops = 0;
  MAX_SIMPLIFICATION_PIPELINE_LOOPS = 2;
  PHASE_ORDER = ["via_removal", "crossing_via_reduction", "via_merging", "path_simplification"];
  currentPhase = "via_removal";
  extractResult = null;
  get simplifiedHdRoutes() {
    return this.hdRoutes;
  }
  validatePreservedRouteEndpoints(e36) {
    if (!this.preservedRouteEndpoints)
      return;
    if (e36.length !== this.preservedRouteEndpoints.size)
      throw new Error(`TraceSimplificationSolver changed the preserved route set (expected ${this.preservedRouteEndpoints.size}, got ${e36.length})`);
    const t2 = new Set, n2 = (e37, t3) => Math.abs(e37.x - t3.x) <= XF && Math.abs(e37.y - t3.y) <= XF && e37.z === t3.z;
    for (const o3 of e36) {
      if (t2.has(o3.connectionName))
        throw new Error(`TraceSimplificationSolver produced duplicate preserved route "${o3.connectionName}"`);
      t2.add(o3.connectionName);
      const e37 = this.preservedRouteEndpoints.get(o3.connectionName), i3 = o3.route[0], r3 = o3.route.at(-1);
      if (!(e37 && i3 && r3 && n2(i3, e37.start) && n2(r3, e37.end)))
        throw new Error(`TraceSimplificationSolver changed a preserved endpoint for route "${o3.connectionName}"`);
    }
  }
  isSameNetObstacle(e36, t2) {
    return t2.connectedTo.some((t3) => t3 === e36.connectionName || t3 === e36.rootConnectionName || this.simplificationConfig.connMap.areIdsConnected(e36.connectionName, t3) || e36.rootConnectionName !== undefined && this.simplificationConfig.connMap.areIdsConnected(e36.rootConnectionName, t3));
  }
  getSameNetObstacleForSegment(e36, t2, n2) {
    return this.simplificationConfig.obstacles.find((o3) => VF(o3) && HF(t2, o3) && HF(n2, o3) && this.isSameNetObstacle(e36, o3));
  }
  isViaInsideSameNetObstacle(e36, t2) {
    return this.simplificationConfig.obstacles.some((n2) => VF(n2) && HF(t2, n2) && this.isSameNetObstacle(e36, n2));
  }
  markThroughObstacleSegments(e36) {
    return e36.map((e37) => ({ ...e37, route: e37.route.map((t2, n2, o3) => {
      const i3 = o3[n2 + 1], r3 = i3 && t2.z !== i3.z && this.getSameNetObstacleForSegment(e37, t2, i3);
      if (r3)
        return { ...t2, toNextSegmentType: "through_obstacle", ...r3.circuitJsonMetadata ? { toNextSegmentCircuitJsonMetadata: r3.circuitJsonMetadata } : {} };
      const s2 = { ...t2 };
      return delete s2.toNextSegmentType, delete s2.toNextSegmentCircuitJsonMetadata, s2;
    }), vias: e37.vias.filter((t2) => !this.isViaInsideSameNetObstacle(e37, t2)) }));
  }
  _step() {
    if (this.simplificationPipelineLoops >= this.MAX_SIMPLIFICATION_PIPELINE_LOOPS)
      this.solved = true;
    else {
      if (this.activeSubSolver) {
        if (this.activeSubSolver.step(), !this.activeSubSolver.failed && !this.activeSubSolver.solved)
          return;
        if (this.activeSubSolver.solved) {
          if (this.extractResult) {
            const e36 = this.extractResult(this.activeSubSolver);
            this.validatePreservedRouteEndpoints(e36), this.hdRoutes = this.markThroughObstacleSegments(e36);
          }
          if (this.activeSubSolver = null, this.extractResult = null, this.currentPhase === "via_removal" ? this.currentPhase = this.simplificationConfig.enableCrossingViaReduction ? "crossing_via_reduction" : "via_merging" : this.currentPhase === "crossing_via_reduction" ? this.currentPhase = "via_merging" : this.currentPhase === "via_merging" ? this.currentPhase = "path_simplification" : (this.currentPhase = "via_removal", this.simplificationPipelineLoops++), this.simplificationPipelineLoops >= this.MAX_SIMPLIFICATION_PIPELINE_LOOPS)
            return void (this.solved = true);
        } else if (this.activeSubSolver.failed)
          return this.failed = true, void (this.error = this.activeSubSolver.error ?? "Sub-solver failed without error message");
      }
      if (!this.activeSubSolver && !this.solved)
        switch (this.currentPhase) {
          case "via_removal":
            this.activeSubSolver = new aF({ enableRoutedTraceDetours: this.simplificationConfig.enableRoutedTraceDetours, unsimplifiedHdRoutes: this.hdRoutes, otherHdRoutes: [...this.simplificationConfig.otherHdRoutes ?? []], obstacles: [...this.simplificationConfig.obstacles], colorMap: { ...this.simplificationConfig.colorMap }, layerCount: this.simplificationConfig.layerCount, connMap: this.simplificationConfig.connMap, outline: this.simplificationConfig.outline ? [...this.simplificationConfig.outline] : undefined, geometryShortcutTraceMargin: 0.1, geometryShortcutObstacleMargin: this.simplificationConfig.minTraceToPadEdgeClearance ?? 0.15, enableGeometryShortcuts: this.simplificationPipelineLoops > 0, enableObstacleDetourShortcuts: this.simplificationConfig.enableCrossingViaReduction === true && this.simplificationPipelineLoops > 0, preserveRouteEndpoints: this.simplificationConfig.preserveRouteEndpoints, terminalLayerIndicesByPcbPortId: this.simplificationConfig.terminalLayerIndicesByPcbPortId }), this.extractResult = (e36) => e36.getOptimizedHdRoutes() ?? [];
            break;
          case "crossing_via_reduction":
            this.activeSubSolver = new YF({ inputHdRoutes: this.hdRoutes, otherHdRoutes: [...this.simplificationConfig.otherHdRoutes ?? []], obstacles: [...this.simplificationConfig.obstacles], connMap: this.simplificationConfig.connMap, layerCount: this.simplificationConfig.layerCount, outline: this.simplificationConfig.outline ? [...this.simplificationConfig.outline] : undefined, traceMargin: 0.1, obstacleMargin: this.simplificationConfig.minTraceToPadEdgeClearance ?? 0.15 }), this.extractResult = (e36) => e36.getReducedHdRoutes();
            break;
          case "via_merging":
            this.activeSubSolver = new PF({ inputHdRoutes: this.hdRoutes, otherHdRoutes: [...this.simplificationConfig.otherHdRoutes ?? []], netByConnectionName: this.simplificationConfig.netByConnectionName, obstacles: [...this.simplificationConfig.obstacles], colorMap: { ...this.simplificationConfig.colorMap }, layerCount: this.simplificationConfig.layerCount, connMap: this.simplificationConfig.connMap, outline: this.simplificationConfig.outline ? [...this.simplificationConfig.outline] : undefined, preserveRouteEndpoints: this.simplificationConfig.preserveRouteEndpoints }), this.extractResult = (e36) => e36.getMergedViaHdRoutes() ?? [];
            break;
          case "path_simplification":
            this.activeSubSolver = new xF({ unsimplifiedHdRoutes: this.hdRoutes, otherHdRoutes: [...this.simplificationConfig.otherHdRoutes ?? []], obstacles: [...this.simplificationConfig.obstacles], connMap: this.simplificationConfig.connMap, colorMap: { ...this.simplificationConfig.colorMap }, outline: this.simplificationConfig.outline ? [...this.simplificationConfig.outline] : undefined, minBoardEdgeClearance: this.simplificationConfig.minBoardEdgeClearance, defaultViaDiameter: this.simplificationConfig.defaultViaDiameter, useTraceWidthAwareClearance: this.simplificationConfig.useTraceWidthAwareClearance, enableVertexShortcuts: this.simplificationConfig.enableVertexShortcuts }), this.extractResult = (e36) => e36.simplifiedHdRoutes;
            break;
          default:
            this.failed = true, this.error = `Unknown phase: ${this.currentPhase}`;
        }
    }
  }
  visualize() {
    if (this.activeSubSolver)
      return this.activeSubSolver.visualize();
    const e36 = { lines: [], points: [], rects: [], circles: [], coordinateSystem: "cartesian", title: "Trace Simplification Solver" };
    for (const t2 of this.simplificationConfig.obstacles) {
      let n2 = "rgba(128, 128, 128, 0.2)";
      const o3 = t2.__zLayers?.includes(0), i3 = t2.__zLayers?.includes(1);
      o3 && i3 ? n2 = "rgba(128, 0, 128, 0.2)" : o3 ? n2 = "rgba(255, 0, 0, 0.2)" : i3 && (n2 = "rgba(0, 0, 255, 0.2)"), e36.rects.push({ center: t2.center, width: t2.width, height: t2.height, fill: n2, label: `Obstacle (Z: ${t2.__zLayers?.join(", ")})` });
    }
    for (const t2 of this.simplificationConfig.otherHdRoutes ?? []) {
      for (let n2 = 0;n2 < t2.route.length - 1; n2++) {
        const o3 = t2.route[n2], i3 = t2.route[n2 + 1];
        o3.z === i3.z && e36.lines.push({ points: [{ x: o3.x, y: o3.y }, { x: i3.x, y: i3.y }], strokeColor: o3.z === 0 ? "rgba(160, 32, 32, 0.55)" : "rgba(32, 32, 160, 0.55)", strokeWidth: t2.traceThickness, strokeDash: [0.08, 0.08], label: `${t2.connectionName} immutable (z=${o3.z})` });
      }
      for (const n2 of t2.vias)
        e36.circles.push({ center: { x: n2.x, y: n2.y }, radius: t2.viaDiameter / 2, fill: "rgba(96, 96, 96, 0.45)", label: `${t2.connectionName} immutable via` });
    }
    for (const t2 of this.hdRoutes)
      if (t2.route.length !== 0) {
        for (let n2 = 0;n2 < t2.route.length - 1; n2++) {
          const o3 = t2.route[n2], i3 = t2.route[n2 + 1];
          o3.z === i3.z && e36.lines.push({ points: [{ x: o3.x, y: o3.y }, { x: i3.x, y: i3.y }], strokeColor: o3.z === 0 ? "red" : "blue", strokeWidth: t2.traceThickness, label: `${t2.connectionName} (z=${o3.z})` });
        }
        for (const n2 of t2.vias)
          e36.circles.push({ center: { x: n2.x, y: n2.y }, radius: t2.viaDiameter / 2, fill: "rgba(255, 0, 255, 0.5)", label: `${t2.connectionName} via` });
        if (t2.jumpers && t2.jumpers.length > 0) {
          const n2 = oF(t2.jumpers, { color: "orange", label: t2.connectionName });
          e36.rects.push(...n2.rects ?? []), e36.lines.push(...n2.lines ?? []);
        }
      }
    return e36;
  }
};
var GF = class {
  tree;
  constructor(e36 = 9) {
    this.tree = new G(e36);
  }
  insert(e36, t2, n2, o3, i3) {
    this.tree.insert({ minX: t2, minY: n2, maxX: o3, maxY: i3, data: e36 });
  }
  bulkLoad(e36) {
    const t2 = e36.map(({ item: e37, minX: t3, minY: n2, maxX: o3, maxY: i3 }) => ({ minX: t3, minY: n2, maxX: o3, maxY: i3, data: e37 }));
    this.tree.load(t2);
  }
  search(e36, t2, n2, o3) {
    return this.tree.search({ minX: e36, minY: t2, maxX: n2, maxY: o3 }).map((e37) => e37.data);
  }
  clear() {
    this.tree.clear();
  }
};
var UF = class {
  index;
  items = [];
  currentIndex = 0;
  capacity;
  constructor(e36) {
    this.capacity = Math.max(1, e36), this.index = new E2(this.capacity);
  }
  insert(e36, t2, n2, o3, i3) {
    if (this.currentIndex >= this.index.numItems)
      throw new Error("Exceeded initial capacity");
    this.items[this.currentIndex] = e36, this.index.add(t2, n2, o3, i3), this.currentIndex++;
  }
  finish() {
    this.index.finish();
  }
  search(e36, t2, n2, o3) {
    return this.index.search(e36, t2, n2, o3).map((e37) => this.items[e37] || null).filter(Boolean);
  }
  clear() {
    this.items = [], this.currentIndex = 0, this.index = new E2(this.capacity);
  }
};
var ZF = class {
  idx;
  storage = [];
  constructor(e36 = "native", t2 = []) {
    e36 === "flatbush" ? t2.length === 0 ? (this.idx = new GF, e36 = "rbush") : this.idx = new UF(t2.length) : this.idx = e36 === "rbush" ? new GF : new class {
      shi = new qF(t2);
      insert(e37) {}
      search(e37, t3, n2, o3) {
        const i3 = (e37 + n2) / 2, r3 = (t3 + o3) / 2, s2 = n2 - e37, a3 = o3 - t3;
        return this.shi.getNodesInArea(i3, r3, s2, a3);
      }
      clear() {}
    }, t2.forEach((e37) => this.insert(e37)), e36 === "flatbush" && t2.length > 0 && this.idx.finish?.();
  }
  insert(e36) {
    this.storage.push(e36), this.idx.insert(e36, e36.center.x - e36.width / 2, e36.center.y - e36.height / 2, e36.center.x + e36.width / 2, e36.center.y + e36.height / 2);
  }
  search(e36) {
    return this.idx.search(e36.minX, e36.minY, e36.maxX, e36.maxY);
  }
  searchArea(e36, t2, n2, o3) {
    return this.search({ minX: e36 - n2 / 2, minY: t2 - o3 / 2, maxX: e36 + n2 / 2, maxY: t2 + o3 / 2 });
  }
};
var qF = class {
  constructor(e36) {
    this.obstacles = e36, this.buckets = new Map;
    for (let t2 = 0;t2 < e36.length; t2++) {
      const n2 = e36[t2], o3 = n2.center.x - n2.width / 2, i3 = n2.center.y - n2.height / 2, r3 = n2.center.x + n2.width / 2, s2 = n2.center.y + n2.height / 2;
      for (let e37 = o3;e37 <= r3; e37 += this.CELL_SIZE)
        for (let o4 = i3;o4 <= s2; o4 += this.CELL_SIZE) {
          const i4 = this.getBucketKey(e37, o4), r4 = this.buckets.get(i4);
          r4 ? r4.push([n2, t2]) : this.buckets.set(i4, [[n2, t2]]);
        }
    }
  }
  buckets;
  CELL_SIZE = 0.4;
  getBucketKey(e36, t2) {
    return `${Math.floor(e36 / this.CELL_SIZE)}x${Math.floor(t2 / this.CELL_SIZE)}`;
  }
  getNodesInArea(e36, t2, n2, o3) {
    const i3 = [], r3 = new Set, s2 = t2 - o3 / 2, a3 = e36 + n2 / 2, c3 = t2 + o3 / 2;
    for (let t3 = e36 - n2 / 2;t3 <= a3; t3 += this.CELL_SIZE)
      for (let e37 = s2;e37 <= c3; e37 += this.CELL_SIZE) {
        const n3 = this.getBucketKey(t3, e37), o4 = this.buckets.get(n3) || [];
        for (const e38 of o4)
          r3.has(e38[1]) || (r3.add(e38[1]), i3.push(e38[0]));
      }
    return i3;
  }
};
var JF = 0.000000001;
var QF = class extends ni {
  getSolverName() {
    return "TraceWidthSolver";
  }
  hdRoutes;
  hdRoutesWithWidths = [];
  nominalTraceWidth;
  minTraceWidth;
  obstacleMargin;
  minTraceToHoleEdgeClearance;
  TRACE_WIDTH_SCHEDULE;
  connectionNominalTraceWidthMap;
  unprocessedRoutes = [];
  processedRoutes = [];
  currentTrace = null;
  cursorPosition = null;
  currentTraceSegmentIndex = 0;
  currentTraceSegmentT = 0;
  currentScheduleIndex = 0;
  currentTargetWidth = 0;
  hasInsufficientClearance = false;
  lastCollidingObstacles = [];
  lastCollidingRoutes = [];
  lastClearance = 1 / 0;
  obstacles = [];
  obstacleSHI;
  hdRouteSHI;
  connMap;
  colorMap;
  constructor(e36) {
    super(), this.MAX_ITERATIONS = 1e6, this.hdRoutes = [...e36.hdRoutes], this.minTraceWidth = e36.minTraceWidth, this.obstacleMargin = e36.obstacleMargin ?? 0.15, this.minTraceToHoleEdgeClearance = e36.minTraceToHoleEdgeClearance, this.nominalTraceWidth = 0, this.TRACE_WIDTH_SCHEDULE = [], this.unprocessedRoutes = [...this.hdRoutes], this.connMap = e36.connMap, this.colorMap = e36.colorMap;
    const t2 = e36.layerCount;
    this.obstacles = ca(e36.obstacles ?? [], t2), this.connectionNominalTraceWidthMap = new Map;
    for (const t3 of e36.connection)
      t3.nominalTraceWidth !== undefined && this.connectionNominalTraceWidthMap.set(t3.name, t3.nominalTraceWidth);
    this.obstacles.length > 0 && (this.obstacleSHI = new ZF("flatbush", this.obstacles)), this.hdRouteSHI = new xr(this.hdRoutes);
  }
  getNominalTraceWidthForRoute(e36) {
    const t2 = this.connectionNominalTraceWidthMap.get(e36.connectionName);
    return t2 !== undefined ? t2 : e36.rootConnectionName ? this.connectionNominalTraceWidthMap.get(e36.rootConnectionName) : undefined;
  }
  _step() {
    if (!this.currentTrace) {
      const e37 = this.unprocessedRoutes.shift();
      if (!e37)
        return this.hdRoutesWithWidths = this.processedRoutes, void (this.solved = true);
      const t2 = this.getNominalTraceWidthForRoute(e37);
      if (t2 === undefined) {
        const t3 = e37.traceThickness ?? this.minTraceWidth;
        return this.processedRoutes.push(this.createRouteWithWidth(e37, t3)), void (this.currentTrace = null);
      }
      this.currentTrace = e37, this.nominalTraceWidth = t2;
      const n2 = (this.nominalTraceWidth + this.minTraceWidth) / 2;
      return this.TRACE_WIDTH_SCHEDULE = [this.nominalTraceWidth, n2], this.currentTrace.route.length < 2 ? (this.processedRoutes.push(this.createRouteWithWidth(this.currentTrace, this.minTraceWidth)), void (this.currentTrace = null)) : (this.currentScheduleIndex = 0, this.currentTargetWidth = this.TRACE_WIDTH_SCHEDULE[0], void this.initializeCursor());
    }
    const e36 = this.stepCursorForward();
    (e36 ? this.getClearanceForSegment(this.cursorPosition, this.cursorPosition) : this.getMinimumRouteClearance()) < this.currentTargetWidth / 2 + this.obstacleMargin ? (this.hasInsufficientClearance = true, this.currentScheduleIndex++, this.currentScheduleIndex < this.TRACE_WIDTH_SCHEDULE.length ? (this.currentTargetWidth = this.TRACE_WIDTH_SCHEDULE[this.currentScheduleIndex], this.initializeCursor()) : this.finalizeCurrentTrace(this.minTraceWidth)) : e36 || this.finalizeCurrentTrace(this.currentTargetWidth);
  }
  initializeCursor() {
    if (!this.currentTrace)
      return;
    const e36 = this.currentTrace.route[0];
    this.cursorPosition = { ...e36 }, this.currentTraceSegmentIndex = 0, this.currentTraceSegmentT = 0, this.hasInsufficientClearance = false;
  }
  stepCursorForward() {
    if (!this.currentTrace || !this.cursorPosition)
      return false;
    const e36 = this.currentTrace.route;
    let t2 = 0.1;
    for (;t2 > 0; ) {
      if (this.currentTraceSegmentIndex >= e36.length - 1)
        return false;
      const n2 = e36[this.currentTraceSegmentIndex], o3 = e36[this.currentTraceSegmentIndex + 1];
      if (n2.insideJumperPad && o3.insideJumperPad) {
        this.currentTraceSegmentIndex++, this.currentTraceSegmentT = 0;
        continue;
      }
      const i3 = o3.x - n2.x, r3 = o3.y - n2.y, s2 = Math.sqrt(i3 * i3 + r3 * r3);
      if (s2 === 0) {
        this.currentTraceSegmentIndex++, this.currentTraceSegmentT = 0;
        continue;
      }
      const a3 = this.currentTraceSegmentT * s2, c3 = s2 - a3;
      if (t2 <= c3) {
        const e37 = a3 + t2;
        return this.currentTraceSegmentT = e37 / s2, this.cursorPosition = { x: n2.x + i3 * this.currentTraceSegmentT, y: n2.y + r3 * this.currentTraceSegmentT, z: n2.z }, true;
      }
      if (t2 -= c3, this.currentTraceSegmentIndex++, this.currentTraceSegmentT = 0, this.currentTraceSegmentIndex >= e36.length - 1) {
        const t3 = e36[e36.length - 1];
        return this.cursorPosition = { ...t3 }, false;
      }
    }
    return true;
  }
  isObstacleOwnJumperPad(e36) {
    if (!this.currentTrace?.jumpers)
      return false;
    for (const t2 of this.currentTrace.jumpers) {
      const n2 = Math.sqrt((e36.center.x - t2.start.x) ** 2 + (e36.center.y - t2.start.y) ** 2), o3 = Math.sqrt((e36.center.x - t2.end.x) ** 2 + (e36.center.y - t2.end.y) ** 2), i3 = Math.max(e36.width, e36.height) / 2 + 0.01;
      if (n2 < i3 || o3 < i3)
        return true;
    }
    return false;
  }
  getMinimumRouteClearance() {
    if (!this.currentTrace)
      return 1 / 0;
    let e36 = 1 / 0;
    const t2 = this.currentTrace.route;
    for (let n2 = 0;n2 < t2.length - 1; n2++) {
      const o3 = t2[n2], i3 = t2[n2 + 1];
      o3.z === i3.z && (o3.insideJumperPad && i3.insideJumperPad || o3.toNextSegmentType !== "through_obstacle" && (e36 = Math.min(e36, this.getClearanceForSegment(o3, i3))));
    }
    return e36;
  }
  getClearanceForSegment(e36, t2) {
    if (!this.currentTrace)
      return 1 / 0;
    const n2 = this.currentTrace.rootConnectionName ?? this.currentTrace.connectionName, o3 = this.currentTargetWidth / 2 + this.obstacleMargin;
    let i3 = 1 / 0;
    this.lastCollidingObstacles = [], this.lastCollidingRoutes = [];
    const r3 = this.currentTargetWidth / 2 + Math.max(this.obstacleMargin, this.minTraceToHoleEdgeClearance ?? 0), s2 = new Set(this.obstacleSHI?.search({ minX: Math.min(e36.x, t2.x) - r3, minY: Math.min(e36.y, t2.y) - r3, maxX: Math.max(e36.x, t2.x) + r3, maxY: Math.max(e36.y, t2.y) + r3 }));
    for (const e37 of this.obstacles)
      e37.ccwRotationDegrees && s2.add(e37);
    for (const r4 of s2) {
      if (!this.isObstacleOnPointLayer(r4, e36))
        continue;
      if (xo(r4, this.currentTrace, this.connMap))
        continue;
      if (r4.obstacleId && this.connMap?.areIdsConnected(n2, r4.obstacleId))
        continue;
      if (this.isObstacleOwnJumperPad(r4))
        continue;
      const s3 = -(r4.ccwRotationDegrees ?? 0) * Math.PI / 180, a4 = Math.cos(s3), c3 = Math.sin(s3), l3 = { x: (e36.x - r4.center.x) * a4 - (e36.y - r4.center.y) * c3, y: (e36.x - r4.center.x) * c3 + (e36.y - r4.center.y) * a4 }, h2 = { x: (t2.x - r4.center.x) * a4 - (t2.y - r4.center.y) * c3, y: (t2.x - r4.center.x) * c3 + (t2.y - r4.center.y) * a4 }, d2 = (r4.isNonPlatedHole && r4.shape === "circle" ? Te(e36, t2, { ...r4.center, radius: r4.width / 2 }) : Re(l3, h2, { center: { x: 0, y: 0 }, width: r4.width, height: r4.height })) - ((r4.isNonPlatedHole ? this.minTraceToHoleEdgeClearance ?? this.obstacleMargin : this.obstacleMargin) - this.obstacleMargin);
      i3 = Math.min(i3, d2), d2 < o3 && this.lastCollidingObstacles.push(r4);
    }
    const a3 = this.hdRouteSHI.getConflictingRoutesForSegment(e36, t2, o3);
    for (const { conflictingRoute: r4 } of a3) {
      const s3 = r4, a4 = s3.rootConnectionName ?? s3.connectionName;
      if (a4 === n2)
        continue;
      if (this.connMap?.areIdsConnected(n2, a4))
        continue;
      let c3 = 1 / 0;
      for (let n3 = 0;n3 < s3.route.length - 1; n3++) {
        const o4 = s3.route[n3], i4 = s3.route[n3 + 1];
        o4.z === i4.z && o4.z === e36.z && (o4.insideJumperPad && i4.insideJumperPad || o4.toNextSegmentType !== "through_obstacle" && (c3 = Math.min(c3, we(e36, t2, o4, i4) - (o4.traceThickness ?? s3.traceThickness) / 2)));
      }
      for (const n3 of s3.vias)
        c3 = Math.min(c3, Te(e36, t2, { ...n3, radius: s3.viaDiameter / 2 }));
      i3 = Math.min(i3, c3), c3 < o3 && this.lastCollidingRoutes.push(s3);
    }
    return this.lastClearance = i3, i3;
  }
  isObstacleOnPointLayer(e36, t2) {
    return !e36.__zLayers || e36.__zLayers.includes(t2.z);
  }
  getAdjacentNonCoincidentRoutePoint(e36, t2) {
    const n2 = e36.route[t2];
    if (!n2)
      return;
    const o3 = t2 === 0 ? 1 : -1;
    for (let i3 = t2 + o3;i3 >= 0 && i3 < e36.route.length; i3 += o3) {
      const t3 = e36.route[i3];
      if (me(t3, n2) > JF)
        return t3;
    }
  }
  getObstacleWidthAlongVector(e36, t2) {
    const n2 = (e36.ccwRotationDegrees ?? 0) * Math.PI / 180, o3 = Math.cos(n2), i3 = Math.sin(n2), r3 = o3, s2 = i3, a3 = -i3, c3 = o3;
    return Math.abs(t2.x * r3 + t2.y * s2) * e36.width + Math.abs(t2.x * a3 + t2.y * c3) * e36.height;
  }
  getTerminalPadWidthLimit(e36, t2, n2) {
    const o3 = e36.route[t2];
    if (!o3)
      return;
    const i3 = this.getAdjacentNonCoincidentRoutePoint(e36, t2);
    if (!i3)
      return;
    const r3 = t2 === 0 ? Ae(o3, i3) : Ae(i3, o3);
    if (me(r3, { x: 0, y: 0 }) <= JF)
      return;
    const s2 = { x: -r3.y, y: r3.x };
    let a3;
    for (const t3 of this.obstacles) {
      if (!this.isObstacleOnPointLayer(t3, o3))
        continue;
      if (Oe(o3, t3) > JF)
        continue;
      if (!xo(t3, e36, this.connMap))
        continue;
      const n3 = this.getObstacleWidthAlongVector(t3, s2);
      if (n3 <= JF)
        continue;
      const i4 = this.getObstacleWidthAlongVector(t3, r3) / 2;
      (!a3 || n3 < a3.width || Math.abs(n3 - a3.width) <= JF && i4 > a3.neckDistance) && (a3 = { width: n3, neckDistance: i4 });
    }
    return !a3 || a3.width >= n2 - JF ? undefined : a3;
  }
  getRouteDistanceInfo(e36) {
    const t2 = [0];
    let n2 = 0;
    for (let o3 = 1;o3 < e36.length; o3++) {
      const i3 = e36[o3 - 1];
      n2 += me(e36[o3], i3), t2.push(n2);
    }
    return { distances: t2, totalDistance: n2 };
  }
  interpolateRoutePointAtDistance(e36, t2, n2) {
    for (let o3 = 1;o3 < e36.length; o3++) {
      const i3 = t2[o3 - 1], r3 = t2[o3], s2 = r3 - i3;
      if (n2 > r3 + JF)
        continue;
      const a3 = e36[o3 - 1], c3 = e36[o3];
      if (s2 <= JF)
        return { ...c3 };
      const l3 = Math.max(0, Math.min(1, (n2 - i3) / s2));
      return { x: a3.x + (c3.x - a3.x) * l3, y: a3.y + (c3.y - a3.y) * l3, z: a3.z };
    }
    return { ...e36[e36.length - 1] };
  }
  getTaperWidthAtDistance({ distanceFromStart: e36, totalDistance: t2, startLimit: n2, endLimit: o3, taperDistance: i3, traceWidth: r3 }) {
    let s2 = r3;
    if (n2 !== undefined && e36 <= i3) {
      const t3 = Math.min(n2.neckDistance, i3);
      if (e36 <= t3)
        s2 = Math.min(s2, n2.width);
      else {
        const o4 = (e36 - t3) / Math.max(i3 - t3, JF);
        s2 = Math.min(s2, n2.width + (r3 - n2.width) * o4);
      }
    }
    if (o3 !== undefined) {
      const n3 = t2 - e36;
      if (n3 <= i3) {
        const e37 = Math.min(o3.neckDistance, i3);
        if (n3 <= e37)
          s2 = Math.min(s2, o3.width);
        else {
          const t3 = (n3 - e37) / Math.max(i3 - e37, JF);
          s2 = Math.min(s2, o3.width + (r3 - o3.width) * t3);
        }
      }
    }
    return s2;
  }
  createTerminalTaperedRoute(e36, t2) {
    if (e36.route.length < 2)
      return e36.route.map((e37) => ({ ...e37, traceThickness: e37.traceThickness ?? t2 }));
    const n2 = this.getTerminalPadWidthLimit(e36, 0, t2), o3 = this.getTerminalPadWidthLimit(e36, e36.route.length - 1, t2), { distances: i3, totalDistance: r3 } = this.getRouteDistanceInfo(e36.route);
    if (r3 <= JF) {
      const i4 = Math.min(n2?.width ?? t2, o3?.width ?? t2);
      return e36.route.map((e37) => ({ ...e37, traceThickness: i4 }));
    }
    const s2 = Math.min(Math.max(2 * t2, 0.75), r3 / 2), a3 = i3.map((e37, t3) => ({ distanceFromStart: e37, originalPointIndex: t3 })), c3 = [];
    if (n2 !== undefined) {
      c3.push(n2.neckDistance);
      for (let e37 = 0;e37 <= 8; e37++)
        c3.push(s2 * e37 / 8);
    }
    if (o3 !== undefined) {
      c3.push(r3 - o3.neckDistance);
      for (let e37 = 0;e37 <= 8; e37++)
        c3.push(r3 - s2 + s2 * e37 / 8);
    }
    for (const e37 of c3) {
      const t3 = Math.max(0, Math.min(r3, e37));
      a3.some((e38) => Math.abs(e38.distanceFromStart - t3) <= JF) || a3.push({ distanceFromStart: t3 });
    }
    return a3.sort((e37, t3) => {
      const n3 = e37.distanceFromStart - t3.distanceFromStart;
      return Math.abs(n3) > JF ? n3 : (e37.originalPointIndex ?? 1 / 0) - (t3.originalPointIndex ?? 1 / 0);
    }), a3.map((a4) => {
      const { distanceFromStart: c4 } = a4, l3 = a4.originalPointIndex !== undefined ? { ...e36.route[a4.originalPointIndex] } : this.interpolateRoutePointAtDistance(e36.route, i3, c4);
      return l3.traceThickness = this.getTaperWidthAtDistance({ distanceFromStart: c4, totalDistance: r3, startLimit: n2, endLimit: o3, taperDistance: s2, traceWidth: t2 }), l3;
    });
  }
  createRouteWithWidth(e36, t2) {
    return { connectionName: e36.connectionName, rootConnectionName: e36.rootConnectionName, startPcbPortId: e36.startPcbPortId, endPcbPortId: e36.endPcbPortId, traceThickness: t2, viaDiameter: e36.viaDiameter, route: this.createTerminalTaperedRoute(e36, t2), vias: [...e36.vias], jumpers: e36.jumpers };
  }
  finalizeCurrentTrace(e36) {
    if (!this.currentTrace)
      return;
    const t2 = this.createRouteWithWidth(this.currentTrace, e36);
    this.processedRoutes.push(t2), this.hdRouteSHI.removeRoute(t2.connectionName), this.hdRouteSHI.addRoute(t2), this.currentTrace = null, this.cursorPosition = null, this.hasInsufficientClearance = false;
  }
  visualize() {
    const e36 = { lines: [], points: [], circles: [], rects: [], coordinateSystem: "cartesian", title: `Trace Width Solver (schedule: [${this.TRACE_WIDTH_SCHEDULE.map((e37) => e37.toFixed(2)).join(", ")}]mm, fallback: ${this.minTraceWidth.toFixed(2)}mm, margin: ${this.obstacleMargin.toFixed(2)}mm)` }, t2 = new Set(this.lastCollidingObstacles.map((e37) => e37.obstacleId)), n2 = new Set(this.lastCollidingRoutes.map((e37) => e37.connectionName));
    for (const n3 of this.obstacles) {
      const o3 = t2.has(n3.obstacleId), i3 = n3.__zLayers?.includes(0), r3 = n3.__zLayers?.includes(1);
      let s2;
      s2 = o3 ? "rgba(255, 0, 0, 0.6)" : i3 && r3 ? "rgba(128, 0, 128, 0.15)" : i3 ? "rgba(255, 0, 0, 0.15)" : r3 ? "rgba(0, 0, 255, 0.15)" : "rgba(128, 128, 128, 0.15)", e36.rects.push({ center: n3.center, width: n3.width, height: n3.height, fill: s2, stroke: o3 ? "red" : undefined, label: o3 ? `COLLIDING: ${n3.obstacleId ?? "obstacle"}` : `${n3.obstacleId ?? "obstacle"} (Z: ${n3.__zLayers?.join(", ")})` });
    }
    for (const t3 of this.processedRoutes) {
      if (t3.route.length === 0)
        continue;
      const n3 = t3.traceThickness === this.nominalTraceWidth, o3 = t3.traceThickness === this.TRACE_WIDTH_SCHEDULE[1], i3 = n3 ? "green" : o3 ? "yellow" : "orange";
      for (let n4 = 0;n4 < t3.route.length - 1; n4++) {
        const o4 = t3.route[n4], r3 = t3.route[n4 + 1];
        o4.insideJumperPad && r3.insideJumperPad || o4.z === r3.z && e36.lines.push({ points: [{ x: o4.x, y: o4.y }, { x: r3.x, y: r3.y }], strokeColor: i3, strokeWidth: o4.traceThickness ?? t3.traceThickness, label: `${t3.connectionName} (w=${(o4.traceThickness ?? t3.traceThickness).toFixed(2)})` });
      }
      for (const n4 of t3.vias)
        e36.circles.push({ center: { x: n4.x, y: n4.y }, radius: t3.viaDiameter / 2, fill: "rgba(255, 0, 255, 0.5)", label: `${t3.connectionName} via` });
      if (t3.jumpers && t3.jumpers.length > 0) {
        const n4 = fB(t3.jumpers, { color: i3, label: t3.connectionName });
        e36.rects.push(...n4.rects ?? []), e36.lines.push(...n4.lines ?? []);
      }
    }
    if (this.currentTrace) {
      for (let t3 = 0;t3 < this.currentTrace.route.length - 1; t3++) {
        const n3 = this.currentTrace.route[t3], o3 = this.currentTrace.route[t3 + 1];
        n3.insideJumperPad && o3.insideJumperPad || n3.z === o3.z && e36.lines.push({ points: [{ x: n3.x, y: n3.y }, { x: o3.x, y: o3.y }], strokeColor: "cyan", strokeWidth: this.currentTrace.traceThickness ?? this.minTraceWidth, label: `Processing: ${this.currentTrace.connectionName}` });
      }
      this.cursorPosition && (e36.circles.push({ center: { x: this.cursorPosition.x, y: this.cursorPosition.y }, radius: this.currentTargetWidth / 2, stroke: this.hasInsufficientClearance ? "red" : "green", fill: "none", label: `Testing width: ${this.currentTargetWidth.toFixed(2)}mm (clearance: ${this.lastClearance.toFixed(2)}mm)` }), e36.points.push({ x: this.cursorPosition.x, y: this.cursorPosition.y, color: "orange", label: "Cursor" }));
    }
    for (const t3 of this.unprocessedRoutes) {
      if (t3.route.length === 0)
        continue;
      const o3 = n2.has(t3.connectionName);
      for (let n3 = 0;n3 < t3.route.length - 1; n3++) {
        const i3 = t3.route[n3], r3 = t3.route[n3 + 1];
        i3.z === r3.z && e36.lines.push({ points: [{ x: i3.x, y: i3.y }, { x: r3.x, y: r3.y }], strokeColor: o3 ? "rgba(255, 0, 0, 0.8)" : "rgba(128, 128, 128, 0.3)", strokeWidth: t3.traceThickness ?? this.minTraceWidth, label: o3 ? `COLLIDING: ${t3.connectionName}` : t3.connectionName });
      }
    }
    return e36;
  }
  getHdRoutesWithWidths() {
    return this.hdRoutesWithWidths;
  }
};
function KF(e36, t2, n2, o3 = {}) {
  return { solverName: e36, solverClass: t2, getConstructorParams: n2, onSolved: o3.onSolved };
}
var ej = class extends ni {
  constructor(e36, t2 = {}) {
    super(), this.srj = e36, this.opts = t2, this.srj = e36, this.opts = { ...t2 }, this.viaDiameter = Yo(e36).padDiameter, this.minTraceWidth = e36.minTraceWidth;
    const n2 = this.opts;
    if (this.effort = n2.effort ?? 1, this.MAX_ITERATIONS = 1e8 * this.effort, n2.capacityDepth === undefined) {
      const t3 = e36.bounds.maxX - e36.bounds.minX, o3 = e36.bounds.maxY - e36.bounds.minY, i3 = Math.max(t3, o3), r3 = n2.targetMinCapacity ?? 0.5;
      n2.capacityDepth = Fz(i3, r3);
    }
    this.connMap = ei(e36), this.colorMap = Eo(e36, this.connMap), this.cacheProvider = n2.cacheProvider === undefined ? no() : n2.cacheProvider === null ? null : n2.cacheProvider, this.startTimeOfPhase = {}, this.endTimeOfPhase = {}, this.timeSpentOnPhase = {};
  }
  getSolverName() {
    return "AutoroutingPipelineSolver2_PortPointPathing";
  }
  netToPointPairsSolver;
  nodeSolver;
  nodeTargetMerger;
  edgeSolver;
  colorMap;
  highDensityRouteSolver;
  highDensityStitchSolver;
  singleLayerNodeMerger;
  strawSolver;
  deadEndSolver;
  traceSimplificationSolver;
  availableSegmentPointSolver;
  portPointPathingSolver;
  multiSectionPortPointOptimizer;
  uniformPortDistributionSolver;
  traceWidthSolver;
  viaDiameter;
  minTraceWidth;
  effort;
  startTimeOfPhase;
  endTimeOfPhase;
  timeSpentOnPhase;
  activeSubSolver = null;
  connMap;
  srjWithPointPairs;
  capacityNodes = null;
  capacityEdges = null;
  inputNodeWithPortPoints = [];
  cacheProvider = null;
  pipelineDef = [KF("netToPointPairsSolver", pB, (e36) => [e36.srj, e36.colorMap, ti(e36.srj)], { onSolved: (e36) => {
    e36.srjWithPointPairs = e36.netToPointPairsSolver?.getNewSimpleRouteJson(), e36.colorMap = Eo(e36.srjWithPointPairs, this.connMap), e36.connMap = ei(e36.srjWithPointPairs);
  } }), KF("nodeSolver", Jn, (e36) => [{ simpleRouteJson: e36.srjWithPointPairs, maxGapFillPasses: 4 }], { onSolved: (e36) => {
    e36.capacityNodes = e36.nodeSolver?.getOutput().meshNodes ?? [];
  } }), KF("edgeSolver", ui, (e36) => [e36.capacityNodes], { onSolved: (e36) => {
    e36.capacityEdges = e36.edgeSolver?.edges;
  } }), KF("availableSegmentPointSolver", ii, (e36) => [{ nodes: e36.capacityNodes, edges: e36.capacityEdges || [], traceWidth: e36.minTraceWidth, colorMap: e36.colorMap, shouldReturnCrampedPortPoints: false }]), KF("portPointPathingSolver", Kz, (e36) => {
    this.inputNodeWithPortPoints = e36.capacityNodes.map((e37) => ({ capacityMeshNodeId: e37.capacityMeshNodeId, center: e37.center, width: e37.width, height: e37.height, portPoints: [], availableZ: e37.availableZ, _containsTarget: e37._containsTarget, _containsObstacle: e37._containsObstacle }));
    const t2 = new Map(this.inputNodeWithPortPoints.map((e37) => [e37.capacityMeshNodeId, e37])), n2 = e36.availableSegmentPointSolver;
    for (const e37 of n2.sharedEdgeSegments)
      for (const n3 of e37.portPoints) {
        const [e38, o3] = n3.nodeIds, i3 = { portPointId: n3.segmentPortPointId, x: n3.x, y: n3.y, z: n3.availableZ[0] ?? 0, connectionNodeIds: [e38, o3], distToCentermostPortOnZ: n3.distToCentermostPortOnZ }, r3 = t2.get(e38);
        r3 && r3.portPoints.push(i3);
      }
    return [{ simpleRouteJson: e36.srjWithPointPairs, inputNodes: this.inputNodeWithPortPoints, capacityMeshNodes: e36.capacityNodes, colorMap: e36.colorMap, numShuffleSeeds: 200, hyperParameters: { NODE_PF_MAX_PENALTY: 100, FORCE_OFF_BOARD_FREQUENCY: 0, STRAIGHT_LINE_DEVIATION_PENALTY_FACTOR: 4 } }];
  }), KF("multiSectionPortPointOptimizer", nB, (e36) => {
    const t2 = e36.portPointPathingSolver;
    return [{ simpleRouteJson: e36.srjWithPointPairs, inputNodes: t2.inputNodes, capacityMeshNodes: e36.capacityNodes, capacityMeshEdges: e36.capacityEdges, colorMap: e36.colorMap, initialConnectionResults: t2.connectionsWithResults, initialAssignedPortPoints: t2.assignedPortPoints, initialNodeAssignedPortPoints: t2.nodeAssignedPortPoints, effort: Math.min(1, e36.effort) }];
  }), KF("uniformPortDistributionSolver", bo, (e36) => [{ nodeWithPortPoints: e36.multiSectionPortPointOptimizer?.getNodesWithPortPoints() ?? e36.portPointPathingSolver?.getNodesWithPortPoints() ?? [], inputNodesWithPortPoints: this.inputNodeWithPortPoints, minTraceWidth: e36.minTraceWidth, obstacles: e36.srj.obstacles, layerCount: e36.srj.layerCount }]), KF("highDensityRouteSolver", Dz, (e36) => [{ nodePortPoints: e36.uniformPortDistributionSolver?.getOutput() ?? e36.multiSectionPortPointOptimizer?.getNodesWithPortPoints() ?? e36.portPointPathingSolver?.getNodesWithPortPoints() ?? [], nodePfById: e36.multiSectionPortPointOptimizer?.nodePfMap ?? new Map((e36.portPointPathingSolver?.inputNodes ?? []).map((t2) => [t2.capacityMeshNodeId, e36.portPointPathingSolver?.computeNodePf(t2) ?? null])), colorMap: e36.colorMap, connMap: e36.connMap, viaDiameter: e36.viaDiameter, traceWidth: e36.minTraceWidth, effort: Math.min(1, e36.effort) }]), KF("highDensityStitchSolver", IB, (e36) => [{ connections: e36.srjWithPointPairs.connections, hdRoutes: e36.highDensityRouteSolver.routes, colorMap: e36.colorMap, layerCount: e36.srj.layerCount, defaultViaDiameter: e36.viaDiameter }]), KF("traceSimplificationSolver", WF, (e36) => [{ hdRoutes: e36.highDensityStitchSolver.mergedHdRoutes, obstacles: e36.srj.obstacles, connMap: e36.connMap, colorMap: e36.colorMap, outline: e36.srj.outline, defaultViaDiameter: e36.viaDiameter, layerCount: e36.srj.layerCount, iterations: 2 }]), KF("traceWidthSolver", QF, (e36) => [{ hdRoutes: e36.traceSimplificationSolver.simplifiedHdRoutes, obstacles: e36.srj.obstacles, connMap: e36.connMap, colorMap: e36.colorMap, minTraceWidth: e36.minTraceWidth, connection: e36.srj.connections, layerCount: e36.srj.layerCount }])];
  getConstructorParams() {
    return [this.srj, this.opts];
  }
  currentPipelineStepIndex = 0;
  _step() {
    const e36 = this.pipelineDef[this.currentPipelineStepIndex];
    if (!e36)
      return void (this.solved = true);
    if (this.activeSubSolver)
      return this.activeSubSolver.step(), void (this.activeSubSolver.solved ? (this.endTimeOfPhase[e36.solverName] = performance.now(), this.timeSpentOnPhase[e36.solverName] = this.endTimeOfPhase[e36.solverName] - this.startTimeOfPhase[e36.solverName], e36.onSolved?.(this), this.activeSubSolver = null, this.currentPipelineStepIndex++) : this.activeSubSolver.failed && (this.error = this.activeSubSolver?.error, this.failed = true, this.activeSubSolver = null));
    const t2 = e36.getConstructorParams(this);
    this.activeSubSolver = new e36.solverClass(...t2), this[e36.solverName] = this.activeSubSolver, this.timeSpentOnPhase[e36.solverName] = 0, this.startTimeOfPhase[e36.solverName] = performance.now();
  }
  solveUntilPhase(e36) {
    for (;this.getCurrentPhase() !== e36; )
      this.step();
  }
  getCurrentPhase() {
    return this.pipelineDef[this.currentPipelineStepIndex]?.solverName ?? "none";
  }
  visualize() {
    if (!this.solved && this.activeSubSolver)
      return this.activeSubSolver.visualize();
    const e36 = this.netToPointPairsSolver?.visualize(), t2 = this.nodeSolver?.visualize(), n2 = this.nodeTargetMerger?.visualize(), o3 = this.singleLayerNodeMerger?.visualize(), i3 = this.strawSolver?.visualize(), r3 = this.edgeSolver?.visualize(), s2 = this.deadEndSolver?.visualize(), a3 = this.availableSegmentPointSolver?.visualize(), c3 = this.portPointPathingSolver?.visualize(), l3 = this.multiSectionPortPointOptimizer?.visualize(), h2 = this.uniformPortDistributionSolver?.visualize(), d2 = this.highDensityRouteSolver?.visualize(), u2 = this.highDensityStitchSolver?.visualize(), p3 = this.traceSimplificationSolver?.visualize(), m2 = this.srj.outline, g2 = [];
    if (g2.push({ points: [{ x: this.srj.bounds?.minX ?? -50, y: this.srj.bounds?.minY ?? -50 }, { x: this.srj.bounds?.maxX ?? 50, y: this.srj.bounds?.minY ?? -50 }, { x: this.srj.bounds?.maxX ?? 50, y: this.srj.bounds?.maxY ?? 50 }, { x: this.srj.bounds?.minX ?? -50, y: this.srj.bounds?.maxY ?? 50 }, { x: this.srj.bounds?.minX ?? -50, y: this.srj.bounds?.minY ?? -50 }], strokeColor: "rgba(255,0,0,0.25)" }), m2 && m2.length >= 2) {
      const e37 = m2.map((e38) => ({ x: e38.x, y: e38.y }));
      e37.push({ ...e37[0] }), g2.push({ points: e37, strokeColor: "rgba(0, 136, 255, 0.95)" });
    }
    const f2 = Lo(this.srj), _2 = { points: [...this.srj.connections.flatMap((e37) => e37.pointsToConnect.map((t3) => ({ ...t3, layer: Bo(t3, this.srj.layerCount), label: `${e37.name} ${t3.pcb_port_id ?? ""}` })))], rects: [...(this.srj.obstacles ?? []).filter((e37) => !e37.isCopperPour).map((e37) => ({ ...e37, fill: e37.layers?.includes("top") ? "rgba(255,0,0,0.25)" : e37.layers?.includes("bottom") ? "rgba(0,0,255,0.25)" : "rgba(255,0,0,0.25)", layer: jo(e37, this.srj.layerCount), label: f2(e37) }))], lines: g2 }, y2 = [_2, e36, t2, n2, o3, i3, r3, s2, a3, c3, l3, h2, d2 ? pi(_2, d2) : null, u2, p3, this.solved ? pi({ lines: g2 }, Wo(this.getOutputSimpleRouteJson())) : null].filter(Boolean);
    return pi(...y2);
  }
  preview() {
    if (this.highDensityRouteSolver) {
      const e36 = [];
      for (let t2 = this.highDensityRouteSolver.routes.length - 1;t2 >= 0; t2--) {
        const n2 = this.highDensityRouteSolver.routes[t2];
        if (e36.push({ points: n2.route.map((e37) => ({ x: e37.x, y: e37.y })), strokeColor: this.colorMap[n2.connectionName] }), e36.length > 200)
          break;
      }
      return { lines: e36 };
    }
    if (this.portPointPathingSolver) {
      const e36 = [];
      for (const t2 of this.portPointPathingSolver.connectionsWithResults)
        t2.path && e36.push({ points: t2.path.map((e37) => ({ x: e37.point.x, y: e37.point.y })), strokeColor: this.colorMap[t2.connection.name] });
      return { lines: e36 };
    }
    return this.netToPointPairsSolver ? this.netToPointPairsSolver?.visualize() : {};
  }
  _getOutputHdRoutes() {
    return this.traceWidthSolver?.getHdRoutesWithWidths() ?? this.traceSimplificationSolver?.simplifiedHdRoutes ?? this.highDensityStitchSolver.mergedHdRoutes;
  }
  getOutputSimplifiedPcbTraces() {
    if (!this.solved || !this.highDensityRouteSolver)
      throw new Error("Cannot get output before solving is complete");
    const e36 = [], t2 = this._getOutputHdRoutes();
    for (const n2 of this.netToPointPairsSolver?.newConnections ?? []) {
      const o3 = n2.__netConnectionName ?? this.srj.connections.find((e37) => e37.name === n2.name)?.__netConnectionName, i3 = t2.filter((e37) => e37.connectionName === n2.name);
      for (let t3 = 0;t3 < i3.length; t3++) {
        const r3 = i3[t3], s2 = { type: "pcb_trace", pcb_trace_id: `${n2.name}_${t3}`, connection_name: o3 ?? n2.__rootConnectionNames?.[0] ?? n2.name, route: Ro(r3, this.srj.layerCount) };
        e36.push(s2);
      }
    }
    return e36;
  }
  getOutputSimpleRouteJson() {
    return { ...this.srj, traces: this.getOutputSimplifiedPcbTraces() };
  }
};
var nj = class extends ni {
  getSolverName() {
    return "CapacityEdgeToPortSegmentSolver";
  }
  nodes;
  edges;
  capacityPaths;
  nodeMap;
  nodeEdgeMap;
  unprocessedNodeIds;
  nodePortSegments;
  colorMap;
  constructor({ nodes: e36, edges: t2, capacityPaths: n2, colorMap: o3 }) {
    super(), this.nodes = e36, this.edges = t2, this.nodeMap = new Map(e36.map((e37) => [e37.capacityMeshNodeId, e37])), this.nodeEdgeMap = oi(t2), this.capacityPaths = n2, this.colorMap = o3 ?? {}, this.unprocessedNodeIds = [...new Set(n2.flatMap((e37) => e37.nodeIds))], this.nodePortSegments = new Map;
  }
  step() {
    const e36 = this.unprocessedNodeIds.pop();
    if (!e36)
      return void (this.solved = true);
    const t2 = [];
    for (const n3 of this.capacityPaths) {
      const o4 = n3.nodeIds.indexOf(e36);
      o4 !== -1 && t2.push({ path: n3, indexOfNodeInPath: o4 });
    }
    const n2 = this.nodeMap.get(e36), o3 = [];
    for (const { path: i4, indexOfNodeInPath: r3 } of t2) {
      const t3 = i4.nodeIds[r3 - 1], s2 = i4.nodeIds[r3 + 1];
      for (const r4 of [t3, s2]) {
        const t4 = this.nodeMap.get(r4);
        if (!t4)
          continue;
        const s3 = oj(n2, t4), a3 = t4.availableZ.filter((e37) => n2.availableZ.includes(e37));
        if (a3.length === 0)
          continue;
        const c3 = { capacityMeshNodeId: e36, start: s3.start, end: s3.end, connectionNames: [i4.connectionName], rootConnectionNames: i4.rootConnectionName ? [i4.rootConnectionName] : undefined, availableZ: a3 };
        o3.push(c3);
      }
    }
    const i3 = function(e37) {
      const t3 = [], n3 = e37.map((e38) => ({ ...e38, connectionNames: [...e38.connectionNames], rootConnectionNames: e38.rootConnectionNames ? [...e38.rootConnectionNames] : [], availableZ: [...e38.availableZ].sort((e39, t4) => e39 - t4) }));
      for (;n3.length > 0; ) {
        const e38 = n3.pop();
        let o4 = false;
        for (let n4 = 0;n4 < t3.length; n4++) {
          const i4 = t3[n4], r3 = rj(i4.start, e38.start) && rj(i4.end, e38.end) || rj(i4.start, e38.end) && rj(i4.end, e38.start), s2 = sj(i4.availableZ, e38.availableZ);
          if (r3 && s2) {
            const t4 = new Set(i4.connectionNames);
            e38.connectionNames.forEach((e39) => t4.add(e39)), i4.connectionNames = Array.from(t4);
            const n5 = new Set(i4.rootConnectionNames || []);
            e38.rootConnectionNames?.forEach((e39) => n5.add(e39)), i4.rootConnectionNames = Array.from(n5), o4 = true;
            break;
          }
        }
        o4 || t3.push(e38);
      }
      return t3;
    }(o3);
    this.nodePortSegments.set(e36, i3);
  }
  visualize() {
    const e36 = { lines: [], points: [], rects: [], circles: [] };
    return this.nodePortSegments.forEach((t2, n2) => {
      this.nodeMap.get(n2);
      t2.forEach((t3) => {
        t3.start.x, t3.end.x;
        for (let o3 = 0;o3 < t3.connectionNames.length; o3++) {
          const i3 = { x: 0.05 * Math.max(...t3.availableZ), y: 0.05 * Math.max(...t3.availableZ) }, r3 = { x: (t3.start.x + t3.end.x) / 2, y: (t3.start.y + t3.end.y) / 2 }, s2 = { x: r3.x + i3.x, y: r3.y + i3.y };
          i3.x > 0 && e36.lines.push({ points: [r3, s2], strokeColor: "rgba(0, 0, 0, 0.25)", strokeDash: "5 5" }), e36.points.push({ x: s2.x, y: s2.y, label: `${n2}: ${t3.connectionNames.join(", ")}
availableZ: ${t3.availableZ.join(",")}
nodePortSegmentId: ${t3.nodePortSegmentId}` }), e36.lines.push({ points: [t3.start, t3.end], strokeColor: Ao(this.colorMap[t3.connectionNames[o3]], 0.6) });
        }
      });
    }), e36;
  }
};
function oj(e36, t2) {
  const n2 = { start: Math.max(e36.center.x - e36.width / 2, t2.center.x - t2.width / 2), end: Math.min(e36.center.x + e36.width / 2, t2.center.x + t2.width / 2) }, o3 = { start: Math.max(e36.center.y - e36.height / 2, t2.center.y - t2.height / 2), end: Math.min(e36.center.y + e36.height / 2, t2.center.y + t2.height / 2) };
  if (n2.end - n2.start < o3.end - o3.start) {
    const e37 = (n2.start + n2.end) / 2;
    return { start: { x: e37, y: o3.start }, end: { x: e37, y: o3.end } };
  }
  {
    const e37 = (o3.start + o3.end) / 2;
    return { start: { x: n2.start, y: e37 }, end: { x: n2.end, y: e37 } };
  }
}
var ij = 0.000000001;
function rj(e36, t2) {
  return Math.abs(e36.x - t2.x) < ij && Math.abs(e36.y - t2.y) < ij;
}
function sj(e36, t2) {
  if (e36.length !== t2.length)
    return false;
  for (let n2 = 0;n2 < e36.length; n2++)
    if (e36[n2] !== t2[n2])
      return false;
  return true;
}
var aj = class {
  constructor(e36) {
    this.targets = e36, this.buckets = new Map;
    for (let t2 = 0;t2 < e36.length; t2++) {
      const n2 = e36[t2], o3 = Math.floor(n2.bounds.minX / this.CELL_SIZE) * this.CELL_SIZE, i3 = Math.floor(n2.bounds.minY / this.CELL_SIZE) * this.CELL_SIZE, r3 = n2.bounds.maxX, s2 = n2.bounds.maxY;
      for (let e37 = o3;e37 <= r3; e37 += this.CELL_SIZE)
        for (let o4 = i3;o4 <= s2; o4 += this.CELL_SIZE) {
          const i4 = this.getBucketKey(e37, o4), r4 = this.buckets.get(i4);
          r4 ? r4.push([n2, t2]) : this.buckets.set(i4, [[n2, t2]]);
        }
    }
  }
  buckets;
  CELL_SIZE = 5;
  getBucketKey(e36, t2) {
    return `${Math.floor(e36 / this.CELL_SIZE)}x${Math.floor(t2 / this.CELL_SIZE)}`;
  }
  getTargetsInArea(e36, t2, n2, o3) {
    const i3 = [], r3 = new Set, s2 = Math.floor((e36 - n2 / 2) / this.CELL_SIZE) * this.CELL_SIZE, a3 = Math.floor((t2 - o3 / 2) / this.CELL_SIZE) * this.CELL_SIZE, c3 = e36 + n2 / 2, l3 = t2 + o3 / 2;
    for (let e37 = s2;e37 <= c3; e37 += this.CELL_SIZE)
      for (let t3 = a3;t3 <= l3; t3 += this.CELL_SIZE) {
        const n3 = this.getBucketKey(e37, t3), o4 = this.buckets.get(n3) || [];
        for (const e38 of o4)
          r3.has(e38[1]) || (r3.add(e38[1]), i3.push(e38[0]));
      }
    return i3;
  }
};
var cj = class extends ni {
  constructor(e36, t2 = {}) {
    super(), this.srj = e36, this.opts = t2, this.MAX_DEPTH = t2?.capacityDepth ?? this.MAX_DEPTH, this.MAX_ITERATIONS = 1e5, this.layerCount = e36.layerCount ?? 2, this.outlinePolygon = e36.outline && e36.outline.length >= 3 ? e36.outline : undefined;
    const n2 = { x: (e36.bounds.minX + e36.bounds.maxX) / 2, y: (e36.bounds.minY + e36.bounds.maxY) / 2 }, o3 = { width: e36.bounds.maxX - e36.bounds.minX, height: e36.bounds.maxY - e36.bounds.minY }, i3 = Math.max(o3.width, o3.height);
    this.unfinishedNodes = [{ capacityMeshNodeId: this.getNextNodeId(), center: n2, width: i3, height: i3, layer: "top", availableZ: Array.from({ length: this.layerCount }, (e37, t3) => t3), _depth: 0, _containsTarget: true, _containsObstacle: true, _completelyInsideObstacle: false }], this.finishedNodes = [], this.nodeToXYOverlappingObstaclesMap = new Map, this.obstacleZLayersByObstacle = new WeakMap;
    const r3 = ca(this.srj.obstacles, this.layerCount);
    for (const [e37, t3] of this.srj.obstacles.entries())
      this.obstacleZLayersByObstacle.set(t3, r3[e37].__zLayers);
    this.obstacleTree = new ZF("flatbush", this.srj.obstacles), this.targets = this.computeTargets(), this.targetTree = new aj(this.targets);
  }
  getSolverName() {
    return "CapacityMeshNodeSolver";
  }
  unfinishedNodes;
  finishedNodes;
  nodeToXYOverlappingObstaclesMap;
  layerCount;
  outlinePolygon;
  MAX_DEPTH = 4;
  targets;
  targetTree;
  obstacleTree;
  obstacleZLayersByObstacle;
  computeTargets() {
    const e36 = [];
    for (const t2 of this.srj.connections)
      for (const n2 of t2.pointsToConnect) {
        const o3 = So(n2), i3 = this.obstacleTree.searchArea(n2.x, n2.y, 0.01, 0.01).filter((e37) => {
          const t3 = this.getObstacleZLayers(e37);
          return !(!t3 || t3.length === 0) && t3.some((e38) => o3.some((t4) => e38 === mo(t4, this.layerCount)));
        });
        let r3 = { minX: n2.x - 0.005, minY: n2.y - 0.005, maxX: n2.x + 0.005, maxY: n2.y + 0.005 };
        i3.length > 0 && (r3 = { minX: Math.min(...i3.map((e37) => e37.center.x - e37.width / 2)), minY: Math.min(...i3.map((e37) => e37.center.y - e37.height / 2)), maxX: Math.max(...i3.map((e37) => e37.center.x + e37.width / 2)), maxY: Math.max(...i3.map((e37) => e37.center.y + e37.height / 2)) });
        const s2 = { ...n2, connectionName: t2.name, availableZ: o3.map((e37) => mo(e37, this.layerCount)), bounds: r3 };
        e36.push(s2);
      }
    return e36;
  }
  getNodeBounds(e36) {
    const t2 = e36.width / 2, n2 = e36.height / 2;
    return { minX: e36.center.x - t2, maxX: e36.center.x + t2, minY: e36.center.y - n2, maxY: e36.center.y + n2 };
  }
  getNodeRect(e36) {
    return { center: { x: e36.center.x, y: e36.center.y }, width: e36.width, height: e36.height };
  }
  _nextNodeCounter = 0;
  getNextNodeId() {
    return "cn" + this._nextNodeCounter++;
  }
  getCapacityFromDepth(e36) {
    return (this.MAX_DEPTH - e36 + 1) ** 2;
  }
  getTargetIfNodeContainsTarget(e36) {
    const t2 = e36.width > 4 * this.targetTree.CELL_SIZE ? this.targets : this.targetTree.getTargetsInArea(e36.center.x, e36.center.y, e36.width, e36.height);
    for (const n2 of t2)
      if (n2.bounds.minX <= e36.center.x + e36.width / 2 && n2.bounds.maxX >= e36.center.x - e36.width / 2 && n2.bounds.minY <= e36.center.y + e36.height / 2 && n2.bounds.maxY >= e36.center.y - e36.height / 2 && n2.availableZ.some((t3) => e36.availableZ.includes(t3)))
        return n2;
    return null;
  }
  getXYOverlappingObstacles(e36) {
    const t2 = this.nodeToXYOverlappingObstaclesMap.get(e36.capacityMeshNodeId);
    if (t2)
      return t2;
    const n2 = [], o3 = this.getNodeBounds(e36), i3 = o3.minX, r3 = o3.maxX, s2 = o3.minY, a3 = o3.maxY, c3 = e36._parent ? this.getXYOverlappingObstacles(e36._parent) : this.srj.obstacles;
    for (const e37 of c3) {
      const t3 = e37.center.x - e37.width / 2, o4 = e37.center.x + e37.width / 2, c4 = e37.center.y - e37.height / 2, l3 = e37.center.y + e37.height / 2;
      r3 >= t3 && i3 <= o4 && a3 >= c4 && s2 <= l3 ? n2.push(e37) : (i3 >= t3 && r3 <= o4 && s2 >= c4 && a3 <= l3 || t3 >= i3 && o4 <= r3 && c4 >= s2 && l3 <= a3) && n2.push(e37);
    }
    return this.nodeToXYOverlappingObstaclesMap.set(e36.capacityMeshNodeId, n2), n2;
  }
  getXYZOverlappingObstacles(e36) {
    const t2 = this.getXYOverlappingObstacles(e36), n2 = [];
    for (const o3 of t2)
      e36.availableZ.some((e37) => this.getObstacleZLayers(o3).includes(e37)) && n2.push(o3);
    return n2;
  }
  doesNodeOverlapObstacle(e36) {
    if (this.getXYZOverlappingObstacles(e36).length > 0)
      return true;
    const t2 = this.getNodeBounds(e36);
    if (this.outlinePolygon) {
      const t3 = this.getNodeRect(e36);
      if (!Ce(t3, this.outlinePolygon))
        return true;
    }
    return t2.minX < this.srj.bounds.minX || t2.maxX > this.srj.bounds.maxX || t2.minY < this.srj.bounds.minY || t2.maxY > this.srj.bounds.maxY;
  }
  isNodeCompletelyInsideObstacle(e36) {
    const t2 = this.getXYZOverlappingObstacles(e36), n2 = this.getNodeBounds(e36);
    if (this.outlinePolygon) {
      const t3 = this.getNodeRect(e36);
      if (!Se(t3, this.outlinePolygon))
        return true;
    }
    for (const e37 of t2) {
      const t3 = e37.center.x - e37.width / 2, o3 = e37.center.x + e37.width / 2, i3 = e37.center.y - e37.height / 2, r3 = e37.center.y + e37.height / 2;
      if (n2.minX >= t3 && n2.maxX <= o3 && n2.minY >= i3 && n2.maxY <= r3)
        return true;
    }
    return false;
  }
  getChildNodes(e36) {
    if (e36._depth === this.MAX_DEPTH)
      return [];
    const t2 = [], n2 = { width: e36.width / 2, height: e36.height / 2 }, o3 = [{ x: e36.center.x - n2.width / 2, y: e36.center.y - n2.height / 2 }, { x: e36.center.x + n2.width / 2, y: e36.center.y - n2.height / 2 }, { x: e36.center.x - n2.width / 2, y: e36.center.y + n2.height / 2 }, { x: e36.center.x + n2.width / 2, y: e36.center.y + n2.height / 2 }];
    for (const i3 of o3) {
      const o4 = { capacityMeshNodeId: this.getNextNodeId(), center: i3, width: n2.width, height: n2.height, layer: e36.layer, availableZ: e36.availableZ, _depth: (e36._depth ?? 0) + 1, _parent: e36 };
      o4._containsObstacle = this.doesNodeOverlapObstacle(o4);
      const r3 = this.getTargetIfNodeContainsTarget(o4);
      r3 && (o4._targetConnectionName = r3.connectionName, o4.availableZ = r3.availableZ, o4._containsTarget = true), o4._containsObstacle && (o4._completelyInsideObstacle = this.isNodeCompletelyInsideObstacle(o4)), o4._completelyInsideObstacle && !o4._containsTarget || t2.push(o4);
    }
    return t2;
  }
  shouldNodeBeXYSubdivided(e36) {
    return !(e36._depth >= this.MAX_DEPTH) && (!!e36._containsTarget || !(!e36._containsObstacle || e36._completelyInsideObstacle));
  }
  _step() {
    const e36 = this.unfinishedNodes.pop();
    if (!e36)
      return void (this.solved = true);
    const t2 = this.getChildNodes(e36), n2 = [], o3 = [];
    for (const e37 of t2) {
      const t3 = this.shouldNodeBeXYSubdivided(e37);
      t3 ? o3.push(e37) : t3 || e37._containsObstacle ? !t3 && e37._containsTarget && n2.push(e37) : n2.push(e37);
    }
    this.unfinishedNodes.push(...o3), this.finishedNodes.push(...n2);
  }
  visualize() {
    const e36 = { lines: [], points: [], rects: [], circles: [], coordinateSystem: "cartesian", title: "Capacity Mesh Visualization" };
    if (this.outlinePolygon && this.outlinePolygon.length >= 2) {
      const t3 = this.outlinePolygon.map((e37) => ({ x: e37.x, y: e37.y }));
      t3.push({ ...t3[0] }), e36.lines.push({ points: t3, strokeColor: "rgba(0, 136, 255, 0.95)", label: "outline" });
      for (const t4 of this.outlinePolygon)
        e36.points.push({ x: t4.x, y: t4.y, color: "rgba(0, 136, 255, 0.95)" });
    }
    for (const t3 of this.srj.obstacles) {
      if (t3.isCopperPour)
        continue;
      const n2 = this.getObstacleZLayers(t3);
      e36.rects.push({ center: t3.center, width: t3.width, height: t3.height, fill: n2.length === 1 && n2.includes(1) ? "rgba(0,0,255,0.3)" : "rgba(255,0,0,0.3)", stroke: "red", label: ["obstacle", `z: ${n2.join(",")}`].join(`
`) });
    }
    const t2 = [...this.finishedNodes, ...this.unfinishedNodes];
    for (const n2 of t2) {
      const t3 = Math.min(...n2.availableZ), o3 = this.unfinishedNodes.length > 0 && n2 === this.unfinishedNodes[this.unfinishedNodes.length - 1];
      e36.rects.push({ center: { x: n2.center.x + t3 * n2.width * 0.05, y: n2.center.y - t3 * n2.width * 0.05 }, width: Math.max(n2.width - 2, 0.8 * n2.width), height: Math.max(n2.height - 2, 0.8 * n2.height), fill: n2._containsObstacle ? "rgba(255,0,0,0.1)" : { "0,1": "rgba(0,0,0,0.1)", 0: "rgba(0,200,200, 0.1)", 1: "rgba(0,0,200, 0.1)" }[n2.availableZ.join(",")] ?? "rgba(0,200,200,0.1)", stroke: o3 ? "rgba(255,165,0,0.5)" : undefined, label: [n2.capacityMeshNodeId, `availableZ: ${n2.availableZ.join(",")}`, `target? ${n2._containsTarget ?? false}`, `obs? ${n2._containsObstacle ?? false}`, `${n2.width.toFixed(2)}x${n2.height.toFixed(2)}`, `capacity: ${Bz(n2).toFixed(2)}`].join(`
`) });
    }
    return e36.rects.sort((e37, t3) => e37.center.y - t3.center.y), this.srj.connections.forEach((t3, n2) => {
      const o3 = To[n2 % To.length];
      for (const i3 of t3.pointsToConnect) {
        const t4 = So(i3);
        e36.points.push({ x: i3.x, y: i3.y, label: `conn-${n2} (${t4.join(",")})`, color: o3 });
      }
    }), e36;
  }
  getObstacleZLayers(e36) {
    return this.obstacleZLayersByObstacle.get(e36) ?? [];
  }
};
var lj = class extends cj {
  constructor(e36, t2 = {}) {
    super(e36, t2), this.srj = e36, this.opts = t2, this.VIA_DIAMETER = Yo(e36).padDiameter;
  }
  getSolverName() {
    return "CapacityMeshNodeSolver2_NodeUnderObstacle";
  }
  VIA_DIAMETER = 0.6;
  OBSTACLE_MARGIN = 0.1;
  OVERLAP_THRESHOLD_FOR_SINGLE_LAYER_NODES = 0.2;
  isNodeCompletelyOutsideBounds(e36) {
    if (this.outlinePolygon) {
      const t2 = this.getNodeRect(e36);
      if (!Se(t2, this.outlinePolygon))
        return true;
    }
    return e36.center.x + e36.width / 2 < this.srj.bounds.minX || e36.center.x - e36.width / 2 > this.srj.bounds.maxX || e36.center.y + e36.height / 2 < this.srj.bounds.minY || e36.center.y - e36.height / 2 > this.srj.bounds.maxY;
  }
  isNodePartiallyOutsideBounds(e36) {
    if (this.outlinePolygon) {
      const t2 = this.getNodeRect(e36);
      return !!Se(t2, this.outlinePolygon) && !Ce(t2, this.outlinePolygon);
    }
    return e36.center.x - e36.width / 2 < this.srj.bounds.minX || e36.center.x + e36.width / 2 > this.srj.bounds.maxX || e36.center.y - e36.height / 2 < this.srj.bounds.minY || e36.center.y + e36.height / 2 > this.srj.bounds.maxY;
  }
  getObstacleCoveragePercentage(e36) {
    const t2 = this.getXYZOverlappingObstacles(e36);
    if (t2.length === 0)
      return 0;
    const n2 = e36.center.x - e36.width / 2, o3 = e36.center.x + e36.width / 2, i3 = e36.center.y - e36.height / 2, r3 = e36.center.y + e36.height / 2, s2 = e36.width * e36.height;
    let a3 = 0;
    for (const e37 of t2) {
      const t3 = Math.max(n2, e37.center.x - e37.width / 2), s3 = Math.min(o3, e37.center.x + e37.width / 2), c3 = Math.max(i3, e37.center.y - e37.height / 2), l3 = Math.min(r3, e37.center.y + e37.height / 2);
      if (t3 < s3 && c3 < l3) {
        a3 += (s3 - t3) * (l3 - c3);
      }
    }
    return a3 / s2;
  }
  shouldFilterSingleLayerNodeForObstacle(e36) {
    if (e36.availableZ.length !== 1)
      return false;
    if (!e36._containsObstacle)
      return false;
    return this.getObstacleCoveragePercentage(e36) > this.OVERLAP_THRESHOLD_FOR_SINGLE_LAYER_NODES;
  }
  shouldFilterNodeForObstacle(e36) {
    return !!e36._containsObstacle && (e36.availableZ.length !== 1 || this.shouldFilterSingleLayerNodeForObstacle(e36));
  }
  createChildNodeAtPosition(e36, t2) {
    const n2 = { capacityMeshNodeId: this.getNextNodeId(), center: t2.center, width: t2.width, height: t2.height, layer: e36.layer, availableZ: t2.availableZ, _depth: t2._depth ?? (e36._depth ?? 0) + 1, _parent: e36 }, o3 = this.getXYZOverlappingObstacles(n2);
    n2._containsObstacle = o3.length > 0 || this.isNodePartiallyOutsideBounds(n2);
    const i3 = this.getTargetIfNodeContainsTarget(n2);
    return i3 && (n2._targetConnectionName = i3.connectionName, n2._containsTarget = true), n2._containsObstacle && (n2._completelyInsideObstacle = this.isNodeCompletelyInsideObstacle(n2)), n2;
  }
  getZSubdivisionChildNodes(e36) {
    if (e36.availableZ.length === 1)
      return [];
    const t2 = [], n2 = e36.availableZ.map((e37) => [e37]);
    for (const o3 of n2) {
      const n3 = this.createChildNodeAtPosition(e36, { center: { ...e36.center }, width: e36.width, height: e36.height, availableZ: o3, _depth: e36._depth });
      this.isNodeCompletelyOutsideBounds(n3) || t2.push(n3);
    }
    return t2;
  }
  getChildNodes(e36) {
    if (e36._depth >= this.MAX_DEPTH)
      return [];
    const t2 = [], n2 = { width: e36.width / 2, height: e36.height / 2 }, o3 = [{ x: e36.center.x - n2.width / 2, y: e36.center.y - n2.height / 2 }, { x: e36.center.x + n2.width / 2, y: e36.center.y - n2.height / 2 }, { x: e36.center.x - n2.width / 2, y: e36.center.y + n2.height / 2 }, { x: e36.center.x + n2.width / 2, y: e36.center.y + n2.height / 2 }];
    for (const i3 of o3) {
      const o4 = this.createChildNodeAtPosition(e36, { center: i3, width: n2.width, height: n2.height, availableZ: e36.availableZ });
      this.isNodeCompletelyOutsideBounds(o4) || t2.push(o4);
    }
    return t2;
  }
  shouldNodeBeXYSubdivided(e36) {
    return !(e36._depth >= this.MAX_DEPTH) && (!!e36._containsTarget || (e36.availableZ.length === 1 && e36._depth <= this.MAX_DEPTH || !(!e36._containsObstacle || e36._completelyInsideObstacle)));
  }
  _step() {
    const e36 = this.unfinishedNodes.pop();
    if (!e36)
      return void (this.solved = true);
    const t2 = this.getChildNodes(e36), n2 = [], o3 = [];
    for (const e37 of t2) {
      const t3 = this.shouldNodeBeXYSubdivided(e37), i3 = e37.availableZ.length > 1 && !t3 && (e37._containsObstacle || e37.width < this.VIA_DIAMETER + this.OBSTACLE_MARGIN);
      if (t3)
        o3.push(e37);
      else if (t3 || this.shouldFilterNodeForObstacle(e37) || i3)
        if (!t3 && e37._containsTarget)
          if (i3) {
            const t4 = this.getZSubdivisionChildNodes(e37);
            n2.push(...t4.filter((e38) => e38._containsTarget || !this.shouldFilterNodeForObstacle(e38)));
          } else
            n2.push(e37);
        else
          i3 && n2.push(...this.getZSubdivisionChildNodes(e37).filter((e38) => !this.shouldFilterNodeForObstacle(e38)));
      else
        n2.push(e37);
    }
    this.unfinishedNodes.push(...o3), this.finishedNodes.push(...n2);
  }
};
var hj = class extends ni {
  getSolverName() {
    return "CapacitySegmentToPointSolver";
  }
  unsolvedSegments;
  solvedSegments;
  nodeMap;
  colorMap;
  constructor({ segments: e36, colorMap: t2, nodes: n2 }) {
    super(), this.MAX_ITERATIONS = 1e5, this.unsolvedSegments = e36, this.solvedSegments = [], this.colorMap = t2 ?? {}, this.nodeMap = Object.fromEntries(n2.map((e37) => [e37.capacityMeshNodeId, e37]));
  }
  _step() {
    let e36 = false;
    const t2 = [...this.unsolvedSegments];
    for (const n2 of t2) {
      const t3 = n2.connectionNames.length;
      if ((!("assignedPoints" in n2) || n2.assignedPoints?.length !== t3) && t3 === 1) {
        const t4 = { x: (n2.start.x + n2.end.x) / 2, y: (n2.start.y + n2.end.y) / 2, z: n2.availableZ[0] };
        n2.assignedPoints = [{ connectionName: n2.connectionNames[0], rootConnectionName: n2.rootConnectionNames?.[0], point: t4 }], this.unsolvedSegments.splice(this.unsolvedSegments.indexOf(n2), 1), this.solvedSegments.push(n2), e36 = true;
      }
    }
    if (!e36 && t2.length > 0) {
      let n2 = t2[0];
      for (const e37 of t2)
        e37.connectionNames.length < n2.connectionNames.length && (n2 = e37);
      const o3 = [...n2.connectionNames].sort(), i3 = n2.end.x - n2.start.x, r3 = n2.end.y - n2.start.y, s2 = o3.length, a3 = [];
      for (let e37 = 1;e37 <= s2; e37++) {
        const t3 = e37 / (s2 + 1);
        a3.push({ x: n2.start.x + i3 * t3, y: n2.start.y + r3 * t3, z: n2.availableZ[0] });
      }
      n2.assignedPoints = o3.map((e37, t3) => ({ connectionName: e37, rootConnectionName: n2.rootConnectionNames?.[n2.connectionNames.indexOf(e37)], point: a3[t3] })), this.unsolvedSegments.splice(this.unsolvedSegments.indexOf(n2), 1), this.solvedSegments.push(n2), e36 = true;
    }
    this.unsolvedSegments.length === 0 && (this.solved = true);
  }
  getNodesWithPortPoints() {
    if (!this.solved)
      throw new Error("CapacitySegmentToPointSolver not solved, can't give port points yet");
    const e36 = new Map;
    for (const t2 of this.solvedSegments) {
      const n2 = t2.capacityMeshNodeId, o3 = this.nodeMap[n2];
      e36.has(n2) || e36.set(n2, { capacityMeshNodeId: n2, portPoints: [], center: o3.center, width: o3.width, height: o3.height }), e36.get(n2).portPoints.push(...t2.assignedPoints.map((e37) => ({ ...e37.point, connectionName: e37.connectionName })));
    }
    return Array.from(e36.values());
  }
  visualize() {
    const e36 = { points: [], lines: this.solvedSegments.map((e37) => ({ points: [e37.start, e37.end], step: 4 })), rects: [], circles: [], coordinateSystem: "cartesian", title: "Capacity Segment to Point Solver" };
    for (let t3 = 0;t3 < this.solvedSegments.length; t3++) {
      const n3 = this.solvedSegments[t3];
      for (let t4 = 0;t4 < n3.assignedPoints.length; t4++) {
        const o3 = n3.assignedPoints[t4], i3 = { x: o3.point.x, y: o3.point.y }, r3 = { x: o3.point.x + 0.05 * o3.point.z, y: o3.point.y + 0.05 * o3.point.z };
        o3.point.z !== 0 && e36.lines.push({ points: [i3, r3], strokeColor: "rgba(0, 0, 0, 0.25)", strokeDash: "5 5", step: 4 }), e36.points.push({ x: r3.x, y: r3.y, label: [`${n3.capacityMeshNodeId}-${o3.connectionName}`, `z: ${n3.availableZ.join(",")}`, `nodePortSegmentId: ${n3.nodePortSegmentId}`].join(`
`), color: this.colorMap[o3.connectionName], step: 4 });
      }
    }
    const t2 = [], n2 = {};
    for (const e37 of this.solvedSegments) {
      const t3 = e37.capacityMeshNodeId;
      n2[t3] || (n2[t3] = {});
      for (const o3 of e37.assignedPoints)
        n2[t3][o3.connectionName] || (n2[t3][o3.connectionName] = []), n2[t3][o3.connectionName].push({ x: o3.point.x, y: o3.point.y });
    }
    for (const e37 in n2)
      for (const o3 in n2[e37]) {
        const i3 = n2[e37][o3];
        i3.length > 1 && t2.push({ points: i3, step: 4, strokeDash: "5 5", strokeColor: this.colorMap[o3] || "#000" });
      }
    return e36.lines.push(...t2), e36;
  }
};
var dj = (e36, t2 = {}) => {
  const n2 = Math.min(...e36.availableZ);
  return { center: !t2.rectMargin || t2.zOffset ? { x: e36.center.x + n2 * e36.width * (t2.zOffset ?? 0.05), y: e36.center.y - n2 * e36.width * (t2.zOffset ?? 0.05) } : e36.center, width: t2.rectMargin ? e36.width - 2 * t2.rectMargin : Math.max(e36.width - 0.5, 0.8 * e36.width), height: t2.rectMargin ? e36.height - 2 * t2.rectMargin : Math.max(e36.height - 0.5, 0.8 * e36.height), fill: e36._containsObstacle ? "rgba(255,0,0,0.1)" : { "0,1": "rgba(0,0,0,0.1)", 0: "rgba(0,200,200, 0.1)", 1: "rgba(0,0,200, 0.1)" }[e36.availableZ.join(",")] ?? "rgba(0,200,200,0.1)", layer: `z${e36.availableZ.join(",")}`, label: [e36.capacityMeshNodeId, `availableZ: ${e36.availableZ.join(",")}`, "" + (e36._containsTarget ? "containsTarget" : ""), "" + (e36._containsObstacle ? "containsObstacle" : "")].filter(Boolean).join(`
`) };
};
var uj = class extends ni {
  getSolverName() {
    return "CapacityPathingSolver";
  }
  connectionsWithNodes;
  usedNodeCapacityMap;
  simpleRouteJson;
  nodes;
  edges;
  GREEDY_MULTIPLIER = 1.1;
  MAX_CANDIDATES_IN_MEMORY = 1e5;
  nodeMap;
  nodeEdgeMap;
  connectionNameToGoalNodeIds;
  colorMap;
  maxDepthOfNodes;
  activeCandidateStraightLineDistance;
  debug_lastNodeCostMap;
  hyperParameters;
  constructor({ simpleRouteJson: e36, nodes: t2, edges: n2, colorMap: o3, MAX_ITERATIONS: i3 = 1e6, hyperParameters: r3 = {} }) {
    super(), this.MAX_ITERATIONS = i3, this.simpleRouteJson = e36, this.nodes = t2, this.edges = n2, this.colorMap = o3 ?? {};
    const { connectionsWithNodes: s2, connectionNameToGoalNodeIds: a3 } = this.getConnectionsWithNodes();
    this.connectionsWithNodes = s2, this.connectionNameToGoalNodeIds = a3, this.hyperParameters = r3, this.usedNodeCapacityMap = new Map(this.nodes.map((e37) => [e37.capacityMeshNodeId, 0])), this.nodeMap = new Map(this.nodes.map((e37) => [e37.capacityMeshNodeId, e37])), this.nodeEdgeMap = oi(this.edges), this.maxDepthOfNodes = Math.max(...this.nodes.map((e37) => e37._depth ?? 0)), this.debug_lastNodeCostMap = new Map;
  }
  getTotalCapacity(e36) {
    const t2 = e36._depth ?? 0;
    return (this.maxDepthOfNodes - t2 + 1) ** 2;
  }
  getConnectionsWithNodes() {
    const e36 = [], t2 = this.nodes.filter((e37) => e37._containsTarget), n2 = new Map;
    for (const o3 of this.simpleRouteJson.connections) {
      const i3 = [];
      for (const e37 of o3.pointsToConnect) {
        let n3 = this.nodes[0], o4 = Number.MAX_VALUE;
        for (const i4 of t2) {
          const t3 = Math.sqrt((i4.center.x - e37.x) ** 2 + (i4.center.y - e37.y) ** 2);
          t3 < o4 && (o4 = t3, n3 = i4);
        }
        i3.push(n3);
      }
      if (i3.length < 2)
        throw new Error(`Not enough nodes for connection "${o3.name}", only ${i3.length} found`);
      n2.set(o3.name, i3.map((e37) => e37.capacityMeshNodeId)), e36.push({ connection: o3, nodes: i3, pathFound: false, straightLineDistance: me(i3[0].center, i3[i3.length - 1].center) });
    }
    return e36.sort((e37, t3) => e37.straightLineDistance - t3.straightLineDistance), { connectionsWithNodes: e36, connectionNameToGoalNodeIds: n2 };
  }
  currentConnectionIndex = 0;
  candidates;
  visitedNodes;
  computeG(e36, t2, n2) {
    return e36.g + this.getDistanceBetweenNodes(e36.node, t2);
  }
  computeH(e36, t2, n2) {
    return this.getDistanceBetweenNodes(t2, n2);
  }
  getBacktrackedPath(e36) {
    const t2 = [];
    let n2 = e36;
    for (;n2; )
      t2.push(n2.node), n2 = n2.prevCandidate;
    return t2;
  }
  getNeighboringNodes(e36) {
    return this.nodeEdgeMap.get(e36.capacityMeshNodeId).flatMap((t2) => t2.nodeIds.filter((t3) => t3 !== e36.capacityMeshNodeId)).map((e37) => this.nodeMap.get(e37));
  }
  getCapacityPaths() {
    const e36 = [];
    for (const t2 of this.connectionsWithNodes) {
      const n2 = t2.path;
      n2 && e36.push({ capacityPathId: t2.connection.name, connectionName: t2.connection.name, rootConnectionName: t2.connection.__rootConnectionNames?.[0], nodeIds: n2.map((e37) => e37.capacityMeshNodeId) });
    }
    return e36;
  }
  doesNodeHaveCapacityForTrace(e36, t2) {
    const n2 = this.usedNodeCapacityMap.get(e36.capacityMeshNodeId) ?? 0, o3 = this.getTotalCapacity(e36);
    if (e36.availableZ.length === 1 && !e36._containsTarget && n2 > 0)
      return false;
    let i3 = 0;
    return e36.availableZ.length > 1 && t2.availableZ.length === 1 && (i3 += 0.5), n2 + i3 < o3;
  }
  canTravelThroughObstacle(e36, t2) {
    const n2 = this.connectionNameToGoalNodeIds.get(t2);
    return n2?.includes(e36.capacityMeshNodeId) ?? false;
  }
  getDistanceBetweenNodes(e36, t2) {
    return Math.sqrt((e36.center.x - t2.center.x) ** 2 + (e36.center.y - t2.center.y) ** 2);
  }
  reduceCapacityAlongPath(e36) {
    for (const t2 of e36.path ?? [])
      this.usedNodeCapacityMap.set(t2.capacityMeshNodeId, this.usedNodeCapacityMap.get(t2.capacityMeshNodeId) + 1);
  }
  isConnectedToEndGoal(e36, t2) {
    return this.nodeEdgeMap.get(e36.capacityMeshNodeId).some((e37) => e37.nodeIds.includes(t2.capacityMeshNodeId));
  }
  _step() {
    const e36 = this.connectionsWithNodes[this.currentConnectionIndex];
    if (!e36)
      return void (this.solved = true);
    const [t2, n2] = e36.nodes;
    this.candidates || (this.candidates = [{ prevCandidate: null, node: t2, f: 0, g: 0, h: 0 }], this.debug_lastNodeCostMap = new Map, this.visitedNodes = new Set([t2.capacityMeshNodeId]), this.activeCandidateStraightLineDistance = me(t2.center, n2.center)), this.candidates.sort((e37, t3) => e37.f - t3.f);
    const o3 = this.candidates.shift();
    if (this.candidates.length > this.MAX_CANDIDATES_IN_MEMORY && this.candidates.splice(this.MAX_CANDIDATES_IN_MEMORY, this.candidates.length - this.MAX_CANDIDATES_IN_MEMORY), !o3)
      return console.error(`Ran out of candidates on connection ${e36.connection.name}`), this.currentConnectionIndex++, this.candidates = null, this.visitedNodes = null, void (this.failed = true);
    if (this.isConnectedToEndGoal(o3.node, n2))
      return e36.path = this.getBacktrackedPath({ prevCandidate: o3, node: n2, f: 0, g: 0, h: 0 }), this.reduceCapacityAlongPath(e36), this.currentConnectionIndex++, this.candidates = null, void (this.visitedNodes = null);
    const i3 = this.getNeighboringNodes(o3.node);
    for (const e37 of i3) {
      if (this.visitedNodes?.has(e37.capacityMeshNodeId))
        continue;
      if (!this.doesNodeHaveCapacityForTrace(e37, o3.node))
        continue;
      const t3 = this.connectionsWithNodes[this.currentConnectionIndex].connection.name;
      if (e37._containsObstacle && !this.canTravelThroughObstacle(e37, t3))
        continue;
      const i4 = this.computeG(o3, e37, n2), r3 = this.computeH(o3, e37, n2), s2 = i4 + r3 * this.GREEDY_MULTIPLIER;
      this.debug_lastNodeCostMap.set(e37.capacityMeshNodeId, { f: s2, g: i4, h: r3 });
      const a3 = { prevCandidate: o3, node: e37, f: s2, g: i4, h: r3 };
      this.candidates.push(a3);
    }
    this.visitedNodes.add(o3.node.capacityMeshNodeId);
  }
  visualize() {
    const e36 = { lines: [], points: [], rects: [], circles: [] };
    if (this.connectionsWithNodes)
      for (let t3 = 0;t3 < this.connectionsWithNodes.length; t3++) {
        const n2 = this.connectionsWithNodes[t3];
        if (n2.path && n2.path.length > 0) {
          const o3 = n2.path.map(({ center: { x: e37, y: n3 }, width: o4, availableZ: i3 }) => ({ x: e37 + 0.005 * o4 * (t3 % 10 + t3 % 19), y: n3 + 0.005 * o4 * (t3 % 10 + t3 % 19), availableZ: i3 }));
          e36.lines.push({ points: o3, strokeColor: this.colorMap[n2.connection.name] });
          for (let t4 = 0;t4 < o3.length; t4++) {
            const i3 = o3[t4];
            e36.points.push({ x: i3.x, y: i3.y, label: [`conn: ${n2.connection.name}`, `node: ${n2.path[t4].capacityMeshNodeId}`, `z: ${i3.availableZ.join(",")}`].join(`
`) });
          }
        }
      }
    for (const t3 of this.nodes) {
      const n2 = this.usedNodeCapacityMap.get(t3.capacityMeshNodeId) ?? 0, o3 = this.getTotalCapacity(t3), i3 = this.debug_lastNodeCostMap.get(t3.capacityMeshNodeId);
      e36.rects.push({ ...dj(t3, { rectMargin: 0.025, zOffset: 0.01 }), label: [`${t3.capacityMeshNodeId}`, `${n2}/${o3}`, `${t3.width.toFixed(2)}x${t3.height.toFixed(2)}`, `g: ${i3?.g !== undefined ? i3.g.toFixed(2) : "?"}`, `h: ${i3?.h !== undefined ? i3.h.toFixed(2) : "?"}`, `f: ${i3?.f !== undefined ? i3.f.toFixed(2) : "?"}`, `z: ${t3.availableZ.join(", ")}`].join(`
`), stroke: n2 > o3 + 0.5 ? "red" : undefined });
    }
    if (this.connectionsWithNodes) {
      for (const t3 of this.connectionsWithNodes)
        if (t3.connection?.pointsToConnect)
          for (const n2 of t3.connection.pointsToConnect)
            e36.points.push({ x: n2.x, y: n2.y, label: [`pointsToConnect ${t3.connection.name}`].join(`
`) });
    }
    let t2 = this.connectionsWithNodes[this.currentConnectionIndex];
    if (!this.candidates && this.currentConnectionIndex > 0 && !this.connectionsWithNodes[this.currentConnectionIndex - 1].path && (t2 = this.connectionsWithNodes[this.currentConnectionIndex - 1]), t2) {
      const [n2, o3] = t2.connection.pointsToConnect;
      e36.lines.push({ points: [{ x: n2.x, y: n2.y }, { x: o3.x, y: o3.y }], strokeColor: "red", strokeDash: "10 5" });
    }
    if (this.candidates) {
      const t3 = this.candidates.slice(0, 5), n2 = this.connectionsWithNodes[this.currentConnectionIndex].connection.name;
      t3.forEach((t4, o3) => {
        const i3 = 0.5 * (1 - o3 / 5), r3 = this.getBacktrackedPath(t4);
        e36.lines.push({ points: r3.map(({ center: { x: e37, y: t5 } }) => ({ x: e37, y: t5 })), strokeColor: Ao(this.colorMap[n2] ?? "red", 1 - i3) });
      });
    }
    return e36;
  }
};
var pj = class extends uj {
  getSolverName() {
    return "CapacityPathingSolver5";
  }
  NEGATIVE_CAPACITY_PENALTY_FACTOR = 1;
  REDUCED_CAPACITY_PENALTY_FACTOR = 1;
  constructor(...e36) {
    super(...e36), this.GREEDY_MULTIPLIER = 2.5;
  }
  get maxCapacityFactor() {
    return this.hyperParameters.MAX_CAPACITY_FACTOR ?? 1;
  }
  getTotalCapacity(e36) {
    return Bz(e36, this.maxCapacityFactor);
  }
  getNodeCapacityPenalty(e36) {
    const t2 = e36.width + e36.height, n2 = 0.05, o3 = this.getTotalCapacity(e36) - (this.usedNodeCapacityMap.get(e36.capacityMeshNodeId) ?? 0);
    if (o3 > 2)
      return n2;
    return (t2 - n2) * Math.max(1, (2 - o3) / (t2 - n2)) + n2;
  }
  getDistanceBetweenNodes(e36, t2) {
    const n2 = e36.center.x - t2.center.x, o3 = e36.center.y - t2.center.y;
    return Math.sqrt(n2 ** 2 + o3 ** 2);
  }
  computeG(e36, t2, n2) {
    return e36.g + this.getDistanceBetweenNodes(e36.node, t2) + this.getNodeCapacityPenalty(t2);
  }
  computeH(e36, t2, n2) {
    return this.getDistanceBetweenNodes(t2, n2) + this.getNodeCapacityPenalty(t2);
  }
};
var mj = class extends pj {
  getSolverName() {
    return "CapacityPathingGreedySolver";
  }
  doesNodeHaveCapacityForTrace(e36, t2) {
    return true;
  }
  getNodeCapacityPenalty(e36) {
    const t2 = this.getTotalCapacity(e36) - (this.usedNodeCapacityMap.get(e36.capacityMeshNodeId) ?? 0) - 1;
    if (t2 > 0)
      return 0;
    let n2 = 1;
    return e36.availableZ.length === 1 && (n2 = 10), (0.05 + 2 * Math.abs(t2)) * n2;
  }
};
function gj(e36, t2, n2) {
  const o3 = t2.x - e36.x, i3 = t2.y - e36.y;
  if (Math.abs(o3) < 0.000000001 && Math.abs(i3) < 0.000000001)
    return e36;
  const r3 = n2.width / 2, s2 = n2.height / 2, a3 = n2.center.x - r3, c3 = n2.center.x + r3, l3 = n2.center.y - s2, h2 = n2.center.y + s2;
  let d2 = 0, u2 = 1 / 0;
  if (Math.abs(o3) > 0.000000001) {
    const t3 = (a3 - e36.x) / o3, n3 = (c3 - e36.x) / o3;
    d2 = Math.max(d2, Math.min(t3, n3)), u2 = Math.min(u2, Math.max(t3, n3));
  } else if (e36.x < a3 || e36.x > c3)
    return e36;
  if (Math.abs(i3) > 0.000000001) {
    const t3 = (l3 - e36.y) / i3, n3 = (h2 - e36.y) / i3;
    d2 = Math.max(d2, Math.min(t3, n3)), u2 = Math.min(u2, Math.max(t3, n3));
  } else if (e36.y < l3 || e36.y > h2)
    return e36;
  if (u2 < d2 || d2 === 1 / 0 || d2 < -1e9)
    return e36;
  return { x: e36.x + o3 * d2, y: e36.y + i3 * d2 };
}
function fj(e36, t2) {
  const n2 = e36.center, o3 = t2.center, i3 = gj(n2, o3, e36), r3 = gj(o3, n2, t2), s2 = o3.x - n2.x, a3 = o3.y - n2.y, c3 = Math.sqrt(s2 * s2 + a3 * a3);
  let l3 = i3, h2 = r3;
  if (c3 > 0.000000001) {
    const n3 = { x: s2 / c3, y: a3 / c3 }, o4 = 0.3 * e36.width, d2 = 0.3 * t2.width;
    o4 + d2 < Math.sqrt((r3.x - i3.x) ** 2 + (r3.y - i3.y) ** 2) ? (l3 = { x: i3.x + n3.x * o4, y: i3.y + n3.y * o4 }, h2 = { x: r3.x - n3.x * d2, y: r3.y - n3.y * d2 }) : (l3 = i3, h2 = r3);
  }
  return { lineStart: l3, lineEnd: h2 };
}
var _j = (e36) => {
  const { usedCapacity: t2, totalCapacity: n2, layerCount: o3 } = e36;
  if (t2 < n2)
    return 0;
  if (n2 < 1 && t2 <= 1)
    return 0;
  if (o3 === 1 && t2 > 1)
    return 1 - 0.01 ** t2;
  const i3 = t2 / n2 - 1;
  return 1 - Math.exp(-2 * i3);
};
var yj = (e36, t2, n2) => {
  if (n2._containsTarget)
    return 0;
  if (e36 <= t2)
    return 0;
  const o3 = 1 - _j({ usedCapacity: e36, totalCapacity: t2, layerCount: n2.availableZ.length });
  return o3 <= 0 ? -1e9 : Math.log(o3);
};
var bj = ({ totalNodeCapacityMap: e36, usedNodeCapacityMap: t2, nodeMap: n2, sectionNodeIds: o3 }) => {
  let i3 = 0;
  const r3 = o3 ?? new Set(t2.keys());
  for (const o4 of r3) {
    if (!e36.has(o4))
      continue;
    const r4 = n2.get(o4);
    if (!r4)
      continue;
    const s2 = e36.get(o4), a3 = t2.get(o4) ?? 0;
    i3 += yj(a3, s2, r4);
  }
  return i3;
};
function xj({ sectionNodes: e36, sectionEdges: t2, sectionConnectionTerminals: n2, completedPaths: o3, nodeMap: i3, colorMap: r3, centerNodeId: s2, title: a3, nodeOpacity: c3 = 0.1, usedNodeCapacityMap: l3, totalCapacityMap: h2 }) {
  const d2 = { points: [], lines: [], rects: [], circles: [], title: a3 }, u2 = new Set(e36.map((e37) => e37.capacityMeshNodeId));
  for (const t3 of e36) {
    let e37 = `rgba(128, 128, 128, ${c3})`, n3 = `rgba(128, 128, 128, ${c3})`;
    const o4 = t3.availableZ ?? [], i4 = o4.includes(0), r4 = o4.includes(1);
    i4 && r4 ? (e37 = `rgba(128, 0, 128, ${c3})`, n3 = `rgba(128, 0, 128, ${c3})`) : i4 ? (e37 = `rgba(0, 0, 255, ${c3})`, n3 = `rgba(0, 0, 255, ${c3})`) : r4 && (e37 = `rgba(255, 0, 0, ${c3})`, n3 = `rgba(255, 0, 0, ${c3})`), s2 && t3.capacityMeshNodeId === s2 && (e37 = `rgba(0, 255, 0, ${c3})`, n3 = `rgba(0, 128, 0, ${c3})`), d2.rects.push({ ...dj(t3), fill: e37, stroke: n3, label: `${t3.capacityMeshNodeId}
(Section Node)
Z: ${o4.join(",")}` });
    const a4 = d2.rects.length - 1;
    if (l3 && h2) {
      const e38 = l3.get(t3.capacityMeshNodeId) ?? 0, n4 = h2.get(t3.capacityMeshNodeId) ?? 0, o5 = n4 > 0 ? (e38 / n4 * 100).toFixed(1) : "N/A", i5 = _j({ usedCapacity: e38, totalCapacity: n4, layerCount: t3.availableZ.length });
      d2.rects[a4].label += `
${e38.toFixed(1)} / ${n4.toFixed(1)}
${o5}% (Pf: ${(100 * i5).toFixed(1)}%)`, i5 > 0.2 && (d2.rects[a4].stroke = Ao("red", 0.7 * (0.8 + c3)));
    }
  }
  for (const e37 of t2) {
    const [t3, n3] = e37.nodeIds, o4 = i3.get(t3), r4 = i3.get(n3);
    if (o4 && r4) {
      const { lineStart: e38, lineEnd: t4 } = fj(o4, r4);
      d2.lines.push({ points: [e38, t4], strokeColor: `rgba(0, 0, 0, ${0.2 * Math.min(1, c3 / 0.1)})` });
    }
  }
  return n2.forEach((e37, t3) => {
    const n3 = i3.get(e37.startNodeId), o4 = i3.get(e37.endNodeId), s3 = r3[e37.connectionName] ?? "black", a4 = n3 && u2.has(n3.capacityMeshNodeId), c4 = o4 && u2.has(o4.capacityMeshNodeId), l4 = (t3 + t3 / 50) % 5;
    let h3 = 0, p3 = 0, m2 = 0, g2 = 0;
    if (a4 && n3) {
      const t4 = 0.02 * Math.min(n3.width, n3.height);
      h3 = t4 * l4, p3 = t4 * l4, d2.points.push({ x: n3.center.x + h3, y: n3.center.y + p3, color: s3, label: `Start: ${e37.connectionName}
(${e37.startNodeId})` }), d2.lines.push({ points: [{ x: n3.center.x, y: n3.center.y }, { x: n3.center.x + h3, y: n3.center.y + p3 }], strokeColor: "gray", strokeDash: "2 2" });
    }
    if (c4 && o4) {
      const t4 = 0.02 * Math.min(o4.width, o4.height);
      m2 = t4 * l4, g2 = t4 * l4, d2.points.push({ x: o4.center.x + m2, y: o4.center.y + g2, color: s3, label: `End: ${e37.connectionName}
(${e37.endNodeId})` }), d2.lines.push({ points: [{ x: o4.center.x, y: o4.center.y }, { x: o4.center.x + m2, y: o4.center.y + g2 }], strokeColor: "gray", strokeDash: "2 2" });
    }
    a4 && c4 && n3 && o4 && d2.lines.push({ points: [{ x: n3.center.x + h3, y: n3.center.y + p3 }, { x: o4.center.x + m2, y: o4.center.y + g2 }], strokeColor: s3, strokeDash: "5 5" });
  }), o3 && o3.forEach((e37, t3) => {
    if (e37.path && e37.path.length > 0) {
      const n3 = r3[e37.connectionName] ?? "gray", o4 = { x: (t3 + t3 / 50) % 5 * 0.03, y: (t3 + t3 / 50) % 5 * 0.03 };
      d2.lines.push({ points: e37.path.map(({ center: { x: e38, y: t4 } }) => ({ x: e38 + o4.x, y: t4 + o4.y })), strokeColor: Ao(n3, 0.2) });
    }
  }), d2;
}
var vj = class extends ni {
  getSolverName() {
    return "CapacityPathingSingleSectionSolver";
  }
  GREEDY_MULTIPLIER = 1.5;
  sectionNodes;
  sectionEdges;
  sectionConnectionTerminals;
  nodeMap;
  nodeEdgeMap;
  colorMap;
  usedNodeCapacityMap;
  totalNodeCapacityMap;
  centerNodeId;
  currentSectionScore = 0;
  MAX_CANDIDATES_IN_MEMORY = 1e4;
  currentConnectionIndex = 0;
  candidates = null;
  visitedNodes = null;
  queuedNodes = null;
  activeCandidateStraightLineDistance;
  debug_lastNodeCostMap = new Map;
  maxCapacityFactor = 1;
  constructor(e36) {
    super(), this.MAX_ITERATIONS = 1e4, this.centerNodeId = e36.centerNodeId, this.sectionNodes = e36.sectionNodes, this.sectionEdges = e36.sectionEdges, this.sectionConnectionTerminals = e36.sectionConnectionTerminals.map((e37) => ({ ...e37, path: undefined })), this.nodeMap = e36.nodeMap ?? new Map(this.sectionNodes.map((e37) => [e37.capacityMeshNodeId, e37])), this.nodeEdgeMap = e36.nodeEdgeMap ?? oi(this.sectionEdges), this.colorMap = e36.colorMap ?? {}, this.usedNodeCapacityMap = new Map(this.sectionNodes.map((e37) => [e37.capacityMeshNodeId, 0])), this.totalNodeCapacityMap = new Map(this.sectionNodes.map((e37) => [e37.capacityMeshNodeId, this.getTotalCapacity(e37)]));
    const t2 = new Set(this.sectionNodes.map((e37) => e37.capacityMeshNodeId));
    this.currentSectionScore = bj({ totalNodeCapacityMap: this.totalNodeCapacityMap, usedNodeCapacityMap: this.usedNodeCapacityMap, nodeMap: this.nodeMap, sectionNodeIds: t2 }), e36.hyperParameters?.SHUFFLE_SEED && (this.sectionConnectionTerminals = Sr(this.sectionConnectionTerminals, e36.hyperParameters?.SHUFFLE_SEED));
  }
  getTotalCapacity(e36) {
    return Bz(e36, this.maxCapacityFactor);
  }
  getNodeCapacityPenalty(e36) {
    if (!this.nodeMap.has(e36.capacityMeshNodeId))
      return 1 / 0;
    const t2 = this.getTotalCapacity(e36) - (this.usedNodeCapacityMap.get(e36.capacityMeshNodeId) ?? 0) - 1;
    if (t2 > 0)
      return 0;
    let n2 = 1;
    return e36.availableZ.length === 1 && (n2 = 10), (0.05 + t2 ** 2 * 4) * n2;
  }
  getDistanceBetweenNodes(e36, t2) {
    const n2 = e36.center.x - t2.center.x, o3 = e36.center.y - t2.center.y;
    return Math.sqrt(n2 ** 2 + o3 ** 2);
  }
  computeG(e36, t2, n2) {
    return e36.g + this.getDistanceBetweenNodes(e36.node, t2) + this.getNodeCapacityPenalty(t2);
  }
  computeH(e36, t2, n2) {
    return this.getDistanceBetweenNodes(t2, n2) + this.getNodeCapacityPenalty(t2);
  }
  getBacktrackedPath(e36) {
    const t2 = [];
    let n2 = e36;
    for (;n2; ) {
      if (t2.push(n2.node), !this.nodeMap.has(n2.node.capacityMeshNodeId)) {
        console.warn("Backtracked path went outside section bounds");
        break;
      }
      n2 = n2.prevCandidate;
    }
    return t2.reverse();
  }
  getNeighboringNodes(e36) {
    return this.nodeMap.has(e36.capacityMeshNodeId) ? this.nodeEdgeMap.get(e36.capacityMeshNodeId)?.flatMap((t2) => t2.nodeIds.filter((t3) => t3 !== e36.capacityMeshNodeId)).map((e37) => this.nodeMap.get(e37)).filter(Boolean) ?? [] : [];
  }
  isConnectedToEndGoal(e36, t2) {
    return !(!this.nodeMap.has(e36.capacityMeshNodeId) || !this.nodeMap.has(t2.capacityMeshNodeId)) && (this.nodeEdgeMap.get(e36.capacityMeshNodeId) ?? []).some((e37) => e37.nodeIds.includes(t2.capacityMeshNodeId));
  }
  doesNodeHaveCapacityForTrace(e36, t2) {
    return true;
  }
  reduceCapacityAlongPath(e36) {
    for (const t2 of e36)
      if (this.usedNodeCapacityMap.has(t2.capacityMeshNodeId)) {
        const e37 = t2.capacityMeshNodeId, n2 = this.nodeMap.get(e37);
        if (!n2) {
          console.warn(`Node ${e37} from path not found in section's nodeMap during score update.`);
          continue;
        }
        const o3 = this.totalNodeCapacityMap.get(e37), i3 = this.usedNodeCapacityMap.get(e37) ?? 0, r3 = yj(i3, o3, n2);
        this.currentSectionScore -= r3;
        const s2 = i3 + 1;
        this.usedNodeCapacityMap.set(e37, s2);
        const a3 = yj(s2, o3, n2);
        this.currentSectionScore += a3;
      }
  }
  getSolvedSectionScore() {
    return this.currentSectionScore;
  }
  _step() {
    const e36 = this.sectionConnectionTerminals[this.currentConnectionIndex];
    if (!e36)
      return void (this.solved = true);
    const t2 = this.nodeMap.get(e36.startNodeId), n2 = this.nodeMap.get(e36.endNodeId);
    if (!t2 || !n2)
      return console.error(`Start or end node not found in section for connection ${e36.connectionName}`), this.currentConnectionIndex++, this.candidates = null, void (this.visitedNodes = null);
    this.candidates || this._setupAStar(t2, n2);
    const o3 = this.candidates;
    if (o3.length === 0)
      return void this._handleCandidatesExhausted(e36);
    o3.sort((e37, t3) => e37.f - t3.f);
    const i3 = o3.shift();
    if (o3.length > this.MAX_CANDIDATES_IN_MEMORY && o3.splice(this.MAX_CANDIDATES_IN_MEMORY, o3.length - this.MAX_CANDIDATES_IN_MEMORY), this.visitedNodes.add(i3.node.capacityMeshNodeId), i3.node.capacityMeshNodeId === n2.capacityMeshNodeId)
      return void this._handleGoalReached(i3, e36, n2);
    const r3 = this.getNeighboringNodes(i3.node);
    for (const t3 of r3) {
      if (this.queuedNodes?.has(t3.capacityMeshNodeId))
        continue;
      if (!this.doesNodeHaveCapacityForTrace(t3, i3.node))
        continue;
      if (t3._containsObstacle) {
        const n3 = t3.capacityMeshNodeId === e36.startNodeId, o4 = t3.capacityMeshNodeId === e36.endNodeId;
        if (!n3 && !o4)
          continue;
      }
      const r4 = this.computeG(i3, t3, n2), s2 = this.computeH(i3, t3, n2), a3 = r4 + s2 * this.GREEDY_MULTIPLIER;
      this.debug_lastNodeCostMap.set(t3.capacityMeshNodeId, { f: a3, g: r4, h: s2 });
      const c3 = { prevCandidate: i3, node: t3, f: a3, g: r4, h: s2 };
      this.queuedNodes?.add(t3.capacityMeshNodeId), o3.push(c3);
    }
  }
  computeProgress() {
    const e36 = this.sectionConnectionTerminals.length;
    if (e36 === 0)
      return 1;
    let t2 = this.currentConnectionIndex / e36;
    if (this.currentConnectionIndex < e36 && this.candidates && this.candidates.length > 0 && this.activeCandidateStraightLineDistance && this.activeCandidateStraightLineDistance > 0) {
      const n2 = this.candidates.reduce((e37, t3) => t3.f < e37.f ? t3 : e37);
      t2 += Math.max(0, Math.min(1, 1 - n2.h / this.activeCandidateStraightLineDistance)) / e36;
    } else
      this.solved && (t2 = 1);
    return Math.min(1, t2);
  }
  _setupAStar(e36, t2) {
    this.candidates = [{ prevCandidate: null, node: e36, f: 0, g: 0, h: 0 }], this.visitedNodes = new Set([e36.capacityMeshNodeId]), this.debug_lastNodeCostMap = new Map, this.activeCandidateStraightLineDistance = me(e36.center, t2.center);
    const n2 = this.computeH(null, e36, t2);
    this.candidates[0].h = n2, this.candidates[0].f = n2 * this.GREEDY_MULTIPLIER, this.debug_lastNodeCostMap.set(e36.capacityMeshNodeId, { f: this.candidates[0].f, g: 0, h: n2 }), this.queuedNodes = new Set([e36.capacityMeshNodeId]);
  }
  _handleCandidatesExhausted(e36) {
    console.error(`Ran out of candidates for section connection ${e36.connectionName}`), this.currentConnectionIndex++, this.candidates = null, this.visitedNodes = null, this.queuedNodes = null;
  }
  _handleGoalReached(e36, t2, n2) {
    const o3 = this.getBacktrackedPath(e36);
    t2.path = o3, this.reduceCapacityAlongPath(o3), this.currentConnectionIndex++, this.candidates = null, this.visitedNodes = null, this.queuedNodes = null;
  }
  visualize() {
    const e36 = this.sectionConnectionTerminals.filter((e37) => e37.path && e37.path.length > 0).map((e37) => ({ connectionName: e37.connectionName, path: e37.path })), t2 = xj({ sectionNodes: this.sectionNodes, sectionEdges: this.sectionEdges, sectionConnectionTerminals: this.sectionConnectionTerminals, completedPaths: e36, nodeMap: this.nodeMap, colorMap: this.colorMap, centerNodeId: null, title: `Section Pathing: Conn ${this.currentConnectionIndex + 1}/${this.sectionConnectionTerminals.length} (${this.sectionNodes.length} nodes)`, nodeOpacity: 0.1 });
    for (const e37 of this.sectionNodes) {
      const n2 = t2.rects.findIndex((t3) => t3.label?.includes(e37.capacityMeshNodeId));
      if (n2 !== -1) {
        const o3 = this.debug_lastNodeCostMap.get(e37.capacityMeshNodeId), i3 = this.usedNodeCapacityMap.get(e37.capacityMeshNodeId) ?? 0, r3 = this.getTotalCapacity(e37), s2 = `${i3.toFixed(1)}/${r3.toFixed(1)}`, a3 = o3 ? `f:${o3.f.toFixed(1)} g:${o3.g.toFixed(1)} h:${o3.h.toFixed(1)}` : "cost:?";
        t2.rects[n2].label = [e37.capacityMeshNodeId, `Cap: ${s2}`, a3, `Z: ${e37.availableZ.join(",")}`].join(`
`), i3 > r3 && (t2.rects[n2].stroke = Ao("red", 0.7));
      }
    }
    if (this.candidates && this.candidates.length > 0) {
      const e37 = this.candidates.slice().sort((e38, t3) => e38.f - t3.f).slice(0, 5), n2 = this.sectionConnectionTerminals[this.currentConnectionIndex], o3 = n2?.connectionName ?? "unknown", i3 = this.colorMap[o3] ?? "purple";
      e37.forEach((e38, n3) => {
        const o4 = 0.8 * (1 - n3 / 5), r3 = this.getBacktrackedPath(e38);
        r3.length > 0 && t2.lines.push({ points: r3.map(({ center: { x: e39, y: t3 } }) => ({ x: e39, y: t3 })), strokeColor: Ao(i3, 1 - o4), strokeWidth: 0.05 });
      });
    }
    return t2;
  }
};
var Ij = (e36) => Array.from({ length: e36 }, (e37, t2) => t2);
var Sj = class extends wa {
  getSolverName() {
    return "HyperCapacityPathingSingleSectionSolver";
  }
  constructorParams;
  constructor(e36) {
    super(), this.MAX_ITERATIONS = 1e5, this.constructorParams = e36;
  }
  computeG(e36) {
    return -e36.getSolvedSectionScore();
  }
  computeH(e36) {
    return 0;
  }
  getCombinationDefs() {
    const e36 = this.constructorParams.sectionConnectionTerminals.length;
    return e36 === 2 ? [["orderings2_for2"]] : e36 === 3 ? [["orderings6_for3"]] : e36 === 4 ? [["orderings24_for4"]] : [["orderings30"]];
  }
  getFailureMessage() {
    return `All CapacityPathingSingleSection solvers failed for "${this.centerNodeId}"`;
  }
  getHyperParameterDefs() {
    return [{ name: "orderings2_for2", possibleValues: Ij(2).map((e36) => ({ SHUFFLE_SEED: e36 })) }, { name: "orderings6_for3", possibleValues: Ij(6).map((e36) => ({ SHUFFLE_SEED: e36 })) }, { name: "orderings24_for4", possibleValues: Ij(24).map((e36) => ({ SHUFFLE_SEED: e36 })) }, { name: "orderings30", possibleValues: Ij(30).map((e36) => ({ SHUFFLE_SEED: e36 })) }];
  }
  generateSolver(e36) {
    return new vj({ ...this.constructorParams, hyperParameters: { ...this.constructorParams.hyperParameters, ...e36 } });
  }
  onSolve({ solver: e36 }) {
    this.winningSolver = e36;
  }
  get centerNodeId() {
    return this.constructorParams.centerNodeId;
  }
  get sectionNodes() {
    return this.constructorParams.sectionNodes;
  }
  get sectionConnectionTerminals() {
    return this.winningSolver?.sectionConnectionTerminals;
  }
};
var Pj = (e36) => Math.floor(10 * e36) / 10;
var Mj = class extends Sj {
  cacheHit = false;
  cacheProvider;
  hasAttemptedToUseCache = false;
  sectionNodeIdSet;
  cachedSectionConnectionTerminals = null;
  sectionScore = 0;
  constructor(e36) {
    e36.nodeMap = e36.nodeMap ?? new Map(e36.sectionNodes.map((e37) => [e37.capacityMeshNodeId, e37])), super(e36), this.sectionNodeIdSet = new Set(e36.sectionNodes.map((e37) => e37.capacityMeshNodeId)), this.cacheProvider = e36.cacheProvider === undefined ? no() : e36.cacheProvider;
  }
  _step() {
    !this.hasAttemptedToUseCache && this.cacheProvider && this.attemptToUseCacheSync() || (super._step(), (this.solved || this.failed) && this.cacheProvider && this.saveToCacheSync());
  }
  _computeBfsOrderingOfNodesInSection() {
    const e36 = new Set(this.constructorParams.centerNodeId), t2 = [], n2 = [{ ancestorCapacitySum: 0, capacity: 0, g: 0, capacityMeshNodeId: this.constructorParams.centerNodeId }];
    for (;n2.length > 0; ) {
      n2.sort((e37, t3) => t3.g - e37.g);
      const o3 = n2.pop();
      if (!o3)
        break;
      t2.push(o3.capacityMeshNodeId);
      const i3 = this.constructorParams.nodeEdgeMap.get(o3.capacityMeshNodeId).flatMap((e37) => e37.nodeIds).filter((t3) => !e36.has(t3)).filter((e37) => this.sectionNodeIdSet.has(e37));
      for (const t3 of i3) {
        e36.add(t3);
        const i4 = this.constructorParams.nodeMap.get(t3), r3 = Bz(i4);
        n2.push({ ancestorCapacitySum: o3.g, capacity: r3, g: o3.g + r3, capacityMeshNodeId: t3 });
      }
    }
    return t2;
  }
  computeCacheKeyAndTransform() {
    const e36 = this._computeBfsOrderingOfNodesInSection(), t2 = new Map, n2 = new Map;
    e36.forEach((e37, o4) => {
      const i4 = `node${o4}`;
      t2.set(e37, i4), n2.set(i4, e37);
    });
    const o3 = {};
    for (const n3 of e36) {
      const e37 = t2.get(n3), i4 = this.constructorParams.nodeMap.get(n3), r4 = Bz(i4);
      o3[e37] = Pj(r4).toFixed(1);
    }
    const i3 = new Set, r3 = [];
    for (const n3 of e36) {
      const e37 = t2.get(n3), o4 = this.constructorParams.nodeEdgeMap.get(n3) ?? [];
      for (const s3 of o4) {
        const o5 = s3.nodeIds.find((e38) => e38 !== n3);
        if (this.sectionNodeIdSet.has(o5)) {
          const n4 = [e37, t2.get(o5)].sort(), s4 = `${n4[0]}-${n4[1]}`;
          i3.has(s4) || (r3.push(n4), i3.add(s4));
        }
      }
    }
    r3.sort((e37, t3) => e37[0] !== t3[0] ? e37[0].localeCompare(t3[0]) : e37[1].localeCompare(t3[1]));
    const s2 = {}, a3 = new Map, c3 = new Map;
    for (const e37 of this.constructorParams.sectionConnectionTerminals) {
      const n3 = t2.get(e37.startNodeId), o4 = t2.get(e37.endNodeId), [i4, r4] = [n3, o4].sort(), l4 = `${i4}->${r4}`, h3 = c3.get(l4) ?? 0;
      c3.set(l4, h3 + 1);
      const d2 = `${i4}->${r4}::${h3}`;
      s2[d2] = { start: i4, end: r4 }, a3.set(d2, e37.connectionName);
    }
    const l3 = `capacitypathing:${import_object_hash2.default({ node_capacity_map: o3, node_edge_map: r3, terminals: s2 })}`, h2 = { cacheSpaceToRealConnectionId: a3, cacheSpaceToRealNodeId: n2 };
    return this.cacheKey = l3, this.cacheToSolveSpaceTransform = h2, { cacheKey: l3, cacheToSolveSpaceTransform: h2 };
  }
  applyCachedSolution(e36) {
    if (!this.cacheToSolveSpaceTransform)
      return console.error("Cache transform not available, cannot apply cached solution."), void (this.failed = true);
    if (!e36.success)
      return this.failed = true, void (this.cacheHit = true);
    this.cachedSectionConnectionTerminals = [];
    const { cacheSpaceToRealNodeId: t2, cacheSpaceToRealConnectionId: n2 } = this.cacheToSolveSpaceTransform;
    for (const [o3, i3] of Object.entries(e36.solutionPaths)) {
      const e37 = n2.get(o3);
      if (!e37) {
        console.warn(`Could not find real connection name for ${o3}`);
        continue;
      }
      const r3 = this.constructorParams.sectionConnectionTerminals.find((t3) => t3.connectionName === e37);
      if (!r3) {
        console.warn(`Could not find original terminal for connection name ${e37}`);
        continue;
      }
      const s2 = i3.map((n3) => {
        const o4 = t2.get(n3);
        if (!o4)
          throw new Error(`Could not map cache node ID ${n3} to real node ID for connection ${e37}`);
        const i4 = this.constructorParams.nodeMap.get(o4);
        if (!i4)
          throw new Error(`Could not find node with ID ${o4} in nodeMap for connection ${e37}`);
        return i4;
      });
      this.cachedSectionConnectionTerminals.push({ ...r3, path: s2 });
    }
    this.sectionScore = e36.sectionScore, this.solved = true, this.cacheHit = true;
  }
  attemptToUseCacheSync() {
    if (this.hasAttemptedToUseCache = true, !this.cacheProvider?.isSyncCache)
      return console.log("Cache provider is not synchronous, skipping sync cache check."), false;
    if (this.cacheKey || this.computeCacheKeyAndTransform(), !this.cacheKey)
      return console.error("Failed to compute cache key."), false;
    try {
      const e36 = this.cacheProvider.getCachedSolutionSync(this.cacheKey);
      if (e36)
        return this.applyCachedSolution(e36), true;
    } catch (e36) {
      console.error("Error attempting to use cache:", e36);
    }
    return false;
  }
  saveToCacheSync() {
    if (!this.cacheKey)
      return void console.error("Cannot save to cache without cache key.");
    if (!this.cacheToSolveSpaceTransform)
      return void console.error("Cache transform not available, cannot save solution to cache.");
    let e36;
    if (this.failed)
      e36 = { success: false };
    else {
      if (!this.solved)
        return;
      {
        const t2 = {}, { cacheSpaceToRealNodeId: n2, cacheSpaceToRealConnectionId: o3 } = this.cacheToSolveSpaceTransform, i3 = new Map;
        for (const [e37, t3] of n2)
          i3.set(t3, e37);
        const r3 = new Map;
        for (const [e37, t3] of o3)
          r3.set(t3, e37);
        const s2 = [];
        if (super.sectionConnectionTerminals) {
          for (const e37 of super.sectionConnectionTerminals)
            if (e37.path && e37.path.length > 0) {
              const t3 = e37.path.map((e38) => e38.capacityMeshNodeId);
              s2.push([e37.connectionName, t3]);
            }
        }
        for (const [e37, n3] of s2) {
          const o4 = r3.get(e37);
          if (!o4) {
            console.warn(`Could not find cache space connection ID for ${e37} when saving to cache.`);
            continue;
          }
          const s3 = n3.map((t3) => {
            const n4 = i3.get(t3);
            if (!n4)
              throw new Error(`Could not map real node ID ${t3} to cache node ID for connection ${e37} when saving to cache.`);
            return n4;
          });
          t2[o4] = s3;
        }
        e36 = { success: true, sectionScore: this.sectionScore, solutionPaths: t2 };
      }
    }
    try {
      this.cacheProvider?.setCachedSolutionSync(this.cacheKey, e36);
    } catch (e37) {
      console.error("Error saving solution to cache:", e37);
    }
  }
  get sectionConnectionTerminals() {
    return this.cacheHit && this.solved && this.cachedSectionConnectionTerminals ? (console.log("returning the cached section connection terminals"), this.cachedSectionConnectionTerminals) : super.sectionConnectionTerminals;
  }
  visualize() {
    if (!this.cacheHit)
      return super.visualize();
    return xj({ sectionNodes: this.constructorParams.sectionNodes, sectionEdges: this.constructorParams.sectionEdges, sectionConnectionTerminals: this.cachedSectionConnectionTerminals, completedPaths: this.cachedSectionConnectionTerminals.map((e36) => ({ connectionName: e36.connectionName, path: e36.path })), nodeMap: this.constructorParams.nodeMap, colorMap: this.constructorParams.colorMap, title: "CachedHyperCapacityPathingSingleSectionSolver" });
  }
};
var wj = class extends ni {
  getSolverName() {
    return "CapacityPathingMultiSectionSolver";
  }
  simpleRouteJson;
  nodes;
  edges;
  nodeEdgeMap;
  connectionsWithNodes = [];
  colorMap;
  initialSolver;
  cacheProvider;
  stage = "initialization";
  nodeMap = new Map;
  allNodeIdsSet;
  usedNodeCapacityMap = new Map;
  totalNodeCapacityMap = new Map;
  nodeCapacityPercentMap = new Map;
  nodeOptimizationAttemptCountMap = new Map;
  currentSection = null;
  sectionSolver = null;
  currentScheduleIndex = 0;
  stats;
  OPTIMIZATION_SCHEDULE = [{ MAX_ATTEMPTS_PER_NODE: 1, MAX_EXPANSION_DEGREES: 3, MINIMUM_PROBABILITY_OF_FAILURE_TO_OPTIMIZE: 0.05 }, { MAX_ATTEMPTS_PER_NODE: 2, MAX_EXPANSION_DEGREES: 5, MINIMUM_PROBABILITY_OF_FAILURE_TO_OPTIMIZE: 0.2 }, { MAX_ATTEMPTS_PER_NODE: 3, MAX_EXPANSION_DEGREES: 7, MINIMUM_PROBABILITY_OF_FAILURE_TO_OPTIMIZE: 0.9 }];
  get currentSchedule() {
    return this.OPTIMIZATION_SCHEDULE[this.currentScheduleIndex] ?? null;
  }
  constructor(e36) {
    super(), this.stats = { successfulOptimizations: 0, failedOptimizations: 0, failedSectionSolvers: 0, startingScore: 0, scheduleScores: this.OPTIMIZATION_SCHEDULE.map(({ MAX_EXPANSION_DEGREES: e37 }) => ({ maxExpansionDegrees: e37, endingScore: 0, endingHighestNodePf: 0, sectionAttempts: 0 })), cacheHits: 0, cacheMisses: 0 }, this.MAX_ITERATIONS = e36.MAX_ITERATIONS ?? 1e7, this.cacheProvider = e36.cacheProvider, this.simpleRouteJson = e36.simpleRouteJson, this.nodes = e36.nodes, this.edges = e36.edges, this.nodeEdgeMap = oi(this.edges), this.colorMap = e36.colorMap ?? {}, this.nodeMap = new Map(this.nodes.map((e37) => [e37.capacityMeshNodeId, e37])), this.nodeEdgeMap = oi(this.edges), this.initialSolver = e36.initialPathingSolver || new mj({ simpleRouteJson: this.simpleRouteJson, nodes: this.nodes, edges: this.edges, colorMap: this.colorMap }), this.activeSubSolver = this.initialSolver;
    for (const e37 of this.nodes) {
      const t2 = this.initialSolver.getTotalCapacity(e37);
      this.totalNodeCapacityMap.set(e37.capacityMeshNodeId, t2);
    }
    this.allNodeIdsSet = new Set(this.nodes.map((e37) => e37.capacityMeshNodeId));
  }
  _stepInitialization() {
    if (this.initialSolver?.step(), this.initialSolver?.failed)
      return this.failed = true, void (this.error = this.initialSolver.error);
    if (this.initialSolver?.solved) {
      this.usedNodeCapacityMap = new Map(this.initialSolver.usedNodeCapacityMap);
      for (const e36 of this.nodes) {
        const t2 = this.totalNodeCapacityMap.get(e36.capacityMeshNodeId) ?? 0, n2 = this.usedNodeCapacityMap.get(e36.capacityMeshNodeId) ?? 0, o3 = t2 > 0 ? n2 / t2 : 0;
        this.nodeCapacityPercentMap.set(e36.capacityMeshNodeId, o3), this.nodeOptimizationAttemptCountMap.set(e36.capacityMeshNodeId, 0);
      }
      this.connectionsWithNodes = this.initialSolver.connectionsWithNodes, this.stats.startingScore = bj({ totalNodeCapacityMap: this.totalNodeCapacityMap, usedNodeCapacityMap: this.usedNodeCapacityMap, nodeMap: this.nodeMap, sectionNodeIds: this.allNodeIdsSet }), this.stage = "section-optimization";
    }
  }
  _getNextNodeToOptimize() {
    let e36 = 0, t2 = 0, n2 = null;
    for (const o3 of this.nodes) {
      if (o3._containsTarget)
        continue;
      const i3 = this.nodeOptimizationAttemptCountMap.get(o3.capacityMeshNodeId), r3 = this.totalNodeCapacityMap.get(o3.capacityMeshNodeId), s2 = _j({ usedCapacity: this.usedNodeCapacityMap.get(o3.capacityMeshNodeId) ?? 0, totalCapacity: r3, layerCount: o3.availableZ.length }), a3 = s2 / (i3 + 1);
      i3 < this.currentSchedule.MAX_ATTEMPTS_PER_NODE && a3 > e36 && s2 > this.currentSchedule.MINIMUM_PROBABILITY_OF_FAILURE_TO_OPTIMIZE && (e36 = a3, t2 = s2, n2 = o3.capacityMeshNodeId);
    }
    return n2;
  }
  getOverallScore() {
    let e36 = 0;
    for (const t2 of this.nodes) {
      if (t2._containsTarget)
        continue;
      const n2 = this.totalNodeCapacityMap.get(t2.capacityMeshNodeId), o3 = _j({ usedCapacity: this.usedNodeCapacityMap.get(t2.capacityMeshNodeId) ?? 0, totalCapacity: n2, layerCount: t2.availableZ.length });
      o3 > e36 && (e36 = o3);
    }
    return { highestNodePf: e36, score: bj({ totalNodeCapacityMap: this.totalNodeCapacityMap, usedNodeCapacityMap: this.usedNodeCapacityMap, nodeMap: this.nodeMap, sectionNodeIds: this.allNodeIdsSet }) };
  }
  _stepSectionOptimization() {
    if (!this.sectionSolver) {
      const e36 = this._getNextNodeToOptimize();
      if (!e36) {
        const { highestNodePf: e37, score: t3 } = this.getOverallScore();
        return this.stats.scheduleScores[this.currentScheduleIndex].endingHighestNodePf = e37, this.stats.scheduleScores[this.currentScheduleIndex].endingScore = t3, this.currentScheduleIndex++, void (this.currentSchedule || (this.solved = true));
      }
      const t2 = ((e37) => {
        const { centerNodeId: t3, connectionsWithNodes: n2, nodeMap: o3, edges: i3, nodeEdgeMap: r3, expansionDegrees: s2 } = e37, a3 = new Set, c3 = [{ nodeId: t3, depth: 0 }];
        a3.add(t3);
        let l3 = 0;
        for (;l3 < c3.length; ) {
          const { nodeId: e38, depth: t4 } = c3[l3++];
          if (t4 >= s2)
            continue;
          const n3 = r3.get(e38)?.flatMap((t5) => t5.nodeIds.filter((t6) => t6 !== e38)) ?? [];
          for (const e39 of n3)
            a3.has(e39) || (a3.add(e39), c3.push({ nodeId: e39, depth: t4 + 1 }));
        }
        const h2 = Array.from(a3).map((e38) => o3.get(e38)), d2 = i3.filter((e38) => {
          const [t4, n3] = e38.nodeIds;
          return a3.has(t4) && a3.has(n3);
        }), u2 = [];
        for (const e38 of n2) {
          if (!e38.path)
            continue;
          let t4 = null, n3 = null;
          for (const n4 of e38.path)
            if (a3.has(n4.capacityMeshNodeId)) {
              t4 = n4.capacityMeshNodeId;
              break;
            }
          for (let t5 = e38.path.length - 1;t5 >= 0; t5--) {
            const o4 = e38.path[t5];
            if (a3.has(o4.capacityMeshNodeId)) {
              n3 = o4.capacityMeshNodeId;
              break;
            }
          }
          t4 && n3 && u2.push({ connectionName: e38.connection.name, startNodeId: t4, endNodeId: n3 });
        }
        return { sectionConnectionTerminals: u2, sectionNodes: h2, sectionEdges: d2, centerNodeId: t3 };
      })({ centerNodeId: e36, connectionsWithNodes: this.connectionsWithNodes, nodeMap: this.nodeMap, edges: this.edges, expansionDegrees: this.currentSchedule.MAX_EXPANSION_DEGREES, nodeEdgeMap: this.nodeEdgeMap });
      this.stats.scheduleScores[this.currentScheduleIndex].sectionAttempts++, this.currentSection = t2, this.sectionSolver = new Mj({ sectionNodes: this.currentSection.sectionNodes, sectionEdges: this.currentSection.sectionEdges, sectionConnectionTerminals: this.currentSection.sectionConnectionTerminals, colorMap: this.colorMap, centerNodeId: this.currentSection.centerNodeId, nodeEdgeMap: this.nodeEdgeMap, hyperParameters: { EXPANSION_DEGREES: this.currentSchedule.MAX_EXPANSION_DEGREES }, cacheProvider: this.cacheProvider }), this.activeSubSolver = this.sectionSolver, this.nodeOptimizationAttemptCountMap.set(e36, (this.nodeOptimizationAttemptCountMap.get(e36) ?? 0) + 1);
    }
    if (this.sectionSolver.step(), (this.sectionSolver.failed || this.sectionSolver.solved) && (this.sectionSolver.cacheHit ? this.stats.cacheHits++ : this.stats.cacheMisses++), this.sectionSolver.failed)
      return console.warn(`Section solver failed for node ${this.currentSection.centerNodeId}. Error: ${this.sectionSolver.error}`), this.stats.failedSectionSolvers++, this.stats.failedOptimizations++, this.sectionSolver = null, void (this.activeSubSolver = null);
    if (this.sectionSolver.solved) {
      const e36 = this.sectionSolver.sectionConnectionTerminals, t2 = this.sectionSolver.sectionNodes, n2 = this.sectionSolver.centerNodeId;
      if (this.sectionSolver = null, this.activeSubSolver = null, !e36)
        return void console.warn(`Pathing sub-solver for section ${this.currentSection.centerNodeId} did not complete successfully. Discarding results.`);
      const o3 = new Set(t2.map((e37) => e37.capacityMeshNodeId)), i3 = bj({ totalNodeCapacityMap: this.totalNodeCapacityMap, usedNodeCapacityMap: this.usedNodeCapacityMap, nodeMap: this.nodeMap, sectionNodeIds: o3 }), r3 = new Map(this.usedNodeCapacityMap), s2 = e36;
      for (const e37 of s2) {
        const t3 = this.connectionsWithNodes.find((t4) => t4.connection.name === e37.connectionName);
        if (t3?.path) {
          for (const e38 of t3.path)
            if (o3.has(e38.capacityMeshNodeId)) {
              const t4 = r3.get(e38.capacityMeshNodeId) ?? 0;
              r3.set(e38.capacityMeshNodeId, Math.max(0, t4 - 1));
            }
        }
      }
      for (const e37 of s2)
        if (e37.path)
          for (const t3 of e37.path)
            o3.has(t3.capacityMeshNodeId) && r3.set(t3.capacityMeshNodeId, (r3.get(t3.capacityMeshNodeId) ?? 0) + 1);
      bj({ totalNodeCapacityMap: this.totalNodeCapacityMap, usedNodeCapacityMap: r3, nodeMap: this.nodeMap, sectionNodeIds: o3 }) > i3 ? (this.stats.successfulOptimizations++, this._mergeSolvedSectionPaths({ centerNodeId: n2, sectionConnectionTerminals: e36 }), this._recalculateNodeCapacityUsage()) : this.stats.failedOptimizations++;
    }
  }
  _mergeSolvedSectionPaths({ centerNodeId: e36, sectionConnectionTerminals: t2 }) {
    for (const n2 of t2) {
      if (!n2.path) {
        console.warn(`No path found for connection ${n2.connectionName} in section ${e36}`);
        continue;
      }
      const t3 = this.connectionsWithNodes.find((e37) => e37.connection.name === n2.connectionName);
      if (!t3 || !t3.path) {
        console.warn(`Original connection or path not found for ${n2.connectionName} while merging section ${e36}`);
        continue;
      }
      const o3 = t3.path, i3 = n2.path, r3 = o3.findIndex((e37) => e37.capacityMeshNodeId === n2.startNodeId), s2 = o3.findIndex((e37) => e37.capacityMeshNodeId === n2.endNodeId);
      if (r3 === -1 || s2 === -1) {
        console.warn(`Could not find start/end nodes (${n2.startNodeId}/${n2.endNodeId}) in original path for ${n2.connectionName}`);
        continue;
      }
      const [a3, c3] = r3 <= s2 ? [r3, s2] : [s2, r3], l3 = o3.slice(0, a3), h2 = o3.slice(c3 + 1);
      let d2 = i3;
      if (i3.length > 0 && o3[a3] && i3[0].capacityMeshNodeId !== o3[a3].capacityMeshNodeId) {
        if (i3[i3.length - 1].capacityMeshNodeId !== o3[a3].capacityMeshNodeId) {
          console.warn(`New section path for ${n2.connectionName} doesn't align with original path boundaries. Skipping merge for this connection.`);
          continue;
        }
        d2 = [...i3].reverse();
      }
      t3.path = [...l3, ...d2, ...h2];
    }
  }
  _recalculateNodeCapacityUsage() {
    this.usedNodeCapacityMap.clear();
    for (const e36 of this.connectionsWithNodes)
      if (e36.path)
        for (const t2 of e36.path)
          this.usedNodeCapacityMap.set(t2.capacityMeshNodeId, (this.usedNodeCapacityMap.get(t2.capacityMeshNodeId) ?? 0) + 1);
    for (const e36 of this.nodes) {
      const t2 = this.totalNodeCapacityMap.get(e36.capacityMeshNodeId) ?? 0, n2 = this.usedNodeCapacityMap.get(e36.capacityMeshNodeId) ?? 0, o3 = t2 > 0 ? n2 / t2 : 0;
      this.nodeCapacityPercentMap.set(e36.capacityMeshNodeId, o3);
    }
  }
  getCapacityPaths() {
    const e36 = [];
    for (const t2 of this.connectionsWithNodes) {
      const n2 = t2.path;
      n2 && e36.push({ capacityPathId: t2.connection.name, connectionName: t2.connection.name, nodeIds: n2.map((e37) => e37.capacityMeshNodeId) });
    }
    return e36;
  }
  _step() {
    this.iterations >= this.MAX_ITERATIONS - 1 ? this.solved = true : this.stage === "initialization" ? this._stepInitialization() : this.stage === "section-optimization" && this._stepSectionOptimization();
  }
  visualize() {
    const e36 = this.connectionsWithNodes.filter((e37) => e37.path && e37.path.length > 0).map((e37) => ({ connectionName: e37.connection.name, path: e37.path }));
    return xj({ nodeMap: this.nodeMap, sectionConnectionTerminals: this.connectionsWithNodes.map((e37) => ({ connectionName: e37.connection.name, startNodeId: e37.path?.[0]?.capacityMeshNodeId, endNodeId: e37.path?.[e37.path.length - 1]?.capacityMeshNodeId })), completedPaths: e36, sectionNodes: this.nodes, sectionEdges: this.edges, colorMap: this.colorMap, totalCapacityMap: this.totalNodeCapacityMap, usedNodeCapacityMap: this.usedNodeCapacityMap, nodeOpacity: 0.05, title: "Capacity Pathing Multi-Section Solver (Solved)" });
  }
};
var Nj = class extends ni {
  getSolverName() {
    return "DeadEndSolver";
  }
  removedNodeIds;
  targetNodeIds;
  leaves;
  leavesIndex;
  adjacencyList;
  nodeMap;
  nodes;
  edges;
  constructor({ nodes: e36, edges: t2 }) {
    super(), this.MAX_ITERATIONS = e36.length, this.nodes = e36, this.edges = t2, this.removedNodeIds = new Set, this.targetNodeIds = new Set(e36.filter((e37) => e37._containsTarget).map((e37) => e37.capacityMeshNodeId)), this.adjacencyList = new Map(e36.map(({ capacityMeshNodeId: e37 }) => [e37, new Set]));
    for (const { nodeIds: [e37, n2] } of t2)
      this.adjacencyList.get(e37).add(n2), this.adjacencyList.get(n2).add(e37);
    this.leavesIndex = 0, this.leaves = [...this.adjacencyList.entries()].filter(([e37, t3]) => t3.size === 1).filter(([e37, t3]) => !this.targetNodeIds.has(e37)).map(([e37, t3]) => e37);
  }
  _step() {
    if (this.leavesIndex === this.leaves.length)
      return void (this.solved = true);
    const e36 = this.leaves[this.leavesIndex], t2 = this.adjacencyList.get(e36);
    if (!t2 || t2.size === 0)
      return this.removedNodeIds.add(e36), this.adjacencyList.delete(e36), this.leavesIndex += 1, void (this.leavesIndex === this.leaves.length && (this.solved = true));
    const [n2] = t2, o3 = n2 ? this.adjacencyList.get(n2) : undefined;
    if (!n2 || !o3)
      return this.removedNodeIds.add(e36), this.adjacencyList.delete(e36), this.leavesIndex += 1, void (this.leavesIndex === this.leaves.length && (this.solved = true));
    o3.delete(e36), this.removedNodeIds.add(e36), this.adjacencyList.delete(e36), o3.size !== 1 || this.targetNodeIds.has(n2) || this.leaves.push(n2), this.leavesIndex += 1, this.leavesIndex === this.leaves.length && (this.solved = true);
  }
  visualize() {
    if (!this.nodeMap) {
      this.nodeMap = new Map;
      for (const e37 of this.nodes)
        this.nodeMap.set(e37.capacityMeshNodeId, e37);
    }
    const e36 = new Map;
    for (const t3 of this.edges)
      for (const n2 of t3.nodeIds)
        e36.set(n2, 1 + (e36.get(n2) ?? 0));
    const t2 = { lines: [], points: [], rects: this.nodes.map((t3) => {
      const n2 = Math.min(...t3.availableZ);
      return { width: Math.max(t3.width - 2, 0.8 * t3.width), height: Math.max(t3.height - 2, 0.8 * t3.height), center: { x: t3.center.x + n2 * t3.width * 0.05, y: t3.center.y - n2 * t3.width * 0.05 }, fill: t3._containsObstacle ? "rgba(255,0,0,0.1)" : { "0,1": "rgba(0,0,0,0.1)", 0: "rgba(0,200,200, 0.1)", 1: "rgba(0,0,200, 0.1)" }[t3.availableZ.join(",")] ?? "rgba(0,200,200,0.1)", label: [t3.capacityMeshNodeId, `availableZ: ${t3.availableZ.join(",")}`, `target? ${t3._containsTarget ?? false}`, `obs? ${t3._containsObstacle ?? false}`, `conn: ${e36.get(t3.capacityMeshNodeId) ?? 0}`].join(`
`), layer: `z${t3.availableZ.join(",")}` };
    }), circles: [] };
    for (const e37 of this.edges) {
      const n2 = this.nodeMap.get(e37.nodeIds[0]), o3 = this.nodeMap.get(e37.nodeIds[1]);
      if (n2?.center && o3?.center) {
        const i3 = Math.min(...n2.availableZ), r3 = Math.min(...o3.availableZ), s2 = { x: n2.center.x + i3 * n2.width * 0.05, y: n2.center.y - i3 * n2.width * 0.05 }, a3 = { x: o3.center.x + r3 * o3.width * 0.05, y: o3.center.y - r3 * o3.width * 0.05 }, c3 = Array.from(new Set([...n2.availableZ, ...o3.availableZ])).sort();
        t2.lines.push({ layer: `z${c3.join(",")}`, points: [s2, a3], strokeDash: n2.availableZ.join(",") === o3.availableZ.join(",") ? undefined : "10 5", strokeColor: e37.nodeIds.some((e38) => this.removedNodeIds.has(e38)) ? Ao("black", 0.9) : undefined });
      }
    }
    return t2;
  }
};
var Rj = class extends IB {
  getSolverName() {
    return "NoOffBoardMultipleHighDensityRouteStitchSolver";
  }
  constructor(e36) {
    super(e36), this.unsolvedRoutes = [];
    const t2 = new Map;
    for (const n2 of e36.hdRoutes) {
      const e37 = t2.get(n2.connectionName) || [];
      e37.push(n2), t2.set(n2.connectionName, e37);
    }
    for (const [n2, o3] of t2.entries()) {
      const t3 = e36.connections.find((e37) => e37.name === n2);
      if (!t3)
        continue;
      const i3 = { ...t3.pointsToConnect[0], z: mo(Io(t3.pointsToConnect[0]), e36.layerCount) }, r3 = { ...t3.pointsToConnect[1], z: mo(Io(t3.pointsToConnect[1]), e36.layerCount) };
      this.unsolvedRoutes.push({ connectionName: n2, hdRoutes: o3, start: i3, end: r3 });
    }
    for (const n2 of e36.connections)
      t2.has(n2.name) || this.unsolvedRoutes.push({ connectionName: n2.name, hdRoutes: [], start: { ...n2.pointsToConnect[0], z: mo(Io(n2.pointsToConnect[0]), e36.layerCount) }, end: { ...n2.pointsToConnect[1], z: mo(Io(n2.pointsToConnect[1]), e36.layerCount) } });
  }
};
var Tj = 0.005;
var Ej = class extends ni {
  getSolverName() {
    return "SingleLayerNodeMergerSolver";
  }
  nodeMap;
  currentBatchNodeIds;
  absorbedNodeIds;
  nextBatchNodeIds;
  batchHadModifications;
  hasComputedAdjacentNodeIds = false;
  newNodes;
  constructor(e36) {
    super(), this.nodeMap = new Map, this.MAX_ITERATIONS = 1e5;
    for (const t3 of e36)
      this.nodeMap.set(t3.capacityMeshNodeId, t3);
    this.newNodes = [], this.absorbedNodeIds = new Set;
    const t2 = [];
    for (const n2 of e36)
      n2.availableZ.length > 1 ? (this.newNodes.push(n2), this.absorbedNodeIds.add(n2.capacityMeshNodeId)) : t2.push([n2, n2.width * n2.height]);
    t2.sort((e37, t3) => e37[1] - t3[1]);
    for (const [e37, n2] of t2) {
      const t3 = { ...e37, center: { ...e37.center } };
      this.nodeMap.set(e37.capacityMeshNodeId, t3);
    }
    this.currentBatchNodeIds = t2.map(([e37]) => e37.capacityMeshNodeId), this.nextBatchNodeIds = [], this.batchHadModifications = false;
  }
  computeAdjacentNodeIdsForFirstBatch(e36) {
    const t2 = Math.max(...e36.map((e37) => Math.max(...e37.availableZ))), n2 = [];
    for (let o3 = 0;o3 <= t2; o3++)
      n2.push(new di(e36.filter((e37) => e37.availableZ[0] === o3)));
    for (const t3 of e36) {
      const e37 = [], o3 = n2[t3.availableZ[0]].getNodesInArea(t3.center.x, t3.center.y, 4 * t3.width, 4 * t3.height);
      for (const n3 of o3)
        n3._containsTarget && n3._targetConnectionName !== t3._targetConnectionName || t3._containsTarget && (!n3._containsTarget || n3._targetConnectionName !== t3._targetConnectionName) || n3.capacityMeshNodeId !== t3.capacityMeshNodeId && ri(t3, n3) && e37.push(n3);
      t3._adjacentNodeIds = e37.map((e38) => e38.capacityMeshNodeId);
    }
  }
  getAdjacentSameLayerUnprocessedNodes(e36) {
    return this.getAdjacentSameLayerUnprocessedNodes2(e36);
  }
  getAdjacentSameLayerUnprocessedNodes2(e36) {
    const t2 = [], n2 = Array.from(new Set((e36._adjacentNodeIds ?? []).map((e37) => this.nodeMap.get(e37)))).filter((t3) => t3 && t3.capacityMeshNodeId !== e36.capacityMeshNodeId);
    n2.sort((e37, t3) => e37.width * e37.height - t3.width * t3.height);
    for (const e37 of n2)
      this.absorbedNodeIds.has(e37.capacityMeshNodeId) || t2.push(e37);
    return t2;
  }
  _step() {
    this.hasComputedAdjacentNodeIds || (this.computeAdjacentNodeIdsForFirstBatch(this.currentBatchNodeIds.map((e37) => this.nodeMap.get(e37))), this.hasComputedAdjacentNodeIds = true);
    let e36 = this.currentBatchNodeIds.pop();
    for (;e36 && this.absorbedNodeIds.has(e36); )
      e36 = this.currentBatchNodeIds.pop();
    if (!e36)
      return this.batchHadModifications ? (this.currentBatchNodeIds = this.nextBatchNodeIds.sort((e37, t3) => {
        const n3 = this.nodeMap.get(e37), o4 = this.nodeMap.get(t3);
        return n3.width * n3.height - o4.width * o4.height;
      }), this.nextBatchNodeIds = [], void (this.batchHadModifications = false)) : (this.solved = true, void this.newNodes.push(...this.nextBatchNodeIds.map((e37) => this.nodeMap.get(e37))));
    const t2 = this.nodeMap.get(e36);
    let n2 = false;
    const o3 = this.getAdjacentSameLayerUnprocessedNodes(t2);
    if (o3.length === 0)
      return void this.nextBatchNodeIds.push(e36);
    const i3 = (e37) => {
      for (const t3 of e37)
        this.absorbedNodeIds.add(t3.capacityMeshNodeId);
      t2._adjacentNodeIds = Array.from(new Set([...t2._adjacentNodeIds ?? [], ...e37.flatMap((e38) => e38._adjacentNodeIds ?? [])].filter((e38) => e38 !== t2.capacityMeshNodeId && !this.absorbedNodeIds.has(e38))));
    }, r3 = o3.filter((e37) => e37.center.x < t2.center.x && Math.abs(e37.center.y - t2.center.y) < t2.height / 2);
    if (r3.length > 0) {
      const { width: e37, height: o4 } = r3[0], s3 = r3.every((t3) => t3.width === e37 && t3.height === o4);
      Math.abs(r3.reduce((e38, t3) => e38 + t3.height, 0) - t2.height) < Tj && s3 && (t2.width += e37, t2.center.x = t2.center.x - e37 / 2, i3(r3), n2 = true);
    }
    const s2 = o3.filter((e37) => e37.center.x > t2.center.x && Math.abs(e37.center.y - t2.center.y) < t2.height / 2);
    if (s2.length > 0 && !n2) {
      const { width: e37, height: o4 } = s2[0], r4 = s2.every((t3) => t3.width === e37 && t3.height === o4);
      Math.abs(s2.reduce((e38, t3) => e38 + t3.height, 0) - t2.height) < Tj && r4 && (t2.width += e37, t2.center.x = t2.center.x + e37 / 2, i3(s2), n2 = true);
    }
    const a3 = o3.filter((e37) => e37.center.y > t2.center.y && Math.abs(e37.center.x - t2.center.x) < t2.width / 2);
    if (a3.length > 0 && !n2) {
      const { width: e37, height: o4 } = a3[0], r4 = a3.every((t3) => t3.width === e37 && t3.height === o4);
      Math.abs(a3.reduce((e38, t3) => e38 + t3.width, 0) - t2.width) < Tj && r4 && (t2.height += o4, t2.center.y = t2.center.y + o4 / 2, i3(a3), n2 = true);
    }
    const c3 = o3.filter((e37) => e37.center.y < t2.center.y && Math.abs(e37.center.x - t2.center.x) < t2.width / 2);
    if (c3.length > 0 && !n2) {
      const { width: e37, height: o4 } = c3[0], r4 = c3.every((t3) => t3.width === e37 && t3.height === o4);
      Math.abs(c3.reduce((e38, t3) => e38 + t3.width, 0) - t2.width) < Tj && r4 && (t2.height += o4, t2.center.y = t2.center.y - o4 / 2, i3(c3), n2 = true);
    }
    n2 ? (this.batchHadModifications = true, this.currentBatchNodeIds.push(e36)) : this.nextBatchNodeIds.unshift(e36);
  }
  visualize() {
    const e36 = { circles: [], lines: [], points: [], rects: [], coordinateSystem: "cartesian", title: "Same Layer Node Merger" };
    for (const t3 of this.newNodes)
      e36.rects.push(dj(t3));
    const t2 = this.currentBatchNodeIds[this.currentBatchNodeIds.length - 1];
    let n2;
    t2 && (n2 = this.getAdjacentSameLayerUnprocessedNodes(this.nodeMap.get(t2)));
    for (const o3 of this.currentBatchNodeIds) {
      const i3 = this.nodeMap.get(o3);
      if (!this.absorbedNodeIds.has(o3) && i3) {
        const r3 = dj(i3, { rectMargin: 0.01 });
        o3 === t2 ? r3.stroke = "rgba(0, 255, 0, 0.8)" : n2?.some((e37) => e37.capacityMeshNodeId === o3) ? r3.stroke = "rgba(128, 0, 128, 0.8)" : r3.stroke = "rgba(255, 165, 0, 0.8)", r3.layer = `z${i3.availableZ.join(",")}`, r3.label = `${r3.label}
(unprocessed)`, e36.rects.push(r3);
      }
    }
    for (const t3 of this.nextBatchNodeIds) {
      const n3 = this.nodeMap.get(t3);
      if (!this.absorbedNodeIds.has(t3) && n3) {
        const t4 = dj(n3, { rectMargin: 0.01 });
        t4.layer = `z${n3.availableZ.join(",")}`, t4.stroke = "rgba(0, 217, 255, 0.8)", t4.label = `${t4.label}
x: ${n3.center.x}, y: ${n3.center.y}
${n3.width}x${n3.height}
(next batch)`, e36.rects.push(t4);
      }
    }
    return e36;
  }
};
var Aj = class extends ni {
  getSolverName() {
    return "StrawSolver";
  }
  multiLayerNodes;
  strawNodes;
  skippedNodes;
  unprocessedNodes;
  strawSize;
  nodeIdCounter;
  constructor(e36) {
    super(), this.MAX_ITERATIONS = 1e5, this.strawSize = e36.strawSize ?? 0.5, this.multiLayerNodes = [], this.strawNodes = [], this.skippedNodes = [], this.nodeIdCounter = 0, this.unprocessedNodes = [];
    for (const t2 of e36.nodes)
      t2.availableZ.length === 1 ? this.unprocessedNodes.push(t2) : this.multiLayerNodes.push(t2);
  }
  getCapacityOfMultiLayerNodesWithinBounds(e36) {
    let t2 = 0;
    for (const n2 of this.multiLayerNodes) {
      const o3 = n2.center.x - n2.width / 2, i3 = n2.center.x + n2.width / 2, r3 = n2.center.y - n2.height / 2, s2 = n2.center.y + n2.height / 2, a3 = Math.max(e36.minX, o3), c3 = Math.min(e36.maxX, i3), l3 = Math.max(e36.minY, r3), h2 = Math.min(e36.maxY, s2);
      if (a3 < c3 && l3 < h2) {
        const e37 = (c3 - a3) * (h2 - l3) / (n2.width * n2.height);
        t2 += Bz(n2) * e37;
      }
    }
    return t2;
  }
  getSurroundingCapacities(e36) {
    const t2 = Math.min(e36.width, e36.height);
    return { leftSurroundingCapacity: this.getCapacityOfMultiLayerNodesWithinBounds({ minX: e36.center.x - e36.width / 2 - t2, maxX: e36.center.x - e36.width / 2, minY: e36.center.y - e36.height / 2, maxY: e36.center.y + e36.height / 2 }), rightSurroundingCapacity: this.getCapacityOfMultiLayerNodesWithinBounds({ minX: e36.center.x + e36.width / 2, maxX: e36.center.x + e36.width / 2 + t2, minY: e36.center.y - e36.height / 2, maxY: e36.center.y + e36.height / 2 }), topSurroundingCapacity: this.getCapacityOfMultiLayerNodesWithinBounds({ minX: e36.center.x - e36.width / 2, maxX: e36.center.x + e36.width / 2, minY: e36.center.y - e36.height / 2 - t2, maxY: e36.center.y - e36.height / 2 }), bottomSurroundingCapacity: this.getCapacityOfMultiLayerNodesWithinBounds({ minX: e36.center.x - e36.width / 2, maxX: e36.center.x + e36.width / 2, minY: e36.center.y + e36.height / 2, maxY: e36.center.y + e36.height / 2 + t2 }) };
  }
  createStrawsForNode(e36) {
    const t2 = [], { leftSurroundingCapacity: n2, rightSurroundingCapacity: o3, topSurroundingCapacity: i3, bottomSurroundingCapacity: r3 } = this.getSurroundingCapacities(e36);
    if (1 * (n2 + o3) > i3 + r3) {
      const n3 = Math.floor(e36.height / this.strawSize), o4 = e36.height / n3;
      for (let i4 = 0;i4 < n3; i4++) {
        const n4 = e36.center.y - e36.height / 2 + i4 * o4 + o4 / 2;
        t2.push({ capacityMeshNodeId: `${e36.capacityMeshNodeId}_straw${i4}`, center: { x: e36.center.x, y: n4 }, width: e36.width, height: o4, layer: e36.layer, availableZ: [...e36.availableZ], _depth: e36._depth, _strawNode: true, _strawParentCapacityMeshNodeId: e36.capacityMeshNodeId });
      }
    } else {
      const n3 = Math.floor(e36.width / this.strawSize), o4 = e36.width / n3;
      for (let i4 = 0;i4 < n3; i4++) {
        const n4 = e36.center.x - e36.width / 2 + i4 * o4 + o4 / 2;
        t2.push({ capacityMeshNodeId: `${e36.capacityMeshNodeId}_straw${i4}`, center: { x: n4, y: e36.center.y }, width: o4, height: e36.height, layer: e36.layer, availableZ: [...e36.availableZ], _depth: e36._depth, _strawNode: true, _strawParentCapacityMeshNodeId: e36.capacityMeshNodeId });
      }
    }
    return t2;
  }
  getResultNodes() {
    return [...this.multiLayerNodes, ...this.strawNodes, ...this.skippedNodes];
  }
  _step() {
    const e36 = this.unprocessedNodes.pop();
    if (!e36)
      return void (this.solved = true);
    if (e36.width < this.strawSize && e36.height < this.strawSize)
      return void this.skippedNodes.push(e36);
    if (e36._containsTarget)
      return void this.skippedNodes.push(e36);
    const t2 = this.createStrawsForNode(e36);
    this.strawNodes.push(...t2), t2.length === 0 && this.strawNodes.push(e36);
  }
  visualize() {
    const e36 = { rects: [], lines: [], points: [], circles: [], title: "Straw Solver" };
    for (const t2 of this.unprocessedNodes)
      e36.rects.push({ center: t2.center, width: t2.width, height: t2.height, fill: "rgba(200, 200, 200, 0.5)", stroke: "rgba(0, 0, 0, 0.5)", label: `${t2.capacityMeshNodeId}
Unprocessed
${t2.width}x${t2.height}` });
    for (const t2 of this.strawNodes) {
      const n2 = t2.availableZ[0] === 0 ? "rgba(0, 150, 255, 0.5)" : "rgba(255, 100, 0, 0.5)";
      e36.rects.push({ center: t2.center, width: t2.width, height: t2.height, fill: n2, stroke: "rgba(0, 0, 0, 0.5)", label: `${t2.capacityMeshNodeId}
Layer: ${t2.availableZ[0]}
${t2.width}x${t2.height}`, layer: `z${t2.availableZ.join(",")}` });
    }
    for (const t2 of this.multiLayerNodes)
      e36.rects.push({ center: t2.center, width: 0.9 * t2.width, height: 0.9 * t2.height, fill: "rgba(100, 255, 100, 0.5)", stroke: "rgba(0, 0, 0, 0.5)", layer: `z${t2.availableZ.join(",")}`, label: `${t2.capacityMeshNodeId}
Layers: ${t2.availableZ.join(",")}
${t2.width}x${t2.height}` });
    return e36;
  }
};
function Oj(e36) {
  const { nodeId: t2, nodeIdToSegmentIds: n2, segmentIdToNodeIds: o3, hops: i3 } = e36;
  if (i3 === 0)
    return [t2];
  const r3 = new Set([t2]), s2 = [{ nodeId: t2, remainingHops: i3 }];
  for (;s2.length > 0; ) {
    const { nodeId: e37, remainingHops: t3 } = s2.shift();
    if (t3 === 0)
      continue;
    const i4 = n2.get(e37) || [];
    for (const e38 of i4) {
      const n3 = o3.get(e38) || [];
      for (const e39 of n3)
        r3.has(e39) || (r3.add(e39), s2.push({ nodeId: e39, remainingHops: t3 - 1 }));
    }
  }
  return Array.from(r3);
}
var kj = (e36) => Array.from(e36.entries()).map(([e37, { x: t2, y: n2, z: o3 }]) => `${e37}(${t2?.toFixed(3) ?? ""},${n2?.toFixed(3) ?? ""},${o3 ?? ""})`).sort().join("&");
var Dj = (e36, t2, n2, o3) => {
  const i3 = Math.min(e36, t2), r3 = Math.max(e36, t2), s2 = Math.min(n2, o3);
  return i3 <= Math.max(n2, o3) && r3 >= s2;
};
var Lj = (e36, t2, n2, o3) => {
  const i3 = [], r3 = new Map(e36.originalPointMap);
  for (const [e37, t3] of n2.entries()) {
    const n3 = r3.get(e37);
    r3.set(e37, { x: t3.x ?? n3.x, y: t3.y ?? n3.y, z: t3.z ?? n3.z });
  }
  for (const n3 of e36.allNodeIds) {
    if (!t2.get(n3))
      continue;
    const s2 = e36.segmentPairsInNode.get(n3);
    for (const e37 of s2) {
      const t3 = r3.get(e37[0]), o4 = r3.get(e37[1]);
      t3.z !== o4.z && i3.push({ type: "transition_via", segmentPoints: e37, capacityMeshNodeId: n3, probabilityOfFailure: 0 });
    }
    for (let e37 = 0;e37 < s2.length; e37++)
      for (let t3 = e37 + 1;t3 < s2.length; t3++) {
        if (o3?.areIdsConnected(s2[e37][0], s2[e37][1]))
          continue;
        const a3 = s2[e37], c3 = s2[t3], l3 = r3.get(a3[0]), h2 = r3.get(a3[1]), d2 = r3.get(c3[0]), u2 = r3.get(c3[1]);
        if (!Dj(l3.z, h2.z, d2.z, u2.z))
          continue;
        const p3 = he(l3, h2, d2, u2), m2 = l3.z === h2.z && d2.z === u2.z && l3.z === d2.z;
        p3 && (m2 ? i3.push({ type: "same_layer_crossing", segmentPoints: [a3, c3], capacityMeshNodeId: n3, crossingLine1: a3, crossingLine2: c3, probabilityOfFailure: 0 }) : l3.z === h2.z && d2.z !== u2.z ? i3.push({ type: "single_transition_crossing", segmentPoints: [a3, c3], capacityMeshNodeId: n3, sameLayerCrossingLine: a3, transitionCrossingLine: c3, probabilityOfFailure: 0 }) : l3.z !== h2.z && d2.z === u2.z ? i3.push({ type: "single_transition_crossing", segmentPoints: [a3, c3], capacityMeshNodeId: n3, sameLayerCrossingLine: c3, transitionCrossingLine: a3, probabilityOfFailure: 0 }) : l3.z !== h2.z && d2.z !== u2.z && i3.push({ type: "double_transition_crossing", segmentPoints: [a3, c3], capacityMeshNodeId: n3, crossingLine1: a3, crossingLine2: c3, probabilityOfFailure: 0 }));
      }
  }
  return i3;
};
var zj = (e36, t2, n2) => {
  if (t2.type === "change_layer")
    for (const n3 of t2.segmentPointIds) {
      const o3 = e36.get(n3) || {};
      e36.set(n3, { ...o3, z: t2.newZ });
    }
  else if (t2.type === "swap_position_on_segment") {
    const [o3, i3] = t2.segmentPointIds, r3 = n2(o3), s2 = n2(i3), a3 = e36.get(o3) || {}, c3 = e36.get(i3) || {};
    e36.set(o3, { ...a3, x: s2.x, y: s2.y }), e36.set(i3, { ...c3, x: r3.x, y: r3.y });
  } else if (t2.type === "combined")
    for (const o3 of t2.operations)
      zj(e36, o3, n2);
};
var Bj = (e36, t2) => {
  const n2 = new Map, o3 = new Map, i3 = new Map, r3 = [];
  let s2 = 0;
  for (const a3 of e36)
    for (const e37 of a3.assignedPoints) {
      const c3 = { segmentPointId: "SP" + s2++, segmentId: a3.nodePortSegmentId, capacityMeshNodeIds: t2.get(a3.nodePortSegmentId), connectionName: e37.connectionName, rootConnectionName: e37.rootConnectionName, x: e37.point.x, y: e37.point.y, z: e37.point.z, directlyConnectedSegmentPointIds: [] };
      n2.set(c3.segmentPointId, c3);
      for (const e38 of c3.capacityMeshNodeIds)
        o3.set(e38, [...o3.get(e38) ?? [], c3.segmentPointId]);
      i3.set(a3.nodePortSegmentId, [...i3.get(a3.nodePortSegmentId) ?? [], c3.segmentPointId]), r3.push(c3);
    }
  return { segmentPointMap: n2, nodeToSegmentPointMap: o3, segmentToSegmentPointMap: i3 };
};
var Fj = class extends ni {
  getSolverName() {
    return "UnravelSectionSolver";
  }
  nodeMap;
  dedupedSegments;
  dedupedSegmentMap;
  MUTABLE_HOPS = 1;
  unravelSection;
  candidates = [];
  lastProcessedCandidate = null;
  bestCandidate = null;
  originalCandidate;
  rootNodeId;
  nodeIdToSegmentIds;
  segmentIdToNodeIds;
  colorMap;
  tunedNodeCapacityMap;
  MAX_CANDIDATES = 500;
  iterationsSinceImprovement = 0;
  hyperParameters;
  selectedCandidateIndex = null;
  queuedOrExploredCandidatePointModificationHashes = new Set;
  constructorParams;
  constructor(e36) {
    if (super(), this.constructorParams = e36, this.MUTABLE_HOPS = e36.MUTABLE_HOPS ?? this.MUTABLE_HOPS, this.MAX_ITERATIONS = 50000, this.hyperParameters = { ...e36.hyperParameters, MAX_ITERATIONS_WITHOUT_IMPROVEMENT: 200 }, this.nodeMap = e36.nodeMap, this.dedupedSegments = e36.dedupedSegments, e36.dedupedSegmentMap)
      this.dedupedSegmentMap = e36.dedupedSegmentMap;
    else {
      this.dedupedSegmentMap = new Map;
      for (const e37 of this.dedupedSegments)
        this.dedupedSegmentMap.set(e37.nodePortSegmentId, e37);
    }
    this.nodeIdToSegmentIds = e36.nodeIdToSegmentIds, this.segmentIdToNodeIds = e36.segmentIdToNodeIds, this.rootNodeId = e36.rootNodeId, this.colorMap = e36.colorMap ?? {}, this.unravelSection = this.createUnravelSection({ segmentPointMap: e36.segmentPointMap, nodeToSegmentPointMap: e36.nodeToSegmentPointMap, segmentToSegmentPointMap: e36.segmentToSegmentPointMap }), this.tunedNodeCapacityMap = new Map;
    for (const e37 of this.unravelSection.allNodeIds)
      this.tunedNodeCapacityMap.set(e37, Bz(this.nodeMap.get(e37)));
    this.originalCandidate = this.createInitialCandidate(), this.candidates = [this.originalCandidate];
  }
  getConstructorParams() {
    return { ...this.constructorParams, segmentPointMap: this.unravelSection.segmentPointMap, nodeToSegmentPointMap: this.unravelSection.segmentPointsInNode, segmentToSegmentPointMap: this.unravelSection.segmentPointsInSegment };
  }
  createUnravelSection(e36) {
    const t2 = Oj({ nodeId: this.rootNodeId, nodeIdToSegmentIds: this.nodeIdToSegmentIds, segmentIdToNodeIds: this.segmentIdToNodeIds, hops: this.MUTABLE_HOPS }), n2 = Oj({ nodeId: this.rootNodeId, nodeIdToSegmentIds: this.nodeIdToSegmentIds, segmentIdToNodeIds: this.segmentIdToNodeIds, hops: this.MUTABLE_HOPS + 1 }), o3 = Array.from(new Set(n2).difference(new Set(t2)));
    e36?.segmentPointMap || (e36 = Bj(this.dedupedSegments, this.segmentIdToNodeIds));
    const i3 = new Map;
    for (const t3 of n2)
      i3.set(t3, e36.nodeToSegmentPointMap.get(t3));
    const r3 = new Map;
    for (const t3 of n2)
      for (const n3 of i3.get(t3)) {
        const t4 = e36.segmentPointMap.get(n3);
        r3.set(n3, t4);
      }
    const s2 = Array.from(r3.values()), a3 = new Map;
    for (const e37 of s2)
      a3.set(e37.segmentId, [...a3.get(e37.segmentId) ?? [], e37.segmentPointId]);
    for (const [t3, n3] of i3.entries())
      for (let t4 = 0;t4 < n3.length; t4++) {
        const o4 = e36.segmentPointMap.get(n3[t4]);
        for (let i4 = t4 + 1;i4 < n3.length; i4++) {
          const t5 = e36.segmentPointMap.get(n3[i4]);
          t5.segmentPointId !== o4.segmentPointId && (t5.segmentId !== o4.segmentId && t5.connectionName === o4.connectionName && (t5.directlyConnectedSegmentPointIds.includes(o4.segmentPointId) || (o4.directlyConnectedSegmentPointIds.push(t5.segmentPointId), t5.directlyConnectedSegmentPointIds.push(o4.segmentPointId))));
        }
      }
    const c3 = new Map;
    for (const e37 of n2)
      c3.set(e37, []);
    for (const t3 of s2)
      for (const n3 of t3.capacityMeshNodeIds) {
        const o4 = c3.get(n3);
        if (o4)
          for (const i4 of t3.directlyConnectedSegmentPointIds) {
            const r4 = e36.segmentPointMap.get(i4);
            r4.segmentPointId !== t3.segmentPointId && (r4.capacityMeshNodeIds.some((e37) => e37 === n3) && (o4.some(([e37, n4]) => e37 === t3.segmentPointId && n4 === r4.segmentPointId || e37 === r4.segmentPointId && n4 === t3.segmentPointId) || o4.push([t3.segmentPointId, r4.segmentPointId])));
          }
      }
    const l3 = new Set;
    for (const e37 of t2)
      for (const t3 of this.nodeIdToSegmentIds.get(e37)) {
        this.segmentIdToNodeIds.get(t3).every((e38) => !this.nodeMap.get(e38)._containsTarget) && l3.add(t3);
      }
    const h2 = new Set;
    for (const e37 of s2) {
      const n3 = e37.capacityMeshNodeIds.some((e38) => t2.includes(e38)), o4 = this.dedupedSegmentMap.get(e37.segmentId), i4 = o4 && o4.availableZ.length > 1;
      (n3 || i4) && h2.add(e37.segmentPointId);
    }
    const d2 = new Set;
    for (const e37 of s2) {
      if (e37.capacityMeshNodeIds.some((e38) => this.nodeMap.get(e38)?._containsTarget)) {
        const t3 = this.dedupedSegmentMap.get(e37.segmentId);
        t3 && t3.availableZ.length === 1 && d2.add(e37.segmentPointId);
      }
    }
    return { allNodeIds: n2, mutableNodeIds: t2, immutableNodeIds: o3, mutableSegmentIds: l3, segmentPairsInNode: c3, segmentPointMap: r3, segmentPointsInNode: i3, segmentPointsInSegment: a3, originalPointMap: r3, mutableSegmentPointIds: h2, zLockedSegmentPointIds: d2 };
  }
  createInitialCandidate() {
    const e36 = new Map, t2 = Lj(this.unravelSection, this.nodeMap, e36), n2 = this.computeG({ issues: t2, originalCandidate: {}, operationsPerformed: 0, operation: {} });
    return { pointModifications: e36, g: n2, h: 0, f: n2, operationsPerformed: 0, candidateHash: kj(e36), issues: Lj(this.unravelSection, this.nodeMap, e36) };
  }
  get nextCandidate() {
    return this.candidates[0] ?? null;
  }
  getPointInCandidate(e36, t2) {
    const n2 = this.unravelSection.segmentPointMap.get(t2), o3 = e36.pointModifications.get(t2);
    return { x: o3?.x ?? n2.x, y: o3?.y ?? n2.y, z: o3?.z ?? n2.z, segmentId: n2.segmentId };
  }
  getConnectionSegmentPointIds(e36) {
    const t2 = [];
    for (const [n2, o3] of this.unravelSection.segmentPointMap.entries())
      o3.connectionName === e36 && t2.push(n2);
    return t2;
  }
  canConnectionUseLayer(e36, t2) {
    for (const n2 of e36) {
      const e37 = this.unravelSection.segmentPointMap.get(n2), o3 = this.dedupedSegmentMap.get(e37.segmentId);
      if (!o3 || !o3.availableZ.includes(t2))
        return false;
    }
    return true;
  }
  getOperationsForIssue(e36, t2) {
    const n2 = [];
    if (t2.type === "transition_via") {
      const [o3, i3] = t2.segmentPoints, r3 = this.getPointInCandidate(e36, o3), s2 = this.getPointInCandidate(e36, i3), a3 = this.unravelSection.segmentPointMap.get(o3), c3 = (this.unravelSection.segmentPointMap.get(i3), this.dedupedSegmentMap.get(r3.segmentId).availableZ), l3 = this.dedupedSegmentMap.get(s2.segmentId).availableZ, h2 = this.unravelSection.zLockedSegmentPointIds.has(o3), d2 = this.unravelSection.zLockedSegmentPointIds.has(i3), u2 = this.getConnectionSegmentPointIds(a3.connectionName);
      if (this.canConnectionUseLayer(u2, s2.z)) {
        const e37 = u2.filter((e38) => this.unravelSection.mutableSegmentPointIds.has(e38) && !this.unravelSection.zLockedSegmentPointIds.has(e38));
        e37.length > 0 && n2.push({ type: "change_layer", newZ: s2.z, segmentPointIds: e37 });
      }
      if (this.canConnectionUseLayer(u2, r3.z)) {
        const e37 = u2.filter((e38) => this.unravelSection.mutableSegmentPointIds.has(e38) && !this.unravelSection.zLockedSegmentPointIds.has(e38));
        e37.length > 0 && n2.push({ type: "change_layer", newZ: r3.z, segmentPointIds: e37 });
      }
      this.unravelSection.mutableSegmentPointIds.has(o3) && !h2 && c3.includes(s2.z) && n2.push({ type: "change_layer", newZ: s2.z, segmentPointIds: [o3] }), this.unravelSection.mutableSegmentPointIds.has(i3) && !d2 && l3.includes(r3.z) && n2.push({ type: "change_layer", newZ: r3.z, segmentPointIds: [i3] });
    }
    if (t2.type === "same_layer_crossing") {
      const [e37, o3] = t2.crossingLine1, [i3, r3] = t2.crossingLine2, s2 = [], a3 = this.unravelSection.segmentPointMap.get(e37), c3 = this.unravelSection.segmentPointMap.get(o3), l3 = this.unravelSection.segmentPointMap.get(i3), h2 = this.unravelSection.segmentPointMap.get(r3), d2 = this.unravelSection.mutableSegmentPointIds.has(e37), u2 = this.unravelSection.mutableSegmentPointIds.has(o3), p3 = this.unravelSection.mutableSegmentPointIds.has(i3), m2 = this.unravelSection.mutableSegmentPointIds.has(r3), g2 = this.unravelSection.zLockedSegmentPointIds.has(e37), f2 = this.unravelSection.zLockedSegmentPointIds.has(o3), _2 = this.unravelSection.zLockedSegmentPointIds.has(i3), y2 = this.unravelSection.zLockedSegmentPointIds.has(r3);
      d2 && p3 && a3.segmentId === l3.segmentId && s2.push([e37, i3]), d2 && m2 && a3.segmentId === h2.segmentId && s2.push([e37, r3]), u2 && p3 && c3.segmentId === l3.segmentId && s2.push([o3, i3]), u2 && m2 && c3.segmentId === h2.segmentId && s2.push([o3, r3]);
      for (const [e38, t3] of s2)
        n2.push({ type: "swap_position_on_segment", segmentPointIds: [e38, t3] });
      const b2 = this.getConnectionSegmentPointIds(a3.connectionName), x2 = this.getConnectionSegmentPointIds(l3.connectionName), v2 = new Set;
      for (const e38 of this.unravelSection.segmentPointMap.values()) {
        const t3 = this.dedupedSegmentMap.get(e38.segmentId);
        if (t3)
          for (const e39 of t3.availableZ)
            v2.add(e39);
      }
      for (const e38 of v2)
        if (e38 !== a3.z && this.canConnectionUseLayer(b2, e38)) {
          const t3 = b2.filter((e39) => this.unravelSection.mutableSegmentPointIds.has(e39) && !this.unravelSection.zLockedSegmentPointIds.has(e39));
          t3.length > 0 && n2.push({ type: "change_layer", newZ: e38, segmentPointIds: t3 });
        }
      for (const e38 of v2)
        if (e38 !== l3.z && this.canConnectionUseLayer(x2, e38)) {
          const t3 = x2.filter((e39) => this.unravelSection.mutableSegmentPointIds.has(e39) && !this.unravelSection.zLockedSegmentPointIds.has(e39));
          t3.length > 0 && n2.push({ type: "change_layer", newZ: e38, segmentPointIds: t3 });
        }
      const I2 = this.dedupedSegmentMap.get(a3.segmentId), S2 = this.dedupedSegmentMap.get(c3.segmentId), C = this.dedupedSegmentMap.get(l3.segmentId), P = this.dedupedSegmentMap.get(h2.segmentId), M = (e38, t3) => e38.every((e39) => e39.availableZ.includes(t3));
      if (d2 && u2 && !g2 && !f2) {
        const t3 = a3.z === 0 ? 1 : 0;
        M([I2, S2], t3) && n2.push({ type: "change_layer", newZ: t3, segmentPointIds: [e37, o3] });
      }
      if (p3 && m2 && !_2 && !y2) {
        const e38 = l3.z === 0 ? 1 : 0;
        M([C, P], e38) && n2.push({ type: "change_layer", newZ: e38, segmentPointIds: [i3, r3] });
      }
      if (d2 && !g2) {
        const t3 = a3.z === 0 ? 1 : 0;
        I2.availableZ.includes(t3) && n2.push({ type: "change_layer", newZ: t3, segmentPointIds: [e37] });
      }
      if (u2 && !f2) {
        const e38 = c3.z === 0 ? 1 : 0;
        S2.availableZ.includes(e38) && n2.push({ type: "change_layer", newZ: e38, segmentPointIds: [o3] });
      }
      if (p3 && !_2) {
        const e38 = l3.z === 0 ? 1 : 0;
        C.availableZ.includes(e38) && n2.push({ type: "change_layer", newZ: e38, segmentPointIds: [i3] });
      }
      if (m2 && !y2) {
        const e38 = h2.z === 0 ? 1 : 0;
        P.availableZ.includes(e38) && n2.push({ type: "change_layer", newZ: e38, segmentPointIds: [r3] });
      }
    }
    return n2;
  }
  computeG(e36) {
    const { issues: t2, originalCandidate: n2, operationsPerformed: o3, operation: i3 } = e36, r3 = new Map;
    for (const e37 of t2) {
      r3.has(e37.capacityMeshNodeId) || r3.set(e37.capacityMeshNodeId, { numTransitionCrossings: 0, numSameLayerCrossings: 0, numEntryExitLayerChanges: 0 });
      const t3 = r3.get(e37.capacityMeshNodeId);
      e37.type === "transition_via" ? t3.numTransitionCrossings++ : e37.type === "same_layer_crossing" ? t3.numSameLayerCrossings++ : e37.type === "double_transition_crossing" || e37.type === "single_transition_crossing" ? t3.numEntryExitLayerChanges++ : e37.type;
    }
    let s2 = 0;
    for (const [e37, { numEntryExitLayerChanges: t3, numSameLayerCrossings: n3, numTransitionCrossings: o4 }] of r3) {
      const i4 = this.nodeMap.get(e37), r4 = Math.min(jz(i4, n3, t3, o4), 0.999999);
      s2 += Math.log(1 - r4);
    }
    var a3;
    return (a3 = s2) < -Math.LN2 ? Math.log(1 - Math.exp(a3)) : Math.log(-Math.expm1(a3));
  }
  getUnexploredNeighborByApplyingOperation(e36, t2) {
    const n2 = new Map(e36.pointModifications);
    zj(n2, t2, (t3) => this.getPointInCandidate(e36, t3));
    const o3 = kj(n2);
    if (this.queuedOrExploredCandidatePointModificationHashes.has(o3))
      return null;
    const i3 = Lj(this.unravelSection, this.nodeMap, n2), r3 = e36.operationsPerformed + 1, s2 = this.computeG({ issues: i3, originalCandidate: e36, operationsPerformed: r3, operation: t2 });
    return { issues: i3, g: s2, h: 0, f: s2, pointModifications: n2, candidateHash: o3, operationsPerformed: r3 };
  }
  getNeighborOperationsForCandidate(e36) {
    return e36.issues.flatMap((t2) => this.getOperationsForIssue(e36, t2));
  }
  getNeighbors(e36) {
    const t2 = [], n2 = this.getNeighborOperationsForCandidate(e36);
    for (const o3 of n2) {
      const n3 = this.getUnexploredNeighborByApplyingOperation(e36, o3);
      n3 && t2.push(n3);
    }
    return t2;
  }
  _step() {
    const e36 = this.candidates.shift();
    this.iterationsSinceImprovement++, this.iterationsSinceImprovement > this.hyperParameters.MAX_ITERATIONS_WITHOUT_IMPROVEMENT ? this.solved = true : e36 ? (this.lastProcessedCandidate = e36, e36.f < (this.bestCandidate?.f ?? 1 / 0) && (this.bestCandidate = e36, this.iterationsSinceImprovement = 0), this.getNeighbors(e36).forEach((e37) => {
      this.queuedOrExploredCandidatePointModificationHashes.has(e37.candidateHash) || (this.queuedOrExploredCandidatePointModificationHashes.add(e37.candidateHash), this.candidates.push(e37));
    }), this.candidates.sort((e37, t2) => e37.f - t2.f), this.candidates.length = Math.min(this.candidates.length, this.MAX_CANDIDATES)) : this.solved = true;
  }
  visualize() {
    const e36 = { points: [], lines: [], rects: [], circles: [], coordinateSystem: "cartesian", title: "Unravel Section Solver" };
    let t2 = null;
    if (t2 = this.selectedCandidateIndex !== null ? this.selectedCandidateIndex === "best" ? this.bestCandidate : this.selectedCandidateIndex === "original" ? this.originalCandidate : this.candidates[this.selectedCandidateIndex] : this.solved ? this.bestCandidate : this.lastProcessedCandidate || this.candidates[0], !t2)
      return e36;
    const n2 = new Map;
    for (const [e37, o4] of this.unravelSection.segmentPointMap) {
      const i3 = { ...o4 }, r3 = t2.pointModifications.get(e37);
      r3 && (r3.x !== undefined && (i3.x = r3.x), r3.y !== undefined && (i3.y = r3.y), r3.z !== undefined && (i3.z = r3.z)), n2.set(e37, i3);
    }
    for (const [t3, o4] of n2)
      e36.points.push({ x: o4.x, y: o4.y, label: `${t3}
Segment: ${o4.segmentId} ${this.unravelSection.mutableSegmentIds.has(o4.segmentId) ? "MUTABLE" : "IMMUTABLE"}
Layer: ${o4.z}`, color: this.colorMap[o4.connectionName] || "#000" });
    const o3 = new Map;
    for (const e37 of this.unravelSection.allNodeIds)
      o3.set(e37, { numTransitionCrossings: 0, numSameLayerCrossings: 0, numEntryExitLayerChanges: 0, estPf: 0 });
    for (const e37 of t2.issues) {
      const t3 = o3.get(e37.capacityMeshNodeId);
      e37.type === "transition_via" ? t3.numTransitionCrossings++ : e37.type === "same_layer_crossing" ? t3.numSameLayerCrossings++ : e37.type !== "double_transition_crossing" && e37.type !== "single_transition_crossing" || t3.numEntryExitLayerChanges++;
    }
    for (const [e37, t3] of o3.entries()) {
      const n3 = this.nodeMap.get(e37);
      t3.estPf = jz(n3, t3.numSameLayerCrossings, t3.numEntryExitLayerChanges, t3.numTransitionCrossings);
    }
    for (const t3 of this.unravelSection.allNodeIds) {
      const n3 = this.nodeMap.get(t3), i3 = this.unravelSection.mutableNodeIds.includes(t3), r3 = o3.get(t3), s2 = [`${t3} (${i3 ? "MUT" : "IMM"})`, `${n3.width.toFixed(2)}x${n3.height.toFixed(2)}`, `Pf: ${r3.estPf.toFixed(3)}`, `TC: ${r3.numTransitionCrossings}`, `SLC: ${r3.numSameLayerCrossings}`, `EELC: ${r3.numEntryExitLayerChanges}`].join(`
`);
      e36.rects.push({ center: n3.center, label: s2, color: i3 ? "green" : "red", width: n3.width / 8, height: n3.height / 8 });
    }
    for (const [t3, o4] of this.unravelSection.segmentPointsInSegment) {
      if (o4.length <= 1)
        continue;
      const i3 = o4.map((e37) => n2.get(e37));
      for (let n3 = 0;n3 < i3.length - 1; n3++)
        e36.lines.push({ points: [{ x: i3[n3].x, y: i3[n3].y }, { x: i3[n3 + 1].x, y: i3[n3 + 1].y }], strokeColor: this.colorMap[t3] || "#000" });
    }
    for (const [t3, o4] of n2)
      for (const i3 of o4.directlyConnectedSegmentPointIds)
        if (t3 < i3) {
          const t4 = n2.get(i3);
          if (!t4)
            continue;
          const r3 = o4.z === t4.z, s2 = o4.z;
          let a3;
          a3 = r3 ? s2 === 0 ? undefined : "10 5" : "3 3 10", e36.lines.push({ points: [{ x: o4.x, y: o4.y }, { x: t4.x, y: t4.y }], strokeDash: a3, strokeColor: this.colorMap[o4.connectionName] || "#000" });
        }
    for (const o4 of t2.issues) {
      const t3 = this.nodeMap.get(o4.capacityMeshNodeId);
      if (o4.type === "transition_via")
        for (const i3 of o4.segmentPoints) {
          const o5 = n2.get(i3);
          e36.circles.push({ center: { x: o5.x, y: o5.y }, radius: t3.width / 16, stroke: "#ff0000", fill: "rgba(255, 0, 0, 0.2)", label: `Via Issue
${i3}
Layer: ${o5.z}` });
        }
      else if (o4.type === "same_layer_crossing")
        for (const [i3, r3] of [o4.crossingLine1, o4.crossingLine2]) {
          const o5 = n2.get(i3), s2 = n2.get(r3);
          e36.lines.push({ points: [{ x: o5.x, y: o5.y }, { x: s2.x, y: s2.y }], strokeColor: "rgba(255,0,0,0.2)", strokeWidth: t3.width / 32 });
        }
    }
    for (const [o4, i3] of t2.pointModifications) {
      const t3 = n2.get(o4), i4 = this.unravelSection.segmentPointMap.get(o4);
      e36.circles.push({ center: { x: t3.x, y: t3.y }, radius: 0.05, stroke: "#0000ff", fill: "rgba(0, 0, 255, 0.2)", label: `${o4}
Original: (${i4.x.toFixed(2)}, ${i4.y.toFixed(2)}, ${i4.z})
New: (${t3.x.toFixed(2)}, ${t3.y.toFixed(2)}, ${t3.z})` });
    }
    return e36;
  }
};
var $j = (e36) => (Math.round(20 * e36) / 20).toFixed(2);
var Yj = (e36) => (Math.round(1000 * e36) / 1000).toFixed(3);
oo();
var Xj = class extends Fj {
  cacheHit = false;
  cacheProvider;
  hasAttemptedToUseCache = false;
  constructor(e36) {
    super(e36), this.cacheProvider = e36.cacheProvider === undefined ? to() : e36.cacheProvider;
  }
  _step() {
    !this.hasAttemptedToUseCache && this.cacheProvider && this.attemptToUseCacheSync() || (super._step(), (this.solved || this.failed) && this.cacheProvider && this.saveToCacheSync());
  }
  computeCacheKeyAndTransform() {
    const e36 = this.nodeMap.get(this.rootNodeId), t2 = Gt(-e36.center.x, -e36.center.y), n2 = new Map, o3 = new Map, i3 = new Map, r3 = new Map, s2 = new Map, a3 = new Map;
    let c3 = 0, l3 = 0, h2 = 0;
    const d2 = [...this.unravelSection.allNodeIds].sort((e37, t3) => {
      const n3 = this.nodeMap.get(e37), o4 = this.nodeMap.get(t3);
      return n3.center.x !== o4.center.x ? n3.center.x - o4.center.x : n3.center.y - o4.center.y;
    });
    for (const e37 of d2) {
      const t3 = "node_" + c3++;
      n2.set(e37, t3), o3.set(t3, e37);
    }
    const u2 = [...Array.from(this.unravelSection.segmentPointMap.entries()).sort(([, e37], [, t3]) => e37.x !== t3.x ? e37.x - t3.x : e37.y - t3.y).map(([e37]) => e37)].sort();
    for (const e37 of u2) {
      const t3 = "sp_" + h2++;
      s2.set(e37, t3), a3.set(t3, e37);
      const n3 = this.unravelSection.segmentPointMap.get(e37).segmentId;
      if (!i3.has(n3)) {
        const e38 = "seg_" + l3++;
        i3.set(n3, e38), r3.set(e38, n3);
      }
    }
    const p3 = {};
    for (const [e37, o4] of n2.entries()) {
      const n3 = this.nodeMap.get(e37), i4 = Ht(t2, n3.center);
      p3[o4] = { width: n3.width, height: n3.height, availableZ: n3.availableZ, center: { x: $j(i4.x), y: $j(i4.y) } };
    }
    const m2 = {};
    for (const [e37, n3] of s2.entries()) {
      const o4 = this.unravelSection.segmentPointMap.get(e37), i4 = Ht(t2, { x: o4.x, y: o4.y });
      m2[n3] = { x: $j(i4.x), y: $j(i4.y), z: o4.z };
    }
    const g2 = { hyperParameters: this.hyperParameters, normalizedNodes: p3, normalizedSegmentPoints: m2, mutableHops: this.MUTABLE_HOPS }, f2 = `unravelsec:${import_object_hash3.default(g2)}`, _2 = { realToCacheTransform: t2, nodeIdMap: n2, segmentIdMap: i3, segmentPointIdMap: s2, reverseNodeIdMap: o3, reverseSegmentIdMap: r3, reverseSegmentPointIdMap: a3 };
    return this.cacheKey = f2, this.cacheToSolveSpaceTransform = _2, { cacheKey: f2, cacheToSolveSpaceTransform: _2 };
  }
  applyCachedSolution(e36) {
    if (e36.success === false)
      return void (this.failed = true);
    if (!this.cacheToSolveSpaceTransform)
      return void console.error("Cache transform not available to apply cached solution.");
    const { reverseSegmentPointIdMap: t2, reverseNodeIdMap: n2 } = this.cacheToSolveSpaceTransform, o3 = new Map;
    for (const [n3, i4] of e36.bestCandidatePointModificationsDelta) {
      const e37 = t2.get(n3);
      if (!e37) {
        console.warn(`Could not find original ID for normalized SP ID: ${n3} when applying cache.`);
        continue;
      }
      const r3 = this.unravelSection.segmentPointMap.get(e37);
      if (!r3) {
        console.warn(`Could not find original segment point for ID: ${e37} when applying cache.`);
        continue;
      }
      const s2 = {};
      if (i4.dx !== undefined) {
        const e38 = parseFloat(i4.dx);
        Number.isNaN(e38) ? console.warn(`Failed to parse cached dx coordinate: ${i4.dx}`) : s2.x = r3.x + e38;
      }
      if (i4.dy !== undefined) {
        const e38 = parseFloat(i4.dy);
        Number.isNaN(e38) ? console.warn(`Failed to parse cached dy coordinate: ${i4.dy}`) : s2.y = r3.y + e38;
      }
      i4.dz !== undefined && (s2.z = r3.z + i4.dz), Object.keys(s2).length > 0 && o3.set(e37, s2);
    }
    const i3 = Lj(this.unravelSection, this.nodeMap, o3);
    this.bestCandidate = { pointModifications: o3, issues: i3, f: e36.bestCandidateF, g: e36.bestCandidateF, h: 0, operationsPerformed: -1, candidateHash: kj(o3) }, this.cacheHit = true, this.solved = true;
  }
  attemptToUseCacheSync() {
    if (this.hasAttemptedToUseCache = true, !this.cacheProvider?.isSyncCache)
      return console.log("Cache provider is not synchronous, skipping sync cache check."), false;
    if (this.cacheKey || this.computeCacheKeyAndTransform(), !this.cacheKey)
      return console.error("Failed to compute cache key."), false;
    try {
      const e36 = this.cacheProvider.getCachedSolutionSync(this.cacheKey);
      if (e36)
        return this.applyCachedSolution(e36), true;
    } catch (e36) {
      console.error("Error attempting to use cache:", e36);
    }
    return false;
  }
  saveToCacheSync() {
    if (this.failed)
      return void this.cacheProvider?.setCachedSolutionSync(this.cacheKey, { success: false });
    if (!this.bestCandidate)
      return;
    const { segmentPointIdMap: e36 } = this.cacheToSolveSpaceTransform, t2 = [];
    for (const [n3, o3] of this.bestCandidate.pointModifications.entries()) {
      const i3 = e36.get(n3);
      if (!i3) {
        console.warn(`Could not find normalized ID for original SP ID: ${n3} when saving to cache.`);
        continue;
      }
      const r3 = this.unravelSection.segmentPointMap.get(n3);
      if (!r3) {
        console.warn(`Could not find original segment point for ID: ${n3} when saving cache.`);
        continue;
      }
      const s2 = {};
      let a3 = false;
      if (o3.x !== undefined) {
        const e37 = o3.x - r3.x, t3 = Yj(e37);
        parseFloat(t3) !== 0 && (s2.dx = t3, a3 = true);
      }
      if (o3.y !== undefined) {
        const e37 = o3.y - r3.y, t3 = Yj(e37);
        parseFloat(t3) !== 0 && (s2.dy = t3, a3 = true);
      }
      if (o3.z !== undefined) {
        const e37 = o3.z - r3.z;
        e37 !== 0 && (s2.dz = e37, a3 = true);
      }
      a3 && t2.push([i3, s2]);
    }
    const n2 = { success: true, bestCandidatePointModificationsDelta: t2, bestCandidateF: this.bestCandidate.f };
    this.cacheProvider?.setCachedSolutionSync(this.cacheKey, n2);
  }
};
var Hj = class extends ni {
  getSolverName() {
    return "UnravelMultiSectionSolver";
  }
  nodeMap;
  dedupedSegmentMap;
  dedupedSegments;
  nodeIdToSegmentIds;
  segmentIdToNodeIds;
  nodeToSegmentPointMap;
  segmentToSegmentPointMap;
  colorMap;
  tunedNodeCapacityMap;
  MAX_NODE_ATTEMPTS = 2;
  MUTABLE_HOPS = 1;
  ACCEPTABLE_PF = 0.05;
  MAX_ITERATIONS_WITHOUT_IMPROVEMENT = 200;
  nodePfMap;
  attemptsToFixNode;
  activeSubSolver = null;
  segmentPointMap;
  cacheProvider = null;
  constructor({ assignedSegments: e36, colorMap: t2, nodes: n2, cacheProvider: o3 }) {
    super(), this.stats.successfulOptimizations = 0, this.stats.failedOptimizations = 0, this.stats.cacheHits = 0, this.stats.cacheMisses = 0, this.cacheProvider = o3 ?? null, this.MAX_ITERATIONS = 1e6, this.dedupedSegments = ((e37) => {
      const t3 = [], n3 = new Map;
      let o4 = -1;
      for (const i4 of e37) {
        const e38 = `${i4.start.x}-${i4.start.y}-${i4.end.x}-${i4.end.y}-${i4.availableZ.join(",")}`, r4 = n3.get(e38);
        r4 ? i4.nodePortSegmentId = r4.nodePortSegmentId : (o4++, i4.nodePortSegmentId = `SEG${o4}`, n3.set(e38, i4), t3.push(i4));
      }
      return t3;
    })(e36), this.dedupedSegmentMap = new Map;
    for (const e37 of this.dedupedSegments)
      this.dedupedSegmentMap.set(e37.nodePortSegmentId, e37);
    this.nodeMap = new Map;
    for (const e37 of n2)
      this.nodeMap.set(e37.capacityMeshNodeId, e37);
    this.nodeIdToSegmentIds = new Map, this.segmentIdToNodeIds = new Map, this.attemptsToFixNode = new Map;
    for (const t3 of e36)
      this.segmentIdToNodeIds.set(t3.nodePortSegmentId, [...this.segmentIdToNodeIds.get(t3.nodePortSegmentId) ?? [], t3.capacityMeshNodeId]), this.nodeIdToSegmentIds.set(t3.capacityMeshNodeId, [...this.nodeIdToSegmentIds.get(t3.capacityMeshNodeId) ?? [], t3.nodePortSegmentId]);
    this.colorMap = t2 ?? {}, this.tunedNodeCapacityMap = new Map;
    for (const [e37, t3] of this.nodeMap)
      this.tunedNodeCapacityMap.set(e37, Bz(t3));
    const { segmentPointMap: i3, nodeToSegmentPointMap: r3, segmentToSegmentPointMap: s2 } = Bj(this.dedupedSegments, this.segmentIdToNodeIds);
    this.segmentPointMap = i3, this.nodeToSegmentPointMap = r3, this.segmentToSegmentPointMap = s2, this.nodePfMap = this.computeInitialPfMap();
  }
  computeInitialPfMap() {
    const e36 = new Map;
    for (const [t2, n2] of this.nodeMap.entries())
      e36.set(t2, this.computeNodePf(n2));
    return e36;
  }
  computeNodePf(e36) {
    const { numSameLayerCrossings: t2, numEntryExitLayerChanges: n2, numTransitionCrossings: o3 } = ((e37) => {
      let t3 = 0, n3 = 0, o4 = 0;
      const i3 = new Map;
      for (const t4 of e37)
        i3.has(t4.connectionName) || i3.set(t4.connectionName, []), i3.get(t4.connectionName).push(t4);
      const r3 = [], s2 = [];
      for (const [e38, t4] of i3.entries()) {
        if (t4.length < 2)
          continue;
        const o5 = t4[0];
        for (let i4 = 1;i4 < t4.length; i4++) {
          const a3 = t4[i4], c3 = { connectionName: e38, z: o5.z, points: [o5, a3] };
          o5.z !== a3.z ? (n3++, s2.push({ connectionName: e38, points: [o5, a3] })) : r3.push(c3);
        }
      }
      for (let e38 = 0;e38 < r3.length; e38++)
        for (let n4 = e38 + 1;n4 < r3.length; n4++) {
          const o5 = r3[e38], i4 = r3[n4];
          o5.z === i4.z && he(o5.points[0], o5.points[1], i4.points[0], i4.points[1]) && t3++;
        }
      for (let e38 = 0;e38 < s2.length; e38++)
        for (let t4 = e38 + 1;t4 < s2.length; t4++) {
          const n4 = s2[e38], i4 = s2[t4];
          he(n4.points[0], n4.points[1], i4.points[0], i4.points[1]) && o4++;
        }
      for (let e38 = 0;e38 < s2.length; e38++)
        for (let t4 = 0;t4 < r3.length; t4++) {
          const n4 = s2[e38], i4 = r3[t4];
          he(n4.points[0], n4.points[1], i4.points[0], i4.points[1]) && o4++;
        }
      return { numSameLayerCrossings: t3, numEntryExitLayerChanges: n3, numTransitionCrossings: o4 };
    })((this.nodeToSegmentPointMap.get(e36.capacityMeshNodeId) ?? []).map((e37) => this.segmentPointMap.get(e37)));
    return jz(e36, t2, n2, o3);
  }
  _step() {
    if (this.iterations >= this.MAX_ITERATIONS - 1)
      return void (this.solved = true);
    if (!this.activeSubSolver) {
      let e37 = null, t3 = 0;
      for (const [n3, o3] of this.nodePfMap.entries()) {
        o3 * (1 - (this.attemptsToFixNode.get(n3) ?? 0) / this.MAX_NODE_ATTEMPTS) > t3 && (t3 = o3, e37 = n3);
      }
      if (!e37 || t3 < this.ACCEPTABLE_PF)
        return void (this.solved = true);
      this.attemptsToFixNode.set(e37, (this.attemptsToFixNode.get(e37) ?? 0) + 1), this.activeSubSolver = new Xj({ dedupedSegments: this.dedupedSegments, dedupedSegmentMap: this.dedupedSegmentMap, nodeMap: this.nodeMap, nodeIdToSegmentIds: this.nodeIdToSegmentIds, segmentIdToNodeIds: this.segmentIdToNodeIds, colorMap: this.colorMap, rootNodeId: e37, MUTABLE_HOPS: this.MUTABLE_HOPS, segmentPointMap: this.segmentPointMap, nodeToSegmentPointMap: this.nodeToSegmentPointMap, segmentToSegmentPointMap: this.segmentToSegmentPointMap, cacheProvider: this.cacheProvider });
    }
    this.activeSubSolver.step();
    const { bestCandidate: e36, originalCandidate: t2, lastProcessedCandidate: n2 } = this.activeSubSolver;
    if (this.activeSubSolver.failed)
      return this.stats.failedOptimizations += 1, void (this.activeSubSolver = null);
    if (this.activeSubSolver.solved) {
      this.activeSubSolver.cacheHit ? this.stats.cacheHits += 1 : this.stats.cacheMisses += 1;
      if (e36 && e36.g < t2.g) {
        this.stats.successfulOptimizations += 1;
        for (const [t3, n3] of e36.pointModifications.entries()) {
          const e37 = this.segmentPointMap.get(t3);
          e37.x = n3.x ?? e37.x, e37.y = n3.y ?? e37.y, e37.z = n3.z ?? e37.z;
        }
        for (const e37 of this.activeSubSolver.unravelSection.allNodeIds)
          this.nodePfMap.set(e37, this.computeNodePf(this.nodeMap.get(e37)));
      } else
        this.stats.failedOptimizations += 1;
      this.activeSubSolver = null;
    }
  }
  visualize() {
    if (this.activeSubSolver)
      return this.activeSubSolver.visualize();
    const e36 = { lines: [], points: [], rects: [], circles: [], coordinateSystem: "cartesian", title: "Unravel Multi Section Solver" };
    for (const [t3, n3] of this.nodeMap.entries()) {
      const o4 = this.nodePfMap.get(t3) || 0, i3 = Math.min(o4, 1), r3 = `rgb(${Math.floor(255 * i3)}, ${Math.floor(255 * (1 - i3))}, 0)`;
      (this.attemptsToFixNode.get(t3) ?? 0) === 0 && i3 === 0 || e36.rects.push({ center: n3.center, label: [t3, `${n3.width.toFixed(2)}x${n3.height.toFixed(2)}`, `Pf: ${o4.toFixed(3)}`].join(`
`), color: r3, width: n3.width / 8, height: n3.height / 8 });
    }
    for (const t3 of this.segmentPointMap.values()) {
      const n3 = this.dedupedSegmentMap.get(t3.segmentId);
      e36.points.push({ x: t3.x, y: t3.y, label: [t3.segmentPointId, t3.segmentId, `z: ${t3.z}`, `segment.availableZ: ${n3?.availableZ.join(",")}`].join(`
`), color: this.colorMap[t3.connectionName] || "#000" });
    }
    const t2 = new Map;
    for (const e37 of this.segmentPointMap.values())
      t2.has(e37.segmentId) || t2.set(e37.segmentId, []), t2.get(e37.segmentId).push(e37);
    for (const [n3, o4] of t2.entries()) {
      if (o4.length < 2)
        continue;
      const t3 = [...o4].sort((e37, t4) => e37.x !== t4.x ? e37.x - t4.x : e37.y - t4.y);
      for (let o5 = 0;o5 < t3.length - 1; o5++)
        e36.lines.push({ points: [{ x: t3[o5].x, y: t3[o5].y }, { x: t3[o5 + 1].x, y: t3[o5 + 1].y }], strokeColor: this.colorMap[n3] || "#000" });
    }
    const n2 = new Set, o3 = Array.from(this.segmentPointMap.values());
    for (let t3 = 0;t3 < o3.length; t3++) {
      const i3 = o3[t3];
      for (let r3 = t3 + 1;r3 < o3.length; r3++) {
        const t4 = o3[r3];
        if (i3.connectionName !== t4.connectionName || i3.segmentId === t4.segmentId)
          continue;
        if (i3.capacityMeshNodeIds.some((e37) => t4.capacityMeshNodeIds.includes(e37))) {
          const o4 = `${i3.segmentPointId}-${t4.segmentPointId}`;
          if (n2.has(o4))
            continue;
          n2.add(o4);
          const r4 = i3.z === t4.z, s2 = i3.z;
          let a3;
          a3 = r4 ? s2 === 0 ? undefined : "10 5" : "3 3 10", e36.lines.push({ points: [{ x: i3.x, y: i3.y }, { x: t4.x, y: t4.y }], strokeDash: a3, strokeColor: this.colorMap[i3.connectionName] || "#666" });
        }
      }
    }
    return e36;
  }
  getNodesWithPortPoints() {
    if (!this.solved)
      throw new Error("CapacitySegmentToPointSolver not solved, can't give port points yet");
    const e36 = new Map;
    for (const t2 of this.dedupedSegments) {
      const n2 = t2.nodePortSegmentId;
      for (const t3 of this.segmentIdToNodeIds.get(n2)) {
        const n3 = this.nodeMap.get(t3);
        e36.has(t3) || e36.set(t3, { capacityMeshNodeId: t3, portPoints: [], center: n3.center, width: n3.width, height: n3.height });
      }
    }
    for (const t2 of this.segmentPointMap.values())
      for (const n2 of t2.capacityMeshNodeIds) {
        const o3 = e36.get(n2);
        o3 && o3.portPoints.push({ x: t2.x, y: t2.y, z: t2.z, connectionName: t2.connectionName, rootConnectionName: t2.rootConnectionName });
      }
    return Array.from(e36.values());
  }
};
function Vj(e36, t2, n2, o3 = {}) {
  return { solverName: e36, solverClass: t2, getConstructorParams: n2, onSolved: o3.onSolved };
}
var Wj = class extends ni {
  constructor(e36, t2 = {}) {
    super(), this.srj = e36, this.opts = t2, this.srj = e36, this.opts = { ...t2 }, this.MAX_ITERATIONS = 1e8, this.viaDiameter = Yo(e36).padDiameter, this.minTraceWidth = e36.minTraceWidth;
    const n2 = this.opts;
    if (n2.capacityDepth === undefined) {
      const t3 = e36.bounds.maxX - e36.bounds.minX, o3 = e36.bounds.maxY - e36.bounds.minY, i3 = Math.max(t3, o3), r3 = n2.targetMinCapacity ?? 0.5;
      n2.capacityDepth = Fz(i3, r3);
    }
    this.connMap = ei(e36), this.colorMap = Eo(e36, this.connMap), this.cacheProvider = n2.cacheProvider === undefined ? no() : n2.cacheProvider === null ? null : n2.cacheProvider, this.startTimeOfPhase = {}, this.endTimeOfPhase = {}, this.timeSpentOnPhase = {};
  }
  getSolverName() {
    return "AutoroutingPipeline1_OriginalUnravel";
  }
  netToPointPairsSolver;
  nodeSolver;
  nodeTargetMerger;
  edgeSolver;
  initialPathingSolver;
  pathingOptimizer;
  edgeToPortSegmentSolver;
  colorMap;
  segmentToPointSolver;
  unravelMultiSectionSolver;
  segmentToPointOptimizer;
  highDensityRouteSolver;
  highDensityStitchSolver;
  singleLayerNodeMerger;
  strawSolver;
  deadEndSolver;
  traceSimplificationSolver;
  viaDiameter;
  minTraceWidth;
  startTimeOfPhase;
  endTimeOfPhase;
  timeSpentOnPhase;
  activeSubSolver = null;
  connMap;
  srjWithPointPairs;
  capacityNodes = null;
  capacityEdges = null;
  cacheProvider = null;
  pipelineDef = [Vj("netToPointPairsSolver", pB, (e36) => [e36.srj, e36.colorMap, ti(e36.srj)], { onSolved: (e36) => {
    e36.srjWithPointPairs = e36.netToPointPairsSolver?.getNewSimpleRouteJson(), e36.colorMap = Eo(e36.srjWithPointPairs, this.connMap), e36.connMap = ei(e36.srjWithPointPairs);
  } }), Vj("nodeSolver", lj, (e36) => [e36.netToPointPairsSolver?.getNewSimpleRouteJson() || e36.srj, e36.opts], { onSolved: (e36) => {
    e36.capacityNodes = e36.nodeSolver?.finishedNodes;
  } }), Vj("singleLayerNodeMerger", Ej, (e36) => [e36.nodeSolver?.finishedNodes], { onSolved: (e36) => {
    e36.capacityNodes = e36.singleLayerNodeMerger?.newNodes;
  } }), Vj("strawSolver", Aj, (e36) => [{ nodes: e36.singleLayerNodeMerger?.newNodes }], { onSolved: (e36) => {
    e36.capacityNodes = e36.strawSolver?.getResultNodes();
  } }), Vj("edgeSolver", ui, (e36) => [e36.capacityNodes], { onSolved: (e36) => {
    e36.capacityEdges = e36.edgeSolver?.edges;
  } }), Vj("deadEndSolver", Nj, (e36) => [{ nodes: e36.capacityNodes, edges: e36.capacityEdges }], { onSolved: (e36) => {
    const t2 = e36.deadEndSolver?.removedNodeIds;
    e36.capacityNodes = e36.capacityNodes.filter((e37) => !t2.has(e37.capacityMeshNodeId)), e36.capacityEdges = e36.capacityEdges.filter((e37) => e37.nodeIds.every((e38) => !t2.has(e38)));
  } }), Vj("initialPathingSolver", mj, (e36) => [{ simpleRouteJson: e36.srjWithPointPairs, nodes: e36.capacityNodes, edges: e36.capacityEdges || [], colorMap: e36.colorMap, hyperParameters: { MAX_CAPACITY_FACTOR: 1 } }]), Vj("pathingOptimizer", wj, (e36) => [{ initialPathingSolver: e36.initialPathingSolver, simpleRouteJson: e36.srjWithPointPairs, nodes: e36.capacityNodes, edges: e36.capacityEdges || [], colorMap: e36.colorMap, cacheProvider: e36.cacheProvider, hyperParameters: { MAX_CAPACITY_FACTOR: 1 } }]), Vj("edgeToPortSegmentSolver", nj, (e36) => [{ nodes: e36.capacityNodes, edges: e36.capacityEdges || [], capacityPaths: e36.pathingOptimizer?.getCapacityPaths() || [], colorMap: e36.colorMap }]), Vj("segmentToPointSolver", hj, (e36) => {
    const t2 = [];
    return e36.edgeToPortSegmentSolver?.nodePortSegments && e36.edgeToPortSegmentSolver.nodePortSegments.forEach((e37) => {
      t2.push(...e37);
    }), [{ segments: t2, colorMap: e36.colorMap, nodes: e36.capacityNodes }];
  }), Vj("unravelMultiSectionSolver", Hj, (e36) => [{ assignedSegments: e36.segmentToPointSolver?.solvedSegments || [], colorMap: e36.colorMap, nodes: e36.capacityNodes, cacheProvider: this.cacheProvider }]), Vj("highDensityRouteSolver", Dz, (e36) => [{ nodePortPoints: e36.unravelMultiSectionSolver?.getNodesWithPortPoints() ?? e36.segmentToPointOptimizer?.getNodesWithPortPoints() ?? [], colorMap: e36.colorMap, connMap: e36.connMap, viaDiameter: e36.viaDiameter, traceWidth: e36.minTraceWidth }]), Vj("highDensityStitchSolver", Rj, (e36) => [{ connections: e36.srjWithPointPairs.connections, hdRoutes: e36.highDensityRouteSolver.routes, colorMap: e36.colorMap, layerCount: e36.srj.layerCount, defaultViaDiameter: e36.viaDiameter }]), Vj("traceSimplificationSolver", WF, (e36) => [{ hdRoutes: e36.highDensityStitchSolver.mergedHdRoutes, obstacles: e36.srj.obstacles, connMap: e36.connMap, colorMap: e36.colorMap, outline: e36.srj.outline, defaultViaDiameter: e36.viaDiameter, layerCount: e36.srj.layerCount }])];
  getConstructorParams() {
    return [this.srj, this.opts];
  }
  currentPipelineStepIndex = 0;
  _step() {
    const e36 = this.pipelineDef[this.currentPipelineStepIndex];
    if (!e36)
      return void (this.solved = true);
    if (this.activeSubSolver)
      return this.activeSubSolver.step(), void (this.activeSubSolver.solved ? (this.endTimeOfPhase[e36.solverName] = performance.now(), this.timeSpentOnPhase[e36.solverName] = this.endTimeOfPhase[e36.solverName] - this.startTimeOfPhase[e36.solverName], e36.onSolved?.(this), this.activeSubSolver = null, this.currentPipelineStepIndex++) : this.activeSubSolver.failed && (this.error = this.activeSubSolver?.error, this.failed = true, this.activeSubSolver = null));
    const t2 = e36.getConstructorParams(this);
    this.activeSubSolver = new e36.solverClass(...t2), this[e36.solverName] = this.activeSubSolver, this.timeSpentOnPhase[e36.solverName] = 0, this.startTimeOfPhase[e36.solverName] = performance.now();
  }
  solveUntilPhase(e36) {
    for (;this.getCurrentPhase() !== e36; )
      this.step();
  }
  getCurrentPhase() {
    return this.pipelineDef[this.currentPipelineStepIndex]?.solverName ?? "none";
  }
  visualize() {
    if (!this.solved && this.activeSubSolver)
      return this.activeSubSolver.visualize();
    const e36 = this.netToPointPairsSolver?.visualize(), t2 = this.nodeSolver?.visualize(), n2 = this.nodeTargetMerger?.visualize(), o3 = this.singleLayerNodeMerger?.visualize(), i3 = this.strawSolver?.visualize(), r3 = this.edgeSolver?.visualize(), s2 = this.deadEndSolver?.visualize(), a3 = this.initialPathingSolver?.visualize(), c3 = this.pathingOptimizer?.visualize(), l3 = this.edgeToPortSegmentSolver?.visualize(), h2 = this.segmentToPointSolver?.visualize(), d2 = this.unravelMultiSectionSolver?.visualize() ?? this.segmentToPointOptimizer?.visualize(), u2 = this.highDensityRouteSolver?.visualize(), p3 = this.highDensityStitchSolver?.visualize(), m2 = this.traceSimplificationSolver?.visualize(), g2 = this.srj.outline, f2 = [];
    if (f2.push({ points: [{ x: this.srj.bounds?.minX ?? -50, y: this.srj.bounds?.minY ?? -50 }, { x: this.srj.bounds?.maxX ?? 50, y: this.srj.bounds?.minY ?? -50 }, { x: this.srj.bounds?.maxX ?? 50, y: this.srj.bounds?.maxY ?? 50 }, { x: this.srj.bounds?.minX ?? -50, y: this.srj.bounds?.maxY ?? 50 }, { x: this.srj.bounds?.minX ?? -50, y: this.srj.bounds?.minY ?? -50 }], strokeColor: "rgba(255,0,0,0.25)" }), g2 && g2.length >= 2) {
      const e37 = g2.map((e38) => ({ x: e38.x, y: e38.y }));
      e37.push({ ...e37[0] }), f2.push({ points: e37, strokeColor: "rgba(0, 136, 255, 0.95)" });
    }
    const _2 = Lo(this.srj), y2 = { points: [...this.srj.connections.flatMap((e37) => e37.pointsToConnect.map((t3) => ({ ...t3, layer: Bo(t3, this.srj.layerCount), label: `${e37.name} ${t3.pcb_port_id ?? ""}` })))], rects: [...(this.srj.obstacles ?? []).filter((e37) => !e37.isCopperPour).map((e37) => ({ ...e37, fill: e37.layers?.includes("top") ? "rgba(255,0,0,0.25)" : e37.layers?.includes("bottom") ? "rgba(0,0,255,0.25)" : "rgba(255,0,0,0.25)", layer: jo(e37, this.srj.layerCount), label: _2(e37) }))], lines: f2 }, b2 = [y2, e36, t2, n2, o3, i3, r3, s2, a3, c3, l3, h2, d2, u2 ? pi(y2, u2) : null, p3, m2, this.solved ? pi({ lines: f2 }, Wo(this.getOutputSimpleRouteJson())) : null].filter(Boolean);
    return pi(...b2);
  }
  preview() {
    if (this.highDensityRouteSolver) {
      const e36 = [];
      for (let t2 = this.highDensityRouteSolver.routes.length - 1;t2 >= 0; t2--) {
        const n2 = this.highDensityRouteSolver.routes[t2];
        if (e36.push({ points: n2.route.map((e37) => ({ x: e37.x, y: e37.y })), strokeColor: this.colorMap[n2.connectionName] }), e36.length > 200)
          break;
      }
      return { lines: e36 };
    }
    if (this.pathingOptimizer) {
      const e36 = [];
      for (const t2 of this.pathingOptimizer.connectionsWithNodes)
        t2.path && e36.push({ points: t2.path.map((e37) => ({ x: e37.center.x, y: e37.center.y })), strokeColor: this.colorMap[t2.connection.name] });
      return { lines: e36 };
    }
    return this.netToPointPairsSolver ? this.netToPointPairsSolver?.visualize() : {};
  }
  _getOutputHdRoutes() {
    return this.traceSimplificationSolver?.simplifiedHdRoutes ?? this.highDensityStitchSolver.mergedHdRoutes;
  }
  getOutputSimplifiedPcbTraces() {
    if (!this.solved || !this.highDensityRouteSolver)
      throw new Error("Cannot get output before solving is complete");
    const e36 = [], t2 = this._getOutputHdRoutes();
    for (const n2 of this.netToPointPairsSolver?.newConnections ?? []) {
      const o3 = n2.__netConnectionName ?? this.srj.connections.find((e37) => e37.name === n2.name)?.__netConnectionName, i3 = t2.filter((e37) => e37.connectionName === n2.name);
      for (let t3 = 0;t3 < i3.length; t3++) {
        const r3 = i3[t3], s2 = { type: "pcb_trace", pcb_trace_id: `${n2.name}_${t3}`, connection_name: o3 ?? n2.__rootConnectionNames?.[0] ?? n2.name, route: Ro(r3, this.srj.layerCount) };
        e36.push(s2);
      }
    }
    return e36;
  }
  getOutputSimpleRouteJson() {
    return { ...this.srj, traces: this.getOutputSimplifiedPcbTraces() };
  }
};
function Gj(e36) {
  const { pos: t2, segments: n2, dir: o3, keepoutRadius: i3 } = e36;
  let r3 = 1 / 0;
  const s2 = i3 / 4, a3 = { x: t2.x - o3.x * s2, y: t2.y - o3.y * s2 }, c3 = { x: t2.x + o3.x * s2, y: t2.y + o3.y * s2 };
  for (const e37 of n2) {
    const t3 = we(a3, c3, e37.start, e37.end);
    r3 = Math.min(r3, t3);
  }
  return r3;
}
function Uj(e36, t2, n2, o3) {
  const i3 = Zj(n2, o3, e36), r3 = Zj(n2, o3, t2), s2 = Zj(e36, t2, n2), a3 = Zj(e36, t2, o3);
  if ((i3 > 0 && r3 < 0 || i3 < 0 && r3 > 0) && (s2 > 0 && a3 < 0 || s2 < 0 && a3 > 0))
    return true;
  const c3 = 0.0001;
  return !!(Math.abs(i3) < c3 && qj(n2, o3, e36)) || (!!(Math.abs(r3) < c3 && qj(n2, o3, t2)) || (!!(Math.abs(s2) < c3 && qj(e36, t2, n2)) || !!(Math.abs(a3) < c3 && qj(e36, t2, o3))));
}
function Zj(e36, t2, n2) {
  return (n2.x - e36.x) * (t2.y - e36.y) - (t2.x - e36.x) * (n2.y - e36.y);
}
function qj(e36, t2, n2) {
  return n2.x >= Math.min(e36.x, t2.x) - 0.0001 && n2.x <= Math.max(e36.x, t2.x) + 0.0001 && n2.y >= Math.min(e36.y, t2.y) - 0.0001 && n2.y <= Math.max(e36.y, t2.y) + 0.0001;
}
function Jj(e36, t2, n2) {
  for (const o3 of n2)
    if (Uj(e36, t2, o3.start, o3.end))
      return false;
  return true;
}
var Qj = 0.0001;
function Kj(e36) {
  const t2 = e36.width / 2, n2 = e36.height / 2, o3 = e36.center.x, i3 = e36.center.y, r3 = { x: o3 - t2, y: i3 + n2 }, s2 = { x: o3 + t2, y: i3 + n2 }, a3 = { x: o3 - t2, y: i3 - n2 }, c3 = { x: o3 + t2, y: i3 - n2 };
  return [{ start: r3, end: s2 }, { start: s2, end: c3 }, { start: c3, end: a3 }, { start: a3, end: r3 }];
}
function e$(e36, t2, n2 = 0.1) {
  const o3 = t2.x - e36.x, i3 = t2.y - e36.y, r3 = Math.sqrt(o3 * o3 + i3 * i3);
  if (r3 === 0)
    return [];
  const s2 = -(i3 / r3), a3 = o3 / r3, c3 = n2 / 2;
  return [{ start: { x: e36.x + s2 * c3, y: e36.y + a3 * c3 }, end: { x: t2.x + s2 * c3, y: t2.y + a3 * c3 } }, { start: { x: e36.x - s2 * c3, y: e36.y - a3 * c3 }, end: { x: t2.x - s2 * c3, y: t2.y - a3 * c3 } }];
}
function t$(e36, t2, n2) {
  const o3 = Math.hypot(e36.start.x - t2.x, e36.start.y - t2.y), i3 = Math.hypot(e36.end.x - t2.x, e36.end.y - t2.y);
  if (o3 <= n2 || i3 <= n2)
    return true;
  const r3 = e36.end.x - e36.start.x, s2 = e36.end.y - e36.start.y, a3 = r3 * r3 + s2 * s2;
  if (a3 === 0)
    return false;
  const c3 = Math.max(0, Math.min(1, ((t2.x - e36.start.x) * r3 + (t2.y - e36.start.y) * s2) / a3)), l3 = e36.start.x + c3 * r3, h2 = e36.start.y + c3 * s2;
  return Math.hypot(l3 - t2.x, h2 - t2.y) <= n2;
}
function n$(e36, t2, n2) {
  if (!n2 || n2.length === 0)
    return false;
  for (const o3 of n2) {
    const n3 = Math.abs(e36.x - o3.start.x) < Qj && Math.abs(e36.y - o3.start.y) < Qj && Math.abs(t2.x - o3.end.x) < Qj && Math.abs(t2.y - o3.end.y) < Qj, i3 = Math.abs(e36.x - o3.end.x) < Qj && Math.abs(e36.y - o3.end.y) < Qj && Math.abs(t2.x - o3.start.x) < Qj && Math.abs(t2.y - o3.start.y) < Qj;
    if (n3 || i3)
      return true;
  }
  return false;
}
function o$(e36, t2, n2, o3, i3) {
  const r3 = [];
  for (let s2 = 0;s2 < e36.length - 1; s2++) {
    const a3 = e36[s2], c3 = e36[s2 + 1];
    n$(a3, c3, i3) || t$({ start: a3, end: c3 }, n2, o3 + t2) && r3.push(...e$(a3, c3, t2));
  }
  return r3;
}
var i$ = 0.0001;
function r$(e36, t2, n2, o3) {
  const i3 = t2.x - e36.x, r3 = t2.y - e36.y, s2 = o3.x - n2.x, a3 = o3.y - n2.y, c3 = i3 * a3 - r3 * s2;
  if (Math.abs(c3) < 0.0000000001)
    return null;
  const l3 = n2.x - e36.x, h2 = n2.y - e36.y, d2 = (l3 * a3 - h2 * s2) / c3, u2 = (l3 * r3 - h2 * i3) / c3, p3 = 0.000001;
  return d2 > p3 && d2 < 0.999999 && u2 > p3 && u2 < 0.999999 ? { x: e36.x + d2 * i3, y: e36.y + d2 * r3 } : null;
}
function s$(e36, t2) {
  if (!t2 || t2.length === 0)
    return false;
  for (const n2 of t2)
    if (Math.abs(e36.x - n2.start.x) < i$ && Math.abs(e36.y - n2.start.y) < i$ || Math.abs(e36.x - n2.end.x) < i$ && Math.abs(e36.y - n2.end.y) < i$)
      return true;
  return false;
}
function a$(e36, t2, n2, o3) {
  if (!o3 || o3.length === 0)
    return false;
  for (let i3 = t2;i3 <= n2; i3++)
    if (i3 >= 0 && i3 < e36.length && s$(e36[i3], o3))
      return true;
  return false;
}
var c$ = 0.0001;
var l$ = class extends ni {
  constructor(e36) {
    super(), this.input = e36;
    const t2 = e36.srj?.layerCount ?? 2;
    this.input = { ...e36, obstacles: ca(e36.obstacles, t2) }, this.MAX_ITERATIONS = 1e6, this.originalHdRoutes = [...this.input.hdRoutes], this.hdRoutes = this.input.hdRoutes, this.KEEPOUT_RADIUS_SCHEDULE = e36.keepoutRadiusSchedule ?? [0.3, 0.5, 0.5], this.currentKeepoutRadius = this.KEEPOUT_RADIUS_SCHEDULE[0] ?? 0.15, this.unprocessedRoutes = [...this.hdRoutes], this.smoothedCursorRoutes = [...this.unprocessedRoutes];
    const n2 = [...this.input.obstacles, ...this.getJumperPadObstacles()];
    this.obstacleSHI = new ZF("flatbush", n2), this.boardOutlineRoutes = this.createBoardOutlineRoutes(), this.hdRouteSHI = new xr([...this.hdRoutes, ...this.boardOutlineRoutes]);
    for (const [e37, t3, n3] of this.hdRoutes.flatMap((e38) => [[e38.route[0], e38.connectionName, e38.rootConnectionName], [e38.route[e38.route.length - 1], e38.connectionName, e38.rootConnectionName]])) {
      const o3 = this.obstacleSHI.searchArea(e37.x, e37.y, 0.01, 0.01).filter((t4) => t4.__zLayers?.includes(e37.z));
      if (o3.length === 0)
        continue;
      const i3 = o3[0];
      this.input.connMap.addConnections([[t3, n3, ...i3.offBoardConnectsTo ?? [], i3.obstacleId, ...i3.connectedTo].filter(Boolean)]);
    }
  }
  getSolverName() {
    return "TraceKeepoutSolver";
  }
  originalHdRoutes;
  hdRoutes;
  redrawnHdRoutes = [];
  KEEPOUT_RADIUS_SCHEDULE;
  currentScheduleIndex = 0;
  currentKeepoutRadius;
  unprocessedRoutes = [];
  smoothedCursorRoutes = [];
  processedRoutes = [];
  currentTrace = null;
  cursorPosition = null;
  lastCursorPosition = null;
  drawPosition = null;
  currentTraceSegmentIndex = 0;
  currentTraceSegmentT = 0;
  recordedDrawPositions = [];
  lastCollidingSegments = [];
  currentTraceJumperSegments = new Map;
  obstacleSHI;
  hdRouteSHI;
  boardOutlineRoutes = [];
  getSmoothDistance() {
    return this.currentKeepoutRadius;
  }
  getJumperPadObstacles() {
    const e36 = [];
    if (!this.input.jumpers)
      return e36;
    for (const t2 of this.input.jumpers)
      for (const n2 of t2.pads)
        e36.push({ ...n2, __zLayers: [0] });
    return e36;
  }
  buildJumperSegmentMap(e36) {
    const t2 = new Map;
    if (!e36.jumpers || e36.jumpers.length === 0)
      return t2;
    const n2 = e36.route;
    for (const o3 of e36.jumpers) {
      let e37 = -1, i3 = 1 / 0;
      for (let t3 = 0;t3 < n2.length - 1; t3++) {
        const r3 = n2[t3], s2 = n2[t3 + 1], a3 = Math.sqrt((r3.x - o3.start.x) ** 2 + (r3.y - o3.start.y) ** 2), c3 = Math.sqrt((s2.x - o3.end.x) ** 2 + (s2.y - o3.end.y) ** 2), l3 = a3 + c3, h2 = Math.sqrt((r3.x - o3.end.x) ** 2 + (r3.y - o3.end.y) ** 2), d2 = Math.sqrt((s2.x - o3.start.x) ** 2 + (s2.y - o3.start.y) ** 2), u2 = h2 + d2, p3 = Math.min(l3, u2);
        (l3 <= u2 ? a3 : h2) < 1 && (l3 <= u2 ? c3 : d2) < 1 && p3 < i3 && (i3 = p3, e37 = t3);
      }
      e37 >= 0 && t2.set(e37, o3);
    }
    return t2;
  }
  _step() {
    if (!this.currentTrace) {
      const e37 = this.unprocessedRoutes.shift();
      if (!e37)
        return this.currentScheduleIndex++, this.currentScheduleIndex < this.KEEPOUT_RADIUS_SCHEDULE.length ? (this.currentKeepoutRadius = this.KEEPOUT_RADIUS_SCHEDULE[this.currentScheduleIndex], this.unprocessedRoutes = Sr([...this.processedRoutes], this.currentScheduleIndex), this.smoothedCursorRoutes = [...this.unprocessedRoutes], this.processedRoutes = [], void (this.hdRouteSHI = new xr([...this.unprocessedRoutes, ...this.boardOutlineRoutes]))) : (this.redrawnHdRoutes = this.processedRoutes, void (this.solved = true));
      if (this.currentTrace = e37, this.currentTrace.route.length < 2)
        return this.processedRoutes.push(this.currentTrace), void (this.currentTrace = null);
      this.currentTraceJumperSegments = this.buildJumperSegmentMap(this.currentTrace);
      const t3 = this.currentTrace.route[0];
      return this.cursorPosition = { ...t3 }, this.lastCursorPosition = { ...t3 }, this.drawPosition = { x: t3.x, y: t3.y }, this.currentTraceSegmentIndex = 0, this.currentTraceSegmentT = 0, void (this.recordedDrawPositions = [{ ...t3 }]);
    }
    this.lastCursorPosition = { ...this.cursorPosition };
    const e36 = this.stepCursorForward();
    if (e36 === "end")
      return void this.finalizeCurrentTrace();
    if (e36 === "jumper")
      return void (this.drawPosition = { x: this.cursorPosition.x, y: this.cursorPosition.y });
    const t2 = this.getCollidingSegments(this.cursorPosition);
    this.lastCollidingSegments = t2;
    const n2 = function(e37) {
      const { cursorPosition: t3, lastCursorPosition: n3, collidingSegments: o4, keepoutRadius: i3 } = e37;
      if (o4.length === 0)
        return null;
      const r3 = 0.0001, s2 = t3.x - n3.x, a3 = t3.y - n3.y, c3 = Math.sqrt(s2 * s2 + a3 * a3), l3 = c3 > r3 ? { x: s2 / c3, y: a3 / c3 } : { x: 1, y: 0 }, h2 = -l3.y, d2 = l3.x, u2 = Gj({ pos: t3, segments: o4, dir: l3, keepoutRadius: i3 });
      if (u2 >= i3)
        return null;
      for (let e38 = 1;e38 <= 20; e38++) {
        const n4 = e38 / 20 * i3, r4 = { x: t3.x + h2 * n4, y: t3.y + d2 * n4 }, s3 = Gj({ pos: r4, segments: o4, dir: l3, keepoutRadius: i3 }), a4 = { x: t3.x - h2 * n4, y: t3.y - d2 * n4 }, c4 = Gj({ pos: a4, segments: o4, dir: l3, keepoutRadius: i3 }), u3 = s3 >= i3 && Jj(t3, r4, o4), p4 = c4 >= i3 && Jj(t3, a4, o4);
        if (u3 && p4)
          return s3 >= c4 ? r4 : a4;
        if (u3)
          return r4;
        if (p4)
          return a4;
      }
      const p3 = i3, m2 = [];
      for (let e38 = -60;e38 <= 60; e38++) {
        const n4 = e38 / 60 * p3, r4 = { x: t3.x + h2 * n4, y: t3.y + d2 * n4 }, s3 = Gj({ pos: r4, segments: o4, dir: l3, keepoutRadius: i3 }), a4 = Jj(t3, r4, o4);
        m2.push({ pos: r4, clearance: s3, dist: Math.abs(n4), pathClear: a4, index: e38 });
      }
      const g2 = m2.filter((e38) => e38.pathClear), f2 = m2.findIndex((e38) => e38.index === 0), _2 = f2 >= 0 ? f2 : Math.floor(m2.length / 2);
      let y2 = null;
      for (let e38 = _2 + 1;e38 < m2.length - 1; e38++) {
        const t4 = m2[e38 - 1], n4 = m2[e38], o5 = m2[e38 + 1];
        if (n4.clearance >= t4.clearance && n4.clearance >= o5.clearance) {
          y2 = n4;
          break;
        }
      }
      let b2 = null;
      for (let e38 = _2 - 1;e38 > 0; e38--) {
        const t4 = m2[e38 - 1], n4 = m2[e38], o5 = m2[e38 + 1];
        if (n4.clearance >= t4.clearance && n4.clearance >= o5.clearance) {
          b2 = n4;
          break;
        }
      }
      let x2 = null, v2 = null;
      if (g2.length > 0) {
        const e38 = g2.findIndex((e39) => e39.index === 0), t4 = e38 >= 0 ? e38 : Math.floor(g2.length / 2);
        for (let e39 = t4 + 1;e39 < g2.length - 1; e39++) {
          const t5 = g2[e39 - 1], n4 = g2[e39], o5 = g2[e39 + 1];
          if (n4.clearance >= t5.clearance && n4.clearance >= o5.clearance) {
            x2 = n4;
            break;
          }
        }
        for (let e39 = t4 - 1;e39 > 0; e39--) {
          const t5 = g2[e39 - 1], n4 = g2[e39], o5 = g2[e39 + 1];
          if (n4.clearance >= t5.clearance && n4.clearance >= o5.clearance) {
            v2 = n4;
            break;
          }
        }
      }
      const I2 = [y2, b2, x2, v2, m2.find((e38) => e38.index === 0)].filter((e38) => e38 != null), S2 = new Set, C = I2.filter((e38) => {
        const t4 = `${e38.pos.x.toFixed(6)},${e38.pos.y.toFixed(6)}`;
        return !S2.has(t4) && (S2.add(t4), true);
      });
      if (C.length === 0) {
        let e38 = m2[0];
        if (!e38)
          return null;
        for (const t4 of m2)
          t4.clearance > e38.clearance && (e38 = t4);
        return Math.sqrt((e38.pos.x - t3.x) ** 2 + (e38.pos.y - t3.y) ** 2) > r3 ? e38.pos : null;
      }
      let P;
      if (u2 < 0.15 * i3) {
        P = C[0];
        for (const e38 of C)
          e38.clearance > P.clearance && (P = e38);
      } else {
        const e38 = C.filter((e39) => e39.pathClear), t4 = e38.length > 0 ? e38 : C;
        P = t4[0];
        for (const e39 of t4)
          e39.clearance > P.clearance && (P = e39);
      }
      return Math.sqrt((P.pos.x - t3.x) ** 2 + (P.pos.y - t3.y) ** 2) > r3 ? P.pos : null;
    }({ cursorPosition: this.cursorPosition, lastCursorPosition: this.lastCursorPosition, collidingSegments: t2, keepoutRadius: this.currentKeepoutRadius });
    this.drawPosition = n2 ?? { ...this.cursorPosition };
    const o3 = this.recordedDrawPositions[this.recordedDrawPositions.length - 1];
    if (o3 && this.drawPosition) {
      const e37 = { x: o3.x, y: o3.y, z: o3.z }, t3 = { x: this.drawPosition.x, y: this.drawPosition.y, z: this.cursorPosition.z };
      this.segmentIntersectsOtherRoutes(e37, t3) && (this.drawPosition = { ...this.cursorPosition });
    }
    this.recordedDrawPositions.push({ x: this.drawPosition.x, y: this.drawPosition.y, z: this.cursorPosition.z });
  }
  getStepDistance() {
    return this.currentKeepoutRadius / 2;
  }
  getJumperAtCurrentSegmentStart() {
    return this.currentTraceSegmentT > c$ ? null : this.currentTraceJumperSegments.get(this.currentTraceSegmentIndex) ?? null;
  }
  stepCursorForward() {
    if (!this.currentTrace || !this.cursorPosition)
      return "end";
    const e36 = this.currentTrace.route;
    let t2 = this.getStepDistance();
    for (;t2 > 0; ) {
      if (this.currentTraceSegmentIndex >= e36.length - 1)
        return "end";
      const n2 = this.getJumperAtCurrentSegmentStart();
      if (n2) {
        const t3 = e36[this.currentTraceSegmentIndex], o4 = e36[this.currentTraceSegmentIndex + 1], i4 = Math.sqrt((t3.x - n2.start.x) ** 2 + (t3.y - n2.start.y) ** 2), r4 = Math.sqrt((t3.x - n2.end.x) ** 2 + (t3.y - n2.end.y) ** 2), s3 = i4 <= r4 ? n2.start : n2.end, a4 = i4 <= r4 ? n2.end : n2.start;
        return this.recordedDrawPositions.push({ x: s3.x, y: s3.y, z: t3.z, insideJumperPad: true }), this.recordedDrawPositions.push({ x: a4.x, y: a4.y, z: o4.z, insideJumperPad: true }), this.cursorPosition = { x: a4.x, y: a4.y, z: o4.z }, this.currentTraceSegmentIndex++, this.currentTraceSegmentT = 0, "jumper";
      }
      const o3 = e36[this.currentTraceSegmentIndex], i3 = e36[this.currentTraceSegmentIndex + 1], r3 = i3.x - o3.x, s2 = i3.y - o3.y, a3 = Math.sqrt(r3 * r3 + s2 * s2);
      if (a3 === 0) {
        this.currentTraceSegmentIndex++, this.currentTraceSegmentT = 0;
        continue;
      }
      const c3 = this.currentTraceSegmentT * a3, l3 = a3 - c3;
      if (t2 <= l3) {
        const e37 = c3 + t2;
        return this.currentTraceSegmentT = e37 / a3, this.cursorPosition = { x: o3.x + r3 * this.currentTraceSegmentT, y: o3.y + s2 * this.currentTraceSegmentT, z: o3.z }, "stepped";
      }
      if (t2 -= l3, this.currentTraceSegmentIndex++, this.currentTraceSegmentT = 0, this.currentTraceSegmentIndex >= e36.length - 1) {
        const t3 = e36[e36.length - 1];
        return this.cursorPosition = { ...t3 }, "end";
      }
    }
    return "stepped";
  }
  getCollidingSegments(e36) {
    if (!this.currentTrace)
      return [];
    const t2 = this.currentTrace.rootConnectionName ?? this.currentTrace.connectionName, n2 = 2 * this.currentKeepoutRadius, o3 = [], i3 = this.obstacleSHI.searchArea(e36.x, e36.y, n2, n2).filter((t3) => t3.__zLayers?.includes(e36.z));
    for (const n3 of i3) {
      if (n3.__zLayers && !n3.__zLayers.includes(e36.z))
        continue;
      if (n3.connectedTo.includes(t2))
        continue;
      if (n3.obstacleId && this.input.connMap.areIdsConnected(t2, n3.obstacleId))
        continue;
      let i4 = false;
      for (const e37 of n3.connectedTo)
        if (this.input.connMap.areIdsConnected(t2, e37)) {
          i4 = true;
          break;
        }
      i4 || o3.push(...Kj(n3));
    }
    const r3 = this.hdRouteSHI.getConflictingRoutesNearPoint({ x: e36.x, y: e36.y, z: e36.z }, n2);
    for (const { conflictingRoute: i4 } of r3) {
      const r4 = i4.rootConnectionName ?? i4.connectionName;
      if (r4 === t2)
        continue;
      if (this.input.connMap.areIdsConnected(t2, r4))
        continue;
      const s2 = i4.traceThickness ?? 0.15;
      o3.push(...o$(i4.route, s2, { x: e36.x, y: e36.y }, n2, i4.jumpers));
    }
    return o3;
  }
  positionHasCollision(e36, t2 = 0) {
    const n2 = this.getCollidingSegments(e36);
    for (const o3 of n2)
      if (pe(e36, o3.start, o3.end) <= this.currentKeepoutRadius + t2)
        return true;
    return false;
  }
  segmentIntersectsOtherRoutes(e36, t2) {
    if (!this.currentTrace)
      return false;
    const n2 = this.currentTrace.rootConnectionName ?? this.currentTrace.connectionName, o3 = [...this.unprocessedRoutes, ...this.smoothedCursorRoutes, ...this.processedRoutes];
    for (const i3 of o3) {
      if ((i3.rootConnectionName ?? i3.connectionName) !== n2)
        for (let n3 = 0;n3 < i3.route.length - 1; n3++) {
          const o4 = i3.route[n3], r3 = i3.route[n3 + 1];
          if ((o4.z === e36.z || r3.z === e36.z) && ((!o4.insideJumperPad || !r3.insideJumperPad) && he({ x: e36.x, y: e36.y }, { x: t2.x, y: t2.y }, { x: o4.x, y: o4.y }, { x: r3.x, y: r3.y })))
            return true;
        }
    }
    return false;
  }
  finalizeCurrentTrace() {
    if (!this.currentTrace)
      return;
    const e36 = this.currentTrace.route[this.currentTrace.route.length - 1], t2 = this.recordedDrawPositions[this.recordedDrawPositions.length - 1];
    t2 && t2.x === e36.x && t2.y === e36.y || this.recordedDrawPositions.push({ ...e36 });
    const n2 = function(e37, t3) {
      if (e37.length < 4)
        return e37;
      let n3 = [...e37], o4 = true;
      for (;o4; ) {
        o4 = false;
        for (let e38 = 0;e38 < n3.length - 1 && !o4; e38++) {
          const i3 = n3[e38], r3 = n3[e38 + 1];
          if (i3.z === r3.z)
            for (let s2 = e38 + 2;s2 < n3.length - 1 && !o4; s2++) {
              if (s2 === e38 + 1)
                continue;
              const a3 = n3[s2], c3 = n3[s2 + 1];
              if (a3.z !== c3.z || i3.z !== a3.z)
                continue;
              const l3 = r$(i3, r3, a3, c3);
              if (l3) {
                if (a$(n3, e38 + 1, s2, t3))
                  continue;
                const r4 = [];
                for (let t4 = 0;t4 <= e38; t4++)
                  r4.push(n3[t4]);
                r4.push({ x: l3.x, y: l3.y, z: i3.z });
                for (let e39 = s2 + 1;e39 < n3.length; e39++)
                  r4.push(n3[e39]);
                n3 = r4, o4 = true;
              }
            }
        }
      }
      return n3;
    }(this.simplifyRoute(this.recordedDrawPositions, this.currentTrace.jumpers), this.currentTrace.jumpers), o3 = { connectionName: this.currentTrace.connectionName, rootConnectionName: this.currentTrace.rootConnectionName, traceThickness: this.currentTrace.traceThickness, viaDiameter: this.currentTrace.viaDiameter, route: n2, vias: [...this.currentTrace.vias], jumpers: this.currentTrace.jumpers };
    this.processedRoutes.push(o3), this.hdRouteSHI.removeRoute(this.currentTrace.connectionName), this.hdRouteSHI.addRoute(o3), this.currentTrace = null, this.cursorPosition = null, this.lastCursorPosition = null, this.drawPosition = null, this.recordedDrawPositions = [];
  }
  isJumperEndpoint(e36, t2) {
    if (!t2 || t2.length === 0)
      return false;
    for (const n2 of t2)
      if (Math.abs(e36.x - n2.start.x) < c$ && Math.abs(e36.y - n2.start.y) < c$ || Math.abs(e36.x - n2.end.x) < c$ && Math.abs(e36.y - n2.end.y) < c$)
        return true;
    return false;
  }
  simplifyRoute(e36, t2) {
    if (e36.length <= 2)
      return e36;
    const n2 = [e36[0]];
    for (let o3 = 1;o3 < e36.length - 1; o3++) {
      const i3 = n2[n2.length - 1], r3 = e36[o3], s2 = e36[o3 + 1];
      if (this.isJumperEndpoint(r3, t2)) {
        n2.push(r3);
        continue;
      }
      if (r3.z !== i3.z || r3.z !== s2.z) {
        n2.push(r3);
        continue;
      }
      const a3 = r3.x - i3.x, c3 = r3.y - i3.y, l3 = s2.x - r3.x, h2 = a3 * (s2.y - r3.y) - c3 * l3, d2 = 0.000001;
      Math.abs(h2) > d2 && n2.push(r3);
    }
    return n2.push(e36[e36.length - 1]), n2;
  }
  createBoardOutlineRoutes() {
    const e36 = [];
    if (!this.input.srj)
      return e36;
    const { outline: t2, bounds: n2 } = this.input.srj;
    let o3;
    o3 = t2 && t2.length >= 3 ? t2 : [{ x: n2.minX, y: n2.minY }, { x: n2.maxX, y: n2.minY }, { x: n2.maxX, y: n2.maxY }, { x: n2.minX, y: n2.maxY }];
    const i3 = this.input.srj.layerCount ?? 2;
    for (let t3 = 0;t3 < o3.length; t3++) {
      const n3 = o3[t3], r3 = o3[(t3 + 1) % o3.length];
      for (let o4 = 0;o4 < i3; o4++)
        e36.push({ connectionName: `__board_outline___${t3}_z${o4}`, traceThickness: 0.01, viaDiameter: 0, route: [{ x: n3.x, y: n3.y, z: o4 }, { x: r3.x, y: r3.y, z: o4 }], vias: [] });
    }
    return e36;
  }
  visualize() {
    const e36 = { lines: [], points: [], rects: [], circles: [], coordinateSystem: "cartesian", title: `Trace Keepout Solver (radius: ${this.currentKeepoutRadius.toFixed(2)})` };
    for (const t2 of this.originalHdRoutes)
      if (t2.route.length !== 0)
        for (let n2 = 0;n2 < t2.route.length - 1; n2++) {
          const o3 = t2.route[n2], i3 = t2.route[n2 + 1];
          o3.z === i3.z && e36.lines.push({ points: [{ x: o3.x, y: o3.y }, { x: i3.x, y: i3.y }], strokeColor: "rgba(0,0,0,0.25)", strokeWidth: 1.5 * (t2.traceThickness ?? 0.15) });
        }
    if (this.input.jumpers)
      for (const t2 of this.input.jumpers) {
        for (const n2 of t2.pads) {
          const t3 = n2.connectedTo.length > 0 ? n2.connectedTo.join(", ") : "unused", o3 = n2.connectedTo.length > 0 ? this.input.colorMap[n2.connectedTo[0]] || "#888888" : "rgba(128, 128, 128, 0.5)";
          e36.rects.push({ center: n2.center, width: n2.width, height: n2.height, fill: o3, stroke: "rgba(0, 0, 0, 0.5)", label: `Jumper pad (${t3})` });
        }
        t2.pads.length >= 2 && e36.lines.push({ points: [t2.pads[0].center, t2.pads[1].center], strokeColor: "rgba(100, 100, 100, 0.8)", strokeWidth: 0.2, label: "Jumper body" });
      }
    for (const t2 of this.input.obstacles) {
      let n2 = "rgba(128, 128, 128, 0.2)";
      const o3 = t2.__zLayers?.includes(0), i3 = t2.__zLayers?.includes(1);
      o3 && i3 ? n2 = "rgba(128, 0, 128, 0.2)" : o3 ? n2 = "rgba(255, 0, 0, 0.2)" : i3 && (n2 = "rgba(0, 0, 255, 0.2)"), e36.rects.push({ center: t2.center, width: t2.width, height: t2.height, fill: n2, label: `Obstacle (Z: ${t2.__zLayers?.join(", ")})` });
    }
    if (this.input.srj) {
      const { outline: t2, bounds: n2 } = this.input.srj;
      let o3;
      o3 = t2 && t2.length >= 3 ? t2 : [{ x: n2.minX, y: n2.minY }, { x: n2.maxX, y: n2.minY }, { x: n2.maxX, y: n2.maxY }, { x: n2.minX, y: n2.maxY }];
      for (let t3 = 0;t3 < o3.length; t3++) {
        const n3 = o3[t3], i3 = o3[(t3 + 1) % o3.length];
        e36.lines.push({ points: [{ x: n3.x, y: n3.y }, { x: i3.x, y: i3.y }], strokeColor: "rgba(0, 128, 0, 0.6)", strokeWidth: 0.1, label: "Board outline" });
      }
    }
    for (const t2 of this.processedRoutes) {
      if (t2.route.length === 0)
        continue;
      const n2 = this.input.colorMap[t2.connectionName] || "#888888", o3 = new Set;
      if (t2.jumpers && t2.jumpers.length > 0)
        for (const e37 of t2.jumpers)
          for (let n3 = 0;n3 < t2.route.length - 1; n3++) {
            const i3 = t2.route[n3], r3 = t2.route[n3 + 1], s2 = Math.abs(i3.x - e37.start.x) < c$ && Math.abs(i3.y - e37.start.y) < c$ && Math.abs(r3.x - e37.end.x) < c$ && Math.abs(r3.y - e37.end.y) < c$, a3 = Math.abs(i3.x - e37.end.x) < c$ && Math.abs(i3.y - e37.end.y) < c$ && Math.abs(r3.x - e37.start.x) < c$ && Math.abs(r3.y - e37.start.y) < c$;
            if (s2 || a3) {
              o3.add(n3);
              break;
            }
          }
      for (let n3 = 0;n3 < t2.route.length - 1; n3++) {
        const i3 = t2.route[n3], r3 = t2.route[n3 + 1];
        o3.has(n3) ? e36.lines.push({ points: [{ x: i3.x, y: i3.y }, { x: r3.x, y: r3.y }], strokeColor: "rgba(128, 128, 128, 0.6)", strokeDash: "2 2", label: `${t2.connectionName} (jumper segment - fixed)` }) : i3.z === r3.z && e36.lines.push({ points: [{ x: i3.x, y: i3.y }, { x: r3.x, y: r3.y }], strokeColor: i3.z === 0 ? "red" : "blue", strokeWidth: t2.traceThickness, label: `${t2.connectionName} (z=${i3.z})` });
      }
      for (const n3 of t2.vias)
        e36.circles.push({ center: { x: n3.x, y: n3.y }, radius: t2.viaDiameter / 2, fill: "rgba(255, 0, 255, 0.5)", label: `${t2.connectionName} via` });
      if (t2.jumpers && t2.jumpers.length > 0) {
        const o4 = fB(t2.jumpers, { color: n2, label: t2.connectionName });
        e36.rects.push(...o4.rects ?? []), e36.lines.push(...o4.lines ?? []);
      }
    }
    if (this.currentTrace && this.recordedDrawPositions.length > 0) {
      this.input.colorMap[this.currentTrace.connectionName];
      for (let t2 = 0;t2 < this.recordedDrawPositions.length - 1; t2++) {
        const n2 = this.recordedDrawPositions[t2], o3 = this.recordedDrawPositions[t2 + 1];
        e36.lines.push({ points: [{ x: n2.x, y: n2.y }, { x: o3.x, y: o3.y }], strokeColor: "green", strokeWidth: this.currentTrace.traceThickness });
      }
      if (this.cursorPosition && (e36.circles.push({ center: { x: this.cursorPosition.x, y: this.cursorPosition.y }, radius: this.currentKeepoutRadius, stroke: "orange", fill: "none" }), e36.points.push({ x: this.cursorPosition.x, y: this.cursorPosition.y, color: "orange", label: "Cursor" }), this.lastCursorPosition)) {
        const t2 = this.cursorPosition.x - this.lastCursorPosition.x, n2 = this.cursorPosition.y - this.lastCursorPosition.y, o3 = Math.sqrt(t2 * t2 + n2 * n2), i3 = o3 > 0.0001 ? { x: t2 / o3, y: n2 / o3 } : { x: 1, y: 0 }, r3 = this.currentKeepoutRadius / 4, s2 = { x: this.cursorPosition.x - i3.x * r3, y: this.cursorPosition.y - i3.y * r3 }, a3 = { x: this.cursorPosition.x + i3.x * r3, y: this.cursorPosition.y + i3.y * r3 };
        e36.lines.push({ points: [s2, a3], strokeColor: "cyan", strokeWidth: 0.05, label: "Projected segment" });
      }
      this.drawPosition && e36.points.push({ x: this.drawPosition.x, y: this.drawPosition.y, color: "lime", label: "Draw" });
      for (const t2 of this.lastCollidingSegments)
        e36.lines.push({ points: [{ x: t2.start.x, y: t2.start.y }, { x: t2.end.x, y: t2.end.y }], strokeColor: "rgba(255, 0, 255, 0.8)", strokeWidth: 0.02, label: "Colliding segment" });
    }
    if (!this.solved) {
      for (const t2 of this.smoothedCursorRoutes)
        if (t2.route.length !== 0)
          for (let n2 = 0;n2 < t2.route.length - 1; n2++) {
            const o3 = t2.route[n2], i3 = t2.route[n2 + 1];
            o3.z === i3.z && e36.lines.push({ points: [{ x: o3.x, y: o3.y }, { x: i3.x, y: i3.y }], strokeColor: "gray" });
          }
    }
    return e36;
  }
  getRedrawnHdRoutes() {
    return this.redrawnHdRoutes;
  }
};
var h$ = class extends ni {
  constructor(e36) {
    super(), this.input = e36, this.unprocessedObstacles = ca(this.input.srj.obstacles, this.input.srj.layerCount).filter((e37) => e37.offBoardConnectsTo && e37.offBoardConnectsTo.length > 0), this.unprocessedObstacles.forEach((e37, t2) => {
      e37.obstacleId = e37.obstacleId ?? `__obs${t2}`;
    }), this.offBoardConnMap = new mB({}), this.offBoardConnMap.addConnections(this.unprocessedObstacles.filter((e37) => e37.offBoardConnectsTo?.length).map((e37) => [e37.obstacleId, ...e37.offBoardConnectsTo ?? []])), this.nodeTree = new di(this.input.capacityMeshNodes);
  }
  getSolverName() {
    return "RelateNodesToOffBoardConnectionsSolver";
  }
  unprocessedObstacles;
  nodeTree;
  offBoardConnMap;
  nodesInNet = new Map;
  lastProcessedObstacle;
  _step() {
    const e36 = this.unprocessedObstacles.pop();
    if (this.lastProcessedObstacle = e36, !e36)
      return void (this.solved = true);
    const t2 = this.offBoardConnMap.getNetConnectedToId(e36.obstacleId), n2 = this.nodeTree.getNodesInArea(e36.center.x, e36.center.y, 0.01, 0.01).filter((t3) => t3.availableZ.some((t4) => e36.__zLayers?.includes(t4))).filter((t3) => Math.abs(t3.center.x - e36.center.x) < 0.01 && Math.abs(t3.center.y - e36.center.y) < 0.01), o3 = n2.map((e37) => e37.capacityMeshNodeId), i3 = this.nodesInNet.get(t2) ?? [], r3 = [...i3.map((e37) => e37.capacityMeshNodeId), ...o3];
    for (const e37 of i3)
      e37._offBoardConnectedCapacityMeshNodeIds = r3;
    for (const e37 of n2)
      e37._offBoardConnectedCapacityMeshNodeIds = r3, e37._offBoardConnectionId = t2;
    this.nodesInNet.set(t2, [...i3, ...n2]);
  }
  getOutput() {
    return { capacityNodes: this.input.capacityMeshNodes };
  }
  visualize() {
    const e36 = { rects: [], lines: [], points: [], circles: [] }, t2 = new Set;
    for (const [e37, n2] of this.nodesInNet)
      for (const e38 of n2)
        t2.add(e38.capacityMeshNodeId);
    for (const n2 of this.input.capacityMeshNodes)
      t2.has(n2.capacityMeshNodeId) || e36.rects.push({ center: n2.center, width: n2.width - 0.1, height: n2.height - 0.1, fill: "rgba(0, 0, 0, 0.2)" });
    this.lastProcessedObstacle && e36.rects.push({ center: this.lastProcessedObstacle.center, width: this.lastProcessedObstacle.width, height: this.lastProcessedObstacle.height, fill: "rgba(255, 0, 0, 0.5)" });
    for (const [t3, n2] of this.nodesInNet.entries()) {
      for (const o3 of n2)
        e36.rects.push({ center: o3.center, width: o3.width, height: o3.height, fill: Oo(t3, 0.2), label: `OffBoardConn: ${t3}` });
      for (const o3 of n2)
        for (const i3 of n2)
          o3.capacityMeshNodeId !== i3.capacityMeshNodeId && e36.lines.push({ points: [o3.center, i3.center], strokeColor: Oo(t3, 1) });
    }
    return e36;
  }
};
var d$ = 0.1;
var u$ = 0.1;
function p$(e36, t2, n2, o3, i3, r3) {
  return (i3 - e36) * (o3 - t2) - (r3 - t2) * (n2 - e36);
}
function m$(e36, t2, n2, o3, i3, r3) {
  return Math.min(e36, n2) <= i3 && i3 <= Math.max(e36, n2) && Math.min(t2, o3) <= r3 && r3 <= Math.max(t2, o3);
}
function g$(e36, t2, n2, o3, i3, r3, s2, a3) {
  const c3 = p$(i3, r3, s2, a3, e36, t2), l3 = p$(i3, r3, s2, a3, n2, o3), h2 = p$(e36, t2, n2, o3, i3, r3), d2 = p$(e36, t2, n2, o3, s2, a3);
  return (c3 > 0 && l3 < 0 || c3 < 0 && l3 > 0) && (h2 > 0 && d2 < 0 || h2 < 0 && d2 > 0) || (!(c3 !== 0 || !m$(i3, r3, s2, a3, e36, t2)) || (!(l3 !== 0 || !m$(i3, r3, s2, a3, n2, o3)) || (!(h2 !== 0 || !m$(e36, t2, n2, o3, i3, r3)) || !(d2 !== 0 || !m$(e36, t2, n2, o3, s2, a3)))));
}
function f$(e36, t2, n2, o3, i3, r3) {
  const s2 = i3 - n2, a3 = r3 - o3, c3 = e36 - n2, l3 = t2 - o3, h2 = s2 * s2 + a3 * a3;
  if (h2 === 0) {
    return { x: n2, y: o3, distSq: c3 * c3 + l3 * l3 };
  }
  let d2 = (c3 * s2 + l3 * a3) / h2;
  d2 = Math.max(0, Math.min(1, d2));
  const u2 = n2 + d2 * s2, p3 = o3 + d2 * a3, m2 = e36 - u2, g2 = t2 - p3;
  return { x: u2, y: p3, distSq: m2 * m2 + g2 * g2 };
}
var _$ = class extends ni {
  getSolverName() {
    return "SimpleHighDensitySolver";
  }
  unsolvedNodes;
  allNodes;
  routes;
  colorMap;
  traceWidth;
  viaDiameter;
  numMovablePoints;
  currentNode = null;
  lastNode = null;
  currentNodeStep = 0;
  routesInProgress = [];
  pushMargin;
  currentNodeBounds = null;
  constructor({ nodePortPoints: e36, colorMap: t2, traceWidth: n2 = 0.1, viaDiameter: o3 = 0.3, pushMargin: i3 = 0.3, numMovablePoints: r3 = 2 }) {
    if (super(), r3 < 1 || r3 > 3)
      throw new Error(`numMovablePoints must be 1, 2, or 3, got ${r3}`);
    this.allNodes = [...e36], this.unsolvedNodes = [...e36], this.colorMap = t2 ?? {}, this.routes = [], this.traceWidth = n2, this.viaDiameter = o3, this.numMovablePoints = r3, this.pushMargin = i3, this.MAX_ITERATIONS = 10 * e36.length + 1;
  }
  _step() {
    if (this.currentNode === null) {
      if (this.unsolvedNodes.length === 0)
        return void (this.solved = true);
      this.lastNode = this.currentNode, this.currentNode = this.unsolvedNodes.pop(), this.currentNodeStep = 0, this.routesInProgress = [], this._initializeRoutesForCurrentNode();
    }
    this.currentNodeStep > 0 && this._runForceDirectedStep(), this.currentNodeStep++, this.currentNodeStep >= 10 && (this._finalizeRoutesForCurrentNode(), this.lastNode = this.currentNode, this.currentNode = null);
  }
  _initializeRoutesForCurrentNode() {
    const e36 = this.currentNode, t2 = e36.center.x - e36.width / 2, n2 = e36.center.x + e36.width / 2, o3 = e36.center.y - e36.height / 2, i3 = e36.center.y + e36.height / 2;
    this.currentNodeBounds = { minX: t2, maxX: n2, minY: o3, maxY: i3 };
    const r3 = new Map;
    for (const t3 of e36.portPoints)
      r3.has(t3.connectionName) || r3.set(t3.connectionName, []), r3.get(t3.connectionName).push({ x: t3.x, y: t3.y, z: t3.z, rootConnectionName: t3.rootConnectionName });
    for (const [e37, t3] of r3) {
      if (t3.length < 2)
        continue;
      const n3 = t3[0], o4 = t3[t3.length - 1], i4 = n3.z, r4 = o4.x - n3.x, s2 = o4.y - n3.y, a3 = Math.sqrt(r4 * r4 + s2 * s2), c3 = a3 > 0 ? r4 / a3 : 0, l3 = a3 > 0 ? s2 / a3 : 0, h2 = [];
      this.numMovablePoints >= 1 && h2.push({ x: n3.x + c3 * u$, y: n3.y + l3 * u$, z: i4, rootConnectionName: n3.rootConnectionName, connectionName: e37 }), this.numMovablePoints >= 2 && h2.push({ x: o4.x - c3 * u$, y: o4.y - l3 * u$, z: i4, rootConnectionName: n3.rootConnectionName, connectionName: e37 }), this.numMovablePoints >= 3 && h2.push({ x: n3.x + r4 / 2, y: n3.y + s2 / 2, z: i4, rootConnectionName: n3.rootConnectionName, connectionName: e37 }), this.routesInProgress.push({ connectionName: e37, rootConnectionName: n3.rootConnectionName, startPoint: { x: n3.x, y: n3.y, z: i4 }, endPoint: { x: o4.x, y: o4.y, z: i4 }, movablePoints: h2 });
    }
  }
  _runForceDirectedStep() {
    const e36 = this.currentNodeBounds, t2 = [];
    for (const e37 of this.routesInProgress)
      t2.push(...e37.movablePoints);
    const n2 = new Map;
    for (const e37 of t2)
      n2.set(e37, { fx: 0, fy: 0 });
    const o3 = 0.3 + this.pushMargin, i3 = new Map;
    for (const e37 of this.routesInProgress) {
      const t3 = [{ x: e37.startPoint.x, y: e37.startPoint.y, movablePoint: null }];
      e37.movablePoints.length === 1 ? t3.push({ x: e37.movablePoints[0].x, y: e37.movablePoints[0].y, movablePoint: e37.movablePoints[0] }) : e37.movablePoints.length === 2 ? (t3.push({ x: e37.movablePoints[0].x, y: e37.movablePoints[0].y, movablePoint: e37.movablePoints[0] }), t3.push({ x: e37.movablePoints[1].x, y: e37.movablePoints[1].y, movablePoint: e37.movablePoints[1] })) : e37.movablePoints.length === 3 && (t3.push({ x: e37.movablePoints[0].x, y: e37.movablePoints[0].y, movablePoint: e37.movablePoints[0] }), t3.push({ x: e37.movablePoints[2].x, y: e37.movablePoints[2].y, movablePoint: e37.movablePoints[2] }), t3.push({ x: e37.movablePoints[1].x, y: e37.movablePoints[1].y, movablePoint: e37.movablePoints[1] })), t3.push({ x: e37.endPoint.x, y: e37.endPoint.y, movablePoint: null }), i3.set(e37, t3);
    }
    for (const r4 of t2) {
      const t3 = n2.get(r4), s3 = r4.x - e36.minX, a3 = e36.maxX - r4.x, c3 = e36.maxY - r4.y, l3 = r4.y - e36.minY;
      s3 < o3 && (t3.fx += d$ * (o3 - s3)), a3 < o3 && (t3.fx -= d$ * (o3 - a3)), l3 < o3 && (t3.fy += d$ * (o3 - l3)), c3 < o3 && (t3.fy -= d$ * (o3 - c3));
      for (const e37 of this.routesInProgress) {
        if (e37.rootConnectionName === r4.rootConnectionName)
          continue;
        const s4 = i3.get(e37);
        for (let e38 = 0;e38 < s4.length - 1; e38++) {
          const i4 = s4[e38], a4 = s4[e38 + 1], c4 = f$(r4.x, r4.y, i4.x, i4.y, a4.x, a4.y), l4 = Math.sqrt(c4.distSq);
          if (l4 > 0 && l4 < 2 * o3) {
            const e39 = r4.x - c4.x, o4 = r4.y - c4.y, s5 = 0.002 / c4.distSq, l5 = s5 * e39, h2 = s5 * o4;
            t3.fx += l5, t3.fy += h2;
            const d2 = i4.movablePoint, u2 = a4.movablePoint;
            if (d2 && u2) {
              const e40 = n2.get(d2), t4 = n2.get(u2);
              e40.fx -= l5 / 2, e40.fy -= h2 / 2, t4.fx -= l5 / 2, t4.fy -= h2 / 2;
            } else if (d2) {
              const e40 = n2.get(d2);
              e40.fx -= l5, e40.fy -= h2;
            } else if (u2) {
              const e40 = n2.get(u2);
              e40.fx -= l5, e40.fy -= h2;
            }
          }
        }
      }
    }
    const r3 = (e37) => e37.movablePoint ? { x: e37.movablePoint.x, y: e37.movablePoint.y } : { x: e37.x, y: e37.y }, s2 = (e37) => {
      let t3 = null;
      for (const n4 of this.routesInProgress)
        if (n4.movablePoints.includes(e37)) {
          t3 = n4;
          break;
        }
      if (!t3)
        return false;
      const n3 = i3.get(t3);
      let o4 = -1;
      for (let t4 = 0;t4 < n3.length; t4++)
        if (n3[t4].movablePoint === e37) {
          o4 = t4;
          break;
        }
      if (o4 === -1)
        return false;
      const s3 = [];
      if (o4 > 0) {
        const t4 = r3(n3[o4 - 1]);
        s3.push({ ax: t4.x, ay: t4.y, bx: e37.x, by: e37.y });
      }
      if (o4 < n3.length - 1) {
        const t4 = r3(n3[o4 + 1]);
        s3.push({ ax: e37.x, ay: e37.y, bx: t4.x, by: t4.y });
      }
      for (const e38 of this.routesInProgress) {
        if (e38.rootConnectionName === t3.rootConnectionName)
          continue;
        const n4 = i3.get(e38);
        for (let e39 = 0;e39 < n4.length - 1; e39++) {
          const t4 = r3(n4[e39]), o5 = r3(n4[e39 + 1]);
          for (const e40 of s3)
            if (g$(e40.ax, e40.ay, e40.bx, e40.by, t4.x, t4.y, o5.x, o5.y))
              return true;
        }
      }
      return false;
    };
    for (const o4 of t2) {
      const t3 = n2.get(o4);
      o4.forceX = t3.fx, o4.forceY = t3.fy;
      const { x: i4, y: r4 } = o4;
      o4.x += t3.fx, o4.y += t3.fy, o4.x = Math.max(e36.minX, Math.min(e36.maxX, o4.x)), o4.y = Math.max(e36.minY, Math.min(e36.maxY, o4.y)), s2(o4) && (o4.x = i4, o4.y = r4);
    }
  }
  _finalizeRoutesForCurrentNode() {
    for (const e36 of this.routesInProgress) {
      const { connectionName: t2, rootConnectionName: n2, startPoint: o3, endPoint: i3, movablePoints: r3 } = e36, s2 = [{ x: o3.x, y: o3.y, z: o3.z }];
      r3.length === 1 ? s2.push({ x: r3[0].x, y: r3[0].y, z: r3[0].z }) : r3.length === 2 ? (s2.push({ x: r3[0].x, y: r3[0].y, z: r3[0].z }), s2.push({ x: r3[1].x, y: r3[1].y, z: r3[1].z })) : r3.length === 3 && (s2.push({ x: r3[0].x, y: r3[0].y, z: r3[0].z }), s2.push({ x: r3[2].x, y: r3[2].y, z: r3[2].z }), s2.push({ x: r3[1].x, y: r3[1].y, z: r3[1].z })), s2.push({ x: i3.x, y: i3.y, z: i3.z });
      const a3 = { connectionName: t2, rootConnectionName: n2, traceThickness: this.traceWidth, viaDiameter: this.viaDiameter, route: s2, vias: [] };
      this.routes.push(a3);
    }
    this.routesInProgress = [];
  }
  _getNodeBounds(e36) {
    return { minX: e36.center.x - e36.width / 2, maxX: e36.center.x + e36.width / 2, minY: e36.center.y - e36.height / 2, maxY: e36.center.y + e36.height / 2 };
  }
  visualize() {
    const e36 = { lines: [], points: [], rects: [], circles: [] };
    for (const t2 of this.unsolvedNodes) {
      if (t2 === this.currentNode)
        continue;
      const n2 = this._getNodeBounds(t2);
      e36.rects.push({ center: { x: (n2.minX + n2.maxX) / 2, y: (n2.minY + n2.maxY) / 2 }, width: n2.maxX - n2.minX, height: n2.maxY - n2.minY, fill: "rgba(0, 0, 0, 0.08)", stroke: "rgba(0, 0, 0, 0.2)", label: t2.capacityMeshNodeId });
    }
    if (this.lastNode) {
      const t2 = this._getNodeBounds(this.lastNode);
      e36.rects.push({ center: { x: (t2.minX + t2.maxX) / 2, y: (t2.minY + t2.maxY) / 2 }, width: t2.maxX - t2.minX, height: t2.maxY - t2.minY, fill: "rgba(0, 200, 0, 0.15)", stroke: "rgba(0, 0, 255, 0.6)" });
    }
    if (this.currentNode) {
      const t2 = this._getNodeBounds(this.currentNode);
      e36.rects.push({ center: { x: (t2.minX + t2.maxX) / 2, y: (t2.minY + t2.maxY) / 2 }, width: t2.maxX - t2.minX, height: t2.maxY - t2.minY, fill: "rgba(0, 200, 0, 0.15)", stroke: "rgba(0, 200, 0, 0.6)" });
    }
    for (const t2 of this.unsolvedNodes) {
      const n2 = new Map;
      for (const e37 of t2.portPoints)
        n2.has(e37.connectionName) || n2.set(e37.connectionName, []), n2.get(e37.connectionName).push({ x: e37.x, y: e37.y });
      for (const [t3, o3] of n2)
        o3.length < 2 || e36.lines.push({ points: o3.map((e37) => ({ x: e37.x, y: e37.y })), label: t3, strokeColor: "gray", strokeWidth: this.traceWidth });
    }
    for (const t2 of this.routes) {
      const n2 = mi(t2.route, t2.connectionName, this.colorMap[t2.connectionName]);
      for (const o4 of n2)
        e36.lines.push({ points: o4.points, label: o4.connectionName, strokeColor: o4.z === 0 ? o4.color : Ao(o4.color, 0.75), layer: `z${o4.z}`, strokeWidth: t2.traceThickness, strokeDash: o4.z !== 0 ? "10, 5" : undefined });
      const o3 = t2.route;
      for (let t3 = 0;t3 < o3.length; t3++) {
        const n3 = o3[t3], i3 = t3 === 0, r3 = t3 === o3.length - 1, s2 = !i3 && !r3;
        let a3;
        a3 = i3 ? "start" : r3 ? "end" : `M${t3}`, e36.points.push({ x: n3.x, y: n3.y, label: a3, color: s2 ? "orange" : "blue" });
      }
    }
    for (const t2 of this.routesInProgress) {
      const { startPoint: n2, endPoint: o3, movablePoints: i3, connectionName: r3 } = t2, s2 = this.colorMap[r3] ?? "gray", a3 = [{ x: n2.x, y: n2.y }];
      i3.length === 1 ? a3.push({ x: i3[0].x, y: i3[0].y }) : i3.length === 2 ? (a3.push({ x: i3[0].x, y: i3[0].y }), a3.push({ x: i3[1].x, y: i3[1].y })) : i3.length === 3 && (a3.push({ x: i3[0].x, y: i3[0].y }), a3.push({ x: i3[2].x, y: i3[2].y }), a3.push({ x: i3[1].x, y: i3[1].y })), a3.push({ x: o3.x, y: o3.y }), e36.lines.push({ points: a3, label: r3, strokeColor: s2, strokeWidth: this.traceWidth }), e36.points.push({ x: n2.x, y: n2.y, label: "start", color: "blue" });
      for (let t3 = 0;t3 < i3.length; t3++) {
        const n3 = i3[t3];
        if (e36.points.push({ x: n3.x, y: n3.y, label: `M${t3 + 1}`, color: "orange" }), n3.forceX !== undefined && n3.forceY !== undefined) {
          if (Math.sqrt(n3.forceX * n3.forceX + n3.forceY * n3.forceY) > 0.001) {
            const o4 = 5;
            e36.lines.push({ points: [{ x: n3.x, y: n3.y }, { x: n3.x + n3.forceX * o4, y: n3.y + n3.forceY * o4 }], strokeColor: "red", strokeWidth: 0.02, label: `F${t3 + 1}` });
            const i4 = 0.05, r4 = n3.x + n3.forceX * o4, s3 = n3.y + n3.forceY * o4, a4 = Math.atan2(n3.forceY, n3.forceX);
            e36.lines.push({ points: [{ x: r4, y: s3 }, { x: r4 - i4 * Math.cos(a4 - Math.PI / 6), y: s3 - i4 * Math.sin(a4 - Math.PI / 6) }], strokeColor: "red", strokeWidth: 0.02 }), e36.lines.push({ points: [{ x: r4, y: s3 }, { x: r4 - i4 * Math.cos(a4 + Math.PI / 6), y: s3 - i4 * Math.sin(a4 + Math.PI / 6) }], strokeColor: "purple", strokeWidth: 0.02 });
          }
        }
      }
      e36.points.push({ x: o3.x, y: o3.y, label: "end", color: "blue" });
    }
    return e36;
  }
};
var y$ = ({ connMap: e36, connectionsWithResults: t2, inputNodes: n2, obstacles: o3 }) => {
  const i3 = o3.filter((e37) => e37.offBoardConnectsTo?.length);
  if (i3.length === 0)
    return;
  const r3 = new Jo({});
  r3.addConnections(i3.map((e37, t3) => [e37.obstacleId ?? `__obs${t3}`, ...e37.offBoardConnectsTo ?? []]));
  const s2 = new Map(n2.map((e37) => [e37.capacityMeshNodeId, e37]));
  for (const n3 of t2) {
    if (!n3.path)
      continue;
    const t3 = n3.connection.rootConnectionName ?? n3.connection.name, o4 = new Set;
    for (const e37 of n3.path) {
      const t4 = s2.get(e37.currentNodeId);
      if (t4?._offBoardConnectionId && o4.add(t4._offBoardConnectionId), e37.throughNodeId) {
        const t5 = s2.get(e37.throughNodeId);
        t5?._offBoardConnectionId && o4.add(t5._offBoardConnectionId);
      }
    }
    for (const n4 of o4) {
      const o5 = r3.getIdsConnectedToNet(n4);
      o5?.length && e36.addConnections([[t3, ...o5]]);
    }
  }
};
function b$(e36, t2, n2, o3 = {}) {
  return { solverName: e36, solverClass: t2, getConstructorParams: n2, onSolved: o3.onSolved };
}
var x$ = class extends ni {
  constructor(e36, t2 = {}) {
    super(), this.srj = e36, this.opts = t2, this.srj = e36, this.opts = { ...t2 }, this.viaDiameter = Yo(e36).padDiameter, this.minTraceWidth = e36.minTraceWidth;
    const n2 = this.opts;
    if (this.effort = n2.effort ?? 1, this.MAX_ITERATIONS = 1e8 * this.effort, n2.capacityDepth === undefined) {
      const t3 = e36.bounds.maxX - e36.bounds.minX, o3 = e36.bounds.maxY - e36.bounds.minY, i3 = Math.max(t3, o3), r3 = n2.targetMinCapacity ?? 0.5;
      n2.capacityDepth = Fz(i3, r3);
    }
    this.connMap = ei(e36), this.colorMap = Eo(e36, this.connMap), this.cacheProvider = n2.cacheProvider === undefined ? no() : n2.cacheProvider === null ? null : n2.cacheProvider, this.startTimeOfPhase = {}, this.endTimeOfPhase = {}, this.timeSpentOnPhase = {};
  }
  getSolverName() {
    return "AssignableAutoroutingPipeline2";
  }
  netToPointPairsSolver;
  nodeSolver;
  nodeTargetMerger;
  edgeSolver;
  relateNodesToOffBoardConnections;
  colorMap;
  highDensityRouteSolver;
  simpleHighDensityRouteSolver;
  highDensitySolver;
  highDensityStitchSolver;
  singleLayerNodeMerger;
  offboardPathFragmentSolver;
  strawSolver;
  deadEndSolver;
  traceSimplificationSolver;
  traceKeepoutSolver;
  traceWidthSolver;
  availableSegmentPointSolver;
  portPointPathingSolver;
  multiSectionPortPointOptimizer;
  viaDiameter;
  minTraceWidth;
  effort;
  startTimeOfPhase;
  endTimeOfPhase;
  timeSpentOnPhase;
  activeSubSolver = null;
  connMap;
  srjWithPointPairs;
  capacityNodes = null;
  capacityEdges = null;
  cacheProvider = null;
  pipelineDef = [b$("netToPointPairsSolver", uB, (e36) => [e36.srj, e36.colorMap, ti(e36.srj)], { onSolved: (e36) => {
    e36.srjWithPointPairs = e36.netToPointPairsSolver?.getNewSimpleRouteJson(), e36.colorMap = Eo(e36.srjWithPointPairs, this.connMap), e36.connMap = ei(e36.srjWithPointPairs);
  } }), b$("nodeSolver", Jn, (e36) => [{ simpleRouteJson: e36.srjWithPointPairs, maxGapFillPasses: 4 }], { onSolved: (e36) => {
    e36.capacityNodes = e36.nodeSolver?.getOutput().meshNodes ?? [];
  } }), b$("relateNodesToOffBoardConnections", h$, (e36) => [{ capacityMeshNodes: e36.capacityNodes, srj: e36.srj }], { onSolved: (e36) => {
    e36.capacityNodes = e36.relateNodesToOffBoardConnections?.getOutput().capacityNodes;
  } }), b$("edgeSolver", ui, (e36) => [e36.capacityNodes], { onSolved: (e36) => {
    e36.capacityEdges = e36.edgeSolver?.edges;
  } }), b$("availableSegmentPointSolver", ii, (e36) => [{ nodes: e36.capacityNodes, edges: e36.capacityEdges || [], traceWidth: e36.minTraceWidth, colorMap: e36.colorMap, shouldReturnCrampedPortPoints: false }]), b$("portPointPathingSolver", Kz, (e36) => {
    const t2 = e36.capacityNodes.map((e37) => ({ capacityMeshNodeId: e37.capacityMeshNodeId, center: e37.center, width: e37.width, height: e37.height, portPoints: [], availableZ: e37.availableZ, _containsTarget: e37._containsTarget, _containsObstacle: e37._containsObstacle, _offBoardConnectionId: e37._offBoardConnectionId, _offBoardConnectedCapacityMeshNodeIds: e37._offBoardConnectedCapacityMeshNodeIds })), n2 = new Map(t2.map((e37) => [e37.capacityMeshNodeId, e37])), o3 = e36.availableSegmentPointSolver;
    for (const e37 of o3.sharedEdgeSegments)
      for (const t3 of e37.portPoints) {
        const [o4, i3] = t3.nodeIds, r3 = { portPointId: t3.segmentPortPointId, x: t3.x, y: t3.y, z: t3.availableZ[0] ?? 0, connectionNodeIds: [o4, i3], distToCentermostPortOnZ: t3.distToCentermostPortOnZ, connectsToOffBoardNode: e37.nodeIds.some((e38) => n2.get(e38)?._offBoardConnectionId) }, s2 = n2.get(o4);
        s2 && s2.portPoints.push(r3);
      }
    return [{ simpleRouteJson: e36.srjWithPointPairs, inputNodes: t2, capacityMeshNodes: e36.capacityNodes, colorMap: e36.colorMap, numShuffleSeeds: 100 * Math.min(1, e36.effort), hyperParameters: { JUMPER_PF_FN_ENABLED: false, NODE_PF_FACTOR: 100, NODE_PF_MAX_PENALTY: 100, CENTER_OFFSET_DIST_PENALTY_FACTOR: 0, FORCE_CENTER_FIRST: true } }];
  }, { onSolved: (e36) => {
    const t2 = e36.portPointPathingSolver;
    t2 && y$({ connMap: e36.connMap, connectionsWithResults: t2.connectionsWithResults, inputNodes: t2.inputNodes, obstacles: e36.srj.obstacles });
  } }), b$("multiSectionPortPointOptimizer", nB, (e36) => {
    const t2 = e36.portPointPathingSolver;
    return [{ simpleRouteJson: e36.srjWithPointPairs, inputNodes: t2.inputNodes, capacityMeshNodes: e36.capacityNodes, capacityMeshEdges: e36.capacityEdges, colorMap: e36.colorMap, initialConnectionResults: t2.connectionsWithResults, initialAssignedPortPoints: t2.assignedPortPoints, initialNodeAssignedPortPoints: t2.nodeAssignedPortPoints }];
  }), b$("highDensitySolver", _$, (e36) => [{ nodePortPoints: e36.multiSectionPortPointOptimizer?.getNodesWithPortPoints() ?? e36.portPointPathingSolver?.getNodesWithPortPoints() ?? [], colorMap: e36.colorMap, viaDiameter: e36.viaDiameter, traceWidth: e36.minTraceWidth, connMap: e36.connMap }]), b$("highDensityStitchSolver", IB, (e36) => [{ connections: e36.srjWithPointPairs.connections, hdRoutes: e36.highDensitySolver.routes, colorMap: e36.colorMap, layerCount: e36.srj.layerCount, defaultViaDiameter: e36.viaDiameter }]), b$("traceSimplificationSolver", WF, (e36) => [{ hdRoutes: e36.highDensityStitchSolver?.mergedHdRoutes ?? e36.highDensitySolver?.routes ?? e36.highDensityRouteSolver?.routes, obstacles: e36.srj.obstacles, connMap: e36.connMap, colorMap: e36.colorMap, outline: e36.srj.outline, defaultViaDiameter: e36.viaDiameter, layerCount: e36.srj.layerCount, iterations: 2 }]), b$("traceKeepoutSolver", l$, (e36) => [{ hdRoutes: e36.traceSimplificationSolver?.simplifiedHdRoutes ?? [], obstacles: e36.srj.obstacles, connMap: e36.connMap, colorMap: e36.colorMap, srj: e36.srj }]), b$("traceWidthSolver", QF, (e36) => [{ hdRoutes: e36.traceKeepoutSolver?.redrawnHdRoutes ?? [], connection: e36.srj.connections, obstacles: e36.srj.obstacles, connMap: e36.connMap, colorMap: e36.colorMap, minTraceWidth: e36.minTraceWidth, obstacleMargin: e36.srj.defaultObstacleMargin ?? 0.15, layerCount: e36.srj.layerCount }])];
  getConstructorParams() {
    return [this.srj, this.opts];
  }
  currentPipelineStepIndex = 0;
  _step() {
    const e36 = this.pipelineDef[this.currentPipelineStepIndex];
    if (!e36)
      return void (this.solved = true);
    if (this.activeSubSolver)
      return this.activeSubSolver.step(), void (this.activeSubSolver.solved ? (this.endTimeOfPhase[e36.solverName] = performance.now(), this.timeSpentOnPhase[e36.solverName] = this.endTimeOfPhase[e36.solverName] - this.startTimeOfPhase[e36.solverName], e36.onSolved?.(this), this.activeSubSolver = null, this.currentPipelineStepIndex++) : this.activeSubSolver.failed && (this.error = this.activeSubSolver?.error, this.failed = true, this.activeSubSolver = null));
    const t2 = e36.getConstructorParams(this);
    this.activeSubSolver = new e36.solverClass(...t2), this[e36.solverName] = this.activeSubSolver, this.timeSpentOnPhase[e36.solverName] = 0, this.startTimeOfPhase[e36.solverName] = performance.now();
  }
  solveUntilPhase(e36) {
    for (;this.getCurrentPhase() !== e36; )
      this.step();
  }
  getCurrentPhase() {
    return this.pipelineDef[this.currentPipelineStepIndex]?.solverName ?? "none";
  }
  visualize() {
    if (!this.solved && this.activeSubSolver)
      return this.activeSubSolver.visualize();
    const e36 = this.netToPointPairsSolver?.visualize(), t2 = this.nodeSolver?.visualize(), n2 = this.nodeTargetMerger?.visualize(), o3 = this.singleLayerNodeMerger?.visualize(), i3 = this.strawSolver?.visualize(), r3 = this.edgeSolver?.visualize(), s2 = this.deadEndSolver?.visualize(), a3 = this.availableSegmentPointSolver?.visualize(), c3 = this.offboardPathFragmentSolver?.visualize(), l3 = this.portPointPathingSolver?.visualize(), h2 = this.multiSectionPortPointOptimizer?.visualize(), d2 = this.highDensityRouteSolver?.visualize(), u2 = this.highDensitySolver?.visualize(), p3 = this.simpleHighDensityRouteSolver?.visualize(), m2 = this.highDensityStitchSolver?.visualize(), g2 = this.traceSimplificationSolver?.visualize(), f2 = this.traceKeepoutSolver?.visualize(), _2 = this.traceWidthSolver?.visualize(), y2 = this.srj.outline, b2 = [];
    if (b2.push({ points: [{ x: this.srj.bounds?.minX ?? -50, y: this.srj.bounds?.minY ?? -50 }, { x: this.srj.bounds?.maxX ?? 50, y: this.srj.bounds?.minY ?? -50 }, { x: this.srj.bounds?.maxX ?? 50, y: this.srj.bounds?.maxY ?? 50 }, { x: this.srj.bounds?.minX ?? -50, y: this.srj.bounds?.maxY ?? 50 }, { x: this.srj.bounds?.minX ?? -50, y: this.srj.bounds?.minY ?? -50 }], strokeColor: "rgba(255,0,0,0.25)" }), y2 && y2.length >= 2) {
      const e37 = y2.map((e38) => ({ x: e38.x, y: e38.y }));
      e37.push({ ...e37[0] }), b2.push({ points: e37, strokeColor: "rgba(0, 136, 255, 0.95)" });
    }
    const x2 = Lo(this.srj), v2 = { points: [...this.srj.connections.flatMap((e37) => e37.pointsToConnect.map((t3) => ({ ...t3, layer: Bo(t3, this.srj.layerCount), label: `${e37.name} ${t3.pcb_port_id ?? ""}` })))], rects: [...(this.srj.obstacles ?? []).filter((e37) => !e37.isCopperPour).map((e37) => ({ ...e37, fill: e37.layers?.includes("top") ? "rgba(255,0,0,0.25)" : e37.layers?.includes("bottom") ? "rgba(0,0,255,0.25)" : "rgba(255,0,0,0.25)", layer: jo(e37, this.srj.layerCount), label: x2(e37) }))], lines: b2 }, I2 = [v2, e36, t2, n2, o3, i3, r3, s2, a3, c3, l3, h2, d2 ? pi(v2, d2) : null, u2 ? pi(v2, u2) : null, p3 ? pi(v2, p3) : null, m2, g2, f2, _2, this.solved ? pi({ lines: b2 }, Wo(this.getOutputSimpleRouteJson())) : null].filter(Boolean);
    return pi(...I2);
  }
  preview() {
    const e36 = this.highDensitySolver?.routes ?? this.simpleHighDensityRouteSolver?.routes ?? this.highDensityRouteSolver?.routes;
    if (e36) {
      const t2 = [];
      for (let n2 = e36.length - 1;n2 >= 0; n2--) {
        const o3 = e36[n2];
        if (t2.push({ points: o3.route.map((e37) => ({ x: e37.x, y: e37.y })), strokeColor: this.colorMap[o3.connectionName] }), t2.length > 200)
          break;
      }
      return { lines: t2 };
    }
    if (this.portPointPathingSolver) {
      const e37 = [];
      for (const t2 of this.portPointPathingSolver.connectionsWithResults)
        t2.path && e37.push({ points: t2.path.map((e38) => ({ x: e38.point.x, y: e38.point.y })), strokeColor: this.colorMap[t2.connection.name] });
      return { lines: e37 };
    }
    return this.netToPointPairsSolver ? this.netToPointPairsSolver?.visualize() : {};
  }
  _getOutputHdRoutes() {
    return this.traceWidthSolver?.hdRoutesWithWidths ?? this.traceKeepoutSolver?.redrawnHdRoutes ?? this.traceSimplificationSolver?.simplifiedHdRoutes ?? this.highDensityStitchSolver?.mergedHdRoutes ?? this.highDensitySolver?.routes ?? this.simpleHighDensityRouteSolver?.routes ?? this.highDensityRouteSolver?.routes;
  }
  getConnectedOffboardObstacles() {
    const e36 = {}, t2 = new Set(this.srj.connections.flatMap((e37) => e37.__rootConnectionNames ?? [e37.name]));
    for (const [n2, o3] of this.srj.obstacles.entries()) {
      if (!o3.offBoardConnectsTo?.length)
        continue;
      const i3 = o3.obstacleId ?? `__obs${n2}`, r3 = this.connMap.getNetConnectedToId(i3);
      if (!r3)
        continue;
      const s2 = this.connMap.getIdsConnectedToNet(r3).find((e37) => t2.has(e37));
      s2 && (e36[i3] = s2);
    }
    return e36;
  }
  getOutputSimplifiedPcbTraces() {
    if (!this.solved || !this.highDensityRouteSolver && !this.simpleHighDensityRouteSolver && !this.highDensitySolver)
      throw new Error("Cannot get output before solving is complete");
    const e36 = [], t2 = this._getOutputHdRoutes();
    for (const n2 of this.netToPointPairsSolver?.newConnections ?? []) {
      const o3 = n2.__netConnectionName ?? this.srj.connections.find((e37) => e37.name === n2.name)?.__netConnectionName, i3 = t2.filter((e37) => e37.connectionName === n2.name);
      for (let t3 = 0;t3 < i3.length; t3++) {
        const r3 = i3[t3], s2 = { type: "pcb_trace", pcb_trace_id: `${n2.name}_${t3}`, connection_name: o3 ?? n2.__rootConnectionNames?.[0] ?? n2.name, route: Ro(r3, this.srj.layerCount) };
        e36.push(s2);
      }
    }
    return e36;
  }
  getOutputSimpleRouteJson() {
    return { ...this.srj, traces: this.getOutputSimplifiedPcbTraces() };
  }
};
var v$ = class extends ni {
  getSolverName() {
    return "MultipleHighDensityRouteStitchSolver2";
  }
  unsolvedRoutes;
  mergedHdRoutes = [];
  colorMap = {};
  defaultTraceThickness;
  defaultViaDiameter;
  constructor(e36) {
    super(), this.colorMap = e36.colorMap ?? {};
    const t2 = e36.hdRoutes[0];
    this.defaultTraceThickness = t2?.traceThickness ?? 0.15, this.defaultViaDiameter = t2?.viaDiameter ?? e36.defaultViaDiameter ?? 0.3;
    const n2 = new Map;
    for (const t3 of e36.connectionPathResults)
      n2.set(t3.connection.name, t3);
    const o3 = new Map;
    for (const t3 of e36.hdRoutes) {
      const e37 = o3.get(t3.connectionName);
      e37 ? e37.push(t3) : o3.set(t3.connectionName, [t3]);
    }
    this.unsolvedRoutes = [];
    for (const [t3, i3] of o3.entries()) {
      const o4 = e36.connections.find((e37) => e37.name === t3);
      if (!o4)
        continue;
      const r3 = n2.get(t3);
      let s2 = [];
      r3?.path && (s2 = r3.path.map((e37) => e37.currentNodeId));
      const a3 = { ...o4.pointsToConnect[0], z: mo(Io(o4.pointsToConnect[0]), e36.layerCount) }, c3 = { ...o4.pointsToConnect[1], z: mo(Io(o4.pointsToConnect[1]), e36.layerCount) };
      this.unsolvedRoutes.push({ connectionName: t3, hdRoutes: i3, nodeOrder: s2, start: a3, end: c3 });
    }
    this.MAX_ITERATIONS = 1e5;
  }
  _step() {
    const e36 = this.unsolvedRoutes.pop();
    if (!e36)
      return void (this.solved = true);
    const t2 = this.stitchOrderedRoutes(e36);
    this.mergedHdRoutes.push(t2);
  }
  stitchOrderedRoutes(e36) {
    const { connectionName: t2, hdRoutes: n2, nodeOrder: o3, start: i3, end: r3 } = e36;
    if (n2.length === 0)
      return { connectionName: t2, traceThickness: this.defaultTraceThickness, viaDiameter: this.defaultViaDiameter, route: [i3, r3], vias: [], jumpers: [] };
    let s2;
    s2 = o3.length > 0 ? this.orderRoutesByNodePath(n2, o3, i3, t2) : this.orderRoutesByProximity(n2, i3);
    const a3 = [], c3 = [], l3 = [];
    a3.push({ x: i3.x, y: i3.y, z: i3.z });
    for (let e37 = 0;e37 < s2.length; e37++) {
      const t3 = s2[e37], n3 = a3[a3.length - 1], o4 = t3.route[0], i4 = t3.route[t3.route.length - 1], r4 = me(n3, o4), h3 = me(n3, i4), d2 = Math.min(r4, h3);
      if (e37 > 0 && d2 > 1)
        continue;
      let u2;
      u2 = r4 <= h3 ? [...t3.route] : [...t3.route].reverse();
      const p3 = 0.001;
      u2.length > 0 && me(n3, u2[0]) < p3 && (u2 = u2.slice(1)), a3.push(...u2), c3.push(...t3.vias), t3.jumpers && l3.push(...t3.jumpers);
    }
    const h2 = me(a3[a3.length - 1], r3);
    return h2 > 0.001 && h2 < 1 && a3.push({ x: r3.x, y: r3.y, z: r3.z }), { connectionName: t2, rootConnectionName: n2[0]?.rootConnectionName, traceThickness: n2[0]?.traceThickness ?? this.defaultTraceThickness, viaDiameter: n2[0]?.viaDiameter ?? this.defaultViaDiameter, route: a3, vias: c3, jumpers: l3 };
  }
  orderRoutesByNodePath(e36, t2, n2, o3) {
    if (e36.length === 0)
      return [];
    const i3 = new Set(e36);
    let r3 = null, s2 = 1 / 0;
    for (const e37 of i3) {
      const t3 = e37.route[0], o4 = e37.route[e37.route.length - 1], i4 = Math.min(me(n2, t3), me(n2, o4));
      i4 < s2 && (s2 = i4, r3 = e37);
    }
    if (!r3)
      return [];
    i3.delete(r3);
    const a3 = r3.route[0], c3 = r3.route[r3.route.length - 1];
    let l3, h2;
    me(n2, a3) <= me(n2, c3) ? (l3 = a3, h2 = c3) : (l3 = c3, h2 = a3);
    const d2 = (e37, t3) => {
      let n3 = 0;
      for (const o4 of i3) {
        if (o4 === t3)
          continue;
        const i4 = o4.route[0], r4 = o4.route[o4.route.length - 1];
        (me(e37, i4) < 10 || me(e37, r4) < 10) && n3++;
      }
      return n3;
    }, u2 = [r3];
    let p3 = h2;
    for (;i3.size > 0; ) {
      let e37 = null, t3 = 1 / 0, n3 = -1;
      for (const o4 of i3) {
        const i4 = o4.route[0], r4 = o4.route[o4.route.length - 1], s3 = me(p3, i4), a4 = me(p3, r4), c4 = Math.min(s3, a4);
        if (c4 >= 10)
          continue;
        const l4 = d2(s3 <= a4 ? r4 : i4, o4), h3 = l4 === 0, u3 = n3 === 0, m3 = c4 - t3;
        let g3 = false;
        g3 = e37 === null || (!!(!h3 && u3 && m3 < 5) || !(h3 && !u3 && m3 > -5) && c4 < t3), g3 && (t3 = c4, e37 = o4, n3 = l4);
      }
      if (!e37)
        break;
      {
        u2.push(e37), i3.delete(e37);
        const t4 = e37.route[0], n4 = e37.route[e37.route.length - 1];
        p3 = me(p3, t4) <= me(p3, n4) ? n4 : t4;
      }
    }
    const m2 = [];
    for (p3 = l3;i3.size > 0; ) {
      let e37 = null, t3 = 1 / 0, o4 = -1;
      const r4 = me(p3, n2);
      for (const s3 of i3) {
        const i4 = s3.route[0], a4 = s3.route[s3.route.length - 1], c4 = me(p3, i4), l4 = me(p3, a4), h3 = Math.min(c4, l4);
        if (h3 >= 10)
          continue;
        const u3 = c4 <= l4 ? a4 : i4;
        if (me(u3, n2) > r4 + 2)
          continue;
        const m3 = d2(u3, s3), g3 = m3 === 0, f2 = o4 === 0, _2 = h3 - t3;
        let y2 = false;
        y2 = e37 === null || (!!(!g3 && f2 && _2 < 5) || !(g3 && !f2 && _2 > -5) && h3 < t3), y2 && (t3 = h3, e37 = s3, o4 = m3);
      }
      if (!e37)
        break;
      {
        m2.unshift(e37), i3.delete(e37);
        const t4 = e37.route[0], n3 = e37.route[e37.route.length - 1];
        p3 = me(p3, t4) <= me(p3, n3) ? n3 : t4;
      }
    }
    const g2 = [...m2, ...u2];
    if (i3.size > 0) {
      const t3 = [...i3].map((e37) => {
        const t4 = e37.route[0], n3 = e37.route[e37.route.length - 1];
        return `start=(${t4.x.toFixed(2)},${t4.y.toFixed(2)}) end=(${n3.x.toFixed(2)},${n3.y.toFixed(2)})`;
      });
      console.warn(`[StitchSolver] Skipped ${i3.size} routes for connection ${e36[0]?.connectionName ?? "?"}, skipped routes: ${t3.join("; ")}`);
    }
    return g2;
  }
  orderRoutesByProximity(e36, t2) {
    const n2 = new Set(e36), o3 = [];
    let i3 = t2;
    for (;n2.size > 0; ) {
      let e37 = null, t3 = 1 / 0, r3 = false;
      for (const o4 of n2) {
        const n3 = o4.route[0], s2 = o4.route[o4.route.length - 1], a3 = me(i3, n3), c3 = me(i3, s2);
        a3 < t3 && (t3 = a3, e37 = o4, r3 = false), c3 < t3 && (t3 = c3, e37 = o4, r3 = true);
      }
      if (!e37)
        break;
      {
        o3.push(e37), n2.delete(e37);
        const t4 = e37.route[0], s2 = e37.route[e37.route.length - 1];
        i3 = r3 ? t4 : s2;
      }
    }
    return o3;
  }
  visualize() {
    const e36 = { points: [], lines: [], circles: [], rects: [], title: "Multiple High Density Route Stitch Solver 2" };
    for (const [t2, n2] of this.mergedHdRoutes.entries()) {
      const o3 = this.colorMap[n2.connectionName] ?? `hsl(120, 100%, ${40 + 10 * t2 % 40}%)`;
      for (let t3 = 0;t3 < n2.route.length - 1; t3++) {
        const i3 = n2.route[t3], r3 = n2.route[t3 + 1], s2 = i3.z !== 0 ? Ao(o3, 0.5) : o3;
        e36.lines?.push({ points: [{ x: i3.x, y: i3.y }, { x: r3.x, y: r3.y }], strokeColor: s2, strokeWidth: n2.traceThickness });
      }
      for (const t3 of n2.route) {
        const n3 = t3.z !== 0 ? Ao(o3, 0.5) : o3;
        e36.points?.push({ x: t3.x, y: t3.y, color: n3 });
      }
      for (const t3 of n2.vias)
        e36.circles?.push({ center: { x: t3.x, y: t3.y }, radius: n2.viaDiameter / 2, fill: o3 });
      if (n2.jumpers && n2.jumpers.length > 0) {
        const t3 = fB(n2.jumpers, { color: o3, label: n2.connectionName });
        e36.rects.push(...t3.rects ?? []), e36.lines.push(...t3.lines ?? []);
      }
    }
    for (const t2 of this.unsolvedRoutes) {
      const n2 = this.colorMap[t2.connectionName] ?? "gray";
      e36.points?.push({ x: t2.start.x, y: t2.start.y, color: n2, label: `${t2.connectionName} Start` }, { x: t2.end.x, y: t2.end.y, color: n2, label: `${t2.connectionName} End` });
      for (let o3 = 0;o3 < t2.hdRoutes.length; o3++) {
        const i3 = t2.hdRoutes[o3];
        if (i3.route.length > 1 && e36.lines?.push({ points: i3.route.map((e37) => ({ x: e37.x, y: e37.y })), strokeColor: Ao(n2, 0.5), strokeDash: "10 5", label: `segment ${o3}` }), i3.jumpers && i3.jumpers.length > 0) {
          const t3 = fB(i3.jumpers, { color: n2, label: i3.connectionName });
          e36.rects.push(...t3.rects ?? []), e36.lines.push(...t3.lines ?? []);
        }
      }
    }
    return e36;
  }
};
var I$ = Object.create;
var S$ = Object.defineProperty;
var C$ = Object.getOwnPropertyDescriptor;
var P$ = Object.getOwnPropertyNames;
var M$ = Object.getPrototypeOf;
var w$ = Object.prototype.hasOwnProperty;
var N$ = (e36, t2) => function() {
  return t2 || (0, e36[P$(e36)[0]])((t2 = { exports: {} }).exports, t2), t2.exports;
};
var R$ = (e36, t2, n2) => (n2 = e36 != null ? I$(M$(e36)) : {}, ((e37, t3, n3, o3) => {
  if (t3 && typeof t3 == "object" || typeof t3 == "function")
    for (let i3 of P$(t3))
      w$.call(e37, i3) || i3 === n3 || S$(e37, i3, { get: () => t3[i3], enumerable: !(o3 = C$(t3, i3)) || o3.enumerable });
  return e37;
})(!t2 && e36 && e36.__esModule ? n2 : S$(n2, "default", { value: e36, enumerable: true }), e36));
var T$ = N$({ "node_modules/is-buffer/index.js"(e36, t2) {
  function n2(e37) {
    return !!e37.constructor && typeof e37.constructor.isBuffer == "function" && e37.constructor.isBuffer(e37);
  }
  t2.exports = function(e37) {
    return e37 != null && (n2(e37) || function(e38) {
      return typeof e38.readFloatLE == "function" && typeof e38.slice == "function" && n2(e38.slice(0, 0));
    }(e37) || !!e37._isBuffer);
  };
} });
var E$ = N$({ "node_modules/kind-of/index.js"(e36, t2) {
  var n2 = T$(), o3 = Object.prototype.toString;
  t2.exports = function(e37) {
    if (e37 === undefined)
      return "undefined";
    if (e37 === null)
      return "null";
    if (e37 === true || e37 === false || e37 instanceof Boolean)
      return "boolean";
    if (typeof e37 == "string" || e37 instanceof String)
      return "string";
    if (typeof e37 == "number" || e37 instanceof Number)
      return "number";
    if (typeof e37 == "function" || e37 instanceof Function)
      return "function";
    if (Array.isArray !== undefined && Array.isArray(e37))
      return "array";
    if (e37 instanceof RegExp)
      return "regexp";
    if (e37 instanceof Date)
      return "date";
    var t3 = o3.call(e37);
    return t3 === "[object RegExp]" ? "regexp" : t3 === "[object Date]" ? "date" : t3 === "[object Arguments]" ? "arguments" : t3 === "[object Error]" ? "error" : n2(e37) ? "buffer" : t3 === "[object Set]" ? "set" : t3 === "[object WeakSet]" ? "weakset" : t3 === "[object Map]" ? "map" : t3 === "[object WeakMap]" ? "weakmap" : t3 === "[object Symbol]" ? "symbol" : t3 === "[object Int8Array]" ? "int8array" : t3 === "[object Uint8Array]" ? "uint8array" : t3 === "[object Uint8ClampedArray]" ? "uint8clampedarray" : t3 === "[object Int16Array]" ? "int16array" : t3 === "[object Uint16Array]" ? "uint16array" : t3 === "[object Int32Array]" ? "int32array" : t3 === "[object Uint32Array]" ? "uint32array" : t3 === "[object Float32Array]" ? "float32array" : t3 === "[object Float64Array]" ? "float64array" : "object";
  };
} });
var A$ = N$({ "node_modules/rename-keys/index.js"(e36, t2) {
  (function() {
    function e37(e38, t3) {
      if (typeof t3 != "function")
        return e38;
      var n2 = {};
      for (var o3 in e38)
        Object.prototype.hasOwnProperty.call(e38, o3) && (n2[t3(o3, e38[o3]) || o3] = e38[o3]);
      return n2;
    }
    t2 !== undefined && t2.exports ? t2.exports = e37 : typeof define == "function" && define.amd ? define([], function() {
      return e37;
    }) : window.rename = e37;
  })();
} });
var O$ = N$({ "node_modules/deep-rename-keys/index.js"(e36, t2) {
  var n2 = E$(), o3 = A$();
  t2.exports = function e37(t3, i3) {
    var r3 = n2(t3);
    if (r3 !== "object" && r3 !== "array")
      throw new Error("expected an object");
    var s2 = [];
    for (var a3 in r3 === "object" && (t3 = o3(t3, i3), s2 = {}), t3)
      if (t3.hasOwnProperty(a3)) {
        var c3 = t3[a3];
        n2(c3) === "object" || n2(c3) === "array" ? s2[a3] = e37(c3, i3) : s2[a3] = c3;
      }
    return s2;
  };
} });
var k$ = N$({ "node_modules/eventemitter3/index.js"(e36, t2) {
  var n2 = Object.prototype.hasOwnProperty, o3 = "~";
  function i3() {}
  function r3(e37, t3, n3) {
    this.fn = e37, this.context = t3, this.once = n3 || false;
  }
  function s2() {
    this._events = new i3, this._eventsCount = 0;
  }
  Object.create && (i3.prototype = Object.create(null), new i3().__proto__ || (o3 = false)), s2.prototype.eventNames = function() {
    var e37, t3, i4 = [];
    if (this._eventsCount === 0)
      return i4;
    for (t3 in e37 = this._events)
      n2.call(e37, t3) && i4.push(o3 ? t3.slice(1) : t3);
    return Object.getOwnPropertySymbols ? i4.concat(Object.getOwnPropertySymbols(e37)) : i4;
  }, s2.prototype.listeners = function(e37, t3) {
    var n3 = o3 ? o3 + e37 : e37, i4 = this._events[n3];
    if (t3)
      return !!i4;
    if (!i4)
      return [];
    if (i4.fn)
      return [i4.fn];
    for (var r4 = 0, s3 = i4.length, a3 = new Array(s3);r4 < s3; r4++)
      a3[r4] = i4[r4].fn;
    return a3;
  }, s2.prototype.emit = function(e37, t3, n3, i4, r4, s3) {
    var a3 = o3 ? o3 + e37 : e37;
    if (!this._events[a3])
      return false;
    var c3, l3, h2 = this._events[a3], d2 = arguments.length;
    if (h2.fn) {
      switch (h2.once && this.removeListener(e37, h2.fn, undefined, true), d2) {
        case 1:
          return h2.fn.call(h2.context), true;
        case 2:
          return h2.fn.call(h2.context, t3), true;
        case 3:
          return h2.fn.call(h2.context, t3, n3), true;
        case 4:
          return h2.fn.call(h2.context, t3, n3, i4), true;
        case 5:
          return h2.fn.call(h2.context, t3, n3, i4, r4), true;
        case 6:
          return h2.fn.call(h2.context, t3, n3, i4, r4, s3), true;
      }
      for (l3 = 1, c3 = new Array(d2 - 1);l3 < d2; l3++)
        c3[l3 - 1] = arguments[l3];
      h2.fn.apply(h2.context, c3);
    } else {
      var u2, p3 = h2.length;
      for (l3 = 0;l3 < p3; l3++)
        switch (h2[l3].once && this.removeListener(e37, h2[l3].fn, undefined, true), d2) {
          case 1:
            h2[l3].fn.call(h2[l3].context);
            break;
          case 2:
            h2[l3].fn.call(h2[l3].context, t3);
            break;
          case 3:
            h2[l3].fn.call(h2[l3].context, t3, n3);
            break;
          case 4:
            h2[l3].fn.call(h2[l3].context, t3, n3, i4);
            break;
          default:
            if (!c3)
              for (u2 = 1, c3 = new Array(d2 - 1);u2 < d2; u2++)
                c3[u2 - 1] = arguments[u2];
            h2[l3].fn.apply(h2[l3].context, c3);
        }
    }
    return true;
  }, s2.prototype.on = function(e37, t3, n3) {
    var i4 = new r3(t3, n3 || this), s3 = o3 ? o3 + e37 : e37;
    return this._events[s3] ? this._events[s3].fn ? this._events[s3] = [this._events[s3], i4] : this._events[s3].push(i4) : (this._events[s3] = i4, this._eventsCount++), this;
  }, s2.prototype.once = function(e37, t3, n3) {
    var i4 = new r3(t3, n3 || this, true), s3 = o3 ? o3 + e37 : e37;
    return this._events[s3] ? this._events[s3].fn ? this._events[s3] = [this._events[s3], i4] : this._events[s3].push(i4) : (this._events[s3] = i4, this._eventsCount++), this;
  }, s2.prototype.removeListener = function(e37, t3, n3, r4) {
    var s3 = o3 ? o3 + e37 : e37;
    if (!this._events[s3])
      return this;
    if (!t3)
      return --this._eventsCount === 0 ? this._events = new i3 : delete this._events[s3], this;
    var a3 = this._events[s3];
    if (a3.fn)
      a3.fn !== t3 || r4 && !a3.once || n3 && a3.context !== n3 || (--this._eventsCount === 0 ? this._events = new i3 : delete this._events[s3]);
    else {
      for (var c3 = 0, l3 = [], h2 = a3.length;c3 < h2; c3++)
        (a3[c3].fn !== t3 || r4 && !a3[c3].once || n3 && a3[c3].context !== n3) && l3.push(a3[c3]);
      l3.length ? this._events[s3] = l3.length === 1 ? l3[0] : l3 : --this._eventsCount === 0 ? this._events = new i3 : delete this._events[s3];
    }
    return this;
  }, s2.prototype.removeAllListeners = function(e37) {
    var t3;
    return e37 ? (t3 = o3 ? o3 + e37 : e37, this._events[t3] && (--this._eventsCount === 0 ? this._events = new i3 : delete this._events[t3])) : (this._events = new i3, this._eventsCount = 0), this;
  }, s2.prototype.off = s2.prototype.removeListener, s2.prototype.addListener = s2.prototype.on, s2.prototype.setMaxListeners = function() {
    return this;
  }, s2.prefixed = o3, s2.EventEmitter = s2, t2 !== undefined && (t2.exports = s2);
} });
var D$ = N$({ "node_modules/xml-lexer/dist/lexer.js"(e36, t2) {
  function n2(e37, t3, n3) {
    return t3 in e37 ? Object.defineProperty(e37, t3, { value: n3, enumerable: true, configurable: true, writable: true }) : e37[t3] = n3, e37;
  }
  var o3 = k$(), i3 = function() {}, r3 = { 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" }, s2 = { 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" }, c3 = { " ": s2.space, "\t": s2.space, "\n": s2.space, "\r": s2.space, "<": s2.lt, ">": s2.gt, '"': s2.quote, "'": s2.quote, "=": s2.equal, "/": s2.slash };
  t2.exports = { State: r3, Action: s2, Type: a3, create: function(e37) {
    var t3, l3, h2, d2, u2, p3, m2, g2, f2, _2;
    e37 = Object.assign({ debug: false }, e37);
    var y2 = new o3, b2 = r3.data, x2 = "", v2 = "", I2 = "", S2 = "", C = "", P = "", M = function(t4, n3) {
      if (v2[0] !== "?" && v2[0] !== "!") {
        var o4 = { type: t4, value: n3 };
        e37.debug && console.log("emit:", o4), y2.emit("data", o4);
      }
    };
    y2.stateMachine = (n2(_2 = {}, r3.data, (n2(t3 = {}, s2.lt, function() {
      x2.trim() && M(a3.text, x2), v2 = "", C = false, b2 = r3.tagBegin;
    }), n2(t3, s2.char, function(e38) {
      x2 += e38;
    }), t3)), n2(_2, r3.cdata, n2({}, s2.char, function(e38) {
      (x2 += e38).substr(-3) === "]]>" && (M(a3.text, x2.slice(0, -3)), x2 = "", b2 = r3.data);
    })), n2(_2, r3.tagBegin, (n2(l3 = {}, s2.space, i3), n2(l3, s2.char, function(e38) {
      v2 = e38, b2 = r3.tagName;
    }), n2(l3, s2.slash, function() {
      v2 = "", C = true;
    }), l3)), n2(_2, r3.tagName, (n2(h2 = {}, s2.space, function() {
      C ? b2 = r3.tagEnd : (b2 = r3.attributeNameStart, M(a3.openTag, v2));
    }), n2(h2, s2.gt, function() {
      M(C ? a3.closeTag : a3.openTag, v2), x2 = "", b2 = r3.data;
    }), n2(h2, s2.slash, function() {
      b2 = r3.tagEnd, M(a3.openTag, v2);
    }), n2(h2, s2.char, function(e38) {
      (v2 += e38) === "![CDATA[" && (b2 = r3.cdata, x2 = "", v2 = "");
    }), h2)), n2(_2, r3.tagEnd, (n2(d2 = {}, s2.gt, function() {
      M(a3.closeTag, v2), x2 = "", b2 = r3.data;
    }), n2(d2, s2.char, i3), d2)), n2(_2, r3.attributeNameStart, (n2(u2 = {}, s2.char, function(e38) {
      I2 = e38, b2 = r3.attributeName;
    }), n2(u2, s2.gt, function() {
      x2 = "", b2 = r3.data;
    }), n2(u2, s2.space, i3), n2(u2, s2.slash, function() {
      C = true, b2 = r3.tagEnd;
    }), u2)), n2(_2, r3.attributeName, (n2(p3 = {}, s2.space, function() {
      b2 = r3.attributeNameEnd;
    }), n2(p3, s2.equal, function() {
      M(a3.attributeName, I2), b2 = r3.attributeValueBegin;
    }), n2(p3, s2.gt, function() {
      S2 = "", M(a3.attributeName, I2), M(a3.attributeValue, S2), x2 = "", b2 = r3.data;
    }), n2(p3, s2.slash, function() {
      C = true, S2 = "", M(a3.attributeName, I2), M(a3.attributeValue, S2), b2 = r3.tagEnd;
    }), n2(p3, s2.char, function(e38) {
      I2 += e38;
    }), p3)), n2(_2, r3.attributeNameEnd, (n2(m2 = {}, s2.space, i3), n2(m2, s2.equal, function() {
      M(a3.attributeName, I2), b2 = r3.attributeValueBegin;
    }), n2(m2, s2.gt, function() {
      S2 = "", M(a3.attributeName, I2), M(a3.attributeValue, S2), x2 = "", b2 = r3.data;
    }), n2(m2, s2.char, function(e38) {
      S2 = "", M(a3.attributeName, I2), M(a3.attributeValue, S2), I2 = e38, b2 = r3.attributeName;
    }), m2)), n2(_2, r3.attributeValueBegin, (n2(g2 = {}, s2.space, i3), n2(g2, s2.quote, function(e38) {
      P = e38, S2 = "", b2 = r3.attributeValue;
    }), n2(g2, s2.gt, function() {
      M(a3.attributeValue, S2 = ""), x2 = "", b2 = r3.data;
    }), n2(g2, s2.char, function(e38) {
      P = "", S2 = e38, b2 = r3.attributeValue;
    }), g2)), n2(_2, r3.attributeValue, (n2(f2 = {}, s2.space, function(e38) {
      P ? S2 += e38 : (M(a3.attributeValue, S2), b2 = r3.attributeNameStart);
    }), n2(f2, s2.quote, function(e38) {
      P === e38 ? (M(a3.attributeValue, S2), b2 = r3.attributeNameStart) : S2 += e38;
    }), n2(f2, s2.gt, function(e38) {
      P ? S2 += e38 : (M(a3.attributeValue, S2), x2 = "", b2 = r3.data);
    }), n2(f2, s2.slash, function(e38) {
      P ? S2 += e38 : (M(a3.attributeValue, S2), C = true, b2 = r3.tagEnd);
    }), n2(f2, s2.char, function(e38) {
      S2 += e38;
    }), f2)), _2);
    var w = function(t4) {
      e37.debug && console.log(b2, t4);
      var n3 = y2.stateMachine[b2], o4 = n3[function(e38) {
        return c3[e38] || s2.char;
      }(t4)] || n3[s2.error] || n3[s2.char];
      o4(t4);
    };
    return y2.write = function(e38) {
      for (var t4 = e38.length, n3 = 0;n3 < t4; n3++)
        w(e38[n3]);
    }, y2;
  } };
} });
var L$ = N$({ "node_modules/xml-reader/dist/reader.js"(e36, t2) {
  var n2 = k$(), o3 = D$(), i3 = o3.Type, r3 = { element: "element", text: "text" }, s2 = function(e37) {
    return Object.assign({ name: "", type: r3.element, value: "", parent: null, attributes: {}, children: [] }, e37);
  }, a3 = function(e37) {
    e37 = Object.assign({ stream: false, parentNodes: true, doneEvent: "done", tagPrefix: "tag:", emitTopLevelOnly: false, debug: false }, e37);
    var t3 = undefined, a4 = undefined, c3 = undefined, l3 = undefined, h2 = new n2, d2 = function(n3) {
      switch (n3.type) {
        case i3.openTag:
          if (c3 === null)
            (c3 = a4).name = n3.value;
          else {
            var o4 = s2({ name: n3.value, parent: c3 });
            c3.children.push(o4), c3 = o4;
          }
          break;
        case i3.closeTag:
          var d3 = c3.parent;
          if (e37.parentNodes || (c3.parent = null), c3.name !== n3.value)
            break;
          e37.stream && d3 === a4 && (a4.children = [], c3.parent = null), e37.emitTopLevelOnly && d3 !== a4 || (h2.emit(e37.tagPrefix + c3.name, c3), h2.emit("tag", c3.name, c3)), c3 === a4 && (t3.removeAllListeners("data"), h2.emit(e37.doneEvent, c3), a4 = null), c3 = d3;
          break;
        case i3.text:
          c3 && c3.children.push(s2({ type: r3.text, value: n3.value, parent: e37.parentNodes ? c3 : null }));
          break;
        case i3.attributeName:
          l3 = n3.value, c3.attributes[l3] = "";
          break;
        case i3.attributeValue:
          c3.attributes[l3] = n3.value;
      }
    };
    return h2.reset = function() {
      (t3 = o3.create({ debug: e37.debug })).on("data", d2), a4 = s2(), c3 = null, l3 = "", h2.parse = t3.write;
    }, h2.reset(), h2;
  };
  t2.exports = { parseSync: function(e37, t3) {
    t3 = Object.assign({}, t3, { stream: false, tagPrefix: ":" });
    var n3 = a3(t3), o4 = undefined;
    return n3.on("done", function(e38) {
      o4 = e38;
    }), n3.parse(e37), o4;
  }, create: a3, NodeType: r3 };
} });
var $$ = (R$(O$()), R$(L$()), class {
  MAX_ITERATIONS = 1e5;
  solved = false;
  failed = false;
  iterations = 0;
  progress = 0;
  error = null;
  activeSubSolver;
  failedSubSolvers;
  timeToSolve;
  stats = {};
  _setupDone = false;
  setup() {
    this._setupDone || (this._setup(), this._setupDone = true);
  }
  _setup() {}
  step() {
    if (this._setupDone || this.setup(), !this.solved && !this.failed) {
      this.iterations++;
      try {
        this._step();
      } catch (e36) {
        throw this.error = `${this.constructor.name} error: ${e36}`, this.failed = true, e36;
      }
      !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 = true), "computeProgress" in this && (this.progress = this.computeProgress());
    }
  }
  _step() {}
  getConstructorParams() {
    throw new Error("getConstructorParams not implemented");
  }
  getOutput() {
    return null;
  }
  solve() {
    const e36 = Date.now();
    for (;!this.solved && !this.failed; )
      this.step();
    const t2 = Date.now();
    this.timeToSolve = t2 - e36;
  }
  visualize() {
    return { lines: [], points: [], rects: [], circles: [] };
  }
  tryFinalAcceptance() {}
  preview() {
    return { lines: [], points: [], rects: [], circles: [] };
  }
});
var Y$ = (e36) => e36 ? `hsl(${((e37) => {
  let t2 = 0;
  for (let n2 = 0;n2 < e37.length; n2++)
    t2 = 779 * e37.charCodeAt(n2) + ((t2 << 5) - t2);
  return t2;
})(e36) % 360}, 100%, 50%)` : "rgba(0, 0, 0, 0.5)";
var X$ = (e36) => [[{ x: e36.minX, y: e36.minY }, { x: e36.maxX, y: e36.minY }], [{ x: e36.maxX, y: e36.minY }, { x: e36.maxX, y: e36.maxY }], [{ x: e36.maxX, y: e36.maxY }, { x: e36.minX, y: e36.maxY }], [{ x: e36.minX, y: e36.maxY }, { x: e36.minX, y: e36.minY }]];
function H$(e36, t2) {
  const { minX: n2, maxX: o3, minY: i3, maxY: r3 } = t2, s2 = o3 - n2, a3 = r3 - i3, c3 = 0.000001;
  return Math.abs(e36.y - r3) < c3 ? e36.x - n2 : Math.abs(e36.x - o3) < c3 ? s2 + (r3 - e36.y) : Math.abs(e36.y - i3) < c3 ? s2 + a3 + (o3 - e36.x) : Math.abs(e36.x - n2) < c3 ? 2 * s2 + a3 + (e36.y - i3) : 0;
}
function V$(e36, t2) {
  const { minX: n2, maxX: o3, minY: i3, maxY: r3 } = t2, s2 = 0.000001, a3 = Math.abs(e36.y - r3) < s2, c3 = Math.abs(e36.y - i3) < s2, l3 = Math.abs(e36.x - o3) < s2, h2 = Math.abs(e36.x - n2) < s2;
  if (a3 && l3)
    return { x: -Math.SQRT1_2, y: -Math.SQRT1_2 };
  if (a3 && h2)
    return { x: Math.SQRT1_2, y: -Math.SQRT1_2 };
  if (c3 && l3)
    return { x: -Math.SQRT1_2, y: Math.SQRT1_2 };
  if (c3 && h2)
    return { x: Math.SQRT1_2, y: Math.SQRT1_2 };
  if (a3)
    return { x: 0, y: -1 };
  if (c3)
    return { x: 0, y: 1 };
  if (l3)
    return { x: -1, y: 0 };
  if (h2)
    return { x: 1, y: 0 };
  const d2 = (i3 + r3) / 2, u2 = (n2 + o3) / 2 - e36.x, p3 = d2 - e36.y, m2 = Math.hypot(u2, p3);
  return m2 > 0 ? { x: u2 / m2, y: p3 / m2 } : { x: 0, y: -1 };
}
function W$(e36, t2, n2, o3, i3, r3, s2, a3, c3, l3) {
  for (let h2 = 0;h2 <= l3; h2++) {
    const d2 = h2 / l3, u2 = 1 - d2, p3 = u2 * u2, m2 = p3 * u2, g2 = d2 * d2, f2 = g2 * d2, _2 = 2 * h2;
    c3[_2] = m2 * e36 + 3 * p3 * d2 * n2 + 3 * u2 * g2 * i3 + f2 * s2, c3[_2 + 1] = m2 * t2 + 3 * p3 * d2 * o3 + 3 * u2 * g2 * r3 + f2 * a3;
  }
}
function G$(e36, t2, n2, o3, i3) {
  const r3 = [];
  for (let s2 = 0;s2 <= i3; s2++) {
    const a3 = s2 / i3, c3 = 1 - a3, l3 = c3 * c3, h2 = l3 * c3, d2 = a3 * a3, u2 = d2 * a3;
    r3.push({ x: h2 * e36.x + 3 * l3 * a3 * t2.x + 3 * c3 * d2 * n2.x + u2 * o3.x, y: h2 * e36.y + 3 * l3 * a3 * t2.y + 3 * c3 * d2 * n2.y + u2 * o3.y });
  }
  return r3;
}
function U$(e36, t2, n2, o3, i3, r3) {
  const s2 = i3 - n2, a3 = r3 - o3, c3 = s2 * s2 + a3 * a3;
  if (c3 === 0) {
    const i4 = e36 - n2, r4 = t2 - o3;
    return i4 * i4 + r4 * r4;
  }
  const l3 = Math.max(0, Math.min(1, ((e36 - n2) * s2 + (t2 - o3) * a3) / c3)), h2 = e36 - (n2 + l3 * s2), d2 = t2 - (o3 + l3 * a3);
  return h2 * h2 + d2 * d2;
}
function Z$(e36, t2, n2, o3, i3, r3, s2, a3) {
  const c3 = (s2 - i3) * (t2 - r3) - (a3 - r3) * (e36 - i3), l3 = (s2 - i3) * (o3 - r3) - (a3 - r3) * (n2 - i3), h2 = (n2 - e36) * (r3 - t2) - (o3 - t2) * (i3 - e36), d2 = (n2 - e36) * (a3 - t2) - (o3 - t2) * (s2 - e36);
  return (c3 > 0 && l3 < 0 || c3 < 0 && l3 > 0) && (h2 > 0 && d2 < 0 || h2 < 0 && d2 > 0) ? 0 : Math.min(U$(e36, t2, i3, r3, s2, a3), U$(n2, o3, i3, r3, s2, a3), U$(i3, r3, e36, t2, n2, o3), U$(s2, a3, e36, t2, n2, o3));
}
function q$(e36, t2, n2, o3, i3, r3, s2, a3) {
  const c3 = (s2 - i3) * (t2 - r3) - (a3 - r3) * (e36 - i3), l3 = (s2 - i3) * (o3 - r3) - (a3 - r3) * (n2 - i3), h2 = (n2 - e36) * (r3 - t2) - (o3 - t2) * (i3 - e36), d2 = (n2 - e36) * (a3 - t2) - (o3 - t2) * (s2 - e36);
  return (c3 > 0 && l3 < 0 || c3 < 0 && l3 > 0) && (h2 > 0 && d2 < 0 || h2 < 0 && d2 > 0);
}
function J$(e36, t2, n2, o3, i3) {
  const r3 = (e37) => (e37 % i3 + i3) % i3, s2 = r3(e36), a3 = r3(t2), c3 = r3(n2), l3 = r3(o3), [h2, d2] = s2 < a3 ? [s2, a3] : [a3, s2];
  return c3 > h2 && c3 < d2 && l3 > h2 && l3 < d2;
}
function Q$(e36, t2) {
  let n2 = 1 / 0, o3 = -1 / 0, i3 = 1 / 0, r3 = -1 / 0;
  for (let s2 = 0;s2 < t2; s2++) {
    const t3 = e36[2 * s2], a3 = e36[2 * s2 + 1];
    t3 < n2 && (n2 = t3), t3 > o3 && (o3 = t3), a3 < i3 && (i3 = a3), a3 > r3 && (r3 = a3);
  }
  return { minX: n2, maxX: o3, minY: i3, maxY: r3 };
}
var K$ = class extends $$ {
  constructor(e36) {
    super(), this.problem = e36;
    for (const e37 of this.problem.obstacles)
      e37.outerSegments = X$(e37);
    this.precomputeObstacles();
  }
  outputTraces = [];
  traces = [];
  optimizationStep = 0;
  maxOptimizationSteps = 100;
  sampledPoints = [];
  traceBounds = [];
  obstacleSegments = new Float64Array(0);
  obstacleNetworkIds = [];
  numObstacleSegments = 0;
  collisionPairs = [];
  lastCost = 1 / 0;
  stagnantSteps = 0;
  effectiveTraceToTraceSpacing = 0;
  getConstructorParams() {
    return this.problem;
  }
  precomputeObstacles() {
    const { obstacles: e36 } = this.problem;
    let t2 = 0;
    for (const n3 of e36)
      n3.outerSegments && (t2 += n3.outerSegments.length);
    this.obstacleSegments = new Float64Array(4 * t2), this.obstacleNetworkIds = [], this.numObstacleSegments = t2;
    let n2 = 0;
    for (const t3 of e36)
      if (t3.outerSegments)
        for (const e37 of t3.outerSegments)
          this.obstacleSegments[n2++] = e37[0].x, this.obstacleSegments[n2++] = e37[0].y, this.obstacleSegments[n2++] = e37[1].x, this.obstacleSegments[n2++] = e37[1].y, this.obstacleNetworkIds.push(t3.networkId);
  }
  initializeTraces() {
    const { bounds: e36, waypointPairs: t2 } = this.problem, { minX: n2, maxX: o3, minY: i3, maxY: r3 } = e36, s2 = o3 - n2, a3 = r3 - i3, c3 = 2 * s2 + 2 * a3, l3 = function(e37) {
      return { x: (e37.minX + e37.maxX) / 2, y: (e37.minY + e37.maxY) / 2 };
    }(e36), h2 = t2.map((t3, n3) => ({ pair: t3, t1: H$(t3.start, e36), t2: H$(t3.end, e36), idx: n3 })), d2 = h2.map(() => []), u2 = h2.map(() => []);
    for (const e37 of h2)
      for (const t3 of h2)
        if (e37.idx !== t3.idx) {
          if (e37.pair.networkId && t3.pair.networkId && e37.pair.networkId === t3.pair.networkId)
            continue;
          J$(t3.t1, t3.t2, e37.t1, e37.t2, c3) && (d2[e37.idx].push(t3.idx), u2[t3.idx].push(e37.idx));
        }
    const p3 = d2.map((e37) => e37.length), m2 = Math.max(...p3, 1);
    this.traces = h2.map(({ pair: t3, t1: n3, t2: o4, idx: i4 }) => {
      const r4 = V$(t3.start, e36), c4 = V$(t3.end, e36), h3 = Math.hypot(t3.end.x - t3.start.x, t3.end.y - t3.start.y), g2 = p3[i4] / m2, f2 = (t3.start.x + t3.end.x) / 2, _2 = (t3.start.y + t3.end.y) / 2, y2 = h3 * (0.25 + 0.15 * (1 - Math.hypot(f2 - l3.x, _2 - l3.y) / Math.hypot(s2 / 2, a3 / 2))) * (1 - 0.3 * g2), b2 = 0.05 * Math.min(s2, a3), x2 = Math.max(b2, y2), v2 = Math.max(b2, y2);
      return { waypointPair: t3, ctrl1: { x: t3.start.x + x2 * r4.x, y: t3.start.y + x2 * r4.y }, ctrl2: { x: t3.end.x + v2 * c4.x, y: t3.end.y + v2 * c4.y }, networkId: t3.networkId, t1: n3, t2: o4, perpDir1: r4, perpDir2: c4, d1: x2, d2: v2, containedBy: d2[i4], contains: u2[i4] };
    }), this.sampledPoints = this.traces.map(() => new Float64Array(12)), this.traceBounds = this.traces.map(() => ({ minX: 0, maxX: 0, minY: 0, maxY: 0 })), this.updateSampledTraces(), this.updateCollisionPairs();
  }
  updateSampledTraces() {
    for (let e36 = 0;e36 < this.traces.length; e36++) {
      const t2 = this.traces[e36];
      W$(t2.waypointPair.start.x, t2.waypointPair.start.y, t2.ctrl1.x, t2.ctrl1.y, t2.ctrl2.x, t2.ctrl2.y, t2.waypointPair.end.x, t2.waypointPair.end.y, this.sampledPoints[e36], 5), this.traceBounds[e36] = Q$(this.sampledPoints[e36], 6);
    }
  }
  updateSingleTraceSample(e36) {
    const t2 = this.traces[e36];
    W$(t2.waypointPair.start.x, t2.waypointPair.start.y, t2.ctrl1.x, t2.ctrl1.y, t2.ctrl2.x, t2.ctrl2.y, t2.waypointPair.end.x, t2.waypointPair.end.y, this.sampledPoints[e36], 5), this.traceBounds[e36] = Q$(this.sampledPoints[e36], 6);
  }
  updateControlPointsFromDistances(e36) {
    const t2 = this.traces[e36], { minX: n2, maxX: o3, minY: i3, maxY: r3 } = this.problem.bounds, s2 = 0.000001;
    let a3 = t2.waypointPair.start.x + t2.d1 * t2.perpDir1.x, c3 = t2.waypointPair.start.y + t2.d1 * t2.perpDir1.y, l3 = t2.waypointPair.end.x + t2.d2 * t2.perpDir2.x, h2 = t2.waypointPair.end.y + t2.d2 * t2.perpDir2.y;
    const d2 = t2.waypointPair.start;
    Math.abs(d2.x - n2) < s2 && (a3 = Math.max(a3, n2)), Math.abs(d2.x - o3) < s2 && (a3 = Math.min(a3, o3)), Math.abs(d2.y - i3) < s2 && (c3 = Math.max(c3, i3)), Math.abs(d2.y - r3) < s2 && (c3 = Math.min(c3, r3));
    const u2 = t2.waypointPair.end;
    Math.abs(u2.x - n2) < s2 && (l3 = Math.max(l3, n2)), Math.abs(u2.x - o3) < s2 && (l3 = Math.min(l3, o3)), Math.abs(u2.y - i3) < s2 && (h2 = Math.max(h2, i3)), Math.abs(u2.y - r3) < s2 && (h2 = Math.min(h2, r3)), a3 = Math.max(n2, Math.min(o3, a3)), c3 = Math.max(i3, Math.min(r3, c3)), l3 = Math.max(n2, Math.min(o3, l3)), h2 = Math.max(i3, Math.min(r3, h2)), t2.ctrl1.x = a3, t2.ctrl1.y = c3, t2.ctrl2.x = l3, t2.ctrl2.y = h2;
  }
  updateCollisionPairs() {
    const e36 = this.effectiveTraceToTraceSpacing;
    this.collisionPairs = [];
    for (let t2 = 0;t2 < this.traces.length; t2++)
      for (let n2 = t2 + 1;n2 < this.traces.length; n2++) {
        const o3 = this.traces[t2], i3 = this.traces[n2];
        if (o3.networkId && i3.networkId && o3.networkId === i3.networkId)
          continue;
        const r3 = this.traceBounds[t2], s2 = this.traceBounds[n2];
        r3.maxX + e36 >= s2.minX && s2.maxX + e36 >= r3.minX && r3.maxY + e36 >= s2.minY && s2.maxY + e36 >= r3.minY && this.collisionPairs.push([t2, n2]);
      }
  }
  computeTotalCost() {
    const { preferredObstacleToTraceSpacing: e36 } = this.problem, t2 = this.effectiveTraceToTraceSpacing, n2 = t2 ** 2, o3 = e36 ** 2;
    let i3 = 0;
    for (const [e37, o4] of this.collisionPairs) {
      const r3 = this.sampledPoints[e37], s2 = this.sampledPoints[o4];
      for (let e38 = 0;e38 < 5; e38++) {
        const o5 = r3[2 * e38], a3 = r3[2 * e38 + 1], c3 = r3[2 * (e38 + 1)], l3 = r3[2 * (e38 + 1) + 1];
        for (let e39 = 0;e39 < 5; e39++) {
          const r4 = Z$(o5, a3, c3, l3, s2[2 * e39], s2[2 * e39 + 1], s2[2 * (e39 + 1)], s2[2 * (e39 + 1) + 1]);
          if (r4 < n2) {
            i3 += (t2 - Math.sqrt(r4)) ** 2, r4 < 0.000000000000000001 && (i3 += 20 * n2);
          }
        }
      }
    }
    for (let t3 = 0;t3 < this.traces.length; t3++) {
      const n3 = this.traces[t3], r3 = this.sampledPoints[t3], s2 = this.traceBounds[t3];
      for (let t4 = 0;t4 < this.numObstacleSegments; t4++) {
        if (n3.networkId && this.obstacleNetworkIds[t4] && n3.networkId === this.obstacleNetworkIds[t4])
          continue;
        const a3 = 4 * t4, c3 = this.obstacleSegments[a3], l3 = this.obstacleSegments[a3 + 1], h2 = this.obstacleSegments[a3 + 2], d2 = this.obstacleSegments[a3 + 3], u2 = Math.min(c3, h2), p3 = Math.max(c3, h2), m2 = Math.min(l3, d2), g2 = Math.max(l3, d2);
        if (!(s2.maxX + e36 < u2 || p3 + e36 < s2.minX || s2.maxY + e36 < m2 || g2 + e36 < s2.minY))
          for (let t5 = 0;t5 < 5; t5++) {
            const n4 = Z$(r3[2 * t5], r3[2 * t5 + 1], r3[2 * (t5 + 1)], r3[2 * (t5 + 1) + 1], c3, l3, h2, d2);
            if (n4 < o3) {
              i3 += (e36 - Math.sqrt(n4)) ** 2, n4 < 0.000000000000000001 && (i3 += 20 * o3);
            }
          }
      }
    }
    return i3;
  }
  computeCostForTrace(e36) {
    const { preferredObstacleToTraceSpacing: t2 } = this.problem, n2 = this.effectiveTraceToTraceSpacing, o3 = n2 ** 2, i3 = t2 ** 2, r3 = this.traces[e36], s2 = this.sampledPoints[e36], a3 = this.traceBounds[e36];
    let c3 = 0;
    for (let t3 = 0;t3 < this.traces.length; t3++) {
      if (t3 === e36)
        continue;
      const i4 = this.traces[t3];
      if (r3.networkId && i4.networkId && r3.networkId === i4.networkId)
        continue;
      const l3 = this.traceBounds[t3];
      if (a3.maxX + n2 < l3.minX || l3.maxX + n2 < a3.minX || a3.maxY + n2 < l3.minY || l3.maxY + n2 < a3.minY)
        continue;
      const h2 = this.sampledPoints[t3];
      for (let e37 = 0;e37 < 5; e37++) {
        const t4 = s2[2 * e37], i5 = s2[2 * e37 + 1], r4 = s2[2 * (e37 + 1)], a4 = s2[2 * (e37 + 1) + 1];
        for (let e38 = 0;e38 < 5; e38++) {
          const s3 = Z$(t4, i5, r4, a4, h2[2 * e38], h2[2 * e38 + 1], h2[2 * (e38 + 1)], h2[2 * (e38 + 1) + 1]);
          if (s3 < o3) {
            c3 += (n2 - Math.sqrt(s3)) ** 2, s3 < 0.000000000000000001 && (c3 += 20 * o3);
          }
        }
      }
    }
    for (let e37 = 0;e37 < this.numObstacleSegments; e37++) {
      if (r3.networkId && this.obstacleNetworkIds[e37] && r3.networkId === this.obstacleNetworkIds[e37])
        continue;
      const n3 = 4 * e37, o4 = this.obstacleSegments[n3], l3 = this.obstacleSegments[n3 + 1], h2 = this.obstacleSegments[n3 + 2], d2 = this.obstacleSegments[n3 + 3], u2 = Math.min(o4, h2), p3 = Math.max(o4, h2), m2 = Math.min(l3, d2), g2 = Math.max(l3, d2);
      if (!(a3.maxX + t2 < u2 || p3 + t2 < a3.minX || a3.maxY + t2 < m2 || g2 + t2 < a3.minY))
        for (let e38 = 0;e38 < 5; e38++) {
          const n4 = Z$(s2[2 * e38], s2[2 * e38 + 1], s2[2 * (e38 + 1)], s2[2 * (e38 + 1) + 1], o4, l3, h2, d2);
          if (n4 < i3) {
            c3 += (t2 - Math.sqrt(n4)) ** 2, n4 < 0.000000000000000001 && (c3 += 20 * i3);
          }
        }
    }
    return c3;
  }
  tracesIntersect(e36, t2) {
    const n2 = this.traces[e36], o3 = this.traces[t2], i3 = 15, r3 = new Float64Array(32), s2 = new Float64Array(32);
    W$(n2.waypointPair.start.x, n2.waypointPair.start.y, n2.ctrl1.x, n2.ctrl1.y, n2.ctrl2.x, n2.ctrl2.y, n2.waypointPair.end.x, n2.waypointPair.end.y, r3, i3), W$(o3.waypointPair.start.x, o3.waypointPair.start.y, o3.ctrl1.x, o3.ctrl1.y, o3.ctrl2.x, o3.ctrl2.y, o3.waypointPair.end.x, o3.waypointPair.end.y, s2, i3);
    for (let e37 = 0;e37 < i3; e37++) {
      const t3 = r3[2 * e37], n3 = r3[2 * e37 + 1], o4 = r3[2 * (e37 + 1)], a3 = r3[2 * (e37 + 1) + 1];
      for (let e38 = 0;e38 < i3; e38++) {
        if (q$(t3, n3, o4, a3, s2[2 * e38], s2[2 * e38 + 1], s2[2 * (e38 + 1)], s2[2 * (e38 + 1) + 1]))
          return true;
      }
    }
    return false;
  }
  findIntersectingPairs() {
    const e36 = [];
    for (let t2 = 0;t2 < this.traces.length; t2++)
      for (let n2 = t2 + 1;n2 < this.traces.length; n2++) {
        const o3 = this.traces[t2], i3 = this.traces[n2];
        if (o3.networkId && i3.networkId && o3.networkId === i3.networkId)
          continue;
        const r3 = this.traceBounds[t2], s2 = this.traceBounds[n2];
        r3.maxX < s2.minX || s2.maxX < r3.minX || r3.maxY < s2.minY || s2.maxY < r3.minY || this.tracesIntersect(t2, n2) && e36.push([t2, n2]);
      }
    return e36;
  }
  resolveIntersections() {
    const { bounds: e36, preferredTraceToTraceSpacing: t2 } = this.problem, { minX: n2, maxX: o3, minY: i3, maxY: r3 } = e36, s2 = Math.min(o3 - n2, r3 - i3), a3 = 0.02 * s2, c3 = 1.5 * s2, l3 = this.findIntersectingPairs();
    if (l3.length === 0)
      return 0;
    let h2 = 0;
    for (const [e37, n3] of l3) {
      const o4 = this.traces[e37], i4 = this.traces[n3];
      if (!this.tracesIntersect(e37, n3))
        continue;
      let r4, s3;
      if (o4.containedBy.includes(n3))
        r4 = n3, s3 = e37;
      else if (i4.containedBy.includes(e37))
        r4 = e37, s3 = n3;
      else {
        (o4.d1 + o4.d2) / 2 < (i4.d1 + i4.d2) / 2 ? (r4 = e37, s3 = n3) : (r4 = n3, s3 = e37);
      }
      const l4 = this.traces[r4], d2 = this.traces[s3], u2 = l4.d1, p3 = l4.d2, m2 = d2.d1, g2 = d2.d2, f2 = 2 * t2, _2 = [{ innerMult: 1, outerMult: 0 }, { innerMult: 0, outerMult: 1 }, { innerMult: 0.5, outerMult: 0.5 }, { innerMult: 2, outerMult: 0 }, { innerMult: 1, outerMult: 1 }, { innerMult: 3, outerMult: 0 }, { innerMult: 2, outerMult: 1 }, { innerMult: 4, outerMult: 0 }];
      let y2 = this.computeTotalCost(), b2 = null;
      for (const e38 of _2)
        if (l4.d1 = u2, l4.d2 = p3, d2.d1 = m2, d2.d2 = g2, d2.d1 = Math.min(c3, m2 + f2 * e38.innerMult), d2.d2 = Math.min(c3, g2 + f2 * e38.innerMult), l4.d1 = Math.max(a3, u2 - f2 * e38.outerMult), l4.d2 = Math.max(a3, p3 - f2 * e38.outerMult), this.updateControlPointsFromDistances(s3), this.updateControlPointsFromDistances(r4), this.updateSingleTraceSample(s3), this.updateSingleTraceSample(r4), !this.tracesIntersect(r4, s3)) {
          const t3 = this.computeTotalCost();
          (b2 === null || t3 < y2) && (y2 = t3, b2 = e38);
        }
      b2 ? (d2.d1 = Math.min(c3, m2 + f2 * b2.innerMult), d2.d2 = Math.min(c3, g2 + f2 * b2.innerMult), l4.d1 = Math.max(a3, u2 - f2 * b2.outerMult), l4.d2 = Math.max(a3, p3 - f2 * b2.outerMult), this.updateControlPointsFromDistances(s3), this.updateControlPointsFromDistances(r4), this.updateSingleTraceSample(s3), this.updateSingleTraceSample(r4), h2++) : (l4.d1 = u2, l4.d2 = p3, d2.d1 = m2, d2.d2 = g2, this.updateControlPointsFromDistances(r4), this.updateControlPointsFromDistances(s3), this.updateSingleTraceSample(r4), this.updateSingleTraceSample(s3));
    }
    return h2;
  }
  optimizeStep() {
    const { bounds: e36 } = this.problem, { minX: t2, maxX: n2, minY: o3, maxY: i3 } = e36, r3 = Math.min(n2 - t2, i3 - o3), s2 = this.effectiveTraceToTraceSpacing, a3 = 4 * (1 - this.optimizationStep / this.maxOptimizationSteps) + 0.5, c3 = 0.02 * r3, l3 = 1.5 * r3, h2 = [];
    for (let e37 = 0;e37 < this.traces.length; e37++)
      h2.push({ idx: e37, cost: this.computeCostForTrace(e37) });
    h2.sort((e37, t3) => t3.cost - e37.cost);
    for (const { idx: e37, cost: t3 } of h2) {
      if (t3 === 0)
        continue;
      const n3 = this.traces[e37], o4 = t3 > 100 ? 2 : 1, i4 = [a3 * o4, 1.5 * a3 * o4, 0.5 * a3];
      for (const o5 of i4) {
        const i5 = t3 > 100 ? [o5, -o5, 2 * o5, 2 * -o5, 3 * o5, 3 * -o5, 2 * s2, 2 * -s2] : [o5, -o5, 2 * o5, 2 * -o5];
        let r4 = this.computeCostForTrace(e37), a4 = n3.d1, h3 = n3.d2;
        const { d1: d2, d2: u2 } = n3;
        for (const t4 of i5) {
          n3.d1 = Math.max(c3, Math.min(l3, d2 + t4)), this.updateControlPointsFromDistances(e37), this.updateSingleTraceSample(e37);
          const o6 = this.computeCostForTrace(e37);
          o6 < r4 && (r4 = o6, a4 = n3.d1, h3 = u2), n3.d1 = d2, this.updateControlPointsFromDistances(e37), n3.d2 = Math.max(c3, Math.min(l3, u2 + t4)), this.updateControlPointsFromDistances(e37), this.updateSingleTraceSample(e37);
          const i6 = this.computeCostForTrace(e37);
          i6 < r4 && (r4 = i6, a4 = d2, h3 = n3.d2), n3.d2 = u2, this.updateControlPointsFromDistances(e37), n3.d1 = Math.max(c3, Math.min(l3, d2 + t4)), n3.d2 = Math.max(c3, Math.min(l3, u2 + t4)), this.updateControlPointsFromDistances(e37), this.updateSingleTraceSample(e37);
          const s3 = this.computeCostForTrace(e37);
          s3 < r4 && (r4 = s3, a4 = n3.d1, h3 = n3.d2), n3.d1 = d2, n3.d2 = u2, this.updateControlPointsFromDistances(e37), n3.d1 = Math.max(c3, Math.min(l3, d2 + t4)), n3.d2 = Math.max(c3, Math.min(l3, u2 - t4)), this.updateControlPointsFromDistances(e37), this.updateSingleTraceSample(e37);
          const p3 = this.computeCostForTrace(e37);
          p3 < r4 && (r4 = p3, a4 = n3.d1, h3 = n3.d2), n3.d1 = d2, n3.d2 = u2, this.updateControlPointsFromDistances(e37);
        }
        if (n3.d1 = a4, n3.d2 = h3, this.updateControlPointsFromDistances(e37), this.updateSingleTraceSample(e37), r4 < 0.9 * t3)
          break;
      }
    }
    this.optimizationStep % 10 == 0 && this.updateCollisionPairs();
  }
  buildOutputTraces() {
    this.outputTraces = this.traces.map((e36) => ({ waypointPair: e36.waypointPair, points: G$(e36.waypointPair.start, e36.ctrl1, e36.ctrl2, e36.waypointPair.end, 20), networkId: e36.networkId }));
  }
  _step() {
    if (this.traces.length === 0 && (this.effectiveTraceToTraceSpacing = 3 * this.problem.preferredTraceToTraceSpacing, this.initializeTraces(), this.lastCost = this.computeTotalCost(), this.stagnantSteps = 0), this.optimizationStep < this.maxOptimizationSteps) {
      const e36 = 3, t2 = e36 + (1 - e36) * (this.optimizationStep / this.maxOptimizationSteps);
      if (this.effectiveTraceToTraceSpacing = this.problem.preferredTraceToTraceSpacing * t2, this.optimizeStep(), this.optimizationStep++, this.optimizationStep % 10 == 0) {
        this.resolveIntersections() > 0 && this.updateCollisionPairs();
      }
      const n2 = this.computeTotalCost();
      if (n2 === 0)
        this.optimizationStep = this.maxOptimizationSteps;
      else if (n2 >= 0.99 * this.lastCost) {
        if (this.stagnantSteps++, this.stagnantSteps > 10) {
          this.resolveIntersections() > 0 ? (this.updateCollisionPairs(), this.stagnantSteps = 0) : this.stagnantSteps > 15 && (this.optimizationStep = this.maxOptimizationSteps);
        }
      } else
        this.stagnantSteps = 0;
      this.lastCost = n2;
    }
    this.optimizationStep >= this.maxOptimizationSteps && (this.resolveIntersections(), this.buildOutputTraces(), this.solved = true);
  }
  visualize() {
    return this.traces.length > 0 && this.buildOutputTraces(), ((e36, t2 = []) => {
      const n2 = { arrows: [], circles: [], lines: [], rects: [], coordinateSystem: "cartesian", points: [], texts: [], title: "Curvy Trace Problem" };
      n2.lines.push({ points: [{ x: e36.bounds.minX, y: e36.bounds.minY }, { x: e36.bounds.maxX, y: e36.bounds.minY }, { x: e36.bounds.maxX, y: e36.bounds.maxY }, { x: e36.bounds.minX, y: e36.bounds.maxY }, { x: e36.bounds.minX, y: e36.bounds.minY }], strokeColor: "rgba(0, 0, 0, 0.1)" });
      for (const t3 of e36.waypointPairs)
        n2.points.push({ ...t3.start, label: `start ${t3.networkId ?? ""}`, color: Y$(t3.networkId) }), n2.points.push({ ...t3.end, label: `end ${t3.networkId ?? ""}`, color: Y$(t3.networkId) });
      for (const t3 of e36.obstacles)
        n2.rects.push({ center: t3.center, width: t3.maxX - t3.minX, height: t3.maxY - t3.minY, fill: "rgba(128, 128, 128, 0.3)", stroke: "rgba(128, 128, 128, 0.8)", label: `netId: ${t3.networkId}` });
      for (const e37 of t2)
        n2.lines.push({ points: e37.points, strokeColor: Y$(e37.networkId) });
      return n2;
    })(this.problem, this.outputTraces);
  }
};
var eY = class extends ni {
  getSolverName() {
    return "CurvyIntraNodeSolver";
  }
  nodeWithPortPoints;
  colorMap;
  traceWidth;
  viaDiameter;
  adjacentObstacles;
  routes = [];
  curvyTraceSolver;
  phase = "initializing";
  constructor(e36) {
    super(), this.nodeWithPortPoints = e36.nodeWithPortPoints, this.colorMap = e36.colorMap ?? {}, this.traceWidth = e36.traceWidth ?? 0.15, this.viaDiameter = e36.viaDiameter ?? 0.3, this.adjacentObstacles = e36.adjacentObstacles ?? [], this.MAX_ITERATIONS = 1000;
  }
  _step() {
    switch (this.phase) {
      case "initializing":
        this._initializeCurvySolver();
        break;
      case "solving":
        this._stepCurvySolver();
        break;
      case "done":
        this.solved = true;
    }
  }
  _initializeCurvySolver() {
    const e36 = this.nodeWithPortPoints, t2 = { minX: e36.center.x - e36.width / 2, minY: e36.center.y - e36.height / 2, maxX: e36.center.x + e36.width / 2, maxY: e36.center.y + e36.height / 2 }, n2 = new Map;
    for (const t3 of e36.portPoints)
      n2.has(t3.connectionName) || n2.set(t3.connectionName, []), n2.get(t3.connectionName).push(t3);
    const o3 = [];
    for (const [e37, t3] of n2) {
      if (t3.length < 2)
        continue;
      const n3 = t3[0], i4 = t3[t3.length - 1];
      o3.push({ start: { x: n3.x, y: n3.y }, end: { x: i4.x, y: i4.y }, networkId: e37 });
    }
    if (o3.length === 0)
      return void (this.phase = "done");
    const i3 = { bounds: t2, waypointPairs: o3, obstacles: this.adjacentObstacles.map((e37) => ({ minX: e37.minX, minY: e37.minY, maxX: e37.maxX, maxY: e37.maxY, center: { x: (e37.minX + e37.maxX) / 2, y: (e37.minY + e37.maxY) / 2 }, networkId: e37.networkId })), preferredTraceToTraceSpacing: 2 * this.traceWidth, preferredObstacleToTraceSpacing: 2 * this.traceWidth };
    this.curvyTraceSolver = new K$(i3), this.phase = "solving";
  }
  _stepCurvySolver() {
    this.curvyTraceSolver ? (this.activeSubSolver = this.curvyTraceSolver, this.curvyTraceSolver.step(), this.curvyTraceSolver.solved ? (this._convertOutputTraces(), this.phase = "done") : this.curvyTraceSolver.failed && (this.error = this.curvyTraceSolver.error, this.failed = true)) : this.phase = "done";
  }
  _convertOutputTraces() {
    if (!this.curvyTraceSolver)
      return;
    const e36 = this.nodeWithPortPoints, t2 = new Map;
    for (const n2 of e36.portPoints) {
      const e37 = n2.connectionName;
      t2.has(e37) || t2.set(e37, { connectionName: n2.connectionName, rootConnectionName: n2.rootConnectionName, z: n2.z });
    }
    for (const e37 of this.curvyTraceSolver.outputTraces) {
      const n2 = e37.networkId ?? "", o3 = t2.get(n2);
      if (!o3)
        continue;
      const i3 = { connectionName: o3.connectionName, rootConnectionName: o3.rootConnectionName, traceThickness: this.traceWidth, viaDiameter: this.viaDiameter, route: e37.points.map((e38) => ({ x: e38.x, y: e38.y, z: o3.z })), vias: [] };
      this.routes.push(i3);
    }
  }
  getConstructorParams() {
    return { nodeWithPortPoints: this.nodeWithPortPoints, colorMap: this.colorMap, traceWidth: this.traceWidth, viaDiameter: this.viaDiameter, adjacentObstacles: this.adjacentObstacles };
  }
  visualize() {
    const e36 = { lines: [], points: [], rects: [], circles: [] }, t2 = this.nodeWithPortPoints;
    e36.rects.push({ center: t2.center, width: t2.width, height: t2.height, fill: "rgba(0, 200, 0, 0.1)", stroke: "rgba(0, 200, 0, 0.5)", label: t2.capacityMeshNodeId });
    for (const t3 of this.adjacentObstacles)
      e36.rects.push({ center: { x: (t3.minX + t3.maxX) / 2, y: (t3.minY + t3.maxY) / 2 }, width: t3.maxX - t3.minX, height: t3.maxY - t3.minY, fill: "rgba(255, 0, 0, 0.1)", stroke: "rgba(255, 0, 0, 0.3)", label: `obstacle: ${t3.networkId ?? ""}` });
    if (this.curvyTraceSolver) {
      const t3 = this.curvyTraceSolver.visualize();
      t3.lines && e36.lines.push(...t3.lines), t3.points && e36.points.push(...t3.points), t3.rects && e36.rects.push(...t3.rects), t3.circles && e36.circles.push(...t3.circles);
    }
    for (const t3 of this.routes) {
      const n2 = this.colorMap[t3.connectionName] ?? "gray";
      e36.lines.push({ points: t3.route.map((e37) => ({ x: e37.x, y: e37.y })), strokeColor: n2, strokeWidth: this.traceWidth, label: t3.connectionName });
    }
    for (const n2 of t2.portPoints) {
      const t3 = this.colorMap[n2.connectionName] ?? "gray";
      e36.points.push({ x: n2.x, y: n2.y, color: t3, label: n2.connectionName });
    }
    return e36;
  }
};
var iY = Object.create;
var rY = Object.defineProperty;
var sY = Object.getOwnPropertyDescriptor;
var aY = Object.getOwnPropertyNames;
var cY = Object.getPrototypeOf;
var lY = Object.prototype.hasOwnProperty;
var hY = (e36, t2) => function() {
  return t2 || (0, e36[aY(e36)[0]])((t2 = { exports: {} }).exports, t2), t2.exports;
};
var dY = hY({ "node_modules/binary-search-bounds/search-bounds.js"(e36, t2) {
  function n2(e37, t3, n3, o4, i4) {
    for (var r4 = i4 + 1;o4 <= i4; ) {
      var s3 = o4 + i4 >>> 1, a4 = e37[s3];
      (n3 !== undefined ? n3(a4, t3) : a4 - t3) >= 0 ? (r4 = s3, i4 = s3 - 1) : o4 = s3 + 1;
    }
    return r4;
  }
  function o3(e37, t3, n3, o4, i4) {
    for (var r4 = i4 + 1;o4 <= i4; ) {
      var s3 = o4 + i4 >>> 1, a4 = e37[s3];
      (n3 !== undefined ? n3(a4, t3) : a4 - t3) > 0 ? (r4 = s3, i4 = s3 - 1) : o4 = s3 + 1;
    }
    return r4;
  }
  function i3(e37, t3, n3, o4, i4) {
    for (var r4 = o4 - 1;o4 <= i4; ) {
      var s3 = o4 + i4 >>> 1, a4 = e37[s3];
      (n3 !== undefined ? n3(a4, t3) : a4 - t3) < 0 ? (r4 = s3, o4 = s3 + 1) : i4 = s3 - 1;
    }
    return r4;
  }
  function r3(e37, t3, n3, o4, i4) {
    for (var r4 = o4 - 1;o4 <= i4; ) {
      var s3 = o4 + i4 >>> 1, a4 = e37[s3];
      (n3 !== undefined ? n3(a4, t3) : a4 - t3) <= 0 ? (r4 = s3, o4 = s3 + 1) : i4 = s3 - 1;
    }
    return r4;
  }
  function s2(e37, t3, n3, o4, i4) {
    for (;o4 <= i4; ) {
      var r4 = o4 + i4 >>> 1, s3 = e37[r4], a4 = n3 !== undefined ? n3(s3, t3) : s3 - t3;
      if (a4 === 0)
        return r4;
      a4 <= 0 ? o4 = r4 + 1 : i4 = r4 - 1;
    }
    return -1;
  }
  function a3(e37, t3, n3, o4, i4, r4) {
    return typeof n3 == "function" ? r4(e37, t3, n3, o4 === undefined ? 0 : 0 | o4, i4 === undefined ? e37.length - 1 : 0 | i4) : r4(e37, t3, undefined, n3 === undefined ? 0 : 0 | n3, o4 === undefined ? e37.length - 1 : 0 | o4);
  }
  t2.exports = { ge: function(e37, t3, o4, i4, r4) {
    return a3(e37, t3, o4, i4, r4, n2);
  }, gt: function(e37, t3, n3, i4, r4) {
    return a3(e37, t3, n3, i4, r4, o3);
  }, lt: function(e37, t3, n3, o4, r4) {
    return a3(e37, t3, n3, o4, r4, i3);
  }, le: function(e37, t3, n3, o4, i4) {
    return a3(e37, t3, n3, o4, i4, r3);
  }, eq: function(e37, t3, n3, o4, i4) {
    return a3(e37, t3, n3, o4, i4, s2);
  } };
} });
var uY = hY({ "node_modules/two-product/two-product.js"(e36, t2) {
  t2.exports = function(e37, t3, o3) {
    var i3 = e37 * t3, r3 = n2 * e37, s2 = r3 - (r3 - e37), a3 = e37 - s2, c3 = n2 * t3, l3 = c3 - (c3 - t3), h2 = t3 - l3, d2 = a3 * h2 - (i3 - s2 * l3 - a3 * l3 - s2 * h2);
    if (o3)
      return o3[0] = d2, o3[1] = i3, o3;
    return [d2, i3];
  };
  var n2 = +(Math.pow(2, 27) + 1);
} });
var pY = hY({ "node_modules/robust-sum/robust-sum.js"(e36, t2) {
  t2.exports = function(e37, t3) {
    var n2 = 0 | e37.length, o3 = 0 | t3.length;
    if (n2 === 1 && o3 === 1)
      return function(e38, t4) {
        var n3 = e38 + t4, o4 = n3 - e38, i4 = n3 - o4, r4 = t4 - o4, s3 = e38 - i4, a4 = s3 + r4;
        if (a4)
          return [a4, n3];
        return [n3];
      }(e37[0], t3[0]);
    var i3, r3, s2 = new Array(n2 + o3), a3 = 0, c3 = 0, l3 = 0, h2 = Math.abs, d2 = e37[c3], u2 = h2(d2), p3 = t3[l3], m2 = h2(p3);
    u2 < m2 ? (r3 = d2, (c3 += 1) < n2 && (u2 = h2(d2 = e37[c3]))) : (r3 = p3, (l3 += 1) < o3 && (m2 = h2(p3 = t3[l3])));
    c3 < n2 && u2 < m2 || l3 >= o3 ? (i3 = d2, (c3 += 1) < n2 && (u2 = h2(d2 = e37[c3]))) : (i3 = p3, (l3 += 1) < o3 && (m2 = h2(p3 = t3[l3])));
    var g2, f2, _2 = i3 + r3, y2 = _2 - i3, b2 = r3 - y2, x2 = b2, v2 = _2;
    for (;c3 < n2 && l3 < o3; )
      u2 < m2 ? (i3 = d2, (c3 += 1) < n2 && (u2 = h2(d2 = e37[c3]))) : (i3 = p3, (l3 += 1) < o3 && (m2 = h2(p3 = t3[l3]))), (b2 = (r3 = x2) - (y2 = (_2 = i3 + r3) - i3)) && (s2[a3++] = b2), x2 = v2 - ((g2 = v2 + _2) - (f2 = g2 - v2)) + (_2 - f2), v2 = g2;
    for (;c3 < n2; )
      (b2 = (r3 = x2) - (y2 = (_2 = (i3 = d2) + r3) - i3)) && (s2[a3++] = b2), x2 = v2 - ((g2 = v2 + _2) - (f2 = g2 - v2)) + (_2 - f2), v2 = g2, (c3 += 1) < n2 && (d2 = e37[c3]);
    for (;l3 < o3; )
      (b2 = (r3 = x2) - (y2 = (_2 = (i3 = p3) + r3) - i3)) && (s2[a3++] = b2), x2 = v2 - ((g2 = v2 + _2) - (f2 = g2 - v2)) + (_2 - f2), v2 = g2, (l3 += 1) < o3 && (p3 = t3[l3]);
    x2 && (s2[a3++] = x2);
    v2 && (s2[a3++] = v2);
    a3 || (s2[a3++] = 0);
    return s2.length = a3, s2;
  };
} });
var mY = hY({ "node_modules/two-sum/two-sum.js"(e36, t2) {
  t2.exports = function(e37, t3, n2) {
    var o3 = e37 + t3, i3 = o3 - e37, r3 = t3 - i3, s2 = e37 - (o3 - i3);
    if (n2)
      return n2[0] = s2 + r3, n2[1] = o3, n2;
    return [s2 + r3, o3];
  };
} });
var gY = hY({ "node_modules/robust-scale/robust-scale.js"(e36, t2) {
  var n2 = uY(), o3 = mY();
  t2.exports = function(e37, t3) {
    var i3 = e37.length;
    if (i3 === 1) {
      var r3 = n2(e37[0], t3);
      return r3[0] ? r3 : [r3[1]];
    }
    var s2 = new Array(2 * i3), a3 = [0.1, 0.1], c3 = [0.1, 0.1], l3 = 0;
    n2(e37[0], t3, a3), a3[0] && (s2[l3++] = a3[0]);
    for (var h2 = 1;h2 < i3; ++h2) {
      n2(e37[h2], t3, c3);
      var d2 = a3[1];
      o3(d2, c3[0], a3), a3[0] && (s2[l3++] = a3[0]);
      var u2 = c3[1], p3 = a3[1], m2 = u2 + p3, g2 = p3 - (m2 - u2);
      a3[1] = m2, g2 && (s2[l3++] = g2);
    }
    a3[1] && (s2[l3++] = a3[1]);
    l3 === 0 && (s2[l3++] = 0);
    return s2.length = l3, s2;
  };
} });
var fY = hY({ "node_modules/robust-subtract/robust-diff.js"(e36, t2) {
  t2.exports = function(e37, t3) {
    var n2 = 0 | e37.length, o3 = 0 | t3.length;
    if (n2 === 1 && o3 === 1)
      return function(e38, t4) {
        var n3 = e38 + t4, o4 = n3 - e38, i4 = n3 - o4, r4 = t4 - o4, s3 = e38 - i4, a4 = s3 + r4;
        if (a4)
          return [a4, n3];
        return [n3];
      }(e37[0], -t3[0]);
    var i3, r3, s2 = new Array(n2 + o3), a3 = 0, c3 = 0, l3 = 0, h2 = Math.abs, d2 = e37[c3], u2 = h2(d2), p3 = -t3[l3], m2 = h2(p3);
    u2 < m2 ? (r3 = d2, (c3 += 1) < n2 && (u2 = h2(d2 = e37[c3]))) : (r3 = p3, (l3 += 1) < o3 && (m2 = h2(p3 = -t3[l3])));
    c3 < n2 && u2 < m2 || l3 >= o3 ? (i3 = d2, (c3 += 1) < n2 && (u2 = h2(d2 = e37[c3]))) : (i3 = p3, (l3 += 1) < o3 && (m2 = h2(p3 = -t3[l3])));
    var g2, f2, _2 = i3 + r3, y2 = _2 - i3, b2 = r3 - y2, x2 = b2, v2 = _2;
    for (;c3 < n2 && l3 < o3; )
      u2 < m2 ? (i3 = d2, (c3 += 1) < n2 && (u2 = h2(d2 = e37[c3]))) : (i3 = p3, (l3 += 1) < o3 && (m2 = h2(p3 = -t3[l3]))), (b2 = (r3 = x2) - (y2 = (_2 = i3 + r3) - i3)) && (s2[a3++] = b2), x2 = v2 - ((g2 = v2 + _2) - (f2 = g2 - v2)) + (_2 - f2), v2 = g2;
    for (;c3 < n2; )
      (b2 = (r3 = x2) - (y2 = (_2 = (i3 = d2) + r3) - i3)) && (s2[a3++] = b2), x2 = v2 - ((g2 = v2 + _2) - (f2 = g2 - v2)) + (_2 - f2), v2 = g2, (c3 += 1) < n2 && (d2 = e37[c3]);
    for (;l3 < o3; )
      (b2 = (r3 = x2) - (y2 = (_2 = (i3 = p3) + r3) - i3)) && (s2[a3++] = b2), x2 = v2 - ((g2 = v2 + _2) - (f2 = g2 - v2)) + (_2 - f2), v2 = g2, (l3 += 1) < o3 && (p3 = -t3[l3]);
    x2 && (s2[a3++] = x2);
    v2 && (s2[a3++] = v2);
    a3 || (s2[a3++] = 0);
    return s2.length = a3, s2;
  };
} });
var _Y = hY({ "node_modules/robust-orientation/orientation.js"(e36, t2) {
  var n2 = uY(), o3 = pY(), i3 = gY(), r3 = fY();
  function s2(e37, t3, n3, o4) {
    return function(n4, i4, r4) {
      var s3 = e37(e37(t3(i4[1], r4[0]), t3(-r4[1], i4[0])), e37(t3(n4[1], i4[0]), t3(-i4[1], n4[0]))), a4 = e37(t3(n4[1], r4[0]), t3(-r4[1], n4[0])), c4 = o4(s3, a4);
      return c4[c4.length - 1];
    };
  }
  function a3(e37, t3, n3, o4) {
    return function(i4, r4, s3, a4) {
      var c4 = e37(e37(n3(e37(t3(s3[1], a4[0]), t3(-a4[1], s3[0])), r4[2]), e37(n3(e37(t3(r4[1], a4[0]), t3(-a4[1], r4[0])), -s3[2]), n3(e37(t3(r4[1], s3[0]), t3(-s3[1], r4[0])), a4[2]))), e37(n3(e37(t3(r4[1], a4[0]), t3(-a4[1], r4[0])), i4[2]), e37(n3(e37(t3(i4[1], a4[0]), t3(-a4[1], i4[0])), -r4[2]), n3(e37(t3(i4[1], r4[0]), t3(-r4[1], i4[0])), a4[2])))), l4 = e37(e37(n3(e37(t3(s3[1], a4[0]), t3(-a4[1], s3[0])), i4[2]), e37(n3(e37(t3(i4[1], a4[0]), t3(-a4[1], i4[0])), -s3[2]), n3(e37(t3(i4[1], s3[0]), t3(-s3[1], i4[0])), a4[2]))), e37(n3(e37(t3(r4[1], s3[0]), t3(-s3[1], r4[0])), i4[2]), e37(n3(e37(t3(i4[1], s3[0]), t3(-s3[1], i4[0])), -r4[2]), n3(e37(t3(i4[1], r4[0]), t3(-r4[1], i4[0])), s3[2])))), h3 = o4(c4, l4);
      return h3[h3.length - 1];
    };
  }
  function c3(e37, t3, n3, o4) {
    return function(i4, r4, s3, a4, c4) {
      var l4 = e37(e37(e37(n3(e37(n3(e37(t3(a4[1], c4[0]), t3(-c4[1], a4[0])), s3[2]), e37(n3(e37(t3(s3[1], c4[0]), t3(-c4[1], s3[0])), -a4[2]), n3(e37(t3(s3[1], a4[0]), t3(-a4[1], s3[0])), c4[2]))), r4[3]), e37(n3(e37(n3(e37(t3(a4[1], c4[0]), t3(-c4[1], a4[0])), r4[2]), e37(n3(e37(t3(r4[1], c4[0]), t3(-c4[1], r4[0])), -a4[2]), n3(e37(t3(r4[1], a4[0]), t3(-a4[1], r4[0])), c4[2]))), -s3[3]), n3(e37(n3(e37(t3(s3[1], c4[0]), t3(-c4[1], s3[0])), r4[2]), e37(n3(e37(t3(r4[1], c4[0]), t3(-c4[1], r4[0])), -s3[2]), n3(e37(t3(r4[1], s3[0]), t3(-s3[1], r4[0])), c4[2]))), a4[3]))), e37(n3(e37(n3(e37(t3(s3[1], a4[0]), t3(-a4[1], s3[0])), r4[2]), e37(n3(e37(t3(r4[1], a4[0]), t3(-a4[1], r4[0])), -s3[2]), n3(e37(t3(r4[1], s3[0]), t3(-s3[1], r4[0])), a4[2]))), -c4[3]), e37(n3(e37(n3(e37(t3(a4[1], c4[0]), t3(-c4[1], a4[0])), r4[2]), e37(n3(e37(t3(r4[1], c4[0]), t3(-c4[1], r4[0])), -a4[2]), n3(e37(t3(r4[1], a4[0]), t3(-a4[1], r4[0])), c4[2]))), i4[3]), n3(e37(n3(e37(t3(a4[1], c4[0]), t3(-c4[1], a4[0])), i4[2]), e37(n3(e37(t3(i4[1], c4[0]), t3(-c4[1], i4[0])), -a4[2]), n3(e37(t3(i4[1], a4[0]), t3(-a4[1], i4[0])), c4[2]))), -r4[3])))), e37(e37(n3(e37(n3(e37(t3(r4[1], c4[0]), t3(-c4[1], r4[0])), i4[2]), e37(n3(e37(t3(i4[1], c4[0]), t3(-c4[1], i4[0])), -r4[2]), n3(e37(t3(i4[1], r4[0]), t3(-r4[1], i4[0])), c4[2]))), a4[3]), e37(n3(e37(n3(e37(t3(r4[1], a4[0]), t3(-a4[1], r4[0])), i4[2]), e37(n3(e37(t3(i4[1], a4[0]), t3(-a4[1], i4[0])), -r4[2]), n3(e37(t3(i4[1], r4[0]), t3(-r4[1], i4[0])), a4[2]))), -c4[3]), n3(e37(n3(e37(t3(s3[1], a4[0]), t3(-a4[1], s3[0])), r4[2]), e37(n3(e37(t3(r4[1], a4[0]), t3(-a4[1], r4[0])), -s3[2]), n3(e37(t3(r4[1], s3[0]), t3(-s3[1], r4[0])), a4[2]))), i4[3]))), e37(n3(e37(n3(e37(t3(s3[1], a4[0]), t3(-a4[1], s3[0])), i4[2]), e37(n3(e37(t3(i4[1], a4[0]), t3(-a4[1], i4[0])), -s3[2]), n3(e37(t3(i4[1], s3[0]), t3(-s3[1], i4[0])), a4[2]))), -r4[3]), e37(n3(e37(n3(e37(t3(r4[1], a4[0]), t3(-a4[1], r4[0])), i4[2]), e37(n3(e37(t3(i4[1], a4[0]), t3(-a4[1], i4[0])), -r4[2]), n3(e37(t3(i4[1], r4[0]), t3(-r4[1], i4[0])), a4[2]))), s3[3]), n3(e37(n3(e37(t3(r4[1], s3[0]), t3(-s3[1], r4[0])), i4[2]), e37(n3(e37(t3(i4[1], s3[0]), t3(-s3[1], i4[0])), -r4[2]), n3(e37(t3(i4[1], r4[0]), t3(-r4[1], i4[0])), s3[2]))), -a4[3]))))), h3 = e37(e37(e37(n3(e37(n3(e37(t3(a4[1], c4[0]), t3(-c4[1], a4[0])), s3[2]), e37(n3(e37(t3(s3[1], c4[0]), t3(-c4[1], s3[0])), -a4[2]), n3(e37(t3(s3[1], a4[0]), t3(-a4[1], s3[0])), c4[2]))), i4[3]), n3(e37(n3(e37(t3(a4[1], c4[0]), t3(-c4[1], a4[0])), i4[2]), e37(n3(e37(t3(i4[1], c4[0]), t3(-c4[1], i4[0])), -a4[2]), n3(e37(t3(i4[1], a4[0]), t3(-a4[1], i4[0])), c4[2]))), -s3[3])), e37(n3(e37(n3(e37(t3(s3[1], c4[0]), t3(-c4[1], s3[0])), i4[2]), e37(n3(e37(t3(i4[1], c4[0]), t3(-c4[1], i4[0])), -s3[2]), n3(e37(t3(i4[1], s3[0]), t3(-s3[1], i4[0])), c4[2]))), a4[3]), n3(e37(n3(e37(t3(s3[1], a4[0]), t3(-a4[1], s3[0])), i4[2]), e37(n3(e37(t3(i4[1], a4[0]), t3(-a4[1], i4[0])), -s3[2]), n3(e37(t3(i4[1], s3[0]), t3(-s3[1], i4[0])), a4[2]))), -c4[3]))), e37(e37(n3(e37(n3(e37(t3(s3[1], c4[0]), t3(-c4[1], s3[0])), r4[2]), e37(n3(e37(t3(r4[1], c4[0]), t3(-c4[1], r4[0])), -s3[2]), n3(e37(t3(r4[1], s3[0]), t3(-s3[1], r4[0])), c4[2]))), i4[3]), n3(e37(n3(e37(t3(s3[1], c4[0]), t3(-c4[1], s3[0])), i4[2]), e37(n3(e37(t3(i4[1], c4[0]), t3(-c4[1], i4[0])), -s3[2]), n3(e37(t3(i4[1], s3[0]), t3(-s3[1], i4[0])), c4[2]))), -r4[3])), e37(n3(e37(n3(e37(t3(r4[1], c4[0]), t3(-c4[1], r4[0])), i4[2]), e37(n3(e37(t3(i4[1], c4[0]), t3(-c4[1], i4[0])), -r4[2]), n3(e37(t3(i4[1], r4[0]), t3(-r4[1], i4[0])), c4[2]))), s3[3]), n3(e37(n3(e37(t3(r4[1], s3[0]), t3(-s3[1], r4[0])), i4[2]), e37(n3(e37(t3(i4[1], s3[0]), t3(-s3[1], i4[0])), -r4[2]), n3(e37(t3(i4[1], r4[0]), t3(-r4[1], i4[0])), s3[2]))), -c4[3])))), d3 = o4(l4, h3);
      return d3[d3.length - 1];
    };
  }
  function l3(e37) {
    return (e37 === 3 ? s2 : e37 === 4 ? a3 : c3)(o3, n2, i3, r3);
  }
  var h2 = l3(3), d2 = l3(4), u2 = [function() {
    return 0;
  }, function() {
    return 0;
  }, function(e37, t3) {
    return t3[0] - e37[0];
  }, function(e37, t3, n3) {
    var o4, i4 = (e37[1] - n3[1]) * (t3[0] - n3[0]), r4 = (e37[0] - n3[0]) * (t3[1] - n3[1]), s3 = i4 - r4;
    if (i4 > 0) {
      if (r4 <= 0)
        return s3;
      o4 = i4 + r4;
    } else {
      if (!(i4 < 0))
        return s3;
      if (r4 >= 0)
        return s3;
      o4 = -(i4 + r4);
    }
    var a4 = 0.00000000000000033306690738754716 * o4;
    return s3 >= a4 || s3 <= -a4 ? s3 : h2(e37, t3, n3);
  }, function(e37, t3, n3, o4) {
    var i4 = e37[0] - o4[0], r4 = t3[0] - o4[0], s3 = n3[0] - o4[0], a4 = e37[1] - o4[1], c4 = t3[1] - o4[1], l4 = n3[1] - o4[1], h3 = e37[2] - o4[2], u3 = t3[2] - o4[2], p4 = n3[2] - o4[2], m3 = r4 * l4, g2 = s3 * c4, f2 = s3 * a4, _2 = i4 * l4, y2 = i4 * c4, b2 = r4 * a4, x2 = h3 * (m3 - g2) + u3 * (f2 - _2) + p4 * (y2 - b2), v2 = 0.0000000000000007771561172376103 * ((Math.abs(m3) + Math.abs(g2)) * Math.abs(h3) + (Math.abs(f2) + Math.abs(_2)) * Math.abs(u3) + (Math.abs(y2) + Math.abs(b2)) * Math.abs(p4));
    return x2 > v2 || -x2 > v2 ? x2 : d2(e37, t3, n3, o4);
  }];
  function p3(e37) {
    var t3 = u2[e37.length];
    return t3 || (t3 = u2[e37.length] = l3(e37.length)), t3.apply(undefined, e37);
  }
  function m2(e37, t3, n3, o4, i4, r4, s3) {
    return function(t4, n4, a4, c4, l4) {
      switch (arguments.length) {
        case 0:
        case 1:
          return 0;
        case 2:
          return o4(t4, n4);
        case 3:
          return i4(t4, n4, a4);
        case 4:
          return r4(t4, n4, a4, c4);
        case 5:
          return s3(t4, n4, a4, c4, l4);
      }
      for (var h3 = new Array(arguments.length), d3 = 0;d3 < arguments.length; ++d3)
        h3[d3] = arguments[d3];
      return e37(h3);
    };
  }
  (function() {
    for (;u2.length <= 5; )
      u2.push(l3(u2.length));
    t2.exports = m2.apply(undefined, [p3].concat(u2));
    for (var e37 = 0;e37 <= 5; ++e37)
      t2.exports[e37] = u2[e37];
  })();
} });
var yY = hY({ "node_modules/cdt2d/lib/monotone.js"(e36, t2) {
  var n2 = dY(), o3 = _Y()[3];
  function i3(e37, t3, n3, o4, i4) {
    this.a = e37, this.b = t3, this.idx = n3, this.lowerIds = o4, this.upperIds = i4;
  }
  function r3(e37, t3, n3, o4) {
    this.a = e37, this.b = t3, this.type = n3, this.idx = o4;
  }
  function s2(e37, t3) {
    var n3 = e37.a[0] - t3.a[0] || e37.a[1] - t3.a[1] || e37.type - t3.type;
    return n3 || (e37.type !== 0 && (n3 = o3(e37.a, e37.b, t3.b)) ? n3 : e37.idx - t3.idx);
  }
  function a3(e37, t3) {
    return o3(e37.a, e37.b, t3);
  }
  function c3(e37, t3, i4, r4, s3) {
    for (var c4 = n2.lt(t3, r4, a3), l4 = n2.gt(t3, r4, a3), h3 = c4;h3 < l4; ++h3) {
      for (var d3 = t3[h3], u2 = d3.lowerIds, p3 = u2.length;p3 > 1 && o3(i4[u2[p3 - 2]], i4[u2[p3 - 1]], r4) > 0; )
        e37.push([u2[p3 - 1], u2[p3 - 2], s3]), p3 -= 1;
      u2.length = p3, u2.push(s3);
      var m2 = d3.upperIds;
      for (p3 = m2.length;p3 > 1 && o3(i4[m2[p3 - 2]], i4[m2[p3 - 1]], r4) < 0; )
        e37.push([m2[p3 - 2], m2[p3 - 1], s3]), p3 -= 1;
      m2.length = p3, m2.push(s3);
    }
  }
  function l3(e37, t3) {
    var n3;
    return (n3 = e37.a[0] < t3.a[0] ? o3(e37.a, e37.b, t3.a) : o3(t3.b, t3.a, e37.a)) ? n3 : (n3 = t3.b[0] < e37.b[0] ? o3(e37.a, e37.b, t3.b) : o3(t3.b, t3.a, e37.b)) || e37.idx - t3.idx;
  }
  function h2(e37, t3, o4) {
    var r4 = n2.le(e37, o4, l3), s3 = e37[r4], a4 = s3.upperIds, c4 = a4[a4.length - 1];
    s3.upperIds = [c4], e37.splice(r4 + 1, 0, new i3(o4.a, o4.b, o4.idx, [c4], a4));
  }
  function d2(e37, t3, o4) {
    var i4 = o4.a;
    o4.a = o4.b, o4.b = i4;
    var r4 = n2.eq(e37, o4, l3), s3 = e37[r4];
    e37[r4 - 1].upperIds = s3.upperIds, e37.splice(r4, 1);
  }
  t2.exports = function(e37, t3) {
    for (var n3 = e37.length, o4 = t3.length, a4 = [], l4 = 0;l4 < n3; ++l4)
      a4.push(new r3(e37[l4], null, 0, l4));
    for (l4 = 0;l4 < o4; ++l4) {
      var u2 = t3[l4], p3 = e37[u2[0]], m2 = e37[u2[1]];
      p3[0] < m2[0] ? a4.push(new r3(p3, m2, 2, l4), new r3(m2, p3, 1, l4)) : p3[0] > m2[0] && a4.push(new r3(m2, p3, 2, l4), new r3(p3, m2, 1, l4));
    }
    a4.sort(s2);
    for (var g2 = a4[0].a[0] - (1 + Math.abs(a4[0].a[0])) * Math.pow(2, -52), f2 = [new i3([g2, 1], [g2, 0], -1, [], [], [], [])], _2 = [], y2 = (l4 = 0, a4.length);l4 < y2; ++l4) {
      var b2 = a4[l4], x2 = b2.type;
      x2 === 0 ? c3(_2, f2, e37, b2.a, b2.idx) : x2 === 2 ? h2(f2, e37, b2) : d2(f2, e37, b2);
    }
    return _2;
  };
} });
var bY = hY({ "node_modules/cdt2d/lib/triangulation.js"(e36, t2) {
  var n2 = dY();
  function o3(e37, t3) {
    this.stars = e37, this.edges = t3;
  }
  t2.exports = function(e37, t3) {
    for (var n3 = new Array(e37), i4 = 0;i4 < e37; ++i4)
      n3[i4] = [];
    return new o3(n3, t3);
  };
  var i3 = o3.prototype;
  function r3(e37, t3, n3) {
    for (var o4 = 1, i4 = e37.length;o4 < i4; o4 += 2)
      if (e37[o4 - 1] === t3 && e37[o4] === n3)
        return e37[o4 - 1] = e37[i4 - 2], e37[o4] = e37[i4 - 1], void (e37.length = i4 - 2);
  }
  i3.isConstraint = function() {
    var e37 = [0, 0];
    function t3(e38, t4) {
      return e38[0] - t4[0] || e38[1] - t4[1];
    }
    return function(o4, i4) {
      return e37[0] = Math.min(o4, i4), e37[1] = Math.max(o4, i4), n2.eq(this.edges, e37, t3) >= 0;
    };
  }(), i3.removeTriangle = function(e37, t3, n3) {
    var o4 = this.stars;
    r3(o4[e37], t3, n3), r3(o4[t3], n3, e37), r3(o4[n3], e37, t3);
  }, i3.addTriangle = function(e37, t3, n3) {
    var o4 = this.stars;
    o4[e37].push(t3, n3), o4[t3].push(n3, e37), o4[n3].push(e37, t3);
  }, i3.opposite = function(e37, t3) {
    for (var n3 = this.stars[t3], o4 = 1, i4 = n3.length;o4 < i4; o4 += 2)
      if (n3[o4] === e37)
        return n3[o4 - 1];
    return -1;
  }, i3.flip = function(e37, t3) {
    var n3 = this.opposite(e37, t3), o4 = this.opposite(t3, e37);
    this.removeTriangle(e37, t3, n3), this.removeTriangle(t3, e37, o4), this.addTriangle(e37, o4, n3), this.addTriangle(t3, n3, o4);
  }, i3.edges = function() {
    for (var e37 = this.stars, t3 = [], n3 = 0, o4 = e37.length;n3 < o4; ++n3)
      for (var i4 = e37[n3], r4 = 0, s2 = i4.length;r4 < s2; r4 += 2)
        t3.push([i4[r4], i4[r4 + 1]]);
    return t3;
  }, i3.cells = function() {
    for (var e37 = this.stars, t3 = [], n3 = 0, o4 = e37.length;n3 < o4; ++n3)
      for (var i4 = e37[n3], r4 = 0, s2 = i4.length;r4 < s2; r4 += 2) {
        var a3 = i4[r4], c3 = i4[r4 + 1];
        n3 < Math.min(a3, c3) && t3.push([n3, a3, c3]);
      }
    return t3;
  };
} });
var xY = hY({ "node_modules/robust-in-sphere/in-sphere.js"(e36, t2) {
  var n2 = uY(), o3 = pY(), i3 = fY(), r3 = gY();
  function s2(e37) {
    return (e37 === 3 ? a3 : e37 === 4 ? c3 : e37 === 5 ? l3 : h2)(o3, i3, n2, r3);
  }
  function a3(e37, t3, n3, o4) {
    return function(i4, r4, s3) {
      var a4 = n3(i4[0], i4[0]), c4 = o4(a4, r4[0]), l4 = o4(a4, s3[0]), h3 = n3(r4[0], r4[0]), d3 = o4(h3, i4[0]), u3 = o4(h3, s3[0]), p4 = n3(s3[0], s3[0]), m2 = o4(p4, i4[0]), g2 = o4(p4, r4[0]), f2 = e37(t3(g2, u3), t3(d3, c4)), _2 = t3(m2, l4), y2 = t3(f2, _2);
      return y2[y2.length - 1];
    };
  }
  function c3(e37, t3, n3, o4) {
    return function(i4, r4, s3, a4) {
      var c4 = e37(n3(i4[0], i4[0]), n3(i4[1], i4[1])), l4 = o4(c4, r4[0]), h3 = o4(c4, s3[0]), d3 = o4(c4, a4[0]), u3 = e37(n3(r4[0], r4[0]), n3(r4[1], r4[1])), p4 = o4(u3, i4[0]), m2 = o4(u3, s3[0]), g2 = o4(u3, a4[0]), f2 = e37(n3(s3[0], s3[0]), n3(s3[1], s3[1])), _2 = o4(f2, i4[0]), y2 = o4(f2, r4[0]), b2 = o4(f2, a4[0]), x2 = e37(n3(a4[0], a4[0]), n3(a4[1], a4[1])), v2 = o4(x2, i4[0]), I2 = o4(x2, r4[0]), S2 = o4(x2, s3[0]), C = e37(e37(o4(t3(S2, b2), r4[1]), e37(o4(t3(I2, g2), -s3[1]), o4(t3(y2, m2), a4[1]))), e37(o4(t3(I2, g2), i4[1]), e37(o4(t3(v2, d3), -r4[1]), o4(t3(p4, l4), a4[1])))), P = e37(e37(o4(t3(S2, b2), i4[1]), e37(o4(t3(v2, d3), -s3[1]), o4(t3(_2, h3), a4[1]))), e37(o4(t3(y2, m2), i4[1]), e37(o4(t3(_2, h3), -r4[1]), o4(t3(p4, l4), s3[1])))), M = t3(C, P);
      return M[M.length - 1];
    };
  }
  function l3(e37, t3, n3, o4) {
    return function(i4, r4, s3, a4, c4) {
      var l4 = e37(n3(i4[0], i4[0]), e37(n3(i4[1], i4[1]), n3(i4[2], i4[2]))), h3 = o4(l4, r4[0]), d3 = o4(l4, s3[0]), u3 = o4(l4, a4[0]), p4 = o4(l4, c4[0]), m2 = e37(n3(r4[0], r4[0]), e37(n3(r4[1], r4[1]), n3(r4[2], r4[2]))), g2 = o4(m2, i4[0]), f2 = o4(m2, s3[0]), _2 = o4(m2, a4[0]), y2 = o4(m2, c4[0]), b2 = e37(n3(s3[0], s3[0]), e37(n3(s3[1], s3[1]), n3(s3[2], s3[2]))), x2 = o4(b2, i4[0]), v2 = o4(b2, r4[0]), I2 = o4(b2, a4[0]), S2 = o4(b2, c4[0]), C = e37(n3(a4[0], a4[0]), e37(n3(a4[1], a4[1]), n3(a4[2], a4[2]))), P = o4(C, i4[0]), M = o4(C, r4[0]), w = o4(C, s3[0]), N = o4(C, c4[0]), R2 = e37(n3(c4[0], c4[0]), e37(n3(c4[1], c4[1]), n3(c4[2], c4[2]))), T2 = o4(R2, i4[0]), E3 = o4(R2, r4[0]), A2 = o4(R2, s3[0]), O2 = o4(R2, a4[0]), k2 = e37(e37(e37(o4(e37(o4(t3(O2, N), s3[1]), e37(o4(t3(A2, S2), -a4[1]), o4(t3(w, I2), c4[1]))), r4[2]), e37(o4(e37(o4(t3(O2, N), r4[1]), e37(o4(t3(E3, y2), -a4[1]), o4(t3(M, _2), c4[1]))), -s3[2]), o4(e37(o4(t3(A2, S2), r4[1]), e37(o4(t3(E3, y2), -s3[1]), o4(t3(v2, f2), c4[1]))), a4[2]))), e37(o4(e37(o4(t3(w, I2), r4[1]), e37(o4(t3(M, _2), -s3[1]), o4(t3(v2, f2), a4[1]))), -c4[2]), e37(o4(e37(o4(t3(O2, N), r4[1]), e37(o4(t3(E3, y2), -a4[1]), o4(t3(M, _2), c4[1]))), i4[2]), o4(e37(o4(t3(O2, N), i4[1]), e37(o4(t3(T2, p4), -a4[1]), o4(t3(P, u3), c4[1]))), -r4[2])))), e37(e37(o4(e37(o4(t3(E3, y2), i4[1]), e37(o4(t3(T2, p4), -r4[1]), o4(t3(g2, h3), c4[1]))), a4[2]), e37(o4(e37(o4(t3(M, _2), i4[1]), e37(o4(t3(P, u3), -r4[1]), o4(t3(g2, h3), a4[1]))), -c4[2]), o4(e37(o4(t3(w, I2), r4[1]), e37(o4(t3(M, _2), -s3[1]), o4(t3(v2, f2), a4[1]))), i4[2]))), e37(o4(e37(o4(t3(w, I2), i4[1]), e37(o4(t3(P, u3), -s3[1]), o4(t3(x2, d3), a4[1]))), -r4[2]), e37(o4(e37(o4(t3(M, _2), i4[1]), e37(o4(t3(P, u3), -r4[1]), o4(t3(g2, h3), a4[1]))), s3[2]), o4(e37(o4(t3(v2, f2), i4[1]), e37(o4(t3(x2, d3), -r4[1]), o4(t3(g2, h3), s3[1]))), -a4[2]))))), D2 = e37(e37(e37(o4(e37(o4(t3(O2, N), s3[1]), e37(o4(t3(A2, S2), -a4[1]), o4(t3(w, I2), c4[1]))), i4[2]), o4(e37(o4(t3(O2, N), i4[1]), e37(o4(t3(T2, p4), -a4[1]), o4(t3(P, u3), c4[1]))), -s3[2])), e37(o4(e37(o4(t3(A2, S2), i4[1]), e37(o4(t3(T2, p4), -s3[1]), o4(t3(x2, d3), c4[1]))), a4[2]), o4(e37(o4(t3(w, I2), i4[1]), e37(o4(t3(P, u3), -s3[1]), o4(t3(x2, d3), a4[1]))), -c4[2]))), e37(e37(o4(e37(o4(t3(A2, S2), r4[1]), e37(o4(t3(E3, y2), -s3[1]), o4(t3(v2, f2), c4[1]))), i4[2]), o4(e37(o4(t3(A2, S2), i4[1]), e37(o4(t3(T2, p4), -s3[1]), o4(t3(x2, d3), c4[1]))), -r4[2])), e37(o4(e37(o4(t3(E3, y2), i4[1]), e37(o4(t3(T2, p4), -r4[1]), o4(t3(g2, h3), c4[1]))), s3[2]), o4(e37(o4(t3(v2, f2), i4[1]), e37(o4(t3(x2, d3), -r4[1]), o4(t3(g2, h3), s3[1]))), -c4[2])))), L2 = t3(k2, D2);
      return L2[L2.length - 1];
    };
  }
  function h2(e37, t3, n3, o4) {
    return function(i4, r4, s3, a4, c4, l4) {
      var h3 = e37(e37(n3(i4[0], i4[0]), n3(i4[1], i4[1])), e37(n3(i4[2], i4[2]), n3(i4[3], i4[3]))), d3 = o4(h3, r4[0]), u3 = o4(h3, s3[0]), p4 = o4(h3, a4[0]), m2 = o4(h3, c4[0]), g2 = o4(h3, l4[0]), f2 = e37(e37(n3(r4[0], r4[0]), n3(r4[1], r4[1])), e37(n3(r4[2], r4[2]), n3(r4[3], r4[3]))), _2 = o4(f2, i4[0]), y2 = o4(f2, s3[0]), b2 = o4(f2, a4[0]), x2 = o4(f2, c4[0]), v2 = o4(f2, l4[0]), I2 = e37(e37(n3(s3[0], s3[0]), n3(s3[1], s3[1])), e37(n3(s3[2], s3[2]), n3(s3[3], s3[3]))), S2 = o4(I2, i4[0]), C = o4(I2, r4[0]), P = o4(I2, a4[0]), M = o4(I2, c4[0]), w = o4(I2, l4[0]), N = e37(e37(n3(a4[0], a4[0]), n3(a4[1], a4[1])), e37(n3(a4[2], a4[2]), n3(a4[3], a4[3]))), R2 = o4(N, i4[0]), T2 = o4(N, r4[0]), E3 = o4(N, s3[0]), A2 = o4(N, c4[0]), O2 = o4(N, l4[0]), k2 = e37(e37(n3(c4[0], c4[0]), n3(c4[1], c4[1])), e37(n3(c4[2], c4[2]), n3(c4[3], c4[3]))), D2 = o4(k2, i4[0]), L2 = o4(k2, r4[0]), z2 = o4(k2, s3[0]), B2 = o4(k2, a4[0]), F2 = o4(k2, l4[0]), j2 = e37(e37(n3(l4[0], l4[0]), n3(l4[1], l4[1])), e37(n3(l4[2], l4[2]), n3(l4[3], l4[3]))), $2 = o4(j2, i4[0]), Y2 = o4(j2, r4[0]), X = o4(j2, s3[0]), H2 = o4(j2, a4[0]), V2 = o4(j2, c4[0]), W2 = e37(e37(e37(o4(e37(e37(o4(e37(o4(t3(V2, F2), a4[1]), e37(o4(t3(H2, O2), -c4[1]), o4(t3(B2, A2), l4[1]))), s3[2]), o4(e37(o4(t3(V2, F2), s3[1]), e37(o4(t3(X, w), -c4[1]), o4(t3(z2, M), l4[1]))), -a4[2])), e37(o4(e37(o4(t3(H2, O2), s3[1]), e37(o4(t3(X, w), -a4[1]), o4(t3(E3, P), l4[1]))), c4[2]), o4(e37(o4(t3(B2, A2), s3[1]), e37(o4(t3(z2, M), -a4[1]), o4(t3(E3, P), c4[1]))), -l4[2]))), r4[3]), e37(o4(e37(e37(o4(e37(o4(t3(V2, F2), a4[1]), e37(o4(t3(H2, O2), -c4[1]), o4(t3(B2, A2), l4[1]))), r4[2]), o4(e37(o4(t3(V2, F2), r4[1]), e37(o4(t3(Y2, v2), -c4[1]), o4(t3(L2, x2), l4[1]))), -a4[2])), e37(o4(e37(o4(t3(H2, O2), r4[1]), e37(o4(t3(Y2, v2), -a4[1]), o4(t3(T2, b2), l4[1]))), c4[2]), o4(e37(o4(t3(B2, A2), r4[1]), e37(o4(t3(L2, x2), -a4[1]), o4(t3(T2, b2), c4[1]))), -l4[2]))), -s3[3]), o4(e37(e37(o4(e37(o4(t3(V2, F2), s3[1]), e37(o4(t3(X, w), -c4[1]), o4(t3(z2, M), l4[1]))), r4[2]), o4(e37(o4(t3(V2, F2), r4[1]), e37(o4(t3(Y2, v2), -c4[1]), o4(t3(L2, x2), l4[1]))), -s3[2])), e37(o4(e37(o4(t3(X, w), r4[1]), e37(o4(t3(Y2, v2), -s3[1]), o4(t3(C, y2), l4[1]))), c4[2]), o4(e37(o4(t3(z2, M), r4[1]), e37(o4(t3(L2, x2), -s3[1]), o4(t3(C, y2), c4[1]))), -l4[2]))), a4[3]))), e37(e37(o4(e37(e37(o4(e37(o4(t3(H2, O2), s3[1]), e37(o4(t3(X, w), -a4[1]), o4(t3(E3, P), l4[1]))), r4[2]), o4(e37(o4(t3(H2, O2), r4[1]), e37(o4(t3(Y2, v2), -a4[1]), o4(t3(T2, b2), l4[1]))), -s3[2])), e37(o4(e37(o4(t3(X, w), r4[1]), e37(o4(t3(Y2, v2), -s3[1]), o4(t3(C, y2), l4[1]))), a4[2]), o4(e37(o4(t3(E3, P), r4[1]), e37(o4(t3(T2, b2), -s3[1]), o4(t3(C, y2), a4[1]))), -l4[2]))), -c4[3]), o4(e37(e37(o4(e37(o4(t3(B2, A2), s3[1]), e37(o4(t3(z2, M), -a4[1]), o4(t3(E3, P), c4[1]))), r4[2]), o4(e37(o4(t3(B2, A2), r4[1]), e37(o4(t3(L2, x2), -a4[1]), o4(t3(T2, b2), c4[1]))), -s3[2])), e37(o4(e37(o4(t3(z2, M), r4[1]), e37(o4(t3(L2, x2), -s3[1]), o4(t3(C, y2), c4[1]))), a4[2]), o4(e37(o4(t3(E3, P), r4[1]), e37(o4(t3(T2, b2), -s3[1]), o4(t3(C, y2), a4[1]))), -c4[2]))), l4[3])), e37(o4(e37(e37(o4(e37(o4(t3(V2, F2), a4[1]), e37(o4(t3(H2, O2), -c4[1]), o4(t3(B2, A2), l4[1]))), r4[2]), o4(e37(o4(t3(V2, F2), r4[1]), e37(o4(t3(Y2, v2), -c4[1]), o4(t3(L2, x2), l4[1]))), -a4[2])), e37(o4(e37(o4(t3(H2, O2), r4[1]), e37(o4(t3(Y2, v2), -a4[1]), o4(t3(T2, b2), l4[1]))), c4[2]), o4(e37(o4(t3(B2, A2), r4[1]), e37(o4(t3(L2, x2), -a4[1]), o4(t3(T2, b2), c4[1]))), -l4[2]))), i4[3]), o4(e37(e37(o4(e37(o4(t3(V2, F2), a4[1]), e37(o4(t3(H2, O2), -c4[1]), o4(t3(B2, A2), l4[1]))), i4[2]), o4(e37(o4(t3(V2, F2), i4[1]), e37(o4(t3($2, g2), -c4[1]), o4(t3(D2, m2), l4[1]))), -a4[2])), e37(o4(e37(o4(t3(H2, O2), i4[1]), e37(o4(t3($2, g2), -a4[1]), o4(t3(R2, p4), l4[1]))), c4[2]), o4(e37(o4(t3(B2, A2), i4[1]), e37(o4(t3(D2, m2), -a4[1]), o4(t3(R2, p4), c4[1]))), -l4[2]))), -r4[3])))), e37(e37(e37(o4(e37(e37(o4(e37(o4(t3(V2, F2), r4[1]), e37(o4(t3(Y2, v2), -c4[1]), o4(t3(L2, x2), l4[1]))), i4[2]), o4(e37(o4(t3(V2, F2), i4[1]), e37(o4(t3($2, g2), -c4[1]), o4(t3(D2, m2), l4[1]))), -r4[2])), e37(o4(e37(o4(t3(Y2, v2), i4[1]), e37(o4(t3($2, g2), -r4[1]), o4(t3(_2, d3), l4[1]))), c4[2]), o4(e37(o4(t3(L2, x2), i4[1]), e37(o4(t3(D2, m2), -r4[1]), o4(t3(_2, d3), c4[1]))), -l4[2]))), a4[3]), o4(e37(e37(o4(e37(o4(t3(H2, O2), r4[1]), e37(o4(t3(Y2, v2), -a4[1]), o4(t3(T2, b2), l4[1]))), i4[2]), o4(e37(o4(t3(H2, O2), i4[1]), e37(o4(t3($2, g2), -a4[1]), o4(t3(R2, p4), l4[1]))), -r4[2])), e37(o4(e37(o4(t3(Y2, v2), i4[1]), e37(o4(t3($2, g2), -r4[1]), o4(t3(_2, d3), l4[1]))), a4[2]), o4(e37(o4(t3(T2, b2), i4[1]), e37(o4(t3(R2, p4), -r4[1]), o4(t3(_2, d3), a4[1]))), -l4[2]))), -c4[3])), e37(o4(e37(e37(o4(e37(o4(t3(B2, A2), r4[1]), e37(o4(t3(L2, x2), -a4[1]), o4(t3(T2, b2), c4[1]))), i4[2]), o4(e37(o4(t3(B2, A2), i4[1]), e37(o4(t3(D2, m2), -a4[1]), o4(t3(R2, p4), c4[1]))), -r4[2])), e37(o4(e37(o4(t3(L2, x2), i4[1]), e37(o4(t3(D2, m2), -r4[1]), o4(t3(_2, d3), c4[1]))), a4[2]), o4(e37(o4(t3(T2, b2), i4[1]), e37(o4(t3(R2, p4), -r4[1]), o4(t3(_2, d3), a4[1]))), -c4[2]))), l4[3]), o4(e37(e37(o4(e37(o4(t3(H2, O2), s3[1]), e37(o4(t3(X, w), -a4[1]), o4(t3(E3, P), l4[1]))), r4[2]), o4(e37(o4(t3(H2, O2), r4[1]), e37(o4(t3(Y2, v2), -a4[1]), o4(t3(T2, b2), l4[1]))), -s3[2])), e37(o4(e37(o4(t3(X, w), r4[1]), e37(o4(t3(Y2, v2), -s3[1]), o4(t3(C, y2), l4[1]))), a4[2]), o4(e37(o4(t3(E3, P), r4[1]), e37(o4(t3(T2, b2), -s3[1]), o4(t3(C, y2), a4[1]))), -l4[2]))), i4[3]))), e37(e37(o4(e37(e37(o4(e37(o4(t3(H2, O2), s3[1]), e37(o4(t3(X, w), -a4[1]), o4(t3(E3, P), l4[1]))), i4[2]), o4(e37(o4(t3(H2, O2), i4[1]), e37(o4(t3($2, g2), -a4[1]), o4(t3(R2, p4), l4[1]))), -s3[2])), e37(o4(e37(o4(t3(X, w), i4[1]), e37(o4(t3($2, g2), -s3[1]), o4(t3(S2, u3), l4[1]))), a4[2]), o4(e37(o4(t3(E3, P), i4[1]), e37(o4(t3(R2, p4), -s3[1]), o4(t3(S2, u3), a4[1]))), -l4[2]))), -r4[3]), o4(e37(e37(o4(e37(o4(t3(H2, O2), r4[1]), e37(o4(t3(Y2, v2), -a4[1]), o4(t3(T2, b2), l4[1]))), i4[2]), o4(e37(o4(t3(H2, O2), i4[1]), e37(o4(t3($2, g2), -a4[1]), o4(t3(R2, p4), l4[1]))), -r4[2])), e37(o4(e37(o4(t3(Y2, v2), i4[1]), e37(o4(t3($2, g2), -r4[1]), o4(t3(_2, d3), l4[1]))), a4[2]), o4(e37(o4(t3(T2, b2), i4[1]), e37(o4(t3(R2, p4), -r4[1]), o4(t3(_2, d3), a4[1]))), -l4[2]))), s3[3])), e37(o4(e37(e37(o4(e37(o4(t3(X, w), r4[1]), e37(o4(t3(Y2, v2), -s3[1]), o4(t3(C, y2), l4[1]))), i4[2]), o4(e37(o4(t3(X, w), i4[1]), e37(o4(t3($2, g2), -s3[1]), o4(t3(S2, u3), l4[1]))), -r4[2])), e37(o4(e37(o4(t3(Y2, v2), i4[1]), e37(o4(t3($2, g2), -r4[1]), o4(t3(_2, d3), l4[1]))), s3[2]), o4(e37(o4(t3(C, y2), i4[1]), e37(o4(t3(S2, u3), -r4[1]), o4(t3(_2, d3), s3[1]))), -l4[2]))), -a4[3]), o4(e37(e37(o4(e37(o4(t3(E3, P), r4[1]), e37(o4(t3(T2, b2), -s3[1]), o4(t3(C, y2), a4[1]))), i4[2]), o4(e37(o4(t3(E3, P), i4[1]), e37(o4(t3(R2, p4), -s3[1]), o4(t3(S2, u3), a4[1]))), -r4[2])), e37(o4(e37(o4(t3(T2, b2), i4[1]), e37(o4(t3(R2, p4), -r4[1]), o4(t3(_2, d3), a4[1]))), s3[2]), o4(e37(o4(t3(C, y2), i4[1]), e37(o4(t3(S2, u3), -r4[1]), o4(t3(_2, d3), s3[1]))), -a4[2]))), l4[3]))))), G2 = e37(e37(e37(o4(e37(e37(o4(e37(o4(t3(V2, F2), a4[1]), e37(o4(t3(H2, O2), -c4[1]), o4(t3(B2, A2), l4[1]))), s3[2]), o4(e37(o4(t3(V2, F2), s3[1]), e37(o4(t3(X, w), -c4[1]), o4(t3(z2, M), l4[1]))), -a4[2])), e37(o4(e37(o4(t3(H2, O2), s3[1]), e37(o4(t3(X, w), -a4[1]), o4(t3(E3, P), l4[1]))), c4[2]), o4(e37(o4(t3(B2, A2), s3[1]), e37(o4(t3(z2, M), -a4[1]), o4(t3(E3, P), c4[1]))), -l4[2]))), i4[3]), e37(o4(e37(e37(o4(e37(o4(t3(V2, F2), a4[1]), e37(o4(t3(H2, O2), -c4[1]), o4(t3(B2, A2), l4[1]))), i4[2]), o4(e37(o4(t3(V2, F2), i4[1]), e37(o4(t3($2, g2), -c4[1]), o4(t3(D2, m2), l4[1]))), -a4[2])), e37(o4(e37(o4(t3(H2, O2), i4[1]), e37(o4(t3($2, g2), -a4[1]), o4(t3(R2, p4), l4[1]))), c4[2]), o4(e37(o4(t3(B2, A2), i4[1]), e37(o4(t3(D2, m2), -a4[1]), o4(t3(R2, p4), c4[1]))), -l4[2]))), -s3[3]), o4(e37(e37(o4(e37(o4(t3(V2, F2), s3[1]), e37(o4(t3(X, w), -c4[1]), o4(t3(z2, M), l4[1]))), i4[2]), o4(e37(o4(t3(V2, F2), i4[1]), e37(o4(t3($2, g2), -c4[1]), o4(t3(D2, m2), l4[1]))), -s3[2])), e37(o4(e37(o4(t3(X, w), i4[1]), e37(o4(t3($2, g2), -s3[1]), o4(t3(S2, u3), l4[1]))), c4[2]), o4(e37(o4(t3(z2, M), i4[1]), e37(o4(t3(D2, m2), -s3[1]), o4(t3(S2, u3), c4[1]))), -l4[2]))), a4[3]))), e37(e37(o4(e37(e37(o4(e37(o4(t3(H2, O2), s3[1]), e37(o4(t3(X, w), -a4[1]), o4(t3(E3, P), l4[1]))), i4[2]), o4(e37(o4(t3(H2, O2), i4[1]), e37(o4(t3($2, g2), -a4[1]), o4(t3(R2, p4), l4[1]))), -s3[2])), e37(o4(e37(o4(t3(X, w), i4[1]), e37(o4(t3($2, g2), -s3[1]), o4(t3(S2, u3), l4[1]))), a4[2]), o4(e37(o4(t3(E3, P), i4[1]), e37(o4(t3(R2, p4), -s3[1]), o4(t3(S2, u3), a4[1]))), -l4[2]))), -c4[3]), o4(e37(e37(o4(e37(o4(t3(B2, A2), s3[1]), e37(o4(t3(z2, M), -a4[1]), o4(t3(E3, P), c4[1]))), i4[2]), o4(e37(o4(t3(B2, A2), i4[1]), e37(o4(t3(D2, m2), -a4[1]), o4(t3(R2, p4), c4[1]))), -s3[2])), e37(o4(e37(o4(t3(z2, M), i4[1]), e37(o4(t3(D2, m2), -s3[1]), o4(t3(S2, u3), c4[1]))), a4[2]), o4(e37(o4(t3(E3, P), i4[1]), e37(o4(t3(R2, p4), -s3[1]), o4(t3(S2, u3), a4[1]))), -c4[2]))), l4[3])), e37(o4(e37(e37(o4(e37(o4(t3(V2, F2), s3[1]), e37(o4(t3(X, w), -c4[1]), o4(t3(z2, M), l4[1]))), r4[2]), o4(e37(o4(t3(V2, F2), r4[1]), e37(o4(t3(Y2, v2), -c4[1]), o4(t3(L2, x2), l4[1]))), -s3[2])), e37(o4(e37(o4(t3(X, w), r4[1]), e37(o4(t3(Y2, v2), -s3[1]), o4(t3(C, y2), l4[1]))), c4[2]), o4(e37(o4(t3(z2, M), r4[1]), e37(o4(t3(L2, x2), -s3[1]), o4(t3(C, y2), c4[1]))), -l4[2]))), i4[3]), o4(e37(e37(o4(e37(o4(t3(V2, F2), s3[1]), e37(o4(t3(X, w), -c4[1]), o4(t3(z2, M), l4[1]))), i4[2]), o4(e37(o4(t3(V2, F2), i4[1]), e37(o4(t3($2, g2), -c4[1]), o4(t3(D2, m2), l4[1]))), -s3[2])), e37(o4(e37(o4(t3(X, w), i4[1]), e37(o4(t3($2, g2), -s3[1]), o4(t3(S2, u3), l4[1]))), c4[2]), o4(e37(o4(t3(z2, M), i4[1]), e37(o4(t3(D2, m2), -s3[1]), o4(t3(S2, u3), c4[1]))), -l4[2]))), -r4[3])))), e37(e37(e37(o4(e37(e37(o4(e37(o4(t3(V2, F2), r4[1]), e37(o4(t3(Y2, v2), -c4[1]), o4(t3(L2, x2), l4[1]))), i4[2]), o4(e37(o4(t3(V2, F2), i4[1]), e37(o4(t3($2, g2), -c4[1]), o4(t3(D2, m2), l4[1]))), -r4[2])), e37(o4(e37(o4(t3(Y2, v2), i4[1]), e37(o4(t3($2, g2), -r4[1]), o4(t3(_2, d3), l4[1]))), c4[2]), o4(e37(o4(t3(L2, x2), i4[1]), e37(o4(t3(D2, m2), -r4[1]), o4(t3(_2, d3), c4[1]))), -l4[2]))), s3[3]), o4(e37(e37(o4(e37(o4(t3(X, w), r4[1]), e37(o4(t3(Y2, v2), -s3[1]), o4(t3(C, y2), l4[1]))), i4[2]), o4(e37(o4(t3(X, w), i4[1]), e37(o4(t3($2, g2), -s3[1]), o4(t3(S2, u3), l4[1]))), -r4[2])), e37(o4(e37(o4(t3(Y2, v2), i4[1]), e37(o4(t3($2, g2), -r4[1]), o4(t3(_2, d3), l4[1]))), s3[2]), o4(e37(o4(t3(C, y2), i4[1]), e37(o4(t3(S2, u3), -r4[1]), o4(t3(_2, d3), s3[1]))), -l4[2]))), -c4[3])), e37(o4(e37(e37(o4(e37(o4(t3(z2, M), r4[1]), e37(o4(t3(L2, x2), -s3[1]), o4(t3(C, y2), c4[1]))), i4[2]), o4(e37(o4(t3(z2, M), i4[1]), e37(o4(t3(D2, m2), -s3[1]), o4(t3(S2, u3), c4[1]))), -r4[2])), e37(o4(e37(o4(t3(L2, x2), i4[1]), e37(o4(t3(D2, m2), -r4[1]), o4(t3(_2, d3), c4[1]))), s3[2]), o4(e37(o4(t3(C, y2), i4[1]), e37(o4(t3(S2, u3), -r4[1]), o4(t3(_2, d3), s3[1]))), -c4[2]))), l4[3]), o4(e37(e37(o4(e37(o4(t3(B2, A2), s3[1]), e37(o4(t3(z2, M), -a4[1]), o4(t3(E3, P), c4[1]))), r4[2]), o4(e37(o4(t3(B2, A2), r4[1]), e37(o4(t3(L2, x2), -a4[1]), o4(t3(T2, b2), c4[1]))), -s3[2])), e37(o4(e37(o4(t3(z2, M), r4[1]), e37(o4(t3(L2, x2), -s3[1]), o4(t3(C, y2), c4[1]))), a4[2]), o4(e37(o4(t3(E3, P), r4[1]), e37(o4(t3(T2, b2), -s3[1]), o4(t3(C, y2), a4[1]))), -c4[2]))), i4[3]))), e37(e37(o4(e37(e37(o4(e37(o4(t3(B2, A2), s3[1]), e37(o4(t3(z2, M), -a4[1]), o4(t3(E3, P), c4[1]))), i4[2]), o4(e37(o4(t3(B2, A2), i4[1]), e37(o4(t3(D2, m2), -a4[1]), o4(t3(R2, p4), c4[1]))), -s3[2])), e37(o4(e37(o4(t3(z2, M), i4[1]), e37(o4(t3(D2, m2), -s3[1]), o4(t3(S2, u3), c4[1]))), a4[2]), o4(e37(o4(t3(E3, P), i4[1]), e37(o4(t3(R2, p4), -s3[1]), o4(t3(S2, u3), a4[1]))), -c4[2]))), -r4[3]), o4(e37(e37(o4(e37(o4(t3(B2, A2), r4[1]), e37(o4(t3(L2, x2), -a4[1]), o4(t3(T2, b2), c4[1]))), i4[2]), o4(e37(o4(t3(B2, A2), i4[1]), e37(o4(t3(D2, m2), -a4[1]), o4(t3(R2, p4), c4[1]))), -r4[2])), e37(o4(e37(o4(t3(L2, x2), i4[1]), e37(o4(t3(D2, m2), -r4[1]), o4(t3(_2, d3), c4[1]))), a4[2]), o4(e37(o4(t3(T2, b2), i4[1]), e37(o4(t3(R2, p4), -r4[1]), o4(t3(_2, d3), a4[1]))), -c4[2]))), s3[3])), e37(o4(e37(e37(o4(e37(o4(t3(z2, M), r4[1]), e37(o4(t3(L2, x2), -s3[1]), o4(t3(C, y2), c4[1]))), i4[2]), o4(e37(o4(t3(z2, M), i4[1]), e37(o4(t3(D2, m2), -s3[1]), o4(t3(S2, u3), c4[1]))), -r4[2])), e37(o4(e37(o4(t3(L2, x2), i4[1]), e37(o4(t3(D2, m2), -r4[1]), o4(t3(_2, d3), c4[1]))), s3[2]), o4(e37(o4(t3(C, y2), i4[1]), e37(o4(t3(S2, u3), -r4[1]), o4(t3(_2, d3), s3[1]))), -c4[2]))), -a4[3]), o4(e37(e37(o4(e37(o4(t3(E3, P), r4[1]), e37(o4(t3(T2, b2), -s3[1]), o4(t3(C, y2), a4[1]))), i4[2]), o4(e37(o4(t3(E3, P), i4[1]), e37(o4(t3(R2, p4), -s3[1]), o4(t3(S2, u3), a4[1]))), -r4[2])), e37(o4(e37(o4(t3(T2, b2), i4[1]), e37(o4(t3(R2, p4), -r4[1]), o4(t3(_2, d3), a4[1]))), s3[2]), o4(e37(o4(t3(C, y2), i4[1]), e37(o4(t3(S2, u3), -r4[1]), o4(t3(_2, d3), s3[1]))), -a4[2]))), c4[3]))))), U2 = t3(W2, G2);
      return U2[U2.length - 1];
    };
  }
  var d2 = [function() {
    return 0;
  }, function() {
    return 0;
  }, function() {
    return 0;
  }];
  function u2(e37) {
    var t3 = d2[e37.length];
    return t3 || (t3 = d2[e37.length] = s2(e37.length)), t3.apply(undefined, e37);
  }
  function p3(e37, t3, n3, o4, i4, r4, s3, a4) {
    return function(t4, n4, c4, l4, h3, d3) {
      switch (arguments.length) {
        case 0:
        case 1:
          return 0;
        case 2:
          return o4(t4, n4);
        case 3:
          return i4(t4, n4, c4);
        case 4:
          return r4(t4, n4, c4, l4);
        case 5:
          return s3(t4, n4, c4, l4, h3);
        case 6:
          return a4(t4, n4, c4, l4, h3, d3);
      }
      for (var u3 = new Array(arguments.length), p4 = 0;p4 < arguments.length; ++p4)
        u3[p4] = arguments[p4];
      return e37(u3);
    };
  }
  (function() {
    for (;d2.length <= 6; )
      d2.push(s2(d2.length));
    t2.exports = p3.apply(undefined, [u2].concat(d2));
    for (var e37 = 0;e37 <= 6; ++e37)
      t2.exports[e37] = d2[e37];
  })();
} });
var vY = hY({ "node_modules/cdt2d/lib/delaunay.js"(e36, t2) {
  var n2 = xY()[4];
  dY();
  function o3(e37, t3, o4, i3, r3, s2) {
    var a3 = t3.opposite(i3, r3);
    if (!(a3 < 0)) {
      if (r3 < i3) {
        var c3 = i3;
        i3 = r3, r3 = c3, c3 = s2, s2 = a3, a3 = c3;
      }
      t3.isConstraint(i3, r3) || n2(e37[i3], e37[r3], e37[s2], e37[a3]) < 0 && o4.push(i3, r3);
    }
  }
  t2.exports = function(e37, t3) {
    for (var i3 = [], r3 = e37.length, s2 = t3.stars, a3 = 0;a3 < r3; ++a3)
      for (var c3 = s2[a3], l3 = 1;l3 < c3.length; l3 += 2) {
        if (!((p3 = c3[l3]) < a3) && !t3.isConstraint(a3, p3)) {
          for (var h2 = c3[l3 - 1], d2 = -1, u2 = 1;u2 < c3.length; u2 += 2)
            if (c3[u2 - 1] === p3) {
              d2 = c3[u2];
              break;
            }
          d2 < 0 || n2(e37[a3], e37[p3], e37[h2], e37[d2]) < 0 && i3.push(a3, p3);
        }
      }
    for (;i3.length > 0; ) {
      for (var p3 = i3.pop(), m2 = (h2 = -1, d2 = -1, c3 = s2[a3 = i3.pop()], 1);m2 < c3.length; m2 += 2) {
        var g2 = c3[m2 - 1], f2 = c3[m2];
        g2 === p3 ? d2 = f2 : f2 === p3 && (h2 = g2);
      }
      h2 < 0 || d2 < 0 || (n2(e37[a3], e37[p3], e37[h2], e37[d2]) >= 0 || (t3.flip(a3, p3), o3(e37, t3, i3, h2, a3, d2), o3(e37, t3, i3, a3, d2, h2), o3(e37, t3, i3, d2, p3, h2), o3(e37, t3, i3, p3, h2, d2)));
    }
  };
} });
var IY = hY({ "node_modules/cdt2d/lib/filter.js"(e36, t2) {
  var n2 = dY();
  function o3(e37, t3, n3, o4, i4, r3, s2) {
    this.cells = e37, this.neighbor = t3, this.flags = o4, this.constraint = n3, this.active = i4, this.next = r3, this.boundary = s2;
  }
  function i3(e37, t3) {
    return e37[0] - t3[0] || e37[1] - t3[1] || e37[2] - t3[2];
  }
  t2.exports = function(e37, t3, n3) {
    var r3 = function(e38, t4) {
      for (var n4 = e38.cells(), r4 = n4.length, s3 = 0;s3 < r4; ++s3) {
        var a4 = (_3 = n4[s3])[0], c4 = _3[1], l4 = _3[2];
        c4 < l4 ? c4 < a4 && (_3[0] = c4, _3[1] = l4, _3[2] = a4) : l4 < a4 && (_3[0] = l4, _3[1] = a4, _3[2] = c4);
      }
      n4.sort(i3);
      var h3 = new Array(r4);
      for (s3 = 0;s3 < h3.length; ++s3)
        h3[s3] = 0;
      var d3 = [], u3 = [], p4 = new Array(3 * r4), m3 = new Array(3 * r4), g3 = null;
      t4 && (g3 = []);
      var f3 = new o3(n4, p4, m3, h3, d3, u3, g3);
      for (s3 = 0;s3 < r4; ++s3)
        for (var _3 = n4[s3], y2 = 0;y2 < 3; ++y2) {
          a4 = _3[y2], c4 = _3[(y2 + 1) % 3];
          var b2 = p4[3 * s3 + y2] = f3.locate(c4, a4, e38.opposite(c4, a4)), x2 = m3[3 * s3 + y2] = e38.isConstraint(a4, c4);
          b2 < 0 && (x2 ? u3.push(s3) : (d3.push(s3), h3[s3] = 1), t4 && g3.push([c4, a4, -1]));
        }
      return f3;
    }(e37, n3);
    if (t3 === 0)
      return n3 ? r3.cells.concat(r3.boundary) : r3.cells;
    var s2 = 1, a3 = r3.active, c3 = r3.next, l3 = r3.flags, h2 = r3.cells, d2 = r3.constraint, u2 = r3.neighbor;
    for (;a3.length > 0 || c3.length > 0; ) {
      for (;a3.length > 0; ) {
        var p3 = a3.pop();
        if (l3[p3] !== -s2) {
          l3[p3] = s2;
          h2[p3];
          for (var m2 = 0;m2 < 3; ++m2) {
            var g2 = u2[3 * p3 + m2];
            g2 >= 0 && l3[g2] === 0 && (d2[3 * p3 + m2] ? c3.push(g2) : (a3.push(g2), l3[g2] = s2));
          }
        }
      }
      var f2 = c3;
      c3 = a3, a3 = f2, c3.length = 0, s2 = -s2;
    }
    var _2 = function(e38, t4, n4) {
      for (var o4 = 0, i4 = 0;i4 < e38.length; ++i4)
        t4[i4] === n4 && (e38[o4++] = e38[i4]);
      return e38.length = o4, e38;
    }(h2, l3, t3);
    if (n3)
      return _2.concat(r3.boundary);
    return _2;
  }, o3.prototype.locate = function() {
    var e37 = [0, 0, 0];
    return function(t3, o4, r3) {
      var s2 = t3, a3 = o4, c3 = r3;
      return o4 < r3 ? o4 < t3 && (s2 = o4, a3 = r3, c3 = t3) : r3 < t3 && (s2 = r3, a3 = t3, c3 = o4), s2 < 0 ? -1 : (e37[0] = s2, e37[1] = a3, e37[2] = c3, n2.eq(this.cells, e37, i3));
    };
  }();
} });
var SY = hY({ "node_modules/cdt2d/cdt2d.js"(e36, t2) {
  var n2 = yY(), o3 = bY(), i3 = vY(), r3 = IY();
  function s2(e37) {
    return [Math.min(e37[0], e37[1]), Math.max(e37[0], e37[1])];
  }
  function a3(e37, t3) {
    return e37[0] - t3[0] || e37[1] - t3[1];
  }
  function c3(e37, t3, n3) {
    return t3 in e37 ? e37[t3] : n3;
  }
  t2.exports = function(e37, t3, l3) {
    Array.isArray(t3) ? (l3 = l3 || {}, t3 = t3 || []) : (l3 = t3 || {}, t3 = []);
    var h2 = !!c3(l3, "delaunay", true), d2 = !!c3(l3, "interior", true), u2 = !!c3(l3, "exterior", true), p3 = !!c3(l3, "infinity", false);
    if (!d2 && !u2 || e37.length === 0)
      return [];
    var m2 = n2(e37, t3);
    if (h2 || d2 !== u2 || p3) {
      for (var g2 = o3(e37.length, function(e38) {
        return e38.map(s2).sort(a3);
      }(t3)), f2 = 0;f2 < m2.length; ++f2) {
        var _2 = m2[f2];
        g2.addTriangle(_2[0], _2[1], _2[2]);
      }
      return h2 && i3(e37, g2), u2 ? d2 ? p3 ? r3(g2, 0, p3) : g2.cells() : r3(g2, 1, p3) : r3(g2, -1);
    }
    return m2;
  };
} });
var CY = (e36) => e36.map((e37) => ({ connectionId: e37.connectionId, startRegionId: e37.startRegion.regionId, endRegionId: e37.endRegion.regionId, mutuallyConnectedNetworkId: e37.mutuallyConnectedNetworkId }));
var PY = (e36) => ({ ports: e36.ports.map((e37) => ({ portId: e37.portId, region1Id: e37.region1.regionId, region2Id: e37.region2.regionId, d: e37.d })), regions: e36.regions.map((e37) => ({ regionId: e37.regionId, pointIds: e37.ports.map((e38) => e38.portId), d: e37.d })) });
var MY = ({ port: e36, boundaryRegionMap: t2 }) => {
  let n2 = t2.get(e36.portId);
  if (!n2) {
    const o3 = typeof e36.d?.x == "number" ? e36.d.x : 0, i3 = typeof e36.d?.y == "number" ? e36.d.y : 0;
    n2 = { regionId: `__section_boundary__${e36.portId}`, ports: [], d: { isBoundaryRegion: true, boundaryPortId: e36.portId, ...e36.d, center: { x: o3, y: i3 }, bounds: { minX: o3 - 0.05, maxX: o3 + 0.05, minY: i3 - 0.05, maxY: i3 + 0.05 } }, assignments: [] }, t2.set(e36.portId, n2);
  }
  return n2;
};
var wY = (e36) => {
  const { sectionRoute: t2, graph: n2 } = e36, o3 = new Set(n2.ports.map((e37) => e37.portId)), i3 = t2.globalRoute.path.slice(t2.sectionStartIndex, t2.sectionEndIndex + 1).filter((e37) => o3.has(e37.port.portId)), r3 = [];
  let s2 = t2.sectionConnection.startRegion;
  for (let e37 = 0;e37 < i3.length; e37++) {
    const t3 = i3[e37], o4 = n2.ports.find((e38) => e38.portId === t3.port.portId), a3 = o4.region1 === s2 ? o4.region2 : o4.region1;
    r3.push({ port: o4, g: 0, h: 0, f: 0, hops: e37, ripRequired: t3.ripRequired, parent: e37 > 0 ? r3[e37 - 1] : undefined, lastPort: e37 > 0 ? r3[e37 - 1].port : undefined, lastRegion: e37 > 0 ? s2 : undefined, nextRegion: a3 }), s2 = a3;
  }
  return { connection: t2.sectionConnection, path: r3, requiredRip: t2.globalRoute.requiredRip };
};
var NY = (e36, t2) => {
  let n2 = -1, o3 = -1;
  for (let i3 = 0;i3 < e36.path.length; i3++) {
    const r3 = e36.path[i3];
    (r3.lastRegion && t2.has(r3.lastRegion.regionId) || r3.nextRegion && t2.has(r3.nextRegion.regionId)) && (n2 === -1 && (n2 = i3), o3 = i3);
  }
  return n2 === -1 ? null : { startIndex: n2, endIndex: o3 };
};
var RY = (e36) => {
  const { graph: t2, solvedRoutes: n2, centralRegion: o3, expansionHopsFromCentralRegion: i3 } = e36, r3 = (({ centralRegion: e37, expansionHopsFromCentralRegion: t3 }) => {
    const n3 = new Set([e37.regionId]), o4 = [{ region: e37, hops: 0 }];
    for (;o4.length > 0; ) {
      const { region: e38, hops: i4 } = o4.shift();
      if (!(i4 >= t3 + 1))
        for (const t4 of e38.ports) {
          const r4 = t4.region1 === e38 ? t4.region2 : t4.region1;
          n3.has(r4.regionId) || (n3.add(r4.regionId), o4.push({ region: r4, hops: i4 + 1 }));
        }
    }
    return n3;
  })({ graph: t2, centralRegion: o3, expansionHopsFromCentralRegion: i3 }), s2 = new Map, a3 = new Map, c3 = [];
  for (const e37 of t2.regions)
    r3.has(e37.regionId) && s2.set(e37.regionId, { regionId: e37.regionId, ports: [], d: e37.d ? structuredClone(e37.d) : e37.d, assignments: [] });
  for (const e37 of t2.ports) {
    const t3 = r3.has(e37.region1.regionId), n3 = r3.has(e37.region2.regionId);
    if (!t3 && !n3)
      continue;
    if (t3 && n3) {
      const t4 = { portId: e37.portId, region1: s2.get(e37.region1.regionId), region2: s2.get(e37.region2.regionId), d: e37.d };
      t4.region1.ports.push(t4), t4.region2.ports.push(t4), c3.push(t4);
      continue;
    }
    const o4 = t3 ? e37.region1 : e37.region2, i4 = MY({ port: e37, boundaryRegionMap: a3 }), l4 = { portId: e37.portId, region1: s2.get(o4.regionId), region2: i4, d: e37.d };
    l4.region1.ports.push(l4), l4.region2.ports.push(l4), c3.push(l4);
  }
  const l3 = { regions: [...s2.values(), ...a3.values()], ports: c3 }, h2 = [], d2 = [], u2 = [];
  for (const e37 of n2) {
    const t3 = NY(e37, r3);
    if (!t3)
      continue;
    const n3 = e37.path[t3.startIndex], o4 = e37.path[t3.endIndex];
    u2.push({ solvedRoute: e37, solvedPathStartIndex: t3.startIndex, solvedPathEndIndex: t3.endIndex, startCandidate: n3, endCandidate: o4 });
  }
  const p3 = new Map(l3.regions.map((e37) => [e37.regionId, e37]));
  for (const { solvedRoute: e37, solvedPathStartIndex: t3, solvedPathEndIndex: n3, startCandidate: o4, endCandidate: i4 } of u2) {
    let s3, c4, u3, m2;
    if (r3.has(e37.connection.startRegion.regionId))
      s3 = e37.connection.startRegion.regionId, c4 = p3.get(s3);
    else {
      const e38 = MY({ port: o4.port, boundaryRegionMap: a3 });
      s3 = e38.regionId, c4 = e38, p3.has(s3) || p3.set(s3, e38);
    }
    if (r3.has(e37.connection.endRegion.regionId))
      u3 = e37.connection.endRegion.regionId, m2 = p3.get(u3);
    else {
      const e38 = MY({ port: i4.port, boundaryRegionMap: a3 });
      u3 = e38.regionId, m2 = e38, p3.has(u3) || p3.set(u3, e38);
    }
    if (!c4)
      throw console.error("[getSectionOfHyperGraphAsHyperGraph] CRITICAL ERROR: startRegion not found!"), console.error(`  Looking for: ${s3}`), console.error(`  Route connection: ${e37.connection.connectionId}`), console.error(`  Original startRegion: ${e37.connection.startRegion.regionId}`), console.error(`  startCandidate port: ${o4.port.portId}`), console.error("  Available regions in sectionRegionMap:", Array.from(p3.keys())), new Error(`startRegion ${s3} not found in sectionRegionMap`);
    if (!m2)
      throw console.error("[getSectionOfHyperGraphAsHyperGraph] CRITICAL ERROR: endRegion not found!"), console.error(`  Looking for: ${u3}`), console.error(`  Route connection: ${e37.connection.connectionId}`), console.error(`  Original endRegion: ${e37.connection.endRegion.regionId}`), console.error(`  endCandidate port: ${i4.port.portId}`), console.error("  Available regions in sectionRegionMap:", Array.from(p3.keys())), new Error(`endRegion ${u3} not found in sectionRegionMap`);
    const g2 = { connectionId: e37.connection.connectionId, mutuallyConnectedNetworkId: e37.connection.mutuallyConnectedNetworkId, startRegion: c4, endRegion: m2 }, f2 = e37.path.slice(t3, n3 + 1), _2 = { globalRoute: e37, globalConnection: e37.connection, sectionConnection: g2, sectionStartIndex: t3, sectionEndIndex: n3 };
    h2.push({ ..._2, canRemainFixedInSectionSolve: f2.every((e38) => l3.ports.some((t4) => t4.portId === e38.port.portId)), sectionRoute: wY({ sectionRoute: _2, graph: l3 }) }), d2.push(g2);
  }
  return { centralRegionId: o3.regionId, sectionRegionIds: r3, graph: l3, connections: d2, sectionRoutes: h2 };
};
var TY = class {
  heap = [];
  maxSize;
  constructor(e36 = [], t2 = 1e4) {
    if (this.maxSize = t2, e36.length > 0) {
      this.heap = [...e36].sort((e37, t3) => e37.f - t3.f).slice(0, this.maxSize);
      for (let e37 = Math.floor(this.heap.length / 2) - 1;e37 >= 0; e37--)
        this._siftDown(e37);
    }
  }
  get size() {
    return this.heap.length;
  }
  isEmpty() {
    return this.heap.length === 0;
  }
  peek() {
    return this.isEmpty() ? null : this.heap[0] ?? null;
  }
  peekMany(e36) {
    return [...this.heap].sort((e37, t2) => e37.f - t2.f).slice(0, e36);
  }
  dequeue() {
    if (this.isEmpty())
      return null;
    const e36 = this.heap[0], t2 = this.heap.pop();
    return this.heap.length === 0 && t2 !== undefined || t2 !== undefined && (this.heap[0] = t2, this._siftDown(0)), e36;
  }
  enqueue(e36) {
    this.heap.length >= this.maxSize || (this.heap.push(e36), this._siftUp(this.heap.length - 1));
  }
  _siftUp(e36) {
    let t2 = e36;
    for (;t2 > 0; ) {
      const e37 = this._parentIndex(t2);
      if (this.heap[e37].f <= this.heap[t2].f)
        break;
      this._swap(t2, e37), t2 = e37;
    }
  }
  _siftDown(e36) {
    let t2 = e36;
    const n2 = this.heap.length;
    for (;; ) {
      const e37 = this._leftChildIndex(t2), o3 = this._rightChildIndex(t2);
      let i3 = t2;
      if (e37 < n2 && this.heap[e37].f < this.heap[i3].f && (i3 = e37), o3 < n2 && this.heap[o3].f < this.heap[i3].f && (i3 = o3), i3 === t2)
        break;
      this._swap(t2, i3), t2 = i3;
    }
  }
  _swap(e36, t2) {
    [this.heap[e36], this.heap[t2]] = [this.heap[t2], this.heap[e36]];
  }
  _parentIndex(e36) {
    return Math.floor((e36 - 1) / 2);
  }
  _leftChildIndex(e36) {
    return 2 * e36 + 1;
  }
  _rightChildIndex(e36) {
    return 2 * e36 + 2;
  }
};
var EY = (e36) => {
  for (const t2 of e36.regions)
    t2.assignments = [];
  for (const t2 of e36.ports)
    t2.assignment = undefined;
};
var AY = ({ graph: e36, connections: t2, solvedRoutes: n2 }) => {
  const o3 = new Map(e36.ports.map((e37) => [e37.portId, e37])), i3 = new Map(e36.regions.map((e37) => [e37.regionId, e37])), r3 = new Map(t2.map((e37) => [e37.connectionId, e37])), s2 = n2.map((e37) => {
    const t3 = [];
    for (const n3 of e37.path) {
      const e38 = { port: o3.get(n3.port.portId), g: n3.g, h: n3.h, f: n3.f, hops: n3.hops, ripRequired: n3.ripRequired };
      n3.lastPort && (e38.lastPort = o3.get(n3.lastPort.portId)), n3.lastRegion && (e38.lastRegion = i3.get(n3.lastRegion.regionId)), n3.nextRegion && (e38.nextRegion = i3.get(n3.nextRegion.regionId));
      const r4 = t3[t3.length - 1];
      r4 && (e38.parent = r4), t3.push(e38);
    }
    return { path: t3, connection: r3.get(e37.connection.connectionId), requiredRip: e37.requiredRip };
  });
  EY(e36), e36.solvedRoutes = s2;
  for (const e37 of s2)
    for (const t3 of e37.path) {
      if (t3.port.assignment = { solvedRoute: e37, connection: e37.connection }, !t3.lastPort || !t3.lastRegion)
        continue;
      const n3 = { regionPort1: t3.lastPort, regionPort2: t3.port, region: t3.lastRegion, connection: e37.connection, solvedRoute: e37 };
      t3.lastRegion.assignments ??= [], t3.lastRegion.assignments.push(n3);
    }
  return s2;
};
var OY = class extends BaseSolver {
  constructor(e36) {
    super(), this.input = e36, this.graph = ((e37) => {
      if (e37.ports.length > 0 && "region1" in e37.ports[0] && typeof e37.ports[0].region1 == "object")
        return e37;
      const t3 = new Map, n2 = new Map;
      for (const t4 of e37.regions) {
        const { assignments: e38, ...o3 } = t4;
        n2.set(t4.regionId, { ...o3, d: o3.d ? structuredClone(o3.d) : o3.d, ports: [], assignments: undefined });
      }
      for (const o3 of e37.ports) {
        const e38 = n2.get(o3.region1Id ?? o3.region1?.regionId), i3 = n2.get(o3.region2Id ?? o3.region2?.regionId), r3 = { portId: o3.portId, region1: e38, region2: i3, d: o3.d };
        t3.set(o3.portId, r3), e38.ports.push(r3), i3.ports.push(r3);
      }
      return { ports: Array.from(t3.values()), regions: Array.from(n2.values()) };
    })(e36.inputGraph), EY(this.graph), this.connections = ((e37, t3) => {
      const n2 = [];
      for (const o3 of e37)
        "startRegionId" in o3 ? n2.push({ connectionId: o3.connectionId, mutuallyConnectedNetworkId: o3.mutuallyConnectedNetworkId ?? o3.connectionId, startRegion: t3.regions.find((e38) => e38.regionId === o3.startRegionId), endRegion: t3.regions.find((e38) => e38.regionId === o3.endRegionId) }) : n2.push(o3);
      return n2;
    })(e36.inputConnections, this.graph), e36.inputSolvedRoutes ? this.solvedRoutes = AY({ graph: this.graph, connections: this.connections, solvedRoutes: e36.inputSolvedRoutes }) : this.graph.solvedRoutes = this.solvedRoutes, e36.greedyMultiplier !== undefined && (this.greedyMultiplier = e36.greedyMultiplier), e36.rippingEnabled !== undefined && (this.rippingEnabled = e36.rippingEnabled), e36.ripCost !== undefined && (this.ripCost = e36.ripCost);
    const t2 = new Set(this.solvedRoutes.map((e37) => e37.connection.connectionId));
    this.unprocessedConnections = this.connections.filter((e37) => !t2.has(e37.connectionId)), this.candidateQueue = new TY, this.unprocessedConnections.length === 0 ? this.solved = true : this.beginNewConnection();
  }
  getSolverName() {
    return "HyperGraphSolver";
  }
  graph;
  connections;
  candidateQueue;
  unprocessedConnections;
  solvedRoutes = [];
  currentConnection = null;
  currentEndRegion = null;
  greedyMultiplier = 1;
  rippingEnabled = false;
  ripCost = 0;
  lastCandidate = null;
  visitedPointsForCurrentConnection = new Map;
  getConstructorParams() {
    return { inputGraph: PY(this.graph), inputConnections: CY(this.connections), greedyMultiplier: this.greedyMultiplier, rippingEnabled: this.rippingEnabled, ripCost: this.ripCost, inputSolvedRoutes: this.solvedRoutes };
  }
  computeH(e36) {
    return this.estimateCostToEnd(e36.port);
  }
  estimateCostToEnd(e36) {
    return 0;
  }
  getPortUsagePenalty(e36) {
    return 0;
  }
  computeIncreasedRegionCostIfPortsAreUsed(e36, t2, n2) {
    return 0;
  }
  getRipsRequiredForPortUsage(e36, t2, n2) {
    return [];
  }
  isRipRequiredForPortUsage(e36, t2, n2) {
    return false;
  }
  isTransitionAllowed(e36, t2, n2) {
    return true;
  }
  computeG(e36) {
    return e36.parent.g + this.computeIncreasedRegionCostIfPortsAreUsed(e36.lastRegion, e36.lastPort, e36.port) + (e36.ripRequired ? this.ripCost : 0) + this.getPortUsagePenalty(e36.port);
  }
  selectCandidatesForEnteringRegion(e36) {
    return e36;
  }
  computeRoutesToRip(e36) {
    const t2 = this.computeCrossingRoutes(e36), n2 = this.computePortOverlapRoutes(e36);
    return new Set([...t2, ...n2]);
  }
  computePortOverlapRoutes(e36) {
    const t2 = new Set;
    for (const n2 of e36.path)
      n2.port.assignment && n2.port.assignment.connection.mutuallyConnectedNetworkId !== e36.connection.mutuallyConnectedNetworkId && t2.add(n2.port.assignment.solvedRoute);
    return t2;
  }
  computeCrossingRoutes(e36) {
    const t2 = new Set;
    for (const n2 of e36.path) {
      if (!n2.lastPort || !n2.lastRegion)
        continue;
      const e37 = this.getRipsRequiredForPortUsage(n2.lastRegion, n2.lastPort, n2.port);
      for (const n3 of e37)
        t2.add(n3.solvedRoute);
    }
    return t2;
  }
  getNextCandidates(e36) {
    const { nextRegion: t2, port: n2 } = e36, o3 = {};
    for (const i4 of t2.ports) {
      if (i4 === e36.port)
        continue;
      if (!this.isTransitionAllowed(t2, n2, i4))
        continue;
      const r3 = i4.assignment && i4.assignment.connection.mutuallyConnectedNetworkId !== this.currentConnection.mutuallyConnectedNetworkId || this.isRipRequiredForPortUsage(t2, n2, i4), s2 = { port: i4, hops: e36.hops + 1, parent: e36, lastRegion: t2, nextRegion: i4.region1 === t2 ? i4.region2 : i4.region1, lastPort: n2, ripRequired: r3 };
      !this.rippingEnabled && s2.ripRequired || (o3[s2.nextRegion.regionId] ??= [], o3[s2.nextRegion.regionId].push(s2));
    }
    const i3 = [];
    for (const e37 in o3) {
      const t3 = o3[e37];
      i3.push(...this.selectCandidatesForEnteringRegion(t3));
    }
    for (const e37 of i3)
      e37.g = this.computeG(e37), e37.h = this.computeH(e37), e37.f = e37.g + e37.h * this.greedyMultiplier;
    return i3;
  }
  processSolvedRoute(e36) {
    const t2 = { path: [], connection: this.currentConnection, requiredRip: false };
    let n2 = e36, o3 = false;
    for (;n2; )
      o3 ||= !!n2.ripRequired, t2.path.unshift(n2), n2 = n2.parent;
    o3 && (t2.requiredRip = true);
    const i3 = this.computeRoutesToRip(t2);
    if (i3.size > 0) {
      t2.requiredRip = true;
      for (const e37 of i3)
        this.ripSolvedRoute(e37);
    }
    for (const e37 of t2.path) {
      if (e37.port.assignment = { solvedRoute: t2, connection: this.currentConnection }, !e37.lastPort)
        continue;
      const n3 = { regionPort1: e37.lastPort, regionPort2: e37.port, region: e37.lastRegion, connection: this.currentConnection, solvedRoute: t2 };
      e37.lastRegion.assignments?.push(n3);
    }
    this.solvedRoutes.push(t2), this.routeSolvedHook(t2);
  }
  routeSolvedHook(e36) {}
  routeStartedHook(e36) {}
  ripSolvedRoute(e36) {
    for (const t2 of e36.path.map((e37) => e37.port))
      t2.ripCount = (t2.ripCount ?? 0) + 1, t2.region1.assignments = t2.region1.assignments?.filter((e37) => e37.regionPort1 !== t2 && e37.regionPort2 !== t2), t2.region2.assignments = t2.region2.assignments?.filter((e37) => e37.regionPort1 !== t2 && e37.regionPort2 !== t2), t2.assignment = undefined;
    this.solvedRoutes = this.solvedRoutes.filter((t2) => t2 !== e36), this.unprocessedConnections.push(e36.connection);
  }
  beginNewConnection() {
    this.currentConnection = this.unprocessedConnections.shift(), this.currentEndRegion = this.currentConnection.endRegion, this.candidateQueue = new TY, this.visitedPointsForCurrentConnection.clear(), this.routeStartedHook(this.currentConnection);
    for (const e36 of this.currentConnection.startRegion.ports)
      this.candidateQueue.enqueue({ port: e36, g: 0, h: 0, f: 0, hops: 0, ripRequired: false, nextRegion: e36.region1 === this.currentConnection.startRegion ? e36.region2 : e36.region1 });
  }
  _step() {
    let e36 = this.candidateQueue.dequeue();
    if (!e36)
      return this.failed = true, void (this.error = "Ran out of candidates");
    let t2 = this.visitedPointsForCurrentConnection.get(e36.port.portId);
    for (;e36 && t2 !== undefined && !(e36.g < t2) && (e36 = this.candidateQueue.dequeue(), e36); )
      t2 = this.visitedPointsForCurrentConnection.get(e36.port.portId);
    if (!e36)
      return this.failed = true, void (this.error = "Ran out of candidates");
    if (this.lastCandidate = e36, this.visitedPointsForCurrentConnection.set(e36.port.portId, e36.g), e36.nextRegion === this.currentEndRegion)
      return this.processSolvedRoute(e36), this.unprocessedConnections.length === 0 ? void (this.solved = true) : void this.beginNewConnection();
    const n2 = this.getNextCandidates(e36);
    for (const e37 of n2)
      this.candidateQueue.enqueue(e37);
  }
};
function kY(e36, t2) {
  const n2 = e36.x - t2.x, o3 = e36.y - t2.y;
  return n2 * n2 + o3 * o3;
}
function DY(e36, t2, n2, o3, i3) {
  const r3 = n2 - t2, s2 = i3 - o3, a3 = 0.000001;
  if (Math.abs(e36.y - i3) < a3)
    return e36.x - t2;
  if (Math.abs(e36.x - n2) < a3)
    return r3 + (i3 - e36.y);
  if (Math.abs(e36.y - o3) < a3)
    return r3 + s2 + (n2 - e36.x);
  if (Math.abs(e36.x - t2) < a3)
    return 2 * r3 + s2 + (e36.y - o3);
  const c3 = Math.abs(e36.y - i3), l3 = Math.abs(e36.x - n2), h2 = Math.abs(e36.y - o3), d2 = Math.abs(e36.x - t2), u2 = Math.min(c3, l3, h2, d2);
  return u2 === c3 ? Math.max(0, Math.min(r3, e36.x - t2)) : u2 === l3 ? r3 + Math.max(0, Math.min(s2, i3 - e36.y)) : u2 === h2 ? r3 + s2 + Math.max(0, Math.min(r3, n2 - e36.x)) : 2 * r3 + s2 + Math.max(0, Math.min(s2, e36.y - o3));
}
function LY(e36, t2, n2) {
  const o3 = n2.x - t2.x, i3 = n2.y - t2.y, r3 = e36.x - t2.x, s2 = e36.y - t2.y, a3 = o3 * o3 + i3 * i3, c3 = a3 > 0 ? (l3 = (r3 * o3 + s2 * i3) / a3, h2 = 0, d2 = 1, Math.max(h2, Math.min(d2, l3))) : 0;
  var l3, h2, d2;
  return { u: c3, d2: kY(e36, { x: t2.x + c3 * o3, y: t2.y + c3 * i3 }) };
}
function zY(e36) {
  const t2 = e36.d.polygon;
  if (!t2 || t2.length < 3)
    return null;
  const n2 = e36.d.polygonPerimeterCache;
  if (n2)
    return n2;
  const o3 = function(e37) {
    const t3 = e37.length, n3 = new Array(t3), o4 = new Array(t3 + 1);
    o4[0] = 0;
    for (let i3 = 0;i3 < t3; i3++) {
      const r3 = e37[i3], s2 = e37[(i3 + 1) % t3], a3 = Math.hypot(s2.x - r3.x, s2.y - r3.y);
      n3[i3] = a3, o4[i3 + 1] = o4[i3] + a3;
    }
    return { edgeLengths: n3, cumulative: o4, perimeter: o4[t3] };
  }(t2);
  return e36.d.polygonPerimeterCache = o3, o3;
}
function BY(e36) {
  const t2 = zY(e36);
  if (t2)
    return t2.perimeter;
  const { minX: n2, maxX: o3, minY: i3, maxY: r3 } = e36.d.bounds;
  return 2 * (o3 - n2) + 2 * (r3 - i3);
}
function FY(e36, t2) {
  if (e36.region1 === t2) {
    if (typeof e36.region1T == "number")
      return e36.region1T;
    const n2 = jY(e36.d, t2);
    return e36.region1T = n2, n2;
  }
  if (e36.region2 === t2) {
    if (typeof e36.region2T == "number")
      return e36.region2T;
    const n2 = jY(e36.d, t2);
    return e36.region2T = n2, n2;
  }
  return jY(e36.d, t2);
}
function jY(e36, t2) {
  const n2 = t2.d.polygon;
  if (n2 && n2.length >= 3) {
    const o4 = zY(t2);
    if (o4)
      return function(e37, t3, n3, o5 = 0.000001) {
        let i4 = 0, r4 = 0, s3 = Number.POSITIVE_INFINITY;
        const a3 = o5 * o5;
        for (let n4 = 0;n4 < t3.length; n4++) {
          const o6 = LY(e37, t3[n4], t3[(n4 + 1) % t3.length]);
          if (o6.d2 <= a3) {
            i4 = n4, r4 = o6.u, s3 = o6.d2;
            break;
          }
          o6.d2 < s3 && (i4 = n4, r4 = o6.u, s3 = o6.d2);
        }
        return n3.cumulative[i4] + r4 * n3.edgeLengths[i4];
      }(e36, n2, o4);
  }
  const { minX: o3, maxX: i3, minY: r3, maxY: s2 } = t2.d.bounds;
  return DY(e36, o3, i3, r3, s2);
}
function $Y(e36, t2, n2 = 0.000001) {
  return Math.abs(e36 - t2) < n2;
}
function YY(e36, t2) {
  return (e36 % t2 + t2) % t2;
}
function XY(e36, t2, n2, o3) {
  const i3 = Math.abs(YY(e36 - t2, n2));
  return i3 < o3 || n2 - i3 < o3;
}
function HY(e36, t2, n2, o3, i3) {
  const r3 = YY(e36, o3), s2 = YY(t2, o3), a3 = YY(n2, o3);
  return !(Math.abs(s2 - a3) < i3) && (s2 < a3 ? s2 < r3 && r3 < a3 : r3 > s2 || r3 < a3);
}
function VY(e36, t2, n2) {
  if (typeof n2 == "number" && n2 > 0) {
    let [o4, i4] = e36, [r4, s3] = t2;
    if (o4 = YY(o4, n2), i4 = YY(i4, n2), r4 = YY(r4, n2), s3 = YY(s3, n2), XY(o4, r4, n2, 0.000001) || XY(o4, s3, n2, 0.000001) || XY(i4, r4, n2, 0.000001) || XY(i4, s3, n2, 0.000001))
      return false;
    return HY(r4, o4, i4, n2, 0.000000000001) !== HY(s3, o4, i4, n2, 0.000000000001);
  }
  const [o3, i3] = e36[0] < e36[1] ? e36 : [e36[1], e36[0]], [r3, s2] = t2[0] < t2[1] ? t2 : [t2[1], t2[0]];
  return !($Y(o3, r3) || $Y(o3, s2) || $Y(i3, r3) || $Y(i3, s2)) && (o3 < r3 && r3 < i3 && i3 < s2 || r3 < o3 && o3 < s2 && s2 < i3);
}
var WY = (e36) => {
  let { POSITIVE_INFINITY: t2, NEGATIVE_INFINITY: n2, POSITIVE_INFINITY: o3, NEGATIVE_INFINITY: i3 } = Number;
  for (const r3 of e36) {
    const { bounds: e37 } = r3.d;
    t2 = Math.min(t2, e37.minX), n2 = Math.max(n2, e37.maxX), o3 = Math.min(o3, e37.minY), i3 = Math.max(i3, e37.maxY);
  }
  return { minX: t2, maxX: n2, minY: o3, maxY: i3 };
};
var GY = (e36, t2, n2, o3) => {
  const i3 = { portId: e36, region1: t2, region2: n2, d: { x: o3.x, y: o3.y } };
  return t2.ports.push(i3), n2.ports.push(i3), i3;
};
var UY = (e36, t2, n2) => {
  const o3 = 0.2;
  return { regionId: e36, ports: [], d: { bounds: { minX: t2 - o3, maxX: t2 + o3, minY: n2 - o3, maxY: n2 + o3 }, center: { x: t2, y: n2 }, isPad: false, isConnectionRegion: true } };
};
var ZY = 0.01;
var qY = (e36, t2, n2) => Math.max(t2, Math.min(n2, e36));
var JY = (e36, t2, n2) => t2 === "left" ? Math.abs(e36.x - n2.minX) < ZY : t2 === "right" ? Math.abs(e36.x - n2.maxX) < ZY : t2 === "top" ? Math.abs(e36.y - n2.maxY) < ZY : Math.abs(e36.y - n2.minY) < ZY;
var QY = (e36, t2, n2, o3) => {
  const i3 = o3.x - n2.x, r3 = o3.y - n2.y, s2 = e36 - n2.x, a3 = t2 - n2.y, c3 = i3 * i3 + r3 * r3, l3 = c3 > 0 ? qY((s2 * i3 + a3 * r3) / c3, 0, 1) : 0, h2 = n2.x + l3 * i3, d2 = n2.y + l3 * r3, u2 = e36 - h2, p3 = t2 - d2;
  return { x: h2, y: d2, d2: u2 * u2 + p3 * p3 };
};
var KY = (e36, t2, n2, o3, i3) => {
  const r3 = n2.d.polygon;
  if (r3 && r3.length >= 3) {
    const n3 = new Set(i3);
    let s3 = null;
    for (let a4 = 0;a4 < r3.length; a4++) {
      const c4 = r3[a4], l3 = r3[(a4 + 1) % r3.length];
      if (i3.length > 0) {
        if (!i3.some((e37) => JY(c4, e37, o3) && JY(l3, e37, o3) && n3.has(e37)))
          continue;
      }
      const h2 = QY(e36, t2, c4, l3);
      (!s3 || h2.d2 < s3.d2) && (s3 = h2);
    }
    if (s3)
      return s3;
  }
  const s2 = n2.d.bounds, a3 = [];
  if (i3.length > 0)
    for (const n3 of i3)
      n3 === "left" ? a3.push({ side: n3, x: s2.minX, y: qY(t2, s2.minY, s2.maxY) }) : n3 === "right" ? a3.push({ side: n3, x: s2.maxX, y: qY(t2, s2.minY, s2.maxY) }) : n3 === "top" ? a3.push({ side: n3, x: qY(e36, s2.minX, s2.maxX), y: s2.maxY }) : a3.push({ side: n3, x: qY(e36, s2.minX, s2.maxX), y: s2.minY });
  a3.length === 0 && a3.push({ side: "left", x: s2.minX, y: qY(t2, s2.minY, s2.maxY) }, { side: "right", x: s2.maxX, y: qY(t2, s2.minY, s2.maxY) }, { side: "top", x: qY(e36, s2.minX, s2.maxX), y: s2.maxY }, { side: "bottom", x: qY(e36, s2.minX, s2.maxX), y: s2.minY });
  let c3 = null;
  for (const n3 of a3) {
    if (i3.length > 0 && !i3.includes(n3.side))
      continue;
    const o4 = e36 - n3.x, r4 = t2 - n3.y, s3 = o4 * o4 + r4 * r4;
    (!c3 || s3 < c3.d2) && (c3 = { x: n3.x, y: n3.y, d2: s3 });
  }
  return c3;
};
var eX = (e36, t2, n2, o3) => {
  const i3 = ((e37, t3, n3) => {
    const o4 = [];
    return Math.abs(e37 - n3.minX) < ZY && o4.push("left"), Math.abs(e37 - n3.maxX) < ZY && o4.push("right"), Math.abs(t3 - n3.maxY) < ZY && o4.push("top"), Math.abs(t3 - n3.minY) < ZY && o4.push("bottom"), o4;
  })(e36, t2, o3);
  let r3 = null, s2 = Number.POSITIVE_INFINITY, a3 = { x: e36, y: t2 };
  for (const c3 of n2) {
    if (c3.d.isPad || c3.d.isThroughJumper)
      continue;
    const n3 = c3.d.bounds;
    if (!(Math.abs(n3.minX - o3.minX) < 0.01 || Math.abs(n3.maxX - o3.maxX) < 0.01 || Math.abs(n3.minY - o3.minY) < 0.01 || Math.abs(n3.maxY - o3.maxY) < 0.01))
      continue;
    const l3 = KY(e36, t2, c3, o3, i3);
    if (!l3)
      continue;
    const h2 = Math.sqrt(l3.d2);
    h2 < s2 && (s2 = h2, r3 = c3, a3 = { x: l3.x, y: l3.y });
  }
  return r3 ? { region: r3, portPosition: a3 } : null;
};
var tX = class extends BaseSolver {
  constructor(e36) {
    super(), this.input = e36, this.graph = e36.hyperGraphSolver.graph;
    const t2 = e36.inputSolvedRoutes, n2 = e36.hyperGraphSolver.connections;
    this.connections = n2, this.solvedRoutes = AY({ graph: this.graph, connections: this.connections, solvedRoutes: t2 }), this.maxAttemptsPerRegion = e36.MAX_ATTEMPTS_PER_REGION, this.maxSectionAttempts = e36.MAX_ATTEMPTS_PER_SECTION ?? 500, this.iterations += this.iterations * (e36.effort ?? 1), this.fractionToReplace = e36.FRACTION_TO_REPLACE ?? 0.2, this.alwaysRipConflicts = e36.alwaysRipConflicts ?? true;
  }
  graph;
  connections;
  solvedRoutes;
  activeSection = null;
  baselineSectionCost = 1 / 0;
  baselineGlobalCost = 1 / 0;
  regionAttemptCounts = new Map;
  sectionAttempts = 0;
  maxAttemptsPerRegion;
  maxSectionAttempts;
  fractionToReplace;
  alwaysRipConflicts;
  random = ((e36) => {
    let t2 = e36;
    return () => (t2 = 1664525 * t2 + 1013904223 >>> 0, t2 / 4294967295);
  })(31337);
  getSolverName() {
    return "HyperGraphSectionOptimizer";
  }
  getConstructorParams() {
    return { inputGraph: PY(this.graph), inputConnections: CY(this.connections), inputSolvedRoutes: this.solvedRoutes, expansionHopsFromCentralRegion: this.input.expansionHopsFromCentralRegion, maxAttemptsPerRegion: this.maxAttemptsPerRegion, maxSectionAttempts: this.maxSectionAttempts, effort: this.input.effort, fractionToReplace: this.fractionToReplace, alwaysRipConflicts: this.alwaysRipConflicts, ACCEPTABLE_COST: this.input.ACCEPTABLE_REGION_COST };
  }
  getOutput() {
    return this.solvedRoutes;
  }
  _setup() {
    this.beginSectionSolve();
  }
  visualize() {
    return this.activeSubSolver ? this.activeSubSolver.visualize() : { title: "HyperGraphSectionOptimizer", points: [], lines: [], rects: [], circles: [], texts: [], polygons: [], arrows: [] };
  }
  getCostOfRegionWithAttempts(e36) {
    const t2 = this.regionAttemptCounts.get(e36.regionId) ?? 0;
    return this.input.regionCost(e36) + 1e4 * t2;
  }
  computeCostOfSection({ section: e36, solvedRoutes: t2 }) {
    if (this.input.computeSolvedGraphCost)
      return this.input.computeSolvedGraphCost(t2);
    const n2 = this.input.createHyperGraphSolver({ inputGraph: e36.graph, inputConnections: e36.connections, inputSolvedRoutes: t2 });
    let o3 = 0;
    for (const e37 of n2.graph.regions)
      o3 += this.input.regionCost(e37);
    return o3;
  }
  computeSolvedGraphCost(e36) {
    if (this.input.computeSolvedGraphCost)
      return this.input.computeSolvedGraphCost(e36);
    const t2 = this.input.createHyperGraphSolver({ inputGraph: this.graph, inputConnections: this.connections, inputSolvedRoutes: e36 });
    let n2 = 0;
    for (const e37 of t2.graph.regions)
      n2 += this.input.regionCost(e37);
    return n2;
  }
  determineConnectionsToRip(e36, t2) {
    const n2 = e36.sectionRoutes.map((e37) => e37.globalConnection.connectionId);
    if (this.fractionToReplace >= 1)
      return new Set(n2);
    const o3 = [...n2];
    for (let e37 = o3.length - 1;e37 > 0; e37--) {
      const t3 = Math.floor(this.random() * (e37 + 1));
      [o3[e37], o3[t3]] = [o3[t3], o3[e37]];
    }
    const i3 = Math.max(1, Math.ceil(o3.length * this.fractionToReplace)), r3 = new Set(o3.slice(0, i3));
    if (!this.alwaysRipConflicts)
      return r3;
    const s2 = new Map(e36.graph.regions.map((e37) => [e37.regionId, e37]));
    for (const n3 of e36.sectionRoutes)
      for (const e37 of n3.sectionRoute.path) {
        if (!e37.lastPort || !e37.lastRegion)
          continue;
        const o4 = s2.get(e37.lastRegion.regionId);
        if (!o4)
          continue;
        t2.currentConnection = n3.globalConnection;
        const i4 = t2.getRipsRequiredForPortUsage(o4, e37.lastPort, e37.port);
        for (const e38 of i4) {
          const t3 = n3.globalConnection.connectionId, o5 = e38.connection.connectionId;
          r3.has(t3) || r3.has(o5) || r3.add(this.random() < 0.5 ? t3 : o5);
        }
      }
    return r3;
  }
  getNextCentralRegion() {
    let e36 = null, t2 = 1 / 0;
    for (const n2 of this.graph.regions) {
      if ((n2.assignments?.length ?? 0) === 0)
        continue;
      if ((this.regionAttemptCounts.get(n2.regionId) ?? 0) >= this.maxAttemptsPerRegion)
        continue;
      if (this.input.regionCost(n2) < this.input.ACCEPTABLE_REGION_COST)
        continue;
      const o3 = this.getCostOfRegionWithAttempts(n2);
      o3 >= t2 || (t2 = o3, e36 = n2);
    }
    return e36;
  }
  beginSectionSolve() {
    if (this.sectionAttempts >= this.maxSectionAttempts)
      return console.log(`Reached max section attempts (${this.maxSectionAttempts}), stopping optimization`), void (this.solved = true);
    const e36 = this.getNextCentralRegion();
    if (!e36)
      return void (this.solved = true);
    if (this.sectionAttempts++, this.activeSection = RY({ graph: this.graph, solvedRoutes: this.solvedRoutes, centralRegion: e36, expansionHopsFromCentralRegion: this.input.expansionHopsFromCentralRegion }), !this.activeSection)
      return;
    if (this.activeSection.connections.length === 0)
      return this.regionAttemptCounts.set(e36.regionId, (this.regionAttemptCounts.get(e36.regionId) ?? 0) + 1), void (this.activeSection = null);
    const t2 = this.activeSection.sectionRoutes.filter((e37) => e37.canRemainFixedInSectionSolve), n2 = this.input.createHyperGraphSolver({ inputGraph: this.activeSection.graph, inputConnections: this.activeSection.connections, inputSolvedRoutes: t2.map((e37) => e37.sectionRoute) }), o3 = this.determineConnectionsToRip(this.activeSection, n2);
    for (const e37 of this.activeSection.sectionRoutes)
      e37.canRemainFixedInSectionSolve || o3.add(e37.globalConnection.connectionId);
    const i3 = this.activeSection.sectionRoutes.filter((e37) => e37.canRemainFixedInSectionSolve && !o3.has(e37.globalConnection.connectionId)).map((e37) => e37.sectionRoute), r3 = [...i3, ...this.activeSection.sectionRoutes.filter((e37) => o3.has(e37.globalConnection.connectionId)).map((e37) => e37.sectionRoute)];
    this.baselineSectionCost = this.computeCostOfSection({ section: this.activeSection, solvedRoutes: r3 }), this.baselineGlobalCost = this.computeSolvedGraphCost(this.solvedRoutes), this.activeSubSolver = this.input.createHyperGraphSolver({ inputGraph: this.activeSection.graph, inputConnections: this.activeSection.connections, inputSolvedRoutes: i3 });
    for (const e37 of this.activeSubSolver.connections)
      e37.startRegion && e37.endRegion || console.error({ startRegion: e37.startRegion?.regionId, endRegion: e37.endRegion?.regionId });
  }
  _step() {
    if (!this.activeSubSolver)
      return void this.beginSectionSolve();
    if (this.activeSubSolver.step(), !this.activeSection)
      return;
    if (this.activeSubSolver.failed) {
      this.failedSubSolvers ??= [], this.failedSubSolvers.push(this.activeSubSolver);
      const e37 = this.regionAttemptCounts.get(this.activeSection.centralRegionId) ?? 0;
      return this.regionAttemptCounts.set(this.activeSection.centralRegionId, e37 + 1), this.activeSubSolver = null, this.activeSection = null, this.baselineSectionCost = 1 / 0, void (this.baselineGlobalCost = 1 / 0);
    }
    if (!this.activeSubSolver.solved)
      return;
    const e36 = this.activeSubSolver.solvedRoutes, t2 = this.computeCostOfSection({ section: this.activeSection, solvedRoutes: e36 }), n2 = ((e37) => {
      const { solvedRoutes: t3, section: n3, replacementSolvedRoutes: o4 } = e37, i4 = new Map(o4.map((e38) => [e38.connection.connectionId, e38]));
      return t3.map((e38) => {
        const t4 = n3.sectionRoutes.find((t5) => t5.globalConnection.connectionId === e38.connection.connectionId);
        if (!t4)
          return e38;
        const o5 = i4.get(e38.connection.connectionId);
        if (!o5)
          return e38;
        const r4 = [...e38.path.slice(0, t4.sectionStartIndex), ...o5.path, ...e38.path.slice(t4.sectionEndIndex + 1)].map((e39) => ({ port: e39.port, g: e39.g, h: e39.h, f: e39.f, hops: e39.hops, ripRequired: e39.ripRequired, lastPort: e39.lastPort, lastRegion: e39.lastRegion, nextRegion: e39.nextRegion }));
        for (let e39 = 0;e39 < r4.length; e39++)
          r4[e39].parent = e39 > 0 ? r4[e39 - 1] : undefined;
        return { connection: e38.connection, path: r4, requiredRip: e38.requiredRip || o5.requiredRip };
      });
    })({ solvedRoutes: this.solvedRoutes, section: this.activeSection, replacementSolvedRoutes: e36 }), o3 = this.computeSolvedGraphCost(n2), i3 = t2 <= this.baselineSectionCost, r3 = o3 < this.baselineGlobalCost;
    if (i3 && r3) {
      this.solvedRoutes = n2;
      const e37 = this.input.hyperGraphSolver;
      if (!e37)
        return;
      e37.solvedRoutes = AY({ graph: e37.graph, connections: e37.connections, solvedRoutes: this.solvedRoutes });
      for (const e38 of this.activeSection.sectionRegionIds)
        this.regionAttemptCounts.set(e38, 0);
      this.baselineSectionCost = t2, this.baselineGlobalCost = o3;
    } else {
      const e37 = this.regionAttemptCounts.get(this.activeSection.centralRegionId) ?? 0;
      this.regionAttemptCounts.set(this.activeSection.centralRegionId, e37 + 1);
    }
    this.activeSubSolver = null, this.activeSection = null, this.baselineSectionCost = 1 / 0, this.baselineGlobalCost = 1 / 0;
  }
};
function nX(e36, t2) {
  return Array.isArray(t2) ? [e36.a * t2[0] + e36.c * t2[1] + e36.e, e36.b * t2[0] + e36.d * t2[1] + e36.f] : { x: e36.a * t2.x + e36.c * t2.y + e36.e, y: e36.b * t2.x + e36.d * t2.y + e36.f };
}
function oX(e36) {
  return e36 === undefined;
}
function iX(e36, t2 = 0) {
  return { a: 1, c: 0, e: e36, b: 0, d: 1, f: t2 };
}
function rX(...e36) {
  const t2 = (e37, t3) => ({ a: e37.a * t3.a + e37.c * t3.b, c: e37.a * t3.c + e37.c * t3.d, e: e37.a * t3.e + e37.c * t3.f + e37.e, b: e37.b * t3.a + e37.d * t3.b, d: e37.b * t3.c + e37.d * t3.d, f: e37.b * t3.e + e37.d * t3.f + e37.f });
  switch ((e36 = Array.isArray(e36[0]) ? e36[0] : e36).length) {
    case 0:
      throw new Error("no matrices provided");
    case 1:
      return e36[0];
    case 2:
      return t2(e36[0], e36[1]);
    default: {
      const [n2, o3, ...i3] = e36;
      return rX(t2(n2, o3), ...i3);
    }
  }
}
var { cos: sX, sin: aX, PI: cX } = Math;
var hX = (e36) => ({ x: (e36.minX + e36.maxX) / 2, y: (e36.minY + e36.maxY) / 2 });
var dX = (e36, t2) => {
  const n2 = e36.regions.map((e37) => {
    const { bounds: n3, center: o4, ...i4 } = e37.d, r4 = [{ x: n3.minX, y: n3.minY }, { x: n3.maxX, y: n3.minY }, { x: n3.minX, y: n3.maxY }, { x: n3.maxX, y: n3.maxY }].map((e38) => nX(t2, e38)), s2 = { minX: Math.min(...r4.map((e38) => e38.x)), maxX: Math.max(...r4.map((e38) => e38.x)), minY: Math.min(...r4.map((e38) => e38.y)), maxY: Math.max(...r4.map((e38) => e38.y)) }, a3 = nX(t2, o4);
    return { ...e37, ports: [], d: { ...i4, bounds: s2, center: a3 } };
  }), o3 = new Map;
  for (let t3 = 0;t3 < e36.regions.length; t3++)
    o3.set(e36.regions[t3], n2[t3]);
  const i3 = e36.ports.map((e37) => {
    const n3 = nX(t2, e37.d), i4 = o3.get(e37.region1), r4 = o3.get(e37.region2), s2 = { ...e37, region1: i4, region2: r4, d: n3 };
    return i4.ports.push(s2), r4.ports.push(s2), s2;
  }), r3 = e36.jumperLocations?.map((e37) => {
    const n3 = nX(t2, e37.center), i4 = e37.padRegions.map((e38) => o3.get(e38)), r4 = nX(t2, { x: 1, y: 0 }), s2 = nX(t2, { x: 0, y: 0 }), a3 = r4.x - s2.x, c3 = r4.y - s2.y;
    return { center: n3, orientation: Math.abs(c3) > Math.abs(a3) ? e37.orientation === "horizontal" ? "vertical" : "horizontal" : e37.orientation, padRegions: i4 };
  });
  return { regions: n2, ports: i3, ...r3 && { jumperLocations: r3 } };
};
var uX = (e36, t2 = 0.8) => {
  let n2 = 0;
  for (let t3 = 0;t3 < e36.length; t3++)
    n2 = 17777 * e36.charCodeAt(t3) + ((n2 << 5) - n2);
  return `hsla(${Math.abs(n2) % 360}, 70%, 50%, ${t2})`;
};
var pX = (e36) => {
  const t2 = ((e37) => {
    const t3 = ((e38, t4) => {
      const n3 = { arrows: [], circles: [], title: "Jumper Graph", lines: [], points: [], rects: [], texts: [], polygons: [], coordinateSystem: "cartesian" };
      for (const t5 of e38.regions) {
        const { bounds: e39, isPad: o4, isThroughJumper: i3, isConnectionRegion: r3, polygon: s2 } = t5.d, a3 = (e39.minX + e39.maxX) / 2, c3 = (e39.minY + e39.maxY) / 2, l3 = e39.maxX - e39.minX, h2 = e39.maxY - e39.minY;
        let d2;
        if (d2 = r3 ? "rgba(255, 100, 255, 0.6)" : i3 ? "rgba(100, 200, 100, 0.5)" : o4 ? "rgba(255, 200, 100, 0.5)" : "rgba(200, 200, 255, 0.1)", s2 && s2.length >= 3) {
          const e40 = s2;
          n3.polygons.push({ points: e40, fill: d2 });
        } else
          n3.rects.push({ center: { x: a3, y: c3 }, width: l3 - 0.1, height: h2 - 0.1, fill: d2 });
      }
      if (!t4?.hidePortPoints)
        for (const t5 of e38.ports) {
          const e39 = t5.region1.regionId.split(":").pop() ?? t5.region1.regionId, o4 = t5.region2.regionId.split(":").pop() ?? t5.region2.regionId;
          n3.circles.push({ center: { x: t5.d.x, y: t5.d.y }, radius: 0.05, fill: "rgba(128, 128, 128, 0.5)", label: `${e39}-${o4}` });
        }
      if (!t4?.hideRegionPortLines)
        for (const t5 of e38.ports) {
          const e39 = { x: (t5.region1.d.bounds.minX + t5.region1.d.bounds.maxX) / 2, y: (t5.region1.d.bounds.minY + t5.region1.d.bounds.maxY) / 2 }, o4 = { x: (t5.region2.d.bounds.minX + t5.region2.d.bounds.maxX) / 2, y: (t5.region2.d.bounds.minY + t5.region2.d.bounds.maxY) / 2 };
          n3.lines.push({ points: [e39, { x: t5.d.x, y: t5.d.y }, o4], strokeColor: "rgba(100, 100, 100, 0.3)" });
        }
      if (t4?.connections && !t4?.hideConnectionLines)
        for (const e39 of t4.connections) {
          const { startRegion: t5, endRegion: o4 } = e39, i3 = { x: (t5.d.bounds.minX + t5.d.bounds.maxX) / 2, y: (t5.d.bounds.minY + t5.d.bounds.maxY) / 2 }, r3 = { x: (o4.d.bounds.minX + o4.d.bounds.maxX) / 2, y: (o4.d.bounds.minY + o4.d.bounds.maxY) / 2 }, s2 = (i3.x + r3.x) / 2, a3 = (i3.y + r3.y) / 2;
          n3.lines.push({ points: [i3, r3], strokeColor: "rgba(255, 50, 150, 0.8)", strokeDash: "3 3" }), n3.points.push({ x: s2, y: a3, color: "rgba(200, 0, 100, 1)", label: e39.connectionId });
        }
      return n3;
    })(e37.graph, { connections: e37.connections, ...e37.hideInitialGeometry ? { hideRegionPortLines: true, hideConnectionLines: true, hidePortPoints: true } : {} });
    if (!e37.hideInitialGeometry)
      for (const e38 of t3.polygons)
        e38.stroke = "rgba(128, 128, 128, 0.5)", e38.strokeWidth = 0.03;
    e37.title && (t3.title = e37.title);
    for (const n3 of e37.priorSolvedRoutes ?? []) {
      const e38 = n3.path.map((e39) => {
        const t4 = e39.port;
        return { x: t4.d.x, y: t4.d.y };
      });
      e38.length !== 0 && t3.lines.push({ points: e38, strokeColor: "rgba(80, 80, 80, 0.45)", strokeDash: "4 4" });
    }
    for (const n3 of e37.solvedRoutes) {
      const e38 = uX(n3.connection.connectionId), o4 = [];
      for (const e39 of n3.path) {
        const t4 = e39.port;
        o4.push({ x: t4.d.x, y: t4.d.y });
      }
      o4.length > 0 && t3.lines.push({ points: o4, strokeColor: e38 });
    }
    return t3;
  })({ graph: { regions: e36.graph.regions, ports: e36.graph.ports }, connections: e36.connections, solvedRoutes: e36.solvedRoutes, hideInitialGeometry: e36.iterations > 0 });
  if (e36.currentConnection && !e36.solved) {
    const n3 = uX(e36.currentConnection.connectionId), o4 = e36.currentConnection.startRegion, i3 = e36.currentConnection.endRegion;
    if (!o4?.d || !i3?.d)
      return t2;
    const r3 = { x: (o4.d.bounds.minX + o4.d.bounds.maxX) / 2, y: (o4.d.bounds.minY + o4.d.bounds.maxY) / 2 }, s2 = { x: (i3.d.bounds.minX + i3.d.bounds.maxX) / 2, y: (i3.d.bounds.minY + i3.d.bounds.maxY) / 2 };
    t2.lines.push({ points: [r3, s2], strokeColor: n3, strokeDash: "10 5" }), t2.points.push({ x: r3.x - 0.1, y: r3.y + 0.1, color: n3, label: [e36.currentConnection.connectionId, "start"].join(`
`) }), t2.points.push({ x: s2.x - 0.1, y: s2.y + 0.1, color: n3, label: [e36.currentConnection.connectionId, "end"].join(`
`) });
  }
  const n2 = e36.candidateQueue.peekMany(10);
  for (let e37 = 0;e37 < n2.length; e37++) {
    const o4 = n2[e37], i3 = o4.port, r3 = e37 === 0;
    t2.points.push({ x: i3.d.x, y: i3.d.y, color: r3 ? "green" : "rgba(128, 128, 128, 0.25)", label: [o4.port.portId, `g: ${o4.g.toFixed(2)}`, `h: ${o4.h.toFixed(2)}`, `f: ${o4.f.toFixed(2)}`].join(`
`) });
  }
  const o3 = n2[0];
  if (!e36.solved && o3 && e36.currentConnection) {
    const n3 = uX(e36.currentConnection.connectionId), i3 = [];
    let r3 = o3;
    for (;r3; ) {
      const e37 = r3.port;
      i3.unshift({ x: e37.d.x, y: e37.d.y }), r3 = r3.parent;
    }
    i3.length > 1 && t2.lines.push({ points: i3, strokeColor: n3 });
  }
  return t2;
};
var mX = 0.034685181009478865;
var gX = 0;
var fX = 4.072520483177124;
var _X = 0;
var yX = 35.38577539020022;
var bX = 0.5518001238069296;
var xX = class extends OY {
  getSolverName() {
    return "JumperGraphSolver";
  }
  UNIT_OF_COST = "hops";
  portUsagePenalty = mX;
  portUsagePenaltySq = gX;
  crossingPenalty = fX;
  crossingPenaltySq = _X;
  ripCost = yX;
  baseMaxIterations = 4000;
  additionalMaxIterationsPerConnection = 2000;
  additionalMaxIterationsPerCrossing = 2000;
  constructor(e36) {
    super({ greedyMultiplier: bX, rippingEnabled: true, ...e36 }), this.ripCost = e36.ripCost ?? this.ripCost, this.portUsagePenalty = e36.portUsagePenalty ?? this.portUsagePenalty, this.crossingPenalty = e36.crossingPenalty ?? this.crossingPenalty, this.baseMaxIterations = e36.baseMaxIterations ?? this.baseMaxIterations, this.additionalMaxIterationsPerConnection = e36.additionalMaxIterationsPerConnection ?? this.additionalMaxIterationsPerConnection;
    const t2 = function(e37, t3) {
      if (t3.length < 2)
        return 0;
      let n2 = 1 / 0, o3 = -1 / 0, i3 = 1 / 0, r3 = -1 / 0;
      for (const t4 of e37.regions) {
        const e38 = t4;
        e38.d?.bounds ? (n2 = Math.min(n2, e38.d.bounds.minX), o3 = Math.max(o3, e38.d.bounds.maxX), i3 = Math.min(i3, e38.d.bounds.minY), r3 = Math.max(r3, e38.d.bounds.maxY)) : e38.d?.center && (n2 = Math.min(n2, e38.d.center.x), o3 = Math.max(o3, e38.d.center.x), i3 = Math.min(i3, e38.d.center.y), r3 = Math.max(r3, e38.d.center.y));
      }
      const s2 = new Map;
      for (const t4 of e37.regions) {
        const e38 = t4;
        e38.d?.center && s2.set(t4.regionId, e38.d.center);
      }
      const a3 = [], c3 = 2 * (o3 - n2) + 2 * (r3 - i3);
      for (const e38 of t3) {
        let t4, c4;
        if ("startRegion" in e38 && e38.startRegion) {
          const { startRegion: n3, endRegion: o4 } = e38;
          t4 = n3.d?.center, c4 = o4.d?.center;
        } else
          "startRegionId" in e38 && (t4 = s2.get(e38.startRegionId), c4 = s2.get(e38.endRegionId));
        if (!t4 || !c4)
          continue;
        const l4 = DY(t4, n2, o3, i3, r3), h2 = DY(c4, n2, o3, i3, r3);
        a3.push([l4, h2]);
      }
      let l3 = 0;
      for (let e38 = 0;e38 < a3.length; e38++)
        for (let t4 = e38 + 1;t4 < a3.length; t4++)
          VY(a3[e38], a3[t4], c3) && l3++;
      return l3;
    }(this.graph, e36.inputConnections);
    this.MAX_ITERATIONS = this.baseMaxIterations + e36.inputConnections.length * this.additionalMaxIterationsPerConnection + t2 * this.additionalMaxIterationsPerCrossing, this.populateDistanceToEndMaps();
  }
  populateDistanceToEndMaps() {
    const e36 = new Set(this.connections.map((e37) => e37.endRegion));
    for (const t2 of e36) {
      const e37 = new Map, n2 = [];
      for (e37.set(t2.regionId, 0), n2.push({ region: t2, distance: 0 });n2.length > 0; ) {
        const { region: t3, distance: o3 } = n2.shift();
        for (const i3 of t3.ports) {
          const r3 = i3.region1 === t3 ? i3.region2 : i3.region1;
          e37.has(r3.regionId) || (e37.set(r3.regionId, o3 + 1), n2.push({ region: r3, distance: o3 + 1 }));
        }
      }
      for (const n3 of this.graph.ports) {
        n3.distanceToEndMap || (n3.distanceToEndMap = {});
        const o3 = e37.get(n3.region1.regionId) ?? 1 / 0, i3 = e37.get(n3.region2.regionId) ?? 1 / 0;
        n3.distanceToEndMap[t2.regionId] = Math.min(o3, i3);
      }
    }
  }
  estimateCostToEnd(e36) {
    const t2 = this.currentEndRegion.regionId;
    return e36.distanceToEndMap[t2];
  }
  getPortUsagePenalty(e36) {
    const t2 = e36.ripCount ?? 0;
    return t2 * this.portUsagePenalty + t2 * this.portUsagePenaltySq;
  }
  isTransitionAllowed(e36, t2, n2) {
    if (!e36.d.isPad)
      return true;
    const o3 = (t3) => {
      const n3 = t3.region1 === e36 ? t3.region2 : t3.region1;
      return Boolean(n3.d.isThroughJumper);
    };
    return o3(t2) || o3(n2);
  }
  computeIncreasedRegionCostIfPortsAreUsed(e36, t2, n2) {
    if (e36.d.isPad) {
      const t3 = (e36.assignments ?? []).filter((e37) => e37.connection.mutuallyConnectedNetworkId !== this.currentConnection.mutuallyConnectedNetworkId).length;
      return t3 > 0 ? t3 * this.crossingPenalty + t3 * this.crossingPenaltySq : 0;
    }
    const o3 = function(e37, t3, n3) {
      const o4 = BY(e37), i3 = [FY(t3, e37), FY(n3, e37)];
      let r3 = 0;
      const s2 = e37.assignments ?? [];
      for (const t4 of s2)
        VY(i3, [FY(t4.regionPort1, e37), FY(t4.regionPort2, e37)], o4) && r3++;
      return r3;
    }(e36, t2, n2);
    return o3 * this.crossingPenalty + o3 * this.crossingPenaltySq;
  }
  getRipsRequiredForPortUsage(e36, t2, n2) {
    if (e36.d.isPad) {
      return (e36.assignments ?? []).filter((e37) => e37.connection.mutuallyConnectedNetworkId !== this.currentConnection.mutuallyConnectedNetworkId);
    }
    const o3 = function(e37, t3, n3) {
      const o4 = BY(e37), i4 = [FY(t3, e37), FY(n3, e37)], r3 = [], s2 = e37.assignments ?? [];
      for (const t4 of s2)
        VY(i4, [FY(t4.regionPort1, e37), FY(t4.regionPort2, e37)], o4) && r3.push(t4);
      return r3;
    }(e36, t2, n2), i3 = o3.filter((e37) => e37.connection.mutuallyConnectedNetworkId !== this.currentConnection.mutuallyConnectedNetworkId);
    if (!e36.d.isThroughJumper)
      return i3;
    for (const t3 of e36.assignments ?? [])
      t3.connection.mutuallyConnectedNetworkId !== this.currentConnection.mutuallyConnectedNetworkId && i3.push(t3);
    return i3;
  }
  isRipRequiredForPortUsage(e36, t2, n2) {
    if (!e36.d.isThroughJumper && !e36.d.isPad)
      return false;
    for (const t3 of e36.assignments ?? [])
      if (t3.connection.mutuallyConnectedNetworkId !== this.currentConnection.mutuallyConnectedNetworkId)
        return true;
    return false;
  }
  routeSolvedHook(e36) {}
  routeStartedHook(e36) {}
  visualize() {
    return pX(this);
  }
};
var vX = { padWidth: 0.8, outerPadHeight: 0.5, innerPadHeight: 0.4, leftPadCenterX: -0.9, rightPadCenterX: 0.9, row1CenterY: -1.2, row2CenterY: -0.4, row3CenterY: 0.4, row4CenterY: 1.2 };
var IX = ({ cols: e36, rows: t2, marginX: n2, marginY: o3, innerColChannelPointCount: i3 = 1, innerRowChannelPointCount: r3 = 1, regionsBetweenPads: s2 = false, outerPaddingX: a3 = 0.5, outerPaddingY: c3 = 0.5, outerChannelXPointCount: l3, outerChannelYPointCount: h2, orientation: d2 = "vertical", center: u2, bounds: p3, parallelTracesUnderJumperCount: m2 = 2 }) => {
  const g2 = [], f2 = [], { padWidth: _2, outerPadHeight: y2, innerPadHeight: b2, leftPadCenterX: x2, rightPadCenterX: v2, row1CenterY: I2, row2CenterY: S2, row3CenterY: C, row4CenterY: P } = vX, M = _2 / 2, w = y2 / 2, N = b2 / 2, R2 = v2 - x2 + _2, T2 = R2 + n2, E3 = P - I2 + y2, A2 = E3 + o3;
  let O2 = a3, k2 = c3;
  if (p3) {
    const i4 = e36 * R2 + (e36 - 1) * n2, r4 = t2 * E3 + (t2 - 1) * o3;
    O2 = ((d2 === "horizontal" ? p3.maxY - p3.minY : p3.maxX - p3.minX) - i4) / 2, k2 = ((d2 === "horizontal" ? p3.maxX - p3.minX : p3.maxY - p3.minY) - r4) / 2;
  }
  const D2 = l3 ?? Math.max(1, Math.floor(O2 / 0.4)), L2 = h2 ?? Math.max(1, Math.floor(k2 / 0.4)), z2 = [], B2 = [], F2 = (e37, t3, n3, o4) => ({ regionId: e37, ports: [], d: { bounds: t3, center: hX(t3), isPad: n3, isThroughJumper: o4 } }), j2 = (e37, t3, n3) => {
    const o4 = t3.d.bounds, i4 = n3.d.bounds;
    let r4, s3;
    Math.abs(o4.maxX - i4.minX) < 0.001 ? (r4 = o4.maxX, s3 = (Math.max(o4.minY, i4.minY) + Math.min(o4.maxY, i4.maxY)) / 2) : Math.abs(o4.minX - i4.maxX) < 0.001 ? (r4 = o4.minX, s3 = (Math.max(o4.minY, i4.minY) + Math.min(o4.maxY, i4.maxY)) / 2) : Math.abs(o4.maxY - i4.minY) < 0.001 ? (r4 = (Math.max(o4.minX, i4.minX) + Math.min(o4.maxX, i4.maxX)) / 2, s3 = o4.maxY) : (r4 = (Math.max(o4.minX, i4.minX) + Math.min(o4.maxX, i4.maxX)) / 2, s3 = o4.minY);
    const a4 = { portId: e37, region1: t3, region2: n3, d: { x: r4, y: s3 } };
    return t3.ports.push(a4), n3.ports.push(a4), a4;
  }, $2 = (e37, t3, n3, o4) => {
    if (o4 <= 0)
      return [];
    if (o4 === 1)
      return [j2(e37, t3, n3)];
    const i4 = t3.d.bounds, r4 = n3.d.bounds, s3 = [];
    let a4, c4, l4, h3;
    Math.abs(i4.maxX - r4.minX) < 0.001 ? (a4 = true, c4 = i4.maxX, l4 = Math.max(i4.minY, r4.minY), h3 = Math.min(i4.maxY, r4.maxY)) : Math.abs(i4.minX - r4.maxX) < 0.001 ? (a4 = true, c4 = i4.minX, l4 = Math.max(i4.minY, r4.minY), h3 = Math.min(i4.maxY, r4.maxY)) : Math.abs(i4.maxY - r4.minY) < 0.001 ? (a4 = false, c4 = i4.maxY, l4 = Math.max(i4.minX, r4.minX), h3 = Math.min(i4.maxX, r4.maxX)) : (a4 = false, c4 = i4.minY, l4 = Math.max(i4.minX, r4.minX), h3 = Math.min(i4.maxX, r4.maxX));
    for (let i5 = 0;i5 < o4; i5++) {
      const r5 = l4 + (i5 + 0.5) / o4 * (h3 - l4), d3 = { portId: `${e37}:${i5}`, region1: t3, region2: n3, d: { x: a4 ? c4 : r5, y: a4 ? r5 : c4 } };
      t3.ports.push(d3), n3.ports.push(d3), s3.push(d3);
    }
    return s3;
  };
  for (let n3 = 0;n3 < t2; n3++) {
    z2[n3] = [];
    for (let a4 = 0;a4 < e36; a4++) {
      const c4 = `cell_${n3}_${a4}`, l4 = a4 * T2, h3 = -n3 * A2, d3 = l4 + x2, u3 = h3 + I2, p4 = l4 + x2, _3 = h3 + S2, y3 = l4 + x2, b3 = h3 + C, R3 = l4 + x2, E4 = h3 + P, Y3 = l4 + v2, X2 = h3 + P, H2 = l4 + v2, V2 = h3 + C, W2 = l4 + v2, G2 = h3 + S2, U2 = l4 + v2, Z2 = h3 + I2, q2 = (e37, t3, n4) => ({ minX: e37 - M, maxX: e37 + M, minY: t3 - n4, maxY: t3 + n4 }), J2 = q2(d3, u3, w), Q2 = q2(p4, _3, N), K2 = q2(y3, b3, N), ee2 = q2(R3, E4, w), te2 = q2(Y3, X2, w), ne2 = q2(H2, V2, N), oe2 = q2(W2, G2, N), ie2 = q2(U2, Z2, w), re2 = { minX: J2.maxX, maxX: ie2.minX, minY: J2.minY, maxY: ee2.maxY }, se2 = 0.3, ae2 = { minX: d3, maxX: U2, minY: u3 - se2 / 2, maxY: u3 + se2 / 2 }, ce2 = { minX: p4, maxX: W2, minY: _3 - se2 / 2, maxY: _3 + se2 / 2 }, le2 = { minX: y3, maxX: H2, minY: b3 - se2 / 2, maxY: b3 + se2 / 2 }, he2 = { minX: R3, maxX: Y3, minY: E4 - se2 / 2, maxY: E4 + se2 / 2 }, de2 = J2.minX, ue2 = ie2.maxX, pe2 = J2.minY, me2 = ee2.maxY, ge2 = F2(`${c4}:pad1`, J2, true), fe2 = F2(`${c4}:pad2`, Q2, true), _e2 = F2(`${c4}:pad3`, K2, true), ye2 = F2(`${c4}:pad4`, ee2, true), be2 = F2(`${c4}:pad5`, te2, true), xe2 = F2(`${c4}:pad6`, ne2, true), ve2 = F2(`${c4}:pad7`, oe2, true), Ie2 = F2(`${c4}:pad8`, ie2, true), Se2 = F2(`${c4}:underjumper`, re2, false), Ce2 = F2(`${c4}:throughjumper1`, ae2, false, true), Pe2 = F2(`${c4}:throughjumper2`, ce2, false, true), Me2 = F2(`${c4}:throughjumper3`, le2, false, true), we2 = F2(`${c4}:throughjumper4`, he2, false, true);
      g2.push(ge2, fe2, _e2, ye2, be2, xe2, ve2, Ie2, Se2, Ce2, Pe2, Me2, we2);
      const Ne2 = (d3 + U2) / 2, Re2 = (u3 + E4) / 2;
      B2.push({ center: { x: Ne2, y: Re2 }, orientation: "vertical", padRegions: [ge2, fe2, _e2, ye2, be2, xe2, ve2, Ie2] });
      let Te2 = null, Ee2 = null, Ae2 = null, Oe2 = null, ke2 = null, De2 = null;
      s2 && (Te2 = F2(`${c4}:L-BP12`, { minX: J2.minX, maxX: J2.maxX, minY: J2.maxY, maxY: Q2.minY }, false), Ee2 = F2(`${c4}:L-BP23`, { minX: Q2.minX, maxX: Q2.maxX, minY: Q2.maxY, maxY: K2.minY }, false), Ae2 = F2(`${c4}:L-BP34`, { minX: K2.minX, maxX: K2.maxX, minY: K2.maxY, maxY: ee2.minY }, false), Oe2 = F2(`${c4}:R-BP87`, { minX: ie2.minX, maxX: ie2.maxX, minY: ie2.maxY, maxY: oe2.minY }, false), ke2 = F2(`${c4}:R-BP76`, { minX: oe2.minX, maxX: oe2.maxX, minY: oe2.maxY, maxY: ne2.minY }, false), De2 = F2(`${c4}:R-BP65`, { minX: ne2.minX, maxX: ne2.maxX, minY: ne2.maxY, maxY: te2.minY }, false), g2.push(Te2, Ee2, Ae2, Oe2, ke2, De2));
      const Le2 = a4 === 0, ze2 = n3 === t2 - 1, Be2 = a4 === e36 - 1;
      let Fe2;
      if (Be2)
        Fe2 = ue2 + O2;
      else {
        Fe2 = (a4 + 1) * T2 + x2 - M;
      }
      let je = null;
      n3 === 0 && (je = F2(`${c4}:T`, { minX: Le2 ? de2 - O2 : de2, maxX: Fe2, minY: me2, maxY: me2 + k2 }, false), g2.push(je));
      let $e2 = null;
      $e2 = F2(`${c4}:B`, { minX: Le2 ? de2 - O2 : de2, maxX: Fe2, minY: pe2 - (ze2 ? k2 : o3), maxY: pe2 }, false), g2.push($e2);
      let Ye2 = null;
      Le2 && (Ye2 = F2(`${c4}:L`, { minX: de2 - O2, maxX: de2, minY: pe2, maxY: me2 }, false), g2.push(Ye2));
      const Xe2 = F2(`${c4}:R`, { minX: ue2, maxX: Fe2, minY: pe2, maxY: me2 }, false);
      if (g2.push(Xe2), z2[n3][a4] = { pad1: ge2, pad2: fe2, pad3: _e2, pad4: ye2, pad5: be2, pad6: xe2, pad7: ve2, pad8: Ie2, underjumper: Se2, throughjumper1: Ce2, throughjumper2: Pe2, throughjumper3: Me2, throughjumper4: we2, top: je, bottom: $e2, left: Ye2, right: Xe2, leftBP12: Te2, leftBP23: Ee2, leftBP34: Ae2, rightBP87: Oe2, rightBP76: ke2, rightBP65: De2 }, je)
        if (Ye2 && f2.push(...$2(`${c4}:T-L`, je, Ye2, D2)), f2.push(...$2(`${c4}:T-R`, je, Xe2, Be2 ? D2 : i3)), f2.push(j2(`${c4}:T-P4`, je, ye2)), f2.push(j2(`${c4}:T-P5`, je, be2)), s2) {
          const e37 = Se2.d.bounds, t3 = (e37.maxX - e37.minX) / (m2 + 1);
          for (let n4 = 1;n4 <= m2; n4++) {
            const o4 = { portId: `${c4}:T-UJ${n4}`, region1: je, region2: Se2, d: { x: e37.minX + t3 * n4, y: e37.maxY } };
            je.ports.push(o4), Se2.ports.push(o4), f2.push(o4);
          }
        } else
          f2.push(j2(`${c4}:T-UJ`, je, Se2));
      if ($e2)
        if (Ye2 && f2.push(...$2(`${c4}:B-L`, $e2, Ye2, D2)), f2.push(...$2(`${c4}:B-R`, $e2, Xe2, Be2 ? D2 : i3)), f2.push(j2(`${c4}:B-P1`, $e2, ge2)), f2.push(j2(`${c4}:B-P8`, $e2, Ie2)), s2) {
          const e37 = Se2.d.bounds, t3 = (e37.maxX - e37.minX) / (m2 + 1);
          for (let n4 = 1;n4 <= m2; n4++) {
            const o4 = { portId: `${c4}:B-UJ${n4}`, region1: $e2, region2: Se2, d: { x: e37.minX + t3 * n4, y: e37.minY } };
            $e2.ports.push(o4), Se2.ports.push(o4), f2.push(o4);
          }
        } else
          f2.push(j2(`${c4}:B-UJ`, $e2, Se2));
      Ye2 && (f2.push(j2(`${c4}:L-P1`, Ye2, ge2)), f2.push(j2(`${c4}:L-P2`, Ye2, fe2)), f2.push(j2(`${c4}:L-P3`, Ye2, _e2)), f2.push(j2(`${c4}:L-P4`, Ye2, ye2))), f2.push(j2(`${c4}:R-P5`, Xe2, be2)), f2.push(j2(`${c4}:R-P6`, Xe2, xe2)), f2.push(j2(`${c4}:R-P7`, Xe2, ve2)), f2.push(j2(`${c4}:R-P8`, Xe2, Ie2)), s2 && (Ye2 && (f2.push(j2(`${c4}:L-BP12`, Ye2, Te2)), f2.push(j2(`${c4}:L-BP23`, Ye2, Ee2)), f2.push(j2(`${c4}:L-BP34`, Ye2, Ae2))), f2.push(j2(`${c4}:UJ-LBP12`, Te2, Se2)), f2.push(j2(`${c4}:UJ-LBP23`, Ee2, Se2)), f2.push(j2(`${c4}:UJ-LBP34`, Ae2, Se2)), f2.push(j2(`${c4}:R-BP87`, Xe2, Oe2)), f2.push(j2(`${c4}:R-BP76`, Xe2, ke2)), f2.push(j2(`${c4}:R-BP65`, Xe2, De2)), f2.push(j2(`${c4}:UJ-RBP87`, Oe2, Se2)), f2.push(j2(`${c4}:UJ-RBP76`, ke2, Se2)), f2.push(j2(`${c4}:UJ-RBP65`, De2, Se2)));
      const He2 = { portId: `${c4}:TJ1-P1`, region1: Ce2, region2: ge2, d: { x: d3, y: u3 } };
      Ce2.ports.push(He2), ge2.ports.push(He2), f2.push(He2);
      const Ve2 = { portId: `${c4}:TJ1-P8`, region1: Ce2, region2: Ie2, d: { x: U2, y: Z2 } };
      Ce2.ports.push(Ve2), Ie2.ports.push(Ve2), f2.push(Ve2);
      const We2 = { portId: `${c4}:TJ2-P2`, region1: Pe2, region2: fe2, d: { x: p4, y: _3 } };
      Pe2.ports.push(We2), fe2.ports.push(We2), f2.push(We2);
      const Ge2 = { portId: `${c4}:TJ2-P7`, region1: Pe2, region2: ve2, d: { x: W2, y: G2 } };
      Pe2.ports.push(Ge2), ve2.ports.push(Ge2), f2.push(Ge2);
      const Ue2 = { portId: `${c4}:TJ3-P3`, region1: Me2, region2: _e2, d: { x: y3, y: b3 } };
      Me2.ports.push(Ue2), _e2.ports.push(Ue2), f2.push(Ue2);
      const Ze2 = { portId: `${c4}:TJ3-P6`, region1: Me2, region2: xe2, d: { x: H2, y: V2 } };
      Me2.ports.push(Ze2), xe2.ports.push(Ze2), f2.push(Ze2);
      const qe2 = { portId: `${c4}:TJ4-P4`, region1: we2, region2: ye2, d: { x: R3, y: E4 } };
      we2.ports.push(qe2), ye2.ports.push(qe2), f2.push(qe2);
      const Je2 = { portId: `${c4}:TJ4-P5`, region1: we2, region2: be2, d: { x: Y3, y: X2 } };
      if (we2.ports.push(Je2), be2.ports.push(Je2), f2.push(Je2), a4 > 0) {
        const e37 = z2[n3][a4 - 1];
        f2.push(j2(`cell_${n3}_${a4 - 1}->cell_${n3}_${a4}:R-P1`, e37.right, ge2)), f2.push(j2(`cell_${n3}_${a4 - 1}->cell_${n3}_${a4}:R-P2`, e37.right, fe2)), f2.push(j2(`cell_${n3}_${a4 - 1}->cell_${n3}_${a4}:R-P3`, e37.right, _e2)), f2.push(j2(`cell_${n3}_${a4 - 1}->cell_${n3}_${a4}:R-P4`, e37.right, ye2)), s2 && (f2.push(j2(`cell_${n3}_${a4 - 1}->cell_${n3}_${a4}:R-LBP12`, e37.right, Te2)), f2.push(j2(`cell_${n3}_${a4 - 1}->cell_${n3}_${a4}:R-LBP23`, e37.right, Ee2)), f2.push(j2(`cell_${n3}_${a4 - 1}->cell_${n3}_${a4}:R-LBP34`, e37.right, Ae2))), je && e37.top && f2.push(...$2(`cell_${n3}_${a4 - 1}->cell_${n3}_${a4}:T-T`, e37.top, je, L2)), $e2 && e37.bottom && f2.push(...$2(`cell_${n3}_${a4 - 1}->cell_${n3}_${a4}:B-B`, e37.bottom, $e2, ze2 ? L2 : r3));
      }
      if (n3 > 0) {
        const e37 = z2[n3 - 1][a4];
        if (Ye2 && f2.push(...$2(`cell_${n3 - 1}_${a4}->cell_${n3}_${a4}:B-L`, e37.bottom, Ye2, D2)), f2.push(j2(`cell_${n3 - 1}_${a4}->cell_${n3}_${a4}:B-P4`, e37.bottom, ye2)), s2) {
          const t3 = Se2.d.bounds, o4 = (t3.maxX - t3.minX) / (m2 + 1);
          for (let i4 = 1;i4 <= m2; i4++) {
            const r4 = t3.minX + o4 * i4, s3 = { portId: `cell_${n3 - 1}_${a4}->cell_${n3}_${a4}:B-UJ${i4}`, region1: e37.bottom, region2: Se2, d: { x: r4, y: t3.maxY } };
            e37.bottom.ports.push(s3), Se2.ports.push(s3), f2.push(s3);
          }
        } else
          f2.push(j2(`cell_${n3 - 1}_${a4}->cell_${n3}_${a4}:B-UJ`, e37.bottom, Se2));
        f2.push(j2(`cell_${n3 - 1}_${a4}->cell_${n3}_${a4}:B-P5`, e37.bottom, be2)), f2.push(...$2(`cell_${n3 - 1}_${a4}->cell_${n3}_${a4}:B-R`, e37.bottom, Xe2, Be2 ? D2 : i3));
      }
    }
  }
  let Y2 = { regions: g2, ports: f2, jumperLocations: B2 };
  const X = d2 === "horizontal";
  if (X || u2 !== undefined || p3 !== undefined) {
    const e37 = WY(Y2.regions), t3 = hX(e37), n3 = [];
    let o4;
    o4 = u2 || (p3 ? hX(p3) : t3), n3.push(iX(o4.x, o4.y)), X && n3.push(function(e38, t4, n4) {
      const o5 = sX(e38), i5 = aX(e38), r4 = { a: o5, c: -i5, e: 0, b: i5, d: o5, f: 0 };
      return oX(t4) || oX(n4) ? r4 : rX([iX(t4, n4), r4, iX(-t4, -n4)]);
    }(-Math.PI / 2)), n3.push(iX(-t3.x, -t3.y));
    const i4 = function(...e38) {
      return rX(...e38);
    }(...n3);
    Y2 = dX(Y2, i4);
  }
  return Y2;
};
var SX = true;
var CX = { CCW: -1, CW: 1, NOT_ORIENTABLE: 0 };
var PX = 2 * Math.PI;
var MX = Object.freeze({ __proto__: null, BOUNDARY: 2, CCW: SX, CONTAINS: 3, CW: false, END_VERTEX: 2, INSIDE: 1, INTERLACE: 4, NOT_VERTEX: 0, ORIENTATION: CX, OUTSIDE: 0, OVERLAP_OPPOSITE: 2, OVERLAP_SAME: 1, PIx2: PX, START_VERTEX: 1 });
var wX = 0.000001;
function NX(e36) {
  wX = e36;
}
function RX() {
  return wX;
}
function TX(e36) {
  return e36 < wX && e36 > -wX;
}
function EX(e36, t2) {
  return e36 - t2 < wX && e36 - t2 > -wX;
}
function AX(e36, t2) {
  return e36 - t2 > wX;
}
function OX(e36, t2) {
  return e36 - t2 < -wX;
}
var kX = { Utils: Object.freeze({ __proto__: null, DECIMALS: 3, EQ: EX, EQ_0: TX, GE: function(e36, t2) {
  return e36 - t2 > -wX;
}, GT: AX, LE: function(e36, t2) {
  return e36 - t2 < wX;
}, LT: OX, getTolerance: RX, setTolerance: NX }), Errors: undefined, Matrix: undefined, Planar_set: undefined, Point: undefined, Vector: undefined, Line: undefined, Circle: undefined, Segment: undefined, Arc: undefined, Box: undefined, Edge: undefined, Face: undefined, Ray: undefined, Ray_shooting: undefined, Multiline: undefined, Polygon: undefined, Distance: undefined, Inversion: undefined };
for (let e36 in MX)
  kX[e36] = MX[e36];
Object.defineProperty(kX, "DP_TOL", { get: function() {
  return RX();
}, set: function(e36) {
  NX(e36);
} });
var DX = class {
  static get ILLEGAL_PARAMETERS() {
    return new ReferenceError("Illegal Parameters");
  }
  static get ZERO_DIVISION() {
    return new Error("Zero division");
  }
  static get UNRESOLVED_BOUNDARY_CONFLICT() {
    return new Error("Unresolved boundary conflict in boolean operation");
  }
  static get INFINITE_LOOP() {
    return new Error("Infinite loop");
  }
  static get CANNOT_COMPLETE_BOOLEAN_OPERATION() {
    return new Error("Cannot complete boolean operation");
  }
  static get CANNOT_INVOKE_ABSTRACT_METHOD() {
    return new Error("Abstract method cannot be invoked");
  }
  static get OPERATION_IS_NOT_SUPPORTED() {
    return new Error("Operation is not supported");
  }
  static get UNSUPPORTED_SHAPE_TYPE() {
    return new Error("Unsupported shape type");
  }
};
kX.Errors = DX;
var LX = class {
  constructor(e36, t2) {
    this.first = e36, this.last = t2 || this.first;
  }
  [Symbol.iterator]() {
    let e36;
    return { next: () => (e36 = e36 ? e36.next : this.first, { value: e36, done: e36 === undefined }) };
  }
  get size() {
    let e36 = 0;
    for (let t2 of this)
      e36++;
    return e36;
  }
  toArray(e36 = undefined, t2 = undefined) {
    let n2 = [], o3 = e36 || this.first, i3 = t2 || this.last, r3 = o3;
    if (r3 === undefined)
      return n2;
    do {
      n2.push(r3), r3 = r3.next;
    } while (r3 !== i3.next);
    return n2;
  }
  append(e36) {
    return this.isEmpty() ? this.first = e36 : (e36.prev = this.last, this.last.next = e36), this.last = e36, this.last.next = undefined, this.first.prev = undefined, this;
  }
  insert(e36, t2) {
    if (this.isEmpty())
      this.first = e36, this.last = e36;
    else if (t2 == null)
      e36.next = this.first, this.first.prev = e36, this.first = e36;
    else {
      let n2 = t2.next;
      t2.next = e36, n2 && (n2.prev = e36), e36.prev = t2, e36.next = n2, this.last === t2 && (this.last = e36);
    }
    return this.last.next = undefined, this.first.prev = undefined, this;
  }
  remove(e36) {
    return e36 === this.first && e36 === this.last ? (this.first = undefined, this.last = undefined) : (e36.prev && (e36.prev.next = e36.next), e36.next && (e36.next.prev = e36.prev), e36 === this.first && (this.first = e36.next), e36 === this.last && (this.last = e36.prev)), this;
  }
  isEmpty() {
    return this.first === undefined;
  }
  static testInfiniteLoop(e36) {
    let t2 = e36, n2 = e36;
    do {
      if (t2 != e36 && t2 === n2)
        throw DX.INFINITE_LOOP;
      t2 = t2.next, n2 = n2.next.next;
    } while (t2 != e36);
  }
};
var zX = { stroke: "black" };
var BX = class {
  constructor(e36 = zX) {
    for (const t2 in e36)
      this[t2] = e36[t2];
    this.stroke = e36.stroke ?? zX.stroke;
  }
  toAttributesString() {
    return Object.keys(this).reduce((e36, t2) => e36 + (this[t2] !== undefined ? this.toAttrString(t2, this[t2]) : ""), "");
  }
  toAttrString(e36, t2) {
    const n2 = e36 === "className" ? "class" : this.convertCamelToKebabCase(e36);
    return t2 === null ? `${n2} ` : `${n2}="${t2.toString()}" `;
  }
  convertCamelToKebabCase(e36) {
    return e36.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g).join("-").toLowerCase();
  }
};
function FX(e36) {
  return new BX(e36).toAttributesString();
}
function jX(e36, t2) {
  let n2 = [], [o3, i3, r3] = e36.standard, [s2, a3, c3] = t2.standard, l3 = o3 * a3 - i3 * s2, h2 = r3 * a3 - i3 * c3, d2 = o3 * c3 - r3 * s2;
  if (!kX.Utils.EQ_0(l3)) {
    let e37, t3;
    i3 === 0 ? (e37 = r3 / o3, t3 = d2 / l3) : a3 === 0 ? (e37 = c3 / s2, t3 = d2 / l3) : o3 === 0 ? (e37 = h2 / l3, t3 = r3 / i3) : s2 === 0 ? (e37 = h2 / l3, t3 = c3 / a3) : (e37 = h2 / l3, t3 = d2 / l3), n2.push(new kX.Point(e37, t3));
  }
  return n2;
}
function $X(e36, t2) {
  let n2 = [], o3 = t2.pc.projectionOn(e36), i3 = t2.pc.distanceTo(o3)[0];
  if (kX.Utils.EQ(i3, t2.r))
    n2.push(o3);
  else if (kX.Utils.LT(i3, t2.r)) {
    let r3, s2, a3 = Math.sqrt(t2.r * t2.r - i3 * i3);
    r3 = e36.norm.rotate90CCW().multiply(a3), s2 = o3.translate(r3), n2.push(s2), r3 = e36.norm.rotate90CW().multiply(a3), s2 = o3.translate(r3), n2.push(s2);
  }
  return n2;
}
function YX(e36, t2) {
  let n2 = [];
  for (let o3 of t2.toSegments()) {
    let t3 = HX(o3, e36);
    for (let e37 of t3)
      cH(e37, n2) || n2.push(e37);
  }
  return n2;
}
function XX(e36, t2) {
  let n2 = [];
  if (YX(e36, t2.box).length === 0)
    return n2;
  let o3 = $X(e36, new kX.Circle(t2.pc, t2.r));
  for (let e37 of o3)
    e37.on(t2) && n2.push(e37);
  return n2;
}
function HX(e36, t2) {
  let n2 = [];
  return e36.ps.on(t2) && n2.push(e36.ps), e36.pe.on(t2) && !e36.isZeroLength() && n2.push(e36.pe), n2.length > 0 || e36.isZeroLength() || e36.ps.leftTo(t2) && e36.pe.leftTo(t2) || !e36.ps.leftTo(t2) && !e36.pe.leftTo(t2) ? n2 : jX(new kX.Line(e36.ps, e36.pe), t2);
}
function VX(e36, t2) {
  let n2 = [];
  if (e36.isZeroLength())
    return e36.ps.on(t2) && n2.push(e36.ps), n2;
  if (t2.isZeroLength())
    return t2.ps.on(e36) && n2.push(t2.ps), n2;
  let o3 = new kX.Line(e36.ps, e36.pe), i3 = new kX.Line(t2.ps, t2.pe);
  if (o3.incidentTo(i3))
    e36.ps.on(t2) && n2.push(e36.ps), e36.pe.on(t2) && n2.push(e36.pe), !t2.ps.on(e36) || t2.ps.equalTo(e36.ps) || t2.ps.equalTo(e36.pe) || n2.push(t2.ps), !t2.pe.on(e36) || t2.pe.equalTo(e36.ps) || t2.pe.equalTo(e36.pe) || n2.push(t2.pe);
  else {
    let r3 = jX(o3, i3);
    r3.length > 0 && WX(r3[0], e36) && WX(r3[0], t2) && n2.push(r3[0]);
  }
  return n2;
}
function WX(e36, t2) {
  const n2 = t2.box;
  return kX.Utils.LE(e36.x, n2.xmax) && kX.Utils.GE(e36.x, n2.xmin) && kX.Utils.LE(e36.y, n2.ymax) && kX.Utils.GE(e36.y, n2.ymin);
}
function GX(e36, t2) {
  let n2 = [];
  if (e36.isZeroLength()) {
    let [o4, i3] = e36.ps.distanceTo(t2.pc);
    return kX.Utils.EQ(o4, t2.r) && n2.push(e36.ps), n2;
  }
  let o3 = $X(new kX.Line(e36.ps, e36.pe), t2);
  for (let t3 of o3)
    t3.on(e36) && n2.push(t3);
  return n2;
}
function UX(e36, t2) {
  let n2 = [];
  if (e36.isZeroLength())
    return e36.ps.on(t2) && n2.push(e36.ps), n2;
  let o3 = $X(new kX.Line(e36.ps, e36.pe), new kX.Circle(t2.pc, t2.r));
  for (let i3 of o3)
    i3.on(e36) && i3.on(t2) && n2.push(i3);
  return n2;
}
function ZX(e36, t2) {
  let n2 = [], o3 = new kX.Vector(e36.pc, t2.pc), i3 = e36.r, r3 = t2.r;
  if (kX.Utils.EQ_0(i3) || kX.Utils.EQ_0(r3))
    return n2;
  if (kX.Utils.EQ_0(o3.x) && kX.Utils.EQ_0(o3.y) && kX.Utils.EQ(i3, r3))
    return n2.push(e36.pc.translate(-i3, 0)), n2;
  let s2, a3 = e36.pc.distanceTo(t2.pc)[0];
  if (kX.Utils.GT(a3, i3 + r3))
    return n2;
  if (kX.Utils.LT(a3, Math.abs(i3 - r3)))
    return n2;
  if (o3.x /= a3, o3.y /= a3, kX.Utils.EQ(a3, i3 + r3) || kX.Utils.EQ(a3, Math.abs(i3 - r3)))
    return s2 = e36.pc.translate(i3 * o3.x, i3 * o3.y), n2.push(s2), n2;
  let c3 = i3 * i3 / (2 * a3) - r3 * r3 / (2 * a3) + a3 / 2, l3 = e36.pc.translate(c3 * o3.x, c3 * o3.y), h2 = Math.sqrt(i3 * i3 - c3 * c3);
  return s2 = l3.translate(o3.rotate90CCW().multiply(h2)), n2.push(s2), s2 = l3.translate(o3.rotate90CW().multiply(h2)), n2.push(s2), n2;
}
function qX(e36, t2) {
  let n2 = [];
  if (e36.pc.equalTo(t2.pc) && kX.Utils.EQ(e36.r, t2.r)) {
    let o4;
    return o4 = e36.start, o4.on(t2) && n2.push(o4), o4 = e36.end, o4.on(t2) && n2.push(o4), o4 = t2.start, o4.on(e36) && n2.push(o4), o4 = t2.end, o4.on(e36) && n2.push(o4), n2;
  }
  let o3 = new kX.Circle(e36.pc, e36.r), i3 = new kX.Circle(t2.pc, t2.r), r3 = o3.intersect(i3);
  for (let o4 of r3)
    o4.on(e36) && o4.on(t2) && n2.push(o4);
  return n2;
}
function JX(e36, t2) {
  let n2 = [];
  if (t2.pc.equalTo(e36.pc) && kX.Utils.EQ(t2.r, e36.r))
    return n2.push(e36.start), n2.push(e36.end), n2;
  let o3 = ZX(t2, new kX.Circle(e36.pc, e36.r));
  for (let t3 of o3)
    t3.on(e36) && n2.push(t3);
  return n2;
}
function QX(e36, t2) {
  return e36.isSegment ? VX(e36.shape, t2) : UX(t2, e36.shape);
}
function KX(e36, t2) {
  return e36.isSegment ? UX(e36.shape, t2) : qX(e36.shape, t2);
}
function eH(e36, t2) {
  return e36.isSegment ? HX(e36.shape, t2) : XX(t2, e36.shape);
}
function tH(e36, t2) {
  return e36.isSegment ? GX(e36.shape, t2) : JX(e36.shape, t2);
}
function nH(e36, t2) {
  let n2 = [];
  for (let o3 of t2.edges)
    for (let t3 of QX(o3, e36))
      n2.push(t3);
  return n2;
}
function oH(e36, t2) {
  let n2 = [];
  for (let o3 of t2.edges)
    for (let t3 of KX(o3, e36))
      n2.push(t3);
  return n2;
}
function iH(e36, t2) {
  let n2 = [];
  if (t2.isEmpty())
    return n2;
  for (let o3 of t2.edges)
    for (let t3 of eH(o3, e36))
      cH(t3, n2) || n2.push(t3);
  return e36.sortPoints(n2);
}
function rH(e36, t2) {
  let n2 = [];
  if (t2.isEmpty())
    return n2;
  for (let o3 of t2.edges)
    for (let t3 of tH(o3, e36))
      n2.push(t3);
  return n2;
}
function sH(e36, t2) {
  return e36.isSegment ? QX(t2, e36.shape) : e36.isArc ? KX(t2, e36.shape) : e36.isLine ? eH(t2, e36.shape) : e36.isRay ? (n2 = t2, o3 = e36.shape, n2.isSegment ? hH(o3, n2.shape) : dH(o3, n2.shape)) : [];
  var n2, o3;
}
function aH(e36, t2) {
  let n2 = [];
  if (t2.isEmpty() || e36.shape.box.not_intersect(t2.box))
    return n2;
  let o3 = t2.edges.search(e36.shape.box);
  for (let t3 of o3)
    n2 = [...n2, ...sH(e36, t3)];
  return n2;
}
function cH(e36, t2) {
  return t2.some((t3) => t3.equalTo(e36));
}
function lH(e36) {
  return new kX.Line(e36.start, e36.norm);
}
function hH(e36, t2) {
  return HX(t2, lH(e36)).filter((t3) => e36.contains(t3));
}
function dH(e36, t2) {
  return XX(lH(e36), t2).filter((t3) => e36.contains(t3));
}
function uH(e36, t2) {
  return $X(lH(e36), t2).filter((t3) => e36.contains(t3));
}
function pH(e36, t2) {
  return jX(lH(e36), t2).filter((t3) => e36.contains(t3));
}
function mH(e36, t2) {
  return iH(lH(e36), t2).filter((t3) => e36.contains(t3));
}
function gH(e36, t2) {
  if (e36.intersect && e36.intersect instanceof Function)
    return e36.intersect(t2);
  throw DX.UNSUPPORTED_SHAPE_TYPE;
}
function fH(e36, t2) {
  let n2 = [];
  for (let o3 of t2)
    n2 = [...n2, ...gH(e36, o3.shape)];
  return n2;
}
var _H = class e36 extends LX {
  constructor(...e37) {
    if (super(), this.isInfinite = false, e37.length === 1 && e37[0] instanceof Array && e37[0].length > 0) {
      const t2 = e37[0], n2 = t2.length, o3 = (e38) => e38 instanceof kX.Segment || e38 instanceof kX.Arc || e38 instanceof kX.Ray, i3 = (e38) => e38 instanceof kX.Segment || e38 instanceof kX.Arc;
      if (!(n2 === 1 && ((e38) => e38 instanceof kX.Segment || e38 instanceof kX.Arc || e38 instanceof kX.Ray || e38 instanceof kX.Line)(t2[0]) || n2 > 1 && o3(t2[0]) && o3(t2[n2 - 1]) && t2.slice(1, n2 - 1).every(i3)))
        throw kX.Errors.ILLEGAL_PARAMETERS;
      this.isInfinite = t2.some((e38) => e38 instanceof kX.Ray || e38 instanceof kX.Line);
      for (let e38 of t2) {
        let t3 = new kX.Edge(e38);
        this.append(t3);
      }
      this.setArcLength();
    }
  }
  get edges() {
    return [...this];
  }
  get box() {
    return this.edges.reduce((e37, t2) => e37.merge(t2.box), new kX.Box);
  }
  get vertices() {
    let e37 = this.edges.map((e38) => e38.start);
    return e37.push(this.last.end), e37;
  }
  get length() {
    if (this.isEmpty())
      return 0;
    if (this.isInfinite)
      return Number.POSITIVE_INFINITY;
    let e37 = 0;
    for (let t2 of this)
      e37 += t2.length;
    return e37;
  }
  clone() {
    return new e36(this.toShapes());
  }
  setArcLength() {
    for (let e37 of this)
      this.setOneEdgeArcLength(e37);
  }
  setOneEdgeArcLength(e37) {
    e37 === this.first ? e37.arc_length = 0 : e37.arc_length = e37.prev.arc_length + e37.prev.length;
  }
  pointAtLength(e37) {
    if (e37 > this.length || e37 < 0)
      return null;
    if (this.isInfinite)
      return null;
    let t2 = null;
    for (let n2 of this)
      if (e37 >= n2.arc_length && (n2 === this.last || e37 < n2.next.arc_length)) {
        t2 = n2.pointAtLength(e37 - n2.arc_length);
        break;
      }
    return t2;
  }
  addVertex(e37, t2) {
    let n2 = t2.shape.split(e37);
    if (n2[0] === null)
      return t2.prev;
    if (n2[1] === null)
      return t2;
    let o3 = new kX.Edge(n2[0]), i3 = t2.prev;
    return this.insert(o3, i3), t2.shape = n2[1], o3;
  }
  getChain(e37, t2) {
    let n2 = [];
    for (let o3 = e37;o3 !== t2.next; o3 = o3.next)
      n2.push(o3);
    return n2;
  }
  split(e37) {
    for (let t2 of e37) {
      let e38 = this.findEdgeByPoint(t2);
      this.addVertex(t2, e38);
    }
    return this;
  }
  findEdgeByPoint(e37) {
    let t2;
    for (let n2 of this)
      if (n2.shape.contains(e37)) {
        t2 = n2;
        break;
      }
    return t2;
  }
  distanceTo(e37) {
    if (e37 instanceof Point) {
      const [t2, n2] = kX.Distance.shape2multiline(e37, this);
      return [t2, n2.reverse()];
    }
    if (e37 instanceof kX.Line) {
      const [t2, n2] = kX.Distance.shape2multiline(e37, this);
      return [t2, n2.reverse()];
    }
    if (e37 instanceof kX.Circle) {
      const [t2, n2] = kX.Distance.shape2multiline(e37, this);
      return [t2, n2.reverse()];
    }
    if (e37 instanceof kX.Segment) {
      const [t2, n2] = kX.Distance.shape2multiline(e37, this);
      return [t2, n2.reverse()];
    }
    if (e37 instanceof kX.Arc) {
      const [t2, n2] = kX.Distance.shape2multiline(e37, this);
      return [t2, n2.reverse()];
    }
    if (e37 instanceof kX.Multiline)
      return kX.Distance.multiline2multiline(this, e37);
    throw kX.Errors.UNSUPPORTED_SHAPE_TYPE;
  }
  intersect(e37) {
    return e37 instanceof kX.Multiline ? function(e38, t2) {
      let n2 = [];
      for (let o3 of e38)
        for (let e39 of t2)
          n2 = [...n2, ...gH(o3.shape, e39.shape)];
      return n2;
    }(this, e37) : fH(e37, this);
  }
  contains(e37) {
    if (e37 instanceof kX.Point)
      return this.edges.some((t2) => t2.shape.contains(e37));
    throw kX.Errors.UNSUPPORTED_SHAPE_TYPE;
  }
  translate(t2) {
    return new e36(this.edges.map((e37) => e37.shape.translate(t2)));
  }
  rotate(t2 = 0, n2 = new kX.Point) {
    return new e36(this.edges.map((e37) => e37.shape.rotate(t2, n2)));
  }
  transform(t2 = new kX.Matrix) {
    return new e36(this.edges.map((e37) => e37.shape.transform(t2)));
  }
  toShapes() {
    return this.edges.map((e37) => e37.shape.clone());
  }
  toJSON() {
    return this.edges.map((e37) => e37.toJSON());
  }
  svgPoints() {
    return this.vertices.map((e37) => `${e37.x},${e37.y}`).join(" ");
  }
  dpath() {
    let e37 = `M${this.first.start.x},${this.first.start.y}`;
    for (let t2 of this)
      e37 += t2.svg();
    return e37;
  }
  svg(e37 = {}) {
    let t2 = `
<path ${FX({ fill: "none", ...e37 })} d="`;
    t2 += `
M${this.first.start.x},${this.first.start.y}`;
    for (let e38 of this)
      t2 += e38.svg();
    return t2 += `" >
</path>`, t2;
  }
};
kX.Multiline = _H;
function yH(e37, t2, n2) {
  let o3 = n2.length, i3 = e37.shape.split(t2);
  if (i3.length === 0)
    return;
  let r3 = 0;
  r3 = i3[0] === null ? 0 : i3[1] === null ? e37.shape.length : i3[0].length;
  let s2, a3 = 0;
  EX(r3, 0) && (a3 |= 1), EX(r3, e37.shape.length) && (a3 |= 2), s2 = r3 === 1 / 0 ? i3[0].coord(t2) : 2 & a3 && e37.next && e37.next.arc_length === 0 ? 0 : e37.arc_length + r3, n2.push({ id: o3, pt: t2, arc_length: s2, edge_before: e37, edge_after: undefined, face: e37.face, is_vertex: a3 });
}
function bH(e37) {
  e37.int_points1_sorted = xH(e37.int_points1), e37.int_points2_sorted = xH(e37.int_points2);
}
function xH(e37) {
  let t2 = new Map, n2 = 0;
  for (let o3 of e37)
    t2.has(o3.face) || (t2.set(o3.face, n2), n2++);
  for (let n3 of e37)
    n3.faceId = t2.get(n3.face);
  return e37.slice().sort(vH);
}
function vH(e37, t2) {
  return e37.faceId < t2.faceId ? -1 : e37.faceId > t2.faceId ? 1 : e37.arc_length < t2.arc_length ? -1 : e37.arc_length > t2.arc_length ? 1 : 0;
}
function IH(e37) {
  if (e37.int_points1.length < 2)
    return;
  let t2, n2, o3, i3, r3 = false;
  for (let s2 = 0;s2 < e37.int_points1_sorted.length; s2++)
    if (e37.int_points1_sorted[s2].id !== -1) {
      t2 = e37.int_points1_sorted[s2], n2 = e37.int_points2[t2.id];
      for (let a3 = s2 + 1;a3 < e37.int_points1_sorted.length && (o3 = e37.int_points1_sorted[a3], EX(o3.arc_length, t2.arc_length)); a3++)
        o3.id !== -1 && (i3 = e37.int_points2[o3.id], i3.id !== -1 && o3.edge_before === t2.edge_before && o3.edge_after === t2.edge_after && i3.edge_before === n2.edge_before && i3.edge_after === n2.edge_after && (o3.id = -1, i3.id = -1, r3 = true));
    }
  n2 = e37.int_points2_sorted[0], t2 = e37.int_points1[n2.id];
  for (let o4 = 1;o4 < e37.int_points2_sorted.length; o4++) {
    let i4 = e37.int_points2_sorted[o4];
    if (i4.id === -1)
      continue;
    if (n2.id === -1 || !EX(i4.arc_length, n2.arc_length)) {
      n2 = i4, t2 = e37.int_points1[n2.id];
      continue;
    }
    let s2 = e37.int_points1[i4.id];
    s2.edge_before === t2.edge_before && s2.edge_after === t2.edge_after && i4.edge_before === n2.edge_before && i4.edge_after === n2.edge_after && (s2.id = -1, i4.id = -1, r3 = true);
  }
  r3 && (e37.int_points1 = e37.int_points1.filter((e38) => e38.id >= 0), e37.int_points2 = e37.int_points2.filter((e38) => e38.id >= 0), e37.int_points1.forEach((e38, t3) => e38.id = t3), e37.int_points2.forEach((e38, t3) => e38.id = t3));
}
function SH(e37) {
  for (let t2 of e37)
    t2.edge_before && (t2.edge_before.bvStart = undefined, t2.edge_before.bvEnd = undefined, t2.edge_before.bv = undefined, t2.edge_before.overlap = undefined), t2.edge_after && (t2.edge_after.bvStart = undefined, t2.edge_after.bvEnd = undefined, t2.edge_after.bv = undefined, t2.edge_after.overlap = undefined);
  for (let t2 of e37)
    t2.edge_before && (t2.edge_before.bvEnd = 2), t2.edge_after && (t2.edge_after.bvStart = 2);
}
function CH(e37, t2) {
  for (let n2 of e37)
    n2.edge_before && n2.edge_before.setInclusion(t2), n2.edge_after && n2.edge_after.setInclusion(t2);
}
function PH(e37, t2, n2) {
  let o3, i3, r3 = 1;
  if (e37.length === 1)
    return 1;
  o3 = e37[t2];
  for (let s2 = t2 + 1;s2 < e37.length && o3.face === n2 && (i3 = e37[s2], i3.pt.equalTo(o3.pt) && i3.edge_before === o3.edge_before && i3.edge_after === o3.edge_after); s2++)
    r3++;
  return r3;
}
function MH(e37, t2) {
  if (t2) {
    for (let n2 of t2) {
      let t3 = n2.edge_before;
      if (n2.is_vertex = 0, t3.shape.start && t3.shape.start.equalTo(n2.pt) && (n2.is_vertex |= 1), t3.shape.end && t3.shape.end.equalTo(n2.pt) && (n2.is_vertex |= 2), 1 & n2.is_vertex) {
        n2.edge_before = t3.prev, t3.prev && (n2.is_vertex = 2);
        continue;
      }
      if (2 & n2.is_vertex)
        continue;
      let o3 = e37.addVertex(n2.pt, t3);
      n2.edge_before = o3;
    }
    for (let n2 of t2)
      n2.edge_before ? n2.edge_after = n2.edge_before.next : e37 instanceof _H && 1 & n2.is_vertex && (n2.edge_after = e37.first);
  }
}
function wH(e37, t2, n2) {
  const o3 = e37.edge_before, i3 = t2.edge_after, r3 = n2.length;
  o3.next = n2[0], n2[0].prev = o3, n2[r3 - 1].next = i3, i3.prev = n2[r3 - 1];
}
kX.multiline = (...e37) => new kX.Multiline(...e37);
var { INSIDE: NH, OUTSIDE: RH, BOUNDARY: TH, OVERLAP_SAME: EH, OVERLAP_OPPOSITE: AH } = MX;
var { NOT_VERTEX: OH, START_VERTEX: kH, END_VERTEX: DH } = MX;
function LH(e37, t2) {
  let n2 = t2.clone().reverse(), [o3, i3] = YH(e37, n2, 3, true);
  return o3;
}
function zH(e37, t2) {
  let [n2, o3] = YH(e37, t2, 2, true);
  return n2;
}
function BH(e37, t2) {
  let [n2, o3] = YH(e37, t2, 2, false), i3 = [];
  for (let e38 of n2.faces)
    i3 = [...i3, ...[...e38.edges].map((e39) => e39.shape)];
  let r3 = [];
  for (let e38 of o3.faces)
    r3 = [...r3, ...[...e38.edges].map((e39) => e39.shape)];
  return [i3, r3];
}
function FH(e37, t2) {
  let [n2, o3] = YH(e37, t2, 3, false), i3 = [];
  for (let e38 of n2.faces)
    i3 = [...i3, ...[...e38.edges].map((e39) => e39.shape)];
  return i3;
}
function jH(e37, t2) {
  let n2 = e37.clone(), o3 = t2.clone(), i3 = XH(n2, o3);
  return bH(i3), MH(n2, i3.int_points1_sorted), MH(o3, i3.int_points2_sorted), IH(i3), bH(i3), [i3.int_points1_sorted.map((e38) => e38.pt), i3.int_points2_sorted.map((e38) => e38.pt)];
}
function $H(e37, t2, n2, o3) {
  let i3 = HH(e37, n2.int_points1), r3 = HH(t2, n2.int_points2);
  for (VH(i3, t2), VH(r3, e37), SH(n2.int_points1), SH(n2.int_points2), CH(n2.int_points1, t2), CH(n2.int_points2, e37);WH(e37, t2, n2.int_points1, n2.int_points1_sorted, n2.int_points2, n2); )
    ;
  (function(e38) {
    let t3, n3, o4, i4 = e38.int_points1.length;
    for (let r4 = 0;r4 < i4; r4++) {
      let s2 = e38.int_points1_sorted[r4];
      s2.face !== t3 && (n3 = r4, t3 = s2.face);
      let a3, c3 = r4, l3 = PH(e38.int_points1_sorted, r4, t3);
      a3 = c3 + l3 < i4 && e38.int_points1_sorted[c3 + l3].face === t3 ? c3 + l3 : n3;
      let h2 = PH(e38.int_points1_sorted, a3, t3);
      o4 = null;
      for (let n4 = a3;n4 < a3 + h2; n4++) {
        let i5 = e38.int_points1_sorted[n4];
        if (i5.face === t3 && e38.int_points2[i5.id].face === e38.int_points2[s2.id].face) {
          o4 = i5;
          break;
        }
      }
      if (o4 === null)
        continue;
      let d2 = s2.edge_after, u2 = o4.edge_before;
      if (d2.bv !== 2 || u2.bv !== 2)
        continue;
      if (d2 !== u2)
        continue;
      let p3 = e38.int_points2[s2.id], m2 = e38.int_points2[o4.id], g2 = p3.edge_after, f2 = m2.edge_before;
      g2.bv === 2 && f2.bv === 2 && g2 === f2 || (p3 = e38.int_points2[o4.id], m2 = e38.int_points2[s2.id], g2 = p3.edge_after, f2 = m2.edge_before), g2.bv === 2 && f2.bv === 2 && g2 === f2 && d2.setOverlap(g2);
    }
  })(n2), GH(e37, o3, n2.int_points1_sorted, true), GH(t2, o3, n2.int_points2_sorted, false), qH(e37, i3, o3, true), qH(t2, r3, o3, false);
}
function YH(e37, t2, n2, o3) {
  let i3 = e37.clone(), r3 = t2.clone(), s2 = XH(i3, r3);
  return bH(s2), MH(i3, s2.int_points1_sorted), MH(r3, s2.int_points2_sorted), IH(s2), bH(s2), $H(i3, r3, s2, n2), o3 && function(e38, t3, n3) {
    (function(e39, t4, n4, o4) {
      for (let n5 of t4.faces) {
        for (let t5 of n5)
          e39.edges.add(t5);
        o4.find((e40) => e40.face === n5) === undefined && e39.addFace(n5.first, n5.last);
      }
    })(e38, t3, 0, n3.int_points2), function(e39, t4, n4) {
      if (n4.int_points1.length !== 0)
        for (let e40 = 0;e40 < n4.int_points1.length; e40++) {
          let t5 = n4.int_points1[e40], o4 = n4.int_points2[e40];
          if (t5.edge_before !== undefined && t5.edge_after === undefined && o4.edge_before === undefined && o4.edge_after !== undefined && (t5.edge_before.next = o4.edge_after, o4.edge_after.prev = t5.edge_before, t5.edge_after = o4.edge_after, o4.edge_before = t5.edge_before), o4.edge_before !== undefined && o4.edge_after === undefined && t5.edge_before === undefined && t5.edge_after !== undefined && (o4.edge_before.next = t5.edge_after, t5.edge_after.prev = o4.edge_before, o4.edge_after = t5.edge_after, t5.edge_before = o4.edge_before), t5.edge_before !== undefined && t5.edge_after === undefined)
            for (let e41 of n4.int_points1_sorted)
              e41 !== t5 && e41.edge_before === undefined && e41.edge_after !== undefined && e41.pt.equalTo(t5.pt) && (t5.edge_before.next = e41.edge_after, e41.edge_after.prev = t5.edge_before, t5.edge_after = e41.edge_after, e41.edge_before = t5.edge_before);
          if (o4.edge_before !== undefined && o4.edge_after === undefined)
            for (let e41 of n4.int_points2_sorted)
              e41 !== o4 && e41.edge_before === undefined && e41.edge_after !== undefined && e41.pt.equalTo(o4.pt) && (o4.edge_before.next = e41.edge_after, e41.edge_after.prev = o4.edge_before, o4.edge_after = e41.edge_after, e41.edge_before = o4.edge_before);
        }
    }(0, 0, n3), UH(e38, n3.int_points1), UH(t3, n3.int_points2), ZH(e38, n3.int_points1, n3.int_points2), ZH(e38, n3.int_points2, n3.int_points1);
  }(i3, r3, s2), [i3, r3];
}
function XH(e37, t2) {
  let n2 = { int_points1: [], int_points2: [] };
  for (let o3 of e37.edges) {
    let e38 = t2.edges.search(o3.box);
    for (let t3 of e38) {
      let e39 = o3.shape.intersect(t3.shape);
      for (let i3 of e39)
        yH(o3, i3, n2.int_points1), yH(t3, i3, n2.int_points2);
    }
  }
  return n2;
}
function HH(e37, t2) {
  let n2 = [];
  for (let o3 of e37.faces)
    t2.find((e38) => e38.face === o3) || n2.push(o3);
  return n2;
}
function VH(e37, t2) {
  for (let n2 of e37)
    n2.first.bv = n2.first.bvStart = n2.first.bvEnd = undefined, n2.first.setInclusion(t2);
}
function WH(e37, t2, n2, o3, i3, r3) {
  let s2, a3, c3, l3 = o3.length, h2 = false;
  for (let d2 = 0;d2 < l3; d2++) {
    let u2 = o3[d2];
    u2.face !== s2 && (a3 = d2, s2 = u2.face);
    let p3, m2 = d2, g2 = PH(o3, d2, s2);
    p3 = m2 + g2 < l3 && o3[m2 + g2].face === s2 ? m2 + g2 : a3;
    let f2 = PH(o3, p3, s2);
    c3 = null;
    for (let e38 = p3;e38 < p3 + f2; e38++) {
      let t3 = o3[e38];
      if (t3.face === s2 && i3[t3.id].face === i3[u2.id].face) {
        c3 = t3;
        break;
      }
    }
    if (c3 === null)
      continue;
    let _2 = u2.edge_after, y2 = c3.edge_before;
    if (_2.bv !== TH || y2.bv == TH)
      if (_2.bv == TH || y2.bv !== TH) {
        if (_2.bv === TH && y2.bv === TH && _2 != y2 || _2.bv === NH && y2.bv === RH || _2.bv === RH && y2.bv === NH) {
          let e38 = _2.next;
          for (;e38 != y2; )
            e38.bvStart = undefined, e38.bvEnd = undefined, e38.bv = undefined, e38.setInclusion(t2), e38 = e38.next;
        }
        if (_2.bv === TH && y2.bv === TH && _2 != y2) {
          let e38, t3 = _2.next;
          for (;t3 != y2; ) {
            if (t3.bv != TH) {
              if (e38 === undefined)
                e38 = t3.bv;
              else if (t3.bv != e38)
                throw DX.UNRESOLVED_BOUNDARY_CONFLICT;
            }
            t3 = t3.next;
          }
          e38 != null && (_2.bv = e38, y2.bv = e38);
          continue;
        }
        if (_2.bv === NH && y2.bv === RH || _2.bv === RH && y2.bv === NH) {
          let o4 = _2;
          for (;o4 != y2; ) {
            if (o4.bvStart === _2.bv && o4.bvEnd === y2.bv) {
              let [s3, a4] = o4.shape.distanceTo(t2);
              if (s3 < 10 * kX.DP_TOL) {
                yH(o4, a4.ps, n2);
                let s4 = n2[n2.length - 1];
                if (s4.is_vertex & kH)
                  s4.edge_after = o4, s4.edge_before = o4.prev, o4.bvStart = TH, o4.bv = undefined, o4.setInclusion(t2);
                else if (s4.is_vertex & DH)
                  s4.edge_after = o4.next, o4.bvEnd = TH, o4.bv = undefined, o4.setInclusion(t2);
                else {
                  let e38 = t2.addVertex(s4.pt, o4);
                  s4.edge_before = e38, s4.edge_after = e38.next, e38.setInclusion(t2), e38.next.bvStart = TH, e38.next.bvEnd = undefined, e38.next.bv = undefined, e38.next.setInclusion(t2);
                }
                let c4 = t2.findEdgeByPoint(a4.pe);
                yH(c4, a4.pe, i3);
                let l4 = i3[i3.length - 1];
                if (l4.is_vertex & kH)
                  l4.edge_after = c4, l4.edge_before = c4.prev;
                else if (l4.is_vertex & DH)
                  l4.edge_after = c4.next;
                else {
                  let n3 = i3.find((e38) => e38.edge_after === c4), o5 = t2.addVertex(l4.pt, c4);
                  l4.edge_before = o5, l4.edge_after = o5.next, n3 && (n3.edge_after = o5), o5.bvStart = undefined, o5.bvEnd = TH, o5.bv = undefined, o5.setInclusion(e37), o5.next.bvStart = TH, o5.next.bvEnd = undefined, o5.next.bv = undefined, o5.next.setInclusion(e37);
                }
                bH(r3), h2 = true;
                break;
              }
            }
            o4 = o4.next;
          }
          if (h2)
            break;
          throw DX.UNRESOLVED_BOUNDARY_CONFLICT;
        }
      } else
        y2.bv = _2.bv;
    else
      _2.bv = y2.bv;
  }
  return h2;
}
function GH(e37, t2, n2, o3) {
  if (!n2)
    return;
  let i3, r3, s2, a3;
  for (let c3 = 0;c3 < n2.length; c3++) {
    if (s2 = n2[c3], s2.face !== i3 && (r3 = c3, i3 = s2.face), i3.isEmpty())
      continue;
    let l3, h2 = c3, d2 = PH(n2, c3, i3);
    l3 = h2 + d2 < n2.length && n2[h2 + d2].face === s2.face ? h2 + d2 : r3, a3 = n2[l3];
    let u2 = l3, p3 = PH(n2, u2, i3), m2 = s2.edge_after, g2 = a3.edge_before;
    if (m2.bv === NH && g2.bv === NH && t2 === 1 || m2.bv === RH && g2.bv === RH && t2 === 2 || (m2.bv === RH || g2.bv === RH) && t2 === 3 && !o3 || (m2.bv === NH || g2.bv === NH) && t2 === 3 && o3 || m2.bv === TH && g2.bv === TH && m2.overlap & EH && o3 || m2.bv === TH && g2.bv === TH && m2.overlap & AH) {
      e37.removeChain(i3, m2, g2);
      for (let e38 = h2;e38 < h2 + d2; e38++)
        n2[e38].edge_after = undefined;
      for (let e38 = u2;e38 < u2 + p3; e38++)
        n2[e38].edge_before = undefined;
    }
    c3 += d2 - 1;
  }
}
function UH(e37, t2) {
  for (let n2 of t2)
    e37.faces.delete(n2.face), n2.face = undefined, n2.edge_before && (n2.edge_before.face = undefined), n2.edge_after && (n2.edge_after.face = undefined);
}
function ZH(e37, t2, n2) {
  for (let o3 of t2) {
    if (o3.edge_before === undefined || o3.edge_after === undefined)
      continue;
    if (o3.face)
      continue;
    if (o3.edge_after.face || o3.edge_before.face)
      continue;
    let { edge_after: i3, edge_before: r3 } = o3;
    try {
      LX.testInfiniteLoop(i3);
    } catch (e38) {
      throw DX.CANNOT_COMPLETE_BOOLEAN_OPERATION;
    }
    let s2 = e37.addFace(i3, r3);
    for (let e38 of t2)
      e38.edge_before && e38.edge_after && e38.edge_before.face === s2 && e38.edge_after.face === s2 && (e38.face = s2);
    for (let e38 of n2)
      e38.edge_before && e38.edge_after && e38.edge_before.face === s2 && e38.edge_after.face === s2 && (e38.face = s2);
  }
}
function qH(e37, t2, n2, o3) {
  for (let i3 of t2) {
    let t3 = i3.first.bv;
    (n2 === 1 && t3 === NH || n2 === 3 && t3 === NH && o3 || n2 === 3 && t3 === RH && !o3 || n2 === 2 && t3 === RH) && e37.deleteFace(i3);
  }
}
var JH = Object.freeze({ __proto__: null, BOOLEAN_INTERSECT: 2, BOOLEAN_SUBTRACT: 3, BOOLEAN_UNION: 1, calculateIntersections: jH, innerClip: BH, intersect: zH, outerClip: FH, removeNotRelevantChains: GH, removeOldFaces: UH, restoreFaces: ZH, subtract: LH, unify: function(e37, t2) {
  let [n2, o3] = YH(e37, t2, 1, true);
  return n2;
} });
var QH = RegExp("T.F..FFF.|T.F...F..");
var KH = RegExp("T........|.T.......|...T.....|....T....");
var eV = RegExp("FT.......|F..T.....|F...T....");
var tV = RegExp("T.F..F...");
var nV = RegExp("T.F..F...|.TF..F...|..FT.F...|..F.TF...");
var oV = class {
  constructor() {
    this.m = new Array(9).fill(undefined);
  }
  get I2I() {
    return this.m[0];
  }
  set I2I(e37) {
    this.m[0] = e37;
  }
  get I2B() {
    return this.m[1];
  }
  set I2B(e37) {
    this.m[1] = e37;
  }
  get I2E() {
    return this.m[2];
  }
  set I2E(e37) {
    this.m[2] = e37;
  }
  get B2I() {
    return this.m[3];
  }
  set B2I(e37) {
    this.m[3] = e37;
  }
  get B2B() {
    return this.m[4];
  }
  set B2B(e37) {
    this.m[4] = e37;
  }
  get B2E() {
    return this.m[5];
  }
  set B2E(e37) {
    this.m[5] = e37;
  }
  get E2I() {
    return this.m[6];
  }
  set E2I(e37) {
    this.m[6] = e37;
  }
  get E2B() {
    return this.m[7];
  }
  set E2B(e37) {
    this.m[7] = e37;
  }
  get E2E() {
    return this.m[8];
  }
  set E2E(e37) {
    this.m[8] = e37;
  }
  toString() {
    return this.m.map((e37) => e37 instanceof Array && e37.length > 0 ? "T" : e37 instanceof Array && e37.length === 0 ? "F" : "*").join("");
  }
  equal() {
    return QH.test(this.toString());
  }
  intersect() {
    return KH.test(this.toString());
  }
  touch() {
    return eV.test(this.toString());
  }
  inside() {
    return tV.test(this.toString());
  }
  covered() {
    return nV.test(this.toString());
  }
};
function iV(e37, t2) {
  let n2, o3 = new kX.Ray(t2), i3 = new kX.Line(o3.pt, o3.norm);
  const r3 = new kX.Box(o3.box.xmin - kX.DP_TOL, o3.box.ymin - kX.DP_TOL, o3.box.xmax + kX.DP_TOL, o3.box.ymax + kX.DP_TOL);
  if (e37.box.not_intersect(r3))
    return kX.OUTSIDE;
  let s2 = e37.edges.search(r3);
  if (s2.length === 0)
    return kX.OUTSIDE;
  for (let e38 of s2)
    if (e38.shape.contains(t2))
      return kX.BOUNDARY;
  let a3 = [...e37.faces], c3 = [];
  for (let e38 of s2)
    for (let n3 of o3.intersect(e38.shape)) {
      if (n3.equalTo(t2))
        return kX.BOUNDARY;
      c3.push({ pt: n3, edge: e38, face_index: a3.indexOf(e38.face) });
    }
  c3.sort((e38, t3) => OX(e38.pt.x, t3.pt.x) ? -1 : AX(e38.pt.x, t3.pt.x) ? 1 : e38.face_index < t3.face_index ? -1 : e38.face_index > t3.face_index ? 1 : e38.edge.arc_length < t3.edge.arc_length ? -1 : e38.edge.arc_length > t3.edge.arc_length ? 1 : 0);
  let l3 = 0;
  for (let e38 = 0;e38 < c3.length; e38++) {
    let t3 = c3[e38];
    if (t3.pt.equalTo(t3.edge.shape.start)) {
      if (e38 > 0 && t3.pt.equalTo(c3[e38 - 1].pt) && t3.face_index === c3[e38 - 1].face_index && t3.edge.prev === c3[e38 - 1].edge)
        continue;
      let n3 = t3.edge.prev;
      for (;TX(n3.length); )
        n3 = n3.prev;
      let o4 = n3.shape.tangentInEnd(), r4 = t3.pt.translate(o4), s3 = t3.edge.shape.tangentInStart(), a4 = t3.pt.translate(s3), h2 = r4.leftTo(i3), d2 = a4.leftTo(i3);
      (h2 && !d2 || !h2 && d2) && l3++;
    } else if (t3.pt.equalTo(t3.edge.shape.end)) {
      if (e38 > 0 && t3.pt.equalTo(c3[e38 - 1].pt) && t3.face_index === c3[e38 - 1].face_index && t3.edge.next === c3[e38 - 1].edge)
        continue;
      let n3 = t3.edge.next;
      for (;TX(n3.length); )
        n3 = n3.next;
      let o4 = n3.shape.tangentInStart(), r4 = t3.pt.translate(o4), s3 = t3.edge.shape.tangentInEnd(), a4 = t3.pt.translate(s3), h2 = r4.leftTo(i3), d2 = a4.leftTo(i3);
      (h2 && !d2 || !h2 && d2) && l3++;
    } else if (t3.edge.shape instanceof kX.Segment)
      l3++;
    else {
      let e39 = t3.edge.shape.box;
      EX(t3.pt.y, e39.ymin) || EX(t3.pt.y, e39.ymax) || l3++;
    }
  }
  return n2 = l3 % 2 == 1 ? 1 : 0, n2;
}
function rV(e37, t2) {
  return lV(e37, t2).intersect();
}
function sV(e37, t2) {
  return lV(e37, t2).inside();
}
function aV(e37, t2) {
  return lV(e37, t2).covered();
}
function cV(e37, t2) {
  return aV(t2, e37);
}
function lV(e37, t2) {
  return e37 instanceof kX.Line && t2 instanceof kX.Line ? function(e38, t3) {
    let n2 = new oV, o3 = jX(e38, t3);
    o3.length === 0 ? e38.contains(t3.pt) && t3.contains(e38.pt) ? (n2.I2I = [e38], n2.I2E = [], n2.E2I = []) : (n2.I2I = [], n2.I2E = [e38], n2.E2I = [t3]) : (n2.I2I = o3, n2.I2E = e38.split(o3), n2.E2I = t3.split(o3));
    return n2;
  }(e37, t2) : e37 instanceof kX.Line && t2 instanceof kX.Circle ? function(e38, t3) {
    let n2 = new oV, o3 = $X(e38, t3);
    if (o3.length === 0)
      n2.I2I = [], n2.I2B = [], n2.I2E = [e38], n2.E2I = [t3];
    else if (o3.length === 1)
      n2.I2I = [], n2.I2B = o3, n2.I2E = e38.split(o3), n2.E2I = [t3];
    else {
      let i3 = new _H([e38]), r3 = e38.sortPoints(o3);
      i3.split(r3);
      let s2 = i3.toShapes();
      n2.I2I = [s2[1]], n2.I2B = r3, n2.I2E = [s2[0], s2[2]], n2.E2I = new kX.Polygon([t3.toArc()]).cutWithLine(e38);
    }
    return n2;
  }(e37, t2) : e37 instanceof kX.Line && t2 instanceof kX.Box ? function(e38, t3) {
    let n2 = new oV, o3 = YX(e38, t3);
    if (o3.length === 0)
      n2.I2I = [], n2.I2B = [], n2.I2E = [e38], n2.E2I = [t3];
    else if (o3.length === 1)
      n2.I2I = [], n2.I2B = o3, n2.I2E = e38.split(o3), n2.E2I = [t3];
    else {
      let i3 = new _H([e38]), r3 = e38.sortPoints(o3);
      i3.split(r3);
      let s2 = i3.toShapes();
      t3.toSegments().some((e39) => e39.contains(o3[0]) && e39.contains(o3[1])) ? (n2.I2I = [], n2.I2B = [s2[1]], n2.I2E = [s2[0], s2[2]], n2.E2I = [t3]) : (n2.I2I = [s2[1]], n2.I2B = r3, n2.I2E = [s2[0], s2[2]], n2.E2I = new kX.Polygon(t3.toSegments()).cutWithLine(e38));
    }
    return n2;
  }(e37, t2) : e37 instanceof kX.Line && t2 instanceof kX.Polygon ? function(e38, t3) {
    let n2 = new oV, o3 = iH(e38, t3), i3 = new _H([e38]), r3 = o3.length > 0 ? o3.slice() : e38.sortPoints(o3);
    return i3.split(r3), [...i3].forEach((e39) => e39.setInclusion(t3)), n2.I2I = [...i3].filter((e39) => e39.bv === kX.INSIDE).map((e39) => e39.shape), n2.I2B = [...i3].slice(1).map((e39) => e39.bv === kX.BOUNDARY ? e39.shape : e39.shape.start), n2.I2E = [...i3].filter((e39) => e39.bv === kX.OUTSIDE).map((e39) => e39.shape), n2.E2I = t3.cutWithLine(e38), n2;
  }(e37, t2) : (e37 instanceof kX.Segment || e37 instanceof kX.Arc) && t2 instanceof kX.Polygon ? hV(e37, t2) : (e37 instanceof kX.Segment || e37 instanceof kX.Arc) && (t2 instanceof kX.Circle || t2 instanceof kX.Box) ? hV(e37, new kX.Polygon(t2)) : e37 instanceof kX.Polygon && t2 instanceof kX.Polygon ? dV(e37, t2) : (e37 instanceof kX.Circle || e37 instanceof kX.Box) && (t2 instanceof kX.Circle || t2 instanceof kX.Box) ? dV(new kX.Polygon(e37), new kX.Polygon(t2)) : (e37 instanceof kX.Circle || e37 instanceof kX.Box) && t2 instanceof kX.Polygon ? dV(new kX.Polygon(e37), t2) : e37 instanceof kX.Polygon && (t2 instanceof kX.Circle || t2 instanceof kX.Box) ? dV(e37, new kX.Polygon(t2)) : undefined;
}
function hV(e37, t2) {
  let n2 = new oV, o3 = function(e38, t3) {
    return e38 instanceof kX.Line ? iH(e38, t3) : e38 instanceof kX.Segment ? nH(e38, t3) : e38 instanceof kX.Arc ? oH(e38, t3) : [];
  }(e37, t2), i3 = o3.length > 0 ? o3.slice() : e37.sortPoints(o3), r3 = new _H([e37]);
  r3.split(i3), [...r3].forEach((e38) => e38.setInclusion(t2)), n2.I2I = [...r3].filter((e38) => e38.bv === kX.INSIDE).map((e38) => e38.shape), n2.I2B = [...r3].slice(1).map((e38) => e38.bv === kX.BOUNDARY ? e38.shape : e38.shape.start), n2.I2E = [...r3].filter((e38) => e38.bv === kX.OUTSIDE).map((e38) => e38.shape), n2.B2I = [], n2.B2B = [], n2.B2E = [];
  for (let o4 of [e37.start, e37.end])
    switch (iV(t2, o4)) {
      case kX.INSIDE:
        n2.B2I.push(o4);
        break;
      case kX.BOUNDARY:
        n2.B2B.push(o4);
        break;
      case kX.OUTSIDE:
        n2.B2E.push(o4);
    }
  return n2;
}
function dV(e37, t2) {
  let n2 = new oV, [o3, i3] = jH(e37, t2), r3 = zH(e37, t2), s2 = LH(e37, t2), a3 = LH(t2, e37), [c3, l3] = BH(e37, t2), h2 = FH(e37, t2), d2 = FH(t2, e37);
  return n2.I2I = r3.isEmpty() ? [] : [r3], n2.I2B = l3, n2.I2E = s2.isEmpty() ? [] : [s2], n2.B2I = c3, n2.B2B = o3, n2.B2E = h2, n2.E2I = a3.isEmpty() ? [] : [a3], n2.E2B = d2, n2;
}
var uV = Object.freeze({ __proto__: null, contain: function(e37, t2) {
  return sV(t2, e37);
}, cover: cV, covered: aV, disjoint: function(e37, t2) {
  return !rV(e37, t2);
}, equal: function(e37, t2) {
  return lV(e37, t2).equal();
}, inside: sV, intersect: rV, relate: lV, touch: function(e37, t2) {
  return lV(e37, t2).touch();
} });
var pV = class e37 {
  constructor(e38 = 1, t2 = 0, n2 = 0, o3 = 1, i3 = 0, r3 = 0) {
    this.a = e38, this.b = t2, this.c = n2, this.d = o3, this.tx = i3, this.ty = r3;
  }
  fromMatrix3x3(t2) {
    const [n2, o3, i3] = t2[0], [r3, s2, a3] = t2[1];
    return new e37(n2, r3, o3, s2, i3, a3);
  }
  toMatrix3x3() {
    return [[this.a, this.c, this.tx], [this.b, this.d, this.ty], [0, 0, 1]];
  }
  clone() {
    return new e37(this.a, this.b, this.c, this.d, this.tx, this.ty);
  }
  transform(e38) {
    return [e38[0] * this.a + e38[1] * this.c + this.tx, e38[0] * this.b + e38[1] * this.d + this.ty];
  }
  multiply(t2) {
    return new e37(this.a * t2.a + this.c * t2.b, this.b * t2.a + this.d * t2.b, this.a * t2.c + this.c * t2.d, this.b * t2.c + this.d * t2.d, this.a * t2.tx + this.c * t2.ty + this.tx, this.b * t2.tx + this.d * t2.ty + this.ty);
  }
  translate(...t2) {
    let n2, o3;
    if (t2.length != 1 || isNaN(t2[0].x) || isNaN(t2[0].y)) {
      if (t2.length !== 2 || typeof t2[0] != "number" || typeof t2[1] != "number")
        throw DX.ILLEGAL_PARAMETERS;
      n2 = t2[0], o3 = t2[1];
    } else
      n2 = t2[0].x, o3 = t2[0].y;
    return this.multiply(new e37(1, 0, 0, 1, n2, o3));
  }
  rotate(t2, n2 = 0, o3 = 0) {
    let i3 = Math.cos(t2), r3 = Math.sin(t2);
    return this.translate(n2, o3).multiply(new e37(i3, r3, -r3, i3, 0, 0)).translate(-n2, -o3);
  }
  scale(t2, n2) {
    return this.multiply(new e37(t2, 0, 0, n2, 0, 0));
  }
  equalTo(e38) {
    return !!kX.Utils.EQ(this.tx, e38.tx) && (!!kX.Utils.EQ(this.ty, e38.ty) && (!!kX.Utils.EQ(this.a, e38.a) && (!!kX.Utils.EQ(this.b, e38.b) && (!!kX.Utils.EQ(this.c, e38.c) && !!kX.Utils.EQ(this.d, e38.d)))));
  }
};
kX.Matrix = pV;
kX.matrix = (...e38) => new kX.Matrix(...e38);
var mV = class {
  constructor(e38, t2) {
    this.low = e38, this.high = t2;
  }
  get max() {
    return this.clone();
  }
  less_than(e38) {
    return this.low < e38.low || this.low === e38.low && this.high < e38.high;
  }
  equal_to(e38) {
    return this.low === e38.low && this.high === e38.high;
  }
  intersect(e38) {
    return !this.not_intersect(e38);
  }
  not_intersect(e38) {
    return this.high < e38.low || e38.high < this.low;
  }
  merge(e38) {
    const t2 = this.low === undefined ? e38.low : this.low < e38.low ? this.low : e38.low, n2 = this.high === undefined ? e38.high : this.high > e38.high ? this.high : e38.high, o3 = this.clone();
    return o3.low = t2, o3.high = n2, o3;
  }
  output() {
    return [this.low, this.high];
  }
  comparable_less_than(e38, t2) {
    return e38 < t2;
  }
};
var gV = class e38 extends mV {
  clone() {
    return new e38(this.low, this.high);
  }
};
var fV = class {
  constructor(e39, t2, n2 = null, o3 = null, i3 = null, r3 = 0) {
    if (this.left = n2, this.right = o3, this.parent = i3, this.color = r3, this.item = { key: undefined, values: [] }, t2 !== undefined && this.item.values.push(t2), e39 !== undefined)
      if (Array.isArray(e39)) {
        const [t3, n3] = e39;
        if (!Number.isNaN(t3) && !Number.isNaN(n3)) {
          let e40 = t3, o4 = n3;
          e40 > o4 && ([e40, o4] = [o4, e40]), this.item.key = new gV(e40, o4);
        }
      } else
        this.item.key = e39;
    this.max = this.item.key ? this.item.key.max : undefined;
  }
  isNil() {
    return this.item.key === undefined && this.item.values.length === 0 && this.left === null && this.right === null && this.color === 0;
  }
  requireKey() {
    if (!this.item.key)
      throw new Error("Node key is undefined (nil/sentinel). Operation is not applicable.");
    return this.item.key;
  }
  less_than(e39) {
    const t2 = this.requireKey(), n2 = e39.requireKey();
    return t2.less_than(n2);
  }
  _value_equal(e39) {
    const t2 = this.item.values[0], n2 = e39.item.values[0];
    return t2 && n2 && t2.equal_to ? t2.equal_to(n2) : t2 === n2;
  }
  equal_to(e39) {
    const t2 = this.requireKey(), n2 = e39.requireKey();
    return t2.equal_to(n2);
  }
  intersect(e39) {
    const t2 = this.requireKey(), n2 = e39.requireKey();
    return t2.intersect(n2);
  }
  copy_data(e39) {
    this.item.key = e39.item.key, this.item.values = e39.item.values.slice();
  }
  update_max() {
    this.max = this.item.key ? this.item.key.max : undefined, this.right && this.right.max && (this.max = this.max ? this.max.merge(this.right.max) : this.right.max), this.left && this.left.max && (this.max = this.max ? this.max.merge(this.left.max) : this.left.max);
  }
  not_intersect_left_subtree(e39) {
    if (!this.left)
      return true;
    const t2 = this.left.max ? this.left.max.high : this.left.item.key.high, n2 = this.requireKey(), o3 = e39.requireKey();
    return n2.comparable_less_than(t2, o3.low);
  }
  not_intersect_right_subtree(e39) {
    if (!this.right)
      return true;
    const t2 = this.right.max ? this.right.max.low : this.right.item.key.low, n2 = this.requireKey(), o3 = e39.requireKey();
    return n2.comparable_less_than(o3.high, t2);
  }
};
var _V = class e39 {
  constructor() {
    this.root = null, this.nil_node = new fV;
  }
  get size() {
    let e40 = 0;
    return this.tree_walk(this.root, (t2) => e40 += t2.item.values.length), e40;
  }
  get keys() {
    const e40 = [];
    return this.tree_walk(this.root, (t2) => e40.push(t2.item.key.output())), e40;
  }
  get values() {
    const e40 = [];
    return this.tree_walk(this.root, (t2) => {
      for (const n2 of t2.item.values)
        e40.push(n2);
    }), e40;
  }
  get items() {
    const e40 = [];
    return this.tree_walk(this.root, (t2) => {
      const n2 = t2.item.key.output();
      for (const o3 of t2.item.values)
        e40.push({ key: n2, value: o3 });
    }), e40;
  }
  isEmpty() {
    return this.root == null || this.root === this.nil_node;
  }
  clear() {
    this.root = null;
  }
  insert(e40, t2 = e40) {
    if (e40 === undefined)
      return;
    const n2 = this.tree_search(this.root, new fV(e40));
    if (n2)
      return n2.item.values.push(t2), n2;
    const o3 = new fV(e40, t2, this.nil_node, this.nil_node, null, 1);
    return this.tree_insert(o3), this.recalc_max(o3), o3;
  }
  exist(e40, t2 = e40) {
    const n2 = this.tree_search(this.root, new fV(e40));
    return !!n2 && (arguments.length < 2 || t2 === e40 || n2.item.values.some((e41) => e41 && e41.equal_to ? e41.equal_to(t2) : e41 === t2));
  }
  remove(e40, t2 = e40) {
    const n2 = this.tree_search(this.root, new fV(e40));
    if (!n2)
      return;
    if (arguments.length < 2)
      return this.tree_delete(n2), n2;
    const o3 = n2.item.values.findIndex((e41) => e41 && e41.equal_to ? e41.equal_to(t2) : e41 === t2);
    return o3 >= 0 ? (n2.item.values.splice(o3, 1), n2.item.values.length === 0 && this.tree_delete(n2), n2) : undefined;
  }
  search(e40, t2 = (e41, t3) => e41 === t3 ? t3.output() : e41) {
    const n2 = new fV(e40), o3 = [];
    this.tree_search_interval(this.root, n2, o3);
    const i3 = [];
    for (const e41 of o3)
      for (const n3 of e41.item.values)
        i3.push(t2(n3, e41.item.key));
    return i3;
  }
  intersect_any(e40) {
    const t2 = new fV(e40);
    return this.tree_find_any_interval(this.root, t2);
  }
  forEach(e40) {
    this.tree_walk(this.root, (t2) => {
      for (const n2 of t2.item.values)
        e40(t2.item.key, n2);
    });
  }
  map(t2) {
    const n2 = new e39;
    return this.tree_walk(this.root, (e40) => {
      for (const o3 of e40.item.values)
        n2.insert(e40.item.key, t2(o3, e40.item.key));
    }), n2;
  }
  *iterate(e40, t2 = (e41, t3) => e41 === t3 ? t3.output() : e41) {
    let n2 = null;
    for (e40 ? n2 = this.tree_search_nearest_forward(this.root, new fV(e40)) : this.root && (n2 = this.local_minimum(this.root));n2; ) {
      for (const e41 of n2.item.values)
        yield t2(e41, n2.item.key);
      n2 = this.tree_successor(n2);
    }
  }
  recalc_max(e40) {
    let t2 = e40;
    for (;t2.parent != null; )
      t2.parent.update_max(), t2 = t2.parent;
  }
  tree_insert(e40) {
    let t2 = this.root, n2 = null;
    if (this.root == null || this.root === this.nil_node)
      this.root = e40;
    else {
      for (;t2 !== this.nil_node; )
        n2 = t2, t2 = e40.less_than(t2) ? t2.left : t2.right;
      e40.parent = n2, e40.less_than(n2) ? n2.left = e40 : n2.right = e40;
    }
    this.insert_fixup(e40);
  }
  insert_fixup(e40) {
    let t2, n2;
    for (t2 = e40;t2 !== this.root && t2.parent.color === 1; )
      t2.parent === t2.parent.parent.left ? (n2 = t2.parent.parent.right, n2.color === 1 ? (t2.parent.color = 0, n2.color = 0, t2.parent.parent.color = 1, t2 = t2.parent.parent) : (t2 === t2.parent.right && (t2 = t2.parent, this.rotate_left(t2)), t2.parent.color = 0, t2.parent.parent.color = 1, this.rotate_right(t2.parent.parent))) : (n2 = t2.parent.parent.left, n2.color === 1 ? (t2.parent.color = 0, n2.color = 0, t2.parent.parent.color = 1, t2 = t2.parent.parent) : (t2 === t2.parent.left && (t2 = t2.parent, this.rotate_right(t2)), t2.parent.color = 0, t2.parent.parent.color = 1, this.rotate_left(t2.parent.parent)));
    this.root.color = 0;
  }
  tree_delete(e40) {
    let t2, n2;
    t2 = e40.left === this.nil_node || e40.right === this.nil_node ? e40 : this.tree_successor(e40), n2 = t2.left !== this.nil_node ? t2.left : t2.right, n2.parent = t2.parent, t2 === this.root ? this.root = n2 : (t2 === t2.parent.left ? t2.parent.left = n2 : t2.parent.right = n2, t2.parent.update_max()), this.recalc_max(n2), t2 !== e40 && (e40.copy_data(t2), e40.update_max(), this.recalc_max(e40)), t2.color === 0 && this.delete_fixup(n2);
  }
  delete_fixup(e40) {
    let t2, n2 = e40;
    for (;n2 !== this.root && n2.parent != null && n2.color === 0; )
      n2 === n2.parent.left ? (t2 = n2.parent.right, t2.color === 1 && (t2.color = 0, n2.parent.color = 1, this.rotate_left(n2.parent), t2 = n2.parent.right), t2.left.color === 0 && t2.right.color === 0 ? (t2.color = 1, n2 = n2.parent) : (t2.right.color === 0 && (t2.color = 1, t2.left.color = 0, this.rotate_right(t2), t2 = n2.parent.right), t2.color = n2.parent.color, n2.parent.color = 0, t2.right.color = 0, this.rotate_left(n2.parent), n2 = this.root)) : (t2 = n2.parent.left, t2.color === 1 && (t2.color = 0, n2.parent.color = 1, this.rotate_right(n2.parent), t2 = n2.parent.left), t2.left.color === 0 && t2.right.color === 0 ? (t2.color = 1, n2 = n2.parent) : (t2.left.color === 0 && (t2.color = 1, t2.right.color = 0, this.rotate_left(t2), t2 = n2.parent.left), t2.color = n2.parent.color, n2.parent.color = 0, t2.left.color = 0, this.rotate_right(n2.parent), n2 = this.root));
    n2.color = 0;
  }
  tree_search(e40, t2) {
    if (e40 != null && e40 !== this.nil_node)
      return t2.equal_to(e40) ? e40 : t2.less_than(e40) ? this.tree_search(e40.left, t2) : this.tree_search(e40.right, t2);
  }
  tree_search_nearest_forward(e40, t2) {
    let n2 = null, o3 = e40;
    for (;o3 && o3 !== this.nil_node; )
      o3.less_than(t2) ? o3.intersect(t2) ? (n2 = o3, o3 = o3.left) : o3 = o3.right : (n2 && !o3.less_than(n2) || (n2 = o3), o3 = o3.left);
    return n2 || null;
  }
  tree_search_interval(e40, t2, n2) {
    e40 != null && e40 !== this.nil_node && (e40.left === this.nil_node || e40.not_intersect_left_subtree(t2) || this.tree_search_interval(e40.left, t2, n2), e40.intersect(t2) && n2.push(e40), e40.right === this.nil_node || e40.not_intersect_right_subtree(t2) || this.tree_search_interval(e40.right, t2, n2));
  }
  tree_find_any_interval(e40, t2) {
    let n2 = false;
    return e40 != null && e40 !== this.nil_node && (e40.left === this.nil_node || e40.not_intersect_left_subtree(t2) || (n2 = this.tree_find_any_interval(e40.left, t2)), n2 || (n2 = e40.intersect(t2)), n2 || e40.right === this.nil_node || e40.not_intersect_right_subtree(t2) || (n2 = this.tree_find_any_interval(e40.right, t2))), n2;
  }
  local_minimum(e40) {
    let t2 = e40;
    for (;t2.left != null && t2.left !== this.nil_node; )
      t2 = t2.left;
    return t2;
  }
  local_maximum(e40) {
    let t2 = e40;
    for (;t2.right != null && t2.right !== this.nil_node; )
      t2 = t2.right;
    return t2;
  }
  tree_successor(e40) {
    let t2, n2, o3;
    if (e40.right !== this.nil_node)
      t2 = this.local_minimum(e40.right);
    else {
      for (n2 = e40, o3 = e40.parent;o3 != null && o3.right === n2; )
        n2 = o3, o3 = o3.parent;
      t2 = o3;
    }
    return t2;
  }
  rotate_left(e40) {
    const t2 = e40.right;
    e40.right = t2.left, t2.left !== this.nil_node && (t2.left.parent = e40), t2.parent = e40.parent, e40 === this.root ? this.root = t2 : e40 === e40.parent.left ? e40.parent.left = t2 : e40.parent.right = t2, t2.left = e40, e40.parent = t2, e40 !== null && e40 !== this.nil_node && e40.update_max(), t2 != null && t2 !== this.nil_node && t2.update_max();
  }
  rotate_right(e40) {
    const t2 = e40.left;
    e40.left = t2.right, t2.right !== this.nil_node && (t2.right.parent = e40), t2.parent = e40.parent, e40 === this.root ? this.root = t2 : e40 === e40.parent.left ? e40.parent.left = t2 : e40.parent.right = t2, t2.right = e40, e40.parent = t2, e40 !== null && e40 !== this.nil_node && e40.update_max(), t2 != null && t2 !== this.nil_node && t2.update_max();
  }
  tree_walk(e40, t2) {
    e40 != null && e40 !== this.nil_node && (this.tree_walk(e40.left, t2), t2(e40), this.tree_walk(e40.right, t2));
  }
  testRedBlackProperty() {
    let e40 = true;
    return this.tree_walk(this.root, function(t2) {
      t2.color === 1 && (t2.left.color === 0 && t2.right.color === 0 || (e40 = false));
    }), e40;
  }
  testBlackHeightProperty(e40) {
    let t2 = 0, n2 = 0, o3 = 0;
    if (e40.color === 0 && t2++, n2 = e40.left !== this.nil_node ? this.testBlackHeightProperty(e40.left) : 1, o3 = e40.right !== this.nil_node ? this.testBlackHeightProperty(e40.right) : 1, n2 !== o3)
      throw new Error("Red-black height property violated");
    return t2 += n2, t2;
  }
};
var yV = class extends Set {
  constructor(e40) {
    super(e40), this.index = new _V, this.forEach((e41) => this.index.insert(e41));
  }
  add(e40) {
    let t2 = this.size;
    const { key: n2, value: o3 } = e40, i3 = n2 || e40.box, r3 = o3 || e40;
    return super.add(r3), this.size > t2 && this.index.insert(i3, r3), this;
  }
  delete(e40) {
    const { key: t2, value: n2 } = e40, o3 = t2 || e40.box, i3 = n2 || e40;
    let r3 = super.delete(i3);
    return r3 && this.index.remove(o3, i3), r3;
  }
  clear() {
    super.clear(), this.index = new _V;
  }
  search(e40) {
    return this.index.search(e40);
  }
  hit(e40) {
    let t2 = new kX.Box(e40.x - 1, e40.y - 1, e40.x + 1, e40.y + 1);
    return this.index.search(t2).filter((t3) => e40.on(t3));
  }
  svg() {
    return [...this].reduce((e40, t2) => e40 + t2.svg(), "");
  }
};
kX.PlanarSet = yV;
var bV = class {
  get name() {
    throw DX.CANNOT_INVOKE_ABSTRACT_METHOD;
  }
  get box() {
    throw DX.CANNOT_INVOKE_ABSTRACT_METHOD;
  }
  clone() {
    throw DX.CANNOT_INVOKE_ABSTRACT_METHOD;
  }
  translate(...e40) {
    return this.transform(new pV().translate(...e40));
  }
  rotate(e40, t2 = new kX.Point) {
    return this.transform(new pV().rotate(e40, t2.x, t2.y));
  }
  scale(e40, t2) {
    return this.transform(new pV().scale(e40, t2));
  }
  transform(...e40) {
    throw DX.CANNOT_INVOKE_ABSTRACT_METHOD;
  }
  toJSON() {
    return Object.assign({}, this, { name: this.name });
  }
  svg(e40 = {}) {
    throw DX.CANNOT_INVOKE_ABSTRACT_METHOD;
  }
};
kX.Point = class e40 extends bV {
  constructor(...e41) {
    if (super(), this.x = 0, this.y = 0, e41.length !== 0) {
      if (e41.length === 1 && e41[0] instanceof Array && e41[0].length === 2) {
        let t2 = e41[0];
        if (typeof t2[0] == "number" && typeof t2[1] == "number")
          return this.x = t2[0], void (this.y = t2[1]);
      }
      if (e41.length === 1 && e41[0] instanceof Object && e41[0].name === "point") {
        let { x: t2, y: n2 } = e41[0];
        return this.x = t2, void (this.y = n2);
      }
      if (e41.length === 2 && typeof e41[0] == "number" && typeof e41[1] == "number")
        return this.x = e41[0], void (this.y = e41[1]);
      throw DX.ILLEGAL_PARAMETERS;
    }
  }
  get box() {
    return new kX.Box(this.x, this.y, this.x, this.y);
  }
  clone() {
    return new kX.Point(this.x, this.y);
  }
  get vertices() {
    return [this.clone()];
  }
  equalTo(e41) {
    return kX.Utils.EQ(this.x, e41.x) && kX.Utils.EQ(this.y, e41.y);
  }
  lessThan(e41) {
    return !!kX.Utils.LT(this.y, e41.y) || !(!kX.Utils.EQ(this.y, e41.y) || !kX.Utils.LT(this.x, e41.x));
  }
  transform(e41) {
    return new kX.Point(e41.transform([this.x, this.y]));
  }
  projectionOn(e41) {
    if (this.equalTo(e41.pt))
      return this.clone();
    let t2 = new kX.Vector(this, e41.pt);
    if (kX.Utils.EQ_0(t2.cross(e41.norm)))
      return e41.pt.clone();
    let n2 = t2.dot(e41.norm), o3 = e41.norm.multiply(n2);
    return this.translate(o3);
  }
  leftTo(e41) {
    let t2 = new kX.Vector(e41.pt, this);
    return kX.Utils.GT(t2.dot(e41.norm), 0);
  }
  distanceTo(t2) {
    if (t2 instanceof e40) {
      let e41 = t2.x - this.x, n2 = t2.y - this.y;
      return [Math.sqrt(e41 * e41 + n2 * n2), new kX.Segment(this, t2)];
    }
    return t2 instanceof kX.Line ? kX.Distance.point2line(this, t2) : t2 instanceof kX.Circle ? kX.Distance.point2circle(this, t2) : t2 instanceof kX.Segment ? kX.Distance.point2segment(this, t2) : t2 instanceof kX.Arc ? kX.Distance.point2arc(this, t2) : t2 instanceof kX.Polygon ? kX.Distance.point2polygon(this, t2) : t2 instanceof kX.PlanarSet ? kX.Distance.shape2planarSet(this, t2) : t2 instanceof kX.Multiline ? kX.Distance.shape2multiline(this, t2) : undefined;
  }
  on(e41) {
    if (e41 instanceof kX.Point)
      return this.equalTo(e41);
    if (e41.contains && e41.contains instanceof Function)
      return e41.contains(this);
    throw kX.Errors.UNSUPPORTED_SHAPE_TYPE;
  }
  get name() {
    return "point";
  }
  svg(e41 = {}) {
    const t2 = e41.r ?? 3;
    return `
<circle cx="${this.x}" cy="${this.y}" r="${t2}"
            ${FX({ fill: "red", ...e41 })} />`;
  }
};
kX.point = (...e41) => new kX.Point(...e41);
kX.Vector = class extends bV {
  constructor(...e41) {
    if (super(), this.x = 0, this.y = 0, e41.length !== 0) {
      if (e41.length === 1 && e41[0] instanceof Array && e41[0].length === 2) {
        let t2 = e41[0];
        if (typeof t2[0] == "number" && typeof t2[1] == "number")
          return this.x = t2[0], void (this.y = t2[1]);
      }
      if (e41.length === 1 && e41[0] instanceof Object && e41[0].name === "vector") {
        let { x: t2, y: n2 } = e41[0];
        return this.x = t2, void (this.y = n2);
      }
      if (e41.length === 1 && e41[0] instanceof Object && e41[0].name === "segment") {
        let { start: t2, end: n2 } = e41[0];
        return this.x = n2.x - t2.x, void (this.y = n2.y - t2.y);
      }
      if (e41.length === 2) {
        let t2 = e41[0], n2 = e41[1];
        if (typeof t2 == "number" && typeof n2 == "number")
          return this.x = t2, void (this.y = n2);
        if (t2 instanceof kX.Point && n2 instanceof kX.Point)
          return this.x = n2.x - t2.x, void (this.y = n2.y - t2.y);
      }
      throw DX.ILLEGAL_PARAMETERS;
    }
  }
  clone() {
    return new kX.Vector(this.x, this.y);
  }
  get slope() {
    let e41 = Math.atan2(this.y, this.x);
    return e41 < 0 && (e41 = 2 * Math.PI + e41), e41;
  }
  get length() {
    return Math.sqrt(this.dot(this));
  }
  isZeroLength() {
    return kX.Utils.EQ_0(this.length);
  }
  equalTo(e41) {
    return kX.Utils.EQ(this.x, e41.x) && kX.Utils.EQ(this.y, e41.y);
  }
  multiply(e41) {
    return new kX.Vector(e41 * this.x, e41 * this.y);
  }
  dot(e41) {
    return this.x * e41.x + this.y * e41.y;
  }
  cross(e41) {
    return this.x * e41.y - this.y * e41.x;
  }
  normalize() {
    if (this.isZeroLength())
      throw DX.ZERO_DIVISION;
    return new kX.Vector(this.x / this.length, this.y / this.length);
  }
  rotate(e41, t2 = new kX.Point) {
    if (t2.x === 0 && t2.y === 0)
      return this.transform(new pV().rotate(e41));
    throw DX.OPERATION_IS_NOT_SUPPORTED;
  }
  transform(e41) {
    return new kX.Vector(e41.transform([this.x, this.y]));
  }
  rotate90CCW() {
    return new kX.Vector(-this.y, this.x);
  }
  rotate90CW() {
    return new kX.Vector(this.y, -this.x);
  }
  invert() {
    return new kX.Vector(-this.x, -this.y);
  }
  add(e41) {
    return new kX.Vector(this.x + e41.x, this.y + e41.y);
  }
  subtract(e41) {
    return new kX.Vector(this.x - e41.x, this.y - e41.y);
  }
  angleTo(e41) {
    let t2 = this.normalize(), n2 = e41.normalize(), o3 = Math.atan2(t2.cross(n2), t2.dot(n2));
    return o3 < 0 && (o3 += 2 * Math.PI), o3;
  }
  projectionOn(e41) {
    let t2 = e41.normalize(), n2 = this.dot(t2);
    return t2.multiply(n2);
  }
  get name() {
    return "vector";
  }
};
var xV = (...e41) => new kX.Vector(...e41);
kX.vector = xV;
kX.Segment = class e41 extends bV {
  constructor(...e42) {
    if (super(), this.ps = new kX.Point, this.pe = new kX.Point, e42.length !== 0) {
      if (e42.length === 1 && e42[0] instanceof Array && e42[0].length === 4) {
        let t2 = e42[0];
        return this.ps = new kX.Point(t2[0], t2[1]), void (this.pe = new kX.Point(t2[2], t2[3]));
      }
      if (e42.length === 1 && e42[0] instanceof Object && e42[0].name === "segment") {
        let { ps: t2, pe: n2 } = e42[0];
        return this.ps = new kX.Point(t2.x, t2.y), void (this.pe = new kX.Point(n2.x, n2.y));
      }
      if (!(e42.length === 1 && e42[0] instanceof kX.Point)) {
        if (e42.length === 2 && e42[0] instanceof kX.Point && e42[1] instanceof kX.Point)
          return this.ps = e42[0].clone(), void (this.pe = e42[1].clone());
        if (e42.length === 4)
          return this.ps = new kX.Point(e42[0], e42[1]), void (this.pe = new kX.Point(e42[2], e42[3]));
        throw DX.ILLEGAL_PARAMETERS;
      }
      this.ps = e42[0].clone();
    }
  }
  clone() {
    return new kX.Segment(this.start, this.end);
  }
  get start() {
    return this.ps;
  }
  get end() {
    return this.pe;
  }
  get vertices() {
    return [this.ps.clone(), this.pe.clone()];
  }
  get length() {
    return this.start.distanceTo(this.end)[0];
  }
  get slope() {
    return new kX.Vector(this.start, this.end).slope;
  }
  get box() {
    return new kX.Box(Math.min(this.start.x, this.end.x), Math.min(this.start.y, this.end.y), Math.max(this.start.x, this.end.x), Math.max(this.start.y, this.end.y));
  }
  equalTo(e42) {
    return this.ps.equalTo(e42.ps) && this.pe.equalTo(e42.pe);
  }
  contains(e42) {
    return kX.Utils.EQ_0(this.distanceToPoint(e42));
  }
  intersect(e42) {
    return e42 instanceof kX.Point ? this.contains(e42) ? [e42] : [] : e42 instanceof kX.Line ? HX(this, e42) : e42 instanceof kX.Ray ? hH(e42, this) : e42 instanceof kX.Segment ? VX(this, e42) : e42 instanceof kX.Circle ? GX(this, e42) : e42 instanceof kX.Box ? function(e43, t2) {
      let n2 = [];
      for (let o3 of t2.toSegments()) {
        let t3 = VX(o3, e43);
        for (let e44 of t3)
          n2.push(e44);
      }
      return n2;
    }(this, e42) : e42 instanceof kX.Arc ? UX(this, e42) : e42 instanceof kX.Polygon ? nH(this, e42) : e42 instanceof kX.Multiline ? fH(this, e42) : undefined;
  }
  distanceTo(e42) {
    if (e42 instanceof kX.Point) {
      let [t2, n2] = kX.Distance.point2segment(e42, this);
      return n2 = n2.reverse(), [t2, n2];
    }
    if (e42 instanceof kX.Circle) {
      let [t2, n2] = kX.Distance.segment2circle(this, e42);
      return [t2, n2];
    }
    if (e42 instanceof kX.Line) {
      let [t2, n2] = kX.Distance.segment2line(this, e42);
      return [t2, n2];
    }
    if (e42 instanceof kX.Segment) {
      let [t2, n2] = kX.Distance.segment2segment(this, e42);
      return [t2, n2];
    }
    if (e42 instanceof kX.Arc) {
      let [t2, n2] = kX.Distance.segment2arc(this, e42);
      return [t2, n2];
    }
    if (e42 instanceof kX.Polygon) {
      let [t2, n2] = kX.Distance.shape2polygon(this, e42);
      return [t2, n2];
    }
    if (e42 instanceof kX.PlanarSet) {
      let [t2, n2] = kX.Distance.shape2planarSet(this, e42);
      return [t2, n2];
    }
    if (e42 instanceof kX.Multiline)
      return kX.Distance.shape2multiline(this, e42);
  }
  tangentInStart() {
    return new kX.Vector(this.start, this.end).normalize();
  }
  tangentInEnd() {
    return new kX.Vector(this.end, this.start).normalize();
  }
  reverse() {
    return new e41(this.end, this.start);
  }
  split(e42) {
    return this.start.equalTo(e42) ? [null, this.clone()] : this.end.equalTo(e42) ? [this.clone(), null] : [new kX.Segment(this.start, e42), new kX.Segment(e42, this.end)];
  }
  middle() {
    return new kX.Point((this.start.x + this.end.x) / 2, (this.start.y + this.end.y) / 2);
  }
  pointAtLength(e42) {
    if (e42 > this.length || e42 < 0)
      return null;
    if (e42 == 0)
      return this.start;
    if (e42 == this.length)
      return this.end;
    let t2 = e42 / this.length;
    return new kX.Point((this.end.x - this.start.x) * t2 + this.start.x, (this.end.y - this.start.y) * t2 + this.start.y);
  }
  distanceToPoint(e42) {
    let [t2, ...n2] = kX.Distance.point2segment(e42, this);
    return t2;
  }
  definiteIntegral(e42 = 0) {
    return (this.end.x - this.start.x) * (this.start.y - e42 + (this.end.y - e42)) / 2;
  }
  transform(t2 = new kX.Matrix) {
    return new e41(this.ps.transform(t2), this.pe.transform(t2));
  }
  isZeroLength() {
    return this.ps.equalTo(this.pe);
  }
  sortPoints(e42) {
    return new kX.Line(this.start, this.end).sortPoints(e42);
  }
  get name() {
    return "segment";
  }
  svg(e42 = {}) {
    return `
<line x1="${this.start.x}" y1="${this.start.y}" x2="${this.end.x}" y2="${this.end.y}" ${FX(e42)} />`;
  }
};
kX.segment = (...e42) => new kX.Segment(...e42);
var { vector: vV } = kX;
kX.Line = class e42 extends bV {
  constructor(...t2) {
    if (super(), this.pt = new kX.Point, this.norm = new kX.Vector(0, 1), t2.length !== 0) {
      if (t2.length === 1 && t2[0] instanceof Object && t2[0].name === "line") {
        let { pt: e43, norm: n2 } = t2[0];
        return this.pt = new kX.Point(e43), void (this.norm = new kX.Vector(n2));
      }
      if (t2.length === 2) {
        let n2 = t2[0], o3 = t2[1];
        if (n2 instanceof kX.Point && o3 instanceof kX.Point)
          return this.pt = n2, this.norm = e42.points2norm(n2, o3), void (this.norm.dot(vV(this.pt.x, this.pt.y)) >= 0 && this.norm.invert());
        if (n2 instanceof kX.Point && o3 instanceof kX.Vector) {
          if (kX.Utils.EQ_0(o3.x) && kX.Utils.EQ_0(o3.y))
            throw DX.ILLEGAL_PARAMETERS;
          return this.pt = n2.clone(), this.norm = o3.clone(), this.norm = this.norm.normalize(), void (this.norm.dot(vV(this.pt.x, this.pt.y)) >= 0 && this.norm.invert());
        }
        if (n2 instanceof kX.Vector && o3 instanceof kX.Point) {
          if (kX.Utils.EQ_0(n2.x) && kX.Utils.EQ_0(n2.y))
            throw DX.ILLEGAL_PARAMETERS;
          return this.pt = o3.clone(), this.norm = n2.clone(), this.norm = this.norm.normalize(), void (this.norm.dot(vV(this.pt.x, this.pt.y)) >= 0 && this.norm.invert());
        }
      }
      throw DX.ILLEGAL_PARAMETERS;
    }
  }
  clone() {
    return new kX.Line(this.pt, this.norm);
  }
  get start() {}
  get end() {}
  get length() {
    return Number.POSITIVE_INFINITY;
  }
  get box() {
    return new kX.Box(Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY);
  }
  get middle() {}
  get slope() {
    return new kX.Vector(this.norm.y, -this.norm.x).slope;
  }
  get standard() {
    return [this.norm.x, this.norm.y, this.norm.dot(vV(this.pt.x, this.pt.y))];
  }
  parallelTo(e43) {
    return kX.Utils.EQ_0(this.norm.cross(e43.norm));
  }
  incidentTo(e43) {
    return this.parallelTo(e43) && this.pt.on(e43);
  }
  contains(e43) {
    if (this.pt.equalTo(e43))
      return true;
    let t2 = new kX.Vector(this.pt, e43);
    return kX.Utils.EQ_0(this.norm.dot(t2));
  }
  coord(e43) {
    return vV(e43.x, e43.y).cross(this.norm);
  }
  intersect(e43) {
    return e43 instanceof kX.Point ? this.contains(e43) ? [e43] : [] : e43 instanceof kX.Line ? jX(this, e43) : e43 instanceof kX.Ray ? pH(e43, this) : e43 instanceof kX.Circle ? $X(this, e43) : e43 instanceof kX.Box ? YX(this, e43) : e43 instanceof kX.Segment ? HX(e43, this) : e43 instanceof kX.Arc ? XX(this, e43) : e43 instanceof kX.Polygon ? iH(this, e43) : e43 instanceof kX.Multiline ? fH(this, e43) : undefined;
  }
  distanceTo(e43) {
    if (e43 instanceof kX.Point) {
      let [t2, n2] = kX.Distance.point2line(e43, this);
      return n2 = n2.reverse(), [t2, n2];
    }
    if (e43 instanceof kX.Circle) {
      let [t2, n2] = kX.Distance.circle2line(e43, this);
      return n2 = n2.reverse(), [t2, n2];
    }
    if (e43 instanceof kX.Segment) {
      let [t2, n2] = kX.Distance.segment2line(e43, this);
      return [t2, n2.reverse()];
    }
    if (e43 instanceof kX.Arc) {
      let [t2, n2] = kX.Distance.arc2line(e43, this);
      return [t2, n2.reverse()];
    }
    if (e43 instanceof kX.Polygon) {
      let [t2, n2] = kX.Distance.shape2polygon(this, e43);
      return [t2, n2];
    }
  }
  split(e43) {
    if (e43 instanceof kX.Point)
      return [new kX.Ray(e43, this.norm), new kX.Ray(e43, this.norm)];
    {
      let t2 = new kX.Multiline([this]), n2 = this.sortPoints(e43);
      return t2.split(n2), t2.toShapes();
    }
  }
  rotate(e43, t2 = new kX.Point) {
    return new kX.Line(this.pt.rotate(e43, t2), this.norm.rotate(e43));
  }
  transform(e43) {
    return new kX.Line(this.pt.transform(e43), this.norm.clone());
  }
  sortPoints(e43) {
    return e43.slice().sort((e44, t2) => this.coord(e44) < this.coord(t2) ? -1 : this.coord(e44) > this.coord(t2) ? 1 : 0);
  }
  get name() {
    return "line";
  }
  svg(e43, t2 = {}) {
    let n2 = YX(this, e43);
    if (n2.length === 0)
      return "";
    let o3 = n2[0], i3 = n2.length === 2 ? n2[1] : n2.find((e44) => !e44.equalTo(o3));
    return i3 === undefined && (i3 = o3), new kX.Segment(o3, i3).svg(t2);
  }
  static points2norm(e43, t2) {
    if (e43.equalTo(t2))
      throw DX.ILLEGAL_PARAMETERS;
    return new kX.Vector(e43, t2).normalize().rotate90CCW();
  }
};
kX.line = (...e43) => new kX.Line(...e43);
kX.Circle = class extends bV {
  constructor(...e43) {
    if (super(), this.pc = new kX.Point, this.r = 1, e43.length === 1 && e43[0] instanceof Object && e43[0].name === "circle") {
      let { pc: t2, r: n2 } = e43[0];
      this.pc = new kX.Point(t2), this.r = n2;
    } else {
      let [t2, n2] = [...e43];
      t2 && t2 instanceof kX.Point && (this.pc = t2.clone()), n2 !== undefined && (this.r = n2);
    }
  }
  clone() {
    return new kX.Circle(this.pc.clone(), this.r);
  }
  get center() {
    return this.pc;
  }
  get box() {
    return new kX.Box(this.pc.x - this.r, this.pc.y - this.r, this.pc.x + this.r, this.pc.y + this.r);
  }
  contains(e43) {
    return e43 instanceof kX.Point ? kX.Utils.LE(e43.distanceTo(this.center)[0], this.r) : e43 instanceof kX.Segment ? kX.Utils.LE(e43.start.distanceTo(this.center)[0], this.r) && kX.Utils.LE(e43.end.distanceTo(this.center)[0], this.r) : e43 instanceof kX.Arc ? this.intersect(e43).length === 0 && kX.Utils.LE(e43.start.distanceTo(this.center)[0], this.r) && kX.Utils.LE(e43.end.distanceTo(this.center)[0], this.r) : e43 instanceof kX.Circle ? this.intersect(e43).length === 0 && kX.Utils.LE(e43.r, this.r) && kX.Utils.LE(e43.center.distanceTo(this.center)[0], this.r) : undefined;
  }
  toArc(e43 = true) {
    return new kX.Arc(this.center, this.r, Math.PI, -Math.PI, e43);
  }
  scale(e43, t2) {
    if (e43 !== t2)
      throw DX.OPERATION_IS_NOT_SUPPORTED;
    if (this.pc.x !== 0 || this.pc.y !== 0)
      throw DX.OPERATION_IS_NOT_SUPPORTED;
    return new kX.Circle(this.pc, this.r * e43);
  }
  transform(e43 = new kX.Matrix) {
    return new kX.Circle(this.pc.transform(e43), this.r);
  }
  intersect(e43) {
    return e43 instanceof kX.Point ? this.contains(e43) ? [e43] : [] : e43 instanceof kX.Line ? $X(e43, this) : e43 instanceof kX.Ray ? uH(e43, this) : e43 instanceof kX.Segment ? GX(e43, this) : e43 instanceof kX.Circle ? ZX(e43, this) : e43 instanceof kX.Box ? function(e44, t2) {
      let n2 = [];
      for (let o3 of t2.toSegments()) {
        let t3 = GX(o3, e44);
        for (let e45 of t3)
          n2.push(e45);
      }
      return n2;
    }(this, e43) : e43 instanceof kX.Arc ? JX(e43, this) : e43 instanceof kX.Polygon ? rH(this, e43) : e43 instanceof kX.Multiline ? fH(this, e43) : undefined;
  }
  distanceTo(e43) {
    if (e43 instanceof kX.Point) {
      let [t2, n2] = kX.Distance.point2circle(e43, this);
      return n2 = n2.reverse(), [t2, n2];
    }
    if (e43 instanceof kX.Circle) {
      let [t2, n2] = kX.Distance.circle2circle(this, e43);
      return [t2, n2];
    }
    if (e43 instanceof kX.Line) {
      let [t2, n2] = kX.Distance.circle2line(this, e43);
      return [t2, n2];
    }
    if (e43 instanceof kX.Segment) {
      let [t2, n2] = kX.Distance.segment2circle(e43, this);
      return n2 = n2.reverse(), [t2, n2];
    }
    if (e43 instanceof kX.Arc) {
      let [t2, n2] = kX.Distance.arc2circle(e43, this);
      return n2 = n2.reverse(), [t2, n2];
    }
    if (e43 instanceof kX.Polygon) {
      let [t2, n2] = kX.Distance.shape2polygon(this, e43);
      return [t2, n2];
    }
    if (e43 instanceof kX.PlanarSet) {
      let [t2, n2] = kX.Distance.shape2planarSet(this, e43);
      return [t2, n2];
    }
    if (e43 instanceof kX.Multiline) {
      let [t2, n2] = kX.Distance.shape2multiline(this, e43);
      return [t2, n2];
    }
  }
  get name() {
    return "circle";
  }
  svg(e43 = {}) {
    return `
<circle cx="${this.pc.x}" cy="${this.pc.y}" r="${this.r}"
                ${FX({ fill: "none", ...e43 })} />`;
  }
};
kX.circle = (...e43) => new kX.Circle(...e43);
kX.Arc = class extends bV {
  constructor(...e43) {
    if (super(), this.pc = new kX.Point, this.r = 1, this.startAngle = 0, this.endAngle = 2 * Math.PI, this.counterClockwise = true, e43.length !== 0)
      if (e43.length === 1 && e43[0] instanceof Object && e43[0].name === "arc") {
        let { pc: t2, r: n2, startAngle: o3, endAngle: i3, counterClockwise: r3 } = e43[0];
        this.pc = new kX.Point(t2.x, t2.y), this.r = n2, this.startAngle = o3, this.endAngle = i3, this.counterClockwise = r3;
      } else {
        let [t2, n2, o3, i3, r3] = [...e43];
        t2 && t2 instanceof kX.Point && (this.pc = t2.clone()), n2 !== undefined && (this.r = n2), o3 !== undefined && (this.startAngle = o3), i3 !== undefined && (this.endAngle = i3), r3 !== undefined && (this.counterClockwise = r3);
      }
  }
  clone() {
    return new kX.Arc(this.pc.clone(), this.r, this.startAngle, this.endAngle, this.counterClockwise);
  }
  get sweep() {
    let e43 = this.startAngle, t2 = this.endAngle;
    if (kX.Utils.EQ(Math.abs(e43 - t2), kX.PIx2))
      return kX.PIx2;
    Math.abs(e43) > kX.PIx2 && (e43 -= Math.trunc(e43 / kX.PIx2) * kX.PIx2), e43 < 0 && (e43 += kX.PIx2), Math.abs(t2) > kX.PIx2 && (t2 -= Math.trunc(t2 / kX.PIx2) * kX.PIx2), t2 < 0 && (t2 += kX.PIx2);
    let n2 = this.counterClockwise ? t2 - e43 : e43 - t2;
    return n2 < 0 && (n2 += kX.PIx2), n2;
  }
  get start() {
    return new kX.Point(this.pc.x + this.r, this.pc.y).rotate(this.startAngle, this.pc);
  }
  get end() {
    return new kX.Point(this.pc.x + this.r, this.pc.y).rotate(this.endAngle, this.pc);
  }
  get center() {
    return this.pc.clone();
  }
  get vertices() {
    return [this.start.clone(), this.end.clone()];
  }
  get length() {
    return Math.abs(this.sweep * this.r);
  }
  get box() {
    let e43 = this.breakToFunctional().reduce((e44, t2) => e44.merge(t2.start.box), new kX.Box);
    return e43 = e43.merge(this.end.box), e43;
  }
  contains(e43) {
    if (!kX.Utils.EQ(this.pc.distanceTo(e43)[0], this.r))
      return false;
    if (e43.equalTo(this.start))
      return true;
    let t2 = new kX.Vector(this.pc, e43).slope, n2 = new kX.Arc(this.pc, this.r, this.startAngle, t2, this.counterClockwise);
    return kX.Utils.LE(n2.length, this.length);
  }
  split(e43) {
    if (this.start.equalTo(e43))
      return [null, this.clone()];
    if (this.end.equalTo(e43))
      return [this.clone(), null];
    let t2 = new kX.Vector(this.pc, e43).slope;
    return [new kX.Arc(this.pc, this.r, this.startAngle, t2, this.counterClockwise), new kX.Arc(this.pc, this.r, t2, this.endAngle, this.counterClockwise)];
  }
  middle() {
    let e43 = this.counterClockwise ? this.startAngle + this.sweep / 2 : this.startAngle - this.sweep / 2;
    return new kX.Arc(this.pc, this.r, this.startAngle, e43, this.counterClockwise).end;
  }
  pointAtLength(e43) {
    if (e43 > this.length || e43 < 0)
      return null;
    if (e43 === 0)
      return this.start;
    if (e43 === this.length)
      return this.end;
    let t2 = e43 / this.length, n2 = this.counterClockwise ? this.startAngle + this.sweep * t2 : this.startAngle - this.sweep * t2;
    return new kX.Arc(this.pc, this.r, this.startAngle, n2, this.counterClockwise).end;
  }
  chordHeight() {
    return (1 - Math.cos(Math.abs(this.sweep / 2))) * this.r;
  }
  intersect(e43) {
    return e43 instanceof kX.Point ? this.contains(e43) ? [e43] : [] : e43 instanceof kX.Line ? XX(e43, this) : e43 instanceof kX.Ray ? dH(e43, this) : e43 instanceof kX.Circle ? JX(this, e43) : e43 instanceof kX.Segment ? UX(e43, this) : e43 instanceof kX.Box ? function(e44, t2) {
      let n2 = [];
      for (let o3 of t2.toSegments()) {
        let t3 = UX(o3, e44);
        for (let e45 of t3)
          n2.push(e45);
      }
      return n2;
    }(this, e43) : e43 instanceof kX.Arc ? qX(this, e43) : e43 instanceof kX.Polygon ? oH(this, e43) : e43 instanceof kX.Multiline ? fH(this, e43) : undefined;
  }
  distanceTo(e43) {
    if (e43 instanceof kX.Point) {
      let [t2, n2] = kX.Distance.point2arc(e43, this);
      return n2 = n2.reverse(), [t2, n2];
    }
    if (e43 instanceof kX.Circle) {
      let [t2, n2] = kX.Distance.arc2circle(this, e43);
      return [t2, n2];
    }
    if (e43 instanceof kX.Line) {
      let [t2, n2] = kX.Distance.arc2line(this, e43);
      return [t2, n2];
    }
    if (e43 instanceof kX.Segment) {
      let [t2, n2] = kX.Distance.segment2arc(e43, this);
      return n2 = n2.reverse(), [t2, n2];
    }
    if (e43 instanceof kX.Arc) {
      let [t2, n2] = kX.Distance.arc2arc(this, e43);
      return [t2, n2];
    }
    if (e43 instanceof kX.Polygon) {
      let [t2, n2] = kX.Distance.shape2polygon(this, e43);
      return [t2, n2];
    }
    if (e43 instanceof kX.PlanarSet) {
      let [t2, n2] = kX.Distance.shape2planarSet(this, e43);
      return [t2, n2];
    }
    if (e43 instanceof kX.Multiline)
      return kX.Distance.shape2multiline(this, e43);
  }
  breakToFunctional() {
    let e43 = [], t2 = [0, Math.PI / 2, Math.PI, 3 * Math.PI / 2], n2 = this.startAngle, o3 = this.endAngle;
    kX.Utils.EQ(Math.abs(n2 - o3), kX.PIx2) && (o3 = n2), Math.abs(n2) > kX.PIx2 && (n2 -= Math.trunc(n2 / kX.PIx2) * kX.PIx2), n2 < 0 && (n2 += kX.PIx2), Math.abs(o3) > kX.PIx2 && (o3 -= Math.trunc(o3 / kX.PIx2) * kX.PIx2), o3 < 0 && (o3 += kX.PIx2);
    let i3, r3, s2, a3 = n2;
    this.counterClockwise ? (r3 = Math.ceil(n2 / (Math.PI / 2)) % 4, s2 = 1) : (r3 = Math.floor(n2 / (Math.PI / 2)) % 4, s2 = -1);
    for (let o4 = 0, c3 = r3;o4 < 4; o4++, c3 = (c3 + s2 + 4) % 4) {
      if (i3 = t2[c3], i3 === a3)
        continue;
      let o5 = this.counterClockwise ? i3 - n2 : n2 - i3;
      if (o5 < 0 && (o5 += kX.PIx2), o5 > this.sweep)
        break;
      e43.push(new kX.Arc(this.pc, this.r, a3, i3, this.counterClockwise)), a3 = i3;
    }
    return e43.length === 0 ? (e43.push(this), e43) : (i3 = o3, a3 !== i3 && e43.push(new kX.Arc(this.pc, this.r, a3, i3, this.counterClockwise)), e43);
  }
  tangentInStart() {
    let e43 = new kX.Vector(this.pc, this.start), t2 = this.counterClockwise ? Math.PI / 2 : -Math.PI / 2;
    return e43.rotate(t2).normalize();
  }
  tangentInEnd() {
    let e43 = new kX.Vector(this.pc, this.end), t2 = this.counterClockwise ? -Math.PI / 2 : Math.PI / 2;
    return e43.rotate(t2).normalize();
  }
  reverse() {
    return new kX.Arc(this.pc, this.r, this.endAngle, this.startAngle, !this.counterClockwise);
  }
  transform(e43 = new kX.Matrix) {
    let t2 = this.start.transform(e43), n2 = this.end.transform(e43), o3 = this.pc.transform(e43), i3 = this.counterClockwise;
    return e43.a * e43.d < 0 && (i3 = !i3), kX.Arc.arcSE(o3, t2, n2, i3);
  }
  static arcSE(e43, t2, n2, o3) {
    let { vector: i3 } = kX, r3 = i3(e43, t2).slope, s2 = i3(e43, n2).slope;
    kX.Utils.EQ(r3, s2) && (s2 += 2 * Math.PI, o3 = true);
    let a3 = i3(e43, t2).length;
    return new kX.Arc(e43, a3, r3, s2, o3);
  }
  definiteIntegral(e43 = 0) {
    return this.breakToFunctional().reduce((t2, n2) => t2 + n2.circularSegmentDefiniteIntegral(e43), 0);
  }
  circularSegmentDefiniteIntegral(e43) {
    let t2 = new kX.Segment(this.start, this.end).definiteIntegral(e43), n2 = kX.Utils.EQ(this.sweep, kX.PIx2) ? 0 : this.circularSegmentArea();
    return this.counterClockwise ? t2 - n2 : t2 + n2;
  }
  circularSegmentArea() {
    return 0.5 * this.r * this.r * (this.sweep - Math.sin(this.sweep));
  }
  sortPoints(e43) {
    let { vector: t2 } = kX;
    return e43.slice().sort((e44, n2) => {
      let o3 = t2(this.pc, e44).slope, i3 = t2(this.pc, n2).slope;
      return o3 < i3 ? -1 : o3 > i3 ? 1 : 0;
    });
  }
  get name() {
    return "arc";
  }
  svg(e43 = {}) {
    let t2 = this.sweep <= Math.PI ? "0" : "1", n2 = this.counterClockwise ? "1" : "0";
    if (kX.Utils.EQ(this.sweep, 2 * Math.PI)) {
      return new kX.Circle(this.pc, this.r).svg(e43);
    }
    return `
<path d="M${this.start.x},${this.start.y}
                             A${this.r},${this.r} 0 ${t2},${n2} ${this.end.x},${this.end.y}"
                    ${FX({ fill: "none", ...e43 })} />`;
  }
};
kX.arc = (...e43) => new kX.Arc(...e43);
kX.Box = class e43 extends bV {
  constructor(e44 = undefined, t2 = undefined, n2 = undefined, o3 = undefined) {
    super(), this.xmin = e44, this.ymin = t2, this.xmax = n2, this.ymax = o3;
  }
  clone() {
    return new e43(this.xmin, this.ymin, this.xmax, this.ymax);
  }
  get low() {
    return new kX.Point(this.xmin, this.ymin);
  }
  get high() {
    return new kX.Point(this.xmax, this.ymax);
  }
  get max() {
    return this.clone();
  }
  get center() {
    return new kX.Point((this.xmin + this.xmax) / 2, (this.ymin + this.ymax) / 2);
  }
  get width() {
    return Math.abs(this.xmax - this.xmin);
  }
  get height() {
    return Math.abs(this.ymax - this.ymin);
  }
  get box() {
    return this.clone();
  }
  not_intersect(e44) {
    return this.xmax < e44.xmin || this.xmin > e44.xmax || this.ymax < e44.ymin || this.ymin > e44.ymax;
  }
  intersect(e44) {
    return !this.not_intersect(e44);
  }
  merge(t2) {
    return new e43(this.xmin === undefined ? t2.xmin : Math.min(this.xmin, t2.xmin), this.ymin === undefined ? t2.ymin : Math.min(this.ymin, t2.ymin), this.xmax === undefined ? t2.xmax : Math.max(this.xmax, t2.xmax), this.ymax === undefined ? t2.ymax : Math.max(this.ymax, t2.ymax));
  }
  less_than(e44) {
    return !!this.low.lessThan(e44.low) || !(!this.low.equalTo(e44.low) || !this.high.lessThan(e44.high));
  }
  equal_to(e44) {
    return this.low.equalTo(e44.low) && this.high.equalTo(e44.high);
  }
  output() {
    return this.clone();
  }
  comparable_less_than(e44, t2) {
    return e44.lessThan(t2);
  }
  set(e44, t2, n2, o3) {
    this.xmin = e44, this.ymin = t2, this.xmax = n2, this.ymax = o3;
  }
  extend(t2) {
    return t2 <= 0 ? this.clone() : new e43(this.xmin - t2, this.ymin - t2, this.xmax + t2, this.ymax + t2);
  }
  toPoints() {
    return [new kX.Point(this.xmin, this.ymin), new kX.Point(this.xmax, this.ymin), new kX.Point(this.xmax, this.ymax), new kX.Point(this.xmin, this.ymax)];
  }
  toSegments() {
    let e44 = this.toPoints();
    return [new kX.Segment(e44[0], e44[1]), new kX.Segment(e44[1], e44[2]), new kX.Segment(e44[2], e44[3]), new kX.Segment(e44[3], e44[0])];
  }
  rotate(e44, t2 = new kX.Point) {
    throw DX.OPERATION_IS_NOT_SUPPORTED;
  }
  transform(t2 = new kX.Matrix) {
    return this.toPoints().map((e44) => e44.transform(t2)).reduce((e44, t3) => e44.merge(t3.box), new e43);
  }
  contains(e44) {
    return e44 instanceof kX.Point ? e44.x >= this.xmin && e44.x <= this.xmax && e44.y >= this.ymin && e44.y <= this.ymax : e44 instanceof kX.Segment ? e44.vertices.every((e45) => this.contains(e45)) : e44 instanceof kX.Box ? e44.toSegments().every((e45) => this.contains(e45)) : e44 instanceof kX.Circle ? this.contains(e44.box) : e44 instanceof kX.Arc ? e44.vertices.every((e45) => this.contains(e45)) && this.toSegments().every((t2) => UX(t2, e44).length === 0) : !(e44 instanceof kX.Line || e44 instanceof kX.Ray) && (e44 instanceof kX.Multiline ? e44.toShapes().every((e45) => this.contains(e45)) : e44 instanceof kX.Polygon ? this.contains(e44.box) : undefined);
  }
  distanceTo(e44) {
    const t2 = this.toSegments().map((t3) => t3.distanceTo(e44));
    let n2 = [Number.MAX_SAFE_INTEGER, null];
    return t2.forEach((e45) => {
      e45[0] < n2[0] && (n2 = e45);
    }), n2;
  }
  get name() {
    return "box";
  }
  svg(e44 = {}) {
    const t2 = this.xmax - this.xmin, n2 = this.ymax - this.ymin;
    return `
<rect x="${this.xmin}" y="${this.ymin}" width="${t2}" height="${n2}"
                ${FX({ fill: "none", ...e44 })} />`;
  }
};
kX.box = (...e44) => new kX.Box(...e44);
kX.Edge = class {
  constructor(e44) {
    this.shape = e44, this.next = undefined, this.prev = undefined, this.face = undefined, this.arc_length = 0, this.bvStart = undefined, this.bvEnd = undefined, this.bv = undefined, this.overlap = undefined;
  }
  get start() {
    return this.shape.start;
  }
  get end() {
    return this.shape.end;
  }
  get length() {
    return this.shape.length;
  }
  get box() {
    return this.shape.box;
  }
  get isSegment() {
    return this.shape instanceof kX.Segment;
  }
  get isArc() {
    return this.shape instanceof kX.Arc;
  }
  get isLine() {
    return this.shape instanceof kX.Line;
  }
  get isRay() {
    return this.shape instanceof kX.Ray;
  }
  middle() {
    return this.shape.middle();
  }
  pointAtLength(e44) {
    return this.shape.pointAtLength(e44);
  }
  contains(e44) {
    return this.shape.contains(e44);
  }
  setInclusion(e44) {
    if (this.bv !== undefined)
      return this.bv;
    if (this.shape instanceof kX.Line || this.shape instanceof kX.Ray)
      return this.bv = kX.OUTSIDE, this.bv;
    if (this.bvStart === undefined && (this.bvStart = iV(e44, this.start)), this.bvEnd === undefined && (this.bvEnd = iV(e44, this.end)), this.bvStart === kX.OUTSIDE || this.bvEnd == kX.OUTSIDE)
      this.bv = kX.OUTSIDE;
    else if (this.bvStart === kX.INSIDE || this.bvEnd == kX.INSIDE)
      this.bv = kX.INSIDE;
    else {
      let t2 = iV(e44, this.middle());
      this.bv = t2;
    }
    return this.bv;
  }
  setOverlap(e44) {
    let t2, n2 = this.shape, o3 = e44.shape;
    n2 instanceof kX.Segment && o3 instanceof kX.Segment ? n2.start.equalTo(o3.start) && n2.end.equalTo(o3.end) ? t2 = kX.OVERLAP_SAME : n2.start.equalTo(o3.end) && n2.end.equalTo(o3.start) && (t2 = kX.OVERLAP_OPPOSITE) : (n2 instanceof kX.Arc && o3 instanceof kX.Arc || n2 instanceof kX.Segment && o3 instanceof kX.Arc || n2 instanceof kX.Arc && o3 instanceof kX.Segment) && (n2.start.equalTo(o3.start) && n2.end.equalTo(o3.end) && n2.middle().equalTo(o3.middle()) ? t2 = kX.OVERLAP_SAME : n2.start.equalTo(o3.end) && n2.end.equalTo(o3.start) && n2.middle().equalTo(o3.middle()) && (t2 = kX.OVERLAP_OPPOSITE)), this.overlap === undefined && (this.overlap = t2), e44.overlap === undefined && (e44.overlap = t2);
  }
  svg() {
    if (this.shape instanceof kX.Segment)
      return ` L${this.shape.end.x},${this.shape.end.y}`;
    if (this.shape instanceof kX.Arc) {
      let e44, t2 = this.shape, n2 = t2.counterClockwise ? "1" : "0";
      if (kX.Utils.EQ(t2.sweep, 2 * Math.PI)) {
        let o3 = t2.counterClockwise ? 1 : -1, i3 = new kX.Arc(t2.pc, t2.r, t2.startAngle, t2.startAngle + o3 * Math.PI, t2.counterClockwise), r3 = new kX.Arc(t2.pc, t2.r, t2.startAngle + o3 * Math.PI, t2.endAngle, t2.counterClockwise);
        return e44 = "0", ` A${i3.r},${i3.r} 0 ${e44},${n2} ${i3.end.x},${i3.end.y}
                    A${r3.r},${r3.r} 0 ${e44},${n2} ${r3.end.x},${r3.end.y}`;
      }
      return e44 = t2.sweep <= Math.PI ? "0" : "1", ` A${t2.r},${t2.r} 0 ${e44},${n2} ${t2.end.x},${t2.end.y}`;
    }
  }
  toJSON() {
    return this.shape.toJSON();
  }
};
var IV = class extends LX {
  constructor(e44, t2) {
    super(e44, t2), this.setCircularLinks();
  }
  setCircularLinks() {
    this.isEmpty() || (this.last.next = this.first, this.first.prev = this.last);
  }
  [Symbol.iterator]() {
    let e44;
    return { next: () => {
      let t2 = e44 || this.first, n2 = !this.first || !!e44 && e44 === this.first;
      return e44 = t2 ? t2.next : undefined, { value: t2, done: n2 };
    } };
  }
  append(e44) {
    return super.append(e44), this.setCircularLinks(), this;
  }
  insert(e44, t2) {
    return super.insert(e44, t2), this.setCircularLinks(), this;
  }
  remove(e44) {
    return super.remove(e44), this;
  }
};
kX.Face = class e44 extends IV {
  constructor(t2, ...n2) {
    if (super(), this._box = undefined, this._orientation = undefined, n2.length !== 0) {
      if (n2.length === 1) {
        if (n2[0] instanceof Array) {
          let o3 = n2[0];
          if (o3.length === 0)
            return;
          if (o3.every((e45) => e45 instanceof kX.Point)) {
            let n3 = e44.points2segments(o3);
            this.shapes2face(t2.edges, n3);
          } else if (o3.every((e45) => e45 instanceof Array && e45.length === 2)) {
            let n3 = o3.map((e45) => new kX.Point(e45[0], e45[1])), i3 = e44.points2segments(n3);
            this.shapes2face(t2.edges, i3);
          } else if (o3.every((e45) => e45 instanceof kX.Segment || e45 instanceof kX.Arc))
            this.shapes2face(t2.edges, o3);
          else if (o3.every((e45) => e45.name === "segment" || e45.name === "arc")) {
            let e45 = [];
            for (let t3 of o3) {
              let n3;
              n3 = t3.name === "segment" ? new kX.Segment(t3) : new kX.Arc(t3), e45.push(n3);
            }
            this.shapes2face(t2.edges, e45);
          }
        } else if (n2[0] instanceof e44) {
          let e45 = n2[0];
          this.first = e45.first, this.last = e45.last;
          for (let n3 of e45)
            t2.edges.add(n3);
        } else if (n2[0] instanceof kX.Circle)
          this.shapes2face(t2.edges, [n2[0].toArc(SX)]);
        else if (n2[0] instanceof kX.Box) {
          let e45 = n2[0];
          this.shapes2face(t2.edges, [new kX.Segment(new kX.Point(e45.xmin, e45.ymin), new kX.Point(e45.xmax, e45.ymin)), new kX.Segment(new kX.Point(e45.xmax, e45.ymin), new kX.Point(e45.xmax, e45.ymax)), new kX.Segment(new kX.Point(e45.xmax, e45.ymax), new kX.Point(e45.xmin, e45.ymax)), new kX.Segment(new kX.Point(e45.xmin, e45.ymax), new kX.Point(e45.xmin, e45.ymin))]);
        }
      }
      n2.length === 2 && n2[0] instanceof kX.Edge && n2[1] instanceof kX.Edge && (this.first = n2[0], this.last = n2[1], this.last.next = this.first, this.first.prev = this.last, this.setArcLength());
    }
  }
  get edges() {
    return this.toArray();
  }
  get vertices() {
    return this.edges.map((e45) => e45.shape.start.clone());
  }
  get shapes() {
    return this.edges.map((e45) => e45.shape.clone());
  }
  get box() {
    if (this._box === undefined) {
      let e45 = new kX.Box;
      for (let t2 of this)
        e45 = e45.merge(t2.box);
      this._box = e45;
    }
    return this._box;
  }
  get perimeter() {
    return this.last.arc_length + this.last.length;
  }
  pointAtLength(e45) {
    if (e45 > this.perimeter || e45 < 0)
      return null;
    let t2 = null;
    for (let n2 of this)
      if (e45 >= n2.arc_length && (n2 === this.last || e45 < n2.next.arc_length)) {
        t2 = n2.pointAtLength(e45 - n2.arc_length);
        break;
      }
    return t2;
  }
  static points2segments(e45) {
    let t2 = [];
    for (let n2 = 0;n2 < e45.length; n2++)
      e45[n2].equalTo(e45[(n2 + 1) % e45.length]) || t2.push(new kX.Segment(e45[n2], e45[(n2 + 1) % e45.length]));
    return t2;
  }
  shapes2face(e45, t2) {
    for (let n2 of t2) {
      let t3 = new kX.Edge(n2);
      this.append(t3), e45.add(t3);
    }
  }
  append(e45) {
    return super.append(e45), this.setOneEdgeArcLength(e45), e45.face = this, this;
  }
  insert(e45, t2) {
    return super.insert(e45, t2), this.setOneEdgeArcLength(e45), e45.face = this, this;
  }
  remove(e45) {
    return super.remove(e45), this.setArcLength(), this;
  }
  merge_with_next_edge(e45) {
    return e45.shape.end.x = e45.next.shape.end.x, e45.shape.end.y = e45.next.shape.end.y, this.remove(e45.next), this;
  }
  reverse() {
    let e45 = [], t2 = this.last;
    do {
      t2.shape = t2.shape.reverse(), e45.push(t2), t2 = t2.prev;
    } while (t2 !== this.last);
    this.first = undefined, this.last = undefined;
    for (let t3 of e45)
      this.first === undefined ? (t3.prev = t3, t3.next = t3, this.first = t3, this.last = t3) : (t3.prev = this.last, this.last.next = t3, this.last = t3, this.last.next = this.first, this.first.prev = this.last), this.setOneEdgeArcLength(t3);
    this._orientation !== undefined && (this._orientation = undefined, this._orientation = this.orientation());
  }
  setArcLength() {
    for (let e45 of this)
      this.setOneEdgeArcLength(e45), e45.face = this;
  }
  setOneEdgeArcLength(e45) {
    e45 === this.first ? e45.arc_length = 0 : e45.arc_length = e45.prev.arc_length + e45.prev.length;
  }
  area() {
    return Math.abs(this.signedArea());
  }
  signedArea() {
    let e45 = 0, t2 = this.box.ymin;
    for (let n2 of this)
      e45 += n2.shape.definiteIntegral(t2);
    return e45;
  }
  orientation() {
    if (this._orientation === undefined) {
      let e45 = this.signedArea();
      kX.Utils.EQ_0(e45) ? this._orientation = CX.NOT_ORIENTABLE : kX.Utils.LT(e45, 0) ? this._orientation = CX.CCW : this._orientation = CX.CW;
    }
    return this._orientation;
  }
  isSimple(t2) {
    return e44.getSelfIntersections(this, t2, true).length === 0;
  }
  static getSelfIntersections(e45, t2, n2 = false) {
    let o3 = [];
    for (let i3 of e45) {
      let r3 = t2.search(i3.box);
      for (let t3 of r3) {
        if (i3 === t3)
          continue;
        if (t3.face !== e45)
          continue;
        if (i3.shape instanceof kX.Segment && t3.shape instanceof kX.Segment && (i3.next === t3 || i3.prev === t3))
          continue;
        let r4 = i3.shape.intersect(t3.shape);
        for (let e46 of r4)
          if ((!e46.equalTo(i3.start) || !e46.equalTo(t3.end) || t3 !== i3.prev) && (!e46.equalTo(i3.end) || !e46.equalTo(t3.start) || t3 !== i3.next) && (o3.push(e46), n2))
            break;
        if (o3.length > 0 && n2)
          break;
      }
      if (o3.length > 0 && n2)
        break;
    }
    return o3;
  }
  findEdgeByPoint(e45) {
    let t2;
    for (let n2 of this)
      if (!e45.equalTo(n2.shape.start) && (e45.equalTo(n2.shape.end) || n2.shape.contains(e45))) {
        t2 = n2;
        break;
      }
    return t2;
  }
  toPolygon() {
    return new kX.Polygon(this.shapes);
  }
  toJSON() {
    return this.edges.map((e45) => e45.toJSON());
  }
  svg() {
    let e45 = `M${this.first.start.x},${this.first.start.y}`;
    for (let t2 of this)
      e45 += t2.svg();
    return e45 += " z", e45;
  }
};
kX.Ray = class e45 extends bV {
  constructor(...e46) {
    if (super(), this.pt = new kX.Point, this.norm = new kX.Vector(0, 1), e46.length !== 0 && (e46.length >= 1 && e46[0] instanceof kX.Point && (this.pt = e46[0].clone()), e46.length !== 1)) {
      if (!(e46.length === 2 && e46[1] instanceof kX.Vector))
        throw DX.ILLEGAL_PARAMETERS;
      this.norm = e46[1].clone();
    }
  }
  clone() {
    return new e45(this.pt, this.norm);
  }
  get slope() {
    return new kX.Vector(this.norm.y, -this.norm.x).slope;
  }
  get box() {
    let e46 = this.slope;
    return new kX.Box(e46 > Math.PI / 2 && e46 < 3 * Math.PI / 2 ? Number.NEGATIVE_INFINITY : this.pt.x, e46 >= 0 && e46 <= Math.PI ? this.pt.y : Number.NEGATIVE_INFINITY, e46 >= Math.PI / 2 && e46 <= 3 * Math.PI / 2 ? this.pt.x : Number.POSITIVE_INFINITY, e46 >= Math.PI && e46 <= 2 * Math.PI || e46 === 0 ? this.pt.y : Number.POSITIVE_INFINITY);
  }
  get start() {
    return this.pt;
  }
  get end() {}
  get length() {
    return Number.POSITIVE_INFINITY;
  }
  contains(e46) {
    if (this.pt.equalTo(e46))
      return true;
    let t2 = new kX.Vector(this.pt, e46);
    return kX.Utils.EQ_0(this.norm.dot(t2)) && kX.Utils.GE(t2.cross(this.norm), 0);
  }
  coord(e46) {
    return xV(e46.x, e46.y).cross(this.norm);
  }
  split(e46) {
    return this.contains(e46) ? this.pt.equalTo(e46) ? [this] : [new kX.Segment(this.pt, e46), new kX.Ray(e46, this.norm)] : [];
  }
  intersect(e46) {
    return e46 instanceof kX.Point ? this.contains(e46) ? [e46] : [] : e46 instanceof kX.Segment ? hH(this, e46) : e46 instanceof kX.Arc ? dH(this, e46) : e46 instanceof kX.Line ? pH(this, e46) : e46 instanceof kX.Ray ? (n2 = e46, jX(lH(t2 = this), lH(n2)).filter((e47) => t2.contains(e47)).filter((e47) => n2.contains(e47))) : e46 instanceof kX.Circle ? uH(this, e46) : e46 instanceof kX.Box ? function(e47, t3) {
      return YX(lH(e47), t3).filter((t4) => e47.contains(t4));
    }(this, e46) : e46 instanceof kX.Polygon ? mH(this, e46) : e46 instanceof kX.Multiline ? fH(this, e46) : undefined;
    var t2, n2;
  }
  rotate(e46, t2 = new kX.Point) {
    return new kX.Ray(this.pt.rotate(e46, t2), this.norm.rotate(e46));
  }
  transform(e46) {
    return new kX.Ray(this.pt.transform(e46), this.norm.clone());
  }
  get name() {
    return "ray";
  }
  svg(e46, t2 = {}) {
    let n2 = YX(new kX.Line(this.pt, this.norm), e46);
    return n2 = n2.filter((e47) => this.contains(e47)), n2.length === 0 || n2.length === 2 ? "" : new kX.Segment(this.pt, n2[0]).svg(t2);
  }
};
kX.ray = (...e46) => new kX.Ray(...e46);
kX.Polygon = class e46 {
  constructor() {
    this.faces = new kX.PlanarSet, this.edges = new kX.PlanarSet;
    let e47 = [...arguments];
    if (e47.length === 1 && (e47[0] instanceof Array && e47[0].length > 0 || e47[0] instanceof kX.Circle || e47[0] instanceof kX.Box)) {
      let t2 = e47[0];
      if (e47[0] instanceof Array && e47[0].every((e48) => e48 instanceof Array))
        if (t2.every((e48) => e48 instanceof Array && e48.length === 2 && typeof e48[0] == "number" && typeof e48[1] == "number"))
          this.faces.add(new kX.Face(this, t2));
        else
          for (let e48 of t2)
            if (e48 instanceof Array && e48[0] instanceof Array && e48[0].every((e49) => e49 instanceof Array && e49.length === 2 && typeof e49[0] == "number" && typeof e49[1] == "number"))
              for (let t3 of e48)
                this.faces.add(new kX.Face(this, t3));
            else
              this.faces.add(new kX.Face(this, e48));
      else
        this.faces.add(new kX.Face(this, t2));
    }
  }
  get box() {
    return [...this.faces].reduce((e47, t2) => e47.merge(t2.box), new kX.Box);
  }
  get vertices() {
    return [...this.faces].flatMap((e47) => e47.vertices);
  }
  clone() {
    let t2 = new e46;
    for (let e47 of this.faces)
      t2.addFace(e47.shapes);
    return t2;
  }
  createFromArray(t2) {
    const n2 = new e46;
    return t2.forEach((e47) => [...e47.faces].forEach((e48) => n2.addFace(e48.shapes))), n2;
  }
  isEmpty() {
    return this.edges.size === 0 || this.faces.size === 0;
  }
  isValid() {
    let e47 = true;
    for (let t2 of this.faces)
      if (!t2.isSimple(this.edges)) {
        e47 = false;
        break;
      }
    return e47;
  }
  area() {
    let e47 = [...this.faces].reduce((e48, t2) => e48 + t2.signedArea(), 0);
    return Math.abs(e47);
  }
  addFace(...e47) {
    let t2 = new kX.Face(this, ...e47);
    return this.faces.add(t2), t2;
  }
  deleteFace(e47) {
    for (let t2 of e47)
      this.edges.delete(t2);
    return this.faces.delete(e47);
  }
  recreateFaces() {
    this.faces.clear();
    for (let e48 of this.edges)
      e48.face = null;
    let e47, t2 = true;
    for (;t2; ) {
      t2 = false;
      for (let n2 of this.edges)
        if (n2.face === null) {
          e47 = n2, t2 = true;
          break;
        }
      if (t2) {
        let t3 = e47;
        do {
          t3 = t3.next;
        } while (t3.next !== e47);
        this.addFace(e47, t3);
      }
    }
  }
  removeChain(e47, t2, n2) {
    if (n2.next !== t2) {
      for (let o3 = t2;o3 !== n2.next; o3 = o3.next)
        if (e47.remove(o3), this.edges.delete(o3), e47.isEmpty()) {
          this.deleteFace(e47);
          break;
        }
    } else
      this.deleteFace(e47);
  }
  addVertex(e47, t2) {
    let n2 = t2.shape.split(e47);
    if (n2[0] === null)
      return t2.prev;
    if (n2[1] === null)
      return t2;
    let o3 = new kX.Edge(n2[0]), i3 = t2.prev;
    return t2.face.insert(o3, i3), this.edges.delete(t2), this.edges.add(o3), t2.shape = n2[1], this.edges.add(t2), o3;
  }
  removeEndVertex(e47) {
    const t2 = e47.next;
    t2 !== e47 && (e47.face.merge_with_next_edge(e47), this.edges.delete(t2));
  }
  cut(e47) {
    const t2 = this.splitToIslands().flatMap((t3) => t3._cutSingleIsland(e47)).filter((e48) => e48.isValid() && e48.isEmpty() === false);
    return this.createFromArray(t2);
  }
  _cutSingleIsland(e47) {
    let t2 = this.clone();
    const n2 = e47.clone();
    let o3, i3, r3 = { int_points1: [], int_points2: [], int_points1_sorted: [], int_points2_sorted: [] };
    for (let e48 of n2.edges)
      for (let n3 of t2.edges) {
        let t3 = sH(e48, n3);
        for (let o4 of t3)
          yH(e48, o4, r3.int_points1), yH(n3, o4, r3.int_points2);
      }
    if (r3.int_points1.length === 0)
      return t2;
    r3.int_points1_sorted = xH(r3.int_points1), r3.int_points2_sorted = xH(r3.int_points2), MH(n2, r3.int_points1_sorted), MH(t2, r3.int_points2_sorted), IH(r3), r3.int_points1_sorted = xH(r3.int_points1), r3.int_points2_sorted = xH(r3.int_points2), SH(r3.int_points1), CH(r3.int_points1, t2);
    for (let e48 of r3.int_points1_sorted)
      e48.edge_before && e48.edge_after && e48.edge_before.bv === e48.edge_after.bv && (r3.int_points2[e48.id] = -1, e48.id = -1);
    if (r3.int_points1 = r3.int_points1.filter((e48) => e48.id >= 0), r3.int_points2 = r3.int_points2.filter((e48) => e48.id >= 0), r3.int_points1.forEach((e48, t3) => {
      e48.id = t3;
    }), r3.int_points2.forEach((e48, t3) => {
      e48.id = t3;
    }), r3.int_points1.length === 0)
      return t2;
    r3.int_points1_sorted = xH(r3.int_points1), r3.int_points2_sorted = xH(r3.int_points2);
    for (let e48 = 1;e48 < r3.int_points1_sorted.length; e48++)
      if (i3 = r3.int_points1_sorted[e48], o3 = r3.int_points1_sorted[e48 - 1], i3.edge_before && i3.edge_before.bv === 1) {
        let e49 = o3.edge_after, s2 = i3.edge_before, a3 = n2.getChain(e49, s2);
        wH(r3.int_points2[o3.id], r3.int_points2[i3.id], a3), a3.forEach((e50) => t2.edges.add(e50)), a3 = a3.reverse().map((e50) => new kX.Edge(e50.shape.reverse()));
        for (let e50 = 0;e50 < a3.length - 1; e50++)
          a3[e50].next = a3[e50 + 1], a3[e50 + 1].prev = a3[e50];
        wH(r3.int_points2[i3.id], r3.int_points2[o3.id], a3), a3.forEach((e50) => t2.edges.add(e50));
      }
    return t2.recreateFaces(), t2;
  }
  cutWithLine(e47) {
    let t2 = new _H([e47]);
    return this.cut(t2);
  }
  findEdgeByPoint(e47) {
    let t2;
    for (let n2 of this.faces)
      if (t2 = n2.findEdgeByPoint(e47), t2 !== undefined)
        break;
    return t2;
  }
  splitToIslands() {
    if (this.isEmpty())
      return [];
    let e47 = this.toArray();
    e47.sort((e48, t3) => t3.area() - e48.area());
    let t2 = [...e47[0].faces][0].orientation(), n2 = e47.filter((e48) => [...e48.faces][0].orientation() === t2);
    for (let o3 of e47) {
      let e48 = [...o3.faces][0];
      if (e48.orientation() !== t2) {
        for (let t3 of n2)
          if (e48.shapes.every((e49) => t3.contains(e49))) {
            t3.addFace(e48.shapes);
            break;
          }
      }
    }
    return n2;
  }
  rearrange() {
    if (this.faces.size <= 1)
      return this.clone();
    const t2 = this.splitToIslands(), n2 = new e46;
    return t2.forEach((e47) => {
      e47.faces.forEach((e48) => n2.addFace(e48.shapes));
    }), n2;
  }
  orientation() {
    return this.isEmpty() ? CX.NOT_ORIENTABLE : [...this.faces][0].orientation();
  }
  isOuter(e47) {
    return e47.orientation() === this.orientation();
  }
  isMultiPolygon() {
    let e47 = 0;
    return this.faces.forEach((t2) => {
      this.isOuter(t2) && e47++;
    }), e47 > 1;
  }
  reverse() {
    for (let e47 of this.faces)
      e47.reverse();
    return this;
  }
  contains(e47) {
    if (e47 instanceof kX.Point) {
      let t2 = iV(this, e47);
      return t2 === 1 || t2 === 2;
    }
    return cV(this, e47);
  }
  distanceTo(e47) {
    if (e47 instanceof kX.Point) {
      let [t2, n2] = kX.Distance.point2polygon(e47, this);
      return n2 = n2.reverse(), [t2, n2];
    }
    if (e47 instanceof kX.Circle || e47 instanceof kX.Line || e47 instanceof kX.Segment || e47 instanceof kX.Arc) {
      let [t2, n2] = kX.Distance.shape2polygon(e47, this);
      return n2 = n2.reverse(), [t2, n2];
    }
    if (e47 instanceof kX.Polygon) {
      let t2, n2, o3 = [Number.POSITIVE_INFINITY, new kX.Segment];
      for (let i3 of this.edges) {
        let r3 = o3[0];
        [t2, n2] = kX.Distance.shape2planarSet(i3.shape, e47.edges, r3), kX.Utils.LT(t2, r3) && (o3 = [t2, n2]);
      }
      return o3;
    }
  }
  intersect(e47) {
    return e47 instanceof kX.Point ? this.contains(e47) ? [e47] : [] : e47 instanceof kX.Line ? iH(e47, this) : e47 instanceof kX.Ray ? mH(e47, this) : e47 instanceof kX.Circle ? rH(e47, this) : e47 instanceof kX.Segment ? nH(e47, this) : e47 instanceof kX.Arc ? oH(e47, this) : e47 instanceof kX.Polygon ? function(e48, t2) {
      let n2 = [];
      if (e48.isEmpty() || t2.isEmpty())
        return n2;
      if (e48.box.not_intersect(t2.box))
        return n2;
      for (let o3 of e48.edges)
        n2 = [...n2, ...aH(o3, t2)];
      return n2;
    }(e47, this) : e47 instanceof kX.Multiline ? function(e48, t2) {
      let n2 = [];
      if (t2.isEmpty() || e48.size === 0)
        return n2;
      for (let o3 of e48)
        n2 = [...n2, ...aH(o3, t2)];
      return n2;
    }(e47, this) : undefined;
  }
  translate(t2) {
    let n2 = new e46;
    for (let e47 of this.faces)
      n2.addFace(e47.shapes.map((e48) => e48.translate(t2)));
    return n2;
  }
  rotate(t2 = 0, n2 = new kX.Point) {
    let o3 = new e46;
    for (let e47 of this.faces)
      o3.addFace(e47.shapes.map((e48) => e48.rotate(t2, n2)));
    return o3;
  }
  scale(t2, n2) {
    let o3 = new e46;
    for (let e47 of this.faces)
      o3.addFace(e47.shapes.map((e48) => e48.scale(t2, n2)));
    return o3;
  }
  transform(t2 = new kX.Matrix) {
    let n2 = new e46;
    for (let e47 of this.faces)
      n2.addFace(e47.shapes.map((e48) => e48.transform(t2)));
    return n2;
  }
  toJSON() {
    return [...this.faces].map((e47) => e47.toJSON());
  }
  toArray() {
    return [...this.faces].map((e47) => e47.toPolygon());
  }
  dpath() {
    return [...this.faces].reduce((e47, t2) => e47 + t2.svg(), "");
  }
  svg(e47 = {}) {
    let t2 = `
<path ${FX({ fillRule: "evenodd", fill: "lightcyan", ...e47 })} d="`;
    for (let e48 of this.faces)
      t2 += `
${e48.svg()}`;
    return t2 += `" >
</path>`, t2;
  }
};
kX.polygon = (...e47) => new kX.Polygon(...e47);
var { Circle: SV, Line: CV, Point: PV, Vector: MV, Utils: wV } = kX;
kX.Inversion = class e47 {
  constructor(e48) {
    this.circle = e48;
  }
  get inversion_circle() {
    return this.circle;
  }
  static inversePoint(e48, t2) {
    const n2 = new MV(e48.pc, t2), o3 = e48.r * e48.r, i3 = n2.dot(n2);
    return wV.EQ_0(i3) ? new PV(Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY) : e48.pc.translate(n2.multiply(o3 / i3));
  }
  static inverseCircle(e48, t2) {
    const n2 = e48.pc.distanceTo(t2.pc)[0];
    if (wV.EQ(n2, t2.r)) {
      let n3 = e48.r * e48.r / (2 * t2.r), o3 = new MV(e48.pc, t2.pc);
      o3 = o3.normalize();
      let i3 = e48.pc.translate(o3.multiply(n3));
      return new CV(i3, o3);
    }
    {
      let n3 = new MV(e48.pc, t2.pc), o3 = e48.r * e48.r / (n3.dot(n3) - t2.r * t2.r), i3 = e48.pc.translate(n3.multiply(o3)), r3 = Math.abs(o3) * t2.r;
      return new SV(i3, r3);
    }
  }
  static inverseLine(e48, t2) {
    const [n2, o3] = e48.pc.distanceTo(t2);
    if (wV.EQ_0(n2))
      return t2.clone();
    {
      let t3 = e48.r * e48.r / (2 * n2), i3 = new MV(e48.pc, o3.end);
      return i3 = i3.multiply(t3 / n2), new SV(e48.pc.translate(i3), t3);
    }
  }
  inverse(t2) {
    return t2 instanceof PV ? e47.inversePoint(this.circle, t2) : t2 instanceof SV ? e47.inverseCircle(this.circle, t2) : t2 instanceof CV ? e47.inverseLine(this.circle, t2) : undefined;
  }
};
kX.inversion = (e48) => new kX.Inversion(e48);
kX.Distance = class e48 {
  static point2point(e49, t2) {
    return e49.distanceTo(t2);
  }
  static point2line(e49, t2) {
    let n2 = e49.projectionOn(t2);
    return [new kX.Vector(e49, n2).length, new kX.Segment(e49, n2)];
  }
  static point2circle(e49, t2) {
    let [n2, o3] = e49.distanceTo(t2.center);
    if (kX.Utils.EQ_0(n2))
      return [t2.r, new kX.Segment(e49, t2.toArc().start)];
    {
      let o4 = Math.abs(n2 - t2.r), i3 = new kX.Vector(t2.pc, e49).normalize().multiply(t2.r), r3 = t2.pc.translate(i3);
      return [o4, new kX.Segment(e49, r3)];
    }
  }
  static point2segment(t2, n2) {
    if (n2.start.equalTo(n2.end))
      return e48.point2point(t2, n2.start);
    let o3, i3, r3 = new kX.Vector(n2.start, n2.end), s2 = new kX.Vector(n2.start, t2), a3 = new kX.Vector(n2.end, t2), c3 = r3.dot(s2), l3 = -r3.dot(a3);
    if (kX.Utils.GE(c3, 0) && kX.Utils.GE(l3, 0)) {
      let e49 = n2.tangentInStart();
      return o3 = Math.abs(e49.cross(s2)), i3 = n2.start.translate(e49.multiply(e49.dot(s2))), [o3, new kX.Segment(t2, i3)];
    }
    return c3 < 0 ? t2.distanceTo(n2.start) : t2.distanceTo(n2.end);
  }
  static point2arc(t2, n2) {
    let o3, i3, r3 = new kX.Circle(n2.pc, n2.r), s2 = [];
    return [o3, i3] = e48.point2circle(t2, r3), i3.end.on(n2) && s2.push(e48.point2circle(t2, r3)), s2.push(e48.point2point(t2, n2.start)), s2.push(e48.point2point(t2, n2.end)), e48.sort(s2), s2[0];
  }
  static point2edge(t2, n2) {
    return n2.shape instanceof kX.Segment ? e48.point2segment(t2, n2.shape) : e48.point2arc(t2, n2.shape);
  }
  static segment2line(t2, n2) {
    let o3 = t2.intersect(n2);
    if (o3.length > 0)
      return [0, new kX.Segment(o3[0], o3[0])];
    let i3 = [];
    return i3.push(e48.point2line(t2.start, n2)), i3.push(e48.point2line(t2.end, n2)), e48.sort(i3), i3[0];
  }
  static segment2segment(t2, n2) {
    let o3 = VX(t2, n2);
    if (o3.length > 0)
      return [0, new kX.Segment(o3[0], o3[0])];
    let i3, r3, s2 = [];
    return [i3, r3] = e48.point2segment(n2.start, t2), s2.push([i3, r3.reverse()]), [i3, r3] = e48.point2segment(n2.end, t2), s2.push([i3, r3.reverse()]), s2.push(e48.point2segment(t2.start, n2)), s2.push(e48.point2segment(t2.end, n2)), e48.sort(s2), s2[0];
  }
  static segment2circle(t2, n2) {
    let o3 = t2.intersect(n2);
    if (o3.length > 0)
      return [0, new kX.Segment(o3[0], o3[0])];
    let i3 = new kX.Line(t2.ps, t2.pe), [r3, s2] = e48.point2line(n2.center, i3);
    if (kX.Utils.GE(r3, n2.r) && s2.end.on(t2))
      return e48.point2circle(s2.end, n2);
    {
      let [o4, i4] = e48.point2circle(t2.start, n2), [r4, s3] = e48.point2circle(t2.end, n2);
      return kX.Utils.LT(o4, r4) ? [o4, i4] : [r4, s3];
    }
  }
  static segment2arc(t2, n2) {
    let o3 = t2.intersect(n2);
    if (o3.length > 0)
      return [0, new kX.Segment(o3[0], o3[0])];
    let i3 = new kX.Line(t2.ps, t2.pe), r3 = new kX.Circle(n2.pc, n2.r), [s2, a3] = e48.point2line(r3.center, i3);
    if (kX.Utils.GE(s2, r3.r) && a3.end.on(t2)) {
      let [t3, o4] = e48.point2circle(a3.end, r3);
      if (o4.end.on(n2))
        return [t3, o4];
    }
    let c3, l3, h2 = [];
    return h2.push(e48.point2arc(t2.start, n2)), h2.push(e48.point2arc(t2.end, n2)), [c3, l3] = e48.point2segment(n2.start, t2), h2.push([c3, l3.reverse()]), [c3, l3] = e48.point2segment(n2.end, t2), h2.push([c3, l3.reverse()]), e48.sort(h2), h2[0];
  }
  static circle2circle(t2, n2) {
    let o3 = t2.intersect(n2);
    if (o3.length > 0)
      return [0, new kX.Segment(o3[0], o3[0])];
    if (t2.center.equalTo(n2.center)) {
      let o4 = t2.toArc(), i3 = n2.toArc();
      return e48.point2point(o4.start, i3.start);
    }
    {
      let o4 = new kX.Line(t2.center, n2.center), i3 = o4.intersect(t2), r3 = o4.intersect(n2), s2 = [];
      return s2.push(e48.point2point(i3[0], r3[0])), s2.push(e48.point2point(i3[0], r3[1])), s2.push(e48.point2point(i3[1], r3[0])), s2.push(e48.point2point(i3[1], r3[1])), e48.sort(s2), s2[0];
    }
  }
  static circle2line(t2, n2) {
    let o3 = t2.intersect(n2);
    if (o3.length > 0)
      return [0, new kX.Segment(o3[0], o3[0])];
    let [i3, r3] = e48.point2line(t2.center, n2), [s2, a3] = e48.point2circle(r3.end, t2);
    return a3 = a3.reverse(), [s2, a3];
  }
  static arc2line(t2, n2) {
    let o3 = n2.intersect(t2);
    if (o3.length > 0)
      return [0, new kX.Segment(o3[0], o3[0])];
    let i3 = new kX.Circle(t2.center, t2.r), [r3, s2] = e48.point2line(i3.center, n2);
    if (!kX.Utils.GE(r3, i3.r)) {
      let o4 = [];
      return o4.push(e48.point2line(t2.start, n2)), o4.push(e48.point2line(t2.end, n2)), e48.sort(o4), o4[0];
    }
    {
      let [n3, o4] = e48.point2circle(s2.end, i3);
      if (o4.end.on(t2))
        return [n3, o4];
    }
  }
  static arc2circle(t2, n2) {
    let o3 = t2.intersect(n2);
    if (o3.length > 0)
      return [0, new kX.Segment(o3[0], o3[0])];
    let i3 = new kX.Circle(t2.center, t2.r), [r3, s2] = e48.circle2circle(i3, n2);
    if (s2.start.on(t2))
      return [r3, s2];
    {
      let o4 = [];
      return o4.push(e48.point2circle(t2.start, n2)), o4.push(e48.point2circle(t2.end, n2)), e48.sort(o4), o4[0];
    }
  }
  static arc2arc(t2, n2) {
    let o3 = t2.intersect(n2);
    if (o3.length > 0)
      return [0, new kX.Segment(o3[0], o3[0])];
    let i3 = new kX.Circle(t2.center, t2.r), r3 = new kX.Circle(n2.center, n2.r), [s2, a3] = e48.circle2circle(i3, r3);
    if (a3.start.on(t2) && a3.end.on(n2))
      return [s2, a3];
    {
      let o4, i4, r4 = [];
      return [o4, i4] = e48.point2arc(t2.start, n2), i4.end.on(n2) && r4.push([o4, i4]), [o4, i4] = e48.point2arc(t2.end, n2), i4.end.on(n2) && r4.push([o4, i4]), [o4, i4] = e48.point2arc(n2.start, t2), i4.end.on(t2) && r4.push([o4, i4.reverse()]), [o4, i4] = e48.point2arc(n2.end, t2), i4.end.on(t2) && r4.push([o4, i4.reverse()]), [o4, i4] = e48.point2point(t2.start, n2.start), r4.push([o4, i4]), [o4, i4] = e48.point2point(t2.start, n2.end), r4.push([o4, i4]), [o4, i4] = e48.point2point(t2.end, n2.start), r4.push([o4, i4]), [o4, i4] = e48.point2point(t2.end, n2.end), r4.push([o4, i4]), e48.sort(r4), r4[0];
    }
  }
  static point2polygon(t2, n2) {
    let o3 = [Number.POSITIVE_INFINITY, new kX.Segment];
    for (let i3 of n2.edges) {
      let [n3, r3] = e48.point2edge(t2, i3);
      kX.Utils.LT(n3, o3[0]) && (o3 = [n3, r3]);
    }
    return o3;
  }
  static shape2polygon(e49, t2) {
    let n2 = [Number.POSITIVE_INFINITY, new kX.Segment];
    for (let o3 of t2.edges) {
      let [t3, i3] = e49.distanceTo(o3.shape);
      kX.Utils.LT(t3, n2[0]) && (n2 = [t3, i3]);
    }
    return n2;
  }
  static polygon2polygon(e49, t2) {
    let n2 = [Number.POSITIVE_INFINITY, new kX.Segment];
    for (let o3 of e49.edges)
      for (let e50 of t2.edges) {
        let [t3, i3] = o3.shape.distanceTo(e50.shape);
        kX.Utils.LT(t3, n2[0]) && (n2 = [t3, i3]);
      }
    return n2;
  }
  static box2box_minmax(e49, t2) {
    let n2 = Math.max(Math.max(e49.xmin - t2.xmax, 0), Math.max(t2.xmin - e49.xmax, 0)), o3 = Math.max(Math.max(e49.ymin - t2.ymax, 0), Math.max(t2.ymin - e49.ymax, 0)), i3 = n2 * n2 + o3 * o3, r3 = e49.merge(t2), s2 = r3.xmax - r3.xmin, a3 = r3.ymax - r3.ymin;
    return [i3, s2 * s2 + a3 * a3];
  }
  static minmax_tree_process_level(t2, n2, o3, i3) {
    let r3, s2;
    for (let a4 of n2) {
      [r3, s2] = e48.box2box_minmax(t2.box, a4.item.key);
      for (let e49 of a4.item.values)
        e49 instanceof kX.Edge ? i3.insert([r3, s2], e49.shape) : i3.insert([r3, s2], e49);
      kX.Utils.LT(s2, o3) && (o3 = s2);
    }
    if (n2.length === 0)
      return o3;
    let a3 = [...n2.map((e49) => e49.left.isNil() ? undefined : e49.left).filter((e49) => e49 !== undefined), ...n2.map((e49) => e49.right.isNil() ? undefined : e49.right).filter((e49) => e49 !== undefined)].filter((n3) => {
      let [i4, r4] = e48.box2box_minmax(t2.box, n3.max);
      return kX.Utils.LE(i4, o3);
    });
    return o3 = e48.minmax_tree_process_level(t2, a3, o3, i3);
  }
  static minmax_tree(t2, n2, o3) {
    let i3 = new _V, r3 = [n2.index.root], s2 = o3 < Number.POSITIVE_INFINITY ? o3 * o3 : Number.POSITIVE_INFINITY;
    return s2 = e48.minmax_tree_process_level(t2, r3, s2, i3), i3;
  }
  static minmax_tree_calc_distance(t2, n2, o3) {
    let i3, r3;
    if (n2 != null && !n2.isNil()) {
      if ([i3, r3] = e48.minmax_tree_calc_distance(t2, n2.left, o3), r3)
        return [i3, r3];
      if (kX.Utils.LT(i3[0], Math.sqrt(n2.item.key.low)))
        return [i3, true];
      let [s2, a3] = e48.distanceToArray(t2, n2.item.values);
      return kX.Utils.LT(s2, i3[0]) && (i3 = [s2, a3]), [i3, r3] = e48.minmax_tree_calc_distance(t2, n2.right, i3), [i3, r3];
    }
    return [o3, false];
  }
  static shape2planarSet(t2, n2, o3 = Number.POSITIVE_INFINITY) {
    let i3 = [o3, new kX.Segment], r3 = false;
    if (n2 instanceof kX.PlanarSet) {
      let s2 = e48.minmax_tree(t2, n2, o3);
      [i3, r3] = e48.minmax_tree_calc_distance(t2, s2.root, i3);
    }
    return i3;
  }
  static sort(e49) {
    e49.sort((e50, t2) => kX.Utils.LT(e50[0], t2[0]) ? -1 : kX.Utils.GT(e50[0], t2[0]) ? 1 : 0);
  }
  static distance(e49, t2) {
    return e49.distanceTo(t2);
  }
  static distanceToArray(e49, t2) {
    let n2 = [Number.POSITIVE_INFINITY, new kX.Segment];
    for (let o3 of t2) {
      let [t3, i3] = e49.distanceTo(o3);
      kX.Utils.LT(t3, n2[0]) && (n2 = [t3, i3]);
    }
    return n2;
  }
  static shape2multiline(t2, n2) {
    let o3 = [Number.POSITIVE_INFINITY, new kX.Segment];
    for (let i3 of n2) {
      let [n3, r3] = e48.distance(t2, i3.shape);
      kX.Utils.LT(n3, o3[0]) && (o3 = [n3, r3]);
    }
    return o3;
  }
  static multiline2multiline(t2, n2) {
    let o3 = [Number.POSITIVE_INFINITY, new kX.Segment];
    for (let i3 of t2)
      for (let t3 of n2) {
        let [n3, r3] = e48.distance(i3.shape, t3.shape);
        kX.Utils.LT(n3, o3[0]) && (o3 = [n3, r3]);
      }
    return o3;
  }
};
var { Multiline: NV, Point: RV, Segment: TV, Polygon: EV } = kX;
function AV(e49) {
  return new RV(e49.split(" ").map(Number));
}
function OV(e49) {
  return e49.split(", ").map(AV);
}
function kV(e49) {
  const t2 = OV(e49);
  let n2 = [];
  for (let e50 = 0;e50 < t2.length - 1; e50++)
    n2.push(new TV(t2[e50], t2[e50 + 1]));
  return new NV(n2);
}
function DV(e49) {
  const t2 = e49.replace(/\(\(/, "").replace(/\)\)$/, "").split("), ("), n2 = new EV;
  let o3;
  return t2.forEach((e50, t3) => {
    let i3 = e50.split(", ").map((e51) => new RV(e51.split(" ").map(Number)));
    const r3 = n2.addFace(i3);
    t3 === 0 ? o3 = r3.orientation() : r3.orientation() === o3 && r3.reverse();
  }), n2;
}
function LV(e49) {
  if (e49.startsWith("POLYGON")) {
    return DV(e49.replace(/^POLYGON /, ""));
  }
  return function(e50) {
    const t2 = e50.split(/\)\), \(\(/).map((e51) => "((" + e51 + "))").map(DV), n2 = new EV;
    return t2.reduce((e51, t3) => [...e51, ...t3?.faces], []).forEach((e51) => n2.addFace([...e51?.shapes])), n2;
  }(e49.replace(/^MULTIPOLYGON \(\(\((.*)\)\)\)$/, "$1"));
}
function zV(e49) {
  return e49.split(`
`)?.every((e50) => e50.includes("POINT"));
}
function BV(e49) {
  return e49.split(`
`)?.every((e50) => e50.includes("LINESTRING"));
}
kX.isWktString = function(e50) {
  return e50.startsWith("POINT") || zV(e50) || e50.startsWith("LINESTRING") || BV(e50) || e50.startsWith("MULTILINESTRING") || e50.startsWith("POLYGON") || e50.startsWith("MULTIPOINT") || e50.startsWith("MULTIPOLYGON") || e50.startsWith("GEOMETRYCOLLECTION");
}, kX.parseWKT = function e49(t2) {
  if (t2.startsWith("POINT")) {
    return AV(t2.replace(/^POINT \(/, "").replace(/\)$/, ""));
  }
  if (t2.startsWith("MULTIPOINT")) {
    return OV(t2.replace(/^MULTIPOINT \(/, "").replace(/\)$/, ""));
  }
  if (t2.startsWith("LINESTRING")) {
    return kV(t2.replace(/^LINESTRING \(/, "").replace(/\)$/, ""));
  }
  if (t2.startsWith("MULTILINESTRING")) {
    return function(e50) {
      return e50.replace(/\(\(/, "").replace(/\)\)$/, "").split("), (").map(kV);
    }(t2.replace(/^MULTILINESTRING /, ""));
  }
  if (t2.startsWith("POLYGON") || t2.startsWith("MULTIPOLYGON"))
    return LV(t2);
  if (t2.startsWith("GEOMETRYCOLLECTION")) {
    const n2 = /(?<type>POINT|LINESTRING|POLYGON|MULTIPOINT|MULTILINESTRING|MULTIPOLYGON) \((?:[^\(\)]|\([^\)]*\))*\)/g, o3 = t2.match(n2);
    o3[0].startsWith("GEOMETRYCOLLECTION") && (o3[0] = o3[0].replace("GEOMETRYCOLLECTION (", ""));
    return o3.map(e49).map((e50) => e50 instanceof Array ? e50 : [e50]).reduce((e50, t3) => [...e50, ...t3], []);
  }
  return zV(t2) ? function(e50) {
    return e50.split(`
`).map((e51) => e51.match(/\(([^)]+)\)/)[1]).map(AV);
  }(t2) : BV(t2) ? function(e50) {
    return e50.split(`
`).map((e51) => e51.match(/\(([^)]+)\)/)[1]).map(kV).reduce((e51, t3) => [...e51, ...t3], []);
  }(t2) : [];
}, kX.BooleanOperations = JH, kX.Relations = uV;
FV = SY(), jV = 1, $V = FV != null ? iY(cY(FV)) : {}, ((e50, t2, n2, o3) => {
  if (t2 && typeof t2 == "object" || typeof t2 == "function")
    for (let i3 of aY(t2))
      lY.call(e50, i3) || i3 === n2 || rY(e50, i3, { get: () => t2[i3], enumerable: !(o3 = sY(t2, i3)) || o3.enumerable });
})(!jV && FV && FV.__esModule ? $V : rY($V, "default", { value: FV, enumerable: true }), FV);
var FV;
var jV;
var $V;
var YV = Object.create;
var XV = Object.defineProperty;
var HV = Object.getOwnPropertyDescriptor;
var VV = Object.getOwnPropertyNames;
var WV = Object.getPrototypeOf;
var GV = Object.prototype.hasOwnProperty;
var UV = (e50, t2) => function() {
  return t2 || (0, e50[VV(e50)[0]])((t2 = { exports: {} }).exports, t2), t2.exports;
};
var ZV = (e50, t2, n2) => (n2 = e50 != null ? YV(WV(e50)) : {}, ((e51, t3, n3, o3) => {
  if (t3 && typeof t3 == "object" || typeof t3 == "function")
    for (let i3 of VV(t3))
      GV.call(e51, i3) || i3 === n3 || XV(e51, i3, { get: () => t3[i3], enumerable: !(o3 = HV(t3, i3)) || o3.enumerable });
  return e51;
})(!t2 && e50 && e50.__esModule ? n2 : XV(n2, "default", { value: e50, enumerable: true }), e50));
var qV = UV({ "node_modules/is-buffer/index.js"(e50, t2) {
  function n2(e51) {
    return !!e51.constructor && typeof e51.constructor.isBuffer == "function" && e51.constructor.isBuffer(e51);
  }
  t2.exports = function(e51) {
    return e51 != null && (n2(e51) || function(e52) {
      return typeof e52.readFloatLE == "function" && typeof e52.slice == "function" && n2(e52.slice(0, 0));
    }(e51) || !!e51._isBuffer);
  };
} });
var JV = UV({ "node_modules/kind-of/index.js"(e50, t2) {
  var n2 = qV(), o3 = Object.prototype.toString;
  t2.exports = function(e51) {
    if (e51 === undefined)
      return "undefined";
    if (e51 === null)
      return "null";
    if (e51 === true || e51 === false || e51 instanceof Boolean)
      return "boolean";
    if (typeof e51 == "string" || e51 instanceof String)
      return "string";
    if (typeof e51 == "number" || e51 instanceof Number)
      return "number";
    if (typeof e51 == "function" || e51 instanceof Function)
      return "function";
    if (Array.isArray !== undefined && Array.isArray(e51))
      return "array";
    if (e51 instanceof RegExp)
      return "regexp";
    if (e51 instanceof Date)
      return "date";
    var t3 = o3.call(e51);
    return t3 === "[object RegExp]" ? "regexp" : t3 === "[object Date]" ? "date" : t3 === "[object Arguments]" ? "arguments" : t3 === "[object Error]" ? "error" : n2(e51) ? "buffer" : t3 === "[object Set]" ? "set" : t3 === "[object WeakSet]" ? "weakset" : t3 === "[object Map]" ? "map" : t3 === "[object WeakMap]" ? "weakmap" : t3 === "[object Symbol]" ? "symbol" : t3 === "[object Int8Array]" ? "int8array" : t3 === "[object Uint8Array]" ? "uint8array" : t3 === "[object Uint8ClampedArray]" ? "uint8clampedarray" : t3 === "[object Int16Array]" ? "int16array" : t3 === "[object Uint16Array]" ? "uint16array" : t3 === "[object Int32Array]" ? "int32array" : t3 === "[object Uint32Array]" ? "uint32array" : t3 === "[object Float32Array]" ? "float32array" : t3 === "[object Float64Array]" ? "float64array" : "object";
  };
} });
var QV = UV({ "node_modules/rename-keys/index.js"(e50, t2) {
  (function() {
    function e51(e52, t3) {
      if (typeof t3 != "function")
        return e52;
      var n2 = {};
      for (var o3 in e52)
        Object.prototype.hasOwnProperty.call(e52, o3) && (n2[t3(o3, e52[o3]) || o3] = e52[o3]);
      return n2;
    }
    t2 !== undefined && t2.exports ? t2.exports = e51 : typeof define == "function" && define.amd ? define([], function() {
      return e51;
    }) : window.rename = e51;
  })();
} });
var KV = UV({ "node_modules/deep-rename-keys/index.js"(e50, t2) {
  var n2 = JV(), o3 = QV();
  t2.exports = function e51(t3, i3) {
    var r3 = n2(t3);
    if (r3 !== "object" && r3 !== "array")
      throw new Error("expected an object");
    var s2 = [];
    for (var a3 in r3 === "object" && (t3 = o3(t3, i3), s2 = {}), t3)
      if (t3.hasOwnProperty(a3)) {
        var c3 = t3[a3];
        n2(c3) === "object" || n2(c3) === "array" ? s2[a3] = e51(c3, i3) : s2[a3] = c3;
      }
    return s2;
  };
} });
var eW = UV({ "node_modules/eventemitter3/index.js"(e50, t2) {
  var n2 = Object.prototype.hasOwnProperty, o3 = "~";
  function i3() {}
  function r3(e51, t3, n3) {
    this.fn = e51, this.context = t3, this.once = n3 || false;
  }
  function s2() {
    this._events = new i3, this._eventsCount = 0;
  }
  Object.create && (i3.prototype = Object.create(null), new i3().__proto__ || (o3 = false)), s2.prototype.eventNames = function() {
    var e51, t3, i4 = [];
    if (this._eventsCount === 0)
      return i4;
    for (t3 in e51 = this._events)
      n2.call(e51, t3) && i4.push(o3 ? t3.slice(1) : t3);
    return Object.getOwnPropertySymbols ? i4.concat(Object.getOwnPropertySymbols(e51)) : i4;
  }, s2.prototype.listeners = function(e51, t3) {
    var n3 = o3 ? o3 + e51 : e51, i4 = this._events[n3];
    if (t3)
      return !!i4;
    if (!i4)
      return [];
    if (i4.fn)
      return [i4.fn];
    for (var r4 = 0, s3 = i4.length, a3 = new Array(s3);r4 < s3; r4++)
      a3[r4] = i4[r4].fn;
    return a3;
  }, s2.prototype.emit = function(e51, t3, n3, i4, r4, s3) {
    var a3 = o3 ? o3 + e51 : e51;
    if (!this._events[a3])
      return false;
    var c3, l3, h2 = this._events[a3], d2 = arguments.length;
    if (h2.fn) {
      switch (h2.once && this.removeListener(e51, h2.fn, undefined, true), d2) {
        case 1:
          return h2.fn.call(h2.context), true;
        case 2:
          return h2.fn.call(h2.context, t3), true;
        case 3:
          return h2.fn.call(h2.context, t3, n3), true;
        case 4:
          return h2.fn.call(h2.context, t3, n3, i4), true;
        case 5:
          return h2.fn.call(h2.context, t3, n3, i4, r4), true;
        case 6:
          return h2.fn.call(h2.context, t3, n3, i4, r4, s3), true;
      }
      for (l3 = 1, c3 = new Array(d2 - 1);l3 < d2; l3++)
        c3[l3 - 1] = arguments[l3];
      h2.fn.apply(h2.context, c3);
    } else {
      var u2, p3 = h2.length;
      for (l3 = 0;l3 < p3; l3++)
        switch (h2[l3].once && this.removeListener(e51, h2[l3].fn, undefined, true), d2) {
          case 1:
            h2[l3].fn.call(h2[l3].context);
            break;
          case 2:
            h2[l3].fn.call(h2[l3].context, t3);
            break;
          case 3:
            h2[l3].fn.call(h2[l3].context, t3, n3);
            break;
          case 4:
            h2[l3].fn.call(h2[l3].context, t3, n3, i4);
            break;
          default:
            if (!c3)
              for (u2 = 1, c3 = new Array(d2 - 1);u2 < d2; u2++)
                c3[u2 - 1] = arguments[u2];
            h2[l3].fn.apply(h2[l3].context, c3);
        }
    }
    return true;
  }, s2.prototype.on = function(e51, t3, n3) {
    var i4 = new r3(t3, n3 || this), s3 = o3 ? o3 + e51 : e51;
    return this._events[s3] ? this._events[s3].fn ? this._events[s3] = [this._events[s3], i4] : this._events[s3].push(i4) : (this._events[s3] = i4, this._eventsCount++), this;
  }, s2.prototype.once = function(e51, t3, n3) {
    var i4 = new r3(t3, n3 || this, true), s3 = o3 ? o3 + e51 : e51;
    return this._events[s3] ? this._events[s3].fn ? this._events[s3] = [this._events[s3], i4] : this._events[s3].push(i4) : (this._events[s3] = i4, this._eventsCount++), this;
  }, s2.prototype.removeListener = function(e51, t3, n3, r4) {
    var s3 = o3 ? o3 + e51 : e51;
    if (!this._events[s3])
      return this;
    if (!t3)
      return --this._eventsCount === 0 ? this._events = new i3 : delete this._events[s3], this;
    var a3 = this._events[s3];
    if (a3.fn)
      a3.fn !== t3 || r4 && !a3.once || n3 && a3.context !== n3 || (--this._eventsCount === 0 ? this._events = new i3 : delete this._events[s3]);
    else {
      for (var c3 = 0, l3 = [], h2 = a3.length;c3 < h2; c3++)
        (a3[c3].fn !== t3 || r4 && !a3[c3].once || n3 && a3[c3].context !== n3) && l3.push(a3[c3]);
      l3.length ? this._events[s3] = l3.length === 1 ? l3[0] : l3 : --this._eventsCount === 0 ? this._events = new i3 : delete this._events[s3];
    }
    return this;
  }, s2.prototype.removeAllListeners = function(e51) {
    var t3;
    return e51 ? (t3 = o3 ? o3 + e51 : e51, this._events[t3] && (--this._eventsCount === 0 ? this._events = new i3 : delete this._events[t3])) : (this._events = new i3, this._eventsCount = 0), this;
  }, s2.prototype.off = s2.prototype.removeListener, s2.prototype.addListener = s2.prototype.on, s2.prototype.setMaxListeners = function() {
    return this;
  }, s2.prefixed = o3, s2.EventEmitter = s2, t2 !== undefined && (t2.exports = s2);
} });
var tW = UV({ "node_modules/xml-lexer/dist/lexer.js"(e50, t2) {
  function n2(e51, t3, n3) {
    return t3 in e51 ? Object.defineProperty(e51, t3, { value: n3, enumerable: true, configurable: true, writable: true }) : e51[t3] = n3, e51;
  }
  var o3 = eW(), i3 = function() {}, r3 = { 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" }, s2 = { 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" }, c3 = { " ": s2.space, "\t": s2.space, "\n": s2.space, "\r": s2.space, "<": s2.lt, ">": s2.gt, '"': s2.quote, "'": s2.quote, "=": s2.equal, "/": s2.slash };
  t2.exports = { State: r3, Action: s2, Type: a3, create: function(e51) {
    var t3, l3, h2, d2, u2, p3, m2, g2, f2, _2;
    e51 = Object.assign({ debug: false }, e51);
    var y2 = new o3, b2 = r3.data, x2 = "", v2 = "", I2 = "", S2 = "", C = "", P = "", M = function(t4, n3) {
      if (v2[0] !== "?" && v2[0] !== "!") {
        var o4 = { type: t4, value: n3 };
        e51.debug && console.log("emit:", o4), y2.emit("data", o4);
      }
    };
    y2.stateMachine = (n2(_2 = {}, r3.data, (n2(t3 = {}, s2.lt, function() {
      x2.trim() && M(a3.text, x2), v2 = "", C = false, b2 = r3.tagBegin;
    }), n2(t3, s2.char, function(e52) {
      x2 += e52;
    }), t3)), n2(_2, r3.cdata, n2({}, s2.char, function(e52) {
      (x2 += e52).substr(-3) === "]]>" && (M(a3.text, x2.slice(0, -3)), x2 = "", b2 = r3.data);
    })), n2(_2, r3.tagBegin, (n2(l3 = {}, s2.space, i3), n2(l3, s2.char, function(e52) {
      v2 = e52, b2 = r3.tagName;
    }), n2(l3, s2.slash, function() {
      v2 = "", C = true;
    }), l3)), n2(_2, r3.tagName, (n2(h2 = {}, s2.space, function() {
      C ? b2 = r3.tagEnd : (b2 = r3.attributeNameStart, M(a3.openTag, v2));
    }), n2(h2, s2.gt, function() {
      M(C ? a3.closeTag : a3.openTag, v2), x2 = "", b2 = r3.data;
    }), n2(h2, s2.slash, function() {
      b2 = r3.tagEnd, M(a3.openTag, v2);
    }), n2(h2, s2.char, function(e52) {
      (v2 += e52) === "![CDATA[" && (b2 = r3.cdata, x2 = "", v2 = "");
    }), h2)), n2(_2, r3.tagEnd, (n2(d2 = {}, s2.gt, function() {
      M(a3.closeTag, v2), x2 = "", b2 = r3.data;
    }), n2(d2, s2.char, i3), d2)), n2(_2, r3.attributeNameStart, (n2(u2 = {}, s2.char, function(e52) {
      I2 = e52, b2 = r3.attributeName;
    }), n2(u2, s2.gt, function() {
      x2 = "", b2 = r3.data;
    }), n2(u2, s2.space, i3), n2(u2, s2.slash, function() {
      C = true, b2 = r3.tagEnd;
    }), u2)), n2(_2, r3.attributeName, (n2(p3 = {}, s2.space, function() {
      b2 = r3.attributeNameEnd;
    }), n2(p3, s2.equal, function() {
      M(a3.attributeName, I2), b2 = r3.attributeValueBegin;
    }), n2(p3, s2.gt, function() {
      S2 = "", M(a3.attributeName, I2), M(a3.attributeValue, S2), x2 = "", b2 = r3.data;
    }), n2(p3, s2.slash, function() {
      C = true, S2 = "", M(a3.attributeName, I2), M(a3.attributeValue, S2), b2 = r3.tagEnd;
    }), n2(p3, s2.char, function(e52) {
      I2 += e52;
    }), p3)), n2(_2, r3.attributeNameEnd, (n2(m2 = {}, s2.space, i3), n2(m2, s2.equal, function() {
      M(a3.attributeName, I2), b2 = r3.attributeValueBegin;
    }), n2(m2, s2.gt, function() {
      S2 = "", M(a3.attributeName, I2), M(a3.attributeValue, S2), x2 = "", b2 = r3.data;
    }), n2(m2, s2.char, function(e52) {
      S2 = "", M(a3.attributeName, I2), M(a3.attributeValue, S2), I2 = e52, b2 = r3.attributeName;
    }), m2)), n2(_2, r3.attributeValueBegin, (n2(g2 = {}, s2.space, i3), n2(g2, s2.quote, function(e52) {
      P = e52, S2 = "", b2 = r3.attributeValue;
    }), n2(g2, s2.gt, function() {
      M(a3.attributeValue, S2 = ""), x2 = "", b2 = r3.data;
    }), n2(g2, s2.char, function(e52) {
      P = "", S2 = e52, b2 = r3.attributeValue;
    }), g2)), n2(_2, r3.attributeValue, (n2(f2 = {}, s2.space, function(e52) {
      P ? S2 += e52 : (M(a3.attributeValue, S2), b2 = r3.attributeNameStart);
    }), n2(f2, s2.quote, function(e52) {
      P === e52 ? (M(a3.attributeValue, S2), b2 = r3.attributeNameStart) : S2 += e52;
    }), n2(f2, s2.gt, function(e52) {
      P ? S2 += e52 : (M(a3.attributeValue, S2), x2 = "", b2 = r3.data);
    }), n2(f2, s2.slash, function(e52) {
      P ? S2 += e52 : (M(a3.attributeValue, S2), C = true, b2 = r3.tagEnd);
    }), n2(f2, s2.char, function(e52) {
      S2 += e52;
    }), f2)), _2);
    var w = function(t4) {
      e51.debug && console.log(b2, t4);
      var n3 = y2.stateMachine[b2], o4 = n3[function(e52) {
        return c3[e52] || s2.char;
      }(t4)] || n3[s2.error] || n3[s2.char];
      o4(t4);
    };
    return y2.write = function(e52) {
      for (var t4 = e52.length, n3 = 0;n3 < t4; n3++)
        w(e52[n3]);
    }, y2;
  } };
} });
var nW = UV({ "node_modules/xml-reader/dist/reader.js"(e50, t2) {
  var n2 = eW(), o3 = tW(), i3 = o3.Type, r3 = { element: "element", text: "text" }, s2 = function(e51) {
    return Object.assign({ name: "", type: r3.element, value: "", parent: null, attributes: {}, children: [] }, e51);
  }, a3 = function(e51) {
    e51 = Object.assign({ stream: false, parentNodes: true, doneEvent: "done", tagPrefix: "tag:", emitTopLevelOnly: false, debug: false }, e51);
    var t3 = undefined, a4 = undefined, c3 = undefined, l3 = undefined, h2 = new n2, d2 = function(n3) {
      switch (n3.type) {
        case i3.openTag:
          if (c3 === null)
            (c3 = a4).name = n3.value;
          else {
            var o4 = s2({ name: n3.value, parent: c3 });
            c3.children.push(o4), c3 = o4;
          }
          break;
        case i3.closeTag:
          var d3 = c3.parent;
          if (e51.parentNodes || (c3.parent = null), c3.name !== n3.value)
            break;
          e51.stream && d3 === a4 && (a4.children = [], c3.parent = null), e51.emitTopLevelOnly && d3 !== a4 || (h2.emit(e51.tagPrefix + c3.name, c3), h2.emit("tag", c3.name, c3)), c3 === a4 && (t3.removeAllListeners("data"), h2.emit(e51.doneEvent, c3), a4 = null), c3 = d3;
          break;
        case i3.text:
          c3 && c3.children.push(s2({ type: r3.text, value: n3.value, parent: e51.parentNodes ? c3 : null }));
          break;
        case i3.attributeName:
          l3 = n3.value, c3.attributes[l3] = "";
          break;
        case i3.attributeValue:
          c3.attributes[l3] = n3.value;
      }
    };
    return h2.reset = function() {
      (t3 = o3.create({ debug: e51.debug })).on("data", d2), a4 = s2(), c3 = null, l3 = "", h2.parse = t3.write;
    }, h2.reset(), h2;
  };
  t2.exports = { parseSync: function(e51, t3) {
    t3 = Object.assign({}, t3, { stream: false, tagPrefix: ":" });
    var n3 = a3(t3), o4 = undefined;
    return n3.on("done", function(e52) {
      o4 = e52;
    }), n3.parse(e51), o4;
  }, create: a3, NodeType: r3 };
} });
var aW = (ZV(KV()), ZV(nW()), Object.create);
var cW = Object.defineProperty;
var lW = Object.getOwnPropertyDescriptor;
var hW = Object.getOwnPropertyNames;
var dW = Object.getPrototypeOf;
var uW = Object.prototype.hasOwnProperty;
var pW = (e50, t2) => function() {
  return t2 || (0, e50[hW(e50)[0]])((t2 = { exports: {} }).exports, t2), t2.exports;
};
var mW = (e50, t2, n2) => (n2 = e50 != null ? aW(dW(e50)) : {}, ((e51, t3, n3, o3) => {
  if (t3 && typeof t3 == "object" || typeof t3 == "function")
    for (let i3 of hW(t3))
      uW.call(e51, i3) || i3 === n3 || cW(e51, i3, { get: () => t3[i3], enumerable: !(o3 = lW(t3, i3)) || o3.enumerable });
  return e51;
})(!t2 && e50 && e50.__esModule ? n2 : cW(n2, "default", { value: e50, enumerable: true }), e50));
var gW = pW({ "node_modules/is-buffer/index.js"(e50, t2) {
  function n2(e51) {
    return !!e51.constructor && typeof e51.constructor.isBuffer == "function" && e51.constructor.isBuffer(e51);
  }
  t2.exports = function(e51) {
    return e51 != null && (n2(e51) || function(e52) {
      return typeof e52.readFloatLE == "function" && typeof e52.slice == "function" && n2(e52.slice(0, 0));
    }(e51) || !!e51._isBuffer);
  };
} });
var fW = pW({ "node_modules/kind-of/index.js"(e50, t2) {
  var n2 = gW(), o3 = Object.prototype.toString;
  t2.exports = function(e51) {
    if (e51 === undefined)
      return "undefined";
    if (e51 === null)
      return "null";
    if (e51 === true || e51 === false || e51 instanceof Boolean)
      return "boolean";
    if (typeof e51 == "string" || e51 instanceof String)
      return "string";
    if (typeof e51 == "number" || e51 instanceof Number)
      return "number";
    if (typeof e51 == "function" || e51 instanceof Function)
      return "function";
    if (Array.isArray !== undefined && Array.isArray(e51))
      return "array";
    if (e51 instanceof RegExp)
      return "regexp";
    if (e51 instanceof Date)
      return "date";
    var t3 = o3.call(e51);
    return t3 === "[object RegExp]" ? "regexp" : t3 === "[object Date]" ? "date" : t3 === "[object Arguments]" ? "arguments" : t3 === "[object Error]" ? "error" : n2(e51) ? "buffer" : t3 === "[object Set]" ? "set" : t3 === "[object WeakSet]" ? "weakset" : t3 === "[object Map]" ? "map" : t3 === "[object WeakMap]" ? "weakmap" : t3 === "[object Symbol]" ? "symbol" : t3 === "[object Int8Array]" ? "int8array" : t3 === "[object Uint8Array]" ? "uint8array" : t3 === "[object Uint8ClampedArray]" ? "uint8clampedarray" : t3 === "[object Int16Array]" ? "int16array" : t3 === "[object Uint16Array]" ? "uint16array" : t3 === "[object Int32Array]" ? "int32array" : t3 === "[object Uint32Array]" ? "uint32array" : t3 === "[object Float32Array]" ? "float32array" : t3 === "[object Float64Array]" ? "float64array" : "object";
  };
} });
var _W = pW({ "node_modules/rename-keys/index.js"(e50, t2) {
  (function() {
    function e51(e52, t3) {
      if (typeof t3 != "function")
        return e52;
      var n2 = {};
      for (var o3 in e52)
        Object.prototype.hasOwnProperty.call(e52, o3) && (n2[t3(o3, e52[o3]) || o3] = e52[o3]);
      return n2;
    }
    t2 !== undefined && t2.exports ? t2.exports = e51 : typeof define == "function" && define.amd ? define([], function() {
      return e51;
    }) : window.rename = e51;
  })();
} });
var yW = pW({ "node_modules/deep-rename-keys/index.js"(e50, t2) {
  var n2 = fW(), o3 = _W();
  t2.exports = function e51(t3, i3) {
    var r3 = n2(t3);
    if (r3 !== "object" && r3 !== "array")
      throw new Error("expected an object");
    var s2 = [];
    for (var a3 in r3 === "object" && (t3 = o3(t3, i3), s2 = {}), t3)
      if (t3.hasOwnProperty(a3)) {
        var c3 = t3[a3];
        n2(c3) === "object" || n2(c3) === "array" ? s2[a3] = e51(c3, i3) : s2[a3] = c3;
      }
    return s2;
  };
} });
var bW = pW({ "node_modules/eventemitter3/index.js"(e50, t2) {
  var n2 = Object.prototype.hasOwnProperty, o3 = "~";
  function i3() {}
  function r3(e51, t3, n3) {
    this.fn = e51, this.context = t3, this.once = n3 || false;
  }
  function s2() {
    this._events = new i3, this._eventsCount = 0;
  }
  Object.create && (i3.prototype = Object.create(null), new i3().__proto__ || (o3 = false)), s2.prototype.eventNames = function() {
    var e51, t3, i4 = [];
    if (this._eventsCount === 0)
      return i4;
    for (t3 in e51 = this._events)
      n2.call(e51, t3) && i4.push(o3 ? t3.slice(1) : t3);
    return Object.getOwnPropertySymbols ? i4.concat(Object.getOwnPropertySymbols(e51)) : i4;
  }, s2.prototype.listeners = function(e51, t3) {
    var n3 = o3 ? o3 + e51 : e51, i4 = this._events[n3];
    if (t3)
      return !!i4;
    if (!i4)
      return [];
    if (i4.fn)
      return [i4.fn];
    for (var r4 = 0, s3 = i4.length, a3 = new Array(s3);r4 < s3; r4++)
      a3[r4] = i4[r4].fn;
    return a3;
  }, s2.prototype.emit = function(e51, t3, n3, i4, r4, s3) {
    var a3 = o3 ? o3 + e51 : e51;
    if (!this._events[a3])
      return false;
    var c3, l3, h2 = this._events[a3], d2 = arguments.length;
    if (h2.fn) {
      switch (h2.once && this.removeListener(e51, h2.fn, undefined, true), d2) {
        case 1:
          return h2.fn.call(h2.context), true;
        case 2:
          return h2.fn.call(h2.context, t3), true;
        case 3:
          return h2.fn.call(h2.context, t3, n3), true;
        case 4:
          return h2.fn.call(h2.context, t3, n3, i4), true;
        case 5:
          return h2.fn.call(h2.context, t3, n3, i4, r4), true;
        case 6:
          return h2.fn.call(h2.context, t3, n3, i4, r4, s3), true;
      }
      for (l3 = 1, c3 = new Array(d2 - 1);l3 < d2; l3++)
        c3[l3 - 1] = arguments[l3];
      h2.fn.apply(h2.context, c3);
    } else {
      var u2, p3 = h2.length;
      for (l3 = 0;l3 < p3; l3++)
        switch (h2[l3].once && this.removeListener(e51, h2[l3].fn, undefined, true), d2) {
          case 1:
            h2[l3].fn.call(h2[l3].context);
            break;
          case 2:
            h2[l3].fn.call(h2[l3].context, t3);
            break;
          case 3:
            h2[l3].fn.call(h2[l3].context, t3, n3);
            break;
          case 4:
            h2[l3].fn.call(h2[l3].context, t3, n3, i4);
            break;
          default:
            if (!c3)
              for (u2 = 1, c3 = new Array(d2 - 1);u2 < d2; u2++)
                c3[u2 - 1] = arguments[u2];
            h2[l3].fn.apply(h2[l3].context, c3);
        }
    }
    return true;
  }, s2.prototype.on = function(e51, t3, n3) {
    var i4 = new r3(t3, n3 || this), s3 = o3 ? o3 + e51 : e51;
    return this._events[s3] ? this._events[s3].fn ? this._events[s3] = [this._events[s3], i4] : this._events[s3].push(i4) : (this._events[s3] = i4, this._eventsCount++), this;
  }, s2.prototype.once = function(e51, t3, n3) {
    var i4 = new r3(t3, n3 || this, true), s3 = o3 ? o3 + e51 : e51;
    return this._events[s3] ? this._events[s3].fn ? this._events[s3] = [this._events[s3], i4] : this._events[s3].push(i4) : (this._events[s3] = i4, this._eventsCount++), this;
  }, s2.prototype.removeListener = function(e51, t3, n3, r4) {
    var s3 = o3 ? o3 + e51 : e51;
    if (!this._events[s3])
      return this;
    if (!t3)
      return --this._eventsCount === 0 ? this._events = new i3 : delete this._events[s3], this;
    var a3 = this._events[s3];
    if (a3.fn)
      a3.fn !== t3 || r4 && !a3.once || n3 && a3.context !== n3 || (--this._eventsCount === 0 ? this._events = new i3 : delete this._events[s3]);
    else {
      for (var c3 = 0, l3 = [], h2 = a3.length;c3 < h2; c3++)
        (a3[c3].fn !== t3 || r4 && !a3[c3].once || n3 && a3[c3].context !== n3) && l3.push(a3[c3]);
      l3.length ? this._events[s3] = l3.length === 1 ? l3[0] : l3 : --this._eventsCount === 0 ? this._events = new i3 : delete this._events[s3];
    }
    return this;
  }, s2.prototype.removeAllListeners = function(e51) {
    var t3;
    return e51 ? (t3 = o3 ? o3 + e51 : e51, this._events[t3] && (--this._eventsCount === 0 ? this._events = new i3 : delete this._events[t3])) : (this._events = new i3, this._eventsCount = 0), this;
  }, s2.prototype.off = s2.prototype.removeListener, s2.prototype.addListener = s2.prototype.on, s2.prototype.setMaxListeners = function() {
    return this;
  }, s2.prefixed = o3, s2.EventEmitter = s2, t2 !== undefined && (t2.exports = s2);
} });
var xW = pW({ "node_modules/xml-lexer/dist/lexer.js"(e50, t2) {
  function n2(e51, t3, n3) {
    return t3 in e51 ? Object.defineProperty(e51, t3, { value: n3, enumerable: true, configurable: true, writable: true }) : e51[t3] = n3, e51;
  }
  var o3 = bW(), i3 = function() {}, r3 = { 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" }, s2 = { 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" }, c3 = { " ": s2.space, "\t": s2.space, "\n": s2.space, "\r": s2.space, "<": s2.lt, ">": s2.gt, '"': s2.quote, "'": s2.quote, "=": s2.equal, "/": s2.slash };
  t2.exports = { State: r3, Action: s2, Type: a3, create: function(e51) {
    var t3, l3, h2, d2, u2, p3, m2, g2, f2, _2;
    e51 = Object.assign({ debug: false }, e51);
    var y2 = new o3, b2 = r3.data, x2 = "", v2 = "", I2 = "", S2 = "", C = "", P = "", M = function(t4, n3) {
      if (v2[0] !== "?" && v2[0] !== "!") {
        var o4 = { type: t4, value: n3 };
        e51.debug && console.log("emit:", o4), y2.emit("data", o4);
      }
    };
    y2.stateMachine = (n2(_2 = {}, r3.data, (n2(t3 = {}, s2.lt, function() {
      x2.trim() && M(a3.text, x2), v2 = "", C = false, b2 = r3.tagBegin;
    }), n2(t3, s2.char, function(e52) {
      x2 += e52;
    }), t3)), n2(_2, r3.cdata, n2({}, s2.char, function(e52) {
      (x2 += e52).substr(-3) === "]]>" && (M(a3.text, x2.slice(0, -3)), x2 = "", b2 = r3.data);
    })), n2(_2, r3.tagBegin, (n2(l3 = {}, s2.space, i3), n2(l3, s2.char, function(e52) {
      v2 = e52, b2 = r3.tagName;
    }), n2(l3, s2.slash, function() {
      v2 = "", C = true;
    }), l3)), n2(_2, r3.tagName, (n2(h2 = {}, s2.space, function() {
      C ? b2 = r3.tagEnd : (b2 = r3.attributeNameStart, M(a3.openTag, v2));
    }), n2(h2, s2.gt, function() {
      M(C ? a3.closeTag : a3.openTag, v2), x2 = "", b2 = r3.data;
    }), n2(h2, s2.slash, function() {
      b2 = r3.tagEnd, M(a3.openTag, v2);
    }), n2(h2, s2.char, function(e52) {
      (v2 += e52) === "![CDATA[" && (b2 = r3.cdata, x2 = "", v2 = "");
    }), h2)), n2(_2, r3.tagEnd, (n2(d2 = {}, s2.gt, function() {
      M(a3.closeTag, v2), x2 = "", b2 = r3.data;
    }), n2(d2, s2.char, i3), d2)), n2(_2, r3.attributeNameStart, (n2(u2 = {}, s2.char, function(e52) {
      I2 = e52, b2 = r3.attributeName;
    }), n2(u2, s2.gt, function() {
      x2 = "", b2 = r3.data;
    }), n2(u2, s2.space, i3), n2(u2, s2.slash, function() {
      C = true, b2 = r3.tagEnd;
    }), u2)), n2(_2, r3.attributeName, (n2(p3 = {}, s2.space, function() {
      b2 = r3.attributeNameEnd;
    }), n2(p3, s2.equal, function() {
      M(a3.attributeName, I2), b2 = r3.attributeValueBegin;
    }), n2(p3, s2.gt, function() {
      S2 = "", M(a3.attributeName, I2), M(a3.attributeValue, S2), x2 = "", b2 = r3.data;
    }), n2(p3, s2.slash, function() {
      C = true, S2 = "", M(a3.attributeName, I2), M(a3.attributeValue, S2), b2 = r3.tagEnd;
    }), n2(p3, s2.char, function(e52) {
      I2 += e52;
    }), p3)), n2(_2, r3.attributeNameEnd, (n2(m2 = {}, s2.space, i3), n2(m2, s2.equal, function() {
      M(a3.attributeName, I2), b2 = r3.attributeValueBegin;
    }), n2(m2, s2.gt, function() {
      S2 = "", M(a3.attributeName, I2), M(a3.attributeValue, S2), x2 = "", b2 = r3.data;
    }), n2(m2, s2.char, function(e52) {
      S2 = "", M(a3.attributeName, I2), M(a3.attributeValue, S2), I2 = e52, b2 = r3.attributeName;
    }), m2)), n2(_2, r3.attributeValueBegin, (n2(g2 = {}, s2.space, i3), n2(g2, s2.quote, function(e52) {
      P = e52, S2 = "", b2 = r3.attributeValue;
    }), n2(g2, s2.gt, function() {
      M(a3.attributeValue, S2 = ""), x2 = "", b2 = r3.data;
    }), n2(g2, s2.char, function(e52) {
      P = "", S2 = e52, b2 = r3.attributeValue;
    }), g2)), n2(_2, r3.attributeValue, (n2(f2 = {}, s2.space, function(e52) {
      P ? S2 += e52 : (M(a3.attributeValue, S2), b2 = r3.attributeNameStart);
    }), n2(f2, s2.quote, function(e52) {
      P === e52 ? (M(a3.attributeValue, S2), b2 = r3.attributeNameStart) : S2 += e52;
    }), n2(f2, s2.gt, function(e52) {
      P ? S2 += e52 : (M(a3.attributeValue, S2), x2 = "", b2 = r3.data);
    }), n2(f2, s2.slash, function(e52) {
      P ? S2 += e52 : (M(a3.attributeValue, S2), C = true, b2 = r3.tagEnd);
    }), n2(f2, s2.char, function(e52) {
      S2 += e52;
    }), f2)), _2);
    var w = function(t4) {
      e51.debug && console.log(b2, t4);
      var n3 = y2.stateMachine[b2], o4 = n3[function(e52) {
        return c3[e52] || s2.char;
      }(t4)] || n3[s2.error] || n3[s2.char];
      o4(t4);
    };
    return y2.write = function(e52) {
      for (var t4 = e52.length, n3 = 0;n3 < t4; n3++)
        w(e52[n3]);
    }, y2;
  } };
} });
var vW = pW({ "node_modules/xml-reader/dist/reader.js"(e50, t2) {
  var n2 = bW(), o3 = xW(), i3 = o3.Type, r3 = { element: "element", text: "text" }, s2 = function(e51) {
    return Object.assign({ name: "", type: r3.element, value: "", parent: null, attributes: {}, children: [] }, e51);
  }, a3 = function(e51) {
    e51 = Object.assign({ stream: false, parentNodes: true, doneEvent: "done", tagPrefix: "tag:", emitTopLevelOnly: false, debug: false }, e51);
    var t3 = undefined, a4 = undefined, c3 = undefined, l3 = undefined, h2 = new n2, d2 = function(n3) {
      switch (n3.type) {
        case i3.openTag:
          if (c3 === null)
            (c3 = a4).name = n3.value;
          else {
            var o4 = s2({ name: n3.value, parent: c3 });
            c3.children.push(o4), c3 = o4;
          }
          break;
        case i3.closeTag:
          var d3 = c3.parent;
          if (e51.parentNodes || (c3.parent = null), c3.name !== n3.value)
            break;
          e51.stream && d3 === a4 && (a4.children = [], c3.parent = null), e51.emitTopLevelOnly && d3 !== a4 || (h2.emit(e51.tagPrefix + c3.name, c3), h2.emit("tag", c3.name, c3)), c3 === a4 && (t3.removeAllListeners("data"), h2.emit(e51.doneEvent, c3), a4 = null), c3 = d3;
          break;
        case i3.text:
          c3 && c3.children.push(s2({ type: r3.text, value: n3.value, parent: e51.parentNodes ? c3 : null }));
          break;
        case i3.attributeName:
          l3 = n3.value, c3.attributes[l3] = "";
          break;
        case i3.attributeValue:
          c3.attributes[l3] = n3.value;
      }
    };
    return h2.reset = function() {
      (t3 = o3.create({ debug: e51.debug })).on("data", d2), a4 = s2(), c3 = null, l3 = "", h2.parse = t3.write;
    }, h2.reset(), h2;
  };
  t2.exports = { parseSync: function(e51, t3) {
    t3 = Object.assign({}, t3, { stream: false, tagPrefix: ":" });
    var n3 = a3(t3), o4 = undefined;
    return n3.on("done", function(e52) {
      o4 = e52;
    }), n3.parse(e51), o4;
  }, create: a3, NodeType: r3 };
} });
mW(yW()), mW(vW());
function MW(e50, t2) {
  if (e50.points)
    for (const n2 of e50.points)
      n2.step = t2;
  if (e50.lines)
    for (const n2 of e50.lines)
      n2.step = t2;
  if (e50.infiniteLines)
    for (const n2 of e50.infiniteLines)
      n2.step = t2;
  if (e50.polygons)
    for (const n2 of e50.polygons)
      n2.step = t2;
  if (e50.rects)
    for (const n2 of e50.rects)
      n2.step = t2;
  if (e50.circles)
    for (const n2 of e50.circles)
      n2.step = t2;
  if (e50.texts)
    for (const n2 of e50.texts)
      n2.step = t2;
  return e50;
}
var wW = class {
  MAX_ITERATIONS = 1e5;
  solved = false;
  failed = false;
  iterations = 0;
  progress = 0;
  error = null;
  activeSubSolver;
  failedSubSolvers;
  timeToSolve;
  stats = {};
  _setupDone = false;
  getSolverName() {
    return this.constructor.name;
  }
  setup() {
    this._setupDone || (this._setup(), this._setupDone = true);
  }
  _setup() {}
  step() {
    if (this._setupDone || this.setup(), !this.solved && !this.failed) {
      this.iterations++;
      try {
        this._step();
      } catch (e50) {
        throw this.error = `${this.getSolverName()} error: ${e50}`, this.failed = true, e50;
      }
      !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 = true), "computeProgress" in this && (this.progress = this.computeProgress());
    }
  }
  _step() {}
  getConstructorParams() {
    throw new Error("getConstructorParams not implemented");
  }
  getOutput() {
    return null;
  }
  solve() {
    const e50 = Date.now();
    for (;!this.solved && !this.failed; )
      this.step();
    const t2 = Date.now();
    this.timeToSolve = t2 - e50;
  }
  visualize() {
    return { lines: [], points: [], rects: [], circles: [] };
  }
  tryFinalAcceptance() {}
  preview() {
    return { lines: [], points: [], rects: [], circles: [] };
  }
};
function NW(e50, t2, n2, o3 = {}) {
  return { solverName: e50, solverClass: t2, getConstructorParams: n2, onSolved: o3.onSolved };
}
var RW = class extends wW {
  startTimeOfStage = {};
  endTimeOfStage = {};
  timeSpentOnStage = {};
  firstIterationOfStage = {};
  currentPipelineStageIndex = 0;
  inputProblem;
  pipelineOutputs = {};
  constructor(e50) {
    super(), this.inputProblem = e50, this.MAX_ITERATIONS = 1e6;
  }
  _step() {
    const e50 = this.pipelineDef[this.currentPipelineStageIndex];
    if (!e50)
      return void (this.solved = true);
    if (this.activeSubSolver) {
      if (this.activeSubSolver.step(), this.activeSubSolver.solved) {
        this.endTimeOfStage[e50.solverName] = performance.now(), this.timeSpentOnStage[e50.solverName] = this.endTimeOfStage[e50.solverName] - this.startTimeOfStage[e50.solverName];
        const t3 = this.activeSubSolver.getOutput();
        t3 !== null && (this.pipelineOutputs[e50.solverName] = t3), e50.onSolved?.(this), this.activeSubSolver = null, this.currentPipelineStageIndex++;
      } else
        this.activeSubSolver.failed && (this.error = this.activeSubSolver?.error, this.failed = true, this.activeSubSolver = null);
      return;
    }
    const t2 = e50.getConstructorParams(this);
    this.activeSubSolver = new e50.solverClass(...t2), this[e50.solverName] = this.activeSubSolver, this.timeSpentOnStage[e50.solverName] = 0, this.startTimeOfStage[e50.solverName] = performance.now(), this.firstIterationOfStage[e50.solverName] = this.iterations;
  }
  solveUntilStage(e50) {
    for (;this.getCurrentStageName().toLowerCase() !== e50.toLowerCase() && (this.step(), !this.failed && !this.solved); )
      ;
  }
  getCurrentStageName() {
    return this.pipelineDef[this.currentPipelineStageIndex]?.solverName ?? "none";
  }
  getStageProgress() {
    const e50 = this.pipelineDef.length;
    if (e50 === 0)
      return 1;
    const t2 = this.activeSubSolver?.progress ?? 0;
    return (this.currentPipelineStageIndex + t2) / e50;
  }
  getStageStats() {
    const e50 = {};
    for (const t2 of this.pipelineDef) {
      const n2 = this.timeSpentOnStage[t2.solverName] || 0, o3 = this.firstIterationOfStage[t2.solverName] || 0, i3 = this.iterations, r3 = t2.solverName === this.getCurrentStageName() ? i3 - o3 : 0, s2 = this.currentPipelineStageIndex > this.pipelineDef.findIndex((e51) => e51.solverName === t2.solverName);
      e50[t2.solverName] = { timeSpent: n2, iterations: r3, completed: s2 };
    }
    return e50;
  }
  initialVisualize() {
    return null;
  }
  finalVisualize() {
    return null;
  }
  visualize() {
    if (!this.solved && this.activeSubSolver)
      return this.activeSubSolver.visualize();
    let e50 = 0;
    const t2 = this.initialVisualize();
    t2 && (MW(t2, 0), e50 = 1);
    let n2 = null;
    this.solved && (n2 = this.finalVisualize());
    const o3 = [t2].filter(Boolean).concat(this.pipelineDef.map((t3, n3) => {
      const o4 = this[t3.solverName], i3 = o4?.visualize();
      return i3 ? (MW(i3, n3 + e50), i3) : null;
    }).filter(Boolean));
    return o3.length === 0 ? { points: [], rects: [], lines: [], circles: [], texts: [] } : (this.solved && n2 && (MW(n2, o3.length + e50 + 1), o3.push(n2)), o3.length === 1 ? o3[0] : { points: o3.flatMap((e51) => e51.points || []), rects: o3.flatMap((e51) => e51.rects || []), lines: o3.flatMap((e51) => e51.lines || []), circles: o3.flatMap((e51) => e51.circles || []), texts: o3.flatMap((e51) => e51.texts || []) });
  }
  preview() {
    return this.activeSubSolver ? this.activeSubSolver.preview() : super.preview();
  }
  computeProgress() {
    return this.getStageProgress();
  }
  getStageOutput(e50) {
    return this.pipelineOutputs[e50];
  }
  getAllOutputs() {
    return { ...this.pipelineOutputs };
  }
  hasStageOutput(e50) {
    return e50 in this.pipelineOutputs;
  }
  getSolver(e50) {
    return this[e50];
  }
};
var TW = (e50, t2, n2) => (t2.x - e50.x) * (n2.y - e50.y) - (t2.y - e50.y) * (n2.x - e50.x);
var EW = (e50, t2) => {
  const n2 = [...new Set(e50)].map((e51) => {
    const n3 = t2[e51];
    return n3 ? { i: e51, x: n3.x, y: n3.y } : null;
  }).filter((e51) => e51 !== null);
  if (n2.sort((e51, t3) => e51.x - t3.x || e51.y - t3.y), n2.length <= 2)
    return n2.map((e51) => e51.i);
  const o3 = [], i3 = [];
  for (const e51 of n2) {
    for (;o3.length >= 2; ) {
      const t3 = o3[o3.length - 2], n3 = o3[o3.length - 1];
      if (!t3 || !n3 || TW(t3, n3, e51) > 0.0000000001)
        break;
      o3.pop();
    }
    o3.push(e51);
  }
  for (let e51 = n2.length - 1;e51 >= 0; e51--) {
    const t3 = n2[e51];
    if (t3) {
      for (;i3.length >= 2; ) {
        const e52 = i3[i3.length - 2], n3 = i3[i3.length - 1];
        if (!e52 || !n3 || TW(e52, n3, t3) > 0.0000000001)
          break;
        i3.pop();
      }
      i3.push(t3);
    }
  }
  return o3.pop(), i3.pop(), o3.concat(i3).map((e51) => e51.i);
};
var AW = (e50) => e50 !== undefined;
var OW = class extends wW {
  input;
  output = null;
  constructor(e50) {
    super(), this.input = e50;
  }
  _step() {
    const { regions: e50, hulls: t2 } = { regions: (n2 = this.input).cells.map((e51) => e51.map((e52) => n2.pts[e52]).filter(AW)), hulls: n2.cells.map((e51) => EW(e51, n2.pts).map((e52) => n2.pts[e52]).filter(AW)) };
    var n2;
    this.output = { pts: this.input.pts, validTris: this.input.validTris, regions: e50, hulls: t2, depths: this.input.depths }, this.stats = { regions: e50.length }, this.solved = true;
  }
  getConstructorParams() {
    return [this.input];
  }
  getOutput() {
    return this.output;
  }
  visualize() {
    const e50 = this.output;
    return e50 ? { points: e50.pts.map((e51) => ({ x: e51.x, y: e51.y, color: "#3b82f6" })), lines: e50.regions.flatMap((e51) => e51.flatMap((t2, n2) => {
      const o3 = e51[(n2 + 1) % e51.length];
      return o3 ? [{ points: [t2, o3], strokeColor: "#0f766e" }] : [];
    })), rects: [], circles: [], texts: [{ x: 4, y: 12, text: `regions: ${e50.regions.length}`, color: "#1f2937" }] } : { points: [], lines: [], rects: [], circles: [], texts: [] };
  }
};
var kW = (e50, t2, n2) => {
  const o3 = Math.cos(n2.ccwRotation), i3 = Math.sin(n2.ccwRotation);
  return { x: n2.center.x + e50 * o3 - t2 * i3, y: n2.center.y + e50 * i3 + t2 * o3 };
};
var DW = (e50, t2 = [], n2, o3 = []) => {
  const i3 = [], { minX: r3, maxX: s2, minY: a3, maxY: c3 } = e50;
  i3.push({ x: r3, y: a3 }, { x: s2, y: a3 }, { x: s2, y: c3 }, { x: r3, y: c3 });
  for (let e51 = 1;e51 < 10; e51++) {
    const t3 = e51 / 10;
    i3.push({ x: r3 + t3 * (s2 - r3), y: a3 }), i3.push({ x: s2, y: a3 + t3 * (c3 - a3) }), i3.push({ x: s2 - t3 * (s2 - r3), y: c3 }), i3.push({ x: r3, y: c3 - t3 * (c3 - a3) });
  }
  for (const e51 of t2) {
    const t3 = e51.diameter / 2 + n2;
    for (let n3 = 0;n3 < 24; n3++) {
      const o4 = 2 * Math.PI * n3 / 24;
      i3.push({ x: e51.center.x + t3 * Math.cos(o4), y: e51.center.y + t3 * Math.sin(o4) });
    }
  }
  for (const e51 of o3) {
    const t3 = e51.width / 2 + n2, o4 = e51.height / 2 + n2, r4 = Math.max(2, Math.ceil(Math.max(2 * t3, 2 * o4) / 20));
    for (let n3 = 0;n3 < r4; n3++) {
      const s3 = n3 / r4;
      i3.push(kW(2 * s3 * t3 - t3, -o4, e51)), i3.push(kW(t3, 2 * s3 * o4 - o4, e51)), i3.push(kW(t3 - 2 * s3 * t3, o4, e51)), i3.push(kW(-t3, o4 - 2 * s3 * o4, e51));
    }
  }
  return i3.map((e51, t3) => ({ x: e51.x + 0.000001 * (t3 % 7 - 3), y: e51.y + 0.000001 * (t3 % 5 - 2) }));
};
var LW = class extends wW {
  input;
  output = null;
  constructor(e50) {
    super(), this.input = e50;
  }
  _step() {
    const e50 = this.input.vias ?? [], t2 = this.input.rects ?? [];
    this.output = { pts: DW(this.input.bounds, e50, this.input.clearance, t2) }, this.stats = { points: this.output.pts.length }, this.solved = true;
  }
  getConstructorParams() {
    return [this.input];
  }
  getOutput() {
    return this.output;
  }
  visualize() {
    const e50 = (this.output?.pts ?? []).map((e51) => ({ x: e51.x, y: e51.y, color: "#2563eb" }));
    return { points: e50, lines: [], rects: [], circles: (this.input.vias ?? []).map((e51) => ({ center: { x: e51.center.x, y: e51.center.y }, radius: e51.diameter / 2 + this.input.clearance, stroke: "#ef4444" })), texts: [{ x: this.input.bounds.minX + 6, y: this.input.bounds.minY + 12, text: `sample points: ${e50.length}`, color: "#1f2937" }] };
  }
};
var zW = (e50, t2, n2) => {
  const o3 = n2.x - t2.x, i3 = n2.y - t2.y, r3 = o3 * o3 + i3 * i3;
  if (r3 < 0.0000000001)
    return Math.hypot(e50.x - t2.x, e50.y - t2.y);
  let s2 = ((e50.x - t2.x) * o3 + (e50.y - t2.y) * i3) / r3;
  return s2 = Math.max(0, Math.min(1, s2)), Math.hypot(e50.x - t2.x - s2 * o3, e50.y - t2.y - s2 * i3);
};
var BW = (e50, t2) => {
  if (e50.length <= 3)
    return 0;
  const n2 = EW(e50, t2), o3 = new Set(n2), i3 = n2.map((e51) => t2[e51]).filter((e51) => Boolean(e51));
  let r3 = 0;
  for (const n3 of e50) {
    if (o3.has(n3))
      continue;
    const e51 = t2[n3];
    if (!e51)
      continue;
    let s2 = Number.POSITIVE_INFINITY;
    for (let t3 = 0;t3 < i3.length; t3++) {
      const n4 = i3[t3], o4 = i3[(t3 + 1) % i3.length];
      n4 && o4 && (s2 = Math.min(s2, zW(e51, n4, o4)));
    }
    r3 = Math.max(r3, s2);
  }
  return r3;
};
var FW = (e50, t2) => e50 < t2 ? 1e5 * e50 + t2 : 1e5 * t2 + e50;
var jW = (e50, t2) => {
  const n2 = e50.map((t3, n3) => [t3, e50[(n3 + 1) % e50.length]]), o3 = t2.map((e51, n3) => [e51, t2[(n3 + 1) % t2.length]]), i3 = new Set;
  for (const [e51, t3] of n2)
    if (t3 !== undefined)
      for (const [n3, r4] of o3)
        r4 !== undefined && e51 === r4 && t3 === n3 && i3.add(FW(e51, t3));
  if (i3.size === 0)
    return null;
  const r3 = [];
  for (const [e51, t3] of n2)
    t3 !== undefined && (i3.has(FW(e51, t3)) || r3.push([e51, t3]));
  for (const [e51, t3] of o3)
    t3 !== undefined && (i3.has(FW(e51, t3)) || r3.push([e51, t3]));
  if (r3.length === 0)
    return null;
  const s2 = new Map;
  for (const [e51, t3] of r3)
    s2.set(e51, t3);
  const a3 = r3[0]?.[0];
  if (a3 === undefined)
    return null;
  const c3 = [a3];
  let l3 = s2.get(a3), h2 = 0;
  for (;l3 !== undefined && l3 !== a3 && h2++ < r3.length + 5; )
    c3.push(l3), l3 = s2.get(l3);
  return l3 !== a3 || c3.length !== r3.length ? null : c3;
};
var $W = (e50, t2) => e50 < t2 ? 1e5 * e50 + t2 : 1e5 * t2 + e50;
var YW = class extends wW {
  input;
  output = null;
  constructor(e50) {
    super(), this.input = e50;
  }
  _step() {
    const e50 = ((e51, t2, n2) => {
      if (!e51.length)
        return { cells: [], depths: [] };
      const o3 = e51.map(([e52, n3, o4]) => {
        const i4 = t2[e52], r4 = t2[n3], s3 = t2[o4];
        return i4 && r4 && s3 && TW(i4, r4, s3) < 0 ? [e52, o4, n3] : [e52, n3, o4];
      });
      let i3 = true, r3 = 0;
      for (;i3 && r3++ < 800; ) {
        i3 = false;
        const e52 = new Map, r4 = o3.map(() => new Set);
        for (let t3 = 0;t3 < o3.length; t3++) {
          const n3 = o3[t3];
          if (n3)
            for (let o4 = 0;o4 < n3.length; o4++) {
              const i4 = n3[o4], s4 = n3[(o4 + 1) % n3.length];
              if (i4 === undefined || s4 === undefined)
                continue;
              const a4 = $W(i4, s4);
              if (e52.has(a4)) {
                const n4 = e52.get(a4);
                n4 !== undefined && (r4[t3]?.add(n4), r4[n4]?.add(t3));
              } else
                e52.set(a4, t3);
            }
        }
        let s3 = -1, a3 = -1, c3 = null, l3 = Number.POSITIVE_INFINITY;
        for (let e53 = 0;e53 < o3.length; e53++) {
          const i4 = r4[e53];
          if (i4)
            for (const r5 of i4) {
              if (r5 <= e53)
                continue;
              const i5 = jW(o3[e53] ?? [], o3[r5] ?? []);
              if (!i5)
                continue;
              const h2 = BW(i5, t2);
              h2 <= n2 + 0.000001 && h2 < l3 && (l3 = h2, s3 = e53, a3 = r5, c3 = i5);
            }
        }
        if (s3 < 0 || a3 < 0 || !c3)
          break;
        o3[s3] = c3, o3.splice(a3, 1), i3 = true;
      }
      const s2 = o3.map((e52) => BW(e52, t2));
      return { cells: o3, depths: s2 };
    })(this.input.validTris, this.input.pts, this.input.concavityTolerance);
    this.output = { pts: this.input.pts, validTris: this.input.validTris, cells: e50.cells, depths: e50.depths }, this.stats = { mergedCells: e50.cells.length, maxDepth: e50.depths.length ? Math.max(...e50.depths) : 0 }, this.solved = true;
  }
  getConstructorParams() {
    return [this.input];
  }
  getOutput() {
    return this.output;
  }
  visualize() {
    const e50 = this.output?.cells ?? [];
    return { points: this.input.pts.map((e51) => ({ x: e51.x, y: e51.y, color: "#3b82f6" })), lines: e50.flatMap((e51) => e51.flatMap((t2, n2) => {
      const o3 = this.input.pts[t2], i3 = e51[(n2 + 1) % e51.length], r3 = i3 === undefined ? undefined : this.input.pts[i3];
      return o3 && r3 ? [{ points: [o3, r3], strokeColor: "#10b981" }] : [];
    })), rects: [], circles: [], texts: [{ x: 4, y: 12, text: `merged cells: ${e50.length}`, color: "#1f2937" }] };
  }
};
var XW = (e50, t2, n2) => {
  const o3 = 2 * (e50.x * (t2.y - n2.y) + t2.x * (n2.y - e50.y) + n2.x * (e50.y - t2.y));
  if (Math.abs(o3) < 0.0000000001)
    return { x: 0, y: 0, r2: 1000000000000000000 };
  const i3 = e50.x * e50.x + e50.y * e50.y, r3 = t2.x * t2.x + t2.y * t2.y, s2 = n2.x * n2.x + n2.y * n2.y, a3 = (i3 * (t2.y - n2.y) + r3 * (n2.y - e50.y) + s2 * (e50.y - t2.y)) / o3, c3 = (i3 * (n2.x - t2.x) + r3 * (e50.x - n2.x) + s2 * (t2.x - e50.x)) / o3;
  return { x: a3, y: c3, r2: (e50.x - a3) ** 2 + (e50.y - c3) ** 2 };
};
var HW = (e50, t2, n2) => [e50.a, e50.b, e50.c].includes(t2) && [e50.a, e50.b, e50.c].includes(n2);
var VW = (e50, t2, n2, o3 = [], i3, r3 = []) => e50.filter(([e51, s2, a3]) => {
  const c3 = t2[e51], l3 = t2[s2], h2 = t2[a3];
  if (!c3 || !l3 || !h2)
    return false;
  return ((e52, t3, n3, o4 = [], i4, r4 = []) => {
    const { minX: s3, maxX: a4, minY: c4, maxY: l4 } = n3;
    if (e52 < s3 - 0.1 || e52 > a4 + 0.1 || t3 < c4 - 0.1 || t3 > l4 + 0.1)
      return false;
    for (const n4 of o4) {
      const o5 = n4.diameter / 2 + i4;
      if ((e52 - n4.center.x) ** 2 + (t3 - n4.center.y) ** 2 < o5 * o5 - 0.1)
        return false;
    }
    for (const n4 of r4) {
      const o5 = n4.width / 2 + i4, r5 = n4.height / 2 + i4, s4 = e52 - n4.center.x, a5 = t3 - n4.center.y, c5 = Math.cos(n4.ccwRotation), l5 = Math.sin(n4.ccwRotation), h3 = s4 * c5 + a5 * l5, d2 = -s4 * l5 + a5 * c5;
      if (Math.abs(h3) < o5 - 0.1 && Math.abs(d2) < r5 - 0.1)
        return false;
    }
    return true;
  })((c3.x + l3.x + h2.x) / 3, (c3.y + l3.y + h2.y) / 3, n2, o3, i3, r3);
});
var WW = class extends wW {
  input;
  output = null;
  constructor(e50) {
    super(), this.input = e50;
  }
  _step() {
    const e50 = this.input.vias ?? [], t2 = this.input.rects ?? [], n2 = ((e51) => {
      const t3 = e51.map((e52, t4) => ({ ...e52, i: t4 }));
      if (t3.length < 3)
        return [];
      let { POSITIVE_INFINITY: n3, POSITIVE_INFINITY: o4, NEGATIVE_INFINITY: i3, NEGATIVE_INFINITY: r3 } = Number;
      for (const e52 of t3)
        n3 = Math.min(n3, e52.x), o4 = Math.min(o4, e52.y), i3 = Math.max(i3, e52.x), r3 = Math.max(r3, e52.y);
      const s2 = Math.max(i3 - n3, r3 - o4) || 1, a3 = (n3 + i3) / 2, c3 = (o4 + r3) / 2, l3 = { x: a3 - 30 * s2, y: c3 - s2, i: -1 }, h2 = { x: a3, y: c3 + 30 * s2, i: -2 }, d2 = { x: a3 + 30 * s2, y: c3 - s2, i: -3 };
      let u2 = [{ a: l3, b: h2, c: d2, cc: XW(l3, h2, d2) }];
      for (const e52 of t3) {
        const t4 = u2.filter((t5) => {
          const n5 = e52.x - t5.cc.x, o6 = e52.y - t5.cc.y;
          return n5 * n5 + o6 * o6 < t5.cc.r2 + 0.000001;
        }), n4 = new Set(t4), o5 = [];
        for (const e53 of t4) {
          const n5 = [[e53.a, e53.b], [e53.b, e53.c], [e53.c, e53.a]];
          for (const [i4, r4] of n5) {
            let n6 = false;
            for (const o6 of t4)
              if (o6 !== e53 && HW(o6, i4, r4)) {
                n6 = true;
                break;
              }
            n6 || o5.push([i4, r4]);
          }
        }
        u2 = u2.filter((e53) => !n4.has(e53));
        for (const [t5, n5] of o5)
          u2.push({ a: t5, b: n5, c: e52, cc: XW(t5, n5, e52) });
      }
      return u2.filter((e52) => e52.a.i >= 0 && e52.b.i >= 0 && e52.c.i >= 0).map((e52) => [e52.a.i, e52.b.i, e52.c.i]);
    })(this.input.pts), o3 = VW(n2, this.input.pts, this.input.bounds, e50, this.input.clearance, t2);
    this.output = { pts: this.input.pts, validTris: o3 }, this.stats = { candidateTriangles: n2.length, validTriangles: o3.length }, this.solved = true;
  }
  getConstructorParams() {
    return [this.input];
  }
  getOutput() {
    return this.output;
  }
  visualize() {
    const e50 = this.output?.validTris ?? [];
    return { points: this.input.pts.map((e51) => ({ x: e51.x, y: e51.y, color: "#2563eb" })), lines: e50.flatMap(([e51, t2, n2]) => {
      const o3 = this.input.pts[e51], i3 = this.input.pts[t2], r3 = this.input.pts[n2];
      return o3 && i3 && r3 ? [{ points: [o3, i3], strokeColor: "#64748b" }, { points: [i3, r3], strokeColor: "#64748b" }, { points: [r3, o3], strokeColor: "#64748b" }] : [];
    }), rects: [], circles: [], texts: [{ x: this.input.bounds.minX + 6, y: this.input.bounds.minY + 12, text: `valid triangles: ${e50.length}`, color: "#1f2937" }] };
  }
};
var GW = class extends RW {
  pipelineDef = [NW("generatePoints", LW, (e50) => [e50.inputProblem]), NW("triangulate", WW, (e50) => {
    const t2 = e50.getStageOutput("generatePoints");
    if (!t2)
      throw new Error("generatePoints output missing");
    return [{ pts: t2.pts, bounds: e50.inputProblem.bounds, vias: e50.inputProblem.vias, rects: e50.inputProblem.rects, clearance: e50.inputProblem.clearance }];
  }), NW("mergeCells", YW, (e50) => {
    const t2 = e50.getStageOutput("triangulate");
    if (!t2)
      throw new Error("triangulate output missing");
    return [{ pts: t2.pts, validTris: t2.validTris, concavityTolerance: e50.inputProblem.concavityTolerance }];
  }), NW("buildRegions", OW, (e50) => {
    const t2 = e50.getStageOutput("mergeCells");
    if (!t2)
      throw new Error("mergeCells output missing");
    return [t2];
  })];
  getConstructorParams() {
    return [this.inputProblem];
  }
  getOutput() {
    return this.getStageOutput("buildRegions") ?? null;
  }
  visualize() {
    const e50 = this.getOutput();
    return e50 ? { points: e50.pts.map((e51) => ({ x: e51.x, y: e51.y, color: "#38b6ff" })), lines: e50.regions.flatMap((e51) => e51.map((t2, n2) => {
      const o3 = e51[(n2 + 1) % e51.length] ?? t2;
      return { points: [{ x: t2.x, y: t2.y }, { x: o3.x, y: o3.y }], strokeColor: "#4ecb82" };
    })), rects: [], circles: (this.inputProblem.vias ?? []).map((e51) => ({ center: { x: e51.center.x, y: e51.center.y }, radius: e51.diameter / 2, stroke: "#ff6b6b" })), texts: [{ x: this.inputProblem.bounds.minX + 8, y: this.inputProblem.bounds.minY + 16, text: `regions=${e50.regions.length}`, color: "#ffffff" }] } : { points: [], lines: [], rects: [], circles: [], texts: [] };
  }
};
var UW = 0.000000001;
var ZW = (e50, t2) => {
  const n2 = [hG(e50)], o3 = [];
  let i3 = t2.maxSplitsPerRegion ?? 32;
  for (;n2.length > 0; ) {
    const e51 = n2.pop();
    if (!e51)
      continue;
    if (e51.length < 4) {
      o3.push(e51);
      continue;
    }
    const r3 = qW(e51, t2);
    if (!r3 || i3 <= 0) {
      o3.push(e51);
      continue;
    }
    const [s2, a3] = QW(e51, r3.i, r3.j);
    i3 -= 1, n2.push(s2, a3);
  }
  return o3;
};
var qW = (e50, t2) => {
  const n2 = eG(e50);
  if (!n2)
    return null;
  const { triangles: o3 } = n2, i3 = sG(e50);
  if (i3 <= UW)
    return null;
  const r3 = Math.sqrt(i3), s2 = o3.map((t3) => aG(e50[t3[0]], e50[t3[1]], e50[t3[2]]));
  let a3 = null;
  for (const c3 of n2.internalEdges) {
    const { i: l3, j: h2, triA: d2, triB: u2 } = c3, p3 = cG(e50[l3], e50[h2]) / r3;
    if (p3 > t2.maxNeckRatio)
      continue;
    const m2 = JW(d2, u2, o3.length, n2.triangleAdjacency, s2), g2 = i3 - m2, f2 = Math.min(m2, g2) / i3;
    if (f2 < t2.minSplitBalanceRatio)
      continue;
    const _2 = p3 / Math.max(f2, UW);
    (!a3 || _2 < a3.score) && (a3 = { i: l3, j: h2, score: _2 });
  }
  return a3 ? { i: a3.i, j: a3.j } : null;
};
var JW = (e50, t2, n2, o3, i3) => {
  const r3 = new Array(n2).fill(false), s2 = [e50];
  r3[t2] = true;
  let a3 = 0;
  for (;s2.length > 0; ) {
    const e51 = s2.pop();
    if (e51 === undefined || r3[e51])
      continue;
    r3[e51] = true, a3 += i3[e51] ?? 0;
    const t3 = o3[e51] ?? [];
    for (const e52 of t3)
      r3[e52] || s2.push(e52);
  }
  return a3;
};
var QW = (e50, t2, n2) => [KW(e50, t2, n2), KW(e50, n2, t2)];
var KW = (e50, t2, n2) => {
  const o3 = [], i3 = e50.length;
  let r3 = t2;
  for (o3.push(e50[r3]);r3 !== n2; )
    r3 = (r3 + 1) % i3, o3.push(e50[r3]);
  return hG(o3);
};
var eG = (e50) => {
  const t2 = e50.length;
  if (t2 < 3)
    return null;
  const n2 = new Set;
  for (let e51 = 0;e51 < t2; e51++) {
    const o4 = (e51 + 1) % t2;
    n2.add(lG(e51, o4));
  }
  const o3 = tG(e50);
  if (!o3 || o3.length === 0)
    return null;
  const i3 = new Map;
  o3.forEach((e51, t3) => {
    for (let n3 = 0;n3 < 3; n3++) {
      const o4 = e51[n3], r4 = e51[(n3 + 1) % 3], s3 = lG(o4, r4), a3 = i3.get(s3);
      a3 ? a3.push(t3) : i3.set(s3, [t3]);
    }
  });
  const r3 = Array.from({ length: o3.length }, () => []), s2 = [];
  for (const [e51, t3] of i3.entries()) {
    if (n2.has(e51))
      continue;
    if (t3.length !== 2)
      continue;
    const [o4, i4] = e51.split("_"), a3 = Number(o4), c3 = Number(i4), l3 = t3[0], h2 = t3[1];
    s2.push({ i: a3, j: c3, triA: l3, triB: h2 });
    const d2 = r3[l3], u2 = r3[h2];
    d2 && d2.push(h2), u2 && u2.push(l3);
  }
  return { triangles: o3, internalEdges: s2, triangleAdjacency: r3 };
};
var tG = (e50) => {
  const t2 = e50.length;
  if (t2 < 3)
    return null;
  const n2 = Math.sign(rG(e50));
  if (n2 === 0)
    return null;
  const o3 = [...Array(t2).keys()];
  n2 < 0 && o3.reverse();
  const i3 = [];
  let r3 = 0;
  for (;o3.length > 3 && r3 < t2 * t2; ) {
    let t3 = false;
    for (let n3 = 0;n3 < o3.length; n3++) {
      const r4 = o3[(n3 - 1 + o3.length) % o3.length], s2 = o3[n3], a3 = o3[(n3 + 1) % o3.length];
      if (r4 === undefined || s2 === undefined || a3 === undefined)
        continue;
      const c3 = e50[r4], l3 = e50[s2], h2 = e50[a3];
      if (!c3 || !l3 || !h2)
        continue;
      if (!nG(c3, l3, h2))
        continue;
      let d2 = false;
      for (const t4 of o3) {
        if (t4 === r4 || t4 === s2 || t4 === a3)
          continue;
        const n4 = e50[t4];
        if (n4 && oG(n4, c3, l3, h2)) {
          d2 = true;
          break;
        }
      }
      if (!d2) {
        i3.push([r4, s2, a3]), o3.splice(n3, 1), t3 = true;
        break;
      }
    }
    if (!t3)
      return null;
    r3 += 1;
  }
  if (o3.length === 3) {
    const [e51, t3, n3] = o3;
    e51 !== undefined && t3 !== undefined && n3 !== undefined && i3.push([e51, t3, n3]);
  }
  return i3;
};
var nG = (e50, t2, n2) => iG(e50, t2, n2) > UW;
var oG = (e50, t2, n2, o3) => {
  const i3 = iG(t2, n2, e50), r3 = iG(n2, o3, e50), s2 = iG(o3, t2, e50);
  return i3 >= -0.000000001 && r3 >= -0.000000001 && s2 >= -0.000000001;
};
var iG = (e50, t2, n2) => (t2.x - e50.x) * (n2.y - e50.y) - (t2.y - e50.y) * (n2.x - e50.x);
var rG = (e50) => {
  let t2 = 0;
  for (let n2 = 0;n2 < e50.length; n2++) {
    const o3 = e50[n2], i3 = e50[(n2 + 1) % e50.length];
    o3 && i3 && (t2 += o3.x * i3.y - i3.x * o3.y);
  }
  return t2 / 2;
};
var sG = (e50) => Math.abs(rG(e50));
var aG = (e50, t2, n2) => Math.abs(iG(e50, t2, n2)) / 2;
var cG = (e50, t2) => Math.hypot(e50.x - t2.x, e50.y - t2.y);
var lG = (e50, t2) => e50 < t2 ? `${e50}_${t2}` : `${t2}_${e50}`;
var hG = (e50) => {
  if (e50.length < 2)
    return e50;
  const t2 = e50[0], n2 = e50[e50.length - 1];
  return t2 && n2 && t2.x === n2.x && t2.y === n2.y ? e50.slice(0, -1) : e50;
};
var dG = { pattern: "grid", pitchX: 2.2, pitchY: 1.8, staggerAxis: "x", staggerOffset: 1.1, staggerOffsetX: 1.1, padWidth: 0.9, padHeight: 1, padGap: 0.35, viaDiameter: 0.3, clearance: 0.2, concavityTolerance: 0.3, boundsPadding: 1.2, orientation: "horizontal", portSpacing: 0.25, maxNeckRatio: 0, minSplitBalanceRatio: 0.2 };
var uG = (e50, t2) => {
  let { POSITIVE_INFINITY: n2, POSITIVE_INFINITY: o3, NEGATIVE_INFINITY: i3, NEGATIVE_INFINITY: r3 } = Number;
  for (const s2 of e50)
    for (const e51 of s2.padCenters) {
      const s3 = t2.orientation === "horizontal" ? t2.padWidth / 2 : t2.padHeight / 2, a3 = t2.orientation === "horizontal" ? t2.padHeight / 2 : t2.padWidth / 2;
      e51.x - s3 < n2 && (n2 = e51.x - s3), e51.y - a3 < o3 && (o3 = e51.y - a3), e51.x + s3 > i3 && (i3 = e51.x + s3), e51.y + a3 > r3 && (r3 = e51.y + a3);
    }
  return { minX: n2 - t2.boundsPadding, minY: o3 - t2.boundsPadding, maxX: i3 + t2.boundsPadding, maxY: r3 + t2.boundsPadding };
};
var pG = (e50) => e50.pattern === "staggered" ? ((e51) => {
  const t2 = [], n2 = [], o3 = e51.padGap / 2 + e51.padWidth / 2, i3 = -(e51.cols - 1) * e51.pitchX / 2, r3 = -(e51.rows - 1) * e51.pitchY / 2;
  for (let s2 = 0;s2 < e51.rows; s2++) {
    const a3 = e51.staggerAxis === "x" && s2 % 2 == 1 ? e51.staggerOffset : 0;
    for (let c3 = 0;c3 < e51.cols; c3++) {
      const l3 = e51.staggerAxis === "y" && c3 % 2 == 1 ? e51.staggerOffset : 0, h2 = { x: i3 + c3 * e51.pitchX + a3, y: r3 + s2 * e51.pitchY + l3 }, d2 = e51.orientation === "horizontal" ? { x: h2.x - o3, y: h2.y } : { x: h2.x, y: h2.y - o3 }, u2 = e51.orientation === "horizontal" ? { x: h2.x + o3, y: h2.y } : { x: h2.x, y: h2.y + o3 };
      t2.push({ jumperId: `jumper_r${s2}_c${c3}`, center: h2, orientation: e51.orientation, padCenters: [d2, u2] }), n2.push({ center: d2, diameter: e51.viaDiameter }, { center: u2, diameter: e51.viaDiameter });
    }
  }
  return { jumpers: t2, vias: n2, bounds: uG(t2, e51) };
})(e50) : ((e51) => {
  const t2 = [], n2 = [], o3 = e51.padGap / 2 + e51.padWidth / 2, i3 = -(e51.cols - 1) * e51.pitchX / 2, r3 = -(e51.rows - 1) * e51.pitchY / 2;
  for (let s2 = 0;s2 < e51.rows; s2++)
    for (let a3 = 0;a3 < e51.cols; a3++) {
      const c3 = { x: i3 + a3 * e51.pitchX, y: r3 + s2 * e51.pitchY }, l3 = e51.orientation === "horizontal" ? { x: c3.x - o3, y: c3.y } : { x: c3.x, y: c3.y - o3 }, h2 = e51.orientation === "horizontal" ? { x: c3.x + o3, y: c3.y } : { x: c3.x, y: c3.y + o3 }, d2 = `jumper_r${s2}_c${a3}`;
      t2.push({ jumperId: d2, center: c3, orientation: e51.orientation, padCenters: [l3, h2] }), n2.push({ center: l3, diameter: e51.viaDiameter }, { center: h2, diameter: e51.viaDiameter });
    }
  return { jumpers: t2, vias: n2, bounds: { minX: i3 - o3 - e51.padWidth / 2 - e51.boundsPadding, maxX: i3 + (e51.cols - 1) * e51.pitchX + o3 + e51.padWidth / 2 + e51.boundsPadding, minY: r3 - o3 - e51.padHeight / 2 - e51.boundsPadding, maxY: r3 + (e51.rows - 1) * e51.pitchY + o3 + e51.padHeight / 2 + e51.boundsPadding } };
})(e50);
var mG = (e50) => ({ x: (e50.minX + e50.maxX) / 2, y: (e50.minY + e50.maxY) / 2 });
var gG = (e50) => [{ x: e50.minX, y: e50.minY }, { x: e50.maxX, y: e50.minY }, { x: e50.maxX, y: e50.maxY }, { x: e50.minX, y: e50.maxY }];
var fG = (e50, t2, n2) => Math.abs(e50 - t2) <= n2;
var _G = (e50, t2, n2) => fG(e50.x, t2.x, n2) && fG(e50.y, t2.y, n2);
var yG = (e50) => e50.map((e51, t2) => {
  const n2 = ((e52) => {
    let { POSITIVE_INFINITY: t3, POSITIVE_INFINITY: n3, NEGATIVE_INFINITY: o3, NEGATIVE_INFINITY: i3 } = Number;
    for (const r3 of e52)
      r3.x < t3 && (t3 = r3.x), r3.y < n3 && (n3 = r3.y), r3.x > o3 && (o3 = r3.x), r3.y > i3 && (i3 = r3.y);
    return { minX: t3, minY: n3, maxX: o3, maxY: i3 };
  })(e51);
  return { regionId: `top_${t2}`, ports: [], d: { bounds: n2, center: mG(n2), polygon: e51, isPad: false } };
});
var bG = (e50) => {
  const t2 = e50.end.x - e50.start.x, n2 = e50.end.y - e50.start.y;
  return Math.hypot(t2, n2);
};
var xG = (e50, t2) => ({ x: e50.start.x + (e50.end.x - e50.start.x) * t2, y: e50.start.y + (e50.end.y - e50.start.y) * t2 });
var vG = (e50, t2, n2) => {
  const o3 = [];
  if (!e50.d.polygon || !t2.d.polygon)
    return o3;
  for (let i3 = 0;i3 < e50.d.polygon.length; i3++) {
    const r3 = e50.d.polygon[i3], s2 = e50.d.polygon[(i3 + 1) % e50.d.polygon.length];
    if (r3 && s2)
      for (let e51 = 0;e51 < t2.d.polygon.length; e51++) {
        const i4 = t2.d.polygon[e51], a3 = t2.d.polygon[(e51 + 1) % t2.d.polygon.length];
        if (!i4 || !a3)
          continue;
        const c3 = PG({ start: r3, end: s2 }, { start: i4, end: a3 }, n2);
        if (!c3)
          continue;
        o3.some((e52) => CG(e52, c3, n2)) || o3.push(c3);
      }
  }
  return o3;
};
var IG = (e50, t2) => {
  const n2 = [];
  for (const o3 of e50) {
    let e51 = o3, i3 = true;
    for (;i3; ) {
      i3 = false;
      for (let o4 = 0;o4 < n2.length; o4++) {
        const r3 = n2[o4];
        if (!r3)
          continue;
        const s2 = SG(e51, r3, t2);
        if (s2) {
          e51 = s2, n2.splice(o4, 1), i3 = true;
          break;
        }
      }
    }
    n2.push(e51);
  }
  return n2;
};
var SG = (e50, t2, n2) => {
  const o3 = e50.end.x - e50.start.x, i3 = e50.end.y - e50.start.y, r3 = t2.end.x - t2.start.x, s2 = t2.end.y - t2.start.y, a3 = o3 ** 2 + i3 ** 2;
  if (a3 <= n2 ** 2)
    return null;
  if (!fG(o3 * s2 - i3 * r3, 0, n2))
    return null;
  const c3 = t2.start.x - e50.start.x, l3 = t2.start.y - e50.start.y, h2 = t2.end.x - e50.start.x, d2 = t2.end.y - e50.start.y, u2 = o3 * d2 - i3 * h2;
  if (!fG(o3 * l3 - i3 * c3, 0, n2) || !fG(u2, 0, n2))
    return null;
  const p3 = (c3 * o3 + l3 * i3) / a3, m2 = (h2 * o3 + d2 * i3) / a3, g2 = Math.min(p3, m2), f2 = Math.max(p3, m2), _2 = n2 / Math.sqrt(a3);
  if (g2 > 1 + _2 || f2 < 0 - _2)
    return null;
  const y2 = Math.min(0, g2), b2 = Math.max(1, f2);
  return { start: xG(e50, y2), end: xG(e50, b2) };
};
var CG = (e50, t2, n2) => _G(e50.start, t2.start, n2) && _G(e50.end, t2.end, n2) || _G(e50.start, t2.end, n2) && _G(e50.end, t2.start, n2);
var PG = (e50, t2, n2) => {
  const o3 = e50.end.x - e50.start.x, i3 = e50.end.y - e50.start.y, r3 = t2.end.x - t2.start.x, s2 = t2.end.y - t2.start.y, a3 = o3 ** 2 + i3 ** 2;
  if (a3 <= n2 ** 2)
    return null;
  if (!fG(o3 * s2 - i3 * r3, 0, n2))
    return null;
  const c3 = t2.start.x - e50.start.x, l3 = t2.start.y - e50.start.y, h2 = t2.end.x - e50.start.x, d2 = t2.end.y - e50.start.y, u2 = o3 * d2 - i3 * h2;
  if (!fG(o3 * l3 - i3 * c3, 0, n2) || !fG(u2, 0, n2))
    return null;
  const p3 = (c3 * o3 + l3 * i3) / a3, m2 = (h2 * o3 + d2 * i3) / a3, g2 = Math.max(0, Math.min(p3, m2)), f2 = Math.min(1, Math.max(p3, m2));
  return f2 - g2 <= n2 / Math.sqrt(a3) ? null : { start: xG(e50, g2), end: xG(e50, f2) };
};
var MG = (e50, t2, n2) => {
  const o3 = Math.max(e50.minX, t2.minX), i3 = Math.min(e50.maxX, t2.maxX), r3 = Math.max(e50.minY, t2.minY), s2 = Math.min(e50.maxY, t2.maxY);
  return i3 < o3 - n2 || s2 < r3 - n2 ? null : { minX: o3, maxX: i3, minY: r3, maxY: s2 };
};
var wG = (e50) => {
  const t2 = ((e51) => {
    const t3 = e51.orientation ?? dG.orientation, n3 = e51.staggerAxis ?? dG.staggerAxis, o4 = e51.padWidth ?? dG.padWidth, i4 = e51.padHeight ?? dG.padHeight, r4 = e51.padGap ?? dG.padGap, s3 = e51.clearance ?? dG.clearance, a4 = e51.colSpacing ?? e51.pitchX ?? dG.pitchX, c4 = e51.rowSpacing ?? e51.pitchY ?? dG.pitchY, l4 = (h3 = o4, d3 = i4, u3 = r4, t3 === "horizontal" ? { x: u3 + 2 * h3, y: d3 } : { x: d3, y: u3 + 2 * h3 });
    var h3, d3, u3;
    const p4 = s3, m2 = ((e52, t4, n4, o5, i5) => e52 === "horizontal" ? t4 === "x" ? i5 + 2 * n4 : o5 : t4 === "x" ? o5 : i5 + 2 * n4)(t3, n3, o4, i4, r4) / 2, g2 = e51.staggerOffset ?? e51.staggerOffsetX ?? m2, f2 = { ...dG, ...e51, orientation: t3, staggerAxis: n3, pitchX: Math.max(a4, l4.x + p4), pitchY: Math.max(c4, l4.y + p4), padWidth: o4, padHeight: i4, padGap: r4, staggerOffset: g2, staggerOffsetX: g2, concavityTolerance: e51.concavityTolerance ?? dG.concavityTolerance, clearance: s3, portSpacing: e51.portSpacing ?? dG.portSpacing, maxNeckRatio: e51.maxNeckRatio ?? dG.maxNeckRatio, minSplitBalanceRatio: e51.minSplitBalanceRatio ?? dG.minSplitBalanceRatio };
    if (f2.cols <= 0 || f2.rows <= 0)
      throw new Error("rows and cols must be > 0");
    if (!Number.isFinite(f2.portSpacing) || f2.portSpacing <= 0)
      throw new Error("portSpacing must be > 0");
    if (!Number.isFinite(f2.maxNeckRatio) || f2.maxNeckRatio < 0)
      throw new Error("maxNeckRatio must be >= 0");
    if (!Number.isFinite(f2.minSplitBalanceRatio) || f2.minSplitBalanceRatio < 0 || f2.minSplitBalanceRatio > 0.5)
      throw new Error("minSplitBalanceRatio must be between 0 and 0.5");
    return f2;
  })(e50), n2 = pG(t2), o3 = t2.orientation === "horizontal" ? t2.padWidth : t2.padHeight, i3 = t2.orientation === "horizontal" ? t2.padHeight : t2.padWidth, r3 = n2.jumpers.flatMap((e51) => e51.padCenters.map((e52) => ({ center: e52, width: o3, height: i3, ccwRotation: 0 }))), s2 = new GW({ bounds: n2.bounds, rects: r3, clearance: 0, concavityTolerance: t2.concavityTolerance });
  s2.solve();
  const a3 = s2.getOutput();
  if (!a3)
    throw new Error(s2.error ?? "ConvexRegionsSolver failed");
  const c3 = ((e51, t3) => {
    if (t3.maxNeckRatio <= 0)
      return e51;
    const n3 = [];
    for (const o4 of e51)
      n3.push(...ZW(o4, t3));
    return n3;
  })(a3.regions, { maxNeckRatio: t2.maxNeckRatio, minSplitBalanceRatio: t2.minSplitBalanceRatio }), l3 = yG(c3), h2 = ((e51, t3) => e51.flatMap((e52) => {
    const [n3, o4] = e52.padCenters, i4 = t3.orientation === "horizontal" ? t3.padWidth / 2 : t3.padHeight / 2, r4 = t3.orientation === "horizontal" ? t3.padHeight / 2 : t3.padWidth / 2, s3 = { minX: n3.x - i4, maxX: n3.x + i4, minY: n3.y - r4, maxY: n3.y + r4 }, a4 = { minX: o4.x - i4, maxX: o4.x + i4, minY: o4.y - r4, maxY: o4.y + r4 }, c4 = i4 / 2, l4 = r4 / 2, h3 = t3.orientation === "horizontal" ? { minX: Math.min(n3.x, o4.x), maxX: Math.max(n3.x, o4.x), minY: e52.center.y - l4, maxY: e52.center.y + l4 } : { minX: e52.center.x - c4, maxX: e52.center.x + c4, minY: Math.min(n3.y, o4.y), maxY: Math.max(n3.y, o4.y) };
    return [{ regionId: `${e52.jumperId}_pad1`, ports: [], d: { bounds: s3, center: n3, polygon: gG(s3), isPad: true, isThroughJumper: false } }, { regionId: `${e52.jumperId}_bridge`, ports: [], d: { bounds: h3, center: e52.center, polygon: gG(h3), isPad: false, isThroughJumper: true } }, { regionId: `${e52.jumperId}_pad2`, ports: [], d: { bounds: a4, center: o4, polygon: gG(a4), isPad: true, isThroughJumper: false } }];
  }))(n2.jumpers, { orientation: t2.orientation, padWidth: t2.padWidth, padHeight: t2.padHeight }), d2 = ((e51, t3, n3 = 0.00001) => {
    const o4 = [];
    let i4 = 0;
    for (let r4 = 0;r4 < e51.length; r4++) {
      const s3 = e51[r4];
      if (s3?.d.polygon)
        for (let a4 = r4 + 1;a4 < e51.length; a4++) {
          const r5 = e51[a4];
          if (!r5?.d.polygon)
            continue;
          const c4 = vG(s3, r5, n3);
          for (const e52 of c4) {
            const n4 = bG(e52), a5 = Math.floor(n4 / t3), c5 = Math.max(1, a5 - 1);
            for (let t4 = 0;t4 < c5; t4++) {
              const n5 = xG(e52, (t4 + 1) / (c5 + 1));
              o4.push({ portId: "tp_" + i4++, region1: s3, region2: r5, d: { x: n5.x, y: n5.y } });
            }
          }
        }
    }
    return o4;
  })(l3, t2.portSpacing), u2 = ((e51, t3, n3 = 0.00001) => {
    const o4 = [];
    let i4 = 0, r4 = 0;
    const s3 = e51.filter((e52) => e52.d.isPad), a4 = e51.filter((e52) => e52.d.isThroughJumper && !e52.d.isPad);
    for (const e52 of s3)
      for (const r5 of t3) {
        const t4 = vG(e52, r5, n3), s4 = IG(t4, n3);
        for (const t5 of s4) {
          const n4 = xG(t5, 0.5);
          o4.push({ portId: "jp_" + i4++, region1: e52, region2: r5, d: { x: n4.x, y: n4.y } });
        }
      }
    for (const e52 of a4)
      for (const t4 of s3) {
        const i5 = MG(e52.d.bounds, t4.d.bounds, n3);
        if (!i5)
          continue;
        const s4 = mG(i5);
        o4.push({ portId: "jip_" + r4++, region1: t4, region2: e52, d: { x: s4.x, y: s4.y } });
      }
    return o4;
  })(h2, l3), p3 = [...d2, ...u2];
  return ((e51) => {
    for (const t3 of e51)
      t3.region1.ports.push(t3), t3.region2.ports.push(t3);
  })(p3), { regions: [...l3, ...h2], ports: p3, jumperLocations: n2.jumpers.map((e51, t3) => ({ center: e51.center, orientation: e51.orientation, padRegions: [h2[3 * t3], h2[3 * t3 + 2]].filter((e52) => Boolean(e52)) })), topLayerRegions: l3, jumperRegions: h2, jumpers: n2.jumpers, vias: n2.vias, bounds: n2.bounds };
};
var NG = class extends ni {
  getSolverName() {
    return "JumperPrepatternSolver2_HyperGraph";
  }
  constructorParams;
  nodeWithPortPoints;
  colorMap;
  traceWidth;
  obstacleMargin;
  hyperParameters;
  jumperGraphSolver = null;
  xyConnections = [];
  graphBounds = null;
  jumperLocations = [];
  solvedRoutes = [];
  jumpers = [];
  phase = "jumperGraph";
  curvySolvers = [];
  currentCurvySolverIndex = 0;
  routeInfos = [];
  regionCurvedPaths = new Map;
  constructor(e50) {
    super(), this.constructorParams = e50, this.nodeWithPortPoints = e50.nodeWithPortPoints, this.colorMap = e50.colorMap ?? {}, this.traceWidth = e50.traceWidth ?? 0.15, this.obstacleMargin = e50.obstacleMargin ?? 0.15, this.hyperParameters = e50.hyperParameters ?? {}, this.MAX_ITERATIONS = 1e6, Object.keys(this.colorMap).length === 0 && (this.colorMap = this._buildColorMap());
  }
  getConstructorParams() {
    return this.constructorParams;
  }
  _buildColorMap() {
    const e50 = ["#e6194b", "#3cb44b", "#ffe119", "#4363d8", "#f58231", "#911eb4", "#46f0f0", "#f032e6", "#bcf60c", "#fabebe"], t2 = {}, n2 = new Set;
    for (const e51 of this.nodeWithPortPoints.portPoints)
      n2.add(e51.connectionName);
    let o3 = 0;
    for (const i3 of Array.from(n2))
      t2[i3] = e50[o3 % e50.length], o3++;
    return t2;
  }
  _normalizeRegionPolygonsToBounds(e50) {
    for (const t2 of e50.regions) {
      const e51 = t2.d, n2 = e51?.polygon, o3 = e51?.bounds;
      if (!n2 || n2.length === 0 || !o3)
        continue;
      let i3 = 1 / 0, r3 = 1 / 0;
      for (const e52 of n2)
        i3 = Math.min(i3, e52.x), r3 = Math.min(r3, e52.y);
      const s2 = o3.minX - i3, a3 = o3.minY - r3;
      (Math.abs(s2) > 0.000000000001 || Math.abs(a3) > 0.000000000001) && (e51.polygon = n2.map((e52) => ({ x: e52.x + s2, y: e52.y + a3 }))), e51.polygonPerimeterCache && (e51.polygonPerimeterCache = undefined);
    }
    return e50;
  }
  _getPatternConfig() {
    return { cols: this.hyperParameters.COLS ?? 1, rows: this.hyperParameters.ROWS ?? 1 };
  }
  _generate0603Grid(e50, t2, n2, o3) {
    const i3 = t2 === "horizontal" ? e50.rows : e50.cols, r3 = t2 === "horizontal" ? e50.cols : e50.rows, s2 = o3.maxX - o3.minX, a3 = o3.maxY - o3.minY, c3 = 0.35, l3 = this.hyperParameters.TRACE_CHANNELS_BETWEEN_JUMPERS ?? 1, h2 = this.traceWidth * l3 + 2 * this.obstacleMargin, d2 = t2 === "horizontal" ? 2.15 : 1, u2 = t2 === "horizontal" ? 1 : 2.15, p3 = t2 === "horizontal" ? "x" : "y", m2 = n2 === "staggered", g2 = m2 && p3 === "x" ? d2 / 2 : m2 ? u2 / 2 : 0, f2 = Math.max(0, s2 - 1), _2 = Math.max(0, a3 - 1), y2 = Math.max(0, f2 - (m2 && p3 === "x" ? g2 : 0)), b2 = Math.max(0, _2 - (m2 && p3 === "y" ? g2 : 0)), x2 = i3 > 1 ? Math.max(d2 + h2, (y2 - d2) / (i3 - 1)) : d2, v2 = r3 > 1 ? Math.max(u2 + h2, (b2 - u2) / (r3 - 1)) : u2, I2 = wG({ cols: i3, rows: r3, orientation: t2, pattern: n2, staggerAxis: p3, colSpacing: x2, rowSpacing: v2, padWidth: 0.9, padHeight: 1, padGap: c3, clearance: h2, boundsPadding: 0, maxNeckRatio: 0.4, minSplitBalanceRatio: 0.2 }), S2 = I2.bounds, C = (S2.minX + S2.maxX) / 2, P = (S2.minY + S2.maxY) / 2, M = Gt((o3.minX + o3.maxX) / 2 - C, (o3.minY + o3.maxY) / 2 - P);
    return this._normalizeRegionPolygonsToBounds(dX(I2, M));
  }
  _initializeGraph() {
    const e50 = this.nodeWithPortPoints, t2 = this._getPatternConfig(), n2 = this.hyperParameters.ORIENTATION ?? "vertical", o3 = this.hyperParameters.JUMPER_TYPE ?? "1206x4", i3 = this.hyperParameters.PATTERN ?? "grid", r3 = { minX: e50.center.x - e50.width / 2, maxX: e50.center.x + e50.width / 2, minY: e50.center.y - e50.height / 2, maxY: e50.center.y + e50.height / 2 };
    let s2;
    if (this.graphBounds = r3, o3 === "0603") {
      const e51 = this._generate0603Grid(t2, n2, i3, r3);
      if (!e51)
        return this.error = `0603 grid (${t2.cols}x${t2.rows}) is too large to fit in node bounds`, this.failed = true, false;
      s2 = e51;
    } else
      s2 = IX({ cols: t2.cols, rows: t2.rows, marginX: Math.max(1.2, 0.3 * t2.cols), marginY: Math.max(1.2, 0.3 * t2.rows), outerPaddingX: 0.4, outerPaddingY: 0.4, parallelTracesUnderJumperCount: 2, innerColChannelPointCount: 3, innerRowChannelPointCount: 3, outerChannelXPointCount: 3, outerChannelYPointCount: 3, regionsBetweenPads: true, orientation: n2, bounds: r3 });
    if (s2.regions.length > 0) {
      let e51 = 1 / 0, t3 = -1 / 0, n3 = 1 / 0, i4 = -1 / 0;
      for (const o4 of s2.regions) {
        if (!o4.d?.isPad)
          continue;
        const r4 = o4.d?.bounds;
        r4 && (e51 = Math.min(e51, r4.minX), t3 = Math.max(t3, r4.maxX), n3 = Math.min(n3, r4.minY), i4 = Math.max(i4, r4.maxY));
      }
      const a4 = o3 === "0603" ? 0.5 : 1;
      if (e51 - a4 < r3.minX || t3 + a4 > r3.maxX || n3 - a4 < r3.minY || i4 + a4 > r3.maxY)
        return this.error = `baseGraph bounds (${e51.toFixed(2)}, ${n3.toFixed(2)}, ${t3.toFixed(2)}, ${i4.toFixed(2)}) exceed node bounds (${r3.minX.toFixed(2)}, ${r3.minY.toFixed(2)}, ${r3.maxX.toFixed(2)}, ${r3.maxY.toFixed(2)})`, this.failed = true, false;
    }
    this.jumperLocations = s2.jumperLocations?.map((e51) => ({ center: e51.center, orientation: e51.orientation, padRegions: e51.padRegions })) ?? [];
    const a3 = new Map;
    for (const t3 of e50.portPoints) {
      const e51 = a3.get(t3.connectionName);
      e51 ? e51.points.push(t3) : a3.set(t3.connectionName, { points: [t3], rootConnectionName: t3.rootConnectionName });
    }
    this.xyConnections = [];
    for (const [e51, t3] of Array.from(a3.entries()))
      t3.points.length < 2 || this.xyConnections.push({ start: { x: t3.points[0].x, y: t3.points[0].y }, end: { x: t3.points[1].x, y: t3.points[1].y }, connectionId: e51 });
    if (this.xyConnections.length === 0)
      return this.solved = true, true;
    const c3 = ((e51, t3) => {
      const n3 = [...e51.regions], o4 = [...e51.ports], i4 = [], r4 = WY(e51.regions);
      for (const s3 of t3) {
        const { start: t4, end: a4, connectionId: c4 } = s3, l3 = UY(`conn:${c4}:start`, t4.x, t4.y);
        n3.push(l3);
        const h2 = UY(`conn:${c4}:end`, a4.x, a4.y);
        n3.push(h2);
        const d2 = eX(t4.x, t4.y, e51.regions, r4);
        if (d2) {
          const e52 = GY(`conn:${c4}:start-port`, l3, d2.region, d2.portPosition);
          o4.push(e52);
        }
        const u2 = eX(a4.x, a4.y, e51.regions, r4);
        if (u2) {
          const e52 = GY(`conn:${c4}:end-port`, h2, u2.region, u2.portPosition);
          o4.push(e52);
        }
        const p3 = { connectionId: c4, mutuallyConnectedNetworkId: c4, startRegion: l3, endRegion: h2 };
        i4.push(p3);
      }
      return { regions: n3, ports: o4, connections: i4 };
    })(s2, this.xyConnections);
    return this.jumperGraphSolver = new xX({ inputGraph: { regions: c3.regions, ports: c3.ports }, inputConnections: c3.connections }), this.jumperGraphSolver.MAX_ITERATIONS *= 3, true;
  }
  _step() {
    switch (this.phase) {
      case "jumperGraph":
        this._stepJumperGraph();
        break;
      case "curvyTrace":
        this._stepCurvyTrace();
        break;
      case "done":
        this.solved = true;
    }
  }
  _stepJumperGraph() {
    if (!this.jumperGraphSolver) {
      if (this._initializeGraph(), this.solved)
        return;
      if (!this.jumperGraphSolver)
        return void (this.failed = true);
    }
    this.activeSubSolver = this.jumperGraphSolver, this.jumperGraphSolver.step(), this.jumperGraphSolver.solved ? (this._initializeCurvyTraceSolvers(), this.curvySolvers.length > 0 ? this.phase = "curvyTrace" : (this._finalizeCurvyTraceResults(), this.phase = "done", this.solved = true)) : this.jumperGraphSolver.failed && (this.error = this.jumperGraphSolver.error, this.failed = true);
  }
  _stepCurvyTrace() {
    if (this.currentCurvySolverIndex >= this.curvySolvers.length)
      return this._finalizeCurvyTraceResults(), this.phase = "done", void (this.solved = true);
    const e50 = this.curvySolvers[this.currentCurvySolverIndex], t2 = e50.solver;
    if (this.activeSubSolver = t2, t2.step(), t2.solved) {
      const n2 = e50.regionId;
      this.regionCurvedPaths.has(n2) || this.regionCurvedPaths.set(n2, new Map);
      for (const e51 of t2.outputTraces) {
        const t3 = e51.networkId ?? "", o3 = e51.points.map((e52) => ({ x: e52.x, y: e52.y })), i3 = { path: o3, start: o3[0] ?? { x: 0, y: 0 }, end: o3[o3.length - 1] ?? { x: 0, y: 0 } };
        this.regionCurvedPaths.get(n2).has(t3) || this.regionCurvedPaths.get(n2).set(t3, []), this.regionCurvedPaths.get(n2).get(t3).push(i3);
      }
      this.currentCurvySolverIndex++;
    } else
      t2.failed && this.currentCurvySolverIndex++;
  }
  _initializeCurvyTraceSolvers() {
    if (!this.jumperGraphSolver)
      return;
    const e50 = new Set, t2 = [];
    for (const e51 of this.jumperLocations)
      for (const n3 of e51.padRegions) {
        const e52 = n3.d.bounds, o3 = n3.d.center;
        t2.push({ minX: e52.minX, minY: e52.minY, maxX: e52.maxX, maxY: e52.maxY, center: { x: o3.x, y: o3.y }, networkIds: [] });
      }
    const n2 = new Map;
    for (let t3 = 0;t3 < this.jumperGraphSolver.solvedRoutes.length; t3++) {
      const o3 = this.jumperGraphSolver.solvedRoutes[t3], i3 = o3.connection.connectionId, r3 = this.nodeWithPortPoints.portPoints.find((e51) => e51.connectionName === i3)?.rootConnectionName, s2 = [], a3 = [];
      let c3 = null, l3 = null;
      for (let h2 = 0;h2 < o3.path.length; h2++) {
        const d2 = o3.path[h2], u2 = d2.port, p3 = d2.lastRegion, m2 = u2.region1, g2 = u2.region2;
        let f2;
        if (p3)
          m2 && m2.regionId !== p3.regionId ? f2 = m2 : g2 && g2.regionId !== p3.regionId && (f2 = g2);
        else {
          const e51 = o3.path[h2 + 1], t4 = e51?.lastRegion;
          if (t4 && (m2 && m2.regionId === t4.regionId ? f2 = m2 : g2 && g2.regionId === t4.regionId && (f2 = g2)), !f2) {
            const e52 = (e53) => e53?.regionId?.startsWith("conn:");
            f2 = !m2 || e52(m2) || m2.d?.isPad || m2.d?.isThroughJumper ? !g2 || e52(g2) || g2.d?.isPad || g2.d?.isThroughJumper ? !m2 || m2.d?.isPad || m2.d?.isThroughJumper ? (!g2 || g2.d?.isPad || g2.d?.isThroughJumper) && m2 || g2 : m2 : g2 : m2;
          }
        }
        if (f2 && (!c3 || f2.regionId !== c3.regionId)) {
          if (c3 && l3) {
            a3.push({ regionId: c3.regionId, region: c3, entryPort: l3, exitPort: u2 });
            const e51 = c3.regionId;
            n2.has(e51) || n2.set(e51, []), n2.get(e51).push({ regionId: c3.regionId, region: c3, routeIndex: t3, connectionName: i3, rootConnectionName: r3, entryPort: l3, exitPort: u2 });
          }
          c3 = f2, l3 = u2;
        }
        if (p3?.d?.isThroughJumper && !e50.has(p3.regionId)) {
          e50.add(p3.regionId);
          const t4 = p3.d.bounds, n3 = p3.d.center, o4 = t4.maxX - t4.minX > t4.maxY - t4.minY, i4 = (this.hyperParameters.JUMPER_TYPE ?? "1206x4") === "0603" ? "0603" : "1206x4_pair";
          o4 ? s2.push({ route_type: "jumper", start: { x: t4.minX, y: n3.y }, end: { x: t4.maxX, y: n3.y }, footprint: i4 }) : s2.push({ route_type: "jumper", start: { x: n3.x, y: t4.minY }, end: { x: n3.x, y: t4.maxY }, footprint: i4 });
        }
      }
      if (c3 && l3) {
        const e51 = o3.path[o3.path.length - 1];
        a3.push({ regionId: c3.regionId, region: c3, entryPort: l3, exitPort: e51?.port || null });
      }
      this.routeInfos.push({ connectionId: i3, rootConnectionName: r3, jumpers: s2, traversals: a3 });
    }
    for (let e51 = 0;e51 < this.routeInfos.length; e51++) {
      const n3 = this.routeInfos[e51], o3 = n3.rootConnectionName ?? n3.connectionId;
      for (const e52 of n3.jumpers) {
        const n4 = [e52.start, e52.end];
        for (const e53 of n4)
          for (const n5 of t2) {
            const t3 = Math.abs(n5.center.x - e53.x), i3 = Math.abs(n5.center.y - e53.y);
            t3 < 0.1 && i3 < 0.1 && (n5.networkIds.includes(o3) || n5.networkIds.push(o3));
          }
      }
    }
    for (const [e51, o3] of n2) {
      if (o3.length === 0)
        continue;
      const n3 = o3[0].region;
      if (n3.d.isPad || n3.d.isThroughJumper)
        continue;
      const i3 = n3.d.bounds, r3 = [];
      for (const e52 of o3)
        r3.push({ start: { x: e52.entryPort.d.x, y: e52.entryPort.d.y }, end: { x: e52.exitPort.d.x, y: e52.exitPort.d.y }, networkId: e52.rootConnectionName ?? e52.connectionName });
      const s2 = 0.01, a3 = t2.filter((e52) => e52.minX <= i3.maxX + s2 && e52.maxX >= i3.minX - s2 && e52.minY <= i3.maxY + s2 && e52.maxY >= i3.minY - s2).map((e52) => {
        const t3 = o3.map((e53) => e53.rootConnectionName ?? e53.connectionName), n4 = e52.networkIds.find((e53) => t3.includes(e53));
        return { minX: e52.minX, minY: e52.minY, maxX: e52.maxX, maxY: e52.maxY, center: e52.center, networkId: n4 };
      }), c3 = { bounds: i3, waypointPairs: r3, obstacles: a3, preferredTraceToTraceSpacing: 2 * this.traceWidth, preferredObstacleToTraceSpacing: 2 * this.traceWidth }, l3 = new K$(c3);
      this.curvySolvers.push({ solver: l3, regionId: e51, traversals: o3.map((e52) => ({ routeIndex: e52.routeIndex, connectionName: e52.connectionName, rootConnectionName: e52.rootConnectionName })) });
    }
  }
  _finalizeCurvyTraceResults() {
    const e50 = (e51, t2) => Math.sqrt((e51.x - t2.x) ** 2 + (e51.y - t2.y) ** 2);
    for (let t2 = 0;t2 < this.routeInfos.length; t2++) {
      const n2 = this.routeInfos[t2], o3 = [];
      for (const t3 of n2.traversals) {
        const i3 = t3.regionId, r3 = n2.rootConnectionName ?? n2.connectionId, s2 = this.regionCurvedPaths.get(i3)?.get(r3);
        let a3 = null;
        if (s2 && s2.length > 0) {
          const n3 = { x: t3.entryPort.d.x, y: t3.entryPort.d.y }, o4 = t3.exitPort ? { x: t3.exitPort.d.x, y: t3.exitPort.d.y } : null;
          let i4 = null, r4 = 1 / 0;
          for (const t4 of s2) {
            const s3 = e50(t4.start, n3) + (o4 ? e50(t4.end, o4) : 0);
            s3 < r4 && (r4 = s3, i4 = t4);
          }
          i4 && r4 < 0.5 && (a3 = i4.path);
        }
        if (a3 && a3.length > 0) {
          for (let e51 = o3.length > 0 ? 1 : 0;e51 < a3.length; e51++)
            o3.push({ x: a3[e51].x, y: a3[e51].y, z: 0 });
        } else
          o3.length === 0 && o3.push({ x: t3.entryPort.d.x, y: t3.entryPort.d.y, z: 0 }), t3.exitPort && o3.push({ x: t3.exitPort.d.x, y: t3.exitPort.d.y, z: 0 });
      }
      this.solvedRoutes.push({ connectionName: n2.connectionId, rootConnectionName: n2.rootConnectionName, traceThickness: this.traceWidth, route: o3, jumpers: n2.jumpers });
    }
  }
  getOutput() {
    return this.solvedRoutes;
  }
  getOutputJumpers() {
    if (this.jumpers.length > 0)
      return this.jumpers;
    const e50 = new Map;
    for (const t3 of this.solvedRoutes)
      for (const n3 of t3.jumpers) {
        const o3 = [n3.start, n3.end];
        for (const n4 of o3) {
          const o4 = `${n4.x.toFixed(3)},${n4.y.toFixed(3)}`, i3 = e50.get(o4) ?? [];
          t3.rootConnectionName && !i3.includes(t3.rootConnectionName) && i3.push(t3.rootConnectionName), i3.includes(t3.connectionName) || i3.push(t3.connectionName), e50.set(o4, i3);
        }
      }
    const t2 = this.hyperParameters.JUMPER_TYPE ?? "1206x4", n2 = Xo[t2 === "0603" ? "0603" : "1206x4_pair"];
    for (const o3 of this.jumperLocations) {
      const i3 = o3.orientation === "horizontal", r3 = o3.padRegions.map((t3) => {
        const n3 = t3.d.bounds, o4 = t3.d.center, i4 = n3.maxX - n3.minX, r4 = n3.maxY - n3.minY, s3 = `${o4.x.toFixed(3)},${o4.y.toFixed(3)}`;
        return { type: "rect", center: o4, width: i4, height: r4, layers: ["top"], connectedTo: [...e50.get(s3) ?? []] };
      }), s2 = { jumper_footprint: t2, center: o3.center, orientation: o3.orientation, width: i3 ? n2.length : n2.width, height: i3 ? n2.width : n2.length, pads: r3 };
      this.jumpers.push(s2);
    }
    return this.jumpers = this.jumpers.filter((e51) => e51.pads.some((e52) => e52.connectedTo.length > 0)), this.jumpers;
  }
  visualize() {
    if (this.jumperGraphSolver && !this.solved)
      return this.jumperGraphSolver.visualize();
    const e50 = { lines: [], points: [], rects: [], circles: [] }, t2 = this.nodeWithPortPoints, n2 = { minX: t2.center.x - t2.width / 2, maxX: t2.center.x + t2.width / 2, minY: t2.center.y - t2.height / 2, maxY: t2.center.y + t2.height / 2 };
    e50.lines.push({ points: [{ x: n2.minX, y: n2.minY }, { x: n2.maxX, y: n2.minY }, { x: n2.maxX, y: n2.maxY }, { x: n2.minX, y: n2.maxY }, { x: n2.minX, y: n2.minY }], strokeColor: "rgba(255, 0, 0, 0.25)", strokeDash: "4 4", layer: "border" });
    for (const n3 of t2.portPoints)
      e50.points.push({ x: n3.x, y: n3.y, label: n3.connectionName, color: this.colorMap[n3.connectionName] ?? "blue" });
    for (const t3 of this.solvedRoutes) {
      const n3 = this.colorMap[t3.connectionName] ?? "blue";
      for (let o3 = 0;o3 < t3.route.length - 1; o3++) {
        const i3 = t3.route[o3], r3 = t3.route[o3 + 1];
        e50.lines.push({ points: [i3, r3], strokeColor: Ao(n3, 0.2), strokeWidth: t3.traceThickness, layer: "route-layer-0" });
      }
      for (const o3 of t3.jumpers)
        this._drawJumperPads(e50, o3, Ao(n3, 0.5));
    }
    return e50;
  }
  _drawJumperPads(e50, t2, n2) {
    const o3 = Xo[t2.footprint], i3 = t2.end.x - t2.start.x, r3 = t2.end.y - t2.start.y, s2 = Math.abs(i3) > Math.abs(r3), a3 = s2 ? o3.padLength : o3.padWidth, c3 = s2 ? o3.padWidth : o3.padLength;
    e50.rects.push({ center: { x: t2.start.x, y: t2.start.y }, width: a3, height: c3, fill: n2, stroke: "rgba(0, 0, 0, 0.5)", layer: "jumper" }), e50.rects.push({ center: { x: t2.end.x, y: t2.end.y }, width: a3, height: c3, fill: n2, stroke: "rgba(0, 0, 0, 0.5)", layer: "jumper" }), e50.lines.push({ points: [t2.start, t2.end], strokeColor: "rgba(100, 100, 100, 0.8)", strokeWidth: 0.3 * o3.padWidth, layer: "jumper-body" });
  }
};
var RG = class extends wa {
  constructorParams;
  nodeWithPortPoints;
  colorMap;
  traceWidth;
  obstacleMargin;
  connMap;
  baseHyperParameters;
  availableJumperTypes;
  solvedRoutes = [];
  jumpers = [];
  constructor(e50) {
    super(), this.constructorParams = e50, this.nodeWithPortPoints = e50.nodeWithPortPoints, this.colorMap = e50.colorMap ?? {}, this.traceWidth = e50.traceWidth ?? 0.15, this.obstacleMargin = e50.obstacleMargin ?? 0.15, this.connMap = e50.connMap, this.baseHyperParameters = e50.hyperParameters ?? {}, this.availableJumperTypes = e50.availableJumperTypes ?? ["0603"], this.MAX_ITERATIONS = 1e6, this.GREEDY_MULTIPLIER = 1, this.MIN_SUBSTEPS = 1000;
  }
  getConstructorParams() {
    return this.constructorParams;
  }
  getHyperParameterDefs() {
    const e50 = [], t2 = this.nodeWithPortPoints, n2 = this.calculateMax0603ConfigWithTraceChannels(t2.width, t2.height, "vertical", 1);
    e50.push({ name: "0603_max_rows_and_cols_vert_1trace_grid", possibleValues: [{ JUMPER_TYPE: "0603", COLS: n2.cols, ROWS: n2.rows, ORIENTATION: "vertical", PATTERN: "grid", TRACE_CHANNELS_BETWEEN_JUMPERS: 1 }] });
    const o3 = this.calculateMax0603ConfigWithTraceChannels(t2.width, t2.height, "vertical", 1, "staggered");
    e50.push({ name: "0603_max_rows_and_cols_vert_1trace_staggered", possibleValues: [{ JUMPER_TYPE: "0603", COLS: o3.cols, ROWS: o3.rows, ORIENTATION: "vertical", PATTERN: "staggered", TRACE_CHANNELS_BETWEEN_JUMPERS: 1 }] });
    const i3 = this.calculateMax0603ConfigWithTraceChannels(t2.width, t2.height, "vertical", 2);
    e50.push({ name: "0603_max_rows_and_cols_vert_2trace_grid", possibleValues: [{ JUMPER_TYPE: "0603", COLS: i3.cols, ROWS: i3.rows, ORIENTATION: "vertical", PATTERN: "grid", TRACE_CHANNELS_BETWEEN_JUMPERS: 2 }] });
    const r3 = this.calculateMax0603ConfigWithTraceChannels(t2.width, t2.height, "vertical", 2, "staggered");
    e50.push({ name: "0603_max_rows_and_cols_vert_2trace_staggered", possibleValues: [{ JUMPER_TYPE: "0603", COLS: r3.cols, ROWS: r3.rows, ORIENTATION: "vertical", PATTERN: "staggered", TRACE_CHANNELS_BETWEEN_JUMPERS: 2 }] });
    const s2 = this.calculateMax0603ConfigWithTraceChannels(t2.width, t2.height, "horizontal", 1);
    e50.push({ name: "0603_max_rows_and_cols_horz_1trace_grid", possibleValues: [{ JUMPER_TYPE: "0603", COLS: s2.cols, ROWS: s2.rows, ORIENTATION: "horizontal", PATTERN: "grid", TRACE_CHANNELS_BETWEEN_JUMPERS: 1 }] });
    const a3 = this.calculateMax0603ConfigWithTraceChannels(t2.width, t2.height, "horizontal", 1, "staggered");
    e50.push({ name: "0603_max_rows_and_cols_horz_1trace_staggered", possibleValues: [{ JUMPER_TYPE: "0603", COLS: a3.cols, ROWS: a3.rows, ORIENTATION: "horizontal", PATTERN: "staggered", TRACE_CHANNELS_BETWEEN_JUMPERS: 1 }] });
    const c3 = this.calculateMax0603ConfigWithTraceChannels(t2.width, t2.height, "horizontal", 2);
    e50.push({ name: "0603_max_rows_and_cols_horz_2trace_grid", possibleValues: [{ JUMPER_TYPE: "0603", COLS: c3.cols, ROWS: c3.rows, ORIENTATION: "horizontal", PATTERN: "grid", TRACE_CHANNELS_BETWEEN_JUMPERS: 2 }] });
    const l3 = this.calculateMax0603ConfigWithTraceChannels(t2.width, t2.height, "horizontal", 2, "staggered");
    e50.push({ name: "0603_max_rows_and_cols_horz_2trace_staggered", possibleValues: [{ JUMPER_TYPE: "0603", COLS: l3.cols, ROWS: l3.rows, ORIENTATION: "horizontal", PATTERN: "staggered", TRACE_CHANNELS_BETWEEN_JUMPERS: 2 }] }), e50.push({ name: "1206x4", possibleValues: [{ JUMPER_TYPE: "1206x4" }] });
    return e50.push({ name: "1206x4_cols", possibleValues: [1, 2, 3, 4, 6, 8, 10].map((e51) => ({ COLS: e51 })) }), e50.push({ name: "1206x4_rows", possibleValues: [1, 2, 3, 4, 8].map((e51) => ({ ROWS: e51 })) }), e50.push({ name: "orientation", possibleValues: [{ ORIENTATION: "vertical" }, { ORIENTATION: "horizontal" }] }), e50;
  }
  isValidCombination(e50) {
    const { JUMPER_TYPE: t2, COLS: n2, ROWS: o3 } = e50, i3 = [1, 2, 4, 6, 8], r3 = [1, 2, 3, 4, 6, 8, 10], s2 = [1, 2, 3, 4, 8];
    return t2 === "0603" ? i3.includes(n2) && i3.includes(o3) : t2 === "1206x4" && (r3.includes(n2) && s2.includes(o3));
  }
  getCombinationDefs() {
    return [["0603_max_rows_and_cols_vert_1trace_grid"], ["0603_max_rows_and_cols_vert_1trace_staggered"], ["0603_max_rows_and_cols_horz_1trace_grid"], ["0603_max_rows_and_cols_horz_1trace_staggered"], ["0603_max_rows_and_cols_vert_2trace_grid"], ["0603_max_rows_and_cols_vert_2trace_staggered"], ["0603_max_rows_and_cols_horz_2trace_grid"], ["0603_max_rows_and_cols_horz_2trace_staggered"], ["1206x4", "1206x4_cols", "1206x4_rows", "orientation"]];
  }
  calculateMax0603ConfigWithTraceChannels(e50, t2, n2, o3, i3 = "grid") {
    const r3 = this.traceWidth * o3 + 2 * this.obstacleMargin, s2 = n2 === "horizontal" ? 2.15 : 1, a3 = n2 === "horizontal" ? 1 : 2.15, c3 = n2 === "horizontal" ? "x" : "y", l3 = i3 === "staggered" && c3 === "x" ? s2 / 2 : i3 === "staggered" ? a3 / 2 : 0, h2 = Math.max(0, e50 - 1), d2 = Math.max(0, t2 - 1), u2 = Math.max(0, h2 - (i3 === "staggered" && c3 === "x" ? l3 : 0)), p3 = Math.max(0, d2 - (i3 === "staggered" && c3 === "y" ? l3 : 0)), m2 = s2 + r3, g2 = a3 + r3, f2 = Math.max(1, Math.floor(1 + (u2 - s2) / m2)), _2 = Math.max(1, Math.floor(1 + (p3 - a3) / g2));
    return n2 === "vertical" ? { cols: f2, rows: _2 } : { cols: _2, rows: f2 };
  }
  initializeSolvers() {
    const e50 = this.getHyperParameterDefs(), t2 = this.getCombinationDefs();
    this.supervisedSolvers = [];
    for (const n2 of t2) {
      const t3 = n2.some((e51) => e51.startsWith("0603_max_rows_and_cols_")), o3 = n2.includes("1206x4");
      if (t3 && !this.availableJumperTypes.includes("0603"))
        continue;
      if (o3 && !this.availableJumperTypes.includes("1206x4"))
        continue;
      const i3 = this.getHyperParameterCombinations(e50.filter((e51) => n2.includes(e51.name)));
      for (const e51 of i3) {
        const t4 = this.generateSolver(e51), n3 = this.computeG(t4);
        this.supervisedSolvers.push({ hyperParameters: e51, solver: t4, h: 0, g: n3, f: n3 });
      }
    }
  }
  generateSolver(e50) {
    return new NG({ nodeWithPortPoints: this.nodeWithPortPoints, colorMap: this.colorMap, traceWidth: this.traceWidth, hyperParameters: { COLS: e50.COLS, ROWS: e50.ROWS, ORIENTATION: e50.ORIENTATION, JUMPER_TYPE: e50.JUMPER_TYPE, PATTERN: e50.PATTERN, TRACE_CHANNELS_BETWEEN_JUMPERS: e50.TRACE_CHANNELS_BETWEEN_JUMPERS }, obstacleMargin: this.obstacleMargin });
  }
  computeG(e50) {
    const t2 = e50.hyperParameters.COLS * e50.hyperParameters.ROWS;
    return e50.iterations / 1e4 + 0.25 * t2;
  }
  computeH(e50) {
    return 1 - (e50.progress || 0);
  }
  onSolve(e50) {
    this.solvedRoutes = e50.solver.solvedRoutes, this.jumpers = e50.solver.getOutputJumpers();
  }
  getOutput() {
    return this.solvedRoutes;
  }
  getOutputJumpers() {
    return this.jumpers;
  }
  visualize() {
    return this.winningSolver ? this.winningSolver.visualize() : super.visualize();
  }
};
function TG(e50) {
  return { connectionName: e50.connectionName, rootConnectionName: e50.rootConnectionName, regionId: e50.regionId, traceThickness: e50.traceThickness, viaDiameter: 0, route: e50.route, vias: [], jumpers: e50.jumpers };
}
var EG = class extends ni {
  getSolverName() {
    return "JumperHighDensitySolver";
  }
  allNodes;
  nodeAnalyses;
  routes;
  colorMap;
  traceWidth;
  obstacleMargin;
  viaDiameter;
  connMap;
  hyperParameters;
  availableJumperTypes;
  capacityMeshNodes;
  capacityMeshEdges;
  capacityMeshNodeMap;
  nodeAdjacencyMap;
  nodesWithoutCrossings;
  nodesWithCrossings;
  curvyIntraNodeSolvers;
  currentCurvySolverIndex;
  jumperSolvers;
  currentJumperSolverIndex;
  phase;
  jumpers = [];
  constructor({ nodePortPoints: e50, colorMap: t2, traceWidth: n2 = 0.15, obstacleMargin: o3 = 0.15, viaDiameter: i3 = 0.3, connMap: r3, hyperParameters: s2, capacityMeshNodes: a3 = [], capacityMeshEdges: c3 = [], availableJumperTypes: l3 }) {
    super(), this.allNodes = [...e50], this.colorMap = t2 ?? {}, this.routes = [], this.traceWidth = n2, this.obstacleMargin = o3, this.viaDiameter = i3, this.connMap = r3, this.hyperParameters = s2, this.capacityMeshNodes = a3, this.capacityMeshEdges = c3, this.availableJumperTypes = l3 ?? ["0603"], this.capacityMeshNodeMap = new Map(a3.map((e51) => [e51.capacityMeshNodeId, e51])), this.nodeAdjacencyMap = this._buildNodeAdjacencyMap(), this.nodesWithoutCrossings = [], this.nodesWithCrossings = [], this.nodeAnalyses = [], this.curvyIntraNodeSolvers = [], this.currentCurvySolverIndex = 0, this.jumperSolvers = [], this.currentJumperSolverIndex = 0, this.phase = "analyzing", this._analyzeNodes();
    const h2 = 1000 * this.nodesWithoutCrossings.length, d2 = 1e5 * this.nodesWithCrossings.length;
    this.MAX_ITERATIONS = h2 + d2 + 100;
  }
  _buildNodeAdjacencyMap() {
    const e50 = new Map;
    for (const t2 of this.capacityMeshEdges) {
      const [n2, o3] = t2.nodeIds;
      e50.has(n2) || e50.set(n2, new Set), e50.has(o3) || e50.set(o3, new Set), e50.get(n2).add(o3), e50.get(o3).add(n2);
    }
    return e50;
  }
  _analyzeNodes() {
    for (const e50 of this.allNodes) {
      const t2 = Cz(e50), n2 = { node: e50, hasCrossings: t2.numSameLayerCrossings > 0, numSameLayerCrossings: t2.numSameLayerCrossings };
      this.nodeAnalyses.push(n2), t2.numSameLayerCrossings > 0 ? this.nodesWithCrossings.push(e50) : this.nodesWithoutCrossings.push(e50);
    }
    this.nodesWithoutCrossings.length > 0 ? (this.phase = "curvy", this._initializeCurvySolvers()) : this.nodesWithCrossings.length > 0 ? (this.phase = "jumpers", this._initializeJumperSolvers()) : this.phase = "done";
  }
  _step() {
    switch (this.phase) {
      case "analyzing":
        this.nodesWithoutCrossings.length > 0 ? (this.phase = "curvy", this._initializeCurvySolvers()) : this.nodesWithCrossings.length > 0 ? (this.phase = "jumpers", this._initializeJumperSolvers()) : this.phase = "done";
        break;
      case "curvy":
        this._stepCurvySolvers();
        break;
      case "jumpers":
        this._stepJumperSolvers();
        break;
      case "done":
        this.solved = true;
    }
  }
  _getAdjacentObstacles(e50) {
    const t2 = [], n2 = this.nodeAdjacencyMap.get(e50.capacityMeshNodeId);
    if (!n2 || n2.size === 0)
      return t2;
    const o3 = new Map(this.allNodes.map((e51) => [e51.capacityMeshNodeId, e51]));
    for (const e51 of n2) {
      const n3 = this.capacityMeshNodeMap.get(e51);
      if (!n3)
        continue;
      if (!n3._containsObstacle && !n3._containsTarget)
        continue;
      const i3 = n3.center.x - n3.width / 2, r3 = n3.center.y - n3.height / 2, s2 = n3.center.x + n3.width / 2, a3 = n3.center.y + n3.height / 2;
      let c3;
      if (n3._containsTarget)
        if (n3._targetConnectionName)
          c3 = n3._targetConnectionName;
        else {
          const t3 = o3.get(e51);
          t3 && t3.portPoints.length > 0 && (c3 = t3.portPoints[0].rootConnectionName ?? t3.portPoints[0].connectionName);
        }
      t2.push({ minX: i3, minY: r3, maxX: s2, maxY: a3, networkId: c3 });
    }
    return t2;
  }
  _initializeCurvySolvers() {
    for (const e50 of this.nodesWithoutCrossings) {
      const t2 = this._getAdjacentObstacles(e50), n2 = new eY({ nodeWithPortPoints: e50, colorMap: this.colorMap, traceWidth: this.traceWidth, viaDiameter: this.viaDiameter, adjacentObstacles: t2 });
      this.curvyIntraNodeSolvers.push(n2);
    }
  }
  _stepCurvySolvers() {
    if (this.curvyIntraNodeSolvers.length === 0)
      return this.phase = this.nodesWithCrossings.length > 0 ? "jumpers" : "done", void (this.phase === "jumpers" && this._initializeJumperSolvers());
    const e50 = this.curvyIntraNodeSolvers[this.currentCurvySolverIndex];
    if (this.activeSubSolver = e50, !e50)
      return this.phase = this.nodesWithCrossings.length > 0 ? "jumpers" : "done", void (this.phase === "jumpers" && this._initializeJumperSolvers());
    if (e50.step(), e50.solved) {
      this.routes.push(...e50.routes), this.currentCurvySolverIndex++;
      for (let e51 = this.currentCurvySolverIndex;e51 < this.curvyIntraNodeSolvers.length; e51++) {
        this.curvyIntraNodeSolvers[e51];
        const t2 = this.nodesWithoutCrossings[e51], n2 = this._getAdjacentObstacles(t2), o3 = new eY({ nodeWithPortPoints: t2, colorMap: this.colorMap, traceWidth: this.traceWidth, viaDiameter: this.viaDiameter, adjacentObstacles: n2 });
        this.curvyIntraNodeSolvers[e51] = o3;
      }
      this.currentCurvySolverIndex >= this.curvyIntraNodeSolvers.length && (this.phase = this.nodesWithCrossings.length > 0 ? "jumpers" : "done", this.phase === "jumpers" && this._initializeJumperSolvers());
    } else
      e50.failed && (this.error = `CurvyIntraNodeSolver failed for node: ${e50.nodeWithPortPoints.capacityMeshNodeId}: ${e50.error}`, this.failed = true);
  }
  _initializeJumperSolvers() {
    for (const e50 of this.nodesWithCrossings) {
      const t2 = new RG({ nodeWithPortPoints: e50, colorMap: this.colorMap, traceWidth: this.traceWidth, obstacleMargin: this.obstacleMargin, connMap: this.connMap, availableJumperTypes: this.availableJumperTypes });
      this.jumperSolvers.push(t2);
    }
  }
  _stepJumperSolvers() {
    if (this.jumperSolvers.length === 0)
      return this.phase = "done", void (this.solved = true);
    const e50 = this.jumperSolvers[this.currentJumperSolverIndex];
    if (this.activeSubSolver = e50, !e50)
      return this.phase = "done", void (this.solved = true);
    if (e50.step(), e50.solved) {
      for (const t2 of e50.solvedRoutes)
        this.routes.push(TG(t2));
      this.jumpers.push(...e50.getOutputJumpers()), this.currentJumperSolverIndex++, this.currentJumperSolverIndex >= this.jumperSolvers.length && (this.phase = "done", this.solved = true);
    } else
      e50.failed && (this.error = `HyperJumperPrepatternSolver2 failed for node: ${e50.nodeWithPortPoints.capacityMeshNodeId}: ${e50.error}`, this.failed = true);
  }
  computeProgress() {
    const e50 = this.allNodes.length;
    if (e50 === 0)
      return 1;
    let t2 = 0;
    t2 += this.currentCurvySolverIndex;
    const n2 = this.curvyIntraNodeSolvers[this.currentCurvySolverIndex];
    n2 && (t2 += n2.progress), t2 += this.currentJumperSolverIndex;
    const o3 = this.jumperSolvers[this.currentJumperSolverIndex];
    return o3 && (t2 += o3.progress), t2 / e50;
  }
  getConstructorParams() {
    return { nodePortPoints: this.allNodes, colorMap: this.colorMap, traceWidth: this.traceWidth, obstacleMargin: this.obstacleMargin, viaDiameter: this.viaDiameter, connMap: this.connMap, hyperParameters: this.hyperParameters, capacityMeshNodes: this.capacityMeshNodes, capacityMeshEdges: this.capacityMeshEdges, availableJumperTypes: this.availableJumperTypes };
  }
  getOutputJumpers() {
    return this.jumpers;
  }
  visualize() {
    const e50 = { lines: [], points: [], rects: [], circles: [] };
    if (this.failed && this.activeSubSolver)
      return this.activeSubSolver.visualize();
    if (this.phase === "curvy" && this.curvyIntraNodeSolvers[this.currentCurvySolverIndex])
      return this.curvyIntraNodeSolvers[this.currentCurvySolverIndex].visualize();
    if (this.phase === "jumpers" && this.jumperSolvers[this.currentJumperSolverIndex])
      return this.jumperSolvers[this.currentJumperSolverIndex].visualize();
    for (const t2 of this.routes) {
      const n2 = t2.rootConnectionName ?? t2.connectionName, o3 = mi(t2.route, t2.connectionName, this.colorMap[n2]);
      for (const n3 of o3)
        e50.lines.push({ points: n3.points, label: n3.connectionName, strokeColor: n3.z === 0 ? n3.color : Ao(n3.color ?? "gray", 0.75), layer: `z${n3.z}`, strokeWidth: t2.traceThickness, strokeDash: n3.z !== 0 ? "10, 5" : undefined });
      for (const o4 of t2.vias)
        e50.circles.push({ center: o4, radius: t2.viaDiameter / 2, fill: Ao(this.colorMap[n2] ?? "gray", 0.5), layer: "via" });
      if ("jumpers" in t2 && t2.jumpers)
        for (const o4 of t2.jumpers) {
          const t3 = this.colorMap[n2] ?? "gray", i3 = o4.footprint ?? "1206", r3 = Xo[i3], s2 = o4.end.x - o4.start.x, a3 = o4.end.y - o4.start.y, c3 = Math.abs(s2) > Math.abs(a3), l3 = c3 ? r3.padLength : r3.padWidth, h2 = c3 ? r3.padWidth : r3.padLength;
          e50.rects.push({ center: o4.start, width: l3, height: h2, fill: Ao(t3, 0.5), stroke: "rgba(0, 0, 0, 0.5)", layer: "jumper" }), e50.rects.push({ center: o4.end, width: l3, height: h2, fill: Ao(t3, 0.5), stroke: "rgba(0, 0, 0, 0.5)", layer: "jumper" }), e50.lines.push({ points: [o4.start, o4.end], strokeColor: "rgba(100, 100, 100, 0.8)", strokeWidth: 0.3 * r3.padWidth, layer: "jumper-body" });
        }
    }
    for (const t2 of this.nodeAnalyses) {
      const n2 = t2.node;
      n2.center.x, n2.width, n2.center.x, n2.width, n2.center.y, n2.height, n2.center.y, n2.height;
      e50.rects.push({ center: n2.center, width: n2.width, height: n2.height, fill: t2.hasCrossings ? "rgba(255, 200, 0, 0.1)" : "rgba(0, 200, 0, 0.1)", stroke: t2.hasCrossings ? "rgba(255, 150, 0, 0.5)" : "rgba(0, 150, 0, 0.5)", label: [n2.capacityMeshNodeId, t2.hasCrossings ? `crossings: ${t2.numSameLayerCrossings}` : "no crossings"].join(`
`) });
    }
    return e50;
  }
};
function AG(e50, t2, n2, o3 = {}) {
  return { solverName: e50, solverClass: t2, getConstructorParams: n2, onSolved: o3.onSolved };
}
var OG = class extends ni {
  constructor(e50, t2 = {}) {
    super(), this.srj = e50, this.opts = t2, this.srj = e50, this.opts = { ...t2 }, this.viaDiameter = Yo(e50).padDiameter, this.minTraceWidth = e50.minTraceWidth;
    const n2 = this.opts;
    if (this.effort = n2.effort ?? 1, this.MAX_ITERATIONS = 1e8 * this.effort, n2.capacityDepth === undefined) {
      const t3 = e50.bounds.maxX - e50.bounds.minX, o3 = e50.bounds.maxY - e50.bounds.minY, i3 = Math.max(t3, o3), r3 = n2.targetMinCapacity ?? 0.5;
      n2.capacityDepth = Fz(i3, r3);
    }
    this.connMap = ei(e50), this.colorMap = Eo(e50, this.connMap), this.cacheProvider = n2.cacheProvider === undefined ? no() : n2.cacheProvider === null ? null : n2.cacheProvider, this.startTimeOfPhase = {}, this.endTimeOfPhase = {}, this.timeSpentOnPhase = {};
  }
  getSolverName() {
    return "AssignableAutoroutingPipeline3";
  }
  netToPointPairsSolver;
  traceKeepoutSolver;
  nodeSolver;
  nodeTargetMerger;
  edgeSolver;
  relateNodesToOffBoardConnections;
  colorMap;
  highDensityRouteSolver;
  simpleHighDensityRouteSolver;
  highDensitySolver;
  highDensityStitchSolver;
  singleLayerNodeMerger;
  offboardPathFragmentSolver;
  strawSolver;
  deadEndSolver;
  traceSimplificationSolver;
  traceWidthSolver;
  availableSegmentPointSolver;
  portPointPathingSolver;
  multiSectionPortPointOptimizer;
  viaDiameter;
  minTraceWidth;
  effort;
  startTimeOfPhase;
  endTimeOfPhase;
  timeSpentOnPhase;
  activeSubSolver = null;
  connMap;
  srjWithPointPairs;
  capacityNodes = null;
  capacityEdges = null;
  cacheProvider = null;
  pipelineDef = [AG("netToPointPairsSolver", uB, (e50) => [e50.srj, e50.colorMap, ti(e50.srj)], { onSolved: (e50) => {
    e50.srjWithPointPairs = e50.netToPointPairsSolver?.getNewSimpleRouteJson(), e50.colorMap = Eo(e50.srjWithPointPairs, this.connMap), e50.connMap = ei(e50.srjWithPointPairs);
  } }), AG("nodeSolver", Jn, (e50) => [{ simpleRouteJson: e50.srjWithPointPairs, maxGapFillPasses: 4 }], { onSolved: (e50) => {
    e50.capacityNodes = e50.nodeSolver?.getOutput().meshNodes ?? [];
  } }), AG("relateNodesToOffBoardConnections", h$, (e50) => [{ capacityMeshNodes: e50.capacityNodes, srj: e50.srj }], { onSolved: (e50) => {
    e50.capacityNodes = e50.relateNodesToOffBoardConnections?.getOutput().capacityNodes;
  } }), AG("edgeSolver", ui, (e50) => [e50.capacityNodes], { onSolved: (e50) => {
    e50.capacityEdges = e50.edgeSolver?.edges;
  } }), AG("availableSegmentPointSolver", ii, (e50) => [{ nodes: e50.capacityNodes, edges: e50.capacityEdges || [], traceWidth: e50.minTraceWidth, colorMap: e50.colorMap, shouldReturnCrampedPortPoints: false }]), AG("portPointPathingSolver", Kz, (e50) => {
    const t2 = e50.capacityNodes.map((e51) => ({ capacityMeshNodeId: e51.capacityMeshNodeId, center: e51.center, width: e51.width, height: e51.height, portPoints: [], availableZ: e51.availableZ, _containsTarget: e51._containsTarget, _containsObstacle: e51._containsObstacle, _offBoardConnectionId: e51._offBoardConnectionId, _offBoardConnectedCapacityMeshNodeIds: e51._offBoardConnectedCapacityMeshNodeIds })), n2 = new Map(t2.map((e51) => [e51.capacityMeshNodeId, e51])), o3 = e50.availableSegmentPointSolver;
    for (const e51 of o3.sharedEdgeSegments)
      for (const t3 of e51.portPoints) {
        const [o4, i3] = t3.nodeIds, r3 = { portPointId: t3.segmentPortPointId, x: t3.x, y: t3.y, z: t3.availableZ[0] ?? 0, connectionNodeIds: [o4, i3], distToCentermostPortOnZ: t3.distToCentermostPortOnZ, connectsToOffBoardNode: e51.nodeIds.some((e52) => n2.get(e52)?._offBoardConnectionId) }, s2 = n2.get(o4);
        s2 && s2.portPoints.push(r3);
      }
    return [{ simpleRouteJson: e50.srjWithPointPairs, inputNodes: t2, capacityMeshNodes: e50.capacityNodes, colorMap: e50.colorMap, numShuffleSeeds: 10 * Math.min(1, e50.effort), hyperParameters: { JUMPER_PF_FN_ENABLED: true, NODE_PF_FACTOR: 100, MAX_RIPS: 100 * Math.min(1, e50.effort), RIPPING_ENABLED: true, MAX_RIPPING_PF_THRESHOLD: 0.9, MIN_RIPPING_PF_THRESHOLD: 0.1, RANDOM_RIP_FRACTION: 0.05, NODE_PF_MAX_PENALTY: 1000, STRAIGHT_LINE_DEVIATION_PENALTY_FACTOR: 0, CENTER_OFFSET_DIST_PENALTY_FACTOR: 0, FORCE_CENTER_FIRST: true } }];
  }, { onSolved: (e50) => {
    const t2 = e50.portPointPathingSolver;
    t2 && y$({ connMap: e50.connMap, connectionsWithResults: t2.connectionsWithResults, inputNodes: t2.inputNodes, obstacles: e50.srj.obstacles });
  } }), AG("highDensitySolver", EG, (e50) => [{ nodePortPoints: e50.multiSectionPortPointOptimizer?.getNodesWithPortPoints() ?? e50.portPointPathingSolver?.getNodesWithPortPoints() ?? [], colorMap: e50.colorMap, viaDiameter: e50.viaDiameter, traceWidth: e50.minTraceWidth, obstacleMargin: e50.srj.defaultObstacleMargin ?? 0.15, connMap: e50.connMap, capacityMeshNodes: e50.capacityNodes ?? [], capacityMeshEdges: e50.capacityEdges ?? [], availableJumperTypes: e50.srj.availableJumperTypes }]), AG("highDensityStitchSolver", v$, (e50) => [{ connections: e50.srjWithPointPairs.connections, hdRoutes: e50.highDensitySolver.routes, connectionPathResults: e50.multiSectionPortPointOptimizer?.connectionResults ?? e50.portPointPathingSolver?.connectionsWithResults ?? [], colorMap: e50.colorMap, layerCount: e50.srj.layerCount, defaultViaDiameter: e50.viaDiameter }]), AG("traceKeepoutSolver", l$, (e50) => [{ hdRoutes: e50.traceSimplificationSolver?.simplifiedHdRoutes ?? e50.highDensityStitchSolver?.mergedHdRoutes ?? [], obstacles: e50.srj.obstacles, jumpers: e50.highDensitySolver?.getOutputJumpers() ?? [], connMap: e50.connMap, colorMap: e50.colorMap, srj: e50.srj }])];
  getConstructorParams() {
    return [this.srj, this.opts];
  }
  currentPipelineStepIndex = 0;
  _step() {
    const e50 = this.pipelineDef[this.currentPipelineStepIndex];
    if (!e50)
      return void (this.solved = true);
    if (this.activeSubSolver)
      return this.activeSubSolver.step(), void (this.activeSubSolver.solved ? (this.endTimeOfPhase[e50.solverName] = performance.now(), this.timeSpentOnPhase[e50.solverName] = this.endTimeOfPhase[e50.solverName] - this.startTimeOfPhase[e50.solverName], e50.onSolved?.(this), this.activeSubSolver = null, this.currentPipelineStepIndex++) : this.activeSubSolver.failed && (this.error = this.activeSubSolver?.error, this.failed = true, this.activeSubSolver = null));
    const t2 = e50.getConstructorParams(this);
    this.activeSubSolver = new e50.solverClass(...t2), this[e50.solverName] = this.activeSubSolver, this.timeSpentOnPhase[e50.solverName] = 0, this.startTimeOfPhase[e50.solverName] = performance.now();
  }
  solveUntilPhase(e50) {
    for (;this.getCurrentPhase() !== e50; )
      this.step();
  }
  getCurrentPhase() {
    return this.pipelineDef[this.currentPipelineStepIndex]?.solverName ?? "none";
  }
  visualize() {
    if (!this.solved && this.activeSubSolver)
      return this.activeSubSolver.visualize();
    const e50 = this.netToPointPairsSolver?.visualize(), t2 = this.nodeSolver?.visualize(), n2 = this.nodeTargetMerger?.visualize(), o3 = this.singleLayerNodeMerger?.visualize(), i3 = this.strawSolver?.visualize(), r3 = this.edgeSolver?.visualize(), s2 = this.traceKeepoutSolver?.visualize(), a3 = this.deadEndSolver?.visualize(), c3 = this.availableSegmentPointSolver?.visualize(), l3 = this.offboardPathFragmentSolver?.visualize(), h2 = this.portPointPathingSolver?.visualize(), d2 = this.multiSectionPortPointOptimizer?.visualize(), u2 = this.highDensityRouteSolver?.visualize(), p3 = this.highDensitySolver?.visualize(), m2 = this.simpleHighDensityRouteSolver?.visualize(), g2 = this.highDensityStitchSolver?.visualize(), f2 = this.traceSimplificationSolver?.visualize(), _2 = this.traceWidthSolver?.visualize(), y2 = this.srj.outline, b2 = [];
    if (b2.push({ points: [{ x: this.srj.bounds?.minX ?? -50, y: this.srj.bounds?.minY ?? -50 }, { x: this.srj.bounds?.maxX ?? 50, y: this.srj.bounds?.minY ?? -50 }, { x: this.srj.bounds?.maxX ?? 50, y: this.srj.bounds?.maxY ?? 50 }, { x: this.srj.bounds?.minX ?? -50, y: this.srj.bounds?.maxY ?? 50 }, { x: this.srj.bounds?.minX ?? -50, y: this.srj.bounds?.minY ?? -50 }], strokeColor: "rgba(255,0,0,0.25)" }), y2 && y2.length >= 2) {
      const e51 = y2.map((e52) => ({ x: e52.x, y: e52.y }));
      e51.push({ ...e51[0] }), b2.push({ points: e51, strokeColor: "rgba(0, 136, 255, 0.95)" });
    }
    const x2 = Lo(this.srj), v2 = { points: [...this.srj.connections.flatMap((e51) => e51.pointsToConnect.map((t3) => ({ ...t3, layer: Bo(t3, this.srj.layerCount), label: `${e51.name} ${t3.pcb_port_id ?? ""}` })))], rects: [...(this.srj.obstacles ?? []).filter((e51) => !e51.isCopperPour).map((e51) => ({ ...e51, fill: e51.layers?.includes("top") ? "rgba(255,0,0,0.25)" : e51.layers?.includes("bottom") ? "rgba(0,0,255,0.25)" : "rgba(255,0,0,0.25)", layer: jo(e51, this.srj.layerCount), label: x2(e51) }))], lines: b2 }, I2 = [v2, e50, t2, n2, o3, i3, r3, a3, c3, l3, h2, d2, u2 ? pi(v2, u2) : null, p3 ? pi(v2, p3) : null, m2 ? pi(v2, m2) : null, g2, f2, s2, _2, this.solved ? pi({ lines: b2 }, Wo(this.getOutputSimpleRouteJson())) : null].filter(Boolean);
    return pi(...I2);
  }
  preview() {
    const e50 = this.highDensitySolver?.routes ?? this.simpleHighDensityRouteSolver?.routes ?? this.highDensityRouteSolver?.routes;
    if (e50) {
      const t2 = [];
      for (let n2 = e50.length - 1;n2 >= 0; n2--) {
        const o3 = e50[n2];
        if (t2.push({ points: o3.route.map((e51) => ({ x: e51.x, y: e51.y })), strokeColor: this.colorMap[o3.connectionName] }), t2.length > 200)
          break;
      }
      return { lines: t2 };
    }
    if (this.portPointPathingSolver) {
      const e51 = [];
      for (const t2 of this.portPointPathingSolver.connectionsWithResults)
        t2.path && e51.push({ points: t2.path.map((e52) => ({ x: e52.point.x, y: e52.point.y })), strokeColor: this.colorMap[t2.connection.name] });
      return { lines: e51 };
    }
    return this.netToPointPairsSolver ? this.netToPointPairsSolver?.visualize() : {};
  }
  _getOutputHdRoutes() {
    return this.traceWidthSolver?.hdRoutesWithWidths ?? this.traceKeepoutSolver?.redrawnHdRoutes ?? this.traceSimplificationSolver?.simplifiedHdRoutes ?? this.highDensityStitchSolver?.mergedHdRoutes ?? this.highDensitySolver?.routes ?? this.simpleHighDensityRouteSolver?.routes ?? this.highDensityRouteSolver?.routes;
  }
  getConnectedOffboardObstacles() {
    const e50 = {}, t2 = new Set(this.srj.connections.flatMap((e51) => e51.__rootConnectionNames ?? [e51.name]));
    for (const [n2, o3] of this.srj.obstacles.entries()) {
      if (!o3.offBoardConnectsTo?.length)
        continue;
      const i3 = o3.obstacleId ?? `__obs${n2}`;
      o3.obstacleId = i3;
      const r3 = this.connMap.getNetConnectedToId(i3);
      if (!r3)
        continue;
      const s2 = this.connMap.getIdsConnectedToNet(r3).find((e51) => t2.has(e51));
      s2 && (e50[i3] = s2);
    }
    return e50;
  }
  getOutputSimplifiedPcbTraces() {
    if (!this.solved || !this.highDensityRouteSolver && !this.simpleHighDensityRouteSolver && !this.highDensitySolver)
      throw new Error("Cannot get output before solving is complete");
    const e50 = [], t2 = this._getOutputHdRoutes();
    for (const n2 of this.netToPointPairsSolver?.newConnections ?? []) {
      const o3 = n2.__netConnectionName ?? this.srj.connections.find((e51) => e51.name === n2.name)?.__netConnectionName, i3 = t2.filter((e51) => e51.connectionName === n2.name);
      for (let t3 = 0;t3 < i3.length; t3++) {
        const r3 = i3[t3], s2 = { type: "pcb_trace", pcb_trace_id: `${n2.name}_${t3}`, connection_name: o3 ?? n2.__rootConnectionNames?.[0] ?? n2.name, route: Ro(r3, this.srj.layerCount) };
        e50.push(s2);
      }
    }
    return e50;
  }
  getOutputJumpers() {
    return this.highDensitySolver ? this.highDensitySolver.getOutputJumpers() : [];
  }
  getOutputSimpleRouteJson() {
    const e50 = this.getOutputJumpers();
    return { ...this.srj, traces: this.getOutputSimplifiedPcbTraces(), jumpers: e50.length > 0 ? e50 : undefined };
  }
};
var DG = (e50) => {
  const { candidates: t2, mapOfCapacityMeshNodeIdToRef: n2 } = e50;
  let o3 = true;
  for (const e51 of t2) {
    let t3 = false;
    e51.port.nodeIds.forEach((e52) => {
      const o4 = n2.get(e52);
      if (!o4)
        throw new Error(`Could not find capacity mesh node for id ${e52}`);
      o4._containsObstacle && (t3 = true);
    }), t3 || (o3 = false);
  }
  return o3;
};
var LG = (e50) => e50.depth + 1000 * e50.countOfCrampedPortPointsInPath;
var BG = class extends BaseSolver {
  constructor(e50) {
    if (super(), this.input = e50, this.input.depthLimit < 1)
      throw new Error("Depth limit must be at least 1");
    this._setup();
  }
  queue = [];
  resultExploredPortPoints = [];
  currentExploredPortPoints = null;
  visitedExploredPortPoints = new Map;
  getSolverName() {
    return "singleTargetNecessaryCrampedPortPointSolver";
  }
  _setup() {
    const e50 = this.input.mapOfCapacityMeshNodeIdToSegmentPortPoints.get(this.input.target.capacityMeshNodeId) ?? [];
    for (const t2 of e50) {
      if (this.input.shouldIgnoreCrampedPortPoints && t2.cramped)
        continue;
      const e51 = { port: t2, depth: 1, parent: null, countOfCrampedPortPointsInPath: t2.cramped ? 1 : 0 }, n2 = this.visitedExploredPortPoints.get(t2);
      (!n2 || this.getCandidateCost(e51) < this.getCandidateCost(n2)) && (this.visitedExploredPortPoints.set(t2, e51), this.queue.push(e51));
    }
  }
  _step() {
    if (this.queue.length === 0)
      return this.currentExploredPortPoints = null, void (this.solved = true);
    for (;this.queue.length > 0; ) {
      this.currentExploredPortPoints = this.queue.shift();
      if (this.visitedExploredPortPoints.get(this.currentExploredPortPoints.port) !== this.currentExploredPortPoints)
        continue;
      if (this.currentExploredPortPoints.depth === this.input.depthLimit) {
        this.resultExploredPortPoints.push(this.currentExploredPortPoints);
        continue;
      }
      const e50 = this.currentExploredPortPoints.port.nodeIds.map((e51) => {
        const t2 = this.input.mapOfCapacityMeshNodeIdToRef.get(e51);
        if (!t2)
          throw new Error(`Could not find capacity mesh node for id ${e51}`);
        return t2;
      }).flatMap((e51) => this.input.mapOfCapacityMeshNodeIdToSegmentPortPoints.get(e51.capacityMeshNodeId) ?? []);
      for (const t2 of e50) {
        if (this.input.shouldIgnoreCrampedPortPoints && t2.cramped)
          continue;
        const e51 = { port: t2, depth: this.currentExploredPortPoints.depth + 1, parent: this.currentExploredPortPoints, countOfCrampedPortPointsInPath: this.currentExploredPortPoints.countOfCrampedPortPointsInPath + (t2.cramped ? 1 : 0) }, n2 = this.visitedExploredPortPoints.get(t2);
        n2 && this.getCandidateCost(n2) <= this.getCandidateCost(e51) || (this.visitedExploredPortPoints.set(t2, e51), this.queue.push(e51));
      }
    }
    this.solved = true;
  }
  getCandidateCost(e50) {
    return e50.depth + 1000 * e50.countOfCrampedPortPointsInPath;
  }
  getOutput() {
    return this.resultExploredPortPoints;
  }
  visualize() {
    const e50 = { points: [], rects: [] };
    for (const t2 of this.visitedExploredPortPoints.keys())
      e50.points.push({ ...t2, color: t2.cramped ? "blue" : "green" });
    return e50;
  }
};
var FG = class extends BaseSolver {
  constructor(e50) {
    super(), this.input = e50, this._setup();
  }
  unprocessedTargets = [];
  targetNode = [];
  currentTarget;
  crampedPortPointsToKeep = new Set;
  candidatesAtDepth = [];
  isRunningCrampedPass = false;
  filteredOutput;
  activeSubSolver = null;
  nodeMap = new Map;
  mapOfCapacityMeshNodeIdToSegmentPortPoints = new Map;
  getSolverName() {
    return "multiTargetNecessaryCrampedPortPointSolver";
  }
  _setup() {
    this.targetNode = this.input.capacityMeshNodes.filter((e50) => e50._containsObstacle), this.targetNode = this.targetNode.filter((e50) => {
      for (const t2 of this.input.simpleRouteJson.connections)
        for (const n2 of t2.pointsToConnect)
          if (Oe(n2, e50) <= 0)
            return true;
      return false;
    }), this.unprocessedTargets = [...this.targetNode], this.unprocessedTargets.sort((e50, t2) => e50.center.x - t2.center.x);
    for (const e50 of this.input.capacityMeshNodes)
      this.nodeMap.set(e50.capacityMeshNodeId, e50);
    for (const e50 of this.input.sharedEdgeSegments)
      for (const t2 of e50.portPoints) {
        const e51 = t2.nodeIds;
        for (const n2 of e51) {
          if (!this.nodeMap.get(n2))
            throw new Error(`Could not find capacity mesh node for id ${n2}`);
          const e52 = this.mapOfCapacityMeshNodeIdToSegmentPortPoints.get(n2) || [];
          this.mapOfCapacityMeshNodeIdToSegmentPortPoints.set(n2, [...e52, t2]);
        }
      }
  }
  _step() {
    if (this.activeSubSolver) {
      if (this.activeSubSolver._step(), !this.activeSubSolver.solved)
        return;
      if (this.activeSubSolver.failed)
        return this.failed = true, void (this.error = this.activeSubSolver.error);
      if (this.candidatesAtDepth = this.activeSubSolver.getOutput(), this.activeSubSolver = null, !this.currentTarget)
        return this.failed = true, void (this.error = "Missing current capacity mesh node while finishing BFS");
      if (!this.isRunningCrampedPass) {
        return DG({ candidates: this.candidatesAtDepth, mapOfCapacityMeshNodeIdToRef: this.nodeMap }) || this.candidatesAtDepth.length === 0 ? (this.isRunningCrampedPass = true, void (this.activeSubSolver = new BG({ target: this.currentTarget, depthLimit: 3, shouldIgnoreCrampedPortPoints: false, mapOfCapacityMeshNodeIdToSegmentPortPoints: this.mapOfCapacityMeshNodeIdToSegmentPortPoints, mapOfCapacityMeshNodeIdToRef: this.nodeMap }))) : void (this.currentTarget = undefined);
      }
      let e50 = this.candidatesAtDepth.filter((e51) => {
        const t2 = e51.port;
        return t2.nodeIds.map((e52) => {
          const t3 = this.nodeMap.get(e52);
          if (!t3)
            throw this.failed = true, this.error = `Could not find capacity mesh node for id ${e52}`, new Error(`Could not find capacity mesh node for id ${e52}`);
          return t3;
        }).every((e52) => !e52._containsObstacle) && t2.cramped;
      });
      if (DG({ candidates: e50, mapOfCapacityMeshNodeIdToRef: this.nodeMap }) && (this.error = `All candidates are blocked by obstacles even after including cramped port points for capacity mesh node ${this.currentTarget.capacityMeshNodeId}`), this.candidatesAtDepth = [...e50].sort((e51, t2) => {
        const n2 = LG(e51) - LG(t2);
        return n2 !== 0 ? n2 : this.getCandidateExitCapacity(t2) - this.getCandidateExitCapacity(e51);
      }), this.candidatesAtDepth.length === 0)
        this.error = `No candidates found for capacity mesh node ${this.currentTarget.capacityMeshNodeId} even after including cramped port points`;
      else {
        const e51 = new Map;
        for (const t3 of this.candidatesAtDepth) {
          if (!t3.parent)
            throw new Error(`Missing parent for cramped escape candidate ${t3.port.segmentPortPointId}`);
          const n2 = `${t3.parent.port.segmentPortPointId}->${t3.port.segmentPortPointId}`;
          if (!e51.has(n2) && (e51.set(n2, t3), e51.size === 5))
            break;
        }
        const t2 = [...e51.values()];
        for (const e52 of t2)
          this.keepCandidatePath(e52);
      }
      return this.isRunningCrampedPass = false, void (this.currentTarget = undefined);
    }
    if (!this.currentTarget)
      return this.currentTarget = this.unprocessedTargets.shift(), this.currentTarget ? (this.isRunningCrampedPass = false, this.candidatesAtDepth = [], void (this.activeSubSolver = new BG({ target: this.currentTarget, depthLimit: 2, shouldIgnoreCrampedPortPoints: true, mapOfCapacityMeshNodeIdToSegmentPortPoints: this.mapOfCapacityMeshNodeIdToSegmentPortPoints, mapOfCapacityMeshNodeIdToRef: this.nodeMap }))) : void (this.solved = true);
  }
  getOutput() {
    return this.filteredOutput || (this.filteredOutput = this.input.sharedEdgeSegments.map((e50) => ({ ...e50, portPoints: e50.portPoints.flatMap((e51) => !e51.cramped || this.crampedPortPointsToKeep.has(e51) ? [e51] : this.isMultilayerEscapePort(e51) ? [{ ...e51, tinyHypergraphPortPenalty: 1000 }] : []) }))), this.filteredOutput;
  }
  getCandidateExitCapacity(e50) {
    if (!e50.parent)
      throw new Error(`Missing parent for cramped escape candidate ${e50.port.segmentPortPointId}`);
    const t2 = new Set(e50.parent.port.nodeIds), n2 = e50.port.nodeIds.filter((e51) => !t2.has(e51)).map((e51) => {
      const t3 = this.nodeMap.get(e51);
      if (!t3)
        throw new Error(`Could not find capacity mesh node for id ${e51}`);
      return t3;
    });
    if (n2.length === 0)
      throw new Error(`Could not find exit node for cramped escape candidate ${e50.port.segmentPortPointId}`);
    return Math.max(0, ...n2.map((e51) => e51.width * e51.height * e51.availableZ.length));
  }
  keepCandidatePath(e50) {
    this.crampedPortPointsToKeep.add(e50.port);
    let t2 = e50.parent;
    for (;t2; )
      this.crampedPortPointsToKeep.add(t2.port), t2 = t2.parent;
  }
  isMultilayerEscapePort(e50) {
    return e50.nodeIds.some((e51) => (this.nodeMap.get(e51)?.availableZ.length ?? 0) > 1);
  }
  visualize() {
    const e50 = { rects: [], points: [] };
    for (const t2 of this.targetNode)
      e50.rects.push({ ...t2, fill: this.currentTarget?.capacityMeshNodeId === t2.capacityMeshNodeId ? "rgba(255, 0, 0, 0.5)" : "rgba(255, 0, 0, 0.2)" });
    for (const t2 of this.candidatesAtDepth)
      e50.points.push({ ...t2.port, color: t2.port.cramped ? "blue" : "green" });
    for (const t2 of this.crampedPortPointsToKeep)
      e50.points.push({ ...t2, color: "blue" });
    return this.activeSubSolver ? Gn(e50, this.activeSubSolver.visualize()) : e50;
  }
};
var jG = (e50) => `${e50.x.toFixed(4)},${e50.y.toFixed(4)}`;
var $G = (e50) => e50.netIsAssignable === true && (e50.layers?.length ?? 0) > 1;
var YG = (e50, t2) => e50.connectedTo?.find((e51) => e51.startsWith("pcb_via")) ?? e50.obstacleId ?? `assignable_via_${t2}`;
var XG = (e50) => [...new Set(e50.obstacle.layers.map((t2) => mo(t2, e50.layerCount)))].sort((e51, t2) => e51 - t2);
var HG = (e50) => jG(e50.center);
var VG = (e50) => new Set(e50.filter($G).map(HG));
function WG(e50, t2) {
  if (e50 == null)
    throw new Error(t2);
}
function GG({ point: e50, layerCount: t2 }) {
  const n2 = So(e50).map((e51) => mo(e51, t2));
  return [...new Set(n2)];
}
function UG(e50) {
  if (Oe(e50.point, e50.region.d) <= 0.001) {
    return (e50.pointZLayers ?? GG(e50)).some((t2) => e50.region.d.availableZ.includes(t2));
  }
  return false;
}
function ZG({ region: e50, pointZLayers: t2 }) {
  return e50.ports.some((e51) => t2.includes(e51.d.z) && t2.some((t3) => e51.region1.d.availableZ.includes(t3)) && t2.some((t3) => e51.region2.d.availableZ.includes(t3)));
}
function qG({ graph: e50, point: t2, layerCount: n2 }) {
  const o3 = GG({ point: t2, layerCount: n2 });
  let i3;
  for (const r3 of e50.regions)
    if (UG({ point: t2, region: r3, layerCount: n2, pointZLayers: o3 }) && (i3 ??= r3, ZG({ region: r3, pointZLayers: o3 })))
      return r3;
  return i3;
}
var JG = (e50, t2) => {
  const n2 = e50.getNetConnectedToId(t2);
  if (!n2)
    throw new Error(`Could not resolve net ID for connection "${t2}"`);
  return n2;
};
var QG = (e50) => {
  const t2 = e50.graph.regions.filter((t3) => t3.d.availableZ.includes(e50.z) && !t3.d._assignableVia).map((t3) => ({ region: t3, distance: Oe(e50.point, t3.d) })).sort((e51, t3) => e51.distance - t3.distance || e51.region.d.width * e51.region.d.height - t3.region.d.width * t3.region.d.height), n2 = t2[0]?.distance;
  if (n2 === undefined)
    return [];
  const o3 = Math.max(n2 + 0.000001, e50.viaRadius + 0.15);
  return t2.filter((e51) => e51.distance <= o3).slice(0, 4).map((e51) => e51.region);
};
function KG(e50) {
  const t2 = { ports: [], regions: [] }, n2 = [], o3 = new Map;
  for (const n3 of e50.capacityMeshNodes) {
    const i3 = n3._connectedTo?.map((t3) => JG(e50.connectivityMap, t3)), r3 = { regionId: n3.capacityMeshNodeId, d: i3 ? { ...n3, _connectedTo: [...new Set(i3)] } : n3, ports: [] };
    t2.regions.push(r3), o3.has(r3.regionId) || o3.set(r3.regionId, r3);
  }
  for (const n3 of e50.segmentPortPoints) {
    const [e51, i3] = n3.nodeIds, r3 = o3.get(e51), s2 = o3.get(i3);
    WG(r3, `Could not find region with id ${e51} for segment port point ${n3.segmentPortPointId}`), WG(s2, `Could not find region with id ${i3} for segment port point ${n3.segmentPortPointId}`);
    for (const e52 of n3.availableZ) {
      const o4 = n3._preloadedTracePortAssignments?.filter((t3) => t3.z === e52), i4 = { portId: `${n3.segmentPortPointId}::${e52}`, x: n3.x, y: n3.y, z: e52, distToCentermostPortOnZ: n3.distToCentermostPortOnZ, cramped: n3.cramped, regions: [r3, s2], tinyHypergraphPortPenalty: n3.tinyHypergraphPortPenalty, _preloadedFixedNetIds: o4 && o4.length > 0 ? [...new Set(o4.map((e53) => e53.fixedNetId))].sort() : undefined, _preloadedTracePortAssignments: o4 }, a3 = { portId: n3.segmentPortPointId, d: i4, region1: r3, region2: s2 };
      t2.ports.push(a3), r3.ports.push(a3), s2.ports.push(a3);
    }
  }
  ((e51) => {
    for (const [t3, n3] of e51.assignableViaObstacles.entries()) {
      if (!$G(n3))
        continue;
      const o4 = XG({ obstacle: n3, layerCount: e51.layerCount });
      if (o4.length < 2)
        continue;
      const i3 = `assignable-via:${YG(n3, t3)}`, r3 = Math.min(n3.width, n3.height) / 2, s2 = { regionId: i3, d: { capacityMeshNodeId: i3, center: { ...n3.center }, width: n3.width, height: n3.height, layer: `z${o4.join(",")}`, availableZ: o4, _containsObstacle: false, _completelyInsideObstacle: false, _containsTarget: false, _assignableVia: true, _assignedViaObstacle: n3 }, ports: [] }, a3 = [];
      for (const t4 of o4)
        for (const o5 of QG({ graph: e51.graph, point: n3.center, z: t4, viaRadius: r3 })) {
          const e52 = { portId: `${i3}:port:${o5.regionId}:z${t4}`, x: n3.center.x, y: n3.center.y, z: t4, distToCentermostPortOnZ: 0, cramped: false, regions: [o5, s2] }, r4 = { portId: e52.portId, d: e52, region1: o5, region2: s2 };
          a3.push(r4), o5.ports.push(r4);
        }
      if (new Set(a3.map((e52) => e52.d.z)).size < 2)
        for (const e52 of a3)
          e52.region1.ports = e52.region1.ports.filter((t4) => t4 !== e52);
      else
        s2.ports.push(...a3), e51.graph.regions.push(s2), e51.graph.ports.push(...a3);
    }
  })({ graph: t2, assignableViaObstacles: e50.assignableViaObstacles ?? [], layerCount: e50.layerCount });
  for (const o4 of e50.simpleRouteJsonConnections) {
    const [i3, r3] = o4.pointsToConnect, s2 = qG({ graph: t2, point: i3, layerCount: e50.layerCount }), a3 = qG({ graph: t2, point: r3, layerCount: e50.layerCount });
    WG(s2, `Could not find start region for connection "${o4.name}"`), WG(a3, `Could not find end region for connection "${o4.name}"`), n2.push({ connectionId: o4.name, mutuallyConnectedNetworkId: JG(e50.connectivityMap, o4.name), startRegion: s2, endRegion: a3, simpleRouteConnection: o4 });
  }
  return { graph: t2, connections: n2 };
}
function eU(e50, t2) {
  const n2 = { lines: [], points: [] };
  if (!e50)
    return n2;
  let o3 = e50.shift();
  if (!o3)
    return n2;
  const i3 = [];
  n2.points.push({ ...o3.port.d, color: "rgb(255, 50, 50)", label: `g: ${o3.g}
h: ${o3.h}
f: ${o3.f}
ripRequired: ${o3.ripRequired}` });
  do {
    i3.push({ x: o3.port.d.x, y: o3.port.d.y, z: o3.port.d.z }), o3 = o3.parent;
  } while (o3);
  i3.reverse();
  const r3 = i3[0]?.z ?? 0;
  i3.unshift({ x: t2.x, y: t2.y, z: r3 });
  for (let e51 = 0;e51 < i3.length - 1; e51++) {
    const t3 = i3[e51], o4 = i3[e51 + 1];
    let r4;
    r4 = t3.z === o4.z ? t3.z === 0 ? undefined : "10 5" : "3 3 10", n2.lines.push({ points: [{ x: t3.x, y: t3.y }, { x: o4.x, y: o4.y }], strokeColor: "rgba(255, 250, 50, 1)", strokeWidth: 0.01, strokeDash: r4 });
  }
  for (const t3 of e50)
    n2.points.push({ ...t3.port.d, color: "rgb(0, 64, 255)", label: `${t3.port.portId}
g: ${t3.g}
h: ${t3.h}
f: ${t3.f}
ripRequired: ${t3.ripRequired}` });
  return n2;
}
function tU(e50, t2) {
  const n2 = { lines: [], points: [] };
  for (const o3 of e50) {
    const e51 = t2[o3.connection.connectionId] ?? "rgba(255, 50, 50, 1)", i3 = [{ x: o3.connection.startRegion.d.center.x, y: o3.connection.startRegion.d.center.y, z: o3.connection.startRegion.d?.availableZ?.[0] ?? 0 }];
    for (const e52 of o3.path)
      i3.push({ x: e52.port.d.x, y: e52.port.d.y, z: e52.port.d.z });
    i3.push({ x: o3.connection.endRegion.d.center.x, y: o3.connection.endRegion.d.center.y, z: o3.connection.endRegion.d?.availableZ?.[0] ?? 0 });
    for (let t3 = 0;t3 < i3.length - 1; t3++) {
      const o4 = i3[t3], r3 = i3[t3 + 1];
      let s2;
      s2 = o4.z === r3.z ? o4.z === 0 ? undefined : "10 5" : "3 3 10";
      const a3 = { points: [{ x: o4.x, y: o4.y }, { x: r3.x, y: r3.y }], strokeColor: e51, strokeWidth: 0.01, strokeDash: s2 };
      n2.lines.push(a3);
    }
  }
  return n2;
}
function nU(e50, t2) {
  const n2 = { lines: [], points: [] };
  for (const o3 of e50) {
    const e51 = o3.startRegion.d.center, i3 = o3.endRegion.d.center, r3 = (e51.x + i3.x) / 2, s2 = (e51.y + i3.y) / 2, a3 = t2[o3.connectionId] ?? "rgba(255, 50, 150, 0.8)";
    n2.points.push({ x: r3, y: s2, color: a3, label: o3.connectionId }), n2.lines.push({ points: [e51, i3], strokeColor: a3, strokeWidth: 0.1, strokeDash: (o3.startRegion.d?.availableZ?.[0] ?? 0) === 0 ? undefined : "10 5" });
  }
  return n2;
}
function oU(e50) {
  const t2 = { rects: [], points: [] };
  for (const n2 of e50.regions)
    t2.rects.push({ center: n2.d.center, width: n2.d.width, height: n2.d.height, fill: "rgba(200, 200, 200, 0.5)", label: n2.regionId });
  for (const n2 of e50.ports)
    t2.points.push({ x: n2.d.x, y: n2.d.y, color: "rgba(4, 90, 20, 0.3)", label: n2.portId });
  return t2;
}
var iU = class extends OY {
  constructor(e50) {
    super({ inputConnections: e50.connections, inputGraph: e50.graph, inputSolvedRoutes: e50.inputSolvedRoutes, greedyMultiplier: e50.weights.GREEDY_MULTIPLIER, ripCost: e50.weights.RIPPING_PF_COST, rippingEnabled: e50.flags.RIPPING_ENABLED }), this.params = e50, this.regionMemoryPfMap = e50.opts?.regionMemoryPfMap ?? new Map, this.baseRegionFailureCostMap = new Map, this.regionRipCountMap = new Map, this.totalRipCount = 0, e50.weights.MAX_ITERATIONS_PER_PATH > 0 && (this.MAX_ITERATIONS = e50.weights.MAX_ITERATIONS_PER_PATH * e50.effort);
  }
  regionMemoryPfMap;
  baseRegionFailureCostMap;
  regionRipCountMap;
  totalRipCount;
  estimateCostToEnd(e50) {
    const t2 = this.currentEndRegion;
    return WG(t2, "Current end region is undefined"), me(e50.d, t2.d.center);
  }
  computeH(e50) {
    const t2 = e50, n2 = this.computeDistanceTraveled(t2);
    if (this.params.weights.RANDOM_WALK_DISTANCE > 0 && n2 < this.params.weights.RANDOM_WALK_DISTANCE)
      return 0;
    const o3 = this.estimateCostToEnd(e50.port), i3 = (e50.port.d.distToCentermostPortOnZ - this.params.weights.CENTER_OFFSET_FOCUS_SHIFT) * this.params.weights.CENTER_OFFSET_DIST_PENALTY_FACTOR, r3 = e50.nextRegion?.regionId ?? e50.lastRegion?.regionId, s2 = r3 ? this.regionMemoryPfMap.get(r3) ?? 0 : 0;
    return o3 + i3 + this.computeMemoryPfPenalty(s2) + this.computeDeviation(e50) * this.params.weights.STRAIGHT_LINE_DEVIATION_PENALTY_FACTOR;
  }
  computeIncreasedRegionCostIfPortsAreUsed(e50, t2, n2) {
    const o3 = this.currentConnection;
    WG(o3, "Current connection is undefined");
    const i3 = this.getBaseRegionFailureCost(e50), r3 = this.computeRegionPfWithAdditionalSegment(e50, t2, n2, o3.connectionId, o3.mutuallyConnectedNetworkId);
    if (r3 >= this.NODE_MAX_PF)
      return this.params.weights.NODE_PF_MAX_PENALTY;
    const s2 = this.pfToFailureCost(r3), a3 = Math.max(0, s2 - i3);
    return Math.min(this.params.weights.NODE_PF_MAX_PENALTY, a3 * this.params.weights.NODE_PF_FACTOR);
  }
  computeG(e50) {
    const t2 = e50;
    let n2 = super.computeG(e50);
    return t2.lastPort && t2.lastPort.d.z !== t2.port.d.z && (n2 += this.params.weights.LAYER_CHANGE_COST), t2.nextRegion !== this.currentEndRegion ? n2 : n2 + this.computeEndRegionCloseCost(t2);
  }
  getPortUsagePenalty(e50) {
    const t2 = e50.assignment;
    if (!t2)
      return 0;
    const n2 = this.currentConnection?.mutuallyConnectedNetworkId;
    return t2.connection.mutuallyConnectedNetworkId === n2 ? 0 : 0.5 * Math.max(1, this.params.weights.NODE_PF_FACTOR) + this.params.weights.BASE_CANDIDATE_COST;
  }
  getRipsRequiredForPortUsage(e50, t2, n2) {
    const o3 = e50.assignments ?? [];
    if (o3.length === 0)
      return [];
    return o3.filter((e51) => e51.connection.mutuallyConnectedNetworkId !== this.currentConnection?.mutuallyConnectedNetworkId && (e51.regionPort1 !== t2 && e51.regionPort2 !== t2 && (e51.regionPort1 !== n2 && e51.regionPort2 !== n2 && he(e51.regionPort1.d, e51.regionPort2.d, t2.d, n2.d))));
  }
  selectCandidatesForEnteringRegion(e50) {
    const t2 = this.currentConnection?.startRegion, n2 = this.currentConnection?.endRegion;
    WG(t2, "Current connection or start region is undefined"), WG(n2, "Current connection or end region is undefined");
    const o3 = e50.filter((e51) => {
      const o4 = e51.nextRegion;
      return !o4?.d._containsObstacle || (o4 === t2 || o4 === n2);
    });
    let i3 = this.params.flags.FORCE_CENTER_FIRST ? this.getCenterFirstEnteringRegionCandidates(o3) : o3;
    const r3 = -this.params.weights.MIN_ALLOWED_BOARD_SCORE;
    if (r3 > 0) {
      const e51 = i3.filter((e52) => e52.g + e52.h <= r3);
      e51.length > 0 && (i3 = e51);
    }
    return i3;
  }
  routeSolvedHook(e50) {
    this.baseRegionFailureCostMap.clear();
    const t2 = new Set;
    for (const n3 of e50.path) {
      const e51 = n3.lastRegion;
      e51 && t2.add(e51);
    }
    for (const e51 of t2) {
      const t3 = this.computeRegionPfFromAssignments(e51);
      this.regionMemoryPfMap.set(e51.regionId, t3);
    }
    if (!e50.requiredRip)
      return;
    if (this.unprocessedConnections.length < 2)
      return;
    const [n2, ...o3] = this.unprocessedConnections;
    this.unprocessedConnections = [...o3, n2];
  }
  computeRoutesToRip(e50) {
    const t2 = super.computePortOverlapRoutes(e50), n2 = new Set(t2), o3 = new Map;
    e50.path.map((e51) => {
      if (!e51.lastPort || !e51.lastRegion)
        return;
      const t3 = this.getRipsRequiredForPortUsage(e51.lastRegion, e51.lastPort, e51.port);
      if (t3.length === 0)
        return null;
      const n3 = o3.get(e51.lastRegion) ?? new Set;
      for (const e52 of t3)
        n3.add(e52.solvedRoute);
      o3.set(e51.lastRegion, n3);
    });
    const i3 = e50.path.flatMap((e51) => e51.lastRegion ? [e51.lastRegion] : []), r3 = Array.from(new Set([...o3.keys(), ...i3])), s2 = this.params.weights.SHUFFLE_SEED + this.iterations + this.solvedRoutes.length + this.totalRipCount, a3 = Sr(r3, s2);
    for (const t3 of a3) {
      if (this.totalRipCount >= this.params.weights.MAX_RIPS)
        break;
      const o4 = this.getRegionRippingPfThreshold(t3.regionId);
      let i4 = this.computeRegionPf({ region: t3, newlySolvedRoute: e50, routesToRip: n2 });
      if (this.regionMemoryPfMap.set(t3.regionId, i4), i4 <= o4)
        continue;
      const r4 = new Set;
      let a4 = 0;
      for (;i4 > o4 && !(this.totalRipCount >= this.params.weights.MAX_RIPS); ) {
        if (!t3.assignments || t3.assignments.length === 0)
          throw new Error("We are trying to rip a region with no assignments, this should not happen");
        const o5 = t3.assignments.map((t4) => {
          const o6 = t4.solvedRoute;
          return t4.connection.connectionId === e50.connection.connectionId ? null : n2.has(o6) ? undefined : o6;
        }).filter((e51) => !!e51);
        if (o5.length === 0)
          break;
        const c3 = Sr(o5, s2 + a4 + r4.size)[0];
        if (!c3)
          break;
        r4.add(c3.connection), n2.add(c3), this.totalRipCount++, a4++, this.regionRipCountMap.set(t3.regionId, (this.regionRipCountMap.get(t3.regionId) ?? 0) + 1), i4 = this.computeRegionPf({ region: t3, newlySolvedRoute: e50, routesToRip: n2 }), this.regionMemoryPfMap.set(t3.regionId, i4);
      }
    }
    if (n2.size > t2.size) {
      if (this.totalRipCount >= this.params.weights.MAX_RIPS)
        return n2;
      const t3 = this.solvedRoutes.filter((t4) => !n2.has(t4) && t4.connection.connectionId !== e50.connection.connectionId);
      if (t3.length === 0)
        return n2;
      const o4 = Math.max(1, Math.floor(this.params.weights.RANDOM_RIP_FRACTION * t3.length)), i4 = Sr(t3, s2);
      let r4 = 0;
      for (const e51 of i4) {
        if (r4 >= o4)
          break;
        if (this.totalRipCount >= this.params.weights.MAX_RIPS)
          break;
        n2.has(e51) || (n2.add(e51), r4++, this.totalRipCount++);
      }
    }
    return n2;
  }
  computeDeviation(e50) {
    const t2 = this.currentConnection?.startRegion.d.center, n2 = this.currentConnection?.endRegion.d.center;
    WG(t2, "Current connection or start region is undefined"), WG(n2, "Current connection or end region is undefined");
    return pe(e50.port.d, t2, n2);
  }
  computeDistanceTraveled(e50) {
    let t2 = 0, n2 = e50;
    for (;n2?.parent; )
      t2 += me(n2.parent.port.d, n2.port.d), n2 = n2.parent;
    return t2;
  }
  computeMemoryPfPenalty(e50) {
    const t2 = Math.min(Math.max(e50, 0), 0.999999), n2 = Math.min(this.params.weights.NODE_PF_MAX_PENALTY, -Math.log(1 - t2));
    return n2 * this.params.weights.MEMORY_PF_FACTOR + n2 * this.params.weights.NODE_PF_FACTOR * 0.01;
  }
  computeEndRegionCloseCost(e50) {
    const t2 = this.currentConnection, n2 = this.currentEndRegion;
    WG(t2, "Current connection is undefined"), WG(n2, "Current end region is undefined");
    const o3 = t2.endRegion.d.center, i3 = { portId: `end-target:${t2.connectionId}`, region1: n2, region2: n2, d: { portId: `end-target:${t2.connectionId}`, x: o3.x, y: o3.y, z: e50.port.d.z, distToCentermostPortOnZ: 0, regions: [n2, n2] } };
    return this.computeIncreasedRegionCostIfPortsAreUsed(n2, e50.port, i3);
  }
  getCenterFirstEnteringRegionCandidates(e50) {
    const t2 = new Map;
    for (const n3 of e50) {
      const e51 = n3.port.d.z, o3 = t2.get(e51) ?? [];
      o3.push(n3), t2.set(e51, o3);
    }
    const n2 = [];
    for (const e51 of t2.values()) {
      const t3 = e51.sort((e52, t4) => e52.port.d.distToCentermostPortOnZ - t4.port.d.distToCentermostPortOnZ)[0];
      if (!t3)
        continue;
      if (this.isPortAvailableForCurrentNet(t3.port)) {
        n2.push(t3);
        continue;
      }
      const o3 = e51.sort((e52, t4) => e52.port.d.x !== t4.port.d.x ? e52.port.d.x - t4.port.d.x : e52.port.d.y - t4.port.d.y), i3 = [];
      let r3 = [];
      for (const e52 of o3)
        this.isPortAvailableForCurrentNet(e52.port) ? r3.push(e52) : r3.length > 0 && (i3.push(r3), r3 = []);
      r3.length > 0 && i3.push(r3);
      for (const e52 of i3)
        n2.push(e52[Math.floor(e52.length / 2)]);
    }
    return n2;
  }
  isPortAvailableForCurrentNet(e50) {
    const t2 = e50.assignment;
    if (!t2)
      return true;
    const n2 = this.currentConnection?.mutuallyConnectedNetworkId;
    return t2.connection.mutuallyConnectedNetworkId === n2;
  }
  computeRegionPfFromAssignments(e50) {
    const t2 = this.getRegionAssignedPortPoints(e50), n2 = { ...e50.d, portPoints: t2 }, o3 = Cz(n2), i3 = e50.d;
    return jz(i3, o3.numSameLayerCrossings, o3.numEntryExitLayerChanges, o3.numTransitionPairCrossings);
  }
  clampPf(e50) {
    return Math.min(Math.max(e50, 0), 0.999999);
  }
  get NODE_MAX_PF() {
    return Math.min(0.99999, 1 - Math.exp(-this.params.weights.NODE_PF_MAX_PENALTY));
  }
  pfToFailureCost(e50) {
    const t2 = this.clampPf(e50);
    return t2 >= this.NODE_MAX_PF ? this.params.weights.NODE_PF_MAX_PENALTY : -Math.log(1 - t2);
  }
  getBaseRegionFailureCost(e50) {
    const t2 = this.baseRegionFailureCostMap.get(e50.regionId);
    if (t2 != null)
      return t2;
    const n2 = this.computeRegionPfFromAssignments(e50), o3 = this.pfToFailureCost(n2);
    return this.baseRegionFailureCostMap.set(e50.regionId, o3), o3;
  }
  getRegionAssignedPortPoints(e50) {
    return (e50.assignments ?? []).flatMap((e51) => {
      const t2 = e51.regionPort1.d, n2 = e51.regionPort2.d, o3 = e51.connection.connectionId, i3 = e51.connection.simpleRouteConnection?.__rootConnectionNames?.[0];
      return [{ x: t2.x, y: t2.y, z: t2.z, connectionName: o3, rootConnectionName: i3 }, { x: n2.x, y: n2.y, z: n2.z, connectionName: o3, rootConnectionName: i3 }];
    });
  }
  computeRegionPfWithAdditionalSegment(e50, t2, n2, o3, i3) {
    const r3 = this.getRegionAssignedPortPoints(e50), s2 = [{ x: t2.d.x, y: t2.d.y, z: t2.d.z, connectionName: o3, rootConnectionName: i3 }, { x: n2.d.x, y: n2.d.y, z: n2.d.z, connectionName: o3, rootConnectionName: i3 }], a3 = { ...e50.d, portPoints: [...r3, ...s2] }, c3 = Cz(a3);
    return jz(e50.d, c3.numSameLayerCrossings, c3.numEntryExitLayerChanges, c3.numTransitionPairCrossings);
  }
  getRegionRippingPfThreshold(e50) {
    const t2 = this.regionRipCountMap.get(e50) ?? 0, n2 = Math.max(1, Math.floor(this.params.weights.MAX_RIPS / 10)), o3 = Math.min(1, t2 / n2);
    return (this.params.weights.START_RIPPING_PF_THRESHOLD || 0.3) * (1 - o3) + (this.params.weights.END_RIPPING_PF_THRESHOLD || 1) * o3;
  }
  computeRegionPf({ region: e50, newlySolvedRoute: t2, routesToRip: n2 }) {
    const o3 = [...(e50.assignments ?? []).filter((e51) => !n2.has(e51.solvedRoute)).flatMap((e51) => {
      const { regionPort1: t3, regionPort2: n3 } = e51, o4 = e51.connection.connectionId, i4 = e51.connection.simpleRouteConnection?.__rootConnectionNames?.[0];
      return [{ x: t3.d.x, y: t3.d.y, z: t3.d.z, connectionName: o4, rootConnectionName: i4 }, { x: n3.d.x, y: n3.d.y, z: n3.d.z, connectionName: o4, rootConnectionName: i4 }];
    }), ...t2.path.flatMap((n3) => {
      if (!n3.lastPort || n3.lastRegion !== e50)
        return [];
      const { lastPort: o4, port: i4 } = n3;
      return [{ x: o4.d.x, y: o4.d.y, z: o4.d.z, connectionName: t2.connection.connectionId, rootConnectionName: t2.connection.simpleRouteConnection?.__rootConnectionNames?.[0] }, { x: i4.d.x, y: i4.d.y, z: i4.d.z, connectionName: t2.connection.connectionId, rootConnectionName: t2.connection.simpleRouteConnection?.__rootConnectionNames?.[0] }];
    })], i3 = { capacityMeshNodeId: e50.d.capacityMeshNodeId, center: e50.d.center, width: e50.d.width, height: e50.d.height, portPoints: o3, availableZ: e50.d.availableZ }, r3 = Cz(i3), s2 = e50.d;
    return jz(s2, r3.numSameLayerCrossings, r3.numEntryExitLayerChanges, r3.numTransitionPairCrossings);
  }
  computeNodePf(e50) {
    const t2 = this.getOutput().nodesWithPortPoints.find((t3) => t3.capacityMeshNodeId === e50.capacityMeshNodeId), n2 = this.params.graph.regions.find((t3) => t3.d.capacityMeshNodeId === e50.capacityMeshNodeId);
    if (!t2 || !n2)
      return null;
    const o3 = Cz(t2);
    return jz(n2.d, o3.numSameLayerCrossings, o3.numEntryExitLayerChanges, o3.numTransitionPairCrossings);
  }
  getOutput() {
    new Map(this.params.graph.regions.map((e51) => [e51.regionId, e51]));
    const e50 = new Set;
    for (const t3 of this.params.connections)
      e50.add(t3.startRegion.regionId), e50.add(t3.endRegion.regionId);
    const t2 = new Map;
    for (const e51 of this.solvedRoutes) {
      const n3 = e51.path;
      if (n3.length === 0)
        continue;
      const o4 = n3[0]?.port, i3 = n3[n3.length - 1]?.port;
      if (!o4 || !i3)
        continue;
      const r3 = e51.connection.connectionId, s2 = e51.connection, a3 = s2.simpleRouteConnection?.__rootConnectionNames?.[0], c3 = e51.connection.startRegion.regionId, l3 = e51.connection.endRegion.regionId, h2 = t2.get(c3) ?? [];
      h2.push({ portPointId: o4.d.portId, x: o4.d.x, y: o4.d.y, z: o4.d.z, connectionName: r3, rootConnectionName: a3 }), t2.set(c3, h2);
      const d2 = t2.get(l3) ?? [];
      d2.push({ portPointId: i3.d.portId, x: i3.d.x, y: i3.d.y, z: i3.d.z, connectionName: r3, rootConnectionName: a3 }), t2.set(l3, d2);
    }
    const n2 = [], o3 = [];
    for (const i3 of this.params.graph.regions) {
      const r3 = (i3.assignments ?? []).flatMap((e51) => {
        const t3 = e51.connection.connectionId, n3 = e51.connection.simpleRouteConnection?.__rootConnectionNames?.[0];
        return [{ portPointId: e51.regionPort1.d.portId, x: e51.regionPort1.d.x, y: e51.regionPort1.d.y, z: e51.regionPort1.d.z, connectionName: t3, rootConnectionName: n3, nextPortPointId: e51.regionPort2.d.portId }, { portPointId: e51.regionPort2.d.portId, x: e51.regionPort2.d.x, y: e51.regionPort2.d.y, z: e51.regionPort2.d.z, connectionName: t3, rootConnectionName: n3, prevPortPointId: e51.regionPort1.d.portId }];
      }), s2 = [];
      if (i3.d._containsObstacle && e50.has(i3.regionId)) {
        const e51 = t2.get(i3.regionId) ?? [], n3 = [];
        for (const t3 of e51) {
          r3.some((e52) => e52.connectionName === t3.connectionName && e52.rootConnectionName === t3.rootConnectionName && e52.portPointId === t3.portPointId) || n3.push(t3);
        }
        r3.push(...n3);
        const o4 = new Map;
        for (const e52 of r3) {
          const t3 = `${e52.connectionName}::${e52.rootConnectionName ?? ""}`, n4 = o4.get(t3) ?? [];
          n4.push(e52), o4.set(t3, n4);
        }
        for (const [e52, t3] of o4.entries()) {
          const [n4, o5 = ""] = e52.split("::"), r4 = t3[0];
          if (!r4)
            continue;
          const a4 = { portPointId: `center:${i3.regionId}:${n4}:${o5}`, x: i3.d.center.x, y: i3.d.center.y, z: r4.z, connectionName: n4, rootConnectionName: o5 || undefined };
          if (t3.length >= 2) {
            const e53 = t3[t3.length - 1];
            r4.portPointId && (r4.nextPortPointId = a4.portPointId, a4.prevPortPointId = r4.portPointId), e53.portPointId && (e53.prevPortPointId = a4.portPointId, a4.nextPortPointId = e53.portPointId);
          }
          s2.push(a4);
        }
      }
      const a3 = [...r3, ...s2];
      a3.length > 0 && n2.push({ capacityMeshNodeId: i3.d.capacityMeshNodeId, center: i3.d.center, width: i3.d.width, height: i3.d.height, portPoints: a3, availableZ: i3.d.availableZ });
      const c3 = i3.ports.map((e51) => {
        const t3 = e51.d, n3 = e51.d.regions.some((e52) => Boolean(e52.d._offBoardConnectionId));
        return { portPointId: e51.d.portId, x: e51.d.x, y: e51.d.y, z: e51.d.z, prevPortPointId: t3.prevPortPointId, nextPortPointId: t3.nextPortPointId, connectionNodeIds: e51.d.regions.map((e52) => e52.regionId), distToCentermostPortOnZ: e51.d.distToCentermostPortOnZ, connectsToOffBoardNode: n3 };
      });
      o3.push({ capacityMeshNodeId: i3.d.capacityMeshNodeId, center: i3.d.center, width: i3.d.width, height: i3.d.height, portPoints: c3, availableZ: i3.d.availableZ, _containsObstacle: i3.d._containsObstacle, _containsTarget: i3.d._containsTarget, _offBoardConnectionId: i3.d._offBoardConnectionId, _offBoardConnectedCapacityMeshNodeIds: i3.d._offBoardConnectedCapacityMeshNodeIds });
    }
    return { nodesWithPortPoints: n2, inputNodeWithPortPoints: o3 };
  }
  visualize() {
    return function(e50) {
      let t2 = {};
      return t2 = e50.reduce((e51, t3) => e51 && t3 ? Gn(e51, t3) : {}, t2), t2 || {};
    }([oU(this.params.graph), this.visualizePfOverlay(), nU(this.params.connections, this.params.colorMap ?? {}), eU(this.candidateQueue.peekMany(100), this.currentConnection?.startRegion.d.center), tU(this.solvedRoutes, this.params.colorMap ?? {})]);
  }
  visualizePfOverlay() {
    const e50 = this.getOutput(), t2 = e50?.inputNodeWithPortPoints ?? [], n2 = new Map((e50?.nodesWithPortPoints ?? []).map((e51) => [e51.capacityMeshNodeId, e51])), o3 = { rects: [] };
    for (const e51 of t2) {
      const t3 = this.computeNodePf(e51), i3 = t3 ?? 0, r3 = n2.get(e51.capacityMeshNodeId), s2 = r3 ? Cz(r3) : { numSameLayerCrossings: 0, numEntryExitLayerChanges: 0, numTransitionPairCrossings: 0 }, a3 = Math.min(255, Math.floor(512 * i3)), c3 = Math.max(0, 255 - Math.floor(512 * i3));
      let l3 = `rgba(${a3}, ${c3}, ${c3}, ${i3 < 0.001 ? "0.1" : "0.3"})`;
      e51._containsObstacle && (l3 = "rgba(255, 0, 0, 0.3)"), e51._offBoardConnectedCapacityMeshNodeIds?.length && (l3 = "rgba(255, 165, 0, 0.3)"), o3.rects.push({ center: e51.center, width: e51.width - 0.2, height: e51.height - 0.2, layer: `z${e51?.availableZ?.join(",")}`, fill: l3, label: `${e51.capacityMeshNodeId}
pf: ${t3 === null ? "n/a" : t3.toFixed(3)}
xSame: ${s2.numSameLayerCrossings}, xLC: ${s2.numEntryExitLayerChanges}, xTransition: ${s2.numTransitionPairCrossings}` });
    }
    return o3;
  }
};
var rU = (e50) => {
  if (!e50.assignments || e50.assignments.length === 0)
    return e50.d?.assignment ? 0 : 1;
  const t2 = e50.assignments.flatMap((e51) => {
    const t3 = e51.regionPort1.d, n3 = e51.regionPort2.d, o4 = e51.connection.connectionId, i3 = e51.connection, r3 = i3.simpleRouteConnection?.__rootConnectionNames?.[0];
    return [{ x: t3.x, y: t3.y, z: t3.z, connectionName: o4, rootConnectionName: r3 }, { x: n3.x, y: n3.y, z: n3.z, connectionName: o4, rootConnectionName: r3 }];
  }), n2 = { ...e50.d, portPoints: t2 }, o3 = Cz(n2);
  return jz(e50.d, o3.numSameLayerCrossings, o3.numEntryExitLayerChanges, o3.numTransitionPairCrossings);
};
function sU(e50, t2, n2, o3 = {}) {
  return { solverName: e50, solverClass: t2, getConstructorParams: n2, onSolved: o3.onSolved };
}
var aU = class extends ni {
  constructor(e50, t2 = {}) {
    super(), this.srj = e50, this.opts = t2, this.srj = e50, this.opts = { ...t2 }, this.viaDiameter = Yo(e50).padDiameter, this.minTraceWidth = e50.minTraceWidth;
    const n2 = this.opts;
    if (this.effort = n2.effort ?? 1, this.MAX_ITERATIONS = 1e8 * this.effort, n2.capacityDepth === undefined) {
      const t3 = e50.bounds.maxX - e50.bounds.minX, o3 = e50.bounds.maxY - e50.bounds.minY, i3 = Math.max(t3, o3), r3 = n2.targetMinCapacity ?? 0.5;
      n2.capacityDepth = Fz(i3, r3);
    }
    this.connMap = ei(e50), this.colorMap = Eo(e50, this.connMap), this.cacheProvider = n2.cacheProvider === undefined ? no() : n2.cacheProvider === null ? null : n2.cacheProvider, this.startTimeOfPhase = {}, this.endTimeOfPhase = {}, this.timeSpentOnPhase = {};
  }
  netToPointPairsSolver;
  nodeSolver;
  nodeTargetMerger;
  edgeSolver;
  colorMap;
  highDensityRouteSolver;
  highDensityStitchSolver;
  singleLayerNodeMerger;
  strawSolver;
  deadEndSolver;
  traceSimplificationSolver;
  availableSegmentPointSolver;
  portPointPathingSolver;
  multiSectionPortPointOptimizer;
  uniformPortDistributionSolver;
  traceWidthSolver;
  necessaryCrampedPortPointSolver;
  hyperGraphSectionOptimizer;
  viaDiameter;
  minTraceWidth;
  effort;
  startTimeOfPhase;
  endTimeOfPhase;
  timeSpentOnPhase;
  activeSubSolver = null;
  connMap;
  srjWithPointPairs;
  capacityNodes = null;
  capacityEdges = null;
  cacheProvider = null;
  pipelineDef = [sU("netToPointPairsSolver", pB, (e50) => [e50.srj, e50.colorMap, ti(e50.srj)], { onSolved: (e50) => {
    e50.srjWithPointPairs = e50.netToPointPairsSolver?.getNewSimpleRouteJson(), e50.colorMap = Eo(e50.srjWithPointPairs, this.connMap), e50.connMap = ei(e50.srjWithPointPairs);
  } }), sU("nodeSolver", Jn, (e50) => [{ simpleRouteJson: e50.srjWithPointPairs, maxGapFillPasses: 4 }], { onSolved: (e50) => {
    e50.capacityNodes = e50.nodeSolver?.getOutput().meshNodes ?? [];
  } }), sU("edgeSolver", ui, (e50) => [e50.capacityNodes], { onSolved: (e50) => {
    e50.capacityEdges = e50.edgeSolver?.edges;
  } }), sU("availableSegmentPointSolver", ii, (e50) => [{ nodes: e50.capacityNodes, edges: e50.capacityEdges || [], traceWidth: e50.minTraceWidth, colorMap: e50.colorMap, shouldReturnCrampedPortPoints: true }]), sU("necessaryCrampedPortPointSolver", FG, (e50) => [{ capacityMeshNodes: e50.capacityNodes, sharedEdgeSegments: e50.availableSegmentPointSolver.getOutput(), simpleRouteJson: e50.srjWithPointPairs }]), sU("portPointPathingSolver", iU, (e50) => {
    const t2 = e50.necessaryCrampedPortPointSolver?.getOutput() ?? e50.availableSegmentPointSolver.getOutput(), { graph: n2, connections: o3 } = KG({ capacityMeshNodes: e50.capacityNodes, layerCount: e50.srj.layerCount, connectivityMap: e50.connMap, segmentPortPoints: t2.flatMap((e51) => e51.portPoints), simpleRouteJsonConnections: e50.srjWithPointPairs.connections });
    return [{ graph: n2, connections: o3, layerCount: e50.srj.layerCount, effort: Math.min(1, e50.effort), flags: { FORCE_CENTER_FIRST: true, RIPPING_ENABLED: true }, weights: { SHUFFLE_SEED: 0, MEMORY_PF_FACTOR: 4, CENTER_OFFSET_DIST_PENALTY_FACTOR: 0, CENTER_OFFSET_FOCUS_SHIFT: 0, NODE_PF_FACTOR: 0, LAYER_CHANGE_COST: 0, RIPPING_PF_COST: 0, NODE_PF_MAX_PENALTY: 100, BASE_CANDIDATE_COST: 0.6, MAX_ITERATIONS_PER_PATH: 0, RANDOM_WALK_DISTANCE: 0, START_RIPPING_PF_THRESHOLD: 0.3, END_RIPPING_PF_THRESHOLD: 1, MAX_RIPS: 1000, RANDOM_RIP_FRACTION: 0.3, STRAIGHT_LINE_DEVIATION_PENALTY_FACTOR: 4, GREEDY_MULTIPLIER: 0.7, MIN_ALLOWED_BOARD_SCORE: -1e4 } }];
  }), sU("hyperGraphSectionOptimizer", tX, (e50) => {
    const t2 = e50.portPointPathingSolver;
    return [{ hyperGraphSolver: t2, inputSolvedRoutes: t2.solvedRoutes, expansionHopsFromCentralRegion: 1, createHyperGraphSolver: (t3) => new iU({ graph: t3.inputGraph, connections: t3.inputConnections, inputSolvedRoutes: t3.inputSolvedRoutes, layerCount: e50.srj.layerCount, effort: Math.min(1, e50.effort), flags: { FORCE_CENTER_FIRST: true, RIPPING_ENABLED: true }, weights: { SHUFFLE_SEED: 0, MEMORY_PF_FACTOR: 4, CENTER_OFFSET_DIST_PENALTY_FACTOR: 0, CENTER_OFFSET_FOCUS_SHIFT: 0, NODE_PF_FACTOR: 0, LAYER_CHANGE_COST: 0, RIPPING_PF_COST: 0, NODE_PF_MAX_PENALTY: 100, BASE_CANDIDATE_COST: 0.6, MAX_ITERATIONS_PER_PATH: 0, RANDOM_WALK_DISTANCE: 0, START_RIPPING_PF_THRESHOLD: 0.3, END_RIPPING_PF_THRESHOLD: 1, MAX_RIPS: 1000, RANDOM_RIP_FRACTION: 0.3, STRAIGHT_LINE_DEVIATION_PENALTY_FACTOR: 4, GREEDY_MULTIPLIER: 0.7, MIN_ALLOWED_BOARD_SCORE: -1e4 } }), regionCost: rU, effort: Math.min(1, e50.effort), ACCEPTABLE_REGION_COST: 0.1, MAX_ATTEMPTS_PER_REGION: Math.max(3, 3 * Math.min(1, e50.effort)), MAX_ATTEMPTS_PER_SECTION: Math.max(50, 50 * Math.min(1, e50.effort)), FRACTION_TO_REPLACE: 1, alwaysRipConflicts: true }];
  }), sU("uniformPortDistributionSolver", bo, (e50) => [{ nodeWithPortPoints: e50.portPointPathingSolver?.getOutput().nodesWithPortPoints ?? [], inputNodesWithPortPoints: e50.portPointPathingSolver?.getOutput().inputNodeWithPortPoints ?? [], minTraceWidth: e50.minTraceWidth, obstacles: e50.srj.obstacles, layerCount: e50.srj.layerCount }]), sU("highDensityRouteSolver", Dz, (e50) => [{ nodePortPoints: e50.uniformPortDistributionSolver?.getOutput() ?? [], nodePfById: new Map((e50.portPointPathingSolver?.getOutput().inputNodeWithPortPoints ?? []).map((t2) => [t2.capacityMeshNodeId, e50.portPointPathingSolver?.computeNodePf(t2) ?? null])), colorMap: e50.colorMap, connMap: e50.connMap, viaDiameter: e50.viaDiameter, traceWidth: e50.minTraceWidth }]), sU("highDensityStitchSolver", IB, (e50) => [{ connections: e50.srjWithPointPairs.connections, hdRoutes: e50.highDensityRouteSolver.routes, colorMap: e50.colorMap, layerCount: e50.srj.layerCount, defaultViaDiameter: e50.viaDiameter }]), sU("traceSimplificationSolver", WF, (e50) => [{ hdRoutes: e50.highDensityStitchSolver.mergedHdRoutes, obstacles: e50.srj.obstacles, connMap: e50.connMap, colorMap: e50.colorMap, outline: e50.srj.outline, defaultViaDiameter: e50.viaDiameter, layerCount: e50.srj.layerCount, iterations: 2 }]), sU("traceWidthSolver", QF, (e50) => [{ hdRoutes: e50.traceSimplificationSolver.simplifiedHdRoutes, obstacles: e50.srj.obstacles, connMap: e50.connMap, colorMap: e50.colorMap, minTraceWidth: e50.minTraceWidth, connection: e50.srj.connections, layerCount: e50.srj.layerCount }])];
  getConstructorParams() {
    return [this.srj, this.opts];
  }
  currentPipelineStepIndex = 0;
  _step() {
    const e50 = this.pipelineDef[this.currentPipelineStepIndex];
    if (!e50)
      return void (this.solved = true);
    if (this.activeSubSolver)
      return this.activeSubSolver.step(), void (this.activeSubSolver.solved ? (this.endTimeOfPhase[e50.solverName] = performance.now(), this.timeSpentOnPhase[e50.solverName] = this.endTimeOfPhase[e50.solverName] - this.startTimeOfPhase[e50.solverName], e50.onSolved?.(this), this.activeSubSolver = null, this.currentPipelineStepIndex++) : this.activeSubSolver.failed && (this.error = this.activeSubSolver?.error, this.failed = true, this.activeSubSolver = null));
    const t2 = e50.getConstructorParams(this);
    this.activeSubSolver = new e50.solverClass(...t2), this[e50.solverName] = this.activeSubSolver, this.timeSpentOnPhase[e50.solverName] = 0, this.startTimeOfPhase[e50.solverName] = performance.now();
  }
  solveUntilPhase(e50) {
    for (;this.getCurrentPhase() !== e50; )
      this.step();
  }
  getCurrentPhase() {
    return this.pipelineDef[this.currentPipelineStepIndex]?.solverName ?? "none";
  }
  visualize() {
    if (!this.solved && this.activeSubSolver)
      return this.activeSubSolver.visualize();
    const e50 = this.netToPointPairsSolver?.visualize(), t2 = this.nodeSolver?.visualize(), n2 = this.nodeTargetMerger?.visualize(), o3 = this.singleLayerNodeMerger?.visualize(), i3 = this.strawSolver?.visualize(), r3 = this.edgeSolver?.visualize(), s2 = this.deadEndSolver?.visualize(), a3 = this.availableSegmentPointSolver?.visualize(), c3 = this.portPointPathingSolver?.visualize(), l3 = this.multiSectionPortPointOptimizer?.visualize(), h2 = this.uniformPortDistributionSolver?.visualize(), d2 = this.highDensityRouteSolver?.visualize(), u2 = this.highDensityStitchSolver?.visualize(), p3 = this.traceSimplificationSolver?.visualize(), m2 = this.necessaryCrampedPortPointSolver?.visualize(), g2 = this.highDensityRouteSolver?.visualize(), f2 = this.srj.outline, _2 = [];
    if (_2.push({ points: [{ x: this.srj.bounds?.minX ?? -50, y: this.srj.bounds?.minY ?? -50 }, { x: this.srj.bounds?.maxX ?? 50, y: this.srj.bounds?.minY ?? -50 }, { x: this.srj.bounds?.maxX ?? 50, y: this.srj.bounds?.maxY ?? 50 }, { x: this.srj.bounds?.minX ?? -50, y: this.srj.bounds?.maxY ?? 50 }, { x: this.srj.bounds?.minX ?? -50, y: this.srj.bounds?.minY ?? -50 }], strokeColor: "rgba(255,0,0,0.25)" }), f2 && f2.length >= 2) {
      const e51 = f2.map((e52) => ({ x: e52.x, y: e52.y }));
      e51.push({ ...e51[0] }), _2.push({ points: e51, strokeColor: "rgba(0, 136, 255, 0.95)" });
    }
    const y2 = Lo(this.srj), b2 = { points: [...this.srj.connections.flatMap((e51) => e51.pointsToConnect.map((t3) => ({ ...t3, layer: Bo(t3, this.srj.layerCount), label: `${e51.name} ${t3.pcb_port_id ?? ""}` })))], rects: [...(this.srj.obstacles ?? []).filter((e51) => !e51.isCopperPour).map((e51) => ({ ...e51, fill: e51.layers?.includes("top") ? "rgba(255,0,0,0.25)" : e51.layers?.includes("bottom") ? "rgba(0,0,255,0.25)" : "rgba(255,0,0,0.25)", layer: jo(e51, this.srj.layerCount), label: y2(e51) }))], lines: _2 }, x2 = [b2, e50, t2, n2, o3, i3, r3, s2, a3, m2, c3, g2, l3, h2, d2 ? pi(b2, d2) : null, u2, p3, this.solved ? pi({ lines: _2 }, Wo(this.getOutputSimpleRouteJson())) : null].filter(Boolean);
    return pi(...x2);
  }
  preview() {
    if (this.highDensityRouteSolver) {
      const e50 = [];
      for (let t2 = this.highDensityRouteSolver.routes.length - 1;t2 >= 0; t2--) {
        const n2 = this.highDensityRouteSolver.routes[t2];
        if (e50.push({ points: n2.route.map((e51) => ({ x: e51.x, y: e51.y })), strokeColor: this.colorMap[n2.connectionName] }), e50.length > 200)
          break;
      }
      return { lines: e50 };
    }
    return this.netToPointPairsSolver ? this.netToPointPairsSolver.visualize() : {};
  }
  _getOutputHdRoutes() {
    return this.traceWidthSolver?.getHdRoutesWithWidths() ?? this.traceSimplificationSolver?.simplifiedHdRoutes ?? this.highDensityStitchSolver.mergedHdRoutes;
  }
  getOutputSimplifiedPcbTraces() {
    if (!this.solved || !this.highDensityRouteSolver)
      throw new Error("Cannot get output before solving is complete");
    const e50 = [], t2 = this._getOutputHdRoutes();
    for (const n2 of this.netToPointPairsSolver?.newConnections ?? []) {
      const o3 = n2.__netConnectionName ?? this.srj.connections.find((e51) => e51.name === n2.name)?.__netConnectionName, i3 = t2.filter((e51) => e51.connectionName === n2.name);
      for (let t3 = 0;t3 < i3.length; t3++) {
        const r3 = i3[t3], s2 = { type: "pcb_trace", pcb_trace_id: `${n2.name}_${t3}`, connection_name: o3 ?? n2.__rootConnectionNames?.[0] ?? n2.name, route: Ro(r3, this.srj.layerCount) };
        e50.push(s2);
      }
    }
    return e50;
  }
  getOutputSimpleRouteJson() {
    return { ...this.srj, traces: this.getOutputSimplifiedPcbTraces() };
  }
};
var cU = class {
  MAX_ITERATIONS = 1000;
  solved = false;
  failed = false;
  iterations = 0;
  progress = 0;
  error = null;
  activeSubSolver;
  failedSubSolvers;
  timeToSolve;
  stats = {};
  pendingEffects;
  cacheHit;
  cacheKey;
  cacheToSolveSpaceTransform;
  getSolverName() {
    return this.constructor.name;
  }
  step() {
    if (!this.solved && !this.failed) {
      this.iterations++;
      try {
        this._step();
      } catch (e50) {
        throw this.error = `${this.getSolverName()} error: ${e50}`, console.error(this.error), this.failed = true, e50;
      }
      !this.solved && this.iterations > this.MAX_ITERATIONS && this.tryFinalAcceptance(), !this.solved && this.iterations > this.MAX_ITERATIONS && (this.error = `${this.getSolverName()} ran out of iterations (MAX_ITERATIONS=${this.MAX_ITERATIONS})`, this.failed = true), "computeProgress" in this && (this.progress = this.computeProgress());
    }
  }
  _step() {}
  getConstructorParams() {
    throw new Error("getConstructorParams not implemented");
  }
  solve() {
    const e50 = Date.now();
    for (;!this.solved && !this.failed; )
      this.step();
    const t2 = Date.now();
    this.timeToSolve = t2 - e50;
  }
  visualize() {
    return { lines: [], points: [], rects: [], circles: [] };
  }
  tryFinalAcceptance() {}
  preview() {
    return { lines: [], points: [], rects: [], circles: [] };
  }
};
var lU = (e50, t2) => {
  const n2 = (e51) => e51 === " " || e51 === `
` || e51 === "\r" || e51 === "\t", o3 = (e51) => {
    let t3 = 0, o4 = e51.length;
    for (;t3 < o4 && n2(e51[t3]); )
      t3 += 1;
    for (;o4 > t3 && n2(e51[o4 - 1]); )
      o4 -= 1;
    return e51.slice(t3, o4);
  }, i3 = (e51) => {
    const t3 = [];
    let n3 = 0, i4 = 0;
    for (let r4 = 0;r4 < e51.length; r4 += 1) {
      const s3 = e51[r4];
      s3 !== "(" ? s3 !== ")" ? s3 === "," && i4 === 0 && (t3.push(o3(e51.slice(n3, r4))), n3 = r4 + 1) : i4 > 0 && (i4 -= 1) : i4 += 1;
    }
    return t3.push(o3(e51.slice(n3))), t3;
  }, r3 = (e51) => {
    return `${t3 = e51, Math.min(1, Math.max(0, t3))}`;
    var t3;
  }, s2 = ((e51) => {
    const t3 = o3(e51);
    if (!t3.startsWith("#"))
      return null;
    const n3 = t3.slice(1);
    if (n3.length !== 3 && n3.length !== 6)
      return null;
    for (const e52 of n3) {
      const t4 = e52.toLowerCase();
      if (!(t4 >= "0" && t4 <= "9") && !(t4 >= "a" && t4 <= "f"))
        return null;
    }
    if (n3.length === 3) {
      const [e52, t4, o4] = n3;
      return { r: Number.parseInt(e52 + e52, 16), g: Number.parseInt(t4 + t4, 16), b: Number.parseInt(o4 + o4, 16) };
    }
    return { r: Number.parseInt(n3.slice(0, 2), 16), g: Number.parseInt(n3.slice(2, 4), 16), b: Number.parseInt(n3.slice(4, 6), 16) };
  })(t2);
  if (s2)
    return `rgba(${s2.r}, ${s2.g}, ${s2.b}, ${r3(1 - e50)})`;
  const a3 = ((e51) => {
    const t3 = o3(e51), n3 = t3.indexOf("(");
    return n3 <= 0 || t3[t3.length - 1] !== ")" ? null : { name: o3(t3.slice(0, n3)).toLowerCase(), args: i3(t3.slice(n3 + 1, -1)) };
  })(t2);
  if (!a3)
    return t2;
  const { name: c3, args: l3 } = a3;
  if (c3 === "hsl" || c3 === "rgb")
    return l3.length !== 3 ? t2 : `${c3}a(${l3[0]}, ${l3[1]}, ${l3[2]}, ${r3(1 - e50)})`;
  if (c3 === "hsla" || c3 === "rgba") {
    if (l3.length !== 4)
      return t2;
    const n3 = ((e51) => {
      const t3 = o3(e51);
      if (!t3)
        return null;
      const n4 = Number.parseFloat(t3);
      return Number.isFinite(n4) ? n4 : null;
    })(l3[3]);
    return n3 === null ? t2 : `${c3}(${l3[0]}, ${l3[1]}, ${l3[2]}, ${r3(n3 - e50)})`;
  }
  return t2;
};
var hU = (e50, t2) => {
  try {
    return lU(t2, e50);
  } catch (t3) {
    return console.error(t3), e50;
  }
};
var dU = (e50) => e50.rootConnectionName ?? e50.connectionName;
var uU = (e50) => {
  const t2 = [];
  for (let n2 = 0;n2 < e50.route.length - 1; n2 += 1) {
    const o3 = e50.route[n2], i3 = e50.route[n2 + 1];
    if (!o3 || !i3 || o3.z === i3.z)
      continue;
    if (Math.abs(o3.x - i3.x) > 0.000001 || Math.abs(o3.y - i3.y) > 0.000001)
      continue;
    const r3 = { x: Math.round(1000 * o3.x) / 1000, y: Math.round(1000 * o3.y) / 1000 }, s2 = t2.at(-1);
    s2 && s2.x === r3.x && s2.y === r3.y || t2.push(r3);
  }
  return t2;
};
var pU = (e50, t2, n2 = 0.001) => Math.abs(e50.x - t2.x) <= n2 && Math.abs(e50.y - t2.y) <= n2;
var mU = (e50, t2) => ({ minX: e50.center.x - e50.width / 2 + t2, maxX: e50.center.x + e50.width / 2 - t2, minY: e50.center.y - e50.height / 2 + t2, maxY: e50.center.y + e50.height / 2 - t2 });
var gU = (e50, t2) => {
  const n2 = Math.max(Math.abs(e50), Math.abs(t2));
  if (n2 === 0 || n2 === Number.POSITIVE_INFINITY)
    return n2;
  const o3 = e50 / n2, i3 = t2 / n2;
  return n2 * Math.sqrt(o3 * o3 + i3 * i3);
};
var fU = (e50, t2) => ({ x: e50.x - t2.x, y: e50.y - t2.y });
var _U = (e50, t2) => e50.x * t2.x + e50.y * t2.y;
var yU = (e50, t2, n2) => ({ x: e50.x + (t2.x - e50.x) * n2, y: e50.y + (t2.y - e50.y) * n2 });
var bU = (e50) => {
  const t2 = [];
  for (let n2 = 0;n2 < e50.length; n2 += 1) {
    const o3 = e50[n2];
    if (o3)
      for (let e51 = 0;e51 < o3.route.length - 1; e51 += 1) {
        const i3 = o3.route[e51], r3 = o3.route[e51 + 1];
        i3 && r3 && (i3.z !== r3.z || pU(i3, r3) || t2.push({ routeIndex: n2, rootConnectionName: dU(o3), startIndex: e51, endIndex: e51 + 1, start: i3, end: r3, z: i3.z, traceRadius: (o3.traceThickness ?? 0.1) / 2 }));
      }
  }
  return t2;
};
var xU = (e50, t2, n2 = 0.000001) => {
  const o3 = t2.end.x - t2.start.x, i3 = t2.end.y - t2.start.y, r3 = o3 * o3 + i3 * i3;
  if (r3 <= n2)
    return { x: t2.start.x, y: t2.start.y, t: 0 };
  const s2 = ((e50.x - t2.start.x) * o3 + (e50.y - t2.start.y) * i3) / r3, a3 = (c3 = s2, Math.max(0, Math.min(c3, 1)));
  var c3;
  return { x: t2.start.x + o3 * a3, y: t2.start.y + i3 * a3, t: a3 };
};
var vU = (e50, t2, n2 = 0.000001) => {
  const o3 = fU(e50.end, e50.start), i3 = fU(t2.end, t2.start), r3 = fU(e50.start, t2.start), s2 = _U(o3, o3), a3 = _U(o3, i3), c3 = _U(i3, i3), l3 = _U(o3, r3), h2 = _U(i3, r3), d2 = s2 * c3 - a3 * a3, u2 = n2;
  let p3, m2, g2 = d2, f2 = d2;
  d2 <= u2 ? (p3 = 0, g2 = 1, m2 = h2, f2 = c3) : (p3 = a3 * h2 - c3 * l3, m2 = s2 * h2 - a3 * l3, p3 < 0 ? (p3 = 0, m2 = h2, f2 = c3) : p3 > g2 && (p3 = g2, m2 = h2 + a3, f2 = c3)), m2 < 0 ? (m2 = 0, -l3 < 0 ? p3 = 0 : -l3 > s2 ? p3 = g2 : (p3 = -l3, g2 = s2)) : m2 > f2 && (m2 = f2, -l3 + a3 < 0 ? p3 = 0 : -l3 + a3 > s2 ? p3 = g2 : (p3 = -l3 + a3, g2 = s2));
  const _2 = Math.abs(p3) <= u2 ? 0 : p3 / g2, y2 = Math.abs(m2) <= u2 ? 0 : m2 / f2, b2 = yU(e50.start, e50.end, _2), x2 = yU(t2.start, t2.end, y2), v2 = xU(e50.start, t2, n2), I2 = xU(e50.end, t2, n2), S2 = xU(t2.start, e50, n2), C = xU(t2.end, e50, n2);
  return [{ leftT: _2, rightT: y2, leftPoint: b2, rightPoint: x2 }, { leftT: 0, rightT: v2.t, leftPoint: e50.start, rightPoint: v2 }, { leftT: 1, rightT: I2.t, leftPoint: e50.end, rightPoint: I2 }, { leftT: S2.t, rightT: 0, leftPoint: S2, rightPoint: t2.start }, { leftT: C.t, rightT: 1, leftPoint: C, rightPoint: t2.end }].sort((e51, t3) => gU(e51.leftPoint.x - e51.rightPoint.x, e51.leftPoint.y - e51.rightPoint.y) - gU(t3.leftPoint.x - t3.rightPoint.x, t3.leftPoint.y - t3.rightPoint.y));
};
var IU = 0.000001;
var SU = (e50) => {
  const t2 = [];
  for (const n2 of e50) {
    const e51 = t2[n2.routeIndex] ?? [];
    e51[n2.startIndex] = n2, t2[n2.routeIndex] = e51;
  }
  return t2;
};
var CU = (e50, t2) => e50 < t2 ? [e50, t2] : [t2, e50];
var PU = (e50, t2) => e50.some(([e51, n2]) => e51 === t2[0] && n2 === t2[1]);
var MU = (e50, t2, n2) => {
  let o3, i3 = Number.POSITIVE_INFINITY;
  for (const r3 of e50) {
    if (r3.routeIndex !== t2.routeIndex || r3.z !== t2.z || r3.endIndex !== t2.startIndex && r3.startIndex !== t2.endIndex)
      continue;
    const [e51] = vU(r3, n2);
    if (!e51)
      continue;
    const s2 = gU(e51.leftPoint.x - e51.rightPoint.x, e51.leftPoint.y - e51.rightPoint.y);
    s2 >= i3 || (i3 = s2, o3 = r3);
  }
  return o3;
};
var wU = (e50, t2) => {
  const n2 = bU(t2), o3 = bU(e50), i3 = SU(o3), r3 = [];
  for (let e51 = 0;e51 < n2.length; e51 += 1) {
    const t3 = n2[e51];
    if (t3)
      for (let s2 = e51 + 1;s2 < n2.length; s2 += 1) {
        const e52 = n2[s2];
        if (!e52 || t3.z !== e52.z || t3.rootConnectionName === e52.rootConnectionName || Math.max(t3.start.x, t3.end.x) < Math.min(e52.start.x, e52.end.x) || Math.max(e52.start.x, e52.end.x) < Math.min(t3.start.x, t3.end.x) || Math.max(t3.start.y, t3.end.y) < Math.min(e52.start.y, e52.end.y) || Math.max(e52.start.y, e52.end.y) < Math.min(t3.start.y, t3.end.y))
          continue;
        const [a3] = vU(t3, e52);
        if (!a3 || gU(a3.leftPoint.x - a3.rightPoint.x, a3.leftPoint.y - a3.rightPoint.y) > IU || a3.leftT <= IU || a3.leftT >= 0.999999 || a3.rightT <= IU || a3.rightT >= 0.999999)
          continue;
        const c3 = i3[t3.routeIndex]?.[t3.startIndex], l3 = i3[e52.routeIndex]?.[e52.startIndex];
        if (!c3 || !l3)
          continue;
        const [h2] = vU(c3, l3);
        if (!h2 || gU(h2.leftPoint.x - h2.rightPoint.x, h2.leftPoint.y - h2.rightPoint.y) <= IU)
          continue;
        const d2 = MU(o3, c3, l3), u2 = MU(o3, l3, c3), p3 = d2 ? [c3, d2] : [c3], m2 = u2 ? [l3, u2] : [l3];
        for (const n3 of p3)
          for (const o4 of m2) {
            const i4 = { leftRouteIndex: t3.routeIndex, leftStartPointIndex: n3.startIndex, rightRouteIndex: e52.routeIndex, rightStartPointIndex: o4.startIndex };
            r3.some((e53) => e53.leftRouteIndex === i4.leftRouteIndex && e53.leftStartPointIndex === i4.leftStartPointIndex && e53.rightRouteIndex === i4.rightRouteIndex && e53.rightStartPointIndex === i4.rightStartPointIndex) || r3.push(i4);
          }
      }
  }
  return r3;
};
var NU = (e50) => {
  const t2 = bU(e50), n2 = [];
  for (let e51 = 0;e51 < t2.length; e51 += 1) {
    const o3 = t2[e51];
    if (o3)
      for (let i3 = e51 + 1;i3 < t2.length; i3 += 1) {
        const e52 = t2[i3];
        if (!e52 || o3.z !== e52.z || o3.rootConnectionName === e52.rootConnectionName)
          continue;
        const [r3] = vU(o3, e52);
        if (!r3)
          continue;
        if (gU(r3.leftPoint.x - r3.rightPoint.x, r3.leftPoint.y - r3.rightPoint.y) + IU < o3.traceRadius + e52.traceRadius) {
          const t3 = CU(o3.routeIndex, e52.routeIndex);
          PU(n2, t3) || n2.push(t3);
        }
      }
  }
  return n2;
};
var RU = (e50, t2) => t2 <= 1 || t2 >= e50 - 2;
var TU = (e50, t2) => t2.some((t3) => RU(e50, t3));
var EU = 0.2;
var AU = 0.4;
var OU = 0.65 + 0.05;
var kU = 0.03;
var DU = 1000;
var LU = 0.000001;
var zU = 0.015;
var BU = (e50) => Math.round(e50 * DU) / DU;
var FU = (e50, t2) => ({ x: e50.x - t2.x, y: e50.y - t2.y });
var jU = (e50, t2) => ({ x: e50.x * t2, y: e50.y * t2 });
var $U = (e50, t2) => e50.x * t2.x + e50.y * t2.y;
var YU = (e50, t2, n2) => ({ x: e50.x + (t2.x - e50.x) * n2, y: e50.y + (t2.y - e50.y) * n2 });
var XU = (e50) => Math.max(0, Math.min(e50, 1));
var HU = (e50, t2, n2) => Math.max(t2, Math.min(e50, n2));
var VU = (e50, t2) => {
  const n2 = ((e51) => gU(e51.x, e51.y))(e50);
  return n2 <= t2 || n2 <= LU ? e50 : jU(e50, t2 / n2);
};
var WU = (e50, t2 = 0) => ({ minX: e50.center.x - e50.width / 2 - t2, maxX: e50.center.x + e50.width / 2 + t2, minY: e50.center.y - e50.height / 2 - t2, maxY: e50.center.y + e50.height / 2 + t2 });
var GU = (e50, t2, n2 = 0) => {
  const o3 = WU(t2, n2);
  return e50.x >= o3.minX && e50.x <= o3.maxX && e50.y >= o3.minY && e50.y <= o3.maxY;
};
var UU = (e50, t2, n2) => {
  if (e50.regionId) {
    const n3 = t2.findIndex((t3) => t3.capacityMeshNodeId === e50.regionId);
    if (n3 !== -1)
      return n3;
  }
  const o3 = [...e50.route.map(({ x: e51, y: t3 }) => ({ x: e51, y: t3 })), ...e50.vias.map(({ x: e51, y: t3 }) => ({ x: e51, y: t3 }))];
  let i3 = -1, r3 = Number.POSITIVE_INFINITY;
  for (let e51 = 0;e51 < t2.length; e51++) {
    const s2 = t2[e51];
    if (!s2 || !o3.every((e52) => GU(e52, s2, n2)))
      continue;
    const a3 = s2.width * s2.height;
    a3 < r3 && (r3 = a3, i3 = e51);
  }
  return i3;
};
var ZU = (e50, t2, n2, o3) => {
  const i3 = ((e51, t3, n3) => {
    const o4 = Math.min(Math.abs(e51.originalX - n3.minX), Math.abs(n3.maxX - e51.originalX)), i4 = Math.min(Math.abs(e51.originalY - n3.minY), Math.abs(n3.maxY - e51.originalY));
    if (Math.abs(o4 - i4) <= LU)
      return Math.abs(t3.x - e51.x) >= Math.abs(t3.y - e51.y) ? "y" : "x";
    return o4 < i4 ? "y" : "x";
  })(e50, t2, n2);
  return VU(i3 === "x" ? { x: 1.1 * (e50.x - t2.x) * o3, y: 0 } : { x: 0, y: 1.1 * (e50.y - t2.y) * o3 }, 0.06 * o3);
};
var qU = (e50, t2, n2, o3, i3 = 3.5, r3 = 0.2, s2 = 0.4) => {
  const a3 = Math.max(e50, 0);
  if (a3 >= s2)
    return 0;
  const c3 = a3 / r3;
  if (c3 < 1) {
    const e51 = 1 - c3;
    return t2 * e51 ** 3 * (1 + e51 * i3);
  }
  const l3 = (a3 - r3) / Math.max(s2 - r3, LU), h2 = t2 * n2 * Math.exp(-l3 * o3);
  return h2 < 0.00001 ? 0 : h2;
};
var JU = (e50, t2) => {
  const n2 = e50.boundaryPadding > 0 ? 0.001 : 0, o3 = t2.minX + e50.boundaryPadding + n2, i3 = t2.maxX - e50.boundaryPadding - n2, r3 = t2.minY + e50.boundaryPadding + n2, s2 = t2.maxY - e50.boundaryPadding - n2;
  e50.x = HU(e50.x, o3, i3), e50.y = HU(e50.y, r3, s2);
};
var QU = (e50, t2) => {
  for (const n2 of e50)
    for (const e51 of n2.nodes)
      JU(e51, t2);
};
var KU = (e50) => e50.kind === "via" ? 0.4 : 0.25;
var eZ = (e50) => (e50.kind, 0.5);
var tZ = (e50) => e50.kind === "via" ? 12 : 3.5;
var nZ = (e50) => e50.kind === "via" ? 0.18 : 0.06;
var oZ = (e50) => e50.kind === "via" ? 1.35 : 1.05;
var iZ = (e50, t2) => e50.kind === "via" ? 3 * t2 : t2;
var rZ = (e50, t2, n2, o3) => {
  const i3 = 2 * t2;
  e50[i3] = (e50[i3] ?? 0) + n2, e50[i3 + 1] = (e50[i3 + 1] ?? 0) + o3;
};
var sZ = (e50, t2, n2, o3, i3, r3) => {
  if (e50.fixed || rZ(o3, e50.node.forceIndex, t2, n2), !e50.fixed && i3 && r3 !== undefined) {
    const e51 = 2 * r3;
    i3[e51] = (i3[e51] ?? 0) + t2, i3[e51 + 1] = (i3[e51 + 1] ?? 0) + n2;
  }
};
var aZ = (e50, t2, n2, o3, i3 = 0.5) => {
  const { startNode: r3, endNode: s2 } = e50, a3 = 1 - XU(i3), c3 = XU(i3), l3 = r3.fixed ? 0 : a3, h2 = s2.fixed ? 0 : c3, d2 = l3 + h2;
  if (!(d2 <= LU)) {
    if (!r3.fixed && l3 > 0) {
      const e51 = l3 / d2;
      rZ(o3, r3.forceIndex, t2 * e51, n2 * e51);
    }
    if (!s2.fixed && h2 > 0) {
      const e51 = h2 / d2;
      rZ(o3, s2.forceIndex, t2 * e51, n2 * e51);
    }
  }
};
var cZ = (e50, t2, n2, o3, i3) => {
  if (t2.fixed)
    return { x: 0, y: 0 };
  const { minX: r3, maxX: s2, minY: a3, maxY: c3 } = e50, l3 = ((e51) => e51.kind === "via" ? 0.65 : EU)(t2), h2 = ((e51) => e51.kind === "via" ? OU : AU)(t2), d2 = ((e51) => e51.kind === "via" ? 0.015 : 0.08)(t2), u2 = ((e51) => e51.kind === "via" ? 80 : 20)(t2), p3 = tZ(t2);
  return { x: qU(n2 - r3, kU, d2, u2, p3, l3, h2) * i3 - qU(s2 - n2, kU, d2, u2, p3, l3, h2) * i3, y: qU(o3 - a3, kU, d2, u2, p3, l3, h2) * i3 - qU(c3 - o3, kU, d2, u2, p3, l3, h2) * i3 };
};
var lZ = (e50) => {
  if (e50.length === 0)
    return null;
  const t2 = new E2(e50.length);
  for (const n2 of e50) {
    const { startNode: e51, endNode: o3 } = n2;
    t2.add(Math.min(e51.x, o3.x), Math.min(e51.y, o3.y), Math.max(e51.x, o3.x), Math.max(e51.y, o3.y));
  }
  return t2.finish(), { index: t2, segments: e50 };
};
var hZ = (e50) => {
  const t2 = new Map, n2 = new Map;
  for (const t3 of e50) {
    const e51 = n2.get(t3.z) ?? [];
    e51.push(t3), n2.set(t3.z, e51);
  }
  for (const [e51, o3] of n2) {
    const n3 = lZ(o3);
    n3 && t2.set(e51, n3);
  }
  return { byLayer: t2 };
};
var dZ = (e50, t2, n2, o3, i3) => {
  const r3 = (e51) => ({ candidateIndexes: e51.index.search(n2 - i3, o3 - i3, n2 + i3, o3 + i3), segments: e51.segments });
  if (t2.kind === "point") {
    const n3 = e50.byLayer.get(t2.z);
    return n3 ? [r3(n3)] : [];
  }
  const s2 = [];
  for (const t3 of e50.byLayer.values())
    s2.push(r3(t3));
  return s2;
};
var uZ = (e50) => {
  const t2 = [];
  for (let n2 = 0;n2 < e50.length; n2 += 1) {
    const o3 = e50[n2];
    if (!o3)
      continue;
    const i3 = new Set;
    for (let e51 = 0;e51 < o3.route.length - 1; e51 += 1) {
      const r3 = o3.route[e51], s2 = o3.route[e51 + 1];
      if (!r3 || !s2)
        continue;
      if (r3.z === s2.z || !pU(r3, s2))
        continue;
      const a3 = [e51, e51 + 1];
      for (let t3 = e51 - 1;t3 >= 0; t3 -= 1) {
        const e52 = o3.route[t3];
        if (!e52 || !pU(e52, r3))
          break;
        a3.push(t3);
      }
      for (let t3 = e51 + 2;t3 < o3.route.length; t3 += 1) {
        const e52 = o3.route[t3];
        if (!e52 || !pU(e52, r3))
          break;
        a3.push(t3);
      }
      const c3 = [...new Set(a3)].sort((e52, t3) => e52 - t3);
      let l3 = false;
      for (const e52 of c3)
        if (i3.has(e52)) {
          l3 = true;
          break;
        }
      if (!l3) {
        for (const e52 of c3)
          i3.add(e52);
        t2.push({ routeIndex: n2, rootConnectionName: dU(o3), pointIndexes: c3, x: r3.x, y: r3.y, radius: (o3.viaDiameter ?? 0.3) / 2, movable: !TU(o3.route.length, c3) });
      }
    }
  }
  return t2;
};
var pZ = (e50) => {
  const { routes: t2, via: n2, dx: o3, dy: i3, node: r3 } = e50;
  if (!n2.movable)
    return false;
  n2.x += o3, n2.y += i3, ((e51, t3) => {
    const n3 = mU(t3, e51.radius + LU);
    e51.x = HU(e51.x, n3.minX, n3.maxX), e51.y = HU(e51.y, n3.minY, n3.maxY);
  })(n2, r3);
  const s2 = t2[n2.routeIndex];
  if (!s2)
    return false;
  for (const e51 of n2.pointIndexes) {
    const t3 = s2.route[e51];
    t3 && (t3.x = n2.x, t3.y = n2.y);
  }
  return true;
};
var mZ = (e50) => {
  const { routes: t2, node: n2, vias: o3 } = e50;
  let i3 = false;
  for (let e51 = 0;e51 < o3.length; e51 += 1) {
    const r3 = o3[e51];
    if (r3)
      for (let s2 = e51 + 1;s2 < o3.length; s2 += 1) {
        const a3 = o3[s2];
        if (!a3)
          continue;
        const c3 = r3.radius + a3.radius + 0.1 + zU, l3 = r3.x - a3.x, h2 = r3.y - a3.y, d2 = gU(l3, h2), u2 = c3 - d2;
        if (u2 <= 0)
          continue;
        const p3 = 1.61803398875 * (97 * e51 + 13 * s2), m2 = d2 > LU ? l3 / d2 : Math.cos(p3), g2 = d2 > LU ? h2 / d2 : Math.sin(p3), f2 = Number(r3.movable) + Number(a3.movable);
        if (f2 === 0)
          continue;
        const _2 = Math.min(0.04, u2 / f2);
        i3 = pZ({ routes: t2, via: r3, dx: m2 * _2, dy: g2 * _2, node: n2 }) || i3, i3 = pZ({ routes: t2, via: a3, dx: -m2 * _2, dy: -g2 * _2, node: n2 }) || i3;
      }
  }
  return i3;
};
var gZ = (e50) => {
  const { routes: t2, node: n2, vias: o3, segments: i3 } = e50;
  let r3 = false;
  for (let e51 = 0;e51 < o3.length; e51 += 1) {
    const s2 = o3[e51];
    if (s2?.movable)
      for (const o4 of i3) {
        if (s2.rootConnectionName === o4.rootConnectionName)
          continue;
        const i4 = xU(s2, o4), a3 = s2.x - i4.x, c3 = s2.y - i4.y, l3 = gU(a3, c3), h2 = s2.radius + o4.traceRadius + 0.1 + zU - l3;
        if (h2 <= 0)
          continue;
        const d2 = o4.end.x - o4.start.x, u2 = o4.end.y - o4.start.y, p3 = gU(d2, u2), m2 = e51 % 2 == 0 ? 1 : -1, g2 = l3 > LU ? a3 / l3 : p3 > LU ? -u2 / p3 * m2 : 1, f2 = l3 > LU ? c3 / l3 : p3 > LU ? d2 / p3 * m2 : 0, _2 = Math.min(0.04, h2);
        r3 = pZ({ routes: t2, via: s2, dx: g2 * _2, dy: f2 * _2, node: n2 }) || r3;
      }
  }
  return r3;
};
var fZ = (e50) => {
  const { routes: t2, routeIndex: n2, pointIndex: o3, dx: i3, dy: r3, node: s2 } = e50, a3 = t2[n2];
  if (!a3 || o3 <= 0 || o3 >= a3.route.length - 1)
    return false;
  const c3 = ((e51, t3, n3 = 0.001) => {
    const o4 = e51[t3];
    if (!o4)
      return [];
    const i4 = [t3];
    for (let r4 = t3 - 1;r4 >= 0; r4 -= 1) {
      const t4 = e51[r4];
      if (!t4 || !pU(t4, o4, n3))
        break;
      i4.push(r4);
    }
    for (let r4 = t3 + 1;r4 < e51.length; r4 += 1) {
      const t4 = e51[r4];
      if (!t4 || !pU(t4, o4, n3))
        break;
      i4.push(r4);
    }
    return [...new Set(i4)];
  })(a3.route, o3);
  if (TU(a3.route.length, c3))
    return false;
  const l3 = mU(s2, LU);
  let h2 = false;
  for (const e51 of c3) {
    const t3 = a3.route[e51];
    t3 && (t3.x = HU(t3.x + i3, l3.minX, l3.maxX), t3.y = HU(t3.y + r3, l3.minY, l3.maxY), h2 = true);
  }
  return h2;
};
var _Z = (e50) => {
  const { routes: t2, segment: n2, dx: o3, dy: i3, node: r3, t: s2 } = e50, a3 = 1 - XU(s2), c3 = XU(s2), l3 = fZ({ routes: t2, routeIndex: n2.routeIndex, pointIndex: n2.startIndex, dx: o3 * a3, dy: i3 * a3, node: r3 }), h2 = fZ({ routes: t2, routeIndex: n2.routeIndex, pointIndex: n2.endIndex, dx: o3 * c3, dy: i3 * c3, node: r3 });
  return l3 || h2;
};
var yZ = (e50) => {
  const { routes: t2, node: n2, segments: o3, movableRouteIndexes: i3 } = e50;
  let r3 = false;
  for (let e51 = 0;e51 < o3.length; e51 += 1) {
    const s2 = o3[e51];
    if (s2)
      for (let a3 = e51 + 1;a3 < o3.length; a3 += 1) {
        const c3 = o3[a3];
        if (!c3 || s2.z !== c3.z || s2.rootConnectionName === c3.rootConnectionName)
          continue;
        const l3 = s2.traceRadius + c3.traceRadius + 0.1 + zU;
        if (Math.max(s2.start.x, s2.end.x) + l3 <= Math.min(c3.start.x, c3.end.x) || Math.max(c3.start.x, c3.end.x) + l3 <= Math.min(s2.start.x, s2.end.x) || Math.max(s2.start.y, s2.end.y) + l3 <= Math.min(c3.start.y, c3.end.y) || Math.max(c3.start.y, c3.end.y) + l3 <= Math.min(s2.start.y, s2.end.y))
          continue;
        const [h2] = vU(s2, c3);
        if (!h2)
          continue;
        const d2 = h2.leftPoint.x - h2.rightPoint.x, u2 = h2.leftPoint.y - h2.rightPoint.y, p3 = gU(d2, u2), m2 = l3 - p3;
        if (m2 <= 0)
          continue;
        const g2 = !i3 || i3.has(s2.routeIndex), f2 = !i3 || i3.has(c3.routeIndex), _2 = Number(g2) + Number(f2);
        if (_2 === 0)
          continue;
        const y2 = s2.end.x - s2.start.x, b2 = s2.end.y - s2.start.y, x2 = gU(y2, b2), v2 = (e51 + a3) % 2 == 0 ? 1 : -1, I2 = p3 > LU ? d2 / p3 : x2 > LU ? -b2 / x2 * v2 : 1, S2 = p3 > LU ? u2 / p3 : x2 > LU ? y2 / x2 * v2 : 0, C = Math.min(0.025, m2 / _2);
        g2 && (r3 = _Z({ routes: t2, segment: s2, dx: I2 * C, dy: S2 * C, node: n2, t: h2.leftT }) || r3), f2 && (r3 = _Z({ routes: t2, segment: c3, dx: -I2 * C, dy: -S2 * C, node: n2, t: h2.rightT }) || r3);
      }
  }
  return r3;
};
var bZ = (e50, t2) => {
  for (let n2 = 0;n2 < 10; n2 += 1) {
    const n3 = uZ(t2), o3 = bU(t2), i3 = mZ({ routes: t2, node: e50, vias: n3 }), r3 = gZ({ routes: t2, node: e50, vias: n3, segments: o3 }), s2 = yZ({ routes: t2, node: e50, segments: o3 });
    if (!i3 && !r3 && !s2)
      break;
  }
  for (const e51 of t2)
    e51.vias = uU(e51);
  return t2;
};
var xZ = (e50, t2, n2) => {
  for (let o3 = 0;o3 < 10; o3 += 1) {
    if (!yZ({ routes: t2, node: e50, segments: bU(t2), movableRouteIndexes: n2 }))
      break;
  }
  for (const e51 of n2) {
    const n3 = t2[e51];
    n3 && (n3.vias = uU(n3));
  }
  return t2;
};
var vZ = (e50, t2, n2, o3, i3, r3 = 3, s2 = 0.02) => {
  for (let a3 = 0;a3 < r3; a3 += 1) {
    i3.fill(0);
    const r4 = hZ(o3);
    for (let e51 = 0;e51 < n2.length; e51 += 1) {
      const t3 = n2[e51];
      if (!t3 || t3.kind !== "via")
        continue;
      const o4 = t3.node;
      for (let r5 = e51 + 1;r5 < n2.length; r5 += 1) {
        const c3 = n2[r5];
        if (!c3 || c3.kind !== "via")
          continue;
        if (t3.rootConnectionName === c3.rootConnectionName)
          continue;
        const l3 = c3.node, h2 = o4.x - l3.x, d2 = o4.y - l3.y;
        if (Math.abs(h2) >= EU || Math.abs(d2) >= EU)
          continue;
        const u2 = gU(h2, d2), p3 = EU - u2;
        if (p3 <= 0)
          continue;
        let m2 = 0, g2 = 0;
        if (u2 > LU) {
          const e52 = 1 / u2;
          m2 = h2 * e52, g2 = d2 * e52;
        } else {
          const t4 = 1.61803398875 * (1009 * a3 + 97 * e51 + 13 * r5);
          m2 = Math.cos(t4), g2 = Math.sin(t4);
        }
        const f2 = Math.min(s2, 0.9 * p3), _2 = m2 * f2, y2 = g2 * f2;
        sZ(t3, _2, y2, i3), sZ(c3, -_2, -y2, i3);
      }
    }
    for (let e51 = 0;e51 < n2.length; e51 += 1) {
      const t3 = n2[e51];
      if (!t3)
        continue;
      const o4 = t3.node, c3 = KU(t3), l3 = dZ(r4, t3, o4.x, o4.y, c3);
      for (const n3 of l3)
        for (const r5 of n3.candidateIndexes) {
          const l4 = n3.segments[r5];
          if (!l4)
            continue;
          if (t3.rootConnectionName === l4.rootConnectionName)
            continue;
          const { startNode: h2, endNode: d2 } = l4, u2 = d2.x - h2.x, p3 = d2.y - h2.y, m2 = u2 * u2 + p3 * p3;
          if (m2 <= LU)
            continue;
          const g2 = o4.x - h2.x, f2 = o4.y - h2.y, _2 = XU((g2 * u2 + f2 * p3) / m2), y2 = h2.x + u2 * _2, b2 = h2.y + p3 * _2, x2 = o4.x - y2, v2 = o4.y - b2, I2 = gU(x2, v2), S2 = c3 - I2;
          if (S2 <= 0)
            continue;
          const C = 1009 * a3 + 97 * e51 + 13 * l4.obstacleIndex;
          let P = 0, M = 0;
          if (I2 > LU) {
            const e52 = 1 / I2;
            P = x2 * e52, M = v2 * e52;
          } else {
            const e52 = -p3, t4 = u2, n4 = gU(e52, t4);
            if (n4 > LU) {
              const o5 = (C % 2 == 0 ? 1 : -1) / n4;
              P = e52 * o5, M = t4 * o5;
            } else {
              const e53 = 1.61803398875 * C;
              P = Math.cos(e53), M = Math.sin(e53);
            }
          }
          const w = Math.min(iZ(t3, s2), S2 * oZ(t3)), N = P * w, R2 = M * w;
          sZ(t3, N, R2, i3), aZ(l4, -N, -R2, i3, _2);
        }
    }
    for (let e51 = 0;e51 < t2.length; e51 += 1) {
      const n3 = t2[e51];
      if (n3)
        for (let e52 = 0;e52 < n3.nodes.length; e52 += 1) {
          const t3 = n3.nodes[e52];
          if (!t3 || t3.fixed)
            continue;
          const o4 = 2 * t3.forceIndex;
          let r5 = i3[o4] ?? 0, a4 = i3[o4 + 1] ?? 0;
          const c3 = gU(r5, a4);
          if (c3 > s2 && c3 > LU) {
            const e53 = s2 / c3;
            r5 *= e53, a4 *= e53;
          }
          t3.x += r5, t3.y += a4;
        }
    }
    QU(t2, e50);
  }
};
var IZ = (e50, t2, n2, o3) => {
  const { mutableRoutes: i3, totalNodeCount: r3 } = ((e51) => {
    let t3 = 0;
    return { mutableRoutes: e51.map((e52) => {
      const n3 = [], o4 = new Int32Array(e52.route.length);
      o4.fill(-1);
      for (let i4 = 0;i4 < e52.route.length; i4 += 1) {
        const r4 = e52.route[i4];
        if (!r4)
          continue;
        const s3 = e52.route[i4 - 1], a4 = n3.at(-1), c4 = n3.length - 1;
        a4 && s3 && s3.x === r4.x && s3.y === r4.y ? (s3.z !== r4.z && (a4.boundaryPadding = Math.max(a4.boundaryPadding, e52.viaDiameter / 2)), a4.pointIndexes.push(i4), a4.fixed ||= RU(e52.route.length, i4), o4[i4] = c4) : (n3.push({ x: r4.x, y: r4.y, originalX: r4.x, originalY: r4.y, boundaryPadding: 0, pointIndexes: [i4], fixed: RU(e52.route.length, i4), forceIndex: t3 }), o4[i4] = n3.length - 1, t3 += 1);
      }
      return { route: e52, rootConnectionName: e52.rootConnectionName ?? e52.connectionName, nodes: n3, pointNodeIndexes: o4 };
    }), totalNodeCount: t3 };
  })(t2), s2 = ((e51) => {
    const t3 = [];
    for (let n3 = 0;n3 < e51.length; n3 += 1) {
      const o4 = e51[n3];
      if (o4)
        for (let e52 = 0;e52 < o4.nodes.length; e52 += 1) {
          const i4 = o4.nodes[e52], r4 = i4?.pointIndexes[0], s3 = r4 === undefined ? undefined : o4.route.route[r4];
          i4 && s3 && (i4.pointIndexes.length > 1 ? t3.push({ kind: "via", routeIndex: n3, rootConnectionName: o4.rootConnectionName, node: i4, fixed: i4.fixed }) : t3.push({ kind: "point", routeIndex: n3, rootConnectionName: o4.rootConnectionName, node: i4, z: s3.z, fixed: i4.fixed }));
        }
    }
    return t3;
  })(i3), a3 = ((e51) => {
    const t3 = [];
    for (let n3 = 0;n3 < e51.length; n3 += 1) {
      const o4 = e51[n3];
      if (o4)
        for (let e52 = 0;e52 < o4.nodes.length - 1; e52 += 1) {
          const n4 = o4.nodes[e52], i4 = o4.nodes[e52 + 1], r4 = n4?.pointIndexes[0], s3 = r4 === undefined ? undefined : o4.route.route[r4];
          n4 && i4 && s3 && t3.push({ obstacleIndex: t3.length, rootConnectionName: o4.rootConnectionName, z: s3.z, startNode: n4, endNode: i4 });
        }
    }
    return t3;
  })(i3), c3 = new Float64Array(2 * r3), l3 = new Float64Array(2 * r3), h2 = o3?.includeForceVectors ?? true;
  QU(i3, e50);
  let d2 = [];
  for (let t3 = 0;t3 < n2; t3 += 1) {
    const o4 = n2 <= 1 ? 0 : t3 / Math.max(n2 - 1, 1), r4 = 0.25 + 0.75 * (1 - o4), u3 = 1 - o4, p3 = h2 && t3 === n2 - 1, m2 = p3 ? new Float64Array(2 * s2.length) : undefined;
    c3.fill(0);
    for (let e51 = 0;e51 < s2.length; e51 += 1) {
      const t4 = s2[e51];
      if (!t4 || t4.kind !== "via")
        continue;
      const n3 = t4.node;
      for (let o5 = e51 + 1;o5 < s2.length; o5 += 1) {
        const i4 = s2[o5];
        if (!i4 || i4.kind !== "via")
          continue;
        if (t4.rootConnectionName === i4.rootConnectionName)
          continue;
        const a4 = i4.node, l4 = n3.x - a4.x, h3 = n3.y - a4.y;
        if (Math.abs(l4) >= AU || Math.abs(h3) >= AU)
          continue;
        const d3 = gU(l4, h3);
        let u4 = 0, p4 = 0;
        if (d3 > LU) {
          const e52 = 1 / d3;
          u4 = l4 * e52, p4 = h3 * e52;
        } else {
          const t5 = 1.61803398875 * (97 * e51 + 13 * o5);
          u4 = Math.cos(t5), p4 = Math.sin(t5);
        }
        const g3 = qU(d3, 0.034, 0.08, 18) * r4;
        if (g3 <= 0)
          continue;
        const f2 = u4 * g3, _2 = p4 * g3;
        sZ(t4, f2, _2, c3, m2, e51), sZ(i4, -f2, -_2, c3, m2, o5);
      }
    }
    const g2 = hZ(a3);
    for (let e51 = 0;e51 < s2.length; e51 += 1) {
      const t4 = s2[e51];
      if (!t4)
        continue;
      const n3 = t4.node, o5 = eZ(t4), i4 = dZ(g2, t4, n3.x, n3.y, o5);
      for (const s3 of i4)
        for (const i5 of s3.candidateIndexes) {
          const a4 = s3.segments[i5];
          if (!a4)
            continue;
          if (t4.rootConnectionName === a4.rootConnectionName)
            continue;
          const { startNode: l4, endNode: h3 } = a4, d3 = h3.x - l4.x, u4 = h3.y - l4.y, p4 = d3 * d3 + u4 * u4;
          if (p4 <= LU)
            continue;
          const g3 = n3.x - l4.x, f2 = n3.y - l4.y, _2 = XU((g3 * d3 + f2 * u4) / p4), y2 = l4.x + d3 * _2, b2 = l4.y + u4 * _2, x2 = n3.x - y2, v2 = n3.y - b2, I2 = gU(x2, v2), S2 = 97 * e51 + 13 * a4.obstacleIndex;
          let C = 0, P = 0;
          if (I2 > LU) {
            const e52 = 1 / I2;
            C = x2 * e52, P = v2 * e52;
          } else {
            const e52 = -u4, t5 = d3, n4 = gU(e52, t5);
            if (n4 > LU) {
              const o6 = (S2 % 2 == 0 ? 1 : -1) / n4;
              C = e52 * o6, P = t5 * o6;
            } else {
              const e53 = 1.61803398875 * S2;
              C = Math.cos(e53), P = Math.sin(e53);
            }
          }
          const M = qU(I2, nZ(t4), 0.08, 18, tZ(t4), KU(t4), o5) * r4;
          if (M <= 0)
            continue;
          const w = C * M, N = P * M;
          sZ(t4, w, N, c3, m2, e51), aZ(a4, -w, -N, c3, _2);
        }
    }
    p3 && (d2 = new Array(s2.length));
    for (let t4 = 0;t4 < s2.length; t4 += 1) {
      const n3 = s2[t4];
      if (!n3)
        continue;
      const o5 = n3.node, i4 = cZ(e50, n3, o5.x, o5.y, r4);
      if (sZ(n3, i4.x, i4.y, c3, m2, t4), p3 && m2) {
        const e51 = 2 * t4;
        d2[t4] = { kind: n3.kind, routeIndex: n3.routeIndex, rootConnectionName: n3.rootConnectionName, x: o5.x, y: o5.y, dx: m2[e51] ?? 0, dy: m2[e51 + 1] ?? 0 };
      }
    }
    for (let t4 = 0;t4 < i3.length; t4 += 1) {
      const n3 = i3[t4];
      if (!n3)
        continue;
      const o5 = n3.nodes.length - 2;
      for (let t5 = 0;t5 < n3.nodes.length; t5 += 1) {
        const i4 = n3.nodes[t5];
        if (!i4 || i4.fixed)
          continue;
        const s3 = 2 * i4.forceIndex;
        let a4 = (c3[s3] ?? 0) + 0.14 * (i4.originalX - i4.x), l4 = (c3[s3 + 1] ?? 0) + 0.14 * (i4.originalY - i4.y), h3 = 0, d3 = 0, p4 = 0, m3 = 0;
        const g3 = n3.nodes[t5 - 1], f2 = n3.nodes[t5 + 1];
        if (g3 || f2) {
          let e51 = 0, t6 = 0, n4 = 0;
          if (g3 && (e51 += g3.x, t6 += g3.y, n4 += 1), f2 && (e51 += f2.x, t6 += f2.y, n4 += 1), n4 > 0) {
            const o6 = 1 / n4;
            a4 += 0.22 * (e51 * o6 - i4.x), l4 += 0.22 * (t6 * o6 - i4.y);
          }
        }
        if (g3 && f2 && u3 > 0) {
          const e51 = FU(f2, g3), t6 = $U(e51, e51);
          if (t6 > LU) {
            const n4 = XU($U(FU(i4, g3), e51) / t6), o6 = YU(g3, f2, n4), r5 = VU(jU(FU(o6, i4), 0.55 * u3), 0.02 * u3);
            h3 = r5.x, d3 = r5.y;
          }
        }
        if (u3 > 0) {
          if (t5 === 1 && g3?.fixed) {
            const t6 = ZU(g3, i4, e50, u3);
            p4 += t6.x, m3 += t6.y;
          }
          if (t5 === o5 && f2?.fixed) {
            const t6 = ZU(f2, i4, e50, u3);
            p4 += t6.x, m3 += t6.y;
          }
        }
        let _2 = 0.85 * a4 * r4, y2 = 0.85 * l4 * r4;
        const b2 = gU(_2, y2), x2 = 0.012 * r4;
        if (b2 > x2 && b2 > LU) {
          const e51 = x2 / b2;
          _2 *= e51, y2 *= e51;
        }
        i4.x += _2 + h3 + p4, i4.y += y2 + d3 + m3;
      }
    }
    QU(i3, e50), vZ(e50, i3, s2, a3, l3, 3, 0.02);
  }
  vZ(e50, i3, s2, a3, l3, 8, 0.03);
  const u2 = ((e51) => e51.map(({ route: e52, nodes: t3, pointNodeIndexes: n3 }) => {
    const o4 = e52.route.map((e53, o5) => {
      const i5 = n3[o5] ?? -1, r4 = i5 >= 0 ? t3[i5] : undefined;
      return r4 ? { ...e53, x: BU(r4.x), y: BU(r4.y) } : e53;
    }), i4 = { ...e52, route: o4, vias: [] };
    return i4.vias = uU(i4), i4;
  }))(i3);
  return { routes: u2, forceVectors: d2, stepsCompleted: n2 };
};
var SZ = class extends cU {
  sampleEntries;
  originalHdRoutes;
  originalNodeWithPortPoints;
  colorMap;
  totalStepsPerNode;
  nodeAssignmentMargin;
  improvedRoutesByIndex = new Map;
  activeSampleIndex = 0;
  latestVisualization = {};
  constructor(e50) {
    super(), this.originalHdRoutes = e50.hdRoutes, this.originalNodeWithPortPoints = e50.nodeWithPortPoints, this.colorMap = e50.colorMap ?? {}, this.totalStepsPerNode = e50.totalStepsPerNode ?? 60, this.nodeAssignmentMargin = e50.nodeAssignmentMargin ?? 0.2;
    const t2 = new Map;
    for (let n2 = 0;n2 < e50.hdRoutes.length; n2++) {
      const o3 = UU(e50.hdRoutes[n2], e50.nodeWithPortPoints, this.nodeAssignmentMargin);
      if (o3 === -1)
        continue;
      const i3 = t2.get(o3) ?? [];
      i3.push(n2), t2.set(o3, i3);
    }
    this.sampleEntries = Array.from(t2.entries()).map(([t3, n2]) => ({ node: e50.nodeWithPortPoints[t3], routeIndexes: n2 })), this.MAX_ITERATIONS = Math.max(10 * this.sampleEntries.length, 1000), this.stats = { nodeAssignmentMargin: this.nodeAssignmentMargin, sampleCount: this.sampleEntries.length, improvedNodeCount: 0, improvedRouteCount: 0, totalStepsPerNode: this.totalStepsPerNode };
  }
  getSolverName() {
    return "HighDensityForceImproveSolver";
  }
  getConstructorParams() {
    return [{ nodeWithPortPoints: this.originalNodeWithPortPoints, hdRoutes: this.originalHdRoutes, totalStepsPerNode: this.totalStepsPerNode, nodeAssignmentMargin: this.nodeAssignmentMargin, colorMap: this.colorMap }];
  }
  _step() {
    const e50 = this.sampleEntries[this.activeSampleIndex];
    if (!e50)
      return void (this.solved = true);
    const t2 = WU(e50.node), n2 = e50.routeIndexes.map((e51) => this.originalHdRoutes[e51]), o3 = IZ(t2, n2, this.totalStepsPerNode, { includeForceVectors: true });
    bZ(e50.node, o3.routes);
    const i3 = wU(n2, o3.routes);
    let r3 = i3.length === 0 ? o3 : IZ(t2, ((e51, t3) => {
      const { routes: n3, node: o4, selectors: i4 } = e51, r4 = structuredClone(n3), s2 = bU(n3), a3 = SU(s2), c3 = i4.flatMap((e52) => {
        const t4 = a3[e52.leftRouteIndex]?.[e52.leftStartPointIndex], n4 = a3[e52.rightRouteIndex]?.[e52.rightStartPointIndex];
        if (!t4 || !n4)
          return [];
        const [o5] = vU(t4, n4);
        if (!o5)
          return [];
        const i5 = o5.leftPoint.x - o5.rightPoint.x, r5 = o5.leftPoint.y - o5.rightPoint.y, s3 = gU(i5, r5);
        return s3 <= IU ? [] : [{ selector: e52, directionX: i5 / s3, directionY: r5 / s3, requiredDistance: t4.traceRadius + n4.traceRadius + 0.015 }];
      });
      for (let e52 = 0;e52 < 3; e52 += 1) {
        const e53 = bU(r4), n4 = SU(e53);
        for (const e54 of c3) {
          const i5 = n4[e54.selector.leftRouteIndex]?.[e54.selector.leftStartPointIndex], s3 = n4[e54.selector.rightRouteIndex]?.[e54.selector.rightStartPointIndex];
          if (!i5 || !s3)
            continue;
          const [a4] = vU(i5, s3);
          if (!a4)
            continue;
          const c4 = (a4.leftPoint.x - a4.rightPoint.x) * e54.directionX + (a4.leftPoint.y - a4.rightPoint.y) * e54.directionY, l3 = e54.requiredDistance - c4;
          if (l3 <= 0)
            continue;
          const h2 = Math.min(0.025, l3 / 2);
          t3({ routes: r4, segment: i5, dx: e54.directionX * h2, dy: e54.directionY * h2, node: o4, t: a4.leftT }), t3({ routes: r4, segment: s3, dx: -e54.directionX * h2, dy: -e54.directionY * h2, node: o4, t: a4.rightT });
        }
      }
      for (const e52 of r4)
        e52.vias = uU(e52);
      return r4;
    })({ routes: n2, node: e50.node, selectors: i3 }, _Z), this.totalStepsPerNode, { includeForceVectors: true });
    if (r3 !== o3) {
      bZ(e50.node, r3.routes);
      const t3 = wU(n2, r3.routes);
      if (t3.length > 0) {
        const o4 = ((e51, t4) => {
          const { originalRoutes: n3, guardedRoutes: o5, node: i4, crossingSelectors: r4, protectedSelectors: s2 } = e51, a3 = SU(bU(n3)), c3 = SU(bU(o5)), l3 = NU(o5), h2 = s2.map(({ leftRouteIndex: e52, rightRouteIndex: t5 }) => CU(e52, t5)), d2 = mU(i4, IU);
          for (const e52 of r4) {
            const r5 = c3[e52.leftRouteIndex]?.[e52.leftStartPointIndex], s3 = c3[e52.rightRouteIndex]?.[e52.rightStartPointIndex];
            if (!r5 || !s3)
              continue;
            const [u2] = vU(r5, s3);
            if (!(!u2 || gU(u2.leftPoint.x - u2.rightPoint.x, u2.leftPoint.y - u2.rightPoint.y) > IU || u2.leftT <= IU || u2.leftT >= 0.999999 || u2.rightT <= IU || u2.rightT >= 0.999999))
              for (const r6 of ["right", "left"]) {
                const s4 = r6 === "left" ? e52.leftRouteIndex : e52.rightRouteIndex, u3 = r6 === "left" ? e52.leftStartPointIndex : e52.rightStartPointIndex, p3 = r6 === "left" ? e52.rightRouteIndex : e52.leftRouteIndex, m2 = r6 === "left" ? e52.rightStartPointIndex : e52.leftStartPointIndex, g2 = n3[s4], f2 = o5[s4], _2 = a3[p3]?.[m2], y2 = c3[p3]?.[m2];
                if (!(g2 && f2 && _2 && y2))
                  continue;
                const b2 = g2.route[u3]?.z, x2 = [];
                for (let e53 = u3 - 2;e53 <= u3 + 3; e53 += 1) {
                  const t5 = g2.route[e53];
                  !t5 || e53 <= 0 || e53 >= g2.route.length - 1 || t5.z !== b2 || [g2.route[e53 - 1], g2.route[e53 + 1]].some((e54) => e54 && e54.z !== t5.z) || x2.push(e53);
                }
                if (x2.length !== 0)
                  for (const [e53, n4] of [[_2.start, y2.start], [_2.end, y2.end]])
                    for (const r7 of [1.51, 1.25, 1.75, 2]) {
                      const a4 = [...o5], c4 = structuredClone(f2);
                      a4[s4] = c4;
                      let u4 = true;
                      for (const t5 of x2) {
                        const o6 = g2.route[t5], i5 = c4.route[t5];
                        if (!o6 || !i5)
                          continue;
                        const s5 = n4.x + (o6.x - e53.x) * r7, a5 = n4.y + (o6.y - e53.y) * r7;
                        if (s5 <= d2.minX || s5 >= d2.maxX || a5 <= d2.minY || a5 >= d2.maxY) {
                          u4 = false;
                          break;
                        }
                        i5.x = s5, i5.y = a5;
                      }
                      if (!u4)
                        continue;
                      c4.vias = uU(c4);
                      let p4 = a4, m3 = NU(p4);
                      const _3 = new Set;
                      for (const [e54, t5] of m3)
                        PU(l3, [e54, t5]) || (e54 === s4 && t5 !== s4 ? _3.add(t5) : t5 === s4 && e54 !== s4 && _3.add(e54));
                      if (_3.size > 0) {
                        const e54 = t4(i4, structuredClone(a4), _3), n5 = NU(e54);
                        h2.every((e55) => !PU(n5, e55)) && n5.length < m3.length && (p4 = e54, m3 = n5);
                      }
                      if (h2.every((e54) => !PU(m3, e54)) && m3.length < l3.length)
                        return p4;
                    }
              }
          }
        })({ originalRoutes: n2, guardedRoutes: r3.routes, node: e50.node, crossingSelectors: t3, protectedSelectors: [...i3, ...t3] }, xZ);
        o4 && (r3 = { ...r3, routes: o4 });
      }
    }
    for (let t3 = 0;t3 < e50.routeIndexes.length; t3++)
      this.improvedRoutesByIndex.set(e50.routeIndexes[t3], r3.routes[t3]);
    this.latestVisualization = CZ({ node: e50.node, routes: r3.routes, forceVectors: r3.forceVectors, colorMap: this.colorMap }), this.activeSampleIndex += 1, this.stats = { nodeAssignmentMargin: this.nodeAssignmentMargin, sampleCount: this.sampleEntries.length, improvedNodeCount: this.activeSampleIndex, improvedRouteCount: this.improvedRoutesByIndex.size, totalStepsPerNode: this.totalStepsPerNode }, this.activeSampleIndex >= this.sampleEntries.length && (this.solved = true);
  }
  getOutput() {
    return this.originalHdRoutes.map((e50, t2) => this.improvedRoutesByIndex.get(t2) ?? e50);
  }
  visualize() {
    return this.solved ? CZ({ routes: this.getOutput(), colorMap: this.colorMap }) : this.latestVisualization;
  }
};
var CZ = (e50) => {
  const t2 = [], n2 = [], o3 = [];
  e50.node && o3.push({ center: e50.node.center, width: e50.node.width, height: e50.node.height, stroke: "rgba(14,165,233,0.7)", fill: "rgba(14,165,233,0.04)", label: e50.node.capacityMeshNodeId });
  for (const o4 of e50.routes) {
    const i3 = e50.colorMap?.[o4.connectionName] ?? "#0ea5e9";
    for (let e51 = 0;e51 < o4.route.length - 1; e51++) {
      const n3 = o4.route[e51], r3 = o4.route[e51 + 1];
      n3.z === r3.z && t2.push({ points: [{ x: n3.x, y: n3.y }, { x: r3.x, y: r3.y }], strokeColor: n3.z === 0 ? i3 : hU(i3, 0.5), strokeWidth: o4.traceThickness, layer: `z${n3.z}`, strokeDash: n3.z !== 0 ? [0.1, 0.3] : undefined });
    }
    for (const e51 of o4.vias)
      n2.push({ center: { x: e51.x, y: e51.y }, radius: o4.viaDiameter / 2, stroke: i3, fill: "rgba(14,165,233,0.12)" });
  }
  for (const n3 of e50.forceVectors ?? [])
    t2.push({ points: [{ x: n3.x, y: n3.y }, { x: n3.x + 5 * n3.dx, y: n3.y + 5 * n3.dy }], strokeColor: "rgba(244,63,94,0.85)", strokeWidth: 0.06, strokeDash: [0.08, 0.08] });
  return { lines: t2, circles: n2, rects: o3 };
};
var PZ = 0.002;
var MZ = class extends ni {
  constructor(e50, t2, n2 = Number.POSITIVE_INFINITY, o3 = 0.010000000000000002) {
    super(), this.nodes = e50, this.maxNodeDimension = t2, this.maxNodeRatio = n2, this.minNodeArea = o3, this.outputNodes = [];
  }
  outputNodes;
  getSolverName() {
    return "NodeDimensionSubdivisionSolver";
  }
  getSubdivisionGrid(e50) {
    const t2 = Number.isFinite(this.maxNodeDimension) && this.maxNodeDimension > 0, n2 = Number.isFinite(this.maxNodeRatio) && this.maxNodeRatio > 0;
    let o3 = t2 ? Math.max(1, Math.ceil(e50.width / this.maxNodeDimension)) : 1, i3 = t2 ? Math.max(1, Math.ceil(e50.height / this.maxNodeDimension)) : 1;
    if (n2 && e50.width > 0 && e50.height > 0)
      for (;; ) {
        const t3 = e50.width / o3, n3 = e50.height / i3;
        if ((t3 >= n3 ? t3 / n3 : n3 / t3) <= this.maxNodeRatio)
          break;
        t3 >= n3 ? o3++ : i3++;
      }
    return { cols: o3, rows: i3 };
  }
  shouldRemoveNode(e50, t2) {
    const n2 = Number.isFinite(this.minNodeArea) && this.minNodeArea > 0;
    if (!Number.isFinite(e50.width) || !Number.isFinite(e50.height))
      return true;
    if (!n2 || e50.width * e50.height >= this.minNodeArea)
      return false;
    if (Math.min(e50.width, e50.height) < 0.002)
      return true;
    if (e50._containsTarget)
      return false;
    if (!Number.isFinite(e50.center.x) || !Number.isFinite(e50.center.y))
      return true;
    const { index: o3, originalNodeIndices: i3 } = t2.bridgeNodeIndex ??= ((e51) => {
      const t3 = [];
      for (let n4 = 0;n4 < e51.length; n4++) {
        const o4 = e51[n4];
        Number.isFinite(o4.center.x) && Number.isFinite(o4.center.y) && !Number.isNaN(o4.width) && !Number.isNaN(o4.height) && t3.push(n4);
      }
      if (t3.length === 0)
        throw new Error("Connectivity bridge index has no original nodes");
      const n3 = new E2(t3.length);
      for (const o4 of t3) {
        const t4 = e51[o4], i4 = t4.center.x - t4.width / 2, r4 = t4.center.x + t4.width / 2, s3 = t4.center.y - t4.height / 2, a3 = t4.center.y + t4.height / 2;
        n3.add(Math.max(-Number.MAX_VALUE, Math.min(i4, r4)), Math.max(-Number.MAX_VALUE, Math.min(s3, a3)), Math.min(Number.MAX_VALUE, Math.max(i4, r4)), Math.min(Number.MAX_VALUE, Math.max(s3, a3)));
      }
      return n3.finish(), { index: n3, originalNodeIndices: t3 };
    })(this.nodes), r3 = o3.search(e50.center.x - e50.width / 2 - PZ, e50.center.y - e50.height / 2 - PZ, e50.center.x + e50.width / 2 + PZ, e50.center.y + e50.height / 2 + PZ);
    r3.sort((e51, t3) => e51 - t3);
    let s2 = 0;
    for (const t3 of r3) {
      const n3 = this.nodes[i3[t3]];
      if (n3.capacityMeshNodeId !== e50.capacityMeshNodeId && (e50.availableZ.some((e51) => n3.availableZ.includes(e51)) && ri(e50, n3))) {
        if (n3._containsTarget)
          return false;
        if (s2++, s2 >= 2)
          return false;
      }
    }
    return true;
  }
  subdivideNode(e50, t2) {
    if (this.shouldRemoveNode(e50, t2))
      return [];
    const { cols: n2, rows: o3 } = this.getSubdivisionGrid(e50);
    if (n2 === 1 && o3 === 1)
      return [e50];
    const i3 = e50.width / n2, r3 = e50.height / o3, s2 = e50.center.x - e50.width / 2, a3 = e50.center.y - e50.height / 2, c3 = [];
    for (let t3 = 0;t3 < o3; t3++)
      for (let o4 = 0;o4 < n2; o4++)
        c3.push({ ...e50, capacityMeshNodeId: `${e50.capacityMeshNodeId}__sub_${t3}_${o4}`, center: { x: s2 + i3 * (o4 + 0.5), y: a3 + r3 * (t3 + 0.5) }, width: i3, height: r3, availableZ: [...e50.availableZ] });
    return c3;
  }
  _step() {
    const e50 = this.nodes.length;
    let t2 = 0, n2 = 0, o3 = 0;
    const i3 = {};
    for (const e51 of this.nodes) {
      const r3 = !Number.isFinite(e51.width) || !Number.isFinite(e51.height), s2 = this.subdivideNode(e51, i3);
      s2.length !== 0 ? (s2.length > 1 && t2++, this.outputNodes.push(...s2)) : r3 ? o3++ : n2++;
    }
    this.stats = { inputNodeCount: e50, outputNodeCount: this.outputNodes.length, subdividedNodeCount: t2, removedSmallNodeCount: n2, removedInvalidNodeCount: o3, maxNodeDimension: this.maxNodeDimension, maxNodeRatio: this.maxNodeRatio, minNodeArea: this.minNodeArea }, this.solved = true;
  }
  visualize() {
    return { rects: this.outputNodes.map((e50) => ({ center: e50.center, width: e50.width, height: e50.height, label: `${e50.capacityMeshNodeId}
${e50.width.toFixed(2)}x${e50.height.toFixed(2)}`, layer: `z${e50.availableZ.join(",")}`, fill: "rgba(0, 200, 255, 0.08)", stroke: "rgba(0, 120, 180, 0.5)" })) };
  }
};
var NZ = (e50) => {
  const t2 = [...new Set(e50.filter((e51) => typeof e51 == "number" && Number.isInteger(e51) && e51 >= 0))].sort((e51, t3) => e51 - t3);
  if (t2.length !== 0)
    return `z${t2.join(",")}`;
};
var RZ = (e50) => {
  const t2 = [];
  for (let n2 = 0;n2 < 31; n2++)
    e50 & 1 << n2 && t2.push(n2);
  return t2;
};
var TZ = (e50) => typeof e50 == "object" && e50 !== null;
var EZ = (e50) => TZ(e50) ? { ...e50 } : e50 === undefined ? {} : { value: e50 };
var AZ = (e50, t2) => {
  const n2 = e50.topology.regionMetadata?.[t2];
  if (TZ(n2)) {
    if (typeof n2.serializedRegionId == "string")
      return n2.serializedRegionId;
    if (typeof n2.regionId == "string")
      return n2.regionId;
    if (typeof n2.capacityMeshNodeId == "string")
      return n2.capacityMeshNodeId;
  }
  return `region-${t2}`;
};
var OZ = (e50, t2) => {
  const n2 = e50.topology.portMetadata?.[t2];
  if (TZ(n2)) {
    if (typeof n2.serializedPortId == "string")
      return n2.serializedPortId;
    if (typeof n2.portId == "string")
      return (o3 = n2.portId).includes("::") ? o3.slice(0, o3.indexOf("::")) : o3;
  }
  var o3;
  return `port-${t2}`;
};
var kZ = (e50, t2) => {
  const n2 = e50.problem.routeMetadata?.[t2];
  return TZ(n2) && typeof n2.connectionId == "string" ? n2.connectionId : `route-${t2}`;
};
var DZ = (e50, t2) => {
  const n2 = EZ(e50.topology.regionMetadata?.[t2]);
  if (TZ(n2.center) || (n2.center = { x: e50.topology.regionCenterX[t2], y: e50.topology.regionCenterY[t2] }), typeof n2.width != "number" && (n2.width = e50.topology.regionWidth[t2]), typeof n2.height != "number" && (n2.height = e50.topology.regionHeight[t2]), !Array.isArray(n2.availableZ)) {
    const o3 = e50.topology.regionAvailableZMask?.[t2] ?? 0;
    o3 !== 0 && (n2.availableZ = RZ(o3));
  }
  return n2.layer = NZ(Array.isArray(n2.availableZ) ? n2.availableZ : []) ?? NZ((e50.topology.regionIncidentPorts[t2] ?? []).map((t3) => e50.topology.portZ[t3])) ?? "z0", n2;
};
var LZ = (e50, t2) => {
  const n2 = EZ(e50.topology.portMetadata?.[t2]);
  return typeof n2.x != "number" && (n2.x = e50.topology.portX[t2]), typeof n2.y != "number" && (n2.y = e50.topology.portY[t2]), typeof n2.z != "number" && (n2.z = e50.topology.portZ[t2]), n2.layer = NZ([e50.topology.portZ[t2]]) ?? "z0", n2;
};
var zZ = (e50, t2, n2) => {
  const o3 = (e50.topology.incidentPortRegion[t2] ?? []).find((e51) => e51 !== n2);
  if (o3 === undefined)
    throw new Error(`Port ${t2} is not incident to a region outside route region ${n2}`);
  return o3;
};
var BZ = (e50, t2, n2) => {
  const { orderedPortIds: o3, orderedRegionIds: i3 } = ((e51, t3, n3) => {
    if (n3.length === 0)
      throw new Error(`Route ${t3} has no solved segments`);
    const o4 = e51.problem.routeStartPort[t3], i4 = e51.problem.routeEndPort[t3], r4 = o4 === i4, s3 = new Map;
    n3.forEach((e52, t4) => {
      const n4 = { ...e52, segmentIndex: t4 }, o5 = s3.get(e52.fromPortId) ?? [];
      o5.push(n4), s3.set(e52.fromPortId, o5);
      const i5 = s3.get(e52.toPortId) ?? [];
      i5.push(n4), s3.set(e52.toPortId, i5);
    });
    const a4 = [o4], c4 = [], l4 = (e52, t4, o5) => {
      if (e52 === i4 && (!r4 || t4.size === n3.length))
        return true;
      for (const h3 of s3.get(e52) ?? []) {
        if (t4.has(h3.segmentIndex))
          continue;
        const s4 = h3.fromPortId === e52 ? h3.toPortId : h3.fromPortId, d2 = r4 && s4 === i4 && t4.size + 1 === n3.length;
        if (o5.has(s4) && !d2)
          continue;
        t4.add(h3.segmentIndex);
        const u2 = !o5.has(s4);
        if (u2 && o5.add(s4), c4.push(h3.regionId), a4.push(s4), l4(s4, t4, o5))
          return true;
        a4.pop(), c4.pop(), u2 && o5.delete(s4), t4.delete(h3.segmentIndex);
      }
      return false;
    };
    if (!l4(o4, new Set, new Set([o4])))
      throw new Error(`Route ${t3} is not a single ordered path from ${o4} to ${i4}`);
    return { orderedPortIds: a4, orderedRegionIds: c4 };
  })(e50, t2, n2), r3 = i3[0], s2 = i3[i3.length - 1];
  if (r3 === undefined || s2 === undefined)
    throw new Error(`Route ${t2} could not determine endpoint regions`);
  const a3 = AZ(e50, zZ(e50, o3[0], r3)), c3 = AZ(e50, zZ(e50, o3[o3.length - 1], s2)), l3 = ((e51, t3, n3, o4) => {
    const i4 = e51.problem.routeMetadata?.[t3];
    return { connectionId: kZ(e51, t3), startRegionId: (TZ(i4) && typeof i4.startRegionId == "string" ? i4.startRegionId : undefined) ?? n3, endRegionId: (TZ(i4) && typeof i4.endRegionId == "string" ? i4.endRegionId : undefined) ?? o4, mutuallyConnectedNetworkId: (TZ(i4) && typeof i4.mutuallyConnectedNetworkId == "string" ? i4.mutuallyConnectedNetworkId : undefined) ?? `net-${e51.problem.routeNet[t3]}` };
  })(e50, t2, a3, c3), h2 = o3.map((t3, n3) => {
    const r4 = { portId: OZ(e50, t3), g: n3, h: 0, f: n3, hops: n3, ripRequired: false, nextRegionId: n3 < i3.length ? AZ(e50, i3[n3]) : l3.endRegionId };
    return n3 > 0 && (r4.lastPortId = OZ(e50, o3[n3 - 1]), r4.lastRegionId = AZ(e50, i3[n3 - 1])), r4;
  });
  return { connection: l3, solvedRoute: { connection: l3, path: h2, requiredRip: false } };
};
var FZ = (e50) => {
  if (!e50.solved || e50.failed)
    throw new Error("convertToSerializedHyperGraph requires a solved, non-failed solver");
  const { topology: t2 } = e50, n2 = ((e51) => {
    const t3 = Array.from({ length: e51.problem.routeCount }, () => []);
    return e51.state.regionSegments.forEach((e52, n3) => {
      for (const [o4, i4, r4] of e52)
        t3[o4].push({ regionId: n3, fromPortId: i4, toPortId: r4 });
    }), t3;
  })(e50), o3 = Array.from({ length: t2.regionCount }, (n3, o4) => {
    const i4 = e50.state.regionSegments[o4].map(([t3, n4, o5]) => ({ regionPort1Id: OZ(e50, n4), regionPort2Id: OZ(e50, o5), connectionId: kZ(e50, t3) }));
    return { regionId: AZ(e50, o4), pointIds: t2.regionIncidentPorts[o4].map((t3) => OZ(e50, t3)), d: DZ(e50, o4), ...i4.length > 0 && { assignments: i4 } };
  }), i3 = Array.from({ length: t2.portCount }, (n3, o4) => {
    const [i4, r4] = t2.incidentPortRegion[o4] ?? [];
    if (i4 === undefined || r4 === undefined)
      throw new Error(`Port ${o4} is missing incident regions`);
    return { portId: OZ(e50, o4), region1Id: AZ(e50, i4), region2Id: AZ(e50, r4), d: LZ(e50, o4) };
  }), r3 = n2.map((t3, n3) => BZ(e50, n3, t3));
  return { regions: o3, ports: i3, connections: r3.map(({ connection: e51 }) => e51), solvedRoutes: r3.map(({ solvedRoute: e51 }) => e51) };
};
var jZ = 0.3;
var $Z = (e50) => e50 > 0 && !(e50 & e50 - 1);
var YZ = (e50, t2, n2, o3, i3, r3, s2 = 0, a3 = 0.3, c3 = 0) => XZ(e50 * t2, n2, o3, i3, r3, s2, a3, c3);
var XZ = (e50, t2, n2, o3, i3, r3 = 0, s2 = 0.3, a3 = 0) => (2 * t2 + 1 * n2 + 1 * o3) * (s2 + 0.15) ** 2 * (1 + i3 / 5) / e50 + ($Z(r3) ? 10 * t2 : 0) + a3 * (i3 / HZ(r3)) ** 2 * 0.1 ** 2 / e50;
var HZ = (e50) => {
  if (e50 === 0)
    return 2;
  let t2 = e50 >>> 0, n2 = 0;
  for (;t2 !== 0; )
    n2 += 1 & t2, t2 >>>= 1;
  return n2;
};
var VZ = (e50, t2) => {
  const { netIds: n2, lesserAngles: o3, greaterAngles: i3, layerMasks: r3 } = e50, { netId: s2, lesserAngle: a3, greaterAngle: c3, layerMask: l3 } = t2;
  let h2 = 0, d2 = 0;
  for (let e51 = 0;e51 < n2.length; e51++) {
    if (s2 === n2[e51])
      continue;
    (a3 < o3[e51] && o3[e51] < c3) !== (a3 < i3[e51] && i3[e51] < c3) && ((l3 & r3[e51]) !== 0 ? h2++ : d2++);
  }
  t2.sameLayerIntersectionCount = h2, t2.crossingLayerIntersectionCount = d2;
};
var WZ = (e50, t2, n2) => {
  const o3 = e50.routeStartPort[t2], i3 = e50.routeEndPort[t2], r3 = new Map;
  for (const { fromPortId: e51, toPortId: t3 } of n2) {
    const n3 = r3.get(e51) ?? new Set;
    n3.add(t3), r3.set(e51, n3);
    const o4 = r3.get(t3) ?? new Set;
    o4.add(e51), r3.set(t3, o4);
  }
  const s2 = new Set, a3 = [o3];
  for (;a3.length > 0; ) {
    const e51 = a3.pop();
    if (!s2.has(e51)) {
      s2.add(e51);
      for (const t3 of r3.get(e51) ?? [])
        a3.push(t3);
    }
  }
  if (!s2.has(i3))
    throw new Error(`Initial assignments for route ${t2} do not connect ${o3} to ${i3}`);
  if (n2.some(({ fromPortId: e51, toPortId: t3 }) => !s2.has(e51) || !s2.has(t3)))
    throw new Error(`Initial assignments for route ${t2} contain disconnected segments`);
};
var GZ = ({ topology: e50, problem: t2, state: n2, routeSuccessCountByRouteId: o3, appendSegmentToRegionCache: i3 }) => {
  const r3 = t2.initialAssignments ?? [];
  if (r3.length === 0)
    return;
  const s2 = new Map;
  for (const n3 of r3) {
    const { routeId: o4, regionId: i4, fromPortId: r4, toPortId: a4 } = n3;
    if (!Number.isInteger(o4) || o4 < 0 || o4 >= t2.routeCount)
      throw new Error(`Initial assignment references invalid route ${o4}`);
    if (!Number.isInteger(i4) || i4 < 0 || i4 >= e50.regionCount)
      throw new Error(`Initial assignment references invalid region ${i4}`);
    for (const t3 of [r4, a4]) {
      if (!Number.isInteger(t3) || t3 < 0 || t3 >= e50.portCount)
        throw new Error(`Initial assignment references invalid port ${t3}`);
      if (!e50.incidentPortRegion[t3]?.includes(i4))
        throw new Error(`Initial assignment port ${t3} is not incident to region ${i4}`);
    }
    const c3 = s2.get(o4) ?? [];
    c3.push(n3), s2.set(o4, c3);
  }
  for (const [e51, n3] of s2)
    WZ(t2, e51, n3);
  const a3 = new Set(s2.keys());
  for (const { routeId: e51, regionId: o4, fromPortId: s3, toPortId: a4 } of r3) {
    const r4 = t2.routeNet[e51];
    for (const e52 of [s3, a4]) {
      const t3 = n2.portAssignment[e52];
      if (t3 !== -1 && t3 !== r4)
        throw new Error(`Initial assignment port ${e52} is assigned to multiple nets`);
      n2.portAssignment[e52] = r4;
    }
    n2.currentRouteNetId = r4, n2.regionSegments[o4].push([e51, s3, a4]), i3(o4, s3, a4);
  }
  n2.currentRouteNetId = undefined, n2.unroutedRoutes = n2.unroutedRoutes.filter((e51) => !a3.has(e51));
  for (const e51 of a3)
    o3[e51] = 1;
  return { initialAssignmentCount: r3.length, initiallyRoutedRouteCount: a3.size };
};
var UZ = class {
  constructor(e50, t2) {
    this.items = e50, this.compare = t2;
  }
  get length() {
    return this.items.length;
  }
  toArray() {
    return [...this.items];
  }
  clear() {
    this.items.length = 0;
  }
  queue(e50) {
    this.items.push(e50), this.siftUp(this.items.length - 1);
  }
  dequeue() {
    const e50 = this.items[0];
    if (e50 === undefined)
      return;
    const t2 = this.items.pop();
    return this.items.length > 0 && (this.items[0] = t2, this.siftDown(0)), e50;
  }
  siftUp(e50) {
    let t2 = e50;
    for (;t2 > 0; ) {
      const e51 = t2 - 1 >> 1, n2 = this.items[e51], o3 = this.items[t2];
      if (this.compare(n2, o3) <= 0)
        return;
      this.items[e51] = o3, this.items[t2] = n2, t2 = e51;
    }
  }
  siftDown(e50) {
    let t2 = e50;
    const n2 = this.items.length;
    for (;; ) {
      const e51 = 2 * t2 + 1;
      if (e51 >= n2)
        return;
      const o3 = e51 + 1;
      let i3 = e51;
      o3 < n2 && this.compare(this.items[o3], this.items[e51]) < 0 && (i3 = o3);
      const r3 = this.items[t2], s2 = this.items[i3];
      if (this.compare(r3, s2) <= 0)
        return;
      this.items[t2] = s2, this.items[i3] = r3, t2 = i3;
    }
  }
};
var ZZ = class {
  constructor(e50, t2) {
    this.regionCount = e50, this.compactHopIndex = t2, t2 && (this.hopStateGeneration = new Uint32Array(t2.hopCapacity), this.hopIndexOrClosed = new Int32Array(t2.hopCapacity));
  }
  items = [];
  indexByHopId = new Map;
  closedHopIds = new Set;
  hopStateGeneration;
  hopIndexOrClosed;
  currentHopStateGeneration = 1;
  closureEpochToken = {};
  get closureEpoch() {
    return this.closureEpochToken;
  }
  get length() {
    return this.items.length;
  }
  toArray() {
    return [...this.items];
  }
  clear() {
    this.closureEpochToken = {}, this.items.length = 0, this.indexByHopId.clear(), this.closedHopIds.clear(), this.hopStateGeneration && (this.currentHopStateGeneration === 4294967295 ? (this.hopStateGeneration.fill(0), this.currentHopStateGeneration = 1) : this.currentHopStateGeneration += 1);
  }
  isClosedHop(e50, t2) {
    return this.isClosedHopId(this.getHopIdFromValues(e50, t2));
  }
  isClosedHopId(e50) {
    return this.isHopClosed(e50);
  }
  queue(e50) {
    const t2 = this.getHopId(e50);
    if (this.isHopClosed(t2))
      return;
    const n2 = this.getQueuedHopIndex(t2);
    if (n2 !== undefined) {
      const t3 = this.items[n2];
      if (e50.g >= t3.g)
        return;
      return this.items[n2] = e50, void (e50.f <= t3.f ? this.siftUp(n2) : this.siftDown(n2));
    }
    const o3 = this.items.length;
    this.items.push(e50), this.siftUp(o3);
  }
  dequeue() {
    const e50 = this.items[0];
    if (!e50)
      return;
    const t2 = this.getHopId(e50);
    this.closeHop(t2);
    const n2 = this.items.pop();
    return this.items.length > 0 && (this.items[0] = n2, this.siftDown(0)), e50;
  }
  getHopId(e50) {
    if (e50.hopId !== undefined)
      return e50.hopId;
    const t2 = this.getHopIdFromValues(e50.portId, e50.nextRegionId);
    return e50.hopId = t2, t2;
  }
  getHopIdFromValues(e50, t2) {
    const n2 = this.compactHopIndex;
    if (!n2)
      return e50 * this.regionCount + t2;
    const o3 = e50 * n2.hopSlotStride;
    if (n2.firstRegionByPortId[e50] === t2)
      return o3;
    if (n2.secondRegionByPortId[e50] === t2)
      return o3 + 1;
    const i3 = n2.incidentPortRegion[e50];
    for (let e51 = 2;e51 < (i3?.length ?? 0); e51++)
      if (i3[e51] === t2)
        return o3 + e51;
    return -(e50 * this.regionCount + t2) - 1;
  }
  getQueuedHopIndex(e50) {
    if (e50 >= 0 && this.hopStateGeneration) {
      if (this.hopStateGeneration[e50] !== this.currentHopStateGeneration)
        return;
      const t2 = this.hopIndexOrClosed[e50];
      return t2 >= 0 ? t2 : undefined;
    }
    return this.indexByHopId.get(e50);
  }
  isHopClosed(e50) {
    return e50 >= 0 && this.hopStateGeneration ? this.hopStateGeneration[e50] === this.currentHopStateGeneration && this.hopIndexOrClosed[e50] === -1 : this.closedHopIds.has(e50);
  }
  setQueuedHopIndex(e50, t2) {
    if (e50 >= 0 && this.hopStateGeneration)
      return this.hopStateGeneration[e50] = this.currentHopStateGeneration, void (this.hopIndexOrClosed[e50] = t2);
    this.indexByHopId.set(e50, t2);
  }
  closeHop(e50) {
    if (e50 >= 0 && this.hopStateGeneration)
      return this.hopStateGeneration[e50] = this.currentHopStateGeneration, void (this.hopIndexOrClosed[e50] = -1);
    this.indexByHopId.delete(e50), this.closedHopIds.add(e50);
  }
  siftUp(e50) {
    const t2 = this.items[e50];
    let n2 = e50;
    for (;n2 > 0; ) {
      const e51 = n2 - 1 >> 1, o3 = this.items[e51];
      if (o3.f <= t2.f)
        break;
      this.items[n2] = o3, this.setQueuedHopIndex(this.getHopId(o3), n2), n2 = e51;
    }
    this.items[n2] = t2, this.setQueuedHopIndex(this.getHopId(t2), n2);
  }
  siftDown(e50) {
    const t2 = this.items[e50];
    let n2 = e50;
    for (;; ) {
      const e51 = 2 * n2 + 1;
      if (e51 >= this.items.length)
        break;
      const o3 = e51 + 1, i3 = o3 < this.items.length && this.items[o3].f < this.items[e51].f ? o3 : e51, r3 = this.items[i3];
      if (t2.f <= r3.f)
        break;
      this.items[n2] = r3, this.setQueuedHopIndex(this.getHopId(r3), n2), n2 = i3;
    }
    this.items[n2] = t2, this.setQueuedHopIndex(this.getHopId(t2), n2);
  }
};
var qZ = (e50, t2) => {
  const n2 = [...e50], o3 = ((e51) => {
    let t3 = e51 >>> 0;
    return () => {
      t3 += 1831565813;
      let e52 = t3;
      return e52 = Math.imul(e52 ^ e52 >>> 15, 1 | e52), e52 ^= e52 + Math.imul(e52 ^ e52 >>> 7, 61 | e52), ((e52 ^ e52 >>> 14) >>> 0) / 4294967296;
    };
  })(t2);
  for (let e51 = n2.length - 1;e51 > 0; e51--) {
    const t3 = Math.floor(o3() * (e51 + 1));
    [n2[e51], n2[t3]] = [n2[t3], n2[e51]];
  }
  return n2;
};
var JZ = (e50, t2) => e50.routeMetadata?.[t2];
var QZ = (e50) => e50?.simpleRouteConnection?.pointsToConnect?.map(({ pointId: e51 }) => typeof e51 == "string" ? e51 : null).filter((e51) => e51 !== null) ?? [];
var KZ = (e50, t2) => {
  const n2 = JZ(e50, t2)?.connectionId;
  return typeof n2 == "string" ? n2 : `route-${t2}`;
};
var eq = (e50, t2, n2) => {
  const o3 = e50.portEndpointNetIds[n2];
  if (!o3)
    return false;
  for (const e51 of o3)
    if (e51 !== t2)
      return true;
  return false;
};
var tq = (e50, t2, n2) => {
  const o3 = e50.regionNetId[n2];
  return o3 !== -1 && o3 !== t2;
};
var nq = (e50) => [...new Set(e50.routeIds)].filter((t2) => !((e51, t3) => {
  const { topology: n2, problem: o3, problemSetup: i3, portAssignment: r3, maxPrecheckHops: s2 } = e51, a3 = o3.routeNet[t3], c3 = o3.routeStartPort[t3], l3 = o3.routeEndPort[t3];
  if (c3 === l3)
    return true;
  const h2 = e51.getStartingNextRegionId(t3, c3);
  if (h2 === undefined)
    return false;
  const d2 = [{ portId: c3, nextRegionId: h2 }], u2 = new Set([c3 * n2.regionCount + h2]);
  for (let e52 = 0;e52 < d2.length; e52++) {
    const t4 = d2[e52];
    if (!tq(o3, a3, t4.nextRegionId))
      for (const e53 of n2.regionIncidentPorts[t4.nextRegionId] ?? []) {
        const c4 = r3[e53];
        if (eq(i3, a3, e53))
          continue;
        if (e53 === l3) {
          if (c4 !== -1 && c4 !== a3)
            continue;
          return true;
        }
        if (e53 === t4.portId)
          continue;
        if (c4 !== -1 && c4 !== a3)
          continue;
        if (o3.portSectionMask[e53] === 0)
          continue;
        const h3 = n2.incidentPortRegion[e53] ?? [], p3 = h3[0] === t4.nextRegionId ? h3[1] : h3[0];
        if (p3 === undefined || tq(o3, a3, p3))
          continue;
        const m2 = e53 * n2.regionCount + p3;
        if (!u2.has(m2)) {
          if (u2.size >= s2)
            return true;
          u2.add(m2), d2.push({ portId: e53, nextRegionId: p3 });
        }
      }
  }
  return false;
})(e50, t2)).map((t2) => e50.getRouteSummary(t2));
var oq = (e50) => {
  const t2 = new Array(e50);
  for (let n2 = 0;n2 < e50; n2++)
    t2[n2] = n2;
  return t2;
};
var iq = "rgba(220, 38, 38, 0.98)";
var rq = "rgba(220, 38, 38, 0.18)";
var sq = (...e50) => e50.filter((e51) => Boolean(e51)).join(`
`);
var aq = (e50, t2) => {
  const n2 = 0.005 * e50.topology.portZ[t2];
  return { x: e50.topology.portX[t2] + n2, y: e50.topology.portY[t2] + n2 };
};
var cq = (e50, t2) => NZ([e50.topology.portZ[t2]]) ?? "z0";
var lq = (e50, t2) => {
  const n2 = e50.topology.portMetadata?.[t2];
  return `port: ${n2?.serializedPortId ?? n2?.portId ?? `port-${t2}`}`;
};
var hq = (e50, t2) => `z: ${e50.topology.portZ[t2]}`;
var dq = (e50, t2) => ((e51, t3, n2) => {
  const o3 = e51.topology.portZ[t3], i3 = e51.topology.portZ[n2];
  return o3 === i3 ? `z: ${o3}` : `z: ${o3} -> ${i3}`;
})(e50, e50.problem.routeStartPort[t2], e50.problem.routeEndPort[t2]);
var uq = (e50, t2) => `net: ${e50.problem.routeNet[t2]}`;
var pq = 0.05;
var mq = { r: 255, g: 64, b: 64, a: 0.72 };
var gq = "rgba(220, 38, 38, 0.98)";
var fq = "rgba(220, 38, 38, 0.12)";
var _q = "10 6";
var yq = (...e50) => e50.filter((e51) => Boolean(e51)).join(`
`);
var bq = (e50) => Math.min(1, Math.max(0, e50));
var xq = (e50, t2, n2) => Math.round(e50 + (t2 - e50) * n2);
var vq = ({ r: e50, g: t2, b: n2, a: o3 }) => `rgba(${e50}, ${t2}, ${n2}, ${o3})`;
var Iq = (e50, t2) => {
  const n2 = e50.problem.routeMetadata?.[t2];
  return n2?.connectionId ?? n2?.mutuallyConnectedNetworkId ?? `route-${t2}`;
};
var Sq = (e50) => typeof e50.centerRouteId == "number";
var Cq = (e50, t2) => Sq(e50) ? t2 === e50.centerRouteId ? 1 : 0.5 : 1;
var Pq = (e50, t2) => {
  const n2 = e50.match(/^(rgba|hsla)\((.*),\s*([0-9]*\.?[0-9]+)\)$/);
  if (!n2)
    return e50;
  const [, o3, i3, r3] = n2, s2 = bq(Number(r3) * t2);
  return `${o3}(${i3}, ${Number(s2.toFixed(3))})`;
};
var Mq = (e50, t2, n2 = 0.8) => ((e51, t3, n3 = 0.8) => {
  const o3 = `${e51.problem.routeNet[t3]}:${Iq(e51, t3)}`;
  let i3 = 0;
  for (let e52 = 0;e52 < o3.length; e52++)
    i3 = 17777 * o3.charCodeAt(e52) + ((i3 << 5) - i3);
  return `hsla(${Math.abs(i3) % 360}, 70%, 50%, ${n3})`;
})(e50, t2, n2 * Cq(e50, t2));
var wq = (e50, t2) => `net: ${e50.problem.routeNet[t2]}`;
var Nq = (e50, t2) => {
  const n2 = e50.topology.regionMetadata?.[t2], o3 = n2?.polygon;
  if (Array.isArray(o3) && o3.length >= 3) {
    const e51 = o3.map((e52) => e52.x), t3 = o3.map((e52) => e52.y);
    return { minX: Math.min(...e51), maxX: Math.max(...e51), minY: Math.min(...t3), maxY: Math.max(...t3) };
  }
  const i3 = n2?.bounds;
  if (i3 && typeof i3.minX == "number" && typeof i3.maxX == "number" && typeof i3.minY == "number" && typeof i3.maxY == "number")
    return i3;
  const r3 = e50.topology.regionWidth[t2], s2 = e50.topology.regionHeight[t2], a3 = e50.topology.regionCenterX[t2], c3 = e50.topology.regionCenterY[t2];
  return { minX: a3 - r3 / 2, maxX: a3 + r3 / 2, minY: c3 - s2 / 2, maxY: c3 + s2 / 2 };
};
var Rq = (e50, t2) => ({ x: e50.topology.regionCenterX[t2], y: e50.topology.regionCenterY[t2] });
var Tq = (e50, t2) => {
  const n2 = e50.topology.regionMetadata?.[t2], o3 = Array.isArray(n2?.availableZ) ? n2.availableZ.filter((e51) => typeof e51 == "number" && Number.isInteger(e51) && e51 >= 0) : [];
  if (o3.length > 0)
    return NZ(o3) ?? "z0";
  const i3 = RZ(e50.topology.regionAvailableZMask?.[t2] ?? 0);
  if (i3.length > 0)
    return NZ(i3) ?? "z0";
  const r3 = [...new Set((e50.topology.regionIncidentPorts[t2] ?? []).map((t3) => e50.topology.portZ[t3]))].sort((e51, t3) => e51 - t3);
  return NZ(r3) ?? "z0";
};
var Eq = (e50, t2) => {
  const n2 = e50.state.regionIntersectionCaches[t2], o3 = n2?.existingRegionCost ?? 0, i3 = e50.state.regionCongestionCost[t2] ?? 0, r3 = e50.problem.regionNetId[t2];
  return yq(`region: region-${t2}`, `net: ${r3 === -1 ? "free" : `${r3}`}`, e50.getAdditionalRegionLabel(t2), `cost: ${o3.toFixed(3)}`, `congestion: ${i3.toFixed(3)}`, `same layer X: ${n2?.existingSameLayerIntersections ?? 0}`, `trans X: ${n2?.existingCrossingLayerIntersections ?? 0}`, `entry exit X: ${n2?.existingEntryExitLayerChanges ?? 0}`);
};
var Aq = (e50, t2) => {
  const n2 = e50.topology.regionMetadata?.[t2];
  return n2?.isConnectionRegion ? { r: 255, g: 100, b: 255, a: 0.6 } : n2?.isThroughJumper ? { r: 100, g: 200, b: 100, a: 0.5 } : n2?.isPad ? { r: 255, g: 200, b: 100, a: 0.5 } : n2?.layer === "bottom" ? { r: 52, g: 152, b: 219, a: 0.08 } : { r: 200, g: 200, b: 255, a: 0.1 };
};
var Oq = (e50, t2) => {
  const n2 = Aq(e50, t2), o3 = bq(e50.state.regionIntersectionCaches[t2]?.existingRegionCost ?? 0);
  return vq((r3 = mq, s2 = o3 ** 0.8, { r: xq((i3 = n2).r, r3.r, s2), g: xq(i3.g, r3.g, s2), b: xq(i3.b, r3.b, s2), a: Number((i3.a + (r3.a - i3.a) * s2).toFixed(3)) }));
  var i3, r3, s2;
};
var kq = (e50, t2) => {
  const n2 = ((e51, t3) => ({ x: e51.topology.portX[t3], y: e51.topology.portY[t3] }))(e50, t2), o3 = 0.005 * e50.topology.portZ[t2];
  return { x: n2.x + o3, y: n2.y + o3 };
};
var Dq = kq;
var Lq = (e50, t2) => NZ([e50.topology.portZ[t2]]) ?? "z0";
var zq = (e50, t2) => {
  const n2 = e50.topology.portMetadata?.[t2];
  return `port: ${n2?.serializedPortId ?? n2?.portId ?? `port-${t2}`}`;
};
var Bq = (e50, t2, n2) => {
  if (n2 !== undefined)
    return `net: ${e50.problem.routeNet[n2]}`;
  const o3 = e50.state.portAssignment[t2];
  if (o3 >= 0)
    return `net: ${o3}`;
  const i3 = new Set;
  for (let n3 = 0;n3 < e50.problem.routeCount; n3++)
    e50.problem.routeStartPort[n3] !== t2 && e50.problem.routeEndPort[n3] !== t2 || i3.add(e50.problem.routeNet[n3]);
  return i3.size !== 0 ? `net: ${Array.from(i3).sort((e51, t3) => e51 - t3).join(", ")}` : undefined;
};
var Fq = (e50, t2) => `z: ${e50.topology.portZ[t2]}`;
var jq = (e50, t2, n2) => {
  const o3 = e50.topology.portZ[t2], i3 = e50.topology.portZ[n2];
  return o3 === i3 ? `z: ${o3}` : `z: ${o3} -> ${i3}`;
};
var $q = (e50, t2) => jq(e50, e50.problem.routeStartPort[t2], e50.problem.routeEndPort[t2]);
var Yq = (e50, t2, n2) => yq(zq(e50, t2), ((e51, t3) => {
  const n3 = e51.topology.incidentPortRegion[t3]?.[0], o3 = e51.topology.incidentPortRegion[t3]?.[1];
  return `connects: region-${n3 ?? "?"} <-> region-${o3 ?? "?"}`;
})(e50, t2), Bq(e50, t2, n2));
var Xq = (e50, t2, n2, o3) => {
  const i3 = e50.topology.portZ[n2];
  return i3 !== e50.topology.portZ[o3] ? { strokeColor: Pq("rgba(22, 160, 133, 0.95)", Cq(e50, t2)), strokeDash: "2 4 2" } : i3 > 0 ? { strokeColor: Pq("rgba(52, 152, 219, 0.95)", Cq(e50, t2)), strokeDash: "3 2" } : { strokeColor: Mq(e50, t2) };
};
var Hq = (e50, t2) => {
  for (let n2 = 0;n2 < e50.state.regionSegments.length; n2++) {
    const o3 = e50.state.regionSegments[n2] ?? [];
    for (const [i3, r3, s2] of o3)
      t2.lines.push({ points: [kq(e50, r3), kq(e50, s2)], label: yq(`route: ${Iq(e50, i3)}`, `region: region-${n2}`, jq(e50, r3, s2)), layer: Lq(e50, r3), ...Xq(e50, i3, r3, s2) });
  }
};
var Vq = (e50, t2) => {
  const n2 = new Set;
  for (let o3 = 0;o3 < e50.state.regionSegments.length; o3++) {
    const i3 = e50.state.regionSegments[o3] ?? [];
    for (const [o4, r3, s2] of i3)
      for (const i4 of [r3, s2]) {
        const r4 = `${o4}:${i4}`;
        if (n2.has(r4))
          continue;
        n2.add(r4);
        const s3 = kq(e50, i4);
        t2.points.push({ x: s3.x, y: s3.y, color: Mq(e50, o4, 1), layer: Lq(e50, i4), label: yq(`route: ${Iq(e50, o4)}`, zq(e50, i4), Bq(e50, i4, o4), Fq(e50, i4)) });
      }
  }
};
var Wq = (e50, t2) => {
  for (let n2 = 0;n2 < e50.problem.routeCount; n2++)
    if (e50.problem.routeStartPort[n2] === t2 || e50.problem.routeEndPort[n2] === t2)
      return true;
  return false;
};
var Gq = (e50, t2, n2) => {
  const o3 = ((e51, t3) => {
    const n3 = new Set;
    for (let o4 = 0;o4 < t3.length; o4++)
      if (t3[o4] === 1)
        for (const t4 of e51.topology.incidentPortRegion[o4] ?? [])
          n3.add(t4);
    return n3;
  })(e50, n2), i3 = "rgba(245, 158, 11, 0.95)", r3 = "rgba(245, 158, 11, 0.08)";
  for (const n3 of o3) {
    const o4 = e50.topology.regionMetadata?.[n3], s2 = o4?.polygon, a3 = Nq(e50, n3), c3 = Rq(e50, n3), l3 = a3.maxX - a3.minX, h2 = a3.maxY - a3.minY, d2 = Tq(e50, n3), u2 = yq("section region", Eq(e50, n3));
    Array.isArray(s2) && s2.length >= 3 ? t2.polygons.push({ points: s2, fill: r3, stroke: i3, strokeWidth: 2, layer: d2, label: u2 }) : t2.rects.push({ center: c3, width: Math.max(l3 - pq, 0.05), height: Math.max(h2 - pq, 0.05), fill: r3, stroke: i3, layer: d2, label: u2 });
  }
  for (let o4 = 0;o4 < n2.length; o4++)
    n2[o4] === 1 && t2.circles.push({ center: Dq(e50, o4), radius: 0.07, fill: "rgba(251, 191, 36, 0.18)", stroke: i3, layer: Lq(e50, o4), label: yq(Yq(e50, o4), Fq(e50, o4), "section port") });
};
var Uq = (e50, t2 = {}) => {
  const n2 = { arrows: [], circles: [], infiniteLines: [], lines: [], points: [], polygons: [], rects: [], texts: [], title: "Tiny HyperGraph", coordinateSystem: "cartesian" }, o3 = ((e51, t3) => {
    if (!t3?.highlightSectionMask)
      return;
    const n3 = t3.sectionPortMask ?? e51.problem.portSectionMask;
    if (n3.length !== e51.topology.portCount)
      return;
    let o4 = 0, i4 = 0;
    for (let e52 = 0;e52 < n3.length; e52++)
      n3[e52] === 1 ? o4 += 1 : i4 += 1;
    return o4 !== 0 && i4 !== 0 ? n3 : undefined;
  })(e50, t2), i3 = ((e51) => {
    const t3 = e51.getStaticallyUnroutableRoutes();
    if (t3.length !== 0)
      return new Set(t3.map((e52) => e52.routeId));
  })(e50);
  for (let t3 = 0;t3 < e50.topology.regionCount; t3++) {
    const o4 = e50.topology.regionMetadata?.[t3], i4 = o4?.polygon, r4 = Nq(e50, t3), s3 = Rq(e50, t3), a3 = r4.maxX - r4.minX, c3 = r4.maxY - r4.minY, l3 = Tq(e50, t3), h2 = vq(Aq(e50, t3));
    Array.isArray(i4) && i4.length >= 3 ? n2.polygons.push({ points: i4, fill: h2, layer: l3 }) : n2.rects.push({ center: s3, width: Math.max(a3 - pq, 0.05), height: Math.max(c3 - pq, 0.05), fill: Oq(e50, t3), layer: l3, label: Eq(e50, t3) });
  }
  if (((e51, t3, n3) => {
    for (let o4 = 0;o4 < e51.problem.routeCount; o4++) {
      if (n3 && !n3.has(o4))
        continue;
      const i4 = e51.problem.routeStartPort[o4], r4 = e51.problem.routeEndPort[o4], s3 = kq(e51, i4), a3 = kq(e51, r4), c3 = Mq(e51, o4), l3 = Iq(e51, o4), h2 = wq(e51, o4);
      t3.points.push({ x: s3.x, y: s3.y, color: c3, layer: Lq(e51, i4), label: yq(`route: ${l3}`, h2, "endpoint: start", zq(e51, i4), Fq(e51, i4)) }), t3.points.push({ x: a3.x, y: a3.y, color: c3, layer: Lq(e51, r4), label: yq(`route: ${l3}`, h2, "endpoint: end", zq(e51, r4), Fq(e51, r4)) });
    }
  })(e50, n2, i3), e50.iterations === 0) {
    for (const e51 of n2.polygons)
      e51.stroke = "rgba(128, 128, 128, 0.5)";
    for (const e51 of n2.rects)
      e51.stroke = "rgba(128, 128, 128, 0.5)";
  }
  if (e50.iterations === 0) {
    for (let i4 = 0;i4 < e50.topology.portCount; i4++) {
      const r4 = o3?.[i4] === 1;
      t2.showOnlySectionPortsOnIdle && !r4 || n2.circles.push({ center: Dq(e50, i4), radius: 0.05, fill: e50.topology.portZ[i4] > 0 ? "rgba(52, 152, 219, 0.55)" : "rgba(128, 128, 128, 0.5)", layer: Lq(e50, i4), label: yq(Yq(e50, i4), Fq(e50, i4)) });
    }
    if (i3)
      ((e51, t3) => {
        for (const n3 of e51.getStaticallyUnroutableRoutes()) {
          const { routeId: o4, connectionId: i4, startPortId: r4, endPortId: s3 } = n3, a3 = aq(e51, r4), c3 = aq(e51, s3), l3 = sq(`static reachability failed: ${i4}`, uq(e51, o4), n3.startRegionId ? `startRegionId: ${n3.startRegionId}` : undefined, n3.endRegionId ? `endRegionId: ${n3.endRegionId}` : undefined, n3.pointIds.length >= 2 ? `points: ${n3.pointIds.join(" -> ")}` : undefined, dq(e51, o4));
          t3.lines.push({ points: [a3, c3], strokeColor: iq, strokeDash: "8 4", label: l3 }), t3.circles.push({ center: a3, radius: 0.12, fill: rq, stroke: iq, layer: cq(e51, r4), label: sq(l3, "endpoint: start", lq(e51, r4), hq(e51, r4)) }), t3.circles.push({ center: c3, radius: 0.12, fill: rq, stroke: iq, layer: cq(e51, s3), label: sq(l3, "endpoint: end", lq(e51, s3), hq(e51, s3)) });
        }
      })(e50, n2);
    else {
      const o4 = new Set;
      for (const t3 of e50.state.regionSegments)
        for (const [e51] of t3)
          o4.add(e51);
      if (o4.size > 0 && (Hq(e50, n2), Vq(e50, n2)), t2.showInitialRouteHints !== false) {
        const t3 = new Set(e50.state.unroutedRoutes);
        e50.state.currentRouteId !== undefined && t3.add(e50.state.currentRouteId), ((e51, t4, n3) => {
          for (let o5 = 0;o5 < e51.problem.routeCount; o5++) {
            if (n3 && !n3.has(o5))
              continue;
            const i4 = e51.problem.routeStartPort[o5], r4 = e51.problem.routeEndPort[o5], s3 = kq(e51, i4), a3 = kq(e51, r4), c3 = { x: (s3.x + a3.x) / 2, y: (s3.y + a3.y) / 2 };
            t4.lines.push({ points: [s3, a3], strokeColor: Mq(e51, o5), strokeDash: "3 3", layer: Lq(e51, i4), label: yq(Iq(e51, o5), $q(e51, o5)) }), t4.points.push({ x: c3.x, y: c3.y, color: Mq(e51, o5, 1), layer: Lq(e51, i4), label: yq(Iq(e51, o5), $q(e51, o5)) });
          }
        })(e50, n2, t3);
      }
    }
  } else
    Hq(e50, n2), Vq(e50, n2), ((e51) => Sq(e51) && e51.showUnassignedPortsInVisualization === true)(e50) && ((e51, t3) => {
      for (let n3 = 0;n3 < e51.topology.portCount; n3++)
        e51.state.portAssignment[n3] >= 0 || Wq(e51, n3) || t3.circles.push({ center: Dq(e51, n3), radius: 0.04, fill: e51.topology.portZ[n3] > 0 ? "rgba(52, 152, 219, 0.2)" : "rgba(128, 128, 128, 0.2)", stroke: e51.topology.portZ[n3] > 0 ? "rgba(52, 152, 219, 0.6)" : "rgba(128, 128, 128, 0.6)", layer: Lq(e51, n3), label: yq(Yq(e51, n3), Fq(e51, n3), "state: unassigned") });
    })(e50, n2), Sq(e50) || (((e51, t3) => {
      const n3 = e51.state.currentRouteId;
      if (n3 === undefined || e51.solved)
        return;
      const o4 = e51.problem.routeStartPort[n3], i4 = e51.problem.routeEndPort[n3], r4 = kq(e51, o4), s3 = kq(e51, i4), a3 = Mq(e51, n3), c3 = Iq(e51, n3);
      t3.lines.push({ points: [r4, s3], strokeColor: a3, strokeDash: "10 5", label: yq(c3, $q(e51, n3)) });
    })(e50, n2), ((e51, t3) => {
      if (e51.solved)
        return;
      const n3 = e51.state.currentRouteId, o4 = e51.state.candidateQueue.toArray().sort((e52, t4) => e52.f - t4.f).slice(0, 10);
      for (let i5 = 0;i5 < o4.length; i5++) {
        const r5 = o4[i5], s4 = kq(e51, r5.portId), a3 = i5 === 0;
        t3.points.push({ x: s4.x, y: s4.y, color: a3 ? "green" : "rgba(128, 128, 128, 0.25)", layer: Lq(e51, r5.portId), label: yq(Yq(e51, r5.portId, n3), Fq(e51, r5.portId), `g: ${r5.g.toFixed(2)}`, `h: ${r5.h.toFixed(2)}`, `f: ${r5.f.toFixed(2)}`) });
      }
      const i4 = o4[0];
      if (!i4)
        return;
      const r4 = [];
      let s3 = i4;
      for (;s3; )
        r4.unshift(kq(e51, s3.portId)), s3 = s3.prevCandidate;
      r4.length > 1 && t3.lines.push({ points: r4, strokeColor: n3 !== undefined ? Mq(e51, n3) : "rgba(0, 160, 120, 0.9)" });
    })(e50, n2));
  o3 && Gq(e50, n2, o3), ((e51, t3) => {
    if (e51.failed)
      for (const n3 of e51.getNeverSuccessfullyRoutedRoutes()) {
        const { routeId: o4, connectionId: i4, attempts: r4, startPortId: s3, endPortId: a3 } = n3, c3 = wq(e51, o4), l3 = Dq(e51, s3), h2 = Dq(e51, a3), d2 = yq(`never routed: ${i4}`, `attempts: ${r4}`, c3, n3.startRegionId ? `startRegionId: ${n3.startRegionId}` : undefined, n3.endRegionId ? `endRegionId: ${n3.endRegionId}` : undefined);
        t3.lines.push({ points: [{ x: 0, y: 0 }, { x: l3.x, y: l3.y }], strokeColor: gq, strokeDash: _q, layer: Lq(e51, s3), label: yq(d2, "origin guide", "endpoint: start") }), t3.circles.push({ center: l3, radius: 1, fill: fq, stroke: gq, layer: Lq(e51, s3), label: yq(d2, "endpoint: start", zq(e51, s3), Fq(e51, s3)) }), t3.lines.push({ points: [{ x: 0, y: 0 }, { x: h2.x, y: h2.y }], strokeColor: gq, strokeDash: _q, layer: Lq(e51, a3), label: yq(d2, "origin guide", "endpoint: end") }), t3.circles.push({ center: h2, radius: 1, fill: fq, stroke: gq, layer: Lq(e51, a3), label: yq(d2, "endpoint: end", zq(e51, a3), Fq(e51, a3)) });
      }
  })(e50, n2);
  const r3 = e50.state.unroutedRoutes.length + (e50.state.currentRouteId === undefined ? 0 : 1), s2 = o3 ? o3.reduce((e51, t3) => e51 + Number(t3 === 1), 0) : 0;
  return n2.title = ["Tiny HyperGraph", `iter=${e50.iterations}`, `pending=${r3}`, o3 ? `sectionPorts=${s2}` : undefined, i3 ? `staticReachabilityFailed=${i3.size}` : undefined, e50.failed ? "failed" : e50.solved ? "solved" : "running"].filter(Boolean).join(" | "), n2;
};
var Zq = () => ({ netIds: new Int32Array(0), lesserAngles: new Int32Array(0), greaterAngles: new Int32Array(0), layerMasks: new Int32Array(0), existingCrossingLayerIntersections: 0, existingSameLayerIntersections: 0, existingEntryExitLayerChanges: 0, existingRegionCost: 0, existingSegmentCount: 0 });
var qq = (e50) => ({ netIds: new Int32Array(e50.netIds), lesserAngles: new Int32Array(e50.lesserAngles), greaterAngles: new Int32Array(e50.greaterAngles), layerMasks: new Int32Array(e50.layerMasks), existingCrossingLayerIntersections: e50.existingCrossingLayerIntersections, existingSameLayerIntersections: e50.existingSameLayerIntersections, existingEntryExitLayerChanges: e50.existingEntryExitLayerChanges, existingRegionCost: e50.existingRegionCost, existingSegmentCount: e50.existingSegmentCount });
var Jq = (e50) => {
  return { portAssignment: new Int32Array(e50.portAssignment), regionSegments: (t2 = e50.regionSegments, t2.map((e51) => e51.map(([e52, t3, n2]) => [e52, t3, n2]))), regionIntersectionCaches: e50.regionIntersectionCaches.map(qq), regionCongestionCost: new Float64Array(e50.regionCongestionCost), ripCount: e50.ripCount };
  var t2;
};
var Qq = (e50, t2) => {
  t2 && (t2.minViaPadDiameter !== undefined && (e50.minViaPadDiameter = t2.minViaPadDiameter), t2.DISTANCE_TO_COST !== undefined && (e50.DISTANCE_TO_COST = t2.DISTANCE_TO_COST), t2.RIP_THRESHOLD_START !== undefined && (e50.RIP_THRESHOLD_START = t2.RIP_THRESHOLD_START), t2.RIP_THRESHOLD_END !== undefined && (e50.RIP_THRESHOLD_END = t2.RIP_THRESHOLD_END), t2.RIP_THRESHOLD_RAMP_ATTEMPTS !== undefined && (e50.RIP_THRESHOLD_RAMP_ATTEMPTS = t2.RIP_THRESHOLD_RAMP_ATTEMPTS), t2.RIP_CONGESTION_REGION_COST_FACTOR !== undefined && (e50.RIP_CONGESTION_REGION_COST_FACTOR = t2.RIP_CONGESTION_REGION_COST_FACTOR), t2.TRACE_DENSITY_COST_FACTOR !== undefined && (e50.TRACE_DENSITY_COST_FACTOR = Math.max(0, t2.TRACE_DENSITY_COST_FACTOR)), t2.USE_LAZY_ROUTE_HEURISTIC !== undefined && (e50.USE_LAZY_ROUTE_HEURISTIC = t2.USE_LAZY_ROUTE_HEURISTIC), t2.USE_SPARSE_CANDIDATE_STORAGE !== undefined && (e50.USE_SPARSE_CANDIDATE_STORAGE = t2.USE_SPARSE_CANDIDATE_STORAGE), t2.OWNED_REGIONAL_HOP_FRONTIER !== undefined && (e50.OWNED_REGIONAL_HOP_FRONTIER = t2.OWNED_REGIONAL_HOP_FRONTIER), t2.MAX_ITERATIONS !== undefined && (e50.MAX_ITERATIONS = t2.MAX_ITERATIONS), t2.VERBOSE !== undefined && (e50.VERBOSE = t2.VERBOSE), t2.STATIC_REACHABILITY_PRECHECK !== undefined && (e50.STATIC_REACHABILITY_PRECHECK = t2.STATIC_REACHABILITY_PRECHECK), t2.STATIC_REACHABILITY_PRECHECK_MAX_HOPS !== undefined && (e50.STATIC_REACHABILITY_PRECHECK_MAX_HOPS = t2.STATIC_REACHABILITY_PRECHECK_MAX_HOPS), t2.ACCEPT_BEST_SOLUTION_ON_TIMEOUT !== undefined && (e50.ACCEPT_BEST_SOLUTION_ON_TIMEOUT = t2.ACCEPT_BEST_SOLUTION_ON_TIMEOUT), t2.GREEDY_FINAL_ROUTE_ITERS !== undefined && (e50.GREEDY_FINAL_ROUTE_ITERS = t2.GREEDY_FINAL_ROUTE_ITERS), t2.PARTIAL_RIP_ENABLED !== undefined && (e50.PARTIAL_RIP_ENABLED = t2.PARTIAL_RIP_ENABLED), t2.PARTIAL_RIP_MIN_ROUTE_COUNT !== undefined && (e50.PARTIAL_RIP_MIN_ROUTE_COUNT = t2.PARTIAL_RIP_MIN_ROUTE_COUNT), t2.PARTIAL_RIP_MAX_ROUTE_COUNT !== undefined && (e50.PARTIAL_RIP_MAX_ROUTE_COUNT = t2.PARTIAL_RIP_MAX_ROUTE_COUNT), t2.PARTIAL_RIP_MAX_DISTANCE !== undefined && (e50.PARTIAL_RIP_MAX_DISTANCE = t2.PARTIAL_RIP_MAX_DISTANCE), t2.PARTIAL_RIP_QUALITY_MAX_DISTANCE !== undefined && (e50.PARTIAL_RIP_QUALITY_MAX_DISTANCE = t2.PARTIAL_RIP_QUALITY_MAX_DISTANCE), t2.PARTIAL_RIP_MAX_ATTEMPTS !== undefined && (e50.PARTIAL_RIP_MAX_ATTEMPTS = t2.PARTIAL_RIP_MAX_ATTEMPTS), t2.PARTIAL_RIP_WARMUP_FULL_RIP_ATTEMPTS !== undefined && (e50.PARTIAL_RIP_WARMUP_FULL_RIP_ATTEMPTS = t2.PARTIAL_RIP_WARMUP_FULL_RIP_ATTEMPTS), t2.PARTIAL_RIP_COMPLEXITY_SELECTION_MIN_ROUTE_COUNT !== undefined && (e50.PARTIAL_RIP_COMPLEXITY_SELECTION_MIN_ROUTE_COUNT = t2.PARTIAL_RIP_COMPLEXITY_SELECTION_MIN_ROUTE_COUNT), t2.PARTIAL_RIP_TARGET_MAX_COST_IMPROVEMENT_RATIO !== undefined && (e50.PARTIAL_RIP_TARGET_MAX_COST_IMPROVEMENT_RATIO = t2.PARTIAL_RIP_TARGET_MAX_COST_IMPROVEMENT_RATIO), t2.PARTIAL_RIP_MAX_REGION_COST_GROWTH_RATIO !== undefined && (e50.PARTIAL_RIP_MAX_REGION_COST_GROWTH_RATIO = t2.PARTIAL_RIP_MAX_REGION_COST_GROWTH_RATIO), t2.PARTIAL_RIP_MAX_TOTAL_COST_GROWTH_RATIO !== undefined && (e50.PARTIAL_RIP_MAX_TOTAL_COST_GROWTH_RATIO = t2.PARTIAL_RIP_MAX_TOTAL_COST_GROWTH_RATIO), t2.OUTSIDE_IN_ROUTING !== undefined && (e50.OUTSIDE_IN_ROUTING = t2.OUTSIDE_IN_ROUTING), t2.OUTSIDE_IN_MAX_DISTANCE !== undefined && (e50.OUTSIDE_IN_MAX_DISTANCE = t2.OUTSIDE_IN_MAX_DISTANCE));
};
var Kq = (e50) => ({ minViaPadDiameter: e50.minViaPadDiameter, DISTANCE_TO_COST: e50.DISTANCE_TO_COST, RIP_THRESHOLD_START: e50.RIP_THRESHOLD_START, RIP_THRESHOLD_END: e50.RIP_THRESHOLD_END, RIP_THRESHOLD_RAMP_ATTEMPTS: e50.RIP_THRESHOLD_RAMP_ATTEMPTS, RIP_CONGESTION_REGION_COST_FACTOR: e50.RIP_CONGESTION_REGION_COST_FACTOR, TRACE_DENSITY_COST_FACTOR: e50.TRACE_DENSITY_COST_FACTOR, USE_LAZY_ROUTE_HEURISTIC: e50.USE_LAZY_ROUTE_HEURISTIC, USE_SPARSE_CANDIDATE_STORAGE: e50.USE_SPARSE_CANDIDATE_STORAGE, OWNED_REGIONAL_HOP_FRONTIER: e50.OWNED_REGIONAL_HOP_FRONTIER, MAX_ITERATIONS: e50.MAX_ITERATIONS, VERBOSE: e50.VERBOSE, STATIC_REACHABILITY_PRECHECK: e50.STATIC_REACHABILITY_PRECHECK, STATIC_REACHABILITY_PRECHECK_MAX_HOPS: e50.STATIC_REACHABILITY_PRECHECK_MAX_HOPS, ACCEPT_BEST_SOLUTION_ON_TIMEOUT: e50.ACCEPT_BEST_SOLUTION_ON_TIMEOUT, GREEDY_FINAL_ROUTE_ITERS: e50.GREEDY_FINAL_ROUTE_ITERS, PARTIAL_RIP_ENABLED: e50.PARTIAL_RIP_ENABLED, PARTIAL_RIP_MIN_ROUTE_COUNT: e50.PARTIAL_RIP_MIN_ROUTE_COUNT, PARTIAL_RIP_MAX_ROUTE_COUNT: e50.PARTIAL_RIP_MAX_ROUTE_COUNT, PARTIAL_RIP_MAX_DISTANCE: e50.PARTIAL_RIP_MAX_DISTANCE, PARTIAL_RIP_QUALITY_MAX_DISTANCE: e50.PARTIAL_RIP_QUALITY_MAX_DISTANCE, PARTIAL_RIP_MAX_ATTEMPTS: e50.PARTIAL_RIP_MAX_ATTEMPTS, PARTIAL_RIP_WARMUP_FULL_RIP_ATTEMPTS: e50.PARTIAL_RIP_WARMUP_FULL_RIP_ATTEMPTS, PARTIAL_RIP_COMPLEXITY_SELECTION_MIN_ROUTE_COUNT: e50.PARTIAL_RIP_COMPLEXITY_SELECTION_MIN_ROUTE_COUNT, PARTIAL_RIP_TARGET_MAX_COST_IMPROVEMENT_RATIO: e50.PARTIAL_RIP_TARGET_MAX_COST_IMPROVEMENT_RATIO, PARTIAL_RIP_MAX_REGION_COST_GROWTH_RATIO: e50.PARTIAL_RIP_MAX_REGION_COST_GROWTH_RATIO, PARTIAL_RIP_MAX_TOTAL_COST_GROWTH_RATIO: e50.PARTIAL_RIP_MAX_TOTAL_COST_GROWTH_RATIO, OUTSIDE_IN_ROUTING: e50.OUTSIDE_IN_ROUTING, OUTSIDE_IN_MAX_DISTANCE: e50.OUTSIDE_IN_MAX_DISTANCE });
var eJ = (e50, t2) => e50.f - t2.f;
var tJ = class e50 extends BaseSolver {
  constructor(e51, t2, n2) {
    super(), this.topology = e51, this.problem = t2, Qq(this, n2);
    let o3 = 1;
    const i3 = new Int32Array(e51.portCount).fill(-1), r3 = new Int32Array(e51.portCount).fill(-1);
    for (let t3 = 0;t3 < e51.portCount; t3++) {
      const n3 = e51.incidentPortRegion[t3] ?? [];
      n3.length > o3 && (o3 = n3.length), i3[t3] = n3[0] ?? -1, r3[t3] = n3[1] ?? -1;
    }
    this.candidateHopSlotStride = o3, this.candidateFirstRegionByPortId = i3, this.candidateSecondRegionByPortId = r3, this.hCostByPortId = new Float64Array(e51.portCount), this.hCostRouteIdByPortId = new Int32Array(e51.portCount).fill(-1);
    const s2 = e51.portCount * o3;
    this.candidateHopCapacity = s2, this.state = { portAssignment: new Int32Array(e51.portCount).fill(-1), regionSegments: Array.from({ length: e51.regionCount }, () => []), regionIntersectionCaches: Array.from({ length: e51.regionCount }, () => Zq()), currentRouteId: undefined, currentRouteNetId: undefined, unroutedRoutes: oq(t2.routeCount), candidateQueue: new UZ([], eJ), candidateBestCostByHopId: this.USE_SPARSE_CANDIDATE_STORAGE ? new Map : new Float64Array(s2), candidateBestCostGenerationByHopId: this.USE_SPARSE_CANDIDATE_STORAGE ? new Map : new Uint32Array(s2), candidateBestCostGeneration: 1, goalPortId: -1, ripCount: 0, regionCongestionCost: new Float64Array(e51.regionCount).fill(0) }, this.routeAttemptCountByRouteId = new Uint32Array(t2.routeCount), this.routeSuccessCountByRouteId = new Uint32Array(t2.routeCount);
    const a3 = GZ({ topology: e51, problem: t2, state: this.state, routeSuccessCountByRouteId: this.routeSuccessCountByRouteId, appendSegmentToRegionCache: (e52, t3, n3) => this.appendSegmentToRegionCache(e52, t3, n3) });
    a3 && (this.stats = { ...this.stats, ...a3 });
  }
  state;
  candidateHopSlotStride;
  candidateHopCapacity;
  candidateFirstRegionByPortId;
  candidateSecondRegionByPortId;
  candidateOverflowBestCost;
  regionalHopFrontierQueue;
  regionalHopFrontierEpoch;
  regionalHopFrontierGoalPortId;
  regionalHopFrontierRouteId;
  regionalHopFrontierNetId;
  regionalHopFrontierBestCostGeneration;
  regionalHopFrontiers = new Map;
  _problemSetup;
  hCostByPortId;
  hCostRouteIdByPortId;
  hCostEndRouteId;
  hCostEndX = 0;
  hCostEndY = 0;
  routeAttemptCountByRouteId;
  routeSuccessCountByRouteId;
  bestSolvedStateSnapshot;
  bestSolvedStateSummary;
  hasLoggedNeverSuccessfullyRoutedRoutes = false;
  staticallyUnroutableRoutes = [];
  segmentGeometryScratch = { netId: 0, lesserAngle: 0, greaterAngle: 0, layerMask: 0, entryExitLayerChanges: 0, sameLayerIntersectionCount: 0, crossingLayerIntersectionCount: 0 };
  ADD_SEGMENT_DISTANCE_TO_G = false;
  costAwareFinalReripBudget = 0;
  DISTANCE_TO_COST = 0.05;
  minViaPadDiameter = jZ;
  RIP_THRESHOLD_START = 0.05;
  RIP_THRESHOLD_END = 0.8;
  RIP_THRESHOLD_RAMP_ATTEMPTS = 50;
  RIP_CONGESTION_REGION_COST_FACTOR = 0.1;
  TRACE_DENSITY_COST_FACTOR = 0;
  USE_LAZY_ROUTE_HEURISTIC = true;
  USE_SPARSE_CANDIDATE_STORAGE = false;
  OWNED_REGIONAL_HOP_FRONTIER = false;
  MAX_ITERATIONS = 1e6;
  VERBOSE = false;
  STATIC_REACHABILITY_PRECHECK = true;
  STATIC_REACHABILITY_PRECHECK_MAX_HOPS = 16;
  ACCEPT_BEST_SOLUTION_ON_TIMEOUT = true;
  GREEDY_FINAL_ROUTE_ITERS = 4;
  PARTIAL_RIP_ENABLED = false;
  PARTIAL_RIP_MIN_ROUTE_COUNT = 0;
  PARTIAL_RIP_MAX_ROUTE_COUNT = Number.POSITIVE_INFINITY;
  PARTIAL_RIP_MAX_DISTANCE = 12;
  PARTIAL_RIP_QUALITY_MAX_DISTANCE;
  PARTIAL_RIP_MAX_ATTEMPTS = Number.POSITIVE_INFINITY;
  PARTIAL_RIP_WARMUP_FULL_RIP_ATTEMPTS = 0;
  PARTIAL_RIP_COMPLEXITY_SELECTION_MIN_ROUTE_COUNT = Number.POSITIVE_INFINITY;
  PARTIAL_RIP_TARGET_MAX_COST_IMPROVEMENT_RATIO = 0;
  PARTIAL_RIP_MAX_REGION_COST_GROWTH_RATIO = 0.2;
  PARTIAL_RIP_MAX_TOTAL_COST_GROWTH_RATIO = 0.1;
  OUTSIDE_IN_ROUTING = false;
  OUTSIDE_IN_MAX_DISTANCE = 24;
  resetForProblem(t2) {
    if (this.constructor !== e50)
      throw new Error("TinyHyperGraphSolver.resetForProblem cannot reset subclass routing state");
    this.problem = t2, this._problemSetup = undefined, this.hCostEndRouteId = undefined, this.hCostRouteIdByPortId.fill(-1), this.state.portAssignment.fill(-1);
    for (const e51 of this.state.regionSegments)
      e51.length = 0;
    this.state.regionIntersectionCaches.fill(Zq()), this.state.currentRouteId = undefined, this.state.currentRouteNetId = undefined, this.state.unroutedRoutes = oq(t2.routeCount), this.state.candidateQueue.clear(), this.state.candidateBestCostGeneration = 1, this.state.candidateBestCostByHopId instanceof Map ? this.state.candidateBestCostByHopId.clear() : this.state.candidateBestCostByHopId.fill(0), this.state.candidateBestCostGenerationByHopId instanceof Map ? this.state.candidateBestCostGenerationByHopId.clear() : this.state.candidateBestCostGenerationByHopId.fill(0), this.state.goalPortId = -1, this.state.ripCount = 0, this.state.regionCongestionCost.fill(0), this.routeAttemptCountByRouteId = new Uint32Array(t2.routeCount), this.routeSuccessCountByRouteId = new Uint32Array(t2.routeCount), this.bestSolvedStateSnapshot = undefined, this.bestSolvedStateSummary = undefined, this.hasLoggedNeverSuccessfullyRoutedRoutes = false, this.staticallyUnroutableRoutes = [], this.candidateOverflowBestCost?.clear(), this.solved = false, this.failed = false, this.iterations = 0, this.progress = 0, this.error = null, this.activeSubSolver = undefined, this.failedSubSolvers = undefined, this.timeToSolve = undefined, this.stats = {}, this._setupDone = false;
    const n2 = GZ({ topology: this.topology, problem: t2, state: this.state, routeSuccessCountByRouteId: this.routeSuccessCountByRouteId, appendSegmentToRegionCache: (e51, t3, n3) => this.appendSegmentToRegionCache(e51, t3, n3) });
    n2 && (this.stats = { ...this.stats, ...n2 });
  }
  get problemSetup() {
    return this._problemSetup || (this._problemSetup = this.computeProblemSetup()), this._problemSetup;
  }
  computeProblemSetup() {
    const { topology: e51, problem: t2 } = this, n2 = this.USE_LAZY_ROUTE_HEURISTIC ? undefined : new Float64Array(e51.portCount * t2.routeCount), o3 = e51.portX, i3 = e51.portY, r3 = [], s2 = new Int32Array(e51.portCount).fill(-1), a3 = (e52, t3) => {
      const n3 = r3[e52] ?? new Set;
      n3.add(t3), r3[e52] = n3;
      const o4 = s2[e52];
      o4 === -1 ? s2[e52] = t3 : o4 !== t3 && (s2[e52] = -2);
    };
    for (let r4 = 0;r4 < t2.routeCount; r4++) {
      const s3 = t2.routeNet[r4];
      if (a3(t2.routeStartPort[r4], s3), a3(t2.routeEndPort[r4], s3), n2) {
        const s4 = t2.routeEndPort[r4], a4 = o3[s4], c3 = i3[s4];
        for (let s5 = 0;s5 < e51.portCount; s5++) {
          const e52 = o3[s5] - a4, l3 = i3[s5] - c3;
          n2[s5 * t2.routeCount + r4] = Math.sqrt(e52 * e52 + l3 * l3) * this.DISTANCE_TO_COST;
        }
      }
    }
    return { ...n2 ? { portHCostToEndOfRoute: n2 } : {}, portEndpointNetIds: r3, portEndpointReservationNetId: s2 };
  }
  _setup() {
    if (this.problemSetup, this.STATIC_REACHABILITY_PRECHECK) {
      const e51 = nq({ topology: this.topology, problem: this.problem, problemSetup: this.problemSetup, portAssignment: this.state.portAssignment, routeIds: this.state.unroutedRoutes, maxPrecheckHops: Math.max(0, this.STATIC_REACHABILITY_PRECHECK_MAX_HOPS), getStartingNextRegionId: (e52, t2) => this.getStartingNextRegionId(e52, t2), getRouteSummary: (e52) => this.getRouteSummary(e52) });
      this.staticallyUnroutableRoutes = e51, e51.length > 0 && (this.failed = true, this.error = ((e52) => {
        const t2 = e52.slice(0, 5).map((e53) => {
          const t3 = e53.pointIds.length >= 2 ? `${e53.pointIds[0]}->${e53.pointIds[1]}` : `${e53.startPortId}->${e53.endPortId}`;
          return `${e53.connectionId} (${t3})`;
        }).join(", "), n2 = e52.length - 5;
        return ["Static reachability precheck failed:", `${e52.length} route(s) have no legal path under the current reservation and start-region rules`, n2 > 0 ? `${t2}, +${n2} more` : t2].join(" ");
      })(e51), this.stats = { ...this.stats, staticallyUnroutableRouteCount: e51.length });
    }
  }
  _step() {
    const { problem: e51, topology: t2, state: n2 } = this;
    if (n2.currentRouteId === undefined) {
      if (n2.unroutedRoutes.length === 0)
        return void this.onAllRoutesRouted();
      n2.currentRouteId = n2.unroutedRoutes.shift(), n2.currentRouteNetId = e51.routeNet[n2.currentRouteId], this.routeAttemptCountByRouteId[n2.currentRouteId] += 1, this.resetCandidateBestCosts();
      const t3 = this.getRouteStartPortId(n2.currentRouteId);
      n2.candidateQueue.clear();
      const o4 = this.getStartingNextRegionId(n2.currentRouteId, t3);
      if (o4 === undefined)
        return this.failed = true, void (this.error = `Start port ${t3} has no incident regions`);
      const i4 = this.getHopId(t3, o4);
      this.setCandidateBestCost(i4, 0), n2.candidateQueue.queue({ hopId: i4, nextRegionId: o4, portId: t3, f: 0, g: 0, h: 0 }), n2.goalPortId = this.getRouteEndPortId(n2.currentRouteId);
    }
    const o3 = n2.candidateQueue.dequeue();
    if (!o3)
      return void this.onOutOfCandidates();
    const i3 = o3.hopId ?? this.getHopId(o3.portId, o3.nextRegionId);
    if (o3.g > this.getCandidateBestCost(i3))
      return;
    if (this.isRegionReservedForDifferentNet(o3.nextRegionId))
      return;
    const r3 = t2.regionIncidentPorts[o3.nextRegionId];
    if (this.OWNED_REGIONAL_HOP_FRONTIER) {
      const e52 = this.getRegionalHopFrontier(o3.nextRegionId, r3);
      if (e52)
        return void this.expandRegionalHopFrontier(o3, e52);
    }
    for (const i4 of r3) {
      if (i4 === n2.goalPortId) {
        const e52 = n2.portAssignment[i4];
        if (this.isPortReservedForDifferentNet(i4))
          continue;
        if (e52 !== -1 && e52 !== n2.currentRouteNetId)
          continue;
        return void this.onPathFound(o3);
      }
      if (i4 === o3.portId)
        continue;
      if (e51.portSectionMask[i4] === 0)
        continue;
      const r4 = t2.incidentPortRegion[i4][0] === o3.nextRegionId ? t2.incidentPortRegion[i4][1] : t2.incidentPortRegion[i4][0];
      if (r4 === undefined)
        continue;
      const s2 = this.getHopId(i4, r4);
      if ((n2.candidateQueue.isClosedHopId ? n2.candidateQueue.isClosedHopId(s2) : n2.candidateQueue.isClosedHop?.(i4, r4)) === true)
        continue;
      const a3 = n2.portAssignment[i4];
      if (this.isPortReservedForDifferentNet(i4))
        continue;
      if (a3 !== -1 && a3 !== n2.currentRouteNetId)
        continue;
      if (this.isRegionReservedForDifferentNet(r4))
        continue;
      const c3 = this.getCandidateBestCost(s2);
      if (o3.g >= c3)
        continue;
      let l3, h2 = o3.g + n2.regionCongestionCost[o3.nextRegionId] + (e51.portPenalty?.[i4] ?? 0);
      if (this.ADD_SEGMENT_DISTANCE_TO_G) {
        const e52 = t2.portX[o3.portId] - t2.portX[i4], n3 = t2.portY[o3.portId] - t2.portY[i4];
        l3 = Math.sqrt(e52 * e52 + n3 * n3), h2 += l3 * this.DISTANCE_TO_COST;
      }
      if (h2 >= c3)
        continue;
      const d2 = this.computeG(o3, i4, c3, l3);
      if (!Number.isFinite(d2) || d2 >= c3)
        continue;
      const u2 = this.computeH(i4), p3 = { hopId: s2, prevRegionId: o3.nextRegionId, nextRegionId: r4, portId: i4, g: d2, h: u2, f: d2 + u2, prevCandidate: o3 };
      if (i4 === n2.goalPortId)
        return void this.onPathFound(p3);
      this.setCandidateBestCost(s2, d2), n2.candidateQueue.queue(p3);
    }
  }
  getRegionalHopFrontier(e51, t2) {
    const { state: n2 } = this, o3 = n2.candidateQueue;
    if (!(o3 instanceof ZZ))
      return this.regionalHopFrontierQueue = undefined, this.regionalHopFrontierEpoch = undefined, void this.regionalHopFrontiers.clear();
    const i3 = o3.closureEpoch;
    if (o3 === this.regionalHopFrontierQueue && i3 === this.regionalHopFrontierEpoch && n2.goalPortId === this.regionalHopFrontierGoalPortId && n2.currentRouteId === this.regionalHopFrontierRouteId && n2.currentRouteNetId === this.regionalHopFrontierNetId && n2.candidateBestCostGeneration === this.regionalHopFrontierBestCostGeneration || (this.regionalHopFrontierQueue = o3, this.regionalHopFrontierEpoch = i3, this.regionalHopFrontierGoalPortId = n2.goalPortId, this.regionalHopFrontierRouteId = n2.currentRouteId, this.regionalHopFrontierNetId = n2.currentRouteNetId, this.regionalHopFrontierBestCostGeneration = n2.candidateBestCostGeneration, this.regionalHopFrontiers.clear()), !Array.isArray(t2) || t2.length > 2147483647)
      return;
    let r3 = this.regionalHopFrontiers.get(e51);
    if (!r3 || r3.neighbors !== t2) {
      const n3 = new Int32Array(t2.length);
      for (let e52 = 0;e52 < t2.length; e52++)
        n3[e52] = e52 + 1 < t2.length ? e52 + 1 : -1;
      r3 = { neighbors: t2, next: n3, prepared: new Uint8Array(t2.length), nextRegionIds: new Float64Array(t2.length), hopIds: new Float64Array(t2.length), head: t2.length > 0 ? 0 : -1 }, this.regionalHopFrontiers.set(e51, r3);
    }
    return r3;
  }
  expandRegionalHopFrontier(e51, t2) {
    const { problem: n2, topology: o3, state: i3 } = this, { neighbors: r3, next: s2, prepared: a3, nextRegionIds: c3, hopIds: l3 } = t2;
    let h2 = t2.head, d2 = -1;
    for (;h2 !== -1; ) {
      const u2 = h2;
      h2 = s2[u2];
      const p3 = d2;
      d2 = u2;
      const m2 = r3[u2];
      if (m2 === i3.goalPortId) {
        const t3 = i3.portAssignment[m2];
        if (this.isPortReservedForDifferentNet(m2))
          continue;
        if (t3 !== -1 && t3 !== i3.currentRouteNetId)
          continue;
        return void this.onPathFound(e51);
      }
      if (m2 === e51.portId)
        continue;
      let g2, f2;
      if (a3[u2])
        g2 = c3[u2], f2 = l3[u2];
      else {
        if (n2.portSectionMask[m2] === 0)
          continue;
        const t3 = o3.incidentPortRegion[m2][0] === e51.nextRegionId ? o3.incidentPortRegion[m2][1] : o3.incidentPortRegion[m2][0];
        if (t3 === undefined)
          continue;
        g2 = t3, f2 = this.getHopId(m2, g2);
      }
      if ((i3.candidateQueue.isClosedHopId ? i3.candidateQueue.isClosedHopId(f2) : i3.candidateQueue.isClosedHop?.(m2, g2)) === true) {
        p3 === -1 ? t2.head = h2 : s2[p3] = h2, d2 = p3;
        continue;
      }
      if (!a3[u2]) {
        const e52 = i3.portAssignment[m2];
        if (this.isPortReservedForDifferentNet(m2))
          continue;
        if (e52 !== -1 && e52 !== i3.currentRouteNetId)
          continue;
        if (this.isRegionReservedForDifferentNet(g2))
          continue;
        c3[u2] = g2, l3[u2] = f2, a3[u2] = 1;
      }
      const _2 = this.getCandidateBestCost(f2);
      if (e51.g >= _2)
        continue;
      let y2, b2 = e51.g + i3.regionCongestionCost[e51.nextRegionId] + (n2.portPenalty?.[m2] ?? 0);
      if (this.ADD_SEGMENT_DISTANCE_TO_G) {
        const t3 = o3.portX[e51.portId] - o3.portX[m2], n3 = o3.portY[e51.portId] - o3.portY[m2];
        y2 = Math.sqrt(t3 * t3 + n3 * n3), b2 += y2 * this.DISTANCE_TO_COST;
      }
      if (b2 >= _2)
        continue;
      const x2 = this.computeG(e51, m2, _2, y2);
      if (!Number.isFinite(x2) || x2 >= _2)
        continue;
      const v2 = this.computeH(m2), I2 = { hopId: f2, prevRegionId: e51.nextRegionId, nextRegionId: g2, portId: m2, g: x2, h: v2, f: x2 + v2, prevCandidate: e51 };
      if (m2 === i3.goalPortId)
        return void this.onPathFound(I2);
      this.setCandidateBestCost(f2, x2), i3.candidateQueue.queue(I2);
    }
  }
  resetCandidateBestCosts() {
    const { state: e51 } = this;
    if (this.candidateOverflowBestCost?.clear(), e51.candidateBestCostGeneration === 4294967295)
      return e51.candidateBestCostByHopId instanceof Map && e51.candidateBestCostByHopId.clear(), e51.candidateBestCostGenerationByHopId instanceof Map ? e51.candidateBestCostGenerationByHopId.clear() : e51.candidateBestCostGenerationByHopId.fill(0), void (e51.candidateBestCostGeneration = 1);
    e51.candidateBestCostGeneration += 1;
  }
  getCandidateBestCost(e51) {
    if (e51 < 0)
      return this.candidateOverflowBestCost?.get(e51) ?? Number.POSITIVE_INFINITY;
    const { state: t2 } = this, n2 = t2.candidateBestCostGenerationByHopId;
    return (n2 instanceof Map ? n2.get(e51) : n2[e51]) === t2.candidateBestCostGeneration ? t2.candidateBestCostByHopId instanceof Map ? t2.candidateBestCostByHopId.get(e51) : t2.candidateBestCostByHopId[e51] : Number.POSITIVE_INFINITY;
  }
  setCandidateBestCost(e51, t2) {
    if (e51 < 0)
      return this.candidateOverflowBestCost || (this.candidateOverflowBestCost = new Map), void this.candidateOverflowBestCost.set(e51, t2);
    const { state: n2 } = this;
    n2.candidateBestCostGenerationByHopId instanceof Map ? n2.candidateBestCostGenerationByHopId.set(e51, n2.candidateBestCostGeneration) : n2.candidateBestCostGenerationByHopId[e51] = n2.candidateBestCostGeneration, n2.candidateBestCostByHopId instanceof Map ? n2.candidateBestCostByHopId.set(e51, t2) : n2.candidateBestCostByHopId[e51] = t2;
  }
  getHopId(e51, t2) {
    const n2 = e51 * this.candidateHopSlotStride;
    if (this.candidateFirstRegionByPortId[e51] === t2)
      return n2;
    if (this.candidateSecondRegionByPortId[e51] === t2)
      return n2 + 1;
    const o3 = this.topology.incidentPortRegion[e51];
    for (let e52 = 2;e52 < (o3?.length ?? 0); e52++)
      if (o3[e52] === t2)
        return n2 + e52;
    return -(e51 * this.topology.regionCount + t2) - 1;
  }
  getStartingNextRegionId(e51, t2) {
    const n2 = this.topology.incidentPortRegion[t2] ?? [], o3 = this.problem.routeNet[e51];
    return n2.find((e52) => this.problem.regionNetId[e52] === -1) ?? n2.find((e52) => this.problem.regionNetId[e52] === o3) ?? n2[0];
  }
  getRouteStartPortId(e51) {
    return this.problem.routeStartPort[e51];
  }
  getRouteEndPortId(e51) {
    return this.problem.routeEndPort[e51];
  }
  isPortReservedForDifferentNet(e51) {
    const t2 = this.problemSetup.portEndpointReservationNetId[e51] ?? -1;
    return t2 === -2 || t2 !== -1 && t2 !== this.state.currentRouteNetId;
  }
  isRegionReservedForDifferentNet(e51) {
    const t2 = this.problem.regionNetId[e51];
    return t2 !== -1 && t2 !== this.state.currentRouteNetId;
  }
  isKnownSingleLayerRegion(e51) {
    const t2 = this.topology.regionAvailableZMask?.[e51] ?? 0;
    return $Z(t2);
  }
  computeRegionCostForRegion(e51, t2, n2, o3, i3) {
    return YZ(this.topology.regionWidth[e51], this.topology.regionHeight[e51], t2, n2, o3, i3, this.topology.regionAvailableZMask?.[e51] ?? 0, this.minViaPadDiameter, this.TRACE_DENSITY_COST_FACTOR);
  }
  populateSegmentGeometryScratch(e51, t2, n2) {
    return this.populateBaseSegmentGeometryScratch(e51, t2, n2);
  }
  populateBaseSegmentGeometryScratch(e51, t2, n2) {
    const { state: o3, topology: i3 } = this, r3 = this.segmentGeometryScratch, s2 = this.candidateFirstRegionByPortId[t2] === e51 || this.candidateSecondRegionByPortId[t2] !== e51 ? i3.portAngleForRegion1[t2] : i3.portAngleForRegion2?.[t2] ?? i3.portAngleForRegion1[t2], a3 = this.candidateFirstRegionByPortId[n2] === e51 || this.candidateSecondRegionByPortId[n2] !== e51 ? i3.portAngleForRegion1[n2] : i3.portAngleForRegion2?.[n2] ?? i3.portAngleForRegion1[n2], c3 = i3.portZ[t2], l3 = i3.portZ[n2];
    return r3.lesserAngle = s2 < a3 ? s2 : a3, r3.greaterAngle = s2 < a3 ? a3 : s2, r3.layerMask = 1 << c3 | 1 << l3, r3.entryExitLayerChanges = c3 !== l3 ? 1 : 0, r3.netId = o3.currentRouteNetId, r3;
  }
  appendSegmentToRegionCache(e51, t2, n2) {
    const { state: o3 } = this, i3 = o3.regionIntersectionCaches[e51], r3 = this.populateSegmentGeometryScratch(e51, t2, n2);
    VZ(i3, r3);
    const { sameLayerIntersectionCount: s2, crossingLayerIntersectionCount: a3, entryExitLayerChanges: c3 } = r3, l3 = i3.netIds.length + 1, h2 = new Int32Array(l3);
    h2.set(i3.netIds), h2[l3 - 1] = o3.currentRouteNetId;
    const d2 = new Int32Array(l3);
    d2.set(i3.lesserAngles), d2[l3 - 1] = r3.lesserAngle;
    const u2 = new Int32Array(l3);
    u2.set(i3.greaterAngles), u2[l3 - 1] = r3.greaterAngle;
    const p3 = new Int32Array(l3);
    p3.set(i3.layerMasks), p3[l3 - 1] = r3.layerMask;
    const m2 = i3.existingSameLayerIntersections + s2, g2 = i3.existingCrossingLayerIntersections + a3, f2 = i3.existingEntryExitLayerChanges + c3, _2 = d2.length;
    o3.regionIntersectionCaches[e51] = { netIds: h2, lesserAngles: d2, greaterAngles: u2, layerMasks: p3, existingSameLayerIntersections: m2, existingCrossingLayerIntersections: g2, existingEntryExitLayerChanges: f2, existingSegmentCount: _2, existingRegionCost: this.computeRegionCostForRegion(e51, m2, g2, f2, _2) };
  }
  getSolvedPathSegments(e51) {
    const { state: t2 } = this, n2 = [];
    let o3 = e51;
    for (;o3; )
      n2.unshift(o3), o3 = o3.prevCandidate;
    const i3 = [];
    for (let e52 = 1;e52 < n2.length; e52++)
      i3.push({ regionId: n2[e52 - 1].nextRegionId, fromPortId: n2[e52 - 1].portId, toPortId: n2[e52].portId });
    const r3 = n2[n2.length - 1];
    return r3 && r3.portId !== t2.goalPortId && i3.push({ regionId: r3.nextRegionId, fromPortId: r3.portId, toPortId: t2.goalPortId }), i3;
  }
  resetRoutingStateForRerip() {
    const { topology: e51, problem: t2, state: n2 } = this;
    n2.portAssignment.fill(-1), n2.regionSegments = Array.from({ length: e51.regionCount }, () => []), n2.regionIntersectionCaches = Array.from({ length: e51.regionCount }, () => Zq()), n2.currentRouteNetId = undefined, n2.currentRouteId = undefined, n2.unroutedRoutes = qZ(oq(t2.routeCount), n2.ripCount), n2.candidateQueue.clear(), this.resetCandidateBestCosts(), n2.goalPortId = -1;
  }
  getMaxRegionCost() {
    const { topology: e51, state: t2 } = this;
    let n2 = 0;
    for (let o3 = 0;o3 < e51.regionCount; o3++) {
      const e52 = t2.regionIntersectionCaches[o3]?.existingRegionCost ?? 0;
      n2 = Math.max(n2, e52);
    }
    return n2;
  }
  getRouteMetadata(e51) {
    return this.problem.routeMetadata?.[e51];
  }
  getRouteConnectionId(e51) {
    const t2 = this.getRouteMetadata(e51)?.connectionId;
    return typeof t2 == "string" ? t2 : `route-${e51}`;
  }
  getRouteSummary(e51) {
    return (({ problem: e52, routeId: t2, getRouteMetadata: n2, getRouteConnectionId: o3 }) => {
      const i3 = n2?.(t2) ?? JZ(e52, t2);
      return { routeId: t2, connectionId: o3?.(t2) ?? KZ(e52, t2), startPortId: e52.routeStartPort[t2], endPortId: e52.routeEndPort[t2], startRegionId: typeof i3?.startRegionId == "string" ? i3.startRegionId : undefined, endRegionId: typeof i3?.endRegionId == "string" ? i3.endRegionId : undefined, pointIds: QZ(i3) };
    })({ problem: this.problem, routeId: e51, getRouteMetadata: (e52) => this.getRouteMetadata(e52), getRouteConnectionId: (e52) => this.getRouteConnectionId(e52) });
  }
  getAdditionalRegionLabel(e51) {}
  getNeverSuccessfullyRoutedRoutes() {
    const e51 = [];
    for (let t2 = 0;t2 < this.problem.routeCount; t2++) {
      const n2 = this.routeAttemptCountByRouteId[t2];
      n2 === 0 || this.routeSuccessCountByRouteId[t2] > 0 || e51.push({ ...this.getRouteSummary(t2), attempts: n2 });
    }
    return e51;
  }
  getStaticallyUnroutableRoutes() {
    return this.staticallyUnroutableRoutes;
  }
  logNeverSuccessfullyRoutedRoutes() {
    if (!this.VERBOSE || this.hasLoggedNeverSuccessfullyRoutedRoutes)
      return;
    const e51 = this.getNeverSuccessfullyRoutedRoutes();
    if (this.hasLoggedNeverSuccessfullyRoutedRoutes = true, e51.length !== 0) {
      console.log(["[TinyHyperGraphSolver:never-routed-summary]", `count=${e51.length}`].join(" "));
      for (const t2 of e51) {
        const e52 = t2.pointIds.length >= 2 ? `${t2.pointIds[0]}->${t2.pointIds[1]}` : "unknown";
        console.log(["[TinyHyperGraphSolver:never-routed]", `routeId=${t2.routeId}`, `connectionId=${t2.connectionId}`, `attempts=${t2.attempts}`, `pointPath=${e52}`, `startRegionId=${t2.startRegionId ?? "unknown"}`, `endRegionId=${t2.endRegionId ?? "unknown"}`].join(" "));
      }
    }
  }
  logRipEvent(e51, t2, n2 = {}) {
    this.VERBOSE && console.log(["[TinyHyperGraphSolver:rip]", `ripCount=${this.state.ripCount}`, `maxRegionCostBeforeRip=${t2.toFixed(3)}`, `reason=${e51}`, ...Object.entries(n2).map(([e52, t3]) => `${e52}=${typeof t3 == "number" ? Number.isInteger(t3) ? String(t3) : t3.toFixed(3) : t3}`)].join(" "));
  }
  compareRegionCostSummaries(e51, t2) {
    return e51.maxRegionCost !== t2.maxRegionCost ? e51.maxRegionCost - t2.maxRegionCost : e51.totalRegionCost - t2.totalRegionCost;
  }
  captureBestSolvedState(e51) {
    this.bestSolvedStateSummary && this.compareRegionCostSummaries(e51, this.bestSolvedStateSummary) >= 0 || this.replaceBestSolvedState(e51);
  }
  replaceBestSolvedState(e51) {
    this.bestSolvedStateSummary = e51, this.bestSolvedStateSnapshot = Jq({ portAssignment: this.state.portAssignment, regionSegments: this.state.regionSegments, regionIntersectionCaches: this.state.regionIntersectionCaches, regionCongestionCost: this.state.regionCongestionCost, ripCount: this.state.ripCount });
  }
  restoreBestSolvedState() {
    if (!this.bestSolvedStateSnapshot)
      return;
    const e51 = Jq(this.bestSolvedStateSnapshot);
    this.state.portAssignment = e51.portAssignment, this.state.regionSegments = e51.regionSegments, this.state.regionIntersectionCaches = e51.regionIntersectionCaches, this.state.regionCongestionCost = e51.regionCongestionCost, this.state.ripCount = e51.ripCount, this.state.currentRouteId = undefined, this.state.currentRouteNetId = undefined, this.state.unroutedRoutes = [], this.state.candidateQueue.clear(), this.resetCandidateBestCosts(), this.state.goalPortId = -1;
  }
  getRemainingRouteIdsForGreedyFinalRoute() {
    const e51 = new Set(this.state.unroutedRoutes);
    return this.state.currentRouteId !== undefined && e51.add(this.state.currentRouteId), [...e51];
  }
  applySnapshotToGreedyFinalRouteSolver(e51, t2, n2) {
    const o3 = Jq(t2);
    e51.state.portAssignment = o3.portAssignment, e51.state.regionSegments = o3.regionSegments, e51.state.regionIntersectionCaches = o3.regionIntersectionCaches, e51.state.regionCongestionCost = o3.regionCongestionCost, e51.state.ripCount = 0, e51.state.currentRouteId = undefined, e51.state.currentRouteNetId = undefined, e51.state.unroutedRoutes = [...n2], e51.state.candidateQueue.clear(), e51.resetCandidateBestCosts(), e51.state.goalPortId = -1;
  }
  summarizeSolvedState(e51) {
    let t2 = 0, n2 = 0;
    for (const o3 of e51.state.regionIntersectionCaches) {
      const e52 = o3.existingRegionCost;
      t2 = Math.max(t2, e52), n2 += e52;
    }
    return { maxRegionCost: t2, totalRegionCost: n2 };
  }
  createGreedyFinalRouteSolver(e51, t2) {
    return new nJ(this.topology, this.problem, e51);
  }
  tryGreedyFinalRouteAcceptance() {
    const e51 = Math.max(0, Math.floor(this.GREEDY_FINAL_ROUTE_ITERS));
    if (e51 === 0)
      return false;
    const t2 = this.getRemainingRouteIdsForGreedyFinalRoute();
    if (t2.length === 0)
      return false;
    const n2 = Jq({ portAssignment: this.state.portAssignment, regionSegments: this.state.regionSegments, regionIntersectionCaches: this.state.regionIntersectionCaches, regionCongestionCost: this.state.regionCongestionCost, ripCount: this.state.ripCount });
    let o3 = 50000;
    for (let i3 = this.state.ripCount < this.costAwareFinalReripBudget ? -1 : 0;i3 < e51; i3++) {
      const e52 = i3 <= 0 ? t2 : qZ(t2, this.state.ripCount + i3), r3 = this.createGreedyFinalRouteSolver({ ...Kq(this), ACCEPT_BEST_SOLUTION_ON_TIMEOUT: false, GREEDY_FINAL_ROUTE_ITERS: 0, MAX_ITERATIONS: 50000, RIP_THRESHOLD_RAMP_ATTEMPTS: 0, STATIC_REACHABILITY_PRECHECK: false, OUTSIDE_IN_ROUTING: false, PARTIAL_RIP_ENABLED: false }, i3);
      if (o3 = r3.MAX_ITERATIONS, this.applySnapshotToGreedyFinalRouteSolver(r3, n2, e52), r3.solve(), r3.solved && !r3.failed)
        return this.bestSolvedStateSnapshot = Jq({ portAssignment: r3.state.portAssignment, regionSegments: r3.state.regionSegments, regionIntersectionCaches: r3.state.regionIntersectionCaches, regionCongestionCost: r3.state.regionCongestionCost, ripCount: r3.state.ripCount }), this.bestSolvedStateSummary = this.summarizeSolvedState(r3), this.restoreBestSolvedState(), this.stats = { ...this.stats, acceptedGreedyFinalRouteOnTimeout: true, greedyFinalRouteIter: Math.max(0, i3), finalRoutingStrategy: i3 < 0 ? "congestion-aware" : "greedy", greedyFinalRouteRemainingRouteCount: t2.length, greedyFinalRouteMaxIterations: o3, neverSuccessfullyRoutedRouteCount: 0, maxRegionCost: this.bestSolvedStateSummary.maxRegionCost, totalRegionCost: this.bestSolvedStateSummary.totalRegionCost, bestMaxRegionCost: this.bestSolvedStateSummary.maxRegionCost, bestTotalRegionCost: this.bestSolvedStateSummary.totalRegionCost }, this.solved = true, this.failed = false, this.error = null, true;
    }
    return this.stats = { ...this.stats, greedyFinalRouteAttemptCount: e51, greedyFinalRouteRemainingRouteCount: t2.length, greedyFinalRouteMaxIterations: o3 }, false;
  }
  onAllRoutesRouted() {
    const { topology: e51, state: t2 } = this, n2 = this.RIP_THRESHOLD_RAMP_ATTEMPTS <= 0 ? 1 : Math.min(1, t2.ripCount / this.RIP_THRESHOLD_RAMP_ATTEMPTS), o3 = this.RIP_THRESHOLD_START + (this.RIP_THRESHOLD_END - this.RIP_THRESHOLD_START) * n2, i3 = [], r3 = new Float64Array(e51.regionCount);
    let s2 = 0, a3 = 0;
    for (let n3 = 0;n3 < e51.regionCount; n3++) {
      const e52 = t2.regionIntersectionCaches[n3]?.existingRegionCost ?? 0;
      r3[n3] = e52, s2 = Math.max(s2, e52), a3 += e52, e52 > o3 && i3.push(n3);
    }
    const c3 = { maxRegionCost: s2, totalRegionCost: a3 }, l3 = i3.length === 0 || t2.ripCount >= this.RIP_THRESHOLD_RAMP_ATTEMPTS;
    if (l3 ? (!this.bestSolvedStateSummary || this.compareRegionCostSummaries(c3, this.bestSolvedStateSummary) < 0) && (this.bestSolvedStateSummary = c3) : this.captureBestSolvedState(c3), this.stats = { ...this.stats, currentRipThreshold: o3, hotRegionCount: i3.length, maxRegionCost: s2, totalRegionCost: a3, bestMaxRegionCost: this.bestSolvedStateSummary?.maxRegionCost, bestTotalRegionCost: this.bestSolvedStateSummary?.totalRegionCost, ripCount: t2.ripCount }, l3)
      this.solved = true;
    else {
      for (let n3 = 0;n3 < e51.regionCount; n3++)
        t2.regionCongestionCost[n3] += r3[n3] * this.RIP_CONGESTION_REGION_COST_FACTOR;
      t2.ripCount += 1, this.resetRoutingStateForRerip(), this.stats = { ...this.stats, ripCount: t2.ripCount, maxRegionCostBeforeRip: s2, reripRegionCount: i3.length }, this.logRipEvent("hot_regions", s2, { hotRegionCount: i3.length, currentRipThreshold: o3 });
    }
  }
  onOutOfCandidates() {
    const { topology: e51, state: t2 } = this, n2 = t2.currentRouteId, o3 = this.getMaxRegionCost();
    for (let n3 = 0;n3 < e51.regionCount; n3++) {
      const e52 = t2.regionIntersectionCaches[n3]?.existingRegionCost ?? 0;
      t2.regionCongestionCost[n3] += e52 * this.RIP_CONGESTION_REGION_COST_FACTOR;
    }
    t2.ripCount += 1, this.resetRoutingStateForRerip(), this.stats = { ...this.stats, ripCount: t2.ripCount, maxRegionCost: o3, maxRegionCostBeforeRip: o3, reripReason: "out_of_candidates" }, this.logRipEvent("out_of_candidates", o3, { ...n2 === undefined ? {} : { routeId: n2, connectionId: this.getRouteConnectionId(n2) } });
  }
  onPathFound(e51) {
    const { state: t2 } = this, n2 = t2.currentRouteId;
    if (n2 === undefined)
      return;
    this.routeSuccessCountByRouteId[n2] += 1;
    const o3 = this.getSolvedPathSegments(e51);
    for (const { regionId: e52, fromPortId: i3, toPortId: r3 } of o3)
      t2.regionSegments[e52].push([n2, i3, r3]), t2.portAssignment[i3] = t2.currentRouteNetId, t2.portAssignment[r3] = t2.currentRouteNetId, this.appendSegmentToRegionCache(e52, i3, r3);
    t2.candidateQueue.clear(), t2.currentRouteNetId = undefined, t2.currentRouteId = undefined;
  }
  computeG(e51, t2, n2 = Number.POSITIVE_INFINITY, o3) {
    const { state: i3, topology: r3 } = this, s2 = e51.nextRegionId, a3 = i3.regionIntersectionCaches[s2], c3 = i3.regionCongestionCost[s2], l3 = this.problem.portPenalty?.[t2] ?? 0;
    let h2 = 0;
    if (this.ADD_SEGMENT_DISTANCE_TO_G) {
      let n3 = o3;
      if (n3 === undefined) {
        const o4 = r3.portX[e51.portId] - r3.portX[t2], i4 = r3.portY[e51.portId] - r3.portY[t2];
        n3 = Math.sqrt(o4 * o4 + i4 * i4);
      }
      h2 = n3 * this.DISTANCE_TO_COST;
    }
    if (e51.g + c3 + l3 + h2 > n2 + 0.000000001)
      return Number.POSITIVE_INFINITY;
    let d2 = 0, u2 = 0, p3 = r3.portZ[e51.portId] !== r3.portZ[t2] ? 1 : 0;
    if (a3.existingSegmentCount > 0) {
      const n3 = this.populateBaseSegmentGeometryScratch(s2, e51.portId, t2);
      VZ(a3, n3), d2 = n3.sameLayerIntersectionCount, u2 = n3.crossingLayerIntersectionCount, p3 = n3.entryExitLayerChanges;
    }
    if (d2 > 0 && this.isKnownSingleLayerRegion(s2))
      return Number.POSITIVE_INFINITY;
    const m2 = this.computeRegionCostForRegion(s2, a3.existingSameLayerIntersections + d2, a3.existingCrossingLayerIntersections + u2, a3.existingEntryExitLayerChanges + p3, a3.existingSegmentCount + 1) - a3.existingRegionCost;
    return e51.g + m2 + c3 + l3 + h2;
  }
  tryFinalAcceptance() {
    const e51 = this.getNeverSuccessfullyRoutedRoutes();
    if (this.stats = { ...this.stats, neverSuccessfullyRoutedRouteCount: e51.length }, this.ACCEPT_BEST_SOLUTION_ON_TIMEOUT && this.bestSolvedStateSnapshot && this.bestSolvedStateSummary)
      return this.restoreBestSolvedState(), this.stats = { ...this.stats, acceptedBestSolutionOnTimeout: true, maxRegionCost: this.bestSolvedStateSummary.maxRegionCost, totalRegionCost: this.bestSolvedStateSummary.totalRegionCost, bestMaxRegionCost: this.bestSolvedStateSummary.maxRegionCost, bestTotalRegionCost: this.bestSolvedStateSummary.totalRegionCost }, this.solved = true, this.failed = false, void (this.error = null);
    this.ACCEPT_BEST_SOLUTION_ON_TIMEOUT && this.tryGreedyFinalRouteAcceptance() || this.logNeverSuccessfullyRoutedRoutes();
  }
  getRouteHeuristic(e51, t2) {
    const n2 = this.problemSetup.portHCostToEndOfRoute;
    if (n2)
      return n2[t2 * this.problem.routeCount + e51];
    if (this.hCostEndRouteId !== e51) {
      this.hCostEndRouteId = e51;
      const t3 = this.getRouteEndPortId(e51);
      this.hCostEndX = this.topology.portX[t3], this.hCostEndY = this.topology.portY[t3];
    }
    if (this.hCostRouteIdByPortId[t2] !== e51) {
      const n3 = this.topology.portX[t2] - this.hCostEndX, o3 = this.topology.portY[t2] - this.hCostEndY;
      this.hCostByPortId[t2] = Math.sqrt(n3 * n3 + o3 * o3) * this.DISTANCE_TO_COST, this.hCostRouteIdByPortId[t2] = e51;
    }
    return this.hCostByPortId[t2];
  }
  computeH(e51) {
    return this.getRouteHeuristic(this.state.currentRouteId, e51);
  }
  visualize() {
    return Uq(this);
  }
  getOutput() {
    return FZ(this);
  }
};
var nJ = class extends tJ {
  computeG(e51, t2) {
    return e51.g;
  }
};
var oJ = (e51, t2) => {
  const n2 = e51.priorityOwnerCount - t2.priorityOwnerCount;
  if (n2 !== 0)
    return n2;
  const o3 = e51.estimatedTotalDistance - t2.estimatedTotalDistance;
  return o3 !== 0 ? o3 : e51.queueOrder - t2.queueOrder;
};
var iJ = class {
  heap = [];
  push(e51) {
    this.heap.push(e51);
    let t2 = this.heap.length - 1;
    for (;t2 > 0; ) {
      const e52 = Math.floor((t2 - 1) / 2);
      if (oJ(this.heap[e52], this.heap[t2]) <= 0)
        break;
      [this.heap[e52], this.heap[t2]] = [this.heap[t2], this.heap[e52]], t2 = e52;
    }
  }
  pop() {
    const e51 = this.heap[0], t2 = this.heap.pop();
    if (!e51 || !t2)
      return null;
    if (this.heap.length === 0)
      return e51;
    this.heap[0] = t2;
    let n2 = 0;
    for (;; ) {
      const e52 = 2 * n2 + 1, t3 = e52 + 1;
      let o3 = n2;
      if (e52 < this.heap.length && oJ(this.heap[e52], this.heap[o3]) < 0 && (o3 = e52), t3 < this.heap.length && oJ(this.heap[t3], this.heap[o3]) < 0 && (o3 = t3), o3 === n2)
        break;
      [this.heap[n2], this.heap[o3]] = [this.heap[o3], this.heap[n2]], n2 = o3;
    }
    return e51;
  }
};
var rJ = (e51, t2, n2) => {
  if (e51 === t2)
    return true;
  if (e51.size > t2.size + n2.length)
    return false;
  for (const o3 of e51)
    if (!t2.has(o3) && !n2.includes(o3))
      return false;
  return true;
};
var sJ = (e51, t2) => !(e51.distance > t2.distance) && ((e52, t3) => {
  if (e52.size > t3.size)
    return false;
  for (const n2 of e52)
    if (!t3.has(n2))
      return false;
  return true;
})(e51.owners, t2.owners);
var aJ = (e51, t2) => {
  const n2 = [], o3 = [];
  let i3 = e51;
  for (;i3 !== null; )
    n2.push(i3.state), i3.incomingHop !== null && o3.push(i3.incomingHop), i3 = i3.parent;
  return n2.reverse(), o3.reverse(), { found: true, states: n2, hops: o3, owners: new Set(e51.owners), distance: e51.distance, expandedLabelCount: t2 };
};
var cJ = (e51) => {
  for (;; ) {
    const t2 = e51.pop();
    if (t2 === null)
      return null;
    if (t2.active)
      return t2;
  }
};
var lJ = (e51) => {
  const t2 = e51.maxExpandedLabels ?? Number.POSITIVE_INFINITY;
  if (t2 !== Number.POSITIVE_INFINITY && (!Number.isInteger(t2) || t2 < 0))
    throw new Error("maxExpandedLabels must be a non-negative integer");
  const n2 = e51.minimumOwnerCount ?? 0;
  if (!Number.isInteger(n2) || n2 < 0)
    throw new Error("minimumOwnerCount must be a non-negative integer");
  if (e51.checkReachability) {
    const n3 = ((e52, t3) => {
      const n4 = [e52.start], o4 = new Set([e52.getStateKey(e52.start)]);
      let i4 = 0, r4 = 0;
      for (let s3 = 0;s3 < n4.length; s3++) {
        const a4 = n4[s3];
        if (e52.isGoal(a4))
          return;
        if (i4 >= t3)
          return;
        i4++;
        for (const t4 of e52.getHops(a4)) {
          if (r4 += t4.distance, t4.distance < 0 || !Number.isFinite(r4))
            return;
          const i5 = e52.getStateKey(t4.state);
          o4.has(i5) || (o4.add(i5), n4.push(t4.state));
        }
      }
      return { found: false, reason: "no_path", expandedLabelCount: i4 };
    })(e51, t2);
    if (n3)
      return n3;
  }
  const o3 = new Map, i3 = new iJ;
  let r3 = 0, s2 = 0;
  const a3 = { state: e51.start, stateKey: e51.getStateKey(e51.start), owners: new Set, priorityOwnerCount: n2, distance: 0, estimatedTotalDistance: e51.getRemainingDistance ? e51.getRemainingDistance(e51.start) : 0, parent: null, incomingHop: null, queueOrder: r3++, active: true };
  if (!Number.isFinite(a3.estimatedTotalDistance) || a3.estimatedTotalDistance < 0)
    throw new Error("Distinct-owner blocker estimates must be finite and >= 0");
  for (o3.set(a3.stateKey, [a3]), i3.push(a3);; ) {
    const a4 = cJ(i3);
    if (a4 === null)
      return { found: false, reason: "no_path", expandedLabelCount: s2 };
    if (e51.isGoal(a4.state))
      return aJ(a4, s2);
    if (s2 >= t2)
      return { found: false, reason: "expansion_limit", expandedLabelCount: s2 };
    s2++;
    for (const t3 of e51.getHops(a4.state)) {
      if (!Number.isFinite(t3.distance) || t3.distance < 0)
        throw new Error("Distinct-owner blocker hops require finite distances >= 0");
      const s3 = a4.distance + t3.distance;
      if (!Number.isFinite(s3))
        throw new Error("Distinct-owner blocker path distance overflowed");
      const c3 = e51.getStateKey(t3.state), l3 = r3++, h2 = o3.get(c3) ?? [], d2 = t3.owners ?? [];
      let u2 = false;
      for (const e52 of h2)
        if (e52.distance <= s3 && rJ(e52.owners, a4.owners, d2)) {
          u2 = true;
          break;
        }
      if (u2)
        continue;
      let p3 = a4.owners;
      for (const e52 of d2)
        p3.has(e52) || (p3 === a4.owners && (p3 = new Set(a4.owners)), p3.add(e52));
      const m2 = e51.getRemainingDistance ? e51.getRemainingDistance(t3.state) : 0, g2 = s3 + m2;
      if (!Number.isFinite(m2) || m2 < 0 || !Number.isFinite(g2))
        throw new Error("Distinct-owner blocker estimates must be finite and >= 0");
      const f2 = { state: t3.state, stateKey: c3, owners: p3, priorityOwnerCount: Math.max(n2, p3.size), distance: s3, estimatedTotalDistance: g2, parent: a4, incomingHop: t3, queueOrder: l3, active: true }, _2 = [];
      for (const e52 of h2)
        sJ(f2, e52) ? e52.active = false : _2.push(e52);
      _2.push(f2), o3.set(f2.stateKey, _2), i3.push(f2);
    }
  }
};
var hJ = class extends tJ {
  constructor(e51, t2, n2) {
    super(e51, t2, n2), this.ADD_SEGMENT_DISTANCE_TO_G = true;
  }
  _setup() {
    super._setup(), this.state.candidateQueue = new ZZ(this.topology.regionCount, { hopCapacity: this.candidateHopCapacity, hopSlotStride: this.candidateHopSlotStride, firstRegionByPortId: this.candidateFirstRegionByPortId, secondRegionByPortId: this.candidateSecondRegionByPortId, incidentPortRegion: this.topology.incidentPortRegion });
  }
  onPathFound(e51) {
    const t2 = this.state.goalPortId;
    if (e51.portId === t2)
      return void super.onPathFound(e51);
    const n2 = this.computeG(e51, t2);
    if (!Number.isFinite(n2))
      return;
    const o3 = this.getHopId(t2, e51.nextRegionId);
    n2 >= this.getCandidateBestCost(o3) || (this.setCandidateBestCost(o3, n2), this.state.candidateQueue.queue({ hopId: o3, prevRegionId: e51.nextRegionId, nextRegionId: e51.nextRegionId, portId: t2, g: n2, h: 0, f: n2, prevCandidate: e51 }));
  }
};
var dJ = new Set;
var uJ = class extends hJ {
  partialRipRoutePlans = new Map;
  outsideInRouteSearch;
  oneSidedFallbackRouteId;
  partialRipWindowDistance;
  partialRipCount = 0;
  partiallyRippedRouteCount = 0;
  partiallyRippedSegmentCount = 0;
  retainedPartialRipSegmentCount = 0;
  outsideInRouteCount = 0;
  outsideInCompletedRouteCount = 0;
  outsideInFallbackRouteCount = 0;
  outsideInForwardExpansionCount = 0;
  outsideInReverseExpansionCount = 0;
  outsideInDistancePruneCount = 0;
  completedRoundSummaries = [];
  firstCompletedRoundSummary;
  partialRipQualityBaselineSummary;
  bestSolvedRoundSummary;
  partialRipTargetReached = false;
  useComplexityAwareSelection = false;
  constructor(e51, t2, n2) {
    super(e51, t2, n2), n2?.PARTIAL_RIP_ENABLED === undefined && (this.PARTIAL_RIP_ENABLED = true), n2?.OUTSIDE_IN_ROUTING === undefined && (this.OUTSIDE_IN_ROUTING = true), this.PARTIAL_RIP_ENABLED && n2?.PARTIAL_RIP_MAX_ATTEMPTS === undefined && (this.PARTIAL_RIP_MAX_ATTEMPTS = 10), (t2.routeCount < Math.max(0, this.PARTIAL_RIP_MIN_ROUTE_COUNT) || t2.routeCount > Math.max(0, this.PARTIAL_RIP_MAX_ROUTE_COUNT)) && (this.PARTIAL_RIP_ENABLED = false, this.OUTSIDE_IN_ROUTING = false), this.useComplexityAwareSelection = t2.routeCount >= Math.max(0, this.PARTIAL_RIP_COMPLEXITY_SELECTION_MIN_ROUTE_COUNT);
  }
  getRouteStartPortId(e51) {
    return this.PARTIAL_RIP_ENABLED ? this.partialRipRoutePlans.get(e51)?.activeStartPortId ?? super.getRouteStartPortId(e51) : super.getRouteStartPortId(e51);
  }
  getRouteEndPortId(e51) {
    return this.PARTIAL_RIP_ENABLED ? this.partialRipRoutePlans.get(e51)?.activeEndPortId ?? super.getRouteEndPortId(e51) : super.getRouteEndPortId(e51);
  }
  getStartingNextRegionId(e51, t2) {
    if (!this.PARTIAL_RIP_ENABLED)
      return super.getStartingNextRegionId(e51, t2);
    const n2 = this.partialRipRoutePlans.get(e51);
    return n2 && n2.activeStartPortId === t2 ? n2.forcedStartRegionId : super.getStartingNextRegionId(e51, t2);
  }
  getEndingNextRegionId(e51, t2) {
    const n2 = this.partialRipRoutePlans.get(e51);
    return n2 && n2.activeEndPortId === t2 ? n2.forcedEndRegionId : super.getStartingNextRegionId(e51, t2);
  }
  computeH(e51) {
    if (!this.PARTIAL_RIP_ENABLED)
      return super.computeH(e51);
    const t2 = this.state.currentRouteId;
    if (t2 === undefined || !this.partialRipRoutePlans.has(t2))
      return super.computeH(e51);
    const n2 = this.getRouteEndPortId(t2), o3 = this.topology.portX[e51] - this.topology.portX[n2], i3 = this.topology.portY[e51] - this.topology.portY[n2];
    return Math.sqrt(o3 * o3 + i3 * i3) * this.DISTANCE_TO_COST;
  }
  onPathFound(e51) {
    if (!this.PARTIAL_RIP_ENABLED && !this.OUTSIDE_IN_ROUTING)
      return void super.onPathFound(e51);
    const t2 = this.state.currentRouteId, n2 = t2 !== undefined && this.outsideInRouteSearch?.routeId === t2;
    super.onPathFound(e51), t2 !== undefined && this.state.currentRouteId === undefined && (this.partialRipRoutePlans.delete(t2), n2 && (this.outsideInCompletedRouteCount += 1), this.oneSidedFallbackRouteId === t2 && (this.oneSidedFallbackRouteId = undefined)), this.outsideInRouteSearch = undefined, this.publishOutsideInStats();
  }
  resetRoutingStateForRerip() {
    this.PARTIAL_RIP_ENABLED || this.OUTSIDE_IN_ROUTING ? (this.partialRipRoutePlans.clear(), this.outsideInRouteSearch = undefined, this.oneSidedFallbackRouteId = undefined, super.resetRoutingStateForRerip()) : super.resetRoutingStateForRerip();
  }
  clearPartialRipPlans(e51) {
    for (const t2 of e51)
      this.partialRipRoutePlans.delete(t2);
  }
  getRouteIdsPreferredForPreservation() {
    return dJ;
  }
  getCommittedRouteSegments(e51) {
    const t2 = [];
    for (let n3 = 0;n3 < this.state.regionSegments.length; n3++)
      for (const [o4, i4, r4] of this.state.regionSegments[n3] ?? [])
        o4 === e51 && t2.push({ segmentIndex: t2.length, regionId: n3, fromPortId: i4, toPortId: r4 });
    if (t2.length === 0)
      return;
    const n2 = new Map;
    for (const e52 of t2)
      for (const t3 of [e52.fromPortId, e52.toPortId]) {
        const o4 = n2.get(t3) ?? [];
        o4.push(e52.segmentIndex), n2.set(t3, o4);
      }
    const o3 = this.problem.routeEndPort[e51], i3 = [], r3 = new Set, s2 = new Set([this.problem.routeStartPort[e51]]), a3 = (e52) => {
      if (e52 === o3)
        return true;
      for (const o4 of n2.get(e52) ?? []) {
        if (r3.has(o4))
          continue;
        const n3 = t2[o4], c3 = n3.fromPortId === e52 ? n3.toPortId : n3.fromPortId;
        if (!s2.has(c3)) {
          if (r3.add(o4), s2.add(c3), i3.push({ regionId: n3.regionId, fromPortId: e52, toPortId: c3 }), a3(c3))
            return true;
          i3.pop(), s2.delete(c3), r3.delete(o4);
        }
      }
      return false;
    };
    return a3(this.problem.routeStartPort[e51]) && r3.size === t2.length ? i3 : undefined;
  }
  getSegmentDistance(e51) {
    const t2 = this.topology.portX[e51.fromPortId] - this.topology.portX[e51.toPortId], n2 = this.topology.portY[e51.fromPortId] - this.topology.portY[e51.toPortId];
    return Math.sqrt(t2 * t2 + n2 * n2);
  }
  getPartialRipWindow(e51, t2, n2) {
    let o3, i3 = Number.NEGATIVE_INFINITY;
    for (let r4 = 0;r4 < e51.length; r4++) {
      const s3 = e51[r4];
      if (!t2.has(s3.regionId))
        continue;
      const a4 = n2[s3.regionId] ?? 0;
      a4 > i3 && (i3 = a4, o3 = r4);
    }
    if (o3 === undefined)
      return;
    const r3 = Math.max(0, this.partialRipWindowDistance ?? this.PARTIAL_RIP_MAX_DISTANCE);
    let s2 = o3, a3 = o3, c3 = this.getSegmentDistance(e51[o3]) / 2, l3 = c3;
    for (;s2 > 0; ) {
      const t3 = this.getSegmentDistance(e51[s2 - 1]);
      if (c3 + t3 > r3)
        break;
      s2 -= 1, c3 += t3;
    }
    for (;a3 + 1 < e51.length; ) {
      const t3 = this.getSegmentDistance(e51[a3 + 1]);
      if (l3 + t3 > r3)
        break;
      a3 += 1, l3 += t3;
    }
    return { startIndex: s2, endIndex: a3 };
  }
  appendRetainedSegment(e51, t2, n2) {
    e51[n2.regionId].push([t2, n2.fromPortId, n2.toPortId]);
  }
  preparePartialRip(e51, t2) {
    if (!this.PARTIAL_RIP_ENABLED || e51.length === 0)
      return false;
    const n2 = new Set(e51);
    if (this.partialRipWindowDistance === undefined) {
      let n3 = 0;
      for (const o5 of e51)
        n3 = Math.max(n3, t2[o5] ?? 0);
      const o4 = Math.max(0, this.PARTIAL_RIP_MAX_DISTANCE), i4 = Math.max(o4, this.PARTIAL_RIP_QUALITY_MAX_DISTANCE ?? 2 * o4);
      this.partialRipWindowDistance = n3 <= 1.5 * this.RIP_THRESHOLD_END ? i4 : o4;
    }
    const o3 = new Set;
    for (const t3 of e51)
      for (const [e52] of this.state.regionSegments[t3] ?? [])
        o3.add(e52);
    if (o3.size === 0)
      return false;
    const i3 = this.getRouteIdsPreferredForPreservation(), r3 = [...o3].some((e52) => !i3.has(e52)), s2 = Array.from({ length: this.topology.regionCount }, () => []), a3 = new Map;
    let c3 = 0, l3 = 0;
    for (let e52 = 0;e52 < this.problem.routeCount; e52++) {
      const h2 = this.getCommittedRouteSegments(e52);
      if (!h2)
        return false;
      if (!o3.has(e52) || r3 && i3.has(e52)) {
        for (const t3 of h2)
          this.appendRetainedSegment(s2, e52, t3), l3 += 1;
        continue;
      }
      const d2 = this.getPartialRipWindow(h2, n2, t2);
      if (!d2)
        return false;
      for (let t3 = 0;t3 < h2.length; t3++) {
        const n3 = h2[t3];
        t3 >= d2.startIndex && t3 <= d2.endIndex ? c3 += 1 : (this.appendRetainedSegment(s2, e52, n3), l3 += 1);
      }
      const u2 = h2[d2.startIndex], p3 = h2[d2.endIndex];
      a3.set(e52, { routeId: e52, activeStartPortId: u2.fromPortId, activeEndPortId: p3.toPortId, forcedStartRegionId: u2.regionId, forcedEndRegionId: p3.regionId, rippedSegmentCount: d2.endIndex - d2.startIndex + 1, retainedSegmentCount: h2.length - (d2.endIndex - d2.startIndex + 1) });
    }
    return a3.size !== 0 && c3 !== 0 && (this.partialRipRoutePlans = a3, this.rebuildRetainedRoutingState(s2, [...a3.keys()]), this.partialRipCount += 1, this.partiallyRippedRouteCount += a3.size, this.partiallyRippedSegmentCount += c3, this.retainedPartialRipSegmentCount += l3, this.publishPartialRipStats(), true);
  }
  rebuildRetainedRoutingState(e51, t2) {
    this.state.portAssignment.fill(-1), this.state.regionSegments = Array.from({ length: this.topology.regionCount }, () => []), this.state.regionIntersectionCaches = Array.from({ length: this.topology.regionCount }, () => Zq()), this.state.currentRouteId = undefined, this.state.currentRouteNetId = undefined, this.state.unroutedRoutes = t2, this.state.candidateQueue.clear(), this.resetCandidateBestCosts(), this.state.goalPortId = -1, this.outsideInRouteSearch = undefined, this.oneSidedFallbackRouteId = undefined;
    for (let t3 = 0;t3 < e51.length; t3++)
      for (const [n2, o3, i3] of e51[t3] ?? []) {
        const e52 = this.problem.routeNet[n2];
        this.state.currentRouteNetId = e52;
        for (const t4 of [o3, i3]) {
          const n3 = this.state.portAssignment[t4];
          if (n3 !== -1 && n3 !== e52)
            throw new Error(`OutsideInPartialRipTinyHyperGraphSolver: retained port ${t4} belongs to multiple nets`);
          this.state.portAssignment[t4] = e52;
        }
        this.state.regionSegments[t3].push([n2, o3, i3]), this.appendSegmentToRegionCache(t3, o3, i3);
      }
    this.state.currentRouteNetId = undefined;
  }
  publishPartialRipStats() {
    this.stats = { ...this.stats, partialRipCount: this.partialRipCount, partiallyRippedRouteCount: this.partiallyRippedRouteCount, partiallyRippedSegmentCount: this.partiallyRippedSegmentCount, retainedPartialRipSegmentCount: this.retainedPartialRipSegmentCount, partialRipMaxDistance: this.partialRipWindowDistance ?? this.PARTIAL_RIP_MAX_DISTANCE, partialRipBaseMaxDistance: this.PARTIAL_RIP_MAX_DISTANCE, partialRipQualityMaxDistance: this.PARTIAL_RIP_QUALITY_MAX_DISTANCE ?? 2 * this.PARTIAL_RIP_MAX_DISTANCE, partialRipMaxAttempts: this.PARTIAL_RIP_MAX_ATTEMPTS };
  }
  publishOutsideInStats() {
    this.stats = { ...this.stats, outsideInRouteCount: this.outsideInRouteCount, outsideInCompletedRouteCount: this.outsideInCompletedRouteCount, outsideInFallbackRouteCount: this.outsideInFallbackRouteCount, outsideInForwardExpansionCount: this.outsideInForwardExpansionCount, outsideInReverseExpansionCount: this.outsideInReverseExpansionCount, outsideInDistancePruneCount: this.outsideInDistancePruneCount, outsideInMaxDistance: this.OUTSIDE_IN_MAX_DISTANCE };
  }
  createOutsideInFrontier(e51, t2, n2) {
    const o3 = new UZ([], (e52, t3) => e52.f === t3.f ? e52.g - t3.g : e52.f - t3.f), i3 = this.topology.portX[e51] - this.topology.portX[n2], r3 = this.topology.portY[e51] - this.topology.portY[n2], s2 = Math.sqrt(i3 * i3 + r3 * r3) * this.DISTANCE_TO_COST, a3 = { portId: e51, nextRegionId: t2, f: s2, g: 0, h: s2, travelDistance: 0 };
    return o3.queue(a3), { queue: o3, bestCostByHopId: new Map([[this.getHopId(e51, t2), 0]]), settledByPortId: new Map, settledByRegionId: new Map, targetPortId: n2 };
  }
  startOutsideInRouteSearch(e51) {
    const t2 = this.getRouteStartPortId(e51), n2 = this.getRouteEndPortId(e51), o3 = this.getStartingNextRegionId(e51, t2), i3 = this.getEndingNextRegionId(e51, n2);
    return o3 !== undefined && i3 !== undefined && (this.state.goalPortId = n2, this.state.candidateQueue.clear(), this.resetCandidateBestCosts(), this.outsideInRouteSearch = { routeId: e51, forward: this.createOutsideInFrontier(t2, o3, n2), reverse: this.createOutsideInFrontier(n2, i3, t2), expandForwardNext: true, distanceLimitHit: false, bestJoinedCost: Number.POSITIVE_INFINITY }, this.outsideInRouteCount += 1, this.publishOutsideInStats(), true);
  }
  dequeueFreshCandidate(e51) {
    for (;e51.queue.length > 0; ) {
      const t2 = e51.queue.dequeue(), n2 = this.getHopId(t2.portId, t2.nextRegionId);
      if (t2.g <= (e51.bestCostByHopId.get(n2) ?? 1 / 0))
        return t2;
    }
  }
  recordSettledCandidate(e51, t2) {
    const n2 = e51.settledByPortId.get(t2.portId);
    (!n2 || t2.g < n2.g) && e51.settledByPortId.set(t2.portId, t2);
    const o3 = e51.settledByRegionId.get(t2.nextRegionId) ?? [];
    o3.push(t2), o3.sort((e52, t3) => e52.g - t3.g), o3.length > 16 && (o3.length = 16), e51.settledByRegionId.set(t2.nextRegionId, o3);
  }
  getCandidatePath(e51) {
    const t2 = [];
    let n2 = e51;
    for (;n2; )
      t2.push(n2), n2 = n2.prevCandidate;
    return t2.reverse(), t2;
  }
  buildJoinedCandidate(e51, t2) {
    const n2 = this.getCandidatePath(e51), o3 = this.getCandidatePath(t2), i3 = n2.map(({ portId: e52 }) => e52), r3 = n2.slice(0, -1).map(({ nextRegionId: e52 }) => e52);
    if (e51.portId !== t2.portId) {
      if (e51.nextRegionId !== t2.nextRegionId)
        return;
      const n3 = this.topology.portX[e51.portId] - this.topology.portX[t2.portId], o4 = this.topology.portY[e51.portId] - this.topology.portY[t2.portId], s3 = Math.sqrt(n3 * n3 + o4 * o4);
      if (e51.travelDistance + t2.travelDistance + s3 > 2 * this.OUTSIDE_IN_MAX_DISTANCE)
        return;
      const a4 = this.computeG(e51, t2.portId);
      if (!Number.isFinite(a4))
        return;
      r3.push(e51.nextRegionId), i3.push(t2.portId);
    }
    for (let e52 = o3.length - 2;e52 >= 0; e52--) {
      const t3 = o3[e52];
      r3.push(t3.nextRegionId), i3.push(t3.portId);
    }
    if (new Set(i3).size !== i3.length || r3.length + 1 !== i3.length)
      return;
    let s2 = { portId: i3[0], nextRegionId: r3[0], f: 0, g: 0, h: 0 };
    for (let e52 = 1;e52 < i3.length; e52++)
      s2 = { portId: i3[e52], prevRegionId: r3[e52 - 1], nextRegionId: r3[e52] ?? r3[e52 - 1], prevCandidate: s2, f: 0, g: 0, h: 0 };
    const a3 = e51.portId === t2.portId ? 0 : this.computeG(e51, t2.portId) - e51.g;
    return { candidate: s2, cost: e51.g + t2.g + a3 };
  }
  considerOutsideInJoins(e51, t2) {
    const n2 = this.outsideInRouteSearch, o3 = t2 ? n2.reverse : n2.forward, i3 = (e52) => {
      !e52 || e52.cost >= n2.bestJoinedCost || (n2.bestJoinedCandidate = e52.candidate, n2.bestJoinedCost = e52.cost, n2.remainingPostMeetingExpansions = 24);
    }, r3 = o3.settledByPortId.get(e51.portId);
    r3 && i3(t2 ? this.buildJoinedCandidate(e51, r3) : this.buildJoinedCandidate(r3, e51));
    for (const n3 of o3.settledByRegionId.get(e51.nextRegionId) ?? [])
      i3(t2 ? this.buildJoinedCandidate(e51, n3) : this.buildJoinedCandidate(n3, e51));
  }
  commitBestOutsideInJoin() {
    const e51 = this.outsideInRouteSearch?.bestJoinedCandidate;
    return !!e51 && (this.onPathFound(e51), true);
  }
  expandOutsideInFrontier(e51) {
    const t2 = this.outsideInRouteSearch, n2 = e51 ? t2.forward : t2.reverse, o3 = this.dequeueFreshCandidate(n2);
    if (!o3)
      return false;
    if (e51 ? this.outsideInForwardExpansionCount += 1 : this.outsideInReverseExpansionCount += 1, this.isRegionReservedForDifferentNet(o3.nextRegionId))
      return true;
    this.recordSettledCandidate(n2, o3), this.considerOutsideInJoins(o3, e51);
    for (const e52 of this.topology.regionIncidentPorts[o3.nextRegionId] ?? []) {
      if (e52 === o3.portId)
        continue;
      if (this.isPortReservedForDifferentNet(e52))
        continue;
      const i3 = this.state.portAssignment[e52];
      if (i3 !== -1 && i3 !== this.state.currentRouteNetId)
        continue;
      if (e52 !== n2.targetPortId && this.problem.portSectionMask[e52] === 0)
        continue;
      const r3 = this.topology.portX[o3.portId] - this.topology.portX[e52], s2 = this.topology.portY[o3.portId] - this.topology.portY[e52], a3 = Math.sqrt(r3 * r3 + s2 * s2), c3 = o3.travelDistance + a3;
      if (c3 > this.OUTSIDE_IN_MAX_DISTANCE) {
        t2.distanceLimitHit = true, this.outsideInDistancePruneCount += 1;
        continue;
      }
      const l3 = this.topology.incidentPortRegion[e52]?.[0] === o3.nextRegionId ? this.topology.incidentPortRegion[e52]?.[1] : this.topology.incidentPortRegion[e52]?.[0];
      if (l3 === undefined || this.isRegionReservedForDifferentNet(l3))
        continue;
      const h2 = this.getHopId(e52, l3), d2 = n2.bestCostByHopId.get(h2) ?? 1 / 0;
      if (o3.g >= d2)
        continue;
      const u2 = this.computeG(o3, e52, d2, a3);
      if (!Number.isFinite(u2) || u2 >= d2)
        continue;
      n2.bestCostByHopId.set(h2, u2);
      const p3 = this.topology.portX[e52] - this.topology.portX[n2.targetPortId], m2 = this.topology.portY[e52] - this.topology.portY[n2.targetPortId], g2 = Math.sqrt(p3 * p3 + m2 * m2) * this.DISTANCE_TO_COST;
      n2.queue.queue({ portId: e52, prevRegionId: o3.nextRegionId, nextRegionId: l3, prevCandidate: o3, f: u2 + g2, g: u2, h: g2, travelDistance: c3 });
    }
    return true;
  }
  fallBackToOneSidedRouteSearch() {
    const e51 = this.state.currentRouteId;
    e51 !== undefined && (this.outsideInRouteSearch = undefined, this.outsideInFallbackRouteCount += 1, this.oneSidedFallbackRouteId = e51, this.state.currentRouteId = undefined, this.state.currentRouteNetId = undefined, this.state.goalPortId = -1, this.state.candidateQueue.clear(), this.resetCandidateBestCosts(), this.state.unroutedRoutes.unshift(e51), this.publishOutsideInStats());
  }
  _step() {
    if (!this.OUTSIDE_IN_ROUTING)
      return void super._step();
    const e51 = this.state.currentRouteId ?? this.state.unroutedRoutes[0];
    if (e51 !== undefined && !this.partialRipRoutePlans.has(e51))
      return void super._step();
    if (this.oneSidedFallbackRouteId !== undefined)
      return void super._step();
    if (this.state.currentRouteId === undefined) {
      if (this.state.unroutedRoutes.length === 0)
        return void this.onAllRoutesRouted();
      const e52 = this.state.unroutedRoutes.shift();
      if (this.state.currentRouteId = e52, this.state.currentRouteNetId = this.problem.routeNet[e52], this.routeAttemptCountByRouteId[e52] += 1, !this.startOutsideInRouteSearch(e52))
        return this.failed = true, void (this.error = `Route ${e52} has an endpoint without an incident region`);
    }
    const t2 = this.outsideInRouteSearch;
    if (!t2)
      return;
    let n2 = this.expandOutsideInFrontier(t2.expandForwardNext);
    if (this.state.currentRouteId !== undefined && (n2 || (n2 = this.expandOutsideInFrontier(!t2.expandForwardNext), this.state.currentRouteId !== undefined)))
      if (t2.expandForwardNext = !t2.expandForwardNext, t2.bestJoinedCandidate && (t2.remainingPostMeetingExpansions = (t2.remainingPostMeetingExpansions ?? 1) - 1, (t2.remainingPostMeetingExpansions ?? 0) <= 0))
        this.commitBestOutsideInJoin();
      else {
        if (!n2 && t2.forward.queue.length === 0 && t2.reverse.queue.length === 0) {
          if (this.commitBestOutsideInJoin())
            return;
          this.outsideInRouteSearch = undefined, t2.distanceLimitHit ? this.fallBackToOneSidedRouteSearch() : this.onOutOfCandidates();
        }
        this.publishOutsideInStats();
      }
  }
  shouldReplaceBestSolvedState(e51) {
    const t2 = this.bestSolvedRoundSummary;
    if (!t2)
      return true;
    if (!this.useComplexityAwareSelection)
      return this.compareRegionCostSummaries(e51, t2) < 0;
    const n2 = this.partialRipQualityBaselineSummary;
    if (!n2)
      return this.compareRegionCostSummaries(e51, t2) < 0;
    const o3 = this.firstCompletedRoundSummary ?? n2, i3 = o3.maxRegionCost * (1 + Math.max(0, this.PARTIAL_RIP_MAX_REGION_COST_GROWTH_RATIO)), r3 = o3.totalRegionCost * (1 + Math.max(0, this.PARTIAL_RIP_MAX_TOTAL_COST_GROWTH_RATIO)), s2 = e51.maxRegionCost <= i3 && e51.totalRegionCost <= r3;
    return s2 !== (t2.maxRegionCost <= i3 && t2.totalRegionCost <= r3) ? s2 : s2 && e51.segmentCount !== t2.segmentCount ? e51.segmentCount < t2.segmentCount : this.compareRegionCostSummaries(e51, t2) < 0;
  }
  onAllRoutesRouted() {
    if (!this.PARTIAL_RIP_ENABLED)
      return void super.onAllRoutesRouted();
    const { state: e51, topology: t2 } = this, n2 = Math.min(this.RIP_THRESHOLD_RAMP_ATTEMPTS, this.PARTIAL_RIP_MAX_ATTEMPTS), o3 = Math.max(0, this.RIP_THRESHOLD_RAMP_ATTEMPTS), i3 = o3 <= 0 ? 1 : Math.min(1, e51.ripCount / o3), r3 = this.RIP_THRESHOLD_START + (this.RIP_THRESHOLD_END - this.RIP_THRESHOLD_START) * i3, s2 = new Float64Array(t2.regionCount), a3 = [];
    let c3 = 0, l3 = 0, h2 = 0, d2 = 0, u2 = 0;
    for (let n3 = 0;n3 < t2.regionCount; n3++) {
      const t3 = e51.regionIntersectionCaches[n3]?.existingRegionCost ?? 0;
      s2[n3] = t3, c3 = Math.max(c3, t3), l3 += t3;
      const o4 = e51.regionSegments[n3]?.length ?? 0;
      h2 += o4, d2 = Math.max(d2, o4), u2 += o4 * o4, t3 > r3 && a3.push(n3);
    }
    const p3 = { maxRegionCost: c3, totalRegionCost: l3 }, m2 = { ...p3, ripCount: e51.ripCount, segmentCount: h2, maxRegionSegmentCount: d2, squaredRegionSegmentCount: u2 };
    this.completedRoundSummaries.push(m2), this.firstCompletedRoundSummary ??= m2, this.partialRipQualityBaselineSummary === undefined && e51.ripCount >= Math.max(0, this.PARTIAL_RIP_WARMUP_FULL_RIP_ATTEMPTS) && (this.partialRipQualityBaselineSummary = m2);
    this.shouldReplaceBestSolvedState(m2) && (this.replaceBestSolvedState(p3), this.bestSolvedRoundSummary = m2);
    const g2 = this.firstCompletedRoundSummary, f2 = this.partialRipQualityBaselineSummary ?? g2, _2 = Math.max(0, this.PARTIAL_RIP_TARGET_MAX_COST_IMPROVEMENT_RATIO), y2 = Math.max(0, this.PARTIAL_RIP_MAX_TOTAL_COST_GROWTH_RATIO), b2 = f2.maxRegionCost * (1 - _2), x2 = f2.totalRegionCost * (1 + y2), v2 = this.useComplexityAwareSelection && e51.ripCount > f2.ripCount && _2 > 0 && c3 <= b2 && l3 <= x2 && h2 <= f2.segmentCount;
    if (v2 && (this.partialRipTargetReached = true), this.stats = { ...this.stats, currentRipThreshold: r3, hotRegionCount: a3.length, maxRegionCost: c3, totalRegionCost: l3, bestMaxRegionCost: this.bestSolvedStateSummary?.maxRegionCost, bestTotalRegionCost: this.bestSolvedStateSummary?.totalRegionCost, ripCount: e51.ripCount, completedRoundSummaries: this.completedRoundSummaries.map((e52) => ({ ...e52 })), firstMaxRegionCost: g2.maxRegionCost, firstTotalRegionCost: g2.totalRegionCost, firstSegmentCount: g2.segmentCount, firstMaxRegionSegmentCount: g2.maxRegionSegmentCount, firstSquaredRegionSegmentCount: g2.squaredRegionSegmentCount, partialRipQualityBaselineRipCount: f2.ripCount, partialRipQualityBaselineMaxRegionCost: f2.maxRegionCost, partialRipQualityBaselineTotalRegionCost: f2.totalRegionCost, partialRipQualityBaselineSegmentCount: f2.segmentCount, partialRipQualityBaselineMaxRegionSegmentCount: f2.maxRegionSegmentCount, partialRipQualityBaselineSquaredRegionSegmentCount: f2.squaredRegionSegmentCount, bestSolvedSegmentCount: this.bestSolvedRoundSummary?.segmentCount, bestSolvedMaxRegionSegmentCount: this.bestSolvedRoundSummary?.maxRegionSegmentCount, bestSolvedSquaredRegionSegmentCount: this.bestSolvedRoundSummary?.squaredRegionSegmentCount, partialRipTargetMaxRegionCost: b2, partialRipMaxTargetTotalRegionCost: x2, partialRipComplexityAwareSelection: this.useComplexityAwareSelection, partialRipComplexitySelectionMinRouteCount: this.PARTIAL_RIP_COMPLEXITY_SELECTION_MIN_ROUTE_COUNT, partialRipMaxRegionCostGrowthRatio: this.PARTIAL_RIP_MAX_REGION_COST_GROWTH_RATIO, partialRipTargetReached: this.partialRipTargetReached }, this.publishPartialRipStats(), a3.length === 0 || v2 || e51.ripCount >= n2)
      return this.restoreBestSolvedState(), void (this.solved = true);
    for (let n3 = 0;n3 < t2.regionCount; n3++)
      e51.regionCongestionCost[n3] += s2[n3] * this.RIP_CONGESTION_REGION_COST_FACTOR;
    const I2 = e51.ripCount < Math.max(0, this.PARTIAL_RIP_WARMUP_FULL_RIP_ATTEMPTS);
    e51.ripCount += 1;
    const S2 = !I2 && this.preparePartialRip(a3, s2);
    S2 || this.resetRoutingStateForRerip();
    const C = I2 ? "warmup_full" : S2 ? "partial" : "full_fallback";
    this.stats = { ...this.stats, ripCount: e51.ripCount, maxRegionCostBeforeRip: c3, reripRegionCount: a3.length, reripMode: C, partialRipWarmupFullRipAttempts: this.PARTIAL_RIP_WARMUP_FULL_RIP_ATTEMPTS }, this.logRipEvent("hot_regions", c3, { hotRegionCount: a3.length, currentRipThreshold: r3, reripMode: C, partialRouteCount: S2 ? this.partialRipRoutePlans.size : 0 });
  }
};
function pJ(e51, t2) {
  if (t2.totalHopDistance += e51.distance, e51.distance < 0 || !Number.isFinite(t2.totalHopDistance))
    return false;
  const n2 = t2.search.solver.getHopId(e51.state.portId, e51.state.nextRegionId);
  return t2.ownerFreePhase ? (e51.owners.length > 0 ? t2.ownerFreeByHopId.has(n2) || (t2.ownerFreeByHopId.set(n2, false), t2.ownedQueue.push(e51.state)) : t2.ownerFreeByHopId.get(n2) !== true && (t2.ownerFreeByHopId.set(n2, true), t2.ownerFreeQueue.push(e51.state)), true) : (t2.ownerFreeByHopId.has(n2) || (t2.ownerFreeByHopId.set(n2, false), t2.ownedQueue.push(e51.state)), true);
}
function mJ(e51, t2) {
  const { solver: n2 } = t2.search, o3 = n2.isKnownSingleLayerRegion(e51.nextRegionId);
  if (!o3) {
    const n3 = t2.expansionsByRegion.get(e51.nextRegionId);
    if (n3 === 2)
      return true;
    t2.expansionsByRegion.set(e51.nextRegionId, n3 === undefined ? 1 : 2);
  }
  if (n2.isRegionReservedForDifferentNet(e51.nextRegionId))
    return true;
  if (o3) {
    for (const n3 of t2.search.getHops(e51))
      if (!pJ(n3, t2))
        return false;
    return true;
  }
  const i3 = t2.search.getHopTemplates(e51), r3 = i3[0];
  if (!r3)
    return true;
  const s2 = { ...r3 };
  for (const o4 of i3)
    if (o4.state.portId !== e51.portId && (s2.state = o4.state, s2.owners = o4.owners, s2.data = o4.data, s2.distance = Math.hypot(n2.topology.portX[e51.portId] - n2.topology.portX[o4.state.portId], n2.topology.portY[e51.portId] - n2.topology.portY[o4.state.portId]), !pJ(s2, t2)))
      return false;
  return true;
}
var gJ = class extends uJ {
  costAwareFinalReripBudget = 8;
  failedOwnerPairCounts = new Map;
  selectiveReripStats = { selectiveRipCount: 0, selectivelyRippedRouteCount: 0, globalReripCount: 0, alternateBlockerSearchCount: 0, alternateOwnerCount: 0, failedOwnerPairCount: 0, maxFailedOwnerPairCount: 0, failedOwnerPairs: [], lastDirectOwnerRouteIds: [], lastRepeatedOwnerRouteIds: [], lastAlternateOwnerRouteIds: [], lastRippedRouteIds: [], lastRelaxedSearchExpandedLabelCount: 0, lastAlternateSearchExpandedLabelCount: 0 };
  selectiveReripCongestionUpdateCount = 0;
  constructor(e51, t2, n2) {
    super(e51, t2, n2);
  }
  getSelectiveReripStats() {
    return { ...this.selectiveReripStats, failedOwnerPairs: this.selectiveReripStats.failedOwnerPairs.map((e51) => ({ ...e51 })), lastDirectOwnerRouteIds: [...this.selectiveReripStats.lastDirectOwnerRouteIds], lastRepeatedOwnerRouteIds: [...this.selectiveReripStats.lastRepeatedOwnerRouteIds], lastAlternateOwnerRouteIds: [...this.selectiveReripStats.lastAlternateOwnerRouteIds], lastRippedRouteIds: [...this.selectiveReripStats.lastRippedRouteIds] };
  }
  createGreedyFinalRouteSolver(e51, t2) {
    if (t2 >= 0)
      return super.createGreedyFinalRouteSolver(e51, t2);
    const n2 = new fJ(this.topology, this.problem, { ...e51, MAX_ITERATIONS: Math.max(e51.MAX_ITERATIONS ?? 50000, 2 * this.MAX_ITERATIONS) });
    return n2.remainingReripBudget = this.costAwareFinalReripBudget - this.state.ripCount, n2;
  }
  onOutOfCandidates() {
    const e51 = this.state.currentRouteId;
    if (e51 === undefined)
      throw new Error("SelectiveReripTinyHyperGraphSolver: candidate search exhausted without a current route");
    const t2 = this.findRelaxedBlockerPathPreferringPreservedRoutes();
    if (!t2.found || t2.owners.size === 0)
      return this.selectiveReripStats.globalReripCount += 1, this.selectiveReripStats.globalReripReason = t2.found ? "no_blocker_path" : t2.reason, this.selectiveReripStats.lastFailedRouteId = e51, this.selectiveReripStats.lastDirectOwnerRouteIds = [], this.selectiveReripStats.lastRepeatedOwnerRouteIds = [], this.selectiveReripStats.lastAlternateOwnerRouteIds = [], this.selectiveReripStats.lastRippedRouteIds = [], this.selectiveReripStats.lastRelaxedSearchExpandedLabelCount = t2.expandedLabelCount, this.selectiveReripStats.lastAlternateSearchExpandedLabelCount = 0, super.onOutOfCandidates(), void this.publishSelectiveReripStats();
    const n2 = [...t2.owners], o3 = [];
    for (const t3 of n2) {
      this.incrementFailedOwnerPair(e51, t3) >= 2 && o3.push(t3);
    }
    if (n2.some((t3) => this.hasFailedOwnerPath(t3, e51)))
      return this.selectiveReripStats.globalReripCount += 1, this.selectiveReripStats.globalReripReason = "failed_owner_cycle", this.selectiveReripStats.lastFailedRouteId = e51, this.selectiveReripStats.lastDirectOwnerRouteIds = n2, this.selectiveReripStats.lastRepeatedOwnerRouteIds = o3, this.selectiveReripStats.lastAlternateOwnerRouteIds = [], this.selectiveReripStats.lastRippedRouteIds = [], this.selectiveReripStats.lastRelaxedSearchExpandedLabelCount = t2.expandedLabelCount, this.selectiveReripStats.lastAlternateSearchExpandedLabelCount = 0, this.failedOwnerPairCounts.clear(), super.onOutOfCandidates(), void this.publishSelectiveReripStats();
    let i3;
    if (o3.length > 0 && (this.selectiveReripStats.alternateBlockerSearchCount += 1, i3 = this.findRelaxedBlockerPathPreferringPreservedRoutes(new Set(o3)), !i3.found))
      return this.selectiveReripStats.globalReripCount += 1, this.selectiveReripStats.globalReripReason = i3.reason, this.selectiveReripStats.lastFailedRouteId = e51, this.selectiveReripStats.lastDirectOwnerRouteIds = n2, this.selectiveReripStats.lastRepeatedOwnerRouteIds = o3, this.selectiveReripStats.lastAlternateOwnerRouteIds = [], this.selectiveReripStats.lastRippedRouteIds = [], this.selectiveReripStats.lastRelaxedSearchExpandedLabelCount = t2.expandedLabelCount, this.selectiveReripStats.lastAlternateSearchExpandedLabelCount = i3.expandedLabelCount, super.onOutOfCandidates(), void this.publishSelectiveReripStats();
    const r3 = i3?.found ? [...i3.owners] : undefined, s2 = function(e52) {
      const t3 = new Set(e52.alternateOwnerRouteIds ?? e52.directOwnerRouteIds);
      if (t3.delete(e52.failedRouteId), t3.size === 0)
        throw new Error(`SelectiveReripTinyHyperGraphSolver: route ${e52.failedRouteId} has blocker resources but no distinct committed owner can be reripped`);
      return t3;
    }({ failedRouteId: e51, directOwnerRouteIds: n2, alternateOwnerRouteIds: r3 });
    this.clearPartialRipPlans(s2);
    const a3 = (r3 ?? []).filter((e52) => !t2.owners.has(e52));
    this.selectiveReripCongestionUpdateCount < 1 && (this.addCongestionCostForSelectiveRerip(), this.selectiveReripCongestionUpdateCount += 1), this.rebuildCommittedState(s2), this.state.ripCount += 1, this.state.currentRouteId = undefined, this.state.currentRouteNetId = undefined, this.state.unroutedRoutes = function(e52) {
      const t3 = e52.pendingRouteIds.filter((t4) => t4 !== e52.failedRouteId && !e52.rippedRouteIds.has(t4)), n3 = [...e52.rippedRouteIds].filter((t4) => t4 !== e52.failedRouteId);
      return [e52.failedRouteId, ...t3, ...n3];
    }({ failedRouteId: e51, pendingRouteIds: this.state.unroutedRoutes, rippedRouteIds: s2 }), this.state.candidateQueue.clear(), this.resetCandidateBestCosts(), this.state.goalPortId = -1, this.selectiveReripStats.selectiveRipCount += 1, this.selectiveReripStats.selectivelyRippedRouteCount += s2.size, this.selectiveReripStats.alternateOwnerCount += a3.length, this.selectiveReripStats.lastFailedRouteId = e51, this.selectiveReripStats.lastDirectOwnerRouteIds = n2, this.selectiveReripStats.lastRepeatedOwnerRouteIds = o3, this.selectiveReripStats.lastAlternateOwnerRouteIds = a3, this.selectiveReripStats.lastRippedRouteIds = [...s2], this.selectiveReripStats.lastRelaxedSearchExpandedLabelCount = t2.expandedLabelCount, this.selectiveReripStats.lastAlternateSearchExpandedLabelCount = i3?.expandedLabelCount ?? 0, this.publishSelectiveReripStats();
  }
  addCongestionCostForSelectiveRerip() {
    for (let e51 = 0;e51 < this.topology.regionCount; e51++) {
      const t2 = this.state.regionIntersectionCaches[e51]?.existingRegionCost ?? 0;
      this.state.regionCongestionCost[e51] += t2 * this.RIP_CONGESTION_REGION_COST_FACTOR;
    }
  }
  findRelaxedBlockerPath(e51 = new Set) {
    const t2 = this.state.currentRouteId, n2 = this.state.currentRouteNetId;
    if (t2 === undefined || n2 === undefined)
      throw new Error("SelectiveReripTinyHyperGraphSolver: blocker search requires a current route and net");
    const o3 = this.getRouteStartPortId(t2), i3 = this.getRouteEndPortId(t2), r3 = this.getStartingNextRegionId(t2, o3);
    if (r3 === undefined)
      throw new Error(`SelectiveReripTinyHyperGraphSolver: route ${this.describeRoute(t2)} has no starting region for blocker search`);
    const s2 = this.getPortOwners(), a3 = this.hasBoundedReachabilityGeometry({ startPortId: o3, goalPortId: i3 }), c3 = new Map, l3 = new Map, h2 = new Map, d2 = new Map, u2 = this.topology.portX[i3], p3 = this.topology.portY[i3], m2 = { goalPortId: i3, routeNetId: n2, portOwners: s2, portResources: c3, hopTemplatesByRegion: l3, forbiddenOwnerRouteIds: e51 }, g2 = this.getRelaxedSearchExpansionLimit(), f2 = { start: { portId: o3, nextRegionId: r3 }, getStateKey: ({ portId: e52, nextRegionId: t3 }) => this.getHopId(e52, t3), isGoal: ({ portId: e52 }) => e52 === i3, getHops: (e52) => {
      const t3 = this.getHopId(e52.portId, e52.nextRegionId), n3 = h2.get(t3);
      if (n3)
        return n3;
      const o4 = this.getRelaxedSearchHops({ state: e52 }, m2);
      return h2.set(t3, o4), o4;
    }, maxExpandedLabels: g2, getRemainingDistance: a3 ? ({ portId: e52 }) => {
      const t3 = d2.get(e52);
      if (t3 !== undefined)
        return t3;
      const n3 = this.topology.portX[e52], o4 = this.topology.portY[e52], i4 = 256 * Number.EPSILON * Math.max(1, Math.abs(n3), Math.abs(o4), Math.abs(u2), Math.abs(p3)), r4 = Math.max(0, Math.hypot(n3 - u2, o4 - p3) - i4);
      return d2.set(e52, r4), r4;
    } : undefined };
    if (!a3)
      return lJ({ ...f2, checkReachability: true });
    const _2 = function(e52, t3) {
      if (e52.maxExpandedStates !== 1 / 0 && (!Number.isInteger(e52.maxExpandedStates) || e52.maxExpandedStates < 0))
        throw new Error("maxExpandedLabels must be a non-negative integer");
      const n3 = { search: t3, ownerFreeQueue: [e52.start], ownedQueue: [], ownerFreeByHopId: new Map([[t3.solver.getHopId(e52.start.portId, e52.start.nextRegionId), true]]), expansionsByRegion: new Map, totalHopDistance: 0, ownerFreePhase: true };
      let o4 = 0;
      for (let i4 = 0;i4 < n3.ownerFreeQueue.length; i4++) {
        const r4 = n3.ownerFreeQueue[i4];
        if (r4.portId === t3.goalPortId)
          return { kind: "reachable", minimumOwnerCount: 0 };
        if (o4 >= e52.maxExpandedStates)
          return { kind: "incomplete", minimumOwnerCount: 0 };
        if (o4++, !mJ(r4, n3))
          return { kind: "incomplete", minimumOwnerCount: 0 };
      }
      n3.ownerFreePhase = false;
      for (let i4 = 0;i4 < n3.ownedQueue.length; i4++) {
        const r4 = n3.ownedQueue[i4], s3 = t3.solver.getHopId(r4.portId, r4.nextRegionId);
        if (n3.ownerFreeByHopId.get(s3) !== true) {
          if (r4.portId === t3.goalPortId)
            return { kind: "reachable", minimumOwnerCount: 1 };
          if (o4 >= e52.maxExpandedStates)
            return { kind: "incomplete", minimumOwnerCount: 1 };
          if (o4++, !mJ(r4, n3))
            return { kind: "incomplete", minimumOwnerCount: 1 };
        }
      }
      return { kind: "disconnected", expandedStateCount: o4 };
    }({ start: f2.start, maxExpandedStates: g2 }, { solver: this, goalPortId: i3, getHops: (e52) => this.getRelaxedSearchHops({ state: e52 }, m2), getHopTemplates: (e52) => this.getRelaxedSearchHopTemplates(e52, m2) });
    return _2.kind === "disconnected" ? { found: false, reason: "no_path", expandedLabelCount: _2.expandedStateCount } : lJ({ ...f2, minimumOwnerCount: _2.minimumOwnerCount });
  }
  findRelaxedBlockerPathPreferringPreservedRoutes(e51 = new Set) {
    const t2 = this.getRouteIdsPreferredForPreservation();
    if (t2.size === 0)
      return this.findRelaxedBlockerPath(e51);
    const n2 = new Set(e51);
    for (const e52 of t2)
      n2.add(e52);
    const o3 = this.findRelaxedBlockerPath(n2);
    return o3.found && o3.owners.size > 0 ? o3 : this.findRelaxedBlockerPath(e51);
  }
  getRelaxedSearchExpansionLimit() {
    let e51 = 0;
    for (const t3 of this.topology.incidentPortRegion)
      e51 += t3.length;
    const t2 = Math.max(4, Math.ceil(Math.log2(this.problem.routeCount + 1)));
    return Math.max(4096, e51 * t2 * 4);
  }
  hasBoundedReachabilityGeometry({ startPortId: e51, goalPortId: t2 }) {
    const { portCount: n2, portX: o3, portY: i3, regionIncidentPorts: r3 } = this.topology;
    if (!Number.isInteger(n2) || n2 < 0 || o3.length !== n2 || i3.length !== n2 || !Number.isInteger(e51) || e51 < 0 || e51 >= n2 || !Number.isInteger(t2) || t2 < 0 || t2 >= n2)
      return false;
    for (let e52 = 0;e52 < n2; e52++)
      if (!(Math.abs(o3[e52]) <= Number.MAX_SAFE_INTEGER && Math.abs(i3[e52]) <= Number.MAX_SAFE_INTEGER))
        return false;
    for (const e52 of r3) {
      if (!e52)
        return false;
      for (const t3 of e52)
        if (!Number.isInteger(t3) || t3 < 0 || t3 >= n2)
          return false;
    }
    return true;
  }
  getRelaxedSearchHopTemplates(e51, t2) {
    let n2 = t2.hopTemplatesByRegion.get(e51.nextRegionId);
    return n2 || (n2 = this.getRelaxedSearchHops({ state: e51, buildRegionTemplates: true }, t2), t2.hopTemplatesByRegion.set(e51.nextRegionId, n2)), n2;
  }
  getRelaxedSearchHops(e51, t2) {
    const { state: n2 } = e51, { goalPortId: o3, routeNetId: i3 } = t2;
    if (this.isRegionReservedForDifferentNet(n2.nextRegionId))
      return [];
    if (!e51.buildRegionTemplates && !this.isKnownSingleLayerRegion(n2.nextRegionId)) {
      const e52 = this.getRelaxedSearchHopTemplates(n2, t2), o4 = [];
      for (const t3 of e52)
        t3.state.portId !== n2.portId && o4.push({ state: t3.state, owners: t3.owners, data: t3.data, distance: Math.hypot(this.topology.portX[n2.portId] - this.topology.portX[t3.state.portId], this.topology.portY[n2.portId] - this.topology.portY[t3.state.portId]) });
      return o4;
    }
    const r3 = [];
    for (const s2 of this.topology.regionIncidentPorts[n2.nextRegionId] ?? []) {
      if (s2 === n2.portId && !e51.buildRegionTemplates)
        continue;
      if (this.isPortReservedForDifferentNet(s2))
        continue;
      if (s2 !== o3 && this.problem.portSectionMask[s2] === 0)
        continue;
      const a3 = this.getHopBlockerResources({ regionId: n2.nextRegionId, fromPortId: n2.portId, toPortId: s2, routeNetId: i3, portOwners: t2.portOwners, portResources: t2.portResources }), c3 = [];
      for (const e52 of a3)
        for (const t3 of e52.owners)
          c3.includes(t3) || c3.push(t3);
      if (c3.some((e52) => t2.forbiddenOwnerRouteIds.has(e52)))
        continue;
      let l3 = n2.nextRegionId;
      if (s2 !== o3) {
        const [e52, t3] = this.topology.incidentPortRegion[s2] ?? [];
        if (l3 = e52 === n2.nextRegionId ? t3 : e52, l3 === undefined || this.isRegionReservedForDifferentNet(l3))
          continue;
      }
      r3.push({ state: { portId: s2, nextRegionId: l3 }, distance: Math.hypot(this.topology.portX[n2.portId] - this.topology.portX[s2], this.topology.portY[n2.portId] - this.topology.portY[s2]), owners: c3, data: { resources: a3 } });
    }
    return r3;
  }
  getHopBlockerResources(e51) {
    const t2 = [], n2 = this.state.portAssignment[e51.toPortId];
    if (n2 !== -1 && n2 !== e51.routeNetId) {
      let o4 = e51.portResources.get(e51.toPortId);
      if (!o4) {
        const t3 = [...e51.portOwners.get(e51.toPortId) ?? new Set].filter((t4) => this.problem.routeNet[t4] !== e51.routeNetId);
        if (t3.length === 0)
          throw new Error(`SelectiveReripTinyHyperGraphSolver: port ${e51.toPortId} is assigned to foreign net ${n2} without a committed route owner`);
        o4 = { kind: "port", portId: e51.toPortId, owners: t3 }, e51.portResources.set(e51.toPortId, o4);
      }
      t2.push(o4);
    }
    const o3 = this.getHardBlockedCrossingOwners(e51.regionId, e51.fromPortId, e51.toPortId);
    return o3.length > 0 && t2.push({ kind: "same_layer_intersection", regionId: e51.regionId, fromPortId: e51.fromPortId, toPortId: e51.toPortId, owners: o3 }), t2;
  }
  getPortOwners() {
    const e51 = new Map;
    for (const t2 of this.state.regionSegments)
      for (const [n2, o3, i3] of t2)
        for (const t3 of [o3, i3]) {
          const o4 = e51.get(t3) ?? new Set;
          o4.add(n2), e51.set(t3, o4);
        }
    return e51;
  }
  getHardBlockedCrossingOwners(e51, t2, n2) {
    if (!this.isKnownSingleLayerRegion(e51))
      return [];
    const o3 = this.state.currentRouteNetId;
    if (o3 === undefined)
      throw new Error("SelectiveReripTinyHyperGraphSolver: crossing ownership requires a current route net");
    const i3 = new Set;
    for (const [r3, s2, a3] of this.state.regionSegments[e51] ?? [])
      this.problem.routeNet[r3] !== o3 && this.segmentsCrossOnSameLayer(e51, t2, n2, s2, a3) && i3.add(r3);
    return [...i3];
  }
  segmentsCrossOnSameLayer(e51, t2, n2, o3, i3) {
    const r3 = this.populateSegmentGeometryScratch(e51, t2, n2), s2 = r3.lesserAngle, a3 = r3.greaterAngle, c3 = r3.layerMask, l3 = this.populateSegmentGeometryScratch(e51, o3, i3);
    if ((c3 & l3.layerMask) === 0)
      return false;
    if (s2 === l3.lesserAngle || s2 === l3.greaterAngle || a3 === l3.lesserAngle || a3 === l3.greaterAngle)
      return false;
    return (s2 < l3.lesserAngle && l3.lesserAngle < a3) !== (s2 < l3.greaterAngle && l3.greaterAngle < a3);
  }
  rebuildCommittedState(e51) {
    const t2 = this.state.regionSegments;
    this.state.regionSegments = this.state.regionSegments.map((t3) => t3.filter(([t4]) => !e51.has(t4))), this.state.portAssignment.fill(-1), this.state.regionIntersectionCaches = Array.from({ length: this.topology.regionCount }, (e52, n2) => this.state.regionSegments[n2].length === t2[n2].length ? this.state.regionIntersectionCaches[n2] : Zq());
    for (let e52 = 0;e52 < this.state.regionSegments.length; e52++) {
      const n2 = this.state.regionSegments[e52].length !== t2[e52].length;
      for (const [t3, o3, i3] of this.state.regionSegments[e52]) {
        const r3 = this.problem.routeNet[t3];
        this.state.currentRouteNetId = r3;
        for (const e53 of [o3, i3]) {
          const t4 = this.state.portAssignment[e53];
          if (t4 !== -1 && t4 !== r3)
            throw new Error(`SelectiveReripTinyHyperGraphSolver: rebuilding committed routes found cross-net ownership at port ${e53} between net ${t4} and net ${r3}`);
          this.state.portAssignment[e53] = r3;
        }
        n2 && this.appendSegmentToRegionCache(e52, o3, i3);
      }
      if (!n2) {
        const t3 = this.state.regionIntersectionCaches[e52];
        if (t3.existingSegmentCount === 0)
          continue;
        const n3 = this.computeRegionCostForRegion(e52, t3.existingSameLayerIntersections, t3.existingCrossingLayerIntersections, t3.existingEntryExitLayerChanges, t3.existingSegmentCount);
        n3 !== t3.existingRegionCost && (this.state.regionIntersectionCaches[e52] = { ...t3, existingRegionCost: n3 });
      }
    }
    this.state.currentRouteNetId = undefined;
  }
  incrementFailedOwnerPair(e51, t2) {
    const n2 = this.failedOwnerPairCounts.get(e51) ?? new Map, o3 = (n2.get(t2) ?? 0) + 1;
    return n2.set(t2, o3), this.failedOwnerPairCounts.set(e51, n2), o3;
  }
  hasFailedOwnerPath(e51, t2) {
    const n2 = [e51], o3 = new Set;
    for (;n2.length > 0; ) {
      const e52 = n2.pop();
      if (e52 === t2)
        return true;
      o3.has(e52) || (o3.add(e52), n2.push(...this.failedOwnerPairCounts.get(e52)?.keys() ?? []));
    }
    return false;
  }
  publishSelectiveReripStats() {
    const e51 = [];
    for (const [t2, n2] of this.failedOwnerPairCounts)
      for (const [o3, i3] of n2)
        e51.push({ failedRouteId: t2, ownerRouteId: o3, count: i3 });
    e51.sort((e52, t2) => e52.failedRouteId - t2.failedRouteId || e52.ownerRouteId - t2.ownerRouteId), this.selectiveReripStats.failedOwnerPairs = e51, this.selectiveReripStats.failedOwnerPairCount = e51.length, this.selectiveReripStats.maxFailedOwnerPairCount = Math.max(0, ...e51.map(({ count: e52 }) => e52)), this.stats = { ...this.stats, ...this.getSelectiveReripStats() };
  }
  describeRoute(e51) {
    const t2 = this.problem.routeMetadata?.[e51]?.connectionId;
    return t2 === undefined ? String(e51) : `${e51} (${String(t2)})`;
  }
};
var fJ = class extends gJ {
  remainingReripBudget = 0;
  onOutOfCandidates() {
    super.onOutOfCandidates(), this.state.ripCount >= this.remainingReripBudget && (this.failed = true, this.error = "Congestion-aware final routing exhausted its rerip budget");
  }
};
var _J = class extends gJ {
  initialAssignmentRouteIds;
  getRouteIdsPreferredForPreservation() {
    return this.initialAssignmentRouteIds || (this.initialAssignmentRouteIds = new Set((this.problem.initialAssignments ?? []).map((e51) => e51.routeId))), this.initialAssignmentRouteIds;
  }
  resetRoutingStateForRerip() {
    super.resetRoutingStateForRerip(), this.problem.initialAssignments?.length && GZ({ topology: this.topology, problem: this.problem, state: this.state, routeSuccessCountByRouteId: this.routeSuccessCountByRouteId, appendSegmentToRegionCache: (e51, t2, n2) => this.appendSegmentToRegionCache(e51, t2, n2) });
  }
};
var yJ = class {
  constructor(e51) {
    this.geometry = e51;
  }
  epoch;
  generation = -1;
  frontiers = new Map;
  rows = [];
  step(e51) {
    const { topology: t2, problem: n2, state: o3 } = e51, i3 = o3.candidateQueue;
    if (!(this.geometry.supported && o3.currentRouteId !== undefined && i3 instanceof ZZ && o3.candidateBestCostByHopId instanceof Float64Array && o3.candidateBestCostGenerationByHopId instanceof Uint32Array))
      return false;
    this.geometry.prepare(), this.epoch === i3.closureEpoch && this.generation === o3.candidateBestCostGeneration || (this.epoch = i3.closureEpoch, this.generation = o3.candidateBestCostGeneration, this.frontiers.clear());
    const r3 = i3.dequeue();
    if (!r3)
      return e51.onOutOfCandidates(), true;
    const s2 = r3.hopId ?? e51.getHopId(r3.portId, r3.nextRegionId);
    if (r3.g > e51.getCandidateBestCost(s2) || e51.isRegionReservedForDifferentNet(r3.nextRegionId))
      return true;
    const a3 = r3.nextRegionId, c3 = o3.currentRouteNetId, l3 = o3.goalPortId, h2 = o3.portAssignment, d2 = e51.problemSetup.portEndpointReservationNetId, u2 = n2.regionNetId;
    let p3 = this.frontiers.get(a3);
    if (!p3) {
      const o4 = t2.regionIncidentPorts[a3], i4 = new Int32Array(o4.length).fill(-1), r4 = new Int32Array(o4.length), s3 = new Int32Array(o4.length);
      let m2 = -1, g2 = -1;
      for (let p4 = 0;p4 < o4.length; p4++) {
        const f2 = o4[p4], _2 = d2[f2];
        if (_2 === -2 || _2 !== -1 && _2 !== c3 || h2[f2] !== -1 && h2[f2] !== c3)
          continue;
        let y2 = a3;
        if (f2 !== l3) {
          if (n2.portSectionMask[f2] === 0)
            continue;
          const e52 = t2.incidentPortRegion[f2], o5 = e52[0] === a3 ? e52[1] : e52[0];
          if (o5 === undefined || u2[o5] !== -1 && u2[o5] !== c3)
            continue;
          y2 = o5;
        }
        r4[p4] = y2, s3[p4] = e51.getHopId(f2, y2), g2 === -1 ? m2 = p4 : i4[g2] = p4, g2 = p4;
      }
      p3 = { neighbors: o4, next: i4, nextRegions: r4, hops: s3, head: m2 }, this.frontiers.set(a3, p3);
    }
    return this.expand(e51, r3, p3), true;
  }
  expand(e51, t2, n2) {
    const { topology: o3, problem: i3, state: r3 } = e51, s2 = t2.nextRegionId, a3 = r3.regionIntersectionCaches[s2];
    let c3 = this.rows[s2];
    if (!c3 || c3.cache !== a3 || c3.via !== e51.minViaPadDiameter || c3.density !== e51.TRACE_DENSITY_COST_FACTOR) {
      const t3 = o3.regionAvailableZMask?.[s2] ?? 0;
      c3 = { cache: a3, via: e51.minViaPadDiameter, density: e51.TRACE_DENSITY_COST_FACTOR, single: t3 > 0 && !(t3 & t3 - 1), costs: new Float64Array(2 * a3.netIds.length + 2) };
      for (let e52 = 0;e52 < c3.costs.length; e52++)
        c3.costs[e52] = YZ(o3.regionWidth[s2], o3.regionHeight[s2], a3.existingSameLayerIntersections, a3.existingCrossingLayerIntersections + e52, a3.existingEntryExitLayerChanges, a3.existingSegmentCount + 1, t3, c3.via, c3.density) - a3.existingRegionCost;
      this.rows[s2] = c3;
    }
    const { neighbors: l3, next: h2, nextRegions: d2, hops: u2 } = n2, p3 = r3.candidateBestCostByHopId, m2 = r3.candidateBestCostGenerationByHopId, g2 = r3.candidateBestCostGeneration, f2 = r3.currentRouteNetId, _2 = r3.candidateQueue, y2 = this.geometry.rowOffsets[2 * t2.portId + (o3.incidentPortRegion[t2.portId][0] === s2 ? 0 : 1)], b2 = this.geometry.distances, x2 = o3.incidentPortRegion[t2.portId][0] === s2 ? o3.portAngleForRegion1[t2.portId] : o3.portAngleForRegion2?.[t2.portId] ?? o3.portAngleForRegion1[t2.portId], v2 = o3.portZ[t2.portId], { netIds: I2, lesserAngles: S2, greaterAngles: C, layerMasks: P } = a3, M = r3.regionCongestionCost[s2], w = t2.g + M;
    let N = n2.head, R2 = -1;
    for (;N !== -1; ) {
      const a4 = N;
      N = h2[a4];
      const T2 = R2;
      R2 = a4;
      const E3 = l3[a4];
      if (E3 === r3.goalPortId)
        return void e51.onPathFound(t2);
      if (E3 === t2.portId)
        continue;
      const A2 = u2[a4];
      if (_2.isClosedHopId(A2)) {
        T2 === -1 ? n2.head = N : h2[T2] = N, R2 = T2;
        continue;
      }
      const O2 = m2[A2] === g2 ? p3[A2] : 1 / 0;
      if (t2.g >= O2)
        continue;
      const k2 = b2[y2 + a4] * e51.DISTANCE_TO_COST, D2 = i3.portPenalty?.[E3] ?? 0;
      if (w + D2 + k2 >= O2)
        continue;
      const L2 = o3.portZ[E3], z2 = o3.incidentPortRegion[E3][0] === s2 ? o3.portAngleForRegion1[E3] : o3.portAngleForRegion2?.[E3] ?? o3.portAngleForRegion1[E3], B2 = Math.min(x2, z2), F2 = Math.max(x2, z2), j2 = 1 << v2 | 1 << L2;
      let $2 = 0, Y2 = 0;
      for (let e52 = 0;e52 < I2.length; e52++)
        I2[e52] !== f2 && (B2 < S2[e52] && S2[e52] < F2) != (B2 < C[e52] && C[e52] < F2) && (j2 & P[e52] ? $2++ : Y2++);
      if ($2 > 0 && c3.single)
        continue;
      const X = t2.g + c3.costs[2 * $2 + Y2 + (v2 !== L2 ? 1 : 0)] + M + D2 + k2;
      if (!Number.isFinite(X) || X >= O2)
        continue;
      const H2 = e51.computeH(E3);
      m2[A2] = g2, p3[A2] = X, _2.queue({ hopId: A2, prevRegionId: s2, nextRegionId: d2[a4], portId: E3, g: X, h: H2, f: X + H2, prevCandidate: t2 });
    }
  }
};
var vJ = class extends BaseSolver {
  constructor(e51) {
    super(), this.input = e51;
  }
  static solverName = "RegionDistancePreparationSolver";
  output;
  _step() {
    const { portX: e51, portY: t2, regions: n2 } = this.input, o3 = new Float64Array(n2.reduce((e52, t3) => e52 + t3.length ** 2, 0));
    let i3 = 0;
    for (const r3 of n2)
      for (const n3 of r3)
        for (const s2 of r3) {
          const r4 = e51[n3] - e51[s2], a3 = t2[n3] - t2[s2];
          o3[i3++] = Math.sqrt(r4 * r4 + a3 * a3);
        }
    this.output = o3, this.solved = true;
  }
  getOutput() {
    if (!this.output)
      throw new Error("Region distances have not been prepared");
    return this.output;
  }
};
SolverRuntime.registerSolver(vJ);
var IJ = class {
  constructor(e51) {
    this.topology = e51, this.rowOffsets = new Int32Array(2 * e51.portCount).fill(-1);
    let t2 = 0;
    if (this.supported = e51.incidentPortRegion.every((e52) => e52.length <= 2) && e51.regionIncidentPorts.reduce((e52, t3) => e52 + t3.length ** 2, 0) <= 16777216, !this.supported)
      return;
    for (let n3 = 0;n3 < e51.regionCount; n3++) {
      const o4 = e51.regionIncidentPorts[n3];
      for (let i3 = 0;i3 < o4.length; i3++) {
        const r3 = o4[i3], s2 = 2 * r3 + (e51.incidentPortRegion[r3][0] === n3 ? 0 : 1);
        this.rowOffsets[s2] = t2 + i3 * o4.length;
      }
      t2 += o4.length ** 2;
    }
    let n2 = [], o3 = 0;
    for (const i3 of e51.regionIncidentPorts)
      n2.push(i3), o3 += i3.length ** 2, o3 >= t2 / 4 && this.jobs.length < 3 && (this.jobs.push({ portX: e51.portX, portY: e51.portY, regions: n2 }), n2 = [], o3 = 0);
    n2.length && this.jobs.push({ portX: e51.portX, portY: e51.portY, regions: n2 });
  }
  rowOffsets;
  jobs = [];
  distances;
  supported;
  accept(e51) {
    this.distances = new Float64Array(e51.reduce((e52, t3) => e52 + t3.length, 0));
    let t2 = 0;
    for (const n2 of e51)
      this.distances.set(n2, t2), t2 += n2.length;
  }
  prepare() {
    !this.distances && this.supported && this.accept(this.jobs.map((e51) => {
      const t2 = new vJ(e51);
      return t2.solve(), t2.getOutput();
    }));
  }
  async prepareAsync(e51) {
    !this.distances && this.supported && this.accept(await Promise.all(this.jobs.map((t2) => e51.executeAsync(vJ, t2))));
  }
};
var SJ = class extends gJ {
  workspace;
  remainingReripBudget = 0;
  constructor(e51, t2, n2, o3) {
    super(e51, t2, n2), this.workspace = new yJ(o3);
  }
  _step() {
    this.workspace.step(this) || super._step();
  }
  onOutOfCandidates() {
    super.onOutOfCandidates(), this.state.ripCount >= this.remainingReripBudget && (this.failed = true, this.error = "Congestion-aware final routing exhausted its rerip budget");
  }
};
var CJ = class extends _J {
  geometry = new IJ(this.topology);
  workspace = new yJ(this.geometry);
  asyncRunning = false;
  _step() {
    const e51 = this.state.currentRouteId;
    (e51 !== undefined && this.partialRipRoutePlans.has(e51) || !this.workspace.step(this)) && super._step();
  }
  createGreedyFinalRouteSolver(e51, t2) {
    if (t2 >= 0)
      return super.createGreedyFinalRouteSolver(e51, t2);
    const n2 = new SJ(this.topology, this.problem, { ...e51, MAX_ITERATIONS: Math.max(e51.MAX_ITERATIONS ?? 50000, 2 * this.MAX_ITERATIONS) }, this.geometry);
    return n2.remainingReripBudget = this.costAwareFinalReripBudget - this.state.ripCount, n2;
  }
  async solveAsync(e51, t2 = 1 / 0) {
    if (this.asyncRunning)
      throw new Error("Prepared routing solveAsync is already running");
    this.asyncRunning = true;
    try {
      for (e51 && !this.solved && !this.failed && this.iterations < t2 && await this.geometry.prepareAsync(e51);!this.solved && !this.failed && this.iterations < t2; )
        this.step();
    } catch (e52) {
      throw this.failed = true, this.error = `Prepared routing execution failed: ${e52}`, e52;
    } finally {
      this.asyncRunning = false;
    }
  }
};
var MJ = (e51) => {
  const t2 = typeof e51.d?.netId == "number" ? e51.d.netId : typeof e51.d?.NetId == "number" ? e51.d.NetId : undefined;
  return Number.isFinite(t2) ? t2 : undefined;
};
var wJ = (e51) => {
  const t2 = new Set;
  for (const n3 of e51.connections ?? [])
    t2.add(n3.startRegionId), t2.add(n3.endRegionId);
  const n2 = new Set(e51.regions.filter((e52) => ((e53) => {
    if (e53.d?._containsObstacle !== true)
      return false;
    const t3 = MJ(e53);
    return t3 === undefined || t3 === -1;
  })(e52) && !t2.has(e52.regionId)).map((e52) => e52.regionId));
  if (n2.size === 0)
    return e51;
  const o3 = e51.ports.filter((e52) => !n2.has(e52.region1Id) && !n2.has(e52.region2Id)), i3 = (e51.connections ?? []).find((e52) => n2.has(e52.startRegionId) || n2.has(e52.endRegionId));
  if (i3)
    throw new Error(`Connection "${i3.connectionId}" references full-obstacle region`);
  return { ...e51, regions: e51.regions.filter((e52) => !n2.has(e52.regionId)), ports: o3 };
};
var NJ = (e51) => {
  const t2 = e51.d?.bounds;
  if (t2)
    return t2;
  const n2 = e51.d?.center, o3 = e51.d?.width, i3 = e51.d?.height;
  return n2 && typeof n2.x == "number" && typeof n2.y == "number" && typeof o3 == "number" && typeof i3 == "number" ? { minX: n2.x - o3 / 2, maxX: n2.x + o3 / 2, minY: n2.y - i3 / 2, maxY: n2.y + i3 / 2 } : { minX: 0, maxX: 0, minY: 0, maxY: 0 };
};
var RJ = (e51) => Number(e51.d?.x ?? 0);
var TJ = (e51) => Number(e51.d?.y ?? 0);
var EJ = (e51, t2) => {
  if (!t2)
    return 0;
  const n2 = NJ(t2), o3 = RJ(e51), i3 = TJ(e51), r3 = n2.minX <= o3 && o3 <= n2.maxX, s2 = n2.minY <= i3 && i3 <= n2.maxY;
  if (s2 && o3 >= n2.maxX) {
    const e52 = Math.max(n2.maxY - n2.minY, 0.000000001), t3 = (i3 - n2.minY) / e52;
    return Math.round(9000 * t3);
  }
  if (r3 && i3 >= n2.maxY) {
    const e52 = Math.max(n2.maxX - n2.minX, 0.000000001), t3 = (n2.maxX - o3) / e52;
    return 9000 + Math.round(9000 * t3);
  }
  if (s2 && o3 <= n2.minX) {
    const e52 = Math.max(n2.maxY - n2.minY, 0.000000001), t3 = (n2.maxY - i3) / e52;
    return 18000 + Math.round(9000 * t3);
  }
  if (r3 && i3 <= n2.minY) {
    const e52 = Math.max(n2.maxX - n2.minX, 0.000000001), t3 = (o3 - n2.minX) / e52;
    return 27000 + Math.round(9000 * t3);
  }
  const a3 = Math.abs(o3 - n2.minX), c3 = Math.abs(o3 - n2.maxX), l3 = Math.abs(i3 - n2.minY), h2 = Math.abs(i3 - n2.maxY), d2 = Math.min(a3, c3, l3, h2), u2 = Math.max(n2.maxX - n2.minX, 0.000000001), p3 = Math.max(n2.maxY - n2.minY, 0.000000001);
  if (d2 === c3) {
    const e52 = (i3 - n2.minY) / p3;
    return Math.round(9000 * e52);
  }
  if (d2 === h2) {
    const e52 = (n2.maxX - o3) / u2;
    return 9000 + Math.round(9000 * e52);
  }
  if (d2 === a3) {
    const e52 = (n2.maxY - i3) / p3;
    return 18000 + Math.round(9000 * e52);
  }
  const m2 = (o3 - n2.minX) / u2;
  return 27000 + Math.round(9000 * m2);
};
var AJ = (e51, t2) => {
  if (!e51)
    return;
  return [...e51.pointIds].sort((e52, n2) => {
    const o3 = t2.get(e52), i3 = t2.get(n2), r3 = Number(o3?.d?.distToCentermostPortOnZ ?? Number.POSITIVE_INFINITY), s2 = Number(i3?.d?.distToCentermostPortOnZ ?? Number.POSITIVE_INFINITY);
    if (r3 !== s2)
      return r3 - s2;
    const a3 = Number(o3?.d?.z ?? 0), c3 = Number(i3?.d?.z ?? 0);
    return a3 !== c3 ? a3 - c3 : e52.localeCompare(n2);
  })[0];
};
var OJ = (e51) => {
  const t2 = wJ(e51), n2 = new Map, o3 = new Map, i3 = new Map, r3 = new Map((t2.solvedRoutes ?? []).map((e52) => [e52.connection.connectionId, e52]));
  t2.regions.forEach((e52, t3) => {
    n2.set(e52.regionId, t3);
  }), t2.ports.forEach((e52, t3) => {
    o3.set(e52.portId, t3), i3.set(e52.portId, e52);
  });
  const s2 = t2.regions.length, a3 = t2.ports.length, c3 = t2.regions.map((e52) => e52.pointIds.map((e53) => o3.get(e53)).filter((e53) => e53 !== undefined)), l3 = Array.from({ length: a3 }, () => []), h2 = new Float64Array(s2), d2 = new Float64Array(s2), u2 = new Float64Array(s2), p3 = new Float64Array(s2), m2 = new Int32Array(s2), g2 = new Int32Array(s2).fill(-1), f2 = new Int8Array(s2);
  t2.regions.forEach((e52, t3) => {
    const n3 = ((e53) => {
      const t4 = NJ(e53), n4 = typeof e53.d?.width == "number" ? e53.d.width : t4.maxX - t4.minX, o5 = typeof e53.d?.height == "number" ? e53.d.height : t4.maxY - t4.minY;
      return { centerX: typeof e53.d?.center?.x == "number" ? e53.d.center.x : (t4.minX + t4.maxX) / 2, centerY: typeof e53.d?.center?.y == "number" ? e53.d.center.y : (t4.minY + t4.maxY) / 2, width: n4, height: o5 };
    })(e52);
    h2[t3] = n3.width, d2[t3] = n3.height, u2[t3] = n3.centerX, p3[t3] = n3.centerY, m2[t3] = ((e53) => {
      const t4 = e53.d?.availableZ;
      if (!Array.isArray(t4))
        return 0;
      let n4 = 0;
      for (const e54 of t4)
        !Number.isInteger(e54) || e54 < 0 || e54 >= 31 || (n4 |= 1 << e54);
      return n4;
    })(e52);
    const o4 = MJ(e52);
    o4 !== undefined && (g2[t3] = o4, f2[t3] = 1);
  });
  const _2 = new Int32Array(a3), y2 = new Int32Array(a3), b2 = new Float64Array(a3), x2 = new Float64Array(a3), v2 = new Int32Array(a3);
  t2.ports.forEach((e52, o4) => {
    const i4 = n2.get(e52.region1Id), r4 = n2.get(e52.region2Id);
    if (i4 === undefined || r4 === undefined)
      throw new Error(`Port "${e52.portId}" references missing regions "${e52.region1Id}" or "${e52.region2Id}"`);
    l3[o4] = [i4, r4], b2[o4] = RJ(e52), x2[o4] = TJ(e52), v2[o4] = ((e53) => {
      const t3 = Number(e53.d?.z ?? 0);
      return Number.isFinite(t3) ? t3 : 0;
    })(e52), _2[o4] = EJ(e52, t2.regions[i4]), y2[o4] = EJ(e52, t2.regions[r4]);
  });
  const I2 = t2.regions.map((e52, t3) => ((e53, t4) => {
    const n3 = e53.d && typeof e53.d == "object" && !Array.isArray(e53.d) ? { ...e53.d } : { value: e53.d };
    return n3.layer = t4, Object.defineProperty(n3, "serializedRegionId", { value: e53.regionId, enumerable: false, configurable: true, writable: true }), n3;
  })(e52, ((e53) => NZ(RZ(m2[e53])) ?? NZ((c3[e53] ?? []).map((e54) => v2[e54])) ?? "z0")(t3))), S2 = t2.ports.map((e52, t3) => ((e53, t4) => {
    const n3 = e53.d && typeof e53.d == "object" && !Array.isArray(e53.d) ? { ...e53.d } : { value: e53.d };
    return n3.layer = t4, Object.defineProperty(n3, "serializedPortId", { value: e53.portId, enumerable: false, configurable: true, writable: true }), n3;
  })(e52, NZ([v2[t3]]) ?? "z0")), C = t2.connections ?? [], P = new Map;
  let M = 0;
  const w = (e52) => {
    const t3 = e52.mutuallyConnectedNetworkId ?? e52.connectionId;
    let n3 = P.get(t3);
    return n3 === undefined && (n3 = M++, P.set(t3, n3)), n3;
  }, N = Array.from({ length: s2 }, () => new Set), R2 = (e52, t3) => {
    const o4 = n2.get(e52);
    if (o4 === undefined)
      throw new Error(`Connection references missing region "${e52}"`);
    N[o4].add(t3);
  };
  C.forEach((e52) => {
    const t3 = w(e52);
    R2(e52.startRegionId, t3), R2(e52.endRegionId, t3);
  }), N.forEach((e52, t3) => {
    f2[t3] !== 1 && e52.size === 1 && (g2[t3] = [...e52][0]);
  });
  const T2 = C.map((e52) => {
    const n3 = r3.get(e52.connectionId), o4 = ((e53, t3) => e53.ports.filter((e54) => e54.region1Id === t3.startRegionId && e54.region2Id === t3.endRegionId || e54.region2Id === t3.startRegionId && e54.region1Id === t3.endRegionId).map((e54) => e54.portId))(t2, e52);
    return { connection: e52, solvedRoute: n3, sharedPortIds: o4 };
  }).filter(({ solvedRoute: e52, sharedPortIds: t3 }) => t3.length === 0 || (e52?.path.length ?? 0) > 1), E3 = T2.length, A2 = new Map(T2.map(({ connection: e52 }, t3) => [e52.connectionId, t3])), O2 = new Int8Array(a3).fill(1), k2 = new Int32Array(E3), D2 = new Int32Array(E3), L2 = new Int32Array(E3);
  T2.forEach(({ connection: e52, solvedRoute: n3 }, r4) => {
    const s3 = AJ(t2.regions.find((t3) => t3.regionId === e52.startRegionId), i3), a4 = AJ(t2.regions.find((t3) => t3.regionId === e52.endRegionId), i3), c4 = n3?.path[0]?.portId ?? s3, l4 = n3?.path[n3.path.length - 1]?.portId ?? a4, h3 = c4 !== undefined ? o3.get(c4) : undefined, d3 = l4 !== undefined ? o3.get(l4) : undefined;
    if (h3 === undefined || d3 === undefined)
      throw new Error(`Connection "${e52.connectionId}" could not be mapped to route endpoints`);
    k2[r4] = h3, D2[r4] = d3, L2[r4] = w(e52);
  });
  const z2 = { portCount: a3, regionCount: s2, regionIncidentPorts: c3, incidentPortRegion: l3, regionWidth: h2, regionHeight: d2, regionCenterX: u2, regionCenterY: p3, regionAvailableZMask: m2, regionMetadata: I2, portAngleForRegion1: _2, portAngleForRegion2: y2, portX: b2, portY: x2, portZ: v2, portMetadata: S2 }, B2 = t2.regions.flatMap((e52, t3) => (e52.assignments ?? []).map((n3) => {
    const i4 = A2.get(n3.connectionId);
    if (i4 === undefined)
      throw new Error(`Region "${e52.regionId}" assignment references unknown routable connection "${n3.connectionId}"`);
    const r4 = o3.get(n3.regionPort1Id), s3 = o3.get(n3.regionPort2Id);
    if (r4 === undefined || s3 === undefined)
      throw new Error(`Region "${e52.regionId}" assignment references missing port "${r4 === undefined ? n3.regionPort1Id : n3.regionPort2Id}"`);
    if (!c3[t3]?.includes(r4) || !c3[t3]?.includes(s3))
      throw new Error(`Region "${e52.regionId}" assignment ports must both belong to the region`);
    return { routeId: i4, regionId: t3, fromPortId: r4, toPortId: s3 };
  })), F2 = Float64Array.from(t2.ports, (e52) => {
    const t3 = Number(e52.d?.tinyHypergraphPortPenalty ?? 0);
    return Number.isFinite(t3) && t3 > 0 ? t3 : 0;
  }), j2 = F2.some((e52) => e52 > 0), $2 = { routeCount: E3, portSectionMask: O2, routeMetadata: T2.map(({ connection: e52 }) => e52), routeStartPort: k2, routeEndPort: D2, routeNet: L2, regionNetId: g2, ...B2.length > 0 && { initialAssignments: B2 }, ...j2 && { portPenalty: F2 } }, Y2 = [], X = [];
  for (const { solvedRoute: e52 } of T2) {
    if (!e52) {
      Y2.push([]), X.push([]);
      continue;
    }
    const t3 = [], i4 = [];
    for (let r4 = 1;r4 < e52.path.length; r4++) {
      const s3 = e52.path[r4 - 1], a4 = e52.path[r4], c4 = s3?.portId, l4 = a4?.portId, h3 = c4 !== undefined ? o3.get(c4) : undefined, d3 = l4 !== undefined ? o3.get(l4) : undefined;
      if (h3 === undefined || d3 === undefined)
        continue;
      const u3 = typeof s3?.nextRegionId == "string" ? s3.nextRegionId : typeof a4?.lastRegionId == "string" ? a4.lastRegionId : undefined;
      t3.push([h3, d3]), i4.push(u3 !== undefined ? n2.get(u3) : undefined);
    }
    Y2.push(t3), X.push(i4);
  }
  return { topology: z2, problem: $2, solution: { solvedRoutePathSegments: Y2, solvedRoutePathRegionIds: X } };
};
var kJ = (e51) => typeof e51 == "object" && e51 !== null;
var DJ = (e51) => Array.isArray(e51) ? e51.map((e52) => DJ(e52)) : kJ(e51) ? Object.fromEntries(Object.entries(e51).map(([e52, t2]) => [e52, DJ(t2)])) : e51;
var LJ = (e51) => kJ(e51) ? { ...e51 } : e51 === undefined ? {} : { value: e51 };
var zJ = (e51, t2 = 0) => typeof e51 == "number" && Number.isFinite(e51) ? e51 : t2;
var BJ = (e51) => ({ x: zJ(e51.d?.x), y: zJ(e51.d?.y) });
var FJ = (e51) => [e51.region1Id, e51.region2Id].sort().join("\x00");
var jJ = (e51, t2) => Math.hypot(e51.x - t2.x, e51.y - t2.y);
var $J = (e51) => {
  const t2 = Math.hypot(e51.x, e51.y);
  if (!(t2 <= 0.000000001))
    return { x: e51.x / t2, y: e51.y / t2 };
};
var YJ = (e51) => {
  const t2 = e51?.d?.center;
  if (kJ(t2))
    return { x: zJ(t2.x), y: zJ(t2.y) };
  const n2 = ((e52) => {
    const t3 = e52?.d?.bounds;
    if (kJ(t3) && typeof t3.minX == "number" && typeof t3.maxX == "number" && typeof t3.minY == "number" && typeof t3.maxY == "number")
      return { minX: t3.minX, maxX: t3.maxX, minY: t3.minY, maxY: t3.maxY };
    const n3 = e52?.d?.center, o3 = zJ(e52?.d?.width), i3 = zJ(e52?.d?.height);
    if (kJ(n3)) {
      const e53 = zJ(n3.x), t4 = zJ(n3.y);
      return { minX: e53 - o3 / 2, maxX: e53 + o3 / 2, minY: t4 - i3 / 2, maxY: t4 + i3 / 2 };
    }
    return { minX: 0, maxX: 0, minY: 0, maxY: 0 };
  })(e51);
  return { x: (n2.minX + n2.maxX) / 2, y: (n2.minY + n2.maxY) / 2 };
};
var XJ = (e51, t2) => {
  const n2 = BJ(e51);
  let o3, i3 = Number.POSITIVE_INFINITY;
  for (const r3 of t2) {
    if (r3.portId === e51.portId)
      continue;
    const t3 = jJ(n2, BJ(r3));
    t3 <= 0.000000001 || t3 >= i3 || (o3 = r3, i3 = t3);
  }
  return o3;
};
var HJ = (e51, t2, n2) => {
  const o3 = BJ(e51);
  if (t2) {
    const e52 = BJ(t2), n3 = $J({ x: o3.x - e52.x, y: o3.y - e52.y });
    if (n3)
      return n3;
  }
  return ((e52, t3) => {
    const n3 = YJ(t3.get(e52.region1Id)), o4 = YJ(t3.get(e52.region2Id));
    return $J({ x: -(o4.y - n3.y), y: o4.x - n3.x }) ?? { x: 1, y: 0 };
  })(e51, n2);
};
var VJ = (e51, t2, n2) => {
  const o3 = `${e51}::dup${t2}`;
  if (!n2.has(o3))
    return n2.add(o3), o3;
  for (let e52 = 2;; e52++) {
    const t3 = `${o3}-${e52}`;
    if (!n2.has(t3))
      return n2.add(t3), t3;
  }
};
var WJ = (e51, t2, n2) => {
  const o3 = e51.indexOf(t2);
  o3 !== -1 ? e51.splice(o3 + 1, 0, ...n2) : e51.push(...n2);
};
var GJ = (e51, t2) => {
  const n2 = e51.portMetadata?.[t2];
  if (kJ(n2)) {
    if (typeof n2.serializedPortId == "string")
      return n2.serializedPortId;
    if (typeof n2.portId == "string")
      return n2.portId;
  }
  return `port-${t2}`;
};
var UJ = (e51, t2) => ({ routeCount: 1, portSectionMask: e51.portSectionMask, routeMetadata: e51.routeMetadata === undefined ? undefined : [e51.routeMetadata[t2]], routeStartPort: Int32Array.from([e51.routeStartPort[t2]]), routeEndPort: Int32Array.from([e51.routeEndPort[t2]]), routeNet: Int32Array.from([e51.routeNet[t2]]), regionNetId: e51.regionNetId, portPenalty: e51.portPenalty });
var ZJ = (e51) => {
  const t2 = new Set;
  for (const n2 of e51.state.regionSegments)
    for (const [, e52, o3] of n2)
      t2.add(e52), t2.add(o3);
  return t2.size === 0 && e51.problem.routeCount === 1 && (t2.add(e51.problem.routeStartPort[0]), t2.add(e51.problem.routeEndPort[0])), t2;
};
var qJ = class extends BaseSolver {
  constructor(e51, t2 = {}) {
    super(), this.serializedHyperGraph = e51, this.options = t2;
  }
  revisedSerializedHyperGraph;
  report = { portUseCounts: {}, duplicatedPorts: [] };
  getDuplicatePortProximity() {
    return this.options.duplicatePortProximity ?? 0.05;
  }
  getIndividualRouteSolveOptions() {
    return { RIP_THRESHOLD_RAMP_ATTEMPTS: 0, STATIC_REACHABILITY_PRECHECK: false, ...this.options.routeSolveOptions };
  }
  getPortUseCounts() {
    const { topology: e51, problem: t2 } = OJ(this.serializedHyperGraph);
    this.options.useSerializedPortPenalties === false && (t2.portPenalty = undefined);
    const n2 = new Map;
    let o3;
    for (let i3 = 0;i3 < t2.routeCount; i3++) {
      const r3 = UJ(t2, i3);
      if (o3 ? o3.resetForProblem(r3) : o3 = new tJ(e51, r3, this.getIndividualRouteSolveOptions()), o3.solve(), !o3.solved || o3.failed)
        throw new Error(`Route ${i3} could not be solved independently: ${o3.error ?? "unknown error"}`);
      for (const t3 of ZJ(o3)) {
        const o4 = GJ(e51, t3);
        n2.set(o4, (n2.get(o4) ?? 0) + 1);
      }
    }
    return n2;
  }
  duplicateCongestedPorts(e51) {
    const t2 = this.getDuplicatePortProximity();
    if (!(t2 > 0))
      throw new Error("duplicatePortProximity must be greater than zero");
    const { solvedRoutes: n2, ...o3 } = this.serializedHyperGraph, i3 = this.serializedHyperGraph.regions.map((e52) => ({ ...e52, pointIds: [...e52.pointIds], d: DJ(e52.d) })), r3 = this.serializedHyperGraph.ports.map((e52) => ({ ...e52, d: DJ(e52.d) })), s2 = new Map(i3.map((e52) => [e52.regionId, e52])), a3 = new Map(r3.map((e52) => [e52.portId, e52])), c3 = ((e52) => {
      const t3 = new Map;
      for (const n3 of e52) {
        const e53 = FJ(n3), o4 = t3.get(e53);
        o4 ? o4.push(n3) : t3.set(e53, [n3]);
      }
      return t3;
    })(this.serializedHyperGraph.ports), l3 = new Set(r3.map((e52) => e52.portId)), h2 = [];
    for (const [n3, o4] of [...e51.entries()].sort(([e52], [t3]) => e52.localeCompare(t3))) {
      if (o4 <= 1)
        continue;
      const e52 = a3.get(n3);
      if (!e52)
        continue;
      const i4 = o4 - 1, d2 = c3.get(FJ(e52));
      if (!d2)
        throw new Error(`No boundary ports found for "${n3}"`);
      const u2 = XJ(e52, d2), p3 = HJ(e52, u2, s2), m2 = BJ(e52), g2 = [];
      for (let s3 = 1;s3 <= i4; s3++) {
        const a4 = VJ(n3, s3, l3), c4 = t2 * s3 / (i4 + 1), h3 = LJ(DJ(e52.d));
        h3.x = m2.x + p3.x * c4, h3.y = m2.y + p3.y * c4, h3.duplicatedFromPortId = n3, h3.duplicateIndex = s3, h3.duplicatePortUseCount = o4, h3.duplicatePortProximity = t2, h3.repairReason = "congested-port", r3.push({ ...e52, portId: a4, d: h3 }), g2.push(a4);
      }
      for (const t3 of [e52.region1Id, e52.region2Id]) {
        const e53 = s2.get(t3);
        e53 && WJ(e53.pointIds, n3, g2);
      }
      h2.push({ sourcePortId: n3, duplicatePortIds: g2, useCount: o4 });
    }
    return this.report = { portUseCounts: Object.fromEntries([...e51.entries()].sort()), duplicatedPorts: h2 }, { ...o3, regions: i3, ports: r3, connections: this.serializedHyperGraph.connections === undefined ? undefined : DJ(this.serializedHyperGraph.connections) };
  }
  _setup() {
    try {
      const e51 = this.getPortUseCounts();
      this.revisedSerializedHyperGraph = this.duplicateCongestedPorts(e51), this.stats = { ...this.stats, duplicateSourcePortCount: this.report.duplicatedPorts.length, duplicatedPortCount: this.report.duplicatedPorts.reduce((e52, t2) => e52 + t2.duplicatePortIds.length, 0) }, this.solved = true;
    } catch (e51) {
      this.failed = true, this.error = e51 instanceof Error ? e51.message : String(e51);
    }
  }
  _step() {
    this.failed || (this.solved = true);
  }
  getOutput() {
    if (!this.revisedSerializedHyperGraph || this.failed)
      throw new Error("DuplicateCongestedPortSolver does not have a repaired topology output");
    return this.revisedSerializedHyperGraph;
  }
};
var QJ = (e51, t2) => {
  Qq(e51, t2), t2 && (t2.MAX_RIPS !== undefined && (e51.MAX_RIPS = t2.MAX_RIPS), t2.MAX_RIPS_WITHOUT_MAX_REGION_COST_IMPROVEMENT !== undefined && (e51.MAX_RIPS_WITHOUT_MAX_REGION_COST_IMPROVEMENT = t2.MAX_RIPS_WITHOUT_MAX_REGION_COST_IMPROVEMENT), t2.EXTRA_RIPS_AFTER_BEATING_BASELINE_MAX_REGION_COST !== undefined && (e51.EXTRA_RIPS_AFTER_BEATING_BASELINE_MAX_REGION_COST = t2.EXTRA_RIPS_AFTER_BEATING_BASELINE_MAX_REGION_COST));
};
var KJ = (e51) => e51.map((e52) => e52.map(([e53, t2, n2]) => [e53, t2, n2]));
var eQ = (e51) => ({ netIds: new Int32Array(e51.netIds), lesserAngles: new Int32Array(e51.lesserAngles), greaterAngles: new Int32Array(e51.greaterAngles), layerMasks: new Int32Array(e51.layerMasks), existingCrossingLayerIntersections: e51.existingCrossingLayerIntersections, existingSameLayerIntersections: e51.existingSameLayerIntersections, existingEntryExitLayerChanges: e51.existingEntryExitLayerChanges, existingRegionCost: e51.existingRegionCost, existingSegmentCount: e51.existingSegmentCount });
var tQ = (e51) => ({ portAssignment: new Int32Array(e51.portAssignment), regionSegments: KJ(e51.regionSegments), regionIntersectionCaches: e51.regionIntersectionCaches.map(eQ) });
var nQ = (e51, t2) => {
  const n2 = tQ(t2);
  e51.state.portAssignment = n2.portAssignment, e51.state.regionSegments = n2.regionSegments, e51.state.regionIntersectionCaches = n2.regionIntersectionCaches;
};
var oQ = (e51) => {
  let t2 = 0, n2 = 0;
  for (let o3 = 0;o3 < e51.length; o3++) {
    const i3 = e51[o3]?.existingRegionCost ?? 0;
    t2 = Math.max(t2, i3), n2 += i3;
  }
  return { maxRegionCost: t2, totalRegionCost: n2 };
};
var iQ = (e51, t2) => e51.maxRegionCost !== t2.maxRegionCost ? e51.maxRegionCost - t2.maxRegionCost : e51.totalRegionCost - t2.totalRegionCost;
var rQ = (e51, t2, n2) => {
  const o3 = e51.incidentPortRegion[t2] ?? [], i3 = e51.incidentPortRegion[n2] ?? [], r3 = o3.find((e52) => i3.includes(e52));
  if (r3 === undefined)
    throw new Error(`Ports ${t2} and ${n2} do not share a region`);
  return r3;
};
var sQ = (e51, t2, n2, o3) => {
  const i3 = n2.solvedRoutePathSegments[o3] ?? [], r3 = n2.solvedRoutePathRegionIds?.[o3] ?? [], s2 = t2.routeStartPort[o3], a3 = t2.routeEndPort[o3];
  if (i3.length === 0) {
    if (s2 === a3)
      return { orderedPortIds: [s2], orderedRegionIds: [] };
    throw new Error(`Route ${o3} does not have an existing solved path`);
  }
  const c3 = new Map;
  i3.forEach(([e52, t3], n3) => {
    const o4 = { segmentIndex: n3, fromPortId: e52, toPortId: t3, regionId: r3[n3] }, i4 = c3.get(e52) ?? [];
    i4.push(o4), c3.set(e52, i4);
    const s3 = c3.get(t3) ?? [];
    s3.push(o4), c3.set(t3, s3);
  });
  const l3 = [s2], h2 = [], d2 = new Set;
  let u2, p3 = s2;
  for (;p3 !== a3 || d2.size < i3.length; ) {
    const t3 = (c3.get(p3) ?? []).filter(({ segmentIndex: e52, fromPortId: t4, toPortId: n4 }) => {
      if (d2.has(e52))
        return false;
      const o4 = t4 === p3 ? n4 : t4, r5 = o4 === a3 && d2.size + 1 === i3.length;
      return o4 !== u2 || r5;
    }), n3 = p3 === a3 && d2.size === 0 && t3.length === 2 || t3.length === 1 ? t3[0] : undefined;
    if (!n3)
      throw new Error(`Route ${o3} is not a single ordered path from ${s2} to ${a3}`);
    const r4 = n3.fromPortId === p3 ? n3.toPortId : n3.fromPortId;
    d2.add(n3.segmentIndex), h2.push(n3.regionId ?? rQ(e51, n3.fromPortId, n3.toPortId)), l3.push(r4), u2 = p3, p3 = r4;
  }
  if (d2.size !== i3.length)
    throw new Error(`Route ${o3} contains disconnected solved segments`);
  return { orderedPortIds: l3, orderedRegionIds: h2 };
};
var aQ = (e51, t2, n2, o3) => {
  const i3 = new tJ(e51, t2, o3);
  return ((e52, t3) => {
    e52.state.portAssignment.fill(-1), e52.state.regionSegments = Array.from({ length: e52.topology.regionCount }, () => []), e52.state.regionIntersectionCaches = Array.from({ length: e52.topology.regionCount }, () => Zq()), e52.state.currentRouteId = undefined, e52.state.currentRouteNetId = undefined, e52.state.unroutedRoutes = [], e52.state.candidateQueue.clear(), e52.resetCandidateBestCosts(), e52.state.goalPortId = -1, e52.state.ripCount = 0, e52.state.regionCongestionCost.fill(0);
    for (let n3 = 0;n3 < t3.length; n3++)
      for (const [o4, i4, r3] of t3[n3] ?? [])
        e52.state.currentRouteNetId = e52.problem.routeNet[o4], e52.state.regionSegments[n3].push([o4, i4, r3]), e52.state.portAssignment[i4] = e52.state.currentRouteNetId, e52.state.portAssignment[r3] = e52.state.currentRouteNetId, e52.appendSegmentToRegionCache(n3, i4, r3);
    e52.state.currentRouteId = undefined, e52.state.currentRouteNetId = undefined, e52.solved = true, e52.failed = false, e52.error = null;
  })(i3, n2), i3;
};
var cQ = (e51, t2, n2) => {
  const o3 = new Int32Array(t2.routeStartPort), i3 = new Int32Array(t2.routeEndPort), r3 = Array.from({ length: t2.routeCount }, (e52, t3) => ({ routeId: t3, fixedSegments: [] })), s2 = [];
  for (let a3 = 0;a3 < t2.routeCount; a3++) {
    const c3 = r3[a3], { orderedPortIds: l3, orderedRegionIds: h2 } = sQ(e51, t2, n2, a3), d2 = [];
    let u2;
    for (let e52 = 0;e52 < l3.length; e52++) {
      const n3 = l3[e52], o4 = t2.portSectionMask[n3] === 1;
      o4 && u2 === undefined ? u2 = e52 : o4 || u2 === undefined || (d2.push({ startIndex: u2, endIndex: e52 - 1 }), u2 = undefined);
    }
    if (u2 !== undefined && d2.push({ startIndex: u2, endIndex: l3.length - 1 }), d2.length === 0) {
      for (let e52 = 1;e52 < l3.length; e52++)
        c3.fixedSegments.push({ regionId: h2[e52 - 1], fromPortId: l3[e52 - 1], toPortId: l3[e52] });
      continue;
    }
    if (d2.length > 1)
      throw new Error(`Route ${a3} enters the section multiple times; only one contiguous section span is currently supported`);
    const p3 = d2[0], m2 = Math.max(0, p3.startIndex - 1), g2 = Math.min(l3.length - 1, p3.endIndex + 1);
    if (g2 <= m2)
      throw new Error(`Route ${a3} does not have a valid section span`);
    for (let e52 = 1;e52 <= m2; e52++)
      c3.fixedSegments.push({ regionId: h2[e52 - 1], fromPortId: l3[e52 - 1], toPortId: l3[e52] });
    for (let e52 = g2 + 1;e52 < l3.length; e52++)
      c3.fixedSegments.push({ regionId: h2[e52 - 1], fromPortId: l3[e52 - 1], toPortId: l3[e52] });
    c3.activeStartPortId = l3[m2], c3.activeEndPortId = l3[g2], c3.forcedStartRegionId = h2[m2], o3[a3] = c3.activeStartPortId, i3[a3] = c3.activeEndPortId, s2.push(a3);
  }
  return { sectionProblem: { routeCount: t2.routeCount, portSectionMask: new Int8Array(t2.portSectionMask), routeMetadata: t2.routeMetadata, routeStartPort: o3, routeEndPort: i3, routeNet: new Int32Array(t2.routeNet), regionNetId: new Int32Array(t2.regionNetId), portPenalty: t2.portPenalty === undefined ? undefined : new Float64Array(t2.portPenalty) }, routePlans: r3, activeRouteIds: s2 };
};
var lQ = (e51, t2, n2) => cQ(e51, t2, n2).activeRouteIds;
var hQ = class extends tJ {
  constructor(e51, t2, n2, o3, i3, r3, s2, a3) {
    super(e51, t2, a3), this.routePlans = n2, this.activeRouteIds = o3, this.mutableRegionIds = i3, this.immutableRegionSummary = r3, this.baselineSummary = s2, QJ(this, a3), this.state.unroutedRoutes = [...o3], this.applyFixedSegments(), this.fixedSnapshot = tQ({ portAssignment: this.state.portAssignment, regionSegments: this.state.regionSegments, regionIntersectionCaches: this.state.regionIntersectionCaches });
  }
  bestSnapshot;
  fixedSnapshot;
  bestSummary;
  baselineBeatRipCount;
  previousBestMaxRegionCost = Number.POSITIVE_INFINITY;
  ripsSinceBestMaxRegionCostImprovement = 0;
  MAX_RIPS = Number.POSITIVE_INFINITY;
  MAX_RIPS_WITHOUT_MAX_REGION_COST_IMPROVEMENT = Number.POSITIVE_INFINITY;
  EXTRA_RIPS_AFTER_BEATING_BASELINE_MAX_REGION_COST = Number.POSITIVE_INFINITY;
  applyFixedSegments() {
    for (const e51 of this.routePlans)
      for (const { regionId: t2, fromPortId: n2, toPortId: o3 } of e51.fixedSegments)
        this.state.currentRouteNetId = this.problem.routeNet[e51.routeId], this.state.regionSegments[t2].push([e51.routeId, n2, o3]), this.state.portAssignment[n2] = this.state.currentRouteNetId, this.state.portAssignment[o3] = this.state.currentRouteNetId, this.appendSegmentToRegionCache(t2, n2, o3);
    this.state.currentRouteId = undefined, this.state.currentRouteNetId = undefined;
  }
  captureBestState(e51) {
    this.bestSummary && iQ(e51, this.bestSummary) >= 0 || (this.bestSummary = e51, this.bestSnapshot = tQ({ portAssignment: this.state.portAssignment, regionSegments: this.state.regionSegments, regionIntersectionCaches: this.state.regionIntersectionCaches }));
  }
  restoreBestState() {
    this.bestSnapshot && (nQ(this, this.bestSnapshot), this.state.currentRouteId = undefined, this.state.currentRouteNetId = undefined, this.state.unroutedRoutes = [], this.state.candidateQueue.clear(), this.resetCandidateBestCosts(), this.state.goalPortId = -1);
  }
  getStartingNextRegionId(e51, t2) {
    const n2 = this.routePlans[e51]?.forcedStartRegionId;
    return n2 !== undefined ? n2 : super.getStartingNextRegionId(e51, t2);
  }
  resetRoutingStateForRerip() {
    if (!this.fixedSnapshot)
      return super.resetRoutingStateForRerip(), this.state.unroutedRoutes = qZ([...this.activeRouteIds], this.state.ripCount), void this.applyFixedSegments();
    nQ(this, this.fixedSnapshot), this.state.currentRouteId = undefined, this.state.currentRouteNetId = undefined, this.state.unroutedRoutes = qZ([...this.activeRouteIds], this.state.ripCount), this.state.candidateQueue.clear(), this.resetCandidateBestCosts(), this.state.goalPortId = -1;
  }
  onAllRoutesRouted() {
    const { state: e51 } = this, t2 = Math.min(this.MAX_RIPS, this.RIP_THRESHOLD_RAMP_ATTEMPTS), n2 = t2 <= 0 ? 1 : Math.min(1, e51.ripCount / t2), o3 = this.RIP_THRESHOLD_START + (this.RIP_THRESHOLD_END - this.RIP_THRESHOLD_START) * n2, i3 = [], r3 = new Float64Array(this.mutableRegionIds.length);
    let s2 = 0, a3 = 0;
    for (let t3 = 0;t3 < this.mutableRegionIds.length; t3++) {
      const n3 = this.mutableRegionIds[t3], c4 = e51.regionIntersectionCaches[n3]?.existingRegionCost ?? 0;
      r3[t3] = c4, s2 = Math.max(s2, c4), a3 += c4, c4 > o3 && i3.push(n3);
    }
    const c3 = Math.max(this.immutableRegionSummary.maxRegionCost, s2), l3 = this.immutableRegionSummary.totalRegionCost + a3;
    this.captureBestState({ maxRegionCost: c3, totalRegionCost: l3 });
    const h2 = this.bestSummary ?? { maxRegionCost: c3, totalRegionCost: l3 };
    if (h2.maxRegionCost < this.previousBestMaxRegionCost - Number.EPSILON ? (this.previousBestMaxRegionCost = h2.maxRegionCost, this.ripsSinceBestMaxRegionCostImprovement = 0) : this.ripsSinceBestMaxRegionCostImprovement += 1, this.baselineBeatRipCount === undefined && h2.maxRegionCost < this.baselineSummary.maxRegionCost - Number.EPSILON && (this.baselineBeatRipCount = e51.ripCount), this.stats = { ...this.stats, activeRouteCount: this.activeRouteIds.length, currentRipThreshold: o3, hotRegionCount: i3.length, maxRegionCost: c3, totalRegionCost: l3, bestMaxRegionCost: h2.maxRegionCost, bestTotalRegionCost: h2.totalRegionCost, ripCount: e51.ripCount }, i3.length === 0 || e51.ripCount >= t2 || this.ripsSinceBestMaxRegionCostImprovement >= this.MAX_RIPS_WITHOUT_MAX_REGION_COST_IMPROVEMENT || this.baselineBeatRipCount !== undefined && e51.ripCount - this.baselineBeatRipCount >= this.EXTRA_RIPS_AFTER_BEATING_BASELINE_MAX_REGION_COST)
      return this.restoreBestState(), void (this.solved = true);
    for (let t3 = 0;t3 < this.mutableRegionIds.length; t3++) {
      const n3 = this.mutableRegionIds[t3];
      e51.regionCongestionCost[n3] += r3[t3] * this.RIP_CONGESTION_REGION_COST_FACTOR;
    }
    e51.ripCount += 1, this.resetRoutingStateForRerip(), this.stats = { ...this.stats, ripCount: e51.ripCount, reripRegionCount: i3.length };
  }
  onOutOfCandidates() {
    const { state: e51 } = this;
    for (const t2 of this.mutableRegionIds) {
      const n2 = e51.regionIntersectionCaches[t2]?.existingRegionCost ?? 0;
      e51.regionCongestionCost[t2] += n2 * this.RIP_CONGESTION_REGION_COST_FACTOR;
    }
    e51.ripCount += 1, this.resetRoutingStateForRerip(), this.stats = { ...this.stats, ripCount: e51.ripCount, reripReason: "out_of_candidates" };
  }
  tryFinalAcceptance() {
    if (this.bestSnapshot)
      return this.restoreBestState(), void (this.solved = true);
    this.fixedSnapshot && nQ(this, this.fixedSnapshot), this.state.currentRouteId = undefined, this.state.currentRouteNetId = undefined, this.state.unroutedRoutes = [...this.activeRouteIds], this.state.candidateQueue.clear(), this.resetCandidateBestCosts(), this.state.goalPortId = -1, this.stats = { ...this.stats, acceptedFixedSectionStateOnTimeout: true }, this.solved = true;
  }
  visualize() {
    return Uq(this, { highlightSectionMask: true, showInitialRouteHints: false, showOnlySectionPortsOnIdle: true });
  }
};
var dQ = class extends BaseSolver {
  constructor(e51, t2, n2, o3) {
    super(), this.topology = e51, this.problem = t2, this.initialSolution = n2, QJ(this, o3), this.baselineSolver = ((e52, t3, n3, o4) => {
      const i3 = Array.from({ length: e52.regionCount }, () => []);
      for (let o5 = 0;o5 < t3.routeCount; o5++) {
        const { orderedPortIds: r3, orderedRegionIds: s2 } = sQ(e52, t3, n3, o5);
        for (let e53 = 1;e53 < r3.length; e53++) {
          const t4 = r3[e53 - 1], n4 = r3[e53];
          i3[s2[e53 - 1]].push([o5, t4, n4]);
        }
      }
      return aQ(e52, t3, i3, o4);
    })(e51, t2, n2, Kq(this)), this.baselineSummary = oQ(this.baselineSolver.state.regionIntersectionCaches), this.sectionRegionIds = ((e52, t3) => {
      const n3 = new Set;
      for (let o4 = 0;o4 < t3.portSectionMask.length; o4++)
        if (t3.portSectionMask[o4] === 1)
          for (const t4 of e52.incidentPortRegion[o4] ?? [])
            n3.add(t4);
      return [...n3];
    })(e51, t2), this.sectionBaselineSummary = ((e52, t3) => {
      let n3 = 0, o4 = 0;
      for (const i3 of t3) {
        const t4 = e52[i3]?.existingRegionCost ?? 0;
        n3 = Math.max(n3, t4), o4 += t4;
      }
      return { maxRegionCost: n3, totalRegionCost: o4 };
    })(this.baselineSolver.state.regionIntersectionCaches, this.sectionRegionIds), this.outsideSectionBaselineSummary = ((e52, t3) => {
      const n3 = new Set(t3);
      let o4 = 0, i3 = 0;
      for (let t4 = 0;t4 < e52.length; t4++) {
        if (n3.has(t4))
          continue;
        const r3 = e52[t4]?.existingRegionCost ?? 0;
        o4 = Math.max(o4, r3), i3 += r3;
      }
      return { maxRegionCost: o4, totalRegionCost: i3 };
    })(this.baselineSolver.state.regionIntersectionCaches, this.sectionRegionIds), this.applySectionRipPolicy();
  }
  baselineSolver;
  baselineSummary;
  sectionBaselineSummary;
  outsideSectionBaselineSummary;
  sectionRegionIds;
  optimizedSolver;
  sectionSolver;
  activeRouteIds = [];
  DISTANCE_TO_COST = 0.05;
  minViaPadDiameter = jZ;
  VERBOSE = false;
  RIP_THRESHOLD_START = 0.05;
  RIP_THRESHOLD_END = 0.8;
  RIP_THRESHOLD_RAMP_ATTEMPTS = 50;
  MAX_RIPS = Number.POSITIVE_INFINITY;
  MAX_RIPS_WITHOUT_MAX_REGION_COST_IMPROVEMENT = 10;
  EXTRA_RIPS_AFTER_BEATING_BASELINE_MAX_REGION_COST = 10;
  RIP_CONGESTION_REGION_COST_FACTOR = 0.1;
  MAX_ITERATIONS = 1e6;
  STATIC_REACHABILITY_PRECHECK = false;
  STATIC_REACHABILITY_PRECHECK_MAX_HOPS = 16;
  ACCEPT_BEST_SOLUTION_ON_TIMEOUT = true;
  GREEDY_FINAL_ROUTE_ITERS = 4;
  applySectionRipPolicy() {
    this.RIP_THRESHOLD_START = 0.05, this.RIP_THRESHOLD_END = Math.max(this.RIP_THRESHOLD_START, this.sectionBaselineSummary.maxRegionCost), this.MAX_RIPS = Math.min(this.MAX_RIPS, 20);
  }
  _setup() {
    this.applySectionRipPolicy();
    const { sectionProblem: e51, routePlans: t2, activeRouteIds: n2 } = cQ(this.topology, this.problem, this.initialSolution);
    if (this.activeRouteIds = n2, n2.length === 0)
      return this.optimizedSolver = this.baselineSolver, this.stats = { ...this.stats, activeRouteCount: 0, initialMaxRegionCost: this.baselineSummary.maxRegionCost, finalMaxRegionCost: this.baselineSummary.maxRegionCost, optimized: false }, void (this.solved = true);
    var o3;
    this.sectionSolver = new hQ(this.topology, e51, t2, n2, this.sectionRegionIds, this.outsideSectionBaselineSummary, this.baselineSummary, { ...Kq(o3 = this), MAX_RIPS: o3.MAX_RIPS, MAX_RIPS_WITHOUT_MAX_REGION_COST_IMPROVEMENT: o3.MAX_RIPS_WITHOUT_MAX_REGION_COST_IMPROVEMENT, EXTRA_RIPS_AFTER_BEATING_BASELINE_MAX_REGION_COST: o3.EXTRA_RIPS_AFTER_BEATING_BASELINE_MAX_REGION_COST }), this.activeSubSolver = this.sectionSolver, this.stats = { ...this.stats, sectionBaselineMaxRegionCost: this.sectionBaselineSummary.maxRegionCost, sectionBaselineTotalRegionCost: this.sectionBaselineSummary.totalRegionCost, effectiveRipThresholdStart: this.RIP_THRESHOLD_START, effectiveRipThresholdEnd: this.RIP_THRESHOLD_END, effectiveMaxRips: this.MAX_RIPS };
  }
  _step() {
    if (!this.sectionSolver)
      return void (this.solved = true);
    if (this.sectionSolver.step(), this.stats = { ...this.stats, ...this.sectionSolver.stats, activeRouteCount: this.activeRouteIds.length }, this.sectionSolver.failed)
      return this.optimizedSolver = this.baselineSolver, this.stats = { ...this.stats, initialMaxRegionCost: this.baselineSummary.maxRegionCost, initialTotalRegionCost: this.baselineSummary.totalRegionCost, finalMaxRegionCost: this.baselineSummary.maxRegionCost, finalTotalRegionCost: this.baselineSummary.totalRegionCost, optimized: false, sectionSearchFailedFallbackToBaseline: true, sectionSearchError: this.sectionSolver.error }, void (this.solved = true);
    if (!this.sectionSolver.solved)
      return;
    const e51 = aQ(this.topology, this.problem, KJ(this.sectionSolver.state.regionSegments), Kq(this)), t2 = oQ(e51.state.regionIntersectionCaches), n2 = iQ(t2, this.baselineSummary) < 0;
    this.optimizedSolver = n2 ? e51 : this.baselineSolver;
    const o3 = n2 ? t2 : this.baselineSummary;
    this.stats = { ...this.stats, initialMaxRegionCost: this.baselineSummary.maxRegionCost, initialTotalRegionCost: this.baselineSummary.totalRegionCost, candidateMaxRegionCost: t2.maxRegionCost, candidateTotalRegionCost: t2.totalRegionCost, finalMaxRegionCost: o3.maxRegionCost, finalTotalRegionCost: o3.totalRegionCost, optimized: n2 }, this.solved = true;
  }
  tryFinalAcceptance() {
    this.optimizedSolver = this.baselineSolver, this.stats = { ...this.stats, initialMaxRegionCost: this.baselineSummary.maxRegionCost, initialTotalRegionCost: this.baselineSummary.totalRegionCost, finalMaxRegionCost: this.baselineSummary.maxRegionCost, finalTotalRegionCost: this.baselineSummary.totalRegionCost, optimized: false, sectionSolverTimeoutFallbackToBaseline: true }, this.solved = true, this.failed = false, this.error = null;
  }
  getSolvedSolver() {
    if (!this.solved || this.failed || !this.optimizedSolver)
      throw new Error("TinyHyperGraphSectionSolver does not have a solved output yet");
    return this.optimizedSolver;
  }
  visualize() {
    return this.optimizedSolver ? Uq(this.optimizedSolver, { highlightSectionMask: true }) : this.sectionSolver ? this.sectionSolver.visualize() : Uq(this.baselineSolver, { highlightSectionMask: true, showInitialRouteHints: false, showOnlySectionPortsOnIdle: true });
  }
  getOutput() {
    return this.getSolvedSolver().getOutput();
  }
};
var pQ = ["self-touch", "onehop-all", "onehop-touch", "twohop-all", "twohop-touch"];
var mQ = { "self-all": 0, "self-touch": 0, "onehop-all": 1, "onehop-touch": 1, "twohop-all": 2, "twohop-touch": 2, "threehop-all": 3, "threehop-touch": 3, "fourhop-all": 4, "fourhop-touch": 4 };
var gQ = (e51, t2) => {
  const n2 = new Set(t2);
  for (const o3 of t2)
    for (const t3 of e51.regionIncidentPorts[o3] ?? [])
      for (const o4 of e51.incidentPortRegion[t3] ?? [])
        n2.add(o4);
  return [...n2];
};
var fQ = (e51, t2, n2) => {
  let o3 = [...new Set(t2)];
  for (let t3 = 0;t3 < n2; t3 += 1)
    o3 = gQ(e51, o3);
  return o3;
};
var _Q = (e51, t2, n2) => t2.flatMap((t3) => n2.map((n3) => ((e52, t4, n4) => ({ label: `hot-${t4}-${n4}`, family: n4, regionIds: fQ(e52, [t4], mQ[n4]), portSelectionRule: n4.endsWith("-all") ? "all-incident-regions-selected" : "touches-selected-region" }))(e51, t3, n3)));
var yQ = { RIP_THRESHOLD_RAMP_ATTEMPTS: 5 };
var bQ = { DISTANCE_TO_COST: 0.05, RIP_THRESHOLD_RAMP_ATTEMPTS: 16, RIP_CONGESTION_REGION_COST_FACTOR: 0.1, MAX_ITERATIONS: 50000, MAX_RIPS_WITHOUT_MAX_REGION_COST_IMPROVEMENT: 6, EXTRA_RIPS_AFTER_BEATING_BASELINE_MAX_REGION_COST: Number.POSITIVE_INFINITY };
var xQ = (e51) => e51.state.regionIntersectionCaches.reduce((e52, t2) => Math.max(e52, t2.existingRegionCost), 0);
var vQ = (e51, t2) => {
  const n2 = OJ(e51), o3 = new dQ(n2.topology, n2.problem, n2.solution, t2);
  return xQ(o3.baselineSolver);
};
var IQ = (e51, t2, n2) => {
  const o3 = new Set(t2);
  return Int8Array.from({ length: e51.portCount }, (t3, i3) => {
    const r3 = e51.incidentPortRegion[i3] ?? [];
    return n2 === "touches-selected-region" ? r3.some((e52) => o3.has(e52)) ? 1 : 0 : r3.length > 0 && r3.every((e52) => o3.has(e52)) ? 1 : 0;
  });
};
var SQ = (e51, t2) => ({ routeCount: e51.routeCount, portSectionMask: t2, routeMetadata: e51.routeMetadata, routeStartPort: new Int32Array(e51.routeStartPort), routeEndPort: new Int32Array(e51.routeEndPort), routeNet: new Int32Array(e51.routeNet), regionNetId: new Int32Array(e51.regionNetId), portPenalty: e51.portPenalty === undefined ? undefined : new Float64Array(e51.portPenalty) });
var CQ = (e51, t2, n2, o3, i3, r3) => {
  const s2 = performance.now(), a3 = performance.now(), c3 = new dQ(t2, n2, o3, r3), l3 = xQ(c3.baselineSolver), h2 = performance.now() - a3;
  let d2, u2, p3 = l3, m2 = new Int8Array(t2.portCount), g2 = 0, f2 = 0, _2 = 0, y2 = 0, b2 = 0, x2 = 0, v2 = 0;
  const I2 = new Set, S2 = i3?.maxHotRegions ?? r3.MAX_HOT_REGIONS ?? 2;
  for (const s3 of ((e52, t3, n3, o4) => {
    const i4 = e52.state.regionIntersectionCaches.map((e53, t4) => ({ regionId: t4, regionCost: e53.existingRegionCost })).filter(({ regionCost: e53 }) => e53 > 0).sort((e53, t4) => t4.regionCost - e53.regionCost).slice(0, n3).map(({ regionId: e53 }) => e53);
    return _Q(t3, i4, o4);
  })(e51, t2, S2, i3?.candidateFamilies ?? [...pQ])) {
    const e52 = SQ(n2, IQ(t2, s3.regionIds, s3.portSelectionRule));
    g2 += 1;
    const i4 = e52.portSectionMask.join(",");
    if (I2.has(i4))
      _2 += 1;
    else {
      I2.add(i4);
      try {
        const n3 = performance.now(), i5 = lQ(t2, e52, o3);
        if (y2 += performance.now() - n3, i5.length === 0)
          continue;
        f2 += 1;
        const a4 = performance.now(), c4 = new dQ(t2, e52, o3, r3);
        b2 += performance.now() - a4;
        const l4 = performance.now();
        if (c4.solve(), x2 += performance.now() - l4, c4.failed || !c4.solved)
          continue;
        if (Number(c4.stats.finalMaxRegionCost ?? xQ(c4.getSolvedSolver())) < p3 - 0.000000001) {
          const t3 = performance.now(), n4 = vQ(c4.getOutput(), r3);
          v2 += performance.now() - t3, n4 < p3 - 0.000000001 && (p3 = n4, m2 = new Int8Array(e52.portSectionMask), d2 = s3.label, u2 = s3.family);
        }
      } catch {}
    }
  }
  return { portSectionMask: m2, baselineMaxRegionCost: l3, finalMaxRegionCost: p3, generatedCandidateCount: g2, candidateCount: f2, duplicateCandidateCount: _2, totalMs: performance.now() - s2, baselineEvaluationMs: h2, candidateEligibilityMs: y2, candidateInitMs: b2, candidateSolveMs: x2, candidateReplayScoreMs: v2, winningCandidateLabel: d2, winningCandidateFamily: u2 };
};
var PQ = class extends BasePipelineSolver {
  initialVisualizationSolver;
  selectedSectionMask;
  selectedSectionCandidateLabel;
  selectedSectionCandidateFamily;
  constructor(e51) {
    super(e51), this.MAX_ITERATIONS = 200000;
  }
  loadHyperGraph(e51) {
    return OJ(e51);
  }
  getSolveGraphOptions() {
    return { ...yQ, ...this.inputProblem.minViaPadDiameter === undefined ? {} : { minViaPadDiameter: this.inputProblem.minViaPadDiameter }, ...this.inputProblem.solveGraphOptions };
  }
  getSectionSolverOptions() {
    return { ...bQ, ...this.inputProblem.minViaPadDiameter === undefined ? {} : { minViaPadDiameter: this.inputProblem.minViaPadDiameter }, ...this.inputProblem.sectionSolverOptions };
  }
  pipelineDef = [{ solverName: "solveGraph", solverClass: tJ, getConstructorParams: (e51) => {
    const { topology: t2, problem: n2 } = e51.loadHyperGraph(e51.inputProblem.serializedHyperGraph);
    return [t2, n2, e51.getSolveGraphOptions()];
  } }, { solverName: "optimizeSection", solverClass: dQ, getConstructorParams: (e51) => e51.getSectionStageParams() }];
  getSectionStageParams() {
    const e51 = this.getStageOutput("solveGraph");
    if (!e51)
      throw new Error("solveGraph did not produce a solved serialized hypergraph");
    const t2 = this.getSolver("solveGraph");
    if (!t2)
      throw new Error("solveGraph solver is unavailable");
    const n2 = this.getSectionSolverOptions(), { topology: o3, problem: i3, solution: r3 } = this.loadHyperGraph(e51), s2 = this.inputProblem.createSectionMask ? this.inputProblem.createSectionMask({ serializedHyperGraph: this.inputProblem.serializedHyperGraph, solvedSerializedHyperGraph: e51, solvedSolver: t2, topology: o3, problem: i3, solution: r3 }) : (() => {
      const e52 = CQ(t2, o3, i3, r3, this.inputProblem.sectionSearchConfig, n2);
      return this.selectedSectionCandidateLabel = e52.winningCandidateLabel, this.selectedSectionCandidateFamily = e52.winningCandidateFamily, this.stats = { ...this.stats, sectionSearchGeneratedCandidateCount: e52.generatedCandidateCount, sectionSearchCandidateCount: e52.candidateCount, sectionSearchDuplicateCandidateCount: e52.duplicateCandidateCount, sectionSearchBaselineMaxRegionCost: e52.baselineMaxRegionCost, sectionSearchFinalMaxRegionCost: e52.finalMaxRegionCost, sectionSearchDelta: e52.baselineMaxRegionCost - e52.finalMaxRegionCost, selectedSectionCandidateLabel: e52.winningCandidateLabel ?? null, selectedSectionCandidateFamily: e52.winningCandidateFamily ?? null, sectionSearchMs: e52.totalMs, sectionSearchBaselineEvaluationMs: e52.baselineEvaluationMs, sectionSearchCandidateEligibilityMs: e52.candidateEligibilityMs, sectionSearchCandidateInitMs: e52.candidateInitMs, sectionSearchCandidateSolveMs: e52.candidateSolveMs, sectionSearchCandidateReplayScoreMs: e52.candidateReplayScoreMs }, e52.portSectionMask;
    })();
    return this.selectedSectionMask = new Int8Array(s2), i3.portSectionMask = new Int8Array(s2), this.stats = { ...this.stats, sectionMaskPortCount: [...s2].filter((e52) => e52 === 1).length }, [o3, i3, r3, n2];
  }
  getInitialVisualizationSolver() {
    if (!this.initialVisualizationSolver) {
      const { topology: e51, problem: t2 } = this.loadHyperGraph(this.inputProblem.serializedHyperGraph);
      this.initialVisualizationSolver = new tJ(e51, t2, this.getSolveGraphOptions());
    }
    return this.initialVisualizationSolver;
  }
  initialVisualize() {
    return this.getInitialVisualizationSolver().visualize();
  }
  visualize() {
    return this.iterations === 0 ? this.initialVisualize() ?? super.visualize() : super.visualize();
  }
  getOutput() {
    return this.getStageOutput("optimizeSection") ?? this.getStageOutput("solveGraph") ?? null;
  }
  tryFinalAcceptance() {
    this.getStageOutput("solveGraph") && (this.stats = { ...this.stats, acceptedSolveGraphOutputOnSectionPipelineTimeout: true }, this.activeSubSolver = undefined, this.solved = true, this.failed = false, this.error = null);
  }
};
new Int32Array(0);
var wQ = (e51) => {
  if (typeof e51 != "object" || e51 === null)
    return false;
  const t2 = e51, n2 = t2.preloadedTraceSection;
  return typeof t2.connectionId == "string" && typeof n2?.traceId == "string" && typeof n2.startRoutePosition == "number" && typeof n2.endRoutePosition == "number" && typeof n2.startPoint?.x == "number" && typeof n2.startPoint.y == "number" && typeof n2.startPoint.z == "number" && typeof n2.endPoint?.x == "number" && typeof n2.endPoint.y == "number" && typeof n2.endPoint.z == "number";
};
var NQ = (e51, t2) => `__tscircuit_preloaded_trace__:${JSON.stringify([e51, t2])}`;
var RQ = (e51) => [e51.region1Id, e51.region2Id];
var TQ = (e51, t2) => {
  const n2 = new Set(RQ(t2));
  return RQ(e51).filter((e52) => n2.has(e52));
};
var EQ = (e51, t2, n2) => {
  const o3 = e51[t2], i3 = e51[t2 + 1], r3 = TQ(o3.port, i3.port);
  if (r3.length === 0)
    return;
  if (r3.length === 1)
    return r3[0];
  const s2 = e51[t2 + 2];
  if (s2) {
    const e52 = new Set(TQ(i3.port, s2.port)), t3 = r3.find((t4) => e52.has(t4));
    if (t3)
      return t3;
  }
  return n2 && r3.includes(n2) ? n2 : [...r3].sort()[0];
};
var AQ = (e51, t2) => RQ(e51).find((e52) => e52 !== t2) ?? t2;
var OQ = (e51) => {
  const t2 = new Set((e51.connections ?? []).filter(wQ).map((e52) => e52.connectionId)), n2 = e51.ports.filter((e52) => (e52.d?._preloadedTracePortAssignments?.length ?? 0) > 0).length, o3 = e51.regions.reduce((e52, n3) => e52 + (n3.assignments ?? []).filter((e53) => t2.has(e53.connectionId)).length, 0);
  return { preloadedTraceCount: t2.size, preloadedPortCount: n2, preloadedAssignmentCount: o3 };
};
var kQ = (e51) => typeof e51 == "object" && e51 !== null ? e51 : {};
var DQ = (e51) => typeof e51 == "object" && e51 !== null ? e51 : {};
var LQ = 0.000001;
var zQ = { DISTANCE_TO_COST: 0.05, RIP_THRESHOLD_START: 0.05, RIP_THRESHOLD_END: 0.8, RIP_CONGESTION_REGION_COST_FACTOR: 0.1, ACCEPT_BEST_SOLUTION_ON_TIMEOUT: true, GREEDY_FINAL_ROUTE_ITERS: 4, PARTIAL_RIP_MIN_ROUTE_COUNT: 100, PARTIAL_RIP_MAX_ROUTE_COUNT: 350, PARTIAL_RIP_MAX_ATTEMPTS: 7, PARTIAL_RIP_WARMUP_FULL_RIP_ATTEMPTS: 1, PARTIAL_RIP_COMPLEXITY_SELECTION_MIN_ROUTE_COUNT: 100, PARTIAL_RIP_TARGET_MAX_COST_IMPROVEMENT_RATIO: 0.02, PARTIAL_RIP_MAX_REGION_COST_GROWTH_RATIO: 0.05, PARTIAL_RIP_MAX_TOTAL_COST_GROWTH_RATIO: 0.1 };
var BQ = { DISTANCE_TO_COST: 0.05, RIP_THRESHOLD_START: 0.05, RIP_THRESHOLD_END: 0.8, RIP_CONGESTION_REGION_COST_FACTOR: 0.1, ACCEPT_BEST_SOLUTION_ON_TIMEOUT: true, GREEDY_FINAL_ROUTE_ITERS: 4, MAX_RIPS_WITHOUT_MAX_REGION_COST_IMPROVEMENT: 6, EXTRA_RIPS_AFTER_BEATING_BASELINE_MAX_REGION_COST: Number.POSITIVE_INFINITY };
var FQ = (e51) => Math.max(e51, 0.01);
var jQ = (e51) => Number.isFinite(e51) ? { minViaPadDiameter: e51 } : {};
var $Q = ({ effort: e51, portCount: t2, minViaPadDiameter: n2 }) => {
  const o3 = FQ(e51), i3 = Math.max(1, Math.floor(t2 / 125000));
  return { ...zQ, ...jQ(n2), OWNED_REGIONAL_HOP_FRONTIER: true, USE_SPARSE_CANDIDATE_STORAGE: false, RIP_THRESHOLD_RAMP_ATTEMPTS: Math.ceil(10 * o3), MAX_ITERATIONS: Math.ceil(2000000 * o3 * i3) };
};
var YQ = (e51, t2) => {
  const n2 = FQ(e51);
  return { ...BQ, ...jQ(t2), USE_SPARSE_CANDIDATE_STORAGE: false, RIP_THRESHOLD_RAMP_ATTEMPTS: Math.ceil(16 * n2), MAX_ITERATIONS: Math.ceil(1e6 * n2) };
};
var XQ = (e51) => (e51.solveGraphOptions?.MAX_ITERATIONS ?? 1e6) + (e51.sectionSolverOptions?.MAX_ITERATIONS ?? 1e6) + 1e6;
var HQ = (e51) => e51.mutuallyConnectedNetworkId;
var VQ = (e51, t2) => e51.simpleRouteConnection?.pointsToConnect[t2];
var WQ = (e51) => {
  const t2 = VQ(e51.routeMetadata, e51.endpointIndex);
  if (!t2)
    return e51.fallbackZ;
  const n2 = So(t2).map((t3) => mo(t3, e51.layerCount));
  return e51.regionAvailableZ.find((e52) => n2.includes(e52)) ?? e51.fallbackZ;
};
var GQ = (e51, t2) => {
  const n2 = e51.d, o3 = n2.bounds;
  return { capacityMeshNodeId: e51.d.capacityMeshNodeId, center: { x: e51.d.center.x, y: e51.d.center.y }, width: e51.d.width, height: e51.d.height, availableZ: [...e51.d.availableZ], ...o3 ? { bounds: { minX: o3.minX, maxX: o3.maxX, minY: o3.minY, maxY: o3.maxY } } : {}, _containsObstacle: e51.d._containsObstacle, _containsTarget: e51.d._containsTarget, _offBoardConnectionId: e51.d._offBoardConnectionId, _offBoardConnectedCapacityMeshNodeIds: e51.d._offBoardConnectedCapacityMeshNodeIds === undefined ? undefined : [...e51.d._offBoardConnectedCapacityMeshNodeIds], _qfpRegionType: n2._qfpRegionType, _isNarrowQfpPadGap: n2._isNarrowQfpPadGap, ...t2 !== undefined ? { netId: t2 } : {} };
};
var UQ = (e51) => {
  const t2 = e51.d;
  return { portId: e51.d.portId, x: e51.d.x, y: e51.d.y, z: e51.d.z, prevPortPointId: t2.prevPortPointId, nextPortPointId: t2.nextPortPointId, distToCentermostPortOnZ: e51.d.distToCentermostPortOnZ, tinyHypergraphPortPenalty: e51.d.tinyHypergraphPortPenalty, cramped: e51.d.cramped, _preloadedFixedNetIds: e51.d._preloadedFixedNetIds, _preloadedTracePortAssignments: e51.d._preloadedTracePortAssignments };
};
var ZQ = (e51) => {
  const t2 = function() {
    const e52 = new Map;
    return (t3) => {
      const n3 = t3.mutuallyConnectedNetworkId;
      let o4 = e52.get(n3);
      return o4 === undefined && (o4 = e52.size, e52.set(n3, o4)), o4;
    };
  }(), n2 = function(e52) {
    const t3 = new Map, n3 = new Set, o4 = new Map;
    for (const i5 of e52.params.connections) {
      const r4 = i5.mutuallyConnectedNetworkId, s3 = e52.getNetIndex({ connectionId: i5.connectionId, mutuallyConnectedNetworkId: r4 });
      for (const e53 of [i5.connectionId, r4])
        o4.set(e53, s3);
      for (const o5 of i5.simpleRouteConnection.pointsToConnect) {
        const i6 = GG({ point: o5, layerCount: e52.params.layerCount });
        for (const r5 of e52.params.graph.regions) {
          if (!UG({ point: o5, region: r5, layerCount: e52.params.layerCount, pointZLayers: i6 }))
            continue;
          if (o5.pcb_port_id === undefined && r5.d._containsTarget !== true) {
            n3.add(r5.regionId);
            continue;
          }
          let a4 = t3.get(r5.regionId);
          a4 || (a4 = new Set, t3.set(r5.regionId, a4)), a4.add(s3);
        }
      }
    }
    for (const n4 of e52.params.graph.regions)
      for (const e53 of n4.d._connectedTo ?? []) {
        const i5 = o4.get(e53);
        if (i5 === undefined)
          continue;
        let r4 = t3.get(n4.regionId);
        r4 || (r4 = new Set, t3.set(n4.regionId, r4)), r4.add(i5);
      }
    const i4 = new Map;
    for (const e53 of n3)
      i4.set(e53, -1);
    for (const [e53, n4] of t3)
      n4.size === 1 && i4.set(e53, [...n4][0]);
    return i4;
  }({ params: e51, getNetIndex: t2 }), o3 = e51.graph.regions.map((e52) => ({ regionId: e52.regionId, pointIds: e52.ports.map((e53) => e53.d.portId), d: GQ(e52, n2.get(e52.regionId)) })), i3 = new Map;
  for (const e52 of o3)
    i3.has(e52.regionId) || i3.set(e52.regionId, e52);
  const r3 = e51.graph.ports.map((e52) => ({ portId: e52.d.portId, region1Id: e52.region1.regionId, region2Id: e52.region2.regionId, d: UQ(e52) })), s2 = e51.connections.map((e52) => ({ connectionId: e52.connectionId, mutuallyConnectedNetworkId: e52.mutuallyConnectedNetworkId, startRegionId: e52.startRegion.regionId, endRegionId: e52.endRegion.regionId, simpleRouteConnection: e52.simpleRouteConnection })), a3 = [];
  for (const n3 of e51.connections) {
    const s3 = { connectionId: n3.connectionId, mutuallyConnectedNetworkId: n3.mutuallyConnectedNetworkId, simpleRouteConnection: n3.simpleRouteConnection }, c4 = t2(s3), l3 = VQ(s3, 0), h2 = VQ(s3, 1), d2 = n3.startRegion.d.availableZ[0] ?? 0, u2 = n3.endRegion.d.availableZ[0] ?? 0, p3 = WQ({ routeMetadata: s3, endpointIndex: 0, fallbackZ: d2, regionAvailableZ: n3.startRegion.d.availableZ, layerCount: e51.layerCount }), m2 = WQ({ routeMetadata: s3, endpointIndex: 1, fallbackZ: u2, regionAvailableZ: n3.endRegion.d.availableZ, layerCount: e51.layerCount }), g2 = `tiny-terminal:start-region:${n3.connectionId}`, f2 = `tiny-terminal:end-region:${n3.connectionId}`, _2 = `tiny-terminal:start-port:${n3.connectionId}`, y2 = `tiny-terminal:end-port:${n3.connectionId}`;
    o3.push({ regionId: g2, pointIds: [_2], d: { capacityMeshNodeId: g2, center: { x: l3?.x ?? n3.startRegion.d.center.x, y: l3?.y ?? n3.startRegion.d.center.y }, width: LQ, height: LQ, availableZ: [p3], _containsTarget: true, _tinyTerminal: true, _tinyTerminalNetId: n3.mutuallyConnectedNetworkId, netId: c4 } }), o3.push({ regionId: f2, pointIds: [y2], d: { capacityMeshNodeId: f2, center: { x: h2?.x ?? n3.endRegion.d.center.x, y: h2?.y ?? n3.endRegion.d.center.y }, width: LQ, height: LQ, availableZ: [m2], _containsTarget: true, _tinyTerminal: true, _tinyTerminalNetId: n3.mutuallyConnectedNetworkId, netId: c4 } }), r3.push({ portId: _2, region1Id: n3.startRegion.regionId, region2Id: g2, d: { portId: _2, x: l3?.x ?? n3.startRegion.d.center.x, y: l3?.y ?? n3.startRegion.d.center.y, z: p3, distToCentermostPortOnZ: 0, _tinyTerminal: true, ...e51.preserveTerminalPcbPortIds && l3?.pcb_port_id ? { pcb_port_id: l3.pcb_port_id } : {} } }), r3.push({ portId: y2, region1Id: n3.endRegion.regionId, region2Id: f2, d: { portId: y2, x: h2?.x ?? n3.endRegion.d.center.x, y: h2?.y ?? n3.endRegion.d.center.y, z: m2, distToCentermostPortOnZ: 0, _tinyTerminal: true, ...e51.preserveTerminalPcbPortIds && h2?.pcb_port_id ? { pcb_port_id: h2.pcb_port_id } : {} } });
    const b2 = i3.get(n3.startRegion.regionId), x2 = i3.get(n3.endRegion.regionId);
    b2?.pointIds.push(_2), x2?.pointIds.push(y2), a3.push({ connection: { connectionId: n3.connectionId }, path: [{ portId: _2 }, { portId: y2 }] });
  }
  const c3 = { regions: o3, ports: r3, connections: s2, solvedRoutes: a3 };
  return ((e52) => {
    const t3 = new Map, n3 = new Map, o4 = new Set((e52.connections ?? []).flatMap((e53) => [e53.startRegionId, e53.endRegionId])), i4 = new Set(e52.regions.filter((e53) => {
      const t4 = typeof e53.d?.netId == "number" ? e53.d.netId : typeof e53.d?.NetId == "number" ? e53.d.NetId : undefined;
      return e53.d?._containsObstacle === true && (t4 === undefined || t4 === -1) && !o4.has(e53.regionId);
    }).map((e53) => e53.regionId));
    let r4 = 0;
    for (const o5 of e52.ports) {
      const e53 = o5.d, s4 = e53?._preloadedTracePortAssignments ?? [];
      if (s4.length > 0 && r4++, !i4.has(o5.region1Id) && !i4.has(o5.region2Id))
        for (const e54 of s4) {
          const i5 = n3.get(e54.traceId);
          if (i5 !== undefined && i5 !== e54.fixedNetId)
            throw new Error(`Preloaded trace "${e54.traceId}" maps to multiple canonical nets`);
          n3.set(e54.traceId, e54.fixedNetId);
          const r5 = t3.get(e54.traceId) ?? [];
          r5.push({ port: o5, assignment: e54 }), t3.set(e54.traceId, r5);
        }
    }
    const s3 = new Map(e52.regions.map((e53) => [e53.regionId, e53])), a4 = e52.connections ??= [], c4 = e52.solvedRoutes ??= [];
    let l3 = 0, h2 = 0;
    for (const [e53, o5] of t3) {
      o5.sort((e54, t5) => e54.assignment.routePosition - t5.assignment.routePosition || e54.assignment.z - t5.assignment.z || e54.port.portId.localeCompare(t5.port.portId));
      const t4 = o5.filter(({ port: e54 }, t5) => t5 === 0 || e54.portId !== o5[t5 - 1].port.portId);
      if (t4.length < 2)
        continue;
      const i5 = [];
      let r5;
      for (let e54 = 0;e54 < t4.length - 1; e54++) {
        const n4 = t4[e54], o6 = t4[e54 + 1];
        if (n4.assignment.z === o6.assignment.z && Math.abs(n4.assignment.routePosition - o6.assignment.routePosition) <= 0.000001) {
          r5 = undefined;
          continue;
        }
        const s4 = EQ(t4, e54, r5);
        s4 ? (i5.push({ regionId: s4, from: n4, to: o6 }), r5 = s4) : r5 = undefined;
      }
      const d2 = [];
      for (const e54 of i5) {
        const t5 = d2.at(-1);
        t5 && t5.at(-1).to.port.portId === e54.from.port.portId ? t5.push(e54) : d2.push([e54]);
      }
      for (const [t5, o6] of d2.entries()) {
        const i6 = NQ(e53, t5);
        for (const t6 of o6) {
          const n4 = s3.get(t6.regionId);
          if (!n4)
            throw new Error(`Preloaded trace "${e53}" references missing region "${t6.regionId}"`);
          n4.assignments = [...n4.assignments ?? [], { regionPort1Id: t6.from.port.portId, regionPort2Id: t6.to.port.portId, connectionId: i6 }], h2++;
        }
        const r6 = o6[0], l4 = o6.at(-1), d3 = r6.from.port, u2 = l4.to.port, p3 = { connectionId: i6, mutuallyConnectedNetworkId: n3.get(e53) ?? e53, startRegionId: AQ(d3, r6.regionId), endRegionId: AQ(u2, l4.regionId), preloadedTraceSection: { traceId: e53, startRoutePosition: r6.from.assignment.routePosition, endRoutePosition: l4.to.assignment.routePosition, startPoint: { x: r6.from.assignment.tracePoint.x, y: r6.from.assignment.tracePoint.y, z: r6.from.assignment.z }, endPoint: { x: l4.to.assignment.tracePoint.x, y: l4.to.assignment.tracePoint.y, z: l4.to.assignment.z } } };
        a4.push(p3), c4.push({ requiredRip: false, connection: p3, path: [d3, u2].map((e54) => ({ portId: e54.portId, g: 0, h: 0, f: 0, hops: 0, ripRequired: false })) });
      }
      d2.length > 0 && l3++;
    }
  })(c3), c3;
};
var qQ = (e51) => {
  const t2 = new Map;
  for (let n2 = 0;n2 < e51.problem.routeNet.length; n2++) {
    const o3 = e51.problem.routeMetadata?.[n2], i3 = o3?.mutuallyConnectedNetworkId;
    if (typeof i3 != "string" || i3.length === 0)
      throw new Error(`Tiny hypergraph route ${n2} is missing a net ID`);
    t2.set(i3, e51.problem.routeNet[n2]);
  }
  for (let n2 = 0;n2 < e51.problem.regionNetId.length; n2++) {
    const o3 = e51.topology.regionMetadata?.[n2]?._tinyTerminalNetId;
    if (typeof o3 != "string")
      continue;
    const i3 = t2.get(o3);
    i3 !== undefined && (e51.problem.regionNetId[n2] = i3);
  }
};
var JQ = (e51) => {
  const t2 = new Map;
  e51.topology.regionMetadata?.forEach((e52, n3) => {
    typeof e52.serializedRegionId == "string" && t2.set(e52.serializedRegionId, n3);
  });
  const n2 = new Set;
  for (const t3 of e51.problem.routeMetadata ?? [])
    wQ(t3) || (typeof t3.startRegionId == "string" && n2.add(t3.startRegionId), typeof t3.endRegionId == "string" && n2.add(t3.endRegionId));
  for (const o3 of e51.problem.routeMetadata ?? [])
    if (wQ(o3))
      for (const i3 of [o3.startRegionId, o3.endRegionId]) {
        if (typeof i3 != "string" || n2.has(i3))
          continue;
        const o4 = t2.get(i3);
        if (o4 === undefined)
          continue;
        const r3 = e51.topology.regionMetadata?.[o4];
        typeof r3?.netId == "number" || typeof r3?.NetId == "number" || (e51.problem.regionNetId[o4] = -1);
      }
};
var QQ = (e51) => {
  if (e51.problem.metadataPortPenaltiesApplied)
    return 0;
  let t2 = 0, n2 = e51.problem.portPenalty !== undefined;
  for (let o4 = 0;o4 < e51.topology.portCount; o4++) {
    const i3 = Number(e51.topology.portMetadata?.[o4]?.tinyHypergraphPortPenalty), r3 = Number.isFinite(i3) && i3 > 0 ? i3 : 0;
    r3 > 0 && t2++, e51.problem.portPenalty?.[o4] !== r3 && (n2 = false);
  }
  if (n2)
    return e51.problem.metadataPortPenaltiesApplied = true, t2;
  t2 = 0;
  const o3 = e51.problem.portPenalty ? new Float64Array(e51.problem.portPenalty) : new Float64Array(e51.topology.portCount);
  for (let n3 = 0;n3 < e51.topology.portCount; n3++) {
    const i3 = Number(e51.topology.portMetadata?.[n3]?.tinyHypergraphPortPenalty);
    !Number.isFinite(i3) || i3 <= 0 || (o3[n3] += i3, t2++);
  }
  return t2 > 0 && (e51.problem.portPenalty = o3), e51.problem.metadataPortPenaltiesApplied = true, t2;
};
var KQ = class extends PQ {
  configuredSolvers = new WeakSet;
  duplicatePortPenaltyCount = 0;
  metadataPortPenaltyCount = 0;
  crampedPortPenaltyCount = 0;
  preloadedPortCount = 0;
  preloadedFixedSegmentCount = 0;
  crampedPortTraversalPenalty;
  useSelectiveReripRouting;
  constructor(e51, t2, n2 = false) {
    super(e51), this.useSelectiveReripRouting = t2, this.crampedPortTraversalPenalty = 150;
    const o3 = OQ(e51.serializedHyperGraph);
    if (this.preloadedPortCount = o3.preloadedPortCount, this.preloadedFixedSegmentCount = o3.preloadedAssignmentCount, t2) {
      const e52 = this.pipelineDef.find((e53) => e53.solverName === "solveGraph");
      if (!e52)
        throw new Error("Tiny hypergraph pipeline is missing the solveGraph stage");
      e52.solverClass = n2 ? CJ : _J;
    }
    this.MAX_ITERATIONS = XQ(e51);
  }
  loadHyperGraph(e51) {
    const t2 = super.loadHyperGraph(e51);
    ((e52, t3) => {
      const n3 = new Map;
      for (const e53 of t3.connections ?? [])
        wQ(e53) && n3.set(e53.connectionId, e53.preloadedTraceSection);
      for (const t4 of e52.problem.routeMetadata ?? []) {
        const e53 = n3.get(t4.connectionId);
        e53 && (t4.preloadedTraceSection = e53);
      }
    })(t2, this.inputProblem.serializedHyperGraph);
    const n2 = QQ(t2), { duplicatePortPenaltyCount: o3, crampedPortPenaltyCount: i3 } = ((e52, t3) => {
      let n3 = 0, o4 = 0;
      const i4 = e52.problem.portPenalty ? new Float64Array(e52.problem.portPenalty) : new Float64Array(e52.topology.portCount);
      for (let r3 = 0;r3 < e52.topology.portCount; r3++) {
        const s2 = e52.topology.portMetadata?.[r3];
        typeof s2?.duplicatedFromPortId == "string" && (i4[r3] += 150, n3++), s2?.cramped && t3 > 0 && (i4[r3] += t3, o4++);
      }
      return (n3 > 0 || o4 > 0) && (e52.problem.portPenalty = i4), { duplicatePortPenaltyCount: n3, crampedPortPenaltyCount: o4 };
    })(t2, this.crampedPortTraversalPenalty);
    return qQ(t2), JQ(t2), this.metadataPortPenaltyCount = Math.max(this.metadataPortPenaltyCount, n2), this.duplicatePortPenaltyCount = Math.max(this.duplicatePortPenaltyCount, o3), this.crampedPortPenaltyCount = Math.max(this.crampedPortPenaltyCount, i3), t2;
  }
  _step() {
    super._step(), this.configureSolver(this.activeSubSolver);
  }
  getInitialVisualizationSolver() {
    if (this.useSelectiveReripRouting && !this.initialVisualizationSolver) {
      const { topology: e52, problem: t2 } = this.loadHyperGraph(this.inputProblem.serializedHyperGraph);
      this.initialVisualizationSolver = new _J(e52, t2, this.getSolveGraphOptions());
    }
    const e51 = super.getInitialVisualizationSolver();
    return this.configureSolver(e51), e51;
  }
  getSolvedTinySolver() {
    const e51 = this.getSolver("optimizeSection");
    if (e51?.solved && !e51.failed)
      return e51.getSolvedSolver();
    const t2 = this.getSolver("solveGraph");
    if (t2?.solved && !t2.failed)
      return t2;
    throw new Error("TinyHyperGraph section pipeline does not have a solved graph");
  }
  configureSolver(e51) {
    if (e51 && !this.configuredSolvers.has(e51)) {
      if (e51 instanceof dQ || e51 instanceof tJ) {
        const t2 = e51;
        QQ(t2), qQ(t2), JQ(t2);
      }
      this.configuredSolvers.add(e51);
    }
  }
};
var eK = class extends ni {
  constructor(e51) {
    super(), this.params = e51;
    const t2 = ((e52) => e52.map((e53) => {
      const t3 = e53.simpleRouteConnection;
      if (!t3)
        throw new Error(`TinyHypergraphPortPointPathingSolver requires a SimpleRouteConnection for "${e53.connectionId}"`);
      const n3 = e53.mutuallyConnectedNetworkId;
      if (!n3)
        throw new Error(`TinyHypergraphPortPointPathingSolver requires a net ID for "${e53.connectionId}"`);
      return { ...e53, mutuallyConnectedNetworkId: n3, simpleRouteConnection: t3 };
    }))(e51.connections), n2 = e51.flags.USE_SELECTIVE_RERIP_ROUTING ? function(e52, t3) {
      const n3 = new Map;
      for (const o4 of e52) {
        const e53 = t3(o4);
        n3.set(e53, (n3.get(e53) ?? 0) + 1);
      }
      return e52.map((e53, t4) => ({ connection: e53, index: t4 })).sort((e53, o4) => (n3.get(t3(o4.connection)) ?? 0) - (n3.get(t3(e53.connection)) ?? 0) || e53.index - o4.index).map(({ connection: e53 }) => e53);
    }(t2, HQ) : t2;
    this.rootConnectionNameByConnectionId = new Map(n2.map((e52) => [e52.connectionId, e52.simpleRouteConnection.__rootConnectionNames?.[0]]));
    const o3 = ZQ({ ...e51, connections: n2 });
    this.originalPreloadedSegmentKeysByConnectionId = ((e52) => {
      const t3 = new Map;
      for (const n3 of e52.connections ?? [])
        wQ(n3) && t3.set(n3.connectionId, new Set);
      for (const n3 of e52.regions)
        for (const e53 of n3.assignments ?? []) {
          const o4 = t3.get(e53.connectionId);
          if (!o4)
            continue;
          const [i4, r4] = [e53.regionPort1Id, e53.regionPort2Id].sort();
          o4.add(JSON.stringify([n3.regionId, i4, r4]));
        }
      return t3;
    })(o3);
    const i3 = OQ(o3), r3 = i3.preloadedPortCount > 0, s2 = r3 && e51.flags.USE_PARTIAL_RIP_ROUTING_WITH_PRELOADED_TRACES === true, a3 = s2 ? Math.max(o3.connections?.length ?? 0, i3.preloadedAssignmentCount) : undefined;
    let c3 = o3;
    const l3 = new qJ(o3, { duplicatePortProximity: 0.05, useSerializedPortPenalties: false, routeSolveOptions: { ...jQ(e51.minViaPadDiameter), USE_SPARSE_CANDIDATE_STORAGE: false, ACCEPT_BEST_SOLUTION_ON_TIMEOUT: true, GREEDY_FINAL_ROUTE_ITERS: 4, MAX_ITERATIONS: Math.ceil(2000000 * FQ(e51.effort)), RIP_THRESHOLD_RAMP_ATTEMPTS: 0, STATIC_REACHABILITY_PRECHECK: true } });
    if (l3.solve(), l3.failed)
      this.duplicateCongestedPortError = l3.error ?? "unknown error";
    else {
      this.duplicateCongestedPortReport = l3.report, c3 = l3.getOutput();
      for (const e52 of c3.ports) {
        const t3 = DQ(e52.d);
        typeof t3.duplicatedFromPortId == "string" && (delete t3._preloadedFixedNetIds, delete t3._preloadedTracePortAssignments);
      }
    }
    this.duplicatedPortCount = this.duplicateCongestedPortReport?.duplicatedPorts.reduce((e52, t3) => e52 + t3.duplicatePortIds.length, 0) ?? 0;
    const h2 = ((e52, t3, n3, o4 = true, i4) => {
      const r4 = e52.connections?.length ?? 0, s3 = i4 ?? r4, a4 = zQ.PARTIAL_RIP_MIN_ROUTE_COUNT ?? 0, c4 = zQ.PARTIAL_RIP_MAX_ROUTE_COUNT ?? Number.POSITIVE_INFINITY, l4 = o4 && s3 >= a4 && s3 <= c4;
      return { serializedHyperGraph: e52, createSectionMask: ({ topology: e53 }) => new Int8Array(e53.portCount), solveGraphOptions: { ...$Q({ effort: t3, portCount: e52.ports.length, minViaPadDiameter: n3 }), ...l4 ? { PARTIAL_RIP_MIN_ROUTE_COUNT: 0, PARTIAL_RIP_MAX_ROUTE_COUNT: Number.POSITIVE_INFINITY, PARTIAL_RIP_COMPLEXITY_SELECTION_MIN_ROUTE_COUNT: 0 } : { PARTIAL_RIP_ENABLED: false, OUTSIDE_IN_ROUTING: false } }, sectionSolverOptions: { ...YQ(t3, n3) } };
    })({ ...c3, solvedRoutes: o3.solvedRoutes }, e51.effort, e51.minViaPadDiameter, !r3 || s2, a3);
    this.tinyPipelineSolver = new KQ(h2, e51.flags.USE_SELECTIVE_RERIP_ROUTING === true, e51.flags.USE_PREPARED_PORT_POINT_ROUTING === true), this.primaryTinyPipelineSolver = this.tinyPipelineSolver, n2.length >= 30 && n2.length <= 99 && (this.alternativeTinyPipelineInput = { ...h2, solveGraphOptions: { ...h2.solveGraphOptions, TRACE_DENSITY_COST_FACTOR: 1 } }), this.MAX_ITERATIONS = XQ(h2) * (this.alternativeTinyPipelineInput ? 2 : 1), this.originalRegionById = new Map(e51.graph.regions.map((e52) => [e52.regionId, e52])), this.originalRegionIds = new Set(this.originalRegionById.keys()), this.inputNodeWithPortPoints = ((e52, t3) => {
      const n3 = new Map(t3.regions.map((e53) => [e53.regionId, e53])), o4 = new Map(t3.ports.map((e53) => [e53.portId, e53]));
      return e52.graph.regions.map((e53) => {
        const t4 = n3.get(e53.regionId), i4 = (t4?.pointIds ?? e53.ports.map((e54) => e54.d.portId)).map((e54) => o4.get(e54)).filter((e54) => e54 && !DQ(e54.d)._tinyTerminal).map((e54) => {
          const t5 = e54, o5 = DQ(t5.d), i5 = n3.get(t5.region1Id), r4 = n3.get(t5.region2Id), s3 = Boolean(kQ(i5?.d)._offBoardConnectionId ?? kQ(r4?.d)._offBoardConnectionId);
          return { portPointId: t5.portId, x: Number(o5.x ?? 0), y: Number(o5.y ?? 0), z: Number(o5.z ?? 0), prevPortPointId: typeof o5.prevPortPointId == "string" ? o5.prevPortPointId : undefined, nextPortPointId: typeof o5.nextPortPointId == "string" ? o5.nextPortPointId : undefined, connectionNodeIds: [t5.region1Id, t5.region2Id], distToCentermostPortOnZ: Number(o5.distToCentermostPortOnZ ?? 0), cramped: Boolean(o5.cramped), connectsToOffBoardNode: s3 };
        });
        return { capacityMeshNodeId: e53.d.capacityMeshNodeId, center: e53.d.center, width: e53.d.width, height: e53.d.height, portPoints: i4, availableZ: e53.d.availableZ, _containsObstacle: e53.d._containsObstacle, _containsTarget: e53.d._containsTarget, _offBoardConnectionId: e53.d._offBoardConnectionId, _offBoardConnectedCapacityMeshNodeIds: e53.d._offBoardConnectedCapacityMeshNodeIds, _qfpRegionType: e53.d._qfpRegionType, _isNarrowQfpPadGap: e53.d._isNarrowQfpPadGap };
      });
    })(e51, c3), Object.defineProperty(this, "stats", { configurable: true, enumerable: true, get: () => this.getStatsSnapshot(), set: (e52) => {
      this.statsSnapshot = e52, this.statsSnapshotDirty = false;
    } });
  }
  tinyPipelineSolver;
  primaryTinyPipelineSolver;
  alternativeTinyPipelineSolver;
  alternativeTinyPipelineInput;
  candidatePortfolioPhase = "primary";
  primaryCandidateSummary;
  alternativeCandidateSummary;
  alternativeCandidateEvaluated = false;
  selectedCandidate = "primary";
  duplicateCongestedPortReport;
  duplicateCongestedPortError;
  duplicatedPortCount = 0;
  inputNodeWithPortPoints;
  originalRegionById;
  originalRegionIds;
  rootConnectionNameByConnectionId;
  originalPreloadedSegmentKeysByConnectionId;
  statsSnapshot = {};
  statsSnapshotDirty = false;
  asyncRunning = false;
  getSolverName() {
    return "TinyHypergraphPortPointPathingSolver";
  }
  getChangedPreloadedRouteIds(e51) {
    const t2 = new Map, n2 = new Map;
    for (let o4 = 0;o4 < e51.problem.routeCount; o4++) {
      const i3 = this.getRouteMetadata(e51, o4);
      wQ(i3) && (t2.set(i3.connectionId, o4), n2.set(o4, new Set));
    }
    for (let t3 = 0;t3 < e51.state.regionSegments.length; t3++) {
      const o4 = e51.topology.regionMetadata?.[t3]?.serializedRegionId;
      for (const [i3, r3, s2] of e51.state.regionSegments[t3] ?? []) {
        const t4 = n2.get(i3);
        if (!t4)
          continue;
        const a3 = e51.topology.portMetadata?.[r3]?.serializedPortId, c3 = e51.topology.portMetadata?.[s2]?.serializedPortId;
        if (typeof o4 != "string" || typeof a3 != "string" || typeof c3 != "string")
          throw new Error(`Tiny hypergraph preloaded route ${i3} has a segment without serialized topology IDs`);
        const [l3, h2] = [a3, c3].sort();
        t4.add(JSON.stringify([o4, l3, h2]));
      }
    }
    const o3 = new Set;
    for (const [e52, i3] of this.originalPreloadedSegmentKeysByConnectionId) {
      const r3 = t2.get(e52);
      if (r3 === undefined)
        throw new Error(`Tiny hypergraph lost preloaded trace section "${e52}"`);
      const s2 = n2.get(r3);
      if (i3.size > 0 && s2.size === 0)
        throw new Error(`Tiny hypergraph lost preloaded trace section "${e52}"`);
      (i3.size !== s2.size || [...i3].some((e53) => !s2.has(e53))) && o3.add(r3);
    }
    return o3;
  }
  summarizePipelineCandidate(e51) {
    const t2 = e51.getSolvedTinySolver();
    let n2 = 0, o3 = 0, i3 = 0, r3 = 0, s2 = 0, a3 = 0;
    const c3 = t2.topology.regionMetadata ?? [];
    for (let e52 = 0;e52 < t2.state.regionSegments.length; e52++) {
      const l3 = t2.state.regionSegments[e52];
      s2 += l3.length;
      for (const [, e53, n3] of l3)
        t2.topology.portZ[e53] !== t2.topology.portZ[n3] && (a3 += 1);
      const h2 = c3[e52]?.capacityMeshNodeId;
      if (!h2 || !this.originalRegionIds.has(h2))
        continue;
      const d2 = this.originalRegionById.get(h2);
      if (!d2 || l3.length === 0)
        continue;
      const u2 = l3.map(([e53, n3, o4]) => [this.createAssignedPortPoint(t2, e53, n3), this.createAssignedPortPoint(t2, e53, o4)]), p3 = { capacityMeshNodeId: d2.d.capacityMeshNodeId, center: d2.d.center, width: d2.d.width, height: d2.d.height, portPoints: u2.flat(), portPointsInPairs: u2, availableZ: d2.d.availableZ }, m2 = Cz(p3), g2 = jz(d2.d, m2.numSameLayerCrossings, m2.numEntryExitLayerChanges, m2.numTransitionPairCrossings);
      n2 += g2, o3 += g2 * g2, i3 = Math.max(i3, g2), r3 += p3.portPoints.length ** 2;
    }
    return { nodePfSum: n2, nodePfSquaredSum: o3, nodePfMax: i3, squaredNodePortPointCount: r3, segmentCount: s2, layerChangeCount: a3, changedPreloadedTraceSectionCount: this.getChangedPreloadedRouteIds(t2).size };
  }
  shouldEvaluateAlternative(e51) {
    const t2 = this.primaryTinyPipelineSolver.getSolvedTinySolver().problem.routeCount;
    return this.alternativeTinyPipelineInput !== undefined && ((e52, t3) => e52.nodePfSum > 4 && e52.nodePfMax > 1 && e52.squaredNodePortPointCount / Math.max(1, t3) >= 125)(e51, t2);
  }
  shouldSelectAlternative(e51, t2) {
    return ((e52, t3, n2) => {
      if (t3.changedPreloadedTraceSectionCount > e52.changedPreloadedTraceSectionCount)
        return false;
      const o3 = n2 > 40 ? 0.92 : 0.95, i3 = t3.nodePfSum <= 0.9 * e52.nodePfSum && t3.nodePfSquaredSum <= 0.85 * e52.nodePfSquaredSum && t3.nodePfMax <= 0.85 * e52.nodePfMax && t3.squaredNodePortPointCount < 0.98 * e52.squaredNodePortPointCount && t3.segmentCount <= 0.97 * e52.segmentCount;
      return t3.nodePfSum <= 1.03 * e52.nodePfSum && t3.nodePfSquaredSum <= 1.06 * e52.nodePfSquaredSum && (t3.squaredNodePortPointCount < e52.squaredNodePortPointCount * o3 || i3);
    })(e51, t2, this.primaryTinyPipelineSolver.getSolvedTinySolver().problem.routeCount);
  }
  finishCandidatePortfolio() {
    this.candidatePortfolioPhase = "complete", this.solved = this.tinyPipelineSolver.solved, this.failed = this.tinyPipelineSolver.failed, this.error = this.tinyPipelineSolver.error ?? null;
  }
  getSolveGraphBenchmarkMetrics() {
    const e51 = this.tinyPipelineSolver.getSolver("solveGraph");
    if (!e51)
      return;
    const t2 = e51.state.regionSegments.map((e52) => e52.length), n2 = this.selectedCandidate === "alternative" ? this.alternativeCandidateSummary : this.primaryCandidateSummary, o3 = e51.stats, i3 = this.tinyPipelineSolver.getStageStats().solveGraph;
    return { routeCount: e51.problem.routeCount, traceDensityCandidateEvaluated: this.alternativeCandidateEvaluated, traceDensityCandidateSelected: this.selectedCandidate === "alternative", downstreamNodePfSum: n2?.nodePfSum, downstreamNodePfSquaredSum: n2?.nodePfSquaredSum, downstreamNodePfMax: n2?.nodePfMax, downstreamSquaredNodePortPointCount: n2?.squaredNodePortPointCount, changedPreloadedTraceSectionCount: n2?.changedPreloadedTraceSectionCount, iterations: e51.iterations, timeMs: i3?.timeSpent, ripCount: o3.ripCount, partialRipCount: o3.partialRipCount, partiallyRippedRouteCount: o3.partiallyRippedRouteCount, partiallyRippedSegmentCount: o3.partiallyRippedSegmentCount, retainedPartialRipSegmentCount: o3.retainedPartialRipSegmentCount, firstMaxRegionCost: o3.firstMaxRegionCost, bestMaxRegionCost: o3.bestMaxRegionCost, firstTotalRegionCost: o3.firstTotalRegionCost, bestTotalRegionCost: o3.bestTotalRegionCost, firstSegmentCount: o3.firstSegmentCount, bestSolvedSegmentCount: o3.bestSolvedSegmentCount, bestSolvedMaxRegionSegmentCount: o3.bestSolvedMaxRegionSegmentCount, bestSolvedSquaredRegionSegmentCount: o3.bestSolvedSquaredRegionSegmentCount, finalMaxRegionSegmentCount: Math.max(0, ...t2), finalSquaredRegionSegmentCount: t2.reduce((e52, t3) => e52 + t3 * t3, 0), finalSegmentCount: n2?.segmentCount, finalLayerChangeCount: n2?.layerChangeCount, warmupFullRipAttempts: o3.partialRipWarmupFullRipAttempts, complexityAwareSelection: o3.partialRipComplexityAwareSelection, targetReached: o3.partialRipTargetReached, outsideInCompletedRouteCount: o3.outsideInCompletedRouteCount, outsideInFallbackRouteCount: o3.outsideInFallbackRouteCount, outsideInForwardExpansionCount: o3.outsideInForwardExpansionCount, outsideInReverseExpansionCount: o3.outsideInReverseExpansionCount };
  }
  _step() {
    this.tinyPipelineSolver.step(), this.candidatePortfolioPhase === "primary" && this.primaryTinyPipelineSolver.failed ? (this.alternativeTinyPipelineInput = undefined, this.finishCandidatePortfolio()) : this.candidatePortfolioPhase === "primary" && this.primaryTinyPipelineSolver.solved ? (this.primaryCandidateSummary = this.summarizePipelineCandidate(this.primaryTinyPipelineSolver), this.shouldEvaluateAlternative(this.primaryCandidateSummary) ? (this.alternativeCandidateEvaluated = true, this.alternativeTinyPipelineSolver = new KQ(this.alternativeTinyPipelineInput, this.params.flags.USE_SELECTIVE_RERIP_ROUTING === true, this.params.flags.USE_PREPARED_PORT_POINT_ROUTING === true), this.tinyPipelineSolver = this.alternativeTinyPipelineSolver, this.candidatePortfolioPhase = "alternative") : (this.alternativeTinyPipelineInput = undefined, this.finishCandidatePortfolio())) : this.candidatePortfolioPhase === "alternative" && (this.tinyPipelineSolver.solved || this.tinyPipelineSolver.failed) && (this.tinyPipelineSolver.solved && !this.tinyPipelineSolver.failed && (this.alternativeCandidateSummary = this.summarizePipelineCandidate(this.tinyPipelineSolver)), this.alternativeCandidateSummary && this.primaryCandidateSummary && this.shouldSelectAlternative(this.primaryCandidateSummary, this.alternativeCandidateSummary) ? (this.selectedCandidate = "alternative", this.primaryTinyPipelineSolver = undefined, this.alternativeTinyPipelineSolver = undefined) : (this.tinyPipelineSolver = this.primaryTinyPipelineSolver, this.alternativeTinyPipelineSolver = undefined), this.alternativeTinyPipelineInput = undefined, this.finishCandidatePortfolio()), this.solved = this.candidatePortfolioPhase === "complete" && this.tinyPipelineSolver.solved, this.failed = this.candidatePortfolioPhase === "complete" && this.tinyPipelineSolver.failed, this.error = this.failed ? this.tinyPipelineSolver.error ?? null : null, this.progress = this.candidatePortfolioPhase === "complete" ? 1 : this.candidatePortfolioPhase === "alternative" ? 0.5 + 0.5 * this.tinyPipelineSolver.progress : this.alternativeTinyPipelineInput ? 0.5 * this.tinyPipelineSolver.progress : this.tinyPipelineSolver.progress, this.statsSnapshotDirty = true, this.activeSubSolver = this.tinyPipelineSolver.activeSubSolver ?? null;
  }
  async solveAsync(e51, t2 = 1 / 0) {
    if (this.asyncRunning)
      throw new Error("Port-point solveAsync is already running");
    this.asyncRunning = true;
    try {
      for (;!this.solved && !this.failed && this.iterations < t2; ) {
        const n2 = this.tinyPipelineSolver.activeSubSolver;
        if (e51 && n2 instanceof CJ) {
          const o3 = n2.iterations;
          await n2.solveAsync(e51, o3 + Math.max(0, t2 - this.iterations));
          const i3 = n2.solved || n2.failed, r3 = Math.max(0, n2.iterations - o3 - (i3 ? 1 : 0));
          if (this.tinyPipelineSolver.iterations += r3, this.iterations += r3, this.iterations >= t2)
            break;
        }
        this.step();
      }
    } catch (e52) {
      throw this.failed = true, this.error = `Port-point asynchronous solve failed: ${e52}`, e52;
    } finally {
      this.asyncRunning = false;
    }
  }
  getStatsSnapshot() {
    if (!this.statsSnapshotDirty)
      return this.statsSnapshot;
    const e51 = this.tinyPipelineSolver.getSolver("optimizeSection"), t2 = this.getCurrentTinySolver();
    return this.statsSnapshot = { duplicateCongestedPortSourceCount: this.duplicateCongestedPortReport?.duplicatedPorts.length ?? 0, duplicateCongestedPortCount: this.duplicatedPortCount, duplicateCongestedPortFallbackToOriginal: Boolean(this.duplicateCongestedPortError), duplicateCongestedPortPenalty: this.duplicatedPortCount > 0 ? 150 : 0, duplicateCongestedPortPenaltyCount: this.tinyPipelineSolver.duplicatePortPenaltyCount, metadataPortPenaltyCount: this.tinyPipelineSolver.metadataPortPenaltyCount, crampedPortPenalty: this.tinyPipelineSolver.crampedPortTraversalPenalty, crampedPortPenaltyCount: this.tinyPipelineSolver.crampedPortPenaltyCount, preloadedPortCount: this.tinyPipelineSolver.preloadedPortCount, preloadedFixedSegmentCount: this.tinyPipelineSolver.preloadedFixedSegmentCount, duplicateCongestedPortError: this.duplicateCongestedPortError, candidatePortfolioPhase: this.candidatePortfolioPhase, candidatePortfolioSelectedCandidate: this.selectedCandidate, candidatePortfolioPrimarySummary: this.primaryCandidateSummary, candidatePortfolioAlternativeSummary: this.alternativeCandidateSummary, ...this.tinyPipelineSolver.stats ?? {}, ...t2?.stats ?? {}, ...e51?.stats ?? {}, currentStage: this.tinyPipelineSolver.getCurrentStageName(), stageStats: this.tinyPipelineSolver.getStageStats() }, this.statsSnapshotDirty = false, this.statsSnapshot;
  }
  preview() {
    return this.visualize();
  }
  getCurrentTinySolver() {
    const e51 = this.tinyPipelineSolver.getSolver("optimizeSection");
    if (e51?.solved && !e51.failed)
      return e51.getSolvedSolver();
    const t2 = this.tinyPipelineSolver.getSolver("solveGraph");
    return t2 || undefined;
  }
  getSolvedTinySolver() {
    return this.tinyPipelineSolver.getSolvedTinySolver();
  }
  getRouteMetadata(e51, t2) {
    return e51.problem.routeMetadata?.[t2];
  }
  createAssignedPortPoint(e51, t2, n2) {
    const o3 = this.getRouteMetadata(e51, t2), i3 = o3 ? ((e52) => e52.simpleRouteConnection?.name ?? e52.connectionId)(o3) : `route-${t2}`, r3 = o3 ? this.rootConnectionNameByConnectionId.get(o3.connectionId) ?? o3.mutuallyConnectedNetworkId : undefined, s2 = e51.topology.portMetadata?.[n2];
    return { portPointId: String(s2?.serializedPortId ?? s2?.portId ?? `tiny-port-${n2}`), x: e51.topology.portX[n2], y: e51.topology.portY[n2], z: e51.topology.portZ[n2], connectionName: i3, rootConnectionName: r3, ...this.params.preserveTerminalPcbPortIds && typeof s2?.pcb_port_id == "string" ? { pcb_port_id: s2.pcb_port_id } : {}, prevPortPointId: typeof s2?.prevPortPointId == "string" ? s2.prevPortPointId : undefined, nextPortPointId: typeof s2?.nextPortPointId == "string" ? s2.nextPortPointId : undefined };
  }
  getOutput() {
    const e51 = this.getSolvedTinySolver(), t2 = [], n2 = e51.state.regionSegments, o3 = e51.topology.regionMetadata ?? [], i3 = this.getChangedPreloadedRouteIds(e51);
    for (let r4 = 0;r4 < n2.length; r4++) {
      const s2 = o3[r4]?.capacityMeshNodeId;
      if (!s2 || !this.originalRegionIds.has(s2))
        continue;
      const a3 = this.originalRegionById.get(s2);
      if (!a3)
        continue;
      const c3 = n2[r4].filter(([t3]) => {
        const n3 = this.getRouteMetadata(e51, t3);
        return !wQ(n3) || i3.has(t3);
      }).map(([t3, n3, o4]) => {
        const i4 = this.createAssignedPortPoint(e51, t3, n3), r5 = this.createAssignedPortPoint(e51, t3, o4);
        return i4.portPointId && r5.portPointId && (i4.nextPortPointId = r5.portPointId, r5.prevPortPointId = i4.portPointId), [i4, r5];
      }), l3 = c3.flat();
      l3.length !== 0 && t2.push({ capacityMeshNodeId: a3.d.capacityMeshNodeId, center: a3.d.center, width: a3.d.width, height: a3.d.height, portPoints: l3, portPointsInPairs: c3, availableZ: a3.d.availableZ });
    }
    const r3 = [...i3].map((t3) => {
      const n3 = this.getRouteMetadata(e51, t3);
      if (!wQ(n3))
        throw new Error(`Changed preloaded hypergraph route ${t3} is missing section metadata`);
      const o4 = n3.preloadedTraceSection;
      return { connectionName: n3.connectionId, traceId: o4.traceId, startRoutePosition: o4.startRoutePosition, endRoutePosition: o4.endRoutePosition, connection: { name: n3.connectionId, __rootConnectionNames: [n3.mutuallyConnectedNetworkId], pointsToConnect: [{ x: o4.startPoint.x, y: o4.startPoint.y, layer: Co(o4.startPoint.z, this.params.layerCount) }, { x: o4.endPoint.x, y: o4.endPoint.y, layer: Co(o4.endPoint.z, this.params.layerCount) }] } };
    });
    return this.stats.changedPreloadedTraceSectionCount = r3.length, { nodesWithPortPoints: t2, inputNodeWithPortPoints: this.inputNodeWithPortPoints, changedPreloadedTraceSections: r3 };
  }
  computeNodePf(e51) {
    const t2 = this.getOutput().nodesWithPortPoints.find((t3) => t3.capacityMeshNodeId === e51.capacityMeshNodeId);
    return this.computeSolvedNodePf(e51.capacityMeshNodeId, t2);
  }
  computeNodePfMap() {
    const e51 = new Map(this.getOutput().nodesWithPortPoints.map((e52) => [e52.capacityMeshNodeId, e52]));
    return new Map(this.inputNodeWithPortPoints.map((t2) => [t2.capacityMeshNodeId, this.computeSolvedNodePf(t2.capacityMeshNodeId, e51.get(t2.capacityMeshNodeId))]));
  }
  computeSolvedNodePf(e51, t2) {
    const n2 = this.originalRegionById.get(e51);
    if (!t2 || !n2)
      return null;
    const o3 = Cz(t2);
    return jz(n2.d, o3.numSameLayerCrossings, o3.numEntryExitLayerChanges, o3.numTransitionPairCrossings);
  }
  tryFinalAcceptance() {}
  getConstructorParams() {
    return [this.params];
  }
  visualize() {
    return this.tinyPipelineSolver.visualize();
  }
};
var tK = (e51, t2) => {
  if (!e51 || e51 === "none")
    return e51;
  try {
    const n2 = Tn(e51);
    return `rgba(${n2.red},${n2.green},${n2.blue},${t2})`;
  } catch {
    return Ao(e51, 1 - t2);
  }
};
var nK = ({ srj: e51, opacity: t2 = 0.25, visualizationOptions: n2 = {} }) => {
  const o3 = Wo({ ...e51, obstacles: [] }, n2);
  return { ...o3, points: [], lines: o3.lines?.map((e52) => ({ ...e52, strokeColor: tK(e52.strokeColor, t2) })), rects: o3.rects?.map((e52) => ({ ...e52, fill: tK(e52.fill, t2), stroke: tK(e52.stroke, t2) })), circles: o3.circles?.map((e52) => ({ ...e52, fill: tK(e52.fill, t2), stroke: tK(e52.stroke, t2) })) };
};
function oK(e51, t2) {
  return e51.x >= t2.center.x - t2.width / 2 && e51.x <= t2.center.x + t2.width / 2 && e51.y >= t2.center.y - t2.height / 2 && e51.y <= t2.center.y + t2.height / 2;
}
var iK = 0.000001;
var rK = (e51, t2, n2) => pe(e51, t2, n2) <= iK;
var sK = (e51, t2) => Math.abs(e51.x - t2.x) <= iK && Math.abs(e51.y - t2.y) <= iK;
var aK = (e51, t2) => {
  if (!t2 || t2.length < 3)
    return false;
  for (let n3 = 0;n3 < t2.length; n3++) {
    const o3 = t2[n3], i3 = t2[(n3 + 1) % t2.length];
    if (rK(e51, o3, i3))
      return true;
  }
  let n2 = false;
  for (let o3 = 0, i3 = t2.length - 1;o3 < t2.length; i3 = o3++) {
    const r3 = t2[o3], s2 = t2[i3];
    r3.y > e51.y != s2.y > e51.y && e51.x < (s2.x - r3.x) * (e51.y - r3.y) / (s2.y - r3.y) + r3.x && (n2 = !n2);
  }
  return n2;
};
var cK = "escape-via:";
var lK = 0.0001;
var hK = (e51) => e51.obstacleId ?? [e51.layers.join("."), e51.center.x.toFixed(4), e51.center.y.toFixed(4), e51.width.toFixed(4), e51.height.toFixed(4)].join(":");
var dK = (e51, t2, n2 = 0.0001) => me(e51, t2) <= n2;
var uK = class extends ni {
  constructor(e51, t2 = {}) {
    super(), this.ogSrj = e51, this.viaDiameter = t2.viaDiameter ?? Yo(e51).padDiameter, this.viaRadius = this.viaDiameter / 2, this.minTraceWidth = t2.minTraceWidth ?? e51.minTraceWidth, this.obstacleMargin = t2.obstacleMargin ?? e51.defaultObstacleMargin ?? 0.15, this.requiredViaToPadClearance = Math.max(this.obstacleMargin, e51.minViaEdgeToPadEdgeClearance ?? 0), this.escapeOffset = this.viaRadius + Math.max(this.minTraceWidth / 2, this.requiredViaToPadClearance), this.requiredTraceClearance = this.minTraceWidth / 2 + this.obstacleMargin / 2, this.requiredViaToViaClearance = this.viaDiameter + this.obstacleMargin, this.outputSrj = e51, this.escapeViaMetadataByPointId = new Map, this.createdEscapeVias = [];
  }
  getSolverName() {
    return "EscapeViaLocationSolver";
  }
  viaDiameter;
  viaRadius;
  minTraceWidth;
  obstacleMargin;
  escapeOffset;
  requiredTraceClearance;
  requiredViaToPadClearance;
  requiredViaToViaClearance;
  outputSrj;
  escapeViaMetadataByPointId;
  createdEscapeVias;
  nextEscapeViaIndex = 0;
  getConnectionNetIds(e51) {
    return new Set([e51.name, ...e51.__rootConnectionNames ?? [], e51.__netConnectionName].filter((e52) => Boolean(e52)));
  }
  obstacleMatchesConnectionNet(e51, t2) {
    return e51.connectedTo.some((e52) => t2.has(e52));
  }
  getObstacleZs(e51) {
    return e51.__zLayers && e51.__zLayers.length > 0 ? e51.__zLayers : e51.layers.map((e52) => mo(e52, this.ogSrj.layerCount));
  }
  getViaSpanLayers(e51, t2) {
    const n2 = mo(e51, this.ogSrj.layerCount), o3 = mo(t2, this.ogSrj.layerCount), i3 = Math.min(n2, o3), r3 = Math.max(n2, o3), s2 = Array.from({ length: r3 - i3 + 1 }, (e52, t3) => i3 + t3);
    return { __zLayers: s2, layers: s2.map((e52) => Co(e52, this.ogSrj.layerCount)) };
  }
  createEscapeViaObstacle(e51) {
    const { escapeVia: t2, connectionNetIds: n2 } = e51, { layers: o3, __zLayers: i3 } = this.getViaSpanLayers(t2.sourceLayer, t2.targetLayer);
    return { obstacleId: `escape-via-obstacle:${t2.pointId}`, type: "rect", layers: o3, __zLayers: i3, center: { x: t2.x, y: t2.y }, width: this.viaDiameter, height: this.viaDiameter, connectedTo: Array.from(n2) };
  }
  selectSourceObstacle(e51) {
    const { point: t2, sourceLayer: n2, connectionNetIds: o3 } = e51;
    return this.ogSrj.obstacles.filter((e52) => !e52.isCopperPour && e52.layers.includes(n2) && oK(t2, e52)).sort((e52, n3) => {
      const i3 = e52.connectedTo.includes(t2.pointId ?? "") || e52.connectedTo.includes(t2.pcb_port_id ?? "") || this.obstacleMatchesConnectionNet(e52, o3);
      return i3 !== (n3.connectedTo.includes(t2.pointId ?? "") || n3.connectedTo.includes(t2.pcb_port_id ?? "") || this.obstacleMatchesConnectionNet(n3, o3)) ? i3 ? -1 : 1 : e52.width * e52.height - n3.width * n3.height;
    })[0];
  }
  getCandidatePositions(e51, t2) {
    if (!t2)
      return this.dedupeCandidatePositions([{ x: e51.x + this.escapeOffset, y: e51.y }, { x: e51.x - this.escapeOffset, y: e51.y }, { x: e51.x, y: e51.y + this.escapeOffset }, { x: e51.x, y: e51.y - this.escapeOffset }, { x: e51.x + this.escapeOffset, y: e51.y + this.escapeOffset }, { x: e51.x + this.escapeOffset, y: e51.y - this.escapeOffset }, { x: e51.x - this.escapeOffset, y: e51.y + this.escapeOffset }, { x: e51.x - this.escapeOffset, y: e51.y - this.escapeOffset }]);
    const n2 = t2.center.x - t2.width / 2, o3 = t2.center.x + t2.width / 2, i3 = t2.center.y - t2.height / 2, r3 = t2.center.y + t2.height / 2, s2 = n2 - this.escapeOffset, a3 = o3 + this.escapeOffset, c3 = i3 - this.escapeOffset, l3 = r3 + this.escapeOffset, h2 = this.getEdgeSamples(i3, r3, e51.y), d2 = this.getEdgeSamples(n2, o3, e51.x), u2 = [];
    for (const e52 of h2)
      u2.push({ x: s2, y: e52 }, { x: a3, y: e52 });
    for (const e52 of d2)
      u2.push({ x: e52, y: c3 }, { x: e52, y: l3 });
    return this.dedupeCandidatePositions(u2);
  }
  dedupeCandidatePositions(e51) {
    const t2 = [];
    for (const n2 of e51)
      t2.some((e52) => dK(e52, n2)) || t2.push(n2);
    return t2;
  }
  pushEdgeSample(e51, t2, n2, o3) {
    const i3 = Math.max(n2, Math.min(o3, t2));
    e51.some((e52) => Math.abs(e52 - i3) <= lK) || e51.push(i3);
  }
  getEdgeSamples(e51, t2, n2) {
    const o3 = [], i3 = t2 - e51;
    if (this.pushEdgeSample(o3, n2, e51, t2), i3 <= lK)
      return o3;
    this.pushEdgeSample(o3, e51, e51, t2), this.pushEdgeSample(o3, t2, e51, t2), this.pushEdgeSample(o3, (e51 + t2) / 2, e51, t2);
    const r3 = Math.max(e51, Math.min(t2, n2)), s2 = Math.max(this.requiredViaToViaClearance, lK), a3 = Math.ceil(i3 / s2);
    for (let n3 = 1;n3 <= a3; n3++) {
      const i4 = n3 * s2;
      this.pushEdgeSample(o3, r3 + i4, e51, t2), this.pushEdgeSample(o3, r3 - i4, e51, t2);
    }
    return o3;
  }
  isInsideBoard(e51) {
    return !!(e51.x >= this.ogSrj.bounds.minX + this.viaRadius && e51.x <= this.ogSrj.bounds.maxX - this.viaRadius && e51.y >= this.ogSrj.bounds.minY + this.viaRadius && e51.y <= this.ogSrj.bounds.maxY - this.viaRadius) && (!(this.ogSrj.outline && this.ogSrj.outline.length >= 3) || aK(e51, this.ogSrj.outline));
  }
  hasClearEscapePath(e51) {
    const { sourcePoint: t2, candidate: n2, sourceLayer: o3, sourceObstacle: i3 } = e51;
    if (this.ogSrj.outline && this.ogSrj.outline.length >= 3) {
      if ((({ start: e52, end: t3, polygon: n3, margin: o4 = 0.2 }) => {
        if (!n3 || n3.length < 3)
          return false;
        const i4 = aK(e52, n3), r3 = aK(t3, n3);
        if (!i4 || !r3)
          return true;
        for (let i5 = 0;i5 < n3.length; i5++) {
          const r4 = n3[i5], s2 = n3[(i5 + 1) % n3.length], a3 = rK(e52, r4, s2), c3 = rK(t3, r4, s2);
          if (a3 && c3)
            continue;
          if (!he(e52, t3, r4, s2)) {
            if (!a3 && !c3 && qr(e52, t3, r4, s2) < o4 - iK)
              return true;
            continue;
          }
          const l3 = ge(e52, t3, r4, s2);
          if (!(l3 && (a3 && sK(l3, e52) || c3 && sK(l3, t3)) || l3 && (sK(l3, e52) || sK(l3, t3))))
            return true;
        }
        return false;
      })({ start: t2, end: n2, polygon: this.ogSrj.outline, margin: this.requiredTraceClearance }))
        return false;
    }
    for (const e52 of this.ogSrj.obstacles) {
      if (e52 === i3)
        continue;
      if (!e52.layers.includes(o3))
        continue;
      if (oK(n2, e52))
        return false;
      const r3 = Kj(e52);
      if (Math.min(...r3.map((e53) => qr(t2, n2, e53.start, e53.end))) + lK < this.requiredTraceClearance)
        return false;
    }
    return true;
  }
  getBoardBoundarySegments() {
    if (this.ogSrj.outline && this.ogSrj.outline.length >= 3)
      return this.ogSrj.outline.map((e52, t3) => ({ start: e52, end: this.ogSrj.outline[(t3 + 1) % this.ogSrj.outline.length] }));
    const { minX: e51, maxX: t2, minY: n2, maxY: o3 } = this.ogSrj.bounds;
    return [{ start: { x: e51, y: n2 }, end: { x: t2, y: n2 } }, { start: { x: t2, y: n2 }, end: { x: t2, y: o3 } }, { start: { x: t2, y: o3 }, end: { x: e51, y: o3 } }, { start: { x: e51, y: o3 }, end: { x: e51, y: n2 } }];
  }
  getRayProbeDistance() {
    const { minX: e51, maxX: t2, minY: n2, maxY: o3 } = this.ogSrj.bounds;
    return 2 * Math.hypot(t2 - e51, o3 - n2) + this.viaDiameter;
  }
  getRayIntersectionDistance(e51) {
    const { rayStart: t2, rayEnd: n2, segmentStart: o3, segmentEnd: i3 } = e51;
    if (!he(t2, n2, o3, i3))
      return null;
    const r3 = ge(t2, n2, o3, i3);
    if (!r3)
      return null;
    const s2 = me(t2, r3);
    return s2 <= lK ? null : s2;
  }
  getProjectedFreeSpace(e51) {
    const { sourcePoint: t2, candidate: n2 } = e51, o3 = n2.x - t2.x, i3 = n2.y - t2.y;
    return Math.abs(o3) <= lK || Math.abs(i3) <= lK ? this.getProjectedFreeSpaceAlongDirection({ ...e51, direction: { x: o3, y: i3 }, travelDistance: me(t2, n2) }) : Math.min(this.getProjectedFreeSpaceAlongDirection({ ...e51, direction: { x: 0, y: Math.sign(i3) }, travelDistance: Math.abs(i3) }), this.getProjectedFreeSpaceAlongDirection({ ...e51, direction: { x: Math.sign(o3), y: Math.sign(i3) }, travelDistance: me(t2, n2) }), this.getProjectedFreeSpaceAlongDirection({ ...e51, direction: { x: Math.sign(o3), y: 0 }, travelDistance: Math.abs(o3) }));
  }
  getProjectedFreeSpaceAlongDirection(e51) {
    const { sourcePoint: t2, sourceLayer: n2, sourceObstacle: o3, direction: i3, travelDistance: r3 } = e51, s2 = Math.hypot(i3.x, i3.y);
    if (s2 <= lK || r3 <= lK)
      return 0;
    const a3 = this.getRayProbeDistance(), c3 = i3.x / s2, l3 = i3.y / s2, h2 = { x: t2.x + c3 * a3, y: t2.y + l3 * a3 };
    let d2 = Number.POSITIVE_INFINITY;
    for (const e52 of this.ogSrj.obstacles)
      if (e52 !== o3 && e52.layers.includes(n2))
        for (const n3 of Kj(e52)) {
          const e53 = this.getRayIntersectionDistance({ rayStart: t2, rayEnd: h2, segmentStart: n3.start, segmentEnd: n3.end });
          e53 !== null && (d2 = Math.min(d2, e53));
        }
    for (const e52 of this.getBoardBoundarySegments()) {
      const n3 = this.getRayIntersectionDistance({ rayStart: t2, rayEnd: h2, segmentStart: e52.start, segmentEnd: e52.end });
      n3 !== null && (d2 = Math.min(d2, n3));
    }
    return Number.isFinite(d2) ? Math.max(0, d2 - r3) : 0;
  }
  getMinBlockingClearance(e51) {
    const { candidate: t2, connectionNetIds: n2, sourceZ: o3, targetZ: i3 } = e51, r3 = Math.min(o3, i3), s2 = Math.max(o3, i3);
    let a3 = Number.POSITIVE_INFINITY;
    for (const e52 of this.ogSrj.obstacles) {
      const n3 = this.getObstacleZs(e52);
      if (!n3.some((e53) => e53 >= r3 && e53 <= s2))
        continue;
      if (e52.isCopperPour && !n3.includes(o3))
        continue;
      const i4 = Oe(t2, e52) - this.viaRadius;
      if (a3 = Math.min(a3, i4), a3 + lK < this.requiredViaToPadClearance)
        return a3;
    }
    return a3;
  }
  getMinPlacedEscapeViaClearance(e51) {
    let t2 = Number.POSITIVE_INFINITY;
    for (const n2 of this.createdEscapeVias) {
      const o3 = me(e51, n2) - this.viaDiameter;
      if (t2 = Math.min(t2, o3), t2 + lK < this.obstacleMargin)
        return t2;
    }
    return t2;
  }
  selectPointOwner(e51) {
    const { point: t2, groupConnections: n2, matchingCopperPours: o3 } = e51, i3 = hB(t2), r3 = n2.map((e52) => ({ connection: e52, pointIndex: e52.pointsToConnect.findIndex((e53) => hB(e53) === i3) })).filter((e52) => e52.pointIndex !== -1);
    return r3.length === 0 ? null : (r3.sort((e52, t3) => {
      const n3 = o3.some((t4) => this.obstacleMatchesConnectionNet(t4, this.getConnectionNetIds(e52.connection)));
      return n3 !== o3.some((e53) => this.obstacleMatchesConnectionNet(e53, this.getConnectionNetIds(t3.connection))) ? n3 ? -1 : 1 : e52.pointIndex - t3.pointIndex;
    }), r3[0]);
  }
  findBestEscapeViaCandidate(e51) {
    const { connection: t2, point: n2, pointIndex: o3, matchingCopperPours: i3, connectionNetIds: r3, sourceObstacle: s2 } = e51;
    if (!vo(n2))
      return null;
    const a3 = n2.layer, c3 = mo(a3, this.ogSrj.layerCount), l3 = s2 ?? this.selectSourceObstacle({ point: n2, sourceLayer: a3, connectionNetIds: r3 }), h2 = this.getCandidatePositions(n2, l3);
    let d2 = null;
    for (const e52 of i3) {
      const i4 = e52.layers[0];
      if (!i4 || i4 === a3)
        continue;
      const s3 = mo(i4, this.ogSrj.layerCount), u2 = hK(e52);
      for (const p3 of h2) {
        if (!this.isInsideBoard(p3))
          continue;
        if (!oK(p3, e52))
          continue;
        if (!this.hasClearEscapePath({ sourcePoint: n2, candidate: p3, sourceLayer: a3, sourceObstacle: l3 }))
          continue;
        const h3 = this.getMinBlockingClearance({ candidate: p3, connectionNetIds: r3, sourceZ: c3, targetZ: s3 });
        if (h3 + lK < this.requiredViaToPadClearance)
          continue;
        const m2 = this.getMinPlacedEscapeViaClearance(p3);
        if (m2 + lK < this.obstacleMargin)
          continue;
        const g2 = this.getProjectedFreeSpace({ sourcePoint: n2, candidate: p3, sourceLayer: a3, sourceObstacle: l3 }), f2 = Math.min(g2, 3), _2 = 100 * h3 - me(n2, p3) - 0.5 * Math.abs(s3 - c3) + 2 * f2 + (Number.isFinite(m2) ? 10 * Math.min(m2, this.requiredViaToViaClearance) : 0);
        (!d2 || _2 > d2.score) && (d2 = { pointId: `${cK}${t2.name}:${n2.pointId ?? `p${o3}`}:${i4}:${this.nextEscapeViaIndex++}`, x: p3.x, y: p3.y, connectionName: t2.name, rootConnectionName: t2.__rootConnectionNames?.[0] ?? t2.name, sourcePointIndex: o3, sourcePointId: n2.pointId, sourceLayer: a3, targetLayer: i4, targetPourKey: u2, score: _2 });
      }
    }
    return d2;
  }
  buildPointPlacementPlans(e51) {
    const { mergedConnection: t2, groupConnections: n2, matchingCopperPours: o3, connectionNetIds: i3 } = e51, r3 = [];
    for (const e52 of t2.pointsToConnect) {
      const t3 = this.selectPointOwner({ point: e52, groupConnections: n2, matchingCopperPours: o3 });
      if (!t3)
        continue;
      const s2 = vo(e52) ? this.selectSourceObstacle({ point: e52, sourceLayer: e52.layer, connectionNetIds: i3 }) : undefined, a3 = vo(e52) ? this.getCandidatePositions(e52, s2).length : 0;
      r3.push({ point: e52, pointOwner: t3, sourceObstacle: s2, candidateCount: a3 });
    }
    return r3.sort((e52, t3) => {
      if (e52.candidateCount !== t3.candidateCount)
        return e52.candidateCount - t3.candidateCount;
      const n3 = (e52.sourceObstacle?.width ?? 0) * (e52.sourceObstacle?.height ?? 0), o4 = (t3.sourceObstacle?.width ?? 0) * (t3.sourceObstacle?.height ?? 0);
      return n3 !== o4 ? n3 - o4 : e52.pointOwner.pointIndex - t3.pointOwner.pointIndex;
    });
  }
  _step() {
    const e51 = this.ogSrj.obstacles.filter((e52) => e52.isCopperPour), t2 = this.ogSrj.connections, n2 = t2.map((e52) => structuredClone(e52)), o3 = new Map(n2.map((e52) => [e52.name, e52])), i3 = structuredClone(this.ogSrj.obstacles), r3 = dB([...t2]);
    for (const n3 of r3) {
      const r4 = new Set(n3.__rootConnectionNames ?? [n3.name]), s2 = t2.filter((e52) => (e52.__rootConnectionNames ?? [e52.name]).some((e53) => r4.has(e53)));
      if (s2.length === 0)
        continue;
      const a3 = new Set;
      for (const e52 of s2)
        for (const t3 of this.getConnectionNetIds(e52))
          a3.add(t3);
      const c3 = e51.filter((e52) => this.obstacleMatchesConnectionNet(e52, a3));
      if (c3.length === 0)
        continue;
      const l3 = new Map, h2 = new Map, d2 = this.buildPointPlacementPlans({ mergedConnection: n3, groupConnections: s2, matchingCopperPours: c3, connectionNetIds: a3 });
      for (const { point: e52, pointOwner: t3, sourceObstacle: n4 } of d2) {
        const r5 = this.findBestEscapeViaCandidate({ connection: t3.connection, point: e52, pointIndex: t3.pointIndex, matchingCopperPours: c3, connectionNetIds: a3, sourceObstacle: n4 });
        if (!r5)
          continue;
        const s3 = o3.get(t3.connection.name);
        if (!s3)
          continue;
        if (s3.pointsToConnect.some((e53) => vo(e53) && e53.layer === r5.sourceLayer && dK(e53, r5)))
          continue;
        s3.pointsToConnect.push({ x: r5.x, y: r5.y, layer: r5.sourceLayer, pointId: r5.pointId, terminalVia: { toLayer: r5.targetLayer, viaDiameter: this.viaDiameter } }), this.escapeViaMetadataByPointId.set(r5.pointId, r5), this.createdEscapeVias.push(r5), i3.push(this.createEscapeViaObstacle({ escapeVia: r5, connectionNetIds: this.getConnectionNetIds(t3.connection) }));
        const d3 = l3.get(r5.targetPourKey);
        d3 ? d3.push(r5.pointId) : l3.set(r5.targetPourKey, [r5.pointId]), h2.has(r5.targetPourKey) || h2.set(r5.targetPourKey, t3.connection.name);
      }
      for (const [e52, t3] of l3.entries()) {
        if (t3.length <= 1)
          continue;
        const n4 = h2.get(e52);
        if (!n4)
          continue;
        const i4 = o3.get(n4);
        i4 && (i4.externallyConnectedPointIds = [...i4.externallyConnectedPointIds ?? [], t3]);
      }
    }
    this.outputSrj = { ...structuredClone(this.ogSrj), connections: n2, obstacles: i3 }, this.solved = true;
  }
  getOutputSimpleRouteJson() {
    return structuredClone(this.outputSrj);
  }
  getEscapeViaMetadataByPointId() {
    return new Map(this.escapeViaMetadataByPointId);
  }
  visualize() {
    return { title: "Escape Via Location Solver", points: this.outputSrj.connections.flatMap((e51) => e51.pointsToConnect.map((t2) => ({ x: t2.x, y: t2.y, color: t2.pointId?.startsWith(cK) === true ? "#0f766e" : "#dc2626", label: t2.pointId?.startsWith(cK) === true ? `${e51.name}
escape via` : e51.name }))), lines: this.createdEscapeVias.map((e51) => {
      const t2 = this.outputSrj.connections.find((t3) => t3.name === e51.connectionName)?.pointsToConnect[e51.sourcePointIndex] ?? null;
      return { points: t2 ? [{ x: t2.x, y: t2.y }, { x: e51.x, y: e51.y }] : [{ x: e51.x, y: e51.y }], strokeColor: "#0f766e" };
    }), circles: this.createdEscapeVias.map((e51) => ({ center: { x: e51.x, y: e51.y }, radius: this.viaRadius, strokeColor: "#0f766e", label: `${e51.connectionName}
${e51.targetLayer}` })), rects: this.outputSrj.obstacles.filter((e51) => !e51.isCopperPour).map((e51) => ({ ...e51, fill: "rgba(220,38,38,0.12)" })) };
  }
};
var mK = (e51) => ({ ...e51 });
var gK = (e51) => ({ ...e51, route: e51.route?.map(mK), vias: e51.vias?.map((e52) => ({ ...e52 })) });
var fK = (e51) => e51.map(gK);
var _K = "#0000FF";
var yK = 0.15;
var bK = 0.000001;
var xK = 0.1;
var vK = ["top", "bottom", "left", "right"];
var IK = (e51) => e51.x * e51.x + e51.y * e51.y;
var SK = (e51, t2) => ({ x: e51.x - t2.x, y: e51.y - t2.y });
var CK = (e51, t2, n2) => {
  const o3 = SK(n2, t2), i3 = IK(o3);
  if (i3 <= bK)
    return Math.sqrt(IK(SK(e51, t2)));
  const r3 = (a3 = SK(e51, t2), c3 = o3, s2 = (a3.x * c3.x + a3.y * c3.y) / i3, Math.max(0, Math.min(1, s2)));
  var s2, a3, c3;
  const l3 = { x: t2.x + o3.x * r3, y: t2.y + o3.y * r3 };
  return Math.sqrt(IK(SK(e51, l3)));
};
var PK = (e51) => e51?.z === 1 ? "bottom" : "top";
var MK = (e51, t2, n2) => (e51.z ?? 0) === (t2.z ?? 0) && ((t2.z ?? 0) === (n2.z ?? 0) && (e51.x === t2.x && t2.x === n2.x || e51.y === t2.y && t2.y === n2.y));
var wK = (e51, t2, n2) => {
  const o3 = n2?.get(e51);
  if (o3)
    return o3;
  const i3 = e51.route ?? [], r3 = e51.traceThickness ?? yK;
  let { POSITIVE_INFINITY: s2, POSITIVE_INFINITY: a3, NEGATIVE_INFINITY: c3, NEGATIVE_INFINITY: l3 } = Number, h2 = false;
  const d2 = (e52, t3, n3) => {
    s2 = Math.min(s2, e52 - n3), a3 = Math.min(a3, t3 - n3), c3 = Math.max(c3, e52 + n3), l3 = Math.max(l3, t3 + n3), h2 = true;
  }, u2 = { segments: [], segmentsByLayer: { top: [], bottom: [] }, vias: (e51.vias ?? []).map((n3) => {
    const o4 = (n3.diameter ?? e51.viaDiameter ?? 0.3) / 2;
    return d2(n3.x, n3.y, o4), { center: { x: n3.x, y: n3.y }, radius: o4, routeIndex: t2 };
  }), bounds: { minX: 0, minY: 0, maxX: 0, maxY: 0 } };
  for (let e52 = 0;e52 < i3.length - 1; ) {
    const n3 = i3[e52];
    let o4 = e52 + 1, s3 = i3[o4];
    const a4 = r3 / 2;
    for (n3 && d2(n3.x, n3.y, a4), s3 && d2(s3.x, s3.y, a4);o4 < i3.length - 1; ) {
      const e53 = i3[o4], t3 = i3[o4 + 1];
      if (!n3 || !e53 || !t3)
        break;
      if (PK(n3) !== PK(e53))
        break;
      if (PK(e53) !== PK(t3))
        break;
      if (!MK(n3, e53, t3))
        break;
      o4 += 1, s3 = t3, d2(t3.x, t3.y, a4);
    }
    if (!n3 || !s3) {
      e52 += 1;
      continue;
    }
    const c4 = PK(n3), l4 = { start: n3, end: s3, routeIndex: t2, pointIndex: e52, endPointIndex: o4, thickness: r3, halfThickness: a4, layer: c4, minX: Math.min(n3.x, s3.x) - a4, maxX: Math.max(n3.x, s3.x) + a4, minY: Math.min(n3.y, s3.y) - a4, maxY: Math.max(n3.y, s3.y) + a4 };
    u2.segments.push(l4), u2.segmentsByLayer[c4].push(l4), e52 = o4;
  }
  if (!h2)
    for (const e52 of i3)
      d2(e52.x, e52.y, r3 / 2);
  return u2.bounds = h2 ? { minX: s2, minY: a3, maxX: c3, maxY: l3 } : { minX: 0, minY: 0, maxX: 0, maxY: 0 }, n2?.set(e51, u2), u2;
};
var NK = (e51, t2, n2) => t2.x <= Math.max(e51.x, n2.x) + bK && t2.x >= Math.min(e51.x, n2.x) - bK && t2.y <= Math.max(e51.y, n2.y) + bK && t2.y >= Math.min(e51.y, n2.y) - bK;
var RK = (e51, t2, n2) => (t2.y - e51.y) * (n2.x - t2.x) - (t2.x - e51.x) * (n2.y - t2.y);
var TK = (e51, t2, n2, o3) => ((e52, t3, n3, o4) => {
  const i3 = RK(e52, t3, n3), r3 = RK(e52, t3, o4), s2 = RK(n3, o4, e52), a3 = RK(n3, o4, t3);
  return !!(Math.abs(i3) <= bK && NK(e52, n3, t3)) || !!(Math.abs(r3) <= bK && NK(e52, o4, t3)) || !!(Math.abs(s2) <= bK && NK(n3, e52, o4)) || !!(Math.abs(a3) <= bK && NK(n3, t3, o4)) || i3 > 0 != r3 > 0 && s2 > 0 != a3 > 0;
})(e51, t2, n2, o3) ? 0 : Math.min(CK(e51, n2, o3), CK(t2, n2, o3), CK(n2, e51, t2), CK(o3, e51, t2));
var EK = (e51, t2) => Math.abs(e51.x - t2.x) <= bK && Math.abs(e51.y - t2.y) <= bK;
var AK = (e51, t2) => EK(e51.start, t2.start) || EK(e51.start, t2.end) || EK(e51.end, t2.start) || EK(e51.end, t2.end);
var OK = (e51) => {
  if (!e51)
    return [];
  const t2 = [e51.connectionName, e51.rootConnectionName].filter((e52) => Boolean(e52));
  return Array.from(new Set(t2));
};
var kK = (e51, t2) => {
  const n2 = OK(e51), o3 = OK(t2);
  return n2.length !== 0 && o3.length !== 0 && n2.some((e52) => o3.includes(e52));
};
var DK = (e51, t2, n2) => e51.minX - n2 <= t2.maxX && e51.maxX + n2 >= t2.minX && e51.minY - n2 <= t2.maxY && e51.maxY + n2 >= t2.minY;
var LK = (e51, t2, n2) => {
  const o3 = n2 + e51.halfThickness + t2.halfThickness - bK;
  return e51.minX - n2 <= t2.maxX && e51.maxX + n2 >= t2.minX && e51.minY - n2 <= t2.maxY && e51.maxY + n2 >= t2.minY && o3 > 0;
};
var zK = (e51, t2, n2, o3) => {
  const i3 = o3 + n2.halfThickness + t2 - bK, r3 = e51.x - i3, s2 = e51.x + i3, a3 = e51.y - i3, c3 = e51.y + i3;
  return r3 <= n2.maxX && s2 >= n2.minX && a3 <= n2.maxY && c3 >= n2.minY;
};
var BK = (e51, t2) => {
  const n2 = new WeakMap, o3 = e51.map((e52, t3) => wK(e52, t3, n2)), i3 = [], r3 = new Set, s2 = (e52) => {
    r3.has(e52.label) || (r3.add(e52.label), i3.push(e52));
  };
  for (let n3 = 0;n3 < o3.length; n3 += 1) {
    const i4 = o3[n3];
    if (i4)
      for (let r4 = n3 + 1;r4 < o3.length; r4 += 1) {
        const a3 = o3[r4];
        if (a3 && (!kK(e51[n3], e51[r4]) && DK(i4.bounds, a3.bounds, t2))) {
          for (const e52 of ["top", "bottom"]) {
            const o4 = i4.segmentsByLayer[e52], c3 = a3.segmentsByLayer[e52];
            for (const i5 of o4)
              for (const o5 of c3) {
                if (AK(i5, o5))
                  continue;
                if (!LK(i5, o5, t2))
                  continue;
                const a4 = t2 + (i5.thickness + o5.thickness) / 2 - bK;
                if (TK(i5.start, i5.end, o5.start, o5.end) >= a4)
                  continue;
                s2({ center: { x: (Math.max(i5.minX - t2, o5.minX - t2) + Math.min(i5.maxX + t2, o5.maxX + t2)) / 2, y: (Math.max(i5.minY - t2, o5.minY - t2) + Math.min(i5.maxY + t2, o5.maxY + t2)) / 2 }, label: `trace-violation:${n3}:s${i5.pointIndex}:${r4}:s${o5.pointIndex}:${e52}` });
              }
          }
          for (const e52 of i4.segments)
            for (const [o4, i5] of a3.vias.entries()) {
              if (!zK(i5.center, i5.radius, e52, t2))
                continue;
              const a4 = t2 + e52.halfThickness + i5.radius - bK;
              CK(i5.center, e52.start, e52.end) >= a4 || s2({ center: i5.center, label: `trace-violation:${n3}:s${e52.pointIndex}:${r4}:v${o4}` });
            }
          for (const e52 of a3.segments)
            for (const [o4, a4] of i4.vias.entries()) {
              if (!zK(a4.center, a4.radius, e52, t2))
                continue;
              const i5 = t2 + e52.halfThickness + a4.radius - bK;
              CK(a4.center, e52.start, e52.end) >= i5 || s2({ center: a4.center, label: `trace-violation:${n3}:v${o4}:${r4}:s${e52.pointIndex}` });
            }
        }
      }
  }
  return ((e52) => {
    const t3 = [];
    for (const n3 of e52) {
      const e53 = t3.find((e54) => {
        return t4 = e54.center, o4 = n3.center, Math.hypot(t4.x - o4.x, t4.y - o4.y) <= 0.28;
        var t4, o4;
      });
      e53 ? (e53.center = { x: (e53.center.x * e53.count + n3.center.x) / (e53.count + 1), y: (e53.center.y * e53.count + n3.center.y) / (e53.count + 1) }, e53.labels.push(n3.label), e53.count += 1) : t3.push({ center: n3.center, labels: [n3.label], count: 1 });
    }
    return t3.map((e53, t4) => ({ center: e53.center, radius: Math.min(0.3, 0.2 + 0.035 * Math.sqrt(e53.count - 1)), stroke: "#f59e0b", fill: "rgba(245, 158, 11, 0.46)", label: e53.count === 1 ? e53.labels[0] : `trace-violations:${t4}:count-${e53.count}` }));
  })(i3);
};
var FK = new WeakMap;
var jK = new WeakMap;
var $K = new WeakMap;
var YK = (e51) => {
  let t2 = FK.get(e51);
  return t2 === undefined && (t2 = e51.length > 2 && e51[e51.length - 1] - e51[0] === e51.length - 1 ? `${e51[0]}..${e51[e51.length - 1]}` : e51.join(","), FK.set(e51, t2)), t2;
};
var XK = ({ routeIndexes: e51, layers: t2, routePointIndexes: n2 }) => `${e51[0]}:${t2[0]}:${YK(n2[0])}:${e51[1]}:${t2[1]}:${YK(n2[1])}`;
var HK = (e51, t2, n2, o3, i3, r3, s2) => {
  const a3 = ((e52, t3, n3, o4, i4, r4) => e52 < n3 ? `${e52}:${t3}:${YK(i4)}:${n3}:${o4}:${YK(r4)}` : `${n3}:${o4}:${YK(r4)}:${e52}:${t3}:${YK(i4)}`)(t2, n2, o3, i3, r3, s2);
  e51.has(a3) || (t2 < o3 ? e51.set(a3, { routeIndexes: [t2, o3], layers: [n2, i3], routePointIndexes: [r3, s2] }) : e51.set(a3, { routeIndexes: [o3, t2], layers: [i3, n2], routePointIndexes: [s2, r3] }));
};
var VK = (e51) => {
  const t2 = jK.get(e51);
  if (t2)
    return t2;
  const n2 = [];
  for (let t3 = e51.pointIndex;t3 <= e51.endPointIndex; t3 += 1)
    n2.push(t3);
  return jK.set(e51, n2), n2;
};
var WK = (e51, t2) => !t2 || e51.some((e52) => t2.has(e52));
var GK = (e51, t2) => {
  const n2 = $K.get(t2);
  if (n2)
    return n2;
  const o3 = e51.route ?? [], i3 = [];
  for (let e52 = 0;e52 < o3.length; e52 += 1) {
    const n3 = o3[e52];
    n3 && (Math.abs(n3.x - t2.center.x) <= bK && Math.abs(n3.y - t2.center.y) <= bK && i3.push(e52));
  }
  return $K.set(t2, i3), i3;
};
var UK = (e51, t2, n2) => e51.minX - n2 <= t2.maxX && e51.maxX + n2 >= t2.minX && e51.minY - n2 <= t2.maxY && e51.maxY + n2 >= t2.minY;
var ZK = (e51, t2, n2) => {
  const o3 = n2 + e51.halfThickness + t2.halfThickness - bK;
  return e51.minX - n2 <= t2.maxX && e51.maxX + n2 >= t2.minX && e51.minY - n2 <= t2.maxY && e51.maxY + n2 >= t2.minY && o3 > 0;
};
var qK = (e51, t2, n2, o3) => {
  const i3 = o3 + n2.halfThickness + t2 - bK, r3 = e51.x - i3, s2 = e51.x + i3, a3 = e51.y - i3, c3 = e51.y + i3;
  return r3 <= n2.maxX && s2 >= n2.minX && a3 <= n2.maxY && c3 >= n2.minY;
};
var JK = (e51, t2, n2) => {
  const o3 = n2 + e51.radius + t2.radius - bK;
  return Math.abs(e51.center.x - t2.center.x) <= o3 && Math.abs(e51.center.y - t2.center.y) <= o3;
};
var QK = (e51, t2, n2, o3, i3) => {
  const r3 = e51.map((e52, t3) => wK(e52, t3, o3)), s2 = new Map;
  if (t2.size === 0)
    return [];
  const a3 = Array.from(t2), c3 = new Map, l3 = (e52) => {
    const t3 = c3.get(e52);
    if (t3)
      return t3;
    const o4 = r3[e52];
    if (!o4)
      return [];
    const i4 = [];
    for (let t4 = 0;t4 < r3.length; t4 += 1) {
      if (t4 === e52)
        continue;
      const s3 = r3[t4];
      s3 && (UK(o4.bounds, s3.bounds, n2) && i4.push(t4));
    }
    return c3.set(e52, i4), i4;
  };
  for (const e52 of a3) {
    const o4 = r3[e52];
    if (!o4)
      continue;
    const a4 = l3(e52), c4 = i3?.get(e52);
    for (const l4 of o4.segments) {
      const o5 = VK(l4);
      if (WK(o5, c4))
        for (const c5 of a4) {
          if (e52 > c5 && t2.has(c5))
            continue;
          const a5 = r3[c5];
          if (!a5)
            continue;
          const h2 = i3?.get(c5), d2 = a5.segmentsByLayer[l4.layer];
          for (const e53 of d2) {
            const t3 = VK(e53);
            if (!WK(t3, h2))
              continue;
            if (AK(l4, e53))
              continue;
            if (!ZK(l4, e53, n2))
              continue;
            const i4 = n2 + (l4.thickness + e53.thickness) / 2 - bK;
            TK(l4.start, l4.end, e53.start, e53.end) < i4 && HK(s2, l4.routeIndex, l4.layer, e53.routeIndex, e53.layer, o5, t3);
          }
        }
    }
  }
  for (const o4 of a3) {
    const a4 = r3[o4];
    if (!a4)
      continue;
    const c4 = l3(o4), h2 = i3?.get(o4);
    for (const l4 of a4.vias) {
      const a5 = GK(e51[l4.routeIndex], l4);
      if (WK(a5, h2))
        for (const e52 of c4) {
          if (o4 > e52 && t2.has(e52))
            continue;
          const c5 = r3[e52];
          if (!c5)
            continue;
          const h3 = i3?.get(e52);
          for (const e53 of c5.segments) {
            const t3 = VK(e53);
            if (!WK(t3, h3))
              continue;
            if (!qK(l4.center, l4.radius, e53, n2))
              continue;
            const o5 = n2 + e53.thickness / 2 + l4.radius - bK;
            CK(l4.center, e53.start, e53.end) < o5 && HK(s2, e53.routeIndex, e53.layer, l4.routeIndex, "via", t3, a5);
          }
        }
    }
  }
  for (const t3 of a3) {
    const o4 = r3[t3];
    if (!o4)
      continue;
    const a4 = l3(t3), c4 = i3?.get(t3);
    for (const t4 of o4.segments) {
      const o5 = VK(t4);
      if (WK(o5, c4))
        for (const c5 of a4) {
          const a5 = r3[c5];
          if (!a5)
            continue;
          const l4 = i3?.get(c5);
          for (const i4 of a5.vias) {
            const r4 = GK(e51[i4.routeIndex], i4);
            if (!WK(r4, l4))
              continue;
            if (!qK(i4.center, i4.radius, t4, n2))
              continue;
            const a6 = n2 + t4.thickness / 2 + i4.radius - bK;
            CK(i4.center, t4.start, t4.end) < a6 && HK(s2, t4.routeIndex, t4.layer, i4.routeIndex, "via", o5, r4);
          }
        }
    }
  }
  for (const o4 of a3) {
    const a4 = r3[o4];
    if (!a4)
      continue;
    const c4 = l3(o4), h2 = i3?.get(o4);
    for (const l4 of a4.vias) {
      const a5 = GK(e51[l4.routeIndex], l4);
      if (WK(a5, h2))
        for (const h3 of c4) {
          if (o4 > h3 && t2.has(h3))
            continue;
          const c5 = r3[h3];
          if (!c5)
            continue;
          const d2 = i3?.get(h3);
          for (const t3 of c5.vias) {
            const o5 = GK(e51[t3.routeIndex], t3);
            if (!WK(o5, d2))
              continue;
            if (!JK(l4, t3, n2))
              continue;
            const i4 = n2 + l4.radius + t3.radius - bK;
            Math.hypot(l4.center.x - t3.center.x, l4.center.y - t3.center.y) < i4 && HK(s2, l4.routeIndex, "via", t3.routeIndex, "via", a5, o5);
          }
        }
    }
  }
  return Array.from(s2.values());
};
var KK = (e51, t2) => e51.x >= t2.minX - bK && e51.x <= t2.maxX + bK && e51.y >= t2.minY - bK && e51.y <= t2.maxY + bK;
var e0 = (e51, t2, n2) => {
  switch (t2) {
    case "left":
      return { minX: e51.minX, maxX: e51.minX + n2, minY: e51.minY, maxY: e51.maxY };
    case "right":
      return { minX: e51.maxX - n2, maxX: e51.maxX, minY: e51.minY, maxY: e51.maxY };
    case "top":
      return { minX: e51.minX, maxX: e51.maxX, minY: e51.maxY - n2, maxY: e51.maxY };
    case "bottom":
      return { minX: e51.minX, maxX: e51.maxX, minY: e51.minY, maxY: e51.minY + n2 };
  }
};
var t0 = (e51, t2, n2) => {
  const o3 = t2.x - e51.x, i3 = t2.y - e51.y;
  let r3 = 0, s2 = 1;
  const a3 = (e52, t3) => {
    if (Math.abs(e52) <= bK)
      return t3 >= -0.000001;
    const n3 = t3 / e52;
    return e52 < 0 ? !(n3 > s2) && (n3 > r3 && (r3 = n3), true) : !(n3 < r3) && (n3 < s2 && (s2 = n3), true);
  };
  if (!(a3(-o3, e51.x - n2.minX) && a3(o3, n2.maxX - e51.x) && a3(-i3, e51.y - n2.minY) && a3(i3, n2.maxY - e51.y)))
    return 0;
  const c3 = Math.hypot(o3, i3);
  return Math.max(0, s2 - r3) * c3;
};
var n0 = (e51, t2) => vK.filter((n2) => {
  switch (n2) {
    case "left":
      return Math.abs(e51.x - t2.minX) <= bK;
    case "right":
      return Math.abs(e51.x - t2.maxX) <= bK;
    case "top":
      return Math.abs(e51.y - t2.maxY) <= bK;
    case "bottom":
      return Math.abs(e51.y - t2.minY) <= bK;
  }
  return false;
});
var o0 = (e51, t2) => {
  const n2 = [];
  return e51.x < t2.minX - bK && n2.push("left"), e51.x > t2.maxX + bK && n2.push("right"), e51.y > t2.maxY + bK && n2.push("top"), e51.y < t2.minY - bK && n2.push("bottom"), n2;
};
var i0 = (e51, t2, n2) => {
  const o3 = t2.x - e51.x, i3 = t2.y - e51.y;
  switch (n2) {
    case "left":
    case "right":
      return Math.abs(o3) <= bK && Math.abs(i3) > bK;
    case "top":
    case "bottom":
      return Math.abs(i3) <= bK && Math.abs(o3) > bK;
  }
};
var r0 = (e51, t2, n2) => {
  const o3 = [], i3 = Math.max(n2, bK), r3 = Math.min(0.1, i3 / 4);
  for (let n3 = 0;n3 < e51.length; n3 += 1) {
    const s2 = e51[n3], a3 = s2?.route ?? [];
    for (let e52 = 0;e52 < a3.length - 1; e52 += 1) {
      const c3 = a3[e52], l3 = a3[e52 + 1];
      if (!c3 || !l3)
        continue;
      const h2 = o0(c3, t2), d2 = o0(l3, t2), u2 = n0(c3, t2), p3 = n0(l3, t2), m2 = vK.filter((e53) => {
        if (s2.connectedPadSides?.includes(e53))
          return false;
        return !(t0(c3, l3, e0(t2, e53, i3)) <= r3) && !!i0(c3, l3, e53);
      }), g2 = !KK(c3, t2) || !KK(l3, t2), f2 = Array.from(new Set([...m2, ...h2, ...d2]));
      (g2 || f2.length !== 0) && o3.push({ routeIndex: n3, connectionName: s2.connectionName ?? s2.rootConnectionName ?? `route-${n3}`, segmentIndex: e52, touchedSides: f2, startSides: u2, endSides: p3, start: c3, end: l3 });
    }
  }
  return o3;
};
var s0 = (e51) => e51?.center && e51.width && e51.height ? { minX: e51.center.x - e51.width / 2, maxX: e51.center.x + e51.width / 2, minY: e51.center.y - e51.height / 2, maxY: e51.center.y + e51.height / 2, width: e51.width, height: e51.height, center: e51.center } : null;
var a0 = (e51) => e51 === "bottom" ? _K : "#FF0000";
var c0 = (e51) => {
  const t2 = e51.route ?? [], n2 = [];
  if (t2.length < 2)
    return n2;
  let o3 = PK(t2[0]), i3 = [t2[0]];
  for (let r3 = 1;r3 < t2.length; r3 += 1) {
    const s2 = t2[r3], a3 = PK(s2);
    a3 === o3 ? i3.push(s2) : (i3.length >= 2 && n2.push({ points: i3, strokeColor: a0(o3), strokeWidth: e51.traceThickness ?? yK, label: e51.connectionName ?? "route" }), o3 = a3, i3 = [t2[r3 - 1], s2]);
  }
  return i3.length >= 2 && n2.push({ points: i3, strokeColor: a0(o3), strokeWidth: e51.traceThickness ?? yK, label: e51.connectionName ?? "route" }), n2;
};
var l0 = (e51) => {
  const t2 = gK(e51), n2 = t2.route ?? [], o3 = t2.vias ?? [];
  for (let e52 = 1;e52 < n2.length; e52++) {
    const i3 = n2[e52 - 1], r3 = n2[e52];
    if ((i3.z ?? 0) === (r3.z ?? 0))
      continue;
    if (i3.x !== r3.x || i3.y !== r3.y)
      throw new Error("Node repair requires coincident via transition endpoints");
    let s2 = -1, a3 = 0.001;
    for (let e53 = 0;e53 < o3.length; e53++) {
      const t3 = o3[e53], n3 = Math.hypot(t3.x - i3.x, t3.y - i3.y);
      n3 <= a3 && (s2 = e53, a3 = n3);
    }
    s2 === -1 ? o3.push({ x: i3.x, y: i3.y, diameter: t2.viaDiameter }) : o3[s2] = { ...o3[s2], x: i3.x, y: i3.y };
  }
  return (o3.length || t2.vias) && (t2.vias = o3), t2;
};
var h0 = class {
  scenes = new WeakMap;
  retainedBytes = 0;
  maximumBytes = 33554432;
  getCandidatePairs(e51, t2, n2, o3, i3) {
    if (!Number.isFinite(i3) || i3 < 0)
      return;
    const r3 = o3[n2];
    for (const e52 of r3)
      if (!Number.isFinite(e52.start.x) || !Number.isFinite(e52.start.y) || !Number.isFinite(e52.end.x) || !Number.isFinite(e52.end.y) || !Number.isFinite(e52.radius) || e52.radius < 0)
        return;
    let s2 = this.scenes.get(e51), a3 = s2?.get(n2);
    if (a3?.fixedRoutes !== t2 && (a3 = undefined), !a3) {
      let i4 = 0, r4 = 1;
      for (let e52 = 0;e52 < o3.length; e52++)
        if (e52 !== n2)
          for (let t3 = 0;t3 < o3[e52].length; t3++) {
            const n3 = o3[e52][t3];
            if (!Number.isFinite(n3.start.x) || !Number.isFinite(n3.start.y) || !Number.isFinite(n3.end.x) || !Number.isFinite(n3.end.y) || !Number.isFinite(n3.radius) || n3.radius < 0)
              return;
            r4 = Math.max(r4, Math.abs(n3.start.x), Math.abs(n3.start.y), Math.abs(n3.end.x), Math.abs(n3.end.y), n3.radius), i4++;
          }
      if (i4 < 32)
        return;
      const c4 = new E2(i4), l3 = new Uint32Array(i4), h2 = new Uint32Array(i4);
      let d2 = 0;
      for (let e52 = 0;e52 < o3.length; e52++)
        if (e52 !== n2)
          for (let t3 = 0;t3 < o3[e52].length; t3++) {
            const n3 = o3[e52][t3], i5 = Math.min(n3.start.x, n3.end.x) - n3.radius, r5 = Math.min(n3.start.y, n3.end.y) - n3.radius, s3 = Math.max(n3.start.x, n3.end.x) + n3.radius, a4 = Math.max(n3.start.y, n3.end.y) + n3.radius;
            if (!(Number.isFinite(i5) && Number.isFinite(r5) && Number.isFinite(s3) && Number.isFinite(a4)))
              return;
            c4.add(i5, r5, s3, a4), l3[d2] = e52, h2[d2] = t3, d2++;
          }
      c4.finish(), a3 = { index: c4, routeIndexes: l3, copperIndexes: h2, maxMagnitude: r4, fixedRoutes: t2, queries: [], queryHitCount: 0 };
      const u2 = c4.data.byteLength + l3.byteLength + h2.byteLength;
      this.retainedBytes + u2 > this.maximumBytes && (this.scenes = new WeakMap, this.retainedBytes = 0, s2 = undefined), u2 <= this.maximumBytes && (s2 || (s2 = new Map, this.scenes.set(e51, s2)), s2.set(n2, a3), this.retainedBytes += u2);
    }
    const c3 = new Map;
    for (let e52 = 0;e52 < r3.length; e52++) {
      const t3 = r3[e52], o4 = i3 + t3.radius, s3 = 8 * Number.EPSILON * (a3.maxMagnitude + Math.abs(t3.start.x) + Math.abs(t3.start.y) + Math.abs(t3.end.x) + Math.abs(t3.end.y) + o4 + 1);
      if (!Number.isFinite(s3 + o4))
        return;
      const l3 = Math.min(t3.start.x, t3.end.x) - o4 - s3, h2 = Math.min(t3.start.y, t3.end.y) - o4 - s3, d2 = Math.max(t3.start.x, t3.end.x) + o4 + s3, u2 = Math.max(t3.start.y, t3.end.y) + o4 + s3, p3 = a3.queries[e52];
      let m2;
      if (p3 && p3.minX === l3 && p3.minY === h2 && p3.maxX === d2 && p3.maxY === u2)
        m2 = p3.hits;
      else {
        m2 = a3.index.search(l3, h2, d2, u2).sort((e53, t5) => e53 - t5);
        const t4 = a3.queryHitCount - (p3?.hits.length ?? 0) + m2.length;
        t4 <= 65536 && (a3.queries[e52] = { minX: l3, minY: h2, maxX: d2, maxY: u2, hits: m2 }, a3.queryHitCount = t4);
      }
      for (const t4 of m2) {
        const o5 = a3.routeIndexes[t4], i4 = a3.copperIndexes[t4];
        let r4 = c3.get(o5);
        r4 || (r4 = [], c3.set(o5, r4));
        const s4 = o5 < n2 ? i4 : e52, l4 = o5 < n2 ? e52 : i4;
        (r4[s4] ??= []).push(l4);
      }
    }
    return c3;
  }
};
var d0 = (e51) => {
  const t2 = e51.route ?? [], n2 = [];
  for (let o3 = 1;o3 < t2.length; o3++) {
    const i3 = t2[o3 - 1], r3 = t2[o3];
    (i3.z ?? 0) === (r3.z ?? 0) && n2.push({ start: i3, end: r3, minX: Math.min(i3.x, r3.x), minY: Math.min(i3.y, r3.y), maxX: Math.max(i3.x, r3.x), maxY: Math.max(i3.y, r3.y), magnitude: 1 + Math.abs(i3.x) + Math.abs(i3.y) + Math.abs(r3.x) + Math.abs(r3.y), radius: (e51.traceThickness ?? yK) / 2, minZ: i3.z ?? 0, maxZ: i3.z ?? 0, indexes: [o3 - 1, o3], via: false });
  }
  for (const [o3, i3] of (e51.vias ?? []).entries()) {
    const r3 = t2.flatMap((e52, t3) => e52.x === i3.x && e52.y === i3.y ? [t3] : []), s2 = r3.map((e52) => t2[e52].z ?? 0);
    n2.push({ start: i3, end: i3, minX: i3.x, minY: i3.y, maxX: i3.x, maxY: i3.y, magnitude: 1 + 2 * (Math.abs(i3.x) + Math.abs(i3.y)), radius: (i3.diameter ?? e51.viaDiameter ?? 0.3) / 2, minZ: s2.length ? Math.min(...s2) : 0, maxZ: s2.length ? Math.max(...s2) : 1, indexes: r3, via: true, viaIndex: o3 });
  }
  return n2;
};
var u0 = (e51, t2, n2, o3 = [], i3, r3 = new WeakMap, s2 = new h0, a3 = new WeakMap, c3 = new WeakMap) => {
  const l3 = [...e51, ...o3], h2 = l3.map((e52) => {
    let t3 = r3.get(e52);
    return t3 || (t3 = d0(e52), r3.set(e52, t3)), t3;
  }), d2 = i3 ? s2.getCandidatePairs(i3.routes, o3, i3.changedRoute, h2, t2) : undefined, u2 = i3 ? i3.evaluation.conflicts.filter((e52) => e52.firstRoute !== i3.changedRoute && e52.secondRoute !== i3.changedRoute) : [];
  let p3 = u2.reduce((e52, t3) => e52 + t3.penetration ** 2, 0);
  for (let o4 = 0;o4 < e51.length && !(i3 && o4 > i3.changedRoute); o4++) {
    const r4 = e51[o4];
    let s3 = c3.get(r4);
    if (s3 || (s3 = new Set([r4.connectionName, r4.rootConnectionName].filter(Boolean)), c3.set(r4, s3)), !i3 || o4 === i3.changedRoute) {
      const e52 = h2[o4].filter((e53) => e53.via);
      for (let n3 = 0;n3 < e52.length; n3++) {
        const i4 = e52[n3];
        for (let r5 = n3 + 1;r5 < e52.length; r5++) {
          const s4 = e52[r5];
          if (i4.maxZ < s4.minZ || s4.maxZ < i4.minZ)
            continue;
          const a4 = Math.hypot(i4.start.x - s4.start.x, i4.start.y - s4.start.y);
          if (a4 === 0)
            continue;
          const c4 = t2 + i4.radius + s4.radius - a4;
          c4 <= bK || (u2.push({ key: `${o4}:vias:${n3}:${r5}`, firstRoute: o4, secondRoute: o4, first: i4, second: s4, penetration: c4 }), p3 += c4 ** 2);
        }
      }
      for (const [e53, i4] of n2.entries()) {
        if (i4.connectedTo?.some((e54) => s3.has(e54)))
          continue;
        let n3, r5 = a3.get(i4);
        !r5 && i4.center && i4.width !== undefined && i4.height !== undefined && i4.width >= 0 && i4.height >= 0 && (r5 = { minX: i4.center.x - i4.width / 2, minY: i4.center.y - i4.height / 2, maxX: i4.center.x + i4.width / 2, maxY: i4.center.y + i4.height / 2, magnitude: Math.abs(i4.center.x) + Math.abs(i4.center.y) + Math.abs(i4.width) + Math.abs(i4.height) }, a3.set(i4, r5));
        for (const s4 of h2[o4]) {
          if (i4.zLayers && !i4.zLayers.some((e54) => e54 >= s4.minZ && e54 <= s4.maxZ))
            continue;
          if (r5 && t2 + s4.radius >= 0) {
            const e54 = t2 + s4.radius, n4 = 32 * Number.EPSILON * (s4.magnitude + r5.magnitude + Math.abs(e54));
            if (s4.minX > r5.maxX + e54 + n4 || s4.maxX < r5.minX - e54 - n4 || s4.minY > r5.maxY + e54 + n4 || s4.maxY < r5.minY - e54 - n4)
              continue;
          }
          const a4 = t2 - p0(s4, i4);
          a4 <= bK || a4 <= (n3?.penetration ?? 0) || (n3 = { key: `${o4}:pad:${e53}`, firstRoute: o4, secondRoute: -1, first: s4, second: s4, penetration: a4 });
        }
        n3 && (u2.push(n3), p3 += n3.penetration ** 2);
      }
    }
    const m2 = i3 && o4 !== i3.changedRoute, g2 = m2 ? i3.changedRoute : o4 + 1, f2 = m2 ? i3.changedRoute + 1 : l3.length;
    for (let e52 = g2;e52 < f2; e52++) {
      const n3 = l3[e52], r5 = s3.has(n3.connectionName) || s3.has(n3.rootConnectionName), a4 = new Map, c4 = d2?.get(o4 === i3?.changedRoute ? e52 : o4);
      if (d2 && !c4)
        continue;
      const m3 = h2[o4], g3 = h2[e52];
      for (let n4 = 0;n4 < m3.length; n4++) {
        const i4 = m3[n4], s4 = c4?.[n4];
        if (d2 && !s4)
          continue;
        const l4 = s4 ? s4.length : g3.length;
        for (let n5 = 0;n5 < l4; n5++) {
          const c5 = g3[s4 ? s4[n5] : n5];
          if (r5 && (!i4.via || !c5.via))
            continue;
          if (i4.maxZ < c5.minZ || c5.maxZ < i4.minZ)
            continue;
          if (r5 && i4.start.x === c5.start.x && i4.start.y === c5.start.y)
            continue;
          const l5 = t2 + i4.radius + c5.radius;
          if (Math.min(i4.start.x, i4.end.x) > Math.max(c5.start.x, c5.end.x) + l5 || Math.min(c5.start.x, c5.end.x) > Math.max(i4.start.x, i4.end.x) + l5 || Math.min(i4.start.y, i4.end.y) > Math.max(c5.start.y, c5.end.y) + l5 || Math.min(c5.start.y, c5.end.y) > Math.max(i4.start.y, i4.end.y) + l5)
            continue;
          const h3 = l5 - TK(i4.start, i4.end, c5.start, c5.end);
          if (h3 <= bK)
            continue;
          const d3 = `${i4.via ? `via:${i4.viaIndex}` : `trace:${i4.minZ}`}:${c5.via ? `via:${c5.viaIndex}` : `trace:${c5.minZ}`}`;
          h3 <= (a4.get(d3)?.penetration ?? 0) || a4.set(d3, { key: `${o4}:${e52}:${d3}`, firstRoute: o4, secondRoute: e52, first: i4, second: c5, penetration: h3 });
        }
      }
      for (const e53 of a4.values())
        u2.push(e53), p3 += e53.penetration ** 2;
    }
  }
  return u2.sort((e52, t3) => t3.penetration - e52.penetration), { conflicts: u2, score: p3 };
};
var p0 = (e51, t2) => {
  if (!t2.center || t2.width === undefined || t2.height === undefined)
    return 1 / 0;
  const n2 = t2.center.x - t2.width / 2, o3 = t2.center.x + t2.width / 2, i3 = t2.center.y - t2.height / 2, r3 = t2.center.y + t2.height / 2;
  let s2 = 0;
  for (const t3 of [e51.start, e51.end])
    t3.x >= n2 && t3.x <= o3 && t3.y >= i3 && t3.y <= r3 && (s2 = Math.max(s2, e51.radius + Math.min(t3.x - n2, o3 - t3.x, t3.y - i3, r3 - t3.y)));
  if (s2 > 0)
    return -s2;
  const a3 = [{ x: n2, y: i3 }, { x: o3, y: i3 }, { x: o3, y: r3 }, { x: n2, y: r3 }];
  return Math.min(...a3.map((t3, n3) => TK(e51.start, e51.end, t3, a3[(n3 + 1) % 4]))) - e51.radius;
};
var m0 = (e51, t2) => {
  const n2 = d0(e51).filter((e52) => !t2.zLayers || t2.zLayers.some((t3) => t3 >= e52.minZ && t3 <= e52.maxZ));
  return Math.min(...n2.map((e52) => p0(e52, t2)));
};
var g0 = (e51, t2, n2, o3, i3) => {
  const r3 = gK(e51), s2 = r3.route ?? [], a3 = e51.route ?? [], c3 = (e52) => e52 === 0 || e52 === s2.length - 1, l3 = new Set;
  for (const e52 of t2.indexes) {
    if (c3(e52))
      continue;
    const t3 = a3[e52];
    a3.forEach((e53, n3) => {
      e53.x === t3.x && e53.y === t3.y && l3.add(n3);
    });
  }
  if (!([...l3].some(c3) || t2.via && t2.indexes.some(c3))) {
    if (l3.size === 0) {
      if (t2.via || t2.indexes.length !== 2)
        return;
      const [e52, i4] = t2.indexes, r4 = s2[e52], a4 = s2[i4], c4 = [0.25, 0.75].map((e53) => ({ ...r4, x: r4.x + (a4.x - r4.x) * e53 + n2, y: r4.y + (a4.y - r4.y) * e53 + o3 }));
      s2.splice(i4, 0, ...c4);
    } else {
      for (const e52 of l3)
        s2[e52].x += n2, s2[e52].y += o3;
      for (const e52 of r3.vias ?? [])
        [...l3].some((t3) => a3[t3].x === e52.x && a3[t3].y === e52.y) && (e52.x += n2, e52.y += o3);
    }
    if (!s2.some((e52, t3) => t3 > 0 && t3 < s2.length - 1 && (e52.x < i3.minX || e52.x > i3.maxX || e52.y < i3.minY || e52.y > i3.maxY)))
      return r3;
  }
};
var f0 = (e51) => {
  const t2 = [], n2 = e51.route ?? [];
  for (let o3 = 1;o3 < n2.length; o3++) {
    const i3 = n2[o3 - 1], r3 = n2[o3];
    (i3.z ?? 0) === (r3.z ?? 0) && t2.push({ start: i3, end: r3, radius: (e51.traceThickness ?? yK) / 2, minZ: i3.z ?? 0, maxZ: i3.z ?? 0 });
  }
  for (const o3 of e51.vias ?? []) {
    let i3 = 1 / 0, r3 = -1 / 0;
    for (let e52 = 1;e52 < n2.length; e52++) {
      const t3 = n2[e52 - 1], s2 = n2[e52];
      Math.hypot(t3.x - o3.x, t3.y - o3.y) > 0.001 || Math.hypot(s2.x - o3.x, s2.y - o3.y) > 0.001 || t3.z === s2.z || (i3 = Math.min(i3, t3.z ?? 0, s2.z ?? 0), r3 = Math.max(r3, t3.z ?? 0, s2.z ?? 0));
    }
    t2.push({ start: o3, end: o3, radius: (o3.diameter ?? e51.viaDiameter ?? 0.3) / 2, minZ: i3 === 1 / 0 ? 0 : i3, maxZ: r3 === -1 / 0 ? 1 : r3 });
  }
  return t2;
};
var _0 = (e51, t2) => {
  let n2 = 1 / 0;
  for (const o3 of e51)
    o3.maxZ < t2.minZ || t2.maxZ < o3.minZ || (n2 = Math.min(n2, TK(o3.start, o3.end, t2.start, t2.end) - o3.radius - t2.radius));
  return n2;
};
var y0 = class {
  constructor(e51, t2, n2 = []) {
    this.minimumClearance = t2, this.obstacles = n2, this.fixedCopper = e51.map((e52) => ({ route: e52, copper: f0(e52) }));
  }
  fixedCopper;
  cache = new WeakMap;
  allows(e51, t2, n2, o3 = true) {
    if (o3 && ((e52, t3, n3) => {
      const o4 = new Map(u0(e52, n3, []).conflicts.map((e53) => [e53.key, e53.penetration]));
      return u0(t3, n3, []).conflicts.some((e53) => e53.penetration > (o4.get(e53.key) ?? 0) + bK);
    })(e51, t2, this.minimumClearance))
      return false;
    if (this.fixedCopper.length === 0 && this.obstacles.length === 0)
      return true;
    for (const o4 of n2) {
      const n3 = e51[o4], i3 = t2[o4];
      if (n3 === i3)
        continue;
      const r3 = this.cache.get(n3) ?? f0(n3), s2 = this.cache.get(i3) ?? f0(i3);
      this.cache.set(n3, r3), this.cache.set(i3, s2);
      const a3 = new Set([n3.connectionName, n3.rootConnectionName].filter(Boolean));
      for (const e52 of this.obstacles) {
        if (e52.connectedTo?.some((e53) => a3.has(e53)))
          continue;
        const t3 = m0(i3, e52);
        if (t3 >= this.minimumClearance - bK)
          continue;
        const o5 = m0(n3, e52);
        if (t3 < Math.min(o5, this.minimumClearance) - bK)
          return false;
      }
      for (const e52 of this.fixedCopper)
        if (!a3.has(e52.route.connectionName) && !a3.has(e52.route.rootConnectionName))
          for (const t3 of e52.copper) {
            const e53 = _0(s2, t3);
            if (e53 >= this.minimumClearance - bK)
              continue;
            const n4 = _0(r3, t3);
            if (e53 < Math.min(n4, this.minimumClearance) - bK)
              return false;
          }
    }
    return true;
  }
};
var b0 = (e51, t2) => ({ title: `HighDensityRepair02 Initial State (margin=${t2})`, routes: e51 });
var x0 = (e51) => {
  const t2 = [];
  for (const n2 of e51) {
    const e52 = t2[t2.length - 1];
    e52 && e52.z === n2.z && EK(e52, n2) || t2.push(n2);
  }
  return t2;
};
var v0 = (e51, t2, n2) => {
  const o3 = Math.max(0, e51.minX - t2.maxX, t2.minX - e51.maxX), i3 = Math.max(0, e51.minY - t2.maxY, t2.minY - e51.maxY);
  return Math.hypot(o3, i3) <= n2 + bK;
};
var I0 = (e51, t2) => {
  let n2 = Number.POSITIVE_INFINITY;
  for (const o3 of e51.segments)
    for (const e52 of t2.segments) {
      if (o3.layer !== e52.layer)
        continue;
      const t3 = TK(o3.start, o3.end, e52.start, e52.end) - (o3.thickness + e52.thickness) / 2;
      n2 = Math.min(n2, t3);
    }
  return n2;
};
var S0 = ({ currentRoutes: e51, candidateRoutes: t2, candidateRouteIndexes: n2, maximumAllowedClearance: o3 }) => {
  const i3 = new WeakMap, r3 = new WeakMap, s2 = [], a3 = Array.from(n2).sort((e52, t3) => e52 - t3), c3 = e51.map((e52, t3) => wK(e52, t3, i3)), l3 = t2.map((e52, t3) => wK(e52, t3, r3)), h2 = new Set;
  for (const e52 of a3)
    for (let n3 = 0;n3 < t2.length; n3 += 1) {
      if (n3 === e52)
        continue;
      const t3 = Math.min(e52, n3), i4 = Math.max(e52, n3), r4 = `${t3}:${i4}`;
      if (h2.has(r4))
        continue;
      h2.add(r4);
      const a4 = l3[t3], d2 = l3[i4];
      if (!a4 || !d2 || !v0(a4.bounds, d2.bounds, o3))
        continue;
      const u2 = I0(a4, d2);
      if (!Number.isFinite(u2) || u2 > o3 + bK || !c3[t3] || !c3[i4])
        continue;
      const p3 = I0(c3[t3], c3[i4]);
      !Number.isFinite(p3) || u2 >= p3 - bK || s2.push({ routeIndexes: [t3, i4], previousClearance: p3, nextClearance: u2 });
    }
  return s2;
};
var C0 = 0.001;
var P0 = (e51, t2) => e51.map((e52) => {
  const n2 = e52.route ?? [];
  return n2.length === 0 ? e52 : { ...e52, route: n2.map((e53, o3) => o3 === 0 || o3 === n2.length - 1 ? ((e54, t3) => {
    const n3 = { ...e54 };
    return Math.abs(n3.x - t3.minX) <= C0 ? n3.x = t3.minX : Math.abs(n3.x - t3.maxX) <= C0 && (n3.x = t3.maxX), Math.abs(n3.y - t3.minY) <= C0 ? n3.y = t3.minY : Math.abs(n3.y - t3.maxY) <= C0 && (n3.y = t3.maxY), n3;
  })(e53, t2) : e53) };
});
var M0 = (e51, t2) => Array.from(t2).flatMap((t3) => c0(e51[t3]).map((e52) => ({ ...e52, strokeColor: "#000000", strokeWidth: e52.strokeWidth, label: `candidate:${e52.label}` })));
var w0 = (e51, t2, n2, o3, i3) => {
  const r3 = "rgba(0, 0, 0, 0)";
  switch (t2) {
    case "left":
      return { center: { x: e51.minX + n2 / 2, y: e51.center.y }, width: n2, height: e51.height, stroke: r3, fill: o3, label: i3 };
    case "right":
      return { center: { x: e51.maxX - n2 / 2, y: e51.center.y }, width: n2, height: e51.height, stroke: r3, fill: o3, label: i3 };
    case "top":
      return { center: { x: e51.center.x, y: e51.maxY - n2 / 2 }, width: e51.width, height: n2, stroke: r3, fill: o3, label: i3 };
    case "bottom":
      return { center: { x: e51.center.x, y: e51.minY + n2 / 2 }, width: e51.width, height: n2, stroke: r3, fill: o3, label: i3 };
  }
};
var N0 = ({ routes: e51, candidateRoutes: t2, candidateRouteIndexes: n2, originalRoutes: o3, boundary: i3, side: r3, margin: s2, rejected: a3, rejectionReason: c3 }) => {
  const l3 = Array.from(n2).map((e52) => t2[e52].connectionName ?? `route-${e52}`);
  return { title: a3 ? `${r3} move rejected (${c3})` : `${r3} move accepted`, routes: a3 ? e51 : t2, originalRoutes: o3, activeSide: r3, candidateRouteNames: l3, overlayLines: a3 ? M0(t2, n2) : [], overlayRects: [w0(i3, r3, s2, a3 ? "rgba(220, 38, 38, 0.14)" : "rgba(16, 185, 129, 0.14)", a3 ? `rejected:${r3}` : `accepted:${r3}`)] };
};
var R0 = (e51, t2, n2, o3) => {
  const i3 = (e51?.adjacentObstacles ?? []).some((e52) => ((e53, t3, n3, o4) => {
    const i4 = ((e54) => e54.center && e54.width && e54.height ? { minX: e54.center.x - e54.width / 2, maxX: e54.center.x + e54.width / 2, minY: e54.center.y - e54.height / 2, maxY: e54.center.y + e54.height / 2 } : null)(e53);
    if (!i4)
      return false;
    switch (n3) {
      case "left":
        return i4.maxX >= t3.minX - bK && i4.minX <= t3.minX + o4 + bK;
      case "right":
        return i4.minX <= t3.maxX + bK && i4.maxX >= t3.maxX - o4 - bK;
      case "top":
        return i4.minY <= t3.maxY + bK && i4.maxY >= t3.maxY - o4 - bK;
      case "bottom":
        return i4.maxY >= t3.minY - bK && i4.minY <= t3.minY + o4 + bK;
    }
  })(e52, t2, n2, o3));
  return { hasObstacle: i3, moveAmount: i3 ? o3 : o3 / 2 };
};
var T0 = ({ start: e51, end: t2, side: n2, boundary: o3, amount: i3, targetAxisValue: r3 }) => {
  const s2 = (({ side: e52, boundary: t3, amount: n3, targetAxisValue: o4 }) => {
    const i4 = o4 ?? (() => {
      switch (e52) {
        case "left":
          return t3.minX + n3;
        case "right":
          return t3.maxX - n3;
        case "top":
          return t3.maxY - n3;
        case "bottom":
          return t3.minY + n3;
      }
    })();
    switch (e52) {
      case "left":
      case "right":
        return Math.min(Math.max(i4, t3.minX), t3.maxX);
      case "top":
      case "bottom":
        return Math.min(Math.max(i4, t3.minY), t3.maxY);
    }
  })({ side: n2, boundary: o3, amount: i3, targetAxisValue: r3 });
  switch (n2) {
    case "left":
    case "right":
      return x0([e51, { x: s2, y: e51.y, z: e51.z }, { x: s2, y: t2.y, z: t2.z }, t2]);
    case "top":
    case "bottom":
      return x0([e51, { x: e51.x, y: s2, z: e51.z }, { x: t2.x, y: s2, z: t2.z }, t2]);
  }
};
var E0 = (e51, t2, n2, o3, i3, r3, s2, a3 = false) => {
  const c3 = e51.route ?? [];
  if (c3.length < 2 || t2.length === 0)
    return gK(e51);
  const l3 = a3 ? i3 : Math.max(i3, r3), h2 = ((e52, t3) => {
    switch (e52) {
      case "left":
        return { x: t3, y: 0 };
      case "right":
        return { x: -t3, y: 0 };
      case "top":
        return { x: 0, y: -t3 };
      case "bottom":
        return { x: 0, y: t3 };
    }
  })(o3, l3);
  if (a3 || (e51.vias?.length ?? 0) > 0 || c3.length > 2) {
    const n3 = gK(e51), o4 = n3.route ?? [];
    for (const e52 of t2) {
      const t3 = o4[e52];
      t3 && (o4[e52] = { ...t3, x: t3.x + h2.x, y: t3.y + h2.y });
    }
    for (const o5 of n3.vias ?? []) {
      t2.some((t3) => {
        const n4 = e51.route?.[t3];
        return !!n4 && EK(n4, o5);
      }) && (o5.x += h2.x, o5.y += h2.y);
    }
    return n3;
  }
  const d2 = gK(e51);
  if (c3.length === 2 && t2.length === 2 && t2[0] === 0 && t2[1] === 1) {
    const t3 = c3[0], i4 = c3[1];
    return gK({ ...e51, route: T0({ start: t3, end: i4, side: o3, boundary: n2, amount: l3, targetAxisValue: s2 }) });
  }
  return d2;
};
var A0 = (e51, t2, n2) => {
  switch (n2) {
    case "left":
      return e51.x - t2.minX;
    case "right":
      return t2.maxX - e51.x;
    case "top":
      return t2.maxY - e51.y;
    case "bottom":
      return e51.y - t2.minY;
  }
};
var O0 = (e51, t2, n2) => {
  const o3 = ((e52) => {
    const t3 = e52.route ?? [];
    if (t3.length === 0)
      return [];
    const n3 = [];
    for (let e53 = 0;e53 < t3.length; e53 += 1) {
      const o4 = t3[e53];
      if (!o4)
        continue;
      e53 === 0 || e53 === t3.length - 1 || n3.push(o4);
      const i3 = t3[e53 + 1];
      i3 && n3.push({ x: (o4.x + i3.x) / 2, y: (o4.y + i3.y) / 2 });
    }
    return n3;
  })(e51);
  return o3.length === 0 ? Number.POSITIVE_INFINITY : o3.reduce((e52, o4) => Math.min(e52, A0(o4, t2, n2)), Number.POSITIVE_INFINITY);
};
var k0 = (e51, t2, n2 = []) => {
  const o3 = e51.route ?? [], i3 = [], r3 = new Set, s2 = t2.length === 0 || t2.includes("via");
  if (o3.length === 2)
    return [0, 1];
  const a3 = (e52) => {
    if (e52 <= 0 || e52 >= o3.length - 1)
      return;
    if (r3.has(e52))
      return;
    const n3 = o3[e52];
    n3 && (s2 || t2.includes(PK(n3))) && (r3.add(e52), i3.push(e52));
  };
  if (n2.length > 0)
    for (const e52 of n2)
      a3(e52);
  else
    for (let e52 = 1;e52 < o3.length - 1; e52 += 1)
      a3(e52);
  for (let e52 = 0;e52 < i3.length; e52 += 1) {
    const t3 = i3[e52], n3 = o3[t3];
    if (n3)
      for (let e53 = 1;e53 < o3.length - 1; e53 += 1) {
        if (r3.has(e53))
          continue;
        const t4 = o3[e53];
        t4 && (t4.z !== n3.z && EK(t4, n3) && (r3.add(e53), i3.push(e53)));
      }
  }
  return i3.sort((e52, t3) => e52 - t3), i3;
};
var D0 = (e51, t2) => Math.max(0, ...(e51.route ?? []).map((e52) => Math.max(t2.minX - e52.x, e52.x - t2.maxX, t2.minY - e52.y, e52.y - t2.maxY, 0)));
var L0 = (e51, t2, n2, o3) => A0(e51, t2, n2) <= o3 + bK;
var z0 = (e51, t2, n2, o3) => {
  const i3 = e51.route ?? [], r3 = [], s2 = new Set;
  let a3 = 1, c3 = i3.length - 2;
  for (;a3 < i3.length - 1 && EK(i3[a3], i3[0]); )
    a3 += 1;
  for (;c3 > 0 && EK(i3[c3], i3[i3.length - 1]); )
    c3 -= 1;
  for (let e52 = a3;e52 <= c3; e52 += 1)
    L0(i3[e52], t2, n2, o3) && (s2.add(e52), r3.push(e52));
  for (let e52 = 0;e52 < r3.length; e52 += 1) {
    const t3 = i3[r3[e52]];
    if (t3)
      for (let e53 = a3;e53 <= c3; e53 += 1) {
        if (s2.has(e53))
          continue;
        const n3 = i3[e53];
        n3 && (n3.z !== t3.z && EK(n3, t3) && (s2.add(e53), r3.push(e53)));
      }
  }
  return r3.length === 0 && i3.length === 2 && i3.some((e52) => L0(e52, t2, n2, o3)) ? [0, 1] : (r3.sort((e52, t3) => e52 - t3), r3);
};
var B0 = (e51, t2, n2) => {
  const o3 = e51.route ?? [], i3 = n2 === 0 ? o3[0] : o3[o3.length - 1];
  return i3 ? vK.filter((e52) => A0(i3, t2, e52) <= bK) : [];
};
var F0 = (e51, t2, n2) => {
  const o3 = e51.route ?? [], i3 = t2.route ?? [];
  if (o3.length === 0 || i3.length === 0)
    return true;
  for (const t3 of [0, -1]) {
    const o4 = B0(e51, n2, t3);
    if (o4.length === 0)
      continue;
    const r3 = t3 === 0 ? i3[0] : i3[i3.length - 1];
    if (!r3)
      return false;
    for (const e52 of o4)
      if (A0(r3, n2, e52) > bK)
        return false;
  }
  return true;
};
var j0 = (e51, t2) => Math.hypot(t2.x - e51.x, t2.y - e51.y);
var $0 = (e51, t2, n2, o3) => {
  const i3 = e51.route ?? [];
  if (i3.length === 0)
    return "none";
  let r3 = false;
  for (let e52 = 0;e52 < i3.length; e52 += 1) {
    const s2 = i3[e52];
    if (s2 && L0(s2, t2, n2, o3)) {
      if (e52 !== 0 && e52 !== i3.length - 1)
        return "interior";
      r3 = true;
    }
  }
  for (let e52 = 0;e52 < i3.length - 1; e52 += 1) {
    const r4 = i3[e52], s2 = i3[e52 + 1];
    if (r4 && s2 && (L0(r4, t2, n2, o3) && L0(s2, t2, n2, o3) && !(j0(r4, s2) <= bK)))
      return "interior";
  }
  return r3 ? "endpoint" : "none";
};
var Y0 = ({ currentRoutes: e51, routeIndex: t2, side: n2, moveSide: o3 = n2, boundary: i3, margin: r3, moveAmount: s2, geometryCache: a3, fixedCopperGuard: c3 }) => {
  const l3 = e51[t2], h2 = (l3.route?.length ?? 0) === 2, d2 = z0(l3, i3, n2, r3);
  if (d2.length === 0)
    return null;
  const u2 = new Set, p3 = new Map, m2 = new Set, g2 = e51.slice();
  let f2 = false, _2 = "overlap";
  const y2 = new Set([t2]), b2 = new Map([[t2, new Set]]), x2 = new Map([[t2, new Set]]), v2 = [t2];
  let I2 = 0, S2 = null, C = null, P = null, M = null;
  const w = (e52) => new Set(e52.map((e53) => XK(e53))), N = () => S2 || (S2 = QK(e51, u2, r3, a3, p3), S2), R2 = () => P || (P = QK(e51, u2, 0, a3, p3), P), T2 = () => M || (M = QK(g2, u2, 0, a3, p3), M);
  for (;I2 < v2.length && !f2; ) {
    const c4 = v2[I2];
    if (I2 += 1, y2.delete(c4), u2.has(c4))
      continue;
    const l4 = g2[c4], h3 = Array.from(b2.get(c4) ?? []), d3 = Array.from(x2.get(c4) ?? []);
    b2.delete(c4), x2.delete(c4);
    const R3 = c4 === t2 ? z0(l4, i3, n2, r3) : k0(l4, h3, d3);
    if (R3.length === 0) {
      if (c4 === t2)
        return null;
      f2 = true, _2 = "eventual-overlap";
      break;
    }
    const T3 = l4.route ?? [], E3 = c4 === t2 ? undefined : o3 === "left" || o3 === "right" ? (T3[R3[0]]?.x ?? 0) + (o3 === "left" ? s2 : -s2) : (T3[R3[0]]?.y ?? 0) + (o3 === "top" ? -s2 : s2);
    g2[c4] = E0(l4, R3, i3, o3, s2, r3, E3, c4 !== t2), u2.add(c4), p3.set(c4, new Set(R3)), S2 = null, C = null, P = null, M = null, (l4.route?.length ?? 0) === 2 && m2.add(c4);
    const A2 = D0(e51[c4], i3);
    if (D0(g2[c4], i3) > A2 + 0.000001) {
      f2 = true, _2 = "boundary";
      break;
    }
    if (!F0(e51[c4], g2[c4], i3)) {
      f2 = true, _2 = "endpoint-boundary";
      break;
    }
    const O2 = QK(g2, new Set([c4]), r3, a3, new Map([[c4, new Set(R3)]]));
    for (const e52 of O2) {
      if (w(N()).has(XK(e52)))
        continue;
      const [t3, n3] = e52.routeIndexes, o4 = u2.has(t3), i4 = u2.has(n3);
      if (o4 && i4)
        continue;
      const r4 = o4 ? n3 : t3, s3 = o4 ? e52.layers[1] : e52.layers[0], a4 = o4 ? e52.routePointIndexes[1] : e52.routePointIndexes[0];
      if (u2.has(r4) || y2.has(r4)) {
        if (y2.has(r4)) {
          const e53 = b2.get(r4) ?? new Set;
          e53.add(s3), b2.set(r4, e53);
          const t4 = x2.get(r4) ?? new Set;
          for (const e54 of a4)
            t4.add(e54);
          x2.set(r4, t4);
        }
      } else
        y2.add(r4), v2.push(r4), b2.set(r4, new Set([s3])), x2.set(r4, new Set(a4));
    }
  }
  if (!f2 && u2.size > 1) {
    const e52 = w(N()), t3 = w(C || (C = QK(g2, u2, r3, a3, p3), C));
    for (const n3 of t3)
      if (!e52.has(n3)) {
        f2 = true, _2 = "eventual-overlap";
        break;
      }
  }
  if (!f2 && u2.size > 1) {
    const e52 = w(R2()), t3 = w(T2());
    for (const n3 of t3)
      if (!e52.has(n3)) {
        f2 = true, _2 = "eventual-overlap";
        break;
      }
  }
  if (!f2) {
    const t3 = new Set(QK(e51, u2, 0, a3).map((e52) => XK(e52))), n3 = QK(g2, u2, 0, a3);
    for (const e52 of n3) {
      const n4 = XK(e52);
      if (!t3.has(n4)) {
        f2 = true, _2 = "eventual-overlap";
        break;
      }
    }
  }
  if (!f2) {
    const t3 = (({ currentRoutes: e52, candidateRoutes: t4, candidateRouteIndexes: n3, boundary: o4, activeSide: i4 }) => {
      const r4 = vK.filter((e53) => e53 !== i4), s3 = [];
      for (const i5 of n3) {
        const n4 = e52[i5], a4 = t4[i5];
        if (n4 && a4)
          for (const e53 of r4) {
            const t5 = O0(n4, o4, e53), r5 = O0(a4, o4, e53);
            t5 > bK && r5 <= bK && s3.push({ routeIndex: i5, side: e53, previousClearance: t5, nextClearance: r5 });
          }
      }
      return s3;
    })({ currentRoutes: e51, candidateRoutes: g2, candidateRouteIndexes: u2, boundary: i3, activeSide: n2 });
    t3.length > 0 && (f2 = true, _2 = "boundary-touch");
  }
  if (!f2) {
    const t3 = (({ currentRoutes: e52, candidateRoutes: t4, candidateRouteIndexes: n3, geometryCache: o4, currentConflicts: i4, candidateConflicts: r4 }) => {
      const s3 = i4 ?? QK(e52, n3, 0, o4), a4 = r4 ?? QK(t4, n3, 0, o4), c4 = new Set(s3.map((e53) => XK(e53)));
      return a4.filter((e53) => {
        const o5 = XK(e53);
        if (c4.has(o5))
          return false;
        const [i5, r5] = e53.routeIndexes, [s4, a5] = e53.layers, l4 = n3.has(i5), h3 = n3.has(r5);
        if (l4 && h3)
          return false;
        const d3 = l4 ? a5 : s4, u3 = t4[l4 ? r5 : i5];
        return !!u3 && k0(u3, [d3]).length === 0;
      });
    })({ currentRoutes: e51, candidateRoutes: g2, candidateRouteIndexes: u2, geometryCache: a3, currentConflicts: R2(), candidateConflicts: T2() });
    t3.length > 0 && (f2 = true, _2 = "fixed-trace-touch");
  }
  if (!f2) {
    S0({ currentRoutes: e51, candidateRoutes: g2, candidateRouteIndexes: u2, maximumAllowedClearance: Math.min(r3 / 2, xK) }).length > 0 && (f2 = true, _2 = "trace-clearance");
  }
  return !f2 && ((e52, t3, n3, o4, i4, r4) => Array.from(n3).some((n4) => {
    const s3 = e52[n4], a4 = t3[n4];
    return vK.filter((e53) => e53 !== i4).some((e53) => {
      const t4 = $0(s3, o4, e53, r4), n5 = $0(a4, o4, e53, r4);
      return t4 === "none" && n5 !== "none";
    });
  }))(e51, g2, u2, i3, n2, r3) && (f2 = true, _2 = "side-regression"), f2 || !c3 || c3.allows(e51, g2, u2) || (f2 = true, _2 = "fixed-copper-clearance"), { isTwoPointRoute: h2, movableIndexes: d2, candidateRouteIndexes: u2, movedTwoPointRouteIndexes: m2, candidateRoutes: g2, rejected: f2, rejectionReason: _2 };
};
var X0 = (e51, t2, n2, o3, i3) => {
  const r3 = e51.route ?? [];
  if (t2.length === 0)
    return null;
  if (o3 === "top" || o3 === "bottom") {
    const e52 = t2.reduce((e53, t3) => e53 + (r3[t3]?.x ?? n2.center.x), 0) / t2.length;
    return e52 < n2.center.x - i3 / 2 ? "right" : e52 > n2.center.x + i3 / 2 ? "left" : null;
  }
  const s2 = t2.reduce((e52, t3) => e52 + (r3[t3]?.y ?? n2.center.y), 0) / t2.length;
  return s2 > n2.center.y + i3 / 2 ? "bottom" : s2 < n2.center.y - i3 / 2 ? "top" : null;
};
var H0 = ({ side: e51, sample: t2, boundary: n2, margin: o3, repairedRoutes: i3, frames: r3, captureProgressFrames: s2, lockedTwoPointRoutes: a3, geometryCache: c3, fixedCopperGuard: l3, allowTwoPointWithoutObstacle: h2 = false }) => {
  const { hasObstacle: d2, moveAmount: u2 } = R0(t2, n2, e51, o3);
  s2 && r3.push(((e52, t3, n3, o4, i4, r4) => ({ title: `${n3} boundary analysis: move=${i4.toFixed(3)} (${r4 ? "obstacle-side" : "clear-side"})`, routes: e52, activeSide: n3, overlayRects: [w0(t3, n3, o4, "rgba(245, 158, 11, 0.16)", `strip:${n3}`)] }))(fK(i3), n2, e51, o3, u2, d2));
  const p3 = new Set;
  let m2 = 0;
  for (let t3 = 0;t3 < i3.length; t3 += 1) {
    if (p3.has(t3))
      continue;
    if (a3.has(t3))
      continue;
    const g2 = i3[t3];
    if (g2.connectedPadSides?.includes(e51))
      continue;
    if ((g2.route?.length ?? 0) === 2 && !d2 && !h2)
      continue;
    let f2 = Y0({ currentRoutes: i3, routeIndex: t3, side: e51, boundary: n2, margin: o3, moveAmount: u2, geometryCache: c3, fixedCopperGuard: l3 });
    if (f2) {
      if (f2.rejected) {
        const r4 = X0(g2, f2.movableIndexes, n2, e51, o3);
        if (r4) {
          const s3 = Y0({ currentRoutes: i3, routeIndex: t3, side: e51, moveSide: r4, boundary: n2, margin: o3, moveAmount: u2, geometryCache: c3, fixedCopperGuard: l3 });
          s3 && !s3.rejected && (f2 = s3);
        }
      }
      if (s2 && r3.push(N0({ routes: fK(i3), candidateRoutes: f2.candidateRoutes, candidateRouteIndexes: f2.candidateRouteIndexes, originalRoutes: f2.rejected ? undefined : Array.from(f2.candidateRouteIndexes).map((e52) => gK(i3[e52])), boundary: n2, side: e51, margin: o3, rejected: f2.rejected, rejectionReason: f2.rejectionReason })), !f2.rejected) {
        i3.splice(0, i3.length, ...f2.candidateRoutes);
        for (const e52 of f2.movedTwoPointRouteIndexes)
          a3.add(e52);
        m2 += 1;
      }
      p3.add(t3);
    }
  }
  return { movesAccepted: m2 };
};
var V0 = (e51, t2, n2, o3) => L0(e51, t2, n2, o3);
var W0 = (e51, t2, n2, o3) => {
  switch (n2) {
    case "left":
      return { ...e51, x: Math.min(t2.minX + o3, t2.maxX) };
    case "right":
      return { ...e51, x: Math.max(t2.maxX - o3, t2.minX) };
    case "top":
      return { ...e51, y: Math.max(t2.maxY - o3, t2.minY) };
    case "bottom":
      return { ...e51, y: Math.min(t2.minY + o3, t2.maxY) };
  }
};
var G0 = (e51) => `${e51.routeIndexes[0]}:${e51.layers[0]}:${e51.routeIndexes[1]}:${e51.layers[1]}`;
var U0 = (e51) => {
  if (!e51)
    return [];
  const t2 = [e51.connectionName, e51.rootConnectionName].filter((e52) => Boolean(e52));
  return Array.from(new Set(t2));
};
var Z0 = (e51, t2) => {
  const n2 = U0(e51), o3 = U0(t2);
  return n2.length !== 0 && o3.length !== 0 && n2.some((e52) => o3.includes(e52));
};
var q0 = (e51, t2, n2) => e51 ? r0([e51], t2, n2).length : 0;
var J0 = (e51, t2, n2, o3) => {
  const i3 = new Set(QK(e51, new Set([n2]), o3).map(XK));
  return QK(t2, new Set([n2]), o3).some((e52) => !i3.has(XK(e52)));
};
var Q0 = (e51, t2, n2) => r0(e51, t2, n2).length;
var K0 = (e51) => {
  if (!e51)
    return [];
  const t2 = [e51.connectionName, e51.rootConnectionName].filter((e52) => Boolean(e52));
  return Array.from(new Set(t2));
};
var e1 = (e51, t2) => QK(e51, new Set(e51.map((e52, t3) => t3)), xK, t2).filter((t3) => !(t3.layers[0] === "via" && t3.layers[1] === "via" || ((e52, t4) => {
  const n2 = K0(e52), o3 = K0(t4);
  return n2.length !== 0 && o3.length !== 0 && n2.some((e53) => o3.includes(e53));
})(e51[t3.routeIndexes[0]], e51[t3.routeIndexes[1]]))).length;
var t1 = (e51) => {
  const t2 = vK;
  return [...t2.slice(e51 % t2.length), ...t2.slice(0, e51 % t2.length)];
};
var n1 = (e51, t2, n2 = false, o3 = true) => {
  const i3 = s0(e51?.nodeWithPortPoints), r3 = (e51?.nodeHdRoutes ?? []).map(l0), s2 = Math.max(t2 ?? 0.4, 0.05), a3 = new y0(e51?.fixedHdRoutes ?? [], Math.min(s2 / 2, xK), e51?.clearanceObstacles ?? e51?.adjacentObstacles), c3 = i3 && o3 ? ((e52, t3) => e52.map((e53) => {
    const n3 = e53.route ?? [];
    let o4 = false;
    const i4 = n3.map((e54) => {
      let { x: n4, y: i5 } = e54;
      return n4 < t3.minX ? n4 = t3.minX : n4 > t3.maxX && (n4 = t3.maxX), i5 < t3.minY ? i5 = t3.minY : i5 > t3.maxY && (i5 = t3.maxY), n4 === e54.x && i5 === e54.y ? e54 : (o4 = true, { ...e54, x: n4, y: i5 });
    });
    return o4 ? { ...e53, route: i4 } : e53;
  }))(P0(fK(r3), i3), i3) : fK(r3), l3 = o3 && a3.allows(r3, c3, r3.keys()) ? c3 : r3, h2 = fK(l3);
  if (!i3)
    return { boundary: null, baseRoutes: l3, repairedRoutes: h2, margin: s2, frames: [{ title: "HighDensityRepair02 Missing Boundary", routes: h2 }] };
  const d2 = n2 ? [b0(fK(h2), s2)] : [];
  if (o3) {
    const t3 = new WeakMap;
    let o4 = Q0(h2, i3, s2);
    for (let r5 = 0;r5 < 1; r5 += 1) {
      const c5 = new Set;
      let l4 = 0;
      for (const o5 of t1(r5)) {
        const { movesAccepted: u4 } = H0({ side: o5, sample: e51, boundary: i3, frames: d2, margin: s2, repairedRoutes: h2, captureProgressFrames: n2, lockedTwoPointRoutes: c5, geometryCache: t3, fixedCopperGuard: a3, allowTwoPointWithoutObstacle: r5 >= 1 });
        l4 += u4;
      }
      const u3 = Q0(h2, i3, s2);
      if (l4 === 0)
        break;
      if (u3 === 0)
        break;
      if (u3 >= o4)
        break;
      o4 = u3;
    }
    const r4 = fK(h2), c4 = e1(h2, t3);
    (({ routes: e52, boundary: t4, margin: n3, geometryCache: o5, fixedCopperGuard: i4 }) => {
      const r5 = r0(e52, t4, n3);
      if (r5.length === 0)
        return { movesAccepted: 0 };
      const s3 = new Map;
      for (const e53 of r5) {
        const t5 = s3.get(e53.routeIndex) ?? new Set;
        for (const n4 of e53.touchedSides)
          t5.add(n4);
        s3.set(e53.routeIndex, t5);
      }
      const a4 = [0.000008, 0.01, n3 / 4, n3 / 2, n3 + 0.000008];
      let c5 = 0;
      const l4 = (r6, s4, a5) => {
        const c6 = s4.route ?? [];
        if (c6.length < 2)
          return false;
        const l5 = { ...s4, route: x0(c6) };
        if ((l5.route?.length ?? 0) < 2)
          return false;
        const h4 = e52.slice();
        if (h4[r6] = l5, i4 && !i4.allows(e52, h4, [r6]))
          return false;
        if (q0(h4[r6], t4, n3) >= a5)
          return false;
        const d4 = (t5) => Z0(e52[t5.routeIndexes[0]], e52[t5.routeIndexes[1]]), u4 = new Set(QK(e52, new Set([r6]), 0, o5).filter((e53) => !d4(e53)).map(G0));
        return !QK(h4, new Set([r6]), 0, o5).filter((e53) => !d4(e53)).some((e53) => !u4.has(G0(e53))) && !(S0({ currentRoutes: e52, candidateRoutes: h4, candidateRouteIndexes: new Set([r6]), maximumAllowedClearance: Math.min(n3 / 2, xK) }).filter((t5) => !Z0(e52[t5.routeIndexes[0]], e52[t5.routeIndexes[1]])).length > 0 || (e52[r6] = l5, 0));
      }, h3 = (n4, o6, i5, r6) => {
        if (o6.length === 0)
          return false;
        for (const s4 of a4) {
          const a5 = e52[n4], c6 = gK(a5), h4 = c6.route ?? [];
          let d4 = false;
          for (const e53 of k0(a5, [], o6)) {
            const n5 = h4[e53];
            n5 && (h4[e53] = W0(n5, t4, i5, s4), d4 = true);
          }
          if (!d4)
            return false;
          if (l4(n4, c6, r6))
            return true;
        }
        return false;
      }, d3 = (e53, n4) => {
        const o6 = [];
        return n4 === "top" || n4 === "bottom" ? (Math.abs(e53.x - t4.minX) <= bK && o6.push("left"), Math.abs(e53.x - t4.maxX) <= bK && o6.push("right")) : (Math.abs(e53.y - t4.minY) <= bK && o6.push("bottom"), Math.abs(e53.y - t4.maxY) <= bK && o6.push("top")), o6;
      }, u3 = (o6, i5, r6) => {
        const s4 = e52[o6], c6 = s4.route ?? [];
        if (c6.length !== 2)
          return false;
        const [h4, u4] = c6;
        if (!V0(h4, t4, i5, n3))
          return false;
        if (!V0(u4, t4, i5, n3))
          return false;
        const p3 = d3(h4, i5), m2 = d3(u4, i5);
        for (const e53 of a4) {
          let n4 = W0(h4, t4, i5, e53), a5 = W0(u4, t4, i5, e53);
          for (const o7 of p3)
            n4 = W0(n4, t4, o7, e53);
          for (const n5 of m2)
            a5 = W0(a5, t4, n5, e53);
          const c7 = { ...s4, route: [h4, n4, a5, u4] };
          if (l4(o6, c7, r6))
            return true;
        }
        return false;
      };
      for (const [o6, i5] of s3)
        if (e52[o6])
          for (const r6 of i5) {
            let i6 = true;
            for (;i6; ) {
              i6 = false;
              const s4 = e52[o6].route ?? [];
              if (s4.length === 2) {
                const i7 = q0(e52[o6], t4, n3);
                i7 > 0 && u3(o6, r6, i7) && (c5 += 1);
                break;
              }
              if (s4.length < 3)
                break;
              const a5 = q0(e52[o6], t4, n3);
              if (a5 === 0)
                break;
              const l5 = [];
              for (let e53 = 1;e53 < s4.length - 1; e53 += 1) {
                const o7 = s4[e53];
                o7 && V0(o7, t4, r6, n3) && l5.push(e53);
              }
              if (l5.length === 0)
                break;
              if (h3(o6, l5, r6, a5)) {
                c5 += 1, i6 = true;
                continue;
              }
              let d4 = false, p3 = a5, m2 = 0;
              for (;m2 < l5.length; ) {
                let i7 = m2;
                for (;i7 + 1 < l5.length && l5[i7 + 1] === l5[i7] + 1; )
                  i7 += 1;
                h3(o6, l5.slice(m2, i7 + 1), r6, p3) && (c5 += 1, d4 = true, p3 = q0(e52[o6], t4, n3)), m2 = i7 + 1;
              }
              if (!d4) {
                const i7 = e52[o6].route ?? [];
                let s5 = a5;
                for (let a6 = 1;a6 < i7.length - 1; a6 += 1) {
                  const l6 = i7[a6];
                  l6 && V0(l6, t4, r6, n3) && h3(o6, [a6], r6, s5) && (c5 += 1, d4 = true, s5 = q0(e52[o6], t4, n3));
                }
              }
              d4 && (i6 = true);
            }
          }
      for (const [o6, i5] of s3) {
        const r6 = e52[o6];
        if (!r6)
          continue;
        const s4 = r6.route ?? [];
        if (s4.length <= 2)
          continue;
        const a5 = q0(e52[o6], t4, n3);
        if (a5 !== 0)
          for (const l5 of i5) {
            if (!s4.every((e53) => V0(e53, t4, l5, n3)))
              continue;
            const i6 = s4[0]?.z;
            if (!s4.every((e53) => e53.z === i6))
              continue;
            const h4 = { ...r6, route: [s4[0], s4[s4.length - 1]] }, d4 = e52[o6];
            e52[o6] = h4, u3(o6, l5, a5) ? c5 += 1 : e52[o6] = d4;
            break;
          }
      }
    })({ routes: r4, boundary: i3, margin: s2, geometryCache: t3, fixedCopperGuard: a3 });
    e1(r4, t3) <= c4 && h2.splice(0, h2.length, ...r4), (({ routes: e52, boundary: t4, clearanceMargin: n3, fixedCopperGuard: o5 }) => {
      for (let i4 = 0;i4 < e52.length; i4 += 1) {
        const r5 = e52[i4];
        if ((r5.route ?? []).length <= 2)
          continue;
        const s3 = n3, a4 = Math.max(t4.width / 2 - bK, 0), c5 = Math.max(t4.height / 2 - bK, 0), l4 = Math.min(s3, a4), h3 = Math.min(s3, c5), d3 = r5.connectedPadSides ?? [], u3 = t4.minX + (d3.includes("left") ? 0 : l4), p3 = t4.maxX - (d3.includes("right") ? 0 : l4), m2 = t4.minY + (d3.includes("bottom") ? 0 : h3), g2 = t4.maxY - (d3.includes("top") ? 0 : h3), f2 = gK(r5), _2 = f2.route ?? [];
        let y2 = false;
        for (let e53 = 1;e53 < _2.length - 1; e53 += 1) {
          const t5 = _2[e53];
          if (!t5)
            continue;
          const n4 = Math.min(Math.max(t5.x, u3), p3), o6 = Math.min(Math.max(t5.y, m2), g2);
          (Math.abs(n4 - t5.x) > bK || Math.abs(o6 - t5.y) > bK) && (t5.x = n4, t5.y = o6, y2 = true);
        }
        if (!y2)
          continue;
        if (f2.route = x0(_2), (f2.route?.length ?? 0) < 2)
          continue;
        const b2 = fK(e52);
        b2[i4] = f2;
        const x2 = J0(e52, b2, i4, 0), v2 = J0(e52, b2, i4, n3), I2 = S0({ currentRoutes: e52, candidateRoutes: b2, candidateRouteIndexes: new Set([i4]), maximumAllowedClearance: n3 }).length > 0;
        x2 || v2 || I2 || !o5.allows(e52, b2, [i4]) || (e52[i4] = f2);
      }
    })({ routes: h2, boundary: i3, clearanceMargin: s2, fixedCopperGuard: a3 });
  }
  const u2 = (({ routes: e52, fixedRoutes: t3 = [], boundary: n3, fixedCopperGuard: o4, adjacentObstacles: i4 = [], clearanceObstacles: r4 = i4, clearance: s3 = 0.1, boundaryMargin: a4 = 0.2, maxCandidates: c4 }) => {
    let l4 = e52;
    const h3 = new WeakMap, d3 = new h0, u3 = new WeakMap, p3 = new WeakMap, m2 = new WeakMap, g2 = new WeakMap;
    let f2 = u0(l4, s3, r4, t3, undefined, h3, d3, p3, g2);
    const _2 = c4 ?? Math.max(256, 96 * f2.conflicts.length), y2 = { routes: e52, initialConflictCount: f2.conflicts.length, finalConflictCount: f2.conflicts.length, candidateCount: 0 };
    for (;f2.conflicts.length && y2.candidateCount < _2; ) {
      let e53 = false;
      const i5 = new Map(f2.conflicts.map((e54) => [e54.key, e54.penetration]));
      for (const c5 of f2.conflicts) {
        for (const [b2, x2] of [[c5.firstRoute, c5.first], [c5.secondRoute, c5.second]]) {
          if (b2 < 0 || b2 >= l4.length)
            continue;
          const v2 = l4[b2], I2 = new Set([v2.connectionName, v2.rootConnectionName].filter(Boolean)), S2 = r4.filter((e54) => !e54.connectedTo?.some((e55) => I2.has(e55))), C = h3.get(v2);
          let P = m2.get(v2);
          P === undefined && (P = r0([v2], n3, a4).length, m2.set(v2, P));
          let M = u3.get(v2);
          M || (M = new Map, u3.set(v2, M));
          const w = S2.map((e54) => {
            const t4 = M.get(e54);
            if (t4 !== undefined)
              return t4;
            const n4 = Math.min(...C.filter((t5) => !e54.zLayers || e54.zLayers.some((e55) => e55 >= t5.minZ && e55 <= t5.maxZ)).map((t5) => p0(t5, e54)));
            return M.set(e54, n4), n4;
          });
          for (const u4 of [1.01, 2, 4]) {
            const m3 = Math.max(0.01, c5.penetration * u4);
            for (const [c6, u5] of [[1, 0], [-1, 0], [0, 1], [0, -1], [Math.SQRT1_2, Math.SQRT1_2], [-Math.SQRT1_2, Math.SQRT1_2], [Math.SQRT1_2, -Math.SQRT1_2], [-Math.SQRT1_2, -Math.SQRT1_2]]) {
              if (y2.candidateCount >= _2)
                break;
              y2.candidateCount++;
              const I3 = g0(v2, x2, c6 * m3, u5 * m3, n3);
              if (!I3)
                continue;
              if (r0([I3], n3, a4).length > P)
                continue;
              const C2 = [...l4];
              C2[b2] = I3;
              const M2 = u0(C2, s3, r4, t3, { evaluation: f2, changedRoute: b2, routes: l4 }, h3, d3, p3, g2);
              if (M2.conflicts.length > f2.conflicts.length || M2.score >= f2.score - 0.000000000001)
                continue;
              if (M2.conflicts.some((e54) => e54.penetration > (i5.get(e54.key) ?? 0) + bK))
                continue;
              if (!o4.allows(l4, C2, [b2], false))
                continue;
              const N = h3.get(I3);
              if (!S2.some((e54, t4) => Math.min(...N.filter((t5) => !e54.zLayers || e54.zLayers.some((e55) => e55 >= t5.minZ && e55 <= t5.maxZ)).map((t5) => p0(t5, e54))) < Math.min(s3, w[t4]) - bK)) {
                l4 = C2, f2 = M2, e53 = true;
                break;
              }
            }
            if (e53 || y2.candidateCount >= _2)
              break;
          }
          if (e53 || y2.candidateCount >= _2)
            break;
        }
        if (e53 || y2.candidateCount >= _2)
          break;
      }
      if (!e53)
        break;
    }
    return { ...y2, routes: l4, finalConflictCount: f2.conflicts.length };
  })({ fixedRoutes: e51?.fixedHdRoutes, routes: h2, boundary: i3, fixedCopperGuard: a3, adjacentObstacles: e51?.adjacentObstacles, clearanceObstacles: e51?.clearanceObstacles, boundaryMargin: s2 });
  return h2.splice(0, h2.length, ...u2.routes), d2.push(((e52, t3, n3) => ({ title: `HighDensityRepair02 Final State (margin=${n3})`, routes: e52, originalRoutes: t3 }))(fK(h2), fK(l3), s2)), { boundary: i3, baseRoutes: l3, repairedRoutes: h2, frames: d2, margin: s2, clearanceRepairStats: { nodeClearanceInitialConflictCount: u2.initialConflictCount, nodeClearanceFinalConflictCount: u2.finalConflictCount, nodeClearanceCandidateCount: u2.candidateCount } };
};
var o1 = class extends BaseSolver {
  constructor(e51 = {}) {
    super(), this.params = e51, this.showBoundryViolationMarkers = e51.showBoundryViolationMarkers ?? false;
  }
  frames = [];
  traceViolationCounts = new WeakMap;
  clearanceRepairStats = {};
  currentFrameIndex = 0;
  showBoundryViolationMarkers;
  repairedRoutes = [];
  _setup() {
    this.buildFrames();
    const e51 = this.getCurrentBoundryViolationCount(), t2 = this.getCurrentTraceViolationCount();
    this.stats = { ...this.clearanceRepairStats, boundryViolationCount: e51, traceViolationCount: t2, margin: this.params.margin ?? 0.4, frames: this.frames.length, currentFrame: this.currentFrameIndex };
  }
  _step() {
    if (this.frames.length <= 1) {
      const e52 = this.getCurrentBoundryViolationCount(), t3 = this.getCurrentTraceViolationCount();
      return this.showBoundryViolationMarkers = true, this.stats = { ...this.stats, boundryViolationCount: e52, traceViolationCount: t3 }, void (this.solved = true);
    }
    this.currentFrameIndex < this.frames.length - 1 && (this.currentFrameIndex += 1);
    const e51 = this.getCurrentBoundryViolationCount(), t2 = this.getCurrentTraceViolationCount();
    this.stats = { ...this.clearanceRepairStats, boundryViolationCount: e51, traceViolationCount: t2, margin: this.params.margin ?? 0.4, frames: this.frames.length, currentFrame: this.currentFrameIndex, title: this.frames[this.currentFrameIndex]?.title }, this.currentFrameIndex >= this.frames.length - 1 && (this.showBoundryViolationMarkers = true, this.solved = true);
  }
  getConstructorParams() {
    return [this.params];
  }
  getOutput() {
    const e51 = this.getCurrentTraceViolationCount();
    return { ...this.clearanceRepairStats, margin: this.params.margin ?? 0.4, repairedRoutes: this.repairedRoutes, frameCount: this.frames.length, traceViolationCount: e51 };
  }
  setShowBoundryViolationMarkers(e51) {
    this.showBoundryViolationMarkers = e51;
  }
  buildFrames() {
    const e51 = n1(this.params.sample, this.params.margin, this.params.captureProgressFrames ?? false, this.params.repairBoundaryDiagonals ?? true);
    this.clearanceRepairStats = e51.clearanceRepairStats ?? {}, this.frames = e51.frames, this.repairedRoutes = e51.repairedRoutes;
  }
  getCurrentFrame() {
    const e51 = this.params.sample;
    return this.frames[this.currentFrameIndex] ?? { title: "HighDensityRepair02", routes: fK(e51?.nodeHdRoutes ?? []) };
  }
  getBoundryViolationsForFrame(e51) {
    const t2 = s0(this.params.sample?.nodeWithPortPoints);
    return t2 ? r0(e51.routes, t2, this.params.margin ?? 0.4) : [];
  }
  getCurrentBoundryViolationCount() {
    return this.getBoundryViolationsForFrame(this.getCurrentFrame()).length;
  }
  getRouteNetNames(e51) {
    if (!e51)
      return [];
    const t2 = [e51.connectionName, e51.rootConnectionName].filter((e52) => Boolean(e52));
    return Array.from(new Set(t2));
  }
  areRoutesSameNet(e51, t2) {
    const n2 = this.getRouteNetNames(e51), o3 = this.getRouteNetNames(t2);
    return n2.length !== 0 && o3.length !== 0 && n2.some((e52) => o3.includes(e52));
  }
  getCurrentTraceViolationCount() {
    const e51 = this.getCurrentFrame(), t2 = this.traceViolationCounts.get(e51);
    if (t2 !== undefined)
      return t2;
    const n2 = e51.routes, o3 = new Set(n2.map((e52, t3) => t3)), i3 = QK(n2, o3, xK).filter((e52) => !(e52.layers[0] === "via" && e52.layers[1] === "via" || this.areRoutesSameNet(n2[e52.routeIndexes[0]], n2[e52.routeIndexes[1]]))).length;
    return this.traceViolationCounts.set(e51, i3), i3;
  }
  visualize() {
    const e51 = this.params.sample, t2 = e51?.nodeWithPortPoints, n2 = e51?.adjacentObstacles ?? [], o3 = this.getCurrentFrame(), i3 = s0(t2), r3 = i3 && t2?.capacityMeshNodeId ? [{ center: i3.center, width: i3.width, height: i3.height, stroke: "#1d4ed8", fill: "rgba(29, 78, 216, 0.08)", label: t2.capacityMeshNodeId }] : i3 ? [{ center: i3.center, width: i3.width, height: i3.height, stroke: "#1d4ed8", fill: "rgba(29, 78, 216, 0.08)", label: "capacity-node" }] : [], s2 = n2.filter((e52) => e52.center && e52.width && e52.height).map((e52, t3) => ({ center: e52.center, width: e52.width, height: e52.height, stroke: e52.type === "oval" ? "#a855f7" : "#dc2626", fill: e52.type === "oval" ? "rgba(168, 85, 247, 0.12)" : "rgba(220, 38, 38, 0.08)", label: e52.type ? `obstacle:${e52.type}:${t3}` : `obstacle:${t3}` })), a3 = this.showBoundryViolationMarkers && i3 ? this.getBoundryViolationsForFrame(o3).map((e52) => {
      const t3 = e52.end.x - e52.start.x, n3 = e52.end.y - e52.start.y, o4 = Math.max(Math.hypot(t3, n3), 0.2), i4 = Math.abs(t3) >= Math.abs(n3);
      return { center: { x: (e52.start.x + e52.end.x) / 2, y: (e52.start.y + e52.end.y) / 2 }, width: i4 ? o4 : 0.18, height: i4 ? 0.18 : o4, stroke: "#b45309", fill: "rgba(250, 204, 21, 0.45)", label: `boundry-violation:${e52.routeIndex}:${e52.segmentIndex}` };
    }) : [];
    const c3 = this.showBoundryViolationMarkers ? BK(o3.routes, xK) : [], l3 = [...(t2?.portPoints ?? []).map((e52) => ({ x: e52.x, y: e52.y, color: "#0f766e", label: e52.connectionName ?? e52.portPointId ?? "port-point" })), ...o3.routes.flatMap((e52) => e52.route ?? []).map((e52) => ({ x: e52.x, y: e52.y, color: PK(e52) === "bottom" ? _K : "#0ea5e9", label: "" })), ...o3.overlayPoints ?? []], h2 = [...(o3.originalRoutes ?? []).flatMap((e52) => c0(e52).map((e53) => ({ ...e53, strokeColor: "#111111", strokeWidth: Math.max(0.6 * e53.strokeWidth, 0.05), label: `original:${e53.label}` }))), ...o3.routes.filter((e52) => (e52.route?.length ?? 0) >= 2).flatMap((e52) => c0(e52)), ...o3.overlayLines ?? []], d2 = o3.routes.flatMap((e52) => (e52.vias ?? []).map((t3) => ({ center: { x: t3.x, y: t3.y }, radius: (t3.diameter ?? e52.viaDiameter ?? 0.3) / 2, stroke: "#7c3aed", fill: "rgba(124, 58, 237, 0.2)", label: e52.connectionName ? `via:${e52.connectionName}` : "via" })));
    return d2.push(...c3), { coordinateSystem: "cartesian", title: o3.title, rects: [...r3, ...s2, ...o3.overlayRects ?? [], ...a3], points: l3, lines: h2, circles: d2, arrows: o3.overlayArrows };
  }
};
var i1 = (e51, t2, n2, o3) => {
  const i3 = 0.001, r3 = new Set;
  for (const s2 of [t2.route[0], t2.route.at(-1)]) {
    if (!s2)
      continue;
    n2.some((e52) => e52.__zLayers.includes(s2.z) && Math.abs(s2.x - e52.center.x) <= e52.width / 2 + i3 && Math.abs(s2.y - e52.center.y) <= e52.height / 2 + i3 && xo(e52, t2, o3)) && (Math.abs(s2.x - (e51.center.x - e51.width / 2)) <= i3 && r3.add("left"), Math.abs(s2.x - (e51.center.x + e51.width / 2)) <= i3 && r3.add("right"), Math.abs(s2.y - (e51.center.y - e51.height / 2)) <= i3 && r3.add("bottom"), Math.abs(s2.y - (e51.center.y + e51.height / 2)) <= i3 && r3.add("top"));
  }
  return [...r3];
};
var s1 = class extends ni {
  constructor(e51) {
    super(), this.input = e51;
  }
  static solverName = "Pipeline4HighDensityRepairSampleSolver";
  output;
  _step() {
    const e51 = n1(this.input.sample, this.input.margin, false, false);
    if (e51.frames.length !== 1)
      throw new Error("Node repair must complete in one frame");
    this.output = { repairedRoutes: e51.repairedRoutes, clearanceStats: e51.clearanceRepairStats }, this.solved = true;
  }
  getOutput() {
    if (!this.output)
      throw new Error("Node repair sample has not completed");
    return this.output;
  }
};
SolverRuntime.registerSolver(s1);
var a1 = (e51, t2) => e51.minX <= t2.maxX && e51.maxX >= t2.minX && e51.minY <= t2.maxY && e51.maxY >= t2.minY;
var c1 = (e51, t2 = 0) => ({ minX: e51.center.x - e51.width / 2 - t2, maxX: e51.center.x + e51.width / 2 + t2, minY: e51.center.y - e51.height / 2 - t2, maxY: e51.center.y + e51.height / 2 + t2 });
var l1 = (e51) => ({ minX: e51.center.x - e51.width / 2, maxX: e51.center.x + e51.width / 2, minY: e51.center.y - e51.height / 2, maxY: e51.center.y + e51.height / 2 });
var h1 = (e51, t2, n2 = 0) => {
  const o3 = c1(t2, n2);
  return e51.x >= o3.minX && e51.x <= o3.maxX && e51.y >= o3.minY && e51.y <= o3.maxY;
};
var d1 = (e51, t2, n2) => e51.route.length > 0 && t2.some((t3) => ((e52) => (e52.__zLayers?.length ?? e52.layers?.length ?? 0) > 1)(t3) && e51.route.every((e52) => ((e53, t4) => {
  const n3 = t4.width / 2, o3 = t4.height / 2;
  return Math.abs(e53.x - t4.center.x) <= n3 + 0.001 && Math.abs(e53.y - t4.center.y) <= o3 + 0.001;
})(e52, t3)) && xo(t3, e51, n2));
var u1 = (e51, t2, n2) => {
  if (e51.regionId) {
    const n3 = t2.findIndex((t3) => t3.capacityMeshNodeId === e51.regionId);
    if (n3 !== -1)
      return n3;
  }
  const o3 = [...e51.route.map(({ x: e52, y: t3 }) => ({ x: e52, y: t3 })), ...e51.vias.map(({ x: e52, y: t3 }) => ({ x: e52, y: t3 }))];
  for (let e52 = 0;e52 < t2.length; e52++) {
    const i3 = t2[e52];
    if (o3.every((e53) => h1(e53, i3, n2)))
      return e52;
  }
  return -1;
};
var p1 = (e51, t2) => ({ connectionName: e51.connectionName ?? t2.connectionName, rootConnectionName: t2.rootConnectionName, ...t2.startPcbPortId ? { startPcbPortId: t2.startPcbPortId } : {}, ...t2.endPcbPortId ? { endPcbPortId: t2.endPcbPortId } : {}, regionId: e51.capacityMeshNodeId ?? t2.regionId, traceThickness: t2.traceThickness, viaDiameter: e51.viaDiameter ?? t2.viaDiameter, route: e51.route?.map((e52) => ({ x: e52.x, y: e52.y, z: e52.z ?? 0 })) ?? t2.route, vias: e51.vias?.map((e52) => ({ x: e52.x, y: e52.y })) ?? t2.vias, jumpers: t2.jumpers });
var m1 = (e51, t2, n2, o3, i3) => {
  const r3 = c1(e51, n2);
  return t2.search(r3).filter((e52) => a1(r3, l1(e52))).filter((e52) => !i3 || !o3.some((t3) => xo(e52, t3, i3))).map((e52) => ({ type: e52.type, center: e52.center, width: e52.width, height: e52.height }));
};
var g1 = class extends ni {
  repairMargin;
  minimumTraceWidth;
  sampleEntries;
  originalHdRoutes;
  originalNodeWithPortPoints;
  originalObstacles;
  obstacleSHI;
  colorMap;
  connMap;
  repairedRoutesByIndex = new Map;
  activeSampleIndex = 0;
  activeSubSolver = null;
  latestVisualization = {};
  asyncRunning = false;
  constructor(e51) {
    super(), this.repairMargin = e51.repairMargin ?? 0.2, this.minimumTraceWidth = e51.minimumTraceWidth, this.originalHdRoutes = e51.hdRoutes, this.originalNodeWithPortPoints = e51.nodeWithPortPoints, this.originalObstacles = e51.obstacles, this.obstacleSHI = new ZF("flatbush", this.originalObstacles), this.colorMap = e51.colorMap ?? {}, this.connMap = e51.connMap;
    const t2 = new Map;
    for (let n3 = 0;n3 < e51.hdRoutes.length; n3++) {
      if (d1(e51.hdRoutes[n3], e51.obstacles, e51.connMap))
        continue;
      const o4 = u1(e51.hdRoutes[n3], e51.nodeWithPortPoints, this.repairMargin);
      if (o4 === -1)
        continue;
      const i4 = t2.get(o4) ?? [];
      i4.push(n3), t2.set(o4, i4);
    }
    const n2 = ca(e51.obstacles, Math.max(2, ...e51.nodeWithPortPoints.flatMap((e52) => e52.availableZ?.map((e53) => e53 + 1) ?? []))), o3 = e51.hdRoutes.map((t3) => ((e52, t4, n3) => ({ capacityMeshNodeId: e52.regionId, connectionName: e52.connectionName, rootConnectionName: t4?.getNetConnectedToId(e52.connectionName) ?? e52.rootConnectionName, route: e52.route.map((e53) => ({ x: e53.x, y: e53.y, z: e53.z })), traceThickness: Math.max(e52.traceThickness, n3 ?? e52.traceThickness), vias: e52.vias.map((t5) => ({ x: t5.x, y: t5.y, diameter: e52.viaDiameter })), viaDiameter: e52.viaDiameter }))(t3, e51.connMap, e51.minimumTraceWidth)), i3 = new UF(e51.hdRoutes.length);
    for (const [t3, n3] of e51.hdRoutes.entries()) {
      const e52 = [...n3.route, ...n3.vias];
      if (e52.length === 0)
        throw new Error(`High density repair route "${n3.connectionName}" has no points`);
      const r4 = Math.max(o3[t3].traceThickness, n3.viaDiameter) / 2;
      i3.insert({ routeIndex: t3 }, Math.min(...e52.map((e53) => e53.x)) - r4, Math.min(...e52.map((e53) => e53.y)) - r4, Math.max(...e52.map((e53) => e53.x)) + r4, Math.max(...e52.map((e53) => e53.y)) + r4);
    }
    e51.hdRoutes.length > 0 && i3.finish();
    const r3 = Array.from(t2.entries()).map(([t3, r4]) => {
      const s2 = e51.nodeWithPortPoints[t3], a3 = Math.max(...r4.map((t4) => Math.max(o3[t4].traceThickness, e51.hdRoutes[t4].viaDiameter) / 2)), c3 = c1(s2, Math.max(this.repairMargin, a3 + 0.1)), l3 = new Set(r4);
      return { node: s2, routeIndexes: r4, sample: { nodeWithPortPoints: { capacityMeshNodeId: s2.capacityMeshNodeId, center: s2.center, width: s2.width, height: s2.height, portPoints: s2.portPoints.map((e52) => ({ x: e52.x, y: e52.y, z: e52.z, connectionName: e52.connectionName, portPointId: e52.portPointId, prevPortPointId: e52.prevPortPointId, nextPortPointId: e52.nextPortPointId })) }, nodeHdRoutes: r4.map((t4) => ({ ...o3[t4], ...e51.connMap ? { connectedPadSides: i1(s2, e51.hdRoutes[t4], n2, e51.connMap) } : {} })), fixedHdRoutes: i3.search(c3.minX, c3.minY, c3.maxX, c3.maxY).filter(({ routeIndex: e52 }) => !l3.has(e52)).map(({ routeIndex: e52 }) => o3[e52]), clearanceObstacles: n2.filter((e52) => a1(c3, l1(e52))).map((t4) => ({ type: t4.type, center: t4.center, width: t4.width, height: t4.height, zLayers: t4.__zLayers, connectedTo: [...new Set(t4.connectedTo.flatMap((t5) => {
        const n3 = e51.connMap?.getNetConnectedToId(t5);
        return n3 ? [t5, n3] : [t5];
      }))] })), adjacentObstacles: m1(s2, this.obstacleSHI, this.repairMargin, r4.map((t4) => e51.hdRoutes[t4]), e51.connMap) } };
    });
    this.sampleEntries = r3, this.MAX_ITERATIONS = Math.max(1000 * this.sampleEntries.length, 1e5), this.stats = { sampleCount: this.sampleEntries.length, repairedNodeCount: 0, repairedRouteCount: 0 };
  }
  getSolverName() {
    return "Pipeline4HighDensityRepairSolver";
  }
  async solveAsync(e51, t2 = 1 / 0) {
    if (this.asyncRunning)
      throw new Error("High-density repair solveAsync is already running");
    if (this.solved || this.failed || this.iterations >= t2)
      return;
    const n2 = performance.now();
    try {
      if (e51 === undefined)
        return void (t2 === 1 / 0 ? this.solve() : this.solveUntilIteration(t2));
      for (;this.activeSubSolver && !this.solved && !this.failed && this.iterations < t2; )
        this.step();
      if (this.solved || this.failed || this.iterations >= t2)
        return;
      this.asyncRunning = true;
      const n3 = Math.max(0, Math.floor((Math.min(this.MAX_ITERATIONS, t2) - this.iterations) / 2)), o3 = this.sampleEntries.slice(this.activeSampleIndex, this.activeSampleIndex + n3).map((t3) => e51.executeAsync(s1, { sample: t3.sample, margin: this.repairMargin }).then((e52) => ({ type: "result", result: e52 }), (e52) => ({ type: "error", error: e52 })));
      for (const e52 of o3) {
        if (this.iterations + 2 > Math.min(this.MAX_ITERATIONS, t2))
          return this.asyncRunning = false, void this.solveUntilIteration(t2);
        const n4 = await e52;
        if (n4.type === "error")
          throw n4.error;
        this.consumeRepairSample(n4.result), this.iterations += 2;
      }
      this.asyncRunning = false, this.solveUntilIteration(t2);
    } catch (e52) {
      throw this.failed = true, this.error = `High-density repair runtime error: ${e52}`, e52;
    } finally {
      this.asyncRunning = false, this.timeToSolve = performance.now() - n2;
    }
  }
  solveUntilIteration(e51) {
    for (;!this.solved && !this.failed && this.iterations < e51; )
      this.step();
  }
  consumeRepairSample(e51) {
    const t2 = this.sampleEntries[this.activeSampleIndex];
    if (!t2)
      throw new Error("Node repair sample is missing");
    const n2 = { nodeClearanceInitialConflictCount: Number(this.stats.nodeClearanceInitialConflictCount ?? 0) + Number(e51.clearanceStats?.nodeClearanceInitialConflictCount ?? 0), nodeClearanceFinalConflictCount: Number(this.stats.nodeClearanceFinalConflictCount ?? 0) + Number(e51.clearanceStats?.nodeClearanceFinalConflictCount ?? 0), nodeClearanceCandidateCount: Number(this.stats.nodeClearanceCandidateCount ?? 0) + Number(e51.clearanceStats?.nodeClearanceCandidateCount ?? 0) };
    for (let n3 = 0;n3 < t2.routeIndexes.length; n3++) {
      const o3 = t2.routeIndexes[n3], i3 = this.originalHdRoutes[o3], r3 = e51.repairedRoutes[n3];
      this.repairedRoutesByIndex.set(o3, r3 ? p1(r3, i3) : i3);
    }
    this.activeSubSolver = null, this.activeSampleIndex += 1, this.stats = { ...n2, sampleCount: this.sampleEntries.length, repairedNodeCount: this.activeSampleIndex, repairedRouteCount: this.repairedRoutesByIndex.size }, this.activeSampleIndex >= this.sampleEntries.length && (this.solved = true);
  }
  getConstructorParams() {
    return [{ nodeWithPortPoints: this.sampleEntries.map((e51) => e51.node), hdRoutes: this.originalHdRoutes, obstacles: this.originalObstacles, repairMargin: this.repairMargin, minimumTraceWidth: this.minimumTraceWidth, colorMap: this.colorMap, connMap: this.connMap }];
  }
  _step() {
    const e51 = this.sampleEntries[this.activeSampleIndex];
    if (e51)
      if (this.activeSubSolver) {
        if (this.activeSubSolver.step(), this.latestVisualization = this.activeSubSolver.visualize(), this.activeSubSolver.failed)
          return this.failed = true, this.error = this.activeSubSolver.error ?? `High density repair failed for node ${e51.node.capacityMeshNodeId}`, void (this.activeSubSolver = null);
        if (!this.activeSubSolver.solved)
          return;
        this.consumeRepairSample({ repairedRoutes: this.activeSubSolver.getOutput().repairedRoutes, clearanceStats: { nodeClearanceInitialConflictCount: this.activeSubSolver.stats.nodeClearanceInitialConflictCount, nodeClearanceFinalConflictCount: this.activeSubSolver.stats.nodeClearanceFinalConflictCount, nodeClearanceCandidateCount: this.activeSubSolver.stats.nodeClearanceCandidateCount } });
      } else
        this.activeSubSolver = new o1({ repairBoundaryDiagonals: false, sample: e51.sample, margin: this.repairMargin }), this.latestVisualization = this.activeSubSolver.visualize();
    else
      this.solved = true;
  }
  getOutput() {
    return this.originalHdRoutes.map((e51, t2) => this.repairedRoutesByIndex.get(t2) ?? e51);
  }
  visualize() {
    if (this.activeSubSolver)
      return this.activeSubSolver.visualize();
    if (!this.solved)
      return this.latestVisualization;
    const e51 = [], t2 = [];
    for (const n2 of this.getOutput()) {
      const o3 = this.colorMap[n2.connectionName] ?? "#0ea5e9";
      for (let t3 = 0;t3 < n2.route.length - 1; t3++) {
        const i3 = n2.route[t3], r3 = n2.route[t3 + 1];
        i3.z === r3.z && e51.push({ points: [{ x: i3.x, y: i3.y }, { x: r3.x, y: r3.y }], strokeColor: i3.z === 0 ? o3 : Ao(o3, 0.5), strokeWidth: n2.traceThickness, layer: `z${i3.z}`, strokeDash: i3.z !== 0 ? [0.1, 0.3] : undefined });
      }
      for (const e52 of n2.vias)
        t2.push({ center: { x: e52.x, y: e52.y }, radius: n2.viaDiameter / 2, stroke: o3, fill: "rgba(14,165,233,0.12)" });
    }
    return { title: "Pipeline4 High Density Repair", lines: e51, circles: t2 };
  }
};
var f1 = 0.000001;
var _1 = ({ startGap: e51, endGap: t2, segmentGap: n2, requiredGap: o3 }) => {
  const i3 = e51 < o3 && t2 >= o3 - f1 && n2 >= e51 - f1, r3 = t2 < o3 && e51 >= o3 - f1 && n2 >= t2 - f1, s2 = e51 < o3 && t2 < o3 && n2 >= Math.min(e51, t2) - f1;
  return i3 || r3 || s2;
};
var y1 = class {
  minClearance;
  rootsByConnection = new Map;
  sameNetCache = new Map;
  segments = [];
  vias = [];
  segmentIndexesByLayer;
  viaIndex;
  constructor({ hdRoutes: e51, minClearance: t2 = 0.1 }) {
    this.minClearance = t2;
    for (const t3 of e51)
      this.addRoute(t3);
    this.buildSpatialIndexes();
  }
  addRoute(e51) {
    const t2 = this.rootsByConnection.get(e51.connectionName) ?? new Set;
    t2.add(e51.rootConnectionName ?? e51.connectionName), this.rootsByConnection.set(e51.connectionName, t2), this.sameNetCache.clear();
    for (let t3 = 0;t3 < e51.route.length - 1; t3 += 1) {
      const n2 = e51.route[t3], o3 = e51.route[t3 + 1];
      if (n2.z !== o3.z)
        continue;
      if (n2.insideJumperPad && o3.insideJumperPad)
        continue;
      const i3 = { connectionName: e51.connectionName, start: n2, end: o3, traceThickness: e51.traceThickness };
      this.segments.push(i3), this.insertSegmentIntoSpatialIndex(i3);
    }
    for (const t3 of e51.vias) {
      const n2 = { connectionName: e51.connectionName, x: t3.x, y: t3.y, diameter: e51.viaDiameter };
      this.vias.push(n2), this.insertViaIntoSpatialIndex(n2);
    }
  }
  insertSegmentIntoSpatialIndex(e51) {
    if (!this.segmentIndexesByLayer)
      return;
    let t2 = this.segmentIndexesByLayer.get(e51.start.z);
    t2 || (t2 = new GF, this.segmentIndexesByLayer.set(e51.start.z, t2));
    const n2 = e51.traceThickness / 2;
    t2.insert(e51, Math.min(e51.start.x, e51.end.x) - n2, Math.min(e51.start.y, e51.end.y) - n2, Math.max(e51.start.x, e51.end.x) + n2, Math.max(e51.start.y, e51.end.y) + n2);
  }
  insertViaIntoSpatialIndex(e51) {
    if (!this.viaIndex)
      return;
    const t2 = e51.diameter / 2;
    this.viaIndex.insert(e51, e51.x - t2, e51.y - t2, e51.x + t2, e51.y + t2);
  }
  buildSpatialIndexes() {
    this.segmentIndexesByLayer = new Map;
    const e51 = new Map;
    for (const t2 of this.segments) {
      const n2 = e51.get(t2.start.z);
      n2 ? n2.push(t2) : e51.set(t2.start.z, [t2]);
    }
    for (const [t2, n2] of e51) {
      const e52 = new GF;
      e52.bulkLoad(n2.map((e53) => {
        const t3 = e53.traceThickness / 2;
        return { item: e53, minX: Math.min(e53.start.x, e53.end.x) - t3, minY: Math.min(e53.start.y, e53.end.y) - t3, maxX: Math.max(e53.start.x, e53.end.x) + t3, maxY: Math.max(e53.start.y, e53.end.y) + t3 };
      })), this.segmentIndexesByLayer.set(t2, e52);
    }
    this.viaIndex = new GF, this.viaIndex.bulkLoad(this.vias.map((e52) => {
      const t2 = e52.diameter / 2;
      return { item: e52, minX: e52.x - t2, minY: e52.y - t2, maxX: e52.x + t2, maxY: e52.y + t2 };
    }));
  }
  areSameNet(e51, t2) {
    if (e51 === t2)
      return true;
    const n2 = this.sameNetCache.get(e51)?.get(t2);
    if (n2 !== undefined)
      return n2;
    const o3 = this.rootsByConnection.get(e51), i3 = this.rootsByConnection.get(t2);
    let r3 = false;
    if (o3 && i3) {
      for (const e52 of o3)
        if (i3.has(e52)) {
          r3 = true;
          break;
        }
    }
    let s2 = this.sameNetCache.get(e51);
    return s2 || (s2 = new Map, this.sameNetCache.set(e51, s2)), s2.set(t2, r3), r3;
  }
  isSegmentClear({ connectionName: e51, start: t2, end: n2, traceThickness: o3 }) {
    const i3 = o3 / 2, r3 = this.minClearance + i3, s2 = Math.min(t2.x, n2.x) - r3, a3 = Math.min(t2.y, n2.y) - r3, c3 = Math.max(t2.x, n2.x) + r3, l3 = Math.max(t2.y, n2.y) + r3, h2 = this.segmentIndexesByLayer?.get(t2.z)?.search(s2, a3, c3, l3) ?? [];
    for (const o4 of h2) {
      if (this.areSameNet(e51, o4.connectionName))
        continue;
      const r4 = this.minClearance + i3 + o4.traceThickness / 2, s3 = qr(t2, n2, o4.start, o4.end);
      if (s3 < r4 && !_1({ startGap: pe(t2, o4.start, o4.end), endGap: pe(n2, o4.start, o4.end), segmentGap: s3, requiredGap: r4 }))
        return false;
    }
    const d2 = this.viaIndex?.search(s2, a3, c3, l3) ?? [];
    for (const o4 of d2) {
      if (this.areSameNet(e51, o4.connectionName))
        continue;
      const r4 = this.minClearance + i3 + o4.diameter / 2, s3 = pe(o4, t2, n2);
      if (s3 < r4 && !_1({ startGap: Math.hypot(t2.x - o4.x, t2.y - o4.y), endGap: Math.hypot(n2.x - o4.x, n2.y - o4.y), segmentGap: s3, requiredGap: r4 }))
        return false;
    }
    return true;
  }
};
var b1 = 0.000000001;
var x1 = 1.25;
var v1 = (e51, t2) => e51 < t2 ? -1 : e51 > t2 ? 1 : 0;
var I1 = (e51, t2) => v1(e51.z, t2.z) || v1(e51.x, t2.x) || v1(e51.y, t2.y);
var S1 = (e51) => `${e51.z.toFixed(6)}:${e51.x.toFixed(6)}:${e51.y.toFixed(6)}`;
var C1 = (e51) => {
  const t2 = e51.route.map(S1).join("|"), n2 = [...e51.route].reverse().map(S1).join("|");
  return t2 <= n2 ? t2 : n2;
};
var P1 = (e51, t2) => {
  const n2 = e51.connectionName.localeCompare(t2.connectionName);
  if (n2 !== 0)
    return n2;
  const o3 = (e51.rootConnectionName ?? "").localeCompare(t2.rootConnectionName ?? "");
  if (o3 !== 0)
    return o3;
  const i3 = C1(e51).localeCompare(C1(t2));
  return i3 !== 0 ? i3 : v1(e51.traceThickness, t2.traceThickness) || v1(e51.viaDiameter, t2.viaDiameter) || v1(e51.route.length, t2.route.length) || v1(e51.vias.length, t2.vias.length) || v1(e51.jumpers?.length ?? 0, t2.jumpers?.length ?? 0);
};
var M1 = 1e5;
var w1 = 0.001;
var N1 = 1.000000001;
var R1 = ({ terminal: e51, point: t2, pcbPortId: n2, preserveTerminalPcbPortIds: o3 }) => o3 && e51.pcb_port_id && n2 && e51.pcb_port_id !== n2 ? 1 / 0 : me(e51, t2);
var T1 = class extends ni {
  getSolverName() {
    return "SingleHighDensityRouteStitchSolver3";
  }
  mergedHdRoute;
  remainingHdRoutes;
  start;
  end;
  colorMap;
  allowedLayerTransitionPointKeys;
  isStitchSegmentClear;
  stitchClearanceMode;
  isPlanarStitchClear(e51, t2) {
    return this.isStitchSegmentClear({ connectionName: this.mergedHdRoute.connectionName, start: e51, end: t2, traceThickness: this.mergedHdRoute.traceThickness });
  }
  constructor(e51) {
    super();
    const t2 = [...e51.hdRoutes].sort(P1);
    if (this.remainingHdRoutes = t2, this.colorMap = e51.colorMap ?? {}, this.allowedLayerTransitionPointKeys = e51.allowedLayerTransitionPointKeys, this.isStitchSegmentClear = e51.isStitchSegmentClear, this.stitchClearanceMode = e51.stitchClearanceMode, t2.length === 0) {
      this.start = e51.start, this.end = e51.end;
      const n3 = e51.defaultTraceThickness ?? 0.15, o4 = [{ x: e51.start.x, y: e51.start.y, z: e51.start.z }], i4 = [];
      if (e51.start.z !== e51.end.z) {
        if (e51.allowedLayerTransitionPointKeys && !e51.allowedLayerTransitionPointKeys.has(jG(e51.start)))
          return this.failed = true, void (this.error = `Layer transition at ${jG(e51.start)} is not allowed`);
        o4.push({ x: e51.start.x, y: e51.start.y, z: e51.end.z }), i4.push({ x: e51.start.x, y: e51.start.y });
      }
      const r4 = o4[o4.length - 1], s3 = { x: e51.end.x, y: e51.end.y, z: e51.end.z }, a4 = { connectionName: e51.connectionName, start: r4, end: s3, traceThickness: n3 };
      return me(r4, s3) > w1 && !this.isStitchSegmentClear(a4) && this.stitchClearanceMode === "require_clear" ? (this.failed = true, void (this.error = `Terminal stitch for "${e51.connectionName}" violates copper clearance`)) : (o4.push(s3), this.mergedHdRoute = { connectionName: e51.connectionName, ...e51.preserveTerminalPcbPortIds && e51.start.pcb_port_id ? { startPcbPortId: e51.start.pcb_port_id } : {}, ...e51.preserveTerminalPcbPortIds && e51.end.pcb_port_id ? { endPcbPortId: e51.end.pcb_port_id } : {}, rootConnectionName: t2[0]?.rootConnectionName, route: o4, vias: i4, jumpers: [], viaDiameter: e51.defaultViaDiameter ?? 0.3, traceThickness: n3 }, void (this.solved = true));
    }
    const n2 = new Set((e51.preserveTerminalPcbPortIds ? [e51.start.pcb_port_id, e51.end.pcb_port_id] : []).filter((e52) => e52 !== undefined));
    if (e51.preserveTerminalPcbPortIds && e51.start.pcb_port_id && e51.start.pcb_port_id === e51.end.pcb_port_id)
      throw new Error(`SingleHighDensityRouteStitchSolver3 received duplicate PCB terminal "${e51.start.pcb_port_id}" for "${e51.connectionName}"`);
    const o3 = t2.flatMap((e52) => [e52.startPcbPortId, e52.endPcbPortId]).filter((e52) => e52 !== undefined);
    if (n2.size > 0) {
      for (const t3 of o3)
        if (!n2.has(t3) && !e51.allowedTerminalPcbPortIds?.has(t3))
          throw new Error(`SingleHighDensityRouteStitchSolver3 found unknown PCB terminal "${t3}" on "${e51.connectionName}"`);
    }
    let i3 = 1 / 0, r3 = t2[0], s2 = "start-to-end";
    for (const n3 of t2) {
      const t3 = n3.route[0], o4 = n3.route[n3.route.length - 1], a4 = R1({ terminal: e51.start, point: t3, pcbPortId: n3.startPcbPortId, preserveTerminalPcbPortIds: e51.preserveTerminalPcbPortIds }), c4 = R1({ terminal: e51.start, point: o4, pcbPortId: n3.endPcbPortId, preserveTerminalPcbPortIds: e51.preserveTerminalPcbPortIds }), l4 = R1({ terminal: e51.end, point: t3, pcbPortId: n3.startPcbPortId, preserveTerminalPcbPortIds: e51.preserveTerminalPcbPortIds }), h3 = R1({ terminal: e51.end, point: o4, pcbPortId: n3.endPcbPortId, preserveTerminalPcbPortIds: e51.preserveTerminalPcbPortIds }), d3 = Math.min(a4, c4, l4, h3);
      (d3 < i3 - b1 || Math.abs(d3 - i3) <= b1 && P1(n3, r3) < 0) && (i3 = d3, r3 = n3, s2 = Math.min(l4, h3) < Math.min(a4, c4) - b1 || Math.abs(Math.min(l4, h3) - Math.min(a4, c4)) <= b1 && I1(e51.end, e51.start) < 0 ? "end-to-start" : "start-to-end");
    }
    s2 === "start-to-end" ? (this.start = e51.start, this.end = e51.end) : (this.start = e51.end, this.end = e51.start);
    const a3 = r3.route[0], c3 = r3.route[r3.route.length - 1], l3 = R1({ terminal: this.start, point: a3, pcbPortId: r3.startPcbPortId, preserveTerminalPcbPortIds: e51.preserveTerminalPcbPortIds }), h2 = R1({ terminal: this.start, point: c3, pcbPortId: r3.endPcbPortId, preserveTerminalPcbPortIds: e51.preserveTerminalPcbPortIds }), d2 = l3 < h2 - b1 || Math.abs(l3 - h2) <= b1 && I1(a3, c3) <= 0 ? a3 : c3, u2 = d2 === a3 ? r3.startPcbPortId : r3.endPcbPortId;
    if (u2 && this.start.pcb_port_id && u2 !== this.start.pcb_port_id)
      throw new Error(`SingleHighDensityRouteStitchSolver3 terminal identity disagrees with route orientation for "${e51.connectionName}"`);
    this.mergedHdRoute = { connectionName: e51.connectionName, ...e51.preserveTerminalPcbPortIds && this.start.pcb_port_id ? { startPcbPortId: this.start.pcb_port_id } : {}, ...e51.preserveTerminalPcbPortIds && this.end.pcb_port_id ? { endPcbPortId: this.end.pcb_port_id } : {}, rootConnectionName: r3.rootConnectionName, route: [{ x: this.start.x, y: this.start.y, z: d2.z }], vias: [], jumpers: [], viaDiameter: r3.viaDiameter, traceThickness: r3.traceThickness };
  }
  getDisjointedRoute() {
    for (const e51 of this.remainingHdRoutes) {
      if ([e51.route[0], e51.route[e51.route.length - 1]].some((t2) => !this.remainingHdRoutes.some((n2) => {
        if (n2 === e51)
          return false;
        return [n2.route[0], n2.route[n2.route.length - 1]].some((e52) => e52.z === t2.z && me(t2, e52) < 0.001);
      })))
        return { firstRoute: e51 };
    }
    return { firstRoute: this.remainingHdRoutes[0] };
  }
  _step() {
    const e51 = this.mergedHdRoute.route.at(-1), t2 = this.mergedHdRoute.endPcbPortId !== undefined && e51.z === this.end.z && me(e51, this.end) < w1;
    if (this.remainingHdRoutes.length === 0 || t2) {
      const e52 = this.mergedHdRoute.route[this.mergedHdRoute.route.length - 1], t3 = { ...this.end, z: e52.z }, n3 = me(e52, t3);
      if (n3 > w1 && n3 <= x1) {
        if (!this.isPlanarStitchClear(e52, t3) && this.stitchClearanceMode === "require_clear")
          return this.failed = true, void (this.error = `Terminal stitch for "${this.mergedHdRoute.connectionName}" violates copper clearance`);
        this.mergedHdRoute.route.push({ x: this.end.x, y: this.end.y, z: e52.z });
      }
      return void (this.solved = true);
    }
    const n2 = this.mergedHdRoute.route[this.mergedHdRoute.route.length - 1];
    let o3 = -1, i3 = "first", r3 = 1 / 0, s2 = false;
    for (let e52 = 0;e52 < this.remainingHdRoutes.length; e52++) {
      const t3 = this.remainingHdRoutes[e52], a4 = t3.route[0], c4 = t3.route[t3.route.length - 1], l3 = me(n2, a4), h2 = me(n2, c4);
      let d2 = 1 / 0;
      if (n2.z === a4.z) {
        if (l3 < w1)
          d2 = l3;
        else if (l3 <= 1) {
          const e53 = this.isPlanarStitchClear(n2, a4);
          if (e53 || this.stitchClearanceMode === "prefer_clear") {
            d2 = M1 + (e53 ? 0 : N1) + l3;
          } else
            s2 = true;
        }
      } else
        l3 < w1 && (!this.allowedLayerTransitionPointKeys || this.allowedLayerTransitionPointKeys.has(jG(a4))) && (d2 = 1000 + l3);
      d2 < r3 && (r3 = d2, o3 = e52, i3 = "first");
      let u2 = 1 / 0;
      if (n2.z === c4.z) {
        if (h2 < w1)
          u2 = h2;
        else if (h2 <= 1) {
          const e53 = this.isPlanarStitchClear(n2, c4);
          if (e53 || this.stitchClearanceMode === "prefer_clear") {
            u2 = M1 + (e53 ? 0 : N1) + h2;
          } else
            s2 = true;
        }
      } else
        h2 < w1 && (!this.allowedLayerTransitionPointKeys || this.allowedLayerTransitionPointKeys.has(jG(c4))) && (u2 = 1000 + h2);
      u2 < r3 && (r3 = u2, o3 = e52, i3 = "last");
    }
    if (o3 === -1)
      return s2 ? (this.failed = true, void (this.error = `Route stitch for "${this.mergedHdRoute.connectionName}" violates copper clearance`)) : void (this.remainingHdRoutes = []);
    const a3 = this.remainingHdRoutes[o3];
    let c3;
    this.remainingHdRoutes.splice(o3, 1), c3 = i3 === "first" ? a3.route : ((e52) => {
      const t3 = [...e52].reverse().map((e53) => {
        const { toNextSegmentType: t4, toNextSegmentCircuitJsonMetadata: n3, ...o4 } = e53;
        return o4;
      });
      for (let n3 = 0;n3 < e52.length - 1; n3++) {
        const o4 = e52[n3]?.toNextSegmentType;
        if (!o4)
          continue;
        const i4 = e52.length - n3 - 2;
        t3[i4] = { ...t3[i4], toNextSegmentType: o4, ...e52[n3]?.toNextSegmentCircuitJsonMetadata && { toNextSegmentCircuitJsonMetadata: e52[n3].toNextSegmentCircuitJsonMetadata } };
      }
      return t3;
    })(a3.route), c3.length > 0 && me(n2, c3[0]) < w1 && n2.z === c3[0].z && (!c3[0].toNextSegmentType || n2.x === c3[0].x && n2.y === c3[0].y) ? (c3[0].toNextSegmentType && (n2.toNextSegmentType = c3[0].toNextSegmentType, c3[0].toNextSegmentCircuitJsonMetadata && (n2.toNextSegmentCircuitJsonMetadata = c3[0].toNextSegmentCircuitJsonMetadata)), this.mergedHdRoute.route.push(...c3.slice(1))) : this.mergedHdRoute.route.push(...c3), this.mergedHdRoute.vias.push(...a3.vias), a3.jumpers && this.mergedHdRoute.jumpers.push(...a3.jumpers);
  }
  visualize() {
    const e51 = { points: [], lines: [], circles: [], rects: [], title: "Single High Density Route Stitch Solver 3" };
    if (e51.points?.push({ x: this.start.x, y: this.start.y, color: "green", label: "Start" }, { x: this.end.x, y: this.end.y, color: "red", label: "End" }), this.mergedHdRoute && this.mergedHdRoute.route.length > 1) {
      e51.lines?.push({ points: this.mergedHdRoute.route.map((e52) => ({ x: e52.x, y: e52.y })), strokeColor: "green" });
      for (const t2 of this.mergedHdRoute.route)
        e51.points?.push({ x: t2.x, y: t2.y, color: "green" });
      for (const t2 of this.mergedHdRoute.vias)
        e51.circles?.push({ center: { x: t2.x, y: t2.y }, radius: this.mergedHdRoute.viaDiameter / 2, fill: "green" });
      if (this.mergedHdRoute.jumpers && this.mergedHdRoute.jumpers.length > 0) {
        const t2 = fB(this.mergedHdRoute.jumpers, { color: "green", label: this.mergedHdRoute.connectionName });
        e51.rects.push(...t2.rects ?? []), e51.lines.push(...t2.lines ?? []);
      }
    }
    for (const t2 of this.remainingHdRoutes) {
      e51.lines?.push({ points: t2.route.map((e52) => ({ x: e52.x, y: e52.y })), strokeColor: "orange" });
      for (const n2 of t2.route)
        e51.points?.push({ x: n2.x, y: n2.y, color: "orange" });
      for (const n2 of t2.vias)
        e51.circles?.push({ center: { x: n2.x, y: n2.y }, radius: t2.viaDiameter / 2, fill: "orange" });
      if (t2.jumpers && t2.jumpers.length > 0) {
        const n2 = fB(t2.jumpers, { color: "orange", label: t2.connectionName });
        e51.rects.push(...n2.rects ?? []), e51.lines.push(...n2.lines ?? []);
      }
    }
    return e51;
  }
};
var E1 = class {
  constructor(e51 = false) {
    this.preferSameLayerTerminalEndpoints = e51;
  }
  endpointClusters = new Map;
  getEndpointKey(e51, t2) {
    const n2 = this.endpointClusters.get(e51) ?? [];
    let o3, i3 = 1 / 0;
    for (const e52 of n2) {
      if (e52.point.z !== t2.z)
        continue;
      const n3 = me(e52.point, t2);
      n3 <= 0.1 && (n3 < i3 - b1 || Math.abs(n3 - i3) <= b1 && (!o3 || I1(e52.point, o3.point) < 0)) && (o3 = e52, i3 = n3);
    }
    if (o3)
      return o3.key;
    const r3 = `${e51}:endpoint_${n2.length}`;
    return n2.push({ key: r3, point: { x: t2.x, y: t2.y, z: t2.z } }), this.endpointClusters.set(e51, n2), r3;
  }
  getClusters(e51) {
    return this.endpointClusters.get(e51) ?? [];
  }
  getClosestEndpointKey(e51, t2, n2) {
    const o3 = t2.flatMap((e52) => [e52.route[0], e52.route[e52.route.length - 1]]), i3 = o3.filter((e52) => e52.z === n2.z), r3 = this.preferSameLayerTerminalEndpoints && i3.length > 0 ? i3 : o3;
    let s2 = null, a3 = null, c3 = 1 / 0;
    for (const t3 of r3) {
      const o4 = me(n2, t3), i4 = this.getEndpointKey(e51, t3);
      (o4 < c3 - b1 || Math.abs(o4 - c3) <= b1 && (s2 === null || i4.localeCompare(s2) < 0 || i4 === s2 && a3 !== null && I1(t3, a3) < 0)) && (c3 = o4, s2 = i4, a3 = t3);
    }
    return s2;
  }
};
var A1 = (e51, t2, n2) => {
  const o3 = e51.get(t2) ?? [];
  o3.some((e52) => e52.nextHash === n2.nextHash && e52.routeIndex === n2.routeIndex) || (o3.push(n2), e51.set(t2, o3));
};
var O1 = (e51) => {
  const t2 = [...e51.possibleEndpoints].sort(I1), n2 = t2.reduce((t3, n3) => {
    const o4 = me(n3, e51.globalStart), i4 = me(t3, e51.globalStart);
    return o4 < i4 - b1 || Math.abs(o4 - i4) <= b1 && I1(n3, t3) < 0 ? n3 : t3;
  }), o3 = t2.filter((e52) => e52 !== n2), i3 = (o3.length > 0 ? o3 : e51.possibleEndpoints).reduce((t3, n3) => {
    const o4 = me(n3, e51.globalEnd), i4 = me(t3, e51.globalEnd);
    return o4 < i4 - b1 || Math.abs(o4 - i4) <= b1 && I1(n3, t3) < 0 ? n3 : t3;
  });
  return { start: n2, end: i3 };
};
var k1 = (e51) => {
  const t2 = e51.terminals.filter((t3) => t3.z === e51.islandEndpoint.z);
  if (e51.preferSameLayerTerminalEndpoints && t2.length === 0)
    return e51.islandEndpoint;
  const n2 = [...e51.preferSameLayerTerminalEndpoints ? t2 : e51.terminals].sort(I1);
  let o3 = n2[0], i3 = me(e51.islandEndpoint, o3);
  for (const t3 of n2.slice(1)) {
    const n3 = me(e51.islandEndpoint, t3);
    (n3 < i3 - b1 || Math.abs(n3 - i3) <= b1 && I1(t3, o3) < 0) && (o3 = t3, i3 = n3);
  }
  return i3 <= x1 ? o3 : e51.islandEndpoint;
};
var D1 = (e51) => {
  if (e51.hdRoutes.length <= 2)
    return e51.hdRoutes;
  const t2 = [...e51.hdRoutes].sort(P1), n2 = e51.endpointIndex.getClosestEndpointKey(e51.connectionName, t2, e51.start), o3 = e51.endpointIndex.getClosestEndpointKey(e51.connectionName, t2, e51.end);
  if (!n2 || !o3 || n2 === o3)
    return t2;
  const i3 = new Map;
  for (let n3 = 0;n3 < t2.length; n3++) {
    const o4 = t2[n3], r4 = e51.endpointIndex.getEndpointKey(e51.connectionName, o4.route[0]), s3 = e51.endpointIndex.getEndpointKey(e51.connectionName, o4.route[o4.route.length - 1]);
    A1(i3, r4, { nextHash: s3, routeIndex: n3 }), A1(i3, s3, { nextHash: r4, routeIndex: n3 });
  }
  const r3 = [...e51.endpointIndex.getClusters(e51.connectionName)].sort((e52, t3) => I1(e52.point, t3.point));
  for (let e52 = 0;e52 < r3.length; e52++) {
    const t3 = r3[e52];
    for (let n3 = e52 + 1;n3 < r3.length; n3++) {
      const e53 = r3[n3];
      t3.point.z === e53.point.z && (me(t3.point, e53.point) > 1 || (A1(i3, t3.key, { nextHash: e53.key, routeIndex: null }), A1(i3, e53.key, { nextHash: t3.key, routeIndex: null })));
    }
  }
  for (const [e52, n3] of i3.entries())
    i3.set(e52, [...n3].sort((e53, n4) => {
      if (e53.routeIndex === null && n4.routeIndex !== null)
        return 1;
      if (e53.routeIndex !== null && n4.routeIndex === null)
        return -1;
      if (e53.routeIndex !== null && n4.routeIndex !== null) {
        const o4 = P1(t2[e53.routeIndex], t2[n4.routeIndex]);
        if (o4 !== 0)
          return o4;
      }
      return e53.nextHash.localeCompare(n4.nextHash);
    }));
  const s2 = [n2], a3 = new Set([n2]), c3 = new Map;
  for (;s2.length > 0; ) {
    const e52 = s2.shift();
    if (e52 === o3)
      break;
    for (const t3 of i3.get(e52) ?? [])
      a3.has(t3.nextHash) || (a3.add(t3.nextHash), c3.set(t3.nextHash, { prevHash: e52, routeIndex: t3.routeIndex }), s2.push(t3.nextHash));
  }
  if (!a3.has(o3))
    return t2;
  const l3 = [];
  let h2 = o3;
  for (;h2 !== n2; ) {
    const e52 = c3.get(h2);
    if (!e52)
      return t2;
    e52.routeIndex !== null && l3.push(e52.routeIndex), h2 = e52.prevHash;
  }
  if (l3.length === 0)
    return e51.hdRoutes;
  const d2 = l3.reverse().map((e52) => t2[e52]);
  return d2.length > 0 && !e51.canStitchBetweenTerminals({ connectionName: e51.connectionName, hdRoutes: d2, start: e51.start, end: e51.end }) ? t2 : d2;
};
var L1 = class extends ni {
  getSolverName() {
    return "MultipleHighDensityRouteStitchSolver3";
  }
  unsolvedRoutes;
  activeSolver = null;
  mergedHdRoutes = [];
  colorMap = {};
  defaultTraceThickness;
  defaultViaDiameter;
  allowedLayerTransitionPointKeys;
  preserveTerminalPcbPortIds;
  terminalPcbPortIdsByConnection = new Map;
  preferSameLayerTerminalEndpoints;
  endpointIndex;
  clearanceValidator;
  canStitchBetweenTerminals(e51) {
    const t2 = new T1({ connectionName: e51.connectionName, hdRoutes: e51.hdRoutes, start: e51.start, end: e51.end, colorMap: this.colorMap, defaultTraceThickness: this.defaultTraceThickness, defaultViaDiameter: this.defaultViaDiameter, allowedLayerTransitionPointKeys: this.allowedLayerTransitionPointKeys, preserveTerminalPcbPortIds: this.preserveTerminalPcbPortIds, allowedTerminalPcbPortIds: this.terminalPcbPortIdsByConnection.get(e51.connectionName), isStitchSegmentClear: (e52) => this.clearanceValidator.isSegmentClear(e52), stitchClearanceMode: "require_clear" });
    for (;!t2.solved && !t2.failed && t2.iterations < t2.MAX_ITERATIONS; )
      t2.step();
    if (t2.failed)
      return false;
    const n2 = t2.mergedHdRoute.route[0], o3 = t2.mergedHdRoute.route[t2.mergedHdRoute.route.length - 1];
    return n2.z === t2.start.z && o3.z === t2.end.z && me(n2, t2.start) + me(o3, t2.end) <= x1;
  }
  getSharedRootPathRoutes(e51) {
    const t2 = e51.rootConnectionName;
    if (!t2)
      return null;
    const n2 = new Set(e51.hdRoutes), o3 = e51.allHdRoutes.filter((e52) => (e52.rootConnectionName ?? e52.connectionName) === t2);
    if (o3.every((e52) => n2.has(e52)))
      return null;
    const i3 = D1({ connectionName: e51.connectionName, hdRoutes: o3, start: e51.start, end: e51.end, endpointIndex: this.endpointIndex, canStitchBetweenTerminals: (e52) => this.canStitchBetweenTerminals(e52) });
    return !i3.some((e52) => !n2.has(e52)) || i3.length >= o3.length ? null : i3;
  }
  constructor(e51) {
    super(), this.preferSameLayerTerminalEndpoints = e51.preferSameLayerTerminalEndpoints ?? false, this.endpointIndex = new E1(e51.preferSameLayerTerminalEndpoints), this.colorMap = e51.colorMap ?? {}, this.allowedLayerTransitionPointKeys = e51.allowedLayerTransitionPointKeys, this.preserveTerminalPcbPortIds = e51.preserveTerminalPcbPortIds ?? false;
    const t2 = ei({ connections: e51.connections, layerCount: e51.layerCount, obstacles: [] }), n2 = new Map;
    for (const o4 of e51.connections) {
      const e52 = t2.getNetConnectedToId(o4.name) ?? o4.name;
      let i4 = n2.get(e52);
      i4 || (i4 = new Set, n2.set(e52, i4));
      for (const e53 of o4.pointsToConnect)
        e53.pcb_port_id && i4.add(e53.pcb_port_id);
      this.terminalPcbPortIdsByConnection.set(o4.name, i4);
    }
    const o3 = [...e51.hdRoutes].sort(P1);
    this.clearanceValidator = new y1({ hdRoutes: o3 });
    const i3 = o3[0];
    this.defaultTraceThickness = i3?.traceThickness ?? 0.15, this.defaultViaDiameter = i3?.viaDiameter ?? e51.defaultViaDiameter ?? 0.3;
    const r3 = new mB({}), s2 = [], a3 = new Map;
    for (let e52 = 0;e52 < o3.length; e52++) {
      const t3 = o3[e52], n3 = t3.route[0], i4 = t3.route[t3.route.length - 1];
      s2.push([`route_island_${e52}`, this.endpointIndex.getEndpointKey(t3.connectionName, n3), this.endpointIndex.getEndpointKey(t3.connectionName, i4)]);
    }
    r3.addConnections(s2);
    for (const e52 of s2)
      for (const t3 of e52.slice(1))
        a3.set(t3, (a3.get(t3) ?? 0) + 1);
    this.unsolvedRoutes = [];
    const c3 = Array.from(new Set(Object.values(r3.idToNetMap)));
    for (const t3 of c3) {
      const n3 = r3.getIdsConnectedToNet(t3), i4 = o3.filter((e52, t4) => n3.includes(`route_island_${t4}`));
      if (i4.length === 0)
        continue;
      const s3 = e51.connections.find((e52) => e52.name === i4[0].connectionName), c4 = i4.flatMap((e52) => [e52.route[0], e52.route[e52.route.length - 1]]), l4 = new Map, h2 = [];
      for (const e52 of c4) {
        const t4 = this.endpointIndex.getEndpointKey(i4[0].connectionName, e52);
        l4.has(t4) || l4.set(t4, e52), a3.get(t4) === 1 && h2.push(e52);
      }
      const d2 = h2.length > 0 ? h2 : [...l4.values()];
      if (d2.length === 0)
        continue;
      let u2, p3;
      if (d2.length >= 2) {
        const t4 = { ...s3.pointsToConnect[0], z: mo(Io(s3.pointsToConnect[0]), e51.layerCount) }, n4 = { ...s3.pointsToConnect[1], z: mo(Io(s3.pointsToConnect[1]), e51.layerCount) };
        ({ start: u2, end: p3 } = O1({ possibleEndpoints: d2, globalStart: t4, globalEnd: n4 })), me(u2, s3.pointsToConnect[1]) < me(p3, s3.pointsToConnect[0]) && ([u2, p3] = [p3, u2]), u2 = k1({ islandEndpoint: u2, terminals: [t4, n4], preferSameLayerTerminalEndpoints: this.preferSameLayerTerminalEndpoints }), p3 = k1({ islandEndpoint: p3, terminals: [t4, n4], preferSameLayerTerminalEndpoints: this.preferSameLayerTerminalEndpoints });
      } else
        u2 = { ...s3.pointsToConnect[0], z: mo(Io(s3.pointsToConnect[0]), e51.layerCount) }, p3 = { ...s3.pointsToConnect[1], z: mo(Io(s3.pointsToConnect[1]), e51.layerCount) };
      const m2 = D1({ connectionName: i4[0].connectionName, hdRoutes: i4, start: u2, end: p3, endpointIndex: this.endpointIndex, canStitchBetweenTerminals: (e52) => this.canStitchBetweenTerminals(e52) });
      this.unsolvedRoutes.push({ connectionName: i4[0].connectionName, hdRoutes: m2, start: u2, end: p3 });
    }
    const l3 = new Map;
    for (const e52 of this.unsolvedRoutes) {
      const t3 = l3.get(e52.connectionName);
      t3 ? t3.push(e52) : l3.set(e52.connectionName, [e52]);
    }
    this.unsolvedRoutes = Array.from(l3.entries()).flatMap(([t3, n3]) => {
      const i4 = e51.connections.find((e52) => e52.name === t3), r4 = n3.some((e52) => e52.hdRoutes.some((e53) => e53.route.length < 2)), s3 = n3.length > 1 && ((e52) => {
        for (let t4 = 0;t4 < e52.length; t4++)
          for (let n4 = t4 + 1;n4 < e52.length; n4++) {
            const o4 = [e52[t4].start, e52[t4].end], i5 = [e52[n4].start, e52[n4].end];
            for (const e53 of o4)
              for (const t5 of i5)
                if (e53.z === t5.z && me(e53, t5) <= 1)
                  return true;
          }
        return false;
      })(n3);
      if (!i4)
        return n3;
      const a4 = { ...i4.pointsToConnect[0], z: mo(Io(i4.pointsToConnect[0]), e51.layerCount) }, c4 = { ...i4.pointsToConnect[1], z: mo(Io(i4.pointsToConnect[1]), e51.layerCount) }, l4 = n3.flatMap((e52) => e52.hdRoutes), h2 = n3.length > 1 ? this.getSharedRootPathRoutes({ connectionName: t3, rootConnectionName: i4.__rootConnectionNames?.[0] ?? l4[0]?.rootConnectionName, hdRoutes: l4, allHdRoutes: o3, start: a4, end: c4 }) : null;
      return r4 || s3 || h2 ? [{ connectionName: t3, hdRoutes: h2 ?? D1({ connectionName: t3, hdRoutes: l4, start: a4, end: c4, endpointIndex: this.endpointIndex, canStitchBetweenTerminals: (e52) => this.canStitchBetweenTerminals(e52) }), start: a4, end: c4 }] : n3;
    }), this.MAX_ITERATIONS = 1e5;
  }
  _step() {
    if (this.activeSolver)
      return this.activeSolver.step(), void (this.activeSolver.solved ? (this.activeSolver instanceof T1 && (this.clearanceValidator.addRoute(this.activeSolver.mergedHdRoute), this.mergedHdRoutes.push(this.activeSolver.mergedHdRoute)), this.activeSolver = null) : this.activeSolver.failed && (this.failed = true, this.error = this.activeSolver.error));
    const e51 = this.unsolvedRoutes.pop();
    if (!e51) {
      const e52 = new Set;
      for (const t2 of this.mergedHdRoutes)
        t2.startPcbPortId && t2.endPcbPortId && e52.add(t2.connectionName);
      return this.mergedHdRoutes = this.mergedHdRoutes.filter((t2) => !e52.has(t2.connectionName) || Boolean(t2.startPcbPortId && t2.endPcbPortId)), void (this.solved = true);
    }
    this.activeSolver = new T1({ connectionName: e51.connectionName, hdRoutes: e51.hdRoutes, start: e51.start, end: e51.end, colorMap: this.colorMap, defaultTraceThickness: this.defaultTraceThickness, defaultViaDiameter: this.defaultViaDiameter, allowedLayerTransitionPointKeys: this.allowedLayerTransitionPointKeys, preserveTerminalPcbPortIds: this.preserveTerminalPcbPortIds, allowedTerminalPcbPortIds: this.terminalPcbPortIdsByConnection.get(e51.connectionName), isStitchSegmentClear: (e52) => this.clearanceValidator.isSegmentClear(e52), stitchClearanceMode: "prefer_clear" });
  }
  visualize() {
    const e51 = { points: [], lines: [], circles: [], rects: [], title: "Multiple High Density Route Stitch Solver 3" };
    if (this.activeSolver) {
      const t2 = this.activeSolver.visualize();
      t2.points?.length && e51.points?.push(...t2.points), t2.lines?.length && e51.lines?.push(...t2.lines), t2.circles?.length && e51.circles?.push(...t2.circles), t2.rects?.length && (e51.rects || (e51.rects = []), e51.rects.push(...t2.rects));
    }
    for (const [t2, n2] of this.mergedHdRoutes.entries()) {
      const o3 = this.colorMap[n2.connectionName] ?? `hsl(120, 100%, ${40 + 10 * t2 % 40}%)`;
      for (let t3 = 0;t3 < n2.route.length - 1; t3++) {
        const i3 = n2.route[t3], r3 = n2.route[t3 + 1], s2 = i3.z !== 0 ? Ao(o3, 0.5) : o3;
        e51.lines?.push({ points: [{ x: i3.x, y: i3.y }, { x: r3.x, y: r3.y }], strokeColor: s2, strokeWidth: n2.traceThickness });
      }
      for (const t3 of n2.route) {
        const n3 = t3.z !== 0 ? Ao(o3, 0.5) : o3;
        e51.points?.push({ x: t3.x, y: t3.y, color: n3 });
      }
      for (const t3 of n2.vias)
        e51.circles?.push({ center: { x: t3.x, y: t3.y }, radius: n2.viaDiameter / 2, fill: o3 });
      if (n2.jumpers && n2.jumpers.length > 0) {
        const t3 = fB(n2.jumpers, { color: o3, label: n2.connectionName });
        e51.rects.push(...t3.rects ?? []), e51.lines.push(...t3.lines ?? []);
      }
    }
    return e51;
  }
};
var z1 = 0.001;
var B1 = (e51) => e51.route_type === "wire";
var F1 = (e51) => e51.route_type === "via";
var j1 = (e51) => e51.route_type === "through_obstacle";
var $1 = (e51, t2, n2) => {
  const o3 = mo(e51, n2), i3 = mo(t2, n2), r3 = Math.min(o3, i3), s2 = Math.max(o3, i3);
  return Array.from({ length: s2 - r3 + 1 }, (e52, t3) => Co(r3 + t3, n2));
};
var Y1 = ({ obstacleId: e51, start: t2, end: n2, width: o3, layer: i3, connectedTo: r3 }) => {
  const s2 = n2.x - t2.x, a3 = n2.y - t2.y, c3 = Math.hypot(s2, a3);
  return c3 <= z1 ? null : { obstacleId: e51, type: "rect", layers: [i3], center: { x: (t2.x + n2.x) / 2, y: (t2.y + n2.y) / 2 }, width: c3, height: Math.max(o3, z1), ccwRotationDegrees: 180 * Math.atan2(a3, s2) / Math.PI, connectedTo: r3 };
};
function X1(e51) {
  if (!e51)
    return e51;
  const t2 = ((e52) => {
    if (!e52)
      return [];
    const t3 = [], n2 = Yo(e52);
    for (const [o3, i3] of (e52.traces ?? []).entries()) {
      const r3 = i3.connectsTo ?? [];
      for (let s2 = 0;s2 < i3.route.length; s2++) {
        const a3 = i3.route[s2];
        if (F1(a3)) {
          const c3 = a3.via_diameter ?? n2.padDiameter;
          t3.push({ obstacleId: `trace_obstacle_${i3.pcb_trace_id}_${o3}_${s2}_via`, type: "rect", layers: $1(a3.from_layer, a3.to_layer, e52.layerCount), center: { x: a3.x, y: a3.y }, width: Math.max(c3, z1), height: Math.max(c3, z1), connectedTo: r3 });
          continue;
        }
        if (j1(a3)) {
          const n3 = Y1({ obstacleId: `trace_obstacle_${i3.pcb_trace_id}_${o3}_${s2}_through`, start: a3.start, end: a3.end, width: a3.width, layer: a3.from_layer, connectedTo: r3 });
          n3 && (n3.layers = $1(a3.from_layer, a3.to_layer, e52.layerCount), t3.push(n3));
        }
      }
      for (let e53 = 0;e53 < i3.route.length - 1; e53++) {
        const n3 = i3.route[e53], s2 = i3.route[e53 + 1];
        if (!B1(n3) || !B1(s2) || n3.layer !== s2.layer)
          continue;
        const a3 = Y1({ obstacleId: `trace_obstacle_${i3.pcb_trace_id}_${o3}_${e53}_wire`, start: n3, end: s2, width: n3.width, layer: n3.layer, connectedTo: r3 });
        a3 && t3.push(a3);
      }
    }
    return t3;
  })(e51);
  return t2.length === 0 ? e51 : { ...e51, obstacles: [...e51.obstacles ?? [], ...t2] };
}
function H1(e51, t2) {
  const n2 = function(e52, t3) {
    const n3 = go(e52.__zLayers ?? e52.zLayers ?? [], t3);
    if (n3.length > 0)
      return n3;
    const o3 = fo(e52.layers, t3);
    if (o3.length > 0)
      return o3;
    throw new Error(`Obstacle "${e52.obstacleId ?? "unknown"}" has no layers on this ${t3}-layer board`);
  }(e51, t2);
  return { ...e51, layers: n2.map((e52) => Co(e52, t2)), zLayers: n2, __zLayers: n2 };
}
function V1(e51) {
  return { ...e51, obstacles: e51.obstacles.map((t2) => H1(t2, e51.layerCount)), jumpers: e51.jumpers?.map((t2) => ({ ...t2, pads: t2.pads.map((t3) => H1(t3, e51.layerCount)) })) };
}
var W1 = (e51) => {
  const t2 = e51.obstacles.filter((t3) => !((e52, t4) => !((e53) => (e53.connectedTo?.length ?? 0) > 0 || (e53.offBoardConnectsTo?.length ?? 0) > 0 || e53.netIsAssignable === true)(e52) && (t4.outline && t4.outline.length >= 3 ? !Se(e52, t4.outline) : !De({ minX: e52.center.x - e52.width / 2, maxX: e52.center.x + e52.width / 2, minY: e52.center.y - e52.height / 2, maxY: e52.center.y + e52.height / 2 }, t4.bounds)))(t3, e51)), n2 = t2.length !== e51.obstacles.length, o3 = n2 && e51.outline && e51.outline.length >= 3 ? ((e52) => {
    if (e52.width && e52.height && e52.center) {
      const t4 = e52.width / 2, n4 = e52.height / 2;
      return { minX: e52.center.x - t4, minY: e52.center.y - n4, maxX: e52.center.x + t4, maxY: e52.center.y + n4, width: e52.width, height: e52.height, center: { x: e52.center.x, y: e52.center.y } };
    }
    if (!e52.outline || e52.outline.length === 0)
      throw new Error("Unable to compute board bounds. pcb_board must include width/height/center or a non-empty outline.");
    let { POSITIVE_INFINITY: t3, POSITIVE_INFINITY: n3, NEGATIVE_INFINITY: o4, NEGATIVE_INFINITY: i3 } = Number;
    for (const r4 of e52.outline)
      t3 = Math.min(t3, r4.x), n3 = Math.min(n3, r4.y), o4 = Math.max(o4, r4.x), i3 = Math.max(i3, r4.y);
    const r3 = o4 - t3, s2 = i3 - n3;
    return { minX: t3, minY: n3, maxX: o4, maxY: i3, width: r3, height: s2, center: { x: t3 + r3 / 2, y: n3 + s2 / 2 } };
  })({ type: "pcb_board", pcb_board_id: "__autorouting_board_outline__", center: { x: 0, y: 0 }, thickness: 1, num_layers: e51.layerCount, material: "fr4", outline: e51.outline }) : e51.bounds;
  return n2 ? { ...e51, obstacles: t2, bounds: o3 } : e51;
};
function G1(e51) {
  const { minX: t2, maxX: n2, minY: o3, maxY: i3 } = e51.bounds;
  for (const r3 of e51.connections)
    if (!r3.isOffBoard) {
      for (const [e52, s2] of r3.pointsToConnect.entries())
        if (!(s2.x >= t2 && s2.x <= n2 && s2.y >= o3 && s2.y <= i3))
          return `Connection "${r3.name}" point "${s2.pointId ?? e52}" at (${s2.x}, ${s2.y}) is outside routing bounds: x [${t2}, ${n2}], y [${o3}, ${i3}]`;
    }
  return null;
}
var U1 = class extends ni {
  constructor(e51, t2 = {}) {
    super(), this.inputSrj = e51, this.visualizationOptions = t2, this.MAX_ITERATIONS = 1;
  }
  outputSrj;
  _step() {
    if (this.error = G1(this.inputSrj), this.error)
      return void (this.failed = true);
    const e51 = V1(this.inputSrj), t2 = X1(e51) ?? e51, n2 = Zr(W1(t2));
    this.outputSrj = V1(n2), this.solved = true;
  }
  getOutputSimpleRouteJson() {
    if (!this.outputSrj)
      throw new Error("PreprocessSimpleRouteJsonSolver has not solved yet");
    return this.outputSrj;
  }
  getConstructorParams() {
    return [this.inputSrj, this.visualizationOptions];
  }
  visualize() {
    return this.outputSrj ? pi(Wo({ ...this.outputSrj, traces: [] }, this.visualizationOptions), nK({ srj: this.outputSrj, visualizationOptions: this.visualizationOptions })) : { lines: [], points: [], rects: [], circles: [] };
  }
};
function Z1(e51, t2, n2, o3 = {}) {
  return { solverName: e51, solverClass: t2, getConstructorParams: n2, onSolved: o3.onSolved };
}
var q1 = class extends ni {
  constructor(e51, t2 = {}) {
    super(), this.srj = e51, this.opts = t2, this.originalSrj = e51, this.opts = { ...t2 };
    const n2 = this.opts;
    if (this.effort = n2.effort ?? 1, this.MAX_ITERATIONS = 1e8 * this.effort, this.maxNodeDimension = n2.maxNodeDimension ?? 16, this.maxNodeRatio = n2.maxNodeRatio ?? 6, this.minNodeArea = n2.minNodeArea ?? 0.1 ** 2, this.setSimpleRouteJson(e51), n2.capacityDepth === undefined) {
      const e52 = this.srj.bounds.maxX - this.srj.bounds.minX, t3 = this.srj.bounds.maxY - this.srj.bounds.minY, o3 = Math.max(e52, t3), i3 = n2.targetMinCapacity ?? 0.5;
      n2.capacityDepth = Fz(o3, i3);
    }
    this.cacheProvider = n2.cacheProvider === undefined ? no() : n2.cacheProvider === null ? null : n2.cacheProvider, this.startTimeOfPhase = {}, this.endTimeOfPhase = {}, this.timeSpentOnPhase = {};
  }
  preprocessSimpleRouteJsonSolver;
  escapeViaLocationSolver;
  netToPointPairsSolver;
  nodeSolver;
  nodeDimensionSubdivisionSolver;
  nodeTargetMerger;
  edgeSolver;
  colorMap;
  highDensityRouteSolver;
  highDensityForceImproveSolver;
  highDensityRepairSolver;
  highDensityStitchSolver;
  globalDrcForceImproveSolver;
  singleLayerNodeMerger;
  strawSolver;
  deadEndSolver;
  traceSimplificationSolver;
  availableSegmentPointSolver;
  portPointPathingSolver;
  multiSectionPortPointOptimizer;
  uniformPortDistributionSolver;
  traceWidthSolver;
  necessaryCrampedPortPointSolver;
  viaDiameter;
  viaHoleDiameter;
  minTraceWidth;
  effort;
  maxNodeDimension;
  maxNodeRatio;
  minNodeArea;
  startTimeOfPhase;
  endTimeOfPhase;
  timeSpentOnPhase;
  activeSubSolver = null;
  connMap;
  srjWithEscapeViaLocations;
  srjWithPointPairs;
  originalSrj;
  capacityNodes = null;
  capacityEdges = null;
  highDensityNodePortPoints;
  cacheProvider = null;
  pipelineDef = [Z1("preprocessSimpleRouteJsonSolver", U1, (e51) => [e51.originalSrj], { onSolved: (e51) => {
    e51.setSimpleRouteJson(e51.preprocessSimpleRouteJsonSolver.getOutputSimpleRouteJson());
  } }), Z1("escapeViaLocationSolver", uK, (e51) => [e51.srj, { viaDiameter: e51.viaDiameter, minTraceWidth: e51.minTraceWidth, obstacleMargin: e51.srj.defaultObstacleMargin ?? 0.15 }], { onSolved: (e51) => {
    e51.srjWithEscapeViaLocations = e51.escapeViaLocationSolver?.getOutputSimpleRouteJson();
  } }), Z1("netToPointPairsSolver", pB, (e51) => {
    const t2 = e51.srjWithEscapeViaLocations ?? e51.srj;
    return [t2, e51.colorMap, ti(t2)];
  }, { onSolved: (e51) => {
    e51.srjWithPointPairs = e51.netToPointPairsSolver?.getNewSimpleRouteJson(), e51.colorMap = Eo(e51.srjWithPointPairs, e51.connMap), e51.connMap = ei(e51.srjWithPointPairs);
  } }), Z1("nodeSolver", Jn, (e51) => [{ simpleRouteJson: e51.srjWithPointPairs, maxGapFillPasses: 4 }], { onSolved: (e51) => {
    e51.capacityNodes = e51.nodeSolver?.getOutput().meshNodes ?? [];
  } }), Z1("nodeDimensionSubdivisionSolver", MZ, (e51) => [e51.capacityNodes, e51.maxNodeDimension, e51.maxNodeRatio, e51.minNodeArea], { onSolved: (e51) => {
    e51.capacityNodes = e51.nodeDimensionSubdivisionSolver?.outputNodes ?? [];
  } }), Z1("edgeSolver", ui, (e51) => [e51.capacityNodes], { onSolved: (e51) => {
    e51.capacityEdges = e51.edgeSolver?.edges;
  } }), Z1("availableSegmentPointSolver", ii, (e51) => [{ nodes: e51.capacityNodes, edges: e51.capacityEdges || [], traceWidth: e51.minTraceWidth, colorMap: e51.colorMap, shouldReturnCrampedPortPoints: true }]), Z1("necessaryCrampedPortPointSolver", FG, (e51) => [{ capacityMeshNodes: e51.capacityNodes, sharedEdgeSegments: e51.availableSegmentPointSolver.getOutput(), simpleRouteJson: e51.srjWithPointPairs }]), Z1("portPointPathingSolver", eK, (e51) => {
    const t2 = e51.necessaryCrampedPortPointSolver?.getOutput() ?? e51.availableSegmentPointSolver.getOutput(), { graph: n2, connections: o3 } = KG({ capacityMeshNodes: e51.capacityNodes, layerCount: e51.srj.layerCount, connectivityMap: e51.connMap, segmentPortPoints: t2.flatMap((e52) => e52.portPoints), simpleRouteJsonConnections: e51.srjWithPointPairs.connections });
    return [{ graph: n2, connections: o3, layerCount: e51.srj.layerCount, effort: Math.min(1, e51.effort), minViaPadDiameter: e51.viaDiameter, flags: { FORCE_CENTER_FIRST: true, RIPPING_ENABLED: true }, weights: { SHUFFLE_SEED: 0, MEMORY_PF_FACTOR: 4, CENTER_OFFSET_DIST_PENALTY_FACTOR: 0, CENTER_OFFSET_FOCUS_SHIFT: 0, NODE_PF_FACTOR: 0, LAYER_CHANGE_COST: 0, RIPPING_PF_COST: 0, NODE_PF_MAX_PENALTY: 100, BASE_CANDIDATE_COST: 0.6, MAX_ITERATIONS_PER_PATH: 0, RANDOM_WALK_DISTANCE: 0, START_RIPPING_PF_THRESHOLD: 0.3, END_RIPPING_PF_THRESHOLD: 1, MAX_RIPS: 1000, RANDOM_RIP_FRACTION: 0.3, STRAIGHT_LINE_DEVIATION_PENALTY_FACTOR: 4, GREEDY_MULTIPLIER: 0.7, MIN_ALLOWED_BOARD_SCORE: -1e4 } }];
  }), Z1("uniformPortDistributionSolver", bo, (e51) => [{ nodeWithPortPoints: e51.portPointPathingSolver?.getOutput().nodesWithPortPoints ?? [], inputNodesWithPortPoints: e51.portPointPathingSolver?.getOutput().inputNodeWithPortPoints ?? [], minTraceWidth: e51.minTraceWidth, obstacles: e51.srj.obstacles, layerCount: e51.srj.layerCount }]), Z1("highDensityRouteSolver", Dz, (e51) => {
    const t2 = e51.uniformPortDistributionSolver?.getOutput() ?? [], n2 = e51.portPointPathingSolver?.getOutput().nodesWithPortPoints ?? [], o3 = (t2.length > 0 ? t2 : n2).map((t3) => Mz(t3) ? { ...t3, availableZ: Array.from({ length: e51.srj.layerCount }, (e52, t4) => t4) } : t3);
    return e51.highDensityNodePortPoints = structuredClone(o3), [{ nodePortPoints: o3, nodePfById: new Map((e51.portPointPathingSolver?.getOutput().inputNodeWithPortPoints ?? []).map((t3) => [t3.capacityMeshNodeId, e51.portPointPathingSolver?.computeNodePf(t3) ?? null])), colorMap: e51.colorMap, connMap: e51.connMap, viaDiameter: e51.viaDiameter, traceWidth: e51.minTraceWidth, obstacleMargin: e51.srj.defaultObstacleMargin ?? 0.15, obstacles: e51.srj.obstacles, layerCount: e51.srj.layerCount, useGrowShrinkHighDensityIntraNodeSolver: true }];
  }), Z1("highDensityForceImproveSolver", SZ, (e51) => [{ nodeWithPortPoints: e51.highDensityNodePortPoints ?? [], hdRoutes: e51.highDensityRouteSolver.routes, colorMap: e51.colorMap, totalStepsPerNode: Math.max(20, Math.round(60 * Math.min(1, e51.effort))), nodeAssignmentMargin: e51.srj.defaultObstacleMargin ?? 0.2 }]), Z1("highDensityRepairSolver", g1, (e51) => [{ nodeWithPortPoints: e51.highDensityNodePortPoints ?? [], hdRoutes: e51.highDensityForceImproveSolver?.getOutput() ?? e51.highDensityRouteSolver.routes, obstacles: e51.srj.obstacles, colorMap: e51.colorMap, repairMargin: e51.srj.defaultObstacleMargin ?? 0.2, minimumTraceWidth: e51.srj.minTraceWidth, connMap: e51.connMap }]), Z1("highDensityStitchSolver", L1, (e51) => [{ connections: e51.srjWithPointPairs.connections, hdRoutes: e51.highDensityRepairSolver?.getOutput() ?? e51.highDensityForceImproveSolver?.getOutput() ?? e51.highDensityRouteSolver.routes, colorMap: e51.colorMap, layerCount: e51.srj.layerCount, defaultViaDiameter: e51.viaDiameter }]), Z1("traceSimplificationSolver", WF, (e51) => [{ hdRoutes: e51.highDensityStitchSolver.mergedHdRoutes, obstacles: e51.srj.obstacles, connMap: e51.connMap, colorMap: e51.colorMap, outline: e51.srj.outline, defaultViaDiameter: e51.viaDiameter, layerCount: e51.srj.layerCount, minTraceToPadEdgeClearance: e51.srj.minTraceToPadEdgeClearance, iterations: 2 }]), Z1("traceWidthSolver", QF, (e51) => [{ hdRoutes: e51.traceSimplificationSolver.simplifiedHdRoutes, obstacles: e51.srj.obstacles, connMap: e51.connMap, colorMap: e51.colorMap, minTraceWidth: e51.minTraceWidth, connection: e51.srj.connections, obstacleMargin: e51.srj.minTraceToPadEdgeClearance ?? 0.15, layerCount: e51.srj.layerCount }]), Z1("globalDrcForceImproveSolver", kN, (e51) => [{ srj: e51.srjWithPointPairs, hdRoutes: e51.traceWidthSolver.getHdRoutesWithWidths(), effort: Math.min(1, e51.effort) }])];
  setSimpleRouteJson(e51) {
    this.srj = e51;
    const t2 = Yo(this.srj);
    this.viaDiameter = t2.padDiameter, this.viaHoleDiameter = t2.holeDiameter, this.minTraceWidth = this.srj.minTraceWidth, this.connMap = ei(this.srj), this.colorMap = Eo(this.srj, this.connMap);
  }
  getConstructorParams() {
    return [this.srj, this.opts];
  }
  currentPipelineStepIndex = 0;
  _step() {
    const e51 = this.pipelineDef[this.currentPipelineStepIndex];
    if (!e51)
      return void (this.solved = true);
    if (this.activeSubSolver)
      return this.activeSubSolver.step(), void (this.activeSubSolver.solved ? (this.endTimeOfPhase[e51.solverName] = performance.now(), this.timeSpentOnPhase[e51.solverName] = this.endTimeOfPhase[e51.solverName] - this.startTimeOfPhase[e51.solverName], e51.onSolved?.(this), this.activeSubSolver = null, this.currentPipelineStepIndex++) : this.activeSubSolver.failed && (this.error = this.activeSubSolver?.error, this.failed = true, this.activeSubSolver = null));
    const t2 = e51.getConstructorParams(this);
    this.activeSubSolver = new e51.solverClass(...t2), this[e51.solverName] = this.activeSubSolver, this.timeSpentOnPhase[e51.solverName] = 0, this.startTimeOfPhase[e51.solverName] = performance.now();
  }
  solveUntilPhase(e51) {
    for (;this.getCurrentPhase() !== e51; )
      this.step();
  }
  getCurrentPhase() {
    return this.pipelineDef[this.currentPipelineStepIndex]?.solverName ?? "none";
  }
  visualize() {
    if (!this.solved && this.activeSubSolver)
      return this.activeSubSolver.visualize();
    const e51 = this.escapeViaLocationSolver?.visualize(), t2 = this.netToPointPairsSolver?.visualize(), n2 = this.nodeSolver?.visualize(), o3 = this.nodeDimensionSubdivisionSolver?.visualize(), i3 = this.nodeTargetMerger?.visualize(), r3 = this.singleLayerNodeMerger?.visualize(), s2 = this.strawSolver?.visualize(), a3 = this.edgeSolver?.visualize(), c3 = this.deadEndSolver?.visualize(), l3 = this.availableSegmentPointSolver?.visualize(), h2 = this.portPointPathingSolver?.visualize(), d2 = this.multiSectionPortPointOptimizer?.visualize(), u2 = this.uniformPortDistributionSolver?.visualize(), p3 = this.highDensityRouteSolver?.visualize(), m2 = this.highDensityForceImproveSolver?.visualize(), g2 = this.highDensityRepairSolver?.visualize(), f2 = this.highDensityStitchSolver?.visualize(), _2 = this.traceSimplificationSolver?.visualize(), y2 = this.necessaryCrampedPortPointSolver?.visualize(), b2 = (this.highDensityRouteSolver?.visualize(), this.originalSrj), x2 = b2.outline, v2 = [];
    if (v2.push({ points: [{ x: b2.bounds?.minX ?? -50, y: b2.bounds?.minY ?? -50 }, { x: b2.bounds?.maxX ?? 50, y: b2.bounds?.minY ?? -50 }, { x: b2.bounds?.maxX ?? 50, y: b2.bounds?.maxY ?? 50 }, { x: b2.bounds?.minX ?? -50, y: b2.bounds?.maxY ?? 50 }, { x: b2.bounds?.minX ?? -50, y: b2.bounds?.minY ?? -50 }], strokeColor: "rgba(255,0,0,0.25)" }), x2 && x2.length >= 2) {
      const e52 = x2.map((e53) => ({ x: e53.x, y: e53.y }));
      e52.push({ ...e52[0] }), v2.push({ points: e52, strokeColor: "rgba(0, 136, 255, 0.95)" });
    }
    const I2 = Lo(b2), S2 = { points: [...b2.connections.flatMap((e52) => e52.pointsToConnect.map((t3) => ({ ...t3, layer: Bo(t3, b2.layerCount), label: `${e52.name} ${t3.pcb_port_id ?? ""}` })))], rects: [...(b2.obstacles ?? []).filter((e52) => !e52.isCopperPour).map((e52) => ({ ...e52, fill: e52.layers?.includes("top") ? "rgba(255,0,0,0.25)" : e52.layers?.includes("bottom") ? "rgba(0,0,255,0.25)" : "rgba(255,0,0,0.25)", layer: jo(e52, b2.layerCount), label: I2(e52) }))], lines: v2 }, C = nK({ srj: b2 }), P = [pi(S2, C), e51, t2, n2, o3, i3, r3, s2, a3, c3, l3, y2, h2, d2, u2, p3 ? pi(S2, p3) : null, m2, g2, f2, _2, this.solved ? pi({ lines: v2 }, nK({ srj: this.originalSrj }), Wo(this.getOutputSimpleRouteJson())) : null].filter(Boolean);
    return pi(...P);
  }
  preview() {
    if (this.highDensityRouteSolver) {
      const e51 = [];
      for (let t2 = this.highDensityRouteSolver.routes.length - 1;t2 >= 0; t2--) {
        const n2 = this.highDensityRouteSolver.routes[t2];
        if (e51.push({ points: n2.route.map((e52) => ({ x: e52.x, y: e52.y })), strokeColor: this.colorMap[n2.connectionName] }), e51.length > 200)
          break;
      }
      return { lines: e51 };
    }
    return this.portPointPathingSolver ? this.portPointPathingSolver.preview() : this.netToPointPairsSolver ? this.netToPointPairsSolver.visualize() : this.escapeViaLocationSolver ? this.escapeViaLocationSolver.visualize() : this.preprocessSimpleRouteJsonSolver ? this.preprocessSimpleRouteJsonSolver.visualize() : {};
  }
  _getOutputHdRoutes() {
    return this.globalDrcForceImproveSolver?.getOutput() ?? this.traceWidthSolver?.getHdRoutesWithWidths() ?? this.traceSimplificationSolver?.simplifiedHdRoutes ?? this.highDensityStitchSolver.mergedHdRoutes;
  }
  getOutputSimplifiedPcbTraces() {
    if (!this.solved || !this.highDensityRouteSolver)
      throw new Error("Cannot get output before solving is complete");
    const e51 = [], t2 = this._getOutputHdRoutes();
    for (const n2 of this.netToPointPairsSolver?.newConnections ?? []) {
      const o3 = n2.__netConnectionName ?? this.originalSrj.connections.find((e52) => e52.name === n2.name)?.__netConnectionName, i3 = t2.filter((e52) => e52.connectionName === n2.name);
      for (let t3 = 0;t3 < i3.length; t3++) {
        const r3 = i3[t3], s2 = { type: "pcb_trace", pcb_trace_id: `${n2.name}_${t3}`, connection_name: o3 ?? n2.__rootConnectionNames?.[0] ?? n2.name, route: Ro(r3, this.srj.layerCount, { connectionPoints: n2.pointsToConnect, defaultViaHoleDiameter: this.viaHoleDiameter, obstacles: this.srj.obstacles, connMap: this.connMap }) };
        e51.push(s2);
      }
    }
    return e51;
  }
  getOutputSimpleRouteJson() {
    return { ...this.originalSrj, traces: this.getOutputSimplifiedPcbTraces() };
  }
};
var Q1 = (e51) => /\/solve\/?$/.test(e51) ? e51.replace(/\/+$/, "") : `${e51.replace(/\/+$/, "")}/solve`;
var K1 = (e51, t2, n2) => {
  const o3 = ((e52) => {
    const t3 = new Map;
    for (const n3 of e52.portPoints)
      n3.rootConnectionName && !t3.has(n3.connectionName) && t3.set(n3.connectionName, n3.rootConnectionName);
    return t3;
  })(e51);
  return t2.map((e52) => ({ connectionName: e52.connectionName, rootConnectionName: e52.rootConnectionName ?? o3.get(e52.connectionName) ?? undefined, traceThickness: e52.traceThickness ?? n2.traceWidth, viaDiameter: e52.viaDiameter ?? n2.viaDiameter, route: (e52.route ?? []).map((e53) => ({ x: e53.x, y: e53.y, z: e53.z, ...e53.insideJumperPad ? { insideJumperPad: true } : {} })), vias: (e52.vias ?? []).map((e53) => ({ x: e53.x, y: e53.y })), ...e52.jumpers ? { jumpers: e52.jumpers } : {} }));
};
var e210 = (e51, t2) => {
  if (e51.length === 0)
    return null;
  const n2 = Math.min(Math.max(t2, 0), 1), o3 = (e51.length - 1) * n2, i3 = Math.floor(o3), r3 = Math.ceil(o3), s2 = e51[i3], a3 = e51[r3];
  return i3 === r3 ? s2 : s2 + (a3 - s2) * (o3 - i3);
};
var t2 = (e51) => new Set(e51.portPoints.map((e52) => e52.connectionName)).size;
var n2 = (e51) => !(t2(e51) < 3) && (e51.availableZ?.length ?? 0) !== 1;
var o22 = (e51) => e51?.MULTI_HEAD_POLYLINE_SOLVER ? "MultiHeadPolyLineIntraNodeSolver3" : e51?.CLOSED_FORM_SINGLE_TRANSITION ? "SingleTransitionIntraNodeSolver" : e51?.CLOSED_FORM_TWO_TRACE_SAME_LAYER ? "TwoCrossingRoutesHighDensitySolver" : e51?.CLOSED_FORM_TWO_TRACE_TRANSITION_CROSSING ? "SingleTransitionCrossingRouteSolver" : e51?.HIGH_DENSITY_A01 ? "HighDensitySolverA01" : e51?.HIGH_DENSITY_A03 ? "HighDensitySolverA03" : "SingleHighDensityRouteSolver6_VertHorzLayer_FutureCost";
var i22 = (e51) => {
  if (e51 instanceof jr) {
    const t4 = o22(e51.hyperParameters);
    return e51.cacheHit ? `${t4} [cached]` : t4;
  }
  if (e51 instanceof Lr)
    return o22(e51.hyperParameters);
  if (e51 && typeof e51 == "object" && "getSolverName" in e51 && typeof e51.getSolverName == "function")
    return e51.getSolverName();
  const t3 = e51?.constructor;
  return typeof t3?.name == "string" ? t3.name : "unknown";
};
var r22 = (e51) => e51.winningSolver ? i22(e51.winningSolver) : i22(e51);
var s2 = class extends ni {
  getSolverName() {
    return "Pipeline5HdCacheHighDensitySolver";
  }
  unsolvedNodePortPoints;
  colorMap;
  connMap;
  viaDiameter;
  traceWidth;
  obstacleMargin;
  obstacles;
  layerCount;
  hdCacheBaseUrl;
  fetchImpl;
  nodePfById;
  routes = [];
  nodeSolveMetadataById = new Map;
  launchedRemoteSolves = false;
  solvedRoutesByNodeIndex = new Map;
  failedNodeResults = [];
  remoteResponseMeasurements = [];
  constructor({ nodePortPoints: e51, colorMap: t3, connMap: n3, viaDiameter: o3, traceWidth: i3, obstacleMargin: r3, obstacles: s3, layerCount: a3, nodePfById: c3, hdCacheBaseUrl: l3, fetchImpl: h2 }) {
    super(), this.unsolvedNodePortPoints = e51, this.colorMap = t3 ?? {}, this.connMap = n3, this.viaDiameter = o3 ?? 0.3, this.traceWidth = i3 ?? 0.15, this.obstacleMargin = r3 ?? 0.15, this.obstacles = s3 ?? [], this.layerCount = a3 ?? 2, this.hdCacheBaseUrl = l3 ?? "https://hd-cache.tscircuit.com", this.fetchImpl = (h2 ?? globalThis.fetch).bind(globalThis), this.nodePfById = c3 instanceof Map ? new Map(c3) : new Map(Object.entries(c3 ?? {})), this.pendingEffects = [], this.stats = { localDirectNodeCount: 0, localSolvedNodeCount: 0, localFallbackNodeCount: 0, remoteFallbackNodeCount: 0, remoteRequestsStarted: 0, remoteRequestsCompleted: 0, remoteResponseSampleCount: 0, remoteKOrderSampleCount: 0, slowestRemoteResponseMs: null, slowestRemoteResponseNodeId: null, p50RemoteResponseMs: null, p50RemoteKOrder: null, p95RemoteKOrder: null, remoteSources: {} };
  }
  computeProgress() {
    return this.unsolvedNodePortPoints.length === 0 ? 1 : this.nodeSolveMetadataById.size / this.unsolvedNodePortPoints.length;
  }
  solveNodeLocally(e51, t3, n3 = {}) {
    const o3 = new xz({ nodeWithPortPoints: e51, colorMap: this.colorMap, connMap: this.connMap, viaDiameter: this.viaDiameter, traceWidth: this.traceWidth, obstacleMargin: this.obstacleMargin, obstacles: this.obstacles, layerCount: this.layerCount });
    if (o3.solve(), o3.failed) {
      const t4 = o3.error ?? `Local intra-node solver failed for ${e51.capacityMeshNodeId}`, i4 = t2(e51);
      return this.failedNodeResults.push({ node: e51, error: n3.remoteFailure && n3.resolution === "local-fallback" ? `Remote solve failed (${n3.remoteFailure}); local fallback failed (${t4})` : t4 }), void this.recordNodeSolveMetadata(e51, { status: "failed", resolution: "failed", solverType: r22(o3), supervisorType: o3.getSolverName(), iterations: o3.iterations, pairCount: i4, routeCount: 0, remoteAttempt: n3.resolution === "local-fallback" ? { attempted: true, endpoint: Q1(this.hdCacheBaseUrl), source: "error", durationMs: n3.remoteDurationMs, error: n3.remoteFailure ?? t4 } : { attempted: false }, error: t4 });
    }
    this.solvedRoutesByNodeIndex.set(t3, o3.solvedRoutes);
    const i3 = t2(e51);
    this.recordNodeSolveMetadata(e51, { status: "solved", resolution: n3.resolution ?? "local", solverType: r22(o3), supervisorType: o3.getSolverName(), iterations: o3.iterations, pairCount: i3, routeCount: o3.solvedRoutes.length, remoteAttempt: n3.resolution === "local-fallback" ? { attempted: true, endpoint: Q1(this.hdCacheBaseUrl), source: "error", durationMs: n3.remoteDurationMs, error: n3.remoteFailure } : { attempted: false } }), n3.resolution === "local-fallback" ? (this.stats.localFallbackNodeCount += 1, this.stats.remoteFallbackNodeCount += 1) : this.stats.localDirectNodeCount += 1, this.stats.localSolvedNodeCount += 1;
  }
  async solveNodeViaHdCache(e51, t3) {
    const n3 = Q1(this.hdCacheBaseUrl), o3 = { "content-type": "application/json" }, i3 = { nodeWithPortPoints: e51 }, r3 = JSON.stringify(i3), s3 = Date.now();
    let a3, c3, l3, h2 = null, d2 = null;
    try {
      const i4 = await this.fetchImpl(n3, { method: "POST", headers: o3, body: r3 });
      if (a3 = i4.status, c3 = i4.ok, l3 = await i4.text(), h2 = Date.now() - s3, d2 = l3 ? JSON.parse(l3) : null, !i4.ok)
        throw new Error(d2?.message ?? l3 ?? `hd-cache request failed with status ${i4.status}`);
      if (!d2?.ok || d2.routes === null)
        throw new Error(d2?.message ?? `hd-cache returned no routes for ${e51.capacityMeshNodeId}`);
      const u3 = K1(e51, d2.routes, { traceWidth: this.traceWidth, viaDiameter: this.viaDiameter });
      this.solvedRoutesByNodeIndex.set(t3, u3), this.recordNodeSolveMetadata(e51, { status: "solved", resolution: "remote", solverType: `hd-cache.tscircuit.com [${d2.source}]`, iterations: null, pairCount: t2(e51), routeCount: u3.length, remoteAttempt: { attempted: true, endpoint: Q1(this.hdCacheBaseUrl), source: d2.source, durationMs: h2 } }), this.recordRemoteSource(d2.source);
    } catch (u3) {
      h2 ??= Date.now() - s3;
      const p3 = ((e52) => e52 instanceof Error ? e52.message : String(e52))(u3);
      this.recordFailedHdCacheRequest({ nodeId: e51.capacityMeshNodeId, pairCount: t2(e51), failedAt: new Date().toISOString(), durationMs: h2, error: p3, url: n3, request: { method: "POST", headers: o3, body: r3, bodyJson: i3 }, response: a3 !== undefined || c3 !== undefined || l3 !== undefined || d2 !== null ? { status: a3, ok: c3, text: l3, body: d2 } : undefined }), this.recordRemoteSource("error"), this.solveNodeLocally(e51, t3, { resolution: "local-fallback", remoteFailure: p3, remoteDurationMs: h2 });
    } finally {
      this.recordRemoteResponseMetrics(e51.capacityMeshNodeId, h2 ?? Date.now() - s3, (u2 = d2?.kOrder, typeof u2 == "number" && Number.isFinite(u2) ? d2.kOrder : null)), this.stats.remoteRequestsCompleted += 1;
    }
    var u2;
  }
  launchRemoteSolves() {
    const e51 = [];
    this.unsolvedNodePortPoints.forEach((t3, n3) => {
      if (!n2(t3))
        return void this.solveNodeLocally(t3, n3);
      const o3 = { name: `hd-cache:${t3.capacityMeshNodeId}`, promise: Promise.resolve() };
      o3.promise = this.solveNodeViaHdCache(t3, n3).finally(() => {
        this.pendingEffects = this.pendingEffects?.filter((e52) => e52 !== o3);
      }), e51.push(o3);
    }), this.pendingEffects = e51, this.stats.remoteRequestsStarted = e51.length;
  }
  recordRemoteSource(e51) {
    this.stats.remoteSources[e51] = (this.stats.remoteSources[e51] ?? 0) + 1;
  }
  recordRemoteResponseMetrics(e51, t3, n3) {
    this.remoteResponseMeasurements.push({ nodeId: e51, durationMs: t3, kOrder: n3 }), this.stats.remoteResponseSampleCount = this.remoteResponseMeasurements.length, this.stats.remoteKOrderSampleCount = this.remoteResponseMeasurements.filter((e52) => e52.kOrder !== null).length;
    let o3 = null;
    for (const e52 of this.remoteResponseMeasurements)
      (!o3 || e52.durationMs > o3.durationMs) && (o3 = e52);
    this.stats.slowestRemoteResponseMs = o3?.durationMs ?? null, this.stats.slowestRemoteResponseNodeId = o3?.nodeId ?? null;
    const i3 = this.remoteResponseMeasurements.map((e52) => e52.durationMs).sort((e52, t4) => e52 - t4);
    this.stats.p50RemoteResponseMs = e210(i3, 0.5);
    const r3 = this.remoteResponseMeasurements.map((e52) => e52.kOrder).filter((e52) => e52 !== null).sort((e52, t4) => e52 - t4);
    this.stats.p50RemoteKOrder = e210(r3, 0.5), this.stats.p95RemoteKOrder = e210(r3, 0.95);
  }
  recordFailedHdCacheRequest(e51) {
    const t3 = (() => {
      if (typeof window == "undefined")
        return null;
      const e52 = window;
      return Array.isArray(e52.__FAILED_HD_CACHE_REQUESTS) || (e52.__FAILED_HD_CACHE_REQUESTS = []), e52.__FAILED_HD_CACHE_REQUESTS;
    })();
    t3 && t3.push(e51);
  }
  recordNodeSolveMetadata(e51, t3) {
    this.nodeSolveMetadataById.set(e51.capacityMeshNodeId, { ...t3, node: e51, nodePf: this.nodePfById.get(e51.capacityMeshNodeId) ?? null });
  }
  ensureFailedNodeMetadata() {
    for (const e51 of this.failedNodeResults)
      this.nodeSolveMetadataById.has(e51.node.capacityMeshNodeId) || this.recordNodeSolveMetadata(e51.node, { status: "failed", resolution: "failed", solverType: "unknown", iterations: null, pairCount: t2(e51.node), routeCount: 0, remoteAttempt: { attempted: n2(e51.node), source: "error", error: e51.error }, error: e51.error });
  }
  getVisibleRoutes() {
    if (this.solved)
      return this.routes;
    const e51 = [];
    for (let t3 = 0;t3 < this.unsolvedNodePortPoints.length; t3++)
      e51.push(...this.solvedRoutesByNodeIndex.get(t3) ?? []);
    return e51;
  }
  createNodeMarkerLabel(e51, t3) {
    return ["hd_node_marker", `node: ${e51}`, `status: ${t3.status}`, `resolution: ${t3.resolution}`, `solver: ${t3.solverType}`, ...t3.supervisorType ? [`supervisor: ${t3.supervisorType}`] : [], ...t3.iterations !== null ? [`iterations: ${t3.iterations}`] : [], `pairCount: ${t3.pairCount}`, `routes: ${t3.routeCount}`, `nodePf: ${t3.nodePf ?? "n/a"}`, "remoteAttempted: " + (t3.remoteAttempt.attempted ? "yes" : "no"), ...t3.remoteAttempt.source ? [`remoteSource: ${t3.remoteAttempt.source}`] : [], ...t3.remoteAttempt.durationMs !== undefined ? [`remoteDurationMs: ${t3.remoteAttempt.durationMs}`] : [], ...t3.remoteAttempt.error ? [`remoteError: ${t3.remoteAttempt.error}`] : [], `portPoints: ${t3.node.portPoints.length}`, ...t3.error ? [`error: ${t3.error}`] : []].join(`
`);
  }
  _step() {
    if (!this.launchedRemoteSolves)
      return this.launchedRemoteSolves = true, void this.launchRemoteSolves();
    if (!((this.pendingEffects?.length ?? 0) > 0)) {
      if (this.failedNodeResults.length > 0) {
        this.ensureFailedNodeMetadata();
        const e51 = this.failedNodeResults[0];
        return this.failed = true, void (this.error = `Failed to solve ${this.failedNodeResults.length} nodes via hd-cache. First failure: ${e51?.node.capacityMeshNodeId} (${e51?.error})`);
      }
      this.routes = [];
      for (let e51 = 0;e51 < this.unsolvedNodePortPoints.length; e51++)
        this.routes.push(...this.solvedRoutesByNodeIndex.get(e51) ?? []);
      this.solved = true;
    }
  }
  visualize() {
    const e51 = { lines: [], points: [], rects: [], circles: [] };
    for (const t3 of this.getVisibleRoutes()) {
      const n3 = mi(t3.route, t3.connectionName, this.colorMap[t3.connectionName]);
      for (const o3 of n3)
        e51.lines.push({ points: o3.points, label: o3.connectionName, strokeColor: o3.z === 0 ? o3.color : Ao(o3.color, 0.75), layer: `z${o3.z}`, strokeWidth: t3.traceThickness, strokeDash: o3.z !== 0 ? "10, 5" : undefined });
      for (const n4 of t3.vias)
        e51.circles.push({ center: n4, layer: "z0,1", radius: t3.viaDiameter / 2, fill: this.colorMap[t3.connectionName], label: `${t3.connectionName} via` });
    }
    for (const [t3, n3] of this.nodeSolveMetadataById) {
      const o3 = n3.node.center.x - n3.node.width / 2, i3 = n3.node.center.x + n3.node.width / 2, r3 = n3.node.center.y - n3.node.height / 2, s3 = n3.node.center.y + n3.node.height / 2, a3 = this.createNodeMarkerLabel(t3, n3), c3 = n3.status === "solved" ? "blue" : "red", l3 = n3.status === "solved" ? 0.03 : 0.08;
      if (e51.lines.push({ points: [{ x: o3, y: r3 }, { x: i3, y: r3 }], layer: "hd_node_boundaries", strokeColor: c3, strokeDash: "6, 4", strokeWidth: l3, label: a3 }, { points: [{ x: i3, y: r3 }, { x: i3, y: s3 }], layer: "hd_node_boundaries", strokeColor: c3, strokeDash: "6, 4", strokeWidth: l3, label: a3 }, { points: [{ x: i3, y: s3 }, { x: o3, y: s3 }], layer: "hd_node_boundaries", strokeColor: c3, strokeDash: "6, 4", strokeWidth: l3, label: a3 }, { points: [{ x: o3, y: s3 }, { x: o3, y: r3 }], layer: "hd_node_boundaries", strokeColor: c3, strokeDash: "6, 4", strokeWidth: l3, label: a3 }), n3.status === "solved")
        e51.points.push({ x: n3.node.center.x, y: n3.node.center.y, color: c3, layer: "hd_node_markers", label: a3 });
      else {
        e51.lines.push({ points: [{ x: 0, y: 0 }, { x: n3.node.center.x, y: n3.node.center.y }], layer: "hd_failed_node_guides", strokeColor: c3, strokeDash: "8, 6", strokeWidth: 0.05, label: a3 });
        const t4 = Math.max(n3.node.width, 1.2), o4 = Math.max(n3.node.height, 1.2), i4 = t4 / 2, r4 = o4 / 2;
        e51.rects.push({ center: n3.node.center, layer: "hd_node_markers", width: t4, height: o4, fill: "rgba(255, 0, 0, 0.3)", stroke: c3, label: a3 }), e51.circles.push({ center: n3.node.center, radius: Math.max(0.6 * Math.max(t4, o4), 1.1), layer: "hd_node_markers", fill: "rgba(255, 0, 0, 0.08)", stroke: c3, label: a3 }), e51.lines.push({ points: [{ x: n3.node.center.x - i4, y: n3.node.center.y - r4 }, { x: n3.node.center.x + i4, y: n3.node.center.y + r4 }], layer: "hd_node_markers", strokeColor: c3, strokeWidth: 0.16, label: a3 }, { points: [{ x: n3.node.center.x - i4, y: n3.node.center.y + r4 }, { x: n3.node.center.x + i4, y: n3.node.center.y - r4 }], layer: "hd_node_markers", strokeColor: c3, strokeWidth: 0.16, label: a3 });
      }
    }
    return e51;
  }
};
var c22 = 0.000000001;
var l22 = Math.PI / 2;
var h2 = (e51, t3) => e51.x * t3.y - e51.y * t3.x;
var d2 = (e51, t3) => e51.x * t3.x + e51.y * t3.y;
var u2 = (e51) => {
  let t3 = e51 % l22;
  return t3 < 0 && (t3 += l22), l22 - t3 < 0.00000001 ? 0 : t3;
};
var p22 = (e51) => {
  const t3 = Math.cos(e51), n3 = Math.sin(e51);
  return { u: { x: t3, y: n3 }, v: { x: -n3, y: t3 } };
};
var m2 = (e51) => {
  let t3 = 0;
  for (let n3 = 0;n3 < e51.length; n3++) {
    const o3 = e51[n3], i3 = e51[(n3 + 1) % e51.length];
    t3 += o3.x * i3.y - i3.x * o3.y;
  }
  return t3 / 2;
};
var g2 = (e51) => Math.abs(m2(e51));
var f2 = (e51) => {
  const t3 = m2(e51);
  if (Math.abs(t3) < c22) {
    const t4 = e51.reduce((e52, t5) => ({ x: e52.x + t5.x, y: e52.y + t5.y }), { x: 0, y: 0 });
    return { x: t4.x / Math.max(1, e51.length), y: t4.y / Math.max(1, e51.length) };
  }
  let n3 = 0, o3 = 0;
  for (let t4 = 0;t4 < e51.length; t4++) {
    const i4 = e51[t4], r3 = e51[(t4 + 1) % e51.length], s3 = i4.x * r3.y - r3.x * i4.y;
    n3 += (i4.x + r3.x) * s3, o3 += (i4.y + r3.y) * s3;
  }
  const i3 = 1 / (6 * t3);
  return { x: n3 * i3, y: o3 * i3 };
};
var _2 = (e51) => m2(e51) >= 0 ? [...e51] : [...e51].reverse();
var y2 = (e51, t3) => {
  const n3 = new Set;
  n3.add(0);
  for (let e52 = 0;e52 < 90; e52++)
    n3.add(e52 / 90 * l22);
  for (let t4 = 0;t4 < e51.length; t4++) {
    const o4 = e51[t4], i4 = e51[(t4 + 1) % e51.length], r4 = Math.atan2(i4.y - o4.y, i4.x - o4.x);
    n3.add(u2(r4)), n3.add(u2(r4 + l22));
  }
  const o3 = (n4) => {
    const o4 = ((e52, t4 = f2(e52), n5 = 0) => {
      const o5 = _2(e52), { u: i4, v: r4 } = p22(n5), s4 = o5.map((e53, n6) => {
        const s5 = o5[(n6 + 1) % o5.length], a5 = s5.x - e53.x, c5 = s5.y - e53.y, l5 = { x: a5, y: c5 };
        return { hxCoeff: Math.abs(h2(l5, i4)), hyCoeff: Math.abs(h2(l5, r4)), limit: a5 * (t4.y - e53.y) - c5 * (t4.x - e53.x) };
      });
      if (s4.some((e53) => e53.limit < -0.0000001))
        throw new Error("Projected rect center is outside polygon");
      let a4 = Number.POSITIVE_INFINITY;
      for (const e53 of s4)
        e53.hxCoeff > c22 && (a4 = Math.min(a4, e53.limit / e53.hxCoeff));
      if (!Number.isFinite(a4) || a4 <= c22)
        return { center: t4, width: 0.000001, height: 0.000001, ccwRotationRadians: n5, ccwRotationDegrees: 180 * n5 / Math.PI };
      const c4 = (e53) => {
        let t5 = Number.POSITIVE_INFINITY;
        for (const n6 of s4) {
          const o6 = n6.limit - n6.hxCoeff * e53;
          if (o6 < -0.00000001)
            return 0;
          n6.hyCoeff > c22 && (t5 = Math.min(t5, o6 / n6.hyCoeff));
        }
        return Number.isFinite(t5) ? Math.max(0, t5) : 0;
      }, l4 = (e53) => e53 * c4(e53);
      let h3 = 0, d3 = a4;
      for (let e53 = 0;e53 < 80; e53++) {
        const e54 = h3 + (d3 - h3) / 3, t5 = d3 - (d3 - h3) / 3;
        l4(e54) < l4(t5) ? h3 = e54 : d3 = t5;
      }
      const u3 = (h3 + d3) / 2, p3 = c4(u3);
      return { center: t4, width: Math.max(0.000001, 2 * u3), height: Math.max(0.000001, 2 * p3), ccwRotationRadians: n5, ccwRotationDegrees: 180 * n5 / Math.PI };
    })(e51, t3, n4);
    return { rect: o4, area: o4.width * o4.height };
  };
  let i3 = o3(0), r3 = 0;
  for (const e52 of n3) {
    const t4 = o3(e52);
    t4.area > i3.area + 0.00000001 && (i3 = t4, r3 = e52);
  }
  const s3 = l22 / 90;
  let a3 = r3 - s3, c3 = r3 + s3;
  for (let e52 = 0;e52 < 60; e52++) {
    const e53 = a3 + (c3 - a3) / 3, t4 = c3 - (c3 - a3) / 3;
    o3(e53).area < o3(t4).area ? a3 = e53 : c3 = t4;
  }
  const l3 = o3(u2((a3 + c3) / 2));
  return l3.area > i3.area + 0.00000001 ? l3.rect : i3.rect;
};
var b2 = (e51, t3, n3, o3) => {
  const i3 = o3.x - n3.x, r3 = o3.y - n3.y, s3 = t3.x * r3 - t3.y * i3;
  if (Math.abs(s3) < c22)
    return;
  const a3 = n3.x - e51.x, c3 = n3.y - e51.y, l3 = (a3 * r3 - c3 * i3) / s3, h3 = (a3 * t3.y - c3 * t3.x) / s3;
  return l3 < -0.00000001 || h3 < -0.00000001 || h3 > 1 + 0.00000001 ? undefined : { x: e51.x + t3.x * l3, y: e51.y + t3.y * l3, rayT: l3 };
};
var x2 = (e51, t3) => {
  const n3 = [], o3 = [];
  for (let i4 = 0;i4 < 4; i4++) {
    const { x: r3, y: s3 } = e51[i4], a3 = t3[i4].x, c3 = t3[i4].y;
    n3.push([r3, s3, 1, 0, 0, 0, -a3 * r3, -a3 * s3]), o3.push(a3), n3.push([0, 0, 0, r3, s3, 1, -c3 * r3, -c3 * s3]), o3.push(c3);
  }
  const i3 = ((e52, t4) => {
    const n4 = t4.length, o4 = e52.map((e53, n5) => [...e53, t4[n5]]);
    for (let e53 = 0;e53 < n4; e53++) {
      let t5 = e53;
      for (let i5 = e53 + 1;i5 < n4; i5++)
        Math.abs(o4[i5][e53]) > Math.abs(o4[t5][e53]) && (t5 = i5);
      if (Math.abs(o4[t5][e53]) < c22)
        throw new Error("Could not solve homography");
      [o4[e53], o4[t5]] = [o4[t5], o4[e53]];
      const i4 = o4[e53][e53];
      for (let t6 = e53;t6 <= n4; t6++)
        o4[e53][t6] = o4[e53][t6] / i4;
      for (let t6 = 0;t6 < n4; t6++) {
        if (t6 === e53)
          continue;
        const i5 = o4[t6][e53];
        for (let r3 = e53;r3 <= n4; r3++)
          o4[t6][r3] = o4[t6][r3] - i5 * o4[e53][r3];
      }
    }
    return o4.map((e53) => e53[n4]);
  })(n3, o3);
  return [i3[0], i3[1], i3[2], i3[3], i3[4], i3[5], i3[6], i3[7], 1];
};
var v2 = (e51, t3) => {
  const n3 = Math.cos(t3), o3 = Math.sin(t3);
  return [n3, -o3, e51.x - n3 * e51.x + o3 * e51.y, o3, n3, e51.y - o3 * e51.x - n3 * e51.y, 0, 0, 1];
};
var I2 = (e51, t3) => {
  const n3 = e51[6] * t3.x + e51[7] * t3.y + e51[8];
  return Math.abs(n3) < c22 ? { x: t3.x, y: t3.y } : { x: (e51[0] * t3.x + e51[1] * t3.y + e51[2]) / n3, y: (e51[3] * t3.x + e51[4] * t3.y + e51[5]) / n3 };
};
var S2 = (e51, t3, n3) => {
  const { u: o3, v: i3 } = p22(n3);
  return { x: t3.x + e51.x * o3.x + e51.y * i3.x, y: t3.y + e51.x * o3.y + e51.y * i3.y };
};
var C2 = (e51, t3) => S2({ x: e51.x - t3.center.x, y: e51.y - t3.center.y }, t3.center, t3.ccwRotationRadians);
var P2 = (e51, t3) => {
  const n3 = ((e52, t4, n4) => {
    const { u: o4, v: i4 } = p22(n4), r4 = { x: e52.x - t4.x, y: e52.y - t4.y };
    return { x: d2(r4, o4), y: d2(r4, i4) };
  })(e51, t3.center, t3.ccwRotationRadians);
  if (Math.abs(n3.x) < c22 && Math.abs(n3.y) < c22)
    return { ...t3.center };
  const o3 = t3.width / 2, i3 = t3.height / 2, r3 = Math.abs(n3.x) > c22 ? o3 / Math.abs(n3.x) : 1 / 0, s3 = Math.abs(n3.y) > c22 ? i3 / Math.abs(n3.y) : 1 / 0, a3 = Math.min(r3, s3);
  return { x: t3.center.x + n3.x * a3, y: t3.center.y + n3.y * a3 };
};
var M2 = (e51, t3 = 0, n3 = 0) => {
  const o3 = ((e52, t4) => {
    const n4 = _2(t4);
    for (let t5 = 0;t5 < n4.length; t5++) {
      const o4 = n4[t5], i4 = n4[(t5 + 1) % n4.length];
      if ((i4.x - o4.x) * (e52.y - o4.y) - (i4.y - o4.y) * (e52.x - o4.x) < -0.0000001)
        return false;
    }
    return true;
  })(f2(e51), e51) ? [...e51] : ((e52) => {
    const t4 = [...e52].filter((e53, t5, n5) => n5.findIndex((t6) => Math.abs(t6.x - e53.x) < 0.000000001 && Math.abs(t6.y - e53.y) < 0.000000001) === t5).sort((e53, t5) => e53.x - t5.x || e53.y - t5.y);
    if (t4.length <= 3)
      return t4;
    const n4 = (e53, t5, n5) => (t5.x - e53.x) * (n5.y - e53.y) - (t5.y - e53.y) * (n5.x - e53.x), o4 = [];
    for (const e53 of t4) {
      for (;o4.length >= 2 && n4(o4[o4.length - 2], o4[o4.length - 1], e53) <= 0.000000001; )
        o4.pop();
      o4.push(e53);
    }
    const i4 = [];
    for (let e53 = t4.length - 1;e53 >= 0; e53--) {
      const o5 = t4[e53];
      for (;i4.length >= 2 && n4(i4[i4.length - 2], i4[i4.length - 1], o5) <= 0.000000001; )
        i4.pop();
      i4.push(o5);
    }
    return o4.pop(), i4.pop(), [...o4, ...i4];
  })(e51), i3 = f2(o3), r3 = y2(o3, i3), s3 = g2(o3), a3 = r3.width * r3.height, c3 = (l3 = t3, Math.max(0, l3));
  var l3;
  const h3 = a3 + Math.max(0, s3 - a3) * c3, d3 = a3 > c22 && h3 > a3 ? Math.sqrt(h3 / a3) : 1, u3 = Math.max(0, n3), p3 = Math.max(r3.width * d3, u3), m3 = Math.max(r3.height * d3, u3), g3 = u2(r3.ccwRotationRadians), f3 = 180 * g3 / Math.PI, _3 = ((e52) => {
    const t4 = e52.width / 2, n4 = e52.height / 2;
    return [{ x: e52.center.x - t4, y: e52.center.y - n4 }, { x: e52.center.x + t4, y: e52.center.y - n4 }, { x: e52.center.x + t4, y: e52.center.y + n4 }, { x: e52.center.x - t4, y: e52.center.y + n4 }];
  })({ center: i3, width: p3, height: m3 }), y3 = ((e52) => {
    const t4 = e52.width / 2, n4 = e52.height / 2;
    return [S2({ x: -t4, y: -n4 }, e52.center, e52.ccwRotationRadians), S2({ x: t4, y: -n4 }, e52.center, e52.ccwRotationRadians), S2({ x: t4, y: n4 }, e52.center, e52.ccwRotationRadians), S2({ x: -t4, y: n4 }, e52.center, e52.ccwRotationRadians)];
  })({ center: i3, width: p3, height: m3, ccwRotationRadians: g3 }), b3 = y3.map((e52) => {
    const t4 = { x: e52.x - i3.x, y: e52.y - i3.y }, n4 = ((e53, t5, n5) => {
      let o4;
      for (let i4 = 0;i4 < n5.length; i4++) {
        const r4 = b2(e53, t5, n5[i4], n5[(i4 + 1) % n5.length]);
        r4 && (!o4 || r4.rayT < o4.rayT) && (o4 = r4);
      }
      return o4;
    })(i3, t4, o3);
    return n4 ? { x: n4.x, y: n4.y } : e52;
  });
  let x3 = g2(b3) > c22 ? b3 : y3;
  let v3, I3;
  try {
    v3 = x2(_3, x3), I3 = ((e52) => {
      const [t4, n4, o4, i4, r4, s4, a4, c4, l4] = e52, h4 = r4 * l4 - s4 * c4, d4 = -(i4 * l4 - s4 * a4), u4 = i4 * c4 - r4 * a4, p4 = -(n4 * l4 - o4 * c4), m4 = t4 * l4 - o4 * a4, g4 = -(t4 * c4 - n4 * a4), f4 = n4 * s4 - o4 * r4, _4 = -(t4 * s4 - o4 * i4), y4 = t4 * r4 - n4 * i4, b4 = t4 * h4 + n4 * d4 + o4 * u4;
      if (Math.abs(b4) < c22)
        throw new Error("Cannot invert singular 3x3 matrix");
      const x4 = 1 / b4;
      return [h4 * x4, p4 * x4, f4 * x4, d4 * x4, m4 * x4, _4 * x4, u4 * x4, g4 * x4, y4 * x4];
    })(v3);
  } catch {
    x3 = y3, v3 = v2(i3, g3), I3 = v2(i3, -g3);
  }
  return { center: i3, width: p3, height: m3, innerWidth: r3.width, innerHeight: r3.height, ccwRotationDegrees: f3, ccwRotationRadians: g3, polygonArea: s3, equivalentAreaExpansionFactor: c3, targetQuad: x3, rectToPolygonMatrix: v3, polygonToRectMatrix: I3 };
};
var w2 = class extends ni {
  constructor(e51) {
    super(), this.params = e51, this.MAX_ITERATIONS = 1;
  }
  getSolverName() {
    return "AttachProjectedRectsSolver";
  }
  outputNodes = [];
  projectionAdjustmentByNodeId = new Map;
  _step() {
    this.projectionAdjustmentByNodeId.clear(), this.outputNodes = this.params.nodesWithPortPoints.map((e51) => {
      const t3 = this.params.equivalentAreaExpansionFactor ?? 0, n3 = this.params.minProjectedRectDimension ?? 0, o3 = (({ traceWidth: e52, viaDiameter: t4, obstacleMargin: n4, minProjectedRectDimension: o4 }) => Math.max(o4, t4 ?? 0, (e52 ?? 0) + 2 * (n4 ?? 0)))({ traceWidth: this.params.traceWidth, viaDiameter: this.params.viaDiameter, obstacleMargin: this.params.obstacleMargin, minProjectedRectDimension: n3 });
      let i3 = M2(e51.polygon, t3, n3);
      if (Math.min(i3.width, i3.height) > o3 + (this.params.traceWidth ?? 0))
        return { ...e51, center: i3.center, width: i3.width, height: i3.height, projectedRect: i3 };
      const r3 = M2(e51.polygon, 1, n3);
      return (({ node: e52, projectedRect: t4, conservativeProjectedRect: n4, requiredRoutingCorridorWidth: o4, traceWidth: i4 }) => {
        if (o4 <= 0)
          return false;
        const r4 = Math.min(t4.width, t4.height), s3 = Math.min(n4.width, n4.height), a3 = Math.max(t4.width, t4.height), c3 = Math.max(n4.width, n4.height), l3 = o4 + (i4 ?? 0), h3 = Math.floor(r4 / o4), d3 = Math.floor(s3 / o4);
        return new Set(e52.portPoints.map((e53) => e53.connectionName)).size > 1 && h3 <= d3 && r4 <= l3 && a3 - c3 >= o4 && t4.equivalentAreaExpansionFactor > 1;
      })({ node: e51, projectedRect: i3, conservativeProjectedRect: r3, requiredRoutingCorridorWidth: o3, traceWidth: this.params.traceWidth }) && (i3 = r3, this.projectionAdjustmentByNodeId.set(e51.capacityMeshNodeId, "corridor-expansion-factor-1")), { ...e51, center: i3.center, width: i3.width, height: i3.height, projectedRect: i3 };
    }), this.solved = true;
  }
  getOutput() {
    return this.outputNodes;
  }
  getConstructorParams() {
    return [this.params];
  }
  visualize() {
    const e51 = this.outputNodes.length > 0 ? this.outputNodes : this.params.nodesWithPortPoints;
    return { polygons: e51.map((e52) => ({ points: e52.polygon, fill: "rgba(40, 140, 220, 0.06)", stroke: "rgba(20, 70, 160, 0.95)", strokeWidth: 0.04, label: `${e52.capacityMeshNodeId} polygon` })), lines: e51.map((e52) => ({ points: [...e52.polygon, e52.polygon[0]], strokeColor: "rgba(20, 70, 160, 0.95)", strokeWidth: 0.04, label: `${e52.capacityMeshNodeId} polygon outline` })), rects: e51.flatMap((e52) => e52.projectedRect ? [{ center: e52.projectedRect.center, width: e52.projectedRect.width, height: e52.projectedRect.height, ccwRotationDegrees: e52.projectedRect.ccwRotationDegrees, fill: "rgba(255, 165, 0, 0.16)", stroke: "rgba(255, 140, 0, 0.8)", label: `${e52.capacityMeshNodeId} projectedRect` }] : []), points: e51.flatMap((e52) => e52.portPoints.map((e53) => ({ x: e53.x, y: e53.y, color: "rgba(30, 30, 30, 0.85)", label: e53.connectionName }))) };
  }
};
var N2 = class extends ni {
  constructor(e51) {
    super(), this.params = e51;
    const { nodeWithPortPoints: t3 } = e51;
    if (!t3.projectedRect)
      throw new Error("Poly node is missing projectedRect");
    this.projectedPorts = t3.portPoints.map((e52) => {
      const n3 = P2(e52, t3.projectedRect);
      return { original: e52, projected: { ...e52, x: n3.x, y: n3.y } };
    }), this.projectedNode = { capacityMeshNodeId: t3.capacityMeshNodeId, center: t3.projectedRect.center, width: t3.projectedRect.width, height: t3.projectedRect.height, availableZ: t3.availableZ, portPoints: this.projectedPorts.map(({ projected: e52 }) => e52) }, this.highDensitySolver = new xz({ nodeWithPortPoints: this.projectedNode, colorMap: e51.colorMap, connMap: e51.connMap, viaDiameter: e51.viaDiameter, traceWidth: e51.traceWidth, obstacleMargin: e51.obstacleMargin, effort: e51.effort }), this.activeSubSolver = this.highDensitySolver, this.MAX_ITERATIONS = this.highDensitySolver.MAX_ITERATIONS + 1000;
  }
  getSolverName() {
    return "PolySingleIntraNodeSolver";
  }
  highDensitySolver;
  projectedNode;
  solvedRoutes = [];
  projectedPorts;
  _step() {
    this.highDensitySolver.step(), this.progress = this.highDensitySolver.progress, this.stats = this.highDensitySolver.stats, this.highDensitySolver.solved ? (this.solvedRoutes = this.highDensitySolver.solvedRoutes, this.solved = true, this.activeSubSolver = null) : this.highDensitySolver.failed && (this.error = this.highDensitySolver.error, this.failed = true, this.activeSubSolver = null);
  }
  getConstructorParams() {
    return [this.params];
  }
  visualize() {
    const e51 = this.params.nodeWithPortPoints, t3 = e51.projectedRect, n3 = { polygons: [{ points: e51.polygon, fill: "rgba(60, 160, 220, 0.10)", stroke: "rgba(40, 90, 150, 0.7)", label: `${e51.capacityMeshNodeId} polygon` }, ...t3 ? [{ points: t3.targetQuad, fill: "rgba(255, 165, 0, 0.08)", stroke: "rgba(255, 120, 0, 0.65)", label: `${e51.capacityMeshNodeId} distortion target` }] : []], rects: t3 ? [{ center: t3.center, width: t3.width, height: t3.height, ccwRotationDegrees: t3.ccwRotationDegrees, fill: "rgba(255, 165, 0, 0.14)", stroke: "rgba(255, 120, 0, 0.8)", label: `${e51.capacityMeshNodeId} projectedRect` }] : [], points: [...e51.portPoints.map((e52) => ({ x: e52.x, y: e52.y, color: "rgba(0, 80, 160, 0.85)", label: `${e52.connectionName} original` })), ...this.projectedPorts.map(({ projected: e52 }) => ({ x: e52.x, y: e52.y, color: "rgba(255, 120, 0, 0.85)", label: `${e52.connectionName} projected` }))] };
    return pi(n3, this.highDensitySolver.visualize());
  }
};
var R2 = class extends ni {
  getSolverName() {
    return "PolyHighDensitySolver";
  }
  unsolvedNodePortPoints;
  nodePortPoints;
  routes = [];
  routesByNodeId = new Map;
  failedSolvers = [];
  activeSubSolver = null;
  colorMap;
  connMap;
  viaDiameter;
  traceWidth;
  obstacleMargin;
  effort;
  nodePfById;
  constructor({ nodePortPoints: e51, colorMap: t3, connMap: n3, viaDiameter: o3, traceWidth: i3, obstacleMargin: r3, effort: s3, nodePfById: a3 }) {
    super(), this.nodePortPoints = [...e51], this.unsolvedNodePortPoints = [...e51], this.colorMap = t3 ?? {}, this.connMap = n3, this.viaDiameter = o3 ?? 0.3, this.traceWidth = i3 ?? 0.15, this.obstacleMargin = r3 ?? 0.15, this.effort = s3 ?? 1, this.MAX_ITERATIONS = 1e7 * this.effort, this.nodePfById = a3 instanceof Map ? new Map(a3) : new Map(Object.entries(a3 ?? {}));
  }
  _step() {
    if (this.activeSubSolver) {
      if (this.activeSubSolver.step(), this.activeSubSolver.solved) {
        const e52 = this.activeSubSolver.params.nodeWithPortPoints.capacityMeshNodeId, t3 = this.activeSubSolver.solvedRoutes;
        this.routesByNodeId.set(e52, [...this.routesByNodeId.get(e52) ?? [], ...t3]), this.routes.push(...this.activeSubSolver.solvedRoutes), this.activeSubSolver = null;
      } else
        this.activeSubSolver.failed && (this.failedSolvers.push(this.activeSubSolver), this.activeSubSolver = null);
      return;
    }
    if (this.unsolvedNodePortPoints.length === 0)
      return this.failedSolvers.length > 0 ? (this.failed = true, void (this.error = `Failed to solve ${this.failedSolvers.length} poly nodes, ${this.failedSolvers.slice(0, 5).map((e52) => e52.params.nodeWithPortPoints.capacityMeshNodeId).join(", ")}. err0: ${this.failedSolvers[0]?.error}`)) : void (this.solved = true);
    const e51 = this.unsolvedNodePortPoints.pop();
    this.activeSubSolver = new N2({ nodeWithPortPoints: e51, colorMap: this.colorMap, connMap: this.connMap, viaDiameter: this.viaDiameter, traceWidth: this.traceWidth, obstacleMargin: this.obstacleMargin, effort: this.effort });
  }
  computeProgress() {
    const e51 = this.routes.length + this.failedSolvers.length + this.unsolvedNodePortPoints.length + (this.activeSubSolver ? 1 : 0);
    return e51 === 0 ? 1 : (this.routes.length + this.failedSolvers.length + (this.activeSubSolver?.progress ?? 0)) / e51;
  }
  getConstructorParams() {
    return [{ nodePortPoints: this.nodePortPoints, colorMap: this.colorMap, connMap: this.connMap, viaDiameter: this.viaDiameter, traceWidth: this.traceWidth, obstacleMargin: this.obstacleMargin, effort: this.effort, nodePfById: this.nodePfById }];
  }
  visualize() {
    const e51 = { polygons: this.nodePortPoints.map((e52) => ({ points: e52.polygon, fill: "rgba(180, 180, 180, 0.05)", stroke: "rgba(120, 120, 120, 0.25)", label: `${e52.capacityMeshNodeId} polygon` })), rects: this.nodePortPoints.flatMap((e52) => e52.projectedRect ? [{ center: e52.projectedRect.center, width: e52.projectedRect.width, height: e52.projectedRect.height, ccwRotationDegrees: e52.projectedRect.ccwRotationDegrees, fill: "rgba(255, 165, 0, 0.08)", stroke: "rgba(255, 120, 0, 0.65)", label: `${e52.capacityMeshNodeId} projectedRect` }] : []), lines: [], circles: [], points: this.nodePortPoints.flatMap((e52) => e52.portPoints.map((e53) => ({ x: e53.x, y: e53.y, color: "rgba(80, 80, 80, 0.5)", label: `${e53.connectionName} original` }))) };
    for (const [t4, n3] of this.routesByNodeId) {
      const o3 = this.nodePortPoints.find((e52) => e52.capacityMeshNodeId === t4), i3 = o3?.projectedRect;
      if (i3)
        for (const t5 of n3) {
          const n4 = this.colorMap[t5.connectionName] ?? "#0000ff", o4 = { ...t5, route: t5.route.map((e52) => ({ ...e52, ...C2(e52, i3) })), vias: t5.vias.map((e52) => C2(e52, i3)) }, r3 = mi(o4.route, t5.connectionName, n4);
          for (const n5 of r3)
            e51.lines.push({ points: n5.points, label: n5.connectionName, strokeColor: n5.z === 0 ? n5.color : Ao(n5.color, 0.5), layer: `z${n5.z}`, strokeWidth: t5.traceThickness, strokeDash: n5.z !== 0 ? [0.1, 0.3] : undefined });
          for (const i4 of o4.vias)
            e51.circles.push({ center: i4, layer: "z0,1", radius: t5.viaDiameter / 2, fill: n4, label: `${t5.connectionName} via` });
        }
    }
    const t3 = this.activeSubSolver?.visualize();
    return t3 && e51.polygons.push(...this.unsolvedNodePortPoints.map((e52) => ({ points: e52.polygon, fill: "rgba(180, 180, 180, 0.08)", stroke: "rgba(120, 120, 120, 0.4)", label: e52.capacityMeshNodeId }))), t3 ? pi(e51, t3) : e51;
  }
};
var E22 = (e51) => {
  const { o: t3, a: n3, b: o3 } = e51;
  return (n3.x - t3.x) * (o3.y - t3.y) - (n3.y - t3.y) * (o3.x - t3.x);
};
var A2 = (e51, t3) => {
  const n3 = [...new Set(e51)].map((e52) => {
    const n4 = t3[e52];
    return n4 ? { i: e52, x: n4.x, y: n4.y } : null;
  }).filter((e52) => e52 !== null);
  if (n3.sort((e52, t4) => e52.x - t4.x || e52.y - t4.y), n3.length <= 2)
    return n3.map((e52) => e52.i);
  const o3 = [], i3 = [];
  for (const e52 of n3) {
    for (;o3.length >= 2; ) {
      const t4 = o3[o3.length - 2], n4 = o3[o3.length - 1];
      if (!t4 || !n4 || E22({ o: t4, a: n4, b: e52 }) > 0.0000000001)
        break;
      o3.pop();
    }
    o3.push(e52);
  }
  for (let e52 = n3.length - 1;e52 >= 0; e52--) {
    const t4 = n3[e52];
    if (t4) {
      for (;i3.length >= 2; ) {
        const e53 = i3[i3.length - 2], n4 = i3[i3.length - 1];
        if (!e53 || !n4 || E22({ o: e53, a: n4, b: t4 }) > 0.0000000001)
          break;
        i3.pop();
      }
      i3.push(t4);
    }
  }
  return o3.pop(), i3.pop(), o3.concat(i3).map((e52) => e52.i);
};
var O2 = (e51) => {
  const t3 = Math.max(0, Math.min(30, Math.floor(e51)));
  return t3 === 0 ? 0 : (1 << t3) - 1;
};
var k2 = (e51, t3 = 31) => {
  const n3 = [], o3 = Math.max(0, Math.min(31, Math.floor(t3)));
  for (let t4 = 0;t4 < o3; t4++)
    e51 & 1 << t4 && n3.push(t4);
  return n3;
};
var D2 = (e51) => {
  let t3 = 0;
  for (const n3 of e51)
    Number.isInteger(n3) && n3 >= 0 && n3 < 31 && (t3 |= 1 << n3);
  return t3;
};
var L2 = (e51, t3) => {
  const n3 = e51.trim().toLowerCase();
  if (n3 === "top")
    return 0;
  if (n3 === "bottom")
    return Math.max(0, t3 - 1);
  const o3 = n3.match(/^inner(\d+)$/);
  if (o3?.[1]) {
    const e52 = Number(o3[1]);
    return e52 >= 0 && e52 < t3 ? e52 : undefined;
  }
  const i3 = n3.match(/^layer(\d+)$/);
  if (i3?.[1]) {
    const e52 = Number(i3[1]) - 1;
    return e52 >= 0 && e52 < t3 ? e52 : undefined;
  }
  const r3 = n3.match(/^z(\d+)$/);
  if (r3?.[1]) {
    const e52 = Number(r3[1]);
    return e52 >= 0 && e52 < t3 ? e52 : undefined;
  }
};
var z2 = (e51, t3) => {
  const n3 = O2(t3), o3 = e51.zLayers;
  if (Array.isArray(o3) && o3.length > 0)
    return D2(o3) & n3;
  const i3 = e51.layers;
  if (Array.isArray(i3) && i3.length > 0) {
    let e52 = 0;
    for (const n4 of i3) {
      const o4 = L2(n4, t3);
      o4 !== undefined && (e52 |= 1 << o4);
    }
    return e52 & n3;
  }
  return n3;
};
var B2 = 0.1;
var F2 = 0.15;
var j2 = B2 + F2;
var $2 = 3 * j2 / 4;
var Y2 = 5;
var X2 = 0.000000001;
var H2 = (e51) => Math.round(1e6 * e51) / 1e6;
var V2 = (e51) => `${H2(e51.x)},${H2(e51.y)}`;
var W2 = (e51, t3) => {
  const n3 = V2(e51), o3 = V2(t3);
  return n3 < o3 ? `${n3}|${o3}` : `${o3}|${n3}`;
};
var G2 = (e51) => {
  let { POSITIVE_INFINITY: t3, NEGATIVE_INFINITY: n3, POSITIVE_INFINITY: o3, NEGATIVE_INFINITY: i3 } = Number;
  for (const r3 of e51)
    t3 = Math.min(t3, r3.x), n3 = Math.max(n3, r3.x), o3 = Math.min(o3, r3.y), i3 = Math.max(i3, r3.y);
  return { minX: t3, maxX: n3, minY: o3, maxY: i3 };
};
var U2 = (e51, t3) => {
  const n3 = e51.x < t3.minX ? t3.minX - e51.x : e51.x > t3.maxX ? e51.x - t3.maxX : 0, o3 = e51.y < t3.minY ? t3.minY - e51.y : e51.y > t3.maxY ? e51.y - t3.maxY : 0;
  return n3 * n3 + o3 * o3;
};
var Z2 = (e51, t3, n3) => {
  const o3 = n3.x - t3.x, i3 = n3.y - t3.y, r3 = o3 * o3 + i3 * i3;
  if (r3 < 0.000000000000000001)
    return false;
  const s3 = ((e51.x - t3.x) * o3 + (e51.y - t3.y) * i3) / r3;
  if (s3 < -0.000000001 || s3 > 1 + 0.000000001)
    return false;
  const a3 = t3.x + s3 * o3, c3 = t3.y + s3 * i3;
  return (e51.x - a3) ** 2 + (e51.y - c3) ** 2 < 0.000000000001;
};
var q2 = (e51, t3, n3) => {
  const o3 = n3.x - t3.x, i3 = n3.y - t3.y, r3 = o3 * o3 + i3 * i3;
  if (r3 < X2)
    return (e51.x - t3.x) ** 2 + (e51.y - t3.y) ** 2;
  const s3 = Math.max(0, Math.min(1, ((e51.x - t3.x) * o3 + (e51.y - t3.y) * i3) / r3)), a3 = t3.x + s3 * o3, c3 = t3.y + s3 * i3;
  return (e51.x - a3) ** 2 + (e51.y - c3) ** 2;
};
var J2 = (e51, t3) => ({ x: (e51.x + t3.x) / 2, y: (e51.y + t3.y) / 2 });
var Q2 = (e51, t3, n3, o3 = 0.001) => {
  const i3 = o3 * o3;
  return ((e52, t4) => {
    let n4 = Number.POSITIVE_INFINITY;
    for (let o4 = 0;o4 < t4.length; o4++) {
      const i4 = t4[o4], r3 = t4[(o4 + 1) % t4.length];
      n4 = Math.min(n4, q2(e52, i4, r3));
    }
    return n4;
  })(J2(e51, t3), n3) <= i3;
};
var K2 = (e51, t3) => {
  let n3 = false;
  for (let o3 = 0, i3 = t3.length - 1;o3 < t3.length; i3 = o3++) {
    const r3 = t3[o3], s3 = t3[i3];
    if (Z2(e51, r3, s3))
      return true;
    r3.y > e51.y != s3.y > e51.y && e51.x < (s3.x - r3.x) * (e51.y - r3.y) / (s3.y - r3.y + 0.000000000001) + r3.x && (n3 = !n3);
  }
  return n3;
};
var e52 = (e51, t3, n3, o3) => {
  const i3 = t3.x - e51.x, r3 = t3.y - e51.y, s3 = o3.x - n3.x, a3 = o3.y - n3.y, c3 = i3 * a3 - r3 * s3;
  if (Math.abs(c3) < X2) {
    for (const i4 of [e51, t3])
      if (Z2(i4, n3, o3))
        return i4;
    for (const i4 of [n3, o3])
      if (Z2(i4, e51, t3))
        return i4;
    return;
  }
  const l3 = ((n3.x - e51.x) * a3 - (n3.y - e51.y) * s3) / c3, h3 = ((n3.x - e51.x) * r3 - (n3.y - e51.y) * i3) / c3;
  if (!(l3 < -0.000000001 || l3 > 1.000000001 || h3 < -0.000000001 || h3 > 1.000000001))
    return { x: e51.x + l3 * i3, y: e51.y + l3 * r3 };
};
var t5 = (e51, t3) => {
  for (const n3 of e51)
    if (K2(n3, t3))
      return n3;
  for (const n3 of t3)
    if (K2(n3, e51))
      return n3;
  for (let n3 = 0;n3 < e51.length; n3++) {
    const o3 = e51[n3], i3 = e51[(n3 + 1) % e51.length];
    for (let e53 = 0;e53 < t3.length; e53++) {
      const n4 = t3[e53], r3 = t3[(e53 + 1) % t3.length], s3 = e52(o3, i3, n4, r3);
      if (s3)
        return s3;
    }
  }
};
var n5 = (e51, t3 = 0.000001) => [{ x: e51.x - t3, y: e51.y - t3 }, { x: e51.x + t3, y: e51.y - t3 }, { x: e51.x, y: e51.y + t3 }];
var o5 = (e51, t3, n3, o3, i3) => {
  const r3 = t3.x - e51.x, s3 = t3.y - e51.y, a3 = Math.hypot(r3, s3);
  if (a3 < X2)
    return [];
  const c3 = Number.isFinite(n3) && n3 > X2 ? n3 : j2, l3 = Number.isFinite(o3) ? Math.max(0, o3) : $2, h3 = Math.min(l3, a3 / 2), d3 = a3 - 2 * h3;
  if (d3 <= 0.75 * c3)
    return [{ x: (e51.x + t3.x) / 2, y: (e51.y + t3.y) / 2, distToCentermostPortOnZ: 0, cramped: true }];
  const u3 = Math.max(1, Math.floor(d3 / c3) + 1), p3 = Number.isFinite(i3) && i3 > 0 ? Math.floor(i3) : Y2, m3 = u3 > p3 ? p3 + Math.floor(u3 / 4) : u3;
  if (m3 <= 1)
    return [{ x: (e51.x + t3.x) / 2, y: (e51.y + t3.y) / 2, distToCentermostPortOnZ: 0, cramped: false }];
  const g3 = a3 / 2, f3 = Array.from({ length: m3 }, (t4, n4) => {
    const o4 = h3 + d3 * n4 / (m3 - 1), i4 = o4 / a3;
    return { x: e51.x + r3 * i4, y: e51.y + s3 * i4, distanceFromStart: o4 };
  }), _3 = f3.reduce((e53, t4) => Math.abs(t4.distanceFromStart - g3) < Math.abs(e53 - g3) ? t4.distanceFromStart : e53, f3[0].distanceFromStart);
  return f3.map(({ x: e53, y: t4, distanceFromStart: n4 }) => ({ x: e53, y: t4, distToCentermostPortOnZ: Math.abs(n4 - _3), cramped: false }));
};
var i5 = (e51, t3) => {
  if (!(Math.hypot(t3.x - e51.x, t3.y - e51.y) < X2))
    return { ...J2(e51, t3), distToCentermostPortOnZ: 0, cramped: false };
};
var r5 = (e51, t3) => {
  if (typeof e51 != "object" || e51 === null)
    return;
  const n3 = e51[t3];
  return typeof n3 == "string" ? n3 : undefined;
};
var s5 = (e51) => {
  const t3 = new Set, n3 = (e53) => {
    typeof e53 == "string" && e53.length > 0 && t3.add(e53);
  }, o3 = (e53) => {
    n3(e53.pointId), n3(e53.pcb_port_id);
  };
  n3(e51.connectionId), n3(e51.mutuallyConnectedNetworkId), o3(e51.start), o3(e51.end);
  const i3 = e51.simpleRouteConnection;
  n3(r5(i3, "name")), n3(r5(i3, "source_trace_id")), n3(r5(i3, "rootConnectionName"));
  const r3 = typeof i3 == "object" && i3 !== null ? i3.pointsToConnect : undefined;
  if (Array.isArray(r3))
    for (const e53 of r3)
      o3(e53);
  return t3;
};
var a5 = (e51) => {
  const { regions: t3, availableZ: n3, layerCount: o3, connections: i3 = [], obstacleRegions: r3 = [], regionIdPrefix: s3 = "free", portIdPrefix: a3 = "shared-port", traceWidth: c3 = B2, obstacleMargin: l3 = F2, portSpacing: h3 = c3 + l3, portMarginFromSegmentEndpoint: d3 = 3 * h3 / 4, maxDensePortsBeforeDecimation: u3 = Y2 } = e51, p3 = Array.from({ length: o3 }, (e53, t4) => t4), m3 = new Map, g3 = new Map, f3 = (e53) => e53.mutuallyConnectedNetworkId ?? e53.connectionId;
  for (const e53 of i3) {
    const t4 = f3(e53);
    let n4 = m3.get(t4);
    n4 === undefined && (n4 = m3.size, m3.set(t4, n4));
    for (const t6 of s5(e53))
      g3.has(t6) || g3.set(t6, n4);
  }
  const _3 = t3.map((e53, t4) => {
    const o4 = G2(e53);
    return { regionId: `${s3}-${t4}`, pointIds: [], d: { polygon: e53, availableZ: n3?.[t4] ?? p3, center: { x: (o4.minX + o4.maxX) / 2, y: (o4.minY + o4.maxY) / 2 }, width: o4.maxX - o4.minX, height: o4.maxY - o4.minY } };
  }), y3 = _3.map((e53, t4) => ({ regionId: e53.regionId, serializedRegionIndex: t4, polygon: e53.d.polygon, availableZ: e53.d.availableZ, bounds: G2(e53.d.polygon), isObstacle: false, netId: undefined })), b3 = r3.flatMap((e53, t4) => {
    if (e53.polygon.length < 3)
      return [];
    const n4 = ((e54) => {
      if (Number.isInteger(e54.netId) && e54.netId >= 0)
        return e54.netId;
      if (typeof e54.mutuallyConnectedNetworkId == "string")
        return m3.get(e54.mutuallyConnectedNetworkId);
      for (const t6 of e54.connectedTo ?? []) {
        const e55 = g3.get(t6);
        if (e55 !== undefined)
          return e55;
      }
    })(e53);
    if (n4 === undefined)
      return [];
    const o4 = e53.polygon, i4 = G2(o4), r4 = e53.availableZ ?? p3, s4 = e53.regionId ?? `obstacle-${t4}`, a4 = _3.length;
    _3.push({ regionId: s4, pointIds: [], d: { ...e53.d ?? {}, polygon: o4, availableZ: r4, center: { x: (i4.minX + i4.maxX) / 2, y: (i4.minY + i4.maxY) / 2 }, width: i4.maxX - i4.minX, height: i4.maxY - i4.minY, _containsObstacle: true, _containsTarget: true, netId: n4 } });
    const c4 = { regionId: s4, serializedRegionIndex: a4, polygon: o4, availableZ: r4, bounds: i4, isObstacle: true, netId: n4 };
    return y3.push(c4), [c4];
  }), x3 = [], v3 = new Map;
  for (let e53 = 0;e53 < t3.length; e53++) {
    const n4 = t3[e53];
    for (let t4 = 0;t4 < n4.length; t4++) {
      const o4 = n4[t4], i4 = n4[(t4 + 1) % n4.length], r4 = W2(o4, i4), s4 = v3.get(r4) ?? [];
      s4.push({ regionIndex: e53, a: o4, b: i4 }), v3.set(r4, s4);
    }
  }
  let I3 = 0;
  const S3 = (e53) => {
    const { region1Id: t4, region2Id: n4, pointIndex: o4, portPoint: i4, z: r4, portIdSuffix: s4 } = e53, c4 = `${a3}-${String(I3).padStart(5, "0")}::p${o4}::z${r4}${s4 ?? ""}`;
    return x3.push({ portId: c4, region1Id: t4, region2Id: n4, d: { portId: c4, x: i4.x, y: i4.y, z: r4, distToCentermostPortOnZ: i4.distToCentermostPortOnZ, ...i4.cramped ? { cramped: true } : {} } }), I3 += 1, c4;
  };
  for (const e53 of v3.values()) {
    if (e53.length !== 2)
      continue;
    const [t4, o4] = e53, i4 = n3?.[t4.regionIndex] ?? p3, r4 = n3?.[o4.regionIndex] ?? p3, a4 = i4.filter((e54) => r4.includes(e54));
    if (a4.length === 0)
      continue;
    const c4 = o5(t4.a, t4.b, h3, d3, u3);
    if (c4.length !== 0)
      for (let e54 = 0;e54 < c4.length; e54++) {
        const n4 = c4[e54];
        for (const i6 of a4) {
          if (b3.some((e55) => e55.availableZ.includes(i6) && Q2(t4.a, t4.b, e55.polygon)))
            continue;
          const r6 = S3({ region1Id: `${s3}-${t4.regionIndex}`, region2Id: `${s3}-${o4.regionIndex}`, pointIndex: e54, portPoint: n4, z: i6 });
          _3[t4.regionIndex].pointIds.push(r6), _3[o4.regionIndex].pointIds.push(r6);
        }
      }
  }
  for (const e53 of b3)
    for (const t4 of v3.values())
      for (const o4 of t4) {
        if (!Q2(o4.a, o4.b, e53.polygon))
          continue;
        const t6 = (n3?.[o4.regionIndex] ?? p3).filter((t7) => e53.availableZ.includes(t7));
        if (t6.length === 0)
          continue;
        const i4 = i5(o4.a, o4.b);
        if (i4)
          for (const n4 of t6) {
            const t7 = S3({ region1Id: `${s3}-${o4.regionIndex}`, region2Id: e53.regionId, pointIndex: 0, portPoint: i4, z: n4, portIdSuffix: "::obstacle" });
            _3[o4.regionIndex].pointIds.push(t7), _3[e53.serializedRegionIndex].pointIds.push(t7);
          }
      }
  for (let e53 = 0;e53 < b3.length; e53++) {
    const t4 = b3[e53];
    for (let n4 = e53 + 1;n4 < b3.length; n4++) {
      const e54 = b3[n4];
      if (t4.netId !== e54.netId)
        continue;
      const o4 = t4.availableZ.filter((t6) => e54.availableZ.includes(t6));
      if (o4.length === 0)
        continue;
      const i4 = t5(t4.polygon, e54.polygon);
      if (i4)
        for (const n6 of o4) {
          const o6 = S3({ region1Id: t4.regionId, region2Id: e54.regionId, pointIndex: 0, portPoint: { x: i4.x, y: i4.y, distToCentermostPortOnZ: 0 }, z: n6, portIdSuffix: "::obstacle-contact" });
          _3[t4.serializedRegionIndex].pointIds.push(o6), _3[e54.serializedRegionIndex].pointIds.push(o6);
        }
    }
  }
  const C = (e53, t4) => {
    const n4 = ((e54, t6) => {
      if (Number.isInteger(e54.z) && e54.z >= 0 && e54.z < t6)
        return [e54.z];
      if (Array.isArray(e54.zLayers) && e54.zLayers.length > 0)
        return e54.zLayers.filter((e55) => Number.isInteger(e55) && e55 >= 0 && e55 < t6);
      if (typeof e54.layer == "string") {
        const n6 = L2(e54.layer, t6);
        return n6 === undefined ? [] : [n6];
      }
      return Array.isArray(e54.layers) && e54.layers.length > 0 ? e54.layers.map((e55) => L2(e55, t6)).filter((e55) => e55 !== undefined) : [0];
    })(e53, o3);
    let i4;
    const r4 = y3.filter((e54) => e54.isObstacle && (t4 === undefined || e54.netId === t4));
    for (const t6 of r4) {
      const o4 = n4.find((e54) => t6.availableZ.includes(e54)) ?? t6.availableZ[0];
      if (o4 !== undefined && K2(e53, t6.polygon))
        return { regionId: t6.regionId, serializedRegionIndex: t6.serializedRegionIndex, z: o4 };
    }
    for (const t6 of y3.filter((e54) => !e54.isObstacle)) {
      const o4 = n4.find((e54) => t6.availableZ.includes(e54)) ?? t6.availableZ[0];
      if (o4 === undefined)
        continue;
      if (K2(e53, t6.polygon))
        return { regionId: t6.regionId, serializedRegionIndex: t6.serializedRegionIndex, z: o4 };
      const r6 = U2(e53, t6.bounds);
      (!i4 || r6 < i4.distanceSq) && (i4 = { regionId: t6.regionId, serializedRegionIndex: t6.serializedRegionIndex, z: o4, distanceSq: r6 });
    }
    return i4;
  }, P = [];
  for (const e53 of i3) {
    const t4 = m3.get(f3(e53)), n4 = C(e53.start, t4), o4 = C(e53.end, t4);
    if (!n4 || !o4)
      throw new Error(`Could not map connection "${e53.connectionId}" endpoint into a generated region`);
    const i4 = `terminal-start-${e53.connectionId}`, r4 = `terminal-end-${e53.connectionId}`, s4 = `terminal-start-port-${e53.connectionId}`, a4 = `terminal-end-port-${e53.connectionId}`;
    _3.push({ regionId: i4, pointIds: [s4], d: { polygon: n5(e53.start), availableZ: [n4.z], center: { x: e53.start.x, y: e53.start.y }, width: 0.000001, height: 0.000001, _containsTarget: true } }), _3.push({ regionId: r4, pointIds: [a4], d: { polygon: n5(e53.end), availableZ: [o4.z], center: { x: e53.end.x, y: e53.end.y }, width: 0.000001, height: 0.000001, _containsTarget: true } }), x3.push({ portId: s4, region1Id: n4.regionId, region2Id: i4, d: { portId: s4, x: e53.start.x, y: e53.start.y, z: n4.z, distToCentermostPortOnZ: 0 } }), x3.push({ portId: a4, region1Id: o4.regionId, region2Id: r4, d: { portId: a4, x: e53.end.x, y: e53.end.y, z: o4.z, distToCentermostPortOnZ: 0 } }), _3[n4.serializedRegionIndex].pointIds.push(s4), _3[o4.serializedRegionIndex].pointIds.push(a4), P.push({ connectionId: e53.connectionId, mutuallyConnectedNetworkId: e53.mutuallyConnectedNetworkId, startRegionId: i4, endRegionId: r4, simpleRouteConnection: e53.simpleRouteConnection });
  }
  return { regions: _3, ports: x3, connections: P };
};
var d5 = (e51) => {
  const { polygon: t3, clearance: n3, verticesOnly: o3 = false } = e51, i3 = t3.points, r3 = i3.length;
  if (r3 < 3)
    return [];
  const s3 = new D_(i3.map((e53) => C_(e53.x, e53.y))).orientation() === Cg.CCW, a3 = [];
  for (let e53 = 0;e53 < r3; e53++) {
    const t4 = i3[e53], o4 = i3[(e53 + 1) % r3], c4 = M_(o4.x - t4.x, o4.y - t4.y);
    if (c4.length === 0) {
      a3.push(T_(C_(t4.x, t4.y), M_(1, 0)));
      continue;
    }
    const l4 = c4.normalize(), h3 = s3 ? M_(l4.y, -l4.x) : M_(-l4.y, l4.x), d3 = C_(t4.x + n3 * h3.x, t4.y + n3 * h3.y);
    a3.push(T_(d3, h3));
  }
  const c3 = [];
  for (let e53 = 0;e53 < r3; e53++) {
    const t4 = a3[(e53 - 1 + r3) % r3], n4 = a3[e53], o4 = t4.intersect(n4);
    if (o4.length > 0) {
      const e54 = o4[0];
      c3.push({ x: e54.x, y: e54.y });
    } else
      c3.push({ x: n4.pt.x, y: n4.pt.y });
  }
  if (o3)
    return c3;
  const l3 = [];
  for (let e53 = 0;e53 < r3; e53++) {
    const t4 = c3[e53], n4 = c3[(e53 + 1) % r3], o4 = N_(C_(t4.x, t4.y), C_(n4.x, n4.y)).length, i4 = Math.max(2, Math.ceil(o4 / 20));
    for (let e54 = 0;e54 < i4; e54++) {
      const o6 = e54 / i4;
      l3.push({ x: t4.x + o6 * (n4.x - t4.x), y: t4.y + o6 * (n4.y - t4.y) });
    }
  }
  return l3;
};
var u5 = (e51) => {
  const { localX: t3, localY: n3, rect: o3 } = e51, i3 = Math.cos(o3.ccwRotation), r3 = Math.sin(o3.ccwRotation);
  return { x: o3.center.x + t3 * i3 - n3 * r3, y: o3.center.y + t3 * r3 + n3 * i3 };
};
var p5 = (e51) => new D_(e51.map((e53) => C_(e53.x, e53.y)));
var m5 = (e51) => {
  const t3 = [];
  for (const n3 of e51.faces) {
    const e53 = [];
    for (const t4 of n3.vertices)
      e53.push({ x: t4.x, y: t4.y });
    e53.length >= 3 && t3.push(e53);
  }
  return t3;
};
var g5 = (e51, t3, n3) => {
  const o3 = t3.length;
  t3.push(...e51);
  const i3 = e51.length;
  for (let e53 = 0;e53 < i3; e53++)
    n3.push([o3 + e53, o3 + (e53 + 1) % i3]);
};
var f5 = (e51) => {
  const { bounds: t3, vias: n3, clearance: o3, rects: i3, polygons: r3 = [], viaSegments: s3 = 8, preserveObstacleBoundaries: a3 = false } = e51, c3 = [], l3 = [], h3 = [], { minX: d3, maxX: u3, minY: p3, maxY: m3 } = t3, g3 = 10, f3 = [];
  for (let e53 = 0;e53 < g3; e53++) {
    const t4 = e53 / g3;
    f3.push({ x: d3 + t4 * (u3 - d3), y: p3 });
  }
  for (let e53 = 0;e53 < g3; e53++) {
    const t4 = e53 / g3;
    f3.push({ x: u3, y: p3 + t4 * (m3 - p3) });
  }
  for (let e53 = 0;e53 < g3; e53++) {
    const t4 = e53 / g3;
    f3.push({ x: u3 - t4 * (u3 - d3), y: m3 });
  }
  for (let e53 = 0;e53 < g3; e53++) {
    const t4 = e53 / g3;
    f3.push({ x: d3, y: m3 - t4 * (m3 - p3) });
  }
  h3.push(l3.length), g5(f3, c3, l3);
  const _3 = [];
  for (const e53 of n3) {
    const t4 = e53.diameter / 2 + o3, n4 = [];
    for (let o4 = 0;o4 < s3; o4++) {
      const i4 = 2 * Math.PI * o4 / s3;
      n4.push({ x: e53.center.x + t4 * Math.cos(i4), y: e53.center.y + t4 * Math.sin(i4) });
    }
    _3.push(n4);
  }
  for (const e53 of i3) {
    const t4 = e53.width / 2 + o3, n4 = e53.height / 2 + o3, i4 = [u5({ localX: -t4, localY: -n4, rect: e53 }), u5({ localX: t4, localY: -n4, rect: e53 }), u5({ localX: t4, localY: n4, rect: e53 }), u5({ localX: -t4, localY: n4, rect: e53 })];
    _3.push(i4);
  }
  for (const e53 of r3) {
    if (e53.points.length < 3)
      continue;
    const t4 = d5({ polygon: e53, clearance: o3, verticesOnly: true });
    _3.push(t4);
  }
  const y3 = a3 ? _3 : ((e53) => {
    if (e53.length <= 1)
      return e53;
    try {
      let t4 = e53.map(p5);
      for (let e54 = 0;e54 < 2; e54++) {
        const e55 = [], n6 = new Set;
        for (let o4 = 0;o4 < t4.length; o4++) {
          if (n6.has(o4))
            continue;
          let i4 = t4[o4];
          for (let e56 = o4 + 1;e56 < t4.length; e56++) {
            if (n6.has(e56))
              continue;
            const o6 = i4.box, r4 = t4[e56].box;
            if (!(o6.xmin > r4.xmax + 0.000001 || o6.xmax < r4.xmin - 0.000001 || o6.ymin > r4.ymax + 0.000001 || o6.ymax < r4.ymin - 0.000001))
              try {
                const o7 = e_.unify(i4, t4[e56]);
                o7.faces.size > 0 && (i4 = o7, n6.add(e56));
              } catch {}
          }
          e55.push(i4), n6.add(o4);
        }
        t4 = e55;
      }
      const n4 = [];
      for (const e54 of t4) {
        const t6 = m5(e54);
        n4.push(...t6);
      }
      return n4.length > 0 ? n4 : e53;
    } catch {
      return e53;
    }
  })(_3);
  for (const e53 of y3)
    h3.push(l3.length), g5(e53, c3, l3);
  const b3 = ((e53, t4, n4) => {
    const o4 = new Array(t4.length);
    for (let e54 = 0;e54 < t4.length; e54++)
      for (let t6 = n4.length - 1;t6 >= 0; t6--)
        if (e54 >= n4[t6]) {
          o4[e54] = t6;
          break;
        }
    const i4 = new Map, r4 = e53.slice();
    for (let e54 = 0;e54 < t4.length; e54++)
      for (let n6 = e54 + 1;n6 < t4.length; n6++) {
        if (o4[e54] === o4[n6])
          continue;
        const [s6, a4] = t4[e54], [c4, l4] = t4[n6], h4 = r4[s6], d4 = r4[a4], u4 = r4[c4], p4 = r4[l4], m4 = d4.x - h4.x, g4 = d4.y - h4.y, f4 = p4.x - u4.x, _4 = p4.y - u4.y, y4 = m4 * _4 - g4 * f4;
        if (Math.abs(y4) < 0.0000000001)
          continue;
        const b4 = ((u4.x - h4.x) * _4 - (u4.y - h4.y) * f4) / y4, x3 = ((u4.x - h4.x) * g4 - (u4.y - h4.y) * m4) / y4;
        if (b4 > 0.000001 && b4 < 0.999999 && x3 > 0.000001 && x3 < 0.999999) {
          const t6 = h4.x + b4 * m4, o6 = h4.y + b4 * g4, s7 = r4.length;
          r4.push({ x: t6, y: o6 }), i4.has(e54) || i4.set(e54, []), i4.get(e54).push({ t: b4, idx: s7 }), i4.has(n6) || i4.set(n6, []), i4.get(n6).push({ t: x3, idx: s7 });
        }
      }
    if (i4.size === 0)
      return { pts: e53, constraintEdges: t4, hadCrossings: false };
    const s4 = [];
    for (let e54 = 0;e54 < t4.length; e54++) {
      const n6 = i4.get(e54);
      if (!n6 || n6.length === 0) {
        s4.push(t4[e54]);
        continue;
      }
      n6.sort((e55, t6) => e55.t - t6.t);
      const [o6, r6] = t4[e54];
      let a4 = o6;
      for (const e55 of n6)
        s4.push([a4, e55.idx]), a4 = e55.idx;
      s4.push([a4, r6]);
    }
    return { pts: r4, constraintEdges: s4, hadCrossings: true };
  })(c3, l3, h3);
  return { pts: b3.pts.map((e53, t4) => ({ x: e53.x + 0.000001 * (t4 % 7 - 3), y: e53.y + 0.000001 * (t4 % 5 - 2) })), constraintEdges: b3.constraintEdges, hadCrossings: b3.hadCrossings };
};
var y5 = (e51) => {
  const { p: t3, a: n3, b: o3 } = e51, i3 = o3.x - n3.x, r3 = o3.y - n3.y, s3 = i3 * i3 + r3 * r3;
  if (s3 < 0.0000000001)
    return Math.hypot(t3.x - n3.x, t3.y - n3.y);
  let a3 = ((t3.x - n3.x) * i3 + (t3.y - n3.y) * r3) / s3;
  return a3 = Math.max(0, Math.min(1, a3)), Math.hypot(t3.x - n3.x - a3 * i3, t3.y - n3.y - a3 * r3);
};
var b5 = (e51, t3) => {
  if (e51.length <= 3)
    return 0;
  const n3 = A2(e51, t3), o3 = new Set(n3), i3 = n3.map((e53) => t3[e53]).filter((e53) => Boolean(e53));
  let r3 = 0;
  for (const n4 of e51) {
    if (o3.has(n4))
      continue;
    const e53 = t3[n4];
    if (!e53)
      continue;
    let s3 = Number.POSITIVE_INFINITY;
    for (let t4 = 0;t4 < i3.length; t4++) {
      const n6 = i3[t4], o4 = i3[(t4 + 1) % i3.length];
      n6 && o4 && (s3 = Math.min(s3, y5({ p: e53, a: n6, b: o4 })));
    }
    r3 = Math.max(r3, s3);
  }
  return r3;
};
var x5 = (e51, t3) => e51 < t3 ? 1e5 * e51 + t3 : 1e5 * t3 + e51;
var v5 = (e51, t3) => {
  const n3 = e51.map((t4, n4) => [t4, e51[(n4 + 1) % e51.length]]), o3 = t3.map((e53, n4) => [e53, t3[(n4 + 1) % t3.length]]), i3 = new Set;
  for (const [e53, t4] of n3)
    if (t4 !== undefined)
      for (const [n4, r4] of o3)
        r4 !== undefined && e53 === r4 && t4 === n4 && i3.add(x5(e53, t4));
  if (i3.size === 0)
    return null;
  const r3 = [];
  for (const [e53, t4] of n3)
    t4 !== undefined && (i3.has(x5(e53, t4)) || r3.push([e53, t4]));
  for (const [e53, t4] of o3)
    t4 !== undefined && (i3.has(x5(e53, t4)) || r3.push([e53, t4]));
  if (r3.length === 0)
    return null;
  const s3 = new Map;
  for (const [e53, t4] of r3)
    s3.set(e53, t4);
  const a3 = r3[0]?.[0];
  if (a3 === undefined)
    return null;
  const c3 = [a3];
  let l3 = s3.get(a3), h3 = 0;
  for (;l3 !== undefined && l3 !== a3 && h3++ < r3.length + 5; )
    c3.push(l3), l3 = s3.get(l3);
  return l3 !== a3 || c3.length !== r3.length ? null : c3;
};
var I5 = (e51, t3) => e51 < t3 ? 1e5 * e51 + t3 : 1e5 * t3 + e51;
var S5 = (e51, t3) => e51 < t3 ? 1e5 * e51 + t3 : 1e5 * t3 + e51;
var P5 = l(S(), 1);
var M5 = (e51) => {
  const { a: t3, b: n3, c: o3 } = e51, i3 = 2 * (t3.x * (n3.y - o3.y) + n3.x * (o3.y - t3.y) + o3.x * (t3.y - n3.y));
  if (Math.abs(i3) < 0.0000000001)
    return { x: 0, y: 0, r2: 1000000000000000000 };
  const r3 = t3.x * t3.x + t3.y * t3.y, s3 = n3.x * n3.x + n3.y * n3.y, a3 = o3.x * o3.x + o3.y * o3.y, c3 = (r3 * (n3.y - o3.y) + s3 * (o3.y - t3.y) + a3 * (t3.y - n3.y)) / i3, l3 = (r3 * (o3.x - n3.x) + s3 * (t3.x - o3.x) + a3 * (n3.x - t3.x)) / i3;
  return { x: c3, y: l3, r2: (t3.x - c3) ** 2 + (t3.y - l3) ** 2 };
};
var w5 = (e51, t3, n3) => [e51.a, e51.b, e51.c].includes(t3) && [e51.a, e51.b, e51.c].includes(n3);
var N5 = (e51) => {
  const { px: t3, py: n3, polygonPoints: o3, clearance: i3 } = e51;
  if (o3.length < 3)
    return false;
  const r3 = o3.map((e53) => C_(e53.x, e53.y)), s3 = [];
  for (let e53 = 0;e53 < r3.length; e53++) {
    const t4 = r3[e53], n4 = r3[(e53 + 1) % r3.length];
    s3.push(N_(t4, n4));
  }
  const a3 = new D_;
  a3.addFace(s3);
  const c3 = C_(t3, n3);
  if (a3.contains(c3))
    return true;
  const [l3] = a3.distanceTo(c3);
  return l3 < i3 - 0.1;
};
var R5 = (e51) => {
  const { point: t3, via: n3, clearance: o3 } = e51, i3 = t3.x - n3.center.x, r3 = t3.y - n3.center.y, s3 = n3.diameter / 2 + o3;
  return i3 * i3 + r3 * r3 <= s3 * s3 + 0.000000001;
};
var T5 = (e51) => {
  const { point: t3, rect: n3, clearance: o3 } = e51, i3 = Math.cos(-n3.ccwRotation), r3 = Math.sin(-n3.ccwRotation), s3 = t3.x - n3.center.x, a3 = t3.y - n3.center.y, c3 = s3 * i3 - a3 * r3, l3 = s3 * r3 + a3 * i3;
  return Math.abs(c3) <= n3.width / 2 + o3 + 0.000000001 && Math.abs(l3) <= n3.height / 2 + o3 + 0.000000001;
};
var E5 = (e51) => N5({ px: e51.point.x, py: e51.point.y, polygonPoints: e51.polygon.points, clearance: e51.clearance });
var A5 = (e51, t3) => e51.x >= t3.minX - 0.000000001 && e51.x <= t3.maxX + 0.000000001 && e51.y >= t3.minY - 0.000000001 && e51.y <= t3.maxY + 0.000000001;
var O5 = (e51) => {
  const { point: t3, vias: n3, rects: o3, polygons: i3, clearance: r3, layerCount: s3 } = e51;
  let a3 = 0;
  for (const e53 of n3)
    R5({ point: t3, via: e53, clearance: r3 }) && (a3 |= z2(e53, s3));
  for (const e53 of o3)
    T5({ point: t3, rect: e53, clearance: r3 }) && (a3 |= z2(e53, s3));
  for (const e53 of i3)
    E5({ point: t3, polygon: e53, clearance: r3 }) && (a3 |= z2(e53, s3));
  return a3;
};
var k5 = (e51) => {
  const { triangles: t3, pts: n3, bounds: o3, vias: i3, clearance: r3, rects: s3, polygons: a3, layerCount: c3 } = e51, l3 = O2(c3), h3 = [], d3 = [];
  for (const [e53, u3, p3] of t3) {
    const t4 = n3[e53], m3 = n3[u3], g3 = n3[p3];
    if (!t4 || !m3 || !g3)
      continue;
    const f3 = { x: (t4.x + m3.x + g3.x) / 3, y: (t4.y + m3.y + g3.y) / 3 };
    if (!A5(f3, o3))
      continue;
    const _3 = l3 & ~O5({ point: f3, vias: i3, rects: s3, polygons: a3, clearance: r3, layerCount: c3 });
    _3 !== 0 && (h3.push([e53, u3, p3]), d3.push(k2(_3, c3)));
  }
  return { triangles: h3, triangleAvailableZ: d3 };
};
var D5 = (e51) => {
  const { triangles: t3, pts: n3, bounds: o3, vias: i3, clearance: r3, rects: s3, polygons: a3 } = e51;
  return t3.filter(([e53, t4, c3]) => {
    const l3 = n3[e53], h3 = n3[t4], d3 = n3[c3];
    if (!l3 || !h3 || !d3)
      return false;
    if (!((e54) => {
      const { px: t6, py: n4, bounds: o4, vias: i4, clearance: r4, rects: s4, polygons: a4 } = e54, { minX: c4, maxX: l4, minY: h4, maxY: d4 } = o4, u3 = 0.000001 * Math.max(l4 - c4, d4 - h4, 1);
      if (t6 < c4 - u3 || t6 > l4 + u3 || n4 < h4 - u3 || n4 > d4 + u3)
        return false;
      for (const e55 of i4) {
        const o6 = e55.diameter / 2 + r4, i6 = Math.max(0, o6 - u3);
        if ((t6 - e55.center.x) ** 2 + (n4 - e55.center.y) ** 2 < i6 * i6)
          return false;
      }
      for (const e55 of s4) {
        const o6 = e55.width / 2 + r4, i6 = e55.height / 2 + r4, s6 = Math.max(0, o6 - u3), a6 = Math.max(0, i6 - u3), c5 = t6 - e55.center.x, l5 = n4 - e55.center.y, h5 = Math.cos(e55.ccwRotation), d6 = Math.sin(e55.ccwRotation), p3 = c5 * h5 + l5 * d6, m3 = -c5 * d6 + l5 * h5;
        if (Math.abs(p3) < s6 && Math.abs(m3) < a6)
          return false;
      }
      for (const e55 of a4)
        if (N5({ px: t6, py: n4, polygonPoints: e55.points, clearance: r4 }))
          return false;
      return true;
    })({ px: (l3.x + h3.x + d3.x) / 3, py: (l3.y + h3.y + d3.y) / 3, bounds: o3, vias: i3, clearance: r3, rects: s3, polygons: a3 }))
      return false;
    if (a3.length > 0) {
      const e54 = [l3, h3, d3, { x: (l3.x + h3.x) / 2, y: (l3.y + h3.y) / 2 }, { x: (h3.x + d3.x) / 2, y: (h3.y + d3.y) / 2 }, { x: (d3.x + l3.x) / 2, y: (d3.y + l3.y) / 2 }];
      for (const t6 of e54)
        for (const e55 of a3)
          if (N5({ px: t6.x, py: t6.y, polygonPoints: e55.points, clearance: r3 }))
            return false;
    }
    return true;
  });
};
var L5 = (e51) => e51 !== undefined;
var z5 = (e51) => {
  const { bounds: t3, clearance: n3, concavityTolerance: o3 } = e51, i3 = e51.vias ?? [], r3 = e51.rects ?? [], s3 = e51.polygons ?? [];
  let a3, c3, l3;
  if (e51.useConstrainedDelaunay !== false) {
    const o4 = f5({ bounds: t3, vias: i3, clearance: n3, rects: r3, polygons: s3, viaSegments: e51.viaSegments, preserveObstacleBoundaries: e51.layerCount !== undefined });
    a3 = o4.pts;
    const h4 = ((e53, t4, n4 = {}) => {
      const o6 = e53.map((e54) => [e54.x, e54.y]);
      return (0, P5.default)(o6, t4, { exterior: !!n4.includeConstraintInteriors });
    })(a3, o4.constraintEdges, { includeConstraintInteriors: e51.layerCount !== undefined });
    if (e51.layerCount !== undefined) {
      const o6 = k5({ triangles: h4, pts: a3, bounds: t3, vias: i3, clearance: n3, rects: r3, polygons: s3, layerCount: e51.layerCount });
      c3 = o6.triangles, l3 = o6.triangleAvailableZ;
    } else {
      c3 = i3.length > 0 || r3.length > 0 || s3.length > 0 ? D5({ triangles: h4, pts: a3, bounds: t3, vias: i3, clearance: n3, rects: r3, polygons: s3 }) : h4;
    }
  } else {
    a3 = ((e53) => {
      const { bounds: t4, vias: n4, clearance: o6, rects: i4, polygons: r4 = [], viaSegments: s4 = 24 } = e53, a4 = [], { minX: c4, maxX: l4, minY: h4, maxY: d4 } = t4;
      a4.push({ x: c4, y: h4 }, { x: l4, y: h4 }, { x: l4, y: d4 }, { x: c4, y: d4 });
      for (let e54 = 1;e54 < 10; e54++) {
        const t6 = e54 / 10;
        a4.push({ x: c4 + t6 * (l4 - c4), y: h4 }), a4.push({ x: l4, y: h4 + t6 * (d4 - h4) }), a4.push({ x: l4 - t6 * (l4 - c4), y: d4 }), a4.push({ x: c4, y: d4 - t6 * (d4 - h4) });
      }
      for (const e54 of n4) {
        const t6 = e54.diameter / 2 + o6;
        for (let n6 = 0;n6 < s4; n6++) {
          const o7 = 2 * Math.PI * n6 / s4;
          a4.push({ x: e54.center.x + t6 * Math.cos(o7), y: e54.center.y + t6 * Math.sin(o7) });
        }
      }
      for (const e54 of i4) {
        const t6 = e54.width / 2 + o6, n6 = e54.height / 2 + o6, i6 = Math.max(2, Math.ceil(Math.max(2 * t6, 2 * n6) / 20));
        for (let o7 = 0;o7 < i6; o7++) {
          const r6 = o7 / i6;
          a4.push(u5({ localX: 2 * r6 * t6 - t6, localY: -n6, rect: e54 })), a4.push(u5({ localX: t6, localY: 2 * r6 * n6 - n6, rect: e54 })), a4.push(u5({ localX: t6 - 2 * r6 * t6, localY: n6, rect: e54 })), a4.push(u5({ localX: -t6, localY: n6 - 2 * r6 * n6, rect: e54 }));
        }
      }
      for (const e54 of r4) {
        if (e54.points.length < 3)
          continue;
        const t6 = d5({ polygon: e54, clearance: o6 });
        a4.push(...t6);
      }
      return a4.map((e54, t6) => ({ x: e54.x + 0.000001 * (t6 % 7 - 3), y: e54.y + 0.000001 * (t6 % 5 - 2) }));
    })({ bounds: t3, vias: i3, clearance: n3, rects: r3, polygons: s3, viaSegments: e51.viaSegments });
    const o4 = ((e53) => {
      const t4 = e53.map((e54, t6) => ({ ...e54, i: t6 }));
      if (t4.length < 3)
        return [];
      let { POSITIVE_INFINITY: n4, POSITIVE_INFINITY: o6, NEGATIVE_INFINITY: i4, NEGATIVE_INFINITY: r4 } = Number;
      for (const e54 of t4)
        n4 = Math.min(n4, e54.x), o6 = Math.min(o6, e54.y), i4 = Math.max(i4, e54.x), r4 = Math.max(r4, e54.y);
      const s4 = Math.max(i4 - n4, r4 - o6) || 1, a4 = (n4 + i4) / 2, c4 = (o6 + r4) / 2, l4 = { x: a4 - 30 * s4, y: c4 - s4, i: -1 }, h4 = { x: a4, y: c4 + 30 * s4, i: -2 }, d4 = { x: a4 + 30 * s4, y: c4 - s4, i: -3 };
      let u4 = [{ a: l4, b: h4, c: d4, cc: M5({ a: l4, b: h4, c: d4 }) }];
      for (const e54 of t4) {
        const t6 = u4.filter((t7) => {
          const n7 = e54.x - t7.cc.x, o8 = e54.y - t7.cc.y;
          return n7 * n7 + o8 * o8 < t7.cc.r2 + 0.000001;
        }), n6 = new Set(t6), o7 = [];
        for (const e55 of t6) {
          const n7 = [[e55.a, e55.b], [e55.b, e55.c], [e55.c, e55.a]];
          for (const [i6, r6] of n7) {
            let n8 = false;
            for (const o8 of t6)
              if (o8 !== e55 && w5(o8, i6, r6)) {
                n8 = true;
                break;
              }
            n8 || o7.push([i6, r6]);
          }
        }
        u4 = u4.filter((e55) => !n6.has(e55));
        for (const [t7, n7] of o7)
          u4.push({ a: t7, b: n7, c: e54, cc: M5({ a: t7, b: n7, c: e54 }) });
      }
      return u4.filter((e54) => e54.a.i >= 0 && e54.b.i >= 0 && e54.c.i >= 0).map((e54) => [e54.a.i, e54.b.i, e54.c.i]);
    })(a3);
    if (e51.layerCount !== undefined) {
      const h4 = k5({ triangles: o4, pts: a3, bounds: t3, vias: i3, clearance: n3, rects: r3, polygons: s3, layerCount: e51.layerCount });
      c3 = h4.triangles, l3 = h4.triangleAvailableZ;
    } else
      c3 = D5({ triangles: o4, pts: a3, bounds: t3, vias: i3, clearance: n3, rects: r3, polygons: s3 });
  }
  const { cells: h3, depths: d3, availableZ: u3 } = e51.usePolyanyaMerge !== false ? ((e53) => {
    const { triangles: t4, pts: n4, cellAvailableZ: o4, layerMergeMode: i4 = "same" } = e53;
    if (!t4.length)
      return { cells: [], depths: [] };
    const r4 = t4.length, s4 = t4.map(([e54, t6, o6]) => {
      const i6 = n4[e54], r6 = n4[t6], s6 = n4[o6];
      return i6 && r6 && s6 && E22({ o: i6, a: r6, b: s6 }) < 0 ? [e54, o6, t6] : [e54, t6, o6];
    }), a4 = o4?.map(D2), c4 = new Array(r4).fill(null);
    for (let e54 = 0;e54 < r4; e54++)
      c4[e54] = new Map;
    function l4() {
      for (let e55 = 0;e55 < c4.length; e55++)
        c4[e55] && c4[e55].clear();
      const e54 = new Map;
      for (let t6 = 0;t6 < s4.length; t6++) {
        const n6 = s4[t6];
        if (n6)
          for (let o6 = 0;o6 < n6.length; o6++) {
            const i6 = n6[o6], r6 = n6[(o6 + 1) % n6.length], s6 = S5(i6, r6), a6 = e54.get(s6);
            a6 ? (c4[t6].set(o6, { neighbor: a6.cellIdx, neighborEdge: a6.edgePos }), c4[a6.cellIdx].set(a6.edgePos, { neighbor: t6, neighborEdge: o6 })) : e54.set(s6, { cellIdx: t6, edgePos: o6 });
          }
      }
    }
    function h4(e54) {
      let t6 = 0;
      for (let o6 = 0;o6 < e54.length; o6++) {
        const i6 = n4[e54[o6]], r6 = n4[e54[(o6 + 1) % e54.length]];
        t6 += i6.x * r6.y - r6.x * i6.y;
      }
      return Math.abs(t6) / 2;
    }
    function d4(e54, t6) {
      const n6 = s4[e54], o6 = c4[e54], i6 = n6.length;
      let r6 = -1;
      for (const [e55, n7] of o6)
        if (n7.neighbor === t6) {
          r6 = e55;
          break;
        }
      if (r6 === -1)
        return null;
      let a6 = r6;
      for (;; ) {
        const e55 = (a6 - 1 + i6) % i6;
        if (e55 === r6)
          break;
        const n7 = o6.get(e55);
        if (!n7 || n7.neighbor !== t6)
          break;
        a6 = e55;
      }
      let l5 = r6;
      for (;; ) {
        const e55 = (l5 + 1) % i6;
        if (e55 === a6)
          break;
        const n7 = o6.get(e55);
        if (!n7 || n7.neighbor !== t6)
          break;
        l5 = e55;
      }
      return { firstK: a6, lastK: l5, sharedCount: (l5 - a6 + i6) % i6 + 1 };
    }
    function u4(e54, t6) {
      const o6 = s4[e54], r6 = s4[t6], c5 = d4(e54, t6);
      if (!c5)
        return false;
      const { firstK: l5, lastK: h5, sharedCount: u6 } = c5, p6 = o6.length, m6 = r6.length, g6 = o6[l5], f4 = o6[(h5 + 1) % p6];
      let _4 = -1;
      for (let e55 = 0;e55 < m6; e55++)
        if (r6[e55] === g6) {
          _4 = e55;
          break;
        }
      if (_4 === -1)
        return false;
      const y4 = (_4 - u6 + m6) % m6;
      if (r6[y4] !== f4)
        return false;
      const b4 = n4[o6[(l5 - 1 + p6) % p6]], x4 = n4[g6], v4 = n4[r6[(_4 + 1) % m6]];
      if (E22({ o: b4, a: x4, b: v4 }) < -0.00000001)
        return false;
      const I4 = n4[r6[(y4 - 1 + m6) % m6]], S3 = n4[f4], C = n4[o6[(h5 + 2) % p6]];
      if (E22({ o: I4, a: S3, b: C }) < -0.00000001)
        return false;
      if (a4) {
        if ((a4[e54] & a4[t6]) === 0)
          return false;
        if (i4 === "same" && a4[e54] !== a4[t6])
          return false;
      }
      return true;
    }
    function p4(e54, t6) {
      const n6 = s4[e54], o6 = s4[t6], i6 = d4(e54, t6), { firstK: r6, lastK: c5, sharedCount: l5 } = i6, h5 = n6.length, u6 = o6.length, p6 = n6[r6], m6 = n6[(c5 + 1) % h5];
      let g6 = -1;
      for (let e55 = 0;e55 < u6; e55++)
        if (o6[e55] === p6) {
          g6 = e55;
          break;
        }
      const f4 = [];
      f4.push(p6);
      const _4 = u6 - l5 - 1;
      for (let e55 = 1;e55 <= _4; e55++)
        f4.push(o6[(g6 + e55) % u6]);
      f4.push(m6);
      const y4 = h5 - l5 - 1;
      for (let e55 = 2;e55 <= y4 + 1; e55++)
        f4.push(n6[(c5 + e55) % h5]);
      s4[e54] = f4, s4[t6] = null, a4 && (a4[e54] = a4[e54] & a4[t6], a4[t6] = 0);
    }
    l4();
    let m4 = true;
    for (;m4; ) {
      m4 = false, l4();
      for (let e54 = 0;e54 < s4.length; e54++) {
        if (!s4[e54])
          continue;
        const t6 = c4[e54], n6 = new Set;
        for (const [, e55] of t6)
          s4[e55.neighbor] && n6.add(e55.neighbor);
        if (n6.size === 1) {
          const t7 = n6.values().next().value;
          u4(e54, t7) && (p4(e54, t7), m4 = true);
        }
      }
    }
    l4();
    const g4 = new Array(s4.length).fill(0);
    for (let e54 = 0;e54 < s4.length; e54++)
      s4[e54] && (g4[e54] = h4(s4[e54]));
    const f3 = [];
    function _3(e54) {
      f3.push(e54);
      let t6 = f3.length - 1;
      for (;t6 > 0; ) {
        const e55 = t6 - 1 >> 1;
        if (f3[e55].area >= f3[t6].area)
          break;
        const n6 = f3[e55];
        f3[e55] = f3[t6], f3[t6] = n6, t6 = e55;
      }
    }
    function y3() {
      if (f3.length === 0)
        return;
      const e54 = f3[0], t6 = f3.pop();
      if (f3.length > 0) {
        f3[0] = t6;
        let e55 = 0;
        for (;; ) {
          let t7 = e55;
          const n6 = 2 * e55 + 1, o6 = 2 * e55 + 2;
          if (n6 < f3.length && f3[n6].area > f3[t7].area && (t7 = n6), o6 < f3.length && f3[o6].area > f3[t7].area && (t7 = o6), t7 === e55)
            break;
          const i6 = f3[e55];
          f3[e55] = f3[t7], f3[t7] = i6, e55 = t7;
        }
      }
      return e54;
    }
    const b3 = new Set;
    for (let e54 = 0;e54 < s4.length; e54++) {
      if (!s4[e54])
        continue;
      const t6 = c4[e54], n6 = new Set;
      for (const [, e55] of t6)
        s4[e55.neighbor] && n6.add(e55.neighbor);
      for (const t7 of n6) {
        const n7 = e54 < t7 ? 1e5 * e54 + t7 : 1e5 * t7 + e54;
        b3.has(n7) || (b3.add(n7), u4(e54, t7) && _3({ area: g4[e54] + g4[t7], xIdx: e54, yIdx: t7 }));
      }
    }
    for (;f3.length > 0; ) {
      const e54 = y3(), { xIdx: t6, yIdx: n6 } = e54;
      if (!s4[t6] || !s4[n6])
        continue;
      const o6 = g4[t6] + g4[n6];
      if (Math.abs(o6 - e54.area) > 0.0000000001) {
        u4(t6, n6) && _3({ area: o6, xIdx: t6, yIdx: n6 });
        continue;
      }
      if (!u4(t6, n6))
        continue;
      p4(t6, n6), g4[t6] = h4(s4[t6]), l4();
      const i6 = c4[t6], r6 = new Set;
      for (const [, e55] of i6)
        s4[e55.neighbor] && r6.add(e55.neighbor);
      for (const e55 of r6)
        u4(t6, e55) && _3({ area: g4[t6] + g4[e55], xIdx: t6, yIdx: e55 });
    }
    const x3 = s4.filter((e54) => e54 !== null), v3 = a4 ? s4.flatMap((e54, t6) => e54 === null ? [] : [k2(a4[t6])]) : undefined, I3 = x3.map(() => 0);
    return { cells: x3, depths: I3, ...v3 ? { availableZ: v3 } : {} };
  })({ triangles: c3, pts: a3, cellAvailableZ: l3, layerMergeMode: e51.layerMergeMode }) : ((e53) => {
    const { triangles: t4, pts: n4, concavityTolerance: o4, cellAvailableZ: i4, layerMergeMode: r4 = "same" } = e53;
    if (!t4.length)
      return { cells: [], depths: [] };
    const s4 = t4.map(([e54, t6, o6]) => {
      const i6 = n4[e54], r6 = n4[t6], s6 = n4[o6];
      return i6 && r6 && s6 && E22({ o: i6, a: r6, b: s6 }) < 0 ? [e54, o6, t6] : [e54, t6, o6];
    }), a4 = i4?.map(D2), c4 = (e54, t6) => {
      if (!a4)
        return;
      const n6 = a4[e54] & a4[t6];
      return n6 === 0 || r4 === "same" && a4[e54] !== a4[t6] ? 0 : n6;
    };
    let l4 = true, h4 = 0;
    for (;l4 && h4++ < 800; ) {
      l4 = false;
      const e54 = new Map, t6 = s4.map(() => new Set);
      for (let n6 = 0;n6 < s4.length; n6++) {
        const o6 = s4[n6];
        if (o6)
          for (let i7 = 0;i7 < o6.length; i7++) {
            const r7 = o6[i7], s6 = o6[(i7 + 1) % o6.length];
            if (r7 === undefined || s6 === undefined)
              continue;
            const a6 = I5(r7, s6);
            if (e54.has(a6)) {
              const o7 = e54.get(a6);
              o7 !== undefined && (t6[n6]?.add(o7), t6[o7]?.add(n6));
            } else
              e54.set(a6, n6);
          }
      }
      let i6 = -1, r6 = -1, h5 = null, d6 = Number.POSITIVE_INFINITY;
      for (let e55 = 0;e55 < s4.length; e55++) {
        const a6 = t6[e55];
        if (a6)
          for (const t7 of a6) {
            if (t7 <= e55)
              continue;
            const a7 = v5(s4[e55] ?? [], s4[t7] ?? []);
            if (!a7)
              continue;
            if (c4(e55, t7) === 0)
              continue;
            const l5 = b5(a7, n4);
            l5 <= o4 + 0.000001 && l5 < d6 && (d6 = l5, i6 = e55, r6 = t7, h5 = a7);
          }
      }
      if (i6 < 0 || r6 < 0 || !h5)
        break;
      s4[i6] = h5, a4 && (a4[i6] = c4(i6, r6), a4.splice(r6, 1)), s4.splice(r6, 1), l4 = true;
    }
    const d4 = s4.map((e54) => b5(e54, n4));
    return { cells: s4, depths: d4, ...a4 ? { availableZ: a4.map((e54) => k2(e54)) } : {} };
  })({ triangles: c3, pts: a3, concavityTolerance: o3, cellAvailableZ: l3, layerMergeMode: e51.layerMergeMode }), p3 = a3.map((e53) => ((e54, t4) => ({ x: Math.min(t4.maxX, Math.max(t4.minX, e54.x)), y: Math.min(t4.maxY, Math.max(t4.minY, e54.y)) }))(e53, t3)), m3 = h3.map((e53) => e53.map((e54) => p3[e54]).filter(L5)), g3 = h3.map((e53) => A2(e53, p3).map((e54) => p3[e54]).filter(L5));
  return { pts: p3, validTris: c3, regions: m3, hulls: g3, depths: d3, ...u3 ? { availableZ: u3 } : {} };
};
var F5 = (e51) => {
  const t3 = [...new Set(e51.filter((e53) => typeof e53 == "number" && Number.isInteger(e53) && e53 >= 0))].sort((e53, t4) => e53 - t4);
  if (t3.length !== 0)
    return `z${t3.join(",")}`;
};
var j5 = (e51) => {
  const t3 = [];
  for (let n3 = 0;n3 < 31; n3++)
    e51 & 1 << n3 && t3.push(n3);
  return t3;
};
var $5 = (e51) => typeof e51 == "object" && e51 !== null;
var Y5 = (e51) => $5(e51) ? { ...e51 } : e51 === undefined ? {} : { value: e51 };
var X5 = (e51, t3) => {
  const n3 = e51.topology.regionMetadata?.[t3];
  if ($5(n3)) {
    if (typeof n3.serializedRegionId == "string")
      return n3.serializedRegionId;
    if (typeof n3.regionId == "string")
      return n3.regionId;
    if (typeof n3.capacityMeshNodeId == "string")
      return n3.capacityMeshNodeId;
  }
  return `region-${t3}`;
};
var H5 = (e51, t3) => {
  const n3 = e51.topology.portMetadata?.[t3];
  if ($5(n3)) {
    if (typeof n3.serializedPortId == "string")
      return n3.serializedPortId;
    if (typeof n3.portId == "string")
      return (o3 = n3.portId).includes("::") ? o3.slice(0, o3.indexOf("::")) : o3;
  }
  var o3;
  return `port-${t3}`;
};
var V5 = (e51, t3) => {
  const n3 = Y5(e51.topology.regionMetadata?.[t3]);
  if ($5(n3.center) || (n3.center = { x: e51.topology.regionCenterX[t3], y: e51.topology.regionCenterY[t3] }), typeof n3.width != "number" && (n3.width = e51.topology.regionWidth[t3]), typeof n3.height != "number" && (n3.height = e51.topology.regionHeight[t3]), !Array.isArray(n3.availableZ)) {
    const o3 = e51.topology.regionAvailableZMask?.[t3] ?? 0;
    o3 !== 0 && (n3.availableZ = j5(o3));
  }
  return n3.layer = F5(Array.isArray(n3.availableZ) ? n3.availableZ : []) ?? F5((e51.topology.regionIncidentPorts[t3] ?? []).map((t4) => e51.topology.portZ[t4])) ?? "z0", n3;
};
var W5 = (e51, t3) => {
  const n3 = Y5(e51.topology.portMetadata?.[t3]);
  return typeof n3.x != "number" && (n3.x = e51.topology.portX[t3]), typeof n3.y != "number" && (n3.y = e51.topology.portY[t3]), typeof n3.z != "number" && (n3.z = e51.topology.portZ[t3]), n3.layer = F5([e51.topology.portZ[t3]]) ?? "z0", n3;
};
var G5 = (e51, t3, n3) => {
  const o3 = (e51.topology.incidentPortRegion[t3] ?? []).find((e53) => e53 !== n3);
  if (o3 === undefined)
    throw new Error(`Port ${t3} is not incident to a region outside route region ${n3}`);
  return o3;
};
var U5 = (e51, t3, n3) => {
  const { orderedPortIds: o3, orderedRegionIds: i3 } = ((e53, t4, n4) => {
    if (n4.length === 0)
      throw new Error(`Route ${t4} has no solved segments`);
    const o4 = e53.problem.routeStartPort[t4], i4 = e53.problem.routeEndPort[t4], r4 = new Map;
    n4.forEach((e54, t6) => {
      const n6 = { ...e54, segmentIndex: t6 }, o6 = r4.get(e54.fromPortId) ?? [];
      o6.push(n6), r4.set(e54.fromPortId, o6);
      const i6 = r4.get(e54.toPortId) ?? [];
      i6.push(n6), r4.set(e54.toPortId, i6);
    });
    const s4 = [o4], a4 = [], c4 = new Set;
    let l4, h4 = o4;
    for (;h4 !== i4; ) {
      const e54 = (r4.get(h4) ?? []).filter((e55) => !c4.has(e55.segmentIndex) && (e55.fromPortId === h4 ? e55.toPortId : e55.fromPortId) !== l4);
      if (e54.length !== 1)
        throw new Error(`Route ${t4} is not a single ordered path from ${o4} to ${i4}`);
      const n6 = e54[0], d3 = n6.fromPortId === h4 ? n6.toPortId : n6.fromPortId;
      c4.add(n6.segmentIndex), a4.push(n6.regionId), s4.push(d3), l4 = h4, h4 = d3;
    }
    if (c4.size !== n4.length)
      throw new Error(`Route ${t4} contains disconnected solved segments`);
    return { orderedPortIds: s4, orderedRegionIds: a4 };
  })(e51, t3, n3), r3 = i3[0], s3 = i3[i3.length - 1];
  if (r3 === undefined || s3 === undefined)
    throw new Error(`Route ${t3} could not determine endpoint regions`);
  const a3 = X5(e51, G5(e51, o3[0], r3)), c3 = X5(e51, G5(e51, o3[o3.length - 1], s3)), l3 = ((e53, t4, n4, o4) => {
    const i4 = e53.problem.routeMetadata?.[t4];
    return { connectionId: ($5(i4) && typeof i4.connectionId == "string" ? i4.connectionId : undefined) ?? `route-${t4}`, startRegionId: ($5(i4) && typeof i4.startRegionId == "string" ? i4.startRegionId : undefined) ?? n4, endRegionId: ($5(i4) && typeof i4.endRegionId == "string" ? i4.endRegionId : undefined) ?? o4, mutuallyConnectedNetworkId: ($5(i4) && typeof i4.mutuallyConnectedNetworkId == "string" ? i4.mutuallyConnectedNetworkId : undefined) ?? `net-${e53.problem.routeNet[t4]}` };
  })(e51, t3, a3, c3), h3 = o3.map((t4, n4) => {
    const r4 = { portId: H5(e51, t4), g: n4, h: 0, f: n4, hops: n4, ripRequired: false, nextRegionId: n4 < i3.length ? X5(e51, i3[n4]) : l3.endRegionId };
    return n4 > 0 && (r4.lastPortId = H5(e51, o3[n4 - 1]), r4.lastRegionId = X5(e51, i3[n4 - 1])), r4;
  });
  return { connection: l3, solvedRoute: { connection: l3, path: h3, requiredRip: false } };
};
var Z5 = (e51) => {
  if (!e51.solved || e51.failed)
    throw new Error("convertToSerializedHyperGraph requires a solved, non-failed solver");
  const { topology: t3 } = e51, n3 = ((e53) => {
    const t4 = Array.from({ length: e53.problem.routeCount }, () => []);
    return e53.state.regionSegments.forEach((e54, n4) => {
      for (const [o4, i4, r4] of e54)
        t4[o4].push({ regionId: n4, fromPortId: i4, toPortId: r4 });
    }), t4;
  })(e51), o3 = Array.from({ length: t3.regionCount }, (n4, o4) => ({ regionId: X5(e51, o4), pointIds: t3.regionIncidentPorts[o4].map((t4) => H5(e51, t4)), d: V5(e51, o4) })), i3 = Array.from({ length: t3.portCount }, (n4, o4) => {
    const [i4, r4] = t3.incidentPortRegion[o4] ?? [];
    if (i4 === undefined || r4 === undefined)
      throw new Error(`Port ${o4} is missing incident regions`);
    return { portId: H5(e51, o4), region1Id: X5(e51, i4), region2Id: X5(e51, r4), d: W5(e51, o4) };
  }), r3 = n3.map((t4, n4) => U5(e51, n4, t4));
  return { regions: o3, ports: i3, connections: r3.map(({ connection: e53 }) => e53), solvedRoutes: r3.map(({ solvedRoute: e53 }) => e53) };
};
var q5 = (e51) => e51 > 0 && !(e51 & e51 - 1);
var J5 = (e51, t3, n3, o3, i3, r3 = 0) => 0.2025 * (2 * t3 + 1 * n3 + 1 * o3) * (1 + i3 / 5) / e51 + (q5(r3) ? 10 * t3 : 0);
var Q5 = (e51, t3, n3, o3, i3, r3) => {
  const { netIds: s3, lesserAngles: a3, greaterAngles: c3, layerMasks: l3 } = e51;
  let h3 = 0, d3 = 0;
  for (let e53 = 0;e53 < s3.length; e53++) {
    if (t3 === s3[e53])
      continue;
    (n3 < a3[e53] && a3[e53] < o3) !== (n3 < c3[e53] && c3[e53] < o3) && ((i3 & l3[e53]) !== 0 ? h3++ : d3++);
  }
  return [h3, d3, r3];
};
var K5 = class {
  constructor(e51, t3) {
    this.items = e51, this.compare = t3;
  }
  get length() {
    return this.items.length;
  }
  toArray() {
    return [...this.items];
  }
  clear() {
    this.items.length = 0;
  }
  queue(e51) {
    this.items.push(e51), this.siftUp(this.items.length - 1);
  }
  dequeue() {
    const e51 = this.items[0];
    if (e51 === undefined)
      return;
    const t3 = this.items.pop();
    return this.items.length > 0 && (this.items[0] = t3, this.siftDown(0)), e51;
  }
  siftUp(e51) {
    let t3 = e51;
    for (;t3 > 0; ) {
      const e53 = t3 - 1 >> 1, n3 = this.items[e53], o3 = this.items[t3];
      if (this.compare(n3, o3) <= 0)
        return;
      this.items[e53] = o3, this.items[t3] = n3, t3 = e53;
    }
  }
  siftDown(e51) {
    let t3 = e51;
    const n3 = this.items.length;
    for (;; ) {
      const e53 = 2 * t3 + 1;
      if (e53 >= n3)
        return;
      const o3 = e53 + 1;
      let i3 = e53;
      o3 < n3 && this.compare(this.items[o3], this.items[e53]) < 0 && (i3 = o3);
      const r3 = this.items[t3], s3 = this.items[i3];
      if (this.compare(r3, s3) <= 0)
        return;
      this.items[t3] = s3, this.items[i3] = r3, t3 = i3;
    }
  }
};
var e310 = (e51, t3) => {
  const n3 = [...e51], o3 = ((e53) => {
    let t4 = e53 >>> 0;
    return () => {
      t4 += 1831565813;
      let e54 = t4;
      return e54 = Math.imul(e54 ^ e54 >>> 15, 1 | e54), e54 ^= e54 + Math.imul(e54 ^ e54 >>> 7, 61 | e54), ((e54 ^ e54 >>> 14) >>> 0) / 4294967296;
    };
  })(t3);
  for (let e53 = n3.length - 1;e53 > 0; e53--) {
    const t4 = Math.floor(o3() * (e53 + 1));
    [n3[e53], n3[t4]] = [n3[t4], n3[e53]];
  }
  return n3;
};
var t3 = (e51, t4) => e51.routeMetadata?.[t4];
var n3 = (e51) => e51?.simpleRouteConnection?.pointsToConnect?.map(({ pointId: e53 }) => typeof e53 == "string" ? e53 : null).filter((e53) => e53 !== null) ?? [];
var o3 = (e51, t4) => {
  const n4 = t3(e51, t4)?.connectionId;
  return typeof n4 == "string" ? n4 : `route-${t4}`;
};
var i3 = (e51, t4, n4) => {
  const o4 = e51.portEndpointNetIds[n4];
  if (!o4)
    return false;
  for (const e53 of o4)
    if (e53 !== t4)
      return true;
  return false;
};
var r3 = (e51, t4, n4) => {
  const o4 = e51.regionNetId[n4];
  return o4 !== -1 && o4 !== t4;
};
var s3 = (e51) => [...new Set(e51.routeIds)].filter((t4) => !((e53, t6) => {
  const { topology: n4, problem: o4, problemSetup: i4, portAssignment: r4, maxPrecheckHops: s4 } = e53, a3 = o4.routeNet[t6], c3 = o4.routeStartPort[t6], l3 = o4.routeEndPort[t6];
  if (c3 === l3)
    return true;
  const h3 = e53.getStartingNextRegionId(t6, c3);
  if (h3 === undefined)
    return false;
  const d3 = [{ portId: c3, nextRegionId: h3 }], u3 = new Set([c3 * n4.regionCount + h3]);
  for (let e54 = 0;e54 < d3.length; e54++) {
    const t7 = d3[e54];
    if (!r3(o4, a3, t7.nextRegionId))
      for (const e55 of n4.regionIncidentPorts[t7.nextRegionId] ?? []) {
        const c4 = r4[e55];
        if (i3(i4, a3, e55))
          continue;
        if (e55 === l3) {
          if (c4 !== -1 && c4 !== a3)
            continue;
          return true;
        }
        if (e55 === t7.portId)
          continue;
        if (c4 !== -1 && c4 !== a3)
          continue;
        if (o4.portSectionMask[e55] === 0)
          continue;
        const h4 = n4.incidentPortRegion[e55] ?? [], p3 = h4[0] === t7.nextRegionId ? h4[1] : h4[0];
        if (p3 === undefined || r3(o4, a3, p3))
          continue;
        const m3 = e55 * n4.regionCount + p3;
        if (!u3.has(m3)) {
          if (u3.size >= s4)
            return true;
          u3.add(m3), d3.push({ portId: e55, nextRegionId: p3 });
        }
      }
  }
  return false;
})(e51, t4)).map((t4) => e51.getRouteSummary(t4));
var a3 = (e51) => {
  const t4 = new Array(e51);
  for (let n4 = 0;n4 < e51; n4++)
    t4[n4] = n4;
  return t4;
};
var c3 = 0.05;
var l3 = { r: 255, g: 64, b: 64, a: 0.72 };
var h3 = "rgba(220, 38, 38, 0.98)";
var d3 = "rgba(220, 38, 38, 0.12)";
var u3 = "10 6";
var p3 = (...e51) => e51.filter((e53) => Boolean(e53)).join(`
`);
var m3 = (e51) => Math.min(1, Math.max(0, e51));
var g3 = (e51, t4, n4) => Math.round(e51 + (t4 - e51) * n4);
var f3 = ({ r: e51, g: t4, b: n4, a: o4 }) => `rgba(${e51}, ${t4}, ${n4}, ${o4})`;
var _3 = (e51, t4) => {
  const n4 = e51.problem.routeMetadata?.[t4];
  return n4?.connectionId ?? n4?.mutuallyConnectedNetworkId ?? `route-${t4}`;
};
var y3 = (e51) => typeof e51.centerRouteId == "number";
var b3 = (e51, t4) => y3(e51) ? t4 === e51.centerRouteId ? 1 : 0.5 : 1;
var x3 = (e51, t4) => {
  const n4 = e51.match(/^(rgba|hsla)\((.*),\s*([0-9]*\.?[0-9]+)\)$/);
  if (!n4)
    return e51;
  const [, o4, i4, r4] = n4, s4 = m3(Number(r4) * t4);
  return `${o4}(${i4}, ${Number(s4.toFixed(3))})`;
};
var v3 = (e51, t4, n4 = 0.8) => ((e53, t6, n6 = 0.8) => {
  const o4 = `${e53.problem.routeNet[t6]}:${_3(e53, t6)}`;
  let i4 = 0;
  for (let e54 = 0;e54 < o4.length; e54++)
    i4 = 17777 * o4.charCodeAt(e54) + ((i4 << 5) - i4);
  return `hsla(${Math.abs(i4) % 360}, 70%, 50%, ${n6})`;
})(e51, t4, n4 * b3(e51, t4));
var I3 = (e51, t4) => `net: ${e51.problem.routeNet[t4]}`;
var S3 = (e51, t4) => {
  const n4 = e51.topology.regionMetadata?.[t4], o4 = n4?.polygon;
  if (Array.isArray(o4) && o4.length >= 3) {
    const e53 = o4.map((e54) => e54.x), t6 = o4.map((e54) => e54.y);
    return { minX: Math.min(...e53), maxX: Math.max(...e53), minY: Math.min(...t6), maxY: Math.max(...t6) };
  }
  const i4 = n4?.bounds;
  if (i4 && typeof i4.minX == "number" && typeof i4.maxX == "number" && typeof i4.minY == "number" && typeof i4.maxY == "number")
    return i4;
  const r4 = e51.topology.regionWidth[t4], s4 = e51.topology.regionHeight[t4], a4 = e51.topology.regionCenterX[t4], c4 = e51.topology.regionCenterY[t4];
  return { minX: a4 - r4 / 2, maxX: a4 + r4 / 2, minY: c4 - s4 / 2, maxY: c4 + s4 / 2 };
};
var C3 = (e51, t4) => ({ x: e51.topology.regionCenterX[t4], y: e51.topology.regionCenterY[t4] });
var P3 = (e51, t4) => {
  const n4 = e51.topology.regionMetadata?.[t4], o4 = Array.isArray(n4?.availableZ) ? n4.availableZ.filter((e53) => typeof e53 == "number" && Number.isInteger(e53) && e53 >= 0) : [];
  if (o4.length > 0)
    return F5(o4) ?? "z0";
  const i4 = j5(e51.topology.regionAvailableZMask?.[t4] ?? 0);
  if (i4.length > 0)
    return F5(i4) ?? "z0";
  const r4 = [...new Set((e51.topology.regionIncidentPorts[t4] ?? []).map((t6) => e51.topology.portZ[t6]))].sort((e53, t6) => e53 - t6);
  return F5(r4) ?? "z0";
};
var M3 = (e51, t4) => {
  const n4 = e51.state.regionIntersectionCaches[t4], o4 = n4?.existingRegionCost ?? 0, i4 = e51.state.regionCongestionCost[t4] ?? 0, r4 = e51.problem.regionNetId[t4];
  return p3(`region: region-${t4}`, `net: ${r4 === -1 ? "free" : `${r4}`}`, e51.getAdditionalRegionLabel(t4), `cost: ${o4.toFixed(3)}`, `congestion: ${i4.toFixed(3)}`, `same layer X: ${n4?.existingSameLayerIntersections ?? 0}`, `trans X: ${n4?.existingCrossingLayerIntersections ?? 0}`, `entry exit X: ${n4?.existingEntryExitLayerChanges ?? 0}`);
};
var w3 = (e51, t4) => {
  const n4 = e51.topology.regionMetadata?.[t4];
  return n4?.isConnectionRegion ? { r: 255, g: 100, b: 255, a: 0.6 } : n4?.isThroughJumper ? { r: 100, g: 200, b: 100, a: 0.5 } : n4?.isPad ? { r: 255, g: 200, b: 100, a: 0.5 } : n4?.layer === "bottom" ? { r: 52, g: 152, b: 219, a: 0.08 } : { r: 200, g: 200, b: 255, a: 0.1 };
};
var N3 = (e51, t4) => {
  const n4 = w3(e51, t4), o4 = m3(e51.state.regionIntersectionCaches[t4]?.existingRegionCost ?? 0), i4 = Math.pow(o4, 0.8);
  return f3((s4 = l3, a4 = i4, { r: g3((r4 = n4).r, s4.r, a4), g: g3(r4.g, s4.g, a4), b: g3(r4.b, s4.b, a4), a: Number((r4.a + (s4.a - r4.a) * a4).toFixed(3)) }));
  var r4, s4, a4;
};
var R3 = (e51, t4) => ({ x: e51.topology.portX[t4], y: e51.topology.portY[t4] });
var T3 = R3;
var E3 = R3;
var A3 = (e51, t4) => F5([e51.topology.portZ[t4]]) ?? "z0";
var O3 = (e51, t4) => {
  const n4 = e51.topology.portMetadata?.[t4];
  return `port: ${n4?.serializedPortId ?? n4?.portId ?? `port-${t4}`}`;
};
var k3 = (e51, t4, n4) => {
  if (n4 !== undefined)
    return `net: ${e51.problem.routeNet[n4]}`;
  const o4 = e51.state.portAssignment[t4];
  if (o4 >= 0)
    return `net: ${o4}`;
  const i4 = new Set;
  for (let n6 = 0;n6 < e51.problem.routeCount; n6++)
    e51.problem.routeStartPort[n6] !== t4 && e51.problem.routeEndPort[n6] !== t4 || i4.add(e51.problem.routeNet[n6]);
  return i4.size !== 0 ? `net: ${Array.from(i4).sort((e53, t6) => e53 - t6).join(", ")}` : undefined;
};
var D3 = (e51, t4) => `z: ${e51.topology.portZ[t4]}`;
var L3 = (e51, t4, n4) => p3(O3(e51, t4), ((e53, t6) => {
  const n6 = e53.topology.incidentPortRegion[t6]?.[0], o4 = e53.topology.incidentPortRegion[t6]?.[1];
  return `connects: region-${n6 ?? "?"} <-> region-${o4 ?? "?"}`;
})(e51, t4), k3(e51, t4, n4));
var z3 = (e51, t4, n4, o4) => {
  const i4 = e51.topology.portZ[n4], r4 = e51.topology.portZ[o4];
  return i4 > 0 && r4 > 0 ? { strokeColor: x3("rgba(52, 152, 219, 0.95)", b3(e51, t4)), strokeDash: "3 2" } : i4 !== r4 ? { strokeColor: x3("rgba(22, 160, 133, 0.95)", b3(e51, t4)), strokeDash: "2 4 2" } : { strokeColor: v3(e51, t4) };
};
var B3 = (e51, t4) => {
  for (let n4 = 0;n4 < e51.problem.routeCount; n4++)
    if (e51.problem.routeStartPort[n4] === t4 || e51.problem.routeEndPort[n4] === t4)
      return true;
  return false;
};
var F3 = (e51, t4, n4) => {
  const o4 = ((e53, t6) => {
    const n6 = new Set;
    for (let o6 = 0;o6 < t6.length; o6++)
      if (t6[o6] === 1)
        for (const t7 of e53.topology.incidentPortRegion[o6] ?? [])
          n6.add(t7);
    return n6;
  })(e51, n4), i4 = "rgba(245, 158, 11, 0.95)", r4 = "rgba(245, 158, 11, 0.08)";
  for (const n6 of o4) {
    const o6 = e51.topology.regionMetadata?.[n6], s4 = o6?.polygon, a4 = S3(e51, n6), c4 = C3(e51, n6), l4 = a4.maxX - a4.minX, h4 = a4.maxY - a4.minY, d4 = P3(e51, n6), u4 = p3("section region", M3(e51, n6));
    Array.isArray(s4) && s4.length >= 3 ? t4.polygons.push({ points: s4, fill: r4, stroke: i4, strokeWidth: 2, layer: d4, label: u4 }) : t4.rects.push({ center: c4, width: Math.max(l4 - c3, 0.05), height: Math.max(h4 - c3, 0.05), fill: r4, stroke: i4, layer: d4, label: u4 });
  }
  for (let o6 = 0;o6 < n4.length; o6++)
    n4[o6] === 1 && t4.circles.push({ center: E3(e51, o6), radius: 0.07, fill: "rgba(251, 191, 36, 0.18)", stroke: i4, layer: A3(e51, o6), label: p3(L3(e51, o6), D3(e51, o6), "section port") });
};
var j3 = (e51, t4 = {}) => {
  const n4 = { arrows: [], circles: [], infiniteLines: [], lines: [], points: [], polygons: [], rects: [], texts: [], title: "Tiny HyperGraph", coordinateSystem: "cartesian" }, o4 = ((e53, t6) => {
    if (!t6?.highlightSectionMask)
      return;
    const n6 = t6.sectionPortMask ?? e53.problem.portSectionMask;
    if (n6.length !== e53.topology.portCount)
      return;
    let o6 = 0, i6 = 0;
    for (let e54 = 0;e54 < n6.length; e54++)
      n6[e54] === 1 ? o6 += 1 : i6 += 1;
    return o6 !== 0 && i6 !== 0 ? n6 : undefined;
  })(e51, t4);
  for (let t6 = 0;t6 < e51.topology.regionCount; t6++) {
    const o6 = e51.topology.regionMetadata?.[t6], i6 = o6?.polygon, r6 = S3(e51, t6), s4 = C3(e51, t6), a4 = r6.maxX - r6.minX, c4 = r6.maxY - r6.minY, l4 = P3(e51, t6), h4 = f3(w3(e51, t6));
    Array.isArray(i6) && i6.length >= 3 ? n4.polygons.push({ points: i6, fill: h4, layer: l4 }) : n4.rects.push({ center: s4, width: Math.max(a4 - c3, 0.05), height: Math.max(c4 - c3, 0.05), fill: N3(e51, t6), layer: l4, label: M3(e51, t6) });
  }
  if (((e53, t6) => {
    for (let n6 = 0;n6 < e53.problem.routeCount; n6++) {
      const o6 = e53.problem.routeStartPort[n6], i6 = e53.problem.routeEndPort[n6], r6 = T3(e53, o6), s4 = T3(e53, i6), a4 = v3(e53, n6), c4 = _3(e53, n6), l4 = I3(e53, n6);
      t6.points.push({ x: r6.x, y: r6.y, color: a4, layer: A3(e53, o6), label: p3(`route: ${c4}`, l4, "endpoint: start", O3(e53, o6), D3(e53, o6)) }), t6.points.push({ x: s4.x, y: s4.y, color: a4, layer: A3(e53, i6), label: p3(`route: ${c4}`, l4, "endpoint: end", O3(e53, i6), D3(e53, i6)) });
    }
  })(e51, n4), e51.iterations === 0) {
    for (const e53 of n4.polygons)
      e53.stroke = "rgba(128, 128, 128, 0.5)";
    for (const e53 of n4.rects)
      e53.stroke = "rgba(128, 128, 128, 0.5)";
  }
  if (e51.iterations === 0) {
    for (let i6 = 0;i6 < e51.topology.portCount; i6++) {
      const r6 = o4?.[i6] === 1;
      t4.showOnlySectionPortsOnIdle && !r6 || n4.circles.push({ center: E3(e51, i6), radius: 0.05, fill: e51.topology.portZ[i6] > 0 ? "rgba(52, 152, 219, 0.55)" : "rgba(128, 128, 128, 0.5)", layer: A3(e51, i6), label: p3(L3(e51, i6), D3(e51, i6)) });
    }
    t4.showInitialRouteHints !== false && ((e53, t6) => {
      for (let n6 = 0;n6 < e53.problem.routeCount; n6++) {
        const o6 = e53.problem.routeStartPort[n6], i6 = e53.problem.routeEndPort[n6], r6 = T3(e53, o6), s4 = T3(e53, i6), a4 = { x: (r6.x + s4.x) / 2, y: (r6.y + s4.y) / 2 };
        t6.lines.push({ points: [r6, s4], strokeColor: v3(e53, n6), strokeDash: "3 3", label: _3(e53, n6) }), t6.points.push({ x: a4.x, y: a4.y, color: v3(e53, n6, 1), label: _3(e53, n6) });
      }
    })(e51, n4);
  } else
    ((e53, t6) => {
      for (let n6 = 0;n6 < e53.state.regionSegments.length; n6++) {
        const o6 = e53.state.regionSegments[n6] ?? [];
        for (const [i6, r6, s4] of o6)
          t6.lines.push({ points: [T3(e53, r6), T3(e53, s4)], label: p3(`route: ${_3(e53, i6)}`, `region: region-${n6}`), ...z3(e53, i6, r6, s4) });
      }
    })(e51, n4), ((e53, t6) => {
      const n6 = new Set;
      for (let o6 = 0;o6 < e53.state.regionSegments.length; o6++) {
        const i6 = e53.state.regionSegments[o6] ?? [];
        for (const [o7, r6, s4] of i6)
          for (const i7 of [r6, s4]) {
            const r7 = `${o7}:${i7}`;
            if (n6.has(r7))
              continue;
            n6.add(r7);
            const s6 = T3(e53, i7);
            t6.points.push({ x: s6.x, y: s6.y, color: v3(e53, o7, 1), layer: A3(e53, i7), label: p3(`route: ${_3(e53, o7)}`, O3(e53, i7), k3(e53, i7, o7), D3(e53, i7)) });
          }
      }
    })(e51, n4), ((e53) => y3(e53) && e53.showUnassignedPortsInVisualization === true)(e51) && ((e53, t6) => {
      for (let n6 = 0;n6 < e53.topology.portCount; n6++)
        e53.state.portAssignment[n6] >= 0 || B3(e53, n6) || t6.circles.push({ center: E3(e53, n6), radius: 0.04, fill: e53.topology.portZ[n6] > 0 ? "rgba(52, 152, 219, 0.2)" : "rgba(128, 128, 128, 0.2)", stroke: e53.topology.portZ[n6] > 0 ? "rgba(52, 152, 219, 0.6)" : "rgba(128, 128, 128, 0.6)", layer: A3(e53, n6), label: p3(L3(e53, n6), D3(e53, n6), "state: unassigned") });
    })(e51, n4), y3(e51) || (((e53, t6) => {
      const n6 = e53.state.currentRouteId;
      if (n6 === undefined || e53.solved)
        return;
      const o6 = e53.problem.routeStartPort[n6], i6 = e53.problem.routeEndPort[n6], r6 = T3(e53, o6), s4 = T3(e53, i6), a4 = v3(e53, n6), c4 = _3(e53, n6);
      t6.lines.push({ points: [r6, s4], strokeColor: a4, strokeDash: "10 5", label: c4 });
    })(e51, n4), ((e53, t6) => {
      if (e53.solved)
        return;
      const n6 = e53.state.currentRouteId, o6 = e53.state.candidateQueue.toArray().sort((e54, t7) => e54.f - t7.f).slice(0, 10);
      for (let i7 = 0;i7 < o6.length; i7++) {
        const r7 = o6[i7], s6 = T3(e53, r7.portId), a4 = i7 === 0;
        t6.points.push({ x: s6.x, y: s6.y, color: a4 ? "green" : "rgba(128, 128, 128, 0.25)", layer: A3(e53, r7.portId), label: p3(L3(e53, r7.portId, n6), D3(e53, r7.portId), `g: ${r7.g.toFixed(2)}`, `h: ${r7.h.toFixed(2)}`, `f: ${r7.f.toFixed(2)}`) });
      }
      const i6 = o6[0];
      if (!i6)
        return;
      const r6 = [];
      let s4 = i6;
      for (;s4; )
        r6.unshift(T3(e53, s4.portId)), s4 = s4.prevCandidate;
      r6.length > 1 && t6.lines.push({ points: r6, strokeColor: n6 !== undefined ? v3(e53, n6) : "rgba(0, 160, 120, 0.9)" });
    })(e51, n4));
  o4 && F3(e51, n4, o4), ((e53, t6) => {
    if (e53.failed)
      for (const n6 of e53.getNeverSuccessfullyRoutedRoutes()) {
        const { routeId: o6, connectionId: i6, attempts: r6, startPortId: s4, endPortId: a4 } = n6, c4 = I3(e53, o6), l4 = E3(e53, s4), h4 = E3(e53, a4), d4 = p3(`never routed: ${i6}`, `attempts: ${r6}`, c4, n6.startRegionId ? `startRegionId: ${n6.startRegionId}` : undefined, n6.endRegionId ? `endRegionId: ${n6.endRegionId}` : undefined);
        t6.lines.push({ points: [{ x: 0, y: 0 }, { x: l4.x, y: l4.y }], strokeColor: h3, strokeDash: u3, layer: A3(e53, s4), label: p3(d4, "origin guide", "endpoint: start") }), t6.circles.push({ center: l4, radius: 1, fill: d3, stroke: h3, layer: A3(e53, s4), label: p3(d4, "endpoint: start", O3(e53, s4), D3(e53, s4)) }), t6.lines.push({ points: [{ x: 0, y: 0 }, { x: h4.x, y: h4.y }], strokeColor: h3, strokeDash: u3, layer: A3(e53, a4), label: p3(d4, "origin guide", "endpoint: end") }), t6.circles.push({ center: h4, radius: 1, fill: d3, stroke: h3, layer: A3(e53, a4), label: p3(d4, "endpoint: end", O3(e53, a4), D3(e53, a4)) });
      }
  })(e51, n4);
  const i4 = e51.state.unroutedRoutes.length + (e51.state.currentRouteId === undefined ? 0 : 1), r4 = o4 ? o4.reduce((e53, t6) => e53 + Number(t6 === 1), 0) : 0;
  return n4.title = ["Tiny HyperGraph", `iter=${e51.iterations}`, `pending=${i4}`, o4 ? `sectionPorts=${r4}` : undefined, e51.failed ? "failed" : e51.solved ? "solved" : "running"].filter(Boolean).join(" | "), n4;
};
var $3 = () => ({ netIds: new Int32Array(0), lesserAngles: new Int32Array(0), greaterAngles: new Int32Array(0), layerMasks: new Int32Array(0), existingCrossingLayerIntersections: 0, existingSameLayerIntersections: 0, existingEntryExitLayerChanges: 0, existingRegionCost: 0, existingSegmentCount: 0 });
var Y3 = (e51, t4) => e51.f - t4.f;
var X3 = class extends BaseSolver {
  constructor(e51, t4, n4) {
    super(), this.topology = e51, this.problem = t4, ((e53, t6) => {
      t6 && (t6.DISTANCE_TO_COST !== undefined && (e53.DISTANCE_TO_COST = t6.DISTANCE_TO_COST), t6.RIP_THRESHOLD_START !== undefined && (e53.RIP_THRESHOLD_START = t6.RIP_THRESHOLD_START), t6.RIP_THRESHOLD_END !== undefined && (e53.RIP_THRESHOLD_END = t6.RIP_THRESHOLD_END), t6.RIP_THRESHOLD_RAMP_ATTEMPTS !== undefined && (e53.RIP_THRESHOLD_RAMP_ATTEMPTS = t6.RIP_THRESHOLD_RAMP_ATTEMPTS), t6.RIP_CONGESTION_REGION_COST_FACTOR !== undefined && (e53.RIP_CONGESTION_REGION_COST_FACTOR = t6.RIP_CONGESTION_REGION_COST_FACTOR), t6.MAX_ITERATIONS !== undefined && (e53.MAX_ITERATIONS = t6.MAX_ITERATIONS), t6.VERBOSE !== undefined && (e53.VERBOSE = t6.VERBOSE), t6.STATIC_REACHABILITY_PRECHECK !== undefined && (e53.STATIC_REACHABILITY_PRECHECK = t6.STATIC_REACHABILITY_PRECHECK), t6.STATIC_REACHABILITY_PRECHECK_MAX_HOPS !== undefined && (e53.STATIC_REACHABILITY_PRECHECK_MAX_HOPS = t6.STATIC_REACHABILITY_PRECHECK_MAX_HOPS));
    })(this, n4), this.state = { portAssignment: new Int32Array(e51.portCount).fill(-1), regionSegments: Array.from({ length: e51.regionCount }, () => []), regionIntersectionCaches: Array.from({ length: e51.regionCount }, () => $3()), currentRouteId: undefined, currentRouteNetId: undefined, unroutedRoutes: a3(t4.routeCount), candidateQueue: new K5([], Y3), candidateBestCostByHopId: new Float64Array(e51.portCount * e51.regionCount), candidateBestCostGenerationByHopId: new Uint32Array(e51.portCount * e51.regionCount), candidateBestCostGeneration: 1, goalPortId: -1, ripCount: 0, regionCongestionCost: new Float64Array(e51.regionCount).fill(0) }, this.routeAttemptCountByRouteId = new Uint32Array(t4.routeCount), this.routeSuccessCountByRouteId = new Uint32Array(t4.routeCount);
  }
  state;
  _problemSetup;
  routeAttemptCountByRouteId;
  routeSuccessCountByRouteId;
  hasLoggedNeverSuccessfullyRoutedRoutes = false;
  segmentGeometryScratch = { lesserAngle: 0, greaterAngle: 0, layerMask: 0, entryExitLayerChanges: 0 };
  DISTANCE_TO_COST = 0.05;
  RIP_THRESHOLD_START = 0.05;
  RIP_THRESHOLD_END = 0.8;
  RIP_THRESHOLD_RAMP_ATTEMPTS = 50;
  RIP_CONGESTION_REGION_COST_FACTOR = 0.1;
  MAX_ITERATIONS = 1e6;
  VERBOSE = false;
  STATIC_REACHABILITY_PRECHECK = true;
  STATIC_REACHABILITY_PRECHECK_MAX_HOPS = 16;
  get problemSetup() {
    return this._problemSetup || (this._problemSetup = this.computeProblemSetup()), this._problemSetup;
  }
  computeProblemSetup() {
    const { topology: e51, problem: t4 } = this, n4 = e51.portX, o4 = e51.portY, i4 = new Float64Array(e51.portCount * t4.routeCount), r4 = Array.from({ length: e51.portCount }, () => new Set);
    for (let s4 = 0;s4 < t4.routeCount; s4++) {
      r4[t4.routeStartPort[s4]].add(t4.routeNet[s4]), r4[t4.routeEndPort[s4]].add(t4.routeNet[s4]);
      const a4 = t4.routeEndPort[s4], c4 = n4[a4], l4 = o4[a4];
      for (let r6 = 0;r6 < e51.portCount; r6++) {
        const e53 = n4[r6] - c4, a6 = o4[r6] - l4;
        i4[r6 * t4.routeCount + s4] = Math.hypot(e53, a6) * this.DISTANCE_TO_COST;
      }
    }
    return { portHCostToEndOfRoute: i4, portEndpointNetIds: r4 };
  }
  _setup() {
    if (this.problemSetup, this.STATIC_REACHABILITY_PRECHECK) {
      const e51 = s3({ topology: this.topology, problem: this.problem, problemSetup: this.problemSetup, portAssignment: this.state.portAssignment, routeIds: this.state.unroutedRoutes, maxPrecheckHops: Math.max(0, this.STATIC_REACHABILITY_PRECHECK_MAX_HOPS), getStartingNextRegionId: (e53, t4) => this.getStartingNextRegionId(e53, t4), getRouteSummary: (e53) => this.getRouteSummary(e53) });
      e51.length > 0 && (this.failed = true, this.error = ((e53) => {
        const t4 = e53.slice(0, 5).map((e54) => {
          const t6 = e54.pointIds.length >= 2 ? `${e54.pointIds[0]}->${e54.pointIds[1]}` : `${e54.startPortId}->${e54.endPortId}`;
          return `${e54.connectionId} (${t6})`;
        }).join(", "), n4 = e53.length - 5;
        return ["Static reachability precheck failed:", `${e53.length} route(s) have no legal path under the current reservation and start-region rules`, n4 > 0 ? `${t4}, +${n4} more` : t4].join(" ");
      })(e51), this.stats = { ...this.stats, staticallyUnroutableRouteCount: e51.length });
    }
  }
  _step() {
    const { problem: e51, topology: t4, state: n4 } = this;
    if (n4.currentRouteId === undefined) {
      if (n4.unroutedRoutes.length === 0)
        return void this.onAllRoutesRouted();
      n4.currentRouteId = n4.unroutedRoutes.shift(), n4.currentRouteNetId = e51.routeNet[n4.currentRouteId], this.routeAttemptCountByRouteId[n4.currentRouteId] += 1, this.resetCandidateBestCosts();
      const t6 = e51.routeStartPort[n4.currentRouteId];
      n4.candidateQueue.clear();
      const o6 = this.getStartingNextRegionId(n4.currentRouteId, t6);
      if (o6 === undefined)
        return this.failed = true, void (this.error = `Start port ${t6} has no incident regions`);
      this.setCandidateBestCost(this.getHopId(t6, o6), 0), n4.candidateQueue.queue({ nextRegionId: o6, portId: t6, f: 0, g: 0, h: 0 }), n4.goalPortId = e51.routeEndPort[n4.currentRouteId];
    }
    const o4 = n4.candidateQueue.dequeue();
    if (!o4)
      return void this.onOutOfCandidates();
    const i4 = this.getHopId(o4.portId, o4.nextRegionId);
    if (o4.g > this.getCandidateBestCost(i4))
      return;
    if (this.isRegionReservedForDifferentNet(o4.nextRegionId))
      return;
    const r4 = t4.regionIncidentPorts[o4.nextRegionId];
    for (const i6 of r4) {
      const r6 = n4.portAssignment[i6];
      if (this.isPortReservedForDifferentNet(i6))
        continue;
      if (i6 === n4.goalPortId) {
        if (r6 !== -1 && r6 !== n4.currentRouteNetId)
          continue;
        return void this.onPathFound(o4);
      }
      if (r6 !== -1 && r6 !== n4.currentRouteNetId)
        continue;
      if (i6 === o4.portId)
        continue;
      if (e51.portSectionMask[i6] === 0)
        continue;
      const s4 = this.computeG(o4, i6);
      if (!Number.isFinite(s4))
        continue;
      const a4 = this.computeH(i6), c4 = t4.incidentPortRegion[i6][0] === o4.nextRegionId ? t4.incidentPortRegion[i6][1] : t4.incidentPortRegion[i6][0];
      if (c4 === undefined || this.isRegionReservedForDifferentNet(c4))
        continue;
      const l4 = { prevRegionId: o4.nextRegionId, nextRegionId: c4, portId: i6, g: s4, h: a4, f: s4 + a4, prevCandidate: o4 };
      if (i6 === n4.goalPortId)
        return void this.onPathFound(l4);
      const h4 = this.getHopId(i6, c4);
      s4 >= this.getCandidateBestCost(h4) || (this.setCandidateBestCost(h4, s4), n4.candidateQueue.queue(l4));
    }
  }
  resetCandidateBestCosts() {
    const { state: e51 } = this;
    if (e51.candidateBestCostGeneration === 4294967295)
      return e51.candidateBestCostGenerationByHopId.fill(0), void (e51.candidateBestCostGeneration = 1);
    e51.candidateBestCostGeneration += 1;
  }
  getCandidateBestCost(e51) {
    const { state: t4 } = this;
    return t4.candidateBestCostGenerationByHopId[e51] === t4.candidateBestCostGeneration ? t4.candidateBestCostByHopId[e51] : Number.POSITIVE_INFINITY;
  }
  setCandidateBestCost(e51, t4) {
    const { state: n4 } = this;
    n4.candidateBestCostGenerationByHopId[e51] = n4.candidateBestCostGeneration, n4.candidateBestCostByHopId[e51] = t4;
  }
  getHopId(e51, t4) {
    return e51 * this.topology.regionCount + t4;
  }
  getStartingNextRegionId(e51, t4) {
    const n4 = this.topology.incidentPortRegion[t4] ?? [], o4 = this.problem.routeNet[e51];
    return n4.find((e53) => this.problem.regionNetId[e53] === -1) ?? n4.find((e53) => this.problem.regionNetId[e53] === o4) ?? n4[0];
  }
  isPortReservedForDifferentNet(e51) {
    const t4 = this.problemSetup.portEndpointNetIds[e51];
    if (!t4)
      return false;
    for (const e53 of t4)
      if (e53 !== this.state.currentRouteNetId)
        return true;
    return false;
  }
  isRegionReservedForDifferentNet(e51) {
    const t4 = this.problem.regionNetId[e51];
    return t4 !== -1 && t4 !== this.state.currentRouteNetId;
  }
  isKnownSingleLayerRegion(e51) {
    const t4 = this.topology.regionAvailableZMask?.[e51] ?? 0;
    return q5(t4);
  }
  computeRegionCostForRegion(e51, t4, n4, o4, i4) {
    return ((e53, t6, n6, o6, i6, r4, s4 = 0) => J5(e53 * t6, n6, o6, i6, r4, s4))(this.topology.regionWidth[e51], this.topology.regionHeight[e51], t4, n4, o4, i4, this.topology.regionAvailableZMask?.[e51] ?? 0);
  }
  populateSegmentGeometryScratch(e51, t4, n4) {
    const { topology: o4 } = this, i4 = this.segmentGeometryScratch, r4 = o4.incidentPortRegion[t4], s4 = o4.incidentPortRegion[n4], a4 = r4[0] === e51 || r4[1] !== e51 ? o4.portAngleForRegion1[t4] : o4.portAngleForRegion2?.[t4] ?? o4.portAngleForRegion1[t4], c4 = s4[0] === e51 || s4[1] !== e51 ? o4.portAngleForRegion1[n4] : o4.portAngleForRegion2?.[n4] ?? o4.portAngleForRegion1[n4], l4 = o4.portZ[t4], h4 = o4.portZ[n4];
    return i4.lesserAngle = a4 < c4 ? a4 : c4, i4.greaterAngle = a4 < c4 ? c4 : a4, i4.layerMask = 1 << l4 | 1 << h4, i4.entryExitLayerChanges = l4 !== h4 ? 1 : 0, i4;
  }
  appendSegmentToRegionCache(e51, t4, n4) {
    const { topology: o4, state: i4 } = this, r4 = i4.regionIntersectionCaches[e51], s4 = this.populateSegmentGeometryScratch(e51, t4, n4), [a4, c4, l4] = Q5(r4, i4.currentRouteNetId, s4.lesserAngle, s4.greaterAngle, s4.layerMask, s4.entryExitLayerChanges), h4 = r4.netIds.length + 1, d4 = new Int32Array(h4);
    d4.set(r4.netIds), d4[h4 - 1] = i4.currentRouteNetId;
    const u4 = new Int32Array(h4);
    u4.set(r4.lesserAngles), u4[h4 - 1] = s4.lesserAngle;
    const p4 = new Int32Array(h4);
    p4.set(r4.greaterAngles), p4[h4 - 1] = s4.greaterAngle;
    const m4 = new Int32Array(h4);
    m4.set(r4.layerMasks), m4[h4 - 1] = s4.layerMask;
    const g4 = r4.existingSameLayerIntersections + a4, f4 = r4.existingCrossingLayerIntersections + c4, _4 = r4.existingEntryExitLayerChanges + l4, y4 = u4.length;
    i4.regionIntersectionCaches[e51] = { netIds: d4, lesserAngles: u4, greaterAngles: p4, layerMasks: m4, existingSameLayerIntersections: g4, existingCrossingLayerIntersections: f4, existingEntryExitLayerChanges: _4, existingSegmentCount: y4, existingRegionCost: this.computeRegionCostForRegion(e51, g4, f4, _4, y4) };
  }
  getSolvedPathSegments(e51) {
    const { state: t4 } = this, n4 = [];
    let o4 = e51;
    for (;o4; )
      n4.unshift(o4), o4 = o4.prevCandidate;
    const i4 = [];
    for (let e53 = 1;e53 < n4.length; e53++)
      i4.push({ regionId: n4[e53 - 1].nextRegionId, fromPortId: n4[e53 - 1].portId, toPortId: n4[e53].portId });
    const r4 = n4[n4.length - 1];
    return r4 && r4.portId !== t4.goalPortId && i4.push({ regionId: r4.nextRegionId, fromPortId: r4.portId, toPortId: t4.goalPortId }), i4;
  }
  resetRoutingStateForRerip() {
    const { topology: e51, problem: t4, state: n4 } = this;
    n4.portAssignment.fill(-1), n4.regionSegments = Array.from({ length: e51.regionCount }, () => []), n4.regionIntersectionCaches = Array.from({ length: e51.regionCount }, () => $3()), n4.currentRouteNetId = undefined, n4.currentRouteId = undefined, n4.unroutedRoutes = e310(a3(t4.routeCount), n4.ripCount), n4.candidateQueue.clear(), this.resetCandidateBestCosts(), n4.goalPortId = -1;
  }
  getMaxRegionCost() {
    const { topology: e51, state: t4 } = this;
    let n4 = 0;
    for (let o4 = 0;o4 < e51.regionCount; o4++) {
      const e53 = t4.regionIntersectionCaches[o4]?.existingRegionCost ?? 0;
      n4 = Math.max(n4, e53);
    }
    return n4;
  }
  getRouteMetadata(e51) {
    return this.problem.routeMetadata?.[e51];
  }
  getRouteConnectionId(e51) {
    const t4 = this.getRouteMetadata(e51)?.connectionId;
    return typeof t4 == "string" ? t4 : `route-${e51}`;
  }
  getRouteSummary(e51) {
    return (({ problem: e53, routeId: t4, getRouteMetadata: n4, getRouteConnectionId: o4 }) => {
      const i4 = n4?.(t4) ?? t3(e53, t4);
      return { routeId: t4, connectionId: o4?.(t4) ?? o3(e53, t4), startPortId: e53.routeStartPort[t4], endPortId: e53.routeEndPort[t4], startRegionId: typeof i4?.startRegionId == "string" ? i4.startRegionId : undefined, endRegionId: typeof i4?.endRegionId == "string" ? i4.endRegionId : undefined, pointIds: n3(i4) };
    })({ problem: this.problem, routeId: e51, getRouteMetadata: (e53) => this.getRouteMetadata(e53), getRouteConnectionId: (e53) => this.getRouteConnectionId(e53) });
  }
  getAdditionalRegionLabel(e51) {}
  getNeverSuccessfullyRoutedRoutes() {
    const e51 = [];
    for (let t4 = 0;t4 < this.problem.routeCount; t4++) {
      const n4 = this.routeAttemptCountByRouteId[t4];
      n4 === 0 || this.routeSuccessCountByRouteId[t4] > 0 || e51.push({ ...this.getRouteSummary(t4), attempts: n4 });
    }
    return e51;
  }
  logNeverSuccessfullyRoutedRoutes() {
    if (!this.VERBOSE || this.hasLoggedNeverSuccessfullyRoutedRoutes)
      return;
    const e51 = this.getNeverSuccessfullyRoutedRoutes();
    if (this.hasLoggedNeverSuccessfullyRoutedRoutes = true, e51.length !== 0) {
      console.log(["[TinyHyperGraphSolver:never-routed-summary]", `count=${e51.length}`].join(" "));
      for (const t4 of e51) {
        const e53 = t4.pointIds.length >= 2 ? `${t4.pointIds[0]}->${t4.pointIds[1]}` : "unknown";
        console.log(["[TinyHyperGraphSolver:never-routed]", `routeId=${t4.routeId}`, `connectionId=${t4.connectionId}`, `attempts=${t4.attempts}`, `pointPath=${e53}`, `startRegionId=${t4.startRegionId ?? "unknown"}`, `endRegionId=${t4.endRegionId ?? "unknown"}`].join(" "));
      }
    }
  }
  logRipEvent(e51, t4, n4 = {}) {
    this.VERBOSE && console.log(["[TinyHyperGraphSolver:rip]", `ripCount=${this.state.ripCount}`, `maxRegionCostBeforeRip=${t4.toFixed(3)}`, `reason=${e51}`, ...Object.entries(n4).map(([e53, t6]) => `${e53}=${typeof t6 == "number" ? Number.isInteger(t6) ? String(t6) : t6.toFixed(3) : t6}`)].join(" "));
  }
  onAllRoutesRouted() {
    const { topology: e51, state: t4 } = this, n4 = this.RIP_THRESHOLD_RAMP_ATTEMPTS <= 0 ? 1 : Math.min(1, t4.ripCount / this.RIP_THRESHOLD_RAMP_ATTEMPTS), o4 = this.RIP_THRESHOLD_START + (this.RIP_THRESHOLD_END - this.RIP_THRESHOLD_START) * n4, i4 = [], r4 = new Float64Array(e51.regionCount);
    let s4 = 0;
    for (let n6 = 0;n6 < e51.regionCount; n6++) {
      const e53 = t4.regionIntersectionCaches[n6]?.existingRegionCost ?? 0;
      r4[n6] = e53, s4 = Math.max(s4, e53), e53 > o4 && i4.push(n6);
    }
    if (this.stats = { ...this.stats, currentRipThreshold: o4, hotRegionCount: i4.length, maxRegionCost: s4, ripCount: t4.ripCount }, i4.length === 0 || t4.ripCount >= this.RIP_THRESHOLD_RAMP_ATTEMPTS)
      this.solved = true;
    else {
      for (let n6 = 0;n6 < e51.regionCount; n6++)
        t4.regionCongestionCost[n6] += r4[n6] * this.RIP_CONGESTION_REGION_COST_FACTOR;
      t4.ripCount += 1, this.resetRoutingStateForRerip(), this.stats = { ...this.stats, ripCount: t4.ripCount, maxRegionCostBeforeRip: s4, reripRegionCount: i4.length }, this.logRipEvent("hot_regions", s4, { hotRegionCount: i4.length, currentRipThreshold: o4 });
    }
  }
  onOutOfCandidates() {
    const { topology: e51, state: t4 } = this, n4 = t4.currentRouteId, o4 = this.getMaxRegionCost();
    for (let n6 = 0;n6 < e51.regionCount; n6++) {
      const e53 = t4.regionIntersectionCaches[n6]?.existingRegionCost ?? 0;
      t4.regionCongestionCost[n6] += e53 * this.RIP_CONGESTION_REGION_COST_FACTOR;
    }
    t4.ripCount += 1, this.resetRoutingStateForRerip(), this.stats = { ...this.stats, ripCount: t4.ripCount, maxRegionCost: o4, maxRegionCostBeforeRip: o4, reripReason: "out_of_candidates" }, this.logRipEvent("out_of_candidates", o4, { ...n4 === undefined ? {} : { routeId: n4, connectionId: this.getRouteConnectionId(n4) } });
  }
  onPathFound(e51) {
    const { state: t4 } = this, n4 = t4.currentRouteId;
    if (n4 === undefined)
      return;
    this.routeSuccessCountByRouteId[n4] += 1;
    const o4 = this.getSolvedPathSegments(e51);
    for (const { regionId: e53, fromPortId: i4, toPortId: r4 } of o4)
      t4.regionSegments[e53].push([n4, i4, r4]), t4.portAssignment[i4] = t4.currentRouteNetId, t4.portAssignment[r4] = t4.currentRouteNetId, this.appendSegmentToRegionCache(e53, i4, r4);
    t4.candidateQueue.clear(), t4.currentRouteNetId = undefined, t4.currentRouteId = undefined;
  }
  computeG(e51, t4) {
    const { topology: n4, state: o4 } = this, i4 = e51.nextRegionId, r4 = o4.regionIntersectionCaches[i4], s4 = this.populateSegmentGeometryScratch(i4, e51.portId, t4), [a4, c4, l4] = Q5(r4, o4.currentRouteNetId, s4.lesserAngle, s4.greaterAngle, s4.layerMask, s4.entryExitLayerChanges);
    if (a4 > 0 && this.isKnownSingleLayerRegion(i4))
      return Number.POSITIVE_INFINITY;
    const h4 = this.computeRegionCostForRegion(i4, r4.existingSameLayerIntersections + a4, r4.existingCrossingLayerIntersections + c4, r4.existingEntryExitLayerChanges + l4, r4.existingSegmentCount + 1) - r4.existingRegionCost;
    return e51.g + h4 + o4.regionCongestionCost[i4];
  }
  tryFinalAcceptance() {
    const e51 = this.getNeverSuccessfullyRoutedRoutes();
    this.stats = { ...this.stats, neverSuccessfullyRoutedRouteCount: e51.length }, this.logNeverSuccessfullyRoutedRoutes();
  }
  computeH(e51) {
    return this.problemSetup.portHCostToEndOfRoute[e51 * this.problem.routeCount + this.state.currentRouteId];
  }
  visualize() {
    return j3(this);
  }
  getOutput() {
    return Z5(this);
  }
};
var H3 = (e51) => {
  const t4 = typeof e51.d?.netId == "number" ? e51.d.netId : typeof e51.d?.NetId == "number" ? e51.d.NetId : undefined;
  return Number.isFinite(t4) ? t4 : undefined;
};
var V3 = (e51) => {
  const t4 = new Set;
  for (const n6 of e51.connections ?? [])
    t4.add(n6.startRegionId), t4.add(n6.endRegionId);
  const n4 = new Set(e51.regions.filter((e53) => ((e54) => {
    if (e54.d?._containsObstacle !== true)
      return false;
    if (e54.d?._containsTarget !== true)
      return true;
    const t6 = H3(e54);
    return t6 === undefined || t6 === -1;
  })(e53) && !t4.has(e53.regionId)).map((e53) => e53.regionId));
  if (n4.size === 0)
    return e51;
  const o4 = e51.ports.filter((e53) => !n4.has(e53.region1Id) && !n4.has(e53.region2Id)), i4 = (e51.connections ?? []).find((e53) => n4.has(e53.startRegionId) || n4.has(e53.endRegionId));
  if (i4)
    throw new Error(`Connection "${i4.connectionId}" references full-obstacle region`);
  return { ...e51, regions: e51.regions.filter((e53) => !n4.has(e53.regionId)), ports: o4 };
};
var W3 = (e51) => {
  const t4 = e51.d?.bounds;
  if (t4)
    return t4;
  const n4 = e51.d?.center, o4 = e51.d?.width, i4 = e51.d?.height;
  return n4 && typeof n4.x == "number" && typeof n4.y == "number" && typeof o4 == "number" && typeof i4 == "number" ? { minX: n4.x - o4 / 2, maxX: n4.x + o4 / 2, minY: n4.y - i4 / 2, maxY: n4.y + i4 / 2 } : { minX: 0, maxX: 0, minY: 0, maxY: 0 };
};
var G3 = (e51) => {
  const t4 = Number(e51.d?.z ?? 0);
  return Number.isFinite(t4) ? t4 : 0;
};
var U3 = (e51) => 0.005 * G3(e51);
var Z3 = (e51) => Number(e51.d?.x ?? 0) + U3(e51);
var q3 = (e51) => Number(e51.d?.y ?? 0) + U3(e51);
var J3 = (e51, t4) => {
  if (!t4)
    return 0;
  const n4 = W3(t4), o4 = Z3(e51), i4 = q3(e51), r4 = n4.minX <= o4 && o4 <= n4.maxX, s4 = n4.minY <= i4 && i4 <= n4.maxY;
  if (s4 && o4 >= n4.maxX) {
    const e53 = Math.max(n4.maxY - n4.minY, 0.000000001), t6 = (i4 - n4.minY) / e53;
    return Math.round(9000 * t6);
  }
  if (r4 && i4 >= n4.maxY) {
    const e53 = Math.max(n4.maxX - n4.minX, 0.000000001), t6 = (n4.maxX - o4) / e53;
    return 9000 + Math.round(9000 * t6);
  }
  if (s4 && o4 <= n4.minX) {
    const e53 = Math.max(n4.maxY - n4.minY, 0.000000001), t6 = (n4.maxY - i4) / e53;
    return 18000 + Math.round(9000 * t6);
  }
  if (r4 && i4 <= n4.minY) {
    const e53 = Math.max(n4.maxX - n4.minX, 0.000000001), t6 = (o4 - n4.minX) / e53;
    return 27000 + Math.round(9000 * t6);
  }
  const a4 = Math.abs(o4 - n4.minX), c4 = Math.abs(o4 - n4.maxX), l4 = Math.abs(i4 - n4.minY), h4 = Math.abs(i4 - n4.maxY), d4 = Math.min(a4, c4, l4, h4), u4 = Math.max(n4.maxX - n4.minX, 0.000000001), p4 = Math.max(n4.maxY - n4.minY, 0.000000001);
  if (d4 === c4) {
    const e53 = (i4 - n4.minY) / p4;
    return Math.round(9000 * e53);
  }
  if (d4 === h4) {
    const e53 = (n4.maxX - o4) / u4;
    return 9000 + Math.round(9000 * e53);
  }
  if (d4 === a4) {
    const e53 = (n4.maxY - i4) / p4;
    return 18000 + Math.round(9000 * e53);
  }
  const m4 = (o4 - n4.minX) / u4;
  return 27000 + Math.round(9000 * m4);
};
var Q3 = (e51, t4) => {
  if (!e51)
    return;
  return [...e51.pointIds].sort((e53, n4) => {
    const o4 = t4.get(e53), i4 = t4.get(n4), r4 = Number(o4?.d?.distToCentermostPortOnZ ?? Number.POSITIVE_INFINITY), s4 = Number(i4?.d?.distToCentermostPortOnZ ?? Number.POSITIVE_INFINITY);
    if (r4 !== s4)
      return r4 - s4;
    const a4 = Number(o4?.d?.z ?? 0), c4 = Number(i4?.d?.z ?? 0);
    return a4 !== c4 ? a4 - c4 : e53.localeCompare(n4);
  })[0];
};
var K3 = (e51) => {
  const t4 = V3(e51), n4 = new Map, o4 = new Map, i4 = new Map, r4 = new Map((t4.solvedRoutes ?? []).map((e53) => [e53.connection.connectionId, e53]));
  t4.regions.forEach((e53, t6) => {
    n4.set(e53.regionId, t6);
  }), t4.ports.forEach((e53, t6) => {
    o4.set(e53.portId, t6), i4.set(e53.portId, e53);
  });
  const s4 = t4.regions.length, a4 = t4.ports.length, c4 = t4.regions.map((e53) => e53.pointIds.map((e54) => o4.get(e54)).filter((e54) => e54 !== undefined)), l4 = Array.from({ length: a4 }, () => []), h4 = new Float64Array(s4), d4 = new Float64Array(s4), u4 = new Float64Array(s4), p4 = new Float64Array(s4), m4 = new Int32Array(s4), g4 = new Int32Array(s4).fill(-1), f4 = new Int8Array(s4);
  t4.regions.forEach((e53, t6) => {
    const n6 = ((e54) => {
      const t7 = W3(e54), n7 = typeof e54.d?.width == "number" ? e54.d.width : t7.maxX - t7.minX, o7 = typeof e54.d?.height == "number" ? e54.d.height : t7.maxY - t7.minY;
      return { centerX: typeof e54.d?.center?.x == "number" ? e54.d.center.x : (t7.minX + t7.maxX) / 2, centerY: typeof e54.d?.center?.y == "number" ? e54.d.center.y : (t7.minY + t7.maxY) / 2, width: n7, height: o7 };
    })(e53);
    h4[t6] = n6.width, d4[t6] = n6.height, u4[t6] = n6.centerX, p4[t6] = n6.centerY, m4[t6] = ((e54) => {
      const t7 = e54.d?.availableZ;
      if (!Array.isArray(t7))
        return 0;
      let n7 = 0;
      for (const e55 of t7)
        !Number.isInteger(e55) || e55 < 0 || e55 >= 31 || (n7 |= 1 << e55);
      return n7;
    })(e53);
    const o6 = H3(e53);
    o6 !== undefined && (g4[t6] = o6, f4[t6] = 1);
  });
  const _4 = new Int32Array(a4), y4 = new Int32Array(a4), b4 = new Float64Array(a4), x4 = new Float64Array(a4), v4 = new Int32Array(a4);
  t4.ports.forEach((e53, o6) => {
    const i6 = n4.get(e53.region1Id), r6 = n4.get(e53.region2Id);
    if (i6 === undefined || r6 === undefined)
      throw new Error(`Port "${e53.portId}" references missing regions "${e53.region1Id}" or "${e53.region2Id}"`);
    l4[o6] = [i6, r6], b4[o6] = Z3(e53), x4[o6] = q3(e53), v4[o6] = G3(e53), _4[o6] = J3(e53, t4.regions[i6]), y4[o6] = J3(e53, t4.regions[r6]);
  });
  const I4 = t4.regions.map((e53, t6) => ((e54, t7) => {
    const n6 = e54.d && typeof e54.d == "object" && !Array.isArray(e54.d) ? { ...e54.d } : { value: e54.d };
    return n6.layer = t7, Object.defineProperty(n6, "serializedRegionId", { value: e54.regionId, enumerable: false, configurable: true, writable: true }), n6;
  })(e53, ((e54) => F5(j5(m4[e54])) ?? F5((c4[e54] ?? []).map((e55) => v4[e55])) ?? "z0")(t6))), S4 = t4.ports.map((e53, t6) => ((e54, t7) => {
    const n6 = e54.d && typeof e54.d == "object" && !Array.isArray(e54.d) ? { ...e54.d } : { value: e54.d };
    return n6.layer = t7, Object.defineProperty(n6, "serializedPortId", { value: e54.portId, enumerable: false, configurable: true, writable: true }), n6;
  })(e53, F5([v4[t6]]) ?? "z0")), C = t4.connections ?? [], P = new Map;
  let M = 0;
  const w = (e53) => {
    const t6 = e53.mutuallyConnectedNetworkId ?? e53.connectionId;
    let n6 = P.get(t6);
    return n6 === undefined && (n6 = M++, P.set(t6, n6)), n6;
  }, N = Array.from({ length: s4 }, () => new Set), R4 = (e53, t6) => {
    const o6 = n4.get(e53);
    if (o6 === undefined)
      throw new Error(`Connection references missing region "${e53}"`);
    N[o6].add(t6);
  };
  C.forEach((e53) => {
    const t6 = w(e53);
    R4(e53.startRegionId, t6), R4(e53.endRegionId, t6);
  }), N.forEach((e53, t6) => {
    f4[t6] !== 1 && e53.size === 1 && (g4[t6] = [...e53][0]);
  });
  const T2 = C.map((e53) => {
    const n6 = r4.get(e53.connectionId), o6 = ((e54, t6) => e54.ports.filter((e55) => e55.region1Id === t6.startRegionId && e55.region2Id === t6.endRegionId || e55.region2Id === t6.startRegionId && e55.region1Id === t6.endRegionId).map((e55) => e55.portId))(t4, e53);
    return { connection: e53, solvedRoute: n6, sharedPortIds: o6 };
  }).filter(({ solvedRoute: e53, sharedPortIds: t6 }) => t6.length === 0 || (e53?.path.length ?? 0) > 1), E4 = T2.length, A4 = new Int8Array(a4).fill(1), O4 = new Int32Array(E4), k4 = new Int32Array(E4), D4 = new Int32Array(E4);
  T2.forEach(({ connection: e53, solvedRoute: n6 }, r6) => {
    const s6 = Q3(t4.regions.find((t6) => t6.regionId === e53.startRegionId), i4), a6 = Q3(t4.regions.find((t6) => t6.regionId === e53.endRegionId), i4), c5 = n6?.path[0]?.portId ?? s6, l5 = n6?.path[n6.path.length - 1]?.portId ?? a6, h5 = c5 !== undefined ? o4.get(c5) : undefined, d6 = l5 !== undefined ? o4.get(l5) : undefined;
    if (h5 === undefined || d6 === undefined)
      throw new Error(`Connection "${e53.connectionId}" could not be mapped to route endpoints`);
    O4[r6] = h5, k4[r6] = d6, D4[r6] = w(e53);
  });
  const L4 = { portCount: a4, regionCount: s4, regionIncidentPorts: c4, incidentPortRegion: l4, regionWidth: h4, regionHeight: d4, regionCenterX: u4, regionCenterY: p4, regionAvailableZMask: m4, regionMetadata: I4, portAngleForRegion1: _4, portAngleForRegion2: y4, portX: b4, portY: x4, portZ: v4, portMetadata: S4 }, z4 = { routeCount: E4, portSectionMask: A4, routeMetadata: T2.map(({ connection: e53 }) => e53), routeStartPort: O4, routeEndPort: k4, routeNet: D4, regionNetId: g4 }, B4 = [], F4 = [];
  for (const { solvedRoute: e53 } of T2) {
    if (!e53) {
      B4.push([]), F4.push([]);
      continue;
    }
    const t6 = [], i6 = [];
    for (let r6 = 1;r6 < e53.path.length; r6++) {
      const s6 = e53.path[r6 - 1], a6 = e53.path[r6], c5 = s6?.portId, l5 = a6?.portId, h5 = c5 !== undefined ? o4.get(c5) : undefined, d6 = l5 !== undefined ? o4.get(l5) : undefined;
      if (h5 === undefined || d6 === undefined)
        continue;
      const u6 = typeof s6?.nextRegionId == "string" ? s6.nextRegionId : typeof a6?.lastRegionId == "string" ? a6.lastRegionId : undefined;
      t6.push([h5, d6]), i6.push(u6 !== undefined ? n4.get(u6) : undefined);
    }
    B4.push(t6), F4.push(i6);
  }
  return { topology: L4, problem: z4, solution: { solvedRoutePathSegments: B4, solvedRoutePathRegionIds: F4 } };
};
Number.POSITIVE_INFINITY;
var n4 = 0.000000001;
var o4 = (e51) => typeof e51 == "object" && e51 !== null;
var i4 = (e51, t4 = 0) => typeof e51 == "number" && Number.isFinite(e51) ? e51 : t4;
var r4 = (e51) => {
  const t4 = ((e53) => {
    const t6 = Math.min(e53.minX, e53.maxX), n6 = Math.max(e53.minX, e53.maxX), o6 = Math.min(e53.minY, e53.maxY), i6 = Math.max(e53.minY, e53.maxY);
    return { minX: t6, maxX: n6 > t6 ? n6 : t6 + n4, minY: o6, maxY: i6 > o6 ? i6 : o6 + n4 };
  })(e51);
  return [{ x: t4.maxX, y: t4.minY }, { x: t4.maxX, y: t4.maxY }, { x: t4.minX, y: t4.maxY }, { x: t4.minX, y: t4.minY }];
};
var s4 = (e51, t4) => {
  const n6 = e51.filter((e53) => Number.isFinite(e53.x) && Number.isFinite(e53.y)), o6 = n6.length >= 3 ? n6 : r4(t4), i6 = ((e53) => {
    let t6 = 0;
    for (let n7 = 0;n7 < e53.length; n7++) {
      const o7 = e53[n7], i7 = e53[(n7 + 1) % e53.length];
      t6 += o7.x * i7.y - o7.y * i7.x;
    }
    return t6;
  })(o6);
  if (Math.abs(i6) <= Number.EPSILON)
    return r4(t4);
  return ((e53) => {
    if (e53.length < 3)
      throw new Error("Convex polygon requires at least three points");
    return e53;
  })(i6 < 0 ? [...o6].reverse() : [...o6]);
};
var a4 = (e51) => {
  const t4 = ((e53) => {
    const t6 = e53.d, n6 = t6?.bounds;
    if (n6 && typeof n6.minX == "number" && typeof n6.maxX == "number" && typeof n6.minY == "number" && typeof n6.maxY == "number")
      return { minX: n6.minX, maxX: n6.maxX, minY: n6.minY, maxY: n6.maxY };
    const o6 = t6?.center, i6 = i4(t6?.width, 0), r6 = i4(t6?.height, 0);
    return o6 && typeof o6.x == "number" && typeof o6.y == "number" ? { minX: o6.x - i6 / 2, maxX: o6.x + i6 / 2, minY: o6.y - r6 / 2, maxY: o6.y + r6 / 2 } : { minX: 0, maxX: n4, minY: 0, maxY: n4 };
  })(e51);
  return s4(((e53) => {
    const t6 = e53.d, n6 = t6?.polygon ?? t6?.points ?? t6?.vertices;
    if (!Array.isArray(n6))
      return;
    const o6 = n6.map((e54) => {
      if (!o4(e54))
        return;
      const { x: t7, y: n7 } = e54;
      return typeof t7 == "number" && typeof n7 == "number" ? { x: t7, y: n7 } : undefined;
    }).filter((e54) => e54 !== undefined);
    if (o6.length > 1) {
      const e54 = o6[0], t7 = o6[o6.length - 1];
      e54.x === t7.x && e54.y === t7.y && o6.pop();
    }
    return o6.length >= 3 ? o6 : undefined;
  })(e51) ?? r4(t4), t4);
};
var c4 = (e51) => {
  let t4 = 0, n6 = 0, o6 = 0, i6 = 0, r6 = Number.POSITIVE_INFINITY, s6 = Number.NEGATIVE_INFINITY, a6 = Number.POSITIVE_INFINITY, c5 = Number.NEGATIVE_INFINITY;
  for (let l5 = 0;l5 < e51.length; l5++) {
    const h5 = e51[l5], d6 = e51[(l5 + 1) % e51.length], u4 = h5.x * d6.y - d6.x * h5.y;
    t4 += u4, n6 += (h5.x + d6.x) * u4, o6 += (h5.y + d6.y) * u4, i6 += Math.hypot(d6.x - h5.x, d6.y - h5.y), r6 = Math.min(r6, h5.x), s6 = Math.max(s6, h5.x), a6 = Math.min(a6, h5.y), c5 = Math.max(c5, h5.y);
  }
  const l4 = Math.abs(t4) / 2, h4 = Math.abs(t4) > Number.EPSILON ? 3 * t4 : Number.NaN, d4 = e51.reduce((t6, n7) => ({ x: t6.x + n7.x / e51.length, y: t6.y + n7.y / e51.length }), { x: 0, y: 0 });
  return { area: l4, perimeter: i6, centerX: Number.isFinite(h4) ? n6 / h4 : d4.x, centerY: Number.isFinite(h4) ? o6 / h4 : d4.y, bounds: { minX: r6, maxX: s6, minY: a6, maxY: c5 } };
};
var l4 = (e51, t4, n6, o6) => {
  if (n6 <= 0)
    return { boundaryPosition: 0, edgeIndex: 0, edgeT: 0 };
  let i6 = Number.POSITIVE_INFINITY, r6 = 0, s6 = 0, a6 = 0, c5 = 0;
  for (let n7 = 0;n7 < t4.length; n7++) {
    const o7 = t4[n7], l5 = t4[(n7 + 1) % t4.length], h4 = l5.x - o7.x, d4 = l5.y - o7.y, u4 = h4 * h4 + d4 * d4, p4 = Math.sqrt(u4), m4 = u4 <= Number.EPSILON ? 0 : ((e51.x - o7.x) * h4 + (e51.y - o7.y) * d4) / u4, g4 = Math.min(1, Math.max(0, m4)), f4 = o7.x + h4 * g4, _4 = o7.y + d4 * g4, y4 = e51.x - f4, b4 = e51.y - _4, x4 = y4 * y4 + b4 * b4;
    x4 < i6 && (i6 = x4, r6 = n7, s6 = g4, a6 = c5 + p4 * g4), c5 += p4;
  }
  return { boundaryPosition: Math.round(a6 / n6 * o6) % o6, edgeIndex: r6, edgeT: s6 };
};
var h4 = (e51, t4) => {
  const n6 = e51.regionMetadata?.[t4];
  return o4(n6) && typeof n6.serializedRegionId == "string" ? n6.serializedRegionId : `region-${t4}`;
};
var d4 = (e51, t4) => {
  const n6 = e51.portMetadata?.[t4];
  return o4(n6) && typeof n6.serializedPortId == "string" ? n6.serializedPortId : `port-${t4}`;
};
var u4 = (e51, t4, n6, o6) => {
  const i6 = { ...o4(e51) ? { ...e51 } : e51 === undefined ? {} : { value: e51 }, polygon: n6, sourceBounds: o6 };
  return Object.defineProperty(i6, "serializedRegionId", { value: t4, enumerable: false, configurable: true, writable: true }), i6;
};
var p4 = (e51, t4) => {
  const n6 = new Map, o6 = new Map, i6 = new Map, r6 = new Map;
  for (let t6 = 0;t6 < e51.regionCount; t6++)
    n6.set(h4(e51, t6), t6);
  for (let t6 = 0;t6 < e51.portCount; t6++)
    o6.set(d4(e51, t6), t6);
  for (let e53 = 0;e53 < t4.routeCount; e53++) {
    const n7 = t4.routeMetadata?.[e53];
    if (!o4(n7))
      continue;
    typeof n7.connectionId == "string" && i6.set(n7.connectionId, e53);
    const o7 = typeof n7.mutuallyConnectedNetworkId == "string" ? n7.mutuallyConnectedNetworkId : typeof n7.connectionId == "string" ? n7.connectionId : undefined;
    o7 !== undefined && r6.set(o7, t4.routeNet[e53]);
  }
  return { serializedRegionIdToRegionId: n6, serializedPortIdToPortId: o6, connectionIdToRouteId: i6, netIdToNetIndex: r6 };
};
var m4 = (e51, t4, n6) => {
  const o6 = e51.incidentPortRegion[t4];
  return o6[0] === n6 || o6[1] !== n6 ? e51.portBoundaryPositionForRegion1[t4] : e51.portBoundaryPositionForRegion2[t4];
};
var g4 = class extends X3 {
  constructor(e51, t4, n6) {
    super(e51, t4, n6), this.topology = e51, this.problem = t4;
  }
  polySegmentGeometryScratch = { lesserAngle: 0, greaterAngle: 0, layerMask: 0, entryExitLayerChanges: 0 };
  populateSegmentGeometryScratch(e51, t4, n6) {
    const { topology: o6 } = this, i6 = this.polySegmentGeometryScratch, r6 = m4(o6, t4, e51), s6 = m4(o6, n6, e51), a6 = o6.portZ[t4], c5 = o6.portZ[n6];
    return i6.lesserAngle = r6 < s6 ? r6 : s6, i6.greaterAngle = r6 < s6 ? s6 : r6, i6.layerMask = 1 << a6 | 1 << c5, i6.entryExitLayerChanges = a6 !== c5 ? 1 : 0, i6;
  }
  computeRegionCostForRegion(e51, t4, n6, o6, i6) {
    return J5(this.topology.regionArea[e51], t4, n6, o6, i6, this.topology.regionAvailableZMask?.[e51] ?? 0);
  }
  visualize() {
    return M4(this);
  }
};
var f4 = (...e51) => e51.filter((e53) => Boolean(e53)).join(`
`);
var _4 = (e51, t4) => {
  const n6 = e51.problem.routeMetadata?.[t4];
  return n6?.connectionId ?? n6?.mutuallyConnectedNetworkId ?? `route-${t4}`;
};
var y4 = (e51, t4, n6 = 0.85) => {
  const o6 = `${e51.problem.routeNet[t4]}:${_4(e51, t4)}`;
  let i6 = 0;
  for (let e53 = 0;e53 < o6.length; e53++)
    i6 = 17777 * o6.charCodeAt(e53) + ((i6 << 5) - i6);
  return `hsla(${Math.abs(i6) % 360}, 70%, 45%, ${n6})`;
};
var b4 = (e51, t4) => {
  const n6 = e51.regionVertexStart[t4], o6 = e51.regionVertexCount[t4], i6 = [];
  for (let t6 = 0;t6 < o6; t6++) {
    const o7 = n6 + t6;
    i6.push({ x: e51.regionVertexX[o7], y: e51.regionVertexY[o7] });
  }
  return i6;
};
var x4 = (e51, t4) => {
  const n6 = e51.state.regionIntersectionCaches[t4]?.existingRegionCost ?? 0, o6 = Math.min(1, Math.max(0, Math.pow(n6, 0.8))), i6 = Math.round(245 - 105 * o6);
  return `rgba(245, ${Math.round(248 - 168 * o6)}, ${i6}, ${0.18 + 0.48 * o6})`;
};
var v4 = (e51, t4) => {
  const n6 = e51.state.regionIntersectionCaches[t4], o6 = h4(e51.topology, t4), i6 = e51.problem.regionNetId[t4];
  return f4(`region: ${o6}`, `net: ${i6 === -1 ? "free" : i6}`, `area: ${e51.topology.regionArea[t4].toFixed(3)}`, `cost: ${(n6?.existingRegionCost ?? 0).toFixed(3)}`, `same layer X: ${n6?.existingSameLayerIntersections ?? 0}`, `trans X: ${n6?.existingCrossingLayerIntersections ?? 0}`, `entry exit X: ${n6?.existingEntryExitLayerChanges ?? 0}`);
};
var I4 = (e51, t4) => F5(j5(e51.topology.regionAvailableZMask?.[t4] ?? 0)) ?? F5((e51.topology.regionIncidentPorts[t4] ?? []).map((t6) => e51.topology.portZ[t6])) ?? "z0";
var S4 = (e51, t4) => ({ x: e51.topology.portX[t4], y: e51.topology.portY[t4] });
var C4 = (e51, t4) => F5([e51.topology.portZ[t4]]) ?? "z0";
var P4 = (e51, t4) => {
  const [n6, o6] = e51.topology.incidentPortRegion[t4] ?? [];
  return f4(`port: ${d4(e51.topology, t4)}`, `connects: ${n6 ?? "?"} <-> ${o6 ?? "?"}`, `z: ${e51.topology.portZ[t4]}`);
};
var M4 = (e51) => {
  const t4 = { arrows: [], circles: [], infiniteLines: [], lines: [], points: [], polygons: [], rects: [], texts: [], title: "Poly HyperGraph", coordinateSystem: "cartesian" };
  for (let n7 = 0;n7 < e51.topology.regionCount; n7++)
    t4.polygons.push({ points: b4(e51.topology, n7), fill: x4(e51, n7), stroke: "rgba(80, 80, 120, 0.55)", layer: I4(e51, n7), label: v4(e51, n7) });
  for (let n7 = 0;n7 < e51.topology.portCount; n7++)
    t4.circles.push({ center: S4(e51, n7), radius: 0.05, fill: e51.topology.portZ[n7] > 0 ? "rgba(52, 152, 219, 0.55)" : "rgba(80, 80, 80, 0.45)", layer: C4(e51, n7), label: P4(e51, n7) });
  ((e53, t6) => {
    for (let n7 = 0;n7 < e53.problem.routeCount; n7++) {
      const o6 = e53.problem.routeStartPort[n7], i6 = e53.problem.routeEndPort[n7], r6 = _4(e53, n7), s6 = y4(e53, n7);
      t6.points.push({ ...S4(e53, o6), color: s6, layer: C4(e53, o6), label: f4(`route: ${r6}`, "endpoint: start", P4(e53, o6)) }), t6.points.push({ ...S4(e53, i6), color: s6, layer: C4(e53, i6), label: f4(`route: ${r6}`, "endpoint: end", P4(e53, i6)) });
    }
  })(e51, t4), ((e53, t6) => {
    for (let n7 = 0;n7 < e53.state.regionSegments.length; n7++)
      for (const [o6, i6, r6] of e53.state.regionSegments[n7] ?? [])
        t6.lines.push({ points: [S4(e53, i6), S4(e53, r6)], strokeColor: y4(e53, o6), layer: F5([e53.topology.portZ[i6], e53.topology.portZ[r6]]) ?? "z0", label: f4(`route: ${_4(e53, o6)}`, `region: ${h4(e53.topology, n7)}`) });
  })(e51, t4), ((e53, t6) => {
    if (e53.solved)
      return;
    const n7 = e53.state.candidateQueue.toArray().sort((e54, t7) => e54.f - t7.f).slice(0, 10);
    for (let o7 = 0;o7 < n7.length; o7++) {
      const i7 = n7[o7];
      t6.points.push({ ...S4(e53, i7.portId), color: o7 === 0 ? "green" : "rgba(128, 128, 128, 0.4)", layer: C4(e53, i7.portId), label: f4(P4(e53, i7.portId), `g: ${i7.g.toFixed(2)}`, `h: ${i7.h.toFixed(2)}`, `f: ${i7.f.toFixed(2)}`) });
    }
    const o6 = n7[0];
    if (!o6)
      return;
    const i6 = [];
    let r6 = o6;
    for (;r6; )
      i6.unshift(S4(e53, r6.portId)), r6 = r6.prevCandidate;
    if (i6.length <= 1)
      return;
    const s6 = e53.state.currentRouteId;
    t6.lines.push({ points: i6, strokeColor: s6 !== undefined ? y4(e53, s6, 0.95) : "rgba(0, 160, 120, 0.95)", strokeDash: "4 3", layer: C4(e53, o6.portId), label: f4(s6 !== undefined ? `route: ${_4(e53, s6)}` : undefined, "active candidate path", `candidate port: ${d4(e53.topology, o6.portId)}`) });
  })(e51, t4);
  const n6 = e51.state.unroutedRoutes.length + (e51.state.currentRouteId === undefined ? 0 : 1);
  return t4.title = ["Poly HyperGraph", `iter=${e51.iterations}`, `pending=${n6}`, e51.failed ? "failed" : e51.solved ? "solved" : "running"].join(" | "), t4;
};
new Int32Array(0);
var N4 = (e51) => (e51.ccwRotationDegrees ?? 0) * Math.PI / 180;
var R4 = (e51, t4 = 8) => {
  const n6 = e51.width / 2, o6 = e51.height / 2, i6 = N4(e51), r6 = Math.cos(i6), s6 = Math.sin(i6);
  return Array.from({ length: t4 }, (i7, a6) => {
    const c5 = 2 * Math.PI * a6 / t4, l5 = n6 * Math.cos(c5), h5 = o6 * Math.sin(c5);
    return { x: e51.center.x + l5 * r6 - h5 * s6, y: e51.center.y + l5 * s6 + h5 * r6 };
  });
};
var T4 = (e51) => (e51.obstacles ?? []).filter((e53) => e53.type === "oval").map((e53) => ({ points: R4(e53), layers: e53.layers, zLayers: e53.__zLayers, isCopperPour: e53.isCopperPour }));
var E4 = (e51, t4) => (e51.obstacles ?? []).flatMap((n6, o6) => {
  if (!Array.isArray(n6.connectedTo) || n6.connectedTo.length === 0)
    return [];
  const i6 = k2(z2(n6, e51.layerCount), e51.layerCount);
  if (i6.length === 0)
    return [];
  let r6;
  const s6 = n6.type;
  if (s6 === "rect")
    r6 = ((e53, t6 = 0) => {
      const n7 = e53.width / 2 + t6, o7 = e53.height / 2 + t6, i7 = N4(e53), r7 = Math.cos(i7), s7 = Math.sin(i7);
      return [{ localX: -n7, localY: -o7 }, { localX: n7, localY: -o7 }, { localX: n7, localY: o7 }, { localX: -n7, localY: o7 }].map(({ localX: t7, localY: n8 }) => ({ x: e53.center.x + t7 * r7 - n8 * s7, y: e53.center.y + t7 * s7 + n8 * r7 }));
    })(n6, t4);
  else {
    if (s6 !== "oval")
      return [];
    r6 = d5({ polygon: { points: R4(n6), layers: n6.layers, zLayers: n6.__zLayers, isCopperPour: n6.isCopperPour }, clearance: t4, verticesOnly: true });
  }
  return [{ regionId: `connected-obstacle-${o6}`, polygon: r6, availableZ: i6, connectedTo: n6.connectedTo, d: { obstacleIndex: o6, obstacleType: s6, connectedTo: n6.connectedTo } }];
});
var A4 = (e51) => typeof e51 == "object" && e51 !== null ? e51 : {};
var O4 = (e51) => typeof e51 == "object" && e51 !== null ? e51 : {};
var k4 = (e51, t4) => {
  const n6 = A4(e51).serializedRegionId;
  return typeof n6 == "string" ? n6 : `region-${t4}`;
};
var D4 = (e51, t4) => {
  const n6 = O4(e51);
  return typeof n6.serializedPortId == "string" ? n6.serializedPortId : typeof n6.portId == "string" ? n6.portId : `poly-port-${t4}`;
};
var L4 = (e51) => {
  const t4 = O4(e51);
  return { prevPortPointId: typeof t4.prevPortPointId == "string" ? t4.prevPortPointId : undefined, nextPortPointId: typeof t4.nextPortPointId == "string" ? t4.nextPortPointId : undefined };
};
var z4 = (e51) => {
  const t4 = A4(e51).polygon;
  if (Array.isArray(t4) && !(t4.length < 3))
    return t4.every((e53) => typeof e53 == "object" && e53 !== null && typeof e53.x == "number" && typeof e53.y == "number") ? t4 : undefined;
};
var B4 = class extends ni {
  constructor(e51) {
    super(), this.params = e51, this.effort = e51.effort ?? 1, this.clearance = e51.srj.defaultObstacleMargin ?? e51.srj.minTraceWidth;
    const t4 = (t6) => {
      return z5({ bounds: e51.srj.bounds, rects: (n7 = e51.srj, (n7.obstacles ?? []).filter((e53) => e53.type === "rect").map((e53) => ({ center: e53.center, width: e53.width, height: e53.height, ccwRotation: N4(e53), layers: e53.layers, zLayers: e53.__zLayers, isCopperPour: e53.isCopperPour }))), polygons: T4(e51.srj), clearance: this.clearance, concavityTolerance: e51.concavityTolerance ?? 0, layerCount: e51.srj.layerCount, layerMergeMode: e51.layerMergeMode ?? "same", useConstrainedDelaunay: t6, usePolyanyaMerge: e51.usePolyanyaMerge ?? false, viaSegments: e51.viaSegments ?? 8 });
      var n7;
    }, n6 = e51.useConstrainedDelaunay ?? true;
    try {
      this.convexRegions = t4(n6);
    } catch (e53) {
      if (!n6)
        throw e53;
      this.usedUnconstrainedDelaunayFallback = true, this.convexRegions = t4(false);
    }
    var o6;
    this.serializedGraph = a5({ regions: this.convexRegions.regions, availableZ: this.convexRegions.availableZ, layerCount: e51.srj.layerCount, connections: (o6 = e51.srj, o6.connections.flatMap((e53) => {
      const t6 = e53.pointsToConnect ?? [];
      if (t6.length < 2)
        return [];
      const n7 = t6[0];
      return t6.slice(1).map((t7, o7) => {
        const i7 = ((e54, t8, n8, o8) => {
          const i8 = e54.pointsToConnect.length === 2 ? e54.name : `${e54.name}::${o8}`;
          return { ...e54, name: i8, __rootConnectionNames: e54.__rootConnectionNames ?? [e54.name], pointsToConnect: [t8, n8] };
        })(e53, n7, t7, o7);
        return { connectionId: i7.name, mutuallyConnectedNetworkId: i7.__rootConnectionNames?.[0] ?? i7.name, start: n7, end: t7, simpleRouteConnection: i7 };
      });
    })), obstacleRegions: E4(e51.srj, this.clearance), portSpacing: e51.portSpacing ?? j2, portMarginFromSegmentEndpoint: e51.portMarginFromSegmentEndpoint ?? $2 }), this.loaded = ((e53, t6 = {}) => {
      const n7 = t6.boundaryCoordinateScale ?? 36000, o7 = K3(e53), { topology: i7, problem: r6, solution: s6 } = o7, a6 = new Map(e53.regions.map((e54) => [e54.regionId, e54])), c5 = [];
      for (let e54 = 0;e54 < i7.regionCount; e54++) {
        const t7 = h4(i7, e54), n8 = a6.get(t7), o8 = n8 ? a4(n8) : r4({ minX: i7.regionCenterX[e54] - i7.regionWidth[e54] / 2, maxX: i7.regionCenterX[e54] + i7.regionWidth[e54] / 2, minY: i7.regionCenterY[e54] - i7.regionHeight[e54] / 2, maxY: i7.regionCenterY[e54] + i7.regionHeight[e54] / 2 });
        c5.push(o8);
      }
      const l5 = c5.reduce((e54, t7) => e54 + t7.length, 0), h5 = new Int32Array(i7.regionCount), d6 = new Int32Array(i7.regionCount), u6 = new Float64Array(l5), p6 = new Float64Array(l5), m6 = new Float64Array(i7.regionCount), g6 = new Float64Array(i7.regionCount), f6 = new Float64Array(i7.regionCount), _5 = new Float64Array(i7.regionCount), y6 = new Float64Array(i7.regionCount), b6 = new Float64Array(i7.regionCount), x6 = new Float64Array(i7.regionCount), v6 = new Float64Array(i7.regionCount), I6 = new Float64Array(i7.regionCount), S6 = new Float64Array(i7.regionCount), C = new Array(i7.regionCount);
      let P = 0;
      for (let e54 = 0;e54 < i7.regionCount; e54++) {
        const t7 = c5[e54], n8 = c4(t7), o8 = Math.sqrt(Math.max(n8.area, n4));
        h5[e54] = P, d6[e54] = t7.length, m6[e54] = n8.area, g6[e54] = n8.perimeter, f6[e54] = n8.centerX, _5[e54] = n8.centerY, y6[e54] = n8.bounds.minX, b6[e54] = n8.bounds.maxX, x6[e54] = n8.bounds.minY, v6[e54] = n8.bounds.maxY, I6[e54] = o8, S6[e54] = o8, C[e54] = u4(i7.regionMetadata?.[e54], h4(i7, e54), t7, n8.bounds);
        for (const e55 of t7)
          u6[P] = e55.x, p6[P] = e55.y, P += 1;
      }
      const M = new Int32Array(i7.portCount), w = new Int32Array(i7.portCount), N = new Int32Array(i7.portCount), R6 = new Int32Array(i7.portCount), T2 = new Float64Array(i7.portCount), E6 = new Float64Array(i7.portCount);
      for (let e54 = 0;e54 < i7.portCount; e54++) {
        const t7 = { x: i7.portX[e54], y: i7.portY[e54] }, [o8, r7] = i7.incidentPortRegion[e54] ?? [];
        if (o8 !== undefined) {
          const i8 = l4(t7, c5[o8], g6[o8], n7);
          M[e54] = i8.boundaryPosition, N[e54] = i8.edgeIndex, T2[e54] = i8.edgeT;
        }
        if (r7 !== undefined) {
          const o9 = l4(t7, c5[r7], g6[r7], n7);
          w[e54] = o9.boundaryPosition, R6[e54] = o9.edgeIndex, E6[e54] = o9.edgeT;
        }
      }
      for (let e54 = 0;e54 < i7.regionCount; e54++)
        C[e54].layer = F5(j5(i7.regionAvailableZMask?.[e54] ?? 0)) ?? F5((i7.regionIncidentPorts[e54] ?? []).map((e55) => i7.portZ[e55])) ?? "z0";
      const A6 = { ...i7, regionWidth: I6, regionHeight: S6, regionCenterX: f6, regionCenterY: _5, regionMetadata: C, portAngleForRegion1: M, portAngleForRegion2: w, regionVertexStart: h5, regionVertexCount: d6, regionVertexX: u6, regionVertexY: p6, regionArea: m6, regionPerimeter: g6, regionBoundsMinX: y6, regionBoundsMaxX: b6, regionBoundsMinY: x6, regionBoundsMaxY: v6, portBoundaryPositionForRegion1: M, portBoundaryPositionForRegion2: w, portEdgeIndexForRegion1: N, portEdgeIndexForRegion2: R6, portEdgeTForRegion1: T2, portEdgeTForRegion2: E6 };
      return { topology: A6, problem: r6, solution: s6, mapping: p4(A6, r6) };
    })(this.serializedGraph), this.reservedRegionCount = ((e53, t6) => {
      const n7 = e53.problem.regionNetId;
      if (!n7)
        return 0;
      const o7 = new Map;
      for (const e54 of t6.regions) {
        const t7 = typeof e54.d?.netId == "number" ? e54.d.netId : typeof e54.d?.NetId == "number" ? e54.d.NetId : undefined;
        Number.isInteger(t7) && t7 >= 0 && o7.set(e54.regionId, t7);
      }
      let i7 = 0;
      for (let t7 = 0;t7 < e53.topology.regionCount; t7++) {
        const r6 = e53.topology.regionMetadata?.[t7], s6 = typeof r6 == "object" && r6 !== null ? r6.serializedRegionId : undefined;
        if (typeof s6 != "string")
          continue;
        const a6 = o7.get(s6);
        a6 !== undefined && (n7[t7] = a6, i7 += 1);
      }
      return i7;
    })(this.loaded, this.serializedGraph);
    const i6 = { DISTANCE_TO_COST: 0.05, RIP_THRESHOLD_START: 0.05, RIP_THRESHOLD_END: 0.8, RIP_CONGESTION_REGION_COST_FACTOR: 0.1, RIP_THRESHOLD_RAMP_ATTEMPTS: Math.max(1, Math.ceil(10 * this.effort)), MAX_ITERATIONS: Math.max(1e5, Math.ceil(1e7 * this.effort)) };
    this.polySolver = new g4(this.loaded.topology, this.loaded.problem, i6), this.activeSubSolver = this.polySolver, this.MAX_ITERATIONS = i6.MAX_ITERATIONS + 1000, this.inputNodeWithPortPoints = this.createInputNodesWithPortPoints();
  }
  getSolverName() {
    return "PolyHypergraphPortPointPathingSolver";
  }
  convexRegions;
  serializedGraph;
  loaded;
  polySolver;
  inputNodeWithPortPoints = [];
  nodesWithPortPoints = [];
  reservedRegionCount = 0;
  clearance;
  effort;
  usedUnconstrainedDelaunayFallback = false;
  createInputNodesWithPortPoints() {
    const { topology: e51 } = this.loaded, t4 = [];
    for (let n6 = 0;n6 < e51.regionCount; n6++) {
      const o6 = A4(e51.regionMetadata?.[n6] ?? {}), i6 = k4(o6, n6);
      if (i6.startsWith("terminal-"))
        continue;
      const r6 = (e51.regionIncidentPorts[n6] ?? []).map((t6) => {
        const n7 = e51.incidentPortRegion[t6] ?? [], o7 = e51.portMetadata?.[t6];
        return { portPointId: D4(o7, t6), x: e51.portX[t6], y: e51.portY[t6], z: e51.portZ[t6], ...L4(o7), connectionNodeIds: n7.map((t7) => k4(e51.regionMetadata?.[t7], t7)), distToCentermostPortOnZ: e51.portMetadata?.[t6]?.distToCentermostPortOnZ ?? 0, connectsToOffBoardNode: false };
      });
      t4.push({ capacityMeshNodeId: i6, center: { x: e51.regionCenterX[n6], y: e51.regionCenterY[n6] }, width: e51.regionWidth[n6], height: e51.regionHeight[n6], portPoints: r6, availableZ: o6.availableZ ?? Array.from({ length: this.params.srj.layerCount }, (e53, t6) => t6), _containsObstacle: Boolean(o6._containsObstacle), _containsTarget: Boolean(o6._containsTarget) });
    }
    return t4;
  }
  createAssignedPortPoint(e51, t4) {
    const n6 = this.polySolver.problem.routeMetadata?.[e51], o6 = n6 ? ((e53) => e53.simpleRouteConnection?.name ?? e53.connectionId)(n6) : `route-${e51}`, i6 = n6 ? ((e53) => e53.simpleRouteConnection?.rootConnectionName ?? e53.mutuallyConnectedNetworkId)(n6) : undefined, r6 = this.polySolver.topology.portMetadata?.[t4];
    return { portPointId: D4(r6, t4), x: this.polySolver.topology.portX[t4], y: this.polySolver.topology.portY[t4], z: this.polySolver.topology.portZ[t4], connectionName: o6, rootConnectionName: i6, ...L4(r6) };
  }
  buildOutputNodes() {
    const { topology: e51, state: t4 } = this.polySolver, n6 = [];
    for (let o6 = 0;o6 < t4.regionSegments.length; o6++) {
      const i6 = A4(e51.regionMetadata?.[o6] ?? {}), r6 = k4(i6, o6);
      if (r6.startsWith("terminal-"))
        continue;
      const s6 = z4(i6);
      if (!s6)
        continue;
      const a6 = (t4.regionSegments[o6] ?? []).flatMap(([e53, t6, n7]) => {
        const o7 = this.createAssignedPortPoint(e53, t6), i7 = this.createAssignedPortPoint(e53, n7);
        return o7.portPointId && i7.portPointId && (o7.nextPortPointId = i7.portPointId, i7.prevPortPointId = o7.portPointId), [o7, i7];
      });
      a6.length !== 0 && n6.push({ capacityMeshNodeId: r6, center: { x: e51.regionCenterX[o6], y: e51.regionCenterY[o6] }, width: e51.regionWidth[o6], height: e51.regionHeight[o6], polygon: s6, portPoints: a6, availableZ: i6.availableZ });
    }
    this.nodesWithPortPoints = n6;
  }
  _step() {
    this.polySolver.step(), this.progress = this.polySolver.progress, this.stats = { ...this.polySolver.stats ?? {}, reservedRegionCount: this.reservedRegionCount, usedUnconstrainedDelaunayFallback: this.usedUnconstrainedDelaunayFallback, regionCount: this.loaded.topology.regionCount, portCount: this.loaded.topology.portCount, routeCount: this.loaded.problem.routeCount }, this.polySolver.solved ? (this.buildOutputNodes(), this.solved = true, this.activeSubSolver = null) : this.polySolver.failed && (this.error = this.polySolver.error, this.failed = true, this.activeSubSolver = null);
  }
  getOutput() {
    return { nodesWithPortPoints: this.nodesWithPortPoints, inputNodeWithPortPoints: this.inputNodeWithPortPoints };
  }
  computeNodePf(e51) {
    const t4 = this.nodesWithPortPoints.find((t6) => t6.capacityMeshNodeId === e51.capacityMeshNodeId);
    if (!t4)
      return null;
    const n6 = Cz(t4);
    return jz({ capacityMeshNodeId: t4.capacityMeshNodeId, center: t4.center, width: t4.width, height: t4.height, layer: "top", availableZ: t4.availableZ ?? [] }, n6.numSameLayerCrossings, n6.numEntryExitLayerChanges, n6.numTransitionPairCrossings);
  }
  getConstructorParams() {
    return [this.params];
  }
  preview() {
    return this.visualize();
  }
  visualize() {
    return this.polySolver.visualize();
  }
};
var F4 = class extends ni {
  constructor(e51) {
    super(), this.inputSrj = e51, this.MAX_ITERATIONS = 1;
  }
  outputSrj;
  _step() {
    this.error = G1(this.inputSrj), this.error ? this.failed = true : (this.outputSrj = X1(this.inputSrj) ?? this.inputSrj, this.solved = true);
  }
  getOutputSimpleRouteJson() {
    if (!this.outputSrj)
      throw new Error("PreprocessSimpleRouteJsonSolver has not solved yet");
    return this.outputSrj;
  }
  getConstructorParams() {
    return [this.inputSrj];
  }
  visualize() {
    return this.outputSrj ? pi(Wo({ ...this.outputSrj, traces: [] }), nK({ srj: this.outputSrj })) : { lines: [], points: [], rects: [], circles: [] };
  }
};
var j4 = (e51, t4) => (e51.x - t4.x) ** 2 + (e51.y - t4.y) ** 2;
var $4 = (e51, t4, n6) => {
  if (!n6)
    return;
  const o6 = e51.filter(({ projected: e53 }) => e53.connectionName === t4 && (n6.z === undefined || e53.z === n6.z));
  return o6.length !== 0 ? o6.reduce((e53, t6) => j4(t6.projected, n6) < j4(e53.projected, n6) ? t6 : e53).original : undefined;
};
var Y4 = (e51, t4) => {
  const n6 = t4.projectedRect;
  if (!n6)
    throw new Error("Poly node is missing projectedRect");
  const o6 = n6.rectToPolygonMatrix, i6 = ((e53) => {
    if (!e53.projectedRect)
      throw new Error("Poly node is missing projectedRect");
    return e53.portPoints.map((t6) => {
      const n7 = P2(t6, e53.projectedRect);
      return { original: t6, projected: { ...t6, x: n7.x, y: n7.y } };
    });
  })(t4), r6 = e51.route.map((e53) => ({ ...e53, ...I2(o6, e53) })), s6 = e51.vias.map((e53) => I2(o6, e53)), a6 = $4(i6, e51.connectionName, e51.route[0]), c5 = $4(i6, e51.connectionName, e51.route[e51.route.length - 1]);
  return a6 && r6[0] && (r6[0] = { ...r6[0], x: a6.x, y: a6.y, z: a6.z }), c5 && r6[r6.length - 1] && (r6[r6.length - 1] = { ...r6[r6.length - 1], x: c5.x, y: c5.y, z: c5.z }), { ...e51, route: r6, vias: s6, jumpers: e51.jumpers?.map((e53) => ({ ...e53, start: I2(o6, e53.start), end: I2(o6, e53.end) })) };
};
var X4 = class extends ni {
  getSolverName() {
    return "ProjectHighDensityToPolygonSolver";
  }
  routes = [];
  routesByNodeId = new Map;
  colorMap;
  nodePortPoints;
  rawRoutesByNodeId;
  constructor({ nodePortPoints: e51, routesByNodeId: t4, colorMap: n6 }) {
    super(), this.MAX_ITERATIONS = 1, this.nodePortPoints = e51, this.rawRoutesByNodeId = t4 instanceof Map ? new Map(t4) : new Map(Object.entries(t4)), this.colorMap = n6 ?? {};
  }
  _step() {
    this.routes = [], this.routesByNodeId = new Map;
    for (const e51 of this.nodePortPoints) {
      const t4 = (this.rawRoutesByNodeId.get(e51.capacityMeshNodeId) ?? []).map((t6) => Y4(t6, e51));
      t4.length > 0 && (this.routesByNodeId.set(e51.capacityMeshNodeId, t4), this.routes.push(...t4));
    }
    this.solved = true;
  }
  getOutput() {
    return this.routes;
  }
  getConstructorParams() {
    return [{ nodePortPoints: this.nodePortPoints, routesByNodeId: this.rawRoutesByNodeId, colorMap: this.colorMap }];
  }
  visualize() {
    const e51 = { polygons: this.nodePortPoints.flatMap((e53) => [{ points: e53.polygon, fill: "rgba(40, 140, 220, 0.06)", stroke: "rgba(20, 70, 160, 0.65)", label: `${e53.capacityMeshNodeId} polygon` }, ...e53.projectedRect ? [{ points: e53.projectedRect.targetQuad, fill: "rgba(255, 165, 0, 0.05)", stroke: "rgba(255, 120, 0, 0.45)", label: `${e53.capacityMeshNodeId} projection target` }] : []]), lines: [], circles: [] };
    for (const t4 of this.routes) {
      const n6 = this.colorMap[t4.connectionName] ?? "#0000ff", o6 = mi(t4.route, t4.connectionName, n6);
      for (const n7 of o6)
        e51.lines.push({ points: n7.points, label: n7.connectionName, strokeColor: n7.z === 0 ? n7.color : Ao(n7.color, 0.5), layer: `z${n7.z}`, strokeWidth: t4.traceThickness, strokeDash: n7.z !== 0 ? [0.1, 0.3] : undefined });
      for (const o7 of t4.vias)
        e51.circles.push({ center: o7, layer: "z0,1", radius: t4.viaDiameter / 2, fill: n6, label: `${t4.connectionName} via` });
    }
    return e51;
  }
};
function H4(e51, t4, n6, o6 = {}) {
  return { solverName: e51, solverClass: t4, getConstructorParams: n6, onSolved: o6.onSolved };
}
var V4 = class extends ni {
  constructor(e51, t4 = {}) {
    super(), this.srj = e51, this.opts = t4, this.originalSrj = e51, this.opts = { ...t4 };
    const n6 = this.opts;
    if (this.effort = n6.effort ?? 1, this.MAX_ITERATIONS = 1e8 * this.effort, this.maxNodeDimension = n6.maxNodeDimension ?? 16, this.maxNodeRatio = n6.maxNodeRatio ?? 6, this.minNodeArea = n6.minNodeArea ?? 0.1 ** 2, this.setSimpleRouteJson(e51), this.equivalentAreaExpansionFactor = n6.equivalentAreaExpansionFactor ?? 2, this.minProjectedRectDimension = n6.minProjectedRectDimension ?? 3 * this.minTraceWidth, n6.capacityDepth === undefined) {
      const e53 = this.srj.bounds.maxX - this.srj.bounds.minX, t6 = this.srj.bounds.maxY - this.srj.bounds.minY, o6 = Math.max(e53, t6), i6 = n6.targetMinCapacity ?? 0.5;
      n6.capacityDepth = Fz(o6, i6);
    }
    this.cacheProvider = n6.cacheProvider === undefined ? no() : n6.cacheProvider === null ? null : n6.cacheProvider, this.startTimeOfPhase = {}, this.endTimeOfPhase = {}, this.timeSpentOnPhase = {};
  }
  preprocessSimpleRouteJsonSolver;
  escapeViaLocationSolver;
  netToPointPairsSolver;
  polyGraphSolver;
  attachProjectedRectsSolver;
  highDensityRouteSolver;
  projectHighDensityToPolgonSolver;
  highDensityStitchSolver;
  traceSimplificationSolver;
  traceWidthSolver;
  globalDrcForceImproveSolver;
  colorMap;
  viaDiameter;
  viaHoleDiameter;
  minTraceWidth;
  effort;
  maxNodeDimension;
  maxNodeRatio;
  minNodeArea;
  equivalentAreaExpansionFactor;
  minProjectedRectDimension;
  startTimeOfPhase;
  endTimeOfPhase;
  timeSpentOnPhase;
  activeSubSolver = null;
  connMap;
  srjWithEscapeViaLocations;
  srjWithPointPairs;
  originalSrj;
  highDensityNodePortPoints;
  projectedHighDensityNodePortPoints;
  cacheProvider = null;
  pipelineDef = [H4("preprocessSimpleRouteJsonSolver", F4, (e51) => [e51.originalSrj], { onSolved: (e51) => {
    e51.setSimpleRouteJson(e51.preprocessSimpleRouteJsonSolver.getOutputSimpleRouteJson());
  } }), H4("escapeViaLocationSolver", uK, (e51) => [e51.srj, { viaDiameter: e51.viaDiameter, minTraceWidth: e51.minTraceWidth, obstacleMargin: e51.srj.defaultObstacleMargin ?? 0.15 }], { onSolved: (e51) => {
    e51.srjWithEscapeViaLocations = e51.escapeViaLocationSolver?.getOutputSimpleRouteJson();
  } }), H4("netToPointPairsSolver", pB, (e51) => {
    const t4 = e51.srjWithEscapeViaLocations ?? e51.srj;
    return [t4, e51.colorMap, ti(t4)];
  }, { onSolved: (e51) => {
    e51.srjWithPointPairs = e51.netToPointPairsSolver?.getNewSimpleRouteJson(), e51.colorMap = Eo(e51.srjWithPointPairs, e51.connMap), e51.connMap = ei(e51.srjWithPointPairs);
  } }), H4("polyGraphSolver", B4, (e51) => [{ srj: e51.srjWithPointPairs, effort: Math.min(1, e51.effort), concavityTolerance: e51.opts.polyConcavityTolerance, portSpacing: e51.opts.polyPortSpacing, portMarginFromSegmentEndpoint: e51.opts.polyPortMarginFromSegmentEndpoint }], { onSolved: (e51) => {
    e51.highDensityNodePortPoints = e51.polyGraphSolver?.getOutput().nodesWithPortPoints ?? [];
  } }), H4("attachProjectedRectsSolver", w2, (e51) => [{ nodesWithPortPoints: e51.highDensityNodePortPoints ?? [], equivalentAreaExpansionFactor: e51.equivalentAreaExpansionFactor, minProjectedRectDimension: e51.minProjectedRectDimension, traceWidth: e51.minTraceWidth, viaDiameter: e51.viaDiameter, obstacleMargin: e51.srj.defaultObstacleMargin ?? 0.15 }], { onSolved: (e51) => {
    e51.projectedHighDensityNodePortPoints = e51.attachProjectedRectsSolver?.getOutput() ?? [];
  } }), H4("highDensityRouteSolver", R2, (e51) => [{ nodePortPoints: e51.projectedHighDensityNodePortPoints ?? [], nodePfById: new Map((e51.polyGraphSolver?.getOutput().inputNodeWithPortPoints ?? []).map((t4) => [t4.capacityMeshNodeId, e51.polyGraphSolver?.computeNodePf(t4) ?? null])), colorMap: e51.colorMap, connMap: e51.connMap, viaDiameter: e51.viaDiameter, traceWidth: e51.minTraceWidth, obstacleMargin: e51.srj.defaultObstacleMargin ?? 0.15, effort: Math.min(1, e51.effort) }]), H4("projectHighDensityToPolgonSolver", X4, (e51) => [{ nodePortPoints: e51.projectedHighDensityNodePortPoints ?? [], routesByNodeId: e51.highDensityRouteSolver.routesByNodeId, colorMap: e51.colorMap }]), H4("highDensityStitchSolver", L1, (e51) => [{ connections: e51.srjWithPointPairs.connections, hdRoutes: e51.projectHighDensityToPolgonSolver.routes, colorMap: e51.colorMap, layerCount: e51.srj.layerCount, defaultViaDiameter: e51.viaDiameter }]), H4("traceSimplificationSolver", WF, (e51) => [{ hdRoutes: e51.highDensityStitchSolver.mergedHdRoutes, obstacles: e51.srj.obstacles, connMap: e51.connMap, colorMap: e51.colorMap, outline: e51.srj.outline, defaultViaDiameter: e51.viaDiameter, layerCount: e51.srj.layerCount, iterations: 2 }]), H4("traceWidthSolver", QF, (e51) => [{ hdRoutes: e51.traceSimplificationSolver.simplifiedHdRoutes, obstacles: e51.srj.obstacles, connMap: e51.connMap, colorMap: e51.colorMap, minTraceWidth: e51.minTraceWidth, connection: e51.srj.connections, layerCount: e51.srj.layerCount }]), H4("globalDrcForceImproveSolver", kN, (e51) => [{ srj: e51.srjWithPointPairs, hdRoutes: e51.traceWidthSolver.getHdRoutesWithWidths(), effort: Math.min(1, e51.effort) }])];
  setSimpleRouteJson(e51) {
    this.srj = e51;
    const t4 = Yo(this.srj);
    this.viaDiameter = t4.padDiameter, this.viaHoleDiameter = t4.holeDiameter, this.minTraceWidth = this.srj.minTraceWidth, this.connMap = ei(this.srj), this.colorMap = Eo(this.srj, this.connMap);
  }
  getConstructorParams() {
    return [this.srj, this.opts];
  }
  currentPipelineStepIndex = 0;
  _step() {
    const e51 = this.pipelineDef[this.currentPipelineStepIndex];
    if (!e51)
      return void (this.solved = true);
    if (this.activeSubSolver)
      return this.activeSubSolver.step(), void (this.activeSubSolver.solved ? (this.endTimeOfPhase[e51.solverName] = performance.now(), this.timeSpentOnPhase[e51.solverName] = this.endTimeOfPhase[e51.solverName] - this.startTimeOfPhase[e51.solverName], e51.onSolved?.(this), this.activeSubSolver = null, this.currentPipelineStepIndex++) : this.activeSubSolver.failed && (this.error = this.activeSubSolver?.error, this.failed = true, this.activeSubSolver = null));
    const t4 = e51.getConstructorParams(this);
    this.activeSubSolver = new e51.solverClass(...t4), this[e51.solverName] = this.activeSubSolver, this.timeSpentOnPhase[e51.solverName] = 0, this.startTimeOfPhase[e51.solverName] = performance.now();
  }
  solveUntilPhase(e51) {
    for (;this.getCurrentPhase() !== e51; )
      this.step();
  }
  getCurrentPhase() {
    return this.pipelineDef[this.currentPipelineStepIndex]?.solverName ?? "none";
  }
  getProblemVisualization({ includeRoutes: e51 = true } = {}) {
    const t4 = this.originalSrj, n6 = [{ points: [{ x: t4.bounds?.minX ?? -50, y: t4.bounds?.minY ?? -50 }, { x: t4.bounds?.maxX ?? 50, y: t4.bounds?.minY ?? -50 }, { x: t4.bounds?.maxX ?? 50, y: t4.bounds?.maxY ?? 50 }, { x: t4.bounds?.minX ?? -50, y: t4.bounds?.maxY ?? 50 }, { x: t4.bounds?.minX ?? -50, y: t4.bounds?.minY ?? -50 }], strokeColor: "rgba(255,0,0,0.25)" }];
    if (t4.outline && t4.outline.length >= 2) {
      const e53 = t4.outline.map((e54) => ({ x: e54.x, y: e54.y }));
      e53.push({ ...e53[0] }), n6.push({ points: e53, strokeColor: "rgba(0, 136, 255, 0.95)" });
    }
    const o6 = Lo(t4), i6 = { points: [...t4.connections.flatMap((e53) => e53.pointsToConnect.map((n7) => ({ ...n7, layer: Bo(n7, t4.layerCount), label: `${e53.name} ${n7.pcb_port_id ?? ""}` })))], rects: [...(t4.obstacles ?? []).filter((e53) => !e53.isCopperPour).map((e53) => ({ ...e53, fill: e53.layers?.includes("top") ? "rgba(255,0,0,0.25)" : e53.layers?.includes("bottom") ? "rgba(0,0,255,0.25)" : "rgba(255,0,0,0.25)", layer: jo(e53, t4.layerCount), label: o6(e53) }))], lines: n6 };
    if (!e51)
      return i6;
    const r6 = nK({ srj: t4 });
    return pi(i6, r6);
  }
  visualize() {
    if (!this.solved && this.activeSubSolver)
      return this.activeSubSolver.visualize();
    const e51 = this.getProblemVisualization(), t4 = this.getProblemVisualization({ includeRoutes: false }), n6 = this.polyGraphSolver?.visualize(), o6 = this.attachProjectedRectsSolver?.visualize(), i6 = this.highDensityRouteSolver?.visualize(), r6 = this.projectHighDensityToPolgonSolver?.visualize(), s6 = this.highDensityStitchSolver?.visualize(), a6 = this.traceSimplificationSolver?.visualize();
    return pi(...[e51, this.escapeViaLocationSolver?.visualize(), this.netToPointPairsSolver?.visualize(), n6, o6, i6 ? pi(t4, i6) : null, r6 ? pi(t4, r6) : null, s6, a6, this.solved ? pi({ lines: t4.lines }, nK({ srj: this.originalSrj }), Wo(this.getOutputSimpleRouteJson())) : null].filter(Boolean));
  }
  preview() {
    if (this.projectHighDensityToPolgonSolver) {
      const e51 = [];
      for (let t4 = this.projectHighDensityToPolgonSolver.routes.length - 1;t4 >= 0; t4--) {
        const n6 = this.projectHighDensityToPolgonSolver.routes[t4];
        if (e51.push({ points: n6.route.map((e53) => ({ x: e53.x, y: e53.y })), strokeColor: this.colorMap[n6.connectionName] }), e51.length > 200)
          break;
      }
      return { lines: e51 };
    }
    if (this.highDensityRouteSolver) {
      const e51 = [];
      for (let t4 = this.highDensityRouteSolver.routes.length - 1;t4 >= 0; t4--) {
        const n6 = this.highDensityRouteSolver.routes[t4];
        if (e51.push({ points: n6.route.map((e53) => ({ x: e53.x, y: e53.y })), strokeColor: this.colorMap[n6.connectionName] }), e51.length > 200)
          break;
      }
      return { lines: e51 };
    }
    return this.polyGraphSolver ? this.polyGraphSolver.preview() : this.netToPointPairsSolver ? this.netToPointPairsSolver.visualize() : this.escapeViaLocationSolver ? this.escapeViaLocationSolver.visualize() : this.preprocessSimpleRouteJsonSolver ? this.preprocessSimpleRouteJsonSolver.visualize() : {};
  }
  _getOutputHdRoutes() {
    return this.globalDrcForceImproveSolver?.getOutput() ?? this.traceWidthSolver?.getHdRoutesWithWidths() ?? this.traceSimplificationSolver?.simplifiedHdRoutes ?? this.highDensityStitchSolver.mergedHdRoutes;
  }
  getOutputSimplifiedPcbTraces() {
    if (!this.solved || !this.highDensityRouteSolver)
      throw new Error("Cannot get output before solving is complete");
    const e51 = [], t4 = this._getOutputHdRoutes();
    for (const n6 of this.netToPointPairsSolver?.newConnections ?? []) {
      const o6 = n6.__netConnectionName ?? this.originalSrj.connections.find((e53) => e53.name === n6.name)?.__netConnectionName, i6 = t4.filter((e53) => e53.connectionName === n6.name);
      for (let t6 = 0;t6 < i6.length; t6++) {
        const r6 = i6[t6], s6 = { type: "pcb_trace", pcb_trace_id: `${n6.name}_${t6}`, connection_name: o6 ?? n6.__rootConnectionNames?.[0] ?? n6.name, route: Ro(r6, this.srj.layerCount, { connectionPoints: n6.pointsToConnect, defaultViaHoleDiameter: this.viaHoleDiameter }) };
        e51.push(s6);
      }
    }
    return e51;
  }
  getOutputSimpleRouteJson() {
    return { ...this.originalSrj, traces: this.getOutputSimplifiedPcbTraces() };
  }
};
var G4 = (e51, t4) => {
  if (e51 === "top")
    return 0;
  if (e51 === "bottom")
    return t4 - 1;
  const n6 = /^inner(\d+)$/.exec(e51);
  if (!n6)
    return -1;
  const o6 = Number(n6[1]);
  return o6 > 0 && o6 < t4 - 1 ? o6 : -1;
};
var U4 = (e51, t4) => e51 === 0 ? "top" : e51 === t4 - 1 ? "bottom" : `inner${e51}`;
var Z4 = (e51, t4, n6) => {
  const o6 = G4(e51, n6), i6 = G4(t4, n6);
  if (o6 < 0 || i6 < 0)
    return [];
  const r6 = Math.min(o6, i6), s6 = Math.max(o6, i6);
  return Array.from({ length: s6 - r6 + 1 }, (e53, t6) => U4(r6 + t6, n6));
};
var q4 = (e51, t4) => {
  const n6 = [], o6 = [], i6 = e51.route.find((e53) => e53.route_type === "wire"), r6 = i6?.route_type === "wire" ? i6.width : null, s6 = { "0603": 0.95, 1206: 1.8, "1206x4_pair": 1.8 };
  let a6 = null;
  for (let i7 = 0;i7 < e51.route.length; i7++) {
    const c5 = e51.route[i7];
    if (c5.route_type === "wire") {
      if (!Number.isFinite(c5.x) || !Number.isFinite(c5.y) || !Number.isFinite(c5.width) || c5.width <= 0 || G4(c5.layer, t4) < 0)
        throw new Error(`PostProcessingSolver: immutable trace "${e51.connection_name}" has an invalid wire`);
      if (a6 && a6.layer !== c5.layer)
        throw new Error(`PostProcessingSolver: immutable trace "${e51.connection_name}" changes layer without a transition`);
      a6 && n6.push({ start: a6, end: c5, layer: c5.layer, width: Math.max(a6.width, c5.width), connectionName: e51.connection_name, terminal: null }), a6 = c5;
      continue;
    }
    if (c5.route_type === "via") {
      const s7 = Z4(c5.from_layer, c5.to_layer, t4), l6 = a6, h6 = c5.via_diameter ?? l6?.width ?? r6;
      if (!Number.isFinite(c5.x) || !Number.isFinite(c5.y) || s7.length < 2 || h6 === null || !Number.isFinite(h6) || h6 <= 0 || c5.via_hole_diameter !== undefined && (!Number.isFinite(c5.via_hole_diameter) || c5.via_hole_diameter <= 0 || h6 !== null && c5.via_hole_diameter >= h6))
        throw new Error(`PostProcessingSolver: immutable trace "${e51.connection_name}" has an invalid via`);
      l6 && Math.hypot(l6.x - c5.x, l6.y - c5.y) > 0.00000001 && n6.push({ start: l6, end: c5, layer: l6.layer, width: l6.width, connectionName: e51.connection_name, terminal: null }), o6.push({ x: c5.x, y: c5.y, layers: s7, diameter: h6, connectionName: e51.connection_name, terminal: i7 === 0 ? "start" : i7 === e51.route.length - 1 ? "end" : null });
      const d7 = e51.route.slice(i7 + 1).find((e53) => e53.route_type === "wire"), u6 = l6?.layer === c5.from_layer ? c5.to_layer : l6?.layer === c5.to_layer ? c5.from_layer : d7?.route_type !== "wire" || d7.layer !== c5.from_layer && d7.layer !== c5.to_layer ? null : d7.layer;
      if (!u6)
        throw new Error(`PostProcessingSolver: immutable trace "${e51.connection_name}" has a discontinuous via`);
      a6 = { x: c5.x, y: c5.y, layer: u6, width: l6?.width ?? r6 ?? h6 };
      continue;
    }
    if (c5.route_type === "jumper") {
      const o7 = s6[c5.footprint];
      if (!Number.isFinite(c5.start.x) || !Number.isFinite(c5.start.y) || !Number.isFinite(c5.end.x) || !Number.isFinite(c5.end.y) || G4(c5.layer, t4) < 0)
        throw new Error(`PostProcessingSolver: immutable trace "${e51.connection_name}" has an invalid jumper`);
      if (a6 && (a6.layer !== c5.layer || Math.hypot(a6.x - c5.start.x, a6.y - c5.start.y) > 0.00000001))
        throw new Error(`PostProcessingSolver: immutable trace "${e51.connection_name}" has a discontinuous jumper`);
      n6.push({ start: c5.start, end: c5.end, layer: c5.layer, width: o7, connectionName: e51.connection_name, terminal: null }), a6 = { ...c5.end, layer: c5.layer, width: o7 };
      continue;
    }
    const l5 = Z4(c5.from_layer, c5.to_layer, t4);
    if (!Number.isFinite(c5.start.x) || !Number.isFinite(c5.start.y) || !Number.isFinite(c5.end.x) || !Number.isFinite(c5.end.y) || !Number.isFinite(c5.width) || c5.width <= 0 || l5.length < 2)
      throw new Error(`PostProcessingSolver: immutable trace "${e51.connection_name}" has invalid through-obstacle copper`);
    if (a6 && (a6.layer !== c5.from_layer && a6.layer !== c5.to_layer || Math.hypot(a6.x - c5.start.x, a6.y - c5.start.y) > 0.00000001))
      throw new Error(`PostProcessingSolver: immutable trace "${e51.connection_name}" has discontinuous through-obstacle copper`);
    for (const t6 of l5)
      n6.push({ start: c5.start, end: c5.end, layer: t6, width: c5.width, connectionName: e51.connection_name, terminal: null });
    const h5 = a6, d6 = h5?.layer === c5.to_layer ? c5.from_layer : c5.to_layer;
    a6 = { ...c5.end, layer: d6, width: c5.width };
  }
  return { segments: n6, vias: o6 };
};
var J4 = (e51) => e51.rootConnectionName ?? e51.connectionName;
var Q4 = (e51, t4) => e51.flatMap((e53, n6) => J4(e53) === t4 ? [n6] : []);
var K4 = (e51, t4, n6, o6) => {
  const i6 = (e53, t6, n7) => {
    const o7 = n7.x - t6.x, i7 = n7.y - t6.y, r7 = e53.x - t6.x, s7 = e53.y - t6.y, a7 = o7 ** 2 + i7 ** 2, c6 = a7 === 0 ? 0 : Math.max(0, Math.min(1, (r7 * o7 + s7 * i7) / a7));
    return Math.hypot(e53.x - (t6.x + c6 * o7), e53.y - (t6.y + c6 * i7));
  }, r6 = { x: t4.x - e51.x, y: t4.y - e51.y }, s6 = { x: o6.x - n6.x, y: o6.y - n6.y }, a6 = { x: n6.x - e51.x, y: n6.y - e51.y }, c5 = (e53, t6) => e53.x * t6.y - e53.y * t6.x, l5 = c5(r6, s6), h5 = Math.hypot(r6.x, r6.y), d6 = 0.000000000001 * (h5 * Math.hypot(s6.x, s6.y) + 1);
  if (Math.abs(l5) > d6) {
    const e53 = c5(a6, s6) / l5, t6 = c5(a6, r6) / l5;
    if (e53 >= -0.000000000001 && e53 <= 1 + 0.000000000001 && t6 >= -0.000000000001 && t6 <= 1 + 0.000000000001)
      return 0;
  } else if (h5 > 0.000000000001 && Math.abs(c5(a6, r6)) <= d6) {
    const i7 = Math.abs(r6.x) >= Math.abs(r6.y), s7 = Math.min(i7 ? e51.x : e51.y, i7 ? t4.x : t4.y), a7 = Math.max(i7 ? e51.x : e51.y, i7 ? t4.x : t4.y), c6 = Math.min(i7 ? n6.x : n6.y, i7 ? o6.x : o6.y), l6 = Math.max(i7 ? n6.x : n6.y, i7 ? o6.x : o6.y);
    if (Math.max(s7, c6) <= Math.min(a7, l6) + 0.000000000001)
      return 0;
  }
  return Math.min(i6(e51, n6, o6), i6(t4, n6, o6), i6(n6, e51, t4), i6(o6, e51, t4));
};
var e62 = (e51, t4) => Math.hypot(t4.x - e51.x, t4.y - e51.y);
var t6 = (e51) => {
  let t4 = 0;
  for (let n6 = 0;n6 < e51.route.length - 1; n6++)
    t4 += e62(e51.route[n6], e51.route[n6 + 1]);
  return t4;
};
var n6 = (e51, t4) => t4.reduce((t7, n7) => t7 + t6(e51[n7]), 0);
var o6 = (e51, t4) => {
  const { __zLayers: n7, zLayers: o7 } = e51, i6 = n7 !== undefined ? n7 : o7;
  if (i6 !== undefined) {
    if (!Array.isArray(i6) || i6.length === 0 || i6.some((e53) => !Number.isInteger(e53) || e53 < 0 || e53 >= t4))
      throw new Error("Obstacle has invalid z-layer indexes");
    return i6;
  }
  if (e51.layers.length === 0)
    throw new Error("Obstacle has no declared layers");
  return e51.layers.map((e53) => {
    if (e53 === "top")
      return 0;
    if (e53 === "bottom")
      return t4 - 1;
    const n8 = /^inner(\d+)$/.exec(e53), o8 = n8 ? Number(n8[1]) : -1;
    if (o8 <= 0 || o8 >= t4 - 1)
      throw new Error(`Obstacle has invalid layer name "${e53}"`);
    return o8;
  });
};
var i6 = (e51) => {
  const t4 = (e53, t7, n8, o8) => {
    const i8 = n8.center.x - n8.width / 2 - o8, r7 = n8.center.x + n8.width / 2 + o8, s7 = n8.center.y - n8.height / 2 - o8, a6 = n8.center.y + n8.height / 2 + o8;
    if (e53.x >= i8 && e53.x <= r7 && e53.y >= s7 && e53.y <= a6 || t7.x >= i8 && t7.x <= r7 && t7.y >= s7 && t7.y <= a6)
      return true;
    const c5 = [{ x: i8, y: s7 }, { x: r7, y: s7 }, { x: r7, y: a6 }, { x: i8, y: a6 }];
    return c5.some((n9, o9) => K4(e53, t7, n9, c5[(o9 + 1) % c5.length]) === 0);
  };
  if (e51.bounds && e51.meanderPoints.some((t7) => t7.x < e51.bounds.minX || t7.x > e51.bounds.maxX || t7.y < e51.bounds.minY || t7.y > e51.bounds.maxY))
    return false;
  const n7 = (e53, t7, n8) => {
    const o8 = n8.x - t7.x, i8 = n8.y - t7.y, r7 = o8 * o8 + i8 * i8, s7 = r7 === 0 ? 0 : Math.max(0, Math.min(1, ((e53.x - t7.x) * o8 + (e53.y - t7.y) * i8) / r7));
    return Math.hypot(e53.x - (t7.x + s7 * o8), e53.y - (t7.y + s7 * i8));
  }, o7 = e51.meanderPoints.some((t7) => !e51.route.route.slice(1).some((o8, i8) => {
    const r7 = e51.route.route[i8];
    return r7.z === t7.z && o8.z === t7.z && n7(t7, r7, o8) <= 0.000000001;
  })), i7 = (e51.traces ?? []).map((t7) => q4(t7, e51.layerCount)), r6 = J4(e51.route), s6 = e51.route.traceThickness / 2 + e51.obstacleMargin;
  for (let a6 = 0;a6 < e51.meanderPoints.length - 1; a6++) {
    const c5 = e51.meanderPoints[a6], l5 = e51.meanderPoints[a6 + 1], h5 = e51.route.route.slice(1).some((t7, o8) => {
      const i8 = e51.route.route[o8];
      return c5.z === l5.z && i8.z === c5.z && t7.z === l5.z && n7(c5, i8, t7) <= 0.000000001 && n7(l5, i8, t7) <= 0.000000001;
    });
    if (o7 && h5)
      continue;
    for (const n8 of e51.obstacles) {
      if (!o6(n8, e51.layerCount).includes(c5.z))
        continue;
      const o8 = a6 === 0 || a6 === e51.meanderPoints.length - 2;
      if ((!n8.connectedTo.includes(r6) || !o8) && t4(c5, l5, n8, s6))
        return false;
    }
    const d6 = U4(c5.z, e51.layerCount);
    for (const { segments: e53, vias: t7 } of i7) {
      for (const t8 of e53)
        if (t8.layer === d6 && K4(c5, l5, t8.start, t8.end) < s6 + t8.width / 2)
          return false;
      for (const e54 of t7)
        if (e54.layers.includes(d6) && n7(e54, c5, l5) < s6 + e54.diameter / 2)
          return false;
    }
    for (const t7 of e51.routedRoutes) {
      const o8 = J4(t7) === r6;
      for (const i8 of t7.vias) {
        if (i8.zLayers && !i8.zLayers.includes(c5.z))
          continue;
        const r7 = Math.hypot(i8.x - c5.x, i8.y - c5.y) <= 0.00000001 || Math.hypot(i8.x - l5.x, i8.y - l5.y) <= 0.00000001, s7 = e51.route.traceThickness / 2 + t7.viaDiameter / 2 + e51.obstacleMargin;
        if ((!o8 || !r7) && n7(i8, c5, l5) < s7)
          return false;
      }
      if (!o8)
        for (let n8 = 0;n8 < t7.route.length - 1; n8++) {
          const o9 = t7.route[n8], i8 = t7.route[n8 + 1];
          if (c5.z !== o9.z || c5.z !== i8.z)
            continue;
          const r7 = e51.route.traceThickness / 2 + t7.traceThickness / 2 + e51.obstacleMargin;
          if (K4(c5, l5, o9, i8) < r7)
            return false;
        }
    }
  }
  return true;
};
var r6 = (e51) => {
  const t4 = [];
  for (const n8 of e51.routeIndexes) {
    const o7 = e51.routes[n8], i7 = e51.minMeanderGap ?? Math.max(0.3, 2 * o7.traceThickness), r7 = o7.traceThickness + i7, s6 = Math.max(e51.minimumToothPitch ?? 0, 2 * r7), a6 = e51.minMeanderHeight ?? r7;
    for (let i8 = 0;i8 < o7.route.length - 1; i8++) {
      const r8 = o7.route[i8], c5 = o7.route[i8 + 1], l5 = e62(r8, c5);
      if (l5 <= 0 || r8.z !== c5.z)
        continue;
      const h5 = Math.min(Math.max(0, Math.floor(l5 / s6) - 1), e51.maxToothCount);
      for (let o8 = 1;o8 <= h5; o8++) {
        const r9 = l5 / (o8 + 1), c6 = [r9, Math.sqrt(s6 * r9), s6].filter((e53, t7, n9) => n9.findIndex((t8) => Math.abs(t8 - e53) < 0.000000001) === t7), h6 = o8 % 2 == 0 ? ["balanced", "negative", "positive"] : ["negative", "positive"];
        for (const r10 of c6)
          for (const s7 of h6)
            t4.push({ routeIndex: n8, segmentIndex: i8, segmentLength: l5, toothCount: o8, maximumDepth: e51.maximumDepth, minimumHeight: a6, toothPitch: r10, placement: s7, heightProfile: o8 > 1 ? "tapered" : "uniform" });
      }
    }
  }
  const n7 = { balanced: 0, negative: 1, positive: 2 };
  return t4.sort((e53, t7) => e53.toothCount - t7.toothCount || n7[e53.placement] - n7[t7.placement] || t7.toothPitch - e53.toothPitch || t7.segmentLength - e53.segmentLength);
};
var s6 = (e51) => {
  if (e51.centerlineDistanceCost === null)
    return 0;
  const t4 = e51.predictedToothDepths.flatMap((e53, t7) => e53 > 0 ? [t7] : []);
  if (t4.length === 0)
    return 0;
  const n7 = t4.map((t7) => e51.predictedToothDepths[t7]), o7 = Math.max(...n7), i7 = n7.reduce((e53, t7) => e53 + t7, 0) / n7.length, r7 = Math.sqrt(n7.reduce((e53, t7) => e53 + (t7 - i7) ** 2, 0) / n7.length), s7 = t4[0], a6 = (t4.at(-1) - s7 + 1) * e51.toothPitch, c5 = o7 / (e51.toothPitch / 2), l5 = e51.addedLength / a6, h5 = c5 / (1 + c5) * 40, d6 = l5 / (1 + l5) * 30, u6 = e51.predictedToothDepths.map((t7, n8) => Math.sin(Math.PI * (n8 + 1) / (e51.predictedToothDepths.length + 1))), p6 = Math.max(...u6), m6 = Math.sqrt(e51.predictedToothDepths.reduce((e53, t7, n8) => e53 + (t7 - o7 * u6[n8] / p6) ** 2, 0) / e51.predictedToothDepths.length), g6 = 100 - h5 - d6 - Math.min(10, (e51.heightProfile === "tapered" ? m6 : r7) / i7 * 10) - 2 * (n7.length - 1) - 7 * Math.min(1, e51.addedLength / e51.segmentLength) - 100 * e51.centerlineDistanceCost, f6 = e51.centerlineDistanceCost > 0 ? g6 : Math.max(0, g6);
  return Math.round(1e6 * f6) / 1e6;
};
var a6 = (e51) => {
  if (e51.toothDepths.length !== e51.toothCount)
    throw new Error(`LengthMatchingSolver: expected ${e51.toothCount} tooth depths, received ${e51.toothDepths.length}`);
  if (e51.toothDepths.some((e53) => !Number.isFinite(e53) || e53 < 0))
    throw new Error("LengthMatchingSolver: every meander tooth depth must be a non-negative finite number");
  const t4 = e51.route.route[e51.segmentIndex], n7 = e51.route.route[e51.segmentIndex + 1], o7 = e62(t4, n7), i7 = (n7.x - t4.x) / o7, r7 = (n7.y - t4.y) / o7, s7 = (o7 - (e51.toothCount - 0.5) * e51.toothPitch) / 2, a7 = [{ ...t4 }];
  for (let n8 = 0;n8 < e51.toothCount; n8++) {
    const o8 = e51.toothDepths[n8];
    if (o8 === 0)
      continue;
    const c5 = e51.placement === "balanced" ? n8 % 2 == 0 ? -1 : 1 : e51.placement === "negative" ? -1 : 1, l5 = { x: -r7 * c5, y: i7 * c5 }, h5 = s7 + n8 * e51.toothPitch, d6 = h5 + e51.toothPitch / 2, u6 = { ...t4, x: t4.x + i7 * h5, y: t4.y + r7 * h5 };
    a7.push(u6, { ...u6, x: u6.x + l5.x * o8, y: u6.y + l5.y * o8 }, { ...t4, x: t4.x + i7 * d6 + l5.x * o8, y: t4.y + r7 * d6 + l5.y * o8 }, { ...t4, x: t4.x + i7 * d6, y: t4.y + r7 * d6 });
  }
  return a7.push({ ...n7 }), ((e53) => {
    if (e53.length < 3)
      return e53;
    const t7 = [{ ...e53[0] }];
    for (let n8 = 1;n8 < e53.length - 1; n8++) {
      const o8 = e53[n8 - 1], i8 = e53[n8], r8 = e53[n8 + 1], s8 = Math.hypot(i8.x - o8.x, i8.y - o8.y), a8 = Math.hypot(r8.x - i8.x, r8.y - i8.y);
      if (s8 === 0 || a8 === 0)
        throw new Error("LengthMatchingSolver: meander contains a zero-length segment");
      const c5 = { x: (i8.x - o8.x) / s8, y: (i8.y - o8.y) / s8 }, l5 = { x: (r8.x - i8.x) / a8, y: (r8.y - i8.y) / a8 };
      if (Math.abs(c5.x * l5.y - c5.y * l5.x) < 0.000000001) {
        t7.push({ ...i8 });
        continue;
      }
      const h5 = Math.min(s8, a8) / 2, d6 = { ...i8, x: i8.x - c5.x * h5, y: i8.y - c5.y * h5 }, u6 = { ...i8, x: i8.x + l5.x * h5, y: i8.y + l5.y * h5 }, p6 = t7.at(-1);
      d6.x === p6.x && d6.y === p6.y || t7.push(d6);
      for (let e54 = 1;e54 < 6; e54++) {
        const n9 = e54 / 6, o9 = 1 - n9;
        t7.push({ ...i8, x: o9 ** 2 * d6.x + 2 * o9 * n9 * i8.x + n9 ** 2 * u6.x, y: o9 ** 2 * d6.y + 2 * o9 * n9 * i8.y + n9 ** 2 * u6.y });
      }
      t7.push(u6);
    }
    return t7.push({ ...e53[e53.length - 1] }), t7;
  })(a7);
};
var c6 = (e51) => [...e51.route.route.slice(0, e51.segmentIndex), ...a6(e51), ...e51.route.route.slice(e51.segmentIndex + 2)];
var l6 = (e51) => {
  const t4 = t6(e51.route), n7 = (() => {
    const t7 = [];
    for (let n8 = 0;n8 < e51.candidate.toothCount; n8++) {
      const o8 = Array(e51.candidate.toothCount).fill(0);
      o8[n8] = e51.candidate.maximumDepth;
      const i8 = a6({ ...e51.candidate, route: e51.route, toothDepths: o8 });
      if (e51.isGeometryValid(i8)) {
        t7.push(e51.candidate.maximumDepth);
        continue;
      }
      let r8 = 0, s8 = e51.candidate.maximumDepth;
      for (let t8 = 0;t8 < 32; t8++) {
        const t9 = (r8 + s8) / 2, o9 = Array(e51.candidate.toothCount).fill(0);
        o9[n8] = t9;
        const i9 = a6({ ...e51.candidate, route: e51.route, toothDepths: o9 });
        e51.isGeometryValid(i9) ? r8 = t9 : s8 = t9;
      }
      t7.push(r8);
    }
    return t7;
  })(), o7 = ((e53) => {
    if (e53.heightProfile !== "tapered")
      return Array(e53.toothCount).fill(1);
    const t7 = Array.from({ length: e53.toothCount }, (t8, n9) => Math.sin(Math.PI * (n9 + 1) / (e53.toothCount + 1))), n8 = Math.max(...t7);
    return t7.map((e54) => e54 / n8);
  })(e51.candidate), i7 = e51.candidate.maximumDepth, r7 = n7.map((e53, t7) => Math.min(e53, i7 * o7[t7])), s7 = [0.25, 0.75], a7 = r7.map((e53) => e53 * s7[0]), c5 = r7.map((e53) => e53 * s7[1]), l5 = c6({ ...e51.candidate, route: e51.route, toothDepths: a7 }), h5 = c6({ ...e51.candidate, route: e51.route, toothDepths: c5 }), d6 = [t6({ ...e51.route, route: l5 }) - t4, t6({ ...e51.route, route: h5 }) - t4], u6 = c6({ ...e51.candidate, route: e51.route, toothDepths: r7 }), p6 = t6({ ...e51.route, route: u6 }) - t4, m6 = (d6[1] - d6[0]) / (s7[1] - s7[0]), g6 = d6[0] - m6 * s7[0], f6 = m6 > 0 && Number.isFinite(m6) ? (e51.targetAddedLength - g6) / m6 : 0, _5 = Math.min(e51.targetAddedLength, p6), y6 = e51.targetAddedLength > 0 && _5 > 0 ? ((t7) => {
    let n8 = 0, o8 = e51.candidate.maximumDepth;
    for (let i9 = 0;i9 < 32; i9++) {
      const i10 = (n8 + o8) / 2, r8 = t7.maximumToothDepths.map((e53, n9) => Math.min(e53, i10 * t7.toothHeightWeights[n9])), s8 = c6({ ...e51.candidate, route: e51.route, toothDepths: r8 }), a8 = t6({ ...e51.route, route: s8 }) - t7.originalLength, c7 = a6({ ...e51.candidate, route: e51.route, toothDepths: r8 });
      e51.isGeometryValid(c7) ? a8 < t7.targetAddedLength ? n8 = i10 : o8 = i10 : o8 = i10;
    }
    const i8 = (n8 + o8) / 2;
    return { depthLevel: i8, toothDepths: t7.maximumToothDepths.map((e53, n9) => Math.min(e53, i8 * t7.toothHeightWeights[n9])) };
  })({ maximumToothDepths: n7, toothHeightWeights: o7, originalLength: t4, targetAddedLength: _5 }) : { depthLevel: f6 * i7, toothDepths: r7.map((e53) => Math.max(0, e53 * f6)) }, b6 = y6.depthLevel / i7, x6 = y6.toothDepths, v6 = c6({ ...e51.candidate, route: e51.route, toothDepths: x6 }), I6 = t6({ ...e51.route, route: v6 }) - t4, S6 = Math.abs(_5 - I6), C = a6({ ...e51.candidate, route: e51.route, toothDepths: x6 });
  let P = 0;
  if (e51.getCenterlineDistanceCost && (P = e51.getCenterlineDistanceCost(C)), P !== null && (!Number.isFinite(P) || P < 0))
    throw new Error("LengthMatchingSolver: meander centerline distance cost must be a non-negative finite number");
  const M = Number.isFinite(b6) && b6 > 0 && b6 <= 1, w = x6.every((t7) => t7 === 0 || t7 >= e51.candidate.minimumHeight), N = e51.isGeometryValid(C);
  let R6, T2 = null;
  P === null ? T2 = "no-paired-same-layer-geometry" : M ? S6 > e51.lengthTolerance ? T2 = "target-error" : N ? w || (T2 = "below-minimum-height") : T2 = "invalid-geometry" : T2 = "invalid-scale", R6 = T2 ? { valid: false, invalidReason: T2 } : { valid: true, invalidReason: null };
  const E6 = { ...e51.candidate, connectionName: e51.connectionName, maximumToothDepths: n7, sampleScaleFactors: s7, sampleAddedLengths: d6, slope: m6, intercept: g6, predictedScaleFactor: b6, predictedToothDepths: x6, predictedRoute: v6, addedLength: I6, maximumAddedLength: p6, resultingError: S6, testedSegment: [{ ...e51.route.route[e51.candidate.segmentIndex] }, { ...e51.route.route[e51.candidate.segmentIndex + 1] }], meanderPoints: C, centerlineDistanceCost: P, qualityScore: 0, ...R6 };
  return { ...E6, qualityScore: s6(E6) };
};
var h6 = (e51) => {
  const t4 = ((e53) => {
    if (e53.heightProfile !== "tapered")
      return Array(e53.toothCount).fill(1);
    const t7 = Array.from({ length: e53.toothCount }, (t8, n9) => Math.sin(Math.PI * (n9 + 1) / (e53.toothCount + 1))), n8 = Math.max(...t7);
    return t7.map((e54) => e54 / n8);
  })(e51.candidate), n7 = Math.max(...t4.map((t7) => e51.candidate.minimumHeight / t7)), o7 = e51.candidate.maximumDepth / 2 ** 30, i7 = t4.map((e53) => e53 * (n7 + o7));
  if (i7.some((t7) => t7 > e51.candidate.maximumDepth))
    return null;
  const r7 = a6({ ...e51.candidate, route: e51.route, toothDepths: i7 });
  if (!e51.isGeometryValid(r7))
    return null;
  const s7 = c6({ ...e51.candidate, route: e51.route, toothDepths: i7 }), a7 = t6({ ...e51.route, route: s7 }) - t6(e51.route), c5 = l6({ ...e51, targetAddedLength: a7 });
  return c5.valid ? c5 : null;
};
var d6 = (e51) => {
  const t4 = (e53, t7) => {
    const n8 = e53[t7.routeIndex];
    if (!n8)
      throw new Error(`LengthMatchingSolver: dual meander references missing route ${t7.routeIndex}`);
    const o8 = [...e53];
    return o8[t7.routeIndex] = { ...n8, route: t7.predictedRoute }, o8;
  }, n7 = (() => {
    if (e51.targetAddedLength + e51.config.lengthTolerance < e51.plan.minimumAddedLength || e51.targetAddedLength - e51.config.lengthTolerance > e51.plan.maximumAddedLength)
      return null;
    const t7 = e51.plan.attemptOptions.map((e53) => Math.min(...e53.map((e54) => e54.attempt.addedLength)));
    let n8 = Math.max(0, e51.targetAddedLength - e51.plan.minimumAddedLength), o8 = t7.map((e53, t8) => t8);
    for (;n8 > 0.000000001 && o8.length > 0; ) {
      const i8 = n8 / o8.length;
      let r8 = 0;
      const s8 = [];
      for (const n9 of o8) {
        const o9 = Math.max(...e51.plan.attemptOptions[n9].map((e53) => e53.attempt.maximumAddedLength)) - t7[n9], a8 = Math.min(o9, i8);
        t7[n9] += a8, r8 += a8, o9 - a8 > 0.000000001 && s8.push(n9);
      }
      if (r8 <= 0.000000001)
        break;
      n8 -= r8, o8 = s8;
    }
    return n8 <= e51.config.lengthTolerance ? t7 : null;
  })();
  if (!n7)
    return null;
  const o7 = e51.plan.attemptOptions.map((e53, t7) => ({ attemptOptions: e53, targetAddedLength: n7[t7] })).sort((e53, t7) => t7.attemptOptions[0].candidate.routeIndex - e53.attemptOptions[0].candidate.routeIndex || t7.attemptOptions[0].candidate.segmentIndex - e53.attemptOptions[0].candidate.segmentIndex);
  let i7 = [...e51.routes];
  const r7 = [];
  for (const n8 of o7) {
    const o8 = n8.attemptOptions[0]?.candidate;
    if (!o8)
      throw new Error("LengthMatchingSolver: empty dual-meander segment options");
    const s8 = i7[o8.routeIndex];
    if (!s8)
      throw new Error(`LengthMatchingSolver: missing planned dual-meander route ${o8.routeIndex}`);
    let a8 = null;
    for (const t7 of n8.attemptOptions) {
      if (t7.attempt.addedLength - e51.config.lengthTolerance > n8.targetAddedLength || t7.attempt.maximumAddedLength + e51.config.lengthTolerance < n8.targetAddedLength)
        continue;
      const o9 = l6({ candidate: t7.candidate, route: s8, connectionName: e51.connectionName, targetAddedLength: n8.targetAddedLength, lengthTolerance: e51.config.lengthTolerance, isGeometryValid: (t8) => i6({ route: s8, meanderPoints: t8, routedRoutes: e51.excludedConnectionName ? i7.filter((t9) => J4(t9) !== e51.excludedConnectionName) : i7, ...e51.config }) });
      o9.valid && (!a8 || o9.qualityScore > a8.qualityScore) && (a8 = o9);
    }
    if (!a8)
      return null;
    i7 = t4(i7, a8), r7.push(a8);
  }
  const s7 = r7.reduce((e53, t7) => e53 + t7.addedLength, 0);
  if (Math.abs(s7 - e51.targetAddedLength) > e51.config.lengthTolerance)
    return null;
  const a7 = r7[0];
  if (!a7)
    throw new Error("LengthMatchingSolver: fitted an empty dual-meander plan");
  return { attempts: [a7, ...r7.slice(1)], routes: i7, addedLength: s7 };
};
var u6 = (e51) => {
  if (e51.length === 0)
    throw new Error("LengthMatchingSolver: cannot score an empty meander plan");
  return e51.reduce((e53, t4) => e53 + t4.qualityScore, 0) / e51.length - 3 * (e51.length - 1);
};
var p6 = (e51) => {
  const t4 = (e53) => [e53.candidate.toothCount, e53.candidate.placement, e53.candidate.heightProfile].join(":"), n7 = new Map;
  for (const o8 of e51) {
    const e53 = t4(o8), i7 = `${o8.candidate.routeIndex}:${o8.candidate.segmentIndex}`, r7 = n7.get(e53);
    if (!r7) {
      n7.set(e53, new Map([[i7, [o8]]]));
      continue;
    }
    const s7 = r7.get(i7);
    s7 ? s7.push(o8) : r7.set(i7, [o8]);
  }
  const o7 = [];
  for (const e53 of n7.values()) {
    const t7 = [...e53.values()].map((e54) => ({ attempts: e54, maximumAddedLength: Math.max(...e54.map((e55) => e55.attempt.maximumAddedLength)), minimumAddedLength: Math.min(...e54.map((e55) => e55.attempt.addedLength)), rankingAttempt: e54.reduce((e55, t8) => t8.attempt.qualityScore > e55.attempt.qualityScore ? t8 : e55) })).sort((e54, t8) => t8.maximumAddedLength - e54.maximumAddedLength);
    for (const e54 of t7)
      o7.push({ attempts: [e54.rankingAttempt], attemptOptions: [e54.attempts], minimumAddedLength: e54.minimumAddedLength, maximumAddedLength: e54.maximumAddedLength, rankingQualityScore: e54.rankingAttempt.attempt.qualityScore });
    for (let e54 = 2;e54 <= t7.length; e54++) {
      const n8 = t7.slice(0, e54), i7 = n8.map((e55) => e55.rankingAttempt);
      o7.push({ attempts: i7, attemptOptions: n8.map((e55) => e55.attempts), minimumAddedLength: n8.reduce((e55, t8) => e55 + t8.minimumAddedLength, 0), maximumAddedLength: n8.reduce((e55, t8) => e55 + t8.maximumAddedLength, 0), rankingQualityScore: u6(i7.map((e55) => e55.attempt)) });
    }
  }
  return o7;
};
var m6 = class extends Error {
  connectionName;
  reason;
  constructor(e51) {
    super(e51.message), this.name = "LengthMatchingNoSolutionError", this.connectionName = e51.connectionName, this.reason = e51.reason;
  }
};
var g6 = (e51) => [e51.routeIndex, e51.segmentIndex, e51.toothCount, e51.placement, e51.toothPitch, e51.heightProfile, e51.maximumDepth, e51.minimumHeight].join(":");
var f6 = (e51) => {
  const t4 = new Map, n7 = [...e51.attempts].sort((e53, t7) => e53.addedLength - t7.addedLength);
  let o7 = e51.targetAddedLength;
  for (let e53 = 0;e53 < n7.length; e53++) {
    const i7 = n7[e53], r7 = Math.min(i7.addedLength, o7 / (n7.length - e53));
    t4.set(g6(i7), { routeIndex: i7.routeIndex, segmentIndex: i7.segmentIndex, targetAddedLength: r7 }), o7 -= r7;
  }
  return t4;
};
var _6 = (e51, t4) => `z${o6(e51, t4).join(",")}`;
var y6 = (e51) => `z${e51}`;
var b6 = (e51) => {
  if (!e51.showAttempt)
    return;
  if (!e51.attempt)
    return void ((e53) => {
      const t7 = e53.activePair?.candidates[e53.activePair.candidateIndex];
      if (!t7)
        return;
      const n8 = e53.routes[t7.routeIndex];
      if (!n8)
        return;
      const o8 = n8.route[t7.segmentIndex], i8 = n8.route[t7.segmentIndex + 1];
      o8 && i8 && e53.graphics.lines.push({ points: [o8, i8], strokeColor: "rgba(234, 179, 8, 0.6)", strokeWidth: 2 * n8.traceThickness, strokeDash: [0.1, 0.1], layer: y6(o8.z) });
    })(e51);
  const t4 = e51.routes[e51.attempt.routeIndex], [n7, o7] = e51.attempt.testedSegment, i7 = e51.theme.getConnectionColor(e51.attempt.connectionName);
  e51.graphics.lines.push({ points: [n7, o7], strokeColor: e51.theme.getTestedSegmentColor(i7), strokeWidth: t4.traceThickness, strokeDash: [0.15, 0.15], layer: y6(n7.z) }), e51.attempt.valid ? e51.graphics.lines.push({ points: e51.attempt.meanderPoints.map(({ x: e53, y: t7 }) => ({ x: e53, y: t7 })), strokeColor: "rgba(234, 179, 8, 0.6)", strokeWidth: 2 * t4.traceThickness, strokeDash: [0.1, 0.1], layer: y6(n7.z) }) : e51.graphics.lines.push({ points: e51.attempt.meanderPoints.map(({ x: e53, y: t7 }) => ({ x: e53, y: t7 })), strokeColor: e51.theme.getRejectedCandidateColor(i7), strokeWidth: t4.traceThickness, strokeDash: [0.1, 0.1], layer: y6(n7.z) }), e51.graphics.points.push({ x: n7.x, y: n7.y, color: i7, layer: y6(n7.z) }, { x: o7.x, y: o7.y, color: i7, layer: y6(o7.z) });
};
var x6 = (e51) => {
  const t4 = { lines: [], points: [], rects: [], circles: [] }, n7 = ((e53) => {
    for (const t7 of Object.values(e53))
      Hn(0, t7);
    return { getConnectionColor: (t7, n8) => e53[t7] ?? (n8 ? e53[n8] : undefined) ?? ((e54) => e54 ? `hsl(${300 * e54.split("").reduce((e55, t8) => e55 + t8.charCodeAt(0), 0) / e54.length % 360}, 100%, 50%)` : "rgba(0, 0, 0, 0.5)")(t7), getInnerLayerConnectionColor: (e54) => Hn(0.5, e54), getTestedSegmentColor: (e54) => Hn(0.55, e54), getRejectedCandidateColor: (e54) => Hn(0.45, e54), boardBounds: { fill: "rgba(30,41,59,0.03)", stroke: "rgba(30,41,59,0.55)" }, obstacle: { fill: "rgba(255,0,0,0.25)", stroke: "rgba(255,0,0,0.5)" }, via: { fill: "blue", stroke: "none" } };
  })(e51.colorMap);
  return ((e53) => {
    for (const t7 of e53.routes) {
      const n8 = J4(t7), o7 = e53.theme.getConnectionColor(n8, t7.connectionName);
      for (let n9 = 0;n9 < t7.route.length - 1; n9++) {
        const i8 = t7.route[n9], r7 = t7.route[n9 + 1];
        i8.z === r7.z && e53.graphics.lines.push({ points: [i8, r7], strokeColor: i8.z === 0 ? o7 : e53.theme.getInnerLayerConnectionColor(o7), strokeWidth: t7.traceThickness, ...i8.z === 0 ? {} : { strokeDash: [0.2, 0.2] }, layer: y6(i8.z) });
      }
      const i7 = [...new Set(t7.route.map((e54) => e54.z))];
      for (const n9 of t7.vias)
        e53.graphics.circles.push({ center: n9, radius: t7.viaDiameter / 2, fill: e53.theme.via.fill, stroke: e53.theme.via.stroke, layer: `z${(n9.zLayers ?? i7).join(",")}` });
    }
  })({ routes: e51.routes, theme: n7, graphics: t4 }), ((e53) => {
    if (e53.bounds) {
      const { minX: t7, maxX: n8, minY: o7, maxY: i7 } = e53.bounds;
      e53.graphics.rects.push({ center: { x: (t7 + n8) / 2, y: (o7 + i7) / 2 }, width: n8 - t7, height: i7 - o7, fill: e53.theme.boardBounds.fill, stroke: e53.theme.boardBounds.stroke, layer: `z${Array.from({ length: e53.layerCount }, (e54, t8) => t8).join(",")}` });
    }
    for (const t7 of e53.obstacles)
      e53.graphics.rects.push({ center: t7.center, width: t7.width, height: t7.height, ccwRotationDegrees: t7.ccwRotationDegrees, fill: e53.theme.obstacle.fill, stroke: e53.theme.obstacle.stroke, layer: _6(t7, e53.layerCount) });
  })({ obstacles: e51.obstacles, bounds: e51.bounds, layerCount: e51.layerCount, theme: n7, graphics: t4 }), b6({ routes: e51.routes, attempt: e51.currentAttempt, activePair: e51.activePair, showAttempt: !e51.solved, theme: n7, graphics: t4 }), { ...t4 };
};
var v6 = class extends BaseSolver {
  constructor(e51) {
    super(), this.params = e51, this.MAX_ITERATIONS = 1e5, this.matchedHdRoutes = e51.hdRoutes.map((e53) => ({ ...e53, route: e53.route.map((e54) => ({ ...e54 })) })), this.pairs = e51.differentialPairs ?? [];
  }
  matchedHdRoutes;
  pairs;
  nextPairIndex = 0;
  activePair = null;
  currentAttempt = null;
  config = null;
  candidatesTried = 0;
  getSolverName() {
    return "LengthMatchingSolver";
  }
  startNextPair() {
    const e51 = this.pairs[this.nextPairIndex++];
    if (!e51)
      return void (this.solved = true);
    ((e53, t7) => {
      if (e53.connectionNames[0] === e53.connectionNames[1])
        throw new Error("LengthMatchingSolver: a differential pair must reference two distinct connections");
      if (!Number.isFinite(e53.lengthTolerance) || e53.lengthTolerance < 0)
        throw new Error("LengthMatchingSolver: differential pair lengthTolerance must be a non-negative finite number");
      for (const t8 of [e53.minimumCenterlineDistance, e53.maximumCenterlineDistance])
        if (t8 !== undefined && (!Number.isFinite(t8) || t8 <= 0))
          throw new Error("LengthMatchingSolver: differential pair centerline distances must be positive finite numbers");
      if (e53.minimumCenterlineDistance !== undefined && e53.maximumCenterlineDistance !== undefined && e53.minimumCenterlineDistance > e53.maximumCenterlineDistance)
        throw new Error("LengthMatchingSolver: differential pair minimumCenterlineDistance cannot exceed maximumCenterlineDistance");
      const n8 = new Map(t7.map((e54) => [e54.name, e54]));
      for (const t8 of e53.connectionNames) {
        const e54 = n8.get(t8);
        if (!e54)
          throw new Error(`LengthMatchingSolver: differential pair references unknown connection "${t8}"`);
        if (e54.pointsToConnect.length !== 2)
          throw new Error(`LengthMatchingSolver: differential pair connection "${t8}" must have exactly two points before MST splitting`);
      }
    })(e51, this.params.originalConnections);
    const t4 = Q4(this.matchedHdRoutes, e51.connectionNames[0]), n7 = Q4(this.matchedHdRoutes, e51.connectionNames[1]);
    if (t4.length === 0 && n7.length === 0)
      return;
    if (t4.length === 0 || n7.length === 0)
      throw new Error(`LengthMatchingSolver: differential pair ${e51.connectionNames.join("/")} has routed geometry for only one connection`);
    const o7 = n6(this.matchedHdRoutes, t4), i7 = n6(this.matchedHdRoutes, n7), r7 = Math.abs(o7 - i7);
    if (r7 <= e51.lengthTolerance)
      return;
    const s7 = o7 < i7, a7 = e51.connectionNames[s7 ? 0 : 1], c5 = e51.connectionNames[s7 ? 1 : 0], l5 = r6({ routes: this.matchedHdRoutes, routeIndexes: s7 ? t4 : n7, maximumDepth: this.getConfig().maximumMeanderDepth, minimumToothPitch: this.getConfig().minimumToothPitch, minMeanderGap: this.getConfig().minMeanderGap, minMeanderHeight: this.getConfig().minMeanderHeight, maxToothCount: this.getConfig().maxToothCount });
    if (l5.length === 0)
      throw new m6({ message: `LengthMatchingSolver: no same-layer straight segment can tune connection "${a7}"`, connectionName: a7, reason: "no-meander-candidate" });
    this.activePair = { pair: e51, longerConnectionName: c5, longerRouteIndexes: s7 ? n7 : t4, shorterConnectionName: a7, targetAddedLength: r7, remainingAddedLength: r7, candidates: l5, candidateIndex: 0, lastMatchedSegmentIndexByRoute: new Map, partialAttempts: [], fullAttempts: [], plannedAttemptTargets: null, hasMinimumHeightBlockedAttempt: false };
  }
  acceptAttempt(e51, t4) {
    const n7 = this.matchedHdRoutes[t4.routeIndex];
    this.matchedHdRoutes[t4.routeIndex] = { ...n7, route: t4.predictedRoute }, e51.remainingAddedLength -= t4.addedLength, e51.lastMatchedSegmentIndexByRoute.set(t4.routeIndex, t4.segmentIndex), e51.candidateIndex = 0, e51.partialAttempts = [], e51.fullAttempts = [], e51.plannedAttemptTargets?.delete(g6(t4)), e51.plannedAttemptTargets?.size === 0 && (e51.plannedAttemptTargets = null), e51.remainingAddedLength <= e51.pair.lengthTolerance && (this.activePair = null);
  }
  tryCandidate(e51) {
    let t4;
    for (;!t4; ) {
      const n8 = e51.candidates[e51.candidateIndex++];
      if (!n8)
        break;
      const o8 = e51.lastMatchedSegmentIndexByRoute.get(n8.routeIndex);
      (o8 === undefined || n8.segmentIndex < o8) && (!e51.plannedAttemptTargets || e51.plannedAttemptTargets.has(g6(n8)) && ![...e51.plannedAttemptTargets.values()].some((e53) => e53.routeIndex === n8.routeIndex && e53.segmentIndex > n8.segmentIndex)) && (t4 = n8);
    }
    if (!t4) {
      const t7 = e51.fullAttempts.reduce((e53, t8) => !e53 || t8.qualityScore > e53.qualityScore ? t8 : e53, null), n8 = ((e53) => {
        const t8 = (e54) => [e54.toothCount, e54.placement, e54.heightProfile].join(":"), n9 = new Map;
        for (const o9 of e53.attempts) {
          const e54 = `${o9.routeIndex}:${o9.segmentIndex}`, i8 = t8(o9), r7 = n9.get(i8);
          if (!r7) {
            n9.set(i8, new Map([[e54, [o9]]]));
            continue;
          }
          const s7 = r7.get(e54);
          s7 ? s7.push(o9) : r7.set(e54, [o9]);
        }
        let o8 = null;
        for (const t9 of n9.values()) {
          const n10 = [...t9.values()].map((e54) => ({ attempts: e54, maximumCapacityAttempt: e54.reduce((e55, t10) => t10.addedLength > e55.addedLength ? t10 : e55) })).sort((e54, t10) => t10.maximumCapacityAttempt.addedLength - e54.maximumCapacityAttempt.addedLength);
          let i8 = 0;
          for (let t10 = 0;t10 < n10.length; t10++) {
            if (i8 += n10[t10].maximumCapacityAttempt.addedLength, i8 + e53.lengthTolerance < e53.targetAddedLength)
              continue;
            const r7 = n10.slice(0, t10 + 1), s7 = r7.map((e54) => e54.maximumCapacityAttempt), a7 = f6({ attempts: s7, targetAddedLength: e53.targetAddedLength }), c5 = r7.map((t11) => {
              const n11 = a7.get(g6(t11.maximumCapacityAttempt));
              if (!n11)
                throw new Error(`LengthMatchingSolver: missing capacity target for ${g6(t11.maximumCapacityAttempt)}`);
              const o9 = t11.attempts.filter((t12) => t12.addedLength + e53.lengthTolerance >= n11.targetAddedLength);
              if (o9.length === 0)
                throw new Error(`LengthMatchingSolver: no pitch can supply planned target for route ${t11.maximumCapacityAttempt.routeIndex} segment ${t11.maximumCapacityAttempt.segmentIndex}`);
              return o9.reduce((e54, t12) => t12.qualityScore > e54.qualityScore || t12.qualityScore === e54.qualityScore && t12.toothPitch > e54.toothPitch ? t12 : e54);
            }), l5 = u6(c5);
            if (!o8) {
              o8 = { attempts: c5 };
              break;
            }
            const h5 = u6(o8.attempts);
            (c5.length < o8.attempts.length || c5.length === o8.attempts.length && l5 > h5) && (o8 = { attempts: c5 });
            break;
          }
        }
        return o8;
      })({ attempts: e51.partialAttempts, targetAddedLength: e51.remainingAddedLength, lengthTolerance: e51.pair.lengthTolerance });
      if (t7 && (!n8 || t7.qualityScore >= u6(n8.attempts)))
        return void this.acceptAttempt(e51, t7);
      if (!n8) {
        if (!(e51.hasMinimumHeightBlockedAttempt && e51.plannedAttemptTargets === null && e51.lastMatchedSegmentIndexByRoute.size === 0))
          throw new m6({ message: `LengthMatchingSolver: linear regression exhausted all segment/tooth combinations for "${e51.shorterConnectionName}"; required ${e51.targetAddedLength.toFixed(4)}mm`, connectionName: e51.shorterConnectionName, reason: "meander-search-exhausted" });
        return this.tryDualMeanderPlan(e51);
      }
      return e51.plannedAttemptTargets = f6({ attempts: n8.attempts, targetAddedLength: e51.remainingAddedLength }), e51.candidateIndex = 0, e51.partialAttempts = [], void (e51.fullAttempts = []);
    }
    const n7 = this.matchedHdRoutes[t4.routeIndex], o7 = this.getConfig(), i7 = e51.plannedAttemptTargets?.get(g6(t4));
    if (e51.plannedAttemptTargets !== null && i7 === undefined)
      throw new Error(`LengthMatchingSolver: missing planned target for ${g6(t4)}`);
    this.currentAttempt = l6({ candidate: t4, route: n7, connectionName: e51.shorterConnectionName, targetAddedLength: i7 === undefined ? e51.remainingAddedLength : i7.targetAddedLength, lengthTolerance: e51.pair.lengthTolerance, isGeometryValid: (e53) => i6({ route: n7, meanderPoints: e53, routedRoutes: this.matchedHdRoutes, traces: o7.traces, obstacles: o7.obstacles, bounds: o7.bounds, layerCount: o7.layerCount, obstacleMargin: o7.obstacleMargin }), getCenterlineDistanceCost: e51.pair.minimumCenterlineDistance === undefined && e51.pair.maximumCenterlineDistance === undefined ? undefined : (t7) => ((e53) => {
      let t8 = 0, n8 = 0;
      for (let o8 = 0;o8 < e53.meanderPoints.length - 1; o8++) {
        const i8 = e53.meanderPoints[o8], r7 = e53.meanderPoints[o8 + 1], s7 = Math.hypot(r7.x - i8.x, r7.y - i8.y);
        if (s7 !== 0) {
          for (let t9 = 0;t9 < 4; t9++) {
            const o9 = (t9 + 0.5) / 4, a7 = { x: i8.x + (r7.x - i8.x) * o9, y: i8.y + (r7.y - i8.y) * o9 }, c5 = [];
            for (const t10 of e53.pairedRoutes)
              for (let e54 = 0;e54 < t10.route.length - 1; e54++) {
                const n9 = t10.route[e54], o10 = t10.route[e54 + 1];
                i8.z === n9.z && i8.z === o10.z && c5.push(K4(a7, a7, n9, o10));
              }
            if (c5.length === 0)
              return null;
            const l5 = Math.min(...c5);
            n8 += s7 * Math.max(0, (e53.minimumCenterlineDistance ?? Number.NEGATIVE_INFINITY) - l5, l5 - (e53.maximumCenterlineDistance ?? Number.POSITIVE_INFINITY)) / 4;
          }
          t8 += s7;
        }
      }
      if (t8 === 0)
        throw new Error("LengthMatchingSolver: cannot measure a zero-length meander centerline");
      return n8 / t8;
    })({ meanderPoints: t7, pairedRoutes: e51.longerRouteIndexes.map((e53) => this.matchedHdRoutes[e53]), minimumCenterlineDistance: e51.pair.minimumCenterlineDistance, maximumCenterlineDistance: e51.pair.maximumCenterlineDistance }) }), this.candidatesTried++, this.currentAttempt.invalidReason === "below-minimum-height" && (e51.hasMinimumHeightBlockedAttempt = true), this.stats = { pair: `${e51.pair.connectionNames[0]}/${e51.pair.connectionNames[1]}`, candidatesTried: this.candidatesTried, segmentIndex: t4.segmentIndex, toothCount: t4.toothCount, toothPitch: t4.toothPitch, placement: t4.placement, predictedScaleFactor: this.currentAttempt.predictedScaleFactor, predictedToothDepths: this.currentAttempt.predictedToothDepths, resultingError: this.currentAttempt.resultingError, qualityScore: this.currentAttempt.qualityScore, accepted: this.currentAttempt.valid }, this.currentAttempt.valid && (e51.plannedAttemptTargets === null ? e51.remainingAddedLength - this.currentAttempt.addedLength <= e51.pair.lengthTolerance ? e51.fullAttempts.push(this.currentAttempt) : e51.partialAttempts.push(this.currentAttempt) : this.acceptAttempt(e51, this.currentAttempt));
  }
  tryDualMeanderPlan(e51) {
    if (e51.remainingAddedLength !== e51.targetAddedLength)
      throw new Error(`LengthMatchingSolver: cannot start a dual-meander plan after partially tuning "${e51.shorterConnectionName}"`);
    const t4 = this.getConfig(), n7 = r6({ routes: this.matchedHdRoutes, routeIndexes: e51.longerRouteIndexes, maximumDepth: t4.maximumMeanderDepth, minimumToothPitch: t4.minimumToothPitch, minMeanderGap: t4.minMeanderGap, minMeanderHeight: t4.minMeanderHeight, maxToothCount: t4.maxToothCount }), o7 = ((e53) => {
      const t7 = (e54, t8) => e54.rankingQualityScore !== t8.rankingQualityScore ? e54.rankingQualityScore > t8.rankingQualityScore : e54.leftIndex !== t8.leftIndex ? e54.leftIndex < t8.leftIndex : e54.rightIndex < t8.rightIndex, n8 = (e54, n9) => {
        e54.push(n9);
        let o9 = e54.length - 1;
        for (;o9 > 0; ) {
          const i9 = Math.floor((o9 - 1) / 2), r9 = e54[i9];
          if (t7(r9, n9))
            break;
          e54[o9] = r9, o9 = i9;
        }
        e54[o9] = n9;
      }, o8 = (e54) => {
        const n9 = e54[0], o9 = e54.pop();
        if (!n9 || !o9 || e54.length === 0)
          return n9;
        let i9 = 0;
        for (;; ) {
          const n10 = 2 * i9 + 1, r9 = n10 + 1;
          if (n10 >= e54.length)
            break;
          const s9 = r9 < e54.length && t7(e54[r9], e54[n10]) ? r9 : n10, a8 = e54[s9];
          if (t7(o9, a8))
            break;
          e54[i9] = a8, i9 = s9;
        }
        return e54[i9] = o9, n9;
      }, i8 = function* (e54) {
        const t8 = [...e54.leftOptions].sort((t9, n9) => e54.getLeftQualityScore(n9) - e54.getLeftQualityScore(t9)), i9 = [...e54.rightOptions].sort((t9, n9) => e54.getRightQualityScore(n9) - e54.getRightQualityScore(t9)), r9 = [];
        for (let o9 = 0;o9 < t8.length; o9++) {
          const s9 = i9[0];
          if (!s9)
            break;
          n8(r9, { leftIndex: o9, rightIndex: 0, rankingQualityScore: (e54.getLeftQualityScore(t8[o9]) + e54.getRightQualityScore(s9)) / 2 });
        }
        for (;r9.length > 0; ) {
          const s9 = o8(r9);
          yield [t8[s9.leftIndex], i9[s9.rightIndex]];
          const a8 = s9.rightIndex + 1, c7 = i9[a8];
          c7 && n8(r9, { leftIndex: s9.leftIndex, rightIndex: a8, rankingQualityScore: (e54.getLeftQualityScore(t8[s9.leftIndex]) + e54.getRightQualityScore(c7)) / 2 });
        }
      }, r8 = (e54, t8) => {
        const n9 = e54[t8.routeIndex];
        if (!n9)
          throw new Error(`LengthMatchingSolver: dual meander references missing route ${t8.routeIndex}`);
        const o9 = [...e54];
        return o9[t8.routeIndex] = { ...n9, route: t8.predictedRoute }, o9;
      }, s8 = (e54) => {
        const t8 = e54.routes[e54.attempt.routeIndex];
        if (!t8)
          throw new Error(`LengthMatchingSolver: cannot validate missing dual-meander route ${e54.attempt.routeIndex}`);
        return i6({ route: t8, meanderPoints: e54.attempt.meanderPoints, routedRoutes: e54.routes, ...e54.config });
      }, a7 = (e54) => {
        const t8 = e54.routes.filter((t9) => J4(t9) !== e54.counterpartConnectionName), n9 = [];
        for (const o9 of e54.candidates) {
          const i9 = e54.routes[o9.routeIndex];
          if (!i9)
            throw new Error(`LengthMatchingSolver: dual-meander candidate references missing route ${o9.routeIndex}`);
          const r9 = h6({ candidate: o9, route: i9, connectionName: e54.connectionName, lengthTolerance: e54.config.lengthTolerance, isGeometryValid: (n10) => i6({ route: i9, meanderPoints: n10, routedRoutes: t8, ...e54.config }) });
          r9 && n9.push({ candidate: o9, attempt: r9 });
        }
        return n9;
      }, c5 = { traces: e53.traces, obstacles: e53.obstacles, bounds: e53.bounds, layerCount: e53.layerCount, obstacleMargin: e53.obstacleMargin }, l5 = a7({ candidates: e53.shorterCandidates, routes: e53.routes, connectionName: e53.shorterConnectionName, counterpartConnectionName: e53.longerConnectionName, config: { ...c5, lengthTolerance: e53.lengthTolerance } });
      if (l5.length === 0)
        return null;
      const h5 = a7({ candidates: e53.longerCandidates, routes: e53.routes, connectionName: e53.longerConnectionName, counterpartConnectionName: e53.shorterConnectionName, config: { ...c5, lengthTolerance: e53.lengthTolerance } }), d7 = i8({ leftOptions: h5, rightOptions: l5, getLeftQualityScore: (e54) => e54.attempt.qualityScore, getRightQualityScore: (e54) => e54.attempt.qualityScore });
      for (const [t8, n9] of d7) {
        const o9 = Math.max(t8.attempt.addedLength, n9.attempt.addedLength - e53.originalLengthDifference), i9 = o9 + e53.originalLengthDifference;
        if (o9 - e53.lengthTolerance > t8.attempt.maximumAddedLength || i9 - e53.lengthTolerance > n9.attempt.maximumAddedLength)
          continue;
        const a8 = e53.routes[t8.candidate.routeIndex];
        if (!a8)
          throw new Error(`LengthMatchingSolver: missing longer route ${t8.candidate.routeIndex}`);
        const l7 = e53.routes[n9.candidate.routeIndex];
        if (!l7)
          throw new Error(`LengthMatchingSolver: missing shorter route ${n9.candidate.routeIndex}`);
        const h7 = e53.routes.filter((t9) => J4(t9) !== e53.shorterConnectionName), d8 = l6({ candidate: t8.candidate, route: a8, connectionName: e53.longerConnectionName, targetAddedLength: o9, lengthTolerance: e53.lengthTolerance, isGeometryValid: (e54) => i6({ route: a8, meanderPoints: e54, routedRoutes: h7, ...c5 }) });
        if (!d8.valid || Math.abs(d8.addedLength - o9) > e53.lengthTolerance)
          continue;
        const u8 = r8(e53.routes, d8), p7 = d8.addedLength + e53.originalLengthDifference, m7 = l6({ candidate: n9.candidate, route: l7, connectionName: e53.shorterConnectionName, targetAddedLength: p7, lengthTolerance: e53.lengthTolerance, isGeometryValid: (e54) => i6({ route: l7, meanderPoints: e54, routedRoutes: u8, ...c5 }) });
        if (!m7.valid)
          continue;
        const g7 = r8(u8, m7), f7 = Q4(g7, e53.longerConnectionName), _5 = Q4(g7, e53.shorterConnectionName);
        if (!(Math.abs(n6(g7, _5) - n6(g7, f7)) > e53.lengthTolerance) && s8({ attempt: d8, routes: g7, config: c5 }) && s8({ attempt: m7, routes: g7, config: c5 }))
          return { longerAttempts: [d8], shorterAttempts: [m7] };
      }
      const u7 = i8({ leftOptions: p6(h5), rightOptions: p6(l5), getLeftQualityScore: (e54) => e54.rankingQualityScore, getRightQualityScore: (e54) => e54.rankingQualityScore });
      for (const [t8, n9] of u7) {
        if (t8.attempts.length === 1 && n9.attempts.length === 1)
          continue;
        const o9 = Math.max(t8.minimumAddedLength, n9.minimumAddedLength - e53.originalLengthDifference), i9 = o9 + e53.originalLengthDifference;
        if (o9 - e53.lengthTolerance > t8.maximumAddedLength || i9 - e53.lengthTolerance > n9.maximumAddedLength)
          continue;
        const r9 = d6({ plan: t8, targetAddedLength: o9, routes: e53.routes, connectionName: e53.longerConnectionName, excludedConnectionName: e53.shorterConnectionName, config: { ...c5, lengthTolerance: e53.lengthTolerance } });
        if (!r9)
          continue;
        const a8 = d6({ plan: n9, targetAddedLength: r9.addedLength + e53.originalLengthDifference, routes: r9.routes, connectionName: e53.shorterConnectionName, config: { ...c5, lengthTolerance: e53.lengthTolerance } });
        if (!a8)
          continue;
        const l7 = Q4(a8.routes, e53.longerConnectionName), h7 = Q4(a8.routes, e53.shorterConnectionName), d8 = Math.abs(n6(a8.routes, h7) - n6(a8.routes, l7)), u8 = [...r9.attempts, ...a8.attempts];
        if (!(d8 > e53.lengthTolerance || u8.some((e54) => !s8({ attempt: e54, routes: a8.routes, config: c5 }))))
          return { longerAttempts: r9.attempts, shorterAttempts: a8.attempts };
      }
      return null;
    })({ routes: this.matchedHdRoutes, longerConnectionName: e51.longerConnectionName, shorterConnectionName: e51.shorterConnectionName, originalLengthDifference: e51.targetAddedLength, lengthTolerance: e51.pair.lengthTolerance, longerCandidates: n7, shorterCandidates: e51.candidates, traces: t4.traces, obstacles: t4.obstacles, bounds: t4.bounds, layerCount: t4.layerCount, obstacleMargin: t4.obstacleMargin });
    if (!o7)
      throw new m6({ message: `LengthMatchingSolver: linear regression exhausted all segment/tooth combinations for "${e51.shorterConnectionName}"; required ${e51.targetAddedLength.toFixed(4)}mm`, connectionName: e51.shorterConnectionName, reason: "meander-search-exhausted" });
    const i7 = [...this.matchedHdRoutes];
    for (const e53 of [...o7.longerAttempts, ...o7.shorterAttempts]) {
      const t7 = this.matchedHdRoutes[e53.routeIndex];
      if (!t7)
        throw new Error(`LengthMatchingSolver: cannot commit dual meander to missing route ${e53.routeIndex}`);
      i7[e53.routeIndex] = { ...t7, route: e53.predictedRoute };
    }
    this.matchedHdRoutes = i7, this.currentAttempt = o7.shorterAttempts[0];
    const r7 = o7.longerAttempts.reduce((e53, t7) => e53 + t7.addedLength, 0), s7 = o7.shorterAttempts.reduce((e53, t7) => e53 + t7.addedLength, 0);
    this.stats = { pair: `${e51.pair.connectionNames[0]}/${e51.pair.connectionNames[1]}`, mode: "dual-meander", longerAddedLength: r7, shorterAddedLength: s7, resultingError: Math.abs(s7 - r7 - e51.targetAddedLength) }, this.activePair = null;
  }
  getConfig() {
    return this.config || (this.config = ((e51) => {
      const t4 = e51.maximumMeanderDepth ?? 5, n7 = e51.maxToothCount ?? 12;
      if (!Number.isFinite(t4) || t4 <= 0)
        throw new Error("LengthMatchingSolver: maximumMeanderDepth must be a positive finite number");
      if (e51.minimumToothPitch !== undefined && (!Number.isFinite(e51.minimumToothPitch) || e51.minimumToothPitch <= 0))
        throw new Error("LengthMatchingSolver: minimumToothPitch must be a positive finite number");
      if (e51.minMeanderGap !== undefined && (!Number.isFinite(e51.minMeanderGap) || e51.minMeanderGap <= 0))
        throw new Error("LengthMatchingSolver: minMeanderGap must be a positive finite number");
      if (e51.minMeanderHeight !== undefined && (!Number.isFinite(e51.minMeanderHeight) || e51.minMeanderHeight <= 0))
        throw new Error("LengthMatchingSolver: minMeanderHeight must be a positive finite number");
      if (e51.minMeanderHeight !== undefined && e51.minMeanderHeight > t4)
        throw new Error("LengthMatchingSolver: minMeanderHeight cannot exceed maximumMeanderDepth");
      if (!Number.isFinite(n7) || !Number.isInteger(n7) || n7 <= 0)
        throw new Error("LengthMatchingSolver: maxToothCount must be a positive finite integer");
      for (const t7 of e51.traces ?? [])
        q4(t7, e51.layerCount ?? 2);
      return { maximumMeanderDepth: t4, minimumToothPitch: e51.minimumToothPitch, minMeanderGap: e51.minMeanderGap, minMeanderHeight: e51.minMeanderHeight, maxToothCount: n7, traces: e51.traces ?? [], obstacles: e51.obstacles ?? [], bounds: e51.bounds, obstacleMargin: e51.obstacleMargin ?? 0.15, layerCount: e51.layerCount ?? 2, colorMap: e51.colorMap ?? {} };
    })(this.params)), this.config;
  }
  _step() {
    this.getConfig(), this.activePair ? this.tryCandidate(this.activePair) : this.startNextPair();
  }
  getConstructorParams() {
    return [this.params];
  }
  getOutput() {
    if (!this.solved)
      throw new Error("LengthMatchingSolver: getOutput() called before the solver completed");
    return { matchedHdRoutes: this.matchedHdRoutes };
  }
  getBestEffortOutput() {
    const e51 = structuredClone(this.matchedHdRoutes), t4 = this.activePair?.fullAttempts ?? [];
    let n7 = null;
    for (const e53 of t4)
      (!n7 || e53.qualityScore > n7.qualityScore) && (n7 = e53);
    if (!n7)
      for (const e53 of this.activePair?.partialAttempts ?? [])
        (!n7 || e53.addedLength > n7.addedLength || e53.addedLength === n7.addedLength && e53.qualityScore > n7.qualityScore) && (n7 = e53);
    if (n7) {
      const t7 = e51[n7.routeIndex];
      t7 && (e51[n7.routeIndex] = { ...t7, route: structuredClone(n7.predictedRoute) });
    }
    return { matchedHdRoutes: e51 };
  }
  computeProgress() {
    if (this.solved)
      return 1;
    if (this.pairs.length === 0)
      return this.config ? 1 : 0;
    const e51 = Math.max(0, this.nextPairIndex - 1), t4 = this.activePair ? this.activePair.candidateIndex / this.activePair.candidates.length : 0;
    return Math.min(0.99, (e51 + t4) / this.pairs.length);
  }
  visualize() {
    const e51 = this.getConfig();
    return x6({ routes: this.matchedHdRoutes, obstacles: e51.obstacles, bounds: e51.bounds, layerCount: e51.layerCount, colorMap: e51.colorMap, activePair: this.activePair, currentAttempt: this.currentAttempt, solved: this.solved });
  }
};
var C6 = 0.00000001;
var P6 = (e51, t4) => {
  if (e51.route.length === 0)
    throw new Error(`trace "${e51.connection_name}" has an empty route`);
  if (e51.route.some((e53) => e53.route_type !== "wire" && e53.route_type !== "via"))
    throw new Error(`trace "${e51.connection_name}" contains unsupported jumper or through-obstacle geometry`);
  const n7 = e51.route.findIndex((e53) => e53.route_type === "wire"), o7 = e51.route[n7], i7 = e51.route.findLast((e53) => e53.route_type === "wire");
  if (o7?.route_type !== "wire" || !i7)
    throw new Error(`trace "${e51.connection_name}" must contain a wire point`);
  const r7 = [], s7 = [], a7 = [], c5 = [];
  let l5 = null, h5 = o7.width;
  if (n7 > 0) {
    let t7 = o7.layer;
    for (let o8 = n7 - 1;o8 >= 0; o8--) {
      const n8 = e51.route[o8];
      if (n8?.route_type !== "via")
        throw new Error(`trace "${e51.connection_name}" has unsupported geometry before its first wire`);
      if (t7 === n8.to_layer)
        t7 = n8.from_layer;
      else {
        if (t7 !== n8.from_layer)
          throw new Error(`trace "${e51.connection_name}" has discontinuous leading vias`);
        t7 = n8.to_layer;
      }
    }
    const i8 = e51.route[0];
    if (i8.route_type !== "via")
      throw new Error(`trace "${e51.connection_name}" has an invalid leading entry`);
    l5 = { x: i8.x, y: i8.y, layer: t7, width: o7.width }, r7.push(l5);
  }
  for (const n8 of e51.route) {
    if (n8.route_type === "wire") {
      if (!Number.isFinite(n8.x) || !Number.isFinite(n8.y) || !Number.isFinite(n8.width) || n8.width <= 0 || G4(n8.layer, t4) < 0)
        throw new Error(`trace "${e51.connection_name}" has an invalid wire point`);
      h5 = Math.max(h5, n8.width);
      const o9 = { x: n8.x, y: n8.y, layer: n8.layer, width: n8.width };
      if (l5) {
        if (l5.layer !== o9.layer)
          throw new Error(`trace "${e51.connection_name}" changes layers without a via`);
        Math.hypot(l5.x - o9.x, l5.y - o9.y) > C6 && s7.push({ start: l5, end: o9, layer: o9.layer, width: Math.max(l5.width, o9.width), connectionName: e51.connection_name, terminal: null });
      }
      r7.push(o9), l5 = o9;
      continue;
    }
    if (n8.route_type !== "via")
      throw new Error(`trace "${e51.connection_name}" contains unsupported route geometry`);
    if (!l5)
      throw new Error(`trace "${e51.connection_name}" has a leading via`);
    const o8 = G4(n8.from_layer, t4), i8 = G4(n8.to_layer, t4), d8 = n8.via_diameter ?? l5.width;
    if (!Number.isFinite(n8.x) || !Number.isFinite(n8.y) || o8 < 0 || i8 < 0 || o8 === i8 || n8.via_diameter !== undefined && (!Number.isFinite(n8.via_diameter) || n8.via_diameter <= 0) || n8.via_hole_diameter !== undefined && (!Number.isFinite(n8.via_hole_diameter) || n8.via_hole_diameter <= 0 || n8.via_hole_diameter >= d8))
      throw new Error(`trace "${e51.connection_name}" has an invalid via`);
    const u7 = l5.layer === n8.from_layer ? n8.from_layer : l5.layer === n8.to_layer ? n8.to_layer : null;
    if (!u7)
      throw new Error(`trace "${e51.connection_name}" has a discontinuous via transition`);
    Math.hypot(l5.x - n8.x, l5.y - n8.y) > C6 && s7.push({ start: l5, end: n8, layer: l5.layer, width: l5.width, connectionName: e51.connection_name, terminal: null });
    const p7 = u7 === n8.from_layer ? n8.to_layer : n8.from_layer;
    c5.push({ ...n8, from_layer: u7, to_layer: p7 }), a7.push({ x: n8.x, y: n8.y, layers: Z4(u7, p7, t4), diameter: d8, connectionName: e51.connection_name, terminal: r7.length === 1 ? "start" : null }), l5 = { x: n8.x, y: n8.y, layer: p7, width: l5.width }, r7.push(l5);
  }
  if (r7.length < 2 || s7.length === 0)
    throw new Error(`trace "${e51.connection_name}" does not contain a routable path`);
  s7[0].terminal = s7.length === 1 ? "both" : "start", s7[s7.length - 1].terminal = s7.length === 1 ? "both" : "end";
  const d7 = a7.at(-1);
  return d7 && Math.hypot(d7.x - i7.x, d7.y - i7.y) <= C6 && (d7.terminal = "end"), { source: e51, points: r7, segments: s7, vias: a7, transitions: c5, width: h5, viaDiameter: e51.__postProcessingViaDiameter ?? h5, ...o7.start_pcb_port_id ? { startPortId: o7.start_pcb_port_id } : {}, ...i7.end_pcb_port_id ? { endPortId: i7.end_pcb_port_id } : {} };
};
var M6 = (e51) => e51.segments.reduce((e53, t4) => e53 + Math.hypot(t4.end.x - t4.start.x, t4.end.y - t4.start.y), 0);
var w6 = (e51) => {
  const { simpleRouteJson: t4 } = e51.params, n7 = ((e53) => {
    const t7 = new Set(e53.reroutedPairs.map((e54) => e54.connectionNames.join("\x00")));
    return e53.declaredPairs.filter((n8) => {
      const o8 = n8.connectionNames.map((t8) => e53.traces.filter((e54) => e54.connection_name === t8));
      if (o8.some((e54) => e54.length !== 1))
        return false;
      if (t7.has(n8.connectionNames.join("\x00")))
        return true;
      const i8 = o8.map((e54) => e54[0]);
      if (i8.some((e54) => e54.route.length < 2 || e54.route[0]?.route_type !== "wire" || !e54.route.every((e55) => e55.route_type === "wire" || e55.route_type === "via")))
        return false;
      const r8 = i8.map((t8) => M6(P6(t8, e53.layerCount)));
      return Math.abs(r8[0] - r8[1]) > n8.lengthTolerance + 0.0000001;
    }).map((e54) => structuredClone(e54));
  })({ traces: e51.result.traces, declaredPairs: t4.differentialPairs, reroutedPairs: e51.result.reroutedPairs, layerCount: t4.layerCount }), o7 = new Set(n7.flatMap((e53) => e53.connectionNames)), i7 = [], r7 = [], s7 = [], a7 = new Set;
  for (let n8 = 0;n8 < e51.result.traces.length; n8++) {
    const c7 = e51.result.traces[n8];
    if (!o7.has(c7.connection_name))
      continue;
    const l7 = c7.route.every((e53) => e53.route_type === "wire" || e53.route_type === "via"), h5 = c7.route[0]?.route_type === "wire";
    if (!l7 || !h5)
      throw new Error(`PostProcessingSolver: rerouted connection "${c7.connection_name}" cannot be bound to LengthMatchingSolver`);
    const d7 = P6(c7, t4.layerCount), u7 = c7.route[0];
    if (u7.route_type !== "wire")
      throw new Error(`PostProcessingSolver: trace "${c7.connection_name}" lost its first wire during binding`);
    const p7 = [{ x: u7.x, y: u7.y, z: G4(u7.layer, t4.layerCount), traceThickness: u7.width }], m7 = [], g7 = [];
    let { layer: f7, width: _5 } = u7;
    for (const e53 of c7.route.slice(1)) {
      if (e53.route_type === "wire") {
        if (e53.layer !== f7)
          throw new Error(`PostProcessingSolver: trace "${c7.connection_name}" changes layers without a via while binding`);
        p7.push({ x: e53.x, y: e53.y, z: G4(e53.layer, t4.layerCount), traceThickness: e53.width }), _5 = e53.width;
        continue;
      }
      if (e53.route_type !== "via")
        throw new Error(`PostProcessingSolver: trace "${c7.connection_name}" contains unsupported bound geometry`);
      const n9 = f7 === e53.from_layer ? e53.to_layer : f7 === e53.to_layer ? e53.from_layer : null;
      if (!n9)
        throw new Error(`PostProcessingSolver: trace "${c7.connection_name}" has a discontinuous bound via`);
      const o8 = p7.at(-1);
      Math.hypot(o8.x - e53.x, o8.y - e53.y) > 0.00000001 && p7.push({ x: e53.x, y: e53.y, z: G4(f7, t4.layerCount), traceThickness: _5 }), p7.push({ x: e53.x, y: e53.y, z: G4(n9, t4.layerCount), traceThickness: _5 }), m7.push({ x: e53.x, y: e53.y, zLayers: Z4(e53.from_layer, e53.to_layer, t4.layerCount).map((e54) => G4(e54, t4.layerCount)) }), g7.push({ ...e53 }), f7 = n9;
    }
    if (p7.length < 2)
      throw new Error(`PostProcessingSolver: trace "${c7.connection_name}" has no bound copper segments`);
    const y7 = Math.max(...p7.map((e53) => e53.traceThickness ?? d7.width)), b7 = d7.viaDiameter, x7 = i7.length;
    i7.push({ connectionName: c7.connection_name, traceThickness: y7, viaDiameter: b7, route: p7, vias: m7 });
    const v7 = p7[0], I6 = p7.at(-1);
    r7.push({ name: c7.connection_name, pointsToConnect: [{ x: v7.x, y: v7.y, layer: u7.layer, ...d7.startPortId ? { pcb_port_id: d7.startPortId } : {} }, { x: I6.x, y: I6.y, layer: d7.points.at(-1).layer, ...d7.endPortId ? { pcb_port_id: d7.endPortId } : {} }] }), s7.push({ traceIndex: n8, matchedRouteIndex: x7, viaTemplates: g7, startEndpoint: { ...v7 }, endEndpoint: { ...I6 }, ...d7.startPortId ? { startPortId: d7.startPortId } : {}, ...d7.endPortId ? { endPortId: d7.endPortId } : {} }), a7.add(c7.connection_name);
  }
  for (const e53 of o7)
    if (!a7.has(e53))
      throw new Error(`PostProcessingSolver: missing LengthMatchingSolver binding for rerouted connection "${e53}"`);
  const c5 = e51.result.traces.filter((e53) => !o7.has(e53.connection_name)), l5 = t4.minTraceToPadEdgeClearance ?? Math.max(0, ...i7.filter((e53) => e53.route.length >= 2).map((e53) => e53.traceThickness), ...c5.flatMap((e53) => q4(e53, t4.layerCount).segments.map((e54) => e54.width)));
  return { solverParams: { hdRoutes: i7, traces: c5, originalConnections: r7, differentialPairs: n7, obstacles: t4.obstacles, bounds: t4.bounds, layerCount: t4.layerCount, obstacleMargin: l5 }, traceBindings: s7, baseTraces: structuredClone(e51.result.traces) };
};
var N6 = (e51) => {
  const t4 = new Map;
  for (const n8 of e51.differentialPairs)
    for (const o8 of n8.connectionNames) {
      const n9 = e51.hdRoutes.map((e53, t7) => ({ route: e53, hdRouteIndex: t7 })).filter(({ route: e53 }) => e53.connectionName === o8);
      n9.length === 1 && t4.set(n9[0].hdRouteIndex, o8);
    }
  const n7 = e51.hdRoutes.map((t7, n8) => {
    const o8 = [], i8 = new Map;
    for (let e53 = 0;e53 < (t7.jumpers?.length ?? 0); e53++) {
      const n9 = t7.jumpers[e53], o9 = t7.route.map((e54, t8) => ({ point: e54, index: t8 })).filter(({ point: e54 }) => Math.hypot(e54.x - n9.start.x, e54.y - n9.start.y) <= 0.00000001).map(({ index: e54 }) => e54), r8 = t7.route.map((e54, t8) => ({ point: e54, index: t8 })).filter(({ point: e54 }) => Math.hypot(e54.x - n9.end.x, e54.y - n9.end.y) <= 0.00000001).map(({ index: e54 }) => e54), s8 = [...o9.flatMap((e54) => r8.filter((t8) => t8 > e54).map((t8) => ({ startIndex: e54, endIndex: t8 }))), ...r8.flatMap((e54) => o9.filter((t8) => t8 > e54).map((t8) => ({ startIndex: e54, endIndex: t8 })))];
      if (s8.length !== 1)
        throw new Error(`PostProcessingSolver: immutable HD route "${t7.connectionName}" has an ambiguous jumper traversal`);
      const a7 = s8[0];
      if (i8.has(a7.startIndex) || [...i8.values()].some(({ endIndex: e54 }) => a7.startIndex < e54 || a7.endIndex <= e54))
        throw new Error(`PostProcessingSolver: immutable HD route "${t7.connectionName}" has overlapping or unordered jumpers`);
      i8.set(a7.startIndex, { endIndex: a7.endIndex, jumperIndex: e53 });
    }
    if (t7.route.length > 0) {
      const n9 = t7.route[0];
      o8.push({ route_type: "wire", x: n9.x, y: n9.y, width: n9.traceThickness ?? t7.traceThickness, layer: U4(n9.z, e51.layerCount) });
      for (let n10 = 0;n10 < t7.route.length - 1; n10++) {
        const r9 = t7.route[n10], s9 = i8.get(n10);
        if (s9) {
          const i9 = t7.route[s9.endIndex], a9 = t7.jumpers[s9.jumperIndex];
          if (r9.z !== i9.z)
            throw new Error(`PostProcessingSolver: immutable HD route "${t7.connectionName}" changes layers through a jumper`);
          o8.push({ route_type: "jumper", start: { x: r9.x, y: r9.y }, end: { x: i9.x, y: i9.y }, footprint: a9.footprint, layer: U4(r9.z, e51.layerCount) }), o8.push({ route_type: "wire", x: i9.x, y: i9.y, width: i9.traceThickness ?? t7.traceThickness, layer: U4(i9.z, e51.layerCount) }), n10 = s9.endIndex - 1;
          continue;
        }
        const a8 = t7.route[n10 + 1], c5 = U4(r9.z, e51.layerCount), l5 = U4(a8.z, e51.layerCount);
        r9.z !== a8.z && (r9.toNextSegmentType === "through_obstacle" ? o8.push({ route_type: "through_obstacle", start: { x: r9.x, y: r9.y }, end: { x: a8.x, y: a8.y }, from_layer: c5, to_layer: l5, width: r9.traceThickness ?? t7.traceThickness }) : o8.push({ route_type: "via", x: a8.x, y: a8.y, from_layer: c5, to_layer: l5, via_diameter: t7.viaDiameter })), o8.push({ route_type: "wire", x: a8.x, y: a8.y, width: a8.traceThickness ?? t7.traceThickness, layer: l5 });
      }
      const r8 = o8.filter((e53) => e53.route_type === "wire"), s8 = t7.startPcbPortId ?? t7.route[0]?.pcb_port_id, a7 = t7.endPcbPortId ?? t7.route.at(-1)?.pcb_port_id;
      s8 && r8[0] && (r8[0].start_pcb_port_id = s8), a7 && r8.at(-1) && (r8.at(-1).end_pcb_port_id = a7);
    }
    return { type: "pcb_trace", pcb_trace_id: `post_processing_hd_route_${n8}`, connection_name: t7.connectionName, __postProcessingViaDiameter: t7.viaDiameter, route: o8 };
  }), o7 = new Set(n7.map((e53) => e53.connection_name));
  for (const [t7, i8] of (e51.traces ?? []).entries()) {
    let e53 = `post_processing_fixed_trace_${t7}`;
    for (;o7.has(e53); )
      e53 += "_";
    o7.add(e53), n7.push({ ...structuredClone(i8), connection_name: e53 });
  }
  const i7 = structuredClone(e51.obstacles), r7 = new Map, s7 = new Map;
  for (const e53 of i7)
    for (const t7 of e53.connectedTo) {
      let n8 = r7.get(t7);
      n8 || (n8 = new Set, r7.set(t7, n8)), n8.add(e53);
    }
  for (let n8 = 0;n8 < e51.hdRoutes.length; n8++) {
    const o8 = e51.hdRoutes[n8], i8 = new Set([o8.connectionName, o8.rootConnectionName, o8.startPcbPortId, o8.endPcbPortId, o8.route[0]?.pcb_port_id, o8.route.at(-1)?.pcb_port_id, t4.get(n8)].filter((e53) => e53 !== undefined)), a7 = new Set;
    for (const e53 of i8) {
      const t7 = r7.get(e53);
      if (t7)
        for (const e54 of t7)
          a7.add(e54);
    }
    for (const e53 of a7) {
      let t7 = s7.get(e53);
      t7 || (t7 = new Set(e53.connectedTo), s7.set(e53, t7), e53.connectedTo = [...t7]);
      for (const n9 of i8) {
        if (t7.has(n9))
          continue;
        t7.add(n9), e53.connectedTo.push(n9);
        let o9 = r7.get(n9);
        o9 || (o9 = new Set, r7.set(n9, o9)), o9.add(e53);
      }
    }
  }
  return { params: { simpleRouteJson: { traces: n7, differentialPairs: structuredClone(e51.differentialPairs), obstacles: i7, bounds: structuredClone(e51.bounds), layerCount: e51.layerCount, minTraceToPadEdgeClearance: e51.minTraceToPadEdgeClearance }, ...e51.routingGrid ? { routingGrid: structuredClone(e51.routingGrid) } : {} }, routeBindings: [...t4.entries()].map(([e53, t7]) => ({ hdRouteIndex: e53, traceIndex: e53, internalConnectionName: t7 })), sourceHdRoutes: structuredClone(e51.hdRoutes) };
};
function R6(e51) {
  const t4 = structuredClone(e51.model.sourceHdRoutes);
  for (const n7 of e51.model.routeBindings) {
    const o7 = e51.binding.traceBindings.find((e53) => e53.traceIndex === n7.traceIndex);
    if (!o7)
      continue;
    const i7 = e51.result.matchedHdRoutes[o7.matchedRouteIndex], r7 = t4[n7.hdRouteIndex];
    if (!i7 || !r7)
      throw new Error(`PostProcessingSolver: missing matched or source HD route for "${n7.internalConnectionName}"`);
    if (i7.connectionName !== n7.internalConnectionName)
      throw new Error(`PostProcessingSolver: matched HD binding changed "${n7.internalConnectionName}" to "${i7.connectionName}"`);
    const s7 = i7.route.map((e53) => ({ ...e53 })), a7 = (t7, o8) => {
      if (t7 && o8 && (o8.pcb_port_id && (t7.pcb_port_id = o8.pcb_port_id), o8.insideJumperPad && e51.rejectInsideJumperPad))
        throw new Error(`PostProcessingSolver: cannot restore jumper-pad metadata on rerouted connection "${n7.internalConnectionName}"`);
    };
    a7(s7[0], r7.route[0]), a7(s7.at(-1), r7.route.at(-1)), t4[n7.hdRouteIndex] = { ...r7, route: s7, vias: structuredClone(i7.vias) };
  }
  return { hdRoutes: t4, postProcessingErrors: [] };
}
var T6 = class extends Error {
  connectionNames;
  reason;
  constructor(e51) {
    super(`PostProcessingSolver: differential pair ${e51.connectionNames.join("/")} ${e51.message}`), this.name = "DifferentialPairRoutingError", this.connectionNames = [e51.connectionNames[0], e51.connectionNames[1]], this.reason = e51.reason;
  }
};
var E6 = class extends Error {
  connectionNames;
  reason;
  constructor(e51) {
    super(e51.message), this.name = "PostProcessingConstraintError", this.connectionNames = [...e51.connectionNames], this.reason = e51.reason;
  }
};
var A6 = class extends Error {
  reason = "grid-capacity-exhausted";
  constructor(e51) {
    super(e51), this.name = "PostProcessingGridCapacityError";
  }
};
var O6 = (e51) => {
  const t4 = 75000 * e51.simpleRouteJson.differentialPairs.length;
  if (!Number.isSafeInteger(t4))
    throw new Error("PostProcessingSolver: derived rerouting iteration bound exceeds the safe integer range");
  const n7 = Math.min(t4, 80000);
  return Math.max(1, n7);
};
var D6 = (e51) => structuredClone(e51);
var L6 = (e51, t4, n7) => {
  const o7 = (e53) => {
    const n8 = -(t4.ccwRotationDegrees ?? 0) * Math.PI / 180, o8 = e53.x - t4.center.x, i8 = e53.y - t4.center.y;
    return { x: o8 * Math.cos(n8) - i8 * Math.sin(n8), y: o8 * Math.sin(n8) + i8 * Math.cos(n8) };
  }, i7 = o7(e51.start), r7 = o7(e51.end), s7 = t4.width / 2 + n7, a7 = t4.height / 2 + n7;
  if (Math.abs(i7.x) <= s7 && Math.abs(i7.y) <= a7 || Math.abs(r7.x) <= s7 && Math.abs(r7.y) <= a7)
    return true;
  const c5 = [{ x: -s7, y: -a7 }, { x: s7, y: -a7 }, { x: s7, y: a7 }, { x: -s7, y: a7 }];
  return c5.some((e53, t7) => K4(i7, r7, e53, c5[(t7 + 1) % c5.length]) <= 0.0000001);
};
var z6 = (e51) => {
  const t4 = [], n7 = [];
  for (const o8 of e51.immutableTraces) {
    const i8 = q4(o8, e51.layerCount);
    t4.push(...i8.segments), n7.push(...i8.vias);
  }
  const o7 = Array.from({ length: e51.layerCount }, () => []);
  for (const n8 of t4) {
    const t7 = G4(n8.layer, e51.layerCount);
    o7[t7].push(n8);
  }
  const i7 = (e53, t7) => Math.hypot(e53.x - t7.x, e53.y - t7.y) <= 0.00000001, r7 = (e53, t7, n8) => {
    const o8 = n8.x - t7.x, i8 = n8.y - t7.y, r8 = o8 * o8 + i8 * i8, s8 = r8 === 0 ? 0 : Math.max(0, Math.min(1, ((e53.x - t7.x) * o8 + (e53.y - t7.y) * i8) / r8));
    return Math.hypot(e53.x - t7.x - o8 * s8, e53.y - t7.y - i8 * s8);
  }, s7 = (e53, t7, n8) => {
    const o8 = -(t7.ccwRotationDegrees ?? 0) * Math.PI / 180, i8 = e53.x - t7.center.x, r8 = e53.y - t7.center.y, s8 = i8 * Math.cos(o8) - r8 * Math.sin(o8), a8 = i8 * Math.sin(o8) + r8 * Math.cos(o8);
    return Math.abs(s8) <= t7.width / 2 + n8 && Math.abs(a8) <= t7.height / 2 + n8;
  }, a7 = (t7, n8) => {
    const o8 = G4(n8, e51.layerCount);
    return o6(t7, e51.layerCount).includes(o8);
  }, c5 = (t7, n8, o8) => {
    const i8 = ((t8, n9, o9) => {
      const i9 = Math.hypot(n9.x, n9.y);
      if (i9 <= 0.0000000001)
        throw new Error("PostProcessingSolver: cannot orient terminal fanout on a zero-length spine");
      const r9 = -n9.y / i9 * e51.side * e51.centerlineSpacing / 2, s8 = n9.x / i9 * e51.side * e51.centerlineSpacing / 2, a8 = o9 === "start" ? [e51.firstStartTerminal, e51.secondStartTerminal] : [e51.firstEndTerminal, e51.secondEndTerminal], c7 = [e51.firstWidth, e51.secondWidth], l7 = [e51.firstConnectionName, e51.secondConnectionName];
      return a8.map((e53, n10) => {
        const i10 = n10 === 0 ? 1 : -1, a9 = { x: t8.x + r9 * i10, y: t8.y + s8 * i10 };
        return { start: o9 === "start" ? e53 : a9, end: o9 === "start" ? a9 : e53, layer: t8.layer, width: c7[n10], connectionName: l7[n10], terminal: o9 };
      });
    })(t7, n8, o8), r8 = i8.map((e53) => o8 === "start" ? e53.end : e53.start);
    return i8.every(l5) && r8.every((n9, o9) => e51.obstacles.every((r9) => !a7(r9, t7.layer) || !s7(n9, r9, 1.5 * i8[o9].width + (e51.terminalMiterMargin ?? 0)))) && K4(i8[0].start, i8[0].end, i8[1].start, i8[1].end) >= i8[0].width / 2 + i8[1].width / 2 - 0.0000001;
  }, l5 = (t7) => {
    const i8 = t7.width / 2, c7 = i8 + (e51.minTraceToPadEdgeClearance ?? t7.width), l7 = G4(t7.layer, e51.layerCount), h7 = Math.min(t7.start.x, t7.end.x), d7 = Math.max(t7.start.x, t7.end.x), u7 = Math.min(t7.start.y, t7.end.y), p7 = Math.max(t7.start.y, t7.end.y);
    for (const n8 of [t7.start, t7.end])
      if (n8.x - i8 < e51.bounds.minX || n8.x + i8 > e51.bounds.maxX || n8.y - i8 < e51.bounds.minY || n8.y + i8 > e51.bounds.maxY)
        return false;
    for (const n8 of e51.obstacles) {
      if (!a7(n8, t7.layer))
        continue;
      const o8 = Math.hypot(n8.width / 2 + c7, n8.height / 2 + c7);
      if (d7 < n8.center.x - o8 || h7 > n8.center.x + o8 || p7 < n8.center.y - o8 || u7 > n8.center.y + o8)
        continue;
      const [i9, r8] = t7.connectionName === e51.firstConnectionName ? [e51.firstStartTerminal, e51.firstEndTerminal] : [e51.secondStartTerminal, e51.secondEndTerminal], l8 = s7(i9, n8, 0) && (s7(t7.start, n8, c7) || s7(t7.end, n8, c7)) && Math.hypot(t7.end.x - i9.x, t7.end.y - i9.y) >= Math.hypot(t7.start.x - i9.x, t7.start.y - i9.y), m7 = s7(r8, n8, 0) && (s7(t7.start, n8, c7) || s7(t7.end, n8, c7)) && Math.hypot(t7.end.x - r8.x, t7.end.y - r8.y) <= Math.hypot(t7.start.x - r8.x, t7.start.y - r8.y);
      if (!(n8.connectedTo.includes(t7.connectionName) && (l8 || m7)) && L6(t7, n8, c7))
        return false;
    }
    for (const e53 of o7[l7]) {
      const n8 = t7.width / 2 + e53.width / 2 + Math.max(t7.width, e53.width);
      if (!(d7 + n8 < Math.min(e53.start.x, e53.end.x) || h7 - n8 > Math.max(e53.start.x, e53.end.x) || p7 + n8 < Math.min(e53.start.y, e53.end.y) || u7 - n8 > Math.max(e53.start.y, e53.end.y)) && K4(t7.start, t7.end, e53.start, e53.end) < n8)
        return false;
    }
    for (const e53 of n7)
      if (e53.layers.includes(t7.layer) && r7(e53, t7.start, t7.end) < t7.width / 2 + e53.diameter / 2 + t7.width)
        return false;
    return true;
  }, h5 = (o8) => {
    const i8 = o8.diameter / 2;
    if (o8.x - i8 < e51.bounds.minX || o8.x + i8 > e51.bounds.maxX || o8.y - i8 < e51.bounds.minY || o8.y + i8 > e51.bounds.maxY)
      return false;
    for (const t7 of e51.obstacles) {
      if (!o8.layers.some((e53) => a7(t7, e53)))
        continue;
      if (!(o8.terminal !== null && t7.connectedTo.includes(o8.connectionName) && s7(o8, t7, 0)) && s7(o8, t7, i8 + o8.diameter))
        return false;
    }
    for (const e53 of t4) {
      if (!o8.layers.includes(e53.layer))
        continue;
      const t7 = i8 + e53.width / 2 + Math.max(o8.diameter, e53.width);
      if (r7(o8, e53.start, e53.end) < t7)
        return false;
    }
    for (const e53 of n7) {
      if (!e53.layers.some((e54) => o8.layers.includes(e54)))
        continue;
      const t7 = i8 + e53.diameter / 2 + Math.max(o8.diameter, e53.diameter);
      if (Math.hypot(o8.x - e53.x, o8.y - e53.y) < t7)
        return false;
    }
    return true;
  };
  return { isEdgeValid: (t7, n8) => {
    if (t7.layer !== n8.layer || !((t8, n9) => {
      const o9 = Math.hypot(n9.x - t8.x, n9.y - t8.y);
      if (o9 === 0)
        return [];
      const r8 = -(n9.y - t8.y) / o9 * e51.side * e51.centerlineSpacing / 2, s8 = (n9.x - t8.x) / o9 * e51.side * e51.centerlineSpacing / 2, a8 = i7(t8, e51.start), c7 = i7(n9, e51.end), l7 = e51.terminalFanout ? a8 && c7 ? "both" : a8 ? "start" : c7 ? "end" : null : null, h7 = a8 && e51.terminalFanout ? e51.firstStartTerminal : { x: t8.x + r8, y: t8.y + s8 }, d7 = c7 && e51.terminalFanout ? e51.firstEndTerminal : { x: n9.x + r8, y: n9.y + s8 }, u7 = a8 && e51.terminalFanout ? e51.secondStartTerminal : { x: t8.x - r8, y: t8.y - s8 }, p7 = c7 && e51.terminalFanout ? e51.secondEndTerminal : { x: n9.x - r8, y: n9.y - s8 };
      return [{ start: h7, end: d7, layer: t8.layer, width: e51.firstWidth, connectionName: e51.firstConnectionName, terminal: l7 }, { start: u7, end: p7, layer: t8.layer, width: e51.secondWidth, connectionName: e51.secondConnectionName, terminal: l7 }];
    })(t7, n8).every(l5))
      return false;
    if (e51.terminalFanout || e51.terminalMiterMargin === undefined)
      return true;
    const o8 = { x: n8.x - t7.x, y: n8.y - t7.y };
    return !(i7(t7, e51.start) && !c5(t7, o8, "start")) && !(i7(n8, e51.end) && !c5(n8, o8, "end"));
  }, isTerminalFanoutValid: c5, isViaValid: (t7, n8, o8) => {
    const r8 = Math.hypot(o8.x, o8.y);
    if (r8 <= 0.0000000001)
      throw new Error("PostProcessingSolver: cannot orient a coupled via on a zero-length spine");
    const s8 = Z4(t7.layer, n8, e51.layerCount), a8 = -o8.y / r8 * e51.side * e51.centerlineSpacing / 2, c7 = o8.x / r8 * e51.side * e51.centerlineSpacing / 2, l7 = i7(t7, e51.start) ? "start" : i7(t7, e51.end) ? "end" : null;
    return [{ x: t7.x + a8, y: t7.y + c7, layers: s8, diameter: e51.firstViaDiameter, connectionName: e51.firstConnectionName, terminal: l7 }, { x: t7.x - a8, y: t7.y - c7, layers: s8, diameter: e51.secondViaDiameter, connectionName: e51.secondConnectionName, terminal: l7 }].every(h5);
  } };
};
var B6 = (e51, t4, n7) => {
  const o7 = 0.0000001, i7 = (e53, t7) => {
    const n8 = -(t7.ccwRotationDegrees ?? 0) * Math.PI / 180, o8 = e53.x - t7.center.x, i8 = e53.y - t7.center.y;
    return { x: o8 * Math.cos(n8) - i8 * Math.sin(n8), y: o8 * Math.sin(n8) + i8 * Math.cos(n8) };
  }, r7 = (e53, t7, n8) => {
    const o8 = n8.x - t7.x, i8 = n8.y - t7.y, r8 = o8 * o8 + i8 * i8, s8 = r8 === 0 ? 0 : Math.max(0, Math.min(1, ((e53.x - t7.x) * o8 + (e53.y - t7.y) * i8) / r8));
    return Math.hypot(e53.x - (t7.x + s8 * o8), e53.y - (t7.y + s8 * i8));
  }, s7 = (e53, t7, n8) => {
    const o8 = G4(t7, n8);
    return o6(e53, n8).includes(o8);
  }, a7 = (e53, t7, n8) => {
    const a8 = e53.width / 2;
    if (e53.start.x - a8 < t7.bounds.minX - o7 || e53.start.x + a8 > t7.bounds.maxX + o7 || e53.start.y - a8 < t7.bounds.minY - o7 || e53.start.y + a8 > t7.bounds.maxY + o7 || e53.end.x - a8 < t7.bounds.minX - o7 || e53.end.x + a8 > t7.bounds.maxX + o7 || e53.end.y - a8 < t7.bounds.minY - o7 || e53.end.y + a8 > t7.bounds.maxY + o7)
      return false;
    for (const n9 of t7.obstacles) {
      if (!s7(n9, e53.layer, t7.layerCount))
        continue;
      const r8 = e53.terminal === "both" ? [e53.start, e53.end] : e53.terminal === "start" ? [e53.start] : e53.terminal === "end" ? [e53.end] : [];
      if (!(n9.connectedTo.includes(e53.connectionName) && r8.some((e54) => {
        const t8 = i7(e54, n9);
        return Math.abs(t8.x) <= n9.width / 2 + o7 && Math.abs(t8.y) <= n9.height / 2 + o7;
      })) && L6(e53, n9, a8 + (t7.minTraceToPadEdgeClearance ?? e53.width)))
        return false;
    }
    for (const t8 of n8.segments) {
      if (t8.layer !== e53.layer)
        continue;
      const n9 = e53.width / 2 + t8.width / 2 + Math.max(e53.width, t8.width);
      if (K4(e53.start, e53.end, t8.start, t8.end) < n9 - o7)
        return false;
    }
    for (const t8 of n8.vias) {
      if (!t8.layers.includes(e53.layer))
        continue;
      const n9 = e53.width / 2 + t8.diameter / 2 + e53.width;
      if (r7(t8, e53.start, e53.end) < n9 - o7)
        return false;
    }
    return true;
  }, c5 = (e53, t7, n8) => {
    const a8 = e53.diameter / 2;
    if (e53.x - a8 < t7.bounds.minX - o7 || e53.x + a8 > t7.bounds.maxX + o7 || e53.y - a8 < t7.bounds.minY - o7 || e53.y + a8 > t7.bounds.maxY + o7)
      return false;
    for (const n9 of t7.obstacles) {
      if (!e53.layers.some((e54) => s7(n9, e54, t7.layerCount)))
        continue;
      const r8 = i7(e53, n9);
      if (!(e53.terminal !== null && n9.connectedTo.includes(e53.connectionName) && Math.abs(r8.x) <= n9.width / 2 + o7 && Math.abs(r8.y) <= n9.height / 2 + o7) && Math.abs(r8.x) <= n9.width / 2 + a8 + e53.diameter && Math.abs(r8.y) <= n9.height / 2 + a8 + e53.diameter)
        return false;
    }
    for (const t8 of n8.segments) {
      if (!e53.layers.includes(t8.layer))
        continue;
      const n9 = a8 + t8.width / 2 + Math.max(e53.diameter, t8.width);
      if (r7(e53, t8.start, t8.end) < n9 - o7)
        return false;
    }
    for (const t8 of n8.vias) {
      if (!t8.layers.some((t9) => e53.layers.includes(t9)))
        continue;
      const n9 = a8 + t8.diameter / 2 + Math.max(e53.diameter, t8.diameter);
      if (Math.hypot(e53.x - t8.x, e53.y - t8.y) < n9 - o7)
        return false;
    }
    return true;
  }, l5 = (e53) => {
    for (let t7 = 0;t7 < e53.segments.length; t7++) {
      const n8 = e53.segments[t7];
      for (let i8 = t7 + 2;i8 < e53.segments.length; i8++) {
        const r8 = e53.segments[i8];
        if (n8.layer !== r8.layer)
          continue;
        if (!(e53.segments.slice(t7 + 1, i8).reduce((e54, t8) => e54 + Math.hypot(t8.end.x - t8.start.x, t8.end.y - t8.start.y), 0) <= n8.width + r8.width + o7) && K4(n8.start, n8.end, r8.start, r8.end) < n8.width / 2 + r8.width / 2 - o7)
          return true;
      }
    }
    for (const t7 of e53.vias)
      for (const n8 of e53.segments) {
        if (!t7.layers.includes(n8.layer))
          continue;
        if (!(Math.hypot(t7.x - n8.start.x, t7.y - n8.start.y) <= o7 || Math.hypot(t7.x - n8.end.x, t7.y - n8.end.y) <= o7) && r7(t7, n8.start, n8.end) < t7.diameter / 2 + n8.width / 2 - o7)
          return true;
      }
    return false;
  }, h5 = ((e53, t7) => {
    const n8 = [], o8 = [];
    for (const i8 of e53) {
      const e54 = q4(i8, t7);
      n8.push(...e54.segments), o8.push(...e54.vias);
    }
    return { segments: n8, vias: o8 };
  })(n7.immutableTraces, n7.layerCount);
  if (!((e53, t7) => {
    for (const n8 of e53.segments)
      for (const e54 of t7.segments) {
        if (n8.layer !== e54.layer)
          continue;
        const t8 = n8.width / 2 + e54.width / 2;
        if (K4(n8.start, n8.end, e54.start, e54.end) < t8 - o7)
          return false;
      }
    for (const [n8, i8] of [[e53.vias, t7.segments], [t7.vias, e53.segments]])
      for (const e54 of n8)
        for (const t8 of i8)
          if (e54.layers.includes(t8.layer) && r7(e54, t8.start, t8.end) < e54.diameter / 2 + t8.width / 2 - o7)
            return false;
    for (const n8 of e53.vias)
      for (const e54 of t7.vias)
        if (n8.layers.some((t8) => e54.layers.includes(t8)) && Math.hypot(n8.x - e54.x, n8.y - e54.y) < n8.diameter / 2 + e54.diameter / 2 - o7)
          return false;
    return true;
  })(e51, t4) || l5(e51) || l5(t4))
    return false;
  for (const o8 of [e51, t4])
    if (o8.segments.some((e53) => !a7(e53, n7, h5)) || o8.vias.some((e53) => !c5(e53, n7, h5)))
      return false;
  return true;
};
var F6 = [{ x: 1, y: 0 }, { x: 1, y: 1 }, { x: 0, y: 1 }, { x: -1, y: 1 }, { x: -1, y: 0 }, { x: -1, y: -1 }, { x: 0, y: -1 }, { x: 1, y: -1 }];
var j6 = class {
  constructor(e51) {
    this.input = e51;
    const { bounds: t4, grid: n7 } = e51, o7 = { minX: t4.minX + n7.outerPerimeterWidth, maxX: t4.maxX - n7.outerPerimeterWidth, minY: t4.minY + n7.outerPerimeterWidth, maxY: t4.maxY - n7.outerPerimeterWidth }, i7 = this.createAxis(t4.minX, t4.maxX, n7.outerGridStep, [o7.minX, o7.maxX]), r7 = this.createAxis(t4.minY, t4.maxY, n7.outerGridStep, [o7.minY, o7.maxY]), s7 = this.createAxis(o7.minX, o7.maxX, n7.innerGridStep, [], e51.start.x), a7 = this.createAxis(o7.minY, o7.maxY, n7.innerGridStep, [], e51.start.y), c5 = this.createGrid(i7, r7, (e53) => e53.x <= o7.minX || e53.x >= o7.maxX || e53.y <= o7.minY || e53.y >= o7.maxY), l5 = this.createGrid(s7, a7, () => true);
    this.connectLocalNeighbors(c5), this.connectLocalNeighbors(l5);
    for (const e53 of ["left", "right", "bottom", "top"])
      this.connectBoundaries(e53, c5, l5, o7);
    const h5 = this.nodes.map((e53, t7) => t7);
    this.connectEndpoint(e51.start, h5), this.connectEndpoint(e51.end, h5);
  }
  nodes = [];
  nodeIdByPoint = new Map;
  endpointNodeIdByPoint = new Map;
  getPlanarNeighbors(e51) {
    const t4 = this.endpointNodeIdByPoint.get(this.exactKeyFor(e51)) ?? this.nodeIdByPoint.get(this.keyFor(e51));
    if (t4 === undefined)
      throw new Error(`PostProcessingSolver: coupled path point (${e51.x}, ${e51.y}) is not on the composite grid`);
    return [...this.nodes[t4].neighborIds].map((t7) => ({ ...this.nodes[t7].point, layer: e51.layer }));
  }
  getNodeCount() {
    return this.nodes.length;
  }
  getSearchStateCountUpperBound(e51) {
    const t4 = this.nodes.reduce((e53, t7) => e53 + t7.neighborIds.size, 0) * e51 + 1;
    if (!Number.isSafeInteger(t4))
      throw new Error("PostProcessingSolver: composite-grid search-state bound exceeds the safe integer range");
    return t4;
  }
  createAxis(e51, t4, n7, o7, i7 = e51) {
    const r7 = [e51, t4, ...o7].map((e53) => ({ value: e53, fixed: true }));
    for (let o8 = Math.ceil((e51 - i7) / n7);i7 + o8 * n7 < t4 - 0.00000001; o8++)
      r7.push({ value: i7 + o8 * n7, fixed: false });
    r7.sort((e53, t7) => e53.value - t7.value || Number(t7.fixed) - Number(e53.fixed));
    const s7 = [];
    for (const e53 of r7) {
      const t7 = s7.at(-1);
      !t7 || Math.abs(e53.value - t7.value) > 0.00000001 ? s7.push(e53) : e53.fixed && !t7.fixed && (s7[s7.length - 1] = e53);
    }
    return s7.map((e53) => e53.value);
  }
  createGrid(e51, t4, n7) {
    return t4.map((t7) => e51.map((e53) => {
      const o7 = { x: e53, y: t7 };
      return n7(o7) ? this.addNode(o7) : null;
    }));
  }
  connectLocalNeighbors(e51) {
    for (let t4 = 0;t4 < e51.length; t4++)
      for (let n7 = 0;n7 < (e51[t4]?.length ?? 0); n7++) {
        const o7 = e51[t4][n7];
        if (o7 !== null)
          for (const i7 of F6) {
            const r7 = e51[t4 + i7.y]?.[n7 + i7.x];
            r7 != null && this.connect(o7, r7);
          }
      }
  }
  connectBoundaries(e51, t4, n7, o7) {
    const i7 = e51 === "left" ? o7.minX : e51 === "right" ? o7.maxX : e51 === "bottom" ? o7.minY : o7.maxY, r7 = e51 === "left" || e51 === "right", s7 = (e53) => Math.abs((r7 ? e53.x : e53.y) - i7) <= 0.00000001, a7 = (e53) => {
      const t7 = new Set;
      for (const n8 of e53)
        for (const e54 of n8)
          e54 !== null && s7(this.nodes[e54].point) && t7.add(e54);
      return [...t7].sort((e54, t8) => {
        const n8 = this.nodes[e54].point, o8 = this.nodes[t8].point;
        return (r7 ? n8.y - o8.y : n8.x - o8.x) || e54 - t8;
      });
    }, c5 = a7(t4), l5 = a7(n7);
    if (c5.length === 0 || l5.length === 0)
      throw new Error(`PostProcessingSolver: composite grid has no ${e51} boundary bridge candidates`);
    for (const e53 of c5)
      this.connect(e53, this.findNearestAlongBoundary(e53, l5, r7));
    for (const e53 of l5)
      this.connect(e53, this.findNearestAlongBoundary(e53, c5, r7));
  }
  findNearestAlongBoundary(e51, t4, n7) {
    const o7 = this.nodes[e51].point;
    let i7 = t4[0], r7 = Number.POSITIVE_INFINITY;
    for (const e53 of t4) {
      const t7 = this.nodes[e53].point, s7 = Math.abs(n7 ? o7.y - t7.y : o7.x - t7.x);
      (s7 < r7 - 0.00000001 || Math.abs(s7 - r7) <= 0.00000001 && e53 < i7) && (r7 = s7, i7 = e53);
    }
    return i7;
  }
  connectEndpoint(e51, t4) {
    const n7 = this.nodeIdByPoint.get(this.keyFor(e51)), o7 = n7 === undefined ? null : this.nodes[n7].point, i7 = o7?.x === e51.x && o7.y === e51.y ? n7 : this.nodes.push({ point: { x: e51.x, y: e51.y }, neighborIds: new Set }) - 1;
    this.endpointNodeIdByPoint.set(this.exactKeyFor(e51), i7);
    const r7 = (e53, n8) => {
      const o8 = this.nodes[e53].point, i8 = t4.filter((t7) => t7 !== e53).map((e54) => ({ nodeId: e54, distance: Math.hypot(this.nodes[e54].point.x - o8.x, this.nodes[e54].point.y - o8.y) })).filter(({ distance: e54 }) => e54 > 0.0000000001).sort((e54, t7) => e54.distance - t7.distance || e54.nodeId - t7.nodeId).slice(0, n8);
      if (i8.length === 0)
        throw new Error("PostProcessingSolver: composite grid has no endpoint connection candidates");
      for (const { nodeId: t7 } of i8)
        this.connect(e53, t7);
    };
    r7(i7, 8);
    for (const t7 of F6) {
      const n8 = { x: e51.x + t7.x * this.input.grid.innerGridStep, y: e51.y + t7.y * this.input.grid.innerGridStep };
      if (n8.x < this.input.bounds.minX || n8.x > this.input.bounds.maxX || n8.y < this.input.bounds.minY || n8.y > this.input.bounds.maxY)
        continue;
      const o8 = this.addNode(n8);
      this.connect(i7, o8), r7(o8, 4);
    }
  }
  addNode(e51) {
    const t4 = this.keyFor(e51), n7 = this.nodeIdByPoint.get(t4);
    if (n7 !== undefined)
      return n7;
    const o7 = this.nodes.length;
    return this.nodes.push({ point: { x: e51.x, y: e51.y }, neighborIds: new Set }), this.nodeIdByPoint.set(t4, o7), o7;
  }
  connect(e51, t4) {
    if (e51 === t4)
      return;
    const n7 = this.nodes[e51], o7 = this.nodes[t4];
    n7.neighborIds.add(t4), o7.neighborIds.add(e51);
  }
  keyFor(e51) {
    const t4 = Object.is(e51.x, -0) ? 0 : e51.x, n7 = Object.is(e51.y, -0) ? 0 : e51.y;
    return `${t4.toFixed(12)}:${n7.toFixed(12)}`;
  }
  exactKeyFor(e51) {
    return `${Object.is(e51.x, -0) ? 0 : e51.x}:${Object.is(e51.y, -0) ? 0 : e51.y}`;
  }
};
var $6 = class {
  constructor(e51) {
    if (this.input = e51, this.startLayer = G4(e51.start.layer, e51.layerCount), this.endLayer = G4(e51.end.layer, e51.layerCount), this.grid = new j6(e51), this.maxSearchStates = this.grid.getSearchStateCountUpperBound(e51.layerCount), this.exploredStateLimit = Math.min(this.maxSearchStates, 20000), this.startLayer < 0 || this.endLayer < 0)
      return this.queue = [], void (this.status = "exhausted");
    const t4 = { point: e51.start, direction: null, cost: 0, estimate: this.estimate(e51.start), parent: null, sequence: 0 };
    this.queue = [t4], this.bestCosts.set(this.keyFor(e51.start, null), 0);
  }
  queue;
  bestCosts = new Map;
  startLayer;
  endLayer;
  grid;
  maxSearchStates;
  exploredStateLimit;
  current = null;
  result = null;
  status = "searching";
  explored = 0;
  nextSequence = 1;
  isComplete() {
    return this.status !== "searching";
  }
  getPath() {
    return this.result;
  }
  getPreviewPath() {
    return this.current ? this.createPath(this.current) : [this.input.start];
  }
  getExploredCount() {
    return this.explored;
  }
  getProgress() {
    return this.status !== "searching" ? 1 : Math.min(0.99, this.explored / this.exploredStateLimit);
  }
  getGridNodeCount() {
    return this.grid.getNodeCount();
  }
  step() {
    if (this.status !== "searching")
      return;
    const e51 = this.popQueue();
    if (!e51)
      return void (this.status = "exhausted");
    const t4 = this.bestCosts.get(this.keyFor(e51.point, e51.direction));
    if (t4 === undefined)
      throw new Error("PostProcessingSolver: coupled path queue contains an untracked state");
    if (e51.cost > t4 + 0.0000000001)
      this.queue.length === 0 && (this.status = "exhausted");
    else {
      if (this.current = e51, this.explored++, this.explored > this.maxSearchStates)
        throw new Error(`PostProcessingSolver: coupled path search exceeded its ${this.maxSearchStates}-state graph invariant limit`);
      if (this.isEnd(e51.point)) {
        const t7 = this.createPath(e51);
        return t7[t7.length - 1] = this.input.end, this.result = this.simplifyPath(t7), void (this.status = "found");
      }
      this.explored >= this.exploredStateLimit ? this.status = "exhausted" : (this.enqueuePlanarNeighbors(e51), this.enqueueViaNeighbors(e51), this.queue.length === 0 && (this.status = "exhausted"));
    }
  }
  isEnd(e51) {
    return e51.layer === this.input.end.layer && e51.x === this.input.end.x && e51.y === this.input.end.y;
  }
  estimate(e51) {
    return Math.hypot(e51.x - this.input.end.x, e51.y - this.input.end.y) + 3 * Math.abs(G4(e51.layer, this.input.layerCount) - this.endLayer);
  }
  keyFor(e51, t4) {
    return `${Object.is(e51.x, -0) ? 0 : e51.x}:${Object.is(e51.y, -0) ? 0 : e51.y}:${e51.layer}:${t4?.key ?? "start"}`;
  }
  createDirection(e51, t4) {
    const n7 = t4.x - e51.x, o7 = t4.y - e51.y, i7 = Math.hypot(n7, o7);
    if (i7 <= 0.0000000001)
      throw new Error("PostProcessingSolver: composite grid produced a zero-length planar edge");
    const r7 = n7 / i7, s7 = o7 / i7;
    return { x: r7, y: s7, key: `${r7.toFixed(6)}:${s7.toFixed(6)}` };
  }
  createPath(e51) {
    const t4 = [];
    let n7 = e51;
    for (;n7; )
      t4.push(n7.point), n7 = n7.parent;
    return t4.reverse();
  }
  simplifyPath(e51) {
    return e51.filter((t4, n7) => {
      if (n7 === 0 || n7 === e51.length - 1)
        return true;
      const o7 = e51[n7 - 1], i7 = e51[n7 + 1], r7 = { x: t4.x - o7.x, y: t4.y - o7.y }, s7 = { x: i7.x - t4.x, y: i7.y - t4.y }, a7 = r7.x * s7.y - r7.y * s7.x, c5 = Math.hypot(r7.x, r7.y) * Math.hypot(s7.x, s7.y);
      return Math.abs(a7) > 0.0000000001 * c5 || t4.layer !== o7.layer || t4.layer !== i7.layer;
    });
  }
  hasHigherQueuePriority(e51, t4) {
    return e51.estimate !== t4.estimate ? e51.estimate < t4.estimate : e51.cost !== t4.cost ? e51.cost < t4.cost : e51.point.x !== t4.point.x ? e51.point.x < t4.point.x : e51.point.y !== t4.point.y ? e51.point.y < t4.point.y : e51.point.layer !== t4.point.layer ? e51.point.layer < t4.point.layer : e51.sequence < t4.sequence;
  }
  pushQueue(e51) {
    this.queue.push(e51);
    let t4 = this.queue.length - 1;
    for (;t4 > 0; ) {
      const n7 = Math.floor((t4 - 1) / 2), o7 = this.queue[n7];
      if (!this.hasHigherQueuePriority(e51, o7))
        break;
      this.queue[t4] = o7, t4 = n7;
    }
    this.queue[t4] = e51;
  }
  popQueue() {
    const e51 = this.queue[0], t4 = this.queue.pop();
    if (!e51 || !t4 || this.queue.length === 0)
      return e51;
    let n7 = 0;
    for (;; ) {
      const e53 = 2 * n7 + 1;
      if (e53 >= this.queue.length)
        break;
      const o7 = e53 + 1;
      let i7 = e53;
      o7 < this.queue.length && this.hasHigherQueuePriority(this.queue[o7], this.queue[e53]) && (i7 = o7);
      const r7 = this.queue[i7];
      if (!this.hasHigherQueuePriority(r7, t4))
        break;
      this.queue[n7] = r7, n7 = i7;
    }
    return this.queue[n7] = t4, e51;
  }
  enqueuePlanarNeighbors(e51) {
    for (const t4 of this.grid.getPlanarNeighbors(e51.point)) {
      if (!this.input.isEdgeValid(e51.point, t4))
        continue;
      const n7 = this.createDirection(e51.point, t4), o7 = e51.direction === null || e51.direction.key === n7.key ? 0 : 0.18, i7 = e51.cost + Math.hypot(t4.x - e51.point.x, t4.y - e51.point.y) + o7, r7 = this.keyFor(t4, n7);
      (this.bestCosts.get(r7) ?? Number.POSITIVE_INFINITY) <= i7 || (this.bestCosts.set(r7, i7), this.pushQueue({ point: t4, direction: n7, cost: i7, estimate: i7 + this.estimate(t4), parent: e51, sequence: this.nextSequence++ }));
    }
  }
  enqueueViaNeighbors(e51) {
    if (!e51.direction)
      return;
    const t4 = G4(e51.point.layer, this.input.layerCount);
    for (const n7 of [t4 - 1, t4 + 1]) {
      if (n7 < 0 || n7 >= this.input.layerCount)
        continue;
      const t7 = U4(n7, this.input.layerCount);
      if (!this.input.isViaValid(e51.point, t7, e51.direction))
        continue;
      const o7 = { ...e51.point, layer: t7 }, i7 = e51.cost + 4, r7 = this.keyFor(o7, e51.direction);
      (this.bestCosts.get(r7) ?? Number.POSITIVE_INFINITY) <= i7 || (this.bestCosts.set(r7, i7), this.pushQueue({ point: o7, direction: e51.direction, cost: i7, estimate: i7 + this.estimate(o7), parent: e51, sequence: this.nextSequence++ }));
    }
  }
};
var Y6 = (e51) => {
  const t4 = Math.min(e51.bounds.maxX - e51.bounds.minX, e51.bounds.maxY - e51.bounds.minY), n7 = e51.config?.innerGridStep ?? e51.defaultInnerGridStep, o7 = e51.config?.outerGridStep ?? 4 * n7, i7 = e51.config?.outerPerimeterWidth ?? Math.min(o7, t4 / 4);
  if (!Number.isFinite(n7) || n7 < 0.0001)
    throw new Error("PostProcessingSolver: routingGrid.innerGridStep must be finite and at least 0.0001");
  if (!Number.isFinite(o7) || o7 <= n7)
    throw new Error("PostProcessingSolver: routingGrid.outerGridStep must be finite and greater than innerGridStep");
  if (!Number.isFinite(i7) || i7 <= 0 || 2 * i7 >= t4)
    throw new Error("PostProcessingSolver: routingGrid.outerPerimeterWidth must be finite, positive, and less than half the smaller board extent");
  const r7 = e51.bounds.maxX - e51.bounds.minX, s7 = e51.bounds.maxY - e51.bounds.minY;
  if ((Math.ceil(r7 / o7) + 4) * (Math.ceil(s7 / o7) + 4) + (Math.ceil((r7 - 2 * i7) / n7) + 2) * (Math.ceil((s7 - 2 * i7) / n7) + 2) + 18 > 250000)
    throw new A6("PostProcessingSolver: valid input exceeds the 250000-node optimization grid capacity");
  return { innerGridStep: n7, outerGridStep: o7, outerPerimeterWidth: i7 };
};
var X6 = (e51) => {
  const t4 = -e51.pathDirection.y, n7 = e51.pathDirection.x, o7 = Math.tan(e51.maximumTurnDegrees * Math.PI / 180), i7 = Math.max(0, ...e51.lanes.map(({ point: i8, polarity: r8 }) => {
    const s8 = i8.x - e51.anchor.x, a8 = i8.y - e51.anchor.y, c5 = s8 * e51.escapeDirection.x + a8 * e51.escapeDirection.y, l5 = s8 * t4 + a8 * n7, h5 = r8 * e51.side * e51.centerlineSpacing / 2;
    return c5 + Math.abs(l5 - h5) / o7;
  })), r7 = e51.maxUncoupledLength ?? i7;
  if (i7 > r7 + 0.00000001)
    return null;
  const s7 = Math.max(0.05, Math.min(0.25, e51.searchStep / 2)), a7 = Math.max(1, Math.ceil((r7 - i7) / s7) + 1);
  for (let o8 = 0;o8 < a7; o8++) {
    const a8 = Math.min(r7, i7 + o8 * s7), c5 = { x: e51.anchor.x + e51.escapeDirection.x * a8, y: e51.anchor.y + e51.escapeDirection.y * a8, layer: e51.anchor.layer };
    if (e51.lanes.every(({ point: o9, polarity: i8 }) => {
      const r8 = i8 * e51.side * e51.centerlineSpacing / 2, s8 = c5.x + t4 * r8, a9 = c5.y + n7 * r8;
      return e51.maxUncoupledLength === undefined || Math.hypot(s8 - o9.x, a9 - o9.y) <= e51.maxUncoupledLength + 0.00000001;
    }) && e51.isValid(c5))
      return c5;
  }
  return null;
};
var H6 = [0.75, 0.5, 1, 0.25, 1.25];
var V6 = 100;
var W6 = class {
  constructor(e51) {
    this.input = e51, this.pairName = e51.pair.connectionNames.join("/"), this.prepared = this.prepare();
  }
  pairName;
  prepared;
  candidates = [];
  result = null;
  search = null;
  nextAttempt = 0;
  exploredNodeCount = 0;
  isComplete() {
    return this.result !== null;
  }
  getResult() {
    if (!this.result)
      throw new Error(`PostProcessingSolver: differential pair ${this.pairName} is not complete`);
    return this.result;
  }
  getPreviewPath() {
    return this.search?.getPreviewPath() ?? null;
  }
  getProgress() {
    if (this.result)
      return 1;
    const e51 = this.prepared.attempts.length, t4 = this.search?.getProgress() ?? 0;
    return Math.min(0.99, (this.nextAttempt + t4) / e51);
  }
  getStats() {
    return { phase: this.search ? "searching" : "candidate-selection", pair: this.pairName, attemptIndex: this.nextAttempt, attemptCount: this.prepared.attempts.length, exploredNodeCount: this.exploredNodeCount + (this.search?.getExploredCount() ?? 0), gridNodeCount: this.search?.getGridNodeCount() ?? 0, acceptedCandidateCount: this.candidates.length };
  }
  step() {
    if (this.result)
      return;
    const e51 = this.prepared;
    if (!this.search) {
      const t7 = e51.attempts[this.nextAttempt];
      return t7 ? void (this.search = new $6(t7.input)) : void this.complete();
    }
    if (this.search.step(), !this.search.isComplete())
      return;
    const t4 = this.search.getPath();
    this.exploredNodeCount += this.search.getExploredCount();
    const n7 = e51.attempts[this.nextAttempt];
    if (!n7)
      throw new Error(`PostProcessingSolver: differential pair ${this.pairName} lost its active attempt`);
    if (this.search = null, this.nextAttempt++, !t4)
      return;
    const o7 = ((e53) => {
      const t7 = (e54, t8) => Math.hypot(e54.x - t8.x, e54.y - t8.y) <= 0.00000001;
      if (e53.path.length < 2)
        throw new Error("PostProcessingSolver: coupled path has fewer than two stations");
      const n8 = (n9, o9) => {
        for (let i8 = n9 + o9;i8 >= 0 && i8 < e53.path.length; i8 += o9) {
          const o10 = e53.path[i8];
          if (!t7(o10, e53.path[n9]))
            return o10;
        }
        return null;
      }, o8 = (t8) => {
        const o9 = e53.path[t8], i8 = n8(t8, -1), r8 = n8(t8, 1), s8 = (e54, t9) => {
          const n9 = t9.x - e54.x, o10 = t9.y - e54.y, i9 = Math.hypot(n9, o10);
          if (i9 <= 0.0000000001)
            throw new Error("PostProcessingSolver: cannot offset a zero-length spine");
          return { x: -o10 / i9, y: n9 / i9 };
        }, a8 = e53.side * e53.centerlineSpacing / 2;
        if (!i8 || !r8) {
          const e54 = s8(i8 ?? o9, r8 ?? o9);
          return { x: e54.x * a8, y: e54.y * a8 };
        }
        if (e53.terminalFanout && t8 === 1)
          return s8(i8, o9);
        if (e53.terminalFanout && t8 === e53.path.length - 2)
          return s8(o9, r8);
        if (e53.terminalFanout && e53.path[t8 + 1]?.layer !== o9.layer)
          return s8(i8, o9);
        const c7 = s8(i8, o9), l7 = s8(o9, r8), h7 = { x: c7.x + l7.x, y: c7.y + l7.y }, d8 = Math.hypot(h7.x, h7.y);
        if (d8 <= 0.0000000001)
          return null;
        const u8 = h7.x / d8, p8 = h7.y / d8, m8 = a8 / (u8 * c7.x + p8 * c7.y);
        return { x: u8 * m8, y: p8 * m8 };
      }, i7 = e53.first.points[0], r7 = e53.first.points.at(-1), s7 = e53.reverseSecond ? e53.second.points.at(-1) : e53.second.points[0], a7 = e53.reverseSecond ? e53.second.points[0] : e53.second.points.at(-1), c5 = [[{ route_type: "wire", x: i7.x, y: i7.y, width: i7.width, layer: i7.layer }], [{ route_type: "wire", x: s7.x, y: s7.y, width: s7.width, layer: s7.layer }]], l5 = [e53.first.transitions[0], e53.second.transitions[0]];
      let h5 = 0;
      const d7 = e53.terminalFanout ? 1 : 0, u7 = e53.path.length - 2, p7 = e53.path[u7], m7 = e53.path[u7 - 1], g7 = e53.terminalFanout && p7?.layer === r7.layer && m7?.layer === p7.layer, f7 = e53.terminalFanout ? g7 ? u7 - 1 : e53.path.length - 1 : e53.path.length;
      for (let n9 = d7;n9 < f7; n9++) {
        const i8 = e53.path[n9], r8 = o8(n9);
        if (!r8)
          return null;
        for (const o9 of [0, 1]) {
          const s8 = o9 === 0 ? 1 : -1, a8 = { x: i8.x + r8.x * s8, y: i8.y + r8.y * s8 }, h7 = c5[o9], d8 = e53.path[n9 - 1];
          if (d8 && d8.layer !== i8.layer) {
            if (!t7(d8, i8))
              throw new Error("PostProcessingSolver: a coupled layer transition moved in the plane");
            const n10 = [...h7].reverse().find((e54) => e54.route_type === "wire");
            if (!n10)
              throw new Error("PostProcessingSolver: generated via has no preceding wire");
            const r9 = l5[o9];
            h7.push({ route_type: "via", x: n10.x, y: n10.y, from_layer: d8.layer, to_layer: i8.layer, via_diameter: r9?.via_diameter ?? (o9 === 0 ? e53.first.viaDiameter : e53.second.viaDiameter), ...r9?.via_hole_diameter !== undefined ? { via_hole_diameter: r9.via_hole_diameter } : {} }), h7.push({ route_type: "wire", x: n10.x, y: n10.y, width: o9 === 0 ? e53.first.width : e53.second.width, layer: i8.layer });
          } else {
            const n10 = h7.at(-1);
            n10?.route_type === "wire" && t7(n10, a8) && n10.layer === i8.layer || h7.push({ route_type: "wire", ...a8, width: o9 === 0 ? e53.first.width : e53.second.width, layer: i8.layer });
          }
        }
        e53.path[n9 - 1]?.layer !== i8.layer && n9 > 0 && h5++;
      }
      const _5 = (t8, n9) => {
        const o9 = t8.at(-1);
        if (!o9 || o9.route_type !== "wire")
          throw new Error("PostProcessingSolver: terminal fanout has no preceding wire");
        const i8 = t8.at(-2);
        let r8 = false;
        if (i8?.route_type === "wire" && i8.layer === o9.layer && o9.layer === n9.layer) {
          const e54 = { x: o9.x - i8.x, y: o9.y - i8.y }, t9 = { x: n9.x - o9.x, y: n9.y - o9.y }, s8 = Math.hypot(e54.x, e54.y), a8 = Math.hypot(t9.x, t9.y);
          if (s8 > 0.00000001 && a8 > 0.00000001 && Math.abs(e54.x * t9.x + e54.y * t9.y) <= 0.00000001) {
            const t10 = { x: o9.x - e54.x / s8 * a8, y: o9.y - e54.y / s8 * a8 };
            (t10.x - i8.x) * (e54.x / s8) + (t10.y - i8.y) * (e54.y / s8) > 0.00000001 && (o9.x = t10.x, o9.y = t10.y, r8 = true);
          }
        }
        e53.terminalFanout && !r8 && o9.x !== n9.x && o9.y !== n9.y && t8.push({ route_type: "wire", x: n9.x, y: o9.y, width: n9.width, layer: n9.layer }), t8.push({ route_type: "wire", x: n9.x, y: n9.y, width: n9.width, layer: n9.layer });
      };
      _5(c5[0], r7), _5(c5[1], a7), e53.reverseSecond && (c5[1] = c5[1].reverse().map((e54) => e54.route_type === "via" ? { ...e54, from_layer: e54.to_layer, to_layer: e54.from_layer } : e54));
      const y7 = (e54, t8) => {
        const n9 = e54.filter((e55) => e55.route_type === "wire");
        for (const e55 of n9)
          delete e55.start_pcb_port_id, delete e55.end_pcb_port_id;
        t8.startPortId && (n9[0].start_pcb_port_id = t8.startPortId), t8.endPortId && (n9.at(-1).end_pcb_port_id = t8.endPortId);
      };
      y7(c5[0], e53.first), y7(c5[1], e53.second);
      const b7 = { ...e53.first.source, route: c5[0] }, x7 = { ...e53.second.source, route: c5[1] };
      return { first: b7, second: x7, firstParsed: P6(b7, e53.layerCount), secondParsed: P6(x7, e53.layerCount), edgeGap: e53.edgeGap, centerlineDistance: e53.centerlineSpacing, bendCount: Math.max(0, e53.path.length - h5 - 2), viaPairCount: h5 };
    })({ first: e51.first, second: e51.second, reverseSecond: e51.reverseSecond, path: t4, centerlineSpacing: n7.edgeGap + e51.first.width / 2 + e51.second.width / 2, edgeGap: n7.edgeGap, side: n7.side, layerCount: this.input.layerCount, terminalFanout: e51.terminalFanout });
    o7 && B6(o7.firstParsed, o7.secondParsed, e51.context) && this.candidates.push(o7);
  }
  prepare() {
    const e51 = this.input.traces.map((e53, t7) => ({ trace: e53, index: t7 })).filter(({ trace: e53 }) => e53.connection_name === this.input.pair.connectionNames[0]), t4 = this.input.traces.map((e53, t7) => ({ trace: e53, index: t7 })).filter(({ trace: e53 }) => e53.connection_name === this.input.pair.connectionNames[1]);
    if (e51.length !== 1 || t4.length !== 1)
      throw new T6({ connectionNames: this.input.pair.connectionNames, reason: "trace-resolution-failure", message: "must resolve each connection_name to exactly one non-branching trace" });
    if (e51[0].index === t4[0].index)
      throw new T6({ connectionNames: this.input.pair.connectionNames, reason: "trace-resolution-failure", message: "resolved both members to one trace" });
    let n7, o7;
    try {
      n7 = P6(e51[0].trace, this.input.layerCount), o7 = P6(t4[0].trace, this.input.layerCount);
    } catch (e53) {
      throw new T6({ connectionNames: this.input.pair.connectionNames, reason: "invalid-routed-geometry", message: `has unsupported or invalid routed geometry: ${e53 instanceof Error ? e53.message : String(e53)}` });
    }
    const i7 = n7.points[0], r7 = n7.points.at(-1), s7 = Math.hypot(i7.x - o7.points[0].x, i7.y - o7.points[0].y) + Math.hypot(r7.x - o7.points.at(-1).x, r7.y - o7.points.at(-1).y), a7 = Math.hypot(i7.x - o7.points.at(-1).x, i7.y - o7.points.at(-1).y) + Math.hypot(r7.x - o7.points[0].x, r7.y - o7.points[0].y) + 0.00000001 < s7, c5 = a7 ? o7.points.at(-1) : o7.points[0], l5 = a7 ? o7.points[0] : o7.points.at(-1);
    if (i7.layer !== c5.layer || r7.layer !== l5.layer)
      throw new T6({ connectionNames: this.input.pair.connectionNames, reason: "terminal-layer-mismatch", message: "does not have common paired layers at both terminal stations" });
    const h5 = { x: (i7.x + c5.x) / 2, y: (i7.y + c5.y) / 2, layer: i7.layer }, d7 = { x: (r7.x + l5.x) / 2, y: (r7.y + l5.y) / 2, layer: r7.layer }, u7 = Math.hypot(d7.x - h5.x, d7.y - h5.y);
    if (u7 < 0.000001)
      throw new T6({ connectionNames: this.input.pair.connectionNames, reason: "coincident-terminal-midpoints", message: "has coincident terminal-pair midpoints" });
    const p7 = { x: -(d7.y - h5.y) / u7, y: (d7.x - h5.x) / u7 }, m7 = i7.x - c5.x, g7 = i7.y - c5.y, f7 = m7 * p7.x + g7 * p7.y >= 0 ? 1 : -1, _5 = (e53, t7) => {
      const n8 = e53.x - t7.x, o8 = e53.y - t7.y, i8 = Math.hypot(n8, o8);
      return i8 > 0.00000001 && Math.abs(n8 * p7.x + o8 * p7.y) / i8 < 0.5;
    }, y7 = _5(i7, c5) && _5(r7, l5), b7 = { x: p7.y, y: -p7.x }, x7 = [i7, c5].some((e53) => (e53.x - h5.x) * b7.x + (e53.y - h5.y) * b7.y > 0.00000001), v7 = { immutableTraces: this.input.traces.filter((n8, o8) => o8 !== e51[0].index && o8 !== t4[0].index), obstacles: this.input.obstacles, bounds: this.input.bounds, layerCount: this.input.layerCount, minTraceToPadEdgeClearance: this.input.minTraceToPadEdgeClearance }, I6 = ((e53) => {
      const { minimumCenterlineDistance: t7, maximumCenterlineDistance: n8 } = e53;
      if (t7 === undefined && n8 === undefined)
        return e53.legacyCenterlineDistances;
      const o8 = [...t7 !== undefined && n8 !== undefined ? [(t7 + n8) / 2, t7, n8, t7 - 0.25, n8 + 0.25] : t7 !== undefined ? [t7, t7 + 0.25, t7 + 0.5, t7 - 0.25, t7 + 1] : [n8, n8 - 0.25, n8 - 0.5, n8 + 0.25, n8 - 1], ...e53.legacyCenterlineDistances];
      return o8.filter((t8, n9) => t8 > e53.minimumPhysicalDistance && o8.findIndex((e54) => Math.abs(e54 - t8) < 0.00000001) === n9);
    })({ minimumCenterlineDistance: this.input.pair.minimumCenterlineDistance, maximumCenterlineDistance: this.input.pair.maximumCenterlineDistance, minimumPhysicalDistance: n7.width / 2 + o7.width / 2, legacyCenterlineDistances: H6.map((e53) => e53 + n7.width / 2 + o7.width / 2) }).flatMap((e53) => {
      const t7 = e53 - n7.width / 2 - o7.width / 2;
      return [f7, f7 === 1 ? -1 : 1].flatMap((s8) => {
        const a8 = Y6({ config: this.input.routingGrid, bounds: this.input.bounds, defaultInnerGridStep: Math.max(0.25, Math.min(0.5, e53 / 2)) }), u8 = (t8, a9) => z6({ ...v7, start: t8, end: a9, firstConnectionName: n7.source.connection_name, secondConnectionName: o7.source.connection_name, firstStartTerminal: i7, firstEndTerminal: r7, secondStartTerminal: c5, secondEndTerminal: l5, firstWidth: n7.width, secondWidth: o7.width, firstViaDiameter: n7.transitions[0]?.via_diameter ?? n7.viaDiameter, secondViaDiameter: o7.transitions[0]?.via_diameter ?? o7.viaDiameter, centerlineSpacing: e53, side: s8, terminalFanout: y7, terminalMiterMargin: this.input.pair.maxUncoupledLength === undefined ? undefined : e53 / 2 });
        let m8 = this.input.pair.maxUncoupledLength === undefined ? ((e54, t8) => {
          if (!x7 || y7)
            return h5;
          const n8 = [{ terminal: i7, offset: t8 * e54 / 2 }, { terminal: c5, offset: -t8 * e54 / 2 }], o8 = Math.tan(55 * Math.PI / 180), r8 = Math.max(...n8.map(({ terminal: e55, offset: t9 }) => {
            const n9 = (e55.x - h5.x) * b7.x + (e55.y - h5.y) * b7.y, i8 = (e55.x - h5.x) * p7.x + (e55.y - h5.y) * p7.y;
            return n9 + Math.abs(i8 - t9) / o8;
          }));
          return { x: h5.x + b7.x * r8, y: h5.y + b7.y * r8, layer: h5.layer };
        })(e53, s8) : h5, g8 = d7;
        if (!y7 && this.input.pair.maxUncoupledLength !== undefined) {
          const t8 = u8(h5, d7), n8 = X6({ anchor: h5, escapeDirection: b7, pathDirection: b7, centerlineSpacing: e53, side: s8, lanes: [{ point: i7, polarity: 1 }, { point: c5, polarity: -1 }], maxUncoupledLength: this.input.pair.maxUncoupledLength, maximumTurnDegrees: 55, searchStep: a8.innerGridStep, isValid: (e54) => t8.isTerminalFanoutValid(e54, b7, "start") }), o8 = X6({ anchor: d7, escapeDirection: { x: -b7.x, y: -b7.y }, pathDirection: b7, centerlineSpacing: e53, side: s8, lanes: [{ point: r7, polarity: 1 }, { point: l5, polarity: -1 }], maxUncoupledLength: this.input.pair.maxUncoupledLength, maximumTurnDegrees: 45, searchStep: a8.innerGridStep, isValid: (e54) => t8.isTerminalFanoutValid(e54, b7, "end") });
          if (!n8 || !o8)
            return [];
          m8 = n8, g8 = o8;
          if ((g8.x - m8.x) * b7.x + (g8.y - m8.y) * b7.y <= a8.innerGridStep)
            return [];
        }
        const f8 = u8(m8, g8);
        return [{ edgeGap: t7, side: s8, input: { start: m8, end: g8, bounds: this.input.bounds, layerCount: this.input.layerCount, grid: a8, ...f8 } }];
      });
    });
    return { first: n7, second: o7, reverseSecond: a7, terminalFanout: y7, context: v7, attempts: I6 };
  }
  complete() {
    if (this.candidates.length === 0)
      throw new T6({ connectionNames: this.input.pair.connectionNames, reason: "no-valid-candidate", message: "could not be improved without violating bounds, copper clearance, or coupled-via constraints" });
    this.candidates.sort((e51, t4) => this.score(e51) - this.score(t4) || e51.edgeGap - t4.edgeGap), this.result = { status: "accepted", candidate: this.candidates[0] };
  }
  score(e51) {
    return (this.input.pair.minimumCenterlineDistance !== undefined || this.input.pair.maximumCenterlineDistance !== undefined ? Math.max(0, (this.input.pair.minimumCenterlineDistance ?? Number.NEGATIVE_INFINITY) - e51.centerlineDistance) * V6 + Math.max(0, e51.centerlineDistance - (this.input.pair.maximumCenterlineDistance ?? Number.POSITIVE_INFINITY)) * V6 : e51.edgeGap < 0.5 ? (0.5 - e51.edgeGap) * V6 : e51.edgeGap > 1 ? (e51.edgeGap - 1) * V6 : 0) + M6(e51.firstParsed) + M6(e51.secondParsed) + 0.15 * e51.bendCount + 8 * e51.viaPairCount;
  }
};
var G6 = (e51) => {
  const t4 = { lines: [], points: [], rects: [], circles: [] };
  t4.rects.push({ center: { x: (e51.bounds.minX + e51.bounds.maxX) / 2, y: (e51.bounds.minY + e51.bounds.maxY) / 2 }, width: e51.bounds.maxX - e51.bounds.minX, height: e51.bounds.maxY - e51.bounds.minY, fill: "rgba(30, 70, 120, 0.04)", stroke: "rgba(30, 70, 120, 0.55)", layer: `z${Array.from({ length: e51.layerCount }, (e53, t7) => t7).join(",")}` });
  for (const n7 of e51.obstacles) {
    const o7 = o6(n7, e51.layerCount);
    t4.rects.push({ center: n7.center, width: n7.width, height: n7.height, ccwRotationDegrees: n7.ccwRotationDegrees, fill: "rgba(220, 60, 60, 0.16)", stroke: "rgba(190, 40, 40, 0.75)", layer: `z${o7.join(",")}` });
  }
  for (let n7 = 0;n7 < (e51.previewPath?.length ?? 0) - 1; n7++) {
    const o7 = e51.previewPath[n7], i7 = e51.previewPath[n7 + 1];
    if (o7.layer !== i7.layer)
      continue;
    const r7 = G4(o7.layer, e51.layerCount);
    t4.lines.push({ points: [o7, i7], strokeColor: "#16a34a", strokeWidth: 0.08, strokeDash: [0.18, 0.12], layer: `z${r7}` });
  }
  for (const n7 of e51.traces) {
    if (e51.activeConnectionNames?.includes(n7.connection_name))
      continue;
    const o7 = "#2563eb";
    let i7 = null;
    for (const r7 of n7.route)
      if (r7.route_type === "wire") {
        if (i7 && i7.layer === r7.layer) {
          const n8 = G4(r7.layer, e51.layerCount);
          t4.lines.push({ points: [i7, r7], strokeColor: o7, strokeWidth: Math.max(i7.width, r7.width), ...n8 === 0 ? {} : { strokeDash: [0.2, 0.16] }, layer: `z${n8}` });
        }
        i7 = r7;
      } else if (r7.route_type === "via") {
        const n8 = Z4(r7.from_layer, r7.to_layer, e51.layerCount).map((t7) => G4(t7, e51.layerCount));
        if (t4.circles.push({ center: r7, radius: (r7.via_diameter ?? i7?.width ?? 0.2) / 2, fill: "rgba(37, 99, 235, 0.45)", stroke: o7, layer: `z${n8.join(",")}` }), i7) {
          const e53 = i7.width;
          i7 = { x: r7.x, y: r7.y, layer: r7.to_layer, width: e53 };
        }
      }
  }
  return t4;
};
var U6 = class extends BaseSolver {
  constructor(e51) {
    super(), this.params = e51, this.outputTraces = D6(e51.simpleRouteJson.traces), this.MAX_ITERATIONS = O6(e51);
  }
  outputTraces;
  reroutedPairs = [];
  failures = [];
  nextPairIndex = 0;
  activeConnectionNames = null;
  activeSession = null;
  getSolverName() {
    return "DifferentialPairReroutingSolver";
  }
  _step() {
    const e51 = this.params.simpleRouteJson.differentialPairs[this.nextPairIndex];
    if (!e51)
      return void this.finish();
    this.activeConnectionNames = e51.connectionNames;
    try {
      if (!this.activeSession)
        return this.activeSession = new W6({ pair: e51, traces: this.outputTraces, obstacles: this.params.simpleRouteJson.obstacles, bounds: this.params.simpleRouteJson.bounds, layerCount: this.params.simpleRouteJson.layerCount, minTraceToPadEdgeClearance: this.params.simpleRouteJson.minTraceToPadEdgeClearance, routingGrid: this.params.routingGrid }), void (this.stats = this.activeSession.getStats());
      this.activeSession.step();
    } catch (t7) {
      if (!(t7 instanceof T6))
        throw t7;
      return void this.skipFailedPair(e51, t7);
    }
    if (this.stats = this.activeSession.getStats(), !this.activeSession.isComplete())
      return;
    const t4 = this.activeSession.getResult();
    this.activeSession = null;
    for (const e53 of [t4.candidate.first, t4.candidate.second]) {
      const t7 = this.outputTraces.findIndex((t8) => t8.connection_name === e53.connection_name);
      if (t7 < 0)
        throw new Error(`DifferentialPairReroutingSolver: accepted replacement for unknown connection "${e53.connection_name}"`);
      this.outputTraces[t7] = e53;
    }
    this.reroutedPairs.push(e51), this.nextPairIndex++, this.nextPairIndex !== this.params.simpleRouteJson.differentialPairs.length ? this.stats = { phase: "accepted", pair: e51.connectionNames.join("/"), pairIndex: this.nextPairIndex - 1, pairCount: this.params.simpleRouteJson.differentialPairs.length } : this.finish();
  }
  finish() {
    this.activeConnectionNames = null, this.solved = true, this.stats = { phase: "complete", acceptedPairCount: this.reroutedPairs.length, skippedPairCount: this.failures.length };
  }
  skipFailedPair(e51, t4) {
    this.failures.push({ connectionNames: [...e51.connectionNames], reason: t4.reason, message: t4.message }), this.activeSession = null, this.nextPairIndex++, this.nextPairIndex !== this.params.simpleRouteJson.differentialPairs.length ? this.stats = { phase: "skipped", pair: e51.connectionNames.join("/"), pairIndex: this.nextPairIndex - 1, pairCount: this.params.simpleRouteJson.differentialPairs.length, skippedPairCount: this.failures.length } : this.finish();
  }
  getConstructorParams() {
    return [this.params];
  }
  getOutput() {
    if (!this.solved)
      throw new Error("DifferentialPairReroutingSolver: getOutput() called before completion");
    return this.getBestEffortOutput();
  }
  getBestEffortOutput() {
    return { traces: D6(this.outputTraces), reroutedPairs: this.reroutedPairs.map((e51) => ({ ...e51, connectionNames: [...e51.connectionNames] })), failures: this.failures.map((e51) => ({ ...e51, connectionNames: [...e51.connectionNames] })) };
  }
  computeProgress() {
    return this.solved ? 1 : this.params.simpleRouteJson.differentialPairs.length === 0 ? 0 : (this.nextPairIndex + (this.activeSession?.getProgress() ?? 0)) / this.params.simpleRouteJson.differentialPairs.length;
  }
  visualize() {
    return G6({ traces: this.outputTraces, obstacles: this.params.simpleRouteJson.obstacles, bounds: this.params.simpleRouteJson.bounds, layerCount: this.params.simpleRouteJson.layerCount, activeConnectionNames: this.activeConnectionNames, previewPath: this.activeSession?.getPreviewPath() ?? null });
  }
};
var q6 = 0.00000001;
var J6 = class extends BaseSolver {
  constructor(e51) {
    super(), this.input = e51, this.traces = D6(e51.traces), this.MAX_ITERATIONS = Math.max(1, e51.reroutedPairs.length + 1);
  }
  traces;
  nextPairIndex = 0;
  getSolverName() {
    return "FortyFiveDegreeSimplificationSolver";
  }
  _step() {
    const e51 = this.input.reroutedPairs[this.nextPairIndex];
    if (!e51)
      return this.solved = true, void (this.stats = { phase: "complete", simplifiedPairCount: this.nextPairIndex });
    this.traces = ((e53) => {
      const t4 = e53.pair.connectionNames.join("/"), n7 = e53.pair.connectionNames.map((t7) => e53.traces.map((e54, t8) => ({ trace: e54, index: t8 })).filter(({ trace: e54 }) => e54.connection_name === t7));
      if (n7[0].length !== 1 || n7[1].length !== 1)
        throw new Error(`FortyFiveDegreeSimplificationSolver: pair ${t4} must resolve to exactly two traces`);
      const o7 = n7[0][0].index, i7 = n7[1][0].index;
      if (o7 === i7)
        throw new Error(`FortyFiveDegreeSimplificationSolver: pair ${t4} resolved both members to one trace`);
      const r7 = structuredClone(e53.traces), s7 = { immutableTraces: r7.filter((e54, t7) => t7 !== o7 && t7 !== i7), obstacles: e53.obstacles, bounds: e53.bounds, layerCount: e53.layerCount, minTraceToPadEdgeClearance: e53.minTraceToPadEdgeClearance }, a7 = (n8) => {
        const r8 = P6(n8[o7], e53.layerCount), s8 = P6(n8[i7], e53.layerCount);
        let a8 = 0;
        for (const [e54, n9] of [[r8.segments, s8.segments], [s8.segments, r8.segments]])
          for (const o8 of e54) {
            if (o8.terminal !== null)
              continue;
            const e55 = n9.filter((e56) => e56.layer === o8.layer);
            if (e55.length === 0)
              throw new Error(`FortyFiveDegreeSimplificationSolver: pair ${t4} lost common-layer interior copper`);
            a8 = Math.max(a8, Math.min(...e55.map((e56) => K4(o8.start, o8.end, e56.start, e56.end))));
          }
        return a8;
      }, c5 = (t7) => {
        const n8 = P6(t7[o7], e53.layerCount), r8 = P6(t7[i7], e53.layerCount);
        let s8 = Number.POSITIVE_INFINITY;
        for (const [e54, t8] of [[n8.segments, r8.segments], [r8.segments, n8.segments]])
          for (const n9 of e54)
            if (n9.terminal === null)
              for (const e55 of t8)
                e55.layer === n9.layer && (s8 = Math.min(s8, K4(n9.start, n9.end, e55.start, e55.end) - n9.width / 2 - e55.width / 2));
        return Number.isFinite(s8) ? s8 : null;
      }, l5 = (t7) => {
        const n8 = P6(t7[o7], e53.layerCount), r8 = P6(t7[i7], e53.layerCount);
        return B6(n8, r8, s7);
      };
      if (!l5(r7))
        throw new Error(`FortyFiveDegreeSimplificationSolver: rerouted pair ${t4} has invalid complete copper before simplification`);
      if (e53.pair.maxUncoupledLength !== undefined && e53.pair.minimumCenterlineDistance !== undefined && e53.pair.maximumCenterlineDistance !== undefined && Math.abs(e53.pair.minimumCenterlineDistance - e53.pair.maximumCenterlineDistance) <= q6)
        return r7;
      const h5 = P6(r7[o7], e53.layerCount), d7 = P6(r7[i7], e53.layerCount), u7 = Math.abs(M6(h5) - M6(d7)), p7 = c5(r7), m7 = e53.pair.maximumCenterlineDistance ?? 1 + h5.width / 2 + d7.width / 2, g7 = Math.min(a7(r7), m7), f7 = (e54) => {
        if (!l5(e54))
          return false;
        if (a7(e54) > g7 + q6)
          return false;
        const t7 = c5(e54);
        return p7 === null || t7 === null || t7 >= p7 - q6;
      }, _5 = (e54, t7) => {
        const n8 = Math.abs(t7.x - e54.x), o8 = Math.abs(t7.y - e54.y), i8 = t7.x >= e54.x ? 1 : -1, r8 = t7.y >= e54.y ? 1 : -1, s8 = [], a8 = { x: t7.x - i8 * o8, y: e54.y };
        (a8.x - e54.x) * i8 >= -0.00000001 && (a8.x - t7.x) * i8 <= q6 && s8.push([e54, a8, t7]);
        const c7 = { x: e54.x, y: t7.y - r8 * n8 };
        (c7.y - e54.y) * r8 >= -0.00000001 && (c7.y - t7.y) * r8 <= q6 && s8.push([e54, c7, t7]);
        const l7 = { x: e54.x + i8 * Math.min(n8, o8), y: e54.y + r8 * Math.min(n8, o8) };
        return s8.push([e54, l7, t7]), s8.map((e55, t8) => {
          const n9 = e55.filter((t9, n10) => n10 === 0 || Math.hypot(t9.x - e55[n10 - 1].x, t9.y - e55[n10 - 1].y) > q6), o9 = n9.slice(0, -1).map((e56, t9) => {
            const o10 = n9[t9 + 1], i9 = Math.abs(o10.x - e56.x), r9 = Math.abs(o10.y - e56.y);
            return { length: Math.hypot(i9, r9), straight: i9 <= q6 || r9 <= q6 ? Math.hypot(i9, r9) : 0 };
          });
          return { points: n9, usableStraightLength: Math.max(0, ...o9.map((e56) => e56.straight)), bendCount: Math.max(0, n9.length - 2), priority: t8 };
        }).filter((e55, t8, n9) => n9.findIndex((t9) => JSON.stringify(t9.points) === JSON.stringify(e55.points)) === t8).sort((e55, t8) => t8.usableStraightLength - e55.usableStraightLength || e55.bendCount - t8.bendCount || e55.priority - t8.priority);
      }, y7 = (e54) => {
        const t7 = [];
        for (let n8 = 0;n8 < e54.route.length - 1; n8++) {
          const o8 = e54.route[n8];
          if (o8?.route_type === "wire")
            for (let i8 = e54.route.length - 1;i8 >= n8 + 1; i8--) {
              if (n8 === 0 || i8 === e54.route.length - 1)
                continue;
              const r8 = e54.route[i8];
              r8?.route_type === "wire" && r8.layer === o8.layer && (e54.route.slice(n8 + 1, i8).some((e55) => e55.route_type !== "wire" || e55.layer !== o8.layer) || t7.push({ startIndex: n8, endIndex: i8, skippedPointCount: i8 - n8 - 1 }));
            }
        }
        return t7.sort((e55, t8) => t8.skippedPointCount - e55.skippedPointCount || e55.startIndex - t8.startIndex || t8.endIndex - e55.endIndex);
      }, b7 = (e54, t7, n8) => {
        const o8 = e54.route[t7.startIndex], i8 = e54.route[t7.endIndex], r8 = Math.max(o8.width, i8.width), s8 = n8.points.slice(1, -1).map((e55) => ({ route_type: "wire", ...e55, width: r8, layer: o8.layer }));
        return { ...e54, route: [...e54.route.slice(0, t7.startIndex + 1), ...s8, ...e54.route.slice(t7.endIndex)] };
      };
      for (const e54 of [o7, i7]) {
        let t7 = true;
        for (;t7; ) {
          t7 = false;
          const n8 = r7[e54];
          for (const s8 of y7(n8)) {
            const a8 = n8.route[s8.startIndex], c7 = n8.route[s8.endIndex], l7 = n8.route.slice(s8.startIndex, s8.endIndex + 1), h7 = l7.slice(0, -1).every((e55, t8) => {
              const n9 = l7[t8 + 1], o8 = Math.abs(n9.x - e55.x), i8 = Math.abs(n9.y - e55.y);
              return o8 <= q6 || i8 <= q6 || Math.abs(o8 - i8) <= q6;
            });
            for (const d8 of _5(a8, c7)) {
              if (d8.points.length >= l7.length && h7)
                continue;
              const a9 = b7(n8, s8, d8), c8 = [...r7];
              if (c8[e54] = a9, JSON.stringify(a9.route) === JSON.stringify(n8.route))
                continue;
              if (f7(c8)) {
                r7[e54] = a9, t7 = true;
                break;
              }
              const u8 = e54 === o7 ? i7 : o7, p8 = r7[u8], m8 = y7(p8).find((e55) => e55.startIndex === s8.startIndex && e55.endIndex === s8.endIndex);
              if (!m8)
                continue;
              const g8 = p8.route[m8.startIndex], x8 = p8.route[m8.endIndex];
              for (const n9 of _5(g8, x8)) {
                const o8 = b7(p8, m8, n9), i8 = [...c8];
                if (i8[u8] = o8, f7(i8)) {
                  r7[e54] = a9, r7[u8] = o8, t7 = true;
                  break;
                }
              }
              if (t7)
                break;
            }
            if (t7)
              break;
          }
        }
      }
      if (!f7(r7))
        throw new Error(`FortyFiveDegreeSimplificationSolver: pair ${t4} produced invalid complete copper`);
      const x7 = P6(r7[o7], e53.layerCount), v7 = P6(r7[i7], e53.layerCount), I6 = Math.abs(M6(x7) - M6(v7));
      return Math.abs(I6 - u7) > e53.pair.lengthTolerance + q6 ? structuredClone(e53.traces) : r7;
    })({ traces: this.traces, pair: e51, obstacles: this.input.obstacles, bounds: this.input.bounds, layerCount: this.input.layerCount, minTraceToPadEdgeClearance: this.input.minTraceToPadEdgeClearance }), this.nextPairIndex++, this.stats = { phase: "simplifying", pair: e51.connectionNames.join("/"), pairIndex: this.nextPairIndex - 1, pairCount: this.input.reroutedPairs.length };
  }
  getConstructorParams() {
    return [this.input];
  }
  getOutput() {
    if (!this.solved)
      throw new Error("FortyFiveDegreeSimplificationSolver: getOutput() called before completion");
    return this.getBestEffortOutput();
  }
  getBestEffortOutput() {
    return { traces: D6(this.traces), reroutedPairs: this.input.reroutedPairs.map((e51) => ({ ...e51, connectionNames: [...e51.connectionNames] })) };
  }
  computeProgress() {
    return this.solved ? 1 : this.input.reroutedPairs.length === 0 ? 0 : this.nextPairIndex / this.input.reroutedPairs.length;
  }
  visualize() {
    return G6({ traces: this.traces, obstacles: this.input.obstacles, bounds: this.input.bounds, layerCount: this.input.layerCount, activeConnectionNames: this.input.reroutedPairs[this.nextPairIndex]?.connectionNames ?? null, previewPath: null });
  }
};
var K6 = (e51, t4) => Math.abs(e51 - t4) <= 0.0000001;
var e92 = (e51, t4) => K6(e51.x, t4.x) && K6(e51.y, t4.y);
var t9 = (e51) => {
  const t4 = e51.candidatePair.map((t7, n7) => {
    const o7 = e51.originalPair[n7];
    return { ...t7, segments: t7.segments.filter((e53) => !o7.segments.some((t8) => {
      return o8 = e53, (n8 = t8).layer === o8.layer && !!K6(n8.width, o8.width) && !!e92(n8.start, o8.start) && !!e92(n8.end, o8.end);
      var n8, o8;
    })), vias: t7.vias.filter((e53) => !o7.vias.some((t8) => {
      return !!e92(n8 = t8, o8 = e53) && !!K6(n8.diameter, o8.diameter) && n8.layers.length === o8.layers.length && !!n8.layers.every((e54) => o8.layers.includes(e54));
      var n8, o8;
    })) };
  });
  return [t4[0], t4[1]];
};
var n9 = class extends BaseSolver {
  constructor(e51) {
    super(), this.input = e51;
  }
  output = null;
  visualizationTraces = null;
  getSolverName() {
    return "HdRouteReconstructionSolver";
  }
  _step() {
    this.visualizationTraces = ((e51) => {
      const { simpleRouteJson: t4 } = e51.params;
      if (e51.result.matchedHdRoutes.length !== e51.binding.solverParams.hdRoutes.length)
        throw new Error("PostProcessingSolver: LengthMatchingSolver changed the search route count");
      const n7 = structuredClone(e51.binding.baseTraces);
      for (const o7 of e51.binding.traceBindings) {
        const i7 = e51.result.matchedHdRoutes[o7.matchedRouteIndex];
        if (!i7)
          throw new Error(`PostProcessingSolver: missing matched route at index ${o7.matchedRouteIndex}`);
        const r7 = n7[o7.traceIndex];
        if (!r7)
          throw new Error(`PostProcessingSolver: missing simplified trace binding at index ${o7.traceIndex}`);
        if (r7.connection_name !== i7.connectionName)
          throw new Error(`PostProcessingSolver: route binding changed connection "${r7.connection_name}" to "${i7.connectionName}"`);
        if (i7.route.length < 2)
          throw new Error(`PostProcessingSolver: matched connection "${i7.connectionName}" has incomplete geometry`);
        const s7 = i7.route[0], a7 = i7.route.at(-1);
        if (Math.hypot(s7.x - o7.startEndpoint.x, s7.y - o7.startEndpoint.y) > 0.00000001 || s7.z !== o7.startEndpoint.z || Math.hypot(a7.x - o7.endEndpoint.x, a7.y - o7.endEndpoint.y) > 0.00000001 || a7.z !== o7.endEndpoint.z)
          throw new Error(`PostProcessingSolver: matched connection "${i7.connectionName}" moved a preserved endpoint`);
        const c5 = [];
        let l5 = 0;
        const h5 = (e53) => ({ route_type: "wire", x: e53.x, y: e53.y, width: e53.traceThickness ?? i7.traceThickness, layer: U4(e53.z, t4.layerCount) });
        c5.push(h5(i7.route[0]));
        for (let e53 = 1;e53 < i7.route.length; e53++) {
          const n8 = i7.route[e53 - 1], r8 = i7.route[e53];
          if (n8.z === r8.z) {
            c5.push(h5(r8));
            continue;
          }
          if (Math.hypot(n8.x - r8.x, n8.y - r8.y) > 0.00000001)
            throw new Error(`PostProcessingSolver: matched connection "${i7.connectionName}" moves while changing layers`);
          const s8 = o7.viaTemplates[l5++];
          if (!s8)
            throw new Error(`PostProcessingSolver: matched connection "${i7.connectionName}" added an unbound via`);
          if (Math.hypot(s8.x - r8.x, s8.y - r8.y) > 0.00000001)
            throw new Error(`PostProcessingSolver: matched connection "${i7.connectionName}" moved a preserved via`);
          const a8 = U4(n8.z, t4.layerCount), d8 = U4(r8.z, t4.layerCount), u7 = new Set([s8.from_layer, s8.to_layer]);
          if (!u7.has(a8) || !u7.has(d8))
            throw new Error(`PostProcessingSolver: matched connection "${i7.connectionName}" changed a preserved via span`);
          c5.push({ ...s8 }), c5.push(h5(r8));
        }
        if (l5 !== o7.viaTemplates.length)
          throw new Error(`PostProcessingSolver: matched connection "${i7.connectionName}" removed a preserved via`);
        const d7 = c5.filter((e53) => e53.route_type === "wire");
        for (const e53 of d7)
          delete e53.start_pcb_port_id, delete e53.end_pcb_port_id;
        o7.startPortId && (d7[0].start_pcb_port_id = o7.startPortId), o7.endPortId && (d7.at(-1).end_pcb_port_id = o7.endPortId), n7[o7.traceIndex] = { ...r7, route: c5 };
      }
      for (const o7 of e51.binding.solverParams.differentialPairs) {
        const i7 = o7.connectionNames.join("/"), r7 = o7.connectionNames.map((e53) => n7.map((e54, t7) => ({ trace: e54, index: t7 })).filter(({ trace: t7 }) => t7.connection_name === e53));
        if (r7[0].length !== 1 || r7[1].length !== 1)
          throw new Error(`PostProcessingSolver: reconstructed pair ${i7} does not resolve to complete copper`);
        const s7 = r7[0][0], a7 = r7[1][0], c5 = o7.connectionNames.map((t7) => {
          const n8 = e51.binding.baseTraces.filter((e53) => e53.connection_name === t7);
          if (n8.length !== 1)
            throw new Error(`PostProcessingSolver: original pair ${i7} does not resolve to complete copper`);
          return n8[0];
        }), l5 = P6(s7.trace, t4.layerCount), h5 = P6(a7.trace, t4.layerCount), d7 = P6(c5[0], t4.layerCount), u7 = P6(c5[1], t4.layerCount), p7 = Math.abs(M6(l5) - M6(h5));
        if (p7 > o7.lengthTolerance + 0.0000001)
          throw new E6({ message: `PostProcessingSolver: reconstructed pair ${i7} exceeds length tolerance ${o7.lengthTolerance} with error ${p7}`, connectionNames: [...o7.connectionNames], reason: "length-tolerance-unsatisfied" });
        const m7 = { immutableTraces: n7.filter((e53, t7) => t7 !== s7.index && t7 !== a7.index), obstacles: t4.obstacles, bounds: t4.bounds, layerCount: t4.layerCount, minTraceToPadEdgeClearance: t4.minTraceToPadEdgeClearance }, g7 = B6(l5, h5, { ...m7, obstacles: [] }), f7 = t9({ candidatePair: [l5, h5], originalPair: [d7, u7] }), _5 = B6(f7[0], f7[1], { ...m7, immutableTraces: [] });
        if (!g7 || !_5)
          throw new E6({ message: `PostProcessingSolver: length matching produced invalid complete copper for pair ${i7}`, connectionNames: [...o7.connectionNames], reason: "invalid-final-copper" });
      }
      return n7;
    })(this.input), this.output = R6({ ...this.input, rejectInsideJumperPad: true }), this.stats = { phase: "complete", routeCount: this.output.hdRoutes.length }, this.solved = true;
  }
  getConstructorParams() {
    return [this.input];
  }
  getOutput() {
    if (!this.output || !this.solved)
      throw new Error("HdRouteReconstructionSolver: getOutput() called before completion");
    return structuredClone(this.output);
  }
  visualize() {
    const e51 = this.visualizationTraces ?? this.input.simplified.traces, { obstacles: t4, bounds: n7, layerCount: o7 } = this.input.params.simpleRouteJson;
    return G6({ traces: e51, obstacles: t4, bounds: n7, layerCount: o7, activeConnectionNames: null, previewPath: null });
  }
};
var o9 = class extends BasePipelineSolver {
  differentialPairReroutingSolver;
  fortyFiveDegreeSimplificationSolver;
  lengthMatchingSolver;
  hdRouteReconstructionSolver;
  lengthMatchingBinding = null;
  model;
  fallbackOutput = null;
  postProcessingErrors = [];
  pipelineDef = [definePipelineStep("differentialPairReroutingSolver", U6, (e51) => [e51.model.params]), definePipelineStep("fortyFiveDegreeSimplificationSolver", J6, (e51) => {
    const t4 = e51.getStageOutput("differentialPairReroutingSolver");
    if (!t4)
      throw new Error("PostProcessingSolver: rerouting stage completed without output");
    const { obstacles: n7, bounds: o7, layerCount: i7, minTraceToPadEdgeClearance: r7 } = e51.model.params.simpleRouteJson;
    return [{ ...t4, obstacles: n7, bounds: o7, layerCount: i7, minTraceToPadEdgeClearance: r7 }];
  }), definePipelineStep("lengthMatchingSolver", v6, (e51) => {
    const t4 = e51.getStageOutput("fortyFiveDegreeSimplificationSolver");
    if (!t4)
      throw new Error("PostProcessingSolver: 45-degree simplification stage completed without output");
    return e51.lengthMatchingBinding = w6({ result: t4, params: e51.model.params }), [e51.lengthMatchingBinding.solverParams];
  }), definePipelineStep("hdRouteReconstructionSolver", n9, (e51) => {
    const t4 = e51.getStageOutput("fortyFiveDegreeSimplificationSolver"), n7 = e51.getStageOutput("lengthMatchingSolver");
    if (!t4 || !n7 || !e51.lengthMatchingBinding)
      throw new Error("PostProcessingSolver: reconstruction stage is missing a required binding or output");
    return [{ binding: e51.lengthMatchingBinding, result: n7, simplified: t4, params: e51.model.params, model: e51.model }];
  }, { onSolved: (e51) => {
    const t4 = e51.getStageOutput("differentialPairReroutingSolver");
    if (!t4)
      throw new Error("PostProcessingSolver: cannot summarize missing rerouting output");
    e51.stats = { phase: "complete", acceptedPairCount: t4.reroutedPairs.length }, t4.failures.length > 0 && (e51.stats.skippedPairCount = t4.failures.length, e51.stats.postProcessingErrorCount = t4.failures.length);
  } })];
  constructor(e51) {
    super(structuredClone(e51));
    let t4 = null;
    try {
      (function(e53) {
        if (!e53 || typeof e53 != "object")
          throw new Error("PostProcessingSolver: params must be an object");
        if (!Array.isArray(e53.hdRoutes))
          throw new Error("PostProcessingSolver: hdRoutes must be an array");
        if (!Array.isArray(e53.differentialPairs))
          throw new Error("PostProcessingSolver: differentialPairs must be an array");
        if (!Array.isArray(e53.obstacles))
          throw new Error("PostProcessingSolver: obstacles must be an array");
        if (e53.minTraceToPadEdgeClearance !== undefined && (!Number.isFinite(e53.minTraceToPadEdgeClearance) || e53.minTraceToPadEdgeClearance < 0))
          throw new Error("PostProcessingSolver: minTraceToPadEdgeClearance must be finite and nonnegative");
        if (!Number.isInteger(e53.layerCount) || e53.layerCount < 1)
          throw new Error("PostProcessingSolver: layerCount must be a positive integer");
        for (const t8 of e53.obstacles) {
          if (!t8 || typeof t8 != "object" || t8.type !== "rect" || !t8.center || !Number.isFinite(t8.center.x) || !Number.isFinite(t8.center.y) || !Number.isFinite(t8.width) || t8.width <= 0 || !Number.isFinite(t8.height) || t8.height <= 0 || !Array.isArray(t8.layers) || t8.layers.some((e54) => typeof e54 != "string") || !Array.isArray(t8.connectedTo) || t8.connectedTo.some((e54) => typeof e54 != "string" || e54.length === 0) || t8.ccwRotationDegrees !== undefined && !Number.isFinite(t8.ccwRotationDegrees))
            throw new Error("PostProcessingSolver: obstacle declaration is invalid");
          o6(t8, e53.layerCount);
        }
        const { minX: t7, maxX: n8, minY: o7, maxY: i7 } = e53.bounds ?? {};
        if (![t7, n8, o7, i7].every(Number.isFinite) || t7 >= n8 || o7 >= i7)
          throw new Error("PostProcessingSolver: bounds must have finite positive extents");
        const r7 = new Set(e53.differentialPairs.flatMap((e54) => e54.connectionNames));
        for (const t8 of e53.hdRoutes) {
          if (!t8 || typeof t8 != "object" || typeof t8.connectionName != "string" || t8.connectionName.length === 0 || t8.rootConnectionName !== undefined && (typeof t8.rootConnectionName != "string" || t8.rootConnectionName.length === 0) || !Number.isFinite(t8.traceThickness) || t8.traceThickness <= 0 || !Number.isFinite(t8.viaDiameter) || t8.viaDiameter < 0 || t8.viaDiameter === 0 && r7.has(t8.connectionName) || !Array.isArray(t8.route) || !Array.isArray(t8.vias) || t8.jumpers !== undefined && !Array.isArray(t8.jumpers))
            throw new Error("PostProcessingSolver: HD route declaration is invalid");
          if (t8.startPcbPortId !== undefined && (typeof t8.startPcbPortId != "string" || t8.startPcbPortId.length === 0) || t8.endPcbPortId !== undefined && (typeof t8.endPcbPortId != "string" || t8.endPcbPortId.length === 0))
            throw new Error(`PostProcessingSolver: HD route "${t8.connectionName}" has invalid terminal metadata`);
          for (const n10 of t8.route)
            if (!n10 || typeof n10 != "object" || !Number.isFinite(n10.x) || !Number.isFinite(n10.y) || !Number.isInteger(n10.z) || n10.z < 0 || n10.z >= e53.layerCount || n10.traceThickness !== undefined && (!Number.isFinite(n10.traceThickness) || n10.traceThickness <= 0))
              throw new Error(`PostProcessingSolver: HD route "${t8.connectionName}" has an invalid route point`);
          for (const n10 of t8.vias)
            if (!n10 || typeof n10 != "object" || !Number.isFinite(n10.x) || !Number.isFinite(n10.y) || n10.zLayers !== undefined && (!Array.isArray(n10.zLayers) || n10.zLayers.some((t10) => !Number.isInteger(t10) || t10 < 0 || t10 >= e53.layerCount)))
              throw new Error(`PostProcessingSolver: HD route "${t8.connectionName}" has an invalid via`);
          if (t8.vias.length > 0 && t8.viaDiameter <= 0)
            throw new Error(`PostProcessingSolver: HD route "${t8.connectionName}" has a non-positive via diameter`);
          for (const e54 of t8.jumpers ?? [])
            if (!(e54 && typeof e54 == "object" && e54.route_type === "jumper" && Number.isFinite(e54.start?.x) && Number.isFinite(e54.start?.y) && Number.isFinite(e54.end?.x) && Number.isFinite(e54.end?.y) && ["0603", "1206", "1206x4_pair"].includes(e54.footprint)))
              throw new Error(`PostProcessingSolver: HD route "${t8.connectionName}" has an invalid jumper`);
        }
        const s7 = new Set;
        for (const t8 of e53.differentialPairs) {
          if (!t8 || typeof t8 != "object" || !Array.isArray(t8.connectionNames) || t8.connectionNames.length !== 2 || t8.connectionNames[0] === t8.connectionNames[1] || !t8.connectionNames.every((e54) => typeof e54 == "string" && e54.length > 0) || !Number.isFinite(t8.lengthTolerance) || t8.lengthTolerance < 0)
            throw new Error("PostProcessingSolver: differential pair declaration is invalid");
          for (const e54 of [t8.minimumCenterlineDistance, t8.maximumCenterlineDistance])
            if (e54 !== undefined && (!Number.isFinite(e54) || e54 <= 0))
              throw new Error("PostProcessingSolver: differential pair centerline distances must be positive finite numbers");
          if (t8.maxUncoupledLength !== undefined && (!Number.isFinite(t8.maxUncoupledLength) || t8.maxUncoupledLength < 0))
            throw new Error("PostProcessingSolver: differential pair maxUncoupledLength must be a non-negative finite number");
          if (t8.minimumCenterlineDistance !== undefined && t8.maximumCenterlineDistance !== undefined && t8.minimumCenterlineDistance > t8.maximumCenterlineDistance)
            throw new Error("PostProcessingSolver: differential pair minimumCenterlineDistance cannot exceed maximumCenterlineDistance");
          for (const e54 of t8.connectionNames) {
            if (s7.has(e54))
              throw new Error(`PostProcessingSolver: connection "${e54}" belongs to multiple differential pairs`);
            s7.add(e54);
          }
        }
        for (const t8 of [0.25, 0.5])
          Y6({ config: e53.routingGrid, bounds: e53.bounds, defaultInnerGridStep: t8 });
      })(e51);
    } catch (e53) {
      if (!(e53 instanceof A6))
        throw e53;
      t4 = e53;
    }
    if (this.model = N6(e51), t4)
      return void this.finishWithBestEffortOutput({ stage: "differentialPairReroutingSolver", message: t4.message, reason: t4.reason });
    const n7 = O6(this.model.params) + Math.max(1, e51.differentialPairs.length + 1) + 1e5 + 10;
    if (!Number.isSafeInteger(n7))
      throw new Error("PostProcessingSolver: derived pipeline iteration bound exceeds the safe integer range");
    this.MAX_ITERATIONS = n7;
  }
  getSolverName() {
    return "PostProcessingSolver";
  }
  getConstructorParams() {
    return [structuredClone(this.inputProblem)];
  }
  _step() {
    const e51 = this.getCurrentStageName();
    try {
      super._step();
    } catch (t7) {
      const n7 = this.classifyOptimizationFailure(t7, e51);
      if (!n7)
        throw t7;
      return void this.finishWithBestEffortOutput(n7);
    }
    if (!this.failed)
      return;
    const t4 = this.classifyIterationFailure(this.error, e51);
    if (!t4)
      throw new Error(this.error ?? "PostProcessingSolver failed without an error message");
    this.finishWithBestEffortOutput(t4);
  }
  tryFinalAcceptance() {
    const e51 = this.getCurrentStageName();
    e51 !== "differentialPairReroutingSolver" && e51 !== "lengthMatchingSolver" || this.finishWithBestEffortOutput({ stage: e51, message: "PostProcessingSolver reached its iteration limit", reason: "iteration-limit-exhausted" });
  }
  classifyOptimizationFailure(e51, t4) {
    return t4 === "lengthMatchingSolver" && e51 instanceof m6 ? { stage: t4, message: e51.message, connectionName: e51.connectionName, reason: e51.reason } : t4 === "hdRouteReconstructionSolver" && e51 instanceof E6 || t4 === "differentialPairReroutingSolver" && e51 instanceof T6 && e51.reason === "no-valid-candidate" ? { stage: t4, message: e51.message, connectionNames: [...e51.connectionNames], reason: e51.reason } : null;
  }
  classifyIterationFailure(e51, t4) {
    return t4 !== "differentialPairReroutingSolver" && t4 !== "lengthMatchingSolver" ? null : e51 && e51.endsWith("ran out of iterations") ? { stage: t4, message: e51, reason: "iteration-limit-exhausted" } : null;
  }
  createBestEffortOutput(e51) {
    let t4 = this.lengthMatchingBinding;
    if (!t4) {
      const e53 = this.getStageOutput("fortyFiveDegreeSimplificationSolver") ?? this.fortyFiveDegreeSimplificationSolver?.getBestEffortOutput(), n8 = this.getStageOutput("differentialPairReroutingSolver") ?? this.differentialPairReroutingSolver?.getBestEffortOutput(), o7 = e53 ?? n8;
      o7 && (t4 = w6({ result: o7, params: this.model.params }));
    }
    if (!t4)
      return { output: { hdRoutes: structuredClone(this.inputProblem.hdRoutes), postProcessingErrors: [] }, source: "input-hd-routes" };
    let n7 = this.getStageOutput("lengthMatchingSolver");
    return n7 || (n7 = this.lengthMatchingSolver?.getBestEffortOutput()), n7 && e51.reason !== "invalid-final-copper" || (n7 = { matchedHdRoutes: t4.solverParams.hdRoutes }), { output: R6({ binding: t4, result: n7, model: this.model }), source: "best-effort-hd-routes" };
  }
  finishWithBestEffortOutput(e51) {
    const t4 = this.createBestEffortOutput(e51), n7 = { type: "post_processing_error", ...e51, returnedRouteSource: t4.source };
    this.postProcessingErrors.push(n7), this.fallbackOutput = t4.output, this.activeSubSolver = null, this.error = null, this.failed = false, this.solved = true, this.progress = 1, this.stats = { phase: "complete", postProcessingErrorCount: this.postProcessingErrors.length };
  }
  getOutput() {
    if (!this.solved)
      throw new Error("PostProcessingSolver: getOutput() called before the solver completed");
    const e51 = this.fallbackOutput ?? this.getStageOutput("hdRouteReconstructionSolver");
    if (!e51)
      throw new Error("PostProcessingSolver: completed pipeline is missing reconstruction output");
    const t4 = this.getStageOutput("differentialPairReroutingSolver") ?? this.differentialPairReroutingSolver?.getBestEffortOutput(), n7 = t4?.failures ?? [];
    let o7 = "input-hd-routes";
    (t4?.reroutedPairs.length ?? 0) > 0 && (o7 = "best-effort-hd-routes");
    const i7 = [...n7.map((e53) => ({ type: "post_processing_error", stage: "differentialPairReroutingSolver", message: e53.message, connectionNames: [...e53.connectionNames], reason: e53.reason, returnedRouteSource: o7 })), ...this.postProcessingErrors], r7 = structuredClone(e51);
    return r7.postProcessingErrors = structuredClone(i7), r7;
  }
  initialVisualize() {
    if (this.fallbackOutput)
      return { lines: this.fallbackOutput.hdRoutes.map((e53) => ({ points: e53.route.map(({ x: e54, y: t7 }) => ({ x: e54, y: t7 })), strokeWidth: e53.traceThickness })) };
    const { traces: e51, obstacles: t4, bounds: n7, layerCount: o7 } = this.model.params.simpleRouteJson;
    return G6({ traces: structuredClone(e51), obstacles: t4, bounds: n7, layerCount: o7, activeConnectionNames: null, previewPath: null });
  }
  finalVisualize() {
    if (this.fallbackOutput)
      return this.initialVisualize();
    const e51 = N6({ ...this.inputProblem, hdRoutes: this.getOutput().hdRoutes }), { traces: t4, obstacles: n7, bounds: o7, layerCount: i7 } = e51.params.simpleRouteJson;
    return G6({ traces: t4, obstacles: n7, bounds: o7, layerCount: i7, activeConnectionNames: null, previewPath: null });
  }
};
var l9 = class e51 {
  static generators = new Map;
  static register(t4) {
    e51.generators.set(t4.componentKind, t4);
  }
  static create(t4) {
    const n7 = t4.detectedComponent.componentKind, o7 = e51.generators.get(n7);
    if (!o7)
      throw new Error(`No topology generator registered for component kind "${n7}"`);
    return new o7(t4);
  }
};
var g9 = (e53) => [e53.obstacle.obstacleId ?? e53.obstacle.componentId ?? "obstacle", e53.start.x.toFixed(4), e53.start.y.toFixed(4), e53.end.x.toFixed(4), e53.end.y.toFixed(4), e53.expansionDirection.x, e53.expansionDirection.y].join(":");
var f9 = (e53) => {
  let t4 = 0;
  for (const n7 of e53)
    t4 = 31 * t4 + n7.charCodeAt(0) >>> 0;
  return t4;
};
var _9 = (e53, t4) => `hsla(${f9(g9(e53)) % 360},72%,36%,${t4})`;
var y9 = (e53) => {
  const t4 = e53.expansionDirection;
  return t4.x < 0 ? "left" : t4.x > 0 ? "right" : t4.y < 0 ? "bottom" : "top";
};
var b9 = (e53) => ({ x: (e53.start.x + e53.end.x) / 2, y: (e53.start.y + e53.end.y) / 2 });
var x9 = (e53) => {
  const t4 = /^bga-gapfill-(\d+)-/.exec(e53.capacityMeshNodeId);
  return t4 ? Number.parseInt(t4[1], 10) : null;
};
var v9 = (e53, t4) => {
  const n7 = b9(e53), o7 = b9(t4), i7 = n7.y - o7.y;
  if (Math.abs(i7) > 0.000001)
    return i7;
  const r7 = n7.x - o7.x;
  return Math.abs(r7) > 0.000001 ? r7 : g9(e53).localeCompare(g9(t4));
};
var I9 = (e53) => {
  const t4 = [...e53].sort(v9), n7 = [];
  let o7 = t4.shift();
  for (;o7 && (n7.push(o7), t4.length !== 0); ) {
    const e54 = b9(o7);
    let n8 = 0, i7 = Number.POSITIVE_INFINITY;
    for (let o8 = 0;o8 < t4.length; o8++) {
      const r7 = t4[o8], s7 = b9(r7), a7 = (s7.x - e54.x) ** 2 + (s7.y - e54.y) ** 2;
      a7 < i7 - 0.000000001 ? (i7 = a7, n8 = o8) : Math.abs(a7 - i7) <= 0.000000001 && v9(r7, t4[n8]) < 0 && (n8 = o8);
    }
    o7 = t4.splice(n8, 1)[0];
  }
  return n7;
};
var S9 = (e53, t4) => {
  const n7 = g9(e53), o7 = t4.findIndex((e54) => g9(e54) === n7);
  return o7 >= 0 ? `E${o7 + 1}` : `E${f9(n7).toString(36).slice(0, 4)}`;
};
var C9 = (e53) => e53.flatMap((e54) => {
  const t4 = Le(e54);
  return [{ obstacle: e54, start: { x: t4.minX, y: t4.minY }, end: { x: t4.minX, y: t4.maxY }, expansionDirection: { x: -1, y: 0 } }, { obstacle: e54, start: { x: t4.maxX, y: t4.minY }, end: { x: t4.maxX, y: t4.maxY }, expansionDirection: { x: 1, y: 0 } }, { obstacle: e54, start: { x: t4.minX, y: t4.minY }, end: { x: t4.maxX, y: t4.minY }, expansionDirection: { x: 0, y: -1 } }, { obstacle: e54, start: { x: t4.minX, y: t4.maxY }, end: { x: t4.maxX, y: t4.maxY }, expansionDirection: { x: 0, y: 1 } }];
});
var P9 = 0.001;
var M9 = 0.001;
var w9 = class extends BaseSolver {
  constructor(e53) {
    super(), this.inputProblem = e53;
  }
  meshIndex;
  allEdges = [];
  queueEdges = [];
  disconnectedEdges = [];
  currentEdge = null;
  lastSearchBounds = null;
  lastCandidateMeshNodes = [];
  lastMatchedMeshNode = null;
  _setup() {
    const e53 = Math.max(this.inputProblem.meshNodes.length, 1);
    this.meshIndex = new E2(e53);
    for (const e54 of this.inputProblem.meshNodes) {
      const t7 = Le(e54);
      this.meshIndex.add(t7.minX, t7.minY, t7.maxX, t7.maxY);
    }
    this.meshIndex.finish();
    const t4 = C9(this.inputProblem.unmarkedComponentObstacles);
    this.queueEdges = t4, this.allEdges = I9(t4), this.currentEdge = null, this.lastSearchBounds = null, this.lastCandidateMeshNodes = [], this.lastMatchedMeshNode = null;
  }
  _step() {
    const e53 = this.queueEdges.shift();
    if (!e53)
      return this.currentEdge = null, this.lastSearchBounds = null, this.lastCandidateMeshNodes = [], this.lastMatchedMeshNode = null, void (this.solved = true);
    this.currentEdge = e53, this.lastMatchedMeshNode = null;
    const t4 = Math.abs(e53.start.x - e53.end.x) <= P9, n7 = t4 ? { minX: e53.start.x - M9, maxX: e53.start.x + M9, minY: Math.min(e53.start.y, e53.end.y), maxY: Math.max(e53.start.y, e53.end.y) } : { minX: Math.min(e53.start.x, e53.end.x), maxX: Math.max(e53.start.x, e53.end.x), minY: e53.start.y - M9, maxY: e53.start.y + M9 };
    this.lastSearchBounds = n7;
    const o7 = this.meshIndex.search(n7.minX, n7.minY, n7.maxX, n7.maxY);
    this.lastCandidateMeshNodes = o7.map((e54) => this.inputProblem.meshNodes[e54]);
    let i7 = false;
    for (const n8 of o7) {
      const o8 = this.inputProblem.meshNodes[n8], r7 = Le(o8);
      if (t4) {
        if (!(Math.min(r7.maxY, Math.max(e53.start.y, e53.end.y)) - Math.max(r7.minY, Math.min(e53.start.y, e53.end.y)) > P9))
          continue;
        if (e53.expansionDirection.x === -1 && Math.abs(r7.maxX - e53.start.x) <= P9) {
          i7 = true, this.lastMatchedMeshNode = o8;
          break;
        }
        if (e53.expansionDirection.x === 1 && Math.abs(r7.minX - e53.start.x) <= P9) {
          i7 = true, this.lastMatchedMeshNode = o8;
          break;
        }
        continue;
      }
      if (Math.min(r7.maxX, Math.max(e53.start.x, e53.end.x)) - Math.max(r7.minX, Math.min(e53.start.x, e53.end.x)) > P9) {
        if (e53.expansionDirection.y === -1 && Math.abs(r7.maxY - e53.start.y) <= P9) {
          i7 = true, this.lastMatchedMeshNode = o8;
          break;
        }
        if (e53.expansionDirection.y === 1 && Math.abs(r7.minY - e53.start.y) <= P9) {
          i7 = true, this.lastMatchedMeshNode = o8;
          break;
        }
      }
    }
    i7 || this.disconnectedEdges.push(e53);
  }
  getOutput() {
    return this.disconnectedEdges;
  }
  visualize() {
    const e53 = this.disconnectedEdges, t4 = this.allEdges.length > 0 ? this.allEdges : [...e53, ...this.currentEdge ? [this.currentEdge] : []], n7 = this.currentEdge ? _9(this.currentEdge, 0.88) : "rgba(40,40,40,0.4)", o7 = this.inputProblem.meshNodes.map((e54) => ({ ...dj(e54, { rectMargin: 0.01 }), fill: e54._containsObstacle ? "rgba(120,120,120,0.18)" : "rgba(120,120,120,0.08)", stroke: e54._containsObstacle ? "rgba(120,120,120,0.42)" : "rgba(120,120,120,0.24)" })), i7 = this.lastSearchBounds && this.currentEdge ? [{ center: (r7 = this.lastSearchBounds, { x: (r7.minX + r7.maxX) / 2, y: (r7.minY + r7.maxY) / 2 }), width: this.lastSearchBounds.maxX - this.lastSearchBounds.minX, height: this.lastSearchBounds.maxY - this.lastSearchBounds.minY, fill: _9(this.currentEdge, 0.1), stroke: _9(this.currentEdge, 0.36), label: [S9(this.currentEdge, t4), "search band"].join(" ") }] : [];
    var r7;
    const s7 = this.lastCandidateMeshNodes.map((e54) => ({ ...dj(e54, { rectMargin: 0.018 }), fill: e54 === this.lastMatchedMeshNode ? "rgba(0,180,90,0.24)" : this.currentEdge ? _9(this.currentEdge, 0.16) : "rgba(80,120,160,0.16)", stroke: e54 === this.lastMatchedMeshNode ? "rgba(0,150,80,0.88)" : n7, label: [e54 === this.lastMatchedMeshNode ? "matched" : "candidate", e54.capacityMeshNodeId, `z:${e54.availableZ.join(",")}`].join(`
`) })), a7 = this.inputProblem.unmarkedComponentObstacles.map((e54) => ({ center: e54.center, width: e54.width, height: e54.height, fill: "rgba(160,160,160,0.10)", stroke: "rgba(160,160,160,0.40)", label: e54.obstacleId ?? e54.componentId ?? "obstacle" })), c5 = e53.map((e54) => ({ points: [e54.start, e54.end], strokeColor: _9(e54, 0.14), strokeWidth: 0.01, strokeDash: "5 4", label: [S9(e54, t4), y9(e54), "disconnected"].join(" ") })), l5 = [], h5 = [];
    if (this.currentEdge) {
      const e54 = b9(this.currentEdge);
      l5.push({ points: [this.currentEdge.start, this.currentEdge.end], strokeColor: _9(this.currentEdge, 1), strokeWidth: 0.06, label: [S9(this.currentEdge, t4), y9(this.currentEdge), "checking"].join(" ") }, { points: [e54, { x: e54.x + 0.16 * this.currentEdge.expansionDirection.x, y: e54.y + 0.16 * this.currentEdge.expansionDirection.y }], strokeColor: _9(this.currentEdge, 0.82), strokeWidth: 0.02, strokeDash: "3 3" }), h5.push({ ...e54, color: _9(this.currentEdge, 1), label: S9(this.currentEdge, t4) });
    }
    return { rects: [...o7, ...i7, ...s7, ...a7], lines: [...c5, ...l5], points: h5 };
  }
};
var R9 = 0.001;
var T9 = 0.001;
var E9 = 0.000001;
var A9 = class extends BaseSolver {
  constructor(e53) {
    super(), this.inputProblem = e53;
  }
  meshIndex;
  meshBounds;
  expandedNodes = [];
  _setup() {
    const e53 = Math.max(this.inputProblem.meshNodes.length, 1);
    this.meshIndex = new E2(e53);
    let { POSITIVE_INFINITY: t4, NEGATIVE_INFINITY: n7, POSITIVE_INFINITY: o7, NEGATIVE_INFINITY: i7 } = Number;
    for (const e54 of this.inputProblem.meshNodes) {
      const r7 = Le(e54);
      this.meshIndex.add(r7.minX, r7.minY, r7.maxX, r7.maxY), t4 = Math.min(t4, r7.minX), n7 = Math.max(n7, r7.maxX), o7 = Math.min(o7, r7.minY), i7 = Math.max(i7, r7.maxY);
    }
    this.meshIndex.finish(), this.meshBounds = this.inputProblem.meshNodes.length ? { minX: t4, maxX: n7, minY: o7, maxY: i7 } : { minX: 0, maxX: 0, minY: 0, maxY: 0 };
  }
  getObstacleAvailableZ(e53) {
    return e53.__zLayers ?? e53.layers.map((e54) => mo(e54, this.inputProblem.layerCount));
  }
  getSharedOverlapArea(e53, t4) {
    if (!e53.availableZ.some((e54) => t4.availableZ.includes(e54)))
      return 0;
    const n7 = Le(e53), o7 = Le(t4), i7 = Math.min(n7.maxX, o7.maxX) - Math.max(n7.minX, o7.minX), r7 = Math.min(n7.maxY, o7.maxY) - Math.max(n7.minY, o7.minY);
    return i7 <= E9 || r7 <= E9 ? 0 : i7 * r7;
  }
  getNodeObstacleOverlapArea(e53, t4) {
    const n7 = this.getObstacleAvailableZ(t4);
    if (!e53.availableZ.some((e54) => n7.includes(e54)))
      return 0;
    const o7 = Le(e53), i7 = Le(t4), r7 = Math.min(o7.maxX, i7.maxX) - Math.max(o7.minX, i7.minX), s7 = Math.min(o7.maxY, i7.maxY) - Math.max(o7.minY, i7.minY);
    return r7 <= E9 || s7 <= E9 ? 0 : r7 * s7;
  }
  getClosestMeshNode(e53, t4) {
    const n7 = Math.abs(e53.start.x - e53.end.x) <= R9, o7 = this.getObstacleAvailableZ(e53.obstacle), i7 = n7 ? e53.expansionDirection.x < 0 ? { minX: this.meshBounds.minX, maxX: e53.start.x, minY: Math.min(e53.start.y, e53.end.y) - T9, maxY: Math.max(e53.start.y, e53.end.y) + T9 } : { minX: e53.start.x, maxX: this.meshBounds.maxX, minY: Math.min(e53.start.y, e53.end.y) - T9, maxY: Math.max(e53.start.y, e53.end.y) + T9 } : e53.expansionDirection.y < 0 ? { minX: Math.min(e53.start.x, e53.end.x) - T9, maxX: Math.max(e53.start.x, e53.end.x) + T9, minY: this.meshBounds.minY, maxY: e53.start.y } : { minX: Math.min(e53.start.x, e53.end.x) - T9, maxX: Math.max(e53.start.x, e53.end.x) + T9, minY: e53.start.y, maxY: this.meshBounds.maxY }, r7 = this.meshIndex.search(i7.minX, i7.minY, i7.maxX, i7.maxY);
    let s7 = null, a7 = Number.POSITIVE_INFINITY;
    const c5 = [...r7.map((e54) => this.inputProblem.meshNodes[e54]), ...t4];
    for (const t7 of c5) {
      if (t7._containsObstacle)
        continue;
      if (!t7.availableZ.some((e54) => o7.includes(e54)))
        continue;
      const i8 = Le(t7);
      if ((n7 ? Math.min(Math.max(e53.start.y, e53.end.y), i8.maxY) - Math.max(Math.min(e53.start.y, e53.end.y), i8.minY) : Math.min(Math.max(e53.start.x, e53.end.x), i8.maxX) - Math.max(Math.min(e53.start.x, e53.end.x), i8.minX)) <= R9)
        continue;
      const r8 = n7 ? e53.expansionDirection.x < 0 ? e53.start.x - i8.maxX : i8.minX - e53.start.x : e53.expansionDirection.y < 0 ? e53.start.y - i8.maxY : i8.minY - e53.start.y;
      r8 < R9 || (r8 >= a7 || (a7 = r8, s7 = t7));
    }
    return s7;
  }
  createExpandedNode(e53, t4, n7) {
    const o7 = Le(t4), i7 = this.getObstacleAvailableZ(e53.obstacle);
    if (Math.abs(e53.start.x - e53.end.x) <= R9) {
      const r8 = Math.max(Math.min(e53.start.y, e53.end.y), o7.minY), s8 = Math.min(Math.max(e53.start.y, e53.end.y), o7.maxY), a8 = e53.expansionDirection.x < 0 ? o7.maxX : e53.start.x, c7 = e53.expansionDirection.x < 0 ? e53.start.x : o7.minX;
      return c7 - a8 <= R9 || s8 - r8 <= R9 ? null : { capacityMeshNodeId: `bga-gapfill-${n7}-${e53.obstacle.obstacleId ?? "no-obstacle"}-${t4.capacityMeshNodeId}`, center: { x: (a8 + c7) / 2, y: (r8 + s8) / 2 }, width: c7 - a8, height: s8 - r8, layer: `z${i7.join(",")}`, availableZ: i7 };
    }
    const r7 = Math.max(Math.min(e53.start.x, e53.end.x), o7.minX), s7 = Math.min(Math.max(e53.start.x, e53.end.x), o7.maxX), a7 = e53.expansionDirection.y < 0 ? o7.maxY : e53.start.y, c5 = e53.expansionDirection.y < 0 ? e53.start.y : o7.minY;
    return s7 - r7 <= R9 || c5 - a7 <= R9 ? null : { capacityMeshNodeId: `bga-gapfill-${n7}-${e53.obstacle.obstacleId ?? "no-obstacle"}-${t4.capacityMeshNodeId}`, center: { x: (r7 + s7) / 2, y: (a7 + c5) / 2 }, width: s7 - r7, height: c5 - a7, layer: `z${i7.join(",")}`, availableZ: i7 };
  }
  overlapsExistingGeometry(e53, t4) {
    for (const t7 of this.inputProblem.meshNodes)
      if (this.getSharedOverlapArea(e53, t7) > 0)
        return true;
    for (const n7 of t4)
      if (this.getSharedOverlapArea(e53, n7) > 0)
        return true;
    for (const t7 of this.inputProblem.edgesWithObstacle)
      if (this.getNodeObstacleOverlapArea(e53, t7.obstacle) > 0)
        return true;
    return false;
  }
  _step() {
    const e53 = [];
    for (const [t4, n7] of this.inputProblem.edgesWithObstacle.entries()) {
      const o7 = this.getClosestMeshNode(n7, e53);
      if (!o7)
        continue;
      const i7 = this.createExpandedNode(n7, o7, t4);
      i7 && (this.overlapsExistingGeometry(i7, e53) || e53.push(i7));
    }
    this.expandedNodes = e53, this.solved = true;
  }
  getOutput() {
    return this.expandedNodes;
  }
  visualize() {
    const e53 = this.inputProblem.edgesWithObstacle, t4 = I9(e53);
    return { rects: [...this.inputProblem.meshNodes.map((e54) => ({ ...dj(e54, { rectMargin: 0.01 }), fill: e54._containsObstacle ? "rgba(255,0,0,0.16)" : "rgba(0,120,255,0.08)", stroke: e54._containsObstacle ? "rgba(255,0,0,0.35)" : "rgba(0,120,255,0.28)" })), ...this.expandedNodes.map((n7) => {
      const o7 = x9(n7), i7 = o7 === null ? null : e53[o7] ?? null;
      return { ...dj(n7, { rectMargin: 0.012, zOffset: 0.01 }), fill: i7 ? _9(i7, 0.24) : "rgba(0,160,100,0.24)", stroke: i7 ? _9(i7, 0.72) : "rgba(0,160,100,0.68)", label: [i7 ? S9(i7, t4) : "E?", "expanded", n7.capacityMeshNodeId, `z:${n7.availableZ.join(",")}`].join(`
`) };
    })], lines: [...this.inputProblem.edgesWithObstacle.map((e54) => ({ points: [e54.start, e54.end], strokeColor: _9(e54, 0.9), strokeWidth: 0.034, label: [S9(e54, t4), y9(e54)].join(" ") })), ...this.inputProblem.edgesWithObstacle.map((e54) => {
      const t7 = b9(e54);
      return { points: [t7, { x: t7.x + 0.16 * e54.expansionDirection.x, y: t7.y + 0.16 * e54.expansionDirection.y }], strokeColor: _9(e54, 0.7), strokeWidth: 0.016, strokeDash: "3 3" };
    })], points: this.inputProblem.edgesWithObstacle.map((e54) => ({ ...b9(e54), color: _9(e54, 0.95), label: S9(e54, t4) })) };
  }
};
var O9 = 0.001;
var k9 = class extends BasePipelineSolver {
  constructor(e53) {
    super(e53), this.inputProblem = e53;
  }
  detectEdgesNotConnectedToMesh;
  expandUnconnectedEdgesToMesh;
  pipelineDef = [definePipelineStep("detectEdgesNotConnectedToMesh", w9, (e53) => [e53.inputProblem]), definePipelineStep("expandUnconnectedEdgesToMesh", A9, (e53) => [{ meshNodes: e53.inputProblem.meshNodes, edgesWithObstacle: e53.detectEdgesNotConnectedToMesh.getOutput(), layerCount: e53.inputProblem.layerCount }])];
  getOutput() {
    return [...this.inputProblem.meshNodes, ...this.expandUnconnectedEdgesToMesh.getOutput()];
  }
  getExpandedNodes() {
    return this.expandUnconnectedEdgesToMesh.getOutput();
  }
  getObstacleLayer(e53) {
    return `z${(e53.obstacle.__zLayers ?? e53.obstacle.layers.map((e54) => mo(e54, this.inputProblem.layerCount))).join(",")}`;
  }
  getObstacleRects() {
    return this.inputProblem.unmarkedComponentObstacles.map((e53) => {
      const t4 = e53.__zLayers ?? e53.layers.map((e54) => mo(e54, this.inputProblem.layerCount));
      return { center: e53.center, width: e53.width, height: e53.height, fill: "rgba(150,150,150,0.08)", stroke: "rgba(90,90,90,0.42)", label: e53.obstacleId ?? e53.componentId ?? "bga obstacle", layer: `z${t4.join(",")}` };
    });
  }
  getBaseMeshRects() {
    return this.inputProblem.meshNodes.map((e53) => ({ ...dj(e53, { rectMargin: 0.025, zOffset: 0.01 }), fill: e53._containsObstacle ? "rgba(210,60,60,0.14)" : "rgba(80,120,160,0.08)", stroke: e53._containsObstacle ? "rgba(190,40,40,0.42)" : "rgba(80,120,160,0.28)", label: `mesh ${e53.capacityMeshNodeId}
z:${e53.availableZ.join(",")}` }));
  }
  initialVisualize() {
    const e53 = C9(this.inputProblem.unmarkedComponentObstacles), t4 = I9(e53), n7 = [...e53.map((e54) => ({ points: [e54.start, e54.end], strokeColor: _9(e54, 0.72), strokeWidth: 0.018, strokeDash: "0.05 0.035", layer: this.getObstacleLayer(e54), label: [S9(e54, t4), y9(e54)].join(" ") })), ...e53.map((e54) => {
      const t7 = b9(e54);
      return { points: [t7, { x: t7.x + 0.18 * e54.expansionDirection.x, y: t7.y + 0.18 * e54.expansionDirection.y }], strokeColor: _9(e54, 0.64), strokeWidth: 0.012, strokeDash: "0.035 0.025", layer: this.getObstacleLayer(e54) };
    })];
    return { title: "BGA GapFill: candidate obstacle edges", rects: [...this.getBaseMeshRects(), ...this.getObstacleRects()], lines: n7 };
  }
  finalVisualize() {
    const e53 = this.getStageOutput("detectEdgesNotConnectedToMesh") ?? [], t4 = this.getStageOutput("expandUnconnectedEdgesToMesh") ?? [], n7 = I9(C9(this.inputProblem.unmarkedComponentObstacles)), o7 = new Map;
    for (const e54 of t4) {
      const t7 = x9(e54);
      t7 !== null && o7.set(t7, e54);
    }
    const i7 = t4.map((t7) => {
      const o8 = x9(t7), i8 = o8 === null ? null : e53[o8] ?? null, r8 = i8 ? (({ expandedNode: e54, edge: t8, meshNodes: n8 }) => {
        const o10 = Le(e54), i9 = Math.abs(t8.start.x - t8.end.x) <= O9;
        return n8.filter((n10) => {
          if (n10._containsObstacle)
            return false;
          if (!e54.availableZ.some((e55) => n10.availableZ.includes(e55)))
            return false;
          const r9 = Le(n10);
          return i9 ? !(Math.min(o10.maxY, r9.maxY) - Math.max(o10.minY, r9.minY) <= O9) && (t8.expansionDirection.x < 0 ? Math.abs(r9.maxX - o10.minX) <= O9 : Math.abs(r9.minX - o10.maxX) <= O9) : !(Math.min(o10.maxX, r9.maxX) - Math.max(o10.minX, r9.minX) <= O9) && (t8.expansionDirection.y < 0 ? Math.abs(r9.maxY - o10.minY) <= O9 : Math.abs(r9.minY - o10.maxY) <= O9);
        }).map((e55) => e55.capacityMeshNodeId);
      })({ expandedNode: t7, edge: i8, meshNodes: this.inputProblem.meshNodes }) : [], s8 = i8 ? S9(i8, n7) : "E?", a8 = i8 === null ? "rgba(0,160,100,0.72)" : _9(i8, 0.72);
      return { ...dj(t7, { rectMargin: 0.012, zOffset: 0.01 }), fill: i8 === null ? "rgba(0,160,100,0.24)" : _9(i8, 0.16), stroke: a8, label: [`${s8} gap fill`, r8.length > 0 ? `to ${r8.join(",")}` : "target mesh not adjacent", `z:${t7.availableZ.join(",")}`].join(`
`) };
    }), r7 = e53.map((e54, t7) => {
      const i8 = o7.get(t7);
      return { points: [e54.start, e54.end], strokeColor: i8 ? _9(e54, 0.68) : "rgba(80,80,80,0.14)", strokeWidth: i8 ? 0.026 : 0.008, ...i8 ? {} : { strokeDash: "5 4" }, layer: this.getObstacleLayer(e54), label: [[S9(e54, n7), y9(e54)].join(" "), i8 ? "filled" : "no fill created"].join(`
`) };
    }), s7 = e53.flatMap((e54, t7) => {
      const n8 = b9(e54), i8 = o7.get(t7);
      return i8 ? [{ points: [n8, i8.center], strokeColor: _9(e54, 0.42), strokeWidth: 0.012, strokeDash: "0.035 0.025", layer: this.getObstacleLayer(e54) }] : [];
    }), a7 = e53.flatMap((e54, t7) => o7.has(t7) ? [{ ...b9(e54), color: _9(e54, 0.82), label: S9(e54, n7), layer: this.getObstacleLayer(e54) }] : []);
    return { title: "BGA GapFill: disconnected edges and created mesh", rects: [...this.getBaseMeshRects(), ...this.getObstacleRects(), ...i7], lines: [...r7, ...s7], points: a7 };
  }
};
function L9(e53, t4) {
  const n7 = [];
  for (let o7 = 0;o7 < e53.length; o7++) {
    const i7 = e53[o7];
    n7.push(i7);
    const r7 = e53[o7 + 1];
    if (r7 === undefined)
      continue;
    const s7 = Math.round((r7 - i7) / t4);
    if (!(s7 <= 1))
      for (let e54 = 1;e54 < s7; e54++) {
        const t7 = e54 / s7;
        n7.push(Number((i7 + (r7 - i7) * t7).toFixed(6)));
      }
  }
  return n7;
}
var z9 = 0.001;
function B9(e53) {
  const t4 = [];
  for (let n8 = 1;n8 < e53.length; n8++) {
    const o8 = e53[n8] - e53[n8 - 1];
    o8 > z9 && t4.push(o8);
  }
  if (t4.length === 0)
    return null;
  const n7 = Math.min(...t4), o7 = t4.filter((e54) => e54 <= 1.5 * n7).sort((e54, t7) => e54 - t7), i7 = Math.floor(o7.length / 2);
  return o7.length % 2 == 0 ? (o7[i7 - 1] + o7[i7]) / 2 : o7[i7];
}
function F9(e53) {
  return [...new Set(e53)].sort((e54, t4) => e54 - t4);
}
function j9(e53) {
  return Number(e53.toFixed(6));
}
var $9 = class e53 {
  static fromObstacles(t4) {
    if (t4.length === 0)
      return null;
    const n7 = F9(t4.map((e54) => e54.center.x)), o7 = F9(t4.map((e54) => e54.center.y)), i7 = B9(n7), r7 = B9(o7);
    return i7 === null || r7 === null ? null : new e53({ obstacles: t4, xCoordinates: L9(n7, i7), yCoordinates: L9(o7, r7), pitchX: i7, pitchY: r7 });
  }
  xCoordinates;
  yCoordinates;
  pitchX;
  pitchY;
  originX;
  originY;
  rowCount;
  colCount;
  padWidth;
  padHeight;
  slots = new Map;
  constructor(e54) {
    this.xCoordinates = e54.xCoordinates, this.yCoordinates = e54.yCoordinates, this.pitchX = e54.pitchX, this.pitchY = e54.pitchY, this.originX = this.xCoordinates[0], this.originY = this.yCoordinates[0], this.colCount = this.xCoordinates.length, this.rowCount = this.yCoordinates.length, this.padWidth = e54.obstacles[0].width, this.padHeight = e54.obstacles[0].height;
    for (const t4 of e54.obstacles) {
      const e55 = this.getSlotForObstacle(t4);
      e55 && this.slots.set(this.getSlotKey(e55.row, e55.col), { ...e55, obstacle: t4 });
    }
  }
  getSlotKey(e54, t4) {
    return `${e54}:${t4}`;
  }
  getAxisIndex(e54, t4) {
    let n7 = -1, o7 = Number.POSITIVE_INFINITY;
    for (let i7 = 0;i7 < e54.length; i7++) {
      const r7 = Math.abs(e54[i7] - t4);
      r7 < o7 && (o7 = r7, n7 = i7);
    }
    return o7 <= z9 ? n7 : null;
  }
  getAxisCoordinate(e54, t4) {
    return e54[t4];
  }
  hasPadAt(e54, t4) {
    return this.slots.has(this.getSlotKey(e54, t4));
  }
  getSlotForObstacle(e54) {
    const t4 = this.getAxisIndex(this.yCoordinates, e54.center.y), n7 = this.getAxisIndex(this.xCoordinates, e54.center.x);
    return t4 === null || n7 === null || t4 < 0 || t4 >= this.rowCount || n7 < 0 || n7 >= this.colCount ? null : { row: t4, col: n7 };
  }
  getSlotCenter(e54, t4) {
    return { x: this.getAxisCoordinate(this.xCoordinates, t4), y: this.getAxisCoordinate(this.yCoordinates, e54) };
  }
  getHorizontalGap(e54, t4) {
    const n7 = this.getSlotCenter(e54, t4), o7 = this.getSlotCenter(e54, t4 + 1), i7 = Math.abs(o7.x - n7.x);
    return { orientation: "horizontal", row: e54, col: t4, center: { x: j9((n7.x + o7.x) / 2), y: n7.y }, width: i7 - this.padWidth, height: this.padHeight, isBetweenTwoPads: this.hasPadAt(e54, t4) && this.hasPadAt(e54, t4 + 1) };
  }
  getVerticalGap(e54, t4) {
    const n7 = this.getSlotCenter(e54, t4), o7 = this.getSlotCenter(e54 + 1, t4), i7 = Math.abs(o7.y - n7.y);
    return { orientation: "vertical", row: e54, col: t4, center: { x: n7.x, y: j9((n7.y + o7.y) / 2) }, width: this.padWidth, height: i7 - this.padHeight, isBetweenTwoPads: this.hasPadAt(e54, t4) && this.hasPadAt(e54 + 1, t4) };
  }
  getDiagonalGap(e54, t4) {
    const n7 = this.getSlotCenter(e54, t4), o7 = this.getSlotCenter(e54 + 1, t4 + 1), i7 = Math.abs(o7.x - n7.x), r7 = Math.abs(o7.y - n7.y);
    return { orientation: "diagonal", row: e54, col: t4, center: { x: j9((n7.x + o7.x) / 2), y: j9((n7.y + o7.y) / 2) }, width: i7 - this.padWidth, height: r7 - this.padHeight, isBetweenTwoPads: this.hasPadAt(e54, t4) && this.hasPadAt(e54 + 1, t4 + 1) };
  }
  getDiagonalGaps() {
    const e54 = [];
    for (let t4 = 0;t4 < this.rowCount - 1; t4++)
      for (let n7 = 0;n7 < this.colCount - 1; n7++)
        e54.push(this.getDiagonalGap(t4, n7));
    return e54.filter((e55) => e55.width > z9 && e55.height > z9);
  }
  getAxisGaps() {
    const e54 = [];
    for (let t4 = 0;t4 < this.rowCount; t4++)
      for (let n7 = 0;n7 < this.colCount - 1; n7++)
        e54.push(this.getHorizontalGap(t4, n7));
    for (let t4 = 0;t4 < this.rowCount - 1; t4++)
      for (let n7 = 0;n7 < this.colCount; n7++)
        e54.push(this.getVerticalGap(t4, n7));
    return e54.filter((e55) => e55.width > z9 && e55.height > z9);
  }
  getMissingSlots() {
    const e54 = [];
    for (let t4 = 0;t4 < this.rowCount; t4++)
      for (let n7 = 0;n7 < this.colCount; n7++)
        this.hasPadAt(t4, n7) || e54.push({ row: t4, col: n7, center: this.getSlotCenter(t4, n7), width: this.padWidth, height: this.padHeight });
    return e54;
  }
};
function Y9(e54) {
  if ([e54.point.pointId, e54.point.pcb_port_id].filter((e55) => typeof e55 == "string").some((t7) => e54.obstacle.connectedTo.includes(t7)))
    return true;
  if (e54.obstacle.connectedTo.length === 0)
    return false;
  if (Oe(e54.point, e54.obstacle) > 0.001)
    return false;
  const t4 = So(e54.point).map((t7) => mo(t7, e54.layerCount)), n7 = e54.obstacle.layers.map((t7) => mo(t7, e54.layerCount));
  return t4.some((e55) => n7.includes(e55));
}
function X9(e54) {
  return e54.obstacleId ?? [e54.componentId ?? "no-component", e54.center.x, e54.center.y, e54.width, e54.height, e54.layers.join(",")].join(":");
}
function H9({ componentId: e54, orientationKey: t4, row: n7, col: o7, center: i7, width: r7, height: s7 }) {
  return ["cmn", t4, e54, n7, o7, i7.x, i7.y, r7, s7].join("_");
}
function V9(e54) {
  const { componentId: t4, bgaGap: n7, freeLayers: o7, multiLayerThreshold: i7 } = e54, r7 = n7.width > i7 && n7.height > i7;
  let s7 = "d";
  n7.orientation === "horizontal" && (s7 = "h"), n7.orientation === "vertical" && (s7 = "v");
  const a7 = H9({ componentId: t4, orientationKey: s7, row: n7.row, col: n7.col, center: n7.center, width: n7.width, height: n7.height });
  return n7.orientation === "diagonal" && r7 || !n7.isBetweenTwoPads && r7 ? [{ center: n7.center, width: n7.width, height: n7.height, availableZ: [...o7], capacityMeshNodeId: `${a7}_all`, layer: "" }] : o7.map((e55) => ({ center: n7.center, width: n7.width, height: n7.height, availableZ: [e55], capacityMeshNodeId: `${a7}_${e55}`, layer: "" }));
}
function W9(e54) {
  const { componentId: t4, obstacle: n7, freeLayers: o7, layerCount: i7 } = e54, r7 = n7.layers.map((e55) => mo(e55, i7)), s7 = o7.filter((e55) => !r7.includes(e55)), a7 = X9(n7);
  return s7.map((e55) => ({ capacityMeshNodeId: `free-${t4}-${a7}-${e55}`, center: n7.center, width: n7.width, height: n7.height, layer: `z${e55}`, availableZ: [e55] }));
}
function G9(e54, t4, n7) {
  const o7 = t4.layers.map((e55) => mo(e55, n7.layerCount)), i7 = X9(t4), r7 = function(e55) {
    for (const t7 of e55.srj.connections)
      for (const n8 of t7.pointsToConnect)
        if (Y9({ point: n8, obstacle: e55.obstacle, layerCount: e55.srj.layerCount }))
          return t7.__rootConnectionNames?.[0] ?? t7.name;
  }({ obstacle: t4, srj: n7 });
  return { capacityMeshNodeId: `obstacle-${e54}-${i7}-${o7.join(",")}-${t4.center.x}-${t4.center.y}`, _containsObstacle: true, ...r7 ? { _containsTarget: true, _targetConnectionName: r7 } : {}, center: t4.center, width: t4.width, height: t4.height, layer: `z${o7.join(",")}`, availableZ: o7 };
}
var U9 = class extends BaseSolver {
  constructor(e54) {
    super(), this.inputProblem = e54;
  }
  componentObstacles = [];
  meshNodes = [];
  getConstructorParams() {
    return [this.inputProblem];
  }
  _step() {
    const { srj: e54, componentBounds: t4, componentId: n7, markedComponentObstacles: o7, unmarkedComponentObstacles: i7 } = this.inputProblem, r7 = e54.obstacles.filter((e55) => e55.isCopperPour === true).filter((e55) => De(Le(e55), t4)).flatMap((t7) => t7.layers.map((t8) => mo(t8, e54.layerCount))), s7 = Array.from({ length: e54.layerCount }, (e55, t7) => t7).filter((e55) => !r7.includes(e55));
    if (this.componentObstacles = o7, o7.length === 0 || s7.length === 0)
      return void (this.solved = true);
    const a7 = $9.fromObstacles(o7);
    if (!a7)
      return void (this.solved = true);
    const c5 = a7.getAxisGaps(), l5 = a7.getDiagonalGaps(), h5 = a7.getMissingSlots(), d7 = 1.2 * (this.inputProblem.viaDiameter ?? Yo(e54).padDiameter);
    this.meshNodes = [...c5.flatMap((e55) => V9({ componentId: n7, bgaGap: e55, freeLayers: s7, multiLayerThreshold: d7 })), ...l5.flatMap((e55) => V9({ componentId: n7, bgaGap: e55, freeLayers: s7, multiLayerThreshold: d7 })), ...h5.flatMap((e55) => function(e56) {
      const { componentId: t7, missingBgaSlot: n8, freeLayers: o8, multiLayerThreshold: i8 } = e56, r8 = H9({ componentId: t7, orientationKey: "missing", row: n8.row, col: n8.col, center: n8.center, width: n8.width, height: n8.height });
      return n8.width > i8 && n8.height > i8 ? [{ center: n8.center, width: n8.width, height: n8.height, availableZ: [...o8], capacityMeshNodeId: `${r8}_all`, layer: "" }] : o8.map((e57) => ({ center: n8.center, width: n8.width, height: n8.height, availableZ: [e57], capacityMeshNodeId: `${r8}_${e57}`, layer: "" }));
    }({ componentId: n7, missingBgaSlot: e55, freeLayers: s7, multiLayerThreshold: d7 })), ...o7.flatMap((t7) => [...W9({ componentId: n7, obstacle: t7, freeLayers: s7, layerCount: e54.layerCount }), G9(n7, t7, e54)]), ...i7.flatMap((t7) => [G9(n7, t7, e54)])], this.meshNodes = function(e55) {
      const t7 = new Map;
      return e55.map((e56) => {
        const n8 = t7.get(e56.capacityMeshNodeId) ?? 0;
        return t7.set(e56.capacityMeshNodeId, n8 + 1), n8 === 0 ? e56 : { ...e56, capacityMeshNodeId: `${e56.capacityMeshNodeId}__dup${n8}` };
      });
    }(this.meshNodes), this.solved = true;
  }
  getOutput() {
    return this.meshNodes;
  }
  visualize() {
    return { rects: [{ center: { x: (this.inputProblem.componentBounds.minX + this.inputProblem.componentBounds.maxX) / 2, y: (this.inputProblem.componentBounds.minY + this.inputProblem.componentBounds.maxY) / 2 }, width: this.inputProblem.componentBounds.maxX - this.inputProblem.componentBounds.minX, height: this.inputProblem.componentBounds.maxY - this.inputProblem.componentBounds.minY, fill: "rgba(0,0,0,0)", stroke: "rgba(30,30,30,0.65)", label: `component ${this.inputProblem.componentId}` }, ...this.inputProblem.markedComponentObstacles.map((e54) => ({ center: e54.center, width: e54.width, height: e54.height, fill: "rgba(255,0,0,0.18)", stroke: "rgba(255,0,0,0.52)", label: `pad ${e54.obstacleId ?? "obstacle"}` })), ...this.inputProblem.unmarkedComponentObstacles.map((e54) => ({ center: e54.center, width: e54.width, height: e54.height, fill: "rgba(255,140,0,0.14)", stroke: "rgba(255,140,0,0.42)", label: `foreign ${e54.obstacleId ?? "obstacle"}` })), ...this.meshNodes.map((e54) => ({ ...dj(e54, { rectMargin: 0.01 }), fill: e54._containsObstacle ? "rgba(255,0,0,0.14)" : e54.capacityMeshNodeId.includes("missing") ? "rgba(0,200,120,0.18)" : "rgba(0,120,255,0.12)", stroke: e54._containsObstacle ? "rgba(255,0,0,0.36)" : e54.capacityMeshNodeId.includes("missing") ? "rgba(0,200,120,0.52)" : "rgba(0,120,255,0.38)" }))] };
  }
};
function q9(e54) {
  return e54.capacityMeshNodeId.startsWith("bga-gapfill-");
}
function J9(e54) {
  return JSON.stringify({ availableZ: [...e54.availableZ].sort((e55, t4) => e55 - t4), _containsTarget: e54._containsTarget ?? false, _targetConnectionName: e54._targetConnectionName ?? null, _depth: e54._depth ?? null, _strawNode: e54._strawNode ?? false, _strawParentCapacityMeshNodeId: e54._strawParentCapacityMeshNodeId ?? null, _qfpRegionType: e54._qfpRegionType ?? null, _isNarrowQfpPadGap: e54._isNarrowQfpPadGap ?? false, _soicRegionType: e54._soicRegionType ?? null, _offBoardConnectionId: e54._offBoardConnectionId ?? null, _offboardNetName: e54._offboardNetName ?? null, _isVirtualOffboard: e54._isVirtualOffboard ?? false, _containsObstacle: e54._containsObstacle ?? false });
}
function Q9(e54, t4) {
  const n7 = Le(e54);
  for (const o7 of t4) {
    if (!e54.availableZ.some((e55) => o7.availableZ.includes(e55)))
      continue;
    const t7 = Le(o7);
    if (De(n7, t7))
      return true;
  }
  return false;
}
function K9(e54) {
  const t4 = e54[0];
  if (!t4)
    throw new Error("createMergedNode requires at least one source node");
  let { POSITIVE_INFINITY: n7, NEGATIVE_INFINITY: o7, POSITIVE_INFINITY: i7, NEGATIVE_INFINITY: r7 } = Number;
  for (const t7 of e54) {
    const e55 = Le(t7);
    n7 = Math.min(n7, e55.minX), o7 = Math.max(o7, e55.maxX), i7 = Math.min(i7, e55.minY), r7 = Math.max(r7, e55.maxY);
  }
  return { ...t4, capacityMeshNodeId: `merge:${e54.map((e55) => e55.capacityMeshNodeId).join(":")}`, center: { x: (n7 + o7) / 2, y: (i7 + r7) / 2 }, width: o7 - n7, height: r7 - i7 };
}
function e82(e54, t4, n7) {
  return { center: e54.center, width: e54.width, height: e54.height, fill: t4, stroke: t4, label: n7 };
}
var t8 = class extends BaseSolver {
  constructor(e54) {
    super(), this.inputProblem = e54;
  }
  obstacleNodes = [];
  passthroughNodes = [];
  mergedNodes = [];
  pendingGroups = [];
  totalGroupCount = 0;
  processedGroupCount = 0;
  debugFilteredNodes = [];
  debugMergeEvents = [];
  currentGroupKey = null;
  currentRootNodeId = null;
  lastMergedNodeId = null;
  _setup() {
    this.obstacleNodes = this.inputProblem.meshNodes.filter((e55) => e55._containsObstacle === true), this.passthroughNodes = [], this.mergedNodes = [], this.pendingGroups = [], this.totalGroupCount = 0, this.processedGroupCount = 0, this.debugFilteredNodes = [], this.debugMergeEvents = [], this.currentGroupKey = null, this.currentRootNodeId = null, this.lastMergedNodeId = null;
    const e54 = new Map;
    for (const t4 of this.inputProblem.meshNodes) {
      if (t4._containsObstacle === true) {
        this.passthroughNodes.push(t4), this.debugFilteredNodes.push({ type: "preserved-obstacle", node: t4, reason: "contains-obstacle" });
        continue;
      }
      if (q9(t4)) {
        this.passthroughNodes.push(t4);
        continue;
      }
      if (t4.availableZ.length !== this.inputProblem.layerCount) {
        this.passthroughNodes.push(t4);
        continue;
      }
      let n7 = false;
      for (let e55 = 0;e55 < this.inputProblem.layerCount; e55 += 1)
        if (!t4.availableZ.includes(e55)) {
          n7 = true;
          break;
        }
      if (n7) {
        this.passthroughNodes.push(t4);
        continue;
      }
      if (Q9(t4, this.obstacleNodes)) {
        this.passthroughNodes.push(t4), this.debugFilteredNodes.push({ type: "preserved-overlap", node: t4, reason: "overlaps-obstacle" });
        continue;
      }
      const o7 = J9(t4), i7 = e54.get(o7);
      i7 ? i7.push(t4) : e54.set(o7, [t4]);
    }
    for (const [t4, n7] of e54.entries())
      n7.length <= 1 ? this.passthroughNodes.push(...n7) : this.pendingGroups.push({ groupKey: t4, nodes: n7 });
    this.pendingGroups.sort((e55, t4) => t4.nodes.length - e55.nodes.length), this.totalGroupCount = this.pendingGroups.length, this.updateStats("setup");
  }
  _step() {
    const e54 = this.pendingGroups.shift();
    if (!e54)
      return this.currentGroupKey = null, this.currentRootNodeId = null, this.solved = true, void this.updateStats("done");
    const t4 = e54.nodes[0];
    this.currentGroupKey = e54.groupKey, this.currentRootNodeId = t4 ? t4.capacityMeshNodeId : null;
    const n7 = function(e55) {
      if (!e55.nodes[0])
        return { outputNodes: [], mergeEvents: [] };
      let { POSITIVE_INFINITY: t7, POSITIVE_INFINITY: n8, POSITIVE_INFINITY: o8, POSITIVE_INFINITY: i7 } = Number;
      for (const r8 of e55.nodes) {
        t7 = Math.min(t7, r8.width), n8 = Math.min(n8, r8.height);
        const e56 = Le(r8);
        o8 = Math.min(o8, e56.minX), i7 = Math.min(i7, e56.minY);
      }
      const r7 = new Map, s7 = [];
      for (const a8 of e55.nodes) {
        const e56 = Le(a8), c7 = Math.round((e56.minX - o8) / t7), l7 = Math.round((e56.minY - i7) / n8), h5 = Math.max(1, Math.round(a8.width / t7)), d7 = Math.max(1, Math.round(a8.height / n8));
        for (let e57 = 0;e57 < d7; e57 += 1)
          for (let t10 = 0;t10 < h5; t10 += 1)
            r7.set(`${c7 + t10},${l7 + e57}`, a8);
        s7.push({ col: c7, row: l7 });
      }
      s7.sort((e56, t10) => e56.row - t10.row || e56.col - t10.col);
      const a7 = new Set, c5 = [], l5 = [];
      for (const o10 of s7) {
        const i8 = `${o10.col},${o10.row}`;
        if (a7.has(i8))
          continue;
        let s8 = 0;
        for (;; ) {
          const e56 = `${o10.col + s8},${o10.row}`;
          if (!r7.has(e56))
            break;
          if (a7.has(e56))
            break;
          s8 += 1;
        }
        let h5 = s8, d7 = 1, u7 = 1, p7 = 1;
        for (let e56 = 1;; e56 += 1) {
          const i9 = o10.row + e56 - 1;
          let s9 = 0;
          for (;s9 < h5; ) {
            const e57 = `${o10.col + s9},${i9}`;
            if (!r7.has(e57))
              break;
            if (a7.has(e57))
              break;
            s9 += 1;
          }
          if (s9 === 0)
            break;
          h5 = Math.min(h5, s9);
          for (let o11 = h5;o11 >= 1; o11 -= 1) {
            const i10 = o11 * t7, r8 = e56 * n8, s10 = Math.min(i10, r8);
            if ((s10 <= 0.000001 ? Number.POSITIVE_INFINITY : Math.max(i10, r8) / s10) > 4)
              continue;
            const a8 = o11 * e56;
            a8 > p7 && (p7 = a8, d7 = o11, u7 = e56);
            break;
          }
        }
        const m7 = new Map;
        for (let e56 = 0;e56 < u7; e56 += 1)
          for (let t10 = 0;t10 < d7; t10 += 1) {
            const n10 = `${o10.col + t10},${o10.row + e56}`, i9 = r7.get(n10);
            i9 && (a7.add(n10), m7.set(i9.capacityMeshNodeId, i9));
          }
        const g7 = [...m7.values()];
        if (g7.length <= 1) {
          const e56 = g7[0];
          e56 && c5.push(e56);
          continue;
        }
        const f7 = K9(g7);
        c5.push(f7), l5.push({ type: "merge", groupKey: e55.groupKey, sourceNodes: g7, mergedNode: f7 });
      }
      return { outputNodes: c5, mergeEvents: l5 };
    }(e54);
    this.mergedNodes.push(...n7.outputNodes), this.processedGroupCount += 1, this.debugMergeEvents.push(...n7.mergeEvents);
    const o7 = n7.mergeEvents[n7.mergeEvents.length - 1];
    o7 && (this.lastMergedNodeId = o7.mergedNode.capacityMeshNodeId), this.updateStats(n7.mergeEvents.length > 0 ? "merged-group" : "passthrough-group");
  }
  computeProgress() {
    return this.totalGroupCount === 0 ? 1 : this.processedGroupCount / this.totalGroupCount;
  }
  updateStats(e54) {
    const t4 = new Set(this.debugMergeEvents.map((e55) => e55.groupKey)), n7 = { lastAction: e54, totalGroupCount: this.totalGroupCount, processedGroupCount: this.processedGroupCount, pendingGroupCount: this.pendingGroups.length, mergedNodeCount: this.mergedNodes.length, passthroughNodeCount: this.passthroughNodes.length, gapFillNodeCount: this.passthroughNodes.filter(q9).length, preservedObstacleNodeCount: this.debugFilteredNodes.filter((e55) => e55.type === "preserved-obstacle").length, preservedOverlapNodeCount: this.debugFilteredNodes.filter((e55) => e55.type === "preserved-overlap").length, mergeCount: this.debugMergeEvents.length, mergedGroupCount: t4.size, currentGroupKey: this.currentGroupKey, currentRootNodeId: this.currentRootNodeId, lastMergedNodeId: this.lastMergedNodeId };
    this.stats = n7;
  }
  getConstructorParams() {
    return [this.inputProblem];
  }
  getOutput() {
    return [...this.mergedNodes, ...this.passthroughNodes];
  }
  visualize() {
    const e54 = this.getOutput(), t4 = this.currentRootNodeId ? e54.find((e55) => e55.capacityMeshNodeId === this.currentRootNodeId) ?? null : null, n7 = this.lastMergedNodeId ? e54.find((e55) => e55.capacityMeshNodeId === this.lastMergedNodeId) ?? null : null;
    return { rects: [...this.debugFilteredNodes.map((e55) => e82(e55.node, e55.type === "preserved-obstacle" ? "rgba(255,64,64,0.35)" : "rgba(255,160,64,0.35)", e55.reason)), ...this.passthroughNodes.map((e55) => e82(e55, e55._containsObstacle ? "rgba(255,0,0,0.35)" : q9(e55) ? "rgba(0,120,255,0.18)" : "rgba(160,160,160,0.12)")), ...this.mergedNodes.map((e55) => e82(e55, "rgba(120,120,120,0.14)")), ...t4 ? [e82(t4, "rgba(255,215,0,0.35)", "active-group")] : [], ...n7 ? [e82(n7, "rgba(0,200,120,0.28)", "merged")] : []] };
  }
};
var o8 = class extends BaseSolver {
  constructor(e54) {
    super(), this.inputProblem = e54;
  }
  obstacleQueue = [];
  obstacleQueueIndex = 0;
  meshNodes = [];
  _setup() {
    this.obstacleQueue = this.inputProblem.obstacles, this.obstacleQueueIndex = 0, this.meshNodes = [...this.inputProblem.meshNodes];
  }
  _step() {
    if (this.obstacleQueueIndex >= this.obstacleQueue.length)
      return void (this.solved = true);
    const e54 = this.obstacleQueue[this.obstacleQueueIndex], t4 = e54.layers.map((e55) => mo(e55, this.inputProblem.layerCount)), n7 = [];
    for (const o7 of this.meshNodes) {
      if (o7._containsObstacle) {
        n7.push(o7);
        continue;
      }
      if (!t4.some((e55) => o7.availableZ.includes(e55))) {
        n7.push(o7);
        continue;
      }
      if (!De(Le(o7), Le(e54))) {
        n7.push(o7);
        continue;
      }
      if (o7.availableZ.length === 1)
        continue;
      const i7 = o7.availableZ.filter((e55) => !t4.includes(e55));
      for (const e55 of i7) {
        const t7 = { ...o7, capacityMeshNodeId: `${o7.capacityMeshNodeId}:z${e55}`, availableZ: [e55], layer: `z${e55}` };
        n7.push(t7);
      }
    }
    this.meshNodes = n7, this.obstacleQueueIndex += 1, this.stats = { obstaclesProcessed: this.obstacleQueueIndex, obstacleCount: this.obstacleQueue.length, meshNodeCount: this.meshNodes.length };
  }
  computeProgress() {
    return this.obstacleQueue.length === 0 ? 1 : this.obstacleQueueIndex / this.obstacleQueue.length;
  }
  getConstructorParams() {
    return [this.inputProblem];
  }
  getOutput() {
    return this.meshNodes;
  }
  visualize() {
    const e54 = this.obstacleQueueIndex < this.obstacleQueue.length ? this.obstacleQueue[this.obstacleQueueIndex] ?? null : null, t4 = this.obstacleQueue.slice(0, this.obstacleQueueIndex), n7 = e54 ? this.obstacleQueue.slice(this.obstacleQueueIndex + 1) : [];
    return { rects: [...t4.map((e55) => ({ center: e55.center, width: e55.width, height: e55.height, fill: "rgba(160,160,160,0.10)", stroke: "rgba(160,160,160,0.35)", label: `processed ${e55.obstacleId ?? "obstacle"}` })), ...e54 ? [{ center: e54.center, width: e54.width, height: e54.height, fill: "rgba(255,140,0,0.22)", stroke: "rgba(255,140,0,0.75)", label: `active ${e54.obstacleId ?? "obstacle"}` }] : [], ...n7.map((e55) => ({ center: e55.center, width: e55.width, height: e55.height, fill: "rgba(255,0,0,0.05)", stroke: "rgba(255,0,0,0.22)", label: `pending ${e55.obstacleId ?? "obstacle"}` })), ...this.meshNodes.map((e55) => ({ ...dj(e55, { rectMargin: 0.01 }), fill: e55._containsObstacle ? "rgba(255,0,0,0.18)" : "rgba(0,120,255,0.12)", stroke: e55._containsObstacle ? "rgba(255,0,0,0.45)" : "rgba(0,120,255,0.45)" }))] };
  }
};
l9.register(class extends BasePipelineSolver {
  constructor(e54) {
    super(e54), this.inputProblem = e54;
  }
  static componentKind = "bga";
  initialTopologySolver;
  removeMeshNodeOverlappingWithUnmarkedObstacle;
  gapfillDueToNodeRemoval;
  mergeMeshNodes;
  markedComponentObstacles = [];
  unmarkedComponentObstacles = [];
  pipelineDef = [definePipelineStep("initialTopologySolver", U9, (e54) => [{ srj: e54.inputProblem.inputSrj, componentBounds: e54.inputProblem.detectedComponent.bounds, componentId: e54.inputProblem.detectedComponent.componentId, markedComponentObstacles: e54.markedComponentObstacles, unmarkedComponentObstacles: e54.unmarkedComponentObstacles, viaDiameter: e54.inputProblem.viaDiameter }]), definePipelineStep("removeMeshNodeOverlappingWithUnmarkedObstacle", o8, (e54) => [{ meshNodes: e54.initialTopologySolver.getOutput(), obstacles: e54.unmarkedComponentObstacles, layerCount: e54.inputProblem.inputSrj.layerCount }]), definePipelineStep("gapfillDueToNodeRemoval", k9, (e54) => [{ meshNodes: e54.removeMeshNodeOverlappingWithUnmarkedObstacle.getOutput(), unmarkedComponentObstacles: e54.unmarkedComponentObstacles, layerCount: e54.inputProblem.inputSrj.layerCount }]), definePipelineStep("mergeMeshNodes", t8, (e54) => [{ meshNodes: e54.gapfillDueToNodeRemoval.getOutput(), layerCount: e54.inputProblem.inputSrj.layerCount }])];
  _setup() {
    const e54 = this.inputProblem.detectedComponent.bounds, t4 = this.inputProblem.detectedComponent.componentId, n7 = [], o7 = [];
    for (const i7 of this.inputProblem.inputSrj.obstacles) {
      const r7 = Le(i7);
      De(e54, r7) && (i7.componentId !== t4 ? o7.push(i7) : n7.push(i7));
    }
    this.markedComponentObstacles = n7, this.unmarkedComponentObstacles = o7;
  }
  getConstructorParams() {
    return [this.inputProblem];
  }
  getOutput() {
    return { routingRegions: this.mergeMeshNodes?.getOutput() ?? this.gapfillDueToNodeRemoval?.getOutput() ?? this.removeMeshNodeOverlappingWithUnmarkedObstacle?.getOutput() ?? [] };
  }
  initialVisualize() {
    return { rects: [{ center: { x: (this.inputProblem.detectedComponent.bounds.minX + this.inputProblem.detectedComponent.bounds.maxX) / 2, y: (this.inputProblem.detectedComponent.bounds.minY + this.inputProblem.detectedComponent.bounds.maxY) / 2 }, width: this.inputProblem.detectedComponent.bounds.maxX - this.inputProblem.detectedComponent.bounds.minX, height: this.inputProblem.detectedComponent.bounds.maxY - this.inputProblem.detectedComponent.bounds.minY, fill: "rgba(0,0,0,0)", stroke: "rgba(30,30,30,0.65)", label: `bga ${this.inputProblem.detectedComponent.componentId}` }, ...this.markedComponentObstacles.map((e54) => ({ center: e54.center, width: e54.width, height: e54.height, fill: "rgba(255,0,0,0.18)", stroke: "rgba(255,0,0,0.52)", label: `pad ${e54.obstacleId ?? "obstacle"}` })), ...this.unmarkedComponentObstacles.map((e54) => ({ center: e54.center, width: e54.width, height: e54.height, fill: "rgba(255,140,0,0.14)", stroke: "rgba(255,140,0,0.42)", label: `foreign ${e54.obstacleId ?? "obstacle"}` }))] };
  }
  finalVisualize() {
    return { rects: this.getOutput().routingRegions.map((e54) => ({ ...dj(e54, { rectMargin: 0.01 }), fill: e54._containsObstacle ? "rgba(255,0,0,0.16)" : "rgba(0,120,255,0.12)", stroke: e54._containsObstacle ? "rgba(255,0,0,0.36)" : "rgba(0,120,255,0.42)" })) };
  }
});
var r8 = 0.000001;
function s8(e54, t4) {
  return e54.__zLayers && e54.__zLayers.length > 0 ? go(e54.__zLayers, t4) : fo(e54.layers, t4);
}
function a8(e54) {
  const t4 = [...e54].sort((e55, t7) => e55 - t7), n7 = [];
  for (let e55 = 1;e55 < t4.length; e55++) {
    const o10 = t4[e55] - t4[e55 - 1];
    o10 > r8 && n7.push(o10);
  }
  const o7 = n7.length > 0 ? Math.max(r8, Math.min(...n7) / 4) : 0.001, i7 = [];
  for (const e55 of t4) {
    const t7 = i7[i7.length - 1];
    (t7 === undefined || Math.abs(e55 - t7) > o7) && i7.push(e55);
  }
  return i7;
}
function c8(e54) {
  return Array.from({ length: Math.max(0, e54) }, (e55, t4) => t4);
}
var l8 = 0.000001;
function h8(e54) {
  return e54.maxX - e54.minX > l8 && e54.maxY - e54.minY > l8;
}
function d8(e54) {
  return function(e55) {
    const t4 = Math.min(e55.width, e55.height), n7 = Math.max(e55.width, e55.height);
    return t4 <= 0 ? 0 : n7 / t4;
  }(e54) >= 1.5;
}
function u8(e54, t4) {
  const n7 = [{ side: "top", distance: Math.abs(e54.center.y - t4.minY) }, { side: "right", distance: Math.abs(t4.maxX - e54.center.x) }, { side: "bottom", distance: Math.abs(t4.maxY - e54.center.y) }, { side: "left", distance: Math.abs(e54.center.x - t4.minX) }];
  return n7.sort((e55, t7) => e55.distance - t7.distance), n7[0].side;
}
function p8(e54, t4) {
  return e54.map((e55, n7) => ({ key: `pad:${e55.obstacleId ?? n7}`, bounds: Pe(e55), regionType: "pad", obstacleZ: s8(e55, t4), connectedTo: [...e55.connectedTo] }));
}
function m8(e54, t4) {
  return e54.map((e55, n7) => ({ key: `thermal-pad:${e55.obstacleId ?? n7}`, bounds: Pe(e55), regionType: "pad", obstacleZ: s8(e55, t4), connectedTo: [...e55.connectedTo] }));
}
function g8(e54, t4) {
  return !!h8(e54) && Math.min(e54.maxX - e54.minX, e54.maxY - e54.minY) <= t4;
}
function f8({ side: e54, sideObstacles: t4, bounds: n7, innerBounds: o7, narrowThreshold: i7 }) {
  const r7 = [];
  for (let s7 = 0;s7 < t4.length - 1; s7++) {
    const a7 = Pe(t4[s7]), c5 = Pe(t4[s7 + 1]);
    let l5;
    l5 = e54 === "top" ? { minX: a7.maxX, maxX: c5.minX, minY: n7.minY, maxY: o7.minY } : e54 === "right" ? { minX: o7.maxX, maxX: n7.maxX, minY: a7.maxY, maxY: c5.minY } : e54 === "bottom" ? { minX: a7.maxX, maxX: c5.minX, minY: o7.maxY, maxY: n7.maxY } : { minX: n7.minX, maxX: o7.minX, minY: a7.maxY, maxY: c5.minY }, r7.push({ key: `${e54}-gap-${s7}`, bounds: l5, regionType: "pad-gap", isNarrowPadGap: g8(l5, i7) });
  }
  return r7;
}
function _8({ side: e54, sideObstacles: t4, thermalPadBounds: n7, narrowThreshold: o7 }) {
  const i7 = [];
  for (let r7 = 0;r7 < t4.length; r7++) {
    const s7 = Pe(t4[r7]), a7 = t4[r7 - 1] ? Pe(t4[r7 - 1]) : null, c5 = t4[r7 + 1] ? Pe(t4[r7 + 1]) : null;
    let l5;
    l5 = e54 === "top" ? { minX: a7 ? (a7.maxX + s7.minX) / 2 : s7.minX, maxX: c5 ? (s7.maxX + c5.minX) / 2 : s7.maxX, minY: s7.maxY, maxY: n7.minY } : e54 === "right" ? { minX: n7.maxX, maxX: s7.minX, minY: a7 ? (a7.maxY + s7.minY) / 2 : s7.minY, maxY: c5 ? (s7.maxY + c5.minY) / 2 : s7.maxY } : e54 === "bottom" ? { minX: a7 ? (a7.maxX + s7.minX) / 2 : s7.minX, maxX: c5 ? (s7.maxX + c5.minX) / 2 : s7.maxX, minY: n7.maxY, maxY: s7.minY } : { minX: s7.maxX, maxX: n7.minX, minY: a7 ? (a7.maxY + s7.minY) / 2 : s7.minY, maxY: c5 ? (s7.maxY + c5.minY) / 2 : s7.maxY }, i7.push({ key: `inner-${e54}-pad-${r7}`, bounds: l5, regionType: "pad-gap", isNarrowPadGap: g8(l5, o7) });
  }
  return i7;
}
function y8({ bounds: e54, innerBounds: t4, sideGroups: n7 }) {
  const o7 = n7.top[0] ? Pe(n7.top[0]) : null, i7 = n7.top.at(-1) ? Pe(n7.top.at(-1)) : null, r7 = n7.right[0] ? Pe(n7.right[0]) : null, s7 = n7.right.at(-1) ? Pe(n7.right.at(-1)) : null, a7 = n7.bottom[0] ? Pe(n7.bottom[0]) : null, c5 = n7.bottom.at(-1) ? Pe(n7.bottom.at(-1)) : null, l5 = n7.left[0] ? Pe(n7.left[0]) : null, h5 = n7.left.at(-1) ? Pe(n7.left.at(-1)) : null;
  return [{ key: "corner-nw-outer", regionType: "corner", bounds: { minX: e54.minX, maxX: t4.minX, minY: e54.minY, maxY: t4.minY } }, { key: "corner-nw-top", regionType: "corner", bounds: { minX: t4.minX, maxX: o7?.minX ?? t4.minX, minY: e54.minY, maxY: t4.minY } }, { key: "corner-nw-left", regionType: "corner", bounds: { minX: e54.minX, maxX: t4.minX, minY: t4.minY, maxY: l5?.minY ?? t4.minY } }, { key: "corner-ne-outer", regionType: "corner", bounds: { minX: t4.maxX, maxX: e54.maxX, minY: e54.minY, maxY: t4.minY } }, { key: "corner-ne-top", regionType: "corner", bounds: { minX: i7?.maxX ?? t4.maxX, maxX: t4.maxX, minY: e54.minY, maxY: t4.minY } }, { key: "corner-ne-right", regionType: "corner", bounds: { minX: t4.maxX, maxX: e54.maxX, minY: t4.minY, maxY: r7?.minY ?? t4.minY } }, { key: "corner-se-outer", regionType: "corner", bounds: { minX: t4.maxX, maxX: e54.maxX, minY: t4.maxY, maxY: e54.maxY } }, { key: "corner-se-right", regionType: "corner", bounds: { minX: t4.maxX, maxX: e54.maxX, minY: s7?.maxY ?? t4.maxY, maxY: t4.maxY } }, { key: "corner-se-bottom", regionType: "corner", bounds: { minX: c5?.maxX ?? t4.maxX, maxX: t4.maxX, minY: t4.maxY, maxY: e54.maxY } }, { key: "corner-sw-outer", regionType: "corner", bounds: { minX: e54.minX, maxX: t4.minX, minY: t4.maxY, maxY: e54.maxY } }, { key: "corner-sw-bottom", regionType: "corner", bounds: { minX: t4.minX, maxX: a7?.minX ?? t4.minX, minY: t4.maxY, maxY: e54.maxY } }, { key: "corner-sw-left", regionType: "corner", bounds: { minX: e54.minX, maxX: t4.minX, minY: h5?.maxY ?? t4.maxY, maxY: t4.maxY } }];
}
function b8({ innerBounds: e54, thermalPadBounds: t4, sideGroups: n7 }) {
  const o7 = n7.top[0] ? Pe(n7.top[0]) : null, i7 = n7.top.at(-1) ? Pe(n7.top.at(-1)) : null, r7 = n7.right[0] ? Pe(n7.right[0]) : null, s7 = n7.right.at(-1) ? Pe(n7.right.at(-1)) : null, a7 = n7.bottom[0] ? Pe(n7.bottom[0]) : null, c5 = n7.bottom.at(-1) ? Pe(n7.bottom.at(-1)) : null, l5 = n7.left[0] ? Pe(n7.left[0]) : null, h5 = n7.left.at(-1) ? Pe(n7.left.at(-1)) : null;
  return [{ key: "inner-corner-nw-core", regionType: "corner", bounds: { minX: e54.minX, maxX: t4.minX, minY: e54.minY, maxY: t4.minY } }, { key: "inner-corner-nw-top", regionType: "corner", bounds: { minX: t4.minX, maxX: o7?.minX ?? t4.minX, minY: e54.minY, maxY: t4.minY } }, { key: "inner-corner-nw-left", regionType: "corner", bounds: { minX: e54.minX, maxX: t4.minX, minY: t4.minY, maxY: l5?.minY ?? t4.minY } }, { key: "inner-corner-ne-core", regionType: "corner", bounds: { minX: t4.maxX, maxX: e54.maxX, minY: e54.minY, maxY: t4.minY } }, { key: "inner-corner-ne-top", regionType: "corner", bounds: { minX: i7?.maxX ?? t4.maxX, maxX: t4.maxX, minY: e54.minY, maxY: t4.minY } }, { key: "inner-corner-ne-right", regionType: "corner", bounds: { minX: t4.maxX, maxX: e54.maxX, minY: t4.minY, maxY: r7?.minY ?? t4.minY } }, { key: "inner-corner-se-core", regionType: "corner", bounds: { minX: t4.maxX, maxX: e54.maxX, minY: t4.maxY, maxY: e54.maxY } }, { key: "inner-corner-se-right", regionType: "corner", bounds: { minX: t4.maxX, maxX: e54.maxX, minY: s7?.maxY ?? t4.maxY, maxY: t4.maxY } }, { key: "inner-corner-se-bottom", regionType: "corner", bounds: { minX: c5?.maxX ?? t4.maxX, maxX: t4.maxX, minY: t4.maxY, maxY: e54.maxY } }, { key: "inner-corner-sw-core", regionType: "corner", bounds: { minX: e54.minX, maxX: t4.minX, minY: t4.maxY, maxY: e54.maxY } }, { key: "inner-corner-sw-bottom", regionType: "corner", bounds: { minX: t4.minX, maxX: a7?.minX ?? t4.minX, minY: t4.maxY, maxY: e54.maxY } }, { key: "inner-corner-sw-left", regionType: "corner", bounds: { minX: e54.minX, maxX: t4.minX, minY: h5?.maxY ?? t4.maxY, maxY: t4.maxY } }];
}
l9.register(class extends BaseSolver {
  constructor(e54) {
    super(), this.inputProblem = e54;
  }
  static componentKind = "qfp_thermalpad";
  output = null;
  getConstructorParams() {
    return [this.inputProblem];
  }
  _step() {
    if (this.output)
      return void (this.solved = true);
    const { layerCount: e54, obstacles: t4 } = this.inputProblem.inputSrj, { bounds: n7, componentId: o7 } = this.inputProblem.detectedComponent, i7 = c8(e54), r7 = t4.filter((e55) => e55.componentId === o7), s7 = r7.length > 0 ? r7 : t4, { padRingObstacles: a7, thermalPadObstacles: c5 } = function(e55) {
      return { padRingObstacles: e55.filter(d8), thermalPadObstacles: e55.filter((e56) => !d8(e56)) };
    }(s7), l5 = function(e55, t7) {
      const n8 = { top: [], right: [], bottom: [], left: [] };
      for (const o10 of e55)
        n8[u8(o10, t7)].push(o10);
      return n8.top.sort((e56, t10) => e56.center.x - t10.center.x), n8.bottom.sort((e56, t10) => e56.center.x - t10.center.x), n8.left.sort((e56, t10) => e56.center.y - t10.center.y), n8.right.sort((e56, t10) => e56.center.y - t10.center.y), n8;
    }(a7, n7), h5 = function({ bounds: e55, sideGroups: t7 }) {
      return { minX: t7.left.length > 0 ? Math.max(...t7.left.map((e56) => Pe(e56).maxX)) : e55.minX, maxX: t7.right.length > 0 ? Math.min(...t7.right.map((e56) => Pe(e56).minX)) : e55.maxX, minY: t7.top.length > 0 ? Math.max(...t7.top.map((e56) => Pe(e56).maxY)) : e55.minY, maxY: t7.bottom.length > 0 ? Math.min(...t7.bottom.map((e56) => Pe(e56).minY)) : e55.maxY };
    }({ bounds: n7, sideGroups: l5 }), d7 = function(e55) {
      return e55.length === 0 ? null : e55.reduce((e56, t7) => {
        const n8 = Pe(t7);
        return { minX: Math.min(e56.minX, n8.minX), maxX: Math.max(e56.maxX, n8.maxX), minY: Math.min(e56.minY, n8.minY), maxY: Math.max(e56.maxY, n8.maxY) };
      }, Pe(e55[0]));
    }(c5);
    if (!d7)
      return this.failed = true, void (this.error = "QfpThermalPadTopologyGeneratorSolver requires a thermal pad");
    const u7 = o7, p7 = this.inputProblem.viaDiameter ?? Yo(this.inputProblem.inputSrj).padDiameter, m7 = this.inputProblem.obstacleMargin ?? this.inputProblem.inputSrj.defaultObstacleMargin ?? 0.15, g7 = p7 + 2 * m7, f7 = this.inputProblem.inputSrj.minTraceWidth + 2 * m7, _5 = [...p8(a7, e54), ...m8(c5, e54), ...f8({ side: "top", sideObstacles: l5.top, bounds: n7, innerBounds: h5, narrowThreshold: f7 }), ...f8({ side: "right", sideObstacles: l5.right, bounds: n7, innerBounds: h5, narrowThreshold: f7 }), ...f8({ side: "bottom", sideObstacles: l5.bottom, bounds: n7, innerBounds: h5, narrowThreshold: f7 }), ...f8({ side: "left", sideObstacles: l5.left, bounds: n7, innerBounds: h5, narrowThreshold: f7 }), ..._8({ side: "top", sideObstacles: l5.top, thermalPadBounds: d7, narrowThreshold: f7 }), ..._8({ side: "right", sideObstacles: l5.right, thermalPadBounds: d7, narrowThreshold: f7 }), ..._8({ side: "bottom", sideObstacles: l5.bottom, thermalPadBounds: d7, narrowThreshold: f7 }), ..._8({ side: "left", sideObstacles: l5.left, thermalPadBounds: d7, narrowThreshold: f7 }), ...b8({ innerBounds: h5, thermalPadBounds: d7, sideGroups: l5 }), ...y8({ bounds: n7, innerBounds: h5, sideGroups: l5 })].flatMap((e55) => function({ nodeId: e56, bounds: t7, availableZ: n8, multiLayerThreshold: o10, regionType: i8, isNarrowPadGap: r9 = false, obstacleZ: s9 = [], connectedTo: a9 }) {
      if (!h8(t7))
        return [];
      const c7 = function(e57) {
        return { center: { x: (e57.minX + e57.maxX) / 2, y: (e57.minY + e57.maxY) / 2 }, width: e57.maxX - e57.minX, height: e57.maxY - e57.minY };
      }(t7), l7 = Math.min(c7.width, c7.height) > o10, h7 = l7 ? [{ availableZ: n8.filter((e57) => !s9.includes(e57)), containsObstacle: false }, { availableZ: n8.filter((e57) => s9.includes(e57)), containsObstacle: true }].filter((e57) => e57.availableZ.length > 0) : n8.map((e57) => ({ availableZ: [e57], containsObstacle: s9.includes(e57) }));
      return h7.map((t10) => ({ capacityMeshNodeId: h7.length === 1 ? e56 : l7 ? `${e56}:${t10.containsObstacle ? "obstacle" : "free"}` : `${e56}:z${t10.availableZ[0]}`, center: c7.center, width: c7.width, height: c7.height, layer: `z${t10.availableZ.join(",")}`, availableZ: t10.availableZ, _qfpRegionType: i8, _isNarrowQfpPadGap: r9, _containsObstacle: t10.containsObstacle, _connectedTo: t10.containsObstacle ? a9 : undefined }));
    }({ nodeId: `qfp_thermalpad:${u7}:${e55.key}`, bounds: e55.bounds, availableZ: i7, multiLayerThreshold: g7, regionType: e55.regionType, isNarrowPadGap: e55.isNarrowPadGap, obstacleZ: e55.obstacleZ, connectedTo: e55.connectedTo }));
    this.output = { routingRegions: _5 }, this.stats = { componentId: o7, layerCount: e54, viaDiameter: p7, obstacleMargin: m7, multiLayerThreshold: g7, narrowPadGapThreshold: f7, thermalPadCount: c5.length, perimeterPadCount: a7.length, innerCornerRectCount: _5.filter((e55) => e55.capacityMeshNodeId.includes(":inner-corner-")).length, narrowPadGapNodeCount: _5.filter((e55) => e55._isNarrowQfpPadGap).length, topPadCount: l5.top.length, rightPadCount: l5.right.length, bottomPadCount: l5.bottom.length, leftPadCount: l5.left.length, multiLayerNodeCount: _5.filter((e55) => e55.availableZ.length > 1).length, totalMeshNodeCount: _5.length }, this.solved = true;
  }
  getOutput() {
    if (!this.output)
      throw new Error("QfpThermalPadTopologyGeneratorSolver has not solved yet");
    return this.output;
  }
});
var v8 = 0.000001;
function I8(e54) {
  return e54.maxX - e54.minX > v8 && e54.maxY - e54.minY > v8;
}
function S8(e54, t4) {
  const n7 = [{ side: "top", distance: Math.abs(e54.center.y - t4.minY) }, { side: "right", distance: Math.abs(t4.maxX - e54.center.x) }, { side: "bottom", distance: Math.abs(t4.maxY - e54.center.y) }, { side: "left", distance: Math.abs(e54.center.x - t4.minX) }];
  return n7.sort((e55, t7) => e55.distance - t7.distance), n7[0].side;
}
function C8(e54, t4) {
  return e54.map((e55, n7) => ({ key: `pad:${e55.obstacleId ?? n7}`, bounds: Pe(e55), regionType: "pad", obstacleZ: s8(e55, t4), connectedTo: [...e55.connectedTo] }));
}
function P8(e54, t4) {
  return !!I8(e54) && Math.min(e54.maxX - e54.minX, e54.maxY - e54.minY) <= t4;
}
function M8({ side: e54, sideObstacles: t4, bounds: n7, centralBounds: o7, narrowThreshold: i7 }) {
  const r7 = [];
  for (let s7 = 0;s7 < t4.length - 1; s7++) {
    const a7 = Pe(t4[s7]), c5 = Pe(t4[s7 + 1]);
    let l5;
    l5 = e54 === "top" ? { minX: a7.maxX, maxX: c5.minX, minY: n7.minY, maxY: o7.minY } : e54 === "right" ? { minX: o7.maxX, maxX: n7.maxX, minY: a7.maxY, maxY: c5.minY } : e54 === "bottom" ? { minX: a7.maxX, maxX: c5.minX, minY: o7.maxY, maxY: n7.maxY } : { minX: n7.minX, maxX: o7.minX, minY: a7.maxY, maxY: c5.minY }, r7.push({ key: `${e54}-gap-${s7}`, bounds: l5, regionType: "pad-gap", isNarrowPadGap: P8(l5, i7) });
  }
  return r7;
}
function w8({ bounds: e54, centralBounds: t4, sideGroups: n7 }) {
  const o7 = n7.top[0] ? Pe(n7.top[0]) : null, i7 = n7.top.at(-1) ? Pe(n7.top.at(-1)) : null, r7 = n7.right[0] ? Pe(n7.right[0]) : null, s7 = n7.right.at(-1) ? Pe(n7.right.at(-1)) : null, a7 = n7.bottom[0] ? Pe(n7.bottom[0]) : null, c5 = n7.bottom.at(-1) ? Pe(n7.bottom.at(-1)) : null, l5 = n7.left[0] ? Pe(n7.left[0]) : null, h5 = n7.left.at(-1) ? Pe(n7.left.at(-1)) : null;
  return [{ key: "corner-nw-outer", regionType: "corner", bounds: { minX: e54.minX, maxX: t4.minX, minY: e54.minY, maxY: t4.minY } }, { key: "corner-nw-top", regionType: "corner", bounds: { minX: t4.minX, maxX: o7?.minX ?? t4.minX, minY: e54.minY, maxY: t4.minY } }, { key: "corner-nw-left", regionType: "corner", bounds: { minX: e54.minX, maxX: t4.minX, minY: t4.minY, maxY: l5?.minY ?? t4.minY } }, { key: "corner-ne-outer", regionType: "corner", bounds: { minX: t4.maxX, maxX: e54.maxX, minY: e54.minY, maxY: t4.minY } }, { key: "corner-ne-top", regionType: "corner", bounds: { minX: i7?.maxX ?? t4.maxX, maxX: t4.maxX, minY: e54.minY, maxY: t4.minY } }, { key: "corner-ne-right", regionType: "corner", bounds: { minX: t4.maxX, maxX: e54.maxX, minY: t4.minY, maxY: r7?.minY ?? t4.minY } }, { key: "corner-se-outer", regionType: "corner", bounds: { minX: t4.maxX, maxX: e54.maxX, minY: t4.maxY, maxY: e54.maxY } }, { key: "corner-se-right", regionType: "corner", bounds: { minX: t4.maxX, maxX: e54.maxX, minY: s7?.maxY ?? t4.maxY, maxY: t4.maxY } }, { key: "corner-se-bottom", regionType: "corner", bounds: { minX: c5?.maxX ?? t4.maxX, maxX: t4.maxX, minY: t4.maxY, maxY: e54.maxY } }, { key: "corner-sw-outer", regionType: "corner", bounds: { minX: e54.minX, maxX: t4.minX, minY: t4.maxY, maxY: e54.maxY } }, { key: "corner-sw-bottom", regionType: "corner", bounds: { minX: t4.minX, maxX: a7?.minX ?? t4.minX, minY: t4.maxY, maxY: e54.maxY } }, { key: "corner-sw-left", regionType: "corner", bounds: { minX: e54.minX, maxX: t4.minX, minY: h5?.maxY ?? t4.maxY, maxY: t4.maxY } }];
}
l9.register(class extends BaseSolver {
  constructor(e54) {
    super(), this.inputProblem = e54;
  }
  static componentKind = "qfp";
  output = null;
  getConstructorParams() {
    return [this.inputProblem];
  }
  _step() {
    if (this.output)
      return void (this.solved = true);
    const { layerCount: e54, obstacles: t4 } = this.inputProblem.inputSrj, { bounds: n7, componentId: o7 } = this.inputProblem.detectedComponent, i7 = c8(e54), r7 = t4.filter((e55) => e55.componentId === o7), s7 = r7.length > 0 ? r7 : t4, a7 = function(e55, t7) {
      const n8 = { top: [], right: [], bottom: [], left: [] };
      for (const o10 of e55)
        n8[S8(o10, t7)].push(o10);
      return n8.top.sort((e56, t10) => e56.center.x - t10.center.x), n8.bottom.sort((e56, t10) => e56.center.x - t10.center.x), n8.left.sort((e56, t10) => e56.center.y - t10.center.y), n8.right.sort((e56, t10) => e56.center.y - t10.center.y), n8;
    }(s7, n7), c5 = function({ bounds: e55, sideGroups: t7 }) {
      return { minX: t7.left.length > 0 ? Math.max(...t7.left.map((e56) => Pe(e56).maxX)) : e55.minX, maxX: t7.right.length > 0 ? Math.min(...t7.right.map((e56) => Pe(e56).minX)) : e55.maxX, minY: t7.top.length > 0 ? Math.max(...t7.top.map((e56) => Pe(e56).maxY)) : e55.minY, maxY: t7.bottom.length > 0 ? Math.min(...t7.bottom.map((e56) => Pe(e56).minY)) : e55.maxY };
    }({ bounds: n7, sideGroups: a7 }), l5 = o7, h5 = this.inputProblem.viaDiameter ?? Yo(this.inputProblem.inputSrj).padDiameter, d7 = this.inputProblem.obstacleMargin ?? this.inputProblem.inputSrj.defaultObstacleMargin ?? 0.15, u7 = h5 + 2 * d7, p7 = this.inputProblem.inputSrj.minTraceWidth + 2 * d7, m7 = [{ key: "center", bounds: c5, regionType: "center" }, ...C8(s7, e54), ...M8({ side: "top", sideObstacles: a7.top, bounds: n7, centralBounds: c5, narrowThreshold: p7 }), ...M8({ side: "right", sideObstacles: a7.right, bounds: n7, centralBounds: c5, narrowThreshold: p7 }), ...M8({ side: "bottom", sideObstacles: a7.bottom, bounds: n7, centralBounds: c5, narrowThreshold: p7 }), ...M8({ side: "left", sideObstacles: a7.left, bounds: n7, centralBounds: c5, narrowThreshold: p7 }), ...w8({ bounds: n7, centralBounds: c5, sideGroups: a7 })].flatMap((e55) => function({ nodeId: e56, bounds: t7, availableZ: n8, multiLayerThreshold: o10, regionType: i8, isNarrowPadGap: r9 = false, obstacleZ: s9 = [], connectedTo: a9 }) {
      if (!I8(t7))
        return [];
      const c7 = function(e57) {
        return { center: { x: (e57.minX + e57.maxX) / 2, y: (e57.minY + e57.maxY) / 2 }, width: e57.maxX - e57.minX, height: e57.maxY - e57.minY };
      }(t7), l7 = Math.min(c7.width, c7.height) > o10, h7 = l7 ? [{ availableZ: n8.filter((e57) => !s9.includes(e57)), containsObstacle: false }, { availableZ: n8.filter((e57) => s9.includes(e57)), containsObstacle: true }].filter((e57) => e57.availableZ.length > 0) : n8.map((e57) => ({ availableZ: [e57], containsObstacle: s9.includes(e57) }));
      return h7.map((t10) => ({ capacityMeshNodeId: h7.length === 1 ? e56 : l7 ? `${e56}:${t10.containsObstacle ? "obstacle" : "free"}` : `${e56}:z${t10.availableZ[0]}`, center: c7.center, width: c7.width, height: c7.height, layer: `z${t10.availableZ.join(",")}`, availableZ: t10.availableZ, _qfpRegionType: i8, _isNarrowQfpPadGap: r9, _containsObstacle: t10.containsObstacle, _connectedTo: t10.containsObstacle ? a9 : undefined }));
    }({ nodeId: `qfp:${l5}:${e55.key}`, bounds: e55.bounds, availableZ: i7, multiLayerThreshold: u7, regionType: e55.regionType, isNarrowPadGap: e55.isNarrowPadGap, obstacleZ: e55.obstacleZ, connectedTo: e55.connectedTo }));
    this.output = { routingRegions: m7 }, this.stats = { componentId: o7, layerCount: e54, viaDiameter: h5, obstacleMargin: d7, multiLayerThreshold: u7, narrowPadGapThreshold: p7, narrowPadGapNodeCount: m7.filter((e55) => e55._isNarrowQfpPadGap).length, topPadCount: a7.top.length, rightPadCount: a7.right.length, bottomPadCount: a7.bottom.length, leftPadCount: a7.left.length, multiLayerNodeCount: m7.filter((e55) => e55.availableZ.length > 1).length, totalMeshNodeCount: m7.length }, this.solved = true;
  }
  getOutput() {
    if (!this.output)
      throw new Error("QfpTopologyGeneratorSolver has not solved yet");
    return this.output;
  }
});
var R8 = 0.000001;
function T8({ nodeId: e54, bounds: t4, availableZ: n7, multiLayerThreshold: o7, regionType: i7, obstacleZ: r7 = [], connectedTo: s7 }) {
  if (!function(e55) {
    return e55.maxX - e55.minX > R8 && e55.maxY - e55.minY > R8;
  }(t4))
    return [];
  const a7 = function(e55) {
    return { center: { x: (e55.minX + e55.maxX) / 2, y: (e55.minY + e55.maxY) / 2 }, width: e55.maxX - e55.minX, height: e55.maxY - e55.minY };
  }(t4), c5 = Math.min(a7.width, a7.height) > o7, l5 = c5 ? [{ availableZ: n7.filter((e55) => !r7.includes(e55)), containsObstacle: false }, { availableZ: n7.filter((e55) => r7.includes(e55)), containsObstacle: true }].filter((e55) => e55.availableZ.length > 0) : n7.map((e55) => ({ availableZ: [e55], containsObstacle: r7.includes(e55) }));
  return l5.map((t7) => ({ capacityMeshNodeId: l5.length === 1 ? e54 : c5 ? `${e54}:${t7.containsObstacle ? "obstacle" : "free"}` : `${e54}:z${t7.availableZ[0]}`, center: a7.center, width: a7.width, height: a7.height, layer: `z${t7.availableZ.join(",")}`, availableZ: t7.availableZ, _soicRegionType: i7, _containsObstacle: t7.containsObstacle, _connectedTo: t7.containsObstacle ? s7 : undefined }));
}
function E8(e54, t4) {
  let n7 = 0, o7 = Number.POSITIVE_INFINITY;
  for (let i7 = 0;i7 < t4.length; i7++) {
    const r7 = Math.abs(e54 - t4[i7]);
    r7 < o7 && (n7 = i7, o7 = r7);
  }
  return n7;
}
function A8(e54, t4) {
  return e54.map((e55, n7) => ({ key: `pad:${e55.obstacleId ?? n7}`, bounds: Pe(e55), regionType: "pad", obstacleZ: s8(e55, t4), connectedTo: [...e55.connectedTo] }));
}
function O8(e54, t4) {
  if (e54.componentId !== t4.componentId)
    return false;
  const { bounds: n7 } = t4;
  return e54.center.x >= n7.minX && e54.center.x <= n7.maxX && e54.center.y >= n7.minY && e54.center.y <= n7.maxY;
}
function k8({ detectedComponent: e54, inputSrj: t4 }) {
  const n7 = t4.obstacles.filter((t7) => O8(t7, e54)), o7 = Array.from({ length: t4.layerCount }, (e55, t7) => t7), i7 = o7.map((e55) => Co(e55, t4.layerCount)), r7 = Array.from(new Set(n7.flatMap((e55) => e55.connectedTo))), { bounds: s7 } = e54;
  return { obstacleId: `${e54.componentId}_component_bounds`, componentId: e54.componentId, type: "rect", layers: i7, __zLayers: o7, center: { x: (s7.minX + s7.maxX) / 2, y: (s7.minY + s7.maxY) / 2 }, width: s7.maxX - s7.minX, height: s7.maxY - s7.minY, connectedTo: r7 };
}
function D8(e54) {
  if (e54.length === 0)
    return { minX: 0, maxX: 0, minY: 0, maxY: 0 };
  let { POSITIVE_INFINITY: t4, NEGATIVE_INFINITY: n7, POSITIVE_INFINITY: o7, NEGATIVE_INFINITY: i7 } = Number;
  for (const r7 of e54) {
    const e55 = Pe(r7);
    t4 = Math.min(t4, e55.minX), n7 = Math.max(n7, e55.maxX), o7 = Math.min(o7, e55.minY), i7 = Math.max(i7, e55.maxY);
  }
  return { minX: t4, maxX: n7, minY: o7, maxY: i7 };
}
function L8(e54) {
  const t4 = e54.componentDetectionOutput ?? [], n7 = function({ detectedComponents: e55, inputSrj: t7 }) {
    return e55.map((e56) => {
      const n8 = t7.obstacles.filter((t10) => O8(t10, e56));
      return { componentId: e56.componentId, componentKind: e56.componentKind, memberObstacleIds: n8.map((t10, n10) => t10.obstacleId ?? `${e56.componentId}:member:${n10}`), memberObstacles: n8, replacementObstacle: k8({ detectedComponent: e56, inputSrj: t7 }) };
    });
  }({ detectedComponents: t4, inputSrj: e54.inputSrj }), o7 = e54.globalNoConnectionSrj ?? (t4.length > 0 ? function({ detectedComponents: e55, inputSrj: t7 }) {
    return { ...structuredClone(t7), obstacles: [...t7.obstacles.filter((t10) => !e55.some((e56) => O8(t10, e56))), ...e55.map((e56) => k8({ detectedComponent: e56, inputSrj: t7 }))] };
  }({ detectedComponents: t4, inputSrj: e54.inputSrj }) : e54.inputSrj) ?? e54.brokenSrj?.componentsAsObstaclesSrj, i7 = e54.components ?? n7 ?? e54.brokenSrj?.components ?? [];
  if (!o7)
    throw new Error("MultiGraphTopologyPlannerSolver requires globalNoConnectionSrj or detected components");
  return { globalNoConnectionSrj: o7, components: i7 };
}
function z8({ rects: e54, components: t4 }) {
  return e54 && t4.length !== 0 ? e54.filter((e55) => !function(e56) {
    return typeof e56.label == "string" && e56.label.startsWith("node ");
  }(e55) || !t4.some((t7) => function({ rect: e56, obstacle: t10 }) {
    if (!e56.center || e56.width === undefined || e56.height === undefined)
      return false;
    const n7 = 0.000000001, o7 = Le({ center: e56.center, width: e56.width, height: e56.height }), i7 = Le({ center: t10.center, width: t10.width, height: t10.height });
    return B8({ bounds: o7, outerBounds: i7, epsilon: n7 });
  }({ rect: e55, obstacle: t7.replacementObstacle }))) : e54;
}
function B8({ bounds: e54, outerBounds: t4, epsilon: n7 }) {
  return e54.minX >= t4.minX - n7 && e54.maxX <= t4.maxX + n7 && e54.minY >= t4.minY - n7 && e54.maxY <= t4.maxY + n7;
}
l9.register(class extends BaseSolver {
  constructor(e54) {
    super(), this.inputProblem = e54;
  }
  static componentKind = "soic";
  output = null;
  getConstructorParams() {
    return [this.inputProblem];
  }
  _step() {
    if (this.output)
      return void (this.solved = true);
    const { layerCount: e54, obstacles: t4 } = this.inputProblem.inputSrj, { bounds: n7, componentId: o7 } = this.inputProblem.detectedComponent, i7 = c8(e54), r7 = t4.filter((e55) => e55.componentId === o7), s7 = r7.length > 0 ? r7 : t4, a7 = function(e55) {
      const t7 = a8(e55.map((e56) => e56.center.y)).length;
      return a8(e55.map((e56) => e56.center.x)).length === 2 && t7 !== 2 ? "vertical-columns" : "horizontal-rows";
    }(s7), c5 = function({ obstacles: e55, orientation: t7 }) {
      const n8 = { left: [], right: [], top: [], bottom: [] };
      if (t7 === "vertical-columns") {
        const t10 = a8(e55.map((e56) => e56.center.x));
        for (const o11 of e55)
          n8[E8(o11.center.x, t10) === 0 ? "left" : "right"].push(o11);
        return n8.left.sort((e56, t11) => e56.center.y - t11.center.y), n8.right.sort((e56, t11) => e56.center.y - t11.center.y), n8;
      }
      const o10 = a8(e55.map((e56) => e56.center.y));
      for (const t10 of e55)
        n8[E8(t10.center.y, o10) === 0 ? "top" : "bottom"].push(t10);
      return n8.top.sort((e56, t10) => e56.center.x - t10.center.x), n8.bottom.sort((e56, t10) => e56.center.x - t10.center.x), n8;
    }({ obstacles: s7, orientation: a7 }), l5 = function({ bounds: e55, orientation: t7, sideGroups: n8 }) {
      return t7 === "vertical-columns" ? { minX: Math.max(...n8.left.map((e56) => Pe(e56).maxX)), maxX: Math.min(...n8.right.map((e56) => Pe(e56).minX)), minY: e55.minY, maxY: e55.maxY } : { minX: e55.minX, maxX: e55.maxX, minY: Math.max(...n8.top.map((e56) => Pe(e56).maxY)), maxY: Math.min(...n8.bottom.map((e56) => Pe(e56).minY)) };
    }({ bounds: n7, orientation: a7, sideGroups: c5 }), h5 = o7, d7 = this.inputProblem.viaDiameter ?? Yo(this.inputProblem.inputSrj).padDiameter, u7 = this.inputProblem.obstacleMargin ?? this.inputProblem.inputSrj.defaultObstacleMargin ?? 0.15, p7 = 2 * (d7 + u7), m7 = a7 === "vertical-columns" ? ["left", "right"] : ["top", "bottom"], g7 = [{ key: "center", bounds: l5, regionType: "center" }, ...A8(s7, e54), ...m7.flatMap((e55) => function({ side: e56, sideObstacles: t7, bounds: n8, centralBounds: o10 }) {
      const i8 = [];
      for (let r9 = 0;r9 < t7.length - 1; r9++) {
        const s9 = Pe(t7[r9]), a9 = Pe(t7[r9 + 1]);
        let c7;
        c7 = e56 === "left" ? { minX: n8.minX, maxX: o10.minX, minY: s9.maxY, maxY: a9.minY } : e56 === "right" ? { minX: o10.maxX, maxX: n8.maxX, minY: s9.maxY, maxY: a9.minY } : e56 === "top" ? { minX: s9.maxX, maxX: a9.minX, minY: n8.minY, maxY: o10.minY } : { minX: s9.maxX, maxX: a9.minX, minY: o10.maxY, maxY: n8.maxY }, i8.push({ key: `${e56}-gap-${r9}`, bounds: c7, regionType: "pad-gap" });
      }
      return i8;
    }({ side: e55, sideObstacles: c5[e55], bounds: n7, centralBounds: l5 }))], f7 = g7.flatMap((e55) => T8({ nodeId: `soic:${h5}:${e55.key}`, bounds: e55.bounds, availableZ: i7, multiLayerThreshold: p7, regionType: e55.regionType, obstacleZ: e55.obstacleZ, connectedTo: e55.connectedTo }));
    this.output = { routingRegions: f7 }, this.stats = { componentId: o7, layerCount: e54, orientation: a7, viaDiameter: d7, obstacleMargin: u7, multiLayerThreshold: p7, firstSidePadCount: c5[m7[0]].length, secondSidePadCount: c5[m7[1]].length, multiLayerNodeCount: f7.filter((e55) => e55.availableZ.length > 1).length, totalMeshNodeCount: f7.length }, this.solved = true;
  }
  getOutput() {
    if (!this.output)
      throw new Error("SoicTopologyGeneratorSolver has not solved yet");
    return this.output;
  }
});
var F8 = class extends BaseSolver {
  constructor(e54) {
    super(), this.inputProblem = e54;
  }
  activeSubSolver = null;
  currentIndex = 0;
  componentMeshNodes = [];
  getConstructorParams() {
    return [this.inputProblem];
  }
  _step() {
    if (this.activeSubSolver) {
      if (this.activeSubSolver.step(), this.activeSubSolver.failed)
        return this.error = this.activeSubSolver.error, this.failed = true, void (this.activeSubSolver = null);
      if (!this.activeSubSolver.solved)
        return;
      return this.componentMeshNodes.push(this.activeSubSolver.getOutput().routingRegions), this.currentIndex += 1, void (this.activeSubSolver = null);
    }
    if (this.currentIndex >= this.inputProblem.componentSrjs.length)
      return void (this.solved = true);
    const e54 = this.inputProblem.componentKinds[this.currentIndex], t4 = this.inputProblem.componentSrjs[this.currentIndex], n7 = { inputSrj: t4, detectedComponent: { componentId: this.inputProblem.componentIds[this.currentIndex], componentKind: e54, bounds: { __type: "rect", ...t4.bounds } }, viaDiameter: this.inputProblem.viaDiameter, obstacleMargin: this.inputProblem.obstacleMargin };
    this.activeSubSolver = l9.create(n7);
  }
  getOutput() {
    return { componentMeshNodes: this.componentMeshNodes };
  }
  visualize() {
    if (this.activeSubSolver)
      return this.activeSubSolver.visualize();
    const e54 = this.inputProblem.componentSrjs[this.currentIndex] ?? null, t4 = this.componentMeshNodes.flatMap((e55) => e55);
    return { rects: [...e54 ? [{ center: { x: (e54.bounds.minX + e54.bounds.maxX) / 2, y: (e54.bounds.minY + e54.bounds.maxY) / 2 }, width: e54.bounds.maxX - e54.bounds.minX, height: e54.bounds.maxY - e54.bounds.minY, fill: "rgba(0,0,0,0)", stroke: "rgba(255,140,0,0.72)", label: `active component ${this.inputProblem.componentIds[this.currentIndex] ?? this.currentIndex}` }, ...e54.obstacles.map((e55) => ({ center: e55.center, width: e55.width, height: e55.height, fill: "rgba(255,140,0,0.10)", stroke: "rgba(255,140,0,0.30)", label: e55.obstacleId ?? e55.componentId ?? "obstacle" }))] : [], ...t4.map((e55) => ({ ...dj(e55, { rectMargin: 0.01 }), fill: e55._containsObstacle ? "rgba(255,0,0,0.14)" : "rgba(0,120,255,0.12)", stroke: e55._containsObstacle ? "rgba(255,0,0,0.34)" : "rgba(0,120,255,0.38)" }))] };
  }
};
var j8 = 0.001;
function $8(e54) {
  const t4 = [...e54].sort((e55, t7) => e55 - t7), n7 = [];
  for (const e55 of t4) {
    const t7 = n7[n7.length - 1];
    (t7 === undefined || Math.abs(e55 - t7) > j8) && n7.push(e55);
  }
  return n7;
}
function Y8(e54) {
  const t4 = Math.min(...e54), n7 = Math.max(...e54);
  return !(t4 <= 0) && n7 / t4 <= 1.01;
}
function X8(e54) {
  if (!function(e55) {
    return Y8(e55.map((e56) => e56.width)) && Y8(e55.map((e56) => e56.height));
  }(e54))
    return false;
  if (!function(e55) {
    return e55.every((e56) => {
      const t7 = Math.min(e56.width, e56.height), n8 = Math.max(e56.width, e56.height);
      return !(t7 <= 0) && n8 / t7 <= 1.5;
    });
  }(e54))
    return false;
  const t4 = $8(e54.map((e55) => e55.center.y)), n7 = $8(e54.map((e55) => e55.center.x)), o7 = t4.length, i7 = n7.length;
  if (o7 < 3 || i7 < 3)
    return false;
  const r7 = o7 * i7;
  return !((r7 > 0 ? e54.length / r7 : 0) < 0.5) && !!function(e55, t7, n8) {
    if (t7.length < 3)
      return false;
    if (n8.length < 3)
      return false;
    const o10 = new Set(t7.slice(1, -1)), i8 = new Set(n8.slice(1, -1));
    let r9 = 0;
    for (const t10 of e55)
      o10.has(t10.center.y) && i8.has(t10.center.x) && (r9 += 1);
    return r9 >= 1;
  }(e54, t4, n7);
}
function H8(e54) {
  return [Math.round(e54.width / j8), Math.round(e54.height / j8), e54.layers.join(",")].join(":");
}
function V8(e54) {
  if (e54.length < 3)
    return false;
  const t4 = [...e54].sort((e55, t7) => e55 - t7), n7 = t4[1] - t4[0];
  return !(n7 <= j8) && t4.every((e55, o7) => o7 === 0 || Math.abs(e55 - t4[o7 - 1] - n7) <= j8);
}
function W8(e54) {
  const t4 = function(e55) {
    const t7 = new Map;
    for (const n8 of e55) {
      const e56 = Math.round(n8.center.y / j8), o7 = Math.round(n8.center.x / j8), i7 = t7.get(e56) ?? { y: n8.center.y, obstaclesByX: new Map };
      i7.obstaclesByX.set(o7, n8), t7.set(e56, i7);
    }
    return [...t7.values()];
  }(e54);
  let n7 = [];
  for (const e55 of t4) {
    const o7 = [...e55.obstaclesByX.keys()];
    if (!V8([...e55.obstaclesByX.values()].map((e56) => e56.center.x)))
      continue;
    const i7 = t4.filter((e56) => o7.every((t7) => e56.obstaclesByX.has(t7)));
    if (!V8(i7.map((e56) => e56.y)))
      continue;
    const r7 = i7.flatMap((e56) => o7.map((t7) => e56.obstaclesByX.get(t7)));
    r7.length > n7.length && (n7 = r7);
  }
  return n7;
}
function G8(e54) {
  if (X8(e54))
    return e54;
  const t4 = Map.groupBy(e54, H8);
  let n7 = [];
  for (const e55 of t4.values()) {
    const t7 = W8(e55);
    t7.length > n7.length && (n7 = t7);
  }
  return n7.length > 0 ? n7 : null;
}
function U8(e54) {
  const t4 = Math.min(e54.width, e54.height), n7 = Math.max(e54.width, e54.height);
  return t4 > 0 && n7 / t4 >= 1.5;
}
function Z8({ perimeterPadObstacles: e54, thermalPadObstacles: t4 }) {
  if (t4.length === 0)
    return true;
  if (t4.length > 4)
    return false;
  const n7 = D8(e54), o7 = n7.maxX - n7.minX, i7 = n7.maxY - n7.minY, r7 = n7.minX + 0.2 * o7, s7 = n7.maxX - 0.2 * o7, a7 = n7.minY + 0.2 * i7, c5 = n7.maxY - 0.2 * i7, l5 = Math.min(...e54.map((e55) => Math.min(e55.width, e55.height)));
  return t4.every((e55) => {
    const t7 = Math.min(e55.width, e55.height);
    return e55.center.x >= r7 && e55.center.x <= s7 && e55.center.y >= a7 && e55.center.y <= c5 && t7 > l5;
  });
}
function q8(e54) {
  if (e54.length < 12)
    return false;
  if (e54.length > 32)
    return false;
  const { counts: t4, maxNearestSideRatio: n7 } = function(e55) {
    const t7 = D8(e55), n8 = t7.maxX - t7.minX, o7 = t7.maxY - t7.minY, i7 = { top: 0, right: 0, bottom: 0, left: 0 };
    if (n8 <= 0 || o7 <= 0)
      return { counts: i7, maxNearestSideRatio: 1 };
    let r7 = 0;
    for (const s7 of e55) {
      const e56 = s7.width > s7.height, a7 = [{ side: "top", distance: Math.abs(s7.center.y - t7.minY), axisSpan: o7, orientationMatches: !e56 }, { side: "right", distance: Math.abs(t7.maxX - s7.center.x), axisSpan: n8, orientationMatches: e56 }, { side: "bottom", distance: Math.abs(t7.maxY - s7.center.y), axisSpan: o7, orientationMatches: !e56 }, { side: "left", distance: Math.abs(s7.center.x - t7.minX), axisSpan: n8, orientationMatches: e56 }].filter((e57) => e57.orientationMatches).sort((e57, t10) => e57.distance - t10.distance)[0];
      i7[a7.side] += 1, r7 = Math.max(r7, a7.distance / a7.axisSpan);
    }
    return { counts: i7, maxNearestSideRatio: r7 };
  }(e54);
  return t4.top >= 3 && t4.right >= 3 && t4.bottom >= 3 && t4.left >= 3 && n7 <= 0.25;
}
function J8(e54) {
  const t4 = function(e55) {
    return e55.filter(U8);
  }(e54);
  return { perimeterPadObstacles: t4, thermalPadObstacles: e54.filter((e55) => !U8(e55)) };
}
function Q8(e54) {
  const t4 = Math.min(...e54), n7 = Math.max(...e54);
  return !(t4 <= 0) && n7 / t4 <= 1.01;
}
function K8(e54, t4) {
  let n7 = 0, o7 = Number.POSITIVE_INFINITY;
  for (let i7 = 0;i7 < t4.length; i7++) {
    const r7 = Math.abs(e54 - t4[i7]);
    r7 < o7 && (n7 = i7, o7 = r7);
  }
  return n7;
}
function e72({ memberObstacles: e54, inputSrj: t4 }) {
  if (!function(e55) {
    return Q8(e55.map((e56) => e56.width)) && Q8(e55.map((e56) => e56.height));
  }(e54))
    return false;
  const n7 = $8(e54.map((e55) => e55.center.y)), o7 = $8(e54.map((e55) => e55.center.x));
  if (!(n7.length === 2 && o7.length >= 4 || o7.length === 2 && n7.length >= 4))
    return false;
  const i7 = function({ memberObstacles: e55, rowAxisValues: t7, columnAxisValues: n8 }) {
    if (t7.length === 2 && n8.length >= 4) {
      const n10 = [[], []];
      for (const o10 of e55)
        n10[K8(o10.center.y, t7)].push(o10);
      return Math.min(...n10[1].map((e56) => e56.center.y - e56.height / 2)) - Math.max(...n10[0].map((e56) => e56.center.y + e56.height / 2));
    }
    if (n8.length === 2 && t7.length >= 4) {
      const t10 = [[], []];
      for (const o10 of e55)
        t10[K8(o10.center.x, n8)].push(o10);
      return Math.min(...t10[1].map((e56) => e56.center.x - e56.width / 2)) - Math.max(...t10[0].map((e56) => e56.center.x + e56.width / 2));
    }
    return null;
  }({ memberObstacles: e54, rowAxisValues: n7, columnAxisValues: o7 });
  if (i7 === null)
    return false;
  return i7 > 2 * (Yo(t4).padDiameter + (t4.defaultObstacleMargin ?? 0.15));
}
var t7 = [class e55 {
  constructor(e54) {
    this.params = e54;
  }
  static componentKind = "qfp_thermalpad";
  componentKind = e55.componentKind;
  static isMatch({ memberObstacles: e54 }) {
    return function(e59) {
      const { perimeterPadObstacles: t4, thermalPadObstacles: n7 } = J8(e59);
      return n7.length !== 0 && !!q8(t4) && Z8({ perimeterPadObstacles: t4, thermalPadObstacles: n7 });
    }(e54);
  }
}, class e56 {
  constructor(e54) {
    this.params = e54;
  }
  static componentKind = "qfp";
  componentKind = e56.componentKind;
  static isMatch({ memberObstacles: e54 }) {
    return function(e59) {
      const { perimeterPadObstacles: t4, thermalPadObstacles: n7 } = J8(e59);
      return !(n7.length > 0) && !!Z8({ perimeterPadObstacles: t4, thermalPadObstacles: n7 }) && q8(t4);
    }(e54);
  }
}, class e57 {
  constructor(e54) {
    this.params = e54;
  }
  static componentKind = "soic";
  componentKind = e57.componentKind;
  static isMatch(e54) {
    return e72(e54);
  }
}, class e58 {
  constructor(e54) {
    this.params = e54;
  }
  static componentKind = "bga";
  componentKind = e58.componentKind;
  static isMatch({ memberObstacles: e54 }) {
    return function(e59) {
      return G8(e59) !== null;
    }(e54);
  }
}];
function n7(e54) {
  return function(e59) {
    for (const t4 of t7)
      if (t4.isMatch(e59))
        return new t4(e59);
    return null;
  }(e54)?.componentKind ?? null;
}
var o7 = class extends BaseSolver {
  inputSrj;
  initialized = false;
  groupedComponentObstacles = {};
  groupedComponentKinds = {};
  unprocessedComponentIds = [];
  detectedComponents = [];
  currentComponentId = null;
  currentMemberObstacles = [];
  output = null;
  constructor({ inputSrj: e54 }) {
    super(), this.inputSrj = e54;
  }
  getConstructorParams() {
    return [{ inputSrj: this.inputSrj }];
  }
  _step() {
    this.initialized ? this.output ? this.solved = true : this.currentComponentId !== null || this.unprocessedComponentIds.length > 0 ? this.processNextComponent() : (this.finalizeOutput(), this.solved = true) : this.initializeDetectionState();
  }
  getOutput() {
    if (!this.output)
      throw new Error("ComponentDetectionSolver has not solved yet");
    return this.output;
  }
  visualize() {
    const e54 = [];
    e54.push(...this.inputSrj.obstacles.filter((e59) => !e59.componentId).map((e59) => ({ center: e59.center, width: e59.width, height: e59.height, fill: "rgba(120, 120, 120, 0.10)", stroke: "rgba(120, 120, 120, 0.40)", label: e59.obstacleId, layer: e59.layers.join(","), step: 0 })));
    const t4 = new Set(this.detectedComponents.map((e59) => e59.componentId));
    for (const n8 of this.inputSrj.obstacles) {
      if (!n8.componentId)
        continue;
      if (t4.has(n8.componentId))
        continue;
      const o10 = n8.componentId === this.currentComponentId, i7 = Oo(n8.componentId), r7 = this.groupedComponentKinds[n8.componentId];
      e54.push({ center: n8.center, width: n8.width, height: n8.height, fill: Ao(i7, o10 ? 0.55 : 0.82), stroke: Ao(i7, o10 ? 0.1 : 0.45), label: r7 ? `${n8.componentId} ${r7.toUpperCase()}` : n8.componentId, layer: n8.layers.join(","), step: o10 ? 1 : 0 });
    }
    for (const t10 of this.detectedComponents) {
      const n8 = Oo(t10.componentId);
      e54.push({ center: { x: (t10.bounds.minX + t10.bounds.maxX) / 2, y: (t10.bounds.minY + t10.bounds.maxY) / 2 }, width: t10.bounds.maxX - t10.bounds.minX, height: t10.bounds.maxY - t10.bounds.minY, fill: Ao(n8, 0.88), stroke: Ao(n8, 0.1), label: `${t10.componentId} ${t10.componentKind.toUpperCase()} region`, step: 2 });
    }
    return { title: this.getVisualizationTitle(), rects: e54, lines: [], points: [], circles: [] };
  }
  preview() {
    return this.visualize();
  }
  initializeDetectionState() {
    this.initialized = true, this.groupedComponentKinds = {}, this.groupedComponentObstacles = this.groupObstaclesByComponentId({ obstacles: this.inputSrj.obstacles }), this.unprocessedComponentIds = Object.keys(this.groupedComponentObstacles).sort(), this.detectedComponents = [], this.currentComponentId = null, this.currentMemberObstacles = [], this.output = null;
  }
  processNextComponent() {
    if (!this.currentComponentId) {
      const e54 = this.unprocessedComponentIds.shift();
      return e54 ? (this.currentComponentId = e54, void (this.currentMemberObstacles = this.groupedComponentObstacles[e54] ?? [])) : (this.currentComponentId = null, void (this.currentMemberObstacles = []));
    }
    if (this.currentMemberObstacles.length === 0)
      return this.currentComponentId = null, void (this.currentMemberObstacles = []);
    this.detectedComponents.push(this.createDetectedComponent({ componentId: this.currentComponentId, componentKind: this.groupedComponentKinds[this.currentComponentId], memberObstacles: this.currentMemberObstacles })), this.currentComponentId = null, this.currentMemberObstacles = [];
  }
  finalizeOutput() {
    this.output = this.detectedComponents.map((e54) => ({ ...e54, bounds: { ...e54.bounds } })), this.stats = { initialized: this.initialized, totalComponentCount: Object.keys(this.groupedComponentObstacles).length, detectedComponentCount: this.detectedComponents.length, detectedBgaComponentCount: this.detectedComponents.filter((e54) => e54.componentKind === "bga").length, detectedQfpComponentCount: this.detectedComponents.filter((e54) => e54.componentKind === "qfp").length, detectedQfpComponentIds: this.detectedComponents.filter((e54) => e54.componentKind === "qfp").map((e54) => e54.componentId), detectedQfpThermalPadComponentCount: this.detectedComponents.filter((e54) => e54.componentKind === "qfp_thermalpad").length, detectedQfpThermalPadComponentIds: this.detectedComponents.filter((e54) => e54.componentKind === "qfp_thermalpad").map((e54) => e54.componentId), detectedSoicComponentCount: this.detectedComponents.filter((e54) => e54.componentKind === "soic").length, detectedSoicComponentIds: this.detectedComponents.filter((e54) => e54.componentKind === "soic").map((e54) => e54.componentId), remainingComponentCount: this.unprocessedComponentIds.length, hasActiveComponent: this.currentComponentId !== null };
  }
  groupObstaclesByComponentId({ obstacles: e54 }) {
    const t4 = {}, n8 = {};
    for (const n10 of e54)
      n10.componentId && (t4[n10.componentId] ??= [], t4[n10.componentId].push(n10));
    const o10 = Object.entries(t4).flatMap(([e59, t10]) => {
      const o11 = this.inputSrj.bounds;
      if (t10.some((e60) => !B8({ bounds: Pe(e60), outerBounds: o11, epsilon: 0 })))
        return [];
      const i7 = n7({ memberObstacles: t10, inputSrj: this.inputSrj });
      if (!i7)
        return [];
      n8[e59] = i7;
      return [[e59, i7 === "bga" ? G8(t10) : t10]];
    });
    return this.groupedComponentKinds = n8, Object.fromEntries(o10);
  }
  createDetectedComponent({ componentId: e54, componentKind: t4, memberObstacles: n8 }) {
    return { componentId: e54, componentKind: t4, bounds: { __type: "rect", ...D8(n8) } };
  }
  getVisualizationTitle() {
    const e54 = Object.keys(this.groupedComponentObstacles).length || new Set(this.inputSrj.obstacles.map((e59) => e59.componentId).filter((e59) => Boolean(e59))).size, t4 = this.detectedComponents.length;
    return this.initialized ? this.output || this.solved ? `Component Detection: done ${t4}/${e54}` : this.currentComponentId !== null || this.unprocessedComponentIds.length > 0 ? `Component Detection: ${t4}/${e54} processed` : `Component Detection: finalizing ${t4}/${e54}` : "Component Detection: setup";
  }
};
var i7 = (e54) => e54.componentId && e54.obstacleId ? `${e54.componentId}
${e54.obstacleId}` : e54.componentId ?? e54.obstacleId ?? "obstacle";
var r7 = class extends BasePipelineSolver {
  rectBoundsComponentDetection;
  pipelineDef = [definePipelineStep("rectBoundsComponentDetection", o7, (e54) => [{ inputSrj: e54.inputProblem.inputSrj }])];
  getConstructorParams() {
    return [this.inputProblem];
  }
  getOutput() {
    const e54 = this.getStageOutput("rectBoundsComponentDetection");
    if (!e54)
      throw new Error("ComponentDetectionSolver has not solved yet");
    return e54;
  }
  initialVisualize() {
    const { bounds: e54 } = this.inputProblem.inputSrj;
    return { title: "Component Detection: board and grouped component pads", rects: [{ center: { x: (e54.minX + e54.maxX) / 2, y: (e54.minY + e54.maxY) / 2 }, width: e54.maxX - e54.minX, height: e54.maxY - e54.minY, fill: "rgba(0, 0, 0, 0)", stroke: "rgba(40, 40, 40, 0.7)", label: "Board bounds", step: 0 }, ...this.inputProblem.inputSrj.obstacles.map((e59) => {
      const t4 = e59.componentId ? Oo(e59.componentId) : null;
      return { center: e59.center, width: e59.width, height: e59.height, fill: t4 ? Ao(t4, 0.72) : "rgba(120, 120, 120, 0.10)", stroke: t4 ? Ao(t4, 0.28) : "rgba(120, 120, 120, 0.40)", label: i7(e59), layer: e59.layers.join(","), step: e59.componentId ? 1 : 0 };
    })], lines: [], points: [], circles: [] };
  }
};
function a7(e54) {
  (function(e59) {
    if (!Number.isInteger(e59.layerCount))
      throw new Error("TopologyMergingSolver: layerCount must be an integer");
    if (e59.layerCount <= 0)
      throw new Error("TopologyMergingSolver: layerCount must be positive");
    if (e59.nodeGroups.length === 0)
      throw new Error("TopologyMergingSolver: at least one node group is required");
    const t10 = new Set;
    let n10 = 0;
    for (const o10 of e59.nodeGroups) {
      if (t10.has(o10.groupId))
        throw new Error(`TopologyMergingSolver: duplicate topology group id "${o10.groupId}"`);
      if (t10.add(o10.groupId), n10 += o10.nodes.length, o10.nodes.length === 0)
        throw new Error(`TopologyMergingSolver: topology group "${o10.groupId}" is empty`);
      const i8 = new Set;
      for (const t11 of o10.nodes) {
        if (i8.has(t11.capacityMeshNodeId))
          throw new Error(`TopologyMergingSolver: duplicate node id "${t11.capacityMeshNodeId}" in group "${o10.groupId}"`);
        i8.add(t11.capacityMeshNodeId), c7({ node: t11, groupId: o10.groupId, layerCount: e59.layerCount });
      }
    }
    if (n10 === 0)
      throw new Error("TopologyMergingSolver: topology node groups are empty");
  })(e54);
  const t4 = [], n8 = new Map;
  for (let o10 = 0;o10 < e54.nodeGroups.length; o10++) {
    const i8 = e54.nodeGroups[o10];
    for (const e59 of i8.nodes) {
      const r9 = { sourceKey: `${i8.groupId}:${e59.capacityMeshNodeId}`, groupIndex: o10, node: e59, bounds: ai(e59) };
      t4.push(r9), n8.set(r9.sourceKey, r9);
    }
  }
  return { preparedNodes: t4, preparedNodeBySourceKey: n8 };
}
function c7({ node: e54, groupId: t4, layerCount: n8 }) {
  if (!li(ai(e54)))
    throw new Error(`TopologyMergingSolver: node "${e54.capacityMeshNodeId}" in group "${t4}" has invalid bounds`);
  if (e54.availableZ.length === 0)
    throw new Error(`TopologyMergingSolver: node "${e54.capacityMeshNodeId}" in group "${t4}" has no available layers`);
  const o10 = [...new Set(e54.availableZ)].sort((e59, t10) => e59 - t10), i8 = o10.some((e59) => !Number.isInteger(e59) || e59 < 0 || e59 >= n8), r9 = o10.length === e54.availableZ.length && o10.every((t10, n10) => t10 === e54.availableZ[n10]);
  if (i8 || !r9)
    throw new Error(`TopologyMergingSolver: node "${e54.capacityMeshNodeId}" in group "${t4}" has invalid or unsorted availableZ`);
}
var l7 = 0.00001;
var h7 = 0.00004;
function d7({ regions: e54, preparedNodeBySourceKey: t4, nodeGroups: n8, provenance: o10, preserveSourceIds: i8 = true }) {
  i8 && (o10.groupIndexesByNodeId.clear(), o10.sourceKeysByNodeId.clear());
  const r9 = [...e54].sort((e59, t10) => e59.bounds.minX - t10.bounds.minX || e59.bounds.minY - t10.bounds.minY || e59.bounds.maxX - t10.bounds.maxX || e59.bounds.maxY - t10.bounds.maxY || e59.availableZ[0] - t10.availableZ[0]), s7 = new Set;
  return r9.map((e59, r10) => {
    const a9 = e59.sourceKeys.map((e60) => {
      const n10 = t4.get(e60);
      if (!n10)
        throw new Error(`TopologyMergingSolver: missing source node for "${e60}"`);
      return n10;
    }), c5 = a9.map(({ node: e60 }) => e60), l5 = function({ sourceNodes: e60, isComponentTopologyNode: t10 }) {
      if (e60.length === 1)
        return { _isComponentTopologyNode: !!t10 || e60[0]._isComponentTopologyNode };
      const n10 = e60.map((e61) => e61.capacityMeshNodeId), o11 = u7(e60.map((e61) => e61._targetConnectionName), "target connection", n10), i9 = u7(e60.map((e61) => e61._offBoardConnectionId), "off-board connection", n10), r11 = u7(e60.map((e61) => e61._offboardNetName), "off-board net", n10), s9 = Array.from(new Set(e60.flatMap((e61) => e61._offBoardConnectedCapacityMeshNodeIds ?? []))), a10 = Array.from(new Set(e60.flatMap((e61) => e61._connectedTo ?? [])));
      return { _containsObstacle: e60.some((e61) => e61._containsObstacle) || undefined, _completelyInsideObstacle: e60.some((e61) => e61._completelyInsideObstacle) || undefined, _containsTarget: e60.some((e61) => e61._containsTarget) || undefined, _targetConnectionName: o11, _isVirtualOffboard: e60.some((e61) => e61._isVirtualOffboard) || undefined, _offboardNetName: r11, _offBoardConnectionId: i9, _offBoardConnectedCapacityMeshNodeIds: s9.length > 0 ? s9 : undefined, _qfpRegionType: p7(e60.map((e61) => e61._qfpRegionType)), _isNarrowQfpPadGap: e60.some((e61) => e61._isNarrowQfpPadGap) || undefined, _soicRegionType: p7(e60.map((e61) => e61._soicRegionType)), _isComponentTopologyNode: t10 || undefined, _connectedTo: a10.length > 0 ? a10 : undefined };
    }({ sourceNodes: c5, isComponentTopologyNode: e59.topologyMode !== "free" && a9.some(({ groupIndex: e60 }) => n8[e60].isComponent) });
    e59.topologyMode === "free" && (l5._isComponentTopologyNode = undefined, l5._isNarrowQfpPadGap = undefined);
    const h5 = i8 && a9.length === 1 ? a9[0].node : null, d9 = Boolean(h5 && function({ region: e60, sourceNode: t10, usedNodeIds: n10 }) {
      const o11 = ai(t10), i9 = Math.abs(e60.bounds.minX - o11.minX) <= l7 && Math.abs(e60.bounds.maxX - o11.maxX) <= l7 && Math.abs(e60.bounds.minY - o11.minY) <= l7 && Math.abs(e60.bounds.maxY - o11.maxY) <= l7, r11 = e60.availableZ.length === t10.availableZ.length && e60.availableZ.every((e61, n11) => e61 === t10.availableZ[n11]);
      return i9 && r11 && !n10.has(t10.capacityMeshNodeId);
    }({ region: e59, sourceNode: h5, usedNodeIds: s7 }));
    let u7 = d9 ? h5.capacityMeshNodeId : `topology_merge_${r10}`;
    for (;s7.has(u7); )
      u7 = `${u7}_next`;
    return s7.add(u7), i8 && (o10.groupIndexesByNodeId.set(u7, [...new Set(a9.map(({ groupIndex: e60 }) => e60))]), o10.sourceKeysByNodeId.set(u7, [...e59.sourceKeys])), { ...h5 ?? c5[0], ...l5, capacityMeshNodeId: u7, center: { x: (e59.bounds.minX + e59.bounds.maxX) / 2, y: (e59.bounds.minY + e59.bounds.maxY) / 2 }, width: e59.bounds.maxX - e59.bounds.minX, height: e59.bounds.maxY - e59.bounds.minY, layer: `z${e59.availableZ.join(",")}`, availableZ: [...e59.availableZ], _adjacentNodeIds: undefined, _parent: undefined, _strawNode: undefined, _strawParentCapacityMeshNodeId: undefined };
  });
}
function u7(e54, t4, n8) {
  const o10 = Array.from(new Set(e54.filter((e59) => e59 !== undefined)));
  if (o10.length > 1)
    throw new Error(`TopologyMergingSolver: conflicting ${t4} values for overlapping source nodes ${n8.join(", ")}`);
  return o10[0];
}
function p7(e54) {
  const t4 = Array.from(new Set(e54.filter((e59) => e59 !== undefined)));
  return t4.length === 1 ? t4[0] : undefined;
}
function m7({ node: e54, sourceKey: t4, preparedNodeBySourceKey: n8 }) {
  const o10 = n8.get(t4);
  if (!o10)
    throw new Error(`TopologyMergingSolver: missing source node for output "${e54.capacityMeshNodeId}"`);
  const i8 = ai(e54), r9 = i8.minX >= o10.bounds.minX - h7 && i8.maxX <= o10.bounds.maxX + h7 && i8.minY >= o10.bounds.minY - h7 && i8.maxY <= o10.bounds.maxY + h7, s7 = e54.availableZ.every((e59) => o10.node.availableZ.includes(e59));
  if (!r9 || !s7)
    throw new Error(`TopologyMergingSolver: output node "${e54.capacityMeshNodeId}" escapes its source geometry or layers`);
}
function g7({ groupIndexesA: e54, groupIndexesB: t4, sourceKeysA: n8, sourceKeysB: o10, sharedLayers: i8, preparedNodeBySourceKey: r9 }) {
  if (e54.length !== 1 || t4.length !== 1 || e54[0] !== t4[0] || n8.length !== 1 || o10.length !== 1 || n8[0] === o10[0])
    return false;
  const s7 = r9.get(n8[0]), a9 = r9.get(o10[0]);
  if (!s7 || !a9 || i8.length === 0)
    return false;
  return i8.some((e59) => s7.node.availableZ.includes(e59) && a9.node.availableZ.includes(e59)) && ci(s7.bounds, a9.bounds) !== null;
}
function f7(e54) {
  const t4 = [...e54].sort((e59, t10) => e59 - t10), n8 = [];
  for (const e59 of t4) {
    const t10 = n8[n8.length - 1];
    (t10 === undefined || Math.abs(e59 - t10) > l7) && n8.push(e59);
  }
  return n8;
}
function _7(e54, t4) {
  return t4.x >= e54.minX - l7 && t4.x <= e54.maxX + l7 && t4.y >= e54.minY - l7 && t4.y <= e54.maxY + l7;
}
function y7({ coveringNodes: e54, nodeGroups: t4, layerCount: n8, allowBlindAndBuriedVias: o10 = false }) {
  const i8 = new Map, r9 = new Set;
  let s7 = -2, a9 = 0;
  for (let c5 = 0;c5 < n8; c5++) {
    const n10 = e54.filter(({ node: e59 }) => e59.availableZ.includes(c5)).sort((e59, t10) => e59.sourceKey.localeCompare(t10.sourceKey));
    if (n10.length === 0)
      continue;
    const l5 = new Set(n10.map(({ groupIndex: e59 }) => e59)), h5 = n10.filter(({ node: e59 }) => e59._containsObstacle && e59._containsTarget), d9 = h5.filter(({ groupIndex: e59 }) => !t4[e59].isComponent), u9 = new Set(h5.map(({ groupIndex: e59 }) => e59)), p9 = h5.length > 0 ? d9.length > 0 || u9.size === 1 ? "target-passthrough" : "target-merged" : l5.size === 1 ? "passthrough" : "merged";
    if (p9 === "target-passthrough" && d9.length > 0)
      for (const { sourceKey: e59, groupIndex: n11 } of h5)
        t4[n11].isComponent && r9.add(e59);
    const m9 = o10 && n10.every(({ node: e59 }) => !e59._containsObstacle && !e59._containsTarget && !e59._isVirtualOffboard);
    m9 && (c5 !== s7 + 1 && (a9 = c5), s7 = c5);
    const g10 = S7({ topologyMode: p9, nodesOnLayer: n10, targetObstacleNodes: h5, globalTargetObstacleNodes: d9 });
    for (const e59 of g10) {
      const t10 = m9 ? `free:${a9}` : JSON.stringify({ mode: p9, sourceKeys: e59 }), n11 = i8.get(t10);
      n11 ? (n11.availableZ.at(-1) !== c5 && n11.availableZ.push(c5), n11.sourceKeys = [...new Set([...n11.sourceKeys, ...e59])].sort()) : i8.set(t10, { availableZ: [c5], sourceKeys: e59, topologyMode: m9 ? "free" : p9, topologySignature: t10 });
    }
  }
  return { layerTopologies: [...i8.values()], overruledTargetSourceKeys: [...r9] };
}
function b7(e54) {
  return JSON.stringify({ availableZ: e54.availableZ, topologySignature: e54.topologySignature });
}
function x7(e54) {
  return JSON.stringify({ mergeKey: b7(e54), minY: e54.bounds.minY.toPrecision(15), maxY: e54.bounds.maxY.toPrecision(15) });
}
function v7(e54) {
  return JSON.stringify({ mergeKey: b7(e54), minX: e54.bounds.minX.toPrecision(15), maxX: e54.bounds.maxX.toPrecision(15) });
}
function I7(e54, t4) {
  const n8 = new Map;
  for (const o10 of e54) {
    const e59 = t4 === "horizontal" ? x7(o10) : v7(o10), i8 = n8.get(e59) ?? [];
    i8.push(o10), n8.set(e59, i8);
  }
  return [...n8.values()].flatMap((e59) => function(e60, t10) {
    const n10 = [...e60].sort((e61, n11) => t10 === "horizontal" ? e61.bounds.minX - n11.bounds.minX : e61.bounds.minY - n11.bounds.minY), o10 = [];
    for (const e61 of n10) {
      const n11 = o10[o10.length - 1], i8 = n11 !== undefined && (t10 === "horizontal" ? Math.abs(n11.bounds.maxX - e61.bounds.minX) <= l7 : Math.abs(n11.bounds.maxY - e61.bounds.minY) <= l7);
      n11 && i8 ? (n11.sourceKeys = [...new Set([...n11.sourceKeys, ...e61.sourceKeys])].sort(), t10 === "horizontal" ? n11.bounds.maxX = e61.bounds.maxX : n11.bounds.maxY = e61.bounds.maxY) : o10.push({ ...e61, bounds: { ...e61.bounds }, availableZ: [...e61.availableZ], sourceKeys: [...e61.sourceKeys] });
    }
    return o10;
  }(e59, t4));
}
function S7({ topologyMode: e54, nodesOnLayer: t4, targetObstacleNodes: n8, globalTargetObstacleNodes: o10 }) {
  if (e54 === "target-passthrough") {
    return (o10.length > 0 ? o10 : n8).map(({ sourceKey: e59 }) => [e59]);
  }
  return e54 === "target-merged" ? [n8.map(({ sourceKey: e59 }) => e59).sort()] : e54 === "passthrough" ? t4.map(({ sourceKey: e59 }) => [e59]) : [t4.map(({ sourceKey: e59 }) => e59).sort()];
}
var C7 = class extends BaseSolver {
  constructor(e54) {
    super(), this.inputProblem = e54, this.MAX_ITERATIONS = 1e5;
    const { preparedNodes: t4, preparedNodeBySourceKey: n8 } = a7(e54);
    this.preparedNodes = t4, this.preparedNodeBySourceKey = n8, this.xCoordinates = f7(this.preparedNodes.flatMap(({ bounds: e59 }) => [e59.minX, e59.maxX])), this.stats = { inputNodeCount: this.preparedNodes.length, xSlabCount: Math.max(0, this.xCoordinates.length - 1), processedXSlabCount: 0, atomicRegionCount: 0, outputNodeCount: 0 };
  }
  preparedNodes;
  preparedNodeBySourceKey;
  outputProvenance = { groupIndexesByNodeId: new Map, sourceKeysByNodeId: new Map };
  xCoordinates;
  atomicRegions = [];
  horizontalRegionByBucket = new Map;
  overruledTargetSourceKeys = new Set;
  outputNodes = [];
  currentXIndex = 0;
  getConstructorParams() {
    return [this.inputProblem];
  }
  _step() {
    if (this.inputProblem.nodeGroups.length === 1)
      return void this.completePassthroughTopology();
    if (this.currentXIndex < this.xCoordinates.length - 1)
      return this.processCurrentXSlab(), this.currentXIndex += 1, this.stats.processedXSlabCount = this.currentXIndex, void (this.stats.atomicRegionCount = this.atomicRegions.length);
    const e54 = function(e59) {
      let t4 = e59;
      for (;; ) {
        const e60 = I7(t4, "horizontal"), n8 = I7(e60, "vertical");
        if (n8.length === t4.length)
          return n8;
        t4 = n8;
      }
    }(function({ regions: e59, preparedNodeBySourceKey: t4, overruledTargetSourceKeys: n8 }) {
      const o10 = new Map;
      for (const t10 of e59)
        for (const e60 of t10.sourceKeys) {
          const n10 = o10.get(e60) ?? new Set;
          n10.add(t10.topologyMode), o10.set(e60, n10);
        }
      const i8 = new Set([...o10.entries()].filter(([e60, t10]) => t10.size === 1 && t10.has("target-passthrough") && !n8.has(e60)).map(([e60]) => e60));
      return i8.size === 0 ? e59 : [...e59.filter((e60) => e60.topologyMode !== "target-passthrough" || !i8.has(e60.sourceKeys[0])), ...[...i8].map((e60) => {
        const n10 = t4.get(e60);
        if (!n10)
          throw new Error(`TopologyMergingSolver: missing authoritative target source "${e60}"`);
        return { bounds: { ...n10.bounds }, availableZ: [...n10.node.availableZ], sourceKeys: [e60], topologyMode: "target-passthrough", topologySignature: JSON.stringify({ mode: "target-passthrough", sourceKeys: [e60] }) };
      })];
    }({ regions: this.atomicRegions, preparedNodeBySourceKey: this.preparedNodeBySourceKey, overruledTargetSourceKeys: this.overruledTargetSourceKeys }));
    this.outputNodes = d7({ regions: e54, preparedNodeBySourceKey: this.preparedNodeBySourceKey, nodeGroups: this.inputProblem.nodeGroups, provenance: this.outputProvenance }), function({ nodes: e59, preparedNodeBySourceKey: t4, provenance: n8 }) {
      const o10 = new Set;
      for (const i8 of e59) {
        if (o10.has(i8.capacityMeshNodeId))
          throw new Error(`TopologyMergingSolver: duplicate output node id "${i8.capacityMeshNodeId}"`);
        if (o10.add(i8.capacityMeshNodeId), !li(ai(i8)))
          throw new Error(`TopologyMergingSolver: output node "${i8.capacityMeshNodeId}" has invalid bounds`);
        if (i8.availableZ.length === 0)
          throw new Error(`TopologyMergingSolver: output node "${i8.capacityMeshNodeId}" has no available layers`);
        const e60 = n8.sourceKeysByNodeId.get(i8.capacityMeshNodeId);
        if (!e60)
          throw new Error(`TopologyMergingSolver: missing output provenance for node "${i8.capacityMeshNodeId}"`);
        e60.length === 1 && m7({ node: i8, sourceKey: e60[0], preparedNodeBySourceKey: t4 });
      }
      for (let o11 = 0;o11 < e59.length; o11++) {
        const i8 = e59[o11], r9 = ai(i8);
        for (let s7 = o11 + 1;s7 < e59.length; s7++) {
          const o12 = e59[s7];
          if (o12.center.x - o12.width / 2 > r9.maxX || o12.center.x + o12.width / 2 < r9.minX || o12.center.y - o12.height / 2 > r9.maxY || o12.center.y + o12.height / 2 < r9.minY)
            continue;
          const a9 = i8.availableZ.filter((e60) => o12.availableZ.includes(e60));
          if (a9.length === 0)
            continue;
          const c5 = ci(r9, ai(o12));
          if (!c5)
            continue;
          const l5 = c5.maxX - c5.minX, h5 = c5.maxY - c5.minY;
          if (l5 <= h7 || h5 <= h7)
            continue;
          const d9 = n8.groupIndexesByNodeId.get(i8.capacityMeshNodeId), u9 = n8.groupIndexesByNodeId.get(o12.capacityMeshNodeId);
          if (!d9 || !u9)
            throw new Error(`TopologyMergingSolver: missing output provenance for overlapping nodes "${i8.capacityMeshNodeId}" and "${o12.capacityMeshNodeId}"`);
          const p9 = n8.sourceKeysByNodeId.get(i8.capacityMeshNodeId), m9 = n8.sourceKeysByNodeId.get(o12.capacityMeshNodeId);
          if (!p9 || !m9)
            throw new Error(`TopologyMergingSolver: missing source provenance for overlapping nodes "${i8.capacityMeshNodeId}" and "${o12.capacityMeshNodeId}"`);
          if (!g7({ groupIndexesA: d9, groupIndexesB: u9, sourceKeysA: p9, sourceKeysB: m9, sharedLayers: a9, preparedNodeBySourceKey: t4 }))
            throw new Error(`TopologyMergingSolver: output nodes "${i8.capacityMeshNodeId}" and "${o12.capacityMeshNodeId}" have an unresolved inter-group overlap on a shared layer`);
        }
      }
    }({ nodes: this.outputNodes, preparedNodeBySourceKey: this.preparedNodeBySourceKey, provenance: this.outputProvenance }), this.stats.outputNodeCount = this.outputNodes.length, this.stats.compactedRegionCount = e54.length, this.solved = true;
  }
  getOutput() {
    if (!this.solved)
      throw new Error("TopologyMergingSolver: getOutput() called before the solver completed");
    return this.outputNodes;
  }
  computeProgress() {
    const e54 = Math.max(1, this.xCoordinates.length - 1);
    return this.solved ? 1 : Math.min(0.99, this.currentXIndex / e54);
  }
  visualize() {
    const e54 = this.solved ? this.outputNodes : d7({ regions: this.atomicRegions, preparedNodeBySourceKey: this.preparedNodeBySourceKey, nodeGroups: this.inputProblem.nodeGroups, provenance: this.outputProvenance, preserveSourceIds: false });
    return { title: `Topology Merging: ${e54.length} refined regions`, coordinateSystem: "cartesian", rects: e54.map((e59) => ({ ...dj(e59, { rectMargin: 0.01, zOffset: 0.02 }), label: `${e59.capacityMeshNodeId}
availableZ: ${e59.availableZ.join(",")}
component: ${e59._isComponentTopologyNode ? "yes" : "no"}` })), lines: [], points: [], circles: [], texts: [] };
  }
  completePassthroughTopology() {
    const e54 = this.inputProblem.nodeGroups[0];
    this.outputNodes = e54.nodes;
    for (const t4 of this.outputNodes)
      this.outputProvenance.groupIndexesByNodeId.set(t4.capacityMeshNodeId, [0]), this.outputProvenance.sourceKeysByNodeId.set(t4.capacityMeshNodeId, [`${e54.groupId}:${t4.capacityMeshNodeId}`]);
    this.stats.processedXSlabCount = this.stats.xSlabCount, this.stats.atomicRegionCount = 0, this.stats.compactedRegionCount = 0, this.stats.outputNodeCount = this.outputNodes.length, this.stats.passthroughNodeCount = this.outputNodes.length, this.solved = true;
  }
  processCurrentXSlab() {
    const e54 = this.xCoordinates[this.currentXIndex], t4 = this.xCoordinates[this.currentXIndex + 1];
    if (t4 - e54 <= l7)
      return;
    const n8 = (e54 + t4) / 2, o10 = this.preparedNodes.filter(({ bounds: e59 }) => n8 >= e59.minX - l7 && n8 <= e59.maxX + l7), i8 = f7(o10.flatMap(({ bounds: e59 }) => [e59.minY, e59.maxY])), r9 = new Map;
    for (let s7 = 0;s7 < i8.length - 1; s7++) {
      const a9 = i8[s7], c5 = i8[s7 + 1];
      if (c5 - a9 <= l7)
        continue;
      const l5 = { x: n8, y: (a9 + c5) / 2 }, h5 = o10.filter(({ bounds: e59 }) => _7(e59, l5));
      if (h5.length === 0)
        continue;
      const { layerTopologies: d9, overruledTargetSourceKeys: u9 } = y7({ coveringNodes: h5, nodeGroups: this.inputProblem.nodeGroups, layerCount: this.inputProblem.layerCount, allowBlindAndBuriedVias: this.inputProblem.allowBlindAndBuriedVias });
      for (const e59 of u9)
        this.overruledTargetSourceKeys.add(e59);
      for (const n10 of d9) {
        const o11 = { bounds: { minX: e54, maxX: t4, minY: a9, maxY: c5 }, availableZ: n10.availableZ, sourceKeys: n10.sourceKeys, topologyMode: n10.topologyMode, topologySignature: n10.topologySignature }, i9 = x7(o11), s9 = r9.get(i9) ?? this.horizontalRegionByBucket.get(i9);
        s9 && Math.abs(s9.bounds.maxX - e54) <= l7 ? (s9.sourceKeys = [...new Set([...s9.sourceKeys, ...o11.sourceKeys])].sort(), s9.bounds.maxX = t4, r9.set(i9, s9)) : (this.atomicRegions.push(o11), r9.set(i9, o11));
      }
    }
    this.horizontalRegionByBucket = r9;
  }
};
function w7({ meshNodes: e54, components: t4 }) {
  return t4.length === 0 ? e54 : e54.map((e59) => {
    const n8 = t4.some((t10) => function({ node: e60, component: t11 }) {
      const { replacementObstacle: n10 } = t11, o10 = Math.abs(e60.center.x - n10.center.x) <= si && Math.abs(e60.center.y - n10.center.y) <= si && Math.abs(e60.width - n10.width) <= si && Math.abs(e60.height - n10.height) <= si;
      if (t11.componentKind !== "qfp" && t11.componentKind !== "qfp_thermalpad" && t11.componentKind !== "soic")
        return o10;
      const i8 = n10.center.x - n10.width / 2, r9 = n10.center.x + n10.width / 2, s7 = n10.center.y - n10.height / 2, a9 = n10.center.y + n10.height / 2, c5 = e60.center.x >= i8 - si && e60.center.x <= r9 + si && e60.center.y >= s7 - si && e60.center.y <= a9 + si, l5 = e60.width * e60.height, h5 = n10.width * n10.height, d9 = c5 && l5 >= 0.2 * h5;
      return o10 || d9;
    }({ node: e59, component: t10 }));
    return n8 ? { ...e59, _containsObstacle: undefined, _completelyInsideObstacle: undefined, _containsTarget: undefined, _targetConnectionName: undefined, _connectedTo: undefined } : e59;
  });
}
var N7 = class extends BasePipelineSolver {
  globalTopologySolver;
  componentTopologyBatchSolver;
  normalizedInput;
  pipelineDef = [definePipelineStep("globalTopologySolver", Jn, (e54) => [e54.getGlobalTopologySolverInput()]), definePipelineStep("componentTopologyBatchSolver", F8, (e54) => [{ componentSrjs: e54.getComponentNoConnectionSrjs(), componentIds: e54.normalizedInput.components.map((e59) => e59.componentId), componentKinds: e54.normalizedInput.components.map((e59) => e59.componentKind), viaDiameter: e54.inputProblem.viaDiameter, obstacleMargin: e54.inputProblem.obstacleMargin }])];
  constructor(e54) {
    super(e54), this.normalizedInput = L8(e54);
  }
  getConstructorParams() {
    return [this.inputProblem];
  }
  getOutput() {
    const e54 = w7({ meshNodes: this.getStageOutput("globalTopologySolver")?.meshNodes ?? [], components: this.normalizedInput.components }), t4 = this.getStageOutput("componentTopologyBatchSolver")?.componentMeshNodes ?? [], n8 = this.getComponentNoConnectionSrjs();
    return { globalNoConnectionSrj: this.normalizedInput.globalNoConnectionSrj, componentNoConnectionSrjs: n8, globalMeshNodes: e54, componentMeshNodes: t4 };
  }
  finalVisualize() {
    const e54 = this.getOutput();
    return { title: "Topology Planning: generated topology groups", rects: [...e54.componentNoConnectionSrjs.flatMap((e59, t4) => {
      const n8 = this.normalizedInput.components[t4] ?? null;
      return e59.obstacles.map((e60) => ({ center: e60.center, width: e60.width, height: e60.height, fill: "rgba(120, 120, 120, 0.06)", stroke: "rgba(120, 120, 120, 0.35)", label: e60.obstacleId ?? n8?.componentId ?? "component-pad", layer: e60.layers.join(",") }));
    }), ...[...e54.globalMeshNodes, ...e54.componentMeshNodes.flat()].map((e59) => {
      const t4 = this.normalizedInput.components.find((t10) => e59.capacityMeshNodeId.includes(t10.componentId));
      return { ...dj(e59, { rectMargin: 0.01 }), fill: e59._containsObstacle ? Ao("red", 0.82) : "rgba(0, 120, 255, 0.12)", stroke: e59._containsObstacle ? Ao("red", 0.3) : "rgba(0, 120, 255, 0.55)", label: t4 ? `${t4.componentKind.toUpperCase()} ${e59.capacityMeshNodeId}` : e59.capacityMeshNodeId };
    })], lines: [], points: [], circles: [], texts: [] };
  }
  visualize() {
    return this.filterGlobalRectDiffNodesFromVisualization({ visualization: super.visualize() });
  }
  preview() {
    return this.filterGlobalRectDiffNodesFromVisualization({ visualization: super.preview() });
  }
  getComponentNoConnectionSrjs() {
    return this.normalizedInput.components.map((e54) => function({ inputSrj: e59, component: t4 }) {
      const n8 = D8(t4.memberObstacles), o10 = Math.max(e59.minViaPadDiameter ?? e59.min_via_pad_diameter ?? e59.minViaDiameter ?? 0.3, e59.defaultObstacleMargin ?? 0.15, 2 * e59.minTraceWidth), i8 = new Set(t4.memberObstacles.flatMap((e60) => e60.connectedTo)), r9 = e59.connections.flatMap((e60) => e60.pointsToConnect.filter((e61) => {
        const t10 = [e61.pointId, e61.pcb_port_id].filter((e63) => typeof e63 == "string").some((e63) => i8.has(e63)), r10 = e61.x >= n8.minX - o10 && e61.x <= n8.maxX + o10 && e61.y >= n8.minY - o10 && e61.y <= n8.maxY + o10;
        return t10 && r10;
      })).reduce((e60, t10) => ({ minX: Math.min(e60.minX, t10.x), maxX: Math.max(e60.maxX, t10.x), minY: Math.min(e60.minY, t10.y), maxY: Math.max(e60.maxY, t10.y) }), n8), s7 = e59.obstacles.filter((e60) => De(Pe(e60), r9)).map((e60) => ({ ...e60 }));
      return { ...structuredClone(e59), bounds: r9, obstacles: s7 };
    }({ inputSrj: this.inputProblem.inputSrj, component: e54 }));
  }
  getGlobalTopologySolverInput() {
    return { simpleRouteJson: this.normalizedInput.globalNoConnectionSrj, maxGapFillPasses: 4 };
  }
  filterGlobalRectDiffNodesFromVisualization({ visualization: e54 }) {
    return { ...e54, rects: z8({ rects: e54.rects, components: this.normalizedInput.components }) };
  }
};
var R7 = (e54, t4) => {
  if (e54)
    return Object.entries(t4).sort(([e59], [t10]) => t10.length - e59.length).find(([t10]) => e54.includes(t10))?.[1];
};
var T7 = (e54, t4) => ({ ...e54, points: e54.points?.map((e59) => ({ ...e59, color: R7(e59.label, t4) ?? e59.color })), lines: e54.lines?.map((e59) => ({ ...e59, strokeColor: R7(e59.label, t4) ?? e59.strokeColor })), circles: e54.circles?.map((e59) => {
  const n8 = R7(e59.label, t4);
  return n8 ? { ...e59, fill: n8, stroke: n8 } : e59;
}) });
var E7 = class extends ni {
  constructor(e54) {
    super(), this.topologyPlanningSolver = e54, this.solved = e54.solved, this.failed = e54.failed, this.error = e54.error, this.stats = e54.stats;
  }
  getOutput() {
    return this.topologyPlanningSolver.getOutput().componentMeshNodes.flat();
  }
  visualize() {
    return this.topologyPlanningSolver.finalVisualize() ?? this.topologyPlanningSolver.visualize();
  }
  preview() {
    return this.visualize();
  }
};
var O7 = (e54) => e54.filter((e59) => Boolean(e59));
var k7 = (e54, t4, n8) => {
  const o10 = `${Math.round(100 * e54.x)},${Math.round(100 * e54.y)}`, i8 = t4.map((e59) => ((e60, t10) => e60 === "top" ? 0 : e60 === "bottom" ? t10 - 1 : Number.parseInt(e60.slice(5), 10))(e59, n8)).sort().join("-");
  return `${o10}:${i8}`;
};
var D7 = class {
  parent = new Map;
  cachedObstacles;
  canonicalSetsByAliases = new Map;
  constructor(e54, t4 = e54.traces ?? [], n8 = {}) {
    for (const t10 of e54.connections)
      this.unionAll(O7([t10.name, t10.source_trace_id, t10.rootConnectionName, t10.netConnectionName, ...t10.mergedConnectionNames ?? [], ...t10.pointsToConnect.flatMap((t11) => [t11.pointId, t11.pcb_port_id, ...n8.includePhysicalPositionAliases ? [k7(t11, t11.layers ?? [t11.layer], e54.layerCount)] : []])]));
    for (const n10 of [...t4, ...e54.fixedTraces ?? []])
      this.unionAll(O7([n10.pcb_trace_id, n10.connection_name, n10.source_trace_id, n10.rootConnectionName, ...n10.mergedConnectionNames ?? [], ...n10.connectsTo ?? []]));
    for (const t10 of e54.obstacles)
      this.unionAll(n8.includePhysicalPositionAliases ? O7([t10.obstacleId, ...t10.connectedTo, ...t10.offBoardConnectsTo ?? [], k7(t10.center, t10.layers, e54.layerCount)]) : t10.connectedTo);
    this.setCacheableObstacles(e54.obstacles);
  }
  setCacheableObstacles(e54) {
    if (this.cachedObstacles !== e54) {
      this.cachedObstacles = e54, this.canonicalSetsByAliases.clear();
      for (const t4 of e54)
        this.canonicalSetsByAliases.set(t4.connectedTo, null);
    }
  }
  canonicalize(e54) {
    return [...new Set(e54.map((e59) => this.find(e59)))];
  }
  canonicalizeToSet(e54) {
    const t4 = this.canonicalSetsByAliases.get(e54);
    if (t4 && e54.length === t4.aliases.length && e54.every((e59, n10) => e59 === t4.aliases[n10]))
      return t4.canonicalNames;
    const n8 = new Set(this.canonicalize(e54));
    return this.canonicalSetsByAliases.has(e54) && this.canonicalSetsByAliases.set(e54, { aliases: [...e54], canonicalNames: n8 }), n8;
  }
  unionAll(e54) {
    const t4 = e54[0];
    if (t4) {
      this.add(t4);
      for (let n8 = 1;n8 < e54.length; n8++)
        this.union(t4, e54[n8]);
    }
  }
  add(e54) {
    this.parent.has(e54) || this.parent.set(e54, e54);
  }
  find(e54) {
    this.add(e54);
    const t4 = this.parent.get(e54);
    if (t4 === e54)
      return e54;
    const n8 = this.find(t4);
    return this.parent.set(e54, n8), n8;
  }
  union(e54, t4) {
    const n8 = this.find(e54), o10 = this.find(t4);
    n8 !== o10 && this.parent.set(o10, n8);
  }
};
var L7 = 0.000001;
var z7 = (e54, t4) => Math.hypot(t4.x - e54.x, t4.y - e54.y);
var B7 = (e54, t4, n8) => {
  const o10 = n8.x - t4.x, i8 = n8.y - t4.y, r9 = o10 * o10 + i8 * i8;
  if (r9 <= 0.000000000001)
    return z7(e54, t4);
  const s7 = j7(((e54.x - t4.x) * o10 + (e54.y - t4.y) * i8) / r9, 0, 1);
  return Math.hypot(e54.x - (t4.x + o10 * s7), e54.y - (t4.y + i8 * s7));
};
var F7 = (e54, t4, n8 = 0.000001) => Math.abs(e54.x - t4.x) <= n8 && Math.abs(e54.y - t4.y) <= n8;
var j7 = (e54, t4, n8) => Math.max(t4, Math.min(n8, e54));
var $7 = (e54, t4, n8) => (t4.x - e54.x) * (n8.y - e54.y) - (t4.y - e54.y) * (n8.x - e54.x);
var Y7 = (e54, t4, n8) => Math.abs($7(t4, n8, e54)) <= 0.000000001 && e54.x >= Math.min(t4.x, n8.x) - 0.000000001 && e54.x <= Math.max(t4.x, n8.x) + 0.000000001 && e54.y >= Math.min(t4.y, n8.y) - 0.000000001 && e54.y <= Math.max(t4.y, n8.y) + 0.000000001;
var X7 = (e54, t4, n8, o10) => {
  const i8 = $7(e54, t4, n8), r9 = $7(e54, t4, o10), s7 = $7(n8, o10, e54), a9 = $7(n8, o10, t4);
  return i8 * r9 < 0 && s7 * a9 < 0 || (Math.abs(i8) <= 0.000000001 && Y7(n8, e54, t4) || Math.abs(r9) <= 0.000000001 && Y7(o10, e54, t4) || Math.abs(s7) <= 0.000000001 && Y7(e54, n8, o10) || Math.abs(a9) <= 0.000000001 && Y7(t4, n8, o10));
};
var H7 = (e54, t4, n8, o10) => X7(e54, t4, n8, o10) ? 0 : Math.min(B7(e54, n8, o10), B7(t4, n8, o10), B7(n8, e54, t4), B7(o10, e54, t4));
var V7 = (e54, t4) => {
  let n8 = false;
  for (let o10 = 0, i8 = t4.length - 1;o10 < t4.length; i8 = o10++) {
    const r9 = t4[o10], s7 = t4[i8];
    if (Y7(e54, s7, r9))
      return true;
    r9.y > e54.y != s7.y > e54.y && e54.x < (s7.x - r9.x) * (e54.y - r9.y) / (s7.y - r9.y) + r9.x && (n8 = !n8);
  }
  return n8;
};
var W7 = (e54, t4, n8) => {
  if (V7(e54, n8) || V7(t4, n8))
    return 0;
  let o10 = Number.POSITIVE_INFINITY;
  for (let i8 = 0;i8 < n8.length; i8++) {
    const r9 = n8[i8], s7 = n8[(i8 + 1) % n8.length];
    o10 = Math.min(o10, H7(e54, t4, r9, s7));
  }
  return o10;
};
var G7 = (e54, t4, n8, o10, i8) => {
  const r9 = Math.max(Math.min(e54.x, t4.x) - Math.max(n8.x, o10.x), Math.min(n8.x, o10.x) - Math.max(e54.x, t4.x), Math.min(e54.y, t4.y) - Math.max(n8.y, o10.y), Math.min(n8.y, o10.y) - Math.max(e54.y, t4.y));
  return !(r9 > Math.max(0, i8) + 0.000000001) && (r9 <= 0.000000001 && X7(e54, t4, n8, o10) ? 0 <= i8 : B7(e54, n8, o10) <= i8 || B7(t4, n8, o10) <= i8 || B7(n8, e54, t4) <= i8 || B7(o10, e54, t4) <= i8);
};
function U7(e54, t4, n8) {
  let o10 = 0, i8 = 1;
  const r9 = t4.x - e54.x, s7 = t4.y - e54.y, a9 = [[-r9, e54.x - n8.minX], [r9, n8.maxX - e54.x], [-s7, e54.y - n8.minY], [s7, n8.maxY - e54.y]];
  for (const [e59, t10] of a9) {
    if (Math.abs(e59) < 0.000000000001) {
      if (t10 < 0)
        return false;
      continue;
    }
    const n10 = t10 / e59;
    if (e59 < 0 ? o10 = Math.max(o10, n10) : i8 = Math.min(i8, n10), o10 > i8)
      return false;
  }
  return true;
}
function Z7({ start: e54, end: t4, width: n8, base: o10 }) {
  const i8 = n8 / 2, r9 = { x: t4.x, y: t4.y };
  return [{ ...o10, minX: Math.min(e54.x, r9.x) - i8, minY: Math.min(e54.y, r9.y) - i8, maxX: Math.max(e54.x, r9.x) + i8, maxY: Math.max(e54.y, r9.y) + i8, exactShape: { type: "segment", start: { x: e54.x, y: e54.y }, end: r9, width: n8 } }];
}
function q7({ start: e54, end: t4, width: n8, base: o10 }) {
  const i8 = z7(e54, t4), r9 = ((e59) => j7(1.25 * e59, 0.25, 0.75))(n8), s7 = Math.max(1, Math.ceil(i8 / r9)), a9 = n8 / 2, c5 = [];
  for (let i9 = 0;i9 < s7; i9++) {
    const r10 = i9 / s7, l5 = (i9 + 1) / s7, h5 = e54.x + (t4.x - e54.x) * r10, d9 = e54.y + (t4.y - e54.y) * r10, u9 = e54.x + (t4.x - e54.x) * l5, p9 = e54.y + (t4.y - e54.y) * l5;
    c5.push({ ...o10, minX: Math.min(h5, u9) - a9, minY: Math.min(d9, p9) - a9, maxX: Math.max(h5, u9) + a9, maxY: Math.max(d9, p9) + a9, exactShape: { type: "segment", start: { x: h5, y: d9 }, end: { x: u9, y: p9 }, width: n8 } });
  }
  return c5;
}
var J7 = (e54, t4, n8) => {
  const o10 = Math.cos(n8), i8 = Math.sin(n8), r9 = e54.x - t4.x, s7 = e54.y - t4.y;
  return { x: t4.x + r9 * o10 - s7 * i8, y: t4.y + r9 * i8 + s7 * o10 };
};
var Q7 = (e54) => e54.isNonPlatedHole ? "hole" : e54.connectedTo[0]?.startsWith("pcb_via_") ? "via" : e54.connectedTo[0]?.startsWith("pcb_smtpad_") || e54.connectedTo[0]?.startsWith("pcb_plated_hole_") ? "pad" : "other";
function K7(e54) {
  if (e54.type !== "rect" || e54.isNonPlatedHole && e54.shape === "circle")
    return function(e59, t10 = 0.6) {
      if (e59.isNonPlatedHole && e59.shape === "circle") {
        const t11 = e59.width / 2;
        return [{ minX: e59.center.x - t11, minY: e59.center.y - t11, maxX: e59.center.x + t11, maxY: e59.center.y + t11, layers: e59.layers, kind: "obstacle", obstacleKind: "hole", connectionNames: e59.connectedTo, exactShape: { type: "circle", center: e59.center, radius: t11 } }];
      }
      const n10 = (e59.ccwRotationDegrees ?? 0) * Math.PI / 180, o11 = Math.max(1, Math.ceil(e59.width / t10)), i9 = Math.max(1, Math.ceil(e59.height / t10)), r10 = e59.width / o11, s7 = e59.height / i9, a9 = [];
      for (let t11 = 0;t11 < i9; t11++)
        for (let i10 = 0;i10 < o11; i10++) {
          const o12 = { x: e59.center.x - e59.width / 2 + (i10 + 0.5) * r10, y: e59.center.y - e59.height / 2 + (t11 + 0.5) * s7 }, c5 = r10 / 2, l5 = s7 / 2, h5 = [{ x: o12.x - c5, y: o12.y - l5 }, { x: o12.x + c5, y: o12.y - l5 }, { x: o12.x + c5, y: o12.y + l5 }, { x: o12.x - c5, y: o12.y + l5 }].map((t12) => J7(t12, e59.center, n10));
          a9.push({ minX: Math.min(...h5.map((e60) => e60.x)), minY: Math.min(...h5.map((e60) => e60.y)), maxX: Math.max(...h5.map((e60) => e60.x)), maxY: Math.max(...h5.map((e60) => e60.y)), layers: e59.layers, kind: "obstacle", obstacleKind: Q7(e59), connectionNames: e59.connectedTo, exactShape: { type: "polygon", points: h5 } });
        }
      return a9;
    }(e54);
  const { center: t4, width: n8, height: o10 } = e54, i8 = (e54.ccwRotationDegrees ?? 0) * Math.PI / 180, r9 = [{ x: t4.x - n8 / 2, y: t4.y - o10 / 2 }, { x: t4.x + n8 / 2, y: t4.y - o10 / 2 }, { x: t4.x + n8 / 2, y: t4.y + o10 / 2 }, { x: t4.x - n8 / 2, y: t4.y + o10 / 2 }].map((e59) => J7(e59, t4, i8));
  return [{ minX: Math.min(...r9.map((e59) => e59.x)), minY: Math.min(...r9.map((e59) => e59.y)), maxX: Math.max(...r9.map((e59) => e59.x)), maxY: Math.max(...r9.map((e59) => e59.y)), layers: e54.layers, kind: "obstacle", obstacleKind: Q7(e54), connectionNames: e54.connectedTo, exactShape: { type: "polygon", points: r9 } }];
}
var tee = class {
  nodeIndices = [];
  priorities = [];
  get size() {
    return this.nodeIndices.length;
  }
  push(e54, t4) {
    let n8 = this.nodeIndices.length;
    for (this.nodeIndices.push(e54), this.priorities.push(t4);n8 > 0; ) {
      const e59 = n8 - 1 >> 1;
      if (this.priorities[e59] <= t4)
        break;
      this.swap(n8, e59), n8 = e59;
    }
  }
  pop() {
    const e54 = this.nodeIndices[0], t4 = this.nodeIndices.pop(), n8 = this.priorities.pop();
    if (this.nodeIndices.length === 0)
      return e54;
    this.nodeIndices[0] = t4, this.priorities[0] = n8;
    let o10 = 0;
    for (;; ) {
      const e59 = 2 * o10 + 1, t10 = e59 + 1;
      if (e59 >= this.nodeIndices.length)
        break;
      let n10 = e59;
      if (t10 < this.nodeIndices.length && this.priorities[t10] < this.priorities[e59] && (n10 = t10), this.priorities[o10] <= this.priorities[n10])
        break;
      this.swap(o10, n10), o10 = n10;
    }
    return e54;
  }
  swap(e54, t4) {
    [this.nodeIndices[e54], this.nodeIndices[t4]] = [this.nodeIndices[t4], this.nodeIndices[e54]], [this.priorities[e54], this.priorities[t4]] = [this.priorities[t4], this.priorities[e54]];
  }
};
var nee = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]];
var oee = ["#d53535", "#3478c8", "#8e44ad", "#15956f"];
var iee = class extends BaseSolver {
  problem;
  searchBounds;
  rows;
  columns;
  origin;
  nodes = [];
  open = new tee;
  bestCost = new Map;
  closed = new Set;
  baseStateCount;
  stateSpaceUpperBound;
  endLayerIndices;
  targetCell;
  segmentWidthCache = new Map;
  closedStateCount = 0;
  output = null;
  constructor(e54) {
    super(), this.problem = e54;
    const t4 = Math.max(e54.traceWidth, e54.viaDiameter) / 2 + e54.obstacleIndex.clearance, n8 = j7(Math.min(e54.start.x, e54.end.x) - e54.searchPadding, e54.bounds.minX + t4, e54.bounds.maxX - t4), o10 = j7(Math.max(e54.start.x, e54.end.x) + e54.searchPadding, e54.bounds.minX + t4, e54.bounds.maxX - t4), i8 = j7(Math.min(e54.start.y, e54.end.y) - e54.searchPadding, e54.bounds.minY + t4, e54.bounds.maxY - t4), r9 = j7(Math.max(e54.start.y, e54.end.y) + e54.searchPadding, e54.bounds.minY + t4, e54.bounds.maxY - t4), s7 = Math.floor((n8 - e54.gridOffset.x) / e54.gridSize) * e54.gridSize + e54.gridOffset.x, a9 = Math.floor((i8 - e54.gridOffset.y) / e54.gridSize) * e54.gridSize + e54.gridOffset.y;
    this.origin = { x: s7, y: a9 }, this.columns = Math.max(2, Math.floor((o10 - s7) / e54.gridSize) + 1), this.rows = Math.max(2, Math.floor((r9 - a9) / e54.gridSize) + 1), this.searchBounds = { minX: s7, minY: a9, maxX: s7 + (this.columns - 1) * e54.gridSize, maxY: a9 + (this.rows - 1) * e54.gridSize };
    const c5 = this.rows * this.columns * e54.layers.length * (e54.maxViaCount + 1);
    this.baseStateCount = c5, this.stateSpaceUpperBound = c5 * (this.rows * this.columns + 1), this.targetCell = this.pointToCell(e54.end), this.endLayerIndices = new Set(e54.endLayers.map((t10) => e54.layers.indexOf(t10)).filter((e59) => e59 >= 0));
    const l5 = this.pointToCell(e54.start);
    for (const t10 of e54.startLayers) {
      const n10 = e54.layers.indexOf(t10);
      if (n10 < 0 || this.endpointCollides(e54.start, n10))
        continue;
      const o11 = { ...l5, ...e54.start, layerIndex: n10, viaCount: 0, viaPoints: [], g: 0, f: this.heuristic(e54.start), parentIndex: -1 }, i9 = this.nodes.length;
      this.nodes.push(o11), this.open.push(i9, o11.f), this.bestCost.set(this.toStateIndex(o11), 0);
    }
    this.open.size !== 0 && this.endLayerIndices.size !== 0 || (this.failed = true, this.error = "No collision-free multilayer route endpoint"), this.MAX_ITERATIONS = Math.min(15000, Math.max(2000, 2 * c5)), this.stats = this.createStats();
  }
  getSolverName() {
    return `LayerAwareGridRouteSolver(${this.problem.gridSize.toFixed(3)}mm)`;
  }
  _step() {
    if (this.open.size === 0)
      return this.failed = true, void (this.error = "No collision-free multilayer grid route found");
    const e54 = this.open.pop(), t4 = this.nodes[e54], n8 = this.toStateIndex(t4);
    if (!this.closed.has(n8)) {
      if (this.closed.add(n8), this.closedStateCount++, t4.row === this.targetCell.row && t4.column === this.targetCell.column && this.endLayerIndices.has(t4.layerIndex) && t4.viaCount >= this.problem.minViaCount && !this.segmentCollides(t4, this.problem.end))
        return this.output = this.reconstructRoute(e54), this.solved = true, void (this.stats = this.createStats());
      this.expandPlanarMoves(e54, t4), this.expandViaMoves(e54, t4), this.stats = this.createStats();
    }
  }
  expandPlanarMoves(e54, t4) {
    for (const [n8, o10] of nee) {
      const i8 = t4.row + n8, r9 = t4.column + o10;
      if (i8 < 0 || i8 >= this.rows || r9 < 0 || r9 >= this.columns)
        continue;
      const s7 = this.cellToPoint(i8, r9), a9 = this.getSafeSegmentWidth(t4, s7);
      if (a9 <= 0)
        continue;
      const c5 = this.problem.gridSize * (n8 !== 0 && o10 !== 0 ? Math.SQRT2 : 1) * Math.max(1, (this.problem.traceWidth / a9) ** this.problem.neckPenaltyExponent);
      this.enqueueNode({ row: i8, column: r9, ...s7, layerIndex: t4.layerIndex, viaCount: t4.viaCount, viaPoints: t4.viaPoints, g: t4.g + c5, parentIndex: e54 });
    }
  }
  expandViaMoves(e54, t4) {
    if (t4.viaCount >= this.problem.maxViaCount)
      return;
    const n8 = 0.5 * this.problem.gridSize;
    if (z7(t4, this.problem.start) < n8 - 0.000000001 || z7(t4, this.problem.end) < n8 - 0.000000001)
      return;
    const o10 = t4.parentIndex >= 0 ? this.nodes[t4.parentIndex] : undefined;
    if (!o10 || o10.layerIndex === t4.layerIndex || !F7(o10, t4))
      for (let n10 = 0;n10 < this.problem.layers.length; n10++)
        n10 !== t4.layerIndex && (this.problem.obstacleIndex.collidesVia({ point: t4, layers: this.problem.layers, padDiameter: this.problem.viaDiameter, holeDiameter: this.problem.viaHoleDiameter, connectionNames: this.problem.connectionNames, ignoreTraceIndex: this.problem.ignoreTraceIndex, ignoreTraceIndices: this.problem.softTraceIndices, ignoreRouteRange: this.problem.ignoreRouteRange, obstacleClearance: this.problem.obstacleClearance, blockSameNetObstacles: true, sameNetObstacleClearance: 0, otherNewViaPoints: t4.viaPoints, fixedVias: this.problem.fixedVias }) || this.enqueueNode({ row: t4.row, column: t4.column, x: t4.x, y: t4.y, layerIndex: n10, viaCount: t4.viaCount + 1, viaPoints: [...t4.viaPoints, { x: t4.x, y: t4.y }], g: t4.g + this.problem.viaCost, parentIndex: e54 }));
  }
  enqueueNode(e54) {
    const t4 = this.toStateIndex(e54);
    if (this.closed.has(t4) || e54.g >= (this.bestCost.get(t4) ?? Number.POSITIVE_INFINITY))
      return;
    this.bestCost.set(t4, e54.g);
    const n8 = e54.g + this.heuristic(e54), o10 = this.nodes.length;
    this.nodes.push({ ...e54, f: n8 }), this.open.push(o10, n8);
  }
  endpointCollides(e54, t4) {
    return this.getSafeSegmentWidth({ ...e54, layerIndex: t4, viaCount: 0 }, e54) <= 0;
  }
  segmentCollides(e54, t4) {
    return this.getSafeSegmentWidth(e54, t4) <= 0;
  }
  getSafeSegmentWidth(e54, t4) {
    const n8 = this.problem.layers[e54.layerIndex], o10 = this.problem.startLayers.length === 1 && e54.viaCount === 0 && n8 === this.problem.originalStartLayer && z7(this.problem.start, e54) <= this.problem.maxStartNeckLength + 0.000000001 && z7(this.problem.start, t4) <= this.problem.maxStartNeckLength + 0.000000001, i8 = this.problem.endLayers.length === 1 && n8 === this.problem.originalEndLayer && z7(this.problem.end, e54) <= this.problem.maxEndNeckLength + 0.000000001 && z7(this.problem.end, t4) <= this.problem.maxEndNeckLength + 0.000000001, r9 = Math.max(o10 ? this.problem.startNeckWidth : 0, i8 ? this.problem.endNeckWidth : 0), s7 = [e54.x, e54.y, t4.x, t4.y, e54.layerIndex, e54.viaCount, r9].join(":"), a9 = this.segmentWidthCache.get(s7);
    if (a9 !== undefined)
      return a9;
    const c5 = (o11) => !this.problem.obstacleIndex.collides({ start: e54, end: t4, layer: n8, width: o11, connectionNames: this.problem.connectionNames, ignoreTraceIndex: this.problem.ignoreTraceIndex, ignoreTraceIndices: this.problem.softTraceIndices, ignoreRouteRange: this.problem.ignoreRouteRange, obstacleClearance: this.problem.obstacleClearance });
    let l5 = 0;
    if (o10 || i8) {
      const e59 = 0.025;
      let t10 = Math.ceil((r9 - 0.000000001) / e59), n10 = Math.floor((this.problem.traceWidth + 0.000000001) / e59);
      for (;t10 <= n10; ) {
        const o11 = Math.floor((t10 + n10) / 2), i9 = Number((o11 * e59).toFixed(6));
        c5(i9) ? (l5 = i9, t10 = o11 + 1) : n10 = o11 - 1;
      }
      l5 < r9 - 0.000000001 && c5(r9) && (l5 = r9);
    } else
      l5 = c5(this.problem.traceWidth) ? this.problem.traceWidth : 0;
    return this.segmentWidthCache.set(s7, l5), l5;
  }
  reconstructRoute(e54) {
    const t4 = [];
    let n8 = e54;
    for (;n8 >= 0; ) {
      const e59 = this.nodes[n8];
      t4.push(e59), n8 = e59.parentIndex;
    }
    t4.reverse();
    const o10 = t4[t4.length - 1];
    F7(o10, this.problem.end) || t4.push({ ...o10, ...this.problem.end, row: this.targetCell.row, column: this.targetCell.column, parentIndex: -1 });
    const i8 = [];
    let r9 = [t4[0]];
    for (let e59 = 1;e59 < t4.length; e59++) {
      const n10 = t4[e59 - 1], o11 = t4[e59];
      o11.layerIndex !== n10.layerIndex ? (i8.push(r9), r9 = [o11]) : r9.push(o11);
    }
    i8.push(r9);
    const s7 = [];
    for (let e59 = 0;e59 < i8.length; e59++) {
      const t10 = this.simplifySection(i8[e59]), n10 = t10.slice(0, -1).map((e60, n11) => this.getSafeSegmentWidth(e60, t10[n11 + 1])), o11 = t10.map((e60, o12) => ({ route_type: "wire", x: e60.x, y: e60.y, layer: this.problem.layers[e60.layerIndex], width: n10.length === 0 ? Math.min(this.problem.startNeckWidth, this.problem.endNeckWidth) : o12 === 0 ? n10[0] : o12 === t10.length - 1 ? n10[n10.length - 1] : Math.min(n10[o12 - 1], n10[o12]) }));
      s7.push(...o11);
      const r10 = i8[e59 + 1];
      if (r10) {
        const e60 = this.problem.layers[t10.at(-1).layerIndex], n11 = this.problem.layers[r10[0].layerIndex], o12 = t10.at(-1);
        s7.push({ route_type: "via", x: o12.x, y: o12.y, from_layer: e60, to_layer: n11, via_diameter: this.problem.viaDiameter, via_hole_diameter: this.problem.viaHoleDiameter });
      }
    }
    return { route: s7, traceWidth: this.problem.traceWidth, startNeckWidth: this.problem.startNeckWidth, endNeckWidth: this.problem.endNeckWidth, gridSize: this.problem.gridSize, gridOffset: this.problem.gridOffset, viaCount: i8.length - 1 };
  }
  simplifySection(e54) {
    return e54.length <= 2 ? e54 : this.problem.neckPenaltyExponent > 1 ? this.simplifyStrictSection(e54) : this.simplifyWidthPreservingSection(e54);
  }
  simplifyStrictSection(e54) {
    const t4 = e54.slice(0, -1).map((t10, n10) => this.getSafeSegmentWidth(t10, e54[n10 + 1])), n8 = [0];
    for (let o11 = 0;o11 < t4.length; o11++)
      n8.push(n8[o11] + this.getWidthPenalizedCost(e54[o11], e54[o11 + 1], t4[o11]));
    const o10 = [e54[0]];
    let i8 = 0;
    for (;i8 < e54.length - 1; ) {
      let r9 = e54.length - 1;
      for (;r9 > i8 + 1 && !this.shortcutPreservesRouteQuality(e54, t4, n8, i8, r9); )
        r9--;
      o10.push(e54[r9]), i8 = r9;
    }
    return this.removeRedundantCollinearPoints(o10);
  }
  shortcutPreservesRouteQuality(e54, t4, n8, o10, i8) {
    const r9 = this.getSafeSegmentWidth(e54[o10], e54[i8]);
    if (r9 <= 0)
      return false;
    let s7 = Number.POSITIVE_INFINITY;
    for (let e59 = o10;e59 < i8; e59++)
      s7 = Math.min(s7, t4[e59]);
    const a9 = n8[i8] - n8[o10];
    return r9 >= s7 - 0.000000001 && this.getWidthPenalizedCost(e54[o10], e54[i8], r9) <= a9 + 0.000000001;
  }
  getWidthPenalizedCost(e54, t4, n8) {
    return z7(e54, t4) * Math.max(1, (this.problem.traceWidth / n8) ** this.problem.neckPenaltyExponent);
  }
  simplifyWidthPreservingSection(e54) {
    const t4 = e54.slice(0, -1).map((t10, n10) => this.getSafeSegmentWidth(t10, e54[n10 + 1])), n8 = [0];
    for (let o11 = 0;o11 < t4.length; o11++)
      n8.push(n8[o11] + z7(e54[o11], e54[o11 + 1]) * Math.max(1, (this.problem.traceWidth / t4[o11]) ** this.problem.neckPenaltyExponent));
    const o10 = new Float64Array(e54.length).fill(Number.POSITIVE_INFINITY), i8 = new Float64Array(e54.length).fill(Number.POSITIVE_INFINITY), r9 = new Int32Array(e54.length).fill(-1);
    o10[0] = 0, i8[0] = 0;
    for (let s9 = 1;s9 < e54.length; s9++) {
      let a10 = Number.POSITIVE_INFINITY;
      for (let c5 = s9 - 1;c5 >= 0; c5--) {
        if (a10 = Math.min(a10, t4[c5]), !Number.isFinite(o10[c5]))
          continue;
        const l5 = this.getSafeSegmentWidth(e54[c5], e54[s9]);
        if (l5 < a10 - 0.000000001)
          continue;
        const h5 = z7(e54[c5], e54[s9]);
        if (h5 * Math.max(1, (this.problem.traceWidth / l5) ** this.problem.neckPenaltyExponent) > n8[s9] - n8[c5] + 0.000000001)
          continue;
        const d9 = o10[c5] + h5 * Math.max(0, this.problem.traceWidth - l5), u9 = i8[c5] + h5;
        (d9 < o10[s9] - 0.000000001 || Math.abs(d9 - o10[s9]) <= 0.000000001 && u9 < i8[s9] - 0.000000001) && (o10[s9] = d9, i8[s9] = u9, r9[s9] = c5);
      }
    }
    const s7 = [];
    let a9 = e54.length - 1;
    for (;a9 >= 0 && (s7.push(e54[a9]), a9 !== 0); )
      if (a9 = r9[a9], a9 < 0)
        return e54;
    return s7.reverse(), this.removeRedundantCollinearPoints(s7);
  }
  removeRedundantCollinearPoints(e54) {
    return e54.filter((e59, t4, n8) => {
      if (t4 === 0 || t4 === n8.length - 1)
        return true;
      const o10 = n8[t4 - 1], i8 = n8[t4 + 1], r9 = (e59.x - o10.x) * (i8.y - e59.y) - (e59.y - o10.y) * (i8.x - e59.x), s7 = Math.abs(this.getSafeSegmentWidth(o10, e59) - this.getSafeSegmentWidth(e59, i8)) < 0.000000001;
      return Math.abs(r9) > 0.00000001 || !s7;
    });
  }
  pointToCell(e54) {
    return { column: j7(Math.round((e54.x - this.origin.x) / this.problem.gridSize), 0, this.columns - 1), row: j7(Math.round((e54.y - this.origin.y) / this.problem.gridSize), 0, this.rows - 1) };
  }
  cellToPoint(e54, t4) {
    return { x: this.origin.x + t4 * this.problem.gridSize, y: this.origin.y + e54 * this.problem.gridSize };
  }
  toStateIndex(e54) {
    const t4 = ((e54.viaCount * this.problem.layers.length + e54.layerIndex) * this.rows + e54.row) * this.columns + e54.column;
    if (e54.viaCount !== 1 || e54.viaPoints.length === 0 || z7(e54, e54.viaPoints[0]) >= this.problem.viaHoleDiameter + this.problem.obstacleIndex.minViaHoleEdgeToViaHoleEdgeClearance - 0.000000001)
      return t4;
    const n8 = this.pointToCell(e54.viaPoints[0]);
    return t4 + (1 + n8.row * this.columns + n8.column) * this.baseStateCount;
  }
  heuristic(e54) {
    return z7(e54, this.problem.end);
  }
  createStats() {
    return { phase: "layer-aware-grid-search", gridSize: this.problem.gridSize, traceWidth: this.problem.traceWidth, startNeckWidth: this.problem.startNeckWidth, endNeckWidth: this.problem.endNeckWidth, maxViaCount: this.problem.maxViaCount, minViaCount: this.problem.minViaCount, openStates: this.open.size, closedStates: this.closedStateCount, trackedStates: this.bestCost.size, stateSpaceUpperBound: this.stateSpaceUpperBound };
  }
  computeProgress() {
    return Math.min(0.99, this.iterations / this.MAX_ITERATIONS);
  }
  getOutput() {
    return this.output;
  }
  getConstructorParams() {
    const { obstacleIndex: e54, ...t4 } = this.problem;
    return [t4];
  }
  visualize() {
    const e54 = this.nodes.filter((e59) => this.closed.has(this.toStateIndex(e59))).slice(-2000).map((e59) => ({ x: e59.x, y: e59.y, color: `${oee[e59.layerIndex % oee.length]}55` })), t4 = [], n8 = [], o10 = this.output?.route ?? [];
    for (let e59 = 0;e59 < o10.length - 1; e59++) {
      const i8 = o10[e59], r9 = o10[e59 + 1];
      if (i8?.route_type === "wire" && r9?.route_type === "wire" && i8.layer === r9.layer) {
        const e60 = this.problem.layers.indexOf(i8.layer);
        t4.push({ points: [i8, r9], strokeColor: oee[e60 % oee.length] ?? "#333", strokeWidth: i8.width });
      }
      i8?.route_type === "via" && n8.push({ center: i8, radius: (i8.via_diameter ?? this.problem.viaDiameter) / 2, fill: "#d4a017" });
    }
    return { coordinateSystem: "cartesian", title: this.getSolverName(), rects: [{ center: { x: (this.searchBounds.minX + this.searchBounds.maxX) / 2, y: (this.searchBounds.minY + this.searchBounds.maxY) / 2 }, width: this.searchBounds.maxX - this.searchBounds.minX, height: this.searchBounds.maxY - this.searchBounds.minY, stroke: "#777" }], points: [...e54, { ...this.problem.start, color: "green", label: "reroute start" }, { ...this.problem.end, color: "purple", label: "reroute target" }], lines: t4, circles: n8, texts: [] };
  }
};
var aee = [{ direction: 1, strength: 0.7 }, { direction: -1, strength: 0.7 }, { direction: 1, strength: 1 }, { direction: -1, strength: 1 }];
var cee = (e54, t4, n8) => {
  const o10 = n8.x - t4.x, i8 = n8.y - t4.y, r9 = o10 * o10 + i8 * i8;
  if (r9 <= 0.000000000001)
    return { ...t4 };
  const s7 = j7(((e54.x - t4.x) * o10 + (e54.y - t4.y) * i8) / r9, 0, 1);
  return { x: t4.x + o10 * s7, y: t4.y + i8 * s7 };
};
var lee = class extends BaseSolver {
  problem;
  phase = "prepare-candidate";
  variantCursor = 0;
  relaxationIteration = 0;
  candidatePoints = [];
  sampledPoints;
  output = null;
  constructor(e54) {
    super(), this.problem = e54, this.sampledPoints = this.sampleRoute(), this.MAX_ITERATIONS = 100, this.stats = this.createStats();
  }
  getSolverName() {
    return "ElasticTracePushSolver";
  }
  _step() {
    switch (this.phase) {
      case "prepare-candidate":
        if (this.variantCursor >= aee.length)
          return this.failed = true, void (this.error = "No collision-free elastic displacement found");
        this.candidatePoints = this.sampledPoints.map((e54) => ({ ...e54 })), this.relaxationIteration = 0, this.phase = "relax-candidate";
        break;
      case "relax-candidate":
        this.relaxCandidate(), this.relaxationIteration++, this.relaxationIteration >= 10 && (this.phase = "validate-candidate");
        break;
      case "validate-candidate": {
        const e54 = this.simplifyCandidate(this.candidatePoints);
        this.pathCollides(e54) ? (this.variantCursor++, this.phase = "prepare-candidate") : (this.output = { points: e54, traceWidth: this.problem.traceWidth }, this.phase = "complete");
        break;
      }
      case "complete":
        this.solved = true;
    }
    this.stats = this.createStats();
  }
  sampleRoute() {
    const e54 = [], t4 = j7(2 * this.problem.traceWidth, 0.2, 0.45), n8 = this.problem.trace.route;
    for (let o10 = this.problem.range.startIndex;o10 < this.problem.range.endIndex; o10++) {
      const i8 = n8[o10], r9 = n8[o10 + 1];
      if (i8?.route_type !== "wire" || r9?.route_type !== "wire" || i8.layer !== r9.layer)
        continue;
      e54.length === 0 && e54.push({ x: i8.x, y: i8.y });
      const s7 = z7(i8, r9), a9 = Math.max(1, Math.ceil(s7 / t4));
      for (let t10 = 1;t10 <= a9; t10++) {
        const n10 = t10 / a9;
        e54.push({ x: i8.x + (r9.x - i8.x) * n10, y: i8.y + (r9.y - i8.y) * n10 });
      }
    }
    return e54;
  }
  relaxCandidate() {
    const e54 = aee[this.variantCursor], t4 = this.candidatePoints.map((e59) => ({ ...e59 })), n8 = new Uint8Array(this.candidatePoints.length);
    for (let o10 = 1;o10 < this.candidatePoints.length - 1; o10++) {
      const i8 = this.candidatePoints[o10], r9 = this.findNearestCorridorSegment(i8);
      if (!r9)
        continue;
      const s7 = z7(r9.segment.start, r9.segment.end);
      if (s7 <= 0.000000001)
        continue;
      const a9 = r9.segment.width / 2 + this.problem.traceWidth / 2 + this.problem.obstacleIndex.clearance + 0.025;
      if (r9.distance > a9 + 0.35)
        continue;
      const c5 = { x: (r9.segment.start.y - r9.segment.end.y) / s7 * e54.direction, y: (r9.segment.end.x - r9.segment.start.x) / s7 * e54.direction }, l5 = a9 - ((i8.x - r9.closest.x) * c5.x + (i8.y - r9.closest.y) * c5.y);
      if (l5 <= 0)
        continue;
      const h5 = Math.min(0.35, l5 * e54.strength);
      t4[o10] = { x: i8.x + c5.x * h5, y: i8.y + c5.y * h5 }, n8[o10] = 1;
    }
    for (let e59 = 1;e59 < t4.length - 1; e59++) {
      if (!n8[e59])
        continue;
      const o10 = t4[e59 - 1], i8 = t4[e59], r9 = t4[e59 + 1];
      t4[e59] = { x: 0.85 * i8.x + (o10.x + r9.x) / 2 * 0.15, y: 0.85 * i8.y + (o10.y + r9.y) / 2 * 0.15 };
    }
    this.candidatePoints = t4;
  }
  findNearestCorridorSegment(e54) {
    let t4;
    for (const n8 of this.problem.corridor) {
      if (n8.layer !== this.problem.layer)
        continue;
      const o10 = cee(e54, n8.start, n8.end), i8 = z7(e54, o10);
      (!t4 || i8 < t4.distance) && (t4 = { segment: n8, closest: o10, distance: i8 });
    }
    return t4;
  }
  simplifyCandidate(e54) {
    if (e54.length <= 2)
      return e54;
    const t4 = [e54[0]];
    let n8 = 0;
    for (;n8 < e54.length - 1; ) {
      let o10 = e54.length - 1;
      for (;o10 > n8 + 1 && this.segmentCollides(e54[n8], e54[o10]); )
        o10--;
      t4.push(e54[o10]), n8 = o10;
    }
    return t4.filter((e59, t10, n10) => t10 === 0 || !F7(e59, n10[t10 - 1]));
  }
  pathCollides(e54) {
    if (e54.length < 2)
      return true;
    for (let t4 = 0;t4 < e54.length - 1; t4++)
      if (this.segmentCollides(e54[t4], e54[t4 + 1]))
        return true;
    return false;
  }
  segmentCollides(e54, t4) {
    return this.problem.obstacleIndex.collides({ start: e54, end: t4, layer: this.problem.layer, width: this.problem.traceWidth, connectionNames: this.problem.connectionNames, ignoreTraceIndex: -1 });
  }
  createStats() {
    const e54 = aee[this.variantCursor];
    return { phase: this.phase, direction: e54?.direction, strength: e54?.strength, variantCursor: this.variantCursor, relaxationIteration: this.relaxationIteration, sampledPointCount: this.sampledPoints.length };
  }
  computeProgress() {
    return Math.min(0.99, (this.variantCursor + this.relaxationIteration / 12) / aee.length);
  }
  getOutput() {
    return this.output;
  }
  getConstructorParams() {
    return [this.problem];
  }
  visualize() {
    return { coordinateSystem: "cartesian", title: `Elastic trace push: ${this.phase}`, lines: [...this.problem.corridor.map((e54) => ({ points: [e54.start, e54.end], strokeColor: "rgba(255, 128, 0, 0.6)", strokeWidth: e54.width })), ...this.candidatePoints.length > 1 ? [{ points: this.candidatePoints, strokeColor: "#1769d2", strokeWidth: this.problem.traceWidth }] : []], points: [], rects: [], circles: [], texts: [] };
  }
};
var dee = (e54, t4) => {
  const n8 = Math.abs(t4.x - e54.x), o10 = Math.abs(t4.y - e54.y);
  return n8 <= L7 || o10 <= L7 || Math.abs(n8 - o10) <= L7;
};
var uee = (e54) => {
  let t4 = 0;
  for (let n8 = 0;n8 < e54.length - 1; n8++)
    dee(e54[n8], e54[n8 + 1]) || t4++;
  return t4;
};
var pee = (e54) => {
  let t4 = 0;
  for (let n8 = 0;n8 < e54.length - 1; n8++)
    t4 += z7(e54[n8], e54[n8 + 1]);
  return t4;
};
var mee = (e54) => e54.filter((t4, n8) => n8 === 0 || !F7(t4, e54[n8 - 1]));
var gee = (e54, t4) => {
  const n8 = t4.x - e54.x, o10 = t4.y - e54.y, i8 = Math.abs(n8), r9 = Math.abs(o10), s7 = Math.sign(n8), a9 = Math.sign(o10), c5 = [];
  dee(e54, t4) && c5.push([e54, t4]), c5.push([e54, { x: t4.x, y: e54.y }, t4], [e54, { x: e54.x, y: t4.y }, t4]), i8 >= r9 ? c5.push([e54, { x: t4.x - s7 * r9, y: e54.y }, t4], [e54, { x: e54.x + s7 * r9, y: t4.y }, t4]) : c5.push([e54, { x: e54.x, y: t4.y - a9 * i8 }, t4], [e54, { x: t4.x, y: e54.y + a9 * i8 }, t4]);
  const l5 = new Map;
  for (const e59 of c5) {
    const t10 = mee(e59);
    if (t10.length < 2 || t10.some((e60, n11) => n11 < t10.length - 1 && !dee(e60, t10[n11 + 1])))
      continue;
    const n10 = t10.map((e60) => `${e60.x.toFixed(6)},${e60.y.toFixed(6)}`).join(";");
    l5.set(n10, t10);
  }
  return [...l5.values()].sort((e59, t10) => pee(e59) - pee(t10) || e59.length - t10.length);
};
var fee = class {
  nodeIndices = [];
  priorities = [];
  get size() {
    return this.nodeIndices.length;
  }
  push(e54, t4) {
    let n8 = this.nodeIndices.length;
    for (this.nodeIndices.push(e54), this.priorities.push(t4);n8 > 0; ) {
      const e59 = n8 - 1 >> 1;
      if (this.priorities[e59] <= t4)
        break;
      this.swap(n8, e59), n8 = e59;
    }
  }
  pop() {
    const e54 = this.nodeIndices[0], t4 = this.nodeIndices.pop(), n8 = this.priorities.pop();
    if (this.nodeIndices.length === 0)
      return e54;
    this.nodeIndices[0] = t4, this.priorities[0] = n8;
    let o10 = 0;
    for (;; ) {
      const e59 = 2 * o10 + 1, t10 = e59 + 1;
      if (e59 >= this.nodeIndices.length)
        break;
      let n10 = e59;
      if (t10 < this.nodeIndices.length && this.priorities[t10] < this.priorities[e59] && (n10 = t10), this.priorities[o10] <= this.priorities[n10])
        break;
      this.swap(o10, n10), o10 = n10;
    }
    return e54;
  }
  swap(e54, t4) {
    [this.nodeIndices[e54], this.nodeIndices[t4]] = [this.nodeIndices[t4], this.nodeIndices[e54]], [this.priorities[e54], this.priorities[t4]] = [this.priorities[t4], this.priorities[e54]];
  }
};
var _ee = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]];
var yee = class extends BaseSolver {
  problem;
  searchBounds;
  rows;
  columns;
  origin;
  nodes = [];
  open = new fee;
  bestCost;
  closed;
  closedCellCount = 0;
  targetCell;
  output = null;
  collisionChecker;
  constructor(e54) {
    super(), this.problem = e54;
    const t4 = e54.traceWidth / 2 + e54.obstacleIndex.clearance, n8 = j7(Math.min(e54.start.x, e54.end.x) - e54.searchPadding, e54.bounds.minX + t4, e54.bounds.maxX - t4), o10 = j7(Math.max(e54.start.x, e54.end.x) + e54.searchPadding, e54.bounds.minX + t4, e54.bounds.maxX - t4), i8 = j7(Math.min(e54.start.y, e54.end.y) - e54.searchPadding, e54.bounds.minY + t4, e54.bounds.maxY - t4), r9 = j7(Math.max(e54.start.y, e54.end.y) + e54.searchPadding, e54.bounds.minY + t4, e54.bounds.maxY - t4), s7 = Math.floor((n8 - e54.gridOffset.x) / e54.gridSize) * e54.gridSize + e54.gridOffset.x, a9 = Math.floor((i8 - e54.gridOffset.y) / e54.gridSize) * e54.gridSize + e54.gridOffset.y;
    if (this.origin = { x: s7, y: a9 }, this.columns = Math.max(2, Math.floor((o10 - s7) / e54.gridSize) + 1), this.rows = Math.max(2, Math.floor((r9 - a9) / e54.gridSize) + 1), this.searchBounds = { minX: s7, minY: a9, maxX: s7 + (this.columns - 1) * e54.gridSize, maxY: a9 + (this.rows - 1) * e54.gridSize }, this.bestCost = new Float64Array(this.rows * this.columns).fill(Number.POSITIVE_INFINITY), this.closed = new Uint8Array(this.rows * this.columns), this.endpointCollides(e54.start) || this.endpointCollides(e54.end))
      return this.failed = true, this.error = "Grid-route endpoint violates obstacle clearance", this.targetCell = { row: 0, column: 0 }, this.MAX_ITERATIONS = 1, void (this.stats = this.createStats());
    this.collisionChecker = e54.obstacleIndex.createSegmentCollisionChecker({ start: e54.start, end: e54.end, layer: e54.layer, width: e54.traceWidth, connectionNames: e54.connectionNames, ignoreTraceIndex: e54.ignoreTraceIndex, ignoreRouteRange: e54.ignoreRouteRange, obstacleClearance: e54.obstacleClearance }, { minX: Math.min(this.searchBounds.minX, e54.start.x, e54.end.x), minY: Math.min(this.searchBounds.minY, e54.start.y, e54.end.y), maxX: Math.max(this.searchBounds.maxX, e54.start.x, e54.end.x), maxY: Math.max(this.searchBounds.maxY, e54.start.y, e54.end.y) });
    const c5 = this.pointToCell(e54.start);
    this.targetCell = this.pointToCell(e54.end);
    const l5 = { ...c5, x: e54.start.x, y: e54.start.y, g: 0, f: this.heuristic(e54.start), parentIndex: -1 };
    this.nodes.push(l5), this.open.push(0, l5.f), this.bestCost[this.toFlatIndex(c5.row, c5.column)] = 0, this.MAX_ITERATIONS = Math.min(5000, Math.max(1000, this.rows * this.columns * 2)), this.stats = this.createStats();
  }
  endpointCollides(e54) {
    return this.problem.obstacleIndex.collides({ start: e54, end: e54, layer: this.problem.layer, width: this.problem.traceWidth, connectionNames: this.problem.connectionNames, ignoreTraceIndex: this.problem.ignoreTraceIndex, ignoreRouteRange: this.problem.ignoreRouteRange, obstacleClearance: this.problem.obstacleClearance });
  }
  getSolverName() {
    return `ObstacleAwareGridRouteSolver(${this.problem.gridSize.toFixed(3)}mm)`;
  }
  _step() {
    if (this.open.size === 0)
      return this.failed = true, void (this.error = "No collision-free grid route found");
    const e54 = this.open.pop(), t4 = this.nodes[e54], n8 = this.toFlatIndex(t4.row, t4.column);
    if (!this.closed[n8]) {
      if (this.closed[n8] = 1, this.closedCellCount++, t4.row === this.targetCell.row && t4.column === this.targetCell.column && this.getAllowedConnector(t4, this.problem.end) !== null)
        return this.output = { points: this.reconstructPath(e54), traceWidth: this.problem.traceWidth, gridSize: this.problem.gridSize, gridOffset: this.problem.gridOffset }, this.solved = true, void (this.stats = this.createStats());
      for (const [n10, o10] of _ee) {
        const i8 = t4.row + n10, r9 = t4.column + o10;
        if (i8 < 0 || i8 >= this.rows || r9 < 0 || r9 >= this.columns)
          continue;
        const s7 = this.toFlatIndex(i8, r9);
        if (this.closed[s7])
          continue;
        const a9 = t4.parentIndex === -1 && this.problem.requireOctilinear;
        let c5 = this.problem.gridSize * (n10 !== 0 && o10 !== 0 ? Math.SQRT2 : 1);
        if (!a9 && t4.g + c5 >= this.bestCost[s7])
          continue;
        const l5 = this.cellToPoint(i8, r9), h5 = this.getAllowedConnector(t4, l5);
        if (h5 === null)
          continue;
        a9 && (c5 = pee(h5));
        const d9 = t4.g + c5;
        if (d9 >= this.bestCost[s7])
          continue;
        this.bestCost[s7] = d9;
        const u9 = d9 + this.heuristic(l5), p9 = this.nodes.length;
        this.nodes.push({ row: i8, column: r9, ...l5, g: d9, f: u9, parentIndex: e54 }), this.open.push(p9, u9);
      }
      this.stats = this.createStats();
    }
  }
  segmentCollides(e54, t4) {
    return this.collisionChecker(e54, t4);
  }
  getAllowedConnector(e54, t4) {
    return this.problem.requireOctilinear && (("parentIndex" in e54) && e54.parentIndex === -1 || F7(t4, this.problem.end)) ? gee(e54, t4).find((e59) => e59.slice(0, -1).every((t10, n8) => !this.segmentCollides(t10, e59[n8 + 1]))) ?? null : this.segmentCollides(e54, t4) ? null : [e54, t4];
  }
  pointToCell(e54) {
    return { column: j7(Math.round((e54.x - this.origin.x) / this.problem.gridSize), 0, this.columns - 1), row: j7(Math.round((e54.y - this.origin.y) / this.problem.gridSize), 0, this.rows - 1) };
  }
  cellToPoint(e54, t4) {
    return { x: this.origin.x + t4 * this.problem.gridSize, y: this.origin.y + e54 * this.problem.gridSize };
  }
  toFlatIndex(e54, t4) {
    return e54 * this.columns + t4;
  }
  heuristic(e54) {
    return Math.hypot(this.problem.end.x - e54.x, this.problem.end.y - e54.y);
  }
  reconstructPath(e54) {
    const t4 = [];
    let n8 = e54;
    for (;n8 >= 0; ) {
      const e59 = this.nodes[n8];
      t4.push({ x: e59.x, y: e59.y }), n8 = e59.parentIndex;
    }
    if (t4.reverse(), F7(t4[0], this.problem.start) || t4.unshift({ ...this.problem.start }), F7(t4[t4.length - 1], this.problem.end) || t4.push({ ...this.problem.end }), this.problem.requireOctilinear) {
      const e59 = [t4[0]];
      for (let n10 = 0;n10 < t4.length - 1; n10++) {
        const o11 = t4[n10], i9 = t4[n10 + 1], r9 = n10 === 0 || n10 === t4.length - 2 ? this.getAllowedConnector(n10 === 0 ? { ...o11, parentIndex: -1 } : o11, i9) : [o11, i9];
        if (!r9)
          return t4;
        e59.push(...r9.slice(1));
      }
      return e59.filter((e60, t10, n10) => {
        if (t10 === 0 || t10 === n10.length - 1)
          return true;
        const o11 = n10[t10 - 1], i9 = n10[t10 + 1], r9 = (e60.x - o11.x) * (i9.y - e60.y) - (e60.y - o11.y) * (i9.x - e60.x);
        return Math.abs(r9) > 0.00000001 || !dee(o11, i9);
      });
    }
    const o10 = [t4[0]];
    let i8 = 0;
    for (;i8 < t4.length - 1; ) {
      let e59 = t4.length - 1;
      for (;e59 > i8 + 1 && this.segmentCollides(t4[i8], t4[e59]); )
        e59--;
      o10.push(t4[e59]), i8 = e59;
    }
    return o10.filter((e59, t10, n10) => {
      if (t10 === 0 || t10 === n10.length - 1)
        return true;
      const o11 = n10[t10 - 1], i9 = n10[t10 + 1], r9 = (e59.x - o11.x) * (i9.y - e59.y) - (e59.y - o11.y) * (i9.x - e59.x);
      return Math.abs(r9) > 0.00000001;
    });
  }
  createStats() {
    return { phase: "obstacle-aware-grid-search", gridSize: this.problem.gridSize, traceWidth: this.problem.traceWidth, gridOffset: this.problem.gridOffset, openCells: this.open.size, closedCells: this.closedCellCount, gridCells: this.rows * this.columns };
  }
  computeProgress() {
    return Math.min(0.99, this.iterations / this.MAX_ITERATIONS);
  }
  getOutput() {
    return this.output;
  }
  getConstructorParams() {
    const { obstacleIndex: e54, ...t4 } = this.problem;
    return [t4];
  }
  visualize() {
    const e54 = this.nodes.filter((e59) => this.closed[this.toFlatIndex(e59.row, e59.column)]).slice(-2000).map((e59) => ({ x: e59.x, y: e59.y, color: "rgba(0,90,255,0.22)" })), t4 = this.output?.points ?? [];
    return { coordinateSystem: "cartesian", title: this.getSolverName(), rects: [{ center: { x: (this.searchBounds.minX + this.searchBounds.maxX) / 2, y: (this.searchBounds.minY + this.searchBounds.maxY) / 2 }, width: this.searchBounds.maxX - this.searchBounds.minX, height: this.searchBounds.maxY - this.searchBounds.minY, stroke: "#777" }], points: [...e54, { ...this.problem.start, color: "green", label: "reroute start" }, { ...this.problem.end, color: "purple", label: "reroute target" }], lines: t4.length > 1 ? [{ points: t4, strokeColor: "#00a050", strokeWidth: this.problem.traceWidth }] : [], circles: [], texts: [] };
  }
};
var bee = [Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array];
var xee = class e59 {
  static from(t4, n8 = 0) {
    if (n8 % 8 != 0)
      throw new Error("byteOffset must be 8-byte aligned.");
    if (!t4 || t4.byteLength === undefined || "buffer" in t4)
      throw new Error("Data must be an instance of ArrayBuffer or SharedArrayBuffer.");
    const [o10, i8] = new Uint8Array(t4, n8 + 0, 2);
    if (o10 !== 251)
      throw new Error("Data does not appear to be in a Flatbush format.");
    const r9 = i8 >> 4;
    if (r9 !== 3)
      throw new Error(`Got v${r9} data when expected v3.`);
    const s7 = bee[15 & i8];
    if (!s7)
      throw new Error("Unrecognized array type.");
    const [a9] = new Uint16Array(t4, n8 + 2, 1), [c5] = new Uint32Array(t4, n8 + 4, 1);
    return new e59(c5, a9, s7, undefined, t4, n8);
  }
  constructor(e54, t4 = 16, n8 = Float64Array, o10 = ArrayBuffer, i8, r9 = 0) {
    if (e54 === undefined)
      throw new Error("Missing required argument: numItems.");
    if (isNaN(e54) || e54 <= 0)
      throw new Error(`Unexpected numItems value: ${e54}.`);
    this.numItems = +e54, this.nodeSize = Math.min(Math.max(+t4, 2), 65535), this.byteOffset = r9;
    let s7 = e54, a9 = s7;
    this._levelBounds = [4 * s7];
    do {
      s7 = Math.ceil(s7 / this.nodeSize), a9 += s7, this._levelBounds.push(4 * a9);
    } while (s7 !== 1);
    this.ArrayType = n8, this.IndexArrayType = a9 < 16384 ? Uint16Array : Uint32Array;
    const c5 = bee.indexOf(n8), l5 = 4 * a9 * n8.BYTES_PER_ELEMENT;
    if (c5 < 0)
      throw new Error(`Unexpected typed array class: ${n8}.`);
    const h5 = n8, d9 = this.IndexArrayType;
    if (i8)
      this.data = i8, this._boxes = new h5(i8, r9 + 8, 4 * a9), this._indices = new d9(i8, r9 + 8 + l5, a9), this._pos = 4 * a9, 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 {
      const n10 = this.data = new o10(8 + l5 + a9 * this.IndexArrayType.BYTES_PER_ELEMENT);
      this._boxes = new h5(n10, 8, 4 * a9), this._indices = new d9(n10, 8 + l5, a9), this._pos = 0, this.minX = 1 / 0, this.minY = 1 / 0, this.maxX = -1 / 0, this.maxY = -1 / 0, new Uint8Array(n10, 0, 2).set([251, 48 + c5]), new Uint16Array(n10, 2, 1)[0] = t4, new Uint32Array(n10, 4, 1)[0] = e54;
    }
    this._queue = new R;
  }
  add(e54, t4, n8 = e54, o10 = t4) {
    const i8 = this._pos, r9 = i8 >> 2, s7 = this._boxes;
    return this._indices[r9] = r9, s7[i8] = e54, s7[i8 + 1] = t4, s7[i8 + 2] = n8, s7[i8 + 3] = o10, this._pos = i8 + 4, e54 < this.minX && (this.minX = e54), t4 < this.minY && (this.minY = t4), n8 > this.maxX && (this.maxX = n8), o10 > this.maxY && (this.maxY = o10), r9;
  }
  finish() {
    if (this._pos >> 2 !== this.numItems)
      throw new Error(`Added ${this._pos >> 2} items when expected ${this.numItems}.`);
    const e54 = this._boxes;
    if (this.numItems <= this.nodeSize)
      return e54[this._pos++] = this.minX, e54[this._pos++] = this.minY, e54[this._pos++] = this.maxX, void (e54[this._pos++] = this.maxY);
    const { numItems: t4, minX: n8, minY: o10, nodeSize: i8, _indices: r9, _levelBounds: s7 } = this, a9 = this.maxX - n8 || 1, c5 = this.maxY - o10 || 1, l5 = new Int32Array(t4), h5 = 65535 / a9, d9 = 65535 / c5;
    for (let i9 = 0, r10 = 0;i9 < t4; i9++) {
      const t10 = e54[r10++], s9 = e54[r10++], a10 = h5 * ((t10 + e54[r10++]) / 2 - n8) | 0, c9 = d9 * ((s9 + e54[r10++]) / 2 - o10) | 0;
      l5[i9] = See(a10, c9);
    }
    (function(e60, t10, n10, o11, i9, r10) {
      const s9 = [o11, i9];
      for (;s9.length; ) {
        const o12 = s9.pop() || 0, i10 = s9.pop() || 0;
        if (o12 - i10 <= r10 && Math.floor(i10 / r10) >= Math.floor(o12 / r10))
          continue;
        const a10 = e60[i10], c9 = e60[i10 + o12 >> 1], l10 = e60[o12], h9 = a10 > c9 != a10 > l10 ? a10 : c9 < a10 != c9 < l10 ? c9 : l10;
        let d10 = i10 - 1, u10 = o12 + 1;
        for (;; ) {
          do {
            d10++;
          } while (e60[d10] < h9);
          do {
            u10--;
          } while (e60[u10] > h9);
          if (d10 >= u10)
            break;
          Iee(e60, t10, n10, d10, u10);
        }
        s9.push(i10, u10, u10 + 1, o12);
      }
    })(l5, e54, r9, 0, t4 - 1, i8);
    let u9 = 4 * t4;
    for (let t10 = 0, n10 = 0;t10 < s7.length - 1; t10++) {
      const o11 = s7[t10];
      for (;n10 < o11; ) {
        const t11 = n10;
        let s9 = e54[n10++], a10 = e54[n10++], c9 = e54[n10++], l10 = e54[n10++];
        for (let t12 = 1;t12 < i8 && n10 < o11; t12++)
          s9 = Math.min(s9, e54[n10++]), a10 = Math.min(a10, e54[n10++]), c9 = Math.max(c9, e54[n10++]), l10 = Math.max(l10, e54[n10++]);
        r9[u9 >> 2] = t11, e54[u9++] = s9, e54[u9++] = a10, e54[u9++] = c9, e54[u9++] = l10;
      }
    }
    this._pos = u9;
  }
  collides(e54, t4, n8, o10, i8) {
    if (this._pos !== this._boxes.length)
      throw new Error("Data not yet indexed - call index.finish().");
    const { _boxes: r9, _levelBounds: s7, _indices: a9, nodeSize: c5 } = this, l5 = 4 * this.numItems;
    let h5 = r9.length - 4, d9 = s7.length - 1;
    const u9 = [];
    for (;h5 !== undefined; ) {
      const p9 = Math.min(h5 + 4 * c5, s7[d9]), m9 = h5 >= l5;
      for (let s9 = h5;s9 < p9; s9 += 4) {
        const c9 = r9[s9];
        if (n8 < c9)
          continue;
        const l10 = r9[s9 + 1];
        if (o10 < l10)
          continue;
        const h9 = r9[s9 + 2];
        if (e54 > h9)
          continue;
        const p10 = r9[s9 + 3];
        if (t4 > p10)
          continue;
        const g10 = 0 | a9[s9 >> 2];
        if (m9)
          u9.push(g10, d9 - 1);
        else if (i8 === undefined || i8(g10, c9, l10, h9, p10))
          return true;
      }
      d9 = u9.pop(), h5 = u9.pop();
    }
    return false;
  }
  search(e54, t4, n8, o10, i8) {
    if (this._pos !== this._boxes.length)
      throw new Error("Data not yet indexed - call index.finish().");
    const { _boxes: r9, _levelBounds: s7, _indices: a9, nodeSize: c5 } = this, l5 = 4 * this.numItems;
    let h5 = r9.length - 4, d9 = s7.length - 1;
    const u9 = [], p9 = [];
    let m9 = false;
    for (;h5 !== undefined; ) {
      const g10 = Math.min(h5 + 4 * c5, s7[d9]), f10 = h5 >= l5;
      if (m9)
        this._collectContained(h5, g10, d9, l5, p9, i8);
      else
        for (let s9 = h5;s9 < g10; s9 += 4) {
          const c9 = r9[s9];
          if (n8 < c9)
            continue;
          const l10 = r9[s9 + 1];
          if (o10 < l10)
            continue;
          const h9 = r9[s9 + 2];
          if (e54 > h9)
            continue;
          const m10 = r9[s9 + 3];
          if (t4 > m10)
            continue;
          const g11 = 0 | a9[s9 >> 2];
          if (f10) {
            const i9 = +(e54 <= c9 && t4 <= l10 && n8 >= h9 && o10 >= m10);
            u9.push(g11 | i9, d9 - 1);
          } else
            (i8 === undefined || i8(g11, c9, l10, h9, m10)) && p9.push(g11);
        }
      d9 = u9.pop(), h5 = u9.pop(), h5 !== undefined && (m9 = !(1 & ~h5), h5 &= -2);
    }
    return p9;
  }
  _collectContained(e54, t4, n8, o10, i8, r9) {
    const s7 = this._boxes, a9 = this._indices;
    let c5 = e54;
    for (let e60 = n8;e60 > 0; e60--)
      c5 = a9[c5 >> 2];
    const l5 = Math.min(c5 + (t4 - e54) * this.nodeSize ** n8, o10);
    if (r9 === undefined)
      for (;c5 < l5; c5 += 4)
        i8.push(0 | a9[c5 >> 2]);
    else
      for (;c5 < l5; c5 += 4) {
        const e60 = 0 | a9[c5 >> 2];
        r9(e60, s7[c5], s7[c5 + 1], s7[c5 + 2], s7[c5 + 3]) && i8.push(e60);
      }
  }
  neighbors(e54, t4, n8 = 1 / 0, o10 = 1 / 0, i8) {
    if (this._pos !== this._boxes.length)
      throw new Error("Data not yet indexed - call index.finish().");
    const { _boxes: r9, _levelBounds: s7, _indices: a9, _queue: c5, nodeSize: l5 } = this, h5 = 4 * this.numItems, d9 = 4 * l5, u9 = [], p9 = n8 === 1;
    let m9 = o10 * o10;
    for (c5.push(r9.length - 4 << 1, 0);c5.length; ) {
      const o11 = c5.ids[0];
      if (1 & o11) {
        if (c5.pop(), u9.push(o11 >> 1), u9.length === n8)
          break;
        continue;
      }
      c5.pop();
      const l10 = o11 >> 1, g10 = l10 < h5, f10 = Math.min(l10 + d9, vee(l10, s7));
      for (let n10 = l10;n10 < f10; n10 += 4) {
        const o12 = r9[n10], s9 = r9[n10 + 1], l11 = r9[n10 + 2], h9 = r9[n10 + 3], d10 = Math.max(Math.max(o12 - e54, e54 - l11), 0), u10 = Math.max(Math.max(s9 - t4, t4 - h9), 0), f11 = d10 * d10 + u10 * u10;
        if (f11 > m9)
          continue;
        const _5 = 0 | a9[n10 >> 2];
        g10 ? (i8 === undefined || i8(_5)) && (c5.push(_5 << 1 | 1, f11), p9 && f11 < m9 && (m9 = f11)) : c5.push(_5 << 1, f11);
      }
    }
    return c5.clear(), u9;
  }
};
function vee(e54, t4) {
  let n8 = 0, o10 = t4.length - 1;
  for (;n8 < o10; ) {
    const i8 = n8 + o10 >> 1;
    t4[i8] > e54 ? o10 = i8 : n8 = i8 + 1;
  }
  return t4[n8];
}
function Iee(e54, t4, n8, o10, i8) {
  const r9 = e54[o10];
  e54[o10] = e54[i8], e54[i8] = r9;
  const s7 = 4 * o10, a9 = 4 * i8, c5 = t4[s7], l5 = t4[s7 + 1], h5 = t4[s7 + 2], d9 = t4[s7 + 3];
  t4[s7] = t4[a9], t4[s7 + 1] = t4[a9 + 1], t4[s7 + 2] = t4[a9 + 2], t4[s7 + 3] = t4[a9 + 3], t4[a9] = c5, t4[a9 + 1] = l5, t4[a9 + 2] = h5, t4[a9 + 3] = d9;
  const u9 = n8[o10];
  n8[o10] = n8[i8], n8[i8] = u9;
}
function See(e54, t4) {
  let n8 = e54 ^ t4, o10 = 65535 ^ n8, i8 = 65535 ^ (e54 | t4), r9 = e54 & (65535 ^ t4), s7 = n8 | o10 >> 1, a9 = n8 >> 1 ^ n8, c5 = i8 ^ i8 >> 1 ^ o10 & r9 >> 1, l5 = r9 ^ n8 & i8 >> 1 ^ r9 >> 1;
  return n8 = s7 & s7 >> 2 ^ a9 & a9 >> 2, o10 = s7 & a9 >> 2 ^ a9 & (s7 ^ a9) >> 2, i8 = c5 ^ s7 & c5 >> 2 ^ a9 & l5 >> 2, r9 = l5 ^ a9 & c5 >> 2 ^ (s7 ^ a9) & l5 >> 2, s7 = n8 & n8 >> 4 ^ o10 & o10 >> 4, a9 = n8 & o10 >> 4 ^ o10 & (n8 ^ o10) >> 4, c5 = i8 ^ n8 & i8 >> 4 ^ o10 & r9 >> 4, l5 = r9 ^ o10 & i8 >> 4 ^ (n8 ^ o10) & r9 >> 4, i8 = c5 ^ s7 & c5 >> 8 ^ a9 & l5 >> 8, r9 = l5 ^ a9 & c5 >> 8 ^ (s7 ^ a9) & l5 >> 8, i8 ^= i8 >> 1, r9 ^= r9 >> 1, n8 = e54 ^ t4, o10 = r9 | 65535 ^ (n8 | i8), n8 = 16711935 & (n8 | n8 << 8), n8 = 252645135 & (n8 | n8 << 4), n8 = 858993459 & (n8 | n8 << 2), n8 = 1431655765 & (n8 | n8 << 1), o10 = 16711935 & (o10 | o10 << 8), o10 = 252645135 & (o10 | o10 << 4), o10 = 858993459 & (o10 | o10 << 2), o10 = 1431655765 & (o10 | o10 << 1), ((o10 << 1 | n8) >>> 0) - 2147483648;
}
var Cee = class {
  items;
  clearance;
  minViaEdgeToPadEdgeClearance;
  minPadEdgeToPadEdgeClearance;
  holeClearance;
  boardEdgeClearance;
  boardLayers;
  minViaHoleEdgeToViaHoleEdgeClearance;
  defaultViaHoleDiameter;
  bounds;
  maxIndexedViaHoleDiameter;
  index;
  collisionIndexesByLayer = new Map;
  connectionNameSets;
  copperObjectIds;
  connectionNameResolver;
  connectedPads;
  dynamicTraceIndex;
  constructor(e54, t4, n8, o10 = [], i8 = new D7(e54, t4)) {
    var r9;
    this.bounds = e54.bounds, this.boardLayers = (r9 = e54.layerCount, ["top", ...Array.from({ length: Math.max(0, r9 - 2) }, (e60, t10) => `inner${t10 + 1}`), ...r9 > 1 ? ["bottom"] : []]), this.dynamicTraceIndex = n8, this.clearance = Math.max(e54.defaultObstacleMargin ?? 0, e54.minTraceToPadEdgeClearance ?? 0, 0.1), this.minViaEdgeToPadEdgeClearance = e54.minViaEdgeToPadEdgeClearance, this.holeClearance = e54.minTraceToHoleEdgeClearance ?? this.clearance, this.minPadEdgeToPadEdgeClearance = e54.minPadEdgeToPadEdgeClearance ?? this.clearance, this.boardEdgeClearance = e54.minBoardEdgeClearance ?? this.clearance, this.minViaHoleEdgeToViaHoleEdgeClearance = Math.max(e54.minViaHoleEdgeToViaHoleEdgeClearance ?? 0, 0.1), this.defaultViaHoleDiameter = e54.min_via_hole_diameter ?? e54.minViaHoleDiameter ?? 0.3, this.items = [...e54.obstacles.flatMap((e60, t10) => K7(e60).map((e61) => ({ ...e61, copperObjectId: `obstacle:${t10}` }))), ...this.createTraceItems(e54.fixedTraces ?? [], true), ...this.createTraceItems(t4), ...o10], this.maxIndexedViaHoleDiameter = this.items.reduce((e60, t10) => t10.kind === "via" ? Math.max(e60, t10.viaHoleDiameter ?? this.defaultViaHoleDiameter) : e60, this.defaultViaHoleDiameter), this.connectionNameResolver = i8, i8.setCacheableObstacles(e54.obstacles);
    const s7 = new Map;
    this.connectionNameSets = this.items.map((e60) => {
      let t10 = s7.get(e60.connectionNames);
      return t10 || (t10 = i8.canonicalizeToSet(e60.connectionNames), s7.set(e60.connectionNames, t10)), t10;
    }), this.copperObjectIds = this.items.map((e60, t10) => e60.copperObjectId ?? `indexed-item:${t10}`), this.connectedPads = e54.obstacles.flatMap((e60) => e60.connectedTo.some((e61) => e61.startsWith("pcb_smtpad_") || e61.startsWith("pcb_plated_hole_")) ? [{ obstacle: e60, canonicalConnectionNames: i8.canonicalizeToSet(e60.connectedTo) }] : []), this.index = this.items.length > 0 ? new xee(this.items.length) : null;
    for (const e60 of this.items)
      this.index.add(e60.minX, e60.minY, e60.maxX, e60.maxY);
    this.index?.finish();
  }
  createTraceItems(e54, t4 = false) {
    const n8 = [];
    for (let o10 = 0;o10 < e54.length; o10++) {
      const i8 = e54[o10], r9 = t4 ? undefined : o10, s7 = `${t4 ? "fixed-trace" : "trace"}:${o10}`, a9 = !t4 && o10 === this.dynamicTraceIndex, c5 = [i8.connection_name, i8.source_trace_id, i8.rootConnectionName, ...i8.mergedConnectionNames ?? [], ...i8.connectsTo ?? []].filter((e60) => Boolean(e60));
      for (let e60 = 0;e60 < i8.route.length; e60++) {
        const t10 = i8.route[e60];
        if (t10.route_type === "via") {
          const o12 = t10.via_diameter ?? 0.6;
          n8.push({ minX: t10.x - o12 / 2, minY: t10.y - o12 / 2, maxX: t10.x + o12 / 2, maxY: t10.y + o12 / 2, layers: this.boardLayers, kind: "via", connectionNames: c5, copperObjectId: s7, traceIndex: r9, routeStartIndex: e60, routeEndIndex: e60, viaHoleDiameter: t10.via_hole_diameter ?? this.defaultViaHoleDiameter, exactShape: { type: "circle", center: { x: t10.x, y: t10.y }, radius: o12 / 2 } });
          continue;
        }
        if (a9)
          continue;
        const o11 = i8.route[e60 + 1];
        t10.route_type === "wire" && o11?.route_type === "wire" && t10.layer === o11.layer && n8.push(...Z7({ start: t10, end: o11, width: t10.width, base: { layers: [t10.layer], kind: "trace", connectionNames: c5, copperObjectId: s7, traceIndex: r9, routeStartIndex: e60, routeEndIndex: e60 + 1 } }));
      }
    }
    return n8;
  }
  collides(e54) {
    if (this.isOutsideBounds(e54))
      return true;
    const { radius: t4, candidates: n8, canonicalConnectionNames: o10 } = this.getCollisionCandidates(e54, true);
    for (const i8 of n8)
      if (this.itemCollides(i8, e54, t4, o10))
        return true;
    return false;
  }
  createSegmentCollisionChecker(e54, t4) {
    const { radius: n8, candidates: o10, canonicalConnectionNames: i8 } = this.getCollisionCandidates({ ...e54, start: { x: t4.minX, y: t4.minY }, end: { x: t4.maxX, y: t4.maxY } }, true), r9 = [];
    for (const t10 of o10) {
      const n10 = this.getItemCollisionRadius(t10, e54, i8);
      n10 !== null && r9.push({ item: this.items[t10], radius: n10 });
    }
    const s7 = r9.length ? new xee(r9.length) : null;
    for (const { item: e60, radius: t10 } of r9) {
      const n10 = Math.max(Math.abs(e60.minX), Math.abs(e60.minY), Math.abs(e60.maxX), Math.abs(e60.maxY)), o11 = t10 + 0.000000001 + Number.EPSILON * (n10 + Math.abs(t10)) * 4;
      s7.add(e60.minX - o11, e60.minY - o11, e60.maxX + o11, e60.maxY + o11);
    }
    s7?.finish();
    const a9 = { ...e54 };
    let c5 = 0, l5 = 0, h5 = 0, d9 = 0;
    const u9 = (e60) => {
      const t10 = r9[e60], n10 = t10.item;
      return !(h5 < n10.minX || d9 < n10.minY || c5 > n10.maxX || l5 > n10.maxY) && this.itemGeometryCollides(n10, a9, t10.radius);
    };
    return (e60, o11) => {
      if (Math.min(e60.x, o11.x) < t4.minX || Math.min(e60.y, o11.y) < t4.minY || Math.max(e60.x, o11.x) > t4.maxX || Math.max(e60.y, o11.y) > t4.maxY)
        throw new Error("Segment exceeds its prepared collision bounds");
      return a9.start = e60, a9.end = o11, !!this.isOutsideBounds(a9) || (c5 = Math.min(e60.x, o11.x) - n8, l5 = Math.min(e60.y, o11.y) - n8, h5 = Math.max(e60.x, o11.x) + n8, d9 = Math.max(e60.y, o11.y) + n8, s7?.collides(Math.min(e60.x, o11.x), Math.min(e60.y, o11.y), Math.max(e60.x, o11.x), Math.max(e60.y, o11.y), u9) ?? false);
    };
  }
  findCollisions(e54) {
    const { radius: t4, candidates: n8, canonicalConnectionNames: o10 } = this.getCollisionCandidates(e54), i8 = [];
    for (const r9 of n8)
      this.itemCollides(r9, e54, t4, o10) && i8.push(this.items[r9]);
    return i8;
  }
  getSameNetCopperContactIds(e54) {
    const t4 = e54.width / 2, n8 = this.index?.search(Math.min(e54.start.x, e54.end.x) - t4, Math.min(e54.start.y, e54.end.y) - t4, Math.max(e54.start.x, e54.end.x) + t4, Math.max(e54.start.y, e54.end.y) + t4) ?? [], o10 = new Set(this.connectionNameResolver.canonicalize(e54.connectionNames)), i8 = new Set;
    for (const r9 of n8) {
      const n10 = this.items[r9];
      n10.layers.includes(e54.layer) && (n10.traceIndex === e54.ignoreTraceIndex || e54.ignoreTraceIndices?.includes(n10.traceIndex ?? -1) || [...this.connectionNameSets[r9]].some((e60) => o10.has(e60)) && this.itemCopperTouches(n10, e54, t4) && i8.add(this.copperObjectIds[r9]));
    }
    return i8;
  }
  getConnectedPadWidthLimit(e54) {
    if (Math.hypot(e54.end.x - e54.start.x, e54.end.y - e54.start.y) <= 0.00001)
      return null;
    const t4 = this.getConnectedPadWidthLimitAtPoint(e54, e54.start), n8 = this.getConnectedPadWidthLimitAtPoint(e54, e54.end);
    return t4 === null ? n8 : n8 === null ? t4 : Math.min(t4, n8);
  }
  getConnectedPadWidthLimitAtPoint(e54, t4) {
    const n8 = this.getConnectedPadsAtPoint(e54, t4);
    return n8.length === 0 ? null : Math.max(...n8.map(({ obstacle: t10 }) => this.getPadWidthNormalToQuery(t10, e54)));
  }
  getConnectedPadEndpointWidthLimitAtPoint(e54, t4) {
    const n8 = this.getConnectedPadsAtPoint(e54, t4);
    return n8.length === 0 ? null : Math.max(...n8.map(({ obstacle: e60 }) => {
      const n10 = this.getObstacleLocalPoint(t4, e60);
      return Math.max(0, 2 * Math.min(e60.width / 2 - Math.abs(n10.x), e60.height / 2 - Math.abs(n10.y)));
    }));
  }
  getConnectedPadBoundaryPoint(e54, t4) {
    const n8 = t4 === "start" ? e54.start : e54.end, o10 = t4 === "start" ? e54.end : e54.start, i8 = this.getConnectedPadsAtPoint(e54, n8).sort((t10, n10) => this.getPadWidthNormalToQuery(n10.obstacle, e54) - this.getPadWidthNormalToQuery(t10.obstacle, e54))[0];
    return !i8 || this.pointIsInsideObstacle(o10, i8.obstacle) ? null : this.getObstacleBoundaryPoint(n8, o10, i8.obstacle);
  }
  getConnectedPadsAtPoint(e54, t4) {
    const n8 = new Set(this.connectionNameResolver.canonicalize(e54.connectionNames));
    return this.connectedPads.filter(({ obstacle: o10, canonicalConnectionNames: i8 }) => o10.layers.includes(e54.layer) && [...i8].some((e60) => n8.has(e60)) && this.pointIsInsideObstacle(t4, o10));
  }
  pointIsInsideObstacle(e54, t4) {
    const { x: n8, y: o10 } = this.getObstacleLocalPoint(e54, t4);
    return Math.abs(n8) <= t4.width / 2 + 0.000000001 && Math.abs(o10) <= t4.height / 2 + 0.000000001;
  }
  getObstacleLocalPoint(e54, t4) {
    const n8 = -(t4.ccwRotationDegrees ?? 0) * Math.PI / 180, o10 = Math.cos(n8), i8 = Math.sin(n8), r9 = e54.x - t4.center.x, s7 = e54.y - t4.center.y;
    return { x: r9 * o10 - s7 * i8, y: r9 * i8 + s7 * o10 };
  }
  getPadWidthNormalToQuery(e54, t4) {
    const n8 = t4.end.x - t4.start.x, o10 = t4.end.y - t4.start.y, i8 = Math.hypot(n8, o10);
    if (i8 <= 0.000000001)
      return Math.min(e54.width, e54.height);
    const r9 = -o10 / i8, s7 = n8 / i8, a9 = -(e54.ccwRotationDegrees ?? 0) * Math.PI / 180, c5 = Math.cos(a9), l5 = Math.sin(a9), h5 = r9 * c5 - s7 * l5, d9 = r9 * l5 + s7 * c5;
    return Math.abs(h5) * e54.width + Math.abs(d9) * e54.height;
  }
  getObstacleBoundaryPoint(e54, t4, n8) {
    const o10 = -(n8.ccwRotationDegrees ?? 0) * Math.PI / 180, i8 = Math.cos(o10), r9 = Math.sin(o10), s7 = (e60) => {
      const t10 = e60.x - n8.center.x, o11 = e60.y - n8.center.y;
      return { x: t10 * i8 - o11 * r9, y: t10 * r9 + o11 * i8 };
    }, a9 = s7(e54), c5 = s7(t4), l5 = { x: c5.x - a9.x, y: c5.y - a9.y }, h5 = [];
    if (Math.abs(l5.x) > 0.000000000001) {
      const e60 = l5.x > 0 ? n8.width / 2 : -n8.width / 2;
      h5.push((e60 - a9.x) / l5.x);
    }
    if (Math.abs(l5.y) > 0.000000000001) {
      const e60 = l5.y > 0 ? n8.height / 2 : -n8.height / 2;
      h5.push((e60 - a9.y) / l5.y);
    }
    const d9 = Math.min(...h5.filter((e60) => e60 >= 0 && e60 <= 1));
    return Number.isFinite(d9) ? { x: e54.x + (t4.x - e54.x) * d9, y: e54.y + (t4.y - e54.y) * d9 } : null;
  }
  getConnectedLayersAtPoint(e54, t4) {
    const n8 = new Set(this.connectionNameResolver.canonicalize(t4)), o10 = new Set, i8 = this.index?.search(e54.x, e54.y, e54.x, e54.y) ?? [];
    for (const t10 of i8) {
      const i9 = this.items[t10];
      if (i9.kind !== "obstacle")
        continue;
      if (![...this.connectionNameSets[t10]].some((e60) => n8.has(e60)))
        continue;
      if (i9.exactShape?.type === "polygon" ? W7(e54, e54, i9.exactShape.points) <= 0.000000001 : i9.exactShape?.type === "circle" ? Math.hypot(i9.exactShape.center.x - e54.x, i9.exactShape.center.y - e54.y) <= i9.exactShape.radius + 0.000000001 : e54.x >= i9.minX - 0.000000001 && e54.x <= i9.maxX + 0.000000001 && e54.y >= i9.minY - 0.000000001 && e54.y <= i9.maxY + 0.000000001)
        for (const e60 of i9.layers)
          o10.add(e60);
    }
    return [...o10];
  }
  collidesVia(e54) {
    return this.getViaViolationSignatures(e54).size > 0;
  }
  getViaViolationSignatures(e54) {
    const t4 = new Set;
    for (const n10 of e54.layers) {
      const o11 = { isVia: true, start: e54.point, end: e54.point, layer: n10, width: e54.padDiameter, connectionNames: e54.connectionNames, ignoreTraceIndex: e54.ignoreTraceIndex, ignoreTraceIndices: e54.ignoreTraceIndices, ignoreRouteRange: e54.ignoreRouteRange, obstacleClearance: Math.max(e54.obstacleClearance ?? this.clearance, this.minViaEdgeToPadEdgeClearance ?? 0), blockSameNetObstacles: e54.blockSameNetObstacles, sameNetObstacleClearance: e54.sameNetObstacleClearance };
      this.isOutsideBounds(o11) && t4.add(`board-edge:${n10}`);
      const { radius: i9, candidates: r10, canonicalConnectionNames: s9 } = this.getCollisionCandidates(o11);
      for (const e60 of r10)
        this.itemCollides(e60, o11, i9, s9) && t4.add(`copper:${n10}:${this.getViolationObjectId(e60)}`);
    }
    const n8 = e54.holeDiameter + this.minViaHoleEdgeToViaHoleEdgeClearance;
    for (const o11 of e54.otherNewViaPoints ?? [])
      Math.hypot(o11.x - e54.point.x, o11.y - e54.point.y) < n8 - 0.000000001 && t4.add(`new-via-drill:${o11.x},${o11.y}:${e54.holeDiameter}`);
    const o10 = e54.fixedVias ?? [];
    for (let n10 = 0;n10 < o10.length; n10++) {
      const i9 = o10[n10], r10 = e54.holeDiameter / 2 + i9.holeDiameter / 2 + this.minViaHoleEdgeToViaHoleEdgeClearance;
      Math.hypot(i9.point.x - e54.point.x, i9.point.y - e54.point.y) < r10 - 0.000000001 && t4.add(`fixed-via-drill:${n10}:${i9.point.x},${i9.point.y}:${i9.holeDiameter}`);
    }
    const i8 = e54.holeDiameter / 2 + this.maxIndexedViaHoleDiameter / 2 + this.minViaHoleEdgeToViaHoleEdgeClearance, r9 = this.index?.search(e54.point.x - i8, e54.point.y - i8, e54.point.x + i8, e54.point.y + i8) ?? [], s7 = new Set;
    for (const n10 of r9) {
      const o11 = this.items[n10];
      if (o11.kind !== "via" || o11.exactShape?.type !== "circle")
        continue;
      if (o11.traceIndex === e54.ignoreTraceIndex && e54.ignoreRouteRange && (o11.routeEndIndex ?? -1) >= e54.ignoreRouteRange.start && (o11.routeStartIndex ?? Number.POSITIVE_INFINITY) <= e54.ignoreRouteRange.end)
        continue;
      if (e54.ignoreTraceIndices?.includes(o11.traceIndex ?? -1))
        continue;
      const i9 = `${this.copperObjectIds[n10] ?? "unknown"}:${o11.routeStartIndex ?? -1}`;
      if (s7.has(i9))
        continue;
      s7.add(i9);
      const r10 = o11.viaHoleDiameter ?? this.defaultViaHoleDiameter, a9 = e54.holeDiameter / 2 + r10 / 2 + this.minViaHoleEdgeToViaHoleEdgeClearance;
      Math.hypot(o11.exactShape.center.x - e54.point.x, o11.exactShape.center.y - e54.point.y) < a9 - 0.000000001 && t4.add(`indexed-via-drill:${this.getViolationObjectId(n10)}`);
    }
    return t4;
  }
  getViolationObjectId(e54) {
    const t4 = this.items[e54], n8 = this.copperObjectIds[e54], o10 = `${t4.routeStartIndex ?? ""}-${t4.routeEndIndex ?? ""}`;
    if (t4.kind === "obstacle")
      return n8;
    if (t4.exactShape?.type === "segment") {
      const { start: e60, end: i8, width: r9 } = t4.exactShape;
      return `${n8}:${t4.kind}:${o10}:${e60.x},${e60.y}:${i8.x},${i8.y}:${r9}`;
    }
    if (t4.exactShape?.type === "circle") {
      const { center: e60, radius: i8 } = t4.exactShape;
      return `${n8}:${t4.kind}:${o10}:${e60.x},${e60.y}:${i8}`;
    }
    return t4.exactShape?.type === "polygon" ? `${n8}:${t4.kind}:${o10}:${t4.exactShape.points.map((e60) => `${e60.x},${e60.y}`).join(";")}` : `${n8}:${t4.kind}:${o10}:${t4.minX},${t4.minY},${t4.maxX},${t4.maxY}`;
  }
  getLayerCollisionIndex(e54) {
    const t4 = this.collisionIndexesByLayer.get(e54);
    if (t4)
      return t4;
    const n8 = [];
    for (let t10 = 0;t10 < this.items.length; t10++)
      this.items[t10].layers.includes(e54) && n8.push(t10);
    const o10 = n8.length ? new xee(n8.length) : null;
    for (const e60 of n8) {
      const t10 = this.items[e60];
      o10.add(t10.minX, t10.minY, t10.maxX, t10.maxY);
    }
    o10?.finish();
    const i8 = { index: o10, itemIndices: n8 };
    return this.collisionIndexesByLayer.set(e54, i8), i8;
  }
  getCollisionCandidates(e54, t4 = false) {
    const n8 = Math.max(this.clearance, this.holeClearance, e54.isVia ? this.minPadEdgeToPadEdgeClearance : 0, e54.obstacleClearance ?? this.clearance, e54.sameNetObstacleClearance ?? 0), o10 = e54.width / 2 + n8, i8 = { minX: Math.min(e54.start.x, e54.end.x) - o10, minY: Math.min(e54.start.y, e54.end.y) - o10, maxX: Math.max(e54.start.x, e54.end.x) + o10, maxY: Math.max(e54.start.y, e54.end.y) + o10 }, r9 = t4 ? this.getLayerCollisionIndex(e54.layer) : null, s7 = r9 ? r9.index : this.index;
    let a9 = s7?.search(i8.minX, i8.minY, i8.maxX, i8.maxY) ?? [];
    return r9 && (a9 = a9.map((e60) => r9.itemIndices[e60])), { radius: o10, candidates: a9, canonicalConnectionNames: this.connectionNameResolver.canonicalize(e54.connectionNames) };
  }
  itemCollides(e54, t4, n8, o10) {
    const i8 = this.getItemCollisionRadius(e54, t4, o10);
    return i8 !== null && this.itemGeometryCollides(this.items[e54], t4, i8);
  }
  getItemCollisionRadius(e54, t4, n8) {
    const o10 = this.items[e54];
    if (!o10.layers.includes(t4.layer))
      return null;
    const i8 = this.connectionNameSets[e54], r9 = n8.some((e60) => i8.has(e60));
    if (r9 && (!t4.blockSameNetObstacles || o10.kind !== "obstacle" || o10.obstacleKind === "via"))
      return null;
    if (o10.kind === "trace" && t4.ignoreTraceIndices?.includes(o10.traceIndex ?? -1))
      return null;
    if (o10.kind === "trace" && o10.traceIndex === t4.ignoreTraceIndex && t4.ignoreRouteRange && (o10.routeEndIndex ?? -1) >= t4.ignoreRouteRange.start && (o10.routeStartIndex ?? Number.POSITIVE_INFINITY) <= t4.ignoreRouteRange.end)
      return null;
    const s7 = t4.isVia && (o10.kind === "via" || o10.kind === "obstacle" && o10.obstacleKind === "via") ? this.minPadEdgeToPadEdgeClearance : o10.kind !== "obstacle" || o10.obstacleKind !== "hole" || t4.isVia ? o10.kind === "obstacle" && o10.obstacleKind === "pad" ? r9 && t4.blockSameNetObstacles ? t4.sameNetObstacleClearance ?? t4.obstacleClearance ?? this.clearance : t4.obstacleClearance ?? this.clearance : this.clearance : this.holeClearance;
    return t4.width / 2 + s7;
  }
  itemGeometryCollides(e54, t4, n8) {
    return e54.exactShape?.type === "segment" ? G7(t4.start, t4.end, e54.exactShape.start, e54.exactShape.end, n8 + e54.exactShape.width / 2 + 0.000000001) : e54.exactShape?.type === "polygon" ? ((e60, t10, n10, o10) => {
      if (V7(e60, n10) || V7(t10, n10))
        return 0 <= o10;
      for (let i8 = 0;i8 < n10.length; i8++)
        if (G7(e60, t10, n10[i8], n10[(i8 + 1) % n10.length], o10))
          return true;
      return Number.POSITIVE_INFINITY <= o10;
    })(t4.start, t4.end, e54.exactShape.points, n8 + 0.000000001) : e54.exactShape?.type === "circle" ? B7(e54.exactShape.center, t4.start, t4.end) <= n8 + e54.exactShape.radius + 0.000000001 : U7(t4.start, t4.end, { minX: e54.minX - n8, minY: e54.minY - n8, maxX: e54.maxX + n8, maxY: e54.maxY + n8 });
  }
  itemCopperTouches(e54, t4, n8) {
    return e54.exactShape?.type === "segment" ? H7(t4.start, t4.end, e54.exactShape.start, e54.exactShape.end) <= n8 + e54.exactShape.width / 2 + 0.000000001 : e54.exactShape?.type === "polygon" ? W7(t4.start, t4.end, e54.exactShape.points) <= n8 + 0.000000001 : e54.exactShape?.type === "circle" ? B7(e54.exactShape.center, t4.start, t4.end) <= n8 + e54.exactShape.radius + 0.000000001 : U7(t4.start, t4.end, { minX: e54.minX - n8, minY: e54.minY - n8, maxX: e54.maxX + n8, maxY: e54.maxY + n8 });
  }
  isOutsideBounds(e54) {
    const t4 = e54.width / 2 + this.boardEdgeClearance;
    return Math.min(e54.start.x, e54.end.x) - t4 < this.bounds.minX || Math.max(e54.start.x, e54.end.x) + t4 > this.bounds.maxX || Math.min(e54.start.y, e54.end.y) - t4 < this.bounds.minY || Math.max(e54.start.y, e54.end.y) + t4 > this.bounds.maxY;
  }
};
var Pee = [{ x: 0, y: 0 }, { x: 0.5, y: 0 }, { x: 0, y: 0.5 }, { x: 0.5, y: 0.5 }];
var Mee = (e54) => e54?.route_type === "wire";
var wee = class extends BaseSolver {
  inputProblem;
  traces;
  corridor;
  phase = "scan-corridor";
  corridorCursor = 0;
  blockerCursor = 0;
  offsetCursor = 0;
  resolutionCursor = 0;
  attemptedGridCount = 0;
  blockerIndex;
  connectionNameResolver;
  connectionByTraceId = new Map;
  mutableTraceIndices;
  blockersByTrace = new Map;
  blockers = [];
  currentBlocker = null;
  currentRange = null;
  currentTraceWidth = 0;
  gridResolutions = [];
  currentObstacleIndex = null;
  output = null;
  constructor(e54, t4 = new D7(e54.simpleRouteJson, e54.traces)) {
    super(), this.inputProblem = structuredClone(e54), this.traces = this.inputProblem.traces.slice(), this.corridor = structuredClone(e54.corridor), this.mutableTraceIndices = e54.mutableTraceIndices ? new Set(e54.mutableTraceIndices) : null, this.connectionNameResolver = t4, this.blockerIndex = new Cee(this.inputProblem.simpleRouteJson, this.traces, e54.powerTraceIndex, [], this.connectionNameResolver), this.activeSubSolver = null, this.MAX_ITERATIONS = 25000, this.stats = this.createStats();
  }
  getSolverName() {
    return "LocalTraceInflationSolver";
  }
  _step() {
    if (this.activeSubSolver) {
      const e54 = this.activeSubSolver;
      return this.stepActiveSubSolver(), void ((e54.solved || e54.failed) && (this.stats = this.createStats()));
    }
    switch (this.phase) {
      case "scan-corridor":
        this.scanNextCorridorSegment();
        break;
      case "select-blocker":
        this.selectNextBlocker();
        break;
      case "try-elastic-push":
        break;
      case "try-grid-candidate":
        this.startNextGridCandidate();
        break;
      case "complete":
        this.output ? this.solved = true : (this.failed = true, this.error = "No locally reroutable trace blocks the power corridor");
    }
    this.stats = this.createStats();
  }
  scanNextCorridorSegment() {
    const e54 = this.corridor[this.corridorCursor];
    if (!e54)
      return this.blockers = [...this.blockersByTrace.values()].sort((e60, t10) => e60.traceIndex - t10.traceIndex), void (this.phase = "select-blocker");
    const t4 = this.traces[this.inputProblem.powerTraceIndex], n8 = this.blockerIndex.findCollisions({ start: e54.start, end: e54.end, layer: e54.layer, width: e54.width, connectionNames: t4 ? this.getTraceConnectionNames(t4) : [] });
    for (const e60 of n8)
      this.recordBlockingTrace(e60);
    this.corridorCursor++;
  }
  recordBlockingTrace(e54) {
    if (e54.kind !== "trace" || e54.traceIndex === undefined || e54.routeStartIndex === undefined || e54.routeEndIndex === undefined || e54.traceIndex === this.inputProblem.powerTraceIndex || this.mutableTraceIndices !== null && !this.mutableTraceIndices.has(e54.traceIndex))
      return;
    const t4 = this.traces[e54.traceIndex];
    if (!t4)
      return;
    const n8 = this.findConnectionForTrace(t4);
    if ((n8 ? this.resolveNominalTraceWidth(n8) : this.getTraceNominalWidth(t4)) >= (this.inputProblem.pushOnlyNominalWidthsBelow ?? this.inputProblem.nominalPowerWidth) - L7)
      return;
    const o10 = this.blockersByTrace.get(e54.traceIndex);
    if (o10)
      return o10.firstRouteIndex = Math.min(o10.firstRouteIndex, e54.routeStartIndex), void (o10.lastRouteIndex = Math.max(o10.lastRouteIndex, e54.routeEndIndex));
    this.blockersByTrace.set(e54.traceIndex, { traceIndex: e54.traceIndex, firstRouteIndex: e54.routeStartIndex, lastRouteIndex: e54.routeEndIndex });
  }
  selectNextBlocker() {
    if (this.currentBlocker = this.blockers[this.blockerCursor] ?? null, !this.currentBlocker)
      return void (this.phase = "complete");
    const e54 = this.findStableAnchorRange(this.currentBlocker);
    if (!e54)
      return void this.blockerCursor++;
    const t4 = this.traces[this.currentBlocker.traceIndex];
    this.currentRange = e54, this.currentTraceWidth = this.getRangeWidth(t4, e54), this.gridResolutions = this.getGridResolutions(this.currentTraceWidth), this.resolutionCursor = 0, this.offsetCursor = 0, this.currentObstacleIndex = new Cee(this.inputProblem.simpleRouteJson, this.traces, this.currentBlocker.traceIndex, this.createInflatedCorridorItems(), this.connectionNameResolver), this.activeSubSolver = new lee({ trace: t4, range: e54, layer: t4.route[e54.startIndex].layer, traceWidth: this.currentTraceWidth, corridor: this.corridor, obstacleIndex: this.currentObstacleIndex, connectionNames: this.getTraceConnectionNames(t4) }), this.phase = "try-elastic-push";
  }
  findStableAnchorRange(e54) {
    const t4 = this.traces[e54.traceIndex];
    if (!t4)
      return null;
    let { firstRouteIndex: n8, lastRouteIndex: o10 } = e54;
    for (;n8 > 0; ) {
      const e60 = t4.route[n8];
      if (Mee(e60) && this.pointClearsCorridor(e60))
        break;
      n8--;
    }
    for (;o10 < t4.route.length - 1; ) {
      const e60 = t4.route[o10];
      if (Mee(e60) && this.pointClearsCorridor(e60))
        break;
      o10++;
    }
    const i8 = t4.route[n8], r9 = t4.route[o10];
    if (!Mee(i8) || !Mee(r9) || i8.layer !== r9.layer || !this.pointClearsCorridor(i8) || !this.pointClearsCorridor(r9) || n8 >= o10)
      return null;
    const s7 = { startIndex: n8, endIndex: o10 }, a9 = this.getRangeLength(t4, s7);
    return !Number.isFinite(a9) || a9 > (this.inputProblem.maxRerouteLength ?? 10) + L7 ? null : s7;
  }
  pointClearsCorridor(e54) {
    return this.corridor.every((t4) => {
      if (t4.layer !== e54.layer)
        return true;
      const n8 = t4.width / 2 + e54.width / 2 + this.blockerIndex.clearance;
      return B7(e54, t4.start, t4.end) >= n8 - L7;
    });
  }
  startNextGridCandidate() {
    if (!this.currentBlocker || !this.currentRange)
      return void (this.phase = "select-blocker");
    if (this.resolutionCursor >= this.gridResolutions.length)
      return this.blockerCursor++, void (this.phase = "select-blocker");
    if (this.offsetCursor >= Pee.length)
      return this.resolutionCursor++, void (this.offsetCursor = 0);
    const e54 = this.traces[this.currentBlocker.traceIndex], t4 = e54.route[this.currentRange.startIndex], n8 = e54.route[this.currentRange.endIndex];
    if (!Mee(t4) || !Mee(n8))
      return this.blockerCursor++, void (this.phase = "select-blocker");
    const o10 = this.gridResolutions[this.resolutionCursor], i8 = Pee[this.offsetCursor], r9 = this.currentObstacleIndex;
    if (!r9)
      return this.blockerCursor++, void (this.phase = "select-blocker");
    this.attemptedGridCount++, this.activeSubSolver = new yee({ start: t4, end: n8, layer: t4.layer, traceWidth: this.currentTraceWidth, gridSize: o10, gridOffset: { x: i8.x * o10, y: i8.y * o10 }, connectionNames: this.getTraceConnectionNames(e54), obstacleIndex: r9, ignoreTraceIndex: this.currentBlocker.traceIndex, ignoreRouteRange: { start: this.currentRange.startIndex, end: this.currentRange.endIndex }, bounds: this.inputProblem.simpleRouteJson.bounds, searchPadding: j7(2.5 * this.inputProblem.nominalPowerWidth, 1.5, 4) });
  }
  stepActiveSubSolver() {
    const e54 = this.activeSubSolver;
    if (e54.step(), e54.solved || e54.failed) {
      if (e54.solved) {
        const t4 = e54.getOutput();
        if (t4)
          return this.applyRoute(t4, e54 instanceof lee ? "elastic" : "grid"), this.activeSubSolver = null, void (this.phase = "complete");
      }
      this.failedSubSolvers ??= [], this.failedSubSolvers.push(e54), this.activeSubSolver = null, e54 instanceof lee ? this.phase = "try-grid-candidate" : this.offsetCursor++;
    }
  }
  applyRoute(e54, t4) {
    const n8 = this.currentBlocker, o10 = this.currentRange;
    this.traces = structuredClone(this.traces);
    const i8 = this.traces[n8.traceIndex], r9 = i8.route[o10.startIndex], s7 = i8.route[o10.endIndex], a9 = e54.points.map((e60) => ({ route_type: "wire", x: e60.x, y: e60.y, width: this.currentTraceWidth, layer: r9.layer }));
    a9[0].width = Math.max(a9[0].width, r9.width), a9[a9.length - 1].width = Math.max(a9[a9.length - 1].width, s7.width), i8.route.splice(o10.startIndex, o10.endIndex - o10.startIndex + 1, ...a9), this.output = { traces: this.traces, pushedTraceIndex: n8.traceIndex, replacedRange: o10, strategy: t4 };
  }
  createInflatedCorridorItems() {
    return this.corridor.flatMap((e54) => q7({ start: e54.start, end: e54.end, width: e54.width, base: { layers: [e54.layer], kind: "obstacle", connectionNames: [] } }));
  }
  getGridResolutions(e54) {
    return [j7(1.5 * e54, 0.1, 0.3), j7(0.75 * e54, 0.08, 0.18)].filter((e60, t4, n8) => n8.findIndex((t10) => Math.abs(t10 - e60) < L7) === t4);
  }
  getRangeWidth(e54, t4) {
    let n8 = this.inputProblem.simpleRouteJson.minTraceWidth;
    for (let o10 = t4.startIndex;o10 <= t4.endIndex; o10++) {
      const t10 = e54.route[o10];
      Mee(t10) && (n8 = Math.max(n8, t10.width));
    }
    return n8;
  }
  getRangeLength(e54, t4) {
    let n8 = 0;
    for (let o10 = t4.startIndex;o10 < t4.endIndex; o10++) {
      const t10 = e54.route[o10], i8 = e54.route[o10 + 1];
      if (!Mee(t10) || !Mee(i8) || t10.layer !== i8.layer)
        return Number.POSITIVE_INFINITY;
      n8 += z7(t10, i8);
    }
    return n8;
  }
  resolveNominalTraceWidth(e54) {
    return Math.max(e54.nominalTraceWidth ?? e54.width ?? this.inputProblem.simpleRouteJson.nominalTraceWidth ?? this.inputProblem.simpleRouteJson.minTraceWidth, this.inputProblem.simpleRouteJson.minTraceWidth);
  }
  getTraceNominalWidth(e54) {
    return e54.route.reduce((e60, t4) => t4.route_type === "wire" ? Math.max(e60, t4.width) : e60, this.inputProblem.simpleRouteJson.minTraceWidth);
  }
  findConnectionForTrace(e54) {
    const t4 = this.connectionByTraceId.get(e54.pcb_trace_id);
    if (t4 !== undefined)
      return t4 ?? undefined;
    const n8 = this.getTraceConnectionNames(e54), o10 = this.inputProblem.simpleRouteJson.connections.find((e60) => [e60.name, e60.source_trace_id, e60.rootConnectionName, e60.netConnectionName, ...e60.mergedConnectionNames ?? []].filter((e61) => Boolean(e61)).some((e61) => n8.includes(e61))) ?? null;
    return this.connectionByTraceId.set(e54.pcb_trace_id, o10), o10 ?? undefined;
  }
  getTraceConnectionNames(e54) {
    return [e54.connection_name, e54.source_trace_id, e54.rootConnectionName, ...e54.mergedConnectionNames ?? []].filter((e60) => Boolean(e60));
  }
  createStats() {
    return { phase: this.phase, corridorSegment: this.corridorCursor, corridorSegmentCount: this.corridor.length, blockingTraceCount: this.blockersByTrace.size, blockerCursor: this.blockerCursor, pushedTraceIndex: this.currentBlocker?.traceIndex, anchorRange: this.currentRange, traceWidth: this.currentTraceWidth, gridSize: this.gridResolutions[this.resolutionCursor], gridOffsetVariant: this.offsetCursor, attemptedGridCount: this.attemptedGridCount };
  }
  computeProgress() {
    return this.phase === "scan-corridor" ? this.corridor.length === 0 ? 0.25 : this.corridorCursor / this.corridor.length * 0.25 : this.blockers.length === 0 ? 0.5 : Math.min(0.99, 0.25 + this.blockerCursor / this.blockers.length);
  }
  getOutput() {
    return this.output;
  }
  getConstructorParams() {
    return [this.inputProblem];
  }
  visualize() {
    const e54 = [];
    for (let t4 = 0;t4 < this.traces.length; t4++) {
      const n8 = this.traces[t4];
      for (let o10 = 0;o10 < n8.route.length - 1; o10++) {
        const i8 = n8.route[o10], r9 = n8.route[o10 + 1];
        Mee(i8) && Mee(r9) && i8.layer === r9.layer && e54.push({ points: [i8, r9], strokeColor: t4 === this.currentBlocker?.traceIndex ? "#1769d2" : "#777", strokeWidth: Math.max(i8.width, r9.width) });
      }
    }
    for (const t4 of this.corridor)
      e54.push({ points: [t4.start, t4.end], strokeColor: "rgba(255, 128, 0, 0.55)", strokeWidth: t4.width });
    return { coordinateSystem: "cartesian", title: this.getSolverName(), lines: e54, points: [], rects: [], circles: [], texts: [] };
  }
};
var Nee = 0.000001;
var Ree = (e54, t4) => Math.hypot(e54.x - t4.x, e54.y - t4.y);
var Tee = (e54, t4, n8) => {
  const o10 = n8.x - t4.x, i8 = n8.y - t4.y, r9 = o10 * o10 + i8 * i8, s7 = r9 <= 0.000000000001 ? 0 : Math.max(0, Math.min(1, ((e54.x - t4.x) * o10 + (e54.y - t4.y) * i8) / r9));
  return Math.hypot(e54.x - (t4.x + s7 * o10), e54.y - (t4.y + s7 * i8));
};
var Eee = (e54, t4, n8) => (t4.x - e54.x) * (n8.y - e54.y) - (t4.y - e54.y) * (n8.x - e54.x);
var Aee = (e54, t4, n8, o10) => ((e60, t10, n10, o11) => {
  const i8 = Eee(n10, o11, e60), r9 = Eee(n10, o11, t10), s7 = Eee(e60, t10, n10), a9 = Eee(e60, t10, o11);
  return (i8 > 0 && r9 < 0 || i8 < 0 && r9 > 0) && (s7 > 0 && a9 < 0 || s7 < 0 && a9 > 0);
})(e54, t4, n8, o10) ? 0 : Math.min(Tee(e54, n8, o10), Tee(t4, n8, o10), Tee(n8, e54, t4), Tee(o10, e54, t4));
var Oee = (e54) => {
  const t4 = (e54.ccwRotationDegrees ?? 0) * Math.PI / 180, n8 = Math.cos(t4), o10 = Math.sin(t4);
  return [{ x: -e54.width / 2, y: -e54.height / 2 }, { x: e54.width / 2, y: -e54.height / 2 }, { x: e54.width / 2, y: e54.height / 2 }, { x: -e54.width / 2, y: e54.height / 2 }].map((t10) => ({ x: e54.center.x + t10.x * n8 - t10.y * o10, y: e54.center.y + t10.x * o10 + t10.y * n8 }));
};
var kee = (e54) => {
  if (!(e54.type === "oval" || e54.shape === "circle"))
    return false;
  if (Math.abs(e54.width - e54.height) > Nee)
    throw new Error(`Physical connectivity does not yet support non-circular oval obstacle ${e54.obstacleId ?? "<unknown>"}`);
  return true;
};
var Dee = (e54, t4) => {
  for (let n10 = 0;n10 < t4.length; n10++)
    if (Tee(e54, t4[n10], t4[(n10 + 1) % t4.length]) <= Nee)
      return true;
  let n8 = false;
  for (let o10 = 0, i8 = t4.length - 1;o10 < t4.length; i8 = o10++) {
    const r9 = t4[o10], s7 = t4[i8];
    r9.y > e54.y != s7.y > e54.y && e54.x < (s7.x - r9.x) * (e54.y - r9.y) / (s7.y - r9.y) + r9.x && (n8 = !n8);
  }
  return n8;
};
var Lee = (e54, t4) => {
  if (kee(t4))
    return Math.max(0, Ree(e54, t4.center) - t4.width / 2);
  const n8 = Oee(t4);
  return Dee(e54, n8) ? 0 : Math.min(...n8.map((t10, o10) => Tee(e54, t10, n8[(o10 + 1) % n8.length])));
};
var zee = (e54, t4) => {
  if (kee(e54))
    return kee(t4) ? Math.max(0, Ree(e54.center, t4.center) - e54.width / 2 - t4.width / 2) : Math.max(0, Lee(e54.center, t4) - e54.width / 2);
  if (kee(t4))
    return zee(t4, e54);
  const n8 = Oee(e54), o10 = Oee(t4);
  if (Dee(n8[0], o10) || Dee(o10[0], n8))
    return 0;
  let i8 = Number.POSITIVE_INFINITY;
  for (let e60 = 0;e60 < n8.length; e60++)
    for (let t10 = 0;t10 < o10.length; t10++)
      i8 = Math.min(i8, Aee(n8[e60], n8[(e60 + 1) % n8.length], o10[t10], o10[(t10 + 1) % o10.length]));
  return i8;
};
var Bee = (e54, t4) => ({ minX: e54.minX - t4, minY: e54.minY - t4, maxX: e54.maxX + t4, maxY: e54.maxY + t4 });
var Fee = (e54) => ({ minX: e54.x, minY: e54.y, maxX: e54.x, maxY: e54.y });
var jee = (e54) => {
  if (kee(e54))
    return Bee(Fee(e54.center), e54.width / 2);
  const t4 = Oee(e54);
  return { minX: Math.min(...t4.map((e60) => e60.x)), minY: Math.min(...t4.map((e60) => e60.y)), maxX: Math.max(...t4.map((e60) => e60.x)), maxY: Math.max(...t4.map((e60) => e60.y)) };
};
var $ee = (e54, t4) => {
  if (!((e60, t10) => e60.layers.some((e61) => t10.layers.includes(e61)))(e54, t4) || !((e60, t10) => e60.maxX + Nee >= t10.minX && t10.maxX + Nee >= e60.minX && e60.maxY + Nee >= t10.minY && t10.maxY + Nee >= e60.minY)(e54.bounds, t4.bounds))
    return false;
  if (e54.kind === "bridge-pad") {
    const n8 = { kind: "obstacle", obstacle: e54.obstacle, layers: e54.layers, bounds: e54.bounds };
    return t4.kind === "bridge-pad" ? $ee(n8, { kind: "obstacle", obstacle: t4.obstacle, layers: t4.layers, bounds: t4.bounds }) : $ee(n8, t4);
  }
  return t4.kind === "bridge-pad" ? $ee(t4, e54) : e54.kind === "endpoint" ? t4.kind === "endpoint" ? Ree(e54.point, t4.point) <= Nee : t4.kind === "obstacle" ? Lee(e54.point, t4.obstacle) <= Nee : t4.kind === "segment" ? Tee(e54.point, t4.start, t4.end) <= t4.width / 2 + Nee : Ree(e54.point, t4.center) <= t4.diameter / 2 + Nee : t4.kind === "endpoint" ? $ee(t4, e54) : e54.kind === "obstacle" ? t4.kind === "obstacle" ? zee(e54.obstacle, t4.obstacle) <= Nee : t4.kind === "segment" ? ((e60, t10, n8) => {
    if (kee(n8))
      return Math.max(0, Tee(n8.center, e60, t10) - n8.width / 2);
    const o10 = Oee(n8);
    return Dee(e60, o10) || Dee(t10, o10) ? 0 : Math.min(...o10.map((n10, i8) => Aee(e60, t10, n10, o10[(i8 + 1) % o10.length])));
  })(t4.start, t4.end, e54.obstacle) <= t4.width / 2 + Nee : Lee(t4.center, e54.obstacle) <= t4.diameter / 2 + Nee : t4.kind === "obstacle" ? $ee(t4, e54) : e54.kind === "segment" ? t4.kind === "segment" ? Aee(e54.start, e54.end, t4.start, t4.end) <= (e54.width + t4.width) / 2 + Nee : Tee(t4.center, e54.start, e54.end) <= e54.width / 2 + t4.diameter / 2 + Nee : t4.kind === "segment" ? $ee(t4, e54) : Ree(e54.center, t4.center) <= (e54.diameter + t4.diameter) / 2 + Nee;
};
var Yee = class {
  parent;
  constructor(e54) {
    this.parent = Array.from({ length: e54 }, (e60, t4) => t4);
  }
  find(e54) {
    const t4 = this.parent[e54];
    if (t4 === e54)
      return e54;
    const n8 = this.find(t4);
    return this.parent[e54] = n8, n8;
  }
  union(e54, t4) {
    const n8 = this.find(e54), o10 = this.find(t4);
    n8 !== o10 && (this.parent[o10] = n8);
  }
};
var Xee = (e54, t4) => {
  const n8 = t4.indexOf(e54.from_layer), o10 = t4.indexOf(e54.to_layer);
  return n8 < 0 || o10 < 0 ? [...new Set([e54.from_layer, e54.to_layer])] : t4.slice(Math.min(n8, o10), Math.max(n8, o10) + 1);
};
var Hee = (e54) => [e54.pcb_trace_id, e54.connection_name, e54.source_trace_id, e54.rootConnectionName, ...e54.mergedConnectionNames ?? [], ...e54.connectsTo ?? []].filter((e60) => Boolean(e60));
var Vee = (e54) => [e54.name, e54.source_trace_id, e54.rootConnectionName, ...e54.mergedConnectionNames ?? [], e54.netConnectionName, ...e54.pointsToConnect.flatMap((e60) => [e60.pointId, e60.pcb_port_id])].filter((e60) => Boolean(e60));
var Wee = (e54) => [e54.obstacleId, ...e54.connectedTo, ...e54.offBoardConnectsTo ?? []].filter((e60) => Boolean(e60));
var Gee = (e54, t4, n8, o10) => ({ kind: "bridge-contact", center: { x: e54.x, y: e54.y }, diameter: t4, layers: n8, bridgeId: o10, bounds: Bee(Fee(e54), t4 / 2) });
var Uee = 0.01;
var Zee = { "0603": { horizontalWidth: 0.8, horizontalHeight: 0.95, centerSpacings: [1.65, 1.8] }, 1206: { horizontalWidth: 0.6, horizontalHeight: 1.6, centerSpacings: [3.2] }, "1206x4_pair": { horizontalWidth: 0.8, horizontalHeight: 0.5, centerSpacings: [2.7] } };
var qee = (e54, t4, n8) => {
  if (!e54.layer)
    throw new Error(`Jumper ${n8} is missing its layer`);
  const o10 = Zee[e54.footprint];
  if (!o10)
    throw new Error(`Unsupported jumper footprint ${String(e54.footprint)} on ${n8}`);
  const i8 = Math.abs(e54.end.x - e54.start.x), r9 = Math.abs(e54.end.y - e54.start.y), s7 = (e60) => o10.centerSpacings.some((t10) => Math.abs(e60 - t10) < Uee), a9 = r9 < Uee && s7(i8), c5 = i8 < Uee && s7(r9);
  if (!a9 && !c5)
    throw new Error(`Jumper ${n8} does not match ${e54.footprint} pad spacing`);
  const l5 = { type: "rect", center: { ...t4 }, width: a9 ? o10.horizontalWidth : o10.horizontalHeight, height: a9 ? o10.horizontalHeight : o10.horizontalWidth, layers: [e54.layer], connectedTo: [] };
  return { kind: "bridge-pad", obstacle: l5, layers: l5.layers, bridgeId: n8, bounds: jee(l5) };
};
var Jee = (e54, t4, n8) => {
  if (e54.layer !== n8.layer || t4.layer !== n8.layer)
    return false;
  const o10 = (e60, t10) => Math.abs(e60.x - t10.x) < Uee && Math.abs(e60.y - t10.y) < Uee, i8 = o10(e54, n8.start) && o10(t4, n8.end), r9 = o10(e54, n8.end) && o10(t4, n8.start);
  return i8 || r9;
};
var Qee = (e54, t4, n8, o10) => {
  const i8 = [], r9 = e54.route.flatMap((e60, t10) => e60.route_type === "jumper" ? [{ routePoint: e60, routePointIndex: t10 }] : []), s7 = new Map;
  for (const t10 of r9) {
    const n10 = [];
    for (let o12 = 1;o12 < e54.route.length; o12++) {
      const i9 = e54.route[o12 - 1], r10 = e54.route[o12];
      i9?.route_type === "wire" && r10?.route_type === "wire" && Jee(i9, r10, t10.routePoint) && n10.push(o12);
    }
    if (n10.length !== 1)
      throw new Error(`Jumper ${e54.pcb_trace_id}:${t10.routePointIndex} matched ${n10.length} placeholder wire segments`);
    const o11 = n10[0];
    if (s7.has(o11))
      throw new Error(`Multiple jumpers matched placeholder segment ${o11} on ${e54.pcb_trace_id}`);
    s7.set(o11, t10);
  }
  let a9;
  for (let r10 = 0;r10 < e54.route.length; r10++) {
    const c5 = e54.route[r10];
    if (c5.route_type === "wire") {
      if (a9 && a9.layer === c5.layer && Ree(a9, c5) > Nee) {
        const e60 = a9;
        if (s7.get(r10))
          ;
        else {
          const t10 = e60.width / 2;
          i8.push({ kind: "segment", start: { x: e60.x, y: e60.y }, end: { x: c5.x, y: c5.y }, width: e60.width, layers: [e60.layer], bounds: Bee({ minX: Math.min(e60.x, c5.x), minY: Math.min(e60.y, c5.y), maxX: Math.max(e60.x, c5.x), maxY: Math.max(e60.y, c5.y) }, t10) });
        }
      }
      a9 = c5;
      continue;
    }
    if (a9 = undefined, c5.route_type === "via") {
      const o11 = e54.route[r10 - 1], s9 = e54.route[r10 + 1];
      for (const t10 of [o11, s9])
        if (t10?.route_type === "wire" && Ree(t10, c5) > Nee)
          throw new Error(`Via ${e54.pcb_trace_id}:${r10} is adjacent to a non-colocated wire endpoint`);
      const a10 = c5.via_diameter ?? n8;
      i8.push({ kind: "via", center: { x: c5.x, y: c5.y }, diameter: a10, layers: Xee(c5, t4), bounds: Bee(Fee(c5), a10 / 2) });
      continue;
    }
    const l5 = `${e54.pcb_trace_id}:${r10}:${c5.route_type}`;
    if (c5.route_type === "jumper") {
      i8.push(qee(c5, c5.start, l5), qee(c5, c5.end, l5));
      continue;
    }
    if (c5.route_type === "through_obstacle") {
      if (!o10.find((e60) => e60.layers.includes(c5.from_layer) && e60.layers.includes(c5.to_layer) && Lee(c5.start, e60) <= Nee && Lee(c5.end, e60) <= Nee))
        throw new Error(`Through-obstacle marker ${l5} has no same-net multilayer obstacle witness`);
      i8.push(Gee(c5.start, 0, [c5.from_layer], l5), Gee(c5.end, 0, [c5.to_layer], l5));
      continue;
    }
    throw new Error(`Unsupported route primitive: ${String(c5.route_type)}`);
  }
  return i8;
};
var Kee = (e54, t4, n8) => {
  const o10 = e54.pointsToConnect[n8];
  return o10.pointId ?? o10.pcb_port_id ?? `${e54.name}[${t4}:${n8}]`;
};
var ete = (e54) => {
  const t4 = {}, n8 = {}, o10 = [];
  for (let i8 = 0;i8 < e54.connections.length; i8++) {
    const r9 = e54.connections[i8];
    for (let e60 = 0;e60 < r9.pointsToConnect.length; e60++) {
      const s7 = `${i8}:${e60}`;
      t4[s7] = Kee(r9, i8, e60), n8[s7] = s7, o10.push([s7]);
    }
  }
  return { endpointCount: Object.keys(t4).length, endpointLabels: t4, componentByEndpointKey: n8, endpointComponents: o10 };
};
var tte = (e54) => {
  if (e54 === null || typeof e54 != "object")
    return JSON.stringify(e54) ?? String(e54);
  if (Array.isArray(e54))
    return `[${e54.map((e60) => tte(e60)).join(",")}]`;
  const t4 = e54;
  return `{${Object.keys(t4).sort().map((e60) => `${JSON.stringify(e60)}:${tte(t4[e60])}`).join(",")}}`;
};
var nte = (e54, t4) => {
  const n8 = new D7(e54, t4, { includePhysicalPositionAliases: true }), o10 = (i8 = e54.layerCount) <= 1 ? ["top"] : i8 === 2 ? ["top", "bottom"] : ["top", ...Array.from({ length: i8 - 2 }, (e60, t10) => `inner${t10 + 1}`), "bottom"];
  var i8;
  const r9 = ((e60) => {
    const t10 = e60.min_via_hole_diameter ?? e60.minViaHoleDiameter ?? 0;
    return Math.max(t10, e60.min_via_pad_diameter ?? e60.minViaPadDiameter ?? e60.minViaDiameter ?? 0.6);
  })(e54), s7 = new Map, a9 = new Map, c5 = {}, l5 = (e60, t10) => {
    const n10 = s7.get(e60) ?? [];
    n10.push(t10), s7.set(e60, n10);
  };
  for (let t10 = 0;t10 < e54.connections.length; t10++) {
    const o11 = e54.connections[t10], i9 = n8.canonicalize(Vee(o11));
    if (i9.length !== 1)
      throw new Error(`Connection ${o11.name} resolved to ${i9.length} canonical nets`);
    for (let e60 = 0;e60 < o11.pointsToConnect.length; e60++) {
      const n10 = o11.pointsToConnect[e60], r10 = `${t10}:${e60}`, s9 = Kee(o11, t10, e60);
      c5[r10] = s9;
      const a10 = { kind: "endpoint", endpointKey: r10, endpointLabel: s9, point: { x: n10.x, y: n10.y }, layers: n10.layers ?? [n10.layer], bounds: Fee(n10) };
      for (const e61 of i9)
        l5(e61, a10);
    }
  }
  for (const t10 of e54.obstacles) {
    const e60 = { kind: "obstacle", obstacle: t10, layers: t10.layers, bounds: jee(t10) };
    for (const o11 of n8.canonicalize(Wee(t10))) {
      const n10 = a9.get(o11) ?? [];
      n10.push(t10), a9.set(o11, n10), s7.has(o11) && l5(o11, e60);
    }
  }
  for (const i9 of [...t4, ...e54.fixedTraces ?? []]) {
    const e60 = n8.canonicalize(Hee(i9));
    if (e60.length !== 1)
      throw new Error(`Trace ${i9.pcb_trace_id} resolved to ${e60.length} canonical nets`);
    const t10 = a9.get(e60[0]) ?? [], c9 = Qee(i9, o10, r9, t10);
    for (const t11 of e60)
      if (s7.has(t11))
        for (const e61 of c9)
          l5(t11, e61);
  }
  const h5 = {}, d9 = [];
  for (const e60 of s7.values()) {
    const t10 = new Yee(e60.length), n10 = new Map;
    for (let o12 = 0;o12 < e60.length; o12++) {
      const i10 = e60[o12];
      if (i10.kind !== "bridge-contact" && i10.kind !== "bridge-pad")
        continue;
      const r10 = n10.get(i10.bridgeId);
      r10 === undefined ? n10.set(i10.bridgeId, o12) : t10.union(r10, o12);
    }
    const o11 = e60.length > 0 ? new xee(e60.length) : null;
    if (o11) {
      for (const t11 of e60)
        o11.add(t11.bounds.minX, t11.bounds.minY, t11.bounds.maxX, t11.bounds.maxY);
      o11.finish();
    }
    for (let n11 = 0;n11 < e60.length; n11++) {
      const i10 = e60[n11], r10 = o11?.search(i10.bounds.minX - Nee, i10.bounds.minY - Nee, i10.bounds.maxX + Nee, i10.bounds.maxY + Nee) ?? [];
      for (const o12 of r10)
        o12 <= n11 || $ee(i10, e60[o12]) && t10.union(n11, o12);
    }
    const i9 = new Map;
    for (let n11 = 0;n11 < e60.length; n11++) {
      const o12 = e60[n11];
      if (o12.kind !== "endpoint")
        continue;
      const r10 = t10.find(n11), s9 = i9.get(r10) ?? [];
      s9.push(o12.endpointKey), i9.set(r10, s9);
    }
    for (const e61 of i9.values()) {
      e61.sort();
      const t11 = e61[0];
      d9.push(e61);
      for (const n11 of e61) {
        if (h5[n11] !== undefined)
          throw new Error(`Endpoint ${n11} was assigned to multiple canonical nets`);
        h5[n11] = t11;
      }
    }
  }
  return d9.sort(([e60 = ""], [t10 = ""]) => e60.localeCompare(t10)), { endpointCount: Object.keys(c5).length, endpointLabels: c5, componentByEndpointKey: h5, endpointComponents: d9 };
};
var ote = class {
  baseline;
  inputProblem;
  baselineCaptureError;
  baselineTraceSignature;
  constructor(e54, t4) {
    this.inputProblem = e54, this.baselineTraceSignature = tte(t4);
    try {
      this.baseline = nte(e54, t4), this.baselineCaptureError = null;
    } catch (t10) {
      this.baseline = ete(e54), this.baselineCaptureError = t10 instanceof Error ? t10.message : String(t10);
    }
  }
  validate(e54) {
    if (this.baselineCaptureError) {
      const t10 = tte(e54) === this.baselineTraceSignature;
      return { safe: t10, candidate: this.baseline, regressions: [], validationError: t10 ? `Connectivity validation is limited to exact trace preservation: ${this.baselineCaptureError}` : `Connectivity validation failed closed: ${this.baselineCaptureError}` };
    }
    let t4;
    try {
      t4 = nte(this.inputProblem, e54);
    } catch (e60) {
      return { safe: false, candidate: ete(this.inputProblem), regressions: [], validationError: `Connectivity validation failed closed: ${e60 instanceof Error ? e60.message : String(e60)}` };
    }
    const n8 = [];
    for (const e60 of this.baseline.endpointComponents) {
      if (e60.length < 2)
        continue;
      const o10 = new Map;
      for (const n10 of e60) {
        const e61 = t4.componentByEndpointKey[n10] ?? `missing:${n10}`, i8 = o10.get(e61) ?? [];
        i8.push(n10), o10.set(e61, i8);
      }
      o10.size <= 1 || n8.push({ baselineEndpointKeys: [...e60], baselineEndpointLabels: e60.map((e61) => this.baseline.endpointLabels[e61]), candidateComponents: [...o10.values()] });
    }
    return { safe: n8.length === 0, candidate: t4, regressions: n8 };
  }
};
var rte = [{ x: 0, y: 0 }, { x: 0.5, y: 0.5 }];
var ste = [0.15, 0.2, 0.25, 0.3, 0.4, 0.5];
var ate = (e54) => e54?.route_type === "wire";
var cte = (e54) => e54?.route_type === "via";
var lte = Array.from({ length: 24 }, (e54, t4) => {
  const n8 = t4 * Math.PI / 12;
  return { x: Math.cos(n8), y: Math.sin(n8) };
});
var hte = (e54) => [...new Set(e54.map((e60) => Number(e60.toFixed(6))))].sort((e60, t4) => t4 - e60);
var dte = class extends BaseSolver {
  inputProblem;
  traces;
  obstacleIndex;
  phase = "repair-vias";
  traceCursor = 0;
  routeCursor = 0;
  candidateCursor = 0;
  clearanceTierCursor = 0;
  attemptedCandidateCount = 0;
  attemptedClearanceShoveCount = 0;
  attemptedViaGridCount = 0;
  committedClearanceShoveCount = 0;
  viaPairCountRemoved = 0;
  viaCountRemoved = 0;
  simplifiedPathCount = 0;
  normalizedSegmentCount = 0;
  achievedExtraClearanceCount = 0;
  relocatedViaCount = 0;
  unresolvedViaCount = 0;
  attemptedPushedViaRepairCount = 0;
  committedPushedViaRepairCount = 0;
  padClearanceRerouteCount = 0;
  unresolvedPadClearanceCount = 0;
  initialPadClearanceViolationCount = 0;
  remainingPadClearanceViolationCount = 0;
  initialPadClearanceViolationCountByClearance = {};
  remainingPadClearanceViolationCountByClearance = {};
  budgetLimited = false;
  connectivityValidationCount = 0;
  connectivityRollbackCount = 0;
  connectivityRegressionEndpointIds = [];
  connectivityValidationError = null;
  connectivityRollbackMutationStats = null;
  connectionNameResolver;
  connectionByTraceId = new Map;
  connectivityInvariant;
  initialConnectivitySafeTraces;
  mutableTraceIndices;
  mutableTraceIndexSet;
  viaRepairTraceIndices;
  traceIndices;
  maxRerouteLength;
  clearancePaddingTiers;
  desiredPadClearance;
  initialTraceLengths = new Map;
  candidates = [];
  candidateShoveCount = 0;
  rollbackTraces = null;
  baseCandidateValidated = false;
  activeShovePadding = 0;
  viaGridAttempt = null;
  candidateSetMayUseGridFallback = false;
  pendingPushedViaRepair = null;
  alternatePushedViaRepairs = [];
  pushedViaRepairRollbackTraces = null;
  connectivityFinalized = false;
  finalizedMutatedTraceIndices = [];
  resumePhase = "scan-via-pairs";
  constructor(e54) {
    super(), this.inputProblem = structuredClone(e54), this.traces = structuredClone(e54.traces), this.initialConnectivitySafeTraces = structuredClone(e54.traces), this.connectivityInvariant = new ote(this.inputProblem.simpleRouteJson, this.initialConnectivitySafeTraces), this.connectionNameResolver = new D7(e54.simpleRouteJson, this.traces), this.maxRerouteLength = e54.maxRerouteLength ?? 10, this.desiredPadClearance = e54.desiredPadClearance, this.clearancePaddingTiers = hte([...e54.clearancePaddingTiers ?? [0.1, 0.05, 0], 0]).filter((e60) => e60 >= 0);
    const t4 = this.traces.map((e60, t10) => t10), n8 = (e60, t10, n10) => {
      const o11 = [...new Set(e60 ?? n10)];
      for (const e61 of o11)
        if (!Number.isInteger(e61) || e61 < 0 || e61 >= this.traces.length)
          throw new RangeError(`Invalid cleanup ${t10} index: ${e61}`);
      return o11;
    }, o10 = n8(e54.traceIndices, "trace", t4);
    this.viaRepairTraceIndices = n8(e54.viaRepairTraceIndices, "via repair trace", o10), this.mutableTraceIndices = n8(e54.mutableTraceIndices, "mutable trace", o10), this.mutableTraceIndexSet = new Set(this.mutableTraceIndices), this.traceIndices = o10.filter((e60) => this.resolveNominalTraceWidth(this.traces[e60]) >= 0.499999);
    for (const e60 of this.traceIndices)
      this.initialTraceLengths.set(e60, this.measureTraceLength(this.traces[e60]));
    this.obstacleIndex = this.createObstacleIndex(), this.initialPadClearanceViolationCount = this.countPadClearanceViolations(), this.remainingPadClearanceViolationCount = this.initialPadClearanceViolationCount, this.initialPadClearanceViolationCountByClearance = this.countPadClearanceViolationsByTier(), this.remainingPadClearanceViolationCountByClearance = { ...this.initialPadClearanceViolationCountByClearance }, this.activeSubSolver = null, this.MAX_ITERATIONS = 1e6, this.stats = this.createStats();
  }
  getSolverName() {
    return "PowerTraceCleanupSolver";
  }
  _step() {
    if (this.activeSubSolver) {
      const e54 = this.activeSubSolver;
      return this.stepActiveShoveSolver(), void ((e54.solved || e54.failed) && (this.stats = this.createStats()));
    }
    switch (this.phase) {
      case "repair-vias":
        this.repairNextVia();
        break;
      case "scan-via-pairs":
        this.scanNextViaPair();
        break;
      case "scan-pad-clearance":
        this.scanNextPadClearance();
        break;
      case "scan-simplification":
        this.scanNextSimplification();
        break;
      case "evaluate-candidate":
        this.evaluateCurrentCandidate();
        break;
      case "shove-clearance":
        break;
      case "route-via-pair":
        this.startNextViaGridCandidate();
        break;
      case "complete":
        this.ensureConnectivitySafeOutput(), this.solved = true;
    }
    this.stats = this.createStats();
  }
  repairNextVia() {
    const e54 = this.viaRepairTraceIndices[this.traceCursor], t4 = e54 === undefined ? undefined : this.traces[e54];
    if (!t4)
      return this.traceCursor = 0, this.routeCursor = 0, this.phase = "scan-via-pairs", void this.rebuildObstacleIndex();
    const n8 = t4.route.findIndex((e60, t10) => t10 >= this.routeCursor && cte(e60));
    if (n8 === -1)
      return this.traceCursor++, void (this.routeCursor = 0);
    this.routeCursor = n8 + 1;
    const o10 = t4.route[n8], i8 = t4.route[n8 - 1], r9 = t4.route[n8 + 1];
    if (!cte(o10) || !ate(i8) || !ate(r9))
      return;
    const s7 = this.getTraceConnectionNames(t4), a9 = this.getBaseObstacleClearance();
    if (!this.obstacleIndex.collidesVia({ point: o10, layers: this.obstacleIndex.boardLayers, padDiameter: o10.via_diameter ?? 0.6, holeDiameter: o10.via_hole_diameter ?? this.obstacleIndex.defaultViaHoleDiameter, connectionNames: s7, ignoreTraceIndex: e54, ignoreRouteRange: { start: n8, end: n8 }, obstacleClearance: a9, blockSameNetObstacles: true, sameNetObstacleClearance: 0 }))
      return;
    const c5 = this.findViaRepair(t4, n8, a9);
    if (!c5) {
      const e60 = this.findPushableViaRepairs(t4, n8, a9), o11 = e60.shift();
      return o11 ? (this.alternatePushedViaRepairs = e60, void this.startPushedViaRepair(o11)) : void this.unresolvedViaCount++;
    }
    t4.route.splice(c5.startIndex, c5.endIndex - c5.startIndex + 1, ...c5.route), this.relocatedViaCount++, this.routeCursor = c5.startIndex + c5.route.length, this.rebuildObstacleIndex();
  }
  findViaRepair(e54, t4, n8) {
    const o10 = this.createViaRepairContext(e54, t4);
    if (!o10)
      return null;
    const i8 = o10.candidates.map((e60) => ({ point: e60, movedLength: z7(o10.leftAnchor, e60) + z7(e60, o10.rightAnchor) })).filter(({ movedLength: e60 }) => e60 <= o10.originalLength + Math.min(6, this.maxRerouteLength) + L7);
    i8.sort((e60, t10) => e60.movedLength - t10.movedLength || z7(e60.point, o10.via) - z7(t10.point, o10.via));
    for (const e60 of i8)
      if (this.isViaRepairPointSafe(o10, e60.point, n8))
        return this.createViaRepairReplacement(o10, e60.point);
    return null;
  }
  findPushableViaRepairs(e54, t4, n8) {
    const o10 = this.viaRepairTraceIndices[this.traceCursor];
    if (o10 === undefined)
      return [];
    const i8 = this.createViaRepairContext(e54, t4);
    if (!i8)
      return [];
    const r9 = i8.candidates.flatMap((e60) => {
      const t10 = z7(i8.leftAnchor, e60) + z7(e60, i8.rightAnchor);
      if (t10 > i8.originalLength + Math.min(6, this.maxRerouteLength) + L7)
        return [];
      const r10 = new Set, s7 = this.getViaRepairCollisionQueries(i8, e60, n8);
      for (const e61 of s7)
        for (const t11 of this.obstacleIndex.findCollisions(e61)) {
          if (t11.kind !== "trace" || t11.traceIndex === undefined || t11.traceIndex === o10 || !this.mutableTraceIndexSet.has(t11.traceIndex))
            return [];
          r10.add(t11.traceIndex);
        }
      if (r10.size === 0 || r10.size > 2)
        return [];
      const a9 = [...r10];
      return this.isViaRepairPointSafe(i8, e60, n8, a9) ? [{ point: e60, movedLength: t10, blockerCount: r10.size, blockerKey: [...r10].sort((e61, t11) => e61 - t11).join(",") }] : [];
    });
    r9.sort((e60, t10) => e60.blockerCount - t10.blockerCount || e60.movedLength - t10.movedLength || z7(e60.point, i8.via) - z7(t10.point, i8.via));
    return [...new Map([...r9].reverse().map((e60) => [e60.blockerKey, e60])).values(), ...r9].filter((e60, t10, n10) => n10.findIndex((t11) => t11.point.x === e60.point.x && t11.point.y === e60.point.y) === t10).slice(0, 12).map((e60) => ({ traceIndex: o10, viaIndex: t4, point: e60.point, padClearance: n8, corridor: [{ start: i8.leftAnchor, end: e60.point, layer: i8.leftWire.layer, width: i8.leftWire.width }, { start: e60.point, end: i8.rightAnchor, layer: i8.rightWire.layer, width: i8.rightWire.width }, ...this.obstacleIndex.boardLayers.map((t10) => ({ start: e60.point, end: e60.point, layer: t10, width: i8.viaDiameter }))] }));
  }
  createViaRepairContext(e54, t4) {
    const n8 = e54.route[t4], o10 = e54.route[t4 - 1], i8 = e54.route[t4 + 1];
    if (!cte(n8) || !ate(o10) || !ate(i8))
      return null;
    const r9 = t4 - 1 == 0 || !ate(e54.route[t4 - 2]), s7 = t4 + 1 === e54.route.length - 1 || !ate(e54.route[t4 + 2]), a9 = r9 ? o10 : e54.route[t4 - 2], c5 = s7 ? i8 : e54.route[t4 + 2], l5 = z7(a9, n8) + z7(n8, c5), h5 = this.getTraceConnectionNames(e54), d9 = n8.via_diameter ?? 0.6, u9 = n8.via_hole_diameter ?? this.obstacleIndex.defaultViaHoleDiameter, p9 = Math.max(0.3, u9 + this.obstacleIndex.minViaHoleEdgeToViaHoleEdgeClearance + 0.05), m9 = [p9, p9 + 0.15, p9 + 0.3, p9 + 0.5, p9 + 0.75, p9 + 1, p9 + 1.5, p9 + 2].flatMap((e60) => lte.map((t10) => ({ x: 0.025 * Math.round((n8.x + t10.x * e60) / 0.025), y: 0.025 * Math.round((n8.y + t10.y * e60) / 0.025) }))), g10 = [...m9, ...m9.flatMap((e60) => [{ x: e60.x, y: Math.floor(10 * n8.y) / 10 }, { x: e60.x, y: Math.ceil(10 * n8.y) / 10 }, { x: Math.floor(10 * n8.x) / 10, y: e60.y }, { x: Math.ceil(10 * n8.x) / 10, y: e60.y }])].filter((e60, t10, n10) => n10.findIndex((t11) => t11.x === e60.x && t11.y === e60.y) === t10);
    return { trace: e54, viaIndex: t4, via: n8, leftWire: o10, rightWire: i8, leftIsEndpoint: r9, rightIsEndpoint: s7, leftAnchor: a9, rightAnchor: c5, originalLength: l5, connectionNames: h5, viaDiameter: d9, holeDiameter: u9, ignoreRouteRange: { start: Math.max(0, t4 - 2), end: Math.min(e54.route.length - 1, t4 + 2) }, candidates: g10 };
  }
  getViaRepairCollisionQueries(e54, t4, n8, o10) {
    const i8 = this.viaRepairTraceIndices[this.traceCursor], r9 = { connectionNames: e54.connectionNames, ignoreTraceIndex: i8, ignoreTraceIndices: o10, ignoreRouteRange: e54.ignoreRouteRange, obstacleClearance: n8 };
    return [...this.obstacleIndex.boardLayers.map((n10) => ({ ...r9, start: t4, end: t4, layer: n10, width: e54.viaDiameter, blockSameNetObstacles: true, sameNetObstacleClearance: 0 })), { ...r9, start: e54.leftAnchor, end: t4, layer: e54.leftWire.layer, width: e54.leftWire.width }, { ...r9, start: t4, end: e54.rightAnchor, layer: e54.rightWire.layer, width: e54.rightWire.width }];
  }
  isViaRepairPointSafe(e54, t4, n8, o10) {
    const i8 = this.viaRepairTraceIndices[this.traceCursor];
    return !this.obstacleIndex.collidesVia({ point: t4, layers: this.obstacleIndex.boardLayers, padDiameter: e54.viaDiameter, holeDiameter: e54.holeDiameter, connectionNames: e54.connectionNames, ignoreTraceIndex: i8, ignoreTraceIndices: o10, ignoreRouteRange: { start: e54.viaIndex, end: e54.viaIndex }, obstacleClearance: n8, blockSameNetObstacles: true, sameNetObstacleClearance: 0 }) && !this.getViaRepairCollisionQueries(e54, t4, n8, o10).slice(this.obstacleIndex.boardLayers.length).some((e60) => this.obstacleIndex.collides(e60));
  }
  createViaRepairReplacement(e54, t4) {
    const n8 = { ...e54.leftWire, ...t4 }, o10 = { ...e54.via, ...t4 }, i8 = { ...e54.rightWire, ...t4 };
    return { startIndex: e54.viaIndex - 1, endIndex: e54.viaIndex + 1, route: [...e54.leftIsEndpoint ? [e54.leftWire] : [], n8, o10, i8, ...e54.rightIsEndpoint ? [e54.rightWire] : []] };
  }
  startPushedViaRepair(e54) {
    this.pendingPushedViaRepair = e54, this.pushedViaRepairRollbackTraces = structuredClone(this.traces), this.attemptedPushedViaRepairCount++, this.activeSubSolver = new wee({ simpleRouteJson: this.inputProblem.simpleRouteJson, traces: this.traces, powerTraceIndex: e54.traceIndex, nominalPowerWidth: Math.max(...e54.corridor.map((e60) => e60.width)), pushOnlyNominalWidthsBelow: Number.POSITIVE_INFINITY, mutableTraceIndices: this.mutableTraceIndices, corridor: e54.corridor, maxRerouteLength: this.maxRerouteLength }, this.connectionNameResolver);
  }
  finishPushedViaRepairSolver(e54) {
    const t4 = this.pendingPushedViaRepair;
    if (this.activeSubSolver = null, !t4)
      return;
    if (e54.solved) {
      const n10 = e54.getOutput();
      if (n10) {
        this.traces = n10.traces, this.rebuildObstacleIndex();
        const e60 = this.traces[t4.traceIndex], o10 = e60 ? this.createViaRepairContext(e60, t4.viaIndex) : null;
        if (o10 && this.isViaRepairPointSafe(o10, t4.point, t4.padClearance)) {
          const n11 = this.createViaRepairReplacement(o10, t4.point);
          return e60.route.splice(n11.startIndex, n11.endIndex - n11.startIndex + 1, ...n11.route), this.relocatedViaCount++, this.committedPushedViaRepairCount++, this.routeCursor = n11.startIndex + n11.route.length, this.pendingPushedViaRepair = null, this.alternatePushedViaRepairs = [], this.pushedViaRepairRollbackTraces = null, void this.rebuildObstacleIndex();
        }
      }
    }
    this.pushedViaRepairRollbackTraces && (this.traces = this.pushedViaRepairRollbackTraces), this.pendingPushedViaRepair = null, this.pushedViaRepairRollbackTraces = null;
    const n8 = this.alternatePushedViaRepairs.shift();
    if (n8)
      return this.rebuildObstacleIndex(), void this.startPushedViaRepair(n8);
    this.alternatePushedViaRepairs = [], this.unresolvedViaCount++, this.rebuildObstacleIndex();
  }
  scanNextViaPair() {
    const e54 = this.traceIndices[this.traceCursor];
    if (e54 === undefined)
      return this.traceCursor = 0, this.routeCursor = 0, void (this.phase = "scan-pad-clearance");
    const t4 = this.traces[e54], n8 = t4.route.findIndex((e60, t10) => t10 >= this.routeCursor && e60.route_type === "via");
    if (n8 === -1)
      return void this.advanceTrace();
    const o10 = t4.route.slice(n8 + 1).findIndex((e60) => e60.route_type === "via");
    if (o10 === -1)
      return void this.advanceTrace();
    const i8 = n8 - 1, r9 = n8 + 1 + o10 + 1, s7 = t4.route[i8], a9 = t4.route[r9];
    if (this.routeCursor = n8 + 1, !ate(s7) || !ate(a9) || s7.layer !== a9.layer || z7(s7, a9) > this.maxRerouteLength + L7)
      return;
    const c5 = this.createCandidates({ kind: "via-pair", traceIndex: e54, startIndex: i8, endIndex: r9 }), l5 = c5[0]?.width ?? Math.max(s7.width, a9.width), h5 = c5[0]?.padClearance ?? this.getCandidatePadClearance("via-pair", e54, i8, r9), d9 = (n10) => {
      const o11 = t4.route[n10];
      return !!ate(o11) && this.obstacleIndex.findCollisions({ start: o11, end: o11, layer: o11.layer, width: l5, connectionNames: this.getTraceConnectionNames(t4), ignoreTraceIndex: e54, ignoreRouteRange: { start: Math.max(0, i8 - 1), end: Math.min(t4.route.length - 1, r9 + 1) }, obstacleClearance: h5 }).some((e60) => e60.kind === "obstacle" && e60.obstacleKind === "pad");
    }, u9 = t4.route[i8 - 1], p9 = t4.route[r9 + 1], m9 = c5.length > 0 && d9(i8) && ate(u9) && u9.layer === s7.layer ? i8 - 1 : i8, g10 = c5.length > 0 && d9(r9) && ate(p9) && p9.layer === a9.layer ? r9 + 1 : r9, f10 = [{ startIndex: i8, endIndex: r9 }, { startIndex: m9, endIndex: r9 }, { startIndex: i8, endIndex: g10 }, { startIndex: m9, endIndex: g10 }].filter((e60, t10, n10) => n10.findIndex((t11) => t11.startIndex === e60.startIndex && t11.endIndex === e60.endIndex) === t10).flatMap((t10) => t10.startIndex === i8 && t10.endIndex === r9 ? c5 : this.createCandidates({ kind: "via-pair", traceIndex: e54, startIndex: t10.startIndex, endIndex: t10.endIndex }));
    f10.length !== 0 && this.beginCandidates(f10, "scan-via-pairs", true);
  }
  scanNextPadClearance() {
    const e54 = this.traceIndices[this.traceCursor];
    if (e54 === undefined)
      return this.traceCursor = 0, this.routeCursor = 0, void (this.phase = "scan-simplification");
    const t4 = this.traces[e54];
    if (this.resolveNominalTraceWidth(t4) < 0.499999)
      return void this.advanceTrace();
    const n8 = this.routeCursor, o10 = t4.route[n8], i8 = t4.route[n8 + 1];
    if (!ate(o10) || !ate(i8) || o10.layer !== i8.layer)
      return void (n8 >= t4.route.length - 1 ? this.advanceTrace() : this.routeCursor++);
    if (this.routeCursor++, !this.segmentHasPadClearanceViolation(e54, n8))
      return;
    const r9 = this.getPadClearanceIntervals(t4, n8).flatMap((t10) => this.getImprovedPadClearanceTiers(e54, t10.startIndex, t10.endIndex).flatMap((n10) => this.createCandidates({ kind: "pad-clearance", traceIndex: e54, startIndex: t10.startIndex, endIndex: t10.endIndex, padClearance: n10 }).slice(0, 8)));
    r9.length !== 0 ? this.beginCandidates(r9.slice(0, 72), "scan-pad-clearance", true) : this.unresolvedPadClearanceCount++;
  }
  segmentHasPadClearanceViolation(e54, t4) {
    const n8 = this.traces[e54], o10 = n8.route[t4], i8 = n8.route[t4 + 1];
    return !(!ate(o10) || !ate(i8) || o10.layer !== i8.layer) && this.obstacleIndex.findCollisions({ start: o10, end: i8, layer: o10.layer, width: Math.max(o10.width, i8.width), connectionNames: this.getTraceConnectionNames(n8), ignoreTraceIndex: e54, ignoreRouteRange: { start: Math.max(0, t4 - 1), end: Math.min(n8.route.length - 1, t4 + 2) }, obstacleClearance: this.getPadClearanceForTrace(n8) }).some((e60) => e60.kind === "obstacle" && e60.obstacleKind === "pad");
  }
  getPadClearanceIntervals(e54, t4) {
    const n8 = e54.route[t4];
    if (!ate(n8))
      return [];
    const o10 = [t4];
    let i8 = 0;
    for (let r10 = t4 - 1;r10 >= 0; r10--) {
      const t10 = e54.route[r10], s7 = e54.route[r10 + 1];
      if (!ate(t10) || !ate(s7) || t10.layer !== n8.layer || s7.layer !== n8.layer)
        break;
      if (i8 += z7(t10, s7), i8 > this.maxRerouteLength / 2 + L7)
        break;
      o10.push(r10);
    }
    const r9 = [t4 + 1];
    i8 = 0;
    for (let o11 = t4 + 1;o11 < e54.route.length - 1; o11++) {
      const t10 = e54.route[o11], s7 = e54.route[o11 + 1];
      if (!ate(t10) || !ate(s7) || t10.layer !== n8.layer || s7.layer !== n8.layer)
        break;
      if (i8 += z7(t10, s7), i8 > this.maxRerouteLength / 2 + L7)
        break;
      r9.push(o11 + 1);
    }
    return o10.flatMap((t10) => r9.map((n10) => ({ startIndex: t10, endIndex: n10, length: this.measureRouteRange(e54, t10, n10).length }))).filter((e60) => e60.length <= this.maxRerouteLength + L7 && e60.startIndex < e60.endIndex).sort((e60, t10) => t10.length - e60.length).slice(0, 8);
  }
  scanNextSimplification() {
    const e54 = this.traceIndices[this.traceCursor];
    if (e54 === undefined)
      return this.remainingPadClearanceViolationCount = this.countPadClearanceViolations(), this.remainingPadClearanceViolationCountByClearance = this.countPadClearanceViolationsByTier(), void (this.phase = "complete");
    const t4 = this.traces[e54], n8 = this.routeCursor, o10 = t4.route[n8];
    if (!ate(o10) || n8 >= t4.route.length - 1)
      return void (n8 >= t4.route.length - 1 ? this.advanceTrace() : this.routeCursor++);
    let i8 = 0;
    const r9 = [];
    for (let e60 = n8 + 1;e60 < t4.route.length; e60++) {
      const s9 = t4.route[e60 - 1], a9 = t4.route[e60];
      if (!ate(s9) || !ate(a9) || s9.layer !== o10.layer || a9.layer !== o10.layer)
        break;
      if (i8 += z7(s9, a9), i8 > this.maxRerouteLength + L7)
        break;
      const c5 = this.measureRouteRange(t4, n8, e60);
      (c5.nonOctilinearSegmentCount > 0 || c5.pointCount > 3) && r9.push(e60);
    }
    const s7 = r9.slice(-6).reverse().flatMap((t10) => this.createCandidates({ kind: "simplification", traceIndex: e54, startIndex: n8, endIndex: t10 }));
    s7.length !== 0 ? this.beginCandidates(s7, "scan-simplification") : this.routeCursor++;
  }
  createCandidates({ kind: e54, traceIndex: t4, startIndex: n8, endIndex: o10, padClearance: i8 }) {
    const r9 = this.traces[t4], s7 = r9.route[n8], a9 = r9.route[o10];
    if (!ate(s7) || !ate(a9) || s7.layer !== a9.layer)
      return [];
    const c5 = this.resolveNominalTraceWidth(r9), l5 = this.measureRouteRange(r9, n8, o10), h5 = i8 ?? this.getCandidatePadClearance(e54, t4, n8, o10), d9 = [], u9 = gee(s7, a9);
    if (e54 === "pad-clearance" && uee([s7, a9]) === 0) {
      const e60 = z7(s7, a9);
      if (e60 > L7) {
        const t10 = { x: -(a9.y - s7.y) / e60, y: (a9.x - s7.x) / e60 };
        for (const e61 of [0.25, 0.5, 0.75, 1, 1.5, 2])
          for (const n10 of [-1, 1])
            u9.push([s7, { x: s7.x + t10.x * e61 * n10, y: s7.y + t10.y * e61 * n10 }, { x: a9.x + t10.x * e61 * n10, y: a9.y + t10.y * e61 * n10 }, a9]);
      }
    }
    const p9 = new Map(u9.map((e60) => [e60.map((e61) => `${e61.x.toFixed(6)},${e61.y.toFixed(6)}`).join(";"), e60]));
    for (const i9 of p9.values()) {
      const u10 = pee(i9);
      if (u10 > this.maxRerouteLength + L7 || e54 === "pad-clearance" && u10 > 1.35 * l5.length + 0.5 || e54 === "simplification" && (u10 > 1.1 * l5.length + L7 || this.measureTraceLength(r9) - l5.length + u10 > 1.01 * (this.initialTraceLengths.get(t4) ?? this.measureTraceLength(r9)) + L7))
        continue;
      const p10 = u10 <= L7 ? c5 : c5 - l5.deficitArea / u10;
      if (p10 > c5 + L7)
        continue;
      const m9 = 0.05 * Math.ceil(Math.max(this.inputProblem.simpleRouteJson.minTraceWidth, p10) / 0.05 - L7), g10 = hte([c5, Math.min(c5, m9), Math.min(c5, Math.max(this.inputProblem.simpleRouteJson.minTraceWidth, p10))].map((e60) => Math.max(e60, s7.width)));
      for (const r10 of g10) {
        const u11 = this.measureCandidate(i9, r10, c5, a9.width, s7.width);
        u11.deficitArea > l5.deficitArea + L7 || u11.conservativeDeficitArea > l5.conservativeDeficitArea + L7 || !this.preservesCoverage(u11, l5) || (e54 !== "simplification" || l5.nonOctilinearSegmentCount !== 0 || u11.pointCount < l5.pointCount && u11.length < l5.length - L7) && d9.push({ kind: e54, traceIndex: t4, startIndex: n8, endIndex: o10, layer: s7.layer, points: i9, width: r10, padClearance: h5, originalQuality: l5 });
      }
    }
    return d9.slice(0, 18);
  }
  beginCandidates(e54, t4, n8 = false) {
    this.candidates = e54, this.candidateCursor = 0, this.clearanceTierCursor = 0, this.candidateShoveCount = 0, this.rollbackTraces = null, this.baseCandidateValidated = false, this.resumePhase = t4, this.candidateSetMayUseGridFallback = n8, this.phase = "evaluate-candidate";
  }
  evaluateCurrentCandidate() {
    const e54 = this.candidates[this.candidateCursor];
    if (!e54)
      return void this.finishCandidateSet(false);
    if (!this.baseCandidateValidated) {
      if (!this.candidateCollides(e54, 0))
        return this.candidateShoveCount > 0 ? void this.applyCandidate(e54, 0) : (this.baseCandidateValidated = true, void (this.clearanceTierCursor = 0));
      return this.getPushableTraceIndices(e54, 0) && this.candidateShoveCount < 2 && this.attemptedClearanceShoveCount < 48 ? void this.startClearanceShove(e54, 0) : void this.advanceCandidate();
    }
    const t4 = this.clearancePaddingTiers[this.clearanceTierCursor];
    if (t4 === undefined || t4 <= L7)
      return void this.applyCandidate(e54, 0);
    if (this.attemptedCandidateCount++, !this.candidateCollides(e54, t4))
      return void this.applyCandidate(e54, t4);
    this.getPushableTraceIndices(e54, t4) && this.candidateShoveCount < 2 && this.attemptedClearanceShoveCount < 48 ? this.startClearanceShove(e54, t4) : (this.rollbackCandidateShoves(), this.clearanceTierCursor++, this.candidateShoveCount = 0);
  }
  advanceCandidate() {
    this.rollbackCandidateShoves(), this.candidateCursor++, this.clearanceTierCursor = 0, this.candidateShoveCount = 0, this.baseCandidateValidated = false;
  }
  candidateCollides(e54, t4) {
    const n8 = this.traces[e54.traceIndex], o10 = this.getTraceConnectionNames(n8);
    for (let i8 = 0;i8 < e54.points.length - 1; i8++) {
      const r9 = this.getCandidateSegmentWidth(e54, i8);
      if (this.obstacleIndex.collides({ start: e54.points[i8], end: e54.points[i8 + 1], layer: e54.layer, width: r9 + 2 * t4, connectionNames: o10, ignoreTraceIndex: e54.traceIndex, ignoreRouteRange: { start: Math.max(0, e54.startIndex - 1), end: Math.min(n8.route.length - 1, e54.endIndex + 1) }, obstacleClearance: e54.padClearance }))
        return true;
    }
    return false;
  }
  getPushableTraceIndices(e54, t4) {
    const n8 = this.traces[e54.traceIndex], o10 = this.getTraceConnectionNames(n8), i8 = new Set;
    for (let r9 = 0;r9 < e54.points.length - 1; r9++) {
      const s7 = this.getCandidateSegmentWidth(e54, r9), a9 = { start: e54.points[r9], end: e54.points[r9 + 1], layer: e54.layer, width: s7 + 2 * t4, connectionNames: o10, ignoreTraceIndex: e54.traceIndex, ignoreRouteRange: { start: Math.max(0, e54.startIndex - 1), end: Math.min(n8.route.length - 1, e54.endIndex + 1) }, obstacleClearance: e54.padClearance };
      if (!this.obstacleIndex.collides(a9))
        continue;
      const c5 = this.obstacleIndex.findCollisions(a9);
      if (c5.length === 0)
        return null;
      for (const t10 of c5) {
        if (t10.kind !== "trace" || t10.traceIndex === undefined || t10.traceIndex === e54.traceIndex || !this.mutableTraceIndexSet.has(t10.traceIndex))
          return null;
        const n10 = this.traces[t10.traceIndex];
        if (!n10 || this.resolveNominalTraceWidth(n10) >= e54.width - L7)
          return null;
        i8.add(t10.traceIndex);
      }
    }
    return i8.size > 0 && i8.size <= 2 ? [...i8] : null;
  }
  startClearanceShove(e54, t4) {
    this.rollbackTraces ??= structuredClone(this.traces), this.activeShovePadding = t4;
    const n8 = e54.width + 2 * t4, o10 = e54.points.slice(0, -1).map((n10, o11) => ({ start: n10, end: e54.points[o11 + 1], layer: e54.layer, width: this.getCandidateSegmentWidth(e54, o11) + 2 * t4 }));
    this.attemptedClearanceShoveCount++, this.activeSubSolver = new wee({ simpleRouteJson: this.inputProblem.simpleRouteJson, traces: this.traces, powerTraceIndex: e54.traceIndex, nominalPowerWidth: n8, pushOnlyNominalWidthsBelow: e54.width, mutableTraceIndices: this.mutableTraceIndices, corridor: o10, maxRerouteLength: this.maxRerouteLength }, this.connectionNameResolver), this.phase = "shove-clearance";
  }
  getCandidateSegmentWidth(e54, t4) {
    const n8 = this.traces[e54.traceIndex], o10 = n8.route[e54.startIndex], i8 = n8.route[e54.endIndex], r9 = t4 === 0 && ate(o10) ? o10.width : e54.width, s7 = t4 === e54.points.length - 2 && ate(i8) ? i8.width : e54.width;
    return Math.max(r9, s7);
  }
  stepActiveShoveSolver() {
    const e54 = this.activeSubSolver;
    if (e54.step(), e54.solved || e54.failed)
      if (this.pendingPushedViaRepair && e54 instanceof wee)
        this.finishPushedViaRepairSolver(e54);
      else if (e54 instanceof yee)
        this.finishViaGridSolver(e54);
      else {
        if (this.activeSubSolver = null, this.phase = "evaluate-candidate", e54.solved) {
          const t4 = e54.getOutput();
          if (t4)
            return this.traces = t4.traces, this.candidateShoveCount++, void this.rebuildObstacleIndex();
        }
        this.failedSubSolvers ??= [], this.failedSubSolvers.push(e54), this.rollbackCandidateShoves(), this.activeShovePadding <= L7 ? this.advanceCandidate() : this.clearanceTierCursor++, this.candidateShoveCount = 0;
      }
  }
  rollbackCandidateShoves() {
    this.rollbackTraces && (this.traces = this.rollbackTraces, this.rollbackTraces = null, this.rebuildObstacleIndex());
  }
  applyCandidate(e54, t4) {
    const n8 = this.traces[e54.traceIndex], o10 = n8.route[e54.startIndex], i8 = n8.route[e54.endIndex], r9 = e54.points.map((t10, n10) => ({ ...n10 === 0 ? o10 : n10 === e54.points.length - 1 ? i8 : { route_type: "wire", layer: e54.layer, width: e54.width }, x: t10.x, y: t10.y, layer: e54.layer, width: n10 === 0 ? o10.width : n10 === e54.points.length - 1 ? i8.width : e54.width })), s7 = n8.route.slice(e54.startIndex, e54.endIndex + 1), a9 = e54.originalQuality.nonOctilinearSegmentCount;
    if (n8.route.splice(e54.startIndex, e54.endIndex - e54.startIndex + 1, ...r9), e54.kind === "via-pair") {
      const t10 = s7.filter((e60) => e60.route_type === "via").length;
      this.viaPairCountRemoved++, this.viaCountRemoved += t10, this.routeCursor = Math.max(0, e54.startIndex - 1);
    } else
      e54.kind === "pad-clearance" ? (this.padClearanceRerouteCount++, this.routeCursor = e54.startIndex + Math.max(1, r9.length - 1)) : (this.simplifiedPathCount++, this.normalizedSegmentCount += a9, this.routeCursor = e54.startIndex + Math.max(1, r9.length - 1));
    this.committedClearanceShoveCount += this.candidateShoveCount, t4 > L7 && this.achievedExtraClearanceCount++, this.rollbackTraces = null, this.candidateShoveCount = 0, this.rebuildObstacleIndex(), this.finishCandidateSet(true);
  }
  finishCandidateSet(e54) {
    const t4 = this.candidates[0], n8 = hte(this.candidates.filter((e60) => e60.kind === t4?.kind).map((e60) => e60.width)), o10 = hte(this.candidates.filter((e60) => e60.kind === t4?.kind && e60.traceIndex === t4.traceIndex && e60.startIndex === t4.startIndex && e60.endIndex === t4.endIndex).map((e60) => e60.padClearance));
    if (this.rollbackCandidateShoves(), this.candidates = [], this.candidateCursor = 0, this.clearanceTierCursor = 0, this.candidateShoveCount = 0, this.baseCandidateValidated = false, !e54 && this.candidateSetMayUseGridFallback && t4)
      return this.candidateSetMayUseGridFallback = false, void this.beginViaGridAttempt(t4, n8, o10);
    this.candidateSetMayUseGridFallback = false, e54 || this.routeCursor++, this.phase = this.resumePhase;
  }
  beginViaGridAttempt(e54, t4, n8 = [e54.padClearance]) {
    this.viaGridAttempt = { kind: e54.kind, traceIndex: e54.traceIndex, startIndex: e54.startIndex, endIndex: e54.endIndex, layer: e54.layer, padClearances: n8, padClearanceCursor: 0, originalQuality: e54.originalQuality, widths: t4, widthCursor: 0, gridSizes: [], gridSizeCursor: 0, offsetCursor: 0 }, this.phase = "route-via-pair";
  }
  startNextViaGridCandidate() {
    const e54 = this.viaGridAttempt;
    if (!e54)
      return void (this.phase = this.resumePhase);
    if (e54.padClearanceCursor >= e54.padClearances.length)
      return e54.kind === "pad-clearance" && this.unresolvedPadClearanceCount++, this.viaGridAttempt = null, this.routeCursor++, void (this.phase = this.resumePhase);
    if (e54.widthCursor >= e54.widths.length)
      return e54.padClearanceCursor++, e54.widthCursor = 0, e54.gridSizes = [], e54.gridSizeCursor = 0, void (e54.offsetCursor = 0);
    const t4 = e54.widths[e54.widthCursor], n8 = e54.padClearances[e54.padClearanceCursor];
    if (e54.gridSizes.length === 0 && (e54.gridSizes = hte([j7(t4 / 2, 0.2, 0.4), j7(t4 / 3, 0.15, 0.25)])), e54.gridSizeCursor >= e54.gridSizes.length)
      return e54.widthCursor++, e54.gridSizes = [], e54.gridSizeCursor = 0, void (e54.offsetCursor = 0);
    if (e54.offsetCursor >= rte.length)
      return e54.gridSizeCursor++, void (e54.offsetCursor = 0);
    const o10 = this.traces[e54.traceIndex], i8 = o10.route[e54.startIndex], r9 = o10.route[e54.endIndex];
    if (!ate(i8) || !ate(r9))
      return this.viaGridAttempt = null, this.routeCursor++, void (this.phase = this.resumePhase);
    const s7 = e54.gridSizes[e54.gridSizeCursor], a9 = rte[e54.offsetCursor];
    this.attemptedViaGridCount++, this.activeSubSolver = new yee({ start: i8, end: r9, layer: e54.layer, traceWidth: t4, gridSize: s7, gridOffset: { x: a9.x * s7, y: a9.y * s7 }, connectionNames: this.getTraceConnectionNames(o10), obstacleIndex: this.obstacleIndex, ignoreTraceIndex: e54.traceIndex, ignoreRouteRange: { start: Math.max(0, e54.startIndex - 1), end: Math.min(o10.route.length - 1, e54.endIndex + 1) }, bounds: this.inputProblem.simpleRouteJson.bounds, obstacleClearance: n8, searchPadding: Math.min(4, Math.max(2, z7(i8, r9) / 2, 3 * t4)), requireOctilinear: true });
  }
  finishViaGridSolver(e54) {
    const t4 = this.viaGridAttempt;
    if (this.activeSubSolver = null, e54.solved && t4) {
      const n8 = e54.getOutput(), o10 = this.traces[t4.traceIndex];
      if (n8 && o10) {
        const e60 = this.resolveNominalTraceWidth(o10), i8 = this.measureCandidate(n8.points, n8.traceWidth, e60, o10.route[t4.endIndex].width, o10.route[t4.startIndex].width);
        if (i8.nonOctilinearSegmentCount === 0 && i8.length <= this.maxRerouteLength + L7 && i8.deficitArea <= t4.originalQuality.deficitArea + L7 && i8.conservativeDeficitArea <= t4.originalQuality.conservativeDeficitArea + L7 && this.preservesCoverage(i8, t4.originalQuality)) {
          const e61 = { kind: t4.kind, traceIndex: t4.traceIndex, startIndex: t4.startIndex, endIndex: t4.endIndex, layer: t4.layer, points: n8.points, width: n8.traceWidth, padClearance: t4.padClearances[t4.padClearanceCursor], originalQuality: t4.originalQuality };
          return this.viaGridAttempt = null, void this.beginCandidates([e61], this.resumePhase, false);
        }
      }
    }
    e54.failed && (this.failedSubSolvers ??= [], this.failedSubSolvers.push(e54)), t4 && t4.offsetCursor++, this.phase = "route-via-pair";
  }
  measureRouteRange(e54, t4, n8) {
    const o10 = this.resolveNominalTraceWidth(e54);
    let i8 = 0, r9 = 0, s7 = 0, a9 = 0, c5 = 0, l5 = 0, h5 = 0;
    for (let d9 = t4;d9 <= n8; d9++) {
      if (ate(e54.route[d9]) && h5++, d9 >= n8)
        continue;
      const t10 = e54.route[d9], u9 = e54.route[d9 + 1];
      if (!ate(t10) || !ate(u9) || t10.layer !== u9.layer)
        continue;
      const p9 = z7(t10, u9);
      i8 += p9, r9 += p9 * Math.max(0, o10 - t10.width), t10.width >= o10 - L7 && (a9 += p9), s7 += p9 * Math.max(0, o10 - Math.min(t10.width, u9.width)), Math.min(t10.width, u9.width) >= o10 - L7 && (c5 += p9), l5 += uee([t10, u9]);
    }
    return { length: i8, deficitArea: r9, conservativeDeficitArea: s7, nominalLength: a9, conservativeNominalLength: c5, nonOctilinearSegmentCount: l5, pointCount: h5 };
  }
  measureTraceLength(e54) {
    let t4 = 0;
    for (let n8 = 0;n8 < e54.route.length - 1; n8++) {
      const o10 = e54.route[n8], i8 = e54.route[n8 + 1];
      ate(o10) && ate(i8) && o10.layer === i8.layer && (t4 += z7(o10, i8));
    }
    return t4;
  }
  measureCandidate(e54, t4, n8, o10 = t4, i8 = t4) {
    const r9 = pee(e54);
    let s7 = 0, a9 = 0, c5 = 0, l5 = 0;
    for (let r10 = 0;r10 < e54.length - 1; r10++) {
      const h5 = z7(e54[r10], e54[r10 + 1]), d9 = r10 === 0 ? i8 : t4, u9 = r10 === e54.length - 2 ? o10 : t4, p9 = Math.min(d9, u9);
      s7 += h5 * Math.max(0, n8 - d9), a9 += h5 * Math.max(0, n8 - p9), d9 >= n8 - L7 && (c5 += h5), p9 >= n8 - L7 && (l5 += h5);
    }
    return { length: r9, deficitArea: s7, conservativeDeficitArea: a9, nominalLength: c5, conservativeNominalLength: l5, nonOctilinearSegmentCount: uee(e54), pointCount: e54.length };
  }
  preservesCoverage(e54, t4) {
    const n8 = t4.length <= L7 ? 1 : t4.nominalLength / t4.length, o10 = e54.length <= L7 ? 1 : e54.nominalLength / e54.length, i8 = t4.length <= L7 ? 1 : t4.conservativeNominalLength / t4.length, r9 = e54.length <= L7 ? 1 : e54.conservativeNominalLength / e54.length;
    return !(o10 + L7 < n8 || r9 + L7 < i8) && !(e54.length > t4.length + L7 && o10 < 0.999999);
  }
  advanceTrace() {
    this.traceCursor++, this.routeCursor = 0, this.rebuildObstacleIndex();
  }
  createObstacleIndex() {
    return new Cee(this.inputProblem.simpleRouteJson, this.traces, this.phase === "repair-vias" ? undefined : this.traceIndices?.[this.traceCursor], [], this.connectionNameResolver);
  }
  rebuildObstacleIndex() {
    this.obstacleIndex = this.createObstacleIndex();
  }
  resolveNominalTraceWidth(e54) {
    const t4 = this.findConnectionForTrace(e54);
    return Math.max(t4?.nominalTraceWidth ?? t4?.width ?? this.inputProblem.simpleRouteJson.nominalTraceWidth ?? this.inputProblem.simpleRouteJson.minTraceWidth, this.inputProblem.simpleRouteJson.minTraceWidth);
  }
  getPadClearanceForTrace(e54) {
    const t4 = this.getBaseObstacleClearance();
    return this.resolveNominalTraceWidth(e54) >= 0.499999 ? Math.max(t4, this.desiredPadClearance ?? this.resolveNominalTraceWidth(e54) / 2) : t4;
  }
  getBaseObstacleClearance() {
    return Math.max(this.inputProblem.simpleRouteJson.defaultObstacleMargin ?? 0, this.inputProblem.simpleRouteJson.minTraceToPadEdgeClearance ?? 0, 0.1);
  }
  getCandidatePadClearance(e54, t4, n8, o10) {
    const i8 = this.traces[t4], r9 = this.getBaseObstacleClearance(), s7 = this.getPadClearanceForTrace(i8);
    if (e54 === "pad-clearance")
      return s7;
    const a9 = e54 === "via-pair" ? Math.min(s7, Math.max(r9, 0.15)) : s7;
    return this.findExistingPadClearance(t4, n8, o10, r9, a9);
  }
  getImprovedPadClearanceTiers(e54, t4, n8) {
    const o10 = this.traces[e54], i8 = this.getBaseObstacleClearance(), r9 = this.getPadClearanceForTrace(o10), s7 = this.findExistingPadClearance(e54, t4, n8, i8, r9), a9 = Math.max(0.025, Math.min(0.05, r9 / 10)), c5 = [r9];
    for (let e60 = r9 - a9;e60 > s7 + a9 / 2; e60 -= a9)
      c5.push(e60);
    return hte(c5).filter((e60) => e60 > s7 + L7);
  }
  findExistingPadClearance(e54, t4, n8, o10, i8) {
    if (this.routeRangeHasPadClearanceViolation(e54, t4, n8, o10))
      return o10;
    if (!this.routeRangeHasPadClearanceViolation(e54, t4, n8, i8))
      return i8;
    let r9 = o10, s7 = i8;
    for (let o11 = 0;o11 < 7; o11++) {
      const o12 = (r9 + s7) / 2;
      this.routeRangeHasPadClearanceViolation(e54, t4, n8, o12) ? s7 = o12 : r9 = o12;
    }
    return Math.max(o10, Number((r9 - 0.001).toFixed(6)));
  }
  routeRangeHasPadClearanceViolation(e54, t4, n8, o10) {
    const i8 = this.traces[e54], r9 = this.getTraceConnectionNames(i8);
    for (let s7 = t4;s7 < n8; s7++) {
      const a9 = i8.route[s7], c5 = i8.route[s7 + 1];
      if (!ate(a9) || !ate(c5) || a9.layer !== c5.layer)
        continue;
      if (this.obstacleIndex.findCollisions({ start: a9, end: c5, layer: a9.layer, width: Math.max(a9.width, c5.width), connectionNames: r9, ignoreTraceIndex: e54, ignoreRouteRange: { start: Math.max(0, t4 - 1), end: Math.min(i8.route.length - 1, n8 + 1) }, obstacleClearance: o10 }).some((e60) => e60.kind === "obstacle" && e60.obstacleKind === "pad"))
        return true;
    }
    return false;
  }
  countPadClearanceViolations(e54) {
    let t4 = 0;
    for (const n8 of this.traceIndices) {
      const o10 = this.traces[n8];
      if (!o10)
        continue;
      const i8 = this.getTraceConnectionNames(o10);
      for (let r9 = 0;r9 < o10.route.length - 1; r9++) {
        const s7 = o10.route[r9], a9 = o10.route[r9 + 1];
        if (!ate(s7) || !ate(a9) || s7.layer !== a9.layer)
          continue;
        this.obstacleIndex.findCollisions({ start: s7, end: a9, layer: s7.layer, width: Math.max(s7.width, a9.width), connectionNames: i8, ignoreTraceIndex: n8, ignoreRouteRange: { start: Math.max(0, r9 - 1), end: Math.min(o10.route.length - 1, r9 + 2) }, obstacleClearance: e54 ?? this.getPadClearanceForTrace(o10) }).some((e60) => e60.kind === "obstacle" && e60.obstacleKind === "pad") && t4++;
      }
    }
    return t4;
  }
  countPadClearanceViolationsByTier() {
    return Object.fromEntries(ste.map((e54) => [e54.toFixed(2), this.countPadClearanceViolations(e54)]));
  }
  findConnectionForTrace(e54) {
    const t4 = this.connectionByTraceId.get(e54.pcb_trace_id);
    if (t4 !== undefined)
      return t4 ?? undefined;
    const n8 = new Set(this.connectionNameResolver.canonicalize(this.getTraceConnectionNames(e54))), o10 = this.inputProblem.simpleRouteJson.connections.find((e60) => this.connectionNameResolver.canonicalize(this.getConnectionNames(e60)).some((e61) => n8.has(e61))) ?? null;
    return this.connectionByTraceId.set(e54.pcb_trace_id, o10), o10 ?? undefined;
  }
  getConnectionNames(e54) {
    return [e54.name, e54.source_trace_id, e54.rootConnectionName, e54.netConnectionName, ...e54.mergedConnectionNames ?? []].filter((e60) => Boolean(e60));
  }
  getTraceConnectionNames(e54) {
    return [e54.pcb_trace_id, e54.connection_name, e54.source_trace_id, e54.rootConnectionName, ...e54.mergedConnectionNames ?? [], ...e54.connectsTo ?? []].filter((e60) => Boolean(e60));
  }
  ensureConnectivitySafeOutput() {
    if (!this.connectivityFinalized) {
      this.connectivityFinalized = true, this.connectivityValidationCount++;
      try {
        const e54 = this.connectivityInvariant.validate(this.traces);
        if (this.connectivityValidationError ??= e54.validationError ?? null, e54.safe)
          return void (this.finalizedMutatedTraceIndices = this.getMutatedTraceIndices());
        this.connectivityRegressionEndpointIds = [...new Set(e54.regressions.flatMap((e60) => e60.baselineEndpointLabels))];
      } catch (e54) {
        this.connectivityValidationError = e54 instanceof Error ? e54.message : String(e54);
      }
      this.connectivityRollbackCount++, this.connectivityRollbackMutationStats = { committedClearanceShoveCount: this.committedClearanceShoveCount, viaPairCountRemoved: this.viaPairCountRemoved, viaCountRemoved: this.viaCountRemoved, simplifiedPathCount: this.simplifiedPathCount, normalizedSegmentCount: this.normalizedSegmentCount, achievedExtraClearanceCount: this.achievedExtraClearanceCount, relocatedViaCount: this.relocatedViaCount, committedPushedViaRepairCount: this.committedPushedViaRepairCount, padClearanceRerouteCount: this.padClearanceRerouteCount }, this.committedClearanceShoveCount = 0, this.viaPairCountRemoved = 0, this.viaCountRemoved = 0, this.simplifiedPathCount = 0, this.normalizedSegmentCount = 0, this.achievedExtraClearanceCount = 0, this.relocatedViaCount = 0, this.committedPushedViaRepairCount = 0, this.padClearanceRerouteCount = 0, this.traces = structuredClone(this.initialConnectivitySafeTraces), this.obstacleIndex = new Cee(this.inputProblem.simpleRouteJson, this.traces, undefined, [], this.connectionNameResolver), this.remainingPadClearanceViolationCount = this.countPadClearanceViolations(), this.remainingPadClearanceViolationCountByClearance = this.countPadClearanceViolationsByTier(), this.finalizedMutatedTraceIndices = this.getMutatedTraceIndices();
    }
  }
  getMutatedTraceIndices() {
    const e54 = Math.max(this.initialConnectivitySafeTraces.length, this.traces.length);
    return Array.from({ length: e54 }, (e60, t4) => t4).filter((e60) => JSON.stringify(this.initialConnectivitySafeTraces[e60]) !== JSON.stringify(this.traces[e60]));
  }
  createStats() {
    const e54 = this.candidates[this.candidateCursor], t4 = this.phase === "repair-vias" ? this.viaRepairTraceIndices : this.traceIndices;
    return { phase: this.phase, budgetLimited: this.budgetLimited, completionReason: this.phase === "complete" || this.solved ? this.connectivityRollbackCount > 0 ? "connectivity_rollback" : this.budgetLimited ? "iteration_budget" : this.connectivityValidationError ? "connectivity_validation_unavailable" : "completed" : null, resultStatus: this.connectivityRollbackCount > 0 || this.budgetLimited || this.connectivityValidationError !== null ? "best_effort" : "complete", traceCursor: this.traceCursor, traceCount: t4.length, traceIndex: t4[this.traceCursor], routeCursor: this.routeCursor, candidateCursor: this.candidateCursor, candidateCount: this.candidates.length, candidateKind: e54?.kind, candidateWidth: e54?.width, candidatePointCount: e54?.points.length, clearancePadding: this.clearancePaddingTiers[this.clearanceTierCursor], candidateShoveCount: this.candidateShoveCount, attemptedCandidateCount: this.attemptedCandidateCount, attemptedClearanceShoveCount: this.attemptedClearanceShoveCount, attemptedViaGridCount: this.attemptedViaGridCount, committedClearanceShoveCount: this.committedClearanceShoveCount, viaPairCountRemoved: this.viaPairCountRemoved, viaCountRemoved: this.viaCountRemoved, simplifiedPathCount: this.simplifiedPathCount, normalizedSegmentCount: this.normalizedSegmentCount, achievedExtraClearanceCount: this.achievedExtraClearanceCount, relocatedViaCount: this.relocatedViaCount, unresolvedViaCount: this.unresolvedViaCount, attemptedPushedViaRepairCount: this.attemptedPushedViaRepairCount, committedPushedViaRepairCount: this.committedPushedViaRepairCount, padClearanceRerouteCount: this.padClearanceRerouteCount, unresolvedPadClearanceCount: this.unresolvedPadClearanceCount, initialPadClearanceViolationCount: this.initialPadClearanceViolationCount, remainingPadClearanceViolationCount: this.remainingPadClearanceViolationCount, initialPadClearanceViolationCountByClearance: { ...this.initialPadClearanceViolationCountByClearance }, remainingPadClearanceViolationCountByClearance: { ...this.remainingPadClearanceViolationCountByClearance }, connectivityValidationCount: this.connectivityValidationCount, connectivityRollbackCount: this.connectivityRollbackCount, connectivityRegressionEndpointIds: [...this.connectivityRegressionEndpointIds], connectivityValidationError: this.connectivityValidationError, connectivityRollbackMutationStats: this.connectivityRollbackMutationStats === null ? null : { ...this.connectivityRollbackMutationStats }, mutatedTraceIndices: [...this.finalizedMutatedTraceIndices], spatialIndexRectCount: this.obstacleIndex.items.length };
  }
  computeProgress() {
    if (this.solved || this.phase === "complete")
      return 1;
    const e54 = this.phase === "repair-vias" ? this.viaRepairTraceIndices : this.traceIndices;
    if (e54.length === 0)
      return 1;
    const t4 = this.resumePhase === "scan-via-pairs" ? 0 : 0.5;
    return Math.min(0.99, t4 + this.traceCursor / e54.length * 0.5);
  }
  getConstructorParams() {
    return [this.inputProblem];
  }
  tryFinalAcceptance() {
    const e54 = this.pushedViaRepairRollbackTraces ?? this.rollbackTraces;
    e54 && (this.traces = e54), this.activeSubSolver = null, this.rollbackTraces = null, this.pushedViaRepairRollbackTraces = null, this.pendingPushedViaRepair = null, this.alternatePushedViaRepairs = [], this.viaGridAttempt = null, this.candidates = [], this.candidateCursor = 0, this.clearanceTierCursor = 0, this.candidateShoveCount = 0, this.baseCandidateValidated = false, this.candidateSetMayUseGridFallback = false, this.ensureConnectivitySafeOutput(), this.obstacleIndex = new Cee(this.inputProblem.simpleRouteJson, this.traces, undefined, [], this.connectionNameResolver), this.remainingPadClearanceViolationCount = this.countPadClearanceViolations(), this.remainingPadClearanceViolationCountByClearance = this.countPadClearanceViolationsByTier(), this.budgetLimited = true, this.phase = "complete", this.solved = true, this.progress = 1, this.stats = this.createStats();
  }
  getOutput() {
    return structuredClone(this.solved ? this.traces : this.initialConnectivitySafeTraces);
  }
  visualize() {
    const e54 = [], t4 = [], n8 = this.candidates[this.candidateCursor];
    for (let n10 = 0;n10 < this.traces.length; n10++) {
      const o10 = this.traces[n10];
      for (const e60 of o10.route)
        e60.route_type === "via" && t4.push({ center: e60, radius: (e60.via_diameter ?? 0.6) / 2, fill: "#d4a017", stroke: "#7a5700" });
      for (let t10 = 0;t10 < o10.route.length - 1; t10++) {
        const n11 = o10.route[t10], i8 = o10.route[t10 + 1];
        ate(n11) && ate(i8) && n11.layer === i8.layer && e54.push({ points: [n11, i8], strokeColor: n11.layer === "bottom" ? "#376fc4" : "#777", strokeWidth: n11.width });
      }
    }
    if (n8)
      for (let t10 = 0;t10 < n8.points.length - 1; t10++)
        e54.push({ points: [n8.points[t10], n8.points[t10 + 1]], strokeColor: "#ff7400", strokeWidth: n8.width + 2 * (this.clearancePaddingTiers[this.clearanceTierCursor] ?? 0) });
    return { coordinateSystem: "cartesian", title: `Power trace cleanup: ${this.phase}`, lines: e54, points: [], circles: t4, rects: [], texts: [] };
  }
};
var pte = (e54) => e54?.route_type === "wire";
var mte = class extends BaseSolver {
  inputProblem;
  traces;
  obstacleIndex;
  traceCursor = 0;
  routeCursor = 0;
  repairedSegmentCount = 0;
  repairedPadNeckSegmentCount = 0;
  unresolvedSegmentCount = 0;
  totalWidthReduction = 0;
  budgetLimited = false;
  connectivityValidationCount = 0;
  connectivityRollbackCount = 0;
  connectivityRegressionEndpointIds = [];
  connectivityValidationError = null;
  connectivityRollbackMutationStats = null;
  connectionNameResolver;
  nominalWidthByTraceId = new Map;
  connectivityInvariant;
  initialConnectivitySafeTraces;
  minimumTraceWidth;
  traceIndices;
  connectivityFinalized = false;
  constructor(e54) {
    super(), this.inputProblem = structuredClone(e54), this.traces = structuredClone(e54.traces), this.initialConnectivitySafeTraces = structuredClone(e54.traces), this.connectivityInvariant = new ote(this.inputProblem.simpleRouteJson, this.initialConnectivitySafeTraces), this.connectionNameResolver = new D7(e54.simpleRouteJson, this.traces), this.minimumTraceWidth = e54.simpleRouteJson.minTraceWidth;
    const t4 = e54.traceIndices ? [...new Set(e54.traceIndices)] : this.traces.map((e60, t10) => t10);
    for (const e60 of t4)
      if (!Number.isInteger(e60) || e60 < 0 || e60 >= this.traces.length)
        throw new RangeError(`Invalid clearance-repair trace index: ${e60}`);
    this.traceIndices = t4, this.obstacleIndex = this.createConservativeObstacleIndex();
    const n8 = this.traceIndices.reduce((e60, t10) => e60 + Math.max(0, this.traces[t10].route.length - 1), 0);
    this.MAX_ITERATIONS = Math.max(10, 8 * n8 + 2 * this.traceIndices.length), this.stats = this.createStats();
  }
  getSolverName() {
    return "PowerTraceClearanceRepairSolver";
  }
  _step() {
    const e54 = this.traceIndices[this.traceCursor], t4 = e54 === undefined ? undefined : this.traces[e54];
    if (!t4)
      return this.ensureConnectivitySafeOutput(), this.solved = true, void (this.stats = this.createStats());
    if (this.routeCursor >= t4.route.length - 1)
      return this.traceCursor++, this.routeCursor = 0, void (this.stats = this.createStats());
    const n8 = this.routeCursor++, o10 = t4.route[n8], i8 = t4.route[n8 + 1];
    if (!pte(o10) || !pte(i8) || o10.layer !== i8.layer)
      return void (this.stats = this.createStats());
    const r9 = Math.max(o10.width, i8.width), s7 = { start: o10, end: i8, layer: o10.layer, width: r9, connectionNames: this.getTraceConnectionNames(t4), ignoreTraceIndex: e54, ignoreRouteRange: { start: n8, end: n8 + 1 } };
    if (this.repairConnectedPadNeck(t4, n8, s7))
      return void (this.stats = this.createStats());
    if (!this.segmentHasForeignTraceCollision(n8, r9))
      return void (this.stats = this.createStats());
    if (this.segmentHasForeignTraceCollision(n8, this.minimumTraceWidth))
      return this.unresolvedSegmentCount++, void (this.stats = this.createStats());
    let a9 = this.minimumTraceWidth, c5 = r9;
    for (let e60 = 0;e60 < 10; e60++) {
      const e61 = (a9 + c5) / 2;
      this.segmentHasForeignTraceCollision(n8, e61) ? c5 = e61 : a9 = e61;
    }
    const l5 = r9 >= 0.5 ? 0.025 : 0.0125, h5 = Math.max(this.minimumTraceWidth, Math.floor((a9 + L7) / l5) * l5), d9 = this.segmentHasForeignTraceCollision(n8, h5) ? a9 : h5, u9 = o10.width, p9 = i8.width;
    o10.width = Math.min(o10.width, d9), i8.width = Math.min(i8.width, d9);
    const m9 = u9 - o10.width + (p9 - i8.width);
    if (m9 <= L7)
      return this.unresolvedSegmentCount++, void (this.stats = this.createStats());
    this.repairedSegmentCount++, this.totalWidthReduction += m9, this.obstacleIndex = this.createConservativeObstacleIndex(), this.routeCursor = Math.max(0, n8 - 1), this.stats = this.createStats();
  }
  repairConnectedPadNeck(e54, t4, n8) {
    const o10 = e54.route[t4], i8 = e54.route[t4 + 1];
    if (!pte(o10) || !pte(i8))
      return false;
    let r9 = this.obstacleIndex.getConnectedPadWidthLimitAtPoint(n8, o10), s7 = this.obstacleIndex.getConnectedPadWidthLimitAtPoint(n8, i8);
    t4 === 0 && (r9 = this.getSmallerLimit(r9, this.obstacleIndex.getConnectedPadEndpointWidthLimitAtPoint(n8, o10))), t4 + 1 === e54.route.length - 1 && (s7 = this.getSmallerLimit(s7, this.obstacleIndex.getConnectedPadEndpointWidthLimitAtPoint(n8, i8)));
    const a9 = r9, c5 = s7;
    if ((a9 === null || o10.width <= a9 + L7) && (c5 === null || i8.width <= c5 + L7))
      return false;
    const l5 = o10.width, h5 = i8.width;
    if (a9 !== null && (o10.width = Math.min(o10.width, a9)), c5 !== null && (i8.width = Math.min(i8.width, c5)), a9 !== null && c5 === null)
      this.insertPadBoundaryTransition(e54, t4, n8, "start", o10.width, h5);
    else if (a9 === null && c5 !== null)
      this.insertPadBoundaryTransition(e54, t4, n8, "end", i8.width, l5);
    else if (a9 !== null && c5 !== null) {
      const r10 = this.obstacleIndex.getConnectedPadBoundaryPoint(n8, "start"), s9 = this.obstacleIndex.getConnectedPadBoundaryPoint(n8, "end");
      r10 && s9 && (this.insertPadBoundaryTransition(e54, t4, n8, "start", o10.width, h5), this.insertPadBoundaryTransition(e54, t4 + 2, n8, "end", i8.width, l5));
    }
    return this.totalWidthReduction += l5 - o10.width + (h5 - i8.width), this.repairedPadNeckSegmentCount++, this.obstacleIndex = this.createConservativeObstacleIndex(), this.routeCursor = Math.max(0, t4 - 1), true;
  }
  getSmallerLimit(e54, t4) {
    return e54 === null ? t4 : t4 === null ? e54 : Math.min(e54, t4);
  }
  insertPadBoundaryTransition(e54, t4, n8, o10, i8, r9) {
    const s7 = this.obstacleIndex.getConnectedPadBoundaryPoint(n8, o10);
    if (!s7)
      return;
    const a9 = o10 === "start" ? n8.start : n8.end, c5 = o10 === "start" ? n8.end : n8.start, l5 = Math.hypot(c5.x - a9.x, c5.y - a9.y);
    if (l5 <= 0.000000001)
      return;
    const h5 = Math.min(0.000001, l5 / 4), d9 = (c5.x - a9.x) / l5, u9 = (c5.y - a9.y) / l5, p9 = { route_type: "wire", x: s7.x - d9 * h5, y: s7.y - u9 * h5, width: i8, layer: n8.layer }, m9 = { ...p9, x: s7.x + d9 * h5, y: s7.y + u9 * h5, width: r9 }, g10 = o10 === "start" ? e54.route[t4 + 1] : e54.route[t4], f10 = o10 === "start" ? e54.route[t4 + 2] : e54.route[t4 - 1];
    if (pte(g10) && f10?.route_type === "via") {
      const t10 = this.resolveNominalTraceWidth(e54);
      this.obstacleIndex.collides({ ...n8, start: g10, end: m9, width: t10 }) || (g10.width = Math.max(g10.width, t10), m9.width = g10.width);
    }
    e54.route.splice(t4 + 1, 0, ...o10 === "start" ? [p9, m9] : [m9, p9]);
  }
  resolveNominalTraceWidth(e54) {
    const t4 = this.nominalWidthByTraceId.get(e54.pcb_trace_id);
    if (t4 !== undefined)
      return t4;
    const n8 = new Set(this.connectionNameResolver.canonicalize(this.getTraceConnectionNames(e54))), o10 = this.inputProblem.simpleRouteJson.connections.find((e60) => this.connectionNameResolver.canonicalize([e60.name, e60.source_trace_id, e60.rootConnectionName, e60.netConnectionName, ...e60.mergedConnectionNames ?? []].filter((e61) => Boolean(e61))).some((e61) => n8.has(e61))), i8 = Math.max(o10?.nominalTraceWidth ?? o10?.width ?? this.inputProblem.simpleRouteJson.nominalTraceWidth ?? this.minimumTraceWidth, this.minimumTraceWidth);
    return this.nominalWidthByTraceId.set(e54.pcb_trace_id, i8), i8;
  }
  segmentHasForeignTraceCollision(e54, t4) {
    const n8 = this.traceIndices[this.traceCursor], o10 = n8 === undefined ? undefined : this.traces[n8], i8 = o10?.route[e54], r9 = o10?.route[e54 + 1];
    return !!(o10 && pte(i8) && pte(r9) && i8.layer === r9.layer) && this.obstacleIndex.findCollisions({ start: i8, end: r9, layer: i8.layer, width: t4, connectionNames: this.getTraceConnectionNames(o10), ignoreTraceIndex: n8, ignoreRouteRange: { start: e54, end: e54 + 1 } }).some((e60) => e60.kind === "trace" && e60.traceIndex !== undefined && e60.traceIndex !== n8);
  }
  createConservativeObstacleIndex() {
    const e54 = structuredClone(this.traces);
    for (const t4 of e54)
      for (let e60 = 0;e60 < t4.route.length - 1; e60++) {
        const n8 = t4.route[e60], o10 = t4.route[e60 + 1];
        pte(n8) && pte(o10) && n8.layer === o10.layer && (n8.width = Math.max(n8.width, o10.width));
      }
    return new Cee(this.inputProblem.simpleRouteJson, e54, undefined, [], this.connectionNameResolver);
  }
  getTraceConnectionNames(e54) {
    return [e54.pcb_trace_id, e54.connection_name, e54.source_trace_id, e54.rootConnectionName, ...e54.mergedConnectionNames ?? [], ...e54.connectsTo ?? []].filter((e60) => Boolean(e60));
  }
  ensureConnectivitySafeOutput() {
    if (!this.connectivityFinalized) {
      this.connectivityFinalized = true, this.connectivityValidationCount++;
      try {
        const e54 = this.connectivityInvariant.validate(this.traces);
        if (this.connectivityValidationError ??= e54.validationError ?? null, e54.safe)
          return;
        this.connectivityRegressionEndpointIds = [...new Set(e54.regressions.flatMap((e60) => e60.baselineEndpointLabels))];
      } catch (e54) {
        this.connectivityValidationError = e54 instanceof Error ? e54.message : String(e54);
      }
      this.connectivityRollbackCount++, this.connectivityRollbackMutationStats = { repairedSegmentCount: this.repairedSegmentCount, repairedPadNeckSegmentCount: this.repairedPadNeckSegmentCount, totalWidthReduction: this.totalWidthReduction }, this.repairedSegmentCount = 0, this.repairedPadNeckSegmentCount = 0, this.totalWidthReduction = 0, this.traces = structuredClone(this.initialConnectivitySafeTraces), this.obstacleIndex = this.createConservativeObstacleIndex();
    }
  }
  createStats() {
    return { phase: this.solved ? "complete" : "repair-trace-clearance", budgetLimited: this.budgetLimited, completionReason: this.solved ? this.connectivityRollbackCount > 0 ? "connectivity_rollback" : this.budgetLimited ? "iteration_budget" : this.connectivityValidationError ? "connectivity_validation_unavailable" : "completed" : null, resultStatus: this.connectivityRollbackCount > 0 || this.budgetLimited || this.connectivityValidationError !== null ? "best_effort" : "complete", traceCursor: this.traceCursor, traceCount: this.traceIndices.length, traceIndex: this.traceIndices[this.traceCursor], routeCursor: this.routeCursor, repairedSegmentCount: this.repairedSegmentCount, repairedPadNeckSegmentCount: this.repairedPadNeckSegmentCount, unresolvedSegmentCount: this.unresolvedSegmentCount, totalWidthReduction: this.totalWidthReduction, connectivityValidationCount: this.connectivityValidationCount, connectivityRollbackCount: this.connectivityRollbackCount, connectivityRegressionEndpointIds: [...this.connectivityRegressionEndpointIds], connectivityValidationError: this.connectivityValidationError, connectivityRollbackMutationStats: this.connectivityRollbackMutationStats === null ? null : { ...this.connectivityRollbackMutationStats }, spatialIndexRectCount: this.obstacleIndex.items.length };
  }
  computeProgress() {
    return this.solved || this.traceIndices.length === 0 ? 1 : Math.min(0.99, this.traceCursor / this.traceIndices.length);
  }
  tryFinalAcceptance() {
    this.ensureConnectivitySafeOutput(), this.budgetLimited = true, this.solved = true, this.progress = 1, this.stats = this.createStats();
  }
  getConstructorParams() {
    return [this.inputProblem];
  }
  getOutput() {
    return structuredClone(this.solved ? this.traces : this.initialConnectivitySafeTraces);
  }
  visualize() {
    const e54 = [];
    for (let t4 = 0;t4 < this.traces.length; t4++) {
      const n8 = this.traces[t4];
      for (let o10 = 0;o10 < n8.route.length - 1; o10++) {
        const i8 = n8.route[o10], r9 = n8.route[o10 + 1];
        pte(i8) && pte(r9) && i8.layer === r9.layer && e54.push({ points: [i8, r9], strokeColor: t4 === this.traceIndices[this.traceCursor] && o10 === this.routeCursor ? "#ff7400" : i8.layer === "bottom" ? "#376fc4" : "#777", strokeWidth: Math.max(i8.width, r9.width) });
      }
    }
    return { coordinateSystem: "cartesian", title: "Power trace direction-independent clearance repair", lines: e54, points: [], circles: [], rects: [], texts: [] };
  }
};
var gte = [{ x: 0, y: 0 }, { x: 0.5, y: 0 }, { x: 0, y: 0.5 }, { x: 0.5, y: 0.5 }];
var fte = [{ offset: { x: 0, y: 0 }, strictNecking: true }, { offset: { x: 0.5, y: 0.5 }, strictNecking: true }, { offset: { x: 0, y: 0 }, strictNecking: false }, { offset: { x: 0.5, y: 0.5 }, strictNecking: false }];
var _te = 64;
var yte = (e54) => [...new Set(e54.map((e60) => Number(e60.toFixed(6))))].sort((e60, t4) => t4 - e60);
var bte = (e54) => e54?.route_type === "wire";
var xte = class extends BaseSolver {
  inputProblem;
  options;
  operationIndex = 0;
  traces;
  obstacleIndex;
  connectionNameResolver;
  connectionByTraceId = new Map;
  connectivityInvariant;
  lastConnectivitySafeTraces;
  traceOrder;
  selectedOwnedTraceIndices;
  selectedCleanupTraceIndices;
  selectedViaRepairTraceIndices;
  mutableBlockerTraceIndices;
  immutableTraceIndices;
  initialImmutableTraceSignatures = new Map;
  traceOrderCursor = -1;
  maxPassCount = 4;
  previousWidthDeficit = 0;
  passIndex = 0;
  completedPassCount = 0;
  lastNormalizedWidthDeficitGain = 0;
  normalizedWidthDeficitGainByPass = [];
  plateauReached = false;
  phase = "scan-trace";
  traceIndex = -1;
  routeSegmentIndex = 0;
  nominalTraceWidth = 0;
  currentIntervals = [];
  intervalCursor = 0;
  candidateWidths = [];
  widthCursor = 0;
  gridResolutions = [];
  resolutionCursor = 0;
  offsetCursor = 0;
  keptTraceCount = 0;
  recreatedTraceCount = 0;
  expandedSegmentCount = 0;
  intermediateExpandedSegmentCount = 0;
  pathWidthUpgradeCount = 0;
  inPlaceWidthProbeCount = 0;
  reroutedSegmentCount = 0;
  unresolvedSegmentCount = 0;
  attemptedGridCount = 0;
  attemptedLayerGridCount = 0;
  attemptedInflationCount = 0;
  pushedTraceCount = 0;
  elasticPushedTraceCount = 0;
  layerReroutedTraceCount = 0;
  insertedViaCount = 0;
  neckedLayerSegmentCount = 0;
  removedViaPairCount = 0;
  removedViaCount = 0;
  simplifiedPathCount = 0;
  normalizedSegmentCount = 0;
  cleanupClearanceShoveCount = 0;
  relocatedViaCount = 0;
  unresolvedViaCount = 0;
  initialImmutableViaViolationCount = 0;
  remainingImmutableViaViolationCount = 0;
  initialImmutableViaViolationPairCount = 0;
  remainingImmutableViaViolationPairCount = 0;
  immutableTraceMutationIds = [];
  lastSafeImmutableViaViolationSignatures = new Set;
  immutableViaViolationRollbackCount = 0;
  attemptedImmutableViaViolationCount = null;
  attemptedImmutableViaViolationPairCount = null;
  immutableViaViolationRegressionIds = [];
  padClearanceRerouteCount = 0;
  unresolvedPadClearanceCount = 0;
  repairedTraceClearanceSegmentCount = 0;
  repairedPadNeckSegmentCount = 0;
  unresolvedTraceClearanceSegmentCount = 0;
  sameNetContactRejectionCount = 0;
  connectivityValidationCount = 0;
  connectivityRollbackCount = 0;
  connectivityRollbackPhases = [];
  immutableSafetyRollbackCount = 0;
  immutableSafetyRollbackPhases = [];
  connectivityRegressionEndpointIds = [];
  connectivityValidationError = null;
  connectivityRollbackMutationStats = null;
  immutableSafetyRollbackMutationStats = null;
  discardedExpansionMutationStats = null;
  initialPadClearanceViolationCount = 0;
  remainingPadClearanceViolationCount = 0;
  initialPadClearanceViolationCountByClearance = {};
  remainingPadClearanceViolationCountByClearance = {};
  budgetLimitedExpansion = false;
  finalAcceptanceUsed = false;
  cleanupCompleted = false;
  clearanceRepairCompleted = false;
  cleanupBestEffortAccepted = false;
  clearanceRepairBestEffortAccepted = false;
  cleanupIterationBudget = 0;
  clearanceRepairIterationBudget = 0;
  expansionPushedTraceIndices = new Set;
  cleanupMutatedTraceIndices = [];
  failedSubSolverCount = 0;
  inflationAttemptsBySegment = new Map;
  layerAttemptCountByTrace = new Map;
  layerRerouteCountByTrace = new Map;
  activeInflationKey = null;
  activeInflationWidth = null;
  layerAttempt = null;
  pendingLayerOutput = null;
  pendingLayerPushCount = 0;
  statsMaxIterations = 0;
  constructor(e54, t4 = {}) {
    super(), this.inputProblem = structuredClone(e54), this.options = structuredClone(t4), this.traces = structuredClone(e54.traces ?? []), this.connectionNameResolver = new D7(this.inputProblem, this.traces), this.lastConnectivitySafeTraces = structuredClone(this.traces), this.connectivityInvariant = new ote(this.inputProblem, this.lastConnectivitySafeTraces);
    const n8 = t4.onlyConnectionNames ? new Set(this.connectionNameResolver.canonicalize([...t4.onlyConnectionNames])) : null, o10 = this.traces.flatMap((e60, t10) => {
      if (!n8)
        return [t10];
      return this.connectionNameResolver.canonicalize(this.getTraceConnectionNames(e60)).some((e61) => n8.has(e61)) ? [t10] : [];
    }), i8 = new Map(o10.map((e60) => [e60, this.getInitialTracePriority(this.traces[e60])]));
    this.traceOrder = o10.sort((e60, t10) => i8.get(t10) - i8.get(e60) || e60 - t10), this.selectedOwnedTraceIndices = this.traceOrder.filter((e60) => this.findConnectionForTrace(this.traces[e60])), this.selectedCleanupTraceIndices = [...this.selectedOwnedTraceIndices], this.selectedViaRepairTraceIndices = [...this.selectedOwnedTraceIndices], this.mutableBlockerTraceIndices = this.traces.flatMap((e60, t10) => this.findConnectionForTrace(e60) ? [t10] : []);
    const r9 = new Set(this.mutableBlockerTraceIndices);
    this.immutableTraceIndices = this.traces.flatMap((e60, t10) => r9.has(t10) ? [] : (this.initialImmutableTraceSignatures.set(t10, JSON.stringify(e60)), [t10])), this.previousWidthDeficit = this.calculateWidthDeficit().deficit, this.obstacleIndex = new Cee(this.inputProblem, this.traces, this.traceIndex >= 0 ? this.traceIndex : undefined, [], this.connectionNameResolver), this.lastSafeImmutableViaViolationSignatures = this.getImmutableViaViolationSignatures(this.traces), this.initialImmutableViaViolationCount = this.countViolatingImmutableVias(this.lastSafeImmutableViaViolationSignatures), this.remainingImmutableViaViolationCount = this.initialImmutableViaViolationCount, this.initialImmutableViaViolationPairCount = this.lastSafeImmutableViaViolationSignatures.size, this.remainingImmutableViaViolationPairCount = this.initialImmutableViaViolationPairCount, this.activeSubSolver = null, this.MAX_ITERATIONS = 125000, this.stats = this.createStats();
  }
  getSolverName() {
    return "PowerTraceExpanderSolver";
  }
  _step() {
    const e54 = this.activeSubSolver;
    for (let e60 = 0;e60 < _te && (this.operationIndex = e60, this.stepOperation(), !this.solved && !this.failed); e60++)
      ;
    (!e54 || this.activeSubSolver !== e54 || e54.solved || e54.failed || this.MAX_ITERATIONS !== this.statsMaxIterations) && (this.stats = this.createStats());
  }
  stepOperation() {
    if (this.shouldStartBudgetFinalization())
      this.startBudgetFinalization();
    else if (this.activeSubSolver)
      this.stepActiveGridSolver();
    else
      switch (this.phase) {
        case "scan-trace":
          this.scanNextTrace();
          break;
        case "evaluate-segment":
          this.evaluateNextSegment();
          break;
        case "try-trace-inflation":
        case "cleanup":
        case "repair-trace-clearance":
          break;
        case "try-layer-candidate":
          this.startNextLayerCandidate();
          break;
        case "try-grid-candidate":
          this.startNextGridCandidate();
          break;
        case "complete":
          this.acceptConnectivityCheckpoint(this.traces, "final"), this.solved = true;
      }
  }
  scanNextTrace() {
    if (this.traceOrderCursor++, this.routeSegmentIndex = 0, this.traceOrderCursor >= this.traceOrder.length)
      return void this.finishOrStartNextPass();
    this.traceIndex = this.traceOrder[this.traceOrderCursor];
    const e54 = this.traces[this.traceIndex];
    this.findConnectionForTrace(e54) ? (this.nominalTraceWidth = this.resolveNominalTraceWidth(e54), this.traceMeetsNominalWidth(e54, this.nominalTraceWidth) ? this.keptTraceCount++ : (this.rebuildObstacleIndex(), e54.route = function(e60, t4) {
      if (e60.length < 2)
        return e60.map((e61) => ({ ...e61 }));
      const n8 = [];
      for (let o10 = 0;o10 < e60.length - 1; o10++) {
        const i8 = e60[o10], r9 = e60[o10 + 1];
        if (n8.push({ ...i8 }), i8.route_type !== "wire" || r9.route_type !== "wire" || i8.layer !== r9.layer || i8.width >= t4 - L7)
          continue;
        const s7 = z7(i8, r9), a9 = Math.max(1, Math.ceil(s7 / t4));
        for (let e61 = 1;e61 < a9; e61++) {
          const t10 = e61 / a9;
          n8.push({ route_type: "wire", x: i8.x + (r9.x - i8.x) * t10, y: i8.y + (r9.y - i8.y) * t10, width: i8.width, layer: i8.layer });
        }
      }
      return n8.push({ ...e60[e60.length - 1] }), n8;
    }(e54.route, this.nominalTraceWidth), this.recreatedTraceCount++, this.phase = "evaluate-segment")) : this.keptTraceCount++;
  }
  finishOrStartNextPass() {
    const { deficit: e54, nominalArea: t4 } = this.calculateWidthDeficit(), n8 = this.previousWidthDeficit - e54;
    if (this.lastNormalizedWidthDeficitGain = t4 <= L7 ? 0 : n8 / t4, this.normalizedWidthDeficitGainByPass.push(this.lastNormalizedWidthDeficitGain), this.plateauReached = this.lastNormalizedWidthDeficitGain < 0.001, this.completedPassCount = this.passIndex + 1, this.passIndex + 1 < this.maxPassCount && this.lastNormalizedWidthDeficitGain >= 0.001)
      return this.previousWidthDeficit = e54, this.passIndex++, this.traceOrderCursor = -1, this.traceIndex = -1, this.routeSegmentIndex = 0, this.inflationAttemptsBySegment.clear(), void (this.phase = "scan-trace");
    this.startCleanup();
  }
  startCleanup() {
    this.acceptConnectivityCheckpoint(this.traces, "expansion"), this.traceIndex = this.traces.length, this.phase = "cleanup";
    const e54 = new dte({ simpleRouteJson: this.inputProblem, traces: this.traces, traceIndices: this.selectedCleanupTraceIndices, viaRepairTraceIndices: this.selectedViaRepairTraceIndices, mutableTraceIndices: this.mutableBlockerTraceIndices, maxRerouteLength: 10, desiredPadClearance: this.options.powerTraceToPadClearance }), t4 = this.getRemainingChildStepBudget(), n8 = t4 === 0 ? 0 : Math.max(1, Math.floor(0.75 * t4));
    e54.MAX_ITERATIONS = Math.min(e54.MAX_ITERATIONS, n8), this.cleanupIterationBudget = e54.MAX_ITERATIONS, this.activeSubSolver = e54;
  }
  shouldStartBudgetFinalization() {
    return !this.budgetLimitedExpansion && (this.phase !== "cleanup" && this.phase !== "repair-trace-clearance" && this.phase !== "complete" && this.getOperationCount() >= this.getExpansionOperationBudget());
  }
  getExpansionOperationBudget() {
    const e54 = this.MAX_ITERATIONS * _te, t4 = Math.min(Math.max(0, e54 - 1), Math.max(1, Math.floor(0.125 * e54)));
    return Math.max(1, e54 - t4);
  }
  getFinalizationIterationReserve() {
    return Math.max(0, this.MAX_ITERATIONS - this.getExpansionIterationBudget());
  }
  getExpansionIterationBudget() {
    return Math.ceil(this.getExpansionOperationBudget() / _te);
  }
  startBudgetFinalization() {
    this.budgetLimitedExpansion = true, this.activeSubSolver = null, this.pendingLayerOutput = null, this.pendingLayerPushCount = 0, this.activeInflationKey = null, this.activeInflationWidth = null, this.layerAttempt = null, this.discardInFlightExpansion(), this.startCleanup();
  }
  discardInFlightExpansion() {
    this.discardedExpansionMutationStats = this.captureAndResetExpansionMutationStats(), this.restoreLastConnectivitySafeTraces();
  }
  rollbackConnectivityRegressedExpansion() {
    this.connectivityRollbackMutationStats = this.captureAndResetExpansionMutationStats(), this.restoreLastConnectivitySafeTraces();
  }
  rollbackImmutableUnsafeExpansion() {
    this.immutableSafetyRollbackMutationStats = this.captureAndResetExpansionMutationStats(), this.restoreLastConnectivitySafeTraces();
  }
  captureAndResetExpansionMutationStats() {
    const e54 = { recreatedTraceCount: this.recreatedTraceCount, expandedSegmentCount: this.expandedSegmentCount, intermediateExpandedSegmentCount: this.intermediateExpandedSegmentCount, pathWidthUpgradeCount: this.pathWidthUpgradeCount, reroutedSegmentCount: this.reroutedSegmentCount, pushedTraceCount: this.pushedTraceCount, elasticPushedTraceCount: this.elasticPushedTraceCount, layerReroutedTraceCount: this.layerReroutedTraceCount, insertedViaCount: this.insertedViaCount, neckedLayerSegmentCount: this.neckedLayerSegmentCount };
    return this.recreatedTraceCount = 0, this.expandedSegmentCount = 0, this.intermediateExpandedSegmentCount = 0, this.pathWidthUpgradeCount = 0, this.reroutedSegmentCount = 0, this.pushedTraceCount = 0, this.elasticPushedTraceCount = 0, this.layerReroutedTraceCount = 0, this.insertedViaCount = 0, this.neckedLayerSegmentCount = 0, this.expansionPushedTraceIndices.clear(), e54;
  }
  restoreLastConnectivitySafeTraces() {
    this.traces = structuredClone(this.lastConnectivitySafeTraces), this.rebuildObstacleIndex();
  }
  getOperationCount() {
    return this.iterations === 0 ? 0 : (this.iterations - 1) * _te + this.operationIndex + 1;
  }
  getRemainingChildStepBudget() {
    return Math.max(0, this.MAX_ITERATIONS * _te - this.getOperationCount() - 1);
  }
  calculateWidthDeficit() {
    let e54 = 0, t4 = 0;
    for (const n8 of this.traceOrder) {
      const o10 = this.traces[n8];
      if (!this.findConnectionForTrace(o10))
        continue;
      const i8 = this.resolveNominalTraceWidth(o10);
      for (let n10 = 0;n10 < o10.route.length - 1; n10++) {
        const r9 = o10.route[n10], s7 = o10.route[n10 + 1];
        if (!bte(r9) || !bte(s7) || r9.layer !== s7.layer)
          continue;
        const a9 = z7(r9, s7), c5 = r9.width;
        t4 += a9 * i8, e54 += a9 * Math.max(0, i8 - c5);
      }
    }
    return { deficit: e54, nominalArea: t4 };
  }
  getInitialTracePriority(e54) {
    const t4 = this.resolveNominalTraceWidth(e54);
    let n8 = 0;
    for (let o10 = 0;o10 < e54.route.length - 1; o10++) {
      const i8 = e54.route[o10], r9 = e54.route[o10 + 1];
      bte(i8) && bte(r9) && i8.layer === r9.layer && (n8 += z7(i8, r9) * Math.max(0, t4 - Math.min(i8.width, r9.width)));
    }
    return t4 * n8;
  }
  evaluateNextSegment() {
    const e54 = this.traces[this.traceIndex];
    if (!e54)
      return void (this.phase = "scan-trace");
    const t4 = this.findNextUnderWidthSegment(e54, this.routeSegmentIndex, this.nominalTraceWidth);
    if (t4 === -1)
      return void (this.phase = "scan-trace");
    this.routeSegmentIndex = t4;
    const n8 = e54.route[t4], o10 = e54.route[t4 + 1];
    if (!bte(n8) || !bte(o10))
      return void this.routeSegmentIndex++;
    const i8 = this.getTraceConnectionNames(e54), r9 = Math.min(n8.width, o10.width), s7 = this.findMaximumSafeInPlaceWidth(e54, t4, i8);
    if (s7 > r9 + L7) {
      if (n8.width = Math.max(n8.width, s7), o10.width = Math.max(o10.width, s7), s7 >= this.nominalTraceWidth - L7)
        return this.expandedSegmentCount++, void this.routeSegmentIndex++;
      this.intermediateExpandedSegmentCount++;
    }
    this.startTraceInflation(e54, t4) || this.prepareLayerRouteAttempt(e54, t4) || this.prepareRegularGridCandidates(e54, t4);
  }
  prepareRegularGridCandidates(e54, t4) {
    if (this.currentIntervals = this.getExponentialIntervalCandidates(e54, t4, this.nominalTraceWidth), this.intervalCursor = 0, this.candidateWidths = this.getCandidateWidths(this.nominalTraceWidth), this.widthCursor = 0, this.gridResolutions = [], this.resolutionCursor = 0, this.offsetCursor = 0, this.currentIntervals.length === 0)
      return this.unresolvedSegmentCount++, void this.routeSegmentIndex++;
    this.phase = "try-grid-candidate";
  }
  prepareLayerRouteAttempt(e54, t4) {
    if (this.nominalTraceWidth < 0.499999)
      return false;
    const n8 = this.options.allowNewVias !== false && this.inputProblem.layerCount >= 2, o10 = n8 ? 2 : this.maxPassCount, i8 = this.layerAttemptCountByTrace.get(this.traceIndex) ?? 0, r9 = this.layerRerouteCountByTrace.get(this.traceIndex) ?? 0;
    if (r9 >= o10 || i8 >= o10 || i8 > this.passIndex || i8 > 0 && r9 === 0)
      return false;
    const s7 = e54.route[t4], a9 = e54.route[t4 + 1];
    if (!bte(s7) || !bte(a9) || Math.min(s7.width, a9.width) >= 0.5 * this.nominalTraceWidth - L7)
      return false;
    const c5 = this.getExponentialIntervalCandidates(e54, t4, this.nominalTraceWidth).filter((t10) => this.intervalSupportsLayerRouting(e54, t10)).sort((t10, n10) => n10.endIndex - t10.endIndex || t10.startIndex - n10.startIndex || this.getRouteIntervalLength(e54, n10.startIndex, n10.endIndex) - this.getRouteIntervalLength(e54, t10.startIndex, t10.endIndex))[0];
    if (!c5)
      return false;
    const l5 = this.getRouteQuality(e54.route.slice(c5.startIndex, c5.endIndex + 1));
    if (l5.deficitArea < this.nominalTraceWidth)
      return false;
    if (i8 > 0 && l5.deficitArea / Math.max(l5.length, L7) < 0.25)
      return false;
    const h5 = e54.route[c5.startIndex], d9 = e54.route[c5.endIndex], u9 = this.getTraceConnectionNames(e54), p9 = n8 ? this.getEndpointLayers(h5, u9) : [h5.layer], m9 = n8 ? this.getEndpointLayers(d9, u9) : [d9.layer], g10 = Math.min(this.nominalTraceWidth, Math.max(h5.width, this.findMaximumSafeInPlaceWidth(e54, c5.startIndex, u9))), f10 = Math.min(this.nominalTraceWidth, Math.max(d9.width, this.findMaximumSafeInPlaceWidth(e54, c5.endIndex - 1, u9))), _5 = this.getSoftTraceIndices(this.nominalTraceWidth);
    return this.layerAttemptCountByTrace.set(this.traceIndex, i8 + 1), this.layerAttempt = { interval: c5, minViaCount: n8 ? 1 : 0, maxViaCount: n8 ? 2 : 0, candidateWidths: [this.nominalTraceWidth], widthCursor: 0, gridResolutions: [j7(this.nominalTraceWidth / 4, 0.2, 0.3)], resolutionCursor: 0, offsetCursor: 0, startLayers: p9, endLayers: m9, startNeckWidth: g10, endNeckWidth: f10, softTraceIndices: _5 }, this.phase = "try-layer-candidate", true;
  }
  intervalSupportsLayerRouting(e54, t4) {
    if (t4.startIndex >= t4.endIndex)
      return false;
    for (let n10 = t4.startIndex;n10 <= t4.endIndex; n10++) {
      const t10 = e54.route[n10];
      if (!bte(t10))
        return false;
    }
    const n8 = e54.route[t4.startIndex], o10 = e54.route[t4.endIndex];
    return n8.layer === o10.layer;
  }
  getEndpointLayers(e54, t4) {
    return [...new Set([e54.layer, ...this.obstacleIndex.getConnectedLayersAtPoint({ x: e54.x, y: e54.y }, t4)])].filter((e60) => this.obstacleIndex.boardLayers.includes(e60));
  }
  getSoftTraceIndices(e54) {
    const t4 = [];
    for (let n8 = 0;n8 < this.traces.length; n8++) {
      if (n8 === this.traceIndex)
        continue;
      const o10 = this.traces[n8], i8 = this.findConnectionForTrace(o10);
      if (!i8)
        continue;
      Math.max(i8.nominalTraceWidth ?? i8.width ?? this.inputProblem.nominalTraceWidth ?? this.inputProblem.minTraceWidth, this.inputProblem.minTraceWidth) < e54 - L7 && t4.push(n8);
    }
    return t4;
  }
  startNextLayerCandidate() {
    const e54 = this.layerAttempt, t4 = this.traces[this.traceIndex];
    if (!e54 || !t4)
      return this.layerAttempt = null, void (this.phase = "evaluate-segment");
    if (e54.widthCursor >= e54.candidateWidths.length) {
      const e60 = this.routeSegmentIndex;
      return this.layerAttempt = null, void this.prepareRegularGridCandidates(t4, e60);
    }
    const n8 = e54.candidateWidths[e54.widthCursor];
    if (e54.gridResolutions.length === 0 && (e54.gridResolutions = this.getGridResolutions(n8)), e54.resolutionCursor >= e54.gridResolutions.length)
      return e54.widthCursor++, e54.gridResolutions = [], e54.resolutionCursor = 0, void (e54.offsetCursor = 0);
    if (e54.offsetCursor >= fte.length)
      return e54.resolutionCursor++, void (e54.offsetCursor = 0);
    const o10 = t4.route[e54.interval.startIndex], i8 = t4.route[e54.interval.endIndex];
    if (!bte(o10) || !bte(i8))
      return this.layerAttempt = null, void this.prepareRegularGridCandidates(t4, this.routeSegmentIndex);
    const r9 = e54.gridResolutions[e54.resolutionCursor], s7 = fte[e54.offsetCursor], a9 = s7.offset, c5 = Math.min(e54.startNeckWidth, e54.endNeckWidth), l5 = this.inputProblem.min_via_hole_diameter ?? this.inputProblem.minViaHoleDiameter ?? 0.3, h5 = Math.max(l5, this.inputProblem.min_via_pad_diameter ?? this.inputProblem.minViaPadDiameter ?? this.inputProblem.minViaDiameter ?? 0.6), d9 = Math.max(this.inputProblem.minTraceWidth, Math.min(s7.strictNecking ? e54.startNeckWidth : c5, n8)), u9 = Math.max(this.inputProblem.minTraceWidth, Math.min(s7.strictNecking ? e54.endNeckWidth : c5, n8)), p9 = j7(3 * this.nominalTraceWidth, 1.5, 3);
    e54.maxViaCount > 0 ? this.attemptedLayerGridCount++ : this.attemptedGridCount++, this.activeSubSolver = new iee({ start: o10, end: i8, originalStartLayer: o10.layer, originalEndLayer: i8.layer, startLayers: e54.startLayers, endLayers: e54.endLayers, layers: this.obstacleIndex.boardLayers, traceWidth: n8, startNeckWidth: d9, endNeckWidth: u9, maxStartNeckLength: p9, maxEndNeckLength: p9, neckPenaltyExponent: s7.strictNecking ? 2 : 1, viaDiameter: h5, viaHoleDiameter: l5, minViaCount: e54.minViaCount, maxViaCount: e54.maxViaCount, viaCost: Math.max(1, 2 * this.nominalTraceWidth), gridSize: r9, gridOffset: { x: a9.x * r9, y: a9.y * r9 }, connectionNames: this.getTraceConnectionNames(t4), obstacleIndex: this.obstacleIndex, ignoreTraceIndex: this.traceIndex, ignoreRouteRange: { start: Math.max(0, e54.interval.startIndex - 1), end: Math.min(t4.route.length - 1, e54.interval.endIndex + 1) }, softTraceIndices: e54.softTraceIndices, fixedVias: this.getFixedViasOutsideInterval(t4, e54.interval), bounds: this.inputProblem.bounds, obstacleClearance: this.getDesiredPadClearance(n8), searchPadding: Math.min(5, Math.max(2.5, z7(o10, i8) / 2, 4 * n8)) });
  }
  startNextGridCandidate() {
    const e54 = this.traces[this.traceIndex];
    if (!e54)
      return void (this.phase = "scan-trace");
    if (this.widthCursor >= this.candidateWidths.length)
      return this.unresolvedSegmentCount++, this.routeSegmentIndex++, void (this.phase = "evaluate-segment");
    if (this.intervalCursor >= this.currentIntervals.length)
      return this.widthCursor++, this.intervalCursor = 0, this.gridResolutions = [], this.resolutionCursor = 0, void (this.offsetCursor = 0);
    const t4 = this.candidateWidths[this.widthCursor], n8 = e54.route[this.routeSegmentIndex], o10 = e54.route[this.routeSegmentIndex + 1];
    if (bte(n8) && bte(o10) && t4 <= Math.min(n8.width, o10.width) + L7)
      return void (this.widthCursor = this.candidateWidths.length);
    if (this.gridResolutions.length === 0 && (this.gridResolutions = this.getGridResolutions(t4)), this.resolutionCursor >= this.gridResolutions.length)
      return this.intervalCursor++, this.resolutionCursor = 0, void (this.offsetCursor = 0);
    if (this.offsetCursor >= gte.length)
      return this.resolutionCursor++, void (this.offsetCursor = 0);
    const i8 = this.currentIntervals[this.intervalCursor], r9 = e54.route[i8.startIndex], s7 = e54.route[i8.endIndex];
    if (!bte(r9) || !bte(s7) || r9.layer !== s7.layer)
      return this.intervalCursor++, this.resolutionCursor = 0, void (this.offsetCursor = 0);
    if (this.endpointCollides(e54, i8, r9, t4) || this.endpointCollides(e54, i8, s7, t4))
      return this.intervalCursor++, this.resolutionCursor = 0, void (this.offsetCursor = 0);
    const a9 = this.gridResolutions[this.resolutionCursor], c5 = gte[this.offsetCursor], l5 = { x: c5.x * a9, y: c5.y * a9 };
    this.attemptedGridCount++, this.activeSubSolver = new yee({ start: r9, end: s7, layer: r9.layer, traceWidth: t4, gridSize: a9, gridOffset: l5, connectionNames: this.getTraceConnectionNames(e54), obstacleIndex: this.obstacleIndex, ignoreTraceIndex: this.traceIndex, ignoreRouteRange: { start: Math.max(0, i8.startIndex - 1), end: Math.min(e54.route.length - 1, i8.endIndex + 1) }, bounds: this.inputProblem.bounds, obstacleClearance: this.getDesiredPadClearance(t4), searchPadding: Math.min(5, Math.max(1.5, z7(r9, s7) / 2, 3 * t4)) });
  }
  endpointCollides(e54, t4, n8, o10) {
    return this.obstacleIndex.collides({ start: n8, end: n8, layer: n8.layer, width: o10, connectionNames: this.getTraceConnectionNames(e54), ignoreTraceIndex: this.traceIndex, ignoreRouteRange: { start: Math.max(0, t4.startIndex - 1), end: Math.min(e54.route.length - 1, t4.endIndex + 1) }, obstacleClearance: this.getDesiredPadClearance(o10) });
  }
  stepActiveGridSolver() {
    if (this.activeSubSolver instanceof mte)
      return void this.stepActiveTraceClearanceRepairSolver();
    if (this.activeSubSolver instanceof dte)
      return void this.stepActiveCleanupSolver();
    if (this.activeSubSolver instanceof wee)
      return void this.stepActiveInflationSolver();
    if (this.activeSubSolver instanceof iee)
      return void this.stepActiveLayerSolver();
    const e54 = this.activeSubSolver;
    if (e54.step(), e54.solved || e54.failed) {
      if (e54.solved) {
        const t4 = e54.getOutput();
        if (t4) {
          const e60 = this.gridRouteReplacementCollides(t4) || this.gridRouteBoundaryCollides(t4);
          if (!e60 && this.gridRoutePreservesSameNetContacts(t4))
            return this.applyGridRoute(this.maximizeGridRouteWidth(t4)), void (this.activeSubSolver = null);
          e60 || this.sameNetContactRejectionCount++;
        }
      }
      this.retainFailedSubSolver(e54), this.activeSubSolver = null, this.offsetCursor++;
    }
  }
  stepActiveCleanupSolver() {
    const e54 = this.activeSubSolver;
    if (e54.step(), e54.solved || e54.failed) {
      if (e54.solved)
        return this.adoptCleanupOutput(e54), this.activeSubSolver = null, void this.startTraceClearanceRepair();
      this.retainFailedSubSolver(e54), this.activeSubSolver = null, this.startTraceClearanceRepair();
    }
  }
  adoptCleanupOutput(e54) {
    const t4 = this.acceptConnectivityCheckpoint(e54.getOutput(), "cleanup");
    this.cleanupCompleted = !e54.budgetLimited;
    const n8 = e54.stats;
    this.connectivityValidationError ??= n8.connectivityValidationError ?? null, this.connectivityValidationCount += Number(n8.connectivityValidationCount ?? 0);
    const o10 = Number(n8.connectivityRollbackCount ?? 0);
    o10 > 0 && (this.connectivityRollbackCount += o10, this.connectivityRollbackPhases.includes("cleanup") || this.connectivityRollbackPhases.push("cleanup"), this.connectivityRegressionEndpointIds = [...new Set([...this.connectivityRegressionEndpointIds, ...n8.connectivityRegressionEndpointIds ?? []])]);
    const i8 = t4 && o10 === 0;
    this.cleanupBestEffortAccepted = e54.budgetLimited && i8, this.cleanupMutatedTraceIndices = i8 ? [...n8.mutatedTraceIndices ?? []] : [], this.removedViaPairCount = i8 ? Number(n8.viaPairCountRemoved ?? 0) : 0, this.removedViaCount = i8 ? Number(n8.viaCountRemoved ?? 0) : 0, this.simplifiedPathCount = i8 ? Number(n8.simplifiedPathCount ?? 0) : 0, this.normalizedSegmentCount = i8 ? Number(n8.normalizedSegmentCount ?? 0) : 0, this.cleanupClearanceShoveCount = i8 ? Number(n8.committedClearanceShoveCount ?? 0) : 0, this.relocatedViaCount = i8 ? Number(n8.relocatedViaCount ?? 0) : 0, this.unresolvedViaCount = Number(n8.unresolvedViaCount ?? 0), this.padClearanceRerouteCount = i8 ? Number(n8.padClearanceRerouteCount ?? 0) : 0, this.unresolvedPadClearanceCount = Number(n8.unresolvedPadClearanceCount ?? 0), this.initialPadClearanceViolationCount = Number(n8.initialPadClearanceViolationCount ?? 0), this.remainingPadClearanceViolationCount = Number(n8.remainingPadClearanceViolationCount ?? 0), this.initialPadClearanceViolationCountByClearance = { ...n8.initialPadClearanceViolationCountByClearance ?? {} }, this.remainingPadClearanceViolationCountByClearance = { ...n8.remainingPadClearanceViolationCountByClearance ?? {} }, this.rebuildObstacleIndex();
  }
  startTraceClearanceRepair() {
    this.phase = "repair-trace-clearance";
    const e54 = [...new Set([...this.getOwnedTraceIndices(), ...this.expansionPushedTraceIndices, ...this.cleanupMutatedTraceIndices])], t4 = new mte({ simpleRouteJson: this.inputProblem, traces: this.traces, traceIndices: e54 });
    t4.MAX_ITERATIONS = Math.min(t4.MAX_ITERATIONS, this.getRemainingChildStepBudget()), this.clearanceRepairIterationBudget = t4.MAX_ITERATIONS, this.activeSubSolver = t4;
  }
  stepActiveTraceClearanceRepairSolver() {
    const e54 = this.activeSubSolver;
    if (e54.step(), e54.solved || e54.failed) {
      if (e54.solved)
        return this.adoptClearanceRepairOutput(e54), this.activeSubSolver = null, void (this.phase = "complete");
      this.retainFailedSubSolver(e54), this.activeSubSolver = null, this.phase = "complete";
    }
  }
  adoptClearanceRepairOutput(e54) {
    const t4 = this.acceptConnectivityCheckpoint(e54.getOutput(), "clearance-repair");
    this.clearanceRepairCompleted = !e54.budgetLimited;
    const n8 = e54.stats;
    this.connectivityValidationError ??= n8.connectivityValidationError ?? null, this.connectivityValidationCount += Number(n8.connectivityValidationCount ?? 0);
    const o10 = Number(n8.connectivityRollbackCount ?? 0);
    o10 > 0 && (this.connectivityRollbackCount += o10, this.connectivityRollbackPhases.includes("clearance-repair") || this.connectivityRollbackPhases.push("clearance-repair"), this.connectivityRegressionEndpointIds = [...new Set([...this.connectivityRegressionEndpointIds, ...n8.connectivityRegressionEndpointIds ?? []])]);
    const i8 = t4 && o10 === 0;
    this.clearanceRepairBestEffortAccepted = e54.budgetLimited && i8, this.repairedTraceClearanceSegmentCount = i8 ? Number(n8.repairedSegmentCount ?? 0) : 0, this.repairedPadNeckSegmentCount = i8 ? Number(n8.repairedPadNeckSegmentCount ?? 0) : 0, this.unresolvedTraceClearanceSegmentCount = Number(n8.unresolvedSegmentCount ?? 0), this.rebuildObstacleIndex();
  }
  stepActiveLayerSolver() {
    const e54 = this.activeSubSolver;
    if (e54.step(), e54.solved || e54.failed) {
      if (e54.solved) {
        const t4 = e54.getOutput();
        if (t4) {
          const e60 = !this.layerRouteReplacementCollides(t4, true) && this.layerRouteImprovesInterval(t4), n8 = e60 && this.layerRoutePreservesSameNetContacts(t4);
          if (n8) {
            if (this.activeSubSolver = null, this.pendingLayerOutput = t4, this.pendingLayerPushCount = 0, !this.layerRouteReplacementCollides(t4, false))
              return void this.applyLayerRoute(t4);
            if (this.startPendingLayerInflation())
              return;
            this.pendingLayerOutput = null;
          }
          e60 && !n8 && this.sameNetContactRejectionCount++;
        }
      }
      this.retainFailedSubSolver(e54), this.activeSubSolver = null, this.layerAttempt && this.layerAttempt.offsetCursor++, this.phase = "try-layer-candidate";
    }
  }
  layerRouteReplacementCollides(e54, t4) {
    const n8 = this.traces[this.traceIndex], o10 = this.layerAttempt;
    if (!n8 || !o10)
      return true;
    const i8 = this.getTraceConnectionNames(n8), r9 = t4 ? o10.softTraceIndices : undefined, s7 = { start: Math.max(0, o10.interval.startIndex - 1), end: Math.min(n8.route.length - 1, o10.interval.endIndex + 1) }, a9 = this.getFixedViasOutsideInterval(n8, o10.interval);
    for (let t10 = 0;t10 < e54.route.length; t10++) {
      const n10 = e54.route[t10];
      if (n10?.route_type === "via") {
        if (this.obstacleIndex.collidesVia({ point: n10, layers: this.obstacleIndex.boardLayers, padDiameter: n10.via_diameter ?? 0.6, holeDiameter: n10.via_hole_diameter ?? this.obstacleIndex.defaultViaHoleDiameter, connectionNames: i8, ignoreTraceIndex: this.traceIndex, ignoreTraceIndices: r9, otherNewViaPoints: e54.route.slice(0, t10).filter((e60) => e60.route_type === "via").map((e60) => ({ x: e60.x, y: e60.y })), fixedVias: a9, ignoreRouteRange: s7, obstacleClearance: this.getDesiredPadClearance(e54.traceWidth), blockSameNetObstacles: true, sameNetObstacleClearance: 0 }))
          return true;
        continue;
      }
      const o11 = e54.route[t10 + 1];
      if (n10?.route_type === "wire" && o11?.route_type === "wire" && n10.layer === o11.layer && this.obstacleIndex.collides({ start: n10, end: o11, layer: n10.layer, width: Math.max(n10.width, o11.width), connectionNames: i8, ignoreTraceIndex: this.traceIndex, ignoreTraceIndices: r9, ignoreRouteRange: s7, obstacleClearance: this.getDesiredPadClearance(e54.traceWidth) }))
        return true;
    }
    return this.layerRouteBoundaryCollides(e54, t4);
  }
  getFixedViasOutsideInterval(e54, t4) {
    return e54.route.flatMap((e60, n8) => e60.route_type !== "via" || n8 >= t4.startIndex && n8 <= t4.endIndex ? [] : [{ point: { x: e60.x, y: e60.y }, padDiameter: e60.via_diameter ?? 0.6, holeDiameter: e60.via_hole_diameter ?? this.obstacleIndex.defaultViaHoleDiameter }]);
  }
  layerRouteBoundaryCollides(e54, t4) {
    const n8 = this.traces[this.traceIndex], o10 = this.layerAttempt, i8 = e54.route.find((e60) => e60.route_type === "wire");
    let r9;
    for (let t10 = e54.route.length - 1;t10 >= 0; t10--) {
      const n10 = e54.route[t10];
      if (n10?.route_type === "wire") {
        r9 = n10;
        break;
      }
    }
    if (!i8 || !r9)
      return true;
    const s7 = [{ outside: n8.route[o10.interval.startIndex - 1], inside: i8 }, { outside: n8.route[o10.interval.endIndex + 1], inside: r9 }];
    for (const i9 of s7)
      if (bte(i9.outside) && i9.outside.layer === i9.inside.layer && this.obstacleIndex.collides({ start: i9.outside, end: i9.inside, layer: i9.inside.layer, width: Math.max(i9.outside.width, i9.inside.width), connectionNames: this.getTraceConnectionNames(n8), ignoreTraceIndex: this.traceIndex, ignoreTraceIndices: t4 ? o10.softTraceIndices : undefined, ignoreRouteRange: { start: Math.max(0, o10.interval.startIndex - 1), end: Math.min(n8.route.length - 1, o10.interval.endIndex + 1) }, obstacleClearance: this.getDesiredPadClearance(e54.traceWidth) }))
        return true;
    return false;
  }
  layerRouteImprovesInterval(e54) {
    const t4 = this.traces[this.traceIndex], n8 = this.layerAttempt.interval, o10 = this.getRouteQuality(t4.route.slice(n8.startIndex, n8.endIndex + 1)), i8 = this.getRouteQuality(e54.route);
    return i8.length <= o10.length + 10 + L7 && i8.deficitArea <= o10.deficitArea - Math.max(0.05, 0.1 * o10.deficitArea);
  }
  getRouteQuality(e54) {
    let t4 = 0, n8 = 0;
    for (let o10 = 0;o10 < e54.length - 1; o10++) {
      const i8 = e54[o10], r9 = e54[o10 + 1];
      if (!bte(i8) || !bte(r9) || i8.layer !== r9.layer)
        continue;
      const s7 = z7(i8, r9), a9 = Math.min(i8.width, r9.width);
      t4 += s7, n8 += s7 * Math.max(0, this.nominalTraceWidth - a9);
    }
    return { length: t4, deficitArea: n8 };
  }
  getLayerInflationCorridor(e54) {
    const t4 = [];
    for (let n8 = 0;n8 < e54.route.length; n8++) {
      const o10 = e54.route[n8];
      if (o10?.route_type === "via") {
        for (const e60 of this.obstacleIndex.boardLayers)
          t4.push({ start: o10, end: o10, layer: e60, width: o10.via_diameter ?? 0.6 });
        continue;
      }
      const i8 = e54.route[n8 + 1];
      o10?.route_type === "wire" && i8?.route_type === "wire" && o10.layer === i8.layer && t4.push({ start: o10, end: i8, layer: o10.layer, width: Math.max(o10.width, i8.width) });
    }
    return t4;
  }
  startPendingLayerInflation() {
    const e54 = this.pendingLayerOutput;
    if (!e54 || this.pendingLayerPushCount >= 2)
      return false;
    const t4 = this.getLayerInflationCorridor(e54);
    return t4.length !== 0 && (this.pendingLayerPushCount++, this.attemptedInflationCount++, this.activeSubSolver = new wee({ simpleRouteJson: this.inputProblem, traces: this.traces, powerTraceIndex: this.traceIndex, nominalPowerWidth: e54.traceWidth, mutableTraceIndices: this.mutableBlockerTraceIndices, corridor: t4, maxRerouteLength: 10 }, this.connectionNameResolver), this.phase = "try-trace-inflation", true);
  }
  applyLayerRoute(e54) {
    const t4 = this.traces[this.traceIndex], n8 = this.layerAttempt.interval, o10 = this.createLayerRouteReplacement(e54);
    t4.route.splice(n8.startIndex, n8.endIndex - n8.startIndex + 1, ...o10), e54.viaCount > 0 && this.layerReroutedTraceCount++, this.layerRerouteCountByTrace.set(this.traceIndex, (this.layerRerouteCountByTrace.get(this.traceIndex) ?? 0) + 1), this.reroutedSegmentCount++, this.insertedViaCount += e54.viaCount, e54.viaCount > 0 && (this.neckedLayerSegmentCount += o10.filter((e60) => e60.route_type === "wire" && e60.width < this.nominalTraceWidth - L7).length), this.routeSegmentIndex = n8.startIndex, this.currentIntervals = [], this.layerAttempt = null, this.pendingLayerOutput = null, this.pendingLayerPushCount = 0, this.phase = "evaluate-segment";
  }
  createLayerRouteReplacement(e54) {
    const t4 = this.traces[this.traceIndex], n8 = this.layerAttempt.interval, o10 = t4.route[n8.startIndex], i8 = t4.route[n8.endIndex], r9 = structuredClone(e54.route), s7 = r9.findIndex((e60) => e60.route_type === "wire");
    let a9 = -1;
    for (let e60 = r9.length - 1;e60 >= 0; e60--)
      if (r9[e60]?.route_type === "wire") {
        a9 = e60;
        break;
      }
    return s7 >= 0 && (r9[s7] = { ...o10, ...r9[s7] }), a9 >= 0 && (r9[a9] = { ...i8, ...r9[a9] }), r9;
  }
  layerRoutePreservesSameNetContacts(e54) {
    const t4 = this.traces[this.traceIndex], n8 = this.layerAttempt.interval;
    return this.routeReplacementPreservesSameNetContacts(t4, n8, this.createLayerRouteReplacement(e54));
  }
  startTraceInflation(e54, t4) {
    const n8 = e54.route[t4], o10 = e54.route[t4 + 1];
    if (!bte(n8) || !bte(o10))
      return false;
    const i8 = Math.min(n8.width, o10.width), r9 = this.findBestPushableInflationWidth(e54, t4, i8);
    if (!r9)
      return false;
    const s7 = this.getLocalInflationCorridor(e54, t4, r9);
    if (s7.length === 0)
      return false;
    const a9 = [this.traceIndex, n8.x, n8.y, o10.x, o10.y].join(":"), c5 = this.inflationAttemptsBySegment.get(a9) ?? 0;
    return !(c5 >= 2) && (this.inflationAttemptsBySegment.set(a9, c5 + 1), this.activeInflationKey = a9, this.activeInflationWidth = r9, this.attemptedInflationCount++, this.activeSubSolver = new wee({ simpleRouteJson: this.inputProblem, traces: this.traces, powerTraceIndex: this.traceIndex, nominalPowerWidth: r9, mutableTraceIndices: this.mutableBlockerTraceIndices, corridor: s7, maxRerouteLength: 10 }, this.connectionNameResolver), this.phase = "try-trace-inflation", true);
  }
  hasOnlyPushableTraceBlockers(e54, t4, n8) {
    const o10 = Math.max(0, t4 - 1), i8 = Math.min(e54.route.length - 2, t4 + 1), r9 = new Set;
    for (let t10 = o10;t10 <= i8; t10++) {
      const s7 = e54.route[t10], a9 = e54.route[t10 + 1];
      if (!bte(s7) || !bte(a9) || s7.layer !== a9.layer)
        continue;
      const c5 = { start: s7, end: a9, layer: s7.layer, width: n8, connectionNames: this.getTraceConnectionNames(e54), ignoreTraceIndex: this.traceIndex, ignoreRouteRange: { start: o10, end: i8 + 1 }, obstacleClearance: this.getDesiredPadClearance(n8) }, l5 = this.obstacleIndex.findCollisions(c5);
      if (l5.length === 0 && this.obstacleIndex.collides(c5))
        return false;
      for (const e60 of l5) {
        if (e60.kind !== "trace" || e60.traceIndex === undefined)
          return false;
        const t11 = this.traces[e60.traceIndex];
        if (!t11)
          return false;
        const o11 = this.findConnectionForTrace(t11);
        if (!o11 || (o11.nominalTraceWidth ?? o11.width ?? this.inputProblem.nominalTraceWidth ?? this.inputProblem.minTraceWidth) >= n8 - L7)
          return false;
        r9.add(e60.traceIndex);
      }
    }
    return r9.size > 0 && r9.size <= 2;
  }
  findBestPushableInflationWidth(e54, t4, n8) {
    const o10 = this.nominalTraceWidth >= 0.5 ? 0.05 : 0.0125;
    for (let i8 = this.nominalTraceWidth;i8 > n8 + L7; i8 -= o10) {
      const n10 = Number(i8.toFixed(6));
      if (this.hasOnlyPushableTraceBlockers(e54, t4, n10))
        return n10;
    }
    return null;
  }
  stepActiveInflationSolver() {
    const e54 = this.activeSubSolver;
    if (e54.step(), e54.solved || e54.failed) {
      if (e54.solved) {
        const t4 = e54.getOutput(), n8 = t4 && this.sameNetContactsArePreserved(this.traces[t4.pushedTraceIndex].route, t4.traces[t4.pushedTraceIndex].route, this.getTraceConnectionNames(this.traces[t4.pushedTraceIndex]), t4.pushedTraceIndex);
        if (t4 && n8) {
          if (this.traces = t4.traces, this.pushedTraceCount++, this.expansionPushedTraceIndices.add(t4.pushedTraceIndex), t4.strategy === "elastic" && this.elasticPushedTraceCount++, this.activeSubSolver = null, this.activeInflationKey = null, this.activeInflationWidth = null, this.rebuildObstacleIndex(), this.pendingLayerOutput) {
            if (!this.layerRouteReplacementCollides(this.pendingLayerOutput, false) && this.layerRoutePreservesSameNetContacts(this.pendingLayerOutput))
              return void this.applyLayerRoute(this.pendingLayerOutput);
            if (this.startPendingLayerInflation())
              return;
            return this.pendingLayerOutput = null, this.pendingLayerPushCount = 0, this.layerAttempt && this.layerAttempt.offsetCursor++, void (this.phase = "try-layer-candidate");
          }
          return void (this.phase = "evaluate-segment");
        }
        t4 && !n8 && this.sameNetContactRejectionCount++;
      }
      if (this.retainFailedSubSolver(e54), this.activeInflationKey && this.inflationAttemptsBySegment.set(this.activeInflationKey, 2), this.activeInflationKey = null, this.activeInflationWidth = null, this.activeSubSolver = null, this.pendingLayerOutput)
        return this.pendingLayerOutput = null, this.pendingLayerPushCount = 0, this.layerAttempt && this.layerAttempt.offsetCursor++, void (this.phase = "try-layer-candidate");
      this.phase = "evaluate-segment";
    }
  }
  getLocalInflationCorridor(e54, t4, n8) {
    const o10 = e54.route[t4], i8 = e54.route[t4 + 1];
    if (!bte(o10) || !bte(i8) || o10.layer !== i8.layer)
      return [];
    const r9 = j7(4 * n8, 2, 4), s7 = r9 / 2;
    let a9 = t4, c5 = 0;
    for (;a9 > 0; ) {
      const t10 = e54.route[a9 - 1], n10 = e54.route[a9];
      if (!bte(t10) || !bte(n10) || t10.layer !== n10.layer)
        break;
      const o11 = z7(t10, n10);
      if (c5 + o11 > s7 + L7)
        break;
      c5 += o11, a9--;
    }
    let l5 = t4 + 1, h5 = 0;
    for (;l5 < e54.route.length - 1; ) {
      const t10 = e54.route[l5], n10 = e54.route[l5 + 1];
      if (!bte(t10) || !bte(n10) || t10.layer !== n10.layer)
        break;
      const o11 = z7(t10, n10);
      if (h5 + o11 > s7 + L7)
        break;
      h5 += o11, l5++;
    }
    let d9 = r9 - c5 - h5;
    for (;d9 > L7 && a9 > 0; ) {
      const t10 = e54.route[a9 - 1], n10 = e54.route[a9];
      if (!bte(t10) || !bte(n10) || t10.layer !== n10.layer)
        break;
      const o11 = z7(t10, n10);
      if (o11 > d9 + L7)
        break;
      d9 -= o11, a9--;
    }
    for (;d9 > L7 && l5 < e54.route.length - 1; ) {
      const t10 = e54.route[l5], n10 = e54.route[l5 + 1];
      if (!bte(t10) || !bte(n10) || t10.layer !== n10.layer)
        break;
      const o11 = z7(t10, n10);
      if (o11 > d9 + L7)
        break;
      d9 -= o11, l5++;
    }
    const u9 = [];
    for (let t10 = a9;t10 < l5; t10++) {
      const o11 = e54.route[t10], i9 = e54.route[t10 + 1];
      bte(o11) && bte(i9) && o11.layer === i9.layer && u9.push({ start: o11, end: i9, layer: o11.layer, width: n8 });
    }
    return u9;
  }
  applyGridRoute(e54) {
    const t4 = this.traces[this.traceIndex], n8 = this.currentIntervals[this.intervalCursor], o10 = this.createGridRouteReplacement(e54);
    t4.route.splice(n8.startIndex, n8.endIndex - n8.startIndex + 1, ...o10), this.reroutedSegmentCount++, this.routeSegmentIndex = n8.startIndex + o10.length - 1, this.currentIntervals = [], this.phase = "evaluate-segment";
  }
  createGridRouteReplacement(e54) {
    const t4 = this.traces[this.traceIndex], n8 = this.currentIntervals[this.intervalCursor], o10 = t4.route[n8.startIndex], i8 = t4.route[n8.endIndex], r9 = e54.points.map((t10) => ({ route_type: "wire", x: t10.x, y: t10.y, width: e54.traceWidth, layer: o10.layer }));
    return r9[0].width = Math.max(o10.width, e54.traceWidth), r9[r9.length - 1].width = Math.max(i8.width, e54.traceWidth), r9;
  }
  gridRoutePreservesSameNetContacts(e54) {
    const t4 = this.traces[this.traceIndex], n8 = this.currentIntervals[this.intervalCursor];
    return this.routeReplacementPreservesSameNetContacts(t4, n8, this.createGridRouteReplacement(e54));
  }
  routeReplacementPreservesSameNetContacts(e54, t4, n8) {
    const o10 = this.getTraceConnectionNames(e54), i8 = this.getSameNetContactIds(e54.route.slice(t4.startIndex, t4.endIndex + 1), o10, this.traceIndex), r9 = new Set([...this.getSameNetContactIds(e54.route.slice(0, t4.startIndex + 1), o10, this.traceIndex), ...this.getSameNetContactIds(e54.route.slice(t4.endIndex), o10, this.traceIndex)]), s7 = new Set([...i8].filter((e60) => !r9.has(e60)));
    if (s7.size === 0)
      return true;
    const a9 = this.getSameNetContactIds(n8, o10, this.traceIndex);
    return [...s7].every((e60) => a9.has(e60));
  }
  sameNetContactsArePreserved(e54, t4, n8, o10) {
    const i8 = this.getSameNetContactIds(e54, n8, o10);
    if (i8.size === 0)
      return true;
    const r9 = this.getSameNetContactIds(t4, n8, o10);
    return [...i8].every((e60) => r9.has(e60));
  }
  getSameNetContactIds(e54, t4, n8) {
    const o10 = new Set;
    for (let i8 = 0;i8 < e54.length; i8++) {
      const r9 = e54[i8];
      if (r9?.route_type === "via") {
        for (const e60 of this.getViaLayers(r9))
          for (const i9 of this.obstacleIndex.getSameNetCopperContactIds({ start: r9, end: r9, layer: e60, width: r9.via_diameter ?? 0.6, connectionNames: t4, ignoreTraceIndex: n8 }))
            o10.add(i9);
        continue;
      }
      const s7 = e54[i8 + 1];
      if (r9?.route_type === "wire" && s7?.route_type === "wire" && r9.layer === s7.layer)
        for (const e60 of this.obstacleIndex.getSameNetCopperContactIds({ start: r9, end: s7, layer: r9.layer, width: Math.min(r9.width, s7.width), connectionNames: t4, ignoreTraceIndex: n8 }))
          o10.add(e60);
    }
    return o10;
  }
  getViaLayers(e54) {
    const t4 = this.obstacleIndex.boardLayers.indexOf(e54.from_layer), n8 = this.obstacleIndex.boardLayers.indexOf(e54.to_layer);
    return t4 < 0 || n8 < 0 ? this.obstacleIndex.boardLayers : this.obstacleIndex.boardLayers.slice(Math.min(t4, n8), Math.max(t4, n8) + 1);
  }
  gridRouteReplacementCollides(e54) {
    const t4 = this.traces[this.traceIndex], n8 = this.currentIntervals[this.intervalCursor], o10 = t4.route[n8.startIndex], i8 = t4.route[n8.endIndex], r9 = this.getTraceConnectionNames(t4);
    for (let s7 = 0;s7 < e54.points.length - 1; s7++) {
      const a9 = Math.max(e54.traceWidth, s7 === 0 ? o10.width : 0, s7 === e54.points.length - 2 ? i8.width : 0);
      if (this.obstacleIndex.collides({ start: e54.points[s7], end: e54.points[s7 + 1], layer: o10.layer, width: a9, connectionNames: r9, ignoreTraceIndex: this.traceIndex, ignoreRouteRange: { start: Math.max(0, n8.startIndex - 1), end: Math.min(t4.route.length - 1, n8.endIndex + 1) }, obstacleClearance: this.getDesiredPadClearance(a9) }))
        return true;
    }
    return false;
  }
  gridRouteBoundaryCollides(e54) {
    const t4 = this.traces[this.traceIndex], n8 = this.currentIntervals[this.intervalCursor], o10 = this.getTraceConnectionNames(t4), i8 = [{ startIndex: n8.startIndex - 1, endIndex: n8.startIndex }, { startIndex: n8.endIndex, endIndex: n8.endIndex + 1 }];
    for (const n10 of i8) {
      const i9 = t4.route[n10.startIndex], r9 = t4.route[n10.endIndex];
      if (bte(i9) && bte(r9) && i9.layer === r9.layer && this.obstacleIndex.collides({ start: i9, end: r9, layer: i9.layer, width: Math.max(i9.width, r9.width, e54.traceWidth), connectionNames: o10, ignoreTraceIndex: this.traceIndex, ignoreRouteRange: { start: n10.startIndex, end: n10.endIndex }, obstacleClearance: this.getDesiredPadClearance(Math.max(i9.width, r9.width, e54.traceWidth)) }))
        return true;
    }
    return false;
  }
  canExpandSegmentAndEndpoints(e54, t4, n8, o10 = this.nominalTraceWidth) {
    const i8 = Math.max(0, t4 - 1), r9 = Math.min(e54.route.length - 2, t4 + 1);
    for (let s7 = i8;s7 <= r9; s7++) {
      const a9 = e54.route[s7], c5 = e54.route[s7 + 1];
      if (!bte(a9) || !bte(c5) || a9.layer !== c5.layer)
        continue;
      const l5 = s7 <= t4 + 1 && s7 + 1 >= t4, h5 = Math.max(a9.width, c5.width, l5 ? o10 : 0);
      if (this.obstacleIndex.collides({ start: a9, end: c5, layer: a9.layer, width: h5, connectionNames: n8, ignoreTraceIndex: this.traceIndex, ignoreRouteRange: { start: i8, end: r9 + 1 }, obstacleClearance: this.getDesiredPadClearance(h5) }))
        return false;
    }
    return true;
  }
  findMaximumSafeInPlaceWidth(e54, t4, n8) {
    const o10 = e54.route[t4], i8 = e54.route[t4 + 1];
    if (!bte(o10) || !bte(i8))
      return 0;
    const r9 = Math.min(o10.width, i8.width);
    if (this.probeInPlaceWidth(e54, t4, n8, this.nominalTraceWidth))
      return this.nominalTraceWidth;
    let s7 = r9, a9 = this.nominalTraceWidth;
    for (let o11 = 0;o11 < 7; o11++) {
      const o12 = (s7 + a9) / 2;
      if (o12 <= s7 + L7)
        break;
      this.probeInPlaceWidth(e54, t4, n8, o12) ? s7 = o12 : a9 = o12;
    }
    const c5 = this.nominalTraceWidth >= 0.5 ? 0.025 : 0.0125, l5 = Math.max(r9, Math.floor((s7 + L7) / c5) * c5);
    return l5 > r9 + L7 && this.probeInPlaceWidth(e54, t4, n8, l5) ? l5 : r9;
  }
  probeInPlaceWidth(e54, t4, n8, o10) {
    return this.inPlaceWidthProbeCount++, this.canExpandSegmentAndEndpoints(e54, t4, n8, o10);
  }
  maximizeGridRouteWidth(e54) {
    if (e54.traceWidth >= this.nominalTraceWidth - L7)
      return e54;
    let t4 = e54.traceWidth, n8 = this.nominalTraceWidth;
    for (let o11 = 0;o11 < 7; o11++) {
      const o12 = (t4 + n8) / 2, i9 = { ...e54, traceWidth: o12 };
      this.gridRouteReplacementCollides(i9) || this.gridRouteBoundaryCollides(i9) ? n8 = o12 : t4 = o12;
    }
    const o10 = this.nominalTraceWidth >= 0.5 ? 0.025 : 0.0125, i8 = Math.max(e54.traceWidth, Math.floor((t4 + L7) / o10) * o10);
    if (i8 > e54.traceWidth + L7) {
      const t10 = { ...e54, traceWidth: i8 };
      if (!this.gridRouteReplacementCollides(t10) && !this.gridRouteBoundaryCollides(t10))
        return this.pathWidthUpgradeCount++, t10;
    }
    return e54;
  }
  getExponentialIntervalCandidates(e54, t4, n8) {
    const o10 = this.getExponentialIndices(e54, t4, -1, n8, 5), i8 = this.getExponentialIndices(e54, t4, 1, n8, 10).filter((e60) => e60 > t4), r9 = [];
    for (const t10 of o10)
      for (const n10 of i8) {
        const o11 = this.getRouteIntervalLength(e54, t10, n10);
        o11 > 10.000001 || r9.push({ startIndex: t10, endIndex: n10, routeLength: o11 });
      }
    return r9.sort((e60, t10) => e60.routeLength - t10.routeLength).filter((e60, t10, n10) => n10.findIndex((t11) => t11.startIndex === e60.startIndex && t11.endIndex === e60.endIndex) === t10).slice(0, 10).map(({ startIndex: e60, endIndex: t10 }) => ({ startIndex: e60, endIndex: t10 }));
  }
  getExponentialIndices(e54, t4, n8, o10, i8) {
    const r9 = [t4];
    let s7 = 0, a9 = Math.max(o10, 0.3), c5 = t4, l5 = t4;
    for (;; ) {
      const t10 = c5 + n8;
      if (t10 < 0 || t10 >= e54.route.length)
        break;
      const o11 = e54.route[c5], h5 = e54.route[t10];
      if (!bte(o11) || !bte(h5) || o11.layer !== h5.layer)
        break;
      const d9 = z7(o11, h5);
      if (s7 + d9 > i8 + L7)
        break;
      s7 += d9, c5 = t10, l5 = t10, s7 + L7 >= a9 && (r9.push(t10), a9 *= 2);
    }
    return r9.includes(l5) || r9.push(l5), r9;
  }
  getRouteIntervalLength(e54, t4, n8) {
    let o10 = 0;
    for (let i8 = t4;i8 < n8; i8++) {
      const t10 = e54.route[i8], n10 = e54.route[i8 + 1];
      if (!bte(t10) || !bte(n10) || t10.layer !== n10.layer)
        return Number.POSITIVE_INFINITY;
      o10 += z7(t10, n10);
    }
    return o10;
  }
  getCandidateWidths(e54) {
    const t4 = this.inputProblem.minTraceWidth;
    return yte([e54, 0.875 * e54, 0.75 * e54, 0.625 * e54, 0.5 * e54, 0.375 * e54, 0.25 * e54, t4]).filter((e60) => e60 >= t4 - L7);
  }
  getGridResolutions(e54) {
    return yte([Math.max(0.1, Math.min(0.5, e54 / 2)), Math.max(0.1, Math.min(0.25, e54 / 3))]);
  }
  resolveNominalTraceWidth(e54) {
    const t4 = this.findConnectionForTrace(e54);
    return Math.max(t4?.nominalTraceWidth ?? t4?.width ?? this.inputProblem.nominalTraceWidth ?? this.inputProblem.minTraceWidth, this.inputProblem.minTraceWidth);
  }
  getDesiredPadClearance(e54 = this.nominalTraceWidth) {
    const t4 = Math.max(this.inputProblem.defaultObstacleMargin ?? 0, this.inputProblem.minTraceToPadEdgeClearance ?? 0, 0.1);
    return e54 < 0.499999 || this.phase !== "cleanup" ? t4 : Math.max(t4, this.options.powerTraceToPadClearance ?? e54 / 2);
  }
  findConnectionForTrace(e54) {
    const t4 = this.connectionByTraceId.get(e54.pcb_trace_id);
    if (t4 !== undefined)
      return t4 ?? undefined;
    const n8 = this.getTraceConnectionNames(e54), o10 = this.inputProblem.connections.find((e60) => this.connectionMatchesTrace(e60, n8)) ?? null;
    return this.connectionByTraceId.set(e54.pcb_trace_id, o10), o10 ?? undefined;
  }
  getOwnedTraceIndices() {
    return [...this.selectedOwnedTraceIndices];
  }
  connectionMatchesTrace(e54, t4) {
    return [e54.name, e54.source_trace_id, e54.rootConnectionName, e54.netConnectionName, ...e54.mergedConnectionNames ?? []].filter((e60) => Boolean(e60)).some((e60) => t4.includes(e60));
  }
  getTraceConnectionNames(e54) {
    return [e54.connection_name, e54.source_trace_id, e54.rootConnectionName, ...e54.mergedConnectionNames ?? []].filter((e60) => Boolean(e60));
  }
  traceMeetsNominalWidth(e54, t4) {
    return e54.route.every((e60) => e60.route_type !== "wire" || e60.width >= t4 - L7);
  }
  findNextUnderWidthSegment(e54, t4, n8) {
    for (let o10 = t4;o10 < e54.route.length - 1; o10++) {
      const t10 = e54.route[o10], i8 = e54.route[o10 + 1];
      if (bte(t10) && bte(i8) && t10.layer === i8.layer && (t10.width < n8 - L7 || i8.width < n8 - L7))
        return o10;
    }
    return -1;
  }
  getMutatedImmutableTraceIds(e54) {
    return this.immutableTraceIndices.flatMap((t4) => {
      const n8 = e54[t4];
      return JSON.stringify(n8) === this.initialImmutableTraceSignatures.get(t4) ? [] : [n8?.pcb_trace_id ?? this.traces[t4]?.pcb_trace_id ?? String(t4)];
    });
  }
  getImmutableViaViolationSignatures(e54) {
    const t4 = new Set;
    if (this.immutableTraceIndices.length === 0)
      return t4;
    const n8 = new D7(this.inputProblem, e54), o10 = new Cee(this.inputProblem, e54, undefined, [], n8);
    for (const n10 of this.immutableTraceIndices) {
      const i8 = e54[n10];
      if (!i8)
        continue;
      const r9 = [i8.pcb_trace_id, i8.connection_name, i8.source_trace_id, i8.rootConnectionName, ...i8.mergedConnectionNames ?? [], ...i8.connectsTo ?? []].filter((e60) => Boolean(e60));
      for (let e60 = 0;e60 < i8.route.length; e60++) {
        const s7 = i8.route[e60];
        if (s7?.route_type !== "via")
          continue;
        const a9 = `${i8.pcb_trace_id}:${e60}`, c5 = o10.getViaViolationSignatures({ point: s7, layers: o10.boardLayers, padDiameter: s7.via_diameter ?? this.inputProblem.min_via_pad_diameter ?? this.inputProblem.minViaPadDiameter ?? this.inputProblem.minViaDiameter ?? 0.6, holeDiameter: s7.via_hole_diameter ?? o10.defaultViaHoleDiameter, connectionNames: r9, ignoreTraceIndex: n10, ignoreRouteRange: { start: e60, end: e60 }, blockSameNetObstacles: true, sameNetObstacleClearance: 0 });
        for (const e61 of c5)
          t4.add(`${a9}|${e61}`);
      }
    }
    return t4;
  }
  countViolatingImmutableVias(e54) {
    return new Set([...e54].map((e60) => e60.split("|")[0])).size;
  }
  acceptConnectivityCheckpoint(e54, t4) {
    this.connectivityValidationCount++;
    let n8 = false, o10 = false;
    try {
      const t10 = this.connectivityInvariant.validate(e54), i8 = this.getMutatedImmutableTraceIds(e54), r9 = this.getImmutableViaViolationSignatures(e54), s7 = [...r9].filter((e60) => !this.lastSafeImmutableViaViolationSignatures.has(e60)), a9 = s7.length > 0;
      if (n8 = !t10.safe, o10 = i8.length > 0 || a9, this.connectivityValidationError ??= t10.validationError ?? null, !n8 && !o10)
        return this.traces = structuredClone(e54), this.lastConnectivitySafeTraces = structuredClone(e54), this.remainingImmutableViaViolationCount = this.countViolatingImmutableVias(r9), this.remainingImmutableViaViolationPairCount = r9.size, this.lastSafeImmutableViaViolationSignatures = r9, this.connectivityInvariant = new ote(this.inputProblem, this.lastConnectivitySafeTraces), true;
      this.immutableTraceMutationIds = [...new Set([...this.immutableTraceMutationIds, ...i8])], a9 && (this.immutableViaViolationRollbackCount++, this.attemptedImmutableViaViolationCount = this.countViolatingImmutableVias(r9), this.attemptedImmutableViaViolationPairCount = r9.size, this.immutableViaViolationRegressionIds = [...new Set([...this.immutableViaViolationRegressionIds, ...s7])]), this.connectivityRegressionEndpointIds = [...new Set([...this.connectivityRegressionEndpointIds, ...t10.regressions.flatMap((e60) => e60.baselineEndpointLabels)])];
    } catch (e60) {
      n8 = true, this.connectivityValidationError = e60 instanceof Error ? e60.message : String(e60);
    }
    return n8 && (this.connectivityRollbackCount++, this.connectivityRollbackPhases.includes(t4) || this.connectivityRollbackPhases.push(t4)), o10 && (this.immutableSafetyRollbackCount++, this.immutableSafetyRollbackPhases.includes(t4) || this.immutableSafetyRollbackPhases.push(t4)), t4 === "expansion" ? n8 ? this.rollbackConnectivityRegressedExpansion() : this.rollbackImmutableUnsafeExpansion() : this.restoreLastConnectivitySafeTraces(), this.remainingImmutableViaViolationCount = this.countViolatingImmutableVias(this.lastSafeImmutableViaViolationSignatures), this.remainingImmutableViaViolationPairCount = this.lastSafeImmutableViaViolationSignatures.size, false;
  }
  rebuildObstacleIndex() {
    this.obstacleIndex = new Cee(this.inputProblem, this.traces, this.traceIndex, [], this.connectionNameResolver);
  }
  retainFailedSubSolver(e54) {
    this.failedSubSolverCount++, this.failedSubSolvers ??= [], this.failedSubSolvers.length < 16 ? this.failedSubSolvers.push(e54) : this.failedSubSolvers[15] = e54;
  }
  tryFinalAcceptance() {
    this.finalAcceptanceUsed = true;
    let e54 = false;
    this.activeSubSolver instanceof dte ? (this.activeSubSolver.tryFinalAcceptance(), this.adoptCleanupOutput(this.activeSubSolver), e54 = true) : this.activeSubSolver instanceof mte && (this.activeSubSolver.tryFinalAcceptance(), this.adoptClearanceRepairOutput(this.activeSubSolver), e54 = true), e54 || this.phase === "cleanup" || this.phase === "repair-trace-clearance" || this.phase === "complete" || this.discardInFlightExpansion(), this.activeSubSolver = null, this.pendingLayerOutput = null, this.pendingLayerPushCount = 0, this.activeInflationKey = null, this.activeInflationWidth = null, this.layerAttempt = null, this.acceptConnectivityCheckpoint(this.traces, "final"), this.traceIndex = this.traces.length, this.phase = "complete", this.rebuildObstacleIndex(), this.progress = 1, this.solved = true, this.stats = this.createStats();
  }
  createStats() {
    return this.statsMaxIterations = this.MAX_ITERATIONS, { phase: this.phase, pass: this.passIndex + 1, completedPassCount: this.completedPassCount, lastNormalizedWidthDeficitGain: this.lastNormalizedWidthDeficitGain, normalizedWidthDeficitGainByPass: [...this.normalizedWidthDeficitGainByPass], plateauReached: this.plateauReached, traceIndex: this.traceIndex, traceCount: this.traces.length, selectedTraceCount: this.traceOrder.length, routeSegmentIndex: this.routeSegmentIndex, nominalTraceWidth: this.nominalTraceWidth, intervalCursor: this.intervalCursor, intervalCount: this.currentIntervals.length, candidateWidth: this.candidateWidths[this.widthCursor], gridSize: this.gridResolutions[this.resolutionCursor], gridOffsetVariant: this.offsetCursor, keptTraceCount: this.keptTraceCount, recreatedTraceCount: this.recreatedTraceCount, expandedSegmentCount: this.expandedSegmentCount, intermediateExpandedSegmentCount: this.intermediateExpandedSegmentCount, pathWidthUpgradeCount: this.pathWidthUpgradeCount, inPlaceWidthProbeCount: this.inPlaceWidthProbeCount, reroutedSegmentCount: this.reroutedSegmentCount, unresolvedSegmentCount: this.unresolvedSegmentCount, attemptedGridCount: this.attemptedGridCount, attemptedLayerGridCount: this.attemptedLayerGridCount, attemptedInflationCount: this.attemptedInflationCount, activeInflationWidth: this.activeInflationWidth, pushedTraceCount: this.pushedTraceCount, elasticPushedTraceCount: this.elasticPushedTraceCount, layerReroutedTraceCount: this.layerReroutedTraceCount, insertedViaCount: this.insertedViaCount, neckedLayerSegmentCount: this.neckedLayerSegmentCount, removedViaPairCount: this.removedViaPairCount, removedViaCount: this.removedViaCount, simplifiedPathCount: this.simplifiedPathCount, normalizedSegmentCount: this.normalizedSegmentCount, cleanupClearanceShoveCount: this.cleanupClearanceShoveCount, relocatedViaCount: this.relocatedViaCount, unresolvedViaCount: this.unresolvedViaCount, initialImmutableViaViolationCount: this.initialImmutableViaViolationCount, remainingImmutableViaViolationCount: this.remainingImmutableViaViolationCount, initialImmutableViaViolationPairCount: this.initialImmutableViaViolationPairCount, remainingImmutableViaViolationPairCount: this.remainingImmutableViaViolationPairCount, skippedImmutableViaRepairCount: this.remainingImmutableViaViolationCount, immutableViaViolationRollbackCount: this.immutableViaViolationRollbackCount, attemptedImmutableViaViolationCount: this.attemptedImmutableViaViolationCount, attemptedImmutableViaViolationPairCount: this.attemptedImmutableViaViolationPairCount, immutableViaViolationRegressionIds: [...this.immutableViaViolationRegressionIds], immutableTraceMutationIds: [...this.immutableTraceMutationIds], padClearanceRerouteCount: this.padClearanceRerouteCount, unresolvedPadClearanceCount: this.unresolvedPadClearanceCount, repairedTraceClearanceSegmentCount: this.repairedTraceClearanceSegmentCount, repairedPadNeckSegmentCount: this.repairedPadNeckSegmentCount, unresolvedTraceClearanceSegmentCount: this.unresolvedTraceClearanceSegmentCount, sameNetContactRejectionCount: this.sameNetContactRejectionCount, connectivityValidationCount: this.connectivityValidationCount, connectivityRollbackCount: this.connectivityRollbackCount, connectivityRollbackPhases: [...this.connectivityRollbackPhases], immutableSafetyRollbackCount: this.immutableSafetyRollbackCount, immutableSafetyRollbackPhases: [...this.immutableSafetyRollbackPhases], connectivityRegressionEndpointIds: [...this.connectivityRegressionEndpointIds], connectivityValidationError: this.connectivityValidationError, connectivityRollbackMutationStats: this.connectivityRollbackMutationStats === null ? null : { ...this.connectivityRollbackMutationStats }, immutableSafetyRollbackMutationStats: this.immutableSafetyRollbackMutationStats === null ? null : { ...this.immutableSafetyRollbackMutationStats }, expansionPushedTraceIndices: [...this.expansionPushedTraceIndices], cleanupMutatedTraceIndices: [...this.cleanupMutatedTraceIndices], discardedExpansionMutationStats: this.discardedExpansionMutationStats === null ? null : { ...this.discardedExpansionMutationStats }, initialPadClearanceViolationCount: this.initialPadClearanceViolationCount, remainingPadClearanceViolationCount: this.remainingPadClearanceViolationCount, initialPadClearanceViolationCountByClearance: { ...this.initialPadClearanceViolationCountByClearance }, remainingPadClearanceViolationCountByClearance: { ...this.remainingPadClearanceViolationCountByClearance }, budgetLimitedExpansion: this.budgetLimitedExpansion, finalAcceptanceUsed: this.finalAcceptanceUsed, cleanupCompleted: this.cleanupCompleted, clearanceRepairCompleted: this.clearanceRepairCompleted, cleanupBestEffortAccepted: this.cleanupBestEffortAccepted, clearanceRepairBestEffortAccepted: this.clearanceRepairBestEffortAccepted, cleanupStatus: this.connectivityRollbackPhases.includes("cleanup") ? "connectivity_rollback" : this.immutableSafetyRollbackPhases.includes("cleanup") ? "immutable_safety_rollback" : this.cleanupBestEffortAccepted ? "budget_limited" : this.cleanupCompleted ? "completed" : this.phase === "cleanup" ? "in_progress" : "not_started", clearanceRepairStatus: this.connectivityRollbackPhases.includes("clearance-repair") ? "connectivity_rollback" : this.immutableSafetyRollbackPhases.includes("clearance-repair") ? "immutable_safety_rollback" : this.clearanceRepairBestEffortAccepted ? "budget_limited" : this.clearanceRepairCompleted ? "completed" : this.phase === "repair-trace-clearance" ? "in_progress" : "not_started", cleanupIterationBudget: this.cleanupIterationBudget, clearanceRepairIterationBudget: this.clearanceRepairIterationBudget, completionReason: this.phase === "complete" || this.solved ? this.connectivityRollbackCount > 0 ? "connectivity_rollback" : this.immutableSafetyRollbackCount > 0 ? "immutable_safety_rollback" : this.connectivityValidationError ? "connectivity_validation_unavailable" : this.finalAcceptanceUsed ? "total_iteration_budget" : this.budgetLimitedExpansion ? "expansion_budget" : this.cleanupBestEffortAccepted ? "cleanup_budget" : this.clearanceRepairBestEffortAccepted ? "clearance_repair_budget" : this.remainingImmutableViaViolationCount > 0 ? "immutable_via_violations_preserved" : "completed" : null, resultStatus: this.finalAcceptanceUsed || this.budgetLimitedExpansion || this.cleanupBestEffortAccepted || this.clearanceRepairBestEffortAccepted || this.connectivityRollbackCount > 0 || this.immutableSafetyRollbackCount > 0 || this.connectivityValidationError !== null || this.remainingImmutableViaViolationCount > 0 ? "best_effort" : "complete", failedSubSolverCount: this.failedSubSolverCount, retainedFailedSubSolverCount: this.failedSubSolvers?.length ?? 0, expansionIterationBudget: this.getExpansionIterationBudget(), finalizationIterationReserve: this.getFinalizationIterationReserve(), spatialIndexRectCount: this.obstacleIndex.items.length };
  }
  computeProgress() {
    return this.solved || this.phase === "complete" ? 1 : this.budgetLimitedExpansion ? 0.99 : this.traceOrder.length === 0 ? 1 : Math.min(0.99, (this.passIndex + Math.max(0, this.traceOrderCursor) / this.traceOrder.length) / this.maxPassCount);
  }
  getConstructorParams() {
    return [this.inputProblem, this.options];
  }
  getOutput() {
    return structuredClone(this.lastConnectivitySafeTraces);
  }
  visualize() {
    const e54 = [], t4 = [];
    for (let n8 = 0;n8 < this.traces.length; n8++) {
      const o10 = this.traces[n8], i8 = this.resolveNominalTraceWidth(o10);
      for (const e60 of o10.route)
        e60.route_type === "via" && t4.push({ center: e60, radius: (e60.via_diameter ?? 0.6) / 2, fill: "#d4a017", stroke: "#7a5700" });
      for (let t10 = 0;t10 < o10.route.length - 1; t10++) {
        const r9 = o10.route[t10], s7 = o10.route[t10 + 1];
        if (!bte(r9) || !bte(s7) || r9.layer !== s7.layer)
          continue;
        const a9 = n8 === this.traceIndex && t10 === this.routeSegmentIndex, c5 = r9.width >= i8 - L7 && s7.width >= i8 - L7, l5 = r9.layer === "bottom";
        e54.push({ points: [r9, s7], strokeColor: a9 ? "#ff8c00" : c5 ? l5 ? "#2468c7" : "#169c45" : l5 ? "#8b4bb8" : "#cc3344", strokeWidth: Math.max(r9.width, s7.width) });
      }
    }
    return { coordinateSystem: "cartesian", title: `Power trace expander: ${this.phase}`, lines: e54, points: [], circles: t4, rects: this.obstacleIndex.items.filter((e60) => e60.kind === "obstacle").slice(0, 2000).map((e60) => ({ center: { x: (e60.minX + e60.maxX) / 2, y: (e60.minY + e60.maxY) / 2 }, width: e60.maxX - e60.minX, height: e60.maxY - e60.minY, fill: "rgba(80,80,80,0.12)", stroke: "rgba(80,80,80,0.35)" })), texts: [] };
  }
};
var vte = (e54) => e54.minViaEdgeToPadEdgeClearance === undefined ? e54.minPadEdgeToPadEdgeClearance : Math.max(e54.minViaEdgeToPadEdgeClearance, e54.minPadEdgeToPadEdgeClearance ?? 0);
var Ite = class extends ni {
  constructor(e54, t4 = {}) {
    if (super(), this.inputSrj = e54, this.options = t4, this.powerTraceExpanderSolver = new xte({ ...e54, minViaEdgeToPadEdgeClearance: vte(e54) }, t4), t4.onlyConnectionNames?.length === 0)
      return this.MAX_ITERATIONS = 1, this.progress = 1, this.solved = true, void (this.stats = { selectedTraceCount: 0, bypassed: true });
    this.MAX_ITERATIONS = this.powerTraceExpanderSolver.MAX_ITERATIONS + 1;
  }
  powerTraceExpanderSolver;
  _step() {
    const e54 = this.powerTraceExpanderSolver;
    if (e54.step(), this.progress = e54.progress, this.stats = e54.stats, e54.failed)
      return this.error = e54.error, void (this.failed = true);
    e54.solved && (this.solved = true);
  }
  getConstructorParams() {
    return [this.inputSrj, this.options];
  }
  getOutput() {
    if (!this.solved)
      throw new Error("Cannot get power trace expansion output before solving");
    return this.powerTraceExpanderSolver.getOutput();
  }
  visualize() {
    return Wo({ ...this.inputSrj, traces: this.getOutput() }, { traceColorMode: "layer" });
  }
};
var Ste = ({ connections: e54, originalConnections: t4, layerCount: n8, obstacles: o10, defaultViaHoleDiameter: i8, connMap: r9 }) => {
  const s7 = new Map;
  for (const e60 of t4)
    s7.has(e60.name) || s7.set(e60.name, e60.__netConnectionName);
  const a9 = e54.map((e60) => {
    if (e60.pointsToConnect.length !== 2)
      throw new Error(`Expected Pipeline7 output connection "${e60.name}" to have two points, got ${e60.pointsToConnect.length}`);
    const [t10, n10] = e60.pointsToConnect;
    return { connection: e60, connectsTo: [t10?.pointId, n10?.pointId].filter((e61) => Boolean(e61)), outputConnectionName: e60.__netConnectionName ?? s7.get(e60.name) ?? e60.__rootConnectionNames?.[0] ?? e60.name };
  }), c5 = o10.filter((e60) => (e60.__zLayers?.length ?? e60.layers?.length ?? 0) > 1), l5 = new Map, h5 = (e60) => {
    let t10 = l5.get(e60.connectionName);
    t10 || (t10 = new Map, l5.set(e60.connectionName, t10));
    const n10 = t10.get(e60.rootConnectionName);
    if (n10)
      return n10;
    const o11 = c5.filter((t11) => xo(t11, e60, r9));
    return t10.set(e60.rootConnectionName, o11), o11;
  };
  return (e60) => {
    const t10 = [], o11 = new Map;
    for (const t11 of e60) {
      const e61 = o11.get(t11.connectionName);
      e61 ? e61.push(t11) : o11.set(t11.connectionName, [t11]);
    }
    for (const { connection: e61, connectsTo: s9, outputConnectionName: c9 } of a9) {
      const a10 = o11.get(e61.name) ?? [];
      for (let o12 = 0;o12 < a10.length; o12 += 1) {
        const l10 = a10[o12];
        t10.push({ type: "pcb_trace", pcb_trace_id: `${e61.name}_${o12}`, connection_name: c9, connectsTo: s9, route: Ro(l10, n8, { connectionPoints: e61.pointsToConnect, defaultViaHoleDiameter: i8, connectedMultilayerObstacles: h5(l10), connMap: r9 }) });
      }
    }
    return t10;
  };
};
var Cte = ({ connections: e54, originalConnections: t4, hdRoutes: n8, layerCount: o10, obstacles: i8, defaultViaHoleDiameter: r9, connMap: s7 }) => Ste({ connections: e54, originalConnections: t4, layerCount: o10, obstacles: i8, defaultViaHoleDiameter: r9, connMap: s7 })(n8);
var Pte = (e54) => {
  const t4 = Math.max(e54.minTraceWidth + 0.1, 2 * e54.minTraceWidth);
  return e54.connections.flatMap((n8) => (n8.nominalTraceWidth ?? e54.nominalTraceWidth ?? e54.minTraceWidth) + 0.000001 >= t4 ? [n8.name] : []);
};
var Mte = ({ hdRoutes: e54, connections: t4 }) => {
  const n8 = new Map(t4.map((e60) => [e60.name, e60]));
  return e54.map((e60) => {
    if (e60.route.length === 0)
      throw new Error(`Cannot lock PCB terminals for empty route "${e60.connectionName}"`);
    const t10 = n8.get(e60.connectionName);
    if (!t10)
      throw new Error(`Cannot lock PCB terminals: connection "${e60.connectionName}" was not found`);
    if (t10.pointsToConnect.length !== 2)
      throw new Error(`Cannot lock PCB terminals for "${e60.connectionName}": expected 2 connection points, found ${t10.pointsToConnect.length}`);
    const o10 = new Map;
    for (const n10 of t10.pointsToConnect)
      if (n10.pcb_port_id) {
        if (o10.has(n10.pcb_port_id))
          throw new Error(`Cannot lock duplicate PCB terminal "${n10.pcb_port_id}" for "${e60.connectionName}"`);
        o10.set(n10.pcb_port_id, n10);
      }
    if (o10.size === 0)
      return e60;
    const i8 = [e60.startPcbPortId, e60.endPcbPortId].filter((e61) => e61 !== undefined);
    if (i8.length === 0)
      return e60;
    if (new Set(i8).size !== i8.length || i8.some((e61) => !o10.has(e61)))
      throw new Error(`Cannot lock PCB terminals for "${e60.connectionName}": route endpoint IDs do not match connection terminal IDs`);
    const r9 = e60.startPcbPortId ? o10.get(e60.startPcbPortId) : undefined, s7 = e60.endPcbPortId ? o10.get(e60.endPcbPortId) : undefined, a9 = e60.route.map((t11, n10) => {
      if (n10 === 0 && r9)
        return { ...t11, x: r9.x, y: r9.y, pcb_port_id: r9.pcb_port_id };
      if (n10 === e60.route.length - 1 && s7)
        return { ...t11, x: s7.x, y: s7.y, pcb_port_id: s7.pcb_port_id };
      const o11 = { ...t11 };
      return delete o11.pcb_port_id, o11;
    });
    return { ...e60, route: a9 };
  });
};
var wte = ({ originalSrj: e54, newlyRoutedTraces: t4, currentPreloadedTraces: n8, expandedConnectionNames: o10, resolveConnectedTraceAliases: i8 = false }) => {
  const r9 = n8 ?? e54.traces ?? [], s7 = i8 ? Nte({ originalSrj: e54, newlyRoutedTraces: t4, preloadedTraces: r9, expandedConnectionNames: o10 }) : new Set(r9.filter((e60) => o10.includes(e60.connection_name))), a9 = r9.filter((e60) => !s7.has(e60)), c5 = new Set([...t4.map((e60) => e60.pcb_trace_id), ...a9.map((e60) => e60.pcb_trace_id)]), l5 = r9.filter((e60) => s7.has(e60)).map((e60) => {
    const t10 = e60.pcb_trace_id;
    let n10 = t10, o11 = 2;
    for (;c5.has(n10); )
      n10 = `${t10}_power_expansion_${o11++}`;
    return c5.add(n10), { ...e60, pcb_trace_id: n10, __replaces_pcb_trace_id: e60.__replaces_pcb_trace_id ?? e60.pcb_trace_id };
  });
  return { ...e54, traces: [...t4, ...l5], fixedTraces: a9 };
};
var Nte = ({ originalSrj: e54, newlyRoutedTraces: t4, preloadedTraces: n8, expandedConnectionNames: o10 }) => {
  const i8 = new Set(n8.map((e60) => e60.pcb_trace_id)), r9 = new Set([...i8, ...t4.map((e60) => e60.pcb_trace_id)]), s7 = t4.map((e60, t10) => {
    if (!i8.has(e60.pcb_trace_id))
      return e60;
    const n10 = `__pipeline7_new_trace_${t10}_${e60.pcb_trace_id}`;
    let o11 = n10, s9 = 2;
    for (;r9.has(o11); )
      o11 = `${n10}_${s9++}`;
    return r9.add(o11), { ...e60, pcb_trace_id: o11 };
  }), a9 = new D7({ ...e54, traces: [...s7, ...n8] }), c5 = new Set(a9.canonicalize([...o10]));
  return new Set(n8.filter((e60) => a9.canonicalize([e60.connection_name]).some((e61) => c5.has(e61))));
};
function Rte(e54) {
  return new Set((e54 ?? []).filter((e60) => e60._isComponentTopologyNode).map((e60) => e60.capacityMeshNodeId));
}
function Tte(e54, t4) {
  return e54.nodeIds.some((e60) => t4.has(e60));
}
function Ete({ sharedEdgeSegments: e54, componentCapacityMeshNodeIds: t4 }) {
  return e54.filter((e60) => !Tte(e60, t4));
}
function Ate(e54, t4, n8, o10 = {}) {
  return { solverName: e54, solverClass: t4, getConstructorParams: n8, onSolved: o10.onSolved };
}
var Ote = class extends ni {
  constructor(e54, t4 = {}) {
    super(), this.srj = e54, this.opts = t4;
    const n8 = V1(e54);
    this.originalSrj = n8, this.opts = { ...t4 };
    const o10 = this.opts;
    if (this.effort = o10.effort ?? 1, this.MAX_ITERATIONS = 1e8 * this.effort, this.maxNodeDimension = o10.maxNodeDimension ?? 16, this.maxNodeRatio = o10.maxNodeRatio ?? 6, this.minNodeArea = o10.minNodeArea ?? 0.1 ** 2, this.visualizationTraceColorMode = o10.visualizationTraceColorMode ?? "layer", this.setSimpleRouteJson(n8), o10.capacityDepth === undefined) {
      const e60 = this.srj.bounds.maxX - this.srj.bounds.minX, t10 = this.srj.bounds.maxY - this.srj.bounds.minY, n10 = Math.max(e60, t10), i8 = o10.targetMinCapacity ?? 0.5;
      o10.capacityDepth = Fz(n10, i8);
    }
    this.cacheProvider = o10.cacheProvider === undefined ? no() : o10.cacheProvider === null ? null : o10.cacheProvider, this.startTimeOfPhase = {}, this.endTimeOfPhase = {}, this.timeSpentOnPhase = {};
  }
  getSolverName() {
    return "AutoroutingPipelineSolver7_MultiGraph";
  }
  preprocessSimpleRouteJsonSolver;
  escapeViaLocationSolver;
  netToPointPairsSolver;
  componentTopologyGeneratorSolver;
  topologyPlanningSolver;
  topologyMergingSolver;
  globalTopologyGeneratorSolver;
  nodeDimensionSubdivisionSolver;
  nodeTargetMerger;
  edgeSolver;
  colorMap;
  highDensityRouteSolver;
  highDensityForceImproveSolver;
  highDensityRepairSolver;
  highDensityStitchSolver;
  globalDrcForceImproveSolver;
  exactGeometryDrcForceImproveSolver;
  singleLayerNodeMerger;
  strawSolver;
  deadEndSolver;
  traceSimplificationSolver;
  lengthMatchingPostProcessingSolver;
  powerTraceExpansionSolver;
  availableSegmentPointSolver;
  portPointPathingSolver;
  multiSectionPortPointOptimizer;
  uniformPortDistributionSolver;
  traceWidthSolver;
  necessaryCrampedPortPointSolver;
  componentDetectionSolver;
  viaDiameter;
  viaHoleDiameter;
  minTraceWidth;
  effort;
  maxNodeDimension;
  maxNodeRatio;
  minNodeArea;
  visualizationTraceColorMode;
  startTimeOfPhase;
  endTimeOfPhase;
  timeSpentOnPhase;
  activeSubSolver = null;
  connMap;
  srjWithEscapeViaLocations;
  srjWithPointPairs;
  originalSrj;
  capacityNodes = null;
  capacityEdges = null;
  sharedEdgeSegmentsWithNecessaryCrampedPortPoints;
  highDensityNodePortPoints;
  cacheProvider = null;
  pipelineDef = [Ate("preprocessSimpleRouteJsonSolver", U1, (e54) => [e54.originalSrj, { traceColorMode: e54.visualizationTraceColorMode }], { onSolved: (e54) => {
    e54.setSimpleRouteJson(e54.preprocessSimpleRouteJsonSolver.getOutputSimpleRouteJson());
  } }), Ate("componentDetectionSolver", r7, (e54) => [{ inputSrj: e54.srj }]), Ate("escapeViaLocationSolver", uK, (e54) => [e54.srj, { viaDiameter: e54.viaDiameter, minTraceWidth: e54.minTraceWidth, obstacleMargin: e54.srj.defaultObstacleMargin ?? 0.15 }], { onSolved: (e54) => {
    e54.srjWithEscapeViaLocations = e54.escapeViaLocationSolver?.getOutputSimpleRouteJson();
  } }), Ate("netToPointPairsSolver", pB, (e54) => {
    const t4 = e54.srjWithEscapeViaLocations ?? e54.srj;
    return [t4, e54.colorMap, ti(t4)];
  }, { onSolved: (e54) => {
    e54.srjWithPointPairs = e54.netToPointPairsSolver?.getNewSimpleRouteJson(), e54.colorMap = Eo(e54.srjWithPointPairs, e54.connMap), e54.connMap = ei(e54.srjWithPointPairs);
  } }), Ate("topologyPlanningSolver", N7, (e54) => [{ inputSrj: e54.srjWithPointPairs, componentDetectionOutput: e54.componentDetectionSolver.getOutput(), viaDiameter: e54.viaDiameter, obstacleMargin: e54.srj.defaultObstacleMargin ?? 0.15 }], { onSolved: (e54) => {
    e54.topologyPlanningSolver.getOutput();
    e54.globalTopologyGeneratorSolver = e54.topologyPlanningSolver.globalTopologySolver, e54.componentTopologyGeneratorSolver = new E7(e54.topologyPlanningSolver);
  } }), Ate("topologyMergingSolver", C7, (e54) => {
    const t4 = e54.topologyPlanningSolver.getOutput();
    return [{ layerCount: e54.srj.layerCount, allowBlindAndBuriedVias: e54.srj.allowBlindAndBuriedVias, nodeGroups: [{ groupId: "global", nodes: t4.globalMeshNodes, isComponent: false }, ...t4.componentMeshNodes.map((e60, t10) => ({ groupId: `component-${t10}`, nodes: e60, isComponent: true }))] }];
  }, { onSolved: (e54) => {
    e54.capacityNodes = e54.topologyMergingSolver.getOutput();
  } }), Ate("nodeDimensionSubdivisionSolver", MZ, (e54) => [e54.capacityNodes, e54.maxNodeDimension, e54.maxNodeRatio, e54.minNodeArea], { onSolved: (e54) => {
    e54.capacityNodes = e54.nodeDimensionSubdivisionSolver.outputNodes;
  } }), Ate("edgeSolver", ui, (e54) => [e54.capacityNodes], { onSolved: (e54) => {
    e54.capacityEdges = e54.edgeSolver?.edges;
  } }), Ate("availableSegmentPointSolver", ii, (e54) => [{ nodes: e54.capacityNodes, edges: e54.capacityEdges || [], traceWidth: e54.minTraceWidth, colorMap: e54.colorMap, shouldReturnCrampedPortPoints: true }]), Ate("necessaryCrampedPortPointSolver", FG, (e54) => {
    const t4 = Rte(e54.capacityNodes);
    return [{ capacityMeshNodes: e54.capacityNodes.filter((e60) => !t4.has(e60.capacityMeshNodeId)), sharedEdgeSegments: Ete({ sharedEdgeSegments: e54.availableSegmentPointSolver.getOutput(), componentCapacityMeshNodeIds: t4 }), simpleRouteJson: e54.srjWithPointPairs }];
  }, { onSolved: (e54) => {
    const t4 = Rte(e54.capacityNodes);
    e54.sharedEdgeSegmentsWithNecessaryCrampedPortPoints = function({ originalSharedEdgeSegments: e60, filteredSharedEdgeSegments: t10, componentCapacityMeshNodeIds: n8 }) {
      const o10 = new Map(t10.map((e61) => [e61.edgeId, e61]));
      return e60.map((e61) => Tte(e61, n8) ? e61 : o10.get(e61.edgeId) ?? e61);
    }({ originalSharedEdgeSegments: e54.availableSegmentPointSolver.getOutput(), filteredSharedEdgeSegments: e54.necessaryCrampedPortPointSolver.getOutput(), componentCapacityMeshNodeIds: t4 });
  } }), Ate("portPointPathingSolver", eK, (e54) => {
    const t4 = e54.sharedEdgeSegmentsWithNecessaryCrampedPortPoints ?? e54.necessaryCrampedPortPointSolver?.getOutput() ?? e54.availableSegmentPointSolver.getOutput(), { graph: n8, connections: o10 } = KG({ capacityMeshNodes: e54.capacityNodes, layerCount: e54.srj.layerCount, connectivityMap: e54.connMap, segmentPortPoints: t4.flatMap((e60) => e60.portPoints), simpleRouteJsonConnections: e54.srjWithPointPairs.connections });
    return [{ graph: n8, connections: o10, layerCount: e54.srj.layerCount, effort: Math.min(1, e54.effort), preserveTerminalPcbPortIds: true, minViaPadDiameter: e54.viaDiameter, flags: { FORCE_CENTER_FIRST: true, RIPPING_ENABLED: true, USE_SELECTIVE_RERIP_ROUTING: true }, weights: { SHUFFLE_SEED: 0, MEMORY_PF_FACTOR: 4, CENTER_OFFSET_DIST_PENALTY_FACTOR: 0, CENTER_OFFSET_FOCUS_SHIFT: 0, NODE_PF_FACTOR: 0, LAYER_CHANGE_COST: 0, RIPPING_PF_COST: 0, NODE_PF_MAX_PENALTY: 100, BASE_CANDIDATE_COST: 0.6, MAX_ITERATIONS_PER_PATH: 0, RANDOM_WALK_DISTANCE: 0, START_RIPPING_PF_THRESHOLD: 0.3, END_RIPPING_PF_THRESHOLD: 1, MAX_RIPS: 1000, RANDOM_RIP_FRACTION: 0.3, STRAIGHT_LINE_DEVIATION_PENALTY_FACTOR: 4, GREEDY_MULTIPLIER: 0.7, MIN_ALLOWED_BOARD_SCORE: -1e4 } }];
  }), Ate("uniformPortDistributionSolver", bo, (e54) => [{ nodeWithPortPoints: e54.portPointPathingSolver?.getOutput().nodesWithPortPoints ?? [], inputNodesWithPortPoints: e54.portPointPathingSolver?.getOutput().inputNodeWithPortPoints ?? [], minTraceWidth: e54.minTraceWidth, obstacles: e54.srj.obstacles, layerCount: e54.srj.layerCount }]), Ate("highDensityRouteSolver", Dz, (e54) => {
    const t4 = e54.uniformPortDistributionSolver?.getOutput() ?? [], n8 = e54.portPointPathingSolver?.getOutput().nodesWithPortPoints ?? [], o10 = t4.length > 0 ? t4 : n8;
    return e54.highDensityNodePortPoints = structuredClone(o10), [{ nodePortPoints: o10, nodePfById: new Map((e54.portPointPathingSolver?.getOutput().inputNodeWithPortPoints ?? []).map((t10) => [t10.capacityMeshNodeId, e54.portPointPathingSolver?.computeNodePf(t10) ?? null])), colorMap: e54.colorMap, connMap: e54.connMap, viaDiameter: e54.viaDiameter, traceWidth: e54.minTraceWidth, obstacleMargin: e54.srj.defaultObstacleMargin ?? 0.15, obstacles: e54.srj.obstacles, layerCount: e54.srj.layerCount, useGrowShrinkHighDensityIntraNodeSolver: true, preserveTerminalPcbPortIds: true, growShrinkFallbackToInvalidGeometryOnFailure: true, captureSearchDebug: false }];
  }), Ate("highDensityForceImproveSolver", SZ, (e54) => [{ nodeWithPortPoints: e54.highDensityNodePortPoints ?? [], hdRoutes: e54.highDensityRouteSolver.routes, colorMap: e54.colorMap, totalStepsPerNode: Math.max(12, Math.round(20 * Math.min(1, e54.effort))), nodeAssignmentMargin: e54.srj.defaultObstacleMargin ?? 0.2 }]), Ate("highDensityRepairSolver", g1, (e54) => [{ nodeWithPortPoints: e54.highDensityNodePortPoints ?? [], hdRoutes: e54.highDensityForceImproveSolver?.getOutput() ?? e54.highDensityRouteSolver.routes, obstacles: e54.srj.obstacles, colorMap: e54.colorMap, repairMargin: e54.srj.defaultObstacleMargin ?? 0.2, minimumTraceWidth: e54.srj.minTraceWidth, connMap: e54.connMap }]), Ate("highDensityStitchSolver", L1, (e54) => [{ connections: e54.srjWithPointPairs.connections, hdRoutes: e54.highDensityRepairSolver?.getOutput() ?? e54.highDensityForceImproveSolver?.getOutput() ?? e54.highDensityRouteSolver.routes, colorMap: e54.colorMap, layerCount: e54.srj.layerCount, defaultViaDiameter: e54.viaDiameter, preserveTerminalPcbPortIds: true }]), Ate("traceSimplificationSolver", WF, (e54) => [{ hdRoutes: e54.highDensityStitchSolver.mergedHdRoutes, obstacles: e54.srj.obstacles, connMap: e54.connMap, colorMap: e54.colorMap, outline: e54.srj.outline, defaultViaDiameter: e54.viaDiameter, layerCount: e54.srj.layerCount, minTraceToPadEdgeClearance: e54.srj.minTraceToPadEdgeClearance, minBoardEdgeClearance: e54.srj.minBoardEdgeClearance, enableCrossingViaReduction: true, iterations: 2 }]), Ate("traceWidthSolver", QF, (e54) => [{ hdRoutes: e54.traceSimplificationSolver.simplifiedHdRoutes, obstacles: e54.srj.obstacles, connMap: e54.connMap, colorMap: e54.colorMap, minTraceWidth: e54.minTraceWidth, connection: e54.srj.connections, obstacleMargin: e54.srj.minTraceToPadEdgeClearance ?? 0.15, layerCount: e54.srj.layerCount }]), Ate("globalDrcForceImproveSolver", kN, (e54) => [{ srj: e54.srjWithPointPairs, hdRoutes: Mte({ hdRoutes: e54.traceWidthSolver.getHdRoutesWithWidths(), connections: e54.netToPointPairsSolver?.newConnections ?? [] }), connMap: e54.connMap, effort: Math.min(1, e54.effort), maxIterations: 16, enableLargeBoardBroadFallback: false, enablePostSolveClearanceRelaxation: false }]), Ate("exactGeometryDrcForceImproveSolver", LN, (e54) => {
    const t4 = e54.globalDrcForceImproveSolver.getOutput(), n8 = ((e60) => {
      const t10 = { ...e60.srjWithPointPairs, obstacles: e60.originalSrj.obstacles, minTraceWidth: e60.originalSrj.minTraceWidth, minViaDiameter: e60.originalSrj.minViaDiameter ?? e60.srjWithPointPairs.minViaDiameter }, n10 = vte(e60.originalSrj), o10 = Math.max(Yo(e60.originalSrj).padDiameter, t10.minTraceWidth) + Math.max(0.1, 0.1), i8 = new mb(t10, { connMap: e60.connMap, includeTraceViaOwnerMetadata: true, traceClearance: 0.1, viaClearance: 0.1, viaToPadClearance: n10, spatialCellSize: o10 }), r9 = Ste(e60), s7 = e60.originalSrj.traces ?? [];
      return ({ routes: e61, hdRoutes: t11 }) => {
        const n11 = e61 ?? t11;
        if (!n11)
          throw new Error("Pipeline7 autorouting DRC evaluation requires HD routes");
        const o11 = r9(n11), a9 = s7.length ? [...s7, ...o11] : o11;
        return i8.evaluate(a9);
      };
    })({ connections: e54.netToPointPairsSolver?.newConnections ?? [], originalConnections: e54.originalSrj.connections, layerCount: e54.srj.layerCount, obstacles: e54.srj.obstacles, defaultViaHoleDiameter: e54.viaHoleDiameter, connMap: e54.connMap, srjWithPointPairs: e54.srjWithPointPairs, originalSrj: e54.originalSrj });
    return [{ srj: e54.srjWithPointPairs, hdRoutes: t4, connMap: e54.connMap, effort: Math.min(1, e54.effort), viaHoleDiameter: e54.viaHoleDiameter, drcEvaluator: n8, viaInPadDrcEvaluator: n8, maxIterations: 32, enableLargeBoardBroadFallback: false, enableBroadFallback: false, enableTargetedErrorSweep: true, enablePostSolveClearanceRelaxation: false, enableSafeTraceLayerMoves: true, enableViaInPadLayerMoves: e54.originalSrj.allowViaInPad ?? false, viaInPadMaxIterations: 32, broadMaxIterations: 12, broadPassMultiplier: 3 }];
  }), Ate("lengthMatchingPostProcessingSolver", o9, (e54) => {
    const t4 = e54.netToPointPairsSolver;
    if (!t4)
      throw new Error("Pipeline7: length-matching post-processing requires NetToPointPairsSolver output");
    const n8 = t4.newConnections, o10 = new Map;
    for (const t10 of e54.srj.differentialPairs ?? [])
      for (const e60 of t10.connectionNames) {
        const t11 = n8.filter((t12) => t12.name === e60 || t12.__rootConnectionNames?.includes(e60) || t12.__netConnectionName === e60);
        if (t11.length !== 1)
          throw new Error(`Pipeline7: differential pair connection "${e60}" must resolve to exactly one final point-pair connection, got ${t11.length}`);
        o10.set(e60, t11[0].name);
      }
    const i8 = e54.exactGeometryDrcForceImproveSolver.getOutput(), r9 = (e54.srj.differentialPairs ?? []).map((e60) => {
      const t10 = e60.connectionNames.map((e61) => {
        const t11 = o10.get(e61);
        if (!t11)
          throw new Error(`Pipeline7: differential pair connection "${e61}" is missing from final routed output`);
        return t11;
      });
      if (t10[0] === t10[1])
        throw new Error(`Pipeline7: differential pair ${e60.connectionNames.join("/")} resolves both members to "${t10[0]}"`);
      if (e60.traceGap === undefined)
        return { connectionNames: t10, lengthTolerance: e60.lengthTolerance, maxUncoupledLength: e60.maxUncoupledLength };
      const n10 = t10.map((e61) => {
        const t11 = i8.filter((t12) => t12.connectionName === e61);
        if (t11.length !== 1)
          throw new Error(`Pipeline7: differential pair connection "${e61}" must resolve to exactly one final HD route, got ${t11.length}`);
        return t11[0];
      }), r10 = e60.traceGap + n10.reduce((e61, t11) => e61 + t11.traceThickness / 2, 0);
      return { connectionNames: t10, lengthTolerance: e60.lengthTolerance, maxUncoupledLength: e60.maxUncoupledLength, minimumCenterlineDistance: r10, maximumCenterlineDistance: r10 };
    });
    return [{ hdRoutes: i8, differentialPairs: r9, obstacles: e54.srj.obstacles, bounds: e54.srj.bounds, layerCount: e54.srj.layerCount }];
  }), Ate("powerTraceExpansionSolver", Ite, (e54) => {
    const t4 = e54.opts.powerTraceExpansion ?? {}, n8 = t4.onlyConnectionNames ?? Pte(e54.originalSrj);
    return [wte({ originalSrj: e54.originalSrj, newlyRoutedTraces: e54.getPrePowerTraceOutputSimplifiedPcbTraces(), expandedConnectionNames: n8 }), { allowNewVias: false, ...t4, onlyConnectionNames: n8 }];
  })];
  setSimpleRouteJson(e54) {
    this.srj = e54;
    const t4 = Yo(this.srj);
    this.viaDiameter = t4.padDiameter, this.viaHoleDiameter = t4.holeDiameter, this.minTraceWidth = this.srj.minTraceWidth, this.connMap = ei(this.srj), this.colorMap = Eo(this.srj, this.connMap);
  }
  getConstructorParams() {
    return [this.srj, this.opts];
  }
  currentPipelineStepIndex = 0;
  computeProgress() {
    const e54 = this.activeSubSolver?.progress ?? 0;
    return (this.currentPipelineStepIndex + e54) / this.pipelineDef.length;
  }
  _step() {
    const e54 = this.pipelineDef[this.currentPipelineStepIndex];
    if (!e54)
      return void (this.solved = true);
    if (this.activeSubSolver)
      return this.activeSubSolver.step(), void (this.activeSubSolver.solved ? (this.endTimeOfPhase[e54.solverName] = performance.now(), this.timeSpentOnPhase[e54.solverName] = this.endTimeOfPhase[e54.solverName] - this.startTimeOfPhase[e54.solverName], e54.onSolved?.(this), this.activeSubSolver = null, this.currentPipelineStepIndex++) : this.activeSubSolver.failed && (this.error = this.activeSubSolver?.error, this.failed = true, this.activeSubSolver = null));
    const t4 = e54.getConstructorParams(this);
    this.activeSubSolver = new e54.solverClass(...t4), this.activeSubSolver instanceof WF && (this.activeSubSolver.MAX_SIMPLIFICATION_PIPELINE_LOOPS = Math.ceil(this.activeSubSolver.MAX_SIMPLIFICATION_PIPELINE_LOOPS * Math.min(1, this.effort))), e54.solverName !== "lengthMatchingPostProcessingSolver" && e54.solverName !== "powerTraceExpansionSolver" || (this.MAX_ITERATIONS = Math.max(this.MAX_ITERATIONS, this.iterations + this.activeSubSolver.MAX_ITERATIONS + 1)), this[e54.solverName] = this.activeSubSolver, this.timeSpentOnPhase[e54.solverName] = 0, this.startTimeOfPhase[e54.solverName] = performance.now();
  }
  solveUntilPhase(e54) {
    for (;this.getCurrentPhase() !== e54; )
      this.step();
  }
  getCurrentPhase() {
    return this.pipelineDef[this.currentPipelineStepIndex]?.solverName ?? "none";
  }
  visualize() {
    if (!this.solved && this.activeSubSolver)
      return this.visualizeStage(this.activeSubSolver);
    const e54 = this.escapeViaLocationSolver?.visualize(), t4 = this.netToPointPairsSolver?.visualize(), n8 = this.componentDetectionSolver?.visualize(), o10 = this.componentTopologyGeneratorSolver?.visualize(), i8 = this.globalTopologyGeneratorSolver?.visualize(), r9 = this.topologyMergingSolver?.visualize(), s7 = this.nodeDimensionSubdivisionSolver?.visualize(), a9 = this.nodeTargetMerger?.visualize(), c5 = this.singleLayerNodeMerger?.visualize(), l5 = this.strawSolver?.visualize(), h5 = this.edgeSolver?.visualize(), d9 = this.deadEndSolver?.visualize(), u9 = this.availableSegmentPointSolver?.visualize(), p9 = this.portPointPathingSolver?.visualize(), m9 = this.multiSectionPortPointOptimizer?.visualize(), g10 = this.uniformPortDistributionSolver?.visualize(), f10 = this.highDensityRouteSolver?.visualize(), _5 = this.highDensityForceImproveSolver?.visualize(), y10 = this.highDensityRepairSolver?.visualize(), b10 = this.highDensityStitchSolver?.visualize(), x8 = this.traceSimplificationSolver?.visualize(), v10 = this.lengthMatchingPostProcessingSolver?.visualize(), I6 = this.traceWidthSolver?.visualize(), S6 = this.necessaryCrampedPortPointSolver?.visualize(), C = (this.highDensityRouteSolver?.visualize(), this.originalSrj), P = C.outline, M = [];
    if (M.push({ points: [{ x: C.bounds?.minX ?? -50, y: C.bounds?.minY ?? -50 }, { x: C.bounds?.maxX ?? 50, y: C.bounds?.minY ?? -50 }, { x: C.bounds?.maxX ?? 50, y: C.bounds?.maxY ?? 50 }, { x: C.bounds?.minX ?? -50, y: C.bounds?.maxY ?? 50 }, { x: C.bounds?.minX ?? -50, y: C.bounds?.minY ?? -50 }], strokeColor: "rgba(255,0,0,0.25)" }), P && P.length >= 2) {
      const e60 = P.map((e61) => ({ x: e61.x, y: e61.y }));
      e60.push({ ...e60[0] }), M.push({ points: e60, strokeColor: "rgba(0, 136, 255, 0.95)" });
    }
    const w = Lo(C), N = { points: [...C.connections.flatMap((e60) => e60.pointsToConnect.map((t10) => ({ ...t10, layer: Bo(t10, C.layerCount), label: `${e60.name} ${t10.pcb_port_id ?? ""}` })))], rects: [...(C.obstacles ?? []).filter((e60) => !e60.isCopperPour).map((e60) => ({ ...e60, fill: e60.layers?.includes("top") ? "rgba(255,0,0,0.25)" : e60.layers?.includes("bottom") ? "rgba(0,0,255,0.25)" : "rgba(255,0,0,0.25)", layer: jo(e60, C.layerCount), label: w(e60) }))], lines: M }, R10 = { traceColorMode: this.visualizationTraceColorMode }, T2 = nK({ srj: C, visualizationOptions: R10 }), E10 = pi(N, T2), A7 = this.preprocessSimpleRouteJsonSolver?.visualize(), O10 = this.globalDrcForceImproveSolver?.visualize(), k6 = this.exactGeometryDrcForceImproveSolver?.visualize(), D9 = [E10, A7, n8, o10, e54, t4, i8, r9, s7, a9, c5, l5, h5, d9, u9, S6, p9, m9, g10, f10 ? pi(N, f10) : null, _5, y10, b10, x8, I6, O10, k6, v10, this.solved ? pi({ lines: M }, nK({ srj: this.originalSrj, visualizationOptions: R10 }), this.visualizeFinalOutput()) : null].filter(Boolean), L10 = pi(...D9);
    return this.visualizationTraceColorMode === "net" ? T7(L10, this.colorMap) : L10;
  }
  visualizeStage(e54) {
    const t4 = e54.visualize();
    return this.visualizationTraceColorMode === "net" ? T7(t4, this.colorMap) : t4;
  }
  visualizeFinalOutput() {
    const e54 = this.visualizationTraceColorMode, t4 = this.getOutputSimpleRouteJson();
    return Wo(t4, { traceColorMode: e54 });
  }
  preview() {
    if (this.highDensityRouteSolver) {
      const e54 = [];
      for (let t4 = this.highDensityRouteSolver.routes.length - 1;t4 >= 0; t4--) {
        const n8 = this.highDensityRouteSolver.routes[t4];
        if (e54.push({ points: n8.route.map((e60) => ({ x: e60.x, y: e60.y })), strokeColor: this.colorMap[n8.connectionName] }), e54.length > 200)
          break;
      }
      return { lines: e54 };
    }
    return this.portPointPathingSolver ? this.portPointPathingSolver.preview() : this.netToPointPairsSolver ? this.netToPointPairsSolver.visualize() : this.escapeViaLocationSolver ? this.escapeViaLocationSolver.visualize() : this.componentTopologyGeneratorSolver ? this.componentTopologyGeneratorSolver.visualize() : this.componentDetectionSolver ? this.componentDetectionSolver.visualize() : this.preprocessSimpleRouteJsonSolver ? this.preprocessSimpleRouteJsonSolver.visualize() : {};
  }
  _getOutputHdRoutes() {
    if (this.lengthMatchingPostProcessingSolver) {
      const { hdRoutes: e54 } = this.lengthMatchingPostProcessingSolver.getOutput();
      return e54;
    }
    return this.exactGeometryDrcForceImproveSolver?.getOutput() ?? this.globalDrcForceImproveSolver?.getOutput() ?? this.traceWidthSolver?.getHdRoutesWithWidths() ?? this.traceSimplificationSolver?.simplifiedHdRoutes ?? this.highDensityStitchSolver.mergedHdRoutes;
  }
  getOutputSimplifiedPcbTraces() {
    if (!this.solved || !this.highDensityRouteSolver)
      throw new Error("Cannot get output before solving is complete");
    return this.powerTraceExpansionSolver ? this.powerTraceExpansionSolver.getOutput() : this.getPrePowerTraceOutputSimplifiedPcbTraces();
  }
  getPrePowerTraceOutputSimplifiedPcbTraces() {
    return Cte({ connections: this.netToPointPairsSolver?.newConnections ?? [], originalConnections: this.originalSrj.connections, hdRoutes: this._getOutputHdRoutes(), layerCount: this.srj.layerCount, obstacles: this.srj.obstacles, defaultViaHoleDiameter: this.viaHoleDiameter, connMap: this.connMap });
  }
  getOutputSimpleRouteJson() {
    return { ...this.originalSrj, traces: this.getOutputSimplifiedPcbTraces() };
  }
};
var kte = (e54) => [...new Set(e54)].sort((e60, t4) => e60 - t4);
var Dte = class extends ni {
  constructor(e54) {
    super(), this.params = e54, this.MAX_ITERATIONS = 1;
  }
  outputNodes = [];
  outputSharedEdgeSegments = [];
  nodeIdByOriginalAndZ = new Map;
  getSolverName() {
    return "SplitNodesIntoSingleLayerNodeSolver";
  }
  _step() {
    this.outputNodes = this.params.capacityMeshNodes.flatMap((e54) => kte(e54.availableZ).map((t4) => {
      const n8 = ((e60, t10) => `${e60}__z${t10}`)(e54.capacityMeshNodeId, t4);
      return this.nodeIdByOriginalAndZ.set(`${e54.capacityMeshNodeId}:${t4}`, n8), { ...e54, capacityMeshNodeId: n8, layer: `z${t4}`, availableZ: [t4], _parent: e54 };
    })), this.outputSharedEdgeSegments = this.params.sharedEdgeSegments.flatMap((e54) => this.splitSharedEdgeSegment(e54)), this.stats = { inputNodeCount: this.params.capacityMeshNodes.length, outputNodeCount: this.outputNodes.length, inputPortPointCount: this.params.sharedEdgeSegments.reduce((e54, t4) => e54 + t4.portPoints.length, 0), outputPortPointCount: this.outputSharedEdgeSegments.reduce((e54, t4) => e54 + t4.portPoints.length, 0) }, this.solved = true;
  }
  getSplitNodeId(e54, t4) {
    return this.nodeIdByOriginalAndZ.get(`${e54}:${t4}`);
  }
  splitPortPoint(e54) {
    return kte(e54.availableZ).flatMap((t4) => {
      const n8 = e54.nodeIds.map((e60) => this.getSplitNodeId(e60, t4));
      return n8[0] && n8[1] ? [{ ...e54, segmentPortPointId: `${e54.segmentPortPointId}__z${t4}`, availableZ: [t4], nodeIds: [n8[0], n8[1]] }] : [];
    });
  }
  splitSharedEdgeSegment(e54) {
    const t4 = new Map;
    for (const n8 of e54.portPoints.flatMap((e60) => this.splitPortPoint(e60))) {
      const e60 = n8.availableZ[0];
      if (e60 === undefined)
        continue;
      const o10 = t4.get(e60) ?? [];
      o10.push(n8), t4.set(e60, o10);
    }
    return [...t4.entries()].map(([t10, n8]) => ({ ...e54, edgeId: `${e54.edgeId}__z${t10}`, nodeIds: n8[0].nodeIds, availableZ: [t10], portPoints: n8 }));
  }
  getOutput() {
    return { capacityMeshNodes: this.outputNodes, sharedEdgeSegments: this.outputSharedEdgeSegments };
  }
  getConstructorParams() {
    return [this.params];
  }
  visualize() {
    return { rects: this.outputNodes.map((e54) => ({ ...dj(e54), label: `${e54.capacityMeshNodeId}
${e54.layer}` })), points: this.outputSharedEdgeSegments.flatMap((e54) => e54.portPoints.map((e60) => ({ x: e60.x, y: e60.y, label: `${e60.segmentPortPointId}
z${e60.availableZ.join(",")}` }))) };
  }
};
function Lte(e54, t4, n8, o10 = {}) {
  return { solverName: e54, solverClass: t4, getConstructorParams: n8, onSolved: o10.onSolved };
}
var zte = class extends ni {
  constructor(e54, t4 = {}) {
    super(), this.srj = e54, this.opts = t4, this.originalSrj = e54, this.opts = { ...t4 };
    const n8 = this.opts;
    if (this.effort = n8.effort ?? 1, this.MAX_ITERATIONS = 1e8 * this.effort, this.maxNodeDimension = n8.maxNodeDimension ?? 16, this.maxNodeRatio = n8.maxNodeRatio ?? 6, this.minNodeArea = n8.minNodeArea ?? 0.1 ** 2, this.setSimpleRouteJson(e54), n8.capacityDepth === undefined) {
      const e60 = this.srj.bounds.maxX - this.srj.bounds.minX, t10 = this.srj.bounds.maxY - this.srj.bounds.minY, o10 = Math.max(e60, t10), i8 = n8.targetMinCapacity ?? 0.5;
      n8.capacityDepth = Fz(o10, i8);
    }
    this.cacheProvider = n8.cacheProvider === undefined ? no() : n8.cacheProvider === null ? null : n8.cacheProvider, this.startTimeOfPhase = {}, this.endTimeOfPhase = {}, this.timeSpentOnPhase = {};
  }
  preprocessSimpleRouteJsonSolver;
  escapeViaLocationSolver;
  netToPointPairsSolver;
  nodeSolver;
  nodeDimensionSubdivisionSolver;
  nodeTargetMerger;
  edgeSolver;
  colorMap;
  highDensityRouteSolver;
  highDensityForceImproveSolver;
  highDensityForceImproveRoutes;
  highDensityRepairSolver;
  highDensityRepairRoutes;
  highDensityStitchSolver;
  globalDrcForceImproveSolver;
  singleLayerNodeMerger;
  strawSolver;
  deadEndSolver;
  traceSimplificationSolver;
  availableSegmentPointSolver;
  splitNodesIntoSingleLayerNodeSolver;
  portPointPathingSolver;
  multiSectionPortPointOptimizer;
  uniformPortDistributionSolver;
  traceWidthSolver;
  necessaryCrampedPortPointSolver;
  viaDiameter;
  viaHoleDiameter;
  minTraceWidth;
  effort;
  maxNodeDimension;
  maxNodeRatio;
  minNodeArea;
  startTimeOfPhase;
  endTimeOfPhase;
  timeSpentOnPhase;
  activeSubSolver = null;
  connMap;
  srjWithEscapeViaLocations;
  srjWithPointPairs;
  originalSrj;
  capacityNodes = null;
  capacityEdges = null;
  highDensityNodePortPoints;
  cacheProvider = null;
  pipelineDef = [Lte("preprocessSimpleRouteJsonSolver", U1, (e54) => [e54.originalSrj], { onSolved: (e54) => {
    e54.setSimpleRouteJson(e54.preprocessSimpleRouteJsonSolver.getOutputSimpleRouteJson());
  } }), Lte("escapeViaLocationSolver", uK, (e54) => [e54.srj, { viaDiameter: e54.viaDiameter, minTraceWidth: e54.minTraceWidth, obstacleMargin: e54.srj.defaultObstacleMargin ?? 0.15 }], { onSolved: (e54) => {
    e54.srjWithEscapeViaLocations = e54.escapeViaLocationSolver?.getOutputSimpleRouteJson();
  } }), Lte("netToPointPairsSolver", pB, (e54) => {
    const t4 = e54.srjWithEscapeViaLocations ?? e54.srj;
    return [t4, e54.colorMap, ti(t4)];
  }, { onSolved: (e54) => {
    e54.srjWithPointPairs = e54.netToPointPairsSolver?.getNewSimpleRouteJson(), e54.colorMap = Eo(e54.srjWithPointPairs, e54.connMap), e54.connMap = ei(e54.srjWithPointPairs);
  } }), Lte("nodeSolver", Jn, (e54) => [{ simpleRouteJson: e54.srjWithPointPairs, maxGapFillPasses: 4 }], { onSolved: (e54) => {
    e54.capacityNodes = e54.nodeSolver?.getOutput().meshNodes ?? [];
  } }), Lte("nodeDimensionSubdivisionSolver", MZ, (e54) => [e54.capacityNodes, e54.maxNodeDimension, e54.maxNodeRatio, e54.minNodeArea], { onSolved: (e54) => {
    e54.capacityNodes = e54.nodeDimensionSubdivisionSolver?.outputNodes ?? [];
  } }), Lte("edgeSolver", ui, (e54) => [e54.capacityNodes], { onSolved: (e54) => {
    e54.capacityEdges = e54.edgeSolver?.edges;
  } }), Lte("availableSegmentPointSolver", ii, (e54) => [{ nodes: e54.capacityNodes, edges: e54.capacityEdges || [], traceWidth: e54.minTraceWidth, colorMap: e54.colorMap, shouldReturnCrampedPortPoints: true }]), Lte("necessaryCrampedPortPointSolver", FG, (e54) => [{ capacityMeshNodes: e54.capacityNodes, sharedEdgeSegments: e54.availableSegmentPointSolver.getOutput(), simpleRouteJson: e54.srjWithPointPairs }]), Lte("splitNodesIntoSingleLayerNodeSolver", Dte, (e54) => [{ capacityMeshNodes: e54.capacityNodes, sharedEdgeSegments: e54.necessaryCrampedPortPointSolver?.getOutput() ?? e54.availableSegmentPointSolver.getOutput() }], { onSolved: (e54) => {
    e54.capacityNodes = e54.splitNodesIntoSingleLayerNodeSolver.getOutput().capacityMeshNodes;
  } }), Lte("portPointPathingSolver", eK, (e54) => {
    const t4 = e54.splitNodesIntoSingleLayerNodeSolver.getOutput(), { graph: n8, connections: o10 } = KG({ capacityMeshNodes: t4.capacityMeshNodes, layerCount: e54.srj.layerCount, connectivityMap: e54.connMap, segmentPortPoints: t4.sharedEdgeSegments.flatMap((e60) => e60.portPoints), simpleRouteJsonConnections: e54.srjWithPointPairs.connections, assignableViaObstacles: e54.originalSrj.obstacles });
    return [{ graph: n8, connections: o10, layerCount: e54.srj.layerCount, effort: Math.min(1, e54.effort), minViaPadDiameter: e54.viaDiameter, flags: { FORCE_CENTER_FIRST: true, RIPPING_ENABLED: true }, weights: { SHUFFLE_SEED: 0, MEMORY_PF_FACTOR: 4, CENTER_OFFSET_DIST_PENALTY_FACTOR: 0, CENTER_OFFSET_FOCUS_SHIFT: 0, NODE_PF_FACTOR: 0, LAYER_CHANGE_COST: 0, RIPPING_PF_COST: 0, NODE_PF_MAX_PENALTY: 100, BASE_CANDIDATE_COST: 0.6, MAX_ITERATIONS_PER_PATH: 0, RANDOM_WALK_DISTANCE: 0, START_RIPPING_PF_THRESHOLD: 0.3, END_RIPPING_PF_THRESHOLD: 1, MAX_RIPS: 1000, RANDOM_RIP_FRACTION: 0.3, STRAIGHT_LINE_DEVIATION_PENALTY_FACTOR: 4, GREEDY_MULTIPLIER: 0.7, MIN_ALLOWED_BOARD_SCORE: -1e4 } }];
  }), Lte("uniformPortDistributionSolver", bo, (e54) => [{ nodeWithPortPoints: e54.portPointPathingSolver?.getOutput().nodesWithPortPoints ?? [], inputNodesWithPortPoints: e54.portPointPathingSolver?.getOutput().inputNodeWithPortPoints ?? [], minTraceWidth: e54.minTraceWidth, obstacles: e54.srj.obstacles, layerCount: e54.srj.layerCount }]), Lte("highDensityRouteSolver", Dz, (e54) => {
    const t4 = e54.uniformPortDistributionSolver?.getOutput() ?? [], n8 = e54.portPointPathingSolver?.getOutput().nodesWithPortPoints ?? [], o10 = t4.length > 0 ? t4 : n8;
    return e54.highDensityNodePortPoints = structuredClone(o10), [{ nodePortPoints: o10, nodePfById: new Map((e54.portPointPathingSolver?.getOutput().inputNodeWithPortPoints ?? []).map((t10) => [t10.capacityMeshNodeId, e54.portPointPathingSolver?.computeNodePf(t10) ?? null])), colorMap: e54.colorMap, connMap: e54.connMap, viaDiameter: e54.viaDiameter, traceWidth: e54.minTraceWidth, obstacleMargin: e54.srj.defaultObstacleMargin ?? 0.15, obstacles: e54.srj.obstacles, layerCount: e54.srj.layerCount }];
  }), Lte("highDensityForceImproveSolver", SZ, (e54) => [{ nodeWithPortPoints: e54.getHighDensityNodePortPointsWithAssignableViasFirst(), hdRoutes: e54.getMovableHighDensityRoutes(e54.highDensityRouteSolver.routes), colorMap: e54.colorMap, totalStepsPerNode: Math.max(20, Math.round(60 * Math.min(1, e54.effort))), nodeAssignmentMargin: e54.srj.defaultObstacleMargin ?? 0.2 }], { onSolved: (e54) => {
    e54.highDensityForceImproveRoutes = e54.mergeMovableHighDensityRoutesBack(e54.highDensityRouteSolver.routes, e54.highDensityForceImproveSolver.getOutput());
  } }), Lte("highDensityRepairSolver", g1, (e54) => [{ nodeWithPortPoints: e54.getHighDensityNodePortPointsWithAssignableViasFirst(), hdRoutes: e54.getMovableHighDensityRoutes(e54.highDensityForceImproveRoutes ?? e54.highDensityForceImproveSolver?.getOutput() ?? e54.highDensityRouteSolver.routes), obstacles: e54.srj.obstacles, colorMap: e54.colorMap, repairMargin: e54.srj.defaultObstacleMargin ?? 0.2, minimumTraceWidth: e54.srj.minTraceWidth, connMap: e54.connMap }], { onSolved: (e54) => {
    const t4 = e54.highDensityForceImproveRoutes ?? e54.highDensityForceImproveSolver?.getOutput() ?? e54.highDensityRouteSolver.routes;
    e54.highDensityRepairRoutes = e54.mergeMovableHighDensityRoutesBack(t4, e54.highDensityRepairSolver.getOutput());
  } }), Lte("highDensityStitchSolver", L1, (e54) => [{ connections: e54.srjWithPointPairs.connections, hdRoutes: e54.highDensityRepairRoutes ?? e54.highDensityRepairSolver?.getOutput() ?? e54.highDensityForceImproveRoutes ?? e54.highDensityForceImproveSolver?.getOutput() ?? e54.highDensityRouteSolver.routes, colorMap: e54.colorMap, layerCount: e54.srj.layerCount, defaultViaDiameter: e54.viaDiameter, allowedLayerTransitionPointKeys: VG(e54.originalSrj.obstacles) }]), Lte("traceSimplificationSolver", WF, (e54) => [{ hdRoutes: e54.highDensityStitchSolver.mergedHdRoutes, obstacles: e54.srj.obstacles, connMap: e54.connMap, colorMap: e54.colorMap, outline: e54.srj.outline, defaultViaDiameter: e54.viaDiameter, layerCount: e54.srj.layerCount, minTraceToPadEdgeClearance: e54.srj.minTraceToPadEdgeClearance, iterations: 2 }]), Lte("traceWidthSolver", QF, (e54) => [{ hdRoutes: e54.traceSimplificationSolver.simplifiedHdRoutes, obstacles: e54.srj.obstacles, connMap: e54.connMap, colorMap: e54.colorMap, minTraceWidth: e54.minTraceWidth, connection: e54.srj.connections, obstacleMargin: e54.srj.minTraceToPadEdgeClearance ?? 0.15, layerCount: e54.srj.layerCount }]), Lte("globalDrcForceImproveSolver", kN, (e54) => [{ srj: e54.srjWithPointPairs, hdRoutes: e54.traceWidthSolver.getHdRoutesWithWidths(), effort: Math.min(1, e54.effort) }])];
  setSimpleRouteJson(e54) {
    this.srj = e54;
    const t4 = Yo(this.srj);
    this.viaDiameter = t4.padDiameter, this.viaHoleDiameter = t4.holeDiameter, this.minTraceWidth = this.srj.minTraceWidth, this.connMap = ei(this.srj), this.colorMap = Eo(this.srj, this.connMap);
  }
  getConstructorParams() {
    return [this.srj, this.opts];
  }
  currentPipelineStepIndex = 0;
  _step() {
    const e54 = this.pipelineDef[this.currentPipelineStepIndex];
    if (!e54)
      return void (this.solved = true);
    if (this.activeSubSolver)
      return this.activeSubSolver.step(), void (this.activeSubSolver.solved ? (this.endTimeOfPhase[e54.solverName] = performance.now(), this.timeSpentOnPhase[e54.solverName] = this.endTimeOfPhase[e54.solverName] - this.startTimeOfPhase[e54.solverName], e54.onSolved?.(this), this.activeSubSolver = null, this.currentPipelineStepIndex++) : this.activeSubSolver.failed && (this.error = this.activeSubSolver?.error, this.failed = true, this.activeSubSolver = null));
    const t4 = e54.getConstructorParams(this);
    this.activeSubSolver = new e54.solverClass(...t4), this[e54.solverName] = this.activeSubSolver, this.timeSpentOnPhase[e54.solverName] = 0, this.startTimeOfPhase[e54.solverName] = performance.now();
  }
  solveUntilPhase(e54) {
    for (;this.getCurrentPhase() !== e54; )
      this.step();
  }
  getCurrentPhase() {
    return this.pipelineDef[this.currentPipelineStepIndex]?.solverName ?? "none";
  }
  visualize() {
    if (!this.solved && this.activeSubSolver)
      return this.activeSubSolver.visualize();
    const e54 = this.escapeViaLocationSolver?.visualize(), t4 = this.netToPointPairsSolver?.visualize(), n8 = this.nodeSolver?.visualize(), o10 = this.nodeDimensionSubdivisionSolver?.visualize(), i8 = this.nodeTargetMerger?.visualize(), r9 = this.singleLayerNodeMerger?.visualize(), s7 = this.strawSolver?.visualize(), a9 = this.edgeSolver?.visualize(), c5 = this.deadEndSolver?.visualize(), l5 = this.availableSegmentPointSolver?.visualize(), h5 = this.splitNodesIntoSingleLayerNodeSolver?.visualize(), d9 = this.portPointPathingSolver?.visualize(), u9 = this.multiSectionPortPointOptimizer?.visualize(), p9 = this.uniformPortDistributionSolver?.visualize(), m9 = this.highDensityRouteSolver?.visualize(), g10 = this.highDensityForceImproveSolver?.visualize(), f10 = this.highDensityRepairSolver?.visualize(), _5 = this.highDensityStitchSolver?.visualize(), y10 = this.traceSimplificationSolver?.visualize(), b10 = this.necessaryCrampedPortPointSolver?.visualize(), x8 = (this.highDensityRouteSolver?.visualize(), this.originalSrj), v10 = x8.outline, I6 = [];
    if (I6.push({ points: [{ x: x8.bounds?.minX ?? -50, y: x8.bounds?.minY ?? -50 }, { x: x8.bounds?.maxX ?? 50, y: x8.bounds?.minY ?? -50 }, { x: x8.bounds?.maxX ?? 50, y: x8.bounds?.maxY ?? 50 }, { x: x8.bounds?.minX ?? -50, y: x8.bounds?.maxY ?? 50 }, { x: x8.bounds?.minX ?? -50, y: x8.bounds?.minY ?? -50 }], strokeColor: "rgba(255,0,0,0.25)" }), v10 && v10.length >= 2) {
      const e60 = v10.map((e61) => ({ x: e61.x, y: e61.y }));
      e60.push({ ...e60[0] }), I6.push({ points: e60, strokeColor: "rgba(0, 136, 255, 0.95)" });
    }
    const S6 = Lo(x8), C = { points: [...x8.connections.flatMap((e60) => e60.pointsToConnect.map((t10) => ({ ...t10, layer: Bo(t10, x8.layerCount), label: `${e60.name} ${t10.pcb_port_id ?? ""}` })))], rects: [...(x8.obstacles ?? []).filter((e60) => !e60.isCopperPour).map((e60) => ({ ...e60, fill: e60.layers?.includes("top") ? "rgba(255,0,0,0.25)" : e60.layers?.includes("bottom") ? "rgba(0,0,255,0.25)" : "rgba(255,0,0,0.25)", layer: jo(e60, x8.layerCount), label: S6(e60) }))], lines: I6 }, P = nK({ srj: x8 }), M = [pi(C, P), e54, t4, n8, o10, i8, r9, s7, a9, c5, l5, b10, h5, d9, u9, p9, m9 ? pi(C, m9) : null, g10, f10, _5, y10, this.solved ? pi({ lines: I6 }, nK({ srj: this.originalSrj }), Wo(this.getOutputSimpleRouteJson())) : null].filter(Boolean);
    return pi(...M);
  }
  preview() {
    if (this.highDensityRouteSolver) {
      const e54 = [];
      for (let t4 = this.highDensityRouteSolver.routes.length - 1;t4 >= 0; t4--) {
        const n8 = this.highDensityRouteSolver.routes[t4];
        if (e54.push({ points: n8.route.map((e60) => ({ x: e60.x, y: e60.y })), strokeColor: this.colorMap[n8.connectionName] }), e54.length > 200)
          break;
      }
      return { lines: e54 };
    }
    return this.portPointPathingSolver ? this.portPointPathingSolver.preview() : this.netToPointPairsSolver ? this.netToPointPairsSolver.visualize() : this.escapeViaLocationSolver ? this.escapeViaLocationSolver.visualize() : this.preprocessSimpleRouteJsonSolver ? this.preprocessSimpleRouteJsonSolver.visualize() : {};
  }
  _getOutputHdRoutes() {
    const e54 = this.globalDrcForceImproveSolver?.getOutput();
    return e54 && this.routesOnlyUsePreplacedVias(e54) ? e54 : this.traceWidthSolver?.getHdRoutesWithWidths() ?? this.traceSimplificationSolver?.simplifiedHdRoutes ?? this.highDensityRepairRoutes ?? this.highDensityForceImproveRoutes ?? this.highDensityStitchSolver.mergedHdRoutes;
  }
  routesOnlyUsePreplacedVias(e54) {
    const t4 = VG(this.originalSrj.obstacles);
    return t4.size === 0 || e54.every((e60) => e60.vias.every((e61) => t4.has(jG(e61))));
  }
  getHighDensityNodePortPointsWithAssignableViasFirst() {
    return [...this.highDensityNodePortPoints ?? []].sort((e54, t4) => {
      const n8 = e54.capacityMeshNodeId.startsWith("assignable-via:");
      return n8 === t4.capacityMeshNodeId.startsWith("assignable-via:") ? 0 : n8 ? -1 : 1;
    });
  }
  getPreplacedAssignableViaObstacles() {
    return this.originalSrj.obstacles.filter((e54) => e54.netIsAssignable === true && (e54.layers?.length ?? 0) > 1);
  }
  isFixedPreplacedViaRoute(e54) {
    const t4 = this.getPreplacedAssignableViaObstacles();
    return t4.length !== 0 && e54.vias.length !== 0 && t4.some((t10) => [...e54.route, ...e54.vias].every((e60) => Oe(e60, t10) <= 0));
  }
  getMovableHighDensityRouteIndexes(e54) {
    return e54.map((e60, t4) => this.isFixedPreplacedViaRoute(e60) ? -1 : t4).filter((e60) => e60 !== -1);
  }
  getMovableHighDensityRoutes(e54) {
    return this.getMovableHighDensityRouteIndexes(e54).map((t4) => e54[t4]);
  }
  mergeMovableHighDensityRoutesBack(e54, t4) {
    const n8 = this.getMovableHighDensityRouteIndexes(e54), o10 = [...e54];
    for (let e60 = 0;e60 < n8.length; e60++)
      o10[n8[e60]] = t4[e60];
    return o10;
  }
  getOutputSimplifiedPcbTraces() {
    if (!this.solved || !this.highDensityRouteSolver)
      throw new Error("Cannot get output before solving is complete");
    const e54 = [], t4 = this._getOutputHdRoutes();
    for (const n8 of this.netToPointPairsSolver?.newConnections ?? []) {
      const o10 = n8.__netConnectionName ?? this.originalSrj.connections.find((e60) => e60.name === n8.name)?.__netConnectionName, i8 = t4.filter((e60) => e60.connectionName === n8.name);
      for (let t10 = 0;t10 < i8.length; t10++) {
        const r9 = i8[t10], s7 = { type: "pcb_trace", pcb_trace_id: `${n8.name}_${t10}`, connection_name: o10 ?? n8.__rootConnectionNames?.[0] ?? n8.name, route: Ro(r9, this.srj.layerCount, { connectionPoints: n8.pointsToConnect, defaultViaHoleDiameter: this.viaHoleDiameter, obstacles: this.srj.obstacles, connMap: this.connMap }) };
        e54.push(s7);
      }
    }
    return e54;
  }
  getOutputSimpleRouteJson() {
    return { ...this.originalSrj, traces: this.getOutputSimplifiedPcbTraces() };
  }
};
var Bte = class extends ni {
  bestRoutes;
  bestCost;
  completedPasses = 0;
  cleanupPasses;
  simplifier;
  viaRemovalSolver;
  params;
  constructor(e54) {
    super(), this.params = e54, this.bestRoutes = structuredClone([...e54.config.hdRoutes]), this.bestCost = e54.getCost(this.bestRoutes), this.cleanupPasses = e54.effort <= 1 ? e54.viaRemovalPasses ?? 1 : Math.ceil(2 * e54.effort), this.MAX_ITERATIONS = 1e8 * Math.max(1, this.cleanupPasses), e54.effort <= 1 ? this.viaRemovalSolver = this.createViaRemovalSolver() : (this.simplifier = new WF({ ...e54.config, enableRoutedTraceDetours: true, hdRoutes: structuredClone(this.bestRoutes) }), this.simplifier.simplificationPipelineLoops = 2, this.simplifier.MAX_SIMPLIFICATION_PIPELINE_LOOPS = 2 + this.cleanupPasses, this.simplifier.MAX_ITERATIONS = this.MAX_ITERATIONS);
  }
  createViaRemovalSolver() {
    const e54 = this.params.config, t4 = new aF({ unsimplifiedHdRoutes: structuredClone(this.bestRoutes), otherHdRoutes: e54.otherHdRoutes, obstacles: [...e54.obstacles], colorMap: e54.colorMap, layerCount: e54.layerCount, connMap: e54.connMap, outline: e54.outline ? [...e54.outline] : undefined, geometryShortcutTraceMargin: 0.1, geometryShortcutObstacleMargin: e54.minTraceToPadEdgeClearance ?? 0.15, enableGeometryShortcuts: true, enableRoutedTraceDetours: true, enableObstacleDetourShortcuts: e54.enableCrossingViaReduction, preserveRouteEndpoints: e54.preserveRouteEndpoints, terminalLayerIndicesByPcbPortId: e54.terminalLayerIndicesByPcbPortId });
    return t4.MAX_ITERATIONS = this.MAX_ITERATIONS, t4;
  }
  _step() {
    if (this.viaRemovalSolver) {
      const e60 = this.viaRemovalSolver;
      if (e60.step(), e60.failed)
        return this.failed = true, void (this.error = e60.error);
      if (!e60.solved)
        return;
      const t10 = e60.getOptimizedHdRoutes();
      if (!t10)
        throw new Error("Via removal has no output");
      const n10 = this.params.getCost(t10), o11 = n10.vias < this.bestCost.vias && this.params.isValid(t10);
      return o11 && (this.bestRoutes = structuredClone(t10), this.bestCost = n10), this.completedPasses++, o11 && this.completedPasses < this.cleanupPasses ? void (this.viaRemovalSolver = this.createViaRemovalSolver()) : void (this.solved = true);
    }
    const e54 = this.simplifier;
    if (!e54)
      throw new Error("Cleanup has no active simplifier");
    const { currentPhase: t4, simplificationPipelineLoops: n8 } = e54;
    if (e54.step(), e54.failed)
      return this.failed = true, void (this.error = e54.error);
    const o10 = e54.simplificationPipelineLoops - 2;
    if (this.completedPasses = o10, e54.currentPhase !== t4 || e54.simplificationPipelineLoops !== n8) {
      const t10 = e54.simplifiedHdRoutes, n10 = this.params.getCost(t10);
      (n10.vias < this.bestCost.vias || n10.vias === this.bestCost.vias && n10.points < this.bestCost.points) && this.params.isValid(t10) && (this.bestRoutes = structuredClone(t10), this.bestCost = n10);
    }
    this.solved = e54.solved;
  }
  getOutput() {
    if (!this.solved)
      throw new Error("Cleanup is not complete");
    return this.bestRoutes;
  }
};
var Fte = (e54, t4) => {
  const n8 = Math.min(e54.start.x, e54.end.x), o10 = Math.min(e54.start.y, e54.end.y), i8 = Math.max(e54.start.x, e54.end.x), r9 = Math.max(e54.start.y, e54.end.y), s7 = (e54.start.width + t4.start.width) / 2, a9 = Math.max(0, s7) + 0.000000001;
  return !(Number.isFinite(n8) && Number.isFinite(o10) && Number.isFinite(i8) && Number.isFinite(r9) && Number.isFinite(t4.start.x) && Number.isFinite(t4.start.y) && Number.isFinite(t4.end.x) && Number.isFinite(t4.end.y) && Number.isFinite(s7) && (Math.min(t4.start.x, t4.end.x) > i8 + a9 || Math.max(t4.start.x, t4.end.x) < n8 - a9 || Math.min(t4.start.y, t4.end.y) > r9 + a9 || Math.max(t4.start.y, t4.end.y) < o10 - a9)) && le([e54.start, e54.end], [t4.start, t4.end], { lineThickness: s7 });
};
var jte = (e54, t4) => {
  if (t4.shape === "circle") {
    const n10 = t4.type === "pcb_smtpad" ? t4.radius : t4.outer_diameter / 2;
    return Math.hypot(e54.x - t4.x, e54.y - t4.y) <= n10 + 0.000000001;
  }
  if (t4.type === "pcb_smtpad" && t4.shape === "rect")
    return Math.abs(e54.x - t4.x) <= t4.width / 2 + 0.000000001 && Math.abs(e54.y - t4.y) <= t4.height / 2 + 0.000000001;
  let n8, o10, i8;
  if (t4.type === "pcb_smtpad" && t4.shape === "rotated_rect")
    n8 = t4.width, o10 = t4.height, i8 = t4.ccw_rotation ?? 0;
  else {
    if (!("rect_pad_width" in t4) || !("rect_pad_height" in t4))
      throw new Error(`Unsupported autorouting continuity pad shape: ${t4.shape}`);
    n8 = t4.rect_pad_width, o10 = t4.rect_pad_height, i8 = "rect_ccw_rotation" in t4 && typeof t4.rect_ccw_rotation == "number" ? t4.rect_ccw_rotation : 0;
  }
  const r9 = i8 * Math.PI / 180, s7 = [{ x: -n8 / 2, y: -o10 / 2 }, { x: n8 / 2, y: -o10 / 2 }, { x: n8 / 2, y: o10 / 2 }, { x: -n8 / 2, y: o10 / 2 }].map(({ x: e60, y: n10 }) => ({ x: t4.x + e60 * Math.cos(r9) - n10 * Math.sin(r9), y: t4.y + e60 * Math.sin(r9) + n10 * Math.cos(r9) }));
  for (let t10 = 0;t10 < s7.length; t10++) {
    const n10 = s7[t10], o11 = s7[(t10 + 1) % s7.length], i9 = o11.x - n10.x, r10 = o11.y - n10.y, a9 = (e54.y - n10.y) * i9 - (e54.x - n10.x) * r10, c5 = (e54.x - n10.x) * i9 + (e54.y - n10.y) * r10;
    if (Math.abs(a9) <= 0.000000001 && c5 >= -0.000000001 && c5 <= i9 * i9 + r10 * r10 + 0.000000001)
      return true;
  }
  return ve(e54, s7);
};
var $te = (e54, t4) => e54.route_type === "wire" && (e54.start_pcb_port_id === t4 || e54.end_pcb_port_id === t4);
var Yte = (e54, t4) => {
  if (e54.route_type !== "wire")
    return false;
  return (t4.type === "pcb_smtpad" ? [t4.layer] : t4.layers).includes(e54.layer) && jte(e54, t4);
};
var Xte = (e54, t4) => {
  if (e54.radius === undefined)
    return jte(e54, t4);
  if (t4.shape === "circle") {
    const n10 = t4.type === "pcb_smtpad" ? t4.radius : t4.outer_diameter / 2;
    return Math.hypot(e54.x - t4.x, e54.y - t4.y) <= n10 + e54.radius + 0.000000001;
  }
  const n8 = "rect_pad_width" in t4 ? t4.rect_pad_width : ("width" in t4) ? t4.width : undefined, o10 = "rect_pad_height" in t4 ? t4.rect_pad_height : ("height" in t4) ? t4.height : undefined;
  if (n8 === undefined || o10 === undefined || !("x" in t4) || !("y" in t4))
    throw new Error(`Unsupported autorouting continuity pad shape: ${t4.shape}`);
  const i8 = ("rect_ccw_rotation" in t4 ? t4.rect_ccw_rotation ?? 0 : ("ccw_rotation" in t4) ? t4.ccw_rotation ?? 0 : 0) * Math.PI / 180, r9 = e54.x - t4.x, s7 = e54.y - t4.y, a9 = r9 * Math.cos(i8) + s7 * Math.sin(i8), c5 = -r9 * Math.sin(i8) + s7 * Math.cos(i8);
  return Math.hypot(Math.max(Math.abs(a9) - n8 / 2, 0), Math.max(Math.abs(c5) - o10 / 2, 0)) <= e54.radius + 0.000000001;
};
var Hte = (e54, t4, n8, o10, i8) => {
  const r9 = [e54, t4];
  for (const e60 of r9)
    if (e60.route_type === "wire" && $te(e60, n8.pcb_port_id))
      return { x: e60.x, y: e60.y };
  for (let e60 = 0;e60 < r9.length; e60++) {
    const t10 = r9[e60], s9 = r9[1 - e60];
    if (t10.route_type === "wire" && s9.route_type === "wire" && o10.some((e61) => e61.pcb_port_id !== n8.pcb_port_id && i8.get(e61.pcb_port_id)?.some((e63) => Yte(t10, e63))))
      return { x: s9.x, y: s9.y };
  }
  if (e54.route_type === "wire" && t4.route_type === "wire") {
    const o11 = Math.hypot(e54.x - n8.x, e54.y - n8.y) <= Math.hypot(t4.x - n8.x, t4.y - n8.y) ? e54 : t4;
    return { x: o11.x, y: o11.y };
  }
  for (const e60 of r9)
    if (e60.route_type === "wire")
      return { x: e60.x, y: e60.y };
  const s7 = r9.map((e60) => e60.route_type === "through_pad" ? { x: (e60.start.x + e60.end.x) / 2, y: (e60.start.y + e60.end.y) / 2 } : { x: e60.x, y: e60.y });
  return { x: (s7[0].x + s7[1].x) / 2, y: (s7[0].y + s7[1].y) / 2 };
};
var Vte = (e54) => {
  const t4 = [], n8 = e54.filter((e60) => e60.type === "pcb_port"), o10 = e54.filter((e60) => e60.type === "pcb_trace"), i8 = e54.filter((e60) => e60.type === "source_trace"), r9 = new Map(i8.map((e60) => [e60.source_trace_id, e60])), s7 = new Map, a9 = [...e54.filter((e60) => e60.type === "pcb_smtpad"), ...e54.filter((e60) => e60.type === "pcb_plated_hole")];
  for (const e60 of a9) {
    if (!e60.pcb_port_id)
      continue;
    const t10 = s7.get(e60.pcb_port_id);
    t10 ? t10.push(e60) : s7.set(e60.pcb_port_id, [e60]);
  }
  const c5 = e54.find((e60) => e60.type === "pcb_board"), l5 = ["top", ...fE.filter((e60) => e60.startsWith("inner")).slice(0, c5 ? Math.max(0, c5.num_layers - 2) : undefined), ...c5?.num_layers === 1 ? [] : ["bottom"]], h5 = Qo(e54), d9 = e54.filter((e60) => e60.type === "pcb_via"), u9 = d9.filter((e60) => Number.isFinite(e60.outer_diameter) && e60.outer_diameter > 0).map((e60) => ({ id: e60.pcb_via_id, x: e60.x, y: e60.y, radius: e60.outer_diameter / 2, layers: e60.layers, ownerTraceId: e60.pcb_trace_id })), p9 = [...u9], m9 = [];
  for (const e60 of o10)
    for (let t10 = 0;t10 < e60.route.length; t10++) {
      const n10 = e60.route[t10], o11 = e60.route[t10 + 1];
      if (n10.route_type === "wire" && o11?.route_type === "wire" && n10.layer === o11.layer && m9.push({ trace: e60, start: n10, end: o11 }), n10.route_type !== "via")
        continue;
      const i9 = l5.indexOf(n10.from_layer), r10 = l5.indexOf(n10.to_layer);
      if (i9 < 0 || r10 < 0)
        continue;
      const s9 = n10.outer_diameter;
      if (s9 !== undefined && (!Number.isFinite(s9) || s9 <= 0))
        continue;
      const a10 = { id: e60.pcb_trace_id, x: n10.x, y: n10.y, radius: s9 === undefined ? undefined : s9 / 2, layers: l5.slice(Math.min(i9, r10), Math.max(i9, r10) + 1), ownerTraceId: e60.pcb_trace_id }, c9 = d9.filter((e61) => Math.hypot(e61.x - n10.x, e61.y - n10.y) <= 0.000000001);
      c9.length === 0 && p9.push(a10), c9.some((t11) => t11.pcb_trace_id === e60.pcb_trace_id || !t11.pcb_trace_id && h5.areIdsConnected(t11.pcb_via_id, e60.pcb_trace_id)) || u9.push(a10);
    }
  const g10 = new Map(n8.map((e60) => [e60.pcb_port_id, e60])), f10 = (e60, t10) => {
    const n10 = s7.get(t10.pcb_port_id), o11 = n10?.length ? [...new Set(n10.flatMap((e61) => e61.type === "pcb_smtpad" ? [e61.layer] : e61.layers))] : t10.layers;
    return !!o11.includes(e60.layer) || p9.some((i9) => {
      if (!i9.layers.includes(e60.layer) || !o11.some((e61) => i9.layers.includes(e61)))
        return false;
      const r10 = i9.radius === undefined ? 0 : i9.radius + e60.width / 2;
      return !(Math.hypot(e60.x - i9.x, e60.y - i9.y) > r10 + 0.000000001) && (n10?.length ? n10.some((e61) => (e61.type === "pcb_smtpad" ? [e61.layer] : e61.layers).some((e63) => i9.layers.includes(e63)) && Xte(i9, e61)) : Math.hypot(t10.x - i9.x, t10.y - i9.y) <= 0.000000001);
    });
  };
  for (const n10 of o10)
    for (const [o11, i9] of n10.route.entries())
      if (i9.route_type === "wire")
        for (const r10 of new Set([i9.start_pcb_port_id, i9.end_pcb_port_id])) {
          if (!r10)
            continue;
          const a10 = g10.get(r10);
          if (!a10 || f10(i9, a10))
            continue;
          const c9 = s7.get(r10), l10 = c9?.length ? [...new Set(c9.flatMap((e60) => e60.type === "pcb_smtpad" ? [e60.layer] : e60.layers))] : a10.layers;
          t4.push({ type: "pcb_trace_error", error_type: "pcb_trace_error", pcb_trace_error_id: `missing_layer_connection_${n10.pcb_trace_id}_${o11}_${a10.pcb_port_id}`, pcb_trace_id: n10.pcb_trace_id, source_trace_id: n10.source_trace_id ?? `!${n10.pcb_trace_id}`, pcb_port_ids: [a10.pcb_port_id], pcb_component_ids: a10.pcb_component_id ? [a10.pcb_component_id] : [], center: { x: i9.x, y: i9.y }, message: `Trace [${oz(e54, n10.pcb_trace_id)}] on ${i9.layer} is missing a via connection to port [${nz(e54, a10.pcb_port_id)}] on ${l10.join(", ")}.` });
        }
  const _5 = new Map(o10.map((e60) => [e60.pcb_trace_id, new Set([...s7].filter(([, t10]) => [e60.route[0], e60.route.at(-1)].some((e61) => e61 && t10.some((t11) => Yte(e61, t11)))).map(([e61]) => e61))])), y10 = new Map;
  for (const [e60, t10] of _5)
    for (const n10 of t10) {
      const t11 = y10.get(n10);
      t11 ? t11.push(e60) : y10.set(n10, [e60]);
    }
  const b10 = new Map, x8 = (e60, t10) => {
    const n10 = b10.get(e60);
    if (n10)
      return n10.has(t10);
    const o11 = [e60], i9 = new Set(o11), r10 = new Set;
    for (;o11.length > 0; ) {
      const e61 = o11.pop();
      for (const t11 of _5.get(e61))
        if (!r10.has(t11)) {
          r10.add(t11);
          for (const e63 of y10.get(t11))
            i9.has(e63) || (i9.add(e63), o11.push(e63));
        }
    }
    for (const e61 of i9)
      b10.set(e61, r10);
    return r10.has(t10);
  };
  let v10;
  const I6 = () => {
    if (v10)
      return v10;
    const e60 = new Jo({}), t10 = [], n10 = m9.map((e61, t11) => ({ ...e61, order: t11, minX: Math.min(e61.start.x, e61.end.x) - e61.start.width / 2 - 0.000000001, minY: Math.min(e61.start.y, e61.end.y) - e61.start.width / 2 - 0.000000001, maxX: Math.max(e61.start.x, e61.end.x) + e61.start.width / 2 + 0.000000001, maxY: Math.max(e61.start.y, e61.end.y) + e61.start.width / 2 + 0.000000001 })), i9 = new G().load(n10);
    for (const e61 of n10)
      for (const n11 of i9.search(e61))
        n11.order <= e61.order || n11.trace.pcb_trace_id === e61.trace.pcb_trace_id || n11.start.layer !== e61.start.layer || Fte(e61, n11) && t10.push([e61.trace.pcb_trace_id, n11.trace.pcb_trace_id]);
    for (const e61 of o10) {
      for (const n11 of _5.get(e61.pcb_trace_id))
        t10.push([e61.pcb_trace_id, n11]);
      for (const n11 of e61.route)
        if (n11.route_type === "wire")
          for (const o11 of new Set([n11.start_pcb_port_id, n11.end_pcb_port_id])) {
            if (!o11)
              continue;
            const i10 = g10.get(o11);
            i10 && f10(n11, i10) && t10.push([e61.pcb_trace_id, o11]);
          }
    }
    const r10 = [], s9 = (e61, t11, n11, o11, i10 = false) => {
      if (n11.isEmpty())
        return;
      const s10 = n11.scale(1e6, 1e6), a10 = s10.box;
      r10.push({ id: e61, layers: t11, geometry: { kind: "polygon", polygon: s10 }, bridge: o11, platedPort: i10, minX: a10.xmin, minY: a10.ymin, maxX: a10.xmax, maxY: a10.ymax });
    };
    for (const e61 of u9)
      e61.radius !== undefined && (s9(e61.id, e61.layers, ZL(e61, e61.radius), true), e61.ownerTraceId && t10.push([e61.id, e61.ownerTraceId]));
    for (const e61 of a9)
      e61.type === "pcb_plated_hole" && e61.pcb_port_id && s9(e61.pcb_port_id, e61.layers, QL(e61), true, true);
    for (const e61 of m9) {
      if (e61.trace.route_thickness_mode === "interpolated" || e61.start.x === e61.end.x && e61.start.y === e61.end.y)
        continue;
      const t11 = e61.start.width / 2;
      !Number.isFinite(t11) || t11 <= 0 ? s9(e61.trace.pcb_trace_id, [e61.start.layer], KL(e61.start, e61.end, e61.start.width), false) : r10.push({ id: e61.trace.pcb_trace_id, layers: [e61.start.layer], geometry: { kind: "segment", segment: e61 }, bridge: false, platedPort: false, minX: 1e6 * (Math.min(e61.start.x, e61.end.x) - t11) - 0.1, minY: 1e6 * (Math.min(e61.start.y, e61.end.y) - t11) - 0.1, maxX: 1e6 * (Math.max(e61.start.x, e61.end.x) + t11) + 0.1, maxY: 1e6 * (Math.max(e61.start.y, e61.end.y) + t11) + 0.1 });
    }
    const c9 = (e61) => {
      const t11 = e61.geometry;
      if (t11.kind === "polygon")
        return t11.polygon;
      if (!t11.polygon) {
        const { start: e63, end: n11 } = t11.segment;
        t11.polygon = KL(e63, n11, e63.width).scale(1e6, 1e6);
      }
      return t11.polygon;
    }, l10 = new G().load(r10);
    for (const e61 of r10)
      if (e61.bridge)
        for (const n11 of l10.search({ minX: e61.minX - 0.1, minY: e61.minY - 0.1, maxX: e61.maxX + 0.1, maxY: e61.maxY + 0.1 })) {
          if (n11.id === e61.id || e61.platedPort && n11.bridge || n11.platedPort && e61.bridge || !n11.layers.some((t11) => e61.layers.includes(t11)))
            continue;
          const o11 = c9(n11), i10 = o11.box;
          o11.isEmpty() || i10.xmax < e61.minX - 0.1 || i10.ymax < e61.minY - 0.1 || i10.xmin > e61.maxX + 0.1 || i10.ymin > e61.maxY + 0.1 || ez(c9(e61), o11, 0.1) && t10.push([e61.id, n11.id]);
        }
    return e60.addConnections(t10), v10 = e60, e60;
  }, S6 = (e60, t10) => {
    const n10 = t10 === "start" ? e60.route[0] : e60.route.at(-1), o11 = ((e61, t11) => {
      if (e61.route_thickness_mode === "interpolated")
        return;
      let n11 = t11 === "start" ? 0 : e61.route.length - 2;
      const o12 = t11 === "start" ? 1 : -1;
      for (;n11 >= 0 && n11 < e61.route.length - 1; ) {
        const t12 = e61.route[n11], i10 = e61.route[n11 + 1];
        if (t12.route_type !== "wire" || i10.route_type !== "wire" || t12.layer !== i10.layer)
          return;
        if (Math.hypot(t12.x - i10.x, t12.y - i10.y) > 0.000000001)
          return t12.width;
        n11 += o12;
      }
    })(e60, t10);
    if (n10?.route_type !== "wire" || o11 === undefined)
      return false;
    const i9 = h5.getNetConnectedToId(e60.pcb_trace_id);
    if (!i9)
      return false;
    const r10 = m9.filter((e61) => e61.trace.route_thickness_mode !== "interpolated" && h5.getNetConnectedToId(e61.trace.pcb_trace_id) === i9 && Math.hypot(e61.start.x - e61.end.x, e61.start.y - e61.end.y) > 0.000000001);
    return !!r10.some((t11) => t11.trace.pcb_trace_id !== e60.pcb_trace_id && t11.start.layer === n10.layer && pe(n10, t11.start, t11.end) <= (o11 + t11.start.width) / 2 + 0.000000001) || !(!Number.isFinite(o11) || o11 <= 0) && u9.some((t11) => {
      if (t11.ownerTraceId === e60.pcb_trace_id || !t11.layers.includes(n10.layer) || h5.getNetConnectedToId(t11.id) !== i9)
        return false;
      const s9 = t11.radius === undefined ? 0 : t11.radius + o11 / 2;
      return !(Math.hypot(n10.x - t11.x, n10.y - t11.y) > s9 + 0.000000001) && (!!a9.some((e61) => h5.getNetConnectedToId(jL(e61)) === i9 && (e61.type === "pcb_smtpad" ? [e61.layer] : e61.layers).some((e63) => t11.layers.includes(e63)) && Xte(t11, e61)) || r10.some((n11) => n11.trace.pcb_trace_id !== e60.pcb_trace_id && t11.layers.includes(n11.start.layer) && Number.isFinite(n11.start.width) && n11.start.width > 0 && pe(t11, n11.start, n11.end) <= (t11.radius === undefined ? 0 : t11.radius + n11.start.width / 2) + 0.000000001));
    });
  }, C = new Set;
  for (const i9 of o10) {
    if (i9.route.length === 0)
      continue;
    const o11 = i9.route[0], a10 = i9.route.at(-1), c9 = r9.get(i9.source_trace_id), h9 = c9 ? n8.filter((e60) => c9.connected_source_port_ids?.includes(e60.source_port_id)) : [];
    let u10;
    const p10 = { type: "pcb_trace_error", error_type: "pcb_trace_error", source_trace_id: c9?.source_trace_id || i9.source_trace_id || `!${i9.pcb_trace_id}`, pcb_trace_id: i9.pcb_trace_id, pcb_component_ids: [] };
    for (let n10 = 1;n10 < i9.route.length - 1; n10++) {
      const o12 = i9.route[n10 - 1], r10 = i9.route[n10], s9 = i9.route[n10 + 1];
      if (r10.route_type !== "via" || o12.route_type !== "wire" || s9.route_type !== "wire")
        continue;
      const a11 = l5.indexOf(r10.from_layer), c10 = l5.indexOf(r10.to_layer), h10 = d9.filter((e60) => e60.pcb_trace_id === i9.pcb_trace_id && Math.abs(e60.x - r10.x) < 0.01 && Math.abs(e60.y - r10.y) < 0.01), m11 = h10.length > 0 ? h10.map((e60) => e60.layers) : [l5.slice(Math.min(a11, c10), Math.max(a11, c10) + 1)], g12 = Math.abs(o12.x - r10.x) < 0.01 && Math.abs(o12.y - r10.y) < 0.01, f11 = Math.abs(s9.x - r10.x) < 0.01 && Math.abs(s9.y - r10.y) < 0.01;
      a11 >= 0 && c10 >= 0 && l5.includes(o12.layer) && l5.includes(s9.layer) && m11.some((e60) => e60.includes(o12.layer) && e60.includes(s9.layer)) && (g12 || o12.layer === r10.from_layer) && (f11 || s9.layer === r10.to_layer) || (u10 ??= oz(e54, i9.pcb_trace_id), t4.push({ ...p10, message: `Via in trace [${u10}] does not connect its adjacent wire layers at position {x: ${r10.x}, y: ${r10.y}}.`, pcb_trace_error_id: `misaligned_via_${i9.pcb_trace_id}_${n10}`, pcb_port_ids: [] }));
    }
    if (c9 && h9.length > 0) {
      if (C.has(c9.source_trace_id))
        continue;
      C.add(c9.source_trace_id);
    }
    for (const n10 of h9) {
      const r10 = s7.get(n10.pcb_port_id);
      if (!r10?.length)
        continue;
      if ([o11, a10].some((e60) => r10.some((t10) => Yte(e60, t10))))
        continue;
      if (x8(i9.pcb_trace_id, n10.pcb_port_id))
        continue;
      const c10 = I6(), l10 = c10.getNetConnectedToId(i9.pcb_trace_id);
      if (l10 !== undefined && c10.getIdsConnectedToNet(l10).some((e60) => _5.get(e60)?.has(n10.pcb_port_id)))
        continue;
      const d10 = nz(e54, n10.pcb_port_id);
      u10 ??= oz(e54, i9.pcb_trace_id), t4.push({ ...p10, message: `Trace [${u10}] is missing a connection to ${r10[0].type === "pcb_smtpad" ? "SMD pad" : "through-hole pad"} ${d10}`, pcb_trace_error_id: `missing_connection_${i9.pcb_trace_id}_${n10.pcb_port_id}`, center: Hte(o11, a10, n10, h9, s7), pcb_port_ids: [n10.pcb_port_id] });
    }
    if (h9.length > 0)
      continue;
    const m10 = [...s7.values()].some((e60) => e60.some((e61) => Yte(o11, e61))) || S6(i9, "start"), g11 = o11.route_type === "wire" && a10.route_type === "wire" && o11.layer === a10.layer && Math.hypot(o11.x - a10.x, o11.y - a10.y) <= 0.000000001;
    for (const [n10, r10] of [o11, a10].entries())
      r10.route_type === "wire" && (n10 === 1 && g11 && !m10 || [...s7.values()].some((e60) => e60.some((e61) => Yte(r10, e61))) || S6(i9, n10 === 0 ? "start" : "end") || (u10 ??= oz(e54, i9.pcb_trace_id), t4.push({ ...p10, message: `Trace [${u10}] has disconnected endpoint at (${r10.x.toFixed(2)}, ${r10.y.toFixed(2)})`, pcb_trace_error_id: `disconnected_endpoint_${i9.pcb_trace_id}_${n10 === 0 ? "start" : "end"}`, center: { x: r10.x, y: r10.y }, pcb_port_ids: [] })));
  }
  return t4;
};
var Wte = (e54, t4) => {
  const n8 = new Set(t4.flatMap((e60) => e60.__replaces_pcb_trace_id ? [e60.__replaces_pcb_trace_id] : []));
  return [...e54.filter((e60) => !n8.has(e60.pcb_trace_id)), ...t4];
};
var Gte = ({ inputSrj: e54, srjWithPointPairs: t4, drcOptions: n8 = {}, includeBoardClearance: o10 = false, connectivityMaps: i8 }) => {
  const r9 = { minTraceWidth: e54.minTraceWidth, minViaDiameter: e54.minViaDiameter, originalSrj: e54, includeOriginalConnections: true, connectivityMaps: i8 }, s7 = o10 ? rR({ ...e54, minBoardEdgeClearance: e54.minBoardEdgeClearance ?? 0 }) : undefined, a9 = sR(t4, [], r9);
  s7 && a9.push(s7);
  const c5 = dz(a9, { traceClearance: n8.traceClearance ?? hR, holeClearance: n8.holeClearance ?? e54.minTraceToHoleEdgeClearance }), l5 = uz(a9, { allowViaInPad: e54.allowViaInPad, minClearance: n8.viaToPadClearance ?? vte(e54) });
  return (o11, i9 = {}) => {
    const a10 = Wte(e54.traces ?? [], o11), h5 = sR(t4, a10, r9);
    s7 && h5.push(s7);
    const d9 = qy(h5);
    aR(h5);
    const u9 = c5(h5, d9), p9 = [...u9.traceErrors, ...lR(h5, { board: s7 }), ...(i9.includeTraceContinuity ?? n8.includeTraceContinuity) === false ? [] : Vte(h5), ...n8.includeTypedTraceClearance === false ? [] : [...u9.viaErrors, ...u9.padErrors], ...u9.holeErrors, ...l5(h5, d9), ...rz(h5, d9, { viaClearance: n8.viaClearance ?? dR })], m9 = new Map(h5.flatMap((e60) => e60.type === "pcb_via" ? [[e60.pcb_via_id, e60]] : [])), g10 = p9.map((e60) => {
      if (e60.type === "pcb_via_trace_clearance_error") {
        const t10 = m9.get(e60.pcb_via_id);
        if (t10)
          return { ...e60, center: { x: t10.x, y: t10.y } };
      }
      return e60.center ? e60 : e60.pcb_center ? { ...e60, center: e60.pcb_center } : e60;
    });
    return { circuitJson: h5, errors: p9, errorsWithCenters: g10, locationAwareErrors: g10.filter((e60) => Boolean(e60.center)) };
  };
};
var Zte = class extends ni {
  constructor(e54) {
    super(), this.input = e54;
  }
  static solverName = "Pipeline9HighDensityForceImproveSampleSolver";
  output;
  _step() {
    const e54 = new SZ(this.input), t4 = e54.sampleEntries[0];
    if (this.input.nodeWithPortPoints.length !== 1 || e54.sampleEntries.length !== 1 || t4.routeIndexes.length !== this.input.hdRoutes.length || t4.routeIndexes.some((e60, t10) => e60 !== t10))
      throw new Error("Force-improve task must contain one preassigned node");
    if (e54.step(), !e54.solved || e54.failed || e54.iterations !== 1)
      throw new Error("Force-improve node must complete in one step");
    this.output = { routes: e54.getOutput(), latestVisualization: e54.latestVisualization }, this.solved = true;
  }
  getOutput() {
    if (!this.output)
      throw new Error("Force-improve node has not completed");
    return this.output;
  }
};
SolverRuntime.registerSolver(Zte);
var qte = class extends SZ {
  asyncRunning = false;
  completedSample;
  async solveAsync(e54, t4 = 1 / 0) {
    if (this.asyncRunning)
      throw new Error("High-density force improvement solveAsync is already running");
    if (this.solved || this.failed || this.iterations >= t4)
      return;
    const n8 = performance.now();
    this.asyncRunning = true;
    try {
      if (e54 === undefined)
        return void this.solveUntilIteration(t4);
      const n10 = Math.max(0, Math.floor(Math.min(this.MAX_ITERATIONS, t4) - this.iterations)), o10 = this.sampleEntries.slice(this.activeSampleIndex, this.activeSampleIndex + n10).map((t10) => e54.executeAsync(Zte, { nodeWithPortPoints: [t10.node], hdRoutes: t10.routeIndexes.map((e60) => this.originalHdRoutes[e60]), totalStepsPerNode: this.totalStepsPerNode, nodeAssignmentMargin: this.nodeAssignmentMargin, colorMap: Object.fromEntries(t10.routeIndexes.map((e60) => {
        const t11 = this.originalHdRoutes[e60].connectionName;
        return [t11, this.colorMap[t11]];
      })) }).then((e60) => ({ type: "result", result: e60 }), (e60) => ({ type: "error", error: e60 })));
      for (const e60 of o10) {
        if (this.solved || this.failed || this.iterations >= Math.min(this.MAX_ITERATIONS, t4))
          break;
        const n11 = await e60;
        if (n11.type === "error")
          throw n11.error;
        this.completedSample = n11.result, this.step();
      }
      this.solveUntilIteration(t4);
    } catch (e60) {
      throw this.failed = true, this.error = `High-density force improvement runtime error: ${e60}`, e60;
    } finally {
      this.completedSample = undefined, this.asyncRunning = false, this.timeToSolve = performance.now() - n8;
    }
  }
  solveUntilIteration(e54) {
    for (;!this.solved && !this.failed && this.iterations < e54; )
      this.step();
  }
  _step() {
    const e54 = this.completedSample;
    if (!e54)
      return void super._step();
    this.completedSample = undefined;
    const t4 = this.sampleEntries[this.activeSampleIndex];
    if (!t4 || e54.routes.length !== t4.routeIndexes.length)
      throw new Error("Force-improve result does not match the current node");
    for (const [n8, o10] of t4.routeIndexes.entries())
      this.improvedRoutesByIndex.set(o10, e54.routes[n8]);
    this.latestVisualization = e54.latestVisualization, this.activeSampleIndex += 1, this.stats = { nodeAssignmentMargin: this.nodeAssignmentMargin, sampleCount: this.sampleEntries.length, improvedNodeCount: this.activeSampleIndex, improvedRouteCount: this.improvedRoutesByIndex.size, totalStepsPerNode: this.totalStepsPerNode }, this.activeSampleIndex >= this.sampleEntries.length && (this.solved = true);
  }
};
var Jte = (e54, t4) => {
  const n8 = e54.filter((e60) => (e60.rootConnectionName ?? e60.connectionName) === t4);
  if (n8.length !== 0)
    return n8.reduce((e60, t10) => e60 + t10.route.slice(1).reduce((e61, n10, o10) => {
      const i8 = t10.route[o10];
      return e61 + Math.hypot(n10.x - i8.x, n10.y - i8.y);
    }, 0), 0);
};
var Qte = (e54, t4) => {
  const n8 = new Set(e54.flatMap((e60) => e60.maxLengthSkew === undefined ? [] : e60.connectionNames));
  return t4.flatMap((e60) => {
    if (!n8.has(e60.name))
      return [];
    const t10 = e60.pointsToConnect[0], o10 = e60.pointsToConnect.at(-1);
    if (!t10 || !o10 || t10 === o10)
      throw new Error(`Length matching: bus connection "${e60.name}" needs at least two points`);
    return [{ ...e60, pointsToConnect: [t10, o10] }];
  });
};
var Kte = class extends ni {
  constructor(e54) {
    super(), this.params = e54, this.differentialPairSolver = new o9({ hdRoutes: e54.hdRoutes, differentialPairs: e54.differentialPairs, traces: e54.traces, obstacles: e54.obstacles, bounds: e54.bounds, layerCount: e54.layerCount, minTraceToPadEdgeClearance: e54.obstacleMargin }), this.MAX_ITERATIONS = this.differentialPairSolver.MAX_ITERATIONS + 1e5 + 10;
  }
  differentialPairSolver;
  busLengthMatchingSolver;
  outputHdRoutes;
  getSolverName() {
    return "LengthMatchingPostProcessingSolver";
  }
  _step() {
    if (!this.differentialPairSolver.solved)
      return this.differentialPairSolver.step(), void (this.differentialPairSolver.failed && (this.failed = true, this.error = this.differentialPairSolver.error));
    if (!this.busLengthMatchingSolver) {
      const n8 = this.differentialPairSolver.getOutput().hdRoutes, o10 = (e54 = this.params.buses, t4 = n8, e54.flatMap((e60) => {
        const n10 = e60.maxLengthSkew;
        if (n10 === undefined || e60.connectionNames.length < 2)
          return [];
        const o11 = e60.connectionNames.map((n11) => {
          const o12 = Jte(t4, n11);
          if (o12 === undefined)
            throw new Error(`Length matching: bus "${e60.busId}" has no routed geometry for connection "${n11}"`);
          return { connectionName: n11, length: o12 };
        }), i8 = o11.reduce((e61, t10) => t10.length > e61.length ? t10 : e61);
        return o11.flatMap((e61) => e61.connectionName === i8.connectionName ? [] : [{ connectionNames: [e61.connectionName, i8.connectionName], lengthTolerance: n10 }]);
      }));
      return o10.length === 0 ? (this.outputHdRoutes = n8, void (this.solved = true)) : void (this.busLengthMatchingSolver = new v6({ hdRoutes: n8, originalConnections: Qte(this.params.buses, this.params.connections), differentialPairs: o10, traces: this.params.traces, obstacles: this.params.obstacles, bounds: this.params.bounds, layerCount: this.params.layerCount, obstacleMargin: this.params.obstacleMargin }));
    }
    var e54, t4;
    if (this.busLengthMatchingSolver.step(), this.busLengthMatchingSolver.failed)
      return this.failed = true, void (this.error = this.busLengthMatchingSolver.error);
    this.busLengthMatchingSolver.solved && (this.outputHdRoutes = this.busLengthMatchingSolver.getOutput().matchedHdRoutes, ((e60, t10) => {
      for (const n8 of e60) {
        if (n8.maxLengthSkew === undefined || n8.connectionNames.length < 2)
          continue;
        const e61 = n8.connectionNames.map((e63) => {
          const o11 = Jte(t10, e63);
          if (o11 === undefined)
            throw new Error(`Length matching: bus "${n8.busId}" lost routed geometry for connection "${e63}"`);
          return o11;
        }), o10 = Math.max(...e61) - Math.min(...e61);
        if (o10 > n8.maxLengthSkew + 0.000001)
          throw new Error(`Length matching: bus "${n8.busId}" routed length skew ${o10.toFixed(4)}mm exceeds ${n8.maxLengthSkew.toFixed(4)}mm`);
      }
    })(this.params.buses, this.outputHdRoutes), this.solved = true);
  }
  getOutput() {
    if (!this.solved || !this.outputHdRoutes)
      throw new Error("LengthMatchingPostProcessingSolver output requested before completion");
    return { hdRoutes: this.outputHdRoutes };
  }
  visualize() {
    return this.busLengthMatchingSolver?.visualize() ?? this.differentialPairSolver.visualize();
  }
};
var ene = 0.000000001;
var tne = (e54, t4) => Math.abs(e54.x - t4.x) <= ene && Math.abs(e54.y - t4.y) <= ene && e54.z === t4.z;
var nne = (e54, t4) => {
  if (e54.length === 0)
    return void e54.push(...t4.route);
  const n8 = e54.at(-1);
  if (t4.route[0] && tne(n8, t4.route[0]))
    e54.push(...t4.route.slice(1));
  else {
    if (!t4.route.at(-1) || !tne(n8, t4.route.at(-1)))
      throw new Error(`Pipeline9 could not reconnect mutated preloaded segment "${t4.connectionName}"`);
    e54.push(...t4.route.slice(0, -1).reverse());
  }
};
var one = (e54, t4) => {
  const n8 = e54.preloadedRoutePositionStart ?? e54.preloadedRouteIndex, o10 = t4.preloadedRoutePositionStart ?? t4.preloadedRouteIndex, i8 = e54.preloadedRoutePositionEnd ?? n8, r9 = t4.preloadedRoutePositionEnd ?? o10;
  return n8 - o10 || i8 - r9 || e54.preloadedRouteIndex - t4.preloadedRouteIndex || e54.connectionName.localeCompare(t4.connectionName);
};
var ine = (e54) => {
  const t4 = e54.route.flatMap((e60) => e60.route_type === "wire" || e60.route_type === "through_obstacle" ? [e60.width] : []);
  return t4.length > 0 ? Math.max(...t4) : undefined;
};
var rne = ({ trace: e54, updatedTraceRoutes: t4, layerCount: n8, defaultViaHoleDiameter: o10, obstacles: i8, connMap: r9 }) => {
  if (t4.length === 0)
    throw new Error(`Pipeline9 lost every fixed route for mutated trace "${e54.pcb_trace_id}"`);
  const s7 = [];
  let a9, c5 = 0, l5 = 0;
  for (const e60 of [...t4].sort(one))
    nne(s7, e60), c5 = Math.max(c5, e60.traceThickness), l5 = Math.max(l5, e60.viaDiameter), a9 ??= e60.rootConnectionName;
  const h5 = { connectionName: e54.connection_name, rootConnectionName: a9, traceThickness: ine(e54) ?? c5, viaDiameter: l5, route: s7, vias: s7.slice(0, -1).flatMap((e60, t10) => {
    const n10 = s7[t10 + 1];
    return e60.z !== n10.z && Math.abs(e60.x - n10.x) <= ene && Math.abs(e60.y - n10.y) <= ene ? [{ x: n10.x, y: n10.y }] : [];
  }) };
  return Ro(h5, n8, { defaultViaHoleDiameter: o10, obstacles: i8, connMap: r9 });
};
var sne = (e54, t4) => e54.filter((e60) => {
  if (e60.isThroughObstacle === true)
    return false;
  const { preloadedRoutePositionStart: n8, preloadedRoutePositionEnd: o10 } = e60;
  if (n8 === undefined || o10 === undefined)
    throw new Error(`Pipeline9 fixed route "${e60.connectionName}" is missing route-position metadata`);
  const i8 = Math.min(n8, o10), r9 = Math.max(n8, o10);
  return i8 >= t4.routePositionStart - ene && r9 <= t4.routePositionEnd + ene;
});
var ane = ({ trace: e54, originalTraceRoutes: t4, updatedTraceRoutes: n8, layerCount: o10, defaultViaHoleDiameter: i8, obstacles: r9, connMap: s7 }) => {
  if (n8.length === 0)
    throw new Error(`Pipeline9 lost every fixed route for mutated trace "${e54.pcb_trace_id}"`);
  const a9 = ((e60) => {
    const t10 = [];
    let n10 = 0;
    for (let o11 = 0;o11 < e60.route.length; o11++)
      e60.route[o11]?.route_type === "through_obstacle" && (n10 < o11 && t10.push({ routePositionStart: n10, routePositionEnd: o11 - 1 }), n10 = o11 + 1);
    return n10 < e60.route.length && t10.push({ routePositionStart: n10, routePositionEnd: e60.route.length - 1 }), t10;
  })(e54), c5 = n8.filter((e60) => e60.isThroughObstacle !== true);
  for (const e60 of c5) {
    if (a9.filter((t10) => sne([e60], t10).includes(e60)).length !== 1)
      throw new Error(`Pipeline9 fixed route "${e60.connectionName}" crosses an immutable through-obstacle primitive`);
  }
  const l5 = [];
  let h5 = 0;
  for (const c9 of a9) {
    l5.push(...e54.route.slice(h5, c9.routePositionStart));
    const a10 = sne(t4, c9), d9 = sne(n8, c9);
    if (a10.length > 0 && d9.length === 0)
      throw new Error(`Pipeline9 lost every fixed route for an ordinary section of mutated trace "${e54.pcb_trace_id}"`);
    l5.push(...d9.length > 0 ? rne({ trace: e54, updatedTraceRoutes: d9, layerCount: o10, defaultViaHoleDiameter: i8, obstacles: r9, connMap: s7 }) : e54.route.slice(c9.routePositionStart, c9.routePositionEnd + 1)), h5 = c9.routePositionEnd + 1;
  }
  return l5.push(...e54.route.slice(h5)), l5;
};
var cne = (e54, t4) => {
  const n8 = new Set(t4.map((e60) => e60.pcb_trace_id));
  return e54.map((e60) => {
    if (!n8.has(e60.pcb_trace_id))
      return n8.add(e60.pcb_trace_id), e60;
    const t10 = `${e60.pcb_trace_id}_routed`;
    let o10 = t10, i8 = 2;
    for (;n8.has(o10); )
      o10 = `${t10}_${i8}`, i8 += 1;
    return n8.add(o10), { ...e60, pcb_trace_id: o10 };
  });
};
var lne = (e54, t4, n8) => {
  const o10 = (e60) => `${e60.x}:${e60.y}`, i8 = new Map;
  for (const e60 of t4) {
    const t10 = o10(e60.center), n10 = i8.get(t10) ?? [];
    n10.push(e60), i8.set(t10, n10);
  }
  const r9 = new Map;
  for (const t10 of e54)
    for (const e60 of t10.pointsToConnect) {
      if (!e60.pcb_port_id)
        continue;
      const t11 = r9.get(e60.pcb_port_id) ?? new Set, s7 = So(e60);
      for (const e61 of s7)
        t11.add(mo(e61, n8));
      for (const r10 of i8.get(o10(e60)) ?? [])
        if (!(r10.layers.length <= 1) && r10.connectedTo.includes(e60.pcb_port_id))
          for (const e61 of r10.layers)
            t11.add(mo(e61, n8));
      r9.set(e60.pcb_port_id, t11);
    }
  return r9;
};
var hne = (e54, t4) => new Map(e54.flatMap((e60) => {
  const n8 = t4.getNetConnectedToId(e60.connectionName) ?? (e60.rootConnectionName ? t4.getNetConnectedToId(e60.rootConnectionName) ?? (t4.netMap[e60.rootConnectionName] ? e60.rootConnectionName : undefined) : undefined);
  return n8 ? [[e60.connectionName, n8]] : [];
}));
var dne = 0.000000001;
var une = 0.000001;
var pne = (e54, t4) => Math.abs(e54.x - t4.x) <= une && Math.abs(e54.y - t4.y) <= une && e54.z === t4.z;
var mne = (e54) => new Map(e54.map((e60, t4) => [e60.pcb_trace_id, t4]));
var gne = (e54, t4) => {
  const n8 = e54[0], o10 = e54.at(-1);
  if (!n8 || !o10)
    throw new Error("Pipeline9 cannot split an empty preloaded route");
  if (n8.z !== o10.z)
    throw new Error("Pipeline9 cannot partially split a preloaded layer transition");
  return { ...n8, x: n8.x + (o10.x - n8.x) * t4, y: n8.y + (o10.y - n8.y) * t4 };
};
var fne = ({ traces: e54, fixedHdRoutes: t4, sections: n8 }) => {
  const o10 = (({ traces: e60, sections: t10 }) => {
    const n10 = mne(e60), o11 = new Map;
    for (const e61 of t10) {
      const t11 = n10.get(e61.traceId);
      if (t11 === undefined)
        throw new Error(`Pipeline9 hypergraph changed missing preloaded trace "${e61.traceId}"`);
      const i8 = o11.get(t11) ?? [];
      i8.push({ start: Math.min(e61.startRoutePosition, e61.endRoutePosition), end: Math.max(e61.startRoutePosition, e61.endRoutePosition) }), o11.set(t11, i8);
    }
    for (const e61 of o11.values())
      e61.sort((e63, t11) => e63.start - t11.start || e63.end - t11.end);
    return o11;
  })({ traces: e54, sections: n8 });
  return t4.flatMap((e60) => {
    const t10 = o10.get(e60.preloadedTraceIndex);
    if (!t10?.length)
      return [e60];
    const { preloadedRoutePositionStart: n10, preloadedRoutePositionEnd: i8 } = e60;
    if (n10 === undefined || i8 === undefined)
      throw new Error(`Pipeline9 fixed route "${e60.connectionName}" is missing route-position metadata`);
    if (Math.abs(i8 - n10) <= dne)
      return t10.some((e61) => e61.start - dne <= n10 && n10 <= e61.end + dne) ? [] : [e60];
    let r9 = [{ start: n10, end: i8 }];
    for (const e61 of t10)
      r9 = r9.flatMap((t11) => {
        if (e61.end <= t11.start + dne || e61.start >= t11.end - dne)
          return [t11];
        const n11 = [];
        return e61.start > t11.start + dne && n11.push({ start: t11.start, end: Math.min(e61.start, t11.end) }), e61.end < t11.end - dne && n11.push({ start: Math.max(e61.end, t11.start), end: t11.end }), n11;
      });
    return r9.map((t11, o11) => {
      const r10 = (t11.start - n10) / (i8 - n10), s7 = (t11.end - n10) / (i8 - n10);
      return { ...e60, connectionName: `${e60.connectionName}_hypergraph_fixed_${o11}`, preloadedRoutePositionStart: t11.start, preloadedRoutePositionEnd: t11.end, route: [gne(e60.route, r10), gne(e60.route, s7)], vias: [] };
    });
  });
};
var _ne = ({ traces: e54, sections: t4, stitchedHdRoutes: n8, layerCount: o10 }) => {
  const i8 = mne(e54);
  return t4.map((e60, r9) => {
    const s7 = i8.get(e60.traceId);
    if (s7 === undefined)
      throw new Error(`Pipeline9 cannot materialize missing preloaded trace "${e60.traceId}"`);
    const [a9, c5] = ((e61, t10) => {
      const n10 = e61.connection.pointsToConnect.map((e63) => ({ x: e63.x, y: e63.y, z: mo(Io(e63), t10) }));
      if (!n10[0] || !n10[1])
        throw new Error(`Pipeline9 changed section "${e61.connectionName}" is missing an endpoint`);
      return [n10[0], n10[1]];
    })(e60, o10), l5 = n8.flatMap((t10) => {
      if (t10.connectionName !== e60.connectionName)
        return [];
      const n10 = (({ route: e61, sectionStart: t11, sectionEnd: n11 }) => {
        const o11 = e61.route[0], i9 = e61.route.at(-1);
        if (!o11 || !i9)
          return null;
        const r10 = o11.z === t11.z && i9.z === n11.z, s9 = o11.z === n11.z && i9.z === t11.z, a10 = r10 ? me(o11, t11) + me(i9, n11) : Number.POSITIVE_INFINITY, c9 = s9 ? me(o11, n11) + me(i9, t11) : Number.POSITIVE_INFINITY;
        return Number.isFinite(a10) || Number.isFinite(c9) ? a10 <= c9 ? { score: a10, reverse: false } : { score: c9, reverse: true } : null;
      })({ route: t10, sectionStart: a9, sectionEnd: c5 });
      return n10 ? [{ route: t10, ...n10 }] : [];
    });
    l5.sort((e61, t10) => e61.score - t10.score);
    const h5 = l5[0], d9 = l5[1];
    if (!h5 || d9 && Math.abs(d9.score - h5.score) <= une)
      throw new Error(`Pipeline9 expected one nearest stitched route for changed preloaded section "${e60.connectionName}", got ${l5.length}`);
    const u9 = (({ route: e61, reverse: t10, sectionStart: n10, sectionEnd: o11 }) => {
      const i9 = t10 ? ((e63) => {
        const t11 = [...e63].reverse().map((e64) => {
          const { toNextSegmentType: t12, ...n11 } = e64;
          return n11;
        });
        for (let n11 = 0;n11 < e63.length - 1; n11++) {
          const o12 = e63[n11]?.toNextSegmentType;
          o12 && (t11[e63.length - n11 - 2] = { ...t11[e63.length - n11 - 2], toNextSegmentType: o12 });
        }
        return t11;
      })(e61.route) : [...e61.route];
      if (!i9[0] || !i9.at(-1))
        throw new Error(`Pipeline9 cannot materialize empty route "${e61.connectionName}"`);
      return pne(i9[0], n10) || i9.unshift(n10), pne(i9.at(-1), o11) || i9.push(o11), { ...e61, route: i9 };
    })({ route: h5.route, reverse: h5.reverse, sectionStart: a9, sectionEnd: c5 });
    return { ...u9, preloadedTraceIndex: s7, preloadedRouteIndex: Number.MAX_SAFE_INTEGER - t4.length + r9, preloadedRoutePositionStart: e60.startRoutePosition, preloadedRoutePositionEnd: e60.endRoutePosition, isThroughObstacle: false };
  });
};
var yne = (e54) => e54.map((e60) => {
  const t4 = [];
  for (const n8 of e60.route) {
    const o10 = t4.at(-1);
    if (!o10 || o10.z === n8.z || o10.toNextSegmentType === "through_obstacle") {
      t4.push(n8);
      continue;
    }
    const i8 = ts({ hdRoute: e60, start: o10, end: n8 });
    i8 !== "colocated" ? (i8 === "start" ? t4.push({ x: o10.x, y: o10.y, z: n8.z }) : t4.push({ x: n8.x, y: n8.y, z: o10.z }), t4.push(n8)) : t4.push(n8);
  }
  return { ...e60, route: t4 };
});
var bne = (e54) => yne(e54).map((e60) => ({ ...e60, route: e60.route.flatMap((t4, n8) => {
  const o10 = e60.route[n8 - 1];
  return !o10 || o10.z === t4.z || o10.toNextSegmentType === "through_obstacle" || o10.x === t4.x && o10.y === t4.y ? [t4] : [{ x: t4.x, y: t4.y, z: o10.z }, t4];
}) }));
var xne = (e54) => {
  const t4 = new Map;
  for (const n8 of e54)
    n8.regionId && t4.set(n8.regionId, (t4.get(n8.regionId) ?? 0) + n8.route.length);
  return e54.map((e60) => {
    if (!e60.regionId || t4.get(e60.regionId) < 4096)
      return e60;
    const n8 = [], o10 = [];
    for (const [t10, i9] of e60.route.entries()) {
      for (;n8.length >= 2; ) {
        const t11 = n8[n8.length - 2], r9 = n8[n8.length - 1];
        if (t11.z !== r9.z || r9.z !== i9.z || t11.toNextSegmentType || t11.traceThickness !== undefined || Object.keys(r9).some((e61) => e61 !== "x" && e61 !== "y" && e61 !== "z") || e60.vias.some((e61) => Math.hypot(e61.x - r9.x, e61.y - r9.y) < 0.000000001))
          break;
        const s7 = r9.x - t11.x, a9 = r9.y - t11.y, c5 = i9.x - r9.x, l5 = i9.y - r9.y, h5 = Math.hypot(i9.x - t11.x, i9.y - t11.y);
        if (h5 === 0 || s7 * c5 + a9 * l5 < 0 || Math.abs(s7 * l5 - a9 * c5) > 0.000000001 * h5)
          break;
        n8.pop(), o10.pop();
      }
      n8.push(i9), o10.push(t10);
    }
    const i8 = [];
    for (let t10 = 0;t10 < n8.length; t10++) {
      const r9 = n8[t10];
      if (n8[t10 - 1]) {
        const n10 = o10[t10 - 1], r10 = o10[t10];
        r10 - n10 < 64 && i8.push(...e60.route.slice(n10 + 1, r10));
      }
      i8.push(r9);
    }
    return { ...e60, route: i8 };
  });
};
var vne = 0.000000001;
var Ine = (e54) => ({ minX: e54.center.x - e54.width / 2, maxX: e54.center.x + e54.width / 2, minY: e54.center.y - e54.height / 2, maxY: e54.center.y + e54.height / 2 });
var Sne = (e54, t4) => e54.x >= t4.minX - vne && e54.x <= t4.maxX + vne && e54.y >= t4.minY - vne && e54.y <= t4.maxY + vne;
var Cne = (e54, t4, n8) => n8 <= vne ? e54 : n8 >= 0.999999999 ? t4 : { x: e54.x + (t4.x - e54.x) * n8, y: e54.y + (t4.y - e54.y) * n8, z: e54.z };
var Pne = (e54, t4, n8) => {
  const o10 = t4.x - e54.x, i8 = t4.y - e54.y;
  if (Math.abs(o10) <= vne && Math.abs(i8) <= vne)
    return Sne(e54, n8) && Sne(t4, n8) ? { start: e54, end: t4 } : null;
  let r9 = 0, s7 = 1;
  const a9 = [[-o10, e54.x - n8.minX], [o10, n8.maxX - e54.x], [-i8, e54.y - n8.minY], [i8, n8.maxY - e54.y]];
  for (const [e60, t10] of a9) {
    if (Math.abs(e60) <= vne) {
      if (t10 < 0)
        return null;
      continue;
    }
    const n10 = t10 / e60;
    if (e60 < 0 ? r9 = Math.max(r9, n10) : s7 = Math.min(s7, n10), r9 > s7 + vne)
      return null;
  }
  return { start: Cne(e54, t4, r9), end: Cne(e54, t4, s7) };
};
var Mne = (e54) => {
  const t4 = e54.sourceRoutes[0], n8 = `pipeline9_fallback:${t4.connectionName}`, o10 = `${n8}:start`, i8 = `${n8}:end`;
  return [{ ...e54.start.point, portPointId: o10, nextPortPointId: i8, connectionName: t4.connectionName, rootConnectionName: t4.rootConnectionName }, { ...e54.end.point, portPointId: i8, prevPortPointId: o10, connectionName: t4.connectionName, rootConnectionName: t4.rootConnectionName }];
};
var wne = (e54, t4) => Math.abs(e54.x - t4.x) <= vne && Math.abs(e54.y - t4.y) <= vne && e54.z === t4.z;
var Nne = (e54, t4) => e54.sourceRoute.preloadedTraceIndex === t4.sourceRoute.preloadedTraceIndex && wne(e54.sourceRoute.route.at(-1), t4.sourceRoute.route[0]);
var Rne = (e54, t4, n8 = new Set) => {
  const o10 = new Map, i8 = [], r9 = new Set(e54.portPoints.map((e60) => e60.z)), s7 = t4.map((t10) => ((e60, t11) => {
    const n10 = Ine(t11);
    let o11, i9;
    for (let t12 = 0;t12 < e60.route.length - 1; t12++) {
      const r10 = Pne(e60.route[t12], e60.route[t12 + 1], n10);
      r10 && (o11 ??= { segmentIndex: t12, point: r10.start }, i9 = { segmentIndex: t12, point: r10.end });
    }
    return o11 && i9 ? { sourceRoute: e60, start: o11, end: i9 } : null;
  })(t10, e54)).filter((e60) => e60 !== null), a9 = s7.filter((e60) => e60.sourceRoute.isThroughObstacle !== true && (((e61, t10) => t10.size === 0 || [e61.start.point, ...e61.sourceRoute.route.slice(e61.start.segmentIndex + 1, e61.end.segmentIndex + 1), e61.end.point].some((e63) => t10.has(e63.z)))(e60, r9) || n8.has(e60.sourceRoute.connectionName))).sort((e60, t10) => e60.sourceRoute.preloadedTraceIndex - t10.sourceRoute.preloadedTraceIndex || e60.sourceRoute.preloadedRouteIndex - t10.sourceRoute.preloadedRouteIndex), c5 = new Set(a9.map((e60) => e60.sourceRoute)), l5 = s7.map((e60) => e60.sourceRoute).filter((e60) => !c5.has(e60)), h5 = [];
  for (let e60 = 0;e60 < a9.length; e60++) {
    const t10 = a9[e60], n10 = a9[e60 - 1], o11 = h5.at(-1);
    n10 && o11 && Nne(n10, t10) ? (o11.sourceRoutes.push(t10.sourceRoute), o11.end = t10.end) : h5.push({ sourceRoutes: [t10.sourceRoute], start: t10.start, end: t10.end });
  }
  for (const e60 of h5) {
    if (wne(e60.start.point, e60.end.point))
      continue;
    const t10 = e60.sourceRoutes[0].connectionName;
    if (o10.has(t10))
      throw new Error(`Pipeline9 regional fallback found duplicate fixed route section identity "${t10}"`);
    o10.set(t10, e60), i8.push(Mne(e60));
  }
  return { nodeWithPortPoints: { ...e54, portPoints: [...e54.portPoints, ...i8.flatMap((e60) => e60)], portPointsInPairs: [...e54.portPointsInPairs ?? [], ...i8] }, fixedRouteSectionsByConnectionName: o10, fixedObstacleRoutes: l5 };
};
var Tne = (e54) => {
  const t4 = [];
  for (let n8 = 0;n8 < e54.length - 1; n8++) {
    const o10 = e54[n8], i8 = e54[n8 + 1];
    o10.z !== i8.z && Math.abs(o10.x - i8.x) <= vne && Math.abs(o10.y - i8.y) <= vne && t4.push({ x: i8.x, y: i8.y });
  }
  return t4;
};
var Ene = (e54, t4) => Ane({ section: e54, replacement: t4, sourceMutationMasks: new Map, replacementIsMutated: false }).route;
var Ane = ({ section: e54, replacement: t4, sourceMutationMasks: n8, replacementIsMutated: o10 }) => {
  const i8 = e54.sourceRoutes[0], r9 = e54.sourceRoutes.at(-1), s7 = ((e60, t10) => {
    const n10 = e60.route, o11 = n10[0], i9 = n10.at(-1);
    if (!o11 || !i9)
      throw new Error(`Pipeline9 regional fallback produced an empty replacement for "${t10.sourceRoutes[0].connectionName}"`);
    const r10 = Math.hypot(o11.x - t10.start.point.x, o11.y - t10.start.point.y) + Math.hypot(i9.x - t10.end.point.x, i9.y - t10.end.point.y);
    return Math.hypot(i9.x - t10.start.point.x, i9.y - t10.start.point.y) + Math.hypot(o11.x - t10.end.point.x, o11.y - t10.end.point.y) < r10 ? [...n10].reverse() : n10;
  })(t4, e54), a9 = [], c5 = [], l5 = (e60, t10) => {
    const o11 = n8.get(e60.connectionName);
    if (o11 && o11.length !== e60.route.length - 1)
      throw new Error(`Pipeline9 fixed route mutation mask for "${e60.connectionName}" has ${o11.length} segments, expected ${e60.route.length - 1}`);
    return o11?.[t10] ?? false;
  }, h5 = (e60, t10) => {
    const n10 = a9.at(-1);
    if (!n10)
      return void a9.push(e60);
    const o11 = n10.x === e60.x && n10.y === e60.y;
    if (!o11 || n10.z !== e60.z) {
      if (n10.z !== e60.z && !o11) {
        const o12 = { ...e60, z: n10.z };
        a9.push(o12), c5.push(t10);
      }
      a9.push(e60), c5.push(t10);
    }
  };
  h5(i8.route[0], false);
  for (let t10 = 1;t10 <= e54.start.segmentIndex; t10++)
    h5(i8.route[t10], l5(i8, t10 - 1));
  h5(e54.start.point, l5(i8, e54.start.segmentIndex));
  const d9 = c5.length;
  for (const e60 of s7.slice(1, -1))
    h5(e60, o10);
  h5(e54.end.point, o10);
  const u9 = c5.length > d9;
  for (let t10 = e54.end.segmentIndex + 1;t10 < r9.route.length; t10++)
    h5(r9.route[t10], l5(r9, t10 - 1));
  if (c5.length !== a9.length - 1)
    throw new Error(`Pipeline9 produced an invalid mutation mask while splicing "${i8.connectionName}"`);
  return { route: { ...i8, preloadedRoutePositionStart: i8.preloadedRoutePositionStart, preloadedRoutePositionEnd: r9.preloadedRoutePositionEnd, traceThickness: Math.max(...e54.sourceRoutes.map((e60) => e60.traceThickness)), viaDiameter: Math.max(...e54.sourceRoutes.map((e60) => e60.viaDiameter)), route: a9, vias: Tne(a9) }, mutatedSegments: c5, replacementProducedSegment: u9 };
};
var One = 0.000001;
var kne = (e54, t4) => Math.abs(e54.x - t4.x) <= One && Math.abs(e54.y - t4.y) <= One && e54.z === t4.z;
var Dne = (e54, t4) => {
  for (const n8 of t4)
    e54.at(-1) && kne(e54.at(-1), n8) || e54.push(n8);
};
var Lne = (e54) => e54.slice(0, -1).flatMap((t4, n8) => {
  const o10 = e54[n8 + 1];
  return t4.z !== o10.z && Math.abs(t4.x - o10.x) <= One && Math.abs(t4.y - o10.y) <= One ? [{ x: o10.x, y: o10.y }] : [];
});
var zne = (e54) => {
  const { preloadedRoutePositionStart: t4, preloadedRoutePositionEnd: n8 } = e54;
  if (t4 === undefined || n8 === undefined)
    throw new Error(`Pipeline9 fixed route "${e54.connectionName}" is missing route-position metadata`);
  return { start: Math.min(t4, n8), end: Math.max(t4, n8) };
};
var Bne = (e54, t4) => {
  const n8 = zne(e54), o10 = zne(t4);
  return e54.preloadedTraceIndex - t4.preloadedTraceIndex || n8.start - o10.start || n8.end - o10.end || e54.preloadedRouteIndex - t4.preloadedRouteIndex || e54.connectionName.localeCompare(t4.connectionName);
};
var Fne = (e54, t4) => {
  const n8 = e54.route.at(-1), o10 = t4.route[0];
  return Boolean(n8 && o10 && e54.preloadedTraceIndex === t4.preloadedTraceIndex && kne(n8, o10));
};
var jne = (e54, t4) => {
  const n8 = e54.preloadedRoutePositionStart ?? e54.preloadedRouteIndex;
  return n8 + ((e54.preloadedRoutePositionEnd ?? e54.preloadedRouteIndex) - n8) * t4 / (e54.route.length - 1);
};
var $ne = (e54, t4) => e54.route[t4].z !== e54.route[t4 + 1].z;
var Yne = ({ updatedFixedRoutes: e54, regionalMutationMasks: t4 }) => {
  const n8 = [], o10 = (({ updatedFixedRoutes: e60, regionalMutationMasks: t10 }) => {
    const n10 = new Map;
    for (const o12 of e60) {
      if (o12.route.length === 0)
        throw new Error(`Pipeline9 cannot normalize empty fixed route "${o12.connectionName}"`);
      const e61 = o12.route.length - 1;
      if (n10.has(o12.connectionName))
        throw new Error(`Pipeline9 cannot normalize duplicate fixed route "${o12.connectionName}"`);
      const i9 = t10.get(o12.connectionName);
      if (i9 && i9.length !== e61)
        throw new Error(`Pipeline9 fixed route mutation mask for "${o12.connectionName}" has ${i9.length} segments, expected ${e61}`);
      const r10 = o12.isThroughObstacle !== true && (o12.jumpers?.length ?? 0) === 0;
      n10.set(o12.connectionName, Array.from({ length: e61 }, (e63, t11) => r10 && (i9?.[t11] ?? false)));
    }
    let o11 = [];
    const i8 = () => {
      for (;o11[0] && $ne(o11[0].route, o11[0].segmentIndex); ) {
        const e61 = o11.shift();
        n10.get(e61.route.connectionName)[e61.segmentIndex] = false;
      }
      for (;o11.at(-1) && $ne(o11.at(-1).route, o11.at(-1).segmentIndex); ) {
        const e61 = o11.pop();
        n10.get(e61.route.connectionName)[e61.segmentIndex] = false;
      }
      o11 = [];
    };
    let r9;
    for (const t11 of [...e60].sort(Bne)) {
      r9 && !Fne(r9, t11) && i8();
      const e61 = n10.get(t11.connectionName);
      if (e61.length !== 0) {
        for (let n11 = 0;n11 < e61.length; n11++)
          e61[n11] ? o11.push({ route: t11, segmentIndex: n11 }) : i8();
        r9 = t11;
      } else
        i8(), r9 = t11;
    }
    return i8(), n10;
  })({ updatedFixedRoutes: e54, regionalMutationMasks: t4 });
  for (const t10 of e54) {
    const e60 = t10.route.length - 1, i8 = o10.get(t10.connectionName);
    if (e60 === 0) {
      n8.push({ route: t10, mutated: false });
      continue;
    }
    const r9 = [];
    for (let t11 = 0;t11 < e60; t11++) {
      const e61 = i8[t11], n10 = r9.at(-1);
      n10?.mutated === e61 ? n10.end = t11 + 1 : r9.push({ start: t11, end: t11 + 1, mutated: e61 });
    }
    for (const [e61, o11] of r9.entries()) {
      const i9 = t10.route.slice(o11.start, o11.end + 1), s7 = { ...t10, connectionName: r9.length === 1 ? t10.connectionName : `${t10.connectionName}_mutation_fragment_${e61}`, preloadedRouteIndex: t10.preloadedRouteIndex + e61 / (r9.length + 1), preloadedRoutePositionStart: jne(t10, o11.start), preloadedRoutePositionEnd: jne(t10, o11.end), route: i9, vias: Lne(i9) };
      n8.push({ route: s7, mutated: o11.mutated });
    }
  }
  return n8;
};
var Xne = ({ updatedFixedRoutes: e54, regionalMutationMasks: t4 }) => {
  const n8 = Yne({ updatedFixedRoutes: e54, regionalMutationMasks: t4 }), o10 = n8.map(({ route: e60 }) => e60), i8 = ((e60) => {
    const t10 = [];
    let n10;
    for (const o11 of [...e60].sort((e61, t11) => Bne(e61.route, t11.route))) {
      const e61 = o11.route;
      if (!o11.mutated) {
        n10 = undefined;
        continue;
      }
      const i9 = e61.route[0], r10 = e61.route.at(-1);
      if (!i9 || !r10 || e61.route.length < 2)
        throw new Error(`Pipeline9 cannot simplify empty fixed route "${e61.connectionName}"`);
      const s9 = n10?.sourceRoutes.at(-1);
      n10 && s9 && Fne(s9, e61) ? (n10.sourceRoutes.push(e61), n10.end = { segmentIndex: e61.route.length - 2, point: r10 }) : (n10 = { sourceRoutes: [e61], start: { segmentIndex: 0, point: i9 }, end: { segmentIndex: e61.route.length - 2, point: r10 } }, t10.push(n10));
    }
    return t10;
  })(n8), r9 = i8.map((e60, t10) => {
    const n10 = ((e61, t11) => {
      const n11 = e61.sourceRoutes[0], o11 = e61.sourceRoutes.at(-1);
      if (!n11 || !o11)
        throw new Error("Pipeline9 cannot simplify an empty mutation section");
      const i9 = [e61.start.point];
      for (const [t12, n12] of e61.sourceRoutes.entries()) {
        const o12 = t12 === 0, r10 = t12 === e61.sourceRoutes.length - 1, s9 = o12 ? e61.start.segmentIndex + 1 : 0, a9 = r10 ? e61.end.segmentIndex + 1 : n12.route.length;
        Dne(i9, n12.route.slice(s9, a9));
      }
      if (Dne(i9, [e61.end.point]), i9.length < 2)
        throw new Error(`Pipeline9 mutation section for "${n11.connectionName}" has no routable span`);
      return { connectionName: `pipeline9_mutated_preload_${n11.preloadedTraceIndex}_${t11}`, rootConnectionName: n11.rootConnectionName, traceThickness: Math.max(...e61.sourceRoutes.map((e63) => e63.traceThickness)), viaDiameter: Math.max(...e61.sourceRoutes.map((e63) => e63.viaDiameter)), route: i9, vias: Lne(i9) };
    })(e60, t10);
    return { connectionName: n10.connectionName, section: e60, hdRoute: n10 };
  }), s7 = new Set(r9.flatMap(({ section: e60 }) => e60.sourceRoutes.map((e61) => e61.connectionName)));
  return { sections: r9, immutableHdRoutes: o10.filter((e60) => !s7.has(e60.connectionName)), normalizedFixedRoutes: o10 };
};
var Hne = 0.000000001;
var Vne = (e54, t4, n8, o10, i8) => {
  const r9 = i8.getNetConnectedToId(e54.connection_name) ?? e54.connection_name, s7 = [], a9 = (n10, i9, a10 = o10, c5 = [], l5, h5, d9 = false) => {
    n10.length < 2 || s7.push({ connectionName: `${e54.connection_name}_fixed_${t4}_${s7.length}`, rootConnectionName: r9, preloadedTraceIndex: t4, preloadedRouteIndex: s7.length, preloadedRoutePositionStart: l5, preloadedRoutePositionEnd: h5, isThroughObstacle: d9, traceThickness: Math.max(Hne, i9), viaDiameter: Math.max(Hne, a10), route: n10, vias: c5 });
  };
  for (let t10 = 0;t10 < e54.route.length; t10++) {
    const i9 = e54.route[t10];
    if (i9.route_type === "via") {
      a9([{ x: i9.x, y: i9.y, z: mo(i9.from_layer, n8) }, { x: i9.x, y: i9.y, z: mo(i9.to_layer, n8) }], Hne, i9.via_diameter ?? o10, [{ x: i9.x, y: i9.y }], t10, t10);
      continue;
    }
    if (i9.route_type === "through_obstacle") {
      const e60 = mo(i9.from_layer, n8), r11 = mo(i9.to_layer, n8);
      for (let n10 = Math.min(e60, r11);n10 <= Math.max(e60, r11); n10++)
        a9([{ ...i9.start, z: n10 }, { ...i9.end, z: n10 }], i9.width, o10, [], t10, t10 + 1, true);
      continue;
    }
    const r10 = e54.route[t10 + 1];
    i9.route_type === "wire" && r10?.route_type === "wire" && i9.layer === r10.layer && a9([{ x: i9.x, y: i9.y, z: mo(i9.layer, n8) }, { x: r10.x, y: r10.y, z: mo(r10.layer, n8) }], Math.max(i9.width, r10.width), o10, [], t10, t10 + 1);
  }
  return s7;
};
var Gne = class extends ni {
  constructor(e54) {
    super(), this.input = e54;
  }
  static solverName = "Pipeline9HighDensityBatchSolver";
  output;
  _step() {
    if (this.input.fixedHdRoutes.length !== 0)
      throw new Error("Parallel high-density batches cannot mutate preloaded copper");
    const e54 = new Jo(this.input.connectivityNetMap);
    this.output = [];
    for (const t4 of this.input.nodePortPoints) {
      const n8 = new Loe({ ...this.input, nodePortPoints: [t4], connMap: e54 });
      n8.MAX_ITERATIONS = this.input.maxIterations, n8.solve(), this.output.push({ routes: n8.routes, stats: n8.stats, benchmarkDiagnosticCounters: n8.benchmarkDiagnosticCounters, iterations: n8.iterations, consumedNodeCount: 1 - n8.unsolvedNodePortPoints.length, solved: n8.solved, error: n8.error });
    }
    this.solved = true;
  }
  getOutput() {
    if (!this.output)
      throw new Error("High-density batch has not completed");
    return this.output;
  }
};
function Une(e54, t4) {
  return { x: e54.a * t4.x + e54.b * t4.y + e54.c, y: e54.d * t4.x + e54.e * t4.y + e54.f };
}
SolverRuntime.registerSolver(Gne);
var Zne = { highResolutionCellSize: 0.1, highResolutionCellThickness: 8, lowResolutionCellSize: 0.4, traceMargin: 0.15, traceThickness: 0.1, viaDiameter: 0.3, viaMinDistFromBorder: 0.15 };
var qne = { ...Zne };
var Qne = (e54, t4, n8) => {
  const [o10, i8] = e54;
  if (o10 === i8)
    return;
  const r9 = ((e60, t10) => {
    const n10 = e60.portPointId ?? `${e60.connectionName}:${e60.x}:${e60.y}:${e60.z}`, o11 = t10.portPointId ?? `${t10.connectionName}:${t10.x}:${t10.y}:${t10.z}`;
    return n10 < o11 ? `${n10}|${o11}` : `${o11}|${n10}`;
  })(o10, i8);
  t4.has(r9) || (t4.add(r9), n8.push(e54));
};
var Kne = (e54, t4, n8) => {
  for (let o10 = 0;o10 < e54.length - 1; o10++)
    Qne([e54[o10], e54[o10 + 1]], t4, n8);
};
var eoe = (e54) => {
  const t4 = [], n8 = new Set, o10 = ((e60) => {
    const t10 = new Map;
    for (const n10 of e60)
      n10.portPointId && t10.set(n10.portPointId, n10);
    return t10;
  })(e54);
  for (const i9 of e54) {
    if (i9.prevPortPointId) {
      const e60 = o10.get(i9.prevPortPointId);
      e60 && e60.connectionName === i9.connectionName && Qne([e60, i9], n8, t4);
    }
    if (i9.nextPortPointId) {
      const e60 = o10.get(i9.nextPortPointId);
      e60 && e60.connectionName === i9.connectionName && Qne([i9, e60], n8, t4);
    }
  }
  if (t4.length === 0)
    return Kne(e54, n8, t4), t4;
  const i8 = ((e60) => {
    const t10 = new Set;
    for (const [n10, o11] of e60)
      n10.portPointId && t10.add(n10.portPointId), o11.portPointId && t10.add(o11.portPointId);
    return t10;
  })(t4), r9 = e54.filter((e60) => !e60.portPointId || !i8.has(e60.portPointId));
  return Kne(r9, n8, t4), t4;
};
function toe(e54, t4, n8) {
  return Math.max(t4, Math.min(n8, e54));
}
var hoe = ["left", "top", "right", "bottom", "middle"];
var doe = class {
  f = new Float64Array(1024);
  seq = new Uint32Array(1024);
  id = new Int32Array(1024);
  n = 0;
  push(e54, t4, n8) {
    this.ensureCapacity(this.n + 1);
    let o10 = this.n++;
    for (this.f[o10] = e54, this.seq[o10] = t4, this.id[o10] = n8;o10 > 0; ) {
      const e60 = o10 - 1 >> 1;
      if (this.less(e60, o10))
        break;
      this.swap(o10, e60), o10 = e60;
    }
  }
  pop() {
    const e54 = 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)), e54;
  }
  get size() {
    return this.n;
  }
  clear() {
    this.n = 0;
  }
  ensureCapacity(e54) {
    if (e54 <= this.f.length)
      return;
    let t4 = this.f.length;
    for (;t4 < e54; )
      t4 *= 2;
    const n8 = new Float64Array(t4);
    n8.set(this.f), this.f = n8;
    const o10 = new Uint32Array(t4);
    o10.set(this.seq), this.seq = o10;
    const i8 = new Int32Array(t4);
    i8.set(this.id), this.id = i8;
  }
  siftDown(e54) {
    for (;; ) {
      const t4 = 2 * e54 + 1, n8 = t4 + 1;
      if (t4 >= this.n)
        return;
      let o10 = t4;
      if (n8 < this.n && !this.less(t4, n8) && (o10 = n8), this.less(e54, o10))
        return;
      this.swap(e54, o10), e54 = o10;
    }
  }
  less(e54, t4) {
    const n8 = this.f[e54], o10 = this.f[t4];
    return n8 !== o10 ? n8 < o10 : this.seq[e54] < this.seq[t4];
  }
  swap(e54, t4) {
    const n8 = this.f[e54];
    this.f[e54] = this.f[t4], this.f[t4] = n8;
    const o10 = this.seq[e54];
    this.seq[e54] = this.seq[t4], this.seq[t4] = o10;
    const i8 = this.id[e54];
    this.id[e54] = this.id[t4], this.id[t4] = i8;
  }
};
var uoe = class {
  z = new Int32Array(1024);
  cellId = new Int32Array(1024);
  g = new Float64Array(1024);
  parent = new Int32Array(1024);
  ripHead = new Int32Array(1024).fill(-1);
  ripCount = new Int32Array(1024);
  length = 0;
  clear() {
    this.length = 0;
  }
  push(e54, t4, n8, o10, i8, r9) {
    this.ensureCapacity(this.length + 1);
    const s7 = this.length++;
    return this.z[s7] = e54, this.cellId[s7] = t4, this.g[s7] = n8, this.parent[s7] = o10, this.ripHead[s7] = i8, this.ripCount[s7] = r9, s7;
  }
  ensureCapacity(e54) {
    if (e54 <= this.z.length)
      return;
    let t4 = this.z.length;
    for (;t4 < e54; )
      t4 *= 2;
    const n8 = new Int32Array(t4);
    n8.set(this.z), this.z = n8;
    const o10 = new Int32Array(t4);
    o10.set(this.cellId), this.cellId = o10;
    const i8 = new Float64Array(t4);
    i8.set(this.g), this.g = i8;
    const r9 = new Int32Array(t4);
    r9.set(this.parent), this.parent = r9;
    const s7 = new Int32Array(t4);
    s7.fill(-1), s7.set(this.ripHead.subarray(0, this.length)), this.ripHead = s7;
    const a9 = new Int32Array(t4);
    a9.set(this.ripCount.subarray(0, this.length)), this.ripCount = a9;
  }
};
var poe = class {
  connId = new Int32Array(1024);
  prev = new Int32Array(1024).fill(-1);
  length = 0;
  clear() {
    this.length = 0;
  }
  append(e54, t4) {
    this.ensureCapacity(this.length + 1);
    const n8 = this.length++;
    return this.connId[n8] = t4, this.prev[n8] = e54, n8;
  }
  contains(e54, t4) {
    for (let n8 = e54;n8 >= 0; n8 = this.prev[n8])
      if (this.connId[n8] === t4)
        return true;
    return false;
  }
  collect(e54, t4) {
    t4.length = 0;
    for (let n8 = e54;n8 >= 0; n8 = this.prev[n8])
      t4.push(this.connId[n8]);
  }
  ensureCapacity(e54) {
    if (e54 <= this.connId.length)
      return;
    let t4 = this.connId.length;
    for (;t4 < e54; )
      t4 *= 2;
    const n8 = new Int32Array(t4);
    n8.set(this.connId), this.connId = n8;
    const o10 = new Int32Array(t4);
    o10.fill(-1), o10.set(this.prev.subarray(0, this.length)), this.prev = o10;
  }
};
function moe(e54, t4) {
  if (e54.length === 0)
    return null;
  const n8 = new E2(e54.length);
  for (const o10 of e54) {
    const e60 = t4(o10);
    n8.add(e60.minX, e60.minY, e60.maxX, e60.maxY);
  }
  return n8.finish(), n8;
}
function goe(e54, t4) {
  return t4 ?? e54.replace(/_mst\d+$/, "");
}
function foe(e54, t4) {
  const n8 = e54.x - t4.center.x, o10 = e54.y - t4.center.y, i8 = Math.cos(-t4.rotationRadians), r9 = Math.sin(-t4.rotationRadians);
  return { x: n8 * i8 - o10 * r9, y: n8 * r9 + o10 * i8 };
}
function _oe(e54) {
  return { minX: -e54.width / 2, minY: -e54.height / 2, maxX: e54.width / 2, maxY: e54.height / 2 };
}
function yoe(e54, t4, n8) {
  return Math.max(t4, Math.min(n8, e54));
}
function boe(e54, t4) {
  for (let n8 = 0;n8 < e54.length; n8++)
    if (e54[n8] === t4)
      return;
  e54.push(t4);
}
function xoe(e54, t4) {
  for (let n8 = 0;n8 < e54.length; n8++)
    if (e54[n8].cellId === t4.cellId)
      return;
  e54.push(t4);
}
function voe(e54, t4, n8, o10, i8, r9, s7) {
  const a9 = e54 - yoe(e54, o10, r9), c5 = t4 - yoe(t4, i8, s7);
  return a9 * a9 + c5 * c5 <= n8 * n8;
}
function Ioe(e54) {
  const t4 = e54.segmentEnd.x - e54.segmentStart.x, n8 = e54.segmentEnd.y - e54.segmentStart.y, o10 = t4 ** 2 + n8 ** 2;
  if (o10 === 0)
    return (e54.point.x - e54.segmentStart.x) ** 2 + (e54.point.y - e54.segmentStart.y) ** 2;
  const i8 = yoe(((e54.point.x - e54.segmentStart.x) * t4 + (e54.point.y - e54.segmentStart.y) * n8) / o10, 0, 1), r9 = e54.segmentStart.x + i8 * t4, s7 = e54.segmentStart.y + i8 * n8;
  return (e54.point.x - r9) ** 2 + (e54.point.y - s7) ** 2;
}
function Soe(e54) {
  const t4 = yoe(e54.point.x, e54.rect.minX, e54.rect.maxX), n8 = yoe(e54.point.y, e54.rect.minY, e54.rect.maxY), o10 = e54.point.x - t4, i8 = e54.point.y - n8;
  return o10 * o10 + i8 * i8;
}
function Coe(e54) {
  return (e54.second.x - e54.first.x) * (e54.third.y - e54.first.y) - (e54.second.y - e54.first.y) * (e54.third.x - e54.first.x);
}
function Poe(e54) {
  return !(Math.abs(Coe({ first: e54.segmentStart, second: e54.segmentEnd, third: e54.point })) > 0.000000001) && (e54.point.x >= Math.min(e54.segmentStart.x, e54.segmentEnd.x) && e54.point.x <= Math.max(e54.segmentStart.x, e54.segmentEnd.x) && e54.point.y >= Math.min(e54.segmentStart.y, e54.segmentEnd.y) && e54.point.y <= Math.max(e54.segmentStart.y, e54.segmentEnd.y));
}
function Moe(e54) {
  const t4 = Coe({ first: e54.firstStart, second: e54.firstEnd, third: e54.secondStart }), n8 = Coe({ first: e54.firstStart, second: e54.firstEnd, third: e54.secondEnd }), o10 = Coe({ first: e54.secondStart, second: e54.secondEnd, third: e54.firstStart }), i8 = Coe({ first: e54.secondStart, second: e54.secondEnd, third: e54.firstEnd });
  return t4 * n8 < 0 && o10 * i8 < 0 || (Poe({ point: e54.secondStart, segmentStart: e54.firstStart, segmentEnd: e54.firstEnd }) || Poe({ point: e54.secondEnd, segmentStart: e54.firstStart, segmentEnd: e54.firstEnd }) || Poe({ point: e54.firstStart, segmentStart: e54.secondStart, segmentEnd: e54.secondEnd }) || Poe({ point: e54.firstEnd, segmentStart: e54.secondStart, segmentEnd: e54.secondEnd }));
}
function woe(e54) {
  return Moe(e54) ? 0 : Math.min(Ioe({ point: e54.firstStart, segmentStart: e54.secondStart, segmentEnd: e54.secondEnd }), Ioe({ point: e54.firstEnd, segmentStart: e54.secondStart, segmentEnd: e54.secondEnd }), Ioe({ point: e54.secondStart, segmentStart: e54.firstStart, segmentEnd: e54.firstEnd }), Ioe({ point: e54.secondEnd, segmentStart: e54.firstStart, segmentEnd: e54.firstEnd }));
}
function Noe(e54) {
  if (function(e60) {
    if (Soe({ point: e60.segmentStart, rect: e60.rect }) === 0 || Soe({ point: e60.segmentEnd, rect: e60.rect }) === 0)
      return true;
    const t10 = [{ x: e60.rect.minX, y: e60.rect.minY }, { x: e60.rect.maxX, y: e60.rect.minY }, { x: e60.rect.maxX, y: e60.rect.maxY }, { x: e60.rect.minX, y: e60.rect.maxY }];
    for (let n8 = 0;n8 < t10.length; n8++) {
      const o10 = (n8 + 1) % t10.length;
      if (Moe({ firstStart: e60.segmentStart, firstEnd: e60.segmentEnd, secondStart: t10[n8], secondEnd: t10[o10] }))
        return true;
    }
    return false;
  }(e54))
    return true;
  const t4 = e54.radius ** 2;
  if (Soe({ point: e54.segmentStart, rect: e54.rect }) <= t4 || Soe({ point: e54.segmentEnd, rect: e54.rect }) <= t4)
    return true;
  return [{ x: e54.rect.minX, y: e54.rect.minY }, { x: e54.rect.maxX, y: e54.rect.minY }, { x: e54.rect.maxX, y: e54.rect.maxY }, { x: e54.rect.minX, y: e54.rect.maxY }].some((n8) => Ioe({ point: n8, segmentStart: e54.segmentStart, segmentEnd: e54.segmentEnd }) <= t4);
}
var Roe = class extends BaseSolver {
  getSolverName() {
    return "HighDensitySolverB01";
  }
  nodeWithPortPoints;
  obstacles;
  highResolutionCellSize;
  highResolutionCellThickness;
  lowResolutionCellSize;
  viaDiameter;
  MAX_RIPS;
  maxCellCount;
  traceThickness;
  traceMargin;
  obstacleClearanceMargin;
  viaMinDistFromBorder;
  showPenaltyMap;
  showUsedCellMap;
  effort;
  stepMultiplier;
  hyperParameters;
  initialPenaltyFn;
  boundsMinX;
  boundsMaxX;
  boundsMinY;
  boundsMaxY;
  gridToBoundsTransform;
  availableZ;
  zToLayer;
  layerToZ;
  layers;
  fineRows;
  fineCols;
  lowScale;
  bandRows;
  bandCols;
  regions;
  planeSize;
  cellCenterX;
  cellCenterY;
  cellMinX;
  cellMinY;
  cellMaxX;
  cellMaxY;
  cellWidth;
  cellHeight;
  cellRegion;
  cellRow;
  cellCol;
  viaAllowed;
  neighborOffset;
  neighborIds;
  neighborCosts;
  usedCellsFlat;
  sharedCellsFlat;
  portOwnerFlat;
  penalty2d;
  ripStateBuckets;
  visitedStamp;
  bestGStamp;
  bestGValue;
  visitedFlatStamp;
  sharedCrossRootPortFlat;
  stamp = 0;
  connNameToId;
  connIdToName;
  connIdToRootNet;
  overlapFriendlyRootNets;
  usedIndicesByConn;
  unsolvedSegs;
  solvedRoutes;
  activeConnSeg = null;
  activeConnId = -1;
  nodePool;
  heap;
  ripChain;
  seqCounter = 0;
  _viaOccs = [];
  _cellOccs = [];
  _rippedIds = [];
  ripCount;
  totalRipEvents = 0;
  searchIterations = 0;
  consecutiveSkips = 0;
  penaltyCap;
  baseSearchBudgetIters;
  _moveCost = 0;
  _moveRippedHead = -1;
  _moveRipCount = 0;
  traceKeepoutRadius;
  viaKeepoutRadius;
  obstacleTraceRootIdsFlat;
  obstacleViaRootIdsByCell;
  obstacleRootNameToId;
  obstacleRootNames;
  obstacleTracePrimitives;
  obstacleViaPrimitives;
  obstacleRectPrimitives;
  obstacleTraceSpatialIndex = null;
  obstacleViaSpatialIndex = null;
  obstacleRectSpatialIndex = null;
  obstacleTraceBlockedCellCount = 0;
  obstacleViaBlockedCellCount = 0;
  get unsolvedConnections() {
    return this.unsolvedSegs;
  }
  get solvedConnectionsMap() {
    const e54 = new Map;
    for (let t4 = 0;t4 < this.solvedRoutes.length; t4++) {
      const n8 = this.getSolvedRoutesForConn(t4);
      n8.length > 0 && e54.set(t4, n8);
    }
    return e54;
  }
  get activeConnection() {
    if (!this.activeConnSeg)
      return null;
    const e54 = this.activeConnSeg.startCellId, t4 = this.activeConnSeg.endCellId;
    return { connectionName: this.connIdToName[this.activeConnSeg.connId] ?? "", start: { cellId: e54, region: hoe[this.cellRegion[e54]], row: this.cellRow[e54], col: this.cellCol[e54], x: this.cellCenterX[e54], y: this.cellCenterY[e54], z: this.activeConnSeg.startZ }, end: { cellId: t4, region: hoe[this.cellRegion[t4]], row: this.cellRow[t4], col: this.cellCol[t4], x: this.cellCenterX[t4], y: this.cellCenterY[t4], 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((e54) => [e54.name, e54.rows * e54.cols])) : {}, obstacleTraceBlockedCells: this.obstacleTraceBlockedCellCount, obstacleViaBlockedCells: this.obstacleViaBlockedCellCount, obstacleRootCount: this.obstacleRootNames?.length ?? 0, obstacleRectCount: this.obstacleRectPrimitives?.length ?? 0 };
  }
  constructor(e54) {
    super(), this.nodeWithPortPoints = e54.nodeWithPortPoints, this.obstacles = e54.obstacles, this.highResolutionCellSize = e54.highResolutionCellSize ?? 0.1, this.highResolutionCellThickness = Math.max(1, Math.floor(e54.highResolutionCellThickness ?? 8)), this.lowResolutionCellSize = e54.lowResolutionCellSize ?? 0.4, this.viaDiameter = e54.viaDiameter, this.maxCellCount = e54.maxCellCount, this.traceThickness = e54.traceThickness ?? 0.1, this.traceMargin = e54.traceMargin ?? 0.15, this.obstacleClearanceMargin = e54.obstacleClearanceMargin ?? 0, this.viaMinDistFromBorder = e54.viaMinDistFromBorder ?? 0.15, this.showPenaltyMap = e54.showPenaltyMap ?? false, this.showUsedCellMap = e54.showUsedCellMap ?? false, this.effort = e54.effort ?? 1, this.stepMultiplier = Math.max(1, Math.floor(e54.stepMultiplier ?? 1)), this.hyperParameters = { shuffleSeed: 0, ripCost: 8, ripTracePenalty: 0.5, ripViaPenalty: 0.75, viaBaseCost: 0.1, greedyMultiplier: 1.5, sameRootObstacleCostMultiplier: 1, ...e54.hyperParameters }, this.MAX_ITERATIONS = 1e8, this.MAX_RIPS = 200, this.initialPenaltyFn = e54.initialPenaltyFn;
  }
  getConstructorParams() {
    return [{ nodeWithPortPoints: this.nodeWithPortPoints, obstacles: this.obstacles, highResolutionCellSize: this.highResolutionCellSize, highResolutionCellThickness: this.highResolutionCellThickness, lowResolutionCellSize: this.lowResolutionCellSize, viaDiameter: this.viaDiameter, maxCellCount: this.maxCellCount, stepMultiplier: this.stepMultiplier, traceThickness: this.traceThickness, traceMargin: this.traceMargin, obstacleClearanceMargin: this.obstacleClearanceMargin, viaMinDistFromBorder: this.viaMinDistFromBorder, showPenaltyMap: this.showPenaltyMap, showUsedCellMap: this.showUsedCellMap, effort: this.effort, hyperParameters: this.hyperParameters, initialPenaltyFn: this.initialPenaltyFn }];
  }
  _setup() {
    const { nodeWithPortPoints: e54 } = this, { width: t4, height: n8, center: o10 } = e54;
    if (t4 > 15 || n8 > 15)
      return this.error = `HighDensitySolverB01 only supports routing windows up to 15x15mm; received ${t4}x${n8}mm`, void (this.failed = true);
    const i8 = this.lowResolutionCellSize / this.highResolutionCellSize, r9 = Math.round(i8);
    if (!Number.isFinite(i8) || i8 <= 0 || Math.abs(i8 - r9) > 0.000000001)
      return this.error = "lowResolutionCellSize must be a positive integer multiple of highResolutionCellSize", void (this.failed = true);
    this.lowScale = Math.max(1, r9), this.availableZ = e54.availableZ ?? [...new Set(e54.portPoints.map((e60) => e60.z))].sort((e60, t10) => e60 - t10), this.layers = this.availableZ.length, this.zToLayer = new Map, this.layerToZ = new Map;
    for (let e60 = 0;e60 < this.availableZ.length; e60++) {
      const t10 = this.availableZ[e60];
      this.zToLayer.set(t10, e60), this.layerToZ.set(e60, t10);
    }
    this.boundsMinX = o10.x - t4 / 2, this.boundsMaxX = o10.x + t4 / 2, this.boundsMinY = o10.y - n8 / 2, this.boundsMaxY = o10.y + n8 / 2, this.traceKeepoutRadius = this.traceMargin + this.traceThickness / 2, this.viaKeepoutRadius = this.viaDiameter / 2 + this.traceKeepoutRadius, this.buildFiveRegionGrid(t4, n8), this.gridToBoundsTransform = this.computeGridToBoundsTransform();
    const s7 = this.layers * this.planeSize;
    if (this.maxCellCount !== undefined && s7 > this.maxCellCount)
      return this.error = `Cell count ${s7} exceeds maxCellCount ${this.maxCellCount}`, void (this.failed = true);
    this.connNameToId = new Map, this.connIdToName = [], this.connIdToRootNet = [], this.overlapFriendlyRootNets = new Set, this.unsolvedSegs = this.buildConnectionSegs(), this.penalty2d = new Float64Array(this.planeSize);
    const a9 = t4 > 0 ? 1 / t4 : 0, c5 = n8 > 0 ? 1 / n8 : 0;
    for (let e60 = 0;e60 < this.planeSize; e60++) {
      let t10 = 0;
      this.initialPenaltyFn && (t10 += this.initialPenaltyFn({ x: this.cellCenterX[e60], y: this.cellCenterY[e60], px: (this.cellCenterX[e60] - this.boundsMinX) * a9, py: (this.cellCenterY[e60] - this.boundsMinY) * c5, cellId: e60, region: hoe[this.cellRegion[e60]], row: this.cellRow[e60], col: this.cellCol[e60] })), this.penalty2d[e60] = t10;
    }
    this.usedCellsFlat = new Int32Array(s7).fill(-1), this.sharedCellsFlat = Array.from({ length: s7 }, () => {}), this.portOwnerFlat = new Int32Array(s7).fill(-1), this.sharedCrossRootPortFlat = new Uint8Array(s7), this.obstacleTraceRootIdsFlat = Array.from({ length: s7 }, () => {}), this.obstacleViaRootIdsByCell = Array.from({ length: this.planeSize }, () => {}), this.obstacleRootNameToId = new Map, this.obstacleRootNames = [], this.obstacleTracePrimitives = [], this.obstacleViaPrimitives = [], this.obstacleRectPrimitives = [];
    const l5 = this.rasterizeObstacles();
    if (l5)
      return this.error = l5, void (this.failed = true);
    this.buildObstacleSpatialIndexes(), this.ripStateBuckets = 1;
    const h5 = s7;
    this.visitedStamp = new Uint32Array(h5), this.bestGStamp = new Uint32Array(h5), this.bestGValue = new Float64Array(h5), this.visitedFlatStamp = new Uint32Array(s7), this.stamp = 0;
    const d9 = new Map;
    for (const e60 of this.nodeWithPortPoints.portPoints) {
      const t10 = this.connNameToId.get(e60.connectionName);
      if (t10 === undefined)
        continue;
      const n10 = this.pointToCell(e60), o11 = n10.z * this.planeSize + n10.cellId, i9 = this.connIdToRootNet[t10], r10 = d9.get(o11);
      r10 === undefined ? d9.set(o11, i9) : r10 !== i9 && (this.sharedCrossRootPortFlat[o11] = 1);
      const s9 = this.portOwnerFlat[o11];
      this.portOwnerFlat[o11] = s9 === -1 || s9 === t10 ? t10 : -2;
    }
    this.solvedRoutes = [], this.usedIndicesByConn = [], this.ripCount = [], this.consecutiveSkips = 0, this.penaltyCap = 0.5 * this.hyperParameters.ripCost, this.shuffleConnections();
    const u9 = function(e60) {
      const t10 = e60.planeSize * e60.layers, n10 = e60.connectionCount, o11 = Math.sqrt(n10), i9 = Math.max(1, e60.maxIterations), r10 = toe(Math.round(t10 * (8 + 1.2 * o11)), 150000, 12000000), s9 = toe(Math.round(r10 * e60.effort), 150000, 12000000), a10 = toe(Math.round(0.2 * i9), 150000, 2000000);
      return { maxIterationsIters: Math.max(1, Math.min(i9, Math.max(a10, s9))), baseSearchBudgetIters: toe(Math.round(t10 * (10 + 0.8 * o11) * e60.effort), 50000, 4000000) };
    }({ planeSize: this.planeSize, layers: this.layers, connectionCount: this.unsolvedSegs.length, effort: this.effort, maxIterations: this.MAX_ITERATIONS });
    this.baseSearchBudgetIters = u9.baseSearchBudgetIters, this.MAX_ITERATIONS = u9.maxIterationsIters, this.activeConnSeg = null, this.activeConnId = -1, this.nodePool = new uoe, this.heap = new doe, this.ripChain = new poe, this.seqCounter = 0;
  }
  _step() {
    for (let e54 = 0;e54 < this.stepMultiplier; e54++) {
      if (this.solved || this.failed)
        return;
      this.stepOnce();
    }
  }
  rasterizeObstacles() {
    for (let e54 = 0;e54 < this.obstacles.length; e54++) {
      const t4 = this.obstacles[e54];
      if (t4.type === "rect") {
        const n10 = this.rasterizeRectObstacle(t4, e54);
        if (n10)
          return n10;
        continue;
      }
      if (t4.traceThickness <= 0 || t4.viaDiameter <= 0 || t4.route.length < 2)
        return `Obstacle ${e54} must have positive trace/via sizes and at least two route points`;
      const n8 = goe(t4.connectionName, t4.rootConnectionName), o10 = this.internObstacleRootName(n8);
      for (let n10 = 1;n10 < t4.route.length; n10++) {
        const i8 = t4.route[n10 - 1], r9 = t4.route[n10];
        if (!(Number.isFinite(i8.x) && Number.isFinite(i8.y) && Number.isFinite(i8.z) && Number.isFinite(r9.x) && Number.isFinite(r9.y) && Number.isFinite(r9.z)))
          return `Obstacle ${e54} contains non-finite route coordinates`;
        if (i8.z === r9.z) {
          const n11 = this.zToLayer.get(i8.z);
          if (n11 === undefined)
            return `Obstacle ${e54} uses unavailable layer z=${i8.z}`;
          this.rasterizeObstacleTraceSegment({ segmentStart: i8, segmentEnd: r9, layer: n11, obstacleRootId: o10, obstacleTraceThickness: t4.traceThickness });
        } else if (!t4.vias.some((e60) => e60.x === r9.x && e60.y === r9.y)) {
          const n11 = this.rasterizeObstacleVia({ center: r9, obstacleRootId: o10, obstacleViaDiameter: t4.viaDiameter, zStart: i8.z, zEnd: r9.z, obstacleIndex: e54 });
          if (n11)
            return n11;
        }
      }
      for (const n10 of t4.vias) {
        if (!Number.isFinite(n10.x) || !Number.isFinite(n10.y))
          return `Obstacle ${e54} contains non-finite via coordinates`;
        const i8 = this.rasterizeObstacleVia({ center: n10, obstacleRootId: o10, obstacleViaDiameter: t4.viaDiameter, zStart: n10.zStart, zEnd: n10.zEnd, obstacleIndex: e54 });
        if (i8)
          return i8;
      }
    }
    return this.obstacleTraceBlockedCellCount = this.obstacleTraceRootIdsFlat.reduce((e54, t4) => e54 + (t4 ? 1 : 0), 0), this.obstacleViaBlockedCellCount = this.obstacleViaRootIdsByCell.reduce((e54, t4) => e54 + (t4 ? 1 : 0), 0), null;
  }
  rasterizeRectObstacle(e54, t4) {
    if (!Number.isFinite(e54.center.x) || !Number.isFinite(e54.center.y) || !Number.isFinite(e54.width) || !Number.isFinite(e54.height) || e54.width <= 0 || e54.height <= 0)
      return `Rect obstacle ${t4} must have finite geometry and positive dimensions`;
    const n8 = [];
    for (const o11 of e54.zLayers) {
      const e60 = this.zToLayer.get(o11);
      if (e60 === undefined)
        return `Rect obstacle ${t4} uses unavailable layer z=${o11}`;
      boe(n8, e60);
    }
    if (n8.length === 0)
      return `Rect obstacle ${t4} must apply to at least one layer`;
    const o10 = this.internObstacleRootName(goe(e54.connectionName, e54.rootConnectionName)), i8 = { rootId: o10, center: e54.center, width: e54.width, height: e54.height, rotationRadians: (e54.ccwRotationDegrees ?? 0) * Math.PI / 180, layers: n8 };
    this.obstacleRectPrimitives.push(i8);
    const r9 = this.transformBoundsPointToGrid(e54.center), s7 = Math.hypot(e54.width / 2, e54.height / 2), a9 = this.getConservativeGridRadius(s7 + this.traceThickness / 2 + this.traceMargin);
    this.forEachCellNearCircle(r9.x, r9.y, a9, (e60) => {
      for (const t10 of n8)
        this.addObstacleRootId({ rootIdsByCell: this.obstacleTraceRootIdsFlat, cellIndex: t10 * this.planeSize + e60, obstacleRootId: o10 });
    });
    const c5 = this.getConservativeGridRadius(s7 + this.viaDiameter / 2 + this.traceMargin);
    return this.forEachCellNearCircle(r9.x, r9.y, c5, (e60) => {
      this.addObstacleRootId({ rootIdsByCell: this.obstacleViaRootIdsByCell, cellIndex: e60, obstacleRootId: o10 });
    }), null;
  }
  internObstacleRootName(e54) {
    const t4 = this.obstacleRootNameToId.get(e54);
    if (t4 !== undefined)
      return t4;
    const n8 = this.obstacleRootNames.length;
    return this.obstacleRootNames.push(e54), this.obstacleRootNameToId.set(e54, n8), n8;
  }
  rasterizeObstacleTraceSegment(e54) {
    this.obstacleTracePrimitives.push({ rootId: e54.obstacleRootId, layer: e54.layer, segmentStart: e54.segmentStart, segmentEnd: e54.segmentEnd, traceRadius: e54.obstacleTraceThickness / 2 });
    const t4 = this.transformBoundsPointToGrid(e54.segmentStart), n8 = this.transformBoundsPointToGrid(e54.segmentEnd), o10 = this.getConservativeGridRadius(e54.obstacleTraceThickness / 2 + this.traceMargin), i8 = this.getConservativeGridRadius(e54.obstacleTraceThickness / 2 + this.viaDiameter / 2 + this.traceMargin);
    this.forEachCellNearSegment({ segmentStart: t4, segmentEnd: n8, radius: o10 }, (t10) => {
      this.addObstacleRootId({ rootIdsByCell: this.obstacleTraceRootIdsFlat, cellIndex: e54.layer * this.planeSize + t10, obstacleRootId: e54.obstacleRootId });
    }), this.forEachCellNearSegment({ segmentStart: t4, segmentEnd: n8, radius: i8 }, (t10) => {
      this.addObstacleRootId({ rootIdsByCell: this.obstacleViaRootIdsByCell, cellIndex: t10, obstacleRootId: e54.obstacleRootId });
    });
  }
  rasterizeObstacleVia(e54) {
    if (e54.zStart === undefined != (e54.zEnd === undefined))
      return `Obstacle ${e54.obstacleIndex} via must provide both zStart and zEnd`;
    let t4 = Array.from({ length: this.layers }, (e60, t10) => t10);
    if (e54.zStart !== undefined && e54.zEnd !== undefined) {
      if (!Number.isFinite(e54.zStart) || !Number.isFinite(e54.zEnd))
        return `Obstacle ${e54.obstacleIndex} contains a non-finite via layer span`;
      const n10 = Math.min(e54.zStart, e54.zEnd), o11 = Math.max(e54.zStart, e54.zEnd);
      t4 = this.availableZ.flatMap((e60, t10) => e60 >= n10 && e60 <= o11 ? [t10] : []);
    }
    if (t4.length === 0)
      return null;
    this.obstacleViaPrimitives.push({ rootId: e54.obstacleRootId, center: e54.center, viaRadius: e54.obstacleViaDiameter / 2, layers: t4 });
    const n8 = this.transformBoundsPointToGrid(e54.center), o10 = this.getConservativeGridRadius(e54.obstacleViaDiameter / 2 + this.traceThickness / 2 + this.traceMargin), i8 = this.getConservativeGridRadius(e54.obstacleViaDiameter / 2 + this.viaDiameter / 2 + this.traceMargin);
    return this.forEachCellNearCircle(n8.x, n8.y, Math.max(o10, i8), (r9) => {
      const s7 = this.getCellRect(r9);
      if (voe(n8.x, n8.y, o10, s7.minX, s7.minY, s7.maxX, s7.maxY))
        for (const n10 of t4)
          this.addObstacleRootId({ rootIdsByCell: this.obstacleTraceRootIdsFlat, cellIndex: n10 * this.planeSize + r9, obstacleRootId: e54.obstacleRootId });
      voe(n8.x, n8.y, i8, s7.minX, s7.minY, s7.maxX, s7.maxY) && this.addObstacleRootId({ rootIdsByCell: this.obstacleViaRootIdsByCell, cellIndex: r9, obstacleRootId: e54.obstacleRootId });
    }), null;
  }
  forEachCellNearSegment(e54, t4) {
    const n8 = { x: (e54.segmentStart.x + e54.segmentEnd.x) / 2, y: (e54.segmentStart.y + e54.segmentEnd.y) / 2 }, o10 = Math.hypot(e54.segmentEnd.x - e54.segmentStart.x, e54.segmentEnd.y - e54.segmentStart.y) / 2 + e54.radius;
    this.forEachCellNearCircle(n8.x, n8.y, o10, (n10) => {
      Noe({ segmentStart: e54.segmentStart, segmentEnd: e54.segmentEnd, radius: e54.radius, rect: this.getCellRect(n10) }) && t4(n10);
    });
  }
  getCellRect(e54) {
    return { minX: this.cellMinX[e54], minY: this.cellMinY[e54], maxX: this.cellMaxX[e54], maxY: this.cellMaxY[e54] };
  }
  transformBoundsPointToGrid(e54) {
    const t4 = this.gridToBoundsTransform;
    return { x: (e54.x - t4.c) / t4.a, y: (e54.y - t4.f) / t4.e };
  }
  getConservativeGridRadius(e54) {
    return e54 / Math.min(Math.abs(this.gridToBoundsTransform.a), Math.abs(this.gridToBoundsTransform.e));
  }
  buildObstacleSpatialIndexes() {
    const e54 = Math.max(Math.abs(this.traceThickness / 2 + this.obstacleClearanceMargin), Math.abs(this.viaDiameter / 2 + this.obstacleClearanceMargin));
    this.obstacleTraceSpatialIndex = moe(this.obstacleTracePrimitives, (t4) => {
      const n8 = t4.traceRadius + e54;
      return { minX: Math.min(t4.segmentStart.x, t4.segmentEnd.x) - n8, minY: Math.min(t4.segmentStart.y, t4.segmentEnd.y) - n8, maxX: Math.max(t4.segmentStart.x, t4.segmentEnd.x) + n8, maxY: Math.max(t4.segmentStart.y, t4.segmentEnd.y) + n8 };
    }), this.obstacleViaSpatialIndex = moe(this.obstacleViaPrimitives, (t4) => {
      const n8 = t4.viaRadius + e54;
      return { minX: t4.center.x - n8, minY: t4.center.y - n8, maxX: t4.center.x + n8, maxY: t4.center.y + n8 };
    }), this.obstacleRectSpatialIndex = moe(this.obstacleRectPrimitives, (t4) => {
      const n8 = Math.hypot(t4.width / 2, t4.height / 2) + e54;
      return { minX: t4.center.x - n8, minY: t4.center.y - n8, maxX: t4.center.x + n8, maxY: t4.center.y + n8 };
    });
  }
  addObstacleRootId(e54) {
    let t4 = e54.rootIdsByCell[e54.cellIndex];
    t4 || (t4 = [], e54.rootIdsByCell[e54.cellIndex] = t4), boe(t4, e54.obstacleRootId);
  }
  isBlockedByObstacleRoots(e54, t4) {
    if (!e54)
      return false;
    const n8 = this.connIdToRootNet[t4];
    for (const t10 of e54)
      if (this.obstacleRootNames[t10] !== n8)
        return true;
    return false;
  }
  hasSameRootObstacle(e54, t4) {
    if (!e54)
      return false;
    const n8 = this.connIdToRootNet[t4];
    return e54.some((e60) => this.obstacleRootNames[e60] === n8);
  }
  isLateralMoveBlockedByObstacleGeometry(e54) {
    const t4 = this.connIdToRootNet[e54.activeConn], n8 = this.activeConnSeg, o10 = n8 && e54.layer === n8.startZ && e54.fromCellId === n8.startCellId ? n8.startPoint : Une(this.gridToBoundsTransform, { x: this.cellCenterX[e54.fromCellId], y: this.cellCenterY[e54.fromCellId] }), i8 = n8 && e54.layer === n8.endZ && e54.toCellId === n8.endCellId ? n8.endPoint : Une(this.gridToBoundsTransform, { x: this.cellCenterX[e54.toCellId], y: this.cellCenterY[e54.toCellId] }), r9 = Math.min(o10.x, i8.x), s7 = Math.min(o10.y, i8.y), a9 = Math.max(o10.x, i8.x), c5 = Math.max(o10.y, i8.y), l5 = this.obstacleTraceSpatialIndex?.search(r9, s7, a9, c5) ?? [];
    for (const n10 of l5) {
      const r10 = this.obstacleTracePrimitives[n10];
      if (r10.layer !== e54.layer || this.obstacleRootNames[r10.rootId] === t4)
        continue;
      const s9 = r10.traceRadius + this.traceThickness / 2 + this.obstacleClearanceMargin;
      if (woe({ firstStart: o10, firstEnd: i8, secondStart: r10.segmentStart, secondEnd: r10.segmentEnd }) < s9 * s9)
        return true;
    }
    const h5 = this.obstacleViaSpatialIndex?.search(r9, s7, a9, c5) ?? [];
    for (const n10 of h5) {
      const r10 = this.obstacleViaPrimitives[n10];
      if (!r10.layers.includes(e54.layer) || this.obstacleRootNames[r10.rootId] === t4)
        continue;
      const s9 = r10.viaRadius + this.traceThickness / 2 + this.obstacleClearanceMargin;
      if (Ioe({ point: r10.center, segmentStart: o10, segmentEnd: i8 }) < s9 * s9)
        return true;
    }
    const d9 = this.obstacleRectSpatialIndex?.search(r9, s7, a9, c5) ?? [];
    for (const n10 of d9) {
      const r10 = this.obstacleRectPrimitives[n10];
      if (r10.layers.includes(e54.layer) && this.obstacleRootNames[r10.rootId] !== t4 && Noe({ segmentStart: foe(o10, r10), segmentEnd: foe(i8, r10), radius: this.traceThickness / 2 + this.obstacleClearanceMargin, rect: _oe(r10) }))
        return true;
    }
    return false;
  }
  isViaMoveBlockedByObstacleGeometry(e54) {
    const t4 = this.connIdToRootNet[e54.activeConn], n8 = Une(this.gridToBoundsTransform, { x: this.cellCenterX[e54.cellId], y: this.cellCenterY[e54.cellId] }), o10 = this.obstacleTraceSpatialIndex?.search(n8.x, n8.y, n8.x, n8.y) ?? [];
    for (const e60 of o10) {
      const o11 = this.obstacleTracePrimitives[e60];
      if (this.obstacleRootNames[o11.rootId] === t4)
        continue;
      const i9 = o11.traceRadius + this.viaDiameter / 2 + this.obstacleClearanceMargin;
      if (Ioe({ point: n8, segmentStart: o11.segmentStart, segmentEnd: o11.segmentEnd }) < i9 * i9)
        return true;
    }
    const i8 = this.obstacleViaSpatialIndex?.search(n8.x, n8.y, n8.x, n8.y) ?? [];
    for (const e60 of i8) {
      const o11 = this.obstacleViaPrimitives[e60];
      if (this.obstacleRootNames[o11.rootId] === t4)
        continue;
      const i9 = o11.viaRadius + this.viaDiameter / 2 + this.obstacleClearanceMargin;
      if ((n8.x - o11.center.x) ** 2 + (n8.y - o11.center.y) ** 2 < i9 * i9)
        return true;
    }
    const r9 = this.obstacleRectSpatialIndex?.search(n8.x, n8.y, n8.x, n8.y) ?? [];
    for (const e60 of r9) {
      const o11 = this.obstacleRectPrimitives[e60];
      if (this.obstacleRootNames[o11.rootId] === t4)
        continue;
      const i9 = foe(n8, o11), r10 = this.viaDiameter / 2 + this.obstacleClearanceMargin;
      if (Soe({ point: i9, rect: _oe(o11) }) < r10 * r10)
        return true;
    }
    return false;
  }
  buildFiveRegionGrid(e54, t4) {
    this.fineCols = Math.max(1, Math.ceil(e54 / this.highResolutionCellSize)), this.fineRows = Math.max(1, Math.ceil(t4 / this.highResolutionCellSize)), this.bandCols = Math.min(this.highResolutionCellThickness, Math.floor(this.fineCols / 2)), this.bandRows = Math.min(this.highResolutionCellThickness, Math.floor(this.fineRows / 2));
    const n8 = Math.max(0, this.fineCols - 2 * this.bandCols), o10 = Math.max(0, this.fineRows - 2 * this.bandRows), i8 = n8, r9 = n8;
    this.regions = [{ id: 0, name: "left", fineOriginRow: 0, fineOriginCol: 0, fineRows: this.fineRows, fineCols: this.bandCols, cellScale: 1, rows: this.fineRows, cols: this.bandCols, offset: 0 }, { id: 1, name: "top", fineOriginRow: 0, fineOriginCol: this.bandCols, fineRows: this.bandRows, fineCols: i8, cellScale: 1, rows: this.bandRows, cols: i8, offset: 0 }, { id: 2, 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: 3, name: "bottom", fineOriginRow: this.fineRows - this.bandRows, fineOriginCol: this.bandCols, fineRows: this.bandRows, fineCols: r9, cellScale: 1, rows: this.bandRows, cols: r9, offset: 0 }, { id: 4, name: "middle", fineOriginRow: this.bandRows, fineOriginCol: this.bandCols, fineRows: o10, fineCols: n8, cellScale: this.lowScale, rows: o10 > 0 ? Math.ceil(o10 / this.lowScale) : 0, cols: n8 > 0 ? Math.ceil(n8 / this.lowScale) : 0, offset: 0 }];
    let s7 = 0;
    for (let e60 = 0;e60 < this.regions.length; e60++)
      this.regions[e60].offset = s7, s7 += this.regions[e60].rows * this.regions[e60].cols;
    this.planeSize = s7, 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 e60 = 0;e60 < this.regions.length; e60++) {
      const t10 = this.regions[e60];
      for (let e61 = 0;e61 < t10.rows; e61++) {
        const n10 = t10.fineOriginRow + e61 * t10.cellScale, o11 = Math.min(t10.fineOriginRow + t10.fineRows, n10 + t10.cellScale), i9 = this.boundsMinY + n10 * this.highResolutionCellSize, r10 = Math.min(this.boundsMaxY, this.boundsMinY + o11 * this.highResolutionCellSize);
        for (let n11 = 0;n11 < t10.cols; n11++) {
          const o12 = t10.fineOriginCol + n11 * t10.cellScale, s9 = Math.min(t10.fineOriginCol + t10.fineCols, o12 + t10.cellScale), a10 = this.boundsMinX + o12 * this.highResolutionCellSize, c9 = Math.min(this.boundsMaxX, this.boundsMinX + s9 * this.highResolutionCellSize), l10 = this.cellIdFor(t10.id, e61, n11);
          this.cellCenterX[l10] = (a10 + c9) / 2, this.cellCenterY[l10] = (i9 + r10) / 2, this.cellMinX[l10] = a10, this.cellMinY[l10] = i9, this.cellMaxX[l10] = c9, this.cellMaxY[l10] = r10, this.cellWidth[l10] = c9 - a10, this.cellHeight[l10] = r10 - i9, this.cellRegion[l10] = t10.id, this.cellRow[l10] = e61, this.cellCol[l10] = n11;
          const h9 = Math.min(this.cellCenterX[l10] - this.boundsMinX, this.boundsMaxX - this.cellCenterX[l10], this.cellCenterY[l10] - this.boundsMinY, this.boundsMaxY - this.cellCenterY[l10]);
          this.viaAllowed[l10] = h9 >= this.viaMinDistFromBorder ? 1 : 0;
        }
      }
    }
    const a9 = Array.from({ length: this.planeSize }, () => []), c5 = (e60, t10) => {
      if (e60 === t10 || e60 < 0 || t10 < 0)
        return;
      const n10 = this.cellCenterX[e60] - this.cellCenterX[t10], o11 = this.cellCenterY[e60] - this.cellCenterY[t10], i9 = Math.hypot(n10, o11);
      xoe(a9[e60], { cellId: t10, cost: i9 }), xoe(a9[t10], { cellId: e60, cost: i9 });
    };
    for (let e60 = 0;e60 < this.regions.length; e60++) {
      const t10 = this.regions[e60];
      for (let e61 = 0;e61 < t10.rows; e61++)
        for (let n10 = 0;n10 < t10.cols; n10++) {
          const o11 = this.cellIdFor(t10.id, e61, n10);
          e61 + 1 < t10.rows && c5(o11, this.cellIdFor(t10.id, e61 + 1, n10)), n10 + 1 < t10.cols && c5(o11, this.cellIdFor(t10.id, e61, n10 + 1));
        }
    }
    const l5 = this.regions[0], h5 = this.regions[1], d9 = this.regions[2], u9 = this.regions[3], p9 = this.regions[4], m9 = l5.rows > 0 && l5.cols > 0, g10 = h5.rows > 0 && h5.cols > 0, f10 = d9.rows > 0 && d9.cols > 0, _5 = u9.rows > 0 && u9.cols > 0, y10 = p9.rows > 0 && p9.cols > 0;
    if (m9 && g10)
      for (let e60 = 0;e60 < this.bandRows; e60++)
        c5(this.cellIdFor(0, e60, l5.cols - 1), this.cellIdFor(1, e60, 0));
    if (g10 && f10)
      for (let e60 = 0;e60 < this.bandRows; e60++)
        c5(this.cellIdFor(1, e60, h5.cols - 1), this.cellIdFor(2, e60, 0));
    if (m9 && _5)
      for (let e60 = this.fineRows - this.bandRows;e60 < this.fineRows; e60++)
        c5(this.cellIdFor(0, e60, l5.cols - 1), this.cellIdFor(3, e60 - (this.fineRows - this.bandRows), 0));
    if (_5 && f10)
      for (let e60 = this.fineRows - this.bandRows;e60 < this.fineRows; e60++)
        c5(this.cellIdFor(3, e60 - (this.fineRows - this.bandRows), u9.cols - 1), this.cellIdFor(2, e60, 0));
    if (m9 && y10)
      for (let e60 = this.bandRows;e60 < this.fineRows - this.bandRows; e60++)
        c5(this.cellIdFor(0, e60, l5.cols - 1), this.cellIdFor(4, Math.floor((e60 - this.bandRows) / this.lowScale), 0));
    if (f10 && y10)
      for (let e60 = this.bandRows;e60 < this.fineRows - this.bandRows; e60++)
        c5(this.cellIdFor(4, Math.floor((e60 - this.bandRows) / this.lowScale), p9.cols - 1), this.cellIdFor(2, e60, 0));
    if (g10 && y10)
      for (let e60 = this.bandCols;e60 < this.fineCols - this.bandCols; e60++)
        c5(this.cellIdFor(1, h5.rows - 1, e60 - this.bandCols), this.cellIdFor(4, 0, Math.floor((e60 - this.bandCols) / this.lowScale)));
    if (_5 && y10)
      for (let e60 = this.bandCols;e60 < this.fineCols - this.bandCols; e60++)
        c5(this.cellIdFor(4, p9.rows - 1, Math.floor((e60 - this.bandCols) / this.lowScale)), this.cellIdFor(3, 0, e60 - this.bandCols));
    if (!y10 && !g10 && !_5 && m9 && f10)
      for (let e60 = 0;e60 < Math.min(l5.rows, d9.rows); e60++)
        c5(this.cellIdFor(0, e60, l5.cols - 1), this.cellIdFor(2, e60, 0));
    if (!y10 && !m9 && !f10 && g10 && _5)
      for (let e60 = 0;e60 < Math.min(h5.cols, u9.cols); e60++)
        c5(this.cellIdFor(1, h5.rows - 1, e60), this.cellIdFor(3, 0, e60));
    const b10 = this.flattenNeighborLists(a9);
    this.neighborOffset = b10.offset, this.neighborIds = b10.ids, this.neighborCosts = b10.costs;
  }
  cellIdFor(e54, t4, n8) {
    const o10 = this.regions[e54];
    return o10.offset + t4 * o10.cols + n8;
  }
  stepOnce() {
    if (!this.activeConnSeg) {
      if (this.unsolvedSegs.length === 0)
        return void (this.solved = true);
      const e60 = this.unsolvedSegs.shift();
      this.activeConnSeg = e60, this.activeConnId = e60.connId, this.nodePool.clear(), this.ripChain.clear(), this.heap.clear(), this.seqCounter = 0, this.searchIterations = 0, this.nextStamp();
      const t10 = this.computeH(e60.startZ, e60.startCellId, e60.endZ, e60.endCellId) * this.hyperParameters.greedyMultiplier, n10 = this.nodePool.push(e60.startZ, e60.startCellId, 0, -1, -1, 0), o11 = e60.startZ * this.planeSize + e60.startCellId, i9 = this.getSearchStateIdx(o11, 0);
      return this.bestGStamp[i9] = this.stamp, this.bestGValue[i9] = 0, void this.heap.push(t10, this.seqCounter++, n10);
    }
    this.searchIterations++;
    const e54 = this.ripCount[this.activeConnId] ?? 0, t4 = Math.round(this.baseSearchBudgetIters * (1 + 0.25 * Math.min(e54, 10)));
    if (this.searchIterations > t4) {
      const e60 = this.penalty2d;
      for (let t10 = 0;t10 < e60.length; t10++)
        e60[t10] = 0.9 * e60[t10];
      return this.unsolvedSegs.push(this.activeConnSeg), this.activeConnSeg = null, this.activeConnId = -1, this.heap.clear(), this.nodePool.clear(), this.consecutiveSkips++, void (this.consecutiveSkips >= Math.max(3, 3 * this.unsolvedSegs.length) && (this.error = `Convergence failure: ${this.unsolvedSegs.length} connections stuck`, this.failed = true));
    }
    if (this.heap.size === 0)
      return this.error = `No path found for ${this.connIdToName[this.activeConnId]}`, void (this.failed = true);
    const n8 = this.heap.pop(), o10 = this.nodePool.z[n8], i8 = this.nodePool.cellId[n8], r9 = this.nodePool.g[n8], s7 = this.nodePool.ripHead[n8], a9 = this.nodePool.ripCount[n8], c5 = o10 * this.planeSize + i8, l5 = this.getSearchStateIdx(c5, a9);
    if (this.visitedStamp[l5] === this.stamp)
      return;
    this.visitedStamp[l5] = this.stamp, this.visitedFlatStamp[c5] = this.stamp;
    const h5 = this.activeConnSeg;
    if (o10 === h5.endZ && i8 === h5.endCellId)
      return this.finalizeRoute(n8), this.activeConnSeg = null, void (this.activeConnId = -1);
    const d9 = this.visitedStamp, u9 = this.stamp, p9 = this.activeConnId, m9 = h5.endZ, g10 = h5.endCellId, f10 = this.neighborOffset[i8], _5 = this.neighborOffset[i8 + 1];
    for (let e60 = f10;e60 < _5; e60++) {
      const t10 = this.neighborIds[e60], c9 = o10 * this.planeSize + t10;
      if (this.computeMoveCostAndRips(p9, o10, i8, t10, false, s7, a9, this.neighborCosts[e60]), this._moveCost < 0)
        continue;
      const l10 = this.getSearchStateIdx(c9, this._moveRipCount);
      if (d9[l10] === u9)
        continue;
      const h9 = r9 + this._moveCost;
      if (this.bestGStamp[l10] === u9 && h9 >= this.bestGValue[l10])
        continue;
      this.bestGStamp[l10] = u9, this.bestGValue[l10] = h9;
      const f11 = h9 + this.computeH(o10, t10, m9, g10) * this.hyperParameters.greedyMultiplier, _10 = this.nodePool.push(o10, t10, h9, n8, this._moveRippedHead, this._moveRipCount);
      this.heap.push(f11, this.seqCounter++, _10);
    }
    if (this.viaAllowed[i8])
      for (let e60 = 0;e60 < this.layers; e60++) {
        if (e60 === o10)
          continue;
        const t10 = e60 * this.planeSize + i8;
        if (this.computeMoveCostAndRips(p9, e60, i8, i8, true, s7, a9, 0), this._moveCost < 0)
          continue;
        const c9 = this.getSearchStateIdx(t10, this._moveRipCount);
        if (d9[c9] === u9)
          continue;
        const l10 = r9 + this._moveCost;
        if (this.bestGStamp[c9] === u9 && l10 >= this.bestGValue[c9])
          continue;
        this.bestGStamp[c9] = u9, this.bestGValue[c9] = l10;
        const h9 = l10 + this.computeH(e60, i8, m9, g10) * this.hyperParameters.greedyMultiplier, f11 = this.nodePool.push(e60, i8, l10, n8, this._moveRippedHead, this._moveRipCount);
        this.heap.push(h9, this.seqCounter++, f11);
      }
  }
  computeMoveCostAndRips(e54, t4, n8, o10, i8, r9, s7, a9) {
    let c5 = 0, l5 = r9, h5 = s7;
    const d9 = t4 * this.planeSize + o10, u9 = i8 ? this.obstacleViaRootIdsByCell[o10] : [...this.obstacleTraceRootIdsFlat[t4 * this.planeSize + n8] ?? [], ...this.obstacleTraceRootIdsFlat[d9] ?? []];
    if (this.isBlockedByObstacleRoots(u9, e54) && (i8 ? this.isViaMoveBlockedByObstacleGeometry({ activeConn: e54, cellId: o10 }) : this.isLateralMoveBlockedByObstacleGeometry({ activeConn: e54, layer: t4, fromCellId: n8, toCellId: o10 })))
      return this._moveCost = -1, this._moveRippedHead = l5, void (this._moveRipCount = h5);
    const p9 = this.hasSameRootObstacle(u9, e54);
    if (i8) {
      c5 += this.hyperParameters.viaBaseCost, c5 += Math.min(this.penalty2d[o10], this.penaltyCap);
      const n10 = this.portOwnerFlat[d9], i9 = this.allowSharedUse(e54, n10), r10 = this.activeConnSeg, s9 = !!r10 && t4 === r10.endZ && o10 === r10.endCellId;
      if (n10 >= 0 && n10 !== e54 && !i9 && !s9)
        return this._moveCost = -1, void (this._moveRippedHead = l5);
      this.fillViaOccupants(o10, e54);
      const a10 = this._viaOccs;
      for (let e60 = 0;e60 < a10.length; e60++) {
        const t10 = a10[e60];
        this.ripChain.contains(l5, t10) || (c5 += this.hyperParameters.ripCost, l5 = this.ripChain.append(l5, t10), h5++), c5 += this.hyperParameters.ripViaPenalty;
      }
    } else {
      c5 += a9, c5 += Math.min(this.penalty2d[o10], this.penaltyCap);
      const n10 = this.portOwnerFlat[d9], i9 = this.allowSharedUse(e54, n10), r10 = this.activeConnSeg, s9 = !!r10 && t4 === r10.endZ && o10 === r10.endCellId;
      if (n10 >= 0 && n10 !== e54 && !i9 && !s9)
        return this._moveCost = -1, void (this._moveRippedHead = l5);
      this.fillTraceOccupants(d9, e54, this._cellOccs);
      for (let e60 = 0;e60 < this._cellOccs.length; e60++) {
        const t10 = this._cellOccs[e60];
        this.ripChain.contains(l5, t10) || (c5 += this.hyperParameters.ripCost, l5 = this.ripChain.append(l5, t10), h5++), c5 += this.hyperParameters.ripTracePenalty;
      }
    }
    p9 && (c5 *= this.hyperParameters.sameRootObstacleCostMultiplier), this._moveCost = c5, this._moveRippedHead = l5, this._moveRipCount = h5;
  }
  fillViaOccupants(e54, t4) {
    const n8 = this._viaOccs;
    n8.length = 0;
    const o10 = this.cellCenterX[e54], i8 = this.cellCenterY[e54];
    this.forEachCellNearCircle(o10, i8, this.viaKeepoutRadius, (e60) => {
      if (voe(o10, i8, this.viaKeepoutRadius, this.cellMinX[e60], this.cellMinY[e60], this.cellMaxX[e60], this.cellMaxY[e60]))
        for (let o11 = 0;o11 < this.layers; o11++)
          this.pushFlatOccupants(o11 * this.planeSize + e60, t4, n8);
    });
  }
  fillTraceOccupants(e54, t4, n8) {
    n8.length = 0, this.pushFlatOccupants(e54, t4, n8);
  }
  pushFlatOccupants(e54, t4, n8) {
    const o10 = this.usedCellsFlat[e54];
    o10 === -1 || o10 === t4 || this.allowSharedUse(t4, o10) || boe(n8, o10);
    const i8 = this.sharedCellsFlat[e54];
    if (i8)
      for (let e60 = 0;e60 < i8.length; e60++) {
        const o11 = i8[e60];
        o11 !== t4 && (this.allowSharedUse(t4, o11) || boe(n8, o11));
      }
  }
  addSharedOccupant(e54, t4) {
    if (this.usedCellsFlat[e54] === t4)
      return;
    let n8 = this.sharedCellsFlat[e54];
    n8 || (n8 = [], this.sharedCellsFlat[e54] = n8), boe(n8, t4);
  }
  replaceOccupants(e54, t4) {
    this.usedCellsFlat[e54] = t4, this.sharedCellsFlat[e54] = undefined;
  }
  removeOccupant(e54, t4) {
    const n8 = this.sharedCellsFlat[e54];
    if (this.usedCellsFlat[e54] === t4)
      return void (n8 && n8.length > 0 ? (this.usedCellsFlat[e54] = n8.pop(), n8.length === 0 && (this.sharedCellsFlat[e54] = undefined)) : this.usedCellsFlat[e54] = -1);
    if (!n8)
      return;
    const o10 = n8.indexOf(t4);
    o10 !== -1 && (n8.splice(o10, 1), n8.length === 0 && (this.sharedCellsFlat[e54] = undefined));
  }
  allowSharedUse(e54, t4) {
    if (t4 < 0)
      return false;
    return this.connIdToRootNet[t4] === this.connIdToRootNet[e54];
  }
  shouldSkipFixedPortHalo(e54, t4) {
    const n8 = this.portOwnerFlat[e54];
    return n8 !== t4 && (n8 === -2 || !(n8 < 0) && !this.allowSharedUse(t4, n8));
  }
  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(e54, t4) {
    return e54;
  }
  computeH(e54, t4, n8, o10) {
    const i8 = Math.hypot(this.cellCenterX[t4] - this.cellCenterX[o10], this.cellCenterY[t4] - this.cellCenterY[o10]);
    return e54 === n8 ? i8 : i8 + this.hyperParameters.viaBaseCost;
  }
  internConn(e54, t4) {
    const n8 = this.connNameToId.get(e54);
    if (n8 !== undefined)
      return n8;
    const o10 = this.connIdToName.length;
    return this.connIdToName.push(e54), this.connIdToRootNet.push(goe(e54, t4)), this.connNameToId.set(e54, o10), o10;
  }
  buildConnectionSegs() {
    const e54 = new Map;
    for (const t10 of this.nodeWithPortPoints.portPoints) {
      const n10 = t10.connectionName;
      e54.has(n10) || e54.set(n10, { points: [], rootConnectionName: t10.rootConnectionName }), e54.get(n10).points.push(t10);
    }
    const t4 = [], n8 = new Map;
    for (const [o10, i8] of e54) {
      const e60 = i8.points, r9 = eoe(e60);
      if (r9.length === 0)
        continue;
      const s7 = this.internConn(o10, i8.rootConnectionName);
      for (const [e61, i9] of r9) {
        const r10 = this.pointToCell(e61), a9 = this.pointToCell(i9), c5 = `${r10.z}:${r10.cellId}`, l5 = `${a9.z}:${a9.cellId}`, h5 = c5 < l5 ? `${c5}|${l5}` : `${l5}|${c5}`, d9 = this.connIdToRootNet[s7], u9 = `${d9}|${h5}`, p9 = n8.get(u9);
        if (p9) {
          if (this.overlapFriendlyRootNets.add(d9), !p9.connectionAliases.some((e63) => e63.connectionName === o10)) {
            const t10 = p9.startZ === r10.z && p9.startCellId === r10.cellId && p9.endZ === a9.z && p9.endCellId === a9.cellId, n10 = p9.startZ === a9.z && p9.startCellId === a9.cellId && p9.endZ === r10.z && p9.endCellId === r10.cellId;
            if (!t10 && !n10)
              throw new Error(`Connection alias ${o10} does not match canonical segment ${u9}`);
            p9.connectionAliases.push({ connectionName: o10, rootConnectionName: d9, startPoint: e61, endPoint: i9, reversedFromCanonical: !t10 && n10 });
          }
          continue;
        }
        const m9 = { connId: s7, startZ: r10.z, startCellId: r10.cellId, startPoint: e61, endZ: a9.z, endCellId: a9.cellId, endPoint: i9, connectionAliases: [{ connectionName: o10, rootConnectionName: d9, startPoint: e61, endPoint: i9, reversedFromCanonical: false }] };
        n8.set(u9, m9), t4.push(m9);
      }
    }
    return t4;
  }
  pointToCell(e54) {
    const t4 = yoe(Math.floor((e54.x - this.boundsMinX) / this.highResolutionCellSize), 0, this.fineCols - 1), n8 = yoe(Math.floor((e54.y - this.boundsMinY) / this.highResolutionCellSize), 0, this.fineRows - 1);
    let o10 = 4;
    t4 < this.bandCols ? o10 = 0 : t4 >= this.fineCols - this.bandCols ? o10 = 2 : n8 < this.bandRows ? o10 = 1 : n8 >= this.fineRows - this.bandRows && (o10 = 3);
    const i8 = this.regions[o10], r9 = n8 - i8.fineOriginRow, s7 = t4 - i8.fineOriginCol, a9 = yoe(Math.floor(r9 / i8.cellScale), 0, Math.max(0, i8.rows - 1)), c5 = yoe(Math.floor(s7 / i8.cellScale), 0, Math.max(0, i8.cols - 1));
    return { z: this.zToLayer.get(e54.z) ?? 0, cellId: this.cellIdFor(o10, a9, c5) };
  }
  shuffleConnections() {
    const e54 = this.unsolvedSegs;
    let t4 = this.hyperParameters.shuffleSeed >>> 0;
    const n8 = () => (t4 = Math.imul(t4, 1664525) + 1013904223 >>> 0, t4 / 4294967295);
    for (let t10 = e54.length - 1;t10 > 0; t10--) {
      const o10 = Math.floor(n8() * (t10 + 1)), i8 = e54[t10];
      e54[t10] = e54[o10], e54[o10] = i8;
    }
  }
  finalizeRoute(e54) {
    this.consecutiveSkips = Math.max(0, this.consecutiveSkips - 1);
    const t4 = [];
    let n8 = e54;
    for (;n8 >= 0; ) {
      const e60 = this.nodePool.z[n8], o11 = this.nodePool.cellId[n8];
      t4.push(e60 * this.planeSize + o11), n8 = this.nodePool.parent[n8];
    }
    for (t4.reverse();t4.length > 1 && this.sharedCrossRootPortFlat[t4[0]]; )
      t4.shift();
    for (;t4.length > 1 && this.sharedCrossRootPortFlat[t4[t4.length - 1]]; )
      t4.pop();
    const o10 = this.extractViaCellIds(t4), i8 = this.activeConnId;
    this.ripChain.collect(this.nodePool.ripHead[e54], this._rippedIds);
    for (let e60 = 0;e60 < this._rippedIds.length; e60++)
      if (this.ripTrace(this._rippedIds[e60]), this.failed)
        return;
    const r9 = [];
    for (let e60 = 0;e60 < t4.length; e60++) {
      const n10 = t4[e60], o11 = Math.floor(n10 / this.planeSize), s9 = n10 - o11 * this.planeSize;
      this.markTraceFootprint(i8, o11, s9, r9);
    }
    const s7 = [];
    for (let e60 = 0;e60 < o10.length; e60++)
      this.markViaFootprint(i8, o10[e60], r9, s7);
    for (;this.usedIndicesByConn.length <= i8; )
      this.usedIndicesByConn.push(undefined);
    const a9 = this.usedIndicesByConn[i8] ?? [];
    for (a9.push(...r9), this.usedIndicesByConn[i8] = a9;this.solvedRoutes.length <= i8; )
      this.solvedRoutes.push(undefined);
    const c5 = this.solvedRoutes[i8] ?? [];
    c5.push({ connId: i8, states: Int32Array.from(t4), viaCellIds: Int32Array.from(o10), startPoint: this.activeConnSeg.startPoint, endPoint: this.activeConnSeg.endPoint, connectionAliases: this.activeConnSeg.connectionAliases }), this.solvedRoutes[i8] = c5;
    for (let e60 = 0;e60 < s7.length; e60++)
      if (this.ripTrace(s7[e60]), this.failed)
        return;
    if (this._rippedIds.length > 0 || s7.length > 0) {
      const e60 = this.penalty2d, t10 = this.penaltyCap;
      if (this.totalRipEvents > 50)
        for (let t11 = 0;t11 < e60.length; t11++)
          e60[t11] = 0.99 * e60[t11];
      else
        for (let n10 = 0;n10 < e60.length; n10++)
          e60[n10] > t10 && (e60[n10] = 0.5 * e60[n10]);
    }
  }
  extractViaCellIds(e54) {
    const t4 = [];
    for (let n8 = 1;n8 < e54.length; n8++) {
      const o10 = e54[n8 - 1], i8 = e54[n8], r9 = Math.floor(o10 / this.planeSize), s7 = Math.floor(i8 / this.planeSize);
      r9 !== s7 && t4.push(i8 - s7 * this.planeSize);
    }
    return t4;
  }
  markTraceFootprint(e54, t4, n8, o10) {
    const i8 = this.cellCenterX[n8], r9 = this.cellCenterY[n8];
    this.forEachCellNearCircle(i8, r9, this.traceKeepoutRadius, (s7) => {
      if (!voe(i8, r9, this.traceKeepoutRadius, this.cellMinX[s7], this.cellMinY[s7], this.cellMaxX[s7], this.cellMaxY[s7]))
        return;
      const a9 = t4 * this.planeSize + s7;
      if (s7 !== n8 && this.shouldSkipFixedPortHalo(a9, e54))
        return;
      const c5 = this.usedCellsFlat[a9], l5 = this.allowSharedUse(e54, c5);
      (c5 === -1 || c5 === e54 || l5) && (c5 !== -1 && c5 !== e54 ? this.addSharedOccupant(a9, e54) : this.usedCellsFlat[a9] = e54, o10.push(a9));
    });
  }
  markViaFootprint(e54, t4, n8, o10) {
    const i8 = this.cellCenterX[t4], r9 = this.cellCenterY[t4];
    this.forEachCellNearCircle(i8, r9, this.viaKeepoutRadius, (s7) => {
      if (voe(i8, r9, this.viaKeepoutRadius, this.cellMinX[s7], this.cellMinY[s7], this.cellMaxX[s7], this.cellMaxY[s7]))
        for (let i9 = 0;i9 < this.layers; i9++) {
          const r10 = i9 * this.planeSize + s7;
          if (s7 !== t4 && this.shouldSkipFixedPortHalo(r10, e54))
            continue;
          if (this.fillTraceOccupants(r10, e54, this._cellOccs), this._cellOccs.length > 0) {
            for (let e60 = 0;e60 < this._cellOccs.length; e60++)
              boe(o10, this._cellOccs[e60]);
            this.replaceOccupants(r10, e54), n8.push(r10);
            continue;
          }
          const a9 = this.usedCellsFlat[r10];
          a9 !== -1 && a9 !== e54 ? this.addSharedOccupant(r10, e54) : this.usedCellsFlat[r10] = e54, n8.push(r10);
        }
    });
  }
  forEachCellNearCircle(e54, t4, n8, o10) {
    const i8 = yoe(Math.floor((e54 - n8 - this.boundsMinX) / this.highResolutionCellSize), 0, this.fineCols - 1), r9 = yoe(Math.floor((e54 + n8 - this.boundsMinX) / this.highResolutionCellSize), 0, this.fineCols - 1), s7 = yoe(Math.floor((t4 - n8 - this.boundsMinY) / this.highResolutionCellSize), 0, this.fineRows - 1), a9 = yoe(Math.floor((t4 + n8 - this.boundsMinY) / this.highResolutionCellSize), 0, this.fineRows - 1);
    for (let e60 = 0;e60 < this.regions.length; e60++) {
      const t10 = this.regions[e60];
      if (t10.rows === 0 || t10.cols === 0)
        continue;
      const n10 = Math.max(s7, t10.fineOriginRow), c5 = Math.min(a9, t10.fineOriginRow + t10.fineRows - 1), l5 = Math.max(i8, t10.fineOriginCol), h5 = Math.min(r9, t10.fineOriginCol + t10.fineCols - 1);
      if (n10 > c5)
        continue;
      if (l5 > h5)
        continue;
      const d9 = Math.floor((n10 - t10.fineOriginRow) / t10.cellScale), u9 = Math.floor((c5 - t10.fineOriginRow) / t10.cellScale), p9 = Math.floor((l5 - t10.fineOriginCol) / t10.cellScale), m9 = Math.floor((h5 - t10.fineOriginCol) / t10.cellScale);
      for (let e61 = d9;e61 <= u9; e61++)
        for (let n11 = p9;n11 <= m9; n11++)
          o10(this.cellIdFor(t10.id, e61, n11));
    }
  }
  ripTrace(e54) {
    for (;this.ripCount.length <= e54; )
      this.ripCount.push(0);
    if (this.ripCount[e54]++, this.totalRipEvents++, this.totalRipEvents >= this.MAX_RIPS)
      return this.error = `Convergence failure: exceeded MAX_RIPS ${this.MAX_RIPS}`, void (this.failed = true);
    const t4 = this.getSolvedRoutesForConn(e54);
    if (t4.length > 0)
      for (const e60 of t4) {
        for (let t10 = 0;t10 < e60.states.length; t10++) {
          const n10 = e60.states[t10] % this.planeSize;
          this.penalty2d[n10] = this.penalty2d[n10] + this.hyperParameters.ripTracePenalty;
        }
        for (let t10 = 0;t10 < e60.viaCellIds.length; t10++) {
          const n10 = e60.viaCellIds[t10];
          this.penalty2d[n10] = this.penalty2d[n10] + this.hyperParameters.ripViaPenalty;
        }
      }
    const n8 = this.usedIndicesByConn[e54];
    if (n8) {
      for (let t10 = 0;t10 < n8.length; t10++)
        this.removeOccupant(n8[t10], e54);
      this.usedIndicesByConn[e54] = undefined;
    }
    if (t4.length > 0) {
      this.solvedRoutes[e54] = undefined;
      for (const n10 of t4) {
        const t10 = n10.states[0], o10 = n10.states[n10.states.length - 1], i8 = Math.floor(t10 / this.planeSize), r9 = Math.floor(o10 / this.planeSize);
        this.unsolvedSegs.push({ connId: e54, startZ: i8, startCellId: t10 - i8 * this.planeSize, startPoint: n10.startPoint, endZ: r9, endCellId: o10 - r9 * this.planeSize, endPoint: n10.endPoint, connectionAliases: n10.connectionAliases });
      }
    }
  }
  flattenNeighborLists(e54) {
    const t4 = new Int32Array(e54.length + 1);
    let n8 = 0;
    for (let o11 = 0;o11 < e54.length; o11++)
      t4[o11] = n8, n8 += e54[o11].length;
    t4[e54.length] = n8;
    const o10 = new Int32Array(n8), i8 = new Float32Array(n8);
    let r9 = 0;
    for (let t10 = 0;t10 < e54.length; t10++) {
      const n10 = e54[t10];
      for (let e60 = 0;e60 < n10.length; e60++) {
        const t11 = n10[e60];
        o10[r9] = t11.cellId, i8[r9] = t11.cost, r9++;
      }
    }
    return { offset: t4, ids: o10, costs: i8 };
  }
  visualize() {
    const e54 = ["red", "blue", "orange", "green"], t4 = this.gridToBoundsTransform, n8 = [], o10 = [], i8 = [], r9 = [];
    r9.push({ center: { x: this.nodeWithPortPoints.center.x, y: this.nodeWithPortPoints.center.y }, width: this.nodeWithPortPoints.width, height: this.nodeWithPortPoints.height, stroke: "gray" });
    const s7 = ({ route: t10, connectionName: n10, strokeWidth: i9, strokeDash: r10, labelPrefix: s9 }) => {
      if (t10.length < 2)
        return;
      let a10 = 0;
      for (let c9 = 1;c9 < t10.length; c9 += 1) {
        const l5 = t10[c9 - 1];
        t10[c9].z !== l5.z && (c9 - a10 >= 2 && o10.push({ points: t10.slice(a10, c9).map((e60) => ({ x: e60.x, y: e60.y })), strokeColor: e54[l5.z] ?? "rgba(128,128,128,0.75)", strokeWidth: i9, strokeDash: r10, label: `${s9} ${n10} z=${l5.z}` }), a10 = c9);
      }
      if (t10.length - a10 < 2)
        return;
      const c5 = t10[a10].z;
      o10.push({ points: t10.slice(a10).map((e60) => ({ x: e60.x, y: e60.y })), strokeColor: e54[c5] ?? "rgba(128,128,128,0.75)", strokeWidth: i9, strokeDash: r10, label: `${s9} ${n10} z=${c5}` });
    };
    for (const e60 of this.obstacles)
      if (e60.type !== "rect") {
        s7({ route: e60.route, connectionName: e60.connectionName, strokeWidth: e60.traceThickness, strokeDash: [0.12, 0.08], labelPrefix: "fixed obstacle" });
        for (const t10 of e60.vias)
          i8.push({ center: { x: t10.x, y: t10.y }, radius: e60.viaDiameter / 2, fill: "rgba(128,0,128,0.25)", stroke: "purple", label: `fixed obstacle ${e60.connectionName} via` });
      } else
        r9.push({ center: e60.center, width: e60.width, height: e60.height, fill: "rgba(128,0,128,0.12)", stroke: "purple", label: `fixed obstacle ${e60.connectionName}` });
    if (this.showPenaltyMap && this.penalty2d) {
      let e60 = 0;
      for (let t10 = 0;t10 < this.penalty2d.length; t10++)
        this.penalty2d[t10] > e60 && (e60 = this.penalty2d[t10]);
      if (e60 > 0)
        for (let n10 = 0;n10 < this.planeSize; n10++) {
          const o11 = this.penalty2d[n10];
          if (o11 <= 0)
            continue;
          const i9 = Une(t4, { x: this.cellCenterX[n10], y: this.cellCenterY[n10] }), s9 = Math.min(0.6, o11 / e60 * 0.6);
          r9.push({ center: i9, width: this.cellWidth[n10] * t4.a, height: this.cellHeight[n10] * t4.e, fill: `rgba(255,165,0,${s9.toFixed(3)})` });
        }
    }
    if (this.showUsedCellMap && this.usedCellsFlat)
      for (let e60 = 0;e60 < this.layers; e60++) {
        const n10 = e60 * this.planeSize;
        for (let e61 = 0;e61 < this.planeSize; e61++) {
          if (this.usedCellsFlat[n10 + e61] === -1)
            continue;
          const o11 = Une(t4, { x: this.cellCenterX[e61], y: this.cellCenterY[e61] });
          r9.push({ center: o11, width: this.cellWidth[e61] * t4.a, height: this.cellHeight[e61] * t4.e, fill: "rgba(0,0,255,0.5)" });
        }
      }
    for (const t10 of this.nodeWithPortPoints.portPoints)
      n8.push({ x: t10.x, y: t10.y, color: e54[t10.z] ?? "gray", label: t10.connectionName });
    const a9 = this.getOutput();
    for (const e60 of a9)
      s7({ route: e60.route, connectionName: e60.connectionName, strokeWidth: this.traceThickness, labelPrefix: "B01 route" });
    for (const e60 of a9)
      for (const t10 of e60.vias)
        i8.push({ center: { x: t10.x, y: t10.y }, radius: this.viaDiameter / 2, fill: "rgba(0,0,0,0.3)", stroke: "black", label: `B01 route ${e60.connectionName} via` });
    if (this.activeConnSeg && this.visitedFlatStamp) {
      const e60 = this.stamp;
      for (let o11 = 0;o11 < this.layers; o11++) {
        const i9 = o11 * this.planeSize;
        for (let o12 = 0;o12 < this.planeSize; o12++) {
          if (this.visitedFlatStamp[i9 + o12] !== e60)
            continue;
          const r10 = Une(t4, { x: this.cellCenterX[o12], y: this.cellCenterY[o12] });
          n8.push({ x: r10.x, y: r10.y, color: "rgba(0,0,255,0.2)" });
        }
      }
    }
    return { points: n8, lines: o10, circles: i8, rects: r9, coordinateSystem: "cartesian", title: `HighDensityB01 [${this.getSolvedRouteCount()} solved, ${this.unsolvedSegs?.length ?? 0} remaining]` };
  }
  getOutput() {
    const e54 = this.gridToBoundsTransform, t4 = [];
    for (let n8 = 0;n8 < this.solvedRoutes.length; n8++) {
      const o10 = this.getSolvedRoutesForConn(n8);
      if (o10.length !== 0)
        for (const n10 of o10) {
          const o11 = Array.from(n10.states, (t10) => {
            const n11 = Math.floor(t10 / this.planeSize), o12 = t10 - n11 * this.planeSize, i9 = Une(e54, { x: this.cellCenterX[o12], y: this.cellCenterY[o12] });
            return { x: i9.x, y: i9.y, z: this.layerToZ.get(n11) ?? n11 };
          }), i8 = Array.from(n10.viaCellIds, (t10) => Une(e54, { x: this.cellCenterX[t10], y: this.cellCenterY[t10] }));
          for (const e60 of n10.connectionAliases) {
            const n11 = (e60.reversedFromCanonical ? [...o11].reverse() : o11).map((e61) => ({ ...e61 }));
            n11.length > 0 && (n11[0] = { ...e60.startPoint }, n11.length > 1 && (n11[n11.length - 1] = { ...e60.endPoint })), t4.push({ connectionName: e60.connectionName, rootConnectionName: e60.rootConnectionName, regionId: this.nodeWithPortPoints.capacityMeshNodeId, traceThickness: this.traceThickness, viaDiameter: this.viaDiameter, route: n11, vias: i8.map((e61) => ({ ...e61 })) });
          }
        }
    }
    return t4;
  }
  getSolvedRoutesForConn(e54) {
    const t4 = this.solvedRoutes[e54];
    return t4 ? Array.isArray(t4) ? t4 : [t4] : [];
  }
  getSolvedRouteCount() {
    let e54 = 0;
    for (let t4 = 0;t4 < this.solvedRoutes.length; t4++)
      e54 += this.getSolvedRoutesForConn(t4).length;
    return e54;
  }
  computeGridToBoundsTransform() {
    let e54 = 1 / 0, t4 = -1 / 0, n8 = 1 / 0, o10 = -1 / 0;
    for (let i9 = 0;i9 < this.planeSize; i9++) {
      const r10 = this.cellCenterX[i9], s9 = this.cellCenterY[i9];
      r10 < e54 && (e54 = r10), r10 > t4 && (t4 = r10), s9 < n8 && (n8 = s9), s9 > o10 && (o10 = s9);
    }
    const i8 = t4 - e54, r9 = o10 - n8, s7 = this.boundsMaxX - this.boundsMinX, a9 = this.boundsMaxY - this.boundsMinY, c5 = i8 > 0 ? s7 / i8 : 1, l5 = r9 > 0 ? a9 / r9 : 1;
    return { a: c5, b: 0, c: i8 > 0 ? this.boundsMinX - c5 * e54 : (this.boundsMinX + this.boundsMaxX) / 2 - e54, d: 0, e: l5, f: r9 > 0 ? this.boundsMinY - l5 * n8 : (this.boundsMinY + this.boundsMaxY) / 2 - n8 };
  }
};
var Toe = ({ routes: e54, movablePreloadedConnectionNames: t4, boardObstacles: n8, connMap: o10, layerCount: i8, viaToPadClearance: r9, allowBlindAndBuriedVias: s7 }) => e54.some((e60) => {
  if (!t4.has(e60.connectionName))
    return false;
  return os(e60, { layerCount: i8, allowBlindAndBuriedVias: s7 }).viaSpans.some((t10) => n8.some((n10) => {
    if ((({ obstacle: e61, route: t11, connMap: n11 }) => {
      if (xo(e61, t11, n11))
        return true;
      if (!t11.rootConnectionName)
        return false;
      const o11 = n11.getNetConnectedToId(t11.connectionName) ?? n11.getNetConnectedToId(t11.rootConnectionName) ?? (n11.netMap[t11.rootConnectionName] ? t11.rootConnectionName : undefined);
      return !!o11 && e61.connectedTo.some((e63) => (n11.getNetConnectedToId(e63) ?? (n11.netMap[e63] ? e63 : undefined)) === o11);
    })({ obstacle: n10, route: e60, connMap: o10 }))
      return false;
    const s9 = ((e61, t11) => {
      const n11 = e61.__zLayers ?? e61.zLayers;
      return n11 || e61.layers.map((e63) => mo(e63, t11));
    })(n10, i8);
    return !!s9.some((e61) => e61 >= t10.minZ && e61 <= t10.maxZ) && ((e61, t11) => {
      const n11 = -1 * (t11.ccwRotationDegrees ?? 0) * Math.PI / 180, o11 = e61.x - t11.center.x, i9 = e61.y - t11.center.y, r10 = o11 * Math.cos(n11) - i9 * Math.sin(n11), s10 = o11 * Math.sin(n11) + i9 * Math.cos(n11), a9 = Math.max(Math.abs(r10) - t11.width / 2, 0), c5 = Math.max(Math.abs(s10) - t11.height / 2, 0);
      return Math.hypot(a9, c5);
    })(t10.center, n10) < t10.diameter / 2 + r9;
  }));
});
var Eoe = class extends ni {
  params;
  highDensitySolver;
  forceImproveSolver;
  repairSolver;
  phase = "route";
  constructor(e54) {
    super(), this.params = e54, this.stats = { preloadedViaCandidateRejectionCount: 0, forceImproveCandidateRejectionCount: 0, repairCandidateRejectionCount: 0 }, this.highDensitySolver = new Dz({ captureSearchDebug: e54.captureSearchDebug, nodePortPoints: [e54.nodeWithPortPoints], colorMap: e54.colorMap, connMap: e54.connMap, viaDiameter: e54.viaDiameter, traceWidth: e54.traceWidth, obstacleMargin: e54.obstacleMargin, effort: e54.effort, nodePfById: e54.nodePfById, obstacles: e54.obstacles, layerCount: e54.layerCount, useGrowShrinkHighDensityIntraNodeSolver: true, preserveTerminalPcbPortIds: false, growShrinkFallbackToInvalidGeometryOnFailure: false, growShrinkSolutionValidator: e54.boardObstacles && e54.movablePreloadedConnectionNames && e54.viaToPadClearance !== undefined ? (e60) => this.validateCandidateRoutes(e60) : undefined }), this.activeSubSolver = this.highDensitySolver, this.MAX_ITERATIONS = 1e8 * e54.effort;
  }
  getSolverName() {
    return "Pipeline9RegionalFallbackSolver";
  }
  validateCandidateRoutes(e54) {
    const { boardObstacles: t4, movablePreloadedConnectionNames: n8, viaToPadClearance: o10 } = this.params;
    if (!t4 || !n8 || o10 === undefined)
      return true;
    const i8 = Toe({ routes: e54, movablePreloadedConnectionNames: n8, boardObstacles: t4, connMap: this.params.connMap, layerCount: this.params.layerCount, allowBlindAndBuriedVias: this.params.allowBlindAndBuriedVias, viaToPadClearance: o10 });
    return i8 && (this.stats.preloadedViaCandidateRejectionCount = Number(this.stats.preloadedViaCandidateRejectionCount ?? 0) + 1), !i8;
  }
  _step() {
    if (this.phase === "route") {
      if (this.highDensitySolver.step(), this.highDensitySolver.failed)
        return this.error = this.highDensitySolver.error, void (this.failed = true);
      if (!this.highDensitySolver.solved)
        return;
      const e54 = yne(this.highDensitySolver.routes);
      return this.validateCandidateRoutes(e54) ? (this.forceImproveSolver = new SZ({ nodeWithPortPoints: [this.params.nodeWithPortPoints], hdRoutes: e54, colorMap: this.params.colorMap, totalStepsPerNode: Math.max(12, Math.round(20 * this.params.effort)), nodeAssignmentMargin: this.params.obstacleMargin }), this.activeSubSolver = this.forceImproveSolver, void (this.phase = "improve")) : (this.error = "Pipeline9 regional route output failed its candidate validator", void (this.failed = true));
    }
    if (this.phase === "improve") {
      if (this.forceImproveSolver.step(), this.forceImproveSolver.failed)
        return this.error = this.forceImproveSolver.error, void (this.failed = true);
      if (!this.forceImproveSolver.solved)
        return;
      const e54 = this.forceImproveSolver.getOutput();
      return this.validateCandidateRoutes(e54) ? (this.repairSolver = new g1({ nodeWithPortPoints: [this.params.nodeWithPortPoints], hdRoutes: e54, obstacles: this.params.obstacles, colorMap: this.params.colorMap, repairMargin: this.params.obstacleMargin, minimumTraceWidth: this.params.traceWidth, connMap: this.params.connMap }), this.activeSubSolver = this.repairSolver, void (this.phase = "repair")) : (this.stats.forceImproveCandidateRejectionCount = Number(this.stats.forceImproveCandidateRejectionCount ?? 0) + 1, this.error = "Pipeline9 regional force-improve output failed its candidate validator", void (this.failed = true));
    }
    if (this.phase === "repair") {
      if (this.repairSolver.step(), this.repairSolver.failed)
        return this.error = this.repairSolver.error, void (this.failed = true);
      if (!this.repairSolver.solved)
        return;
      const e54 = this.repairSolver.getOutput();
      return this.validateCandidateRoutes(e54) ? (this.activeSubSolver = null, this.phase = "done", void (this.solved = true)) : (this.stats.repairCandidateRejectionCount = Number(this.stats.repairCandidateRejectionCount ?? 0) + 1, this.error = "Pipeline9 regional repair output failed its candidate validator", void (this.failed = true));
    }
  }
  getOutput() {
    return this.repairSolver?.getOutput() ?? this.forceImproveSolver?.getOutput() ?? this.highDensitySolver.routes;
  }
  visualize() {
    return this.repairSolver?.visualize() ?? this.forceImproveSolver?.visualize() ?? this.highDensitySolver.visualize();
  }
};
var Aoe = (e54, t4) => ({ minX: e54.center.x - e54.width / 2 - t4, maxX: e54.center.x + e54.width / 2 + t4, minY: e54.center.y - e54.height / 2 - t4, maxY: e54.center.y + e54.height / 2 + t4 });
var Ooe = (e54, t4, n8, o10, i8) => {
  const r9 = new Set(t4.availableZ ?? t4.portPoints.map((e60) => e60.z)), s7 = os(e54, i8);
  return s7.wireSegments.some((e60) => r9.has(e60.z) && ((e61, t10, n10, o11) => Math.min(e61.x, t10.x) - n10 <= o11.maxX && Math.max(e61.x, t10.x) + n10 >= o11.minX && Math.min(e61.y, t10.y) - n10 <= o11.maxY && Math.max(e61.y, t10.y) + n10 >= o11.minY)(e60.start, e60.end, e60.width / 2 + o10, n8)) || s7.viaSpans.some((e60) => [...r9].some((t10) => t10 >= e60.minZ && t10 <= e60.maxZ) && ((e61, t10, n10) => {
    const o11 = Math.max(n10.minX - e61.x, 0, e61.x - n10.maxX), i9 = Math.max(n10.minY - e61.y, 0, e61.y - n10.maxY);
    return o11 * o11 + i9 * i9 <= t10 * t10;
  })(e60.center, e60.diameter / 2 + o10, n8));
};
var koe = (e54, t4) => {
  const n8 = (e60) => ({ ...e60, rootConnectionName: t4.getNetConnectedToId(e60.rootConnectionName ?? e60.connectionName) ?? e60.rootConnectionName ?? e60.connectionName });
  return { ...e54, portPoints: e54.portPoints.map(n8), portPointsInPairs: e54.portPointsInPairs?.map(([e60, t10]) => [n8(e60), n8(t10)]) };
};
var Doe = ({ nodeWithPortPoints: e54, connMap: t4, colorMap: n8, viaDiameter: o10, viaHoleDiameter: i8, minViaHoleEdgeToViaHoleEdgeClearance: r9, allowBlindAndBuriedVias: s7, priorityDiagnostics: a9, priorityDagSearch: c5 = false, captureSearchDebug: l5 = false, traceWidth: h5, obstacleMargin: d9, effort: u9, nodePfById: p9, obstacles: m9, boardGeometry: g10, layerCount: f10 }) => new Dz({ nodePortPoints: [koe(e54, t4)], colorMap: n8, connMap: t4, viaDiameter: o10, traceWidth: h5, obstacleMargin: d9, effort: u9, nodePfById: p9, obstacles: m9, layerCount: f10, useGrowShrinkHighDensityIntraNodeSolver: true, enableNegotiatedSearch: true, gridSearchSegmentWork: 500, gridSearchWorkScale: f10 > 2 ? 0.25 : 1, rejectOverlappingTerminals: f10 > 2, boardGeometry: g10, preserveTerminalPcbPortIds: false, growShrinkFallbackToInvalidGeometryOnFailure: false, captureSearchDebug: l5, priorityDagSearch: c5, priorityDiagnostics: a9, viaHoleDiameter: i8, minViaHoleEdgeToViaHoleEdgeClearance: r9, allowBlindAndBuriedVias: s7 });
var Loe = class extends ni {
  constructor(e54) {
    super(), this.params = e54, this.fixedHdRoutes = e54.fixedHdRoutes, this.connMap = e54.connMap, this.colorMap = e54.colorMap ?? {}, this.obstacles = e54.obstacles, this.boardGeometry = e54.boardGeometry, this.layerCount = e54.layerCount, this.allowBlindAndBuriedVias = e54.allowBlindAndBuriedVias ?? false, this.viaDiameter = e54.viaDiameter, this.traceWidth = e54.traceWidth, this.obstacleMargin = e54.obstacleMargin, this.viaToPadClearance = e54.viaToPadClearance, this.effort = e54.effort, this.nodePfById = e54.nodePfById instanceof Map ? new Map(e54.nodePfById) : new Map(Object.entries(e54.nodePfById ?? {})), this.preserveTerminalPcbPortIds = e54.preserveTerminalPcbPortIds ?? false, this.includeBoardObstacles = e54.includeBoardObstacles ?? false, this.enableRegionalFallback = e54.enableRegionalFallback ?? true, this.maxB01Rips = e54.maxB01Rips, this.unsolvedNodePortPoints = [...e54.nodePortPoints], this.MAX_ITERATIONS = 1e8 * this.effort, this.stats = { nodeCount: e54.nodePortPoints.length, solvedNodeCount: 0, fixedObstacleCount: e54.fixedHdRoutes.length, fixedObstacleUses: 0, boardObstacleUses: 0, fallbackNodeCount: 0, regularNodeCount: 0, b01NodeCount: 0, reroutedFixedRouteCount: 0, reroutedFixedRouteSectionCount: 0, promotedFallbackAttemptCount: 0, promotedFixedRouteCount: 0, regionalPreloadedViaCandidateRejectionCount: 0, regionalForceImproveCandidateRejectionCount: 0, regionalRepairCandidateRejectionCount: 0 };
  }
  fixedHdRoutes;
  connMap;
  colorMap;
  obstacles;
  boardGeometry;
  layerCount;
  allowBlindAndBuriedVias;
  viaDiameter;
  traceWidth;
  obstacleMargin;
  viaToPadClearance;
  effort;
  nodePfById;
  preserveTerminalPcbPortIds;
  includeBoardObstacles;
  enableRegionalFallback;
  maxB01Rips;
  routes = [];
  failedSolvers = [];
  unsolvedNodePortPoints;
  fixedRouteReplacements = new Map;
  removedFixedRouteConnectionNames = new Set;
  preloadedTraceMutationMasks = new Map;
  activeRegularSolver = null;
  activeB01Solver = null;
  activeFallbackSolver = null;
  activeFallbackFixedRouteSections = new Map;
  activeFallbackFixedObstacleRoutes = [];
  activeFallbackPromotedFixedRouteConnectionNames = new Set;
  activeFallbackReason = null;
  activeNode = null;
  asyncRunning = false;
  benchmarkDiagnosticCounters = {};
  getSolverName() {
    return "Pipeline9HighDensitySolver";
  }
  async solveAsync(e54, t4 = 1 / 0) {
    if (this.asyncRunning)
      throw new Error("High-density solveAsync is already running");
    if (this.solved || this.failed || this.iterations >= t4)
      return;
    const n8 = performance.now();
    try {
      if (e54 === undefined)
        return void (t4 === 1 / 0 ? this.solve() : this.solveUntilIteration(t4));
      if (this.fixedHdRoutes.length > 0)
        return void this.solveUntilIteration(t4);
      for (;this.activeNode && !this.solved && !this.failed && this.iterations < t4; )
        this.step();
      if (this.solved || this.failed || this.iterations >= t4)
        return;
      this.asyncRunning = true;
      const n10 = [...this.unsolvedNodePortPoints].reverse(), { connMap: o10, nodePortPoints: i8, ...r9 } = this.params, s7 = Array.from({ length: Math.min(16, n10.length) }, () => ({ work: 0, nodes: [] })), a9 = n10.map((e60, t10) => ({ node: e60, index: t10 })).sort((e60, t10) => t10.node.portPoints.length - e60.node.portPoints.length);
      for (const e60 of a9) {
        const t10 = s7.reduce((e61, t11) => t11.work < e61.work ? t11 : e61);
        t10.nodes.push(e60), t10.work += Math.max(1, e60.node.portPoints.length) ** 3;
      }
      const c5 = [];
      for (const t10 of s7) {
        const n11 = new Map(t10.nodes.map(({ node: e60 }) => [e60.capacityMeshNodeId, this.nodePfById.get(e60.capacityMeshNodeId) ?? null])), i9 = e54.executeAsync(Gne, { ...r9, nodePortPoints: t10.nodes.map(({ node: e60 }) => e60), nodePfById: n11, connectivityNetMap: o10.netMap, maxIterations: this.MAX_ITERATIONS }).then((e60) => {
          for (const t11 of e60)
            for (const [e61, n12] of Object.entries(t11.benchmarkDiagnosticCounters))
              this.benchmarkDiagnosticCounters[e61] = (this.benchmarkDiagnosticCounters[e61] ?? 0) + n12;
          return this.benchmarkDiagnosticCounters.priorityWorkerBatchesCompleted = (this.benchmarkDiagnosticCounters.priorityWorkerBatchesCompleted ?? 0) + 1, this.benchmarkDiagnosticCounters.priorityWorkerNodesCompleted = (this.benchmarkDiagnosticCounters.priorityWorkerNodesCompleted ?? 0) + e60.length, { type: "result", results: e60 };
        }, (e60) => ({ type: "error", error: e60 }));
        for (const [e60, { index: n12 }] of t10.nodes.entries())
          c5[n12] = i9.then((t11) => t11.type === "error" ? t11 : { type: "result", result: t11.results[e60] });
      }
      this.benchmarkDiagnosticCounters.priorityWorkerBatchesDispatched = (this.benchmarkDiagnosticCounters.priorityWorkerBatchesDispatched ?? 0) + s7.length, this.benchmarkDiagnosticCounters.priorityWorkerNodesDispatched = (this.benchmarkDiagnosticCounters.priorityWorkerNodesDispatched ?? 0) + n10.length;
      for (const e60 of c5) {
        const n11 = await e60;
        if (n11.type === "error")
          throw n11.error;
        const o11 = n11.result, i9 = o11.iterations - (o11.solved ? 1 : 0);
        if (this.iterations + i9 > Math.min(this.MAX_ITERATIONS, t4))
          return this.asyncRunning = false, void this.solveUntilIteration(t4);
        this.benchmarkDiagnosticCounters.priorityWorkerNodesAccepted = (this.benchmarkDiagnosticCounters.priorityWorkerNodesAccepted ?? 0) + 1, this.iterations += i9, this.routes.push(...o11.routes);
        for (const [e61, t10] of Object.entries(o11.stats))
          e61 !== "nodeCount" && e61 !== "fixedObstacleCount" && (this.stats[e61] += t10);
        if (this.unsolvedNodePortPoints.splice(-o11.consumedNodeCount, o11.consumedNodeCount), this.progress = this.computeProgress(), !o11.solved)
          return this.error = o11.error, void (this.failed = true);
      }
      this.asyncRunning = false, this.iterations < t4 && this.step();
    } catch (e60) {
      throw this.failed = true, this.error = `Pipeline9 high-density runtime error: ${e60}`, e60;
    } finally {
      this.asyncRunning = false, this.timeToSolve = performance.now() - n8;
    }
  }
  solveUntilIteration(e54) {
    for (;!this.solved && !this.failed && this.iterations < e54; )
      this.step();
  }
  getUpdatedFixedHdRoutes() {
    return this.fixedHdRoutes.flatMap((e54) => this.removedFixedRouteConnectionNames.has(e54.connectionName) ? [] : [this.fixedRouteReplacements.get(e54.connectionName) ?? e54]);
  }
  finishActiveNode(e54) {
    const t4 = this.activeNode ? ((e60, t10) => e60.map((e61) => ({ ...e61, rootConnectionName: t10.portPoints.find((t11) => t11.connectionName === e61.connectionName)?.rootConnectionName ?? e61.rootConnectionName })))(e54, this.activeNode) : e54;
    this.routes.push(...this.preserveTerminalPcbPortIds && this.activeNode ? ((e60, t10) => {
      const n8 = t10.portPoints.filter((e61) => e61.pcb_port_id !== undefined);
      return e60.map((e61) => {
        const t11 = e61.route[0], o10 = e61.route.at(-1), i8 = n8.find((n10) => t11 !== undefined && n10.connectionName === e61.connectionName && n10.x === t11.x && n10.y === t11.y && n10.z === t11.z), r9 = n8.find((t12) => o10 !== undefined && t12.connectionName === e61.connectionName && t12.x === o10.x && t12.y === o10.y && t12.z === o10.z);
        return { ...e61, startPcbPortId: i8?.pcb_port_id, endPcbPortId: r9?.pcb_port_id };
      });
    })(t4, this.activeNode) : t4), this.stats.solvedNodeCount = Number(this.stats.solvedNodeCount ?? 0) + 1, this.activeB01Solver = null, this.activeRegularSolver = null, this.activeFallbackSolver = null, this.activeFallbackFixedRouteSections.clear(), this.activeFallbackFixedObstacleRoutes = [], this.activeFallbackPromotedFixedRouteConnectionNames.clear(), this.activeFallbackReason = null, this.activeNode = null;
  }
  startRegularSolver(e54) {
    this.activeNode = e54, this.activeRegularSolver = Doe({ nodeWithPortPoints: e54, colorMap: this.colorMap, connMap: this.connMap, viaDiameter: this.viaDiameter, traceWidth: this.traceWidth, obstacleMargin: this.obstacleMargin, effort: this.effort, nodePfById: this.nodePfById, obstacles: this.obstacles, boardGeometry: this.boardGeometry, layerCount: this.layerCount, viaHoleDiameter: this.params.viaHoleDiameter, minViaHoleEdgeToViaHoleEdgeClearance: this.params.minViaHoleEdgeToViaHoleEdgeClearance, allowBlindAndBuriedVias: this.params.allowBlindAndBuriedVias, priorityDiagnostics: this.benchmarkDiagnosticCounters, priorityDagSearch: true, captureSearchDebug: this.params.captureSearchDebug }), this.stats.regularNodeCount = Number(this.stats.regularNodeCount ?? 0) + 1;
  }
  startRegionalFallback(e54 = new Set) {
    if (!this.activeNode)
      throw new Error("Pipeline9 cannot start a regional fallback without an active node");
    const t4 = { ...koe(this.activeNode, this.connMap), availableZ: Array.from({ length: this.layerCount }, (e60, t10) => t10) }, n8 = Rne(t4, this.getUpdatedFixedHdRoutes(), e54), o10 = new Set([...n8.fixedRouteSectionsByConnectionName.values()].flatMap((e60) => e60.sourceRoutes.map((e61) => e61.connectionName)));
    for (const t10 of e54)
      if (!o10.has(t10))
        throw new Error(`Pipeline9 could not promote fixed route "${t10}" into the active regional fallback`);
    const i8 = [...e54].filter((e60) => !this.activeFallbackPromotedFixedRouteConnectionNames.has(e60)).length;
    this.activeFallbackFixedRouteSections = n8.fixedRouteSectionsByConnectionName, this.activeFallbackFixedObstacleRoutes = n8.fixedObstacleRoutes, this.activeFallbackPromotedFixedRouteConnectionNames = new Set(e54);
    const r9 = rs({ fixedObstacleRoutes: this.activeFallbackFixedObstacleRoutes, layerCount: this.layerCount, allowBlindAndBuriedVias: this.allowBlindAndBuriedVias });
    this.activeFallbackSolver = new Eoe({ captureSearchDebug: this.params.captureSearchDebug, nodeWithPortPoints: n8.nodeWithPortPoints, colorMap: this.colorMap, connMap: this.connMap, viaDiameter: this.viaDiameter, traceWidth: this.traceWidth, obstacleMargin: this.obstacleMargin, effort: this.effort, nodePfById: this.nodePfById, obstacles: [...this.obstacles, ...r9], boardObstacles: this.obstacles, movablePreloadedConnectionNames: o10, viaToPadClearance: this.viaToPadClearance, layerCount: this.layerCount, allowBlindAndBuriedVias: this.allowBlindAndBuriedVias }), e54.size === 0 ? this.stats.fallbackNodeCount = Number(this.stats.fallbackNodeCount ?? 0) + 1 : (this.stats.promotedFallbackAttemptCount = Number(this.stats.promotedFallbackAttemptCount ?? 0) + 1, this.stats.promotedFixedRouteCount = Number(this.stats.promotedFixedRouteCount ?? 0) + i8);
  }
  finishRegionalFallback() {
    if (!this.activeFallbackSolver)
      return;
    if (!this.activeNode)
      throw new Error("Pipeline9 cannot finish a regional fallback without an active node");
    this.recordRegionalCandidateRejections();
    const e54 = [], t4 = new Map;
    for (const n10 of this.activeFallbackSolver.getOutput()) {
      if (!this.activeFallbackFixedRouteSections.has(n10.connectionName)) {
        e54.push(n10);
        continue;
      }
      const o11 = t4.get(n10.connectionName) ?? [];
      o11.push(n10), t4.set(n10.connectionName, o11);
    }
    const n8 = [], o10 = [];
    for (const [e60, i9] of this.activeFallbackFixedRouteSections) {
      const r10 = t4.get(e60) ?? [];
      if (r10.length === 0) {
        o10.push(i9);
        continue;
      }
      if (r10.length > 1)
        return this.error = `Pipeline9 regional fallback expected one replacement for fixed route "${e60}", got ${r10.length}`, void (this.failed = true);
      const s9 = Ane({ section: i9, replacement: r10[0], sourceMutationMasks: this.preloadedTraceMutationMasks, replacementIsMutated: true });
      n8.push({ connectionName: e60, section: i9, replacement: s9.route, mutatedSegments: s9.mutatedSegments, replacementProducedSegment: s9.replacementProducedSegment });
    }
    const i8 = [...e54, ...n8.map(({ replacement: e60 }) => e60)], r9 = [...this.activeFallbackFixedObstacleRoutes, ...o10.flatMap((e60) => e60.sourceRoutes)], s7 = Aoe(this.activeNode, this.obstacleMargin + Math.max(this.traceWidth, this.viaDiameter) / 2), a9 = new Map;
    for (const e60 of i8)
      for (const t10 of r9)
        ss(e60, t10, this.connMap) || cs({ left: e60, right: t10, clearance: this.obstacleMargin, leftBounds: s7, layerCount: this.layerCount, allowBlindAndBuriedVias: this.allowBlindAndBuriedVias }) && a9.set(t10.connectionName, t10);
    if (a9.size > 0) {
      const e60 = [...a9.keys()], t10 = [...a9].flatMap(([e61, t11]) => t11.isThroughObstacle === true ? [] : [e61]), n10 = new Set(this.activeFallbackPromotedFixedRouteConnectionNames);
      for (const e61 of t10)
        n10.add(e61);
      if (n10.size === this.activeFallbackPromotedFixedRouteConnectionNames.size) {
        const t11 = [...a9].flatMap(([e61, t12]) => t12.isThroughObstacle === true ? [e61] : []);
        return this.error = t11.length > 0 ? `Pipeline9 regional fallback conflicts with immutable through-obstacle route(s): ${t11.join(", ")}` : `Pipeline9 promoted regional fallback could not resolve immutable fixed route conflict(s): ${e60.join(", ")}`, void (this.failed = true);
      }
      return void this.startRegionalFallback(n10);
    }
    const c5 = new Map;
    for (const { section: e60, replacementProducedSegment: t10 } of n8)
      if (t10)
        for (const t11 of e60.sourceRoutes) {
          const { preloadedRoutePositionStart: e61, preloadedRoutePositionEnd: n10 } = t11;
          if (e61 === undefined != (n10 === undefined))
            throw new Error(`Pipeline9 fixed route "${t11.connectionName}" has incomplete route-position metadata`);
          const o11 = Math.min(e61 ?? t11.preloadedRouteIndex, n10 ?? t11.preloadedRouteIndex), i9 = Math.max(e61 ?? t11.preloadedRouteIndex, n10 ?? t11.preloadedRouteIndex), r10 = c5.get(t11.preloadedTraceIndex);
          c5.set(t11.preloadedTraceIndex, { start: Math.min(r10?.start ?? o11, o11), end: Math.max(r10?.end ?? i9, i9) });
        }
    for (const { connectionName: e60, section: t10, replacement: o11, mutatedSegments: i9 } of n8) {
      this.fixedRouteReplacements.set(e60, o11), this.preloadedTraceMutationMasks.set(e60, i9);
      for (const e61 of t10.sourceRoutes.slice(1))
        this.removedFixedRouteConnectionNames.add(e61.connectionName), this.preloadedTraceMutationMasks.delete(e61.connectionName);
    }
    const l5 = Rne({ ...koe(this.activeNode, this.connMap), portPoints: [], portPointsInPairs: [], availableZ: Array.from({ length: this.layerCount }, (e60, t10) => t10) }, this.getUpdatedFixedHdRoutes()), h5 = new Set;
    for (const e60 of l5.fixedRouteSectionsByConnectionName.values()) {
      const t10 = e60.sourceRoutes[0];
      if (!t10)
        continue;
      const n10 = c5.get(t10.preloadedTraceIndex);
      if (n10)
        for (const [o11, i9] of e60.sourceRoutes.entries()) {
          const r10 = i9.preloadedRoutePositionStart ?? i9.preloadedRouteIndex, s9 = i9.preloadedRoutePositionEnd ?? i9.preloadedRouteIndex, a10 = { start: Math.min(r10, s9), end: Math.max(r10, s9) }, c9 = a10.start === a10.end, l10 = n10.start === n10.end;
          if (!(c9 || l10 ? a10.start <= n10.end && n10.start <= a10.end : a10.start < n10.end && n10.start < a10.end))
            continue;
          h5.add(t10.preloadedTraceIndex);
          const d10 = [...this.preloadedTraceMutationMasks.get(i9.connectionName) ?? Array(i9.route.length - 1).fill(false)];
          if (d10.length !== i9.route.length - 1)
            throw new Error(`Pipeline9 fixed route mutation mask for "${i9.connectionName}" has ${d10.length} segments, expected ${i9.route.length - 1}`);
          const u9 = o11 === 0 ? e60.start.segmentIndex : 0, p9 = o11 === e60.sourceRoutes.length - 1 ? e60.end.segmentIndex : i9.route.length - 2;
          for (let e61 = u9;e61 <= p9; e61++)
            d10[e61] = true;
          this.preloadedTraceMutationMasks.set(i9.connectionName, d10);
        }
    }
    for (const e60 of c5.keys())
      if (!h5.has(e60))
        throw new Error(`Pipeline9 could not capture accepted mutation provenance for trace ${e60}`);
    const d9 = n8.reduce((e60, { section: t10 }) => e60 + t10.sourceRoutes.length, 0);
    this.stats.reroutedFixedRouteCount = Number(this.stats.reroutedFixedRouteCount ?? 0) + d9, this.stats.reroutedFixedRouteSectionCount = Number(this.stats.reroutedFixedRouteSectionCount ?? 0) + n8.length, this.finishActiveNode(e54);
  }
  recordRegionalCandidateRejections() {
    if (!this.activeFallbackSolver)
      return;
    const e54 = this.activeFallbackSolver.stats;
    this.stats.regionalPreloadedViaCandidateRejectionCount = Number(this.stats.regionalPreloadedViaCandidateRejectionCount ?? 0) + Number(e54.preloadedViaCandidateRejectionCount ?? 0), this.stats.regionalForceImproveCandidateRejectionCount = Number(this.stats.regionalForceImproveCandidateRejectionCount ?? 0) + Number(e54.forceImproveCandidateRejectionCount ?? 0), this.stats.regionalRepairCandidateRejectionCount = Number(this.stats.regionalRepairCandidateRejectionCount ?? 0) + Number(e54.repairCandidateRejectionCount ?? 0);
  }
  finishRegularSolverFailure(e54) {
    if (this.activeFallbackReason = `regular high-density routing failed: ${e54}`, this.activeRegularSolver = null, !this.enableRegionalFallback)
      return this.error = `Pipeline9 ${this.activeFallbackReason}`, this.failed = true, void (this.activeNode = null);
    this.startRegionalFallback();
  }
  _step() {
    this.stepNodeRouting(), this.activeSubSolver = this.activeFallbackSolver ?? this.activeRegularSolver ?? this.activeB01Solver;
  }
  computeProgress() {
    if (this.solved)
      return 1;
    const e54 = Number(this.stats.nodeCount);
    if (e54 === 0)
      return 0;
    const t4 = Math.max(0, Math.min(1, this.activeSubSolver?.progress ?? 0));
    return Math.max(this.progress, (Number(this.stats.solvedNodeCount) + t4) / e54);
  }
  stepNodeRouting() {
    if (this.activeFallbackSolver) {
      if (this.activeFallbackSolver.step(), this.activeFallbackSolver.failed)
        return this.recordRegionalCandidateRejections(), this.error = [`Pipeline9 primary high-density routing failed: ${this.activeFallbackReason ?? "unknown error"}`, `regional fallback failed: ${this.activeFallbackSolver.error ?? "unknown error"}`].join("; "), this.failed = true, this.activeFallbackSolver = null, this.activeFallbackFixedRouteSections.clear(), this.activeFallbackFixedObstacleRoutes = [], this.activeFallbackPromotedFixedRouteConnectionNames.clear(), void (this.activeNode = null);
      if (!this.activeFallbackSolver.solved)
        return;
      return void this.finishRegionalFallback();
    }
    if (this.activeRegularSolver) {
      if (this.activeRegularSolver.step(), this.activeRegularSolver.failed)
        return void this.finishRegularSolverFailure(this.activeRegularSolver.error ?? "unknown error");
      if (!this.activeRegularSolver.solved)
        return;
      return void this.finishActiveNode(this.activeRegularSolver.routes);
    }
    if (this.activeB01Solver) {
      if (this.activeB01Solver.step(), this.activeB01Solver.failed)
        return this.failedSolvers.push(this.activeB01Solver), this.activeFallbackReason = `B01 failed: ${this.activeB01Solver.error ?? "unknown error"}`, this.activeB01Solver = null, this.enableRegionalFallback ? void this.startRegionalFallback() : (this.error = `Pipeline9 ${this.activeFallbackReason}`, this.failed = true, void (this.activeNode = null));
      if (!this.activeB01Solver.solved)
        return;
      return void this.finishActiveNode(this.activeB01Solver.getOutput());
    }
    const e54 = this.unsolvedNodePortPoints.pop();
    if (!e54)
      return void (this.solved = true);
    const t4 = Aoe(e54, this.obstacleMargin), n8 = Math.max(this.traceWidth, this.viaDiameter) / 2, o10 = this.getUpdatedFixedHdRoutes().filter((o11) => Ooe(o11, e54, t4, n8, this)).flatMap((t10) => ((e60, t11, n10) => {
      const o11 = new Set(t11.availableZ ?? t11.portPoints.map((e61) => e61.z));
      if (o11.size === 0)
        throw new Error(`Pipeline9 B01 node "${t11.capacityMeshNodeId}" has no available layers`);
      const i9 = { type: "route", connectionName: e60.connectionName, rootConnectionName: e60.rootConnectionName, traceThickness: e60.traceThickness, viaDiameter: e60.viaDiameter }, r10 = [], s7 = os(e60, n10);
      for (const e61 of s7.wireSegments)
        o11.has(e61.z) && r10.push({ ...i9, traceThickness: e61.width, route: [e61.start, e61.end], vias: [] });
      for (const e61 of s7.viaSpans)
        [...o11].some((t12) => t12 >= e61.minZ && t12 <= e61.maxZ) && r10.push({ ...i9, viaDiameter: e61.diameter, route: [{ ...e61.center, z: e61.minZ }, { ...e61.center, z: e61.maxZ }], vias: [{ ...e61.center, zStart: e61.minZ, zEnd: e61.maxZ }] });
      return r10;
    })(t10, e54, this));
    if (this.stats.fixedObstacleUses = Number(this.stats.fixedObstacleUses ?? 0) + o10.length, o10.length === 0 && !this.params.b01RepairOptions)
      return void this.startRegularSolver(e54);
    const i8 = (this.includeBoardObstacles ? this.obstacles : []).filter((e60) => ((e61, t10) => {
      const n10 = (e61.ccwRotationDegrees ?? 0) * Math.PI / 180, o11 = Math.abs(Math.cos(n10)), i9 = Math.abs(Math.sin(n10)), r10 = e61.width / 2 * o11 + e61.height / 2 * i9, s7 = e61.width / 2 * i9 + e61.height / 2 * o11;
      return e61.center.x - r10 <= t10.maxX && e61.center.x + r10 >= t10.minX && e61.center.y - s7 <= t10.maxY && e61.center.y + s7 >= t10.minY;
    })(e60, t4)).map((t10) => (({ obstacle: e60, node: t11, connMap: n10, layerCount: o11 }) => {
      const i9 = new Set(t11.availableZ ?? t11.portPoints.map((e61) => e61.z)), r10 = (e60.zLayers ?? e60.layers.map((e61) => mo(e61, o11))).filter((e61) => i9.has(e61));
      if (r10.length === 0)
        return;
      const s7 = e60.connectedTo[0] ?? e60.obstacleId ?? `pipeline9_obstacle_${e60.center.x}_${e60.center.y}`;
      return { type: "rect", connectionName: s7, rootConnectionName: n10.getNetConnectedToId(s7) ?? s7, center: e60.center, width: e60.width, height: e60.height, ccwRotationDegrees: e60.ccwRotationDegrees, zLayers: r10 };
    })({ obstacle: t10, node: e54, connMap: this.connMap, layerCount: this.layerCount })).filter((e60) => e60 !== undefined);
    if (this.stats.boardObstacleUses = Number(this.stats.boardObstacleUses ?? 0) + i8.length, this.activeNode = e54, e54.width > 15 || e54.height > 15)
      return this.activeFallbackReason = `B01 node "${e54.capacityMeshNodeId}" exceeds the 15x15mm routing limit (${e54.width}x${e54.height}mm)`, void this.startRegionalFallback();
    const r9 = koe(e54, this.connMap);
    this.stats.b01NodeCount = Number(this.stats.b01NodeCount ?? 0) + 1, this.activeB01Solver = new Roe({ ...qne, nodeWithPortPoints: r9, obstacles: [...o10, ...i8], viaDiameter: this.viaDiameter, viaMinDistFromBorder: this.viaDiameter / 2, traceThickness: this.traceWidth, traceMargin: this.obstacleMargin, obstacleClearanceMargin: 0.15, ...this.params.b01RepairOptions, effort: this.effort }), this.maxB01Rips !== undefined && (this.activeB01Solver.MAX_RIPS = this.maxB01Rips);
  }
  visualize() {
    return this.activeFallbackSolver?.visualize() ?? this.activeRegularSolver?.visualize() ?? this.activeB01Solver?.visualize() ?? { lines: this.routes.flatMap((e54) => e54.route.slice(0, -1).map((t4, n8) => ({ points: [t4, e54.route[n8 + 1]], strokeWidth: e54.traceThickness, layer: `z${t4.z}`, label: e54.connectionName }))), points: [], rects: [], circles: [] };
  }
};
var zoe = (e54, t4) => {
  const n8 = e54({ hdRoutes: t4, traces: [] });
  return Array.isArray(n8) ? n8 : n8.errorsWithCenters ?? n8.errors;
};
var Boe = (e54) => {
  const t4 = typeof e54.pcb_trace_id == "string" ? e54.pcb_trace_id : undefined, n8 = Array.isArray(e54.pcb_trace_ids) ? e54.pcb_trace_ids.filter((e60) => typeof e60 == "string") : [], o10 = [...typeof e54.pcb_via_id == "string" ? [e54.pcb_via_id] : [], ...Array.isArray(e54.pcb_via_ids) ? e54.pcb_via_ids : []].filter((e60) => typeof e60 == "string"), i8 = t4 ? `overlap_${t4}_` : undefined, r9 = i8 && typeof e54.pcb_trace_error_id == "string" && e54.pcb_trace_error_id.startsWith(i8) ? e54.pcb_trace_error_id.slice(i8.length) : undefined;
  if (n8.length > 0) {
    const e60 = t4 && !n8.includes(t4) ? [t4, ...n8] : [...n8];
    return e60.length < 2 && r9 && !o10.includes(r9) && e60.push(r9), e60;
  }
  return [t4, r9].filter((e60) => typeof e60 == "string" && !o10.includes(e60));
};
var Foe = (e54) => Boe(e54).filter((e60, t4, n8) => n8.indexOf(e60) === t4);
var joe = (e54) => e54.reduce((e60, t4) => {
  if (typeof t4.actual_clearance == "number" && typeof t4.minimum_clearance == "number")
    return e60 + Math.max(0, t4.minimum_clearance - t4.actual_clearance);
  const n8 = (typeof t4.message == "string" ? t4.message : "").match(/gap: (-?\d+(?:\.\d+)?)mm/);
  return n8 ? e60 + Math.max(0, 0.1 - Number.parseFloat(n8[1])) : e60 + 1;
}, 0);
var $oe = (e54, t4) => e54.length < t4.length || e54.length === t4.length && joe(e54) < joe(t4) - 0.000000001;
var Yoe = ({ routes: e54, newConnections: t4, syntheticConnectionNames: n8 }) => {
  const o10 = new Set([...t4.map((e60) => e60.name), ...n8]), i8 = new Map, r9 = new Map;
  for (let t10 = 0;t10 < e54.length; t10++) {
    const n10 = e54[t10];
    if (!o10.has(n10.connectionName))
      continue;
    const s7 = i8.get(n10.connectionName) ?? 0;
    i8.set(n10.connectionName, s7 + 1), r9.set(`${n10.connectionName}_${s7}`, t10);
  }
  return r9;
};
var Xoe = 0.01;
var Hoe = [0.03, 0.1, 0.25];
var Voe = (e54) => {
  let t4 = 0;
  for (const n8 of e54) {
    if (typeof n8.actual_clearance != "number" || !Number.isFinite(n8.actual_clearance) || typeof n8.minimum_clearance != "number" || !Number.isFinite(n8.minimum_clearance))
      return;
    if (t4 += Math.max(0, n8.minimum_clearance - n8.actual_clearance), !Number.isFinite(t4))
      return;
  }
  return t4;
};
var Woe = ({ errors: e54, errorsWithCenters: t4, routeIndexByTraceId: n8, padPositionById: o10 }) => {
  const i8 = [];
  let r9 = 0;
  for (const s7 of e54) {
    const e60 = s7.type === "pcb_via_trace_clearance_error", a9 = s7.type === "pcb_pad_trace_clearance_error";
    if (!e60 && !a9 || typeof s7.pcb_trace_id != "string" || !n8.has(s7.pcb_trace_id) || typeof s7.actual_clearance != "number" || !Number.isFinite(s7.actual_clearance) || typeof s7.minimum_clearance != "number" || !Number.isFinite(s7.minimum_clearance))
      return;
    const c5 = Foe(s7);
    if (e60 && c5.length < 2 || c5.some((e61) => !n8.has(e61)))
      return;
    const l5 = t4.find((e61) => e61.type === s7.type && e61.pcb_trace_id === s7.pcb_trace_id && e61.pcb_pad_id === s7.pcb_pad_id && e61.pcb_via_id === s7.pcb_via_id), h5 = a9 ? typeof s7.pcb_pad_id == "string" ? o10.get(s7.pcb_pad_id) : undefined : l5?.center ?? s7.center;
    if (!h5 || typeof h5 != "object")
      return;
    if (!(("x" in h5) && ("y" in h5) && typeof h5.x == "number" && Number.isFinite(h5.x) && typeof h5.y == "number" && Number.isFinite(h5.y)))
      return;
    const d9 = { ...s7, pcb_trace_id: s7.pcb_trace_id, actual_clearance: s7.actual_clearance, minimum_clearance: s7.minimum_clearance, center: { x: h5.x, y: h5.y } };
    if (e60) {
      if (typeof s7.pcb_via_id != "string")
        return;
      i8.push({ ...d9, type: "pcb_via_trace_clearance_error", pcb_via_id: s7.pcb_via_id, pcb_pad_id: undefined });
    } else {
      if (typeof s7.pcb_pad_id != "string")
        return;
      i8.push({ ...d9, type: "pcb_pad_trace_clearance_error", pcb_pad_id: s7.pcb_pad_id, pcb_via_id: undefined });
    }
    if (r9 += Math.max(0, s7.minimum_clearance - s7.actual_clearance), !Number.isFinite(r9))
      return;
  }
  return { errors: i8, deficit: r9 };
};
var Goe = (e54) => {
  if (e54.type !== "pcb_pad_pad_clearance_error" || typeof e54.pcb_trace_id != "string")
    return false;
  const { pcb_via_ids: t4, pcb_pad_ids: n8 } = e54;
  return !(!Array.isArray(t4) || t4.length !== 1 || typeof t4[0] != "string") && (Array.isArray(n8) && n8.length === 2 && typeof n8[0] == "string" && typeof n8[1] == "string" && n8.includes(t4[0]));
};
var Uoe = (e54) => ((e60) => {
  const t4 = typeof e60.pcb_trace_id == "string" ? e60.pcb_trace_id : undefined, n8 = Array.isArray(e60.pcb_trace_ids) ? e60.pcb_trace_ids.filter((e61) => typeof e61 == "string") : [], o10 = [...typeof e60.pcb_via_id == "string" ? [e60.pcb_via_id] : [], ...Array.isArray(e60.pcb_via_ids) ? e60.pcb_via_ids : []].filter((e61) => typeof e61 == "string"), i8 = t4 ? `overlap_${t4}_` : undefined, r9 = i8 && typeof e60.pcb_trace_error_id == "string" && e60.pcb_trace_error_id.startsWith(i8) ? e60.pcb_trace_error_id.slice(i8.length) : undefined;
  if (n8.length > 0) {
    const e61 = t4 && !n8.includes(t4) ? [t4, ...n8] : [...n8];
    return e61.length < 2 && r9 && !o10.includes(r9) && e61.push(r9), e61;
  }
  return [t4, r9].filter((e61) => typeof e61 == "string" && !o10.includes(e61));
})(e54).filter((e60, t4, n8) => n8.indexOf(e60) === t4);
var Zoe = (e54, t4) => {
  const n8 = [...new Set(t4.flatMap(Uoe))];
  return e54.map((e60) => {
    if (e60.jumpers?.length || !n8.some((t11) => t11 === e60.connectionName || t11.startsWith(`${e60.connectionName}_`)))
      return e60;
    const t10 = e60.route.flatMap((t11, n10) => {
      const o10 = e60.route[n10 + 1];
      if (!o10 || t11.z !== o10.z || t11.toNextSegmentType || t11.insideJumperPad || o10.insideJumperPad || (t11.traceThickness ?? e60.traceThickness) !== (o10.traceThickness ?? e60.traceThickness))
        return [t11];
      const i8 = Math.min(32, Math.ceil(((e61, t12) => {
        const n11 = Math.max(Math.abs(e61), Math.abs(t12));
        if (n11 === 0 || n11 === Number.POSITIVE_INFINITY)
          return n11;
        const o11 = e61 / n11, i9 = t12 / n11;
        return n11 * Math.sqrt(o11 * o11 + i9 * i9);
      })(o10.x - t11.x, o10.y - t11.y) / 0.25));
      return [t11, ...Array.from({ length: Math.max(0, i8 - 1) }, (e61, n11) => ({ x: t11.x + (o10.x - t11.x) * (n11 + 1) / i8, y: t11.y + (o10.y - t11.y) * (n11 + 1) / i8, z: t11.z, traceThickness: t11.traceThickness }))];
    });
    return t10.length === e60.route.length ? e60 : { ...e60, route: t10 };
  });
};
var qoe = class extends ni {
  params;
  state = { phase: "initialize" };
  constructor(e54) {
    super(), this.params = e54;
  }
  _step() {
    const e54 = this.state, t4 = this.params;
    if (e54.phase === "initialize") {
      const e60 = t4.drcEvaluator({ traces: [], routes: t4.routes, hdRoutes: t4.routes }), n10 = Array.isArray(e60) ? e60 : e60.errors;
      if (n10.length === 0)
        return this.state = { phase: "finished", output: t4.routes }, void (this.solved = true);
      const o11 = { ...V1(t4.originalSrj), traces: undefined }, i9 = bne(t4.routes), r10 = t4.subdivideSegments ? Zoe(i9, n10) : i9, s9 = new Zy({ srj: o11, routes: r10, bounds: o11.bounds, boundaryMargin: 0, boardEdgeClearance: t4.originalSrj.minBoardEdgeClearance ?? 0, lockedPointIndices: r10.map((e61) => e61.route.map((n11) => n11.terminalApproach !== undefined || t4.lockedConnectionNames?.has(e61.connectionName) === true || t4.movableRegions !== undefined && !t4.movableRegions.some(({ center: e63, radius: t10 }) => Math.hypot(n11.x - e63.x, n11.y - e63.y) <= t10))), allowViaMovement: !t4.allowPartialRepair, traceClearance: (t4.originalSrj.minTraceToPadEdgeClearance ?? hR) + (t4.allowPartialRepair || t4.usePrecisionMargin ? Xoe : 0), viaClearance: (t4.originalSrj.minPadEdgeToPadEdgeClearance ?? dR) + 0.00001 + (t4.usePrecisionMargin ? Xoe : 0) });
      return this.MAX_ITERATIONS = s9.MAX_ITERATIONS + 4, this.activeSubSolver = s9, void (this.state = { phase: "relax", context: { srj: o11, errors: n10, originalCanonicalRoutes: i9, canonicalRoutes: r10 }, solver: s9 });
    }
    if (e54.phase === "relax") {
      if (e54.solver.step(), this.MAX_ITERATIONS = e54.solver.MAX_ITERATIONS + 4, e54.solver.failed)
        throw new Error(`Clearance relaxation failed: ${e54.solver.error}`);
      return void (e54.solver.solved && (this.activeSubSolver = null, this.state = { phase: "select", context: e54.context, candidate: e54.solver.getOutput() }));
    }
    if (e54.phase === "finished")
      throw new Error("Clearance projection stepped after completion");
    const { srj: n8, errors: o10, originalCanonicalRoutes: i8, canonicalRoutes: r9 } = e54.context;
    if (e54.phase === "select") {
      let o11 = e54.candidate;
      return t4.allowPartialRepair && (o11 = (({ srj: e60, routes: t10, proposedRoutes: n10 }) => {
        if (t10.length !== n10.length)
          throw new Error("Clearance projection changed the route count");
        if (e60.allowBlindAndBuriedVias || t10.some((e61) => e61.jumpers?.length || e61.route.some((e63) => e63.toNextSegmentType || e63.insideJumperPad)))
          return t10;
        const { holeDiameter: o12 } = Yo(e60), i9 = (t11, n11) => ({ type: "pcb_trace", pcb_trace_id: `projection_${n11}`, connection_name: t11.rootConnectionName ?? t11.connectionName, route: Ro(t11, e60.layerCount, { defaultViaHoleDiameter: o12 }) }), r10 = t10.map(i9), s9 = { ...e60, minBoardEdgeClearance: e60.minBoardEdgeClearance ?? 0, traces: r10 }, a10 = new D7(s9), c9 = new Set(a10.canonicalize([...(e60.differentialPairs ?? []).flatMap((e61) => e61.connectionNames), ...(e60.buses ?? []).flatMap((e61) => e61.connectionNames)])), l5 = [...t10], h5 = [];
        for (const [e61, o13] of n10.entries()) {
          const n11 = t10[e61];
          if (o13.route.length !== n11.route.length)
            throw new Error("Partial clearance projection changed routing topology");
          const i10 = [r10[e61].pcb_trace_id];
          if (!a10.canonicalize(i10).some((e63) => c9.has(e63))) {
            l5[e61] = { ...n11, route: [...o13.route] };
            for (let t11 = 0;t11 < o13.route.length; t11++)
              o13.route[t11].x === n11.route[t11].x && o13.route[t11].y === n11.route[t11].y || h5.push({ routeIndex: e61, pointIndex: t11 });
          }
        }
        let d9 = new Cee(s9, l5.map(i9), undefined, [], a10);
        const u9 = ({ routeIndex: t11, pointIndex: n11 }) => {
          const o13 = l5[t11];
          for (let i10 = Math.max(1, n11);i10 <= Math.min(n11 + 1, o13.route.length - 1); i10++) {
            const n12 = o13.route[i10 - 1], s10 = o13.route[i10];
            if (n12.z !== s10.z)
              throw new Error("Partial clearance projection moved a layer transition");
            if (d9.collides({ start: n12, end: s10, layer: Co(n12.z, e60.layerCount), width: Math.max(n12.traceThickness ?? o13.traceThickness, s10.traceThickness ?? o13.traceThickness), connectionNames: [r10[t11].pcb_trace_id] }))
              return false;
          }
          return true;
        };
        let p9 = h5;
        for (;p9.length > 0; ) {
          const e61 = p9.filter((e63) => !u9(e63));
          if (e61.length === 0)
            break;
          for (const { routeIndex: n12, pointIndex: o13 } of e61)
            l5[n12].route[o13] = t10[n12].route[o13];
          const n11 = new Set(e61);
          p9 = p9.filter((e63) => !n11.has(e63)), d9 = new Cee(s9, l5.map(i9), undefined, [], a10);
        }
        const m9 = new Set(p9);
        for (let e61 = 0;e61 < h5.length; e61++) {
          const o13 = h5[e61];
          if (m9.has(o13))
            continue;
          let r11 = [o13];
          for (;e61 + 1 < h5.length; ) {
            const t11 = h5[e61 + 1];
            if (m9.has(t11) || t11.routeIndex !== o13.routeIndex || t11.pointIndex !== h5[e61].pointIndex + 1)
              break;
            r11.push(t11), e61++;
          }
          for (const { routeIndex: e63, pointIndex: t11 } of r11)
            l5[e63].route[t11] = n10[e63].route[t11];
          for (;r11.length > 0; ) {
            const e63 = r11.filter((e64) => !u9(e64));
            if (e63.length === 0)
              break;
            for (const { routeIndex: n12, pointIndex: o14 } of e63)
              l5[n12].route[o14] = t10[n12].route[o14];
            const n11 = new Set(e63);
            r11 = r11.filter((e64) => !n11.has(e64));
          }
          if (r11.length !== 0) {
            for (const e63 of r11)
              m9.add(e63);
            d9 = new Cee(s9, l5.map(i9), undefined, [], a10);
          }
        }
        const g10 = new Set([...m9].map(({ routeIndex: e61 }) => e61));
        return l5.map((e61, n11) => g10.has(n11) ? e61 : t10[n11]);
      })({ srj: n8, routes: r9, proposedRoutes: o11 }), o11 = o11.map((e60, t10) => e60 === r9[t10] ? i8[t10] : e60)), void (this.state = { phase: "physical-validation", context: e54.context, candidate: o11 });
    }
    if (e54.phase === "physical-validation") {
      const o11 = new Map(ay({ srj: n8, routes: r9 }).map((e60) => [e60.key, e60.severity]));
      return ay({ srj: n8, routes: e54.candidate }).some(({ key: e60, severity: t10 }) => !o11.has(e60) || t10 > o11.get(e60) + 0.00000001) || ly({ srj: n8, previousRoutes: t4.previousRoutes ?? r9, routes: e54.candidate }).length > 0 ? (this.state = { phase: "finished", output: t4.routes }, void (this.solved = true)) : void (this.state = { ...e54, phase: "reference-validation" });
    }
    const s7 = t4.drcEvaluator({ traces: [], routes: e54.candidate, hdRoutes: e54.candidate }), a9 = Array.isArray(s7) ? s7 : s7.errors, c5 = t4.allowPartialRepair ? ((e60, t10) => {
      if (t10.length >= e60.length)
        return false;
      const n10 = (e61) => e61.type === "pcb_via_trace_clearance_error" ? JSON.stringify([e61.type, e61.pcb_trace_id, e61.pcb_via_id]) : e61.type === "pcb_pad_trace_clearance_error" ? JSON.stringify([e61.type, e61.pcb_trace_id, e61.pcb_pad_id]) : Goe(e61) ? JSON.stringify([e61.type, e61.pcb_trace_id, [...e61.pcb_pad_ids].sort()]) : e61.type === "pcb_via_clearance_error" && Array.isArray(e61.pcb_via_ids) ? JSON.stringify([e61.type, [...e61.pcb_via_ids].sort()]) : e61.type === "pcb_trace_error" && typeof e61.pcb_trace_error_id == "string" && e61.pcb_trace_error_id.startsWith(`overlap_${e61.pcb_trace_id}_`) ? JSON.stringify([e61.type, e61.pcb_trace_error_id]) : undefined, o11 = [...e60];
      for (const e61 of t10) {
        const t11 = n10(e61);
        if (t11 === undefined)
          return false;
        const i9 = o11.findIndex((e63) => n10(e63) === t11);
        if (i9 < 0)
          return false;
        const r10 = o11.splice(i9, 1)[0];
        if (e61.type !== "pcb_trace_error" && (typeof e61.actual_clearance != "number" || !Number.isFinite(e61.actual_clearance) || typeof r10.actual_clearance != "number" || !Number.isFinite(r10.actual_clearance) || e61.minimum_clearance !== r10.minimum_clearance || e61.actual_clearance < r10.actual_clearance - 0.000000001))
          return false;
      }
      return true;
    })(o10, a9) : a9.length < o10.length;
    this.state = { phase: "finished", output: c5 ? e54.candidate : t4.routes }, this.solved = true;
  }
  getOutput() {
    if (!this.solved || this.state.phase !== "finished")
      throw new Error("Clearance projection is not complete");
    return this.state.output;
  }
  computeProgress() {
    switch (this.state.phase) {
      case "initialize":
        return 0;
      case "relax":
        return 0.9 * this.state.solver.progress;
      case "select":
        return 0.9;
      case "physical-validation":
        return 0.93;
      case "reference-validation":
        return 0.96;
      case "finished":
        return 1;
    }
  }
};
var Joe = { maxRegions: 4, maxCandidateAttempts: 1024, maxPathSearchNodes: 480000 };
var Qoe = (e54, t4, n8) => {
  if (!Number.isFinite(n8) || n8 <= 0)
    throw new Error("Pipeline9 regional repair effort must be positive and finite");
  const o10 = Math.max(1, n8);
  return { maxRegions: Math.ceil(24 * o10), maxCandidateAttempts: Math.ceil(4096 * o10), maxPathSearchNodes: Math.ceil(40000000 * o10), initialMaxRegions: Math.ceil(4 * o10), initialMaxCandidateAttempts: Math.ceil(1024 * o10), initialMaxPathSearchNodes: Math.ceil(2000000 * o10), regionsPerAcceptedRepair: 2, candidateAttemptsPerAcceptedRepair: 512, pathSearchNodesPerAcceptedRepair: 2000000, maxCandidateAttemptsPerRegion: 512, maxPathSearchNodesPerCall: 1e6, pathGridSizeScale: 2, pathHeuristicWeight: 3, searchDirectionCount: 2, revisitChangedRegions: true, regionSizes: [16, 32] };
};
var Koe = (e54, t4) => ({ maxRegions: Math.min(e54.maxRegions, (e54.initialMaxRegions ?? e54.maxRegions) + t4 * (e54.regionsPerAcceptedRepair ?? 0)), maxCandidateAttempts: Math.min(e54.maxCandidateAttempts, (e54.initialMaxCandidateAttempts ?? e54.maxCandidateAttempts) + t4 * (e54.candidateAttemptsPerAcceptedRepair ?? 0)), maxPathSearchNodes: Math.min(e54.maxPathSearchNodes, (e54.initialMaxPathSearchNodes ?? e54.maxPathSearchNodes) + t4 * (e54.pathSearchNodesPerAcceptedRepair ?? 0)) });
function eie({ routes: e54, srj: t4 }) {
  const { holeDiameter: n8 } = Yo(t4);
  return e54.flatMap((e60, o10) => {
    if ("type" in e60) {
      const n10 = { ...e60, route: e60.route.filter((e61) => e61.route_type === "via") };
      return sR({ ...t4, obstacles: [], connections: [], traces: undefined }, [n10]).filter((e61) => e61.type === "pcb_via");
    }
    return cy(e60, t4.layerCount).map((e61, i8) => {
      let r9 = 0, s7 = t4.layerCount - 1;
      return t4.allowBlindAndBuriedVias === true && (r9 = e61.minZ, s7 = e61.maxZ), { type: "pcb_via", pcb_via_id: `repair_via_${o10}_${i8}`, x: e61.x, y: e61.y, hole_diameter: n8, outer_diameter: e61.diameter, layers: Array.from({ length: s7 - r9 + 1 }, (e63, n10) => Co(r9 + n10, t4.layerCount)) };
    });
  });
}
var tie = [3, 4, 5, 6, 8];
var nie = (e54) => {
  const t4 = e54.center;
  return t4 && typeof t4 == "object" && "x" in t4 && "y" in t4 && typeof t4.x == "number" && typeof t4.y == "number" ? { x: t4.x, y: t4.y } : undefined;
};
var oie = (e54, t4) => {
  const n8 = nie(e54);
  if (n8)
    return n8;
  const o10 = typeof e54.pcb_pad_id == "string" ? e54.pcb_pad_id : typeof e54.pcb_trace_error_id == "string" ? e54.pcb_trace_error_id.match(/(pcb_(?:smtpad|plated_hole|hole|keepout)_\d+)$/)?.[1] : undefined;
  if (o10) {
    const e60 = t4.obstacles.find((e61) => e61.obstacleId === o10 || e61.connectedTo[0] === o10);
    if (e60)
      return e60.center;
  }
  return nie(e54);
};
var iie = ({ error: e54, routeIndexByTraceId: t4 }) => {
  const n8 = typeof e54.pcb_trace_id == "string" ? e54.pcb_trace_id : undefined, o10 = [...typeof e54.pcb_via_id == "string" ? [e54.pcb_via_id] : [], ...Array.isArray(e54.pcb_via_ids) ? e54.pcb_via_ids.filter((e60) => typeof e60 == "string") : []], i8 = n8 ? `overlap_${n8}_` : undefined, r9 = i8 && typeof e54.pcb_trace_error_id == "string" && e54.pcb_trace_error_id.startsWith(i8) ? e54.pcb_trace_error_id.slice(i8.length) : undefined, s7 = r9 !== undefined && o10.includes(r9);
  return [n8, ...Array.isArray(e54.pcb_trace_ids) ? e54.pcb_trace_ids : [], s7 ? undefined : r9].filter((e60) => typeof e60 == "string" && t4.has(e60)).filter((e60, t10, n10) => n10.indexOf(e60) === t10);
};
var rie = (e54, t4) => !(e54.type !== "pcb_trace_error" || typeof e54.pcb_via_id == "string" || Array.isArray(e54.pcb_via_ids) && e54.pcb_via_ids.length > 0) && iie({ error: e54, routeIndexByTraceId: t4 }).length === 2;
var sie = (e54) => e54.filter((e60) => e60.type === "pcb_via_clearance_error" || Array.isArray(e60.pcb_via_ids)).length;
var aie = (e54, t4) => {
  const n8 = new Map;
  for (const t10 of e54)
    n8.set(t10.connectionName, (n8.get(t10.connectionName) ?? 0) + 1);
  return e54.map((e60, o10) => {
    const i8 = n8.get(e60.connectionName) > 1 ? `${e60.connectionName}_regional_${o10}` : e60.connectionName;
    return i8 !== e60.connectionName && t4.addConnections([[i8, e60.connectionName, e60.rootConnectionName ?? e60.connectionName]]), { ...e60, connectionName: i8, preloadedTraceId: `pipeline9_joint_candidate_${o10}`, preloadedTraceIndex: o10, preloadedRouteIndex: 0, isThroughObstacle: false };
  });
};
var cie = (e54, t4) => e54.minX <= t4.maxX && e54.maxX >= t4.minX && e54.minY <= t4.maxY && e54.maxY >= t4.minY;
var lie = (e54) => ({ minX: e54.center.x - e54.diameter / 2, maxX: e54.center.x + e54.diameter / 2, minY: e54.center.y - e54.diameter / 2, maxY: e54.center.y + e54.diameter / 2 });
var hie = (e54) => ({ minX: e54.center.x - e54.width / 2, maxX: e54.center.x + e54.width / 2, minY: e54.center.y - e54.height / 2, maxY: e54.center.y + e54.height / 2 });
var die = (e54, t4, n8) => {
  const o10 = os(e54, n8);
  return o10.wireSegments.some((e60) => cie(((e61) => ({ minX: Math.min(e61.start.x, e61.end.x) - e61.width / 2, maxX: Math.max(e61.start.x, e61.end.x) + e61.width / 2, minY: Math.min(e61.start.y, e61.end.y) - e61.width / 2, maxY: Math.max(e61.start.y, e61.end.y) + e61.width / 2 }))(e60), t4)) || o10.viaSpans.some((e60) => cie(lie(e60), t4));
};
var uie = ({ routes: e54, fixedRouteCopperSpatialIndex: t4, center: n8, regionSize: o10, srj: i8, connMap: r9, colorMap: s7, viaDiameter: a9, traceWidth: c5, obstacleMargin: l5, effort: h5 }) => {
  const d9 = aie(e54, r9), u9 = { capacityMeshNodeId: "pipeline9_joint_drc_regular_fallback", center: n8, width: o10, height: o10, availableZ: Array.from({ length: i8.layerCount }, (e60, t10) => t10), portPoints: [], portPointsInPairs: [] }, p9 = Rne(u9, d9);
  if (p9.fixedRouteSectionsByConnectionName.size === 0)
    return;
  if (!((e60) => {
    const t10 = Ine(e60);
    return e60.portPoints.every((e61) => ga({ point: e61, bounds: t10 }) === "on-boundary");
  })(p9.nodeWithPortPoints))
    return;
  const m9 = [...p9.fixedRouteSectionsByConnectionName.values()].flatMap((e60) => e60.sourceRoutes).reduce((e60, t10) => {
    const n10 = os(t10, i8);
    return Math.max(e60, t10.viaDiameter / 2, ...n10.wireSegments.map((e61) => e61.width / 2), ...n10.viaSpans.map((e61) => e61.diameter / 2));
  }, Math.max(c5 / 2, a9 / 2)), g10 = { minX: n8.x - o10 / 2 - l5 - m9, maxX: n8.x + o10 / 2 + l5 + m9, minY: n8.y - o10 / 2 - l5 - m9, maxY: n8.y + o10 / 2 + l5 + m9 }, f10 = t4.getRoutesOverlappingBounds(g10), _5 = rs({ fixedObstacleRoutes: f10, layerCount: i8.layerCount, allowBlindAndBuriedVias: i8.allowBlindAndBuriedVias });
  return { solver: new Eoe({ nodeWithPortPoints: p9.nodeWithPortPoints, colorMap: s7, connMap: r9, viaDiameter: a9, traceWidth: c5, obstacleMargin: l5, effort: h5, obstacles: [...i8.obstacles, ..._5], layerCount: i8.layerCount, allowBlindAndBuriedVias: i8.allowBlindAndBuriedVias }), routes: e54, regionalRoutes: d9, problem: p9, candidateBounds: g10, localFixedObstacleRoutes: f10, obstacleMargin: l5, connMap: r9, srj: i8 };
};
var pie = ({ solver: e54, routes: t4, regionalRoutes: n8, problem: o10, candidateBounds: i8, localFixedObstacleRoutes: r9, obstacleMargin: s7, connMap: a9, srj: c5 }) => {
  if (!e54.solved || e54.failed)
    return;
  const l5 = e54.getOutput(), h5 = new Map(l5.map((e60) => [e60.connectionName, e60])), d9 = new Map, u9 = new Set;
  for (const [e60, t10] of o10.fixedRouteSectionsByConnectionName) {
    const n10 = h5.get(e60);
    if (!n10)
      return;
    d9.set(t10.sourceRoutes[0].preloadedTraceIndex, Ene(t10, n10));
    for (const e61 of t10.sourceRoutes.slice(1))
      u9.add(e61.preloadedTraceIndex);
  }
  const p9 = n8.flatMap((e60, n10) => u9.has(n10) ? [] : [{ ...d9.get(n10) ?? e60, connectionName: t4[n10].connectionName }]);
  return (({ candidateRoutes: e60, fixedObstacleRoutes: t10, obstacleMargin: n10, connMap: o11, candidateBounds: i9, srj: r10 }) => {
    for (const s9 of e60)
      for (const e61 of t10)
        if (!ss(s9, e61, o11) && cs({ left: s9, right: e61, clearance: n10, leftBounds: i9, layerCount: r10.layerCount, allowBlindAndBuriedVias: r10.allowBlindAndBuriedVias }))
          return true;
    return false;
  })({ candidateRoutes: p9, fixedObstacleRoutes: r9, obstacleMargin: s7, connMap: a9, candidateBounds: i8, srj: c5 }) ? undefined : p9;
};
var mie = class extends ni {
  evaluateViaInPad;
  params;
  candidateSearchBudget;
  phase = "initialize";
  result;
  currentRoutes;
  currentErrors = [];
  bestRoutes;
  bestErrors = [];
  fixedRouteCopperSpatialIndex;
  routeIndexByTraceId = new Map;
  repairableErrors = [];
  passIndex = 0;
  errorIndex = 0;
  traceIndex = 0;
  regionIndex = 0;
  traceIds = [];
  repairCenter;
  stopB01SearchForError = false;
  acceptedOnPass = false;
  attemptedCandidateCount = 0;
  acceptedCandidateCount = 0;
  fallbackCandidateCount = 0;
  candidateSearchCount = 0;
  candidateSearchBudgetExhausted = false;
  safeTraceLayerRepairSkippedForBudget = false;
  preloadEligibleDrcIssueCount = 0;
  pairCandidate;
  b01Candidate;
  regularCandidate;
  safeTraceLayerSolver;
  viaPadProjectionSolver;
  cleanup;
  constructor(e54) {
    super(), this.params = e54, this.evaluateViaInPad = function({ srj: e60, previousRoutes: t4 }) {
      const n8 = oR(V1(e60)), o10 = new G, i8 = n8.filter((e61) => e61.type === "pcb_smtpad" || e61.type === "pcb_plated_hole");
      o10.load(i8.map(az));
      const r9 = new Set(eie({ routes: t4, srj: e60 }).map((e61) => JSON.stringify([e61.x, e61.y, e61.hole_diameter, e61.layers])));
      return (t10) => {
        const n10 = eie({ routes: t10, srj: e60 }).filter((e61) => !r9.has(JSON.stringify([e61.x, e61.y, e61.hole_diameter, e61.layers])));
        for (const e61 of n10) {
          const t11 = e61.hole_diameter / 2, n11 = o10.search({ minX: e61.x - t11, minY: e61.y - t11, maxX: e61.x + t11, maxY: e61.y + t11 });
          for (const t12 of n11)
            if (e61.layers.some((e63) => t12.layers.includes(e63)) && lz(e61, e61, e61.hole_diameter, t12).gap < -0.000001)
              return true;
        }
        return false;
      };
    }({ srj: e54.srj, previousRoutes: e54.routes }), this.currentRoutes = e54.routes, this.bestRoutes = e54.routes, this.candidateSearchBudget = ((e60) => {
      if (!Number.isInteger(e60) || e60 < 0)
        throw new Error("Pipeline9 regional repair route count must be nonnegative");
      const t4 = Math.floor(7000 / Math.max(1, e60));
      return Math.max(16, Math.min(192, t4));
    })(e54.routes.length), this.MAX_ITERATIONS = 64 + 8 * this.candidateSearchBudget;
  }
  introducesViaInPad(e54) {
    return this.params.srj.allowViaInPad !== true && this.evaluateViaInPad(e54);
  }
  initializeRepair() {
    const { initialErrors: e54, drcEvaluator: t4, newConnections: n8, syntheticConnectionNames: o10 } = this.params;
    this.currentErrors = e54 ?? zoe(t4, this.currentRoutes), this.MAX_ITERATIONS += 16 * this.currentErrors.length, this.preloadEligibleDrcIssueCount = this.currentErrors.filter((e60) => (({ error: e61, preloadRepairTraceIds: t10 }) => !!Boe(e61).some((e63) => t10.has(e63)) || (e61.__collapsed_trace_participants ?? []).flatMap((e63) => new Set(e63.evaluationTraceIds).size > 1 ? [e63.solverTraceId] : []).some((e63) => t10.collidingFixedTraceIds?.has(e63)))({ error: e60, preloadRepairTraceIds: this.params.preloadRepairTraceIds })).length;
    const i8 = Yoe({ routes: this.currentRoutes, newConnections: n8, syntheticConnectionNames: o10 }), r9 = this.params.allowTracePairRepair === true && this.currentErrors.some((e60) => rie(e60, i8));
    this.preloadEligibleDrcIssueCount !== 0 || r9 ? (this.fixedRouteCopperSpatialIndex = ((e60, t10) => {
      const n10 = new Map, o11 = (e61, t11) => {
        const o12 = Math.floor(t11.minX / 4), i9 = Math.floor(t11.maxX / 4), r10 = Math.floor(t11.minY / 4), s7 = Math.floor(t11.maxY / 4);
        for (let t12 = o12;t12 <= i9; t12++)
          for (let o13 = r10;o13 <= s7; o13++) {
            const i10 = `${t12}:${o13}`, r11 = n10.get(i10) ?? new Set;
            r11.add(e61), n10.set(i10, r11);
          }
      };
      for (let n11 = 0;n11 < e60.length; n11++) {
        const i9 = os(e60[n11], t10);
        for (const e61 of i9.wireSegments)
          for (const t11 of is(e61, 4, 1))
            o11(n11, hie(t11));
        for (const e61 of i9.viaSpans)
          o11(n11, lie(e61));
      }
      return { getRoutesOverlappingBounds: (o12) => {
        const i9 = new Set, r10 = Math.floor(o12.minX / 4), s7 = Math.floor(o12.maxX / 4), a9 = Math.floor(o12.minY / 4), c5 = Math.floor(o12.maxY / 4);
        for (let e61 = r10;e61 <= s7; e61++)
          for (let t11 = a9;t11 <= c5; t11++)
            for (const o13 of n10.get(`${e61}:${t11}`) ?? [])
              i9.add(o13);
        return [...i9].sort((e61, t11) => e61 - t11).map((t11) => e60[t11]).filter((e61) => die(e61, o12, t10));
      } };
    })(this.params.fixedObstacleRoutes, this.params.srj), this.phase = "begin-pass") : this.finishRepair();
  }
  beginPass() {
    this.candidateSearchBudgetExhausted || this.passIndex >= 2 ? this.beginCleanup({ kind: "accepted-routes", routes: this.currentRoutes, errors: this.currentErrors }) : (this.acceptedOnPass = false, this.routeIndexByTraceId = Yoe({ routes: this.currentRoutes, newConnections: this.params.newConnections, syntheticConnectionNames: this.params.syntheticConnectionNames }), this.repairableErrors = this.currentErrors.filter((e54) => (e54.type === "pcb_trace_error" || e54.type === "pcb_pad_trace_clearance_error" || e54.type === "pcb_via_trace_clearance_error" || e54.type === "pcb_via_clearance_error" || Goe(e54)) && typeof e54.pcb_trace_id == "string"), this.errorIndex = 0, this.phase = "begin-error");
  }
  beginError() {
    if (this.candidateSearchBudgetExhausted || this.errorIndex >= this.repairableErrors.length)
      return void (this.phase = "finish-pass");
    const e54 = this.repairableErrors[this.errorIndex];
    this.repairCenter = oie(e54, this.params.srj), this.traceIds = iie({ error: e54, routeIndexByTraceId: this.routeIndexByTraceId }).slice(0, 2), this.repairCenter ? (this.bestRoutes = this.currentRoutes, this.bestErrors = this.currentErrors, this.traceIndex = 0, this.regionIndex = 0, this.stopB01SearchForError = false, this.phase = rie(e54, this.routeIndexByTraceId) ? "prepare-pair" : "prepare-b01") : this.errorIndex++;
  }
  preparePairCandidate() {
    if (this.candidateSearchCount >= this.candidateSearchBudget)
      return this.candidateSearchBudgetExhausted = true, void (this.phase = "commit-error");
    const e54 = this.traceIds.map((e60) => this.routeIndexByTraceId.get(e60));
    this.pairCandidate = (({ routeIndexes: e60, ...t4 }) => {
      const { routes: n8, connMap: o10, srj: i8, fixedObstacleRoutes: r9 } = t4, s7 = e60.map((e61) => n8[e61]);
      if (s7.some((e61) => t4.syntheticConnectionNames.has(e61.connectionName) || (e61.jumpers?.length ?? 0) > 0 || e61.route.some((t10, n10) => t10.insideJumperPad || t10.toNextSegmentType !== undefined || t10.toNextSegmentCircuitJsonMetadata !== undefined || t10.traceThickness !== undefined && t10.traceThickness !== e61.traceThickness || t10.pcb_port_id !== undefined && n10 > 0 && n10 < e61.route.length - 1)))
        return;
      const a9 = s7.flatMap((e61) => e61.route);
      if (a9.some((e61) => e61.x < i8.bounds.minX || e61.x > i8.bounds.maxX || e61.y < i8.bounds.minY || e61.y > i8.bounds.maxY))
        return;
      for (const e61 of s7) {
        const t10 = e61.route[0], i9 = e61.route.at(-1), s9 = [...n8, ...r9].filter((t11) => t11 !== e61 && ss(e61, t11, o10));
        for (const n10 of s9)
          for (const o11 of [n10.route[0], n10.route.at(-1)])
            if (!(o11.z === t10.z && Math.hypot(o11.x - t10.x, o11.y - t10.y) < 0.000000001 || o11.z === i9.z && Math.hypot(o11.x - i9.x, o11.y - i9.y) < 0.000000001))
              for (let t11 = 1;t11 < e61.route.length; t11++) {
                const n11 = e61.route[t11 - 1], i10 = e61.route[t11];
                if (o11.z >= Math.min(n11.z, i10.z) && o11.z <= Math.max(n11.z, i10.z) && pe(o11, n11, i10) < 0.000000001)
                  return;
              }
      }
      const c5 = Math.max(t4.traceWidth, ...s7.map((e61) => e61.traceThickness), ...a9.map((e61) => e61.traceThickness ?? t4.traceWidth)), l5 = Math.max(t4.viaDiameter, ...s7.map((e61) => e61.viaDiameter)), h5 = Math.max(t4.obstacleMargin, i8.minViaEdgeToPadEdgeClearance ?? t4.obstacleMargin, i8.minTraceToHoleEdgeClearance ?? t4.obstacleMargin), d9 = l5 + h5, u9 = Math.max(i8.bounds.minX, Math.min(...a9.map((e61) => e61.x)) - d9), p9 = Math.min(i8.bounds.maxX, Math.max(...a9.map((e61) => e61.x)) + d9), m9 = Math.max(i8.bounds.minY, Math.min(...a9.map((e61) => e61.y)) - d9), g10 = Math.min(i8.bounds.maxY, Math.max(...a9.map((e61) => e61.y)) + d9);
      if (p9 - u9 > 15 || g10 - m9 > 15)
        return;
      const f10 = aie(n8, o10), _5 = { capacityMeshNodeId: "pipeline9_trace_pair_repair", center: { x: (u9 + p9) / 2, y: (m9 + g10) / 2 }, width: p9 - u9, height: g10 - m9, availableZ: Array.from({ length: i8.layerCount }, (e61, t10) => t10), portPoints: [], portPointsInPairs: [] }, y10 = Rne(_5, e60.map((e61) => f10[e61]));
      if (y10.fixedRouteSectionsByConnectionName.size !== 2)
        return;
      const b10 = new Map;
      for (const t10 of e60)
        b10.set(t10, y10.fixedRouteSectionsByConnectionName.get(f10[t10].connectionName));
      const x8 = f10.filter((e61, t10) => !b10.has(t10));
      return { solver: new Loe({ nodePortPoints: [y10.nodeWithPortPoints], fixedHdRoutes: [...x8, ...r9].map((e61) => ({ ...e61, rootConnectionName: o10.getNetConnectedToId(e61.rootConnectionName ?? e61.connectionName) ?? e61.rootConnectionName ?? e61.connectionName })), connMap: o10, colorMap: t4.colorMap, obstacles: i8.obstacles, layerCount: i8.layerCount, allowBlindAndBuriedVias: i8.allowBlindAndBuriedVias, viaDiameter: l5, traceWidth: c5, obstacleMargin: t4.obstacleMargin, effort: t4.effort, preserveTerminalPcbPortIds: true, includeBoardObstacles: true, enableRegionalFallback: false, maxB01Rips: 120, b01RepairOptions: { lowResolutionCellSize: qne.highResolutionCellSize, obstacleClearanceMargin: h5 } }), routes: n8, sections: b10 };
    })({ ...this.params, routes: this.currentRoutes, routeIndexes: [e54[0], e54[1]] }), this.pairCandidate ? (this.candidateSearchCount++, this.startChildSolver(this.pairCandidate.solver), this.phase = "route-pair") : this.phase = "prepare-b01";
  }
  stepPairCandidate() {
    const e54 = this.pairCandidate;
    if (!e54)
      throw new Error("Regional pair repair has no candidate");
    e54.solver.step(), (e54.solver.solved || e54.solver.failed) && (this.activeSubSolver = null, this.phase = "validate-pair");
  }
  validatePairCandidate() {
    const e54 = this.pairCandidate;
    if (!e54)
      throw new Error("Regional pair repair has no completed candidate");
    const t4 = (({ solver: e60, routes: t10, sections: n10 }) => {
      if (e60.solved && !e60.failed)
        return t10.map((t11, o10) => {
          const i8 = n10.get(o10);
          if (!i8)
            return t11;
          const r9 = e60.routes.find((e61) => e61.connectionName === i8.sourceRoutes[0].connectionName);
          if (!r9)
            throw new Error("Completed pair repair is missing a route");
          return { ...Ene(i8, r9), connectionName: t11.connectionName };
        });
    })(e54);
    if (this.pairCandidate = undefined, this.phase = "prepare-b01", !t4)
      return;
    this.attemptedCandidateCount++;
    const n8 = zoe(this.params.drcEvaluator, t4);
    $oe(n8, this.bestErrors) && !this.introducesViaInPad(t4) && (this.bestRoutes = t4, this.bestErrors = n8, this.phase = "commit-error");
  }
  startChildSolver(e54) {
    const t4 = Math.floor(e54.MAX_ITERATIONS) + 1;
    if (!Number.isSafeInteger(t4) || t4 < 1)
      throw new Error("Regional B01 child has an invalid iteration limit");
    this.MAX_ITERATIONS += t4, this.activeSubSolver = e54;
  }
  prepareB01Candidate() {
    if (this.stopB01SearchForError || this.candidateSearchBudgetExhausted || this.traceIndex >= this.traceIds.length)
      return void (this.phase = "prepare-regional");
    const e54 = this.routeIndexByTraceId.get(this.traceIds[this.traceIndex]);
    if (e54 === undefined)
      return this.traceIndex++, void (this.regionIndex = 0);
    if (this.regionIndex >= tie.length)
      return void (this.bestErrors.length === 0 ? this.stopB01SearchForError = true : (this.traceIndex++, this.regionIndex = 0));
    if (this.candidateSearchCount >= this.candidateSearchBudget)
      return this.candidateSearchBudgetExhausted = true, void (this.phase = "prepare-regional");
    const t4 = this.repairCenter;
    if (!t4)
      throw new Error("Regional B01 candidate has no repair center");
    const n8 = tie[this.regionIndex];
    this.regionIndex++, this.candidateSearchCount++, this.b01Candidate = (({ routes: e60, fixedObstacleRoutes: t10, routeIndex: n10, center: o10, regionSize: i8, srj: r9, connMap: s7, colorMap: a9, viaDiameter: c5, traceWidth: l5, obstacleMargin: h5, effort: d9 }) => {
      const u9 = aie(e60, s7), p9 = u9[n10];
      if (!p9)
        return;
      const m9 = { capacityMeshNodeId: `pipeline9_joint_drc_${n10}_${i8}`, center: o10, width: i8, height: i8, availableZ: Array.from({ length: r9.layerCount }, (e61, t11) => t11), portPoints: [], portPointsInPairs: [] }, g10 = Rne(m9, [p9]), f10 = g10.fixedRouteSectionsByConnectionName.get(p9.connectionName);
      if (!f10)
        return;
      const _5 = u9.filter((e61, t11) => t11 !== n10);
      return { solver: new Loe({ nodePortPoints: [g10.nodeWithPortPoints], fixedHdRoutes: [..._5, ...t10].map((e61) => ({ ...e61, rootConnectionName: s7.getNetConnectedToId(e61.rootConnectionName ?? e61.connectionName) ?? e61.rootConnectionName ?? e61.connectionName })), connMap: s7, colorMap: a9, obstacles: r9.obstacles, layerCount: r9.layerCount, allowBlindAndBuriedVias: r9.allowBlindAndBuriedVias, viaDiameter: c5, traceWidth: l5, obstacleMargin: h5, effort: d9, preserveTerminalPcbPortIds: true, includeBoardObstacles: true, enableRegionalFallback: false, maxB01Rips: 120 }), routes: e60, movableRoute: p9, movableSection: f10, routeIndex: n10 };
    })({ ...this.params, routes: this.currentRoutes, routeIndex: e54, center: t4, regionSize: n8 }), this.b01Candidate && (this.startChildSolver(this.b01Candidate.solver), this.phase = "route-b01");
  }
  stepB01Candidate() {
    const e54 = this.b01Candidate;
    if (!e54)
      throw new Error("Regional B01 has no active candidate");
    e54.solver.step(), (e54.solver.solved || e54.solver.failed) && (this.activeSubSolver = null, this.phase = "validate-b01");
  }
  validateB01Candidate() {
    const e54 = this.b01Candidate;
    if (!e54)
      throw new Error("Regional B01 has no completed candidate");
    const t4 = (({ solver: e60, routes: t10, movableRoute: n8, movableSection: o10, routeIndex: i8 }) => {
      if (!e60.solved || e60.failed)
        return;
      const r9 = e60.routes.find((e61) => e61.connectionName === n8.connectionName);
      return r9 ? { routes: t10.map((e61, t11) => t11 === i8 ? { ...Ene(o10, r9), connectionName: e61.connectionName } : e61), usedFallback: Number(e60.stats.fallbackNodeCount ?? 0) > 0 } : undefined;
    })(e54);
    if (this.b01Candidate = undefined, t4) {
      this.attemptedCandidateCount++, t4.usedFallback && this.fallbackCandidateCount++;
      const e60 = zoe(this.params.drcEvaluator, t4.routes);
      $oe(e60, this.bestErrors) && !this.introducesViaInPad(t4.routes) && (this.bestRoutes = t4.routes, this.bestErrors = e60), this.bestErrors.length === 0 && (this.stopB01SearchForError = true);
    }
    this.phase = "prepare-b01";
  }
  prepareRegularCandidate() {
    if (this.bestRoutes !== this.currentRoutes || this.candidateSearchBudgetExhausted)
      return void (this.phase = "commit-error");
    if (this.candidateSearchCount >= this.candidateSearchBudget)
      return this.candidateSearchBudgetExhausted = true, void (this.phase = "commit-error");
    this.candidateSearchCount++;
    const e54 = this.repairCenter, t4 = this.fixedRouteCopperSpatialIndex;
    if (!e54 || !t4)
      throw new Error("Regional fallback candidate is missing its fixed context");
    this.regularCandidate = uie({ ...this.params, routes: this.currentRoutes, fixedRouteCopperSpatialIndex: t4, center: e54, regionSize: 3 }), this.regularCandidate ? (this.startChildSolver(this.regularCandidate.solver), this.phase = "route-regional") : this.phase = "commit-error";
  }
  stepRegularCandidate() {
    const e54 = this.regularCandidate;
    if (!e54)
      throw new Error("Regional fallback has no active candidate");
    e54.solver.step(), (e54.solver.solved || e54.solver.failed) && (this.activeSubSolver = null, this.phase = "validate-regional");
  }
  validateRegularCandidate() {
    const e54 = this.regularCandidate;
    if (!e54)
      throw new Error("Regional fallback has no completed candidate");
    const t4 = pie(e54);
    if (this.regularCandidate = undefined, t4) {
      this.attemptedCandidateCount++, this.fallbackCandidateCount++;
      const e60 = zoe(this.params.drcEvaluator, t4);
      if ($oe(e60, this.bestErrors)) {
        if (this.introducesViaInPad(t4))
          return void this.beginCleanup({ kind: "regular-candidate", routes: t4, errors: e60 });
        this.bestRoutes = t4, this.bestErrors = e60;
      }
    }
    this.phase = "commit-error";
  }
  commitErrorRepair() {
    this.bestRoutes !== this.currentRoutes && (this.currentRoutes = this.bestRoutes, this.currentErrors = this.bestErrors, this.acceptedCandidateCount++, this.acceptedOnPass = true), this.errorIndex++, this.phase = this.candidateSearchBudgetExhausted ? "finish-pass" : "begin-error";
  }
  finishPass() {
    this.passIndex++, this.acceptedOnPass && this.currentErrors.length !== 0 && !this.candidateSearchBudgetExhausted ? this.phase = "begin-pass" : this.beginCleanup({ kind: "accepted-routes", routes: this.currentRoutes, errors: this.currentErrors });
  }
  beginCleanup(e54) {
    if (this.cleanup)
      throw new Error("Regional B01 cleanup is already active");
    this.cleanup = e54, this.phase = "refine";
  }
  getCleanupOrThrow() {
    const e54 = this.cleanup;
    if (!e54)
      throw new Error("Regional B01 repair has no active cleanup");
    return e54;
  }
  refineCleanupRoutes() {
    const e54 = this.getCleanupOrThrow();
    if ((e54.kind === "regular-candidate" || this.acceptedCandidateCount > 0) && e54.errors.length > 0) {
      const t4 = ((e60, t10) => {
        if (e60 === t10)
          return t10;
        let n8 = t10;
        for (const [o10, i8] of e60.entries()) {
          const e61 = i8.route.filter((e63) => e63.terminalApproach !== undefined);
          if (e61.length === 0)
            continue;
          const r9 = t10[o10], s7 = [...r9.route];
          for (const t11 of e61) {
            const e63 = r9.route.flatMap((e64, n10) => e64.terminalApproach === t11.terminalApproach ? [n10] : []);
            if (e63.length !== 1)
              return;
            s7[e63[0]] = t11;
          }
          n8 === t10 && (n8 = [...t10]), n8[o10] = { ...r9, route: s7 };
        }
        return n8;
      })(e54.routes, ow({ ...this.params.srj, traces: undefined }, e54.routes, this.params.effort, 1, this.params.connMap));
      if (t4 && t4 !== e54.routes) {
        const n8 = zoe(this.params.drcEvaluator, t4);
        sie(n8) <= sie(e54.errors) && $oe(n8, e54.errors) && !this.introducesViaInPad(t4) && (e54.routes = t4, e54.errors = n8);
      }
    }
    this.phase = "prepare-via-pad-projection";
  }
  prepareViaPadProjection() {
    const e54 = this.getCleanupOrThrow(), t4 = e54.errors.filter(Goe).flatMap((e60) => {
      const t10 = oie(e60, this.params.srj);
      return t10 ? [{ center: t10, radius: tie[0] / 2 }] : [];
    });
    if (t4.length === 0)
      return void (this.phase = "prepare-safe-layer");
    const n8 = e54.routes.length;
    this.viaPadProjectionSolver = new qoe({ originalSrj: this.params.srj, routes: [...e54.routes, ...this.params.fixedObstacleRoutes], lockedConnectionNames: new Set([...this.params.syntheticConnectionNames, ...this.params.fixedObstacleRoutes.map((e60) => e60.connectionName)]), movableRegions: t4, usePrecisionMargin: true, drcEvaluator: ({ hdRoutes: e60 }) => {
      if (!e60)
        throw new Error("Via-pad projection requires HD routes");
      return this.params.drcEvaluator({ traces: [], hdRoutes: e60.slice(0, n8) });
    } }), this.startChildSolver(this.viaPadProjectionSolver), this.phase = "project-via-pad";
  }
  stepViaPadProjection() {
    const e54 = this.getCleanupOrThrow(), t4 = this.viaPadProjectionSolver;
    if (!t4)
      throw new Error("Regional B01 has no via-pad projection");
    if (t4.step(), this.MAX_ITERATIONS = Math.max(this.MAX_ITERATIONS, this.iterations + t4.MAX_ITERATIONS - t4.iterations + 16), t4.failed)
      throw new Error(`Regional via-pad projection failed: ${t4.error}`);
    t4.solved && (e54.routes = t4.getOutput().slice(0, e54.routes.length), e54.errors = zoe(this.params.drcEvaluator, e54.routes), this.activeSubSolver = null, this.phase = "prepare-safe-layer");
  }
  prepareSafeLayerRepair() {
    const e54 = this.getCleanupOrThrow(), t4 = e54.errors.some((e60) => e60.type === "pcb_trace_error" || e60.type === "pcb_pad_trace_clearance_error");
    this.safeTraceLayerRepairSkippedForBudget = t4 && this.candidateSearchBudgetExhausted, t4 && !this.candidateSearchBudgetExhausted ? (this.safeTraceLayerSolver = new kN({ srj: { ...this.params.srj, traces: undefined }, hdRoutes: e54.routes, connMap: this.params.connMap, effort: this.params.effort, drcEvaluator: this.params.drcEvaluator, maxIterations: 8, enableLargeBoardBroadFallback: false, enableTargetedErrorSweep: false, enablePostSolveClearanceRelaxation: false, enableSafeTraceLayerMoves: true, enableViaInPadLayerMoves: false }), this.startChildSolver(this.safeTraceLayerSolver), this.phase = "route-safe-layer") : this.finishCleanup();
  }
  stepSafeLayerRepair() {
    const e54 = this.safeTraceLayerSolver;
    if (!e54)
      throw new Error("Regional B01 has no safe trace-layer solver");
    if (e54.step(), e54.failed)
      throw new Error(`Pipeline9 post-regional safe trace-layer repair failed: ${e54.error ?? "unknown error"}`);
    e54.solved && (this.activeSubSolver = null, this.phase = "validate-safe-layer");
  }
  validateSafeLayerRepair() {
    const e54 = this.getCleanupOrThrow(), t4 = this.safeTraceLayerSolver;
    if (!t4)
      throw new Error("Regional B01 has no completed safe trace-layer solver");
    const n8 = t4.getOutput(), o10 = zoe(this.params.drcEvaluator, n8);
    $oe(o10, e54.errors) && !this.introducesViaInPad(n8) && (e54.routes = n8, e54.errors = o10), this.safeTraceLayerSolver = undefined, this.finishCleanup();
  }
  finishCleanup() {
    const e54 = this.getCleanupOrThrow();
    this.cleanup = undefined;
    const t4 = this.introducesViaInPad(e54.routes);
    if (e54.kind === "regular-candidate")
      return !t4 && $oe(e54.errors, this.bestErrors) && (this.bestRoutes = e54.routes, this.bestErrors = e54.errors), void (this.phase = "commit-error");
    t4 || (this.currentRoutes = e54.routes, this.currentErrors = e54.errors), this.finishRepair();
  }
  finishRepair() {
    if (this.activeSubSolver = null, this.introducesViaInPad(this.currentRoutes))
      return this.error = "Pipeline9 regional repair introduced a forbidden via-in-pad", void (this.failed = true);
    this.result = { routes: this.currentRoutes, attemptedCandidateCount: this.attemptedCandidateCount, acceptedCandidateCount: this.acceptedCandidateCount, fallbackCandidateCount: this.fallbackCandidateCount, candidateSearchCount: this.candidateSearchCount, candidateSearchBudget: this.candidateSearchBudget, candidateSearchBudgetExhausted: this.candidateSearchBudgetExhausted, safeTraceLayerRepairSkippedForBudget: this.safeTraceLayerRepairSkippedForBudget, remainingDrcIssueCount: this.currentErrors.length, preloadEligibleDrcIssueCount: this.preloadEligibleDrcIssueCount, preloadRepairAttempted: this.preloadEligibleDrcIssueCount > 0 }, this.stats = { ...this.result, routes: undefined }, this.phase = "done", this.solved = true;
  }
  _step() {
    switch (this.phase) {
      case "initialize":
        return this.initializeRepair();
      case "begin-pass":
        return this.beginPass();
      case "begin-error":
        return this.beginError();
      case "prepare-pair":
        return this.preparePairCandidate();
      case "route-pair":
        return this.stepPairCandidate();
      case "validate-pair":
        return this.validatePairCandidate();
      case "prepare-b01":
        return this.prepareB01Candidate();
      case "route-b01":
        return this.stepB01Candidate();
      case "validate-b01":
        return this.validateB01Candidate();
      case "prepare-regional":
        return this.prepareRegularCandidate();
      case "route-regional":
        return this.stepRegularCandidate();
      case "validate-regional":
        return this.validateRegularCandidate();
      case "commit-error":
        return this.commitErrorRepair();
      case "finish-pass":
        return this.finishPass();
      case "refine":
        return this.refineCleanupRoutes();
      case "prepare-via-pad-projection":
        return this.prepareViaPadProjection();
      case "project-via-pad":
        return this.stepViaPadProjection();
      case "prepare-safe-layer":
        return this.prepareSafeLayerRepair();
      case "route-safe-layer":
        return this.stepSafeLayerRepair();
      case "validate-safe-layer":
        return this.validateSafeLayerRepair();
      case "done":
        throw new Error("Regional B01 repair was stepped after completion");
    }
  }
  computeProgress() {
    if (this.solved)
      return 1;
    const e54 = this.activeSubSolver ? Math.max(0, Math.min(1, this.activeSubSolver.progress)) : 1;
    return Math.max(this.progress, Math.min(1, (Math.max(0, this.candidateSearchCount - 1) + e54) / (this.candidateSearchBudget + 1)));
  }
  getResult() {
    if (!this.solved || this.failed || !this.result)
      throw new Error("Pipeline9 regional B01 repair is not complete");
    return this.result;
  }
};
var gie = class extends ni {
  params;
  merger;
  result;
  phase = "initialize";
  physicalSrj;
  movableRoutes = [];
  candidateRoutes;
  beforeErrorCount = 0;
  constructor(e54) {
    super(), this.params = e54, this.MAX_ITERATIONS = 1000004;
  }
  initializeMerge() {
    const { srj: e54, routes: t4, connMap: n8, drcEvaluator: o10, referenceResult: i8 } = this.params, r9 = i8 ?? o10({ traces: [], routes: t4, hdRoutes: t4 });
    this.result = { routes: t4, referenceResult: r9, referenceValidationCount: i8 === undefined ? 1 : 0, accepted: false };
    const s7 = Array.isArray(r9) ? r9 : r9.errors;
    this.beforeErrorCount = s7.length;
    const a9 = s7.filter((e60) => e60.type === "pcb_via_clearance_error").flatMap(Uoe);
    if (this.movableRoutes = t4.filter((e60) => a9.some((t10) => t10 === e60.connectionName || t10.startsWith(`${e60.connectionName}_`))), this.movableRoutes.length === 0)
      return this.phase = "done", void (this.solved = true);
    this.physicalSrj = { ...V1(e54), traces: undefined };
    const c5 = new Set(this.movableRoutes);
    this.merger = new PF({ inputHdRoutes: this.movableRoutes, otherHdRoutes: t4.filter((e60) => !c5.has(e60)), netByConnectionName: hne(t4, n8), obstacles: this.physicalSrj.obstacles, layerCount: this.physicalSrj.layerCount, connMap: n8, colorMap: {}, preserveRouteEndpoints: true }), this.MAX_ITERATIONS = this.merger.MAX_ITERATIONS + 4, this.activeSubSolver = this.merger, this.phase = "merge";
  }
  stepMerge() {
    const e54 = this.merger;
    if (!e54)
      throw new Error("Reported via merge has no active merger");
    if (e54.step(), e54.failed)
      throw new Error(`Reported via merge failed: ${e54.error}`);
    if (!e54.solved)
      return;
    if (e54.mergedViaHdRoutes.length !== this.movableRoutes.length)
      throw new Error("Reported via merge changed the number of route pieces");
    const t4 = new Map(this.movableRoutes.map((t10, n8) => [t10, e54.mergedViaHdRoutes[n8]]));
    this.candidateRoutes = this.params.routes.map((e60) => t4.get(e60) ?? e60), this.activeSubSolver = null, this.phase = "physical-check";
  }
  validatePhysicalProposal() {
    const e54 = this.physicalSrj, t4 = this.candidateRoutes;
    if (!e54 || !t4)
      throw new Error("Reported via merge has no physical proposal");
    const n8 = this.params.routes, o10 = new Map(ay({ srj: e54, routes: n8 }).map(({ key: e60, severity: t10 }) => [e60, t10]));
    if (!ay({ srj: e54, routes: t4 }).every(({ key: e60, severity: t10 }) => o10.has(e60) && t10 <= o10.get(e60) + 0.00000001) || ly({ srj: e54, previousRoutes: n8, routes: t4 }).length > 0)
      return this.phase = "done", void (this.solved = true);
    this.phase = "reference-check";
  }
  validateReferenceProposal() {
    const e54 = this.result, t4 = this.candidateRoutes;
    if (!e54 || !t4)
      throw new Error("Reported via merge has no reference proposal");
    const n8 = this.params.drcEvaluator({ traces: [], routes: t4, hdRoutes: t4 });
    e54.referenceValidationCount++;
    (Array.isArray(n8) ? n8 : n8.errors).length < this.beforeErrorCount && (this.result = { ...e54, routes: t4, referenceResult: n8, accepted: true }), this.phase = "done", this.solved = true;
  }
  _step() {
    switch (this.phase) {
      case "initialize":
        return this.initializeMerge();
      case "merge":
        return this.stepMerge();
      case "physical-check":
        return this.validatePhysicalProposal();
      case "reference-check":
        return this.validateReferenceProposal();
      case "done":
        throw new Error("Reported via merge was stepped after completion");
    }
  }
  getResult() {
    if (!this.solved || this.failed || !this.result)
      throw new Error("Reported via merge is not complete");
    return this.result;
  }
};
var fie = [10, 16];
var _ie = class extends ni {
  params;
  budget;
  state = { phase: "initialize" };
  result;
  reservedChildMaximum = 0;
  constructor(e54) {
    super(), this.params = e54, this.budget = e54.budget ?? Joe, this.result = { routes: e54.routes, attemptedRegionCount: 0, acceptedRegionCount: 0, candidateAttemptCount: 0, pathSearchNodeCount: 0, referenceValidationCount: 0, initialDrcIssueCount: undefined, finalDrcIssueCount: undefined, publishedDrcIssueCount: undefined, repaired: false }, this.MAX_ITERATIONS = 16 * this.budget.maxRegions + 32;
  }
  updateProgress() {
    const e54 = Koe(this.budget, this.result.acceptedRegionCount), t4 = this.state.phase === "negotiate" ? this.state.solver : undefined, n8 = typeof t4?.stats.pathSearchCalls == "number" ? t4.stats.pathSearchCalls : 0, o10 = typeof t4?.stats.pathSearchNodes == "number" ? t4.stats.pathSearchNodes : 0;
    this.stats = { ...this.result, routes: undefined, phase: this.state.phase, candidateAttemptCount: this.result.candidateAttemptCount + n8, pathSearchNodeCount: this.result.pathSearchNodeCount + o10, allowedRegionCount: e54.maxRegions, allowedCandidateAttemptCount: e54.maxCandidateAttempts, allowedPathSearchNodeCount: e54.maxPathSearchNodes };
    const i8 = Math.max(this.result.attemptedRegionCount / Math.max(1, this.budget.maxRegions), this.stats.candidateAttemptCount / Math.max(1, this.budget.maxCandidateAttempts), this.stats.pathSearchNodeCount / Math.max(1, this.budget.maxPathSearchNodes));
    this.progress = this.solved ? 1 : Math.max(this.progress, Math.min(0.99, i8));
  }
  startChild(e54) {
    if (this.activeSubSolver)
      throw new Error("Regional repair started a child before the previous stage completed");
    this.activeSubSolver = e54, this.reservedChildMaximum = e54.MAX_ITERATIONS, this.MAX_ITERATIONS += this.reservedChildMaximum + 1;
  }
  finish() {
    if (this.activeSubSolver)
      throw new Error("Regional repair finished with an active child solver");
    this.solved = true, this.state = { phase: "done" };
  }
  publish(e54, t4) {
    this.result.routes = e54.currentRoutes, this.result.publishedDrcIssueCount = e54.currentErrors.length, this.result.finalDrcIssueCount = e54.currentErrors.length, this.result.repaired = t4, this.finish();
  }
  initialize() {
    const { originalSrj: e54, routes: t4, syntheticConnectionNames: n8 } = this.params;
    if (e54.traces?.length || n8.size > 0)
      return void this.finish();
    const o10 = Math.max(e54.defaultObstacleMargin ?? 0.2, e54.minTraceToPadEdgeClearance ?? 0, e54.minTraceToHoleEdgeClearance ?? 0, e54.minViaEdgeToPadEdgeClearance ?? 0);
    let i8 = Math.max(e54.minTraceWidth, e54.minViaDiameter ?? 0);
    for (const e60 of t4) {
      i8 = Math.max(i8, e60.traceThickness, e60.viaDiameter);
      for (const t10 of e60.route)
        i8 = Math.max(i8, t10.traceThickness ?? 0);
    }
    const r9 = Math.max(0.5, i8 + o10), s7 = (this.budget.regionSizes ?? fie).filter((e60) => !Number.isFinite(r9) || 2 * r9 < e60);
    s7.length !== 0 ? this.state = { phase: "initial-reference", context: { boundaryMargin: r9, regionSizes: s7 } } : this.finish();
  }
  initialReference(e54) {
    const t4 = this.params.drcEvaluator({ traces: [], routes: this.params.routes, hdRoutes: this.params.routes });
    this.result.referenceValidationCount++;
    const n8 = Array.isArray(t4) ? t4 : t4.errors, o10 = { ...e54, currentRoutes: this.params.routes, reference: t4, currentErrors: n8, initialErrors: n8 };
    if (this.result.initialDrcIssueCount = n8.length, this.result.finalDrcIssueCount = n8.length, this.result.publishedDrcIssueCount = n8.length, n8.length === 0)
      return void this.finish();
    const i8 = [], r9 = Array.isArray(t4) ? t4 : t4.errorsWithCenters ?? t4.errors;
    for (const t10 of r9) {
      const n10 = t10.center ?? t10.pcb_center;
      n10 && typeof n10 == "object" && "x" in n10 && typeof n10.x == "number" && Number.isFinite(n10.x) && "y" in n10 && typeof n10.y == "number" && Number.isFinite(n10.y) && i8.push({ center: { x: n10.x, y: n10.y }, radius: e54.regionSizes[0] / 2 });
    }
    const s7 = new qoe({ originalSrj: this.params.originalSrj, routes: o10.currentRoutes, movableRegions: i8, drcEvaluator: (e60) => (this.result.referenceValidationCount++, this.params.drcEvaluator(e60)) });
    this.state = { phase: "initial-projection", context: o10, solver: s7 }, this.startChild(s7);
  }
  initialProjectionReference(e54) {
    const t4 = this.params.drcEvaluator({ traces: [], routes: e54.currentRoutes, hdRoutes: e54.currentRoutes });
    this.result.referenceValidationCount++, e54.reference = t4, e54.currentErrors = Array.isArray(t4) ? t4 : t4.errors, this.result.finalDrcIssueCount = e54.currentErrors.length, e54.currentErrors.length !== 0 ? this.state = { phase: "prepare-regions", context: e54 } : this.publish(e54, true);
  }
  prepareRegions(e54) {
    const t4 = { ...V1(this.params.originalSrj), traces: undefined }, n8 = new Map;
    for (const e60 of this.params.originalSrj.obstacles)
      for (const t10 of [e60.obstacleId, e60.circuitJsonMetadata?.pcb_smtpad_id, e60.circuitJsonMetadata?.pcb_plated_hole_id, e60.connectedTo[0]])
        typeof t10 == "string" && n8.set(t10, e60.center);
    const o10 = bne(e54.currentRoutes), i8 = { ...e54, srj: t4, obstacleCenterById: n8, currentRoutes: o10, attemptedRegions: [], fixedViolations: new Map(ay({ srj: t4, routes: o10 }).map(({ key: e60, severity: t10 }) => [e60, t10])) };
    this.state = { phase: "select-region", context: i8 };
  }
  selectRegion(e54) {
    const t4 = Koe(this.budget, this.result.acceptedRegionCount);
    if (this.result.attemptedRegionCount >= t4.maxRegions || this.result.candidateAttemptCount >= t4.maxCandidateAttempts || this.result.pathSearchNodeCount >= t4.maxPathSearchNodes)
      return void (this.state = { phase: "publish-partial", context: e54 });
    const n8 = Array.isArray(e54.reference) ? e54.reference : e54.reference.errorsWithCenters ?? e54.reference.errors, o10 = n8.filter((e60) => !uw(e60)), i8 = o10.length > 0 ? o10 : n8, r9 = i8.map((t10) => {
      const n10 = `overlap_${t10.pcb_trace_id}_`, o11 = typeof t10.pcb_pad_id == "string" ? t10.pcb_pad_id : typeof t10.pcb_trace_error_id == "string" && t10.pcb_trace_error_id.startsWith(n10) ? t10.pcb_trace_error_id.slice(n10.length) : undefined;
      return (o11 ? e54.obstacleCenterById.get(o11) : undefined) ?? t10.center ?? t10.pcb_center;
    }).filter((e60) => e60 !== null && typeof e60 == "object" && ("x" in e60) && ("y" in e60) && typeof e60.x == "number" && typeof e60.y == "number" && Number.isFinite(e60.x) && Number.isFinite(e60.y));
    let s7;
    for (const t10 of e54.regionSizes) {
      const n10 = r9.filter(({ x: n11, y: o12 }) => !e54.attemptedRegions.some(({ bounds: e60, size: i10 }) => t10 === i10 && n11 >= e60.minX && n11 <= e60.maxX && o12 >= e60.minY && o12 <= e60.maxY)), o11 = n10[0];
      if (!o11)
        continue;
      let { x: i9, x: a10, y: c9, y: l10 } = o11;
      const h9 = t10 - 2 * e54.boundaryMargin;
      for (const e60 of n10.slice(1)) {
        const t11 = Math.min(i9, e60.x), n11 = Math.max(a10, e60.x), o12 = Math.min(c9, e60.y), r10 = Math.max(l10, e60.y);
        n11 - t11 >= h9 || r10 - o12 >= h9 || (i9 = t11, a10 = n11, c9 = o12, l10 = r10);
      }
      s7 = { center: { x: (i9 + a10) / 2, y: (c9 + l10) / 2 }, size: t10 };
      break;
    }
    if (!s7)
      return void (this.state = { phase: "publish-partial", context: e54 });
    const { center: a9, size: c5 } = s7, l5 = Iy({ srj: e54.srj, routes: e54.currentRoutes, bounds: { minX: a9.x - c5 / 2, maxX: a9.x + c5 / 2, minY: a9.y - c5 / 2, maxY: a9.y + c5 / 2 } });
    if (e54.attemptedRegions.push({ bounds: l5.mutableBounds, size: c5 }), this.result.attemptedRegionCount++, l5.routes.length === 0)
      return;
    const h5 = e54.currentErrors.map(Uoe);
    if (this.params.prioritizeConflictedRoutes) {
      const e60 = i8.map(Uoe), t10 = l5.routes.map((t11) => e60.filter((e61) => e61.some((e63) => e63 === t11.connectionName || e63.startsWith(`${t11.connectionName}_`))).length), n10 = l5.routes.map((e61, t11) => t11).sort((e61, n11) => t10[n11] - t10[e61]);
      l5.routes = n10.map((e61) => l5.routes[e61]), l5.lockedPointIndices = n10.map((e61) => l5.lockedPointIndices[e61]), l5.routeMappings = n10.map((e61) => l5.routeMappings[e61]);
    }
    const d9 = new Set(h5.flat()), u9 = l5.routes.flatMap((e60, t10) => [...d9].some((t11) => t11 === e60.connectionName || t11.startsWith(`${e60.connectionName}_`)) ? [t10] : []), p9 = Math.min(this.budget.maxCandidateAttemptsPerRegion ?? (this.budget.revisitChangedRegions ? Math.ceil(t4.maxCandidateAttempts / 2) : t4.maxCandidateAttempts), t4.maxCandidateAttempts - this.result.candidateAttemptCount), m9 = l5.routes;
    for (const [t10, n10] of m9.entries()) {
      const o11 = l5.routeMappings[t10].sourceRouteIndex, i9 = e54.currentRoutes[o11].route.filter((e60) => e60.terminalApproach !== undefined);
      if (i9.length !== 0)
        for (const [e60, o12] of n10.route.entries())
          i9.some((e61) => e61.terminalApproach === o12.terminalApproach && e61.x === o12.x && e61.y === o12.y && e61.z === o12.z) && (l5.lockedPointIndices[t10][e60] = true);
    }
    const g10 = new Xy({ srj: l5.srj, routes: m9, bounds: l5.mutableBounds, dirtyRouteIndices: u9, isLocked: (e60, t10) => l5.lockedPointIndices[e60][t10], maxPathSearchCalls: p9, maxPathSearchNodes: t4.maxPathSearchNodes - this.result.pathSearchNodeCount, maxPathSearchNodesPerCall: this.budget.maxPathSearchNodesPerCall, pathHeuristicWeight: this.budget.pathHeuristicWeight, pathGridSizeScale: this.budget.pathGridSizeScale === undefined ? undefined : this.budget.pathGridSizeScale * (e54.regionSizes[0] / c5), allowLayerChanges: true, traceClearance: hR, viaClearance: e54.srj.minPadEdgeToPadEdgeClearance ?? dR, viaHoleDiameter: this.params.viaHoleDiameter, searchDirectionCount: this.budget.searchDirectionCount ?? 1 });
    this.state = { phase: "negotiate", negotiation: { context: e54, allowance: t4, maxPathSearchCalls: p9, region: l5 }, solver: g10 }, this.startChild(g10);
  }
  completeNegotiation(e54) {
    const t4 = e54.solver.getOutput(), { context: n8, allowance: o10, maxPathSearchCalls: i8 } = e54.negotiation, { pathSearchCalls: r9, pathSearchNodes: s7 } = t4;
    if (this.budget.revisitChangedRegions && t4.unresolvedSpanCount > 0 && r9 < i8 && s7 < o10.maxPathSearchNodes - this.result.pathSearchNodeCount && n8.regionSizes.sort((e60, t10) => t10 - e60), !Number.isSafeInteger(r9) || r9 < 0 || r9 + this.result.candidateAttemptCount > this.budget.maxCandidateAttempts || !Number.isSafeInteger(s7) || s7 < 0 || s7 + this.result.pathSearchNodeCount > this.budget.maxPathSearchNodes)
      throw new Error("Pipeline9 bounded regional repair exceeded its work budget");
    this.result.candidateAttemptCount += r9, this.result.pathSearchNodeCount += s7, this.state = { phase: "splice-region", negotiation: e54.negotiation, repair: t4 };
  }
  spliceRegion(e54) {
    const { context: t4, region: n8 } = e54.negotiation, o10 = ((e60, t10) => {
      let n10 = t10;
      for (const [o11, i9] of t10.entries()) {
        if (!i9.route.some((e61) => e61.terminalApproach !== undefined))
          continue;
        const r9 = e60[o11].route.filter((e61) => e61.terminalApproach !== undefined);
        let s7 = i9.route;
        for (const [e61, t11] of i9.route.entries()) {
          if (t11.terminalApproach === undefined || r9.some((e63) => e63.terminalApproach === t11.terminalApproach && e63.x === t11.x && e63.y === t11.y && e63.z === t11.z))
            continue;
          s7 === i9.route && (s7 = [...i9.route]);
          const n11 = { ...t11 };
          delete n11.terminalApproach, s7[e61] = n11;
        }
        s7 !== i9.route && (n10 === t10 && (n10 = [...t10]), n10[o11] = { ...i9, route: s7 });
      }
      return n10;
    })(t4.currentRoutes, (({ routes: e60, region: t10, repairedRoutes: n10 }) => {
      if (n10.length !== t10.routeMappings.length || t10.lockedPointIndices.length !== n10.length)
        throw new Error("repair04 merge requires exactly one replacement for every extracted fragment");
      const o11 = new Map;
      for (let i9 = 0;i9 < n10.length; i9 += 1) {
        const r9 = t10.routeMappings[i9], s7 = n10[i9];
        if (!e60[r9.sourceRouteIndex])
          throw new Error("repair04 merge source route no longer exists");
        if (Py(r9.originalFragment, s7, t10.lockedPointIndices[i9], t10.mutableBounds, t10.contextBounds, t10.srj.layerCount), za(r9.originalFragment) === za(s7))
          continue;
        const a9 = o11.get(r9.sourceRouteIndex) ?? [];
        a9.push({ mapping: r9, repaired: s7 }), o11.set(r9.sourceRouteIndex, a9);
      }
      return e60.map((e61, t11) => {
        const n11 = o11.get(t11);
        if (!n11)
          return e61;
        n11.sort((e63, t12) => Ny(e63.mapping.start) - Ny(t12.mapping.start));
        const i9 = [];
        let r9 = 0;
        for (const { mapping: t12, repaired: o12 } of n11) {
          const n12 = Ny(t12.start), s9 = Ny(t12.end);
          if (n12 < r9 - Aa || s9 < n12 || s9 > e61.route.length - 1 + Aa)
            throw new Error("repair04 merge received overlapping or stale fragment provenance");
          if (Fa(e61, n12, s9) !== t12.sourceGeometryKey)
            throw new Error("repair04 merge rejected stale source geometry");
          My(i9, Ba(e61, r9, n12)), My(i9, o12.route), r9 = s9;
        }
        My(i9, Ba(e61, r9, e61.route.length - 1));
        const s7 = new Set(n11.flatMap(({ mapping: e63 }) => e63.originalFragment.vias.map((e64) => `${e64.x},${e64.y}`))), a9 = e61.vias.filter((e63) => !s7.has(`${e63.x},${e63.y}`)).map((e63) => structuredClone(e63));
        for (const { repaired: e63 } of n11)
          for (const t12 of e63.vias)
            a9.some((e64) => Math.abs(e64.x - t12.x) <= Aa && Math.abs(e64.y - t12.y) <= Aa) || a9.push(structuredClone(t12));
        return { ...e61, route: wy(i9, e61, n11.map(({ mapping: e63 }) => e63)), vias: a9 };
      });
    })({ routes: t4.currentRoutes, region: n8, repairedRoutes: e54.repair.routes }));
    if (o10.every((e60, n10) => e60 === t4.currentRoutes[n10]))
      return void (this.state = { phase: "select-region", context: t4 });
    const i8 = new qoe({ originalSrj: this.params.originalSrj, routes: o10, previousRoutes: t4.currentRoutes, subdivideSegments: true, drcEvaluator: (e60) => (this.result.referenceValidationCount++, this.params.drcEvaluator(e60)) });
    this.state = { phase: "candidate-projection", context: t4, solver: i8 }, this.startChild(i8);
  }
  prepareViaMerge(e54) {
    if (!this.params.connMap)
      return void (this.state = { ...e54, phase: "candidate-physical" });
    const t4 = new gie({ srj: e54.context.srj, routes: e54.candidateRoutes, connMap: this.params.connMap, drcEvaluator: this.params.drcEvaluator });
    this.state = { ...e54, phase: "via-merge", solver: t4 }, this.startChild(t4);
  }
  validateCandidate(e54) {
    const { context: t4, candidateRoutes: n8 } = e54, o10 = ay({ srj: t4.srj, routes: n8 });
    !o10.every(({ key: e60, severity: n10 }) => t4.fixedViolations.has(e60) && n10 <= t4.fixedViolations.get(e60) + 0.00000001) || ly({ srj: t4.srj, previousRoutes: t4.currentRoutes, routes: n8 }).length > 0 ? this.state = { phase: "select-region", context: t4 } : this.state = e54.candidateReference === undefined ? { phase: "candidate-reference", context: t4, candidateRoutes: n8, candidateFixedViolations: o10 } : { phase: "accept-candidate", context: t4, candidateRoutes: n8, candidateFixedViolations: o10, candidateReference: e54.candidateReference };
  }
  referenceCandidate(e54) {
    const t4 = this.params.drcEvaluator({ traces: [], routes: e54.candidateRoutes, hdRoutes: e54.candidateRoutes });
    this.result.referenceValidationCount++, this.state = { ...e54, phase: "accept-candidate", candidateReference: t4 };
  }
  acceptCandidate(e54) {
    const { context: t4, candidateReference: n8 } = e54, o10 = Array.isArray(n8) ? n8 : n8.errors;
    o10.length >= t4.currentErrors.length ? this.state = { phase: "select-region", context: t4 } : (t4.currentRoutes = e54.candidateRoutes, t4.currentErrors = o10, t4.reference = n8, t4.fixedViolations = new Map(e54.candidateFixedViolations.map(({ key: e60, severity: t10 }) => [e60, t10])), this.result.acceptedRegionCount++, this.budget.revisitChangedRegions && (t4.attemptedRegions.length = 0), this.result.finalDrcIssueCount = o10.length, o10.length !== 0 ? this.state = { phase: "select-region", context: t4 } : this.publish(t4, true));
  }
  publishPartial(e54) {
    (({ originalSrj: e60, initialErrors: t4, remainingErrors: n8 }) => {
      if (n8.length >= t4.length)
        return false;
      if (n8.length === 0)
        return true;
      const o10 = new Set(oR(e60).flatMap((e61) => e61.type === "pcb_smtpad" ? [e61.pcb_smtpad_id] : e61.type === "pcb_plated_hole" ? [e61.pcb_plated_hole_id] : [])), i8 = [...t4];
      for (const e61 of n8) {
        if (typeof e61.pcb_trace_id != "string")
          return false;
        const t10 = `overlap_${e61.pcb_trace_id}_`, n10 = e61.type === "pcb_trace_error" && typeof e61.pcb_trace_error_id == "string" && e61.pcb_trace_error_id.startsWith(t10) ? e61.pcb_trace_error_id.slice(t10.length) : undefined, r9 = Goe(e61), s7 = e61.type === "pcb_pad_trace_clearance_error" || r9, a9 = r9 ? e61.pcb_pad_ids.find((e63) => o10.has(e63)) : s7 ? e61.pcb_pad_id : n10;
        if (typeof a9 != "string" || !o10.has(a9))
          return false;
        const c5 = i8.findIndex((t11) => t11.type === e61.type && t11.pcb_trace_id === e61.pcb_trace_id && (r9 ? Goe(t11) && t11.pcb_pad_ids.includes(a9) : s7 ? t11.pcb_pad_id === a9 : t11.pcb_trace_error_id === e61.pcb_trace_error_id));
        if (c5 === -1)
          return false;
        const l5 = i8.splice(c5, 1)[0];
        if (s7 && (typeof e61.actual_clearance != "number" || !Number.isFinite(e61.actual_clearance) || typeof l5.actual_clearance != "number" || !Number.isFinite(l5.actual_clearance) || typeof e61.minimum_clearance != "number" || !Number.isFinite(e61.minimum_clearance) || e61.minimum_clearance !== l5.minimum_clearance || e61.actual_clearance < l5.actual_clearance))
          return false;
      }
      return true;
    })({ originalSrj: this.params.originalSrj, initialErrors: e54.initialErrors, remainingErrors: e54.currentErrors }) ? this.publish(e54, false) : this.state = { phase: "prepare-independent-projection", context: e54 };
  }
  prepareIndependentProjection(e54) {
    const t4 = new qoe({ originalSrj: this.params.originalSrj, routes: this.params.routes, allowPartialRepair: true, drcEvaluator: (e60) => (this.result.referenceValidationCount++, this.params.drcEvaluator(e60)) });
    this.state = { phase: "independent-projection", context: e54, solver: t4 }, this.startChild(t4);
  }
  prepareIndependentSubdivision(e54) {
    const t4 = new qoe({ originalSrj: this.params.originalSrj, routes: e54.independentRoutes, allowPartialRepair: true, subdivideSegments: true, drcEvaluator: (e60) => (this.result.referenceValidationCount++, this.params.drcEvaluator(e60)) });
    this.state = { phase: "independent-subdivision", context: e54.context, solver: t4 }, this.startChild(t4);
  }
  prepareIndependentCoupled(e54) {
    const t4 = new qoe({ originalSrj: this.params.originalSrj, routes: e54.independentRoutes, usePrecisionMargin: true, drcEvaluator: (e60) => (this.result.referenceValidationCount++, this.params.drcEvaluator(e60)) });
    this.state = { phase: "independent-coupled", context: e54.context, solver: t4 }, this.startChild(t4);
  }
  referenceIndependent(e54) {
    const t4 = this.params.drcEvaluator({ traces: [], routes: e54.independentRoutes, hdRoutes: e54.independentRoutes });
    this.result.referenceValidationCount++;
    const n8 = Array.isArray(t4) ? t4 : t4.errors;
    this.result.routes = e54.independentRoutes, this.result.publishedDrcIssueCount = n8.length, this.result.finalDrcIssueCount = n8.length, this.result.repaired = n8.length === 0, this.finish();
  }
  completeChild() {
    const e54 = this.state;
    switch (e54.phase) {
      case "initial-projection": {
        const t4 = e54.solver.getOutput();
        t4 !== e54.context.currentRoutes ? (e54.context.currentRoutes = t4, this.state = { phase: "initial-projection-reference", context: e54.context }) : this.state = { phase: "prepare-regions", context: e54.context };
        break;
      }
      case "negotiate":
        this.completeNegotiation(e54);
        break;
      case "candidate-projection": {
        const t4 = new qoe({ originalSrj: this.params.originalSrj, routes: e54.solver.getOutput(), previousRoutes: e54.context.currentRoutes, usePrecisionMargin: true, drcEvaluator: (e60) => (this.result.referenceValidationCount++, this.params.drcEvaluator(e60)) });
        this.state = { phase: "candidate-margin-projection", context: e54.context, solver: t4 }, this.startChild(t4);
        break;
      }
      case "candidate-margin-projection":
        this.state = { phase: "prepare-via-merge", context: e54.context, candidateRoutes: e54.solver.getOutput() };
        break;
      case "via-merge": {
        const t4 = e54.solver.getResult();
        this.result.referenceValidationCount += t4.referenceValidationCount, this.state = { phase: "candidate-physical", context: e54.context, candidateRoutes: t4.routes, candidateReference: t4.referenceResult };
        break;
      }
      case "independent-projection":
        this.state = { phase: "prepare-independent-subdivision", context: e54.context, independentRoutes: e54.solver.getOutput() };
        break;
      case "independent-subdivision": {
        const t4 = e54.solver.getOutput();
        t4 === this.params.routes ? this.finish() : this.state = { phase: "prepare-independent-coupled", context: e54.context, independentRoutes: t4 };
        break;
      }
      case "independent-coupled":
        this.state = { phase: "independent-reference", context: e54.context, independentRoutes: e54.solver.getOutput() };
        break;
      default:
        throw new Error(`Regional repair child completed during phase ${e54.phase}`);
    }
  }
  _step() {
    const e54 = this.activeSubSolver;
    if (e54)
      return e54.step(), e54.MAX_ITERATIONS > this.reservedChildMaximum && (this.MAX_ITERATIONS += e54.MAX_ITERATIONS - this.reservedChildMaximum, this.reservedChildMaximum = e54.MAX_ITERATIONS), e54.failed ? (this.failed = true, this.error = e54.error) : e54.solved && (this.activeSubSolver = null, this.reservedChildMaximum = 0, this.completeChild()), void this.updateProgress();
    const t4 = this.state;
    switch (t4.phase) {
      case "initialize":
        this.initialize();
        break;
      case "initial-reference":
        this.initialReference(t4.context);
        break;
      case "initial-projection-reference":
        this.initialProjectionReference(t4.context);
        break;
      case "prepare-regions":
        this.prepareRegions(t4.context);
        break;
      case "select-region":
        this.selectRegion(t4.context);
        break;
      case "splice-region":
        this.spliceRegion(t4);
        break;
      case "prepare-via-merge":
        this.prepareViaMerge(t4);
        break;
      case "candidate-physical":
        this.validateCandidate(t4);
        break;
      case "candidate-reference":
        this.referenceCandidate(t4);
        break;
      case "accept-candidate":
        this.acceptCandidate(t4);
        break;
      case "publish-partial":
        this.publishPartial(t4.context);
        break;
      case "prepare-independent-projection":
        this.prepareIndependentProjection(t4.context);
        break;
      case "prepare-independent-subdivision":
        this.prepareIndependentSubdivision(t4);
        break;
      case "prepare-independent-coupled":
        this.prepareIndependentCoupled(t4);
        break;
      case "independent-reference":
        this.referenceIndependent(t4);
        break;
      default:
        throw new Error(`Regional repair has no active child during phase ${t4.phase}`);
    }
    this.updateProgress();
  }
  getResult() {
    if (!this.solved || this.failed)
      throw new Error("Pipeline9 bounded regional repair result requested before completion");
    return this.result;
  }
};
var yie = [0.9, 0.72];
var bie = Array.from({ length: 16 }, (e54, t4) => t4 * Math.PI / 8);
var xie = (e54) => e54.type === "pcb_pad_trace_clearance_error" || e54.type === "pcb_trace_error" && !(Array.isArray(e54.pcb_trace_ids) && e54.pcb_trace_ids.length >= 2);
var vie = (e54) => {
  if (typeof e54.pcb_pad_id == "string")
    return e54.pcb_pad_id;
  if (typeof e54.pcb_trace_error_id == "string") {
    const t10 = e54.pcb_trace_error_id.match(/(pcb_(?:smtpad|plated_hole|hole|keepout)_\d+)$/)?.[1];
    if (t10)
      return t10;
  }
  const t4 = typeof e54.message == "string" ? e54.message : "";
  return t4.match(/(?:pcb_smtpad|pcb_plated_hole|pcb_hole|pcb_keepout)\[#?([^\]"]+)\]/)?.[1];
};
var Iie = (e54, t4) => {
  if (!t4)
    return;
  const n8 = t4.startsWith("pcb_") ? t4 : `pcb_${t4}`;
  return e54.obstacles.find((e60) => e60.obstacleId === n8 || e60.connectedTo[0] === n8);
};
var Sie = ({ srj: e54, pcbPortId: t4, z: n8, portPositionMap: o10 }) => {
  const i8 = Co(n8, e54.layerCount), r9 = o10.get(t4), s7 = e54.obstacles.filter((e60) => e60.layers.includes(i8) && e60.connectedTo.includes(t4));
  return r9 ? s7.reduce((e60, t10) => e60 ? Math.hypot(t10.center.x - r9.x, t10.center.y - r9.y) < Math.hypot(e60.center.x - r9.x, e60.center.y - r9.y) ? t10 : e60 : t10, undefined) : s7[0];
};
var Cie = (e54, t4) => ({ x: e54.x * Math.cos(t4) - e54.y * Math.sin(t4), y: e54.x * Math.sin(t4) + e54.y * Math.cos(t4) });
var Pie = (e54, t4, n8, o10) => {
  if (n8.type !== "pcb_pad_trace_clearance_error" && n8.type !== "pcb_trace_error" || typeof n8.actual_clearance != "number" || n8.actual_clearance < 0)
    return false;
  for (const i8 of [0, e54.route.length - 1]) {
    const r9 = e54.route[i8], s7 = e54.route[i8 === 0 ? 1 : i8 - 1];
    if (!r9?.pcb_port_id || !s7 || r9.z !== s7.z || r9.toNextSegmentType || s7.toNextSegmentType || !t4.layers.includes(Co(r9.z, o10)))
      continue;
    const a9 = ((i8 === 0 ? r9 : s7).traceThickness ?? e54.traceThickness) / 2, c5 = Cie({ x: r9.x - t4.center.x, y: r9.y - t4.center.y }, -(t4.ccwRotationDegrees ?? 0) * Math.PI / 180);
    if ((t4.shape === "circle" ? Math.max(0, Math.hypot(c5.x, c5.y) - t4.width / 2) : Math.hypot(Math.max(0, Math.abs(c5.x) - t4.width / 2), Math.max(0, Math.abs(c5.y) - t4.height / 2))) - a9 <= n8.actual_clearance + 0.000000001)
      return true;
  }
  return false;
};
var Mie = ({ terminalObstacle: e54, conflictingObstacle: t4, traceRadius: n8 }) => {
  const o10 = Math.max(0, e54.width / 2 - n8), i8 = Math.max(0, e54.height / 2 - n8), r9 = (e54.ccwRotationDegrees ?? 0) * Math.PI / 180;
  return yie.flatMap((t10) => bie.map((n10) => {
    const s7 = { x: Math.cos(n10) * o10 * t10, y: Math.sin(n10) * i8 * t10 }, a9 = Cie(s7, r9);
    return { x: e54.center.x + a9.x, y: e54.center.y + a9.y };
  })).sort((e60, n10) => Math.hypot(n10.x - t4.center.x, n10.y - t4.center.y) - Math.hypot(e60.x - t4.center.x, e60.y - t4.center.y)).slice(0, 16);
};
var wie = ({ routes: e54, routeIndex: t4, endpointIndex: n8, point: o10, bounds: i8, collapseAdjacent: r9 }) => {
  const s7 = e54[t4];
  if (!s7 || s7.route.length < 2)
    return;
  const a9 = n8 === 0 ? 0 : s7.route.length - 1, c5 = n8 === 0 ? 1 : a9 - 1, l5 = s7.route[a9], h5 = s7.route[c5];
  if (!l5 || !h5 || l5.z !== h5.z)
    return;
  if (l5.toNextSegmentType || h5.toNextSegmentType)
    return;
  const d9 = s7.traceThickness / 2;
  if (o10.x - d9 < i8.minX || o10.x + d9 > i8.maxX || o10.y - d9 < i8.minY || o10.y + d9 > i8.maxY)
    return;
  const u9 = n8 === 0 ? "start" : "end", p9 = { ...h5, ...o10, terminalApproach: u9 };
  if (r9) {
    const e60 = n8 === 0 ? c5 + 1 : c5 - 1, t10 = s7.route[e60], o11 = s7.vias.some((e61) => e61.x === h5.x && e61.y === h5.y);
    if (!t10 || t10.z !== l5.z || h5.pcb_port_id !== undefined || o11)
      return;
  }
  const m9 = [...e54], g10 = ((e60) => e60.map((e61) => ({ ...e61, route: e61.route.map((e63) => ({ ...e63 })), vias: e61.vias.map((e63) => ({ ...e63 })) })))([s7])[0];
  m9[t4] = g10;
  for (const e60 of g10.route)
    e60.terminalApproach === u9 && delete e60.terminalApproach;
  if (r9)
    g10.route[c5] = p9;
  else {
    const e60 = n8 === 0 ? l5 : h5;
    g10.route.splice(n8 === 0 ? 1 : a9, 0, { x: o10.x, y: o10.y, z: l5.z, terminalApproach: u9, ...e60.traceThickness !== undefined ? { traceThickness: e60.traceThickness } : {} });
  }
  return m9;
};
var Nie = ({ srj: e54, originalSrj: t4, routes: n8, newConnections: o10, syntheticConnectionNames: i8, drcEvaluator: r9, effort: s7 = 1 }) => {
  let a9 = n8, c5 = zoe(r9, a9), l5 = 0, h5 = 0;
  const d9 = c5.length < 20 || n8.length <= 120 ? 256 : Math.max(32, Math.min(256, Math.floor(16384 * Math.max(1, s7) / n8.length))), u9 = ((e60) => {
    const t10 = new Map;
    for (const n10 of e60.connections)
      for (const e61 of n10.pointsToConnect)
        e61.pcb_port_id && t10.set(e61.pcb_port_id, e61);
    return t10;
  })(t4);
  for (let n10 = 0;n10 < 2; n10++) {
    let n11 = false;
    const s9 = Yoe({ routes: a9, newConnections: o10, syntheticConnectionNames: i8 });
    for (const o11 of c5.filter(xie)) {
      if (l5 >= d9)
        break;
      if (typeof o11.pcb_trace_id != "string")
        continue;
      const i9 = s9.get(o11.pcb_trace_id), p9 = Iie(e54, vie(o11));
      if (i9 === undefined || !p9)
        continue;
      const m9 = a9[i9], g10 = Iie(t4, vie(o11));
      if (c5.length === 1 && c5[0] === o11 && g10 && Pie(m9, g10, o11, t4.layerCount))
        continue;
      let f10 = a9, _5 = c5;
      e:
        for (const n12 of [0, -1]) {
          const o12 = n12 === 0 ? m9.route[0] : m9.route.at(-1);
          if (!o12 || typeof o12.pcb_port_id != "string")
            continue;
          const s10 = Sie({ srj: t4, pcbPortId: o12.pcb_port_id, z: o12.z, portPositionMap: u9 });
          if (!s10 || s10 === p9)
            continue;
          const c9 = Math.hypot(p9.width, p9.height) / 2 + Math.hypot(s10.width, s10.height) / 2 + 0.5;
          if (!(Math.hypot(o12.x - p9.center.x, o12.y - p9.center.y) > c9))
            for (const t10 of Mie({ terminalObstacle: s10, conflictingObstacle: p9, traceRadius: m9.traceThickness / 2 }))
              for (const o13 of [false, true]) {
                if (l5 >= d9)
                  break e;
                const s11 = wie({ routes: a9, routeIndex: i9, endpointIndex: n12, point: t10, bounds: e54.bounds, collapseAdjacent: o13 });
                if (!s11)
                  continue;
                l5++;
                const c10 = zoe(r9, s11);
                if ($oe(c10, _5) && (f10 = s11, _5 = c10, _5.length === 0))
                  return { routes: f10, attemptedCandidateCount: l5, acceptedCandidateCount: h5 + 1, remainingErrors: _5 };
              }
        }
      f10 !== a9 && (a9 = f10, c5 = _5, h5++, n11 = true);
    }
    if (!n11 || c5.length === 0)
      break;
  }
  return { routes: a9, attemptedCandidateCount: l5, acceptedCandidateCount: h5, remainingErrors: c5 };
};
var Rie = ["pcb_trace_error_id", "pcb_error_id", "pcb_via_trace_clearance_error_id", "pcb_pad_trace_clearance_error_id"];
var Tie = (e54, t4) => {
  let n8 = e54;
  const o10 = [...t4].sort(([e60], [t10]) => t10.length - e60.length);
  for (const [e60, t10] of o10)
    n8 = n8.replaceAll(e60, t10);
  return n8;
};
var Eie = (e54, t4) => {
  const n8 = String(e54.type ?? e54.error_type ?? "unknown");
  if (n8 === "pcb_via_clearance_error")
    return ((e60, t10) => {
      const n10 = [...typeof e60.pcb_trace_id == "string" ? [e60.pcb_trace_id] : [], ...Array.isArray(e60.pcb_trace_ids) ? e60.pcb_trace_ids.filter((e61) => typeof e61 == "string") : []].map((e61) => Tie(e61, t10)).filter((e61, t11, n11) => n11.indexOf(e61) === t11).sort(), o11 = e60.center && typeof e60.center == "object" ? e60.center : e60.pcb_center && typeof e60.pcb_center == "object" ? e60.pcb_center : undefined, i8 = typeof o11?.x == "number" && typeof o11.y == "number" ? { x: o11.x, y: o11.y } : undefined, r9 = typeof e60.pcb_via_pair_net_relation == "string" ? e60.pcb_via_pair_net_relation : undefined;
      if (n10.length !== 0 && i8 && r9)
        return `pcb_via_clearance_error:${JSON.stringify({ traceIds: n10, center: i8, netRelation: r9 })}`;
    })(e54, t4);
  for (const o11 of Rie) {
    const i8 = e54[o11];
    if (typeof i8 == "string")
      return `${n8}:${Tie(i8, t4)}`;
  }
  const o10 = Object.fromEntries(Object.entries(e54).filter(([e60, t10]) => (e60.endsWith("_id") || e60.endsWith("_ids")) && (typeof t10 == "string" || Array.isArray(t10))).sort(([e60], [t10]) => e60.localeCompare(t10)).map(([e60, n10]) => [e60, typeof n10 == "string" ? Tie(n10, t4) : n10]));
  return `${n8}:${JSON.stringify(o10)}`;
};
var Aie = ({ errors: e54, baselineErrors: t4, originalTraceIdByPreparedTraceId: n8 = new Map }) => {
  const o10 = new Set(t4.filter((e60) => !((e61) => typeof e61.pcb_trace_error_id == "string" && e61.pcb_trace_error_id.startsWith("missing_connection_"))(e60)).map((e60) => Eie(e60, new Map)));
  return o10.delete(undefined), e54.filter((e60) => {
    const t10 = Eie(e60, n8);
    return t10 === undefined || !o10.has(t10);
  });
};
var Oie = 1.5;
var kie = ({ errorsWithCenters: e54, traces: t4, layerCount: n8, defaultViaDiameter: o10, connMap: i8 }) => {
  const r9 = ((e60) => e60.flatMap((e61) => {
    if (e61.type !== "pcb_trace_error" || !Array.isArray(e61.pcb_port_ids) || e61.pcb_port_ids.length < 4)
      return [];
    const t10 = e61.center;
    return t10 && typeof t10 == "object" && "x" in t10 && "y" in t10 && typeof t10.x == "number" && typeof t10.y == "number" ? [{ x: t10.x, y: t10.y }] : [];
  }))(e54), s7 = new Set;
  for (let e60 = 0;e60 < t4.length; e60++) {
    const a9 = t4[e60], c5 = Vne(a9, e60, n8, o10, i8);
    r9.some((e61) => c5.some((t10) => {
      const n10 = t10.route.map((e63) => e63.x), o11 = t10.route.map((e63) => e63.y);
      return Math.min(...n10) <= e61.x + Oie && Math.max(...n10) >= e61.x - Oie && Math.min(...o11) <= e61.y + Oie && Math.max(...o11) >= e61.y - Oie;
    })) && s7.add(a9.pcb_trace_id);
  }
  return s7;
};
var Die = ({ routes: e54, otherHdRoutes: t4, obstacles: n8, colorMap: o10, layerCount: i8, connMap: r9 }) => {
  const s7 = hne([...e54, ...t4], r9), a9 = new PF({ inputHdRoutes: e54, otherHdRoutes: t4, netByConnectionName: s7, obstacles: n8, colorMap: o10, layerCount: i8, connMap: r9 });
  if (a9.solve(), a9.failed)
    throw new Error(`Pipeline9 could not merge movable preloaded vias: ${a9.error ?? "unknown error"}`);
  return a9.getMergedViaHdRoutes() ?? e54;
};
var Lie = ({ errors: e54, circuitJson: t4, newTraceIds: n8 }) => {
  const o10 = new Map(t4.flatMap((e60) => e60.type === "pcb_via" && typeof e60.pcb_via_id == "string" && typeof e60.pcb_trace_id == "string" ? [[e60.pcb_via_id, e60.pcb_trace_id]] : []));
  return e54.map((e60) => {
    const t10 = typeof e60.pcb_trace_id == "string" ? e60.pcb_trace_id : undefined, i8 = Array.isArray(e60.pcb_trace_ids) ? e60.pcb_trace_ids.filter((e61) => typeof e61 == "string") : [], r9 = [...typeof e60.pcb_via_id == "string" ? [e60.pcb_via_id] : [], ...Array.isArray(e60.pcb_via_ids) ? e60.pcb_via_ids.filter((e61) => typeof e61 == "string") : []].filter((e61, t11, n10) => n10.indexOf(e61) === t11);
    if (t10 && typeof e60.pcb_trace_error_id == "string") {
      const s9 = `overlap_${t10}_`, a10 = e60.pcb_trace_error_id.startsWith(s9) ? e60.pcb_trace_error_id.slice(s9.length) : undefined, c9 = a10 !== undefined && (r9.includes(a10) || o10.has(a10) && !i8.includes(a10)), l5 = i8.find((e61) => e61 !== t10 && n8.has(e61)) ?? (a10 && !c9 ? a10 : undefined);
      if (!n8.has(t10) && r9.length === 0 && l5 && n8.has(l5)) {
        const n10 = [l5, t10, ...i8].filter((e61, t11, n11) => n11.indexOf(e61) === t11);
        return { ...e60, pcb_trace_id: l5, pcb_trace_ids: n10, pcb_trace_error_id: `overlap_${l5}_${t10}` };
      }
    }
    const s7 = r9.flatMap((e61) => {
      const t11 = o10.get(e61);
      return t11 ? [t11] : [];
    }).filter((e61, t11, n10) => n10.indexOf(e61) === t11), a9 = s7.length > 0 ? s7 : i8.filter((e61) => e61 !== t10), c5 = a9.find((e61) => n8.has(e61));
    if (c5 && (!t10 || !n8.has(t10))) {
      const n10 = [c5, ...t10 ? [t10] : [], ...i8, ...a9].filter((e61, t11, n11) => n11.indexOf(e61) === t11);
      return { ...e60, pcb_trace_id: c5, pcb_trace_ids: n10, pcb_via_id: r9[0], pcb_via_ids: r9 };
    }
    if (r9.length > 0) {
      const n10 = [...t10 ? [t10] : [], ...i8, ...a9].filter((e61, t11, n11) => n11.indexOf(e61) === t11);
      return { ...e60, pcb_trace_ids: n10, pcb_via_id: r9[0], pcb_via_ids: r9 };
    }
    return e60;
  });
};
var zie = 0.000000001;
var Bie = (e54) => {
  const t4 = new Set, n8 = [];
  for (const o10 of e54)
    for (const e60 of o10.route) {
      if (e60.route_type !== "via")
        continue;
      const i8 = `${e60.x},${e60.y},${e60.from_layer},${e60.to_layer}`;
      t4.has(i8) || (t4.add(i8), n8.push({ type: "pcb_via", pcb_via_id: `via_${n8.length}`, pcb_trace_id: o10.pcb_trace_id }));
    }
  return n8;
};
var Fie = ({ errors: e54, circuitJson: t4, evaluatedTraceIds: n8 }) => {
  const o10 = new Map(t4.flatMap((e60) => e60.type === "pcb_via" && typeof e60.pcb_via_id == "string" && typeof e60.pcb_trace_id == "string" ? [[e60.pcb_via_id, e60.pcb_trace_id]] : []));
  return e54.map((e60) => {
    const t10 = [...typeof e60.pcb_via_id == "string" ? [e60.pcb_via_id] : [], ...Array.isArray(e60.pcb_via_ids) ? e60.pcb_via_ids.filter((e61) => typeof e61 == "string") : []], i8 = typeof e60.pcb_trace_id == "string" ? e60.pcb_trace_id : undefined, r9 = i8 ? `overlap_${i8}_` : undefined, s7 = r9 && typeof e60.pcb_trace_error_id == "string" && e60.pcb_trace_error_id.startsWith(r9) ? e60.pcb_trace_error_id.slice(r9.length) : undefined, a9 = typeof e60.pcb_trace_error_id == "string" ? e60.pcb_trace_error_id.match(/_(via_\d+)$/)?.[1] : undefined, c5 = t10.length !== 0 || !a9 || !o10.has(a9) || s7 && n8.has(s7) ? undefined : a9, l5 = [...t10, ...c5 ? [c5] : []].filter((e61, t11, n10) => n10.indexOf(e61) === t11), h5 = [...typeof e60.pcb_trace_id == "string" ? [e60.pcb_trace_id] : [], ...Array.isArray(e60.pcb_trace_ids) ? e60.pcb_trace_ids.filter((e61) => typeof e61 == "string") : [], ...l5.flatMap((e61) => {
      const t11 = o10.get(e61);
      return t11 ? [t11] : [];
    })].filter((e61, t11, n10) => n10.indexOf(e61) === t11);
    return { ...e60, ...l5.length > 0 ? { pcb_via_id: l5[0], pcb_via_ids: l5 } : {}, ...l5.length > 0 && h5.length > 0 ? { pcb_trace_ids: h5 } : {} };
  });
};
var jie = (e54, t4) => Math.abs(e54.x - t4.x) <= zie && Math.abs(e54.y - t4.y) <= zie && e54.z === t4.z;
var $ie = ({ trace: e54, sectionGroup: t4, syntheticConnectionName: n8, connMap: o10 }) => {
  const i8 = t4.routes;
  if (i8.length === 0)
    throw new Error(`Pipeline9 cannot exactly repair empty preloaded section for trace "${e54.pcb_trace_id}"`);
  const r9 = [];
  for (const t10 of i8) {
    if (r9.length === 0) {
      r9.push(...t10.route);
      continue;
    }
    const n10 = r9.at(-1);
    if (t10.route[0] && jie(n10, t10.route[0]))
      r9.push(...t10.route.slice(1));
    else {
      if (!t10.route.at(-1) || !jie(n10, t10.route.at(-1)))
        throw new Error(`Pipeline9 cannot reconnect preloaded trace "${e54.pcb_trace_id}" for exact repair`);
      r9.push(...t10.route.slice(0, -1).reverse());
    }
  }
  const s7 = t4.routePositionStart === 0, a9 = t4.routePositionEnd === e54.route.length - 1, c5 = s7 ? e54.connectsTo?.[0] : null, l5 = a9 ? e54.connectsTo?.at(-1) : null;
  return c5 && r9[0] && (r9[0] = { ...r9[0], pcb_port_id: c5 }), l5 && r9.at(-1) && (r9[r9.length - 1] = { ...r9.at(-1), pcb_port_id: l5 }), { connectionName: n8, rootConnectionName: o10.getNetConnectedToId(e54.connection_name) ?? e54.connection_name, traceThickness: Math.max(...i8.map((e60) => e60.traceThickness)), viaDiameter: Math.max(...i8.map((e60) => e60.viaDiameter)), route: r9, vias: r9.slice(0, -1).flatMap((e60, t10) => {
    const n10 = r9[t10 + 1];
    return e60.z !== n10.z && (o11 = e60, i9 = n10, Math.abs(o11.x - i9.x) <= zie && Math.abs(o11.y - i9.y) <= zie) ? [{ x: n10.x, y: n10.y }] : [];
    var o11, i9;
  }) };
};
var Yie = ({ trace: e54, traceIndex: t4, layerCount: n8, defaultViaDiameter: o10, connMap: i8 }) => {
  const r9 = e54.route.flatMap((e60, t10) => e60.route_type === "through_obstacle" ? [t10] : []), s7 = new Map, a9 = Vne(e54, t4, n8, o10, i8);
  for (const t10 of a9) {
    const { preloadedRoutePositionStart: n10, preloadedRoutePositionEnd: o11 } = t10;
    if (n10 === undefined || o11 === undefined)
      throw new Error(`Pipeline9 preloaded trace section is missing route positions for "${e54.pcb_trace_id}"`);
    if (e54.route[n10]?.route_type === "through_obstacle")
      continue;
    const i9 = r9.filter((e60) => e60 < n10).length, a10 = s7.get(i9) ?? { routePositionStart: n10, routePositionEnd: o11, routes: [] };
    a10.routePositionStart = Math.min(a10.routePositionStart, n10), a10.routePositionEnd = Math.max(a10.routePositionEnd, o11), a10.routes.push(t10), s7.set(i9, a10);
  }
  return [...s7.values()];
};
var Xie = (e54, t4) => e54.map((e60) => {
  const n8 = Array.isArray(e60.pcb_trace_ids) ? e60.pcb_trace_ids.filter((e61) => typeof e61 == "string") : [], o10 = typeof e60.pcb_trace_id == "string" ? e60.pcb_trace_id : undefined, i8 = o10 ? `overlap_${o10}_` : undefined, r9 = i8 && typeof e60.pcb_trace_error_id == "string" && e60.pcb_trace_error_id.startsWith(i8) ? e60.pcb_trace_error_id.slice(i8.length) : undefined, s7 = [...typeof e60.pcb_via_id == "string" ? [e60.pcb_via_id] : [], ...Array.isArray(e60.pcb_via_ids) ? e60.pcb_via_ids.filter((e61) => typeof e61 == "string") : []], a9 = r9 !== undefined && s7.includes(r9), c5 = [o10, ...n8, a9 ? undefined : r9].filter((e61) => typeof e61 == "string"), l5 = new Map;
  for (const e61 of c5) {
    const n10 = t4.get(e61) ?? e61, o11 = l5.get(n10) ?? new Set;
    o11.add(e61), l5.set(n10, o11);
  }
  const h5 = [...l5].flatMap(([e61, t10]) => t10.size > 1 ? [{ solverTraceId: e61, evaluationTraceIds: [...t10] }] : []), d9 = o10 ? t4.get(o10) ?? o10 : undefined, u9 = n8.map((e61) => t4.get(e61) ?? e61), p9 = r9 ? a9 ? r9 : t4.get(r9) ?? r9 : undefined;
  return d9 !== o10 || u9.some((e61, t10) => e61 !== n8[t10]) || p9 !== r9 ? { ...e60, ...o10 ? { pcb_trace_id: d9 } : {}, ...Array.isArray(e60.pcb_trace_ids) ? { pcb_trace_ids: u9 } : {}, ...d9 && p9 ? { pcb_trace_error_id: `overlap_${d9}_${p9}` } : {}, ...h5.length > 0 ? { __collapsed_trace_participants: h5 } : {} } : e60;
});
var Hie = (e54, t4) => {
  const n8 = e54.hdRoute.route[0], o10 = e54.hdRoute.route.at(-1);
  return { name: e54.syntheticConnectionName, rootConnectionName: e54.hdRoute.rootConnectionName, __netConnectionName: e54.originalTrace.connection_name, nominalTraceWidth: e54.hdRoute.traceThickness, pointsToConnect: [{ x: n8.x, y: n8.y, layer: Co(n8.z, t4), pointId: `${e54.syntheticConnectionName}:start` }, { x: o10.x, y: o10.y, layer: Co(o10.z, t4), pointId: `${e54.syntheticConnectionName}:end` }] };
};
var Vie = ({ originalTrace: e54, repairedSections: t4 }) => {
  const n8 = [];
  let o10 = 0;
  for (const i8 of [...t4].sort((e60, t10) => e60.routePositionStart - t10.routePositionStart)) {
    if (i8.routePositionStart < o10)
      throw new Error(`Pipeline9 found overlapping repaired sections for preloaded trace "${e54.pcb_trace_id}"`);
    n8.push(...e54.route.slice(o10, i8.routePositionStart), ...i8.route), o10 = i8.routePositionEnd + 1;
  }
  return n8.push(...e54.route.slice(o10)), { ...e54, __replaces_pcb_trace_id: e54.pcb_trace_id, route: n8 };
};
var Wie = class extends ni {
  params;
  inputNewHdRoutes;
  inputUpdatedPreloadedTraces;
  movablePreloadedSections;
  fixedPreloadedObstacleRoutes;
  syntheticConnectionNames;
  exactRepairSolver;
  traceContactRepairSolver;
  traceContactGuard;
  traceContactInputHdRoutes;
  exactRepairParams;
  clearanceProjectionSolver;
  drcEvaluator;
  cachedReferenceDrcEvaluator;
  clearancePrecisionDrcEvaluator;
  clearancePrecisionIndexedDrcEvaluator;
  clearanceMarginDrcEvaluator;
  referenceDrcValidationCount = 0;
  referenceDrcFalseNegativeCount = 0;
  indexedDrcEvaluationCount = 0;
  indexedDrcCacheHitCount = 0;
  indexedDrcEvaluationTimeMs = 0;
  indexedDrcCandidateCache = new Map;
  combinedOutput;
  currentPipelineStepIndex = 0;
  regionalB01Params;
  boundedRegionalParams;
  boundedRegionalRepairStartedAt;
  initialBoundedRegionalRepairSolver;
  initialBoundedRegionalRepairStartedAt;
  prioritizeConflictedRoutes;
  pipelineDef = [{ solverName: "clearanceProjectionSolver", createSolver: () => {
    if (!this.exactRepairParams)
      throw new Error("Pipeline9 clearance projection is missing its input");
    return this.clearanceProjectionSolver = new qoe({ originalSrj: this.params.originalSrj, routes: this.exactRepairParams.hdRoutes, drcEvaluator: this.cachedReferenceDrcEvaluator }), this.clearanceProjectionSolver;
  }, onSolved: () => {} }, { solverName: "initialBoundedRegionalRepairSolver", createSolver: () => {
    if (!this.exactRepairParams || !this.cachedReferenceDrcEvaluator)
      throw new Error("Pipeline9 initial regional repair is missing its input");
    return this.initialBoundedRegionalRepairStartedAt = performance.now(), this.initialBoundedRegionalRepairSolver = new _ie({ connMap: this.params.connMap, originalSrj: { ...this.params.originalSrj, connections: [...this.params.originalSrj.connections, ...this.params.newConnections] }, routes: this.clearanceProjectionSolver?.getOutput() ?? this.exactRepairParams.hdRoutes, viaHoleDiameter: this.params.defaultViaHoleDiameter, syntheticConnectionNames: this.syntheticConnectionNames, drcEvaluator: this.cachedReferenceDrcEvaluator, prioritizeConflictedRoutes: this.prioritizeConflictedRoutes, budget: Qoe(this.exactRepairParams.hdRoutes.length, this.stats.initialJointDrcIssueCount, this.params.effort) }), this.initialBoundedRegionalRepairSolver;
  }, onSolved: () => this.finishInitialBoundedRegionalRepair() }, { solverName: "exactRepairSolver", createSolver: () => {
    if (!this.exactRepairParams)
      throw new Error("Pipeline9 exact repair stage is missing its input");
    return this.exactRepairSolver = new LN({ ...this.exactRepairParams, hdRoutes: this.clearanceProjectionSolver?.getOutput() ?? this.exactRepairParams.hdRoutes }), this.exactRepairSolver;
  }, onSolved: () => this.finishExactRepair() }, { solverName: "regionalB01RepairSolver", createSolver: () => {
    if (!this.regionalB01Params)
      throw new Error("Pipeline9 regional B01 stage is missing its input");
    return this.regionalB01RepairSolver = new mie(this.regionalB01Params), this.regionalB01RepairSolver;
  }, onSolved: () => this.finishRegionalB01Repair() }, { solverName: "boundedRegionalRepairSolver", createSolver: () => {
    if (!this.boundedRegionalParams)
      throw new Error("Pipeline9 bounded regional stage is missing its input");
    return this.boundedRegionalRepairStartedAt = performance.now(), this.boundedRegionalRepairSolver = new _ie(this.boundedRegionalParams), this.boundedRegionalRepairSolver;
  }, onSolved: () => this.finishBoundedRegionalRepair() }];
  boundedRegionalRepairSolver;
  regionalB01RepairSolver;
  cacheIndexedDrcResult(e54, t4) {
    if (this.indexedDrcCandidateCache.size >= 64) {
      const e60 = this.indexedDrcCandidateCache.keys().next().value;
      e60 !== undefined && this.indexedDrcCandidateCache.delete(e60);
    }
    this.indexedDrcCandidateCache.set(e54, t4);
  }
  constructor(e54) {
    if (super(), e54.obstacles.some((e60) => e60.isNonPlatedHole)) {
      const t10 = e54.originalSrj.minTraceToHoleEdgeClearance ?? 0.2;
      e54 = { ...e54, srj: { ...e54.srj, minTraceToHoleEdgeClearance: t10 }, originalSrj: { ...e54.originalSrj, minTraceToHoleEdgeClearance: t10 } };
    }
    this.params = e54, this.inputNewHdRoutes = e54.newHdRoutes, this.inputUpdatedPreloadedTraces = e54.updatedPreloadedTraces;
    const t4 = e54.updatedPreloadedTraces.filter((t10) => e54.mutatedPreloadedTraceIds.has(t10.pcb_trace_id)), n8 = Ste({ connections: e54.newConnections, originalConnections: e54.originalSrj.connections, layerCount: e54.layerCount, obstacles: e54.obstacles, defaultViaHoleDiameter: e54.defaultViaHoleDiameter, connMap: e54.connMap }), o10 = n8(e54.newHdRoutes), i8 = new Set(o10.map((e60) => e60.pcb_trace_id)), r9 = (({ originalPreloadedTraces: e60, mutatedPreloadedTraces: t10, newTraces: n10 }) => {
      const o11 = new Set(n10.map((e61) => e61.pcb_trace_id)), i9 = new Map(t10.map((e61) => [e61.pcb_trace_id, e61])), r10 = new Set([...e60.map((e61) => e61.pcb_trace_id), ...o11]), s9 = new Map;
      return { routedTraces: [...e60.filter((e61) => o11.has(e61.pcb_trace_id)).map((e61) => {
        const t11 = i9.get(e61.pcb_trace_id) ?? e61, n11 = `${e61.pcb_trace_id}_preloaded`;
        let o12 = n11, a10 = 2;
        for (;r10.has(o12); )
          o12 = `${n11}_${a10}`, a10 += 1;
        return r10.add(o12), s9.set(o12, e61.pcb_trace_id), { ...t11, pcb_trace_id: o12, __replaces_pcb_trace_id: e61.pcb_trace_id };
      }), ...t10.filter((e61) => !o11.has(e61.pcb_trace_id)), ...n10], originalPreloadedTraceIdByPreparedTraceId: s9 };
    })({ originalPreloadedTraces: e54.originalSrj.traces ?? [], mutatedPreloadedTraces: t4, newTraces: o10 }), s7 = e54.originalSrj.minTraceToPadEdgeClearance ?? e54.originalSrj.defaultObstacleMargin ?? hR, a9 = dR, c5 = vte(e54.originalSrj), l5 = e54.originalSrj.minViaHoleEdgeToViaHoleEdgeClearance ?? dR, h5 = Gte({ includeBoardClearance: true, inputSrj: e54.originalSrj, srjWithPointPairs: e54.srjWithPointPairs, drcOptions: { traceClearance: s7, viaClearance: l5 } }), d9 = h5([]), u9 = new Set((e54.originalSrj.traces ?? []).map((e60) => e60.pcb_trace_id)), p9 = Fie({ errors: d9.errors, circuitJson: d9.circuitJson, evaluatedTraceIds: u9 }), m9 = Fie({ errors: d9.errorsWithCenters, circuitJson: d9.circuitJson, evaluatedTraceIds: u9 }), g10 = h5(r9.routedTraces), f10 = new Set(Wte(e54.originalSrj.traces ?? [], r9.routedTraces).map((e60) => e60.pcb_trace_id)), _5 = Fie({ errors: g10.errors, circuitJson: g10.circuitJson, evaluatedTraceIds: f10 }), y10 = Fie({ errors: g10.errorsWithCenters, circuitJson: g10.circuitJson, evaluatedTraceIds: f10 }), b10 = { ...g10, errors: Aie({ errors: _5, baselineErrors: p9, originalTraceIdByPreparedTraceId: r9.originalPreloadedTraceIdByPreparedTraceId }), errorsWithCenters: Aie({ errors: y10, baselineErrors: m9, originalTraceIdByPreparedTraceId: r9.originalPreloadedTraceIdByPreparedTraceId }) }, x8 = (({ errors: e60, circuitJson: t10 }) => {
      const n10 = new Map(t10.flatMap((e61) => e61.type === "pcb_via" && typeof e61.pcb_via_id == "string" && typeof e61.pcb_trace_id == "string" ? [[e61.pcb_via_id, e61.pcb_trace_id]] : [])), o11 = new Set;
      for (const t11 of e60) {
        const e61 = typeof t11.pcb_trace_id == "string" ? t11.pcb_trace_id : undefined, i9 = [...typeof t11.pcb_via_id == "string" ? [t11.pcb_via_id] : [], ...Array.isArray(t11.pcb_via_ids) ? t11.pcb_via_ids.filter((e63) => typeof e63 == "string") : []];
        if (typeof t11.pcb_trace_id == "string" && o11.add(t11.pcb_trace_id), Array.isArray(t11.pcb_trace_ids))
          for (const e63 of t11.pcb_trace_ids)
            typeof e63 == "string" && o11.add(e63);
        if (typeof t11.pcb_via_id == "string") {
          const e63 = n10.get(t11.pcb_via_id);
          e63 && o11.add(e63);
        }
        if (Array.isArray(t11.pcb_via_ids))
          for (const e63 of t11.pcb_via_ids) {
            if (typeof e63 != "string")
              continue;
            const t12 = n10.get(e63);
            t12 && o11.add(t12);
          }
        const r10 = e61 ? `overlap_${e61}_` : undefined;
        if (r10 && typeof t11.pcb_trace_error_id == "string" && t11.pcb_trace_error_id.startsWith(r10)) {
          const e63 = t11.pcb_trace_error_id.slice(r10.length);
          i9.includes(e63) || o11.add(e63);
        }
      }
      return o11;
    })({ errors: b10.errors, circuitJson: b10.circuitJson }), v10 = new Map(e54.updatedPreloadedTraces.map((e60) => [e60.pcb_trace_id, e60])), I6 = new Set;
    for (const e60 of x8) {
      const t10 = r9.originalPreloadedTraceIdByPreparedTraceId.get(e60);
      t10 && v10.has(t10) ? I6.add(t10) : !i8.has(e60) && v10.has(e60) && I6.add(e60);
    }
    for (const t10 of kie({ errorsWithCenters: b10.errorsWithCenters, traces: e54.updatedPreloadedTraces, layerCount: e54.layerCount, defaultViaDiameter: e54.defaultViaDiameter, connMap: e54.connMap }))
      I6.add(t10);
    this.movablePreloadedSections = [];
    for (const t10 of I6) {
      const n10 = v10.get(t10);
      if (!n10)
        throw new Error(`Pipeline9 cannot find preloaded trace "${t10}" selected for exact repair`);
      const o11 = e54.updatedPreloadedTraces.findIndex((e60) => e60.pcb_trace_id === t10), i9 = Yie({ trace: n10, traceIndex: o11, layerCount: e54.layerCount, defaultViaDiameter: e54.defaultViaDiameter, connMap: e54.connMap });
      for (const [t11, o12] of i9.entries()) {
        const i10 = `pipeline9_preloaded_drc_${this.movablePreloadedSections.length}`;
        this.movablePreloadedSections.push({ originalTrace: n10, originalRoutePositionStart: o12.routePositionStart, originalRoutePositionEnd: o12.routePositionEnd, syntheticConnectionName: i10, evaluationTraceId: `${n10.pcb_trace_id}__pipeline9_section_${t11}`, hdRoute: $ie({ trace: n10, sectionGroup: o12, syntheticConnectionName: i10, connMap: e54.connMap }) });
      }
    }
    this.syntheticConnectionNames = new Set(this.movablePreloadedSections.map((e60) => e60.syntheticConnectionName));
    const S6 = new Set(this.movablePreloadedSections.map((e60) => e60.originalTrace.pcb_trace_id));
    this.fixedPreloadedObstacleRoutes = e54.updatedPreloadedTraces.flatMap((t10, n10) => {
      const o11 = Vne(t10, n10, e54.layerCount, e54.defaultViaDiameter, e54.connMap);
      return S6.has(t10.pcb_trace_id) ? o11.filter((e60) => {
        const n11 = e60.preloadedRoutePositionStart;
        return n11 !== undefined && t10.route[n11]?.route_type === "through_obstacle";
      }) : o11;
    });
    const C = new Map;
    for (const [e60, t10] of this.movablePreloadedSections.entries()) {
      const n10 = t10.originalTrace.pcb_trace_id, o11 = C.get(n10) ?? [];
      o11.push(e60), C.set(n10, o11);
    }
    for (const t10 of (({ errors: e60, circuitJson: t11, originalTraceIdByPreparedTraceId: n10 }) => {
      const o11 = new Map(t11.flatMap((e61) => e61.type === "pcb_via" && typeof e61.pcb_via_id == "string" && typeof e61.pcb_trace_id == "string" ? [[e61.pcb_via_id, e61.pcb_trace_id]] : []));
      return e60.flatMap((e61) => {
        if (e61.type !== "pcb_via_clearance_error" || !Array.isArray(e61.pcb_via_ids) || typeof e61.actual_clearance != "number" || e61.actual_clearance >= 0)
          return [];
        const t12 = e61.pcb_via_ids.flatMap((e63) => {
          if (typeof e63 != "string")
            return [];
          const t13 = o11.get(e63);
          return t13 ? [n10.get(t13) ?? t13] : [];
        }).filter((e63, t13, n11) => n11.indexOf(e63) === t13);
        return t12.length > 0 ? [t12] : [];
      });
    })({ errors: b10.errors, circuitJson: b10.circuitJson, originalTraceIdByPreparedTraceId: r9.originalPreloadedTraceIdByPreparedTraceId })) {
      const n10 = t10.flatMap((e60) => C.get(e60) ?? []).filter((e60, t11, n11) => n11.indexOf(e60) === t11);
      if (n10.length === 0)
        continue;
      const o11 = new Set(n10), i9 = Die({ routes: n10.map((e60) => this.movablePreloadedSections[e60].hdRoute), otherHdRoutes: [...e54.newHdRoutes, ...this.fixedPreloadedObstacleRoutes, ...this.movablePreloadedSections.flatMap((e60, t11) => o11.has(t11) ? [] : [e60.hdRoute])], obstacles: e54.obstacles, colorMap: e54.colorMap, layerCount: e54.layerCount, connMap: e54.connMap });
      for (let e60 = 0;e60 < n10.length; e60++)
        this.movablePreloadedSections[n10[e60]].hdRoute = i9[e60];
    }
    const P = e54.newHdRoutes.length + this.movablePreloadedSections.length, M = b10.errors.length >= 20 && P > 120 ? Math.min(1, 120 * Math.max(1, e54.effort) / P) : 1, w = b10.errors.length >= 200 ? M ** 2 : M, N = Math.max(b10.errors.length >= 200 ? 2 : 8, Math.floor(32 * w)), R10 = Math.max(b10.errors.length >= 200 ? 1 : 4, Math.floor(12 * w)), T2 = b10.errors.filter((e60) => e60.type === "pcb_trace_error").length;
    this.prioritizeConflictedRoutes = T2 > b10.errors.length / 2, this.stats = { initialJointDrcIssueCount: b10.errors.length, baselineJointDrcIssueCount: d9.errors.length, initialJointDrcIssueCountByType: b10.errors.reduce((e60, t10) => {
      const n10 = String(t10.type ?? t10.error_type ?? "unknown");
      return e60[n10] = (e60[n10] ?? 0) + 1, e60;
    }, {}), movablePreloadedTraceCount: S6.size, movablePreloadedSectionCount: this.movablePreloadedSections.length, exactRepairConfiguredMaxIterations: N, exactRepairConfiguredViaInPadMaxIterations: N, exactRepairConfiguredBroadMaxIterations: R10 }, this.traceContactInputHdRoutes = structuredClone([...e54.originalNewHdRoutes ?? e54.newHdRoutes, ...this.movablePreloadedSections.map((e60) => e60.hdRoute)]), this.traceContactGuard = new RN({ srj: e54.srjWithPointPairs, inputRoutes: this.traceContactInputHdRoutes, connMap: e54.connMap });
    const E10 = [...e54.newHdRoutes, ...this.movablePreloadedSections.map((e60) => e60.hdRoute)];
    if (b10.errors.length === 0 && this.traceContactGuard.getNewContactPairs(E10).length === 0)
      return void (this.solved = true);
    const A7 = new Set(this.movablePreloadedSections.map((e60) => e60.originalTrace.pcb_trace_id)), O10 = t4.filter((e60) => !A7.has(e60.pcb_trace_id)), k6 = new Map(this.movablePreloadedSections.map((t10) => [t10.syntheticConnectionName, Hie(t10, e54.layerCount)])), { traces: D9, ...L10 } = e54.srjWithPointPairs, z10 = { ...L10, connections: [...e54.srjWithPointPairs.connections, ...k6.values()] }, B5 = new mb({ ...z10, obstacles: e54.originalSrj.obstacles, minTraceWidth: e54.originalSrj.minTraceWidth, minViaDiameter: e54.originalSrj.minViaDiameter ?? e54.defaultViaDiameter }, { connMap: e54.connMap, traceClearance: s7, viaClearance: a9, viaToPadClearance: c5, includeTraceViaOwnerMetadata: true, spatialCellSize: Math.max(e54.defaultViaDiameter, e54.originalSrj.minTraceWidth) + Math.max(s7, a9) }), F10 = B5.evaluate(e54.originalSrj.traces ?? []), j10 = Bie(e54.originalSrj.traces ?? []), $10 = { ...F10, errors: Fie({ errors: F10.errors, circuitJson: j10, evaluatedTraceIds: u9 }), errorsWithCenters: Fie({ errors: F10.errorsWithCenters, circuitJson: j10, evaluatedTraceIds: u9 }) }, Y10 = new Map, X = (t10) => {
      const o11 = t10.filter((e60) => !this.syntheticConnectionNames.has(e60.connectionName)), i9 = n8(o11), r10 = cne(i9, e54.originalSrj.traces ?? []), s9 = new Set, a10 = new Map, c9 = this.movablePreloadedSections.map((n10) => {
        const o12 = t10.find((e60) => e60.connectionName === n10.syntheticConnectionName);
        if (!o12)
          throw new Error(`Pipeline9 joint DRC repair lost preloaded section "${n10.syntheticConnectionName}"`);
        const i10 = n10.originalTrace.pcb_trace_id;
        a10.set(n10.evaluationTraceId, i10);
        const r11 = !s9.has(i10);
        return s9.add(i10), { ...n10.originalTrace, pcb_trace_id: n10.evaluationTraceId, ...r11 ? { __replaces_pcb_trace_id: i10 } : { __replaces_pcb_trace_id: undefined }, route: Ro(o12, e54.layerCount, { defaultViaHoleDiameter: e54.defaultViaHoleDiameter, obstacles: e54.obstacles, connMap: e54.connMap }) };
      }), l10 = new Map;
      for (let e60 = 0;e60 < i9.length; e60++)
        l10.set(r10[e60].pcb_trace_id, i9[e60].pcb_trace_id);
      for (const e60 of this.movablePreloadedSections)
        l10.set(e60.evaluationTraceId, `${e60.syntheticConnectionName}_0`);
      const h9 = new Set(l10.values()), d10 = [...O10, ...c9, ...r10];
      return { evaluatedTraces: Wte(e54.originalSrj.traces ?? [], d10), movableTraceIds: h9, originalTraceIdByEvaluationTraceId: a10, routedTraces: d10, solverTraceIdByEvaluationTraceId: l10 };
    }, H10 = ({ errors: e60, errorsWithCenters: t10, circuitJson: n10, movableTraceIds: o11, solverTraceIdByEvaluationTraceId: i9 }) => {
      const r10 = n10.map((e61) => {
        if (!("pcb_trace_id" in e61) || typeof e61.pcb_trace_id != "string")
          return e61;
        const t11 = i9.get(e61.pcb_trace_id);
        return t11 ? { ...e61, pcb_trace_id: t11 } : e61;
      });
      return { errors: Lie({ errors: Xie(e60, i9), circuitJson: r10, newTraceIds: o11 }), errorsWithCenters: Lie({ errors: Xie(t10, i9), circuitJson: r10, newTraceIds: o11 }) };
    }, V10 = { source: ei(e54.originalSrj === e54.srjWithPointPairs ? e54.originalSrj : { ...e54.originalSrj, connections: [...e54.srjWithPointPairs.connections, ...e54.originalSrj.connections] }), route: ei(e54.srjWithPointPairs) }, W4 = Gte({ includeBoardClearance: true, connectivityMaps: V10, inputSrj: e54.originalSrj, srjWithPointPairs: e54.srjWithPointPairs, drcOptions: { traceClearance: s7, viaClearance: l5 } }), G10 = ({ routes: e60, hdRoutes: t10 }, n10 = true) => {
      const o11 = e60 ?? t10;
      if (!o11)
        throw new Error("Pipeline9 reference DRC repair requires HD routes");
      const i9 = X(o11), r10 = W4(i9.routedTraces, { includeTraceContinuity: n10 }), s9 = new Set(i9.evaluatedTraces.map((e61) => e61.pcb_trace_id)), a10 = Fie({ errors: r10.errors, circuitJson: r10.circuitJson, evaluatedTraceIds: s9 }), c9 = Fie({ errors: r10.errorsWithCenters, circuitJson: r10.circuitJson, evaluatedTraceIds: s9 }), l10 = Aie({ errors: a10, baselineErrors: p9, originalTraceIdByPreparedTraceId: i9.originalTraceIdByEvaluationTraceId }), h9 = Aie({ errors: c9, baselineErrors: m9, originalTraceIdByPreparedTraceId: i9.originalTraceIdByEvaluationTraceId });
      return H10({ errors: l10, errorsWithCenters: h9, circuitJson: r10.circuitJson, movableTraceIds: i9.movableTraceIds, solverTraceIdByEvaluationTraceId: i9.solverTraceIdByEvaluationTraceId });
    }, U10 = ({ routes: e60, hdRoutes: t10 }) => {
      const n10 = e60 ?? t10;
      if (!n10)
        throw new Error("Pipeline9 cached reference DRC requires HD routes");
      const o11 = JSON.stringify(n10), i9 = Y10.get(o11);
      if (i9 !== undefined)
        return i9;
      this.referenceDrcValidationCount += 1;
      const r10 = G10({ traces: [], routes: n10, hdRoutes: n10 });
      if (Y10.size >= 2) {
        const e61 = Y10.keys().next().value;
        e61 !== undefined && Y10.delete(e61);
      }
      return Y10.set(o11, r10), r10;
    };
    U10.inputMode = "routes-only", this.cachedReferenceDrcEvaluator = U10, this.clearancePrecisionDrcEvaluator = ({ routes: e60, hdRoutes: t10 }) => G10({ traces: [], routes: e60, hdRoutes: t10 }, false);
    const Z6 = (t10) => {
      const n10 = X(t10);
      return sR(e54.srjWithPointPairs, n10.routedTraces, { minTraceWidth: e54.originalSrj.minTraceWidth, minViaDiameter: e54.originalSrj.minViaDiameter, originalSrj: e54.originalSrj, includeOriginalConnections: true, connectivityMaps: V10 });
    };
    let q10;
    this.clearanceMarginDrcEvaluator = (e60, t10, n10) => (q10?.routes !== n10 && (q10 = { routes: n10, circuitJson: Z6(n10) }), (({ circuitJson: e61, originalCircuitJson: t11, targets: n11 }) => {
      const o11 = new Map(e61.filter((e63) => e63.type === "pcb_trace").map((e63) => [e63.pcb_trace_id, e63])), i9 = new Map(t11.filter((e63) => e63.type === "pcb_trace").map((e63) => [e63.pcb_trace_id, e63])), r10 = e61.filter((e63) => e63.type === "pcb_via"), s9 = new Map;
      for (const t12 of e61)
        t12.type === "pcb_via" ? s9.set(t12.pcb_via_id, t12) : t12.type === "pcb_smtpad" ? s9.set(t12.pcb_smtpad_id, t12) : t12.type === "pcb_plated_hole" && s9.set(t12.pcb_plated_hole_id, t12);
      const a10 = [];
      for (const e63 of n11) {
        const n12 = e63.type === "pcb_via_trace_clearance_error", c9 = n12 ? e63.pcb_via_id : e63.pcb_pad_id;
        if (!n12 && e63.type !== "pcb_pad_trace_clearance_error" || typeof e63.pcb_trace_id != "string" || typeof c9 != "string" || typeof e63.minimum_clearance != "number" || !Number.isFinite(e63.minimum_clearance) || e63.minimum_clearance <= 0)
          throw new Error("Pipeline9 clearance margin requires a valid target pair");
        const l10 = i9.get(e63.pcb_trace_id), h9 = t11.find((e64) => n12 ? e64.type === "pcb_via" && e64.pcb_via_id === c9 : e64.type === "pcb_smtpad" && e64.pcb_smtpad_id === c9 || e64.type === "pcb_plated_hole" && e64.pcb_plated_hole_id === c9);
        if (!l10 || !h9)
          throw new Error(`Pipeline9 clearance margin has no original target ${c9}/${e63.pcb_trace_id}`);
        const d10 = o11.get(e63.pcb_trace_id);
        let u10 = s9.get(c9);
        if (n12) {
          if (h9.type !== "pcb_via" || typeof h9.pcb_trace_id != "string")
            throw new Error("Pipeline9 clearance margin requires the original via owner");
          const e64 = i9.get(h9.pcb_trace_id);
          if (!e64)
            throw new Error("Pipeline9 clearance margin lost the original via owner");
          const t12 = e64.route.filter((e65) => e65.route_type === "via"), n13 = t12.map((e65, t13) => ({ segment: e65, index: t13 })).filter(({ segment: e65 }) => e65.x === h9.x && e65.y === h9.y && h9.layers.includes(e65.from_layer) && h9.layers.includes(e65.to_layer)).filter(({ segment: e65 }, t13, n14) => n14.findIndex((t14) => t14.segment.from_layer === e65.from_layer && t14.segment.to_layer === e65.to_layer) === t13);
          if (n13.length === 0)
            throw new Error("Pipeline9 clearance margin lost the original via transition");
          if (n13.length !== 1)
            return { status: "unsupported-identity" };
          const s10 = n13[0].index, a11 = o11.get(h9.pcb_trace_id), c10 = a11?.route.filter((e65) => e65.route_type === "via");
          if (!c10 || c10.length !== t12.length || c10.some((e65, n14) => e65.from_layer !== t12[n14].from_layer || e65.to_layer !== t12[n14].to_layer))
            return { status: "unsupported-identity" };
          const l11 = c10[s10];
          u10 = r10.filter((e65) => e65.x === l11.x && e65.y === l11.y && e65.layers.join() === h9.layers.join()).reduce((e65, t13) => !e65 || t13.outer_diameter > e65.outer_diameter ? t13 : e65, undefined);
        }
        if (!(d10 && u10 && ("x" in u10) && ("y" in u10)))
          return { status: "unsupported-identity" };
        const p10 = [d10, u10], m10 = dz([u10], { traceClearance: e63.minimum_clearance + 1 })(p10, Qo(p10)), g11 = n12 ? m10.viaErrors : m10.padErrors, f11 = e63.minimum_clearance + Xoe;
        for (const t12 of g11) {
          const n13 = t12.actual_clearance;
          if (typeof n13 != "number" || !Number.isFinite(n13))
            throw new Error("Pipeline9 clearance margin requires a finite measurement");
          n13 >= f11 || a10.push({ ...e63, ...u10.type === "pcb_via" ? { pcb_via_id: u10.pcb_via_id, pcb_via_ids: [u10.pcb_via_id] } : {}, actual_clearance: n13, minimum_clearance: f11, center: { x: u10.x, y: u10.y } });
        }
      }
      return { status: "measured", errors: a10 };
    })({ circuitJson: Z6(e60), originalCircuitJson: q10.circuitJson, targets: t10 })), this.clearancePrecisionIndexedDrcEvaluator = ({ routes: e60, hdRoutes: t10 }) => {
      const n10 = e60 ?? t10;
      if (!n10)
        throw new Error("Pipeline9 clearance ranking requires HD routes");
      const o11 = X(n10);
      return B5.evaluate(o11.evaluatedTraces);
    };
    const J10 = ({ routes: e60, hdRoutes: t10 }) => {
      const n10 = e60 ?? t10;
      if (!n10)
        throw new Error("Pipeline9 joint DRC repair requires HD routes");
      const o11 = JSON.stringify(n10), i9 = this.indexedDrcCandidateCache.get(o11);
      if (i9 !== undefined)
        return this.indexedDrcCacheHitCount += 1, i9;
      const r10 = performance.now();
      this.indexedDrcEvaluationCount += 1;
      const s9 = X(n10), a10 = B5.evaluate(s9.evaluatedTraces), c9 = Bie(s9.evaluatedTraces), l10 = new Set(s9.evaluatedTraces.map((e61) => e61.pcb_trace_id)), h9 = Fie({ errors: a10.errors, circuitJson: c9, evaluatedTraceIds: l10 }), d10 = Fie({ errors: a10.errorsWithCenters, circuitJson: c9, evaluatedTraceIds: l10 }), u10 = Aie({ errors: h9, baselineErrors: $10.errors, originalTraceIdByPreparedTraceId: s9.originalTraceIdByEvaluationTraceId }), p10 = Aie({ errors: d10, baselineErrors: $10.errorsWithCenters, originalTraceIdByPreparedTraceId: s9.originalTraceIdByEvaluationTraceId });
      if (u10.length === 0) {
        const e61 = this.referenceDrcValidationCount, t11 = U10({ traces: [], routes: n10, hdRoutes: n10 }), i10 = Array.isArray(t11) ? t11 : t11.errors;
        return this.referenceDrcValidationCount > e61 && i10.length > 0 && (this.referenceDrcFalseNegativeCount += 1), this.indexedDrcEvaluationTimeMs += performance.now() - r10, this.cacheIndexedDrcResult(o11, t11), t11;
      }
      const m10 = H10({ errors: u10, errorsWithCenters: p10, circuitJson: c9, movableTraceIds: s9.movableTraceIds, solverTraceIdByEvaluationTraceId: s9.solverTraceIdByEvaluationTraceId });
      return this.indexedDrcEvaluationTimeMs += performance.now() - r10, this.cacheIndexedDrcResult(o11, m10), m10;
    };
    if (J10.inputMode = "routes-only", this.drcEvaluator = J10, this.exactRepairParams = { srj: z10, hdRoutes: [...e54.newHdRoutes, ...this.movablePreloadedSections.map((e60) => e60.hdRoute)], connMap: e54.connMap, effort: e54.effort, viaHoleDiameter: e54.defaultViaHoleDiameter, drcEvaluator: J10, viaInPadDrcEvaluator: J10, maxIterations: N, enableBroadFallback: false, enableLargeBoardBroadFallback: false, enableTargetedErrorSweep: true, enableTraceViaOwnerTargeting: true, enablePostSolveClearanceRelaxation: false, deferTraceContactGuard: true, prioritizeMultipleTraceContactRepair: true, enableSafeTraceLayerMoves: true, enableViaInPadLayerMoves: e54.originalSrj.allowViaInPad ?? false, viaInPadMaxIterations: N, broadMaxIterations: R10, broadPassMultiplier: 3 * w }, b10.errors.length === 0)
      return this.combinedOutput = E10, void this.finishWithTraceContactCheck();
    (e54.updatedPreloadedTraces.length > 0 || (e54.originalSrj.traces?.length ?? 0) > 0) && this.pipelineDef.splice(1, 1), (e54.updatedPreloadedTraces.length > 0 || !e54.obstacles.some((e60) => e60.isNonPlatedHole)) && (this.currentPipelineStepIndex = 1), this.activeSubSolver = this.pipelineDef[this.currentPipelineStepIndex].createSolver(), this.MAX_ITERATIONS = this.activeSubSolver.MAX_ITERATIONS + 1;
  }
  getSolverName() {
    return "Pipeline9JointDrcRepairSolver";
  }
  _step() {
    if (this.traceContactRepairSolver) {
      const e60 = this.traceContactRepairSolver;
      if (e60.step(), e60.failed)
        throw new Error(`Pipeline9 trace contact repair failed: ${e60.error}`);
      if (!e60.solved)
        return;
      if (this.combinedOutput = e60.getOutput(), this.traceContactGuard.getNewContactPairs(this.combinedOutput).length > 0)
        throw new Error("Pipeline9 trace contact repair published a new short");
      return this.stats = { ...this.stats, ...e60.stats }, this.activeSubSolver = null, void (this.solved = true);
    }
    const e54 = this.pipelineDef[this.currentPipelineStepIndex];
    if (e54) {
      if (this.activeSubSolver) {
        const t4 = this.activeSubSolver;
        if (t4.step(), this.MAX_ITERATIONS = Math.max(this.MAX_ITERATIONS, this.iterations + t4.MAX_ITERATIONS - t4.iterations + 2), t4.failed)
          this.failed = true, this.error = t4.error, this.activeSubSolver = null;
        else if (t4.solved) {
          if (e54.onSolved(), this.traceContactRepairSolver)
            return void (this.activeSubSolver = this.traceContactRepairSolver);
          this.activeSubSolver = null, this.currentPipelineStepIndex++;
        }
        return;
      }
      this.activeSubSolver = e54.createSolver(), this.MAX_ITERATIONS = Math.max(this.MAX_ITERATIONS, this.iterations + this.activeSubSolver.MAX_ITERATIONS + 2);
    } else
      this.solved = true;
  }
  computeProgress() {
    return this.solved ? 1 : Math.max(this.progress, (this.currentPipelineStepIndex + (this.activeSubSolver?.progress ?? 0)) / this.pipelineDef.length);
  }
  getCurrentPhase() {
    return this.pipelineDef[this.currentPipelineStepIndex]?.solverName ?? "none";
  }
  finishInitialBoundedRegionalRepair() {
    if (!this.initialBoundedRegionalRepairSolver?.solved || this.initialBoundedRegionalRepairStartedAt === undefined || !this.cachedReferenceDrcEvaluator)
      throw new Error("Pipeline9 initial regional repair is not complete");
    const e54 = this.initialBoundedRegionalRepairSolver.getResult();
    if (this.stats = { ...this.stats, initialBoundedRegionalRepairAccepted: false, initialBoundedRegionalRepairAttemptedRegionCount: e54.attemptedRegionCount, initialBoundedRegionalRepairAcceptedRegionCount: e54.acceptedRegionCount, initialBoundedRegionalRepairCandidateAttemptCount: e54.candidateAttemptCount, initialBoundedRegionalRepairPathSearchNodeCount: e54.pathSearchNodeCount, initialBoundedRegionalRepairReferenceValidationCount: e54.referenceValidationCount, initialBoundedRegionalRepairPublishedDrcIssueCount: e54.publishedDrcIssueCount, initialBoundedRegionalRepairTimeMs: performance.now() - this.initialBoundedRegionalRepairStartedAt }, e54.publishedDrcIssueCount !== 0)
      return;
    const t4 = this.cachedReferenceDrcEvaluator({ traces: [], routes: e54.routes, hdRoutes: e54.routes });
    if ((Array.isArray(t4) ? t4 : t4.errors).length !== 0)
      throw new Error("Pipeline9 initial regional repair lost its zero-DRC validation");
    this.combinedOutput = e54.routes, this.stats = { ...this.stats, finalDrcIssueCount: 0, initialBoundedRegionalRepairAccepted: true, boundedRegionalRepairMaxRegions: this.initialBoundedRegionalRepairSolver.budget.maxRegions, boundedRegionalRepairMaxCandidateAttempts: this.initialBoundedRegionalRepairSolver.budget.maxCandidateAttempts, boundedRegionalRepairMaxPathSearchNodes: this.initialBoundedRegionalRepairSolver.budget.maxPathSearchNodes, boundedRegionalRepairAttemptedRegionCount: e54.attemptedRegionCount, boundedRegionalRepairAcceptedRegionCount: e54.acceptedRegionCount, boundedRegionalRepairCandidateAttemptCount: e54.candidateAttemptCount, boundedRegionalRepairPathSearchNodeCount: e54.pathSearchNodeCount, boundedRegionalRepairReferenceValidationCount: e54.referenceValidationCount, boundedRegionalRepairRepaired: e54.repaired, boundedRegionalRepairPublishedDrcIssueCount: e54.publishedDrcIssueCount, initialBoundedRegionalRepairAddedViaCount: Math.max(0, e54.routes.reduce((e60, t10) => e60 + t10.vias.length, 0) - this.inputNewHdRoutes.reduce((e60, t10) => e60 + t10.vias.length, 0)), terminalEscapeCandidateCount: 0, terminalEscapeAcceptedCount: 0, regionalB01RepairAttempted: false, regionalB01RepairCandidateSearchCount: 0, regionalB01RepairCandidateSearchBudget: 0, clearancePrecisionCandidateCount: 0, clearancePrecisionCandidateValidationCount: 0, clearancePrecisionReferenceValidationCount: 0, clearancePrecisionRepaired: false, referenceDrcValidationCount: this.referenceDrcValidationCount, referenceDrcFalseNegativeCount: this.referenceDrcFalseNegativeCount, indexedDrcEvaluationCount: this.indexedDrcEvaluationCount, indexedDrcCacheHitCount: this.indexedDrcCacheHitCount, indexedDrcEvaluationTimeMs: this.indexedDrcEvaluationTimeMs, indexedDrcCandidateCacheSize: this.indexedDrcCandidateCache.size, indexedDrcCandidateCacheCapacity: 64 }, this.finishWithTraceContactCheck();
  }
  finishExactRepair() {
    if (!this.exactRepairSolver)
      throw new Error("Pipeline9 post-exact repair requires the exact solver");
    let e54 = this.exactRepairSolver.getOutput();
    const t4 = this.exactRepairSolver.stats.finalDrcIssueCount, n8 = typeof t4 == "number" && Number.isFinite(t4) && t4 >= 0 ? t4 : undefined;
    let o10, i8 = 0, r9 = 0, s7 = 0, a9 = false;
    const c5 = this.cachedReferenceDrcEvaluator({ traces: [], routes: e54, hdRoutes: e54 }), l5 = Array.isArray(c5) ? c5 : c5.errors;
    if (o10 = l5.length, l5.length > 0) {
      const t10 = (({ srj: e60, routes: t11, newConnections: n10, syntheticConnectionNames: o11, connMap: i9, indexedDrcEvaluator: r10, candidateDrcEvaluator: s9, marginDrcEvaluator: a10, drcEvaluator: c9, initialErrors: l10, initialErrorsWithCenters: h9 = l10 }) => {
        const d10 = { routes: t11, attemptedCandidateCount: 0, candidateValidationCount: 0, referenceValidationCount: 0, repaired: false };
        if ((e60.traces?.length ?? 0) > 0 || o11.size > 0)
          return d10;
        if (l10.length === 0)
          return d10;
        const u9 = Yoe({ routes: t11, newConnections: n10, syntheticConnectionNames: o11 }), p9 = new Map;
        for (const t12 of e60.obstacles)
          for (const e61 of [t12.obstacleId, t12.circuitJsonMetadata?.pcb_smtpad_id, t12.circuitJsonMetadata?.pcb_plated_hole_id, t12.connectedTo[0]])
            typeof e61 == "string" && p9.set(e61, t12.center);
        const m9 = Woe({ errors: l10, errorsWithCenters: h9, routeIndexByTraceId: u9, padPositionById: p9 });
        if (!m9)
          return d10;
        let g10 = m9;
        const f10 = m9.errors, _5 = m9.errors.map((e61) => ({ ...e61, minimum_clearance: e61.minimum_clearance + Xoe })), y10 = Voe(_5);
        if (y10 === undefined)
          return d10;
        let b10 = { errors: _5, deficit: y10 }, x8 = t11, v10 = 0, I6 = 0, S6 = 0;
        for (let n11 = 0;n11 < 8; n11++) {
          const n12 = new Map;
          for (const e61 of [...b10.errors, ...g10.errors]) {
            const t12 = JSON.stringify([e61.type, e61.pcb_trace_id, e61.pcb_pad_id, e61.pcb_via_id]);
            n12.set(t12, e61);
          }
          const o12 = [...n12.values()];
          let l11;
          for (const t12 of Hoe) {
            const n13 = AP(x8);
            if (!Ww(e60, n13, o12, u9, t12, i9, true, true, true, false))
              continue;
            const s10 = sw(n13);
            v10++;
            const a11 = r10({ traces: [], routes: s10, hdRoutes: s10 }), c10 = Voe(Array.isArray(a11) ? a11 : a11.errors);
            c10 !== undefined && (!l11 || c10 < l11.deficit) && (l11 = { routes: s10, deficit: c10 });
          }
          if (!l11)
            break;
          I6++;
          const h10 = s9({ traces: [], routes: l11.routes, hdRoutes: l11.routes }), d11 = Array.isArray(h10) ? h10 : h10.errors, m10 = Woe({ errors: d11, errorsWithCenters: Array.isArray(h10) ? h10 : h10.errorsWithCenters ?? h10.errors, routeIndexByTraceId: u9, padPositionById: p9 });
          if (!m10)
            break;
          const _10 = a10(l11.routes, f10, t11);
          if (_10.status === "unsupported-identity")
            break;
          const y11 = _10.errors, C = Woe({ errors: y11, errorsWithCenters: y11, routeIndexByTraceId: u9, padPositionById: p9 });
          if (!C)
            break;
          if (d11.length === 0 && y11.length === 0) {
            S6++;
            const e61 = c9({ traces: [], routes: l11.routes, hdRoutes: l11.routes });
            if ((Array.isArray(e61) ? e61 : e61.errors).length === 0)
              return { routes: l11.routes, attemptedCandidateCount: v10, candidateValidationCount: I6, referenceValidationCount: S6, repaired: true };
            break;
          }
          if (m10.deficit + C.deficit >= g10.deficit + b10.deficit - 0.000000001)
            break;
          x8 = l11.routes, g10 = m10, b10 = C;
        }
        return { routes: t11, attemptedCandidateCount: v10, candidateValidationCount: I6, referenceValidationCount: S6, repaired: false };
      })({ srj: this.params.srj, routes: e54, newConnections: this.params.newConnections, syntheticConnectionNames: this.syntheticConnectionNames, connMap: this.params.connMap, indexedDrcEvaluator: this.clearancePrecisionIndexedDrcEvaluator, candidateDrcEvaluator: this.clearancePrecisionDrcEvaluator, marginDrcEvaluator: this.clearanceMarginDrcEvaluator, drcEvaluator: this.cachedReferenceDrcEvaluator, initialErrors: l5, initialErrorsWithCenters: Array.isArray(c5) ? c5 : c5.errorsWithCenters ?? c5.errors });
      i8 = t10.attemptedCandidateCount, r9 = t10.candidateValidationCount, s7 = t10.referenceValidationCount, a9 = t10.repaired, t10.repaired && (e54 = t10.routes, o10 = 0);
    }
    if (o10 === 0)
      return this.combinedOutput = e54, this.stats = { ...this.stats, ...this.exactRepairSolver.stats, postExactIndexedDrcIssueCount: n8, postExactReferenceValidationAttempted: true, postExactReferenceDrcIssueCount: 0, postExactReferenceAccepted: true, clearancePrecisionCandidateCount: i8, clearancePrecisionCandidateValidationCount: r9, clearancePrecisionReferenceValidationCount: s7, clearancePrecisionRepaired: a9, boundedRegionalRepairMaxRegions: 0, boundedRegionalRepairMaxCandidateAttempts: 0, boundedRegionalRepairMaxPathSearchNodes: 0, boundedRegionalRepairAttemptedRegionCount: 0, boundedRegionalRepairAcceptedRegionCount: 0, boundedRegionalRepairCandidateAttemptCount: 0, boundedRegionalRepairPathSearchNodeCount: 0, boundedRegionalRepairReferenceValidationCount: 0, boundedRegionalRepairRepaired: false, boundedRegionalRepairTimeMs: 0, regionalB01RepairCandidateCount: 0, regionalB01RepairAcceptedCount: 0, regionalB01RepairFallbackCandidateCount: 0, regionalB01RepairCandidateSearchCount: 0, regionalB01RepairCandidateSearchBudget: 0, regionalB01RepairCandidateSearchBudgetExhausted: false, regionalB01RepairSafeTraceLayerSkippedForBudget: false, regionalB01RepairRemainingDrcIssueCount: 0, regionalB01RepairPreloadEligibleDrcIssueCount: 0, regionalB01RepairAttempted: false, regionalB01RepairTraceIdCount: 0, terminalEscapeCandidateCount: 0, terminalEscapeAcceptedCount: 0, referenceDrcValidationCount: this.referenceDrcValidationCount, referenceDrcFalseNegativeCount: this.referenceDrcFalseNegativeCount, indexedDrcEvaluationCount: this.indexedDrcEvaluationCount, indexedDrcCacheHitCount: this.indexedDrcCacheHitCount, indexedDrcEvaluationTimeMs: this.indexedDrcEvaluationTimeMs, indexedDrcCandidateCacheSize: this.indexedDrcCandidateCache.size, indexedDrcCandidateCacheCapacity: 64 }, void this.finishWithTraceContactCheck();
    const h5 = Nie({ srj: this.params.srj, originalSrj: this.params.originalSrj, routes: e54, newConnections: this.params.newConnections, syntheticConnectionNames: this.syntheticConnectionNames, drcEvaluator: this.drcEvaluator, effort: this.params.effort }), d9 = (({ routes: e60, newConnections: t10, syntheticConnectionNames: n10, fixedPreloadedObstacleRoutes: o11, updatedPreloadedTraces: i9 }) => {
      const r10 = new Set, s9 = Object.assign(new Set, { collidingFixedTraceIds: r10 }), a10 = Yoe({ routes: e60, newConnections: t10, syntheticConnectionNames: n10 }), c9 = new Set;
      for (const [t11, o12] of a10)
        n10.has(e60[o12].connectionName) ? s9.add(t11) : c9.add(t11);
      for (const e61 of o11) {
        const t11 = i9[e61.preloadedTraceIndex];
        if (!t11)
          throw new Error(`Pipeline9 fixed preload route has invalid trace index ${e61.preloadedTraceIndex}`);
        c9.has(t11.pcb_trace_id) ? r10.add(t11.pcb_trace_id) : s9.add(t11.pcb_trace_id);
      }
      return s9;
    })({ routes: h5.routes, newConnections: this.params.newConnections, syntheticConnectionNames: this.syntheticConnectionNames, fixedPreloadedObstacleRoutes: this.fixedPreloadedObstacleRoutes, updatedPreloadedTraces: this.params.updatedPreloadedTraces });
    this.regionalB01Params = { srj: this.params.srj, routes: h5.routes, fixedObstacleRoutes: this.fixedPreloadedObstacleRoutes, newConnections: this.params.newConnections, syntheticConnectionNames: this.syntheticConnectionNames, drcEvaluator: this.drcEvaluator, initialErrors: h5.remainingErrors, allowTracePairRepair: true, preloadRepairTraceIds: d9, connMap: this.params.connMap, colorMap: this.params.colorMap, viaDiameter: this.params.defaultViaDiameter, traceWidth: this.params.srj.minTraceWidth, obstacleMargin: this.params.srj.defaultObstacleMargin ?? this.params.srj.minTraceToPadEdgeClearance ?? 0.15, effort: this.params.effort }, this.stats = { ...this.stats, ...this.exactRepairSolver.stats, postExactIndexedDrcIssueCount: n8, postExactReferenceValidationAttempted: true, postExactReferenceDrcIssueCount: o10, postExactReferenceAccepted: false, clearancePrecisionCandidateCount: i8, clearancePrecisionCandidateValidationCount: r9, clearancePrecisionReferenceValidationCount: s7, clearancePrecisionRepaired: a9, regionalB01RepairTraceIdCount: d9.size + (d9.collidingFixedTraceIds?.size ?? 0), terminalEscapeCandidateCount: h5.attemptedCandidateCount, terminalEscapeAcceptedCount: h5.acceptedCandidateCount }, this.exactRepairSolver.stats.drcBranchPortfolioStoppedForTraceContacts === true && this.traceContactGuard.getNewContactPairs(h5.routes).length > 1 && (this.combinedOutput = h5.routes, this.finishWithTraceContactCheck());
  }
  finishRegionalB01Repair() {
    if (!this.regionalB01RepairSolver?.solved)
      throw new Error("Pipeline9 regional B01 stage must solve before completion");
    const e54 = this.regionalB01RepairSolver.getResult(), t4 = this.cachedReferenceDrcEvaluator({ traces: [], routes: e54.routes, hdRoutes: e54.routes }), n8 = Qoe(e54.routes.length, (Array.isArray(t4) ? t4 : t4.errors).length, this.params.effort);
    this.boundedRegionalParams = { connMap: this.params.connMap, originalSrj: { ...this.params.originalSrj, connections: [...this.params.originalSrj.connections, ...this.params.newConnections] }, routes: e54.routes, viaHoleDiameter: this.params.defaultViaHoleDiameter, syntheticConnectionNames: this.syntheticConnectionNames, drcEvaluator: this.cachedReferenceDrcEvaluator, budget: n8 };
  }
  finishBoundedRegionalRepair() {
    if (!this.boundedRegionalRepairSolver?.solved || !this.regionalB01RepairSolver?.solved || !this.boundedRegionalParams?.budget || this.boundedRegionalRepairStartedAt === undefined)
      throw new Error("Pipeline9 bounded regional stage is missing its completed inputs");
    const e54 = this.regionalB01RepairSolver.getResult(), t4 = this.boundedRegionalRepairSolver.getResult(), n8 = this.boundedRegionalParams.budget;
    this.combinedOutput = t4.routes, this.stats = { ...this.stats, boundedRegionalRepairMaxRegions: n8.maxRegions, boundedRegionalRepairMaxCandidateAttempts: n8.maxCandidateAttempts, boundedRegionalRepairMaxPathSearchNodes: n8.maxPathSearchNodes, boundedRegionalRepairAttemptedRegionCount: t4.attemptedRegionCount, boundedRegionalRepairAcceptedRegionCount: t4.acceptedRegionCount, boundedRegionalRepairCandidateAttemptCount: t4.candidateAttemptCount, boundedRegionalRepairPathSearchNodeCount: t4.pathSearchNodeCount, boundedRegionalRepairReferenceValidationCount: t4.referenceValidationCount, boundedRegionalRepairRepaired: t4.repaired, boundedRegionalRepairPublishedDrcIssueCount: t4.publishedDrcIssueCount, boundedRegionalRepairTimeMs: performance.now() - this.boundedRegionalRepairStartedAt, regionalB01RepairCandidateCount: e54.attemptedCandidateCount, regionalB01RepairAcceptedCount: e54.acceptedCandidateCount, regionalB01RepairFallbackCandidateCount: e54.fallbackCandidateCount, regionalB01RepairCandidateSearchCount: e54.candidateSearchCount, regionalB01RepairCandidateSearchBudget: e54.candidateSearchBudget, regionalB01RepairCandidateSearchBudgetExhausted: e54.candidateSearchBudgetExhausted, regionalB01RepairSafeTraceLayerSkippedForBudget: e54.safeTraceLayerRepairSkippedForBudget, regionalB01RepairRemainingDrcIssueCount: e54.remainingDrcIssueCount, regionalB01RepairPreloadEligibleDrcIssueCount: e54.preloadEligibleDrcIssueCount, regionalB01RepairAttempted: e54.preloadRepairAttempted, referenceDrcValidationCount: this.referenceDrcValidationCount, referenceDrcFalseNegativeCount: this.referenceDrcFalseNegativeCount, indexedDrcEvaluationCount: this.indexedDrcEvaluationCount, indexedDrcCacheHitCount: this.indexedDrcCacheHitCount, indexedDrcEvaluationTimeMs: this.indexedDrcEvaluationTimeMs, indexedDrcCandidateCacheSize: this.indexedDrcCandidateCache.size, indexedDrcCandidateCacheCapacity: 64 }, this.finishWithTraceContactCheck();
  }
  finishWithTraceContactCheck() {
    if (!this.combinedOutput || !this.exactRepairParams)
      throw new Error("Pipeline9 final trace contact check is missing repair state");
    this.traceContactGuard.getNewContactPairs(this.combinedOutput).length !== 0 ? (this.traceContactRepairSolver = new HN({ ...this.exactRepairParams, hdRoutes: this.combinedOutput, inputHdRoutes: this.traceContactInputHdRoutes, deferTraceContactGuard: false }), this.activeSubSolver = this.traceContactRepairSolver, this.MAX_ITERATIONS += this.traceContactRepairSolver.MAX_ITERATIONS) : this.solved = true;
  }
  getCombinedOutput() {
    return this.combinedOutput ?? this.exactRepairSolver?.getOutput() ?? this.inputNewHdRoutes;
  }
  getOutput() {
    return this.getCombinedOutput().filter((e54) => !this.syntheticConnectionNames.has(e54.connectionName));
  }
  getUpdatedPreloadedTraces() {
    const e54 = new Map(this.getCombinedOutput().map((e60) => [e60.connectionName, e60])), t4 = new Map;
    for (const n10 of this.movablePreloadedSections) {
      const o10 = e54.get(n10.syntheticConnectionName);
      if (!o10)
        throw new Error(`Pipeline9 joint DRC repair output is missing "${n10.syntheticConnectionName}"`);
      const i8 = n10.originalTrace.pcb_trace_id, r9 = t4.get(i8) ?? [];
      r9.push({ routePositionStart: n10.originalRoutePositionStart, routePositionEnd: n10.originalRoutePositionEnd, route: Ro(o10, this.params.layerCount, { defaultViaHoleDiameter: this.params.defaultViaHoleDiameter, obstacles: this.params.obstacles, connMap: this.params.connMap }) }), t4.set(i8, r9);
    }
    const n8 = new Map([...t4].map(([e60, t10]) => {
      const n10 = this.inputUpdatedPreloadedTraces.find((t11) => t11.pcb_trace_id === e60);
      if (!n10)
        throw new Error(`Pipeline9 cannot find preloaded trace "${e60}" while rebuilding repaired sections`);
      return [e60, Vie({ originalTrace: n10, repairedSections: t10 })];
    }));
    return this.inputUpdatedPreloadedTraces.map((e60) => n8.get(e60.pcb_trace_id) ?? e60);
  }
  getMutatedPreloadedTraces() {
    const e54 = new Set([...this.params.mutatedPreloadedTraceIds, ...this.movablePreloadedSections.map((e60) => e60.originalTrace.pcb_trace_id)]);
    return this.getUpdatedPreloadedTraces().filter((t4) => e54.has(t4.pcb_trace_id));
  }
  visualize() {
    return this.exactRepairSolver?.visualize() ?? {};
  }
};
var Gie = 0.000001;
var Uie = (e54, t4, n8) => {
  const o10 = mo(e54, n8), i8 = mo(t4, n8);
  return Array.from({ length: Math.abs(i8 - o10) + 1 }, (e60, t10) => Math.min(o10, i8) + t10);
};
var Zie = (e54) => e54.route_type === "wire";
var qie = (e54, t4, n8) => e54.portPoints.filter((e60) => e60.availableZ.includes(n8) && !(e60._preloadedTracePortAssignments ?? []).some((e61) => e61.z === n8 && e61.fixedNetId !== t4.fixedNetId)).map((e60) => ({ portPoint: e60, distance: pe(e60, t4.start, t4.end) })).sort((e60, t10) => e60.distance - t10.distance || e60.portPoint.distToCentermostPortOnZ - t10.portPoint.distToCentermostPortOnZ || e60.portPoint.segmentPortPointId.localeCompare(t10.portPoint.segmentPortPointId))[0]?.portPoint;
var Jie = (e54, t4, n8) => {
  e54._preloadedFixedNetIds = [...new Set([...e54._preloadedFixedNetIds ?? [], t4.fixedNetId])].sort();
  const o10 = t4.end.x - t4.start.x, i8 = t4.end.y - t4.start.y, r9 = o10 * o10 + i8 * i8, s7 = r9 === 0 ? 0 : Math.max(0, Math.min(1, ((e54.x - t4.start.x) * o10 + (e54.y - t4.start.y) * i8) / r9)), a9 = { traceId: t4.traceId, fixedNetId: t4.fixedNetId, routePosition: t4.routePositionStart + s7 * (t4.routePositionEnd - t4.routePositionStart), tracePoint: { x: t4.start.x + s7 * o10, y: t4.start.y + s7 * i8 }, z: n8 }, c5 = e54._preloadedTracePortAssignments ?? [];
  c5.some((e60) => e60.traceId === a9.traceId && e60.fixedNetId === a9.fixedNetId && e60.z === a9.z && Math.abs(e60.routePosition - a9.routePosition) <= Gie) || (e54._preloadedTracePortAssignments = [...c5, a9].sort((e60, t10) => e60.traceId.localeCompare(t10.traceId) || e60.routePosition - t10.routePosition || e60.z - t10.z));
};
var Qie = class extends ni {
  constructor(e54, t4) {
    if (super(), this.sharedEdgeSegments = e54, this.srj = t4, this.MAX_ITERATIONS = 1, this.primitives = ((e60) => {
      const t10 = [], n8 = ei(e60);
      for (const o10 of e60.traces ?? []) {
        if (!o10.connection_name)
          throw new Error(`Preloaded trace "${o10.pcb_trace_id}" is missing a connection name`);
        const i8 = n8.getNetConnectedToId(o10.connection_name) ?? o10.connection_name;
        for (const [n10, r9] of o10.route.entries())
          if (r9.route_type === "via")
            t10.push({ traceId: o10.pcb_trace_id, fixedNetId: i8, connectionName: o10.connection_name, routePositionStart: n10, routePositionEnd: n10, zLayers: Uie(r9.from_layer, r9.to_layer, e60.layerCount), start: r9, end: r9 });
          else if (r9.route_type === "through_obstacle")
            t10.push({ traceId: o10.pcb_trace_id, fixedNetId: i8, connectionName: o10.connection_name, routePositionStart: n10, routePositionEnd: n10 + 1, zLayers: Uie(r9.from_layer, r9.to_layer, e60.layerCount), start: r9.start, end: r9.end });
          else if (r9.route_type === "jumper") {
            const s7 = mo(r9.layer, e60.layerCount);
            for (const [e61, a9] of [r9.start, r9.end].entries())
              t10.push({ traceId: o10.pcb_trace_id, fixedNetId: i8, connectionName: o10.connection_name, routePositionStart: n10 + e61, routePositionEnd: n10 + e61, zLayers: [s7], start: a9, end: a9 });
          }
        for (let n10 = 0;n10 < o10.route.length - 1; n10++) {
          const r9 = o10.route[n10], s7 = o10.route[n10 + 1];
          Zie(r9) && Zie(s7) && r9.layer === s7.layer && t10.push({ traceId: o10.pcb_trace_id, fixedNetId: i8, connectionName: o10.connection_name, routePositionStart: n10, routePositionEnd: n10 + 1, zLayers: [mo(r9.layer, e60.layerCount)], start: r9, end: s7 });
        }
      }
      return t10;
    })(t4), this.boundaryIndex = e54.length > 0 ? new E2(e54.length) : null, this.boundaryIndex) {
      for (const t10 of e54)
        this.boundaryIndex.add(Math.min(t10.start.x, t10.end.x), Math.min(t10.start.y, t10.end.y), Math.max(t10.start.x, t10.end.x), Math.max(t10.start.y, t10.end.y));
      this.boundaryIndex.finish();
    }
  }
  primitives;
  boundaryIndex;
  getSolverName() {
    return "PreloadedTraceGraphSolver";
  }
  _step() {
    let e54 = 0;
    for (const t10 of this.primitives) {
      if (this.boundaryIndex === null)
        break;
      const n10 = this.boundaryIndex.search(Math.min(t10.start.x, t10.end.x) - Gie, Math.min(t10.start.y, t10.end.y) - Gie, Math.max(t10.start.x, t10.end.x) + Gie, Math.max(t10.start.y, t10.end.y) + Gie).sort((e60, t11) => e60 - t11);
      for (const o10 of n10) {
        const n11 = this.sharedEdgeSegments[o10];
        if (e54++, !(qr(t10.start, t10.end, n11.start, n11.end) > Gie))
          for (const e60 of t10.zLayers) {
            if (!n11.availableZ.includes(e60))
              continue;
            const o11 = qie(n11, t10, e60);
            o11 && Jie(o11, t10, e60);
          }
      }
    }
    const t4 = this.sharedEdgeSegments.flatMap((e60) => e60.portPoints), n8 = t4.filter((e60) => (e60._preloadedFixedNetIds?.length ?? 0) > 0);
    this.stats = { boundaryDistanceCheckCount: e54, preloadedTraceCount: this.srj.traces?.length ?? 0, preloadedTraceShapeCount: this.primitives.length, inputBoundaryCount: this.sharedEdgeSegments.length, outputBoundaryCount: this.sharedEdgeSegments.length, inputPortCount: t4.length, outputPortCount: t4.length, preloadedPortCount: n8.length, tracePortAssignmentCount: n8.reduce((e60, t10) => e60 + (t10._preloadedTracePortAssignments?.length ?? 0), 0), topologyChanged: false }, this.solved = true;
  }
  getOutput() {
    if (!this.solved)
      throw new Error("PreloadedTraceGraphSolver has not solved yet");
    return this.sharedEdgeSegments;
  }
};
var Kie = class extends U1 {
  _step() {
    if (this.error = G1(this.inputSrj), this.error)
      return void (this.failed = true);
    const { traces: e54, ...t4 } = this.inputSrj, n8 = V1(t4), o10 = V1(Zr(W1(n8)));
    this.error = G1(o10), this.error ? this.failed = true : (this.outputSrj = e54 === undefined ? o10 : { ...o10, traces: e54 }, this.solved = true);
  }
};
function ere(e54) {
  return new Set((e54 ?? []).filter((e60) => e60._isComponentTopologyNode).map((e60) => e60.capacityMeshNodeId));
}
function tre(e54, t4) {
  return e54.nodeIds.some((e60) => t4.has(e60));
}
function nre({ sharedEdgeSegments: e54, componentCapacityMeshNodeIds: t4 }) {
  return e54.filter((e60) => !tre(e60, t4));
}
function ore(e54, t4, n8, o10 = {}) {
  return { solverName: e54, solverClass: t4, getConstructorParams: n8, onSolved: o10.onSolved };
}
var ire = class extends ni {
  constructor(e54, t4 = {}) {
    super(), this.srj = e54, this.opts = t4;
    const n8 = V1(e54);
    this.originalSrj = n8, this.opts = { ...t4 };
    const o10 = this.opts;
    if (this.effort = o10.effort ?? 1, this.MAX_ITERATIONS = 1e8 * this.effort, this.maxNodeDimension = o10.maxNodeDimension ?? 15, this.maxNodeRatio = o10.maxNodeRatio ?? 6, this.minNodeArea = o10.minNodeArea ?? 0.1 ** 2, this.visualizationTraceColorMode = o10.visualizationTraceColorMode ?? "layer", this.setSimpleRouteJson(n8), o10.capacityDepth === undefined) {
      const e60 = this.srj.bounds.maxX - this.srj.bounds.minX, t10 = this.srj.bounds.maxY - this.srj.bounds.minY, n10 = Math.max(e60, t10), i8 = o10.targetMinCapacity ?? 0.5;
      o10.capacityDepth = Fz(n10, i8);
    }
    this.cacheProvider = o10.cacheProvider === undefined ? no() : o10.cacheProvider === null ? null : o10.cacheProvider, this.startTimeOfPhase = {}, this.endTimeOfPhase = {}, this.timeSpentOnPhase = {};
  }
  getSolverName() {
    return "AutoroutingPipelineSolver9_PreloadedTraceGraph";
  }
  preprocessSimpleRouteJsonSolver;
  escapeViaLocationSolver;
  netToPointPairsSolver;
  componentTopologyGeneratorSolver;
  topologyPlanningSolver;
  topologyMergingSolver;
  globalTopologyGeneratorSolver;
  nodeDimensionSubdivisionSolver;
  nodeTargetMerger;
  edgeSolver;
  colorMap;
  highDensityRouteSolver;
  highDensityForceImproveSolver;
  highDensityRepairSolver;
  highDensityStitchSolver;
  globalDrcForceImproveSolver;
  pipeline9JointDrcRepairSolver;
  singleLayerNodeMerger;
  strawSolver;
  deadEndSolver;
  traceSimplificationSolver;
  mutatedPreloadedTraceSimplificationSolver;
  lengthMatchingPostProcessingSolver;
  powerTraceExpansionSolver;
  availableSegmentPointSolver;
  portPointPathingSolver;
  multiSectionPortPointOptimizer;
  uniformPortDistributionSolver;
  traceWidthSolver;
  necessaryCrampedPortPointSolver;
  preloadedTraceGraphSolver;
  componentDetectionSolver;
  viaDiameter;
  viaHoleDiameter;
  minTraceWidth;
  effort;
  effortCleanupSolver;
  maxNodeDimension;
  maxNodeRatio;
  minNodeArea;
  visualizationTraceColorMode;
  startTimeOfPhase;
  endTimeOfPhase;
  timeSpentOnPhase;
  activeSubSolver = null;
  connMap;
  srjWithEscapeViaLocations;
  srjWithPointPairs;
  originalSrj;
  capacityNodes = null;
  capacityEdges = null;
  sharedEdgeSegmentsWithNecessaryCrampedPortPoints;
  highDensityNodePortPoints;
  cacheProvider = null;
  pipelineDef = [ore("preprocessSimpleRouteJsonSolver", Kie, (e54) => [e54.originalSrj, { traceColorMode: e54.visualizationTraceColorMode }], { onSolved: (e54) => {
    e54.setSimpleRouteJson(e54.preprocessSimpleRouteJsonSolver.getOutputSimpleRouteJson());
  } }), ore("componentDetectionSolver", r7, (e54) => [{ inputSrj: e54.srj }]), ore("escapeViaLocationSolver", uK, (e54) => [e54.srj, { viaDiameter: e54.viaDiameter, minTraceWidth: e54.minTraceWidth, obstacleMargin: e54.srj.defaultObstacleMargin ?? 0.15 }], { onSolved: (e54) => {
    e54.srjWithEscapeViaLocations = e54.escapeViaLocationSolver?.getOutputSimpleRouteJson();
  } }), ore("netToPointPairsSolver", pB, (e54) => {
    const t4 = e54.srjWithEscapeViaLocations ?? e54.srj;
    return [t4, e54.colorMap, ti(t4)];
  }, { onSolved: (e54) => {
    e54.srjWithPointPairs = e54.netToPointPairsSolver?.getNewSimpleRouteJson(), e54.colorMap = Eo(e54.srjWithPointPairs, e54.connMap), e54.connMap = ei(e54.srjWithPointPairs);
  } }), ore("topologyPlanningSolver", N7, (e54) => [{ inputSrj: e54.srjWithPointPairs, componentDetectionOutput: e54.componentDetectionSolver.getOutput(), viaDiameter: e54.viaDiameter, obstacleMargin: e54.srj.defaultObstacleMargin ?? 0.15 }], { onSolved: (e54) => {
    e54.topologyPlanningSolver.getOutput();
    e54.globalTopologyGeneratorSolver = e54.topologyPlanningSolver.globalTopologySolver, e54.componentTopologyGeneratorSolver = new E7(e54.topologyPlanningSolver);
  } }), ore("topologyMergingSolver", C7, (e54) => {
    const t4 = e54.topologyPlanningSolver.getOutput();
    return [{ layerCount: e54.srj.layerCount, allowBlindAndBuriedVias: e54.srj.allowBlindAndBuriedVias, nodeGroups: [{ groupId: "global", nodes: t4.globalMeshNodes, isComponent: false }, ...t4.componentMeshNodes.map((e60, t10) => ({ groupId: `component-${t10}`, nodes: e60, isComponent: true }))] }];
  }, { onSolved: (e54) => {
    e54.capacityNodes = e54.topologyMergingSolver.getOutput();
  } }), ore("nodeDimensionSubdivisionSolver", MZ, (e54) => [e54.capacityNodes, e54.maxNodeDimension, e54.maxNodeRatio, e54.minNodeArea], { onSolved: (e54) => {
    e54.capacityNodes = e54.nodeDimensionSubdivisionSolver.outputNodes;
  } }), ore("edgeSolver", ui, (e54) => [e54.capacityNodes], { onSolved: (e54) => {
    e54.capacityEdges = e54.edgeSolver?.edges;
  } }), ore("availableSegmentPointSolver", ii, (e54) => [{ nodes: e54.capacityNodes, edges: e54.capacityEdges || [], traceWidth: e54.minTraceWidth, colorMap: e54.colorMap, shouldReturnCrampedPortPoints: true }]), ore("necessaryCrampedPortPointSolver", FG, (e54) => {
    const t4 = ere(e54.capacityNodes);
    return [{ capacityMeshNodes: e54.capacityNodes.filter((e60) => !t4.has(e60.capacityMeshNodeId)), sharedEdgeSegments: nre({ sharedEdgeSegments: e54.availableSegmentPointSolver.getOutput(), componentCapacityMeshNodeIds: t4 }), simpleRouteJson: e54.srjWithPointPairs }];
  }, { onSolved: (e54) => {
    const t4 = ere(e54.capacityNodes);
    e54.sharedEdgeSegmentsWithNecessaryCrampedPortPoints = function({ originalSharedEdgeSegments: e60, filteredSharedEdgeSegments: t10, componentCapacityMeshNodeIds: n8 }) {
      const o10 = new Map(t10.map((e61) => [e61.edgeId, e61]));
      return e60.map((e61) => tre(e61, n8) ? e61 : o10.get(e61.edgeId) ?? e61);
    }({ originalSharedEdgeSegments: e54.availableSegmentPointSolver.getOutput(), filteredSharedEdgeSegments: e54.necessaryCrampedPortPointSolver.getOutput(), componentCapacityMeshNodeIds: t4 });
  } }), ore("preloadedTraceGraphSolver", Qie, (e54) => [e54.sharedEdgeSegmentsWithNecessaryCrampedPortPoints, e54.srjWithPointPairs]), ore("portPointPathingSolver", eK, (e54) => {
    const t4 = e54.sharedEdgeSegmentsWithNecessaryCrampedPortPoints ?? e54.necessaryCrampedPortPointSolver?.getOutput() ?? e54.availableSegmentPointSolver.getOutput(), { graph: n8, connections: o10 } = KG({ capacityMeshNodes: e54.capacityNodes, layerCount: e54.srj.layerCount, connectivityMap: e54.connMap, segmentPortPoints: t4.flatMap((e60) => e60.portPoints), simpleRouteJsonConnections: e54.srjWithPointPairs.connections });
    return [{ graph: n8, connections: o10, layerCount: e54.srj.layerCount, effort: Math.min(1, e54.effort), preserveTerminalPcbPortIds: true, captureSearchDebug: e54.opts.captureSearchDebug ?? false, minViaPadDiameter: e54.viaDiameter, flags: { FORCE_CENTER_FIRST: true, RIPPING_ENABLED: true, USE_SELECTIVE_RERIP_ROUTING: true, USE_PREPARED_PORT_POINT_ROUTING: true, USE_PARTIAL_RIP_ROUTING_WITH_PRELOADED_TRACES: true }, weights: { SHUFFLE_SEED: 0, MEMORY_PF_FACTOR: 4, CENTER_OFFSET_DIST_PENALTY_FACTOR: 0, CENTER_OFFSET_FOCUS_SHIFT: 0, NODE_PF_FACTOR: 0, LAYER_CHANGE_COST: 0, RIPPING_PF_COST: 0, NODE_PF_MAX_PENALTY: 100, BASE_CANDIDATE_COST: 0.6, MAX_ITERATIONS_PER_PATH: 0, RANDOM_WALK_DISTANCE: 0, START_RIPPING_PF_THRESHOLD: 0.3, END_RIPPING_PF_THRESHOLD: 1, MAX_RIPS: 1000, RANDOM_RIP_FRACTION: 0.3, STRAIGHT_LINE_DEVIATION_PENALTY_FACTOR: 4, GREEDY_MULTIPLIER: 0.7, MIN_ALLOWED_BOARD_SCORE: -1e4 } }];
  }), ore("uniformPortDistributionSolver", bo, (e54) => [{ nodeWithPortPoints: e54.portPointPathingSolver?.getOutput().nodesWithPortPoints ?? [], inputNodesWithPortPoints: e54.portPointPathingSolver?.getOutput().inputNodeWithPortPoints ?? [], minTraceWidth: e54.minTraceWidth, obstacles: e54.srj.obstacles, layerCount: e54.srj.layerCount, useLayerAwareGeometry: e54.srj.layerCount > 2, preserveSolitaryPorts: Boolean(e54.srj.traces?.length) }]), ore("highDensityRouteSolver", Loe, (e54) => {
    const t4 = e54.portPointPathingSolver;
    if (!t4)
      throw new Error("Pipeline9 invariant violated: high-density routing requires the completed port-point pathing solver");
    const n8 = t4.getOutput(), o10 = e54.uniformPortDistributionSolver?.getOutput() ?? [], i8 = n8.nodesWithPortPoints, r9 = o10.length > 0 ? o10 : i8;
    e54.highDensityNodePortPoints = structuredClone(r9);
    const s7 = (e54.originalSrj.traces ?? []).flatMap((t10, n10) => Vne(t10, n10, e54.originalSrj.layerCount, e54.viaDiameter, e54.connMap)), a9 = fne({ traces: e54.originalSrj.traces ?? [], fixedHdRoutes: s7, sections: e54.getChangedPreloadedTraceSections() });
    return [{ nodePortPoints: r9, boardGeometry: { bounds: e54.originalSrj.bounds, outline: e54.originalSrj.outline, minBoardEdgeClearance: e54.originalSrj.minBoardEdgeClearance }, fixedHdRoutes: a9, connMap: e54.connMap, colorMap: e54.colorMap, obstacles: e54.srj.obstacles, layerCount: e54.srj.layerCount, allowBlindAndBuriedVias: e54.srj.allowBlindAndBuriedVias, viaDiameter: e54.viaDiameter, viaHoleDiameter: e54.viaHoleDiameter, minViaHoleEdgeToViaHoleEdgeClearance: e54.originalSrj.minViaHoleEdgeToViaHoleEdgeClearance ?? 0.1, traceWidth: e54.minTraceWidth, obstacleMargin: e54.srj.defaultObstacleMargin ?? 0.15, viaToPadClearance: e54.srj.minViaEdgeToPadEdgeClearance, effort: Math.min(1, e54.effort), includeBoardObstacles: true, nodePfById: t4.computeNodePfMap(), preserveTerminalPcbPortIds: true }];
  }), ore("highDensityForceImproveSolver", qte, (e54) => [{ nodeWithPortPoints: e54.highDensityNodePortPoints ?? [], hdRoutes: xne(yne(e54.highDensityRouteSolver.routes)), colorMap: e54.colorMap, totalStepsPerNode: Math.max(12, Math.round(20 * Math.min(1, e54.effort))), nodeAssignmentMargin: e54.srj.defaultObstacleMargin ?? 0.2 }]), ore("highDensityRepairSolver", g1, (e54) => [{ nodeWithPortPoints: e54.highDensityNodePortPoints ?? [], hdRoutes: e54.highDensityForceImproveSolver?.getOutput() ?? e54.highDensityRouteSolver.routes, obstacles: e54.srj.obstacles, colorMap: e54.colorMap, repairMargin: e54.srj.defaultObstacleMargin ?? 0.2, minimumTraceWidth: e54.srj.minTraceWidth, connMap: e54.connMap }]), ore("highDensityStitchSolver", L1, (e54) => [{ connections: [...e54.srjWithPointPairs.connections, ...e54.getChangedPreloadedTraceSections().map((e60) => e60.connection)], hdRoutes: e54.highDensityRepairSolver?.getOutput() ?? e54.highDensityForceImproveSolver?.getOutput() ?? e54.highDensityRouteSolver.routes, colorMap: e54.colorMap, layerCount: e54.srj.layerCount, defaultViaDiameter: e54.viaDiameter, preserveTerminalPcbPortIds: true, preferSameLayerTerminalEndpoints: true }]), ore("traceSimplificationSolver", WF, (e54) => {
    const t4 = e54.getPreloadedTraceUpdatesAfterHighDensity().updatedPreloadedTraces.flatMap((t10, n10) => Vne(t10, n10, e54.originalSrj.layerCount, e54.viaDiameter, e54.connMap).map((e60) => ({ ...e60, rootConnectionName: t10.connection_name }))), n8 = new Set(e54.getChangedPreloadedTraceSections().map((e60) => e60.connectionName)), o10 = e54.highDensityStitchSolver.mergedHdRoutes.filter((e60) => !n8.has(e60.connectionName)), i8 = hne([...o10, ...t4], e54.connMap);
    return [{ hdRoutes: o10, obstacles: e54.srj.obstacles, connMap: e54.connMap, colorMap: e54.colorMap, outline: e54.srj.outline, defaultViaDiameter: e54.viaDiameter, layerCount: e54.srj.layerCount, minTraceToPadEdgeClearance: e54.srj.minTraceToPadEdgeClearance, minBoardEdgeClearance: e54.srj.minBoardEdgeClearance, otherHdRoutes: t4, netByConnectionName: i8, enableCrossingViaReduction: true, terminalLayerIndicesByPcbPortId: lne(e54.srj.connections, e54.srj.obstacles, e54.srj.layerCount), iterations: 2 }];
  }), ore("mutatedPreloadedTraceSimplificationSolver", WF, (e54) => {
    const t4 = e54.getPreparedMutatedPreloadedTraceSections(), n8 = t4.sections.map((e60) => e60.hdRoute), o10 = [...t4.immutableHdRoutes, ...e54.traceSimplificationSolver.simplifiedHdRoutes];
    return [{ hdRoutes: n8, obstacles: e54.srj.obstacles, connMap: e54.connMap, colorMap: e54.colorMap, outline: e54.srj.outline, defaultViaDiameter: e54.viaDiameter, layerCount: e54.srj.layerCount, minTraceToPadEdgeClearance: e54.srj.minTraceToPadEdgeClearance, minBoardEdgeClearance: e54.srj.minBoardEdgeClearance, otherHdRoutes: o10, netByConnectionName: hne([...n8, ...o10], e54.connMap), enableCrossingViaReduction: true, preserveRouteEndpoints: true, enableVertexShortcuts: true, iterations: 2 }];
  }), ore("traceWidthSolver", QF, (e54) => [{ hdRoutes: e54.traceSimplificationSolver.simplifiedHdRoutes, obstacles: e54.srj.obstacles, connMap: e54.connMap, colorMap: e54.colorMap, minTraceWidth: e54.minTraceWidth, connection: e54.srjWithPointPairs.connections, obstacleMargin: e54.srj.minTraceToPadEdgeClearance ?? 0.15, minTraceToHoleEdgeClearance: e54.srj.minTraceToHoleEdgeClearance, layerCount: e54.srj.layerCount }]), ore("globalDrcForceImproveSolver", kN, (e54) => [{ srj: e54.getSrjWithMaterializedPreloadedTraces(), hdRoutes: Mte({ hdRoutes: bne(e54.traceWidthSolver.getHdRoutesWithWidths()), connections: e54.netToPointPairsSolver?.newConnections ?? [] }), connMap: e54.connMap, effort: Math.min(1, e54.effort), maxIterations: 16, enableLargeBoardBroadFallback: false, enablePostSolveClearanceRelaxation: false, deferTraceContactGuard: true }]), ore("pipeline9JointDrcRepairSolver", Wie, (e54) => {
    const t4 = e54.getPreloadedTraceUpdatesAfterHighDensity(), n8 = e54.getSrjWithMaterializedPreloadedTraces();
    return [{ srj: n8, srjWithPointPairs: n8, originalSrj: e54.originalSrj, newConnections: e54.netToPointPairsSolver?.newConnections ?? [], newHdRoutes: e54.globalDrcForceImproveSolver.getOutput(), originalNewHdRoutes: e54.globalDrcForceImproveSolver.guardedInputHdRoutes, updatedPreloadedTraces: t4.updatedPreloadedTraces, mutatedPreloadedTraceIds: new Set(t4.mutatedPreloadedTraces.map((e60) => e60.pcb_trace_id)), connMap: e54.connMap, obstacles: e54.srj.obstacles, layerCount: e54.srj.layerCount, defaultViaDiameter: e54.viaDiameter, defaultViaHoleDiameter: e54.viaHoleDiameter, effort: Math.min(1, e54.effort), colorMap: e54.colorMap }];
  }), ore("effortCleanupSolver", Bte, (e54) => {
    const t4 = e54.getUpdatedPreloadedTraces(), n8 = { ...e54.originalSrj, traces: t4 }, o10 = bne(e54.pipeline9JointDrcRepairSolver.getOutput()), i8 = (t10) => cne(Cte({ connections: e54.netToPointPairsSolver.newConnections, originalConnections: e54.originalSrj.connections, hdRoutes: bne(t10), layerCount: e54.srj.layerCount, obstacles: e54.srj.obstacles, defaultViaHoleDiameter: e54.viaHoleDiameter, connMap: e54.connMap }), e54.originalSrj.traces ?? []), r9 = Gte({ inputSrj: n8, srjWithPointPairs: e54.srjWithPointPairs, includeBoardClearance: true, drcOptions: { traceClearance: e54.originalSrj.minTraceToPadEdgeClearance ?? e54.originalSrj.defaultObstacleMargin ?? 0.1, viaClearance: e54.originalSrj.minViaHoleEdgeToViaHoleEdgeClearance ?? 0.1 } });
    return [{ effort: e54.effort, viaRemovalPasses: e54.pipeline9JointDrcRepairSolver.stats.initialBoundedRegionalRepairAddedViaCount > 0 ? 2 : 1, config: { hdRoutes: o10, preserveRouteEndpoints: true, obstacles: e54.srj.obstacles, connMap: e54.connMap, colorMap: e54.colorMap, outline: e54.srj.outline, defaultViaDiameter: e54.viaDiameter, layerCount: e54.srj.layerCount, minTraceToPadEdgeClearance: e54.srj.minTraceToPadEdgeClearance, minBoardEdgeClearance: e54.srj.minBoardEdgeClearance, otherHdRoutes: t4.flatMap((t10, n10) => Vne(t10, n10, e54.srj.layerCount, e54.viaDiameter, e54.connMap)), enableCrossingViaReduction: true, terminalLayerIndicesByPcbPortId: lne(e54.srj.connections, e54.srj.obstacles, e54.srj.layerCount) }, getCost: (e60) => {
      const t10 = i8(e60);
      return { vias: t10.reduce((e61, t11) => e61 + t11.route.filter((e63) => e63.route_type === "via").length, 0), points: t10.reduce((e61, t11) => e61 + t11.route.length, 0) };
    }, isValid: (e60) => r9(i8(e60)).errors.length === 0 }];
  }), ore("lengthMatchingPostProcessingSolver", Kte, (e54) => {
    const t4 = e54.netToPointPairsSolver;
    if (!t4)
      throw new Error("Pipeline9: length-matching post-processing requires NetToPointPairsSolver output");
    const n8 = t4.newConnections, o10 = new Map;
    for (const t10 of e54.srj.differentialPairs ?? [])
      for (const e60 of t10.connectionNames) {
        const t11 = n8.filter((t12) => t12.name === e60 || t12.__rootConnectionNames?.includes(e60) || t12.__netConnectionName === e60);
        if (t11.length !== 1)
          throw new Error(`Pipeline9: differential pair connection "${e60}" must resolve to exactly one final point-pair connection, got ${t11.length}`);
        o10.set(e60, t11[0].name);
      }
    const i8 = e54.effortCleanupSolver.getOutput(), r9 = (e54.srj.differentialPairs ?? []).map((e60) => {
      const t10 = e60.connectionNames.map((e61) => {
        const t11 = o10.get(e61);
        if (!t11)
          throw new Error(`Pipeline9: differential pair connection "${e61}" is missing from final routed output`);
        return t11;
      });
      if (t10[0] === t10[1])
        throw new Error(`Pipeline9: differential pair ${e60.connectionNames.join("/")} resolves both members to "${t10[0]}"`);
      const n10 = { connectionNames: t10, lengthTolerance: e60.lengthTolerance };
      if (e60.maxUncoupledLength !== undefined && (n10.maxUncoupledLength = e60.maxUncoupledLength), e60.traceGap === undefined)
        return n10;
      const r10 = t10.map((e61) => {
        const t11 = i8.filter((t12) => t12.connectionName === e61);
        if (t11.length !== 1)
          throw new Error(`Pipeline9: differential pair connection "${e61}" must resolve to exactly one final HD route, got ${t11.length}`);
        return t11[0];
      }), s7 = e60.traceGap + r10.reduce((e61, t11) => e61 + t11.traceThickness / 2, 0);
      return { ...n10, minimumCenterlineDistance: s7, maximumCenterlineDistance: s7 };
    });
    return [{ hdRoutes: i8, differentialPairs: r9, buses: e54.srj.buses ?? [], connections: e54.srj.connections, obstacles: e54.srj.obstacles, traces: e54.getUpdatedPreloadedTraces(), bounds: e54.srj.bounds, layerCount: e54.srj.layerCount, obstacleMargin: e54.srj.minTraceToPadEdgeClearance ?? 0.15 }];
  }), ore("powerTraceExpansionSolver", Ite, (e54) => {
    const t4 = e54.opts.powerTraceExpansion ?? {}, n8 = t4.onlyConnectionNames ?? Pte(e54.originalSrj);
    return [wte({ originalSrj: e54.originalSrj, newlyRoutedTraces: e54.getNewTracesBeforePowerExpansion(), currentPreloadedTraces: e54.getUpdatedPreloadedTraces(), expandedConnectionNames: n8, resolveConnectedTraceAliases: true }), { allowNewVias: false, ...t4, onlyConnectionNames: n8 }];
  })];
  setSimpleRouteJson(e54) {
    this.srj = e54;
    const t4 = Yo(this.srj);
    this.viaDiameter = t4.padDiameter, this.viaHoleDiameter = t4.holeDiameter, this.minTraceWidth = this.srj.minTraceWidth, this.connMap = ei(this.srj), this.colorMap = Eo(this.srj, this.connMap);
  }
  getConstructorParams() {
    return [this.srj, this.opts];
  }
  currentPipelineStepIndex = 0;
  asyncRunning = false;
  async solveAsync(e54) {
    if (this.asyncRunning)
      throw new Error("Pipeline9 solveAsync is already running");
    const t4 = performance.now();
    let n8 = t4;
    this.asyncRunning = true;
    try {
      if (e54 === undefined)
        return void this.solve();
      for (;!this.solved && !this.failed; ) {
        if (this.activeSubSolver instanceof Loe || this.activeSubSolver instanceof eK || this.activeSubSolver instanceof g1 || this.activeSubSolver instanceof qte) {
          const t10 = this.activeSubSolver, n10 = t10.iterations;
          await t10.solveAsync(e54, n10 + Math.max(0, this.MAX_ITERATIONS - this.iterations));
          const o10 = t10.solved || t10.failed;
          this.iterations += Math.max(0, t10.iterations - n10 - (o10 ? 1 : 0));
        }
        this.step(), this.iterations % 1024 == 0 && performance.now() - n8 >= 16 && (await new Promise((e60) => setTimeout(e60, 0)), n8 = performance.now());
      }
    } catch (e60) {
      throw this.failed = true, this.error = `Pipeline9 asynchronous solve error: ${e60}`, e60;
    } finally {
      this.asyncRunning = false, this.timeToSolve = performance.now() - t4;
    }
  }
  computeProgress() {
    const e54 = this.activeSubSolver?.progress ?? 0;
    return (this.currentPipelineStepIndex + e54) / this.pipelineDef.length;
  }
  _step() {
    const e54 = this.pipelineDef[this.currentPipelineStepIndex];
    if (!e54)
      return void (this.solved = true);
    if (this.activeSubSolver)
      return this.activeSubSolver.step(), void (this.activeSubSolver.solved ? (this.endTimeOfPhase[e54.solverName] = performance.now(), this.timeSpentOnPhase[e54.solverName] = this.endTimeOfPhase[e54.solverName] - this.startTimeOfPhase[e54.solverName], e54.onSolved?.(this), this.activeSubSolver = null, this.currentPipelineStepIndex++) : this.activeSubSolver.failed && (this.error = this.activeSubSolver?.error, this.failed = true, this.activeSubSolver = null));
    const t4 = e54.getConstructorParams(this);
    this.activeSubSolver = new e54.solverClass(...t4), this.activeSubSolver instanceof WF && (this.activeSubSolver.MAX_SIMPLIFICATION_PIPELINE_LOOPS = Math.ceil(this.activeSubSolver.MAX_SIMPLIFICATION_PIPELINE_LOOPS * Math.min(1, this.effort))), e54.solverName !== "lengthMatchingPostProcessingSolver" && e54.solverName !== "powerTraceExpansionSolver" && e54.solverName !== "effortCleanupSolver" || (this.MAX_ITERATIONS = Math.max(this.MAX_ITERATIONS, this.iterations + this.activeSubSolver.MAX_ITERATIONS + 1)), this[e54.solverName] = this.activeSubSolver, this.timeSpentOnPhase[e54.solverName] = 0, this.startTimeOfPhase[e54.solverName] = performance.now();
  }
  solveUntilPhase(e54) {
    for (;this.getCurrentPhase() !== e54; )
      this.step();
  }
  getCurrentPhase() {
    return this.pipelineDef[this.currentPipelineStepIndex]?.solverName ?? "none";
  }
  visualize() {
    if (!this.solved && this.activeSubSolver)
      return this.visualizeStage(this.activeSubSolver);
    const e54 = this.escapeViaLocationSolver?.visualize(), t4 = this.netToPointPairsSolver?.visualize(), n8 = this.componentDetectionSolver?.visualize(), o10 = this.componentTopologyGeneratorSolver?.visualize(), i8 = this.globalTopologyGeneratorSolver?.visualize(), r9 = this.topologyMergingSolver?.visualize(), s7 = this.nodeDimensionSubdivisionSolver?.visualize(), a9 = this.nodeTargetMerger?.visualize(), c5 = this.singleLayerNodeMerger?.visualize(), l5 = this.strawSolver?.visualize(), h5 = this.edgeSolver?.visualize(), d9 = this.deadEndSolver?.visualize(), u9 = this.availableSegmentPointSolver?.visualize(), p9 = this.portPointPathingSolver?.visualize(), m9 = this.multiSectionPortPointOptimizer?.visualize(), g10 = this.uniformPortDistributionSolver?.visualize(), f10 = this.highDensityRouteSolver?.visualize(), _5 = this.highDensityForceImproveSolver?.visualize(), y10 = this.highDensityRepairSolver?.visualize(), b10 = this.highDensityStitchSolver?.visualize(), x8 = this.traceSimplificationSolver?.visualize(), v10 = this.mutatedPreloadedTraceSimplificationSolver?.visualize(), I6 = this.lengthMatchingPostProcessingSolver?.visualize(), S6 = this.powerTraceExpansionSolver?.visualize(), C = this.traceWidthSolver?.visualize(), P = this.necessaryCrampedPortPointSolver?.visualize(), M = (this.highDensityRouteSolver?.visualize(), this.originalSrj), w = M.outline, N = [];
    if (N.push({ points: [{ x: M.bounds?.minX ?? -50, y: M.bounds?.minY ?? -50 }, { x: M.bounds?.maxX ?? 50, y: M.bounds?.minY ?? -50 }, { x: M.bounds?.maxX ?? 50, y: M.bounds?.maxY ?? 50 }, { x: M.bounds?.minX ?? -50, y: M.bounds?.maxY ?? 50 }, { x: M.bounds?.minX ?? -50, y: M.bounds?.minY ?? -50 }], strokeColor: "rgba(255,0,0,0.25)" }), w && w.length >= 2) {
      const e60 = w.map((e61) => ({ x: e61.x, y: e61.y }));
      e60.push({ ...e60[0] }), N.push({ points: e60, strokeColor: "rgba(0, 136, 255, 0.95)" });
    }
    const R10 = Lo(M), T2 = { points: [...M.connections.flatMap((e60) => e60.pointsToConnect.map((t10) => ({ ...t10, layer: Bo(t10, M.layerCount), label: `${e60.name} ${t10.pcb_port_id ?? ""}` })))], rects: [...(M.obstacles ?? []).filter((e60) => !e60.isCopperPour).map((e60) => ({ ...e60, fill: e60.layers?.includes("top") ? "rgba(255,0,0,0.25)" : e60.layers?.includes("bottom") ? "rgba(0,0,255,0.25)" : "rgba(255,0,0,0.25)", layer: jo(e60, M.layerCount), label: R10(e60) }))], lines: N }, E10 = { traceColorMode: this.visualizationTraceColorMode }, A7 = nK({ srj: M, visualizationOptions: E10 }), O10 = pi(T2, A7), k6 = this.preprocessSimpleRouteJsonSolver?.visualize(), D9 = this.globalDrcForceImproveSolver?.visualize(), L10 = this.pipeline9JointDrcRepairSolver?.visualize(), z10 = [O10, k6, n8, o10, e54, t4, i8, r9, s7, a9, c5, l5, h5, d9, u9, P, p9, m9, g10, f10 ? pi(T2, f10) : null, _5, y10, b10, x8, v10, C, D9, L10, I6, S6, this.solved ? pi({ lines: N }, nK({ srj: this.originalSrj, visualizationOptions: E10 }), this.visualizeFinalOutput()) : null].filter(Boolean), B5 = pi(...z10);
    return this.visualizationTraceColorMode === "net" ? T7(B5, this.colorMap) : B5;
  }
  visualizeStage(e54) {
    const t4 = e54.visualize();
    return this.visualizationTraceColorMode === "net" ? T7(t4, this.colorMap) : t4;
  }
  visualizeFinalOutput() {
    const e54 = this.visualizationTraceColorMode, t4 = this.getOutputSimpleRouteJson();
    return Wo(t4, { traceColorMode: e54 });
  }
  preview() {
    if (this.highDensityRouteSolver) {
      const e54 = [];
      for (let t4 = this.highDensityRouteSolver.routes.length - 1;t4 >= 0; t4--) {
        const n8 = this.highDensityRouteSolver.routes[t4];
        if (e54.push({ points: n8.route.map((e60) => ({ x: e60.x, y: e60.y })), strokeColor: this.colorMap[n8.connectionName] }), e54.length > 200)
          break;
      }
      return { lines: e54 };
    }
    return this.portPointPathingSolver ? this.portPointPathingSolver.preview() : this.netToPointPairsSolver ? this.netToPointPairsSolver.visualize() : this.escapeViaLocationSolver ? this.escapeViaLocationSolver.visualize() : this.componentTopologyGeneratorSolver ? this.componentTopologyGeneratorSolver.visualize() : this.componentDetectionSolver ? this.componentDetectionSolver.visualize() : this.preprocessSimpleRouteJsonSolver ? this.preprocessSimpleRouteJsonSolver.visualize() : {};
  }
  _getOutputHdRoutes() {
    if (((this.originalSrj.differentialPairs?.length ?? 0) > 0 || (this.originalSrj.buses ?? []).some((e54) => e54.maxLengthSkew !== undefined)) && this.lengthMatchingPostProcessingSolver) {
      const { hdRoutes: e54 } = this.lengthMatchingPostProcessingSolver.getOutput();
      return e54;
    }
    return (this.effortCleanupSolver?.solved ? this.effortCleanupSolver.getOutput() : undefined) ?? this.pipeline9JointDrcRepairSolver?.getOutput() ?? this.globalDrcForceImproveSolver?.getOutput() ?? this.traceWidthSolver?.getHdRoutesWithWidths() ?? this.traceSimplificationSolver?.simplifiedHdRoutes ?? this.highDensityStitchSolver.mergedHdRoutes;
  }
  getOriginalFixedHdRoutes() {
    return (this.originalSrj.traces ?? []).flatMap((e54, t4) => Vne(e54, t4, this.originalSrj.layerCount, this.viaDiameter, this.connMap));
  }
  getChangedPreloadedTraceSections() {
    return this.portPointPathingSolver?.getOutput().changedPreloadedTraceSections ?? [];
  }
  getPreloadedFixedRouteStateAfterHighDensity() {
    const e54 = this.getOriginalFixedHdRoutes(), t4 = this.getChangedPreloadedTraceSections(), n8 = fne({ traces: this.originalSrj.traces ?? [], fixedHdRoutes: e54, sections: t4 }), o10 = t4.length === 0 ? [] : _ne({ traces: this.originalSrj.traces ?? [], sections: t4, stitchedHdRoutes: this.highDensityStitchSolver?.mergedHdRoutes ?? [], layerCount: this.originalSrj.layerCount }), i8 = new Set(t4.map((e60) => e60.traceId)), r9 = e54.filter((e60) => i8.has(this.originalSrj.traces?.[e60.preloadedTraceIndex]?.pcb_trace_id ?? "")).map((e60) => e60.connectionName);
    return { originalFixedRoutes: e54, updatedFixedRoutes: [...this.highDensityRouteSolver?.getUpdatedFixedHdRoutes() ?? n8, ...o10], replacedConnectionNames: new Set([...this.highDensityRouteSolver?.fixedRouteReplacements.keys() ?? [], ...r9]), mutationMasks: new Map([...this.highDensityRouteSolver?.preloadedTraceMutationMasks ?? [], ...o10.map((e60) => [e60.connectionName, Array(e60.route.length - 1).fill(true)])]) };
  }
  getPreparedMutatedPreloadedTraceSections() {
    const e54 = this.getPreloadedFixedRouteStateAfterHighDensity();
    return Xne({ updatedFixedRoutes: e54.updatedFixedRoutes, regionalMutationMasks: e54.mutationMasks });
  }
  getPreloadedTraceUpdatesAfterHighDensity() {
    const e54 = this.getPreloadedFixedRouteStateAfterHighDensity(), t4 = this.getPreparedMutatedPreloadedTraceSections(), n8 = this.mutatedPreloadedTraceSimplificationSolver?.solved === true ? (({ updatedFixedRoutes: e60, sections: t10, simplifiedHdRoutes: n10 }) => {
      const o10 = new Set(t10.map((e61) => e61.connectionName)), i8 = new Map(n10.map((e61) => [e61.connectionName, e61]));
      if (i8.size !== t10.length || n10.some((e61) => !o10.has(e61.connectionName)))
        throw new Error(`Pipeline9 trace simplification changed the mutation-section set (expected ${t10.length}, got ${n10.length})`);
      const r9 = new Map, s7 = new Set;
      for (const e61 of t10) {
        const t11 = i8.get(e61.connectionName);
        if (!t11)
          throw new Error(`Pipeline9 trace simplification lost mutation section "${e61.connectionName}"`);
        const n11 = t11.route[0], o11 = t11.route.at(-1);
        if (!(n11 && o11 && kne(n11, e61.section.start.point) && kne(o11, e61.section.end.point)))
          throw new Error(`Pipeline9 trace simplification changed mutation-section boundary "${e61.connectionName}"`);
        const a9 = Ene(e61.section, t11), c5 = e61.section.sourceRoutes[0];
        s7.add(c5.connectionName);
        for (const t12 of e61.section.sourceRoutes) {
          if (r9.has(t12.connectionName))
            throw new Error(`Pipeline9 attempted to simplify fixed route "${t12.connectionName}" more than once`);
          r9.set(t12.connectionName, a9);
        }
      }
      return e60.flatMap((e61) => {
        const t11 = r9.get(e61.connectionName);
        return t11 ? s7.has(e61.connectionName) ? [t11] : [] : [e61];
      });
    })({ updatedFixedRoutes: t4.normalizedFixedRoutes, sections: t4.sections, simplifiedHdRoutes: this.mutatedPreloadedTraceSimplificationSolver.simplifiedHdRoutes }) : e54.updatedFixedRoutes;
    return (({ originalTraces: e60, originalFixedRoutes: t10, updatedFixedRoutes: n10, replacedConnectionNames: o10, layerCount: i8, defaultViaHoleDiameter: r9, obstacles: s7, connMap: a9 }) => {
      const c5 = new Map, l5 = new Map;
      for (const e61 of t10) {
        const t11 = c5.get(e61.preloadedTraceIndex) ?? [];
        t11.push(e61), c5.set(e61.preloadedTraceIndex, t11);
      }
      for (const e61 of n10) {
        const t11 = l5.get(e61.preloadedTraceIndex) ?? [];
        t11.push(e61), l5.set(e61.preloadedTraceIndex, t11);
      }
      const h5 = [];
      return { updatedPreloadedTraces: e60.map((e61, t11) => {
        const n11 = (c5.get(t11) ?? []).sort(one);
        if (!n11.some((e63) => o10.has(e63.connectionName)))
          return e61;
        const d9 = (l5.get(t11) ?? []).sort(one), u9 = e61.route.some((e63) => e63.route_type === "through_obstacle"), p9 = { ...e61, __replaces_pcb_trace_id: e61.pcb_trace_id, route: u9 ? ane({ trace: e61, originalTraceRoutes: n11, updatedTraceRoutes: d9, layerCount: i8, defaultViaHoleDiameter: r9, obstacles: s7, connMap: a9 }) : rne({ trace: e61, updatedTraceRoutes: d9, layerCount: i8, defaultViaHoleDiameter: r9, obstacles: s7, connMap: a9 }) };
        return h5.push(p9), p9;
      }), mutatedPreloadedTraces: h5 };
    })({ originalTraces: this.originalSrj.traces ?? [], originalFixedRoutes: e54.originalFixedRoutes, updatedFixedRoutes: n8, replacedConnectionNames: e54.replacedConnectionNames, layerCount: this.originalSrj.layerCount, defaultViaHoleDiameter: this.viaHoleDiameter, obstacles: this.originalSrj.obstacles, connMap: this.connMap });
  }
  getSrjWithMaterializedPreloadedTraces() {
    return { ...this.srjWithPointPairs, traces: this.getPreloadedTraceUpdatesAfterHighDensity().updatedPreloadedTraces };
  }
  getUpdatedPreloadedTraces() {
    return this.pipeline9JointDrcRepairSolver?.getUpdatedPreloadedTraces() ?? this.getPreloadedTraceUpdatesAfterHighDensity().updatedPreloadedTraces;
  }
  getMutatedPreloadedTraces() {
    return this.pipeline9JointDrcRepairSolver?.getMutatedPreloadedTraces() ?? this.getPreloadedTraceUpdatesAfterHighDensity().mutatedPreloadedTraces;
  }
  getNewTracesBeforePowerExpansion() {
    if (!this.highDensityRouteSolver)
      throw new Error("Cannot get new traces before high-density routing");
    const e54 = Cte({ connections: this.netToPointPairsSolver?.newConnections ?? [], originalConnections: this.originalSrj.connections, hdRoutes: bne(this._getOutputHdRoutes()), layerCount: this.srj.layerCount, obstacles: this.srj.obstacles, defaultViaHoleDiameter: this.viaHoleDiameter, connMap: this.connMap });
    return cne(e54, this.originalSrj.traces ?? []);
  }
  getPowerTraceExpansionFixedTraces() {
    if (!this.powerTraceExpansionSolver)
      throw new Error("Pipeline9 invariant violated: solved pipeline is missing the unconditional power-trace expansion solver");
    return this.powerTraceExpansionSolver.inputSrj.fixedTraces;
  }
  getOutputSimplifiedPcbTraces() {
    if (!this.solved)
      throw new Error("Cannot get output before solving is complete");
    if (!this.powerTraceExpansionSolver)
      throw new Error("Pipeline9 invariant violated: solved pipeline is missing the unconditional power-trace expansion solver");
    return [...this.getPowerTraceExpansionFixedTraces().filter((e54) => e54.__replaces_pcb_trace_id !== undefined), ...this.powerTraceExpansionSolver.getOutput()];
  }
  getOutputSimpleRouteJson() {
    if (!this.solved)
      throw new Error("Cannot get output before solving is complete");
    if (!this.powerTraceExpansionSolver)
      throw new Error("Pipeline9 invariant violated: solved pipeline is missing the unconditional power-trace expansion solver");
    const e54 = [...this.getPowerTraceExpansionFixedTraces(), ...this.powerTraceExpansionSolver.getOutput()];
    return { ...this.originalSrj, traces: e54 };
  }
};
var rre = String("0.0.1038");
var sre = ({ nodeWithPortPoints: e54, obstacleMargin: t4, traceWidth: n8, viaDiameter: o10 }) => {
  const i8 = ro(e54), r9 = t4 + Math.max(n8, o10) / 2 + 0.000001;
  return { minX: e54.center.x + 8 * (i8.minX - e54.center.x) - r9, maxX: e54.center.x + 8 * (i8.maxX - e54.center.x) + r9, minY: e54.center.y + 8 * (i8.minY - e54.center.y) - r9, maxY: e54.center.y + 8 * (i8.maxY - e54.center.y) + r9 };
};
var are = (e54, t4) => {
  const n8 = (e54.ccwRotationDegrees ?? 0) * Math.PI / 180, o10 = Math.abs(Math.cos(n8)), i8 = Math.abs(Math.sin(n8)), r9 = e54.width / 2, s7 = e54.height / 2, a9 = Math.max(r9, r9 * o10 + s7 * i8), c5 = Math.max(s7, r9 * i8 + s7 * o10);
  return e54.center.x - a9 <= t4.maxX && e54.center.x + a9 >= t4.minX && e54.center.y - c5 <= t4.maxY && e54.center.y + c5 >= t4.minY;
};
var cre = (e54, t4) => {
  for (const n8 of [t4.connectionName, t4.rootConnectionName, t4.portPointId, t4.pcb_port_id, t4.prevPortPointId, t4.nextPortPointId])
    n8 !== undefined && e54.add(n8);
};
var lre = (e54, t4) => Object.fromEntries(Object.entries(e54.netMap).flatMap(([e60, n8]) => {
  const o10 = n8.filter((e61) => t4.has(e61));
  return o10.length > 0 || t4.has(e60) ? [[e60, o10]] : [];
}));
var hre = ({ obstacle: e54, connectedTo: t4, preserveRotation: n8 }) => ({ type: "rect", layers: e54.layers, ...e54.zLayers === undefined ? {} : { zLayers: e54.zLayers }, ...e54.__zLayers === undefined ? {} : { __zLayers: e54.__zLayers }, center: e54.center, width: e54.width, height: e54.height, ...n8 && e54.ccwRotationDegrees !== undefined ? { ccwRotationDegrees: e54.ccwRotationDegrees } : {}, connectedTo: t4, ...e54.circuitJsonMetadata === undefined ? {} : { circuitJsonMetadata: e54.circuitJsonMetadata } });
function dre({ nodeWithPortPoints: e54, connMap: t4, obstacles: n8, obstacleMargin: o10, traceWidth: i8, viaDiameter: r9 }) {
  const s7 = sre({ nodeWithPortPoints: e54, obstacleMargin: o10, traceWidth: i8, viaDiameter: r9 }), a9 = new Set;
  for (const t10 of e54.portPoints)
    cre(a9, t10);
  for (const t10 of e54.portPointsInPairs ?? [])
    cre(a9, t10[0]), cre(a9, t10[1]);
  const c5 = n8.flatMap((n10) => {
    if (!are(n10, s7))
      return [];
    const o11 = (({ obstacle: e60, nodeWithPortPoints: t10, connMap: n11 }) => {
      const o12 = new Set(t10.portPoints.flatMap((e61) => {
        const t11 = n11.getNetConnectedToId(e61.rootConnectionName ?? e61.connectionName) ?? e61.rootConnectionName ?? e61.connectionName;
        return [e61.connectionName, t11];
      })), i9 = new Set(e60.connectedTo.filter((e61) => o12.has(e61))), r10 = new Map;
      for (const e61 of o12) {
        const t11 = n11.getNetConnectedToId(e61) ?? e61, o13 = r10.get(t11) ?? [];
        o13.push(e61), r10.set(t11, o13);
      }
      for (const t11 of r10.values()) {
        if ([...i9].some((e61) => t11.some((t12) => t12 === e61 || n11.areIdsConnected(t12, e61))))
          continue;
        const o13 = e60.connectedTo.find((e61) => t11.some((t12) => t12 === e61 || n11.areIdsConnected(t12, e61)));
        o13 !== undefined && i9.add(o13);
      }
      return [...i9];
    })({ obstacle: n10, nodeWithPortPoints: e54, connMap: t4 });
    for (const e60 of o11)
      a9.add(e60);
    return [hre({ obstacle: n10, connectedTo: o11, preserveRotation: true })];
  });
  return { connectivityNetMap: lre(t4, a9), obstacles: c5 };
}
var ure = (...e54) => {
  const t4 = new Map;
  for (const n8 of e54)
    for (const [e60, o10] of Object.entries(n8)) {
      const n10 = t4.get(e60) ?? new Set;
      for (const e61 of o10)
        n10.add(e61);
      t4.set(e60, n10);
    }
  return Object.fromEntries([...t4].map(([e60, t10]) => [e60, [...t10]]));
};
function pre({ nodeWithPortPoints: e54, connMap: t4, colorMap: n8, obstacles: o10, obstacleMargin: i8, traceWidth: r9, viaDiameter: s7 }) {
  const a9 = sre({ nodeWithPortPoints: e54, obstacleMargin: i8, traceWidth: r9, viaDiameter: s7 }), c5 = ((e60) => [...new Set(e60.portPoints.map((e61) => e61.connectionName))])(e54), l5 = o10.flatMap((e60) => {
    if (!are(e60, a9))
      return [];
    const n10 = c5.filter((n11) => e60.connectedTo.some((e61) => e61 === n11 || t4.areIdsConnected(n11, e61)));
    return n10.length === 0 ? [] : [hre({ obstacle: e60, connectedTo: n10, preserveRotation: false })];
  }), h5 = new Set;
  for (const t10 of e54.portPoints)
    cre(h5, t10);
  for (const t10 of e54.portPointsInPairs ?? [])
    cre(h5, t10[0]), cre(h5, t10[1]);
  for (const e60 of l5)
    for (const t10 of [e60.circuitJsonMetadata?.pcb_smtpad_id, e60.circuitJsonMetadata?.pcb_plated_hole_id, e60.circuitJsonMetadata?.pcb_port_id, e60.circuitJsonMetadata?.pcb_via_id, ...e60.connectedTo ?? []])
      t10 !== undefined && h5.add(t10);
  return { connectivityNetMap: lre(t4, h5), colorMap: Object.fromEntries(Object.entries(n8 ?? {}).filter(([e60]) => h5.has(e60))), obstacles: l5 };
}
var mre = "https://hd-cache2.tscircuit.com";
var gre = 310000;
var fre = 1835008;
var _re = 16777216;
var yre = class extends Error {
  constructor(e54, t4) {
    super(t4), this.reason = e54, this.name = "HdCache2RequestError";
  }
};
var bre = (e54) => e54 instanceof Error ? e54.message : String(e54);
var xre = new Set(["pcb_smtpad_id", "pcb_plated_hole_id", "pcb_port_id", "pcb_via_id", "source_component_name", "source_port_name"]);
var vre = (e54) => !(!e54 || typeof e54 != "object" || Array.isArray(e54)) && Object.entries(e54).every(([e60, t4]) => xre.has(e60) && typeof t4 == "string");
var Ire = (e54, t4) => Math.abs(e54 - t4) <= 0.000000001 * Math.max(1, Math.abs(e54), Math.abs(t4));
var Sre = 0.000001;
var Cre = (e54, t4) => {
  const n8 = t4 === "ordinary" ? Sre : 0.001, o10 = new Set;
  for (let i9 = 0;i9 < e54.route.length - 1; i9++) {
    const r9 = e54.route[i9], s7 = e54.route[i9 + 1], a9 = r9.z !== s7.z;
    if (r9.toNextSegmentType === "through_obstacle") {
      if (!a9)
        return false;
      continue;
    }
    if (r9.toNextSegmentCircuitJsonMetadata !== undefined)
      return false;
    if (!a9)
      continue;
    const c5 = [], l5 = [];
    for (const [t10, o11] of e54.vias.entries())
      Math.hypot(o11.x - r9.x, o11.y - r9.y) <= n8 && c5.push(t10), Math.hypot(o11.x - s7.x, o11.y - s7.y) <= n8 && l5.push(t10);
    if (Math.hypot(r9.x - s7.x, r9.y - s7.y) <= Sre) {
      if (c5.length === 0)
        return false;
      for (const e60 of c5)
        o10.add(e60);
    } else {
      if (t4 === "regional-fallback")
        return false;
      if (c5.length === 0 == (l5.length === 0))
        return false;
      for (const e60 of [...c5, ...l5])
        o10.add(e60);
    }
  }
  const i8 = e54.route.at(-1);
  return i8.toNextSegmentType === undefined && i8.toNextSegmentCircuitJsonMetadata === undefined && e54.vias.every((e60, t10) => o10.has(t10));
};
var Pre = (e54, t4, n8) => {
  if (!Array.isArray(e54))
    return false;
  const o10 = new Map;
  for (const e60 of t4.nodeWithPortPoints.portPoints) {
    const t10 = o10.get(e60.connectionName) ?? [];
    t10.push(e60), o10.set(e60.connectionName, t10);
  }
  const i8 = new Set(t4.nodeWithPortPoints.availableZ ?? t4.nodeWithPortPoints.portPoints.map((e60) => e60.z)), r9 = sre({ nodeWithPortPoints: t4.nodeWithPortPoints, obstacleMargin: t4.obstacleMargin, traceWidth: t4.traceWidth, viaDiameter: t4.viaDiameter }), s7 = (e60, t10) => (o10.get(t10) ?? []).some((t11) => typeof e60.x == "number" && Ire(e60.x, t11.x) && typeof e60.y == "number" && Ire(e60.y, t11.y) && e60.z === t11.z);
  for (const a10 of e54) {
    if (!a10 || typeof a10 != "object")
      return false;
    const e60 = a10;
    if (typeof e60.connectionName != "string" || e60.connectionName.length === 0 || !o10.has(e60.connectionName) || typeof e60.traceThickness != "number" || !Number.isFinite(e60.traceThickness) || e60.traceThickness <= 0 || typeof e60.viaDiameter != "number" || !Number.isFinite(e60.viaDiameter) || e60.viaDiameter <= 0 || !Ire(e60.viaDiameter, t4.viaDiameter) || !Array.isArray(e60.route) || e60.route.length < 2 || !Array.isArray(e60.vias))
      return false;
    for (const t10 of [e60.rootConnectionName, e60.startPcbPortId, e60.endPcbPortId, e60.regionId])
      if (t10 !== undefined && typeof t10 != "string")
        return false;
    for (const o11 of e60.route) {
      if (!o11 || typeof o11 != "object")
        return false;
      const e61 = o11;
      if (typeof e61.x != "number" || !Number.isFinite(e61.x) || typeof e61.y != "number" || !Number.isFinite(e61.y) || e61.x < r9.minX || e61.x > r9.maxX || e61.y < r9.minY || e61.y > r9.maxY || typeof e61.z != "number" || !Number.isInteger(e61.z) || e61.z < 0 || e61.z >= t4.layerCount || n8 === "ordinary" && !i8.has(e61.z))
        return false;
      if (e61.traceThickness !== undefined && (typeof e61.traceThickness != "number" || !Number.isFinite(e61.traceThickness) || e61.traceThickness <= 0))
        return false;
      if (e61.pcb_port_id !== undefined && typeof e61.pcb_port_id != "string")
        return false;
      if (e61.insideJumperPad !== undefined && typeof e61.insideJumperPad != "boolean")
        return false;
      if (e61.toNextSegmentType !== undefined && e61.toNextSegmentType !== "through_obstacle")
        return false;
      if (e61.toNextSegmentCircuitJsonMetadata !== undefined && !vre(e61.toNextSegmentCircuitJsonMetadata))
        return false;
    }
    const c5 = e60.route;
    if (!(n8 !== "ordinary" || s7(c5[0], e60.connectionName) && s7(c5.at(-1), e60.connectionName)))
      return false;
    for (const t10 of e60.vias) {
      if (!t10 || typeof t10 != "object")
        return false;
      const e61 = t10;
      if (typeof e61.x != "number" || !Number.isFinite(e61.x) || typeof e61.y != "number" || !Number.isFinite(e61.y) || e61.x < r9.minX || e61.x > r9.maxX || e61.y < r9.minY || e61.y > r9.maxY)
        return false;
    }
    if (!Cre(e60, n8))
      return false;
    if (e60.jumpers !== undefined) {
      if (!Array.isArray(e60.jumpers))
        return false;
      for (const t10 of e60.jumpers) {
        if (!t10 || typeof t10 != "object")
          return false;
        const e61 = t10, n10 = e61.start, o11 = e61.end;
        if (e61.route_type !== "jumper" || e61.footprint !== "0603" && e61.footprint !== "1206" && e61.footprint !== "1206x4_pair" || !n10 || typeof n10.x != "number" || !Number.isFinite(n10.x) || typeof n10.y != "number" || !Number.isFinite(n10.y) || !o11 || typeof o11.x != "number" || !Number.isFinite(o11.x) || typeof o11.y != "number" || !Number.isFinite(o11.y) || n10.x < r9.minX || n10.x > r9.maxX || n10.y < r9.minY || n10.y > r9.maxY || o11.x < r9.minX || o11.x > r9.maxX || o11.y < r9.minY || o11.y > r9.maxY)
          return false;
      }
    }
  }
  const a9 = e54;
  return n8 === "ordinary" ? ((e60, t10) => {
    const n10 = t10.portPointsInPairs ?? [];
    if (n10.length > 0) {
      for (const [t11, o12] of n10)
        if (!yz(e60, t11.connectionName, fz(t11)).has(fz(o12)))
          return false;
      return true;
    }
    const o11 = new Map;
    for (const e61 of t10.portPoints) {
      const t11 = o11.get(e61.connectionName) ?? [];
      t11.push(e61), o11.set(e61.connectionName, t11);
    }
    for (const [t11, n11] of o11)
      for (const [o12, i9] of Ws(n11))
        if (!yz(e60, t11, fz(o12)).has(fz(i9)))
          return false;
    return true;
  })(a9, t4.nodeWithPortPoints) : ((e60, t10) => {
    const n10 = (e61, t11) => {
      if (e61.z !== t11.z)
        return false;
      const n11 = e61.x - t11.x, o12 = e61.y - t11.y;
      return Math.hypot(n11, o12) <= 0.001;
    }, o11 = new Map;
    for (const i10 of e60) {
      const e61 = i10.route.some((e63, t11) => {
        const n11 = i10.route[t11 + 1];
        return !(n11 === undefined || Ire(e63.x, n11.x) && Ire(e63.y, n11.y) && e63.z === n11.z);
      }), r11 = i10.route[0], s10 = i10.route.at(-1);
      if (!e61 || !r11 || !s10)
        return false;
      const a10 = t10.portPoints.filter((e63) => e63.connectionName === i10.connectionName);
      if (!a10.some((e63) => n10(r11, e63)) || !a10.some((e63) => n10(s10, e63)))
        return false;
      const c5 = o11.get(i10.connectionName) ?? [];
      c5.push({ start: r11, end: s10 }), o11.set(i10.connectionName, c5);
    }
    const i9 = (e61, t11, i10) => {
      if (n10(t11, i10))
        return true;
      const r11 = o11.get(e61) ?? [], s10 = [], a10 = new Set;
      for (const [e63, o12] of r11.entries())
        (n10(t11, o12.start) || n10(t11, o12.end)) && (s10.push(e63), a10.add(e63));
      for (;s10.length > 0; ) {
        const e63 = r11[s10.pop()];
        if (n10(i10, e63.start) || n10(i10, e63.end))
          return true;
        for (const [t12, o12] of r11.entries())
          a10.has(t12) || (n10(e63.start, o12.start) || n10(e63.start, o12.end) || n10(e63.end, o12.start) || n10(e63.end, o12.end)) && (a10.add(t12), s10.push(t12));
      }
      return false;
    }, r10 = t10.portPointsInPairs ?? [];
    if (r10.length > 0)
      return r10.every(([e61, t11]) => i9(e61.connectionName, e61, t11));
    const s9 = new Map;
    for (const e61 of t10.portPoints) {
      const t11 = s9.get(e61.connectionName) ?? [];
      t11.push(e61), s9.set(e61.connectionName, t11);
    }
    return [...s9].every(([, e61]) => Ws(e61).every(([e63, t11]) => i9(e63.connectionName, e63, t11)));
  })(a9, t4.nodeWithPortPoints);
};
var Mre = class {
  constructor(e54, t4 = mre, n8 = {}) {
    this.autorouterVersion = e54, this.serverUrl = t4;
    const { cacheVersion: o10 } = n8;
    if (o10 !== undefined && o10.trim().length === 0)
      throw new Error("hd-cache2 cacheVersion must not be empty");
    this.cacheVersion = o10;
  }
  cacheVersion;
  stats = { batchRequestsStarted: 0, batchRequestsCompleted: 0, batchItemsStarted: 0, batchBodyBytesStarted: 0, batchMaxBodyBytes: 0, batchCacheMisses: 0, singleRequestsStarted: 0, batchInvalidLines: 0, batchUnknownRequestIds: 0, batchDuplicateRequestIds: 0 };
  solveMany(e54) {
    const t4 = e54.map((e60, t10) => this.createPendingSolve(String(t10), e60)), n8 = t4.filter((e60) => e60.serializedItem !== null), { batches: o10, singletonSolves: i8 } = this.prepareBatches(n8);
    for (const e60 of o10)
      this.fetchBatch(e60);
    for (const e60 of i8)
      this.launchSingleSolve(e60);
    return t4.map((e60) => e60.promise);
  }
  createPendingSolve(e54, t4) {
    let n8;
    const o10 = { requestId: e54, input: t4, serializedItem: null, promise: new Promise((e60) => {
      n8 = e60;
    }), resolve: n8, settled: false, singleSolveStarted: false };
    try {
      o10.serializedItem = JSON.stringify({ requestId: e54, input: t4 });
    } catch (e60) {
      this.settleWithFallback(o10, "request_serialization_error", bre(e60));
    }
    return o10;
  }
  settle(e54, t4) {
    e54.settled || (e54.settled = true, e54.resolve(t4));
  }
  settleWithFallback(e54, t4, n8) {
    this.settle(e54, { kind: "local-fallback", reason: t4, error: n8 });
  }
  parseSuccessfulResponse(e54, t4) {
    if (!e54 || typeof e54 != "object" || Array.isArray(e54))
      throw new yre("invalid_response", "hd-cache2 returned a non-object response");
    const n8 = e54;
    if (n8.ok !== true)
      throw new yre("remote_error", typeof n8.message == "string" ? n8.message : "hd-cache2 returned an unsuccessful response");
    if (n8.autorouterVersion !== this.autorouterVersion)
      throw new yre("version_mismatch", `hd-cache2 returned autorouter version ${String(n8.autorouterVersion)}, expected ${this.autorouterVersion}`);
    if (n8.cacheVersion !== this.cacheVersion)
      throw new yre("cache_version_mismatch", `hd-cache2 returned cache version ${String(n8.cacheVersion)}, expected ${String(this.cacheVersion)}`);
    if (n8.source !== "cache" && n8.source !== "solver")
      throw new yre("invalid_response", "hd-cache2 returned an invalid cache source");
    if (n8.solutionStage !== "ordinary" && n8.solutionStage !== "regional-fallback")
      throw new yre("invalid_response", "hd-cache2 returned an invalid solution stage");
    if (n8.solutionStage === "regional-fallback" && (!t4.enableRegionalFallback || typeof n8.ordinaryFailure != "string" || n8.ordinaryFailure.length === 0))
      throw new yre("invalid_response", "hd-cache2 returned invalid regional fallback metadata");
    if (n8.solutionStage === "ordinary" && Object.prototype.hasOwnProperty.call(n8, "ordinaryFailure"))
      throw new yre("invalid_response", "hd-cache2 returned regional metadata on an ordinary result");
    if (n8.solutionStage === "ordinary" && n8.status === "failed" && t4.enableRegionalFallback)
      throw new yre("invalid_response", "hd-cache2 returned an intermediate ordinary failure");
    if (n8.status === "solved" && Pre(n8.routes, t4, n8.solutionStage))
      return n8;
    if (n8.status === "failed" && typeof n8.error == "string" && n8.error.length > 0)
      return n8;
    throw new yre("invalid_response", "hd-cache2 returned an invalid solve result");
  }
  parseBatchCacheMiss(e54) {
    if (e54.ok !== false || e54.code !== "CACHE_MISS")
      return null;
    if (e54.autorouterVersion !== this.autorouterVersion)
      throw new yre("version_mismatch", `hd-cache2 returned autorouter version ${String(e54.autorouterVersion)}, expected ${this.autorouterVersion}`);
    if (e54.cacheVersion !== this.cacheVersion)
      throw new yre("cache_version_mismatch", `hd-cache2 returned cache version ${String(e54.cacheVersion)}, expected ${String(this.cacheVersion)}`);
    if (typeof e54.message != "string")
      throw new yre("invalid_response", "hd-cache2 returned an invalid cache miss response");
    return e54;
  }
  async fetchSingle(e54) {
    const t4 = new AbortController;
    let n8 = false;
    const o10 = setTimeout(() => {
      n8 = true, t4.abort(new Error("hd-cache2 transport timed out after 310000ms"));
    }, gre);
    o10.unref?.();
    try {
      const n10 = { autorouterVersion: this.autorouterVersion, ...this.cacheVersion === undefined ? {} : { cacheVersion: this.cacheVersion }, input: e54.input };
      let o11;
      try {
        o11 = JSON.stringify(n10);
      } catch (e60) {
        throw new yre("request_serialization_error", bre(e60));
      }
      const r9 = await fetch((i8 = this.serverUrl, /\/solve\/?$/.test(i8) ? i8.replace(/\/+$/, "") : `${i8.replace(/\/+$/, "")}/solve`), { method: "POST", headers: { accept: "application/json", "content-type": "application/json" }, body: o11, signal: t4.signal }), s7 = await r9.text();
      let a9 = null;
      try {
        a9 = s7 ? JSON.parse(s7) : null;
      } catch {
        if (!r9.ok)
          throw new yre("http_error", `hd-cache2 request failed with status ${r9.status}`);
        throw new yre("invalid_json", `hd-cache2 returned invalid JSON with status ${r9.status}`);
      }
      if (!r9.ok) {
        const e60 = a9 && typeof a9 == "object" && "message" in a9 && typeof a9.message == "string" ? a9.message : `hd-cache2 request failed with status ${r9.status}`;
        throw new yre("http_error", e60);
      }
      this.settle(e54, { kind: "remote", response: this.parseSuccessfulResponse(a9, e54.input) });
    } catch (t10) {
      const o11 = t10 instanceof yre ? t10.reason : n8 ? "transport_timeout" : "transport_error";
      this.settleWithFallback(e54, o11, bre(t10));
    } finally {
      clearTimeout(o10);
    }
    var i8;
  }
  launchSingleSolve(e54) {
    e54.singleSolveStarted || e54.settled || (e54.singleSolveStarted = true, this.stats.singleRequestsStarted += 1, this.fetchSingle(e54));
  }
  handleBatchResponseLine(e54, t4, n8) {
    if (e54.trim().length === 0)
      return;
    if (e54.length > _re)
      throw new yre("response_too_large", "hd-cache2 returned an oversized batch result line");
    let o10;
    try {
      o10 = JSON.parse(e54);
    } catch {
      return void (this.stats.batchInvalidLines += 1);
    }
    if (!o10 || typeof o10 != "object" || Array.isArray(o10))
      return void (this.stats.batchInvalidLines += 1);
    const i8 = o10, r9 = i8.requestId;
    if (typeof r9 != "string")
      return void (this.stats.batchInvalidLines += 1);
    const s7 = t4.get(r9);
    if (s7)
      if (n8.has(r9))
        this.stats.batchDuplicateRequestIds += 1;
      else {
        n8.add(r9);
        try {
          if (this.parseBatchCacheMiss(i8))
            return this.stats.batchCacheMisses += 1, void this.launchSingleSolve(s7);
          this.settle(s7, { kind: "remote", response: this.parseSuccessfulResponse(i8, s7.input) });
        } catch (e60) {
          this.stats.batchInvalidLines += 1, this.settleWithFallback(s7, e60 instanceof yre ? e60.reason : "invalid_response", bre(e60));
        }
      }
    else
      this.stats.batchUnknownRequestIds += 1;
  }
  async readBatchResponse(e54, t4) {
    if (!e54.body)
      throw new yre("invalid_response", "hd-cache2 returned an empty batch response body");
    const n8 = new Map(t4.items.map((e60) => [e60.requestId, e60])), o10 = new Set, i8 = new TextDecoder, r9 = e54.body.getReader();
    let s7 = "";
    for (;o10.size < t4.items.length; ) {
      const { done: e60, value: t10 } = await r9.read();
      if (s7 += i8.decode(t10, { stream: !e60 }), s7.length > _re && !s7.includes(`
`))
        throw new yre("response_too_large", "hd-cache2 returned an oversized unterminated batch result line");
      let a9 = s7.indexOf(`
`);
      for (;a9 >= 0; ) {
        const e61 = s7.slice(0, a9);
        s7 = s7.slice(a9 + 1), this.handleBatchResponseLine(e61, n8, o10), a9 = s7.indexOf(`
`);
      }
      if (e60) {
        s7.trim().length > 0 && this.handleBatchResponseLine(s7, n8, o10);
        break;
      }
    }
    if (o10.size !== t4.items.length)
      for (const e60 of t4.items)
        o10.has(e60.requestId) || this.settleWithFallback(e60, "missing_response", `hd-cache2 batch ended without result ${e60.requestId}`);
    else
      await r9.cancel().catch(() => {});
  }
  async fetchBatch(e54) {
    const t4 = new AbortController;
    let n8 = false;
    const o10 = setTimeout(() => {
      n8 = true, t4.abort(new Error("hd-cache2 batch transport timed out after 310000ms"));
    }, gre);
    o10.unref?.(), this.stats.batchRequestsStarted += 1, this.stats.batchItemsStarted += e54.items.length, this.stats.batchBodyBytesStarted += e54.bodyBytes, this.stats.batchMaxBodyBytes = Math.max(this.stats.batchMaxBodyBytes, e54.bodyBytes);
    try {
      const n10 = await fetch(((e60) => {
        const t10 = e60.replace(/\/+$/, "");
        return /\/solve-batch$/.test(t10) ? t10 : /\/solve$/.test(t10) ? t10.replace(/\/solve$/, "/solve-batch") : `${t10}/solve-batch`;
      })(this.serverUrl), { method: "POST", headers: { accept: "application/x-ndjson", "content-type": "application/json" }, body: e54.body, signal: t4.signal });
      if (!n10.ok) {
        const e60 = await n10.text().catch(() => "");
        let t10 = `hd-cache2 batch request failed with status ${n10.status}`;
        try {
          const n11 = e60 ? JSON.parse(e60) : null;
          n11 && typeof n11 == "object" && "message" in n11 && typeof n11.message == "string" && (t10 = n11.message);
        } catch {}
        throw new yre("http_error", t10);
      }
      await this.readBatchResponse(n10, e54);
    } catch (t10) {
      const o11 = t10 instanceof yre ? t10.reason : n8 ? "transport_timeout" : "transport_error";
      for (const n10 of e54.items)
        n10.singleSolveStarted || this.settleWithFallback(n10, o11, bre(t10));
    } finally {
      clearTimeout(o10), this.stats.batchRequestsCompleted += 1;
    }
  }
  prepareBatches(e54) {
    const t4 = new TextEncoder, n8 = this.cacheVersion === undefined ? "" : `,"cacheVersion":${JSON.stringify(this.cacheVersion)}`, o10 = `{"autorouterVersion":${JSON.stringify(this.autorouterVersion)}${n8},"items":[`, i8 = t4.encode(o10 + "]}").byteLength, r9 = [], s7 = [];
    let a9 = [], c5 = i8;
    const l5 = () => {
      a9.length !== 0 && (r9.push({ body: `${o10}${a9.map((e60) => e60.serializedItem).join(",")}]}`, bodyBytes: c5, items: a9 }), a9 = [], c5 = i8);
    };
    for (const n10 of e54) {
      const e60 = t4.encode(n10.serializedItem).byteLength, o11 = a9.length === 0 ? 0 : 1;
      i8 + e60 > fre ? (l5(), s7.push(n10)) : ((a9.length >= 100 || c5 + o11 + e60 > fre) && l5(), a9.push(n10), c5 += (a9.length === 1 ? 0 : 1) + e60);
    }
    return l5(), { batches: r9, singletonSolves: s7 };
  }
};
var wre = "ordinary_then_regional_without_fixed_copper_v1";
var Nre = class extends Loe {
  autorouterVersion;
  hdCache2ServerUrl;
  hdCache2CacheVersion;
  requestTimeoutMs;
  hdCache2Client;
  launchedRemoteSolves = false;
  waitingForRemoteNode = null;
  remoteRequestByNode = new Map;
  remoteResultByNode = new Map;
  logicallyTimedOutNodes = new Set;
  constructor({ autorouterVersion: e54, hdCache2ServerUrl: t4, hdCache2CacheVersion: n8, requestTimeoutMs: o10, ...i8 }) {
    if (super(i8), i8.effort !== 1)
      throw new Error(`Pipeline9 networked high-density routing requires effort=1, received ${i8.effort}`);
    if (this.requestTimeoutMs = o10 ?? 30000, !Number.isFinite(this.requestTimeoutMs) || this.requestTimeoutMs <= 0)
      throw new Error(`Pipeline9 network request timeout must be a positive number, received ${this.requestTimeoutMs}`);
    this.autorouterVersion = e54, this.hdCache2ServerUrl = t4 ?? mre, this.hdCache2CacheVersion = n8, this.hdCache2Client = new Mre(this.autorouterVersion, this.hdCache2ServerUrl, { cacheVersion: n8 }), this.pendingEffects = [], this.stats = { ...this.stats, remoteRequestsStarted: 0, remoteRequestsCompleted: 0, remoteBatchRequestsStarted: 0, remoteBatchRequestsCompleted: 0, remoteBatchItemsStarted: 0, remoteBatchBodyBytesStarted: 0, remoteBatchMaxBodyBytes: 0, remoteBatchCacheMisses: 0, remoteSingleRequestsStarted: 0, remoteBatchInvalidLines: 0, remoteBatchUnknownRequestIds: 0, remoteBatchDuplicateRequestIds: 0, remoteCacheHits: 0, remoteSolverResults: 0, remoteSolvedResults: 0, remoteFailedResults: 0, remoteOrdinaryResults: 0, remoteRegionalFallbackResults: 0, remoteRegionalFallbackResultsApplied: 0, remoteRegionalFallbackResultsDeferredToLocal: 0, remoteTransportFallbacks: 0, remoteLogicalTimeoutFallbacks: 0, remoteFallbackReasonCounts: {} };
  }
  getSolverName() {
    return "Pipeline9NetworkedHighDensitySolver";
  }
  async waitForAllRemoteRequests() {
    const e54 = [...this.remoteRequestByNode.values()];
    e54.length !== 0 ? (await Promise.all(e54.map(({ promise: e60 }) => e60)), this.syncClientStats()) : this.syncClientStats();
  }
  createNodeInput(e54) {
    const t4 = this.enableRegionalFallback ? dre({ nodeWithPortPoints: e54, connMap: this.connMap, obstacles: this.obstacles, obstacleMargin: this.obstacleMargin, traceWidth: this.traceWidth, viaDiameter: this.viaDiameter }) : { connectivityNetMap: {}, obstacles: [] }, n8 = pre({ nodeWithPortPoints: e54, connMap: this.connMap, colorMap: this.colorMap, obstacles: this.enableRegionalFallback ? t4.obstacles : this.obstacles, obstacleMargin: this.obstacleMargin, traceWidth: this.traceWidth, viaDiameter: this.viaDiameter });
    return { solvePolicy: wre, enableRegionalFallback: this.enableRegionalFallback, nodeWithPortPoints: e54, connectivityNetMap: ure(n8.connectivityNetMap, t4.connectivityNetMap), colorMap: n8.colorMap, viaDiameter: this.viaDiameter, traceWidth: this.traceWidth, obstacleMargin: this.obstacleMargin, effort: 1, obstacles: n8.obstacles, boardGeometry: this.boardGeometry, regionalObstacles: t4.obstacles, layerCount: this.layerCount, nodePf: this.nodePfById.get(e54.capacityMeshNodeId) ?? null };
  }
  syncClientStats() {
    const e54 = this.hdCache2Client.stats;
    this.stats.remoteBatchRequestsStarted = e54.batchRequestsStarted, this.stats.remoteBatchRequestsCompleted = e54.batchRequestsCompleted, this.stats.remoteBatchItemsStarted = e54.batchItemsStarted, this.stats.remoteBatchBodyBytesStarted = e54.batchBodyBytesStarted, this.stats.remoteBatchMaxBodyBytes = e54.batchMaxBodyBytes, this.stats.remoteBatchCacheMisses = e54.batchCacheMisses, this.stats.remoteSingleRequestsStarted = e54.singleRequestsStarted, this.stats.remoteBatchInvalidLines = e54.batchInvalidLines, this.stats.remoteBatchUnknownRequestIds = e54.batchUnknownRequestIds, this.stats.remoteBatchDuplicateRequestIds = e54.batchDuplicateRequestIds;
  }
  recordFallbackReason(e54) {
    const t4 = this.stats.remoteFallbackReasonCounts;
    t4[e54] = (t4[e54] ?? 0) + 1;
  }
  trackRemoteSolve(e54, t4) {
    const n8 = performance.now() + this.requestTimeoutMs;
    this.stats.remoteRequestsStarted += 1;
    const o10 = t4.then((t10) => {
      const n10 = this.logicallyTimedOutNodes.has(e54);
      n10 || this.remoteResultByNode.set(e54, t10), t10.kind === "remote" ? (t10.response.source === "cache" && (this.stats.remoteCacheHits += 1), t10.response.source === "solver" && (this.stats.remoteSolverResults += 1), t10.response.status === "solved" ? this.stats.remoteSolvedResults += 1 : this.stats.remoteFailedResults += 1) : n10 || (this.stats.remoteTransportFallbacks += 1, this.recordFallbackReason(t10.reason)), this.stats.remoteRequestsCompleted += 1, this.syncClientStats();
    });
    this.remoteRequestByNode.set(e54, { promise: o10, deadlineAt: n8 });
  }
  launchRemoteSolves() {
    const e54 = [], t4 = [...this.unsolvedNodePortPoints].reverse();
    for (const n10 of t4)
      try {
        e54.push({ node: n10, input: this.createNodeInput(n10) });
      } catch (e60) {
        this.trackRemoteSolve(n10, Promise.resolve({ kind: "local-fallback", reason: "request_serialization_error", error: e60 instanceof Error ? e60.message : String(e60) }));
      }
    const n8 = this.hdCache2Client.solveMany(e54.map(({ input: e60 }) => e60));
    for (const [t10, o10] of n8.entries())
      this.trackRemoteSolve(e54[t10].node, o10);
    this.syncClientStats();
  }
  async waitForCurrentRemoteNode(e54, t4) {
    const n8 = t4.deadlineAt - performance.now();
    if (n8 <= 0)
      return void this.recordLogicalTimeout(e54);
    let o10;
    const i8 = await Promise.race([t4.promise.then(() => "request-settled"), new Promise((e60) => {
      o10 = setTimeout(() => e60("logical-timeout"), n8);
    })]);
    o10 !== undefined && clearTimeout(o10), i8 === "logical-timeout" && this.recordLogicalTimeout(e54);
  }
  recordLogicalTimeout(e54) {
    this.logicallyTimedOutNodes.add(e54), this.stats.remoteLogicalTimeoutFallbacks += 1, this.stats.remoteTransportFallbacks += 1, this.recordFallbackReason("logical_timeout");
  }
  startRegularSolver(e54) {
    const t4 = this.remoteResultByNode.get(e54);
    if (!t4) {
      const t10 = this.remoteRequestByNode.get(e54);
      if (t10) {
        this.waitingForRemoteNode = e54;
        const n8 = this.waitForCurrentRemoteNode(e54, t10);
        n8.then(() => {
          this.waitingForRemoteNode === e54 && (this.pendingEffects = []);
        });
        const o10 = { name: `hd-cache2:${e54.capacityMeshNodeId}`, promise: n8 };
        return void (this.pendingEffects = [o10]);
      }
      return void super.startRegularSolver(e54);
    }
    this.applyRemoteResultToRegularNode(e54, t4);
  }
  applyRemoteResultToRegularNode(e54, t4) {
    if (t4.kind !== "local-fallback") {
      if (this.stats.regularNodeCount = Number(this.stats.regularNodeCount ?? 0) + 1, this.activeNode = e54, t4.response.solutionStage === "regional-fallback") {
        if (this.stats.remoteRegionalFallbackResults += 1, !this.canUseNoFixedCopperRegionalResult(e54))
          return this.stats.remoteRegionalFallbackResultsDeferredToLocal += 1, void this.finishRegularSolverFailure(t4.response.ordinaryFailure);
        this.stats.remoteRegionalFallbackResultsApplied += 1, this.stats.fallbackNodeCount = Number(this.stats.fallbackNodeCount ?? 0) + 1;
      } else
        this.stats.remoteOrdinaryResults += 1;
      if (t4.response.status === "failed")
        return this.error = t4.response.error, this.failed = true, void (this.activeNode = null);
      this.finishActiveNode(t4.response.routes);
    } else
      super.startRegularSolver(e54);
  }
  canUseNoFixedCopperRegionalResult(e54) {
    const t4 = { ...koe(e54, this.connMap), availableZ: Array.from({ length: this.layerCount }, (e60, t10) => t10) }, n8 = Rne(t4, this.getUpdatedFixedHdRoutes());
    return n8.fixedRouteSectionsByConnectionName.size === 0 && n8.fixedObstacleRoutes.length === 0;
  }
  _step() {
    if (this.syncClientStats(), this.launchedRemoteSolves || (this.launchedRemoteSolves = true, this.launchRemoteSolves()), this.waitingForRemoteNode) {
      const e54 = this.waitingForRemoteNode;
      if (this.logicallyTimedOutNodes.has(e54))
        return this.waitingForRemoteNode = null, this.pendingEffects = [], void super.startRegularSolver(e54);
      const t4 = this.remoteResultByNode.get(e54);
      if (!t4)
        return;
      return this.waitingForRemoteNode = null, this.pendingEffects = [], void this.applyRemoteResultToRegularNode(e54, t4);
    }
    super._step();
  }
};
function Are(e54) {
  const t4 = `${e54.connectionName}:source-${e54.sourcePointIndex}`;
  return { boundaryExitPointId: `fanout-exit:${t4}`, planeExitPointId: `fanout-plane:${t4}`, traceId: `fanout:${t4}`, viaObstacleId: `fanout-via:${t4}`, planeEndpointPointId: `fanout-plane-endpoint-point:${t4}`, planeEndpointTraceId: `fanout-plane-endpoint:${t4}`, planeEndpointViaObstacleId: `fanout-plane-endpoint-via:${t4}` };
}
function Ore(e54, t4, n8 = false) {
  const o10 = n8 ? e54.planeEndpointVia : e54.via;
  if (!o10)
    return null;
  const i8 = o10.spanLayers.map((n10) => {
    const o11 = t4.indexOf(n10);
    if (o11 < 0)
      throw new Error(`FanoutSolver: via for "${e54.connectionName}" uses unknown layer "${n10}"`);
    return o11;
  }), r9 = Are(e54);
  return { obstacleId: n8 ? r9.planeEndpointViaObstacleId : r9.viaObstacleId, type: "rect", center: o10.center, width: o10.diameter, height: o10.diameter, layers: o10.spanLayers, zLayers: i8, __zLayers: i8, connectedTo: [e54.connectionName, e54.trace.pcb_trace_id] };
}
function kre(e54) {
  const { inputSrj: t4, plans: n8, layerNames: o10 } = e54, i8 = t4.connections.map((e60) => ({ ...e60, pointsToConnect: e60.pointsToConnect.map((e61) => ({ ...e61 })) })), r9 = [], s7 = new Set;
  for (const e60 of n8) {
    const t10 = i8[e60.connectionIndex];
    if (!t10)
      throw new Error(`FanoutSolver: output connection index ${e60.connectionIndex} is missing`);
    const n10 = Are(e60);
    t10.pointsToConnect[e60.sourcePointIndex] = { x: e60.exitPoint.x, y: e60.exitPoint.y, layer: e60.targetLayer, pointId: e60.termination.type === "plane" ? n10.planeExitPointId : n10.boundaryExitPointId }, e60.termination.type === "plane" && s7.add(e60.connectionName);
    const a10 = Ore(e60, o10);
    a10 && r9.push(a10);
    const c9 = Ore(e60, o10, true);
    c9 && r9.push(c9);
  }
  const a9 = n8.flatMap((e60) => [e60.trace, ...e60.planeEndpointTrace ? [e60.planeEndpointTrace] : []]), c5 = a9.flatMap((e60) => e60.route.filter((e61) => ("x" in e61) && ("y" in e61))), l5 = Math.max(t4.defaultObstacleMargin ?? 0, t4.minTraceWidth), h5 = c5.length === 0 ? { ...t4.bounds } : { minX: Math.min(t4.bounds.minX, ...c5.map((e60) => e60.x - l5)), maxX: Math.max(t4.bounds.maxX, ...c5.map((e60) => e60.x + l5)), minY: Math.min(t4.bounds.minY, ...c5.map((e60) => e60.y - l5)), maxY: Math.max(t4.bounds.maxY, ...c5.map((e60) => e60.y + l5)) };
  return { ...t4, fanoutPlaneConnectivity: n8.flatMap((e60) => e60.termination.type === "plane" ? [{ connectionName: e60.connectionName, layer: e60.termination.layer }] : []), bounds: h5, connections: i8.filter((e60) => !s7.has(e60.name)), buses: t4.buses?.map((e60) => ({ ...e60, connectionNames: e60.connectionNames.filter((e61) => !s7.has(e61)) })).filter((e60) => e60.connectionNames.length > 0), obstacles: [...t4.obstacles.map((e60) => ({ ...e60, center: { ...e60.center }, layers: [...e60.layers], connectedTo: [...e60.connectedTo] })), ...r9], traces: [...(t4.traces ?? []).map((e60) => ({ ...e60, route: e60.route.map((e61) => ({ ...e61 })) })), ...a9] };
}
var Dre = 0.000000001;
function Lre(e54) {
  return e54.shape === "circle";
}
function zre(e54, t4) {
  const n8 = -(t4.ccwRotationDegrees ?? 0) * Math.PI / 180, o10 = e54.x - t4.center.x, i8 = e54.y - t4.center.y;
  return { x: o10 * Math.cos(n8) - i8 * Math.sin(n8), y: o10 * Math.sin(n8) + i8 * Math.cos(n8) };
}
function Bre(e54, t4) {
  return Math.hypot(e54.x - t4.x, e54.y - t4.y);
}
function Fre(e54, t4, n8) {
  const o10 = n8.x - t4.x, i8 = n8.y - t4.y, r9 = o10 * o10 + i8 * i8, s7 = r9 < Dre ? 0 : ((e54.x - t4.x) * o10 + (e54.y - t4.y) * i8) / r9, a9 = Math.max(0, Math.min(1, s7));
  return Math.hypot(e54.x - (t4.x + a9 * o10), e54.y - (t4.y + a9 * i8));
}
function jre(e54, t4, n8) {
  return (t4.x - e54.x) * (n8.y - e54.y) - (t4.y - e54.y) * (n8.x - e54.x);
}
function $re(e54, t4, n8, o10) {
  return function(e60, t10, n10, o11) {
    const i8 = jre(n10, o11, e60), r9 = jre(n10, o11, t10), s7 = jre(e60, t10, n10), a9 = jre(e60, t10, o11);
    return (i8 > 0 && r9 < 0 || i8 < 0 && r9 > 0) && (s7 > 0 && a9 < 0 || s7 < 0 && a9 > 0);
  }(e54, t4, n8, o10) ? 0 : Math.min(Fre(e54, n8, o10), Fre(t4, n8, o10), Fre(n8, e54, t4), Fre(o10, e54, t4));
}
function Yre(e54, t4, n8 = 0.000000001) {
  if (Lre(t4))
    return Bre(e54, t4.center) <= t4.width / 2 + n8;
  const o10 = zre(e54, t4);
  return Math.abs(o10.x) <= t4.width / 2 + n8 && Math.abs(o10.y) <= t4.height / 2 + n8;
}
function Xre(e54, t4) {
  if (Lre(t4))
    return Math.max(0, Bre(e54, t4.center) - t4.width / 2);
  const n8 = zre(e54, t4), o10 = Math.max(Math.abs(n8.x) - t4.width / 2, 0), i8 = Math.max(Math.abs(n8.y) - t4.height / 2, 0);
  return Math.hypot(o10, i8);
}
function Hre(e54, t4) {
  if (Lre(t4))
    return Math.max(0, Fre(t4.center, e54.start, e54.end) - t4.width / 2);
  const n8 = zre(e54.start, t4), o10 = zre(e54.end, t4);
  if (Math.abs(n8.x) <= t4.width / 2 + Dre && Math.abs(n8.y) <= t4.height / 2 + Dre)
    return 0;
  if (Math.abs(o10.x) <= t4.width / 2 + Dre && Math.abs(o10.y) <= t4.height / 2 + Dre)
    return 0;
  const i8 = -t4.width / 2, r9 = t4.width / 2, s7 = -t4.height / 2, a9 = t4.height / 2, c5 = [{ x: i8, y: s7 }, { x: r9, y: s7 }, { x: r9, y: a9 }, { x: i8, y: a9 }];
  let l5 = Number.POSITIVE_INFINITY;
  for (let e60 = 0;e60 < c5.length; e60++)
    l5 = Math.min(l5, $re(n8, o10, c5[e60], c5[(e60 + 1) % c5.length]));
  return l5;
}
function Vre(e54, t4, n8) {
  if (e54.layer !== t4.layer)
    return true;
  const o10 = (e54.width + t4.width) / 2 + n8;
  return $re(e54.start, e54.end, t4.start, t4.end) >= o10 - Dre;
}
function Wre(e54) {
  if (!Number.isInteger(e54) || e54 < 1)
    throw new Error(`FanoutSolver: layerCount must be a positive integer, received ${e54}`);
  return e54 === 1 ? ["top"] : e54 === 2 ? ["top", "bottom"] : ["top", ...Array.from({ length: e54 - 2 }, (e60, t4) => `inner${t4 + 1}`), "bottom"];
}
function Gre(e54, t4, n8) {
  const o10 = n8.indexOf(e54), i8 = n8.indexOf(t4);
  if (o10 < 0 || i8 < 0)
    throw new Error(`FanoutSolver: cannot build via span from "${e54}" to "${t4}"`);
  const r9 = Math.min(o10, i8), s7 = Math.max(o10, i8);
  return n8.slice(r9, s7 + 1);
}
var Ure = new WeakMap;
function Zre(e54) {
  return e54.netConnectionName ?? e54.rootConnectionName ?? e54.name;
}
function qre(e54, t4, n8) {
  if (!t4)
    return false;
  const o10 = e54.get(t4) ?? new Set, i8 = o10.size;
  return o10.add(n8), e54.set(t4, o10), o10.size !== i8;
}
function Jre(e54, t4) {
  const n8 = new Set;
  for (const o10 of t4)
    for (const t10 of e54.get(o10) ?? [])
      n8.add(t10);
  return n8;
}
function Qre(e54) {
  const t4 = Ure.get(e54);
  if (t4)
    return t4;
  const n8 = function(e60) {
    const t10 = new Map, n10 = new Map;
    for (const o11 of e60.connections) {
      const e61 = Zre(o11);
      t10.set(o11.name, e61), qre(n10, o11.name, e61), qre(n10, o11.rootConnectionName, e61), qre(n10, o11.netConnectionName, e61);
      for (const t11 of o11.pointsToConnect)
        qre(n10, t11.pointId, e61), qre(n10, t11.pcb_port_id, e61);
    }
    for (const o11 of e60.traces ?? []) {
      const e61 = o11.connection_name ? t10.get(o11.connection_name) : undefined;
      if (e61) {
        qre(n10, o11.pcb_trace_id, e61);
        for (const t11 of o11.connectsTo ?? [])
          qre(n10, t11, e61);
      }
    }
    for (let t11 = 0;t11 < 2; t11++) {
      let t12 = false;
      for (const o11 of e60.obstacles) {
        const e61 = Jre(n10, o11.connectedTo);
        if (e61.size !== 1)
          continue;
        const i9 = [...e61][0];
        for (const e63 of o11.connectedTo)
          t12 = qre(n10, e63, i9) || t12;
      }
      if (!t12)
        break;
    }
    const o10 = new Map, i8 = (e61) => {
      const t11 = o10.get(e61) ?? e61;
      if (o10.set(e61, t11), t11 === e61)
        return e61;
      const n11 = i8(t11);
      return o10.set(e61, n11), n11;
    }, r9 = (e61, t11) => {
      const n11 = i8(e61), r10 = i8(t11);
      n11 !== r10 && o10.set(r10, n11);
    };
    for (const e61 of n10.values()) {
      const [t11, ...n11] = [...e61];
      if (t11)
        for (const e63 of n11)
          r9(t11, e63);
    }
    for (const t11 of [...e60.obstacles.map((e61) => e61.connectedTo), ...(e60.traces ?? []).map((e61) => e61.connectsTo ?? [])]) {
      const [e61, ...o11] = [...Jre(n10, t11)];
      if (e61)
        for (const t12 of o11)
          r9(e61, t12);
    }
    for (const [e61, n11] of t10)
      t10.set(e61, i8(n11));
    for (const [e61, t11] of n10)
      n10.set(e61, new Set([...t11].map((e63) => i8(e63))));
    return { connectionNetKeys: t10, tokenNetKeys: n10 };
  }(e54);
  return Ure.set(e54, n8), n8;
}
function Kre(e54, t4, n8) {
  const o10 = Qre(e54), i8 = o10.connectionNetKeys.get(t4), r9 = o10.connectionNetKeys.get(n8);
  return i8 !== undefined && i8 === r9;
}
function ese(e54, t4, n8) {
  const o10 = Qre(e54), i8 = o10.connectionNetKeys.get(n8);
  return !!i8 && t4.connectedTo.some((e60) => o10.tokenNetKeys.get(e60)?.has(i8));
}
var tse = 0.000001;
function nse(e54) {
  return "layer" in e54 ? [e54.layer] : e54.layers;
}
function ose(e54, t4) {
  return e54.some((e60) => t4.includes(e60));
}
function ise(e54, t4) {
  const n8 = [];
  let o10;
  for (const i8 of e54.route)
    i8.route_type !== "via" ? i8.route_type === "wire" && (o10 && o10.layer === i8.layer && Bre(o10, i8) > tse && n8.push({ type: "segment", segment: { start: { x: o10.x, y: o10.y }, end: { x: i8.x, y: i8.y }, width: i8.width, layer: i8.layer } }), o10 = i8) : (n8.push({ type: "via", center: { x: i8.x, y: i8.y }, diameter: i8.via_diameter ?? 0, layers: Gre(i8.from_layer, i8.to_layer, t4) }), o10 = undefined);
  return n8;
}
function rse(e54, t4) {
  return e54.type === "plane" && t4.type === "plane" ? e54.layer === t4.layer : e54.type === "plane" && t4.type === "via" ? t4.layers.includes(e54.layer) : e54.type === "via" && t4.type === "plane" ? rse(t4, e54) : e54.type === "plane" && t4.type === "segment" ? e54.layer === t4.segment.layer : e54.type === "segment" && t4.type === "plane" ? rse(t4, e54) : e54.type === "endpoint" && t4.type === "endpoint" ? ose(e54.layers, t4.layers) && Bre(e54.point, t4.point) <= tse : e54.type === "endpoint" && t4.type === "obstacle" ? ose(e54.layers, t4.obstacle.layers) && Yre(e54.point, t4.obstacle, tse) : e54.type === "obstacle" && t4.type === "endpoint" ? rse(t4, e54) : e54.type === "endpoint" && t4.type === "segment" ? e54.layers.includes(t4.segment.layer) && Fre(e54.point, t4.segment.start, t4.segment.end) <= t4.segment.width / 2 + tse : e54.type === "segment" && t4.type === "endpoint" ? rse(t4, e54) : e54.type === "endpoint" && t4.type === "via" ? ose(e54.layers, t4.layers) && Bre(e54.point, t4.center) <= t4.diameter / 2 + tse : e54.type === "via" && t4.type === "endpoint" ? rse(t4, e54) : e54.type === "obstacle" && t4.type === "segment" ? e54.obstacle.layers.includes(t4.segment.layer) && Hre(t4.segment, e54.obstacle) <= t4.segment.width / 2 + tse : e54.type === "segment" && t4.type === "obstacle" ? rse(t4, e54) : e54.type === "obstacle" && t4.type === "via" ? ose(e54.obstacle.layers, t4.layers) && Xre(t4.center, e54.obstacle) <= t4.diameter / 2 + tse : e54.type === "via" && t4.type === "obstacle" ? rse(t4, e54) : e54.type === "segment" && t4.type === "segment" ? e54.segment.layer === t4.segment.layer && $re(e54.segment.start, e54.segment.end, t4.segment.start, t4.segment.end) <= (e54.segment.width + t4.segment.width) / 2 + tse : e54.type === "segment" && t4.type === "via" ? t4.layers.includes(e54.segment.layer) && Fre(t4.center, e54.segment.start, e54.segment.end) <= t4.diameter / 2 + e54.segment.width / 2 + tse : e54.type === "via" && t4.type === "segment" ? rse(t4, e54) : e54.type === "via" && t4.type === "via" && (ose(e54.layers, t4.layers) && Bre(e54.center, t4.center) <= (e54.diameter + t4.diameter) / 2 + tse);
}
var sse = class {
  parent;
  constructor(e54) {
    this.parent = Array.from({ length: e54 }, (e60, t4) => t4);
  }
  find(e54) {
    const t4 = this.parent[e54];
    if (t4 === e54)
      return e54;
    const n8 = this.find(t4);
    return this.parent[e54] = n8, n8;
  }
  union(e54, t4) {
    const n8 = this.find(e54), o10 = this.find(t4);
    n8 !== o10 && (this.parent[o10] = n8);
  }
};
function ase(e54, t4, n8) {
  return Boolean(t4.connection_name && Kre(e54, t4.connection_name, n8.name));
}
function cse(e54) {
  const { inputSrj: t4, routedSrj: n8 } = e54, o10 = n8.fanoutPlaneConnectivity, i8 = Wre(n8.layerCount), r9 = new Map;
  for (const e60 of t4.connections) {
    const t10 = Zre(e60), n10 = r9.get(t10) ?? [];
    n10.push(e60), r9.set(t10, n10);
  }
  const s7 = [];
  let a9 = 0, c5 = 0;
  for (const e60 of r9.values()) {
    const r10 = e60[0], l10 = e60.flatMap((e61) => e61.pointsToConnect.map((t10, n10) => ({ type: "endpoint", connectionName: e61.name, endpointIndex: n10, point: t10, layers: nse(t10) }))), h5 = t4.obstacles.filter((e61) => ese(t4, e61, r10.name)).map((e61) => ({ type: "obstacle", obstacle: e61 })), d9 = (n8.traces ?? []).filter((e61) => ase(t4, e61, r10)).flatMap((e61) => ise(e61, i8)), u9 = [...new Set((o10 ?? []).flatMap((e61) => Kre(t4, e61.connectionName, r10.name) ? [e61.layer] : []))].map((e61) => ({ type: "plane", layer: e61 })), p9 = [...l10, ...h5, ...d9, ...u9], m9 = new sse(p9.length);
    for (let e61 = 0;e61 < p9.length; e61++)
      for (let t10 = e61 + 1;t10 < p9.length; t10++)
        rse(p9[e61], p9[t10]) && m9.union(e61, t10);
    const g10 = new Map;
    for (let e61 = 0;e61 < l10.length; e61++) {
      const t10 = l10[e61], n10 = g10.get(t10.connectionName) ?? [];
      n10[t10.endpointIndex] = e61, g10.set(t10.connectionName, n10);
    }
    for (const t10 of e60) {
      const e61 = g10.get(t10.name) ?? [], n10 = e61[0], o11 = n10 === undefined ? undefined : m9.find(n10), i9 = e61.flatMap((e63, t11) => o11 === undefined || m9.find(e63) !== o11 ? [t11] : []);
      c5 += e61.length - i9.length, i9.length === 0 ? a9++ : s7.push({ code: "original-endpoints-disconnected", connectionName: t10.name, disconnectedEndpointIndices: i9, message: `Connection ${t10.name} has no physical copper path from endpoint 0 to original endpoint${i9.length === 1 ? "" : "s"} ${i9.join(", ")}` });
    }
  }
  const l5 = t4.connections.reduce((e60, t10) => e60 + t10.pointsToConnect.length, 0);
  return { valid: s7.length === 0, checkedConnectionCount: t4.connections.length, connectedConnectionCount: a9, checkedEndpointCount: l5, connectedEndpointCount: c5, issues: s7 };
}
var lse = 0.000001;
function hse(e54) {
  const { inputSrj: t4, segment: n8, bodyObstacle: o10, connectionName: i8 } = e54;
  if (o10.connectedTo.length > 0 || !o10.componentId)
    return false;
  const r9 = t4.obstacles.filter((e60) => e60.componentId === o10.componentId && e60.layers.includes(n8.layer) && ese(t4, e60, i8));
  for (const e60 of r9)
    for (const [t10, i9] of [[n8.start, n8.end], [n8.end, n8.start]]) {
      if (!Yre(t10, e60, lse))
        continue;
      const n10 = { x: t10.x - o10.center.x, y: t10.y - o10.center.y }, r10 = { x: i9.x - t10.x, y: i9.y - t10.y };
      if (n10.x * r10.x + n10.y * r10.y > lse)
        return true;
    }
  return false;
}
function dse(e54, t4) {
  return Bre(e54, t4) <= lse;
}
function use(e54, t4) {
  e54.push(t4);
}
function pse(e54) {
  const { srj: t4, trace: n8, connectionName: o10, layerNames: i8, issues: r9 } = e54, s7 = [], a9 = [];
  let c5, l5;
  for (const e60 of n8.route) {
    if (e60.route_type === "via") {
      const s9 = Gre(e60.from_layer, e60.to_layer, i8);
      a9.push({ center: { x: e60.x, y: e60.y }, diameter: e60.via_diameter ?? t4.minViaPadDiameter ?? t4.minTraceWidth, spanLayers: s9 }), c5 && dse(c5, e60) && c5.layer === e60.from_layer || use(r9, { code: "disconnected-trace", traceId: n8.pcb_trace_id, connectionName: o10, message: `Trace ${n8.pcb_trace_id} reaches a via without a matching ${e60.from_layer} wire endpoint` }), l5 = e60;
      continue;
    }
    e60.route_type === "wire" ? l5 ? (dse(e60, l5) && e60.layer === l5.to_layer || use(r9, { code: "disconnected-trace", traceId: n8.pcb_trace_id, connectionName: o10, message: `Trace ${n8.pcb_trace_id} does not continue from its via on ${l5.to_layer}` }), c5 = e60, l5 = undefined) : (c5 && (c5.layer !== e60.layer ? use(r9, { code: "disconnected-trace", traceId: n8.pcb_trace_id, connectionName: o10, message: `Trace ${n8.pcb_trace_id} changes from ${c5.layer} to ${e60.layer} without a via` }) : dse(c5, e60) || s7.push({ start: { x: c5.x, y: c5.y }, end: { x: e60.x, y: e60.y }, width: e60.width, layer: e60.layer })), c5 = e60) : (use(r9, { code: "unsupported-route-point", traceId: n8.pcb_trace_id, connectionName: o10, message: `Trace ${n8.pcb_trace_id} contains unsupported ${e60.route_type} geometry` }), c5 = undefined, l5 = undefined);
  }
  return l5 && use(r9, { code: "disconnected-trace", traceId: n8.pcb_trace_id, connectionName: o10, message: `Trace ${n8.pcb_trace_id} ends at a via without a wire on ${l5.to_layer}` }), { trace: n8, connectionName: o10, segments: s7, vias: a9 };
}
function mse(e54) {
  const { inputSrj: t4, routedSrj: n8, clearance: o10 } = e54, i8 = [], r9 = Wre(n8.layerCount), s7 = [], a9 = [t4, n8].flatMap((e60) => e60.connections.flatMap((e61) => e61.pointsToConnect.map((t10) => ({ connectionName: e61.name, point: t10 }))));
  for (const e60 of n8.traces ?? []) {
    const o11 = e60.connection_name;
    o11 && t4.connections.some((e61) => e61.name === o11) ? s7.push(pse({ srj: n8, trace: e60, connectionName: o11, layerNames: r9, issues: i8 })) : use(i8, { code: "unknown-trace-connection", traceId: e60.pcb_trace_id, ...o11 ? { connectionName: o11 } : {}, message: `Trace ${e60.pcb_trace_id} does not identify an input connection` });
  }
  for (const e60 of s7) {
    for (const n10 of e60.segments)
      for (const r10 of t4.obstacles) {
        if (!r10.layers.includes(n10.layer) || ese(t4, r10, e60.connectionName))
          continue;
        if (hse({ inputSrj: t4, segment: n10, bodyObstacle: r10, connectionName: e60.connectionName }))
          continue;
        const s9 = Hre(n10, r10), a10 = n10.width / 2 + o10;
        s9 < a10 - lse && use(i8, { code: "trace-obstacle-clearance", traceId: e60.trace.pcb_trace_id, connectionName: e60.connectionName, layer: n10.layer, obstacleId: r10.obstacleId, message: `Trace ${e60.trace.pcb_trace_id} on ${n10.layer} is ${s9.toFixed(4)}mm from different-net obstacle ${r10.obstacleId}; ${a10.toFixed(4)}mm is required` });
      }
    for (const n10 of e60.vias) {
      const r10 = a9.find(({ point: e61 }) => Bre(n10.center, e61) <= lse);
      r10 && use(i8, { code: "via-at-endpoint", traceId: e60.trace.pcb_trace_id, connectionName: e60.connectionName, otherConnectionName: r10.connectionName, message: `Via in ${e60.trace.pcb_trace_id} is placed directly at an original or routed connection endpoint` });
      for (const r11 of t4.obstacles) {
        if (!r11.layers.some((e61) => n10.spanLayers.includes(e61)) || ese(t4, r11, e60.connectionName))
          continue;
        const s9 = Xre(n10.center, r11), a10 = n10.diameter / 2 + o10;
        s9 < a10 - lse && use(i8, { code: "via-obstacle-clearance", traceId: e60.trace.pcb_trace_id, connectionName: e60.connectionName, obstacleId: r11.obstacleId, message: `Via in ${e60.trace.pcb_trace_id} is ${s9.toFixed(4)}mm from different-net obstacle ${r11.obstacleId} on its layer span; ${a10.toFixed(4)}mm is required` });
      }
    }
  }
  for (let e60 = 0;e60 < s7.length; e60++) {
    const n10 = s7[e60];
    for (let r10 = e60 + 1;r10 < s7.length; r10++) {
      const e61 = s7[r10];
      if (!Kre(t4, n10.connectionName, e61.connectionName)) {
        for (const t10 of n10.segments) {
          for (const r11 of e61.segments)
            Vre(t10, r11, o10) || use(i8, { code: "different-net-trace-clearance", traceId: n10.trace.pcb_trace_id, connectionName: n10.connectionName, otherTraceId: e61.trace.pcb_trace_id, otherConnectionName: e61.connectionName, layer: t10.layer, message: `Different-net traces ${n10.trace.pcb_trace_id} and ${e61.trace.pcb_trace_id} intersect or violate clearance on ${t10.layer}` });
          for (const r11 of e61.vias)
            !r11.spanLayers.includes(t10.layer) || Fre(r11.center, t10.start, t10.end) >= r11.diameter / 2 + t10.width / 2 + o10 - lse || use(i8, { code: "different-net-trace-via-clearance", traceId: n10.trace.pcb_trace_id, connectionName: n10.connectionName, otherTraceId: e61.trace.pcb_trace_id, otherConnectionName: e61.connectionName, layer: t10.layer, message: `Trace ${n10.trace.pcb_trace_id} violates via clearance to ${e61.trace.pcb_trace_id} on ${t10.layer}` });
        }
        for (const t10 of n10.vias) {
          for (const r11 of e61.segments)
            !t10.spanLayers.includes(r11.layer) || Fre(t10.center, r11.start, r11.end) >= t10.diameter / 2 + r11.width / 2 + o10 - lse || use(i8, { code: "different-net-trace-via-clearance", traceId: n10.trace.pcb_trace_id, connectionName: n10.connectionName, otherTraceId: e61.trace.pcb_trace_id, otherConnectionName: e61.connectionName, layer: r11.layer, message: `Via in ${n10.trace.pcb_trace_id} violates trace clearance to ${e61.trace.pcb_trace_id} on ${r11.layer}` });
          for (const r11 of e61.vias)
            !t10.spanLayers.some((e63) => r11.spanLayers.includes(e63)) || Bre(t10.center, r11.center) >= (t10.diameter + r11.diameter) / 2 + o10 - lse || use(i8, { code: "different-net-via-clearance", traceId: n10.trace.pcb_trace_id, connectionName: n10.connectionName, otherTraceId: e61.trace.pcb_trace_id, otherConnectionName: e61.connectionName, message: `Different-net vias in ${n10.trace.pcb_trace_id} and ${e61.trace.pcb_trace_id} violate clearance on an overlapping layer span` });
        }
      }
    }
  }
  return { valid: i8.length === 0, checkedTraceCount: n8.traces?.length ?? 0, checkedSegmentCount: s7.reduce((e60, t10) => e60 + t10.segments.length, 0), checkedViaCount: s7.reduce((e60, t10) => e60 + t10.vias.length, 0), issues: i8 };
}
var gse = 0.000000001;
function fse(e54, t4) {
  if ("layer" in e54)
    return e54.layer;
  if (t4 && e54.layers.includes(t4))
    return t4;
  const n8 = e54.layers[0];
  if (!n8)
    throw new Error("Endpoint completion received a layerless point");
  return n8;
}
function _se(e54) {
  const t4 = [];
  for (const n8 of e54)
    t4.at(-1) && Bre(t4.at(-1), n8) < gse || t4.push(n8);
  return t4;
}
function yse(e54, t4) {
  const n8 = _se(e54);
  if (n8.length < 3)
    return n8;
  const o10 = [n8[0]];
  for (let e60 = 1;e60 < n8.length - 1; e60++) {
    const i8 = n8[e60 - 1], r9 = n8[e60], s7 = n8[e60 + 1], a9 = Bre(i8, r9), c5 = Bre(r9, s7), l5 = { x: (r9.x - i8.x) / a9, y: (r9.y - i8.y) / a9 }, h5 = { x: (s7.x - r9.x) / c5, y: (s7.y - r9.y) / c5 };
    if (Math.abs(l5.x * h5.x + l5.y * h5.y) > 0.000001) {
      o10.push(r9);
      continue;
    }
    const d9 = Math.min(t4, a9 / 2, c5 / 2);
    o10.push({ x: r9.x - l5.x * d9, y: r9.y - l5.y * d9 }), o10.push({ x: r9.x + h5.x * d9, y: r9.y + h5.y * d9 });
  }
  return o10.push(n8.at(-1)), _se(o10);
}
function bse(e54) {
  const { inputSrj: t4, plan: n8 } = e54, o10 = fse(n8.targetPoint), i8 = function(e60) {
    const { inputSrj: t10, connectionName: n10, target: o11, targetLayer: i9 } = e60;
    return t10.obstacles.find((e61) => e61.layers.includes(i9) && ese(t10, e61, n10) && Yre(o11, e61, 0.000001));
  }({ inputSrj: t4, connectionName: n8.connectionName, target: n8.targetPoint, targetLayer: o10 }), r9 = t4.obstacles.find((e60) => e60.componentId === i8?.componentId && e60.connectedTo.length === 0), s7 = r9 ? { x: n8.targetPoint.x - r9.center.x, y: n8.targetPoint.y - r9.center.y } : { x: n8.targetPoint.x - n8.sourcePoint.x, y: n8.targetPoint.y - n8.sourcePoint.y }, a9 = Math.hypot(s7.x, s7.y), c5 = a9 > gse ? { x: s7.x / a9, y: s7.y / a9 } : { x: 1, y: 0 };
  return { outward: c5, perpendicular: { x: -c5.y, y: c5.x } };
}
function xse(e54) {
  const { plan: t4, branchStart: n8, viaPoint: o10, assignedLayerPath: i8, terminalApproach: r9, traceWidth: s7, viaDiameter: a9, viaHoleDiameter: c5, candidateIndex: l5, chamfer: h5 } = e54, d9 = fse(t4.targetPoint), u9 = yse(i8, h5), p9 = yse([o10, ...r9 ? [r9] : [], t4.targetPoint], h5), m9 = u9.map((e60) => ({ route_type: "wire", x: e60.x, y: e60.y, width: s7, layer: n8.layer }));
  n8.layer !== d9 && (m9.push({ route_type: "via", x: o10.x, y: o10.y, from_layer: n8.layer, to_layer: d9, via_diameter: a9, via_hole_diameter: c5 }), m9.push({ route_type: "wire", x: o10.x, y: o10.y, width: s7, layer: d9 }));
  for (const e60 of p9.slice(1))
    m9.push({ route_type: "wire", x: e60.x, y: e60.y, width: s7, layer: d9 });
  return { type: "pcb_trace", pcb_trace_id: (g10 = { connectionName: t4.connectionName, sourcePointIndex: t4.sourcePointIndex, candidateIndex: l5 }, `fanout-completion:${g10.connectionName}:source-${g10.sourcePointIndex}:${g10.candidateIndex}`), connection_name: t4.connectionName, route: m9 };
  var g10;
}
function vse(e54, t4) {
  return !e54.issues.some((e60) => e60.connectionName === t4);
}
function Ise(e54) {
  const { trace: t4, endpointSrjs: n8 } = e54, o10 = n8.flatMap((e60) => e60.connections.flatMap((e61) => e61.pointsToConnect));
  return t4.route.some((e60) => e60.route_type === "via" && o10.some((t10) => Bre(e60, t10) <= 0.000001));
}
function Sse(e54) {
  const { inputSrj: t4, fanoutSrj: n8, plan: o10, acceptedTraces: i8, traceWidth: r9, viaDiameter: s7, viaHoleDiameter: a9, clearance: c5 } = e54, { outward: l5, perpendicular: h5 } = bse({ inputSrj: t4, plan: o10 }), d9 = [...o10.via ? [{ x: o10.via.center.x, y: o10.via.center.y, layer: o10.targetLayer }] : [], { x: o10.sourcePoint.x, y: o10.sourcePoint.y, layer: o10.sourceLayer }];
  let u9 = [], p9 = Number.POSITIVE_INFINITY, m9 = 0;
  const g10 = t4.connections.length > 32 ? 600 : Number.POSITIVE_INFINITY, f10 = o10.termination.type === "plane" ? wse({ trace: o10.trace, endpoint: o10.exitPoint, layer: o10.sourceLayer, distances: [0.2, 0.3, 0.4] }) : [], _5 = [...o10.termination.type === "plane" && o10.via ? [{ ...o10.via.center }] : [], ...f10, ...[0.4, 0.8, 1.2, 1.6].flatMap((e60) => [0, 0.4, -0.4, 0.8, -0.8, 1.2, -1.2, 1.6, -1.6].map((t10) => ({ x: o10.sourcePoint.x + l5.x * e60 + h5.x * t10, y: o10.sourcePoint.y + l5.y * e60 + h5.y * t10 })))];
  for (const e60 of _5) {
    const _10 = [...o10.termination.type === "plane" ? [{ ...e60, layer: o10.targetLayer }] : [], ...d9, ...f10.flatMap((t10) => Bre(t10, e60) <= 0.000001 ? [{ ...t10, layer: o10.sourceLayer }] : [])];
    for (const d10 of _10) {
      const f11 = Bre(d10, e60) <= 0.000001 ? [[d10]] : [[d10, e60], [d10, { x: e60.x, y: d10.y }, e60], [d10, { x: d10.x, y: e60.y }, e60], ...[0.4, -0.4].map((t10) => [d10, { x: d10.x + t10, y: d10.y }, { x: d10.x + t10, y: e60.y }, e60])];
      for (const _11 of f11) {
        const f12 = [undefined, ...[0.4, 0.8].map((e61) => ({ x: o10.targetPoint.x + l5.x * e61, y: o10.targetPoint.y + l5.y * e61 })), ...[0.4, -0.4].map((e61) => ({ x: o10.targetPoint.x + 0.4 * l5.x + h5.x * e61, y: o10.targetPoint.y + 0.4 * l5.y + h5.y * e61 }))];
        for (const l10 of f12) {
          if (m9 >= g10)
            return { blockingConnectionNames: u9 };
          const h9 = xse({ plan: o10, branchStart: d10, viaPoint: e60, assignedLayerPath: _11, terminalApproach: l10, traceWidth: r9, viaDiameter: s7, viaHoleDiameter: a9, candidateIndex: m9++, chamfer: 0 });
          if (Ise({ trace: h9, endpointSrjs: [t4, n8] }))
            continue;
          const f13 = { ...n8, traces: [...n8.traces ?? [], ...i8, h9] }, y10 = mse({ inputSrj: t4, routedSrj: f13, clearance: c5 });
          if (!y10.valid) {
            y10.issues.length < p9 && (p9 = y10.issues.length, u9 = [...new Set(y10.issues.flatMap((e61) => [e61.connectionName, e61.otherConnectionName].flatMap((e63) => e63 && e63 !== o10.connectionName ? [e63] : [])))]);
            continue;
          }
          if (vse(cse({ inputSrj: t4, routedSrj: f13 }), o10.connectionName))
            return { trace: h9, blockingConnectionNames: [] };
        }
      }
    }
  }
  return { blockingConnectionNames: u9 };
}
function Cse(e54) {
  const { inputSrj: t4, fanoutSrj: n8, plans: o10, traceWidth: i8, viaDiameter: r9, viaHoleDiameter: s7, clearance: a9 } = e54, c5 = [], l5 = [], h5 = new Set;
  for (const e60 of o10) {
    const o11 = Sse({ inputSrj: t4, fanoutSrj: n8, plan: e60, acceptedTraces: c5, traceWidth: i8, viaDiameter: r9, viaHoleDiameter: s7, clearance: a9 });
    if (o11.trace)
      c5.push(o11.trace);
    else {
      l5.push(e60.connectionName);
      for (const e61 of o11.blockingConnectionNames)
        h5.add(e61);
    }
  }
  const d9 = { ...n8, traces: [...n8.traces ?? [], ...c5] };
  return { traces: c5, failedConnectionNames: l5, blockingConnectionNames: [...h5], connectivity: cse({ inputSrj: t4, routedSrj: d9 }), drc: mse({ inputSrj: t4, routedSrj: d9, clearance: a9 }) };
}
function Pse(e54) {
  let t4, n8 = 0;
  for (const o10 of e54.route)
    o10.route_type === "wire" ? (t4?.layer === o10.layer && (n8 += Bre(t4, o10)), t4 = o10) : t4 = undefined;
  return n8;
}
function Mse(e54) {
  const t4 = Wre(e54.layerCount), n8 = [];
  for (const o10 of e54.traces ?? []) {
    let i8;
    for (const r9 of o10.route)
      if (r9.route_type !== "via")
        if (r9.route_type === "wire") {
          if (i8?.layer === r9.layer) {
            const e60 = Bre(i8, r9);
            e60 > gse && n8.push({ obstacleId: `endpoint-completion-keepout:${o10.pcb_trace_id}:segment:${n8.length}`, type: "rect", center: { x: (i8.x + r9.x) / 2, y: (i8.y + r9.y) / 2 }, width: e60, height: Math.max(i8.width, r9.width), ccwRotationDegrees: 180 * Math.atan2(r9.y - i8.y, r9.x - i8.x) / Math.PI, layers: [r9.layer], connectedTo: [o10.connection_name] });
          }
          i8 = r9;
        } else
          i8 = undefined;
      else
        n8.push({ obstacleId: `endpoint-completion-keepout:${o10.pcb_trace_id}:via:${n8.length}`, type: "rect", center: { x: r9.x, y: r9.y }, width: r9.via_diameter ?? e54.minViaPadDiameter ?? 0.3, height: r9.via_diameter ?? e54.minViaPadDiameter ?? 0.3, layers: Gre(r9.from_layer, r9.to_layer, t4), connectedTo: [o10.connection_name] }), i8 = undefined;
  }
  return n8;
}
function wse(e54) {
  const { trace: t4, endpoint: n8, layer: o10, distances: i8 } = e54, r9 = t4.route.findLastIndex((e60) => e60.route_type === "wire" && e60.layer === o10 && Bre(e60, n8) <= 0.000001);
  return r9 < 0 ? [] : i8.flatMap((e60) => {
    let i9 = e60, s7 = n8;
    for (let e61 = r9 - 1;e61 >= 0; e61--) {
      const n10 = t4.route[e61];
      if (n10?.route_type !== "wire" || n10.layer !== o10)
        break;
      const r10 = Bre(s7, n10);
      if (!(r10 <= gse)) {
        if (i9 < r10 - 0.000001)
          return [{ x: s7.x + (n10.x - s7.x) * i9 / r10, y: s7.y + (n10.y - s7.y) * i9 / r10 }];
        i9 -= r10, s7 = n10;
      }
    }
    return [];
  });
}
function Nse(e54) {
  const { inputSrj: t4, fanoutSrj: n8, plan: o10, acceptedTraces: i8, traceWidth: r9, viaDiameter: s7, viaHoleDiameter: a9, clearance: c5 } = e54, l5 = { x: o10.exitPoint.x, y: o10.exitPoint.y, layer: o10.targetLayer }, h5 = o10.targetPoint, d9 = fse(h5);
  let u9 = 0;
  const p9 = (e60) => {
    const l10 = xse({ plan: o10, branchStart: e60.start, viaPoint: e60.viaPoint, assignedLayerPath: [e60.start, e60.viaPoint], terminalApproach: e60.terminalApproach, traceWidth: r9, viaDiameter: s7, viaHoleDiameter: a9, candidateIndex: 1e4 + u9++, chamfer: Math.max(r9, 0.1) });
    if (Ise({ trace: l10, endpointSrjs: [t4, n8] }))
      return;
    const h9 = { ...n8, traces: [...n8.traces ?? [], ...i8, l10] };
    return mse({ inputSrj: t4, routedSrj: h9, clearance: c5 }).valid && vse(cse({ inputSrj: t4, routedSrj: h9 }), o10.connectionName) ? l10 : undefined;
  };
  if (l5.layer !== d9) {
    const e60 = wse({ trace: o10.trace, endpoint: o10.exitPoint, layer: o10.targetLayer, distances: [0.4, 0.8, 1.2, 1.6] });
    for (const t10 of e60) {
      const e61 = { ...t10, layer: o10.targetLayer };
      for (const n10 of [undefined, { x: h5.x, y: t10.y }, { x: t10.x, y: h5.y }]) {
        const o11 = p9({ start: e61, viaPoint: t10, terminalApproach: n10 });
        if (o11)
          return o11;
      }
    }
  }
  const m9 = [[h5], [{ x: h5.x, y: l5.y }, h5], [{ x: l5.x, y: h5.y }, h5]];
  for (const e60 of m9) {
    const t10 = e60[0], n10 = Bre(l5, t10), o11 = l5.layer === d9 ? [0] : [0.4, 0.8, 1.2, 1.6];
    for (const i9 of o11) {
      if (l5.layer !== d9 && (n10 <= i9 + 0.2 || i9 <= 0.000001))
        continue;
      const o12 = p9({ start: l5, viaPoint: l5.layer === d9 ? { x: l5.x, y: l5.y } : { x: l5.x + (t10.x - l5.x) * i9 / n10, y: l5.y + (t10.y - l5.y) * i9 / n10 }, terminalApproach: e60.length > 1 ? t10 : undefined });
      if (o12)
        return o12;
    }
  }
}
function Rse(e54) {
  const { inputSrj: t4, fanoutSrj: n8, plans: o10, traceWidth: i8, viaDiameter: r9, viaHoleDiameter: s7, clearance: a9, effort: c5 = 1, routeDownstreamConnections: l5 } = e54, h5 = [], d9 = mse({ inputSrj: t4, routedSrj: n8, clearance: a9 }), u9 = cse({ inputSrj: t4, routedSrj: n8 }), p9 = o10.filter((e60) => fse(e60.sourcePoint) !== fse(e60.targetPoint) && Bre(e60.sourcePoint, e60.targetPoint) <= 0.25 && !vse(u9, e60.connectionName));
  let m9 = { traces: [], failedConnectionNames: p9.map((e60) => e60.connectionName), blockingConnectionNames: [], connectivity: u9, drc: d9 }, g10 = 0;
  if (d9.valid) {
    let e60 = [];
    const o11 = new Map(p9.map((e61, t10) => [e61.connectionName, t10])), c9 = t4.connections.length > 32 ? 1 : 3;
    for (let l10 = 0;l10 < c9; l10++) {
      const c10 = new Map(e60.map((e61, t10) => [e61, t10])), l11 = Cse({ inputSrj: t4, fanoutSrj: n8, plans: p9.toSorted((e61, t10) => (c10.get(e61.connectionName) ?? Number.MAX_SAFE_INTEGER) - (c10.get(t10.connectionName) ?? Number.MAX_SAFE_INTEGER) || (o11.get(e61.connectionName) ?? 0) - (o11.get(t10.connectionName) ?? 0)), traceWidth: i8, viaDiameter: r9, viaHoleDiameter: s7, clearance: a9 });
      if (g10++, l11.drc.valid && (l11.connectivity.connectedConnectionCount > m9.connectivity.connectedConnectionCount || l11.connectivity.connectedConnectionCount === m9.connectivity.connectedConnectionCount && l11.traces.length < m9.traces.length) && (m9 = l11), e60 = [...new Set([...l11.failedConnectionNames, ...l11.blockingConnectionNames, ...e60])], l11.failedConnectionNames.length === 0)
        break;
    }
  } else
    h5.push("Fanout prefix failed emitted-copper DRC; skipped completion");
  const f10 = new Set(p9.map((e60) => e60.connectionName)), _5 = o10.filter((e60) => !f10.has(e60.connectionName) && !vse(u9, e60.connectionName)), y10 = [];
  if (d9.valid)
    for (const e60 of _5) {
      const o11 = Nse({ inputSrj: t4, fanoutSrj: n8, plan: e60, acceptedTraces: [...m9.traces, ...y10], traceWidth: i8, viaDiameter: r9, viaHoleDiameter: s7, clearance: a9 });
      o11 && y10.push(o11);
    }
  const b10 = { ...n8, traces: [...n8.traces ?? [], ...m9.traces, ...y10] }, x8 = new Set(cse({ inputSrj: t4, routedSrj: b10 }).issues.map((e60) => e60.connectionName)), v10 = n8.connections.filter((e60) => !f10.has(e60.name) && x8.has(e60.name));
  let I6 = [];
  if (d9.valid && v10.length > 0 && v10.length <= 12 && l5) {
    const e60 = new Set(v10.map((e61) => e61.name)), o11 = { ...n8, connections: v10, buses: n8.buses?.map((t10) => ({ ...t10, connectionNames: t10.connectionNames.filter((t11) => e60.has(t11)) })).filter((e61) => e61.connectionNames.length > 0), obstacles: [...n8.obstacles, ...Mse(n8)], traces: [] };
    try {
      const i9 = l5(o11, { effort: c5 });
      I6 = function(e61) {
        const { inputSrj: t10, fanoutSrj: n10, localTraces: o12, candidates: i10, clearance: r10 } = e61, s9 = [...n10.traces ?? [], ...o12], a10 = { ...n10, traces: s9 }, c9 = cse({ inputSrj: t10, routedSrj: a10 }), l10 = i10.filter((e63) => e63.route.length > 1 && e63.route.every((e64) => e64.route_type === "wire" || e64.route_type === "via") && !Ise({ trace: e63, endpointSrjs: [t10, n10] })).filter((e63) => {
          const o13 = cse({ inputSrj: t10, routedSrj: { ...n10, traces: [...s9, e63] } });
          return o13.connectedConnectionCount > c9.connectedConnectionCount && vse(o13, e63.connection_name);
        }), h9 = { ...n10, traces: [...s9, ...l10] };
        if (mse({ inputSrj: t10, routedSrj: h9, clearance: r10 }).valid)
          return l10;
        const d10 = [];
        for (const e63 of l10.toSorted((e64, t11) => Pse(e64) - Pse(t11))) {
          const o13 = { ...n10, traces: [...s9, ...d10, e63] };
          if (!mse({ inputSrj: t10, routedSrj: o13, clearance: r10 }).valid)
            continue;
          const i11 = cse({ inputSrj: t10, routedSrj: { ...n10, traces: [...s9, ...d10] } }), a11 = cse({ inputSrj: t10, routedSrj: o13 });
          a11.connectedConnectionCount > i11.connectedConnectionCount && vse(a11, e63.connection_name) && d10.push(e63);
        }
        return d10;
      }({ inputSrj: t4, fanoutSrj: n8, localTraces: [...m9.traces, ...y10], candidates: i9.filter((t10) => e60.has(t10.connection_name)), clearance: a9 });
    } catch (e61) {
      h5.push(`Downstream router failed: ${e61 instanceof Error ? e61.message : String(e61)}`);
    }
  } else
    !d9.valid && v10.length > 0 ? h5.push("Skipped downstream router because the endpoint-completion baseline failed emitted-copper DRC") : v10.length > 12 ? h5.push(`Skipped downstream router for ${v10.length} unresolved connections (bounded at 12)`) : v10.length > 0 && !l5 && h5.push(`Skipped downstream router for ${v10.length} unresolved connections because no routeDownstreamConnections callback was provided`);
  const S6 = [...m9.traces, ...y10, ...I6];
  for (const e60 of _5) {
    if (vse(cse({ inputSrj: t4, routedSrj: { ...n8, traces: [...n8.traces ?? [], ...S6] } }), e60.connectionName))
      continue;
    const o11 = Nse({ inputSrj: t4, fanoutSrj: n8, plan: e60, acceptedTraces: S6, traceWidth: i8, viaDiameter: r9, viaHoleDiameter: s7, clearance: a9 });
    o11 && S6.push(o11);
  }
  const C = function(e60) {
    const { fanoutSrj: t10, completionTraces: n10 } = e60, o11 = new Map(n10.flatMap((e61) => {
      const t11 = e61.route.find((e63) => e63.route_type === "wire");
      return t11 ? [[e61.connection_name, { x: t11.x, y: t11.y, layer: t11.layer }]] : [];
    })), i9 = (t10.traces ?? []).map((e61) => {
      if (!e61.pcb_trace_id.startsWith("fanout:"))
        return e61;
      const t11 = o11.get(e61.connection_name);
      if (!t11)
        return e61;
      let n11;
      for (let o12 = 0;o12 < e61.route.length; o12++) {
        const i10 = e61.route[o12];
        if (i10?.route_type === "wire") {
          if (n11 !== undefined) {
            const o13 = e61.route[n11];
            if (o13?.route_type === "wire" && o13.layer === t11.layer && i10.layer === t11.layer && Fre(t11, o13, i10) <= 0.000001) {
              const r10 = e61.route.slice(0, n11 + 1);
              return Bre(o13, t11) > 0.000001 && r10.push({ route_type: "wire", x: t11.x, y: t11.y, width: i10.width, layer: t11.layer }), { ...e61, route: r10 };
            }
          }
          n11 = o12;
        } else
          n11 = undefined;
      }
      return e61;
    });
    return { ...t10, traces: i9 };
  }({ fanoutSrj: { ...n8, traces: [...n8.traces ?? [], ...S6] }, completionTraces: S6 }), P = cse({ inputSrj: t4, routedSrj: C }), M = mse({ inputSrj: t4, routedSrj: C, clearance: a9 });
  return M.valid ? { simpleRouteJson: C, traces: S6, report: { attemptedLocalConnectionCount: p9.length, attemptedDownstreamConnectionCount: _5.length, completionTraceCount: S6.length, searchPassCount: g10, errors: h5, connectivity: P, drc: M } } : (h5.push("Final endpoint-completion output failed emitted-copper DRC"), { simpleRouteJson: n8, traces: [], report: { attemptedLocalConnectionCount: p9.length, attemptedDownstreamConnectionCount: _5.length, completionTraceCount: 0, searchPassCount: g10, errors: h5, connectivity: cse({ inputSrj: t4, routedSrj: n8 }), drc: d9 } });
}
var Tse = new Set(["left", "right", "top", "bottom", "top-left", "top-right", "bottom-left", "bottom-right"]);
var Ese = { top_left: { direction: "up", preferredExit: "top-left" }, top_middle: { direction: "up", preferredExit: "top" }, top_right: { direction: "up", preferredExit: "top-right" }, right_top: { direction: "right", preferredExit: "top-right" }, right_middle: { direction: "right", preferredExit: "right" }, right_bottom: { direction: "right", preferredExit: "bottom-right" }, bottom_right: { direction: "down", preferredExit: "bottom-right" }, bottom_middle: { direction: "down", preferredExit: "bottom" }, bottom_left: { direction: "down", preferredExit: "bottom-left" }, left_bottom: { direction: "left", preferredExit: "bottom-left" }, left_middle: { direction: "left", preferredExit: "left" }, left_top: { direction: "left", preferredExit: "top-left" }, top: { direction: "up", preferredExit: "top" }, right: { direction: "right", preferredExit: "right" }, bottom: { direction: "down", preferredExit: "bottom" }, left: { direction: "left", preferredExit: "left" } };
function Ase(e54) {
  const t4 = [...e54].sort((e60, t10) => e60 - t10), n8 = [];
  for (const e60 of t4)
    (n8.length === 0 || Math.abs(n8[n8.length - 1] - e60) > 0.000001) && n8.push(e60);
  return n8;
}
function Ose(e54) {
  let t4 = Number.POSITIVE_INFINITY;
  for (let n8 = 1;n8 < e54.length; n8++) {
    const o10 = e54[n8] - e54[n8 - 1];
    o10 > 0.000001 && (t4 = Math.min(t4, o10));
  }
  return t4;
}
function kse(e54, t4) {
  const n8 = t4 === "x" ? "y" : "x";
  let o10 = Number.POSITIVE_INFINITY;
  for (let i8 = 0;i8 < e54.length; i8++) {
    const r9 = e54[i8];
    for (let s7 = i8 + 1;s7 < e54.length; s7++) {
      const i9 = e54[s7];
      if (Math.abs(r9.center[n8] - i9.center[n8]) > 0.000001)
        continue;
      const a9 = Math.abs(r9.center[t4] - i9.center[t4]);
      a9 > 0.000001 && (o10 = Math.min(o10, a9));
    }
  }
  return o10;
}
function Dse(e54) {
  return { minX: Math.min(...e54.map((e60) => e60.center.x - e60.width / 2)), maxX: Math.max(...e54.map((e60) => e60.center.x + e60.width / 2)), minY: Math.min(...e54.map((e60) => e60.center.y - e60.height / 2)), maxY: Math.max(...e54.map((e60) => e60.center.y + e60.height / 2)) };
}
function Lse(e54, t4) {
  const n8 = t4.componentBounds?.[e54.componentId];
  if (!n8) {
    const t10 = 2.25 * e54.pitchX, n10 = 2.25 * e54.pitchY;
    return { minX: e54.bounds.minX - t10, maxX: e54.bounds.maxX + t10, minY: e54.bounds.minY - n10, maxY: e54.bounds.maxY + n10 };
  }
  if ([n8.minX, n8.maxX, n8.minY, n8.maxY].some((e60) => !Number.isFinite(e60)) || n8.minX >= n8.maxX || n8.minY >= n8.maxY)
    throw new Error(`FanoutSolver: componentBounds for "${e54.componentId}" must contain finite, increasing bounds`);
  if (n8.minX > e54.bounds.minX + 0.000001 || n8.maxX < e54.bounds.maxX - 0.000001 || n8.minY > e54.bounds.minY + 0.000001 || n8.maxY < e54.bounds.maxY - 0.000001)
    throw new Error(`FanoutSolver: componentBounds for "${e54.componentId}" must contain every component pad`);
  return { ...n8 };
}
function zse(e54, t4) {
  if ([e54.minX, e54.maxX, e54.minY, e54.maxY].some((e60) => !Number.isFinite(e60)) || e54.minX >= e54.maxX || e54.minY >= e54.maxY)
    throw new Error("FanoutSolver: sharedBoundary must contain finite, increasing bounds");
  for (const n8 of t4)
    if (e54.minX > n8.bounds.minX + 0.000001 || e54.maxX < n8.bounds.maxX - 0.000001 || e54.minY > n8.bounds.minY + 0.000001 || e54.maxY < n8.bounds.maxY - 0.000001)
      throw new Error(`FanoutSolver: sharedBoundary must contain every pad of component "${n8.componentId}"`);
  return { ...e54 };
}
function Bse(e54) {
  return "layer" in e54 ? [e54.layer] : e54.layers;
}
function Fse(e54) {
  const { point: t4, connection: n8, componentGrids: o10 } = e54, i8 = Bse(t4), r9 = [];
  for (const e60 of o10) {
    const o11 = e60.obstacles.filter((e61) => e61.layers.some((e63) => i8.includes(e63))).filter((e61) => Yre(t4, e61, 0.00001)).sort((e61, o12) => {
      const i9 = e61.connectedTo.includes(n8.name) || e61.connectedTo.includes(t4.pointId ?? "") || e61.connectedTo.includes(t4.pcb_port_id ?? "");
      return i9 !== (o12.connectedTo.includes(n8.name) || o12.connectedTo.includes(t4.pointId ?? "") || o12.connectedTo.includes(t4.pcb_port_id ?? "")) ? i9 ? -1 : 1 : e61.width * e61.height - o12.width * o12.height;
    });
    o11[0] && r9.push({ grid: e60, obstacle: o11[0] });
  }
  return r9;
}
function jse(e54) {
  for (const t10 of e54.pointsToConnect)
    if ("layers" in t10 && t10.busId)
      return t10.busId;
  const t4 = /^BUS[_:-]([^_:-]+)(?:[_:-]\d+)?$/i.exec(e54.name);
  return t4?.[1] ?? null;
}
function $se(e54, t4) {
  if (t4 !== undefined) {
    if (!Tse.has(t4))
      throw new Error(`FanoutSolver: bus "${e54}" has invalid preferredExit "${t4}"`);
    return t4;
  }
}
function Yse(e54) {
  if (e54 === undefined)
    return;
  if (e54.length === 0)
    throw new Error("FanoutSolver: availableCornersAndSides must contain at least one boundary region");
  const t4 = [], n8 = new Set;
  for (const o10 of e54) {
    const e60 = Ese[o10];
    if (!e60)
      throw new Error(`FanoutSolver: invalid availableCornersAndSides value "${o10}"`);
    const i8 = `${e60.direction}:${e60.preferredExit}`;
    n8.has(i8) || (n8.add(i8), t4.push(e60));
  }
  return t4;
}
function Xse(e54, t4) {
  if (t4 === undefined || t4.type === "boundary")
    return { type: "boundary" };
  if (t4.type !== "plane" || typeof t4.layer != "string" || t4.layer.length === 0)
    throw new Error(`FanoutSolver: bus "${e54}" has an invalid termination target`);
  return { type: "plane", layer: t4.layer };
}
function Hse(e54, t4, n8, o10) {
  const i8 = t4.pointsToConnect.filter((e60, t10) => t10 !== n8).sort((t10, n10) => Bre(e54, n10) - Bre(e54, t10))[0];
  if (!i8 && o10.type === "plane")
    return e54;
  if (!i8)
    throw new Error(`FanoutSolver: connection "${t4.name}" has no target beyond its BGA pad`);
  return i8;
}
function Vse(e54, t4) {
  let n8 = 0, o10 = 0;
  for (const e60 of t4) {
    const t10 = e60.exitTargetPoint ?? e60.targetPoint;
    n8 += t10.x - e60.sourcePoint.x, o10 += t10.y - e60.sourcePoint.y;
  }
  if (Math.abs(n8) < 0.000000001 && Math.abs(o10) < 0.000000001)
    throw new Error(`FanoutSolver: cannot infer an escape direction for bus "${e54}"`);
  return Math.abs(n8) >= Math.abs(o10) ? n8 >= 0 ? "right" : "left" : o10 >= 0 ? "up" : "down";
}
function Wse(e54) {
  return { x: e54.reduce((e60, t4) => e60 + t4.sourcePoint.x, 0) / e54.length, y: e54.reduce((e60, t4) => e60 + t4.sourcePoint.y, 0) / e54.length };
}
function Gse(e54, t4, n8) {
  switch (t4) {
    case "left":
      return e54.x - n8.minX;
    case "right":
      return n8.maxX - e54.x;
    case "up":
      return n8.maxY - e54.y;
    case "down":
      return e54.y - n8.minY;
  }
}
function Use(e54, t4) {
  return e54.direction === "up" || e54.direction === "down" ? e54.preferredExit.endsWith("left") ? t4.minX : e54.preferredExit.endsWith("right") ? t4.maxX : (t4.minX + t4.maxX) / 2 : e54.preferredExit.startsWith("top") ? t4.maxY : e54.preferredExit.startsWith("bottom") ? t4.minY : (t4.minY + t4.maxY) / 2;
}
function Zse(e54, t4) {
  return t4 === "up" || t4 === "down" ? e54.x : e54.y;
}
function qse(e54) {
  const { busId: t4, explicitDirection: n8, preferredExit: o10, connections: i8, sharedBoundary: r9, availableRegions: s7 } = e54, a9 = s7.filter((e60) => !(n8 !== undefined && e60.direction !== n8 || o10 !== undefined && e60.preferredExit !== o10));
  if (a9.length === 0)
    throw new Error(`FanoutSolver: bus "${t4}" cannot use its requested exit with availableCornersAndSides`);
  const c5 = n8 ? undefined : function(e60, t10) {
    try {
      return Vse(e60, t10);
    } catch {
      return;
    }
  }(t4, i8), l5 = c5 ? a9.filter((e60) => e60.direction === c5) : [], h5 = l5.length > 0 ? l5 : a9, d9 = Wse(i8);
  return [...h5].toSorted((e60, t10) => Gse(d9, e60.direction, r9) - Gse(d9, t10.direction, r9) || Math.abs(Zse(d9, e60.direction) - Use(e60, r9)) - Math.abs(Zse(d9, t10.direction) - Use(t10, r9)) || e60.preferredExit.localeCompare(t10.preferredExit))[0];
}
function Jse(e54) {
  const { busId: t4, explicitDirection: n8, preferredExit: o10, connections: i8, sharedBoundary: r9, availableRegions: s7 } = e54;
  if (s7)
    return qse({ busId: t4, explicitDirection: n8, preferredExit: o10, connections: i8, sharedBoundary: r9, availableRegions: s7 });
  if (!o10)
    return { direction: n8 ?? Vse(t4, i8) };
  const a9 = function(e60) {
    switch (e60) {
      case "left":
        return ["left"];
      case "right":
        return ["right"];
      case "top":
        return ["up"];
      case "bottom":
        return ["down"];
      case "top-left":
        return ["up", "left"];
      case "top-right":
        return ["up", "right"];
      case "bottom-left":
        return ["down", "left"];
      case "bottom-right":
        return ["down", "right"];
    }
  }(o10);
  if (n8) {
    if (!a9.includes(n8))
      throw new Error(`FanoutSolver: bus "${t4}" direction "${n8}" is incompatible with preferredExit "${o10}"`);
    return { direction: n8, preferredExit: o10 };
  }
  if (a9.length === 1)
    return { direction: a9[0], preferredExit: o10 };
  let c5;
  try {
    c5 = Vse(t4, i8);
  } catch {
    c5 = undefined;
  }
  if (c5 && a9.includes(c5))
    return { direction: c5, preferredExit: o10 };
  const l5 = Wse(i8);
  return { direction: a9.toSorted((e60, t10) => Gse(l5, e60, r9) - Gse(l5, t10, r9) || e60.localeCompare(t10))[0], preferredExit: o10 };
}
function Qse(e54, t4) {
  const n8 = function(e60) {
    const t10 = new Map;
    for (const n11 of e60) {
      if (!n11.componentId || n11.isCopperPour)
        continue;
      const e61 = t10.get(n11.componentId) ?? [];
      e61.push(n11), t10.set(n11.componentId, e61);
    }
    const n10 = [];
    for (const [e61, o11] of t10) {
      const t11 = Ase(o11.map((e63) => e63.center.x)), i9 = Ase(o11.map((e63) => e63.center.y)), r10 = kse(o11, "x"), s9 = kse(o11, "y"), a10 = Ose(t11), c5 = Ose(i9), l5 = Math.min(...[r10, s9, a10, c5].filter(Number.isFinite)), h5 = Math.max(...o11.flatMap((e63) => [e63.width, e63.height])), d9 = Number.isFinite(l5) ? l5 : h5, u9 = Number.isFinite(r10) ? r10 : Number.isFinite(a10) ? a10 : d9, p9 = Number.isFinite(s9) ? s9 : Number.isFinite(c5) ? c5 : d9;
      n10.push({ componentId: e61, obstacles: o11, xCoordinates: t11, yCoordinates: i9, pitchX: u9, pitchY: p9, bounds: Dse(o11) });
    }
    return n10;
  }(e54.obstacles);
  if (n8.length === 0 && e54.connections.length > 0)
    throw new Error("FanoutSolver: no componentId-tagged pad footprint was found");
  const o10 = new Map(e54.connections.map((e60, t10) => [e60.name, t10])), i8 = function(e60, t10) {
    const n10 = t10.buses ?? e60.buses, o11 = new Map, i9 = new Set, r10 = new Set(e60.connections.map((e61) => e61.name));
    for (const e61 of n10 ?? []) {
      if (o11.has(e61.busId))
        throw new Error(`FanoutSolver: duplicate bus id "${e61.busId}"`);
      for (const t11 of e61.connectionNames) {
        if (!r10.has(t11))
          throw new Error(`FanoutSolver: bus "${e61.busId}" references unknown connection "${t11}"`);
        if (i9.has(t11))
          throw new Error(`FanoutSolver: connection "${t11}" belongs to more than one bus`);
        i9.add(t11);
      }
      const n11 = Xse(e61.busId, e61.termination), s9 = $se(e61.busId, t10.busExitPreferences?.[e61.busId] ?? e61.preferredExit ?? t10.defaultPreferredExit);
      if (n11.type === "plane" && s9 !== undefined)
        throw new Error(`FanoutSolver: plane-terminated bus "${e61.busId}" cannot also specify preferredExit`);
      o11.set(e61.busId, { ...e61, sourceComponentId: e61.sourceComponentId ?? t10.sourceComponentId, direction: t10.busDirections?.[e61.busId] ?? e61.direction ?? t10.defaultDirection, preferredExit: s9, termination: n11 });
    }
    for (const n11 of e60.connections) {
      if (i9.has(n11.name))
        continue;
      const e61 = jse(n11);
      if (e61) {
        const i10 = o11.get(e61);
        o11.set(e61, { busId: e61, connectionNames: [...i10?.connectionNames ?? [], n11.name], direction: t10.busDirections?.[e61] ?? i10?.direction ?? t10.defaultDirection, sourceComponentId: i10?.sourceComponentId ?? t10.sourceComponentId, preferredExit: $se(e61, t10.busExitPreferences?.[e61] ?? i10?.preferredExit ?? t10.defaultPreferredExit), termination: i10?.termination ?? { type: "boundary" } });
      } else {
        const e63 = `connection:${n11.name}`;
        o11.set(e63, { busId: e63, connectionNames: [n11.name], sourceComponentId: t10.sourceComponentId, direction: t10.busDirections?.[e63] ?? t10.defaultDirection, preferredExit: $se(e63, t10.busExitPreferences?.[e63] ?? t10.defaultPreferredExit), termination: { type: "boundary" } });
      }
    }
    return [...o11.values()];
  }(e54, t4).map((t10) => {
    for (const [e60, n10] of Object.entries(t10.connectionExitTargets ?? {})) {
      if (!t10.connectionNames.includes(e60))
        throw new Error(`FanoutSolver: connectionExitTargets contains connection "${e60}" outside bus "${t10.busId}"`);
      if (!Number.isFinite(n10.x) || !Number.isFinite(n10.y))
        throw new Error(`FanoutSolver: connectionExitTargets for connection "${e60}" must contain finite x and y coordinates`);
    }
    const i9 = t10.connectionNames.map((t11) => {
      const n10 = o10.get(t11);
      if (n10 === undefined)
        throw new Error(`FanoutSolver: connection "${t11}" is missing from the input`);
      return e54.connections[n10];
    }), r10 = function(e60) {
      const { busSpec: t11, connections: n10, componentGrids: o11 } = e60, i10 = new Map;
      for (const e61 of n10) {
        const t12 = new Set;
        for (const n11 of e61.pointsToConnect)
          for (const i11 of Fse({ point: n11, connection: e61, componentGrids: o11 }))
            t12.add(i11.grid.componentId);
        for (const e63 of t12)
          i10.set(e63, (i10.get(e63) ?? 0) + 1);
      }
      const r11 = [...o11].sort((e61, t12) => {
        const n11 = (i10.get(t12.componentId) ?? 0) - (i10.get(e61.componentId) ?? 0);
        return n11 !== 0 ? n11 : t12.obstacles.length - e61.obstacles.length;
      })[0], s10 = t11.sourceComponentId ? o11.find((e61) => e61.componentId === t11.sourceComponentId) : undefined;
      if (t11.sourceComponentId && !s10)
        throw new Error(`FanoutSolver: source component "${t11.sourceComponentId}" for bus "${t11.busId}" was not found`);
      const a10 = s10 ?? r11, c5 = a10 ? i10.get(a10.componentId) ?? 0 : 0;
      if (!a10 || c5 !== n10.length)
        throw new Error(t11.sourceComponentId ? `FanoutSolver: source component "${t11.sourceComponentId}" is not an endpoint on every connection in bus "${t11.busId}"` : `FanoutSolver: bus "${t11.busId}" does not have one component endpoint on every connection`);
      return a10;
    }({ busSpec: t10, connections: i9, componentGrids: n8 }), s9 = i9.map((e60) => function(e61) {
      const { connection: t11, connectionIndex: n10, sourceGrid: o11, componentGrids: i10, termination: r11, exitTargetPoint: s10 } = e61;
      for (let e63 = 0;e63 < t11.pointsToConnect.length; e63++) {
        const a10 = t11.pointsToConnect[e63], c5 = Fse({ point: a10, connection: t11, componentGrids: i10 }).find((e64) => e64.grid.componentId === o11.componentId);
        if (!c5)
          continue;
        const l5 = Bse(a10).find((e64) => c5.obstacle.layers.includes(e64));
        if (!l5)
          throw new Error(`FanoutSolver: connection "${t11.name}" has no source layer shared with its BGA pad`);
        const h5 = Hse(a10, t11, e63, r11);
        return { connection: t11, connectionIndex: n10, sourcePoint: a10, sourcePointIndex: e63, sourceLayer: l5, sourceObstacle: c5.obstacle, targetPoint: h5, exitTargetPoint: s10 ?? h5 };
      }
      throw new Error(`FanoutSolver: connection "${t11.name}" does not touch component "${o11.componentId}"`);
    }({ connection: e60, connectionIndex: o10.get(e60.name), sourceGrid: r10, componentGrids: n8, termination: t10.termination ?? { type: "boundary" }, exitTargetPoint: t10.connectionExitTargets?.[e60.name] }));
    return { busSpec: t10, sourceGrid: r10, preparedConnections: s9 };
  }), r9 = function(e60, t10) {
    if (t10.sharedBoundary)
      return zse(t10.sharedBoundary, e60);
    const n10 = e60.map((e61) => Lse(e61, t10)), o11 = 2.25 * Math.max(...e60.flatMap((e61) => [e61.pitchX, e61.pitchY]));
    return zse({ minX: Math.min(...n10.map((e61) => e61.minX)) - o11, maxX: Math.max(...n10.map((e61) => e61.maxX)) + o11, minY: Math.min(...n10.map((e61) => e61.minY)) - o11, maxY: Math.max(...n10.map((e61) => e61.maxY)) + o11 }, e60);
  }([...new Map(i8.map(({ sourceGrid: e60 }) => [e60.componentId, e60])).values()], t4), s7 = Yse(t4.availableCornersAndSides), a9 = [];
  for (const { busSpec: e60, sourceGrid: n10, preparedConnections: o11 } of i8) {
    const i9 = Jse({ busId: e60.busId, explicitDirection: e60.direction ?? t4.busDirections?.[e60.busId], preferredExit: e60.preferredExit, connections: o11, sharedBoundary: r9, availableRegions: e60.termination?.type === "plane" ? undefined : s7 });
    a9.push({ busId: e60.busId, direction: i9.direction, preferredExit: i9.preferredExit, termination: e60.termination ?? { type: "boundary" }, connections: o11, componentId: n10.componentId, componentObstacles: n10.obstacles, componentBounds: Lse(n10, t4), sharedBoundary: r9, xCoordinates: [...n10.xCoordinates], yCoordinates: [...n10.yCoordinates], pitchX: n10.pitchX, pitchY: n10.pitchY });
  }
  return a9;
}
function Kse(e54) {
  return e54 === "left" || e54 === "right";
}
function eae(e54) {
  return e54 === "right" || e54 === "up" ? 1 : -1;
}
function tae(e54, t4) {
  return Kse(t4) ? e54.x : e54.y;
}
function nae(e54, t4) {
  return Kse(t4) ? e54.y : e54.x;
}
function oae(e54, t4, n8) {
  return Kse(n8) ? { x: e54, y: t4 } : { x: t4, y: e54 };
}
function iae(e54) {
  switch (e54.direction) {
    case "right":
      return e54.sharedBoundary.maxX;
    case "left":
      return e54.sharedBoundary.minX;
    case "up":
      return e54.sharedBoundary.maxY;
    case "down":
      return e54.sharedBoundary.minY;
  }
}
function rae(e54) {
  return Kse(e54.direction) ? e54.pitchX : e54.pitchY;
}
function sae(e54) {
  const t4 = Kse(e54.direction) ? e54.xCoordinates : e54.yCoordinates, n8 = e54.connections.reduce((t10, n10) => t10 + tae(n10.sourcePoint, e54.direction), 0) / e54.connections.length, o10 = eae(e54.direction) > 0 ? Math.max(...t4) : Math.min(...t4);
  return Math.abs(n8 - o10) < 0.000001;
}
function aae(e54, t4) {
  const n8 = [...e54.connections].sort((t10, n10) => nae(t10.sourcePoint, e54.direction) - nae(n10.sourcePoint, e54.direction)).findIndex((e60) => e60.connectionIndex === t4.connectionIndex);
  if (n8 < 0)
    throw new Error(`FanoutSolver: connection "${t4.connection.name}" is missing from bus "${e54.busId}"`);
  return n8;
}
function cae(e54, t4) {
  return e54.x >= t4.minX - 0.000001 && e54.x <= t4.maxX + 0.000001 && e54.y >= t4.minY - 0.000001 && e54.y <= t4.maxY + 0.000001;
}
function lae(e54, t4, n8, o10, i8) {
  const r9 = t4 - e54, s7 = Math.floor((r9 - o10) / (n8 + o10) + 0.000000001);
  if (s7 < 1)
    return [];
  const a9 = e54 + (r9 - (s7 * n8 + (s7 - 1) * o10)) / 2 + n8 / 2;
  return Array.from({ length: s7 }, (e60, t10) => ({ value: a9 + t10 * (n8 + o10), kind: i8 }));
}
function hae(e54) {
  const t4 = nae(e54.connection.exitTargetPoint ?? e54.connection.targetPoint, e54.bus.direction), n8 = Kse(e54.bus.direction) ? e54.bus.sharedBoundary.minY : e54.bus.sharedBoundary.minX, o10 = Kse(e54.bus.direction) ? e54.bus.sharedBoundary.maxY : e54.bus.sharedBoundary.maxX;
  return Math.max(n8 + e54.traceWidth / 2, Math.min(o10 - e54.traceWidth / 2, t4));
}
function dae(e54) {
  const { bus: t4, connection: n8, targetUsesVia: o10, interstitialEscape: i8, compactBusTracks: r9, traceWidth: s7, viaDiameter: a9, clearance: c5 } = e54, l5 = (Kse(t4.direction) ? t4.yCoordinates : t4.xCoordinates).toSorted((e60, t10) => e60 - t10), h5 = nae(n8.sourcePoint, t4.direction);
  if (r9) {
    const e60 = aae(t4, n8);
    return (l5[0] + l5.at(-1)) / 2 + (e60 - (t4.connections.length - 1) / 2) * (s7 + c5);
  }
  if (!o10 || !i8)
    return h5;
  const d9 = function(e60) {
    const t10 = (Kse(e60.direction) ? e60.xCoordinates : e60.yCoordinates).toSorted((e61, t11) => e61 - t11), n10 = e60.connections.reduce((t11, n11) => t11 + tae(n11.sourcePoint, e60.direction), 0) / e60.connections.length, o11 = eae(e60.direction) > 0 ? t10.at(-1) : t10[0];
    return Math.abs(o11 - n10) / rae(e60);
  }(t4), u9 = s7 + c5, p9 = Math.ceil(t4.connections.length / 2), m9 = (p9 - 1) * u9, g10 = a9 / 2 + s7 / 2 + c5 + 0.001, f10 = Math.round(d9) + 1, _5 = f10 * g10 + (f10 - 1) * m9, y10 = aae(t4, n8), b10 = l5[0], x8 = l5.at(-1), v10 = y10 < p9 ? b10 - _5 - (p9 - y10 - 1) * u9 : x8 + _5 + (y10 - p9) * u9, I6 = Kse(t4.direction) ? t4.sharedBoundary.minY : t4.sharedBoundary.minX, S6 = Kse(t4.direction) ? t4.sharedBoundary.maxY : t4.sharedBoundary.maxX;
  return Math.max(I6 + s7 / 2, Math.min(S6 - s7 / 2, v10));
}
function uae(e54) {
  const t4 = eae(e54.direction), n8 = [...e54.connections].sort((n10, o11) => {
    const i9 = t4 * (tae(o11.sourcePoint, e54.direction) - tae(n10.sourcePoint, e54.direction));
    return Math.abs(i9) > 0.000001 ? i9 : nae(n10.sourcePoint, e54.direction) - nae(o11.sourcePoint, e54.direction);
  }), o10 = [...e54.connections].sort((n10, o11) => nae(n10.sourcePoint, e54.direction) - nae(o11.sourcePoint, e54.direction) || t4 * (tae(o11.sourcePoint, e54.direction) - tae(n10.sourcePoint, e54.direction))), i8 = [n8, [...n8].reverse(), o10, [...o10].reverse()];
  for (let e60 = 1;e60 < Math.min(n8.length, 8); e60++)
    i8.push([...n8.slice(e60), ...n8.slice(0, e60)]);
  return i8;
}
function pae(e54, t4, n8, o10, i8) {
  Bre(t4, n8) < 0.000000001 || e54.push({ start: t4, end: n8, width: o10, layer: i8 });
}
function mae(e54) {
  const { preparedConnection: t4, bus: n8, targetLayer: o10, track: i8, exitAxis: r9, layerNames: s7, traceWidth: a9, viaDiameter: c5, viaHoleDiameter: l5, viaHandedness: h5, interstitialEscape: d9, spreadLaneIndex: u9, clearance: p9, terminateAtVia: m9 } = e54, g10 = { x: t4.sourcePoint.x, y: t4.sourcePoint.y }, f10 = eae(n8.direction), _5 = rae(n8), y10 = function(e60) {
    return Kse(e60.direction) ? e60.pitchY : e60.pitchX;
  }(n8), b10 = o10 !== t4.sourceLayer, x8 = Kse(n8.direction) ? t4.sourceObstacle.width : t4.sourceObstacle.height, v10 = b10 && !sae(n8) ? x8 >= _5 ? x8 / 2 + c5 / 2 + p9 + 0.001 : 0.5 * _5 : b10 ? Math.max(0.5 * _5, x8 / 2 + (b10 ? c5 : a9) / 2 + p9 + 0.001) : x8 / 2 + a9 / 2 + p9 + 0.001, I6 = tae(g10, n8.direction) + f10 * v10, S6 = nae(g10, n8.direction) + h5 * y10 * 0.5, C = oae(I6, S6, n8.direction), P = c5 / 2 + a9 / 2 + p9 + 0.001 + u9 * (a9 + p9), M = d9 && _5 >= P + c5 / 2 + p9, w = M ? oae(I6 + f10 * P, S6, n8.direction) : C, N = oae(M ? tae(w, n8.direction) : I6 + f10 * Math.abs(i8 - S6), i8, n8.direction), R10 = m9 ? C : oae(r9, i8, n8.direction), T2 = [], E10 = [];
  let A7;
  if (E10.push({ route_type: "wire", x: g10.x, y: g10.y, width: a9, layer: t4.sourceLayer, start_pcb_port_id: t4.sourcePoint.pcb_port_id }), pae(T2, g10, C, a9, t4.sourceLayer), E10.push({ route_type: "wire", x: C.x, y: C.y, width: a9, layer: t4.sourceLayer }), o10 !== t4.sourceLayer) {
    const e60 = Gre(t4.sourceLayer, o10, s7);
    A7 = { center: C, diameter: c5, holeDiameter: l5, fromLayer: t4.sourceLayer, toLayer: o10, spanLayers: e60 }, E10.push({ route_type: "via", x: C.x, y: C.y, from_layer: t4.sourceLayer, to_layer: o10, via_diameter: c5, via_hole_diameter: l5 }), E10.push({ route_type: "wire", x: C.x, y: C.y, width: a9, layer: o10 });
  }
  const O10 = m9 ? [C] : M ? function(e60, t10) {
    if (e60.length < 3)
      return e60;
    const n10 = [e60[0]];
    for (let o11 = 1;o11 < e60.length - 1; o11++) {
      const i9 = e60[o11 - 1], r10 = e60[o11], s9 = e60[o11 + 1], a10 = Bre(i9, r10), c9 = Bre(r10, s9);
      if (a10 < 0.000000001 || c9 < 0.000000001)
        continue;
      const l10 = { x: (r10.x - i9.x) / a10, y: (r10.y - i9.y) / a10 }, h9 = { x: (s9.x - r10.x) / c9, y: (s9.y - r10.y) / c9 }, d10 = l10.x * h9.x + l10.y * h9.y;
      if (Math.abs(d10) > 0.000001) {
        n10.push(r10);
        continue;
      }
      const u10 = Math.min(t10, a10 / 2, c9 / 2);
      n10.push({ x: r10.x - l10.x * u10, y: r10.y - l10.y * u10 }), n10.push({ x: r10.x + h9.x * u10, y: r10.y + h9.y * u10 });
    }
    return n10.push(e60.at(-1)), n10;
  }([C, w, N, R10], Math.max(a9 + p9, 2 * a9)) : [C, N, R10];
  for (let e60 = 1;e60 < O10.length; e60++) {
    const t10 = O10[e60 - 1], n10 = O10[e60];
    pae(T2, t10, n10, a9, o10), E10.push({ route_type: "wire", x: n10.x, y: n10.y, width: a9, layer: o10 });
  }
  const k6 = Are({ connectionName: t4.connection.name, sourcePointIndex: t4.sourcePointIndex });
  return { busId: n8.busId, connectionName: t4.connection.name, connectionIndex: t4.connectionIndex, sourcePointIndex: t4.sourcePointIndex, sourcePoint: t4.sourcePoint, sourceObstacle: t4.sourceObstacle, sourceLayer: t4.sourceLayer, targetPoint: t4.targetPoint, targetLayer: o10, termination: n8.termination, direction: n8.direction, exitPoint: R10, trace: { type: "pcb_trace", pcb_trace_id: k6.traceId, connection_name: t4.connection.name, connectsTo: [...t4.sourcePoint.pointId ? [t4.sourcePoint.pointId] : [], ...t4.sourcePoint.pcb_port_id ? [t4.sourcePoint.pcb_port_id] : [], k6.boundaryExitPointId], route: E10 }, segments: T2, via: A7, length: T2.reduce((e60, t10) => e60 + Bre(t10.start, t10.end), 0) };
}
function gae(e54) {
  const { preparedConnection: t4, bus: n8, viaDiameter: o10, clearance: i8 } = e54, { sourcePoint: r9, targetPoint: s7 } = t4, a9 = 0.5 * Math.max(n8.pitchX, n8.pitchY);
  if (Bre(r9, s7) <= 0.000001 || Bre(r9, s7) > a9)
    return [];
  const c5 = (() => {
    switch (n8.direction) {
      case "left":
        return { x: -1, y: 0 };
      case "right":
        return { x: 1, y: 0 };
      case "up":
        return { x: 0, y: 1 };
      case "down":
        return { x: 0, y: -1 };
    }
  })(), l5 = Math.SQRT1_2, h5 = [c5, ...[{ x: l5, y: l5 }, { x: l5, y: -l5 }, { x: -l5, y: l5 }, { x: -l5, y: -l5 }, { x: 1, y: 0 }, { x: -1, y: 0 }, { x: 0, y: 1 }, { x: 0, y: -1 }].toSorted((e60, t10) => t10.x * c5.x + t10.y * c5.y - (e60.x * c5.x + e60.y * c5.y))], d9 = Math.max(o10, o10 / 2 + i8), u9 = [d9, Math.max(d9, 0.5 * Math.min(n8.pitchX, n8.pitchY)), Math.max(d9, 0.625 * Math.min(n8.pitchX, n8.pitchY)), Math.max(d9, 0.75 * Math.min(n8.pitchX, n8.pitchY))], p9 = [];
  for (const e60 of [r9, s7])
    for (const t10 of u9)
      for (const n10 of h5) {
        const o11 = { x: e60.x + n10.x * t10, y: e60.y + n10.y * t10 };
        Bre(o11, r9) <= 0.000001 || Bre(o11, s7) <= 0.000001 || p9.some((e61) => Bre(e61, o11) <= 0.000001) || p9.push(o11);
      }
  return p9;
}
function fae(e54) {
  const { plan: t4, preparedConnection: n8, planeLayer: o10, viaPoint: i8, layerNames: r9, traceWidth: s7, viaDiameter: a9, viaHoleDiameter: c5 } = e54, l5 = { x: n8.targetPoint.x, y: n8.targetPoint.y }, h5 = function(e60) {
    const t10 = "layer" in e60 ? e60.layer : e60.layers[0];
    if (!t10)
      throw new Error("FanoutSolver: plane endpoint has no copper layer");
    return t10;
  }(n8.targetPoint), d9 = Gre(o10, h5, r9);
  if (!d9.includes(o10))
    throw new Error(`FanoutSolver: via for "${n8.connection.name}" does not cross plane ${o10}`);
  const u9 = [{ start: i8, end: l5, width: s7, layer: h5 }], p9 = { center: i8, diameter: a9, holeDiameter: c5, fromLayer: o10, toLayer: h5, spanLayers: d9 }, m9 = Are({ connectionName: n8.connection.name, sourcePointIndex: n8.sourcePointIndex }), g10 = { type: "pcb_trace", pcb_trace_id: m9.planeEndpointTraceId, connection_name: n8.connection.name, connectsTo: [...n8.targetPoint.pointId ? [n8.targetPoint.pointId] : [], ...n8.targetPoint.pcb_port_id ? [n8.targetPoint.pcb_port_id] : [], m9.planeEndpointPointId], route: [{ route_type: "wire", ...i8, width: s7, layer: o10 }, { route_type: "via", ...i8, from_layer: o10, to_layer: h5, via_diameter: a9, via_hole_diameter: c5 }, { route_type: "wire", ...i8, width: s7, layer: h5 }, { route_type: "wire", ...l5, width: s7, layer: h5 }] };
  return { ...t4, planeEndpointTrace: g10, planeEndpointSegments: u9, planeEndpointVia: p9, length: t4.length + u9.reduce((e60, t10) => e60 + Bre(t10.start, t10.end), 0) };
}
function _ae(e54) {
  const { segment: t4, plan: n8, segmentIndex: o10, srj: i8, allowSameNetMerges: r9, obstacles: s7, clearance: a9 } = e54;
  for (const e60 of s7)
    if (e60.layers.includes(t4.layer) && !e60.connectedTo.includes(n8.connectionName) && !(r9 && ese(i8, e60, n8.connectionName) || hse({ inputSrj: i8, segment: t4, bodyObstacle: e60, connectionName: n8.connectionName }) || o10 === 0 && e60 === n8.sourceObstacle && t4.layer === n8.sourceLayer || !(Hre(t4, e60) < t4.width / 2 + a9 - 0.000000001)))
      return false;
  return true;
}
function yae(e54) {
  return [...e54.segments, ...e54.planeEndpointSegments ?? []];
}
function bae(e54) {
  return [e54.via, e54.planeEndpointVia].filter((e60) => Boolean(e60));
}
function xae(e54) {
  const { plan: t4, srj: n8, sharedBoundary: o10, clearance: i8, allowSameNetMerges: r9 } = e54, s7 = function(e60, t10) {
    return { minX: Math.min(e60.minX, t10.minX), maxX: Math.max(e60.maxX, t10.maxX), minY: Math.min(e60.minY, t10.minY), maxY: Math.max(e60.maxY, t10.maxY) };
  }(n8.bounds, o10);
  if (!cae(t4.exitPoint, s7) || yae(t4).some((e60) => !cae(e60.start, s7) || !cae(e60.end, s7)))
    return false;
  const a9 = yae(t4);
  for (let e60 = 0;e60 < a9.length; e60++)
    if (!_ae({ segment: a9[e60], plan: t4, segmentIndex: e60 < t4.segments.length ? e60 : -1, srj: n8, allowSameNetMerges: r9, obstacles: n8.obstacles, clearance: i8 }))
      return false;
  for (const e60 of bae(t4))
    for (const o11 of n8.obstacles)
      if (o11.layers.some((t10) => e60.spanLayers.includes(t10)) && (!r9 || !ese(n8, o11, t4.connectionName)) && Xre(e60.center, o11) < e60.diameter / 2 + i8 - 0.000000001)
        return false;
  return true;
}
function vae(e54) {
  const { plan: t4, otherPlans: n8, staticClearanceCache: o10, blockingBusCounts: i8, cacheKey: r9, srj: s7, sharedBoundary: a9, clearance: c5, allowSameNetMerges: l5 } = e54;
  let h5 = o10?.get(r9);
  return h5 === undefined && (h5 = xae({ plan: t4, srj: s7, sharedBoundary: a9, clearance: c5, allowSameNetMerges: l5 }), o10?.set(r9, h5)), h5 && function(e60) {
    const { plan: t10, otherPlans: n10, srj: o11, allowSameNetMerges: i9, clearance: r10, blockingBusCounts: s9 } = e60;
    for (const e61 of n10) {
      if (i9 && Kre(o11, t10.connectionName, e61.connectionName))
        continue;
      if (t10.sourcePoint.pcb_port_id && t10.sourcePoint.pcb_port_id === e61.sourcePoint.pcb_port_id || t10.sourcePoint.pointId && t10.sourcePoint.pointId === e61.sourcePoint.pointId)
        continue;
      const n11 = () => {
        e61.busId !== t10.busId && s9?.set(e61.busId, (s9.get(e61.busId) ?? 0) + 1);
      }, a10 = yae(t10), c9 = yae(e61), l10 = bae(t10), h9 = bae(e61);
      for (const e63 of a10) {
        for (const t11 of c9)
          if (!Vre(e63, t11, r10))
            return n11(), false;
        for (const t11 of h9)
          if (t11.spanLayers.includes(e63.layer) && Fre(t11.center, e63.start, e63.end) < t11.diameter / 2 + e63.width / 2 + r10 - 0.000000001)
            return n11(), false;
      }
      for (const e63 of l10) {
        for (const t11 of c9)
          if (e63.spanLayers.includes(t11.layer) && Fre(e63.center, t11.start, t11.end) < e63.diameter / 2 + t11.width / 2 + r10 - 0.000000001)
            return n11(), false;
        for (const t11 of h9)
          if (e63.spanLayers.some((e64) => t11.spanLayers.includes(e64)) && Bre(e63.center, t11.center) < (e63.diameter + t11.diameter) / 2 + r10 - 0.000000001)
            return n11(), false;
      }
    }
    return true;
  }({ plan: t4, otherPlans: n8, srj: s7, allowSameNetMerges: l5, clearance: c5, blockingBusCounts: i8 });
}
function Iae(e54, t4 = 1) {
  const { srj: n8, bus: o10, targetLayer: i8, acceptedPlans: r9, layerNames: s7, traceWidth: a9, viaDiameter: c5, viaHoleDiameter: l5, clearance: h5, compactBusTracks: d9, staticClearanceCache: u9, blockingBusCounts: p9, allowSameNetMerges: m9 = false } = e54;
  if (!Number.isInteger(t4) || t4 < 1)
    throw new Error(`FanoutSolver: maxAlternatives must be a positive integer, received ${t4}`);
  if (o10.termination.type === "plane") {
    const t10 = function(e60) {
      const { srj: t11, bus: n10, targetLayer: o11, acceptedPlans: i9, layerNames: r10, traceWidth: s9, viaDiameter: a10, viaHoleDiameter: c9, clearance: l10, staticClearanceCache: h9, blockingBusCounts: d10, allowSameNetMerges: u10 = false } = e60, p10 = n10.connections[0]?.sourceObstacle;
      if (!p10 || n10.termination.type !== "plane")
        return null;
      const m10 = n10.connections[0].sourceLayer;
      if (o11 === m10)
        return null;
      const g11 = [n10.direction, ...["left", "right", "up", "down"].filter((e61) => e61 !== n10.direction)];
      for (const e61 of g11) {
        const m11 = e61 === n10.direction ? n10 : { ...n10, direction: e61 }, g12 = Kse(e61) ? p10.width : p10.height, f11 = rae(m11) / 2 - g12 / 2 >= a10 / 2 + l10 - 0.000000001, _10 = f11 ? [0] : [1, -1];
        for (const p11 of _10)
          for (const g13 of uae(m11)) {
            const _11 = [];
            let y11 = true;
            for (const b11 of g13) {
              const g14 = nae(b11.sourcePoint, e61), x10 = mae({ preparedConnection: b11, bus: m11, targetLayer: o11, track: g14, exitAxis: iae(m11), layerNames: r10, traceWidth: s9, viaDiameter: a10, viaHoleDiameter: c9, viaHandedness: p11, interstitialEscape: !f11, spreadLaneIndex: 0, clearance: l10, terminateAtVia: true }), v11 = [...gae({ preparedConnection: b11, bus: m11, viaDiameter: a10, clearance: l10 }).map((e63) => fae({ plan: x10, preparedConnection: b11, planeLayer: o11, viaPoint: e63, layerNames: r10, traceWidth: s9, viaDiameter: a10, viaHoleDiameter: c9 })), x10].find((r11, s10) => vae({ plan: r11, otherPlans: [...i9, ..._11], staticClearanceCache: h9, blockingBusCounts: d10, cacheKey: `plane:${n10.busId}:${o11}:${e61}:${b11.connectionIndex}:${p11}:${s10}`, srj: t11, sharedBoundary: n10.sharedBoundary, clearance: l10, allowSameNetMerges: u10 }));
              if (!v11) {
                y11 = false;
                break;
              }
              _11.push(v11);
            }
            if (y11)
              return _11;
          }
      }
      return null;
    }(e54);
    return t10 ? [t10] : [];
  }
  const g10 = iae(o10), f10 = o10.connections[0]?.sourceObstacle;
  if (!f10)
    return [[]];
  const _5 = Kse(o10.direction) ? f10.width : f10.height, y10 = o10.connections[0].sourceLayer, b10 = i8 !== y10, x8 = sae(o10), v10 = rae(o10) / 2 - _5 / 2 >= c5 / 2 + h5 - 0.000000001, I6 = b10 && !x8 && !v10, S6 = b10 ? v10 || x8 ? [0] : [1, -1] : [0], C = [], P = new Set, M = (e60, f11, _10, y11) => {
    if (C.length >= t4)
      return;
    if (_10 >= e60.length)
      return void ((e61) => {
        const t10 = e61.map((e63) => `${e63.connectionIndex}:${e63.targetLayer}:${e63.exitPoint.x}:${e63.exitPoint.y}:${e63.segments.map((e64) => `${e64.start.x},${e64.start.y},${e64.end.x},${e64.end.y},${e64.layer}`).join(";")}`).join("|");
        P.has(t10) || (P.add(t10), C.push(e61));
      })(y11);
    const x10 = e60[_10], v11 = aae(o10, x10), S10 = [hae({ bus: o10, connection: x10, traceWidth: a9 }), dae({ bus: o10, connection: x10, targetUsesVia: b10, interstitialEscape: I6, compactBusTracks: d9, traceWidth: a9, viaDiameter: c5, clearance: h5 })].filter((e61, t10, n10) => n10.findIndex((t11) => Math.abs(t11 - e61) < 0.000000001) === t10).flatMap((e61) => function(e63) {
      const { bus: t10, connection: n10, preferredTrack: o11, traceWidth: i9, clearance: r10 } = e63, s9 = (Kse(t10.direction) ? t10.yCoordinates : t10.xCoordinates).toSorted((e64, t11) => e64 - t11), a10 = Math.max(...t10.componentObstacles.map((e64) => Kse(t10.direction) ? e64.height / 2 : e64.width / 2)), c9 = Kse(t10.direction) ? t10.sharedBoundary.minY : t10.sharedBoundary.minX, l10 = Kse(t10.direction) ? t10.sharedBoundary.maxY : t10.sharedBoundary.maxX, h9 = l10 - c9, d10 = l10, u10 = [{ value: o11, kind: "preferred" }, ...lae(c9, s9[0] - a10, i9, r10, "margin")];
      for (let e64 = 0;e64 < s9.length; e64++)
        u10.push({ value: s9[e64], kind: "corridor" }), e64 < s9.length - 1 && u10.push(...lae(s9[e64] + a10, s9[e64 + 1] - a10, i9, r10, "gap"));
      u10.push(...lae(s9.at(-1) + a10, d10, i9, r10, "margin"));
      const p10 = nae(n10.sourcePoint, t10.direction), m10 = (s9[0] + s9.at(-1)) / 2;
      return u10.filter((e64) => Math.abs(e64.value - p10) <= h9 + 0.000000001).filter((e64, t11, n11) => n11.findIndex((t12) => Math.abs(t12.value - e64.value) < 0.000000001) === t11).sort((e64, t11) => Math.abs(e64.value - o11) - Math.abs(t11.value - o11) - 0.001 * (Math.abs(e64.value - m10) - Math.abs(t11.value - m10)));
    }({ bus: o10, connection: x10, preferredTrack: e61, traceWidth: a9, clearance: h5 })).filter((e61, t10, n10) => n10.findIndex((t11) => Math.abs(t11.value - e61.value) < 0.000000001) === t10);
    for (let d10 = 0;d10 < S10.length; d10++) {
      const b11 = S10[d10], P7 = mae({ preparedConnection: x10, bus: o10, targetLayer: i8, track: b11.value, exitAxis: g10, layerNames: s7, traceWidth: a9, viaDiameter: c5, viaHoleDiameter: l5, viaHandedness: f11, interstitialEscape: I6, spreadLaneIndex: Math.min(v11, o10.connections.length - v11 - 1), clearance: h5, terminateAtVia: false });
      if (vae({ plan: P7, otherPlans: [...r9, ...y11], staticClearanceCache: u9, blockingBusCounts: p9, cacheKey: `boundary:${o10.busId}:${i8}:${x10.connectionIndex}:${f11}:${d10}`, srj: n8, sharedBoundary: o10.sharedBoundary, clearance: h5, allowSameNetMerges: m9 })) {
        if (M(e60, f11, _10 + 1, [...y11, P7]), C.length >= t4)
          return;
        if (t4 === 1)
          return;
      }
    }
  };
  for (const e60 of S6)
    for (const n10 of uae(o10))
      if (M(n10, e60, 0, []), C.length >= t4)
        return C;
  return C;
}
function Sae(e54) {
  return Iae(e54, 1)[0] ?? null;
}
var Cae = 0.000000001;
var Pae = globalThis.process?.env?.FANOUT_FLOW_DEBUG === "1";
function Mae(e54) {
  const t4 = e54.connection;
  return e54.sourceObstacle.connectedTo.find((e60) => e60.startsWith("connectivity_net")) ?? t4.netConnectionName ?? e54.connection.name.replace(/::fanout:\d+$/, "");
}
function wae(e54, t4) {
  return e54 === t4.connection.sourceObstacle || e54.connectedTo.includes(t4.connection.connection.name) || e54.connectedTo.includes(t4.netKey);
}
function Nae(e54, t4) {
  const n8 = t4.x - e54.x, o10 = t4.y - e54.y, i8 = Math.abs(n8), r9 = Math.abs(o10);
  return i8 < Cae || r9 < Cae || Math.abs(i8 - r9) < Cae ? [e54, t4] : i8 > r9 ? [e54, { x: e54.x + Math.sign(n8) * r9, y: t4.y }, t4] : [e54, { x: t4.x, y: e54.y + Math.sign(o10) * i8 }, t4];
}
function Rae(e54) {
  if (e54.length < 2)
    return e54;
  const t4 = [e54[0]];
  for (const n8 of e54.slice(1)) {
    const e60 = t4.at(-1), o10 = Math.abs(n8.x - e60.x), i8 = Math.abs(n8.y - e60.y);
    o10 < Cae || i8 < Cae || Math.abs(o10 - i8) < Cae ? t4.push(n8) : t4.push(...Nae(n8, e60).reverse().slice(1));
  }
  return Tae(t4);
}
function Tae(e54) {
  if (e54.length < 3)
    return e54;
  const t4 = [e54[0]];
  for (let n8 = 1;n8 < e54.length - 1; n8++) {
    const o10 = t4.at(-1), i8 = e54[n8], r9 = e54[n8 + 1];
    Math.sign(i8.x - o10.x) === Math.sign(r9.x - i8.x) && Math.sign(i8.y - o10.y) === Math.sign(r9.y - i8.y) || t4.push(i8);
  }
  return t4.push(e54.at(-1)), t4;
}
function Eae(e54, t4) {
  if (e54.length < 3)
    return e54;
  const n8 = [e54[0]];
  for (let o10 = 1;o10 < e54.length - 1; o10++) {
    const i8 = e54[o10 - 1], r9 = e54[o10], s7 = e54[o10 + 1], a9 = Bre(i8, r9), c5 = Bre(r9, s7);
    if (a9 < Cae || c5 < Cae)
      continue;
    const l5 = { x: (r9.x - i8.x) / a9, y: (r9.y - i8.y) / a9 }, h5 = { x: (s7.x - r9.x) / c5, y: (s7.y - r9.y) / c5 };
    if (Math.abs(l5.x * h5.x + l5.y * h5.y) > 0.000001) {
      n8.push(r9);
      continue;
    }
    const d9 = Math.min(t4, a9 / 2, c5 / 2);
    n8.push({ x: r9.x - l5.x * d9, y: r9.y - l5.y * d9 }), n8.push({ x: r9.x + h5.x * d9, y: r9.y + h5.y * d9 });
  }
  return n8.push(e54.at(-1)), Tae(n8);
}
function Aae(e54, t4) {
  const n8 = [];
  for (let o10 = 1;o10 < e54.length; o10++)
    Bre(e54[o10 - 1], e54[o10]) < Cae || n8.push({ start: e54[o10 - 1], end: e54[o10], width: t4, layer: "top" });
  return n8;
}
var Oae = class {
  edges;
  levels;
  nextEdges;
  constructor(e54) {
    this.edges = Array.from({ length: e54 }, () => []), this.levels = new Int32Array(e54), this.nextEdges = new Int32Array(e54);
  }
  addEdge(e54, t4, n8, o10 = {}) {
    const i8 = { to: t4, reverseIndex: this.edges[t4].length, capacity: n8, initialCapacity: n8, ...o10 }, r9 = { to: e54, reverseIndex: this.edges[e54].length, capacity: 0, initialCapacity: 0 };
    this.edges[e54].push(i8), this.edges[t4].push(r9);
  }
  buildLevels(e54, t4) {
    this.levels.fill(-1);
    const n8 = new Int32Array(this.edges.length);
    let o10 = 0, i8 = 0;
    for (n8[i8++] = e54, this.levels[e54] = 0;o10 < i8; ) {
      const e60 = n8[o10++];
      for (const t10 of this.edges[e60])
        t10.capacity <= 0 || this.levels[t10.to] >= 0 || (this.levels[t10.to] = this.levels[e60] + 1, n8[i8++] = t10.to);
    }
    return this.levels[t4] >= 0;
  }
  sendFlow(e54, t4) {
    if (e54 === t4)
      return 1;
    for (let n8 = this.nextEdges[e54];n8 < this.edges[e54].length; n8++, this.nextEdges[e54] = n8) {
      const o10 = this.edges[e54][n8];
      if (o10.capacity <= 0 || this.levels[o10.to] !== this.levels[e54] + 1)
        continue;
      const i8 = this.sendFlow(o10.to, t4);
      if (i8 !== 0)
        return o10.capacity -= i8, this.edges[o10.to][o10.reverseIndex].capacity += i8, i8;
    }
    return 0;
  }
  maximumFlow(e54, t4, n8) {
    let o10 = 0;
    for (;o10 < n8 && this.buildLevels(e54, t4); )
      for (this.nextEdges.fill(0);o10 < n8; ) {
        const n10 = this.sendFlow(e54, t4);
        if (n10 === 0)
          break;
        o10 += n10;
      }
    return o10;
  }
};
function kae(e54) {
  const { direction: t4, availableDirections: n8, items: o10, grid: i8, obstacles: r9, traceWidth: s7, clearance: a9, occupiedNodes: c5, acceptedSegments: l5, connectorSelectionOffset: h5 = 0 } = e54;
  if (o10.length === 0)
    return { routes: [], usedNodes: [], unmatchedItems: [] };
  const { boundary: d9, step: u9, columnCount: p9, rowCount: m9, nodeCount: g10 } = i8, f10 = (e60) => i8.points[e60], _5 = s7 / 2 + a9, y10 = s7 + a9, b10 = new Uint8Array(g10);
  for (let e60 = 0;e60 < g10; e60++)
    !c5[e60] && i8.obstacleFreeNodes[e60] && (b10[e60] = 1);
  const x8 = (e60, t10) => {
    const n10 = Aae(e60, s7);
    return n10.every((e61) => r9.every((n11) => wae(n11, t10) || Hre(e61, n11) >= _5 - Cae)) && n10.every((e61) => l5.every((t11) => $re(e61.start, e61.end, t11.start, t11.end) >= y10 - Cae));
  }, v10 = new Map;
  for (const e60 of o10) {
    const t10 = `${e60.source.x.toFixed(6)}:${e60.source.y.toFixed(6)}:${e60.netKey}`, n10 = v10.get(t10) ?? [];
    n10.push(e60), v10.set(t10, n10);
  }
  const I6 = Array.from({ length: 3721 }, (e60, t10) => {
    const n10 = t10 % 61 - 30, o11 = Math.floor(t10 / 61) - 30;
    return { x: n10, y: o11, distanceSquared: n10 * n10 + o11 * o11 };
  }).sort((e60, t10) => e60.distanceSquared - t10.distanceSquared), S6 = [];
  for (const e60 of v10.values()) {
    const t10 = e60[0], n10 = Math.hypot(t10.connection.sourceObstacle.width / 2, t10.connection.sourceObstacle.height / 2) + a9 + 2 * u9, o11 = Math.round((t10.source.x - d9.minX) / u9), i9 = Math.round((t10.source.y - d9.minY) / u9), r10 = [], s9 = new Set;
    for (const e61 of I6) {
      const a10 = o11 + e61.x, c9 = i9 + e61.y;
      if (a10 < 0 || a10 >= p9 || c9 < 0 || c9 >= m9)
        continue;
      const l10 = c9 * p9 + a10;
      if (!b10[l10] || s9.has(l10))
        continue;
      if (Bre(t10.source, f10(l10)) > n10)
        continue;
      const h9 = Nae(t10.source, f10(l10));
      if (x8(h9, t10) && (s9.add(l10), r10.push({ node: l10, connectorPoints: h9 }), r10.length >= 12))
        break;
    }
    if (r10.length === 0)
      return null;
    S6.push({ item: t10, equivalentItems: e60, candidates: r10 });
  }
  const C = [];
  for (const e60 of [...S6].sort((e61, t10) => e61.candidates.length - t10.candidates.length)) {
    const t10 = e60.candidates.length === 0 ? 0 : h5 % e60.candidates.length, n10 = [...e60.candidates.slice(t10), ...e60.candidates.slice(0, t10)].find((t11) => {
      const n11 = Aae(t11.connectorPoints, s7);
      return C.every((t12) => t12.netKey === e60.item.netKey || n11.every((e61) => t12.segments.every((t13) => $re(e61.start, e61.end, t13.start, t13.end) >= y10 - Cae)));
    });
    if (!n10)
      return null;
    e60.candidates = [n10], C.push({ netKey: e60.item.netKey, segments: Aae(n10.connectorPoints, s7) });
  }
  const P = new Set(S6.map((e60) => e60.candidates[0].node));
  for (const e60 of C)
    for (const t10 of e60.segments) {
      const e61 = Math.max(0, Math.floor((Math.min(t10.start.x, t10.end.x) - y10 - d9.minX) / u9)), n10 = Math.min(p9 - 1, Math.ceil((Math.max(t10.start.x, t10.end.x) + y10 - d9.minX) / u9)), o11 = Math.max(0, Math.floor((Math.min(t10.start.y, t10.end.y) - y10 - d9.minY) / u9)), i9 = Math.min(m9 - 1, Math.ceil((Math.max(t10.start.y, t10.end.y) + y10 - d9.minY) / u9));
      for (let r10 = o11;r10 <= i9; r10++)
        for (let o12 = e61;o12 <= n10; o12++) {
          const e63 = r10 * p9 + o12;
          if (!b10[e63] || P.has(e63))
            continue;
          const n11 = f10(e63);
          $re(t10.start, t10.end, n11, n11) < y10 - Cae && (b10[e63] = 0);
        }
    }
  const M = 1 + S6.length, w = M + g10, N = w + g10, R10 = new Oae(N + 1);
  for (let e60 = 0;e60 < S6.length; e60++) {
    const t10 = 1 + e60;
    R10.addEdge(0, t10, 1);
    for (const n10 of S6[e60].candidates)
      R10.addEdge(t10, M + n10.node, 1, { gridNode: n10.node });
  }
  for (let e60 = 0;e60 < g10; e60++) {
    if (!b10[e60])
      continue;
    R10.addEdge(M + e60, w + e60, 1);
    const o11 = e60 % p9, r10 = Math.floor(e60 / p9);
    for (const t10 of i8.neighbors[e60])
      b10[t10] && R10.addEdge(w + e60, M + t10, 1, { gridNode: t10 });
    (t4 === "any" && ((!n8 || n8.has("left")) && o11 === 0 || (!n8 || n8.has("right")) && o11 === p9 - 1 || (!n8 || n8.has("down")) && r10 === 0 || (!n8 || n8.has("up")) && r10 === m9 - 1) || t4 === "left" && o11 === 0 || t4 === "right" && o11 === p9 - 1 || t4 === "down" && r10 === 0 || t4 === "up" && r10 === m9 - 1) && R10.addEdge(w + e60, N, 1, { isSink: true });
  }
  const T2 = R10.maximumFlow(0, N, S6.length), E10 = (e60) => {
    const t10 = 1 + e60;
    return R10.edges[0].some((e61) => e61.to === t10 && e61.initialCapacity === 1 && e61.capacity === 0);
  };
  if (T2 !== S6.length && Pae) {
    const e60 = S6.flatMap((e61, t10) => E10(t10) ? [] : [e61.item.connection.connection.name]);
    console.error("single-layer flow group failed", { direction: t4, achievedFlow: T2, requiredFlow: S6.length, unmatchedConnections: e60 });
  }
  const A7 = [], O10 = [], k6 = [];
  for (let e60 = 0;e60 < S6.length; e60++) {
    const t10 = S6[e60];
    if (!E10(e60)) {
      k6.push(...t10.equivalentItems);
      continue;
    }
    const n10 = 1 + e60, o11 = R10.edges[n10].find((e61) => e61.initialCapacity === 1 && e61.capacity === 0 && e61.gridNode !== undefined);
    if (o11?.gridNode === undefined)
      return null;
    const i9 = t10.candidates.find((e61) => e61.node === o11.gridNode);
    if (!i9)
      return null;
    const r10 = [f10(i9.node)];
    let a10 = i9.node;
    const c9 = [a10];
    for (let e61 = 0;e61 <= g10; e61++) {
      const e63 = w + a10, t11 = R10.edges[e63].find((e64) => e64.initialCapacity === 1 && e64.capacity === 0 && (e64.gridNode !== undefined || e64.isSink));
      if (!t11)
        return null;
      if (t11.isSink)
        break;
      if (t11.gridNode === undefined)
        return null;
      a10 = t11.gridNode, c9.push(a10), r10.push(f10(a10));
    }
    O10.push(...c9);
    const l10 = Rae(Eae(Tae([...i9.connectorPoints, ...r10.slice(1)]), u9 / 2)), h9 = Aae(l10, s7);
    for (const e61 of t10.equivalentItems)
      A7.push({ item: e61, points: l10, segments: h9 });
  }
  return { routes: A7, usedNodes: O10, unmatchedItems: k6 };
}
function Dae(e54, t4) {
  const n8 = Nae(e54, t4), o10 = Nae(t4, e54).reverse();
  return n8.length === o10.length && n8.every((e60, t10) => Bre(e60, o10[t10]) < Cae) ? [n8] : [n8, o10];
}
function Lae(e54, t4) {
  return Math.abs(e54.x - t4.minX) < Cae ? "left" : Math.abs(e54.x - t4.maxX) < Cae ? "right" : Math.abs(e54.y - t4.minY) < Cae ? "down" : Math.abs(e54.y - t4.maxY) < Cae ? "up" : null;
}
function zae(e54) {
  const { items: t4, grid: n8, obstacles: o10, traceWidth: i8, clearance: r9, availableBoundaryRegions: s7 } = e54, a9 = s7 ? new Set(s7.map((e60) => e60.direction)) : undefined, c5 = new Set(t4.filter((e60) => e60.connection.sourceObstacle.width > 2 && e60.connection.sourceObstacle.height > 2));
  let l5 = null;
  for (let e60 = 0;e60 < 4; e60++) {
    const e61 = t4.filter((e63) => !c5.has(e63));
    let s9 = null;
    for (let t10 = 0;t10 < 4; t10++) {
      const c9 = kae({ direction: "any", availableDirections: a9, items: e61, grid: n8, obstacles: o10, traceWidth: i8, clearance: r9, occupiedNodes: new Uint8Array(n8.nodeCount), acceptedSegments: [], connectorSelectionOffset: t10 });
      if (c9 && ((!s9 || c9.routes.length > s9.routes.length) && (s9 = c9), c9.routes.length === e61.length))
        break;
    }
    if (!s9)
      return null;
    if (s9.routes.length === e61.length) {
      l5 = s9;
      break;
    }
    const h9 = new Map;
    for (const t10 of e61)
      h9.set(t10.netKey, (h9.get(t10.netKey) ?? 0) + 1);
    let d10 = false;
    for (const e63 of s9.unmatchedItems)
      (h9.get(e63.netKey) ?? 0) < 2 || (c5.add(e63), d10 = true);
    if (!d10)
      return null;
  }
  if (!l5)
    return null;
  const h5 = [...l5.routes], d9 = i8 / 2 + r9, u9 = i8 + r9;
  for (const e60 of c5) {
    const t10 = h5.filter((t11) => t11.item.netKey === e60.netKey).flatMap((e61) => e61.points.map((t11, n11) => ({ route: e61, point: t11, pointIndex: n11 }))).sort((t11, n11) => Number(n11.route.item.bus.componentId === e60.bus.componentId) - Number(t11.route.item.bus.componentId === e60.bus.componentId) || Bre(e60.source, t11.point) - Bre(e60.source, n11.point));
    let n10 = null;
    for (const r10 of t10) {
      for (const t11 of Dae(e60.source, r10.point)) {
        const s9 = Aae(t11, i8), a10 = s9.every((t12) => o10.every((n11) => wae(n11, e60) || Hre(t12, n11) >= d9 - Cae)), c9 = s9.every((t12) => h5.every((n11) => n11.item.netKey === e60.netKey || n11.segments.every((e61) => $re(t12.start, t12.end, e61.start, e61.end) >= u9 - Cae)));
        if (!a10 || !c9)
          continue;
        const l10 = Rae(Tae([...t11, ...r10.route.points.slice(r10.pointIndex + 1)]));
        n10 = { item: e60, points: l10, segments: Aae(l10, i8) };
        break;
      }
      if (n10)
        break;
    }
    if (!n10)
      return null;
    h5.push(n10);
  }
  const p9 = h5.map((e60) => function(e61, t10) {
    const { item: n10, points: o11, segments: i9 } = e61, r10 = o11.map((e63, o12) => ({ route_type: "wire", x: e63.x, y: e63.y, width: t10, layer: "top", ...o12 === 0 && n10.connection.sourcePoint.pcb_port_id ? { start_pcb_port_id: n10.connection.sourcePoint.pcb_port_id } : {} })), s9 = Are({ connectionName: n10.connection.connection.name, sourcePointIndex: n10.connection.sourcePointIndex });
    return { busId: n10.bus.busId, connectionName: n10.connection.connection.name, connectionIndex: n10.connection.connectionIndex, sourcePointIndex: n10.connection.sourcePointIndex, sourcePoint: n10.connection.sourcePoint, sourceObstacle: n10.connection.sourceObstacle, sourceLayer: n10.connection.sourceLayer, targetPoint: n10.connection.targetPoint, targetLayer: "top", termination: n10.bus.termination, direction: n10.bus.direction, exitPoint: o11.at(-1), trace: { type: "pcb_trace", pcb_trace_id: s9.traceId, connection_name: n10.connection.connection.name, connectsTo: [...n10.connection.sourcePoint.pointId ? [n10.connection.sourcePoint.pointId] : [], ...n10.connection.sourcePoint.pcb_port_id ? [n10.connection.sourcePoint.pcb_port_id] : [], s9.boundaryExitPointId], route: r10 }, segments: i9, length: i9.reduce((e63, t11) => e63 + Bre(t11.start, t11.end), 0) };
  }(e60, i8));
  if (!function(e60) {
    const { plans: t10, items: n10, obstacles: o11, traceWidth: i9, clearance: r10 } = e60, s9 = new Map(n10.map((e61) => [e61.connection.connection.name, e61.netKey])), a10 = new Map, c9 = new Map;
    for (const e61 of t10) {
      const t11 = s9.get(e61.connectionName), n11 = a10.get(t11) ?? [], o12 = c9.get(t11) ?? new Set;
      for (const t12 of e61.segments) {
        const e63 = [t12.start, t12.end].map((e64) => `${e64.x.toFixed(6)}:${e64.y.toFixed(6)}`).sort().join(":");
        o12.has(e63) || (o12.add(e63), n11.push(t12));
      }
      a10.set(t11, n11), c9.set(t11, o12);
    }
    const l10 = i9 / 2 + r10;
    for (const [e61, t11] of a10)
      for (const n11 of t11)
        for (const t12 of o11)
          if (!(t12.connectedTo.includes(e61) || Hre(n11, t12) >= l10 - Cae))
            return Pae && console.error("single-layer route violates obstacle clearance", { netKey: e61, segment: n11, obstacleId: t12.obstacleId, distance: Hre(n11, t12), requiredObstacleDistance: l10 }), false;
    const h9 = i9 + r10, d10 = [...a10];
    for (let e61 = 0;e61 < d10.length; e61++)
      for (let t11 = e61 + 1;t11 < d10.length; t11++)
        for (const n11 of d10[e61][1])
          for (const o12 of d10[t11][1])
            if ($re(n11.start, n11.end, o12.start, o12.end) < h9 - Cae)
              return Pae && console.error("single-layer routes violate copper clearance", { firstNetKey: d10[e61][0], secondNetKey: d10[t11][0], first: n11, second: o12, distance: $re(n11.start, n11.end, o12.start, o12.end), requiredRouteDistance: h9 }), false;
    return true;
  }({ plans: p9, items: t4, obstacles: o10, traceWidth: i8, clearance: r9 }))
    return Pae && console.error("single-layer adaptive exits failed exact clearance"), null;
  for (const e60 of p9) {
    const o11 = Lae(e60.exitPoint, n8.boundary);
    if (!o11 || a9 && !a9.has(o11))
      return null;
    const i9 = t4.find((t10) => t10.connection.connection.name === e60.connectionName);
    i9.bus.direction = o11;
    const r10 = s7?.filter((e61) => e61.direction === o11), c9 = o11 === "up" || o11 === "down" ? e60.exitPoint.x : e60.exitPoint.y;
    i9.bus.preferredExit = r10?.toSorted((e61, t10) => Math.abs(c9 - Use(e61, n8.boundary)) - Math.abs(c9 - Use(t10, n8.boundary)))[0]?.preferredExit ?? (o11 === "up" ? "top" : o11 === "down" ? "bottom" : o11), e60.direction = o11;
  }
  const m9 = new Map(p9.map((e60) => [e60.connectionName, e60]));
  return t4.map((e60) => m9.get(e60.connection.connection.name));
}
function Bae(e54) {
  const { srj: t4, buses: n8, traceWidth: o10, clearance: i8, availableBoundaryRegions: r9 } = e54;
  if (n8.some((e60) => e60.connections.length !== 1))
    return null;
  const s7 = n8.flatMap((e60) => e60.connections.map((t10) => ({ bus: e60, connection: t10, source: { x: t10.sourcePoint.x, y: t10.sourcePoint.y }, netKey: Mae(t10) }))), a9 = t4.obstacles.filter((e60) => e60.layers.includes("top")), c5 = n8[0]?.sharedBoundary;
  if (!c5)
    return [];
  const l5 = function(e60) {
    const { boundary: t10, obstacles: n10, traceWidth: o11, clearance: i9 } = e60, r10 = o11 + i9, s9 = Math.round((t10.maxX - t10.minX) / r10) + 1, a10 = Math.round((t10.maxY - t10.minY) / r10) + 1, c9 = s9 * a10, l10 = Array.from({ length: c9 }, (e61, n11) => ({ x: t10.minX + n11 % s9 * r10, y: t10.minY + Math.floor(n11 / s9) * r10 })), h9 = o11 / 2 + i9, d9 = new Map;
    for (let e61 = 0;e61 < n10.length; e61++) {
      const t11 = n10[e61], o12 = Math.floor((t11.center.x - t11.width / 2 - h9) / 1), i10 = Math.floor((t11.center.x + t11.width / 2 + h9) / 1), r11 = Math.floor((t11.center.y - t11.height / 2 - h9) / 1), s10 = Math.floor((t11.center.y + t11.height / 2 + h9) / 1);
      for (let t12 = o12;t12 <= i10; t12++)
        for (let n11 = r11;n11 <= s10; n11++) {
          const o13 = `${t12}:${n11}`, i11 = d9.get(o13) ?? [];
          i11.push(e61), d9.set(o13, i11);
        }
    }
    const u9 = (e61, t11 = e61) => {
      const o12 = Math.floor(Math.min(e61.x, t11.x) / 1), i10 = Math.floor(Math.max(e61.x, t11.x) / 1), r11 = Math.floor(Math.min(e61.y, t11.y) / 1), s10 = Math.floor(Math.max(e61.y, t11.y) / 1), a11 = new Set;
      for (let e63 = o12;e63 <= i10; e63++)
        for (let t12 = r11;t12 <= s10; t12++)
          for (const n11 of d9.get(`${e63}:${t12}`) ?? [])
            a11.add(n11);
      return [...a11].map((e63) => n10[e63]);
    }, p9 = new Uint8Array(c9);
    for (let e61 = 0;e61 < c9; e61++) {
      const t11 = l10[e61];
      u9(t11).every((e63) => Xre(t11, e63) >= h9 - Cae) && (p9[e61] = 1);
    }
    const m9 = Array.from({ length: c9 }, () => []);
    for (let e61 = 0;e61 < c9; e61++) {
      if (!p9[e61])
        continue;
      const t11 = e61 % s9, n11 = Math.floor(e61 / s9);
      for (const [i10, r11] of [[1, 0], [0, 1]]) {
        const c10 = t11 + i10, d10 = n11 + r11;
        if (c10 >= s9 || d10 >= a10)
          continue;
        const g10 = d10 * s9 + c10;
        if (!p9[g10])
          continue;
        const f10 = { start: l10[e61], end: l10[g10], width: o11, layer: "top" };
        u9(f10.start, f10.end).some((e63) => Hre(f10, e63) < h9 - Cae) || (m9[e61].push(g10), m9[g10].push(e61));
      }
    }
    return { boundary: t10, step: r10, columnCount: s9, rowCount: a10, nodeCount: c9, points: l10, obstacleFreeNodes: p9, neighbors: m9 };
  }({ boundary: c5, obstacles: a9, traceWidth: o10, clearance: i8 });
  Pae && console.error("single-layer adaptive-exit grid ready", { nodeCount: l5.nodeCount });
  const h5 = zae({ items: s7, grid: l5, obstacles: a9, traceWidth: o10, clearance: i8, availableBoundaryRegions: r9 });
  return h5 || null;
}
function Fae(e54) {
  return e54 === "left" || e54 === "right";
}
function jae(e54) {
  return e54 === "right" || e54 === "up" ? 1 : -1;
}
function $ae(e54, t4) {
  return Fae(t4) ? e54.x : e54.y;
}
function Yae(e54, t4) {
  return Fae(t4) ? e54.y : e54.x;
}
function Xae(e54, t4, n8) {
  return Fae(n8) ? { x: e54, y: t4 } : { x: t4, y: e54 };
}
function Hae(e54) {
  switch (e54.direction) {
    case "right":
      return e54.sharedBoundary.maxX;
    case "left":
      return e54.sharedBoundary.minX;
    case "up":
      return e54.sharedBoundary.maxY;
    case "down":
      return e54.sharedBoundary.minY;
  }
}
function Vae(e54) {
  if (e54.length < 3)
    return e54;
  const t4 = [e54[0]];
  for (let n8 = 1;n8 < e54.length - 1; n8++) {
    const o10 = t4.at(-1), i8 = e54[n8], r9 = e54[n8 + 1], s7 = { x: Math.sign(i8.x - o10.x), y: Math.sign(i8.y - o10.y) }, a9 = { x: Math.sign(r9.x - i8.x), y: Math.sign(r9.y - i8.y) };
    s7.x === a9.x && s7.y === a9.y || t4.push(i8);
  }
  return t4.push(e54.at(-1)), t4;
}
function Wae(e54, t4) {
  const n8 = [];
  for (let o10 = 1;o10 < e54.length; o10++)
    Bre(e54[o10 - 1], e54[o10]) < 0.000000001 || n8.push({ start: e54[o10 - 1], end: e54[o10], width: t4, layer: "top" });
  return n8;
}
function Gae(e54) {
  const { item: t4, srj: n8, acceptedSegments: o10, traceWidth: i8, clearance: r9 } = e54, s7 = t4.cornerChannelPrefixes;
  if (!s7)
    return null;
  const a9 = t4.direction, c5 = jae(a9), l5 = Hae(t4.bus), h5 = i8 + r9, d9 = i8 / 2 + r9, u9 = Fae(a9) ? t4.bus.sharedBoundary.minY : t4.bus.sharedBoundary.minX, p9 = Fae(a9) ? t4.bus.sharedBoundary.maxY : t4.bus.sharedBoundary.maxX, m9 = u9 + i8 / 2, g10 = p9 - i8 / 2, f10 = Yae(t4.connection.exitTargetPoint ?? t4.connection.targetPoint, a9), _5 = h5 / 2, y10 = new Set([Math.max(m9, Math.min(g10, f10))]);
  for (let e60 = Math.ceil(m9 / _5) * _5;e60 <= g10 + 0.000000001; e60 += _5)
    y10.add(Number(e60.toFixed(9)));
  const b10 = [...y10].toSorted((e60, t10) => Math.abs(e60 - f10) - Math.abs(t10 - f10));
  for (const e60 of s7) {
    const s9 = e60.at(-1), u10 = Yae(s9, a9);
    for (const p10 of b10) {
      const m10 = Math.abs(p10 - u10), g11 = Xae($ae(s9, a9) + c5 * h5, u10, a9), f11 = Xae($ae(g11, a9) + c5 * m10, p10, a9);
      if (c5 * (l5 - $ae(f11, a9)) < -0.000000001)
        continue;
      const _10 = Xae(l5, p10, a9), y11 = [...e60, g11, ...m10 > 0.000000001 ? [f11] : []];
      Bre(y11.at(-1), _10) > 0.000000001 && y11.push(_10);
      const b11 = Vae(y11), x8 = Wae(b11, i8);
      if (!x8.every((e61) => n8.obstacles.every((n10) => n10 === t4.connection.sourceObstacle || !n10.layers.includes("top") || Hre(e61, n10) >= d9 - 0.000000001)))
        continue;
      if (x8.every((e61) => o10.every((t10) => $re(e61.start, e61.end, t10.start, t10.end) >= i8 + r9 - 0.000000001)))
        return { item: t4, points: b11, track: p10 };
    }
  }
  return null;
}
function Uae(e54) {
  const { route: t4, direction: n8, exitAxis: o10, signedShift: i8, maximumShift: r9, obstacles: s7, requiredObstacleDistance: a9 } = e54;
  if (r9 <= 0.000000001 || Math.abs(i8) <= 0.000000001)
    return 0;
  const c5 = Math.sign(i8), l5 = (e60) => {
    if (e60 <= 0.000000001)
      return true;
    const i9 = { start: Xae(o10 - jae(n8) * e60, t4.track, n8), end: Xae(o10, t4.track + c5 * e60, n8), width: 0, layer: "top" };
    return s7.every((e61) => e61 === t4.item.connection.sourceObstacle || !e61.layers.includes("top") || Hre(i9, e61) >= a9 - 0.000000001);
  };
  if (l5(r9))
    return r9;
  let h5 = 0, d9 = r9;
  for (let e60 = 0;e60 < 32; e60++) {
    const e61 = (h5 + d9) / 2;
    l5(e61) ? h5 = e61 : d9 = e61;
  }
  return h5;
}
function Zae(e54) {
  const { requestedTracks: t4, currentTracks: n8, candidateTracks: o10, maximumShifts: i8 } = e54, r9 = t4.length + 1, s7 = o10.length + 1, a9 = Array.from({ length: r9 }, () => new Float64Array(s7).fill(Number.POSITIVE_INFINITY)), c5 = Array.from({ length: r9 }, () => new Uint8Array(s7));
  a9[0].fill(0);
  for (let e60 = 1;e60 < r9; e60++)
    for (let r10 = 1;r10 < s7; r10++) {
      const s9 = a9[e60][r10 - 1], l10 = Math.abs(t4[e60 - 1] - o10[r10 - 1]), h9 = Math.abs(n8[e60 - 1] - o10[r10 - 1]) > i8[e60 - 1] + 0.000000001 ? Number.POSITIVE_INFINITY : a9[e60 - 1][r10 - 1] + l10;
      h9 < s9 ? (a9[e60][r10] = h9, c5[e60][r10] = 1) : a9[e60][r10] = s9;
    }
  if (!Number.isFinite(a9.at(-1).at(-1)))
    return null;
  const l5 = [];
  let h5 = t4.length, d9 = o10.length;
  for (;h5 > 0 && d9 > 0; )
    c5[h5][d9] && (l5.push(o10[d9 - 1]), h5--), d9--;
  return h5 > 0 ? null : l5.reverse();
}
function qae(e54) {
  const { direction: t4, activeRoutes: n8, obstacles: o10, boundaryMinimum: i8, boundaryMaximum: r9, traceWidth: s7, clearance: a9, requestedTracks: c5, maximumShifts: l5 } = e54, h5 = s7 + a9, d9 = s7 / 2 + a9;
  let u9 = null, p9 = Number.POSITIVE_INFINITY;
  for (const e60 of Array.from({ length: Math.round(h5 / s7) }, (e61, t10) => t10 * s7)) {
    const a10 = [];
    for (let n10 = Math.ceil((i8 - e60) / h5) * h5 + e60;n10 <= r9 + 0.000000001; n10 += h5) {
      const e61 = Math.round(n10 / s7) * s7;
      o10.every((n11) => {
        const o11 = Yae(n11.center, t4), i9 = Fae(t4) ? n11.height : n11.width;
        return Math.abs(e61 - o11) >= i9 / 2 + d9 - 0.000000001;
      }) && a10.push(e61);
    }
    const m9 = Zae({ requestedTracks: c5, currentTracks: n8.map((e61) => e61.track), candidateTracks: a10, maximumShifts: l5 });
    if (!m9)
      continue;
    const g10 = m9.reduce((e61, t10, n10) => e61 + Math.abs(t10 - c5[n10]), 0);
    g10 < p9 && (p9 = g10, u9 = m9);
  }
  return u9;
}
function Jae(e54, t4) {
  switch (t4) {
    case "up":
      return e54 === "top-left" ? "minimum" : e54 === "top-right" ? "maximum" : null;
    case "down":
      return e54 === "bottom-left" ? "minimum" : e54 === "bottom-right" ? "maximum" : null;
    case "left":
      return e54 === "bottom-left" ? "minimum" : e54 === "top-left" ? "maximum" : null;
    case "right":
      return e54 === "bottom-right" ? "minimum" : e54 === "top-right" ? "maximum" : null;
  }
}
function Qae(e54) {
  const { items: t4, direction: n8, boundaryMinimum: o10, boundaryMaximum: i8, traceWidth: r9, clearance: s7, borderDistribution: a9, currentTrackByConnectionName: c5 } = e54, l5 = (e60) => c5.get(e60.connection.connection.name) ?? Yae(e60.source, n8), h5 = [...t4].toSorted((e60, t10) => l5(e60) - l5(t10) || e60.connection.connection.name.localeCompare(t10.connection.connection.name)), d9 = r9 + s7, u9 = o10 + r9 / 2, p9 = i8 - r9 / 2;
  if (p9 - u9 < d9 * Math.max(h5.length - 1, 0) - 0.000000001)
    return null;
  const m9 = h5.map(l5);
  let g10 = [...m9], f10 = d9;
  const _5 = new Set;
  if (a9 === "even" && h5.length > 1) {
    const e60 = m9[0], t10 = m9.at(-1), n10 = Math.max(d9, (t10 - e60) / (h5.length - 1)), o11 = (e61) => {
      const t11 = [...m9], n11 = Math.floor(h5.length / 2), o12 = h5.length % 2 == 0 ? n11 - 1 : n11;
      if (o12 !== n11) {
        const i10 = t11[n11] - t11[o12];
        if (i10 < e61) {
          const r10 = (e61 - i10) / 2;
          t11[o12] = t11[o12] - r10, t11[n11] = t11[n11] + r10;
        }
      }
      for (let n12 = o12 - 1;n12 >= 0; n12--)
        t11[n12] = Math.min(t11[n12], t11[n12 + 1] - e61);
      for (let o13 = n11 + 1;o13 < t11.length; o13++)
        t11[o13] = Math.max(t11[o13], t11[o13 - 1] + e61);
      return t11;
    }, i9 = (e61) => e61[0] >= u9 - 0.000000001 && e61.at(-1) <= p9 + 0.000000001;
    if (g10 = o11(n10), i9(g10))
      f10 = n10;
    else {
      let e61 = d9, t11 = n10;
      if (g10 = o11(e61), !i9(g10))
        return null;
      for (let n11 = 0;n11 < 32; n11++) {
        const n12 = (e61 + t11) / 2, r10 = o11(n12);
        i9(r10) ? (e61 = n12, g10 = r10) : t11 = n12;
      }
      f10 = e61;
    }
    for (const e61 of h5)
      _5.add(e61.connection.connection.name);
  }
  const y10 = [], b10 = [];
  for (let e60 = 0;e60 < h5.length; e60++) {
    const t10 = h5[e60], o11 = t10.bus.preferredExit;
    if (!o11?.includes("-"))
      continue;
    const i9 = Jae(o11, n8);
    if (!i9)
      return null;
    _5.add(t10.connection.connection.name), i9 === "minimum" ? y10.push(e60) : b10.push(e60);
  }
  if (y10.some((e60, t10) => e60 !== t10) || b10.some((e60, t10) => e60 !== h5.length - b10.length + t10))
    return null;
  const x8 = 2 * d9;
  if (y10.length > 0) {
    g10[0] = u9 + x8;
    for (let e60 = 1;e60 < y10.length; e60++) {
      const t10 = Math.max(f10, m9[e60] - m9[e60 - 1]);
      g10[e60] = g10[e60 - 1] + t10;
    }
  }
  if (b10.length > 0) {
    const e60 = h5.length - 1;
    g10[e60] = p9 - x8;
    for (let t10 = e60 - 1;t10 >= h5.length - b10.length; t10--) {
      const e61 = Math.max(f10, m9[t10 + 1] - m9[t10]);
      g10[t10] = g10[t10 + 1] - e61;
    }
  }
  return { byConnectionName: new Map(h5.map((e60, t10) => [e60.connection.connection.name, g10[t10]])), enforcedConnectionNames: _5 };
}
function Kae(e54) {
  const { item: t4, points: n8, segments: o10 } = e54, i8 = n8.map((e60, n10) => ({ route_type: "wire", x: e60.x, y: e60.y, width: o10[0]?.width ?? 0.1, layer: "top", ...n10 === 0 && t4.connection.sourcePoint.pcb_port_id ? { start_pcb_port_id: t4.connection.sourcePoint.pcb_port_id } : {} })), r9 = Are({ connectionName: t4.connection.connection.name, sourcePointIndex: t4.connection.sourcePointIndex });
  return { busId: t4.bus.busId, connectionName: t4.connection.connection.name, connectionIndex: t4.connection.connectionIndex, sourcePointIndex: t4.connection.sourcePointIndex, sourcePoint: t4.connection.sourcePoint, sourceObstacle: t4.connection.sourceObstacle, sourceLayer: t4.connection.sourceLayer, targetPoint: t4.connection.targetPoint, targetLayer: "top", termination: t4.bus.termination, direction: t4.direction, exitPoint: n8.at(-1), trace: { type: "pcb_trace", pcb_trace_id: r9.traceId, connection_name: t4.connection.connection.name, connectsTo: [...t4.connection.sourcePoint.pointId ? [t4.connection.sourcePoint.pointId] : [], ...t4.connection.sourcePoint.pcb_port_id ? [t4.connection.sourcePoint.pcb_port_id] : [], r9.boundaryExitPointId], route: i8 }, segments: o10, length: o10.reduce((e60, t10) => e60 + Bre(t10.start, t10.end), 0) };
}
function ece(e54) {
  const { srj: t4, buses: n8, traceWidth: o10, clearance: i8, borderDistribution: r9 } = e54, s7 = o10 / 2 + i8, a9 = new Map, c5 = new Map, l5 = n8.flatMap((e60) => e60.connections.map((n10) => {
    const r10 = { x: n10.sourcePoint.x, y: n10.sourcePoint.y }, s9 = function(e61) {
      const { srj: t10, bus: n11, connection: o11, traceWidth: i9, clearance: r11 } = e61, s10 = n11.direction, a10 = jae(s10), c9 = { x: o11.sourcePoint.x, y: o11.sourcePoint.y }, l10 = $ae(c9, s10), h9 = Yae(c9, s10), d10 = i9 / 2 + r11, u10 = (() => {
        switch (s10) {
          case "right":
            return n11.componentBounds.maxX + d10;
          case "left":
            return n11.componentBounds.minX - d10;
          case "up":
            return n11.componentBounds.maxY + d10;
          case "down":
            return n11.componentBounds.minY - d10;
        }
      })(), p9 = (e63) => Math.min(...t10.obstacles.filter((e64) => e64 !== o11.sourceObstacle && e64.layers.includes("top")).map((t11) => Hre(e63, t11))), m9 = { start: c9, end: Xae(u10, h9, s10), width: i9, layer: "top" };
      if (p9(m9) >= d10 - 0.000000001)
        return null;
      const g10 = Fae(s10) ? { minimum: n11.componentBounds.minY, maximum: n11.componentBounds.maxY } : { minimum: n11.componentBounds.minX, maximum: n11.componentBounds.maxX }, f10 = a10 * (u10 - l10), _5 = Yae(o11.exitTargetPoint ?? o11.targetPoint, s10), y10 = i9 + r11, b10 = Hae(n11), x8 = [-1, 1].map((e63) => {
        const t11 = e63 * ((e63 < 0 ? g10.minimum - d10 : g10.maximum + d10) - h9), o12 = Math.max(f10, t11), r12 = Xae(l10 + a10 * o12, h9 + e63 * o12, s10);
        if (a10 * (b10 - $ae(r12, s10)) < y10 - 0.000000001)
          return null;
        const u11 = [c9, r12];
        if (!u11.every((e64) => e64.x >= n11.sharedBoundary.minX - 0.000000001 && e64.x <= n11.sharedBoundary.maxX + 0.000000001 && e64.y >= n11.sharedBoundary.minY - 0.000000001 && e64.y <= n11.sharedBoundary.maxY + 0.000000001))
          return null;
        const m10 = Math.min(...Wae(u11, i9).map(p9));
        return m10 < d10 - 0.000000001 ? null : { points: u11, obstacleDistance: m10, targetDistance: Math.abs(Yae(r12, s10) - _5) };
      }).filter((e63) => e63 !== null).toSorted((e63, t11) => t11.obstacleDistance - e63.obstacleDistance || e63.targetDistance - t11.targetDistance);
      return x8.length > 0 ? x8.map((e63) => e63.points) : null;
    }({ srj: t4, bus: e60, connection: n10, traceWidth: o10, clearance: i8 });
    return { bus: e60, connection: n10, direction: e60.direction, source: r10, ...s9 ? { cornerChannelPrefixes: s9 } : {} };
  }));
  for (const e60 of ["left", "right", "up", "down"]) {
    const n10 = jae(e60), h9 = l5.filter((t10) => t10.direction === e60 && !t10.cornerChannelPrefixes);
    if (h9.length === 0)
      continue;
    const d10 = Fae(e60) ? h9[0].bus.sharedBoundary.minY : h9[0].bus.sharedBoundary.minX, u10 = Fae(e60) ? h9[0].bus.sharedBoundary.maxY : h9[0].bus.sharedBoundary.maxX, p9 = Hae(h9[0].bus), m9 = new Map, g10 = new Map, f10 = new Map;
    for (const t10 of h9) {
      const n11 = $ae(t10.source, e60), o11 = n11.toFixed(6);
      f10.set(o11, n11);
      const i9 = m9.get(o11) ?? [];
      i9.push(t10), m9.set(o11, i9);
    }
    for (const [n11, o11] of m9) {
      const i9 = f10.get(n11), r10 = new Set(o11.map((e61) => e61.bus.componentId));
      g10.set(n11, t4.obstacles.filter((t10) => t10.layers.includes("top") && !!t10.componentId && r10.has(t10.componentId) && Math.abs($ae(t10.center, e60) - i9) < 0.000001));
    }
    const _5 = [...f10.values()].toSorted((e61, t10) => n10 * (e61 - t10)), y10 = new Map;
    for (let t10 = 0;t10 < _5.length; t10++) {
      const r10 = _5[t10], a10 = r10.toFixed(6);
      for (const t11 of m9.get(a10) ?? []) {
        const o11 = Fae(e60) ? t11.connection.sourceObstacle.width : t11.connection.sourceObstacle.height, i9 = Math.max(t11.connection.sourceObstacle.width, t11.connection.sourceObstacle.height) < 1.5 ? o11 / 2 + s7 : 0, a11 = Xae(r10 + n10 * i9, Yae(t11.source, e60), e60);
        y10.set(t11.connection.connection.name, { item: t11, points: Bre(t11.source, a11) > 0.000000001 ? [t11.source, a11] : [t11.source], track: Yae(t11.source, e60) });
      }
      const c9 = _5[t10 + 1] ?? p9;
      if (y10.size === 0 || n10 * (c9 - r10) <= 0.000000001)
        continue;
      const l10 = [...y10.values()].toSorted((e61, t11) => e61.track - t11.track || e61.item.connection.connection.name.localeCompare(t11.item.connection.connection.name)), h10 = _5.slice(t10 + 1, t10 + 3).flatMap((e61) => g10.get(e61.toFixed(6)) ?? []), f11 = l10.map((t11) => Math.abs(c9 - $ae(t11.points.at(-1), e60))), b11 = qae({ direction: e60, activeRoutes: l10, obstacles: h10, boundaryMinimum: d10, boundaryMaximum: u10, traceWidth: o10, clearance: i8, requestedTracks: l10.map((e61) => e61.track), maximumShifts: f11 });
      if (!b11)
        return null;
      for (let t11 = 0;t11 < l10.length; t11++) {
        const o11 = l10[t11], i9 = b11[t11], r11 = Math.abs(i9 - o11.track), s9 = Xae($ae(o11.points.at(-1), e60) + n10 * r11, i9, e60);
        Bre(o11.points.at(-1), s9) > 0.000000001 && o11.points.push(s9);
        const a11 = Xae(c9, i9, e60);
        Bre(o11.points.at(-1), a11) > 0.000000001 && o11.points.push(a11), o11.track = i9;
      }
    }
    const b10 = Qae({ items: h9, direction: e60, boundaryMinimum: d10, boundaryMaximum: u10, traceWidth: o10, clearance: i8, borderDistribution: r9, currentTrackByConnectionName: new Map([...y10.values()].map((e61) => [e61.item.connection.connection.name, e61.track])) });
    if (!b10)
      return null;
    const x8 = [...y10.values()].toSorted((e61, t10) => e61.track - t10.track || e61.item.connection.connection.name.localeCompare(t10.item.connection.connection.name)), v10 = new Map, I6 = o10 + i8;
    let S6 = I6;
    for (const e61 of x8) {
      const t10 = e61.item.connection.connection.name;
      if (!b10.enforcedConnectionNames.has(t10))
        continue;
      b10.byConnectionName.get(t10) - e61.track >= -0.000000001 || (v10.set(t10, S6), S6 += 2 * I6);
    }
    let C = I6;
    for (let e61 = x8.length - 1;e61 >= 0; e61--) {
      const t10 = x8[e61], n11 = t10.item.connection.connection.name;
      if (!b10.enforcedConnectionNames.has(n11))
        continue;
      b10.byConnectionName.get(n11) - t10.track <= 0.000000001 || (v10.set(n11, C), C += 2 * I6);
    }
    for (const o11 of x8) {
      const i9 = o11.item.connection.connection.name, r10 = b10.byConnectionName.get(i9) ?? o11.track, a10 = v10.get(i9) ?? 0, c9 = o11.points.at(-2), l10 = c9 ? n10 * (p9 - $ae(c9, e60)) : 0, h10 = r10 - o11.track, d11 = Math.min(Math.abs(h10), Math.max(0, l10 - a10)), u11 = Uae({ route: o11, direction: e60, exitAxis: p9, signedShift: h10, maximumShift: d11, obstacles: t4.obstacles, requiredObstacleDistance: s7 }), m10 = Math.sign(h10) * u11;
      b10.byConnectionName.set(i9, o11.track + m10);
    }
    for (const e61 of b10.enforcedConnectionNames)
      c5.set(e61, b10.byConnectionName.get(e61));
    for (const t10 of x8) {
      const o11 = t10.item.connection.connection.name, i9 = b10.byConnectionName.get(o11) ?? t10.track, r10 = Math.abs(i9 - t10.track), s9 = v10.get(o11) ?? 0, a10 = p9 - n10 * (r10 > 0.000000001 ? s9 + r10 : 0), c9 = t10.points.at(-1);
      if (Math.abs($ae(c9, e60) - p9) > 0.000001)
        return null;
      const l10 = t10.points.at(-2);
      if (l10 && (Math.abs(Yae(l10, e60) - t10.track) > 0.000001 || n10 * (a10 - $ae(l10, e60)) < -0.000001))
        return null;
      const h10 = Xae(a10, t10.track, e60);
      l10 && Bre(l10, h10) < 0.000000001 ? t10.points.pop() : t10.points[t10.points.length - 1] = h10;
    }
    for (const t10 of x8) {
      const o11 = t10.item.connection.connection.name, i9 = b10.byConnectionName.get(o11) ?? t10.track, r10 = Math.abs(i9 - t10.track), s9 = v10.get(o11) ?? 0;
      r10 > 0.000000001 && s9 > 0.000000001 && t10.points.push(Xae($ae(t10.points.at(-1), e60) + n10 * s9, t10.track, e60)), r10 > 0.000000001 && (t10.points.push(Xae($ae(t10.points.at(-1), e60) + n10 * r10, i9, e60)), t10.track = i9);
      const c9 = Xae(p9, t10.track, e60);
      if (Bre(t10.points.at(-1), c9) > 0.000000001) {
        if (n10 * (p9 - $ae(t10.points.at(-1), e60)) < -0.000001)
          return null;
        t10.points.push(c9);
      }
      a9.set(o11, t10);
    }
  }
  const h5 = [...a9.values()].flatMap((e60) => Wae(Vae(e60.points), o10));
  for (const e60 of l5) {
    if (!e60.cornerChannelPrefixes)
      continue;
    const n10 = Gae({ item: e60, srj: t4, acceptedSegments: h5, traceWidth: o10, clearance: i8 });
    if (!n10)
      return null;
    a9.set(e60.connection.connection.name, n10), h5.push(...Wae(Vae(n10.points), o10));
  }
  if (a9.size !== l5.length)
    return null;
  const d9 = (o10 + i8) / 2 + 0.000001;
  for (const [e60, t10] of c5) {
    const n10 = a9.get(e60);
    if (!n10 || Math.abs(n10.track - t10) > d9)
      return null;
  }
  const u9 = l5.map((e60) => {
    const t10 = Vae(a9.get(e60.connection.connection.name).points);
    return { item: e60, points: t10, segments: Wae(t10, o10) };
  });
  return function(e60) {
    const { paths: t10, obstacles: n10, traceWidth: o11, clearance: i9 } = e60, r10 = o11 / 2 + i9, s9 = o11 + i9;
    for (const e61 of t10) {
      if (Math.abs($ae(e61.points.at(-1), e61.item.direction) - Hae(e61.item.bus)) > 0.000001)
        return false;
      for (const t11 of e61.segments)
        for (const o12 of n10)
          if (o12 !== e61.item.connection.sourceObstacle && o12.layers.includes("top") && Hre(t11, o12) < r10 - 0.000000001)
            return false;
    }
    for (let e61 = 0;e61 < t10.length; e61++)
      for (let n11 = e61 + 1;n11 < t10.length; n11++)
        for (const o12 of t10[e61].segments)
          for (const e63 of t10[n11].segments)
            if ($re(o12.start, o12.end, e63.start, e63.end) < s9 - 0.000000001)
              return false;
    return true;
  }({ paths: u9, obstacles: t4.obstacles, traceWidth: o10, clearance: i8 }) ? u9.map(Kae) : null;
}
var tce = 0.000001;
function nce(e54, t4) {
  return Bre(e54, t4) <= tce;
}
function oce(e54) {
  return "layer" in e54 ? [e54.layer] : e54.layers;
}
function ice(e54) {
  return [...e54.segments, ...e54.planeEndpointSegments ?? []];
}
function rce(e54) {
  return [e54.via, e54.planeEndpointVia].filter((e60) => Boolean(e60));
}
function sce(e54, t4) {
  return nce(e54, t4) && oce(e54).join("\x00") === oce(t4).join("\x00") && e54.pointId === t4.pointId && e54.pcb_port_id === t4.pcb_port_id;
}
function ace(e54, t4) {
  const n8 = e54.x >= t4.minX - tce && e54.x <= t4.maxX + tce && e54.y >= t4.minY - tce && e54.y <= t4.maxY + tce, o10 = Math.abs(e54.x - t4.minX) <= tce || Math.abs(e54.x - t4.maxX) <= tce || Math.abs(e54.y - t4.minY) <= tce || Math.abs(e54.y - t4.maxY) <= tce;
  return n8 && o10;
}
function cce(e54, t4) {
  return e54.x >= t4.minX - tce && e54.x <= t4.maxX + tce && e54.y >= t4.minY - tce && e54.y <= t4.maxY + tce;
}
function lce(e54, t4, n8, o10, i8) {
  e54.push({ code: t4, message: n8, ...o10 ? { connectionName: o10.connectionName, busId: o10.busId } : {}, ...i8 ? { otherConnectionName: i8 } : {} });
}
function hce(e54) {
  const { trace: t4, plan: n8, issues: o10 } = e54, i8 = [];
  let r9, s7;
  for (const e60 of t4.route)
    e60.route_type !== "via" ? e60.route_type === "wire" ? s7 ? (nce(e60, s7) && e60.layer === s7.to_layer || lce(o10, "disconnected-trace", `Trace ${t4.pcb_trace_id} does not continue from its via on ${s7.to_layer}`, n8), r9 = e60, s7 = undefined) : (r9 && (r9.layer !== e60.layer ? lce(o10, "disconnected-trace", `Trace ${t4.pcb_trace_id} changes from ${r9.layer} to ${e60.layer} without a via`, n8) : nce(r9, e60) || i8.push({ start: { x: r9.x, y: r9.y }, end: { x: e60.x, y: e60.y }, width: e60.width, layer: e60.layer })), r9 = e60) : lce(o10, "unsupported-route-point", `Trace ${t4.pcb_trace_id} contains unsupported ${e60.route_type} geometry`, n8) : (r9 && nce(r9, e60) && r9.layer === e60.from_layer || lce(o10, "disconnected-trace", `Trace ${t4.pcb_trace_id} reaches a via without a matching ${e60.from_layer} wire endpoint`, n8), s7 = e60);
  return s7 && lce(o10, "disconnected-trace", `Trace ${t4.pcb_trace_id} ends at a via without a wire on ${s7.to_layer}`, n8), i8;
}
function dce(e54) {
  const { plan: t4, preparedBus: n8, inputSrj: o10, outputSrj: i8, sharedBoundary: r9, issues: s7 } = e54, a9 = o10.connections[t4.connectionIndex];
  if (!a9 || a9.name !== t4.connectionName)
    return void lce(s7, "connection-mismatch", `Plan index ${t4.connectionIndex} does not identify connection ${t4.connectionName}`, t4);
  const c5 = n8?.connections.find((e60) => e60.connectionIndex === t4.connectionIndex);
  if (c5 && c5.sourcePointIndex === t4.sourcePointIndex && sce(c5.sourcePoint, t4.sourcePoint) && c5.sourceObstacle.obstacleId === t4.sourceObstacle.obstacleId || lce(s7, "source-mismatch", `Plan ${t4.connectionName} does not start at its prepared component endpoint`, t4), n8?.termination.type !== t4.termination.type && lce(s7, "termination-mismatch", `Plan ${t4.connectionName} does not use its bus termination`, t4), t4.segments.length === 0 || t4.length <= tce)
    lce(s7, "not-broken-out", `Plan ${t4.connectionName} has no non-zero escape geometry`, t4);
  else {
    const e60 = { minX: Math.min(o10.bounds.minX, r9.minX), maxX: Math.max(o10.bounds.maxX, r9.maxX), minY: Math.min(o10.bounds.minY, r9.minY), maxY: Math.max(o10.bounds.maxY, r9.maxY) };
    t4.segments.some((t10) => !cce(t10.start, e60) || !cce(t10.end, e60)) && lce(s7, "outside-routing-bounds", `Plan ${t4.connectionName} leaves the routable SRJ/shared-boundary area`, t4), nce(t4.segments[0].start, t4.sourcePoint) || lce(s7, "disconnected-trace", `Plan ${t4.connectionName} does not start at its source pad`, t4), nce(t4.segments.at(-1).end, t4.exitPoint) || lce(s7, "disconnected-trace", `Plan ${t4.connectionName} does not end at its declared exit`, t4);
    for (let e61 = 1;e61 < t4.segments.length; e61++) {
      const n10 = t4.segments[e61 - 1], o11 = t4.segments[e61];
      nce(n10.end, o11.start) || lce(s7, "disconnected-trace", `Plan ${t4.connectionName} has a gap between route segments`, t4), n10.layer === o11.layer || t4.via && nce(n10.end, t4.via.center) && t4.via.spanLayers.includes(n10.layer) && t4.via.spanLayers.includes(o11.layer) || lce(s7, "disconnected-trace", `Plan ${t4.connectionName} changes layers without a connecting via`, t4);
    }
  }
  const l5 = hce({ trace: t4.trace, plan: t4, issues: s7 });
  if ((l5.length !== t4.segments.length || l5.some((e60, n10) => {
    const o11 = t4.segments[n10];
    return !o11 || e60.layer !== o11.layer || Math.abs(e60.width - o11.width) > tce || !nce(e60.start, o11.start) || !nce(e60.end, o11.end);
  })) && lce(s7, "trace-plan-mismatch", `Trace ${t4.trace.pcb_trace_id} does not encode its declared route segments`, t4), t4.planeEndpointTrace || t4.planeEndpointSegments || t4.planeEndpointVia)
    if (t4.planeEndpointTrace && t4.planeEndpointSegments && t4.planeEndpointVia) {
      const e60 = hce({ trace: t4.planeEndpointTrace, plan: t4, issues: s7 });
      (e60.length !== t4.planeEndpointSegments.length || e60.some((e61, n10) => {
        const o11 = t4.planeEndpointSegments?.[n10];
        return !o11 || e61.layer !== o11.layer || Math.abs(e61.width - o11.width) > tce || !nce(e61.start, o11.start) || !nce(e61.end, o11.end);
      }) || Bre(t4.planeEndpointVia.center, t4.targetPoint) <= tce) && lce(s7, "trace-plan-mismatch", `Trace ${t4.planeEndpointTrace.pcb_trace_id} does not encode a valid offset plane-to-endpoint dogbone`, t4);
    } else
      lce(s7, "trace-plan-mismatch", `Plane endpoint geometry for ${t4.connectionName} is incomplete`, t4);
  const h5 = t4.trace.route.find((e60) => ("x" in e60) && ("y" in e60)), d9 = [...t4.trace.route].reverse().find((e60) => ("x" in e60) && ("y" in e60));
  h5 && d9 && nce(h5, t4.sourcePoint) && nce(d9, t4.exitPoint) || lce(s7, "disconnected-trace", `Trace ${t4.trace.pcb_trace_id} does not span its source and exit`, t4);
  const u9 = i8.connections.find((e60) => e60.name === t4.connectionName);
  if (t4.termination.type === "boundary")
    if (u9) {
      const e60 = u9.pointsToConnect[t4.sourcePointIndex];
      e60 && nce(e60, t4.exitPoint) && "layer" in e60 && e60.layer === t4.targetLayer || lce(s7, "output-exit-mismatch", `Output connection ${t4.connectionName} is not attached to its fanout exit`, t4);
      for (let e61 = 0;e61 < a9.pointsToConnect.length; e61++) {
        if (e61 === t4.sourcePointIndex)
          continue;
        const n10 = a9.pointsToConnect[e61], o11 = u9.pointsToConnect[e61];
        n10 && o11 && sce(n10, o11) || lce(s7, "downstream-endpoint-lost", `Output connection ${t4.connectionName} did not retain downstream endpoint ${e61}`, t4);
      }
    } else
      lce(s7, "output-connection-missing", `Boundary connection ${t4.connectionName} was removed from the output`, t4);
  else
    u9 && lce(s7, "plane-connection-retained", `Plane-terminated connection ${t4.connectionName} remains in the output`, t4);
}
function uce(e54, t4) {
  const n8 = ice(e54), o10 = ice(t4), i8 = rce(e54), r9 = rce(t4);
  for (const e60 of n8) {
    for (const t10 of o10)
      if (e60.layer === t10.layer && $re(e60.start, e60.end, t10.start, t10.end) <= (e60.width + t10.width) / 2 + tce)
        return true;
    for (const t10 of r9)
      if (t10.spanLayers.includes(e60.layer) && Fre(t10.center, e60.start, e60.end) <= t10.diameter / 2 + e60.width / 2 + tce)
        return true;
  }
  for (const e60 of i8) {
    for (const t10 of o10)
      if (e60.spanLayers.includes(t10.layer) && Fre(e60.center, t10.start, t10.end) <= e60.diameter / 2 + t10.width / 2 + tce)
        return true;
    for (const t10 of r9)
      if (e60.spanLayers.some((e61) => t10.spanLayers.includes(e61)) && Bre(e60.center, t10.center) <= (e60.diameter + t10.diameter) / 2 + tce)
        return true;
  }
  return false;
}
function pce(e54) {
  const { inputSrj: t4, outputSrj: n8, plans: o10, preparedBuses: i8, sharedBoundary: r9, clearance: s7 } = e54, a9 = [], c5 = new Map, l5 = new Map(i8.map((e60) => [e60.busId, e60]));
  for (const e60 of o10) {
    const t10 = c5.get(e60.connectionName) ?? [];
    t10.push(e60), c5.set(e60.connectionName, t10);
  }
  for (const e60 of t4.connections) {
    const t10 = c5.get(e60.name) ?? [];
    t10.length === 0 ? lce(a9, "missing-plan", `Connection ${e60.name} has no fanout plan`) : t10.length > 1 && lce(a9, "duplicate-plan", `Connection ${e60.name} has ${t10.length} fanout plans`, t10[0]);
  }
  for (const e60 of o10)
    t4.connections.some((t10) => t10.name === e60.connectionName) ? dce({ plan: e60, preparedBus: l5.get(e60.busId), inputSrj: t4, outputSrj: n8, sharedBoundary: r9, issues: a9 }) : lce(a9, "unknown-plan", `Plan ${e60.connectionName} is not an input connection`, e60);
  const h5 = function(e60) {
    const { plans: t10, inputSrj: n10, sharedBoundary: o11, issues: i9 } = e60, r10 = new Set, s9 = new Map;
    for (const e61 of t10)
      s9.set(e61, []);
    for (let e61 = 0;e61 < t10.length; e61++) {
      const i10 = t10[e61];
      (i10.termination.type === "plane" ? Boolean(i10.via) : i10.segments.some((e63) => ace(e63.start, o11) || ace(e63.end, o11))) && r10.add(i10);
      for (let o12 = e61 + 1;o12 < t10.length; o12++) {
        const e63 = t10[o12];
        Kre(n10, i10.connectionName, e63.connectionName) && uce(i10, e63) && (s9.get(i10).push(e63), s9.get(e63).push(i10));
      }
    }
    const a10 = [...r10];
    for (;a10.length > 0; ) {
      const e61 = a10.shift();
      for (const t11 of s9.get(e61) ?? [])
        r10.has(t11) || (r10.add(t11), a10.push(t11));
    }
    for (const e61 of t10)
      r10.has(e61) || lce(i9, "not-broken-out", e61.termination.type === "boundary" ? `Connection ${e61.connectionName} has no continuous same-net copper path to the shared boundary` : `Plane connection ${e61.connectionName} has no terminating via`, e61);
    return r10;
  }({ plans: o10, inputSrj: t4, sharedBoundary: r9, issues: a9 });
  return function(e60) {
    const { plans: t10, inputSrj: n10, clearance: o11, issues: i9 } = e60;
    for (const e61 of t10) {
      const t11 = ice(e61);
      for (let r10 = 0;r10 < t11.length; r10++) {
        const s9 = t11[r10];
        for (const t12 of n10.obstacles) {
          if (!t12.layers.includes(s9.layer))
            continue;
          if (ese(n10, t12, e61.connectionName))
            continue;
          if (r10 === 0 && t12.obstacleId === e61.sourceObstacle.obstacleId && s9.layer === e61.sourceLayer)
            continue;
          if (hse({ inputSrj: n10, segment: s9, bodyObstacle: t12, connectionName: e61.connectionName }))
            continue;
          const a10 = Hre(s9, t12), c9 = s9.width / 2 + o11;
          a10 < c9 - 0.000000001 && lce(i9, "obstacle-clearance", `Trace ${e61.connectionName} on ${s9.layer} is ${a10.toFixed(4)}mm from different-net obstacle ${t12.obstacleId}; ${c9.toFixed(4)}mm is required`, e61);
        }
      }
      for (const t12 of rce(e61))
        for (const r10 of n10.obstacles) {
          if (!r10.layers.some((e63) => t12.spanLayers.includes(e63)) || ese(n10, r10, e61.connectionName))
            continue;
          const s9 = Xre(t12.center, r10), a10 = t12.diameter / 2 + o11;
          s9 < a10 - 0.000000001 && lce(i9, "via-obstacle-clearance", `Via ${e61.connectionName} is ${s9.toFixed(4)}mm from different-net obstacle ${r10.obstacleId} on its layer span; ${a10.toFixed(4)}mm is required`, e61);
        }
    }
    for (let e61 = 0;e61 < t10.length; e61++) {
      const r10 = t10[e61];
      for (let s9 = e61 + 1;s9 < t10.length; s9++) {
        const e63 = t10[s9];
        if (Kre(n10, r10.connectionName, e63.connectionName))
          continue;
        const a10 = ice(r10), c9 = ice(e63), l10 = rce(r10), h9 = rce(e63);
        for (const t11 of a10) {
          for (const n11 of c9)
            Vre(t11, n11, o11) || lce(i9, "different-net-trace-clearance", `Different-net traces ${r10.connectionName} and ${e63.connectionName} intersect or violate clearance on ${t11.layer}`, r10, e63.connectionName);
          for (const n11 of h9)
            n11.spanLayers.includes(t11.layer) && Fre(n11.center, t11.start, t11.end) < n11.diameter / 2 + t11.width / 2 + o11 - 0.000000001 && lce(i9, "different-net-trace-via-clearance", `Trace ${r10.connectionName} violates via clearance to ${e63.connectionName} on ${t11.layer}`, r10, e63.connectionName);
        }
        for (const t11 of l10) {
          for (const n11 of c9)
            t11.spanLayers.includes(n11.layer) && Fre(t11.center, n11.start, n11.end) < t11.diameter / 2 + n11.width / 2 + o11 - 0.000000001 && lce(i9, "different-net-trace-via-clearance", `Via ${r10.connectionName} violates trace clearance to ${e63.connectionName} on ${n11.layer}`, r10, e63.connectionName);
          for (const n11 of h9)
            t11.spanLayers.some((e64) => n11.spanLayers.includes(e64)) && Bre(t11.center, n11.center) < (t11.diameter + n11.diameter) / 2 + o11 - 0.000000001 && lce(i9, "different-net-via-clearance", `Vias ${r10.connectionName} and ${e63.connectionName} violate clearance on an overlapping layer span`, r10, e63.connectionName);
        }
      }
    }
  }({ plans: o10, inputSrj: t4, clearance: s7, issues: a9 }), { valid: a9.length === 0, checkedConnectionCount: t4.connections.length, brokenOutConnectionCount: new Set([...h5].map((e60) => e60.connectionName)).size, issues: a9 };
}
var mce = ["#ef4444", "#2563eb", "#16a34a", "#9333ea", "#f59e0b", "#0891b2", "#db2777", "#65a30d", "#4f46e5", "#ea580c"];
function gce(e54) {
  if (!Number.isInteger(e54) || e54 < 0)
    throw new Error(`FanoutSolver: copper layer index must be a non-negative integer, received ${e54}`);
  return mce[e54 % mce.length];
}
var fce = new Set(["top", "bottom", "inner1", "inner2", "inner3", "inner4", "inner5", "inner6", "inner7", "inner8"]);
var _ce = { "0603": { padLength: 0.8, padWidth: 0.95 }, 1206: { padLength: 0.6, padWidth: 1.6 }, "1206x4_pair": { padLength: 0.8, padWidth: 0.5 } };
var yce = (e54, t4) => {
  const n8 = e54.indexOf(t4);
  if (n8 < 0)
    throw new Error(`FanoutSolver: cannot visualize unknown copper layer "${t4}"`);
  return n8;
};
var bce = (e54, t4) => `z${[...new Set(t4.map((t10) => yce(e54, t10)))].sort((e60, t10) => e60 - t10).join(",")}`;
var xce = (e54) => {
  const t4 = "layers" in e54 ? e54.layers : undefined;
  return t4 && t4.length > 0 ? t4 : [e54.layer];
};
var vce = (e54, t4) => e54.__zLayers && e54.__zLayers.length > 0 ? [...new Set(e54.__zLayers)].filter((e60) => Number.isInteger(e60) && e60 >= 0 && e60 < t4.length).sort((e60, t10) => e60 - t10) : [...new Set(e54.layers.map((e60) => yce(t4, e60)))].sort((e60, t10) => e60 - t10);
var Ice = (e54, t4, n8) => {
  const o10 = yce(e54, t4), i8 = yce(e54, n8);
  return e54.slice(Math.min(o10, i8), Math.max(o10, i8) + 1);
};
var Sce = (...e54) => e54.find((e60) => typeof e60 == "number" && Number.isFinite(e60));
var Cce = (e54) => {
  const t4 = Sce(e54.min_via_hole_diameter, e54.minViaHoleDiameter), n8 = Sce(e54.min_via_pad_diameter, e54.minViaPadDiameter, e54.minViaDiameter);
  return Math.max(n8 ?? e54.minViaDiameter ?? 0.3, t4 ?? 0);
};
var Pce = (e54, t4) => {
  let n8 = { blue: [0, 0, 255], orange: [255, 165, 0], purple: [128, 0, 128], red: [255, 0, 0] }[e54], o10 = 1;
  const i8 = /^rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)(?:\s*,\s*([\d.]+))?\s*\)$/.exec(e54);
  i8 && (n8 = [Number(i8[1]), Number(i8[2]), Number(i8[3])], o10 = i8[4] === undefined ? 1 : Number(i8[4]));
  const r9 = /^hsl\(\s*([\d.-]+)\s*,\s*([\d.]+)%\s*,\s*([\d.]+)%\s*\)$/.exec(e54);
  if (r9 && (n8 = ((e60, t10, n10) => {
    const o11 = (1 - Math.abs(2 * n10 - 1)) * t10, i9 = (e60 % 360 + 360) % 360 / 60, r10 = o11 * (1 - Math.abs(i9 % 2 - 1)), [s9, a9, c5] = i9 < 1 ? [o11, r10, 0] : i9 < 2 ? [r10, o11, 0] : i9 < 3 ? [0, o11, r10] : i9 < 4 ? [0, r10, o11] : i9 < 5 ? [r10, 0, o11] : [o11, 0, r10], l5 = n10 - o11 / 2;
    return [s9, a9, c5].map((e61) => Math.round(255 * (e61 + l5)));
  })(Number(r9[1]), Number(r9[2]) / 100, Number(r9[3]) / 100)), !n8)
    return e54;
  const s7 = +Math.max(0, 100 * o10 - 100 * t4).toFixed(2) / 100;
  if (s7 >= 1) {
    const e60 = n8.map((e61) => Math.round(e61).toString(16).padStart(2, "0")).join("");
    return e60[0] === e60[1] && e60[2] === e60[3] && e60[4] === e60[5] ? `#${e60[0]}${e60[2]}${e60[4]}` : `#${e60}`;
  }
  return `rgba(${n8.join(",")},${s7})`;
};
var Mce = (e54) => {
  const t4 = new Map, n8 = (e60, n10) => {
    if (!e60)
      return;
    const o10 = t4.get(e60) ?? [];
    o10.includes(n10) || o10.push(n10), t4.set(e60, o10);
  };
  for (const t10 of e54.connections) {
    const e60 = t10.__rootConnectionNames ?? [t10.name];
    for (const o10 of e60) {
      n8(t10.name, o10), n8(o10, o10), n8(t10.__netConnectionName, o10);
      for (const e61 of t10.pointsToConnect)
        n8(e61.pointId, o10), n8(e61.pcb_port_id, o10);
    }
  }
  return (e60) => {
    const n10 = ((e61) => {
      const t10 = new Set;
      return e61.filter((e63) => !t10.has(e63) && (t10.add(e63), true));
    })([...e60.connectedTo.flatMap((e61) => t4.get(e61) ?? []), ...(e60.offBoardConnectsTo ?? []).flatMap((e61) => t4.get(e61) ?? [])]).join(", ");
    return e60.layers.map((e61) => n10 ? `${e61}
${n10}` : e61).join(`
`);
  };
};
function wce(e54) {
  const t4 = Wre(e54.layerCount), n8 = (e54.traces ?? []).some((e60) => e60.route.some((t10, n10) => {
    const o11 = e60.route[n10 + 1];
    return t10.route_type === "wire" && o11?.route_type === "wire" && o11.layer === t10.layer && !fce.has(t10.layer);
  })), o10 = new Set(e54.connections.map(({ name: e60 }) => e60)), i8 = n8 ? [...new Set((e54.traces ?? []).map(({ connection_name: e60 }) => e60).filter((e60) => e60 && !o10.has(e60)))].map((e60) => ({ name: e60, pointsToConnect: [] })) : [], r9 = [...e54.connections, ...i8], s7 = (a9 = r9, Object.fromEntries(a9.map((e60, t10) => [e60.name, `hsl(${340 * t10 / a9.length}, 100%, 50%)`])));
  var a9;
  const c5 = Mce({ ...e54, connections: r9 }), l5 = [], h5 = [], d9 = [], u9 = [];
  for (const e60 of r9)
    for (const n10 of e60.pointsToConnect) {
      const o11 = xce(n10), i9 = e60.__rootConnectionNames ?? [e60.name];
      u9.push({ x: n10.x, y: n10.y, color: s7[e60.name], layer: bce(t4, o11), label: [e60.name, i9.join(", "), o11.join(",")].join(`
`) });
    }
  for (const o11 of e54.traces ?? []) {
    const i9 = o11.route.filter((e60) => e60.route_type === "jumper"), r10 = (e60, t10) => i9.some((n10) => {
      const o12 = 0.01;
      return Math.abs(e60.x - n10.start.x) < o12 && Math.abs(e60.y - n10.start.y) < o12 && Math.abs(t10.x - n10.end.x) < o12 && Math.abs(t10.y - n10.end.y) < o12 || Math.abs(e60.x - n10.end.x) < o12 && Math.abs(e60.y - n10.end.y) < o12 && Math.abs(t10.x - n10.start.x) < o12 && Math.abs(t10.y - n10.start.y) < o12;
    });
    for (const i10 of o11.route)
      if (i10.route_type === "via") {
        const r11 = Ice(t4, i10.from_layer, i10.to_layer);
        h5.push({ center: { x: i10.x, y: i10.y }, radius: (i10.via_diameter ?? Cce(e54)) / 2, fill: n8 ? s7[o11.connection_name] : "blue", stroke: "none", layer: bce(t4, r11) });
      } else
        i10.route_type === "through_obstacle" && l5.push({ points: [i10.start, i10.end], strokeColor: Pce(s7[o11.connection_name] ?? "purple", 0.35), strokeWidth: i10.width, strokeDash: [0.1, 0.1], layer: bce(t4, [i10.from_layer, i10.to_layer]), label: `${o11.connection_name} through_obstacle` });
    for (let e60 = 0;e60 < o11.route.length - 1; e60++) {
      const i10 = o11.route[e60], a10 = o11.route[e60 + 1];
      if (i10.route_type === "jumper") {
        const e61 = s7[o11.connection_name] ?? "rgba(255, 165, 0, 0.8)", n10 = _ce[i10.footprint === "1206x4_pair" ? "1206x4_pair" : "0603"], r11 = Math.abs(i10.end.x - i10.start.x) > Math.abs(i10.end.y - i10.start.y), a11 = r11 ? n10.padLength : n10.padWidth, c9 = r11 ? n10.padWidth : n10.padLength, h9 = bce(t4, [i10.layer]);
        for (const t10 of [i10.start, i10.end])
          d9.push({ center: t10, width: a11, height: c9, fill: Pce(e61, 0.5), stroke: "rgba(0, 0, 0, 0.5)", layer: h9 });
        l5.push({ points: [i10.start, i10.end], strokeColor: "rgba(100, 100, 100, 0.8)", strokeWidth: 0.3 * n10.padWidth, layer: h9 });
      } else if (i10.route_type === "wire" && a10.route_type === "wire" && a10.layer === i10.layer && !r10(i10, a10)) {
        const e61 = yce(t4, i10.layer);
        l5.push({ points: [{ x: i10.x, y: i10.y }, { x: a10.x, y: a10.y }], layer: `z${e61}`, strokeWidth: i10.width, strokeColor: gce(e61), ...n8 ? { label: o11.connection_name } : {} });
      }
    }
  }
  for (const n10 of e54.obstacles) {
    if (n10.isCopperPour)
      continue;
    const e60 = vce(n10, t4);
    if (e60.length === 0)
      throw new Error(`FanoutSolver: cannot visualize obstacle "${n10.obstacleId ?? "unknown"}" without a valid layer`);
    const o11 = e60.length === 1 ? t4[e60[0]] : undefined, i9 = Pce(o11 === "bottom" ? "blue" : "red", 0.5 ** e60.length), r10 = n10.shape, s9 = { center: n10.center, fill: i9, layer: `z${e60.join(",")}`, label: c5(n10) };
    r10 === "circle" ? h5.push({ ...s9, radius: Math.min(n10.width, n10.height) / 2 }) : d9.push({ ...s9, width: n10.width, height: n10.height, ccwRotationDegrees: n10.ccwRotationDegrees });
  }
  for (const n10 of e54.jumpers ?? [])
    for (const e60 of n10.pads)
      d9.push({ center: e60.center, width: e60.width, height: e60.height, ccwRotationDegrees: e60.ccwRotationDegrees, fill: "rgba(255, 165, 0, 0.3)", stroke: "rgba(255, 165, 0, 0.8)", layer: bce(t4, e60.layers) });
  return { rects: d9, circles: h5, lines: l5, points: u9 };
}
function Nce(e54, t4) {
  if (!Number.isFinite(t4) || t4 <= 0)
    throw new Error(`FanoutSolver: ${e54} must be a positive number, received ${t4}`);
  return t4;
}
function Rce(e54, t4, n8) {
  const o10 = new Map(t4.map((e60) => [e60.busId, e60.connections.length])), i8 = new Map;
  for (const [t10, r9] of Object.entries(e54))
    i8.set(r9, (i8.get(r9) ?? 0) + (n8 ? o10.get(t10) ?? 1 : 1));
  return [...i8.values()].reduce((e60, t10) => e60 + t10 * t10, 0);
}
function Tce(e54) {
  return e54.balanceLayerLoadByConnectionCount ? 0.25 : 0.01;
}
function Ece(e54) {
  return e54.reduce((e60, t4) => e60 + Number(Boolean(t4.via)) + Number(Boolean(t4.planeEndpointVia)), 0);
}
function Ace(e54) {
  const t4 = e54.connections.reduce((t10, n8) => t10 + (e54.direction === "left" || e54.direction === "right" ? n8.sourcePoint.x : n8.sourcePoint.y), 0) / e54.connections.length;
  switch (e54.direction) {
    case "right":
      return e54.sharedBoundary.maxX - t4;
    case "left":
      return t4 - e54.sharedBoundary.minX;
    case "up":
      return e54.sharedBoundary.maxY - t4;
    case "down":
      return t4 - e54.sharedBoundary.minY;
  }
}
function Oce(e54) {
  const t4 = e54.direction === "left" || e54.direction === "right";
  return e54.connections.some((e60) => {
    const n8 = e60.exitTargetPoint ?? e60.targetPoint, o10 = t4 ? e60.sourcePoint.y : e60.sourcePoint.x, i8 = t4 ? n8.y : n8.x;
    return Math.abs(o10 - i8) > 0.000001;
  });
}
function kce(e54) {
  const t4 = e54.direction === "left" || e54.direction === "right", n8 = t4 ? e54.xCoordinates : e54.yCoordinates, o10 = e54.connections.reduce((e60, n10) => e60 + (t4 ? n10.sourcePoint.x : n10.sourcePoint.y), 0) / e54.connections.length, i8 = e54.direction === "right" || e54.direction === "up" ? Math.max(...n8) : Math.min(...n8);
  return Math.abs(o10 - i8) < 0.000001;
}
function Dce(e54) {
  const t4 = e54.direction === "left" || e54.direction === "right", n8 = t4 ? e54.xCoordinates : e54.yCoordinates, o10 = e54.connections.reduce((e60, n10) => e60 + (t4 ? n10.sourcePoint.x : n10.sourcePoint.y), 0) / e54.connections.length, i8 = e54.direction === "right" || e54.direction === "up" ? Math.max(...n8) : Math.min(...n8), r9 = t4 ? e54.pitchX : e54.pitchY;
  return Math.round(Math.abs(o10 - i8) / r9);
}
function Lce(e54) {
  const { buses: t4, escapeLayers: n8, escapeLayersByBusId: o10 } = e54, i8 = {}, r9 = new Map;
  let s7 = 0;
  for (const e60 of t4) {
    const t10 = r9.get(e60.componentId) ?? new Set;
    t10.add(e60.direction), r9.set(e60.componentId, t10);
  }
  for (const e60 of t4) {
    const t10 = e60.connections[0]?.sourceLayer;
    if (!t10)
      throw new Error(`FanoutSolver: bus "${e60.busId}" has no connections`);
    if (e60.termination.type === "plane") {
      i8[e60.busId] = e60.termination.layer;
      continue;
    }
    const a9 = o10[e60.busId] ?? n8, c5 = a9.filter((e61) => e61 !== t10);
    if (a9.includes(t10) && (Oce(e60) || kce(e60)))
      i8[e60.busId] = t10;
    else if (c5.length > 0) {
      const t11 = r9.get(e60.componentId);
      if (t11.has("left") && t11.has("right") || t11.has("up") && t11.has("down")) {
        const t12 = Dce(e60);
        i8[e60.busId] = c5[Math.max(t12 - 1, 0) % c5.length];
      } else
        i8[e60.busId] = c5[s7 % c5.length], s7++;
    } else
      i8[e60.busId] = t10;
  }
  return i8;
}
function zce(e54) {
  const { bus: t4, srj: n8, config: o10, staticClearanceCache: i8 } = e54, r9 = o10.escapeLayers.filter((e60) => Sae({ srj: n8, bus: t4, targetLayer: e60, acceptedPlans: [], layerNames: o10.layerNames, traceWidth: o10.traceWidth, viaDiameter: o10.viaDiameter, viaHoleDiameter: o10.viaHoleDiameter, clearance: o10.clearance, compactBusTracks: o10.compactBusTracks, allowSameNetMerges: o10.allowSameNetMerges, staticClearanceCache: i8 }) !== null);
  return r9.length > 0 ? r9 : o10.escapeLayers;
}
var Bce = class extends BaseSolver {
  constructor(e54, t4 = {}) {
    super(), this.inputSrj = e54, this.options = t4, this.config = function(e60, t10) {
      const n10 = Nce("traceWidth", t10.traceWidth ?? e60.nominalTraceWidth ?? e60.minTraceWidth), o11 = Nce("viaDiameter", t10.viaDiameter ?? e60.minViaPadDiameter ?? e60.min_via_pad_diameter ?? e60.minViaDiameter ?? Math.max(2 * n10, 0.3)), i9 = Nce("viaHoleDiameter", t10.viaHoleDiameter ?? e60.minViaHoleDiameter ?? e60.min_via_hole_diameter ?? 0.5 * o11);
      if (i9 >= o11)
        throw new Error(`FanoutSolver: viaHoleDiameter ${i9} must be smaller than viaDiameter ${o11}`);
      const r10 = Nce("clearance", t10.clearance ?? e60.minViaEdgeToPadEdgeClearance ?? e60.minTraceToPadEdgeClearance ?? e60.defaultObstacleMargin ?? e60.minTraceWidth), s7 = Wre(e60.layerCount), a9 = t10.escapeLayers ?? s7;
      for (const t11 of a9)
        if (!s7.includes(t11))
          throw new Error(`FanoutSolver: escape layer "${t11}" is not available in a ${e60.layerCount}-layer SimpleRouteJson`);
      if (new Set(a9).size !== a9.length)
        throw new Error("FanoutSolver: escapeLayers contains duplicates");
      const c5 = t10.borderDistribution ?? "preserve";
      if (c5 !== "preserve" && c5 !== "even")
        throw new Error(`FanoutSolver: borderDistribution must be "preserve" or "even", received "${c5}"`);
      return { traceWidth: n10, viaDiameter: o11, viaHoleDiameter: i9, clearance: r10, compactBusTracks: t10.compactBusTracks ?? false, allowSameNetMerges: t10.allowSameNetMerges ?? false, singleLayerPushAndShove: t10.singleLayerPushAndShove ?? false, singleLayerAdaptiveExits: t10.singleLayerAdaptiveExits ?? false, borderDistribution: c5, layerNames: s7, escapeLayers: a9, maxLayerCombinations: t10.maxLayerCombinations === undefined ? 256 : Nce("maxLayerCombinations", t10.maxLayerCombinations), balanceLayerLoadByConnectionCount: t10.balanceLayerLoadByConnectionCount ?? false };
    }(e54, t4), this.preparedBuses = Qse(e54, t4);
    for (const e60 of this.preparedBuses) {
      if (e60.termination.type !== "plane")
        continue;
      const t10 = e60.termination.layer;
      if (!this.config.layerNames.includes(t10))
        throw new Error(`FanoutSolver: plane-terminated bus "${e60.busId}" targets unavailable layer "${t10}"`);
      if (e60.connections.some((e61) => e61.sourceLayer === t10))
        throw new Error(`FanoutSolver: plane-terminated bus "${e60.busId}" must target a layer below its source pad`);
    }
    const n8 = this.preparedBuses.filter((e60) => e60.termination.type === "boundary").map((e60) => e60.busId), o10 = Object.fromEntries(this.preparedBuses.flatMap((e60) => e60.termination.type === "plane" ? [[e60.busId, e60.termination.layer]] : [])), i8 = Object.fromEntries(this.preparedBuses.flatMap((t10) => t10.termination.type === "plane" ? [] : [[t10.busId, zce({ bus: t10, srj: e54, config: this.config, staticClearanceCache: this.routeStaticClearanceCache })]]));
    this.escapeLayersByBusId = i8;
    const r9 = function(e60) {
      const { busIds: t10, layers: n10, layersByBusId: o11, maxAssignments: i9 } = e60;
      if (n10.length === 0)
        throw new Error("FanoutSolver: no escape layers are available");
      if (!Number.isInteger(i9) || i9 < 1)
        throw new Error(`FanoutSolver: maxLayerCombinations must be positive, received ${i9}`);
      const r10 = t10.map((e61) => o11?.[e61] ?? n10), s7 = r10.findIndex((e61) => e61.length === 0);
      if (s7 >= 0)
        throw new Error(`FanoutSolver: no escape layers are available for bus "${t10[s7]}"`);
      const a9 = r10.reduce((e61, t11) => e61 * t11.length, 1), c5 = Math.min(i9, Number.isFinite(a9) ? a9 : i9), l5 = [], h5 = new Set;
      function d9(e61) {
        const n11 = {};
        for (let o13 = 0;o13 < t10.length; o13++)
          n11[t10[o13]] = r10[o13][e61[o13]];
        const o12 = JSON.stringify(n11);
        h5.has(o12) || (h5.add(o12), l5.push(n11));
      }
      if (a9 <= i9) {
        for (let e61 = 0;e61 < c5; e61++) {
          const n11 = [];
          let o12 = e61;
          for (let e63 = 0;e63 < t10.length; e63++) {
            const t11 = r10[e63].length, i10 = o12 % t11;
            o12 = Math.floor(o12 / t11), n11.push((i10 + e63) % t11);
          }
          d9(n11);
        }
        return l5;
      }
      function u9(e61) {
        let t11 = 0 | e61;
        return t11 = Math.imul(t11 ^ t11 >>> 16, 569420461), t11 = Math.imul(t11 ^ t11 >>> 15, 1935289751), (t11 ^ t11 >>> 15) >>> 0;
      }
      const p9 = t10.map((e61, t11) => t11 % r10[t11].length);
      d9(p9);
      const m9 = Math.max(...r10.map((e61) => e61.length));
      for (let e61 = 1;e61 < m9 && l5.length < c5; e61++)
        d9(p9.map((t11, n11) => (t11 + e61) % r10[n11].length));
      for (let e61 = 0;e61 < t10.length && l5.length < c5; e61++)
        for (let t11 = 1;t11 < r10[e61].length && l5.length < c5; t11++) {
          const n11 = [...p9];
          n11[e61] = (p9[e61] + t11) % r10[e61].length, d9(n11);
        }
      for (let e61 = 1;l5.length < c5 && e61 < 20 * c5; e61++)
        d9(t10.map((t11, n11) => u9(2654435761 * e61 + 2246822507 * n11) % r10[n11].length));
      return l5;
    }({ busIds: n8, layers: this.config.escapeLayers, layersByBusId: i8, maxAssignments: this.config.maxLayerCombinations }).map((e60) => ({ ...e60, ...o10 }));
    this.layerAssignments = function(e60) {
      const { preferredAssignment: t10, generatedAssignments: n10, maxAssignments: o11 } = e60, i9 = JSON.stringify(t10);
      return [t10, ...n10.filter((e61) => JSON.stringify(e61) !== i9)].slice(0, o11);
    }({ preferredAssignment: Lce({ buses: this.preparedBuses, escapeLayers: this.config.escapeLayers, escapeLayersByBusId: i8 }), generatedAssignments: r9, maxAssignments: this.config.maxLayerCombinations }), this.MAX_ITERATIONS = this.config.maxLayerCombinations + 2;
  }
  preparedBuses;
  attempts = [];
  layerAssignments;
  config;
  escapeLayersByBusId;
  evaluatedAssignmentKeys = new Set;
  queuedAssignmentKeys = new Set;
  assignmentRepairDepthByKey = new Map;
  pendingRepairAssignments = [];
  routeStaticClearanceCache = new Map;
  routingPrefixCache = new Map;
  groupedBeamEvaluated = false;
  nextAssignmentIndex = 0;
  nextGeneratedAssignmentIndex = 0;
  bestAttempt = null;
  endpointCompletion = null;
  getSolverName() {
    return "FanoutSolver";
  }
  completeBestAttemptEndpoints() {
    this.options.completeOriginalEndpoints && !this.endpointCompletion && this.bestAttempt && (this.endpointCompletion = Rse({ inputSrj: this.inputSrj, fanoutSrj: this.bestAttempt.outputSrj, plans: this.bestAttempt.plans, traceWidth: this.config.traceWidth, viaDiameter: this.config.viaDiameter, viaHoleDiameter: this.config.viaHoleDiameter, clearance: this.config.clearance, effort: this.options.endpointCompletionEffort, routeDownstreamConnections: this.options.routeDownstreamConnections }));
  }
  getValidationBoundary() {
    if (this.options.sharedBoundary)
      return this.options.sharedBoundary;
    const e54 = this.preparedBuses[0]?.sharedBoundary;
    return e54 ? this.preparedBuses.slice(1).reduce((e60, t4) => ({ minX: Math.min(e60.minX, t4.sharedBoundary.minX), maxX: Math.max(e60.maxX, t4.sharedBoundary.maxX), minY: Math.min(e60.minY, t4.sharedBoundary.minY), maxY: Math.max(e60.maxY, t4.sharedBoundary.maxY) }), { ...e54 }) : this.inputSrj.bounds;
  }
  validateCompletePlans(e54, t4) {
    return pce({ inputSrj: this.inputSrj, outputSrj: t4, plans: e54, preparedBuses: this.preparedBuses, sharedBoundary: this.getValidationBoundary(), clearance: this.config.clearance });
  }
  evaluateAssignmentWithStrategy(e54, t4, n8) {
    let o10 = [], i8 = [], r9 = new Map;
    const s7 = this.config.escapeLayers.length === 1;
    if (s7 && this.config.singleLayerPushAndShove) {
      const e60 = { srj: this.inputSrj, buses: this.preparedBuses, traceWidth: this.config.traceWidth, clearance: this.config.clearance, borderDistribution: this.config.borderDistribution }, t10 = ece(e60) ?? (this.config.singleLayerAdaptiveExits ? Bae({ ...e60, availableBoundaryRegions: Yse(this.options.availableCornersAndSides) }) : null);
      t10 ? o10.push(...t10) : i8.push(...this.preparedBuses.map((e61) => e61.busId));
    }
    const a9 = [...this.preparedBuses].sort((e60, o11) => Number(o11.termination.type === "plane") - Number(e60.termination.type === "plane") || (n8 === "group-by-layer" ? (t4[e60.busId] ?? "").localeCompare(t4[o11.busId] ?? "") : 0) || o11.componentObstacles.length - e60.componentObstacles.length || (s7 ? Ace(o11) - Ace(e60) : o11.connections.length - e60.connections.length || (n8 === "deep-first" ? Ace(o11) - Ace(e60) : Ace(e60) - Ace(o11))));
    let c5, l5 = `${n8}|`;
    for (const n10 of s7 && this.config.singleLayerPushAndShove ? [] : a9) {
      const s9 = t4[n10.busId];
      if (!s9)
        throw new Error(`FanoutSolver: assignment ${e54} has no layer for bus "${n10.busId}"`);
      l5 += `${n10.busId.length}:${n10.busId};${s9.length}:${s9};`;
      const a10 = this.routingPrefixCache.get(l5);
      if (a10) {
        o10 = [...a10.plans], i8 = [...a10.failedBusIds], r9 = new Map(a10.blockingBusCounts);
        continue;
      }
      const c9 = new Map, h9 = Sae({ srj: this.inputSrj, bus: n10, targetLayer: s9, acceptedPlans: o10, layerNames: this.config.layerNames, traceWidth: this.config.traceWidth, viaDiameter: this.config.viaDiameter, viaHoleDiameter: this.config.viaHoleDiameter, clearance: this.config.clearance, compactBusTracks: this.config.compactBusTracks, allowSameNetMerges: this.config.allowSameNetMerges, staticClearanceCache: this.routeStaticClearanceCache, blockingBusCounts: c9 });
      if (h9)
        o10.push(...h9);
      else {
        i8.push(n10.busId);
        for (const [e60, t10] of c9)
          r9.set(e60, (r9.get(e60) ?? 0) + t10);
      }
      this.routingPrefixCache.set(l5, { plans: [...o10], failedBusIds: [...i8], blockingBusCounts: new Map(r9) });
    }
    let h5 = kre({ inputSrj: this.inputSrj, plans: o10, layerNames: this.config.layerNames });
    const d9 = o10.length === this.inputSrj.connections.length ? this.validateCompletePlans(o10, h5) : null;
    d9 && !d9.valid && (c5 = d9.issues, o10 = [], i8 = this.preparedBuses.map((e60) => e60.busId), r9.clear(), h5 = kre({ inputSrj: this.inputSrj, plans: o10, layerNames: this.config.layerNames }));
    const u9 = this.preparedBuses.length - i8.length, p9 = o10.reduce((e60, t10) => e60 + t10.length, 0), m9 = 1e6 * (this.inputSrj.connections.length - o10.length) + 1e5 * i8.length + p9 + 0.1 * Ece(o10) + Rce(t4, this.preparedBuses, this.config.balanceLayerLoadByConnectionCount) * Tce(this.config);
    return { summary: { assignmentIndex: e54, busLayerAssignments: t4, routedBusCount: u9, routedConnectionCount: o10.length, failedBusIds: i8, score: m9, ...c5 ? { validationIssues: c5 } : {} }, plans: o10, blockingBusIds: [...r9.entries()].toSorted(([, e60], [, t10]) => t10 - e60).map(([e60]) => e60), outputSrj: h5 };
  }
  evaluateAssignment(e54, t4) {
    let n8 = this.evaluateAssignmentWithStrategy(e54, t4, "default");
    if (n8.summary.routedConnectionCount === this.inputSrj.connections.length)
      return n8;
    for (const o10 of ["group-by-layer", "deep-first"]) {
      const i8 = this.evaluateAssignmentWithStrategy(e54, t4, o10);
      if (i8.summary.score < n8.summary.score && (n8 = i8), n8.summary.routedConnectionCount === this.inputSrj.connections.length)
        return n8;
    }
    return n8;
  }
  evaluateGroupedBeam(e54, t4 = false) {
    if (this.config.escapeLayers.length < 2)
      return null;
    if (this.preparedBuses.length > 56)
      return null;
    const n8 = this.inputSrj.connections.length;
    if (n8 > 64)
      return null;
    if (new Set(this.preparedBuses.map((e60) => e60.componentId)).size !== 1)
      return null;
    const o10 = [...this.preparedBuses].sort((e60, n10) => {
      const o11 = e60.termination.type === "plane" ? 1 : this.escapeLayersByBusId[e60.busId]?.length ?? this.config.escapeLayers.length, i9 = n10.termination.type === "plane" ? 1 : this.escapeLayersByBusId[n10.busId]?.length ?? this.config.escapeLayers.length;
      return Number(n10.termination.type === "plane") - Number(e60.termination.type === "plane") || (t4 ? e60.direction.localeCompare(n10.direction) : 0) || o11 - i9 || n10.componentObstacles.length - e60.componentObstacles.length || n10.connections.length - e60.connections.length || Dce(n10) - Dce(e60) || e60.busId.localeCompare(n10.busId);
    }), i8 = n8 <= 24, r9 = this.preparedBuses.some((e60) => e60.connections.length > 1), s7 = i8 ? 48 : n8 <= 32 ? 24 : 12, a9 = i8 && !r9 ? 4 : 1;
    let c5 = [{ assignment: {}, plans: [] }];
    const l5 = (e60) => e60.plans.reduce((e61, t10) => e61 + t10.length, 0) + 0.1 * Ece(e60.plans) + 1e4 * this.preparedBuses.reduce((t10, n10) => {
      if (n10.termination.type !== "boundary" || !Oce(n10))
        return t10;
      const o11 = n10.connections[0]?.sourceLayer;
      return e60.assignment[n10.busId] === o11 ? t10 : t10 + n10.connections.length;
    }, 0) + Rce(e60.assignment, this.preparedBuses, this.config.balanceLayerLoadByConnectionCount) * Tce(this.config);
    for (const e60 of o10) {
      const t10 = [];
      for (const n11 of c5) {
        const o11 = e60.termination.type === "plane" ? [e60.termination.layer] : this.escapeLayersByBusId[e60.busId] ?? this.config.escapeLayers, i9 = new Map;
        for (const [e61, t11] of Object.entries(n11.assignment)) {
          const n12 = this.preparedBuses.find((t12) => t12.busId === e61);
          i9.set(t11, (i9.get(t11) ?? 0) + (this.config.balanceLayerLoadByConnectionCount ? n12?.connections.length ?? 1 : 1));
        }
        const r10 = e60.connections[0]?.sourceLayer, s9 = Oce(e60), c9 = o11.toSorted((e61, t11) => (i9.get(e61) ?? 0) - (i9.get(t11) ?? 0) || (s9 ? Number(t11 === r10) - Number(e61 === r10) : Number(e61 === r10) - Number(t11 === r10)) || e61.localeCompare(t11));
        for (const o12 of c9) {
          const i10 = Iae({ srj: this.inputSrj, bus: e60, targetLayer: o12, acceptedPlans: n11.plans, layerNames: this.config.layerNames, traceWidth: this.config.traceWidth, viaDiameter: this.config.viaDiameter, viaHoleDiameter: this.config.viaHoleDiameter, clearance: this.config.clearance, compactBusTracks: this.config.compactBusTracks, allowSameNetMerges: this.config.allowSameNetMerges, staticClearanceCache: this.routeStaticClearanceCache }, a9);
          for (const r11 of i10)
            t10.push({ assignment: { ...n11.assignment, [e60.busId]: o12 }, plans: [...n11.plans, ...r11] });
        }
      }
      if (t10.length === 0)
        return null;
      t10.sort((e61, t11) => {
        const n11 = l5(e61) - l5(t11);
        return Math.abs(n11) > 0.000000001 ? n11 : JSON.stringify(e61.assignment).localeCompare(JSON.stringify(t11.assignment));
      });
      const n10 = new Map;
      c5 = [];
      for (const e61 of t10) {
        const t11 = JSON.stringify(e61.assignment), o11 = n10.get(t11) ?? 0;
        if (!(o11 >= 2) && (n10.set(t11, o11 + 1), c5.push(e61), c5.length >= s7))
          break;
      }
    }
    const h5 = c5[0];
    if (!h5)
      return null;
    const d9 = kre({ inputSrj: this.inputSrj, plans: h5.plans, layerNames: this.config.layerNames });
    if (h5.plans.length === this.inputSrj.connections.length && !this.validateCompletePlans(h5.plans, d9).valid)
      return null;
    const u9 = h5.plans.length === this.inputSrj.connections.length ? h5.plans.reduce((e60, t10) => e60 + t10.length, 0) + 0.1 * Ece(h5.plans) + Rce(h5.assignment, this.preparedBuses, this.config.balanceLayerLoadByConnectionCount) * Tce(this.config) : Number.POSITIVE_INFINITY;
    if (!Number.isFinite(u9))
      return null;
    return { summary: { assignmentIndex: e54, busLayerAssignments: h5.assignment, routedBusCount: this.preparedBuses.length, routedConnectionCount: h5.plans.length, failedBusIds: [], score: u9 }, plans: h5.plans, blockingBusIds: [], outputSrj: d9 };
  }
  prioritizeFailedBusRepairs(e54, t4, n8) {
    const o10 = JSON.stringify(e54), i8 = this.assignmentRepairDepthByKey.get(o10) ?? 0;
    if (i8 >= 2)
      return;
    const r9 = [], s7 = new Set, a9 = (e60) => {
      const t10 = JSON.stringify(e60);
      s7.has(t10) || this.evaluatedAssignmentKeys.has(t10) || this.queuedAssignmentKeys.has(t10) || (s7.add(t10), this.queuedAssignmentKeys.add(t10), this.assignmentRepairDepthByKey.set(t10, i8 + 1), r9.push(e60));
    }, c5 = [];
    for (let e60 = 0;e60 < Math.max(t4.length, n8.length); e60++) {
      const o11 = t4[e60], i9 = n8[e60];
      o11 && !c5.includes(o11) && c5.push(o11), i9 && !c5.includes(i9) && c5.push(i9);
    }
    for (const o11 of t4) {
      const t10 = e54[o11], i9 = this.escapeLayersByBusId[o11];
      if (t10 && i9) {
        for (const s9 of n8.slice(0, 4)) {
          const n10 = e54[s9], c9 = this.escapeLayersByBusId[s9];
          if (n10 && c9 && i9.includes(n10) && c9.includes(t10) && (a9({ ...e54, [o11]: n10, [s9]: t10 }), r9.length >= 8))
            break;
        }
        if (r9.length >= 8)
          break;
      }
    }
    for (const t10 of c5) {
      const n10 = e54[t10], o11 = this.escapeLayersByBusId[t10];
      if (!n10 || !o11)
        continue;
      const i9 = o11.indexOf(n10);
      for (let s9 = 1;s9 < o11.length; s9++) {
        const c9 = o11[(Math.max(i9, 0) + s9) % o11.length];
        if (c9 !== n10 && (a9({ ...e54, [t10]: c9 }), r9.length >= 8))
          break;
      }
      if (r9.length >= 8)
        break;
    }
    this.pendingRepairAssignments.push(...r9);
  }
  hasCompleteBestAttempt() {
    return this.bestAttempt?.summary.routedConnectionCount === this.inputSrj.connections.length;
  }
  shouldEvaluateGroupedBeam() {
    if (this.groupedBeamEvaluated || this.nextAssignmentIndex === 0)
      return false;
    return this.hasCompleteBestAttempt() || this.pendingRepairAssignments.length === 0 || this.nextAssignmentIndex >= this.config.maxLayerCombinations;
  }
  _step() {
    if (this.shouldEvaluateGroupedBeam()) {
      this.groupedBeamEvaluated = true;
      let e60 = this.evaluateGroupedBeam(-1);
      if (e60 || (e60 = this.evaluateGroupedBeam(-1, true)), e60) {
        this.attempts.push(e60.summary), (!this.bestAttempt || e60.summary.score < this.bestAttempt.summary.score) && (this.bestAttempt = e60);
        const t10 = this.bestAttempt.summary;
        return this.stats = { assignment: t10.assignmentIndex < 0 ? 0 : t10.assignmentIndex + 1, assignmentCount: this.config.maxLayerCombinations, routedBuses: `${t10.routedBusCount}/${this.preparedBuses.length}`, routedConnections: `${t10.routedConnectionCount}/${this.inputSrj.connections.length}`, failedBuses: "none", bestScore: t10.score }, this.completeBestAttemptEndpoints(), void (this.solved = true);
      }
      if (this.hasCompleteBestAttempt())
        return this.completeBestAttemptEndpoints(), void (this.solved = true);
    }
    let e54;
    for (;!e54 && this.nextAssignmentIndex < this.config.maxLayerCombinations; ) {
      const t10 = this.nextAssignmentIndex % 3 == 0;
      let n8, o10 = false;
      if (!this.groupedBeamEvaluated && this.nextAssignmentIndex > 0 ? (n8 = this.pendingRepairAssignments.pop(), o10 = n8 !== undefined) : t10 ? n8 = this.layerAssignments[this.nextGeneratedAssignmentIndex++] : (n8 = this.pendingRepairAssignments.pop(), o10 = n8 !== undefined), n8 || !this.groupedBeamEvaluated && this.nextAssignmentIndex !== 0 || (n8 = t10 ? this.pendingRepairAssignments.pop() : this.layerAssignments[this.nextGeneratedAssignmentIndex++], o10 = t10 && n8 !== undefined), !n8)
        break;
      const i8 = JSON.stringify(n8);
      o10 && this.queuedAssignmentKeys.delete(i8), this.evaluatedAssignmentKeys.has(i8) || (e54 = n8);
    }
    if (!e54 && !this.groupedBeamEvaluated)
      return;
    if (!e54)
      return void (this.hasCompleteBestAttempt() ? (this.completeBestAttemptEndpoints(), this.solved = true) : (this.failed = true, this.error = this.bestAttempt ? `FanoutSolver: best layer assignment routed ${this.bestAttempt.summary.routedConnectionCount}/${this.inputSrj.connections.length} connections` : "FanoutSolver: no layer assignment could be evaluated"));
    const t4 = this.evaluateAssignment(this.nextAssignmentIndex, e54);
    this.nextAssignmentIndex++, this.evaluatedAssignmentKeys.add(JSON.stringify(e54)), (!this.bestAttempt || t4.summary.routedConnectionCount >= this.bestAttempt.summary.routedConnectionCount) && this.prioritizeFailedBusRepairs(e54, t4.summary.failedBusIds, t4.blockingBusIds), this.attempts.push(t4.summary), (!this.bestAttempt || t4.summary.score < this.bestAttempt.summary.score) && (this.bestAttempt = t4), this.stats = { assignment: t4.summary.assignmentIndex + 1, assignmentCount: this.config.maxLayerCombinations, routedBuses: `${t4.summary.routedBusCount}/${this.preparedBuses.length}`, routedConnections: `${t4.summary.routedConnectionCount}/${this.inputSrj.connections.length}`, failedBuses: t4.summary.failedBusIds.join(", ") || "none", bestScore: this.bestAttempt.summary.score }, this.groupedBeamEvaluated && t4.summary.routedConnectionCount === this.inputSrj.connections.length && (this.completeBestAttemptEndpoints(), this.solved = true);
  }
  computeProgress() {
    return this.solved || this.failed ? 1 : this.nextAssignmentIndex / this.config.maxLayerCombinations;
  }
  getConstructorParams() {
    return [this.inputSrj, this.options];
  }
  getOutput() {
    if (!this.solved || !this.bestAttempt)
      throw new Error("FanoutSolver: getOutput() called before a complete fanout was solved");
    const e54 = this.validateCompletePlans(this.bestAttempt.plans, this.bestAttempt.outputSrj);
    if (!e54.valid)
      throw new Error(`FanoutSolver: completed output failed validation: ${e54.issues[0]?.message ?? "unknown validation error"}`);
    const t4 = this.endpointCompletion?.simpleRouteJson ?? this.bestAttempt.outputSrj, n8 = new Map((t4.traces ?? []).map((e60) => [e60.pcb_trace_id, e60]));
    return { simpleRouteJson: this.endpointCompletion?.simpleRouteJson ?? this.bestAttempt.outputSrj, fanoutTraces: this.bestAttempt.plans.flatMap((e60) => [n8.get(e60.trace.pcb_trace_id) ?? e60.trace, ...e60.planeEndpointTrace ? [n8.get(e60.planeEndpointTrace.pcb_trace_id) ?? e60.planeEndpointTrace] : []]), completionTraces: this.endpointCompletion?.traces ?? [], ...this.endpointCompletion ? { endpointCompletion: this.endpointCompletion.report } : {}, planeTerminations: this.bestAttempt.plans.flatMap((e60) => e60.termination.type === "plane" && e60.via ? [{ busId: e60.busId, connectionName: e60.connectionName, layer: e60.termination.layer, via: e60.via }] : []), busLayerAssignments: this.bestAttempt.summary.busLayerAssignments, busDirections: Object.fromEntries(this.preparedBuses.map((e60) => [e60.busId, e60.direction])), attempts: [...this.attempts], validation: e54 };
  }
  getOutputSimpleRouteJson() {
    return this.getOutput().simpleRouteJson;
  }
  visualize() {
    return wce(this.endpointCompletion?.simpleRouteJson ?? this.bestAttempt?.outputSrj ?? this.inputSrj);
  }
};
function Yce(e54) {
  const { minX: t4, maxX: n8 } = e54.bounds, o10 = (t4 + n8) / 2;
  if (!Number.isFinite(o10))
    throw new Error(`Detected component ${e54.componentId} has bad bounds`);
  return o10;
}
function Xce(e54) {
  const { minY: t4, maxY: n8 } = e54.bounds, o10 = (t4 + n8) / 2;
  if (!Number.isFinite(o10))
    throw new Error(`Detected component ${e54.componentId} has bad bounds`);
  return o10;
}
function Hce(e54, t4) {
  const n8 = (function(e60, t10) {
    const [n10, o10] = Yce(e60) < Yce(t10) ? [e60, t10] : [t10, e60];
    return o10.bounds.minX - n10.bounds.maxX;
  }(e54, t4) - 2) / 2;
  return Math.min(4.5, n8);
}
function Vce(e54, t4) {
  const n8 = t4.filter((e60) => e60.componentKind === "bga").map((t10) => function(e60, t11) {
    const n10 = e60.obstacles.filter((e61) => e61.componentId === t11.componentId);
    if (n10.length === 0)
      throw new Error(`Detected component ${t11.componentId} has no physical obstacles`);
    return { ...t11, bounds: { __type: "rect", minX: Math.min(...n10.map((e61) => e61.center.x - e61.width / 2)), maxX: Math.max(...n10.map((e61) => e61.center.x + e61.width / 2)), minY: Math.min(...n10.map((e61) => e61.center.y - e61.height / 2)), maxY: Math.max(...n10.map((e61) => e61.center.y + e61.height / 2)) } };
  }(e54, t10)).toSorted((e60, t10) => Yce(e60) - Yce(t10));
  if (n8.length !== 2)
    throw new Error(`Pipeline 10 requires exactly two detected BGAs; found ${n8.map((e60) => e60.componentId).join(", ") || "none"}`);
  const [o10, i8] = n8;
  if (o10.componentId === i8.componentId)
    throw new Error("Pipeline 10 requires two distinct BGA component IDs");
  if (Hce(o10, i8) < 2)
    throw new Error("Pipeline 10 cannot provide 2mm fanout margins while retaining a 2mm routing corridor");
  return { first: o10, second: i8 };
}
function Wce(e54, t4) {
  const { minX: n8, maxX: o10, minY: i8, maxY: r9 } = e54.bounds;
  return { minX: n8 - t4, maxX: o10 + t4, minY: i8 - t4, maxY: r9 + t4 };
}
function Gce(e54) {
  const { minX: t4, maxX: n8, minY: o10, maxY: i8 } = e54.bounds;
  return { minX: t4, maxX: n8, minY: o10, maxY: i8 };
}
function Uce({ inputSrj: e54, source: t4, target: n8 }) {
  const o10 = Hce(t4, n8), i8 = Wce(t4, o10), r9 = Yce(n8) > Yce(t4) ? "right" : "left", s7 = r9 === "right" ? "left" : "right";
  return e54.connections.map((e60, n10) => {
    const a9 = e60.pointsToConnect.filter((e61) => e61.x >= t4.bounds.minX && e61.x <= t4.bounds.maxX && e61.y >= t4.bounds.minY && e61.y <= t4.bounds.maxY);
    if (a9.length !== 1)
      throw new Error(`Connection ${e60.name} must touch ${t4.componentId} exactly once before fanout`);
    const c5 = a9[0], l5 = r9 === "right" ? i8.maxX - c5.x : c5.x - i8.minX, h5 = [{ direction: "up", distance: i8.maxY - c5.y }, { direction: "down", distance: c5.y - i8.minY }, { direction: s7, distance: s7 === "right" ? i8.maxX - c5.x : c5.x - i8.minX }].toSorted((e61, t10) => e61.distance - t10.distance)[0].direction, d9 = l5 <= o10 + 1.2 ? r9 : h5;
    let u9 = d9 === "up" ? "top" : d9 === "down" ? "bottom" : d9;
    return d9 === "up" ? u9 = c5.x < Yce(t4) ? "top-left" : "top-right" : d9 === "down" ? u9 = c5.x < Yce(t4) ? "bottom-left" : "bottom-right" : c5.y > Xce(t4) + 0.000001 ? u9 = d9 === "right" ? "top-right" : "top-left" : c5.y < Xce(t4) - 0.000001 && (u9 = d9 === "right" ? "bottom-right" : "bottom-left"), { busId: `pipeline10_fanout:${t4.componentId}:${n10}`, connectionNames: [e60.name], sourceComponentId: t4.componentId, direction: d9, preferredExit: u9, termination: { type: "boundary" } };
  });
}
function Zce({ inputSrj: e54, source: t4, target: n8 }) {
  const o10 = Hce(t4, n8);
  return { buses: Uce({ inputSrj: e54, source: t4, target: n8 }), sourceComponentId: t4.componentId, availableCornersAndSides: ["top_left", "top_middle", "top_right", "right_top", "right_middle", "right_bottom", "bottom_right", "bottom_middle", "bottom_left", "left_bottom", "left_middle", "left_top"], componentBounds: { [t4.componentId]: Gce(t4) }, sharedBoundary: Wce(t4, o10), maxLayerCombinations: 256, balanceLayerLoadByConnectionCount: true, compactBusTracks: true, borderDistribution: "even" };
}
var qce = class extends BaseSolver {
  constructor(e54) {
    super(), this.inputProblem = e54, this.fanoutSolver = new Bce(e54.inputSrj, e54.options), this.activeSubSolver = this.fanoutSolver, this.MAX_ITERATIONS = this.fanoutSolver.MAX_ITERATIONS + 1;
  }
  fanoutSolver;
  _step() {
    if (this.fanoutSolver.step(), this.progress = this.fanoutSolver.progress, this.stats = { ...this.fanoutSolver.stats }, this.fanoutSolver.failed)
      return this.error = this.fanoutSolver.error ?? "Fanout solver failed", this.failed = true, void (this.activeSubSolver = null);
    this.fanoutSolver.solved && (this.solved = true, this.activeSubSolver = null);
  }
  getConstructorParams() {
    return [this.inputProblem];
  }
  getOutput() {
    return this.fanoutSolver.getOutput();
  }
  getOutputSimpleRouteJson() {
    return this.fanoutSolver.getOutputSimpleRouteJson();
  }
  visualize() {
    return this.fanoutSolver.visualize();
  }
  preview() {
    return this.fanoutSolver.preview();
  }
};
var Jce = class extends BaseSolver {
  constructor(e54) {
    super(), this.inputProblem = e54, this.autoroutingPipelineSolver = new ire(e54.inputSrj, e54.options), this.activeSubSolver = this.autoroutingPipelineSolver, this.MAX_ITERATIONS = this.autoroutingPipelineSolver.MAX_ITERATIONS + 1;
  }
  autoroutingPipelineSolver;
  _step() {
    if (this.autoroutingPipelineSolver.step(), this.progress = this.autoroutingPipelineSolver.progress, this.stats = { ...this.autoroutingPipelineSolver.stats }, this.autoroutingPipelineSolver.failed)
      return this.error = this.autoroutingPipelineSolver.error ?? "Autorouting pipeline failed", this.failed = true, void (this.activeSubSolver = null);
    this.autoroutingPipelineSolver.solved && (this.solved = true, this.activeSubSolver = null);
  }
  getConstructorParams() {
    return [this.inputProblem];
  }
  getOutput() {
    return this.autoroutingPipelineSolver.getOutputSimpleRouteJson();
  }
  visualize() {
    return this.autoroutingPipelineSolver.visualize();
  }
  preview() {
    return this.autoroutingPipelineSolver.preview();
  }
};
var Qce = class extends BasePipelineSolver {
  componentDetectionSolver;
  firstBgaFanoutSolver;
  secondBgaFanoutSolver;
  autoroutingPipelineSolver;
  get currentPipelineStepIndex() {
    return this.currentPipelineStageIndex;
  }
  get startTimeOfPhase() {
    return this.startTimeOfStage;
  }
  get timeSpentOnPhase() {
    return this.timeSpentOnStage;
  }
  pipelineDef = [definePipelineStep("componentDetectionSolver", r7, (e54) => [{ inputSrj: e54.inputProblem.inputSrj }]), definePipelineStep("firstBgaFanoutSolver", qce, (e54) => {
    const t4 = Vce(e54.inputProblem.inputSrj, e54.componentDetectionSolver.getOutput());
    return [{ inputSrj: e54.inputProblem.inputSrj, options: Zce({ inputSrj: e54.inputProblem.inputSrj, source: t4.first, target: t4.second }) }];
  }), definePipelineStep("secondBgaFanoutSolver", qce, (e54) => {
    const t4 = Vce(e54.inputProblem.inputSrj, e54.componentDetectionSolver.getOutput()), n8 = e54.firstBgaFanoutSolver.getOutputSimpleRouteJson();
    return [{ inputSrj: n8, options: Zce({ inputSrj: n8, source: t4.second, target: t4.first }) }];
  }), definePipelineStep("autoroutingPipelineSolver", Jce, (e54) => [{ inputSrj: e54.secondBgaFanoutSolver.getOutputSimpleRouteJson(), options: e54.inputProblem.options }])];
  constructor(e54, t4 = {}) {
    super({ inputSrj: e54, options: t4 }), this.MAX_ITERATIONS = 1e8 * (t4.effort ?? 1) + 1024;
  }
  getSolverName() {
    return "AutoroutingPipelineSolver10_BgaFanout";
  }
  getConstructorParams() {
    return [this.inputProblem.inputSrj, this.inputProblem.options];
  }
  getOutput() {
    if (!this.autoroutingPipelineSolver?.solved)
      throw new Error("Pipeline 10 has not solved yet");
    return this.autoroutingPipelineSolver.getOutput();
  }
  getOutputSimpleRouteJson() {
    return this.getOutput();
  }
  getOutputSimplifiedPcbTraces() {
    return this.getOutput().traces ?? [];
  }
  get srjWithPointPairs() {
    return this.autoroutingPipelineSolver?.autoroutingPipelineSolver.srjWithPointPairs;
  }
  initialVisualize() {
    return Wo(this.inputProblem.inputSrj);
  }
  finalVisualize() {
    return Wo(this.getOutput());
  }
};
var nle = class extends BaseSolver {
  constructor(e54) {
    super(), this.inputProblem = e54, this.simplifiedRouteByTraceId = new Map(e54.simplifiedHdRoutes.map((e60) => [e60.connectionName, e60])), this.MAX_ITERATIONS = e54.preparedInput.preparedTraces.length + 1;
  }
  simplifiedRouteByTraceId;
  outputTraces = [];
  nextTraceIndex = 0;
  getSolverName() {
    return "ApplyTraceSimplificationSolver";
  }
  _step() {
    const e54 = this.inputProblem.preparedInput.preparedTraces, t4 = e54[this.nextTraceIndex];
    t4 ? (this.outputTraces.push(this.applyTrace(t4)), this.nextTraceIndex++, this.progress = this.nextTraceIndex / Math.max(1, e54.length)) : this.finishApplication();
  }
  applyTrace(e54) {
    if (!e54.mutableHdRoute)
      return structuredClone(e54.originalTrace);
    const t4 = this.simplifiedRouteByTraceId.get(e54.originalTrace.pcb_trace_id);
    if (!t4 || e54.uniformTraceWidth === undefined)
      throw new Error(`Simplification removed trace "${e54.originalTrace.pcb_trace_id}"`);
    const n8 = Ro(t4, this.inputProblem.preparedInput.srj.layerCount, { defaultViaHoleDiameter: e54.viaHoleDiameter, obstacles: this.inputProblem.preparedInput.srj.obstacles, connMap: this.inputProblem.preparedInput.connMap }), o10 = n8.filter((e60) => e60.route_type === "jumper"), i8 = ((e60, t10) => e60.map((e61) => e61.route_type === "wire" || e61.route_type === "through_obstacle" ? { ...e61, width: t10 } : e61))([...structuredClone(e54.leadingTerminalVias), ...n8.filter((e60) => e60.route_type !== "jumper"), ...structuredClone(e54.trailingTerminalVias), ...o10], e54.uniformTraceWidth);
    return ((e60, t10) => {
      const n10 = e60.filter((e61) => e61.route_type === "wire");
      t10.startPcbPortId && n10[0] && (n10[0].start_pcb_port_id = t10.startPcbPortId), t10.endPcbPortId && n10.at(-1) && (n10.at(-1).end_pcb_port_id = t10.endPcbPortId);
    })(i8, t4), { ...structuredClone(e54.originalTrace), route: i8 };
  }
  finishApplication() {
    const e54 = this.inputProblem.preparedInput.preparedTraces;
    this.stats = { inputTraceCount: e54.length, outputTraceCount: this.outputTraces.length, inputRoutePointCount: e54.reduce((e60, t4) => e60 + t4.originalTrace.route.length, 0), outputRoutePointCount: this.outputTraces.reduce((e60, t4) => e60 + t4.route.length, 0) }, this.progress = 1, this.solved = true;
  }
  getConstructorParams() {
    return [this.inputProblem];
  }
  getOutput() {
    if (!this.solved)
      throw new Error("Cannot get applied traces before conversion completes");
    return { ...structuredClone(this.inputProblem.preparedInput.originalSrj), traces: structuredClone(this.outputTraces) };
  }
};
var ile = (e54, t4) => {
  const n8 = e54.at(-1);
  if (n8 && (o10 = n8, i8 = t4, Math.abs(o10.x - i8.x) <= 0.000000001 && Math.abs(o10.y - i8.y) <= 0.000000001 && o10.z === i8.z))
    return t4.traceThickness !== undefined && (n8.traceThickness = t4.traceThickness), void (t4.pcb_port_id !== undefined && (n8.pcb_port_id = t4.pcb_port_id));
  var o10, i8;
  e54.push(t4);
};
var rle = (e54, t4, n8) => {
  for (let o10 = t4 + 1;o10 < e54.length; o10++) {
    const t10 = e54[o10];
    if (t10.route_type === "wire")
      return mo(t10.layer, n8);
    if (t10.route_type === "through_obstacle")
      return mo(t10.from_layer, n8);
  }
};
var sle = ({ fromZ: e54, toZ: t4, previousZ: n8, nextZ: o10 }) => n8 === e54 ? [e54, t4] : n8 === t4 ? [t4, e54] : o10 === t4 ? [e54, t4] : o10 === e54 ? [t4, e54] : [e54, t4];
var ale = (e54, t4) => {
  for (const t10 of e54)
    if (t10.route_type === "via" && t10.via_diameter !== undefined)
      return t10.via_diameter;
  return t4;
};
var cle = (e54, t4) => {
  const n8 = t4 === "start" ? e54 : [...e54].reverse();
  for (const e60 of n8) {
    if (e60.route_type !== "wire")
      continue;
    const n10 = t4 === "start" ? e60.start_pcb_port_id : e60.end_pcb_port_id;
    if (n10)
      return n10;
  }
};
var lle = (e54) => ({ route_type: "jumper", start: { ...e54.start }, end: { ...e54.end }, footprint: e54.footprint });
var hle = (e54, t4) => {
  for (const t10 of e54.route)
    if (t10.route_type === "via" && t10.via_hole_diameter !== undefined)
      return t10.via_hole_diameter;
  return t4;
};
var dle = class extends BaseSolver {
  preparedInput;
  seenTraceIds = new Set;
  nextTraceIndex = 0;
  constructor(e54) {
    super();
    const t4 = structuredClone(e54.inputSrj), n8 = V1(t4), o10 = ei(n8);
    this.preparedInput = { originalSrj: t4, srj: n8, connMap: o10, colorMap: Eo(n8, o10), immutableHdRoutes: [], mutableHdRoutes: [], netByConnectionName: new Map, options: { ...e54.options }, preparedTraces: [] }, this.MAX_ITERATIONS = (n8.traces?.length ?? 0) + 1;
  }
  getSolverName() {
    return "PrepareTraceSimplificationSolver";
  }
  _step() {
    const e54 = this.preparedInput.srj.traces ?? [], t4 = e54[this.nextTraceIndex];
    if (!t4)
      return this.stats = { inputTraceCount: e54.length, mutableTraceCount: this.preparedInput.mutableHdRoutes.length, immutableTraceCount: e54.length - this.preparedInput.mutableHdRoutes.length }, this.progress = 1, void (this.solved = true);
    this.prepareTrace(t4, this.nextTraceIndex), this.nextTraceIndex++, this.progress = this.nextTraceIndex / Math.max(1, e54.length);
  }
  prepareTrace(e54, t4) {
    if (this.seenTraceIds.has(e54.pcb_trace_id))
      throw new Error(`Duplicate pcb_trace_id "${e54.pcb_trace_id}"`);
    this.seenTraceIds.add(e54.pcb_trace_id);
    const n8 = Yo(this.preparedInput.srj), o10 = ((e60) => {
      const t10 = e60.route.flatMap((e61) => e61.route_type === "wire" || e61.route_type === "through_obstacle" ? [e61.width] : []), n10 = t10[0];
      if (n10 !== undefined && !t10.some((e61) => Math.abs(e61 - n10) > 0.000000001))
        return n10;
    })(e54), { traceToSimplify: i8, leadingTerminalVias: r9, trailingTerminalVias: s7 } = ((e60) => {
      let t10 = 0;
      for (;e60.route[t10]?.route_type === "via"; )
        t10++;
      let n10 = e60.route.length;
      for (;e60.route[n10 - 1]?.route_type === "jumper"; )
        n10--;
      let o11 = n10;
      for (;o11 > t10 && e60.route[o11 - 1]?.route_type === "via"; )
        o11--;
      return { traceToSimplify: { ...e60, route: [...e60.route.slice(t10, o11), ...e60.route.slice(n10)] }, leadingTerminalVias: e60.route.slice(0, t10), trailingTerminalVias: e60.route.slice(o11, n10) };
    })(e54), a9 = this.preparedInput.connMap.getNetConnectedToId(e54.connection_name) ?? e54.connection_name, c5 = o10 === undefined ? undefined : ((e60, t10) => {
      const n10 = [], o11 = [], i9 = [], r10 = ((e61, t11) => {
        for (const t12 of e61)
          if (t12.route_type === "wire" || t12.route_type === "through_obstacle")
            return t12.width;
        return t11;
      })(e60.route, t10.defaultTraceThickness);
      for (let s9 = 0;s9 < e60.route.length; s9++) {
        const a10 = e60.route[s9];
        if (a10.route_type === "jumper") {
          i9.push(lle(a10));
          continue;
        }
        if (a10.route_type === "wire") {
          ile(n10, { x: a10.x, y: a10.y, z: mo(a10.layer, t10.layerCount), traceThickness: a10.width, pcb_port_id: a10.start_pcb_port_id ?? a10.end_pcb_port_id });
          continue;
        }
        const c9 = mo(a10.from_layer, t10.layerCount), l10 = mo(a10.to_layer, t10.layerCount), [h9, d9] = sle({ fromZ: c9, toZ: l10, previousZ: n10.at(-1)?.z, nextZ: rle(e60.route, s9, t10.layerCount) });
        if (a10.route_type === "via") {
          ile(n10, { x: a10.x, y: a10.y, z: h9, traceThickness: r10 }), ile(n10, { x: a10.x, y: a10.y, z: d9, traceThickness: r10 }), o11.push({ x: a10.x, y: a10.y });
          continue;
        }
        const u9 = h9 === c9, p9 = u9 ? a10.start : a10.end, m9 = u9 ? a10.end : a10.start;
        ile(n10, { ...p9, z: h9, traceThickness: a10.width, toNextSegmentType: "through_obstacle", ...a10.circuitJsonMetadata ? { toNextSegmentCircuitJsonMetadata: a10.circuitJsonMetadata } : {} }), ile(n10, { ...m9, z: d9, traceThickness: a10.width });
      }
      return { connectionName: e60.pcb_trace_id, rootConnectionName: t10.rootConnectionName, startPcbPortId: cle(e60.route, "start"), endPcbPortId: cle(e60.route, "end"), traceThickness: r10, viaDiameter: ale(e60.route, t10.defaultViaDiameter), route: n10, vias: o11, ...i9.length > 0 ? { jumpers: i9 } : {} };
    })(i8, { layerCount: this.preparedInput.srj.layerCount, defaultTraceThickness: o10, defaultViaDiameter: n8.padDiameter, rootConnectionName: a9 }), l5 = c5 && c5.route.length >= 2 ? c5 : undefined;
    if (this.preparedInput.preparedTraces.push({ originalTrace: e54, mutableHdRoute: l5, leadingTerminalVias: r9, trailingTerminalVias: s7, uniformTraceWidth: o10, viaHoleDiameter: hle(e54, n8.holeDiameter) }), !l5)
      return void this.preparedInput.immutableHdRoutes.push(...Vne(e54, t4, this.preparedInput.srj.layerCount, n8.padDiameter, this.preparedInput.connMap));
    this.preparedInput.mutableHdRoutes.push(l5), this.preparedInput.netByConnectionName.set(l5.connectionName, a9), this.preparedInput.colorMap[l5.connectionName] = this.preparedInput.colorMap[a9] ?? this.preparedInput.colorMap[e54.connection_name] ?? "#2563eb";
    const h5 = { ...e54, route: [...r9, ...s7] };
    this.preparedInput.immutableHdRoutes.push(...Vne(h5, t4, this.preparedInput.srj.layerCount, n8.padDiameter, this.preparedInput.connMap));
  }
  getOutput() {
    if (!this.solved)
      throw new Error("Cannot get prepared traces before preparation completes");
    return this.preparedInput;
  }
};
var ple = class extends BaseSolver {
  constructor(e54) {
    super(), this.inputProblem = e54;
    const t4 = e54.preparedInput, n8 = Yo(t4.srj);
    this.traceSimplificationSolver = new WF({ hdRoutes: t4.mutableHdRoutes, otherHdRoutes: t4.immutableHdRoutes, obstacles: t4.srj.obstacles, connMap: t4.connMap, colorMap: t4.colorMap, outline: t4.srj.outline, defaultViaDiameter: n8.padDiameter, layerCount: t4.srj.layerCount, minTraceToPadEdgeClearance: t4.srj.minTraceToPadEdgeClearance, minBoardEdgeClearance: t4.srj.minBoardEdgeClearance, netByConnectionName: t4.netByConnectionName, enableCrossingViaReduction: t4.options.enableCrossingViaReduction ?? true, preserveRouteEndpoints: true, useTraceWidthAwareClearance: true, enableVertexShortcuts: t4.options.enableVertexShortcuts ?? true }), this.traceSimplificationSolver.MAX_SIMPLIFICATION_PIPELINE_LOOPS = t4.options.iterations ?? 2, this.activeSubSolver = this.traceSimplificationSolver, this.MAX_ITERATIONS = this.traceSimplificationSolver.MAX_ITERATIONS + 1;
  }
  traceSimplificationSolver;
  getSolverName() {
    return "TraceSimplificationStageSolver";
  }
  _step() {
    if (this.traceSimplificationSolver.step(), this.progress = this.traceSimplificationSolver.progress, this.stats = { ...this.traceSimplificationSolver.stats }, this.traceSimplificationSolver.failed)
      return this.error = this.traceSimplificationSolver.error ?? "Trace simplification failed", this.failed = true, void (this.activeSubSolver = null);
    this.traceSimplificationSolver.solved && (this.progress = 1, this.solved = true, this.activeSubSolver = null);
  }
  getConstructorParams() {
    return [this.inputProblem];
  }
  getOutput() {
    if (!this.solved)
      throw new Error("Cannot get simplified routes before cleanup completes");
    return structuredClone(this.traceSimplificationSolver.simplifiedHdRoutes);
  }
  visualize() {
    return this.traceSimplificationSolver.visualize();
  }
  preview() {
    return this.traceSimplificationSolver.preview();
  }
};
var gle = class extends BaseSolver {
  constructor(e54) {
    super(), this.inputProblem = e54;
    const t4 = e54.preparedInput;
    this.drcEngine = new mb(t4.srj, { connMap: t4.connMap, traceClearance: t4.srj.minTraceToPadEdgeClearance ?? 0.1, viaClearance: 0.1, viaToPadClearance: vte(t4.originalSrj) }), this.MAX_ITERATIONS = 3;
  }
  drcEngine;
  phase = "baseline";
  baselineErrorCounts = {};
  outputErrorCounts = {};
  getSolverName() {
    return "ValidateTraceSimplificationSolver";
  }
  _step() {
    return this.phase === "baseline" ? (this.baselineErrorCounts = this.evaluateErrorCounts(this.inputProblem.preparedInput.originalSrj), this.phase = "output", void (this.progress = 1 / 3)) : this.phase === "output" ? (this.outputErrorCounts = this.evaluateErrorCounts(this.inputProblem.outputSrj), this.phase = "compare", void (this.progress = 2 / 3)) : (this.assertNoNewDrcErrors(), this.stats = { baselineErrorCounts: this.baselineErrorCounts, outputErrorCounts: this.outputErrorCounts }, this.progress = 1, void (this.solved = true));
  }
  evaluateErrorCounts(e54) {
    return ((e60) => {
      const t4 = {};
      for (const n8 of e60.errors)
        t4[n8.type] = (t4[n8.type] ?? 0) + 1;
      return t4;
    })(this.drcEngine.evaluate(e54.traces ?? []));
  }
  assertNoNewDrcErrors() {
    const e54 = [...new Set([...Object.keys(this.baselineErrorCounts), ...Object.keys(this.outputErrorCounts)])].filter((e60) => (this.outputErrorCounts[e60] ?? 0) > (this.baselineErrorCounts[e60] ?? 0));
    if (e54.length === 0)
      return;
    const t4 = e54.map((e60) => `${e60}: ${this.baselineErrorCounts[e60] ?? 0} -> ${this.outputErrorCounts[e60] ?? 0}`).join(", ");
    throw new Error(`Pipeline 11 simplification introduced DRC errors (${t4})`);
  }
  getConstructorParams() {
    return [this.inputProblem];
  }
  getOutput() {
    if (!this.solved)
      throw new Error("Cannot get Pipeline 11 output before DRC validation");
    return structuredClone(this.inputProblem.outputSrj);
  }
};
var fle = class extends BasePipelineSolver {
  prepareTraceSimplificationSolver;
  traceSimplificationStageSolver;
  applyTraceSimplificationSolver;
  validateTraceSimplificationSolver;
  pipelineDef = [definePipelineStep("prepareTraceSimplificationSolver", dle, (e54) => [{ inputSrj: e54.inputProblem.inputSrj, options: e54.inputProblem.options }]), definePipelineStep("traceSimplificationStageSolver", ple, (e54) => [{ preparedInput: e54.prepareTraceSimplificationSolver.getOutput() }]), definePipelineStep("applyTraceSimplificationSolver", nle, (e54) => [{ preparedInput: e54.prepareTraceSimplificationSolver.getOutput(), simplifiedHdRoutes: e54.traceSimplificationStageSolver.getOutput() }]), definePipelineStep("validateTraceSimplificationSolver", gle, (e54) => [{ preparedInput: e54.prepareTraceSimplificationSolver.getOutput(), outputSrj: e54.applyTraceSimplificationSolver.getOutput() }])];
  constructor(e54, t4 = {}) {
    if (t4.iterations !== undefined && (!Number.isInteger(t4.iterations) || t4.iterations < 1))
      throw new Error("Simplification iterations must be a positive integer");
    super({ inputSrj: e54, options: { ...t4 } }), this.MAX_ITERATIONS = 1e8;
  }
  getSolverName() {
    return "AutoroutingPipelineSolver11_Simplification";
  }
  getConstructorParams() {
    return [this.inputProblem.inputSrj, this.inputProblem.options];
  }
  getOutput() {
    if (!this.validateTraceSimplificationSolver?.solved)
      throw new Error("Pipeline 11 simplification has not solved yet");
    return this.validateTraceSimplificationSolver.getOutput();
  }
  getOutputSimpleRouteJson() {
    return this.getOutput();
  }
  getOutputSimplifiedPcbTraces() {
    return structuredClone(this.getOutput().traces ?? []);
  }
  initialVisualize() {
    return Wo(this.inputProblem.inputSrj);
  }
  finalVisualize() {
    return Wo(this.getOutput());
  }
};
var _le = class extends lj {
  constructor(e54, t4 = {}) {
    super(e54, t4), this.srj = e54, this.opts = t4;
  }
  MAX_SIZE_FOR_SINGLE_LAYER_NODES = 2;
  isObstacleAssignable(e54) {
    return Boolean(e54?.netIsAssignable);
  }
  getOverlappingAssignableObstacles(e54) {
    return this.getXYZOverlappingObstacles(e54).filter((e60) => this.isObstacleAssignable(e60));
  }
  shouldNodeBeXYSubdivided(e54) {
    return !(e54._depth >= this.MAX_DEPTH) && (!!e54._containsTarget || (!(!e54._containsObstacle || e54._completelyInsideObstacle) || e54.availableZ.length === 1 && (e54.width > this.MAX_SIZE_FOR_SINGLE_LAYER_NODES || e54.height > this.MAX_SIZE_FOR_SINGLE_LAYER_NODES)));
  }
  shouldFilterNodeForObstacle(e54) {
    if (!e54._containsObstacle)
      return false;
    return !(this.getOverlappingAssignableObstacles(e54).length > 0) && (e54.availableZ.length !== 1 || this.shouldFilterSingleLayerNodeForObstacle(e54));
  }
  insertAssignableObstaclesAsNodes() {
    const e54 = this.srj.obstacles.filter((e60) => this.isObstacleAssignable(e60)), t4 = new Map;
    for (const n10 of e54) {
      const e60 = [];
      for (const t10 of this.finishedNodes) {
        this.getXYZOverlappingObstacles(t10).some((e61) => e61 === n10) && e60.push(t10);
      }
      t4.set(n10, e60);
    }
    const n8 = new Set;
    for (const e60 of t4.values())
      for (const t10 of e60)
        n8.add(t10);
    this.finishedNodes = this.finishedNodes.filter((e60) => !n8.has(e60));
    for (const n10 of e54) {
      const e60 = t4.get(n10) || [], o10 = n10.layers && n10.layers.length > 0 ? Array.from(new Set(n10.layers.map((e61) => mo(e61, this.srj.layerCount)))).sort((e61, t10) => e61 - t10) : Array.from({ length: this.srj.layerCount }, (e61, t10) => this.srj.layerCount - t10 - 1);
      let i8 = n10.center.x - n10.width / 2, r9 = n10.center.x + n10.width / 2, s7 = n10.center.y - n10.height / 2, a9 = n10.center.y + n10.height / 2;
      for (const t10 of e60) {
        const e61 = t10.center.x - t10.width / 2, n11 = t10.center.x + t10.width / 2, o11 = t10.center.y - t10.height / 2, c9 = t10.center.y + t10.height / 2;
        i8 = Math.min(i8, e61), r9 = Math.max(r9, n11), s7 = Math.min(s7, o11), a9 = Math.max(a9, c9);
      }
      const c5 = r9 - i8, l5 = a9 - s7, h5 = (i8 + r9) / 2, d9 = (s7 + a9) / 2;
      let u9 = false;
      for (const e61 of this.srj.connections) {
        for (const t10 of e61.pointsToConnect)
          if (t10.x >= i8 && t10.x <= r9 && t10.y >= s7 && t10.y <= a9) {
            u9 = true;
            break;
          }
        if (u9)
          break;
      }
      const p9 = { capacityMeshNodeId: `assignable_via_${n10.center.x}_${n10.center.y}`, center: { x: h5, y: d9 }, width: c5, height: l5, layer: o10.length === 1 ? `z${o10[0]}` : `z${o10.join(",")}`, availableZ: o10, _depth: 0, _containsTarget: u9, _containsObstacle: false, _completelyInsideObstacle: false };
      p9._assignedViaObstacle = n10, this.finishedNodes.push(p9);
    }
  }
  _step() {
    const e54 = this.unfinishedNodes.pop();
    if (!e54)
      return this.insertAssignableObstaclesAsNodes(), void (this.solved = true);
    const t4 = this.getChildNodes(e54), n8 = [], o10 = [];
    for (const e60 of t4) {
      const t10 = this.shouldNodeBeXYSubdivided(e60), i8 = e60.availableZ.length > 1 && !t10;
      if (t10)
        o10.push(e60);
      else {
        if (i8) {
          const t11 = this.getZSubdivisionChildNodes(e60);
          for (const e61 of t11)
            !e61._containsTarget && this.shouldFilterNodeForObstacle(e61) || (this.shouldNodeBeXYSubdivided(e61) ? o10.push(e61) : (e61._containsObstacle = false, n8.push(e61)));
          continue;
        }
        this.shouldFilterNodeForObstacle(e60) && !e60._containsTarget || n8.push(e60);
      }
    }
    this.unfinishedNodes.push(...o10), this.finishedNodes.push(...n8);
  }
};
var yle = 0.005;
var ble = class extends ni {
  getSolverName() {
    return "SingleLayerNodeMergerSolver_OnlyMergeTargets";
  }
  nodeMap;
  currentBatchNodeIds;
  absorbedNodeIds;
  nextBatchNodeIds;
  batchHadModifications;
  hasComputedAdjacentNodeIds = false;
  newNodes;
  constructor(e54) {
    super(), this.nodeMap = new Map, this.MAX_ITERATIONS = 1e5;
    for (const t10 of e54)
      this.nodeMap.set(t10.capacityMeshNodeId, t10);
    this.newNodes = [], this.absorbedNodeIds = new Set;
    const t4 = [];
    for (const n8 of e54)
      n8._assignedViaObstacle ? (this.newNodes.push(n8), this.absorbedNodeIds.add(n8.capacityMeshNodeId)) : n8._containsTarget ? n8.availableZ.length > 1 ? (this.newNodes.push(n8), this.absorbedNodeIds.add(n8.capacityMeshNodeId)) : t4.push([n8, n8.width * n8.height]) : (this.newNodes.push(n8), this.absorbedNodeIds.add(n8.capacityMeshNodeId));
    t4.sort((e60, t10) => e60[1] - t10[1]);
    for (const [e60, n8] of t4) {
      const t10 = { ...e60, center: { ...e60.center } };
      this.nodeMap.set(e60.capacityMeshNodeId, t10);
    }
    this.currentBatchNodeIds = t4.map(([e60]) => e60.capacityMeshNodeId), this.nextBatchNodeIds = [], this.batchHadModifications = false;
  }
  computeAdjacentNodeIdsForFirstBatch(e54) {
    const t4 = Math.max(...e54.map((e60) => Math.max(...e60.availableZ))), n8 = [];
    for (let o10 = 0;o10 <= t4; o10++)
      n8.push(new di(e54.filter((e60) => e60.availableZ[0] === o10)));
    for (const t10 of e54) {
      const e60 = [], o10 = n8[t10.availableZ[0]].getNodesInArea(t10.center.x, t10.center.y, 4 * t10.width, 4 * t10.height);
      for (const n10 of o10)
        n10._containsTarget && n10._targetConnectionName !== t10._targetConnectionName || t10._containsTarget && (!n10._containsTarget || n10._targetConnectionName !== t10._targetConnectionName) || n10.capacityMeshNodeId !== t10.capacityMeshNodeId && ri(t10, n10) && e60.push(n10);
      t10._adjacentNodeIds = e60.map((e61) => e61.capacityMeshNodeId);
    }
  }
  getAdjacentSameLayerUnprocessedNodes(e54) {
    const t4 = [], n8 = Array.from(new Set((e54._adjacentNodeIds ?? []).map((e60) => this.nodeMap.get(e60)))).filter((t10) => t10 && t10.capacityMeshNodeId !== e54.capacityMeshNodeId);
    n8.sort((e60, t10) => e60.width * e60.height - t10.width * t10.height);
    for (const e60 of n8)
      this.absorbedNodeIds.has(e60.capacityMeshNodeId) || t4.push(e60);
    return t4;
  }
  _step() {
    this.hasComputedAdjacentNodeIds || (this.computeAdjacentNodeIdsForFirstBatch(this.currentBatchNodeIds.map((e60) => this.nodeMap.get(e60))), this.hasComputedAdjacentNodeIds = true);
    let e54 = this.currentBatchNodeIds.pop();
    for (;e54 && this.absorbedNodeIds.has(e54); )
      e54 = this.currentBatchNodeIds.pop();
    if (!e54)
      return this.batchHadModifications ? (this.currentBatchNodeIds = this.nextBatchNodeIds.sort((e60, t10) => {
        const n10 = this.nodeMap.get(e60), o11 = this.nodeMap.get(t10);
        return n10.width * n10.height - o11.width * o11.height;
      }), this.nextBatchNodeIds = [], void (this.batchHadModifications = false)) : (this.solved = true, void this.newNodes.push(...this.nextBatchNodeIds.map((e60) => this.nodeMap.get(e60))));
    const t4 = this.nodeMap.get(e54);
    let n8 = false;
    const o10 = this.getAdjacentSameLayerUnprocessedNodes(t4);
    if (o10.length === 0)
      return void this.nextBatchNodeIds.push(e54);
    const i8 = (e60) => {
      for (const t10 of e60)
        this.absorbedNodeIds.add(t10.capacityMeshNodeId);
      t4._adjacentNodeIds = Array.from(new Set([...t4._adjacentNodeIds ?? [], ...e60.flatMap((e61) => e61._adjacentNodeIds ?? [])].filter((e61) => e61 !== t4.capacityMeshNodeId && !this.absorbedNodeIds.has(e61))));
    }, r9 = o10.filter((e60) => e60.center.x < t4.center.x && Math.abs(e60.center.y - t4.center.y) < t4.height / 2);
    if (r9.length > 0) {
      const { width: e60, height: o11 } = r9[0], s9 = r9.every((t10) => t10.width === e60 && t10.height === o11);
      Math.abs(r9.reduce((e61, t10) => e61 + t10.height, 0) - t4.height) < yle && s9 && (t4.width += e60, t4.center.x = t4.center.x - e60 / 2, i8(r9), n8 = true);
    }
    const s7 = o10.filter((e60) => e60.center.x > t4.center.x && Math.abs(e60.center.y - t4.center.y) < t4.height / 2);
    if (s7.length > 0 && !n8) {
      const { width: e60, height: o11 } = s7[0], r10 = s7.every((t10) => t10.width === e60 && t10.height === o11);
      Math.abs(s7.reduce((e61, t10) => e61 + t10.height, 0) - t4.height) < yle && r10 && (t4.width += e60, t4.center.x = t4.center.x + e60 / 2, i8(s7), n8 = true);
    }
    const a9 = o10.filter((e60) => e60.center.y > t4.center.y && Math.abs(e60.center.x - t4.center.x) < t4.width / 2);
    if (a9.length > 0 && !n8) {
      const { width: e60, height: o11 } = a9[0], r10 = a9.every((t10) => t10.width === e60 && t10.height === o11);
      Math.abs(a9.reduce((e61, t10) => e61 + t10.width, 0) - t4.width) < yle && r10 && (t4.height += o11, t4.center.y = t4.center.y + o11 / 2, i8(a9), n8 = true);
    }
    const c5 = o10.filter((e60) => e60.center.y < t4.center.y && Math.abs(e60.center.x - t4.center.x) < t4.width / 2);
    if (c5.length > 0 && !n8) {
      const { width: e60, height: o11 } = c5[0], r10 = c5.every((t10) => t10.width === e60 && t10.height === o11);
      Math.abs(c5.reduce((e61, t10) => e61 + t10.width, 0) - t4.width) < yle && r10 && (t4.height += o11, t4.center.y = t4.center.y - o11 / 2, i8(c5), n8 = true);
    }
    n8 ? (this.batchHadModifications = true, this.currentBatchNodeIds.push(e54)) : this.nextBatchNodeIds.unshift(e54);
  }
  visualize() {
    const e54 = { circles: [], lines: [], points: [], rects: [], coordinateSystem: "cartesian", title: "Single Layer Node Merger (Only Merge Targets)" };
    for (const t10 of this.newNodes)
      e54.rects.push(dj(t10));
    const t4 = this.currentBatchNodeIds[this.currentBatchNodeIds.length - 1];
    let n8;
    t4 && (n8 = this.getAdjacentSameLayerUnprocessedNodes(this.nodeMap.get(t4)));
    for (const o10 of this.currentBatchNodeIds) {
      const i8 = this.nodeMap.get(o10);
      if (!this.absorbedNodeIds.has(o10) && i8) {
        const r9 = dj(i8, { rectMargin: 0.01 });
        o10 === t4 ? r9.stroke = "rgba(0, 255, 0, 0.8)" : n8?.some((e60) => e60.capacityMeshNodeId === o10) ? r9.stroke = "rgba(128, 0, 128, 0.8)" : r9.stroke = "rgba(255, 165, 0, 0.8)", r9.layer = `z${i8.availableZ.join(",")}`, r9.label = `${r9.label}
(unprocessed)`, e54.rects.push(r9);
      }
    }
    for (const t10 of this.nextBatchNodeIds) {
      const n10 = this.nodeMap.get(t10);
      if (!this.absorbedNodeIds.has(t10) && n10) {
        const t11 = dj(n10, { rectMargin: 0.01 });
        t11.layer = `z${n10.availableZ.join(",")}`, t11.stroke = "rgba(0, 217, 255, 0.8)", t11.label = `${t11.label}
x: ${n10.center.x}, y: ${n10.center.y}
${n10.width}x${n10.height}
(next batch)`, e54.rects.push(t11);
      }
    }
    return e54;
  }
};
var xle = class extends ni {
  getSolverName() {
    return "AssignableViaNodeMergerSolver";
  }
  newNodes;
  obstacleToNodesMap;
  obstaclesToProcess;
  mergedNodeIds;
  constructor(e54) {
    super(), this.MAX_ITERATIONS = 1e4, this.newNodes = [], this.obstacleToNodesMap = new Map, this.mergedNodeIds = new Set;
    for (const t4 of e54) {
      const e60 = t4._assignedViaObstacle;
      if (e60) {
        const n8 = this.obstacleToNodesMap.get(e60) || [];
        n8.push(t4), this.obstacleToNodesMap.set(e60, n8);
      } else
        this.newNodes.push(t4);
    }
    this.obstaclesToProcess = Array.from(this.obstacleToNodesMap.keys());
  }
  _step() {
    const e54 = this.obstaclesToProcess.pop();
    if (!e54)
      return void (this.solved = true);
    const t4 = this.obstacleToNodesMap.get(e54);
    if (!t4 || t4.length === 0)
      return;
    let { POSITIVE_INFINITY: n8, NEGATIVE_INFINITY: o10, POSITIVE_INFINITY: i8, NEGATIVE_INFINITY: r9 } = Number;
    const s7 = new Set;
    let a9 = false;
    for (const e60 of t4) {
      const t10 = e60.center.x - e60.width / 2, c9 = e60.center.x + e60.width / 2, l10 = e60.center.y - e60.height / 2, h9 = e60.center.y + e60.height / 2;
      n8 = Math.min(n8, t10), o10 = Math.max(o10, c9), i8 = Math.min(i8, l10), r9 = Math.max(r9, h9);
      for (const t11 of e60.availableZ)
        s7.add(t11);
      e60._containsTarget && (a9 = true);
    }
    const c5 = o10 - n8, l5 = r9 - i8, h5 = (n8 + o10) / 2, d9 = (i8 + r9) / 2, u9 = Array.from(s7).sort((e60, t10) => e60 - t10), p9 = { capacityMeshNodeId: `merged_via_${e54.center.x}_${e54.center.y}`, center: { x: h5, y: d9 }, width: c5, height: l5, layer: u9.length === 1 ? `z${u9[0]}` : `z${u9.join(",")}`, availableZ: u9, _containsTarget: a9, _containsObstacle: false, _completelyInsideObstacle: false };
    p9._assignedViaObstacle = e54;
    for (const e60 of t4)
      this.mergedNodeIds.add(e60.capacityMeshNodeId);
    this.newNodes.push(p9);
  }
  visualize() {
    const e54 = { circles: [], lines: [], points: [], rects: [], coordinateSystem: "cartesian", title: "Assignable Via Node Merger" };
    for (const t10 of this.newNodes) {
      const n8 = dj(t10);
      t10._assignedViaObstacle && (n8.stroke = "rgba(255, 0, 255, 0.8)", n8.label = `${n8.label || ""}
(merged via)`), e54.rects.push(n8);
    }
    const t4 = this.obstaclesToProcess[this.obstaclesToProcess.length - 1];
    if (t4) {
      const n8 = this.obstacleToNodesMap.get(t4) || [];
      for (const t10 of n8) {
        const n10 = dj(t10, { rectMargin: 0.01 });
        n10.stroke = "rgba(0, 255, 0, 0.8)", n10.label = `${n10.label || ""}
(to be merged)`, e54.rects.push(n10);
      }
    }
    return e54;
  }
};
var vle = class extends ni {
  constructor(e54) {
    const { simpleRouteJson: t4, nodes: n8, edges: o10, colorMap: i8, MAX_ITERATIONS: r9 = 1e6, hyperParameters: s7 = {} } = e54;
    super(), this.inputParams = e54, this.hyperParameters = s7, this.MAX_ITERATIONS = r9, this.simpleRouteJson = t4, this.nodes = n8, this.edges = o10, this.colorMap = i8 ?? {}, this.nodeMap = new Map(this.nodes.map((e60) => [e60.capacityMeshNodeId, e60])), this.nodeEdgeMap = oi(this.edges);
    const a9 = this.nodes.filter((e60) => e60._containsTarget);
    this.unprocessedConnectionPairs = Sr(this.simpleRouteJson.connections.map((e60) => {
      const [t10, n10] = e60.pointsToConnect;
      return { start: a9.find((e61) => me(e61.center, t10) < e61.width / 2), end: a9.find((e61) => me(e61.center, n10) < e61.width / 2), connection: e60 };
    }), this.hyperParameters.SHUFFLE_SEED ?? 0), this.viaNodes = this.nodes.filter((e60) => e60.availableZ.length > 1);
  }
  getSolverName() {
    return "AssignableViaCapacityPathingSolver_DirectiveSubOptimal";
  }
  GREEDY_MULTIPLIER = 1.5;
  simpleRouteJson;
  nodes;
  edges;
  colorMap;
  MAX_ITERATIONS;
  hyperParameters;
  usedNodeMap = new Map;
  nodeMap;
  nodeEdgeMap;
  unprocessedConnectionPairs;
  solvedRoutes = [];
  activeConnectionPair = null;
  ogUnprocessedSubpaths = null;
  unprocessedSubpaths = null;
  solvedSubpaths = null;
  activeSubpath = null;
  viaNodes = [];
  closestViaForConnectionStartMap = new Map;
  closestViaForConnectionEndMap = new Map;
  getConstructorParams() {
    return this.inputParams;
  }
  lastStepOperation = "none";
  computeClosestViaForAllConnections() {
    this.closestViaForConnectionStartMap.clear(), this.closestViaForConnectionEndMap.clear();
    for (const e54 of this.unprocessedConnectionPairs) {
      const t4 = this.viaNodes.filter((e60) => !e60._completelyInsideObstacle && !e60._containsObstacle).filter((e60) => !this.usedNodeMap.has(e60.capacityMeshNodeId));
      if (t4.length > 0) {
        const n8 = t4.reduce((t10, n10) => {
          const o11 = this._dist(t10, e54.start);
          return this._dist(n10, e54.start) < o11 ? n10 : t10;
        });
        this.closestViaForConnectionStartMap.set(e54, n8);
        const o10 = t4.reduce((t10, n10) => {
          const o11 = this._dist(t10, e54.end);
          return this._dist(n10, e54.end) < o11 ? n10 : t10;
        });
        this.closestViaForConnectionEndMap.set(e54, o10);
      }
    }
  }
  _step() {
    if (!this.activeConnectionPair)
      return this.activeConnectionPair = this.unprocessedConnectionPairs.shift(), this.activeConnectionPair ? (this.computeClosestViaForAllConnections(), void (this.lastStepOperation = "dequeueConnectionPair")) : void (this.solved = true);
    if (this.activeConnectionPair && !this.unprocessedSubpaths)
      return this.unprocessedSubpaths = this.breakConnectionPairIntoSubpaths(this.activeConnectionPair), this.ogUnprocessedSubpaths = this.unprocessedSubpaths.slice(), this.solvedSubpaths = [], void (this.lastStepOperation = "breakConnectionPairIntoSubpaths");
    if (this.activeSubpath) {
      if (this.activeSubpath && (this.stepSolveSubpath(this.activeSubpath), this.activeSubpath.solved))
        return this.solvedSubpaths.push(this.activeSubpath), this.activeSubpath = null, this.clearCandidateNodes(), void (this.lastStepOperation = "finishedSolvingSubpath");
      this.lastStepOperation = "stepSolveSubpath";
    } else {
      if (this.activeSubpath = this.unprocessedSubpaths.shift(), !this.activeSubpath) {
        const e54 = this.activeConnectionPair;
        return this.activeConnectionPair = null, this.unprocessedSubpaths = null, this.ogUnprocessedSubpaths = null, this.activeSubpath = null, this.solvedRoutes.push(this.createSolvedRoute(this.solvedSubpaths, e54)), void (this.lastStepOperation = "finishedSolvingConnectionPair");
      }
      this.lastStepOperation = "dequeueSubpath";
    }
  }
  queuedCandidateNodes = [];
  visitedNodes = new Set;
  _dist(e54, t4) {
    return Math.hypot(e54.center.x - t4.center.x, e54.center.y - t4.center.y);
  }
  stepSolveSubpath(e54) {
    const { start: t4, end: n8 } = e54;
    if (t4.capacityMeshNodeId === n8.capacityMeshNodeId)
      return e54.path = [t4], e54.solved = true, void this.usedNodeMap.set(t4.capacityMeshNodeId, true);
    if (this.queuedCandidateNodes.length === 0 && this.visitedNodes.size === 0) {
      const e60 = this._dist(t4, n8), o11 = { prevCandidate: null, node: t4, g: 0, h: e60, f: this.GREEDY_MULTIPLIER * e60 };
      this.queuedCandidateNodes.push(o11);
    }
    let o10;
    for (this.queuedCandidateNodes.sort((e60, t10) => e60.f - t10.f);this.queuedCandidateNodes.length && !o10; ) {
      const e60 = this.queuedCandidateNodes.shift();
      this.visitedNodes.has(e60.node.capacityMeshNodeId) || (o10 = e60);
    }
    if (!o10)
      return this.failed = true, void (this.error = "No viable candidates left");
    if (this.visitedNodes.add(o10.node.capacityMeshNodeId), o10.node.capacityMeshNodeId === n8.capacityMeshNodeId) {
      const t10 = [];
      let n10 = o10;
      for (;n10; )
        t10.unshift(n10.node), this.usedNodeMap.set(n10.node.capacityMeshNodeId, true), n10 = n10.prevCandidate;
      return e54.path = t10, void (e54.solved = true);
    }
    const i8 = this.getNeighbors(o10.node);
    for (const e60 of i8) {
      const t10 = e60.capacityMeshNodeId;
      if (this.visitedNodes.has(t10))
        continue;
      const i9 = this.computeG(o10, e60, n8), r9 = this.computeH(o10, e60, n8), s7 = i9 + this.GREEDY_MULTIPLIER * r9, a9 = this.queuedCandidateNodes.findIndex((e61) => e61.node.capacityMeshNodeId === t10);
      if (a9 >= 0) {
        if (this.queuedCandidateNodes[a9].g <= i9)
          continue;
        this.queuedCandidateNodes.splice(a9, 1);
      }
      this.queuedCandidateNodes.push({ prevCandidate: o10, node: e60, g: i9, h: r9, f: s7 });
    }
  }
  getNeighbors(e54) {
    const t4 = new Set, n8 = this.nodeEdgeMap.get(e54.capacityMeshNodeId) ?? [];
    for (const o11 of n8) {
      const [n10, i8] = o11.nodeIds, r9 = n10 === e54.capacityMeshNodeId ? i8 : n10, s7 = this.nodeMap.get(r9);
      s7 && t4.add(s7);
    }
    const o10 = this.activeSubpath?.layer;
    return Array.from(t4).filter((e60) => !(e60.capacityMeshNodeId !== this.activeSubpath?.end.capacityMeshNodeId) || !e60._containsObstacle && (!e60._containsTarget && (!this.usedNodeMap.has(e60.capacityMeshNodeId) && !(o10 !== undefined && !e60.availableZ.includes(o10)))));
  }
  clearCandidateNodes() {
    this.queuedCandidateNodes = [], this.visitedNodes = new Set;
  }
  computeG(e54, t4, n8) {
    const o10 = this._dist(e54.node, t4);
    return e54.g + o10;
  }
  computeH(e54, t4, n8) {
    return this._dist(t4, n8);
  }
  createSolvedRoute(e54, t4) {
    const n8 = [];
    for (let t10 = 0;t10 < e54.length; t10++) {
      const o10 = e54[t10];
      o10.path ? t10 === 0 ? n8.push(...o10.path) : n8.push(...o10.path.slice(1)) : (t10 === 0 && n8.push(o10.start), t10 === e54.length - 1 && n8.push(o10.end));
    }
    return { connection: t4.connection, path: n8 };
  }
  breakConnectionPairIntoSubpaths(e54) {
    var t4, n8;
    if (!(t4 = [this.hyperParameters.DIRECTIVE_SEED ?? 0, this.solvedRoutes.length], n8 = this.hyperParameters.FORCE_VIA_TRAVEL_CHANCE ?? 0, vr(t4.reduce((e60, t10) => e60 + 16807 * t10 % 2147483647, 0))() < n8))
      return [{ start: e54.start, end: e54.end, solved: false, layer: e54.start.availableZ[0] ?? 0 }];
    const o10 = this.getClosestVia(e54.start), i8 = this.getFarVia(o10, e54.end), r9 = e54.start.availableZ[0] ?? 0, s7 = e54.end.availableZ[0] ?? 0, a9 = [];
    return a9.push({ start: e54.start, end: o10, solved: false, layer: r9 }), r9 === s7 ? (a9.push({ start: o10, end: i8, solved: false, layer: r9 === 0 ? 1 : 0 }), a9.push({ start: i8, end: e54.end, solved: false, layer: s7 })) : a9.push({ start: o10, end: e54.end, solved: false, layer: s7 }), a9;
  }
  getClosestVia(e54) {
    if (this.viaNodes.length === 0)
      return e54;
    const t4 = new Set;
    for (const [e60, n10] of this.closestViaForConnectionStartMap)
      e60 !== this.activeConnectionPair && t4.add(n10.capacityMeshNodeId);
    for (const [e60, n10] of this.closestViaForConnectionEndMap)
      e60 !== this.activeConnectionPair && t4.add(n10.capacityMeshNodeId);
    const n8 = this.viaNodes.filter((e60) => !e60._completelyInsideObstacle && !e60._containsObstacle).filter((e60) => !this.usedNodeMap.has(e60.capacityMeshNodeId)).filter((e60) => !t4.has(e60.capacityMeshNodeId));
    if (n8.length === 0) {
      const t10 = this.viaNodes.filter((e60) => !e60._completelyInsideObstacle && !e60._containsObstacle).filter((e60) => !this.usedNodeMap.has(e60.capacityMeshNodeId));
      return t10.length === 0 ? e54 : (t10.sort((t11, n10) => this._dist(t11, e54) - this._dist(n10, e54)), t10[0]);
    }
    n8.sort((t10, n10) => this._dist(t10, e54) - this._dist(n10, e54));
    const o10 = this.hyperParameters.MAX_CLOSEST_VIA_SKIP ?? 0;
    if (o10 > 0 && n8.length > 1) {
      const e60 = vr((this.hyperParameters.DIRECTIVE_SEED ?? 0) + this.solvedRoutes.length), t10 = Math.floor(e60() * (o10 + 1));
      return n8[Math.min(t10, n8.length - 1)];
    }
    return n8[0];
  }
  getFarVia(e54, t4) {
    if (this.viaNodes.length === 0)
      return e54;
    const n8 = this.hyperParameters.FAR_VIA_MIN_DISTANCE != null ? this.hyperParameters.FAR_VIA_MIN_DISTANCE : 50, o10 = new Set;
    for (const [e60, t10] of this.closestViaForConnectionStartMap)
      e60 !== this.activeConnectionPair && o10.add(t10.capacityMeshNodeId);
    for (const [e60, t10] of this.closestViaForConnectionEndMap)
      e60 !== this.activeConnectionPair && o10.add(t10.capacityMeshNodeId);
    const i8 = this.viaNodes.filter((t10) => !this.usedNodeMap.has(t10.capacityMeshNodeId) && t10.capacityMeshNodeId !== e54.capacityMeshNodeId && !t10._completelyInsideObstacle && !t10._containsObstacle && !o10.has(t10.capacityMeshNodeId) && this._dist(t10, e54) >= n8);
    if (i8.length === 0) {
      const o11 = this.viaNodes.filter((t10) => t10.capacityMeshNodeId !== e54.capacityMeshNodeId && !t10._completelyInsideObstacle && !t10._containsObstacle && !this.usedNodeMap.has(t10.capacityMeshNodeId) && this._dist(t10, e54) >= n8).sort((e60, n10) => this._dist(e60, t4) - this._dist(n10, t4));
      if (o11.length > 0)
        return o11[0];
      return this.viaNodes.filter((t10) => t10.capacityMeshNodeId !== e54.capacityMeshNodeId && !t10._completelyInsideObstacle && !t10._containsObstacle && !this.usedNodeMap.has(t10.capacityMeshNodeId)).sort((e60, n10) => this._dist(e60, t4) - this._dist(n10, t4))[0] ?? e54;
    }
    i8.sort((e60, n10) => this._dist(e60, t4) - this._dist(n10, t4));
    const r9 = this.hyperParameters.MAX_FURTHEST_VIA_SKIP ?? 0;
    if (r9 > 0 && i8.length > 1) {
      const e60 = vr((this.hyperParameters.DIRECTIVE_SEED ?? 0) + this.solvedRoutes.length + 1000), t10 = Math.floor(e60() * (r9 + 1));
      return i8[Math.min(t10, i8.length - 1)];
    }
    return i8[0];
  }
  getCapacityPaths() {
    const e54 = [];
    for (const t4 of this.solvedRoutes) {
      const n8 = t4.path;
      n8 && n8.length > 0 && e54.push({ capacityPathId: t4.connection.name, connectionName: t4.connection.name, nodeIds: n8.map((e60) => e60.capacityMeshNodeId) });
    }
    return e54;
  }
  visualize() {
    const e54 = { lines: [], points: [], rects: [], circles: [] }, t4 = (e60) => !!e60 && typeof e60.x == "number" && typeof e60.y == "number" && !Number.isNaN(e60.x) && !Number.isNaN(e60.y) && Number.isFinite(e60.x) && Number.isFinite(e60.y), n8 = (e60) => typeof e60 == "number" && !Number.isNaN(e60) && Number.isFinite(e60);
    for (const o11 of this.nodes) {
      const i8 = this.queuedCandidateNodes.some((e60) => e60.node.capacityMeshNodeId === o11.capacityMeshNodeId), r9 = this.queuedCandidateNodes.find((e60) => e60.node.capacityMeshNodeId === o11.capacityMeshNodeId);
      if (t4(o11.center) && n8(o11.width) && n8(o11.height)) {
        const t10 = dj(o11, { rectMargin: 0.025, zOffset: 0.01 });
        e54.rects.push({ ...t10, fill: i8 ? "rgba(255, 128, 255, 0.5)" : o11._containsTarget ? "rgba(0, 150, 255, 0.15)" : o11._containsObstacle ? "rgba(255, 0, 0, 0.1)" : "rgba(200, 200, 200, 0.05)", label: [`ID: ${o11.capacityMeshNodeId}`, `Size: ${o11.width.toFixed(2)}x${o11.height.toFixed(2)}`, `Z: ${o11.availableZ.join(", ")}`, r9 ? `g: ${r9.g.toFixed(2)}` : "", r9 ? `h: ${r9.h.toFixed(2)}` : "", r9 ? `f: ${r9.f.toFixed(2)}` : "", o11._containsTarget ? "TARGET" : "", o11._containsObstacle ? "OBSTACLE" : ""].filter((e60) => e60).join(`
`) });
      }
    }
    for (const n10 of this.edges) {
      const [o11, i8] = n10.nodeIds, r9 = this.nodeMap.get(o11), s7 = this.nodeMap.get(i8);
      r9?.center && s7?.center && t4(r9.center) && t4(s7.center) && e54.lines.push({ points: [r9.center, s7.center], strokeColor: "rgba(150, 150, 150, 0.2)" });
    }
    for (let n10 = 0;n10 < this.solvedRoutes.length; n10++) {
      const o11 = this.solvedRoutes[n10], i8 = o11.path, r9 = "blue";
      for (let o12 = 0;o12 < i8.length - 1; o12++) {
        const s7 = i8[o12], a9 = i8[o12 + 1];
        if (s7?.center && a9?.center && t4(s7.center) && t4(a9.center)) {
          const t10 = s7.availableZ.includes(1) && a9.availableZ.includes(1), o13 = n10 % 5 * 0.02;
          e54.lines.push({ points: [{ x: s7.center.x + o13, y: s7.center.y + o13 }, { x: a9.center.x + o13, y: a9.center.y + o13 }], strokeColor: r9, strokeDash: t10 ? "5 5" : undefined });
        }
      }
      if (i8.length > 0) {
        const n11 = i8[0], r10 = i8[i8.length - 1];
        n11?.center && t4(n11.center) && e54.points.push({ x: n11.center.x, y: n11.center.y, label: `START: ${o11.connection.name}` }), r10?.center && t4(r10.center) && e54.points.push({ x: r10.center.x, y: r10.center.y, label: `END: ${o11.connection.name}` });
      }
    }
    if (this.solvedSubpaths)
      for (let n10 = 0;n10 < this.solvedSubpaths.length; n10++) {
        const o11 = this.solvedSubpaths[n10];
        if (o11.path && o11.path.length > 1)
          for (let n11 = 0;n11 < o11.path.length - 1; n11++) {
            const i8 = o11.path[n11], r9 = o11.path[n11 + 1];
            i8?.center && r9?.center && t4(i8.center) && t4(r9.center) && e54.lines.push({ points: [i8.center, r9.center], strokeColor: "green", strokeDash: o11.layer === 1 ? "3 3" : undefined });
          }
      }
    if (this.activeSubpath) {
      const n10 = this.activeSubpath.start?.center, o11 = this.activeSubpath.end?.center;
      n10 && o11 && t4(n10) && t4(o11) && (e54.lines.push({ points: [n10, o11], strokeColor: "orange", strokeDash: "5 5" }), e54.points.push({ x: n10.x, y: n10.y, label: "ACTIVE START" }), e54.points.push({ x: o11.x, y: o11.y, label: "ACTIVE END" }));
    }
    const o10 = this.queuedCandidateNodes.slice(0, 10).sort((e60, t10) => e60.f - t10.f);
    for (let n10 = 0;n10 < o10.length; n10++) {
      const i8 = 0.6 * (1 - n10 / 10), r9 = [];
      let s7 = o10[n10];
      for (;s7; )
        r9.push(s7.node), s7 = s7.prevCandidate;
      if (r9.reverse(), r9.length > 1) {
        const n11 = r9.map((e60) => e60.center).filter((e60) => t4(e60));
        n11.length > 1 && e54.lines.push({ points: n11, strokeColor: Ao("purple", 1 - i8), strokeDash: this.activeSubpath?.layer === 1 ? "4 2" : undefined });
      }
    }
    if (this.activeConnectionPair) {
      const n10 = this.activeConnectionPair.start?.center, o11 = this.activeConnectionPair.end?.center;
      n10 && o11 && t4(n10) && t4(o11) && e54.lines.push({ points: [n10, o11], strokeColor: "cyan", strokeDash: "20 5" });
    }
    if (this.ogUnprocessedSubpaths && this.ogUnprocessedSubpaths.length === 3) {
      const [, o11] = this.ogUnprocessedSubpaths;
      if (o11.start?.center && t4(o11.start.center)) {
        const t10 = Math.max(o11.start.width || 0, o11.start.height || 0);
        n8(t10) && t10 > 0 && (e54.circles.push({ center: o11.start.center, radius: t10, stroke: "blue" }), e54.points.push({ x: o11.start.center.x, y: o11.start.center.y, label: "DIRECTIVE VIA 1" }));
      }
      if (o11.end?.center && t4(o11.end.center)) {
        const t10 = Math.max(o11.end.width || 0, o11.end.height || 0);
        n8(t10) && t10 > 0 && (e54.circles.push({ center: o11.end.center, radius: t10, stroke: "purple" }), e54.points.push({ x: o11.end.center.x, y: o11.end.center.y, label: "DIRECTIVE VIA 2" }));
      }
    }
    if (this.queuedCandidateNodes.length > 0)
      for (const n10 of this.queuedCandidateNodes) {
        const o11 = n10.node;
        o11?.center && t4(o11.center) && e54.circles.push({ center: o11.center, radius: 0.05, fill: "rgba(255, 255, 0, 0.6)", stroke: "yellow" });
      }
    if (this.visitedNodes.size > 0)
      for (const n10 of this.visitedNodes) {
        const o11 = this.nodeMap.get(n10);
        o11?.center && t4(o11.center) && e54.circles.push({ center: o11.center, radius: 0.08, fill: "rgba(128, 128, 128, 0.5)", stroke: "gray" });
      }
    return e54;
  }
};
var Ile = class extends wa {
  getSolverName() {
    return "HyperAssignableViaCapacityPathingSolver";
  }
  constructorParams;
  constructor(e54) {
    super(), this.constructorParams = e54, this.MAX_ITERATIONS = e54.MAX_ITERATIONS ?? 120000, this.MIN_SUBSTEPS = 5, this.GREEDY_MULTIPLIER = 1.35;
  }
  getHyperParameterDefs() {
    return [{ name: "traceOrderingSeed", possibleValues: [{ SHUFFLE_SEED: 0 }, { SHUFFLE_SEED: 1 }, { SHUFFLE_SEED: 2 }, { SHUFFLE_SEED: 3 }, { SHUFFLE_SEED: 4 }, { SHUFFLE_SEED: 5 }, { SHUFFLE_SEED: 6 }, { SHUFFLE_SEED: 7 }, { SHUFFLE_SEED: 8 }, { SHUFFLE_SEED: 9 }] }, { name: "forceViaTravelChance", possibleValues: [{ FORCE_VIA_TRAVEL_CHANCE: 0.6 }, { FORCE_VIA_TRAVEL_CHANCE: 0.8 }, { FORCE_VIA_TRAVEL_CHANCE: 0.9 }] }];
  }
  computeG(e54) {
    const t4 = e54.unprocessedConnectionPairs.length + e54.solvedRoutes.length + (e54.activeConnectionPair ? 1 : 0), n8 = e54.solvedRoutes.length, o10 = t4 > 0 ? n8 / t4 : 0;
    return e54.iterations / e54.MAX_ITERATIONS + (1 - o10);
  }
  computeH(e54) {
    const t4 = e54.unprocessedConnectionPairs.length + e54.solvedRoutes.length + (e54.activeConnectionPair ? 1 : 0), n8 = e54.solvedRoutes.length;
    return t4 > 0 ? 1 - n8 / t4 : 0;
  }
  generateSolver(e54) {
    return new vle({ ...this.constructorParams, hyperParameters: { ...this.constructorParams.hyperParameters, ...e54 } });
  }
};
function Sle(e54) {
  const t4 = new Map;
  for (const n8 of e54)
    t4.set(n8.capacityMeshNodeId, n8);
  return t4;
}
function Cle(e54, t4) {
  return { x: (e54.x + t4.x) / 2, y: (e54.y + t4.y) / 2 };
}
var Ple = class extends ni {
  getSolverName() {
    return "OffboardCapacityNodeSolver";
  }
  capacityNodes;
  capacityEdges;
  enhancedEdges = [];
  animationState = "showing_nodes";
  assignableNodes = [];
  shownNodes = [];
  pendingEdges = [];
  createdEdges = [];
  nextEdgeId = 0;
  nodeMap = new Map;
  constructor(e54) {
    super(), this.capacityNodes = e54.capacityNodes, this.capacityEdges = e54.capacityEdges, this.nodeMap = Sle(this.capacityNodes), this.enhancedEdges = [...this.capacityEdges], this.initializeAssignableNodes(), this.initializePendingEdges(), this.MAX_ITERATIONS = this.assignableNodes.length + this.pendingEdges.length + 10;
  }
  initializeAssignableNodes() {
    for (const e54 of this.capacityNodes) {
      const t4 = e54._assignedViaObstacle;
      t4?.offBoardConnectsTo && t4.offBoardConnectsTo.length > 0 && this.assignableNodes.push(e54);
    }
  }
  initializePendingEdges() {
    const e54 = new Map;
    for (const t4 of this.assignableNodes) {
      const n8 = t4._assignedViaObstacle;
      if (n8?.offBoardConnectsTo)
        for (const o10 of n8.offBoardConnectsTo)
          e54.has(o10) || e54.set(o10, []), e54.get(o10).push(t4);
    }
    this.pendingEdges = [];
    for (const [t4, n8] of e54)
      if (n8.length > 1)
        for (let e60 = 0;e60 < n8.length; e60++)
          for (let o10 = e60 + 1;o10 < n8.length; o10++)
            this.pendingEdges.push({ node1: n8[e60], node2: n8[o10], netName: t4 });
  }
  _step() {
    switch (this.animationState) {
      case "showing_nodes":
        if (this.assignableNodes.length > 0) {
          const e54 = this.assignableNodes.shift();
          this.shownNodes.push(e54);
        } else
          this.animationState = "showing_edges";
        break;
      case "showing_edges":
        if (this.pendingEdges.length > 0) {
          const { node1: e54, node2: t4, netName: n8 } = this.pendingEdges.shift(), o10 = this.createOffboardEdge(e54, t4, n8);
          this.enhancedEdges.push(o10), this.createdEdges.push(o10);
        } else
          this.animationState = "done", this.solved = true;
        break;
      case "done":
        this.solved = true;
    }
  }
  createOffboardEdge(e54, t4, n8) {
    return { capacityMeshEdgeId: "offboard_" + this.nextEdgeId++, nodeIds: [e54.capacityMeshNodeId, t4.capacityMeshNodeId], isOffboardEdge: true, offboardNetName: n8 };
  }
  visualize() {
    const e54 = [], t4 = [], n8 = [], o10 = new Set(this.shownNodes.map((e60) => e60.capacityMeshNodeId));
    for (const t10 of this.capacityEdges) {
      if (t10.isOffboardEdge)
        continue;
      if (o10.has(t10.nodeIds[0]) || o10.has(t10.nodeIds[1])) {
        const n10 = this.nodeMap.get(t10.nodeIds[0]), o11 = this.nodeMap.get(t10.nodeIds[1]);
        n10 && o11 && e54.push({ points: [n10.center, o11.center], strokeColor: "rgba(0, 200, 0, 0.5)", strokeWidth: 0.05 });
      }
    }
    for (let e60 = 0;e60 < this.shownNodes.length; e60++) {
      const o11 = this.shownNodes[e60], i9 = o11._assignedViaObstacle, r9 = e60 === this.shownNodes.length - 1 && this.animationState === "showing_nodes";
      n8.push({ center: o11.center, width: o11.width, height: o11.height, fill: r9 ? "rgba(255, 165, 0, 0.5)" : "rgba(173, 216, 230, 0.5)", stroke: r9 ? "orange" : "blue", strokeWidth: r9 ? 0.15 : 0.1 }), t4.push({ x: o11.center.x, y: o11.center.y, color: r9 ? "orange" : "blue", label: `${r9 ? "NEW: " : ""}${o11.capacityMeshNodeId}
${i9?.offBoardConnectsTo?.join(", ") || ""}` });
    }
    for (let n10 = 0;n10 < this.createdEdges.length; n10++) {
      const o11 = this.createdEdges[n10], i9 = n10 === this.createdEdges.length - 1 && this.animationState === "showing_edges", r9 = this.nodeMap.get(o11.nodeIds[0]), s7 = this.nodeMap.get(o11.nodeIds[1]);
      if (r9 && s7) {
        e54.push({ points: [r9.center, s7.center], strokeColor: i9 ? "red" : "orange", strokeWidth: i9 ? 0.2 : 0.1, strokeDasharray: "0.3,0.15" });
        const n11 = Cle(r9.center, s7.center);
        t4.push({ x: n11.x, y: n11.y, color: i9 ? "red" : "orange", label: `${i9 ? "NEW: " : ""}⚡ ${o11.offboardNetName}` });
      }
    }
    let i8 = "Offboard Capacity Node Solver";
    switch (this.animationState) {
      case "showing_nodes":
        i8 += ` - Showing nodes (${this.shownNodes.length}/${this.shownNodes.length + this.assignableNodes.length})`;
        break;
      case "showing_edges":
        i8 += ` - Creating edges (${this.createdEdges.length}/${this.createdEdges.length + this.pendingEdges.length})`;
        break;
      case "done":
        i8 += ` - Done (${this.shownNodes.length} nodes, ${this.createdEdges.length} edges)`;
    }
    return { lines: e54, points: t4, rects: n8, title: i8 };
  }
  getVirtualOffboardNodes() {
    return [];
  }
  getOffboardEdges() {
    return this.enhancedEdges.filter((e54) => e54.isOffboardEdge);
  }
};
var Mle = class extends ni {
  getSolverName() {
    return "OffboardPathFragmentSolver";
  }
  inputPaths;
  capacityEdges;
  originalConnections;
  fragmentedPaths = [];
  fragmentedConnections = [];
  fragmentedOriginalConnectionNames = new Set;
  nextFragmentId = 0;
  animationState = "showing_original_path";
  currentPath = null;
  currentFragments = [];
  currentFragmentIndex = 0;
  nodeMap = new Map;
  constructor({ capacityPaths: e54, capacityEdges: t4, capacityNodes: n8, connections: o10 }) {
    super(), this.inputPaths = [...e54], this.capacityEdges = t4, this.originalConnections = o10, this.nodeMap = Sle(n8);
  }
  _step() {
    switch (this.animationState) {
      case "showing_original_path":
        if (this.inputPaths.length === 0)
          return this.animationState = "done", void (this.solved = true);
        this.currentPath = this.inputPaths.shift(), this.currentFragments = this.splitPath(this.currentPath), this.currentFragmentIndex = 0;
        this.currentFragments.some((e54) => e54.isFragmentedPath) ? this.animationState = "showing_fragment" : this.fragmentedPaths.push(...this.currentFragments);
        break;
      case "showing_fragment":
        if (this.currentFragmentIndex < this.currentFragments.length) {
          const e54 = this.currentFragments[this.currentFragmentIndex];
          this.fragmentedPaths.push(e54), this.currentFragmentIndex++;
        } else
          this.currentPath && (this.fragmentedOriginalConnectionNames.add(this.currentPath.connectionName), this.createFragmentConnections(this.currentPath, this.currentFragments)), this.currentPath = null, this.currentFragments = [], this.currentFragmentIndex = 0, this.animationState = "showing_original_path";
        break;
      case "done":
        this.solved = true;
    }
  }
  createFragmentConnections(e54, t4) {
    const n8 = this.originalConnections.find((t10) => t10.name === e54.connectionName);
    if (n8)
      for (let e60 = 0;e60 < t4.length; e60++) {
        const o10 = t4[e60];
        if (!o10.isFragmentedPath)
          continue;
        const i8 = n8.pointsToConnect.filter((e61) => {
          for (const t10 of o10.nodeIds) {
            const n10 = this.nodeMap.get(t10);
            if (n10 && oK(e61, n10))
              return true;
          }
          return false;
        }), r9 = e60 === 0, s7 = r9 ? o10.nodeIds[o10.nodeIds.length - 1] : o10.nodeIds[0], a9 = this.nodeMap.get(s7);
        if (i8.length > 0 && a9) {
          const e61 = i8[0], t10 = { x: a9.center.x, y: a9.center.y, layer: Io(e61) }, s9 = r9 ? [...i8, t10] : [t10, ...i8];
          this.fragmentedConnections.push({ name: o10.connectionName, pointsToConnect: s9, __netConnectionName: n8.__netConnectionName, __rootConnectionNames: n8.__rootConnectionNames });
        }
      }
  }
  splitPath(e54) {
    const { nodeIds: t4 } = e54;
    if (t4.length < 2)
      return [e54];
    const n8 = [];
    for (let e60 = 0;e60 < t4.length - 1; e60++) {
      const o11 = this.capacityEdges.find((n10) => n10.nodeIds[0] === t4[e60] && n10.nodeIds[1] === t4[e60 + 1] || n10.nodeIds[0] === t4[e60 + 1] && n10.nodeIds[1] === t4[e60]);
      o11 && o11.isOffboardEdge && n8.push(e60);
    }
    if (n8.length === 0)
      return [e54];
    const o10 = [];
    let i8 = 0, r9 = 0;
    for (const s7 of n8) {
      const n10 = t4.slice(i8, s7 + 1);
      if (n10.length >= 1) {
        const t10 = this.nextFragmentId++;
        o10.push({ capacityPathId: `${e54.capacityPathId}_frag_${t10}`, connectionName: `${e54.connectionName}_frag_${r9++}`, rootConnectionName: e54.rootConnectionName, nodeIds: n10, isFragmentedPath: true, mstPairConnectionName: e54.connectionName });
      }
      i8 = s7 + 1;
    }
    if (i8 < t4.length) {
      const n10 = t4.slice(i8);
      if (n10.length >= 1) {
        const t10 = this.nextFragmentId++;
        o10.push({ capacityPathId: `${e54.capacityPathId}_frag_${t10}`, connectionName: `${e54.connectionName}_frag_${r9++}`, rootConnectionName: e54.rootConnectionName, nodeIds: n10, isFragmentedPath: true, mstPairConnectionName: e54.connectionName });
      }
    }
    return o10.length > 0 ? o10 : [e54];
  }
  getFragmentedPaths() {
    return this.fragmentedPaths;
  }
  getFragmentedConnections() {
    return this.fragmentedConnections;
  }
  getFragmentedOriginalConnectionNames() {
    return this.fragmentedOriginalConnectionNames;
  }
  visualize() {
    const e54 = [], t4 = [], n8 = [];
    if (this.animationState === "showing_original_path" && this.currentPath && this.drawPath({ path: this.currentPath, color: "gray", lines: e54, points: t4, rects: n8, labelPrefix: "Original: " }), this.fragmentedPaths.forEach((o11, i8) => {
      if (o11.isFragmentedPath) {
        const r9 = i8 % 2 == 0 ? "blue" : "red";
        this.drawPath({ path: o11, color: r9, lines: e54, points: t4, rects: n8, labelPrefix: `Frag ${i8}: ` });
      } else
        this.drawPath({ path: o11, color: "green", lines: e54, points: t4, rects: n8, labelPrefix: "" });
    }), this.animationState === "showing_fragment" && this.currentFragmentIndex > 0) {
      const o11 = this.fragmentedPaths.length - 1;
      if (o11 >= 0) {
        const i8 = this.fragmentedPaths[o11];
        i8.isFragmentedPath && this.drawPath({ path: i8, color: "orange", lines: e54, points: t4, rects: n8, labelPrefix: "NEW: " });
      }
    }
    for (const t10 of this.capacityEdges)
      if (t10.isOffboardEdge) {
        const n10 = this.nodeMap.get(t10.nodeIds[0]), o11 = this.nodeMap.get(t10.nodeIds[1]);
        n10 && o11 && e54.push({ points: [n10.center, o11.center], strokeColor: "orange", strokeWidth: 0.15, strokeDasharray: "0.3,0.15" });
      }
    let o10 = "Offboard Path Fragment Solver";
    return this.animationState === "showing_original_path" ? o10 += " - Analyzing path..." : this.animationState === "showing_fragment" ? o10 += ` - Fragment ${this.currentFragmentIndex}/${this.currentFragments.length}` : o10 += ` - Done (${this.fragmentedPaths.filter((e60) => e60.isFragmentedPath).length} fragments)`, { lines: e54, points: t4, rects: n8, title: o10 };
  }
  drawPath(e54) {
    const { path: t4, color: n8, lines: o10, points: i8, rects: r9, labelPrefix: s7 } = e54, a9 = [];
    for (let e60 = 0;e60 < t4.nodeIds.length; e60++) {
      const o11 = t4.nodeIds[e60], c5 = this.nodeMap.get(o11);
      c5 && (a9.push(c5.center), r9.push({ center: c5.center, width: 0.8 * c5.width, height: 0.8 * c5.height, stroke: n8, strokeWidth: 0.05, fill: `${n8}33` }), e60 !== 0 && e60 !== t4.nodeIds.length - 1 || i8.push({ x: c5.center.x, y: c5.center.y, color: n8, label: `${s7}${t4.connectionName}
${o11}` }));
    }
    a9.length > 1 && o10.push({ points: a9, strokeColor: n8, strokeWidth: 0.1 });
  }
};
function wle(e54, t4, n8, o10 = {}) {
  return { solverName: e54, solverClass: t4, getConstructorParams: n8, onSolved: o10.onSolved };
}
var Nle = class extends ni {
  constructor(e54, t4 = {}) {
    super(), this.srj = e54, this.opts = t4, this.srj = e54, this.opts = { ...t4 }, this.MAX_ITERATIONS = 1e8;
    const n8 = this.opts;
    if (n8.capacityDepth === undefined) {
      const t10 = e54.bounds.maxX - e54.bounds.minX, o10 = e54.bounds.maxY - e54.bounds.minY, i8 = Math.max(t10, o10), r9 = n8.targetMinCapacity ?? 0.5;
      n8.capacityDepth = Fz(i8, r9);
    }
    this.connMap = ei(e54), this.colorMap = Eo(e54, this.connMap), this.cacheProvider = n8.cacheProvider === undefined ? no() : n8.cacheProvider === null ? null : n8.cacheProvider, this.startTimeOfPhase = {}, this.endTimeOfPhase = {}, this.timeSpentOnPhase = {};
  }
  getSolverName() {
    return "AssignableAutoroutingPipeline1Solver";
  }
  netToPointPairsSolver;
  nodeSolver;
  nodeTargetMerger;
  edgeSolver;
  initialPathingSolver;
  initialPathingHyperSolver;
  pathingOptimizer;
  edgeToPortSegmentSolver;
  colorMap;
  segmentToPointSolver;
  unravelMultiSectionSolver;
  segmentToPointOptimizer;
  highDensityRouteSolver;
  highDensityStitchSolver;
  singleLayerNodeMerger;
  mergeAssignableViaNodes;
  offboardCapacityNodeSolver;
  offboardPathFragmentSolver;
  strawSolver;
  deadEndSolver;
  uselessViaRemovalSolver1;
  uselessViaRemovalSolver2;
  multiSimplifiedPathSolver1;
  multiSimplifiedPathSolver2;
  startTimeOfPhase;
  endTimeOfPhase;
  timeSpentOnPhase;
  activeSubSolver = null;
  connMap;
  srjWithPointPairs;
  capacityNodes = null;
  capacityEdges = null;
  cacheProvider = null;
  pipelineDef = [wle("netToPointPairsSolver", uB, (e54) => [e54.srj, e54.colorMap, ti(e54.srj)], { onSolved: (e54) => {
    e54.srjWithPointPairs = e54.netToPointPairsSolver?.getNewSimpleRouteJson(), e54.colorMap = Eo(e54.srjWithPointPairs, this.connMap), e54.connMap = ei(e54.srjWithPointPairs);
  } }), wle("nodeSolver", _le, (e54) => [e54.netToPointPairsSolver?.getNewSimpleRouteJson() || e54.srj, e54.opts], { onSolved: (e54) => {
    e54.capacityNodes = e54.nodeSolver?.finishedNodes;
  } }), wle("mergeAssignableViaNodes", xle, (e54) => [e54.nodeSolver?.finishedNodes], { onSolved: (e54) => {
    e54.capacityNodes = e54.mergeAssignableViaNodes?.newNodes;
  } }), wle("singleLayerNodeMerger", ble, (e54) => [e54.capacityNodes], { onSolved: (e54) => {
    e54.capacityNodes = e54.singleLayerNodeMerger?.newNodes;
  } }), wle("edgeSolver", ui, (e54) => [e54.capacityNodes], { onSolved: (e54) => {
    e54.capacityEdges = e54.edgeSolver?.edges;
  } }), wle("offboardCapacityNodeSolver", Ple, (e54) => [{ capacityNodes: e54.capacityNodes, capacityEdges: e54.capacityEdges || [] }], { onSolved: (e54) => {
    e54.capacityEdges = e54.offboardCapacityNodeSolver?.enhancedEdges || e54.capacityEdges;
  } }), wle("deadEndSolver", Nj, (e54) => [{ nodes: e54.capacityNodes, edges: e54.capacityEdges }], { onSolved: (e54) => {
    const t4 = e54.deadEndSolver?.removedNodeIds;
    e54.capacityNodes = e54.capacityNodes.filter((e60) => !t4.has(e60.capacityMeshNodeId)), e54.capacityEdges = e54.capacityEdges.filter((e60) => e60.nodeIds.every((e61) => !t4.has(e61)));
  } }), wle("initialPathingHyperSolver", Ile, (e54) => [{ simpleRouteJson: e54.srjWithPointPairs, nodes: e54.capacityNodes, edges: e54.capacityEdges || [], colorMap: e54.colorMap, hyperParameters: { MAX_CAPACITY_FACTOR: 1 } }], { onSolved: (e54) => {
    const t4 = e54.initialPathingHyperSolver?.winningSolver;
    t4 && (e54.initialPathingSolver = t4);
  } }), wle("offboardPathFragmentSolver", Mle, (e54) => [{ capacityPaths: e54.initialPathingSolver?.getCapacityPaths() || [], capacityEdges: e54.capacityEdges || [], capacityNodes: e54.capacityNodes || [], connections: e54.srjWithPointPairs?.connections || [] }], { onSolved: (e54) => {
    const t4 = e54.offboardPathFragmentSolver;
    if (!t4)
      return;
    const n8 = t4.getFragmentedPaths();
    for (const t10 of n8)
      if (t10.isFragmentedPath && t10.mstPairConnectionName) {
        const n10 = e54.colorMap[t10.mstPairConnectionName];
        n10 && !e54.colorMap[t10.connectionName] && (e54.colorMap[t10.connectionName] = n10);
      }
    const o10 = t4.getFragmentedOriginalConnectionNames(), i8 = t4.getFragmentedConnections();
    o10.size > 0 && e54.srjWithPointPairs && (e54.srjWithPointPairs = { ...e54.srjWithPointPairs, connections: [...e54.srjWithPointPairs.connections.filter((e60) => !o10.has(e60.name)), ...i8] }, e54.connMap = ei(e54.srjWithPointPairs));
  } }), wle("edgeToPortSegmentSolver", nj, (e54) => [{ nodes: e54.capacityNodes, edges: e54.capacityEdges || [], capacityPaths: e54.offboardPathFragmentSolver?.getFragmentedPaths() || e54.initialPathingSolver?.getCapacityPaths() || [], colorMap: e54.colorMap }]), wle("segmentToPointSolver", hj, (e54) => {
    const t4 = [];
    return e54.edgeToPortSegmentSolver?.nodePortSegments && e54.edgeToPortSegmentSolver.nodePortSegments.forEach((e60) => {
      t4.push(...e60);
    }), [{ segments: t4, colorMap: e54.colorMap, nodes: e54.capacityNodes }];
  }), wle("unravelMultiSectionSolver", Hj, (e54) => [{ assignedSegments: e54.segmentToPointSolver?.solvedSegments || [], colorMap: e54.colorMap, nodes: e54.capacityNodes, cacheProvider: this.cacheProvider }]), wle("highDensityRouteSolver", Dz, (e54) => [{ nodePortPoints: e54.unravelMultiSectionSolver?.getNodesWithPortPoints() ?? e54.segmentToPointOptimizer?.getNodesWithPortPoints() ?? [], colorMap: e54.colorMap, connMap: e54.connMap }]), wle("highDensityStitchSolver", IB, (e54) => [{ connections: e54.srjWithPointPairs.connections, hdRoutes: e54.highDensityRouteSolver.routes, colorMap: e54.colorMap, layerCount: e54.srj.layerCount }]), wle("uselessViaRemovalSolver1", aF, (e54) => [{ unsimplifiedHdRoutes: e54.highDensityStitchSolver.mergedHdRoutes, obstacles: e54.srj.obstacles, colorMap: e54.colorMap, layerCount: e54.srj.layerCount, connMap: e54.connMap }]), wle("multiSimplifiedPathSolver1", xF, (e54) => [{ unsimplifiedHdRoutes: e54.uselessViaRemovalSolver1?.getOptimizedHdRoutes() || e54.highDensityStitchSolver.mergedHdRoutes, obstacles: e54.srj.obstacles, connMap: e54.connMap, colorMap: e54.colorMap, outline: e54.srj.outline }]), wle("uselessViaRemovalSolver2", aF, (e54) => [{ unsimplifiedHdRoutes: e54.multiSimplifiedPathSolver1.simplifiedHdRoutes, obstacles: e54.srj.obstacles, colorMap: e54.colorMap, layerCount: e54.srj.layerCount, connMap: e54.connMap }]), wle("multiSimplifiedPathSolver2", xF, (e54) => [{ unsimplifiedHdRoutes: e54.uselessViaRemovalSolver2?.getOptimizedHdRoutes(), obstacles: e54.srj.obstacles, connMap: e54.connMap, colorMap: e54.colorMap, outline: e54.srj.outline }])];
  getConstructorParams() {
    return [this.srj, this.opts];
  }
  currentPipelineStepIndex = 0;
  _step() {
    const e54 = this.pipelineDef[this.currentPipelineStepIndex];
    if (!e54)
      return void (this.solved = true);
    if (this.activeSubSolver)
      return this.activeSubSolver.step(), void (this.activeSubSolver.solved ? (this.endTimeOfPhase[e54.solverName] = performance.now(), this.timeSpentOnPhase[e54.solverName] = this.endTimeOfPhase[e54.solverName] - this.startTimeOfPhase[e54.solverName], e54.onSolved?.(this), this.activeSubSolver = null, this.currentPipelineStepIndex++) : this.activeSubSolver.failed && (this.error = this.activeSubSolver?.error, this.failed = true, this.activeSubSolver = null));
    const t4 = e54.getConstructorParams(this);
    this.activeSubSolver = new e54.solverClass(...t4), this[e54.solverName] = this.activeSubSolver, this.timeSpentOnPhase[e54.solverName] = 0, this.startTimeOfPhase[e54.solverName] = performance.now();
  }
  solveUntilPhase(e54) {
    for (;this.getCurrentPhase() !== e54; )
      this.step();
  }
  getCurrentPhase() {
    return this.pipelineDef[this.currentPipelineStepIndex]?.solverName ?? "none";
  }
  visualize() {
    if (!this.solved && this.activeSubSolver)
      return this.activeSubSolver.visualize();
    const e54 = this.netToPointPairsSolver?.visualize(), t4 = this.nodeSolver?.visualize(), n8 = this.nodeTargetMerger?.visualize(), o10 = this.mergeAssignableViaNodes?.visualize(), i8 = this.singleLayerNodeMerger?.visualize(), r9 = this.strawSolver?.visualize(), s7 = this.edgeSolver?.visualize(), a9 = (this.offboardCapacityNodeSolver?.visualize(), this.deadEndSolver?.visualize()), c5 = this.initialPathingSolver?.visualize(), l5 = this.offboardPathFragmentSolver?.visualize(), h5 = this.pathingOptimizer?.visualize(), d9 = this.edgeToPortSegmentSolver?.visualize(), u9 = this.segmentToPointSolver?.visualize(), p9 = this.unravelMultiSectionSolver?.visualize() ?? this.segmentToPointOptimizer?.visualize(), m9 = this.highDensityRouteSolver?.visualize(), g10 = this.highDensityStitchSolver?.visualize(), f10 = this.uselessViaRemovalSolver1?.visualize(), _5 = this.uselessViaRemovalSolver2?.visualize(), y10 = this.multiSimplifiedPathSolver1?.visualize(), b10 = this.multiSimplifiedPathSolver2?.visualize(), x8 = this.srj.outline, v10 = [];
    if (v10.push({ points: [{ x: this.srj.bounds?.minX ?? -50, y: this.srj.bounds?.minY ?? -50 }, { x: this.srj.bounds?.maxX ?? 50, y: this.srj.bounds?.minY ?? -50 }, { x: this.srj.bounds?.maxX ?? 50, y: this.srj.bounds?.maxY ?? 50 }, { x: this.srj.bounds?.minX ?? -50, y: this.srj.bounds?.maxY ?? 50 }, { x: this.srj.bounds?.minX ?? -50, y: this.srj.bounds?.minY ?? -50 }], strokeColor: "rgba(255,0,0,0.25)" }), x8 && x8.length >= 2) {
      const e60 = x8.map((e61) => ({ x: e61.x, y: e61.y }));
      e60.push({ ...e60[0] }), v10.push({ points: e60, strokeColor: "rgba(0, 136, 255, 0.95)" });
    }
    const I6 = Lo(this.srj), S6 = { points: [...this.srj.connections.flatMap((e60) => e60.pointsToConnect.map((t10) => ({ ...t10, layer: Bo(t10, this.srj.layerCount), label: `${e60.name} ${t10.pcb_port_id ?? ""}` })))], rects: [...(this.srj.obstacles ?? []).filter((e60) => !e60.isCopperPour).map((e60) => ({ ...e60, fill: e60.layers?.includes("top") ? "rgba(255,0,0,0.25)" : e60.layers?.includes("bottom") ? "rgba(0,0,255,0.25)" : "rgba(255,0,0,0.25)", layer: jo(e60, this.srj.layerCount), label: I6(e60) }))], lines: v10 }, C = [S6, e54, t4, n8, o10, i8, r9, s7, a9, c5, l5, h5, d9, u9, p9, m9 ? pi(S6, m9) : null, g10, f10, y10, _5, b10, this.solved ? pi({ lines: v10 }, Wo(this.getOutputSimpleRouteJson())) : null].filter(Boolean);
    return pi(...C);
  }
  preview() {
    if (this.highDensityRouteSolver) {
      const e54 = [];
      for (let t4 = this.highDensityRouteSolver.routes.length - 1;t4 >= 0; t4--) {
        const n8 = this.highDensityRouteSolver.routes[t4];
        if (e54.push({ points: n8.route.map((e60) => ({ x: e60.x, y: e60.y })), strokeColor: this.colorMap[n8.connectionName] }), e54.length > 200)
          break;
      }
      return { lines: e54 };
    }
    if (this.pathingOptimizer) {
      const e54 = [];
      for (const t4 of this.pathingOptimizer.connectionsWithNodes)
        t4.path && e54.push({ points: t4.path.map((e60) => ({ x: e60.center.x, y: e60.center.y })), strokeColor: this.colorMap[t4.connection.name] });
      return { lines: e54 };
    }
    return this.netToPointPairsSolver ? this.netToPointPairsSolver?.visualize() : {};
  }
  _getOutputHdRoutes() {
    return this.multiSimplifiedPathSolver2?.simplifiedHdRoutes ?? this.uselessViaRemovalSolver2?.getOptimizedHdRoutes() ?? this.multiSimplifiedPathSolver1?.simplifiedHdRoutes ?? this.uselessViaRemovalSolver1?.getOptimizedHdRoutes() ?? this.highDensityStitchSolver.mergedHdRoutes;
  }
  getOutputSimplifiedPcbTraces() {
    if (!this.solved || !this.highDensityRouteSolver)
      throw new Error("Cannot get output before solving is complete");
    const e54 = [], t4 = this._getOutputHdRoutes(), n8 = this.srjWithPointPairs?.connections ?? [];
    for (const o10 of n8) {
      const n10 = o10.__netConnectionName, i8 = o10.__rootConnectionNames?.[0], r9 = t4.filter((e60) => e60.connectionName === o10.name);
      for (let t10 = 0;t10 < r9.length; t10++) {
        const s7 = r9[t10], a9 = { type: "pcb_trace", pcb_trace_id: `${o10.name}_${t10}`, connection_name: n10 ?? i8 ?? o10.name, route: Ro(s7, this.srj.layerCount) };
        e54.push(a9);
      }
    }
    return e54;
  }
  getOutputSimpleRouteJson() {
    return { ...this.srj, traces: this.getOutputSimplifiedPcbTraces() };
  }
};
/*! Bundled license information:

is-buffer/index.js:
  (*!
   * Determine if an object is a Buffer
   *
   * @author   Feross Aboukhadijeh <https://feross.org>
   * @license  MIT
   *)

deep-rename-keys/index.js:
  (*!
   * deep-rename-keys <https://github.com/jonschlinkert/deep-rename-keys>
   *
   * Copyright (c) 2015 Jon Schlinkert, contributors.
   * Licensed under the MIT license.
   *)

@tscircuit/curvy-trace-solver/dist/index.js:
@tscircuit/find-convex-regions/dist/index.js:
  (*! Bundled license information:
  
  is-buffer/index.js:
    (*!
     * Determine if an object is a Buffer
     *
     * @author   Feross Aboukhadijeh <https://feross.org>
     * @license  MIT
     *)
  
  deep-rename-keys/index.js:
    (*!
     * deep-rename-keys <https://github.com/jonschlinkert/deep-rename-keys>
     *
     * Copyright (c) 2015 Jon Schlinkert, contributors.
     * Licensed under the MIT license.
     *)
  *)

@tscircuit/hypergraph/dist/index.js:
  (*! Bundled license information:
  
  @tscircuit/find-convex-regions/dist/index.js:
    (*! Bundled license information:
    
    is-buffer/index.js:
      (*!
       * Determine if an object is a Buffer
       *
       * @author   Feross Aboukhadijeh <https://feross.org>
       * @license  MIT
       *)
    
    deep-rename-keys/index.js:
      (*!
       * deep-rename-keys <https://github.com/jonschlinkert/deep-rename-keys>
       *
       * Copyright (c) 2015 Jon Schlinkert, contributors.
       * Licensed under the MIT license.
       *)
    *)
  *)
*/

// routing.ts
async function routeRemaining(input) {
  const solver = new Ote(input, {
    powerTraceExpansion: { onlyConnectionNames: [] }
  });
  const existing = new Set((input.traces ?? []).map((trace) => trace.pcb_trace_id));
  const handlers = {
    complete: [],
    error: [],
    progress: []
  };
  let stopped = false;
  const run = () => {
    if (stopped)
      return;
    try {
      const until = Date.now() + 40;
      while (!solver.solved && !solver.failed && Date.now() < until)
        solver.step();
      if (solver.failed) {
        handlers.error.forEach((handler) => handler({ error: new Error(solver.error || "Routing failed") }));
        return;
      }
      if (solver.solved) {
        const traces = (solver.getOutputSimpleRouteJson().traces ?? []).filter((trace) => !existing.has(trace.pcb_trace_id));
        handlers.complete.forEach((handler) => handler({ traces }));
        return;
      }
      setTimeout(run, 0);
    } catch (error) {
      handlers.error.forEach((handler) => handler({ error }));
    }
  };
  return {
    on: (event, handler) => {
      handlers[event].push(handler);
    },
    start: () => setTimeout(run, 0),
    stop: () => {
      stopped = true;
    }
  };
}

// props-schema.ts
var propsJsonSchema = {
  $schema: "http://json-schema.org/draft-07/schema#",
  type: "object",
  additionalProperties: false,
  properties: {
    externalLfCrystal: { type: "boolean", title: "External LF crystal", default: true },
    debugHeader: { type: "boolean", title: "SWD header", default: true },
    supplyVoltage: { type: "number", title: "Supply voltage", enum: [1.8, 2.5, 3, 3.3], default: 2.5, "x-unit": "V" },
    inputBulkCapacitance: { type: "string", title: "Input bulk capacitor", enum: ["10uF", "22uF"], default: "10uF", "x-unit": "F" },
    resetPullupResistance: { type: "string", title: "Reset pull-up", enum: ["100k", "10k"], default: "100k", "x-unit": "Ω" }
  },
  required: ["externalLfCrystal", "debugHeader", "supplyVoltage", "inputBulkCapacitance", "resetPullupResistance"]
};

// scripts/shared/props-parser.ts
import Ajv from "ajv";
function createPropsParser(schema) {
  const ajv = new Ajv({ useDefaults: true, strictSchema: false, allErrors: true });
  const validate = ajv.compile(schema);
  return {
    parse(input) {
      const value = structuredClone(input);
      if (!validate(value))
        throw new Error(ajv.errorsText(validate.errors));
      return value;
    }
  };
}
// imports/cc2340r52e0rger.tsx
import { jsxDEV } from "react/jsx-dev-runtime";
var pinLabels = {
  pin1: ["ANT"],
  pin2: ["VDDR1"],
  pin3: ["DIO8"],
  pin4: ["DIO11"],
  pin5: ["DIO12"],
  pin6: ["DIO13"],
  pin7: ["DIO16_SWDIO"],
  pin8: ["DIO17_SWDCK"],
  pin9: ["DIO20_A11"],
  pin10: ["DIO21_A10"],
  pin11: ["VDDS1"],
  pin12: ["DIO24_A7"],
  pin13: ["RSTN"],
  pin14: ["DIO3_X32P"],
  pin15: ["DIO4_X32N"],
  pin16: ["VDDD"],
  pin17: ["DCDC"],
  pin18: ["VDDS2"],
  pin19: ["DIO6_A1"],
  pin20: ["VDDR2"],
  pin21: ["X48P"],
  pin22: ["X48N"],
  pin23: ["GND"],
  pin24: ["VDDS3"],
  pin25: ["EP"]
};
var cc2340PinAttributes = {
  pin23: { requiresGround: true, mustBeConnected: true },
  pin1: { isBidirectional: true },
  pin2: {
    mustBeConnected: true,
    shouldHaveDecouplingCapacitor: true,
    recommendedDecouplingCapacitorCapacitance: "10uF"
  },
  pin3: {
    isBidirectional: true,
    capabilities: ["spi_sck", "i2c_sda"],
    canUseInternalPullup: true,
    canUseInternalPulldown: true,
    canUseOpenDrain: true,
    canUsePushPull: true,
    isGpio: true
  },
  pin4: {
    isBidirectional: true,
    capabilities: ["spi_cs", "spi_miso"],
    canUseInternalPullup: true,
    canUseInternalPulldown: true,
    canUseOpenDrain: true,
    canUsePushPull: true,
    isGpio: true
  },
  pin5: {
    isBidirectional: true,
    capabilities: ["spi_miso", "spi_mosi", "uart_rx", "i2c_sda"],
    canUseInternalPullup: true,
    canUseInternalPulldown: true,
    canUseOpenDrain: true,
    canUsePushPull: true,
    isGpio: true
  },
  pin6: {
    isBidirectional: true,
    capabilities: ["spi_miso", "spi_mosi", "uart_tx"],
    canUseInternalPullup: true,
    canUseInternalPulldown: true,
    canUseOpenDrain: true,
    canUsePushPull: true,
    isGpio: true
  },
  pin7: {
    isBidirectional: true,
    capabilities: ["spi_mosi", "uart_rx", "i2c_sda"],
    canUseInternalPullup: true,
    canUseInternalPulldown: true,
    canUseOpenDrain: true,
    canUsePushPull: true,
    isGpio: true
  },
  pin8: {
    isBidirectional: true,
    capabilities: ["spi_sck", "uart_tx", "i2c_scl"],
    canUseInternalPullup: true,
    canUseInternalPulldown: true,
    canUseOpenDrain: true,
    canUsePushPull: true,
    isGpio: true
  },
  pin9: {
    isBidirectional: true,
    capabilities: ["uart_tx", "uart_rx", "spi_miso"],
    canUseInternalPullup: true,
    canUseInternalPulldown: true,
    canUseOpenDrain: true,
    canUsePushPull: true,
    isGpio: true
  },
  pin10: {
    isBidirectional: true,
    capabilities: ["spi_miso"],
    canUseInternalPullup: true,
    canUseInternalPulldown: true,
    canUseOpenDrain: true,
    canUsePushPull: true,
    isGpio: true
  },
  pin11: {
    requiresPower: true,
    mustBeConnected: true,
    shouldHaveDecouplingCapacitor: true
  },
  pin12: {
    isBidirectional: true,
    capabilities: ["spi_sck", "i2c_scl"],
    canUseInternalPullup: true,
    canUseInternalPulldown: true,
    canUseOpenDrain: true,
    canUsePushPull: true,
    isGpio: true
  },
  pin13: { isInput: true },
  pin14: {
    isBidirectional: true,
    canUseInternalPullup: true,
    canUseInternalPulldown: true,
    canUseOpenDrain: true,
    canUsePushPull: true,
    isGpio: true
  },
  pin15: {
    isBidirectional: true,
    capabilities: ["uart_tx", "spi_mosi"],
    canUseInternalPullup: true,
    canUseInternalPulldown: true,
    canUseOpenDrain: true,
    canUsePushPull: true,
    isGpio: true
  },
  pin16: { mustBeConnected: true, shouldHaveDecouplingCapacitor: true },
  pin18: {
    requiresPower: true,
    mustBeConnected: true,
    shouldHaveDecouplingCapacitor: true
  },
  pin19: {
    isBidirectional: true,
    capabilities: ["spi_cs", "i2c_scl", "uart_tx"],
    canUseInternalPullup: true,
    canUseInternalPulldown: true,
    canUseOpenDrain: true,
    canUsePushPull: true,
    isGpio: true
  },
  pin20: {
    mustBeConnected: true,
    shouldHaveDecouplingCapacitor: true,
    recommendedDecouplingCapacitorCapacitance: "10uF"
  },
  pin24: {
    requiresPower: true,
    mustBeConnected: true,
    shouldHaveDecouplingCapacitor: true
  },
  pin25: { mustBeConnected: true }
};
var CC2340R52E0RGER = ({
  pinAttributes: selectedPinAttributes,
  ...props
}) => {
  const overrides = selectedPinAttributes ?? {};
  const pinAttributes = Object.fromEntries(Object.keys({ ...cc2340PinAttributes, ...overrides }).map((pin) => [
    pin,
    { ...cc2340PinAttributes[pin], ...overrides[pin] }
  ]));
  return /* @__PURE__ */ jsxDEV("chip", {
    pinLabels,
    pinAttributes,
    supplierPartNumbers: {
      jlcpcb: ["C20416850"]
    },
    manufacturerPartNumber: "CC2340R52E0RGER",
    footprint: /* @__PURE__ */ jsxDEV("footprint", {
      children: [
        /* @__PURE__ */ jsxDEV("smtpad", {
          portHints: ["pin1"],
          pcbX: "-1.89992mm",
          pcbY: "1.250061mm",
          width: "0.5999988mm",
          height: "0.2500122mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV("smtpad", {
          portHints: ["pin2"],
          pcbX: "-1.89992mm",
          pcbY: "0.750189mm",
          width: "0.5999988mm",
          height: "0.2500122mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV("smtpad", {
          portHints: ["pin3"],
          pcbX: "-1.89992mm",
          pcbY: "0.250063mm",
          width: "0.5999988mm",
          height: "0.2500122mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV("smtpad", {
          portHints: ["pin4"],
          pcbX: "-1.89992mm",
          pcbY: "-0.249809mm",
          width: "0.5999988mm",
          height: "0.2500122mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV("smtpad", {
          portHints: ["pin5"],
          pcbX: "-1.89992mm",
          pcbY: "-0.749935mm",
          width: "0.5999988mm",
          height: "0.2500122mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV("smtpad", {
          portHints: ["pin6"],
          pcbX: "-1.89992mm",
          pcbY: "-1.249807mm",
          width: "0.5999988mm",
          height: "0.2500122mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV("smtpad", {
          portHints: ["pin7"],
          pcbX: "-1.250188mm",
          pcbY: "-1.900047mm",
          width: "0.2500122mm",
          height: "0.5999988mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV("smtpad", {
          portHints: ["pin8"],
          pcbX: "-0.750316mm",
          pcbY: "-1.900047mm",
          width: "0.2500122mm",
          height: "0.5999988mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV("smtpad", {
          portHints: ["pin9"],
          pcbX: "-0.25019mm",
          pcbY: "-1.900047mm",
          width: "0.2500122mm",
          height: "0.5999988mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV("smtpad", {
          portHints: ["pin10"],
          pcbX: "0.249682mm",
          pcbY: "-1.900047mm",
          width: "0.2500122mm",
          height: "0.5999988mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV("smtpad", {
          portHints: ["pin11"],
          pcbX: "0.749808mm",
          pcbY: "-1.900047mm",
          width: "0.2500122mm",
          height: "0.5999988mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV("smtpad", {
          portHints: ["pin12"],
          pcbX: "1.24968mm",
          pcbY: "-1.900047mm",
          width: "0.2500122mm",
          height: "0.5999988mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV("smtpad", {
          portHints: ["pin13"],
          pcbX: "1.89992mm",
          pcbY: "-1.250061mm",
          width: "0.5999988mm",
          height: "0.2500122mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV("smtpad", {
          portHints: ["pin14"],
          pcbX: "1.89992mm",
          pcbY: "-0.749935mm",
          width: "0.5999988mm",
          height: "0.2500122mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV("smtpad", {
          portHints: ["pin15"],
          pcbX: "1.89992mm",
          pcbY: "-0.250063mm",
          width: "0.5999988mm",
          height: "0.2500122mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV("smtpad", {
          portHints: ["pin16"],
          pcbX: "1.89992mm",
          pcbY: "0.250063mm",
          width: "0.5999988mm",
          height: "0.2500122mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV("smtpad", {
          portHints: ["pin17"],
          pcbX: "1.89992mm",
          pcbY: "0.749935mm",
          width: "0.5999988mm",
          height: "0.2500122mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV("smtpad", {
          portHints: ["pin18"],
          pcbX: "1.89992mm",
          pcbY: "1.250061mm",
          width: "0.5999988mm",
          height: "0.2500122mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV("smtpad", {
          portHints: ["pin19"],
          pcbX: "1.24968mm",
          pcbY: "1.900047mm",
          width: "0.2500122mm",
          height: "0.5999988mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV("smtpad", {
          portHints: ["pin20"],
          pcbX: "0.749808mm",
          pcbY: "1.900047mm",
          width: "0.2500122mm",
          height: "0.5999988mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV("smtpad", {
          portHints: ["pin21"],
          pcbX: "0.249682mm",
          pcbY: "1.900047mm",
          width: "0.2500122mm",
          height: "0.5999988mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV("smtpad", {
          portHints: ["pin22"],
          pcbX: "-0.25019mm",
          pcbY: "1.900047mm",
          width: "0.2500122mm",
          height: "0.5999988mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV("smtpad", {
          portHints: ["pin23"],
          pcbX: "-0.750316mm",
          pcbY: "1.900047mm",
          width: "0.2500122mm",
          height: "0.5999988mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV("smtpad", {
          portHints: ["pin24"],
          pcbX: "-1.250188mm",
          pcbY: "1.900047mm",
          width: "0.2500122mm",
          height: "0.5999988mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV("smtpad", {
          portHints: ["pin25"],
          pcbX: "0mm",
          pcbY: "-0.000127mm",
          width: "2.4500078mm",
          height: "2.4500078mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV("silkscreenpath", {
          route: [
            { x: -2.1044915999999603, y: 1.7001743999999235 },
            { x: -2.1044915999999603, y: 2.100148200000035 },
            { x: -1.7001743999999235, y: 2.1000212000000147 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV("silkscreenpath", {
          route: [
            { x: -2.1001990000000887, y: -1.6998696000000564 },
            { x: -2.1001990000000887, y: -2.0999704000000747 },
            { x: -1.7001743999999235, y: -2.0999704000000747 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV("silkscreenpath", {
          route: [
            { x: 2.0997926000000007, y: -1.5999713999999585 },
            { x: 2.0997926000000007, y: -2.0999704000000747 },
            { x: 1.6998188000001164, y: -2.0999704000000747 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV("silkscreenpath", {
          route: [
            { x: 1.6954753999999639, y: 2.100148200000035 },
            { x: 2.095449199999962, y: 2.100148200000035 },
            { x: 2.095449199999962, y: 1.7001743999999235 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV("silkscreencircle", {
          pcbX: -1.65,
          pcbY: 1.65,
          radius: 0.12
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV("courtyardoutline", {
          outline: [
            { x: -2.45, y: -2.45 },
            { x: 2.45, y: -2.45 },
            { x: 2.45, y: 2.45 },
            { x: -2.45, y: 2.45 },
            { x: -2.45, y: -2.45 }
          ]
        }, undefined, false, undefined, this)
      ]
    }, undefined, true, undefined, this),
    cadModel: {
      objUrl: "https://modelcdn.tscircuit.com/easyeda_models/assets/C20416850.obj?uuid=d7837941ee5a48928cbbb5a65ba7a879",
      stepUrl: "https://modelcdn.tscircuit.com/easyeda_models/assets/C20416850.step?uuid=d7837941ee5a48928cbbb5a65ba7a879",
      pcbRotationOffset: 0,
      modelOriginPosition: { x: 0, y: 0.000025400000026820635, z: 0 }
    },
    ...props
  }, undefined, false, undefined, this);
};

// imports/abm11w-48-0000mhz-8-d1x-t3.tsx
import { jsxDEV as jsxDEV2 } from "react/jsx-dev-runtime";
var pinLabels2 = {
  pin1: ["OSC1", "X1"],
  pin2: ["GND1"],
  pin3: ["OSC2", "X2"],
  pin4: ["GND2"]
};
var pinAttributes = {
  pin2: { requiresGround: true },
  pin4: { requiresGround: true }
};
var ABM11W_48_0000MHZ_8_D1X_T3 = (props) => {
  return /* @__PURE__ */ jsxDEV2("crystal", {
    frequency: "48MHz",
    loadCapacitance: "8pF",
    pinVariant: "four_pin",
    pinLabels: pinLabels2,
    pinAttributes,
    supplierPartNumbers: {
      jlcpcb: ["C1986112"]
    },
    manufacturerPartNumber: "ABM11W-48.0000MHZ-8-D1X-T3",
    footprint: /* @__PURE__ */ jsxDEV2("footprint", {
      children: [
        /* @__PURE__ */ jsxDEV2("smtpad", {
          portHints: ["pin2"],
          pcbX: "0.6375mm",
          pcbY: "-0.4875mm",
          width: "0.875mm",
          height: "0.775mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV2("smtpad", {
          portHints: ["pin3"],
          pcbX: "0.6375mm",
          pcbY: "0.4875mm",
          width: "0.875mm",
          height: "0.775mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV2("smtpad", {
          portHints: ["pin4"],
          pcbX: "-0.6375mm",
          pcbY: "0.4875mm",
          width: "0.875mm",
          height: "0.775mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV2("smtpad", {
          portHints: ["pin1"],
          pcbX: "-0.6375mm",
          pcbY: "-0.4875mm",
          width: "0.875mm",
          height: "0.775mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV2("silkscreenrect", {
          pcbX: "0mm",
          pcbY: "0mm",
          width: "2.05mm",
          height: "1.65mm",
          strokeWidth: "0.151999696mm"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV2("courtyardoutline", {
          outline: [
            { x: -1.4, y: -1.2 },
            { x: 1.4, y: -1.2 },
            { x: 1.4, y: 1.2 },
            { x: -1.4, y: 1.2 },
            { x: -1.4, y: -1.2 }
          ]
        }, undefined, false, undefined, this)
      ]
    }, undefined, true, undefined, this),
    cadModel: {
      objUrl: "https://modelcdn.tscircuit.com/easyeda_models/assets/C1986112.obj?uuid=51ae9b24ba7a408881f7752b57b66e45",
      stepUrl: "https://modelcdn.tscircuit.com/easyeda_models/assets/C1986112.step?uuid=51ae9b24ba7a408881f7752b57b66e45",
      pcbRotationOffset: 0,
      modelOriginPosition: { x: 0, y: -0.00011430000006384944, z: -0.01 }
    },
    ...props
  }, undefined, false, undefined, this);
};

// imports/abs07-32-768khz-7-t.tsx
import { jsxDEV as jsxDEV3 } from "react/jsx-dev-runtime";
var pinLabels3 = {
  pin1: ["OSC1"],
  pin2: ["OSC2"]
};
var ABS07_32_768KHZ_7_T = (props) => {
  return /* @__PURE__ */ jsxDEV3("crystal", {
    frequency: "32.768kHz",
    loadCapacitance: "7pF",
    pinLabels: pinLabels3,
    supplierPartNumbers: {
      jlcpcb: ["C276424"]
    },
    manufacturerPartNumber: "ABS07_32_768KHZ_7_T",
    footprint: /* @__PURE__ */ jsxDEV3("footprint", {
      children: [
        /* @__PURE__ */ jsxDEV3("smtpad", {
          portHints: ["pin1"],
          pcbX: "-1.1549888mm",
          pcbY: "0mm",
          width: "0.850011mm",
          height: "1.6999966mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV3("smtpad", {
          portHints: ["pin2"],
          pcbX: "1.1549888mm",
          pcbY: "0mm",
          width: "0.850011mm",
          height: "1.6999966mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV3("silkscreenpath", {
          route: [
            { x: -2.028596400000083, y: -1.0786109999999098 },
            { x: -2.028596400000083, y: 1.0786110000000235 },
            { x: 2.0285963999999694, y: 1.0786110000000235 },
            { x: 2.0285963999999694, y: -1.0786109999999098 },
            { x: -2.028596400000083, y: -1.0786109999999098 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV3("courtyardoutline", {
          outline: [
            { x: -2.282000000000039, y: 1.3167999999999438 },
            { x: 2.2819999999999254, y: 1.3167999999999438 },
            { x: 2.2819999999999254, y: -1.3421999999999343 },
            { x: -2.282000000000039, y: -1.3421999999999343 },
            { x: -2.282000000000039, y: 1.3167999999999438 }
          ]
        }, undefined, false, undefined, this)
      ]
    }, undefined, true, undefined, this),
    cadModel: {
      objUrl: "https://modelcdn.tscircuit.com/easyeda_models/assets/C276424.obj?uuid=b374b09d4a6d4557b2ff8af51e7e333f",
      stepUrl: "https://modelcdn.tscircuit.com/easyeda_models/assets/C276424.step?uuid=b374b09d4a6d4557b2ff8af51e7e333f",
      pcbRotationOffset: 0,
      modelOriginPosition: { x: 0, y: -0.000012700000070253736, z: 0 }
    },
    ...props
  }, undefined, false, undefined, this);
};

// imports/bm05b-srss-tb-lf-sn.tsx
import { jsxDEV as jsxDEV4 } from "react/jsx-dev-runtime";
var pinLabels4 = {
  pin1: ["VTREF", "pin1"],
  pin2: ["SWDIO", "pin2"],
  pin3: ["SWCLK", "pin3"],
  pin4: ["GND", "pin4"],
  pin5: ["RESET_N", "pin5"],
  pin6: ["SHIELD1", "MT1", "pin6"],
  pin7: ["SHIELD2", "MT2", "pin7"]
};
var BM05B_SRSS_TB_LF__SN_ = (props) => {
  return /* @__PURE__ */ jsxDEV4("connector", {
    pinLabels: pinLabels4,
    supplierPartNumbers: {
      jlcpcb: ["C160391"]
    },
    manufacturerPartNumber: "BM05B-SRSS-TB(LF)(SN)",
    footprint: /* @__PURE__ */ jsxDEV4("footprint", {
      insertionDirection: "from_above",
      children: [
        /* @__PURE__ */ jsxDEV4("smtpad", {
          portHints: ["pin7"],
          pcbX: "-3.299968mm",
          pcbY: "-1.1998833mm",
          width: "1.1999976mm",
          height: "1.7999964mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV4("smtpad", {
          portHints: ["pin6"],
          pcbX: "3.299968mm",
          pcbY: "-1.1998833mm",
          width: "1.1999976mm",
          height: "1.7999964mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV4("smtpad", {
          portHints: ["pin5"],
          pcbX: "-1.999996mm",
          pcbY: "1.3248767mm",
          width: "0.5999988mm",
          height: "1.5500096mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV4("smtpad", {
          portHints: ["pin4"],
          pcbX: "-0.999998mm",
          pcbY: "1.3248767mm",
          width: "0.5999988mm",
          height: "1.5500096mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV4("smtpad", {
          portHints: ["pin3"],
          pcbX: "0mm",
          pcbY: "1.3248767mm",
          width: "0.5999988mm",
          height: "1.5500096mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV4("smtpad", {
          portHints: ["pin2"],
          pcbX: "0.999998mm",
          pcbY: "1.3248767mm",
          width: "0.5999988mm",
          height: "1.5500096mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV4("smtpad", {
          portHints: ["pin1"],
          pcbX: "1.999996mm",
          pcbY: "1.3248767mm",
          width: "0.5999988mm",
          height: "1.5500096mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV4("silkscreenpath", {
          route: [
            { x: -2.468829199999959, y: -1.8425033000000894 },
            { x: 2.4688800000001265, y: -1.8425033000000894 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV4("silkscreenpath", {
          route: [
            { x: 2.5311607999999524, y: 1.0784966999999597 },
            { x: 3.556025400000067, y: 1.0784966999999597 },
            { x: 3.556025400000067, y: -0.0688466999999946 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV4("silkscreenpath", {
          route: [
            { x: -3.555974600000013, y: -0.0688466999999946 },
            { x: -3.555974600000013, y: 1.0784966999999597 },
            { x: -2.5311099999998987, y: 1.0784966999999597 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV4("silkscreencircle", {
          pcbX: "2.921mm",
          pcbY: "1.7134967mm",
          radius: "0.179578mm"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV4("courtyardoutline", {
          outline: [
            { x: -4.159568000000036, y: 2.354402700000037 },
            { x: 4.138232000000016, y: 2.354402700000037 },
            { x: 4.138232000000016, y: -2.336597299999994 },
            { x: -4.159568000000036, y: -2.336597299999994 },
            { x: -4.159568000000036, y: 2.354402700000037 }
          ]
        }, undefined, false, undefined, this)
      ]
    }, undefined, true, undefined, this),
    cadModel: {
      objUrl: "https://modelcdn.tscircuit.com/easyeda_models/assets/C160391.obj?uuid=eaf9e23008df4ce1b5a7b451075b7284",
      stepUrl: "https://modelcdn.tscircuit.com/easyeda_models/assets/C160391.step?uuid=eaf9e23008df4ce1b5a7b451075b7284",
      pcbRotationOffset: 180,
      modelOriginPosition: {
        x: 2.000025400000027,
        y: -0.43250299999996966,
        z: -0.01
      }
    },
    ...props
  }, undefined, false, undefined, this);
};

// imports/a-2450at18a100e.tsx
import { jsxDEV as jsxDEV5 } from "react/jsx-dev-runtime";
var pinLabels5 = {
  pin1: ["ANT"],
  pin2: ["NC"]
};
var A_2450AT18A100E = (props) => {
  return /* @__PURE__ */ jsxDEV5("antenna", {
    pinLabels: pinLabels5,
    symbol: /* @__PURE__ */ jsxDEV5("symbol", {
      children: [
        /* @__PURE__ */ jsxDEV5("schematictext", {
          text: props.name,
          schX: 0.5,
          schY: 0,
          fontSize: 0.18
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV5("schematicpath", {
          points: [
            { x: 0, y: 0 },
            { x: -0.2, y: 0.2 }
          ],
          strokeColor: "#8D2323"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV5("schematicpath", {
          points: [
            { x: 0.2, y: 0.2 },
            { x: 0, y: 0 }
          ],
          strokeColor: "#8D2323"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV5("schematicpath", {
          points: [
            { x: 0, y: 0 },
            { x: 0, y: -0.2 }
          ],
          strokeColor: "#8D2323"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV5("port", {
          name: "pin1",
          pinNumber: 1,
          aliases: ["ANT"],
          direction: "down",
          schX: 0,
          schY: -0.4,
          schStemLength: 0.2
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV5("schematicpath", {
          points: [
            { x: 0, y: 0 },
            { x: 0, y: 0.3 }
          ],
          strokeColor: "#880000"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV5("port", {
          name: "pin2",
          pinNumber: 2,
          aliases: ["2"],
          direction: "up",
          schX: 0,
          schY: 0.3,
          schStemLength: 0.2
        }, undefined, false, undefined, this)
      ]
    }, undefined, true, undefined, this),
    supplierPartNumbers: {
      jlcpcb: ["C89334"]
    },
    manufacturerPartNumber: "2450AT18A100E",
    footprint: /* @__PURE__ */ jsxDEV5("footprint", {
      children: [
        /* @__PURE__ */ jsxDEV5("smtpad", {
          portHints: ["pin1"],
          pcbX: "-1.7mm",
          pcbY: "0mm",
          width: "0.8mm",
          height: "1.6mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV5("smtpad", {
          portHints: ["pin2"],
          pcbX: "1.7mm",
          pcbY: "0mm",
          width: "0.8mm",
          height: "1.6mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV5("silkscreenpath", {
          route: [
            { x: -0.7619999999998299, y: 0.2540000000000191 },
            { x: -0.7619999999998299, y: -0.2539999999999054 },
            { x: -0.2539999999999054, y: -0.2539999999999054 },
            { x: -0.2539999999999054, y: 0.2540000000000191 },
            { x: -0.7619999999998299, y: 0.2540000000000191 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV5("silkscreenpath", {
          route: [
            { x: -1.6759935999999698, y: 1.059967400000005 },
            { x: 1.6759936000000835, y: 1.0499852000000374 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV5("silkscreenpath", {
          route: [
            { x: 1.5240000000001146, y: -1.0500105999999505 },
            { x: -1.6759428000000298, y: -1.0499852000000374 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV5("fabricationnotepath", {
          route: [
            { x: -1.2597129999999197, y: 0.22793960000001334 },
            { x: -0.2838195999999016, y: 0.22793960000001334 },
            { x: -0.2838195999999016, y: -0.20652739999991354 },
            { x: -1.2599669999999605, y: -0.2116073999999344 },
            { x: -1.2597129999999197, y: -0.17978119999997944 },
            { x: -1.2597129999999197, y: 0.22793960000001334 }
          ],
          strokeWidth: "0.254mm"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV5("courtyardoutline", {
          outline: [
            { x: -2.3330539999998336, y: 1.3167999999999438 },
            { x: 2.3325459999999794, y: 1.3167999999999438 },
            { x: 2.3325459999999794, y: -1.291400000000067 },
            { x: -2.3330539999998336, y: -1.291400000000067 },
            { x: -2.3330539999998336, y: 1.3167999999999438 }
          ]
        }, undefined, false, undefined, this)
      ]
    }, undefined, true, undefined, this),
    cadModel: {
      objUrl: "https://modelcdn.tscircuit.com/easyeda_models/assets/C89334.obj?uuid=cbaa998426f54032b453ce6fafc2cd5a",
      stepUrl: "https://modelcdn.tscircuit.com/easyeda_models/assets/C89334.step?uuid=cbaa998426f54032b453ce6fafc2cd5a",
      pcbRotationOffset: 180,
      modelOriginPosition: { x: 0, y: 0, z: -0.65 }
    },
    ...props
  }, undefined, false, undefined, this);
};

// imports/cl05b104ko5nnnc.tsx
import { jsxDEV as jsxDEV6 } from "react/jsx-dev-runtime";
var CL05B104KO5NNNC = (props) => {
  const { name = "C1", ...restProps } = props;
  return /* @__PURE__ */ jsxDEV6("capacitor", {
    name,
    capacitance: "100nF",
    supplierPartNumbers: {
      jlcpcb: ["C1525"]
    },
    manufacturerPartNumber: "CL05B104KO5NNNC",
    footprint: /* @__PURE__ */ jsxDEV6("footprint", {
      children: [
        /* @__PURE__ */ jsxDEV6("smtpad", {
          portHints: ["pin2"],
          pcbX: "0.420116mm",
          pcbY: "0mm",
          width: "0.499999mm",
          height: "0.540004mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV6("smtpad", {
          portHints: ["pin1"],
          pcbX: "-0.420116mm",
          pcbY: "0mm",
          width: "0.499999mm",
          height: "0.540004mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV6("silkscreenpath", {
          route: [
            { x: -0.721385400000031, y: 0.49753519999990203 },
            { x: -0.22138640000002852, y: 0.49753519999990203 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV6("silkscreenpath", {
          route: [
            { x: -0.8738108000000011, y: -0.34724340000002485 },
            { x: -0.8738108000000011, y: 0.3451606000000993 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV6("silkscreenpath", {
          route: [
            { x: -0.22138640000002852, y: -0.4996433999999681 },
            { x: -0.721385400000031, y: -0.4996433999999681 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV6("silkscreenpath", {
          route: [
            { x: 0.7213853999999174, y: -0.4975097999999889 },
            { x: 0.22138639999991483, y: -0.4975097999999889 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV6("silkscreenpath", {
          route: [
            { x: 0.22138639999991483, y: 0.49961800000005496 },
            { x: 0.7213853999999174, y: 0.49961800000005496 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV6("silkscreenpath", {
          route: [
            { x: 0.8738108000000011, y: 0.34726880000005167 },
            { x: 0.8738108000000011, y: -0.3451606000000993 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV6("silkscreenpath", {
          route: [
            { x: 0.7213853999999174, y: 0.4996433999998544 },
            { x: 0.829148473452733, y: 0.4550064734527268 },
            { x: 0.8737853999998606, y: 0.34724340000002485 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV6("silkscreenpath", {
          route: [
            { x: 0.8737853999998606, y: -0.3451606000000993 },
            { x: 0.829148473452733, y: -0.4529236734526876 },
            { x: 0.7213853999999174, y: -0.49756059999992885 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV6("silkscreenpath", {
          route: [
            { x: -0.721385400000031, y: -0.4996433999997407 },
            { x: -0.829148473452733, y: -0.45500647345261314 },
            { x: -0.8737853999999743, y: -0.34724340000002485 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV6("silkscreenpath", {
          route: [
            { x: -0.8737853999999743, y: 0.3451606000000993 },
            { x: -0.829148473452733, y: 0.45292367345280127 },
            { x: -0.721385400000031, y: 0.49756060000004254 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV6("courtyardoutline", {
          outline: [
            { x: -1.1136000000000195, y: 0.7580000000000382 },
            { x: 1.1389999999998963, y: 0.7580000000000382 },
            { x: 1.1389999999998963, y: -0.7326000000000477 },
            { x: -1.1136000000000195, y: -0.7326000000000477 },
            { x: -1.1136000000000195, y: 0.7580000000000382 }
          ]
        }, undefined, false, undefined, this)
      ]
    }, undefined, true, undefined, this),
    cadModel: {
      objUrl: "https://modelcdn.tscircuit.com/easyeda_models/assets/C1525.obj?uuid=32fe2cf9314f444ca2785a33c2db7189",
      stepUrl: "https://modelcdn.tscircuit.com/easyeda_models/assets/C1525.step?uuid=32fe2cf9314f444ca2785a33c2db7189",
      pcbRotationOffset: 0,
      modelOriginPosition: { x: 0, y: -0.000012700000070253736, z: -0.25 }
    },
    ...restProps
  }, undefined, false, undefined, this);
};

// imports/grm033r61a104ke15d.tsx
import { jsxDEV as jsxDEV7 } from "react/jsx-dev-runtime";
var GRM033R61A104KE15D = (props) => {
  const { name = "C1", ...restProps } = props;
  return /* @__PURE__ */ jsxDEV7("capacitor", {
    name,
    capacitance: "100nF",
    supplierPartNumbers: {
      jlcpcb: ["C76934"]
    },
    manufacturerPartNumber: "GRM033R61A104KE15D",
    footprint: /* @__PURE__ */ jsxDEV7("footprint", {
      children: [
        /* @__PURE__ */ jsxDEV7("smtpad", {
          portHints: ["pin2"],
          pcbX: "0.27432mm",
          pcbY: "0mm",
          width: "0.368427mm",
          height: "0.3240024mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV7("smtpad", {
          portHints: ["pin1"],
          pcbX: "-0.27432mm",
          pcbY: "0mm",
          width: "0.368427mm",
          height: "0.3240024mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV7("silkscreenpath", {
          route: [
            { x: 0.5346445999999787, y: 0.3906011999999919 },
            { x: 0.16619220000006862, y: 0.3906011999999919 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV7("silkscreenpath", {
          route: [
            { x: 0.16619220000006862, y: -0.3906011999999919 },
            { x: 0.5346445999999787, y: -0.3906011999999919 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV7("silkscreenpath", {
          route: [
            { x: 0.6870446000000356, y: -0.23820120000004863 },
            { x: 0.6870446000000356, y: 0.23820120000004863 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV7("silkscreenpath", {
          route: [
            { x: -0.5346446000000924, y: 0.3906011999999919 },
            { x: -0.16619220000006862, y: 0.3906011999999919 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV7("silkscreenpath", {
          route: [
            { x: -0.16619220000006862, y: -0.3906011999999919 },
            { x: -0.5346446000000924, y: -0.3906011999999919 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV7("silkscreenpath", {
          route: [
            { x: -0.6870446000001493, y: -0.23820120000004863 },
            { x: -0.6870446000001493, y: 0.23820120000004863 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV7("silkscreenpath", {
          route: [
            { x: 0.5346445999999787, y: -0.3906011999998782 },
            { x: 0.6424076734527944, y: -0.3459642734528643 },
            { x: 0.6870446000000356, y: -0.23820120000004863 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV7("silkscreenpath", {
          route: [
            { x: 0.6870446000000356, y: 0.23820120000004863 },
            { x: 0.6424076734527944, y: 0.3459642734528643 },
            { x: 0.5346445999999787, y: 0.3906011999999919 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV7("silkscreenpath", {
          route: [
            { x: -0.5346446000000924, y: -0.3906011999998782 },
            { x: -0.6424076734529081, y: -0.3459642734528643 },
            { x: -0.6870446000001493, y: -0.23820120000004863 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV7("silkscreenpath", {
          route: [
            { x: -0.6870446000001493, y: 0.23820120000004863 },
            { x: -0.6424076734529081, y: 0.3459642734528643 },
            { x: -0.5346446000000924, y: 0.3906011999999919 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV7("courtyardoutline", {
          outline: [
            { x: -0.935799999999972, y: 0.6309999999999718 },
            { x: 0.9358000000000857, y: 0.6309999999999718 },
            { x: 0.9358000000000857, y: -0.6563999999999623 },
            { x: -0.935799999999972, y: -0.6563999999999623 },
            { x: -0.935799999999972, y: 0.6309999999999718 }
          ]
        }, undefined, false, undefined, this)
      ]
    }, undefined, true, undefined, this),
    cadModel: {
      objUrl: "https://modelcdn.tscircuit.com/easyeda_models/assets/C76934.obj?uuid=c3e75c3d90204c70b153866ab54c789f",
      stepUrl: "https://modelcdn.tscircuit.com/easyeda_models/assets/C76934.step?uuid=c3e75c3d90204c70b153866ab54c789f",
      pcbRotationOffset: 0,
      modelOriginPosition: { x: 0, y: -0.000012700000070253736, z: -0.15 }
    },
    ...restProps
  }, undefined, false, undefined, this);
};

// imports/grm188z71a106ka73d.tsx
import { jsxDEV as jsxDEV8 } from "react/jsx-dev-runtime";
var GRM188Z71A106KA73D = (props) => {
  const { name = "C1", ...restProps } = props;
  return /* @__PURE__ */ jsxDEV8("capacitor", {
    name,
    capacitance: "10uF",
    supplierPartNumbers: {
      jlcpcb: ["C2959727"]
    },
    manufacturerPartNumber: "GRM188Z71A106KA73D",
    footprint: /* @__PURE__ */ jsxDEV8("footprint", {
      children: [
        /* @__PURE__ */ jsxDEV8("smtpad", {
          portHints: ["pin2"],
          pcbX: "0.700024mm",
          pcbY: "0mm",
          width: "0.7999984mm",
          height: "0.8999982mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV8("smtpad", {
          portHints: ["pin1"],
          pcbX: "-0.700024mm",
          pcbY: "0mm",
          width: "0.7999984mm",
          height: "0.8999982mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV8("silkscreenpath", {
          route: [
            { x: -0.2801873999999316, y: -0.7095743999998376 },
            { x: -1.080160400000068, y: -0.7095743999998376 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV8("silkscreenpath", {
          route: [
            { x: 0.28026359999989836, y: -0.7100315999998656 },
            { x: 1.080236599999921, y: -0.7100315999998656 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV8("silkscreenpath", {
          route: [
            { x: -0.2801873999999316, y: 0.7101078000000598 },
            { x: -1.080160400000068, y: 0.7101078000000598 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV8("silkscreenpath", {
          route: [
            { x: 0.28026359999989836, y: 0.7096252000001186 },
            { x: 1.080236599999921, y: 0.7096252000001186 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV8("silkscreenpath", {
          route: [
            { x: -1.3899134000000686, y: -0.3997452000000976 },
            { x: -1.3899134000000686, y: 0.40030400000000554 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV8("silkscreenpath", {
          route: [
            { x: 1.3900149999998348, y: 0.39977060000001075 },
            { x: 1.3900149999998348, y: -0.4002531999999519 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV8("silkscreenpath", {
          route: [
            { x: 1.080185799999981, y: 0.7096252000001186 },
            { x: 1.299277109074751, y: 0.6188693482574763 },
            { x: 1.3900149999998348, y: 0.39977060000001075 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV8("silkscreenpath", {
          route: [
            { x: 1.3900149999998348, y: -0.40020240000012564 },
            { x: 1.2992681283295724, y: -0.6192847283296032 },
            { x: 1.080185799999981, y: -0.7100315999998656 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV8("silkscreenpath", {
          route: [
            { x: -1.0801096000000143, y: -0.7095743999998376 },
            { x: -1.2991755087698493, y: -0.6188185485625581 },
            { x: -1.3899134000000686, y: -0.3997452000000976 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV8("silkscreenpath", {
          route: [
            { x: -1.3899134000000686, y: 0.40022780000003877 },
            { x: -1.2991934705021322, y: 0.6193339880503572 },
            { x: -1.0801096000000143, y: 0.7101078000000598 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV8("courtyardoutline", {
          outline: [
            { x: -1.647000000000162, y: 0.9612000000000762 },
            { x: 1.6216000000000577, y: 0.9612000000000762 },
            { x: 1.6216000000000577, y: -0.9611999999999625 },
            { x: -1.647000000000162, y: -0.9611999999999625 },
            { x: -1.647000000000162, y: 0.9612000000000762 }
          ]
        }, undefined, false, undefined, this)
      ]
    }, undefined, true, undefined, this),
    cadModel: {
      objUrl: "https://modelcdn.tscircuit.com/easyeda_models/assets/C2959727.obj?uuid=ac9b32e974bc448eab36b1293f859dcb",
      stepUrl: "https://modelcdn.tscircuit.com/easyeda_models/assets/C2959727.step?uuid=ac9b32e974bc448eab36b1293f859dcb",
      pcbRotationOffset: 0,
      modelOriginPosition: { x: 0, y: 0, z: -0.4 }
    },
    ...restProps
  }, undefined, false, undefined, this);
};

// imports/cl05a105ka5nqnc.tsx
import { jsxDEV as jsxDEV9 } from "react/jsx-dev-runtime";
var CL05A105KA5NQNC = (props) => {
  const { name = "C1", ...restProps } = props;
  return /* @__PURE__ */ jsxDEV9("capacitor", {
    name,
    capacitance: "1uF",
    supplierPartNumbers: {
      jlcpcb: ["C52923"]
    },
    manufacturerPartNumber: "CL05A105KA5NQNC",
    footprint: /* @__PURE__ */ jsxDEV9("footprint", {
      children: [
        /* @__PURE__ */ jsxDEV9("smtpad", {
          portHints: ["pin2"],
          pcbX: "0.420116mm",
          pcbY: "0mm",
          width: "0.499999mm",
          height: "0.540004mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV9("smtpad", {
          portHints: ["pin1"],
          pcbX: "-0.420116mm",
          pcbY: "0mm",
          width: "0.499999mm",
          height: "0.540004mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV9("silkscreenpath", {
          route: [
            { x: -0.721385400000031, y: 0.49753519999990203 },
            { x: -0.22138640000002852, y: 0.49753519999990203 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV9("silkscreenpath", {
          route: [
            { x: -0.8738108000000011, y: -0.34724340000002485 },
            { x: -0.8738108000000011, y: 0.3451606000000993 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV9("silkscreenpath", {
          route: [
            { x: -0.22138640000002852, y: -0.4996433999999681 },
            { x: -0.721385400000031, y: -0.4996433999999681 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV9("silkscreenpath", {
          route: [
            { x: 0.7213853999999174, y: -0.4975097999999889 },
            { x: 0.22138639999991483, y: -0.4975097999999889 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV9("silkscreenpath", {
          route: [
            { x: 0.22138639999991483, y: 0.49961800000005496 },
            { x: 0.7213853999999174, y: 0.49961800000005496 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV9("silkscreenpath", {
          route: [
            { x: 0.8738108000000011, y: 0.34726880000005167 },
            { x: 0.8738108000000011, y: -0.3451606000000993 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV9("silkscreenpath", {
          route: [
            { x: 0.7213853999999174, y: 0.4996433999998544 },
            { x: 0.829148473452733, y: 0.4550064734527268 },
            { x: 0.8737853999998606, y: 0.34724340000002485 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV9("silkscreenpath", {
          route: [
            { x: 0.8737853999998606, y: -0.3451606000000993 },
            { x: 0.829148473452733, y: -0.4529236734526876 },
            { x: 0.7213853999999174, y: -0.49756059999992885 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV9("silkscreenpath", {
          route: [
            { x: -0.721385400000031, y: -0.4996433999997407 },
            { x: -0.829148473452733, y: -0.45500647345261314 },
            { x: -0.8737853999999743, y: -0.34724340000002485 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV9("silkscreenpath", {
          route: [
            { x: -0.8737853999999743, y: 0.3451606000000993 },
            { x: -0.829148473452733, y: 0.45292367345280127 },
            { x: -0.721385400000031, y: 0.49756060000004254 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV9("courtyardoutline", {
          outline: [
            { x: -1.1136000000000195, y: 0.7580000000000382 },
            { x: 1.1389999999998963, y: 0.7580000000000382 },
            { x: 1.1389999999998963, y: -0.7326000000000477 },
            { x: -1.1136000000000195, y: -0.7326000000000477 },
            { x: -1.1136000000000195, y: 0.7580000000000382 }
          ]
        }, undefined, false, undefined, this)
      ]
    }, undefined, true, undefined, this),
    cadModel: {
      objUrl: "https://modelcdn.tscircuit.com/easyeda_models/assets/C52923.obj?uuid=32fe2cf9314f444ca2785a33c2db7189",
      stepUrl: "https://modelcdn.tscircuit.com/easyeda_models/assets/C52923.step?uuid=32fe2cf9314f444ca2785a33c2db7189",
      pcbRotationOffset: 0,
      modelOriginPosition: { x: 0, y: -0.000012700000070253736, z: -0.25 }
    },
    ...restProps
  }, undefined, false, undefined, this);
};

// imports/gjm0335c1h1r5bb01d.tsx
import { jsxDEV as jsxDEV10 } from "react/jsx-dev-runtime";
var GJM0335C1H1R5BB01D = (props) => {
  const { name = "C1", ...restProps } = props;
  return /* @__PURE__ */ jsxDEV10("capacitor", {
    name,
    capacitance: "1.5pF",
    supplierPartNumbers: {
      jlcpcb: ["C237515"]
    },
    manufacturerPartNumber: "GJM0335C1H1R5BB01D",
    footprint: /* @__PURE__ */ jsxDEV10("footprint", {
      children: [
        /* @__PURE__ */ jsxDEV10("smtpad", {
          portHints: ["pin2"],
          pcbX: "0.27432mm",
          pcbY: "0mm",
          width: "0.368427mm",
          height: "0.3240024mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV10("smtpad", {
          portHints: ["pin1"],
          pcbX: "-0.27432mm",
          pcbY: "0mm",
          width: "0.368427mm",
          height: "0.3240024mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV10("silkscreenpath", {
          route: [
            { x: 0.5346445999999787, y: 0.3906011999999919 },
            { x: 0.16619220000006862, y: 0.3906011999999919 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV10("silkscreenpath", {
          route: [
            { x: 0.16619220000006862, y: -0.3906011999999919 },
            { x: 0.5346445999999787, y: -0.3906011999999919 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV10("silkscreenpath", {
          route: [
            { x: 0.6870446000000356, y: -0.23820120000004863 },
            { x: 0.6870446000000356, y: 0.23820120000004863 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV10("silkscreenpath", {
          route: [
            { x: -0.5346446000000924, y: 0.3906011999999919 },
            { x: -0.16619220000006862, y: 0.3906011999999919 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV10("silkscreenpath", {
          route: [
            { x: -0.16619220000006862, y: -0.3906011999999919 },
            { x: -0.5346446000000924, y: -0.3906011999999919 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV10("silkscreenpath", {
          route: [
            { x: -0.6870446000001493, y: -0.23820120000004863 },
            { x: -0.6870446000001493, y: 0.23820120000004863 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV10("silkscreenpath", {
          route: [
            { x: 0.5346445999999787, y: -0.3906011999998782 },
            { x: 0.6424076734527944, y: -0.3459642734528643 },
            { x: 0.6870446000000356, y: -0.23820120000004863 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV10("silkscreenpath", {
          route: [
            { x: 0.6870446000000356, y: 0.23820120000004863 },
            { x: 0.6424076734527944, y: 0.3459642734528643 },
            { x: 0.5346445999999787, y: 0.3906011999999919 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV10("silkscreenpath", {
          route: [
            { x: -0.5346446000000924, y: -0.3906011999998782 },
            { x: -0.6424076734529081, y: -0.3459642734528643 },
            { x: -0.6870446000001493, y: -0.23820120000004863 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV10("silkscreenpath", {
          route: [
            { x: -0.6870446000001493, y: 0.23820120000004863 },
            { x: -0.6424076734529081, y: 0.3459642734528643 },
            { x: -0.5346446000000924, y: 0.3906011999999919 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV10("courtyardoutline", {
          outline: [
            { x: -0.935799999999972, y: 0.6309999999999718 },
            { x: 0.9358000000000857, y: 0.6309999999999718 },
            { x: 0.9358000000000857, y: -0.6563999999999623 },
            { x: -0.935799999999972, y: -0.6563999999999623 },
            { x: -0.935799999999972, y: 0.6309999999999718 }
          ]
        }, undefined, false, undefined, this)
      ]
    }, undefined, true, undefined, this),
    cadModel: {
      objUrl: "https://modelcdn.tscircuit.com/easyeda_models/assets/C237515.obj?uuid=c3e75c3d90204c70b153866ab54c789f",
      stepUrl: "https://modelcdn.tscircuit.com/easyeda_models/assets/C237515.step?uuid=c3e75c3d90204c70b153866ab54c789f",
      pcbRotationOffset: 0,
      modelOriginPosition: { x: 0, y: -0.000012700000070253736, z: -0.15 }
    },
    ...restProps
  }, undefined, false, undefined, this);
};

// imports/gjm1555c1h1r0bb01d.tsx
import { jsxDEV as jsxDEV11 } from "react/jsx-dev-runtime";
var GJM1555C1H1R0BB01D = (props) => {
  const { name = "C1", ...restProps } = props;
  return /* @__PURE__ */ jsxDEV11("capacitor", {
    name,
    capacitance: "1pF",
    supplierPartNumbers: {
      jlcpcb: ["C76898"]
    },
    manufacturerPartNumber: "GJM1555C1H1R0BB01D",
    footprint: /* @__PURE__ */ jsxDEV11("footprint", {
      children: [
        /* @__PURE__ */ jsxDEV11("smtpad", {
          portHints: ["pin2"],
          pcbX: "0.420116mm",
          pcbY: "0mm",
          width: "0.499999mm",
          height: "0.540004mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV11("smtpad", {
          portHints: ["pin1"],
          pcbX: "-0.420116mm",
          pcbY: "0mm",
          width: "0.499999mm",
          height: "0.540004mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV11("silkscreenpath", {
          route: [
            { x: -0.721385400000031, y: 0.49753519999990203 },
            { x: -0.22138640000002852, y: 0.49753519999990203 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV11("silkscreenpath", {
          route: [
            { x: -0.8738108000000011, y: -0.34724340000002485 },
            { x: -0.8738108000000011, y: 0.3451606000000993 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV11("silkscreenpath", {
          route: [
            { x: -0.22138640000002852, y: -0.4996433999999681 },
            { x: -0.721385400000031, y: -0.4996433999999681 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV11("silkscreenpath", {
          route: [
            { x: 0.7213853999999174, y: -0.4975097999999889 },
            { x: 0.22138639999991483, y: -0.4975097999999889 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV11("silkscreenpath", {
          route: [
            { x: 0.22138639999991483, y: 0.49961800000005496 },
            { x: 0.7213853999999174, y: 0.49961800000005496 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV11("silkscreenpath", {
          route: [
            { x: 0.8738108000000011, y: 0.34726880000005167 },
            { x: 0.8738108000000011, y: -0.3451606000000993 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV11("silkscreenpath", {
          route: [
            { x: 0.7213853999999174, y: 0.4996433999998544 },
            { x: 0.829148473452733, y: 0.4550064734527268 },
            { x: 0.8737853999998606, y: 0.34724340000002485 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV11("silkscreenpath", {
          route: [
            { x: 0.8737853999998606, y: -0.3451606000000993 },
            { x: 0.829148473452733, y: -0.4529236734526876 },
            { x: 0.7213853999999174, y: -0.49756059999992885 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV11("silkscreenpath", {
          route: [
            { x: -0.721385400000031, y: -0.4996433999997407 },
            { x: -0.829148473452733, y: -0.45500647345261314 },
            { x: -0.8737853999999743, y: -0.34724340000002485 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV11("silkscreenpath", {
          route: [
            { x: -0.8737853999999743, y: 0.3451606000000993 },
            { x: -0.829148473452733, y: 0.45292367345280127 },
            { x: -0.721385400000031, y: 0.49756060000004254 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV11("courtyardoutline", {
          outline: [
            { x: -1.1136000000000195, y: 0.7580000000000382 },
            { x: 1.1389999999998963, y: 0.7580000000000382 },
            { x: 1.1389999999998963, y: -0.7326000000000477 },
            { x: -1.1136000000000195, y: -0.7326000000000477 },
            { x: -1.1136000000000195, y: 0.7580000000000382 }
          ]
        }, undefined, false, undefined, this)
      ]
    }, undefined, true, undefined, this),
    cadModel: {
      objUrl: "https://modelcdn.tscircuit.com/easyeda_models/assets/C76898.obj?uuid=32fe2cf9314f444ca2785a33c2db7189",
      stepUrl: "https://modelcdn.tscircuit.com/easyeda_models/assets/C76898.step?uuid=32fe2cf9314f444ca2785a33c2db7189",
      pcbRotationOffset: 0,
      modelOriginPosition: { x: 0, y: -0.000012700000070253736, z: -0.25 }
    },
    ...restProps
  }, undefined, false, undefined, this);
};

// imports/lqm18dn100m70l.tsx
import { jsxDEV as jsxDEV12 } from "react/jsx-dev-runtime";
var pinLabels6 = {
  pin1: ["pin1"],
  pin2: ["pin2"]
};
var LQM18DN100M70L = (props) => {
  return /* @__PURE__ */ jsxDEV12("chip", {
    pinLabels: pinLabels6,
    symbol: /* @__PURE__ */ jsxDEV12("symbol", {
      children: [
        /* @__PURE__ */ jsxDEV12("schematicpath", {
          svgPath: "M 0.174 0.00138 A 0.08 0.078 0 1 0 0.3333 0.00128",
          strokeColor: "#880000"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV12("schematicpath", {
          svgPath: "M 0.00134 0.00142 A 0.08 0.078 0 1 0 0.16064 0.00132",
          strokeColor: "#880000"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV12("schematicpath", {
          svgPath: "M -0.168 0.00142 A 0.08 0.078 0 1 0 -0.0087 0.00132",
          strokeColor: "#880000"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV12("schematicpath", {
          svgPath: "M -0.33766 0.00136 A 0.08 0.078 0 1 0 -0.17836 0.00128",
          strokeColor: "#880000"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV12("port", {
          name: "pin1",
          pinNumber: 1,
          aliases: ["1"],
          direction: "left",
          schX: -0.4,
          schY: 0,
          schStemLength: 0.06
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV12("port", {
          name: "pin2",
          pinNumber: 2,
          aliases: ["2"],
          direction: "right",
          schX: 0.4,
          schY: 0,
          schStemLength: 0.06
        }, undefined, false, undefined, this)
      ]
    }, undefined, true, undefined, this),
    supplierPartNumbers: {
      jlcpcb: ["C713281"]
    },
    manufacturerPartNumber: "LQM18DN100M70L",
    footprint: /* @__PURE__ */ jsxDEV12("footprint", {
      children: [
        /* @__PURE__ */ jsxDEV12("smtpad", {
          portHints: ["pin1"],
          pcbX: "-0.699897mm",
          pcbY: "0mm",
          width: "0.7999984mm",
          height: "0.8640064mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV12("smtpad", {
          portHints: ["pin2"],
          pcbX: "0.699897mm",
          pcbY: "0mm",
          width: "0.7999984mm",
          height: "0.8640064mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV12("silkscreenpath", {
          route: [
            { x: -1.2700000000000955, y: -0.6513575999998693 },
            { x: -1.4241018000001304, y: -0.499008399999866 },
            { x: -1.4241018000001304, y: 0.5174234000000979 },
            { x: -1.2700000000000955, y: 0.6499860000001263 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV12("silkscreenpath", {
          route: [
            { x: 1.2699999999998681, y: 0.6499860000001263 },
            { x: 1.4241525999999567, y: 0.49898300000006657 },
            { x: 1.4241525999999567, y: -0.5174487999998973 },
            { x: 1.2699999999998681, y: -0.6500114000000394 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV12("silkscreenpath", {
          route: [
            { x: -1.272006600000168, y: 0.6499860000001263 },
            { x: -0.5100066000001107, y: 0.6499860000001263 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV12("silkscreenpath", {
          route: [
            { x: 1.2720573999999942, y: -0.6500114000000394 },
            { x: 0.5100573999999369, y: -0.6500114000000394 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV12("silkscreenpath", {
          route: [
            { x: -1.272006600000168, y: -0.6500114000000394 },
            { x: -0.5100066000001107, y: -0.6500114000000394 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV12("silkscreenpath", {
          route: [
            { x: 1.2720573999999942, y: 0.6499860000001263 },
            { x: 0.5100573999999369, y: 0.6499860000001263 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV12("courtyardoutline", {
          outline: [
            { x: -1.6628750000002128, y: 0.8875400000000582 },
            { x: 1.6819249999998647, y: 0.8875400000000582 },
            { x: 1.6819249999998647, y: -0.9078599999998005 },
            { x: -1.6628750000002128, y: -0.9078599999998005 },
            { x: -1.6628750000002128, y: 0.8875400000000582 }
          ]
        }, undefined, false, undefined, this)
      ]
    }, undefined, true, undefined, this),
    cadModel: {
      objUrl: "https://modelcdn.tscircuit.com/easyeda_models/assets/C713281.obj?uuid=a7f84688c5004aa68dbcbddc99bd5473",
      stepUrl: "https://modelcdn.tscircuit.com/easyeda_models/assets/C713281.step?uuid=a7f84688c5004aa68dbcbddc99bd5473",
      pcbRotationOffset: 180,
      modelOriginPosition: {
        x: 0.0023875999999063424,
        y: 0.015976600000044527,
        z: -0.25
      }
    },
    ...props
  }, undefined, false, undefined, this);
};

// imports/lqp03tn2n8b02d.tsx
import { jsxDEV as jsxDEV13 } from "react/jsx-dev-runtime";
var pinLabels7 = {
  pin1: ["pin1"],
  pin2: ["pin2"]
};
var LQP03TN2N8B02D = (props) => {
  return /* @__PURE__ */ jsxDEV13("chip", {
    pinLabels: pinLabels7,
    symbol: /* @__PURE__ */ jsxDEV13("symbol", {
      children: [
        /* @__PURE__ */ jsxDEV13("port", {
          name: "pin2",
          pinNumber: 2,
          aliases: ["2"],
          direction: "right",
          schX: 0.4,
          schY: 0,
          schStemLength: 0.06
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV13("port", {
          name: "pin1",
          pinNumber: 1,
          aliases: ["1"],
          direction: "left",
          schX: -0.4,
          schY: 0,
          schStemLength: 0.06
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV13("schematicpath", {
          svgPath: "M -0.33766 0.00136 A 0.08 0.078 0 1 0 -0.17836 0.00128",
          strokeColor: "#880000"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV13("schematicpath", {
          svgPath: "M -0.168 0.00142 A 0.08 0.078 0 1 0 -0.0087 0.00132",
          strokeColor: "#880000"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV13("schematicpath", {
          svgPath: "M 0.00134 0.00142 A 0.08 0.078 0 1 0 0.16064 0.00132",
          strokeColor: "#880000"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV13("schematicpath", {
          svgPath: "M 0.174 0.00138 A 0.08 0.078 0 1 0 0.3333 0.00128",
          strokeColor: "#880000"
        }, undefined, false, undefined, this)
      ]
    }, undefined, true, undefined, this),
    supplierPartNumbers: {
      jlcpcb: ["C206433"]
    },
    manufacturerPartNumber: "LQP03TN2N8B02D",
    footprint: /* @__PURE__ */ jsxDEV13("footprint", {
      children: [
        /* @__PURE__ */ jsxDEV13("smtpad", {
          portHints: ["pin2"],
          pcbX: "0.27432mm",
          pcbY: "0mm",
          width: "0.368427mm",
          height: "0.3240024mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV13("smtpad", {
          portHints: ["pin1"],
          pcbX: "-0.27432mm",
          pcbY: "0mm",
          width: "0.368427mm",
          height: "0.3240024mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV13("silkscreenpath", {
          route: [
            { x: 0.16619220000006862, y: -0.3906011999999919 },
            { x: 0.5346445999999787, y: -0.3906011999999919 },
            { x: 0.6870446000000356, y: -0.23820120000004863 },
            { x: 0.6870446000000356, y: 0.23820120000004863 },
            { x: 0.5346445999999787, y: 0.3906011999999919 },
            { x: 0.16619220000006862, y: 0.3906011999999919 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV13("silkscreenpath", {
          route: [
            { x: -0.16619220000006862, y: -0.3906011999999919 },
            { x: -0.5346446000000924, y: -0.3906011999999919 },
            { x: -0.6870446000001493, y: -0.23820120000004863 },
            { x: -0.6870446000001493, y: 0.23820120000004863 },
            { x: -0.5346446000000924, y: 0.3906011999999919 },
            { x: -0.16619220000006862, y: 0.3906011999999919 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV13("courtyardoutline", {
          outline: [
            { x: -0.935799999999972, y: 0.6309999999999718 },
            { x: 0.9358000000000857, y: 0.6309999999999718 },
            { x: 0.9358000000000857, y: -0.6563999999999623 },
            { x: -0.935799999999972, y: -0.6563999999999623 },
            { x: -0.935799999999972, y: 0.6309999999999718 }
          ]
        }, undefined, false, undefined, this)
      ]
    }, undefined, true, undefined, this),
    cadModel: {
      objUrl: "https://modelcdn.tscircuit.com/easyeda_models/assets/C206433.obj?uuid=fa57e36e003e4ee2b14b14feaebd32e1",
      stepUrl: "https://modelcdn.tscircuit.com/easyeda_models/assets/C206433.step?uuid=fa57e36e003e4ee2b14b14feaebd32e1",
      pcbRotationOffset: 0,
      modelOriginPosition: { x: 0, y: 0.000012699999956566899, z: -0.01 }
    },
    ...props
  }, undefined, false, undefined, this);
};

// imports/lqg15hs2n7s02d.tsx
import { jsxDEV as jsxDEV14 } from "react/jsx-dev-runtime";
var pinLabels8 = {
  pin1: ["pin1"],
  pin2: ["pin2"]
};
var LQG15HS2N7S02D = (props) => {
  return /* @__PURE__ */ jsxDEV14("chip", {
    pinLabels: pinLabels8,
    symbol: /* @__PURE__ */ jsxDEV14("symbol", {
      children: [
        /* @__PURE__ */ jsxDEV14("port", {
          name: "pin2",
          pinNumber: 2,
          aliases: ["2"],
          direction: "right",
          schX: 0.4,
          schY: 0,
          schStemLength: 0.06
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV14("port", {
          name: "pin1",
          pinNumber: 1,
          aliases: ["1"],
          direction: "left",
          schX: -0.4,
          schY: 0,
          schStemLength: 0.06
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV14("schematicpath", {
          svgPath: "M -0.3376 0.0014 A 0.08 0.078 0 1 0 -0.1784 0.0012",
          strokeColor: "#880000"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV14("schematicpath", {
          svgPath: "M -0.168 0.0014 A 0.08 0.078 0 1 0 -0.0088 0.0014",
          strokeColor: "#880000"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV14("schematicpath", {
          svgPath: "M 0.0014 0.0014 A 0.08 0.078 0 1 0 0.1606 0.0014",
          strokeColor: "#880000"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV14("schematicpath", {
          svgPath: "M 0.174 0.0014 A 0.08 0.078 0 1 0 0.3334 0.0012",
          strokeColor: "#880000"
        }, undefined, false, undefined, this)
      ]
    }, undefined, true, undefined, this),
    supplierPartNumbers: {
      jlcpcb: ["C77108"]
    },
    manufacturerPartNumber: "LQG15HS2N7S02D",
    footprint: /* @__PURE__ */ jsxDEV14("footprint", {
      children: [
        /* @__PURE__ */ jsxDEV14("smtpad", {
          portHints: ["pin2"],
          pcbX: "0.419989mm",
          pcbY: "0mm",
          width: "0.540004mm",
          height: "0.540004mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV14("smtpad", {
          portHints: ["pin1"],
          pcbX: "-0.419989mm",
          pcbY: "0mm",
          width: "0.540004mm",
          height: "0.540004mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV14("silkscreenpath", {
          route: [
            { x: -0.12687300000004598, y: -0.5080000000000382 },
            { x: -0.9169654000000946, y: -0.5080000000000382 },
            { x: -1.0693908000000647, y: -0.3556253999998944 },
            { x: -1.0693908000000647, y: 0.3367785999998887 },
            { x: -0.9169654000000946, y: 0.4891532000000325 },
            { x: -0.12687300000004598, y: 0.4891532000000325 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV14("silkscreenpath", {
          route: [
            { x: 0.12712699999997312, y: -0.5080000000000382 },
            { x: 0.9170669999998609, y: -0.5080000000000382 },
            { x: 1.0694670000000315, y: -0.3555999999998676 },
            { x: 1.0694670000000315, y: 0.32766000000003714 },
            { x: 0.9069069999999329, y: 0.4902200000000221 },
            { x: 0.12712699999997312, y: 0.4902200000000221 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV14("courtyardoutline", {
          outline: [
            { x: -1.3168000000000575, y: 0.7326000000000477 },
            { x: 1.3168000000000575, y: 0.7326000000000477 },
            { x: 1.3168000000000575, y: -0.7580000000000382 },
            { x: -1.3168000000000575, y: -0.7580000000000382 },
            { x: -1.3168000000000575, y: 0.7326000000000477 }
          ]
        }, undefined, false, undefined, this)
      ]
    }, undefined, true, undefined, this),
    cadModel: {
      objUrl: "https://modelcdn.tscircuit.com/easyeda_models/assets/C77108.obj?uuid=c498e8771bc24312a11c6413631665a8",
      stepUrl: "https://modelcdn.tscircuit.com/easyeda_models/assets/C77108.step?uuid=c498e8771bc24312a11c6413631665a8",
      pcbRotationOffset: 0,
      modelOriginPosition: { x: 0, y: -0.000012700000070253736, z: -0.25 }
    },
    ...props
  }, undefined, false, undefined, this);
};

// imports/lqg15hs3n9s02d.tsx
import { jsxDEV as jsxDEV15 } from "react/jsx-dev-runtime";
var pinLabels9 = {
  pin1: ["pin1"],
  pin2: ["pin2"]
};
var LQG15HS3N9S02D = (props) => {
  return /* @__PURE__ */ jsxDEV15("chip", {
    pinLabels: pinLabels9,
    symbol: /* @__PURE__ */ jsxDEV15("symbol", {
      children: [
        /* @__PURE__ */ jsxDEV15("port", {
          name: "pin2",
          pinNumber: 2,
          aliases: ["2"],
          direction: "right",
          schX: 0.4,
          schY: 0,
          schStemLength: 0.06
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV15("port", {
          name: "pin1",
          pinNumber: 1,
          aliases: ["1"],
          direction: "left",
          schX: -0.4,
          schY: 0,
          schStemLength: 0.06
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV15("schematicpath", {
          svgPath: "M -0.3376 0.0014 A 0.08 0.078 0 1 0 -0.1784 0.0012",
          strokeColor: "#880000"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV15("schematicpath", {
          svgPath: "M -0.168 0.0014 A 0.08 0.078 0 1 0 -0.0088 0.0014",
          strokeColor: "#880000"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV15("schematicpath", {
          svgPath: "M 0.0014 0.0014 A 0.08 0.078 0 1 0 0.1606 0.0014",
          strokeColor: "#880000"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV15("schematicpath", {
          svgPath: "M 0.174 0.0014 A 0.08 0.078 0 1 0 0.3334 0.0012",
          strokeColor: "#880000"
        }, undefined, false, undefined, this)
      ]
    }, undefined, true, undefined, this),
    supplierPartNumbers: {
      jlcpcb: ["C77109"]
    },
    manufacturerPartNumber: "LQG15HS3N9S02D",
    footprint: /* @__PURE__ */ jsxDEV15("footprint", {
      children: [
        /* @__PURE__ */ jsxDEV15("smtpad", {
          portHints: ["pin2"],
          pcbX: "0.419989mm",
          pcbY: "0mm",
          width: "0.540004mm",
          height: "0.540004mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV15("smtpad", {
          portHints: ["pin1"],
          pcbX: "-0.419989mm",
          pcbY: "0mm",
          width: "0.540004mm",
          height: "0.540004mm",
          shape: "rect"
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV15("silkscreenpath", {
          route: [
            { x: -0.12687300000004598, y: -0.5080000000000382 },
            { x: -0.9169654000000946, y: -0.5080000000000382 },
            { x: -1.0693908000000647, y: -0.3556253999998944 },
            { x: -1.0693908000000647, y: 0.3367785999998887 },
            { x: -0.9169654000000946, y: 0.4891532000000325 },
            { x: -0.12687300000004598, y: 0.4891532000000325 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV15("silkscreenpath", {
          route: [
            { x: 0.12712699999997312, y: -0.5080000000000382 },
            { x: 0.9170669999998609, y: -0.5080000000000382 },
            { x: 1.0694670000000315, y: -0.3555999999998676 },
            { x: 1.0694670000000315, y: 0.32766000000003714 },
            { x: 0.9069069999999329, y: 0.4902200000000221 },
            { x: 0.12712699999997312, y: 0.4902200000000221 }
          ]
        }, undefined, false, undefined, this),
        /* @__PURE__ */ jsxDEV15("courtyardoutline", {
          outline: [
            { x: -1.3168000000000575, y: 0.7326000000000477 },
            { x: 1.3168000000000575, y: 0.7326000000000477 },
            { x: 1.3168000000000575, y: -0.7580000000000382 },
            { x: -1.3168000000000575, y: -0.7580000000000382 },
            { x: -1.3168000000000575, y: 0.7326000000000477 }
          ]
        }, undefined, false, undefined, this)
      ]
    }, undefined, true, undefined, this),
    cadModel: {
      objUrl: "https://modelcdn.tscircuit.com/easyeda_models/assets/C77109.obj?uuid=c498e8771bc24312a11c6413631665a8",
      stepUrl: "https://modelcdn.tscircuit.com/easyeda_models/assets/C77109.step?uuid=c498e8771bc24312a11c6413631665a8",
      pcbRotationOffset: 0,
      modelOriginPosition: { x: 0, y: -0.000012700000070253736, z: -0.25 }
    },
    ...props
  }, undefined, false, undefined, this);
};

// index.circuit.tsx
import { jsxDEV as jsxDEV16, Fragment as Fragment2 } from "react/jsx-dev-runtime";
var Note = (props) => /* @__PURE__ */ jsxDEV16("schematictext", {
  ...props,
  schSheetName: "reference"
}, undefined, false, undefined, this);
var sectionMembers = {
  mcu: ["U1"],
  power_input: ["J1"],
  vdds: ["C1", "C2", "C19", "C20"],
  vddr: ["L1", "C21", "C22", "C25"],
  vddd: ["C23"],
  rf: ["C26", "C27", "C28", "L2", "L3", "L4", "ANT1"],
  hf: ["Y2"],
  lf: ["Y1", "C14", "C15"],
  reset: ["R14", "C24"],
  debug: ["J4", "TP1", "TP2"]
};
var schematic = Object.fromEntries(Object.entries(sectionMembers).flatMap(([section, names]) => names.map((name) => [
  name,
  { schSheetName: "reference", schSectionName: section }
])));
var propsSchema = createPropsParser(propsJsonSchema);
var referenceProps = propsSchema;
function Cc2340Reference(input = {}) {
  const {
    externalLfCrystal,
    debugHeader,
    supplyVoltage,
    inputBulkCapacitance,
    resetPullupResistance
  } = referenceProps.parse(input);
  const supplyLabel = `${supplyVoltage.toFixed(1)}V`;
  const nets = {
    VDDS: [
      "J1.1",
      "U1.11",
      "U1.18",
      "U1.24",
      "C1.1",
      "C2.1",
      "C19.1",
      "C20.1",
      "R14.1"
    ],
    GND: [
      "J1.2",
      "U1.23",
      "U1.25",
      "Y2.2",
      "Y2.4",
      "C1.2",
      "C2.2",
      "C19.2",
      "C20.2",
      "C21.2",
      "C22.2",
      "C23.2",
      "C24.2",
      "C25.2",
      "C26.2",
      "C27.2",
      "L3.2"
    ],
    VDDR: ["U1.2", "U1.20", "L1.2", "C21.1", "C22.1", "C25.1"],
    VDDD: ["U1.16", "C23.1"],
    DCDC: ["U1.17", "L1.1"],
    RESET_N: ["U1.13", "R14.2", "C24.1"],
    HF_P: ["U1.21", "Y2.1"],
    HF_N: ["U1.22", "Y2.3"],
    RF_IC: ["U1.1", "C26.1", "L2.2"],
    RF_50: ["L2.1", "C27.1", "C28.1"],
    RF_MATCH: ["C28.2", "L3.1", "L4.1"],
    RF_ANT: ["L4.2", "ANT1.1"],
    SWDIO: ["U1.7", "TP1.1"],
    SWCLK: ["U1.8", "TP2.1"]
  };
  if (externalLfCrystal) {
    nets.LF_P = ["U1.14", "Y1.1", "C14.1"];
    nets.LF_N = ["U1.15", "Y1.2", "C15.1"];
    nets.GND.push("C14.2", "C15.2");
  }
  if (debugHeader) {
    nets.VDDS.push("J4.1");
    nets.SWDIO.push("J4.2");
    nets.SWCLK.push("J4.3");
    nets.GND.push("J4.4", "J4.6", "J4.7");
    nets.RESET_N.push("J4.5");
  }
  const unusedPins = [
    "pin3",
    "pin4",
    "pin5",
    "pin6",
    "pin9",
    "pin10",
    "pin12",
    "pin19",
    ...!externalLfCrystal ? ["pin14", "pin15"] : []
  ];
  const inductorParts = [
    ["L1", "10uH", LQM18DN100M70L, 7, 5, -10, -5, 0],
    ["L2", "2.8nH", LQP03TN2N8B02D, -6.8, 3.25, 5.5, 7, 0],
    ["L3", "2.7nH", LQG15HS2N7S02D, -12, 0, 12.3, 5, 270],
    ["L4", "3.9nH", LQG15HS3N9S02D, -15, 3.25, 14.8, 7, 180]
  ];
  const criticalRoutes = [
    { from: "U1.1", to: "L2.2", rf: true },
    { from: "U1.1", to: "C26.1", points: [{ x: -4.7, y: 1.25 }], rf: true },
    { from: "L2.1", to: "C28.1", rf: true },
    { from: "L2.1", to: "C27.1", points: [{ x: -1.9, y: 0 }], rf: true },
    { from: "C28.2", to: "L4.1", rf: true },
    { from: "C28.2", to: "L3.1", points: [{ x: 1.6, y: 0 }], rf: true },
    { from: "L4.2", to: "ANT1.1", rf: true },
    { from: "U1.21", to: "Y2.1" },
    {
      from: "U1.22",
      to: "Y2.3",
      points: [
        { x: -0.25019, y: 2.7 },
        { x: -1.6, y: 3.5 },
        { x: -1.6, y: 5.6375 }
      ]
    },
    ...externalLfCrystal ? [
      {
        from: "U1.14",
        to: "Y1.1",
        points: [
          { x: 2.7, y: -0.749935 },
          { x: 2.7, y: -2.4 }
        ]
      },
      { from: "Y1.1", to: "C14.1" },
      {
        from: "U1.15",
        to: "Y1.2",
        points: [
          { x: 2.8, y: -0.250063 },
          { x: 6.6549888, y: -0.250063 }
        ]
      },
      { from: "Y1.2", to: "C15.1" }
    ] : []
  ];
  const selector = (pin) => {
    const [ref, num] = pin.split(".");
    return `.${ref} > .pin${num}`;
  };
  return /* @__PURE__ */ jsxDEV16("board", {
    width: 44,
    height: 30,
    layers: 2,
    borderRadius: 1.5,
    title: "CC2340R5 / radio reference",
    schMaxTraceDistance: 20,
    schStyle: {
      defaultPassiveSize: "md",
      defaultCapacitorOrientation: "vertical"
    },
    autorouter: {
      local: true,
      groupMode: "subcircuit",
      algorithmFn: routeRemaining,
      traceClearance: 0.15
    },
    minTraceWidth: 0.15,
    defaultTraceWidth: 0.18,
    pcbStyle: { silkscreenFontSize: 0.65 },
    solderMaskColor: "green",
    children: [
      /* @__PURE__ */ jsxDEV16("schematicsheet", {
        name: "reference",
        displayName: "CC2340R5 radio reference",
        sheetIndex: 0,
        sheetSize: "A4"
      }, undefined, false, undefined, this),
      Object.keys(sectionMembers).map((name) => /* @__PURE__ */ jsxDEV16(Fragment, {
        children: /* @__PURE__ */ jsxDEV16("schematicsection", {
          name
        }, undefined, false, undefined, this)
      }, name, false, undefined, this)),
      /* @__PURE__ */ jsxDEV16(Note, {
        text: "CC2340R5  /  RADIO REFERENCE",
        schX: -11.7,
        schY: 8.775,
        anchor: "left",
        fontSize: 0.65
      }, undefined, false, undefined, this),
      /* @__PURE__ */ jsxDEV16(Note, {
        text: `CC2340R52E0RGER  ·  RGE QFN-24  ·  ${supplyVoltage.toFixed(1)} V supply`,
        schX: -11.7,
        schY: 8.06,
        anchor: "left",
        fontSize: 0.3
      }, undefined, false, undefined, this),
      /* @__PURE__ */ jsxDEV16(Note, {
        text: "01  MCU",
        schX: -11.7,
        schY: 7.02,
        anchor: "left",
        fontSize: 0.34
      }, undefined, false, undefined, this),
      /* @__PURE__ */ jsxDEV16(Note, {
        text: "02  2.4 GHz FILTER & ANTENNA",
        schX: 0.65,
        schY: 7.02,
        anchor: "left",
        fontSize: 0.34
      }, undefined, false, undefined, this),
      /* @__PURE__ */ jsxDEV16(Note, {
        text: "03  DC/DC & DECOUPLING",
        schX: -11.7,
        schY: -1.82,
        anchor: "left",
        fontSize: 0.34
      }, undefined, false, undefined, this),
      /* @__PURE__ */ jsxDEV16(Note, {
        text: "04  CLOCKS",
        schX: 0.975,
        schY: 0.91,
        anchor: "left",
        fontSize: 0.34
      }, undefined, false, undefined, this),
      /* @__PURE__ */ jsxDEV16(Note, {
        text: "05  RESET & DEBUG",
        schX: 0.975,
        schY: -4.03,
        anchor: "left",
        fontSize: 0.34
      }, undefined, false, undefined, this),
      /* @__PURE__ */ jsxDEV16(CC2340R52E0RGER, {
        name: "U1",
        ...schematic.U1,
        schX: -6.5,
        schY: 2.665,
        pcbX: 0,
        pcbY: 2,
        schWidth: 4.2,
        schHeight: 5,
        schPinStyle: Object.fromEntries(Array.from({ length: 25 }, (_5, i8) => [
          `pin${i8 + 1}`,
          {
            marginTop: 0.1,
            marginBottom: 0.1,
            marginLeft: 0.08,
            marginRight: 0.08
          }
        ])),
        schPinArrangement: {
          leftSide: [
            "VDDS1",
            "VDDS2",
            "VDDS3",
            "VDDR1",
            "VDDR2",
            "VDDD",
            "DCDC",
            "GND",
            "EP"
          ],
          rightSide: [
            "ANT",
            "X48P",
            "X48N",
            "DIO3_X32P",
            "DIO4_X32N",
            "RSTN",
            "DIO16_SWDIO",
            "DIO17_SWDCK"
          ],
          bottomSide: [
            "DIO8",
            "DIO11",
            "DIO12",
            "DIO13",
            "DIO20_A11",
            "DIO21_A10",
            "DIO24_A7",
            "DIO6_A1"
          ]
        },
        noConnect: unusedPins,
        pinAttributes: Object.fromEntries(unusedPins.map((pin) => [pin, { doNotConnect: true }]))
      }, undefined, false, undefined, this),
      /* @__PURE__ */ jsxDEV16("pinheader", {
        name: "J1",
        ...schematic.J1,
        manufacturerPartNumber: "TSW-102-07-G-S",
        pinCount: 2,
        pitch: "2.54mm",
        schX: -10.4,
        schY: -3.51,
        schPinArrangement: { rightSide: [1, 2] },
        pcbX: 16,
        pcbY: 9,
        pinLabels: [supplyVoltage.toFixed(1).replace(".", "V"), "GND"],
        pinAttributes: {
          pin1: { providesPower: true, providesVoltage: supplyVoltage },
          pin2: { providesGround: true }
        }
      }, undefined, false, undefined, this),
      /* @__PURE__ */ jsxDEV16("capacitor", {
        name: "C1",
        schRotation: 270,
        ...schematic.C1,
        capacitance: "100nF",
        footprint: "0402",
        pcbX: -1,
        pcbY: -1.8,
        schX: -10.4,
        schY: -5.59
      }, undefined, false, undefined, this),
      /* @__PURE__ */ jsxDEV16("capacitor", {
        name: "C2",
        schRotation: 270,
        ...schematic.C2,
        capacitance: inputBulkCapacitance,
        maxVoltageRating: "10V",
        footprint: inputBulkCapacitance === "22uF" ? "0805" : "0603",
        pcbX: 12,
        pcbY: 1.5,
        schX: -8.775,
        schY: -5.59
      }, undefined, false, undefined, this),
      /* @__PURE__ */ jsxDEV16(CL05B104KO5NNNC, {
        name: "C19",
        schRotation: 270,
        ...schematic.C19,
        pcbX: 3.8,
        pcbY: 5.2,
        schX: -7.15,
        schY: -5.59
      }, undefined, false, undefined, this),
      /* @__PURE__ */ jsxDEV16(GRM033R61A104KE15D, {
        name: "C20",
        schRotation: 270,
        ...schematic.C20,
        pcbX: -3.6,
        pcbY: 5.2,
        schX: -5.525,
        schY: -5.59
      }, undefined, false, undefined, this),
      /* @__PURE__ */ jsxDEV16(GRM188Z71A106KA73D, {
        name: "C21",
        schRotation: 270,
        ...schematic.C21,
        pcbX: 8.8,
        pcbY: 8.8,
        schX: -4.55,
        schY: -3.38
      }, undefined, false, undefined, this),
      /* @__PURE__ */ jsxDEV16(CL05B104KO5NNNC, {
        name: "C22",
        schRotation: 270,
        ...schematic.C22,
        pcbX: 3.8,
        pcbY: 7,
        schX: -2.925,
        schY: -3.38
      }, undefined, false, undefined, this),
      /* @__PURE__ */ jsxDEV16(CL05B104KO5NNNC, {
        name: "C25",
        schRotation: 270,
        ...schematic.C25,
        pcbX: -3.8,
        pcbY: 0.5,
        schX: -1.3,
        schY: -3.38
      }, undefined, false, undefined, this),
      /* @__PURE__ */ jsxDEV16(CL05A105KA5NQNC, {
        name: "C23",
        schRotation: 270,
        ...schematic.C23,
        pcbX: 3.6,
        pcbY: 3,
        schX: -2.925,
        schY: -5.59
      }, undefined, false, undefined, this),
      /* @__PURE__ */ jsxDEV16(GJM0335C1H1R5BB01D, {
        name: "C26",
        schRotation: 270,
        ...schematic.C26,
        pcbX: -4.7,
        pcbY: 2.8,
        pcbRotation: 270,
        schX: 1.95,
        schY: 3.25
      }, undefined, false, undefined, this),
      /* @__PURE__ */ jsxDEV16(GJM0335C1H1R5BB01D, {
        name: "C27",
        schRotation: 270,
        ...schematic.C27,
        pcbX: -8.7,
        pcbY: 1.5,
        pcbRotation: 270,
        schX: 5.2,
        schY: 3.25
      }, undefined, false, undefined, this),
      /* @__PURE__ */ jsxDEV16(GJM1555C1H1R0BB01D, {
        name: "C28",
        ...schematic.C28,
        pcbX: -10.4,
        pcbY: 3.25,
        pcbRotation: 180,
        schX: 6.565,
        schY: 4.55,
        schRotation: 0
      }, undefined, false, undefined, this),
      /* @__PURE__ */ jsxDEV16(A_2450AT18A100E, {
        name: "ANT1",
        ...schematic.ANT1,
        pcbX: -19.5,
        pcbY: 3.25,
        pcbRotation: 180,
        schX: 11.375,
        schY: 5.2,
        noConnect: ["pin2"],
        pinAttributes: {
          pin1: {},
          ANT: {},
          pin2: { doNotConnect: true },
          NC: { doNotConnect: true }
        }
      }, undefined, false, undefined, this),
      inductorParts.map(([name, inductance, Part, pcbX, pcbY, schX, schY, rotation]) => {
        const imported = Part({ name }).props;
        return /* @__PURE__ */ jsxDEV16("inductor", {
          name,
          ...schematic[name],
          inductance,
          footprint: imported.footprint,
          cadModel: imported.cadModel,
          manufacturerPartNumber: imported.manufacturerPartNumber,
          supplierPartNumbers: imported.supplierPartNumbers,
          pcbX,
          pcbY,
          pcbRotation: rotation,
          schX: schX * 0.65,
          schY: schY * 0.65,
          schRotation: name === "L3" ? 270 : name === "L2" ? 180 : 0
        }, name, false, undefined, this);
      }),
      /* @__PURE__ */ jsxDEV16(Note, {
        text: "Values retained from the pedometer RF network.",
        schX: 0.65,
        schY: 2.015,
        anchor: "left",
        fontSize: 0.24
      }, undefined, false, undefined, this),
      /* @__PURE__ */ jsxDEV16(Note, {
        text: "Antenna match requires tuning on the assembled PCB.",
        schX: 0.65,
        schY: 1.69,
        anchor: "left",
        fontSize: 0.24
      }, undefined, false, undefined, this),
      /* @__PURE__ */ jsxDEV16(ABM11W_48_0000MHZ_8_D1X_T3, {
        name: "Y2",
        ...schematic.Y2,
        pcbX: 0,
        pcbY: 7,
        pcbRotation: 90,
        schX: 3.38,
        schY: -0.65
      }, undefined, false, undefined, this),
      /* @__PURE__ */ jsxDEV16(Note, {
        text: "48 MHz  /  CL = 8 pF in SysConfig",
        schX: 0.65,
        schY: 0.52,
        anchor: "left",
        fontSize: 0.25
      }, undefined, false, undefined, this),
      externalLfCrystal ? /* @__PURE__ */ jsxDEV16(Fragment2, {
        children: [
          /* @__PURE__ */ jsxDEV16(ABS07_32_768KHZ_7_T, {
            name: "Y1",
            ...schematic.Y1,
            pcbX: 5.5,
            pcbY: -0.8,
            schX: 8.775,
            schY: -0.65
          }, undefined, false, undefined, this),
          /* @__PURE__ */ jsxDEV16("capacitor", {
            name: "C14",
            schRotation: 270,
            ...schematic.C14,
            capacitance: "12pF",
            footprint: "0402",
            pcbX: 4.5,
            pcbY: -2.8,
            schX: 7.475,
            schY: -2.275
          }, undefined, false, undefined, this),
          /* @__PURE__ */ jsxDEV16("capacitor", {
            name: "C15",
            schRotation: 270,
            ...schematic.C15,
            capacitance: "15pF",
            footprint: "0402",
            pcbX: 6.6,
            pcbY: -2.8,
            schX: 10.075,
            schY: -2.275
          }, undefined, false, undefined, this),
          /* @__PURE__ */ jsxDEV16(Note, {
            text: "32.768 kHz  /  external LF clock",
            schX: 6.5,
            schY: 0.52,
            anchor: "left",
            fontSize: 0.25
          }, undefined, false, undefined, this)
        ]
      }, undefined, true, undefined, this) : null,
      /* @__PURE__ */ jsxDEV16("resistor", {
        name: "R14",
        ...schematic.R14,
        resistance: resetPullupResistance,
        footprint: "0402",
        pcbX: 1,
        pcbY: -3.5,
        pcbRotation: 90,
        schX: 2.6,
        schY: -5.33,
        schRotation: 270
      }, undefined, false, undefined, this),
      /* @__PURE__ */ jsxDEV16(CL05B104KO5NNNC, {
        name: "C24",
        schRotation: 270,
        ...schematic.C24,
        pcbX: 3,
        pcbY: -5,
        schX: 2.6,
        schY: -7.15
      }, undefined, false, undefined, this),
      /* @__PURE__ */ jsxDEV16("testpoint", {
        doNotPlace: true,
        name: "TP1",
        ...schematic.TP1,
        footprint: /* @__PURE__ */ jsxDEV16("footprint", {
          children: /* @__PURE__ */ jsxDEV16("smtpad", {
            portHints: ["pin1"],
            pcbX: 0,
            pcbY: 0,
            shape: "circle",
            radius: 0.6
          }, undefined, false, undefined, this)
        }, undefined, false, undefined, this),
        pcbX: -4,
        pcbY: -8,
        schX: 5.85,
        schY: -5.85
      }, undefined, false, undefined, this),
      /* @__PURE__ */ jsxDEV16("testpoint", {
        doNotPlace: true,
        name: "TP2",
        ...schematic.TP2,
        footprint: /* @__PURE__ */ jsxDEV16("footprint", {
          children: /* @__PURE__ */ jsxDEV16("smtpad", {
            portHints: ["pin1"],
            pcbX: 0,
            pcbY: 0,
            shape: "circle",
            radius: 0.6
          }, undefined, false, undefined, this)
        }, undefined, false, undefined, this),
        pcbX: 0,
        pcbY: -8,
        schX: 5.85,
        schY: -7.15
      }, undefined, false, undefined, this),
      debugHeader ? /* @__PURE__ */ jsxDEV16(BM05B_SRSS_TB_LF__SN_, {
        name: "J4",
        ...schematic.J4,
        schWidth: 2.2,
        schHeight: 2.4,
        schPinStyle: Object.fromEntries(Array.from({ length: 7 }, (_5, i8) => [
          `pin${i8 + 1}`,
          { marginTop: 0.08, marginBottom: 0.08 }
        ])),
        schX: 10.075,
        schY: -6.37,
        schPinArrangement: { leftSide: [1, 2, 3, 4, 5], bottomSide: [6, 7] },
        pcbX: 10,
        pcbY: -9,
        pinLabels: {
          pin1: ["VTREF"],
          pin2: ["SWDIO"],
          pin3: ["SWCLK"],
          pin4: ["GND"],
          pin5: ["RESET_N"],
          pin6: ["SHIELD1"],
          pin7: ["SHIELD2"]
        },
        pinAttributes: {
          pin1: { requiresPower: true, requiresVoltage: supplyVoltage }
        }
      }, undefined, false, undefined, this) : null,
      criticalRoutes.map(({ from: from2, to: to2, points, rf: rf2 }) => /* @__PURE__ */ jsxDEV16("trace", {
        name: `${from2.replaceAll(".", "_")}_to_${to2.replaceAll(".", "_")}`,
        from: selector(from2),
        to: selector(to2),
        pcbPath: points ?? [],
        maxViaCount: 0,
        thickness: rf2 ? 0.2 : 0.15
      }, `route:${from2}:${to2}`, false, undefined, this)),
      Object.keys(nets).map((name) => /* @__PURE__ */ jsxDEV16(Fragment2, {
        children: /* @__PURE__ */ jsxDEV16("net", {
          name,
          isGroundNet: name === "GND"
        }, undefined, false, undefined, this)
      }, name, false, undefined, this)),
      Object.entries(nets).flatMap(([net, pins]) => pins.map((pin) => {
        const [ref, num] = pin.split(".");
        return /* @__PURE__ */ jsxDEV16("trace", {
          from: `.${ref} > .pin${num}`,
          to: `net.${net}`,
          schDisplayLabel: net
        }, `${net}:${pin}`, false, undefined, this);
      })),
      Object.entries({
        U1: [0.6, 4.9],
        Y2: [-1.8, 8.8],
        Y1: [5.5, 1.1],
        ANT1: [-19, 5.5],
        C19: [3.8, 6.2],
        C20: [-3.6, 6.4],
        C21: [8.8, 10.4],
        C22: [3.8, 8.2],
        C23: [5.1, 3],
        C24: [3, -6.2],
        C25: [-3.8, -0.8],
        C26: [-4.6, 4.1],
        C27: [-8.7, 0.2],
        C28: [-10.4, 4.3],
        L1: [7.2, 6.5],
        L2: [-6.8, 4.3],
        L3: [-12, -1.8],
        L4: [-15, 4.3],
        ...debugHeader ? { J4: [10, -12] } : {}
      }).filter(([name]) => externalLfCrystal || name !== "Y1").map(([text, [pcbX, pcbY]]) => /* @__PURE__ */ jsxDEV16(Fragment2, {
        children: /* @__PURE__ */ jsxDEV16("silkscreentext", {
          text,
          pcbX,
          pcbY,
          fontSize: 0.5
        }, undefined, false, undefined, this)
      }, `label:${text}`, false, undefined, this)),
      /* @__PURE__ */ jsxDEV16("silkscreentext", {
        text: "CC2340R5 REFERENCE",
        pcbX: 1,
        pcbY: 12.3,
        fontSize: 0.85
      }, undefined, false, undefined, this),
      /* @__PURE__ */ jsxDEV16("silkscreentext", {
        text: "VDDS / GND",
        pcbX: 16,
        pcbY: 6.5,
        fontSize: 0.65
      }, undefined, false, undefined, this),
      /* @__PURE__ */ jsxDEV16("silkscreentext", {
        text: "SWDIO",
        pcbX: -4,
        pcbY: -10,
        fontSize: 0.6
      }, undefined, false, undefined, this),
      /* @__PURE__ */ jsxDEV16("silkscreentext", {
        text: "SWCLK",
        pcbX: 0,
        pcbY: -10,
        fontSize: 0.6
      }, undefined, false, undefined, this),
      /* @__PURE__ */ jsxDEV16("keepout", {
        shape: "rect",
        pcbX: -20,
        pcbY: 3.25,
        width: 4,
        height: 7,
        layers: ["top", "bottom"],
        excludeRefs: [".ANT1"]
      }, undefined, false, undefined, this),
      /* @__PURE__ */ jsxDEV16(Note, {
        text: "Derived from imrishabh18/pedometer 1.1.8",
        schX: -11.7,
        schY: -9.165,
        anchor: "left",
        fontSize: 0.25
      }, undefined, false, undefined, this)
    ]
  }, undefined, true, undefined, this);
}
export {
  referenceProps,
  propsSchema,
  propsJsonSchema,
  Cc2340Reference as default
};